diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 2967773d..7e658358 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -79,17 +79,19 @@ 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 分发到业务处理器;文件/报表事实类 - # 回调(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 + # onhand/inbound/outbound RPA 回调 sink 注册(幂等):按消费域分组合根—— + # onhand → shipping_notice.rpa_sinks;inbound/outbound → in_transit_transfer.rpa_sinks。 + # 进度类经 callback_sinks.dispatch_sink;文件事实经 reports.dispatch; + # 未注册 kind 显式 404(FREIGHT_RPA.SINK_NOT_REGISTERED)。 + from app.services.in_transit_transfer.rpa_sinks import ( + register_inbound_sinks, + register_outbound_sinks, + ) + from app.services.shipping_notice.rpa_sinks import register_onhand_sinks register_onhand_sinks() register_inbound_sinks() + register_outbound_sinks() # 启动时强制加载一次,避免 worker 冷启动到首个请求之间仍用镜像默认值。 with app.app_context(): diff --git a/backend/app/api/admin/shipping_notice_admin.py b/backend/app/api/admin/shipping_notice_admin.py index 2904d458..183169c6 100644 --- a/backend/app/api/admin/shipping_notice_admin.py +++ b/backend/app/api/admin/shipping_notice_admin.py @@ -1,9 +1,9 @@ """ api/admin/shipping_notice_admin.py -用途:发货通知仍留在本蓝图的管理面——Excel 模板、临时在手会话、异动字段目录。 -依赖:admin blueprint、require_admin、excel_template、异动字段契约、临时会话服务。 -逻辑:货代 RPA 管理路由(sources / onhand / inbound-report-config / rpa-profiles)已迁至 +用途:发货通知仍留在本蓝图的管理面——Excel 模板、临时在手会话。 +依赖:admin blueprint、require_admin、excel_template、临时会话服务。 +逻辑:货代 RPA 管理路由(含 movement-fields / 报表规则)已迁至 api/admin_freight_rpa.py 的 /api/admin/freight-rpa/;本文件不再注册那些路径。 临时会话只改路径段 temporary-onhand-sessions,仍挂在 /shipping-notice/。 """ @@ -106,21 +106,6 @@ def delete_shipping_excel_template(template_id: int): 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(): diff --git a/backend/app/api/admin_freight_rpa.py b/backend/app/api/admin_freight_rpa.py index e209f06b..2ef4dcb5 100644 --- a/backend/app/api/admin_freight_rpa.py +++ b/backend/app/api/admin_freight_rpa.py @@ -1,11 +1,15 @@ """ api/admin_freight_rpa.py -用途:货代 RPA 管理 API,挂在 /api/admin/freight-rpa/(站点 sources、onhand 配置、入站报表配置、RPA Profile)。 -依赖:admin blueprint、require_admin、shipping_onhand_admin_service、onhand 解析/字段/结构分析服务、订单 Schema。 +用途:货代 RPA 管理 API,挂在 /api/admin/freight-rpa/(站点 sources、onhand 配置、 + 入站/出站报表配置、报表规则、异动字段目录、RPA Profile)。 +依赖:admin blueprint、require_admin、freight_rpa_source_admin_service、 + shipping_onhand_admin_service、freight_rpa_report_config_service、 + freight_rpa.parsing_profile、 + onhand 字段/结构分析服务、in_transit_transfer.movement_contract。 逻辑:路由只做鉴权与 JSON 参数;业务校验与事务留在服务层。 - rpa-profiles 与本批迁入的 sources/onhand 路由同文件注册,不保留 /shipping-notice/ 双路由。 - Excel 模板、temporary-onhand-sessions、movement-fields 仍在 admin/shipping_notice_admin.py。 + 不保留 /shipping-notice/ 双路由。Excel 模板与 temporary-onhand-sessions + 仍在 admin/shipping_notice_admin.py。 """ from __future__ import annotations @@ -16,10 +20,13 @@ 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_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.admin import ( + freight_rpa_report_config_service, + freight_rpa_source_admin_service, + shipping_onhand_admin_service, +) +from app.services.freight_rpa import parsing_profile as onhand_parsing_profile +from app.services.shipping_notice import onhand_field_catalog, onhand_structure_analysis from app.services.shipping_notice.order_schema import service as order_schema_service @@ -37,28 +44,28 @@ def _ok(data, *, status: int = 200): @require_admin def list_shipping_rpa_profiles(): """列出脱敏后的 RPA Profile 配置。""" - return _ok(shipping_onhand_admin_service.list_profiles()) + return _ok(freight_rpa_source_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_onhand_admin_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201) + return _ok(freight_rpa_source_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_onhand_admin_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id)) + return _ok(freight_rpa_source_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_onhand_admin_service.delete_profile(profile_id) + freight_rpa_source_admin_service.delete_profile(profile_id) return '', 204 @@ -66,14 +73,14 @@ def delete_shipping_rpa_profile(profile_id: int): @require_admin def list_shipping_inventory_sources(): """列出库存业务来源。""" - return _ok(shipping_onhand_admin_service.list_sources()) + return _ok(freight_rpa_source_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( + return _ok(freight_rpa_source_admin_service.save_source( request.get_json(silent=True) or {}, actor_id=_actor_id(), allow_enable_transition=False, ), status=201) @@ -82,7 +89,7 @@ def create_shipping_inventory_source(): @require_admin def update_shipping_inventory_source(source_id: int): """更新库存站点业务配置;不能借由普通保存绕过启用门禁。""" - return _ok(shipping_onhand_admin_service.save_source( + return _ok(freight_rpa_source_admin_service.save_source( request.get_json(silent=True) or {}, actor_id=_actor_id(), source_id=source_id, allow_enable_transition=False, )) @@ -91,25 +98,56 @@ def update_shipping_inventory_source(source_id: int): @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)) + """读取站点独立入站报表配置;库存配置和入站配置永不混写。""" + return _ok(freight_rpa_report_config_service.get_inbound_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( + """保存独立入站报表配置,并由服务记录可追溯的前后快照审计。""" + return _ok(freight_rpa_report_config_service.save_inbound_report_config( source_id, request.get_json(silent=True) or {}, actor_id=_actor_id(), )) +@admin_bp.route('/freight-rpa/sources//outbound-report-config', methods=['GET']) +@require_admin +def get_shipping_outbound_report_config(source_id: int): + """读取站点独立出站报表配置;库存/入站/出站配置永不混写。""" + return _ok(freight_rpa_report_config_service.get_outbound_report_config(source_id)) + + +@admin_bp.route('/freight-rpa/sources//outbound-report-config', methods=['PUT']) +@require_admin +def save_shipping_outbound_report_config(source_id: int): + """保存独立出站报表配置,并由服务记录可追溯的前后快照审计。""" + return _ok(freight_rpa_report_config_service.save_outbound_report_config( + source_id, request.get_json(silent=True) or {}, actor_id=_actor_id(), + )) + + +@admin_bp.route('/freight-rpa/movement-fields', methods=['GET']) +@require_admin +def list_freight_rpa_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('/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( + rows = freight_rpa_source_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', ) @@ -124,7 +162,7 @@ def bulk_bind_shipping_inventory_source_parsing_profile(): source_ids = payload.get('source_ids') if not isinstance(source_ids, list): source_ids = [] - return _ok(shipping_onhand_admin_service.bind_source_parsing_profile( + return _ok(freight_rpa_source_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', )) @@ -134,28 +172,28 @@ def bulk_bind_shipping_inventory_source_parsing_profile(): @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)) + return _ok(freight_rpa_source_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())) + return _ok(freight_rpa_source_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())) + return _ok(freight_rpa_source_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) + freight_rpa_source_admin_service.delete_source(source_id) return '', 204 diff --git a/backend/app/api/freight_rpa.py b/backend/app/api/freight_rpa.py index 22d1f10b..dac5cf04 100644 --- a/backend/app/api/freight_rpa.py +++ b/backend/app/api/freight_rpa.py @@ -2,18 +2,18 @@ backend/app/api/freight_rpa.py 用途:货代 RPA 回调蓝图(/api/freight-rpa/*)——Windows Worker 向后端上报心跳、 - 库存(onhand)/收料(inbound)导出结果与货代上传结果的唯一回调入口。 + 库存(onhand)/入站(inbound)/出站(outbound)导出结果与货代上传结果的唯一回调入口。 批次 R 解耦后取代旧 shipping-notice rpa 回调前缀(无双路由、无兼容层)。 依赖:app.core.tool_auth(集成密钥鉴权)、freight_rpa.common.callback_sinks(sink 分发)、 - freight_rpa.common.worker_heartbeat(心跳)、shipping_tools、 - shipping_notice.rpa_sinks(api 层为组合根,允许同时 import 双侧)。 + freight_rpa.common.worker_heartbeat(心跳)、shipping_tools。 逻辑:before_request 统一 Bearer / X-Integration-Key 鉴权(与 Tool 蓝图同一把 key)。 分发策略按「处理函数当前住在哪个包」决定: - /heartbeat 直连 freight_rpa.common.worker_heartbeat; - /upload-complete 直连现有业务处理器(shipping_notice.tools); - - onhand-* 与 inbound-* 全部经 callback_sinks.dispatch_sink 分发,真实业务 sink 由 - 组合根(create_app → shipping_notice.rpa_sinks.register_onhand_sinks / - register_inbound_sinks)注册;未注册的 kind 显式 404(FREIGHT_RPA.SINK_NOT_REGISTERED)。 + - onhand-* / inbound-* / outbound-* 全部经 callback_sinks.dispatch_sink 分发, + 真实业务 sink 由组合根注册(onhand→shipping_notice.rpa_sinks; + inbound/outbound→in_transit_transfer.rpa_sinks); + 未注册的 kind 显式 404(FREIGHT_RPA.SINK_NOT_REGISTERED)。 """ from __future__ import annotations @@ -55,7 +55,7 @@ def _verify_worker_access(): def heartbeat(): """ RPA Worker 心跳上报。 - 【AI 触发时机】:非 Agent 入口;Windows Worker(库存/收料)由独立守护线程周期调用。 + 【AI 触发时机】:非 Agent 入口;Windows Worker(库存/入站)由独立守护线程周期调用。 核心逻辑:校验 payload 后写入 Redis/内存;后端在写各类 trigger 前以此做在线就绪检查。 """ @@ -169,12 +169,13 @@ def onhand_repair(): def inbound_batch_ready(): """ inbound(收料)批量导出终态回调(旧 /rpa/receipt-batch-ready)。 - 【AI 触发时机】:非 Agent 入口;收料 Worker 完成报表导出并落 drop 目录后调用。 + 【AI 触发时机】:非 Agent 入口;入站 Worker 完成报表导出并落 drop 目录后调用。 - 核心逻辑:dispatch_sink('inbound-batch-ready') 分发到组合根注册的业务 sink - (inbound_report_storage.ingest_receipt_callback:委托 freight_rpa.inbound.report_archive - 原样归档,终态 commit 后由域内业务桥推进在途调拨并归集排程终态)——独立归档文件, - 绝不进入库存回调或库存匹配链路;envelope = {'success': True, 'data': ...}(旧端点逐字一致)。 + 核心逻辑:dispatch_sink('inbound-batch-ready') 分发到组合根 + (in_transit_transfer.rpa_sinks)注册的业务 sink——直挂 + freight_rpa.inbound.report_archive.ingest_inbound_callback 原样归档,终态 commit + 后经 ReportFact → handle_inbound_report 推进调拨并归集排程;绝不进入库存匹配链路; + envelope = {'success': True, 'data': ...}(旧端点逐字一致)。 """ return jsonify(dispatch_sink('inbound-batch-ready', **_payload())) @@ -183,9 +184,9 @@ def inbound_batch_ready(): def inbound_unit_progress(): """ inbound 单元领取/导出中回调(旧 /rpa/receipt-unit-progress)。 - 【AI 触发时机】:非 Agent 入口;收料 Worker 领取单元后调用(awaiting_rpa → processing)。 + 【AI 触发时机】:非 Agent 入口;入站 Worker 领取单元后调用(awaiting_rpa → processing)。 - 核心逻辑:dispatch_sink('inbound-unit-progress') 分发到 mark_receipt_unit_processing + 核心逻辑:dispatch_sink('inbound-unit-progress') 分发到 mark_inbound_unit_processing (Task 11 已随排程壳平移改名,现住 schedule.freight_rpa_inbound_finalize);本路由同时是收料 超时对账的活动锚数据源(mark 落单元 started_at)。曾因重构分叉合并丢失(2026-10-08), Worker 上报全程 404,勿再从任何路由文件删除。 @@ -197,15 +198,50 @@ def inbound_unit_progress(): def inbound_batch_progress(): """ inbound 批量导出累计进度回调(旧 /rpa/receipt-batch-progress)。 - 【AI 触发时机】:非 Agent 入口;收料 Worker 每完成一笔导出后调用(非终态)。 + 【AI 触发时机】:非 Agent 入口;入站 Worker 每完成一笔导出后调用(非终态)。 - 核心逻辑:dispatch_sink('inbound-batch-progress') 分发到 report_receipt_batch_progress + 核心逻辑:dispatch_sink('inbound-batch-progress') 分发到 report_inbound_batch_progress (Task 11 已随排程壳平移改名,现住 schedule.freight_rpa_inbound_finalize),回写排程 run 计数 (对齐 onhand-batch-progress 语义)。 """ return jsonify(dispatch_sink('inbound-batch-progress', **_payload())) +@freight_rpa_bp.route('/outbound-batch-ready', methods=['POST']) +def outbound_batch_ready(): + """ + outbound(出站)批量导出终态回调。 + 【AI 触发时机】:非 Agent 入口;出站 Worker 完成报表导出并落 drop 目录后调用。 + + 核心逻辑:dispatch_sink('outbound-batch-ready') 分发到组合根或测内注册的 sink + (ingest_outbound_callback:原样归档,终态 commit 后 dispatch_report_fact + report_kind='outbound');鉴权与入站同 ToolApiKey。 + """ + return jsonify(dispatch_sink('outbound-batch-ready', **_payload())) + + +@freight_rpa_bp.route('/outbound-unit-progress', methods=['POST']) +def outbound_unit_progress(): + """ + outbound 单元领取/导出中回调。 + 【AI 触发时机】:非 Agent 入口;出站 Worker 领取单元后调用(awaiting_rpa → processing)。 + + 核心逻辑:dispatch_sink('outbound-unit-progress') 分发;鉴权与入站同 ToolApiKey。 + """ + return jsonify(dispatch_sink('outbound-unit-progress', **_payload())) + + +@freight_rpa_bp.route('/outbound-batch-progress', methods=['POST']) +def outbound_batch_progress(): + """ + outbound 批量导出累计进度回调。 + 【AI 触发时机】:非 Agent 入口;出站 Worker 每完成一笔导出后调用(非终态)。 + + 核心逻辑:dispatch_sink('outbound-batch-progress') 分发;鉴权与入站同 ToolApiKey。 + """ + return jsonify(dispatch_sink('outbound-batch-progress', **_payload())) + + @freight_rpa_bp.route('/upload-complete', methods=['POST']) def upload_complete(): """ diff --git a/backend/app/api/internal/jobs.py b/backend/app/api/internal/jobs.py index f31718de..1b061731 100644 --- a/backend/app/api/internal/jobs.py +++ b/backend/app/api/internal/jobs.py @@ -2,7 +2,8 @@ backend/app/api/internal/jobs.py 用途:平台内置 Job 内部 API(POST /api/internal/jobs/)。 -依赖:job_registry、schedule_contract、scheduler_service。 +依赖:job_registry、schedule_contract、scheduler_service、 + freight_rpa_onhand_finalize / inbound_finalize / outbound_finalize(awaiting 延后终态)。 逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。 """ from __future__ import annotations @@ -25,9 +26,14 @@ from app.services.schedule.freight_rpa_onhand_finalize import ( should_defer_schedule_run_finalization, ) 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, + apply_deferred_inbound_schedule_run_state, + recover_stale_inbound_rpa_schedule_runs, + should_defer_inbound_schedule_run, +) +from app.services.schedule.freight_rpa_outbound_finalize import ( + apply_deferred_outbound_schedule_run_state, + recover_stale_outbound_rpa_schedule_runs, + should_defer_outbound_schedule_run, ) internal_jobs_bp = Blueprint('internal_jobs', __name__) @@ -139,7 +145,8 @@ def run_internal_job(name: str): task, run = _resolve_schedule_task_and_run(key, data) recover_stale_awaiting_rpa_schedule_runs(task) - recover_stale_receipt_rpa_schedule_runs(task) + recover_stale_inbound_rpa_schedule_runs(task) + recover_stale_outbound_rpa_schedule_runs(task) try: total_count, success_count, failed_count, skipped_count, details, errors, step_logs = run_platform_job( key, task, run, data, @@ -189,8 +196,8 @@ def run_internal_job(name: str): 'awaiting_rpa_callback': True, }) - if should_defer_receipt_schedule_run(task, step_logs): - apply_deferred_receipt_schedule_run_state( + if should_defer_inbound_schedule_run(task, step_logs): + apply_deferred_inbound_schedule_run_state( run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs, ) return jsonify({ @@ -199,7 +206,20 @@ def run_internal_job(name: str): 'failed_count': failed_count, 'skipped_count': skipped_count, }, 'details': details, 'errors': errors, 'step_logs': step_logs, - 'awaiting_receipt_rpa_callback': True, + 'awaiting_inbound_rpa_callback': True, + }) + + if should_defer_outbound_schedule_run(task, step_logs): + apply_deferred_outbound_schedule_run_state( + run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs, + ) + return jsonify({ + 'summary': { + 'total_count': total_count, 'success_count': success_count, + 'failed_count': failed_count, 'skipped_count': skipped_count, + }, + 'details': details, 'errors': errors, 'step_logs': step_logs, + 'awaiting_outbound_rpa_callback': True, }) _finalize_run( diff --git a/backend/app/api/schedule/rpa_workers.py b/backend/app/api/schedule/rpa_workers.py index 2e08cd84..ba0228e9 100644 --- a/backend/app/api/schedule/rpa_workers.py +++ b/backend/app/api/schedule/rpa_workers.py @@ -1,9 +1,9 @@ """ backend/app/api/schedule/rpa_workers.py -用途:管理端查询货代库存/收料 RPA Worker 在线状态与就绪摘要。 +用途:管理端查询货代库存/入站/出站 RPA Worker 在线状态与就绪摘要。 依赖:schedule.blueprint、freight_rpa.common.worker_heartbeat.serialize_rpa_worker_status。 -逻辑:ScheduleWorkbenchPanel 在库存或收料 RPA 排程工作台展示对应 worker 心跳状态。 +逻辑:ScheduleWorkbenchPanel 在库存、入站或出站 RPA 排程工作台展示对应 worker 心跳状态。 """ from __future__ import annotations @@ -23,7 +23,7 @@ def get_rpa_workers_status(): 返回 RPA Worker 心跳摘要(在线/离线、最后心跳时间、就绪原因)。 Query: - scope: onhand(默认)或 inbound。 + scope: onhand(默认)、inbound 或 outbound。 """ scope = str(request.args.get('scope') or 'onhand').strip().lower() or 'onhand' return ok(serialize_rpa_worker_status(scope=scope)) diff --git a/backend/app/api/schedule/runs.py b/backend/app/api/schedule/runs.py index a3d30d6b..c7099ce3 100644 --- a/backend/app/api/schedule/runs.py +++ b/backend/app/api/schedule/runs.py @@ -2,8 +2,10 @@ backend/app/api/schedule/runs.py 用途:排程运行触发与运行记录查询 API。 -依赖:schedule.blueprint、services/schedule/query_service、queue_service。 +依赖:schedule.blueprint、services/schedule/query_service、queue_service、 + freight_rpa inbound/outbound archive 与 trigger_io。 逻辑:手动执行仅创建 queued run/job;独立 schedule worker 承担实际运行。 + 入站/出站 raw-zip 下载与失败单元 list/retry 对照同构。 """ from __future__ import annotations @@ -18,14 +20,15 @@ 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, FreightRpaInboundReportFile, FreightRpaInboundUnitRun +from app.models import ScheduleRun, ScheduleTask, FreightRpaInboundUnitRun, FreightRpaOutboundUnitRun 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_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.schedule.freight_rpa_inbound_archive import resolve_inbound_raw_zip_download +from app.services.schedule.freight_rpa_outbound_archive import resolve_outbound_raw_zip_download 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 +from app.services.freight_rpa.outbound.trigger_io import SCHEMA as OUTBOUND_SCHEMA, write_outbound_export_batch_trigger @schedule_admin_bp.route('/schedules//run', methods=['POST']) @@ -124,18 +127,18 @@ def get_schedule_run_inventory_raw_zip(run_id: int): ) -@schedule_admin_bp.route('/schedule-runs//receipt-raw-zip', methods=['GET']) +@schedule_admin_bp.route('/schedule-runs//inbound-raw-zip', methods=['GET']) @require_admin -def get_schedule_run_receipt_raw_zip(run_id: int): +def get_schedule_run_inbound_raw_zip(run_id: int): """ - 下载收料 RPA 排程 run 的原始收料 Excel 打包(ZIP + manifest)。 + 下载入站 RPA 排程 run 的原始入站 Excel 打包(ZIP + manifest)。 - 核心逻辑:对齐 inventory-raw-zip;展示名为 收料RPA-{日期}-{时刻}-收料.zip。 + 核心逻辑:对齐 inventory-raw-zip;展示名为 入站RPA-{日期}-{时刻}-入站.zip。 """ run = get_run(run_id) if not run: raise NotFoundError('Not found') - zip_path, file_name = resolve_receipt_raw_zip_download(run) + zip_path, file_name = resolve_inbound_raw_zip_download(run) return send_file( zip_path, as_attachment=True, @@ -144,31 +147,10 @@ def get_schedule_run_receipt_raw_zip(run_id: int): ) -@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(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_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)}, - artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], - metadata={'success_count': int(outcome.get('success_count', 0)), 'failed_count': int(outcome.get('failed_count', 0))}, - ) - db.session.commit() - return jsonify({'success': True, 'data': outcome}) - - @schedule_admin_bp.route('/inbound-rpa-units', methods=['GET']) @require_admin -def list_receipt_rpa_units(): - """管理员查看收料单元运行事实,供失败单元填写原因后人工重试。""" +def list_inbound_rpa_units(): + """管理员查看入站单元运行事实,供失败单元填写原因后人工重试。""" status = str(request.args.get('status') or '').strip().lower() if status and status not in {'queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled'}: from app.core.errors import ValidationError @@ -190,7 +172,7 @@ def list_receipt_rpa_units(): 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}, - metadata={'surface': 'workspace_receipt_report_files'}, + metadata={'surface': 'admin_inbound_rpa_units'}, ) db.session.commit() return jsonify({'success': True, 'data': {'items': [{ @@ -209,23 +191,23 @@ def list_receipt_rpa_units(): @schedule_admin_bp.route('/inbound-rpa-units//retry', methods=['POST']) @require_admin -def retry_receipt_rpa_unit(unit_id: int): - """管理员为失败收料单元创建独立重试事实;旧单元永不覆盖。""" +def retry_inbound_rpa_unit(unit_id: int): + """管理员为失败入站单元创建独立重试事实;旧单元永不覆盖。""" failed = db.session.get(FreightRpaInboundUnitRun, unit_id) if failed is None: - raise NotFoundError('Receipt RPA unit not found') + raise NotFoundError('Inbound RPA unit not found') if failed.status not in {'failed', 'cancelled'}: - raise ConflictError('Only failed receipt RPA units can be retried') + raise ConflictError('Only failed inbound RPA units can be retried') data = request.get_json(silent=True) or {} reason = str(data.get('reason') or '').strip() if not reason: from app.core.errors import ValidationError - raise ValidationError('reason is required', code='SHIPPING.RECEIPT_RETRY_REASON_REQUIRED') + raise ValidationError('reason is required', code='SHIPPING.INBOUND_RETRY_REASON_REQUIRED') user = get_current_user() 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', + warehouse_id=failed.warehouse_id, callback_id=f'inbound:{uuid.uuid4().hex}', status='awaiting_rpa', config_snapshot_json=dict(failed.config_snapshot_json or {}), ) db.session.add(retry) @@ -234,7 +216,7 @@ def retry_receipt_rpa_unit(unit_id: int): 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() - raise ConflictError('Receipt RPA profile is unavailable') + raise ConflictError('Inbound RPA profile is unavailable') snapshot = dict(retry.config_snapshot_json or {}) trigger_unit = { 'unit_run_id': retry.id, 'callback_id': retry.callback_id, 'source_code': retry.source_code, @@ -253,11 +235,11 @@ def retry_receipt_rpa_unit(unit_id: int): ) if not trigger_path: db.session.rollback() - raise ConflictError('Receipt RPA trigger directory is unavailable') + raise ConflictError('Inbound RPA trigger directory is unavailable') run.status = 'running' run.finished_at = None summary = dict(run.response_summary_json or {}) - summary['awaiting_receipt_rpa'] = True + summary['awaiting_inbound_rpa'] = True run.response_summary_json = summary append_shipping_audit_event( event_type='shipping_inbound_rpa_unit_retried', aggregate_type='shipping_inbound_unit', @@ -269,3 +251,136 @@ def retry_receipt_rpa_unit(unit_id: int): ) db.session.commit() return jsonify({'success': True, 'data': {'unit_id': retry.id, 'retry_of_id': failed.id, 'callback_id': retry.callback_id, 'trigger_path': trigger_path}}) + + +@schedule_admin_bp.route('/schedule-runs//outbound-raw-zip', methods=['GET']) +@require_admin +def get_schedule_run_outbound_raw_zip(run_id: int): + """ + 下载出站 RPA 排程 run 的原始出站 Excel 打包(ZIP + manifest)。 + + 核心逻辑:对齐 inbound-raw-zip;展示名为 出站RPA-{日期}-{时刻}-出站.zip。 + """ + run = get_run(run_id) + if not run: + raise NotFoundError('Not found') + zip_path, file_name = resolve_outbound_raw_zip_download(run) + return send_file( + zip_path, + as_attachment=True, + download_name=file_name, + mimetype='application/zip', + ) + + +@schedule_admin_bp.route('/outbound-rpa-units', methods=['GET']) +@require_admin +def list_outbound_rpa_units(): + """管理员查出站单元运行事实,供失败单元填写原因后人工重试。""" + status = str(request.args.get('status') or '').strip().lower() + if status and status not in {'queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled'}: + from app.core.errors import ValidationError + raise ValidationError('status is invalid') + try: + limit = max(1, min(int(request.args.get('limit') or 100), 200)) + except (TypeError, ValueError): + from app.core.errors import ValidationError + raise ValidationError('limit is invalid') + query = FreightRpaOutboundUnitRun.query.order_by( + FreightRpaOutboundUnitRun.created_at.desc(), FreightRpaOutboundUnitRun.id.desc(), + ) + if status: + query = query.filter(FreightRpaOutboundUnitRun.status == status) + units = query.limit(limit).all() + user = get_current_user() + append_shipping_audit_event( + event_type='shipping_outbound_rpa_units_listed', aggregate_type='shipping_outbound_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}, + metadata={'surface': 'admin_outbound_rpa_units'}, + ) + db.session.commit() + return jsonify({'success': True, 'data': {'items': [{ + 'id': unit.id, + 'source_code': unit.source_code, + 'warehouse_id': unit.warehouse_id, + 'status': unit.status, + 'error_code': unit.error_code, + 'error_message': unit.error_message, + 'retry_of_id': unit.retry_of_id, + 'schedule_run_id': unit.schedule_run_id, + 'created_at': unit.created_at.isoformat() if unit.created_at else None, + 'finished_at': unit.finished_at.isoformat() if unit.finished_at else None, + } for unit in units]}}) + + +@schedule_admin_bp.route('/outbound-rpa-units//retry', methods=['POST']) +@require_admin +def retry_outbound_rpa_unit(unit_id: int): + """管理员为失败出站单元创建独立重试事实;旧单元永不覆盖。调拨按需单元无排程 run 时仍可重试。""" + failed = db.session.get(FreightRpaOutboundUnitRun, unit_id) + if failed is None: + raise NotFoundError('Outbound RPA unit not found') + if failed.status not in {'failed', 'cancelled'}: + raise ConflictError('Only failed outbound RPA units can be retried') + data = request.get_json(silent=True) or {} + reason = str(data.get('reason') or '').strip() + if not reason: + from app.core.errors import ValidationError + raise ValidationError('reason is required', code='SHIPPING.OUTBOUND_RETRY_REASON_REQUIRED') + user = get_current_user() + retry = FreightRpaOutboundUnitRun( + 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'outbound:{uuid.uuid4().hex}', status='awaiting_rpa', + config_snapshot_json=dict(failed.config_snapshot_json or {}), + ) + db.session.add(retry) + db.session.flush() + 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() + raise ConflictError('Outbound RPA profile is unavailable') + snapshot = dict(retry.config_snapshot_json or {}) + trigger_unit = { + 'unit_run_id': retry.id, 'callback_id': retry.callback_id, 'source_code': retry.source_code, + 'connector_type': retry.connector_type, 'warehouse_id': retry.warehouse_id, + 'rpa_profile_id': profile.id, 'rpa_profile_code': profile.profile_code, 'login_url': profile.login_url, + 'login_config': dict(profile.login_config_json or {}), + 'credential_envelope': {'username_ciphertext': profile.username_ciphertext, 'password_ciphertext': profile.password_ciphertext}, + 'report_path_json': dict(snapshot.get('report_path_json') or {}), + 'query_parameters_json': list(snapshot.get('query_parameters_json') or []), 'config_snapshot': snapshot, + } + retry.trigger_snapshot_json = trigger_unit + run = retry.schedule_run + run_no = run.run_no if run is not None else f'outbound-retry-{retry.id}' + trigger_meta = { + 'schema_version': OUTBOUND_SCHEMA, 'retry_of_unit_id': failed.id, + } + if run is not None: + trigger_meta['schedule_run_id'] = run.id + trigger_meta['schedule_task_id'] = run.schedule_task_id + trigger_path = write_outbound_export_batch_trigger( + f'{run_no}-retry-{retry.id}', [trigger_unit], trigger_meta, + ) + if not trigger_path: + db.session.rollback() + raise ConflictError('Outbound RPA trigger directory is unavailable') + if run is not None: + run.status = 'running' + run.finished_at = None + summary = dict(run.response_summary_json or {}) + summary['awaiting_outbound_rpa'] = True + run.response_summary_json = summary + append_shipping_audit_event( + event_type='shipping_outbound_rpa_unit_retried', aggregate_type='shipping_outbound_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}, + after={'status': retry.status, 'source_run_no': retry.callback_id, 'owner_user_id': getattr(user, 'id', None)}, + metadata={'retry_of_id': failed.id}, + ) + db.session.commit() + return jsonify({'success': True, 'data': {'unit_id': retry.id, 'retry_of_id': failed.id, 'callback_id': retry.callback_id, 'trigger_path': trigger_path}}) diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index 528c6741..d4b27ac7 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -87,34 +87,6 @@ def _ok(payload: Any, *, status: int = 200): return ok(payload, request_id=getattr(g, 'request_id', None), status=status) -@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.inbound_report_access import resolve_receipt_report_download - - stream, filename, content_type = resolve_receipt_report_download(file_id, user) - response = send_file( - stream, as_attachment=True, download_name=filename, - mimetype=content_type or 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - ) - response.call_on_close(stream.close) - return response - - -@workspace_shipping_notice_bp.route('/inbound-report-files', methods=['GET']) -def workspace_list_receipt_report_files(): - """列出当前接收人或管理员可下载的收料归档文件,不返回对象存储定位。""" - user = _require_user() - try: - 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.inbound_report_access import list_receipt_report_files - - return _ok({'items': list_receipt_report_files(user, limit=limit)}) - - def _assert_fulfillment_task_ownership(task: ShippingNotice, user_id: int) -> None: """ 履约写接口:若请求携带期望 OT/Case/Run,校验与正式 Notice 归属一致。 diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index f84461bd..dda8657d 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -4,7 +4,7 @@ backend/app/models/__init__.py 用途:按业务域拆分的 ORM 模型包入口;聚合导出以保持 `from app.models import User` 兼容。 依赖:models/* 子模块(含 voucher_check、equipment_acceptance、freight_rpa_*)、app.extensions.db(经 base.Base)。 逻辑:Alembic / Flask-Migrate 通过本模块 import 注册全部表元数据;业务代码继续从此处导入模型类。 - 在手/入站模型导出 FreightRpa*。 + 在手/入站/出站模型导出 FreightRpa*。 """ from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest @@ -154,11 +154,15 @@ from app.models.freight_rpa_config import ( FreightRpaProfile, ) from app.models.freight_rpa_inbound_report import ( - FreightRpaInboundNotificationDelivery, FreightRpaInboundReportConfig, FreightRpaInboundReportFile, FreightRpaInboundUnitRun, ) +from app.models.freight_rpa_outbound_report import ( + FreightRpaOutboundReportConfig, + FreightRpaOutboundReportFile, + FreightRpaOutboundUnitRun, +) from app.models.shipping_temporary_onhand import ShippingTemporaryOnhandSession from app.models.shipping_customer import ( ShippingBusinessSequence, @@ -378,7 +382,9 @@ __all__ = [ 'FreightRpaInboundReportConfig', 'FreightRpaInboundUnitRun', 'FreightRpaInboundReportFile', - 'FreightRpaInboundNotificationDelivery', + 'FreightRpaOutboundReportConfig', + 'FreightRpaOutboundUnitRun', + 'FreightRpaOutboundReportFile', 'FreightRpaOnhandField', 'FreightRpaOnhandStructureAnalysis', 'FreightRpaOnhandRoutingRule', diff --git a/backend/app/models/freight_rpa_config.py b/backend/app/models/freight_rpa_config.py index 6450f7ab..481cfe28 100644 --- a/backend/app/models/freight_rpa_config.py +++ b/backend/app/models/freight_rpa_config.py @@ -1,10 +1,11 @@ """ backend/app/models/freight_rpa_config.py -用途:定义货代库存源、RPA Profile、在手报表配置、通用路由规则及外部系统仓库映射主数据。 +用途:定义货代库存源、RPA Profile、在手/入站/出站报表配置、通用路由规则及外部系统仓库映射主数据。 依赖:models.base.Base、SQLAlchemy ORM;凭据密文由 freight_rpa.common.credential_crypto 读写。 逻辑:库存运行链路以 FreightRpaSource.source_code 为业务主键;RPA Profile 仅提供登录连接配置; 在手报表路径/查询条件/解析方案绑定自 s18 起归 FreightRpaOnhandReportConfig(站点行不再存这三列), + 入站/出站配置分别挂 inbound_report_config / outbound_report_config 一对一关系; 外部系统映射仅供后端内部复用,不承载调拨决策。 """ @@ -132,6 +133,9 @@ class FreightRpaSource(Base): inbound_report_config: Mapped[Optional['FreightRpaInboundReportConfig']] = relationship( back_populates='source', uselist=False, cascade='all, delete-orphan', ) + outbound_report_config: Mapped[Optional['FreightRpaOutboundReportConfig']] = relationship( + back_populates='source', uselist=False, cascade='all, delete-orphan', + ) class FreightRpaOnhandReportConfig(Base): diff --git a/backend/app/models/freight_rpa_inbound_report.py b/backend/app/models/freight_rpa_inbound_report.py index 47471aff..72b13805 100644 --- a/backend/app/models/freight_rpa_inbound_report.py +++ b/backend/app/models/freight_rpa_inbound_report.py @@ -1,7 +1,7 @@ """ backend/app/models/freight_rpa_inbound_report.py -用途:入站报表 RPA 的配置、运行、归档与通知投递持久化模型。 +用途:入站报表 RPA 的配置、运行与归档持久化模型(per-file 企微投递表已拆除,见 Task 4 迁移)。 依赖:freight_rpa_sources、排程运行、freight_rpa_parsing_profiles、SQLAlchemy Base;完整操作追溯统一写入 ShippingAuditEvent。 逻辑:模型只复用站点连接资料,通过独立外键与唯一约束隔离在手快照、匹配和旧 RPA Worker 链路。 """ @@ -126,45 +126,3 @@ class FreightRpaInboundReportFile(Base): created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) unit_run: Mapped[FreightRpaInboundUnitRun] = relationship(back_populates='files') - deliveries: Mapped[list['FreightRpaInboundNotificationDelivery']] = relationship( - back_populates='report_file', cascade='all, delete-orphan', - ) - - -class FreightRpaInboundNotificationDelivery(Base): - """收料文件或汇总企微消息的幂等投递事实,响应仅保存脱敏摘要。""" - - __tablename__ = 'freight_rpa_inbound_notification_deliveries' - __table_args__ = ( - 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_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('freight_rpa_inbound_rpa_unit_runs.id'), nullable=True, index=True, - ) - report_file_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('freight_rpa_inbound_report_files.id'), nullable=True, 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') - response_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) - error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) - sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) - created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) - updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) - - 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/freight_rpa_outbound_report.py b/backend/app/models/freight_rpa_outbound_report.py new file mode 100644 index 00000000..a78563ea --- /dev/null +++ b/backend/app/models/freight_rpa_outbound_report.py @@ -0,0 +1,129 @@ +""" +backend/app/models/freight_rpa_outbound_report.py + +用途:出站报表 RPA 的配置、运行与归档持久化模型(不建 per-file 企微投递表)。 +依赖:freight_rpa_sources、排程运行、freight_rpa_parsing_profiles、SQLAlchemy Base;完整操作追溯统一写入 ShippingAuditEvent。 +逻辑:模型只复用站点连接资料,通过独立外键与唯一约束隔离在手快照、匹配和旧 RPA Worker 链路。 + FreightRpaSource.outbound_report_config 一对一回指本配置行。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Optional + +from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.models.base import Base + + +class FreightRpaOutboundReportConfig(Base): + """库存站点的一对一出站报表配置;路径和条件始终独立于库存 / 入站配置。""" + + __tablename__ = 'freight_rpa_outbound_report_configs' + __table_args__ = ( + UniqueConstraint('source_id', name='uq_freight_rpa_outbound_report_configs_source'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + source_id: Mapped[int] = mapped_column( + ForeignKey('freight_rpa_sources.id'), nullable=False, index=True, + ) + # 出站不设独立启停:是否运行统一由库存站点 enabled 与本配置是否存在决定。 + # 出站文件解析规则(purpose='outbound');定死领域字段端点。空则无法解析出站文件。 + parsing_profile_id: Mapped[Optional[int]] = mapped_column( + 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, + ) + query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column( + JSON, default=list, server_default=text("'[]'"), nullable=False, + ) + # 与库存同构:查询条件原样下发 Worker;空条件表示页面默认。排程一源一单元,不按仓拆分。 + 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='outbound_report_config') + parsing_profile: Mapped[Optional['FreightRpaParsingProfile']] = relationship() + + +class FreightRpaOutboundUnitRun(Base): + """一次出站执行的站点或站点-Warehouse 不可重复执行单元。 + + schedule_run_id 指向排程 run;调拨按需触发(重试/预检补抓)无排程,保持 NULL。 + """ + + __tablename__ = 'freight_rpa_outbound_rpa_unit_runs' + __table_args__ = ( + UniqueConstraint('callback_id', name='uq_freight_rpa_outbound_rpa_unit_runs_callback'), + CheckConstraint( + "status IN ('queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled')", + name='ck_freight_rpa_outbound_rpa_unit_runs_status', + ), + Index('ix_freight_rpa_outbound_unit_run_schedule_status', 'schedule_run_id', 'status'), + Index('ix_freight_rpa_outbound_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) + source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False, index=True) + retry_of_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('freight_rpa_outbound_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) + warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + callback_id: Mapped[str] = mapped_column(String(128), nullable=False) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued') + config_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + trigger_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + schedule_run: Mapped[Optional['ScheduleRun']] = relationship(foreign_keys=[schedule_run_id]) + source: Mapped['FreightRpaSource'] = relationship() + retry_of: Mapped[Optional['FreightRpaOutboundUnitRun']] = relationship(remote_side=[id]) + files: Mapped[list['FreightRpaOutboundReportFile']] = relationship( + back_populates='unit_run', cascade='all, delete-orphan', + ) + + +class FreightRpaOutboundReportFile(Base): + """出站原样归档文件;保留文件身份和对象清理事实,不关联库存快照。""" + + __tablename__ = 'freight_rpa_outbound_report_files' + __table_args__ = ( + UniqueConstraint('unit_run_id', 'sha256', name='uq_freight_rpa_outbound_report_files_unit_sha256'), + CheckConstraint("file_size >= 0", name='ck_freight_rpa_outbound_report_files_size'), + Index('ix_freight_rpa_outbound_report_files_unit', 'unit_run_id'), + Index('ix_freight_rpa_outbound_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('freight_rpa_outbound_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) + original_filename: Mapped[str] = mapped_column(String(255), nullable=False) + content_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + file_size: Mapped[int] = mapped_column(Integer, nullable=False) + sha256: Mapped[str] = mapped_column(String(64), nullable=False) + # 解析失败分层标记:归档文件解析失败时写入;三者全空=未失败/已清除。 + parse_failed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + parse_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + parse_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + archive_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + archive_deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + 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[FreightRpaOutboundUnitRun] = relationship(back_populates='files') diff --git a/backend/app/services/admin/freight_rpa_form_utils.py b/backend/app/services/admin/freight_rpa_form_utils.py new file mode 100644 index 00000000..dfbbec15 --- /dev/null +++ b/backend/app/services/admin/freight_rpa_form_utils.py @@ -0,0 +1,105 @@ +""" +services/admin/freight_rpa_form_utils.py + +用途:货代 RPA 管理端表单校验共用件(JSON 对象、报表路径、查询条件、时间序列化)。 +依赖:app.core.errors.ValidationError。 +逻辑:freight_rpa_source_admin_service(站点/连接)与 freight_rpa_report_config_service + (入站/出站报表配置)共用;错误码沿用历史 SHIPPING.ONHAND_SOURCE_CONFIG_INVALID, + 调用方可按域 remap。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from app.core.errors import ValidationError + + +def json_object(data: dict[str, Any], field: str) -> dict[str, Any]: + """读取并复制对象型 JSON 配置。 + + Args: + data: 管理 API 的请求载荷。 + field: 只允许 JSON object 的字段名。 + + Returns: + 空值规范化为空对象后的可写入配置。 + + Raises: + ValidationError: 字段不是 JSON object。 + """ + value = data.get(field, {}) + if not isinstance(value, dict): + raise ValidationError(f'{field} must be an object', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID') + return dict(value) + + +def validate_report_path(connector_type: str, report_path: dict[str, Any]) -> dict[str, str]: + """校验 DBS 四级报表路径,防止技术选择器混入业务配置。""" + allowed = {'program_group', 'program_label', 'report_group', 'report_name'} + if set(report_path) - allowed: + raise ValidationError('report_path_json contains unsupported fields', code='SHIPPING.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.ONHAND_SOURCE_CONFIG_INVALID', details={'missing': sorted(missing)}, + ) + elif normalized: + raise ValidationError( + 'Only DBS inventory sources can define report_path_json', + code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID', + ) + return {key: normalized[key] for key in allowed if normalized.get(key)} + + +def validate_query_parameters(data: dict[str, Any]) -> list[dict[str, Any]]: + """校验 Source 的可视化查询参数列表,禁止保存 selector 等 Driver 实现细节。""" + raw = data.get('query_parameters_json', []) + if not isinstance(raw, list): + raise ValidationError('query_parameters_json must be a list', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID') + result: list[dict[str, Any]] = [] + seen_names: set[str] = set() + allowed = {'name', 'mode', 'values', 'required', 'select_all', 'joiner'} + for index, item in enumerate(raw): + if not isinstance(item, dict) or set(item) - allowed: + raise ValidationError( + 'query parameter contains unsupported fields', + code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID', details={'index': index}, + ) + name = str(item.get('name') or '').strip() + mode = str(item.get('mode') or 'single').strip().lower() + values = item.get('values', []) + required = item.get('required', False) + select_all = item.get('select_all', False) + if not name or name.lower() in seen_names or mode not in {'single', 'multi_text', 'multi_select'}: + raise ValidationError('query parameter name or mode is invalid', code='SHIPPING.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.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.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.ONHAND_SOURCE_CONFIG_INVALID') + if select_all and mode != 'multi_select': + 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, + } + if mode == 'multi_text': + joiner = str(item.get('joiner') or ',').strip() + if not joiner: + 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 iso(value: datetime | None) -> str | None: + """datetime → ISO 字符串;None 保持 None。""" + return value.isoformat() if value else None diff --git a/backend/app/services/admin/freight_rpa_report_config_service.py b/backend/app/services/admin/freight_rpa_report_config_service.py new file mode 100644 index 00000000..ca8a9fd5 --- /dev/null +++ b/backend/app/services/admin/freight_rpa_report_config_service.py @@ -0,0 +1,224 @@ +""" +services/admin/freight_rpa_report_config_service.py + +用途:货代 RPA 入站 / 出站报表配置管理(GET/PUT),与在手配置解耦。 +依赖:db、FreightRpaSource / FreightRpaInboundReportConfig / FreightRpaOutboundReportConfig / + FreightRpaParsingProfile、freight_rpa_form_utils、shipping_notice.audit_service。 +逻辑:admin_freight_rpa 蓝图委托本服务;不进入来源站点启用硬门槛; + 解析绑定须 published 且 purpose 匹配 inbound/outbound。 +""" + +from __future__ import annotations + +from typing import Any + +from app.core.errors import NotFoundError, ValidationError +from app.extensions import db +from app.models import ( + FreightRpaInboundReportConfig, + FreightRpaOutboundReportConfig, + FreightRpaParsingProfile, + FreightRpaSource, +) +from app.services.admin.freight_rpa_form_utils import iso, json_object, validate_query_parameters, validate_report_path +from app.services.shipping_notice.audit_service import append_shipping_audit_event + + +def _inbound_report_config_payload(config: FreightRpaInboundReportConfig) -> dict[str, Any]: + """序列化独立入站配置,禁止把库存路径或凭据透传至管理端。""" + profile = config.parsing_profile + return { + 'id': config.id, 'source_id': config.source_id, + 'report_path_json': config.report_path_json or {}, + 'query_parameters_json': config.query_parameters_json or [], + 'parsing_profile_id': config.parsing_profile_id, + 'parsing_profile': ({ + 'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name, + 'version': profile.version, 'status': profile.status, + } if profile else None), + 'config_version': config.config_version, + 'created_at': iso(config.created_at), 'updated_at': iso(config.updated_at), + } + + +def _outbound_report_config_payload(config: FreightRpaOutboundReportConfig) -> dict[str, Any]: + """序列化独立出站配置,禁止把库存/入站路径或凭据透传至管理端。""" + profile = config.parsing_profile + return { + 'id': config.id, 'source_id': config.source_id, + 'report_path_json': config.report_path_json or {}, + 'query_parameters_json': config.query_parameters_json or [], + 'parsing_profile_id': config.parsing_profile_id, + 'parsing_profile': ({ + 'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name, + 'version': profile.version, 'status': profile.status, + } if profile else None), + 'config_version': config.config_version, + 'created_at': iso(config.created_at), 'updated_at': iso(config.updated_at), + } + + +def _validate_inbound_profile_binding(profile_id: Any) -> int | None: + """校验入站配置绑定的解析规则:必须已发布且 purpose='inbound';空值表示解绑。""" + if profile_id is None or str(profile_id).strip() == '': + return None + 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', + code='SHIPPING.INBOUND_PROFILE_INVALID', + ) + return profile.id + + +def _validate_outbound_profile_binding(profile_id: Any) -> int | None: + """校验出站配置绑定的解析规则:必须已发布且 purpose='outbound';空值表示解绑。""" + if profile_id is None or str(profile_id).strip() == '': + return None + profile = db.session.get(FreightRpaParsingProfile, int(profile_id)) + if profile is None or profile.status != 'published' or profile.purpose != 'outbound': + raise ValidationError( + 'Outbound parsing profile must be published with purpose outbound', + code='SHIPPING.OUTBOUND_PROFILE_INVALID', + ) + return profile.id + + +def _validate_inbound_report_config( + source: FreightRpaSource, data: dict[str, Any], +) -> tuple[dict[str, str], list[dict[str, Any]]]: + """规范入站配置:路径+查询条件;日期禁填。""" + try: + parameters = validate_query_parameters(data) + except ValidationError as exc: + raise ValidationError(str(exc), code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID') from exc + if any('date' in str(item.get('name') or '').strip().lower() for item in parameters): + raise ValidationError('Inbound report date filtering is not supported', code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID') + raw_path = json_object(data, 'report_path_json') + if source.connector_type == 'dbs': + try: + path = validate_report_path('dbs', raw_path) + except ValidationError as exc: + raise ValidationError(str(exc), code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID') from exc + return path, parameters + if source.connector_type == 'crane': + if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Inbound Details'): + raise ValidationError('Crane inbound report is fixed to Inbound Details', code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID') + if parameters: + raise ValidationError( + 'Crane inbound report does not support query parameters', + code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID', + ) + return {'report_name': 'Inbound Details'}, [] + raise ValidationError('Unsupported inbound connector type', code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID') + + +def _validate_outbound_report_config( + source: FreightRpaSource, data: dict[str, Any], +) -> tuple[dict[str, str], list[dict[str, Any]]]: + """规范出站配置:路径+查询条件;日期禁填;Crane 固定 Outbound Details。""" + try: + parameters = validate_query_parameters(data) + except ValidationError as exc: + raise ValidationError(str(exc), code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID') from exc + if any('date' in str(item.get('name') or '').strip().lower() for item in parameters): + raise ValidationError('Outbound report date filtering is not supported', code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID') + raw_path = json_object(data, 'report_path_json') + if source.connector_type == 'dbs': + try: + path = validate_report_path('dbs', raw_path) + except ValidationError as exc: + raise ValidationError(str(exc), code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID') from exc + return path, parameters + if source.connector_type == 'crane': + if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Outbound Details'): + raise ValidationError('Crane outbound report is fixed to Outbound Details', code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID') + if parameters: + raise ValidationError( + 'Crane outbound report does not support query parameters', + code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID', + ) + return {'report_name': 'Outbound Details'}, [] + raise ValidationError('Unsupported outbound connector type', code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID') + + +def get_inbound_report_config(source_id: int) -> dict[str, Any] | None: + """读取站点的入站配置;不存在时返回空。""" + source = db.session.get(FreightRpaSource, source_id) + if source is 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 _inbound_report_config_payload(config) if config else None + + +def save_inbound_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: + """保存站点内独立入站配置并追加配置前后快照审计。""" + source = db.session.get(FreightRpaSource, source_id) + if source is None: + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') + path, parameters = _validate_inbound_report_config(source, data) + config = FreightRpaInboundReportConfig.query.filter_by(source_id=source.id).one_or_none() + before = _inbound_report_config_payload(config) if config else None + is_new = config is None + if config is None: + config = FreightRpaInboundReportConfig(source_id=source.id) + config.created_by = actor_id + db.session.add(config) + else: + config.config_version += 1 + config.report_path_json = path + config.query_parameters_json = parameters + config.parsing_profile_id = _validate_inbound_profile_binding(data.get('parsing_profile_id')) + config.updated_by = actor_id + db.session.flush() + after = _inbound_report_config_payload(config) + append_shipping_audit_event( + 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={'source_id': source.id, 'connector_type': source.connector_type, + 'parsing_profile_id': config.parsing_profile_id}, + ) + db.session.commit() + return after + + +def get_outbound_report_config(source_id: int) -> dict[str, Any] | None: + """读取站点的出站配置;不存在时返回空。""" + source = db.session.get(FreightRpaSource, source_id) + if source is None: + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') + config = FreightRpaOutboundReportConfig.query.filter_by(source_id=source.id).one_or_none() + return _outbound_report_config_payload(config) if config else None + + +def save_outbound_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: + """保存站点内独立出站配置并追加配置前后快照审计。""" + source = db.session.get(FreightRpaSource, source_id) + if source is None: + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') + path, parameters = _validate_outbound_report_config(source, data) + config = FreightRpaOutboundReportConfig.query.filter_by(source_id=source.id).one_or_none() + before = _outbound_report_config_payload(config) if config else None + is_new = config is None + if config is None: + config = FreightRpaOutboundReportConfig(source_id=source.id) + config.created_by = actor_id + db.session.add(config) + else: + config.config_version += 1 + config.report_path_json = path + config.query_parameters_json = parameters + config.parsing_profile_id = _validate_outbound_profile_binding(data.get('parsing_profile_id')) + config.updated_by = actor_id + db.session.flush() + after = _outbound_report_config_payload(config) + append_shipping_audit_event( + event_type='shipping_outbound_report_config_saved', aggregate_type='shipping_outbound_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={'source_id': source.id, 'connector_type': source.connector_type, + 'parsing_profile_id': config.parsing_profile_id}, + ) + db.session.commit() + return after diff --git a/backend/app/services/admin/freight_rpa_source_admin_service.py b/backend/app/services/admin/freight_rpa_source_admin_service.py new file mode 100644 index 00000000..8f58e135 --- /dev/null +++ b/backend/app/services/admin/freight_rpa_source_admin_service.py @@ -0,0 +1,702 @@ +""" +services/admin/freight_rpa_source_admin_service.py + +用途:货代 RPA 共用主数据管理——登录连接(FreightRpaProfile)与来源站点(FreightRpaSource), + 含站点启用门禁、在手配置行写入、解析绑定审计。 +依赖:db、FreightRpaProfile / FreightRpaSource / FreightRpaOnhandReportConfig、 + freight_rpa_form_utils、credential_crypto、parsing_profile、upload_config_validation、 + onhand_source_repository.validate_source_profile、audit_service。 +逻辑:admin_freight_rpa 蓝图的 rpa-profiles / sources / bind-parsing / activate 委托本服务; + 在手快照/路由规则/外部映射仍见 shipping_onhand_admin_service。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.extensions import db +from app.models import ( + FreightRpaOnhandExternalMapping, + FreightRpaOnhandReportConfig, + FreightRpaOnhandReportFile, + FreightRpaOnhandRoutingRule, + FreightRpaParsingProfile, + FreightRpaProfile, + FreightRpaSource, + FreightRpaSourceParsingBindingAudit, + ScheduleRun, + ShippingExcelTemplate, + ShippingNoticeLine, + ShippingNoticeLineOnhandMatch, +) +from app.services.admin.freight_rpa_form_utils import ( + iso as _iso, + json_object as _json_object, + validate_query_parameters as _validate_query_parameters, + validate_report_path as _validate_report_path, +) +from app.services.freight_rpa import parsing_profile as onhand_parsing_profile +from app.services.freight_rpa.common.credential_crypto import encrypt_credential +from app.services.shipping_notice.audit_service import append_shipping_audit_event +from app.services.shipping_notice.onhand_source_repository import validate_source_profile +from app.services.shipping_notice.upload_config_validation import validate_upload_config + + +def _text(data: dict[str, Any], field: str, *, required: bool = False) -> str | None: + """读取并清洗字符串表单字段。""" + value = str(data.get(field) or '').strip() + if required and not value: + raise ValidationError(f'{field} is required', code='VALIDATION.INVALID_PARAM', details={'field': field}) + return value or None + + +def _bool(data: dict[str, Any], field: str, default: bool = True) -> bool: + """读取布尔表单字段。""" + value = data.get(field, default) + if not isinstance(value, bool): + raise ValidationError(f'{field} must be a boolean', details={'field': field}) + return value + + + +def _validate_profile_login_config(data: dict[str, Any]) -> dict[str, str]: + """校验连接级登录配置,不接收页面选择器或报表操作字段。""" + value = data.get('login_config_json', {}) + if not isinstance(value, dict) or set(value) - {'auth_mode'}: + raise ValidationError('login_config_json is invalid', code='SHIPPING.RPA_PROFILE_CONFIG_INVALID') + auth_mode = str(value.get('auth_mode') or 'password').strip().lower() + if auth_mode != 'password': + raise ValidationError( + 'Only password authentication is currently supported', + code='SHIPPING.RPA_PROFILE_CONFIG_INVALID', + ) + return {'auth_mode': auth_mode} + + + + +def _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, + 'login_config_json': profile.login_config_json or {'auth_mode': 'password'}, 'enabled': bool(profile.enabled), + 'upload_config_json': profile.upload_config_json, + 'config_version': profile.config_version, 'username_masked': _mask(profile.username_ciphertext), + 'password_configured': bool(profile.password_ciphertext), 'credential_updated_at': _iso(profile.credential_updated_at), + 'created_at': _iso(profile.created_at), 'updated_at': _iso(profile.updated_at), + } + + +def _mask(ciphertext: str | None) -> str | None: + """凭据密文不支持反向展示;仅以配置状态提示管理员。""" + return 'configured' if ciphertext else None + + + + +def list_profiles() -> list[dict[str, Any]]: + """列出 Profile 元数据,不返回可恢复的凭据。""" + 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(FreightRpaProfile, profile_id) + if profile is None: + raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND') + 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() + + +def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]: + """创建或更新货代登录连接;密码留空表示保留既有密文。""" + 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 FreightRpaProfile(profile_code='', display_name='', connector_type='', login_url='', login_config_json={}) + # 记录“非 upload_config”的既有运行时配置快照:仅当这些字段变化才递增 config_version, + # upload_config_json 属于连接上传配置,变更不得误判库存 RPA 配置测试过期。 + prev_non_upload = ( + profile.profile_code, profile.display_name, profile.connector_type, profile.login_url, + dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled), + bool(profile.username_ciphertext), bool(profile.password_ciphertext), + ) if profile_id else None + profile.profile_code = str(_text(data, 'profile_code', required=True)).upper() + profile.display_name = str(_text(data, 'display_name', required=True)) + profile.connector_type = str(_text(data, 'connector_type', required=True)).lower() + profile.login_url = str(_text(data, 'login_url', required=True)) + profile.login_config_json = _validate_profile_login_config(data) + profile.enabled = _bool(data, 'enabled', bool(profile.enabled) if profile_id else True) + if not profile.enabled and any(source.enabled for source in profile.sources): + raise ConflictError( + 'Disable inventory sources before disabling their RPA Profile', + code='SHIPPING.RPA_PROFILE_DISABLE_BLOCKED', + ) + username = _text(data, 'username') + password = _text(data, 'password') + if username is not None: + profile.username_ciphertext = encrypt_credential(username) + if password is not None: + profile.password_ciphertext = encrypt_credential(password) + if username is not None or password is not None: + profile.credential_updated_at = datetime.utcnow() + # 连接级受控上传配置(受限 JSON);与库存 RPA 运行期配置隔离,不参与 config_version。 + if 'upload_config_json' in data: + profile.upload_config_json = validate_upload_config(profile.connector_type, data.get('upload_config_json')) + profile.updated_by = actor_id + if profile_id: + now_non_upload = ( + profile.profile_code, profile.display_name, profile.connector_type, profile.login_url, + dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled), + bool(profile.username_ciphertext), bool(profile.password_ciphertext), + ) + if now_non_upload != prev_non_upload: + profile.config_version += 1 + if not profile_id: + profile.created_by = actor_id + db.session.add(profile) + try: + db.session.commit() + except Exception as exc: + db.session.rollback() + raise ConflictError('RPA Profile code already exists', code='SHIPPING.RPA_PROFILE_CONFLICT') from exc + return _profile_payload(profile) + + +def _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, + 'excel_template_id': source.excel_template_id, + 'warehouse_resolution_mode': source.warehouse_resolution_mode, 'fixed_warehouse_id': source.fixed_warehouse_id, + '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 _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': 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: FreightRpaSource, profile: FreightRpaParsingProfile) -> None: + """校验站点可直接采用的已发布方案与当前发货模板字段契约;启用中的站点同样允许更换解析绑定。""" + if profile.status != 'published': + 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.ONHAND_PARSING_PROFILE_REQUIRED') + template = source.excel_template + if template is None: + return + if template.status != 'published': + raise ValidationError('Published excel template is required', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED') + template_definition = template.definition_json if isinstance(template.definition_json, dict) else {} + template_mappings = template_definition.get('mappings') if isinstance(template_definition.get('mappings'), list) else [] + missing_fields = sorted({ + str(item.get('source_key') or '') + for item in template_mappings + if isinstance(item, dict) + and item.get('source_kind') == 'inventory_field' + and str(item.get('source_key') or '') not in mapping + }) + if missing_fields: + raise ValidationError( + 'Parsing profile does not provide all inventory fields required by the excel template', + code='SHIPPING.ONHAND_SOURCE_BINDING_TEMPLATE_INVALID', details={'inventory_field_ids': missing_fields}, + ) + + +def bind_source_parsing_profile( + source_ids: list[int], profile_id: int, *, actor_id: int | None, reason: str | None = None, operation: str, +) -> list[dict[str, Any]]: + """为一个或多个库存站点原子绑定已发布解析方案并写入追加式审计(含已启用站点)。 + + Args: + source_ids: 待绑定的库存站点主键,不能为空且不得重复。 + profile_id: 必须为已发布解析方案主键。 + actor_id: 当前管理员主键,仅写入审计。 + reason: 可选的补充说明;未填写时由系统记录本次直接或批量绑定动作。 + operation: 审计操作类型,仅允许 ``direct`` 或 ``bulk``。 + + Returns: + list[dict[str, Any]]: 已更新站点的管理端 DTO。 + + Raises: + ValidationError: 任一站点、方案或模板字段契约不合法;批量请求不会部分写入。 + ConflictError: 试图变更已启用站点的正式解析方案。 + """ + try: + normalized_ids = sorted({int(item) for item in source_ids if int(item) > 0}) + except (TypeError, ValueError) as exc: + raise ValidationError('source_ids must be a non-empty unique integer list', code='VALIDATION.INVALID_PARAM') from exc + if not normalized_ids or len(normalized_ids) != len(source_ids): + raise ValidationError('source_ids must be a non-empty unique integer list', code='VALIDATION.INVALID_PARAM') + if operation not in {'direct', 'bulk'}: + raise ValidationError('Binding operation is invalid', code='VALIDATION.INVALID_PARAM') + normalized_reason = str(reason or '').strip() + if len(normalized_reason) > 500: + raise ValidationError('Binding note must not exceed 500 characters', code='VALIDATION.INVALID_PARAM') + # 审计必须保留可读动作,但不应把技术审计字段变成管理员的额外填写负担。 + if not normalized_reason: + normalized_reason = '管理员直接绑定已发布解析方案' if operation == 'direct' else '管理员批量绑定已发布解析方案' + try: + 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(FreightRpaParsingProfile, normalized_profile_id) + if profile is None: + 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.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) + # 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(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), + )) + db.session.commit() + return [_source_payload(source) for source in typed_sources] + + +def get_source_parsing_binding_audits(source_id: int) -> list[dict[str, Any]]: + """读取库存站点解析绑定审计,仅返回配置快照和操作者标识。""" + 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, + 'source_config_version_before': row.source_config_version_before, + 'source_config_version_after': row.source_config_version_after, + 'before': row.before_snapshot_json, 'after': row.after_snapshot_json, + 'created_at': row.created_at.isoformat() if row.created_at else None, + } for row in rows] + + +def list_sources() -> list[dict[str, Any]]: + """列出库存源及其稳定业务配置。""" + 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(FreightRpaSource, source_id) + if source is None: + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') + source_code = str(source.source_code or '').strip().upper() + 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 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(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} + for run in ScheduleRun.query.all() + for source_codes in [(run.api_request_json or {}).get('source_codes', [])] + if isinstance(source_codes, list) + ) + if has_mapping or has_snapshot or has_rule or has_task or has_export_run: + raise ConflictError('Inventory Source has operational references', code='SHIPPING.ONHAND_SOURCE_DELETE_BLOCKED') + db.session.delete(source) + db.session.commit() + + +def _template_validation_missing(source: FreightRpaSource) -> list[str]: + """确认发货模板引用的库存字段均由当前解析方案提供,避免启用后才发现字段断链。""" + template = source.excel_template + # 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 {} + mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else [] + profile_definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} + inventory_fields = {str(field_id) for field_id in (profile_definition.get('field_mapping') or {}).keys()} + invalid = any( + isinstance(item, dict) + and item.get('source_kind') == 'inventory_field' + and str(item.get('source_key') or '') not in inventory_fields + for item in mappings + ) + return ['template_validation'] if not mappings or invalid else [] + + +def _activation_check( + code: str, *, passed: bool, action: str, evidence: dict[str, Any], status: str | None = None, + blocking: bool | None = None, +) -> dict[str, Any]: + """构造单项启用门禁结果,确保管理端只展示服务端已判定的业务事实。""" + return { + 'code': code, + 'status': status or ('passed' if passed else 'pending'), + 'blocking': not passed if blocking is None else blocking, + 'action': action, + 'evidence': evidence, + } + + +def _source_activation_checks(source: FreightRpaSource) -> list[dict[str, Any]]: + """构建库存站点启用硬门槛:可用连接、已发布解析方案、已绑定已发布发货模板及字段契约。 + + 测试导出不再参与启用门禁;启停由管理员显式开关完成。 + """ + profile_ready = source.rpa_profile is not None and bool(source.rpa_profile.enabled) + # 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 [ + _activation_check( + 'rpa_profile', passed=profile_ready, action='configure_connection', + evidence={'profile_id': source.rpa_profile_id, 'enabled': profile_ready}, + ), + _activation_check( + 'parsing_profile', passed=parsing_ready, action='configure_parsing_profile', + 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', + evidence={'template_id': source.excel_template_id, 'published': template_ready}, + ), + _activation_check( + 'template_validation', passed=not template_invalid, + action='configure_excel_template', evidence={}, blocking=template_invalid, + ), + ] + + +def get_source_activation_status(source: FreightRpaSource) -> dict[str, Any]: + """返回库存站点启用硬门槛的结构化结果。 + + Args: + source: 已持久化的库存站点,关联配置由当前数据库事务提供。 + + Returns: + dict[str, Any]: ``checks`` 为前端唯一的检查真相;``ready`` 为启用结论; + ``missing_requirements`` 是由 checks 派生的紧凑摘要,供现有调用方读取。 + """ + checks = _source_activation_checks(source) + missing = [item['code'] for item in checks if item['blocking']] + return { + 'ready': not missing, + 'checks': checks, + 'missing_requirements': missing, + } + + +def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]: + """启用已满足硬门槛的库存站点;未通过任一前置条件时保持停用。""" + source = db.session.get(FreightRpaSource, source_id) + if source is None: + 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.ONHAND_SOURCE_ACTIVATION_BLOCKED', + details=status, + ) + source.enabled = True + source.updated_by = actor_id + db.session.commit() + return _source_payload(source) + + +def deactivate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]: + """停用库存站点,保留其解析方案和历史运行审计。""" + source = db.session.get(FreightRpaSource, source_id) + if source is None: + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') + source.enabled = False + source.updated_by = actor_id + db.session.commit() + return _source_payload(source) + + +def save_source( + data: dict[str, Any], *, actor_id: int | None, source_id: int | None = None, + allow_enable_transition: bool = True, +) -> dict[str, Any]: + """保存库存站点基础配置;管理 API 不允许通过普通保存直接启用站点。 + + 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.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(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) + if not allow_enable_transition: + # 普通保存不承担状态切换:首次一律停用,已启用站点保留当前状态。 + enabled = bool(source.enabled) if source is not None else False + else: + enabled = requested_enabled + if enabled and not profile.enabled: + raise ValidationError( + 'Enabled Inventory Source requires an enabled RPA Profile', + code='SHIPPING.RPA_PROFILE_DISABLED', + ) + 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') + is_new = source is None + 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.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.snapshot_ttl_seconds = int(data.get('snapshot_ttl_seconds') or 86400) + source.enabled = enabled + source.updated_by = actor_id + if source_id: + source.config_version += 1 + if is_new: + source.created_by = actor_id + db.session.add(source) + # [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.ONHAND_SOURCE_INVALID') from exc + return _source_payload(source) + diff --git a/backend/app/services/admin/shipping_onhand_admin_service.py b/backend/app/services/admin/shipping_onhand_admin_service.py index 29a8839d..3a8b5aad 100644 --- a/backend/app/services/admin/shipping_onhand_admin_service.py +++ b/backend/app/services/admin/shipping_onhand_admin_service.py @@ -1,44 +1,38 @@ """ services/admin/shipping_onhand_admin_service.py -用途:管理库存源、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 不能跨表)。 +用途:在手域管理——库存快照只读、导出运行记录、路由规则、外部仓库映射。 +依赖:db、FreightRpaOnhandReportFile / FreightRpaOnhandRoutingRule / + FreightRpaOnhandExternalMapping、order_schema、routing_operators、ALLOWED_ACTIONS。 +逻辑:admin_freight_rpa 的 snapshots / export-records / rules / external-mappings 委托本服务; + 登录连接与来源站点见 freight_rpa_source_admin_service。 """ from __future__ import annotations -from datetime import datetime from typing import Any -from app.extensions import db from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.extensions import db from app.models import ( - FreightRpaOnhandExternalMapping, FreightRpaOnhandReportFile, FreightRpaOnhandRoutingRule, FreightRpaOnhandRoutingRuleCondition, - FreightRpaOnhandRoutingRuleVersion, FreightRpaSource, FreightRpaProfile, ScheduleRun, ScheduleTask, ShippingNotice, + FreightRpaOnhandExternalMapping, + FreightRpaOnhandReportFile, + FreightRpaOnhandRoutingRule, + FreightRpaOnhandRoutingRuleCondition, + FreightRpaOnhandRoutingRuleVersion, + FreightRpaSource, + ScheduleRun, + ScheduleTask, ShippingOrderField, - FreightRpaParsingProfile, - ShippingNoticeLine, ShippingNoticeLineOnhandMatch, - ShippingExcelTemplate, - 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.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.admin.freight_rpa_form_utils import iso as _iso 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 +from app.services.shipping_notice.routing_operators import ALLOWED_OPERATORS def _text(data: dict[str, Any], field: str, *, required: bool = False) -> str | None: + """读取并清洗字符串表单字段。""" value = str(data.get(field) or '').strip() if required and not value: raise ValidationError(f'{field} is required', code='VALIDATION.INVALID_PARAM', details={'field': field}) @@ -46,653 +40,13 @@ def _text(data: dict[str, Any], field: str, *, required: bool = False) -> str | def _bool(data: dict[str, Any], field: str, default: bool = True) -> bool: + """读取布尔表单字段。""" value = data.get(field, default) if not isinstance(value, bool): raise ValidationError(f'{field} must be a boolean', details={'field': field}) return value -def _json_object(data: dict[str, Any], field: str) -> dict[str, Any]: - """读取并复制对象型 JSON 配置。 - - Args: - data: 管理 API 的请求载荷。 - field: 只允许 JSON object 的字段名。 - - Returns: - dict[str, Any]: 空值规范化为空对象后的可写入配置。 - - Raises: - ValidationError: 字段不是 JSON object。 - """ - value = data.get(field, {}) - if not isinstance(value, dict): - raise ValidationError(f'{field} must be an object', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID') - return dict(value) - - -def _validate_profile_login_config(data: dict[str, Any]) -> dict[str, str]: - """校验连接级登录配置,不接收页面选择器或报表操作字段。""" - value = data.get('login_config_json', {}) - if not isinstance(value, dict) or set(value) - {'auth_mode'}: - raise ValidationError('login_config_json is invalid', code='SHIPPING.RPA_PROFILE_CONFIG_INVALID') - auth_mode = str(value.get('auth_mode') or 'password').strip().lower() - if auth_mode != 'password': - raise ValidationError( - 'Only password authentication is currently supported', - code='SHIPPING.RPA_PROFILE_CONFIG_INVALID', - ) - return {'auth_mode': auth_mode} - - -def _validate_report_path(connector_type: str, report_path: dict[str, Any]) -> dict[str, str]: - """校验 DBS 四级报表路径,防止技术选择器混入业务配置。""" - allowed = {'program_group', 'program_label', 'report_group', 'report_name'} - if set(report_path) - allowed: - raise ValidationError('report_path_json contains unsupported fields', code='SHIPPING.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.ONHAND_SOURCE_CONFIG_INVALID', details={'missing': sorted(missing)}, - ) - elif normalized: - raise ValidationError( - 'Only DBS inventory sources can define report_path_json', - code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID', - ) - return {key: normalized[key] for key in allowed if normalized.get(key)} - - -def _validate_query_parameters(data: dict[str, Any]) -> list[dict[str, Any]]: - """校验 Source 的可视化查询参数列表,禁止保存 selector 等 Driver 实现细节。""" - raw = data.get('query_parameters_json', []) - if not isinstance(raw, list): - raise ValidationError('query_parameters_json must be a list', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID') - result: list[dict[str, Any]] = [] - seen_names: set[str] = set() - allowed = {'name', 'mode', 'values', 'required', 'select_all', 'joiner'} - for index, item in enumerate(raw): - if not isinstance(item, dict) or set(item) - allowed: - raise ValidationError( - 'query parameter contains unsupported fields', - code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID', details={'index': index}, - ) - name = str(item.get('name') or '').strip() - mode = str(item.get('mode') or 'single').strip().lower() - values = item.get('values', []) - required = item.get('required', False) - select_all = item.get('select_all', False) - if not name or name.lower() in seen_names or mode not in {'single', 'multi_text', 'multi_select'}: - raise ValidationError('query parameter name or mode is invalid', code='SHIPPING.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.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.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.ONHAND_SOURCE_CONFIG_INVALID') - if select_all and mode != 'multi_select': - 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, - } - if mode == 'multi_text': - joiner = str(item.get('joiner') or ',').strip() - if not joiner: - 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: 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, - 'login_config_json': profile.login_config_json or {'auth_mode': 'password'}, 'enabled': bool(profile.enabled), - 'upload_config_json': profile.upload_config_json, - 'config_version': profile.config_version, 'username_masked': _mask(profile.username_ciphertext), - 'password_configured': bool(profile.password_ciphertext), 'credential_updated_at': _iso(profile.credential_updated_at), - 'created_at': _iso(profile.created_at), 'updated_at': _iso(profile.updated_at), - } - - -def _mask(ciphertext: str | None) -> str | None: - """凭据密文不支持反向展示;仅以配置状态提示管理员。""" - return 'configured' if ciphertext else None - - -def _iso(value: datetime | None) -> str | None: - return value.isoformat() if value else None - - -def list_profiles() -> list[dict[str, Any]]: - """列出 Profile 元数据,不返回可恢复的凭据。""" - return [_profile_payload(item) for item in FreightRpaProfile.query.order_by(FreightRpaProfile.profile_code).all()] - - -def delete_profile(profile_id: int) -> None: - """删除未绑定库存源的错误连接配置,保留已使用连接的可追溯性。""" - profile = db.session.get(FreightRpaProfile, profile_id) - if profile is None: - raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND') - 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() - - -def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]: - """创建或更新货代登录连接;密码留空表示保留既有密文。""" - 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 FreightRpaProfile(profile_code='', display_name='', connector_type='', login_url='', login_config_json={}) - # 记录“非 upload_config”的既有运行时配置快照:仅当这些字段变化才递增 config_version, - # upload_config_json 属于连接上传配置,变更不得误判库存 RPA 配置测试过期。 - prev_non_upload = ( - profile.profile_code, profile.display_name, profile.connector_type, profile.login_url, - dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled), - bool(profile.username_ciphertext), bool(profile.password_ciphertext), - ) if profile_id else None - profile.profile_code = str(_text(data, 'profile_code', required=True)).upper() - profile.display_name = str(_text(data, 'display_name', required=True)) - profile.connector_type = str(_text(data, 'connector_type', required=True)).lower() - profile.login_url = str(_text(data, 'login_url', required=True)) - profile.login_config_json = _validate_profile_login_config(data) - profile.enabled = _bool(data, 'enabled', bool(profile.enabled) if profile_id else True) - if not profile.enabled and any(source.enabled for source in profile.sources): - raise ConflictError( - 'Disable inventory sources before disabling their RPA Profile', - code='SHIPPING.RPA_PROFILE_DISABLE_BLOCKED', - ) - username = _text(data, 'username') - password = _text(data, 'password') - if username is not None: - profile.username_ciphertext = encrypt_credential(username) - if password is not None: - profile.password_ciphertext = encrypt_credential(password) - if username is not None or password is not None: - profile.credential_updated_at = datetime.utcnow() - # 连接级受控上传配置(受限 JSON);与库存 RPA 运行期配置隔离,不参与 config_version。 - if 'upload_config_json' in data: - profile.upload_config_json = validate_upload_config(profile.connector_type, data.get('upload_config_json')) - profile.updated_by = actor_id - if profile_id: - now_non_upload = ( - profile.profile_code, profile.display_name, profile.connector_type, profile.login_url, - dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled), - bool(profile.username_ciphertext), bool(profile.password_ciphertext), - ) - if now_non_upload != prev_non_upload: - profile.config_version += 1 - if not profile_id: - profile.created_by = actor_id - db.session.add(profile) - try: - db.session.commit() - except Exception as exc: - db.session.rollback() - raise ConflictError('RPA Profile code already exists', code='SHIPPING.RPA_PROFILE_CONFLICT') from exc - return _profile_payload(profile) - - -def _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, - 'excel_template_id': source.excel_template_id, - 'warehouse_resolution_mode': source.warehouse_resolution_mode, 'fixed_warehouse_id': source.fixed_warehouse_id, - '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: FreightRpaInboundReportConfig) -> dict[str, Any]: - """序列化独立收料配置,禁止把库存路径或凭据透传至管理端。""" - profile = config.parsing_profile - return { - 'id': config.id, 'source_id': config.source_id, - 'report_path_json': config.report_path_json or {}, - 'query_parameters_json': config.query_parameters_json or [], - # 入站解析绑定:供抽屉回显当前规则;摘要只取展示字段,不透传定义。 - 'parsing_profile_id': config.parsing_profile_id, - 'parsing_profile': ({ - 'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name, - 'version': profile.version, 'status': profile.status, - } if profile else None), - 'config_version': config.config_version, - 'created_at': _iso(config.created_at), 'updated_at': _iso(config.updated_at), - } - - -def _validate_inbound_profile_binding(profile_id: Any) -> int | None: - """校验收料配置绑定的入站解析规则:必须已发布且 purpose='inbound';空值表示解绑。 - - Args: - profile_id: 请求中的 parsing_profile_id;None/空串表示解绑。 - Returns: - 规整后的规则 id 或 None。 - Raises: - ValidationError: 规则不存在/未发布/用途不是 inbound(fail-closed,防误绑在手/出站规则)。 - """ - if profile_id is None or str(profile_id).strip() == '': - return None - 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', - code='SHIPPING.INBOUND_PROFILE_INVALID', - ) - return profile.id - - -def _validate_receipt_report_config( - source: FreightRpaSource, data: dict[str, Any], -) -> tuple[dict[str, str], list[dict[str, Any]]]: - """规范收料配置,与库存同构:路径+查询条件;日期禁填。 - - DBS 的 Warehouse 等查询条件均为可选报表筛选:空条件表示 Worker 使用页面默认; - 不作为排程是否产出执行单元的门禁(一源一单元)。 - """ - try: - parameters = _validate_query_parameters(data) - except ValidationError as exc: - raise ValidationError(str(exc), code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') from exc - # 报表日期不筛选,避免管理端误传日期使跨日排程导出产生漏数。 - if any('date' in str(item.get('name') or '').strip().lower() for item in parameters): - raise ValidationError('Receipt report date filtering is not supported', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') - raw_path = _json_object(data, 'report_path_json') - if source.connector_type == 'dbs': - try: - path = _validate_report_path('dbs', raw_path) - except ValidationError as exc: - raise ValidationError(str(exc), code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') from exc - # Warehouse 等条件可选;缺失/空值允许保存,运行期原样下发或走页面默认。 - return path, parameters - if source.connector_type == 'crane': - if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Inbound Details'): - raise ValidationError('Crane receipt report is fixed to Inbound Details', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') - if parameters: - raise ValidationError( - 'Crane receipt report does not support query parameters', - code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID', - ) - return {'report_name': 'Inbound Details'}, [] - raise ValidationError('Unsupported receipt connector type', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') - - -def get_receipt_report_config(source_id: int) -> dict[str, Any] | None: - """读取站点的收料配置;不存在时返回空,供抽屉初始化而非创建库存配置。""" - source = db.session.get(FreightRpaSource, source_id) - if source is 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(FreightRpaSource, source_id) - if source is None: - raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') - path, parameters = _validate_receipt_report_config(source, data) - 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 = FreightRpaInboundReportConfig(source_id=source.id) - config.created_by = actor_id - db.session.add(config) - else: - config.config_version += 1 - config.report_path_json = path - config.query_parameters_json = parameters - config.parsing_profile_id = _validate_inbound_profile_binding(data.get('parsing_profile_id')) - config.updated_by = actor_id - db.session.flush() - after = _receipt_report_config_payload(config) - append_shipping_audit_event( - 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={'source_id': source.id, 'connector_type': source.connector_type, - 'parsing_profile_id': config.parsing_profile_id}, - ) - db.session.commit() - return after - - -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': 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: FreightRpaSource, profile: FreightRpaParsingProfile) -> None: - """校验站点可直接采用的已发布方案与当前发货模板字段契约;启用中的站点同样允许更换解析绑定。""" - if profile.status != 'published': - 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.ONHAND_PARSING_PROFILE_REQUIRED') - template = source.excel_template - if template is None: - return - if template.status != 'published': - raise ValidationError('Published excel template is required', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED') - template_definition = template.definition_json if isinstance(template.definition_json, dict) else {} - template_mappings = template_definition.get('mappings') if isinstance(template_definition.get('mappings'), list) else [] - missing_fields = sorted({ - str(item.get('source_key') or '') - for item in template_mappings - if isinstance(item, dict) - and item.get('source_kind') == 'inventory_field' - and str(item.get('source_key') or '') not in mapping - }) - if missing_fields: - raise ValidationError( - 'Parsing profile does not provide all inventory fields required by the excel template', - code='SHIPPING.ONHAND_SOURCE_BINDING_TEMPLATE_INVALID', details={'inventory_field_ids': missing_fields}, - ) - - -def bind_source_parsing_profile( - source_ids: list[int], profile_id: int, *, actor_id: int | None, reason: str | None = None, operation: str, -) -> list[dict[str, Any]]: - """为一个或多个库存站点原子绑定已发布解析方案并写入追加式审计(含已启用站点)。 - - Args: - source_ids: 待绑定的库存站点主键,不能为空且不得重复。 - profile_id: 必须为已发布解析方案主键。 - actor_id: 当前管理员主键,仅写入审计。 - reason: 可选的补充说明;未填写时由系统记录本次直接或批量绑定动作。 - operation: 审计操作类型,仅允许 ``direct`` 或 ``bulk``。 - - Returns: - list[dict[str, Any]]: 已更新站点的管理端 DTO。 - - Raises: - ValidationError: 任一站点、方案或模板字段契约不合法;批量请求不会部分写入。 - ConflictError: 试图变更已启用站点的正式解析方案。 - """ - try: - normalized_ids = sorted({int(item) for item in source_ids if int(item) > 0}) - except (TypeError, ValueError) as exc: - raise ValidationError('source_ids must be a non-empty unique integer list', code='VALIDATION.INVALID_PARAM') from exc - if not normalized_ids or len(normalized_ids) != len(source_ids): - raise ValidationError('source_ids must be a non-empty unique integer list', code='VALIDATION.INVALID_PARAM') - if operation not in {'direct', 'bulk'}: - raise ValidationError('Binding operation is invalid', code='VALIDATION.INVALID_PARAM') - normalized_reason = str(reason or '').strip() - if len(normalized_reason) > 500: - raise ValidationError('Binding note must not exceed 500 characters', code='VALIDATION.INVALID_PARAM') - # 审计必须保留可读动作,但不应把技术审计字段变成管理员的额外填写负担。 - if not normalized_reason: - normalized_reason = '管理员直接绑定已发布解析方案' if operation == 'direct' else '管理员批量绑定已发布解析方案' - try: - 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(FreightRpaParsingProfile, normalized_profile_id) - if profile is None: - 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.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) - # 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(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), - )) - db.session.commit() - return [_source_payload(source) for source in typed_sources] - - -def get_source_parsing_binding_audits(source_id: int) -> list[dict[str, Any]]: - """读取库存站点解析绑定审计,仅返回配置快照和操作者标识。""" - 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, - 'source_config_version_before': row.source_config_version_before, - 'source_config_version_after': row.source_config_version_after, - 'before': row.before_snapshot_json, 'after': row.after_snapshot_json, - 'created_at': row.created_at.isoformat() if row.created_at else None, - } for row in rows] - - -def list_sources() -> list[dict[str, Any]]: - """列出库存源及其稳定业务配置。""" - 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(FreightRpaSource, source_id) - if source is None: - raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') - source_code = str(source.source_code or '').strip().upper() - 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 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(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} - for run in ScheduleRun.query.all() - for source_codes in [(run.api_request_json or {}).get('source_codes', [])] - if isinstance(source_codes, list) - ) - if has_mapping or has_snapshot or has_rule or has_task or has_export_run: - raise ConflictError('Inventory Source has operational references', code='SHIPPING.ONHAND_SOURCE_DELETE_BLOCKED') - db.session.delete(source) - db.session.commit() - - def _snapshot_payload(snapshot: FreightRpaOnhandReportFile) -> dict[str, Any]: """投影库存快照的管理端只读行,不暴露存储路径或库存明细。""" return { @@ -803,204 +157,6 @@ def list_export_records(*, limit: int = 100) -> list[dict[str, Any]]: return records[:max(1, min(limit, 200))] -def _template_validation_missing(source: FreightRpaSource) -> list[str]: - """确认发货模板引用的库存字段均由当前解析方案提供,避免启用后才发现字段断链。""" - template = source.excel_template - # 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 {} - mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else [] - profile_definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} - inventory_fields = {str(field_id) for field_id in (profile_definition.get('field_mapping') or {}).keys()} - invalid = any( - isinstance(item, dict) - and item.get('source_kind') == 'inventory_field' - and str(item.get('source_key') or '') not in inventory_fields - for item in mappings - ) - return ['template_validation'] if not mappings or invalid else [] - - -def _activation_check( - code: str, *, passed: bool, action: str, evidence: dict[str, Any], status: str | None = None, - blocking: bool | None = None, -) -> dict[str, Any]: - """构造单项启用门禁结果,确保管理端只展示服务端已判定的业务事实。""" - return { - 'code': code, - 'status': status or ('passed' if passed else 'pending'), - 'blocking': not passed if blocking is None else blocking, - 'action': action, - 'evidence': evidence, - } - - -def _source_activation_checks(source: FreightRpaSource) -> list[dict[str, Any]]: - """构建库存站点启用硬门槛:可用连接、已发布解析方案、已绑定已发布发货模板及字段契约。 - - 测试导出不再参与启用门禁;启停由管理员显式开关完成。 - """ - profile_ready = source.rpa_profile is not None and bool(source.rpa_profile.enabled) - # 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 [ - _activation_check( - 'rpa_profile', passed=profile_ready, action='configure_connection', - evidence={'profile_id': source.rpa_profile_id, 'enabled': profile_ready}, - ), - _activation_check( - 'parsing_profile', passed=parsing_ready, action='configure_parsing_profile', - 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', - evidence={'template_id': source.excel_template_id, 'published': template_ready}, - ), - _activation_check( - 'template_validation', passed=not template_invalid, - action='configure_excel_template', evidence={}, blocking=template_invalid, - ), - ] - - -def get_source_activation_status(source: FreightRpaSource) -> dict[str, Any]: - """返回库存站点启用硬门槛的结构化结果。 - - Args: - source: 已持久化的库存站点,关联配置由当前数据库事务提供。 - - Returns: - dict[str, Any]: ``checks`` 为前端唯一的检查真相;``ready`` 为启用结论; - ``missing_requirements`` 是由 checks 派生的紧凑摘要,供现有调用方读取。 - """ - checks = _source_activation_checks(source) - missing = [item['code'] for item in checks if item['blocking']] - return { - 'ready': not missing, - 'checks': checks, - 'missing_requirements': missing, - } - - -def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]: - """启用已满足硬门槛的库存站点;未通过任一前置条件时保持停用。""" - source = db.session.get(FreightRpaSource, source_id) - if source is None: - 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.ONHAND_SOURCE_ACTIVATION_BLOCKED', - details=status, - ) - source.enabled = True - source.updated_by = actor_id - db.session.commit() - return _source_payload(source) - - -def deactivate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]: - """停用库存站点,保留其解析方案和历史运行审计。""" - source = db.session.get(FreightRpaSource, source_id) - if source is None: - raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') - source.enabled = False - source.updated_by = actor_id - db.session.commit() - return _source_payload(source) - - -def save_source( - data: dict[str, Any], *, actor_id: int | None, source_id: int | None = None, - allow_enable_transition: bool = True, -) -> dict[str, Any]: - """保存库存站点基础配置;管理 API 不允许通过普通保存直接启用站点。 - - 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.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(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) - if not allow_enable_transition: - # 普通保存不承担状态切换:首次一律停用,已启用站点保留当前状态。 - enabled = bool(source.enabled) if source is not None else False - else: - enabled = requested_enabled - if enabled and not profile.enabled: - raise ValidationError( - 'Enabled Inventory Source requires an enabled RPA Profile', - code='SHIPPING.RPA_PROFILE_DISABLED', - ) - 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') - is_new = source is None - 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.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.snapshot_ttl_seconds = int(data.get('snapshot_ttl_seconds') or 86400) - source.enabled = enabled - source.updated_by = actor_id - if source_id: - source.config_version += 1 - if is_new: - source.created_by = actor_id - db.session.add(source) - # [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.ONHAND_SOURCE_INVALID') from exc - return _source_payload(source) - - 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, diff --git a/backend/app/services/freight_rpa/common/worker_heartbeat.py b/backend/app/services/freight_rpa/common/worker_heartbeat.py index bbcaa839..9c925a52 100644 --- a/backend/app/services/freight_rpa/common/worker_heartbeat.py +++ b/backend/app/services/freight_rpa/common/worker_heartbeat.py @@ -1,13 +1,14 @@ """ services/freight_rpa/common/worker_heartbeat.py -用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传/收料就绪检查与状态查询。 +用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传/入站/出站就绪检查与状态查询。 依赖:Flask current_app、redis_client、同包 rpa_runtime(mock 模式)、 freight_rpa.onhand.trigger_io(onhand trigger 目录)、 freight_rpa.upload.trigger_io(上传目录)、 - freight_rpa.inbound.trigger_io(inbound trigger 目录)。 -逻辑:Windows Worker 调 POST /api/freight-rpa/heartbeat;写 onhand/upload/inbound trigger 前强制就绪检查; - 管理端 /rpa-workers/status?scope=onhand|inbound 展示对应 Worker 心跳徽标。 + freight_rpa.inbound.trigger_io(inbound trigger 目录)、 + freight_rpa.outbound.trigger_io(outbound trigger 目录)。 +逻辑:Windows Worker 调 POST /api/freight-rpa/heartbeat;写 onhand/upload/inbound/outbound trigger 前强制就绪检查; + 管理端 /rpa-workers/status?scope=onhand|inbound|outbound 展示对应 Worker 心跳徽标。 """ from __future__ import annotations @@ -40,8 +41,11 @@ RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE = "货代上传 RPA 未就绪,请检查 W ONHAND_EXPORT_CAPABILITY = "onhand_export" FREIGHT_RPA_UPLOAD_CAPABILITY = "freight_rpa_upload" INBOUND_EXPORT_CAPABILITY = "inbound_export" +OUTBOUND_EXPORT_CAPABILITY = "outbound_export" # inbound Worker 由 start_inbound_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-inbound。 INBOUND_WORKER_ID_SUFFIX = "-inbound" +# outbound Worker 由 start_outbound_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-outbound。 +OUTBOUND_WORKER_ID_SUFFIX = "-outbound" _REDIS_INDEX_KEY = "shipping:rpa:heartbeat:index" _REDIS_WORKER_KEY_PREFIX = "shipping:rpa:heartbeat:worker:" _MEMORY_STORE: dict[str, dict[str, Any]] = {} @@ -59,6 +63,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_outbound_export_capability": "Worker 未声明 outbound_export 能力", "missing_freight_rpa_upload_capability": "Worker 未声明 freight_rpa_upload 能力", "credential_key_missing": "未配置 FREIGHT_RPA_CREDENTIAL_KEY", "upload_queue_dir_not_configured": "未配置货代上传队列目录", @@ -369,7 +374,7 @@ def _verify_shared_trigger_mount( trigger_dir: Path | None, *, require_sentinel: bool = True, ) -> tuple[bool, list[str]]: """ - 校验 trigger 目录可写;默认要求共享哨兵(库存与收料同口径)。 + 校验 trigger 目录可写;默认要求共享哨兵(库存与入站同口径)。 Args: trigger_dir: 共享 trigger 目录。 @@ -407,7 +412,7 @@ def _verify_shared_trigger_mount( return not reasons, reasons -def is_receipt_rpa_worker(worker: dict[str, Any]) -> bool: +def is_inbound_rpa_worker(worker: dict[str, Any]) -> bool: """ 判断心跳是否来自 inbound(原收料)Worker。 @@ -428,6 +433,27 @@ def is_receipt_rpa_worker(worker: dict[str, Any]) -> bool: return False +def is_outbound_rpa_worker(worker: dict[str, Any]) -> bool: + """ + 判断心跳是否来自 outbound Worker。 + + 优先认 <主机名>-outbound(ps1 注入);兼容未注入 FREIGHT_RPA_WORKER_ID、 + 回退为 <主机名>- 的进程——用心跳 trigger_dir 与 outbound 目录对齐判定。 + """ + if str(worker.get("worker_id") or "").strip().lower().endswith(OUTBOUND_WORKER_ID_SUFFIX): + return True + from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir + + expected = outbound_trigger_dir() + actual = str(worker.get("trigger_dir") or "").strip() + if expected is None or not actual: + return False + try: + return Path(actual).resolve() == expected.resolve() + except OSError: + return False + + def _worker_scope_matches(worker: dict[str, Any]) -> tuple[bool, list[str]]: expected_scope = shared_scope_id() if not expected_scope: @@ -454,7 +480,7 @@ def _worker_is_eligible( backend_env: 后端归一环境(dev/test/prod)。 ttl_seconds: 心跳 TTL。 now: 当前 epoch 秒。 - required_capability: 必选能力(onhand_export / inbound_export / freight_rpa_upload)。 + required_capability: 必选能力(onhand_export / inbound_export / outbound_export / freight_rpa_upload)。 Returns: (是否合格, 不合格原因列表)。 @@ -482,7 +508,7 @@ def _worker_is_eligible( def _missing_capability_reason(required_capability: str) -> str: - """按必选能力生成缺失原因码(onhand_export / inbound_export / freight_rpa_upload)。""" + """按必选能力生成缺失原因码(onhand_export / inbound_export / outbound_export / freight_rpa_upload)。""" return f"missing_{required_capability}_capability" @@ -521,8 +547,8 @@ def _check_rpa_worker_ready_for_capability( trigger_dir: 待校验的共享 trigger 目录。 required_capability: 必选 Worker 能力;空字符串表示不校验能力。 extra_reasons: 调用方预检附加原因(凭据/队列等)。 - worker_predicate: 可选过滤(如仅收料 Worker);不匹配的心跳不进入列表。 - require_sentinel: 是否要求共享哨兵(库存/收料同口径均 True)。 + worker_predicate: 可选过滤(如仅入站 Worker);不匹配的心跳不进入列表。 + require_sentinel: 是否要求共享哨兵(库存/入站同口径均 True)。 Returns: RpaWorkerReadiness。 @@ -637,9 +663,9 @@ def check_inventory_rpa_worker_ready() -> RpaWorkerReadiness: ) -def check_receipt_rpa_worker_ready() -> RpaWorkerReadiness: +def check_inbound_rpa_worker_ready() -> RpaWorkerReadiness: """ - 检查收料 RPA Worker 是否在线(管理端徽标 + 写 trigger 前 fail-fast)。 + 检查入站 RPA Worker 是否在线(管理端徽标 + 写 trigger 前 fail-fast)。 核心逻辑:仅看 inbound Worker 心跳(*-inbound 或 trigger_dir 对齐);要求 inbound_export 能力;校验 inbound trigger 目录可写;与 onhand 同口径要求共享哨兵。 @@ -649,24 +675,24 @@ def check_receipt_rpa_worker_ready() -> RpaWorkerReadiness: return _check_rpa_worker_ready_for_capability( trigger_dir=inbound_trigger_dir(), required_capability=INBOUND_EXPORT_CAPABILITY, - worker_predicate=is_receipt_rpa_worker, + worker_predicate=is_inbound_rpa_worker, require_sentinel=True, ) -def assert_receipt_rpa_worker_ready() -> None: +def assert_inbound_rpa_worker_ready() -> None: """ - 写收料 trigger 前的强制就绪检查。 + 写入站 trigger 前的强制就绪检查。 核心逻辑:镜像 assert_inventory_rpa_worker_ready;离线则抛 ServiceUnavailableError, - 排程不得进入 awaiting_receipt_rpa。 + 排程不得进入 awaiting_inbound_rpa。 Raises: ServiceUnavailableError: worker 未就绪、共享目录无效或心跳存储不可用。 """ from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir - result = check_receipt_rpa_worker_ready() + result = check_inbound_rpa_worker_ready() if result.ready: return code = 'RPA.WORKER_OFFLINE' @@ -691,6 +717,60 @@ def assert_receipt_rpa_worker_ready() -> None: ) +def check_outbound_rpa_worker_ready() -> RpaWorkerReadiness: + """ + 检查出站 RPA Worker 是否在线(写 trigger 前 fail-fast)。 + + 核心逻辑:仅看 outbound Worker 心跳(*-outbound 或 trigger_dir 对齐);要求 + outbound_export 能力;校验 outbound trigger 目录可写;与 onhand/inbound 同口径要求共享哨兵。 + """ + from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir + + return _check_rpa_worker_ready_for_capability( + trigger_dir=outbound_trigger_dir(), + required_capability=OUTBOUND_EXPORT_CAPABILITY, + worker_predicate=is_outbound_rpa_worker, + require_sentinel=True, + ) + + +def assert_outbound_rpa_worker_ready() -> None: + """ + 写出站 trigger 前的强制就绪检查。 + + 核心逻辑:镜像 assert_inbound_rpa_worker_ready;离线则抛 ServiceUnavailableError, + 排程不得进入 awaiting_outbound_rpa_callback。 + + Raises: + ServiceUnavailableError: worker 未就绪、共享目录无效或心跳存储不可用。 + """ + from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir + + result = check_outbound_rpa_worker_ready() + if result.ready: + return + code = 'RPA.WORKER_OFFLINE' + if 'heartbeat_storage_unavailable' in result.reasons: + code = 'RPA.HEARTBEAT_STORAGE_UNAVAILABLE' + logger.warning( + '[rpa-heartbeat] outbound readiness blocked code=%s reasons=%s detail=%s', + code, + result.reasons, + result.detail_message, + ) + raise ServiceUnavailableError( + result.message, + code=code, + details={ + 'reasons': result.reasons, + 'detail_message': result.detail_message, + 'checked_at': result.checked_at, + 'shared_scope_id': shared_scope_id(), + 'trigger_dir': str(outbound_trigger_dir() or ''), + }, + ) + + def _freight_upload_config_reasons() -> list[str]: """ 预检货代上传静态配置:凭据主密钥、上传队列目录、回调 API 基址。 @@ -852,19 +932,23 @@ def assert_inventory_rpa_worker_ready() -> None: def serialize_rpa_worker_status(*, scope: str = "onhand") -> dict[str, Any]: """ - 管理端展示:按 scope 返回在手(onhand)或入站(inbound)Worker 心跳摘要。 + 管理端展示:按 scope 返回在手(onhand)、入站(inbound)或出站(outbound)Worker 心跳摘要。 Args: - scope: onhand(默认,库存 RPA 工作台)或 inbound(入站 RPA 工作台); - 取值为后端内部与前端查询参数约定,与 Worker 上报能力标识(Task 12)无关。 + scope: onhand(默认,库存 RPA 工作台)、inbound(入站)或 outbound(出站); + 取值为后端内部与前端查询参数约定,与 Worker 上报能力标识无关。 """ from app.services.freight_rpa.upload.trigger_io import upload_trigger_dir from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir + from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir normalized = str(scope or "onhand").strip().lower() if normalized == "inbound": - readiness = check_receipt_rpa_worker_ready() + readiness = check_inbound_rpa_worker_ready() trigger_path = str(inbound_trigger_dir() or "") + elif normalized == "outbound": + readiness = check_outbound_rpa_worker_ready() + trigger_path = str(outbound_trigger_dir() or "") else: readiness = check_inventory_rpa_worker_ready() trigger_path = str(onhand_trigger_dir() or "") diff --git a/backend/app/services/freight_rpa/inbound/report_archive.py b/backend/app/services/freight_rpa/inbound/report_archive.py index 423ea62e..40761cd6 100644 --- a/backend/app/services/freight_rpa/inbound/report_archive.py +++ b/backend/app/services/freight_rpa/inbound/report_archive.py @@ -2,19 +2,16 @@ services/freight_rpa/inbound/report_archive.py 用途:inbound(入站,原收料)RPA 产物事实能力——Worker 回调的原样归档(xlsx 落 MinIO、 - 三年保留期、不写库存快照表)、到期对象清理(retention)、单文件企微投递与管理员 - 强制重发(resend)。批次 R Task 10 自 shipping_notice.receipt_report_storage / - 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 根)、 + 三年保留期、不写库存快照表)与到期对象清理(retention)。per-file 企微投递与 resend + 已拆除(Task 2);排程终态通知仍走 freight_rpa_inbound_finalize 统一出口。 +依赖:models(FreightRpaInboundReportFile / FreightRpaInboundUnitRun、ScheduleRun 经行对象访问)、 + file_assets.storage、freight_rpa.inbound.trigger_io(回调 SCHEMA 与 drop 根)、 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 完成原样归档, + (in_transit_transfer.rpa_sinks.register_inbound_sinks)调 ingest_inbound_callback 完成原样归档, empty/success/failed 三个终态分支各自「先 db.session.commit() 再投递事实」—— commit 后构造 ReportFact(report_kind='inbound', ...) 调 dispatch_report_fact; 处理函数异常原样外抛(不吞、不回滚已提交终态),kind 未注册时 404 @@ -36,19 +33,14 @@ from flask import current_app from app import db from app.core.errors import NotFoundError, ValidationError from app.models import ( - 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 - - def _read_inbound_callback_file(file_path: str) -> bytes: """只读取 inbound 专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。 @@ -59,7 +51,7 @@ def _read_inbound_callback_file(file_path: str) -> bytes: """ configured_root = str(inbound_drop_dir() or '').strip() if not configured_root: - raise ValidationError('receipt callback file root is unavailable', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID') + raise ValidationError('inbound callback file root is unavailable', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID') root = Path(configured_root).resolve() # 容忍历史载荷携带 Windows 绝对路径:先归一分隔符再取末段文件名(防遍历,单一分段)。 name = Path(str(file_path).replace('\\', '/')).name @@ -67,12 +59,12 @@ def _read_inbound_callback_file(file_path: str) -> bytes: try: path.relative_to(root) except ValueError as exc: - raise ValidationError('receipt callback file is outside receipt drop root', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID') from exc + raise ValidationError('inbound callback file is outside inbound drop root', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID') from exc if path.suffix.lower() != '.xlsx' or not path.is_file(): - raise ValidationError('receipt callback file must be an existing xlsx', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID') + raise ValidationError('inbound callback file must be an existing xlsx', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID') max_size = max(int(current_app.config.get('FILE_ASSET_MAX_SIZE_MB', 30) or 30), 1) * 1024 * 1024 if path.stat().st_size > max_size: - raise ValidationError('receipt callback file exceeds configured size limit', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID') + raise ValidationError('inbound callback file exceeds configured size limit', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID') return path.read_bytes() @@ -96,23 +88,23 @@ def ingest_inbound_callback(payload: dict[str, Any]) -> dict[str, Any]: (供处理函数重试)。落 MinIO / 插行失败时事务回滚,同样不投递。 """ if payload.get('schema_version') != INBOUND_TRIGGER_SCHEMA: - raise ValidationError('receipt callback schema_version is invalid', code='SHIPPING.RECEIPT_CALLBACK_INVALID') + raise ValidationError('inbound callback schema_version is invalid', code='SHIPPING.INBOUND_CALLBACK_INVALID') callback_id = str(payload.get('callback_id') or '').strip() 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') + raise NotFoundError('Inbound RPA unit not found', code='SHIPPING.INBOUND_UNIT_NOT_FOUND') status = str(payload.get('status') or '').strip().lower() before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message} if status in {'empty', 'no_data'}: - # [STEP] 与库存 no_inventory_data 对齐:empty 是合法业务结果,落 error_code=no_receipt_data。 + # [STEP] 与库存 no_inventory_data 对齐:empty 是合法业务结果,落 error_code=no_inbound_data。 unit.status = 'empty' - 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.error_code = str(payload.get('error_code') or 'no_inbound_data')[:64] + unit.error_message = str(payload.get('error_message') or 'no_inbound_data')[:2000] unit.finished_at = datetime.utcnow() 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', + actor_type='rpa', actor_id='inbound-worker', unit_id=unit.id, result='success', before=before, after={ 'status': 'empty', @@ -127,17 +119,17 @@ def ingest_inbound_callback(payload: dict[str, Any]) -> dict[str, Any]: db.session.commit() 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', + error_code=unit.error_code or 'no_inbound_data', + error_message=unit.error_message or 'no_inbound_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() + unit.status = 'failed'; unit.error_code = str(payload.get('error_code') or 'RPA.INBOUND_EXPORT_FAILED')[:64]; unit.error_message = str(payload.get('error_message') or 'inbound export failed')[:2000]; unit.finished_at = datetime.utcnow() 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', + actor_type='rpa', actor_id='inbound-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}, ) @@ -154,7 +146,7 @@ def ingest_inbound_callback(payload: dict[str, Any]) -> dict[str, Any]: 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') + raise ValidationError('inbound callback sha256 mismatch', code='SHIPPING.INBOUND_CALLBACK_SHA_MISMATCH') existing = FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id, sha256=sha256).one_or_none() if existing: # [STEP] 幂等重放:不插第二行,仍投递 ok=True 事实(同一 file_id),供处理函数重试; @@ -171,7 +163,7 @@ def ingest_inbound_callback(payload: dict[str, Any]) -> dict[str, Any]: db.session.add(record) unit.status = 'success'; unit.finished_at = datetime.utcnow() db.session.flush() - 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}) + 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='inbound-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': 'inbound_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() @@ -210,7 +202,7 @@ def run_freight_rpa_inbound_retention_schedule(task: Any, run: Any) -> tuple[int 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'}, - artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], + artifact_refs=[{'kind': 'inbound_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], ) success += 1 except Exception as exc: @@ -220,88 +212,8 @@ def run_freight_rpa_inbound_retention_schedule(task: Any, run: Any) -> tuple[int 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]}, - artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], + artifact_refs=[{'kind': 'inbound_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], ) failed += 1 db.session.commit() - 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: FreightRpaInboundReportFile) -> list[int]: - """从所属排程冻结的接收人列表取目标用户;停用通知时返回空。""" - run = report_file.unit_run.schedule_run - task = run.task if run else None - if task is None or not task.notify_enabled: - return [] - return sorted({int(user_id) for user_id in (task.notify_user_ids_json or []) if str(user_id).isdigit()}) - - -def deliver_inbound_file(file_id: int, *, force: bool = False) -> dict: - """向排程接收人逐一投递原样收料文件;同文件用户的成功投递可幂等重放。 - - Args: - file_id: 已归档收料文件主键(FreightRpaInboundReportFile.id)。 - force: 管理员补偿重发(resend 端点传 True),绕过成功幂等但仍受通知开关约束。 - Returns: - dict: success_count / failed_count(file_not_found 时附 reason)。 - """ - 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 = 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 = 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', - ) - db.session.add(delivery) - db.session.flush() - user = db.session.get(User, user_id) - 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_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'}, - after={'delivery_status': delivery.status, 'error_code': delivery.error_code}, - artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], - metadata={'delivery_id': delivery.id, 'message_type': 'file'}, - ) - continue - try: - media_id = upload_wecom_temp_media(file_asset_storage.get_bytes(report_file.storage_key), report_file.original_filename) - result = send_wecom_file_message(user.wecom_userid, media_id) - if int(result.get('errcode', -1)) != 0: - raise RuntimeError(str(result.get('errmsg') or result.get('errcode'))) - 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_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}], - metadata={'delivery_id': delivery.id, 'message_type': 'file'}, - ) - except Exception as exc: - delivery.status = 'failed'; delivery.error_code = 'WECOM_SEND_FAILED'; delivery.error_message = str(exc)[:2000] - failed_count += 1 - 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'}, - after={'delivery_status': delivery.status, 'error_code': delivery.error_code, 'error_message': delivery.error_message}, - artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], - metadata={'delivery_id': delivery.id, 'message_type': 'file'}, - ) - db.session.commit() - return {'success_count': success_count, 'failed_count': failed_count} + return len(rows), success, failed, 0, [{'file_id': row.id} for row in rows], errors, [{'step': 'inbound_retention', 'status': 'completed'}] diff --git a/backend/app/services/freight_rpa/outbound/__init__.py b/backend/app/services/freight_rpa/outbound/__init__.py new file mode 100644 index 00000000..ccddbc5a --- /dev/null +++ b/backend/app/services/freight_rpa/outbound/__init__.py @@ -0,0 +1 @@ +"""outbound:出站 RPA。""" diff --git a/backend/app/services/freight_rpa/outbound/report_archive.py b/backend/app/services/freight_rpa/outbound/report_archive.py new file mode 100644 index 00000000..59746f44 --- /dev/null +++ b/backend/app/services/freight_rpa/outbound/report_archive.py @@ -0,0 +1,246 @@ +""" +services/freight_rpa/outbound/report_archive.py + +用途:outbound(出站)RPA 产物事实能力——Worker 回调的原样归档(xlsx 落 MinIO、 + 三年保留期、不写库存快照表)。 +依赖:models(FreightRpaOutboundReportFile / FreightRpaOutboundUnitRun)、 + file_assets.storage、freight_rpa.outbound.trigger_io(回调 SCHEMA 与 drop 根)、 + freight_rpa.common.report_audit(本域唯一审计写入口)、 + freight_rpa.reports.facts / reports.dispatch(ReportFact 事实投递)。 +逻辑:Worker 回调进入 /api/freight-rpa/outbound-batch-ready 后由组合根(Task 10) + 或测内临时 register 的 sink 调 ingest_outbound_callback 完成原样归档; + empty/success/failed 三个终态分支各自「先 db.session.commit() 再投递事实」—— + commit 后构造 ReportFact(report_kind='outbound', ...) 调 dispatch_report_fact; + 处理函数异常原样外抛(不吞、不回滚已提交终态);同一 unit_run_id + sha256 + 已有文件时不插第二行、仍投递 ok=True 的事实供处理函数重试。 + 跨机路径:file_path 只认 outbound drop 根内文件名,禁止把 Worker Windows + 绝对路径当 Linux 路径打开(对照 inbound._read_inbound_callback_file)。 + 本模块不 import shipping_notice / in_transit_transfer,不移植入站逐文件企微投递。 +""" + +from __future__ import annotations + +import hashlib +from datetime import datetime, timedelta +from pathlib import Path +from typing import Any + +from flask import current_app + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import ( + FreightRpaOutboundReportFile, + FreightRpaOutboundUnitRun, +) +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.outbound.trigger_io import SCHEMA as OUTBOUND_TRIGGER_SCHEMA, outbound_drop_dir +from app.services.freight_rpa.reports.dispatch import dispatch_report_fact +from app.services.freight_rpa.reports.facts import ReportFact + + +def _read_outbound_callback_file(file_path: str) -> bytes: + """只读取 outbound 专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。 + + 路径契约为「drop 根内文件名」:Worker(Windows RPA 主机)与后端(Linux 容器)分属 + 两机,各自看到的根路径不同(C:\\HxopsRpaTest\\... vs /mnt/hxops-rpa-*-data/...)。 + 一律 replace('\\','/') 后取 .name,再拼本机 FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR, + relative_to(root) 防穿越。禁止把回调串当 Linux 路径直接 open。 + """ + configured_root = str(outbound_drop_dir() or "").strip() + if not configured_root: + raise ValidationError( + "outbound callback file root is unavailable", + code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID", + ) + root = Path(configured_root).resolve() + # [STEP] 跨机:先归一分隔符再取末段文件名,绝不 Path(file_path).read_bytes()。 + name = Path(str(file_path).replace("\\", "/")).name + path = (root / name).resolve() + try: + path.relative_to(root) + except ValueError as exc: + raise ValidationError( + "outbound callback file is outside outbound drop root", + code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID", + ) from exc + if path.suffix.lower() != ".xlsx" or not path.is_file(): + raise ValidationError( + "outbound callback file must be an existing xlsx", + code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID", + ) + max_size = max(int(current_app.config.get("FILE_ASSET_MAX_SIZE_MB", 30) or 30), 1) * 1024 * 1024 + if path.stat().st_size > max_size: + raise ValidationError( + "outbound callback file exceeds configured size limit", + code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID", + ) + return path.read_bytes() + + +def ingest_outbound_callback(payload: dict[str, Any]) -> dict[str, Any]: + """幂等接收单个 outbound 单元回调,原样归档三年且不写库存快照表。 + + Args: + payload: Worker 回调载荷(schema_version/callback_id/status/file_path/...)。 + Returns: + dict: unit_run_id/status[/file_id/idempotent],供 HTTP envelope 的 data 使用。 + (brief 曾写 -> None;与入站 API envelope 对齐仍返回 dict。) + Raises: + ValidationError: 载荷非法(schema/callback_id/sha256/文件路径)——commit 之前抛出,不投递事实。 + NotFoundError: callback_id 无匹配单元——commit 之前抛出,不投递事实。 + AppError: 终态已 commit 后 kind 未注册处理函数(FREIGHT_RPA.SINK_NOT_REGISTERED, 404)。 + 业务顺序:每个终态分支先 db.session.commit() 再构造 + ReportFact(report_kind='outbound', source_code=unit.source_code, ...) 调 + dispatch_report_fact;事实恒带 unit_run_id=unit.id;处理函数异常原样外抛; + 同一 unit_run_id + sha256 已有文件时不插第二行,仍投递 ok=True 的事实。 + """ + if payload.get("schema_version") != OUTBOUND_TRIGGER_SCHEMA: + raise ValidationError( + "outbound callback schema_version is invalid", + code="SHIPPING.OUTBOUND_CALLBACK_INVALID", + ) + callback_id = str(payload.get("callback_id") or "").strip() + unit = FreightRpaOutboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none() + if unit is None: + raise NotFoundError("Outbound RPA unit not found", code="SHIPPING.OUTBOUND_UNIT_NOT_FOUND") + status = str(payload.get("status") or "").strip().lower() + before = {"status": unit.status, "error_code": unit.error_code, "error_message": unit.error_message} + if status in {"empty", "no_data"}: + # [STEP] 与入站 empty / 库存 no_inventory_data 对齐:empty 是合法业务结果。 + unit.status = "empty" + unit.error_code = str(payload.get("error_code") or "no_outbound_data")[:64] + unit.error_message = str(payload.get("error_message") or "no_outbound_data")[:2000] + unit.finished_at = datetime.utcnow() + append_rpa_report_event( + event_type="shipping_outbound_rpa_callback_received", + aggregate_type="shipping_outbound_unit", + aggregate_id=str(unit.id), + run_no=unit.schedule_run.run_no if unit.schedule_run else None, + actor_type="rpa", + actor_id="outbound-worker", + unit_id=unit.id, + result="success", + before=before, + after={ + "status": "empty", + "callback_id": unit.callback_id, + "error_code": unit.error_code, + "error_message": unit.error_message, + }, + metadata={"callback_status": status, "skip_reason": unit.error_code}, + ) + db.session.commit() + dispatch_report_fact(ReportFact( + report_kind="outbound", + source_code=unit.source_code, + file_id=None, + sha256=None, + ok=False, + error_code=unit.error_code or "no_outbound_data", + error_message=unit.error_message or "no_outbound_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.OUTBOUND_EXPORT_FAILED")[:64] + unit.error_message = str(payload.get("error_message") or "outbound export failed")[:2000] + unit.finished_at = datetime.utcnow() + append_rpa_report_event( + event_type="shipping_outbound_rpa_callback_received", + aggregate_type="shipping_outbound_unit", + aggregate_id=str(unit.id), + run_no=unit.schedule_run.run_no if unit.schedule_run else None, + actor_type="rpa", + actor_id="outbound-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}, + ) + db.session.commit() + dispatch_report_fact(ReportFact( + report_kind="outbound", + 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_outbound_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( + "outbound callback sha256 mismatch", + code="SHIPPING.OUTBOUND_CALLBACK_SHA_MISMATCH", + ) + existing = FreightRpaOutboundReportFile.query.filter_by(unit_run_id=unit.id, sha256=sha256).one_or_none() + if existing: + dispatch_report_fact(ReportFact( + report_kind="outbound", + 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 "outbound.xlsx")).name + storage_key = f"shipping/outbound-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 = FreightRpaOutboundReportFile( + 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_rpa_report_event( + event_type="shipping_outbound_report_archived", + aggregate_type="shipping_outbound_unit", + aggregate_id=str(unit.id), + run_no=unit.schedule_run.run_no if unit.schedule_run else None, + actor_type="rpa", + actor_id="outbound-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": "outbound_report", "id": str(record.id), "sha256": sha256}], + metadata={"file_size": len(data), "retention_days": 365 * 3}, + ) + db.session.commit() + dispatch_report_fact(ReportFact( + report_kind="outbound", + 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} diff --git a/backend/app/services/freight_rpa/outbound/trigger_io.py b/backend/app/services/freight_rpa/outbound/trigger_io.py new file mode 100644 index 00000000..bab76679 --- /dev/null +++ b/backend/app/services/freight_rpa/outbound/trigger_io.py @@ -0,0 +1,92 @@ +""" +services/freight_rpa/outbound/trigger_io.py + +用途:outbound(出站)RPA 的纯文件 IO——trigger/落盘目录解析、批量 trigger JSON + 原子写入,以及 Worker 触发/回调契约常量(SCHEMA/ACTION_*)。 +依赖:Flask current_app 配置、Path/JSON/文件系统工具;不 import 任何业务编排模块 + (import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。 +逻辑:由 schedule.freight_rpa_outbound_job(排程写 trigger)、api.schedule.runs(admin 单元重试)、 + in_transit_transfer.outbound_trigger_service(调拨按需/批量触发)、 + freight_rpa.common.worker_heartbeat(outbound trigger 目录探测/就绪检查)、 + freight_rpa.outbound.report_archive(drop 目录定位与回调 SCHEMA 校验,后续任务)等调用, + 与外部 RPA Worker 的文件投递目录交互;schema/action 以本文件常量为单一真相 + (Worker 侧对表:freight_rpa.outbound.v1 / outbound_export_batch)。 +""" + +from __future__ import annotations + +import json +import os +from datetime import datetime +from pathlib import Path +from typing import Any + +from flask import current_app + +# Worker 触发/回调契约常量:后端写入侧与校验侧共用单一真相,禁止再写字面量。 +SCHEMA = "freight_rpa.outbound.v1" +ACTION_OUTBOUND_EXPORT_BATCH = "outbound_export_batch" + + +def _path(key: str) -> Path | None: + value = str(current_app.config.get(key) or "").strip() + if not value: + return None + return Path(value) + + +def outbound_trigger_dir() -> Path | None: + """RPA outbound 批量导出触发 JSON 目录(FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR); + 绝不回落到 onhand/inbound trigger 目录。""" + return _path("FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR") + + +def outbound_drop_dir() -> Path | None: + """RPA outbound 导出文件落盘目录(FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR)。""" + return _path("FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR") + + +def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None: + """原子发布 trigger,避免 Worker 读取到写入中的半截 JSON。""" + temp_path = path.with_name(f'.{path.name}.{os.getpid()}.tmp') + try: + with open(temp_path, 'w', encoding='utf-8') as handle: + json.dump(body, handle, ensure_ascii=False, indent=2) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temp_path, path) + finally: + if temp_path.exists(): + temp_path.unlink(missing_ok=True) + + +def write_outbound_export_batch_trigger( + run_no: str, + units: list[dict[str, Any]], + meta: dict[str, Any] | None = None, +) -> str | None: + """ + 写入 outbound 批量 trigger 文件 outbound_export_batch_{run_no}.json + (Worker 轮询 /*.json 按内容消费,schema/action 取本文件常量)。 + + Args: + run_no: 批次运行号;进 body.batch_run_no 并参与文件名(安全化仅保留字母数字-_)。 + units: 触发单元载荷列表;业务约束——空列表直接返回 None(无单元不落盘)。 + meta: 调用方附加字段,合并覆盖 body 顶层键(schema_version/action 缺省取常量)。 + + Returns: + str | None: 触发文件绝对路径;目录未配置或 units 为空时返回 None。 + """ + trigger_dir = outbound_trigger_dir() + if not trigger_dir or not units: + return None + trigger_dir.mkdir(parents=True, exist_ok=True) + safe_run_no = ''.join(char for char in run_no if char.isalnum() or char in {'-', '_'}) or 'outbound' + body = { + 'schema_version': SCHEMA, 'action': ACTION_OUTBOUND_EXPORT_BATCH, + 'batch_run_no': run_no, 'requested_at': datetime.utcnow().isoformat(), 'units': units, + **(meta or {}), + } + path = trigger_dir / f'outbound_export_batch_{safe_run_no}.json' + _write_trigger_json_atomic(path, body) + return str(path) diff --git a/backend/app/services/shipping_notice/onhand_parsing_profile.py b/backend/app/services/freight_rpa/parsing_profile.py similarity index 90% rename from backend/app/services/shipping_notice/onhand_parsing_profile.py rename to backend/app/services/freight_rpa/parsing_profile.py index a800e462..3dc38ab6 100644 --- a/backend/app/services/shipping_notice/onhand_parsing_profile.py +++ b/backend/app/services/freight_rpa/parsing_profile.py @@ -1,9 +1,16 @@ """ -backend/app/services/shipping_notice/onhand_parsing_profile.py +services/freight_rpa/parsing_profile.py -用途:管理可跨库存源复用的版本化库存解析 Profile,并为运行期提供确定性解析定义。 -依赖:FreightRpaParsingProfile、FreightRpaOnhandReportConfig(s18 起站点绑定归配置行)、FreightRpaInboundReportConfig、ShippingOrderField、onhand_mapping。 -逻辑:管理员保存草稿并发布不可变版本;库存源仅绑定 published Profile,解析链直接使用定义中的列映射与订单字段匹配键。 +用途:管理货代「报表规则」(FreightRpaParsingProfile)的草稿/发布与运行期定义读取。 + purpose=onhand 走库存字段目录 + match_keys;purpose=inbound/outbound 走调拨 + MOVEMENT_FIELDS 契约(与在途异动对齐)。 +依赖:FreightRpaParsingProfile、FreightRpaOnhandReportConfig、FreightRpaInboundReportConfig、 + FreightRpaOutboundReportConfig、ShippingOrderField、 + in_transit_transfer.movement_contract.MOVEMENT_FIELDS、 + shipping_notice.order_schema(仅 onhand 发布时校验订单字段)。 +逻辑:管理员保存草稿并发布不可变版本;来源站点 / 入站·出站报表配置只绑定 published + Profile;退役前检查 onhand/inbound/outbound 配置引用。管理端入口 + /api/admin/freight-rpa/.../parsing-profiles。 """ from __future__ import annotations @@ -24,6 +31,7 @@ from app.models import ( FreightRpaOnhandStructureAnalysis, ShippingOrderField, FreightRpaInboundReportConfig, + FreightRpaOutboundReportConfig, ) @@ -59,7 +67,7 @@ def _required_catalog_field_ids(fields: dict[str, FreightRpaOnhandField]) -> set # 入站(inbound)用途的定死字段端点与必需字段集(领域定死,不依赖库存字段目录)。 def _required_movement_field_ids(definition: dict[str, Any]) -> set[str]: - """校验 inbound 用途的解析定义只引用定死领域字段,且必需字段齐全。""" + """校验 inbound/outbound 用途的解析定义只引用定死领域字段,且必需字段齐全。""" from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS movement_codes = {field.code for field in MOVEMENT_FIELDS} @@ -85,8 +93,8 @@ def _validate_definition(raw: Any, *, purpose: str = 'onhand') -> dict[str, Any] Args: raw: 解析定义对象。 - purpose: 'onhand'/'outbound'(沿用库存字段目录与 match_keys)或 - 'inbound'(端点用定死 MOVEMENT_FIELDS,无 match_keys)。 + purpose: 'onhand'(库存字段目录 + match_keys)或 + 'inbound'/'outbound'(端点用定死 MOVEMENT_FIELDS,无 match_keys)。 """ if not isinstance(raw, dict): raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') @@ -99,7 +107,7 @@ def _validate_definition(raw: Any, *, purpose: str = 'onhand') -> dict[str, Any] 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.ONHAND_PARSING_PROFILE_INVALID') - if purpose == 'inbound': + if purpose in {'inbound', 'outbound'}: _required_movement_field_ids(raw) return { 'sheet_name': str(raw.get('sheet_name') or '').strip() or None, @@ -290,13 +298,13 @@ def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]: ) from app.services.shipping_notice.order_schema import service as order_schema_service - # inbound 用途无订单匹配键(端点为定死异动字段),跳过订单 Schema 契约校验;onhand/outbound 维持原约束。 + # inbound/outbound 无订单匹配键(端点为定死异动字段),跳过订单 Schema 契约校验;onhand 维持原约束。 referenced_field_ids = { str(item.get('order_field_id') or '') for item in (profile.definition_json or {}).get('match_keys', []) if isinstance(item, dict) } - if profile.purpose != 'inbound': + if profile.purpose == 'onhand': published_field_ids = { str(item.get('field_id') or '') for item in order_schema_service.get_published_contract().get('fields', []) @@ -316,7 +324,7 @@ def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]: def retire(profile_id: int) -> dict[str, Any]: - """退役无库存源/收料报表配置引用的 published Profile,避免使现有绑定静默失效。""" + """退役无库存源/入站/出站报表配置引用的 published Profile,避免使现有绑定静默失效。""" profile = db.session.get(FreightRpaParsingProfile, profile_id) if profile is None: raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND') @@ -324,10 +332,11 @@ def retire(profile_id: int) -> dict[str, Any]: 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 = FreightRpaInboundReportConfig.query.filter_by(parsing_profile_id=profile.id).count() - if bound_sources or bound_receipt_configs: + # 入站/出站报表配置同样绑定解析 Profile:退役前必须一并核查, + # 否则入站/出站文件解析链会静默失去规则。 + bound_inbound_configs = FreightRpaInboundReportConfig.query.filter_by(parsing_profile_id=profile.id).count() + bound_outbound_configs = FreightRpaOutboundReportConfig.query.filter_by(parsing_profile_id=profile.id).count() + if bound_sources or bound_inbound_configs or bound_outbound_configs: raise ConflictError('Rebind inventory sources before retiring profile', code='SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED') profile.status = 'retired' db.session.commit() diff --git a/backend/app/services/freight_rpa/reports/__init__.py b/backend/app/services/freight_rpa/reports/__init__.py index 11e0c747..d08ec315 100644 --- a/backend/app/services/freight_rpa/reports/__init__.py +++ b/backend/app/services/freight_rpa/reports/__init__.py @@ -1,7 +1,7 @@ """freight_rpa/reports/__init__.py -用途:报表读域(阶段 B Task 3)——发货(shipping_notice 域)与在途调拨 - (in_transit_transfer 域)读取货代 RPA 报表事实的唯一入口包。 +用途:报表读域——发货(shipping_notice 域)与在途调拨 + (in_transit_transfer 域)读取货代 RPA 报表事实的唯一入口包(含出站配置视图)。 依赖:facts(报表事实与 report kind 白名单)、queries(只读查询与解析失败标记)。 逻辑:仅做门面转发;调用方(后续 in_transit_transfer / shipping_notice) 一律 import 本包,禁止绕过直接引用 freight_rpa 模型表。 @@ -15,12 +15,15 @@ from app.services.freight_rpa.reports.queries import ( InboundConfigView, InboundFileView, OnhandConfigView, + OutboundConfigView, SiteView, clear_inbound_parse_failure, get_inbound_config, get_onhand_config, + get_outbound_config, get_site, latest_usable_inbound_file, + list_outbound_configured_source_codes, mark_inbound_parse_failure, read_inbound_file_bytes, usable_inbound_file_condition, @@ -31,13 +34,16 @@ __all__ = [ 'InboundConfigView', 'InboundFileView', 'OnhandConfigView', + 'OutboundConfigView', 'ReportFact', 'SiteView', 'clear_inbound_parse_failure', 'get_inbound_config', 'get_onhand_config', + 'get_outbound_config', 'get_site', 'latest_usable_inbound_file', + 'list_outbound_configured_source_codes', 'mark_inbound_parse_failure', 'read_inbound_file_bytes', 'require_report_kind', diff --git a/backend/app/services/freight_rpa/reports/dispatch.py b/backend/app/services/freight_rpa/reports/dispatch.py index a1530856..666712c5 100644 --- a/backend/app/services/freight_rpa/reports/dispatch.py +++ b/backend/app/services/freight_rpa/reports/dispatch.py @@ -4,8 +4,9 @@ 终态、再投递事实」的第二段分发(批次 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 注入各 +逻辑:组合根(shipping_notice.rpa_sinks.register_onhand_sinks / + in_transit_transfer.rpa_sinks.register_inbound_sinks / + register_outbound_sinks)在应用启动时调用 register_report_handler 注入各 kind 的业务处理函数;归档入口(如 freight_rpa.inbound.report_archive. ingest_inbound_callback)在每个终态 db.session.commit() 之后调用 dispatch_report_fact。kind 未注册时显式 404(FREIGHT_RPA. @@ -33,8 +34,8 @@ def register_report_handler(report_kind: str, handler: Handler) -> None: """ 注册一个报表事实处理函数(由组合根在应用启动时调用)。 - 【AI 触发时机】:组合根装配(Task 7 的 register_inbound_sinks / - register_onhand_sinks)时调用;测试直接调用注入临时处理函数。 + 【AI 触发时机】:组合根装配(register_onhand_sinks / register_inbound_sinks / + register_outbound_sinks)时调用;测试直接调用注入临时处理函数。 核心逻辑:kind 先经 require_report_kind 白名单校验(onhand / inbound / outbound,非法即 400 fail-closed);同一 kind 重复注册为覆盖。 Args: @@ -42,7 +43,7 @@ def register_report_handler(report_kind: str, handler: Handler) -> None: handler: 处理函数(Handler 契约见模块 docstring);本模块只保存引用, 不校验其内部行为。 Raises: - ValidationError: report_kind 不在白名单(code=SHIPPING.RECEIPT_CALLBACK_INVALID)。 + ValidationError: report_kind 不在白名单(code=SHIPPING.INBOUND_CALLBACK_INVALID)。 """ kind = require_report_kind(report_kind) _REPORT_HANDLERS[kind] = handler diff --git a/backend/app/services/freight_rpa/reports/facts.py b/backend/app/services/freight_rpa/reports/facts.py index 6933889a..e718874a 100644 --- a/backend/app/services/freight_rpa/reports/facts.py +++ b/backend/app/services/freight_rpa/reports/facts.py @@ -4,7 +4,7 @@ 依赖:app.core.errors.ValidationError(非法 kind 的统一失败出口)。 逻辑:本模块是纯契约层(dataclass + 校验函数),不做任何数据库/IO 操作; report kind 只认 onhand / inbound / outbound,非法值抛 - ValidationError(code='SHIPPING.RECEIPT_CALLBACK_INVALID'), + ValidationError(code='SHIPPING.INBOUND_CALLBACK_INVALID'), 与收料回调契约共用既有错误码(后续任务 6/7 的回调分发依赖此约定)。 本模块不 import shipping_notice / in_transit_transfer。 【Task 7 修复轮 2】ReportFact 末位新增可选 unit_run_id——归档入口每次投递 @@ -23,7 +23,7 @@ REPORT_KINDS = ('onhand', 'inbound', 'outbound') # 非法 report kind 复用收料回调契约错误码:同一回调入口族共享一个客户端可辨识码, # 避免为同一类入参错误分裂出多个近义 code。 -_INVALID_KIND_ERROR_CODE = 'SHIPPING.RECEIPT_CALLBACK_INVALID' +_INVALID_KIND_ERROR_CODE = 'SHIPPING.INBOUND_CALLBACK_INVALID' @dataclass(frozen=True) @@ -53,7 +53,7 @@ def require_report_kind(value: str) -> str: 用途:构造 ReportFact、注册/分发报表处理器前,把 kind 校验收敛到唯一入口。 核心逻辑:value 不在 REPORT_KINDS 白名单(onhand / inbound / outbound)即抛 - ValidationError(code='SHIPPING.RECEIPT_CALLBACK_INVALID'),fail-closed。 + ValidationError(code='SHIPPING.INBOUND_CALLBACK_INVALID'),fail-closed。 Args: value: 待校验的报表种类字符串;空值/大小写敏感不匹配同样视为非法。 diff --git a/backend/app/services/freight_rpa/reports/queries.py b/backend/app/services/freight_rpa/reports/queries.py index 4808b3cc..bd5d5879 100644 --- a/backend/app/services/freight_rpa/reports/queries.py +++ b/backend/app/services/freight_rpa/reports/queries.py @@ -2,10 +2,11 @@ 用途:本模块是发货与调拨读报表的唯一入口——以只读视图(View dataclass)+ 解析失败标记的方式,向 in_transit_transfer / shipping_notice 域暴露 - freight_rpa 报表事实(站点、登录连接、在手/入站报表配置、入站解析方案、 + freight_rpa 报表事实(站点、登录连接、在手/入站/出站报表配置、入站解析方案、 入站归档文件),使消费方不再直接 import freight_rpa 模型表。 依赖:app.db、app.models(FreightRpaSource / FreightRpaOnhandReportConfig / - FreightRpaInboundReportConfig / FreightRpaInboundReportFile;登录连接 + FreightRpaInboundReportConfig / FreightRpaOutboundReportConfig / + FreightRpaInboundReportFile;登录连接 (RpaProfile)与解析方案(ParsingProfile)经站点/配置关系连线引用)、 app.core.errors(NotFoundError)、 file_assets.storage.file_asset_storage(按 storage_key 读对象字节)。 @@ -23,8 +24,8 @@ 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 读取」的只读函数消费面。 + 编码清单(list_inbound_configured_source_codes / list_outbound_configured_source_codes) + ——供 in_transit_transfer 收敛为「只按 source_code / file_id 读取」的只读函数消费面。 mark/clear 解析失败只 flush 不 commit——事务提交时机归属调用方。 """ @@ -42,6 +43,7 @@ from app.models import ( FreightRpaInboundReportConfig, FreightRpaInboundReportFile, FreightRpaOnhandReportConfig, + FreightRpaOutboundReportConfig, FreightRpaSource, ) from app.services.file_assets.storage import file_asset_storage @@ -200,6 +202,21 @@ class InboundConfigView: config_version: int = 1 +@dataclass(frozen=True) +class OutboundConfigView: + """出站报表配置只读视图(freight_rpa_outbound_report_configs 行),与入站同构。 + + 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 行)。 @@ -321,6 +338,36 @@ def get_inbound_config(source_code: str) -> InboundConfigView | None: ) +def get_outbound_config(source_code: str) -> OutboundConfigView | None: + """按 source_code 返回出站报表配置只读视图(与入站配置同构)。 + + 用途:调拨出站触发读路径取出站报表定义;出站不设独立启停,是否运行由站点 + enabled 与本配置行是否存在决定。 + 核心逻辑:join 站点表按 source_code 查 freight_rpa_outbound_report_configs 行, + 命中即映射视图;缺失返回 None。 + + Args: + source_code: 站点实例编码。 + Returns: + OutboundConfigView;站点或配置不存在返回 None。 + """ + config = ( + FreightRpaOutboundReportConfig.query + .join(FreightRpaSource, FreightRpaOutboundReportConfig.source_id == FreightRpaSource.id) + .filter(FreightRpaSource.source_code == source_code) + .first() + ) + if config is None: + return None + return OutboundConfigView( + 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, + 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 登录连接只读视图。 @@ -478,6 +525,24 @@ def list_inbound_configured_source_codes() -> list[str]: return [str(code) for (code,) in rows] +def list_outbound_configured_source_codes() -> list[str]: + """列出已配置出站报表的启用站点编码(调拨排程缺省执行范围)。 + + 用途:在途自动调拨排程 source_codes 留空时的缺省范围 + (outbound_trigger_service.list_outbound_capable_source_codes 委托本函数) + ——出站文件只能来自已配置出站报表的启用站点。 + 核心逻辑:站点 join 出站配置行、仅启用站点、按 source_code 排序;只读查询。 + + Returns: + 按 source_code 排序的来源编码列表;无匹配站点时为空列表。 + """ + rows = db.session.query(FreightRpaSource.source_code).join( + FreightRpaOutboundReportConfig, + FreightRpaOutboundReportConfig.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, *, 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 1445d212..1afab2cc 100644 --- a/backend/app/services/in_transit_transfer/inbound_callback_bridge.py +++ b/backend/app/services/in_transit_transfer/inbound_callback_bridge.py @@ -8,7 +8,7 @@ 避免回调迟到误推进其他阶段任务。生产调用方为调拨侧报表事实处理函数 handle_inbound_report(Task 7,inbound_report_handler.py——归档终态 commit 后 经 dispatch_report_fact 调入;返回 None 时调用方跳过提交分支);回归测试桥 - (inbound_report_storage._advance_transfer_source_job)仍走本函数。 + (handle_inbound_report / 历史测试桥)仍走本函数。 SourceJob 状态为字符串常量(见 models)。 """ diff --git a/backend/app/services/in_transit_transfer/inbound_report_handler.py b/backend/app/services/in_transit_transfer/inbound_report_handler.py index 025f2f7f..2b2d01f5 100644 --- a/backend/app/services/in_transit_transfer/inbound_report_handler.py +++ b/backend/app/services/in_transit_transfer/inbound_report_handler.py @@ -9,7 +9,7 @@ services/in_transit_transfer/inbound_report_handler.py 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) +逻辑:由组合根(app.create_app → in_transit_transfer.rpa_sinks.register_inbound_sinks) 注册为 'inbound' kind 处理函数;freight_rpa.inbound.report_archive. ingest_inbound_callback 在每个终态 db.session.commit() 之后经 dispatch_report_fact 调入本函数。处理函数只改调拨自己的行; @@ -65,7 +65,7 @@ def handle_inbound_report(fact: ReportFact) -> None: if kind != 'inbound': raise ValidationError( f"handle_inbound_report only accepts inbound facts, got: {kind!r}", - code='SHIPPING.RECEIPT_CALLBACK_INVALID', + code='SHIPPING.INBOUND_CALLBACK_INVALID', details={'report_kind': fact.report_kind}, ) @@ -126,9 +126,9 @@ def handle_inbound_report(fact: ReportFact) -> None: 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, + finalize_inbound_schedule_run_if_complete, + refresh_inbound_schedule_run_progress, ) - refresh_receipt_schedule_run_progress(schedule_run_id) - finalize_receipt_schedule_run_if_complete(schedule_run_id) + refresh_inbound_schedule_run_progress(schedule_run_id) + finalize_inbound_schedule_run_if_complete(schedule_run_id) diff --git a/backend/app/services/in_transit_transfer/outbound_report_handler.py b/backend/app/services/in_transit_transfer/outbound_report_handler.py new file mode 100644 index 00000000..97a3edde --- /dev/null +++ b/backend/app/services/in_transit_transfer/outbound_report_handler.py @@ -0,0 +1,144 @@ +""" +services/in_transit_transfer/outbound_report_handler.py + +用途:outbound 报表事实的调拨侧业务处理函数——出站归档终态 commit 后由 + dispatch_report_fact 投递的 ReportFact 只在此推进调拨自己的任务: + TransferSourceJob 等待态推进、出站排程收口。 +依赖:app.db、app.models(FreightRpaOutboundUnitRun——执行单元读取)、 + app.core.errors.ValidationError、freight_rpa.reports.facts(ReportFact / + require_report_kind——只消费事实契约,不 import freight_rpa 工作流)。 +逻辑:由组合根(app.create_app → in_transit_transfer.rpa_sinks.register_outbound_sinks) + 注册为 'outbound' kind 处理函数;freight_rpa.outbound.report_archive. + ingest_outbound_callback 在每个终态 db.session.commit() 之后经 + dispatch_report_fact 调入本函数。处理函数只改调拨自己的行; + 【不捕获异常】——任何失败原样外抛,归档文件已提交不回滚, + Worker 重试整笔回调即可补齐推进(先 commit 再投递的顺序契约)。 + 状态机字段与入站同一套:waiting_rpa_callback → file_ready / failed; + 无等待任务则 no-op;第二次调用该行已离开等待态,不再改(可重入)。 +""" + +from __future__ import annotations + +from datetime import datetime + +from app import db +from app.core.errors import ValidationError +from app.models import FreightRpaOutboundUnitRun, TransferSourceJob +from app.services.freight_rpa.reports.facts import ReportFact, require_report_kind + +_FILE_READY = 'file_ready' +_WAITING_RPA_CALLBACK = 'waiting_rpa_callback' +_FAILED = 'failed' + + +def _advance_waiting_source_job( + *, source_code: str, file_no: str | None = None, file_sha256: str | None = None, + callback_ok: bool = True, error_code: str | None = None, error_message: str | None = None, +) -> TransferSourceJob | None: + """按来源推进最新等待回调的调拨来源任务(与入站桥同一等待态字段)。 + + 核心逻辑:只改 status='waiting_rpa_callback' 的行;无匹配则不动作, + 避免回调迟到误推进其他阶段任务。success/有文件 → file_ready;否则 → failed。 + 本函数只 flush 不 commit,提交归属 handle_outbound_report。 + + Args: + source_code: 回调所属来源实例。 + file_no: 出站文件号(success 时)。 + file_sha256: 出站文件 sha256(success 时)。 + callback_ok / error_code / error_message: 回调终态。 + Returns: + 被推进的任务;无等待任务或已终态时返回 None。 + """ + job = ( + TransferSourceJob.query + .filter_by(source_code=source_code, status=_WAITING_RPA_CALLBACK) + .order_by(TransferSourceJob.id.desc()) + .first() + ) + if job is None: + return None + if callback_ok and file_no: + job.status = _FILE_READY + job.file_no = file_no + job.file_sha256 = file_sha256 + job.error_code = None + job.error_message = None + job.finished_at = datetime.utcnow() + else: + job.status = _FAILED + job.error_code = error_code or 'RPA_OUTBOUND_CALLBACK_FAILED' + job.error_message = error_message or 'outbound rpa callback failed' + job.finished_at = datetime.utcnow() + db.session.flush() + return job + + +def handle_outbound_report(fact: ReportFact) -> None: + """report_kind 必须是 outbound。ok 且 file_id 有值时把等待中的 TransferSourceJob 推进到 file_ready; + ok 为假时推进到 failed。没有 waiting_rpa_callback 行则 return。第二次调用时该行已离开等待态,不再改。 + + 核心逻辑: + [STEP 1] kind 门禁(fail-closed);[STEP 2] 推进等待中的来源任务(只改 + status='waiting_rpa_callback' 的行,无等待行返回 None);[STEP 3] + 推进结果必须在此提交;[STEP 4] 精确定位本次回调收尾的执行单元并回写出站 + 排程进度、归集终态。不调用入站 evidence_sync(record_kind=inbound 专用)。 + 【不捕获异常】任何一步失败原样外抛供 Worker 重试。 + + Args: + fact: 终态已提交后由归档入口构造的报表事实(report_kind/source_code/ + file_id/sha256/ok/error_code/error_message/unit_run_id)。 + Returns: + None(推进/收口结果全部写库,不返回业务值)。 + Raises: + ValidationError: report_kind 非 outbound(误注册/误分发,fail-closed)。 + """ + # [STEP 1] kind 门禁:本函数只消费 outbound 事实。 + kind = require_report_kind(fact.report_kind) + if kind != 'outbound': + raise ValidationError( + f"handle_outbound_report only accepts outbound facts, got: {kind!r}", + code='SHIPPING.OUTBOUND_CALLBACK_INVALID', + details={'report_kind': fact.report_kind}, + ) + + # [STEP 2] 推进等待中的调拨来源任务:ok 且 file_id 有值 → file_ready; + # 否则 → failed。无等待行返回 None(调拨侧无行可改,直接结束推进分支)。 + if fact.ok and fact.file_id is not None: + advanced = _advance_waiting_source_job( + source_code=fact.source_code, + file_no=str(fact.file_id), + file_sha256=fact.sha256, + callback_ok=True, + ) + else: + advanced = _advance_waiting_source_job( + source_code=fact.source_code, + callback_ok=False, + error_code=fact.error_code, + error_message=fact.error_message, + ) + + # [STEP 3] 桥只 flush 不 commit:推进落库必须在此提交。 + if advanced is not None: + db.session.commit() + + # [STEP 4] 出站排程收口:按 fact.unit_run_id 精确定位本次回调收尾的执行单元。 + schedule_run_id: int | None = None + if fact.unit_run_id is not None: + unit = db.session.get(FreightRpaOutboundUnitRun, int(fact.unit_run_id)) + if unit is None: + from app.core.errors import NotFoundError + + raise NotFoundError( + f"Outbound 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_outbound_finalize import ( + finalize_outbound_schedule_run_if_complete, + refresh_outbound_schedule_run_progress, + ) + + refresh_outbound_schedule_run_progress(schedule_run_id) + finalize_outbound_schedule_run_if_complete(schedule_run_id) diff --git a/backend/app/services/in_transit_transfer/outbound_trigger_service.py b/backend/app/services/in_transit_transfer/outbound_trigger_service.py new file mode 100644 index 00000000..0ca30b24 --- /dev/null +++ b/backend/app/services/in_transit_transfer/outbound_trigger_service.py @@ -0,0 +1,261 @@ +"""在途调拨出站 RPA 触发服务。 + +用途:为单个或多个来源触发出站 RPA 抓取(出站证据 = freight_rpa 出站 RPA 产物, + 复用货代出站 trigger 链路),不创建排程。按来源取站点、出站配置与登录连接 + (全部经 freight_rpa.reports.queries 只读入口),先落 RPA 单元运行行 + (awaiting_rpa,回调按 callback_id 查库可达),再装配出站 trigger unit 并 + 调用 write_outbound_export_batch_trigger 原子写 trigger。 +依赖:write_outbound_export_batch_trigger(默认 writer,freight_rpa.outbound.trigger_io)、 + freight_rpa.reports.queries(get_site / get_outbound_config / get_rpa_login_profile / + list_outbound_configured_source_codes——站点、配置与登录连接读取唯一权威)、db。 +逻辑:list_outbound_capable_source_codes 供排程 source_codes 留空时的缺省范围; + 一源一单元,query_parameters 原样下发;来源停用/出站配置缺失/登录连接缺失时 + fail-closed;写 trigger 失败把单元行标 failed 并 commit。 + trigger_outbound_rpa_batch 把多来源合并为一个 batch trigger 文件: + Worker 对单文件按 profile 分组共享一次浏览器会话,避免逐来源开/关浏览器。 + trigger unit 载荷键集与 Worker 契约(freight_rpa.outbound.v1)逐键对齐入站。 +""" + +from __future__ import annotations + +import uuid +from typing import Any, Callable + +from app.services.freight_rpa.outbound.trigger_io import ( + ACTION_OUTBOUND_EXPORT_BATCH, + SCHEMA, + write_outbound_export_batch_trigger, +) +from app.services.freight_rpa.reports.queries import ( + get_outbound_config, + get_rpa_login_profile, + get_site, + list_outbound_configured_source_codes, +) + +RouteTriggerWriter = Callable[..., str | None] + + +def _write_outbound_trigger(run_no: str, units: list[dict[str, Any]], payload: dict[str, Any] | None = None) -> str | None: + """适配出站 IO 的 meta 形参,对外保持与入站 writer 相同的 payload= 协议。""" + return write_outbound_export_batch_trigger(run_no, units, meta=payload) + + +def _build_trigger_unit( + *, source_code: str, business_date: str, reason: str, +) -> dict[str, Any]: + """装配单来源出站 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。 + + 核心逻辑:一源一单元,query_parameters 原样下发;空条件表示 Worker 走页面默认。 + 站点(get_site)/ 出站配置(get_outbound_config)/ 登录连接 + (get_rpa_login_profile)读取改经 freight_rpa.reports.queries 只读入口;装配出的 + unit 载荷键集与 Worker 契约逐键保持不变(快照含配置行主键与版本)。 + """ + site = get_site(source_code) + if site is None or not site.enabled: + raise RuntimeError(f'source not enabled: {source_code}') + config = get_outbound_config(source_code) + if config is None: + raise RuntimeError(f'outbound config missing: {source_code}') + profile = get_rpa_login_profile(source_code) + if profile is None or not profile.enabled: + raise RuntimeError(f'outbound 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.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': profile.profile_id, + } + return { + 'source_id': site.source_id, + 'callback_id': f'outbound:{uuid.uuid4().hex}', + 'source_code': site.source_code, + 'connector_type': site.connector_type, + 'warehouse_id': None, + 'rpa_profile_id': profile.profile_id, + 'rpa_profile_code': profile.profile_code, + 'login_url': profile.login_url, + 'login_config': dict(profile.login_config or {}), + 'credential_envelope': { + 'username_ciphertext': profile.username_ciphertext, + 'password_ciphertext': profile.password_ciphertext, + }, + 'report_path_json': dict(snapshot.get('report_path_json') or {}), + 'query_parameters_json': list(query_parameters), + 'config_snapshot': snapshot, + 'business_date': business_date, + 'reason': reason, + } + + +def list_outbound_capable_source_codes() -> list[str]: + """列出可产出出站文件的启用来源实例(已配置出站报表的启用站点)。 + + 用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——出站文件 + 只能来自已配置出站报表的站点,与货代出站 RPA 排程的站点口径一致。 + Returns: + 按 source_code 排序的来源编码列表;无匹配站点时为空列表。 + """ + return list_outbound_configured_source_codes() + + +def trigger_outbound_rpa( + *, + source_code: str, + business_date: str, + reason: str = 'transfer_retry_outbound', + writer: RouteTriggerWriter | None = None, +) -> dict[str, Any]: + """触发一次来源出站 RPA 抓取(先落单元行再写 trigger,保证回调可达)。 + + Args: + source_code: 来源实例编码。 + business_date: 业务日期。 + reason: 触发原因(写入 trigger)。 + writer: 触发写者;缺省复用 write_outbound_export_batch_trigger(payload= 协议)。 + Returns: + {"ok": True, "callback_id": ..., "trigger_path": ...} 或 + {"ok": False, "error_code": ...}(配置缺失 / 触发目录不可用)。 + """ + try: + unit_payload = _build_trigger_unit(source_code=source_code, business_date=business_date, reason=reason) + except RuntimeError as exc: + return {"ok": False, "error_code": "RPA_OUTBOUND_CONFIG_MISSING", "error_message": str(exc)} + + # [STEP 1] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库, + # 不落行则回调必然 404(与排程路径 / 入站按需触发同一模式)。 + from app import db + from app.models.freight_rpa_outbound_report import FreightRpaOutboundUnitRun as FreightRpaOutboundUnitRun + + unit = FreightRpaOutboundUnitRun( + # 按需触发无 ScheduleRun:schedule_run_id 保持 NULL(列可空;FK 禁止 0 占位)。 + 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'), + callback_id=unit_payload['callback_id'], + status='awaiting_rpa', + config_snapshot_json=dict(unit_payload['config_snapshot']), + ) + db.session.add(unit) + db.session.flush() + unit_payload['unit_run_id'] = unit.id + + # [STEP 2] 原子写 trigger;目录不可用则单元标 failed(fail-closed,不留永久 awaiting)。 + run_no = f"TRIG-{source_code}-{uuid.uuid4().hex[:8].upper()}" + writer_fn = writer or _write_outbound_trigger + path = writer_fn(run_no, [unit_payload], payload={ + 'schema_version': SCHEMA, + 'action': ACTION_OUTBOUND_EXPORT_BATCH, + 'source_code': source_code, + 'business_date': business_date, + 'reason': reason, + }) + if not path: + unit.status = 'failed' + unit.error_code = 'RPA_OUTBOUND_TRIGGER_UNAVAILABLE' + unit.error_message = 'outbound trigger directory unavailable' + db.session.commit() + return {"ok": False, "error_code": "RPA_OUTBOUND_TRIGGER_UNAVAILABLE"} + + # [STEP 3] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。 + unit.trigger_snapshot_json = unit_payload + db.session.commit() + return {"ok": True, "callback_id": unit_payload['callback_id'], "trigger_path": path} + + +def trigger_outbound_rpa_batch( + *, + source_codes: list[str], + business_date: str, + reason: str = 'transfer_retry_outbound', + writer: RouteTriggerWriter | None = None, +) -> dict[str, Any]: + """批量触发多来源出站 RPA:全部有效来源合并写**一个** batch trigger 文件。 + + 【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个出站来源编码时调用; + 行级单来源重试仍走 trigger_outbound_rpa(一源一文件语义不变)。 + + 核心逻辑:逐来源装配 unit(来源级隔离——配置缺失/停用跳过并记录,不炸整批); + 有效 units 先各落一行 RPA 单元运行行再一次性 write_outbound_export_batch_trigger + 原子落盘。Worker 对单文件按 profile 分组共享一次浏览器会话串行导出。 + 入站 batch 的 parse_failed 本地重解析不在此复用——来源文件状态投影仅覆盖入站归档。 + + Args: + source_codes: 来源实例编码列表(去重保序;空串自动剔除)。 + business_date: 业务日期。 + reason: 触发原因(写入 trigger payload)。 + writer: 触发写者;缺省复用 write_outbound_export_batch_trigger。 + + Returns: + {"ok": True/False, "triggered": bool, "results": [...], "trigger_path"?/「error_code」?}。 + ok=本次请求产生了主效果(写盘成功);triggered=是否写了 batch trigger; + results 逐来源携带真实结果。 + """ + from app import db + from app.models.freight_rpa_outbound_report import FreightRpaOutboundUnitRun as FreightRpaOutboundUnitRun + + codes = list(dict.fromkeys(str(code).strip() for code in source_codes if str(code).strip())) + results: list[dict[str, Any]] = [] + units: list[FreightRpaOutboundUnitRun] = [] + unit_payloads: list[dict[str, Any]] = [] + + # [STEP 1] 逐来源装配 unit;单源失败跳过不阻断整批。 + for code in codes: + try: + unit_payloads.append(_build_trigger_unit(source_code=code, business_date=business_date, reason=reason)) + except RuntimeError as exc: + results.append({ + 'source_code': code, 'ok': False, + 'error_code': 'RPA_OUTBOUND_CONFIG_MISSING', 'error_message': str(exc), + }) + + if not unit_payloads: + db.session.commit() + return {"ok": False, "triggered": False, "error_code": "RPA_OUTBOUND_NO_TRIGGERABLE_SOURCE", "results": results} + + # [STEP 2] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库(与单来源同模式)。 + for payload in unit_payloads: + unit = FreightRpaOutboundUnitRun( + source_id=payload['source_id'], + source_code=payload['source_code'], + connector_type=payload['connector_type'], + warehouse_id=payload.get('warehouse_id'), + callback_id=payload['callback_id'], + status='awaiting_rpa', + config_snapshot_json=dict(payload['config_snapshot']), + ) + db.session.add(unit) + units.append(unit) + db.session.flush() + for unit, payload in zip(units, unit_payloads): + payload['unit_run_id'] = unit.id + + # [STEP 3] 一个 batch trigger 原子落盘;目录不可用则本批单元全部标 failed(不留永久 awaiting)。 + run_no = f"TRIG-BATCH-{uuid.uuid4().hex[:8].upper()}" + writer_fn = writer or _write_outbound_trigger + path = writer_fn(run_no, unit_payloads, payload={ + 'schema_version': SCHEMA, + 'action': ACTION_OUTBOUND_EXPORT_BATCH, + 'business_date': business_date, + 'reason': reason, + 'source_codes': [payload['source_code'] for payload in unit_payloads], + }) + if not path: + for unit in units: + unit.status = 'failed' + unit.error_code = 'RPA_OUTBOUND_TRIGGER_UNAVAILABLE' + unit.error_message = 'outbound trigger directory unavailable' + db.session.commit() + return {"ok": False, "triggered": False, "error_code": "RPA_OUTBOUND_TRIGGER_UNAVAILABLE", "results": results} + + # [STEP 4] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。 + for unit, payload in zip(units, unit_payloads): + unit.trigger_snapshot_json = payload + results.append({'source_code': unit.source_code, 'ok': True}) + db.session.commit() + return {"ok": True, "triggered": True, "trigger_path": path, "results": results} diff --git a/backend/app/services/in_transit_transfer/rpa_sinks.py b/backend/app/services/in_transit_transfer/rpa_sinks.py new file mode 100644 index 00000000..5daad3be --- /dev/null +++ b/backend/app/services/in_transit_transfer/rpa_sinks.py @@ -0,0 +1,63 @@ +""" +services/in_transit_transfer/rpa_sinks.py + +用途:入站 / 出站 RPA 回调与报表事实的组合根注册——把 /api/freight-rpa/inbound-*、 + outbound-* 接到 freight_rpa 归档入口与本包事实处理函数(调拨是唯一业务消费方)。 +依赖:freight_rpa.common.callback_sinks、freight_rpa.reports.dispatch、 + freight_rpa.inbound/outbound.report_archive、schedule.freight_rpa_*_finalize、 + inbound_report_handler / outbound_report_handler。 +逻辑:由 app.create_app 调用 register_inbound_sinks / register_outbound_sinks(幂等)。 + 进度类 sink 复刻 {'success':True,'data':...} envelope;文件事实经 + register_report_handler 注册。不 import shipping_notice。 +""" + +from __future__ import annotations + +from typing import Any, Callable + + +def _success_data_envelope(handler: Callable[[dict[str, Any]], dict[str, Any]]) -> Callable[..., dict[str, Any]]: + """旧 inbound/outbound 进度端点 envelope:{'success':True,'data':业务结果}。""" + + def _sink(**payload: Any) -> dict[str, Any]: + return {'success': True, 'data': handler(payload)} + + return _sink + + +def register_inbound_sinks() -> None: + """注册全部 inbound 进度 sink 与 inbound 事实处理函数(幂等)。 + + 核心逻辑:inbound-batch-ready 直挂 freight_rpa.inbound.report_archive.ingest_inbound_callback + (与 outbound 对称,无 shipping_notice 薄壳);unit/batch-progress 挂 + schedule.freight_rpa_inbound_finalize;事实处理函数挂 handle_inbound_report。 + """ + from app.services.freight_rpa.common.callback_sinks import register_sink + 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 + from app.services.schedule import freight_rpa_inbound_finalize + + register_sink('inbound-batch-ready', _success_data_envelope(ingest_inbound_callback)) + register_sink('inbound-unit-progress', _success_data_envelope(freight_rpa_inbound_finalize.mark_inbound_unit_processing)) + register_sink('inbound-batch-progress', _success_data_envelope(freight_rpa_inbound_finalize.report_inbound_batch_progress)) + register_report_handler('inbound', handle_inbound_report) + + +def register_outbound_sinks() -> None: + """注册全部 outbound 进度 sink 与 outbound 事实处理函数(幂等)。 + + 核心逻辑:outbound-batch-ready 直挂 freight_rpa.outbound.report_archive.ingest_outbound_callback; + unit/batch-progress 挂 schedule.freight_rpa_outbound_finalize;事实处理函数挂 + handle_outbound_report。 + """ + from app.services.freight_rpa.common.callback_sinks import register_sink + from app.services.freight_rpa.outbound.report_archive import ingest_outbound_callback + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report + from app.services.schedule import freight_rpa_outbound_finalize + + register_sink('outbound-batch-ready', _success_data_envelope(ingest_outbound_callback)) + register_sink('outbound-unit-progress', _success_data_envelope(freight_rpa_outbound_finalize.mark_outbound_unit_processing)) + register_sink('outbound-batch-progress', _success_data_envelope(freight_rpa_outbound_finalize.report_outbound_batch_progress)) + register_report_handler('outbound', handle_outbound_report) diff --git a/backend/app/services/schedule/__init__.py b/backend/app/services/schedule/__init__.py index 3edcd460..eeda8605 100644 --- a/backend/app/services/schedule/__init__.py +++ b/backend/app/services/schedule/__init__.py @@ -344,10 +344,12 @@ def _register_headers_from_config() -> None: if cfg.alias_order and cfg.header_labels: register_schedule_header(name, cfg.alias_order, cfg.header_labels) 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 + from app.services.schedule.freight_rpa_inbound_finalize import register_inbound_rpa_excel_headers + from app.services.schedule.freight_rpa_outbound_finalize import register_outbound_rpa_excel_headers register_inventory_rpa_excel_headers() - register_receipt_rpa_excel_headers() + register_inbound_rpa_excel_headers() + register_outbound_rpa_excel_headers() def reload_config() -> dict[str, Any]: diff --git a/backend/app/services/schedule/freight_rpa_inbound_archive.py b/backend/app/services/schedule/freight_rpa_inbound_archive.py index b681eaab..cd25799e 100644 --- a/backend/app/services/schedule/freight_rpa_inbound_archive.py +++ b/backend/app/services/schedule/freight_rpa_inbound_archive.py @@ -1,11 +1,11 @@ """ backend/app/services/schedule/freight_rpa_inbound_archive.py -用途:货代收料 RPA 排程 run 的原始收料 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。 +用途:货代入站 RPA 排程 run 的原始入站 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。 依赖: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`; + file_asset_storage、timezone_util、freight_rpa_inbound_finalize.is_freight_inbound_rpa_task。 +逻辑:finalize 调用 persist_inbound_rpa_raw_zip_archive 写入磁盘与 summary; + 企微/下载展示名用「入站RPA-日期-时刻-入站」;包内条目 `{序号}_{source_code}.xlsx`; warehouse_id / file_id 只写在 manifest.json;磁盘归档键为 {run_no}.zip。 """ @@ -23,23 +23,23 @@ from flask import current_app from app.core.errors import NotFoundError from app.models import ScheduleRun, FreightRpaInboundReportFile, FreightRpaInboundUnitRun from app.services.file_assets.storage import file_asset_storage -from app.services.schedule.freight_rpa_inbound_finalize import is_freight_receipt_rpa_task +from app.services.schedule.freight_rpa_inbound_finalize import is_freight_inbound_rpa_task from app.services.schedule.timezone_util import resolve_schedule_tzinfo -_RAW_ZIP_NOT_FOUND_MESSAGE = '原始收料包不存在,请重新执行或联系管理员' +_RAW_ZIP_NOT_FOUND_MESSAGE = '原始入站包不存在,请重新执行或联系管理员' _EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = { - 'raw_receipt_zip_available': False, - 'raw_receipt_zip_path': None, - 'raw_receipt_file_count': 0, - 'raw_receipt_file_ids': [], - 'raw_receipt_zip_size': 0, + 'raw_inbound_zip_available': False, + 'raw_inbound_zip_path': None, + 'raw_inbound_file_count': 0, + 'raw_inbound_file_ids': [], + 'raw_inbound_zip_size': 0, } -def get_receipt_archive_dir() -> str: +def get_inbound_archive_dir() -> str: """ - 返回收料 RPA 原始 ZIP 归档根目录(自动创建)。 + 返回入站 RPA 原始 ZIP 归档根目录(自动创建)。 核心逻辑:优先读 Flask config;值为 None/空时回落到 Config 默认路径, 避免 Path(None) 在 finalize 阶段把整次 ZIP 归档打成空 summary。 @@ -87,9 +87,9 @@ def _attachment_when_from_run(run: ScheduleRun) -> datetime: return when_utc.astimezone(tz) -def receipt_rpa_attachment_stem(run: ScheduleRun) -> str: +def inbound_rpa_attachment_stem(run: ScheduleRun) -> str: """ - 收料 RPA 企微附件共用前缀:收料RPA-{yyyyMMdd}-{HHmm}(业务时区当地时间)。 + 入站 RPA 企微附件共用前缀:入站RPA-{yyyyMMdd}-{HHmm}(业务时区当地时间)。 Args: run: 排程执行记录。 @@ -98,29 +98,29 @@ def receipt_rpa_attachment_stem(run: ScheduleRun) -> str: 不含角色后缀与扩展名的展示名前缀。 """ when = _attachment_when_from_run(run) - return f"收料RPA-{when.strftime('%Y%m%d')}-{when.strftime('%H%M')}" + return f"入站RPA-{when.strftime('%Y%m%d')}-{when.strftime('%H%M')}" -def receipt_raw_zip_download_name(run: ScheduleRun) -> str: +def inbound_raw_zip_download_name(run: ScheduleRun) -> str: """ - 收料 ZIP 的企微/浏览器下载展示名。 + 入站 ZIP 的企微/浏览器下载展示名。 核心逻辑:磁盘归档仍为 {run_no}.zip;本函数只影响 Content-Disposition 与企微 filename。 """ - return f'{receipt_rpa_attachment_stem(run)}-收料.zip' + return f'{inbound_rpa_attachment_stem(run)}-入站.zip' -def receipt_rpa_result_excel_name(run: ScheduleRun) -> str: - """收料 RPA 结果 Excel 的企微/下载展示名(对齐库存 onhand_rpa_result_excel_name)。""" - return f'{receipt_rpa_attachment_stem(run)}-结果.xlsx' +def inbound_rpa_result_excel_name(run: ScheduleRun) -> str: + """入站 RPA 结果 Excel 的企微/下载展示名(对齐库存 onhand_rpa_result_excel_name)。""" + return f'{inbound_rpa_attachment_stem(run)}-结果.xlsx' -def _receipt_raw_zip_archive_path(run_no: str) -> Path: +def _inbound_raw_zip_archive_path(run_no: str) -> Path: """磁盘归档路径:/.zip。""" - return Path(get_receipt_archive_dir()) / f'{run_no}.zip' + return Path(get_inbound_archive_dir()) / f'{run_no}.zip' -def _iter_packable_receipt_files(run: ScheduleRun): +def _iter_packable_inbound_files(run: ScheduleRun): """ 遍历该 run 下可打包的收料归档文件。 @@ -129,7 +129,7 @@ def _iter_packable_receipt_files(run: ScheduleRun): Yields: FreightRpaInboundReportFile: 可从 MinIO 读取的归档记录。 """ - if not is_freight_receipt_rpa_task(getattr(run, 'task', None)): + if not is_freight_inbound_rpa_task(getattr(run, 'task', None)): return rows = ( FreightRpaInboundReportFile.query.join( @@ -147,35 +147,35 @@ def _iter_packable_receipt_files(run: ScheduleRun): yield report_file -def receipt_raw_zip_available_from_summary(summary: dict[str, Any] | None) -> bool: +def inbound_raw_zip_available_from_summary(summary: dict[str, Any] | None) -> bool: """ - 从 response_summary_json 读取原始收料 ZIP 是否可下载。 + 从 response_summary_json 读取原始入站 ZIP 是否可下载。 核心逻辑:列表序列化只读 summary,不查库、不访问磁盘。 """ if not isinstance(summary, dict): return False - return bool(summary.get('raw_receipt_zip_available')) + return bool(summary.get('raw_inbound_zip_available')) -def persist_receipt_rpa_raw_zip_archive(run: ScheduleRun) -> dict[str, Any]: +def persist_inbound_rpa_raw_zip_archive(run: ScheduleRun) -> dict[str, Any]: """ - finalize 阶段预生成原始收料 ZIP 归档并返回 summary 字段。 + finalize 阶段预生成原始入站 ZIP 归档并返回 summary 字段。 核心逻辑:从 MinIO 拉取各单元归档字节 → 写入 /.zip - (含 manifest.json);无可用文件时返回 raw_receipt_zip_available=false。 + (含 manifest.json);无可用文件时返回 raw_inbound_zip_available=false。 Args: - run: 收料 RPA ScheduleRun。 + run: 入站 RPA ScheduleRun。 Returns: - dict: raw_receipt_zip_available / path / file_count / file_ids / zip_size。 + dict: raw_inbound_zip_available / path / file_count / file_ids / zip_size。 """ - packable_files = list(_iter_packable_receipt_files(run)) + packable_files = list(_iter_packable_inbound_files(run)) if not packable_files: return dict(_EMPTY_ARCHIVE_SUMMARY) - archive_path = _receipt_raw_zip_archive_path(run.run_no) + archive_path = _inbound_raw_zip_archive_path(run.run_no) files_manifest: list[dict[str, Any]] = [] with zipfile.ZipFile(archive_path, 'w', compression=zipfile.ZIP_DEFLATED) as archive: @@ -217,15 +217,15 @@ def persist_receipt_rpa_raw_zip_archive(run: ScheduleRun) -> dict[str, Any]: ) return { - 'raw_receipt_zip_available': True, - 'raw_receipt_zip_path': str(archive_path.resolve()), - 'raw_receipt_file_count': len(files_manifest), - 'raw_receipt_file_ids': [item['file_id'] for item in files_manifest], - 'raw_receipt_zip_size': int(archive_path.stat().st_size), + 'raw_inbound_zip_available': True, + 'raw_inbound_zip_path': str(archive_path.resolve()), + 'raw_inbound_file_count': len(files_manifest), + 'raw_inbound_file_ids': [item['file_id'] for item in files_manifest], + 'raw_inbound_zip_size': int(archive_path.stat().st_size), } -def _is_allowed_receipt_archive_path(zip_path: Path) -> bool: +def _is_allowed_inbound_archive_path(zip_path: Path) -> bool: """ 校验归档 ZIP 路径是否安全可下载。 @@ -237,7 +237,7 @@ def _is_allowed_receipt_archive_path(zip_path: Path) -> bool: if not resolved.is_file(): return False - archive_dir = Path(get_receipt_archive_dir()).resolve() + archive_dir = Path(get_inbound_archive_dir()).resolve() try: resolved.relative_to(archive_dir) except ValueError: @@ -245,11 +245,11 @@ def _is_allowed_receipt_archive_path(zip_path: Path) -> bool: return True -def resolve_receipt_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]: +def resolve_inbound_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]: """ - 解析 run 已归档的原始收料 ZIP 路径供下载接口 send_file。 + 解析 run 已归档的原始入站 ZIP 路径供下载接口 send_file。 - 核心逻辑:读取 summary.raw_receipt_zip_path,校验文件存在、后缀为 .zip、 + 核心逻辑:读取 summary.raw_inbound_zip_path,校验文件存在、后缀为 .zip、 且真实路径位于 FREIGHT_RPA_INBOUND_ARCHIVE_DIR 内;任一不满足则 404。 Returns: @@ -259,18 +259,18 @@ def resolve_receipt_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]: NotFoundError: summary 未标记可用、路径非法或归档文件已丢失。 """ summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} - if not receipt_raw_zip_available_from_summary(summary): + if not inbound_raw_zip_available_from_summary(summary): raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE) - zip_path_raw = str(summary.get('raw_receipt_zip_path') or '').strip() + zip_path_raw = str(summary.get('raw_inbound_zip_path') or '').strip() if not zip_path_raw: raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE) zip_path = Path(zip_path_raw) - if not _is_allowed_receipt_archive_path(zip_path): + if not _is_allowed_inbound_archive_path(zip_path): raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE) - return zip_path.resolve(), receipt_raw_zip_download_name(run) + return zip_path.resolve(), inbound_raw_zip_download_name(run) def _sanitize_zip_segment(value: str) -> str: diff --git a/backend/app/services/schedule/freight_rpa_inbound_finalize.py b/backend/app/services/schedule/freight_rpa_inbound_finalize.py index 69b9c354..83c742a3 100644 --- a/backend/app/services/schedule/freight_rpa_inbound_finalize.py +++ b/backend/app/services/schedule/freight_rpa_inbound_finalize.py @@ -1,7 +1,7 @@ """ backend/app/services/schedule/freight_rpa_inbound_finalize.py -用途:独立收料 RPA 排程等待态收口——进度回写、全单元终态后写计数、预生成 ZIP、发企微; +用途:独立入站 RPA 排程等待态收口——进度回写、全单元终态后写计数、预生成 ZIP、发企微; 另含超时对账:排程 run 级(每轮 tick)与按需触发孤儿单元级(schedule_run_id=NULL)。 依赖:FreightRpaInboundUnitRun、freight_rpa_inbound_archive、scheduler_service 企微通知。 逻辑:每笔回调 → refresh 进度计数 → 全终态时 persist ZIP → _notify_schedule_run_wecom; @@ -21,7 +21,7 @@ from app.models import ScheduleRun, ScheduleTask 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_rpa_inbound_job import AWAITING_RECEIPT_RPA_CALLBACK_STATUS, INBOUND_RPA_JOB_KEY +from app.services.schedule.freight_rpa_inbound_job import AWAITING_INBOUND_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 @@ -29,25 +29,25 @@ _RECEIPT_RPA_HEADER_ORDER = [ "source_code", "warehouse_id", "connector_type", - "receipt_file_count", + "inbound_file_count", "export_status", "skip_reason", "error_message", ] _RECEIPT_RPA_HEADER_LABELS = { - "source_code": "收料源", + "source_code": "入站源", "warehouse_id": "仓库", "connector_type": "连接器", - "receipt_file_count": "归档文件数", + "inbound_file_count": "归档文件数", "export_status": "导出状态", "skip_reason": "跳过原因", "error_message": "错误原因", } -def register_receipt_rpa_excel_headers() -> None: +def register_inbound_rpa_excel_headers() -> None: """ - 注册货代收料 RPA 排程 Excel 列头(幂等)。 + 注册货代入站 RPA 排程 Excel 列头(幂等)。 核心逻辑:由 schedule.__init__._register_headers_from_config 在 reload 后调用,避免被 clear 冲掉。 """ register_schedule_header( @@ -57,15 +57,15 @@ def register_receipt_rpa_excel_headers() -> None: ) -def _build_receipt_finalize_details(units: list[FreightRpaInboundUnitRun]) -> list[dict[str, Any]]: +def _build_inbound_finalize_details(units: list[FreightRpaInboundUnitRun]) -> list[dict[str, Any]]: """ - 收料单元 → 排程 Excel 明细行(对齐库存 finalize 的行结构)。 + 入站单元 → 排程 Excel 明细行(对齐库存 finalize 的行结构)。 核心逻辑:empty 归一为 skipped、cancelled 归一为 failed,与卡片 计数口径一致; - 归档文件数便于与原始收料包内 {序号}_{source_code}.xlsx 条目对账。 + 归档文件数便于与原始入站包内 {序号}_{source_code}.xlsx 条目对账。 Args: - units: 该 run 的全部收料单元(已全部终态)。 + units: 该 run 的全部入站单元(已全部终态)。 Returns: list[dict]: 按 unit.id 升序的明细行。 @@ -83,7 +83,7 @@ def _build_receipt_finalize_details(units: list[FreightRpaInboundUnitRun]) -> li 'source_code': unit.source_code, 'warehouse_id': unit.warehouse_id or '', 'connector_type': unit.connector_type or '', - 'receipt_file_count': len(unit.files or []), + 'inbound_file_count': len(unit.files or []), 'export_status': export_status, 'skip_reason': str(unit.error_code or '') if export_status == 'skipped' else '', 'error_message': str(unit.error_message or '')[:500] if export_status == 'failed' else '', @@ -91,25 +91,25 @@ def _build_receipt_finalize_details(units: list[FreightRpaInboundUnitRun]) -> li return rows -def should_defer_receipt_schedule_run(task: ScheduleTask, step_logs: list | None) -> bool: - """仅当独立收料 job 成功写入 trigger 后延后终态,避免影响库存 job 判断。""" +def should_defer_inbound_schedule_run(task: ScheduleTask, step_logs: list | None) -> bool: + """仅当独立入站 job 成功写入 trigger 后延后终态,避免影响库存 job 判断。""" return bool( task.schedule_type == 'platform_job' and normalize_platform_api_path(task.platform_api_path) == INBOUND_RPA_JOB_KEY - and any(isinstance(row, dict) and row.get('status') == AWAITING_RECEIPT_RPA_CALLBACK_STATUS for row in step_logs or []) + and any(isinstance(row, dict) and row.get('status') == AWAITING_INBOUND_RPA_CALLBACK_STATUS for row in step_logs or []) ) -def is_awaiting_receipt_rpa_schedule_run(run: ScheduleRun | None) -> bool: - """判断 run 是否为独立收料 callback 等待态,供 worker 启动恢复时保护。""" +def is_awaiting_inbound_rpa_schedule_run(run: ScheduleRun | None) -> bool: + """判断 run 是否为独立入站 callback 等待态,供 worker 启动恢复时保护。""" summary = run.response_summary_json if run is not None and isinstance(run.response_summary_json, dict) else {} - return bool(run is not None and run.status == 'running' and summary.get('awaiting_receipt_rpa')) + return bool(run is not None and run.status == 'running' and summary.get('awaiting_inbound_rpa')) -def apply_deferred_receipt_schedule_run_state( +def apply_deferred_inbound_schedule_run_state( run: ScheduleRun, task: ScheduleTask, *, total_count: int, details: list[dict], errors: list[str], step_logs: list[dict], ) -> ScheduleRun: - """将收料 run 保持为 awaiting callback,终态由所有收料单元回调完成后专用服务写入。""" + """将收料 run 保持为 awaiting callback,终态由所有入站单元回调完成后专用服务写入。""" run.status = 'running' run.started_at = run.started_at or datetime.utcnow() run.total_count = total_count @@ -118,18 +118,18 @@ def apply_deferred_receipt_schedule_run_state( run.skipped_count = 0 run.finished_at = None run.step_logs = step_logs - run.response_summary_json = {'awaiting_receipt_rpa': True, 'pending_details': details, 'errors': errors[:20]} + run.response_summary_json = {'awaiting_inbound_rpa': True, 'pending_details': details, 'errors': errors[:20]} db.session.commit() return run -def refresh_receipt_schedule_run_progress(schedule_run_id: int) -> dict: +def refresh_inbound_schedule_run_progress(schedule_run_id: int) -> dict: """ - 收料单元每笔回调后回写排程 run 进度计数(非终态,对齐库存 inventory-batch-progress)。 + 入站单元每笔回调后回写排程 run 进度计数(非终态,对齐库存 inventory-batch-progress)。 - 核心逻辑:仅在 awaiting_receipt_rpa 时,按已终态单元聚合 success/empty/failed 写入 + 核心逻辑:仅在 awaiting_inbound_rpa 时,按已终态单元聚合 success/empty/failed 写入 ScheduleRun 计数与 response_summary_json.progress;不改 status/finished_at, - 终态仍由 finalize_receipt_schedule_run_if_complete 负责。 + 终态仍由 finalize_inbound_schedule_run_if_complete 负责。 Args: schedule_run_id: 排程执行记录主键。 @@ -141,8 +141,8 @@ def refresh_receipt_schedule_run_progress(schedule_run_id: int) -> dict: if run is None: return {'updated': False, 'reason': 'schedule_run_not_found'} summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} - if run.status != 'running' or not summary.get('awaiting_receipt_rpa'): - return {'updated': False, 'reason': 'not_awaiting_receipt_callback'} + if run.status != 'running' or not summary.get('awaiting_inbound_rpa'): + return {'updated': False, 'reason': 'not_awaiting_inbound_callback'} units = FreightRpaInboundUnitRun.query.filter_by(schedule_run_id=run.id).all() success_count = sum(unit.status == 'success' for unit in units) @@ -173,11 +173,11 @@ def refresh_receipt_schedule_run_progress(schedule_run_id: int) -> dict: } -def report_receipt_batch_progress(payload: dict) -> dict: +def report_inbound_batch_progress(payload: dict) -> dict: """ - Worker 每完成一笔收料导出后的实时进度回写(非终态,对齐 inventory-batch-progress)。 + Worker 每完成一笔入站导出后的实时进度回写(非终态,对齐 inventory-batch-progress)。 - 核心逻辑:校验 schema + schedule_run_id;仅 awaiting_receipt_rpa 时抬升 + 核心逻辑:校验 schema + schedule_run_id;仅 awaiting_inbound_rpa 时抬升 ScheduleRun 计数;最终以 unit 终态回调 + finalize 为准。 Args: @@ -199,8 +199,8 @@ def report_receipt_batch_progress(payload: dict) -> dict: if run is None: return {'updated': False, 'reason': 'schedule_run_not_found'} summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} - if run.status != 'running' or not summary.get('awaiting_receipt_rpa'): - return {'updated': False, 'reason': 'not_awaiting_receipt_callback'} + if run.status != 'running' or not summary.get('awaiting_inbound_rpa'): + return {'updated': False, 'reason': 'not_awaiting_inbound_callback'} incoming = { 'success_count': max(0, int(payload.get('success_count') or 0)), @@ -228,9 +228,9 @@ def report_receipt_batch_progress(payload: dict) -> dict: } -def mark_receipt_unit_processing(payload: dict) -> dict: +def mark_inbound_unit_processing(payload: dict) -> dict: """ - Worker 开始导出某收料单元时标记 processing(对齐库存 claimed / rpa_exporting)。 + Worker 开始导出某入站单元时标记 processing(对齐库存 claimed / rpa_exporting)。 核心逻辑:仅 awaiting_rpa → processing;已终态或已 processing 幂等返回。 """ @@ -247,27 +247,27 @@ def mark_receipt_unit_processing(payload: dict) -> dict: if unit.status == 'processing': return {'updated': True, 'status': 'processing', 'idempotent': True} unit.status = 'processing' - # started_at 是收料超时对账的活动锚(_receipt_last_activity):在飞单元必须有 + # started_at 是入站超时对账的活动锚(_inbound_last_activity):在飞单元必须有 # 开始时间,否则长静默批次无法区分"在跑"与"worker 已死"。 unit.started_at = datetime.utcnow() db.session.commit() if unit.schedule_run_id: - refresh_receipt_schedule_run_progress(unit.schedule_run_id) + refresh_inbound_schedule_run_progress(unit.schedule_run_id) return {'updated': True, 'status': 'processing', 'unit_run_id': unit.id} -def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict: +def finalize_inbound_schedule_run_if_complete(schedule_run_id: int) -> dict: """ 当收料 run 的全部单元已回调后写入独立排程终态,不读取库存回调结果。 - 核心逻辑:聚合单元计数 → 预生成原始收料 ZIP 写入 summary → 企微发 textcard+单 ZIP。 + 核心逻辑:聚合单元计数 → 预生成原始入站 ZIP 写入 summary → 企微发 textcard+单 ZIP。 """ run = db.session.get(ScheduleRun, schedule_run_id) if run is None: return {'finalized': False, 'reason': 'schedule_run_not_found'} 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'} + if not summary.get('awaiting_inbound_rpa'): + return {'finalized': False, 'reason': 'not_awaiting_inbound_callback'} 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): @@ -284,8 +284,8 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict: run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed' run.error_message = '; '.join(filter(None, (unit.error_message for unit in units if unit.status == 'failed')))[:2000] or None - # [STEP] 对齐库存 finalize:终态前生成收料汇总 Excel,企微在 textcard+ZIP 之外多发一条 [文件] 消息。 - register_receipt_rpa_excel_headers() + # [STEP] 对齐库存 finalize:终态前生成入站汇总 Excel,企微在 textcard+ZIP 之外多发一条 [文件] 消息。 + register_inbound_rpa_excel_headers() header_order, header_labels = resolve_schedule_header(INBOUND_RPA_JOB_KEY) excel_export_ok = True excel_data, excel_name, excel_size = None, None, 0 @@ -300,49 +300,49 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict: 'failed_count': failed_count, 'duration_ms': run.duration_ms, }, - details=_build_receipt_finalize_details(units), + details=_build_inbound_finalize_details(units), header_order=header_order, header_labels=header_labels, ) except Exception as excel_exc: excel_export_ok = False current_app.logger.error( - '[schedule-run] receipt RPA excel export failed for run %s: %s', run.run_no, excel_exc, + '[schedule-run] inbound RPA excel export failed for run %s: %s', run.run_no, excel_exc, ) # 对齐库存:全成功批次的 Excel 失败要降级,不得让收件人误以为一切正常。 if run.status == 'success': run.status = 'partial_failed' 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_rpa_inbound_archive import receipt_rpa_result_excel_name + # 企微/下载展示名:入站RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。 + from app.services.schedule.freight_rpa_inbound_archive import inbound_rpa_result_excel_name - excel_name = receipt_rpa_result_excel_name(run) + excel_name = inbound_rpa_result_excel_name(run) run.excel_file_data = excel_data run.excel_file_name = excel_name if excel_data else None run.excel_file_size = excel_size or 0 - # [STEP] 对齐库存:终态前预生成原始收料 ZIP,企微只发一个包。 + # [STEP] 对齐库存:终态前预生成原始入站 ZIP,企微只发一个包。 archive_summary = { - 'raw_receipt_zip_available': False, - 'raw_receipt_zip_path': None, - 'raw_receipt_file_count': 0, - 'raw_receipt_file_ids': [], - 'raw_receipt_zip_size': 0, + 'raw_inbound_zip_available': False, + 'raw_inbound_zip_path': None, + 'raw_inbound_file_count': 0, + 'raw_inbound_file_ids': [], + 'raw_inbound_zip_size': 0, } try: - from app.services.schedule.freight_rpa_inbound_archive import persist_receipt_rpa_raw_zip_archive + from app.services.schedule.freight_rpa_inbound_archive import persist_inbound_rpa_raw_zip_archive - archive_summary = persist_receipt_rpa_raw_zip_archive(run) + archive_summary = persist_inbound_rpa_raw_zip_archive(run) except Exception as archive_exc: current_app.logger.error( - '[schedule-run] receipt RPA zip archive failed for run %s: %s', + '[schedule-run] inbound RPA zip archive failed for run %s: %s', run.run_no, archive_exc, ) run.response_summary_json = { **summary, - 'awaiting_receipt_rpa': False, + 'awaiting_inbound_rpa': False, 'success_count': success_count, 'empty_count': skipped_count, 'failed_count': failed_count, @@ -351,7 +351,7 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict: **archive_summary, } db.session.commit() - # 通知与库存 RPA 完全同构:run 终态后走通用排程出口一次性发 textcard+收料 ZIP。 + # 通知与库存 RPA 完全同构:run 终态后走通用排程出口一次性发 textcard+入站 ZIP。 try: task = run.task if task is not None and task.notify_enabled: @@ -360,20 +360,20 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict: _notify_schedule_run_wecom(task, run) db.session.commit() except Exception as wecom_exc: - current_app.logger.error('[schedule-run] receipt RPA wecom notify failed: %s', wecom_exc) + current_app.logger.error('[schedule-run] inbound RPA wecom notify failed: %s', wecom_exc) return {'finalized': True, 'status': run.status} -def _receipt_timeout_seconds() -> int: - """读取收料回调等待上限;超时只标记失败,不会自动重试或重发。""" +def _inbound_timeout_seconds() -> int: + """读取入站回调等待上限;超时只标记失败,不会自动重试或重发。""" try: return max(60, int(current_app.config.get('FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS', 900))) except (TypeError, ValueError): return 900 -def is_freight_receipt_rpa_task(task: ScheduleTask | None) -> bool: - """识别独立收料 RPA 排程,避免超时回收影响库存或其他平台任务。""" +def is_freight_inbound_rpa_task(task: ScheduleTask | None) -> bool: + """识别独立入站 RPA 排程,避免超时回收影响库存或其他平台任务。""" return bool( task and task.schedule_type == 'platform_job' @@ -381,7 +381,7 @@ def is_freight_receipt_rpa_task(task: ScheduleTask | None) -> bool: ) -def _receipt_last_activity(run: ScheduleRun, units: list[FreightRpaInboundUnitRun]) -> datetime: +def _inbound_last_activity(run: ScheduleRun, units: list[FreightRpaInboundUnitRun]) -> datetime: """收料 run 的最后活动锚:run 开始时间与全部单元 started/finished 时间的最大值。 语义为「笔间静默」:worker 每开始/完成一笔都会推进锚点,锚点静默超过 @@ -398,18 +398,18 @@ def _receipt_last_activity(run: ScheduleRun, units: list[FreightRpaInboundUnitRu return max(stamps) -def _fail_receipt_unit_with_timeout( +def _fail_inbound_unit_with_timeout( unit: FreightRpaInboundUnitRun, *, now: datetime, timeout_seconds: int, run_no: str | None = None, ) -> None: - """单个收料单元回调超时收口为失败并写审计(run 级与孤儿级回收共用的唯一实现)。 + """单个入站单元回调超时收口为失败并写审计(run 级与孤儿级回收共用的唯一实现)。 核心逻辑:错误码/错误文案/审计事件三者的单一事实来源——run 级扫描与孤儿 单元扫描共用本函数收口单元,防止两条路径语义漂移。只改单元不 commit, 事务归属调用方。 Args: - unit: 待收口的非终态收料单元。 + unit: 待收口的非终态入站单元。 now: 收口时刻(同批单元共享同一时间戳)。 timeout_seconds: 超时窗(写入错误文案与审计 metadata)。 run_no: 所属排程 run 号(run 级回收传实;孤儿单元无排程,保持 None)。 @@ -418,8 +418,8 @@ def _fail_receipt_unit_with_timeout( """ before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message} unit.status = 'failed' - unit.error_code = 'RPA.RECEIPT_CALLBACK_TIMEOUT' - unit.error_message = f'Receipt RPA callback timed out after {timeout_seconds} seconds' + unit.error_code = 'RPA.INBOUND_CALLBACK_TIMEOUT' + unit.error_message = f'Inbound RPA callback timed out after {timeout_seconds} seconds' unit.finished_at = now append_shipping_audit_event( event_type='shipping_inbound_rpa_callback_timeout', aggregate_type='shipping_inbound_unit', @@ -430,46 +430,46 @@ def _fail_receipt_unit_with_timeout( ) -def _recover_stale_receipt_run(run: ScheduleRun, *, cutoff: datetime, timeout_seconds: int) -> bool: - """将无回调的独立收料运行收口为失败,保留其单元与触发审计事实。 +def _recover_stale_inbound_run(run: ScheduleRun, *, cutoff: datetime, timeout_seconds: int) -> bool: + """将无回调的独立入站运行收口为失败,保留其单元与触发审计事实。 - 截止判据为最后活动锚(_receipt_last_activity)而非 run.started_at—— + 截止判据为最后活动锚(_inbound_last_activity)而非 run.started_at—— 串行长批次(>timeout)只要仍有笔间活动就不得被误杀。 """ summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} - if not summary.get('awaiting_receipt_rpa') or run.status != 'running' or not run.started_at: + if not summary.get('awaiting_inbound_rpa') or run.status != 'running' or not run.started_at: return False task = run.task or db.session.get(ScheduleTask, run.schedule_task_id) - if not is_freight_receipt_rpa_task(task): + if not is_freight_inbound_rpa_task(task): return False units = FreightRpaInboundUnitRun.query.filter_by(schedule_run_id=run.id).all() - if _receipt_last_activity(run, units) > cutoff: + if _inbound_last_activity(run, units) > cutoff: return False now = datetime.utcnow() pending = [unit for unit in units if unit.status in {'queued', 'awaiting_rpa', 'processing'}] for unit in pending: - _fail_receipt_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds, run_no=run.run_no) + _fail_inbound_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds, run_no=run.run_no) run.status = 'failed' run.finished_at = now run.duration_ms = int((now - run.started_at).total_seconds() * 1000) run.failed_count = len(pending) or max(1, int(run.failed_count or 0)) - run.error_message = f'收料 RPA 回调等待超时({timeout_seconds} 秒)' + run.error_message = f'入站 RPA 回调等待超时({timeout_seconds} 秒)' run.step_logs = [*(run.step_logs or []), { - 'step': 'freight_receipt_rpa', 'status': 'failed', + 'step': 'freight_inbound_rpa', 'status': 'failed', 'detail': {'message': run.error_message, 'timeout_seconds': timeout_seconds}, }] - run.response_summary_json = {**summary, 'awaiting_receipt_rpa': False, 'recovered_reason': 'receipt_rpa_callback_timeout'} + run.response_summary_json = {**summary, 'awaiting_inbound_rpa': False, 'recovered_reason': 'inbound_rpa_callback_timeout'} return True -def recover_stale_receipt_rpa_schedule_runs(task: ScheduleTask) -> int: - """在同一收料排程开始前回收超时运行,解除后续 Cron/手动执行的互斥。""" - if not is_freight_receipt_rpa_task(task): +def recover_stale_inbound_rpa_schedule_runs(task: ScheduleTask) -> int: + """在同一入站排程开始前回收超时运行,解除后续 Cron/手动执行的互斥。""" + if not is_freight_inbound_rpa_task(task): return 0 - timeout_seconds = _receipt_timeout_seconds() + timeout_seconds = _inbound_timeout_seconds() cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds) recovered = sum( - _recover_stale_receipt_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds) + _recover_stale_inbound_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds) for run in ScheduleRun.query.filter_by(schedule_task_id=task.id, status='running').all() ) if recovered: @@ -477,12 +477,12 @@ def recover_stale_receipt_rpa_schedule_runs(task: ScheduleTask) -> int: return recovered -def recover_all_stale_receipt_rpa_schedule_runs() -> int: - """Worker 启动时扫描全部超时收料回调,避免重启后运行永久卡住。""" - timeout_seconds = _receipt_timeout_seconds() +def recover_all_stale_inbound_rpa_schedule_runs() -> int: + """Worker 启动时扫描全部超时入站回调,避免重启后运行永久卡住。""" + timeout_seconds = _inbound_timeout_seconds() cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds) recovered = sum( - _recover_stale_receipt_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds) + _recover_stale_inbound_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds) for run in ScheduleRun.query.filter_by(status='running').all() ) if recovered: @@ -490,30 +490,30 @@ def recover_all_stale_receipt_rpa_schedule_runs() -> int: return recovered -def recover_all_stale_orphan_receipt_units() -> int: - """回收按需触发(无排程绑定)的超时收料单元,解除来源投影永久 fetching。 +def recover_all_stale_orphan_inbound_units() -> int: + """回收按需触发(无排程绑定)的超时入站单元,解除来源投影永久 fetching。 【AI 触发时机】仅由排程队列每轮领取维护(queue_service)调用。调拨工作台 重试/自动调拨补抓创建的单元 schedule_run_id 为 NULL(见 inbound_trigger_service), - 不在 run 级扫描(recover_all_stale_receipt_rpa_schedule_runs 按 run 遍历)范围内; + 不在 run 级扫描(recover_all_stale_inbound_rpa_schedule_runs 按 run 遍历)范围内; Worker 网页异常关闭后回调永不到达,若不回收则来源投影(source_file_status) 永久 fetching、前端重试按钮永久锁死(2026-10-16 事故根因)。 核心逻辑:[STEP 1] 扫 schedule_run_id IS NULL、状态非终态、活动锚 (coalesce(started_at, created_at):与 run 级同为活动锚思想,单元未被领取 - 无 started_at 时以 created_at 兜底;注意 run 级 _receipt_last_activity 是 + 无 started_at 时以 created_at 兜底;注意 run 级 _inbound_last_activity 是 笔间静默口径、刻意不含 created_at,两者语义不同)超过 - FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS 的单元;admin 单元重试(retry_receipt_rpa_unit) + FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS 的单元;admin 单元重试(retry_inbound_rpa_unit) 原样复制 schedule_run_id,其 retry 单元同为孤儿,一并覆盖。 - [STEP 2] 逐单元经 _fail_receipt_unit_with_timeout 收口(failed + - RPA.RECEIPT_CALLBACK_TIMEOUT + 审计,与 run 级扫描同一实现零漂移); + [STEP 2] 逐单元经 _fail_inbound_unit_with_timeout 收口(failed + + RPA.INBOUND_CALLBACK_TIMEOUT + 审计,与 run 级扫描同一实现零漂移); 绝不自动重试或重发——恢复走调拨工作台显式「重试 RPA」 (与 recover_stale_waiting_source_jobs 口径一致)。 Returns: 本次回收的单元数。 """ - timeout_seconds = _receipt_timeout_seconds() + timeout_seconds = _inbound_timeout_seconds() cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds) orphans = ( FreightRpaInboundUnitRun.query @@ -528,6 +528,6 @@ def recover_all_stale_orphan_receipt_units() -> int: return 0 now = datetime.utcnow() for unit in orphans: - _fail_receipt_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds) + _fail_inbound_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds) db.session.commit() return len(orphans) diff --git a/backend/app/services/schedule/freight_rpa_inbound_job.py b/backend/app/services/schedule/freight_rpa_inbound_job.py index e1593f5b..51250d56 100644 --- a/backend/app/services/schedule/freight_rpa_inbound_job.py +++ b/backend/app/services/schedule/freight_rpa_inbound_job.py @@ -1,12 +1,12 @@ """ 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、 +用途:独立入站 RPA 排程——按勾选来源站点一对一冻结执行单元并写 inbound trigger。 +依赖:freight_rpa.inbound.trigger_io.write_inbound_export_batch_trigger、assert_inbound_rpa_worker_ready、 FreightRpaSource / FreightRpaInboundReportConfig / FreightRpaInboundUnitRun、 ScheduleTask/Run。 逻辑:job_registry 的 freight-rpa-inbound 调用本 handler;写 trigger 前 fail-fast; - 口径与库存排程一致(选中 N 源 → N unit),query_parameters 原样下发。 + 口径与 onhand 排程一致(选中 N 源 → N unit),query_parameters 原样下发。 """ from __future__ import annotations @@ -20,16 +20,16 @@ from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaIn 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, - assert_receipt_rpa_worker_ready, + assert_inbound_rpa_worker_ready, ) INBOUND_RPA_JOB_KEY = 'freight-rpa-inbound' -AWAITING_RECEIPT_RPA_CALLBACK_STATUS = 'awaiting_receipt_rpa_callback' +AWAITING_INBOUND_RPA_CALLBACK_STATUS = 'awaiting_inbound_rpa_callback' ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]] def _wanted_source_codes(task: ScheduleTask) -> set[str]: - """提取结构化 source_codes;留空代表全部具备有效收料配置的站点。""" + """提取结构化 source_codes;留空代表全部具备有效入站配置的站点。""" params = task.job_params if isinstance(task.job_params, dict) else {} values = params.get('source_codes') or [] if isinstance(values, str): @@ -38,7 +38,7 @@ def _wanted_source_codes(task: ScheduleTask) -> set[str]: def _eligible_sources(task: ScheduleTask) -> list[tuple[FreightRpaSource, FreightRpaInboundReportConfig]]: - """读取已启用且已配置收料报表的站点;不依赖库存报表路径、解析绑定或 Warehouse 条件。""" + """读取已启用且已配置入站报表的站点;不依赖库存报表路径、解析绑定或 Warehouse 条件。""" wanted = _wanted_source_codes(task) rows = db.session.query(FreightRpaSource, FreightRpaInboundReportConfig).join( FreightRpaInboundReportConfig, FreightRpaInboundReportConfig.source_id == FreightRpaSource.id, @@ -47,7 +47,7 @@ def _eligible_sources(task: ScheduleTask) -> list[tuple[FreightRpaSource, Freigh def _copy_query_parameters(config: FreightRpaInboundReportConfig) -> list[dict[str, Any]]: - """浅拷贝收料查询条件原样入快照;空列表表示 Worker 使用页面默认、不填 Warehouse。""" + """浅拷贝入站查询条件原样入快照;空列表表示 Worker 使用页面默认、不填 Warehouse。""" return [ dict(item) for item in (config.query_parameters_json or []) if isinstance(item, dict) @@ -57,8 +57,8 @@ def _copy_query_parameters(config: FreightRpaInboundReportConfig) -> list[dict[s def _build_unit( source: FreightRpaSource, config: FreightRpaInboundReportConfig, schedule_run_id: int, ) -> FreightRpaInboundUnitRun: - """冻结可审计的收料执行单元(一源一单元);DBS 日期字段不进入查询快照。""" - callback_id = f'receipt:{uuid.uuid4().hex}' + """冻结可审计的入站执行单元(一源一单元);DBS 日期字段不进入查询快照。""" + callback_id = f'inbound:{uuid.uuid4().hex}' snapshot = { 'config_id': config.id, 'config_version': config.config_version, 'connector_type': source.connector_type, 'report_path_json': config.report_path_json or {}, 'query_parameters_json': _copy_query_parameters(config), @@ -98,27 +98,27 @@ def _serialize_trigger_unit(unit: FreightRpaInboundUnitRun) -> dict[str, Any]: } -def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: +def run_freight_rpa_inbound_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: """ - 写独立收料 trigger;每个勾选站点对应一个执行单元(与库存 RPA 同口径)。 + 写独立入站 trigger;每个勾选站点对应一个执行单元(与 onhand RPA 同口径)。 - 核心逻辑:写 trigger 前 assert_receipt_rpa_worker_ready;离线立即 failed, - 不创建 unit、不进入 awaiting_receipt_rpa。 + 核心逻辑:写 trigger 前 assert_inbound_rpa_worker_ready;离线立即 failed, + 不创建 unit、不进入 awaiting_inbound_rpa。 """ units: list[FreightRpaInboundUnitRun] = [ _build_unit(source, config, run.id) for source, config in _eligible_sources(task) ] if not units: - return 0, 0, 0, 1, [], ['no enabled receipt report sources'], [{'step': 'freight_receipt_rpa', 'status': 'skipped'}] + return 0, 0, 0, 1, [], ['no enabled inbound report sources'], [{'step': 'freight_inbound_rpa', 'status': 'skipped'}] # [STEP] 写 trigger / 入库 unit 前 fail-fast,避免 Worker 离线干等到超时。 try: - assert_receipt_rpa_worker_ready() + assert_inbound_rpa_worker_ready() except ServiceUnavailableError as exc: message = str(exc.message or RPA_WORKER_OFFLINE_MESSAGE) detail_message = str((exc.details or {}).get('detail_message') or message) return len(units), 0, len(units), 0, [], [detail_message], [{ - 'step': 'freight_receipt_rpa', + 'step': 'freight_inbound_rpa', 'status': 'failed', 'detail': { 'message': message, @@ -134,9 +134,9 @@ def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc trigger_units = [_serialize_trigger_unit(unit) for unit in units] except RuntimeError as exc: for unit in units: - unit.status = 'failed'; unit.error_code = 'RPA.RECEIPT_PROFILE_UNAVAILABLE'; unit.error_message = str(exc) + unit.status = 'failed'; unit.error_code = 'RPA.INBOUND_PROFILE_UNAVAILABLE'; unit.error_message = str(exc) db.session.commit() - return len(units), 0, len(units), 0, [], [str(exc)], [{'step': 'freight_receipt_rpa', 'status': 'failed'}] + return len(units), 0, len(units), 0, [], [str(exc)], [{'step': 'freight_inbound_rpa', 'status': 'failed'}] for unit, trigger_unit in zip(units, trigger_units): unit.trigger_snapshot_json = trigger_unit trigger_path = write_inbound_export_batch_trigger(run.run_no, trigger_units, { @@ -144,13 +144,13 @@ def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc }) if not trigger_path: for unit in units: - unit.status = 'failed'; unit.error_code = 'RPA.RECEIPT_TRIGGER_UNAVAILABLE'; unit.error_message = 'receipt trigger directory unavailable' + unit.status = 'failed'; unit.error_code = 'RPA.INBOUND_TRIGGER_UNAVAILABLE'; unit.error_message = 'inbound trigger directory unavailable' db.session.commit() - return len(units), 0, len(units), 0, [], ['receipt trigger directory unavailable'], [{'step': 'freight_receipt_rpa', 'status': 'failed'}] + return len(units), 0, len(units), 0, [], ['inbound trigger directory unavailable'], [{'step': 'freight_inbound_rpa', 'status': 'failed'}] details = [{'source_code': unit.source_code, 'warehouse_id': unit.warehouse_id, 'callback_id': unit.callback_id} for unit in units] run.api_request_json = {'run_no': run.run_no, 'trigger_path': trigger_path, 'source_codes': sorted({unit.source_code for unit in units})} db.session.commit() return len(units), 0, 0, 0, details, [], [{ - 'step': 'freight_receipt_rpa', 'status': AWAITING_RECEIPT_RPA_CALLBACK_STATUS, + 'step': 'freight_inbound_rpa', 'status': AWAITING_INBOUND_RPA_CALLBACK_STATUS, 'detail': {'trigger_path': trigger_path, 'unit_count': len(units)}, }] diff --git a/backend/app/services/schedule/freight_rpa_inbound_retention.py b/backend/app/services/schedule/freight_rpa_inbound_retention.py index a117bce4..c8bd2734 100644 --- a/backend/app/services/schedule/freight_rpa_inbound_retention.py +++ b/backend/app/services/schedule/freight_rpa_inbound_retention.py @@ -11,8 +11,13 @@ from __future__ import annotations 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_rpa_inbound_retention_schedule +def run_freight_rpa_inbound_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]: + """排程壳:委托 freight_rpa.inbound.report_archive 执行三年保留清理(行为不变)。 - return run_freight_rpa_inbound_retention_schedule(task, run) + 核心逻辑:本函数与 archive 同名;必须 as 别名导入,避免递归调用自身。 + """ + from app.services.freight_rpa.inbound.report_archive import ( + run_freight_rpa_inbound_retention_schedule as _run_inbound_archive_retention, + ) + + return _run_inbound_archive_retention(task, run) diff --git a/backend/app/services/schedule/freight_rpa_outbound_archive.py b/backend/app/services/schedule/freight_rpa_outbound_archive.py new file mode 100644 index 00000000..95b55d2b --- /dev/null +++ b/backend/app/services/schedule/freight_rpa_outbound_archive.py @@ -0,0 +1,311 @@ +""" +backend/app/services/schedule/freight_rpa_outbound_archive.py + +用途:货代出站 RPA 排程 run 的原始出站 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。 +依赖:ScheduleRun、FreightRpaOutboundReportFile / FreightRpaOutboundUnitRun、 + file_asset_storage、timezone_util、freight_rpa_outbound_finalize.is_freight_outbound_rpa_task。 +逻辑:finalize 调用 persist_outbound_rpa_raw_zip_archive 写入磁盘与 summary; + 企微/下载展示名用「出站RPA-日期-时刻-出站」;包内条目 `{序号}_{source_code}.xlsx`; + warehouse_id / file_id 只写在 manifest.json;磁盘归档键为 {run_no}.zip。 +""" + +from __future__ import annotations + +import json +import re +import zipfile +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +from flask import current_app + +from app.core.errors import NotFoundError +from app.models import ScheduleRun, FreightRpaOutboundReportFile, FreightRpaOutboundUnitRun +from app.services.file_assets.storage import file_asset_storage +from app.services.schedule.freight_rpa_outbound_finalize import is_freight_outbound_rpa_task +from app.services.schedule.timezone_util import resolve_schedule_tzinfo + +_RAW_ZIP_NOT_FOUND_MESSAGE = '原始出站包不存在,请重新执行或联系管理员' + +_EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = { + 'raw_outbound_zip_available': False, + 'raw_outbound_zip_path': None, + 'raw_outbound_file_count': 0, + 'raw_outbound_file_ids': [], + 'raw_outbound_zip_size': 0, +} + + +def get_outbound_archive_dir() -> str: + """ + 返回出站 RPA 原始 ZIP 归档根目录(自动创建)。 + + 核心逻辑:优先读 Flask config;值为 None/空时回落到 Config 默认路径, + 避免 Path(None) 在 finalize 阶段把整次 ZIP 归档打成空 summary。 + """ + configured = '' + if current_app: + raw = current_app.config.get('FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR') + configured = str(raw).strip() if raw is not None else '' + if not configured: + from app.core.config.settings import Config + + configured = str(Config.FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR or '').strip() + archive_dir = Path(configured) + archive_dir.mkdir(parents=True, exist_ok=True) + return str(archive_dir) + + +def _attachment_when_from_run(run: ScheduleRun) -> datetime: + """ + 推导企微/下载展示名中的当地时刻。 + + 核心逻辑:与库存归档同构——started_at → created_at → finished_at → + 解析 RUN{yyyyMMddHHmmss}* → utcnow;再转到任务 schedule_timezone。 + """ + when_utc: datetime | None = None + for value in (run.started_at, run.created_at, run.finished_at): + if isinstance(value, datetime): + when_utc = value + break + if when_utc is None: + match = re.match(r'^RUN(\d{14})', str(run.run_no or '').strip()) + if match: + try: + when_utc = datetime.strptime(match.group(1), '%Y%m%d%H%M%S') + except ValueError: + when_utc = None + if when_utc is None: + when_utc = datetime.now(timezone.utc).replace(tzinfo=None) + + task = getattr(run, 'task', None) + tz_name = getattr(task, 'schedule_timezone', None) if task is not None else None + tz = resolve_schedule_tzinfo(tz_name) + if when_utc.tzinfo is None: + when_utc = when_utc.replace(tzinfo=timezone.utc) + return when_utc.astimezone(tz) + + +def outbound_rpa_attachment_stem(run: ScheduleRun) -> str: + """ + 出站 RPA 企微附件共用前缀:出站RPA-{yyyyMMdd}-{HHmm}(业务时区当地时间)。 + + Args: + run: 排程执行记录。 + + Returns: + 不含角色后缀与扩展名的展示名前缀。 + """ + when = _attachment_when_from_run(run) + return f"出站RPA-{when.strftime('%Y%m%d')}-{when.strftime('%H%M')}" + + +def outbound_raw_zip_download_name(run: ScheduleRun) -> str: + """ + 出站 ZIP 的企微/浏览器下载展示名。 + + 核心逻辑:磁盘归档仍为 {run_no}.zip;本函数只影响 Content-Disposition 与企微 filename。 + """ + return f'{outbound_rpa_attachment_stem(run)}-出站.zip' + + +def outbound_rpa_result_excel_name(run: ScheduleRun) -> str: + """出站 RPA 结果 Excel 的企微/下载展示名(对齐入站 inbound_rpa_result_excel_name)。""" + return f'{outbound_rpa_attachment_stem(run)}-结果.xlsx' + + +def _outbound_raw_zip_archive_path(run_no: str) -> Path: + """磁盘归档路径:/.zip。""" + return Path(get_outbound_archive_dir()) / f'{run_no}.zip' + + +def _iter_packable_outbound_files(run: ScheduleRun): + """ + 遍历该 run 下可打包的出站归档文件。 + + 核心逻辑:join unit_run,过滤 archive_deleted_at 为空;按 file id 升序稳定序号。 + + Yields: + FreightRpaOutboundReportFile: 可从 MinIO 读取的归档记录。 + """ + if not is_freight_outbound_rpa_task(getattr(run, 'task', None)): + return + rows = ( + FreightRpaOutboundReportFile.query.join( + FreightRpaOutboundUnitRun, + FreightRpaOutboundReportFile.unit_run_id == FreightRpaOutboundUnitRun.id, + ) + .filter( + FreightRpaOutboundUnitRun.schedule_run_id == run.id, + FreightRpaOutboundReportFile.archive_deleted_at.is_(None), + ) + .order_by(FreightRpaOutboundReportFile.id.asc()) + .all() + ) + for report_file in rows: + yield report_file + + +def outbound_raw_zip_available_from_summary(summary: dict[str, Any] | None) -> bool: + """ + 从 response_summary_json 读取原始出站 ZIP 是否可下载。 + + 核心逻辑:列表序列化只读 summary,不查库、不访问磁盘。 + """ + if not isinstance(summary, dict): + return False + return bool(summary.get('raw_outbound_zip_available')) + + +def persist_outbound_rpa_raw_zip_archive(run: ScheduleRun) -> dict[str, Any]: + """ + finalize 阶段预生成原始出站 ZIP 归档并返回 summary 字段。 + + 核心逻辑:从 MinIO 拉取各单元归档字节 → 写入 /.zip + (含 manifest.json);无可用文件时返回 raw_outbound_zip_available=false。 + + Args: + run: 出站 RPA ScheduleRun。 + + Returns: + dict: raw_outbound_zip_available / path / file_count / file_ids / zip_size。 + """ + packable_files = list(_iter_packable_outbound_files(run)) + if not packable_files: + return dict(_EMPTY_ARCHIVE_SUMMARY) + + archive_path = _outbound_raw_zip_archive_path(run.run_no) + files_manifest: list[dict[str, Any]] = [] + + with zipfile.ZipFile(archive_path, 'w', compression=zipfile.ZIP_DEFLATED) as archive: + for zip_index, report_file in enumerate(packable_files, start=1): + unit = report_file.unit_run + source_code = str(getattr(unit, 'source_code', None) or '').strip() + warehouse_id = str(getattr(unit, 'warehouse_id', None) or '').strip() + original_name = str(report_file.original_filename or '').strip() or 'outbound.xlsx' + suffix = Path(original_name).suffix or '.xlsx' + entry_name = _build_zip_entry_name( + index=zip_index, + source_code=source_code, + warehouse_id=warehouse_id, + original_suffix=suffix, + ) + # [STEP] 出站归档在 MinIO:读字节后 writestr,不依赖本地 storage_path。 + data = file_asset_storage.get_bytes(report_file.storage_key) + archive.writestr(entry_name, data) + files_manifest.append({ + 'file_id': report_file.id, + 'source_code': source_code, + 'warehouse_id': warehouse_id, + 'file_name': entry_name, + 'original_file_name': original_name, + 'sha256': report_file.sha256, + }) + + manifest = { + 'run_no': run.run_no, + 'total_count': int(run.total_count or 0), + 'success_count': int(run.success_count or 0), + 'skipped_count': int(run.skipped_count or 0), + 'failed_count': int(run.failed_count or 0), + 'files': files_manifest, + } + archive.writestr( + 'manifest.json', + json.dumps(manifest, ensure_ascii=False, indent=2), + ) + + return { + 'raw_outbound_zip_available': True, + 'raw_outbound_zip_path': str(archive_path.resolve()), + 'raw_outbound_file_count': len(files_manifest), + 'raw_outbound_file_ids': [item['file_id'] for item in files_manifest], + 'raw_outbound_zip_size': int(archive_path.stat().st_size), + } + + +def _is_allowed_outbound_archive_path(zip_path: Path) -> bool: + """ + 校验归档 ZIP 路径是否安全可下载。 + + 核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR 内。 + """ + resolved = zip_path.resolve() + if resolved.suffix.lower() != '.zip': + return False + if not resolved.is_file(): + return False + + archive_dir = Path(get_outbound_archive_dir()).resolve() + try: + resolved.relative_to(archive_dir) + except ValueError: + return False + return True + + +def resolve_outbound_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]: + """ + 解析 run 已归档的原始出站 ZIP 路径供下载接口 send_file。 + + 核心逻辑:读取 summary.raw_outbound_zip_path,校验文件存在、后缀为 .zip、 + 且真实路径位于 FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR 内;任一不满足则 404。 + + Returns: + tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。 + + Raises: + NotFoundError: summary 未标记可用、路径非法或归档文件已丢失。 + """ + summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} + if not outbound_raw_zip_available_from_summary(summary): + raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE) + + zip_path_raw = str(summary.get('raw_outbound_zip_path') or '').strip() + if not zip_path_raw: + raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE) + + zip_path = Path(zip_path_raw) + if not _is_allowed_outbound_archive_path(zip_path): + raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE) + + return zip_path.resolve(), outbound_raw_zip_download_name(run) + + +def _sanitize_zip_segment(value: str) -> str: + """ZIP 内文件名片段安全化,避免路径穿越与非法字符。""" + cleaned = re.sub(r'[^\w\-.]+', '_', str(value or '').strip()) + return cleaned or 'unknown' + + +def _zip_entry_label(*, source_code: str, warehouse_id: str) -> str: + """ + 包内短标签:优先 source_code;无则回退仓码;再否则 outbound。 + + warehouse_id / file_id 已写入 manifest.json;条目名不必再叠仓码。 + """ + source = str(source_code or '').strip() + if source: + return source + warehouse = str(warehouse_id or '').strip() + if warehouse and warehouse.lower() not in {'unknown', 'na'}: + return warehouse + return 'outbound' + + +def _build_zip_entry_name( + *, + index: int, + source_code: str, + warehouse_id: str, + original_suffix: str, +) -> str: + """ + 生成 ZIP 内单文件条目名(不含目录)。 + + 核心逻辑:`{序号}_{source_code}.{ext}`;序号保证极端撞名时仍唯一。 + """ + label = _sanitize_zip_segment(_zip_entry_label(source_code=source_code, warehouse_id=warehouse_id)) + suffix = original_suffix if original_suffix.startswith('.') else f'.{original_suffix}' + return f'{index:03d}_{label}{suffix}' diff --git a/backend/app/services/schedule/freight_rpa_outbound_finalize.py b/backend/app/services/schedule/freight_rpa_outbound_finalize.py new file mode 100644 index 00000000..7f1f45bd --- /dev/null +++ b/backend/app/services/schedule/freight_rpa_outbound_finalize.py @@ -0,0 +1,532 @@ +""" +backend/app/services/schedule/freight_rpa_outbound_finalize.py + +用途:独立出站 RPA 排程等待态收口——进度回写、全单元终态后写计数、预生成 ZIP、发企微; + 另含超时对账:排程 run 级(每轮 tick)与按需触发孤儿单元级(schedule_run_id=NULL)。 +依赖:FreightRpaOutboundUnitRun、freight_rpa_outbound_archive、scheduler_service 企微通知。 +逻辑:每笔回调 → refresh 进度计数 → 全终态时 persist ZIP → _notify_schedule_run_wecom; + 超时对账只终态化失败,绝不自动重试或重发(恢复走人工显式重试入口)。 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta +from typing import Any + +from flask import current_app +from sqlalchemy import func + +from app import db +from app.models import ScheduleRun, ScheduleTask +from app.models import FreightRpaOutboundUnitRun +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_rpa_outbound_job import AWAITING_OUTBOUND_RPA_CALLBACK_STATUS, OUTBOUND_RPA_JOB_KEY +from app.services.freight_rpa.outbound.trigger_io import SCHEMA as OUTBOUND_TRIGGER_SCHEMA +from app.services.shipping_notice.audit_service import append_shipping_audit_event + +_OUTBOUND_RPA_HEADER_ORDER = [ + "source_code", + "warehouse_id", + "connector_type", + "outbound_file_count", + "export_status", + "skip_reason", + "error_message", +] +_OUTBOUND_RPA_HEADER_LABELS = { + "source_code": "出站源", + "warehouse_id": "仓库", + "connector_type": "连接器", + "outbound_file_count": "归档文件数", + "export_status": "导出状态", + "skip_reason": "跳过原因", + "error_message": "错误原因", +} + + +def register_outbound_rpa_excel_headers() -> None: + """ + 注册货代出站 RPA 排程 Excel 列头(幂等)。 + 核心逻辑:由 schedule.__init__._register_headers_from_config 在 reload 后调用,避免被 clear 冲掉。 + """ + register_schedule_header( + OUTBOUND_RPA_JOB_KEY, + _OUTBOUND_RPA_HEADER_ORDER, + _OUTBOUND_RPA_HEADER_LABELS, + ) + + +def _build_outbound_finalize_details(units: list[FreightRpaOutboundUnitRun]) -> list[dict[str, Any]]: + """ + 出站单元 → 排程 Excel 明细行(对齐入站 finalize 的行结构)。 + + 核心逻辑:empty 归一为 skipped、cancelled 归一为 failed,与卡片计数口径一致; + 归档文件数便于与原始出站包内 {序号}_{source_code}.xlsx 条目对账。 + + Args: + units: 该 run 的全部出站单元(已全部终态)。 + + Returns: + list[dict]: 按 unit.id 升序的明细行。 + """ + rows: list[dict[str, Any]] = [] + for unit in sorted(units, key=lambda item: item.id): + status = unit.status + if status == 'empty': + export_status = 'skipped' + elif status == 'cancelled': + export_status = 'failed' + else: + export_status = status + rows.append({ + 'source_code': unit.source_code, + 'warehouse_id': unit.warehouse_id or '', + 'connector_type': unit.connector_type or '', + 'outbound_file_count': len(unit.files or []), + 'export_status': export_status, + 'skip_reason': str(unit.error_code or '') if export_status == 'skipped' else '', + 'error_message': str(unit.error_message or '')[:500] if export_status == 'failed' else '', + }) + return rows + + +def should_defer_outbound_schedule_run(task: ScheduleTask, step_logs: list | None) -> bool: + """仅当独立出站 job 成功写入 trigger 后延后终态,避免影响库存/入站 job 判断。""" + return bool( + task.schedule_type == 'platform_job' + and normalize_platform_api_path(task.platform_api_path) == OUTBOUND_RPA_JOB_KEY + and any(isinstance(row, dict) and row.get('status') == AWAITING_OUTBOUND_RPA_CALLBACK_STATUS for row in step_logs or []) + ) + + +def is_awaiting_outbound_rpa_schedule_run(run: ScheduleRun | None) -> bool: + """判断 run 是否为独立出站 callback 等待态,供 worker 启动恢复时保护。""" + summary = run.response_summary_json if run is not None and isinstance(run.response_summary_json, dict) else {} + return bool(run is not None and run.status == 'running' and summary.get('awaiting_outbound_rpa')) + + +def apply_deferred_outbound_schedule_run_state( + run: ScheduleRun, task: ScheduleTask, *, total_count: int, details: list[dict], errors: list[str], step_logs: list[dict], +) -> ScheduleRun: + """将出站 run 保持为 awaiting callback,终态由所有出站单元回调完成后专用服务写入。""" + run.status = 'running' + run.started_at = run.started_at or datetime.utcnow() + run.total_count = total_count + run.success_count = 0 + run.failed_count = 0 + run.skipped_count = 0 + run.finished_at = None + run.step_logs = step_logs + run.response_summary_json = {'awaiting_outbound_rpa': True, 'pending_details': details, 'errors': errors[:20]} + db.session.commit() + return run + + +def refresh_outbound_schedule_run_progress(schedule_run_id: int) -> dict: + """ + 出站单元每笔回调后回写排程 run 进度计数(非终态,对齐库存 inventory-batch-progress)。 + + 核心逻辑:仅在 awaiting_outbound_rpa 时,按已终态单元聚合 success/empty/failed 写入 + ScheduleRun 计数与 response_summary_json.progress;不改 status/finished_at, + 终态仍由 finalize_outbound_schedule_run_if_complete 负责。 + + Args: + schedule_run_id: 排程执行记录主键。 + + Returns: + dict: updated=True/False 及当前计数;非等待态返回 reason。 + """ + run = db.session.get(ScheduleRun, schedule_run_id) + if run is None: + return {'updated': False, 'reason': 'schedule_run_not_found'} + summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} + if run.status != 'running' or not summary.get('awaiting_outbound_rpa'): + return {'updated': False, 'reason': 'not_awaiting_outbound_callback'} + + units = FreightRpaOutboundUnitRun.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) + + # [STEP] 与库存进度同口径:只抬升计数,防乱序回调把笔数打回去。 + run.success_count = max(int(run.success_count or 0), success_count) + run.skipped_count = max(int(run.skipped_count or 0), skipped_count) + run.failed_count = max(int(run.failed_count or 0), failed_count) + if run.total_count is None or int(run.total_count or 0) < len(units): + run.total_count = len(units) + summary = dict(summary) + summary['progress'] = { + 'success_count': int(run.success_count or 0), + 'skipped_count': int(run.skipped_count or 0), + 'failed_count': int(run.failed_count or 0), + 'processing_count': sum(unit.status == 'processing' for unit in units), + 'updated_at': datetime.utcnow().isoformat(), + } + run.response_summary_json = summary + db.session.commit() + return { + 'updated': True, + 'success_count': int(run.success_count or 0), + 'skipped_count': int(run.skipped_count or 0), + 'failed_count': int(run.failed_count or 0), + } + + +def report_outbound_batch_progress(payload: dict) -> dict: + """ + Worker 每完成一笔出站导出后的实时进度回写(非终态,对齐 inventory-batch-progress)。 + + 核心逻辑:校验 schema + schedule_run_id;仅 awaiting_outbound_rpa 时抬升 + ScheduleRun 计数;最终以 unit 终态回调 + finalize 为准。 + + Args: + payload: Worker 上报的累计 success/skipped/failed 与 schedule_run_id。 + + Returns: + dict: updated / rejected 及当前计数。 + """ + if payload.get('schema_version') != OUTBOUND_TRIGGER_SCHEMA: + return {'updated': False, 'reason': 'callback_schema_invalid'} + try: + schedule_run_id = int(payload.get('schedule_run_id')) if payload.get('schedule_run_id') is not None else None + except (TypeError, ValueError): + schedule_run_id = None + if not schedule_run_id: + return {'updated': False, 'reason': 'schedule_run_id_required'} + + run = db.session.get(ScheduleRun, schedule_run_id) + if run is None: + return {'updated': False, 'reason': 'schedule_run_not_found'} + summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} + if run.status != 'running' or not summary.get('awaiting_outbound_rpa'): + return {'updated': False, 'reason': 'not_awaiting_outbound_callback'} + + incoming = { + 'success_count': max(0, int(payload.get('success_count') or 0)), + 'skipped_count': max(0, int(payload.get('skipped_count') or 0)), + 'failed_count': max(0, int(payload.get('failed_count') or 0)), + } + run.success_count = max(int(run.success_count or 0), incoming['success_count']) + run.skipped_count = max(int(run.skipped_count or 0), incoming['skipped_count']) + run.failed_count = max(int(run.failed_count or 0), incoming['failed_count']) + summary = dict(summary) + summary['progress'] = { + 'success_count': int(run.success_count or 0), + 'skipped_count': int(run.skipped_count or 0), + 'failed_count': int(run.failed_count or 0), + 'batch_run_no': str(payload.get('batch_run_no') or payload.get('run_no') or ''), + 'updated_at': datetime.utcnow().isoformat(), + } + run.response_summary_json = summary + db.session.commit() + return { + 'updated': True, + 'success_count': int(run.success_count or 0), + 'skipped_count': int(run.skipped_count or 0), + 'failed_count': int(run.failed_count or 0), + } + + +def mark_outbound_unit_processing(payload: dict) -> dict: + """ + Worker 开始导出某出站单元时标记 processing(对齐库存 claimed / rpa_exporting)。 + + 核心逻辑:仅 awaiting_rpa → processing;已终态或已 processing 幂等返回。 + """ + if payload.get('schema_version') != OUTBOUND_TRIGGER_SCHEMA: + return {'updated': False, 'reason': 'callback_schema_invalid'} + callback_id = str(payload.get('callback_id') or '').strip() + if not callback_id: + return {'updated': False, 'reason': 'callback_id_required'} + unit = FreightRpaOutboundUnitRun.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'}: + return {'updated': False, 'reason': 'already_terminal', 'status': unit.status} + if unit.status == 'processing': + return {'updated': True, 'status': 'processing', 'idempotent': True} + unit.status = 'processing' + # started_at 是出站超时对账的活动锚(_outbound_last_activity):在飞单元必须有 + # 开始时间,否则长静默批次无法区分"在跑"与"worker 已死"。 + unit.started_at = datetime.utcnow() + db.session.commit() + if unit.schedule_run_id: + refresh_outbound_schedule_run_progress(unit.schedule_run_id) + return {'updated': True, 'status': 'processing', 'unit_run_id': unit.id} + + +def finalize_outbound_schedule_run_if_complete(schedule_run_id: int) -> dict: + """ + 当出站 run 的全部单元已回调后写入独立排程终态,不读取库存/入站回调结果。 + + 核心逻辑:聚合单元计数 → 预生成原始出站 ZIP 写入 summary → 企微发 textcard+单 ZIP。 + """ + run = db.session.get(ScheduleRun, schedule_run_id) + if run is None: + return {'finalized': False, 'reason': 'schedule_run_not_found'} + summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} + if not summary.get('awaiting_outbound_rpa'): + return {'finalized': False, 'reason': 'not_awaiting_outbound_callback'} + units = FreightRpaOutboundUnitRun.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'} + 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) + run.total_count = len(units) + run.success_count = success_count + run.skipped_count = skipped_count + run.failed_count = failed_count + run.finished_at = datetime.utcnow() + run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000) if run.started_at else 0 + run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed' + run.error_message = '; '.join(filter(None, (unit.error_message for unit in units if unit.status == 'failed')))[:2000] or None + + # [STEP] 对齐入站 finalize:终态前生成出站汇总 Excel,企微在 textcard+ZIP 之外多发一条 [文件] 消息。 + register_outbound_rpa_excel_headers() + header_order, header_labels = resolve_schedule_header(OUTBOUND_RPA_JOB_KEY) + excel_export_ok = True + excel_data, excel_name, excel_size = None, None, 0 + try: + excel_data, _excel_name, excel_size = export_schedule_result_excel( + run_no=run.run_no, + summary={ + 'status': run.status, + 'total_count': len(units), + 'success_count': success_count, + 'skipped_count': skipped_count, + 'failed_count': failed_count, + 'duration_ms': run.duration_ms, + }, + details=_build_outbound_finalize_details(units), + header_order=header_order, + header_labels=header_labels, + ) + except Exception as excel_exc: + excel_export_ok = False + current_app.logger.error( + '[schedule-run] outbound RPA excel export failed for run %s: %s', run.run_no, excel_exc, + ) + # 对齐库存:全成功批次的 Excel 失败要降级,不得让收件人误以为一切正常。 + if run.status == 'success': + run.status = 'partial_failed' + 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_rpa_outbound_archive import outbound_rpa_result_excel_name + + excel_name = outbound_rpa_result_excel_name(run) + run.excel_file_data = excel_data + run.excel_file_name = excel_name if excel_data else None + run.excel_file_size = excel_size or 0 + + # [STEP] 对齐入站:终态前预生成原始出站 ZIP,企微只发一个包。 + archive_summary = { + 'raw_outbound_zip_available': False, + 'raw_outbound_zip_path': None, + 'raw_outbound_file_count': 0, + 'raw_outbound_file_ids': [], + 'raw_outbound_zip_size': 0, + } + try: + from app.services.schedule.freight_rpa_outbound_archive import persist_outbound_rpa_raw_zip_archive + + archive_summary = persist_outbound_rpa_raw_zip_archive(run) + except Exception as archive_exc: + current_app.logger.error( + '[schedule-run] outbound RPA zip archive failed for run %s: %s', + run.run_no, archive_exc, + ) + + run.response_summary_json = { + **summary, + 'awaiting_outbound_rpa': False, + 'success_count': success_count, + 'empty_count': skipped_count, + 'failed_count': failed_count, + 'excel_export_status': 'ok' if excel_export_ok else 'failed', + 'excel_failed': not excel_export_ok, + **archive_summary, + } + db.session.commit() + # 通知与入站 RPA 完全同构:run 终态后走通用排程出口一次性发 textcard+出站 ZIP。 + try: + task = run.task + if task is not None and task.notify_enabled: + from app.services.schedule.scheduler_service import _notify_schedule_run_wecom + + _notify_schedule_run_wecom(task, run) + db.session.commit() + except Exception as wecom_exc: + current_app.logger.error('[schedule-run] outbound RPA wecom notify failed: %s', wecom_exc) + return {'finalized': True, 'status': run.status} + + +def _outbound_timeout_seconds() -> int: + """读取出站回调等待上限;超时只标记失败,不会自动重试或重发。""" + try: + return max(60, int(current_app.config.get('FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS', 900))) + except (TypeError, ValueError): + return 900 + + +def is_freight_outbound_rpa_task(task: ScheduleTask | None) -> bool: + """识别独立出站 RPA 排程,避免超时回收影响库存或其他平台任务。""" + return bool( + task + and task.schedule_type == 'platform_job' + and normalize_platform_api_path(task.platform_api_path) == OUTBOUND_RPA_JOB_KEY + ) + + +def _outbound_last_activity(run: ScheduleRun, units: list[FreightRpaOutboundUnitRun]) -> datetime: + """出站 run 的最后活动锚:run 开始时间与全部单元 started/finished 时间的最大值。 + + 语义为「笔间静默」:worker 每开始/完成一笔都会推进锚点,锚点静默超过 + FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS 才判定 worker 不再活动。刻意不含单元 + created_at——批量 trigger 中排队单元的创建时间不代表活动,否则整批永不超时。 + 极端长单笔(单站点导出超过 timeout)会被判超时,需按最慢单笔调大该配置。 + """ + stamps = [run.started_at] if run.started_at else [] + for unit in units: + if unit.started_at: + stamps.append(unit.started_at) + if unit.finished_at: + stamps.append(unit.finished_at) + return max(stamps) + + +def _fail_outbound_unit_with_timeout( + unit: FreightRpaOutboundUnitRun, *, now: datetime, timeout_seconds: int, + run_no: str | None = None, +) -> None: + """单个出站单元回调超时收口为失败并写审计(run 级与孤儿级回收共用的唯一实现)。 + + 核心逻辑:错误码/错误文案/审计事件三者的单一事实来源——run 级扫描与孤儿 + 单元扫描共用本函数收口单元,防止两条路径语义漂移。只改单元不 commit, + 事务归属调用方。 + + Args: + unit: 待收口的非终态出站单元。 + now: 收口时刻(同批单元共享同一时间戳)。 + timeout_seconds: 超时窗(写入错误文案与审计 metadata)。 + run_no: 所属排程 run 号(run 级回收传实;孤儿单元无排程,保持 None)。 + Returns: + None。 + """ + before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message} + unit.status = 'failed' + unit.error_code = 'RPA.OUTBOUND_CALLBACK_TIMEOUT' + unit.error_message = f'Outbound RPA callback timed out after {timeout_seconds} seconds' + unit.finished_at = now + append_shipping_audit_event( + event_type='shipping_outbound_rpa_callback_timeout', aggregate_type='shipping_outbound_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}, + metadata={'timeout_seconds': timeout_seconds}, + ) + + +def _recover_stale_outbound_run(run: ScheduleRun, *, cutoff: datetime, timeout_seconds: int) -> bool: + """将无回调的独立出站运行收口为失败,保留其单元与触发审计事实。 + + 截止判据为最后活动锚(_outbound_last_activity)而非 run.started_at—— + 串行长批次(>timeout)只要仍有笔间活动就不得被误杀。 + """ + summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} + if not summary.get('awaiting_outbound_rpa') or run.status != 'running' or not run.started_at: + return False + task = run.task or db.session.get(ScheduleTask, run.schedule_task_id) + if not is_freight_outbound_rpa_task(task): + return False + units = FreightRpaOutboundUnitRun.query.filter_by(schedule_run_id=run.id).all() + if _outbound_last_activity(run, units) > cutoff: + return False + now = datetime.utcnow() + pending = [unit for unit in units if unit.status in {'queued', 'awaiting_rpa', 'processing'}] + for unit in pending: + _fail_outbound_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds, run_no=run.run_no) + run.status = 'failed' + run.finished_at = now + run.duration_ms = int((now - run.started_at).total_seconds() * 1000) + run.failed_count = len(pending) or max(1, int(run.failed_count or 0)) + run.error_message = f'出站 RPA 回调等待超时({timeout_seconds} 秒)' + run.step_logs = [*(run.step_logs or []), { + 'step': 'freight_outbound_rpa', 'status': 'failed', + 'detail': {'message': run.error_message, 'timeout_seconds': timeout_seconds}, + }] + run.response_summary_json = {**summary, 'awaiting_outbound_rpa': False, 'recovered_reason': 'outbound_rpa_callback_timeout'} + return True + + +def recover_stale_outbound_rpa_schedule_runs(task: ScheduleTask) -> int: + """在同一出站排程开始前回收超时运行,解除后续 Cron/手动执行的互斥。""" + if not is_freight_outbound_rpa_task(task): + return 0 + timeout_seconds = _outbound_timeout_seconds() + cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds) + recovered = sum( + _recover_stale_outbound_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds) + for run in ScheduleRun.query.filter_by(schedule_task_id=task.id, status='running').all() + ) + if recovered: + db.session.commit() + return recovered + + +def recover_all_stale_outbound_rpa_schedule_runs() -> int: + """Worker 启动时扫描全部超时出站回调,避免重启后运行永久卡住。""" + timeout_seconds = _outbound_timeout_seconds() + cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds) + recovered = sum( + _recover_stale_outbound_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds) + for run in ScheduleRun.query.filter_by(status='running').all() + ) + if recovered: + db.session.commit() + return recovered + + +def recover_all_stale_orphan_outbound_units() -> int: + """回收按需触发(无排程绑定)的超时出站单元,解除来源投影永久 fetching。 + + 【AI 触发时机】仅由排程队列每轮领取维护(queue_service)调用。调拨工作台 + 重试/自动调拨补抓创建的单元 schedule_run_id 为 NULL(见 outbound_trigger_service), + 不在 run 级扫描(recover_all_stale_outbound_rpa_schedule_runs 按 run 遍历)范围内; + Worker 网页异常关闭后回调永不到达,若不回收则来源投影(source_file_status) + 永久 fetching、前端重试按钮永久锁死。 + + 核心逻辑:[STEP 1] 扫 schedule_run_id IS NULL、状态非终态、活动锚 + (coalesce(started_at, created_at):与 run 级同为活动锚思想,单元未被领取 + 无 started_at 时以 created_at 兜底;注意 run 级 _outbound_last_activity 是 + 笔间静默口径、刻意不含 created_at,两者语义不同)超过 + FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS 的单元;admin 单元重试 + 原样复制 schedule_run_id,其 retry 单元同为孤儿,一并覆盖。 + [STEP 2] 逐单元经 _fail_outbound_unit_with_timeout 收口(failed + + RPA.OUTBOUND_CALLBACK_TIMEOUT + 审计,与 run 级扫描同一实现零漂移); + 绝不自动重试或重发——恢复走调拨工作台显式「重试 RPA」。 + + Returns: + 本次回收的单元数。 + """ + timeout_seconds = _outbound_timeout_seconds() + cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds) + orphans = ( + FreightRpaOutboundUnitRun.query + .filter( + FreightRpaOutboundUnitRun.schedule_run_id.is_(None), + FreightRpaOutboundUnitRun.status.in_(('queued', 'awaiting_rpa', 'processing')), + func.coalesce(FreightRpaOutboundUnitRun.started_at, FreightRpaOutboundUnitRun.created_at) < cutoff, + ) + .all() + ) + if not orphans: + return 0 + now = datetime.utcnow() + for unit in orphans: + _fail_outbound_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds) + db.session.commit() + return len(orphans) diff --git a/backend/app/services/schedule/freight_rpa_outbound_job.py b/backend/app/services/schedule/freight_rpa_outbound_job.py new file mode 100644 index 00000000..96b5ae7a --- /dev/null +++ b/backend/app/services/schedule/freight_rpa_outbound_job.py @@ -0,0 +1,156 @@ +""" +backend/app/services/schedule/freight_rpa_outbound_job.py + +用途:独立出站 RPA 排程——按勾选库存源一对一冻结执行单元并写 outbound trigger。 +依赖:freight_rpa.outbound.trigger_io.write_outbound_export_batch_trigger、assert_outbound_rpa_worker_ready、 + FreightRpaSource / FreightRpaOutboundReportConfig / FreightRpaOutboundUnitRun、 + ScheduleTask/Run。 +逻辑:job_registry 的 freight-rpa-outbound 调用本 handler;写 trigger 前 fail-fast; + 口径与入站排程一致(选中 N 源 → N unit),query_parameters 原样下发。 +""" + +from __future__ import annotations + +import uuid +from typing import Any + +from app import db +from app.core.errors import ServiceUnavailableError +from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaOutboundReportConfig, FreightRpaOutboundUnitRun +from app.services.freight_rpa.outbound.trigger_io import SCHEMA, write_outbound_export_batch_trigger +from app.services.freight_rpa.common.worker_heartbeat import ( + RPA_WORKER_OFFLINE_MESSAGE, + assert_outbound_rpa_worker_ready, +) + +OUTBOUND_RPA_JOB_KEY = 'freight-rpa-outbound' +AWAITING_OUTBOUND_RPA_CALLBACK_STATUS = 'awaiting_outbound_rpa_callback' +ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]] + + +def _wanted_source_codes(task: ScheduleTask) -> set[str]: + """提取结构化 source_codes;留空代表全部具备有效出站配置的站点。""" + params = task.job_params if isinstance(task.job_params, dict) else {} + values = params.get('source_codes') or [] + if isinstance(values, str): + values = [values] + return {str(value).strip().upper() for value in values if str(value).strip()} + + +def _eligible_sources(task: ScheduleTask) -> list[tuple[FreightRpaSource, FreightRpaOutboundReportConfig]]: + """读取已启用且已配置出站报表的站点;不依赖库存报表路径、解析绑定或 Warehouse 条件。""" + wanted = _wanted_source_codes(task) + rows = db.session.query(FreightRpaSource, FreightRpaOutboundReportConfig).join( + FreightRpaOutboundReportConfig, FreightRpaOutboundReportConfig.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: FreightRpaOutboundReportConfig) -> list[dict[str, Any]]: + """浅拷贝出站查询条件原样入快照;空列表表示 Worker 使用页面默认、不填 Warehouse。""" + return [ + dict(item) for item in (config.query_parameters_json or []) + if isinstance(item, dict) + ] + + +def _build_unit( + source: FreightRpaSource, config: FreightRpaOutboundReportConfig, schedule_run_id: int, +) -> FreightRpaOutboundUnitRun: + """冻结可审计的出站执行单元(一源一单元);DBS 日期字段不进入查询快照。""" + callback_id = f'outbound:{uuid.uuid4().hex}' + snapshot = { + 'config_id': config.id, 'config_version': config.config_version, 'connector_type': source.connector_type, + '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 FreightRpaOutboundUnitRun( + 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: FreightRpaOutboundUnitRun) -> dict[str, Any]: + """生成 Worker 唯一可见的冻结执行载荷;密文凭据只随 outbound trigger 下发。""" + 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'outbound source profile unavailable: {unit.source_code}') + snapshot = dict(unit.config_snapshot_json or {}) + return { + 'unit_run_id': unit.id, + 'callback_id': unit.callback_id, + 'source_code': unit.source_code, + 'connector_type': unit.connector_type, + 'warehouse_id': unit.warehouse_id, + 'rpa_profile_id': profile.id, + 'rpa_profile_code': profile.profile_code, + 'login_url': profile.login_url, + 'login_config': dict(profile.login_config_json or {}), + 'credential_envelope': { + 'username_ciphertext': profile.username_ciphertext, + 'password_ciphertext': profile.password_ciphertext, + }, + 'report_path_json': dict(snapshot.get('report_path_json') or {}), + 'query_parameters_json': list(snapshot.get('query_parameters_json') or []), + 'config_snapshot': snapshot, + } + + +def run_freight_rpa_outbound_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: + """ + 写独立出站 trigger;每个勾选站点对应一个执行单元(与入站 RPA 同口径)。 + + 核心逻辑:写 trigger 前 assert_outbound_rpa_worker_ready;离线立即 failed, + 不创建 unit、不进入 awaiting_outbound_rpa_callback。 + """ + units: list[FreightRpaOutboundUnitRun] = [ + _build_unit(source, config, run.id) for source, config in _eligible_sources(task) + ] + if not units: + return 0, 0, 0, 1, [], ['no enabled outbound report sources'], [{'step': 'freight_outbound_rpa', 'status': 'skipped'}] + + # [STEP] 写 trigger / 入库 unit 前 fail-fast,避免 Worker 离线干等到超时。 + try: + assert_outbound_rpa_worker_ready() + except ServiceUnavailableError as exc: + message = str(exc.message or RPA_WORKER_OFFLINE_MESSAGE) + detail_message = str((exc.details or {}).get('detail_message') or message) + return len(units), 0, len(units), 0, [], [detail_message], [{ + 'step': 'freight_outbound_rpa', + 'status': 'failed', + 'detail': { + 'message': message, + 'detail_message': detail_message, + 'error_code': exc.code, + 'reasons': (exc.details or {}).get('reasons') or [], + }, + }] + + db.session.add_all(units) + db.session.flush() + try: + trigger_units = [_serialize_trigger_unit(unit) for unit in units] + except RuntimeError as exc: + for unit in units: + unit.status = 'failed'; unit.error_code = 'RPA.OUTBOUND_PROFILE_UNAVAILABLE'; unit.error_message = str(exc) + db.session.commit() + return len(units), 0, len(units), 0, [], [str(exc)], [{'step': 'freight_outbound_rpa', 'status': 'failed'}] + for unit, trigger_unit in zip(units, trigger_units): + unit.trigger_snapshot_json = trigger_unit + trigger_path = write_outbound_export_batch_trigger(run.run_no, trigger_units, { + 'schedule_run_id': run.id, 'schedule_task_id': task.id, 'schema_version': SCHEMA, + }) + if not trigger_path: + for unit in units: + unit.status = 'failed'; unit.error_code = 'RPA.OUTBOUND_TRIGGER_UNAVAILABLE'; unit.error_message = 'outbound trigger directory unavailable' + db.session.commit() + return len(units), 0, len(units), 0, [], ['outbound trigger directory unavailable'], [{'step': 'freight_outbound_rpa', 'status': 'failed'}] + details = [{'source_code': unit.source_code, 'warehouse_id': unit.warehouse_id, 'callback_id': unit.callback_id} for unit in units] + run.api_request_json = {'run_no': run.run_no, 'trigger_path': trigger_path, 'source_codes': sorted({unit.source_code for unit in units})} + db.session.commit() + return len(units), 0, 0, 0, details, [], [{ + 'step': 'freight_outbound_rpa', 'status': AWAITING_OUTBOUND_RPA_CALLBACK_STATUS, + 'detail': {'trigger_path': trigger_path, 'unit_count': len(units)}, + }] diff --git a/backend/app/services/schedule/freight_rpa_outbound_retention.py b/backend/app/services/schedule/freight_rpa_outbound_retention.py new file mode 100644 index 00000000..d8a1ef75 --- /dev/null +++ b/backend/app/services/schedule/freight_rpa_outbound_retention.py @@ -0,0 +1,66 @@ +""" +backend/app/services/schedule/freight_rpa_outbound_retention.py + +用途:出站原样归档三年到期对象清理(排程壳 + 本阶段清理本体)。 +依赖:FreightRpaOutboundReportFile、file_asset_storage、freight_rpa.common.report_audit。 +逻辑:job_registry 的 freight-rpa-outbound-retention 调用本 handler;仅删除已过保留期的 + MinIO 对象,保留运行、文件事实和审计记录。Task 9 可将本体下沉 outbound.report_archive, + 本文件届时改回薄接缝(对照 inbound_retention)。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from app import db +from app.models import FreightRpaOutboundReportFile +from app.services.file_assets.storage import file_asset_storage +from app.services.freight_rpa.common.report_audit import append_rpa_report_event + +OUTBOUND_RETENTION_JOB_KEY = 'freight-rpa-outbound-retention' + + +def run_freight_rpa_outbound_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]: + """仅删除已到三年保留期的 MinIO 对象,永不删除文件事实、运行或审计。 + + Args: + task: 排程任务行(job_params.limit 提供单批上限,1..1000)。 + run: 排程执行记录(本函数不改写 run,仅按排程协议返回计数/明细/日志)。 + Returns: + 排程平台 Job 协议七元组(总查得数、成功、失败、跳过 0、明细、错误、step_logs)。 + """ + limit = max(1, min(int((getattr(task, 'job_params', {}) or {}).get('limit', 100)), 1000)) + now = datetime.utcnow() + rows = FreightRpaOutboundReportFile.query.filter( + FreightRpaOutboundReportFile.archive_expires_at.is_not(None), + FreightRpaOutboundReportFile.archive_expires_at <= now, + FreightRpaOutboundReportFile.archive_deleted_at.is_(None), + ).order_by(FreightRpaOutboundReportFile.id).limit(limit).all() + success = failed = 0 + errors: list[str] = [] + for report_file in rows: + try: + 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_rpa_report_event( + event_type='shipping_outbound_report_archive_deleted', aggregate_type='shipping_outbound_file', + aggregate_id=str(report_file.id), actor_type='worker', actor_id='outbound-retention', + unit_id=report_file.unit_run_id, result='success', + before={'status': 'archived'}, after={'status': 'archive_deleted'}, + artifact_refs=[{'kind': 'outbound_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], + ) + success += 1 + except Exception as exc: + errors.append(f'{report_file.id}: {exc}') + append_rpa_report_event( + event_type='shipping_outbound_report_archive_delete_attempted', aggregate_type='shipping_outbound_file', + aggregate_id=str(report_file.id), actor_type='worker', actor_id='outbound-retention', + unit_id=report_file.unit_run_id, result='failure', + before={'status': 'archived'}, after={'status': 'archived', 'delete_error': str(exc)[:2000]}, + artifact_refs=[{'kind': 'outbound_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], + ) + failed += 1 + db.session.commit() + return len(rows), success, failed, 0, [{'file_id': row.id} for row in rows], errors, [{'step': 'outbound_retention', 'status': 'completed'}] diff --git a/backend/app/services/schedule/job_options.py b/backend/app/services/schedule/job_options.py index 879e5232..3ce9ec26 100644 --- a/backend/app/services/schedule/job_options.py +++ b/backend/app/services/schedule/job_options.py @@ -5,7 +5,7 @@ backend/app/services/schedule/job_options.py 依赖: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。 + 货代 RPA 注册键为 freight_rpa_sources、freight_rpa_inbound_sources 与 freight_rpa_outbound_sources。 """ from __future__ import annotations @@ -34,8 +34,8 @@ def _agent_apps_options() -> list[dict[str, Any]]: ] -def _shipping_inventory_sources_options() -> list[dict[str, Any]]: - """启用中的货代库存源(value=source_code,来自数据库主数据)。""" +def _freight_rpa_sources_options() -> list[dict[str, Any]]: + """启用中的货代来源站点(value=source_code,来自数据库主数据;供 onhand 排程选源)。""" from app.services.shipping_notice.onhand_source_repository import list_database_inventory_sources return [ @@ -52,8 +52,8 @@ def _shipping_inventory_sources_options() -> list[dict[str, Any]]: ] -def _shipping_receipt_sources_options() -> list[dict[str, Any]]: - """已启用且已配置收料报表的站点,供独立收料排程选择。""" +def _freight_rpa_inbound_sources_options() -> list[dict[str, Any]]: + """已启用且已配置入站报表的站点,供独立入站排程选择。""" from app.models import FreightRpaSource, FreightRpaInboundReportConfig rows = db.session.query(FreightRpaSource, FreightRpaInboundReportConfig).join( @@ -61,7 +61,20 @@ def _shipping_receipt_sources_options() -> list[dict[str, Any]]: ).filter(FreightRpaSource.enabled.is_(True)).all() return [{ 'label': source.display_name or source.source_code, 'value': source.source_code, - 'description': f'{source.connector_type} · 收料已配置', + 'description': f'{source.connector_type} · 入站已配置', + } for source, _config in rows] + + +def _freight_rpa_outbound_sources_options() -> list[dict[str, Any]]: + """已启用且已配置出站报表的站点,供独立出站排程选择。""" + from app.models import FreightRpaSource, FreightRpaOutboundReportConfig + + rows = db.session.query(FreightRpaSource, FreightRpaOutboundReportConfig).join( + FreightRpaOutboundReportConfig, FreightRpaOutboundReportConfig.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} · 出站已配置', } for source, _config in rows] @@ -102,8 +115,9 @@ 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, - "freight_rpa_sources": _shipping_inventory_sources_options, - "freight_rpa_inbound_sources": _shipping_receipt_sources_options, + "freight_rpa_sources": _freight_rpa_sources_options, + "freight_rpa_inbound_sources": _freight_rpa_inbound_sources_options, + "freight_rpa_outbound_sources": _freight_rpa_outbound_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 e1ff4e33..580fae9c 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_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。 +依赖:freight_rpa_onhand_job、freight_rpa_inbound_job、freight_rpa_outbound_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 通用渲染。 """ @@ -133,8 +133,10 @@ def _register_builtin_platform_jobs() -> None: 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_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.freight_rpa_inbound_job import run_freight_rpa_inbound_schedule + from app.services.schedule.freight_rpa_inbound_retention import run_freight_rpa_inbound_retention_schedule + from app.services.schedule.freight_rpa_outbound_job import run_freight_rpa_outbound_schedule + from app.services.schedule.freight_rpa_outbound_retention import run_freight_rpa_outbound_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, @@ -399,22 +401,41 @@ def _register_builtin_platform_jobs() -> None: register_platform_job(PlatformJobDefinition( key="freight-rpa-inbound", label="货代入站 RPA", - handler=run_freight_receipt_rpa_schedule, + handler=run_freight_rpa_inbound_schedule, description="按计划从已配置入站报表的站点导出并归档入站文件。", category="shipping", params_schema=({ - "key": "source_codes", "type": "multi_select", "label": "收料站点", "required": False, + "key": "source_codes", "type": "multi_select", "label": "入站站点", "required": False, "default": [], "options_source": "freight_rpa_inbound_sources", - "help": "选择需要执行的收料站点;留空则执行所有已启用收料配置。", + "help": "选择需要执行的入站站点;留空则执行所有已启用入站配置。", },), defaults={"source_codes": []}, )) register_platform_job(PlatformJobDefinition( key='freight-rpa-inbound-retention', label='货代入站归档到期清理', - handler=run_freight_receipt_rpa_retention_schedule, + handler=run_freight_rpa_inbound_retention_schedule, description='仅删除已过三年保留期的入站对象,保留运行、文件事实和审计记录。', category='shipping', params_schema=({'key': 'limit', 'type': 'number', 'label': '单批上限', 'required': False, 'default': 100},), defaults={'limit': 100}, )) + register_platform_job(PlatformJobDefinition( + key="freight-rpa-outbound", + label="货代出站 RPA", + handler=run_freight_rpa_outbound_schedule, + description="按计划从已配置出站报表的站点导出并归档出站文件。", + category="shipping", + params_schema=({ + "key": "source_codes", "type": "multi_select", "label": "出站站点", "required": False, + "default": [], "options_source": "freight_rpa_outbound_sources", + "help": "选择需要执行的出站站点;留空则执行所有已启用出站配置。", + },), + defaults={"source_codes": []}, + )) + register_platform_job(PlatformJobDefinition( + key='freight-rpa-outbound-retention', label='货代出站归档到期清理', + handler=run_freight_rpa_outbound_retention_schedule, + description='仅删除已过三年保留期的出站对象,保留运行、文件事实和审计记录。', category='shipping', + params_schema=({'key': 'limit', 'type': 'number', 'label': '单批上限', 'required': False, 'default': 100},), defaults={'limit': 100}, + )) register_platform_job(PlatformJobDefinition( key="faq-aggregate-hot", label="FAQ 热点聚合", diff --git a/backend/app/services/schedule/query_service.py b/backend/app/services/schedule/query_service.py index d6ac09e3..c9f75377 100644 --- a/backend/app/services/schedule/query_service.py +++ b/backend/app/services/schedule/query_service.py @@ -1,3 +1,10 @@ +""" +backend/app/services/schedule/query_service.py + +用途:排程任务与运行记录的查询/序列化。 +依赖:ScheduleRun / ScheduleTask、库存/入站/出站 raw-zip 可用性判定。 +逻辑:list_tasks / get_run / serialize_run 供管理端排程工作台与下载按钮读取。 +""" from __future__ import annotations from datetime import datetime, timezone @@ -10,7 +17,8 @@ from app import db from app.models import ScheduleRun, ScheduleTask from app.core.response import utc_iso 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.freight_rpa_inbound_archive import inbound_raw_zip_available_from_summary +from app.services.schedule.freight_rpa_outbound_archive import outbound_raw_zip_available_from_summary from app.services.schedule.timezone_util import ( DEFAULT_SCHEDULE_TIMEZONE, compute_next_run_at, @@ -61,6 +69,7 @@ def serialize_task(task: ScheduleTask, *, last_status: str | None = None) -> dic def serialize_run(run: ScheduleRun) -> dict: + """序列化单条运行记录;附带库存/入站/出站 raw-zip 是否可下载。""" summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} return { 'id': run.id, @@ -86,7 +95,8 @@ def serialize_run(run: ScheduleRun) -> dict: 'excel_file_name': run.excel_file_name, 'excel_file_size': run.excel_file_size, 'inventory_raw_zip_available': inventory_raw_zip_available_from_summary(summary), - 'receipt_raw_zip_available': receipt_raw_zip_available_from_summary(summary), + 'inbound_raw_zip_available': inbound_raw_zip_available_from_summary(summary), + 'outbound_raw_zip_available': outbound_raw_zip_available_from_summary(summary), 'kb_sync_status': run.kb_sync_status, 'kb_group_id': run.kb_group_id, 'kb_document_id': run.kb_document_id, diff --git a/backend/app/services/schedule/queue_service.py b/backend/app/services/schedule/queue_service.py index f14db6cb..372e1a99 100644 --- a/backend/app/services/schedule/queue_service.py +++ b/backend/app/services/schedule/queue_service.py @@ -2,7 +2,8 @@ backend/app/services/schedule/queue_service.py 用途:把手动与 Cron 排程统一写入通用 Job 队列,并维护 ScheduleRun 业务状态。 -依赖:models.ScheduleTask/ScheduleRun、jobs.queue、schedule timezone 与 RPA 收口服务。 +依赖:models.ScheduleTask/ScheduleRun、jobs.queue、schedule timezone 与 RPA 收口服务 + (onhand / inbound / outbound finalize 超时回收)。 逻辑:API 只创建 queued run;独立 schedule worker 扫描到期任务、领取 Job 后执行 scheduler_service。 domain/job_type 固定 schedule/schedule_run 供 worker 认领;业务身份写入 business_ref(schedule_run:{id}:{platform_api_path})、payload 与 message。 @@ -24,10 +25,15 @@ from app.services.schedule.freight_rpa_onhand_finalize import ( recover_stale_awaiting_rpa_schedule_runs, ) 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, - is_awaiting_receipt_rpa_schedule_run, + recover_all_stale_orphan_inbound_units, + recover_all_stale_inbound_rpa_schedule_runs, + recover_stale_inbound_rpa_schedule_runs, + is_awaiting_inbound_rpa_schedule_run, +) +from app.services.schedule.freight_rpa_outbound_finalize import ( + recover_all_stale_orphan_outbound_units, + recover_all_stale_outbound_rpa_schedule_runs, + recover_stale_outbound_rpa_schedule_runs, ) from app.services.schedule.timezone_util import compute_next_run_at, utc_now_naive @@ -233,7 +239,8 @@ def enqueue_manual_schedule_run( if task is None: raise LookupError(f"schedule task {task_id} not found") recover_stale_awaiting_rpa_schedule_runs(task) - recover_stale_receipt_rpa_schedule_runs(task) + recover_stale_inbound_rpa_schedule_runs(task) + recover_stale_outbound_rpa_schedule_runs(task) active = _active_run(task.id) if active is not None: job = ( @@ -287,7 +294,8 @@ def enqueue_due_schedule_runs(*, limit: int = 5) -> int: # 每轮都回收当前任务已超时的外部 RPA 回调,不能仅依赖 worker 启动时扫一次; # 这只是终态化失败,不会自动重新导出。 recover_stale_awaiting_rpa_schedule_runs(task) - recover_stale_receipt_rpa_schedule_runs(task) + recover_stale_inbound_rpa_schedule_runs(task) + recover_stale_outbound_rpa_schedule_runs(task) if _active_run(task.id) is None: _create_queued_run(task, trigger_type="cron", triggered_by_user_id=None) _advance_next_run(task) @@ -337,7 +345,7 @@ def prepare_schedule_queue() -> int: legacy_running = db.session.query(ScheduleRun).filter(ScheduleRun.status == "running").all() interrupted = 0 for run in legacy_running: - if is_awaiting_rpa_schedule_run(run) or is_awaiting_receipt_rpa_schedule_run(run): + if is_awaiting_rpa_schedule_run(run) or is_awaiting_inbound_rpa_schedule_run(run): continue active_job = ( query_jobs_for_schedule_run(run.id) @@ -380,16 +388,24 @@ def prepare_schedule_queue() -> int: # 收料 run 超时对账同为每轮领取维护(2026-10-07 从启动一次性分支迁出): # 此前长驻进程期间超时 run 永不终态(RUN20261001131705E5E5 卡执行中的根因)。 # 回收判据为最后活动锚(笔间静默),健康长批次不被误杀,见 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) + inbound_stale = recover_all_stale_inbound_rpa_schedule_runs() + if inbound_stale: + current_app.logger.info("[schedule-worker] recovered %d stale inbound RPA runs", inbound_stale) # 按需触发(无排程)孤儿单元同口径回收(2026-10-16):调拨工作台重试/自动调拨 # 补抓创建的单元 schedule_run_id 为 NULL,上方 run 级扫描按 run 遍历覆盖不到; # 网页异常关闭后回调永不到达,不回收则来源投影永久 fetching、重试按钮永久锁死。 - orphan_stale = recover_all_stale_orphan_receipt_units() + orphan_stale = recover_all_stale_orphan_inbound_units() if orphan_stale: - current_app.logger.info("[schedule-worker] recovered %d stale orphan receipt RPA units", orphan_stale) + current_app.logger.info("[schedule-worker] recovered %d stale orphan inbound RPA units", orphan_stale) + + # 出站 run / 孤儿单元超时对账与入站同属每轮领取维护,不得挂启动一次性分支。 + outbound_stale = recover_all_stale_outbound_rpa_schedule_runs() + if outbound_stale: + current_app.logger.info("[schedule-worker] recovered %d stale outbound RPA runs", outbound_stale) + outbound_orphan_stale = recover_all_stale_orphan_outbound_units() + if outbound_orphan_stale: + current_app.logger.info("[schedule-worker] recovered %d stale orphan outbound RPA units", outbound_orphan_stale) try: from app.services.freight_rpa.common.worker_heartbeat_alert import maybe_alert_rpa_worker_status diff --git a/backend/app/services/schedule/scheduler_service.py b/backend/app/services/schedule/scheduler_service.py index a1d08e16..d8bb7012 100644 --- a/backend/app/services/schedule/scheduler_service.py +++ b/backend/app/services/schedule/scheduler_service.py @@ -2,7 +2,9 @@ backend/app/services/schedule/scheduler_service.py 用途:排程任务生命周期(创建/更新)与单次运行执行器。 -依赖:schedule_contract、job_params、cron_util、timezone_util、excel_service、wecom_notify、kb_sync。 +依赖:schedule_contract、job_params、cron_util、timezone_util、excel_service、wecom_notify、kb_sync、 + freight_rpa_onhand_finalize / inbound_finalize / outbound_finalize(awaiting 延后终态与超时回收)、 + onhand / inbound / outbound archive raw-zip 可用性(企微深链 download 意图)。 逻辑:api/schedule/tasks.py 与 import_service 调用 create_task/update_task/enable_task; job_params 在本层经 normalize_job_params_for_contract 唯一归一化(含切换 platform_api_path 未传参时重置默认值);schedule worker 调用 run_task_now 并经 resolve_schedule_executor 分发 handler; @@ -31,9 +33,14 @@ from app.services.schedule.freight_rpa_onhand_finalize import ( should_defer_schedule_run_finalization, ) 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, + apply_deferred_inbound_schedule_run_state, + recover_stale_inbound_rpa_schedule_runs, + should_defer_inbound_schedule_run, +) +from app.services.schedule.freight_rpa_outbound_finalize import ( + apply_deferred_outbound_schedule_run_state, + recover_stale_outbound_rpa_schedule_runs, + should_defer_outbound_schedule_run, ) from app.services.schedule.job_params import normalize_job_params_for_contract from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id @@ -103,11 +110,12 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun) """ 构造排程企微 textcard 跳转 query 参数。 - 核心逻辑:指向管理端 /admin/schedules;有原始库存/收料归档时附加 raw_zip=1 + 核心逻辑:指向管理端 /admin/schedules;有原始库存/入站/出站归档时附加 raw_zip=1 与对应 download 意图,由前端登录后自动触发一次下载,失败时保留手动入口。 """ 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.freight_rpa_inbound_archive import inbound_raw_zip_available_from_summary + from app.services.schedule.freight_rpa_outbound_archive import outbound_raw_zip_available_from_summary summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} params: dict[str, Any] = { @@ -117,17 +125,20 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun) if inventory_raw_zip_available_from_summary(summary): params['raw_zip'] = '1' params['download'] = 'inventory_raw_zip' - elif receipt_raw_zip_available_from_summary(summary): + elif inbound_raw_zip_available_from_summary(summary): params['raw_zip'] = '1' - params['download'] = 'receipt_raw_zip' + params['download'] = 'inbound_raw_zip' + elif outbound_raw_zip_available_from_summary(summary): + params['raw_zip'] = '1' + params['download'] = 'outbound_raw_zip' return params -def _receipt_report_files_for_run(run: ScheduleRun) -> list[FreightRpaInboundReportFile]: +def _inbound_report_files_for_run(run: ScheduleRun) -> list[FreightRpaInboundReportFile]: """ - 收集收料排程 run 名下可投递的收料报表文件;非收料任务返回空列表。 + 收集入站排程 run 名下可投递的入站报表文件;非收料任务返回空列表。 - 核心逻辑:按 platform_api_path 识别收料排程,返回该 run 全部单元已归档且 + 核心逻辑:按 platform_api_path 识别入站排程,返回该 run 全部单元已归档且 未被清理(archive_deleted_at 为空)的报表文件。企微完成通知已改为发 ZIP, 本函数保留给管理员单文件重发等旁路读取。 """ @@ -158,7 +169,7 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str: 组装排程完成企微 textcard 正文。 核心逻辑:与管理端统计口径一致,展示 total/success/skipped/failed 四列计数; - 有原始库存/收料归档时提示包已随通知发送或可点击下载。 + 有原始库存/入站/出站归档时提示包已随通知发送或可点击下载。 """ status_label = _WECOM_STATUS_LABEL.get(run.status, run.status) skipped_count = int(run.skipped_count or 0) @@ -172,12 +183,15 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str: if summary.get('excel_failed') or summary.get('excel_export_status') == 'failed': description += '\n备注: 库存源已成功,但排程 Excel 生成失败' 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.freight_rpa_inbound_archive import inbound_raw_zip_available_from_summary + from app.services.schedule.freight_rpa_outbound_archive import outbound_raw_zip_available_from_summary if inventory_raw_zip_available_from_summary(summary): description += '\n原始库存包:点击本通知,登录 HXOPS 后自动下载' - if receipt_raw_zip_available_from_summary(summary): - description += '\n原始收料包:已随本通知发送;亦可点击本通知登录后下载' + if inbound_raw_zip_available_from_summary(summary): + description += '\n原始入站包:已随本通知发送;亦可点击本通知登录后下载' + if outbound_raw_zip_available_from_summary(summary): + description += '\n原始出站包:已随本通知发送;亦可点击本通知登录后下载' return description @@ -186,8 +200,8 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None: 排程完成后的通用企微通知。 核心逻辑:若 response_summary_json.domain_notification_managed=true(如立账凭证检核), 则跳过以免与领域缺件/失败告警重复。 - 库存与收料 RPA 共用本出口与同一套门禁:库存附加排程 Excel 与原始库存包; - 收料附加该 run 的原始收料 ZIP(不再逐文件推送)。 + 库存、入站、出站 RPA 共用本出口与同一套门禁:库存附加排程 Excel 与原始库存包; + 入站/出站附加该 run 的原始 ZIP(不再逐文件推送)。 """ from app.services.integrations.wecom.notify import ( upload_wecom_temp_media, @@ -248,18 +262,33 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None: run.run_no, exc, ) - receipt_zip_media_id = None - receipt_zip_file_name = None + inbound_zip_media_id = None + inbound_zip_file_name = None try: - from app.services.schedule.freight_rpa_inbound_archive import resolve_receipt_raw_zip_download + from app.services.schedule.freight_rpa_inbound_archive import resolve_inbound_raw_zip_download - receipt_zip_path, receipt_zip_file_name = resolve_receipt_raw_zip_download(run) - receipt_zip_media_id = upload_wecom_temp_media( - receipt_zip_path.read_bytes(), receipt_zip_file_name, + inbound_zip_path, inbound_zip_file_name = resolve_inbound_raw_zip_download(run) + inbound_zip_media_id = upload_wecom_temp_media( + inbound_zip_path.read_bytes(), inbound_zip_file_name, ) except Exception as exc: current_app.logger.info( - '[wecom-schedule] raw receipt zip media skipped for run %s: %s', + '[wecom-schedule] raw inbound zip media skipped for run %s: %s', + run.run_no, exc, + ) + + outbound_zip_media_id = None + outbound_zip_file_name = None + try: + from app.services.schedule.freight_rpa_outbound_archive import resolve_outbound_raw_zip_download + + outbound_zip_path, outbound_zip_file_name = resolve_outbound_raw_zip_download(run) + outbound_zip_media_id = upload_wecom_temp_media( + outbound_zip_path.read_bytes(), outbound_zip_file_name, + ) + except Exception as exc: + current_app.logger.info( + '[wecom-schedule] raw outbound zip media skipped for run %s: %s', run.run_no, exc, ) @@ -318,23 +347,41 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None: except Exception as exc: errors.append(f'{u.real_name or u.username}: raw zip exception={exc}') - if receipt_zip_media_id: + if inbound_zip_media_id: try: - receipt_zip_audit = _create_audit( - f'{_WECOM_EVENT_TYPE}_receipt_raw_zip', u, - title, f'[原始收料包] {receipt_zip_file_name}', uuid.uuid4().hex, + inbound_zip_audit = _create_audit( + f'{_WECOM_EVENT_TYPE}_inbound_raw_zip', u, + title, f'[原始入站包] {inbound_zip_file_name}', uuid.uuid4().hex, ) - receipt_zip_data = send_wecom_file_message(u.wecom_userid, receipt_zip_media_id) - if receipt_zip_data.get('errcode') == 0: - receipt_zip_audit.status = 'sent' + inbound_zip_data = send_wecom_file_message(u.wecom_userid, inbound_zip_media_id) + if inbound_zip_data.get('errcode') == 0: + inbound_zip_audit.status = 'sent' else: - receipt_zip_audit.error_code = str(receipt_zip_data.get('errcode')) - receipt_zip_audit.error_message = str(receipt_zip_data.get('errmsg', 'unknown'))[:255] + inbound_zip_audit.error_code = str(inbound_zip_data.get('errcode')) + inbound_zip_audit.error_message = str(inbound_zip_data.get('errmsg', 'unknown'))[:255] errors.append( - f'{u.real_name or u.username}: receipt zip errcode={receipt_zip_data.get("errcode")}' + f'{u.real_name or u.username}: inbound zip errcode={inbound_zip_data.get("errcode")}' ) except Exception as exc: - errors.append(f'{u.real_name or u.username}: receipt zip exception={exc}') + errors.append(f'{u.real_name or u.username}: inbound zip exception={exc}') + + if outbound_zip_media_id: + try: + outbound_zip_audit = _create_audit( + f'{_WECOM_EVENT_TYPE}_outbound_raw_zip', u, + title, f'[原始出站包] {outbound_zip_file_name}', uuid.uuid4().hex, + ) + outbound_zip_data = send_wecom_file_message(u.wecom_userid, outbound_zip_media_id) + if outbound_zip_data.get('errcode') == 0: + outbound_zip_audit.status = 'sent' + else: + outbound_zip_audit.error_code = str(outbound_zip_data.get('errcode')) + outbound_zip_audit.error_message = str(outbound_zip_data.get('errmsg', 'unknown'))[:255] + errors.append( + f'{u.real_name or u.username}: outbound zip errcode={outbound_zip_data.get("errcode")}' + ) + except Exception as exc: + errors.append(f'{u.real_name or u.username}: outbound zip exception={exc}') if textcard_ok_count > 0: run.wecom_notified = True @@ -570,7 +617,8 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: 该路径原先只写库不打日志,worker 汇总行看不到失败原因。 """ recover_stale_awaiting_rpa_schedule_runs(task) - recover_stale_receipt_rpa_schedule_runs(task) + recover_stale_inbound_rpa_schedule_runs(task) + recover_stale_outbound_rpa_schedule_runs(task) if run is None: existing = db.session.query(ScheduleRun).filter( @@ -640,8 +688,12 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: errors=errors, step_logs=step_logs, ) - if should_defer_receipt_schedule_run(task, step_logs): - return apply_deferred_receipt_schedule_run_state( + if should_defer_inbound_schedule_run(task, step_logs): + return apply_deferred_inbound_schedule_run_state( + run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs, + ) + if should_defer_outbound_schedule_run(task, step_logs): + return apply_deferred_outbound_schedule_run_state( run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs, ) diff --git a/backend/app/services/shipping_notice/inbound_report_access.py b/backend/app/services/shipping_notice/inbound_report_access.py deleted file mode 100644 index 23e1194e..00000000 --- a/backend/app/services/shipping_notice/inbound_report_access.py +++ /dev/null @@ -1,100 +0,0 @@ -""" -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 - -from io import BytesIO -from typing import Any - -from app import db -from app.core.errors import ForbiddenError, NotFoundError -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 - - -def _is_admin(user: User) -> bool: - """判断用户是否为收料报表管理角色。""" - return bool(user.is_platform_admin()) - - -def can_download_receipt_report_file(report_file: FreightRpaInboundReportFile, user: User) -> bool: - """仅允许管理员或所属排程通知接收人读取收料归档。""" - if _is_admin(user): - return True - run = report_file.unit_run.schedule_run - task = run.task if run is not None else None - return task is not None and int(user.id) in { - int(value) for value in (task.notify_user_ids_json or []) if str(value).isdigit() - } - - -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 - return { - 'id': report_file.id, - 'original_filename': report_file.original_filename, - 'content_type': report_file.content_type, - 'file_size': report_file.file_size, - 'sha256': report_file.sha256, - 'source_code': unit.source_code if unit is not None else None, - 'warehouse_id': unit.warehouse_id if unit is not None else None, - '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/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 = 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_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'}, - ) - db.session.commit() - return [_serialize_receipt_report_file(item) for item in visible] - - -def resolve_receipt_report_download(file_id: int, user: User) -> tuple[BytesIO, str, str | None]: - """授权读取私有对象并记录允许或拒绝的下载审计。""" - 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_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') - # [STEP] 阶段 B Task 5:归档字节统一经 freight_rpa/reports 只读函数读取(对象存储 key 不外泄、不双跳)。 - data = read_inbound_file_bytes(file_id) - append_shipping_audit_event( - 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}], - ) - db.session.commit() - return BytesIO(data), report_file.original_filename, report_file.content_type diff --git a/backend/app/services/shipping_notice/inbound_report_storage.py b/backend/app/services/shipping_notice/inbound_report_storage.py deleted file mode 100644 index acb10cac..00000000 --- a/backend/app/services/shipping_notice/inbound_report_storage.py +++ /dev/null @@ -1,122 +0,0 @@ -""" -services/shipping_notice/inbound_report_storage.py - -收料 RPA callback 的域内业务桥与终态收尾(shipping_notice 留守侧)。 - -用途:批次 R Task 10 拆分后,本模块只留守「业务桥」——收料终态落库后推进在途调拨的 - waiting_rpa_callback 来源任务(B3 接线)、success 终态的调拨证据同步,以及排程 - 终态归集(finalize)调用;原样归档/三年保留/resend/通知投递等 RPA 产物事实能力 - 已下沉 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_rpa_inbound_finalize(惰性导入,仅 finalize)。 -逻辑:ingest_receipt_callback 仍是本域回调入口(rpa_sinks 以 {'success':True,'data':...} - envelope 注册为 inbound-batch-ready sink):委托 report_archive.ingest_inbound_callback - 归档(各终态分支各自 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 - -from typing import Any - -from flask import current_app - -from app.models import FreightRpaInboundUnitRun - - -def _advance_transfer_source_job( - 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 重试; - 本函数留守为回归测试桥,同样不再吞失败)。 - """ - 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: '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 之后的业务收尾(留守测试桥),顺序与拆分前逐点一致。 - - 定位(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 终态触发调拨证据同步(桥模式失败仅日志,绝不影响收料归档主链路, - 语义见 in_transit_transfer/evidence_sync.sync_and_commit_for_callback);[STEP 3] 有排程 - run 时回写进度并归集终态(按需触发单元 schedule_run_id 为 NULL,跳过排程终态归集; - 文件通知不在此逐文件发送:统一由排程终态归集后一次性推送,与库存 RPA 同构)。 - """ - _advance_transfer_source_job( - unit, ok=ok, file_no=file_no, file_sha256=file_sha256, - error_code=error_code, error_message=error_message, - ) - if ok: - # [调拨证据同步·主链路] success 终态文件落地即解析写调拨待办(本分支专属; - # empty/failed 分支不触发同步)。 - try: - from datetime import datetime as _dt - - from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback - - sync_and_commit_for_callback( - source_code=unit.source_code, business_date=str(_dt.utcnow().date()), now=_dt.utcnow(), - ) - except Exception as exc: # noqa: BLE001 —— 双保险:桥内部已吞异常 - current_app.logger.warning('[receipt-callback] transfer evidence sync failed: %s', exc) - from app.services.schedule.freight_rpa_inbound_finalize import ( - finalize_receipt_schedule_run_if_complete, - refresh_receipt_schedule_run_progress, - ) - if unit.schedule_run_id: - refresh_receipt_schedule_run_progress(unit.schedule_run_id) - finalize_receipt_schedule_run_if_complete(unit.schedule_run_id) - - -def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]: - """幂等接收单个收料单元回调:委托 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) diff --git a/backend/app/services/shipping_notice/onhand_configuration_test.py b/backend/app/services/shipping_notice/onhand_configuration_test.py index a409f51d..b53fa174 100644 --- a/backend/app/services/shipping_notice/onhand_configuration_test.py +++ b/backend/app/services/shipping_notice/onhand_configuration_test.py @@ -514,7 +514,7 @@ def confirm_test_profile(source_id: int, run_no: str, profile_id: int, *, actor_ adopt_published_profile(run.analysis_id, profile_id) # s18 起解析绑定写 onhand_report_config 配置行(无则插入),站点行不再承载该外键; - # 与 shipping_onhand_admin_service.bind_source_parsing_profile 的批量绑定写序保持同构。 + # 与 freight_rpa_source_admin_service.bind_source_parsing_profile 的批量绑定写序保持同构。 config = source.onhand_report_config if config is None: config = FreightRpaOnhandReportConfig(source=source) diff --git a/backend/app/services/shipping_notice/onhand_file_store.py b/backend/app/services/shipping_notice/onhand_file_store.py index 231a3dbd..f32a8a41 100644 --- a/backend/app/services/shipping_notice/onhand_file_store.py +++ b/backend/app/services/shipping_notice/onhand_file_store.py @@ -689,7 +689,7 @@ def parse_inventory_snapshot_file(inv_file: FreightRpaOnhandReportFile) -> tuple if not path.is_file(): 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.services.freight_rpa.parsing_profile import require_source_profile from app.core.errors import ValidationError source = FreightRpaSource.query.filter_by(source_code=inv_file.source_code).first() diff --git a/backend/app/services/shipping_notice/onhand_report_handler.py b/backend/app/services/shipping_notice/onhand_report_handler.py index 7d1ad0f7..d3754593 100644 --- a/backend/app/services/shipping_notice/onhand_report_handler.py +++ b/backend/app/services/shipping_notice/onhand_report_handler.py @@ -10,7 +10,8 @@ services/shipping_notice/onhand_report_handler.py require_report_kind——只消费事实契约,不 import freight_rpa 工作流)、 onhand_recovery_service(候选准备 settle/聚合/等待任务反查)、 process_gate_bridge(门禁同步)。 -逻辑:由组合根(app.create_app → shipping_notice.rpa_sinks.register_onhand_sinks) +逻辑:由组合根(app.create_app → shipping_notice.rpa_sinks.register_onhand_sinks; + 入站/出站另见 in_transit_transfer.rpa_sinks) 注册为 'onhand' kind 处理函数;onhand_rpa_workflow 的单回调 (rpa_report_inventory)与批量 worker(process_rpa_report_inventory_batch) 在文件行 commit 后逐文件投递 ok=True 事实(先 commit 再投递——Task 7 修复轮 @@ -100,7 +101,7 @@ def handle_onhand_report(fact: ReportFact) -> None: if kind != 'onhand': raise ValidationError( f"handle_onhand_report only accepts onhand facts, got: {kind!r}", - code='SHIPPING.RECEIPT_CALLBACK_INVALID', + code='SHIPPING.INBOUND_CALLBACK_INVALID', details={'report_kind': fact.report_kind}, ) diff --git a/backend/app/services/shipping_notice/onhand_structure_analysis.py b/backend/app/services/shipping_notice/onhand_structure_analysis.py index 858df483..4b06e72a 100644 --- a/backend/app/services/shipping_notice/onhand_structure_analysis.py +++ b/backend/app/services/shipping_notice/onhand_structure_analysis.py @@ -448,7 +448,7 @@ def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: in } if any(str(value or '').strip() in duplicates for value in mapping.values()): 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 + from app.services.freight_rpa import parsing_profile as onhand_parsing_profile saved = onhand_parsing_profile.save_draft({ 'profile_code': data.get('profile_code'), diff --git a/backend/app/services/shipping_notice/onhand_temporary_session.py b/backend/app/services/shipping_notice/onhand_temporary_session.py index 8b9a6007..399f0b45 100644 --- a/backend/app/services/shipping_notice/onhand_temporary_session.py +++ b/backend/app/services/shipping_notice/onhand_temporary_session.py @@ -525,7 +525,7 @@ def create_parsing_profile_draft_from_temporary_session( if existing_draft_id: existing_draft = db.session.get(FreightRpaParsingProfile, existing_draft_id) if existing_draft is not None: - from app.services.shipping_notice.onhand_parsing_profile import payload as profile_payload + from app.services.freight_rpa.parsing_profile import payload as profile_payload return profile_payload(existing_draft) analysis = db.session.get(FreightRpaOnhandStructureAnalysis, item.analysis_id) if item.analysis_id else None diff --git a/backend/app/services/shipping_notice/rpa_sinks.py b/backend/app/services/shipping_notice/rpa_sinks.py index fc0fba2b..6921e8dd 100644 --- a/backend/app/services/shipping_notice/rpa_sinks.py +++ b/backend/app/services/shipping_notice/rpa_sinks.py @@ -1,23 +1,14 @@ """ services/shipping_notice/rpa_sinks.py -用途:onhand(在手库存)与 inbound(入站,原收料)RPA 回调的业务 sink 注册适配层——把 - /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。文件事实处理函数经 register_report_handler 注册 - (Task 7:inbound→handle_inbound_report、onhand→handle_onhand_report)——归档入口 - 终态 commit 后经 dispatch_report_fact 投递 ReportFact 调入;业务事务边界完全由被 - 包装的域内函数保持,本层只做接线,不碰 db。 +用途:onhand(在手库存)RPA 回调与报表事实的组合根注册——把 /api/freight-rpa/onhand-* + 接到发货域业务处理器。入站 / 出站注册见 in_transit_transfer.rpa_sinks。 +依赖:freight_rpa.common.callback_sinks、freight_rpa.reports.dispatch、 + onhand_rpa_workflow、per_source_rpa_service、onhand_configuration_test、 + onhand_report_handler。 +逻辑:由 app.create_app 调用 register_onhand_sinks()(幂等)。进度类 sink 复刻旧 + shipping-notice rpa 回调 envelope;onhand-repair 注入 payload['repair']=True; + 文件事实经 register_report_handler('onhand', handle_onhand_report) 注册。 """ from __future__ import annotations @@ -64,11 +55,9 @@ def register_onhand_sinks() -> None: """组合根入口:注册全部 onhand 回调 sink 与 onhand 事实处理函数(幂等;create_app 每次启动调用)。 核心逻辑:进度类 kind 命名 = /api/freight-rpa/* 回调路由名去前缀,被包装函数全部住在 - shipping_notice(业务落盘留守域),与 Task 4 裁定一致——认领(claim_inventory_batch) - 与批量编排留 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 不变。 + shipping_notice(业务落盘留守域)——认领(claim_inventory_batch)与批量编排留 + per_source_rpa_service,本层只做 envelope 复刻与分发接线;文件事实处理函数走 + reports.dispatch:'onhand' kind 注册 handle_onhand_report。 """ from app.services.freight_rpa.common.callback_sinks import register_sink from app.services.freight_rpa.reports.dispatch import register_report_handler @@ -93,35 +82,4 @@ def register_onhand_sinks() -> None: _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 与 inbound 事实处理函数(幂等;create_app 每次启动调用)。 - - 核心逻辑:进度类 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.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(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/migrations/versions/s19a0b1c2d3e4_freight_rpa_outbound_and_inbound_slim.py b/backend/migrations/versions/s19a0b1c2d3e4_freight_rpa_outbound_and_inbound_slim.py new file mode 100644 index 00000000..cb89f06e --- /dev/null +++ b/backend/migrations/versions/s19a0b1c2d3e4_freight_rpa_outbound_and_inbound_slim.py @@ -0,0 +1,275 @@ +""" +migrations/versions/s19a0b1c2d3e4_freight_rpa_outbound_and_inbound_slim.py + +用途:新建出站 RPA 三表,并拆除入站 per-file 企微投递表 + freight_rpa_inbound_notification_deliveries(Task 2 已删 Python 模型)。 +依赖:alembic.op、SQLAlchemy;down_revision 为实施时单 head s18d1e2f3a4b5。 +逻辑:autogenerate 噪声过大(无关 drop / 历史索引改名),故手写本 revision。 + 升级先 drop 投递表及其历史索引,再按 ORM 同构建 + configs → unit_runs → files;降级先拆出站三表,再按 s17b 后的现行结构 + 还原投递表(不恢复投递数据)。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = "s19a0b1c2d3e4" +down_revision = "s18d1e2f3a4b5" +branch_labels = None +depends_on = None + +_DELIVERIES_TABLE = "freight_rpa_inbound_notification_deliveries" +_DELIVERIES_INDEXES = ( + "ix_fr_inbound_notif_deliveries_recipient_user_id", + "ix_shipping_receipt_delivery_file_recipient", + "ix_shipping_receipt_delivery_unit_created", +) + + +def upgrade() -> None: + """Drop inbound notification deliveries, then create outbound config / run / file tables.""" + # [STEP 1] 入站投递账本:索引名含 s17b 未改的 shipping_receipt_delivery_* 与补建短名。 + for index_name in _DELIVERIES_INDEXES: + op.drop_index(index_name, table_name=_DELIVERIES_TABLE) + op.drop_table(_DELIVERIES_TABLE) + + # [STEP 2] 出站配置:站点一对一,字段与入站配置同构,无独立启停列。 + op.create_table( + "freight_rpa_outbound_report_configs", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("source_id", sa.Integer(), nullable=False), + sa.Column("parsing_profile_id", sa.Integer(), nullable=True), + sa.Column("report_path_json", sa.JSON(), server_default=sa.text("'{}'"), nullable=False), + sa.Column("query_parameters_json", sa.JSON(), server_default=sa.text("'[]'"), nullable=False), + sa.Column("config_version", sa.Integer(), server_default=sa.text("1"), nullable=False), + 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(["created_by"], ["users.id"]), + sa.ForeignKeyConstraint(["parsing_profile_id"], ["freight_rpa_parsing_profiles.id"]), + sa.ForeignKeyConstraint(["source_id"], ["freight_rpa_sources.id"]), + sa.ForeignKeyConstraint(["updated_by"], ["users.id"]), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("source_id", name="uq_freight_rpa_outbound_report_configs_source"), + ) + op.create_index( + "ix_freight_rpa_outbound_report_configs_parsing_profile_id", + "freight_rpa_outbound_report_configs", + ["parsing_profile_id"], + unique=False, + ) + op.create_index( + "ix_freight_rpa_outbound_report_configs_source_id", + "freight_rpa_outbound_report_configs", + ["source_id"], + unique=False, + ) + + # [STEP 3] 出站执行单元:回调幂等;schedule_run_id 可空以支持按需触发。 + op.create_table( + "freight_rpa_outbound_rpa_unit_runs", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("schedule_run_id", sa.Integer(), nullable=True), + sa.Column("source_id", sa.Integer(), nullable=False), + sa.Column("retry_of_id", sa.Integer(), nullable=True), + sa.Column("source_code", sa.String(length=64), nullable=False), + sa.Column("connector_type", sa.String(length=32), nullable=False), + sa.Column("warehouse_id", sa.String(length=64), nullable=True), + sa.Column("callback_id", sa.String(length=128), nullable=False), + sa.Column("status", sa.String(length=32), server_default="queued", nullable=False), + sa.Column("config_snapshot_json", sa.JSON(), nullable=False), + sa.Column("trigger_snapshot_json", sa.JSON(), nullable=False), + sa.Column("result_json", sa.JSON(), nullable=False), + sa.Column("error_code", sa.String(length=64), nullable=True), + sa.Column("error_message", sa.Text(), nullable=True), + sa.Column("started_at", sa.DateTime(), nullable=True), + sa.Column("finished_at", sa.DateTime(), nullable=True), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.CheckConstraint( + "status IN ('queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled')", + name="ck_freight_rpa_outbound_rpa_unit_runs_status", + ), + sa.ForeignKeyConstraint(["retry_of_id"], ["freight_rpa_outbound_rpa_unit_runs.id"]), + sa.ForeignKeyConstraint(["schedule_run_id"], ["schedule_runs.id"]), + sa.ForeignKeyConstraint(["source_id"], ["freight_rpa_sources.id"]), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("callback_id", name="uq_freight_rpa_outbound_rpa_unit_runs_callback"), + ) + op.create_index( + "ix_freight_rpa_outbound_rpa_unit_runs_retry_of_id", + "freight_rpa_outbound_rpa_unit_runs", + ["retry_of_id"], + unique=False, + ) + op.create_index( + "ix_freight_rpa_outbound_rpa_unit_runs_schedule_run_id", + "freight_rpa_outbound_rpa_unit_runs", + ["schedule_run_id"], + unique=False, + ) + op.create_index( + "ix_freight_rpa_outbound_rpa_unit_runs_source_id", + "freight_rpa_outbound_rpa_unit_runs", + ["source_id"], + unique=False, + ) + op.create_index( + "ix_freight_rpa_outbound_unit_run_schedule_status", + "freight_rpa_outbound_rpa_unit_runs", + ["schedule_run_id", "status"], + unique=False, + ) + op.create_index( + "ix_freight_rpa_outbound_unit_run_source_created", + "freight_rpa_outbound_rpa_unit_runs", + ["source_id", "created_at"], + unique=False, + ) + + # [STEP 4] 出站归档文件:含解析失败分层列,不建 notification_deliveries。 + op.create_table( + "freight_rpa_outbound_report_files", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("unit_run_id", sa.Integer(), nullable=False), + sa.Column("storage_provider", sa.String(length=32), nullable=False), + sa.Column("storage_bucket", sa.String(length=128), nullable=False), + sa.Column("storage_key", sa.String(length=1024), nullable=False), + sa.Column("original_filename", sa.String(length=255), nullable=False), + sa.Column("content_type", sa.String(length=128), nullable=True), + sa.Column("file_size", sa.Integer(), nullable=False), + sa.Column("sha256", sa.String(length=64), nullable=False), + sa.Column("parse_failed_at", sa.DateTime(), nullable=True), + sa.Column("parse_error_code", sa.String(length=64), nullable=True), + sa.Column("parse_error_message", sa.Text(), nullable=True), + sa.Column("archive_expires_at", sa.DateTime(), nullable=True), + sa.Column("archive_deleted_at", sa.DateTime(), nullable=True), + sa.Column("archive_delete_result_json", sa.JSON(), nullable=False), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.CheckConstraint("file_size >= 0", name="ck_freight_rpa_outbound_report_files_size"), + sa.ForeignKeyConstraint(["unit_run_id"], ["freight_rpa_outbound_rpa_unit_runs.id"]), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("unit_run_id", "sha256", name="uq_freight_rpa_outbound_report_files_unit_sha256"), + ) + op.create_index( + "ix_freight_rpa_outbound_report_files_expires", + "freight_rpa_outbound_report_files", + ["archive_expires_at", "archive_deleted_at"], + unique=False, + ) + op.create_index( + "ix_freight_rpa_outbound_report_files_unit", + "freight_rpa_outbound_report_files", + ["unit_run_id"], + unique=False, + ) + op.create_index( + "ix_freight_rpa_outbound_report_files_unit_run_id", + "freight_rpa_outbound_report_files", + ["unit_run_id"], + unique=False, + ) + + +def downgrade() -> None: + """Drop outbound tables, then restore the inbound deliveries table structure (empty).""" + op.drop_index( + "ix_freight_rpa_outbound_report_files_unit_run_id", + table_name="freight_rpa_outbound_report_files", + ) + op.drop_index( + "ix_freight_rpa_outbound_report_files_unit", + table_name="freight_rpa_outbound_report_files", + ) + op.drop_index( + "ix_freight_rpa_outbound_report_files_expires", + table_name="freight_rpa_outbound_report_files", + ) + op.drop_table("freight_rpa_outbound_report_files") + + op.drop_index( + "ix_freight_rpa_outbound_unit_run_source_created", + table_name="freight_rpa_outbound_rpa_unit_runs", + ) + op.drop_index( + "ix_freight_rpa_outbound_unit_run_schedule_status", + table_name="freight_rpa_outbound_rpa_unit_runs", + ) + op.drop_index( + "ix_freight_rpa_outbound_rpa_unit_runs_source_id", + table_name="freight_rpa_outbound_rpa_unit_runs", + ) + op.drop_index( + "ix_freight_rpa_outbound_rpa_unit_runs_schedule_run_id", + table_name="freight_rpa_outbound_rpa_unit_runs", + ) + op.drop_index( + "ix_freight_rpa_outbound_rpa_unit_runs_retry_of_id", + table_name="freight_rpa_outbound_rpa_unit_runs", + ) + op.drop_table("freight_rpa_outbound_rpa_unit_runs") + + op.drop_index( + "ix_freight_rpa_outbound_report_configs_source_id", + table_name="freight_rpa_outbound_report_configs", + ) + op.drop_index( + "ix_freight_rpa_outbound_report_configs_parsing_profile_id", + table_name="freight_rpa_outbound_report_configs", + ) + op.drop_table("freight_rpa_outbound_report_configs") + + # 还原投递表结构供降级路径;不回填 Task 2 之后的投递行。 + op.create_table( + _DELIVERIES_TABLE, + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("unit_run_id", sa.Integer(), nullable=True), + sa.Column("report_file_id", sa.Integer(), nullable=True), + sa.Column("recipient_user_id", sa.Integer(), nullable=False), + sa.Column("message_type", sa.String(length=16), nullable=False), + sa.Column("idempotency_key", sa.String(length=255), nullable=False), + sa.Column("status", sa.String(length=16), server_default=sa.text("'pending'"), nullable=False), + sa.Column("response_summary_json", sa.JSON(), server_default=sa.text("'{}'"), nullable=False), + sa.Column("error_code", sa.String(length=64), nullable=True), + sa.Column("error_message", sa.Text(), nullable=True), + sa.Column("sent_at", sa.DateTime(), nullable=True), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.Column("updated_at", sa.DateTime(), nullable=False), + sa.CheckConstraint( + "message_type IN ('file', 'summary')", + name="ck_freight_rpa_inbound_notification_deliveries_type", + ), + sa.CheckConstraint( + "status IN ('pending', 'sending', 'success', 'failed')", + name="ck_freight_rpa_inbound_notification_deliveries_status", + ), + sa.ForeignKeyConstraint(["unit_run_id"], ["freight_rpa_inbound_rpa_unit_runs.id"]), + sa.ForeignKeyConstraint(["report_file_id"], ["freight_rpa_inbound_report_files.id"]), + sa.ForeignKeyConstraint(["recipient_user_id"], ["users.id"]), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint( + "idempotency_key", + name="uq_freight_rpa_inbound_notification_deliveries_idempotency", + ), + ) + op.create_index( + "ix_fr_inbound_notif_deliveries_recipient_user_id", + _DELIVERIES_TABLE, + ["recipient_user_id"], + unique=False, + ) + op.create_index( + "ix_shipping_receipt_delivery_file_recipient", + _DELIVERIES_TABLE, + ["report_file_id", "recipient_user_id"], + unique=False, + ) + op.create_index( + "ix_shipping_receipt_delivery_unit_created", + _DELIVERIES_TABLE, + ["unit_run_id", "created_at"], + unique=False, + ) diff --git a/backend/tests/api/test_freight_rpa_api.py b/backend/tests/api/test_freight_rpa_api.py index bba3ccef..380d6f15 100644 --- a/backend/tests/api/test_freight_rpa_api.py +++ b/backend/tests/api/test_freight_rpa_api.py @@ -212,7 +212,7 @@ def test_onhand_repair_envelope_matches_legacy(client, tool_auth_headers): # --------------------------------------------------------------------------- def test_inbound_unit_progress_envelope_matches_legacy(client, tool_auth_headers): - """inbound-unit-progress(旧直连 jsonify({'success':True,'data':mark_receipt_unit_processing(p)})): + """inbound-unit-progress(旧直连 jsonify({'success':True,'data':mark_inbound_unit_processing(p)})): schema 非法分支 data={'updated':False,'reason':'callback_schema_invalid'},证明 sink 已注册 (未注册会是 404 FREIGHT_RPA.SINK_NOT_REGISTERED)且 envelope 未漂移。""" resp = client.post("/api/freight-rpa/inbound-unit-progress", json={}, headers=tool_auth_headers) @@ -235,17 +235,17 @@ def test_inbound_batch_progress_envelope_matches_legacy(client, tool_auth_header def test_inbound_batch_ready_schema_invalid_reaches_business_validation(client, tool_auth_headers): """inbound-batch-ready sink 已注册:schema 非法穿透到业务校验(400 + - SHIPPING.RECEIPT_CALLBACK_INVALID),而非未注册 404;错误 envelope 与拆分前同形 + SHIPPING.INBOUND_CALLBACK_INVALID),而非未注册 404;错误 envelope 与拆分前同形 (旧端点在 jsonify 之前由 ingest 抛 ValidationError → 全局 AppError handler)。""" resp = client.post("/api/freight-rpa/inbound-batch-ready", json={}, headers=tool_auth_headers) assert resp.status_code == 400 body = resp.get_json() assert body["success"] is False - assert body["error"]["code"] == "SHIPPING.RECEIPT_CALLBACK_INVALID" + assert body["error"]["code"] == "SHIPPING.INBOUND_CALLBACK_INVALID" def test_inbound_batch_ready_unknown_unit_is_404(client, tool_auth_headers): - """inbound-batch-ready 未知 callback_id:404 + SHIPPING.RECEIPT_UNIT_NOT_FOUND, + """inbound-batch-ready 未知 callback_id:404 + SHIPPING.INBOUND_UNIT_NOT_FOUND, 与拆分前 ingest 直连时的 NotFoundError 路径逐字一致。""" resp = client.post( "/api/freight-rpa/inbound-batch-ready", @@ -254,7 +254,7 @@ def test_inbound_batch_ready_unknown_unit_is_404(client, tool_auth_headers): ) assert resp.status_code == 404 body = resp.get_json() - assert body["error"]["code"] == "SHIPPING.RECEIPT_UNIT_NOT_FOUND" + assert body["error"]["code"] == "SHIPPING.INBOUND_UNIT_NOT_FOUND" @pytest.mark.pure_unit diff --git a/backend/tests/services/admin/test_shipping_onhand_service.py b/backend/tests/services/admin/test_shipping_onhand_service.py index 1d37f15b..907ff9de 100644 --- a/backend/tests/services/admin/test_shipping_onhand_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_onhand_admin_service、库存配置模型。 +依赖:Flask app/db、freight_rpa_source_admin_service、shipping_onhand_admin_service、库存配置模型。 逻辑:管理后台写配置前锁定凭据脱敏、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。 """ @@ -12,8 +12,8 @@ from cryptography.fernet import Fernet import pytest from app.core.errors import ConflictError, ValidationError -from app.services.admin import shipping_onhand_admin_service -from app.services.shipping_notice import onhand_parsing_profile +from app.services.admin import freight_rpa_source_admin_service, shipping_onhand_admin_service +from app.services.freight_rpa import parsing_profile as onhand_parsing_profile from app.services.shipping_notice.order_schema import service as order_schema_service from app import db from app.models import ( @@ -164,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_onhand_admin_service.save_profile(_profile_data(), actor_id=None) + payload = freight_rpa_source_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 @@ -178,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_onhand_admin_service.save_profile(payload, actor_id=None) + freight_rpa_source_admin_service.save_profile(payload, actor_id=None) assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_CONFIG_INVALID' @@ -186,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_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) + first = freight_rpa_source_admin_service.save_profile(_profile_data(code='DBS_EU_A'), actor_id=None) + second = freight_rpa_source_admin_service.save_profile(_profile_data(code='DBS_EU_B'), actor_id=None) + first_source = freight_rpa_source_admin_service.save_source(_source_data(first['id'], code='DBS_DUB'), actor_id=None) + second_source = freight_rpa_source_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'] @@ -198,9 +198,9 @@ 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_onhand_admin_service.save_profile(_profile_data(connector_type='crane'), actor_id=None) + profile = freight_rpa_source_admin_service.save_profile(_profile_data(connector_type='crane'), actor_id=None) with pytest.raises(ValidationError) as exc_info: - shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None) + freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None) assert exc_info.value.code == 'SHIPPING.ONHAND_PROFILE_CONNECTOR_MISMATCH' @@ -208,18 +208,18 @@ 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_onhand_admin_service.save_profile(_profile_data(code='DRAFT_SOURCE_LOGIN'), actor_id=None) + login = freight_rpa_source_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, 'excel_template_id': None}) payload['onhand_report_config']['parsing_profile_id'] = None - draft = shipping_onhand_admin_service.save_source(payload, actor_id=None) + draft = freight_rpa_source_admin_service.save_source(payload, actor_id=None) assert draft['enabled'] is False 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_onhand_admin_service.save_source(payload, actor_id=None, source_id=draft['id']) + freight_rpa_source_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。 @@ -227,7 +227,7 @@ def test_disabled_source_can_be_saved_before_profile_and_template_binding(app): 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']) + enabled = freight_rpa_source_admin_service.save_source(payload, actor_id=None, source_id=draft['id']) assert enabled['enabled'] is True @@ -235,22 +235,22 @@ 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_onhand_admin_service.save_profile(_profile_data(code='ACTIVATION_LOGIN'), actor_id=None) + login = freight_rpa_source_admin_service.save_profile(_profile_data(code='ACTIVATION_LOGIN'), actor_id=None) payload = _source_data(login['id'], code='ACTIVATION_SOURCE') 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) + draft = freight_rpa_source_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_onhand_admin_service.save_source( + saved = freight_rpa_source_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_onhand_admin_service.activate_source(draft['id'], actor_id=None) + freight_rpa_source_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'] @@ -259,7 +259,7 @@ 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_onhand_admin_service.save_profile(_profile_data(code='CHECKS_LOGIN'), actor_id=None) + login = freight_rpa_source_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'], 'excel_template_id': None, @@ -275,7 +275,7 @@ def test_activation_status_exposes_only_hard_gate_checks(app): }, 'enabled': False, } - draft = shipping_onhand_admin_service.save_source(payload, actor_id=None, allow_enable_transition=False) + draft = freight_rpa_source_admin_service.save_source(payload, actor_id=None, allow_enable_transition=False) checks = {item['code']: item for item in draft['activation']['checks']} @@ -292,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_onhand_admin_service.save_profile( + profile = freight_rpa_source_admin_service.save_profile( {**_profile_data(code='DISABLED_LOGIN'), 'enabled': False}, actor_id=None, ) with pytest.raises(ValidationError) as exc_info: - shipping_onhand_admin_service.save_source(_source_data(profile['id'], code='BLOCKED_SOURCE'), actor_id=None) + freight_rpa_source_admin_service.save_source(_source_data(profile['id'], code='BLOCKED_SOURCE'), actor_id=None) assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DISABLED' @@ -304,8 +304,8 @@ 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_onhand_admin_service.save_profile(_profile_data(), actor_id=None) - source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None) + profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None) + source = freight_rpa_source_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'] == [ @@ -317,11 +317,11 @@ 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_onhand_admin_service.save_profile(_profile_data(), actor_id=None) + profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None) payload = _source_data(profile['id']) payload['onhand_report_config']['query_parameters_json'][0]['selector_env'] = 'FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR' with pytest.raises(ValidationError) as exc_info: - shipping_onhand_admin_service.save_source(payload, actor_id=None) + freight_rpa_source_admin_service.save_source(payload, actor_id=None) assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_CONFIG_INVALID' @@ -329,12 +329,12 @@ 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_onhand_admin_service.save_profile(_profile_data(code='CRANE', connector_type='crane'), actor_id=None) + profile = freight_rpa_source_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_onhand_admin_service.save_source(payload, actor_id=None) + freight_rpa_source_admin_service.save_source(payload, actor_id=None) assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_CONFIG_INVALID' @@ -342,14 +342,14 @@ def test_direct_parsing_profile_binding_keeps_source_disabled_and_writes_audit(a """停用站点可直接绑定已发布方案;绑定必须递增版本并留下不可变审计。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - login = shipping_onhand_admin_service.save_profile(_profile_data(code='DIRECT_BIND_LOGIN'), actor_id=7) + login = freight_rpa_source_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}) payload['onhand_report_config']['parsing_profile_id'] = None - source = shipping_onhand_admin_service.save_source(payload, actor_id=7, allow_enable_transition=False) + source = freight_rpa_source_admin_service.save_source(payload, actor_id=7, allow_enable_transition=False) profile = _parsing_profile() - bound = shipping_onhand_admin_service.bind_source_parsing_profile( + bound = freight_rpa_source_admin_service.bind_source_parsing_profile( [source['id']], profile['id'], actor_id=7, operation='direct', ) @@ -364,7 +364,7 @@ def test_direct_parsing_profile_binding_keeps_source_disabled_and_writes_audit(a 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_onhand_admin_service.get_source_parsing_binding_audits(source['id']) + history = freight_rpa_source_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'] @@ -373,15 +373,15 @@ 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_onhand_admin_service.save_profile(_profile_data(code='BULK_BIND_LOGIN'), actor_id=None) + login = freight_rpa_source_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}) 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) + disabled = freight_rpa_source_admin_service.save_source(disabled_payload, actor_id=None, allow_enable_transition=False) + enabled = freight_rpa_source_admin_service.save_source(_source_data(login['id'], code='BULK_BIND_ENABLED'), actor_id=None) profile = _parsing_profile() - bound = shipping_onhand_admin_service.bind_source_parsing_profile( + bound = freight_rpa_source_admin_service.bind_source_parsing_profile( [disabled['id'], enabled['id']], profile['id'], actor_id=None, reason='批量迁移同类报表', operation='bulk', ) @@ -398,11 +398,11 @@ 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_onhand_admin_service.save_profile(_profile_data(code='TEMPLATE_GATE_LOGIN'), actor_id=None) + login = freight_rpa_source_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}) payload['onhand_report_config']['parsing_profile_id'] = None - source = shipping_onhand_admin_service.save_source(payload, actor_id=None, allow_enable_transition=False) + source = freight_rpa_source_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', @@ -411,7 +411,7 @@ def test_direct_parsing_binding_rejects_template_fields_missing_from_profile(app db.session.commit() with pytest.raises(ValidationError) as exc_info: - shipping_onhand_admin_service.bind_source_parsing_profile( + freight_rpa_source_admin_service.bind_source_parsing_profile( [source['id']], _parsing_profile()['id'], actor_id=None, reason='模板字段契约预检', operation='direct', ) @@ -427,8 +427,8 @@ 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_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) + profile = freight_rpa_source_admin_service.save_profile(_profile_data(code='IMMUTABLE_RULE_LOGIN'), actor_id=None) + source = freight_rpa_source_admin_service.save_source(_source_data(profile['id'], code='DBS_DUB'), actor_id=None) reservation_field_id = _published_route_field_id() rule = shipping_onhand_admin_service.save_rule({ 'rule_code': 'RSV_PREFIX_1', 'rule_name': 'Reservation starts with 1', 'scope': 'line', @@ -489,17 +489,17 @@ 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_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()) + unused = freight_rpa_source_admin_service.save_profile(_profile_data(code='UNUSED'), actor_id=None) + freight_rpa_source_admin_service.delete_profile(unused['id']) + assert all(item['profile_code'] != 'UNUSED' for item in freight_rpa_source_admin_service.list_profiles()) - 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) + profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None) + source = freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None) with pytest.raises(ConflictError) as exc_info: - shipping_onhand_admin_service.delete_profile(profile['id']) + freight_rpa_source_admin_service.delete_profile(profile['id']) assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DELETE_BLOCKED' with pytest.raises(ConflictError) as exc_info: - shipping_onhand_admin_service.save_profile({**_profile_data(), 'enabled': False}, actor_id=None, profile_id=profile['id']) + freight_rpa_source_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() @@ -520,12 +520,12 @@ 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_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) + profile = freight_rpa_source_admin_service.save_profile(_profile_data(code='ROUTE_LOGIN'), actor_id=None) + source = freight_rpa_source_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, 'excel_template_id': None}) disabled_payload['onhand_report_config']['parsing_profile_id'] = None - shipping_onhand_admin_service.save_source(disabled_payload, actor_id=None) + freight_rpa_source_admin_service.save_source(disabled_payload, actor_id=None) reservation_field_id = _published_route_field_id() missing_rule = shipping_onhand_admin_service.save_rule({ @@ -556,8 +556,8 @@ 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_onhand_admin_service.save_profile(_profile_data(), actor_id=None) - source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None) + profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None) + source = freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None) payload = { 'source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP', 'external_organization_code': None, 'external_site_code': 'EU01', @@ -573,8 +573,8 @@ 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_onhand_admin_service.save_profile(_profile_data(), actor_id=None) - source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None) + profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None) + source = freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None) # [断言意图] 货代仓库为空不阻断保存;在途仓编码必填且大写归一后随 payload 返回。 mapping = shipping_onhand_admin_service.save_external_mapping({ 'source_id': source['id'], 'freight_warehouse_id': None, 'external_system_code': 'TOPGP', @@ -589,8 +589,8 @@ 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_onhand_admin_service.save_profile(_profile_data(), actor_id=None) - source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None) + profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None) + source = freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None) # [断言意图] 缺在途仓编码的映射会让调拨拨出库位无来源,保存端必须 fail-closed。 with pytest.raises(ValidationError): shipping_onhand_admin_service.save_external_mapping({ @@ -603,8 +603,8 @@ 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_onhand_admin_service.save_profile(_profile_data(), actor_id=None) - source = shipping_onhand_admin_service.save_source(_source_data(profile['id']), actor_id=None) + profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None) + source = freight_rpa_source_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', @@ -617,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_onhand_admin_service.save_profile(_profile_data(), actor_id=None) + profile = freight_rpa_source_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_onhand_admin_service.save_profile( + updated = freight_rpa_source_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_onhand_admin_service.save_profile( + bumped = freight_rpa_source_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_onhand_admin_service.save_profile( + freight_rpa_source_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_onhand_admin_service.save_profile( + freight_rpa_source_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_outbound_trigger_contract.py b/backend/tests/services/freight_rpa/test_outbound_trigger_contract.py new file mode 100644 index 00000000..9f4c2630 --- /dev/null +++ b/backend/tests/services/freight_rpa/test_outbound_trigger_contract.py @@ -0,0 +1,16 @@ +""" +tests/services/freight_rpa/test_outbound_trigger_contract.py + +用途:出站 RPA trigger_io 与 Worker 心跳能力串的契约常量回归。 +依赖:freight_rpa.outbound.trigger_io、worker_heartbeat.OUTBOUND_EXPORT_CAPABILITY。 +逻辑:Task 7 接口清单的单一真相,防止 schema/action/能力名漂移。 +""" +from app.services.freight_rpa.outbound import trigger_io +from app.services.freight_rpa.common.worker_heartbeat import OUTBOUND_EXPORT_CAPABILITY + + +def test_outbound_trigger_constants(): + """出站 trigger schema/action 与 Worker outbound_export 能力须与设计 spec 一致。""" + assert trigger_io.SCHEMA == "freight_rpa.outbound.v1" + assert trigger_io.ACTION_OUTBOUND_EXPORT_BATCH == "outbound_export_batch" + assert OUTBOUND_EXPORT_CAPABILITY == "outbound_export" diff --git a/backend/tests/services/freight_rpa/test_report_fact_dispatch.py b/backend/tests/services/freight_rpa/test_report_fact_dispatch.py index 5bfa0c1e..cf1f28b4 100644 --- a/backend/tests/services/freight_rpa/test_report_fact_dispatch.py +++ b/backend/tests/services/freight_rpa/test_report_fact_dispatch.py @@ -179,18 +179,18 @@ def test_empty_callback_dispatches_failure_fact(app, db_session): "schema_version": "freight_rpa.inbound.v1", "callback_id": unit.callback_id, "status": "empty", - "error_code": "no_receipt_data", - "error_message": "no_receipt_data", + "error_code": "no_inbound_data", + "error_message": "no_inbound_data", } ) assert result["status"] == "empty" assert len(seen) == 1 fact = seen[0] - # [断言意图] empty 是合法业务结果 → ok=False + error_code=no_receipt_data 的事实。 + # [断言意图] empty 是合法业务结果 → ok=False + error_code=no_inbound_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" + assert fact.error_code == "no_inbound_data" + assert fact.error_message == "no_inbound_data" diff --git a/backend/tests/services/freight_rpa/test_worker_heartbeat.py b/backend/tests/services/freight_rpa/test_worker_heartbeat.py index f8bcf49e..a7eed125 100644 --- a/backend/tests/services/freight_rpa/test_worker_heartbeat.py +++ b/backend/tests/services/freight_rpa/test_worker_heartbeat.py @@ -202,13 +202,13 @@ def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path assert (exc_info.value.details or {}).get("detail_message") -def test_assert_receipt_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch): +def test_assert_inbound_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch): """收料 fail-fast 应附带 reasons,且与库存同口径要求共享哨兵。""" from app.core.errors import ServiceUnavailableError from app.services.freight_rpa.common import worker_heartbeat as heartbeat_module from app.services.freight_rpa.common.worker_heartbeat import ( RPA_WORKER_OFFLINE_MESSAGE, - assert_receipt_rpa_worker_ready, + assert_inbound_rpa_worker_ready, reset_rpa_worker_heartbeat_state_for_tests, ) @@ -224,7 +224,7 @@ def test_assert_receipt_rpa_worker_ready_includes_reason_details(app, tmp_path, with app.app_context(): with pytest.raises(ServiceUnavailableError) as exc_info: - assert_receipt_rpa_worker_ready() + assert_inbound_rpa_worker_ready() # [断言意图] 与库存同构的用户可见文案与 reasons;缺哨兵与无心跳同时暴露, # 对应部署侧必须由 ps1 注入 FREIGHT_RPA_SHARED_SCOPE_ID 写哨兵。 assert exc_info.value.message == RPA_WORKER_OFFLINE_MESSAGE @@ -502,7 +502,7 @@ def test_assert_freight_upload_rpa_ready_includes_reasons(app, tmp_path): def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path): """收料 ready 与库存同口径:要求共享哨兵;仅有库存 Worker 不能冒充收料在线。""" from app.services.freight_rpa.common.worker_heartbeat import ( - check_receipt_rpa_worker_ready, + check_inbound_rpa_worker_ready, reset_rpa_worker_heartbeat_state_for_tests, serialize_rpa_worker_status, ) @@ -528,7 +528,7 @@ def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path): trigger_dir=str(inventory_trigger), shared_scope_id="hxops-rpa-test-data", )) - receipt_offline = check_receipt_rpa_worker_ready() + receipt_offline = check_inbound_rpa_worker_ready() assert receipt_offline.ready is False assert receipt_offline.workers == [] @@ -539,11 +539,11 @@ def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path): shared_scope_id="hxops-rpa-test-data", capabilities=[INBOUND_EXPORT_CAPABILITY], )) - without_sentinel = check_receipt_rpa_worker_ready() + without_sentinel = check_inbound_rpa_worker_ready() assert without_sentinel.ready is False _write_shared_sentinel(receipt_trigger, scope_id="hxops-rpa-test-data") - receipt_ready = check_receipt_rpa_worker_ready() + receipt_ready = check_inbound_rpa_worker_ready() assert receipt_ready.ready is True assert [w["worker_id"] for w in receipt_ready.workers] == ["HOST-receipt"] @@ -557,7 +557,7 @@ def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path): def test_receipt_worker_recognized_by_trigger_dir_without_receipt_suffix(app, tmp_path): """未注入 *-receipt 身份时,仍可用收料 trigger_dir 识别在线收料 Worker。""" from app.services.freight_rpa.common.worker_heartbeat import ( - check_receipt_rpa_worker_ready, + check_inbound_rpa_worker_ready, reset_rpa_worker_heartbeat_state_for_tests, ) @@ -579,6 +579,6 @@ def test_receipt_worker_recognized_by_trigger_dir_without_receipt_suffix(app, tm shared_scope_id="", capabilities=[INBOUND_EXPORT_CAPABILITY], )) - result = check_receipt_rpa_worker_ready() + result = check_inbound_rpa_worker_ready() assert result.ready is True assert [w["worker_id"] for w in result.workers] == ["Hugo-30820"] 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 index 0c447916..c0e4e9d1 100644 --- a/backend/tests/services/in_transit_transfer/test_inbound_report_handler.py +++ b/backend/tests/services/in_transit_transfer/test_inbound_report_handler.py @@ -180,7 +180,7 @@ def test_no_waiting_job_is_success(app, db_session): def _awaiting_schedule_run(db_session, *, schedule_no: str, run_no: str, awaiting: bool = True): - """构造一个收料排程 task/run 对;awaiting=True 时挂 awaiting_receipt_rpa 等待态。""" + """构造一个收料排程 task/run 对;awaiting=True 时挂 awaiting_inbound_rpa 等待态。""" from app.models import ScheduleRun, ScheduleTask task = ScheduleTask( @@ -192,7 +192,7 @@ def _awaiting_schedule_run(db_session, *, schedule_no: str, run_no: str, awaitin 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}, + response_summary_json={'awaiting_inbound_rpa': awaiting}, ) db_session.add(run) db_session.commit() @@ -218,7 +218,7 @@ def test_finalize_targets_unit_of_this_callback_not_newest_unit(app, db_session, """同来源两个单元分属两个排程 run:本回调收尾的单元(按文件反查)只收口它自己的 run。 [断言意图] 修复「按来源取最新单元」的错位:旧逻辑会把收口打到更新单元的 run, - 本回调刚完成的 run 永久滞留 awaiting_receipt_rpa。 + 本回调刚完成的 run 永久滞留 awaiting_inbound_rpa。 """ from app.models import ScheduleRun from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback @@ -254,18 +254,18 @@ def test_finalize_targets_unit_of_this_callback_not_newest_unit(app, db_session, # [断言意图] 本回调收尾的是旧单元:只有旧 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") + assert not (refreshed_old.response_summary_json or {}).get("awaiting_inbound_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 + assert (refreshed_new.response_summary_json or {}).get("awaiting_inbound_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。 + 会收口新单元的 run,本回调刚失败的 run 永久滞留 awaiting_inbound_rpa。 """ from datetime import datetime @@ -310,11 +310,11 @@ def test_finalize_targets_failed_unit_of_this_callback_not_newest_unit(app, db_s # [断言意图] 只有旧单元的 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") + assert not (refreshed_old.response_summary_json or {}).get("awaiting_inbound_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 + assert (refreshed_new.response_summary_json or {}).get("awaiting_inbound_rpa") is True diff --git a/backend/tests/services/in_transit_transfer/test_outbound_trigger_service.py b/backend/tests/services/in_transit_transfer/test_outbound_trigger_service.py new file mode 100644 index 00000000..a0e5d5c6 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_outbound_trigger_service.py @@ -0,0 +1,316 @@ +"""出站 RPA 触发服务与报表处理函数测试。 + +用途:验证 trigger_outbound_rpa / trigger_outbound_rpa_batch 按来源装配出站 + trigger unit 并调用写者;站点停用 / 出站配置缺失 / 登录连接缺失 fail-closed; + handle_outbound_report 把等待中的 TransferSourceJob 从 waiting_rpa_callback + 推进到 file_ready(无等待任务 no-op,可重入)。 +依赖:app(SQLite)fixture、outbound_trigger_service、outbound_report_handler、 + 既有测试种子(FreightRpaProfile/FreightRpaSource)。 +逻辑:对照 test_inbound_trigger_service;出站配置行挂 FreightRpaOutboundReportConfig; + 写者协议与入站一致(payload= 附加字段);handler 只改调拨等待行,不写新状态。 +""" + +from __future__ import annotations + +import pytest + +from app.models import FreightRpaSource, FreightRpaOutboundReportConfig +from app.services.in_transit_transfer.outbound_trigger_service import ( + trigger_outbound_rpa, + trigger_outbound_rpa_batch, +) + + +@pytest.fixture +def outbound_source(): + """复用种子来源并为其创建出站配置。""" + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first() + assert source is not None + config = FreightRpaOutboundReportConfig( + source_id=source.id, + report_path_json={'program_group': 'Bison', 'report_name': 'Outbound Details'}, + query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False}], + ) + from app import db + + db.session.add(config) + db.session.commit() + return source + + +def test_trigger_outbound_rpa_disabled_source_fails_closed(app): + """来源停用 → ok=False,不写 trigger。""" + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first() + source.enabled = False + from app import db + + db.session.commit() + result = trigger_outbound_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06') + assert result['ok'] is False + assert result['error_code'] == 'RPA_OUTBOUND_CONFIG_MISSING' + + +def test_trigger_outbound_rpa_missing_config_fails_closed(app): + """来源启用但无出站配置 → ok=False。""" + result = trigger_outbound_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06') + assert result['ok'] is False + assert result['error_code'] == 'RPA_OUTBOUND_CONFIG_MISSING' + + +def test_trigger_outbound_rpa_missing_login_fails_closed(app, outbound_source): + """出站配置存在但登录连接停用 → ok=False,不写 trigger。""" + from app import db + + outbound_source.rpa_profile.enabled = False + db.session.commit() + result = trigger_outbound_rpa( + source_code='DSV360_AWSDU', business_date='2026-08-06', + writer=lambda *a, **k: (_ for _ in ()).throw(AssertionError('writer must not be called')), + ) + assert result['ok'] is False + assert result['error_code'] == 'RPA_OUTBOUND_CONFIG_MISSING' + + +def test_trigger_outbound_rpa_writes_batch_trigger(app, outbound_source): + """来源有效 → 写入 trigger 并返回 callback_id / trigger_path。""" + calls = {} + + def fake_writer(run_no, units, payload=None): + calls['run_no'] = run_no + calls['units'] = units + calls['payload'] = payload or {} + return f'/tmp/trigger/{run_no}.json' + + result = trigger_outbound_rpa( + source_code='DSV360_AWSDU', business_date='2026-08-06', + reason='transfer_retry_outbound', writer=fake_writer, + ) + assert result['ok'] is True + assert result['callback_id'] + assert result['trigger_path'].endswith('.json') + assert calls['units'][0]['source_code'] == 'DSV360_AWSDU' + assert calls['units'][0]['warehouse_id'] is None + assert calls['units'][0]['query_parameters_json'] == [ + {'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False}, + ] + assert calls['units'][0]['credential_envelope'] + assert calls['payload']['schema_version'] == 'freight_rpa.outbound.v1' + + +def test_trigger_outbound_rpa_creates_unit_run_before_writing_trigger(app, outbound_source): + """触发必须先落 FreightRpaOutboundUnitRun(awaiting_rpa),否则回调按 callback_id 404。""" + from app.models import FreightRpaOutboundUnitRun + + captured: dict = {} + + def fake_writer(run_no, units, payload=None): + captured['units'] = units + return 'trigger.json' + + outcome = trigger_outbound_rpa( + source_code=outbound_source.source_code, business_date='2026-10-19', + reason='transfer_retry_outbound', writer=fake_writer, + ) + assert outcome['ok'] is True + unit = FreightRpaOutboundUnitRun.query.filter_by(callback_id=outcome['callback_id']).one() + assert unit.status == 'awaiting_rpa' + assert unit.schedule_run_id is None + assert FreightRpaOutboundUnitRun.__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 test_trigger_outbound_rpa_marks_unit_failed_when_trigger_unavailable(app, outbound_source): + """trigger 目录不可用(writer 返回 None)时单元必须标 failed,不留永久 awaiting 幽灵。""" + from app.models import FreightRpaOutboundUnitRun + + outcome = trigger_outbound_rpa( + source_code=outbound_source.source_code, business_date='2026-10-19', + reason='transfer_retry_outbound', writer=lambda *a, **k: None, + ) + assert outcome['ok'] is False + unit = FreightRpaOutboundUnitRun.query.filter_by(source_code=outbound_source.source_code).order_by( + FreightRpaOutboundUnitRun.id.desc()).first() + assert unit.status == 'failed' + assert unit.error_code == 'RPA_OUTBOUND_TRIGGER_UNAVAILABLE' + + +@pytest.fixture +def second_outbound_source(app): + """再造一个启用来源 + 出站配置(批量用例需要多来源)。""" + from app import db + from app.models import FreightRpaOnhandReportConfig, FreightRpaSource, FreightRpaProfile, FreightRpaOutboundReportConfig + + seed = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first() + profile = FreightRpaProfile( + profile_code='DBS_SG_OUT_TEST', display_name='DBS SG Out', connector_type='dbs', + login_url='https://test.invalid/dbs-sg', login_config_json={'auth_mode': 'password'}, + ) + source = FreightRpaSource( + source_code='DSV360_AWSSG', display_name='DBS SG AWSSG', connector_type='dbs', + rpa_profile=profile, + excel_template=seed.excel_template, + warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSSG', + enabled=True, + ) + 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() + config = FreightRpaOutboundReportConfig( + source_id=source.id, + report_path_json={'program_group': 'Bison', 'report_name': 'Outbound Details'}, + query_parameters_json=[], + ) + db.session.add(config) + db.session.commit() + return source + + +def test_trigger_outbound_rpa_batch_writes_one_trigger_for_all_units(app, outbound_source, second_outbound_source): + """多来源 → 只写一次 trigger(一个文件 N units),各单元独立 callback_id/unit_run_id。""" + from app.models import FreightRpaOutboundUnitRun + + calls: list = [] + + def fake_writer(run_no, units, payload=None): + calls.append({'run_no': run_no, 'units': units, 'payload': payload or {}}) + return f'/tmp/trigger/{run_no}.json' + + outcome = trigger_outbound_rpa_batch( + source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-19', + reason='transfer_retry_outbound', writer=fake_writer, + ) + assert len(calls) == 1 + assert outcome['ok'] is True and outcome['triggered'] is True + assert calls[0]['run_no'].startswith('TRIG-BATCH-') + assert [u['source_code'] for u in calls[0]['units']] == ['DSV360_AWSDU', 'DSV360_AWSSG'] + assert calls[0]['payload']['schema_version'] == 'freight_rpa.outbound.v1' + callback_ids = {u['callback_id'] for u in calls[0]['units']} + assert len(callback_ids) == 2 + rows = FreightRpaOutboundUnitRun.query.filter(FreightRpaOutboundUnitRun.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) + assert {row.id for row in rows} == {u['unit_run_id'] for u in calls[0]['units']} + + +def test_trigger_outbound_rpa_batch_skips_invalid_source(app, outbound_source): + """单源配置缺失 → 跳过该源并逐源记录 error_code,其余来源照常进 batch trigger。""" + captured: dict = {} + + def fake_writer(run_no, units, payload=None): + captured['units'] = units + return f'/tmp/trigger/{run_no}.json' + + outcome = trigger_outbound_rpa_batch( + source_codes=['DSV360_AWSDU', 'DSV360_NOPE'], business_date='2026-10-19', + writer=fake_writer, + ) + assert outcome['ok'] is True and outcome['triggered'] is True + assert [u['source_code'] for u in captured['units']] == ['DSV360_AWSDU'] + by_code = {item['source_code']: item for item in outcome['results']} + assert by_code['DSV360_AWSDU']['ok'] is True + assert by_code['DSV360_NOPE']['ok'] is False + assert by_code['DSV360_NOPE']['error_code'] == 'RPA_OUTBOUND_CONFIG_MISSING' + + +def test_trigger_outbound_rpa_batch_all_invalid_no_trigger(app): + """全部来源无效 → 不写 trigger,ok=False + RPA_OUTBOUND_NO_TRIGGERABLE_SOURCE。""" + outcome = trigger_outbound_rpa_batch( + source_codes=['DSV360_NOPE'], business_date='2026-10-19', + writer=lambda *a, **k: (_ for _ in ()).throw(AssertionError('writer must not be called')), + ) + assert outcome['ok'] is False and outcome['triggered'] is False + assert outcome['error_code'] == 'RPA_OUTBOUND_NO_TRIGGERABLE_SOURCE' + + +def test_trigger_outbound_rpa_batch_writer_unavailable_marks_all_failed(app, outbound_source, second_outbound_source): + """trigger 目录不可用 → 本批全部单元标 failed,不留永久 awaiting 幽灵。""" + from app.models import FreightRpaOutboundUnitRun + + outcome = trigger_outbound_rpa_batch( + source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-19', + writer=lambda *a, **k: None, + ) + assert outcome['ok'] is False and outcome['triggered'] is False + assert outcome['error_code'] == 'RPA_OUTBOUND_TRIGGER_UNAVAILABLE' + rows = FreightRpaOutboundUnitRun.query.filter(FreightRpaOutboundUnitRun.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_OUTBOUND_TRIGGER_UNAVAILABLE'} + + +def _waiting_job(source_code: str): + """构造一个未落库的 waiting_rpa_callback 来源任务。""" + from app import db + from app.models import TransferRun, TransferSourceJob + + run = TransferRun( + run_no=f'RUN-OUT-{source_code}', + business_date='2026-10-19', + 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 test_handle_outbound_report_advances_waiting_job_to_file_ready(app): + """ok 事实把等待中的 SourceJob 从 waiting_rpa_callback 推进到 file_ready。""" + from app import db + from app.services.freight_rpa.reports.facts import ReportFact + from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report + + job = _waiting_job('DSV') + db.session.add(job) + db.session.commit() + handle_outbound_report(ReportFact( + report_kind='outbound', source_code='DSV', file_id=42, sha256='abc', ok=True, + )) + db.session.refresh(job) + assert job.status == 'file_ready' + assert job.file_no == '42' + assert job.file_sha256 == 'abc' + + +def test_handle_outbound_report_noop_without_waiting_job(app): + """无等待中的调拨任务:处理函数 no-op,不产生任何调拨来源任务行。""" + from app.models import TransferSourceJob + from app.services.freight_rpa.reports.facts import ReportFact + from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report + + handle_outbound_report(ReportFact( + report_kind='outbound', source_code='DSV', file_id=42, sha256='abc', ok=True, + )) + assert TransferSourceJob.query.filter_by(source_code='DSV').count() == 0 + + +def test_handle_outbound_report_is_reentrant(app): + """第二次投递时该行已离开等待态,不再改(可重入)。""" + from app import db + from app.services.freight_rpa.reports.facts import ReportFact + from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report + + job = _waiting_job('DSV') + db.session.add(job) + db.session.commit() + fact = ReportFact(report_kind='outbound', source_code='DSV', file_id=42, sha256='abc', ok=True) + handle_outbound_report(fact) + db.session.refresh(job) + first_finished = job.finished_at + handle_outbound_report(ReportFact( + report_kind='outbound', source_code='DSV', file_id=99, sha256='zzz', ok=True, + )) + db.session.refresh(job) + assert job.status == 'file_ready' + assert job.file_no == '42' + assert job.file_sha256 == 'abc' + assert job.finished_at == first_finished + diff --git a/backend/tests/services/in_transit_transfer/test_rpa_sinks_ownership.py b/backend/tests/services/in_transit_transfer/test_rpa_sinks_ownership.py new file mode 100644 index 00000000..4097b053 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_rpa_sinks_ownership.py @@ -0,0 +1,51 @@ +""" +tests/services/in_transit_transfer/test_rpa_sinks_ownership.py + +用途:锁定入站/出站 sink 组合根归属——住在 in_transit_transfer,不在 shipping_notice; + inbound-batch-ready 直挂 freight_rpa 归档入口(无 shipping_notice Middle Man)。 +""" + +from __future__ import annotations + +import importlib + +import pytest + + +def test_shipping_notice_rpa_sinks_only_exposes_onhand_registration(): + """发货包只保留 onhand 注册入口,不再导出 inbound/outbound 注册。""" + sinks = importlib.import_module('app.services.shipping_notice.rpa_sinks') + assert hasattr(sinks, 'register_onhand_sinks') + assert not hasattr(sinks, 'register_inbound_sinks') + assert not hasattr(sinks, 'register_outbound_sinks') + + +def test_shipping_notice_inbound_report_storage_module_removed(): + """入站 Middle Man 模块已删除,生产与测试均直连 freight_rpa / 调拨处理函数。""" + with pytest.raises(ModuleNotFoundError): + importlib.import_module('app.services.shipping_notice.inbound_report_storage') + + +def test_register_inbound_sinks_binds_archive_and_transfer_handler(app): + """register_inbound_sinks 把归档入口与调拨 handler 接到 inbound kinds。""" + from app.services.freight_rpa.common import callback_sinks + from app.services.freight_rpa.reports import dispatch as dispatch_module + from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report + from app.services.in_transit_transfer.rpa_sinks import register_inbound_sinks + + dispatch_module._REPORT_HANDLERS.pop('inbound', None) + callback_sinks._SINKS.pop('inbound-batch-ready', None) + register_inbound_sinks() + assert dispatch_module._REPORT_HANDLERS.get('inbound') is handle_inbound_report + assert 'inbound-batch-ready' in callback_sinks._SINKS + + +def test_register_outbound_sinks_binds_outbound_handler(app): + """register_outbound_sinks 把 handle_outbound_report 接到 outbound kind。""" + from app.services.freight_rpa.reports import dispatch as dispatch_module + from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report + from app.services.in_transit_transfer.rpa_sinks import register_outbound_sinks + + dispatch_module._REPORT_HANDLERS.pop('outbound', None) + register_outbound_sinks() + assert dispatch_module._REPORT_HANDLERS.get('outbound') is handle_outbound_report 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 c72c8a5b..5f17963b 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 @@ -229,7 +229,7 @@ def test_stale_orphan_unit_sweeps_projection_to_failed(app): """ from app import db from app.models import FreightRpaSource, FreightRpaInboundUnitRun - from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_orphan_receipt_units + from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_orphan_inbound_units with app.app_context(): app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60 @@ -244,6 +244,6 @@ def test_stale_orphan_unit_sweeps_projection_to_failed(app): assert resolve_source_file_status(source_code=SOURCE_CODE)['file_status'] == 'fetching' # [断言意图] 回收扫描后投影必须翻转为 failed:这是前端重试门禁 # (file_status !== 'fetching')解锁的依据,也是本测试与事故的直接回归点。 - assert recover_all_stale_orphan_receipt_units() == 1 + assert recover_all_stale_orphan_inbound_units() == 1 db.session.expire_all() assert resolve_source_file_status(source_code=SOURCE_CODE)['file_status'] == 'failed' diff --git a/backend/tests/test_admin_freight_rpa_onhand_config.py b/backend/tests/test_admin_freight_rpa_onhand_config.py index 52f63ffb..d1e177cc 100644 --- a/backend/tests/test_admin_freight_rpa_onhand_config.py +++ b/backend/tests/test_admin_freight_rpa_onhand_config.py @@ -3,8 +3,9 @@ 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 等模型。 + freight_rpa_source_admin_service(assert_onhand_source_can_enable / save_onhand_report_config)、 + freight_rpa_report_config_service.save_inbound_report_config、 + FreightRpaOnhandReportConfig / FreightRpaSource 等模型。 逻辑:验证启用中站点缺模板/缺配置行/缺解析绑定时 fail-closed;保存在手配置只写配置行、 不写站点已删除的三列,并递增配置行 config_version;在手与入站两侧解析方案 purpose 互斥。 """ @@ -19,8 +20,9 @@ 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, +from app.services.admin.freight_rpa_report_config_service import save_inbound_report_config +from app.services.admin.freight_rpa_source_admin_service import ( + assert_onhand_source_can_enable, save_onhand_report_config, ) # 站点/连接编码自增,保证同一测试内多次构造不撞唯一约束。 @@ -184,13 +186,13 @@ def test_save_onhand_report_config_rejects_non_onhand_parsing_profile(app, db_se 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' 的解析方案(在手/入站互斥回归)。""" +def test_save_inbound_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, { + save_inbound_report_config(source.id, { # 先给合法 DBS 四段路径,确保失败点落在解析绑定校验(purpose 互斥)而非路径校验。 "report_path_json": { "program_group": "Bison", "program_label": "AWSBI", diff --git a/backend/tests/test_admin_freight_rpa_routes.py b/backend/tests/test_admin_freight_rpa_routes.py index 324e51f4..23226bec 100644 --- a/backend/tests/test_admin_freight_rpa_routes.py +++ b/backend/tests/test_admin_freight_rpa_routes.py @@ -76,11 +76,12 @@ def test_freight_rpa_admin_routes_moved_and_old_paths_404(app, client): assert fields.status_code == 200 assert fields.get_json()['success'] is True - # [断言意图] 临时会话只改词根,仍留在 shipping-notice;Excel 模板与异动字段不动。 + # [断言意图] 临时会话只改词根,仍留在 shipping-notice;Excel 模板不动;异动字段归 freight-rpa。 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 + assert '/api/admin/freight-rpa/movement-fields' in rules + assert '/api/admin/shipping-notice/movement-fields' not 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_movement_fields.py b/backend/tests/test_admin_movement_fields.py index d22d182b..685073c2 100644 --- a/backend/tests/test_admin_movement_fields.py +++ b/backend/tests/test_admin_movement_fields.py @@ -1,7 +1,7 @@ """ 标准异动字段目录接口测试。 -用途:验证 GET /api/admin/shipping-notice/movement-fields 下发只读领域契约。 +用途:验证 GET /api/admin/freight-rpa/movement-fields 下发只读领域契约。 依赖:Flask 管理 API、movement_contract 契约常量。 逻辑:字段目录是 immutable 常量的投影——码/类型/必填/身份标记与契约逐项一致, 不提供任何增删改入口,字段 label 由前端 i18n 渲染。 @@ -27,7 +27,7 @@ def test_movement_fields_returns_fixed_catalog(app, client): db.session.add(User(username='movement-admin', email='movement-admin@example.com', role='admin', status='active')) db.session.commit() - response = client.get('/api/admin/shipping-notice/movement-fields', headers=_headers()) + response = client.get('/api/admin/freight-rpa/movement-fields', headers=_headers()) assert response.status_code == 200 data = parse_api_data(response.get_json()) # [断言意图] 字段码与顺序是前后端共同契约——后端 movement_contract 变更必须显式同步本断言。 @@ -53,7 +53,7 @@ def test_movement_fields_rejects_non_admin(app, client): db.session.add(User(username='movement-user', email='movement-user@example.com', role='user', status='active')) db.session.commit() - response = client.get('/api/admin/shipping-notice/movement-fields', headers={ + response = client.get('/api/admin/freight-rpa/movement-fields', headers={ 'X-Username': 'movement-user', 'X-Role': 'user', 'Content-Type': 'application/json', }) assert response.status_code == 403 diff --git a/backend/tests/test_admin_shipping_receipt_config.py b/backend/tests/test_admin_shipping_receipt_config.py index 9de04668..bcb74e77 100644 --- a/backend/tests/test_admin_shipping_receipt_config.py +++ b/backend/tests/test_admin_shipping_receipt_config.py @@ -118,7 +118,7 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c json=invalid_date, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 400 - assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID' + assert parse_api_error(response.get_json())['code'] == 'SHIPPING.INBOUND_REPORT_CONFIG_INVALID' invalid_selector = _dbs_payload() invalid_selector['query_parameters_json'] = [{'name': 'Owner', 'mode': 'single', 'values': [], 'selector': '#owner'}] @@ -127,7 +127,7 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c json=invalid_selector, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 400 - assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID' + assert parse_api_error(response.get_json())['code'] == 'SHIPPING.INBOUND_REPORT_CONFIG_INVALID' # 关键断言:Warehouse 条件由管理员自行维护——缺失/空值允许保存,不再强制拦截。 missing_warehouse = _dbs_payload() @@ -159,7 +159,7 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c json=invalid_crane, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 400 - assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID' + assert parse_api_error(response.get_json())['code'] == 'SHIPPING.INBOUND_REPORT_CONFIG_INVALID' def _create_parsing_profile(profile_code: str, *, status: str, purpose: str): @@ -298,7 +298,7 @@ def test_crane_receipt_config_rejects_query_parameters(app, client): json=configured, headers=_headers('receipt-admin', 'admin'), ) assert rejected.status_code == 400 - assert parse_api_error(rejected.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID' + assert parse_api_error(rejected.get_json())['code'] == 'SHIPPING.INBOUND_REPORT_CONFIG_INVALID' def test_retire_rejects_profile_bound_by_receipt_report_config(app): @@ -311,7 +311,7 @@ def test_retire_rejects_profile_bound_by_receipt_report_config(app): """ from app import db from app.models import FreightRpaInboundReportConfig - from app.services.shipping_notice import onhand_parsing_profile + from app.services.freight_rpa import parsing_profile as onhand_parsing_profile app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): diff --git a/backend/tests/test_freight_receipt_rpa_access.py b/backend/tests/test_freight_receipt_rpa_access.py index a2da6a16..bc434c3e 100644 --- a/backend/tests/test_freight_receipt_rpa_access.py +++ b/backend/tests/test_freight_receipt_rpa_access.py @@ -1,4 +1,10 @@ -"""收料文件下载和人工补偿的权限/审计契约测试。""" +""" +backend/tests/test_freight_receipt_rpa_access.py + +用途:入站 RPA 管理员补偿 API 契约(失败单元列表/重试);工作台收料文件与 resend 已拆除。 +依赖:Flask test client、freight_rpa 入站模型与 schedule runs 路由。 +逻辑:仅覆盖 /api/admin/inbound-rpa-units 与 retry;审计 surface 为 admin_inbound_rpa_units。 +""" from __future__ import annotations @@ -7,131 +13,6 @@ def _headers(username: str, role: str) -> dict[str, str]: return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'} -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, 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 = 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 = 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 = 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 - # 阶段 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/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 - - -def test_receipt_recipient_lists_only_own_archived_files(app, client): - """接收人文件列表仅返回本人排程归档,并且不得泄露对象存储定位。""" - from app import db - 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 = 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 = 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 = 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/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'/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, 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 = 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 = 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 = 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(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) - - # 关键断言:授权过滤发生在截断之前,避免被其他排程的归档饿死。 - assert [item['id'] for item in items] == [own_file.id] - - -def test_admin_can_resend_without_reexporting(app, client, monkeypatch): - """管理员重发只调用文件投递,不创建 RPA 单元或 trigger。""" - from app import db - 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 = 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 = 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 = 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/inbound-report-files/{file_id}/resend', headers=_headers('receipt-resend-admin', 'admin')) - assert response.status_code == 200 - assert calls == [(file_id, True)] - - def test_admin_retry_creates_a_new_receipt_unit_linked_to_failed_unit(app, client, monkeypatch): """失败单元重试保留旧失败事实,创建新的 callback 单元和独立 trigger。""" from app import db @@ -158,6 +39,7 @@ def test_admin_retry_creates_a_new_receipt_unit_linked_to_failed_unit(app, clien retry = FreightRpaInboundUnitRun.query.filter_by(retry_of_id=failed_id).one() assert retry.status == 'awaiting_rpa' assert retry.callback_id != 'receipt-failed' + assert retry.callback_id.startswith('inbound:') assert captured and captured[0][1][0]['callback_id'] == retry.callback_id @@ -175,7 +57,7 @@ def test_admin_lists_failed_receipt_units_for_manual_compensation(app, client): 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 = 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={}) + 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.INBOUND_EXPORT_FAILED', config_snapshot_json={}) db.session.add(unit); db.session.commit() unit_id = unit.id @@ -184,4 +66,61 @@ def test_admin_lists_failed_receipt_units_for_manual_compensation(app, client): 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_inbound_rpa_units_listed').count() == 1 + listed = ShippingAuditEvent.query.filter_by(event_type='shipping_inbound_rpa_units_listed').one() + assert listed.metadata_json.get('surface') == 'admin_inbound_rpa_units' + + +def test_admin_retry_inbound_unit_messages_use_inbound_not_receipt(app, client): + """入站 retry 面向用户的英文错误须用 Inbound,不得再写 Receipt。""" + from app import db + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun, User + from tests.conftest import parse_api_error + + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + admin = User( + username='inbound-retry-msg-admin', + email='inbound-retry-msg-admin@example.com', + role='admin', + status='active', + ) + db.session.add(admin) + db.session.flush() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + task = ScheduleTask( + schedule_no='SCH-INBOUND-RETRY-MSG', + name='Inbound retry messages', + 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-INBOUND-RETRY-MSG', schedule_task_id=task.id, status='failed') + db.session.add(run) + db.session.flush() + success = FreightRpaInboundUnitRun( + schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, + connector_type='dbs', warehouse_id='A', callback_id='inbound-success-no-retry', + status='success', config_snapshot_json={}, + ) + db.session.add(success) + db.session.commit() + success_id = success.id + + missing = client.post( + '/api/admin/inbound-rpa-units/999999/retry', + json={'reason': 'should 404'}, + headers=_headers('inbound-retry-msg-admin', 'admin'), + ) + assert missing.status_code == 404 + assert parse_api_error(missing.get_json())['message'] == 'Inbound RPA unit not found' + + blocked = client.post( + f'/api/admin/inbound-rpa-units/{success_id}/retry', + json={'reason': 'should conflict'}, + headers=_headers('inbound-retry-msg-admin', 'admin'), + ) + assert blocked.status_code == 409 + assert parse_api_error(blocked.get_json())['message'] == 'Only failed inbound RPA units can be retried' diff --git a/backend/tests/test_freight_receipt_rpa_callback.py b/backend/tests/test_freight_receipt_rpa_callback.py index 491aec93..09438ad9 100644 --- a/backend/tests/test_freight_receipt_rpa_callback.py +++ b/backend/tests/test_freight_receipt_rpa_callback.py @@ -7,30 +7,17 @@ import hashlib import pytest -def _register_legacy_terminal_handler(unit): - """注册测试用 inbound 事实处理函数,复刻拆分前的终态收尾(桥 + 证据同步 + finalize)。 +def _register_inbound_report_handler(): + """注册生产用 inbound 事实处理函数(调拨侧 handle_inbound_report)。 - 核心逻辑: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 → 旧钩子实参逐字段换算, - 行为与拆分前逐点一致。 + 核心逻辑:归档入口终态 commit 后经 dispatch_report_fact 投递;测试在调用 + ingest_inbound_callback 前显式注册,避免依赖 create_app 全局状态顺序。 """ from app.services.freight_rpa.reports.dispatch import register_report_handler - from app.services.shipping_notice.inbound_report_storage import _finish_inbound_callback_terminal + from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report - 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 + register_report_handler('inbound', handle_inbound_report) + return handle_inbound_report def test_receipt_unit_processing_and_batch_progress(app): @@ -38,8 +25,8 @@ def test_receipt_unit_processing_and_batch_progress(app): from app import db 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, + mark_inbound_unit_processing, + report_inbound_batch_progress, ) with app.app_context(): @@ -53,7 +40,7 @@ def test_receipt_unit_processing_and_batch_progress(app): run = ScheduleRun( run_no='RUN-RECEIPT-LIVE', schedule_task_id=task.id, status='running', total_count=2, success_count=0, failed_count=0, skipped_count=0, - response_summary_json={'awaiting_receipt_rpa': True}, + response_summary_json={'awaiting_inbound_rpa': True}, ) db.session.add(run) db.session.flush() @@ -65,7 +52,7 @@ def test_receipt_unit_processing_and_batch_progress(app): db.session.add(unit) db.session.commit() - marked = mark_receipt_unit_processing({ + marked = mark_inbound_unit_processing({ 'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'processing', @@ -74,7 +61,7 @@ def test_receipt_unit_processing_and_batch_progress(app): db.session.expire_all() assert db.session.get(FreightRpaInboundUnitRun, unit.id).status == 'processing' - progressed = report_receipt_batch_progress({ + progressed = report_inbound_batch_progress({ 'schema_version': 'freight_rpa.inbound.v1', 'schedule_run_id': run.id, 'batch_run_no': run.run_no, @@ -93,7 +80,7 @@ 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, FreightRpaSource, FreightRpaInboundUnitRun - from app.services.shipping_notice.inbound_report_storage import ingest_receipt_callback + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback with app.app_context(): source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() @@ -106,7 +93,7 @@ def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch): run = ScheduleRun( run_no='RUN-RECEIPT-PROG', 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': True}, + response_summary_json={'awaiting_inbound_rpa': True}, ) db.session.add(run) db.session.flush() @@ -125,7 +112,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) + _register_inbound_report_handler() payload = { 'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, @@ -134,7 +121,7 @@ def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch): 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest(), } - ingest_receipt_callback(payload) + ingest_inbound_callback(payload) db.session.expire_all() refreshed = db.session.get(ScheduleRun, run.id) # [断言意图] success 后进度至少抬升 success_count;终态可能已 finalize 清 awaiting。 @@ -145,7 +132,7 @@ def test_receipt_callback_archives_once_without_inventory_file(app, monkeypatch) """同一 callback 重放只归档一条收料文件,绝不创建库存快照。""" from app import db from app.models import ScheduleRun, ScheduleTask, FreightRpaOnhandReportFile, FreightRpaSource, FreightRpaInboundUnitRun - from app.services.shipping_notice.inbound_report_storage import ingest_receipt_callback + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback with app.app_context(): source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() @@ -157,10 +144,10 @@ def test_receipt_callback_archives_once_without_inventory_file(app, monkeypatch) 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) + _register_inbound_report_handler() 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) + first = ingest_inbound_callback(payload) + second = ingest_inbound_callback(payload) assert first['file_id'] == second['file_id'] assert FreightRpaOnhandReportFile.query.count() == 0 @@ -169,7 +156,7 @@ def test_ingest_success_advances_transfer_waiting_job(app, monkeypatch): """收料回调 success 落归档后,必须推进调拨 waiting 来源任务(B3 接线)。""" from app import db from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun, TransferSourceJob, TransferRun - from app.services.shipping_notice.inbound_report_storage import ingest_receipt_callback + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback with app.app_context(): source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() @@ -185,10 +172,10 @@ 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) + _register_inbound_report_handler() 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) + result = ingest_inbound_callback(payload) # [断言意图] 桥接发生:收料归档后调拨任务状态推进 file_ready,file_no 为归档文件 id db.session.expire_all() advanced = db.session.get(TransferSourceJob, job.id) @@ -200,7 +187,7 @@ def test_ingest_failed_advance_is_durable(app): """failed 回调推进调拨任务后必须已 commit——rollback 不得丢弃该推进(B3 持久性)。""" from app import db from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun, TransferSourceJob, TransferRun - from app.services.shipping_notice.inbound_report_storage import ingest_receipt_callback + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback with app.app_context(): source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() @@ -214,10 +201,10 @@ def test_ingest_failed_advance_is_durable(app): 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) + _register_inbound_report_handler() 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) + result = ingest_inbound_callback(payload) assert result['status'] == 'failed' # [断言意图] 推进必须已落库而非仅 flush:rollback 丢弃会话内未提交变更, # 只有真正 commit 过的推进才能在 expire_all 后被新查询读到。 @@ -240,19 +227,19 @@ def test_receipt_callback_rejects_file_outside_receipt_drop_root(app, tmp_path): outside = tmp_path / 'outside.xlsx' outside.write_bytes(b'not-a-real-xlsx') - with pytest.raises(ValidationError, match='receipt callback file'): + with pytest.raises(ValidationError, match='inbound callback file'): _read_inbound_callback_file(str(outside)) -def test_ingest_empty_persists_no_receipt_data(app): +def test_ingest_empty_persists_no_inbound_data(app): """ - empty 回调须落库 no_receipt_data(对齐库存 no_inventory_data)。 + empty 回调须落库 no_inbound_data(对齐库存 no_inventory_data)。 - [断言意图] 单元 status=empty 且 error_code/error_message 为 no_receipt_data,供管理端展示跳过原因。 + [断言意图] 单元 status=empty 且 error_code/error_message 为 no_inbound_data,供管理端展示跳过原因。 """ from app import db from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun - from app.services.shipping_notice.inbound_report_storage import ingest_receipt_callback + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback with app.app_context(): source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() @@ -281,22 +268,22 @@ def test_ingest_empty_persists_no_receipt_data(app): ) db.session.add(unit) db.session.commit() - _register_legacy_terminal_handler(unit) + _register_inbound_report_handler() - result = ingest_receipt_callback({ + 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', + 'error_code': 'no_inbound_data', + 'error_message': 'no_inbound_data', }) assert result['status'] == 'empty' db.session.expire_all() saved = db.session.get(FreightRpaInboundUnitRun, unit.id) assert saved is not None assert saved.status == 'empty' - assert saved.error_code == 'no_receipt_data' - assert saved.error_message == 'no_receipt_data' + assert saved.error_code == 'no_inbound_data' + assert saved.error_message == 'no_inbound_data' def test_receipt_progress_routes_are_registered(app): @@ -343,5 +330,5 @@ def test_read_receipt_callback_file_resolves_drop_root_filename(app, tmp_path): ) == b'receipt-bytes' outside = tmp_path / 'outside.xlsx' outside.write_bytes(b'x') - with pytest.raises(ValidationError, match='receipt callback file'): + with pytest.raises(ValidationError, match='inbound callback file'): _read_inbound_callback_file(str(outside)) diff --git a/backend/tests/test_freight_receipt_rpa_notifications.py b/backend/tests/test_freight_receipt_rpa_notifications.py index 966b7b48..8e71712c 100644 --- a/backend/tests/test_freight_receipt_rpa_notifications.py +++ b/backend/tests/test_freight_receipt_rpa_notifications.py @@ -1,70 +1,14 @@ -"""收料文件企微投递和授权下载契约测试。""" +""" +backend/tests/test_freight_receipt_rpa_notifications.py + +用途:入站排程终态企微通知与 finalize 汇总 Excel 契约(统一排程出口)。 +依赖:freight_rpa_inbound_finalize、scheduler_service 企微门禁。 +逻辑:per-file deliver_inbound_file 已拆除;本文件不再覆盖单文件投递/resend。 +""" from __future__ import annotations -def test_receipt_file_delivery_is_idempotent_and_only_targets_schedule_recipients(app, monkeypatch): - """同一文件只向排程接收人发送一次,重放不会重复调用企微。""" - from app import db - from app.models import ( - 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 = 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 = 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 = 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') - calls: list[tuple] = [] - monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.send_wecom_file_message', lambda *args: calls.append(args) or {'errcode': 0}) - - assert deliver_inbound_file(report_file.id)['success_count'] == 1 - assert deliver_inbound_file(report_file.id)['success_count'] == 1 - assert len(calls) == 1 - - -def test_receipt_notification_failure_is_audited(app, monkeypatch): - """企微投递失败也必须保留接收人、时间、失败码和文件身份审计。""" - from app import db - from app.models import ( - 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 = 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 = 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 = 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_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' - - def _make_receipt_run_fixture(db, task_no: str, run_no: str, callback_id: str, *, awaiting: bool = True): """构造一个收料排程任务+run+成功单元+归档文件的最小通知夹具。""" from app.models import ( @@ -75,7 +19,7 @@ def _make_receipt_run_fixture(db, task_no: str, run_no: str, callback_id: str, * 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) + run = ScheduleRun(run_no=run_no, schedule_task_id=task.id, status='running', response_summary_json={'awaiting_inbound_rpa': True} if awaiting else None) db.session.add(run); db.session.flush() 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() @@ -115,7 +59,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_rpa_inbound_finalize import finalize_receipt_schedule_run_if_complete + from app.services.schedule.freight_rpa_inbound_finalize import finalize_inbound_schedule_run_if_complete with app.app_context(): app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives') @@ -130,27 +74,27 @@ def test_receipt_run_notification_is_one_shot_at_finalize(app, monkeypatch, tmp_ app.config['WECOM_PUBLIC_BASE_URL'] = 'https://hxops.example.com' textcards, media_uploads, file_sends = _patch_unified_wecom(monkeypatch, enabled_events=True) - outcome = finalize_receipt_schedule_run_if_complete(run.id) + outcome = finalize_inbound_schedule_run_if_complete(run.id) # [断言意图] 一次性出口:单条 textcard + 结果 Excel + 单个收料 ZIP,与库存排程同通道同门禁。 assert outcome == {'finalized': True, 'status': 'success'} assert len(textcards) == 1 - assert '原始收料包:已随本通知发送' in textcards[0][1] + assert '原始入站包:已随本通知发送' in textcards[0][1] assert len(media_uploads) == 2 - assert media_uploads[0].startswith('收料RPA-') and media_uploads[0].endswith('-结果.xlsx') - assert media_uploads[1].startswith('收料RPA-') and media_uploads[1].endswith('-收料.zip') + assert media_uploads[0].startswith('入站RPA-') and media_uploads[0].endswith('-结果.xlsx') + assert media_uploads[1].startswith('入站RPA-') and media_uploads[1].endswith('-入站.zip') assert file_sends == ['media-1', 'media-2'] assert run.wecom_notified is True - assert run.response_summary_json.get('raw_receipt_zip_available') is True + assert run.response_summary_json.get('raw_inbound_zip_available') is True # [断言意图] awaiting 标志清零后再次归集必须短路,绝不二次打扰接收人。 - outcome_again = finalize_receipt_schedule_run_if_complete(run.id) - assert outcome_again == {'finalized': False, 'reason': 'not_awaiting_receipt_callback'} + outcome_again = finalize_inbound_schedule_run_if_complete(run.id) + assert outcome_again == {'finalized': False, 'reason': 'not_awaiting_inbound_callback'} assert len(textcards) == 1 and len(file_sends) == 2 def test_receipt_finalize_generates_summary_excel(app, tmp_path): - """收料 finalize 生成汇总 Excel:行结构对齐库存、状态归一、展示名 收料RPA-*-结果.xlsx。""" + """收料 finalize 生成汇总 Excel:行结构对齐库存、状态归一、展示名 入站RPA-*-结果.xlsx。""" from io import BytesIO from openpyxl import load_workbook @@ -160,28 +104,28 @@ def test_receipt_finalize_generates_summary_excel(app, tmp_path): ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile, FreightRpaInboundUnitRun, ) - from app.services.schedule.freight_rpa_inbound_finalize import finalize_receipt_schedule_run_if_complete + from app.services.schedule.freight_rpa_inbound_finalize import finalize_inbound_schedule_run_if_complete with app.app_context(): app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives-excel') 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}) + run = ScheduleRun(run_no='RUN-RECEIPT-EXCEL', schedule_task_id=task.id, status='running', response_summary_json={'awaiting_inbound_rpa': True}) db.session.add(run); db.session.flush() 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={}) + 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.INBOUND_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(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) + outcome = finalize_inbound_schedule_run_if_complete(run.id) # [断言意图] finalize 生成汇总 Excel,并携带与库存同名的 summary 契约键。 assert outcome == {'finalized': True, 'status': 'partial_failed'} assert run.excel_file_data - assert run.excel_file_name.startswith('收料RPA-') and run.excel_file_name.endswith('-结果.xlsx') + assert run.excel_file_name.startswith('入站RPA-') and run.excel_file_name.endswith('-结果.xlsx') assert run.response_summary_json['excel_export_status'] == 'ok' assert run.response_summary_json['excel_failed'] is False @@ -189,7 +133,7 @@ def test_receipt_finalize_generates_summary_excel(app, tmp_path): workbook = load_workbook(BytesIO(run.excel_file_data)) sheet = workbook.active header = [cell.value for cell in sheet[1]] - assert header[:2] == ['收料源', '仓库'] + assert header[:2] == ['入站源', '仓库'] rows = {row[0]: row for row in sheet.iter_rows(min_row=2, values_only=True)} assert rows['DSV360_AWSDU'][3] == 1 and rows['DSV360_AWSDU'][4] == 'success' assert rows['DSV360_AWSCV'][4] == 'skipped' diff --git a/backend/tests/test_freight_receipt_rpa_schedule.py b/backend/tests/test_freight_receipt_rpa_schedule.py index 10b2800b..1701408d 100644 --- a/backend/tests/test_freight_receipt_rpa_schedule.py +++ b/backend/tests/test_freight_receipt_rpa_schedule.py @@ -9,7 +9,7 @@ def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app, """一源一单元:有/无 Warehouse 条件均产出 unit;多值 Warehouse 不拆分。""" from app import db from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportConfig, FreightRpaProfile - from app.services.schedule.freight_rpa_inbound_job import run_freight_receipt_rpa_schedule + from app.services.schedule.freight_rpa_inbound_job import run_freight_rpa_inbound_schedule with app.app_context(): dbs = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() @@ -66,7 +66,7 @@ def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app, '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) + total, success, failed, skipped, details, errors, logs = run_freight_rpa_inbound_schedule(task, run) # 关键断言:三源三单元;多值 Warehouse 不拆;空 query_parameters 仍产出。 assert (total, success, failed, skipped, errors) == (3, 0, 0, 0, []) @@ -96,7 +96,7 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa from app import db from app.core.errors import ServiceUnavailableError 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.schedule.freight_rpa_inbound_job import run_freight_rpa_inbound_schedule from app.services.freight_rpa.common.worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE with app.app_context(): @@ -122,11 +122,11 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa trigger_calls = [] monkeypatch.setattr( - 'app.services.schedule.freight_rpa_inbound_job.assert_receipt_rpa_worker_ready', + 'app.services.schedule.freight_rpa_inbound_job.assert_inbound_rpa_worker_ready', lambda: (_ for _ in ()).throw(ServiceUnavailableError( RPA_WORKER_OFFLINE_MESSAGE, code='RPA.WORKER_OFFLINE', - details={'reasons': ['no_worker_heartbeat'], 'detail_message': 'receipt worker offline'}, + details={'reasons': ['no_worker_heartbeat'], 'detail_message': 'inbound worker offline'}, )), ) monkeypatch.setattr( @@ -134,18 +134,18 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa lambda *args, **kwargs: trigger_calls.append(args) or 'should-not-write.json', ) - total, success, failed, skipped, details, errors, logs = run_freight_receipt_rpa_schedule(task, run) + total, success, failed, skipped, details, errors, logs = run_freight_rpa_inbound_schedule(task, run) # [断言意图] fail-fast:计 failed、不入库 unit、不写 trigger、不进入 awaiting。 assert (total, success, failed, skipped) == (1, 0, 1, 0) assert details == [] - assert errors == ['receipt worker offline'] + assert errors == ['inbound worker offline'] assert trigger_calls == [] 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( - isinstance(log, dict) and log.get('status') == 'awaiting_receipt_rpa' + isinstance(log, dict) and log.get('status') == 'awaiting_inbound_rpa_callback' for log in logs ) @@ -174,24 +174,24 @@ def test_stale_receipt_callback_run_is_failed_without_automatic_retry(app): """无回调超时只关闭本次 run/单元并写审计,绝不创建重试单元。""" from app import db from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, FreightRpaSource, FreightRpaInboundUnitRun - from app.services.schedule.freight_rpa_inbound_finalize import recover_stale_receipt_rpa_schedule_runs + from app.services.schedule.freight_rpa_inbound_finalize import recover_stale_inbound_rpa_schedule_runs with app.app_context(): app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60 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}) + 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_inbound_rpa': True}) db.session.add(run); db.session.flush() 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 + assert recover_stale_inbound_rpa_schedule_runs(task) == 1 db.session.refresh(run); db.session.refresh(unit) assert run.status == 'failed' assert unit.status == 'failed' - assert unit.error_code == 'RPA.RECEIPT_CALLBACK_TIMEOUT' + assert unit.error_code == 'RPA.INBOUND_CALLBACK_TIMEOUT' 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 @@ -212,38 +212,38 @@ 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, FreightRpaSource, FreightRpaInboundUnitRun - from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_receipt_rpa_schedule_runs + from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_inbound_rpa_schedule_runs with app.app_context(): app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60 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}) + 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_inbound_rpa': True}) db.session.add(run); db.session.flush() 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 修复口径); # 超时窗(60s)过后扫描即收口为 failed 并写 recovered_reason。 - assert recover_all_stale_receipt_rpa_schedule_runs() == 1 + assert recover_all_stale_inbound_rpa_schedule_runs() == 1 db.session.refresh(run) assert run.status == 'failed' - assert run.response_summary_json.get('recovered_reason') == 'receipt_rpa_callback_timeout' + assert run.response_summary_json.get('recovered_reason') == 'inbound_rpa_callback_timeout' -def test_receipt_recovery_respects_fresh_activity_of_long_batch(app): +def test_inbound_recovery_respects_fresh_activity_of_long_batch(app): """长批次健康在跑不得被误杀:超时锚取最后单元活动而非 run 开始时间。""" from app import db from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun - from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_receipt_rpa_schedule_runs + from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_inbound_rpa_schedule_runs with app.app_context(): app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60 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}) + 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_inbound_rpa': True}) db.session.add(run); db.session.flush() # 单元1:30 秒前终态(笔间活动新鲜);单元2:45 秒前进入 processing(在飞,started_at 为锚) 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))) @@ -252,12 +252,12 @@ def test_receipt_recovery_respects_fresh_activity_of_long_batch(app): # [断言意图] run.started_at(30min 前) 已远超 60s 窗,但最后活动仅 30~45s—— # 笔间静默口径下健康长批次必须不被回收(旧口径按 started_at 会误杀)。 - assert recover_all_stale_receipt_rpa_schedule_runs() == 0 + assert recover_all_stale_inbound_rpa_schedule_runs() == 0 db.session.refresh(run) assert run.status == 'running' -def test_receipt_recovery_is_wired_into_per_tick_maintenance_not_startup_only(): +def test_inbound_recovery_is_wired_into_per_tick_maintenance_not_startup_only(): """哨兵回归:收料超时对账必须挂在每轮领取维护区,不得回流启动一次性分支。""" import inspect @@ -266,16 +266,16 @@ def test_receipt_recovery_is_wired_into_per_tick_maintenance_not_startup_only(): source = inspect.getsource(queue_service) marker_init = source.index("_worker_initialized = True") # [断言意图] 调用点必须位于一次性分支竖旗之后(每轮维护区); - # 回流旧写法(receipt_recovered = ...)会让长驻进程永不回收(RUN20261001131705E5E5 根因)。 - assert source.index("receipt_stale = recover_all_stale_receipt_rpa_schedule_runs()") > marker_init - assert "receipt_recovered = recover_all_stale_receipt_rpa_schedule_runs()" not in source + # 回流旧写法(inbound_recovered = ...)会让长驻进程永不回收(RUN20261001131705E5E5 根因)。 + assert source.index("inbound_stale = recover_all_stale_inbound_rpa_schedule_runs()") > marker_init + assert "inbound_recovered = recover_all_stale_inbound_rpa_schedule_runs()" not in source def test_stale_orphan_inbound_units_are_failed_by_full_scan(app): """按需触发(无排程)的入站单元超时由全量扫描收口为失败,健康在跑单元不受影响。""" from app import db from app.models import ShippingAuditEvent, FreightRpaSource, FreightRpaInboundUnitRun - from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_orphan_receipt_units + from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_orphan_inbound_units with app.app_context(): app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60 @@ -303,16 +303,16 @@ def test_stale_orphan_inbound_units_are_failed_by_full_scan(app): db.session.commit() # [断言意图] 调拨工作台按需触发单元 schedule_run_id=NULL,不在 run 级扫描 - # (recover_all_stale_receipt_rpa_schedule_runs 按 run 遍历)范围内;网页异常 + # (recover_all_stale_inbound_rpa_schedule_runs 按 run 遍历)范围内;网页异常 # 关闭后回调永不到达,必须由本扫描终态化(2026-10-16 事故回归),健康单元原样; # 与 run 级回收同口径:只标失败、写审计,绝不自动创建重试单元。 - assert recover_all_stale_orphan_receipt_units() == 2 + assert recover_all_stale_orphan_inbound_units() == 2 db.session.refresh(stale_queued) db.session.refresh(stale_processing) db.session.refresh(fresh_processing) assert stale_queued.status == 'failed' - assert stale_queued.error_code == 'RPA.RECEIPT_CALLBACK_TIMEOUT' + assert stale_queued.error_code == 'RPA.INBOUND_CALLBACK_TIMEOUT' assert stale_queued.finished_at is not None assert stale_processing.status == 'failed' assert fresh_processing.status == 'processing' @@ -325,7 +325,7 @@ def test_stale_orphan_inbound_units_are_failed_by_full_scan(app): assert (timeout_event.after_snapshot_json or {}).get('status') == 'failed' -def test_orphan_receipt_recovery_is_wired_into_per_tick_maintenance(): +def test_orphan_inbound_recovery_is_wired_into_per_tick_maintenance(): """哨兵回归:孤儿单元回收必须挂在每轮领取维护区(与 run 级扫描同区同轮)。""" import inspect @@ -334,5 +334,5 @@ def test_orphan_receipt_recovery_is_wired_into_per_tick_maintenance(): source = inspect.getsource(queue_service) # [断言意图] 调用点必须与 run 级收料扫描同在每轮维护区且在其后; # 缺席或回流启动一次性分支都会复现「长驻进程期间来源永久 fetching」事故。 - marker_run_scan = source.index("receipt_stale = recover_all_stale_receipt_rpa_schedule_runs()") - assert source.index("recover_all_stale_orphan_receipt_units()") > marker_run_scan + marker_run_scan = source.index("inbound_stale = recover_all_stale_inbound_rpa_schedule_runs()") + assert source.index("recover_all_stale_orphan_inbound_units()") > marker_run_scan diff --git a/backend/tests/test_freight_receipt_worker_contract.py b/backend/tests/test_freight_receipt_worker_contract.py index 8216d24e..60ded775 100644 --- a/backend/tests/test_freight_receipt_worker_contract.py +++ b/backend/tests/test_freight_receipt_worker_contract.py @@ -91,7 +91,7 @@ def test_receipt_worker_save_download_uses_directory_fallback(): def test_receipt_worker_validates_excel_and_reports_empty(): - """收料落盘后必须结构校验;无明细走 NoReceiptDataError → empty/no_receipt_data。""" + """收料落盘后必须结构校验;无明细走 NoReceiptDataError → empty/no_inbound_data。""" text = ( Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py' ).read_text(encoding='utf-8') @@ -105,9 +105,9 @@ def test_receipt_worker_validates_excel_and_reports_empty(): assert 'def _validate_inbound_excel(' in text assert 'from inbound_excel_empty import' in text assert 'class NoInboundDataError' in empty_mod - assert 'no_receipt_data' in empty_mod + assert 'no_inbound_data' in empty_mod assert 'is_inbound_excel_header_row' in empty_mod - assert "'error_code': 'no_receipt_data'" in text + assert "'error_code': 'no_inbound_data'" in text assert "_post_callback({" in text and "'status': 'empty'" in text assert '_EXPORT_UNIT_MAX_ATTEMPTS = 2' in text assert 'retry with clean page' in text diff --git a/backend/tests/test_freight_rpa_admin_ownership_gate.py b/backend/tests/test_freight_rpa_admin_ownership_gate.py new file mode 100644 index 00000000..054f3673 --- /dev/null +++ b/backend/tests/test_freight_rpa_admin_ownership_gate.py @@ -0,0 +1,68 @@ +""" +tests/test_freight_rpa_admin_ownership_gate.py + +用途:锁定货代 RPA 管理归属——入站/出站配置、报表规则、来源站点/登录连接不再寄宿 shipping_onhand 命名空间。 +依赖:pathlib、importlib、pytest。 +""" + +from __future__ import annotations + +import importlib +from pathlib import Path + +BACKEND_ROOT = Path(__file__).resolve().parents[1] + + +def test_parsing_profile_lives_under_freight_rpa(): + """报表规则模块在 freight_rpa,shipping_notice 不再保留 onhand_parsing_profile 文件。""" + assert (BACKEND_ROOT / 'app/services/freight_rpa/parsing_profile.py').is_file() + assert not (BACKEND_ROOT / 'app/services/shipping_notice/onhand_parsing_profile.py').exists() + mod = importlib.import_module('app.services.freight_rpa.parsing_profile') + assert callable(mod.save_draft) + assert callable(mod.list_profiles) + + +def test_inbound_outbound_report_config_not_on_shipping_onhand_admin(): + """入站/出站配置 CRUD 在 freight_rpa_report_config_service,不在 onhand admin。""" + onhand = importlib.import_module('app.services.admin.shipping_onhand_admin_service') + report = importlib.import_module('app.services.admin.freight_rpa_report_config_service') + for name in ( + 'get_inbound_report_config', + 'save_inbound_report_config', + 'get_outbound_report_config', + 'save_outbound_report_config', + ): + assert not hasattr(onhand, name) + assert callable(getattr(report, name)) + + +def test_movement_fields_route_under_freight_rpa_not_shipping_notice(): + """异动字段目录挂在 /freight-rpa/,不在 /shipping-notice/。""" + freight = (BACKEND_ROOT / 'app/api/admin_freight_rpa.py').read_text(encoding='utf-8') + shipping = (BACKEND_ROOT / 'app/api/admin/shipping_notice_admin.py').read_text(encoding='utf-8') + assert "/freight-rpa/movement-fields" in freight + assert "/shipping-notice/movement-fields" not in shipping + +def test_source_profile_admin_not_on_shipping_onhand(): + """登录连接与来源站点 CRUD 在 freight_rpa_source_admin_service。""" + onhand = importlib.import_module('app.services.admin.shipping_onhand_admin_service') + source = importlib.import_module('app.services.admin.freight_rpa_source_admin_service') + for name in ( + 'list_profiles', + 'save_profile', + 'delete_profile', + 'list_sources', + 'save_source', + 'delete_source', + 'activate_source', + 'deactivate_source', + 'bind_source_parsing_profile', + 'assert_onhand_source_can_enable', + 'save_onhand_report_config', + ): + assert not hasattr(onhand, name), name + assert callable(getattr(source, name)), name + for name in ('list_snapshots', 'list_rules', 'list_external_mappings'): + assert callable(getattr(onhand, name)), name + assert not hasattr(source, name), name + diff --git a/backend/tests/test_freight_rpa_heartbeat.py b/backend/tests/test_freight_rpa_heartbeat.py index 32fd7987..5f55f2a2 100644 --- a/backend/tests/test_freight_rpa_heartbeat.py +++ b/backend/tests/test_freight_rpa_heartbeat.py @@ -47,6 +47,18 @@ def test_build_heartbeat_payload_inbound_worker_declares_inbound_export(monkeypa assert payload["worker_id"].endswith("-inbound") +def test_build_heartbeat_payload_outbound_worker_declares_outbound_export(monkeypatch): + """outbound Worker(*-outbound 或 outbound trigger 路径)须声明 outbound_export。""" + module = _load_freight_rpa_heartbeat_module() + monkeypatch.setenv("FREIGHT_RPA_WORKER_ID", "WIN-RPA-01-outbound") + payload = module.build_heartbeat_payload( + trigger_dir=r"C:\HxopsRpaTest\data\freight_rpa\outbound\triggers", + drop_dir=r"C:\HxopsRpaTest\data\freight_rpa\outbound\drop", + ) + assert payload["capabilities"] == ["outbound_export"] + assert payload["worker_id"].endswith("-outbound") + + def test_build_heartbeat_payload_adds_freight_rpa_upload_when_upload_enabled(monkeypatch): """开启上传时心跳能力是 freight_rpa_upload,不再上报 freight_upload。""" module = _load_freight_rpa_heartbeat_module() diff --git a/backend/tests/test_freight_rpa_inbound_slim_gate.py b/backend/tests/test_freight_rpa_inbound_slim_gate.py new file mode 100644 index 00000000..bd8a634d --- /dev/null +++ b/backend/tests/test_freight_rpa_inbound_slim_gate.py @@ -0,0 +1,29 @@ +""" +backend/tests/test_freight_rpa_inbound_slim_gate.py + +用途:Task 2 回归门禁——确认入站 per-file 企微投递模型/符号与工作台收料 API 已从 backend/app 拆除。 +依赖:pathlib、pytest。 +逻辑:仅扫描 Python 源码字符串,不断言 DB 表是否已 DROP(迁移归属 Task 4)。 +""" + +from __future__ import annotations + +from pathlib import Path + +BACKEND_ROOT = Path(__file__).resolve().parents[1] + + +def test_no_inbound_notification_delivery_symbol(): + """backend/app 内不得再出现投递模型符号或 deliver_inbound_file 实现。""" + hits = [] + for path in (BACKEND_ROOT / 'app').rglob('*.py'): + text = path.read_text(encoding='utf-8') + if 'InboundNotificationDelivery' in text or 'deliver_inbound_file' in text: + hits.append(str(path)) + assert hits == [] + + +def test_no_workspace_inbound_report_routes(): + """工作台 shipping_notice 蓝图不得再暴露 inbound-report-files 路由。""" + text = (BACKEND_ROOT / 'app/api/workspace/shipping_notice.py').read_text(encoding='utf-8') + assert 'inbound-report-files' not in text diff --git a/backend/tests/test_freight_rpa_outbound_access.py b/backend/tests/test_freight_rpa_outbound_access.py new file mode 100644 index 00000000..8d2c5b79 --- /dev/null +++ b/backend/tests/test_freight_rpa_outbound_access.py @@ -0,0 +1,183 @@ +""" +backend/tests/test_freight_rpa_outbound_access.py + +用途:出站 RPA 管理员补偿 API 契约(失败单元列表/重试)与 raw-zip 下载。 +依赖:Flask test client、freight_rpa 出站模型与 schedule runs 路由。 +逻辑:覆盖 /api/admin/outbound-rpa-units、retry 与 /schedule-runs//outbound-raw-zip。 +""" + +from __future__ import annotations + +from urllib.parse import quote + +import pytest + + +def _headers(username: str, role: str) -> dict[str, str]: + return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'} + + +@pytest.fixture +def admin_jwt_headers(app): + """创建 admin 用户并签发 Bearer JWT,供 raw-zip 下载走正式鉴权。""" + from app import db + from app.models import User + from app.core.auth.jwt import issue_local_access_token + + with app.app_context(): + user = db.session.query(User).filter_by(username='admin').first() + if not user: + user = User( + username='admin', + email='admin@example.com', + role='admin', + status='active', + ) + user.set_password('admin') + db.session.add(user) + db.session.commit() + token = issue_local_access_token(user) + return { + 'Authorization': f'Bearer {token}', + 'Content-Type': 'application/json', + } + + +def test_admin_retry_creates_a_new_outbound_unit_linked_to_failed_unit(app, client, monkeypatch): + """失败单元重试保留旧失败事实,创建新的 callback 单元和独立 trigger。""" + from app import db + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaOutboundUnitRun, User + + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + admin = User(username='outbound-retry-admin', email='outbound-retry-admin@example.com', role='admin', status='active') + db.session.add(admin); db.session.flush() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + task = ScheduleTask(schedule_no='SCH-OUTBOUND-RETRY', name='Outbound retry', schedule_type='platform_job', platform_api_path='freight-rpa-outbound', owner_user_id=admin.id, cron_expr='0 8 * * *') + db.session.add(task); db.session.flush() + run = ScheduleRun(run_no='RUN-OUTBOUND-RETRY', schedule_task_id=task.id, status='failed') + db.session.add(run); db.session.flush() + failed = FreightRpaOutboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='outbound-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_outbound_export_batch_trigger', lambda run_no, units, payload: captured.append((run_no, units, payload)) or 'retry-trigger.json') + + response = client.post(f'/api/admin/outbound-rpa-units/{failed_id}/retry', json={'reason': 'portal recovered'}, headers=_headers('outbound-retry-admin', 'admin')) + assert response.status_code == 200 + with app.app_context(): + retry = FreightRpaOutboundUnitRun.query.filter_by(retry_of_id=failed_id).one() + assert retry.status == 'awaiting_rpa' + assert retry.callback_id != 'outbound-failed' + assert retry.callback_id.startswith('outbound:') + assert captured and captured[0][1][0]['callback_id'] == retry.callback_id + + +def test_admin_lists_failed_outbound_units_for_manual_compensation(app, client): + """管理员可见失败单元用于人工补偿;该接口会记录管理员查看审计。""" + from app import db + from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, FreightRpaSource, FreightRpaOutboundUnitRun, User + + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + admin = User(username='outbound-units-admin', email='outbound-units-admin@example.com', role='admin', status='active') + db.session.add(admin); db.session.flush() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + task = ScheduleTask(schedule_no='SCH-OUTBOUND-UNITS', name='Outbound units', schedule_type='platform_job', platform_api_path='freight-rpa-outbound', owner_user_id=admin.id, cron_expr='0 8 * * *') + db.session.add(task); db.session.flush() + run = ScheduleRun(run_no='RUN-OUTBOUND-UNITS', schedule_task_id=task.id, status='failed') + db.session.add(run); db.session.flush() + unit = FreightRpaOutboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='outbound-admin-list', status='failed', error_code='RPA.OUTBOUND_EXPORT_FAILED', config_snapshot_json={}) + db.session.add(unit); db.session.commit() + unit_id = unit.id + + response = client.get('/api/admin/outbound-rpa-units?status=failed', headers=_headers('outbound-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_outbound_rpa_units_listed').count() == 1 + + +def test_serialize_run_reads_outbound_raw_zip_available_from_summary(app): + """serialize_run 应暴露 outbound_raw_zip_available 供管理端深链/按钮。""" + from app import db + from app.models import ScheduleRun, ScheduleTask, User + from app.services.schedule.query_service import serialize_run + + with app.app_context(): + user = User(username='arch_outbound_ser', email='arch_outbound_ser@example.com') + db.session.add(user) + db.session.flush() + task = ScheduleTask( + schedule_no='ARCH-OUT-SER', + name='Outbound archive serialize', + schedule_type='platform_job', + platform_api_path='freight-rpa-outbound', + owner_user_id=user.id, + cron_expr='0 8 * * *', + ) + db.session.add(task) + db.session.flush() + run = ScheduleRun( + run_no='RUN-OUT-SER', + schedule_task_id=task.id, + status='success', + response_summary_json={'raw_outbound_zip_available': True}, + ) + db.session.add(run) + db.session.commit() + payload = serialize_run(run) + assert payload['outbound_raw_zip_available'] is True + assert payload['inbound_raw_zip_available'] is False + + +def test_admin_can_download_outbound_raw_zip(app, client, admin_jwt_headers, tmp_path): + """管理端 outbound-raw-zip 应返回 ZIP 与展示名。""" + from app import db + from app.models import ScheduleRun, ScheduleTask, User + from app.services.schedule.freight_rpa_outbound_archive import outbound_raw_zip_download_name + + archive_dir = tmp_path / 'outbound_archives' + archive_dir.mkdir() + zip_path = archive_dir / 'RUNOUTDL1.zip' + zip_path.write_bytes(b'PK\x03\x04outbound-zip') + app.config['FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR'] = str(archive_dir) + + with app.app_context(): + user = User(username='outbound-zip-admin', email='outbound-zip-admin@example.com', role='admin', status='active') + db.session.add(user) + db.session.flush() + task = ScheduleTask( + schedule_no='SCH-OUT-DL', + name='Outbound zip download', + schedule_type='platform_job', + platform_api_path='freight-rpa-outbound', + owner_user_id=user.id, + cron_expr='0 8 * * *', + ) + db.session.add(task) + db.session.flush() + run = ScheduleRun( + run_no='RUNOUTDL1', + schedule_task_id=task.id, + status='success', + response_summary_json={ + 'raw_outbound_zip_available': True, + 'raw_outbound_zip_path': str(zip_path.resolve()), + }, + ) + db.session.add(run) + db.session.commit() + run_id = run.id + expected_name = outbound_raw_zip_download_name(run) + + response = client.get( + f'/api/admin/schedule-runs/{run_id}/outbound-raw-zip', + headers=admin_jwt_headers, + ) + assert response.status_code == 200 + assert response.mimetype == 'application/zip' + disposition = response.headers.get('Content-Disposition') or '' + assert expected_name in disposition or quote(expected_name) in disposition + assert response.data == b'PK\x03\x04outbound-zip' diff --git a/backend/tests/test_freight_rpa_outbound_callback.py b/backend/tests/test_freight_rpa_outbound_callback.py new file mode 100644 index 00000000..d072b296 --- /dev/null +++ b/backend/tests/test_freight_rpa_outbound_callback.py @@ -0,0 +1,228 @@ +""" +tests/test_freight_rpa_outbound_callback.py + +用途:锁定出站 RPA 回调跨机路径契约、schema 校验与 ingest 归档投递。 +依赖:pytest、app 夹具、freight_rpa.outbound.report_archive、 + freight_rpa.reports.dispatch、freight_rpa API 蓝图。 +逻辑:Worker(Windows)与后端(Linux)分属两机;file_path 只认 outbound drop + 根内文件名。本文件先锁 Windows 绝对路径 / 裸文件名 / 穿越拒绝,再锁 + schema 4xx、ingest 归档后 dispatch_report_fact,以及三条回调路由鉴权。 +""" + +from __future__ import annotations + +import hashlib + +import pytest + + +@pytest.fixture(autouse=True) +def _isolate_callback_registries(): + """隔离 sink / report handler 注册表,避免测内临时 register 串扰其它用例。""" + from app.services.freight_rpa.common import callback_sinks + from app.services.freight_rpa.reports import dispatch as dispatch_module + + saved_sinks = dict(callback_sinks._SINKS) + saved_handlers = dict(dispatch_module._REPORT_HANDLERS) + yield + callback_sinks._SINKS.clear() + callback_sinks._SINKS.update(saved_sinks) + dispatch_module._REPORT_HANDLERS.clear() + dispatch_module._REPORT_HANDLERS.update(saved_handlers) + + + +def test_read_outbound_callback_file_accepts_windows_absolute_path(tmp_path, app): + """Worker 上报 C:\\...\\drop\\foo.xlsx 时,Linux 侧只按文件名拼本机 drop 根。""" + drop = tmp_path / "outbound_drop" + drop.mkdir() + target = drop / "foo.xlsx" + target.write_bytes(b"PK\x03\x04fake") + with app.app_context(): + app.config["FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR"] = str(drop) + from app.services.freight_rpa.outbound.report_archive import _read_outbound_callback_file + data = _read_outbound_callback_file(r"C:\HxopsRpaTest\data\freight_rpa\outbound\drop\foo.xlsx") + assert data.startswith(b"PK") + + +def test_read_outbound_callback_file_accepts_bare_filename(tmp_path, app): + """file_path 仅为 foo.xlsx 时同样定位到本机 outbound drop 根内同名文件。""" + drop = tmp_path / "outbound_drop" + drop.mkdir() + target = drop / "foo.xlsx" + target.write_bytes(b"PK\x03\x04fake") + with app.app_context(): + app.config["FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR"] = str(drop) + from app.services.freight_rpa.outbound.report_archive import _read_outbound_callback_file + data = _read_outbound_callback_file("foo.xlsx") + assert data.startswith(b"PK") + + +def test_read_outbound_callback_file_rejects_traversal(tmp_path, app): + """带 ..\\ 的路径必须拒绝,禁止按 Linux 路径打开 Worker 上报串。""" + drop = tmp_path / "outbound_drop" + drop.mkdir() + with app.app_context(): + app.config["FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR"] = str(drop) + from app.services.freight_rpa.outbound.report_archive import _read_outbound_callback_file + from app.core.errors import ValidationError + with pytest.raises(ValidationError): + _read_outbound_callback_file(r"..\..\etc\passwd") + + +def test_ingest_outbound_callback_rejects_invalid_schema(app): + """错误 schema_version 必须在 commit / 投递之前以 4xx ValidationError 失败。""" + from app.core.errors import ValidationError + from app.services.freight_rpa.outbound.report_archive import ingest_outbound_callback + + with app.app_context(): + with pytest.raises(ValidationError) as excinfo: + ingest_outbound_callback({"schema_version": "freight_rpa.inbound.v1", "callback_id": "x"}) + assert excinfo.value.http_status == 400 + assert excinfo.value.code == "SHIPPING.OUTBOUND_CALLBACK_INVALID" + + +TEST_TOOL_KEY = "test-tool-key" +SEED_SOURCE_CODE = "DSV360_AWSDU" + + +def _awaiting_outbound_unit(*, callback_id: str): + """构造 awaiting_rpa 出站单元,source_id 挂种子站点以满足外键。""" + from app.models import FreightRpaOutboundUnitRun, FreightRpaSource + + source = FreightRpaSource.query.filter_by(source_code=SEED_SOURCE_CODE).one() + return FreightRpaOutboundUnitRun( + source_id=source.id, + source_code=source.source_code, + connector_type="dbs", + callback_id=callback_id, + status="awaiting_rpa", + config_snapshot_json={}, + ) + + +def test_ingest_outbound_callback_archives_and_dispatches_fact(tmp_path, app, monkeypatch): + """success 回调按 Windows 绝对路径只认文件名归档,并投递 report_kind=outbound 事实。""" + from app import db + from app.models import FreightRpaOutboundReportFile + from app.services.freight_rpa.outbound.report_archive import ingest_outbound_callback + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.freight_rpa.reports.facts import ReportFact + + drop = tmp_path / "outbound_drop" + drop.mkdir() + payload_bytes = b"PK\x03\x04fake" + (drop / "foo.xlsx").write_bytes(payload_bytes) + + with app.app_context(): + app.config["FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR"] = str(drop) + unit = _awaiting_outbound_unit(callback_id="outbound-cb-archive") + db.session.add(unit) + db.session.commit() + monkeypatch.setattr( + "app.services.freight_rpa.outbound.report_archive.file_asset_storage.upload_bytes", + lambda **_kwargs: None, + ) + seen: list[ReportFact] = [] + register_report_handler("outbound", seen.append) + + result = ingest_outbound_callback({ + "schema_version": "freight_rpa.outbound.v1", + "callback_id": unit.callback_id, + "status": "success", + "file_path": r"C:\HxopsRpaTest\data\freight_rpa\outbound\drop\foo.xlsx", + "original_filename": "foo.xlsx", + "sha256": hashlib.sha256(payload_bytes).hexdigest(), + }) + assert result["status"] == "success" + assert FreightRpaOutboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1 + assert len(seen) == 1 + fact = seen[0] + assert fact.report_kind == "outbound" + assert fact.ok is True + assert fact.file_id == result["file_id"] + assert fact.unit_run_id == unit.id + + +def test_ingest_outbound_empty_dispatches_failure_fact(app): + """empty 终态先 commit 再投递 ok=False 事实,不读 drop 文件。""" + from app import db + from app.models import FreightRpaOutboundUnitRun + from app.services.freight_rpa.outbound.report_archive import ingest_outbound_callback + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.freight_rpa.reports.facts import ReportFact + + with app.app_context(): + unit = _awaiting_outbound_unit(callback_id="outbound-cb-empty") + db.session.add(unit) + db.session.commit() + seen: list[ReportFact] = [] + register_report_handler("outbound", seen.append) + result = ingest_outbound_callback({ + "schema_version": "freight_rpa.outbound.v1", + "callback_id": unit.callback_id, + "status": "empty", + "error_code": "no_outbound_data", + "error_message": "no_outbound_data", + }) + assert result["status"] == "empty" + db.session.expire_all() + saved = db.session.get(FreightRpaOutboundUnitRun, unit.id) + assert saved.status == "empty" + assert saved.error_code == "no_outbound_data" + assert len(seen) == 1 + assert seen[0].report_kind == "outbound" + assert seen[0].ok is False + assert seen[0].error_code == "no_outbound_data" + + +def test_outbound_callback_routes_require_auth(client, app): + """三条出站回调路由与入站同 ToolApiKey:无 Header 必须 401。""" + app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = TEST_TOOL_KEY + for path in ( + "/api/freight-rpa/outbound-batch-ready", + "/api/freight-rpa/outbound-unit-progress", + "/api/freight-rpa/outbound-batch-progress", + ): + assert client.post(path, json={}).status_code == 401, path + + +def test_outbound_callback_routes_are_registered(client, app): + """组合根已注册 outbound sinks:空载荷不得 404 SINK_NOT_REGISTERED。 + + 核心逻辑:batch-ready 空载荷穿透到 ingest 业务校验(400); + progress 空载荷走 schema 非法分支(200 + updated=False)。 + """ + app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = TEST_TOOL_KEY + headers = {"Authorization": f"Bearer {TEST_TOOL_KEY}"} + ready = client.post("/api/freight-rpa/outbound-batch-ready", json={}, headers=headers) + assert ready.status_code == 400, ready.get_json() + assert ready.get_json()["error"]["code"] == "SHIPPING.OUTBOUND_CALLBACK_INVALID" + for path in ( + "/api/freight-rpa/outbound-unit-progress", + "/api/freight-rpa/outbound-batch-progress", + ): + resp = client.post(path, json={}, headers=headers) + assert resp.status_code == 200, (path, resp.status_code, resp.get_json()) + body = resp.get_json() + assert body["success"] is True + assert body["data"] == {"updated": False, "reason": "callback_schema_invalid"} + + +def test_outbound_batch_ready_invalid_schema_is_400_when_sink_registered(client, app): + """sink 在测内临时注册后,错误 schema 穿透到 ingest → 400 SHIPPING.OUTBOUND_CALLBACK_INVALID。""" + from app.services.freight_rpa.common.callback_sinks import register_sink + from app.services.freight_rpa.outbound.report_archive import ingest_outbound_callback + + def _ready_sink(**payload): + return {"success": True, "data": ingest_outbound_callback(payload)} + + register_sink("outbound-batch-ready", _ready_sink) + app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = TEST_TOOL_KEY + resp = client.post( + "/api/freight-rpa/outbound-batch-ready", + json={}, + headers={"Authorization": f"Bearer {TEST_TOOL_KEY}"}, + ) + assert resp.status_code == 400 + assert resp.get_json()["error"]["code"] == "SHIPPING.OUTBOUND_CALLBACK_INVALID" diff --git a/backend/tests/test_freight_rpa_outbound_job.py b/backend/tests/test_freight_rpa_outbound_job.py new file mode 100644 index 00000000..c25435d6 --- /dev/null +++ b/backend/tests/test_freight_rpa_outbound_job.py @@ -0,0 +1,183 @@ +""" +backend/tests/test_freight_rpa_outbound_job.py + +用途:锁定出站 RPA 排程 fail-closed 口径——空 eligible source 不进入 awaiting, + Worker 离线立即 failed 且不写 trigger / 不落 unit;并哨兵 scheduler/internal jobs 接线。 +依赖:freight_rpa_outbound_job、FreightRpaOutbound* 模型、job_registry、scheduler_service、internal jobs。 +逻辑:对照入站 test_freight_receipt_rpa_schedule 的空源/离线用例;被 pytest 直接导入。 +""" + +from __future__ import annotations + + +def test_outbound_schedule_fails_closed_when_no_eligible_sources(app, monkeypatch): + """无已启用出站配置时排程跳过,不写 trigger、不落 unit、不进入 awaiting。""" + from app import db + from app.models import ScheduleRun, ScheduleTask, FreightRpaOutboundUnitRun + from app.services.schedule.freight_rpa_outbound_job import ( + AWAITING_OUTBOUND_RPA_CALLBACK_STATUS, + run_freight_rpa_outbound_schedule, + ) + + with app.app_context(): + task = ScheduleTask( + schedule_no='SCH-OUTBOUND-EMPTY', + name='Outbound empty', + schedule_type='platform_job', + platform_api_path='freight-rpa-outbound', + owner_user_id=1, + cron_expr='0 8 * * *', + job_params={'source_codes': []}, + ) + db.session.add(task) + db.session.flush() + run = ScheduleRun(run_no='RUN-OUTBOUND-EMPTY', schedule_task_id=task.id, status='running') + db.session.add(run) + db.session.commit() + + trigger_calls = [] + monkeypatch.setattr( + 'app.services.schedule.freight_rpa_outbound_job.write_outbound_export_batch_trigger', + lambda *args, **kwargs: trigger_calls.append(args) or 'should-not-write.json', + ) + + total, success, failed, skipped, details, errors, logs = run_freight_rpa_outbound_schedule(task, run) + + # [断言意图] 空 eligible source fail-closed:计 skipped、不入库 unit、不写 trigger。 + assert (total, success, failed, skipped) == (0, 0, 0, 1) + assert details == [] + assert errors == ['no enabled outbound report sources'] + assert trigger_calls == [] + assert FreightRpaOutboundUnitRun.query.filter_by(schedule_run_id=run.id).count() == 0 + assert any(isinstance(log, dict) and log.get('status') == 'skipped' for log in logs) + assert not any( + isinstance(log, dict) and log.get('status') == AWAITING_OUTBOUND_RPA_CALLBACK_STATUS + for log in logs + ) + + +def test_outbound_schedule_fails_fast_when_worker_offline(app, monkeypatch): + """出站 Worker 离线时排程立即 failed,不写 trigger、不落 unit。""" + from app import db + from app.core.errors import ServiceUnavailableError + from app.models import ( + ScheduleRun, + ScheduleTask, + FreightRpaSource, + FreightRpaOutboundReportConfig, + FreightRpaOutboundUnitRun, + ) + from app.services.schedule.freight_rpa_outbound_job import ( + AWAITING_OUTBOUND_RPA_CALLBACK_STATUS, + run_freight_rpa_outbound_schedule, + ) + from app.services.freight_rpa.common.worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE + + with app.app_context(): + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + db.session.add(FreightRpaOutboundReportConfig( + source_id=source.id, + report_path_json={ + 'program_group': 'Bison', + 'program_label': 'AWSBI', + 'report_group': 'Outbound', + 'report_name': 'Outbound Detail', + }, + query_parameters_json=[], + )) + task = ScheduleTask( + schedule_no='SCH-OUTBOUND-OFFLINE', + name='Outbound offline', + schedule_type='platform_job', + platform_api_path='freight-rpa-outbound', + owner_user_id=1, + cron_expr='0 8 * * *', + job_params={'source_codes': [source.source_code]}, + ) + db.session.add(task) + db.session.flush() + run = ScheduleRun(run_no='RUN-OUTBOUND-OFFLINE', schedule_task_id=task.id, status='running') + db.session.add(run) + db.session.commit() + + trigger_calls = [] + monkeypatch.setattr( + 'app.services.schedule.freight_rpa_outbound_job.assert_outbound_rpa_worker_ready', + lambda: (_ for _ in ()).throw(ServiceUnavailableError( + RPA_WORKER_OFFLINE_MESSAGE, + code='RPA.WORKER_OFFLINE', + details={'reasons': ['no_worker_heartbeat'], 'detail_message': 'outbound worker offline'}, + )), + ) + monkeypatch.setattr( + 'app.services.schedule.freight_rpa_outbound_job.write_outbound_export_batch_trigger', + lambda *args, **kwargs: trigger_calls.append(args) or 'should-not-write.json', + ) + + total, success, failed, skipped, details, errors, logs = run_freight_rpa_outbound_schedule(task, run) + + # [断言意图] fail-fast:计 failed、不入库 unit、不写 trigger、不进入 awaiting。 + assert (total, success, failed, skipped) == (1, 0, 1, 0) + assert details == [] + assert errors == ['outbound worker offline'] + assert trigger_calls == [] + assert FreightRpaOutboundUnitRun.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 failed_log['detail'].get('error_code') == 'RPA.WORKER_OFFLINE' + assert not any( + isinstance(log, dict) and log.get('status') == AWAITING_OUTBOUND_RPA_CALLBACK_STATUS + for log in logs + ) + + +def test_outbound_platform_jobs_are_registered(): + """平台 Job 必须注册 freight-rpa-outbound 与 freight-rpa-outbound-retention。""" + from app.services.schedule.job_registry import get_platform_job + + outbound = get_platform_job('freight-rpa-outbound') + retention = get_platform_job('freight-rpa-outbound-retention') + assert outbound is not None + assert retention is not None + assert outbound.key == 'freight-rpa-outbound' + assert retention.key == 'freight-rpa-outbound-retention' + + +def test_outbound_defer_is_wired_next_to_inbound_defer(): + """哨兵:出站 awaiting 延后终态与入队前超时回收必须挂在入站同路径。""" + import inspect + + from app.api.internal import jobs as internal_jobs + from app.services.schedule import queue_service, scheduler_service + + scheduler_src = inspect.getsource(scheduler_service) + jobs_src = inspect.getsource(internal_jobs) + queue_src = inspect.getsource(queue_service) + + # [断言意图] recover / should_defer / apply_deferred 必须出现在入站同名调用之后, + # 否则出站 run 写完 trigger 会被立刻标 success,回调永远对不上等待态。 + inbound_recover = scheduler_src.index('recover_stale_inbound_rpa_schedule_runs(task)') + assert scheduler_src.index('recover_stale_outbound_rpa_schedule_runs(task)') > inbound_recover + inbound_defer = scheduler_src.index('should_defer_inbound_schedule_run(task, step_logs)') + assert scheduler_src.index('should_defer_outbound_schedule_run(task, step_logs)') > inbound_defer + assert 'apply_deferred_outbound_schedule_run_state(' in scheduler_src + + jobs_inbound_recover = jobs_src.index('recover_stale_inbound_rpa_schedule_runs(task)') + assert jobs_src.index('recover_stale_outbound_rpa_schedule_runs(task)') > jobs_inbound_recover + jobs_inbound_defer = jobs_src.index('should_defer_inbound_schedule_run(task, step_logs)') + assert jobs_src.index('should_defer_outbound_schedule_run(task, step_logs)') > jobs_inbound_defer + assert 'apply_deferred_outbound_schedule_run_state(' in jobs_src + assert "'awaiting_outbound_rpa_callback': True" in jobs_src + + # [断言意图] 入队前两处(手动 enqueue / Cron 到期扫描)都必须回收出站超时 run, + # 否则同任务互斥会把后续 Cron/手动挡在过期 awaiting 上。 + assert queue_src.count('recover_stale_inbound_rpa_schedule_runs(task)') == 2 + assert queue_src.count('recover_stale_outbound_rpa_schedule_runs(task)') == 2 + + # [断言意图] 每轮领取维护区必须全量扫描出站超时 run 与孤儿单元,且位于启动竖旗之后。 + marker_init = queue_src.index('_worker_initialized = True') + assert queue_src.index('recover_all_stale_outbound_rpa_schedule_runs()') > marker_init + assert queue_src.index('recover_all_stale_orphan_outbound_units()') > marker_init + assert queue_src.index('recover_all_stale_outbound_rpa_schedule_runs()') > queue_src.index( + 'recover_all_stale_inbound_rpa_schedule_runs()' + ) diff --git a/backend/tests/test_freight_rpa_outbound_models.py b/backend/tests/test_freight_rpa_outbound_models.py new file mode 100644 index 00000000..c1b4c979 --- /dev/null +++ b/backend/tests/test_freight_rpa_outbound_models.py @@ -0,0 +1,18 @@ +""" +backend/tests/test_freight_rpa_outbound_models.py + +用途:锁定出站 RPA 三模型的类导出与表名,防止建表时漂移或漏导出。 +依赖:app.models 聚合导出的 FreightRpaOutbound* 类。 +逻辑:被 pytest 直接导入;不连数据库。生产侧漏建类时本文件 import 即失败。 +""" + +from __future__ import annotations + +from app.models import FreightRpaOutboundReportConfig, FreightRpaOutboundUnitRun, FreightRpaOutboundReportFile + + +def test_outbound_model_tablenames(): + """出站配置 / 单元运行 / 归档文件必须使用规格表名。""" + assert FreightRpaOutboundReportConfig.__tablename__ == "freight_rpa_outbound_report_configs" + assert FreightRpaOutboundUnitRun.__tablename__ == "freight_rpa_outbound_rpa_unit_runs" + assert FreightRpaOutboundReportFile.__tablename__ == "freight_rpa_outbound_report_files" diff --git a/backend/tests/test_freight_rpa_outbound_notifications.py b/backend/tests/test_freight_rpa_outbound_notifications.py new file mode 100644 index 00000000..d3c5be7d --- /dev/null +++ b/backend/tests/test_freight_rpa_outbound_notifications.py @@ -0,0 +1,103 @@ +""" +backend/tests/test_freight_rpa_outbound_notifications.py + +用途:锁定出站排程终态企微通知必须附带 raw outbound ZIP(与入站对称)。 +依赖:scheduler_service._notify_schedule_run_wecom、outbound archive 下载名、企微 notify 门禁。 +逻辑:直接调用通用排程出口;断言 textcard 文案、ZIP 上传/发送与 outbound_raw_zip 审计事件。 +""" + +from __future__ import annotations + + +def _patch_unified_wecom(monkeypatch): + """拦截通用排程出口的企微调用,返回可断言的捕获列表。""" + textcards: list[tuple[str, str]] = [] + media_uploads: list[str] = [] + file_sends: list[str] = [] + notify_mod = 'app.services.integrations.wecom.notify' + + def _fake_send_textcard(_userid, _title, description, _jump_url): + textcards.append((_title, description)) + return {'errcode': 0} + + monkeypatch.setattr(f'{notify_mod}.send_wecom_textcard_message', _fake_send_textcard) + monkeypatch.setattr(f'{notify_mod}._get_enabled_events', lambda: {'schedule_completed'}) + monkeypatch.setattr( + f'{notify_mod}.upload_wecom_temp_media', + lambda _data, filename: media_uploads.append(filename) or f'media-{len(media_uploads)}', + ) + monkeypatch.setattr( + f'{notify_mod}.send_wecom_file_message', + lambda _userid, media_id: file_sends.append(media_id) or {'errcode': 0}, + ) + return textcards, media_uploads, file_sends + + +def test_notify_schedule_run_wecom_attaches_outbound_raw_zip(app, monkeypatch, tmp_path): + """出站 run 企微完成通知须上传并发送 raw outbound ZIP,审计事件为 schedule_completed_outbound_raw_zip。""" + from app import db + from app.models import ScheduleRun, ScheduleTask, User, WecomNotifyAudit + from app.services.schedule.freight_rpa_outbound_archive import outbound_raw_zip_download_name + from app.services.schedule.scheduler_service import _notify_schedule_run_wecom + + archive_dir = tmp_path / 'outbound-archives' + archive_dir.mkdir() + zip_path = archive_dir / 'RUNOUTWECOM1.zip' + zip_path.write_bytes(b'PK\x03\x04outbound-notify') + + with app.app_context(): + app.config['FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR'] = str(archive_dir) + app.config['WECOM_NOTIFY_ENABLED'] = True + app.config['WECOM_PUBLIC_BASE_URL'] = 'https://hxops.example.com' + recipient = User( + username='outbound-zip-notify', + email='outbound-zip-notify@example.com', + role='user', + status='active', + wecom_userid='outbound-zip-user', + ) + db.session.add(recipient) + db.session.flush() + task = ScheduleTask( + schedule_no='SCH-OUT-WECOM-ZIP', + name='Outbound wecom zip', + schedule_type='platform_job', + platform_api_path='freight-rpa-outbound', + owner_user_id=recipient.id, + cron_expr='0 8 * * *', + notify_enabled=True, + notify_user_ids_json=[recipient.id], + ) + db.session.add(task) + db.session.flush() + run = ScheduleRun( + run_no='RUNOUTWECOM1', + schedule_task_id=task.id, + status='success', + excel_file_data=b'excel-bytes', + excel_file_name='出站RPA-20261019-1546-结果.xlsx', + response_summary_json={ + 'raw_outbound_zip_available': True, + 'raw_outbound_zip_path': str(zip_path.resolve()), + }, + ) + db.session.add(run) + db.session.commit() + expected_zip_name = outbound_raw_zip_download_name(run) + + textcards, media_uploads, file_sends = _patch_unified_wecom(monkeypatch) + _notify_schedule_run_wecom(task, run) + + # [断言意图] 与入站对称:textcard 提示包已随通知发送,并上传 Excel + 出站 ZIP。 + assert len(textcards) == 1 + assert '原始出站包:已随本通知发送' in textcards[0][1] + assert media_uploads[0] == run.excel_file_name + assert media_uploads[1] == expected_zip_name + assert file_sends == ['media-1', 'media-2'] + assert run.wecom_notified is True + zip_audits = WecomNotifyAudit.query.filter_by( + event_type='schedule_completed_outbound_raw_zip', + ).all() + assert len(zip_audits) == 1 + assert zip_audits[0].content == f'[原始出站包] {expected_zip_name}' + assert zip_audits[0].status == 'sent' diff --git a/backend/tests/test_freight_rpa_outbound_rename_gate.py b/backend/tests/test_freight_rpa_outbound_rename_gate.py new file mode 100644 index 00000000..6df2c5a6 --- /dev/null +++ b/backend/tests/test_freight_rpa_outbound_rename_gate.py @@ -0,0 +1,45 @@ +""" +backend/tests/test_freight_rpa_outbound_rename_gate.py + +用途:Task 14 单发布总闸门——grep 断言改名、出站异动解析分支、无 outbound 投递表引用。 +依赖:pathlib、pytest。 +逻辑:只读扫描 backend/app 与关键路由文件;不替代 inbound slim gate 或批次 S grep gate。 +""" + +from __future__ import annotations + +from pathlib import Path + +BACKEND_ROOT = Path(__file__).resolve().parents[1] + +_OUTBOUND_DELIVERY_TOKENS = ( + 'freight_rpa_outbound_notification_deliveries', + 'FreightRpaOutboundNotificationDelivery', + 'outbound_notification_deliveries', +) + + +def test_no_receipt_raw_zip_route(): + """排程 run 下载路由已改为 inbound-raw-zip,不得保留 receipt-raw-zip。""" + text = (BACKEND_ROOT / 'app/api/schedule/runs.py').read_text(encoding='utf-8') + assert 'receipt-raw-zip' not in text + assert 'inbound-raw-zip' in text + + +def test_outbound_purpose_not_catalog_in_validate_docstring(): + """outbound 与 inbound 共用异动字段分支,而非库存字段目录。""" + text = ( + BACKEND_ROOT / 'app/services/freight_rpa/parsing_profile.py' + ).read_text(encoding='utf-8') + assert "purpose in {'inbound', 'outbound'}" in text or 'purpose in {"inbound", "outbound"}' in text + + +def test_no_outbound_notification_deliveries_table_reference(): + """backend/app 不得引用出站逐文件企微投递表或模型符号。""" + hits: list[str] = [] + for path in (BACKEND_ROOT / 'app').rglob('*.py'): + text = path.read_text(encoding='utf-8') + for token in _OUTBOUND_DELIVERY_TOKENS: + if token in text: + hits.append(f'{path.relative_to(BACKEND_ROOT)}:{token}') + assert hits == [] diff --git a/backend/tests/test_freight_rpa_outbound_report_config_api.py b/backend/tests/test_freight_rpa_outbound_report_config_api.py new file mode 100644 index 00000000..405f18e0 --- /dev/null +++ b/backend/tests/test_freight_rpa_outbound_report_config_api.py @@ -0,0 +1,313 @@ +""" +tests/test_freight_rpa_outbound_report_config_api.py + +用途:锁定来源站点出站报表配置 Admin API 的绑定校验、路径规则与启用门禁边界。 +依赖:Flask 管理 API、库存站点测试种子、FreightRpaOutboundReportConfig、货代统一审计事件。 +逻辑:请求打到 /api/admin/freight-rpa/sources//outbound-report-config; + 解析绑定必须 published 且 purpose=outbound;保存只写出站配置,不改在手/入站,也不进入启用硬门槛; + parsing_profile.retire 须拦截仍绑定出站配置的 published 规则。 +""" + +from __future__ import annotations + +import pytest + +from app import db +from app.models import ( + FreightRpaInboundReportConfig, + FreightRpaOutboundReportConfig, + FreightRpaParsingProfile, + FreightRpaSource, + ShippingAuditEvent, + User, +) +from tests.conftest import parse_api_data, parse_api_error + + +def _headers(username: str, role: str) -> dict[str, str]: + """构造当前管理 API 使用的 Header 身份上下文。""" + return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'} + + +@pytest.fixture(autouse=True) +def _admin_user(app): + """关闭 JWT 并播种 admin/user,使 conftest.admin_headers 的 X-Username=admin 可解析。""" + from app import db + + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + if User.query.filter_by(username='admin').first() is None: + db.session.add(User(username='admin', email='admin@example.com', role='admin', status='active')) + if User.query.filter_by(username='outbound-user').first() is None: + db.session.add(User( + username='outbound-user', email='outbound-user@example.com', role='user', status='active', + )) + db.session.commit() + + +@pytest.fixture +def source_id(app) -> int: + """conftest 播种的 DBS 站点主键。""" + with app.app_context(): + return FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one().id + + +@pytest.fixture +def onhand_profile_id(app) -> int: + """conftest 播种的已发布 onhand 解析规则主键,用于证明出站拒绝跨 purpose 绑定。""" + with app.app_context(): + profile = FreightRpaParsingProfile.query.filter_by(profile_code='TEST_RUNTIME', status='published').one() + assert profile.purpose == 'onhand' + return profile.id + + +def _dbs_payload() -> dict: + """构造 DBS 出站配置;Warehouse 为可选筛选,日期不出现。""" + return { + 'report_path_json': { + 'program_group': 'Bison', 'program_label': 'AWSBI', + 'report_group': 'Outbound', 'report_name': 'Outbound Detail', + }, + 'query_parameters_json': [ + {'name': 'Warehouse', 'mode': 'multi_text', 'values': ['AWSDU'], 'required': False, 'select_all': False}, + ], + } + + +def _create_parsing_profile(profile_code: str, *, status: str, purpose: str) -> FreightRpaParsingProfile: + """创建出站/入站/在手解析 Profile 种子;定义仅用于绑定校验。""" + 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, + 'field_mapping': { + 'doc_no': '单据编号', 'material_code': '料号', + 'quantity': '数量', 'movement_date': '异动日期', + }, + 'match_keys': [], + }, + ) + db.session.add(profile) + db.session.commit() + return profile + + +def test_put_outbound_report_config_requires_outbound_profile(client, admin_headers, source_id, onhand_profile_id): + """绑定 onhand 解析规则时必须 400/422(出站只允许 purpose=outbound)。""" + resp = client.put( + f"/api/admin/freight-rpa/sources/{source_id}/outbound-report-config", + json={"parsing_profile_id": onhand_profile_id, "report_path_json": {}, "query_parameters_json": []}, + headers=admin_headers, + ) + assert resp.status_code in (400, 422) + + +def test_put_outbound_report_config_rejects_non_outbound_profile_with_valid_path( + client, admin_headers, source_id, onhand_profile_id, app, +): + """合法 DBS 路径下仍拒绝 onhand / inbound / draft / 不存在的解析绑定。""" + with app.app_context(): + inbound = _create_parsing_profile('OUT_CFG_INBOUND', status='published', purpose='inbound') + draft = _create_parsing_profile('OUT_CFG_DRAFT', status='draft', purpose='outbound') + cases = [onhand_profile_id, inbound.id, draft.id, 999999] + + for profile_id in cases: + response = client.put( + f'/api/admin/freight-rpa/sources/{source_id}/outbound-report-config', + json={**_dbs_payload(), 'parsing_profile_id': profile_id}, + headers=admin_headers, + ) + assert response.status_code == 400, f'profile_id={profile_id}' + assert parse_api_error(response.get_json())['code'] == 'SHIPPING.OUTBOUND_PROFILE_INVALID' + + +def test_put_outbound_report_config_saves_published_outbound_and_audit( + client, admin_headers, source_id, app, +): + """已发布 outbound 规则可保存;payload 回显绑定摘要,审计 event 为 shipping_outbound_report_config_saved。""" + with app.app_context(): + profile = _create_parsing_profile('OUT_MOVE_STD', status='published', purpose='outbound') + profile_id = profile.id + source = db.session.get(FreightRpaSource, source_id) + onhand_before = { + 'path': dict(source.onhand_report_config.report_path_json), + 'parameters': list(source.onhand_report_config.query_parameters_json), + 'config_version': source.config_version, + } + inbound_exists = FreightRpaInboundReportConfig.query.filter_by(source_id=source_id).count() + + forbidden = client.put( + f'/api/admin/freight-rpa/sources/{source_id}/outbound-report-config', + json={**_dbs_payload(), 'parsing_profile_id': profile_id}, + headers=_headers('outbound-user', 'user'), + ) + assert forbidden.status_code == 403 + + missing = client.get( + f'/api/admin/freight-rpa/sources/{source_id}/outbound-report-config', + headers=admin_headers, + ) + assert missing.status_code == 200 + assert parse_api_data(missing.get_json()) is None + + response = client.put( + f'/api/admin/freight-rpa/sources/{source_id}/outbound-report-config', + json={**_dbs_payload(), 'parsing_profile_id': profile_id}, + headers=admin_headers, + ) + assert response.status_code == 200 + config = parse_api_data(response.get_json()) + assert config['parsing_profile_id'] == profile_id + assert config['parsing_profile']['profile_code'] == 'OUT_MOVE_STD' + assert config['parsing_profile']['status'] == 'published' + assert config['report_path_json']['report_group'] == 'Outbound' + assert config['query_parameters_json'][0]['values'] == ['AWSDU'] + + fetched = client.get( + f'/api/admin/freight-rpa/sources/{source_id}/outbound-report-config', + headers=admin_headers, + ) + assert fetched.status_code == 200 + assert parse_api_data(fetched.get_json())['parsing_profile_id'] == profile_id + + with app.app_context(): + source = db.session.get(FreightRpaSource, source_id) + onhand_config = source.onhand_report_config + assert onhand_config.report_path_json == onhand_before['path'] + assert onhand_config.query_parameters_json == onhand_before['parameters'] + assert source.config_version == onhand_before['config_version'] + assert FreightRpaInboundReportConfig.query.filter_by(source_id=source_id).count() == inbound_exists + assert FreightRpaOutboundReportConfig.query.filter_by(source_id=source_id).count() == 1 + audit = ShippingAuditEvent.query.filter_by( + event_type='shipping_outbound_report_config_saved', aggregate_id=str(source_id), + ).one() + assert audit.before_snapshot_json is None + assert audit.metadata_json['parsing_profile_id'] == profile_id + + +def test_outbound_report_config_empty_profile_id_unbinds(client, admin_headers, source_id, app): + """parsing_profile_id 传 None → 解绑,不做校验也不报错。""" + with app.app_context(): + profile = _create_parsing_profile('OUT_UNBIND', status='published', purpose='outbound') + profile_id = profile.id + + bound = client.put( + f'/api/admin/freight-rpa/sources/{source_id}/outbound-report-config', + json={**_dbs_payload(), 'parsing_profile_id': profile_id}, + headers=admin_headers, + ) + assert bound.status_code == 200 + + unbound = client.put( + f'/api/admin/freight-rpa/sources/{source_id}/outbound-report-config', + json={**_dbs_payload(), 'parsing_profile_id': None}, + headers=admin_headers, + ) + assert unbound.status_code == 200 + assert parse_api_data(unbound.get_json())['parsing_profile_id'] is None + + +def test_outbound_report_config_rejects_date_filter(client, admin_headers, source_id): + """出站与入站相同:拒绝日期筛选。""" + 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/freight-rpa/sources/{source_id}/outbound-report-config', + json=invalid_date, headers=admin_headers, + ) + assert response.status_code == 400 + assert parse_api_error(response.get_json())['code'] == 'SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID' + + +def test_crane_outbound_report_is_fixed_to_outbound_details(client, admin_headers, app): + """Crane 固定 Outbound Details,拒绝查询条件与其它报表名。""" + from app import db + + with app.app_context(): + dbs = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + crane_profile = dbs.rpa_profile.__class__( + profile_code='CRANE_OUTBOUND_CFG', display_name='Crane Outbound', connector_type='crane', + login_url='https://crane.example.invalid', login_config_json={'auth_mode': 'password'}, + ) + crane_source = FreightRpaSource( + source_code='CRANE_OUTBOUND_CFG', display_name='Crane Outbound', connector_type='crane', + rpa_profile=crane_profile, warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE', + enabled=False, + ) + db.session.add(crane_source) + db.session.commit() + crane_id = crane_source.id + + ok_payload = { + 'report_path_json': {'report_name': 'Outbound Details'}, + 'query_parameters_json': [], + } + response = client.put( + f'/api/admin/freight-rpa/sources/{crane_id}/outbound-report-config', + json=ok_payload, headers=admin_headers, + ) + assert response.status_code == 200 + assert parse_api_data(response.get_json())['query_parameters_json'] == [] + assert parse_api_data(response.get_json())['report_path_json']['report_name'] == 'Outbound Details' + + inbound_name = client.put( + f'/api/admin/freight-rpa/sources/{crane_id}/outbound-report-config', + json={'report_path_json': {'report_name': 'Inbound Details'}, 'query_parameters_json': []}, + headers=admin_headers, + ) + assert inbound_name.status_code == 400 + assert parse_api_error(inbound_name.get_json())['code'] == 'SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID' + + with_query = client.put( + f'/api/admin/freight-rpa/sources/{crane_id}/outbound-report-config', + json={ + 'report_path_json': {'report_name': 'Outbound Details'}, + 'query_parameters_json': [ + {'name': 'material', 'mode': 'single', 'values': ['PN-01'], 'required': False, 'select_all': False}, + ], + }, + headers=admin_headers, + ) + assert with_query.status_code == 400 + assert parse_api_error(with_query.get_json())['code'] == 'SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID' + + +def test_activation_does_not_require_outbound_report_config(app, source_id): + """出站配置不是来源站点启用硬门槛:缺出站行不得新增 blocking check。""" + from app.services.admin.freight_rpa_source_admin_service import get_source_activation_status + + with app.app_context(): + source = db.session.get(FreightRpaSource, source_id) + assert source.outbound_report_config is None + status = get_source_activation_status(source) + check_codes = [item['code'] for item in status['checks']] + assert all('outbound' not in code for code in check_codes) + assert all('outbound' not in str(item) for item in status['missing_requirements']) + + +def test_retire_rejects_profile_bound_by_outbound_report_config(app, source_id): + """绑定出站报表配置的 published 解析 Profile 退役必须被拒(与入站守卫对称)。 + + 背景:retire 此前只核查库存源与入站配置,遗漏 FreightRpaOutboundReportConfig。 + 守卫补查后三者任一绑定都返回 SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED。 + """ + from app.services.freight_rpa import parsing_profile as onhand_parsing_profile + + with app.app_context(): + profile = _create_parsing_profile('OUT_RETIRE_GUARD', status='published', purpose='outbound') + db.session.add(FreightRpaOutboundReportConfig( + source_id=source_id, parsing_profile_id=profile.id, + report_path_json={}, query_parameters_json=[], + )) + db.session.commit() + profile_id = profile.id + + # 关键断言:仅绑定出站配置(无库存源/入站绑定)也必须拒绝退役。 + with pytest.raises(Exception) as exc_info: + onhand_parsing_profile.retire(profile_id) + assert getattr(exc_info.value, 'code', '') == 'SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED' + assert db.session.get(FreightRpaParsingProfile, profile_id).status == 'published' + assert FreightRpaOutboundReportConfig.query.filter_by(parsing_profile_id=profile_id).count() == 1 diff --git a/backend/tests/test_freight_rpa_outbound_worker_contract.py b/backend/tests/test_freight_rpa_outbound_worker_contract.py new file mode 100644 index 00000000..078b35e8 --- /dev/null +++ b/backend/tests/test_freight_rpa_outbound_worker_contract.py @@ -0,0 +1,148 @@ +""" +tests/test_freight_rpa_outbound_worker_contract.py + +用途:Windows 出站 Worker 脚本静态契约——schema/action、回调 basename、 + Crane 固定页、心跳能力、ps1 Worker ID。 +依赖:scripts/freight_rpa/outbound/*、common/rpa_heartbeat.py、common/rpa_callbacks.py。 +逻辑:Worker 无 pytest 运行时;本文件读常量与源码断言,对齐 inbound + test_freight_receipt_worker_contract.py。Task 12 闸门。 +""" + +from __future__ import annotations + +import importlib.util +import sys +from pathlib import Path + +_REPO_ROOT = Path(__file__).resolve().parents[2] +_OUTBOUND_DIR = _REPO_ROOT / "scripts" / "freight_rpa" / "outbound" +_COMMON_DIR = _REPO_ROOT / "scripts" / "freight_rpa" / "common" + + +def test_outbound_worker_uses_outbound_contract_and_dirs(): + """出站 Worker 只消费 freight_rpa.outbound.v1 / outbound_export_batch 与专用目录。""" + text = (_OUTBOUND_DIR / "outbound_rpa_worker.py").read_text(encoding="utf-8") + assert "FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR" in text + assert "FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR" in text + assert "freight_rpa.outbound.v1" in text + assert "outbound_export_batch" in text + assert "from rpa_callbacks import" in text + assert "OUTBOUND_BATCH_READY" in text + assert "OUTBOUND_BATCH_PROGRESS" in text + assert "OUTBOUND_UNIT_PROGRESS" in text + assert "FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR" not in text + assert "FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR" not in text + assert "INBOUND_BATCH_READY" not in text + + +def test_outbound_callback_file_path_is_basename_only(): + """ + 回调 file_path 必须是 Path.name,禁止 Windows 绝对路径当契约主值。 + + [断言意图] spec §4.2 跨机路径:Worker 只报 drop 根内文件名; + 若把 C:\\...\\drop\\xxx.xlsx 整串上报,Linux 后端按原样 open 会 400。 + """ + text = (_OUTBOUND_DIR / "outbound_rpa_worker.py").read_text(encoding="utf-8") + assert "'file_path': output.name" in text or '"file_path": output.name' in text + assert "§4.2" in text + assert "'file_path': str(output)" not in text + assert '"file_path": str(output)' not in text + assert "str(output.resolve())" not in text + + +def test_outbound_dbs_export_maps_report_path_to_navigation(): + """DBS 出站必须把配置 report_path_json 写入 navigation,不得写死库存/入站报表名。""" + text = (_OUTBOUND_DIR / "outbound_dbs_export.py").read_text(encoding="utf-8") + assert "'navigation': report_path" in text + assert "report_path = dict(unit.get('report_path_json') or {})" in text + assert "__export_kind__" in text + assert "'outbound'" in text + + +def test_outbound_crane_driver_forces_outbound_details_not_inbound(): + """Crane 出站固定 Outbound Details,禁止误用 Inbound Details / On Hand Details。""" + text = (_OUTBOUND_DIR / "outbound_crane_export.py").read_text(encoding="utf-8") + assert "'scheduled_report_name': 'Outbound Details'" in text + assert "outbound-details-query" in text + # 注释可提及禁令;契约主值不得把入站/库存页当出站报表名。 + assert "'scheduled_report_name': 'Inbound Details'" not in text + assert "inbound-details-query" not in text + assert "on-hand-details-query" not in text + + +def test_outbound_crane_entry_url_rewrites_hash_to_outbound_details(): + """复用 Profile 登录地址时必须改写到出站页,不得停在门户首页或入站页。""" + sys.path.insert(0, str(_REPO_ROOT / "scripts" / "freight_rpa")) + spec = importlib.util.spec_from_file_location( + "freight_outbound_crane_export_test", + _OUTBOUND_DIR / "outbound_crane_export.py", + ) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + + assert module._outbound_details_entry_url("https://wms-portal.craneww.com/#/") == ( + "https://wms-portal.craneww.com/#/outbound-details-query" + ) + assert module._outbound_details_entry_url("https://wms-portal.craneww.com/") == ( + "https://wms-portal.craneww.com/#/outbound-details-query" + ) + assert module._outbound_details_entry_url( + "https://wms-portal.craneww.com/#/inbound-details-query" + ) == "https://wms-portal.craneww.com/#/outbound-details-query" + + +def test_outbound_ps1_injects_worker_id_and_outbound_logs(): + """ps1 必须注入 FREIGHT_RPA_WORKER_ID=-outbound 与 outbound logs 目录。""" + ps1 = (_OUTBOUND_DIR / "start_outbound_worker.ps1").read_text(encoding="utf-8") + assert "FREIGHT_RPA_WORKER_ID" in ps1 + assert "-outbound" in ps1 + assert r"outbound\logs\worker.log" in ps1 + assert "FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR" in ps1 + assert "FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR" in ps1 + assert "start_inbound_worker.ps1" not in ps1 + + +def test_outbound_register_script_has_distinct_task_names(): + """出站计划任务名独立,可与 onhand/inbound 同机并存。""" + receipt = (_OUTBOUND_DIR / "register_outbound_worker_tasks.ps1").read_text(encoding="utf-8") + assert '$TestTask = "HXOPS Freight Outbound RPA Worker TEST"' in receipt + assert '$ProdTask = "HXOPS Freight Outbound RPA Worker PROD"' in receipt + assert "start_outbound_worker.ps1" in receipt + assert "start_inbound_worker.ps1" not in receipt + assert "start_onhand_worker.ps1" not in receipt + assert "AtLogOn" in receipt and "Interactive" in receipt and "Headless" in receipt + + +def test_outbound_heartbeat_capability_is_outbound_export(): + """脚本心跳须按 *-outbound / outbound trigger 目录声明 outbound_export。""" + text = (_COMMON_DIR / "rpa_heartbeat.py").read_text(encoding="utf-8") + assert "outbound_export" in text + assert "is_outbound" in text or "-outbound" in text + + +def test_outbound_worker_uses_common_trigger_consumer(): + """出站 Worker 必须复用公共 claim/归档原语。""" + text = (_OUTBOUND_DIR / "outbound_rpa_worker.py").read_text(encoding="utf-8") + assert "claim_trigger" in text + assert "archive_trigger" in text + + +def test_rpa_callbacks_export_outbound_paths(): + """rpa_callbacks 出站端点须与后端 /api/freight-rpa/outbound-* 对齐。""" + sys.path.insert(0, str(_COMMON_DIR)) + import rpa_callbacks # noqa: E402 + + assert rpa_callbacks.OUTBOUND_BATCH_READY == "/api/freight-rpa/outbound-batch-ready" + assert rpa_callbacks.OUTBOUND_UNIT_PROGRESS == "/api/freight-rpa/outbound-unit-progress" + assert rpa_callbacks.OUTBOUND_BATCH_PROGRESS == "/api/freight-rpa/outbound-batch-progress" + + +def test_outbound_worker_ready_callback_outside_export_retry(): + """导出重试不得包裹 ready;成功后先 progress 再 basename ready。""" + text = (_OUTBOUND_DIR / "outbound_rpa_worker.py").read_text(encoding="utf-8") + assert "def _post_unit_ready(" in text + assert "ready 回调禁止进入本循环" in text or "重试只覆盖导出/落盘/校验" in text + progress_at = text.find("progress_counts['success'] += 1") + ready_at = text.find("_post_unit_ready(unit, output)") + assert progress_at > 0 and ready_at > progress_at diff --git a/backend/tests/test_onhand_configuration_test.py b/backend/tests/test_onhand_configuration_test.py index ed47427d..d6ee4951 100644 --- a/backend/tests/test_onhand_configuration_test.py +++ b/backend/tests/test_onhand_configuration_test.py @@ -23,10 +23,10 @@ from app.models import ( FreightRpaProfile, FreightRpaSource, ) -from app.services.admin import shipping_onhand_admin_service +from app.services.admin import freight_rpa_source_admin_service, shipping_onhand_admin_service +from app.services.freight_rpa import parsing_profile as onhand_parsing_profile from app.services.shipping_notice import ( onhand_configuration_test, - onhand_parsing_profile, onhand_structure_analysis, ) from app.services.shipping_notice.order_schema import service as order_schema_service @@ -48,13 +48,13 @@ def _workbook(path: Path) -> None: def _source(code: str = 'TEST_EXPORT_SOURCE', profile_code: str = 'TEST_EXPORT_LOGIN') -> dict: """创建一个保持停用的 DBS 库存站点。""" - login = shipping_onhand_admin_service.save_profile({ + login = freight_rpa_source_admin_service.save_profile({ 'profile_code': profile_code, 'display_name': 'Test Login', 'connector_type': 'dbs', 'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'}, 'username': 'user', 'password': 'password', 'enabled': True, }, actor_id=None) # s18 起报表路径/查询条件/解析方案绑定经内嵌 onhand_report_config 写配置行,站点载荷不再平铺。 - return shipping_onhand_admin_service.save_source({ + return freight_rpa_source_admin_service.save_source({ 'source_code': code, 'display_name': 'Test Export Source', 'connector_type': 'dbs', 'rpa_profile_id': login['id'], 'excel_template_id': None, 'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': 'DUB', 'snapshot_ttl_seconds': 3600, @@ -187,7 +187,7 @@ def test_empty_configuration_export_is_successful_but_marks_data_validation_pend 'run_no': seed_run['run_no'], 'status': 'success', 'file_path': str(analysis_path), }) profile = _publish_profile_from_analysis(seeded['analysis_id'], field_id, code='EMPTY_RESULT_PROFILE') - shipping_onhand_admin_service.bind_source_parsing_profile( + freight_rpa_source_admin_service.bind_source_parsing_profile( [source['id']], profile['id'], actor_id=None, reason='空结果前已确认同类报表结构', operation='direct', ) @@ -201,7 +201,7 @@ def test_empty_configuration_export_is_successful_but_marks_data_validation_pend assert result['stage'] == 'empty_data_pending_validation' assert result['result']['data_validation'] == 'pending_first_non_empty_export' assert not FreightRpaOnhandReportFile.query.count() - current = next(item for item in shipping_onhand_admin_service.list_sources() if item['id'] == source['id']) + current = next(item for item in freight_rpa_source_admin_service.list_sources() if item['id'] == source['id']) # 关键断言:空结果测试不自动启用;本例仍缺发货模板,硬门槛阻断启用。 assert current['enabled'] is False assert current['activation']['missing_requirements'] == ['excel_template'] @@ -236,7 +236,7 @@ def test_configuration_test_automatically_verifies_compatible_bound_profile(app, seed_file = tmp_path / 'bound-profile-seed.xlsx'; _workbook(seed_file) seeded = onhand_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)}) profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='BOUND_PROFILE_VERIFY') - shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='direct') + freight_rpa_source_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='direct') verified = _complete_test_run(source, tmp_path) # 关键断言:当前绑定方案无需再出现在候选确认列表,测试直接写入启用所需的确认事实。 @@ -256,16 +256,16 @@ def test_verified_current_profile_does_not_auto_enable_ready_source(app, tmp_pat profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='AUTO_ENABLE_PROFILE') template = _published_template(code='AUTO_ENABLE_TEMPLATE') # s18 起解析绑定走配置行绑定服务,模板绑定仍走站点保存。 - shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='direct') - current = next(item for item in shipping_onhand_admin_service.list_sources() if item['id'] == source['id']) - shipping_onhand_admin_service.save_source({**current, 'excel_template_id': template.id}, actor_id=None, source_id=source['id']) + freight_rpa_source_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='direct') + current = next(item for item in freight_rpa_source_admin_service.list_sources() if item['id'] == source['id']) + freight_rpa_source_admin_service.save_source({**current, 'excel_template_id': template.id}, actor_id=None, source_id=source['id']) verified = _complete_test_run(source, tmp_path) source_model = db.session.get(FreightRpaSource, source['id']) # 关键断言:测试只写入验证事实,站点保持停用直至管理员显式启用。 assert verified['stage'] == 'current_profile_verified' assert source_model.enabled is False - assert shipping_onhand_admin_service.get_source_activation_status(source_model)['ready'] is True + assert freight_rpa_source_admin_service.get_source_activation_status(source_model)['ready'] is True def test_verified_current_profile_keeps_source_disabled_without_template(app, tmp_path): @@ -278,13 +278,13 @@ def test_verified_current_profile_keeps_source_disabled_without_template(app, tm seeded = _complete_test_run(source, tmp_path) profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='AUTO_ENABLE_BLOCKED') # s18 起解析绑定走配置行绑定服务;本例不绑模板以验证模板硬门槛。 - shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='direct') + freight_rpa_source_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='direct') _complete_test_run(source, tmp_path) source_model = db.session.get(FreightRpaSource, source['id']) # 关键断言:自动启用始终复用正式门禁,缺少模板不会被测试成功放行。 assert source_model.enabled is False - assert shipping_onhand_admin_service.get_source_activation_status(source_model)['missing_requirements'] == ['excel_template'] + assert freight_rpa_source_admin_service.get_source_activation_status(source_model)['missing_requirements'] == ['excel_template'] def test_empty_export_does_not_auto_enable_ready_fixed_source(app, tmp_path): @@ -298,9 +298,9 @@ def test_empty_export_does_not_auto_enable_ready_fixed_source(app, tmp_path): profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='AUTO_ENABLE_EMPTY') template = _published_template(code='AUTO_ENABLE_EMPTY_TEMPLATE') # s18 起解析绑定走配置行绑定服务,模板绑定仍走站点保存。 - shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='direct') - current = next(item for item in shipping_onhand_admin_service.list_sources() if item['id'] == source['id']) - shipping_onhand_admin_service.save_source({**current, 'excel_template_id': template.id}, actor_id=None, source_id=source['id']) + freight_rpa_source_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='direct') + current = next(item for item in freight_rpa_source_admin_service.list_sources() if item['id'] == source['id']) + freight_rpa_source_admin_service.save_source({**current, 'excel_template_id': template.id}, actor_id=None, source_id=source['id']) started = onhand_configuration_test.start_test_export(source['id'], actor_id=None) completed = onhand_configuration_test.report_test_export({'run_no': started['run_no'], 'status': 'empty'}) @@ -308,7 +308,7 @@ def test_empty_export_does_not_auto_enable_ready_fixed_source(app, tmp_path): # 关键断言:空库存是成功查询事实;硬门槛齐备时仍保持停用,等待显式开关。 assert completed['status'] == 'completed_empty' assert source_model.enabled is False - assert shipping_onhand_admin_service.get_source_activation_status(source_model)['ready'] is True + assert freight_rpa_source_admin_service.get_source_activation_status(source_model)['ready'] is True def test_batch_configuration_test_groups_profiles_and_isolates_site_results(app, tmp_path): @@ -329,7 +329,7 @@ def test_batch_configuration_test_groups_profiles_and_isolates_site_results(app, seed_file = tmp_path / 'batch-seed.xlsx'; _workbook(seed_file) seeded = onhand_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)}) profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='BATCH_PROFILE') - shipping_onhand_admin_service.bind_source_parsing_profile( + freight_rpa_source_admin_service.bind_source_parsing_profile( [first['id'], second['id'], third['id']], profile['id'], actor_id=None, reason='批量验证测试', operation='bulk', ) @@ -364,7 +364,7 @@ def test_retry_batch_only_retriggers_failed_sites(app, tmp_path): seed_file = tmp_path / 'retry-seed.xlsx'; _workbook(seed_file) seeded = onhand_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)}) profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='RETRY_PROFILE') - shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, reason='重试测试', operation='bulk') + freight_rpa_source_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, reason='重试测试', operation='bulk') batch = onhand_configuration_test.start_batch_test_export([source['id']], actor_id=None) run = batch['runs'][0] onhand_configuration_test.report_batch_test_exports({'validation_batch_id': batch['id'], 'results': [ @@ -386,7 +386,7 @@ def test_batch_callback_marks_changed_source_stale_and_ignores_unknown_run(app, seed_file = tmp_path / 'stale-batch-seed.xlsx'; _workbook(seed_file) seeded = onhand_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)}) profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='STALE_BATCH_PROFILE') - shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, reason='过期回调测试', operation='bulk') + freight_rpa_source_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, reason='过期回调测试', operation='bulk') batch = onhand_configuration_test.start_batch_test_export([source['id']], actor_id=None) run = batch['runs'][0] source_model = db.session.get(FreightRpaSource, source['id']) @@ -414,7 +414,7 @@ def test_latest_active_batch_restores_only_unfinished_validation(app, tmp_path): seed_file = tmp_path / 'restore-batch-seed.xlsx'; _workbook(seed_file) seeded = onhand_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)}) profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='RESTORE_BATCH_PROFILE') - shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='bulk') + freight_rpa_source_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='bulk') batch = onhand_configuration_test.start_batch_test_export([source['id']], actor_id=None) # 关键断言:刷新期间读取服务端 active batch,会返回待 Worker 处理的真实运行。 assert onhand_configuration_test.get_latest_active_validation_batch()['id'] == batch['id'] @@ -436,7 +436,7 @@ def test_batch_progress_marks_only_claimed_current_run_processing(app, tmp_path) seed_file = tmp_path / 'progress-batch-seed.xlsx'; _workbook(seed_file) seeded = onhand_configuration_test.report_test_export({'run_no': seed['run_no'], 'status': 'success', 'file_path': str(seed_file)}) profile = _publish_profile_from_analysis(seeded['analysis_id'], _published_order_field(), code='PROGRESS_BATCH_PROFILE') - shipping_onhand_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='bulk') + freight_rpa_source_admin_service.bind_source_parsing_profile([source['id']], profile['id'], actor_id=None, operation='bulk') batch = onhand_configuration_test.start_batch_test_export([source['id']], actor_id=None) run = batch['runs'][0] @@ -468,8 +468,8 @@ def test_latest_configuration_test_recovers_only_current_configuration(app, tmp_ first = onhand_configuration_test.start_test_export(source['id'], actor_id=None) assert onhand_configuration_test.get_latest_test_run(source['id'])['run_no'] == first['run_no'] - current = next(item for item in shipping_onhand_admin_service.list_sources() if item['id'] == source['id']) - shipping_onhand_admin_service.save_source({**current, 'display_name': 'Changed before callback'}, actor_id=None, source_id=source['id']) + current = next(item for item in freight_rpa_source_admin_service.list_sources() if item['id'] == source['id']) + freight_rpa_source_admin_service.save_source({**current, 'display_name': 'Changed before callback'}, actor_id=None, source_id=source['id']) # 关键断言:旧运行不再属于当前配置,重新测试必须创建新运行而不是误复用。 assert onhand_configuration_test.get_latest_test_run(source['id']) is None @@ -523,7 +523,7 @@ def test_batch_configuration_test_timeout_scales_with_shared_worker_queue(app, t db.session.commit() seed = _complete_test_run(first, tmp_path) profile = _publish_profile_from_analysis(seed['analysis_id'], _published_order_field(), code='TIMEOUT_QUEUE_PROFILE') - shipping_onhand_admin_service.bind_source_parsing_profile([first['id'], second['id']], profile['id'], actor_id=None, operation='bulk') + freight_rpa_source_admin_service.bind_source_parsing_profile([first['id'], second['id']], profile['id'], actor_id=None, operation='bulk') batch = onhand_configuration_test.start_batch_test_export([first['id'], second['id']], actor_id=None) queued_run = FreightRpaOnhandConfigurationTestRun.query.filter_by(source_id=second['id']).one() queued_run.created_at = datetime.utcnow() - timedelta(seconds=15) @@ -553,9 +553,9 @@ def test_confirming_test_profile_binds_only_compatible_published_profile(app, tm source_model = db.session.get(FreightRpaSource, source['id']) # s18 起解析绑定归 onhand_report_config 配置行,站点行不再有 parsing_profile_id。 assert source_model.onhand_report_config.parsing_profile_id == profile['id'] - assert 'configuration_test' not in shipping_onhand_admin_service.get_source_activation_status(source_model)['missing_requirements'] + assert 'configuration_test' not in freight_rpa_source_admin_service.get_source_activation_status(source_model)['missing_requirements'] # 关键断言:外部仓库映射只在调拨前校验,不应出现在站点启用阻断清单。 - assert shipping_onhand_admin_service.get_source_activation_status(source_model)['missing_requirements'] == ['excel_template'] + assert freight_rpa_source_admin_service.get_source_activation_status(source_model)['missing_requirements'] == ['excel_template'] template = ShippingExcelTemplate( template_code='TEST_ACTIVATION', display_name='Activation Template', version=1, status='published', @@ -570,10 +570,10 @@ def test_confirming_test_profile_binds_only_compatible_published_profile(app, tm db.session.flush() source_model.excel_template_id = template.id db.session.commit() - assert shipping_onhand_admin_service.get_source_activation_status(source_model)['ready'] is True - assert shipping_onhand_admin_service.activate_source(source['id'], actor_id=None)['enabled'] is True + assert freight_rpa_source_admin_service.get_source_activation_status(source_model)['ready'] is True + assert freight_rpa_source_admin_service.activate_source(source['id'], actor_id=None)['enabled'] is True assert 'configuration_test' not in { - item['code'] for item in shipping_onhand_admin_service.get_source_activation_status(source_model)['checks'] + item['code'] for item in freight_rpa_source_admin_service.get_source_activation_status(source_model)['checks'] } @@ -594,7 +594,7 @@ def test_rpa_profile_change_does_not_block_activation_hard_gates(app, tmp_path): db.session.commit() rpa_profile = db.session.get(FreightRpaProfile, source['rpa_profile_id']) - shipping_onhand_admin_service.save_profile({ + freight_rpa_source_admin_service.save_profile({ 'profile_code': rpa_profile.profile_code, 'display_name': rpa_profile.display_name, 'connector_type': rpa_profile.connector_type, 'login_url': rpa_profile.login_url, 'login_config_json': rpa_profile.login_config_json, 'enabled': True, @@ -602,11 +602,11 @@ def test_rpa_profile_change_does_not_block_activation_hard_gates(app, tmp_path): }, actor_id=None, profile_id=rpa_profile.id) source_model = db.session.get(FreightRpaSource, source['id']) - status = shipping_onhand_admin_service.get_source_activation_status(source_model) + status = freight_rpa_source_admin_service.get_source_activation_status(source_model) # 关键断言:连接变更不再把测试导出塞进启用门禁;硬门槛齐备即可启用。 assert 'configuration_test' not in {item['code'] for item in status['checks']} assert status['ready'] is True - assert shipping_onhand_admin_service.activate_source(source['id'], actor_id=None)['enabled'] is True + assert freight_rpa_source_admin_service.activate_source(source['id'], actor_id=None)['enabled'] is True def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, tmp_path): @@ -620,8 +620,8 @@ def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, t completed = _complete_test_run(source, tmp_path) profile = _publish_profile_from_analysis(completed['analysis_id'], _published_order_field(), code='TEST_STALE') - current = next(item for item in shipping_onhand_admin_service.list_sources() if item['id'] == source['id']) - shipping_onhand_admin_service.save_source({**current, 'display_name': 'Changed after test'}, actor_id=None, source_id=source['id']) + current = next(item for item in freight_rpa_source_admin_service.list_sources() if item['id'] == source['id']) + freight_rpa_source_admin_service.save_source({**current, 'display_name': 'Changed after test'}, actor_id=None, source_id=source['id']) with pytest.raises(ConflictError) as stale: onhand_configuration_test.confirm_test_profile(source['id'], completed['run_no'], profile['id'], actor_id=None) assert stale.value.code == 'SHIPPING.ONHAND_CONFIGURATION_TEST_STALE' diff --git a/backend/tests/test_onhand_parsing_profile.py b/backend/tests/test_onhand_parsing_profile.py index 31ce3416..6a233b9a 100644 --- a/backend/tests/test_onhand_parsing_profile.py +++ b/backend/tests/test_onhand_parsing_profile.py @@ -1,6 +1,6 @@ """ 用途:验证可复用库存解析 Profile 的版本、共享绑定和订单字段匹配键门禁。 -依赖:onhand_parsing_profile、shipping_onhand_admin_service、订单 Schema 服务。 +依赖:freight_rpa.parsing_profile、freight_rpa_source_admin_service、订单 Schema 服务。 逻辑:发布一个 Profile 后绑定多个 Source;新版本并存且旧绑定稳定,非法字段、退役引用或非发布绑定被拒绝。 """ @@ -8,8 +8,8 @@ from cryptography.fernet import Fernet import pytest from app.core.errors import ValidationError -from app.services.admin import shipping_onhand_admin_service -from app.services.shipping_notice import onhand_parsing_profile +from app.services.admin import freight_rpa_source_admin_service +from app.services.freight_rpa import parsing_profile as 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, FreightRpaOnhandField, FreightRpaOnhandStructureAnalysis @@ -84,14 +84,21 @@ def _schema_field_config(field_id: str) -> dict: def _source(profile_id: int, parsing_id: int, code: str) -> dict: - """构造绑定共享解析 Profile 的 DBS 库存源。""" + """构造绑定共享解析 Profile 的 DBS 库存源(s18:解析绑定走 onhand_report_config)。""" return { 'source_code': code, 'display_name': code, 'connector_type': 'dbs', - 'rpa_profile_id': profile_id, 'parsing_profile_id': parsing_id, + 'rpa_profile_id': profile_id, 'excel_template_id': _excel_template_id(), 'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': code, - 'report_path_json': {'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand'}, - 'query_parameters_json': [], 'snapshot_ttl_seconds': 3600, 'enabled': True, + 'snapshot_ttl_seconds': 3600, 'enabled': True, + 'onhand_report_config': { + 'parsing_profile_id': parsing_id, + 'report_path_json': { + 'program_group': 'Bison', 'program_label': 'AWSBI', + 'report_group': 'Inventory', 'report_name': 'On Hand', + }, + 'query_parameters_json': [], + }, } @@ -117,16 +124,16 @@ def test_published_parsing_profile_can_be_shared_by_sources(app): app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): parsing = _published_profile() - login = shipping_onhand_admin_service.save_profile({ + login = freight_rpa_source_admin_service.save_profile({ 'profile_code': 'DBS_LOGIN', 'display_name': 'DBS', 'connector_type': 'dbs', 'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'}, 'username': 'u', 'password': 'p', 'enabled': True, }, actor_id=None) - first = shipping_onhand_admin_service.save_source(_source(login['id'], parsing['id'], 'DUB'), actor_id=None) - second = shipping_onhand_admin_service.save_source(_source(login['id'], parsing['id'], 'RTM'), actor_id=None) + first = freight_rpa_source_admin_service.save_source(_source(login['id'], parsing['id'], 'DUB'), actor_id=None) + second = freight_rpa_source_admin_service.save_source(_source(login['id'], parsing['id'], 'RTM'), actor_id=None) - assert first['parsing_profile_id'] == parsing['id'] - assert second['parsing_profile_id'] == parsing['id'] + assert first['onhand_report_config']['parsing_profile_id'] == parsing['id'] + assert second['onhand_report_config']['parsing_profile_id'] == parsing['id'] assert onhand_parsing_profile.list_profiles()[0]['source_count'] == 2 @@ -144,13 +151,13 @@ def test_source_rejects_draft_parsing_profile(app): }, 'sample_analysis_id': _sample_evidence(headers=['SKU', 'RSV', 'QTY']), }, actor_id=None) - login = shipping_onhand_admin_service.save_profile({ + login = freight_rpa_source_admin_service.save_profile({ 'profile_code': 'LOGIN', 'display_name': 'Login', 'connector_type': 'dbs', 'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'}, 'username': 'u', 'password': 'p', 'enabled': True, }, actor_id=None) with pytest.raises(ValidationError) as exc_info: - shipping_onhand_admin_service.save_source(_source(login['id'], draft['id'], 'DUB'), actor_id=None) + freight_rpa_source_admin_service.save_source(_source(login['id'], draft['id'], 'DUB'), actor_id=None) assert exc_info.value.code == 'SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED' @@ -178,7 +185,10 @@ def test_new_published_version_does_not_retire_bound_version(app): app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): first = _published_profile() - field_id = order_schema_service.get_state()['fields'][0]['id'] + field_id = next( + item['field_id'] for item in order_schema_service.get_published_contract()['fields'] + if item.get('field_code') == 'part_number' and item.get('scope') == 'line' + ) second_draft = onhand_parsing_profile.save_draft({ 'profile_code': 'DBS_COMMON', 'display_name': 'DBS Common v2', 'file_format': 'xlsx', 'sample_analysis_id': _sample_evidence(headers=['SKU', 'RSV', 'QTY']), @@ -198,12 +208,12 @@ def test_referenced_published_profile_cannot_be_retired(app): app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): parsing = _published_profile() - login = shipping_onhand_admin_service.save_profile({ + login = freight_rpa_source_admin_service.save_profile({ 'profile_code': 'RETIRE_LOGIN', 'display_name': 'DBS', 'connector_type': 'dbs', 'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'}, 'username': 'u', 'password': 'p', 'enabled': True, }, actor_id=None) - shipping_onhand_admin_service.save_source(_source(login['id'], parsing['id'], 'RETIRE'), actor_id=None) + freight_rpa_source_admin_service.save_source(_source(login['id'], parsing['id'], 'RETIRE'), actor_id=None) with pytest.raises(Exception) as exc_info: onhand_parsing_profile.retire(parsing['id']) assert getattr(exc_info.value, 'code', '') == 'SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED' diff --git a/backend/tests/test_onhand_profile_matching.py b/backend/tests/test_onhand_profile_matching.py index cca877d0..1c782761 100644 --- a/backend/tests/test_onhand_profile_matching.py +++ b/backend/tests/test_onhand_profile_matching.py @@ -13,7 +13,8 @@ from io import BytesIO from openpyxl import Workbook from werkzeug.datastructures import FileStorage -from app.services.shipping_notice import onhand_parsing_profile, onhand_structure_analysis +from app.services.freight_rpa import parsing_profile as 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 from app.models import FreightRpaOnhandField diff --git a/backend/tests/test_onhand_structure_analysis.py b/backend/tests/test_onhand_structure_analysis.py index c0984d47..e74f269d 100644 --- a/backend/tests/test_onhand_structure_analysis.py +++ b/backend/tests/test_onhand_structure_analysis.py @@ -260,7 +260,7 @@ def test_profile_draft_requires_persisted_sample_evidence(app): """绕过样本分析直接保存草稿时必须被拒绝,避免来源表头脱离审计依据。""" with app.app_context(): field_id = _published_part_number() - from app.services.shipping_notice import onhand_parsing_profile + from app.services.freight_rpa import parsing_profile as onhand_parsing_profile with pytest.raises(ValidationError) as exc_info: onhand_parsing_profile.save_draft({ @@ -303,7 +303,7 @@ def test_profile_draft_purpose_passthrough_creates_inbound_profile(app, tmp_path def test_publish_inbound_profile_skips_order_match_key_contract(app, tmp_path): """发布 inbound 规则不需要订单匹配键:其端点契约是定死异动字段,不是订单 Schema。""" - from app.services.shipping_notice import onhand_parsing_profile + from app.services.freight_rpa import parsing_profile as onhand_parsing_profile app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') with app.app_context(): diff --git a/backend/tests/test_parsing_profile_purpose.py b/backend/tests/test_parsing_profile_purpose.py index 03c42b91..75ae61a9 100644 --- a/backend/tests/test_parsing_profile_purpose.py +++ b/backend/tests/test_parsing_profile_purpose.py @@ -1,9 +1,9 @@ """通用文件解析规则 purpose 字段测试(L0 纯单元 + DB 列校验 + 迁移往返)。 用途:验证 onhand_parsing_profile._validate_definition(purpose=...) 分支—— - inbound 端点用定死领域字段(doc_no/material_code/quantity/movement_date 必填、 - 不查库存字段目录、无 match_keys);onhand/outbound 维持既有库存字段目录 + match_keys - 校验(outbound 出站文件结构就位,暂无运行时消费方)。并用 app fixture 校验模型 + inbound/outbound 端点用定死领域字段(doc_no/material_code/quantity/movement_date 必填、 + 不查库存字段目录、无 match_keys);onhand 维持库存字段目录 + match_keys 校验。 + 并用 app fixture 校验模型 purpose 列默认 'onhand'、CHECK 约束三元枚举,以及 tt15 迁移 SQLite 真实往返。 依赖:onhand_parsing_profile._validate_definition / save_draft(纯 + app SQLite)、 migrations/versions/tt15(batch_alter_table 改枚举)、app_ctx(根 conftest app @@ -23,7 +23,7 @@ from alembic.migration import MigrationContext from alembic.operations import Operations from app.core.errors import ValidationError -from app.services.shipping_notice.onhand_parsing_profile import _validate_definition, save_draft +from app.services.freight_rpa.parsing_profile import _validate_definition, save_draft pytestmark = pytest.mark.pure_unit @@ -81,6 +81,36 @@ def test_inbound_definition_rejects_unknown_field(): _validate_definition(raw, purpose='inbound') +def test_outbound_definition_uses_movement_fields(): + """outbound 定义完整 → 走异动字段路径,match_keys 空。""" + definition = _validate_definition(_inbound_definition(), purpose='outbound') + assert definition['match_keys'] == [] + assert definition['field_mapping']['doc_no'] == '单据编号' + + +def test_outbound_onhand_shaped_definition_rejected(app_ctx): + """库存目录形态(含 match_keys)在 outbound 下应失败。""" + from app.models import FreightRpaOnhandField, ShippingOrderField + from app import db + + rows = {item.field_code: item for item in FreightRpaOnhandField.query.filter_by(status='active').all()} + field_mapping = { + str(rows['part_number'].id): 'Supplier Sku', + str(rows['reservation_id'].id): 'Reservation ID', + str(rows['available_qty'].id): 'Qty Available', + } + order_field = ShippingOrderField(field_code='part_number', scope='line', value_type='string') + db.session.add(order_field) + db.session.flush() + raw = { + 'header_row_index': 1, + 'field_mapping': field_mapping, + 'match_keys': [{'order_field_id': order_field.id, 'inventory_field_id': next(iter(field_mapping))}], + } + with pytest.raises(ValidationError): + _validate_definition(raw, purpose='outbound') + + def test_purpose_enum_values(): """模型 purpose 列:default/server_default 均为 'onhand',CHECK 名为批次 S 新约束,枚举恰为三元。""" from app.models.freight_rpa_config import FreightRpaParsingProfile @@ -128,25 +158,15 @@ def _catalog_mapping() -> dict[str, str]: def test_draft_accepts_outbound_and_rejects_legacy(app_ctx): """save_draft purpose='outbound' 通过校验;purpose='movement' 报 SHIPPING.ONHAND_PARSING_PROFILE_INVALID。""" - from app import db - from app.models import ShippingOrderField - - # 出站文件结构就位:outbound 走库存字段目录分支(与 onhand 同构),需行级订单匹配键。 - order_field = ShippingOrderField(field_code='part_number', scope='line', value_type='string') - db.session.add(order_field) - db.session.flush() - headers = ['Supplier Sku', 'Reservation ID', 'Qty Available'] + headers = [value for value in _inbound_definition()['field_mapping'].values()] outbound = save_draft({ - 'profile_code': 'OUT_STD', 'display_name': '出站结构就位', 'purpose': 'outbound', - 'file_format': 'xlsx', 'sample_analysis_id': _sample_evidence(headers=headers), - 'definition': { - 'header_row_index': 1, - 'field_mapping': _catalog_mapping(), - 'match_keys': [{'order_field_id': order_field.id, 'inventory_field_id': next(iter(_catalog_mapping()))}], - }, + 'profile_code': 'OUT_STD', 'display_name': '出站异动解析', 'purpose': 'outbound', + 'file_format': 'xlsx', 'sample_analysis_id': _sample_evidence(headers=headers, sheet_name='Inbound'), + 'definition': _inbound_definition(), }, actor_id=None) assert outbound['purpose'] == 'outbound' + assert outbound['definition']['match_keys'] == [] with pytest.raises(ValidationError) as exc_info: save_draft({ diff --git a/backend/tests/test_receipt_excel_empty.py b/backend/tests/test_receipt_excel_empty.py index 6f6e0c03..04dda536 100644 --- a/backend/tests/test_receipt_excel_empty.py +++ b/backend/tests/test_receipt_excel_empty.py @@ -68,12 +68,12 @@ def test_title_row_must_not_count_as_detail(tmp_path: Path): """ 标题含 receipt 时旧逻辑会把真表头当成明细 → 误 success。 - [断言意图] 仅标题+表头必须判定为无明细(False),enforce 抛 no_receipt_data。 + [断言意图] 仅标题+表头必须判定为无明细(False),enforce 抛 no_inbound_data。 """ path = tmp_path / 'header_only.xlsx' _write_dsv_title_header_only(path) assert inbound_excel_has_detail_rows(path) is False - with pytest.raises(NoInboundDataError, match='no_receipt_data'): + with pytest.raises(NoInboundDataError, match='no_inbound_data'): enforce_inbound_excel_not_empty(path) @@ -97,10 +97,10 @@ def test_production_header_only_sample_is_empty(tmp_path: Path): """ 生产样例 receipt_RUN202609290016193A2E_*_BYAWSPRD01_* 仅表头却曾 success。 - [断言意图] 复制该文件后必须判 empty / no_receipt_data。 + [断言意图] 复制该文件后必须判 empty / no_inbound_data。 """ target = tmp_path / _DROP_SAMPLE.name shutil.copy2(_DROP_SAMPLE, target) assert inbound_excel_has_detail_rows(target) is False - with pytest.raises(NoInboundDataError, match='no_receipt_data'): + with pytest.raises(NoInboundDataError, match='no_inbound_data'): enforce_inbound_excel_not_empty(target) diff --git a/backend/tests/test_shipping_receipt_rpa_archive.py b/backend/tests/test_shipping_receipt_rpa_archive.py index 4720b70b..eff5cbdb 100644 --- a/backend/tests/test_shipping_receipt_rpa_archive.py +++ b/backend/tests/test_shipping_receipt_rpa_archive.py @@ -27,12 +27,12 @@ from app.models import ( User, ) from app.services.schedule.freight_rpa_inbound_archive import ( - get_receipt_archive_dir, - persist_receipt_rpa_raw_zip_archive, - receipt_raw_zip_available_from_summary, - receipt_raw_zip_download_name, - receipt_rpa_attachment_stem, - resolve_receipt_raw_zip_download, + get_inbound_archive_dir, + persist_inbound_rpa_raw_zip_archive, + inbound_raw_zip_available_from_summary, + inbound_raw_zip_download_name, + inbound_rpa_attachment_stem, + resolve_inbound_raw_zip_download, _build_zip_entry_name, ) from tests.conftest import parse_api_error @@ -125,14 +125,14 @@ def _make_receipt_run_with_file( return run, report_file -def test_receipt_raw_zip_available_from_summary_reads_persisted_flag(): - """列表可见性应只依赖 summary.raw_receipt_zip_available。""" - assert receipt_raw_zip_available_from_summary({'raw_receipt_zip_available': True}) is True - assert receipt_raw_zip_available_from_summary({'raw_receipt_zip_available': False}) is False - assert receipt_raw_zip_available_from_summary(None) is False +def test_inbound_raw_zip_available_from_summary_reads_persisted_flag(): + """列表可见性应只依赖 summary.raw_inbound_zip_available。""" + assert inbound_raw_zip_available_from_summary({'raw_inbound_zip_available': True}) is True + assert inbound_raw_zip_available_from_summary({'raw_inbound_zip_available': False}) is False + assert inbound_raw_zip_available_from_summary(None) is False -def test_get_receipt_archive_dir_falls_back_when_config_none(app, tmp_path, monkeypatch): +def test_get_inbound_archive_dir_falls_back_when_config_none(app, tmp_path, monkeypatch): """ Config 缺项时 Flask config 可能为 None;不得 Path(None) 导致 finalize ZIP 全空。 @@ -147,7 +147,7 @@ def test_get_receipt_archive_dir_falls_back_when_config_none(app, tmp_path, monk ) with app.app_context(): app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = None - archive_dir = Path(get_receipt_archive_dir()) + archive_dir = Path(get_inbound_archive_dir()) assert archive_dir.is_dir() assert archive_dir == (tmp_path / 'receipt_archives_fallback').resolve() @@ -160,8 +160,8 @@ def test_config_exposes_freight_rpa_receipt_archive_dir(app): assert str(value).strip() != '' -def test_serialize_run_reads_receipt_raw_zip_available_from_summary(app): - """serialize_run 应暴露 receipt_raw_zip_available 供管理端深链/按钮。""" +def test_serialize_run_reads_inbound_raw_zip_available_from_summary(app): + """serialize_run 应暴露 inbound_raw_zip_available 供管理端深链/按钮。""" from app.services.schedule.query_service import serialize_run with app.app_context(): @@ -182,12 +182,12 @@ def test_serialize_run_reads_receipt_raw_zip_available_from_summary(app): run_no='RUN-RCP-SER', schedule_task_id=task.id, status='success', - response_summary_json={'raw_receipt_zip_available': True}, + response_summary_json={'raw_inbound_zip_available': True}, ) db.session.add(run) db.session.commit() payload = serialize_run(run) - assert payload['receipt_raw_zip_available'] is True + assert payload['inbound_raw_zip_available'] is True assert payload['inventory_raw_zip_available'] is False @@ -201,7 +201,7 @@ def test_build_zip_entry_name_prefers_source_code(): ) == '001_DSV360_AWSBI.xlsx' -def test_persist_receipt_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_path, monkeypatch): +def test_persist_inbound_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_path, monkeypatch): """finalize 预生成应落盘 ZIP(含 manifest)并返回 summary 字段。""" archive_dir = tmp_path / 'receipt_archives' app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(archive_dir) @@ -217,13 +217,13 @@ def test_persist_receipt_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_pat callback_id='receipt-arch-1', original_filename='receipt_RUN_DSV360_AWSDU_NA.xlsx', ) - summary = persist_receipt_rpa_raw_zip_archive(run) + summary = persist_inbound_rpa_raw_zip_archive(run) # [断言意图] summary 标记可用且路径落在配置归档目录。 - assert summary['raw_receipt_zip_available'] is True - assert summary['raw_receipt_file_count'] == 1 - assert summary['raw_receipt_file_ids'] == [report_file.id] - zip_path = Path(summary['raw_receipt_zip_path']) + assert summary['raw_inbound_zip_available'] is True + assert summary['raw_inbound_file_count'] == 1 + assert summary['raw_inbound_file_ids'] == [report_file.id] + zip_path = Path(summary['raw_inbound_zip_path']) assert zip_path.is_file() assert zip_path.parent.resolve() == archive_dir.resolve() @@ -237,7 +237,7 @@ def test_persist_receipt_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_pat assert manifest['files'][0]['file_id'] == report_file.id -def test_resolve_receipt_raw_zip_download_rejects_missing_summary(app, tmp_path): +def test_resolve_inbound_raw_zip_download_rejects_missing_summary(app, tmp_path): """summary 未标记可用时应 404。""" app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(tmp_path / 'receipt_archives') with app.app_context(): @@ -246,27 +246,27 @@ def test_resolve_receipt_raw_zip_download_rejects_missing_summary(app, tmp_path) run_no='RUNRCPARCHMISS', callback_id='receipt-arch-miss', ) - run.response_summary_json = {'raw_receipt_zip_available': False} + run.response_summary_json = {'raw_inbound_zip_available': False} db.session.commit() with pytest.raises(NotFoundError): - resolve_receipt_raw_zip_download(run) + resolve_inbound_raw_zip_download(run) def test_receipt_attachment_stem_uses_local_timezone(app): - """展示名前缀为收料RPA-日期-时刻(业务时区)。""" + """展示名前缀为入站RPA-日期-时刻(业务时区)。""" with app.app_context(): run, _ = _make_receipt_run_with_file( schedule_no='SCH-RCP-STEM', run_no='RUN202609281530001234', callback_id='receipt-stem', ) - stem = receipt_rpa_attachment_stem(run) - assert stem.startswith('收料RPA-') - assert receipt_raw_zip_download_name(run) == f'{stem}-收料.zip' + stem = inbound_rpa_attachment_stem(run) + assert stem.startswith('入站RPA-') + assert inbound_raw_zip_download_name(run) == f'{stem}-入站.zip' -def test_admin_can_download_receipt_raw_zip(app, client, admin_jwt_headers, tmp_path, monkeypatch): - """管理端 receipt-raw-zip 应返回 ZIP 与展示名。""" +def test_admin_can_download_inbound_raw_zip(app, client, admin_jwt_headers, tmp_path, monkeypatch): + """管理端 inbound-raw-zip 应返回 ZIP 与展示名。""" archive_dir = tmp_path / 'receipt_archives' app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(archive_dir) monkeypatch.setattr( @@ -280,14 +280,14 @@ def test_admin_can_download_receipt_raw_zip(app, client, admin_jwt_headers, tmp_ run_no='RUNRCPDL1', callback_id='receipt-dl-1', ) - summary = persist_receipt_rpa_raw_zip_archive(run) + summary = persist_inbound_rpa_raw_zip_archive(run) run.response_summary_json = summary db.session.commit() run_id = run.id - expected_name = receipt_raw_zip_download_name(run) + expected_name = inbound_raw_zip_download_name(run) response = client.get( - f'/api/admin/schedule-runs/{run_id}/receipt-raw-zip', + f'/api/admin/schedule-runs/{run_id}/inbound-raw-zip', headers=admin_jwt_headers, ) assert response.status_code == 200 diff --git a/docs/adr/0004-freight-rpa-report-ownership.md b/docs/adr/0004-freight-rpa-report-ownership.md index 02f5932b..58b3a477 100644 --- a/docs/adr/0004-freight-rpa-report-ownership.md +++ b/docs/adr/0004-freight-rpa-report-ownership.md @@ -1,12 +1,12 @@ # Freight RPA 报表归 RPA,业务方只消费报表事实 -阶段 A 只归位编排,写入权仍在发货代码。2026-10-18 收进同一 Flask 进程:登录连接、站点、在手配置、入站配置、解析方案、在手文件、入站文件由 `freight_rpa` 写入。业务方只消费报表事实(`report_kind`、`source_code`、`file_id`、`sha256`、`ok`、`error_code`、`error_message`,可选 `unit_run_id`)。本阶段分发 onhand 与 inbound;`handle_onhand_report` 由 `register_onhand_sinks` 注册,`handle_inbound_report` 由 `register_inbound_sinks` 注册。 +阶段 A 只归位编排,写入权仍在发货代码。2026-10-18 收进同一 Flask 进程:登录连接、站点、在手配置、入站/出站配置、解析方案、在手/入站/出站文件由 `freight_rpa` 写入。业务方只消费报表事实(`report_kind`、`source_code`、`file_id`、`sha256`、`ok`、`error_code`、`error_message`,可选 `unit_run_id`)。本阶段分发 onhand、inbound 与 outbound;`handle_onhand_report` 由 `shipping_notice.rpa_sinks.register_onhand_sinks` 注册,`handle_inbound_report` / `handle_outbound_report` 由 `in_transit_transfer.rpa_sinks.register_inbound_sinks` / `register_outbound_sinks` 注册(2026-10-19 出站全栈;组合根按消费域拆分)。 -文件在 RPA 事务提交之后,同一次 HTTP 请求调用 `handle_onhand_report` / `handle_inbound_report`。失败返回 5xx,文件保留,Worker 重试。在手批量 HTTP 入口只把既有发货作业入队,该作业在文件提交之后分发在手事实。不另建服务、不引入消息队列。出站抓取不在本决策内;`report_kind=outbound` 只占位。 +文件在 RPA 事务提交之后,同一次 HTTP 请求调用 `handle_onhand_report` / `handle_inbound_report` / `handle_outbound_report`。失败返回 5xx,文件保留,Worker 重试。在手批量 HTTP 入口只把既有发货作业入队,该作业在文件提交之后分发在手事实。不另建服务、不引入消息队列。 ## Consequences - 业务方不再写站点、配置、解析方案和报表文件,只保存 `source_code`。 - 处理函数失败不回滚已提交文件,Worker 凭 5xx 重试整笔回调。 - 在手批量与单笔分叉:批量入口只入队既有发货作业,不在该 HTTP 请求内分发。 -- outbound 留在事实白名单;本阶段不注册处理函数,也不做出站抓取。 +- `report_kind=outbound` 已注册 `handle_outbound_report`(在途调拨 sink);出站不建 notification_deliveries,运维与入站对称走排程。 diff --git a/docs/convention/env_loading_priority.md b/docs/convention/env_loading_priority.md index 3b3d347a..619cefe9 100644 --- a/docs/convention/env_loading_priority.md +++ b/docs/convention/env_loading_priority.md @@ -68,6 +68,6 @@ - 后端与 Windows Worker 共享目录、共享 scope、哨兵:`FREIGHT_RPA_SHARED_<配置项>`。 - Windows Worker 自身运行、浏览器、Driver、日志与账号参数:`FREIGHT_RPA_WORKER_<配置项>`。 - RPA Profile 凭据 Fernet 主密钥:`FREIGHT_RPA_CREDENTIAL_KEY`。 -- 共享目录在 `freight_rpa/` 根下按域分层:`onhand/`(在手库存,原 `inventory/`)、`inbound/`(入站,原 `receipt/`)、`outbound/`(出站抓取预留,叶目录与 inbound 同构)、`upload/`(货代上传,叶 `triggers`/`queue`)、`common/`(跨 Worker 共享物)。抓取域 env 形如 `FREIGHT_RPA_SHARED_{ONHAND|INBOUND|OUTBOUND}_{TRIGGER|DROP}_DIR`、`FREIGHT_RPA_{ONHAND|INBOUND|OUTBOUND}_{TIMEOUT_SECONDS|ARCHIVE_DIR}`;上传域为 `FREIGHT_RPA_SHARED_UPLOAD_{TRIGGER|QUEUE}_DIR`;另有 `FREIGHT_RPA_WORKER_SAMPLE_ONHAND`。 +- 共享目录在 `freight_rpa/` 根下按域分层:`onhand/`(在手库存,原 `inventory/`)、`inbound/`(入站,原 `receipt/`)、`outbound/`(出站抓取,叶目录与 inbound 同构:`triggers`/`drop`/`logs`/`archives`)、`upload/`(货代上传,叶 `triggers`/`queue`)、`common/`(跨 Worker 共享物)。抓取域 env 形如 `FREIGHT_RPA_SHARED_{ONHAND|INBOUND|OUTBOUND}_{TRIGGER|DROP}_DIR`、`FREIGHT_RPA_{ONHAND|INBOUND|OUTBOUND}_{TIMEOUT_SECONDS|ARCHIVE_DIR}`(出站超时默认 900 秒,与入站同口径);上传域为 `FREIGHT_RPA_SHARED_UPLOAD_{TRIGGER|QUEUE}_DIR`;另有 `FREIGHT_RPA_WORKER_SAMPLE_ONHAND`。出站 trigger/drop 须与 Windows `start_outbound_worker.ps1` 指向同一物理目录,漏配时后端会写容器本地默认路径导致 Worker 看不到 trigger。 - 修订注记:2026-10-16 批次 R 更名——分域名与 env 后缀 inventory→onhand、receipt→inbound 一并切换(`FREIGHT_RPA_UPLOAD_*` 词根不变;不设旧名兼容层)。 - 禁止新增 `SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`。历史名称 `SHIPPING_NOTICE_RPA_*` 于 2026-09-18 未上线期一刀切废弃,不设兼容层,禁止再新增或引用。 diff --git a/docs/features/freight-rpa/GLOSSARY.md b/docs/features/freight-rpa/GLOSSARY.md index 1650dc7c..bb4f8aaa 100644 --- a/docs/features/freight-rpa/GLOSSARY.md +++ b/docs/features/freight-rpa/GLOSSARY.md @@ -9,11 +9,11 @@ _Avoid_: inventory(代码/契约中已退役) **Inbound(入站)**: -货代系统导出的入站(收货)文件,即原「收料报表」。代码、契约、目录一律用 inbound;中文用户文案用「入站」;指货代开出的原始单据本身时可保留「收料报表」称谓。表名归属:inbound 子域事实前缀 `freight_rpa_inbound_*`。 -_Avoid_: receipt(代码/契约中已退役) +货代系统导出的入站(收货)文件,即原「收料报表」。代码、契约、目录一律用 inbound;**中文用户可见文案统一「入站」**(排程企微 raw-zip 提示、跳过计数等);指货代 WMS 原始报表称谓时可保留「收料报表」。表名归属:inbound 子域事实前缀 `freight_rpa_inbound_*`。入站侧已删除 `freight_rpa_inbound_notification_deliveries` 与「重发企微」;**无**工作台「收料文件」页,运维统一到排程管理 + `inbound-raw-zip` 深链下载。 +_Avoid_: receipt(代码/契约中已退役);在工作台单独维护收料文件列表 **Outbound(出站)**: -**仅**在途仓调拨语境:出站异动 / 未来出站文件抓取(与 `record_kind=outbound` 同语义)。共享目录与 inbound **同构就位**:`freight_rpa/outbound/{triggers,drop,logs,archives}`;对应 env `FREIGHT_RPA_SHARED_OUTBOUND_*` / `FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR` / `FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS`。抓取 Worker 本期未实施。**不承载**发货履约「出货」、**不承载上传**。 +**仅**在途仓调拨语境:出站异动 / 出站文件抓取(与 `record_kind=outbound` 同语义)。共享目录与 inbound **同构**:`freight_rpa/outbound/{triggers,drop,logs,archives}`;env `FREIGHT_RPA_SHARED_OUTBOUND_{TRIGGER,DROP}_DIR`、`FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR`、`FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS`(默认 900)。独立 Worker(`outbound_rpa_worker.py`)、排程 `freight-rpa-outbound`、回调 `/api/freight-rpa/outbound-*`、事实 `report_kind=outbound` 经 `register_outbound_sinks` → `handle_outbound_report` 已交付。**不建** outbound `notification_deliveries`;**无**工作台出站文件页(与入站瘦身对称)。**不承载**发货履约「出货」、**不承载 upload**。 _Avoid_: 与货代履约「出货」(shipment Excel / 上传门户) 混用;把 upload 目录塞进 outbound/ **货代出货(履约 / shipment)**: diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index bbaf4e33..16d40ec3 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -2958,11 +2958,11 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui - 上传成功 / 失败回执样例 - CRANE「Inbound Details」真实收料样本文件(用于建立异动解析规则的字段映射) -### 1.9 收料报表 RPA 共享部署(Windows RPA + Ubuntu 后端) +### 1.9 入站报表 RPA 共享部署(Windows RPA + Ubuntu 后端) -> 本节是收料报表 RPA(独立 Windows Worker)的部署手册,章节结构与 `1.5` 库存导出 RPA 对应。安全提示与 `1.5` 相同:示例中的 IP、账号、密码、API Key 均为占位符,请在各环境本地替换为实际值,**禁止将真实密码/密钥写入仓库或提交到 Git**。 -> 前置条件:已按 `1.5.2` 至 `1.5.10` 完成同一台 Windows RPA 主机、`hxops-rpa-test-data` / `hxops-rpa-prod-data` SMB 共享、Ubuntu 挂载与后端容器挂载。收料**不新建共享、不新建挂载**,只在既有共享下增加专用子目录、独立 Worker 与独立回调。 -> Worker 脚本层速查另见 [scripts/freight_rpa/README.md](../../../scripts/freight_rpa/README.md) 顶部「收料 RPA(独立 Worker)」;本节是部署权威来源。 +> 本节是**入站**(inbound,用户文案「入站」)报表 RPA 的部署手册,章节结构与 `1.5` 库存导出 RPA 对应。安全提示与 `1.5` 相同:示例中的 IP、账号、密码、API Key 均为占位符,请在各环境本地替换为实际值,**禁止将真实密码/密钥写入仓库或提交到 Git**。 +> 前置条件:已按 `1.5.2` 至 `1.5.10` 完成同一台 Windows RPA 主机、`hxops-rpa-test-data` / `hxops-rpa-prod-data` SMB 共享、Ubuntu 挂载与后端容器挂载。入站**不新建共享、不新建挂载**,只在既有共享下增加专用子目录、独立 Worker 与独立回调。工作台「收料文件」页已下线;接收人通过排程执行结果通知或 `inbound-raw-zip` 深链下载,**无** inbound notification_deliveries / 管理端「重发企微」。 +> Worker 脚本层速查另见 [scripts/freight_rpa/README.md](../../../scripts/freight_rpa/README.md) 顶部「入站 RPA(独立 Worker)」;本节是部署权威来源。 #### 1.9.1 与库存 RPA 的边界和目录规划 @@ -3070,7 +3070,7 @@ FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS=900 - 到期对象由平台排程任务 **货代收料归档到期清理**(`freight-rpa-inbound-retention`)删除,建议在排程管理配置每日一次;它只删除过期对象,不删除运行、文件事实与审计记录。 - 企微通知与库存排程**同一出口同一门禁**(`scheduler_service._notify_schedule_run_wecom`,2026-09-21 统一;2026-09-28 起附件改为 ZIP):收料 run 全部单元终态归集后**一次性**发送 textcard 汇总(`schedule_completed` 事件)+ **汇总结果 Excel** `收料RPA-{yyyyMMdd}-{HHmm}-结果.xlsx`(2026-10-12 对齐库存补齐;列头 收料源/仓库/连接器/归档文件数/导出状态/跳过原因/错误原因,`empty→skipped`、`cancelled→failed` 与卡片计数同口径,导出失败降级 success→partial_failed 并记 `excel_export_status/excel_failed`)+ **一个**原始收料包 `收料RPA-{yyyyMMdd}-{HHmm}-收料.zip`(包内 `{序号}_{source_code}.xlsx` + `manifest.json`,磁盘键 `{run_no}.zip`);不再逐文件推送。Worker 落盘名为 `receipt_{batch_run_no}_{source_code}_{warehouse_or_NA}_{stamp}.xlsx`。接收人取排程任务的 `notify_user_ids` + `notify_enabled`,且必须已完成企微绑定;排障查 `schedule_runs.wecom_notified / wecom_notify_error`。管理员重发(`/receipt-report-files/{id}/resend`)保留为补偿通道,不触发 RPA,投递失败记 `WECOM_USER_UNBOUND`。 -排程创建:管理端「排程管理」新增平台任务 **货代收料 RPA**(`freight-rpa-inbound`),可选参数 `source_codes` 留空则执行全部已启用站点中已配置收料的站点,按需配置 Cron 与接收人。收料排程与库存排程相互独立(站点、Cron、接收人分别选择)。收料触发前执行**与库存同口径**的 Worker 在线 fail-fast 检查(`assert_receipt_rpa_worker_ready`:心跳 TTL + 收料 trigger 目录哨兵 + scope 匹配,2026-09-30 起对齐):Worker 离线、哨兵缺失(含漏配 `FREIGHT_RPA_SHARED_SCOPE_ID`)或 scope 不符时排程立即 failed(`RPA.WORKER_OFFLINE`),不再空等 `FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS`(默认 900 秒)超时回收。上线后仍应按 `1.9.4` 验收并保留 `data\freight_rpa\inbound\logs\worker.log` 巡检。 +排程创建:管理端「排程管理」新增平台任务 **货代入站 RPA**(`freight-rpa-inbound`),可选参数 `source_codes` 留空则执行全部已启用站点中已配置入站的站点,按需配置 Cron 与接收人。入站排程与库存排程相互独立(站点、Cron、接收人分别选择)。入站触发前执行**与库存同口径**的 Worker 在线 fail-fast 检查(`assert_inbound_rpa_worker_ready`:心跳 TTL + 入站 trigger 目录哨兵 + scope 匹配,2026-09-30 起对齐):Worker 离线、哨兵缺失(含漏配 `FREIGHT_RPA_SHARED_SCOPE_ID`)或 scope 不符时排程立即 failed(`RPA.WORKER_OFFLINE`),不再空等 `FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS`(默认 900 秒)超时回收。上线后仍应按 `1.9.4` 验收并保留 `data\freight_rpa\inbound\logs\worker.log` 巡检。 #### 1.9.4 端到端验证 @@ -3081,7 +3081,7 @@ FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS=900 - Worker 领取后文件进入同目录 `processing/`,全部单元处理完进入 `processed/`(契约级失败进 `failed/`); - inbound drop 出现 `inbound_{run}_{source}_{wh}_{stamp}.xlsx`; - 回调 `/api/freight-rpa/inbound-batch-ready` 成功,单元 `success`,MinIO 出现归档对象; - - 接收人企微一次性收到 textcard 汇总与全部收料文件消息(与库存排程同一出口),工作台「收料文件」可查看并下载。 + - 接收人企微一次性收到 textcard 汇总与原始入站包(与库存排程同一出口);排程管理执行记录可下载 `inbound-raw-zip`(企微深链 `raw_zip=1` 时突出下载入口)。 4. 失败路径:制造一个失败单元(如停用对应 RPA Profile),确认排程终态 `failed` / `partial_failed`、管理端失败单元可查、带原因重试生成新单元且以 `retry_of_id` 关联旧单元;通知重发不触发重新导出。 5. 隔离确认:收料文件不出现在 `onhand drop`,不产生任何 `ShippingOnhandFile` / 库存快照 / 库存匹配记录。 @@ -3124,6 +3124,85 @@ python scripts/freight_rpa/inbound/inbound_rpa_worker.py 真实本地导出(`MOCK=false`)还需受控注入 `FREIGHT_RPA_CREDENTIAL_KEY` 并设置 `FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR`;排程下发的真实 trigger 均含加密凭据,Mock 消费真实 trigger 时同样需要该密钥。也可改用启动脚本 `.\scripts\freight_rpa\inbound\start_inbound_worker.ps1 -Environment test -ApiBase "http://127.0.0.1:5052" ...`(需先按 `1.5.10` 生成本地 Secret 文件)。 +### 1.10 出站报表 RPA 共享部署(Windows RPA + Ubuntu 后端) + +> 本节是**出站**(outbound,在途调拨语境)报表 RPA 的部署手册,结构与 `1.9` 入站对称。术语见 `docs/features/freight-rpa/GLOSSARY.md`。**不承载**发货履约「出货」与 upload 域;**无** outbound notification_deliveries、**无**工作台出站文件页(运维走排程 + `outbound-raw-zip` 深链,与入站瘦身一致)。 + +#### 1.10.1 与库存/入站 RPA 的边界和目录规划 + +**与 `1.5` / `1.9` 复用**:同一 Windows RPA 主机、SMB 共享与 Ubuntu 挂载、DPAPI Secret、`FREIGHT_RPA_CREDENTIAL_KEY`、`-ApiBase` 网关口径、trigger 四态契约与 fail-fast(心跳 TTL + trigger 目录哨兵 + `FREIGHT_RPA_SHARED_SCOPE_ID`)。 + +**出站专用**: + +| 项 | 入站 RPA | 出站 RPA | +| --- | --- | --- | +| Worker | `inbound\inbound_rpa_worker.py` | `outbound\outbound_rpa_worker.py` | +| 启动脚本 | `inbound\start_inbound_worker.ps1` | `outbound\start_outbound_worker.ps1` | +| trigger / drop | `freight_rpa\inbound\{triggers,drop}` | `freight_rpa\outbound\{triggers,drop}` | +| 回调 | `/api/freight-rpa/inbound-batch-ready` 等 | `/api/freight-rpa/outbound-batch-ready` 等 | +| 心跳身份 | `<主机名>-inbound` | `<主机名>-outbound` | +| 事实分发 | `report_kind=inbound` | `report_kind=outbound` → `handle_outbound_report` | +| 排程 | `freight-rpa-inbound` | `freight-rpa-outbound`(归档清理 `freight-rpa-outbound-retention`) | + +路径示例(test;prod 换 `prod-data` / `HxopsRpaProd`): + +```text +Windows:C:\HxopsRpaTest\data\freight_rpa\outbound\triggers +Ubuntu:/mnt/hxops-rpa-test-data/freight_rpa/outbound/triggers + +Windows:C:\HxopsRpaTest\data\freight_rpa\outbound\drop +Ubuntu:/mnt/hxops-rpa-test-data/freight_rpa/outbound/drop +``` + +Crane 出站固定 **Outbound Details**;DBS 路径/查询与入站同构(日期不得出现在查询条件)。回调 `file_path` **只认 drop 根内文件名**(跨机 Windows 绝对路径须在后端取 `.name` 再拼 `FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR`)。 + +#### 1.10.2 Windows:部署出站 Worker + +目录初始化(与入站并列,不共用 trigger/drop/logs): + +```powershell +foreach ($root in @("C:\HxopsRpaTest", "C:\HxopsRpaProd")) { + New-Item -ItemType Directory -Force "$root\data\freight_rpa\outbound\triggers" + New-Item -ItemType Directory -Force "$root\data\freight_rpa\outbound\drop" + New-Item -ItemType Directory -Force "$root\data\freight_rpa\outbound\logs" +} +``` + +须同步**整个** `scripts\freight_rpa`(含 `outbound/`、`inbound/`、`onhand/`、`connectors/`、`common/`)。启动示例: + +```powershell +powershell.exe -NoProfile -ExecutionPolicy Bypass -File ` + "C:\HxopsRpaTest\scripts\freight_rpa\outbound\start_outbound_worker.ps1" ` + -Environment test ` + -ApiBase "http://:<端口>" ` + -WorkerRoot "C:\HxopsRpaTest" ` + -SecretFile "C:\HxopsRpaSecrets\test.xml" +``` + +常驻任务脚本:`scripts\freight_rpa\outbound\register_outbound_worker_tasks.ps1`(与入站/库存任务并存)。日志默认 `data\freight_rpa\outbound\logs\worker.log`。 + +#### 1.10.3 Ubuntu 后端:环境变量与排程 + +`.env.test` / `.env.prod` 在入站变量旁追加(路径与 Windows 同一 SMB 子树): + +```env +FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/outbound/triggers +FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/outbound/drop +FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/outbound/archives +# 可选;默认 900,超时回收 RPA.OUTBOUND_CALLBACK_TIMEOUT,不自动重试 +FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS=900 +``` + +> ⚠️ 漏配 `FREIGHT_RPA_SHARED_OUTBOUND_*` 时后端会写容器本地 `data/freight_rpa/outbound/*`,Windows Worker 看不到 trigger。 + +排程:平台任务 **货代出站 RPA**(`freight-rpa-outbound`),参数 `source_codes` 可选;写 trigger 前 `assert_outbound_rpa_worker_ready` fail-fast。归档到期清理注册 **货代出站归档到期清理**(`freight-rpa-outbound-retention`)。在途调拨缺出站文件时可按需触发同一出站 RPA(与入站 trigger 对称,来源隔离)。 + +#### 1.10.4 端到端验证(摘要) + +1. 管理端「来源站点」配置**出站报表**与 published `purpose=outbound` 解析绑定;DBS/Crane 约束同 API(`SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID` / `SHIPPING.OUTBOUND_PROFILE_INVALID`)。 +2. `-Mock` 启动出站 Worker → 手工执行 `freight-rpa-outbound` → 确认 trigger 消费、回调、`report_kind=outbound` 事实、MinIO 归档、企微汇总与 `outbound-raw-zip` 下载。 +3. 失败单元:排程管理带原因重试(`SHIPPING.OUTBOUND_RETRY_REASON_REQUIRED`);回调文件/sha 类错误见四语言 `SHIPPING.OUTBOUND_CALLBACK_*` / `RPA.OUTBOUND_*`。 + *** ## 2. Dify 手工配置边界 diff --git a/docs/funclist.md b/docs/funclist.md index 2560820d..bc81a4e4 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -731,7 +731,8 @@ | 功能项 | 状态 | 说明 | | ------------------------------ | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| 货代收料 RPA 后端与独立 Worker | 已实现(待测试环境联调) | 独立排程、原子 trigger、callback 超时回收、DBS Warehouse 拆分、Crane 强制 `#/inbound-details-query` 后按页面默认条件导出 Inbound Details、归档、企微、管理员失败单元补偿、接收人授权下载及完整审计已实现;写 trigger 前与库存同口径 fail-fast 就绪检查(心跳+哨兵+scope,部署侧由 `start_inbound_worker.ps1` 注入 `FREIGHT_RPA_SHARED_SCOPE_ID`);库存 Worker 和链路未改动。 | +| 货代入站 RPA 后端与独立 Worker | 已实现(待测试环境联调) | 独立排程 `freight-rpa-inbound`、原子 trigger、callback 超时回收、DBS Warehouse 拆分、Crane 强制 `#/inbound-details-query` 后按页面默认条件导出 Inbound Details、归档、企微、管理员失败单元补偿、排程 `inbound-raw-zip` 深链下载及完整审计;已删除 deliveries 表与「重发企微」、下线工作台收料文件页;写 trigger 前与库存同口径 fail-fast 就绪检查(心跳+哨兵+scope,部署侧由 `start_inbound_worker.ps1` 注入 `FREIGHT_RPA_SHARED_SCOPE_ID`)。 | +| 货代出站 RPA 后端与独立 Worker | 已实现(待测试环境联调) | 镜像入站:配置/unit/file 三表、排程 `freight-rpa-outbound` 与 `freight-rpa-outbound-retention`、trigger schema `freight_rpa.outbound.v1`、回调 `outbound-*`、MinIO 归档、`report_kind=outbound` → `handle_outbound_report` 在途按需触发;无 notification_deliveries、无工作台出站文件页;运维走排程管理与 `outbound-raw-zip`。 | | 功能项 | 状态 | 说明 | | ------------------------- | ------ | ------------------------------------------------------------------------------------------------------------- | @@ -810,7 +811,7 @@ | 排程/恢复/异常/通知 | 后端已实现 | 08:00 入站文件与 09:00 自动调拨(现注册表单列 `in-transit-transfer` platform job,缺当日入站文件自动触发收料 RPA);任务参数=来源实例/历史可恢复异常复核/可选异动日期起止(T-N 偏移天数,执行日换算,测试/排障缩小匹配面;留空=全部积压;非法偏移快速失败,越界由匹配层卡控截止≤业务日期);待处理池 3/5/7 天老化;人工重试/关闭;七 Sheet 异常 Excel;执行结果通知统一走排程「启用通知」通用执行结果通知(空数据日静默,失败不改 ERP 结果;2026-10-12 移除任务级通知人参数) | | 调拨类型配置化(2026-10-14) | 已实现 | 类型来自平台配置表 `transfer_type_configs`(ADR 0002,代码枚举/CHECK 约束/前端 union/「即将上线」占位全退役):管理端「在途调拨类型」页四块配置(基本信息/范围规则/仓库定义/字段转换),admin CRUD API + chat enabled 最小暴露 API;`transfer_type` 匹配创建必填(未配置/停用 fail-closed),配置为空前端空态;范围规则引擎(18 字段白名单、规则间 AND 值间 OR、内存谓词+SQL 编译双形态)、仓库定义(mapped/fixed+法人覆盖)、字段转换(批号前缀替换,六个系统边界生效,行/档保原值);规则随匹配快照进 scope_json;管理页见 `features/admin/modules/transfer-types/`,运维手册 technical.md §11 | | 库存异动档与出生翻转(2026-10-14) | 已实现 | 新建 `transfer_movement_ledger`(ADR 0001,外部入站/出站记录唯一镜像):自然键幂等五语义(插入/sha 幂等跳过/证据变原行更新/缺席不删/已执行封存)、record_kind 声明+in_out_flag 交叉校验(矛盾打审计标记照常落档)、D13 业务字段+出站预留列、档级封存回写(执行成功 transfer_executed=true 防二次调拨);items 出生翻转=匹配创建时从档圈定建行(matching_id/ledger_record_id 出生即绑定),落地停写 items、重查对档对账、scope_item_query 退役;D17 圈档互斥(一条档记录一生一次绑定,取消释放/终态不释放) | -| 入站/出站统一改版与幂等修复(2026-10-15) | 已实现 | record_kind 枚举值改版 inbound/outbound(迁移 tt14 值迁移);明细/单据列异动口径 `movement_*`(异动日期/数量/仓库列与匹配创建参数 `movement_date_from/to`、序列化键、Excel 表头随行更名,无兼容层);异动档自然键扩为 8 成分(+箱号/批号,三份真实 WMS 文件实测塌缩归零)+「异动日期非空才落档」过滤(`date_skipped`,未完成/已取消行不入档);解析规则 purpose 三枚举 onhand/inbound/outbound(迁移 tt15 值迁移;outbound 结构就位、出站证据链路未建,fail-closed 天然安全);收料配置绑定校验改 inbound 专用(`SHIPPING.INBOUND_PROFILE_INVALID`);解析规则退役守卫补查收料配置绑定(防入站解析链静默失去规则);API 路由 `/sources/inbound-files`、`/runs/{run_no}/inbound-files` 与错误码/审计事件 inbound 化;设计规格见 [superpowers/specs/2026-10-15-inbound-outbound-idempotency-rename-design.md](superpowers/specs/2026-10-15-inbound-outbound-idempotency-rename-design.md),运维手册 technical.md §12 | +| 入站/出站统一改版与幂等修复(2026-10-15) | 已实现 | record_kind 枚举值改版 inbound/outbound(迁移 tt14 值迁移);明细/单据列异动口径 `movement_*`(异动日期/数量/仓库列与匹配创建参数 `movement_date_from/to`、序列化键、Excel 表头随行更名,无兼容层);异动档自然键扩为 8 成分(+箱号/批号,三份真实 WMS 文件实测塌缩归零)+「异动日期非空才落档」过滤(`date_skipped`,未完成/已取消行不入档);解析规则 purpose 三枚举 onhand/inbound/outbound(迁移 tt15 值迁移);入站配置绑定校验 inbound 专用(`SHIPPING.INBOUND_PROFILE_INVALID`),出站绑定 `SHIPPING.OUTBOUND_PROFILE_INVALID`(2026-10-19 出站全栈);解析规则退役守卫补查入站/出站配置绑定;API 路由 `/sources/inbound-files`、`/runs/{run_no}/inbound-files` 与错误码/审计事件 inbound 化;出站 RPA 与调拨 sink 见 [superpowers/specs/2026-10-19-freight-rpa-outbound-and-rename-design.md](superpowers/specs/2026-10-19-freight-rpa-outbound-and-rename-design.md);2026-10-15 设计见 [superpowers/specs/2026-10-15-inbound-outbound-idempotency-rename-design.md](superpowers/specs/2026-10-15-inbound-outbound-idempotency-rename-design.md),运维手册 technical.md §12 | | 待匹配桶清空并重新解析(2026-10-15) | 已实现 | 解析规则修改后的存量档行重建入口:`GET /backlog/pending-match/reparse-preview` 预检(可重建归档文件清单/份数、将用规则 code+version、将清除行数、证据缺失保留行数)+ `POST /backlog/pending-match/reparse` 执行(单事务:先全量重解析归档文件,任一失败 400 `TRANSFER.REPARSE_PARSE_FAILED` 一行不删;删除可重建/未封存/未被有效 items 占用行后按当前模板幂等重落,8 成分键与异动日期过滤自动生效);审计 `TRANSFER_PENDING_MATCH_REPARSED`(操作人/来源/文件清单/规则版本/前后计数) | | 首页待匹配桶与 file_current 改锚(2026-10-14) | 已实现 | 待办看板新增「待匹配」桶(已落档但从未匹配的外部记录只读可见+去匹配引导,不可勾选执行),四队列卡数据源改档+最近执行状态联查;file_current 门禁改锚档记录 file_version(==来源最新可用文件 sha 即当前) | | 生产硬化 | 后端已实现 | MinIO 归档+Hash 复核;Worker 崩溃/陈旧执行恢复;运营指标;越权 403;下载访问审计;性能测试;运维手册 docs/features/in-transit-transfer/technical.md | @@ -844,5 +845,6 @@ | 调拨 query_inventory 接线 | 后端已实现 | `services/in_transit_transfer/gateway_adapter.py` 把 ERP 访问收敛到 gateway(P1 用默认绑定,来源专属绑定待 P2/P3) | | 配置作业 UI / MCP / Dify 暴露 / RPA/SQL 传输 | 待实施 | 属 P2/P3(AI 只暴露 Capability;RPA 为独立异步 Transport) | | 入站解析规则(标准字段目录 + 解析类型) | 后端+管理端已实现 | purpose 三枚举 onhand/inbound/outbound(2026-10-15 由两值旧枚举改版,迁移 tt15 值迁移);purpose='inbound' 解析规则创建/发布;`GET /api/admin/shipping-notice/movement-fields` 只读目录(10 定死字段,禁自定义);movement 映射表单(前端 `admin/shipping-notice` 解析模块) | -| 收料配置绑定入站解析规则 | 后端+管理端已实现 | 收料配置保存/回显 `parsing_profile_id`(校验 published+purpose='inbound',`SHIPPING.INBOUND_PROFILE_INVALID`);抽屉绑定选择器;审计快照含绑定 | -| 预检未绑入站规则守卫 | 后端已实现 | 收料配置存在但未绑已发布 inbound 规则 → `RPA_INBOUND_PROFILE_MISSING`,fail-closed 不触发徒劳抓取 | +| 入站报表配置绑定入站解析规则 | 后端+管理端已实现 | 入站配置保存/回显 `parsing_profile_id`(校验 published+purpose='inbound',`SHIPPING.INBOUND_PROFILE_INVALID`);抽屉绑定选择器;审计快照含绑定 | +| 出站报表配置绑定出站解析规则 | 后端+管理端已实现 | 出站配置保存/回显 `parsing_profile_id`(校验 published+purpose='outbound',`SHIPPING.OUTBOUND_PROFILE_INVALID`);与入站同构路径/查询/绑定 UI | +| 预检未绑入站规则守卫 | 后端已实现 | 入站配置存在但未绑已发布 inbound 规则 → `RPA_INBOUND_PROFILE_MISSING`,fail-closed 不触发徒劳抓取 | diff --git a/docs/superpowers/plans/2026-10-19-freight-rpa-outbound-and-rename.md b/docs/superpowers/plans/2026-10-19-freight-rpa-outbound-and-rename.md new file mode 100644 index 00000000..01619192 --- /dev/null +++ b/docs/superpowers/plans/2026-10-19-freight-rpa-outbound-and-rename.md @@ -0,0 +1,737 @@ +# 货代 RPA:报表规则改名 + 出站全栈 + 入站运维瘦身 Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** 管理端改名为「报表规则 / 来源站点 / 入站报表」,交付与入站同构的出站 RPA 全栈,并拆除入站 deliveries 与工作台收料文件页。 + +**Architecture:** 做法 A——按入站包逐文件克隆出站(models / trigger_io / report_archive / schedule job / Worker / 调拨 trigger / sink),不先做泛化层。改名与入站瘦身穿插在前序任务,降低出站联调噪声。`purpose=outbound` 校验改走 `MOVEMENT_FIELDS`。通知只走排程 `notify_user_ids`。 + +**Tech Stack:** Flask、SQLAlchemy 2.0、Alembic、Vue 3、pytest、Playwright Worker(Python)。后端测试工作目录 `backend/`;Windows 上 Python 用 `backend/.venv/Scripts/python.exe`(若无则用已激活的 venv)。 + +**Spec:** `docs/superpowers/specs/2026-10-19-freight-rpa-outbound-and-rename-design.md` + +## Global Constraints + +- 入口文案:`库存解析` → **报表规则**;`库存站点` → **来源站点**;`收料报表配置` → **入站报表配置**。父级「库存管理」、库存字段目录不改。 +- 出站类名一律 `FreightRpaOutbound*`;假定 class-prefix 已合入(`FreightRpaSource` 等)。禁止引入 `Shipping*Outbound*`。 +- 出站新建三表:`freight_rpa_outbound_report_configs` / `freight_rpa_outbound_rpa_unit_runs` / `freight_rpa_outbound_report_files`。**禁止**建 `*_notification_deliveries`。 +- 删除 `freight_rpa_inbound_notification_deliveries` 及 resend / 工作台收料页 / `inbound_report_access`。 +- `receipt-raw-zip` → `inbound-raw-zip`(路径与深链参数),无兼容别名。 +- 出站配置非启用硬门槛;触发时站点停用/缺配置 fail-closed。 +- `purpose=outbound` 与 inbound 同异动契约;旧 onhand 形态 outbound 草稿不自动迁移。 +- RPA 层不强制 `in_out_flag`;方向过滤留在调拨域。 +- 不改履约出货 / upload;不新建工作台出站文件页。 +- 四语言 i18n 同步;错误码新增须写 `locales/*/errors.json`。 +- 改函数签名或模块协作时同步文件头与函数注释(AGENTS.md §5)。 +- 禁止 `git add -A` / `git commit`;每任务只 stage 该任务列出的路径。工作区可能已有未提交的其它批次,勿混入。 +- **跨机路径(硬约束)**:出站回调 `file_path` 只按「outbound drop 根内文件名」解析。后端必须 `replace('\\','/')` 后取 `.name`,再拼 `FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR`,`relative_to(root)` 防穿越。禁止把 Windows 绝对路径当 Linux 路径打开。对照入站 `_read_inbound_callback_file` 与在手 `resolve_shared_inventory_drop_file`。Worker 侧优先只上报文件名。必须有带 `C:\\...\\foo.xlsx` 的回归测。 + +## 文件地图 + +| 文件 / 目录 | 职责 | +| --- | --- | +| `frontend/src/locales/{zh-CN,zh-TW,en,th}/admin.json` 等 | 报表规则 / 来源站点 / 入站·出站报表文案 | +| `frontend/src/features/admin/modules/freight-rpa/*` | 来源站点三块配置、报表规则 purpose=outbound UI | +| `frontend/src/features/workspace/**`(收料页相关) | 删除 | +| `backend/app/models/freight_rpa_outbound_report.py` | 出站三模型(新建) | +| `backend/app/models/freight_rpa_inbound_report.py` | 去掉 NotificationDelivery | +| `backend/migrations/versions/*_freight_rpa_outbound_and_inbound_slim.py` | 出站建表 + drop deliveries | +| `backend/app/services/shipping_notice/onhand_parsing_profile.py` | outbound → 异动校验 | +| `backend/app/services/admin/shipping_onhand_admin_service.py` | `get_/save_inbound_*` + `get_/save_outbound_*` | +| `backend/app/services/freight_rpa/outbound/*` | trigger_io、report_archive | +| `backend/app/services/schedule/freight_rpa_outbound_*.py` | job / finalize / archive / retention | +| `backend/app/api/freight_rpa.py` | outbound 回调路由 | +| `backend/app/api/schedule/runs.py` | inbound-raw-zip、outbound-raw-zip、outbound units | +| `backend/app/services/in_transit_transfer/outbound_trigger_service.py` | 按需触发 | +| `backend/app/services/in_transit_transfer/outbound_report_handler.py` | sink handler | +| `backend/app/services/shipping_notice/rpa_sinks.py` | `register_outbound_sinks` | +| `scripts/freight_rpa/outbound/*` | Worker / ps1 / 驱动 | +| `docs/features/freight-rpa/GLOSSARY.md` 等 | 术语与运维文档 | + +--- + +### Task 1: 管理端改名(报表规则 / 来源站点 / 入站报表) + +**Files:** +- Modify: `frontend/src/locales/zh-CN/admin.json` +- Modify: `frontend/src/locales/zh-TW/admin.json` +- Modify: `frontend/src/locales/en/admin.json` +- Modify: `frontend/src/locales/th/admin.json` +- Modify: `frontend/src/features/admin/shippingConfigNavigation.spec.ts`(若断言旧文案) +- Modify: `frontend/src/features/admin/modules/freight-rpa/FreightRpaPage.vue`(仅当硬编码「收料」时) +- Modify: `frontend/src/features/admin/modules/freight-rpa/receiptReportConfigForm.ts` → 重命名文件为 `inboundReportConfigForm.ts`,并改导出函数名 +- Modify: 所有 import 上述 form 的文件(`FreightRpaPage.vue`、`*.spec.ts`) +- Test: `frontend/src/features/admin/modules/freight-rpa/receiptReportConfigForm.spec.ts` → `inboundReportConfigForm.spec.ts` + +**Interfaces:** +- Consumes: 现有 i18n 键 `admin.freightRpa.parsingProfiles`、`sources`、`receiptReportConfig*` +- Produces: 用户可见字符串变更;键名可将 `receiptReportConfig` 改为 `inboundReportConfig`(四语言同步改键,调用处同步);`buildInboundReportConfigPayload` 替代 `buildReceiptReportConfigPayload` + +- [ ] **Step 1: 写失败的导航/文案断言(若已有 spec 则改期望)** + +在 `shippingConfigNavigation.spec.ts` 或新建窄测中断言 labelKey 对应文案解析后为「报表规则」「来源站点」(用 i18n 或直接断言 key 不变、另测 locale 文件内容)。 + +最小 locale 断言脚本(Node,在 `frontend/`): + +```js +const zh = require('./src/locales/zh-CN/admin.json'); +if (zh.freightRpa.parsingProfiles !== '报表规则') throw new Error('parsingProfiles'); +if (zh.freightRpa.sources !== '来源站点') throw new Error('sources'); +if ((zh.freightRpa.inboundReportConfig || zh.freightRpa.receiptReportConfig) !== '入站报表配置') { + throw new Error('inboundReportConfig'); +} +``` + +先跑应失败(当前为库存解析/库存站点/收料报表配置)。 + +- [ ] **Step 2: 改四语言文案与键** + +zh-CN 最低改动示例: + +```json +"parsingProfiles": "报表规则", +"parsingProfilesHelp": "维护可辨识的文件解析规则:库存面向字段目录与订单匹配,入站/出站面向标准异动字段(只读契约)。", +"sources": "来源站点", +"inventorySites": "来源站点", +"inboundReportConfig": "入站报表配置", +"inboundReportConfigHint": "与库存配置同构:报表路径 + 查询条件。查询条件可选,空则使用页面默认;排程按站点一对一导出。入站无独立开关,随站点统一启停。", +"outboundReportConfig": "出站报表配置", +"outboundReportConfigHint": "与入站配置同构:报表路径 + 查询条件;出站无独立开关,随站点统一启停。" +``` + +删除或停止使用 `receiptReportConfig*` 键。zh-TW / en / th 同步语义(en: Report Rules / Source Sites / Inbound Report Config / Outbound Report Config)。 + +同步 `parsingPurposeHint` 等仍写「仅入站」的句子,改为「入站/出站」。 + +- [ ] **Step 3: 重命名前端 form 模块** + +`buildReceiptReportConfigPayload` → `buildInboundReportConfigPayload`;文件改名;`FreightRpaPage.vue` 中 `receiptConfig` 展示文案键改为 `inboundReportConfig*`(状态变量可暂留,Task 6/11 再统一)。 + +- [ ] **Step 4: 跑前端相关测试** + +Run: `cd frontend && npx vitest run src/features/admin/modules/freight-rpa/inboundReportConfigForm.spec.ts src/features/admin/shippingConfigNavigation.spec.ts` +Expected: PASS + +- [ ] **Step 5: Stage** + +```bash +git add frontend/src/locales/zh-CN/admin.json frontend/src/locales/zh-TW/admin.json frontend/src/locales/en/admin.json frontend/src/locales/th/admin.json frontend/src/features/admin/modules/freight-rpa/inboundReportConfigForm.ts frontend/src/features/admin/modules/freight-rpa/inboundReportConfigForm.spec.ts frontend/src/features/admin/modules/freight-rpa/FreightRpaPage.vue frontend/src/features/admin/shippingConfigNavigation.spec.ts +``` + +(含删除旧 `receiptReportConfigForm*` 的 staged deletion。) + +--- + +### Task 2: 拆除入站 deliveries + 工作台收料页 + +**Files:** +- Modify: `backend/app/models/freight_rpa_inbound_report.py`(删 `FreightRpaInboundNotificationDelivery` 与 relationship) +- Modify: `backend/app/models/__init__.py` +- Modify: `backend/app/services/freight_rpa/inbound/report_archive.py`(删 `deliver_inbound_file`、`_recipient_ids` 及 WeCom 投递 import) +- Modify: `backend/app/api/schedule/runs.py`(删 resend 路由) +- Delete: `backend/app/services/shipping_notice/inbound_report_access.py` +- Modify: `backend/app/api/workspace/shipping_notice.py`(删 list/download inbound-report-files 两路由) +- Delete: `frontend/src/features/workspace/pages/InboundReportFilesPage.vue` 及其 `.spec.ts` +- Delete: `frontend/src/features/workspace/api/inbound-report.api.ts` 及其 `.spec.ts`(若仅服务该页) +- Modify: `frontend/src/app/router/routes/workspace.routes.ts` +- Modify: `frontend/src/features/workspace/components/WorkspaceSidebar.vue` +- Modify: `frontend/src/features/workspace/constants/routes.ts` +- Modify: `frontend/src/features/workspace/composables/useWorkspaceNavigation.ts` +- Modify: 四语言 `workspace` locale(去掉 `inboundReports` / nav 项) +- Delete or rewrite: `backend/tests/test_freight_receipt_rpa_notifications.py`、`test_freight_receipt_rpa_access.py`(去掉 deliveries/resend/workspace 断言) +- Create: `backend/migrations/versions/_drop_inbound_notification_deliveries.py`(可与 Task 4 合并为一迁移;若拆分则本任务只 drop) +- Test: 新建 `backend/tests/test_freight_rpa_inbound_slim_gate.py` + +**Interfaces:** +- Consumes: 无 +- Produces: 无 `FreightRpaInboundNotificationDelivery`;无 resend API;无 workspace 收料路由 + +- [ ] **Step 1: 写 grep gate 失败用例** + +```python +# backend/tests/test_freight_rpa_inbound_slim_gate.py +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] + + +def test_no_inbound_notification_delivery_symbol(): + hits = [] + for path in (ROOT / "app").rglob("*.py"): + text = path.read_text(encoding="utf-8") + if "InboundNotificationDelivery" in text or "deliver_inbound_file" in text: + hits.append(str(path)) + assert hits == [] + + +def test_no_workspace_inbound_report_routes(): + text = (ROOT / "app/api/workspace/shipping_notice.py").read_text(encoding="utf-8") + assert "inbound-report-files" not in text +``` + +Run: `pytest tests/test_freight_rpa_inbound_slim_gate.py -v` +Expected: FAIL + +- [ ] **Step 2: 删模型、服务、API、前端页与测试中的引用** + +按 Files 列表删除/改写。`report_archive.py` 文件头 docstring 去掉投递职责。迁移 `op.drop_table('freight_rpa_inbound_notification_deliveries')`(downgrade 可重建最小表结构或 `pass` 并在注释标明不可逆——推荐完整 rebuild 以便本地 downgrade)。 + +- [ ] **Step 3: 再跑 gate + 受影响测试** + +Run: `pytest tests/test_freight_rpa_inbound_slim_gate.py tests/test_freight_receipt_rpa_notifications.py tests/test_freight_receipt_rpa_access.py -v` +Expected: gate PASS;旧测文件已删或改写后 PASS + +- [ ] **Step 4: Stage 本任务路径** + +```bash +git add backend/app/models/freight_rpa_inbound_report.py backend/app/models/__init__.py backend/app/services/freight_rpa/inbound/report_archive.py backend/app/api/schedule/runs.py backend/app/api/workspace/shipping_notice.py backend/migrations/versions/ backend/tests/test_freight_rpa_inbound_slim_gate.py frontend/src/app/router/routes/workspace.routes.ts frontend/src/features/workspace/ +``` + +--- + +### Task 3: `receipt-raw-zip` → `inbound-raw-zip` + +**Files:** +- Modify: `backend/app/api/schedule/runs.py`(路由与函数名) +- Modify: `backend/app/services/schedule/freight_rpa_inbound_archive.py`(`receipt_raw_zip_*` → `inbound_raw_zip_*` 函数名) +- Modify: `backend/app/services/schedule/scheduler_service.py`(深链 `download=inbound_raw_zip`) +- Modify: `backend/app/services/schedule/query_service.py`(summary 字段 `inbound_raw_zip_available`) +- Modify: `frontend/src/features/admin/api/schedule.api.ts` +- Modify: `frontend/src/features/admin/modules/schedules/**`(文案与 query 参数) +- Modify: 四语言 `admin.json` 中 downloadReceipt* → downloadInbound* +- Test: 既有 receipt zip 相关测改断言 + +**Interfaces:** +- Consumes: `resolve_receipt_raw_zip_download`(旧) +- Produces: `resolve_inbound_raw_zip_download(run) -> tuple[Path, str]`;路由 `GET /api/admin/schedule-runs//inbound-raw-zip`;深链 `download=inbound_raw_zip` + +- [ ] **Step 1: 改后端路由与函数名,更新调用方** + +路由: + +```python +@schedule_admin_bp.route('/schedule-runs//inbound-raw-zip', methods=['GET']) +@require_admin +def get_schedule_run_inbound_raw_zip(run_id: int): + """下载入站 RPA 排程 run 的原始入站 Excel 打包(ZIP + manifest)。""" + ... +``` + +禁止保留 `receipt-raw-zip` 路由。 + +- [ ] **Step 2: 改前端 API 与深链** + +```ts +export const scheduleRunInboundRawZipUrl = (runId: number) => + `/api/admin/schedule-runs/${runId}/inbound-raw-zip`; +``` + +`useScheduleAdminDeepLink`:`downloadKind === 'inbound_raw_zip'`。 + +- [ ] **Step 3: 跑相关测试** + +Run: `pytest tests/ -k "inbound_raw_zip or receipt_raw_zip" -v` +Expected: 无 receipt_raw_zip 残留失败;新名 PASS + +- [ ] **Step 4: Stage** + +```bash +git add backend/app/api/schedule/runs.py backend/app/services/schedule/freight_rpa_inbound_archive.py backend/app/services/schedule/scheduler_service.py backend/app/services/schedule/query_service.py frontend/src/features/admin/api/schedule.api.ts frontend/src/features/admin/modules/schedules frontend/src/locales +``` + +--- + +### Task 4: 出站模型 + Alembic 迁移 + +**Files:** +- Create: `backend/app/models/freight_rpa_outbound_report.py` +- Modify: `backend/app/models/freight_rpa_config.py`(`FreightRpaSource.outbound_report_config` relationship) +- Modify: `backend/app/models/__init__.py` +- Create/Modify: Alembic revision(建三表;若 Task 2 未 drop deliveries 则本迁移一并 drop) +- Test: `backend/tests/test_freight_rpa_outbound_models.py` + +**Interfaces:** +- Consumes: `FreightRpaSource`、`FreightRpaParsingProfile` +- Produces: `FreightRpaOutboundReportConfig` / `UnitRun` / `ReportFile`;表名见 Global Constraints + +- [ ] **Step 1: 写模型存在性测试** + +```python +from app.models import FreightRpaOutboundReportConfig, FreightRpaOutboundUnitRun, FreightRpaOutboundReportFile + +def test_outbound_model_tablenames(): + assert FreightRpaOutboundReportConfig.__tablename__ == "freight_rpa_outbound_report_configs" + assert FreightRpaOutboundUnitRun.__tablename__ == "freight_rpa_outbound_rpa_unit_runs" + assert FreightRpaOutboundReportFile.__tablename__ == "freight_rpa_outbound_report_files" +``` + +Expected FAIL(未建类) + +- [ ] **Step 2: 复制入站模型文件并改名** + +以 `freight_rpa_inbound_report.py` 为模板新建 outbound 文件: + +- 类/表/约束名全面 `Inbound`→`Outbound`、`inbound`→`outbound` +- **不要**复制 NotificationDelivery +- 文件头 docstring 写清出站职责;注释去掉「收料」 +- `FreightRpaSource`:`outbound_report_config = relationship(..., uselist=False, back_populates='source')` + +- [ ] **Step 3: 生成并手审迁移** + +Run: `flask db migrate -m "freight_rpa outbound tables and drop inbound notification deliveries"` +手审:仅目标三表 create + deliveries drop;无无关 drop。 + +Run: `flask db upgrade` +Expected: OK + +- [ ] **Step 4: 跑模型测** + +Run: `pytest tests/test_freight_rpa_outbound_models.py -v` +Expected: PASS + +- [ ] **Step 5: Stage** + +```bash +git add backend/app/models/freight_rpa_outbound_report.py backend/app/models/freight_rpa_config.py backend/app/models/__init__.py backend/migrations/versions/ backend/tests/test_freight_rpa_outbound_models.py +``` + +--- + +### Task 5: `purpose=outbound` 改走异动校验 + +**Files:** +- Modify: `backend/app/services/shipping_notice/onhand_parsing_profile.py` +- Modify: `backend/tests/test_parsing_profile_purpose.py` +- Modify: `frontend/src/features/admin/modules/freight-rpa/FreightRpaPage.vue`(`parsing.purpose === 'inbound'` 判断扩展为 inbound|outbound 共用异动 UI) +- Modify: `frontend/src/features/admin/modules/freight-rpa/movementParsingProfileForm.ts`(若有 purpose 分支) + +**Interfaces:** +- Consumes: `_validate_definition(..., purpose=)` +- Produces: `purpose in {'inbound','outbound'}` 均走 `_required_movement_field_ids`,`match_keys=[]` + +- [ ] **Step 1: 改测试期望** + +```python +def test_outbound_definition_uses_movement_fields(): + definition = _validate_definition(_inbound_definition(), purpose='outbound') + assert definition['match_keys'] == [] + assert definition['field_mapping']['doc_no'] == '单据编号' + + +def test_outbound_onhand_shaped_definition_rejected(): + """库存目录形态(含 match_keys)在 outbound 下应失败。""" + # 使用现有 onhand 合法定义夹具;expect ValidationError + ... +``` + +文件头注释:删除「onhand/outbound 维持库存字段目录」。 + +Run: `pytest tests/test_parsing_profile_purpose.py::test_outbound_definition_uses_movement_fields -v` +Expected: FAIL + +- [ ] **Step 2: 改校验分支** + +```python + if purpose in {'inbound', 'outbound'}: + _required_movement_field_ids(raw) + return { + 'sheet_name': str(raw.get('sheet_name') or '').strip() or None, + 'header_row_index': header_row_index, + 'field_mapping': {str(key).strip(): str(value).strip() for key, value in field_mapping.items()}, + 'match_keys': [], + } +``` + +同步所有 `purpose == 'inbound'` 的文档字符串与 `purpose != 'inbound'` 的前端条件 → `purpose === 'onhand'` 才走库存目录 UI。 + +站点绑定过滤: + +- 库存报表:`purpose === 'onhand'`(不要再用 `!== 'inbound'`,以免 outbound 混入) +- 入站:`purpose === 'inbound'` +- 出站:`purpose === 'outbound'` + +- [ ] **Step 3: 跑测试** + +Run: `pytest tests/test_parsing_profile_purpose.py -v` +Expected: PASS + +- [ ] **Step 4: Stage** + +```bash +git add backend/app/services/shipping_notice/onhand_parsing_profile.py backend/tests/test_parsing_profile_purpose.py frontend/src/features/admin/modules/freight-rpa/FreightRpaPage.vue frontend/src/features/admin/modules/freight-rpa/movementParsingProfileForm.ts +``` + +--- + +### Task 6: 出站报表配置 Admin API + receipt→inbound 服务符号 + +**Files:** +- Modify: `backend/app/services/admin/shipping_onhand_admin_service.py` +- Modify: `backend/app/api/admin_freight_rpa.py` +- Modify: `frontend/src/features/admin/api/admin.api.ts` +- Create: `frontend/src/features/admin/modules/freight-rpa/outboundReportConfigForm.ts`(镜像 inbound form) +- Test: `backend/tests/test_freight_rpa_outbound_report_config_api.py` + +**Interfaces:** +- Consumes: `FreightRpaOutboundReportConfig` +- Produces: + - `get_inbound_report_config(source_id) -> dict | None`(由 `get_receipt_report_config` 改名) + - `save_inbound_report_config(source_id, data, *, actor_id) -> dict` + - `get_outbound_report_config(source_id) -> dict | None` + - `save_outbound_report_config(source_id, data, *, actor_id) -> dict` + - 路由 `GET/PUT /api/admin/freight-rpa/sources//outbound-report-config` + - 载荷键:`parsing_profile_id`、`report_path_json`、`query_parameters_json`(与入站相同) + +- [ ] **Step 1: API 契约测试(失败)** + +```python +def test_put_outbound_report_config_requires_outbound_profile(client, admin_headers, source_id, onhand_profile_id): + resp = client.put( + f"/api/admin/freight-rpa/sources/{source_id}/outbound-report-config", + json={"parsing_profile_id": onhand_profile_id, "report_path_json": {}, "query_parameters_json": []}, + headers=admin_headers, + ) + assert resp.status_code in (400, 422) +``` + +- [ ] **Step 2: 实现服务与路由** + +校验:`parsing_profile.purpose == 'outbound' and status == 'published'`(或允许草稿绑定策略与入站现行一致——**逐行对照** `_validate_receipt_report_config` 后改名为 `_validate_inbound_report_config`,再复制为 `_validate_outbound_report_config` 只改 purpose)。 + +重命名所有 `receipt_report_config` 服务函数与事件名中的 receipt→inbound(审计 `event_type` 若已有历史,新事件用 `shipping_outbound_report_config_saved` / `freight_rpa_inbound_report_config_saved`,不强制改历史事件字符串除非测试锁死)。 + +- [ ] **Step 3: 前端 API** + +```ts +export const getOutboundReportConfig = (sourceId: number) => + requestJson(`/api/admin/freight-rpa/sources/${sourceId}/outbound-report-config`); +export const saveOutboundReportConfig = (sourceId: number, body: unknown) => + requestJson(`/api/admin/freight-rpa/sources/${sourceId}/outbound-report-config`, { method: 'PUT', body }); +``` + +- [ ] **Step 4: 跑测** + +Run: `pytest tests/test_freight_rpa_outbound_report_config_api.py -v` +Expected: PASS + +- [ ] **Step 5: Stage 列出文件** + +--- + +### Task 7: 出站 trigger_io + Worker 心跳能力 + +**Files:** +- Create: `backend/app/services/freight_rpa/outbound/__init__.py` +- Create: `backend/app/services/freight_rpa/outbound/trigger_io.py` +- Modify: `backend/app/services/freight_rpa/common/worker_heartbeat.py`(`OUTBOUND_EXPORT_CAPABILITY`、`assert_outbound_rpa_worker_ready`) +- Modify: `scripts/freight_rpa/common/rpa_callbacks.py`(outbound 回调路径常量) +- Test: `backend/tests/services/freight_rpa/test_outbound_trigger_contract.py` + +**Interfaces:** +- Produces: + - `SCHEMA = "freight_rpa.outbound.v1"` + - `ACTION_OUTBOUND_EXPORT_BATCH = "outbound_export_batch"` + - `write_outbound_export_batch_trigger(run_no, units, meta) -> str | None` + - `outbound_trigger_dir()` / `outbound_drop_dir()` 读 `FREIGHT_RPA_SHARED_OUTBOUND_*` + - `OUTBOUND_EXPORT_CAPABILITY = "outbound_export"` + +- [ ] **Step 1: 契约测试** + +```python +from app.services.freight_rpa.outbound import trigger_io +from app.services.freight_rpa.common.worker_heartbeat import OUTBOUND_EXPORT_CAPABILITY + +def test_outbound_trigger_constants(): + assert trigger_io.SCHEMA == "freight_rpa.outbound.v1" + assert trigger_io.ACTION_OUTBOUND_EXPORT_BATCH == "outbound_export_batch" + assert OUTBOUND_EXPORT_CAPABILITY == "outbound_export" +``` + +- [ ] **Step 2: 实现**(逐函数对照 `inbound/trigger_io.py` 与 `assert_receipt_rpa_worker_ready`,符号全部 outbound 化;**禁止**复用 inbound 目录配置键) + +- [ ] **Step 3: 跑测并 stage** + +--- + +### Task 8: 出站排程 job / finalize / archive / retention + 注册 + +**Files:** +- Create: `backend/app/services/schedule/freight_rpa_outbound_job.py` +- Create: `backend/app/services/schedule/freight_rpa_outbound_finalize.py` +- Create: `backend/app/services/schedule/freight_rpa_outbound_archive.py` +- Create: `backend/app/services/schedule/freight_rpa_outbound_retention.py` +- Modify: `backend/app/services/schedule/job_registry.py` +- Modify: `backend/app/services/schedule/__init__.py`(若需注册 excel headers) +- Test: `backend/tests/test_freight_rpa_outbound_job.py` + +**Interfaces:** +- Consumes: `write_outbound_export_batch_trigger`、`assert_outbound_rpa_worker_ready` +- Produces: + - `OUTBOUND_RPA_JOB_KEY = "freight-rpa-outbound"` + - `OUTBOUND_RETENTION_JOB_KEY = "freight-rpa-outbound-retention"` + - `AWAITING_OUTBOUND_RPA_CALLBACK_STATUS = "awaiting_outbound_rpa_callback"` + - 错误码使用 `RPA.OUTBOUND_*`(如 `RPA.OUTBOUND_TRIGGER_UNAVAILABLE`、`RPA.OUTBOUND_CALLBACK_TIMEOUT`),四语言 errors 本任务或 Task 13 补齐 + - 单元表写入 `FreightRpaOutboundUnitRun` + +- [ ] **Step 1: 对照入站 job 写「空 source 列表 fail-closed / worker 离线 failed」测试** + +- [ ] **Step 2: 复制入站四文件并全文替换符号**(`receipt`→`outbound` 语义处改为 outbound;状态串不要沿用 `awaiting_receipt_*`) + +- [ ] **Step 3: `job_registry` 注册两个 platform job** + +- [ ] **Step 4: 跑测并 stage** + +--- + +### Task 9: 出站回调 API + report_archive ingest + +**Files:** +- Create: `backend/app/services/freight_rpa/outbound/report_archive.py` +- Modify: `backend/app/api/freight_rpa.py` +- Modify: `scripts/freight_rpa/common/rpa_callbacks.py`(若 Task 7 未完) +- Test: `backend/tests/test_freight_rpa_outbound_callback.py` +- Optional Create: `backend/app/services/freight_rpa/common/drop_path.py`(若抽取共用「drop 根 + 文件名」解析,供 outbound 使用;抽取时入站可后续再迁,本任务不强制改 inbound) + +**Interfaces:** +- Produces: `ingest_outbound_callback(payload) -> None`;`_read_outbound_callback_file(file_path: str) -> bytes`;路由: + - `POST /api/freight-rpa/outbound-batch-ready` + - `POST /api/freight-rpa/outbound-unit-progress` + - `POST /api/freight-rpa/outbound-batch-progress` +- 归档成功后 `dispatch_report_fact(report_kind='outbound', ...)`(handler 可在 Task 10 注册前用测内临时 register) +- 路径解析语义与入站 `_read_inbound_callback_file` 一致(见 Global Constraints) + +- [ ] **Step 1: 先写跨机路径回归测(必须红)** + +```python +def test_read_outbound_callback_file_accepts_windows_absolute_path(tmp_path, app): + """Worker 上报 C:\\...\\drop\\foo.xlsx 时,Linux 侧只按文件名拼本机 drop 根。""" + drop = tmp_path / "outbound_drop" + drop.mkdir() + target = drop / "foo.xlsx" + target.write_bytes(b"PK\x03\x04fake") + with app.app_context(): + app.config["FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR"] = str(drop) + from app.services.freight_rpa.outbound.report_archive import _read_outbound_callback_file + data = _read_outbound_callback_file(r"C:\HxopsRpaTest\data\freight_rpa\outbound\drop\foo.xlsx") + assert data.startswith(b"PK") + + +def test_read_outbound_callback_file_rejects_traversal(tmp_path, app): + drop = tmp_path / "outbound_drop" + drop.mkdir() + with app.app_context(): + app.config["FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR"] = str(drop) + from app.services.freight_rpa.outbound.report_archive import _read_outbound_callback_file + from app.core.errors import ValidationError + with pytest.raises(ValidationError): + _read_outbound_callback_file(r"..\..\etc\passwd") +``` + +另测:`file_path="foo.xlsx"`(仅文件名)同样成功。 +Run: `pytest tests/test_freight_rpa_outbound_callback.py -k windows_absolute -v` +Expected: FAIL(函数未实现) + +- [ ] **Step 2: 回调 schema 校验失败测试**(错误 schema → 4xx) + +- [ ] **Step 3: 实现 `_read_outbound_callback_file` + archive** + +最小实现(对照入站,**禁止** `Path(file_path).read_bytes()` 直接读回调串): + +```python +def _read_outbound_callback_file(file_path: str) -> bytes: + configured_root = str(outbound_drop_dir() or "").strip() + if not configured_root: + raise ValidationError("outbound callback file root is unavailable", code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID") + root = Path(configured_root).resolve() + name = Path(str(file_path).replace("\\", "/")).name + path = (root / name).resolve() + try: + path.relative_to(root) + except ValueError as exc: + raise ValidationError( + "outbound callback file is outside outbound drop root", + code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID", + ) from exc + if path.suffix.lower() != ".xlsx" or not path.is_file(): + raise ValidationError( + "outbound callback file must be an existing xlsx", + code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID", + ) + ... + return path.read_bytes() +``` + +**不要**移植已删除的 `deliver_inbound_file`。 + +- [ ] **Step 4: 接线路由与鉴权(与入站回调同 ToolApiKey 机制)** + +- [ ] **Step 5: 跑测并 stage**(含 Step 1 路径测必须绿) + +--- + +### Task 10: 调拨 outbound_trigger_service + handler/sink + +**Files:** +- Create: `backend/app/services/in_transit_transfer/outbound_trigger_service.py` +- Create: `backend/app/services/in_transit_transfer/outbound_report_handler.py` +- Modify: `backend/app/services/shipping_notice/rpa_sinks.py`(`register_outbound_sinks`) +- Modify: `backend/app/__init__.py` 或组合根调用处(与 `register_inbound_sinks` 并列) +- Modify: `backend/app/services/freight_rpa/reports/queries.py`(`get_outbound_config` / `list_outbound_configured_source_codes`,对照 inbound) +- Test: `backend/tests/services/in_transit_transfer/test_outbound_trigger_service.py` + +**Interfaces:** +- Produces: + - `trigger_outbound_rpa(...)` / `trigger_outbound_rpa_batch(...)` + - `handle_outbound_report(fact) -> None`(对称 `handle_inbound_report`:推进等待中的出站相关 SourceJob;无等待任务则 no-op;可重入) + - `register_outbound_sinks()` → `register_report_handler('outbound', handle_outbound_report)` + +- [ ] **Step 1: 缺配置 fail-closed 测试** + +- [ ] **Step 2: 实现 trigger + handler**(对照 inbound 文件;调拨状态机字段名以现有 outbound `record_kind` / SourceJob 为准,禁止猜新状态——若入站 handler 推 `waiting_rpa_callback`→`file_ready`,出站同一套等待态字段) + +- [ ] **Step 3: 组合根注册** + +- [ ] **Step 4: 跑测并 stage** + +--- + +### Task 11: 管理端来源站点出站配置卡 + 排程运维 UI + +**Files:** +- Modify: `frontend/src/features/admin/modules/freight-rpa/FreightRpaPage.vue` +- Create: `frontend/src/features/admin/modules/freight-rpa/outboundReportConfigForm.ts`(若 Task 6 未建) +- Modify: `frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminRuns.ts` +- Modify: `backend/app/api/schedule/runs.py`(`outbound-rpa-units` list/retry、`outbound-raw-zip`) +- Modify: 四语言 admin schedule 文案 +- Test: vitest 组件/ composable 窄测;后端 units API 测 + +**Interfaces:** +- Produces: 来源站点第三折叠「出站报表配置」;排程 scope `outbound`;`rpaWorkerStatusScope: 'onhand'|'inbound'|'outbound'` + +- [ ] **Step 1: Vue —— 在入站配置块后复制一块出站**,绑定 `outboundConfig`,保存调 `saveOutboundReportConfig`;解析下拉 `purpose === 'outbound'` + +- [ ] **Step 2: 排程 —— 对齐 inbound 的 worker 徽标与 raw-zip 下载按钮** + +- [ ] **Step 3: 后端 units/retry/raw-zip 对照 inbound 路由实现** + +- [ ] **Step 4: `cd frontend && npm run build`** Expected: PASS + +- [ ] **Step 5: Stage** + +--- + +### Task 12: Windows Outbound Worker 脚本 + +**Files:** +- Create: `scripts/freight_rpa/outbound/outbound_rpa_worker.py` +- Create: `scripts/freight_rpa/outbound/start_outbound_worker.ps1` +- Create: `scripts/freight_rpa/outbound/register_outbound_worker_tasks.ps1` +- Create: `scripts/freight_rpa/outbound/outbound_dbs_export.py` +- Create: `scripts/freight_rpa/outbound/outbound_crane_export.py` +- Modify: `scripts/freight_rpa/README.md` +- Modify: `scripts/freight_rpa/common/rpa_callbacks.py`(确认 outbound 端点) +- Test: 后端侧可用「trigger 文件名/schema」合同测;Worker 无 pytest 时用脚本静态断言(读常量) + +**Interfaces:** +- Consumes: `freight_rpa.outbound.v1` / `outbound_export_batch` +- Produces: 轮询 `FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR`;回调 outbound-*-progress/ready;心跳 `outbound_export`;Worker ID `*-outbound` + +- [ ] **Step 1: 复制 inbound Worker 目录结构并替换常量/路径/回调** + +- [ ] **Step 2: 回调 `file_path` 只报文件名** + +在 outbound Worker 组装 batch-ready / unit 成功载荷时,`file_path`(及若有的等价字段)必须是 `Path(local_drop_file).name`,**禁止**把 `C:\\...\\drop\\xxx.xlsx` 整串作为契约主值(与入站现行「后端可容忍绝对路径、Worker 应只报文件名」一致)。在 worker 内加注释指向规格 §4.2 跨机路径契约。 + +- [ ] **Step 3: DBS 使用配置 `report_path`;Crane 固定出站页**(页面选择器字符串实现时按货代实名填写,注释标明来源截图/环境;禁止误用 Inbound Details) + +- [ ] **Step 4: ps1 注入 `FREIGHT_RPA_WORKER_ID=-outbound`、outbound logs 目录** + +- [ ] **Step 5: Stage `scripts/freight_rpa/outbound/` 与 README** + +--- + +### Task 13: 错误码四语言 + 文档 + ADR + 规格状态 + +**Files:** +- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/errors.json` +- Modify: `docs/features/freight-rpa/GLOSSARY.md` +- Modify: `docs/features/shipping-notice/technical.md`(改名 + 出站部署节,对称 §1.9) +- Modify: `docs/funclist.md` +- Modify: `docs/adr/0004-freight-rpa-report-ownership.md` +- Modify: `docs/superpowers/specs/2026-10-19-freight-rpa-outbound-and-rename-design.md`(状态 → 已有实施计划) +- Modify: 环境变量权威文档(若缺 OUTBOUND 项则补齐说明,不改真实密钥) + +**Interfaces:** 无代码接口 + +- [ ] **Step 1: 为 Task 8/9 引入的每个新 `code=` 补四语言** + +- [ ] **Step 2: Glossary —— Outbound 改为已交付抓取;注明无 deliveries、无工作台收料页;Inbound 用户文案「入站」** + +- [ ] **Step 3: ADR 0004 Consequences 增加「本阶段注册 outbound handler」** + +- [ ] **Step 4: 规格头状态改为「已有实施计划」并链到本 plan 路径** + +- [ ] **Step 5: Stage 文档与 errors.json** + +--- + +### Task 14: 总闸门(grep + 构建) + +**Files:** +- Create/Modify: `backend/tests/test_freight_rpa_outbound_rename_gate.py` + +**Interfaces:** 无 + +- [ ] **Step 1: 写入总闸门测试** + +```python +def test_no_receipt_raw_zip_route(): + text = Path("app/api/schedule/runs.py").read_text(encoding="utf-8") + assert "receipt-raw-zip" not in text + assert "inbound-raw-zip" in text + +def test_outbound_purpose_not_catalog_in_validate_docstring(): + text = Path("app/services/shipping_notice/onhand_parsing_profile.py").read_text(encoding="utf-8") + assert "purpose in {'inbound', 'outbound'}" in text or 'purpose in {"inbound", "outbound"}' in text + +def test_no_outbound_notification_deliveries_table_reference(): + ... +``` + +- [ ] **Step 2: 跑闸门 + 出站相关测 + frontend build** + +Run: + +```bash +cd backend && pytest tests/test_freight_rpa_outbound_rename_gate.py tests/test_freight_rpa_inbound_slim_gate.py tests/test_parsing_profile_purpose.py tests/test_freight_rpa_outbound_models.py -v +cd ../frontend && npm run build +``` + +Expected: 全部 PASS + +- [ ] **Step 3: Stage 闸门测试** + +--- + +## Spec coverage(自检) + +| 规格项 | 任务 | +| --- | --- | +| 报表规则 / 来源站点 / 入站报表文案 | T1 | +| 出站报表配置 UI | T11(API T6) | +| outbound 异动解析 | T5 | +| 出站三表 + 迁移 | T4 | +| 无 outbound deliveries;删入站 deliveries | T2、T4 | +| 下线工作台收料页 | T2 | +| inbound-raw-zip | T3 | +| trigger/心跳/回调/排程/retention | T7–T9、T8 | +| 按需 trigger + sink | T10 | +| Worker 脚本 | T12 | +| 错误码 / 文档 / ADR | T13 | +| 单发布总闸门 | T14 | +| 启用非硬门槛 | T6 校验不接入 activation checks(显式不改 `_source_activation_checks`) | +| Crane 固定出站页 | T12 | +| class-prefix 前置 | Global Constraints | +| 跨机路径:Windows `file_path` → Linux drop 文件名映射 | T9(测+读)、T12(Worker 只报文件名)、Global Constraints | + +无 TBD。入站历史错误码 `RPA.RECEIPT_*` **本计划不强制改名**(避免无收益大爆炸);用户可见「收料」文案必须清掉。 diff --git a/docs/superpowers/specs/2026-10-19-freight-rpa-outbound-and-rename-design.md b/docs/superpowers/specs/2026-10-19-freight-rpa-outbound-and-rename-design.md new file mode 100644 index 00000000..b0d0eb65 --- /dev/null +++ b/docs/superpowers/specs/2026-10-19-freight-rpa-outbound-and-rename-design.md @@ -0,0 +1,183 @@ +# 货代 RPA:报表规则 / 来源站点改名 + 出站全栈 + 入站运维瘦身 + +日期:2026-10-19 | 状态:**已有实施计划**(`docs/superpowers/plans/2026-10-19-freight-rpa-outbound-and-rename.md`)| 前置:`docs/superpowers/specs/2026-10-18-freight-rpa-phase-b-design.md`、`docs/superpowers/specs/2026-10-19-freight-rpa-class-prefix-design.md`(假定 `FreightRpa*` 已落地或同发布先合入)| 术语:`docs/features/freight-rpa/GLOSSARY.md` | ADR:延续 `docs/adr/0004-freight-rpa-report-ownership.md`(本规格注册 outbound handler) + +## 0. 问题 + +管理端货代域仍用「库存解析」「库存站点」「收料报表」等旧称,与已落地的 onhand / inbound 代码语义不一致。解析用途里虽有 `purpose=outbound`,但 UI/校验仍按库存字段目录占位;出站抓取(配置表、Worker、排程、回调、事实分发)未实施,仅有共享目录与 env 占位。 + +入站侧另有两处过度设计:`freight_rpa_inbound_notification_deliveries` 仅服务工作台「重发企微」幂等账,日常通知已由排程任务的通知人清单 + `_notify_schedule_run_wecom` 覆盖;工作台「收料文件」页与排程管理的 run 查询 / raw-zip 下载重叠。 + +## 1. 目标与非目标 + +**目标** + +1. 用户可见改名(四语言):`库存解析` → **报表规则**;`库存站点` → **来源站点**;`收料报表配置` → **入站报表配置**。父级菜单「库存管理」、页内「库存字段目录」不改。 +2. 来源站点详情新增 **出站报表配置**,与入站配置同构(路径 / 查询条件 / 解析绑定)。 +3. `purpose=outbound` 解析改为与 inbound 相同的 **标准异动字段**(`MOVEMENT_FIELDS`)契约;纠正现有 onhand 形态占位。 +4. 出站全栈镜像入站(做法 A:逐文件克隆,不先做泛化重构):配置 / unit / file 三表、trigger schema、独立 Worker、排程 + retention、回调、排程运维(unit 列表/重试/raw-zip)、在途调拨按需触发、`report_kind=outbound` handler + sinks。 +5. 管理端代码命名:`receipt*` → `inbound*`(对外已是 `inbound-report-config` 的路径保持;`receipt-raw-zip` → `inbound-raw-zip`,无兼容别名)。 +6. 入站瘦身:删除 deliveries 表与「重发企微」;下线工作台收料文件页;运维统一到排程管理。通知人须为可进入排程管理的管理员。 + +**非目标** + +- 不改父级「库存管理」、不改「库存字段目录」信息架构。 +- 不把履约「出货」/`shipment_*`/`freight_upload`/upload 域改名为 outbound。 +- 不把入站/出站配置纳入来源站点启用硬门槛(与入站现状一致:可选配置,触发时 fail-closed)。 +- 不做 outbound 旧解析草稿的自动字段迁移。 +- 不重做 class-prefix;出站类一律 `FreightRpaOutbound*`。 +- 不在本规格改在途调拨匹配算法,只接线 outbound 报表事实。 +- 不新建工作台「出站文件」页。 +- 出站不建 `notification_deliveries`;入站该表删除后亦不重建。 + +## 2. 已拍板决策 + +| 编号 | 决策 | +| --- | --- | +| D1 | 出站解析对齐入站异动契约(`MOVEMENT_FIELDS`) | +| D2 | 注册 `report_kind=outbound` handler + 调拨 sink(对称入站) | +| D3 | 改名含用户可见文案 + 管理端 `receipt*` 符号清理;回调路径无兼容层 | +| D4 | 单发布:改名 + 出站全栈 + 入站瘦身同交付 | +| D5 | 出站配置非启用硬门槛 | +| D6 | 出站触发 = 排程 `freight-rpa-outbound`(+ retention)+ 调拨 `outbound_trigger_service` | +| D7 | DBS 路径/查询可配;Crane 固定出站报表页(实名实现时对接,规格约束:固定页、不按 Warehouse 拆分) | +| D8 | 旧 onhand 形态 outbound 草稿:发布失败,人工重建 | +| D9 | 通知只走排程通知人清单;无逐文件企微投递账 | +| D10 | 父级「库存管理」不改 | +| D11 | 假定 `FreightRpa*` class-prefix 已落地或同发先合入 | +| D12 | RPA 层不强制 `in_out_flag`;方向过滤留在调拨域 | +| D13 | 库存字段目录保留,仅服务 onhand | +| D14 | 入口文案最终为 **报表规则**(非「文档规则」) | +| D15 | 删除入站 deliveries + resend API + 工作台收料页;运维归排程 | + +**实现路径:做法 A**(入站模板逐文件克隆)。否决:先抽象 MovementReport 泛化层(B);复用入站 Worker 目录承载出站(C)。 + +## 3. 数据模型与解析契约 + +### 3.1 解析 Profile + +| purpose | 字段契约 | 管理端 | +| --- | --- | --- | +| `onhand` | 库存字段目录 + `match_keys` | 不变 | +| `inbound` | `MOVEMENT_FIELDS` | 不变 | +| `outbound` | 与 inbound 相同 | 纠正:异动映射 UI/校验 | + +创建后 purpose 不可改。保存/发布 outbound 必须通过与 inbound 同源的异动必填映射校验。 + +### 3.2 出站新建表(三张) + +| 类 | 表 | +| --- | --- | +| `FreightRpaOutboundReportConfig` | `freight_rpa_outbound_report_configs` | +| `FreightRpaOutboundUnitRun` | `freight_rpa_outbound_rpa_unit_runs` | +| `FreightRpaOutboundReportFile` | `freight_rpa_outbound_report_files` | + +配置字段与入站同构:`source_id`(1:1)、`parsing_profile_id`(仅 published 且 `purpose=outbound`)、`report_path_json`、`query_parameters_json`、`config_version`。无独立启停:是否运行 = 来源站点 `enabled` ∧ 配置存在且可解析。 + +`FreightRpaSource` 增加 `outbound_report_config` 关系(并列 `onhand_report_config` / `inbound_report_config`)。 + +### 3.3 报表事实分发 + +在阶段 B 白名单上注册 `handle_outbound_report` 与 `register_outbound_sinks`。在途调拨消费出站事实;方向过滤不在 RPA 层新增规则。 + +### 3.4 入站拆除 + +Alembic:`DROP` `freight_rpa_inbound_notification_deliveries`。删除模型 `FreightRpaInboundNotificationDelivery`、`deliver_inbound_file`、`POST /api/admin/inbound-report-files//resend`,以及仅服务于该账本的测试。 + +工作台下线:`/workspace/inbound-reports` 路由、侧栏入口、`InboundReportFilesPage`、workspace `inbound-report-files` list/download API,以及仅被该页使用的 `shipping_notice.inbound_report_access` 模块(当前无其它调用方)。失败 unit 重试保留在**排程管理 / admin inbound-rpa-units**;原始包下载保留在排程 `inbound-raw-zip`。 + +## 4. API / 管理端 / 触发 / Worker + +### 4.1 管理端 API + +| 能力 | 说明 | +| --- | --- | +| `GET/PUT .../sources//inbound-report-config` | 已有;服务层/前端符号 `receipt*` → `inbound*` | +| `GET/PUT .../sources//outbound-report-config` | 新增,镜像入站 | +| parsing-profiles | `purpose=outbound` 走异动校验 | +| `receipt-raw-zip` → `inbound-raw-zip` | 无别名;企微深链参数同发 | + +### 4.2 Worker 回调与契约 + +新增(镜像入站): + +- `/api/freight-rpa/outbound-batch-ready` +- `/api/freight-rpa/outbound-unit-progress` +- `/api/freight-rpa/outbound-batch-progress` + +Trigger:schema `freight_rpa.outbound.v1`,action `outbound_export_batch`,文件名 `outbound_export_batch_{run_no}.json`。 +心跳能力:`outbound_export`;Worker ID:`*-outbound`。 +目录(env 多已占位):`FREIGHT_RPA_SHARED_OUTBOUND_{TRIGGER,DROP}_DIR`、`FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR`、`FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS`。 + +**跨机路径契约(硬约束,复现 onhand/inbound 历史事故禁止项)** + +Windows Worker 与 Linux 后端通过同一 SMB 共享看到不同绝对路径根(如 `C:\HxopsRpaTest\data\freight_rpa\outbound\drop\...` vs `/mnt/hxops-rpa-*-data/freight_rpa/outbound/drop/...`)。历史上曾因回调 `file_path` 携带 Windows 分隔符/`\` 绝对路径,在 Linux 侧按原样打开导致成功抓取后全程 400(入站于 2026-10-08 按「只认文件名」修复)。 + +出站必须遵守: + +1. Worker 回调 `file_path` **优先只报 drop 根内的文件名**(单一路径段,无目录)。 +2. 后端读取时:**禁止**把 Worker 绝对路径当 Linux 路径直接 `open`;一律 `Path(str(file_path).replace('\\', '/')).name` 取末段,再拼到本机 `FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR` 根下,并用 `resolve().relative_to(root)` 防穿越。 +3. 实现时对照入站 `_read_inbound_callback_file`(`freight_rpa/inbound/report_archive.py`)与在手 `resolve_shared_inventory_drop_file`(`onhand/workflow_protocol.py`);出站可抽共用 helper,但**不得**弱化「只认文件名」语义。 +4. 必须有回归测试:载荷带 `C:\\...\\outbound\\drop\\foo.xlsx` 与仅 `foo.xlsx` 均能读到 Linux drop 内同名文件;带 `..\\` 的路径被拒绝。 + +### 4.3 排程与运维 + +- 平台任务:`freight-rpa-outbound`、`freight-rpa-outbound-retention` +- Admin:`outbound-rpa-units`(list/retry)、`GET .../schedule-runs//outbound-raw-zip` +- 入站排程文案「收料」→「入站」;finalize 仍用排程通知人清单发企微(可附 raw-zip,与现网库存/入站一致) + +### 4.4 按需触发 + +新增 `outbound_trigger_service`(镜像 `inbound_trigger_service`):一源一单元;站点停用 / 出站配置缺失 / 登录连接缺失 → fail-closed。 + +### 4.5 脚本 + +`scripts/freight_rpa/outbound/`:`outbound_rpa_worker.py`、`start_outbound_worker.ps1`、`register_outbound_worker_tasks.ps1`、DBS/Crane export 驱动。Windows 任务名与入站同构独立(如 `HXOPS Freight Outbound RPA Worker TEST/PROD`)。后端与 Worker **同发**。 + +### 4.6 管理端 UI + +- `FreightRpaPage`:侧栏/标题改为报表规则、来源站点;来源站点详情三块折叠——库存报表|入站报表|出站报表。 +- 报表规则:outbound 与 inbound 共用异动映射交互。 +- 排程工作台:outbound job key、Worker 轮询 scope=`outbound`。 + +## 5. 错误处理 / 测试 / 文档 / 发布 + +### 5.1 错误 + +新增出站错误码(镜像入站超时/Worker 离线等),四语言 `locales/*/errors.json` 同步。统一 envelope / `AppError` / `requestJson` / `useMessage`。 + +### 5.2 测试最低集 + +- outbound 异动校验;旧 onhand 形态 outbound 发布失败 +- 出站配置 GET/PUT、1:1、绑定约束 +- 排程/按需 trigger 契约;回调 → 归档 → dispatch(fake sink) +- grep gate:无 deliveries / resend / 工作台收料页引用 +- i18n/导航:报表规则、来源站点、入站报表 +- Worker env 目录契约 + +### 5.3 文档(同 PR) + +- `GLOSSARY.md`:出站改为已交付抓取;注明无 deliveries、无工作台收料页 +- `docs/features/shipping-notice/technical.md`:改名 + 出站部署对称入站 §1.9 +- `docs/funclist.md`:补出站 RPA 与改名 +- 环境变量权威文档确认 `FREIGHT_RPA_*OUTBOUND*` +- ADR 0004 Consequences:本阶段注册 outbound handler + +### 5.4 发布 + +- class-prefix 先合入或同发 +- 迁移:新建出站三表 + drop inbound deliveries +- 共享目录创建 `freight_rpa/outbound/{triggers,drop,logs,archives}` +- 先 Worker 心跳就绪再挂排程;不提交密钥 + +## 6. 成功标准 + +- 管理端可见文案符合 §1;来源站点可独立维护入站/出站报表配置。 +- 出站排程与按需触发可跑通:trigger → Worker → 回调 → 文件归档 → outbound 事实分发。 +- 排程管理可查 outbound run、下载 outbound-raw-zip、重试失败 unit;企微走排程通知人。 +- 工作台无收料文件入口;无 deliveries 表与 resend 企微 API。 +- `frontend` 相关改动 `npm run build` 通过;关键后端测试与 grep gate 通过。 + +## 7. 后续实施 + +实施计划:`docs/superpowers/plans/2026-10-19-freight-rpa-outbound-and-rename.md`。按任务执行;提交须用户显式授权。 diff --git a/frontend/src/app/router/routes/workspace.routes.ts b/frontend/src/app/router/routes/workspace.routes.ts index f875f4a2..37724b78 100644 --- a/frontend/src/app/router/routes/workspace.routes.ts +++ b/frontend/src/app/router/routes/workspace.routes.ts @@ -62,12 +62,6 @@ export const workspaceRoutes: RouteRecordRaw[] = [ component: () => import('@/features/workspace/pages/ScheduleRunsPage.vue'), meta: { title: 'workspace.nav.scheduleRuns' }, }, - { - path: 'inbound-reports', - name: 'workspace-inbound-reports', - component: () => import('@/features/workspace/pages/InboundReportFilesPage.vue'), - meta: { title: 'workspace.nav.inboundReports' }, - }, { path: 'shipping-notice', redirect: '/workspace/shipping-notice/my-tasks', diff --git a/frontend/src/features/admin/api/admin.api.ts b/frontend/src/features/admin/api/admin.api.ts index 2545ae4f..a77fd18d 100644 --- a/frontend/src/features/admin/api/admin.api.ts +++ b/frontend/src/features/admin/api/admin.api.ts @@ -295,9 +295,9 @@ export const createShippingOnhandStructureAnalysis = (file: File) => { method: 'POST', body: form, ...auth(), }); }; -/** 读取标准异动字段目录(只读领域契约,供收料异动解析规则映射表单)。 */ +/** 读取标准异动字段目录(只读领域契约,供入站/出站报表规则映射表单)。 */ export const fetchMovementFields = () => requestJson>( - '/api/admin/shipping-notice/movement-fields', auth(), + '/api/admin/freight-rpa/movement-fields', auth(), ); /** 用已分析的真实栏位创建库存文件解析方案草稿。 */ export const createShippingOnhandParsingDraftFromAnalysis = (id: number, payload: Record) => requestJson( @@ -339,13 +339,21 @@ export const saveShippingOnhandSource = (payload: Record, id?: { method: id ? 'PUT' : 'POST', body: JSON.stringify(payload), ...jsonAuth() }, ); /** 读取/保存站点独立入站报表配置(/freight-rpa/sources//inbound-report-config);严禁通过库存站点保存接口夹带这些字段。 */ -export const getShippingReceiptReportConfig = (sourceId: number) => requestJson | null>( +export const getInboundReportConfig = (sourceId: number) => requestJson | null>( `/api/admin/freight-rpa/sources/${sourceId}/inbound-report-config`, auth(), ); -export const saveShippingReceiptReportConfig = (sourceId: number, payload: Record) => requestJson>( +export const saveInboundReportConfig = (sourceId: number, payload: Record) => requestJson>( `/api/admin/freight-rpa/sources/${sourceId}/inbound-report-config`, { method: 'PUT', body: JSON.stringify(payload), ...jsonAuth() }, ); +/** 读取/保存站点独立出站报表配置;载荷键与入站相同,严禁夹带来源站点字段。 */ +export const getOutboundReportConfig = (sourceId: number) => requestJson | null>( + `/api/admin/freight-rpa/sources/${sourceId}/outbound-report-config`, auth(), +); +export const saveOutboundReportConfig = (sourceId: number, payload: Record) => requestJson>( + `/api/admin/freight-rpa/sources/${sourceId}/outbound-report-config`, + { method: 'PUT', body: JSON.stringify(payload), ...jsonAuth() }, +); /** 直接绑定停用库存站点到已发布解析方案;服务端自动写入操作审计。 */ export const bindShippingOnhandSourceParsingProfile = (id: number, payload: { parsing_profile_id: number }) => requestJson( `/api/admin/freight-rpa/sources/${id}/bind-parsing-profile`, { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() }, diff --git a/frontend/src/features/admin/api/schedule.api.ts b/frontend/src/features/admin/api/schedule.api.ts index 5ff6596b..71e7a96d 100644 --- a/frontend/src/features/admin/api/schedule.api.ts +++ b/frontend/src/features/admin/api/schedule.api.ts @@ -1,6 +1,6 @@ /** * features/admin/api/schedule.api.ts - * 管理后台定时任务 HTTP API:任务 CRUD、配置、测试执行、运行记录。 + * 管理后台定时任务 HTTP API:任务 CRUD、配置、测试执行、运行记录、库存/入站/出站 raw-zip。 */ import { getAuthHeaders } from '@/shared/utils/auth'; import { requestJson } from '@/shared/api/client'; @@ -159,8 +159,11 @@ export const adminRunExcelUrl = (runId: number) => `/api/admin/schedule-runs/${r export const adminRunInventoryRawZipUrl = (runId: number) => `/api/admin/schedule-runs/${runId}/inventory-raw-zip`; -export const adminRunReceiptRawZipUrl = (runId: number) => - `/api/admin/schedule-runs/${runId}/receipt-raw-zip`; +export const adminRunInboundRawZipUrl = (runId: number) => + `/api/admin/schedule-runs/${runId}/inbound-raw-zip`; + +export const adminRunOutboundRawZipUrl = (runId: number) => + `/api/admin/schedule-runs/${runId}/outbound-raw-zip`; export interface RpaWorkerHeartbeatWorker { worker_id?: string; @@ -181,7 +184,7 @@ export interface RpaWorkerHeartbeatWorker { } export interface RpaWorkerHeartbeatSummary { - scope?: 'onhand' | 'inbound' | string; + scope?: 'onhand' | 'inbound' | 'outbound' | string; ready: boolean; message: string; detail_message?: string; @@ -195,7 +198,7 @@ export interface RpaWorkerHeartbeatSummary { workers: RpaWorkerHeartbeatWorker[]; } -export const getAdminRpaWorkersStatus = (scope: 'onhand' | 'inbound' = 'onhand') => +export const getAdminRpaWorkersStatus = (scope: 'onhand' | 'inbound' | 'outbound' = 'onhand') => getJson(`/api/admin/rpa-workers/status?scope=${encodeURIComponent(scope)}`); export type { DifyExecutionSnapshot, ScheduleRun, ScheduleTask, StepLog, TestScheduleRunResult, TestScheduleSqlResult }; diff --git a/frontend/src/features/admin/modules/freight-rpa/FreightRpaPage.vue b/frontend/src/features/admin/modules/freight-rpa/FreightRpaPage.vue index 8b299979..50bbfabd 100644 --- a/frontend/src/features/admin/modules/freight-rpa/FreightRpaPage.vue +++ b/frontend/src/features/admin/modules/freight-rpa/FreightRpaPage.vue @@ -1,11 +1,13 @@ - + -
- -
+
- + +
+
+
+ +
+ +
@@ -204,8 +257,8 @@
{{ t(`admin.freightRpa.${parsingLabelNs}.fieldMappings`) }}
-

{{ t(parsing.purpose === 'inbound' ? 'admin.freightRpa.movementMappingHint' : 'admin.freightRpa.readonlyFieldMappingsHint') }}

-
{{ t(`admin.freightRpa.${parsingLabelNs}.sampleRequired`) }}
-