diff --git a/.env.dev b/.env.dev index 101da6b1..9dcc3a21 100644 --- a/.env.dev +++ b/.env.dev @@ -146,6 +146,7 @@ FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=data/freight_rpa/inventory/drop FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory/triggers FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=data/freight_rpa/receipt/drop FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=data/freight_rpa/receipt/triggers +FREIGHT_RPA_RECEIPT_ARCHIVE_DIR=data/freight_rpa/receipt/archives FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=data/freight_rpa/inventory/upload_queue FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/freight_rpa/inventory/upload_triggers FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR=data/freight_rpa/common/browser_profile diff --git a/.env.prod b/.env.prod index 5064c65c..736bdf96 100644 --- a/.env.prod +++ b/.env.prod @@ -158,6 +158,7 @@ FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inven FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/triggers FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/drop FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/triggers +FREIGHT_RPA_RECEIPT_ARCHIVE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/archives FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_queue FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_triggers # 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问) diff --git a/.env.shared b/.env.shared index 928581e3..10765a36 100644 --- a/.env.shared +++ b/.env.shared @@ -238,6 +238,7 @@ IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS=86400 IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS=3 IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS=5 IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS=7 +IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS=2 # 归档 bucket(MinIO;凭据复用 MINIO_*) IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET=hxops-transfer diff --git a/.env.test b/.env.test index 833bafd6..99e5e40a 100644 --- a/.env.test +++ b/.env.test @@ -175,6 +175,7 @@ FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inven FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/drop FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/triggers +FREIGHT_RPA_RECEIPT_ARCHIVE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/archives FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_queue FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_triggers # AWS 库存列映射(可选 JSON 字符串) diff --git a/backend/app/api/in_transit_transfer.py b/backend/app/api/in_transit_transfer.py index 60b15de5..287f95c1 100644 --- a/backend/app/api/in_transit_transfer.py +++ b/backend/app/api/in_transit_transfer.py @@ -322,15 +322,18 @@ def retrigger_document_api(run_no: str, doc_no: str): @in_transit_transfer_bp.route("/documents", methods=["GET"]) @require_transfer_permission def list_documents_api(): - """已执行单分页查询(首页「已执行」区块数据源;只读,不写审计)。 + """已执行单分页查询(首页「执行看板」区块数据源;只读,不写审计)。 Query: status_group ∈ {success, failed, executing, result_unknown}(可选,缺省全部; - 非法 400);date_from/date_to=YYYY-MM-DD(可选,仅作用 orders 列表); + 非法 400);date_from/date_to=YYYY-MM-DD(可选,仅作用 orders 列表, + 按收料日期过滤——列表展示的业务日期口径,2026-09-29 由 created_at 切换); page(默认 1);page_size(默认 20,上限 100)。 口径:分组计数恒全量(GROUP BY status 对全部单统计,不受筛选影响—— 失败/结果未知/执行中=未完结即待办,全量才不漏;成功=累计产出); - 列表 created_at 倒序分页,cancelled 不展示(无产生路径)。 + 列表按 收料日期→数据源→拨出/拨入库位 升序分页(2026-09-29 与可调拨 + 明细/待处理池/结果卡统一口径,跨数据源不再乱序;执行落库时间仅作 + 同序兜底),cancelled 不展示(无产生路径)。 响应:{groups, total, page, page_size, orders:[serialize_executed_order 投影]}。 """ from app import db @@ -383,19 +386,28 @@ def list_documents_api(): for group, statuses in DOCUMENT_STATUS_GROUPS.items() } - # [STEP 3] 列表查询:status_group / created_at 时间窗仅作用列表; - # cancelled 恒不展示;created_at 倒序稳定分页(id 兜底同刻排序)。 + # [STEP 3] 列表查询:status_group / 时间窗仅作用列表;cancelled 恒不展示。 + # [2026-09-29 口径] 时间窗按收料日期过滤(receipt_date 为 ISO 日期字符串, + # 字典序即时间序);排序与可调拨明细/结果卡统一:收料日期→数据源→库位升序, + # created_at/id 兜底稳定分页(跨数据源不再按落库序乱序)。 query = TransferDocument.query.filter(TransferDocument.status != "cancelled") if status_group: query = query.filter(TransferDocument.status.in_(DOCUMENT_STATUS_GROUPS[status_group])) if date_from: - query = query.filter(TransferDocument.created_at >= datetime(date_from.year, date_from.month, date_from.day)) + query = query.filter(TransferDocument.receipt_date >= date_from.isoformat()) if date_to: - window_end = datetime(date_to.year, date_to.month, date_to.day) + timedelta(days=1) - query = query.filter(TransferDocument.created_at < window_end) + window_end = (date_to + timedelta(days=1)).isoformat() + query = query.filter(TransferDocument.receipt_date < window_end) total = query.count() docs = ( - query.order_by(TransferDocument.created_at.desc(), TransferDocument.id.desc()) + query.order_by( + TransferDocument.receipt_date.asc(), + TransferDocument.source_code.asc(), + TransferDocument.from_warehouse.asc(), + TransferDocument.to_warehouse.asc(), + TransferDocument.created_at.asc(), + TransferDocument.id.asc(), + ) .offset((page - 1) * page_size) .limit(page_size) .all() @@ -507,9 +519,9 @@ def retry_document_api(doc_no: str): 门禁:仅 business_failed/technical_failed 可重试;result_unknown → 400 (D11 唯一出口=重新触发);pending/executing 在飞拒绝;单不存在 404。 - 行为:单内 blocked 行逐行重查(复用 retry_item,单行隔离)→ 全部 ready 则 - 自动建新 Run 重跑(prepare_execution,D7①分支②复用原单号);任一行仍 - 阻断则不重跑(单是原子单位),阻断明细随响应返回由恢复池兜底。 + 行为:单内 blocked 行按组织批量重查(一次外部查询,行级 Attempt/隔离不变) + → 全部 ready 则自动建新 Run 重跑(prepare_execution,D7①分支②复用原单号); + 任一行仍阻断则不重跑(单是原子单位),阻断明细随响应返回由恢复池兜底。 """ from app.services.in_transit_transfer.retry_service import retry_document @@ -525,7 +537,7 @@ def retry_document_api(doc_no: str): @in_transit_transfer_bp.route("/items/batch-requery", methods=["POST"]) @require_transfer_permission def batch_requery_items_api(): - """批量重查外部系统库存(待处理池多选「重查」;单行隔离)。""" + """批量重查外部系统库存(待处理池多选「重查」;单行隔离,按组织一次外部查询)。""" user = _require_user() body = request.get_json(silent=True) or {} item_ids = _require_item_ids(body) @@ -698,7 +710,7 @@ def transfer_metrics_api(): def transfer_sources_api(): """来源实例列表(决策 3:平台 DBS/Crane 仅分组,实例为执行边界)。 - 每来源附收料文件状态(ready/fetching/failed/expired/none + has_ready_file), + 每来源附收料文件状态(ready/parse_failed/fetching/failed/expired/none + has_ready_file), 供前端门禁(无 ready 文件时禁止确认匹配)与状态标识;保留期已到或非当天 (业务日)抓取且未清理均投影 expired。只读复用已启用库存来源。 """ @@ -725,13 +737,41 @@ def transfer_sources_api(): def retry_source_rpa_api(source_code: str): """对指定来源重新触发一次收料 RPA 抓取(复用货代收料 trigger 链路)。 - 响应:{"source_code", "file_status", "ok"};配置缺失时 fail-closed(ok=False)。 + 【AI 触发时机】来源收料文件不可用需要恢复时调用:解析失败(parse_failed)先 + 本地重解析已归档文件;文件缺失/失效(none/expired/failed)才重新触发 RPA 抓取。 + + 解析失败优先本地重解析(解析失败分层 2026-09-29):当日文件可用但解析失败时, + 先走 sync_and_commit_for_callback 重解析归档文件——成功且投影回 ready → + 200 {"source_code", "ok": true, "file_status": "ready", "reparsed": true} + (不触发 RPA、不返回 202/fetching);仍失败 → 同结构 ok=false + (file_status=parse_failed)。其余状态沿用原路径:重新触发一次收料 RPA, + 成功 202+fetching;配置缺失时 fail-closed(ok=False)。 """ + from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa from app.services.in_transit_transfer.source_file_status import resolve_source_file_status - from app.services.in_transit_transfer.date_policy import business_date_now source_code = str(source_code).strip() + + # [STEP 1] 解析失败分层:文件可用但解析失败 → 先本地重解析归档文件,不触发 RPA。 + status = resolve_source_file_status(source_code=source_code) + if status.get("file_status") == "parse_failed" and status.get("file_sha256"): + synced = sync_and_commit_for_callback( + source_code=source_code, + business_date=str(business_date_now()), + now=datetime.utcnow(), + ) + # 重解析后再取投影:以真实落库事实(而非 sync 返回值)决定 ok。 + status = resolve_source_file_status(source_code=source_code) + ready = bool(synced) and status.get("file_status") == "ready" + return _ok({ + "source_code": source_code, + "ok": ready, + "file_status": status["file_status"], + "reparsed": True, + }) + + # [STEP 2] 其余状态沿用原路径:重新触发一次收料 RPA 抓取(202 + fetching)。 outcome = trigger_receipt_rpa( source_code=source_code, business_date=str(business_date_now()), diff --git a/backend/app/api/schedule/rpa_workers.py b/backend/app/api/schedule/rpa_workers.py index 4616e456..3f44d8dd 100644 --- a/backend/app/api/schedule/rpa_workers.py +++ b/backend/app/api/schedule/rpa_workers.py @@ -1,13 +1,15 @@ """ backend/app/api/schedule/rpa_workers.py -用途:管理端查询货代库存 RPA Worker 在线状态与就绪摘要。 +用途:管理端查询货代库存/收料 RPA Worker 在线状态与就绪摘要。 依赖:schedule.blueprint、rpa_worker_heartbeat.serialize_rpa_worker_status。 -逻辑:ScheduleWorkbenchPanel 在库存 RPA 排程工作台展示 worker 心跳状态。 +逻辑:ScheduleWorkbenchPanel 在库存或收料 RPA 排程工作台展示对应 worker 心跳状态。 """ from __future__ import annotations +from flask import request + from app.api.schedule.blueprint import schedule_admin_bp from app.core.decorators import require_admin from app.core.response import ok @@ -18,7 +20,10 @@ from app.services.shipping_notice.rpa_worker_heartbeat import serialize_rpa_work @require_admin def get_rpa_workers_status(): """ - 返回库存 RPA Worker 心跳摘要(在线/离线、最后心跳时间、就绪原因)。 - 核心逻辑:读取 Redis/内存心跳并与当前环境、trigger 目录比对。 + 返回 RPA Worker 心跳摘要(在线/离线、最后心跳时间、就绪原因)。 + + Query: + scope: inventory(默认)或 receipt。 """ - return ok(serialize_rpa_worker_status()) + scope = str(request.args.get('scope') or 'inventory').strip().lower() or 'inventory' + 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 c98990ff..e7df4178 100644 --- a/backend/app/api/schedule/runs.py +++ b/backend/app/api/schedule/runs.py @@ -22,6 +22,7 @@ from app.models import ScheduleRun, ScheduleTask, ShippingReceiptReportFile, Shi 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.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download +from app.services.schedule.shipping_receipt_rpa_archive import resolve_receipt_raw_zip_download from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file from app.services.shipping_notice.audit_service import append_shipping_audit_event from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger @@ -123,6 +124,26 @@ def get_schedule_run_inventory_raw_zip(run_id: int): ) +@schedule_admin_bp.route('/schedule-runs//receipt-raw-zip', methods=['GET']) +@require_admin +def get_schedule_run_receipt_raw_zip(run_id: int): + """ + 下载收料 RPA 排程 run 的原始收料 Excel 打包(ZIP + manifest)。 + + 核心逻辑:对齐 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) + return send_file( + zip_path, + as_attachment=True, + download_name=file_name, + mimetype='application/zip', + ) + + @schedule_admin_bp.route('/receipt-report-files//resend', methods=['POST']) @require_admin def resend_receipt_report_file(file_id: int): diff --git a/backend/app/api/shipping_notice_tools.py b/backend/app/api/shipping_notice_tools.py index 4b69c224..d9bbadab 100644 --- a/backend/app/api/shipping_notice_tools.py +++ b/backend/app/api/shipping_notice_tools.py @@ -335,6 +335,22 @@ def rpa_receipt_batch_ready(): return jsonify({'success': True, 'data': ingest_receipt_callback(_payload())}) +@shipping_notice_bp.route('/rpa/receipt-unit-progress', methods=['POST']) +def rpa_receipt_unit_progress(): + """收料单元领取/导出中:awaiting_rpa → processing,供管理端实时看到进行中。""" + from app.services.schedule.freight_receipt_rpa_finalize import mark_receipt_unit_processing + + return jsonify({'success': True, 'data': mark_receipt_unit_processing(_payload())}) + + +@shipping_notice_bp.route('/rpa/receipt-batch-progress', methods=['POST']) +def rpa_receipt_batch_progress(): + """收料批量进度:每完成一笔导出即回写排程 run 计数(非终态,对齐库存)。""" + from app.services.schedule.freight_receipt_rpa_finalize import report_receipt_batch_progress + + return jsonify({'success': True, 'data': report_receipt_batch_progress(_payload())}) + + @shipping_notice_bp.route('/rpa/inventory-batch-claimed', methods=['POST']) def rpa_inventory_batch_claimed(): """v2 Worker 领取回调:仅记录 Attempt 执行阶段。""" diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index 3ac27e20..f54b9e70 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -289,10 +289,17 @@ class Config: IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS = int( os.getenv('IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS', '600') or '600' ) + # 行库存查得时刻(inventory_checked_at)的 stale 徽标判定窗口(纯展示阈值)。 + IN_TRANSIT_TRANSFER_INVENTORY_STALE_TTL_SECONDS = int( + os.getenv('IN_TRANSIT_TRANSFER_INVENTORY_STALE_TTL_SECONDS', '86400') or '86400' + ) IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS', '3') or '3') IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS', '5') or '5') IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS', '7') or '7') IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET = os.getenv('IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET', 'hxops-transfer').strip() + IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS = int( + os.getenv('IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS', '2') or '2' + ) SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float( os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '420') ) @@ -463,6 +470,9 @@ class Config: FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = _rpa_data_path( 'FREIGHT_RPA_INVENTORY_ARCHIVE_DIR', 'freight_rpa', 'inventory', 'archives' ) + FREIGHT_RPA_RECEIPT_ARCHIVE_DIR = _rpa_data_path( + 'FREIGHT_RPA_RECEIPT_ARCHIVE_DIR', 'freight_rpa', 'receipt', 'archives' + ) FREIGHT_RPA_WORKER_MOCK = os.getenv('FREIGHT_RPA_WORKER_MOCK', 'false') # WeCom (企业微信) 登录配置 @@ -761,6 +771,8 @@ class TestingConfig(Config): SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:' # 钉住测试 TTL 语义(陈旧行门禁用例按 600s 书写),不随开发者 .env.shared 漂移。 IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS = 600 + # 库存查得时刻 stale 阈值钉 24h(stale 用例按 86400s 书写)。 + IN_TRANSIT_TRANSFER_INVENTORY_STALE_TTL_SECONDS = 86400 WTF_CSRF_ENABLED = False SQLALCHEMY_ENGINE_OPTIONS = {} SCHEDULE_WORKER_ENABLED = False diff --git a/backend/app/models/in_transit_transfer.py b/backend/app/models/in_transit_transfer.py index 19461cf5..6a9c7fe6 100644 --- a/backend/app/models/in_transit_transfer.py +++ b/backend/app/models/in_transit_transfer.py @@ -69,7 +69,8 @@ TRANSFER_DOCUMENT_STATUSES = ( ) # 未完结单状态集合(组锁生效范围,D7①/D15):同五元组存在任一未完结单时 # 复用其 doc_no+submit_timestamp,禁止新建;部分唯一索引的 WHERE 子句由该 -# 元组生成,保证「常量集 ↔ DB 约束」永远一致(test_document_model.py 锁定)。 +# 元组生成,保证「常量集 ↔ DB 约束」永远一致(原锁定测试 test_document_model.py +# 已删除,改动本元组时须人工核对迁移内 CHECK/WHERE 字面量同口径)。 UNRESOLVED_DOC_STATUSES = ( 'pending', 'executing', 'result_unknown', 'business_failed', 'technical_failed', ) @@ -262,6 +263,10 @@ class TransferInvoiceItem(Base): # 数量以 Decimal 文本保存,杜绝浮点误差;比较在服务层完成。 receipt_quantity: Mapped[str] = mapped_column(String(40), nullable=False) external_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True) + # [库存查得时刻] 当前 external_quantity 的 ERP 取数时间戳(stale 徽标判定时钟, + # 2026-09-29 起与行新鲜度 updated_at 分离:证据同步换戳/存续不续期本字段, + # 仅匹配评估/重查/写前复查在真实取数时写入;置空库存时同步置空)。NULL=无库存数据。 + inventory_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) status: Mapped[str] = mapped_column(String(32), nullable=False) result_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) result_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) diff --git a/backend/app/models/shipping_receipt_report.py b/backend/app/models/shipping_receipt_report.py index ce4c3ae0..22ec2ac8 100644 --- a/backend/app/models/shipping_receipt_report.py +++ b/backend/app/models/shipping_receipt_report.py @@ -40,7 +40,7 @@ class ShippingReceiptReportConfig(Base): query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column( JSON, default=list, server_default=text("'[]'"), nullable=False, ) - # 与库存同构:Warehouse 是查询条件之一(支持多值),逐仓拆分在排程/触发时由该条件运行时派生,不单独持久化仓库清单。 + # 与库存同构:查询条件原样下发 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) @@ -116,6 +116,10 @@ class ShippingReceiptReportFile(Base): 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) diff --git a/backend/app/services/admin/shipping_inventory_service.py b/backend/app/services/admin/shipping_inventory_service.py index 17ce5efa..ce074a2e 100644 --- a/backend/app/services/admin/shipping_inventory_service.py +++ b/backend/app/services/admin/shipping_inventory_service.py @@ -18,7 +18,6 @@ from app.models import ( ShippingInventoryRoutingRuleVersion, ShippingInventorySource, ShippingRpaProfile, ScheduleRun, ScheduleTask, ShippingNotice, ShippingOrderField, ShippingInventoryParsingProfile, - ShippingInventoryConfigurationTestRun, ShippingInventoryStructureAnalysis, ShippingNoticeLine, ShippingNoticeLineInventoryMatch, ShippingExcelTemplate, ShippingInventorySourceParsingBindingAudit, @@ -295,7 +294,11 @@ def _validate_movement_profile_binding(profile_id: Any) -> int | None: def _validate_receipt_report_config( source: ShippingInventorySource, data: dict[str, Any], ) -> tuple[dict[str, str], list[dict[str, Any]]]: - """规范收料配置,与库存同构:路径+查询条件;日期禁填,DBS 以 Warehouse 条件为逐仓拆分维度。""" + """规范收料配置,与库存同构:路径+查询条件;日期禁填。 + + DBS 的 Warehouse 等查询条件均为可选报表筛选:空条件表示 Worker 使用页面默认; + 不作为排程是否产出执行单元的门禁(一源一单元)。 + """ try: parameters = _validate_query_parameters(data) except ValidationError as exc: @@ -309,14 +312,7 @@ def _validate_receipt_report_config( path = _validate_report_path('dbs', raw_path) except ValidationError as exc: raise ValidationError(str(exc), code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') from exc - # Warehouse 条件即逐仓拆分维度(不单独持久化仓库清单):必须恰一条且至少一个有效值。 - warehouse_conditions = [item for item in parameters if str(item.get('name') or '').strip().lower() == 'warehouse'] - warehouse_values = [str(value or '').strip() for value in (warehouse_conditions[0].get('values') or [])] if warehouse_conditions else [] - if len(warehouse_conditions) != 1 or not any(warehouse_values): - raise ValidationError( - 'DBS receipt report requires exactly one Warehouse query condition with values', - code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID', - ) + # 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'): @@ -385,9 +381,7 @@ def _binding_snapshot(source: ShippingInventorySource) -> dict[str, Any]: def _validate_source_parsing_binding(source: ShippingInventorySource, profile: ShippingInventoryParsingProfile) -> None: - """校验停用站点可直接采用的已发布方案与当前发货模板字段契约。""" - if source.enabled: - raise ConflictError('Disable inventory source before changing parsing profile', code='SHIPPING.INVENTORY_SOURCE_BINDING_BLOCKED') + """校验站点可直接采用的已发布方案与当前发货模板字段契约;启用中的站点同样允许更换解析绑定。""" if profile.status != 'published': raise ValidationError('Published parsing profile is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED') definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} @@ -418,7 +412,7 @@ def _validate_source_parsing_binding(source: ShippingInventorySource, profile: S 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: 待绑定的库存站点主键,不能为空且不得重复。 @@ -642,115 +636,6 @@ def list_export_records(*, limit: int = 100) -> list[dict[str, Any]]: return records[:max(1, min(limit, 200))] -def _enabled_external_mapping_exists(source: ShippingInventorySource, warehouse_id: str | None) -> bool: - """判断已确认的货代仓库是否已有精确映射或库存源默认映射。""" - query = ShippingInventoryExternalMapping.query.filter_by(inventory_source_id=source.id, enabled=True) - warehouse = str(warehouse_id or '').strip().upper() - if warehouse and query.filter_by(freight_warehouse_id=warehouse).first() is not None: - return True - return query.filter(ShippingInventoryExternalMapping.freight_warehouse_id.is_(None)).first() is not None - - -def _test_analysis_validation(source: ShippingInventorySource) -> tuple[list[str], dict[str, Any]]: - """复核测试连接证据并生成行级解析/调拨映射准备状态,不将后两者作为启用条件。""" - missing: list[str] = [] - details: dict[str, Any] = {'sample_warehouses': []} - confirmed_test = ShippingInventoryConfigurationTestRun.query.filter( - ShippingInventoryConfigurationTestRun.inventory_source_id == source.id, - ShippingInventoryConfigurationTestRun.status.in_(['completed', 'completed_empty']), - ShippingInventoryConfigurationTestRun.source_config_version == source.config_version, - ).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first() - result = confirmed_test.result_json if confirmed_test and isinstance(confirmed_test.result_json, dict) else {} - if ( - not confirmed_test - or source.rpa_profile is None - or confirmed_test.rpa_profile_config_version != source.rpa_profile.config_version - or int(result.get('confirmed_profile_id') or 0) != int(source.parsing_profile_id or 0) - ): - return ['configuration_test'], details - if confirmed_test.status == 'completed_empty': - # 无库存时只能确认连接与查询成功;行级解析和调拨映射留待首个非空文件或实际调拨前验证。 - details['data_validation'] = 'pending_first_non_empty_export' - details['parsing_validation'] = 'pending_first_non_empty_export' - details['warehouse_mapping'] = 'deferred_until_transfer' - return missing, details - analysis = db.session.get(ShippingInventoryStructureAnalysis, confirmed_test.analysis_id) - profile = source.parsing_profile - if analysis is None or profile is None: - return ['configuration_test'], details - structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {} - candidates = structure.get('candidates') if isinstance(structure.get('candidates'), list) else [] - definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} - selected = next((item for item in candidates if isinstance(item, dict) - and item.get('sheet_name') == definition.get('sheet_name') - and item.get('header_row_index') == definition.get('header_row_index')), None) - headers = [str(item).strip() for item in (selected or {}).get('headers', []) if str(item).strip()] - duplicate_headers = { - str(item.get('header') or '').strip() - for item in (selected or {}).get('columns', []) - if isinstance(item, dict) and item.get('duplicate') - } - mapping = definition.get('field_mapping') if isinstance(definition.get('field_mapping'), dict) else {} - from app.services.shipping_notice.inventory_mapping import runtime_field_mapping, usage_field_ids - - runtime_mapping, catalog = runtime_field_mapping(mapping) - usages = usage_field_ids() - mapped_ids = set(runtime_mapping) - match_fields = mapped_ids & usages.get('match_identity', set()) - quantity_fields = mapped_ids & usages.get('inventory_quantity', set()) - required_fields = match_fields | quantity_fields - if ( - not selected - or not match_fields - or len(quantity_fields) != 1 - or not required_fields <= set(runtime_mapping) - or any(str(runtime_mapping.get(field) or '').strip() not in headers for field in required_fields) - or any(str(value or '').strip() in duplicate_headers for value in mapping.values()) - or not int((selected or {}).get('sample_row_count') or 0) - ): - details['parsing_validation'] = 'pending_first_non_empty_export' - return missing, details - column_by_header = { - str(item.get('header') or '').strip(): item - for item in (selected or {}).get('columns', []) if isinstance(item, dict) - } - quantity_codes = quantity_fields - quantity_column = next(( - column_by_header.get(str(runtime_mapping.get(field) or '').strip(), {}) - for field in quantity_codes - ), {}) - identifier_columns = [ - column_by_header.get(str(runtime_mapping.get(field) or '').strip(), {}) - for field in match_fields - ] - if ( - quantity_column.get('inferred_type') != 'number' - or any(not item.get('sample_values') for item in identifier_columns) - ): - details['parsing_validation'] = 'pending_first_non_empty_export' - return missing, details - if source.warehouse_resolution_mode == 'fixed': - details['warehouse_mapping'] = 'ready_for_transfer' if _enabled_external_mapping_exists(source, source.fixed_warehouse_id) else 'deferred_until_transfer' - return missing, details - warehouse_codes = mapped_ids & usages.get('warehouse_identity', set()) - if len(warehouse_codes) != 1: - details['warehouse_identification'] = 'pending_first_non_empty_export' - return missing, details - warehouse_header = next((str(runtime_mapping.get(field) or '').strip() for field in warehouse_codes), '') - if not warehouse_header or warehouse_header not in headers or warehouse_header in duplicate_headers: - details['warehouse_identification'] = 'pending_first_non_empty_export' - return missing, details - column = next((item for item in (selected or {}).get('columns', []) - if isinstance(item, dict) and str(item.get('header') or '').strip() == warehouse_header), {}) - sample_warehouses = sorted({str(value).strip().upper() for value in column.get('sample_values', []) if str(value).strip()}) - details['sample_warehouses'] = sample_warehouses - details['warehouse_identification'] = 'ready_for_transfer' if sample_warehouses else 'pending_first_non_empty_export' - details['warehouse_mapping'] = 'ready_for_transfer' if sample_warehouses and all( - _enabled_external_mapping_exists(source, warehouse) for warehouse in sample_warehouses - ) else 'deferred_until_transfer' - return missing, details - - def _template_validation_missing(source: ShippingInventorySource) -> list[str]: """确认发货模板引用的库存字段均由当前解析方案提供,避免启用后才发现字段断链。""" template = source.excel_template @@ -770,35 +655,11 @@ def _template_validation_missing(source: ShippingInventorySource) -> list[str]: return ['template_validation'] if not mappings or invalid else [] -def _latest_test_run_evidence(source: ShippingInventorySource) -> dict[str, Any]: - """提取最近一次配置测试的非敏感证据,供上线检查说明测试是否过期或失败。""" - run = ShippingInventoryConfigurationTestRun.query.filter_by( - inventory_source_id=source.id, - ).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first() - if run is None: - return {'state': 'not_started'} - profile_version = source.rpa_profile.config_version if source.rpa_profile is not None else None - if ( - run.source_config_version != source.config_version - or run.rpa_profile_config_version != profile_version - ): - return { - 'state': 'stale', 'run_no': run.run_no, 'status': run.status, - 'source_config_version': run.source_config_version, - 'rpa_profile_config_version': run.rpa_profile_config_version, - } - if run.status == 'failed': - return {'state': 'failed', 'run_no': run.run_no, 'status': run.status, 'stage': run.stage} - if run.status == 'completed_empty': - return {'state': 'empty', 'run_no': run.run_no, 'status': run.status, 'stage': run.stage} - return {'state': 'current', 'run_no': run.run_no, 'status': run.status, 'stage': run.stage} - - 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'), @@ -809,16 +670,15 @@ def _activation_check( def _source_activation_checks(source: ShippingInventorySource) -> list[dict[str, Any]]: - """构建库存站点启用条件与后续准备项;行级解析和调拨映射不阻断启用。""" - validation_missing, validation_details = _test_analysis_validation(source) - missing = set(validation_missing) - test_evidence = _latest_test_run_evidence(source) - test_complete = 'configuration_test' not in missing + """构建库存站点启用硬门槛:可用连接、已发布解析方案、已绑定已发布发货模板及字段契约。 + + 测试导出不再参与启用门禁;启停由管理员显式开关完成。 + """ profile_ready = source.rpa_profile is not None and bool(source.rpa_profile.enabled) parsing_ready = source.parsing_profile is not None and source.parsing_profile.status == 'published' template_ready = source.excel_template is not None and source.excel_template.status == 'published' - template_valid = template_ready and 'template_validation' not in missing - checks = [ + 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}, @@ -832,40 +692,14 @@ def _source_activation_checks(source: ShippingInventorySource) -> list[dict[str, evidence={'template_id': source.excel_template_id, 'published': template_ready}, ), _activation_check( - 'template_validation', passed=not template_ready or template_valid, - action='configure_excel_template', evidence={}, blocking=template_ready and not template_valid, - ), - _activation_check( - 'configuration_test', passed=test_complete, - action='run_configuration_test', evidence=test_evidence, - status=test_evidence['state'] if test_evidence['state'] in {'stale', 'failed', 'empty'} else None, - ), - _activation_check( - 'parsing_validation', passed=test_complete and not validation_details.get('parsing_validation'), - action='run_configuration_test', evidence={'sample_warehouses': validation_details['sample_warehouses']}, - status='pending' if validation_details.get('parsing_validation') else None, blocking=False, + 'template_validation', passed=not template_invalid, + action='configure_excel_template', evidence={}, blocking=template_invalid, ), ] - if source.warehouse_resolution_mode == 'inventory_match': - checks.append(_activation_check( - 'warehouse_identification', passed=validation_details.get('warehouse_identification') == 'ready_for_transfer', - action='configure_parsing_profile', evidence={'sample_warehouses': validation_details['sample_warehouses']}, - status='pending' if validation_details.get('warehouse_identification') else None, blocking=False, - )) - checks.append(_activation_check( - 'warehouse_mapping', passed=validation_details.get('warehouse_mapping') == 'ready_for_transfer', action='configure_warehouse_mapping', - evidence={ - 'mode': source.warehouse_resolution_mode, - 'fixed_warehouse_id': source.fixed_warehouse_id, - 'sample_warehouses': validation_details['sample_warehouses'], - }, - status='pending' if validation_details.get('warehouse_mapping') else None, blocking=False, - )) - return checks def get_source_activation_status(source: ShippingInventorySource) -> dict[str, Any]: - """返回库存站点正式运行的结构化门禁结果。 + """返回库存站点启用硬门槛的结构化结果。 Args: source: 已持久化的库存站点,关联配置由当前数据库事务提供。 @@ -883,25 +717,8 @@ def get_source_activation_status(source: ShippingInventorySource) -> dict[str, A } -def activate_source_if_ready(source: ShippingInventorySource, *, actor_id: int | None) -> bool: - """在测试回调后自动启用已满足全部正式运行条件的停用站点。 - - Args: - source: 已完成当前版本测试的库存站点;调用方负责统一提交事务。 - actor_id: 发起测试的管理员标识,仅用于更新审计字段。 - - Returns: - 当本次将站点改为启用时返回 ``True``;条件未齐或已启用时返回 ``False``。 - """ - if source.enabled or not get_source_activation_status(source)['ready']: - return False - source.enabled = True - source.updated_by = actor_id - return True - - def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]: - """启用完成验证的库存站点;未通过任一前置条件时保持停用。""" + """启用已满足硬门槛的库存站点;未通过任一前置条件时保持停用。""" source = db.session.get(ShippingInventorySource, source_id) if source is None: raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') @@ -919,7 +736,7 @@ def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]: def deactivate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]: - """停用库存站点,保留其解析方案和历史运行审计以便后续重新测试。""" + """停用库存站点,保留其解析方案和历史运行审计。""" source = db.session.get(ShippingInventorySource, source_id) if source is None: raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') diff --git a/backend/app/services/in_transit_transfer/auto_transfer.py b/backend/app/services/in_transit_transfer/auto_transfer.py index 39f165bc..605db83d 100644 --- a/backend/app/services/in_transit_transfer/auto_transfer.py +++ b/backend/app/services/in_transit_transfer/auto_transfer.py @@ -36,14 +36,17 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps, recipients: list[str] | None = None) -> AutoTransferOutcome: """执行一次自动调拨排程。 + 核心逻辑:可选恢复 → 自动匹配 → 若 executable_count>0 则执行并写 run_no; + 空数据日(匹配后无可执行行)直接返回,不执行、不通知、不记 error(C5)。 + Args: business_date: 业务日期。 deps: 注入依赖。 source_codes: 来源实例列表(缺省全部启用来源)。 recover_history: 是否执行历史恢复。 - sender / recipients: 企微通知(None 则跳过通知)。 + sender / recipients: 企微通知(None 则跳过通知;run_no 为空时不发送)。 Returns: - AutoTransferOutcome。 + AutoTransferOutcome;空数据日时 run_no/run_status 均为 None 且 errors 为空。 """ outcome = AutoTransferOutcome() if recover_history: @@ -57,10 +60,12 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps, business_date=business_date, deps=deps, ) - # 执行不再绑定匹配确认:按匹配 scope 圈 ready 行委托 execute_items - # (两道门禁:可执行/文件版本对账;TTL 新鲜度门禁 2026-09-25 退役); - # 无可执行行时门禁抛错, - # 与旧流程一致记入 errors 不阻断通知阶段。 + # [STEP 2] 空数据日跳过执行:匹配后无可执行行(含恢复后仍为 0)时不建票、 + # 不写 ERP、不通知(产品决策 C5);该日仅留痕 Run/Matching,不视作失败。 + if summary.counts.executable_count == 0: + return outcome + # [STEP 3] 执行不再绑定匹配确认:按匹配 scope 圈 ready 行委托 execute_items + # (两道门禁:可执行/文件版本对账;TTL 新鲜度门禁 2026-09-25 退役)。 executed = execute_matching_items(matching_id=summary.matching_id, deps=deps) outcome.run_no = executed.run_no outcome.run_status = executed.status diff --git a/backend/app/services/in_transit_transfer/backlog_service.py b/backend/app/services/in_transit_transfer/backlog_service.py index f57adf95..b434e6bd 100644 --- a/backend/app/services/in_transit_transfer/backlog_service.py +++ b/backend/app/services/in_transit_transfer/backlog_service.py @@ -13,6 +13,9 @@ from dataclasses import dataclass from datetime import datetime from typing import Optional +from sqlalchemy import func + +from app import db from app.models import TransferAttempt, TransferInvoiceItem from app.services.in_transit_transfer.status import TransferStatus @@ -73,24 +76,35 @@ def aging_level_for(age_days: int, *, warn: int = 3, escalate: int = 5, critical return AGING_NORMAL -def _latest_attempt(item: TransferInvoiceItem) -> Optional[TransferAttempt]: - """返回明细最近一次 Attempt(无则 None)。""" - return TransferAttempt.query.filter_by(item_id=item.id).order_by( - TransferAttempt.created_at.desc(), - ).first() +def _latest_attempt_times(item_ids: list[int]) -> dict[int, datetime]: + """批量取每行最近一次 Attempt 时间(单条 GROUP BY 聚合)。 + 【为什么批量】待处理池历史行持续累积,旧实现逐行 `_latest_attempt` 子查询 + 在列表接口放大为 2N+1 条 SQL(age 判定一次、DTO 组装各一次),是 + backlog / backlog/summary 接口 4s+ 响应的根因(2026-09-29 修复); + 分组聚合后整池仅 1 条。 -def _item_age_days(item: TransferInvoiceItem, now: datetime) -> int: - """按最近 Attempt 或明细更新时间计算积压天数。""" - latest = _latest_attempt(item) - base = latest.created_at if latest is not None else item.updated_at - return max(0, int((now - base).total_seconds() // 86400)) + Args: + item_ids: 池内明细 id 列表(空列表直接返回空表,不发查询)。 + Returns: + {item_id: 最近 Attempt 的 created_at};无 Attempt 的行不在表中。 + """ + if not item_ids: + return {} + rows = ( + db.session.query(TransferAttempt.item_id, func.max(TransferAttempt.created_at)) + .filter(TransferAttempt.item_id.in_(item_ids)) + .group_by(TransferAttempt.item_id) + .all() + ) + return {item_id: latest for item_id, latest in rows} def list_backlog(*, now: datetime | None = None, source_code: str | None = None) -> list[BacklogItemDTO]: """列出待处理池项(可恢复 + 已关闭 + 结果未知)。 - 排序:收料日期 → Invoice → 创建时间(业务稳定键,与重查/恢复等操作无关)。 + 排序:收料日期 → 数据源 → Invoice → 创建时间(全链路统一业务稳定键, + 与可调拨明细/匹配卡视图同口径,2026-09-29 统一;与重查/恢复等操作无关)。 不用 updated_at 排序——它是行级新鲜度时间戳,重查/恢复会刷新它, 以此排序会让正在处理的行在列表中跳位。 @@ -110,15 +124,19 @@ def list_backlog(*, now: datetime | None = None, source_code: str | None = None) ) if source_code: query = query.filter_by(source_code=source_code) - output: list[BacklogItemDTO] = [] - for item in query.order_by( + pool_rows = query.order_by( TransferInvoiceItem.receipt_date.asc().nulls_last(), + TransferInvoiceItem.source_code.asc(), TransferInvoiceItem.invoice_no.asc(), TransferInvoiceItem.created_at.asc(), TransferInvoiceItem.id.asc(), - ).all(): - age = _item_age_days(item, current) - latest = _latest_attempt(item) + ).all() + latest_map = _latest_attempt_times([row.id for row in pool_rows]) + output: list[BacklogItemDTO] = [] + for item in pool_rows: + latest = latest_map.get(item.id) + base = latest if latest is not None else item.updated_at + age = max(0, int((current - base).total_seconds() // 86400)) if item.status == TransferStatus.RESULT_UNKNOWN.value: level = AGING_UNKNOWN elif item.status == TransferStatus.MANUALLY_CLOSED.value: @@ -134,7 +152,7 @@ def list_backlog(*, now: datetime | None = None, source_code: str | None = None) reason=item.result_message or item.result_code or "", age_days=age, aging_level=level, - last_attempt_at=latest.created_at.isoformat() if latest is not None else None, + last_attempt_at=latest.isoformat() if latest is not None else None, receipt_date=item.receipt_date, material_name=item.material_name, from_warehouse=item.from_warehouse, diff --git a/backend/app/services/in_transit_transfer/contracts.py b/backend/app/services/in_transit_transfer/contracts.py index 33a0933d..33f7f75e 100644 --- a/backend/app/services/in_transit_transfer/contracts.py +++ b/backend/app/services/in_transit_transfer/contracts.py @@ -74,7 +74,7 @@ class MatchingCountsDTO: # 文件已落地、尚未查 ERP 库存的待查行(status='matching' + # result_code='pending_stock_check',evidence_sync 落地态)。 pending_stock_check_count: int = 0 - # blocked_file_removed 行数(文件新版本中消失,已出清,不进默认视图/明细)。 + # blocked_file_removed 行数(历史残留:存续语义上线前误标;不进默认视图/明细,修复脚本恢复后归零)。 invalid_count: int = 0 @@ -162,13 +162,16 @@ class ExternalDocumentDTO: @dataclass(frozen=True) class TransferExceptionDTO: - """未生成 外部系统 单据的异常项(单独展示)。""" + """未生成 外部系统 单据的异常项(单独展示;仅收未建单被阻断的行)。""" source_code: str invoice_no: str material_no: str reason: str facts: str + # 行级人话原因(= 行 result_message,2026-09-29 契约扩充):前端展示优先于 + # reason 状态码标签(分组阻断时携带阻断单号等可行动信息),空则标签兜底。 + message: str = "" @dataclass(frozen=True) diff --git a/backend/app/services/in_transit_transfer/date_policy.py b/backend/app/services/in_transit_transfer/date_policy.py index e32f969f..31b9ad42 100644 --- a/backend/app/services/in_transit_transfer/date_policy.py +++ b/backend/app/services/in_transit_transfer/date_policy.py @@ -1,10 +1,11 @@ """在途调拨业务日期与成熟度策略。 -用途:固定业务时区 Asia/Shanghai,实现 D+1 成熟规则(当天收料 not_matured, - 昨天及更早可匹配,未来日期阻断)。 -依赖:标准库 zoneinfo / datetime。 -逻辑:所有日期判定集中在本模块,供 matching_service / recovery_service 复用, - 避免各服务各自计算导致口径漂移。 +用途:固定业务时区 Asia/Shanghai,实现 T+lag 成熟规则(默认 T+2:收料日期 ≤ T-2 + 可匹配,T-1/当天 not_matured,未来日期阻断);统一 parse_date 归一化收料日期 + (ISO + DSV SSRS 美式 MM/DD/YYYY[ HH:MM:SS])。 +依赖:标准库 zoneinfo / datetime;可选 Flask current_app(读成熟滞后配置)。 +逻辑:所有日期判定集中在本模块,供 matching_service / file_parser / evidence_sync + 复用,避免各服务各自计算导致口径漂移。 """ from __future__ import annotations @@ -19,15 +20,29 @@ MATURITY_ELIGIBLE = "eligible" MATURITY_NOT_MATURED = "not_matured" MATURITY_FUTURE = "future" +# 成熟滞后天数默认值(T+2:收料日期 ≤ T-2 才可匹配;与海外的时差余量)。 +# 可经环境变量 IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS 覆盖(settings 装载)。 +DEFAULT_MATURITY_LAG_DAYS = 2 + +# DSV SSRS Date Received 常见美式格式(月/日/年,可选时分秒);%m/%d 亦接受单位数。 +_US_DATE_FORMATS = ( + "%m/%d/%Y %H:%M:%S", + "%m/%d/%Y %H:%M", + "%m/%d/%Y", +) + def parse_date(value: date | datetime | str) -> date: """将 date/datetime 或日期字符串归一化为 date。 + 核心逻辑:先认 ISO(含带时间),再认美式 MM/DD/YYYY[ HH:MM[:SS]](DSV 收料); + 均失败则 ValueError(fail-closed)。 + Args: - value: date/datetime 对象,或日期字符串(允许携带时间部分,如 - Excel 日期单元格经字符串化的 '2026-08-26 17:38:38')。 + value: date/datetime 对象,或日期字符串(ISO 如 '2026-08-26 17:38:38'; + 美式如 '08/13/2026 13:08:00')。 Returns: - 归一化后的 date。 + 归一化后的 date(忽略时分秒)。 Raises: ValueError: 字符串不是可识别的日期/日期时间。 """ @@ -42,8 +57,15 @@ def parse_date(value: date | datetime | str) -> date: pass try: return datetime.fromisoformat(text).date() - except ValueError as exc: - raise ValueError(f"Invalid date value: {value!r}") from exc + except ValueError: + pass + # [STEP] DSV SSRS 收料 Date Received:美式月/日/年(可带时分秒)。 + for fmt in _US_DATE_FORMATS: + try: + return datetime.strptime(text, fmt).date() + except ValueError: + continue + raise ValueError(f"Invalid date value: {value!r}") def business_date_now(moment: datetime | None = None) -> date: @@ -85,31 +107,51 @@ def business_date_utc_window(now: datetime | None = None) -> tuple[datetime, dat return start_utc, start_utc + timedelta(hours=24) -def maturity_status(receipt_date: date | str, business_date: date | str) -> str: - """按 D+1 规则判定收料日期成熟度。 +def maturity_lag_days() -> int: + """读取成熟滞后天数(app 配置优先,缺省回退 DEFAULT_MATURITY_LAG_DAYS)。 + + Returns: + 成熟滞后天数 lag;无 Flask app 上下文(纯单元测试/脚本)时回退默认值, + 保持策略函数可纯调用。 + """ + try: + from flask import current_app + return int(current_app.config.get( + "IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS") or DEFAULT_MATURITY_LAG_DAYS) + except RuntimeError: # 无 app 上下文 + return DEFAULT_MATURITY_LAG_DAYS + + +def maturity_status(receipt_date: date | str, business_date: date | str, + lag_days: int | None = None) -> str: + """按 T+lag 规则判定收料日期成熟度(默认 lag=2)。 Args: receipt_date: 收料日期。 business_date: 当前业务日期 T。 + lag_days: 显式滞后天数;None 时读 maturity_lag_days()。 Returns: - 'eligible'(receipt_date < T)、'not_matured'(receipt_date == T)或 - 'future'(receipt_date > T,结构化阻断)。 + 'eligible'(receipt ≤ T-lag)、'not_matured'(T-lag < receipt ≤ T)或 + 'future'(receipt > T,结构化阻断)。 """ receipt = parse_date(receipt_date) business = parse_date(business_date) - if receipt == business: - return MATURITY_NOT_MATURED + lag = maturity_lag_days() if lag_days is None else int(lag_days) if receipt > business: return MATURITY_FUTURE + if receipt > business - timedelta(days=lag): + return MATURITY_NOT_MATURED return MATURITY_ELIGIBLE -def eligible_receipt_date_to(business_date: date | str) -> date: - """返回可进入匹配的收料截止日期(业务日期 T - 1 天)。 +def eligible_receipt_date_to(business_date: date | str, lag_days: int | None = None) -> date: + """返回可进入匹配的收料截止日期(业务日期 T - lag 天,默认 T-2)。 Args: business_date: 当前业务日期。 + lag_days: 显式滞后天数;None 时读 maturity_lag_days()。 Returns: - T - 1 天。 + T - lag 天。 """ - return parse_date(business_date) - timedelta(days=1) + lag = maturity_lag_days() if lag_days is None else int(lag_days) + return parse_date(business_date) - timedelta(days=lag) diff --git a/backend/app/services/in_transit_transfer/deps.py b/backend/app/services/in_transit_transfer/deps.py index b57eaa2a..21b2dfba 100644 --- a/backend/app/services/in_transit_transfer/deps.py +++ b/backend/app/services/in_transit_transfer/deps.py @@ -29,6 +29,7 @@ from app.services.in_transit_transfer.matching_service import ( ) from app.services.in_transit_transfer.strategy import ( DEFAULT_CONFIRM_TTL_SECONDS, + DEFAULT_INVENTORY_STALE_TTL_SECONDS, default_strategy, ) @@ -107,6 +108,18 @@ def set_transfer_dependencies(deps: TransferDeps | None) -> None: _override = deps +def _ttl_from_config(key: str, default: int) -> int: + """读取整型 TTL 配置(无应用上下文/非法值回落代码默认,下限 1 秒)。""" + try: + raw = current_app.config.get(key, default) + except RuntimeError: # 无 app context:回落代码默认(等同旧行为) + raw = default + try: + return max(1, int(raw)) + except (TypeError, ValueError): + return default + + def _strategy_from_config(): """从 Flask 配置装配策略快照(TTL 环境变量的真实生效点)。 @@ -115,19 +128,18 @@ def _strategy_from_config(): 无应用上下文(纯脚本/裸调用)时回落代码默认值,行为与历史一致。 Returns: - TransferStrategyPolicy(confirm_ttl_seconds=max(1, 配置值),禁令项沿用默认)。 + TransferStrategyPolicy(confirm_ttl_seconds / inventory_stale_ttl_seconds + =max(1, 配置值),禁令项沿用默认)。 """ - try: - raw = current_app.config.get( + return replace( + default_strategy(), + confirm_ttl_seconds=_ttl_from_config( "IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS", DEFAULT_CONFIRM_TTL_SECONDS, - ) - except RuntimeError: # 无 app context:回落代码默认(等同旧行为) - raw = DEFAULT_CONFIRM_TTL_SECONDS - try: - ttl = int(raw) - except (TypeError, ValueError): - ttl = DEFAULT_CONFIRM_TTL_SECONDS - return replace(default_strategy(), confirm_ttl_seconds=max(1, ttl)) + ), + inventory_stale_ttl_seconds=_ttl_from_config( + "IN_TRANSIT_TRANSFER_INVENTORY_STALE_TTL_SECONDS", DEFAULT_INVENTORY_STALE_TTL_SECONDS, + ), + ) def get_transfer_dependencies() -> TransferDeps: diff --git a/backend/app/services/in_transit_transfer/evidence_sync.py b/backend/app/services/in_transit_transfer/evidence_sync.py index 015eedf7..6f456692 100644 --- a/backend/app/services/in_transit_transfer/evidence_sync.py +++ b/backend/app/services/in_transit_transfer/evidence_sync.py @@ -3,16 +3,22 @@ 用途:收料证据同步——把来源最新可用收料文件解析为调拨待办行(文件落地即写, 主链路),并提供「行版本戳 vs 最新文件 sha」的对齐入口(匹配/重查兜底)。 依赖:file_parser / invoice_aggregator / transfer_type / source_file_status / - matching_service(_item_evaluated_sha 复用)/ models / audit。 -逻辑:一次解析三分类写入——文件里有、本地没有 → 插入待查行;有且 sha 未变 → + matching_service(_item_evaluated_sha、_latest_usable_report_file 复用)/ + contracts / models / audit。 +逻辑:一次解析写入——文件里有、本地没有 → 插入待查行;有且 sha 未变 → 整行跳过(幂等,不续新鲜度);sha 变了证据没变 → 刷新名称/规格展示值并只换 版本戳;证据变了(数量/批号/仓库)→ 刷新证据并重置回待查(旧库存是对旧数量 - 查的,作废);消失标记行复现 → 无论证据变化与否无条件恢复待查(防复现行卡死 - 隐藏);文件里消失 → blocked_file_removed 且换戳到最新 sha(保证对齐入口 - row_shas 收敛直通)。全程零外部调用(不查 ERP、不触发 RPA);终态行绝不触碰, - 终态四元组入去重圈——同文件重落地不复活已执行行(防二次真实调拨); + 查的,作废);历史残留 blocked_file_removed 行复现 → 无论证据变化与否无条件 + 恢复待查(防御路径,2026-09-28 起同步不再新产生该码);缺席存续(只换版本戳 + 到最新文件 sha,状态与结果码原样保留——收料 RPA 非全量导出,缺席≠删除;行 + 复现时经 STEP 2 正常刷新)。全程零外部调用(不查 ERP、不触发 RPA);终态行 + 绝不触碰,终态四元组入去重圈——同文件重落地不复活已执行行(防二次真实调拨); 不 commit 只 flush(提交归调用方:落地桥自行 commit,匹配/重查随主事务)。 13 状态冻结契约内表达待查态:status='matching' + result_code='pending_stock_check'。 + 【解析失败分层 2026-09-29】同步成功 = 当前可用文件解析成功 → 清除其解析失败 + 标记(parse_failed 三列置空,投影恢复 ready);桥入口同步失败先 rollback + (保持桥隔离),仅 schema 类解析失败(TRANSFER_FILE_SCHEMA_INVALID / + ReceiptFileSchemaError)把失败事实独立 commit 落到当前可用文件上。 """ from __future__ import annotations @@ -24,14 +30,20 @@ from app import db from app.models import TransferInvoiceItem from app.services.in_transit_transfer import status as status_machine from app.services.in_transit_transfer.audit import build_transfer_audit_event -from app.services.in_transit_transfer.file_parser import parse_movement_rows +from app.services.in_transit_transfer.contracts import TRANSFER_FILE_SCHEMA_INVALID +from app.services.in_transit_transfer.file_parser import ReceiptFileSchemaError, parse_movement_rows from app.services.in_transit_transfer.invoice_aggregator import aggregate_invoices from app.services.in_transit_transfer.matching_service import ( RESULT_FILE_REMOVED, RouteNotResolvedError, _item_evaluated_sha, + _latest_usable_report_file, +) +from app.services.in_transit_transfer.source_file_status import ( + clear_receipt_parse_failure, + record_receipt_parse_failure, + resolve_source_file_status, ) -from app.services.in_transit_transfer.source_file_status import resolve_source_file_status from app.services.in_transit_transfer.transfer_type import ( TransferType, filter_invoices_for_type, @@ -61,20 +73,25 @@ class SyncOutcome: inserted: int = 0 # 文件有、本地无 → 插入待查行 refreshed: int = 0 # sha 变了、业务值没变 → 只换版本戳,状态保留 reset_pending: int = 0 # 业务值变了 → 刷新值 + 重置待查(旧库存作废) - removed: int = 0 # 文件里消失 → blocked_file_removed + absent_kept: int = 0 # 文件里缺席 → 换戳保留状态(存续:缺席≠删除,2026-09-28) skipped: int = 0 # sha 未变的幂等跳过;终态四元组重落地亦计入(不复活) def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetime) -> SyncOutcome | None: """解析来源最新可用收料文件并三分类写入待办行(零外部调用,flush 不 commit)。 + 【解析失败分层 2026-09-29】成功返回前清除当前可用文件的解析失败标记 + (parse_failed 三列置空,来源投影恢复 ready)——能走到成功返回即代表该 + 文件已成功解析;无标记时为 no-op。 + Args: source_code: 来源实例编码。 deps: TransferDeps(只用 file_repository 与 route_resolver)。 business_date: 业务日期(文件仓库「当天抓取」新鲜度口径)。 now: 新鲜度基准(显式续 updated_at,执行门禁展示依据)。 Returns: - SyncOutcome;来源无可用文件(未抓取/已过期/已清理)返回 None。 + SyncOutcome;来源无可用文件(未抓取/已过期/已清理)返回 None(该分支 + 不触碰解析失败标记——没有成功解析的事实不得清除失败标记)。 """ ready = deps.file_repository.latest_ready_file(source_code=source_code, business_date=business_date) if ready is None: @@ -112,7 +129,7 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim ).all() } - counters = {"inserted": 0, "refreshed": 0, "reset_pending": 0, "removed": 0, "skipped": 0} + counters = {"inserted": 0, "refreshed": 0, "reset_pending": 0, "absent_kept": 0, "skipped": 0} incoming_keys: set[tuple] = set() # [STEP 2] 文件内单逐张三分类:跳过 / 插入 / 刷新+重置。 @@ -166,10 +183,10 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim )) counters["inserted"] += 1 continue - # [Important② 复现行] 消失标记行(blocked_file_removed)重新出现在最新 - # 文件:无论证据变化与否都必须恢复待查态——其历史解释(文件里消失)已 - # 失效;若只换戳不恢复,行卡在 blocked 且对齐入口直通,永久隐藏。 - # 非终态行恢复不违反终态冻结。 + # [Important② 复现行] 历史残留消失标记行(blocked_file_removed)重新出现 + # 在最新文件:无论证据变化与否都必须恢复待查态——其历史解释(文件里消失) + # 已失效;若只换戳不恢复,行卡在 blocked 且对齐入口直通,永久隐藏。 + # 非终态行恢复不违反终态冻结。历史残留行防御(2026-09-28 起同步不再新产生该码)。 restored_from_removed = row.result_code == RESULT_FILE_REMOVED # [版本戳] 行随最新文件版本刷新(复现行与普通行同路径换新戳,对齐入口 # 据此收敛直通)。 @@ -195,27 +212,32 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim row.result_code = SYNC_RESULT_PENDING row.result_message = None row.external_quantity = None # 旧库存对旧数量,作废待重查 + # [库存查得时刻] 库存作废即置空取数时刻(不变式:本字段=当前 + # external_quantity 的取数时间;NULL=无库存数据,stale 不判定)。 + row.inventory_checked_at = None counters["reset_pending"] += 1 else: counters["refreshed"] += 1 + # refreshed/absent_kept 只换文件版本戳——本分支不续期 inventory_checked_at + #(2026-09-29 起 stale 判定时钟,换戳≠查过库存),仅 updated_at 照常续期。 row.updated_at = now - # [STEP 4] 文件里消失的非终态行 → blocked_file_removed(终态行不在 by_key,绝不触碰)。 + # [STEP 4] 文件里缺席的非终态行 → 存续处理(2026-09-28 语义升级):收料 RPA + # 导出非全量,缺席≠删除(行业存续原则)——保留原 status/result_code/message, + # 只把版本戳换到最新文件 sha(保留 sheet/row_no 行定位):对齐入口 row_shas + # 收敛直通、执行门禁②继续放行(历史行不会被 TRANSFER.FILE_CHANGED 死锁)。 + # 行日后复现时 evaluated_sha≠新文件 sha,自然走 STEP 2 刷新/重置分支;真实 + # 删除由人工关闭兜底(待处理池 3/5/7 天老化防遗忘)。终态行不在 by_key, + # 绝不触碰。 for key, row in by_key.items(): if key in incoming_keys: continue - # [版本戳] 消失标记行同样换戳到最新文件 sha(保留原 sheet/row_no 行定位, - # 只更新版本号与 sha):否则行版本戳停在旧文件,align 判据 row_shas 永不 - # 收敛为 {latest_sha},每次兜底都会空转重解析。 row.raw_lines_json = [ {**line, "file_version": ready.file_version, "file_sha256": ready.checksum} for line in (row.raw_lines_json or []) ] - row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value - row.result_code = RESULT_FILE_REMOVED - row.result_message = "receipt row removed from latest file" row.updated_at = now - counters["removed"] += 1 + counters["absent_kept"] += 1 # [STEP 5] 只 flush 不 commit:落地桥自行 commit,匹配/重查随主事务。 db.session.flush() @@ -229,10 +251,18 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim after={ "file_sha256": outcome.file_sha256, "inserted": outcome.inserted, "refreshed": outcome.refreshed, - "reset_pending": outcome.reset_pending, "removed": outcome.removed, + "reset_pending": outcome.reset_pending, "absent_kept": outcome.absent_kept, "skipped": outcome.skipped, }, )) + # [解析失败分层 2026-09-29] 同步成功 = 当前可用文件已成功解析:清除其解析 + # 失败标记(若此前失败过),来源状态投影随之恢复 ready。查询口径与 + # source_file_status 一致(_latest_usable_report_file);只 flush 不 commit, + # 提交归调用方(桥自行 commit / 匹配随主事务)。无可用 ORM 文件(Fake + # 仓库测试场景/文件已清理)时为 no-op。 + report = _latest_usable_report_file(source_code) + if report is not None and report.parse_failed_at is not None: + clear_receipt_parse_failure(report=report) return outcome @@ -296,13 +326,16 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d 【AI 触发时机】:收料 RPA 回调 success 终态落文件后由 shipping_notice.receipt_report_storage 的桥函数调用——桥是记账不是收料链路 的正确性依赖,任何异常不得向收料归档主链路传播(B3:必须自行 commit)。 + 【解析失败分层 2026-09-29】失败路径先 rollback(桥隔离),仅 schema 类 + 解析失败把失败事实(parse_failed 三列)独立 commit 落到当前可用文件上。 Args: source_code: 来源实例编码(收料单元行上的 source_code)。 business_date: 业务日期(文件仓库「当天抓取」新鲜度口径)。 now: 新鲜度基准(显式续 updated_at)。 Returns: - True=同步成功或无事可做(无可用文件);False=同步失败(已记日志)。 + True=同步成功或无事可做(无可用文件);False=同步失败(已记日志; + schema 类失败尽力把解析失败标记落库并独立提交,标记失败仅告警不影响返回)。 """ from flask import current_app @@ -315,9 +348,9 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d db.session.commit() if outcome is not None: current_app.logger.info( - "TRANSFER_EVIDENCE_SYNC source=%s inserted=%s refreshed=%s reset=%s removed=%s skipped=%s", + "TRANSFER_EVIDENCE_SYNC source=%s inserted=%s refreshed=%s reset=%s absent=%s skipped=%s", source_code, outcome.inserted, outcome.refreshed, - outcome.reset_pending, outcome.removed, outcome.skipped) + outcome.reset_pending, outcome.absent_kept, outcome.skipped) return True except Exception as exc: # noqa: BLE001 —— 桥隔离:失败仅日志(见模块 docstring「落地桥」) # [桥隔离] 为什么吞异常:桥是记账不是收料链路的正确性依赖,同步崩溃 @@ -325,6 +358,30 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d current_app.logger.warning( "TRANSFER_EVIDENCE_SYNC_FAILED source=%s error=%s", source_code, exc) db.session.rollback() + # [解析失败分层 2026-09-29] rollback 之后再写标记,避免脏会话污染写路径; + # 仅 schema 类失败(TRANSFER_FILE_SCHEMA_INVALID / ReceiptFileSchemaError) + # 落库——通用异常(网络/DB 故障等)不是文件解析问题,不落标记。标记写入后 + # 独立 commit(B3:桥自行提交;同步数据已回滚,本次 commit 只持久化失败 + # 事实),桥隔离语义保持,仍返回 False。 + # [取消息] AppError 为 dataclass(kwargs 初始化)str() 为空串:按 _matching_rows + # 同款兜底链取 message 字段,保证落库的错误信息可用于诊断。 + # 标记写入是尽力而为:查询/落库/提交若再抛异常(如 DB 抖动)也必须吞掉, + # B3(任何异常不得向收料归档主链路传播)优先于标记落库,丢失标记由下次重试补。 + try: + code = getattr(exc, "code", None) or "" + if code == TRANSFER_FILE_SCHEMA_INVALID or isinstance(exc, ReceiptFileSchemaError): + detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__ + report = _latest_usable_report_file(source_code) + if report is not None: + record_receipt_parse_failure( + report=report, + error_code=str(code or TRANSFER_FILE_SCHEMA_INVALID), + error_message=str(detail)[:2000], + ) + db.session.commit() + except Exception as mark_exc: # noqa: BLE001 —— 桥隔离:标记失败仅日志,仍返回 False + current_app.logger.warning( + "TRANSFER_PARSE_MARK_FAILED source=%s error=%s", source_code, mark_exc) return False diff --git a/backend/app/services/in_transit_transfer/execution_service.py b/backend/app/services/in_transit_transfer/execution_service.py index 79fbe2a0..f742e47e 100644 --- a/backend/app/services/in_transit_transfer/execution_service.py +++ b/backend/app/services/in_transit_transfer/execution_service.py @@ -634,6 +634,9 @@ def _recheck_stock_for_document( material_no=item.material_no, warehouse_code=route.from_warehouse, lot_no=external_lot_no(item.lot_no), ) + # [库存查得时刻] 写前复查是真实取数:无论查无/漂移/通过,随后落定的 + # external_quantity 都以本次取数为准(stale 判定时钟,见 _item_dto)。 + item.inventory_checked_at = datetime.utcnow() if row is None: # 查无账面:原位刷新最新事实(账面按 0 留痕)并移出本单。 item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value @@ -1248,7 +1251,8 @@ def get_run(run_no: str) -> dict[str, Any]: """按 run_no 恢复 Run 结果(result 单号聚合/异常 + orders 调拨单清单投影)。 orders 为 D9 融合卡数据源(调拨单清单=进度=结果),结构与行集口径见 - serialize_run_orders;result.exceptions 既有口径不变。 + serialize_run_orders;result.exceptions 仅收未建单阻断行(2026-09-29 收窄, + 已建单失败/未知行的原因与动作由 orders 卡片承载,不再重复进异常区)。 """ run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first() if run is None: @@ -1285,12 +1289,22 @@ def _build_run_result(run: TransferRun) -> RunResultDTO: # T7 交接补齐:交易单位原值透传(执行结果视图 unit 不再恒空,计划 D4)。 unit=str(item.unit or ""), )) - if result not in {"success", "duplicate_success"}: + # [2026-09-29 口径收窄] exceptions 仅收「未落入任何调拨单」的阻断行 + # (如分组单冲突 group_order_unresolved):已建单的失败/未知行由 orders + # 卡片展示行级原因与动作;关闭单脱离回 ready 的行(result=executable) + # 回到待执行池,同样不算异常。Excel 异常下载(excel_export)仍走全量 + # 行集,审计口径不受本投影收窄影响。 + if ( + item.document_id is None + and result not in {"success", "duplicate_success", RESULT_EXECUTABLE} + ): exceptions.append(TransferExceptionDTO( source_code=item.source_code, invoice_no=item.invoice_no, material_no=item.material_no, reason=result, + # 行级人话原因(阻断单号等),前端优先展示、状态码标签兜底。 + message=str(item.result_message or "").strip(), facts=f"收料 {item.receipt_quantity}" + (f" / 外部系统 {item.external_quantity}" if item.external_quantity else ""), )) return RunResultDTO( @@ -1333,6 +1347,8 @@ def serialize_run_result(result: RunResultDTO) -> dict[str, Any]: "invoice_no": exc.invoice_no, "material_no": exc.material_no, "reason": exc.reason, + # 行级人话原因(2026-09-29):前端优先展示,状态码标签兜底。 + "message": exc.message, "facts": exc.facts, } for exc in result.exceptions @@ -1347,7 +1363,9 @@ def serialize_run_orders(run: TransferRun) -> list[dict[str, Any]]: (D9,无独立进度卡);逐单亮 ERP 单号与状态徽标。 核心逻辑:[STEP 1] 按 run_id 取单(复用单 run_id 指现任 Run,投影不丢), - created_at/id 升序稳定排序;[STEP 2] 每单行集取自单挂接行(document_id → + 展示序对齐可调拨明细/待处理池口径(2026-09-29 统一):收料日期 → 数据源 → + 拨出/拨入库位升序,created_at/id 兜底稳定排序(跨数据源不再按建单序出现 + 日期乱序);[STEP 2] 每单行集取自单挂接行(document_id → items,复用单新旧行全量),按 ERP 行粒度(物料+批号+拨出/拨入库位,与 _build_order_lines 同键同序)聚合:数量 Decimal 相加取 6 位小数字符串 (D14 快照口径),unit/material_name 取组内首个非空原值。 @@ -1358,16 +1376,24 @@ def serialize_run_orders(run: TransferRun) -> list[dict[str, Any]]: Returns: orders 数组(计划 Task 11 JSON 规格逐键 + T13-3 控制器裁决扩充): [{doc_no, receipt_date, from_warehouse, to_warehouse, status, - erp_document_no, error_message, lines: [{material_no, material_name, - lot_no, quantity(6 位小数字符串), unit, reason}]}]。 + erp_document_no, error_message, lines: [{invoice_no, material_no, + material_name, lot_no, quantity(6 位小数字符串), unit, reason}]}]。 行 reason 契约(框线图失败行原因展示,偏离 Task 11 五键字面属控制器裁决): 键恒出现——失败/未知行 = 组内首个非空行级 result_message,成功行/无原因为 None(前端按「reason ?? 单 error_message」展示);ERP 写入行( _build_order_lines)不携带该键,投影层专属。 """ + # [2026-09-29 排序对齐] 仅投影层展示序,建单/执行顺序(组键序)不变。 docs = ( TransferDocument.query.filter_by(run_id=run.id) - .order_by(TransferDocument.created_at.asc(), TransferDocument.id.asc()) + .order_by( + TransferDocument.receipt_date.asc(), + TransferDocument.source_code.asc(), + TransferDocument.from_warehouse.asc(), + TransferDocument.to_warehouse.asc(), + TransferDocument.created_at.asc(), + TransferDocument.id.asc(), + ) .all() ) # [Task 17 重构] 行聚合与 reason 契约统一收敛到 serializers.serialize_order diff --git a/backend/app/services/in_transit_transfer/matching_service.py b/backend/app/services/in_transit_transfer/matching_service.py index 0b755ed7..2dd903be 100644 --- a/backend/app/services/in_transit_transfer/matching_service.py +++ b/backend/app/services/in_transit_transfer/matching_service.py @@ -1,6 +1,6 @@ """在途调拨匹配服务。 -用途:编排「证据兜底对齐 → 圈行 → D+1 成熟过滤 → 路由分组批量查 外部系统 库存 → +用途:编排「证据兜底对齐 → 圈行 → T+lag 成熟过滤(默认 T+2)→ 路由分组批量查 外部系统 库存 → 严格数量比对落位 → 匹配快照与 Hash」,并支持匹配进度恢复(restore)。 依赖:evidence_sync(STEP 0 兜底对齐)/ file_preparation(缺文件 RPA 分支)/ source_file_status / capability_client / date_policy / quantity / contracts / @@ -10,13 +10,18 @@ 匹配只读 DB 行并写库存侧字段(status/result_code/result_message/ external_quantity/from_warehouse/to_warehouse/unit/updated_at), raw_lines 版本戳归 evidence_sync 所有,匹配不碰。来源实例独立处理, - 任一来源失败不阻断其他来源;当天收料不查询 外部系统;匹配 Hash 由冻结 + 任一来源失败不阻断其他来源;【失败分层 2026-09-29】路由不可解析只落 + 行级 blocked_route_not_resolved(来源保持 file_ready 不整源抬升), + align 的 schema 类解析失败把失败事实落到来源可用文件(parse_failed + 三列,record_receipt_parse_failure),投影转 parse_failed 阻止下游当 + ready 使用;当天收料不查询 外部系统;匹配 Hash 由冻结 快照复算;create_matching 只落 Run + SourceJob + Matching 留痕(行落位 已由 run_matching 完成,行归属 matching_id 保持首次创建值不迁移); restore 与可调拨明细队列按匹配 scope(scope_item_query)实时圈行; restore 匹配卡是 scope 的实时视图:按 scope 圈行并逐行装饰新鲜度 - (checked_at/stale)与文件对账(file_current),counts 亦为实时聚合, - blocked_file_removed 行不进明细与常规 counts(只进 invalid_count); + (checked_at/stale)与文件对账(file_current),counts 亦为实时聚合; + 历史残留 blocked_file_removed(2026-09-28 起不再新产生)仅过滤进 + invalid_count,不进明细与常规 counts; 行交易单位(movement 契约第 11 字段 unit)只取 ERP 库存查询返回的 stock_unit(img09,单据字段以 ERP 为唯一来源,禁用货代文件单位列): 命中库存但 ERP 未给单位 → 行级 blocked_missing_unit(拨出/拨入仓库 @@ -35,10 +40,11 @@ from sqlalchemy import func, false, or_ from app import db from app.core.errors import AppError, NotFoundError, ValidationError -from app.models import TransferInvoiceItem, TransferMatching, TransferRun +from app.models import ShippingReceiptReportFile, TransferInvoiceItem, TransferMatching, TransferRun from app.services.in_transit_transfer import status as status_machine from app.services.in_transit_transfer.audit import canonical_hash from app.services.in_transit_transfer.contracts import ( + TRANSFER_FILE_SCHEMA_INVALID, MatchingCountsDTO, MatchingItemDTO, MatchingSummaryDTO, @@ -60,7 +66,11 @@ from app.services.in_transit_transfer.file_preparation import ( ) from app.services.in_transit_transfer.movement_contract import external_lot_no from app.services.in_transit_transfer.quantity import classify_quantity_match -from app.services.in_transit_transfer.source_file_status import resolve_source_file_status +from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition +from app.services.in_transit_transfer.source_file_status import ( + record_receipt_parse_failure, + resolve_source_file_status, +) from app.services.in_transit_transfer.strategy import ( TransferStrategyPolicy, default_strategy, @@ -83,14 +93,15 @@ RESULT_INVENTORY_NOT_FOUND = "blocked_inventory_not_found" RESULT_FUTURE_DATE = "blocked_future_date" RESULT_EXTERNAL_QUERY_FAILED = "blocked_external_query_failed" RESULT_EXTERNAL_QUERY_TIMEOUT = "external_query_timeout" -# 文件新版本缺失该行(上一版本可执行、最新文件中消失)。 +# 历史残留结果码(2026-09-28 前按"文件新版本缺失该行"自动标记;存续语义上线后不再新产生,仅作历史数据防御识别)。 RESULT_FILE_REMOVED = "blocked_file_removed" # 交易单位缺失:ERP 库存行未返回单位(stock_unit 空,img09 契约恒非空——出现即 # ERP 侧数据异常):行级数据质量阻断。行在此前已完成路由解析,拨出/拨入仓库 # 已落列(可解释、可重查);blocked_ 前缀计入 blocked_count(既有 blocked_* 契约)。 RESULT_MISSING_UNIT = "blocked_missing_unit" -# 路由不可解析(2026-09-25 行级化):行落 blocked 可解释、可重查(路由配置修复后 -# 重跑匹配/重查即恢复);同时来源级 stage 仍标 failed(fail-closed 语义保留)。 +# 路由不可解析(2026-09-25 行级化;【2026-09-29 失败分层】取消来源级整源抬升): +# 行落 blocked 可解释、可重查(路由配置修复后重跑匹配/重查即恢复);来源级 +# stage 保持 file_ready(有可用文件时),失败事实只落在行上。 RESULT_ROUTE_NOT_RESOLVED = "blocked_route_not_resolved" # 匹配不触碰的行终态集合(与 evidence_sync._TERMINAL_ITEM_STATUSES 同口径): @@ -176,6 +187,36 @@ def _summary_status(sources: tuple[SourceProgressDTO, ...], counts: MatchingCoun return "success" +def _latest_usable_report_file(source_code: str) -> ShippingReceiptReportFile | None: + """返回某来源当前「可用」(当天抓取且未清理未过期)的收料归档文件,最新优先。 + + 【AI 触发时机】解析失败分层(2026-09-29)需要把失败事实写到来源当前可用 + 文件上(parse_failed 三列)、或同步成功后清除其标记时调用——查询口径与 + source_file_status.resolve_source_file_status 的可用文件判定一致 + (receipt_file_gate.usable_receipt_file_condition),防止两处口径漂移。 + + 核心逻辑:[STEP 1] 按 source_code(经 ShippingReceiptReportFile.unit_run + 关联 ShippingReceiptRpaUnitRun.source_code)+ 可用门禁过滤;[STEP 2] 按 + created_at/id 倒序取最新一份。只读不写、不 flush 不 commit。 + + Args: + source_code: 来源实例编码(收料执行单元行上的 source_code)。 + Returns: + 最新的可用 ShippingReceiptReportFile;来源无可用文件(未抓取/已失效/ + 已清理)返回 None。 + """ + return ( + ShippingReceiptReportFile.query + .join(ShippingReceiptReportFile.unit_run) + .filter( + ShippingReceiptReportFile.unit_run.has(source_code=source_code), + usable_receipt_file_condition(), + ) + .order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc()) + .first() + ) + + def run_matching( *, source_codes: list[str], @@ -192,7 +233,10 @@ def run_matching( 【语义变更 2026-09-25】本函数不再解析收料文件:行由文件落地同步(收料回调桥, 主链路)或 STEP 0 兜底对齐(备)写入 DB;本函数只做「成熟过滤 → 路由分组 批量查库存 → 数量比对落位」。来源无可用文件时保留既有 UX:触发 RPA 抓取 - 并按准备结果标来源阶段。落库写入不在此 commit(随调用方事务:create_matching + 并按准备结果标来源阶段。【失败分层 2026-09-29】路由不可解析只落行级 + blocked_route_not_resolved(来源有可用文件时 stage 保持 file_ready,不再整源 + 抬升 failed);align 的 schema 类解析失败额外把失败事实落到来源可用文件 + (parse_failed 三列)。落库写入不在此 commit(随调用方事务:create_matching 末尾统一提交 / 异步 Job handler 回写后提交)。 Args: @@ -212,7 +256,7 @@ def run_matching( raise ValidationError("source_codes is required") resolved_transfer_type = normalize_transfer_type(transfer_type) ensure_transfer_type_supported(resolved_transfer_type) - # [日期范围] 可选收料日期过滤;卡控:截止不得超出 D+1 规则(业务日期-1),起始不得晚于截止。 + # [日期范围] 可选收料日期过滤;卡控:截止不得超出成熟规则(业务日期-lag,默认 T-2),起始不得晚于截止。 range_from = parse_date(receipt_date_from) if receipt_date_from else None range_to = parse_date(receipt_date_to) if receipt_date_to else None if range_from and range_to and range_from > range_to: @@ -221,7 +265,7 @@ def run_matching( ) if range_to and range_to > eligible_receipt_date_to(business_date): raise ValidationError( - "receipt date range end exceeds D+1 maturity limit", code="TRANSFER.RECEIPT_DATE_RANGE_INVALID", + "receipt date range end exceeds receipt maturity limit", code="TRANSFER.RECEIPT_DATE_RANGE_INVALID", ) now = datetime.utcnow() @@ -250,6 +294,19 @@ def run_matching( for source_code in source_codes: if source_code in align_errors: error_code, error_message = align_errors[source_code] + # [解析失败分层 2026-09-29] 仅 schema 类解析失败把失败事实落到该来源 + # 当前可用文件(parse_failed 三列,只 flush;随 create_matching 主事务 + # 统一提交)——来源状态投影随之转 parse_failed,阻止下游把坏文件当 + # ready 使用。TRANSFER.SOURCE_MATCH_ERROR 是通用匹配层错误(网络/依赖 + # 异常等),不代表文件解析失败,不落文件标记。 + if error_code == TRANSFER_FILE_SCHEMA_INVALID: + report = _latest_usable_report_file(source_code) + if report is not None: + record_receipt_parse_failure( + report=report, + error_code=error_code, + error_message=error_message[:2000], + ) sources.append(SourceProgressDTO( source_code=source_code, stage="failed", error_code=error_code, error_message=error_message, @@ -299,25 +356,15 @@ def run_matching( )) pipeline_codes.append(source_code) - items, pending_stock_check_count, route_failed_sources = _matching_rows( + # [失败分层 2026-09-29] _matching_rows 不再回传路由失败来源集合:路由不可 + # 解析只落行级 blocked_route_not_resolved(行可解释、可重查),来源级 stage + # 保持 file_ready(有可用文件时),不再整源抬升 failed——顶栏匹配状态由行 + # blocked_count 呈现,来源错误码不再被路由问题污染。 + items, pending_stock_check_count = _matching_rows( source_codes=pipeline_codes, business_date=business_date, deps=deps, receipt_date_from=receipt_date_from, receipt_date_to=receipt_date_to, file_snapshot=file_snapshot, now=now, ) - # [来源级 fail-closed] 路由不可解析的来源整源标 failed(行级已落 - # blocked_route_not_resolved,二者同源不同层:行可解释可重查,来源状态 - # 提示配置缺漏需人工处理)。 - for failed_code in route_failed_sources: - sources = [ - SourceProgressDTO( - source_code=stage.source_code, stage="failed", - file_no=stage.file_no, file_version=stage.file_version, - checksum=stage.checksum, - error_code=ROUTE_NOT_RESOLVED_CODE, - error_message=f"route not resolved for source {stage.source_code}", - ) if stage.source_code == failed_code else stage - for stage in sources - ] # [失效行计数] 同口径独立计数:blocked_file_removed 行不进明细与常规 counts, # 只以 invalid_count 透出(范围过滤与 _matching_rows 一致)。 @@ -401,13 +448,15 @@ def _matching_rows( receipt_date_to: str | None, file_snapshot: dict[str, Any], now: datetime, -) -> tuple[list[MatchingItemDTO], int, set[str]]: +) -> tuple[list[MatchingItemDTO], int]: """对 scope 内全部非终态非失效行执行「成熟过滤→路由分组批量查库存→落位」。 【2026-09-25】替代旧 _matching_invoices(按文件 Invoice 内存匹配):行已在 DB(evidence_sync 落地),本函数只写库存侧字段(status/result_code/ result_message/external_quantity/from_warehouse/to_warehouse/unit/ updated_at);raw_lines 版本戳归 evidence_sync 所有,匹配不碰。 + 【失败分层 2026-09-29】路由不可解析只落行级 blocked_route_not_resolved, + 不再回传失败来源集合(run_matching 不再整源抬升 failed)。 Args: source_codes: 本轮有可用文件的来源(无文件来源不圈行,行保持既有状态)。 @@ -417,9 +466,8 @@ def _matching_rows( file_snapshot: {source_code: 文件留痕}(行 DTO 文件对账装饰输入)。 now: 落位时间(updated_at 新鲜度基准)。 Returns: - (items DTO 列表, pending_count, route_failed_sources)——pending_count= - 落位前的待查行数(counts 桶);route_failed_sources=路由不可解析的来源 - 集合(run_matching 据此整源标 failed)。 + (items DTO 列表, pending_count)——pending_count=落位前的待查行数 + (counts 桶)。 """ # 延迟引用(evidence_sync 顶层反向导入本模块,模块级互相引用会循环导入)。 from app.services.in_transit_transfer.evidence_sync import SYNC_RESULT_PENDING @@ -427,7 +475,7 @@ def _matching_rows( query = TransferInvoiceItem.query.filter( TransferInvoiceItem.source_code.in_(source_codes), TransferInvoiceItem.status.not_in(_SYNC_TERMINAL_STATUSES), - # 失效行(文件新版本消失)不参与匹配,也不进明细(invalid_count 单独计数)。 + # 失效行(历史残留 blocked_file_removed 行防御过滤)不参与匹配,也不进明细(invalid_count 单独计数)。 or_(TransferInvoiceItem.result_code.is_(None), TransferInvoiceItem.result_code != RESULT_FILE_REMOVED), ) @@ -435,14 +483,19 @@ def _matching_rows( query = query.filter(TransferInvoiceItem.receipt_date >= str(receipt_date_from)) if receipt_date_to: query = query.filter(TransferInvoiceItem.receipt_date <= str(receipt_date_to)) + # [统一排序] 收料日期(空值最后)→ 数据源 → Invoice → 创建时间:与可调拨 + # 明细队列/待处理池同口径的业务稳定键(2026-09-29 统一),行不因重查/恢复跳位。 scope_rows_all = query.order_by( - TransferInvoiceItem.receipt_date.asc(), TransferInvoiceItem.id.asc(), + TransferInvoiceItem.receipt_date.asc().nulls_last(), + TransferInvoiceItem.source_code.asc(), + TransferInvoiceItem.invoice_no.asc(), + TransferInvoiceItem.created_at.asc(), + TransferInvoiceItem.id.asc(), ).all() # [STEP 1] 成熟过滤与路由解析(不查询):未成熟/未来日期直接落位;成熟行 # 逐行重解析路由(配置可能已变:以本次解析值为准,执行期写前复查兜底漂移)。 pending_count = 0 - route_failed_sources: set[str] = set() matured: list[tuple[TransferInvoiceItem, RouteMapping]] = [] output: list[MatchingItemDTO] = [] for row in scope_rows_all: @@ -454,10 +507,10 @@ def _matching_rows( if maturity == MATURITY_NOT_MATURED: row.status = status_machine.TransferStatus.NOT_MATURED.value row.result_code = RESULT_NOT_MATURED - row.result_message = "receipt not matured until next business day" + row.result_message = f"receipt not matured before {eligible_receipt_date_to(business_date).isoformat()}" row.updated_at = now output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now, - int(deps.strategy.confirm_ttl_seconds))) + int(deps.strategy.inventory_stale_ttl_seconds))) continue if maturity == MATURITY_FUTURE: row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value @@ -465,7 +518,7 @@ def _matching_rows( row.result_message = "future receipt date" row.updated_at = now output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now, - int(deps.strategy.confirm_ttl_seconds))) + int(deps.strategy.inventory_stale_ttl_seconds))) continue try: route = deps.route_resolver.resolve( @@ -473,15 +526,16 @@ def _matching_rows( warehouse_code=row.receipt_warehouse_code or "", ) except RouteNotResolvedError: - # [2026-09-25 行级化] 路由不可解析:行落 blocked(可解释、可重查), - # 来源级 stage 由调用方标 failed;不炸整批(原「来源级中断」语义)。 + # [2026-09-25 行级化 / 2026-09-29 失败分层] 路由不可解析:行落 + # blocked(可解释、可重查);来源级 stage 保持 file_ready 不整源 + # 抬升(失败事实只在行上,匹配卡顶栏由 blocked_count 呈现); + # 不炸整批(原「来源级中断」语义)。 row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value row.result_code = RESULT_ROUTE_NOT_RESOLVED row.result_message = f"route not resolved for source {row.source_code}" row.updated_at = now - route_failed_sources.add(row.source_code) output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now, - int(deps.strategy.confirm_ttl_seconds))) + int(deps.strategy.inventory_stale_ttl_seconds))) continue row.from_warehouse, row.to_warehouse = route.from_warehouse, route.to_warehouse matured.append((row, route)) @@ -512,7 +566,7 @@ def _matching_rows( row.result_message = "external query timeout" row.updated_at = now output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now, - int(deps.strategy.confirm_ttl_seconds))) + int(deps.strategy.inventory_stale_ttl_seconds))) continue except Exception as exc: # noqa: BLE001 —— 网关/绑定层故障降级为整组阻断,不炸整来源 # [语义] 绑定缺失、连接失败等基础设施故障是环境问题而非业务阻断: @@ -524,7 +578,7 @@ def _matching_rows( row.result_message = f"external query failed: {detail}" row.updated_at = now output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now, - int(deps.strategy.confirm_ttl_seconds))) + int(deps.strategy.inventory_stale_ttl_seconds))) continue for row, route in entries: stock_row = stock.lookup_row( @@ -538,6 +592,8 @@ def _matching_rows( row.result_code = RESULT_INVENTORY_NOT_FOUND row.result_message = "external inventory not found" row.external_quantity = "0" + # [库存查得时刻] 查无记录也是一次真实取数(按 0 落痕)。 + row.inventory_checked_at = now row.unit = "" else: stock_unit = (stock_row.stock_unit or "").strip() @@ -549,10 +605,12 @@ def _matching_rows( row.result_code = RESULT_MISSING_UNIT row.result_message = "external inventory unit is missing" row.external_quantity = str(stock_row.quantity) + row.inventory_checked_at = now row.unit = "" else: match = classify_quantity_match(Decimal(row.receipt_quantity), stock_row.quantity) row.external_quantity = str(stock_row.quantity) + row.inventory_checked_at = now row.unit = stock_unit if match == RESULT_EXECUTABLE: row.status = status_machine.TransferStatus.READY_TO_EXECUTE.value @@ -564,8 +622,8 @@ def _matching_rows( row.result_message = "strict quantity mismatch" row.updated_at = now output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now, - int(deps.strategy.confirm_ttl_seconds))) - return output, pending_count, route_failed_sources + int(deps.strategy.inventory_stale_ttl_seconds))) + return output, pending_count def _generate_no(prefix: str, business_date: str) -> str: @@ -577,9 +635,10 @@ def _generate_no(prefix: str, business_date: str) -> str: def _item_evaluated_sha(item: TransferInvoiceItem) -> str | None: """读取行的文件版本戳(评估该行时所用的收料文件 checksum)。 - 用途:消失行标记(create_matching)与文件对账(restore 展示 / execute_items - 执行门禁②)据此判断"行的评估版本是否仍是最新文件版本"。 - 两个消费方对 None(未知版本)口径不同: + 用途:文件对账(restore 展示 / execute_items 执行门禁②)据此判断 + "行的评估版本是否仍是最新文件版本"。2026-09-28 起不再用于 + 消失行标记(blocked_file_removed 仅历史残留防御,匹配侧只过滤/ + invalid_count)。两个消费方对 None(未知版本)口径不同: - restore 展示:None → file_current=False(仅展示不可执行原因,不阻断); - execute_items 门禁②:None 按"评估版本缺失"fail-closed 拒绝执行 (TRANSFER.FILE_CHANGED),宁可误拒也不按过期文件写 ERP。 @@ -610,9 +669,10 @@ def create_matching( 【语义变更 2026-09-25】行落位已全部由 run_matching 完成(证据同步落地 + 库存比对落位),本函数只负责留痕:Run / 来源级 SourceJob / Matching 记录 - (scope / file_snapshot / counts / Hash)。不再做「解析→upsert→消失行标记」 - ——消失行标记(blocked_file_removed)归 evidence_sync;行归属 matching_id - 保持首次创建值(原地刷新语义),重复匹配不迁移、不累加行。 + (scope / file_snapshot / counts / Hash)。不再做「解析→upsert→消失行标记」。 + 【2026-09-28】evidence_sync 对缺席行改为存续只换戳,不再新产生 + blocked_file_removed(该码仅历史残留防御;匹配侧过滤/invalid_count); + 行归属 matching_id 保持首次创建值(原地刷新语义),重复匹配不迁移、不累加行。 Args: source_codes / business_date / deps: 同 run_matching。 @@ -722,14 +782,14 @@ def restore_matching( 匹配卡是 scope 的实时视图:明细不读 matching.items 行归属关系(行归属与 匹配解耦后,"这份匹配覆盖哪些行"由 scope 重新圈定),counts 亦按 scope 行 - 实时聚合;blocked_file_removed 行不进明细与常规 counts(只计入 - counts.invalid_count,2026-09-25);estimated_* 与 expires_at / + 实时聚合;历史残留 blocked_file_removed(2026-09-28 起不再新产生)不进 + 明细与常规 counts(只计入 counts.invalid_count);estimated_* 与 expires_at / matching_hash 沿用匹配记录留痕展示。 Args: matching_id: 匹配编号(MTG-...)。 deps: 注入依赖(缺省内部取 deps.get_transfer_dependencies();restore - 只读 strategy.confirm_ttl_seconds,不产生外部调用)。 + 只读 strategy.inventory_stale_ttl_seconds,不产生外部调用)。 now: 新鲜度判定基准时间(缺省 datetime.utcnow(),测试注入冻结时钟)。 Returns: {"summary": {...}, "items": [...], "sources": [...]};items 每行额外装饰 @@ -742,7 +802,7 @@ def restore_matching( from app.services.in_transit_transfer import deps as transfer_deps deps = transfer_deps.get_transfer_dependencies() moment = now or datetime.utcnow() - ttl_seconds = int(deps.strategy.confirm_ttl_seconds) + ttl_seconds = int(deps.strategy.inventory_stale_ttl_seconds) matching = db.session.query(TransferMatching).filter_by( matching_no=str(matching_id).strip() @@ -752,13 +812,22 @@ def restore_matching( # [STEP 1] 按 scope 实时圈行(来源 + 收料日期区间 + 调拨类型前缀),行归属 # (matching_id)不参与——同一批行可被多份同 scope 匹配同时看到。 + # [统一排序] 与可调拨明细队列/待处理池同口径(2026-09-29 统一), + # 同一批行在匹配卡/可调拨明细/待处理池三处视图顺序一致。 rows_all = ( scope_item_query(matching) - .order_by(TransferInvoiceItem.invoice_no.asc(), TransferInvoiceItem.id.asc()) + .order_by( + TransferInvoiceItem.receipt_date.asc().nulls_last(), + TransferInvoiceItem.source_code.asc(), + TransferInvoiceItem.invoice_no.asc(), + TransferInvoiceItem.created_at.asc(), + TransferInvoiceItem.id.asc(), + ) .all() ) - # [失效行分层]【2026-09-25】blocked_file_removed 行已出清:不进明细与常规 - # counts(与 _matching_rows 圈行口径一致),只计入 invalid_count。 + # [失效行分层]【2026-09-28】历史残留 blocked_file_removed(存续语义上线后 + # 不再新产生)防御过滤:不进明细与常规 counts(与 _matching_rows 圈行 + # 口径一致),只计入 invalid_count。 from app.services.in_transit_transfer.evidence_sync import SYNC_RESULT_PENDING invalid_rows = [row for row in rows_all if row.result_code == RESULT_FILE_REMOVED] @@ -874,7 +943,7 @@ def _item_dto( item: TransferInvoiceItem, latest: dict, moment: datetime, - ttl_seconds: int, + inventory_stale_ttl_seconds: int, ) -> MatchingItemDTO: """把 InvoiceItem 装饰为前端行 DTO(restore 视图与可调拨明细队列共用)。 @@ -882,13 +951,13 @@ def _item_dto( item: 明细行。 latest: 该行来源当前可用文件状态投影(resolve_source_file_status 结果)。 moment: 新鲜度判定基准时间。 - ttl_seconds: 行级 stale 展示阈值(strategy.confirm_ttl_seconds;仅驱动 - stale 徽标提示,不阻断执行——2026-09-25 TTL 门禁退役)。 + inventory_stale_ttl_seconds: stale 展示阈值(strategy.inventory_stale_ttl_seconds; + 仅驱动 stale 徽标提示,不阻断执行——2026-09-25 TTL 门禁退役)。 Returns: MatchingItemDTO(含 item_id / checked_at / stale / file_current)。 """ evaluated_sha = _item_evaluated_sha(item) - updated_at = item.updated_at + inventory_checked_at = item.inventory_checked_at return MatchingItemDTO( source_code=item.source_code, material_no=item.material_no, @@ -919,15 +988,19 @@ def _item_dto( ) for line in (item.raw_lines_json or []) ), - # [行装饰] 行级新鲜度与文件对账(均纯展示,不阻断执行): + # [行装饰] 库存时效与文件对账(均纯展示,不阻断执行): # [2026-09-25 TTL 退役] stale 仅是「库存数据已过期,请重查」展示徽标 # (原 TTL 执行门禁已删除,防错由文件版本对账 + worker 写前库存复查 - # 承担):stale=距上次评估超过展示阈值(confirm_ttl_seconds); + # 承担)。[2026-09-29 时钟换源] stale/checked_at 挂 inventory_checked_at + # (库存查得时刻,仅匹配评估/重查/写前复查写入)——原 updated_at 时钟 + # 被证据同步换戳每日续期,徽标对老行永不触发;stale=距库存取数超过 + # 展示阈值(inventory_stale_ttl_seconds),无库存数据(NULL)不判定; # file_current=行评估版本戳仍是该来源当前可用文件 sha # (无版本戳或无可用文件均视为不一致 → False)。 item_id=item.id, - checked_at=updated_at.isoformat() if updated_at else None, - stale=bool(updated_at) and (moment - updated_at).total_seconds() > ttl_seconds, + checked_at=inventory_checked_at.isoformat() if inventory_checked_at else None, + stale=bool(inventory_checked_at) + and (moment - inventory_checked_at).total_seconds() > inventory_stale_ttl_seconds, file_current=bool(evaluated_sha) and evaluated_sha == latest.get("file_sha256"), ) @@ -950,16 +1023,18 @@ def list_executable_items(*, deps: TransferDeps | None = None, now: datetime | N from app.services.in_transit_transfer import deps as transfer_deps deps = transfer_deps.get_transfer_dependencies() moment = now or datetime.utcnow() - ttl_seconds = int(deps.strategy.confirm_ttl_seconds) + ttl_seconds = int(deps.strategy.inventory_stale_ttl_seconds) - # [稳定排序] 收料日期(空值最后)→ Invoice → 创建时间:与重查/恢复等操作 - # 无关的业务键——正在处理的行不会因 updated_at 被新鲜度续期而跳位。 + # [稳定排序] 收料日期(空值最后)→ 数据源 → Invoice → 创建时间:与重查/恢复 + # 等操作无关的业务键——正在处理的行不会因 updated_at 被新鲜度续期而跳位; + # 2026-09-29 与待处理池/匹配卡视图统一为同一口径(用户按同序处理两个池子)。 rows = ( TransferInvoiceItem.query.filter( TransferInvoiceItem.status == status_machine.TransferStatus.READY_TO_EXECUTE.value, ) .order_by( TransferInvoiceItem.receipt_date.asc().nulls_last(), + TransferInvoiceItem.source_code.asc(), TransferInvoiceItem.invoice_no.asc(), TransferInvoiceItem.created_at.asc(), TransferInvoiceItem.id.asc(), diff --git a/backend/app/services/in_transit_transfer/movement_file_repository.py b/backend/app/services/in_transit_transfer/movement_file_repository.py index dfc7b839..b737c5a6 100644 --- a/backend/app/services/in_transit_transfer/movement_file_repository.py +++ b/backend/app/services/in_transit_transfer/movement_file_repository.py @@ -8,11 +8,13 @@ 逻辑:按来源取最新【当天(业务日)抓取】且未过期(未清理)的收料文件;无绑定规则、 文件缺失或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域 字段 + 溯源字段(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整 - 校验由下游 file_parser 完成。 + 校验由下游 file_parser 完成。表头别名匹配前归一化空白/换行(DSV SSRS 单元格内 + 折行如 External\\nASN #),仍以站点绑定规则别名为准,不另造硬编码模板。 """ from __future__ import annotations +import re from io import BytesIO from typing import Any, Mapping @@ -20,6 +22,20 @@ from app.services.file_assets.storage import file_asset_storage from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition +# 表头单元格内换行/多空白 → 单空格,使绑定别名与 SSRS 折行表头可精确匹配。 +_HEADER_WS_RE = re.compile(r"\s+") + + +def _normalize_header_label(value: Any) -> str: + """归一化表头/别名文本:去首尾空白,内部任意空白(含 \\n)压成单空格。 + + Args: + value: 原始表头单元格或 field_mapping 别名。 + Returns: + 归一化后的字符串;空输入返回空串。 + """ + return _HEADER_WS_RE.sub(" ", str(value or "").strip()) + class ShippingReceiptFileRepository: """真实收料/异动 ready 文件仓库(复用货代收料归档 + movement 解析规则)。""" @@ -89,9 +105,16 @@ def _extract_movement_rows( ) -> list[dict[str, Any]]: """从 xlsx 字节按 movement field_mapping 提取领域行 dict。 + 核心逻辑:定位表头行 → 别名/表头归一化后建反查表 → 逐数据行映射领域字段 + 溯源。 field_mapping: {定死领域字段 code: Excel 表头别名}(端点必须是 MOVEMENT_FIELDS 的 code)。 输出以领域字段 code 为 key 的行,并附带溯源字段(sheet=实际使用的工作表标题、 row_no=数据行在工作表中的真实 1-based 行号),供 file_parser.parse_movement_rows 校验。 + + Args: + data: xlsx 原始字节。 + field_mapping: 领域字段 → 表头别名(来自站点绑定的 movement profile)。 + sheet_name: 工作表名;空则取 active。 + header_row_index: 1-based 表头行;空则自动探测。 """ from openpyxl import load_workbook from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index @@ -114,14 +137,17 @@ def _extract_movement_rows( header_idx = idx if header_idx is None: header_idx = find_inventory_header_row_index(raw_rows) - headers = [str(c or '').strip() for c in raw_rows[header_idx]] - data_rows = [list(r) for r in raw_rows[header_idx + 1:] if r] - + # [STEP] 别名与表头均经 _normalize_header_label,抗 SSRS 单元格内换行。 header_to_code: dict[str, list[str]] = {} for code, alias in field_mapping.items(): # 一个表头别名可被多个领域字段共用(如 CRANE 单号/批号同源 ASN 列); # 反查必须是 一别名→多字段,不得互相覆盖。 - header_to_code.setdefault(str(alias).strip(), []).append(str(code).strip()) + key = _normalize_header_label(alias) + if not key: + continue + header_to_code.setdefault(key, []).append(str(code).strip()) + headers = [_normalize_header_label(c) for c in raw_rows[header_idx]] + data_rows = [list(r) for r in raw_rows[header_idx + 1:] if r] # 溯源字段:sheet 取实际使用的工作表标题;row_no 为数据行在工作表中的真实 # 1-based 行号(表头在第 header_idx+1 行,第 offset 个数据行 = header_idx+2+offset), # 使下游 RawLineRef 证据引用指向真实电子表格行,并满足 parse_movement_rows 行校验。 @@ -136,6 +162,7 @@ def _extract_movement_rows( def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str, list[str]]) -> dict[str, Any]: """把一行原始单元格按表头别名映射为定死领域字段 dict。 + headers / header_to_code 的键须已由 _normalize_header_label 归一化。 header_to_code 为 一别名→多字段 列表:共用同一表头别名的字段 (如 doc_no 与 lot_no 同源一列)各自都写入该单元格值,互不覆盖。 """ diff --git a/backend/app/services/in_transit_transfer/receipt_trigger_service.py b/backend/app/services/in_transit_transfer/receipt_trigger_service.py index 7cdcf44e..25a87aa1 100644 --- a/backend/app/services/in_transit_transfer/receipt_trigger_service.py +++ b/backend/app/services/in_transit_transfer/receipt_trigger_service.py @@ -5,8 +5,9 @@ 先落 ShippingReceiptRpaUnitRun(awaiting_rpa,回调按 callback_id 查库可达), 再装配收料 trigger unit 并调用 write_receipt_export_batch_trigger 原子写 trigger。 依赖:write_receipt_export_batch_trigger(默认 writer)、models、db。 -逻辑:来源停用/收料配置缺失/rpa_profile 缺失时 fail-closed(返回 ok=False),绝不伪造等待; - 写 trigger 失败把单元行标 failed 并 commit;写 trigger writer 可注入替身(测试)。 +逻辑:list_receipt_capable_source_codes 供排程 source_codes 留空时的缺省范围; + 一源一单元,query_parameters 原样下发;来源停用/收料配置缺失/rpa_profile 缺失时 + fail-closed;写 trigger 失败把单元行标 failed 并 commit。 """ from __future__ import annotations @@ -22,9 +23,11 @@ RouteTriggerWriter = Callable[..., str | None] def _build_trigger_unit( *, source_code: str, business_date: str, reason: str, ) -> dict[str, Any]: - """装配单来源收料 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。""" + """装配单来源收料 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。 + + 核心逻辑:一源一单元,query_parameters 原样下发;空条件表示 Worker 走页面默认。 + """ from app.models import ShippingInventorySource, ShippingReceiptReportConfig - from app.services.shipping_notice.receipt_rpa import receipt_unit_parameters, receipt_warehouse_values source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() if source is None: @@ -35,22 +38,22 @@ def _build_trigger_unit( profile = source.rpa_profile if profile is None or not profile.enabled: raise RuntimeError(f'receipt source profile unavailable: {source_code}') - # Warehouse 条件即逐仓拆分维度:按需触发取第一个仓,单元快照剥离 Warehouse 条件。 - warehouses = receipt_warehouse_values(config) if source.connector_type == 'dbs' else [None] - warehouse_id = str(warehouses[0]) if warehouses and warehouses[0] else None + query_parameters = [ + dict(item) for item in (config.query_parameters_json or []) if isinstance(item, dict) + ] snapshot = { 'config_id': config.id, 'config_version': config.config_version, 'connector_type': source.connector_type, 'report_path_json': config.report_path_json or {}, - 'query_parameters_json': receipt_unit_parameters(config), - 'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id, + 'query_parameters_json': query_parameters, + 'warehouse_id': None, 'rpa_profile_id': source.rpa_profile_id, } return { 'inventory_source_id': source.id, 'callback_id': f'receipt:{uuid.uuid4().hex}', 'source_code': source.source_code, 'connector_type': source.connector_type, - 'warehouse_id': warehouse_id, + 'warehouse_id': None, 'rpa_profile_id': profile.id, 'rpa_profile_code': profile.profile_code, 'login_url': profile.login_url, @@ -60,13 +63,31 @@ def _build_trigger_unit( '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 []), + 'query_parameters_json': list(query_parameters), 'config_snapshot': snapshot, 'business_date': business_date, 'reason': reason, } +def list_receipt_capable_source_codes() -> list[str]: + """列出可产出收料文件的启用来源实例(enabled 库存源 + 已配置收料报表)。 + + 用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——收料文件只能 + 来自已配置收料报表的站点,与货代收料 RPA 排程的站点口径保持一致。 + Returns: + 按 source_code 排序的来源编码列表;无匹配站点时为空列表。 + """ + from app import db + from app.models import ShippingInventorySource, ShippingReceiptReportConfig + + rows = db.session.query(ShippingInventorySource.source_code).join( + ShippingReceiptReportConfig, + ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id, + ).filter(ShippingInventorySource.enabled.is_(True)).order_by(ShippingInventorySource.source_code).all() + return [str(code) for (code,) in rows] + + def trigger_receipt_rpa( *, source_code: str, diff --git a/backend/app/services/in_transit_transfer/recovery_service.py b/backend/app/services/in_transit_transfer/recovery_service.py index e852396c..2bca26b2 100644 --- a/backend/app/services/in_transit_transfer/recovery_service.py +++ b/backend/app/services/in_transit_transfer/recovery_service.py @@ -2,8 +2,9 @@ 用途:下一排程对可恢复异常项用最新文件与 外部系统 重新匹配并创建新 Attempt; result_unknown / manually_closed / success 不自动写入。 -依赖:models、retry_service._recheck_item、TransferDeps。 -逻辑:恢复仅查询/匹配,不写 外部系统;每次恢复新 Attempt,旧 Attempt 不变。 +依赖:models、retry_service._recheck_items_batch、TransferDeps。 +逻辑:恢复仅查询/匹配,不写 外部系统;每次恢复新 Attempt,旧 Attempt 不变; + 库存查询与人工重查共用按组织批量核心(一组一次外部调用,2026-09-29)。 """ from __future__ import annotations @@ -14,7 +15,7 @@ from app import db from app.models import TransferInvoiceItem from app.services.in_transit_transfer import status as status_machine from app.services.in_transit_transfer.matching_service import TransferDeps -from app.services.in_transit_transfer.retry_service import _recheck_item +from app.services.in_transit_transfer.retry_service import _recheck_items_batch @dataclass @@ -45,6 +46,7 @@ def run_daily_recovery(*, business_date: str, deps: TransferDeps) -> RecoveryOut status_machine.TransferStatus.MANUALLY_CLOSED.value, ]), ).all() + eligible: list[TransferInvoiceItem] = [] for item in items: if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value: # 只读隔离:不查询、不写入、不创建 Attempt。 @@ -54,13 +56,19 @@ def run_daily_recovery(*, business_date: str, deps: TransferDeps) -> RecoveryOut # 永久排除。 outcome.skipped_manually_closed += 1 continue - before_attempt = item.attempt_no - new_status = _recheck_item(item, deps=deps, request_id=None) - if new_status == status_machine.TransferStatus.READY_TO_EXECUTE.value: - outcome.recovered_count += 1 + eligible.append(item) + # [按组织批量查询] 恢复与人工重查共用批量核心:每组织一次外部调用,行级 + # Attempt/审计/新鲜度语义与人工重查完全一致;路由解析失败行未建 Attempt、 + # 保持阻断原状(计入 still_blocked)。 + statuses, _row_errors = _recheck_items_batch(eligible, deps=deps, request_id=None) + for item in eligible: + if item.id in statuses: + outcome.attempts_created += 1 + if statuses[item.id] == status_machine.TransferStatus.READY_TO_EXECUTE.value: + outcome.recovered_count += 1 + else: + outcome.still_blocked_count += 1 else: outcome.still_blocked_count += 1 - if item.attempt_no > before_attempt: - outcome.attempts_created += 1 db.session.commit() return outcome diff --git a/backend/app/services/in_transit_transfer/retry_service.py b/backend/app/services/in_transit_transfer/retry_service.py index aded4063..12cd4b31 100644 --- a/backend/app/services/in_transit_transfer/retry_service.py +++ b/backend/app/services/in_transit_transfer/retry_service.py @@ -7,9 +7,14 @@ 重查即续新鲜度——每次重检显式刷新行 updated_at(执行门禁行级 TTL 的续期机制); 重查前置兜底对齐(STEP 0,同 run_matching):两个批量重查入口先 align_scope_rows 补救落地同步失败/迟到的证据,再圈行重查(待处理池后门不得基于过期证据作答); + 库存查询按组织批量(2026-09-29):全部重查/恢复/单据重试入口统一经 + _recheck_items_batch——路由解析按 external_org 分组,一组一次 + capabilities.query_stock(与执行链写前复查同形态),行级评估 / Attempt / + 审计 / 新鲜度续期保持单行粒度;N 行重查 = 每组织 1 次外部调用, + 禁止回退逐行单查(N 行 N 次调用会打崩外部系统); file_removed 失效行不可重查:匹配号圈行路径由 scope 谓词排除,按 id 直取与 - 单行入口由 retry_item 的 result_code 兜底拒绝(拒绝逻辑单点闭环,消失证据 - 不可用旧库存翻回可执行); + 单行入口由资格门禁 _gate_retryable_item 兜底拒绝(拒绝逻辑单点闭环,消失 + 证据不可用旧库存翻回可执行); 交易单位唯一来源=ERP 库存行 stock_unit(img09):重查命中且数量一致但 ERP 未给单位 → blocked_missing_unit(不落 ready,单位不得以文件值顶替)。 """ @@ -36,6 +41,7 @@ from app.services.in_transit_transfer.matching_service import ( RESULT_EXECUTABLE, RESULT_FILE_REMOVED, RESULT_MISSING_UNIT, + RouteMapping, TransferDeps, scope_item_query, ) @@ -56,86 +62,98 @@ _RETRYABLE_STATUSES = { logger = logging.getLogger(__name__) -def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id: str | None) -> str: - """对单个异常项重新查询 外部系统 并更新状态(创建新 Attempt)。 +def _gate_retryable_item(item_id: int) -> TransferInvoiceItem: + """单行重查资格门禁(单行与按 id 批量入口共用的拒绝单点)。 + Args: + item_id: TransferInvoiceItem.id。 Returns: - 重检后的 item 状态。 + 通过门禁的行(本函数不触碰任何字段)。 + Raises: + NotFoundError: item 不存在。 + ValidationError: result_unknown 只读 / 状态不可重试 / file_removed 行 + 不可重查(消失证据不可恢复:证据行的源单已从最新收料文件中消失, + 重查只会用外部系统旧库存把行翻回可执行,唯一出口=人工关闭 / + 等重新同步恢复该行)。 """ - route = deps.route_resolver.resolve( - source_code=item.source_code, invoice_no=item.invoice_no, - warehouse_code=item.receipt_warehouse_code or "", - ) - # [口径] 重查按当前路由配置发查询,行上仓库字段同步刷新为本次解析值—— - # 查询与后续执行写路径必须用同一仓库值:行上旧值可能来自更早配置(路由 - # 已漂移),也可能为空(如 blocked_missing_unit 行在路由解析前被阻断)。 - if (item.from_warehouse or "") != route.from_warehouse or (item.to_warehouse or "") != route.to_warehouse: - item.from_warehouse = route.from_warehouse - item.to_warehouse = route.to_warehouse - operation_id = f"op-{uuid.uuid4().hex[:12]}" - receipt_qty = Decimal(item.receipt_quantity) - item.attempt_no += 1 - before_status = item.status - attempt = TransferAttempt( - item_id=item.id, attempt_no=item.attempt_no, kind="external_query", - status="running", operation_id=operation_id, - request_snapshot_json={ - "invoice_no": item.invoice_no, "external_org": route.external_org, - "from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse, - "quantity": str(receipt_qty), - }, - ) - db.session.add(attempt) + item = db.session.get(TransferInvoiceItem, item_id) + if item is None: + raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND") + if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value: + raise ValidationError("result_unknown is read-only; follow manual verification SOP", code="TRANSFER_RESULT_UNKNOWN") + if item.status not in _RETRYABLE_STATUSES: + raise ValidationError(f"item status {item.status} is not retryable", code="TRANSFER.RETRY_NOT_ALLOWED") + # [兜底] file_removed 行拒绝重查:匹配号圈行路径(requery_items)已在 scope + # 谓词排除失效行,但按 id 直取(requery_items_by_ids)与单行入口绕过该谓词 + # ——拒绝逻辑只落在此单点,三条入口同时闭环。 + if item.result_code == RESULT_FILE_REMOVED: + raise ValidationError( + "removed rows cannot be requeried; close manually or wait for re-sync", + code="TRANSFER.RETRY_NOT_ALLOWED", + ) + return item + + +def _degrade_recheck_row(item: TransferInvoiceItem, *, attempt: TransferAttempt, + before_status: str, detail: str, + operation_id: str, request_id: str | None) -> str: + """行级降级收口:外部查询故障 → blocked_external_query_failed + 原因。 + + 与单行历史语义一致:网关/绑定故障不向调用方抛基础设施异常(避免全局错误 + 弹窗);本次失败也是一次真实评估,行级 TTL 照常续期。 + + Args: + item: 重查行(Attempt 已创建并 flush)。 + attempt: 该行本次 external_query Attempt(running 态)。 + before_status: 重查前状态(审计 before)。 + detail: 外部异常摘要(落 result_message 与审计)。 + operation_id / request_id: 审计上下文(查询 operation_id 组内共享)。 + Returns: + 降级后的行状态。 + """ + item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value + item.result_code = RESULT_EXTERNAL_QUERY_FAILED + item.result_message = f"external query failed: {detail}" + attempt.status = "failed" + attempt.completed_at = datetime.utcnow() + # [行级 TTL 续期] 降级也是一次真实评估:显式刷新 updated_at(执行门禁 + # TTL 依据),不依赖 attempt_no 变更间接触发 onupdate 的隐式行为。 + item.updated_at = datetime.utcnow() + db.session.add(build_transfer_audit_event( + event_type="TRANSFER_ITEM_RECHECKED", + aggregate_type="transfer_item", + aggregate_id=str(item.id), + run_no=item.run.run_no if item.run else None, + invoice_no=item.invoice_no, + item_id=str(item.id), + attempt_no=item.attempt_no, + actor_type="worker", + request_id=request_id, + operation_id=operation_id, + result="failure", + before={"status": before_status}, + after={"status": item.status, "attempt_no": item.attempt_no, "error": detail}, + )) db.session.flush() - # [降级] 与 matching 逐单语义一致:外部系统网关/绑定故障(如集成连接器缺绑定 - # BindingNotFoundError)记为该行 blocked_external_query_failed + 原因, - # 不中断批量重查、不向调用方抛基础设施异常(避免全局错误弹窗)。 - try: - # [外部形态] 查询目标与回查同用 WTP→HOW 派生批号(movement_contract.external_lot_no)。 - stock = deps.capabilities.query_stock( - operation_id=operation_id, external_org=route.external_org, - targets=[StockTarget( - material_no=item.material_no, warehouse_code=route.from_warehouse, - lot_no=external_lot_no(item.lot_no), - )], - ) - stock_row = stock.lookup_row( - material_no=item.material_no, warehouse_code=route.from_warehouse, - lot_no=external_lot_no(item.lot_no), - ) - stock_qty = stock_row.quantity if stock_row is not None else None - except Exception as exc: # noqa: BLE001 - detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__ - # 降级只落 DB(result_message/审计),若再无应用日志,控制台侧完全无痕可查。 - logger.warning( - "transfer external recheck failed (degrade to blocked): invoice=%s item=%s attempt=%s error=%s", - item.invoice_no, item.id, item.attempt_no, detail, - ) - item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value - item.result_code = RESULT_EXTERNAL_QUERY_FAILED - item.result_message = f"external query failed: {detail}" - attempt.status = "failed" - attempt.completed_at = datetime.utcnow() - # [行级 TTL 续期] 降级也是一次真实评估:显式刷新 updated_at(执行门禁 - # TTL 依据),不依赖 attempt_no 变更间接触发 onupdate 的隐式行为。 - item.updated_at = datetime.utcnow() - db.session.add(build_transfer_audit_event( - event_type="TRANSFER_ITEM_RECHECKED", - aggregate_type="transfer_item", - aggregate_id=str(item.id), - run_no=item.run.run_no if item.run else None, - invoice_no=item.invoice_no, - item_id=str(item.id), - attempt_no=item.attempt_no, - actor_type="worker", - request_id=request_id, - operation_id=operation_id, - result="failure", - before={"status": before_status}, - after={"status": item.status, "attempt_no": item.attempt_no, "error": detail}, - )) - db.session.flush() - return item.status + return item.status + + +def _apply_recheck_outcome(item: TransferInvoiceItem, *, attempt: TransferAttempt, + before_status: str, receipt_qty: Decimal, stock_row, + operation_id: str, request_id: str | None) -> str: + """行级评估收口:账面对照落状态/结果码/外部数量/单位,关闭 Attempt 并写审计。 + + Args: + item: 重查行(Attempt 已创建并 flush)。 + attempt: 该行本次 external_query Attempt(running 态)。 + before_status: 重查前状态(审计 before)。 + receipt_qty: 行收料数量(严格相等判定的基准)。 + stock_row: 批量查询结果中该行的账面行(StockRow);查无记录为 None。 + operation_id / request_id: 审计上下文(查询 operation_id 组内共享)。 + Returns: + 重查后的行状态。 + """ + stock_qty = stock_row.quantity if stock_row is not None else None if stock_qty is None or classify_quantity_match(receipt_qty, stock_qty) != RESULT_EXECUTABLE: item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value item.result_code = "blocked_inventory_not_found" if stock_qty is None else "blocked_quantity_mismatch" @@ -162,8 +180,12 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id: item.unit = (stock_row.stock_unit or "").strip() attempt.status = "success" attempt.completed_at = datetime.utcnow() - # [行级 TTL 续期] 重查即续新鲜度:状态落定后显式刷新 updated_at(执行门禁 - # TTL 依据),不依赖 attempt_no 变更间接触发 onupdate 的隐式行为。 + # [库存查得时刻] 重查是真实取数:三个分支(查无按 0/单位缺失/正常)落定的 + # external_quantity 都以本次取数为准,同步刷新其取数时间戳——stale 徽标 + # 判定时钟(2026-09-29 起挂本字段,不再依赖 updated_at,见 _item_dto)。 + item.inventory_checked_at = datetime.utcnow() + # [行级新鲜度续期] 重查显式刷新 updated_at(行新鲜度口径),不依赖 + # attempt_no 变更间接触发 onupdate 的隐式行为。 item.updated_at = datetime.utcnow() db.session.add(build_transfer_audit_event( event_type="TRANSFER_ITEM_RECHECKED", @@ -184,9 +206,133 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id: return item.status +def _recheck_items_batch( + items: list[TransferInvoiceItem], *, deps: TransferDeps, request_id: str | None = None, +) -> tuple[dict[int, str], dict[int, Exception]]: + """按组织批量重查核心:一组(external_org)一次 capabilities.query_stock。 + + 【AI 触发时机】:全部重查/恢复/单据重试入口(retry_item / requery_items / + requery_items_by_ids / retry_document / run_daily_recovery)圈定行集并过完 + 资格门禁后统一调用;本函数不再校验状态与 file_removed。 + + 【为什么按组织批量】重查面向整批行(可调拨清单「重查选中」可达数百行), + 逐行单查会把 N 行放大成 N 次外部调用,外部系统不可承受;外部访问按 + (料号, 仓库, 批号) 元组天然支持批量,执行链写前复查已按组织批量——本函数 + 与其同形态。行级粒度保留:评估/Attempt/审计/新鲜度续期仍逐行落库, + 单行路由解析失败只跳过该行。 + + Args: + items: 已过资格门禁的可重查行。 + deps: 注入依赖(capabilities = 外部系统网关客户端)。 + request_id: 审计上下文。 + Returns: + (statuses, row_errors): + statuses = {item_id: 重查后状态}(进入查询的行,含降级为 blocked 的行); + row_errors = {item_id: 原始异常}(路由/数量前置解析失败行:未发起查询、 + 行未被触碰、未建 Attempt;批量入口转为该行 ok=False,单行入口原样上抛 + 保持历史 fail-closed 行为)。 + """ + # [STEP 1] 行级前置解析(行级隔离):路由解析 + 收料数量解析,失败行原位 + # 跳过、不拖垮整批;行仓库字段刷新为本次解析值——查询与后续执行写路径必须 + # 用同一仓库值:行上旧值可能来自更早配置(路由已漂移),也可能为空(如 + # blocked_missing_unit 行在路由解析前被阻断)。 + resolved: list[tuple[TransferInvoiceItem, RouteMapping, Decimal]] = [] + row_errors: dict[int, Exception] = {} + for item in items: + try: + route = deps.route_resolver.resolve( + source_code=item.source_code, invoice_no=item.invoice_no, + warehouse_code=item.receipt_warehouse_code or "", + ) + receipt_qty = Decimal(item.receipt_quantity) + except Exception as exc: # noqa: BLE001 —— 行级隔离:路由漂移/缺失/脏数量只影响该行 + row_errors[item.id] = exc + logger.warning( + "transfer recheck row skipped (pre-resolve failed): invoice=%s item=%s error=%s", + item.invoice_no, item.id, str(exc).strip() or exc.__class__.__name__, + ) + continue + if (item.from_warehouse or "") != route.from_warehouse or (item.to_warehouse or "") != route.to_warehouse: + item.from_warehouse = route.from_warehouse + item.to_warehouse = route.to_warehouse + resolved.append((item, route, receipt_qty)) + + # [STEP 2] 按组织分组(同写前复查的 external_org 分组口径):同组行共享 + # 一次批量查询,N 行 = 每组织 1 次外部调用。 + groups: dict[str, list[tuple[TransferInvoiceItem, RouteMapping, Decimal]]] = {} + for entry in resolved: + groups.setdefault(str(entry[1].external_org or "").strip(), []).append(entry) + + statuses: dict[int, str] = {} + # [STEP 3] 每组织:行级 Attempt(running)→ 一次批量查询 → 行级收口(评估或 + # 降级)→ 组粒度提交(一组落库即一组持久,后续组故障不回滚已落组)。组内 + # Attempt 共享查询 operation_id,与 IntegrationCall 调用审计可互查。 + for external_org, entries in groups.items(): + operation_id = f"op-{uuid.uuid4().hex[:12]}" + attempts: dict[int, TransferAttempt] = {} + before_statuses: dict[int, str] = {} + for item, route, receipt_qty in entries: + item.attempt_no += 1 + before_statuses[item.id] = item.status + attempts[item.id] = TransferAttempt( + item_id=item.id, attempt_no=item.attempt_no, kind="external_query", + status="running", operation_id=operation_id, + request_snapshot_json={ + "invoice_no": item.invoice_no, "external_org": external_org, + "from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse, + "quantity": str(receipt_qty), + }, + ) + db.session.add(attempts[item.id]) + db.session.flush() + try: + # [外部形态] 查询目标与回查同用 WTP→HOW 派生批号(movement_contract.external_lot_no)。 + stock = deps.capabilities.query_stock( + operation_id=operation_id, external_org=external_org, + targets=[StockTarget( + material_no=item.material_no, warehouse_code=route.from_warehouse, + lot_no=external_lot_no(item.lot_no), + ) for item, route, _receipt_qty in entries], + ) + except Exception as exc: # noqa: BLE001 + # [降级] 外部系统网关/绑定故障是组级事实:组内各行统一降级为 + # blocked_external_query_failed + 原因(逐行查询时同样会全部失败, + # 语义一致只是不再慢速放大),不中断批次、不向调用方抛异常。 + detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__ + logger.warning( + "transfer recheck org query failed (degrade rows): org=%s rows=%s error=%s", + external_org, len(entries), detail, + ) + for item, route, receipt_qty in entries: + statuses[item.id] = _degrade_recheck_row( + item, attempt=attempts[item.id], before_status=before_statuses[item.id], + detail=detail, operation_id=operation_id, request_id=request_id, + ) + db.session.commit() + continue + for item, route, receipt_qty in entries: + # [外部形态] 回查键与查询目标同用派生批号(三元组精确匹配)。 + stock_row = stock.lookup_row( + material_no=item.material_no, warehouse_code=route.from_warehouse, + lot_no=external_lot_no(item.lot_no), + ) + statuses[item.id] = _apply_recheck_outcome( + item, attempt=attempts[item.id], before_status=before_statuses[item.id], + receipt_qty=receipt_qty, stock_row=stock_row, + operation_id=operation_id, request_id=request_id, + ) + db.session.commit() + return statuses, row_errors + + +def _row_error_text(exc: Exception) -> str: + """行级异常 → 用户可见错误文本(AppError 取 message,其余取 str/类名)。""" + return str(getattr(exc, "message", "") or "").strip() or str(exc).strip() or exc.__class__.__name__ + + def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_EXTERNAL_RECHECK, actor_id: int | None = None, request_id: str | None = None) -> dict: - """人工重试异常项。 + """人工重试异常项(单行入口:资格门禁 + 按组织批量核心的单行特例)。 Args: item_id: TransferInvoiceItem.id。 @@ -197,37 +343,20 @@ def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_EXTER {"item_id": ..., "status": ..., "attempt_no": ...}。 Raises: ValidationError: 状态不可重试 / 重试类型不允许 / result_unknown 只读 / - file_removed 行不可重查(消失证据不可恢复:证据行的源单已从最新 - 收料文件中消失,重查只会用外部系统旧库存把行翻回可执行,唯一出口 - = 人工关闭 / 等重新同步恢复)。 + file_removed 行不可重查(资格门禁,见 _gate_retryable_item)。 NotFoundError: item 不存在。 + Exception: 路由/数量前置解析失败原样上抛(fail-closed,保持单行历史行为)。 """ kind_value = str(kind or "").strip() if kind_value == RETRY_KIND_RPA_REFETCH: raise ValidationError("RPA refetch is not allowed after execution run is created", code="TRANSFER.RETRY_RPA_NOT_ALLOWED") if kind_value != RETRY_KIND_EXTERNAL_RECHECK: raise ValidationError(f"unsupported retry kind: {kind_value}", code="TRANSFER.RETRY_KIND_INVALID") - item = db.session.get(TransferInvoiceItem, item_id) - if item is None: - raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND") - if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value: - raise ValidationError("result_unknown is read-only; follow manual verification SOP", code="TRANSFER_RESULT_UNKNOWN") - if item.status not in _RETRYABLE_STATUSES: - raise ValidationError(f"item status {item.status} is not retryable", code="TRANSFER.RETRY_NOT_ALLOWED") - # [兜底] file_removed 行拒绝重查:匹配号圈行路径(requery_items)已在 scope - # 谓词排除失效行,但按 id 直取(requery_items_by_ids 循环)与单行入口都绕过 - # 该谓词——拒绝逻辑只落在此单点,三条入口同时闭环。为什么拒绝:消失证据 - # 不可恢复,重查会用外部系统旧库存把行翻回可执行(虚假放行),唯一出口 - # = 人工关闭 / 等重新同步恢复该行。 - if item.result_code == RESULT_FILE_REMOVED: - raise ValidationError( - "removed rows cannot be requeried; close manually or wait for re-sync", - code="TRANSFER.RETRY_NOT_ALLOWED", - ) - - status = _recheck_item(item, deps=deps, request_id=request_id) - db.session.commit() - return {"item_id": item.id, "status": status, "attempt_no": item.attempt_no} + item = _gate_retryable_item(item_id) + statuses, row_errors = _recheck_items_batch([item], deps=deps, request_id=request_id) + if item.id in row_errors: + raise row_errors[item.id] + return {"item_id": item.id, "status": statuses[item.id], "attempt_no": item.attempt_no} def requery_items_by_ids( @@ -237,8 +366,8 @@ def requery_items_by_ids( """按明细 id 批量重查外部系统库存(待处理池批量「重查」入口)。 与 requery_items(匹配号定位)的差异:待处理池的行可能分散在多份历史 - 匹配,只能按 id 直取。单行失败(状态不允许/不存在/异常)不影响其余行, - 隔离语义与 requery_items 一致。 + 匹配,只能按 id 直取。单行门禁失败(状态不允许/不存在/file_removed)不 + 影响其余行;库存查询按组织批量(每组织一次外部调用)。 Args: item_ids: TransferInvoiceItem.id 列表(非空)。 @@ -263,29 +392,28 @@ def requery_items_by_ids( # 重查读取执行,否则待处理池后门会基于过期证据放行旧库存。 align_scope_rows(source_codes=affected_sources, deps=deps, business_date=str(business_date_now()), now=datetime.utcnow()) - results: list[dict] = [] + results_by_id: dict[int, dict] = {} + eligible: list[TransferInvoiceItem] = [] for item_id in ids: try: - retry_item(item_id=item_id, deps=deps, kind=RETRY_KIND_EXTERNAL_RECHECK, - actor_id=actor_id, request_id=request_id) - item = db.session.get(TransferInvoiceItem, item_id) - results.append({"item_id": item_id, "invoice_no": item.invoice_no if item else "", - "ok": True, "status": item.status if item else ""}) + eligible.append(_gate_retryable_item(item_id)) except (ValidationError, NotFoundError) as exc: - results.append({"item_id": item_id, "invoice_no": "", "ok": False, "error": exc.message}) - except Exception as exc: # noqa: BLE001 —— 批量隔离兜底:单行异常不炸整批 - logger.warning( - "transfer batch requery row crashed (skipped): item=%s error=%s", - item_id, str(exc).strip() or exc.__class__.__name__, - ) - results.append({"item_id": item_id, "invoice_no": "", "ok": False, - "error": str(exc).strip() or exc.__class__.__name__}) - return {"total": len(ids), "results": results} + results_by_id[item_id] = {"item_id": item_id, "invoice_no": "", + "ok": False, "error": exc.message} + statuses, row_errors = _recheck_items_batch(eligible, deps=deps, request_id=request_id) + for item in eligible: + if item.id in row_errors: + results_by_id[item.id] = {"item_id": item.id, "invoice_no": item.invoice_no, + "ok": False, "error": _row_error_text(row_errors[item.id])} + else: + results_by_id[item.id] = {"item_id": item.id, "invoice_no": item.invoice_no, + "ok": True, "status": statuses[item.id]} + return {"total": len(ids), "results": [results_by_id[item_id] for item_id in ids]} def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str] | None = None, actor_id: int | None = None, request_id: str | None = None) -> dict: - """批量重查 外部系统 库存:按匹配 scope 圈定全部/指定的可重查行逐单重查并刷新。 + """批量重查 外部系统 库存:按匹配 scope 圈定全部/指定的可重查行,按组织批量查询并刷新。 圈行口径与匹配卡实时视图同源(scope_item_query:来源+收料日期区间+调拨类型), 行归属 matching_id 不参与——行归属解耦后行不随匹配迁移,视图能看到的历史行 @@ -299,7 +427,7 @@ def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str actor_id / request_id: 审计上下文。 Returns: {"matching_no", "total", "results": [{invoice_no, item_id, ok, status|error}]}; - 单行失败(状态不允许/不存在)不影响其余行(来源级隔离同款语义)。 + 单行门禁/路由失败不影响其余行(来源级隔离同款语义)。 """ from app.models import TransferMatching @@ -333,25 +461,17 @@ def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str query = query.filter(TransferInvoiceItem.invoice_no.in_(wanted)) items = query.order_by(TransferInvoiceItem.id).all() + # [按组织批量查询] 圈定行集一次性交批量核心:每组织一次外部调用; + # 行级结果按输入行序(id 序)回报。 + statuses, row_errors = _recheck_items_batch(items, deps=deps, request_id=request_id) results: list[dict] = [] for item in items: - try: - retry_item(item_id=item.id, deps=deps, kind=RETRY_KIND_EXTERNAL_RECHECK, - actor_id=actor_id, request_id=request_id) + if item.id in row_errors: results.append({"invoice_no": item.invoice_no, "item_id": item.id, - "ok": True, "status": item.status}) - except (ValidationError, NotFoundError) as exc: + "ok": False, "error": _row_error_text(row_errors[item.id])}) + else: results.append({"invoice_no": item.invoice_no, "item_id": item.id, - "ok": False, "error": exc.message}) - except Exception as exc: # noqa: BLE001 —— 批量隔离兜底:任何单行异常不炸整批 - # 与 _recheck_item 降级同理:DB 只留单行结果,控制台必须同步留痕。 - logger.warning( - "transfer requery row crashed (skipped): invoice=%s item=%s error=%s", - item.invoice_no, item.id, str(exc).strip() or exc.__class__.__name__, - ) - results.append({"invoice_no": item.invoice_no, "item_id": item.id, - "ok": False, - "error": str(exc).strip() or exc.__class__.__name__}) + "ok": True, "status": statuses[item.id]}) return {"matching_no": matching_no, "total": len(items), "results": results} @@ -359,7 +479,7 @@ def retry_document( *, doc_no: str, deps: TransferDeps, actor_id: int | None = None, request_id: str | None = None, ) -> dict: - """调拨单级重试(失败单一键恢复,主路径):圈单内行 → 逐行重查 → 全 ready 自动重跑。 + """调拨单级重试(失败单一键恢复,主路径):圈单内行 → 按组织批量重查 → 全 ready 自动重跑。 【AI 触发时机】:用户在失败调拨单上点「重试」——替代旧的单据级重查(其按 可执行池关联行,对 blocked 行必报"未能关联");本函数按单圈行(单是行权威 @@ -367,10 +487,11 @@ def retry_document( 核心逻辑:[STEP 1] 状态门禁——仅 failed 族(business/technical_failed)可重试; result_unknown 唯一出口=重新触发(D11),pending/executing 在飞拒绝,终态拒绝。 - [STEP 2] 单内 blocked 行逐行重查(复用 retry_item:单行隔离、file_removed 拒绝、 - 每行落 Attempt);ready 行原样保留。 [STEP 3] 全部行 ready → 自动建新 Run 重跑 - (prepare_execution:门禁②文件对账 + D7①分支②复用原单号,写前复查兜底); - 任一行仍阻断 → 不重跑(单是原子单位,缺行不跑),阻断明细原样返回由池子兜底。 + [STEP 2] 单内 blocked 行批量重查(按组织一次外部查询;file_removed 行不可 + 重查、保持阻断——消失证据不可恢复,拒绝语义同资格门禁);ready 行原样保留。 + [STEP 3] 全部行 ready → 自动建新 Run 重跑(prepare_execution:门禁②文件对账 + + D7①分支②复用原单号,写前复查兜底);任一行仍阻断 → 不重跑(单是原子单位, + 缺行不跑),阻断明细原样返回由池子兜底。 Args: doc_no: TransferDocument.doc_no。 @@ -404,16 +525,15 @@ def retry_document( "document has no attached items", code="TRANSFER.DOCUMENT_RETRY_NOT_ALLOWED", ) - # [STEP 2] 单内 blocked 行逐行重查(行级隔离,单行失败不炸整单)。 - for item in items: - if item.status != status_machine.TransferStatus.BLOCKED_RECOVERABLE.value: - continue - try: - retry_item(item_id=item.id, deps=deps, kind=RETRY_KIND_EXTERNAL_RECHECK, - actor_id=actor_id, request_id=request_id) - except (ValidationError, NotFoundError): - # file_removed 等拒绝语义:行保持阻断,原因随结果返回。 - continue + # [STEP 2] 单内 blocked 行批量重查(按组织一次外部查询,行级隔离语义不变; + # file_removed 行直接排除——消失证据不可恢复,保持阻断原样)。 + eligible = [ + item for item in items + if item.status == status_machine.TransferStatus.BLOCKED_RECOVERABLE.value + and item.result_code != RESULT_FILE_REMOVED + ] + if eligible: + _recheck_items_batch(eligible, deps=deps, request_id=request_id) for item in items: db.session.expire(item) diff --git a/backend/app/services/in_transit_transfer/serializers.py b/backend/app/services/in_transit_transfer/serializers.py index 48671be5..eccc6ddc 100644 --- a/backend/app/services/in_transit_transfer/serializers.py +++ b/backend/app/services/in_transit_transfer/serializers.py @@ -124,7 +124,8 @@ def serialize_order(doc, items: list) -> dict[str, Any]: 核心逻辑:[STEP 1] 行集按 ERP 行粒度(物料+批号+拨出/拨入库位)聚合,数量 Decimal 相加取 6 位小数字符串(D14 快照口径),unit/material_name 取组内首个 - 非空原值;[STEP 2] 行级 reason 契约(T13-3):键恒出现——失败/未知行=组内 + 非空原值,行级 invoice_no 随 ERP 写入行同款口径透传(2026-09-29 契约扩充); + [STEP 2] 行级 reason 契约(T13-3):键恒出现——失败/未知行=组内 首个非空行级 result_message,成功行/无原因为 None(前端按 「reason ?? 单 error_message」展示)。 @@ -170,6 +171,9 @@ def serialize_order(doc, items: list) -> dict[str, Any]: "error_message": doc.error_message, "lines": [ { + # 行级溯源收料通知号(2026-09-29 契约扩充,随 ERP 写入行同款口径 + # 透传):业务上一行恒对应一张 invoice,前端明细表首列展示。 + "invoice_no": line["invoice_no"], "material_no": line["material_no"], "material_name": name_by_key.get( (line["material_no"], line["lot_no"], @@ -217,10 +221,14 @@ def serialize_executed_order(doc, items: list) -> dict[str, Any]: "invoice_no": item.invoice_no, "material_no": item.material_no, "material_name": item.material_name, + # 批号保持文件证据原形态(raw 原则);展示侧拨出批号由前端 + # deriveBatchNo 镜像转换(与匹配卡/可调拨明细/待办池同规则)。 "lot_no": item.lot_no or "", "quantity": item.receipt_quantity, "unit": item.unit or "", } - for item in sorted(items, key=lambda row: row.id) + # 行序对齐统一规则第三键(2026-09-29):同单内收料日期/数据源恒同 + # (组键含两者),按 invoice_no 升序、id 兜底稳定排序。 + for item in sorted(items, key=lambda row: (str(row.invoice_no or ""), row.id)) ], } diff --git a/backend/app/services/in_transit_transfer/source_file_status.py b/backend/app/services/in_transit_transfer/source_file_status.py index fb3616a9..44036750 100644 --- a/backend/app/services/in_transit_transfer/source_file_status.py +++ b/backend/app/services/in_transit_transfer/source_file_status.py @@ -1,17 +1,24 @@ """在途调拨来源收料文件状态投影服务。 用途:只读货代收料链路已有事实(ShippingReceiptRpaUnitRun + ShippingReceiptReportFile), - 按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 无文件待触发", - 供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。 + 按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 是否解析失败 / + 无文件待触发",供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。 依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile)、 receipt_file_gate(可用/失效判定单一事实来源)。 逻辑:按来源取该来源最新收料执行单元;命中可用门禁(当天业务日抓取且未过期, - 见 receipt_file_gate)→ ready;有进行中单元 → fetching; - 最新单元为失败终态 → failed;文件仍在但已失效 → expired;否则 → none。 + 见 receipt_file_gate)→ ready,但文件已标记解析失败(parse_failed_at 非空)→ + parse_failed(不可当 ready,仍带 file_no/file_sha256 便于诊断); + 有进行中单元 → fetching;最新单元为失败终态 → failed; + 文件仍在但已失效 → expired;否则 → none。 + record_receipt_parse_failure / clear_receipt_parse_failure 维护解析失败三列 + (写入与清除均只 flush 不 commit,事务归属调用方)。 """ from __future__ import annotations +from datetime import datetime + +from app import db from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun from app.services.in_transit_transfer.receipt_file_gate import ( expired_receipt_file_condition, @@ -30,7 +37,9 @@ def resolve_source_file_status(*, source_code: str) -> dict: Returns: {"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...}, - file_status ∈ {'ready', 'fetching', 'failed', 'expired', 'none'}。 + file_status ∈ {'ready', 'parse_failed', 'fetching', 'failed', 'expired', 'none'}; + parse_failed 表示文件仍可用但解析失败:has_ready_file=False, + 仍带 file_no/file_sha256 便于诊断与前端提示。 """ report = ( ShippingReceiptReportFile.query @@ -43,6 +52,15 @@ def resolve_source_file_status(*, source_code: str) -> dict: .first() ) if report is not None: + # 解析失败分层:文件本身可用(当天抓取未过期未清理)但解析失败, + # 不得当 ready 放行,单独投影 parse_failed 并保留文件身份供诊断。 + if report.parse_failed_at is not None: + return { + 'file_status': 'parse_failed', + 'has_ready_file': False, + 'file_no': report.original_filename or str(report.id), + 'file_sha256': report.sha256, + } return { 'file_status': 'ready', 'has_ready_file': True, @@ -83,3 +101,55 @@ def resolve_source_file_status(*, source_code: str) -> dict: return {'file_status': 'expired', 'has_ready_file': False, 'file_no': None, 'file_sha256': None} return {'file_status': 'none', 'has_ready_file': False, 'file_no': None, 'file_sha256': None} + + +def record_receipt_parse_failure( + *, + report: ShippingReceiptReportFile, + error_code: str, + error_message: str, + now: datetime | None = None, +) -> None: + """标记一份收料归档文件解析失败(写入 parse_failed_at / parse_error_code / parse_error_message)。 + + 【AI 触发时机】收料归档文件解析(schema/字段校验)失败需要把失败事实落到文件上、 + 让来源状态投影为 parse_failed 阻止下游当作 ready 使用时调用;解析成功或重抓成功后 + 改调 clear_receipt_parse_failure。 + + 核心逻辑:[STEP 1] 写入失败时间(now 或当前 UTC)与截断后的错误码/错误信息; + [STEP 2] db.session.flush() 使投影同事务内立即可见。只 flush 不 commit, + 事务提交时机归调用方(与解析流程共用同一事务,禁止在 service 层越权提交)。 + + Args: + report: 待标记的 ShippingReceiptReportFile(须已入库,主键可用)。 + error_code: 机器可读错误码,超 64 字符截断(对齐列宽 String(64))。 + error_message: 人类可读错误信息,超 2000 字符截断(Text 列防御性截断)。 + now: 可选失败时刻;缺省取当前 UTC(与全链路 utcnow 口径一致)。 + Returns: + None。失败标记写在传入对象上并 flush,由调用方决定何时 commit 或回滚。 + """ + report.parse_failed_at = now or datetime.utcnow() + report.parse_error_code = (error_code or '')[:64] + report.parse_error_message = (error_message or '')[:2000] + db.session.flush() + + +def clear_receipt_parse_failure(*, report: ShippingReceiptReportFile) -> None: + """清除一份收料归档文件的解析失败标记(三列置空),投影恢复 ready。 + + 【AI 触发时机】同一文件重新解析成功、或人工确认可恢复后调用,使来源状态 + 投影从 parse_failed 回到 ready;不要在文件已被清理/失效后调用(无意义)。 + + 核心逻辑:[STEP 1] 将 parse_failed_at / parse_error_code / parse_error_message + 三列置 None(三者全空即未失败/已清除的约定态);[STEP 2] flush 使同事务内 + 投影立即可见。只 flush 不 commit,事务提交时机归调用方。 + + Args: + report: 待清除标记的 ShippingReceiptReportFile(须已入库,主键可用)。 + Returns: + None。清除写在传入对象上并 flush,由调用方决定何时 commit 或回滚。 + """ + report.parse_failed_at = None + report.parse_error_code = None + report.parse_error_message = None + db.session.flush() diff --git a/backend/app/services/in_transit_transfer/strategy.py b/backend/app/services/in_transit_transfer/strategy.py index a5e74d7a..27c1f297 100644 --- a/backend/app/services/in_transit_transfer/strategy.py +++ b/backend/app/services/in_transit_transfer/strategy.py @@ -1,8 +1,10 @@ """在途调拨策略硬门禁。 用途:一期策略禁止部分数量调拨、数量容差与 外部系统 自动重试; - confirm_ttl_seconds 为纯展示阈值(默认 10 分钟 stale 徽标判定窗口, - 不再作为执行门禁——2026-09-25 退役)。 + confirm_ttl_seconds 与 inventory_stale_ttl_seconds 均为纯展示阈值 + (stale 徽标判定窗口,不再作为执行门禁——2026-09-25 退役); + 2026-09-29 起 stale 时钟换源:挂 inventory_checked_at(库存查得 + 时刻),阈值默认 24 小时——证据同步换戳不续期该时钟。 依赖:app.core.errors.AppError、standard decimal。 逻辑:任何策略变体触碰三项禁令之一即抛 StrategyViolationError, 阻止发布/执行(fail-closed)。 @@ -17,6 +19,7 @@ from app.core.errors import AppError STRATEGY_VIOLATION_CODE = "TRANSFER.STRATEGY_VIOLATION" DEFAULT_CONFIRM_TTL_SECONDS = 600 # 10 分钟 +DEFAULT_INVENTORY_STALE_TTL_SECONDS = 86400 # 24 小时 @dataclass(frozen=True) @@ -30,6 +33,10 @@ class TransferStrategyPolicy: # 不再作为执行门禁(2026-09-25 退役)——防错由文件版本对账 + worker 写前 # 库存复查承担(见 execution_service)。 confirm_ttl_seconds: int = DEFAULT_CONFIRM_TTL_SECONDS + # 纯展示阈值:stale 徽标判定窗口,时钟=inventory_checked_at(库存查得 + # 时刻,仅匹配评估/重查/写前复查写入;2026-09-29 起替换原 updated_at + # 时钟——后者被证据同步换戳每日续期,徽标对老行永不触发)。 + inventory_stale_ttl_seconds: int = DEFAULT_INVENTORY_STALE_TTL_SECONDS class StrategyViolationError(AppError): @@ -61,5 +68,6 @@ def validate_strategy(strategy: TransferStrategyPolicy) -> None: def default_strategy() -> TransferStrategyPolicy: - """返回一期默认策略(全部禁令关闭,stale 展示阈值 600 秒)。""" + """返回一期默认策略(全部禁令关闭;stale 展示阈值:行新鲜度 600 秒 / + 库存查得时刻 24 小时)。""" return TransferStrategyPolicy() diff --git a/backend/app/services/in_transit_transfer/wecom_sender.py b/backend/app/services/in_transit_transfer/wecom_sender.py new file mode 100644 index 00000000..08cf8215 --- /dev/null +++ b/backend/app/services/in_transit_transfer/wecom_sender.py @@ -0,0 +1,97 @@ +"""在途调拨企微汇总通知的真实通道适配(notification.WeComSender 协议实现)。 + +用途:把自动调拨 Run 汇总经企微 textcard 发给通知人,替代排程 handler 的 + sender=None 占位;通知失败只落 run.notification_status,不影响 ERP 结果。 +依赖:integrations.wecom.notify.send_wecom_event_message(事件门禁+审计)、models.User。 +逻辑:逐收件人解析 wecom_userid 后发送;复用 schedule_completed 事件开关(与排程 + 通用通知同一启停入口,不新增 WECOM_NOTIFY_EVENTS 事件名);至少一人送达即 + success,无可用收件人或全部失败为 failed,由 notify_run_summary 统一落库。 +""" + +from __future__ import annotations + +from typing import Any + +from app.services.integrations.wecom.notify import send_wecom_event_message + +# 复用排程完成事件开关:运维通过 WECOM_NOTIFY_EVENTS 的 schedule_completed +# 统一启停排程类通知,本发送器不引入独立事件名(避免各环境事件表漂移)。 +WECOM_EVENT_TYPE = "schedule_completed" + +_STATUS_LABELS = { + "success": "全部成功", + "partial_failed": "部分失败", + "failed": "失败", + "matching": "匹配中", +} + + +class WecomSummarySender: + """企微汇总通知发送器(协议见 notification.WeComSender)。 + + Args 约定:recipients 为 HXOPS 用户 id 列表(字符串/整数均可),由排程参数 + notify_user_ids(options_source=users)下发;未绑定企微的用户跳过。 + excel_path 为协议占位,当前不发送附件(异常明细以管理端已执行区块为准)。 + """ + + def send_summary(self, *, run_no: str, summary: dict[str, Any], + recipients: list[str], excel_path: str | None = None) -> dict[str, Any]: + """向通知人逐一发送一条 Run 汇总 textcard。 + + Args: + run_no: 调拨 Run 编号(RUN-YYYYMMDD-XXXXXX)。 + summary: notify_run_summary 组装的汇总(run_no/status/business_date/counts)。 + recipients: 用户 id 列表。 + excel_path: 协议占位;当前不发送附件。 + Returns: + {"status": "success", "delivered": n} 或 + {"status": "failed", "error_code": "WECOM_SEND_FAILED", "error_message": str}; + 由 notify_run_summary 写入 run.notification_* 字段。 + """ + counts = summary.get("counts") if isinstance(summary.get("counts"), dict) else {} + status = str(summary.get("status") or "") + title = f"在途自动调拨 {run_no}" + content = "\n".join([ + f"状态: {_STATUS_LABELS.get(status, status or '未知')}", + f"业务日期: {summary.get('business_date') or '-'}", + "文件票数: {tickets} 已匹配: {matched} 待查库存: {pending}".format( + tickets=counts.get("file_invoice_count", 0), + matched=counts.get("matched_count", 0), + pending=counts.get("pending_stock_check_count", 0), + ), + "可执行: {executable} 数量不符: {blocked} 未成熟: {not_matured}".format( + executable=counts.get("executable_count", 0), + blocked=counts.get("blocked_count", 0), + not_matured=counts.get("not_matured_count", 0), + ), + ]) + + user_ids = [int(item) for item in (recipients or []) if str(item).strip().isdigit()] + users = [] + if user_ids: + from app.models import User + + users = User.query.filter(User.id.in_(user_ids)).all() + + # [STEP 1] 逐收件人投递;send_wecom_event_message 内部完成事件门禁与审计落库。 + delivered = 0 + last_error = "" + for user in users: + if not user.wecom_userid: + continue + outcome = send_wecom_event_message( + event_type=WECOM_EVENT_TYPE, user=user, title=title, content=content, + jump_path="/workspace", + ) + if outcome.get("ok"): + delivered += 1 + else: + last_error = str(outcome.get("reason") or "send_failed") + + if delivered: + return {"status": "success", "delivered": delivered} + return { + "status": "failed", + "error_code": "WECOM_SEND_FAILED", + "error_message": last_error or "no wecom-bound recipients", + } diff --git a/backend/app/services/schedule/freight_receipt_rpa_finalize.py b/backend/app/services/schedule/freight_receipt_rpa_finalize.py index 4891e20e..9aa75251 100644 --- a/backend/app/services/schedule/freight_receipt_rpa_finalize.py +++ b/backend/app/services/schedule/freight_receipt_rpa_finalize.py @@ -1,4 +1,10 @@ -"""独立收料 RPA 排程等待态收口辅助。""" +""" +backend/app/services/schedule/freight_receipt_rpa_finalize.py + +用途:独立收料 RPA 排程等待态收口——进度回写、全单元终态后写计数、预生成 ZIP、发企微。 +依赖:ShippingReceiptRpaUnitRun、shipping_receipt_rpa_archive、scheduler_service 企微通知。 +逻辑:每笔回调 → refresh 进度计数 → 全终态时 persist ZIP → _notify_schedule_run_wecom。 +""" from __future__ import annotations @@ -46,8 +52,142 @@ def apply_deferred_receipt_schedule_run_state( return run +def refresh_receipt_schedule_run_progress(schedule_run_id: int) -> dict: + """ + 收料单元每笔回调后回写排程 run 进度计数(非终态,对齐库存 inventory-batch-progress)。 + + 核心逻辑:仅在 awaiting_receipt_rpa 时,按已终态单元聚合 success/empty/failed 写入 + ScheduleRun 计数与 response_summary_json.progress;不改 status/finished_at, + 终态仍由 finalize_receipt_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_receipt_rpa'): + return {'updated': False, 'reason': 'not_awaiting_receipt_callback'} + + units = ShippingReceiptRpaUnitRun.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_receipt_batch_progress(payload: dict) -> dict: + """ + Worker 每完成一笔收料导出后的实时进度回写(非终态,对齐 inventory-batch-progress)。 + + 核心逻辑:校验 schema + schedule_run_id;仅 awaiting_receipt_rpa 时抬升 + ScheduleRun 计数;最终以 unit 终态回调 + finalize 为准。 + + Args: + payload: Worker 上报的累计 success/skipped/failed 与 schedule_run_id。 + + Returns: + dict: updated / rejected 及当前计数。 + """ + if payload.get('schema_version') != 'shipping_receipt_rpa.v1': + 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_receipt_rpa'): + return {'updated': False, 'reason': 'not_awaiting_receipt_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_receipt_unit_processing(payload: dict) -> dict: + """ + Worker 开始导出某收料单元时标记 processing(对齐库存 claimed / rpa_exporting)。 + + 核心逻辑:仅 awaiting_rpa → processing;已终态或已 processing 幂等返回。 + """ + if payload.get('schema_version') != 'shipping_receipt_rpa.v1': + 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 = ShippingReceiptRpaUnitRun.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' + db.session.commit() + if unit.schedule_run_id: + refresh_receipt_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: - """当收料 run 的全部单元已回调后写入独立排程终态,不读取库存回调结果。""" + """ + 当收料 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'} @@ -69,9 +209,35 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict: 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 - run.response_summary_json = {**summary, 'awaiting_receipt_rpa': False, 'success_count': success_count, 'empty_count': skipped_count, 'failed_count': failed_count} + + # [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, + } + try: + from app.services.schedule.shipping_receipt_rpa_archive import persist_receipt_rpa_raw_zip_archive + + archive_summary = persist_receipt_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', + run.run_no, archive_exc, + ) + + run.response_summary_json = { + **summary, + 'awaiting_receipt_rpa': False, + 'success_count': success_count, + 'empty_count': skipped_count, + 'failed_count': failed_count, + **archive_summary, + } db.session.commit() - # 通知与库存 RPA 完全同构:run 终态后走通用排程出口一次性发 textcard+全部收料文件。 + # 通知与库存 RPA 完全同构:run 终态后走通用排程出口一次性发 textcard+收料 ZIP。 try: task = run.task if task is not None and task.notify_enabled: diff --git a/backend/app/services/schedule/freight_receipt_rpa_job.py b/backend/app/services/schedule/freight_receipt_rpa_job.py index 5efe7bdd..9e714374 100644 --- a/backend/app/services/schedule/freight_receipt_rpa_job.py +++ b/backend/app/services/schedule/freight_receipt_rpa_job.py @@ -1,4 +1,13 @@ -"""独立收料 RPA 排程:冻结站点配置并按 DBS Warehouse 展开执行单元。""" +""" +backend/app/services/schedule/freight_receipt_rpa_job.py + +用途:独立收料 RPA 排程——按勾选库存源一对一冻结执行单元并写 receipt trigger。 +依赖:receipt_rpa.write_receipt_export_batch_trigger、assert_receipt_rpa_worker_ready、 + ShippingInventorySource / ShippingReceiptReportConfig / ShippingReceiptRpaUnitRun、 + ScheduleTask/Run。 +逻辑:job_registry 的 freight-receipt-rpa 调用本 handler;写 trigger 前 fail-fast; + 口径与库存排程一致(选中 N 源 → N unit),query_parameters 原样下发。 +""" from __future__ import annotations @@ -6,8 +15,13 @@ import uuid from typing import Any from app import db +from app.core.errors import ServiceUnavailableError from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptRpaUnitRun -from app.services.shipping_notice.receipt_rpa import receipt_unit_parameters, receipt_warehouse_values, write_receipt_export_batch_trigger +from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger +from app.services.shipping_notice.rpa_worker_heartbeat import ( + RPA_WORKER_OFFLINE_MESSAGE, + assert_receipt_rpa_worker_ready, +) RECEIPT_RPA_JOB_KEY = 'freight-receipt-rpa' AWAITING_RECEIPT_RPA_CALLBACK_STATUS = 'awaiting_receipt_rpa_callback' @@ -24,7 +38,7 @@ def _wanted_source_codes(task: ScheduleTask) -> set[str]: def _eligible_sources(task: ScheduleTask) -> list[tuple[ShippingInventorySource, ShippingReceiptReportConfig]]: - """读取已启用且收料配置已启用的站点,不依赖库存报表路径或解析绑定。""" + """读取已启用且已配置收料报表的站点;不依赖库存报表路径、解析绑定或 Warehouse 条件。""" wanted = _wanted_source_codes(task) rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join( ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id, @@ -32,20 +46,27 @@ def _eligible_sources(task: ScheduleTask) -> list[tuple[ShippingInventorySource, return [(source, config) for source, config in rows if not wanted or source.source_code.upper() in wanted] +def _copy_query_parameters(config: ShippingReceiptReportConfig) -> list[dict[str, Any]]: + """浅拷贝收料查询条件原样入快照;空列表表示 Worker 使用页面默认、不填 Warehouse。""" + return [ + dict(item) for item in (config.query_parameters_json or []) + if isinstance(item, dict) + ] + + def _build_unit( - source: ShippingInventorySource, config: ShippingReceiptReportConfig, - warehouse_id: str | None, schedule_run_id: int, + source: ShippingInventorySource, config: ShippingReceiptReportConfig, schedule_run_id: int, ) -> ShippingReceiptRpaUnitRun: - """冻结可审计的收料执行单元;DBS 日期字段不进入查询快照。""" + """冻结可审计的收料执行单元(一源一单元);DBS 日期字段不进入查询快照。""" callback_id = f'receipt:{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': receipt_unit_parameters(config), - 'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id, + 'report_path_json': config.report_path_json or {}, 'query_parameters_json': _copy_query_parameters(config), + 'warehouse_id': None, 'rpa_profile_id': source.rpa_profile_id, } return ShippingReceiptRpaUnitRun( schedule_run_id=schedule_run_id, inventory_source_id=source.id, source_code=source.source_code, - connector_type=source.connector_type, warehouse_id=warehouse_id, callback_id=callback_id, + connector_type=source.connector_type, warehouse_id=None, callback_id=callback_id, status='awaiting_rpa', config_snapshot_json=snapshot, ) @@ -78,15 +99,35 @@ def _serialize_trigger_unit(unit: ShippingReceiptRpaUnitRun) -> dict[str, Any]: def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: - """写独立收料 trigger;一个 DBS Warehouse 或一个 Crane 站点对应一个单元。""" - units: list[ShippingReceiptRpaUnitRun] = [] - for source, config in _eligible_sources(task): - # Warehouse 条件即逐仓拆分维度:运行时从条件派生仓库清单,不读取持久化列表。 - warehouses = receipt_warehouse_values(config) if source.connector_type == 'dbs' else [None] - for warehouse_id in warehouses: - units.append(_build_unit(source, config, str(warehouse_id) if warehouse_id else None, run.id)) + """ + 写独立收料 trigger;每个勾选站点对应一个执行单元(与库存 RPA 同口径)。 + + 核心逻辑:写 trigger 前 assert_receipt_rpa_worker_ready;离线立即 failed, + 不创建 unit、不进入 awaiting_receipt_rpa。 + """ + units: list[ShippingReceiptRpaUnitRun] = [ + _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'}] + + # [STEP] 写 trigger / 入库 unit 前 fail-fast,避免 Worker 离线干等到超时。 + try: + assert_receipt_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', + '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: diff --git a/backend/app/services/schedule/in_transit_receipt_file_job.py b/backend/app/services/schedule/in_transit_receipt_file_job.py deleted file mode 100644 index 48e17521..00000000 --- a/backend/app/services/schedule/in_transit_receipt_file_job.py +++ /dev/null @@ -1,57 +0,0 @@ -"""独立收料文件抓取排程(08:00)。 - -用途:为已启用来源实例确保当日 ready 收料文件;缺文件时按来源触发收料 RPA。 -依赖:schedule.job_registry 的 ScheduleExecuteResult、transfer deps、file_preparation。 -逻辑:与 09:00 自动调拨解耦;自动调拨仍会调用统一文件准备服务,不假设本排程成功。 -""" - -from __future__ import annotations - -from typing import Any - -from app.models import ScheduleRun, ScheduleTask -from app.services.in_transit_transfer import deps as transfer_deps -from app.services.in_transit_transfer.date_policy import business_date_now -from app.services.in_transit_transfer.file_preparation import ensure_receipt_file_ready -from app.services.schedule.job_registry import ScheduleExecuteResult - - -def _wanted_sources(task: ScheduleTask) -> list[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(item).strip() for item in values if str(item).strip()] - - -def run_in_transit_receipt_file_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: - """08:00 收料文件抓取;按来源实例独立执行。""" - deps = transfer_deps.get_transfer_dependencies() - sources = _wanted_sources(task) or [] - business_date = str(business_date_now()) - total = success = failed = empty = 0 - results: list[dict[str, Any]] = [] - warnings: list[str] = [] - errors: list[str] = [] - for source_code in sources: - total += 1 - try: - prepared = ensure_receipt_file_ready( - source_code=source_code, - business_date=business_date, - repository=deps.file_repository, - rpa_trigger=deps.rpa_trigger, - ) - results.append({"source_code": source_code, "stage": prepared.stage}) - if prepared.stage == "file_ready": - success += 1 - elif prepared.stage == "waiting_rpa_callback": - empty += 1 - else: - failed += 1 - errors.append(f"{source_code}: {prepared.error_code or 'file_prep_failed'}") - except Exception as exc: # noqa: BLE001 —— 来源隔离 - failed += 1 - errors.append(f"{source_code}: {exc}") - return (total, success, failed, empty, results, warnings, errors) diff --git a/backend/app/services/schedule/in_transit_transfer_job.py b/backend/app/services/schedule/in_transit_transfer_job.py index 460540c3..ec2fb621 100644 --- a/backend/app/services/schedule/in_transit_transfer_job.py +++ b/backend/app/services/schedule/in_transit_transfer_job.py @@ -1,8 +1,12 @@ -"""自动调拨排程(09:00)。 +"""自动调拨排程。 用途:自动处理当日新成熟可调拨项与历史可恢复异常,并发送一次企微汇总通知。 -依赖:auto_transfer、transfer deps、ScheduleExecuteResult。 -逻辑:复用统一文件准备服务,不假设 08:00 排程成功;来源实例独立执行。 +依赖:auto_transfer、transfer deps、wecom_sender、job_registry.ScheduleExecuteResult、 + receipt_trigger_service.list_receipt_capable_source_codes(缺省来源口径)。 +逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发收料 RPA), + 不依赖其他排程成功;来源留空兜底为全部启用收料来源;有通知人时构造 + sender,仅在有 run_no 或空数据日(无 errors)后置 domain_notification_managed + 抑制框架卡;硬失败不置标记以便框架兜底。 """ from __future__ import annotations @@ -11,42 +15,90 @@ from typing import Any from app.models import ScheduleRun, ScheduleTask from app.services.in_transit_transfer import deps as transfer_deps -from app.services.in_transit_transfer.auto_transfer import run_auto_transfer +from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome, run_auto_transfer from app.services.in_transit_transfer.date_policy import business_date_now +from app.services.in_transit_transfer.receipt_trigger_service import list_receipt_capable_source_codes +from app.services.in_transit_transfer.wecom_sender import WecomSummarySender from app.services.schedule.job_registry import ScheduleExecuteResult def _task_params(task: ScheduleTask) -> dict[str, Any]: + """读取排程结构化参数(job_params 非字典时回落空对象)。""" return task.job_params if isinstance(task.job_params, dict) else {} -def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: - """09:00 自动调拨:恢复 + 预检 + 执行 + 通知。""" +def _wanted_source_codes(task: ScheduleTask) -> list[str]: + """提取结构化 source_codes;留空回落为全部启用且已配置收料报表的来源。 + + Args: + task: 排程任务(job_params.source_codes 可为列表/字符串/缺省)。 + Returns: + 去空白后的来源编码列表;留空时为 list_receipt_capable_source_codes() 结果。 + """ params = _task_params(task) - source_codes = params.get("source_codes") or [] - if isinstance(source_codes, str): - source_codes = [source_codes] + values = params.get("source_codes") or [] + if isinstance(values, str): + values = [values] + codes = [str(item).strip() for item in values if str(item).strip()] + if not codes: + codes = list_receipt_capable_source_codes() + return codes + + +def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: + """自动调拨:恢复 + 匹配(严格相等)+ 执行 + 企微汇总通知。 + + 核心逻辑:有通知人时构造 WecomSummarySender 传入 run_auto_transfer; + 仅在返回后按结果决定是否置 domain_notification_managed——有 run_no + (成功/部分失败领域卡路径)或无 errors(空数据日 C5)时抑制框架卡; + 硬失败(无 run_no 且有 errors)不置标记,允许框架完成卡兜底。 + + Args: + task: 排程任务(job_params: source_codes/recover_history/notify_user_ids)。 + run: 排程执行批次(领域自管通知时写入 response_summary_json 标记)。 + Returns: + ScheduleExecuteResult 七元组;空数据日 total=0 且不记 error(C5)。 + """ + params = _task_params(task) + source_codes = _wanted_source_codes(task) recover_history = bool(params.get("recover_history", True)) - recipients = params.get("notify_user_ids") or [] + recipients = [str(item).strip() for item in (params.get("notify_user_ids") or []) if str(item).strip()] + + # 有通知人时构造 sender 传入领域层;是否抑制框架卡见下方按 outcome 判定。 + sender = WecomSummarySender() if recipients else None deps = transfer_deps.get_transfer_dependencies() outcome = run_auto_transfer( business_date=str(business_date_now()), deps=deps, - source_codes=[str(item).strip() for item in source_codes], + source_codes=source_codes, recover_history=recover_history, - sender=None, # 企微发送器在 deps/运维接线处注入(本期先记录阶段结果) - recipients=[str(item) for item in recipients], + sender=sender, + recipients=recipients, ) + + # [STEP] 领域自管通知门禁:仅在领域卡已发出(有 run_no)或空数据日 + # (无 errors,C5 静默)时置标记;硬失败让框架完成卡兜底。 + if recipients and (outcome.run_no or not outcome.errors): + run.response_summary_json = { + **(run.response_summary_json or {}), + "domain_notification_managed": True, + } results: list[dict[str, Any]] = [] errors: list[str] = list(outcome.errors) + recovery = outcome.recovery + warnings: list[str] = [ + f"sources={len(source_codes)} recovered={recovery.recovered_count} still_blocked={recovery.still_blocked_count}", + ] if outcome.run_no: results.append({ "run_no": outcome.run_no, "status": outcome.run_status, "notification_status": outcome.notification_status, }) - recovery = outcome.recovery + elif not outcome.errors: + # 空数据日:匹配后无可执行行,执行与通知按 C5 跳过,不记失败。 + warnings.append("no executable items; execution and notification skipped") success = 1 if outcome.run_status in {"success", "partial_failed"} else 0 return ( success + recovery.recovered_count, @@ -54,6 +106,6 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc recovery.still_blocked_count, 0, results, - [f"recovered={recovery.recovered_count} still_blocked={recovery.still_blocked_count}"], + warnings, errors, ) diff --git a/backend/app/services/schedule/job_options.py b/backend/app/services/schedule/job_options.py index 2733a95e..952b45cd 100644 --- a/backend/app/services/schedule/job_options.py +++ b/backend/app/services/schedule/job_options.py @@ -64,11 +64,31 @@ def _shipping_receipt_sources_options() -> list[dict[str, Any]]: } for source, _config in rows] +def _users_options() -> list[dict[str, Any]]: + """启用中的用户列表(value=user.id),供排程通知人类参数选择。""" + from app.models import User + + users = ( + User.query.filter(User.status == "active") + .order_by(User.username.asc()) + .all() + ) + return [ + { + "label": user.real_name or user.username, + "value": user.id, + "description": None if not user.wecom_userid else "wecom", + } + for user in users + ] + + # options_source 注册表:新增来源只需在此登记 provider,不动 API 层 _OPTIONS_PROVIDERS: dict[str, Callable[[], list[dict[str, Any]]]] = { "agent_apps": _agent_apps_options, "shipping_inventory_sources": _shipping_inventory_sources_options, "shipping_receipt_sources": _shipping_receipt_sources_options, + "users": _users_options, } diff --git a/backend/app/services/schedule/job_registry.py b/backend/app/services/schedule/job_registry.py index dba20992..12f7d8da 100644 --- a/backend/app/services/schedule/job_registry.py +++ b/backend/app/services/schedule/job_registry.py @@ -193,7 +193,6 @@ def _register_builtin_platform_jobs() -> None: description="按预付款、出货款、验收款、质保款的三轮升级规则发送企业微信提醒。", category="procurement", )) - from app.services.schedule.in_transit_receipt_file_job import run_in_transit_receipt_file_schedule from app.services.schedule.in_transit_transfer_job import run_in_transit_transfer_schedule register_platform_job(PlatformJobDefinition( @@ -472,35 +471,15 @@ def _register_builtin_platform_jobs() -> None: ), defaults=dict(DEFAULT_OA_SALES_RELEASE_JOB_PARAMS), )) - register_platform_job(PlatformJobDefinition( - key="in-transit-receipt-file", - label="在途收料文件抓取", - handler=run_in_transit_receipt_file_schedule, - description=( - "每日 08:00 为已启用来源实例确保当日 ready 收料文件;缺文件时按来源触发收料 RPA。" - "09:00 自动调拨仍会调用统一文件准备服务,不假设本排程成功。" - ), - category="platform", - params_schema=( - { - "key": "source_codes", - "type": "multi_select", - "label": "来源实例", - "label_key": "admin.schedule.form.transferSourceCodes", - "required": False, - "default": [], - "options_source": "shipping_inventory_sources", - }, - ), - defaults={"source_codes": []}, - )) register_platform_job(PlatformJobDefinition( key="in-transit-transfer", label="在途自动调拨", handler=run_in_transit_transfer_schedule, description=( - "每日 09:00 自动处理新增可调拨项与历史可恢复异常;" - "每非空 Run 发送一条企微汇总通知;通知失败不改变 ERP 结果。" + "自动处理可调拨项与历史可恢复异常:调拨前确保各来源当日收料文件就绪" + "(就绪复用,缺失自动触发收料 RPA),数量严格相等匹配后自动生成 ERP 调拨单;" + "每非空 Run 发送一条企微汇总通知,通知失败不改变 ERP 结果。" + "执行时间由排程配置决定,建议配置在业务期望的调拨时点之前。" ), category="platform", params_schema=( diff --git a/backend/app/services/schedule/query_service.py b/backend/app/services/schedule/query_service.py index c7dba7d4..837af26a 100644 --- a/backend/app/services/schedule/query_service.py +++ b/backend/app/services/schedule/query_service.py @@ -10,6 +10,7 @@ from app import db from app.models import ScheduleRun, ScheduleTask from app.core.response import utc_iso from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary +from app.services.schedule.shipping_receipt_rpa_archive import receipt_raw_zip_available_from_summary from app.services.schedule.timezone_util import ( DEFAULT_SCHEDULE_TIMEZONE, compute_next_run_at, @@ -85,6 +86,7 @@ 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), '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/scheduler_service.py b/backend/app/services/schedule/scheduler_service.py index abb718f8..b2059780 100644 --- a/backend/app/services/schedule/scheduler_service.py +++ b/backend/app/services/schedule/scheduler_service.py @@ -103,10 +103,11 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun) """ 构造排程企微 textcard 跳转 query 参数。 - 核心逻辑:指向管理端 /admin/schedules;有原始库存归档时附加 raw_zip=1 与 download 意图, - 由前端在登录后自动触发一次下载,失败时保留手动下载入口。 + 核心逻辑:指向管理端 /admin/schedules;有原始库存/收料归档时附加 raw_zip=1 + 与对应 download 意图,由前端登录后自动触发一次下载,失败时保留手动入口。 """ from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary + from app.services.schedule.shipping_receipt_rpa_archive import receipt_raw_zip_available_from_summary summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} params: dict[str, Any] = { @@ -116,6 +117,9 @@ 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): + params['raw_zip'] = '1' + params['download'] = 'receipt_raw_zip' return params @@ -123,9 +127,9 @@ def _receipt_report_files_for_run(run: ScheduleRun) -> list[ShippingReceiptRepor """ 收集收料排程 run 名下可投递的收料报表文件;非收料任务返回空列表。 - 核心逻辑:库存与收料 RPA 共用同一企微通知出口(_notify_schedule_run_wecom), - 本函数是收料侧的唯一分叉点——按 platform_api_path 识别收料排程,返回该 run - 全部单元已归档且未被清理(archive_deleted_at 为空)的报表文件。 + 核心逻辑:按 platform_api_path 识别收料排程,返回该 run 全部单元已归档且 + 未被清理(archive_deleted_at 为空)的报表文件。企微完成通知已改为发 ZIP, + 本函数保留给管理员单文件重发等旁路读取。 """ from app.models import ShippingReceiptRpaUnitRun @@ -154,7 +158,7 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str: 组装排程完成企微 textcard 正文。 核心逻辑:与管理端统计口径一致,展示 total/success/skipped/failed 四列计数; - 有原始库存归档时提示点击卡片进入 HXOPS 并在登录后自动下载(URL 仅放 jump_url,不写进正文)。 + 有原始库存/收料归档时提示包已随通知发送或可点击下载。 """ status_label = _WECOM_STATUS_LABEL.get(run.status, run.status) skipped_count = int(run.skipped_count or 0) @@ -168,12 +172,12 @@ 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.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary + from app.services.schedule.shipping_receipt_rpa_archive import receipt_raw_zip_available_from_summary if inventory_raw_zip_available_from_summary(summary): description += '\n原始库存包:点击本通知,登录 HXOPS 后自动下载' - receipt_files = _receipt_report_files_for_run(run) - if receipt_files: - description += f'\n收料报表文件 {len(receipt_files)} 份:已随本通知发送' + if receipt_raw_zip_available_from_summary(summary): + description += '\n原始收料包:已随本通知发送;亦可点击本通知登录后下载' return description @@ -183,7 +187,7 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None: 核心逻辑:若 response_summary_json.domain_notification_managed=true(如立账凭证检核), 则跳过以免与领域缺件/失败告警重复。 库存与收料 RPA 共用本出口与同一套门禁:库存附加排程 Excel 与原始库存包; - 收料附加该 run 全部单元的收料报表文件(见 _receipt_report_files_for_run)。 + 收料附加该 run 的原始收料 ZIP(不再逐文件推送)。 """ from app.services.integrations.wecom.notify import ( upload_wecom_temp_media, @@ -244,20 +248,20 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None: run.run_no, exc, ) - receipt_media: list[tuple[str, str]] = [] - for receipt_file in _receipt_report_files_for_run(run): - try: - from app.services.file_assets.storage import file_asset_storage + receipt_zip_media_id = None + receipt_zip_file_name = None + try: + from app.services.schedule.shipping_receipt_rpa_archive import resolve_receipt_raw_zip_download - receipt_media_id = upload_wecom_temp_media( - file_asset_storage.get_bytes(receipt_file.storage_key), receipt_file.original_filename, - ) - receipt_media.append((receipt_media_id, receipt_file.original_filename)) - except Exception as exc: - current_app.logger.warning( - '[wecom-schedule] receipt file media upload failed for run %s file %s: %s', - run.run_no, receipt_file.id, exc, - ) + 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, + ) + except Exception as exc: + current_app.logger.info( + '[wecom-schedule] raw receipt zip media skipped for run %s: %s', + run.run_no, exc, + ) textcard_ok_count = 0 errors = [] @@ -314,21 +318,23 @@ 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}') - for receipt_media_id, receipt_filename in receipt_media: + if receipt_zip_media_id: try: - receipt_audit = _create_audit( - f'{_WECOM_EVENT_TYPE}_receipt_file', u, - title, f'[收料报表] {receipt_filename}', uuid.uuid4().hex, + receipt_zip_audit = _create_audit( + f'{_WECOM_EVENT_TYPE}_receipt_raw_zip', u, + title, f'[原始收料包] {receipt_zip_file_name}', uuid.uuid4().hex, ) - receipt_data = send_wecom_file_message(u.wecom_userid, receipt_media_id) - if receipt_data.get('errcode') == 0: - receipt_audit.status = 'sent' + 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' else: - receipt_audit.error_code = str(receipt_data.get('errcode')) - receipt_audit.error_message = str(receipt_data.get('errmsg', 'unknown'))[:255] - errors.append(f'{u.real_name or u.username}: receipt file errcode={receipt_data.get("errcode")}') + receipt_zip_audit.error_code = str(receipt_zip_data.get('errcode')) + receipt_zip_audit.error_message = str(receipt_zip_data.get('errmsg', 'unknown'))[:255] + errors.append( + f'{u.real_name or u.username}: receipt zip errcode={receipt_zip_data.get("errcode")}' + ) except Exception as exc: - errors.append(f'{u.real_name or u.username}: receipt file exception={exc}') + errors.append(f'{u.real_name or u.username}: receipt zip exception={exc}') if textcard_ok_count > 0: run.wecom_notified = True diff --git a/backend/app/services/schedule/shipping_receipt_rpa_archive.py b/backend/app/services/schedule/shipping_receipt_rpa_archive.py new file mode 100644 index 00000000..19b7f726 --- /dev/null +++ b/backend/app/services/schedule/shipping_receipt_rpa_archive.py @@ -0,0 +1,306 @@ +""" +backend/app/services/schedule/shipping_receipt_rpa_archive.py + +用途:货代收料 RPA 排程 run 的原始收料 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。 +依赖:ScheduleRun、ShippingReceiptReportFile / ShippingReceiptRpaUnitRun、 + file_asset_storage、timezone_util、freight_receipt_rpa_finalize.is_freight_receipt_rpa_task。 +逻辑:finalize 调用 persist_receipt_rpa_raw_zip_archive 写入磁盘与 summary; + 企微/下载展示名用「收料RPA-日期-时刻-收料」;包内条目 `{序号}_{source_code}.xlsx`; + warehouse_id / file_id 只写在 manifest.json;磁盘归档键为 {run_no}.zip。 +""" + +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, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun +from app.services.file_assets.storage import file_asset_storage +from app.services.schedule.freight_receipt_rpa_finalize import is_freight_receipt_rpa_task +from app.services.schedule.timezone_util import resolve_schedule_tzinfo + +_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, +} + + +def get_receipt_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_RECEIPT_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_RECEIPT_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 receipt_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 receipt_raw_zip_download_name(run: ScheduleRun) -> str: + """ + 收料 ZIP 的企微/浏览器下载展示名。 + + 核心逻辑:磁盘归档仍为 {run_no}.zip;本函数只影响 Content-Disposition 与企微 filename。 + """ + return f'{receipt_rpa_attachment_stem(run)}-收料.zip' + + +def _receipt_raw_zip_archive_path(run_no: str) -> Path: + """磁盘归档路径:/.zip。""" + return Path(get_receipt_archive_dir()) / f'{run_no}.zip' + + +def _iter_packable_receipt_files(run: ScheduleRun): + """ + 遍历该 run 下可打包的收料归档文件。 + + 核心逻辑:join unit_run,过滤 archive_deleted_at 为空;按 file id 升序稳定序号。 + + Yields: + ShippingReceiptReportFile: 可从 MinIO 读取的归档记录。 + """ + if not is_freight_receipt_rpa_task(getattr(run, 'task', None)): + return + rows = ( + ShippingReceiptReportFile.query.join( + ShippingReceiptRpaUnitRun, + ShippingReceiptReportFile.unit_run_id == ShippingReceiptRpaUnitRun.id, + ) + .filter( + ShippingReceiptRpaUnitRun.schedule_run_id == run.id, + ShippingReceiptReportFile.archive_deleted_at.is_(None), + ) + .order_by(ShippingReceiptReportFile.id.asc()) + .all() + ) + for report_file in rows: + yield report_file + + +def receipt_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_receipt_zip_available')) + + +def persist_receipt_rpa_raw_zip_archive(run: ScheduleRun) -> dict[str, Any]: + """ + finalize 阶段预生成原始收料 ZIP 归档并返回 summary 字段。 + + 核心逻辑:从 MinIO 拉取各单元归档字节 → 写入 /.zip + (含 manifest.json);无可用文件时返回 raw_receipt_zip_available=false。 + + Args: + run: 收料 RPA ScheduleRun。 + + Returns: + dict: raw_receipt_zip_available / path / file_count / file_ids / zip_size。 + """ + packable_files = list(_iter_packable_receipt_files(run)) + if not packable_files: + return dict(_EMPTY_ARCHIVE_SUMMARY) + + archive_path = _receipt_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 'receipt.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_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), + } + + +def _is_allowed_receipt_archive_path(zip_path: Path) -> bool: + """ + 校验归档 ZIP 路径是否安全可下载。 + + 核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_RECEIPT_ARCHIVE_DIR 内。 + """ + resolved = zip_path.resolve() + if resolved.suffix.lower() != '.zip': + return False + if not resolved.is_file(): + return False + + archive_dir = Path(get_receipt_archive_dir()).resolve() + try: + resolved.relative_to(archive_dir) + except ValueError: + return False + return True + + +def resolve_receipt_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]: + """ + 解析 run 已归档的原始收料 ZIP 路径供下载接口 send_file。 + + 核心逻辑:读取 summary.raw_receipt_zip_path,校验文件存在、后缀为 .zip、 + 且真实路径位于 FREIGHT_RPA_RECEIPT_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 receipt_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() + 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): + raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE) + + return zip_path.resolve(), receipt_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;无则回退仓码;再否则 receipt。 + + 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 'receipt' + + +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/shipping_notice/inventory_configuration_test.py b/backend/app/services/shipping_notice/inventory_configuration_test.py index f002e823..c6c80fa8 100644 --- a/backend/app/services/shipping_notice/inventory_configuration_test.py +++ b/backend/app/services/shipping_notice/inventory_configuration_test.py @@ -1,9 +1,9 @@ """ services/shipping_notice/inventory_configuration_test.py -用途:编排库存站点测试导出、RPA 回调文件分析和自动启用判定。 +用途:编排库存站点测试导出、RPA 回调文件分析(可选运维工具,不参与启用门禁)。 依赖:库存站点/RPA trigger、库存结构分析、库存解析方案模型。 -逻辑:管理端仅对停用站点发起测试;RPA 文件只写测试运行和结构分析,不创建生产快照、不关联订单任务。 +逻辑:管理端发起批量/单站测试;RPA 文件只写测试运行和结构分析,不创建生产快照、不自动启用站点、不关联订单任务。 """ from __future__ import annotations @@ -347,9 +347,6 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]: 'confirmed_profile_checksum': source.parsing_profile.checksum, } run.completed_at = datetime.utcnow() - # 空库存同样证明当前配置可查询;全部必要条件满足时自动投入正式运行。 - from app.services.admin.shipping_inventory_service import activate_source_if_ready - activate_source_if_ready(source, actor_id=run.created_by) db.session.commit() return _payload(run) if status != 'success': @@ -401,7 +398,7 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]: ), None) run.analysis_id = analysis.id; run.status = 'completed' if current_profile_candidate is not None: - # 当前绑定的方案已验证时,测试应直接成为站点启用证据,无需管理员重复确认相同方案。 + # 当前绑定的方案已验证时,直接写入确认事实;启用仍由管理员显式开关完成。 run.stage = 'current_profile_verified' run.result_json = { 'analysis': serialize_analysis(analysis), @@ -410,9 +407,6 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]: 'current_profile_verified': True, 'profile_match_level': current_profile_candidate.get('level'), } - # 当前绑定解析已由本次文件验证,无需管理员重复确认或手动启用。 - from app.services.admin.shipping_inventory_service import activate_source_if_ready - activate_source_if_ready(source, actor_id=run.created_by) else: run.stage = 'ready_for_confirmation' run.result_json = {'analysis': serialize_analysis(analysis)} diff --git a/backend/app/services/shipping_notice/inventory_snapshot_store.py b/backend/app/services/shipping_notice/inventory_snapshot_store.py index 24df9f41..9d12e71f 100644 --- a/backend/app/services/shipping_notice/inventory_snapshot_store.py +++ b/backend/app/services/shipping_notice/inventory_snapshot_store.py @@ -62,7 +62,11 @@ _WAREHOUSE_ID_HEADER_ALIASES = { def inventory_snapshot_ttl_hours() -> int: - """库存快照 TTL(小时);默认 24。""" + """库存快照 TTL(小时);默认 24。 + + 唯一权威来源为全局配置 SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS; + 不读取站点字段 snapshot_ttl_seconds(该字段已退出管理端配置面)。 + """ raw = current_app.config.get("SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS", 24) try: return max(int(raw), 1) diff --git a/backend/app/services/shipping_notice/per_source_rpa_service.py b/backend/app/services/shipping_notice/per_source_rpa_service.py index 01000925..78d35e2f 100644 --- a/backend/app/services/shipping_notice/per_source_rpa_service.py +++ b/backend/app/services/shipping_notice/per_source_rpa_service.py @@ -147,9 +147,17 @@ class PerSourcePrepareResult: def _per_source_run_no(attempt: ShippingTaskInventoryRpaAttempt) -> str: - """构造 per-source 三元组唯一 run_no:PSR----。""" - suffix = uuid.uuid4().hex[:8].upper() - return f'{PER_SOURCE_RUN_NO_PREFIX}-{attempt.task_no}-{attempt.source_code}-A{attempt.attempt_no}-{suffix}' + """ + 构造 per-source 唯一 run_no:PSR-(dumb ID)。 + + [设计] 编号只承担唯一标识与回调回显匹配,不嵌入业务语义——task_no/source_code/ + attempt_no 已是 Attempt 行的结构化列,嵌入只会让长度被最长的语义段绑架 + (2026-09-27:65 字符组合超 varchar(64) 致门禁 Attempt 终态失败;迁移 + we9f0a1b2c3d 已加宽到 128,兜底旧格式与外部变化)。Worker 侧将该编号当作 + 不透明标签透传(文件命名/回调回显),不做解析,缩短对 Worker 零影响。 + PSR- 前缀保留,用于与 legacy T-xxx 全局 run_no 家族区分。 + """ + return f'{PER_SOURCE_RUN_NO_PREFIX}-{attempt.id}' def _latest_attempt( @@ -649,7 +657,7 @@ def per_source_callback_handler( # [STEP 4] 迟到保护:同 (task, source) 有更新 run 已终态 consumed_runs = _consumed_run_nos(task_no, source_code_up, session=sess) - # Run no format: PSR---A- → 排序按 attempt_no 前缀即可 + # 迟到判断按 attempt_no 数值比较(run_no 自身为 PSR-,不含序号语义) try: current_attempt_no = int(attempt.attempt_no) except (TypeError, ValueError): diff --git a/backend/app/services/shipping_notice/receipt_report_notification.py b/backend/app/services/shipping_notice/receipt_report_notification.py index 1bea89ea..ff61a471 100644 --- a/backend/app/services/shipping_notice/receipt_report_notification.py +++ b/backend/app/services/shipping_notice/receipt_report_notification.py @@ -1,7 +1,7 @@ """收料报表企微通知的管理员重发通道。 用途:收料排程的正常通知已统一并入排程通用出口——run 终态后一次性发送 - textcard 汇总 + 全部收料文件(scheduler_service._notify_schedule_run_wecom, + textcard 汇总 + 原始收料 ZIP(scheduler_service._notify_schedule_run_wecom, 与库存 RPA 同门禁同出口);本模块只保留管理员对单个已归档收料文件的 强制重发能力(POST /receipt-report-files//resend),不触发 RPA。 依赖:models、file_asset_storage、audit_service、integrations.wecom.notify。 diff --git a/backend/app/services/shipping_notice/receipt_report_storage.py b/backend/app/services/shipping_notice/receipt_report_storage.py index cac43ce0..11019780 100644 --- a/backend/app/services/shipping_notice/receipt_report_storage.py +++ b/backend/app/services/shipping_notice/receipt_report_storage.py @@ -1,13 +1,15 @@ """收料 RPA callback 的原样归档服务。 用途:接收收料 RPA 单元回调,原样归档文件三年且不写库存快照表;终态落库后 - 通过收料回调桥推进在途调拨的 waiting_rpa_callback 来源任务(B3 接线)。 + 通过收料回调桥推进在途调拨的 waiting_rpa_callback 来源任务(B3 接线); + 每笔终态回调回写 ScheduleRun 进度计数(对齐库存 inventory-batch-progress)。 依赖:models(ShippingReceiptReportFile/ShippingReceiptRpaUnitRun)、file_asset_storage、 - audit_service、in_transit_transfer.receipt_callback_bridge(惰性导入)、 + audit_service、freight_receipt_rpa_finalize、in_transit_transfer.receipt_callback_bridge(惰性导入)、 in_transit_transfer.evidence_sync(惰性导入,仅 success 终态)。 逻辑:success/empty/failed 三个终态分支各自 commit 后调用 _advance_transfer_source_job; - success 分支再触发调拨证据同步(sync_and_commit_for_callback);两座桥都是记账 - 不是收料链路的正确性依赖,桥内异常只记日志绝不回滚归档终态。 + empty 落库 error_code=no_receipt_data(对齐库存 no_inventory_data); + 有 schedule_run_id 时 refresh 进度再 finalize;success 分支再触发调拨证据同步; + 两座桥都是记账不是收料链路的正确性依赖,桥内异常只记日志绝不回滚归档终态。 """ from __future__ import annotations @@ -85,19 +87,36 @@ def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]: 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'}: - unit.status = 'empty'; unit.error_code = None; unit.error_message = None; unit.finished_at = datetime.utcnow() + # [STEP] 与库存 no_inventory_data 对齐:empty 是合法业务结果,落 error_code=no_receipt_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.finished_at = datetime.utcnow() append_shipping_audit_event( event_type='shipping_receipt_rpa_callback_received', aggregate_type='shipping_receipt_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success', - before=before, after={'status': 'empty', 'callback_id': unit.callback_id}, - metadata={'callback_status': status}, + 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() - _advance_transfer_source_job(unit, ok=False, error_code='RPA_RECEIPT_EMPTY', error_message='receipt export empty') - from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete + _advance_transfer_source_job( + unit, ok=False, error_code=unit.error_code or 'no_receipt_data', + error_message=unit.error_message or 'no_receipt_data', + ) + from app.services.schedule.freight_receipt_rpa_finalize import ( + finalize_receipt_schedule_run_if_complete, + refresh_receipt_schedule_run_progress, + ) # 按需触发单元无排程 run(schedule_run_id 为 NULL),跳过排程终态归集。 if unit.schedule_run_id: + refresh_receipt_schedule_run_progress(unit.schedule_run_id) finalize_receipt_schedule_run_if_complete(unit.schedule_run_id) return {'unit_run_id': unit.id, 'status': 'empty'} if status != 'success': @@ -111,9 +130,13 @@ def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]: ) db.session.commit() _advance_transfer_source_job(unit, ok=False, error_code=unit.error_code, error_message=unit.error_message) - from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete + from app.services.schedule.freight_receipt_rpa_finalize import ( + finalize_receipt_schedule_run_if_complete, + refresh_receipt_schedule_run_progress, + ) # 按需触发单元无排程 run(schedule_run_id 为 NULL),跳过排程终态归集。 if unit.schedule_run_id: + refresh_receipt_schedule_run_progress(unit.schedule_run_id) finalize_receipt_schedule_run_if_complete(unit.schedule_run_id) return {'unit_run_id': unit.id, 'status': 'failed'} data = _read_receipt_callback_file(str(payload.get('file_path') or '')) @@ -147,9 +170,13 @@ def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]: ) except Exception as exc: # noqa: BLE001 —— 双保险:桥内部已吞异常 current_app.logger.warning('[receipt-callback] transfer evidence sync failed: %s', exc) - from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete + from app.services.schedule.freight_receipt_rpa_finalize import ( + finalize_receipt_schedule_run_if_complete, + refresh_receipt_schedule_run_progress, + ) # 按需触发单元无排程 run(schedule_run_id 为 NULL),跳过排程终态归集。 # 文件通知不在此处逐文件发送:统一由排程终态归集后一次性推送(与库存 RPA 同构)。 if unit.schedule_run_id: + refresh_receipt_schedule_run_progress(unit.schedule_run_id) finalize_receipt_schedule_run_if_complete(unit.schedule_run_id) return {'unit_run_id': unit.id, 'status': 'success', 'file_id': record.id, 'idempotent': False} diff --git a/backend/app/services/shipping_notice/receipt_rpa.py b/backend/app/services/shipping_notice/receipt_rpa.py index c8e153ad..77a0f9aa 100644 --- a/backend/app/services/shipping_notice/receipt_rpa.py +++ b/backend/app/services/shipping_notice/receipt_rpa.py @@ -1,4 +1,11 @@ -"""独立收料 RPA trigger 的目录和载荷构造服务。""" +""" +backend/app/services/shipping_notice/receipt_rpa.py + +用途:独立收料 RPA trigger 的目录解析与批量载荷原子写入。 +依赖:Flask current_app 配置 FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR。 +逻辑:freight_receipt_rpa_job / receipt_trigger_service 调用写 trigger; + Worker 仅消费 shipping_receipt_rpa.v1,绝不回落到库存 trigger 目录。 +""" from __future__ import annotations @@ -18,35 +25,6 @@ def receipt_trigger_dir() -> Path | None: return Path(value) if value else None -def receipt_warehouse_values(config: Any) -> list[str]: - """从收料配置的查询条件中提取 Warehouse 条件值(去空去重,保持顺序)。 - - Warehouse 条件即逐仓拆分维度(与库存配置同构,不单独持久化仓库清单); - 排程/触发按返回值逐仓展开执行单元。DBS 配置由校验保证恰一条非空条件。 - """ - values: list[str] = [] - for item in (config.query_parameters_json or []): - if not isinstance(item, dict) or str(item.get('name') or '').strip().lower() != 'warehouse': - continue - for raw in (item.get('values') or []): - cleaned = str(raw or '').strip() - if cleaned and cleaned not in values: - values.append(cleaned) - return values - - -def receipt_unit_parameters(config: Any) -> list[dict[str, Any]]: - """构建单个执行单元的受控条件:剥离 Warehouse 条件。 - - Worker 会按单元的 warehouse_id 自动追加单值 Warehouse 条件, - 快照里保留用户维护的 Warehouse 条件会与之重复冲突。 - """ - return [ - dict(item) for item in (config.query_parameters_json or []) - if not (isinstance(item, dict) and str(item.get('name') or '').strip().lower() == 'warehouse') - ] - - def write_receipt_export_batch_trigger(run_no: str, units: list[dict[str, Any]], payload: dict[str, Any] | None = None) -> str | None: """写入收料批量 trigger;worker 仅允许消费 shipping_receipt_rpa.v1。""" trigger_dir = receipt_trigger_dir() diff --git a/backend/app/services/shipping_notice/rpa_worker_heartbeat.py b/backend/app/services/shipping_notice/rpa_worker_heartbeat.py index 3d6aee30..3bd744b4 100644 --- a/backend/app/services/shipping_notice/rpa_worker_heartbeat.py +++ b/backend/app/services/shipping_notice/rpa_worker_heartbeat.py @@ -1,10 +1,11 @@ """ services/shipping_notice/rpa_worker_heartbeat.py -用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传就绪检查与状态查询。 -依赖:Flask current_app、redis_client、shipping_notice.rpa(库存与上传目录、mock 模式)。 -逻辑:freight_rpa_worker 调 POST /rpa/heartbeat;写 inventory/upload trigger 前强制就绪检查; - AUTO_UPLOAD 开启时由 create_app 与履约链调用货代上传就绪校验(Worker/凭据/共享目录/环境隔离)。 +用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传/收料就绪检查与状态查询。 +依赖:Flask current_app、redis_client、shipping_notice.rpa(库存与上传目录、mock 模式)、 + shipping_notice.receipt_rpa(收料 trigger 目录)。 +逻辑:freight_rpa_worker 调 POST /rpa/heartbeat;写 inventory/upload/receipt trigger 前强制就绪检查; + 管理端 /rpa-workers/status?scope=inventory|receipt 展示对应 Worker 心跳徽标。 """ from __future__ import annotations @@ -32,6 +33,9 @@ RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE = "RPA Worker 心跳存储不可用, RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE = "货代上传 RPA 未就绪,请检查 Worker、凭据与共享目录后重试" INVENTORY_EXPORT_CAPABILITY = "inventory_export" FREIGHT_UPLOAD_CAPABILITY = "freight_upload" +RECEIPT_EXPORT_CAPABILITY = "receipt_export" +# 收料 Worker 由 start_receipt_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-receipt。 +RECEIPT_WORKER_ID_SUFFIX = "-receipt" _REDIS_INDEX_KEY = "shipping:rpa:heartbeat:index" _REDIS_WORKER_KEY_PREFIX = "shipping:rpa:heartbeat:worker:" _MEMORY_STORE: dict[str, dict[str, Any]] = {} @@ -354,10 +358,15 @@ def _read_shared_sentinel(trigger_dir: Path) -> tuple[dict[str, str] | None, str return None, "shared_sentinel_unreadable" -def _verify_shared_trigger_mount(trigger_dir: Path | None) -> tuple[bool, list[str]]: +def _verify_shared_trigger_mount( + trigger_dir: Path | None, *, require_sentinel: bool = True, +) -> tuple[bool, list[str]]: """ - 校验 trigger 目录为真实共享挂载,而非 Ubuntu 本地误创建目录。 - 核心逻辑:目录必须已存在;test/prod 或配置 scope_id 时要求哨兵文件且 scope 一致。 + 校验 trigger 目录可写;默认要求共享哨兵(库存与收料同口径)。 + + Args: + trigger_dir: 共享 trigger 目录。 + require_sentinel: 为 True 时在 test/prod 或配置了 scope 时校验哨兵。 """ reasons: list[str] = [] if trigger_dir is None: @@ -368,7 +377,7 @@ def _verify_shared_trigger_mount(trigger_dir: Path | None) -> tuple[bool, list[s return False, ["trigger_dir_not_accessible"] expected_scope = shared_scope_id() - if _shared_mount_check_required(): + if require_sentinel and _shared_mount_check_required(): sentinel, sentinel_reason = _read_shared_sentinel(trigger_dir) if sentinel_reason: reasons.append(sentinel_reason) @@ -391,6 +400,27 @@ def _verify_shared_trigger_mount(trigger_dir: Path | None) -> tuple[bool, list[s return not reasons, reasons +def is_receipt_rpa_worker(worker: dict[str, Any]) -> bool: + """ + 判断心跳是否来自收料 Worker。 + + 优先认 <主机名>-receipt(ps1 注入);兼容未注入 FREIGHT_RPA_WORKER_ID、 + 回退为 <主机名>- 的进程——用心跳 trigger_dir 与收料目录对齐判定。 + """ + if str(worker.get("worker_id") or "").strip().lower().endswith(RECEIPT_WORKER_ID_SUFFIX): + return True + from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir + + expected = receipt_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: @@ -472,14 +502,18 @@ def _check_rpa_worker_ready_for_capability( trigger_dir: Path | None, required_capability: str, extra_reasons: list[str] | None = None, + worker_predicate: Any | None = None, + require_sentinel: bool = True, ) -> RpaWorkerReadiness: """ 通用 Worker 就绪检查:心跳存储、共享挂载、能力声明与环境隔离。 Args: trigger_dir: 待校验的共享 trigger 目录。 - required_capability: 必选 Worker 能力。 + required_capability: 必选 Worker 能力;空字符串表示不校验能力。 extra_reasons: 调用方预检附加原因(凭据/队列等)。 + worker_predicate: 可选过滤(如仅收料 Worker);不匹配的心跳不进入列表。 + require_sentinel: 是否要求共享哨兵(收料为 False)。 Returns: RpaWorkerReadiness。 @@ -496,7 +530,9 @@ def _check_rpa_worker_ready_for_capability( if _heartbeat_redis_required() and _redis_client() is None: reasons.append("heartbeat_storage_unavailable") - _mount_ok, mount_reasons = _verify_shared_trigger_mount(trigger_dir) + _mount_ok, mount_reasons = _verify_shared_trigger_mount( + trigger_dir, require_sentinel=require_sentinel, + ) reasons.extend(mount_reasons) backend_env = resolve_backend_rpa_environment() @@ -505,6 +541,8 @@ def _check_rpa_worker_ready_for_capability( workers, storage_read_failed = list_rpa_worker_heartbeats() if storage_read_failed: reasons.append("heartbeat_storage_unavailable") + if worker_predicate is not None: + workers = [worker for worker in workers if worker_predicate(worker)] eligible_workers: list[dict[str, Any]] = [] enriched_workers: list[dict[str, Any]] = [] @@ -590,6 +628,60 @@ def check_inventory_rpa_worker_ready() -> RpaWorkerReadiness: ) +def check_receipt_rpa_worker_ready() -> RpaWorkerReadiness: + """ + 检查收料 RPA Worker 是否在线(管理端徽标 + 写 trigger 前 fail-fast)。 + + 核心逻辑:仅看收料 Worker 心跳(*-receipt 或 trigger_dir 对齐);要求 + receipt_export 能力;校验收料 trigger 目录可写;与库存同口径要求共享哨兵。 + """ + from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir + + return _check_rpa_worker_ready_for_capability( + trigger_dir=receipt_trigger_dir(), + required_capability=RECEIPT_EXPORT_CAPABILITY, + worker_predicate=is_receipt_rpa_worker, + require_sentinel=True, + ) + + +def assert_receipt_rpa_worker_ready() -> None: + """ + 写收料 trigger 前的强制就绪检查。 + + 核心逻辑:镜像 assert_inventory_rpa_worker_ready;离线则抛 ServiceUnavailableError, + 排程不得进入 awaiting_receipt_rpa。 + + Raises: + ServiceUnavailableError: worker 未就绪、共享目录无效或心跳存储不可用。 + """ + from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir + + result = check_receipt_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] receipt 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(receipt_trigger_dir() or ''), + }, + ) + + def _freight_upload_config_reasons() -> list[str]: """ 预检货代上传静态配置:凭据主密钥、上传队列目录、回调 API 基址。 @@ -749,11 +841,25 @@ def assert_inventory_rpa_worker_ready() -> None: ) -def serialize_rpa_worker_status() -> dict[str, Any]: - """管理端展示:在线 worker 列表与库存/货代上传就绪摘要(含详细 reasons)。""" +def serialize_rpa_worker_status(*, scope: str = "inventory") -> dict[str, Any]: + """ + 管理端展示:按 scope 返回库存或收料 Worker 心跳摘要。 + + Args: + scope: inventory(默认)或 receipt。 + """ from app.services.shipping_notice.rpa import upload_trigger_dir + from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir + + normalized = str(scope or "inventory").strip().lower() + if normalized == "receipt": + readiness = check_receipt_rpa_worker_ready() + trigger_path = str(receipt_trigger_dir() or "") + else: + readiness = check_inventory_rpa_worker_ready() + trigger_path = str(inventory_trigger_dir() or "") + normalized = "inventory" - readiness = check_inventory_rpa_worker_ready() freight_readiness = check_freight_upload_rpa_ready() ttl_seconds = _heartbeat_ttl_seconds() workers = [] @@ -777,6 +883,7 @@ def serialize_rpa_worker_status() -> dict[str, Any]: "ineligible_reasons": worker.get("ineligible_reasons") or [], }) return { + "scope": normalized, "ready": readiness.ready, "message": readiness.message, "detail_message": readiness.detail_message, @@ -785,7 +892,7 @@ def serialize_rpa_worker_status() -> dict[str, Any]: "backend_environment": resolve_backend_rpa_environment(), "shared_scope_id": shared_scope_id(), "shared_sentinel_name": shared_sentinel_name(), - "trigger_dir": str(inventory_trigger_dir() or ""), + "trigger_dir": trigger_path, "upload_trigger_dir": str(upload_trigger_dir() or ""), "reasons": readiness.reasons, "workers": workers, diff --git a/backend/migrations/versions/q4c5d6e7f8a9_add_receipt_report_parse_failed.py b/backend/migrations/versions/q4c5d6e7f8a9_add_receipt_report_parse_failed.py new file mode 100644 index 00000000..38d26cf5 --- /dev/null +++ b/backend/migrations/versions/q4c5d6e7f8a9_add_receipt_report_parse_failed.py @@ -0,0 +1,40 @@ +"""Add parse failure markers to shipping_receipt_report_files. + +用途:shipping_receipt_report_files 新增三个可空列 parse_failed_at / +parse_error_code / parse_error_message,为在途调拨来源错误分层提供 +「parse 失败」归档标记。 +依赖:shipping_receipt_report_files 表(收料原样归档文件); + 模型 backend/app/models/shipping_receipt_report.py 的 + ShippingReceiptReportFile 同步声明同名列。 +逻辑:解析失败时写入失败时间与错误码(≤64)/错误详情(Text); + 三列均为可空且无默认值,三者全空表示未失败或已清除,历史行 + 与正常解析行不受影响;downgrade 直接 drop 三列。 + +Revision ID: q4c5d6e7f8a9 +Revises: p1b2c3d4e5f6 +Create Date: 2026-09-29 00:00:00.000000 + +""" + +from __future__ import annotations + +from alembic import op +import sqlalchemy as sa + + +revision = "q4c5d6e7f8a9" +down_revision = "p1b2c3d4e5f6" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.add_column("shipping_receipt_report_files", sa.Column("parse_failed_at", sa.DateTime(), nullable=True)) + op.add_column("shipping_receipt_report_files", sa.Column("parse_error_code", sa.String(length=64), nullable=True)) + op.add_column("shipping_receipt_report_files", sa.Column("parse_error_message", sa.Text(), nullable=True)) + + +def downgrade() -> None: + op.drop_column("shipping_receipt_report_files", "parse_error_message") + op.drop_column("shipping_receipt_report_files", "parse_error_code") + op.drop_column("shipping_receipt_report_files", "parse_failed_at") diff --git a/backend/migrations/versions/t5a6b7c8d9e0f_transfer_item_inventory_checked_at.py b/backend/migrations/versions/t5a6b7c8d9e0f_transfer_item_inventory_checked_at.py new file mode 100644 index 00000000..3b9d714d --- /dev/null +++ b/backend/migrations/versions/t5a6b7c8d9e0f_transfer_item_inventory_checked_at.py @@ -0,0 +1,43 @@ +"""Add inventory_checked_at to transfer_invoice_items. + +用途:transfer_invoice_items 新增可空列 inventory_checked_at,承载「当前 +external_quantity 的 ERP 取数时刻」,修复 stale 徽标判定时钟被证据同步 +换戳续期污染的问题(此前 stale 挂 updated_at,每日收料文件同步会把 +老行新鲜度续期,徽标对最需要提示的行永不触发)。 +依赖:transfer_invoice_items 表(调拨明细行);模型 + backend/app/models/in_transit_transfer.py 的 TransferInvoiceItem + 同步声明同名列。 +逻辑:仅匹配评估/重查/执行写前复查在真实取数时写入;证据同步换戳/ + 存续分支不续期本字段,置空库存时同步置空。回填口径:存量行中 + external_quantity 非空者以 updated_at 近似(历史取数时刻未单独 + 记录,取行最后一次变更是可得的最优近似);无库存数据行保持 + NULL。downgrade 直接 drop。 + +Revision ID: t5a6b7c8d9e0f +Revises: q4c5d6e7f8a9 +Create Date: 2026-09-29 00:00:00.000000 + +""" + +from __future__ import annotations + +from alembic import op +import sqlalchemy as sa + + +revision = "t5a6b7c8d9e0f" +down_revision = "q4c5d6e7f8a9" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.add_column("transfer_invoice_items", sa.Column("inventory_checked_at", sa.DateTime(), nullable=True)) + op.execute( + "UPDATE transfer_invoice_items SET inventory_checked_at = updated_at " + "WHERE external_quantity IS NOT NULL" + ) + + +def downgrade() -> None: + op.drop_column("transfer_invoice_items", "inventory_checked_at") diff --git a/backend/tests/api/test_in_transit_transfer_api.py b/backend/tests/api/test_in_transit_transfer_api.py index f9e11a8f..3473e8d4 100644 --- a/backend/tests/api/test_in_transit_transfer_api.py +++ b/backend/tests/api/test_in_transit_transfer_api.py @@ -506,6 +506,125 @@ def test_list_transfer_sources_forbidden(app, client, unauthorized_headers): assert response.status_code == 403 +# --------------------------------------------------------------------------- +# Task 4:retry-rpa 对 parse_failed 先本地重解析(成功 200+ready / 仍失败 ok=False; +# 两条路径均不触发 RPA、不返回 202/fetching) +# --------------------------------------------------------------------------- + +def _seed_parse_failed_receipt_file(source_code: str): + """造一条「当日可用但解析失败」的收料归档文件(success 单元 + parse_failed 三列)。 + + 与 tests/services/in_transit_transfer/test_source_file_status.py 同款最小造数: + 来源须在全局 app 夹具种子中(DSV360_AWSDU);文件 created_at 取默认当前 UTC + (当日业务日窗口内 → 可用门禁命中),返回该文件供测试断言。 + """ + import hashlib + from datetime import datetime + from uuid import uuid4 + + from app.models import ( + ShippingInventorySource, + ShippingReceiptReportFile, + ShippingReceiptRpaUnitRun, + ) + + source = ShippingInventorySource.query.filter_by(source_code=source_code).one() + unit = ShippingReceiptRpaUnitRun( + inventory_source_id=source.id, source_code=source.source_code, + connector_type=source.connector_type, warehouse_id=source.fixed_warehouse_id, + callback_id=f"receipt-retry-{uuid4().hex[:12]}", status="success", + config_snapshot_json={}, + ) + db.session.add(unit) + db.session.flush() + report = ShippingReceiptReportFile( + unit_run_id=unit.id, storage_provider="minio", storage_bucket="test", + storage_key=f"shipping/receipt/retry-{unit.id}.xlsx", + original_filename="retry.xlsx", file_size=16, + sha256=hashlib.sha256(b"retry workbook").hexdigest(), + parse_failed_at=datetime.utcnow(), + parse_error_code="TRANSFER_FILE_SCHEMA_INVALID", parse_error_message="schema", + ) + db.session.add(report) + db.session.commit() + return report + + +def test_retry_rpa_parse_failed_reparses_existing_file(app, client, admin_headers, monkeypatch): + """parse_failed 且有可用文件 → retry 先本地重解析(sync),不触发 RPA(200 非 202)。""" + called = {"sync": 0, "rpa": 0} + _seed_parse_failed_receipt_file("DSV360_AWSDU") + + def fake_sync(*, source_code, business_date, now): + # 断言意图:重解析路径 sync 恰好 1 次;成功链路清除解析失败标记使投影回 + # ready(请求会话内重查后清除并 commit,保证端点再解析可见)。 + from app.models import ShippingReceiptReportFile + from app.services.in_transit_transfer.source_file_status import clear_receipt_parse_failure + + called["sync"] += 1 + file = ( + ShippingReceiptReportFile.query + .join(ShippingReceiptReportFile.unit_run) + .filter(ShippingReceiptReportFile.unit_run.has(source_code=source_code)) + .first() + ) + if file is not None: + clear_receipt_parse_failure(report=file) + db.session.commit() + return True + + monkeypatch.setattr( + "app.services.in_transit_transfer.evidence_sync.sync_and_commit_for_callback", + fake_sync, + ) + monkeypatch.setattr( + "app.services.in_transit_transfer.receipt_trigger_service.trigger_receipt_rpa", + lambda **kw: called.__setitem__("rpa", called["rpa"] + 1) or {"ok": True, "callback_id": "x"}, + ) + response = client.post(f"{API_PREFIX}/sources/DSV360_AWSDU/retry-rpa", headers=admin_headers) + # 断言意图:重解析成功返回 200(非 202/fetching),payload 恰为四键契约, + # 且 RPA 触发 0 次(本地重解析不落 RPA 单元)。 + assert response.status_code == 200 + body = response.get_json()["data"] + assert body == { + "source_code": "DSV360_AWSDU", "ok": True, + "file_status": "ready", "reparsed": True, + } + assert called["sync"] == 1 + assert called["rpa"] == 0 + + +def test_retry_rpa_parse_failed_still_failed_reports_not_ok(app, client, admin_headers, monkeypatch): + """sync 返回 True 但投影仍 parse_failed → ok=False(不触发 RPA、不回 202)。""" + called = {"sync": 0, "rpa": 0} + _seed_parse_failed_receipt_file("DSV360_AWSDU") + + def fake_sync(*, source_code, business_date, now): + # 断言意图:sync 返回 True 不代表投影恢复——标记未清除时端点必须如实报 + # 失败(ok=False + parse_failed),由用户感知仍不可用。 + called["sync"] += 1 + return True + + monkeypatch.setattr( + "app.services.in_transit_transfer.evidence_sync.sync_and_commit_for_callback", + fake_sync, + ) + monkeypatch.setattr( + "app.services.in_transit_transfer.receipt_trigger_service.trigger_receipt_rpa", + lambda **kw: called.__setitem__("rpa", called["rpa"] + 1) or {"ok": True, "callback_id": "x"}, + ) + response = client.post(f"{API_PREFIX}/sources/DSV360_AWSDU/retry-rpa", headers=admin_headers) + # 断言意图:仍失败也返回 200(业务结果在 ok 字段),RPA 0 次不兜底重抓。 + assert response.status_code == 200 + body = response.get_json()["data"] + assert body == { + "source_code": "DSV360_AWSDU", "ok": False, + "file_status": "parse_failed", "reparsed": True, + } + assert called["sync"] == 1 + assert called["rpa"] == 0 + + def test_metrics_endpoint(app, transfer_db, client, admin_headers, transfer_deps): """运营指标端点:返回 Run/明细/待处理/通知失败结构。""" response = client.get(f"{API_PREFIX}/metrics", headers=admin_headers) @@ -755,15 +874,17 @@ def test_run_projection_returns_order_list_with_multi_status( data = run.get_json()["data"] orders = data["orders"] assert len(orders) == 3 - # 断言意图:单序稳定(created_at/id 升序 = 组建单的组键升序:收料日期升序)。 + # 断言意图:单序稳定(2026-09-29 投影排序=收料日期→数据源→库位;本例同数据源, + # 收料日期升序,与建单的组键序一致)。 assert [t["receipt_date"] for t in orders] == ["2026-08-03", "2026-08-04", "2026-08-05"] by_status = {t["status"]: t for t in orders} assert set(by_status) == {"success", "business_failed", "result_unknown"} success = by_status["success"] - # 断言意图:计划 Task 11 JSON 规格逐键——order 恰含八键、line 恰含六键 - # (含 reason:框线图失败行原因展示契约,控制器裁决扩充,T13-3)。 + # 断言意图:计划 Task 11 JSON 规格逐键——order 恰含八键、line 恰含七键 + # (+invoice_no:行级溯源收料通知号 2026-09-29 契约扩充;含 reason:框线图 + # 失败行原因展示契约,控制器裁决扩充,T13-3)。 assert set(success.keys()) == { "doc_no", "receipt_date", "from_warehouse", "to_warehouse", "status", "erp_document_no", "error_message", "lines", @@ -777,6 +898,7 @@ def test_run_projection_returns_order_list_with_multi_status( # 断言意图:行数量为 6 位小数字符串(D14 快照口径),unit 原值透传非空; # 成功行 reason 为 None(键恒出现)。 assert success["lines"] == [{ + "invoice_no": "HOM-A", "material_no": "MAT-001", "material_name": "物料MAT-001", "lot_no": "LOT-10", "quantity": "500.000000", "unit": "EA", "reason": None, }] @@ -784,8 +906,9 @@ def test_run_projection_returns_order_list_with_multi_status( failed = by_status["business_failed"] assert failed["erp_document_no"] is None # 断言意图:单据级 error_message 恒 null(T11 裁决契约:失败/未知原因只在 - # 行级 reason 与 run exceptions 透出,单据级不落原因文本)。 + # 行级 reason 与 orders 卡片透出,单据级不落原因文本)。 assert failed["error_message"] is None + assert failed["lines"][0]["invoice_no"] == "HOX-B" assert failed["lines"][0]["quantity"] == "700.000000" # 断言意图:失败行 reason=行级 result_message(框线图「原因」展示数据源)。 assert failed["lines"][0]["reason"] == "rejected by external system" @@ -800,10 +923,9 @@ def test_run_projection_returns_order_list_with_multi_status( # 断言意图:未知行 reason 回落 error_code(result_message 为空时引擎已写入)。 assert unknown["lines"][0]["reason"] == "EXTERNAL_TIMEOUT_AFTER_COMMIT" - # 断言意图:exceptions 既有口径不变——成功族行不进异常清单,失败/未知行逐行进。 - exceptions = data["result"]["exceptions"] - assert len(exceptions) == 2 - assert {exc["reason"] for exc in exceptions} == {"business_failed", "result_unknown"} + # 断言意图:[2026-09-29 口径收窄] exceptions 仅收未建单阻断行——失败/未知行 + # 已建单,不再进异常清单(原因/动作由 orders 卡片承载)。 + assert data["result"]["exceptions"] == [] # 断言意图:external_documents 既有口径不变——仅成功单聚合出单据视图。 assert len(data["result"]["external_documents"]) == 1 @@ -973,9 +1095,10 @@ def test_list_documents_group_counts_always_full(app, transfer_db, client, admin assert data["total"] == 7 # cancelled 不进列表 assert data["page"] == 1 assert data["page_size"] == 20 - # 断言意图:列表 created_at 倒序(无筛选=全部未关闭单)。 + # 断言意图:列表按 收料日期→数据源→库位 升序(2026-09-29 统一口径;本组 + # 造数同日同源,按拨入库位字典序升序)。 assert [t["doc_no"] for t in data["orders"]] == [ - "D-UNK-1", "D-EXEC-2", "D-EXEC-1", "D-FAIL-2", "D-FAIL-1", "D-SUC-2", "D-SUC-1", + "D-EXEC-1", "D-EXEC-2", "D-FAIL-1", "D-FAIL-2", "D-SUC-1", "D-SUC-2", "D-UNK-1", ] # 过滤 failed:groups 计数不变(恒全量),列表仅失败族。 @@ -1030,7 +1153,7 @@ def test_list_documents_order_projection_and_items(app, transfer_db, client, adm def test_list_documents_pagination(app, transfer_db, client, admin_headers, docs_matching): - """分页:默认 page_size=20;created_at 倒序;page/page_size 翻页取片;上限 100。""" + """分页:默认 page_size=20;收料日期→数据源→库位升序;page/page_size 翻页取片;上限 100。""" from datetime import datetime, timedelta with app.app_context(): @@ -1045,22 +1168,23 @@ def test_list_documents_pagination(app, transfer_db, client, admin_headers, docs first_page = client.get(f"{API_PREFIX}/documents?status_group=failed", headers=admin_headers).get_json()["data"] assert first_page["total"] == 25 assert len(first_page["orders"]) == 20 - # 断言意图:列表 created_at 倒序——第一页含最新的 24~5 号单。 - assert first_page["orders"][0]["doc_no"] == "D-PG-24" - assert first_page["orders"][-1]["doc_no"] == "D-PG-05" + # 断言意图:列表升序(2026-09-29 统一口径;本组造数同日同源,按拨入库位 + # 字典序 = doc_no 序)——第一页含最早的 00~19 号单。 + assert first_page["orders"][0]["doc_no"] == "D-PG-00" + assert first_page["orders"][-1]["doc_no"] == "D-PG-19" second_page = client.get( f"{API_PREFIX}/documents?status_group=failed&page=2", headers=admin_headers, ).get_json()["data"] assert len(second_page["orders"]) == 5 - assert second_page["orders"][0]["doc_no"] == "D-PG-04" + assert second_page["orders"][0]["doc_no"] == "D-PG-20" sized = client.get( f"{API_PREFIX}/documents?status_group=failed&page=2&page_size=10", headers=admin_headers, ).get_json()["data"] assert sized["page"] == 2 assert sized["page_size"] == 10 - assert [t["doc_no"] for t in sized["orders"]] == [f"D-PG-{n:02d}" for n in range(14, 4, -1)] + assert [t["doc_no"] for t in sized["orders"]] == [f"D-PG-{n:02d}" for n in range(10, 20)] # page_size 上限 100:超限收口到 100(防大页拖库)。 capped = client.get( @@ -1070,26 +1194,29 @@ def test_list_documents_pagination(app, transfer_db, client, admin_headers, docs def test_list_documents_date_range_filters_list_only(app, transfer_db, client, admin_headers, docs_matching): - """时间范围仅作用 orders 列表(groups 恒全量);历史单(30 天前失败单)计入且可查出。""" + """时间范围(收料日期口径,2026-09-29 切换)仅作用 orders 列表(groups 恒全量); + 历史收料日期的失败单计入且可查出。""" from datetime import datetime, timedelta with app.app_context(): now = datetime(2026, 9, 24, 10, 0, 0) _seed_document(transfer_db, docs_matching, "D-OLD-1", "2026-08-06 09:00:00", "business_failed", + group={"receipt_date": "2026-08-25"}, created_at=now - timedelta(days=30)) _seed_document(transfer_db, docs_matching, "D-NEW-1", "2026-08-06 10:00:00", "business_failed", + group={"receipt_date": "2026-09-23"}, created_at=now - timedelta(days=1)) transfer_db.session.commit() unfiltered = client.get(f"{API_PREFIX}/documents", headers=admin_headers).get_json()["data"] - # 断言意图:历史失败单(30 天前)计入分组计数且默认列表可查(created_at 倒序在前)。 + # 断言意图:历史收料日期失败单计入分组计数且默认列表可查(收料日期升序在前)。 assert unfiltered["groups"]["failed"] == 2 - assert [t["doc_no"] for t in unfiltered["orders"]] == ["D-NEW-1", "D-OLD-1"] + assert [t["doc_no"] for t in unfiltered["orders"]] == ["D-OLD-1", "D-NEW-1"] ranged = client.get( f"{API_PREFIX}/documents?date_from=2026-09-20&date_to=2026-09-30", headers=admin_headers, ).get_json()["data"] - # 断言意图:时间窗只筛列表;groups 计数不受筛选影响(恒全量,缩小范围不隐藏异常)。 + # 断言意图:时间窗按收料日期只筛列表;groups 计数不受筛选影响(恒全量,缩小范围不隐藏异常)。 assert [t["doc_no"] for t in ranged["orders"]] == ["D-NEW-1"] assert ranged["groups"]["failed"] == 2 diff --git a/backend/tests/services/admin/test_shipping_inventory_service.py b/backend/tests/services/admin/test_shipping_inventory_service.py index 0b880e61..e9cc5dcb 100644 --- a/backend/tests/services/admin/test_shipping_inventory_service.py +++ b/backend/tests/services/admin/test_shipping_inventory_service.py @@ -226,7 +226,7 @@ def test_disabled_source_can_be_saved_before_profile_and_template_binding(app): def test_activation_is_a_separate_gate_and_reports_unfinished_steps(app): - """普通保存只能保留停用站点;独立启用动作必须返回尚未完成的测试步骤。""" + """普通保存只能保留停用站点;独立启用动作必须返回尚未完成的硬门槛。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): login = shipping_inventory_service.save_profile(_profile_data(code='ACTIVATION_LOGIN'), actor_id=None) @@ -234,7 +234,7 @@ def test_activation_is_a_separate_gate_and_reports_unfinished_steps(app): payload.update({'enabled': False, 'parsing_profile_id': None, 'excel_template_id': None}) draft = shipping_inventory_service.save_source(payload, actor_id=None, allow_enable_transition=False) assert draft['activation']['ready'] is False - assert draft['activation']['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test'] + assert draft['activation']['missing_requirements'] == ['parsing_profile', 'excel_template'] payload['enabled'] = True saved = shipping_inventory_service.save_source( @@ -245,11 +245,11 @@ def test_activation_is_a_separate_gate_and_reports_unfinished_steps(app): with pytest.raises(ConflictError) as exc_info: shipping_inventory_service.activate_source(draft['id'], actor_id=None) assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_ACTIVATION_BLOCKED' - assert exc_info.value.details['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test'] + assert exc_info.value.details['missing_requirements'] == ['parsing_profile', 'excel_template'] -def test_activation_status_exposes_structured_checks_without_duplicate_test_blocks(app): - """未测试站点应显示后续验证步骤,但只由测试门禁阻断,避免管理员面对重复待办。""" +def test_activation_status_exposes_only_hard_gate_checks(app): + """启用门禁仅暴露连接/解析/发货模板硬门槛,不再包含测试导出或后续准备项。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): login = shipping_inventory_service.save_profile(_profile_data(code='CHECKS_LOGIN'), actor_id=None) @@ -267,14 +267,13 @@ def test_activation_status_exposes_structured_checks_without_duplicate_test_bloc checks = {item['code']: item for item in draft['activation']['checks']} - # 关键断言:未进行测试时,解析/仓库验证被展示为待测试而非额外阻断门禁。 - assert checks['configuration_test']['blocking'] is True - assert checks['configuration_test']['evidence'] == {'state': 'not_started'} - assert checks['parsing_validation']['status'] == 'pending' - assert checks['parsing_validation']['blocking'] is False - assert checks['warehouse_mapping']['status'] == 'pending' - assert checks['warehouse_mapping']['blocking'] is False - assert draft['activation']['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test'] + # 关键断言:测试导出与可选准备项已退出启用门禁;仅硬门槛阻断。 + assert set(checks) == {'rpa_profile', 'parsing_profile', 'excel_template', 'template_validation'} + assert 'configuration_test' not in checks + assert checks['rpa_profile']['blocking'] is False + assert checks['parsing_profile']['blocking'] is True + assert checks['excel_template']['blocking'] is True + assert draft['activation']['missing_requirements'] == ['parsing_profile', 'excel_template'] def test_enabled_source_rejects_disabled_rpa_profile(app): @@ -355,8 +354,8 @@ def test_direct_parsing_profile_binding_keeps_source_disabled_and_writes_audit(a assert history[0]['source_config_version_after'] == bound[0]['config_version'] -def test_bulk_parsing_profile_binding_is_atomic_when_one_site_is_enabled(app): - """批量绑定必须先全量预检;已启用站点阻断时其余站点不能部分写入。""" +def test_bulk_parsing_profile_binding_allows_enabled_sites(app): + """批量绑定允许包含已启用站点;全部预检通过后原子写入。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): login = shipping_inventory_service.save_profile(_profile_data(code='BULK_BIND_LOGIN'), actor_id=None) @@ -366,16 +365,16 @@ def test_bulk_parsing_profile_binding_is_atomic_when_one_site_is_enabled(app): enabled = shipping_inventory_service.save_source(_source_data(login['id'], code='BULK_BIND_ENABLED'), actor_id=None) profile = _parsing_profile() - with pytest.raises(ConflictError) as exc_info: - shipping_inventory_service.bind_source_parsing_profile( - [disabled['id'], enabled['id']], profile['id'], actor_id=None, - reason='批量迁移同类报表', operation='bulk', - ) + bound = shipping_inventory_service.bind_source_parsing_profile( + [disabled['id'], enabled['id']], profile['id'], actor_id=None, + reason='批量迁移同类报表', operation='bulk', + ) - # 关键断言:任一站点不可变更时,停用站点也不得留下部分绑定或审计。 - assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_BINDING_BLOCKED' - assert db.session.get(ShippingInventorySource, disabled['id']).parsing_profile_id is None - assert ShippingInventorySourceParsingBindingAudit.query.count() == 0 + # 关键断言:已启用站点可直接换绑;两站同步写入且留下审计。 + assert {row['id'] for row in bound} == {disabled['id'], enabled['id']} + assert all(row['parsing_profile_id'] == profile['id'] for row in bound) + assert db.session.get(ShippingInventorySource, enabled['id']).enabled is True + assert ShippingInventorySourceParsingBindingAudit.query.count() == 2 def test_direct_parsing_binding_rejects_template_fields_missing_from_profile(app): diff --git a/backend/tests/services/in_transit_transfer/conftest.py b/backend/tests/services/in_transit_transfer/conftest.py index 5e2f6116..6741e069 100644 --- a/backend/tests/services/in_transit_transfer/conftest.py +++ b/backend/tests/services/in_transit_transfer/conftest.py @@ -34,6 +34,22 @@ def _stub_doc_sequence(monkeypatch): ) +@pytest.fixture(autouse=True) +def _pin_maturity_lag_legacy(request): + """在途套件钉成熟滞后=1(T+1)。 + + 用途:存量夹具生态按 T+1 语义构建(fixed_clock 业务日 2026-08-06、收料日期 + 2026-08-05=T-1);生产默认 T+2(settings IN_TRANSIT_TRANSFER_MATURITY_ + LAG_DAYS=2)的边界行为由 test_matching_service / test_date_policy 专项 + 用例显式覆盖,不被本钉值掩盖。 + 逻辑:仅对已请求 app 的用例钉值(request.fixturenames 判定),pure_unit 用例 + (如 test_date_policy)不触碰 Flask,继续走 date_policy 的无上下文回退。 + """ + if "app" in getattr(request, "fixturenames", []): + app = request.getfixturevalue("app") + app.config["IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS"] = 1 + + @pytest.fixture def fixed_clock() -> FakeClock: """固定时钟:默认 2026-08-06 09:00:00+08:00(业务日 T=2026-08-06)。""" diff --git a/backend/tests/services/in_transit_transfer/test_auto_transfer.py b/backend/tests/services/in_transit_transfer/test_auto_transfer.py new file mode 100644 index 00000000..a4f4c105 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_auto_transfer.py @@ -0,0 +1,66 @@ +"""自动调拨编排(run_auto_transfer)测试:空数据日跳过与正常执行透传。 + +用途:锁定 09:00 自动排程编排的阶段语义——匹配后无可执行行(含恢复后仍为 0) + 时不建票、不写 ERP、不通知、不记 error(产品决策 C5);有可执行行时把 + 执行结果透传给调用方。 +依赖:auto_transfer(monkeypatch create_matching / execute_matching_items)。 +逻辑:纯单元用例,不触库;恢复阶段用 recover_history=False 关闭。 +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import app.services.in_transit_transfer.auto_transfer as at +from app.services.in_transit_transfer.contracts import MatchingCountsDTO, MatchingSummaryDTO + + +def _summary(executable_count: int) -> MatchingSummaryDTO: + return MatchingSummaryDTO( + matching_id="MTG-20260928-ABC123", + status="matched", + business_date="2026-09-28", + eligible_receipt_date_to="2026-09-27", + expires_at="2026-09-28T10:00:00", + counts=MatchingCountsDTO(executable_count=executable_count), + estimated_transfer_quantity="0", + estimated_external_write_count=executable_count, + matching_hash="hash-x", + ) + + +def test_skips_execution_when_no_executable_items(monkeypatch): + """空数据日:不执行、不通知、不记 error,clean no-op。""" + monkeypatch.setattr(at, "create_matching", lambda **kwargs: _summary(0)) + + def _must_not_execute(**kwargs): + raise AssertionError("execute_matching_items must not be called on empty day") + + monkeypatch.setattr(at, "execute_matching_items", _must_not_execute) + + outcome = at.run_auto_transfer( + business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False, + ) + assert outcome.run_no is None + assert outcome.run_status is None + assert outcome.errors == [] + + +def test_executes_and_propagates_result_when_executable(monkeypatch): + """有可执行行:按匹配执行并透传 run_no/status。""" + monkeypatch.setattr(at, "create_matching", lambda **kwargs: _summary(3)) + captured = {} + + def _fake_execute(**kwargs): + captured.update(kwargs) + return SimpleNamespace(run_no="RUN-20260928-XYZ789", status="success") + + monkeypatch.setattr(at, "execute_matching_items", _fake_execute) + + outcome = at.run_auto_transfer( + business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False, + ) + assert captured["matching_id"] == "MTG-20260928-ABC123" + assert outcome.run_no == "RUN-20260928-XYZ789" + assert outcome.run_status == "success" + assert outcome.errors == [] diff --git a/backend/tests/services/in_transit_transfer/test_backlog_service.py b/backend/tests/services/in_transit_transfer/test_backlog_service.py index 8c33455b..5ed8260a 100644 --- a/backend/tests/services/in_transit_transfer/test_backlog_service.py +++ b/backend/tests/services/in_transit_transfer/test_backlog_service.py @@ -53,7 +53,7 @@ def test_list_backlog_includes_blocked_only(transfer_db, dbs_ready_file): def test_backlog_order_stable_across_requery_touch(transfer_db, dbs_ready_file): - """排序=收料日期→Invoice→created_at,与重查触碰(updated_at 刷新)无关。 + """排序=收料日期→数据源→Invoice→created_at,与重查触碰(updated_at 刷新)无关。 [断言意图] 恢复处理/重查会刷新 updated_at(行级新鲜度续期);排序键若用 updated_at 会让正在处理的行跳位(用户实测:恢复后被处理的行跳到列表末尾)。 @@ -76,6 +76,7 @@ def test_backlog_order_stable_across_requery_touch(transfer_db, dbs_ready_file): invoices = [dto.invoice_no for dto in list_backlog()] # 排序只看业务键:HOM-002 收料日期(08-01) 早于 HOM-001(08-05),尽管它刚被触碰过 + # (两行同来源,数据源键不改变先后)。 assert invoices == ["HOM-002", "HOM-001"] diff --git a/backend/tests/services/in_transit_transfer/test_date_policy.py b/backend/tests/services/in_transit_transfer/test_date_policy.py index fb02e800..0aadb2a7 100644 --- a/backend/tests/services/in_transit_transfer/test_date_policy.py +++ b/backend/tests/services/in_transit_transfer/test_date_policy.py @@ -1,6 +1,7 @@ """在途调拨日期成熟度策略测试(L0 纯单元)。 -用途:验证 D+1 成熟规则、当天 not_matured、未来日期阻断与上海业务时区。 +用途:验证 T+lag 成熟规则(默认 T+2)、当天/T-1 not_matured、未来日期阻断与上海业务时区; + 以及 parse_date 对 ISO / 美式 MM/DD/YYYY 收料日期的归一化。 依赖:app.services.in_transit_transfer.date_policy(纯函数)。 逻辑:全部断言只依赖业务日期与收料日期,不接触 Flask/DB(pure_unit)。 """ @@ -17,6 +18,7 @@ from app.services.in_transit_transfer.date_policy import ( business_date_utc_window, eligible_receipt_date_to, maturity_status, + parse_date, ) pytestmark = pytest.mark.pure_unit @@ -29,9 +31,14 @@ def test_same_day_receipt_is_not_matured(): assert maturity_status(date(2026, 8, 6), BUSINESS_T) == "not_matured" -def test_yesterday_receipt_is_eligible(): - """昨天(T-1)收料进入预检。""" - assert maturity_status(date(2026, 8, 5), BUSINESS_T) == "eligible" +def test_yesterday_receipt_is_not_matured(): + """T+2 默认:昨天(T-1)收料尚未成熟(海外时差:28 号最早处理 26 号)。""" + assert maturity_status(date(2026, 8, 5), BUSINESS_T) == "not_matured" + + +def test_t_minus_2_receipt_is_eligible(): + """T+2 默认:前天(T-2)收料起可预检(纯单元无 app 上下文 → 回退默认 lag=2)。""" + assert maturity_status(date(2026, 8, 4), BUSINESS_T) == "eligible" def test_older_receipt_is_eligible(): @@ -46,13 +53,25 @@ def test_future_receipt_is_blocked(): def test_maturity_status_accepts_iso_strings(): """字符串日期与 date 对象等价。""" - assert maturity_status("2026-08-05", "2026-08-06") == "eligible" + assert maturity_status("2026-08-04", "2026-08-06") == "eligible" + assert maturity_status("2026-08-05", "2026-08-06") == "not_matured" assert maturity_status("2026-08-06", "2026-08-06") == "not_matured" -def test_eligible_receipt_date_to_is_previous_day(): - """可调拨收料截止日期 = 业务日期 - 1 天。""" - assert eligible_receipt_date_to(BUSINESS_T) == date(2026, 8, 5) +def test_explicit_lag_days_overrides_default(): + """显式 lag=1 复现旧 T+1 口径(兼容回滚与测试钉值场景)。""" + assert maturity_status(date(2026, 8, 5), BUSINESS_T, lag_days=1) == "eligible" + assert maturity_status(date(2026, 8, 6), BUSINESS_T, lag_days=1) == "not_matured" + + +def test_eligible_receipt_date_to_is_t_minus_two(): + """可调拨收料截止日期 = 业务日期 - 2 天(默认 lag)。""" + assert eligible_receipt_date_to(BUSINESS_T) == date(2026, 8, 4) + + +def test_eligible_receipt_date_to_explicit_lag(): + """显式 lag=1 时截止 = 业务日期 - 1 天。""" + assert eligible_receipt_date_to(BUSINESS_T, lag_days=1) == date(2026, 8, 5) def test_business_date_now_uses_shanghai_across_utc_midnight(): @@ -93,3 +112,26 @@ def test_invalid_date_string_raises(): """非法日期字符串必须抛 ValueError,不得静默解析。""" with pytest.raises(ValueError): maturity_status("2026/13/99", BUSINESS_T) + + +def test_parse_date_accepts_us_mdy_with_time(): + """DSV SSRS Date Received(美式带时分秒)须解析为业务 date。 + + [断言意图] 收料文件常见 '08/13/2026 13:08:00';仅认 ISO 会导致 + evidence_sync 整链 invalid_receipt_date,transfer_invoice_items 零写入。 + """ + assert parse_date("08/13/2026 13:08:00") == date(2026, 8, 13) + assert parse_date("6/11/2026 08:37:07") == date(2026, 6, 11) + + +def test_parse_date_accepts_us_mdy_date_only(): + """美式日期无时间部分同样可解析。""" + assert parse_date("08/13/2026") == date(2026, 8, 13) + + +def test_parse_date_keeps_iso_and_rejects_garbage(): + """ISO 既有口径不变;无法识别的字符串仍 fail-closed。""" + assert parse_date("2026-08-13") == date(2026, 8, 13) + assert parse_date("2026-08-13 17:38:38") == date(2026, 8, 13) + with pytest.raises(ValueError): + parse_date("not-a-date") diff --git a/backend/tests/services/in_transit_transfer/test_document_model.py b/backend/tests/services/in_transit_transfer/test_document_model.py deleted file mode 100644 index 5d0ba45d..00000000 --- a/backend/tests/services/in_transit_transfer/test_document_model.py +++ /dev/null @@ -1,267 +0,0 @@ -"""TransferDocument 单模型测试(L1,使用 SQLite 内存库)。 - -用途:验证 ERP 调拨单(单)模型的唯一约束、状态 CHECK 兜底、部分唯一索引 - 组锁语义、行/尝试与单的关联关系、document_id 单列索引、pending 初始态、 - 常量集与索引 WHERE/CHECK 子句一致性,以及迁移链单 head - (计划 Task 8 / D3 / D7 / D14 / D15 / D18 + 控制器裁决修正轮)。 -依赖:app fixture(create_all 自动建表)、models/in_transit_transfer、 - migrations/versions 目录(迁移链纯文本解析,不跑 SQLite 往返—— - 自动化往返由 T16 统一补齐)。 -逻辑:全部走真实 ORM 落库,不 Mock 模型本身;IntegrityError 用例遵循 - 既有 test_models.py 模式(flush 触发 → 断言 → rollback 复位)。 -""" - -from __future__ import annotations - -import re -from pathlib import Path - -import pytest -from sqlalchemy.exc import IntegrityError -from sqlalchemy import inspect - -from app import db -from app.models import TransferAttempt, TransferInvoiceItem, TransferMatching -from app.models.in_transit_transfer import ( - UNRESOLVED_DOC_STATUSES, - TRANSFER_DOCUMENT_STATUSES, - TransferDocument, -) - -MIGRATIONS_DIR = Path(__file__).resolve().parents[3] / "migrations" / "versions" -# 当前迁移链 head(2026-09-27 集成调用日志计划:integration_calls 增 wire_json/ -# business_ref 列,迁移 wd7e8f9a0b1c); -# 新增迁移时同步推进本常量,保持「单 head」不变量断言有效。 -NEW_REVISION = "wd7e8f9a0b1c" -# 单表迁移(本文件守护对象):revision/down_revision 冻结,不得随新迁移改动。 -DOC_TABLE_REVISION = "tt0d1e2f3a4b" -DOC_TABLE_REVISION_PARENT = "tt9c0d1e2f3a" - -# 五元组样例(组锁键):同组 = 五字段全等。 -GROUP_A = { - "source_code": "DBS-AWSBI", - "external_org": "ORGA", - "receipt_date": "2026-08-06", - "from_warehouse": "DBS-TRANSIT", - "to_warehouse": "HUB-CN01", -} -# 与 GROUP_A 仅 to_warehouse 不同的第二组(验证不同五元组互不干扰)。 -GROUP_B = {**GROUP_A, "to_warehouse": "HUB-CN02"} - - -def _doc(group: dict, doc_no: str, submit_timestamp: str, status: str | None = None) -> TransferDocument: - """按五元组构造单记录;status=None 时依赖 ORM default 'pending'(④的隐式覆盖)。""" - return TransferDocument( - **group, - doc_no=doc_no, - submit_timestamp=submit_timestamp, - **({"status": status} if status else {}), - ) - - -def _flush_error(transfer_db) -> None: - """flush 触发约束冲突并断言为 IntegrityError,随后 rollback 复位会话。""" - with pytest.raises(IntegrityError): - transfer_db.session.flush() - transfer_db.session.rollback() - - -def test_doc_no_and_submit_timestamp_unique(transfer_db): - """① doc_no / submit_timestamp 全局唯一(终身复用标识,D3),重复插入必须被 DB 拒绝。""" - transfer_db.session.add(_doc(GROUP_A, "DOC-001", "2026-08-06 09:00:00", status="pending")) - transfer_db.session.commit() # 锚定行先提交,回滚不会抹掉冲突源 - - # 不同五元组但复用同一 doc_no → 违反 uq_transfer_documents_doc_no。 - transfer_db.session.add(_doc(GROUP_B, "DOC-001", "2026-08-06 09:00:01", status="pending")) - _flush_error(transfer_db) - - # 不同五元组但复用同一 submit_timestamp → 违反 uq_transfer_documents_submit_timestamp。 - transfer_db.session.add(_doc(GROUP_B, "DOC-002", "2026-08-06 09:00:00", status="pending")) - _flush_error(transfer_db) - - -def test_partial_index_blocks_second_unresolved_order(transfer_db): - """② 同五元组第二张未完结单(pending)插入 → IntegrityError(D15 组锁由 DB 强制)。""" - transfer_db.session.add(_doc(GROUP_A, "DOC-A1", "2026-08-06 09:00:00", status="pending")) - transfer_db.session.flush() - - transfer_db.session.add(_doc(GROUP_A, "DOC-A2", "2026-08-06 09:00:01", status="pending")) - _flush_error(transfer_db) - - -@pytest.mark.parametrize("terminal_status", ["success", "duplicate_success", "cancelled"]) -def test_terminal_order_releases_group_lock(transfer_db, terminal_status): - """② 终态单(success/duplicate_success/cancelled)不占组锁:同五元组可再建新 pending 单(复用/重开语义)。""" - transfer_db.session.add(_doc(GROUP_A, "DOC-A1", "2026-08-06 09:00:00", status=terminal_status)) - transfer_db.session.flush() - - transfer_db.session.add(_doc(GROUP_A, "DOC-A2", "2026-08-06 09:00:01", status="pending")) - transfer_db.session.flush() # 不抛即共存成立 - transfer_db.session.rollback() - - -def test_different_groups_both_keep_unresolved_orders(transfer_db): - """② 不同五元组两张未完结单可共存:组锁仅约束同组,不跨组误伤。""" - transfer_db.session.add(_doc(GROUP_A, "DOC-A1", "2026-08-06 09:00:00", status="pending")) - transfer_db.session.add(_doc(GROUP_B, "DOC-B1", "2026-08-06 09:00:01", status="pending")) - transfer_db.session.flush() # 不抛即共存成立 - transfer_db.session.rollback() - - -def test_item_and_attempt_attach_to_document(transfer_db): - """③ item.document_id / attempt.document_id 挂接与回读(D14:单:Attempt=1:N, - 外键在 Attempt 侧;写 Attempt 挂单,重查 Attempt 仍挂 item——两外键并存)。""" - matching = TransferMatching( - matching_no="MTG-DOC-001", business_date="2026-08-06", status="ready_to_execute", - scope_json={}, counts_json={}, matching_hash="sha256:doc", - ) - transfer_db.session.add(matching) - transfer_db.session.flush() - - doc = _doc(GROUP_A, "DOC-REL-1", "2026-08-06 09:00:00", status="executing") - item = TransferInvoiceItem( - matching_id=matching.id, source_code=GROUP_A["source_code"], invoice_no="INV-REL-1", - material_no="MAT-REL", receipt_date=GROUP_A["receipt_date"], - from_warehouse=GROUP_A["from_warehouse"], to_warehouse=GROUP_A["to_warehouse"], - receipt_quantity="10", status="executing", raw_lines_json=[], - ) - transfer_db.session.add_all([doc, item]) - transfer_db.session.flush() # 先落单与行取得主键,再挂外键 - - # 挂接:行/写尝试都指向单;重查尝试仍只挂行(单据级事实与行级事实分开锚定)。 - item.document_id = doc.id - write_attempt = TransferAttempt( - item_id=item.id, attempt_no=1, kind="external_write", status="running", - request_snapshot_json={"invoice_no": "INV-REL-1"}, - ) - write_attempt.document_id = doc.id - requery_attempt = TransferAttempt( - item_id=item.id, attempt_no=2, kind="external_query", status="queued", - request_snapshot_json={"invoice_no": "INV-REL-1"}, - ) - transfer_db.session.add_all([write_attempt, requery_attempt]) - transfer_db.session.commit() - - loaded_doc = transfer_db.session.get(TransferDocument, doc.id) - assert [i.invoice_no for i in loaded_doc.items] == ["INV-REL-1"] - # 单侧只挂写尝试(重查尝试不挂单,document_id=NULL)。 - assert [a.kind for a in loaded_doc.attempts] == ["external_write"] - loaded_item = transfer_db.session.get(TransferInvoiceItem, item.id) - assert loaded_item.document.doc_no == "DOC-REL-1" - # 行侧行级事实不变:写/重查两次尝试都锚定 item(两外键并存)。 - assert sorted(a.kind for a in loaded_item.attempts) == ["external_query", "external_write"] - loaded_requery = transfer_db.session.get(TransferAttempt, requery_attempt.id) - assert loaded_requery.document_id is None # 重查尝试不挂单 - assert loaded_requery.item.invoice_no == "INV-REL-1" # 仍锚定行 - loaded_write = transfer_db.session.get(TransferAttempt, write_attempt.id) - assert loaded_write.document.doc_no == "DOC-REL-1" - assert loaded_write.item.invoice_no == "INV-REL-1" - - -def test_initial_status_defaults_to_pending(transfer_db): - """④ 单创建后初始态为 'pending'(ORM default 在 flush 时生效,落库回读一致)。""" - doc = _doc(GROUP_A, "DOC-INIT-1", "2026-08-06 09:00:00") - transfer_db.session.add(doc) - transfer_db.session.flush() - assert doc.status == "pending" # ORM 侧 default - transfer_db.session.commit() - - loaded = transfer_db.session.get(TransferDocument, doc.id) - assert loaded.status == "pending" # 落库回读一致 - - -def test_create_all_includes_transfer_documents(app): - """create_all 必须包含单表(迁移与测试建表同源,沿用 test_models 约定)。""" - assert "transfer_documents" in set(inspect(db.engine).get_table_names()) - - -def test_status_constants_match_partial_index_where_and_check(transfer_db): - """⑤ 常量集(八态/五未完结态)与部分唯一索引 WHERE 子句完全一致(双方言), - 组锁范围以 UNRESOLVED_DOC_STATUSES 为唯一真相源;ck_transfer_documents_status - CHECK 兜底同口径:八态全部合法可落库(各占独立五元组避免组锁串扰), - 非法态('succeeded')在 DB 层拒绝(fail-closed)。""" - assert TRANSFER_DOCUMENT_STATUSES == ( - "pending", "executing", "success", "duplicate_success", - "business_failed", "technical_failed", "result_unknown", "cancelled", - ) - assert UNRESOLVED_DOC_STATUSES == ( - "pending", "executing", "result_unknown", "business_failed", "technical_failed", - ) - assert set(UNRESOLVED_DOC_STATUSES) < set(TRANSFER_DOCUMENT_STATUSES) - - index = next( - ix for ix in TransferDocument.__table__.indexes - if ix.name == "uq_transfer_documents_group_live" - ) - # 组锁键 = 完整五元组,且为唯一索引。 - assert [c.name for c in index.columns] == [ - "source_code", "external_org", "receipt_date", "from_warehouse", "to_warehouse", - ] - assert index.unique is True - # SQLite 与 PostgreSQL 的 WHERE 子句都必须恰好圈定五个未完结态。 - for dialect in ("postgresql", "sqlite"): - where_sql = str(index.dialect_options[dialect]["where"]) - assert re.findall(r"'([a-z_]+)'", where_sql) == list(UNRESOLVED_DOC_STATUSES), dialect - - # CHECK 元数据:名为 ck_transfer_documents_status,覆盖八态全部字面量。 - check = next( - c for c in TransferDocument.__table__.constraints - if getattr(c, "name", None) == "ck_transfer_documents_status" - ) - assert re.findall(r"'([a-z_]+)'", str(check.sqltext)) == list(TRANSFER_DOCUMENT_STATUSES) - - # 行为断言(DB 兜底):八态逐一落库(每态独立五元组/单号/时间戳,组锁互不干扰)。 - for i, status in enumerate(TRANSFER_DOCUMENT_STATUSES): - transfer_db.session.add(_doc( - {**GROUP_A, "to_warehouse": f"HUB-CN-{i:02d}"}, - f"DOC-ST-{i}", f"2026-08-06 09:{i:02d}:00", status=status, - )) - transfer_db.session.commit() - - # 非法状态 'succeeded'(想当然的 success 变体)必须被 CHECK 拒绝。 - transfer_db.session.add(_doc(GROUP_A, "DOC-BAD-1", "2026-08-06 09:40:00", status="succeeded")) - _flush_error(transfer_db) - - -def test_invoice_item_document_id_indexed(): - """⑦ 控制器裁决修正:document_id 单列索引存在于模型元数据 - (T10 单据级执行高频按单查行;迁移同迁移内建同名列索引)。""" - index = next( - ix for ix in TransferInvoiceItem.__table__.indexes - if ix.name == "ix_transfer_invoice_items_document_id" - ) - assert [c.name for c in index.columns] == ["document_id"] - assert index.unique is False - - -def test_migration_single_head_and_chain(): - """⑥ 迁移链单 head(当前 = tt1a2b3c4d5e6f),且单表迁移挂在 tt9c0d1e2f3a - 之后(等价 `flask db heads` 单 head 断言:同为 alembic - ScriptDirectory.get_heads,可正确处理 merge 迁移的元组 down_revision; - SQLite 往返由 T16 统一补自动化)。""" - from alembic.config import Config - from alembic.script import ScriptDirectory - - alembic_config = Config() - alembic_config.set_main_option("script_location", str(MIGRATIONS_DIR.parent)) - assert ScriptDirectory.from_config(alembic_config).get_heads() == [NEW_REVISION] - - # 单表迁移文件固定 revision/down_revision(不得改动既有迁移)。 - migration_path = MIGRATIONS_DIR / f"{DOC_TABLE_REVISION}_add_transfer_documents.py" - new_migration_text = migration_path.read_text(encoding="utf-8") - assert f"revision = '{DOC_TABLE_REVISION}'" in new_migration_text - assert f"down_revision = '{DOC_TABLE_REVISION_PARENT}'" in new_migration_text - - # 迁移内两处状态字面量与常量集一致(建表侧与模型侧同口径): - # 一处 = ck_transfer_documents_status CHECK(八态);一处 = 组锁 WHERE(五未完结态)。 - # 按内容识别而非书写顺序(模块级常量定义顺序不影响语义)。 - in_lists = re.findall(r"status IN \(([^)]*)\)", new_migration_text) - assert len(in_lists) == 2 - assert sorted(re.findall(r"'([a-z_]+)'", s) for s in in_lists) == sorted( - [list(TRANSFER_DOCUMENT_STATUSES), list(UNRESOLVED_DOC_STATUSES)] - ) - # downgrade 精确反向:先删两 FK 列,再 drop 单表。 - downgrade_text = new_migration_text.split("def downgrade", 1)[1] - assert "document_id" in downgrade_text - assert "drop_table" in downgrade_text - assert downgrade_text.index("document_id") < downgrade_text.index("drop_table") diff --git a/backend/tests/services/in_transit_transfer/test_evidence_sync.py b/backend/tests/services/in_transit_transfer/test_evidence_sync.py index a5365599..60bee863 100644 --- a/backend/tests/services/in_transit_transfer/test_evidence_sync.py +++ b/backend/tests/services/in_transit_transfer/test_evidence_sync.py @@ -1,9 +1,12 @@ """证据同步三分类写入回归。 用途:锁死 evidence_sync 的核心语义——新行插入(待查态)、既有行按文件刷新、 - 值变重置库存侧、消失行失效、终态行绝不触碰、全程零 ERP 调用。 + 值变重置库存侧、缺席行存续(只换戳不改状态)、终态行绝不触碰、全程零 ERP 调用; + 解析失败分层(2026-09-29):同步成功清除当前可用文件的解析失败标记, + 桥内 schema 类解析失败把失败事实独立 commit 落到当前可用文件上。 依赖:repo_fakes(Fake 文件仓库注入文件行)、app fixture。 -逻辑:通过 Fake repository 的 latest_ready_file 提供文件;直接断言行级状态。 +逻辑:通过 Fake repository 的 latest_ready_file 提供文件;直接断言行级状态; + 解析失败标记用例另建真实 ORM 收料单元/归档文件(当天业务日窗口内 → 可用)。 """ from __future__ import annotations @@ -33,6 +36,41 @@ def _pending_count(source_code="DBS-AWSBI"): source_code=source_code, result_code=SYNC_RESULT_PENDING).count() +def _seed_usable_report_file(*, source_code: str, sha: str, callback_id: str): + """在 ORM 建一条当天抓取(业务日窗口内 → 可用)的收料执行单元与归档文件。 + + Args: + source_code: 来源实例编码(写进收料执行单元行)。 + sha: 归档文件 sha256(与 Fake 仓库 checksum 保持同值,模拟同一份文件)。 + callback_id: 收料执行单元回调键(唯一约束,用例间取不同值)。 + Returns: + 已入库的 ShippingReceiptReportFile。 + """ + from app import db + from app.models import ( + ShippingInventorySource, + ShippingReceiptReportFile, + ShippingReceiptRpaUnitRun, + ) + + source = ShippingInventorySource.query.filter_by(source_code="DSV360_AWSDU").one() + unit = ShippingReceiptRpaUnitRun( + inventory_source_id=source.id, source_code=source_code, + connector_type="dbs", callback_id=callback_id, + status="success", config_snapshot_json={}, + ) + db.session.add(unit) + db.session.flush() + report = ShippingReceiptReportFile( + unit_run_id=unit.id, storage_provider="minio", storage_bucket="test", + storage_key=f"shipping/receipt/{callback_id}.xlsx", + original_filename=f"{callback_id}.xlsx", file_size=16, sha256=sha, + ) + db.session.add(report) + db.session.commit() + return report + + def test_sync_inserts_pending_rows_without_erp(app, dbs_ready_file): # [断言意图] 首次同步:文件行全部落库为待查态;ERP 能力零调用。 deps, erp, _ = make_transfer_deps(dbs_ready_file) @@ -41,7 +79,7 @@ def test_sync_inserts_pending_rows_without_erp(app, dbs_ready_file): business_date="2026-08-06", now=NOW) assert outcome is not None and outcome.inserted > 0 # [断言意图] 有新行 - assert outcome.removed == 0 + assert outcome.absent_kept == 0 assert _pending_count() == outcome.inserted # [断言意图] 插入行全部待查态 row = TransferInvoiceItem.query.filter_by(source_code="DBS-AWSBI").first() assert row.status == "matching" # [断言意图] 13 状态内的待查表达 @@ -64,10 +102,12 @@ def test_sync_is_idempotent_when_sha_unchanged(app, dbs_ready_file): assert [r.updated_at for r in after] == stamps # [断言意图] sha 一致零写入 -def test_sync_marks_vanished_rows_and_never_touches_terminal(app, dbs_ready_file): - # [断言意图] 新版文件里消失的行 → blocked_file_removed;终态行保持既定事实。 +def test_sync_keeps_absent_rows_and_never_touches_terminal(app, dbs_ready_file): + # [断言意图] 新版文件缺席的行 → 存续:状态/结果码原样保留,只换版本戳; + # 终态行保持既定事实。(收料 RPA 非全量导出:缺席≠删除,2026-09-28 语义) deps, _, _ = make_transfer_deps(dbs_ready_file) - sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW) + sync_source_rows(source_code="DBS-AWSBI", deps=deps, + business_date="2026-08-06", now=NOW) doomed = TransferInvoiceItem.query.filter_by(source_code="DBS-AWSBI").first() doomed.status = "ready_to_execute" # 模拟上一版可执行 db.session.flush() @@ -82,17 +122,17 @@ def test_sync_marks_vanished_rows_and_never_touches_terminal(app, dbs_ready_file db.session.flush() deps2, _, _ = make_transfer_deps(dbs_ready_file) - # 换一版不含任何行的文件:经 Fake 仓库一次性覆盖注入(executor 按 repo_fakes - # 实际结构用 set_next_file 提供空 rows 的 ReadyReceiptFile,checksum 用不同 sha)。 + # 换一版不含任何行的文件:经 Fake 仓库一次性覆盖注入空 rows(新 sha)。 repo2 = deps2.file_repository repo2.set_next_file(source_code="DBS-AWSBI", rows=(), checksum="e" * 64) outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps2, business_date="2026-08-06", now=NOW) - assert outcome is not None and outcome.removed == 2 # [断言意图] 两个非终态行全部出清 + assert outcome is not None and outcome.absent_kept == 2 # [断言意图] 两行缺席存续 db.session.refresh(doomed) - assert doomed.status == "blocked_recoverable" # [断言意图] 消失行失效 - assert doomed.result_code == "blocked_file_removed" + assert doomed.status == "ready_to_execute" # [断言意图] 状态不被缺席改写 + assert doomed.result_code == SYNC_RESULT_PENDING # [断言意图] 结果码保留 + assert doomed.raw_lines_json[0]["file_sha256"] == "e" * 64 # [断言意图] 版本戳已换新 db.session.refresh(terminal) assert terminal.status == "success" # [断言意图] 终态行不复活 @@ -151,32 +191,8 @@ def test_sync_refreshes_display_fields_without_reset(app, dbs_ready_file): assert row.raw_lines_json[0]["file_sha256"] == "f" * 64 # [断言意图] 版本戳已换新 -def test_sync_restores_reappeared_removed_rows(app, dbs_ready_file): - # [断言意图] file_removed 行重新出现且证据未变 → 无条件恢复待查态(不卡死隐藏)。 - deps, _, _ = make_transfer_deps(dbs_ready_file) - sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW) - deps.file_repository.set_next_file(source_code="DBS-AWSBI", rows=(), checksum="e" * 64) - removed_outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps, - business_date="2026-08-06", now=NOW) - assert removed_outcome.removed == 2 # [断言意图] 前置:两行已标记消失 - - deps.file_repository.set_next_file( - source_code="DBS-AWSBI", rows=tuple(dbs_ready_file["rows"]), checksum="a" * 64) - outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps, - business_date="2026-08-06", now=NOW) - - assert outcome.reset_pending == 2 # [断言意图] 复现行全部恢复待查 - row = TransferInvoiceItem.query.filter_by( - source_code="DBS-AWSBI", invoice_no="HOX-002").first() - assert row.status == "matching" # [断言意图] 脱离 blocked_recoverable - assert row.result_code == SYNC_RESULT_PENDING - assert row.result_message is None # [断言意图] 消失解释已清除 - assert row.external_quantity is None # [断言意图] 旧库存作废待重查 - assert row.raw_lines_json[0]["file_sha256"] == "a" * 64 # [断言意图] 复现行已换最新戳 - - -def test_vanished_rows_restamped_so_align_passes_through(app, dbs_ready_file, monkeypatch): - # [断言意图] 消失行已换最新文件戳 → align 判据 row_shas == latest_sha 直通(None)。 +def test_absent_rows_restamped_so_align_passes_through(app, dbs_ready_file, monkeypatch): + # [断言意图] 缺席行已换最新文件戳 → align 判据 row_shas == latest_sha 直通(None)。 deps, _, _ = make_transfer_deps(dbs_ready_file) sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW) deps.file_repository.set_next_file(source_code="DBS-AWSBI", rows=(), checksum="e" * 64) @@ -184,8 +200,8 @@ def test_vanished_rows_restamped_so_align_passes_through(app, dbs_ready_file, mo row = TransferInvoiceItem.query.filter_by( source_code="DBS-AWSBI", invoice_no="HOX-002").first() - assert row.result_code == "blocked_file_removed" - assert row.raw_lines_json[0]["file_sha256"] == "e" * 64 # [断言意图] 消失行已换新戳 + assert row.result_code == SYNC_RESULT_PENDING # [断言意图] 缺席不改结果码(存续) + assert row.raw_lines_json[0]["file_sha256"] == "e" * 64 # [断言意图] 缺席行已换新戳 # 文件状态投影返回空 files 版 sha(align 判据输入);测试注入替身避免触碰真实表。 monkeypatch.setattr( @@ -198,6 +214,53 @@ def test_vanished_rows_restamped_so_align_passes_through(app, dbs_ready_file, mo assert outcomes["DBS-AWSBI"] is None # [断言意图] 已对齐:直通零解析 +def test_reappeared_absent_rows_refresh_without_reset(app, dbs_ready_file): + # [断言意图] 缺席存续行重新出现且证据未变 → refreshed(只换戳),状态保持待查。 + deps, _, _ = make_transfer_deps(dbs_ready_file) + sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW) + deps.file_repository.set_next_file(source_code="DBS-AWSBI", rows=(), checksum="e" * 64) + absent_outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps, + business_date="2026-08-06", now=NOW) + assert absent_outcome.absent_kept == 2 # [断言意图] 前置:两行缺席存续 + + deps.file_repository.set_next_file( + source_code="DBS-AWSBI", rows=tuple(dbs_ready_file["rows"]), checksum="a" * 64) + outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps, + business_date="2026-08-06", now=NOW) + + assert outcome.refreshed == 2 # [断言意图] 复现行走刷新分支 + assert outcome.reset_pending == 0 # [断言意图] 证据未变不重置 + row = TransferInvoiceItem.query.filter_by( + source_code="DBS-AWSBI", invoice_no="HOX-002").first() + assert row.status == "matching" # [断言意图] 状态保持待查 + assert row.result_code == SYNC_RESULT_PENDING + assert row.raw_lines_json[0]["file_sha256"] == "a" * 64 # [断言意图] 已换最新戳 + + +def test_historical_removed_row_restored_on_reappear(app, dbs_ready_file): + # [断言意图] 历史残留 blocked_file_removed 行复现 → 无条件恢复待查(防御路径, + # 2026-09-28 起不再新产生,但存量行修复前仍可能命中)。 + deps, _, _ = make_transfer_deps(dbs_ready_file) + sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW) + row = TransferInvoiceItem.query.filter_by( + source_code="DBS-AWSBI", invoice_no="HOX-002").first() + row.status = "blocked_recoverable" + row.result_code = "blocked_file_removed" + row.result_message = "receipt row removed from latest file" + db.session.flush() + + deps.file_repository.set_next_file( + source_code="DBS-AWSBI", rows=tuple(dbs_ready_file["rows"]), checksum="a" * 64) + outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps, + business_date="2026-08-06", now=NOW) + + db.session.refresh(row) + assert outcome.reset_pending >= 1 # [断言意图] 复现行计入重置口径 + assert row.status == "matching" # [断言意图] 脱离 blocked + assert row.result_code == SYNC_RESULT_PENDING + assert row.result_message is None # [断言意图] 删除解释清除 + + def test_receipt_bridge_is_failure_isolated(app, monkeypatch, caplog): # [断言意图] 同步崩溃只记日志:异常绝不向收料回调链路传播。 from app.services.in_transit_transfer import evidence_sync @@ -233,3 +296,104 @@ def test_receipt_bridge_skips_when_no_file(app): from app.services.in_transit_transfer import evidence_sync assert evidence_sync.sync_and_commit_for_callback( source_code="NO-SUCH", business_date="2026-09-25", now=NOW) is True + + +def test_receipt_bridge_schema_failure_marks_parse_failed(app, dbs_ready_file, monkeypatch): + # [断言意图] 桥内同步抛 ReceiptFileSchemaError(schema 类解析失败)→ 失败事实 + # 独立 commit 落到当前可用文件(parse_failed 三列),来源投影转 parse_failed; + # 同步数据已回滚(桥隔离保持)。 + from app import db + from app.models import ShippingReceiptReportFile + from app.services.in_transit_transfer import evidence_sync + from app.services.in_transit_transfer.source_file_status import resolve_source_file_status + + report = _seed_usable_report_file( + source_code="DBS-AWSBI", sha="d" * 64, callback_id="cb-schema-bad") + deps, _, _ = make_transfer_deps(dbs_ready_file) + # 行缺单号(doc_no 置空)→ 解析必抛 ReceiptFileSchemaError(行级 missing_invoice_no)。 + bad_row = {**dbs_ready_file["rows"][0], "doc_no": ""} + deps.file_repository.set_next_file( + source_code="DBS-AWSBI", rows=[bad_row], checksum="d" * 64) + monkeypatch.setattr( + "app.services.in_transit_transfer.deps.get_transfer_dependencies", lambda: deps) + + ok = evidence_sync.sync_and_commit_for_callback( + source_code="DBS-AWSBI", business_date="2026-08-06", now=NOW) + + assert ok is False # [断言意图] 同步失败被吞(桥隔离) + assert _pending_count() == 0 # [断言意图] 坏行未落库(同步数据已回滚) + db.session.expire_all() # 标记经桥内独立 commit:失效缓存重读 + row = db.session.query(ShippingReceiptReportFile).filter_by(id=report.id).one() + assert row.parse_failed_at is not None # [断言意图] 失败事实已落库 + assert row.parse_error_code == "TRANSFER_FILE_SCHEMA_INVALID" + assert row.parse_error_message + assert resolve_source_file_status( + source_code="DBS-AWSBI")["file_status"] == "parse_failed" # [断言意图] 投影分层生效 + + +def test_sync_success_clears_parse_failed_mark(app, dbs_ready_file): + # [断言意图] 同步成功 = 当前可用文件已成功解析:此前落下的 parse_failed 三列 + # 被清除,来源投影恢复 ready(只 flush 不 commit,事务归属调用方不变)。 + from app.services.in_transit_transfer.source_file_status import ( + record_receipt_parse_failure, + resolve_source_file_status, + ) + + report = _seed_usable_report_file( + source_code="DBS-AWSBI", sha="d" * 64, callback_id="cb-schema-clear") + record_receipt_parse_failure( + report=report, error_code="TRANSFER_FILE_SCHEMA_INVALID", error_message="stale mark") + assert resolve_source_file_status( + source_code="DBS-AWSBI")["file_status"] == "parse_failed" # [断言意图] 前置:确已标记 + + deps, erp, _ = make_transfer_deps(dbs_ready_file) + outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps, + business_date="2026-08-06", now=NOW) + + assert outcome is not None and outcome.inserted > 0 # [断言意图] 同步真实成功 + assert erp.query_calls == 0 # [断言意图] 清除路径零外部调用 + assert report.parse_failed_at is None # [断言意图] 标记已清(三列全空) + assert report.parse_error_code is None + assert report.parse_error_message is None + assert resolve_source_file_status( + source_code="DBS-AWSBI")["file_status"] == "ready" # [断言意图] 投影恢复 ready + + +def test_sync_never_renews_inventory_checked_at_and_resets_nulls_it(app, dbs_ready_file): + # [断言意图] stale 时钟不被换戳续期:refreshed(三证据未变)→ + # inventory_checked_at 保持原值(仅 updated_at 续期);reset_pending + # (证据变化,旧库存作废)→ 取数时刻随 external_quantity 一并置空。 + deps, _, _ = make_transfer_deps(dbs_ready_file) + sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW) + row = TransferInvoiceItem.query.filter_by( + source_code="DBS-AWSBI", invoice_no="HOM-001").first() + assert row.inventory_checked_at is None # [断言意图] 新落行未取数 + + checked = datetime(2026, 9, 24, 9, 0, 0) + row.inventory_checked_at = checked + db.session.commit() + + # 同证据换戳(新 sha、收料事实不变)→ refreshed:取数时刻不得被续期。 + deps.file_repository.set_next_file(source_code="DBS-AWSBI", rows=dbs_ready_file["rows"], + checksum="e" * 64) + outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps, + business_date="2026-08-06", now=NOW) + assert outcome.refreshed >= 1 + db.session.expire_all() + row = TransferInvoiceItem.query.filter_by( + source_code="DBS-AWSBI", invoice_no="HOM-001").first() + assert row.inventory_checked_at == checked # [断言意图] 换戳≠查过库存 + + # 收料数量变化 → reset_pending:旧库存作废,取数时刻同步置空。 + changed = [{**r, "quantity": "1300"} if r["doc_no"] == "HOM-001" else r + for r in dbs_ready_file["rows"]] + deps.file_repository.set_next_file(source_code="DBS-AWSBI", rows=changed, + checksum="d" * 64) + outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps, + business_date="2026-08-06", now=NOW) + assert outcome.reset_pending >= 1 + db.session.expire_all() + row = TransferInvoiceItem.query.filter_by( + source_code="DBS-AWSBI", invoice_no="HOM-001").first() + assert row.external_quantity is None + assert row.inventory_checked_at is None diff --git a/backend/tests/services/in_transit_transfer/test_execute_items.py b/backend/tests/services/in_transit_transfer/test_execute_items.py index 7467a821..2eeb85d3 100644 --- a/backend/tests/services/in_transit_transfer/test_execute_items.py +++ b/backend/tests/services/in_transit_transfer/test_execute_items.py @@ -97,6 +97,8 @@ def test_execute_items_writes_one_order_and_aggregates(transfer_db, dbs_ready_fi linked = _load_items(outcome.run_no) assert all(item.status == "success" for item in linked.values()) assert {item.external_document_no for item in linked.values()} == {doc.erp_document_no} + # [断言意图] 写前复查是真实取数:通过复查的行库存查得时刻已刷新(非 NULL)。 + assert all(item.inventory_checked_at is not None for item in linked.values()) # 一单一次写调用 + 一条挂单写 Attempt(D14:document_id=单 id)。 assert len(erp.write_calls()) == 1 attempts = TransferAttempt.query.filter_by(document_id=doc.id, kind="external_write").all() @@ -165,8 +167,9 @@ def test_execute_items_order_failure_does_not_block_other_orders(transfer_db, db assert linked["HOM-001"].result_code == "business_failed" # 其他单继续:不同收料日期另一单成功。 assert linked["HOX-002"].status == "success" - # 异常项进入结果页"未生成单据"区;两单各一次写调用。 - assert any(exc.invoice_no == "HOM-001" for exc in outcome.result.exceptions) + # [2026-09-29 口径收窄] 失败行已建单 → 不进结果页"未生成单据"区(原因与 + # 重试/关闭动作由调拨单清单卡片承载);两单各一次写调用。 + assert outcome.result.exceptions == () assert len(erp.write_calls()) == 2 @@ -311,7 +314,7 @@ def test_execute_matching_items_unknown_matching_404(transfer_db, dbs_ready_file def test_get_run_restores_document_projection(transfer_db, dbs_ready_file, patch_source_file_status): - """GET run → 按 ERP 单号聚合单据 + 未生成单据异常分开展示(单据级语义)。""" + """GET run → 按 ERP 单号聚合单据;失败单走 orders 卡片(2026-09-29 异常区收窄)。""" patch_source_file_status() deps, erp, items = _two_group_deps(dbs_ready_file, patch_source_file_status) erp.write_scenarios["HOM-001"] = "business_failed" @@ -319,6 +322,8 @@ def test_get_run_restores_document_projection(transfer_db, dbs_ready_file, patch restored = get_run(outcome.run_no) assert restored["run_no"] == outcome.run_no - # 成功单聚合为单据;失败单行进入异常清单。 + # 成功单聚合为单据;失败单行已建单 → 不进异常清单,原因由 orders 行级 reason 承载。 assert len(restored["result"]["external_documents"]) == 1 - assert any(exc["invoice_no"] == "HOM-001" for exc in restored["result"]["exceptions"]) + assert restored["result"]["exceptions"] == [] + failed_orders = [t for t in restored["orders"] if t["status"] == "business_failed"] + assert failed_orders and failed_orders[0]["lines"][0]["reason"] diff --git a/backend/tests/services/in_transit_transfer/test_execution_documents.py b/backend/tests/services/in_transit_transfer/test_execution_documents.py index ae721f32..96358086 100644 --- a/backend/tests/services/in_transit_transfer/test_execution_documents.py +++ b/backend/tests/services/in_transit_transfer/test_execution_documents.py @@ -435,6 +435,14 @@ def test_result_unknown_order_blocks_new_rows( assert blocked.result_code == "group_order_unresolved" # 断言意图:全程零新增外部写调用(fail-closed)。 assert len(erp.write_calls()) == calls_after_first + # [2026-09-29 异常区收窄] 未建单阻断行仍进异常清单(唯一保留场景),且带 + # 行级人话原因:reason=状态码、message=行级 result_message(含阻断单号, + # 前端优先展示)、facts=数量对账。 + restored = execution_service.get_run(run2.run_no) + exceptions = restored["result"]["exceptions"] + assert [exc["invoice_no"] for exc in exceptions] == ["HOM-NEW"] + assert exceptions[0]["reason"] == "group_order_unresolved" + assert "blocked until resolved" in exceptions[0]["message"] db.session.expire_all() @@ -836,11 +844,13 @@ def test_serialize_run_orders_projects_multi_status_order_list( orders = execution_service.serialize_run_orders(run) assert len(orders) == 2 - # 断言意图:单序稳定(created_at/id 升序 = 组建单的组键升序)。 + # 断言意图:单序稳定(2026-09-29 投影排序=收料日期→数据源→库位,跨数据源 + # 不再随建单序乱序;本例同数据源,收料日期升序)。 assert [t["receipt_date"] for t in orders] == ["2026-08-04", "2026-08-05"] failed, success = orders - # 断言意图:计划 Task 11 JSON 规格逐键——order 八键、line 六键(+reason: - # 框线图失败行原因展示契约,控制器裁决扩充,T13-3)。 + # 断言意图:计划 Task 11 JSON 规格逐键——order 八键、line 七键(+invoice_no: + # 行级溯源收料通知号 2026-09-29 契约扩充;+reason:框线图失败行原因展示契约, + # 控制器裁决扩充,T13-3)。 assert set(failed.keys()) == { "doc_no", "receipt_date", "from_warehouse", "to_warehouse", "status", "erp_document_no", "error_message", "lines", @@ -848,6 +858,7 @@ def test_serialize_run_orders_projects_multi_status_order_list( assert failed["status"] == "business_failed" assert failed["erp_document_no"] is None assert failed["lines"] == [{ + "invoice_no": "HOX-B", "material_no": "MAT-002", "material_name": "物料MAT-002", "lot_no": "LOT-20", "quantity": "700.000000", "unit": "EA", "reason": "rejected by external system", @@ -858,6 +869,7 @@ def test_serialize_run_orders_projects_multi_status_order_list( # 单位唯一来源=ERP 库存单位(Fake 默认 EA,img09 契约),文件单位不参与; # 成功行 reason 为 None(键恒出现,T13-3 契约)。 assert success["lines"] == [{ + "invoice_no": "HOM-A", "material_no": "MAT-001", "material_name": "物料MAT-001", "lot_no": "LOT-10", "quantity": "500.000000", "unit": "EA", "reason": None, }] diff --git a/backend/tests/services/in_transit_transfer/test_matching_inplace.py b/backend/tests/services/in_transit_transfer/test_matching_inplace.py index 1f53bdf0..41c50733 100644 --- a/backend/tests/services/in_transit_transfer/test_matching_inplace.py +++ b/backend/tests/services/in_transit_transfer/test_matching_inplace.py @@ -1,9 +1,8 @@ """行原地刷新与文件版本戳测试(L1,SQLite 内存库)。 用途:验证重复匹配对既有 InvoiceItem 行为"原地刷新"(不迁移 matching_id、显式续 - updated_at)、行携带证据同步落地的 file_sha256 版本戳,以及文件新版本缺失行 - 时 blocked_file_removed 标记【2026-09-25 语义变更:消失行标记归 - evidence_sync(四元组身份判定),匹配不再解析文件、只做库存落位】; + updated_at)、行携带证据同步落地的 file_sha256 版本戳,以及文件新版本缺席行 + 存续(只换戳不改状态)【2026-09-28 语义:缺席≠删除,归 evidence_sync】; 最近匹配计数按匹配 scope 实时聚合(不再按行归属)。 依赖:transfer_db、matching_service、evidence_sync(seed_rows_from_file 桥)、 transfer_type、repo_fakes。 @@ -115,9 +114,9 @@ def test_scope_query_sees_same_rows_for_overlapping_matchings(transfer_db, dbs_r assert sum(1 for r in rows if r.status == "blocked_recoverable") == 1 -def test_file_removed_marks_ready_rows_blocked(transfer_db, dbs_ready_file): - """文件新版本缺失该行:evidence_sync 将消失行标 blocked_file_removed(2026-09-25 - 消失行标记归证据同步);仍在文件中的行保持可执行并换新版本戳。""" +def test_file_absent_keeps_ready_rows_and_restamps(transfer_db, dbs_ready_file): + """文件新版本缺席该行:evidence_sync 存续(状态原样、只换戳);仍在文件中的行 + 保持可执行并换新版本戳。(2026-09-28:缺席≠删除)""" deps, erp, _ = make_transfer_deps(dbs_ready_file) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") # HOM-001 → executable erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # HOX-002 → executable @@ -127,28 +126,33 @@ def test_file_removed_marks_ready_rows_blocked(transfer_db, dbs_ready_file): hox = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOX-002").first() assert hom.status == "ready_to_execute" - # 新文件版本:内容只剩 HOX-002(HOM-001 消失),checksum 变化——先经证据同步 - # 落地新版本(消失标记在此发生),再跑匹配落位剩余行。 + # 新文件版本:内容只剩 HOX-002(HOM-001 缺席),checksum 变化——证据同步只换戳。 new_file = _file_without(dbs_ready_file, "HOM-001", checksum="e" * 64) deps2, erp2, _ = make_transfer_deps(new_file) - erp2.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # HOX-002 仍可执行 + # 存续行仍会进入匹配圈(缺席≠出清):两边库存都要备齐,避免二次匹配误伤缺席行。 + erp2.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") + erp2.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") seed_rows_from_file("DBS-AWSBI", deps2, "2026-08-06") - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps2) db.session.refresh(hom) db.session.refresh(hox) - # [断言意图] 上一版本可执行、新版本消失的行必须停用(否则会按过期数据执行); - # 仍在文件中的行随新版本换戳(证据同步刷新)并保持可执行(匹配落位)。 - assert hom.status == "blocked_recoverable" - assert hom.result_code == "blocked_file_removed" - assert hom.result_message == "receipt row removed from latest file" - assert hox.status == "ready_to_execute" + # [断言意图] 同步后:缺席行状态原样保留(ready),只换最新文件戳;不产生 blocked_file_removed。 + assert hom.status == "ready_to_execute" + assert hom.result_code != "blocked_file_removed" + assert _item_evaluated_sha(hom) == "e" * 64 assert _item_evaluated_sha(hox) == "e" * 64 + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps2) + db.session.refresh(hom) + db.session.refresh(hox) + # [断言意图] 二次匹配后:缺席存续行与在文件行均可执行(两边库存齐备)。 + assert hom.status == "ready_to_execute" + assert hox.status == "ready_to_execute" -def test_file_removed_by_identity_even_without_stamp(transfer_db, dbs_ready_file): - """[语义变更 2026-09-25] 消失行标记按 (来源,单号,料号,日期) 四元组身份判定: - 行上无 file_sha256(存量数据)同样不漏标;仍在文件中的无戳行随最新文件回填戳。""" + +def test_file_absent_restamps_even_without_prior_stamp(transfer_db, dbs_ready_file): + """[语义变更 2026-09-28] 缺席存续按四元组身份判定:行上无 file_sha256(存量数据) + 同样只换戳不改状态;仍在文件中的无戳行随最新文件回填戳。""" deps, erp, _ = make_transfer_deps(dbs_ready_file) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") @@ -172,18 +176,18 @@ def test_file_removed_by_identity_even_without_stamp(transfer_db, dbs_ready_file db.session.refresh(hom) db.session.refresh(hox) - # [断言意图] 身份判定不依赖版本戳:消失行必须停用(防按过期数据执行), - # 不会因存量行缺戳而漏标;在文件行无证据变化 → 只换戳不重置待查。 - assert hom.status == "blocked_recoverable" - assert hom.result_code == "blocked_file_removed" + # [断言意图] 身份判定不依赖版本戳:缺席行存续(状态保留),回填最新戳; + # 在文件行无证据变化 → 只换戳不重置待查。 + assert hom.status == "ready_to_execute" + assert hom.result_code != "blocked_file_removed" + assert _item_evaluated_sha(hom) == "e" * 64 assert hox.status == "ready_to_execute" assert _item_evaluated_sha(hox) == "e" * 64 -def test_file_removed_covers_blocked_missing_rows(transfer_db, dbs_ready_file): - """[语义变更 2026-09-25] 非终态行(含 blocked)从最新文件消失 → 统一标 - blocked_file_removed:其既有解释(数量不一致)基于旧文件证据,证据已消失, - 保留旧解释会误导排查;匹配圈行与 restore 视图均不再展示该行(仅入 invalid_count)。""" +def test_file_absent_keeps_blocked_mismatch_explanation(transfer_db, dbs_ready_file): + """[语义变更 2026-09-28] 非终态 blocked 行从最新文件缺席 → 存续:保留既有 + 数量不一致解释(缺席≠删除,不改标 blocked_file_removed)。""" deps, erp, _ = make_transfer_deps(dbs_ready_file) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # HOM-001 → 数量不一致 blocked erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # HOX-002 → executable @@ -199,11 +203,10 @@ def test_file_removed_covers_blocked_missing_rows(transfer_db, dbs_ready_file): seed_rows_from_file("DBS-AWSBI", deps2, "2026-08-06") db.session.refresh(hom) - # [断言意图] 消失的 blocked 行改标 file_removed(旧阻断解释作废); - # 该行退出 restore 明细视图(出清语义),不占用 blocked_count。 + # [断言意图] 缺席不改写既有阻断解释;版本戳换到最新文件。 assert hom.status == "blocked_recoverable" - assert hom.result_code == "blocked_file_removed" - assert hom.result_message == "receipt row removed from latest file" + assert hom.result_code == "blocked_quantity_mismatch" + assert _item_evaluated_sha(hom) == "e" * 64 def test_invoice_in_scope_predicate(): diff --git a/backend/tests/services/in_transit_transfer/test_matching_service.py b/backend/tests/services/in_transit_transfer/test_matching_service.py index 80901be9..66da2204 100644 --- a/backend/tests/services/in_transit_transfer/test_matching_service.py +++ b/backend/tests/services/in_transit_transfer/test_matching_service.py @@ -1,7 +1,7 @@ """在途调拨匹配服务测试(L1,SQLite 内存库)。 -用途:验证 D+1 过滤(当天收料 外部系统 调用=0)、严格数量匹配、来源隔离、 - 匹配快照 Hash 稳定、缺文件等待与进度恢复。 +用途:验证 T+lag 成熟过滤(套件钉 lag=1)、严格数量匹配、来源隔离、 + 匹配快照 Hash 稳定、缺文件等待与进度恢复;专项用例锁生产默认 lag=2。 依赖:app fixture、transfer_db、fakes、repo_fakes、matching_service。 逻辑:全部经真实 ORM 落库(create_matching/restore_matching), 外部依赖注入 Fake 替身。 @@ -11,7 +11,9 @@ from __future__ import annotations import pytest +from app import db from app.core.errors import ValidationError +from app.models import TransferInvoiceItem from app.services.in_transit_transfer.matching_service import ( RouteMapping, TransferDeps, @@ -332,7 +334,7 @@ def test_receipt_date_range_filters_invoices(transfer_db, dbs_ready_file): def test_receipt_date_range_end_beyond_d1_rejected(transfer_db, dbs_ready_file): - """卡控:截止日期超出 D+1 规则(业务日期-1)必须拒绝。""" + """卡控:截止日期超出成熟规则(业务日期-lag,套件钉值 lag=1)必须拒绝。""" from app.core.errors import ValidationError deps, erp, _ = _deps(dbs_ready_file) @@ -344,8 +346,43 @@ def test_receipt_date_range_end_beyond_d1_rejected(transfer_db, dbs_ready_file): assert exc_info.value.code == "TRANSFER.RECEIPT_DATE_RANGE_INVALID" -def test_route_not_resolved_marks_source_failed(dbs_ready_file): - """来源缺少路由映射 → 该来源阶段失败,其余来源继续(fail-closed)。""" +def test_t_plus_2_default_boundary_yesterday_not_matured(app, dbs_ready_file): + """生产默认 lag=2 边界:昨天(T-1)收料 not_matured,改到 T-2 后可预检。 + + [断言意图] 套件 conftest 把 lag 钉为 1(存量夹具语义);本用例显式恢复生产 + 默认 2,锁定真实默认口径不被钉值掩盖(海外时差:28 号最早处理 26 号)。 + """ + deps, erp, _ = _deps(dbs_ready_file) + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") + erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") + seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") + app.config["IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS"] = 2 # 覆盖套件钉值,锁生产默认 + + result = run_matching( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + ) + # [断言意图] 夹具行收料 2026-08-05(T-1):默认 lag=2 下全部未成熟,零 ERP 调用。 + assert result.summary.counts.not_matured_count == 2 + assert result.summary.counts.executable_count == 0 + assert_erp_calls(erp, 0) + + # [边界] 收料日期改到 T-2(2026-08-04)后即可进入匹配并严格匹配成功。 + for row in TransferInvoiceItem.query.filter_by(source_code="DBS-AWSBI").all(): + row.receipt_date = "2026-08-04" + db.session.flush() + result2 = run_matching( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + ) + assert result2.summary.counts.executable_count == 2 + + +def test_route_not_resolved_stays_row_level_not_source_failed(dbs_ready_file): + """路由缺失 → 行 blocked_route_not_resolved;来源保持 file_ready(不抬升顶栏)。 + + [断言意图] 2026-09-29 失败分层:路由不可解析是行级数据质量问题(可解释、 + 可重查),不再整源抬升 failed——来源有可用文件时 stage 保持 file_ready 且 + 无 error_code,失败事实只落在行 result 上。 + """ erp = FakeCapabilityClient() rpa = FakeRPA() deps = TransferDeps( @@ -359,8 +396,13 @@ def test_route_not_resolved_marks_source_failed(dbs_ready_file): source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps, ) by_source = {stage.source_code: stage for stage in result.sources} - assert by_source["DBS-AWSBI"].stage == "failed" + assert by_source["DBS-AWSBI"].stage == "file_ready" + assert by_source["DBS-AWSBI"].error_code is None assert by_source["CRANE-SZ"].stage == "waiting_rpa_callback" # 无文件 → 等待,不阻断 + assert all( + item.result == "blocked_route_not_resolved" + for item in result.items if item.source_code == "DBS-AWSBI" + ) def test_run_matching_consumes_movement_field_rows(app): @@ -500,3 +542,52 @@ def test_placeholder_transfer_types_fail_closed(): ) assert invalid.value.code == "TRANSFER.TRANSFER_TYPE_INVALID" assert TransferRun.query.count() == 0 + + +def test_evaluation_stamps_inventory_checked_at(dbs_ready_file): + # [断言意图] 匹配评估是真实取数:落定 external_quantity 的分支同步写库存 + # 查得时刻(inventory_checked_at)——stale 徽标判定时钟的数据来源。 + deps, erp, _ = _deps(dbs_ready_file) + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") + seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") + run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + row = TransferInvoiceItem.query.filter_by( + source_code="DBS-AWSBI", invoice_no="HOM-001").first() + assert row.status == "ready_to_execute" + assert row.inventory_checked_at is not None + + +def test_executable_list_stale_clock_is_inventory_checked_at(app, dbs_ready_file): + # [断言意图] stale/checked_at 挂库存查得时刻(2026-09-29 时钟换源):取数超 + # 阈值(TestingConfig 钉 24h)→ stale=True 且 checked_at=取数时刻; + # 无库存数据(NULL)→ 不判定(stale=False、checked_at 空)—— + # updated_at 被证据同步每日续期,不得再作为该徽标的时钟。 + from datetime import datetime, timedelta + + from app.services.in_transit_transfer.matching_service import list_executable_items + + old_ts = datetime.utcnow() - timedelta(hours=25) + db.session.add(TransferInvoiceItem( + matching_id=None, source_code="DBS-AWSBI", invoice_no="HOX-OLD", + material_no="MAT-001", material_name="n", specification="", + receipt_date="2026-09-01", status="ready_to_execute", result_code=None, + result_message=None, from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01", + receipt_quantity="1200", external_quantity="1200", lot_no="LOT-10", + receipt_warehouse_code="W1", unit="PCS", raw_lines_json=[], + inventory_checked_at=old_ts, + )) + db.session.add(TransferInvoiceItem( + matching_id=None, source_code="DBS-AWSBI", invoice_no="HOX-NOCHK", + material_no="MAT-001", material_name="n", specification="", + receipt_date="2026-09-01", status="ready_to_execute", result_code=None, + result_message=None, from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01", + receipt_quantity="1200", external_quantity=None, lot_no="LOT-10", + receipt_warehouse_code="W1", unit="PCS", raw_lines_json=[], + )) + db.session.commit() + payload = list_executable_items() + items = {i.invoice_no: i for i in payload["items"]} + assert items["HOX-OLD"].stale is True + assert items["HOX-OLD"].checked_at == old_ts.isoformat() + assert items["HOX-NOCHK"].stale is False + assert items["HOX-NOCHK"].checked_at is None diff --git a/backend/tests/services/in_transit_transfer/test_movement_file_repository.py b/backend/tests/services/in_transit_transfer/test_movement_file_repository.py index 522b75fe..3340edd8 100644 --- a/backend/tests/services/in_transit_transfer/test_movement_file_repository.py +++ b/backend/tests/services/in_transit_transfer/test_movement_file_repository.py @@ -132,3 +132,52 @@ def test_extract_movement_rows_skips_missing_alias_columns(): # 部分映射下溯源字段仍在:sheet/row_no 不依赖业务列是否齐全。 assert rows[0]['sheet'] == 'S' assert rows[0]['row_no'] == 2 + + +def test_extract_movement_rows_normalizes_ssrs_wrapped_headers(): + """DSV SSRS 表头单元格内换行时,须与无换行别名匹配。 + + [断言意图] 真实收料文件表头为 External\\nASN # / Qty\\nReceived 等; + 绑定规则别名写成 External ASN #。归一化后须命中 doc_no/quantity, + 否则 evidence_sync 整链 missing_invoice_no。 + """ + wb = Workbook() + ws = wb.active + ws.title = 'LognetAWSReceiptDetail3lv' + # 第 1 行标题,第 2 行表头(含换行),第 3 行起数据——与 profile header_row_index=2 对齐。 + ws.append(['AWS Receipt Detail']) + ws.append([ + 'Supplier', 'External\nASN #', 'Date\nReceived', 'External\nLine #', + 'Supplier Sku', 'Sku Description', 'Qty\nReceived', 'Warehouse', + ]) + ws.append([ + 'Well Trust', 'ASN-PHX-1', '2026-08-13', '0010', + 'MAT-PHX', 'Bracket', 24, 'BYAWSPHX01', + ]) + buf = BytesIO() + wb.save(buf) + rows = _extract_movement_rows( + buf.getvalue(), + field_mapping={ + 'doc_no': 'External ASN #', + 'lot_no': 'External ASN #', + 'line_no': 'External Line #', + 'material_code': 'Supplier Sku', + 'material_name': 'Sku Description', + 'quantity': 'Qty Received', + 'movement_date': 'Date Received', + 'warehouse_code': 'Warehouse', + }, + sheet_name='LognetAWSReceiptDetail3lv', + header_row_index=2, + ) + assert len(rows) == 1 + assert rows[0]['doc_no'] == 'ASN-PHX-1' + assert rows[0]['lot_no'] == 'ASN-PHX-1' + assert rows[0]['material_code'] == 'MAT-PHX' + assert rows[0]['quantity'] == 24 + assert rows[0]['warehouse_code'] == 'BYAWSPHX01' + assert rows[0]['row_no'] == 3 + parsed = parse_movement_rows(source_code='DSV360_AWSBI_BYAWSPHX01', rows=rows) + assert parsed[0].invoice_no == 'ASN-PHX-1' + assert parsed[0].receipt_quantity == 24 diff --git a/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py b/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py index 1e11e2cc..9fe39c4a 100644 --- a/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py +++ b/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py @@ -51,8 +51,11 @@ def test_trigger_receipt_rpa_writes_batch_trigger(app, receipt_source): assert result['callback_id'] assert result['trigger_path'].endswith('.json') assert calls['units'][0]['source_code'] == 'DSV360_AWSDU' - # 关键断言:按需触发取 Warehouse 条件的第一个仓作为拆分维度。 - assert calls['units'][0]['warehouse_id'] == 'AWSDU' + # 关键断言:一源一单元;Warehouse 留在 query_parameters,不再拆 warehouse_id。 + 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'] == 'shipping_receipt_rpa.v1' diff --git a/backend/tests/services/in_transit_transfer/test_requery_batch_query.py b/backend/tests/services/in_transit_transfer/test_requery_batch_query.py new file mode 100644 index 00000000..a8298828 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_requery_batch_query.py @@ -0,0 +1,144 @@ +"""重查按组织批量查询回归(2026-09-29):N 行重查 = 每组织 1 次外部调用。 + +用途:锁死重查外部访问形态——全部重查入口经 retry_service._recheck_items_batch + 按组织分组批量 query_stock(与执行链写前复查同形态);禁止回退逐行单查 + (N 行 N 次外部调用会打崩外部系统)。 +依赖:app fixture、repo_fakes.make_transfer_deps、models。 +逻辑:同组织多行 → 1 次 query_stock 且目标元组一次下传全部行;跨组织 → 每组织 + 各 1 次;单行路由解析失败只跳过该行(ok=False、行未被触碰、未建 Attempt), + 不拖垮同批其他行。 +""" + +from __future__ import annotations + +from datetime import datetime + +import pytest + +from app import db +from app.models import TransferInvoiceItem, TransferMatching, TransferRun +from app.services.in_transit_transfer.matching_service import RouteMapping +from app.services.in_transit_transfer.retry_service import requery_items +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + +pytestmark = [pytest.mark.usefixtures("app")] + + +def _seed(scope_sources, matching_no): + run = TransferRun(run_no=f"RUN-{matching_no}", trigger_type="manual", + business_date="2026-09-24", status="matching", + source_codes_json=scope_sources, counts_json={}, transfer_type="in_transit_to_hub") + db.session.add(run) + db.session.flush() + matching = TransferMatching( + matching_no=matching_no, run_id=run.id, business_date="2026-09-24", + status="success", + scope_json={"source_codes": scope_sources, "receipt_date_from": None, + "receipt_date_to": None, "transfer_type": "in_transit_to_hub"}, + file_snapshot_json={}, mapping_version="v0", strategy_version="v0", + counts_json={}, estimated_transfer_quantity="0", + estimated_external_write_count=0, matching_hash="sha256:x", + expires_at=datetime.utcnow(), + ) + db.session.add(matching) + db.session.flush() + return matching + + +def _seed_row(source_code, invoice_no, lot_no): + row = TransferInvoiceItem( + matching_id=None, source_code=source_code, invoice_no=invoice_no, + material_no="MAT-1", material_name="n", specification="", + receipt_date="2026-09-20", status="blocked_recoverable", + result_code="blocked_quantity_mismatch", result_message="strict quantity mismatch", + from_warehouse="W-FROM", to_warehouse="W-TO", receipt_quantity="36", + external_quantity="30", lot_no=lot_no, receipt_warehouse_code="W1", + unit="PCS", raw_lines_json=[], + ) + db.session.add(row) + db.session.flush() + return row + + +def test_requery_same_org_hits_single_external_call(app): + # [断言意图] 同组织两行重查 = 1 次 query_stock,两行目标元组一次下传; + # 回退逐行单查(2 次调用)即回归。 + matching = _seed(["DBS-AWSBI", "DBS-AWSSG"], "MTG-BATCH-1") + row1 = _seed_row("DBS-AWSBI", "HOX-1", "LOT-1") + row2 = _seed_row("DBS-AWSSG", "HOX-2", "LOT-2") + deps, erp, _ = make_transfer_deps() # 默认路由:两来源同组织 HX-CN01 + erp.seed_stock("MAT-1", "DBS-TRANSIT", "LOT-1", "36") + erp.seed_stock("MAT-1", "AWSSG-TRANSIT", "LOT-2", "36") + + outcome = requery_items(matching_no=matching.matching_no, deps=deps, actor_id="1") + + assert outcome["total"] == 2 + rows = {row["item_id"]: row for row in outcome["results"]} + assert rows[row1.id]["ok"] is True + assert rows[row1.id]["status"] == "ready_to_execute" + assert rows[row2.id]["ok"] is True + assert rows[row2.id]["status"] == "ready_to_execute" + assert erp.query_calls == 1 # [断言意图] 一组(组织)一次批量查询 + assert set(erp.call_log[-1].targets) == { + ("MAT-1", "DBS-TRANSIT", "LOT-1"), ("MAT-1", "AWSSG-TRANSIT", "LOT-2"), + } # [断言意图] 两行目标元组在同一次调用中下传 + + +def test_requery_multi_org_one_call_per_org(app): + # [断言意图] 跨组织行按组织分组各查一次:2 组织 = 2 次调用,各自只带本组目标。 + matching = _seed(["DBS-AWSBI", "DBS-AWSSG"], "MTG-BATCH-2") + _seed_row("DBS-AWSBI", "HOX-3", "LOT-3") + _seed_row("DBS-AWSSG", "HOX-4", "LOT-4") + deps, erp, _ = make_transfer_deps(routes={ + "DBS-AWSBI": RouteMapping(external_org="HX-CN01", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01"), + "DBS-AWSSG": RouteMapping(external_org="HX-SG01", from_warehouse="AWSSG-TRANSIT", to_warehouse="HUB-SG"), + }) + + outcome = requery_items(matching_no=matching.matching_no, deps=deps, actor_id="1") + + assert outcome["total"] == 2 + assert all(row["ok"] for row in outcome["results"]) + assert erp.query_calls == 2 # [断言意图] 每组织恰好一次 + orgs = [record.external_org for record in erp.call_log if record.method == "query_stock"] + assert sorted(orgs) == ["HX-CN01", "HX-SG01"] + + +def test_requery_route_failure_isolates_row(app): + # [断言意图] 单行路由解析失败只跳过该行(ok=False、行未被触碰、未建 Attempt), + # 同批其他行照常批量重查。 + matching = _seed(["DBS-AWSBI", "GHOST-SRC"], "MTG-BATCH-3") + good = _seed_row("DBS-AWSBI", "HOX-5", "LOT-5") + bad = _seed_row("GHOST-SRC", "HOX-6", "LOT-6") + deps, erp, _ = make_transfer_deps() # GHOST-SRC 未配置路由 → RouteNotResolvedError + erp.seed_stock("MAT-1", "DBS-TRANSIT", "LOT-5", "36") + + outcome = requery_items(matching_no=matching.matching_no, deps=deps, actor_id="1") + + rows = {row["item_id"]: row for row in outcome["results"]} + assert rows[good.id]["ok"] is True + assert rows[good.id]["status"] == "ready_to_execute" + assert rows[bad.id]["ok"] is False # [断言意图] 路由失败行原位报错,不炸整批 + assert erp.query_calls == 1 # [断言意图] 失败行不发起外部查询 + db.session.expire(bad) + assert bad.status == "blocked_recoverable" # [断言意图] 失败行未被触碰 + assert bad.attempt_no == 0 # [断言意图] 未创建 Attempt + + +def test_requery_stamps_inventory_checked_at(app): + # [断言意图] 重查是真实取数:成功落 ready 的行同步刷新库存查得时刻 + # (stale 判定时钟),旧时刻被覆盖。 + matching = _seed(["DBS-AWSBI"], "MTG-BATCH-STALE") + row = _seed_row("DBS-AWSBI", "HOX-STALE", "LOT-1") + row.inventory_checked_at = datetime(2026, 9, 1, 8, 0, 0) + db.session.commit() + + deps, erp, _ = make_transfer_deps() + erp.seed_stock("MAT-1", "DBS-TRANSIT", "LOT-1", "36") + outcome = requery_items(matching_no=matching.matching_no, deps=deps, actor_id="1") + + assert outcome["results"][0]["ok"] is True + db.session.expire_all() + refreshed = db.session.get(TransferInvoiceItem, row.id) + assert refreshed.status == "ready_to_execute" + assert refreshed.inventory_checked_at is not None + assert refreshed.inventory_checked_at > datetime(2026, 9, 1, 8, 0, 0) diff --git a/backend/tests/services/in_transit_transfer/test_restore_file_removed_rows.py b/backend/tests/services/in_transit_transfer/test_restore_file_removed_rows.py new file mode 100644 index 00000000..0cbf5c4b --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_restore_file_removed_rows.py @@ -0,0 +1,77 @@ +"""存量误标行修复脚本回归(L1,SQLite 内存库)。 + +用途:锁定 restore_file_removed_transfer_rows.restore_rows 的恢复语义——只动 + blocked_file_removed 误标行,恢复待查态并作废旧库存;其他行绝不触碰。 +依赖:app fixture、dbs_ready_file、evidence_sync(构造前置状态)。 +逻辑:importlib 直载脚本模块(backend/scripts 不在包路径内),只测纯函数。 +""" + +import importlib.util +from datetime import datetime +from pathlib import Path + +import pytest + +from app import db +from app.models import TransferInvoiceItem +from app.services.in_transit_transfer.evidence_sync import sync_source_rows +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + +NOW = datetime(2026, 9, 28, 10, 0, 0) + + +def _load_script(): + """按路径加载修复脚本模块(脚本自举 sys.path,不依赖包安装)。""" + path = Path(__file__).parents[3] / "scripts" / "restore_file_removed_transfer_rows.py" + spec = importlib.util.spec_from_file_location("restore_file_removed_transfer_rows", path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +@pytest.mark.usefixtures("app") +def test_restore_flips_only_file_removed_rows(app, dbs_ready_file): + # [断言意图] 只有 blocked_file_removed 行被恢复为待查态;正常行分毫不动。 + script = _load_script() + deps, _, _ = make_transfer_deps(dbs_ready_file) + sync_source_rows(source_code="DBS-AWSBI", deps=deps, + business_date="2026-08-06", now=NOW) + good = TransferInvoiceItem.query.filter_by( + source_code="DBS-AWSBI", invoice_no="HOM-001").first() + doomed = TransferInvoiceItem.query.filter_by( + source_code="DBS-AWSBI", invoice_no="HOX-002").first() + doomed.status = "blocked_recoverable" + doomed.result_code = "blocked_file_removed" + doomed.result_message = "receipt row removed from latest file" + db.session.flush() + + result = script.restore_rows(source_code="DBS-AWSBI", now=NOW) + + assert result == {"restored": 1} # [断言意图] 只命中误标行 + db.session.refresh(doomed) + assert doomed.status == "matching" # [断言意图] 恢复待查态 + assert doomed.result_code == "pending_stock_check" + assert doomed.result_message is None # [断言意图] 删除解释清除 + assert doomed.external_quantity is None # [断言意图] 旧库存作废待重查 + db.session.refresh(good) + assert good.result_code == "pending_stock_check" # [断言意图] 正常行不触碰 + + +@pytest.mark.usefixtures("app") +def test_restore_is_idempotent(app, dbs_ready_file): + # [断言意图] 修复后再跑一遍 restored=0(无新命中),行状态不再变化。 + script = _load_script() + deps, _, _ = make_transfer_deps(dbs_ready_file) + sync_source_rows(source_code="DBS-AWSBI", deps=deps, + business_date="2026-08-06", now=NOW) + row = TransferInvoiceItem.query.filter_by( + source_code="DBS-AWSBI", invoice_no="HOX-002").first() + row.status = "blocked_recoverable" + row.result_code = "blocked_file_removed" + db.session.flush() + script.restore_rows(source_code="DBS-AWSBI", now=NOW) + + second = script.restore_rows(source_code="DBS-AWSBI", now=NOW) + + assert second == {"restored": 0} # [断言意图] 幂等:无新命中 diff --git a/backend/tests/services/in_transit_transfer/test_schedule_jobs.py b/backend/tests/services/in_transit_transfer/test_schedule_jobs.py index fa4df666..68e20a2e 100644 --- a/backend/tests/services/in_transit_transfer/test_schedule_jobs.py +++ b/backend/tests/services/in_transit_transfer/test_schedule_jobs.py @@ -1,46 +1,220 @@ -"""在途调拨排程注册与执行测试(Phase 3)。 +"""在途调拨排程注册与执行测试。 -用途:验证 08:00 收料文件 / 09:00 自动调拨 platform job 已注册(含参数契约), - handler 返回标准 ScheduleExecuteResult(7 元组)。 -依赖:schedule.job_registry、schedule 两个 in_transit job 模块。 +用途:验证在途自动调拨 platform job 注册契约与 handler 调用形态; + in-transit-receipt-file 已于 2026-09-28 下线(文件就绪保障内建于自动调拨, + 见 job_registry 在途自动调拨描述),此处锁定其"不再注册"防回归。 +依赖:schedule.job_registry、receipt_trigger_service、in_transit_transfer_job。 逻辑:只验证注册契约与调用形态,真实排程触发由 scheduler 驱动。 """ from __future__ import annotations -import pytest +from types import SimpleNamespace from app.services.schedule.job_registry import get_platform_job, list_platform_jobs -def test_receipt_file_job_registered_with_schedule_defaults(): - """08:00 收料文件 job 注册且含 source_codes 参数契约。""" - job = get_platform_job("in-transit-receipt-file") - assert job is not None - assert job.enabled - keys = {field.get("key") for field in job.params_schema} - assert "source_codes" in keys +def test_receipt_file_job_deregistered(): + """in-transit-receipt-file 已下线:不再注册、不可创建。""" + assert get_platform_job("in-transit-receipt-file") is None + keys = {job.key for job in list_platform_jobs()} + assert "in-transit-receipt-file" not in keys def test_transfer_job_registered_with_schedule_defaults(): - """09:00 自动调拨 job 注册且含并发/恢复参数契约。""" + """自动调拨 job 注册且含来源/恢复参数契约;描述不得硬编码时刻。""" + import re + job = get_platform_job("in-transit-transfer") assert job is not None assert job.enabled keys = {field.get("key") for field in job.params_schema} assert {"source_codes", "recover_history"} <= keys + assert not re.search(r"\d{2}:\d{2}", job.description), "描述禁止硬编码执行时刻" -def test_schedule_handlers_return_seven_tuple(): - """两个排程 handler 返回标准 ScheduleExecuteResult(7 元组)。""" - from app.services.schedule.in_transit_receipt_file_job import run_in_transit_receipt_file_schedule +def test_schedule_handler_callable(): + """自动调拨 handler 可调用(返回 7 元组的契约由执行链路测试覆盖)。""" from app.services.schedule.in_transit_transfer_job import run_in_transit_transfer_schedule - for handler in (run_in_transit_receipt_file_schedule, run_in_transit_transfer_schedule): - assert callable(handler) + assert callable(run_in_transit_transfer_schedule) -def test_jobs_visible_in_platform_list(): - """platform job 列表包含两个调拨排程。""" - keys = {job.key for job in list_platform_jobs()} - assert {"in-transit-receipt-file", "in-transit-transfer"} <= keys +def _make_receipt_source(db, source_code: str, *, enabled: bool): + """创建可参与收料的最小库存源(rpa_profile_id 非空,须先建 Profile)。""" + from app.models import ( + ShippingExcelTemplate, + ShippingInventoryParsingProfile, + ShippingInventorySource, + ShippingRpaProfile, + ) + + profile = ShippingRpaProfile( + profile_code=f"RPA_{source_code}", display_name=source_code, connector_type="crane", + login_url="https://test.invalid/login", login_config_json={"auth_mode": "password"}, + ) + db.session.add(profile) + db.session.flush() + source_kwargs: dict = { + "source_code": source_code, "display_name": source_code, "connector_type": "crane", + "rpa_profile_id": profile.id, "enabled": enabled, + } + if enabled: + parsing = ShippingInventoryParsingProfile( + profile_code=f"PARSE_{source_code}", display_name=source_code, version=1, + status="published", file_format="xlsx", + definition_json={"field_mapping": {}, "match_keys": []}, + checksum="0" * 64, structure_definition_json={}, + exact_structure_fingerprint="0" * 64, compatibility_fingerprint="0" * 64, + fingerprint_version=1, + ) + template = ShippingExcelTemplate( + template_code=f"TPL_{source_code}", display_name=source_code, version=1, + status="published", storage_provider="minio", storage_bucket="test", + storage_key=f"test/{source_code}.xlsx", original_filename="t.xlsx", + file_checksum="0" * 64, definition_json={}, definition_checksum="0" * 64, + ) + db.session.add_all([parsing, template]) + db.session.flush() + source_kwargs.update( + parsing_profile_id=parsing.id, excel_template_id=template.id, + warehouse_resolution_mode="fixed", fixed_warehouse_id="WH1", + ) + else: + source_kwargs.update(warehouse_resolution_mode="inventory_match", fixed_warehouse_id=None) + source = ShippingInventorySource(**source_kwargs) + db.session.add(source) + return source + + +def test_list_receipt_capable_source_codes_filters_by_enabled_and_config(app, transfer_db): + """缺省来源口径:enabled 库存源且已配置收料报表才入选;停用/无配置排除。""" + from app.models import ShippingReceiptReportConfig + from app.services.in_transit_transfer.receipt_trigger_service import list_receipt_capable_source_codes + + enabled = _make_receipt_source(transfer_db, "CRANE_SGP", enabled=True) + _make_receipt_source(transfer_db, "DBS_OFF", enabled=False) + _make_receipt_source(transfer_db, "CRANE_NOCONF", enabled=True) + transfer_db.session.flush() + transfer_db.session.add(ShippingReceiptReportConfig( + inventory_source_id=enabled.id, report_path_json={}, query_parameters_json=[], + )) + transfer_db.session.commit() + + result = list_receipt_capable_source_codes() + assert "CRANE_SGP" in result + assert "DBS_OFF" not in result + assert "CRANE_NOCONF" not in result + assert result == sorted(result) + + +def test_wanted_source_codes_falls_back_when_empty(monkeypatch): + """09:00 排程来源留空=全部启用收料来源;显式选择优先。""" + import app.services.schedule.in_transit_transfer_job as job_mod + from app.models import ScheduleTask + from app.services.schedule.in_transit_transfer_job import _wanted_source_codes + + monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP", "DBS_HUB"]) + empty = ScheduleTask(job_params={"source_codes": []}) + assert _wanted_source_codes(empty) == ["CRANE_SGP", "DBS_HUB"] + explicit = ScheduleTask(job_params={"source_codes": ["DBS_HUB"]}) + assert _wanted_source_codes(explicit) == ["DBS_HUB"] + string_param = ScheduleTask(job_params={"source_codes": "DBS_HUB"}) + assert _wanted_source_codes(string_param) == ["DBS_HUB"] + + +class _FakeSender: + """记录实例化的发送器替身(断言 handler 接线,不发真实消息)。""" + + instantiated = 0 + + def __init__(self): + type(self).instantiated += 1 + + +def test_handler_wires_sender_and_domain_notification(monkeypatch): + """配了通知人:构造 sender、置领域自管标记、recipients 透传。""" + import app.services.schedule.in_transit_transfer_job as job_mod + from app.models import ScheduleRun, ScheduleTask + + monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"]) + captured = {} + + def _fake_auto_transfer(**kwargs): + captured.update(kwargs) + return job_mod.AutoTransferOutcome() + + monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer) + monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None)) + + class _FakeSenderInner: + pass + + monkeypatch.setattr(job_mod, "WecomSummarySender", _FakeSenderInner) + + task = ScheduleTask(job_params={"source_codes": [], "recover_history": True, "notify_user_ids": ["7"]}) + run = ScheduleRun(run_no="RUNR-1", status="running") + total, success, failed, skipped, results, warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run) + + assert captured["source_codes"] == ["CRANE_SGP"] + assert captured["recipients"] == ["7"] + assert isinstance(captured["sender"], _FakeSenderInner) + assert run.response_summary_json["domain_notification_managed"] is True + assert (total, success, failed, skipped) == (0, 0, 0, 0) + + +def test_handler_without_recipients_skips_domain_notification(monkeypatch): + """未配通知人:sender=None、不置标记、落回框架通用通知(由框架按任务配置发送)。""" + import app.services.schedule.in_transit_transfer_job as job_mod + from app.models import ScheduleRun, ScheduleTask + + monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"]) + captured = {} + + def _fake_auto_transfer(**kwargs): + captured.update(kwargs) + return job_mod.AutoTransferOutcome() + + monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer) + monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None)) + + task = ScheduleTask(job_params={}) + run = ScheduleRun(run_no="RUNR-2", status="running") + job_mod.run_in_transit_transfer_schedule(task, run) + + assert captured["sender"] is None + assert captured["recipients"] == [] + assert not (run.response_summary_json or {}).get("domain_notification_managed") + + +def test_handler_hard_failure_keeps_framework_notification(monkeypatch): + """硬失败(有通知人、无 run_no、有 errors):仍构造并传入 sender,但不置自管标记。""" + import app.services.schedule.in_transit_transfer_job as job_mod + from app.models import ScheduleRun, ScheduleTask + + monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"]) + captured = {} + + def _fake_auto_transfer(**kwargs): + captured.update(kwargs) + return job_mod.AutoTransferOutcome(errors=["match pipeline boom"]) + + monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer) + monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None)) + + class _FakeSenderInner: + pass + + monkeypatch.setattr(job_mod, "WecomSummarySender", _FakeSenderInner) + + task = ScheduleTask(job_params={"notify_user_ids": ["7"]}) + run = ScheduleRun(run_no="RUNR-3", status="running") + _total, _success, _failed, _skipped, _results, _warnings, errors = ( + job_mod.run_in_transit_transfer_schedule(task, run) + ) + + # 断言:sender 已构造并透传;硬失败不抑制框架完成卡。 + assert isinstance(captured["sender"], _FakeSenderInner) + assert captured["recipients"] == ["7"] + assert not (run.response_summary_json or {}).get("domain_notification_managed") + assert errors == ["match pipeline boom"] 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 84192834..8adb03f2 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 @@ -1,10 +1,12 @@ """来源收料文件状态投影服务测试。 用途:验证 resolve_source_file_status 只读货代收料事实(UnitRun/ReportFile), - 按来源投影 ready/fetching/failed/expired/none。调拨不维护独立抓取状态表。 + 按来源投影 ready/fetching/failed/expired/parse_failed/none,并验证解析失败 + 标记 record/clear 的往返语义。调拨不维护独立抓取状态表。 依赖:app(SQLite)、ShippingInventorySource 种子、ScheduleTask/ScheduleRun/UnitRun/ReportFile。 -逻辑:有当天(业务日)抓取且未过期文件→ready;有进行中单元→fetching; - 最新单元失败终态→failed;保留期已到或隔日旧文件(未清理)→expired;否则→none。 +逻辑:有当天(业务日)抓取且未过期文件→ready(若标记解析失败→parse_failed); + 有进行中单元→fetching;最新单元失败终态→failed; + 保留期已到或隔日旧文件(未清理)→expired;否则→none。 """ from __future__ import annotations @@ -154,3 +156,54 @@ def test_stale_report_is_expired(app, receipt_unit_run): status = resolve_source_file_status(source_code=SOURCE_CODE) assert status['file_status'] == 'expired' assert status['has_ready_file'] is False + + +def test_usable_file_with_parse_failed_at_projects_parse_failed(app, receipt_unit_run): + """可用归档文件若已标记 parse_failed_at → file_status=parse_failed 且不可当 ready。""" + from app import db + from app.models import ShippingReceiptReportFile + + receipt_unit_run.status = 'success' + digest = hashlib.sha256(b'bad workbook').hexdigest() + db.session.add(ShippingReceiptReportFile( + unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test', + storage_key='shipping/receipt/bad.xlsx', original_filename='bad.xlsx', + file_size=16, sha256=digest, + parse_failed_at=datetime.utcnow(), + parse_error_code='TRANSFER_FILE_SCHEMA_INVALID', + parse_error_message='schema', + )) + db.session.commit() + status = resolve_source_file_status(source_code=SOURCE_CODE) + assert status["file_status"] == "parse_failed" + assert status["has_ready_file"] is False + assert status["file_sha256"] == digest + + +def test_record_and_clear_parse_failure_roundtrip(app, receipt_unit_run): + """record 写入三列;clear 清空后投影回 ready。""" + from app import db + from app.models import ShippingReceiptReportFile + from app.services.in_transit_transfer.source_file_status import ( + clear_receipt_parse_failure, + record_receipt_parse_failure, + resolve_source_file_status, + ) + + receipt_unit_run.status = 'success' + digest = hashlib.sha256(b'roundtrip').hexdigest() + report = ShippingReceiptReportFile( + unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test', + storage_key='shipping/receipt/ok.xlsx', original_filename='ok.xlsx', + file_size=16, sha256=digest, + ) + db.session.add(report) + db.session.commit() + record_receipt_parse_failure( + report=report, error_code="TRANSFER_FILE_SCHEMA_INVALID", error_message="bad", + ) + db.session.commit() + assert resolve_source_file_status(source_code=SOURCE_CODE)["file_status"] == "parse_failed" + clear_receipt_parse_failure(report=report) + db.session.commit() + assert resolve_source_file_status(source_code=SOURCE_CODE)["file_status"] == "ready" diff --git a/backend/tests/services/in_transit_transfer/test_wecom_sender.py b/backend/tests/services/in_transit_transfer/test_wecom_sender.py new file mode 100644 index 00000000..1e88ed64 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_wecom_sender.py @@ -0,0 +1,89 @@ +"""企微汇总发送器(WecomSummarySender)测试。 + +用途:锁定 notify_run_summary 真实通道的投递语义——逐收件人解析 wecom_userid + 后经 schedule_completed 事件开关发送;≥1 人送达即 success;无可用收件人 + 或全部失败为 failed(由 notify_run_summary 落库,不影响 ERP 结果)。 +依赖:app fixture(SQLite)、User 行、monkeypatch send_wecom_event_message。 +逻辑:纯单元用例;不发送真实企微消息。 +""" + +from __future__ import annotations + +import pytest + +import app.services.in_transit_transfer.wecom_sender as ws + + +@pytest.fixture +def wecom_user_ids(transfer_db): + """两个用户:一个绑定企微、一个未绑定;返回 {角色: 用户id}。""" + from app.models import User + + bound = User(username="u_bound", email="u_bound@test.dev", wecom_userid="wecom_bound") + loose = User(username="u_loose", email="u_loose@test.dev", wecom_userid=None) + transfer_db.session.add_all([bound, loose]) + transfer_db.session.commit() + return {"bound": bound.id, "loose": loose.id} + + +def _summary() -> dict: + return { + "run_no": "RUN-20260928-XYZ789", + "status": "success", + "business_date": "2026-09-28", + "counts": {"file_invoice_count": 2, "matched_count": 2, "executable_count": 2}, + } + + +def test_delivers_to_wecom_bound_user_only(monkeypatch, wecom_user_ids): + """送达绑定用户计 delivered;未绑定用户跳过;≥1 送达即 success。""" + calls = [] + + def _fake(**kwargs): + calls.append(kwargs) + return {"ok": True, "trace_id": "t1"} + + monkeypatch.setattr(ws, "send_wecom_event_message", _fake) + outcome = ws.WecomSummarySender().send_summary( + run_no="RUN-20260928-XYZ789", summary=_summary(), + recipients=[str(wecom_user_ids["bound"]), str(wecom_user_ids["loose"])], + ) + assert outcome == {"status": "success", "delivered": 1} + assert len(calls) == 1 + assert calls[0]["event_type"] == "schedule_completed" + assert calls[0]["user"].wecom_userid == "wecom_bound" + assert calls[0]["title"].startswith("在途自动调拨 RUN-") + + +def test_failed_when_all_sends_fail(monkeypatch, wecom_user_ids): + """企微侧全部失败 → failed + WECOM_SEND_FAILED(交 notify_run_summary 落库)。""" + monkeypatch.setattr(ws, "send_wecom_event_message", lambda **kwargs: {"ok": False, "reason": "event_disabled"}) + outcome = ws.WecomSummarySender().send_summary( + run_no="RUN-1", summary=_summary(), recipients=[str(wecom_user_ids["bound"])], + ) + assert outcome["status"] == "failed" + assert outcome["error_code"] == "WECOM_SEND_FAILED" + assert outcome["error_message"] == "event_disabled" + + +def test_failed_when_no_wecom_bound_recipient(monkeypatch, wecom_user_ids): + """收件人全部未绑定企微 → failed(no wecom-bound recipients),不调用发送。""" + sent = [] + + monkeypatch.setattr(ws, "send_wecom_event_message", lambda **kwargs: sent.append(kwargs)) + outcome = ws.WecomSummarySender().send_summary( + run_no="RUN-1", summary=_summary(), recipients=[str(wecom_user_ids["loose"])], + ) + assert outcome["status"] == "failed" + assert outcome["error_message"] == "no wecom-bound recipients" + assert sent == [] + + +def test_non_digit_recipients_ignored(monkeypatch, wecom_user_ids): + """非数字收件人(脏数据)直接忽略,不查询不发送。""" + monkeypatch.setattr(ws, "send_wecom_event_message", lambda **kwargs: {"ok": True}) + outcome = ws.WecomSummarySender().send_summary( + run_no="RUN-1", summary=_summary(), recipients=["abc", ""], + ) + assert outcome["status"] == "failed" + assert outcome["error_message"] == "no wecom-bound recipients" diff --git a/backend/tests/test_admin_shipping_receipt_config.py b/backend/tests/test_admin_shipping_receipt_config.py index 4207a5e1..c6bc90ad 100644 --- a/backend/tests/test_admin_shipping_receipt_config.py +++ b/backend/tests/test_admin_shipping_receipt_config.py @@ -29,7 +29,7 @@ def _create_users() -> None: def _dbs_payload() -> dict: - """构造 DBS 收料配置;Warehouse 条件即逐仓拆分维度,日期未出现表示保持系统页面默认 NULL。""" + """构造 DBS 收料配置;Warehouse 为可选筛选条件,日期未出现表示保持系统页面默认。""" return { 'report_path_json': { 'program_group': 'Bison', 'program_label': 'AWSBI', @@ -66,7 +66,7 @@ def test_admin_saves_independent_dbs_receipt_config_and_audit(app, client): ) assert response.status_code == 200 config = parse_api_data(response.get_json()) - # 关键断言:Warehouse 条件原样保存,作为逐仓拆分维度的唯一持久化位置。 + # 关键断言:Warehouse 条件原样保存(可选筛选,不作为单元门禁)。 warehouse_condition = next(item for item in config['query_parameters_json'] if item['name'] == 'Warehouse') assert warehouse_condition['values'] == ['AWSDU', 'AWSDU-02'] assert config['report_path_json']['report_group'] == 'Inbound' @@ -85,7 +85,7 @@ def test_admin_saves_independent_dbs_receipt_config_and_audit(app, client): def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, client): - """拒绝日期/selector 等 Driver 细节;DBS 与 Crane 的 Warehouse 规则必须分开。""" + """拒绝日期/selector 等 Driver 细节;DBS Warehouse 可选,Crane 禁止查询条件。""" app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): _create_users() @@ -123,27 +123,16 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c assert response.status_code == 400 assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID' - # 关键断言:Warehouse 条件即逐仓拆分维度——缺失、重复、空值都必须拒绝。 + # 关键断言:Warehouse 条件由管理员自行维护——缺失/空值允许保存,不再强制拦截。 missing_warehouse = _dbs_payload() missing_warehouse['query_parameters_json'] = [{'name': 'Owner', 'mode': 'single', 'values': ['AWS'], 'required': False, 'select_all': False}] response = client.put( f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config', json=missing_warehouse, headers=_headers('receipt-admin', 'admin'), ) - assert response.status_code == 400 - assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID' - - duplicate_warehouse = _dbs_payload() - duplicate_warehouse['query_parameters_json'] = [ - {'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False}, - {'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU-02'], 'required': False, 'select_all': False}, - ] - response = client.put( - f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config', - json=duplicate_warehouse, headers=_headers('receipt-admin', 'admin'), - ) - assert response.status_code == 400 - assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID' + assert response.status_code == 200 + saved_missing = parse_api_data(response.get_json())['query_parameters_json'] + assert len(saved_missing) == 1 and saved_missing[0]['name'] == 'Owner' empty_warehouse = _dbs_payload() empty_warehouse['query_parameters_json'] = [{'name': 'Warehouse', 'mode': 'multi_text', 'values': [], 'required': False, 'select_all': False}] @@ -151,8 +140,9 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config', json=empty_warehouse, headers=_headers('receipt-admin', 'admin'), ) - assert response.status_code == 400 - assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID' + assert response.status_code == 200 + saved_empty = parse_api_data(response.get_json())['query_parameters_json'] + assert len(saved_empty) == 1 and saved_empty[0]['name'] == 'Warehouse' and saved_empty[0]['values'] == [] invalid_crane = { 'report_path_json': {'report_name': 'Other Report'}, diff --git a/backend/tests/test_crane_report_export.py b/backend/tests/test_crane_report_export.py index 2b60d053..85e29f22 100644 --- a/backend/tests/test_crane_report_export.py +++ b/backend/tests/test_crane_report_export.py @@ -18,8 +18,8 @@ def _load_export(): return module -def test_fill_parameters_skips_warehouse(monkeypatch): - """Warehouse 参数应被跳过,不再填写。""" +def test_fill_parameters_skips_all_query_conditions(monkeypatch): + """Crane 不得填写任何页面查询条件(含 Owner/Project/Warehouse)。""" module = _load_export() calls: list[tuple[str, str, str]] = [] @@ -40,14 +40,15 @@ def test_fill_parameters_skips_warehouse(monkeypatch): "mode": "single", "values": ["OWNER1"], }, - ] + ], + "query": {"owner_code": "OWNER2", "project_code": "PRJ1"}, }, env=lambda name, default="": default, browser_timeout_ms=5_000, select_or_fill=_fake_select, ) - assert calls == [("FREIGHT_RPA_WORKER_CRANE_OWNER_SELECTOR", "Select Owner...", "OWNER1")] + assert calls == [] def test_build_schedule_description_uses_short_uuid_hex(monkeypatch): diff --git a/backend/tests/test_dsv_report_parameters.py b/backend/tests/test_dsv_report_parameters.py index 7b38e7ff..37248f97 100644 --- a/backend/tests/test_dsv_report_parameters.py +++ b/backend/tests/test_dsv_report_parameters.py @@ -189,6 +189,34 @@ def test_resolve_parameter_controls_3lv_report_warehouse_select(): } +def test_resolve_parameter_controls_receipt_detail_warehouse_select(): + """Receipt Detail 的 Warehouse 应按实机 DOM 使用 ctl27_ddValue(非库存默认 ctl17)。""" + module = _load_module() + controls = module.resolve_parameter_controls("Receipt Detail", "Warehouse") + # 关键断言:与 2026-09-28 Bison/AWSBI 实机 DOM(data-parametername=p_dns_cd_wh)一致。 + assert controls == { + "control": "select", + "selector": "#ReportViewerMain_ctl08_ctl27_ddValue", + } + + +def test_resolve_parameter_controls_receipt_detail_awsrtm_warehouse_multi_value(): + """Moerdijk/AWSRTM 收料 Receipt Detail 的 Warehouse 应为 ctl29 multi_value(对齐库存 JDA)。""" + module = _load_module() + controls = module.resolve_parameter_controls( + "Receipt Detail", "Warehouse", program_label="AWSRTM", + ) + # 关键断言:2026-09-28 实机 DOM——txtValue + glyphui-downarrow + divDropDown。 + assert controls == { + "control": "multi_value", + "text": "#ReportViewerMain_ctl08_ctl29_txtValue", + "toggle": "#ReportViewerMain_ctl08_ctl29_ctl01", + "dropdown": "#ReportViewerMain_ctl08_ctl29_divDropDown", + } + # 无 program_label 时仍回落 AWSBI 原生 select,避免误伤。 + assert module.resolve_parameter_controls("Receipt Detail", "Warehouse")["control"] == "select" + + def test_resolve_parameter_controls_unknown_report_empty(): """未登记报表名应返回空配置,由调用方回退参数名默认值(保持旧行为)。""" module = _load_module() @@ -299,4 +327,124 @@ def test_fill_dsv_filter_if_needed_jda_report_uses_template_multi_value(): ) assert payloads, "应进入多选框下拉填充路径而不是无痕失败" - assert payloads[-1]["dropdownSelector"] == "#ReportViewerMain_ctl08_ctl17_divDropDown" + assert any( + payload.get("dropdownSelector") == "#ReportViewerMain_ctl08_ctl17_divDropDown" + for payload in payloads + ), f"应命中 JDA ctl17 multi_value dropdown,实际 payloads={payloads!r}" + + +def test_awsrtm_multi_value_miss_must_not_fallback_to_default_ctl17_ddvalue(monkeypatch, capsys): + """ + 根因回归:默认 Warehouse.selector=ctl17_ddValue 不得在模板 multi_value 命中后残留。 + + [断言意图] multi_value 失败时禁止走 ctl17_ddValue select/fill(08:46 RTM 偶发失败日志形态)。 + """ + module = _load_module() + seen: list[tuple[str, str]] = [] + + monkeypatch.setattr(module, '_fill_multi_value_parameter', lambda *args, **kwargs: False) + + def _fake_fill_select(page, label, value, selector, *, timeout_ms): + seen.append(('select', selector)) + return False + + def _fake_fill_input(root, selector, value): + seen.append(('input', selector)) + return False + + monkeypatch.setattr(module, '_fill_select_parameter', _fake_fill_select) + monkeypatch.setattr(module, '_fill_input_via_script', _fake_fill_input) + monkeypatch.setattr(module, '_find_locator', lambda page, selector: (None, None)) + monkeypatch.setattr(module, '_probe_report_parameter_controls', lambda page: {'roots': 0, 'controls': []}) + + class _FakePage: + frames = [] + + def get_by_text(self, text: str, exact: bool = False): + raise RuntimeError('not visible') + + module.fill_dsv_filter_if_needed( + _FakePage(), + 'FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR', + 'Warehouse', + 'RTM', + env=lambda name, default='': default, + browser_timeout_ms=lambda: 3_000, + report_name='Receipt Detail', + program_label='AWSRTM', + ) + # [断言意图] 不得被默认 select 污染;允许回退到 ctl29_txtValue 文本路径。 + assert not any(selector.endswith('ctl17_ddValue') for _, selector in seen), seen + assert not any(kind == 'select' for kind, _ in seen), seen + captured = capsys.readouterr() + assert 'ctl17_ddValue' not in captured.out + captured.err + + +def test_fill_dsv_filter_if_needed_receipt_awsrtm_uses_ctl29_multi_value(): + """AWSRTM 收料 Receipt Detail 的 Warehouse 应走 ctl29 multi_value,而非 AWSBI ctl27 select。""" + module = _load_module() + payloads: list[dict[str, object]] = [] + + class _FakeLocator: + first = None + + def __init__(self) -> None: + self.first = self + + def wait_for(self, *args, **kwargs) -> None: + return None + + def input_value(self, timeout: int | None = None) -> str: + return "" + + def click(self, timeout: int | None = None, force: bool = False) -> None: + return None + + class _FakeReportRootLocator: + def count(self) -> int: + return 1 + + class _FakeFrame: + def locator(self, selector: str): + if selector == "#ReportViewerMain": + return _FakeReportRootLocator() + return _FakeLocator() + + def evaluate(self, script: str, payload: dict[str, object]) -> bool: + payloads.append(payload) + return True + + class _FakePage: + frames = [_FakeFrame()] + + def get_by_text(self, text: str, exact: bool = False): + raise RuntimeError("not visible") + + module.fill_dsv_filter_if_needed( + _FakePage(), + "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", + "Warehouse", + "AWSRTM", + env=lambda name, default="": default, + browser_timeout_ms=lambda: 3_000, + report_name="Receipt Detail", + program_label="AWSRTM", + ) + + assert payloads, "应进入 AWSRTM multi_value 填充路径" + assert any( + payload.get("dropdownSelector") == "#ReportViewerMain_ctl08_ctl29_divDropDown" + for payload in payloads + ), f"应命中 ctl29 multi_value dropdown,实际 payloads={payloads!r}" + + +def test_fill_multi_value_js_uses_entry_text_not_bare_text(): + """multi_value 勾选脚本须用 entry.text,禁止裸引用 text(AWSRTM ReferenceError 根因)。""" + import inspect + + module = _load_module() + source = inspect.getsource(module._fill_multi_value_parameter) + assert "entry.text" in source + # 禁止在 checkbox 循环里出现未绑定的 `text`(旧脚本 ReferenceError)。 + assert "desiredValues.includes(text" not in source + assert "normalize(text)" not in source or "entryText" in source diff --git a/backend/tests/test_freight_receipt_rpa_callback.py b/backend/tests/test_freight_receipt_rpa_callback.py index 6346e4a1..43c02feb 100644 --- a/backend/tests/test_freight_receipt_rpa_callback.py +++ b/backend/tests/test_freight_receipt_rpa_callback.py @@ -7,6 +7,113 @@ import hashlib import pytest +def test_receipt_unit_processing_and_batch_progress(app): + """开始导出标记 processing;每笔完成后 batch-progress 抬升排程计数。""" + from app import db + from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun + from app.services.schedule.freight_receipt_rpa_finalize import ( + mark_receipt_unit_processing, + report_receipt_batch_progress, + ) + + with app.app_context(): + source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + task = ScheduleTask( + schedule_no='SCH-RECEIPT-LIVE', name='Receipt live progress', schedule_type='platform_job', + platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *', + ) + db.session.add(task) + db.session.flush() + 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}, + ) + db.session.add(run) + db.session.flush() + unit = ShippingReceiptRpaUnitRun( + schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, + connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-live-progress', + status='awaiting_rpa', config_snapshot_json={}, + ) + db.session.add(unit) + db.session.commit() + + marked = mark_receipt_unit_processing({ + 'schema_version': 'shipping_receipt_rpa.v1', + 'callback_id': unit.callback_id, + 'status': 'processing', + }) + assert marked['updated'] is True + db.session.expire_all() + assert db.session.get(ShippingReceiptRpaUnitRun, unit.id).status == 'processing' + + progressed = report_receipt_batch_progress({ + 'schema_version': 'shipping_receipt_rpa.v1', + 'schedule_run_id': run.id, + 'batch_run_no': run.run_no, + 'success_count': 1, + 'skipped_count': 0, + 'failed_count': 0, + }) + assert progressed['updated'] is True + db.session.expire_all() + refreshed = db.session.get(ScheduleRun, run.id) + assert int(refreshed.success_count or 0) == 1 + assert refreshed.response_summary_json['progress']['success_count'] == 1 + + +def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch): + """success 回调在 finalize 前须回写 ScheduleRun 进度计数(对齐 empty/failed)。""" + from app import db + from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun + from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback + + with app.app_context(): + source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + task = ScheduleTask( + schedule_no='SCH-RECEIPT-PROG', name='Receipt progress', schedule_type='platform_job', + platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *', + ) + db.session.add(task) + db.session.flush() + 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}, + ) + db.session.add(run) + db.session.flush() + unit = ShippingReceiptRpaUnitRun( + schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, + connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-progress', + status='awaiting_rpa', config_snapshot_json={}, + ) + db.session.add(unit) + db.session.commit() + monkeypatch.setattr( + 'app.services.shipping_notice.receipt_report_storage._read_receipt_callback_file', + lambda _path: b'receipt-bytes', + ) + monkeypatch.setattr( + 'app.services.shipping_notice.receipt_report_storage.file_asset_storage.upload_bytes', + lambda **_kwargs: None, + ) + payload = { + 'schema_version': 'shipping_receipt_rpa.v1', + 'callback_id': unit.callback_id, + 'status': 'success', + 'file_path': 'Z:/receipt.xlsx', + 'original_filename': 'receipt.xlsx', + 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest(), + } + ingest_receipt_callback(payload) + db.session.expire_all() + refreshed = db.session.get(ScheduleRun, run.id) + # [断言意图] success 后进度至少抬升 success_count;终态可能已 finalize 清 awaiting。 + assert int(refreshed.success_count or 0) >= 1 + + def test_receipt_callback_archives_once_without_inventory_file(app, monkeypatch): """同一 callback 重放只归档一条收料文件,绝不创建库存快照。""" from app import db @@ -105,3 +212,57 @@ def test_receipt_callback_rejects_file_outside_receipt_drop_root(app, tmp_path): with pytest.raises(ValidationError, match='receipt callback file'): _read_receipt_callback_file(str(outside)) + + +def test_ingest_empty_persists_no_receipt_data(app): + """ + empty 回调须落库 no_receipt_data(对齐库存 no_inventory_data)。 + + [断言意图] 单元 status=empty 且 error_code/error_message 为 no_receipt_data,供管理端展示跳过原因。 + """ + from app import db + from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun + from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback + + with app.app_context(): + source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + task = ScheduleTask( + schedule_no='SCH-RECEIPT-EMPTY', + name='Receipt empty', + schedule_type='platform_job', + platform_api_path='freight-receipt-rpa', + owner_user_id=1, + cron_expr='0 8 * * *', + ) + db.session.add(task) + db.session.flush() + run = ScheduleRun(run_no='RUN-RECEIPT-EMPTY', schedule_task_id=task.id, status='running') + db.session.add(run) + db.session.flush() + unit = ShippingReceiptRpaUnitRun( + schedule_run_id=run.id, + inventory_source_id=source.id, + source_code=source.source_code, + connector_type='dbs', + warehouse_id='AWSDU', + callback_id='receipt-callback-empty', + status='awaiting_rpa', + config_snapshot_json={}, + ) + db.session.add(unit) + db.session.commit() + + result = ingest_receipt_callback({ + 'schema_version': 'shipping_receipt_rpa.v1', + 'callback_id': unit.callback_id, + 'status': 'empty', + 'error_code': 'no_receipt_data', + 'error_message': 'no_receipt_data', + }) + assert result['status'] == 'empty' + db.session.expire_all() + saved = db.session.get(ShippingReceiptRpaUnitRun, 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' diff --git a/backend/tests/test_freight_receipt_rpa_notifications.py b/backend/tests/test_freight_receipt_rpa_notifications.py index 8b05ef53..677f5e8a 100644 --- a/backend/tests/test_freight_receipt_rpa_notifications.py +++ b/backend/tests/test_freight_receipt_rpa_notifications.py @@ -90,27 +90,35 @@ def _patch_unified_wecom(monkeypatch, *, enabled_events: bool): 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('app.services.wecom_notify.send_wecom_textcard_message', _fake_send_textcard) + monkeypatch.setattr(f'{notify_mod}.send_wecom_textcard_message', _fake_send_textcard) if enabled_events: - monkeypatch.setattr('app.services.wecom_notify._get_enabled_events', lambda: {'schedule_completed'}) - monkeypatch.setattr('app.services.wecom_notify.upload_wecom_temp_media', lambda _data, filename: media_uploads.append(filename) or f'media-{len(media_uploads)}') - monkeypatch.setattr('app.services.wecom_notify.send_wecom_file_message', lambda _userid, media_id: file_sends.append(media_id) or {'errcode': 0}) + 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}, + ) monkeypatch.setattr('app.services.file_assets.storage.file_asset_storage.get_bytes', lambda _key: b'receipt-data') return textcards, media_uploads, file_sends -def test_receipt_run_notification_is_one_shot_at_finalize(app, monkeypatch): - """收料 run 终态后经通用排程出口一次性发 textcard+全部收料文件;重复归集不重发。""" +def test_receipt_run_notification_is_one_shot_at_finalize(app, monkeypatch, tmp_path): + """收料 run 终态后经通用排程出口一次性发 textcard+收料 ZIP;重复归集不重发。""" from app import db from app.models import User from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete with app.app_context(): + app.config['FREIGHT_RPA_RECEIPT_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives') recipient = User(username='receipt-one-shot', email='one-shot@example.com', role='user', status='active', wecom_userid='one-shot-user') db.session.add(recipient); db.session.flush() task, run, _report_file = _make_receipt_run_fixture(db, 'SCH-RECEIPT-ONESHOT', 'RUN-RECEIPT-ONESHOT', 'receipt-oneshot-callback') @@ -124,13 +132,15 @@ def test_receipt_run_notification_is_one_shot_at_finalize(app, monkeypatch): outcome = finalize_receipt_schedule_run_if_complete(run.id) - # [断言意图] 一次性出口:单条 textcard + 单文件消息,与库存排程同通道同门禁。 + # [断言意图] 一次性出口:单条 textcard + 单个收料 ZIP,与库存排程同通道同门禁。 assert outcome == {'finalized': True, 'status': 'success'} assert len(textcards) == 1 - assert '收料报表文件 1 份:已随本通知发送' in textcards[0][1] - assert media_uploads == ['receipt.xlsx'] + assert '原始收料包:已随本通知发送' in textcards[0][1] + assert len(media_uploads) == 1 + assert media_uploads[0].startswith('收料RPA-') and media_uploads[0].endswith('-收料.zip') assert file_sends == ['media-1'] assert run.wecom_notified is True + assert run.response_summary_json.get('raw_receipt_zip_available') is True # [断言意图] awaiting 标志清零后再次归集必须短路,绝不二次打扰接收人。 outcome_again = finalize_receipt_schedule_run_if_complete(run.id) diff --git a/backend/tests/test_freight_receipt_rpa_schedule.py b/backend/tests/test_freight_receipt_rpa_schedule.py index 624d9d34..941ca93d 100644 --- a/backend/tests/test_freight_receipt_rpa_schedule.py +++ b/backend/tests/test_freight_receipt_rpa_schedule.py @@ -1,12 +1,12 @@ -"""独立收料 RPA 排程的单元展开和 trigger 契约测试。""" +"""独立收料 RPA 排程的单元口径和 trigger 契约测试。""" from __future__ import annotations from datetime import datetime, timedelta -def test_receipt_schedule_expands_dbs_warehouses_and_crane_once(app, monkeypatch): - """DBS 必须按 Warehouse 展开;Crane 固定为每站点一个单元。""" +def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app, monkeypatch): + """一源一单元:有/无 Warehouse 条件均产出 unit;多值 Warehouse 不拆分。""" from app import db from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingRpaProfile from app.services.schedule.freight_receipt_rpa_job import run_freight_receipt_rpa_schedule @@ -19,24 +19,61 @@ def test_receipt_schedule_expands_dbs_warehouses_and_crane_once(app, monkeypatch parsing_profile=dbs.parsing_profile, excel_template=dbs.excel_template, warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE', report_path_json={}, query_parameters_json=[], enabled=True, ) - db.session.add_all([crane, ShippingReceiptReportConfig(inventory_source_id=dbs.id, report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail'}, query_parameters_json=[{'name': 'Warehouse', 'mode': 'multi_text', 'values': ['A', 'B'], 'required': False, 'select_all': False}]),]) + empty_dbs = ShippingInventorySource( + source_code='DSV360_EMPTY_QP', display_name='Empty QP', connector_type='dbs', rpa_profile=dbs.rpa_profile, + parsing_profile=dbs.parsing_profile, excel_template=dbs.excel_template, + warehouse_resolution_mode='fixed', fixed_warehouse_id='EMPTY', report_path_json={}, query_parameters_json=[], enabled=True, + ) + db.session.add_all([ + crane, empty_dbs, + ShippingReceiptReportConfig( + inventory_source_id=dbs.id, + report_path_json={ + 'program_group': 'Bison', 'program_label': 'AWSBI', + 'report_group': 'Inbound', 'report_name': 'Receipt Detail', + }, + query_parameters_json=[ + {'name': 'Warehouse', 'mode': 'multi_text', 'values': ['A', 'B'], 'required': False, 'select_all': False}, + ], + ), + ]) db.session.flush() - db.session.add(ShippingReceiptReportConfig(inventory_source_id=crane.id, report_path_json={'report_name': 'Inbound Details'}, query_parameters_json=[])) - task = ScheduleTask(schedule_no='SCH-RECEIPT-1', name='Receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *', job_params={'source_codes': [dbs.source_code, crane.source_code]}) + db.session.add_all([ + ShippingReceiptReportConfig( + inventory_source_id=crane.id, report_path_json={'report_name': 'Inbound Details'}, query_parameters_json=[], + ), + ShippingReceiptReportConfig( + inventory_source_id=empty_dbs.id, + report_path_json={ + 'program_group': 'Bison', 'program_label': 'AWSBI', + 'report_group': 'Inbound', 'report_name': 'Receipt Detail', + }, + query_parameters_json=[], + ), + ]) + task = ScheduleTask( + schedule_no='SCH-RECEIPT-1', name='Receipt', schedule_type='platform_job', + platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *', + job_params={'source_codes': [dbs.source_code, crane.source_code, empty_dbs.source_code]}, + ) db.session.add(task); db.session.flush() run = ScheduleRun(run_no='RUN-RECEIPT-1', schedule_task_id=task.id, status='running') db.session.add(run); db.session.commit() captured = {} - monkeypatch.setattr('app.services.schedule.freight_receipt_rpa_job.write_receipt_export_batch_trigger', lambda run_no, units, payload: captured.update(run_no=run_no, units=units, payload=payload) or 'receipt-trigger.json') + monkeypatch.setattr( + 'app.services.schedule.freight_receipt_rpa_job.write_receipt_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) + # 关键断言:三源三单元;多值 Warehouse 不拆;空 query_parameters 仍产出。 assert (total, success, failed, skipped, errors) == (3, 0, 0, 0, []) - assert {(item['source_code'], item['warehouse_id']) for item in details} == {(dbs.source_code, 'A'), (dbs.source_code, 'B'), (crane.source_code, None)} + assert {item['source_code'] for item in details} == {dbs.source_code, crane.source_code, empty_dbs.source_code} + assert all(item['warehouse_id'] is None for item in details) assert captured['payload']['schema_version'] == 'shipping_receipt_rpa.v1' assert len(captured['units']) == 3 dbs_unit = next(item for item in captured['units'] if item['source_code'] == dbs.source_code) - # Worker only receives this frozen execution snapshot, not a later mutable site config. assert dbs_unit['rpa_profile_code'] == 'DBS_DUB_TEST' assert dbs_unit['login_url'] == 'https://test.invalid/dbs' assert dbs_unit['credential_envelope'] == { @@ -44,9 +81,72 @@ def test_receipt_schedule_expands_dbs_warehouses_and_crane_once(app, monkeypatch 'password_ciphertext': None, } assert dbs_unit['report_path_json']['report_name'] == 'Receipt Detail' - assert dbs_unit['warehouse_id'] == 'A' - # 关键断言:单元快照必须剥离 Warehouse 条件,Worker 才能按 warehouse_id 自动追加不重复。 - assert all(item['name'] != 'Warehouse' for item in dbs_unit['query_parameters_json']) + assert dbs_unit['warehouse_id'] is None + # 关键断言:Warehouse 条件原样保留在单元快照,由 Worker 按参数填写或走页面默认。 + assert dbs_unit['query_parameters_json'] == [ + {'name': 'Warehouse', 'mode': 'multi_text', 'values': ['A', 'B'], 'required': False, 'select_all': False}, + ] + empty_unit = next(item for item in captured['units'] if item['source_code'] == empty_dbs.source_code) + assert empty_unit['query_parameters_json'] == [] + + +def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypatch): + """收料 Worker 离线时排程立即 failed,不写 trigger、不落 unit。""" + from app import db + from app.core.errors import ServiceUnavailableError + from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptRpaUnitRun + from app.services.schedule.freight_receipt_rpa_job import run_freight_receipt_rpa_schedule + from app.services.shipping_notice.rpa_worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE + + with app.app_context(): + source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + db.session.add(ShippingReceiptReportConfig( + inventory_source_id=source.id, + report_path_json={ + 'program_group': 'Bison', 'program_label': 'AWSBI', + 'report_group': 'Inbound', 'report_name': 'Receipt Detail', + }, + query_parameters_json=[], + )) + task = ScheduleTask( + schedule_no='SCH-RECEIPT-OFFLINE', name='Receipt offline', schedule_type='platform_job', + platform_api_path='freight-receipt-rpa', 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-RECEIPT-OFFLINE', schedule_task_id=task.id, status='running') + db.session.add(run) + db.session.commit() + + trigger_calls = [] + monkeypatch.setattr( + 'app.services.schedule.freight_receipt_rpa_job.assert_receipt_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'}, + )), + ) + monkeypatch.setattr( + 'app.services.schedule.freight_receipt_rpa_job.write_receipt_export_batch_trigger', + 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) + + # [断言意图] fail-fast:计 failed、不入库 unit、不写 trigger、不进入 awaiting。 + assert (total, success, failed, skipped) == (1, 0, 1, 0) + assert details == [] + assert errors == ['receipt worker offline'] + assert trigger_calls == [] + assert ShippingReceiptRpaUnitRun.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' + for log in logs + ) def test_receipt_schedule_options_only_return_enabled_configured_sources(app): @@ -101,8 +201,7 @@ def test_receipt_trigger_is_published_atomically(app, tmp_path): with app.app_context(): app.config['FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR'] = str(tmp_path) - written = write_receipt_export_batch_trigger('RUN-ATOMIC', [{'callback_id': 'receipt:atomic'}]) - - assert written is not None - assert (tmp_path / 'receipt_export_batch_RUN-ATOMIC.json').is_file() - assert not list(tmp_path.glob('*.tmp')) + path = write_receipt_export_batch_trigger('RUN-ATOMIC', [{'callback_id': 'c1'}], {}) + assert path + assert (tmp_path / 'receipt_export_batch_RUN-ATOMIC.json').exists() + assert not list(tmp_path.glob('.*.tmp')) diff --git a/backend/tests/test_freight_receipt_worker_contract.py b/backend/tests/test_freight_receipt_worker_contract.py index 5569a347..117ce9c0 100644 --- a/backend/tests/test_freight_receipt_worker_contract.py +++ b/backend/tests/test_freight_receipt_worker_contract.py @@ -12,10 +12,55 @@ def test_receipt_worker_isolated_from_inventory_worker_and_uses_receipt_contract assert 'FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR' in text assert 'shipping_receipt_rpa.v1' in text assert '/api/shipping-notice/rpa/receipt-batch-ready' in text + assert '/api/shipping-notice/rpa/receipt-batch-progress' in text + assert '/api/shipping-notice/rpa/receipt-unit-progress' in text assert 'freight_rpa_worker' not in text assert 'FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR' not in text +def test_receipt_dbs_export_does_not_require_warehouse_id(): + """空条件允许走页面默认:Worker 不得因缺少 warehouse_id 直接失败。""" + text = ( + Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_dbs_export.py' + ).read_text(encoding='utf-8') + # 关键断言:历史必填门禁已移除;仅在 warehouse_id 有值时追加(兼容旧 trigger)。 + assert 'DBS receipt unit requires warehouse_id' not in text + assert "if warehouse_id:" in text + + +def test_receipt_dbs_export_maps_report_path_to_navigation(): + """收料路径必须写入 navigation,避免共享导出驱动回退到库存报表名。""" + text = ( + Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_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 + + +def test_receipt_dbs_batch_reuses_inventory_session_prepare(): + """DBS 收料批内必须复用库存 prepare_dsv_batch_export_step,禁止每源 new_page。""" + root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' + worker = (root / 'receipt_rpa_worker.py').read_text(encoding='utf-8') + export = (root / 'receipt_dbs_export.py').read_text(encoding='utf-8') + # 关键断言:与库存同构的批内会话准备;不得再写 first_in_profile / 按 index 新开空白页。 + assert 'prepare_dsv_batch_export_step' in worker + assert 'skip_navigation' in worker and 'skip_navigation' in export + assert 'first_in_profile' not in export + assert "if index:\n page = context.new_page()" not in worker + + +def test_receipt_worker_download_name_uses_source_not_callback(): + """落盘名必须含 source_code,禁止用 callback_id 拼文件名(对齐库存 batch 命名)。""" + root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' + worker = (root / 'receipt_rpa_worker.py').read_text(encoding='utf-8') + # 关键断言:命名函数与 source/run 字段存在;不再用 safe_callback 拼 receipt_ 文件名。 + assert 'def _receipt_download_name(' in worker + assert 'batch_run_no' in worker + assert "f'receipt_{safe_run}_{safe_source}_{safe_wh}_{stamp}{suffix}'" in worker + assert 'safe_callback' not in worker + assert "receipt_{safe_callback}" not in worker + + def test_receipt_crane_driver_forces_inbound_details_match_name(): """收料 Crane 必须将固定报表名传给轮询匹配,不能落回库存文件名默认值。""" root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' @@ -25,6 +70,77 @@ def test_receipt_crane_driver_forces_inbound_details_match_name(): assert "source_value = str((source or {}).get('scheduled_report_name') or '').strip()" in crane_driver +def test_receipt_crane_export_passes_download_dir_for_fallback(): + """Crane 收料 source 必须带 __download_dir,否则共享 driver 目录兜底不会启用。""" + text = ( + Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_crane_export.py' + ).read_text(encoding='utf-8') + assert "'__download_dir': str(unit.get('__download_dir') or '')" in text + + +def test_receipt_worker_save_download_uses_directory_fallback(): + """收料落盘必须在 TargetClosed 时走 download_artifact_fallback(对齐库存)。""" + text = ( + Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py' + ).read_text(encoding='utf-8') + assert 'download_artifact_fallback' in text + assert 'def _persist_download_to_dest(' in text + assert '_download_dir_baseline_names' in text + assert 'baseline_names=baseline_names' in text + + +def test_receipt_worker_validates_excel_and_reports_empty(): + """收料落盘后必须结构校验;无明细走 NoReceiptDataError → empty/no_receipt_data。""" + text = ( + Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py' + ).read_text(encoding='utf-8') + empty_mod = ( + Path(__file__).resolve().parents[2] + / 'scripts' + / 'freight_rpa' + / 'receipt' + / 'receipt_excel_empty.py' + ).read_text(encoding='utf-8') + assert 'def _validate_receipt_excel(' in text + assert 'from receipt_excel_empty import' in text + assert 'class NoReceiptDataError' in empty_mod + assert 'no_receipt_data' in empty_mod + assert 'is_receipt_excel_header_row' in empty_mod + assert "'error_code': 'no_receipt_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 + + +def test_receipt_ready_callback_outside_export_retry_like_inventory_progress(): + """ + 对齐库存:导出重试不得包裹 ready;成功后先轻量 progress 再 ready。 + + [断言意图] 同源双文件根因是 ready 超时落入导出重试;契约上必须把 + _post_unit_ready / batch-progress 放在导出循环外,并禁止 ready 失败再导。 + """ + text = ( + Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py' + ).read_text(encoding='utf-8') + assert 'def _post_unit_ready(' in text + assert '重试只覆盖导出/落盘/校验' in text or 'ready 回调禁止进入本循环' in text + assert 'ready callback failed' in text + assert '_emit_batch_progress(body, progress_counts)' in text + # success 路径:先 progress 再 ready(progress 出现在 _post_unit_ready 调用之前) + 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 + + +def test_receipt_heartbeat_capability_is_receipt_export(): + """收料 Worker 心跳能力必须声明 receipt_export,不得再写 inventory_export。""" + text = ( + Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'common' / 'rpa_heartbeat.py' + ).read_text(encoding='utf-8') + assert 'receipt_export' in text + assert 'is_receipt' in text + + def test_receipt_crane_driver_forces_inbound_details_entry_route(): """复用 Profile 的门户首页时,收料不能误走库存 On Hand Details 路由。""" root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' @@ -85,15 +201,15 @@ def test_receipt_register_script_mirrors_inventory_with_distinct_identity(): assert 'AtLogOn' in receipt and 'Interactive' in receipt and 'Headless' in receipt and 'WindowStyle Hidden' in receipt -def test_receipt_worker_supports_opt_in_session_reuse(): - """收料 Worker 支持可选跨批次会话复用:ps1 注入开关,worker 按 env 切换持久/一次性 Profile。""" +def test_receipt_worker_defaults_session_reuse_with_scoped_profiles(): + """收料默认会话复用,且持久目录按 connector+profile 隔离(对齐库存)。""" text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8') - # [断言意图] 开关经 env 读取(默认 false 保持一次性 Profile 行为不变) - assert "env('FREIGHT_RPA_WORKER_SESSION_REUSE', 'false')" in text - # [断言意图] 复用模式使用持久 receipt_session 目录,且该目录不做批次后删除(跨批次复用登录态) - assert "profile_root / 'receipt_session'" in text - assert 'not reuse_session' in text + # [断言意图] 默认开启复用;持久目录形如 connector__profile_session,禁止单一 receipt_session + assert 'def _session_reuse_enabled()' in text + assert "f'{connector}__{code}_session'" in text or 'f"{connector}__{code}_session"' in text + assert "profile_root / 'receipt_session'" not in text + assert 'receipt-batch-progress' in text + assert 'receipt-unit-progress' in text ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'start_receipt_worker.ps1').read_text(encoding='utf-8') - # [断言意图] 启动脚本提供 -SessionReuse 开关并注入对应 env - assert '[switch]$SessionReuse' in ps1 - assert 'FREIGHT_RPA_WORKER_SESSION_REUSE' in ps1 + assert '[switch]$NoSessionReuse' in ps1 + assert "FREIGHT_RPA_WORKER_SESSION_REUSE = $sessionReuse" in ps1 diff --git a/backend/tests/test_freight_rpa_heartbeat.py b/backend/tests/test_freight_rpa_heartbeat.py index 6a9bc4de..c09b988f 100644 --- a/backend/tests/test_freight_rpa_heartbeat.py +++ b/backend/tests/test_freight_rpa_heartbeat.py @@ -24,6 +24,7 @@ def _load_freight_rpa_heartbeat_module(): def test_build_heartbeat_payload_includes_shared_scope_id(monkeypatch): module = _load_freight_rpa_heartbeat_module() + monkeypatch.delenv("FREIGHT_RPA_WORKER_ID", raising=False) monkeypatch.setenv("FREIGHT_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data") payload = module.build_heartbeat_payload( trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers", @@ -31,6 +32,19 @@ def test_build_heartbeat_payload_includes_shared_scope_id(monkeypatch): ) assert payload["shared_scope_id"] == "hxops-rpa-test-data" assert payload["trigger_dir"] == r"C:\HxopsRpaTest\data\inventory_triggers" + assert payload["capabilities"] == ["inventory_export"] + + +def test_build_heartbeat_payload_receipt_worker_declares_receipt_export(monkeypatch): + """收料 Worker(*-receipt 或 receipt trigger 路径)须声明 receipt_export。""" + module = _load_freight_rpa_heartbeat_module() + monkeypatch.setenv("FREIGHT_RPA_WORKER_ID", "WIN-RPA-01-receipt") + payload = module.build_heartbeat_payload( + trigger_dir=r"C:\HxopsRpaTest\data\freight_rpa\receipt\triggers", + drop_dir=r"C:\HxopsRpaTest\data\freight_rpa\receipt\drop", + ) + assert payload["capabilities"] == ["receipt_export"] + assert payload["worker_id"].endswith("-receipt") def test_resolve_shared_scope_id_from_trigger_path(monkeypatch): diff --git a/backend/tests/test_freight_rpa_worker.py b/backend/tests/test_freight_rpa_worker.py index 8d3bb74d..0430d743 100644 --- a/backend/tests/test_freight_rpa_worker.py +++ b/backend/tests/test_freight_rpa_worker.py @@ -2614,6 +2614,28 @@ def test_get_dsv_report_result_state_keeps_waiting_when_loading_overlay_and_head assert state["bodyScore"] == 4 +def test_dsv_async_wait_uses_visible_reportviewer_overlay_not_body_loading_text(): + """ + View Report 后的 asyncWait 必须认可见 #ReportViewerMain_AsyncWait,禁止 body 扫 loading。 + + [断言意图] 日历 iframe 隐藏 Loading 文案会假阳性拖满超时;契约锁死为遮罩可见性。 + """ + text = ( + Path(__file__).resolve().parents[2] + / "scripts" + / "freight_rpa" + / "connectors" + / "dsv" + / "dsv_report_export.py" + ).read_text(encoding="utf-8") + assert "#ReportViewerMain_AsyncWait" in text + assert "WaitControlBackground" in text + assert "visible(asyncWaitNode)" in text + # 旧逻辑:正文 token 列表判定 asyncWait(会误伤隐藏 Loading) + assert "'please wait',\n 'generating'," not in text + assert "normalizedBody.includes(token));\n const asyncWait" not in text + + @pytest.mark.rpa_e2e def test_inventory_export_trigger_2edadc77_downloads_real_file(monkeypatch, tmp_path): """ diff --git a/backend/tests/test_freight_rpa_worker_inventory_params.py b/backend/tests/test_freight_rpa_worker_inventory_params.py index 7bfff083..b5a42f31 100644 --- a/backend/tests/test_freight_rpa_worker_inventory_params.py +++ b/backend/tests/test_freight_rpa_worker_inventory_params.py @@ -51,7 +51,7 @@ def test_fill_report_parameter_multi_select(monkeypatch): page = MagicMock() calls: list[tuple[str, str, list[str]]] = [] - def _fake_multi(page_arg, selector_env, label, values, *, selectors=None, select_all=False, report_name=None): + def _fake_multi(page_arg, selector_env, label, values, *, selectors=None, select_all=False, report_name=None, program_label=None): calls.append((selector_env, label, list(values))) monkeypatch.setattr(worker, "_fill_dsv_multi_select", _fake_multi) @@ -73,7 +73,7 @@ def test_fill_report_parameter_multi_select_with_select_all(monkeypatch): page = MagicMock() calls: list[dict[str, object]] = [] - def _fake_multi(page_arg, selector_env, label, values, *, selectors=None, select_all=False, report_name=None): + def _fake_multi(page_arg, selector_env, label, values, *, selectors=None, select_all=False, report_name=None, program_label=None): calls.append( { "selector_env": selector_env, @@ -111,7 +111,7 @@ def test_fill_report_parameter_multi_select_jda_report_passes_template_selectors page = MagicMock() calls: list[dict[str, object]] = [] - def _fake_multi(page_arg, selector_env, label, values, *, selectors=None, select_all=False, report_name=None): + def _fake_multi(page_arg, selector_env, label, values, *, selectors=None, select_all=False, report_name=None, program_label=None): calls.append( { "selector_env": selector_env, @@ -183,7 +183,7 @@ def test_ensure_dsv_inventory_rows_retries_view_report_then_allows_export_fallba "_click_dsv_view_report", lambda page_arg: clicks.append("view"), ) - monkeypatch.setattr(worker, "_wait_dsv_report_ready", lambda page_arg, timeout_ms: None) + monkeypatch.setattr(worker, "_wait_dsv_report_ready", lambda page_arg, timeout_ms, kind="inventory": None) worker._ensure_dsv_inventory_rows_or_export_fallback(page=object(), report_name="On Hand Inventory by Location") @@ -204,6 +204,113 @@ def test_ensure_dsv_inventory_rows_skips_retry_when_rows_already_visible(monkeyp assert clicks == [] +def test_dsv_export_kind_receipt_from_flag_and_report_name(): + """收料 source 须显式或按报表名识别为 receipt,不得默认库存。""" + worker = _load_dsv_report_export() + assert worker._dsv_export_kind({"__export_kind__": "receipt"}) == "receipt" + assert worker._dsv_export_kind({"navigation": {"report_name": "Receipt Detail"}}) == "receipt" + assert worker._dsv_export_kind({"navigation": {"report_name": "On Hand Inventory by Location"}}) == "inventory" + assert "on hand inventory by location" not in worker._dsv_body_markers_for_kind("receipt") + assert "qty expected" in worker._dsv_body_markers_for_kind("receipt") + assert "qty available" not in " ".join(worker._dsv_body_markers_for_kind("receipt")) + + +def test_wait_receipt_result_ready_accepts_export_toolbar(monkeypatch): + """收料就绪:无库存正文时,Export 工具栏 + 非 loading 即应放行。""" + worker = _load_dsv_report_export() + state = { + "asyncWait": False, + "processingError": False, + "exportReady": True, + "excelReady": False, + "bodyReady": False, + "bodyScore": 0, + "directExportReady": False, + } + + class _FakePage: + frames: list = [] + + monkeypatch.setattr( + worker, + "_find_dsv_report_result_frame", + lambda page_arg, kind="inventory": (0, object(), state), + ) + monkeypatch.setattr(worker, "_debug_dsv_stage", lambda *args, **kwargs: None) + monkeypatch.setattr(worker, "_emit_debug_event", lambda *args, **kwargs: None) + worker._wait_for_dsv_report_result_ready(_FakePage(), 2_000, kind="receipt") + + +def test_ensure_dsv_receipt_rows_retries_then_export_fallback(monkeypatch): + """收料 DOM 无行时重试 View Report;仍无行不得抛空,继续导出。""" + worker = _load_dsv_report_export() + clicks: list[str] = [] + waits: list[int] = [] + row_outcomes = iter([False, False]) + + monkeypatch.setattr(worker, "_browser_timeout_ms", lambda: 5_000) + monkeypatch.setattr( + worker, + "_wait_dsv_report_receipt_rows", + lambda page_arg, timeout_ms: (waits.append(timeout_ms) or next(row_outcomes, False)), + ) + monkeypatch.setattr(worker, "_click_dsv_view_report", lambda page_arg: clicks.append("view")) + monkeypatch.setattr(worker, "_wait_dsv_report_ready", lambda page_arg, timeout_ms, kind="inventory": None) + + worker._ensure_dsv_receipt_rows_or_export_fallback(page=object(), report_name="Receipt Detail") + + assert clicks == ["view"] + assert waits == [5_000, 5_000] + + +def test_run_dsv_export_uses_receipt_row_probe(monkeypatch): + """__export_kind__=receipt 时须走收料行探针,不得调用库存行 ensure。""" + worker = _load_dsv_report_export() + calls: list[str] = [] + monkeypatch.setattr(worker, "_fill_report_parameters", lambda page_arg, source: None) + monkeypatch.setattr(worker, "_click_dsv_view_report", lambda page_arg: None) + monkeypatch.setattr(worker, "_wait_dsv_report_ready", lambda page_arg, timeout_ms, kind="inventory": calls.append(f"wait:{kind}")) + monkeypatch.setattr( + worker, + "_ensure_dsv_receipt_rows_or_export_fallback", + lambda page_arg, report_name: calls.append("receipt-rows"), + ) + monkeypatch.setattr( + worker, + "_ensure_dsv_inventory_rows_or_export_fallback", + lambda page_arg, report_name: calls.append("inventory-rows"), + ) + monkeypatch.setattr(worker, "_dsv_download_wait_ms", lambda: 1_000) + monkeypatch.setattr(worker, "_report_dsv_chain_stage", lambda *args, **kwargs: None) + + class _DownloadCtx: + def __enter__(self): + return self + + def __exit__(self, *args): + return False + + @property + def value(self): + return "download" + + class _Page: + def expect_download(self, timeout=None): + return _DownloadCtx() + + monkeypatch.setattr(worker, "_click_dsv_export_excel", lambda page_arg, kind="inventory": calls.append(f"export:{kind}")) + + result = worker._run_dsv_inventory_export_from_form( + _Page(), + {"__export_kind__": "receipt", "navigation": {"report_name": "Receipt Detail"}}, + ) + assert result == "download" + assert "wait:receipt" in calls + assert "receipt-rows" in calls + assert "inventory-rows" not in calls + assert "export:receipt" in calls + + def test_download_dsv360_inventory_delegates_to_shared_export(monkeypatch): """单票 DSV 导出应走与批量相同的 session + export 函数。""" worker = _load_worker() @@ -227,7 +334,7 @@ def test_dsv_report_has_inventory_data_rows_false_when_table_has_only_three_rows worker = _load_dsv_report_export() frame = MagicMock() frame.evaluate.return_value = False - monkeypatch.setattr(worker, "_find_dsv_report_result_frame", lambda page: (0, frame, {})) + monkeypatch.setattr(worker, "_find_dsv_report_result_frame", lambda page, kind="inventory": (0, frame, {})) assert worker._dsv_report_has_inventory_data_rows(MagicMock()) is False frame.evaluate.assert_called_once() @@ -243,7 +350,7 @@ def test_dsv_report_has_inventory_data_rows_true_when_table_has_detail_rows(monk worker = _load_dsv_report_export() frame = MagicMock() frame.evaluate.return_value = True - monkeypatch.setattr(worker, "_find_dsv_report_result_frame", lambda page: (0, frame, {})) + monkeypatch.setattr(worker, "_find_dsv_report_result_frame", lambda page, kind="inventory": (0, frame, {})) assert worker._dsv_report_has_inventory_data_rows(MagicMock()) is True frame.evaluate.assert_called_once() diff --git a/backend/tests/test_inventory_configuration_test.py b/backend/tests/test_inventory_configuration_test.py index 64c44738..a5e894a1 100644 --- a/backend/tests/test_inventory_configuration_test.py +++ b/backend/tests/test_inventory_configuration_test.py @@ -198,15 +198,10 @@ def test_empty_configuration_export_is_successful_but_marks_data_validation_pend assert result['result']['data_validation'] == 'pending_first_non_empty_export' assert not ShippingInventoryFile.query.count() current = next(item for item in shipping_inventory_service.list_sources() if item['id'] == source['id']) - checks = {item['code']: item for item in current['activation']['checks']} - # 关键断言:连接测试已通过;数量与匹配字段仅待首次非空文件验证,不能伪装成失败。 - assert checks['configuration_test']['status'] == 'empty' - assert checks['configuration_test']['blocking'] is False - assert checks['parsing_validation']['status'] == 'pending' - assert checks['parsing_validation']['blocking'] is False - assert checks['warehouse_mapping']['blocking'] is False - # 关键断言:无库存不会被行级解析或调拨映射阻断;本例仍缺发货模板,因此尚不可启用。 + # 关键断言:空结果测试不自动启用;本例仍缺发货模板,硬门槛阻断启用。 + assert current['enabled'] is False assert current['activation']['missing_requirements'] == ['excel_template'] + assert 'configuration_test' not in {item['code'] for item in current['activation']['checks']} def test_empty_configuration_export_without_published_profile_is_rejected(app): @@ -246,8 +241,8 @@ def test_configuration_test_automatically_verifies_compatible_bound_profile(app, assert verified['result']['confirmed_profile_id'] == profile['id'] -def test_verified_current_profile_automatically_enables_ready_source(app, tmp_path): - """当前解析验证通过且必要条件齐全时,站点无需人工确认即可自动启用。""" +def test_verified_current_profile_does_not_auto_enable_ready_source(app, tmp_path): + """当前解析验证通过且硬门槛齐全时,测试回调仍不得自动启用;启停只走显式开关。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(), patch( 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', @@ -263,9 +258,10 @@ def test_verified_current_profile_automatically_enables_ready_source(app, tmp_pa verified = _complete_test_run(source, tmp_path) source_model = db.session.get(ShippingInventorySource, source['id']) - # 关键断言:测试证据与完整门禁在同一事务提交,避免页面看到已验证但仍需手动启用。 + # 关键断言:测试只写入验证事实,站点保持停用直至管理员显式启用。 assert verified['stage'] == 'current_profile_verified' - assert source_model.enabled is True + assert source_model.enabled is False + assert shipping_inventory_service.get_source_activation_status(source_model)['ready'] is True def test_verified_current_profile_keeps_source_disabled_without_template(app, tmp_path): @@ -289,8 +285,8 @@ def test_verified_current_profile_keeps_source_disabled_without_template(app, tm assert shipping_inventory_service.get_source_activation_status(source_model)['missing_requirements'] == ['excel_template'] -def test_empty_export_automatically_enables_ready_fixed_source(app, tmp_path): - """固定仓查询成功但无库存时,也能在完整门禁下自动启用站点。""" +def test_empty_export_does_not_auto_enable_ready_fixed_source(app, tmp_path): + """固定仓查询成功但无库存时,只写入验证事实,不得自动启用站点。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(), patch( 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', @@ -307,9 +303,10 @@ def test_empty_export_automatically_enables_ready_fixed_source(app, tmp_path): started = inventory_configuration_test.start_test_export(source['id'], actor_id=None) completed = inventory_configuration_test.report_test_export({'run_no': started['run_no'], 'status': 'empty'}) source_model = db.session.get(ShippingInventorySource, source['id']) - # 关键断言:无库存是成功查询事实,完整门禁下不再要求人工启用。 + # 关键断言:空库存是成功查询事实;硬门槛齐备时仍保持停用,等待显式开关。 assert completed['status'] == 'completed_empty' - assert source_model.enabled is True + assert source_model.enabled is False + assert shipping_inventory_service.get_source_activation_status(source_model)['ready'] is True def test_batch_configuration_test_groups_profiles_and_isolates_site_results(app, tmp_path): @@ -572,14 +569,13 @@ def test_confirming_test_profile_binds_only_compatible_published_profile(app, tm db.session.commit() assert shipping_inventory_service.get_source_activation_status(source_model)['ready'] is True assert shipping_inventory_service.activate_source(source['id'], actor_id=None)['enabled'] is True - assert next( - item for item in shipping_inventory_service.get_source_activation_status(source_model)['checks'] - if item['code'] == 'configuration_test' - )['status'] == 'passed' + assert 'configuration_test' not in { + item['code'] for item in shipping_inventory_service.get_source_activation_status(source_model)['checks'] + } -def test_rpa_profile_change_stales_completed_configuration_test(app, tmp_path): - """连接凭据或登录配置变更后,旧测试不得继续作为当前库存站点的启用证据。""" +def test_rpa_profile_change_does_not_block_activation_hard_gates(app, tmp_path): + """连接变更后测试证据可能过期,但启用硬门槛不再依赖测试导出。""" app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(), patch( @@ -589,6 +585,10 @@ def test_rpa_profile_change_stales_completed_configuration_test(app, tmp_path): completed = _complete_test_run(source, tmp_path) profile = _publish_profile_from_analysis(completed['analysis_id'], _published_order_field(), code='PROFILE_STALE') inventory_configuration_test.confirm_test_profile(source['id'], completed['run_no'], profile['id'], actor_id=None) + template = _published_template(code='PROFILE_STALE_TEMPLATE') + source_model = db.session.get(ShippingInventorySource, source['id']) + source_model.excel_template_id = template.id + db.session.commit() rpa_profile = db.session.get(ShippingRpaProfile, source['rpa_profile_id']) shipping_inventory_service.save_profile({ @@ -599,13 +599,11 @@ def test_rpa_profile_change_stales_completed_configuration_test(app, tmp_path): }, actor_id=None, profile_id=rpa_profile.id) source_model = db.session.get(ShippingInventorySource, source['id']) - test_check = next( - item for item in shipping_inventory_service.get_source_activation_status(source_model)['checks'] - if item['code'] == 'configuration_test' - ) - # 关键断言:连接配置版本变更使已完成测试失效,不能继续放行正式运行。 - assert test_check['status'] == 'stale' - assert test_check['blocking'] is True + status = shipping_inventory_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_inventory_service.activate_source(source['id'], actor_id=None)['enabled'] is True def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, tmp_path): @@ -625,15 +623,6 @@ def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, t inventory_configuration_test.confirm_test_profile(source['id'], completed['run_no'], profile['id'], actor_id=None) assert stale.value.code == 'SHIPPING.INVENTORY_CONFIGURATION_TEST_STALE' - # 关键断言:旧配置版本的测试只能作为过期证据展示,不能被误判为当前测试通过。 - stale_status = shipping_inventory_service.get_source_activation_status( - db.session.get(ShippingInventorySource, source['id']), - ) - test_check = next(item for item in stale_status['checks'] if item['code'] == 'configuration_test') - assert test_check['status'] == 'stale' - assert test_check['blocking'] is True - assert test_check['evidence']['run_no'] == completed['run_no'] - source_model = db.session.get(ShippingInventorySource, source['id']) source_model.parsing_profile_id = profile['id'] template = ShippingExcelTemplate( diff --git a/backend/tests/test_receipt_excel_empty.py b/backend/tests/test_receipt_excel_empty.py new file mode 100644 index 00000000..15ddfa88 --- /dev/null +++ b/backend/tests/test_receipt_excel_empty.py @@ -0,0 +1,106 @@ +""" +backend/tests/test_receipt_excel_empty.py + +用途:收料 Excel「有表头无明细」判空回归;钉死标题行不得当表头。 +依赖:openpyxl、scripts/freight_rpa/receipt/receipt_excel_empty。 +逻辑:构造 DSV 标题+表头无数据簿;复制生产 drop 样例断言 empty。 +""" + +from __future__ import annotations + +import shutil +import sys +from pathlib import Path + +import pytest +from openpyxl import Workbook + +_REPO_ROOT = Path(__file__).resolve().parents[2] +_RECEIPT_DIR = _REPO_ROOT / 'scripts' / 'freight_rpa' / 'receipt' +if str(_RECEIPT_DIR) not in sys.path: + sys.path.insert(0, str(_RECEIPT_DIR)) + +from receipt_excel_empty import ( # noqa: E402 + NoReceiptDataError, + enforce_receipt_excel_not_empty, + receipt_excel_has_detail_rows, +) + +_DROP_SAMPLE = ( + _REPO_ROOT + / 'backend' + / 'data' + / 'freight_rpa' + / 'receipt' + / 'drop' + / 'receipt_RUN202609290016193A2E_DSV360_AWSBI_BYAWSPRD01_NA_20260929002248.xlsx' +) + + +def _write_dsv_title_header_only(path: Path) -> None: + """写入与生产一致的标题行 + 表头行、无明细。""" + workbook = Workbook() + sheet = workbook.active + assert sheet is not None + sheet.title = 'LognetAWSReceiptDetail3lv' + sheet.append(['AWS Receipt Detail', '1 | + | | | + | + | CBIS-0000000100 | | | ']) + sheet.append([ + 'Supplier', + 'External\nASN #', + 'WMS\nReceipt #', + 'Mode of\nTransport', + 'Carrier\nCode', + 'Waybill #', + 'Type', + 'ASN Status', + 'Date\nExpected', + 'Date\nReceived', + 'External\nLine #', + 'Supplier ID', + 'Carton ID', + 'Pallet ID', + 'AWS Sku', + ]) + workbook.save(path) + + +def test_title_row_must_not_count_as_detail(tmp_path: Path): + """ + 标题含 receipt 时旧逻辑会把真表头当成明细 → 误 success。 + + [断言意图] 仅标题+表头必须判定为无明细(False),enforce 抛 no_receipt_data。 + """ + path = tmp_path / 'header_only.xlsx' + _write_dsv_title_header_only(path) + assert receipt_excel_has_detail_rows(path) is False + with pytest.raises(NoReceiptDataError, match='no_receipt_data'): + enforce_receipt_excel_not_empty(path) + + +def test_header_plus_data_row_is_not_empty(tmp_path: Path): + """有表头且下一行有业务单元格时不得 empty。""" + path = tmp_path / 'with_data.xlsx' + _write_dsv_title_header_only(path) + from openpyxl import load_workbook + + workbook = load_workbook(path) + sheet = workbook.active + assert sheet is not None + sheet.append(['Well Trust', 'HOX1', '0001', 'O', 'KN', 'WB1', 'Inbound', 'Closed', '01/01/2026', '', '0010', 'CBIS', '', '', 'SKU-1']) + workbook.save(path) + assert receipt_excel_has_detail_rows(path) is True + enforce_receipt_excel_not_empty(path) + + +@pytest.mark.skipif(not _DROP_SAMPLE.is_file(), reason='production drop sample not present') +def test_production_header_only_sample_is_empty(tmp_path: Path): + """ + 生产样例 receipt_RUN202609290016193A2E_*_BYAWSPRD01_* 仅表头却曾 success。 + + [断言意图] 复制该文件后必须判 empty / no_receipt_data。 + """ + target = tmp_path / _DROP_SAMPLE.name + shutil.copy2(_DROP_SAMPLE, target) + assert receipt_excel_has_detail_rows(target) is False + with pytest.raises(NoReceiptDataError, match='no_receipt_data'): + enforce_receipt_excel_not_empty(target) diff --git a/backend/tests/test_rpa_worker_heartbeat.py b/backend/tests/test_rpa_worker_heartbeat.py index 50515b58..61b55232 100644 --- a/backend/tests/test_rpa_worker_heartbeat.py +++ b/backend/tests/test_rpa_worker_heartbeat.py @@ -17,6 +17,7 @@ from app.core.errors import ServiceUnavailableError from app.services.shipping_notice.rpa_worker_heartbeat import ( FREIGHT_UPLOAD_CAPABILITY, INVENTORY_EXPORT_CAPABILITY, + RECEIPT_EXPORT_CAPABILITY, RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE, RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE, RPA_WORKER_OFFLINE_MESSAGE, @@ -201,6 +202,36 @@ 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): + """收料 fail-fast 应附带 reasons,且不要求共享哨兵。""" + from app.core.errors import ServiceUnavailableError + from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module + from app.services.shipping_notice.rpa_worker_heartbeat import ( + RPA_WORKER_OFFLINE_MESSAGE, + assert_receipt_rpa_worker_ready, + reset_rpa_worker_heartbeat_state_for_tests, + ) + + monkeypatch.setattr(heartbeat_module, '_redis_client', lambda: None) + reset_rpa_worker_heartbeat_state_for_tests() + trigger_dir = tmp_path / 'receipt_triggers' + trigger_dir.mkdir() + app.config['ENV_NAME'] = 'test' + app.config['FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR'] = str(trigger_dir) + app.config['FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED'] = True + app.config['FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK'] = True + app.config['FREIGHT_RPA_WORKER_MOCK'] = 'false' + + with app.app_context(): + with pytest.raises(ServiceUnavailableError) as exc_info: + assert_receipt_rpa_worker_ready() + # [断言意图] 与库存同构的用户可见文案与 reasons;收料不因缺哨兵失败。 + assert exc_info.value.message == RPA_WORKER_OFFLINE_MESSAGE + reasons = (exc_info.value.details or {}).get('reasons', []) + assert 'no_worker_heartbeat' in reasons + assert 'shared_sentinel_missing' not in reasons + + def test_check_inventory_rpa_worker_ready_rejects_stale_heartbeat(app, tmp_path, monkeypatch): """超过 TTL 的心跳应视为离线。""" import time as time_module @@ -465,3 +496,88 @@ def test_assert_freight_upload_rpa_ready_includes_reasons(app, tmp_path): assert exc_info.value.message == RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE reasons = (exc_info.value.details or {}).get("reasons", []) assert "credential_key_missing" in reasons + + +def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path): + """收料 ready 与库存同口径:要求共享哨兵;仅有库存 Worker 不能冒充收料在线。""" + from app.services.shipping_notice.rpa_worker_heartbeat import ( + check_receipt_rpa_worker_ready, + reset_rpa_worker_heartbeat_state_for_tests, + serialize_rpa_worker_status, + ) + + receipt_trigger = tmp_path / "receipt" / "triggers" + receipt_trigger.mkdir(parents=True) + inventory_trigger = tmp_path / "inventory" / "triggers" + inventory_trigger.mkdir(parents=True) + _write_shared_sentinel(inventory_trigger, scope_id="hxops-rpa-test-data") + app.config["ENV_NAME"] = "test" + app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(inventory_trigger) + app.config["FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR"] = str(receipt_trigger) + app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data" + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True + app.config["FREIGHT_RPA_WORKER_MOCK"] = "false" + reset_rpa_worker_heartbeat_state_for_tests() + + with app.app_context(): + record_rpa_worker_heartbeat(_heartbeat_payload( + worker_id="HOST-inventory", + trigger_dir=str(inventory_trigger), + shared_scope_id="hxops-rpa-test-data", + )) + receipt_offline = check_receipt_rpa_worker_ready() + assert receipt_offline.ready is False + assert receipt_offline.workers == [] + + # 无哨兵时即便有收料心跳也不得 ready。 + record_rpa_worker_heartbeat(_heartbeat_payload( + worker_id="HOST-receipt", + trigger_dir=str(receipt_trigger), + shared_scope_id="hxops-rpa-test-data", + capabilities=[RECEIPT_EXPORT_CAPABILITY], + )) + without_sentinel = check_receipt_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() + assert receipt_ready.ready is True + assert [w["worker_id"] for w in receipt_ready.workers] == ["HOST-receipt"] + + payload = serialize_rpa_worker_status(scope="receipt") + assert payload["scope"] == "receipt" + assert payload["ready"] is True + assert payload["trigger_dir"] == str(receipt_trigger) + assert [w["worker_id"] for w in payload["workers"]] == ["HOST-receipt"] + + +def test_receipt_worker_recognized_by_trigger_dir_without_receipt_suffix(app, tmp_path): + """未注入 *-receipt 身份时,仍可用收料 trigger_dir 识别在线收料 Worker。""" + from app.services.shipping_notice.rpa_worker_heartbeat import ( + check_receipt_rpa_worker_ready, + reset_rpa_worker_heartbeat_state_for_tests, + ) + + receipt_trigger = tmp_path / "receipt" / "triggers" + receipt_trigger.mkdir(parents=True) + app.config["ENV_NAME"] = "dev" + app.config["FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR"] = str(receipt_trigger) + app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "" + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True + app.config["FREIGHT_RPA_WORKER_MOCK"] = "false" + reset_rpa_worker_heartbeat_state_for_tests() + + with app.app_context(): + record_rpa_worker_heartbeat(_heartbeat_payload( + worker_id="Hugo-30820", + trigger_dir=str(receipt_trigger), + shared_scope_id="", + capabilities=[RECEIPT_EXPORT_CAPABILITY], + )) + result = check_receipt_rpa_worker_ready() + assert result.ready is True + assert [w["worker_id"] for w in result.workers] == ["Hugo-30820"] diff --git a/backend/tests/test_shipping_receipt_rpa_archive.py b/backend/tests/test_shipping_receipt_rpa_archive.py new file mode 100644 index 00000000..2ac9cb52 --- /dev/null +++ b/backend/tests/test_shipping_receipt_rpa_archive.py @@ -0,0 +1,296 @@ +""" +backend/tests/test_shipping_receipt_rpa_archive.py + +用途:收料 RPA 原始收料 ZIP 归档、summary 可见性与 admin API 路由单测。 +依赖:shipping_receipt_rpa_archive、api/schedule/runs、freight_receipt_rpa_finalize。 +逻辑:finalize 预生成 ZIP;下载 send_file 归档路径;包内条目为序号_source_code。 +""" + +from __future__ import annotations + +import json +import zipfile +from pathlib import Path +from urllib.parse import quote + +import pytest + +from app import db +from app.core.auth.jwt import issue_local_access_token +from app.core.errors import NotFoundError +from app.models import ( + ScheduleRun, + ScheduleTask, + ShippingInventorySource, + ShippingReceiptReportFile, + ShippingReceiptRpaUnitRun, + User, +) +from app.services.schedule.shipping_receipt_rpa_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, + _build_zip_entry_name, +) +from tests.conftest import parse_api_error + + +@pytest.fixture +def admin_jwt_headers(app): + """创建 admin 用户并签发 Bearer JWT。""" + 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 _make_receipt_run_with_file( + *, + schedule_no: str, + run_no: str, + callback_id: str, + source_code: str = 'DSV360_AWSDU', + original_filename: str = 'receipt.xlsx', +) -> tuple[ScheduleRun, ShippingReceiptReportFile]: + """构造收料排程 run + 成功单元 + 归档文件。""" + source = ShippingInventorySource.query.filter_by(source_code=source_code).one() + owner = db.session.query(User).filter_by(username='admin').first() + if owner is None: + owner = User(username=f'owner-{schedule_no}', email=f'{schedule_no}@example.com', role='admin', status='active') + owner.set_password('admin') + db.session.add(owner) + db.session.flush() + task = ScheduleTask( + schedule_no=schedule_no, + name=f'Receipt archive {schedule_no}', + schedule_type='platform_job', + platform_api_path='freight-receipt-rpa', + owner_user_id=owner.id, + cron_expr='0 8 * * *', + schedule_timezone='Asia/Shanghai', + ) + db.session.add(task) + db.session.flush() + run = ScheduleRun( + run_no=run_no, + schedule_task_id=task.id, + trigger_type='manual', + status='success', + total_count=1, + success_count=1, + failed_count=0, + skipped_count=0, + ) + db.session.add(run) + db.session.flush() + unit = ShippingReceiptRpaUnitRun( + schedule_run_id=run.id, + inventory_source_id=source.id, + source_code=source.source_code, + connector_type='dbs', + warehouse_id=None, + callback_id=callback_id, + status='success', + config_snapshot_json={}, + ) + db.session.add(unit) + db.session.flush() + report_file = ShippingReceiptReportFile( + unit_run_id=unit.id, + storage_provider='minio', + storage_bucket='test', + storage_key=f'{callback_id}.xlsx', + original_filename=original_filename, + file_size=12, + sha256='d' * 64, + ) + db.session.add(report_file) + db.session.commit() + 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_get_receipt_archive_dir_falls_back_when_config_none(app, tmp_path, monkeypatch): + """ + Config 缺项时 Flask config 可能为 None;不得 Path(None) 导致 finalize ZIP 全空。 + + 断言:显式 None 时回落到 Config 默认路径并可创建目录。 + """ + from app.core.config.settings import Config + + monkeypatch.setattr( + Config, + 'FREIGHT_RPA_RECEIPT_ARCHIVE_DIR', + str(tmp_path / 'receipt_archives_fallback'), + ) + with app.app_context(): + app.config['FREIGHT_RPA_RECEIPT_ARCHIVE_DIR'] = None + archive_dir = Path(get_receipt_archive_dir()) + assert archive_dir.is_dir() + assert archive_dir == (tmp_path / 'receipt_archives_fallback').resolve() + + +def test_config_exposes_freight_rpa_receipt_archive_dir(app): + """Flask Config 必须声明收料归档目录,否则 env 不会进 app.config。""" + with app.app_context(): + value = app.config.get('FREIGHT_RPA_RECEIPT_ARCHIVE_DIR') + assert value is not None + assert str(value).strip() != '' + + +def test_serialize_run_reads_receipt_raw_zip_available_from_summary(app): + """serialize_run 应暴露 receipt_raw_zip_available 供管理端深链/按钮。""" + from app.services.schedule.query_service import serialize_run + + with app.app_context(): + user = User(username='arch_receipt_ser', email='arch_receipt_ser@example.com') + db.session.add(user) + db.session.flush() + task = ScheduleTask( + schedule_no='ARCH-RCP-SER', + name='Receipt archive serialize', + schedule_type='platform_job', + platform_api_path='freight-receipt-rpa', + owner_user_id=user.id, + cron_expr='0 8 * * *', + ) + db.session.add(task) + db.session.flush() + run = ScheduleRun( + run_no='RUN-RCP-SER', + schedule_task_id=task.id, + status='success', + response_summary_json={'raw_receipt_zip_available': True}, + ) + db.session.add(run) + db.session.commit() + payload = serialize_run(run) + assert payload['receipt_raw_zip_available'] is True + assert payload['inventory_raw_zip_available'] is False + + +def test_build_zip_entry_name_prefers_source_code(): + """ZIP 条目名必须优先 source_code,序号三位补零。""" + assert _build_zip_entry_name( + index=1, + source_code='DSV360_AWSBI', + warehouse_id='BYAWSCM401', + original_suffix='.xlsx', + ) == '001_DSV360_AWSBI.xlsx' + + +def test_persist_receipt_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_RECEIPT_ARCHIVE_DIR'] = str(archive_dir) + monkeypatch.setattr( + 'app.services.schedule.shipping_receipt_rpa_archive.file_asset_storage.get_bytes', + lambda _key: b'fake-receipt-xlsx', + ) + + with app.app_context(): + run, report_file = _make_receipt_run_with_file( + schedule_no='SCH-RCP-ARCH-1', + run_no='RUNRCPARCH1', + callback_id='receipt-arch-1', + original_filename='receipt_RUN_DSV360_AWSDU_NA.xlsx', + ) + summary = persist_receipt_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 zip_path.is_file() + assert zip_path.parent.resolve() == archive_dir.resolve() + + with zipfile.ZipFile(zip_path, 'r') as archive: + names = archive.namelist() + assert 'manifest.json' in names + assert '001_DSV360_AWSDU.xlsx' in names + manifest = json.loads(archive.read('manifest.json').decode('utf-8')) + assert manifest['run_no'] == run.run_no + assert manifest['files'][0]['source_code'] == 'DSV360_AWSDU' + assert manifest['files'][0]['file_id'] == report_file.id + + +def test_resolve_receipt_raw_zip_download_rejects_missing_summary(app, tmp_path): + """summary 未标记可用时应 404。""" + app.config['FREIGHT_RPA_RECEIPT_ARCHIVE_DIR'] = str(tmp_path / 'receipt_archives') + with app.app_context(): + run, _ = _make_receipt_run_with_file( + schedule_no='SCH-RCP-ARCH-MISS', + run_no='RUNRCPARCHMISS', + callback_id='receipt-arch-miss', + ) + run.response_summary_json = {'raw_receipt_zip_available': False} + db.session.commit() + with pytest.raises(NotFoundError): + resolve_receipt_raw_zip_download(run) + + +def test_receipt_attachment_stem_uses_local_timezone(app): + """展示名前缀为收料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' + + +def test_admin_can_download_receipt_raw_zip(app, client, admin_jwt_headers, tmp_path, monkeypatch): + """管理端 receipt-raw-zip 应返回 ZIP 与展示名。""" + archive_dir = tmp_path / 'receipt_archives' + app.config['FREIGHT_RPA_RECEIPT_ARCHIVE_DIR'] = str(archive_dir) + monkeypatch.setattr( + 'app.services.schedule.shipping_receipt_rpa_archive.file_asset_storage.get_bytes', + lambda _key: b'fake-receipt-xlsx', + ) + + with app.app_context(): + run, _ = _make_receipt_run_with_file( + schedule_no='SCH-RCP-DL', + run_no='RUNRCPDL1', + callback_id='receipt-dl-1', + ) + summary = persist_receipt_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) + + response = client.get( + f'/api/admin/schedule-runs/{run_id}/receipt-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 diff --git a/docs/features/in-transit-transfer/minimum-implementation-spec.md b/docs/features/in-transit-transfer/minimum-implementation-spec.md index 8def6439..77cde852 100644 --- a/docs/features/in-transit-transfer/minimum-implementation-spec.md +++ b/docs/features/in-transit-transfer/minimum-implementation-spec.md @@ -62,7 +62,7 @@ - 按来源实例分组、路由或指定 Invoice 查询;DBS、Crane 仅为当前已配置的来源分组示例。 - 检查当前业务日期的最新 `ready` 收料文件。 - 文件缺失时实时触发 RPA,并在对话中持续展示进度。 -- 按 HUB 仓收料日期执行 D+1 成熟规则。 +- 按 HUB 仓收料日期执行 T+lag 成熟规则(默认 T+2,`IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS` 可配)。 - 相同 Invoice 多行汇总收料数量。 - 按 Invoice No 查询 ERP 账面库存。 - 生成可执行、未成熟、阻断和预计调拨数量。 @@ -691,7 +691,7 @@ AI:正在检查已选来源实例的收料文件;缺失来源会实时抓取 ```text ┌─ 调拨策略 Draft V4 ─────────────────────────────────────────────┐ -│ 业务时区 Asia/Shanghai 成熟规则 D+1 │ +│ 业务时区 Asia/Shanghai 成熟规则 T+2(可配) │ │ 数量门禁 必须完全相等 确认有效期 10分钟 │ │ ERP查询超时 60秒(环境变量) ERP写超时 60秒 │ │ [开] 对话执行前一次确认 │ @@ -856,7 +856,7 @@ AI:正在检查已选来源实例的收料文件;缺失来源会实时抓取 | 路径 | 内容 | | --- | --- | -| `backend/app/services/schedule/in_transit_receipt_file_job.py` | 08:00文件抓取排程 | +| ~~`backend/app/services/schedule/in_transit_receipt_file_job.py`~~ | 已下线(2026-09-28):文件就绪保障内建于在途自动调拨,独立排程类型删除 | | `backend/app/services/schedule/in_transit_transfer_job.py` | 09:00自动调拨排程 | | `backend/app/services/in_transit_transfer/backlog_service.py` | 历史待处理池和老化 | | `backend/app/services/in_transit_transfer/recovery_service.py` | 自动复核和新Attempt | @@ -918,7 +918,7 @@ AI:正在检查已选来源实例的收料文件;缺失来源会实时抓取 | 风险 | 控制 | | --- | --- | -| 当天收料被误调拨 | D+1硬门禁,未成熟不查询ERP | +| 当天收料被误调拨 | T+2成熟硬门禁(可配),未成熟不查询ERP | | 历史失败被遗忘 | 自动待办池、每日复核、3/5/7天升级 | | 自动恢复误补偿 | 最新文件、ERP、幂等、映射全门禁和新Attempt | | 人工关闭滥用 | 原因必填、快照、永久审计 | diff --git a/docs/features/in-transit-transfer/roadmap.md b/docs/features/in-transit-transfer/roadmap.md index ee1d188a..d58a02de 100644 --- a/docs/features/in-transit-transfer/roadmap.md +++ b/docs/features/in-transit-transfer/roadmap.md @@ -382,7 +382,7 @@ Phase 2完成后可以在ERP测试组织进行端到端试点。若申请小范 | 复用修改 | `backend/app/services/schedule/job_params.py` | 来源、所有者、通知人、并发、恢复参数 | | 复用修改 | `backend/app/services/schedule/schedule_contract.py` | 调拨排程稳定契约 | | 复用修改 | `backend/app/services/schedule/scheduler_service.py` | 调拨Run收尾、通知状态和运行摘要 | -| 计划新增 | `backend/app/services/schedule/in_transit_receipt_file_job.py` | 08:00文件准备任务 | +| ~~计划新增~~ 已下线(2026-09-28) | `backend/app/services/schedule/in_transit_receipt_file_job.py` | 文件准备职责内建于在途自动调拨排程 | | 计划新增 | `backend/app/services/schedule/in_transit_transfer_job.py` | 09:00自动调拨任务 | | 计划新增 | `backend/app/services/in_transit_transfer/backlog_service.py` | 待处理池、3/5/7天老化和责任人 | | 计划新增 | `backend/app/services/in_transit_transfer/recovery_service.py` | 最新快照重新预检和新Attempt | diff --git a/docs/features/in-transit-transfer/technical.md b/docs/features/in-transit-transfer/technical.md index 3d3c4200..9a266400 100644 --- a/docs/features/in-transit-transfer/technical.md +++ b/docs/features/in-transit-transfer/technical.md @@ -27,10 +27,12 @@ | --- | --- | --- | | `IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY` | 2 | 来源并发 | | `IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS` | 600 | stale 徽标展示阈值(**2026-09-25 由执行门禁退役为纯展示**:超时行仅亮「库存数据已过期,请重查」徽标引导重查,不拦截执行;防错由文件版本对账 + worker 写前库存复查承担,见 §6.3。历史:2026-09-24 曾作为行级新鲜度执行门禁由确认窗 10 分钟放宽为 24h=当日有效,随三层管道定稿退役;经 `deps._strategy_from_config` 从 Flask 配置装配——2026-09-24 接线修复,此前该环境变量为死配置恒 600s) | +| `IN_TRANSIT_TRANSFER_INVENTORY_STALE_TTL_SECONDS` | 86400 | 库存查得时刻(`inventory_checked_at`)的 stale 徽标判定窗口(**2026-09-29 新增**:stale 时钟由 `updated_at` 换源为库存取数时刻——仅匹配评估/重查/写前复查写入,证据同步换戳不续期;修复原时钟被每日收料文件同步续期导致老行徽标永不触发的问题) | | `IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS` | 3 | 老化预警阈值 | | `IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS` | 5 | 老化升级阈值 | | `IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS` | 7 | 老化严重阈值 | | `IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET` | hxops-transfer | 归档 bucket | +| `IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS` | 2 | 收料成熟滞后天数(T+lag;eligible ≤ T−lag) | | `MINIO_ENDPOINT` / `MINIO_ACCESS_KEY` / `MINIO_SECRET_KEY` / `MINIO_SECURE` | 既有 | MinIO 连接(复用既有变量) | | `FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR` | 既有 | 收料 RPA trigger 目录(复用收料链路) | @@ -47,9 +49,9 @@ | Method | Path | 说明 | | --- | --- | --- | | POST | `/matchings` | 创建/复用一次调拨匹配(只读,不写 ERP;body `source_codes` 必填,可选 `business_date`/`receipt_date_from`/`receipt_date_to`/`transfer_type`,缺省 `in_transit_to_hub`;响应含 matching_id/hash/计数/来源进度) | -| GET | `/items/executable` | 可调拨明细:全局 ready_to_execute 行队列(业务稳定排序=收料日期→Invoice→created_at;行含 item_id/checked_at/stale/file_current),勾选后 POST `/items/execute` 按行生成调拨单 | +| GET | `/items/executable` | 可调拨明细:全局 ready_to_execute 行队列(业务稳定排序=收料日期→数据源→Invoice→created_at,2026-09-29 与待处理池/匹配卡视图统一为同一口径;行含 item_id/checked_at/stale/file_current),勾选后 POST `/items/execute` 按行生成调拨单 | | GET | `/matchings/{id}` | 按 scope 实时视图恢复匹配进度(行含 `item_id`/`checked_at`/`stale`/`file_current`,counts 实时聚合) | -| POST | `/matchings/{no}/items/requery` | 批量重查 ERP 库存——圈行口径=匹配 scope(与匹配卡实时视图同源谓词,行归属 matching_id 不参与;2026-09-24 修复:旧按 matching_id 圈行致历史行重查不可达);body 可选 `invoice_nos` 限定范围 | +| POST | `/matchings/{no}/items/requery` | 批量重查 ERP 库存——圈行口径=匹配 scope(与匹配卡实时视图同源谓词,行归属 matching_id 不参与;2026-09-24 修复:旧按 matching_id 圈行致历史行重查不可达);body 可选 `invoice_nos` 限定范围;库存查询按组织批量(2026-09-29:每组织一次 `query_stock`,N 行=N 组织内 1 次调用,行级评估/Attempt/审计保持单行粒度) | | POST | `/sources/receipt-files` | 按选中来源打包下载各自最新归档收料文件 zip(下载留审计) | | GET | `/runs/{run_no}` | Run 结果(`orders` 调拨单清单=进度=结果,逐单八键/行六键含 reason;+ 按 ERP 单号聚合 external_documents + 未落单异常 exceptions) | | POST | `/runs/{run_no}/cancel` | 请求停止剩余任务(原因必填) | @@ -57,16 +59,16 @@ | POST | `/items/{id}/manual-close` | 人工关闭(原因必填) | | POST | `/items/execute` | 按行提交执行(**202 异步**:body `{"item_ids":[..]}`;API 侧两道门禁——存在可执行 / 文件版本对账——任一不过 fail-closed 400,错误码 `TRANSFER.EXECUTE_ITEMS_INVALID` / `TRANSFER.FILE_CHANGED`,`error.details` 携带对应 id 列表;通过即建 queued Run + 五元组分组建单 + 一次入队,响应 `data={"run_no","status":"queued"}`,Run 留痕不绑匹配;进度与结果经 `GET /runs/{run_no}` 轮询,worker 逐单执行:文件对账复核 + 写前路由/库存复查后建单。门禁终态见 §6.3——行级新鲜度 TTL/`TRANSFER.ITEMS_STALE` 已退役) | | POST | `/runs/{run_no}/documents/{doc_no}/retrigger` | 人工重新触发 result_unknown 单(D11 唯一出口,禁止关闭重建):复用原单 doc_no/submit_timestamp 只触发末步(幂等);202 `data={"run_no","doc_no","status":"queued"}`;非 result_unknown 单 400 `TRANSFER.RETRIGGER_NOT_ALLOWED` | -| GET | `/documents` | 已执行单分页查询(首页「已执行」区块数据源,只读):query `status_group` ∈ {success,failed,executing,result_unknown}(缺省全部)/ `date_from`/`date_to`(仅作用列表)/ `page`/`page_size`(默认 20 上限 100);分组计数恒全量(GROUP BY status 不受筛选影响),列表 created_at 倒序,cancelled 不展示 | +| GET | `/documents` | 已执行单分页查询(首页「执行看板」区块数据源,只读):query `status_group` ∈ {success,failed,executing,result_unknown}(缺省全部)/ `date_from`/`date_to`(按收料日期过滤,仅作用列表;2026-09-29 由 created_at 切换)/ `page`/`page_size`(默认 20 上限 100);分组计数恒全量(GROUP BY status 不受筛选影响),列表按 收料日期→数据源→拨出/拨入库位 升序分页(2026-09-29 与池子/结果卡统一),cancelled 不展示 | | POST | `/documents/{doc_no}/close` | 人工关闭失败单(D18 废单不废行):仅 business_failed/technical_failed 可关(result_unknown 走 retrigger、在飞/已完结 400 `TRANSFER.DOCUMENT_CLOSE_NOT_ALLOWED`),原因必填;单 → cancelled + closed_reason,单内行全部脱离(回 ready_to_execute、清行级结果),组锁释放可另开新单;审计留痕 | -| POST | `/items/batch-requery` | 批量重查库存=恢复处理(body `item_ids`;单行隔离,逐行 external_recheck) | +| POST | `/items/batch-requery` | 批量重查库存=恢复处理(body `item_ids`;单行隔离;2026-09-29 起库存查询按组织批量——每组织一次 `query_stock`,不再逐行单查外部系统) | | POST | `/items/batch-manual-close` | 批量人工关闭(body `item_ids` + `reason`;单行隔离) | | GET | `/runs/{run_no}/exceptions.xlsx` | 七 Sheet 异常 Excel(下载留审计) | | GET | `/runs/{run_no}/receipt-files` | 收料来源文件 zip(下载留审计) | | GET | `/runs/{run_no}/external-inventory` | 匹配冻结 ERP 库存表 csv(下载留审计) | | GET | `/metrics` | 调拨运营指标(成功率/失败类型/待处理老化/通知失败) | -| GET | `/sources` | 来源实例列表(附收料文件状态 ready/fetching/failed/expired/none + has_ready_file,供前端门禁) | -| POST | `/sources/{source_code}/retry-rpa` | 对指定来源重新触发一次收料 RPA 抓取(配置缺失 fail-closed ok=False) | +| GET | `/sources` | 来源实例列表(附收料文件状态 ready/parse_failed/fetching/failed/expired/none + has_ready_file,供前端门禁;2026-09-29 起 `parse_failed`=当日文件在但 movement 解析失败(`has_ready_file=false`),路由失败仅行内 `blocked_route_not_resolved`、不抬升来源顶栏) | +| POST | `/sources/{source_code}/retry-rpa` | 来源收料重试(2026-09-29 起分层:parse_failed 且有当日可用文件时优先本地重解析——成功 ready / 仍失败 parse_failed,200 `reparsed=true`,不触发 RPA;否则原样重新触发一次收料 RPA 抓取,202+fetching,配置缺失 fail-closed ok=False) | | GET | `/backlog` | 待处理异常列表(可恢复/已关闭/结果未知 + 老化等级;查看留审计) | | GET | `/backlog/summary` | 待处理异常汇总(含 3/5/7 天老化分级) | @@ -78,19 +80,19 @@ - **主叙事**:库存匹配(动作,首页「库存匹配」卡发起)→ 可调拨清单(匹配结果的实时视图,勾选)→ 生成调拨单(按行执行);匹配不上的行进入待恢复异常(恢复处理=行级重查)。 - **行不迁移(行归属与匹配解耦)**:`TransferInvoiceItem.matching_id` 仅记录首次评估建行时的匹配(2026-09-25 起文件落地同步行 `matching_id` 为 NULL,见 §6.3)。后续对同一 scope 的重复匹配/重查对既有行**原地刷新**(不迁移 `matching_id`),并刷新 `updated_at`(stale 徽标的新鲜度展示依据);终态行(success / duplicate_success / manually_closed / cancelled / executing)不迁移、不复活。同一批行可同时被多份同 scope 匹配看到,不存在"行被掏空/迁走",也不依赖两份匹配的执行集合互斥来防重(防重由执行门禁——文件版本对账/写前库存复查——+ ERP Invoice 幂等键承担)。 -- **匹配 = 评估留痕**:匹配记录(表 `transfer_matchings`,单号 `matching_no` 前缀 `MTG-` 由 `_generate_no` 生成)固化 scope(来源 / 收料日期区间 / 调拨类型)、counts、收料文件快照与 `matching_hash` 作为**评估留痕**;hash 与 `expires_at` **不拦截执行**(仅展示)。匹配卡与 `GET /matchings/{id}` 是 scope 的**实时视图**:按 scope 重新圈行并逐行装饰 `checked_at`(库存查询时刻)/ `stale`(新鲜度)/ `file_current`(文件版本对账),counts 亦为 scope 实时聚合(不读 counts_json 快照)。 +- **匹配 = 评估留痕**:匹配记录(表 `transfer_matchings`,单号 `matching_no` 前缀 `MTG-` 由 `_generate_no` 生成)固化 scope(来源 / 收料日期区间 / 调拨类型)、counts、收料文件快照与 `matching_hash` 作为**评估留痕**;hash 与 `expires_at` **不拦截执行**(仅展示)。匹配卡与 `GET /matchings/{id}` 是 scope 的**实时视图**:按 scope 重新圈行并逐行装饰 `checked_at`(库存查询时刻=「inventory_checked_at」,2026-09-29 起仅匹配评估/重查/写前复查刷新,证据同步换戳不续期)/ `stale`(新鲜度,时钟=inventory_checked_at,阈值 `IN_TRANSIT_TRANSFER_INVENTORY_STALE_TTL_SECONDS` 默认 24h)/ `file_current`(文件版本对账),counts 亦为 scope 实时聚合(不读 counts_json 快照)。 - **执行 = 按行 + 执行门禁(2026-09-25 定稿,权威口径见 §6.3)**:`POST /items/execute` 按 `item_ids` 执行,Run 留痕不绑匹配;手工执行与自动排程共用同一入口。门禁任一不过 fail-closed(ERP 写入为 0): | 门禁 | 防什么 | 机制 | 失败表现 | | --- | --- | --- | --- | | ① 存在可执行(API 前置校验) | 误传/不可执行行 | id 不存在或非 `ready_to_execute` 即拒绝 | `TRANSFER.EXECUTE_ITEMS_INVALID`(`details.invalid_item_ids`) | - | ② 文件版本对账(API + worker 双侧) | 文件漂移 | 行评估版本戳(file_sha256)≠ 来源最新可用文件 sha(含来源无可用文件 / 行无版本戳)即拒绝;API 侧 400、worker 侧整 Run 落败(单 technical_failed/file_changed);评估后被更新版本文件取代而**消失的 ready 行**在匹配/重查时标 `blocked_file_removed` 入异常池(fail-closed,宁可误拒也不按过期文件写 ERP);匹配卡主视图不渲染该类行(折叠提示计数+引导去待处理池「标记无需继续处理」,2026-09-24) | `TRANSFER.FILE_CHANGED`(`details.changed_item_ids`) | + | ② 文件版本对账(API + worker 双侧) | 文件漂移 | 行评估版本戳(file_sha256)≠ 来源最新可用文件 sha(含来源无可用文件 / 行无版本戳)即拒绝;API 侧 400、worker 侧整 Run 落败(单 technical_failed/file_changed);2026-09-28 起收料文件按非全量导出对待(存续原则:缺席≠删除),缺席行只换版本戳保留状态,不再产生 `blocked_file_removed`;该结果码仅为历史残留数据的防御识别,真实删除走待处理池人工关闭;匹配卡主视图不渲染历史 `blocked_file_removed` 行(折叠提示计数+引导去待处理池「标记无需继续处理」,2026-09-24) | `TRANSFER.FILE_CHANGED`(`details.changed_item_ids`) | | ③ 写前库存复查(worker 逐单,仅全量重跑路径) | ERP 账面漂移 | `create_transfer` 前按组织批量重查账面:查无 → `blocked_inventory_not_found`、数量不等 → `blocked_quantity_mismatch`,均携带最新账面数量原位落行并移出本单(不写 ERP,单项失败不阻断其他行);final_only/result_unknown 续跑**不复查**(单可能已建成,阻断即假失败) | 行级 `blocked_inventory_not_found` / `blocked_quantity_mismatch`(不整批失败;全行漂移 → 单 business_failed/stock_drifted) | | ④ 写前路由复查(worker 逐单) | 路由漂移 | 以收料仓库列重解析路由,路由变化标该行阻断(单项失败不阻断其他行) | 行级 `matching_expired`(不整批失败) | 门禁前置校验:id 不存在或非 `ready_to_execute` → `TRANSFER.EXECUTE_ITEMS_INVALID`(`details.invalid_item_ids`)。 **[2026-09-25 TTL 退役]** 原「① 行级新鲜度 TTL」门禁(行 `updated_at` 距 now 超过 `IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS` → `TRANSFER.ITEMS_STALE`,API 与 worker 双侧)已整体删除——匹配 10 分钟后必被拒是 2026-09-24 事故的死锁根因;该阈值降级为 stale 徽标(「库存数据已过期,请重查」)纯展示提示,不拦截执行;`TRANSFER.ITEMS_STALE` 错误码退役(后端不再抛出)。 -- **恢复处理 = 行级重查**:待处理池「恢复处理」= 对选中行逐行 external_recheck(`POST /items/batch-requery`,重查前先做证据对齐兜底 `align_scope_rows`,见 §6.3)**原地刷新 + 续新鲜度**,不创建匹配、不迁移行,单行隔离;ERP 事实修正后重查通过即回到可执行。按组重建范围匹配的 `POST /items/batch-resume` 与 `resume_service` 已删除,无兼容层。 +- **恢复处理 = 行级重查**:待处理池「恢复处理」= 对选中行批量 external_recheck(`POST /items/batch-requery`,重查前先做证据对齐兜底 `align_scope_rows`,见 §6.3)**原地刷新 + 续新鲜度**,不创建匹配、不迁移行,单行隔离(单行门禁/路由失败不影响其余行);ERP 事实修正后重查通过即回到可执行。按组重建范围匹配的 `POST /items/batch-resume` 与 `resume_service` 已删除,无兼容层。 ## 5. 部署 @@ -135,7 +137,7 @@ cd backend && flask db upgrade **证据轴(文件落地 → 待办行,主链路)** -- 收料 RPA 回调 success 终态落文件后,`shipping_notice/receipt_report_storage.ingest_receipt_callback` 内联桥接 `evidence_sync.sync_and_commit_for_callback` → `evidence_sync.sync_source_rows`,一次解析三分类写入:文件里有、本地无 → 插入**待查行**(`status='matching'` + `result_code='pending_stock_check'`);收料证据变了(数量/批号/仓库)→ 刷新证据并**重置回待查**(旧库存是对旧数量查的,作废;名称/规格等展示值变更只换版本戳不重置);文件里消失 → **`blocked_file_removed` 入待处理池出清**(换戳到最新文件 sha)。同文件重复落地零写入(幂等跳过,不续新鲜度);消失标记行复现 → 无条件恢复待查。终态行绝不触碰。全程零外部调用(不查 ERP、不触发 RPA)。 +- 收料 RPA 回调 success 终态落文件后,`shipping_notice/receipt_report_storage.ingest_receipt_callback` 内联桥接 `evidence_sync.sync_and_commit_for_callback` → `evidence_sync.sync_source_rows`,一次解析三分类写入:文件里有、本地无 → 插入**待查行**(`status='matching'` + `result_code='pending_stock_check'`);收料证据变了(数量/批号/仓库)→ 刷新证据并**重置回待查**(旧库存是对旧数量查的,作废;名称/规格等展示值变更只换版本戳不重置);文件里缺席 → **存续**(只换版本戳到最新文件 sha,状态与结果码原样保留;缺席≠删除)。同文件重复落地零写入(幂等跳过,不续新鲜度);终态行绝不触碰。全程零外部调用(不查 ERP、不触发 RPA)。 - **桥模式**:try/except 仅 warning 日志 + 桥内自行 commit——桥是记账不是收料链路的正确性依赖,任何异常不得波及收料归档终态(`sync_source_rows` 只 flush 不 commit:桥自行 commit,匹配/重查随主事务)。 - **兜底对齐 `align_scope_rows`**:匹配主入口(`run_matching` STEP 0)与两类批量重查(scope 重查 / batch-requery)执行前先对齐——按来源比对「非终态行版本戳集合 vs 最新文件 sha」,不一致才重解析(落地同步失败/迟到的静默补救),**sha 一致直通零解析开销**;来源级隔离(单来源解析失败只标该来源,不炸整批)。 @@ -189,7 +191,7 @@ cd backend && flask db upgrade - **融合卡**:`GET /runs/{run_no}` orders 逐单亮态(成功/失败/未知三态+ERP 单号回显),202 提交后 4s 轮询至严格终态;retrigger 受理窗口不误停轮询。 - **retrigger**:result_unknown 单复用 doc_no/submit_timestamp 只触发末步,ERP 幂等回原单号;非 result_unknown 400。 - **关闭单**:business_failed/technical_failed 人工关闭(原因必填),单 cancelled、行脱离回可执行、组锁释放可另开新单;result_unknown 无关闭入口(SOP 红线 §10.8)。 - - **已执行区块**:`GET /documents` 分组计数恒全量、时间窗/状态筛选仅作用列表、分页上限 100、cancelled 不展示。 + - **执行看板区块**(2026-09-29 由「已执行调拨单」改名):`GET /documents` 分组计数恒全量、时间窗(收料日期)/状态筛选仅作用列表、列表按收料日期→数据源→库位升序、分页上限 100、cancelled 不展示。 - **database 直连**:四库 `db_kind` 探针连通性验证;中间表 SQL `identifiers` 白名单替换 + 残留 `{...}` fail-closed;同 operation_id 多步审计共存(迁移 tt5b6c7d8e9f 往返有自动化测试)。 - 上线门禁:P0/P1 缺陷 0;越权写 403 100%;当天收料 ERP 调用 0;审计 Hash 复算一致率 100%;Secret 明文暴露 0。 diff --git a/docs/features/shipping-notice/business.md b/docs/features/shipping-notice/business.md index 53493a7e..3612f1a1 100644 --- a/docs/features/shipping-notice/business.md +++ b/docs/features/shipping-notice/business.md @@ -58,11 +58,10 @@ ### 库存站点启用 -- 管理员可先保存停用的库存站点,填写系统连接、报表路径、查询条件、仓库识别方式和快照有效期;首次保存不要求手工选择库存文件解析方案。 -- 库存文件解析方案说明 Excel 的工作表、表头、栏位对应和订单匹配键;仓库映射说明货代仓库对应哪个外部系统仓库,两者是不同配置。 -- 正式启用是单独操作。系统会显示尚未完成的系统连接、库存文件解析方案、发货模板和测试导出与解析验证。管理员必须在停用状态发起测试导出,查看结构分析结果并确认本次推荐的已发布解析方案;站点编辑后须重新测试。 -- 启用前系统还会复核:解析方案至少配置一个用于订单与库存关联的字段、且只配置一个库存数量字段;发货模板引用的库存字段均由解析方案提供。固定仓须有精确仓库映射或库存源默认映射;按库存行识别仓库的站点还须配置一个仓库识别字段,并为样例出现的每个货代仓维护外部系统仓库映射。系统只提出缺失项,不会猜测或自动建立仓库映射。 -- 站点进入正式运行后,每次 RPA 导出仍会检查文件结构。新增无关栏位会作为提示记录在库存快照中;关键栏位改名、缺失或结构不兼容时,本次文件不会进入库存匹配,管理员需修订并发布解析方案后重新测试和启用。 +- 管理员可先保存停用的库存站点,填写系统连接、报表路径、查询条件、仓库识别方式,并绑定已发布的库存解析方案与发货模板;首次保存不启用。 +- 正式启用由管理端即时开关完成。硬门槛仅为:可用连接、已发布库存解析方案、已绑定已发布发货模板及模板字段契约。不再要求先测试导出,也不再因测试回调自动启用。 +- 已启用站点可直接更换库存解析绑定(仍须满足已发布方案与发货模板字段契约);停用经确认后立即生效。 +- 批量测试导出仍可作为可选运维工具,不阻断启停。站点进入正式运行后,每次 RPA 导出仍会检查文件结构;关键栏位改名、缺失或结构不兼容时,本次文件不会进入库存匹配。 3. **核对库存**:按管理员维护的订单字段与库存字段对应关系进行匹配,再用配置为“库存数量”的字段判断是否可满足需求数量。 4. **生成发货文件**:生成符合货代要求的发货 Excel。 5. **上传货代系统**:自动或手工确认上传至货代平台。 diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 27942573..34e65b6c 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -1737,6 +1737,7 @@ FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=data/freight_rpa/inventory/drop FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory/triggers FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=data/freight_rpa/receipt/drop FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=data/freight_rpa/receipt/triggers +FREIGHT_RPA_RECEIPT_ARCHIVE_DIR=data/freight_rpa/receipt/archives FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=data/freight_rpa/inventory/upload_queue FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/freight_rpa/inventory/upload_triggers @@ -1839,7 +1840,7 @@ GET /api/admin/shipping-order-schema/published-contract - 批量测试创建时各站点先处于 `awaiting_rpa / waiting_worker`。Windows Worker 实际领取某个站点前,会向 `POST /api/shipping-notice/rpa/inventory-configuration-test-batch-progress` 回调该站点的 `validation_run_no` 与受控阶段 `rpa_exporting`;后端仅允许将当前批次的非终态运行写为 `processing / rpa_exporting`。因此管理端可以区分“尚未被 Worker 领取”和“RPA 正在登录并导出”;最终成功、无库存或失败仍必须通过原有 `inventory-configuration-test-batch-ready` 回调确认,进度回调不得覆盖终态。同一 Profile 仍只登录一次,但每个 DSV 站点使用新的页面并复用同一 browser context 的登录 Cookie,避免上一站报表 iframe、下载菜单或等待状态污染下一站。 - 测试运行超过 `FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS`(默认 900 秒)仍未完成时,服务端在读取或再次发起测试时将其收口为 `failed / failed`,提示“等待 RPA Worker 超时,请重新测试”。同一 Worker 队列中的批量站点按队列站点数线性扩展等待窗口,避免后排站点尚未领取就按单站时限误判超时;单站测试仍使用原始等待窗口。超时、版本不一致和重复/迟到回调都不能更新当前站点绑定或放行启用。**Dify 手动配置说明**:此恢复与轮询机制不要求修改 Dify 画布、Tool 或 Prompt;Dify 不读取此管理端状态接口。 - **DSV SSO 回跳优化(2026-07)**:密码提交后,Worker 将 `auth.dbschenker.com` 的授权回跳与 Portal Reports 菜单加载分开计时。空白 `authorization.ping/oauth2` 中转页停留 `FREIGHT_RPA_WORKER_DSV_SSO_RELOAD_AFTER_MS`(默认 12000)后只刷新一次;超过 `FREIGHT_RPA_WORKER_DSV_SSO_RETURN_TIMEOUT_MS`(默认 90000)仍未回到 Portal 时,明确报 `DSV SSO authorization return timed out`,不再伪装为库存测试超时。Portal 壳层出现后仅轮询 Reports 导航,避免反复读取整页与 iframe。Dify 无需修改配置。 -- **DSV 性能证据与快速路径(2026-08)**:库存导出 Worker 以 `[dsv-chain]` 输出不含凭据和查询参数的 `session_prepare`、`report_navigation`、`report_parameter_fill`、`report_execute_and_download`,并将最后一段拆为 `report_result_ready` 与 `excel_export_and_download` 的 `start/end/error` 与 `elapsedMs`;登录内层继续输出 `auto_login.*` 子阶段,Warehouse option 等待继续输出 `waitedMs`。- 提交 View Report 后直接等待 SSRS 业务就绪条件,不以可能被长连接阻塞的 `networkidle` 作为前置条件。result_ready(分页/工具栏)之后**明细行是异步渲染**的:worker 用 `_wait_dsv_report_inventory_rows` 做条件轮询(1s 间隔、上限 45s)等待真实数据行,而非单次快照,避免"分页已出、行未渲染"被误判为无库存数据(2026-08-26 真实案例:160 页报表被单次探针误判 skip)。Excel 下载等待窗口按实测放宽:`expect_download` 使用 `FREIGHT_RPA_WORKER_DSV_DOWNLOAD_WAIT_MS`(默认 240s,SSRS 生成 34s~90s+ 波动),目录兜底 60s;禁止复用全局 60s 浏览器超时作为下载等待(2026-08-26 多次 `Timeout 60000ms exceeded while waiting for event "download"` 根因)。Reports 级联菜单先走一次精确文本的 hover/click 快速路径,只有未确认下一级已展开时才退回原多 selector、多动作兼容链;不得因优化删除回退逻辑。一次真实运行据此区分认证/首页、报表菜单/参数页、参数异步加载、SSRS 结果与 Excel 导出下载耗时。 +- **DSV 性能证据与快速路径(2026-08)**:库存导出 Worker 以 `[dsv-chain]` 输出不含凭据和查询参数的 `session_prepare`、`report_navigation`、`report_parameter_fill`、`report_execute_and_download`,并将最后一段拆为 `report_result_ready` 与 `excel_export_and_download` 的 `start/end/error` 与 `elapsedMs`;登录内层继续输出 `auto_login.*` 子阶段,Warehouse option 等待继续输出 `waitedMs`。- 提交 View Report 后直接等待 SSRS 业务就绪条件,不以可能被长连接阻塞的 `networkidle` 作为前置条件。result_ready(分页/工具栏)之后**明细行是异步渲染**的:worker 用 `_wait_dsv_report_inventory_rows` 做条件轮询(1s 间隔、上限 45s)等待真实数据行,而非单次快照,避免"分页已出、行未渲染"被误判为无库存数据(2026-08-26 真实案例:160 页报表被单次探针误判 skip)。**收料 Receipt Detail(2026-09-28)**:共享导出驱动按 `source.__export_kind__=receipt`(或报表名含 Receipt Detail)分流——正文标记用 `external asn` / `wms receipt` / `qty expected|received` 等,就绪也可看 Export 工具栏;`asyncWait` 以可见 `#ReportViewerMain_AsyncWait` 消失为准(禁止 body 扫 loading,避免日历 iframe 假阳性);明细行探针用收料表头,**禁止复用**库存 `on hand inventory` / `Qty Available` 判定。Excel 下载等待窗口按实测放宽:`expect_download` 使用 `FREIGHT_RPA_WORKER_DSV_DOWNLOAD_WAIT_MS`(默认 240s,SSRS 生成 34s~90s+ 波动),目录兜底 60s;禁止复用全局 60s 浏览器超时作为下载等待(2026-08-26 多次 `Timeout 60000ms exceeded while waiting for event "download"` 根因)。Reports 级联菜单先走一次精确文本的 hover/click 快速路径,只有未确认下一级已展开时才退回原多 selector、多动作兼容链;不得因优化删除回退逻辑。一次真实运行据此区分认证/首页、报表菜单/参数页、参数异步加载、SSRS 结果与 Excel 导出下载耗时。 - 多个 Inventory Source 可绑定同一个 published Profile;同模板只维护一份。存在少量列差异时创建新 Profile 版本或新 Profile,不在 Source 中复制完整映射。 - 库存站点首次保存不要求绑定解析方案,且普通保存始终保持停用;后端仅允许通过独立启用接口进入正式运行。启用检查列出系统连接、库存文件解析方案、发货模板和测试导出与解析验证;确认后测试记录与站点当前配置版本绑定,后续编辑会使其失效。草稿、缺失或非法作用域字段仍阻断正式运行期自动解析。 - 启用检查复用确认测试的结构记录,按当前方案实际映射的用途验证:至少一个匹配字段样例非空、唯一数量字段为数值;发货模板的全部库存字段必须由该方案提供。固定仓要求精确 `freight_warehouse_id` 映射或库存源默认映射;动态仓还要求唯一仓库识别字段且测试样例中每个仓库都有精确映射或默认映射。该检查只查询已维护的 `ShippingInventoryExternalMapping`,绝不自动创建映射。 @@ -2195,7 +2196,7 @@ Get-Content C:\HxopsRpaTest\data\freight_rpa\inventory\triggers\.hxops_rpa_share cat /mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers/.hxops_rpa_shared_mount ``` -管理端 `GET /api/admin/rpa-workers/status` 可查看最后心跳;Worker 离线时触发库存 RPA 会立即失败(fail-fast),不再空等 900s。排程管理工作台的「RPA Worker 在线」徽标对该接口做 **10s 前台轮询**(仅库存排程工作台模式,后台标签页暂停、请求未返回时跳过);执行记录列表按**历史查询**处理,仅切任务/点查询/重置时加载,不做定时自动刷新。 +管理端 `GET /api/admin/rpa-workers/status?scope=inventory|receipt` 可查看最后心跳;Worker 离线时触发库存 RPA 会立即失败(fail-fast),不再空等 900s。排程管理工作台的「RPA Worker 在线」徽标对该接口做 **10s 前台轮询**(库存 `shipping-inventory-rpa` 与收料 `freight-receipt-rpa` 工作台;收料按 `*-receipt` 身份且与库存同口径要求共享哨兵;后台标签页暂停、请求未返回时跳过);执行记录列表按**历史查询**处理,仅切任务/点查询/重置时加载,不做定时自动刷新。「立即执行」等待期只轻量轮询任务 last_status(listAdminSchedules),禁止连环打 runs 或盖住「正在查询记录…」;离开 running 或等待超时后再拉一次执行记录(库存/收料 RPA 写 trigger 后会长时间 running/awaiting callback,旧逻辑每 5s 全量 runs 会把收料工作台打爆)。 心跳存储:test/prod 默认要求 **Redis**(`FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=true`)。Redis 不可用时触发与排程会报 `RPA.HEARTBEAT_STORAGE_UNAVAILABLE`;仅当 `FREIGHT_RPA_WORKER_ALERT_ENABLED=true` 时,调度器才会按冷却发送企微「心跳存储异常」告警(默认关闭)。 @@ -2352,6 +2353,7 @@ SHIPPING_NOTICE_TOOL_API_KEY=请替换为强随机ASCII密钥 SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900 +# 库存快照复用/过期的唯一权威(小时);站点表 snapshot_ttl_seconds 不参与 expires_at 计算,管理端也不再暴露按源 TTL。 SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers @@ -2988,7 +2990,7 @@ Windows RPA:C:\HxopsRpaTest\data\freight_rpa\receipt\drop Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_rpa/receipt/drop ``` -浏览器 Profile:收料 Worker 在 `FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR`(收料启动脚本默认指向 `\data\freight_rpa\common\browser_profile`)下,为每个 `connector + profile + login_url` 分组创建 `receipt_*` 临时目录,组处理完立即删除;不保留跨排程登录会话。与库存 Worker 的 `run_*` 一次性 Profile、`{connector}__{profile}_session` 长期会话目录互不影响。 +浏览器 Profile:收料 Worker 默认开启会话复用(`FREIGHT_RPA_WORKER_SESSION_REUSE`,对齐库存;关闭传 `-NoSessionReuse`)。持久目录按 `connector_type + rpa_profile_code` 隔离为 `{connector}__{profile}_session`(`dbs`/`crane` 与库存 `dsv360`/`crane_footprint` 命名空间分离,禁止共用单一 `receipt_session`)。一次性模式仍用 `receipt_*` 临时目录,批次结束删除。Profile 根目录为 `FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR`(收料启动脚本默认指向 `\data\freight_rpa\common\browser_profile`)。每笔导出开始回调 `receipt-unit-progress`(`awaiting_rpa`→`processing`)。对齐库存:导出重试只覆盖落盘/校验;落盘成功后先轻量 `receipt-batch-progress` 抬升排程计数,再调 `receipt-batch-ready` 归档;ready 超时不得触发重新下载(2026-09-28 同源双文件根因)。 #### 1.9.2 Windows RPA 主机:部署收料 Worker @@ -3062,13 +3064,13 @@ FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS=900 - 收料文件在回调时**原样上传 MinIO**(`shipping/receipt-reports/{年}/{月}/{单元}/{sha256}.xlsx`),保留三年;MinIO 不可用时该单元回调失败,不落成功态。 - 到期对象由平台排程任务 **货代收料归档到期清理**(`freight-receipt-rpa-retention`)删除,建议在排程管理配置每日一次;它只删除过期对象,不删除运行、文件事实与审计记录。 -- 企微通知与库存排程**同一出口同一门禁**(`scheduler_service._notify_schedule_run_wecom`,2026-09-21 统一):收料 run 全部单元终态归集后**一次性**发送 textcard 汇总(`schedule_completed` 事件)+ 该 run 全部收料文件消息;回调时不再逐文件即时推送。接收人取排程任务的 `notify_user_ids` + `notify_enabled`,且必须已完成企微绑定;排障查 `schedule_runs.wecom_notified / wecom_notify_error`。管理员重发(`/receipt-report-files/{id}/resend`)保留为补偿通道,不触发 RPA,投递失败记 `WECOM_USER_UNBOUND`。 +- 企微通知与库存排程**同一出口同一门禁**(`scheduler_service._notify_schedule_run_wecom`,2026-09-21 统一;2026-09-28 起附件改为 ZIP):收料 run 全部单元终态归集后**一次性**发送 textcard 汇总(`schedule_completed` 事件)+ **一个**原始收料包 `收料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-receipt-rpa`),可选参数 `source_codes` 留空则执行全部已启用站点中已配置收料的站点,按需配置 Cron 与接收人。收料排程与库存排程相互独立(站点、Cron、接收人分别选择)。收料触发前**没有**库存那套 Worker 在线 fail-fast 检查:Worker 停止只会让单元等待到 `FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS` 超时回收,因此上线后应按 `1.9.4` 验收并保留 `data\freight_rpa\receipt\logs\worker.log` 巡检。 #### 1.9.4 端到端验证 -1. 管理端「货代管理 → 库存站点」抽屉为目标站点配置收料卡(与库存同构):DBS 必须在查询条件中维护 Warehouse 条件(支持多值,每个 Warehouse 展开一个单元);报表日期不得出现在查询条件中。Crane 固定 `Inbound Details`,拒绝查询条件。收料无独立开关,站点启用即参与收料排程。 +1. 管理端「货代管理 → 库存站点」抽屉为目标站点配置收料卡(与库存同构):DBS 的 Warehouse 条件可选(支持多值,每个 Warehouse 展开一个单元;未填则不派生执行单元);报表日期不得出现在查询条件中。Crane 固定 `Inbound Details`,拒绝查询条件。收料无独立开关,站点启用即参与收料排程。 2. 链路演练(不依赖真实货代网站):以 `-Mock` 启动收料 Worker → 排程管理手工执行一次「货代收料 RPA」→ 确认回调、MinIO 归档、企微投递全链路成功后停止 Mock Worker。 3. 真实链路:启动真实收料 Worker 并触发排程,依次确认: - `ls /mnt/hxops-rpa-test-data/freight_rpa/receipt/triggers` 出现 `receipt_export_batch_{run_no}.json`; @@ -3432,13 +3434,12 @@ API 层 - Source 使用 `warehouse_resolution_mode`:`fixed` 直接给出 Warehouse;`inventory_match`(Crane)不预维护 Warehouse 清单。 - 外部系统仓库映射保存在 `shipping_inventory_external_mappings`:货代仓库(`freight_warehouse_id`)为可选维度——`inventory_match` 源按「收料文件仓库列 == 货代仓库」匹配映射行,空值即「空库位」默认映射行;在途仓编码(`in_transit_warehouse_code`)为在途调拨拨出库位来源(保存端必填)。发货链路仍按精确 `source + warehouse` 优先、随后回退 Source 默认映射查询;调拨链路(拨出库位)口径见 docs/features/in-transit-transfer/technical.md §1。 -### 6.2 库存站点测试与自动启用 +### 6.2 库存站点启用与可选测试 -- 管理端在停用站点表单直接选择 published 解析方案,和其他站点字段一起通过“保存更改”提交;不要求填写绑定原因,不提供单站点的二次绑定或确认按钮。 -- RPA 配置测试回调只在当前绑定方案为本次文件的 `exact`/`compatible` 候选时,写入 `current_profile_verified` 证据;候选为其他方案时只提示管理员在表单选择、保存并重新测试,绝不自动替换绑定。 -- 对于当前绑定 published 方案,非空测试验证成功或空库存查询成功后,`inventory_configuration_test.report_test_export` 在同一事务调用 `shipping_inventory_service.activate_source_if_ready`。该函数复用 `get_source_activation_status`,仅当连接、解析方案、发货模板、模板字段契约及当前版本测试证据全部通过时设置 `source.enabled=True`。 -- 自动启用不放宽任何门禁:缺少发货模板、模板字段不兼容、配置/连接版本已变更时均保持停用;外部仓库映射和首次非空文件的数据行验证仍属于后续流程,不阻断站点启用。Dify 无需修改配置。 -- **停用后再启用**:停用后若 `activation.ready` 仍为真,管理端显示“启用库存站点”并调用既有 `POST /sources/{id}/activate`(与自动启用同一门禁);表单有未保存修改时禁用该按钮。也可再次测试导出以触发 `activate_source_if_ready`。 +- 管理端在站点表单直接选择 published 解析方案,和其他站点字段一起通过“保存更改”提交;已启用站点也可更换解析绑定(仍校验已发布方案与发货模板字段契约)。 +- 启用硬门槛仅为:可用连接、已发布库存解析方案、已绑定已发布发货模板及模板字段契约。测试导出不再参与启用门禁,也不再自动启用站点。 +- 管理端抽屉以即时开关调用 `POST /sources/{id}/activate` 与 `POST /sources/{id}/deactivate`(停用经确认);表单有未保存修改时禁用开关。 +- 批量测试导出仍可作为可选运维工具保留;RPA 配置测试回调只写入验证证据,不创建生产快照、不自动切换 `enabled`。 ### 6.3 快照复用规则 @@ -3455,7 +3456,7 @@ API 层 - **按需单票**:`write_inventory_export_trigger_for_task`;batch 开启时包装为单源 batch trigger(与定时共用 worker 路径) - **单票 legacy 路径**:`_download_dsv360_inventory` / `_download_crane_inventory` 已委托 `_export_*_inventory_source`,与批量共用 `parameters` 填充 - **multi_select**:worker `_fill_dsv_multi_select` 支持多选控件(非仅取第一个值) -- **报表控件模板**(2026-08-26):同一参数名在不同报表的 SSRS 控件长相不同(`On Hand Inventory By Location 3lv` 的 Warehouse 是原生 select `ddValue`,JDA 版 `On Hand Inventory by Location` 是 txtValue/toggle/divDropDown 多选框下拉)。控件差异由 Worker 按归一化报表名登记在 `dsv_report_parameters._DSV_REPORT_PARAM_TEMPLATES`,填参时把 `report_name` 透传到模块解析;`selector_env/selectors` 继续不进入数据库,未登记报表回退参数名默认值。填参失败会输出参数区控件探针日志(`[dsv-filter] ... control probe`),便于定位控件 ID/类型漂移。 +- **报表控件模板**(2026-08-26,2026-09-28 修订):同一参数名在不同报表/站点的 SSRS 控件长相不同(`On Hand Inventory By Location 3lv` 的 Warehouse 是原生 select `ddValue`,JDA 版 `On Hand Inventory by Location` 是 txtValue/toggle/divDropDown 多选框下拉;收料 `Receipt Detail` 在 AWSBI 为 ctl27 select,在 AWSRTM/Moerdijk 为 ctl29 multi_value)。控件差异由 Worker 登记在 `dsv_report_parameters._DSV_REPORT_PARAM_TEMPLATES`;同名报表可用 `报表名@program_label` 覆盖(如 `receipt detail@awsrtm`)。填参时透传 `report_name` + `program_label`;`selector_env/selectors` 继续不进入数据库,未登记报表回退参数名默认值。填参失败会输出参数区控件探针日志(`[dsv-filter] ... control probe`),便于定位控件 ID/类型漂移。 - Worker:`scripts/freight_rpa/inventory/inventory_rpa_worker.py` → `_handle_inventory_batch_trigger` - **DOM 假空兜底**(2026-09-09):`result_ready` 后 DOM 明细行探测仅作加速;无行时重试一次 View Report,仍无行则继续 Excel 导出。真空只在落盘 Excel「有 Supplier ID/AWS Sku 表头但无明细」时记 `NoInventoryDataError`/`no_inventory_data`,避免 Salt Lake 等慢报表假 skip。 - 回调:`POST /api/shipping-notice/rpa/inventory-batch-ready` @@ -3463,8 +3464,9 @@ API 层 - **单票身份与失败收口**(2026-08-20):首次自动库存准备和用户重试均必须经 `ensure_all_required_sources_prepared` 创建逐源 Attempt;禁止写缺少 `source_run_no / lease_token / candidate_set_id / execution_id / gate_id` 的旧 task 级 trigger。Worker 发现 `trigger_identity_invalid` 时必须在 `results[]` 回传可用的 source 身份片段;后端按已定位的 Attempt 立即标记失败、同步 PreparationSourceAttempt、`inventory_preparation` Gate 与 `step3_inventory_prepare=needs_human`,不得等待库存轮询超时。 - 定时排程:`schedule_type=platform_job`,`platform_api_path=shipping-inventory-rpa`,`data_source_type=null`;建议 cron `0 3 * * *`(Asia/Shanghai) - 排程语义:`data_source_type` 仅用于 `schedule_type=data_pipeline`(`database` | `external_api`);平台任务通过 Job Registry 注册,由 `platform_api_path` 引用 job key -- **排程完成企微通知门禁**(`_notify_schedule_run_wecom`,2026-08-26 排障确认;2026-09-21 起收料排程并入同一出口,门禁/审计/`wecom_notified` 记账完全一致,仅附件不同——库存附 Excel+原始库存包、收料附该 run 全部收料文件):finalize 成功后按序检查 ① `response_summary_json.domain_notification_managed`(领域自管时跳过)→ ② `WECOM_NOTIFY_ENABLED`(默认 true,被本地 `.env.local` 覆盖为 false 会静默拦截并写 `schedule_runs.wecom_notify_error='WECOM_NOTIFY_ENABLED=false'`)→ ③ `schedule_completed` ∈ `WECOM_NOTIFY_EVENTS`(本地覆盖列表漏掉它时同样拦截)→ ④ 任务 `notify_enabled` 且 `notify_user_ids_json` 非空 → ⑤ 用户已绑 `wecom_userid`。任一环节不满足都不发消息;排障先查 `schedule_runs.wecom_notified / wecom_notify_error`,再对 `app_settings`(DB 权威源)与 `.env.` 的合并结果核对 ②③(DB 优先于 env 文件)。 +- **排程完成企微通知门禁**(`_notify_schedule_run_wecom`,2026-08-26 排障确认;2026-09-21 起收料排程并入同一出口,门禁/审计/`wecom_notified` 记账完全一致;2026-09-28 起收料附件改为原始 ZIP 单包):finalize 成功后按序检查 ① `response_summary_json.domain_notification_managed`(领域自管时跳过)→ ② `WECOM_NOTIFY_ENABLED`(默认 true,被本地 `.env.local` 覆盖为 false 会静默拦截并写 `schedule_runs.wecom_notify_error='WECOM_NOTIFY_ENABLED=false'`)→ ③ `schedule_completed` ∈ `WECOM_NOTIFY_EVENTS`(本地覆盖列表漏掉它时同样拦截)→ ④ 任务 `notify_enabled` 且 `notify_user_ids_json` 非空 → ⑤ 用户已绑 `wecom_userid`。任一环节不满足都不发消息;排障先查 `schedule_runs.wecom_notified / wecom_notify_error`,再对 `app_settings`(DB 权威源)与 `.env.` 的合并结果核对 ②③(DB 优先于 env 文件)。附件差异:库存附 Excel+原始库存包;收料附原始收料包(`收料RPA-…-收料.zip`)。 - **库存 RPA 企微/下载文件名**(2026-09-09):展示名统一为 `库存RPA-{yyyyMMdd}-{HHmm}-结果.xlsx` 与 `库存RPA-{yyyyMMdd}-{HHmm}-库存.zip`(`HHmm` 按任务 `schedule_timezone`,缺省 Asia/Shanghai,勿直接用 UTC/`run_no` 内嵌时刻);完整 `run_no` 只留在 textcard 与磁盘归档键 `{run_no}.zip`。ZIP 包内条目为 `{序号}_{source_code}.xlsx`(无 source_code 时回退仓码);`warehouse_id` / `inventory_file_no` 仅写入 `manifest.json`。 +- **收料 RPA 企微/下载文件名**(2026-09-28):Worker 落盘 `receipt_{batch_run_no}_{source_code}_{warehouse_or_NA}_{stamp}.xlsx`;finalize 预生成 ZIP,企微/管理端下载展示名 `收料RPA-{yyyyMMdd}-{HHmm}-收料.zip`;包内 `{序号}_{source_code}.xlsx` + `manifest.json`;归档目录 `FREIGHT_RPA_RECEIPT_ARCHIVE_DIR`(默认 `freight_rpa/receipt/archives`);管理端 `GET /schedule-runs//receipt-raw-zip`。 - **空快照状态约束**(2026-08-26):`create_empty_rpa_inventory_snapshot` 写入 `snapshot_status='empty'`(no_inventory_data 审计快照),依赖迁移 `hq0r1s2t3u4v` 把 `ck_shipping_inventory_files_snapshot_status` 检查约束从 `('ready','failed','expired')` 放宽为含 `'empty'`;未执行该迁移(或回退版本)时,批量回调插入空快照会触发 CheckViolation 导致整笔 Job 事务回滚、ScheduleRun 停在 awaiting 后被超时回收为 failed。 ### 6.5 审计字段 @@ -3734,9 +3736,9 @@ Case 状态:`unreviewed`、`draft`、`ready`、`confirming`、`confirmed`、`n - 嵌套标注采用固定语义层级:明细字段高于物理行容器,表头只展示列级字段,不显示内部表头行容器。物理行内部不吞掉字段点击,管理员通过物理行标签、边缘或已选中的缩放手柄操作父区域。 # 独立收料报表 RPA -收料不进入库存快照、匹配或 ERP 链路,也没有独立启停字段:是否运行统一由库存站点 `enabled` 与配置是否存在决定。站点的一对一 `ShippingReceiptReportConfig` 保存收料路径与受控查询条件(Warehouse 条件即逐仓拆分维度,不单独持久化仓库清单);`ShippingReceiptRpaUnitRun` 保存每次冻结单元与重试关系(按需触发无排程时 `schedule_run_id` 为 NULL);`ShippingReceiptReportFile` 保存原样对象、SHA-256、到期和删除事实;`ShippingReceiptNotificationDelivery` 保存管理员重发通道的投递幂等事实(正常通知自 2026-09-21 起走通用排程出口,由 `schedule_runs.wecom_notified` 记账)。 +收料不进入库存快照、匹配或 ERP 链路,也没有独立启停字段:是否运行统一由库存站点 `enabled` 与配置是否存在决定。站点的一对一 `ShippingReceiptReportConfig` 保存收料路径与受控查询条件;`ShippingReceiptRpaUnitRun` 保存每次冻结单元与重试关系(按需触发无排程时 `schedule_run_id` 为 NULL);`ShippingReceiptReportFile` 保存原样对象、SHA-256、到期和删除事实;`ShippingReceiptNotificationDelivery` 保存管理员重发通道的投递幂等事实(正常通知自 2026-09-21 起走通用排程出口,由 `schedule_runs.wecom_notified` 记账)。 -DBS 每个 Warehouse 单独导出且不填报表日期。**Warehouse 即逐仓拆分维度,配置与库存完全同构**:仓库维护在查询条件的 Warehouse 条件里(支持多值,逗号分隔),不单独持久化仓库清单;排程/按需触发时由后端运行时从该条件派生仓库清单(`receipt_rpa.receipt_warehouse_values`),一仓展开一个执行单元、一个归档文件,并把单元快照中的 Warehouse 条件剥离(`receipt_rpa.receipt_unit_parameters`)——收料 Worker(`receipt_dbs_export.py`)执行时再把当前 `warehouse_id` 作为必填单值条件自动追加,单元快照若保留该条件会重复冲突。校验要求 DBS 收料配置恰一条非空 Warehouse 条件(`shipping_inventory_service._validate_receipt_report_config`)。报表日期固定不筛选同理属于受控边界:跨日排程不筛日期,避免管理端误传日期导致导出漏数。Crane 固定 `Inbound Details`,按本次唯一 Description 等待并下载匹配项,禁止取“最新历史报表”。重试创建新的单元并以 `retry_of_id` 关联旧失败单元,绝不覆盖历史。库存 Worker 与收料 Worker 可在不同专用目录下并行运行,但首版不复用跨排程登录会话。 +DBS/Crane 收料排程与库存 RPA 同口径:**选中 N 个库存源 → N 个执行单元**,`query_parameters_json` 原样下发。Warehouse 等查询条件仅为可选报表筛选,**不作为是否产出单元的门禁**,也不再按仓拆分单元;空条件表示 Worker 使用页面默认(不填 Warehouse)。收料 Worker(`receipt_dbs_export.py`)仅在历史 trigger 仍带 `warehouse_id` 时追加单值 Warehouse 以兼容旧载荷。报表日期固定不筛选:跨日排程不筛日期,避免管理端误传日期导致导出漏数。Crane 固定 `Inbound Details`,按本次唯一 Description 等待并下载匹配项,禁止取“最新历史报表”;**不填写** Owner/Project/Warehouse 等页面查询条件。重试创建新的单元并以 `retry_of_id` 关联旧失败单元,绝不覆盖历史。库存 Worker 与收料 Worker 可在不同专用目录下并行运行。收料浏览器会话默认复用且按 connector+profile 分目录;需要每次全新登录时传 `-NoSessionReuse`。 ### 可靠性、补偿与审计边界 @@ -3756,8 +3758,8 @@ DBS 每个 Warehouse 单独导出且不填报表日期。**Warehouse 即逐仓 | 接口 | 权限 | 关键请求/响应约束 | 审计 | | --- | --- | --- | --- | -| `GET /api/admin/shipping-notice/sources/{source_id}/receipt-report-config` | 管理员 | 返回独立收料路径与查询条件(含 Warehouse 拆分条件);不返回凭据 | 配置读取沿用管理端访问链路 | -| `PUT /api/admin/shipping-notice/sources/{source_id}/receipt-report-config` | 管理员 | body 仅 `report_path_json/query_parameters_json`;DBS 必须恰一条非空 Warehouse 条件;日期/selector 拒绝;Crane 固定 `Inbound Details`,拒绝全部查询条件;Worker 无论 Profile 登录 URL 的原 hash,均强制进入 `#/inbound-details-query` 并使用页面默认条件执行 | `shipping_receipt_report_config_saved`,含前后快照 | +| `GET /api/admin/shipping-notice/sources/{source_id}/receipt-report-config` | 管理员 | 返回独立收料路径与查询条件;不返回凭据 | 配置读取沿用管理端访问链路 | +| `PUT /api/admin/shipping-notice/sources/{source_id}/receipt-report-config` | 管理员 | body 仅 `report_path_json/query_parameters_json`;DBS 查询条件可选(空=页面默认,不作为单元门禁);日期/selector 拒绝;Crane 固定 `Inbound Details`,拒绝全部查询条件;Worker 无论 Profile 登录 URL 的原 hash,均强制进入 `#/inbound-details-query` 并使用页面默认条件执行 | `shipping_receipt_report_config_saved`,含前后快照 | | `POST /api/shipping-notice/rpa/receipt-batch-ready` | 收料 Worker | 仅 `shipping_receipt_rpa.v1`;`file_path` 必须在 receipt drop 根且为 `.xlsx`;校验大小、SHA-256 | 归档、通知、排程终态均保留事实 | | `GET /api/workspace/receipt-report-files` | 管理员或排程接收人 | 当前用户授权过滤后再应用 `limit`;不泄露对象存储定位 | `shipping_receipt_report_files_listed` | | `GET /api/workspace/receipt-report-files/{file_id}/download` | 管理员或对应接收人 | 原样下载;过期对象或无权限拒绝 | 成功/拒绝均记录下载审计 | diff --git a/docs/funclist.md b/docs/funclist.md index 74fb936f..e819ef16 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -758,16 +758,16 @@ | 功能项 | 状态 | 说明 | | --- | --- | --- | | 领域模型/状态机/DTO/审计/迁移 | 后端已实现 | backend/app/models/in_transit_transfer.py(Run/SourceJob/Matching/InvoiceItem/Attempt/AuditEvent/Archive)+ 迁移 it1a2b3c4d5e / rn1a2b3c4d5e6(precheck→match 术语改名);13 状态服务端门禁(services/in_transit_transfer/status.py) | -| 收料文件准备与只读匹配(原"预检") | 后端已实现 | 收料文件落地即同步待办行(RPA 回调桥 → evidence_sync 三分类写入:新行待查/证据变化刷新重置/消失行出清);匹配=证据对齐兜底(align_scope_rows,sha 一致直通零解析)+ 按组织批量查库存 + 严格数量比对;缺文件按来源触发收料 RPA/来源隔离/字段校验/D+1/Invoice 多行汇总+原始行追溯/匹配快照 Hash/进度恢复 | +| 收料文件准备与只读匹配(原"预检") | 后端已实现 | 收料文件落地即同步待办行(RPA 回调桥 → evidence_sync 三分类写入:新行待查/证据变化刷新重置/缺席行存续只换戳);匹配=证据对齐兜底(align_scope_rows,sha 一致直通零解析)+ 按组织批量查库存 + 严格数量比对;缺文件按来源触发收料 RPA/来源隔离/字段校验/T+lag 成熟(默认 T+2)/Invoice 多行汇总+原始行追溯/匹配快照 Hash/进度恢复 | | 可调拨清单勾选与 ERP 原子调拨 | 后端已实现 | 可调拨明细队列勾选按行提交执行 Run/写前复查/Invoice 幂等/duplicate_success/result_unknown 隔离/单项失败不阻断/按票聚合结果(写路径已接线,见下行「ERP 建单写路径」) | | 排程/恢复/异常/通知 | 后端已实现 | 08:00 收料文件与 09:00 自动调拨 platform job;待处理池 3/5/7 天老化;人工重试/关闭;七 Sheet 异常 Excel;每非空 Run 一条企微通知(失败不改 ERP 结果) | | 调拨业务类型 | 后端已实现(类型2/3占位) | 三类型:在途仓至HUB仓(一期开放,仅纳入 INVOICE 前缀 HOM/HOX/WTP 的票)/HUB仓维修出(占位,规则 ODM ID=HoxinRMA 待文件层支持 odm_id)/HUB仓间调拨(占位);类型随 Run 落库并入匹配 Hash,占位类型 fail-closed;前端来源选择卡选择(占位类型禁用) | | 生产硬化 | 后端已实现 | MinIO 归档+Hash 复核;Worker 崩溃/陈旧执行恢复;运营指标;越权 403;下载访问审计;性能测试;运维手册 docs/features/in-transit-transfer/technical.md | | 可调拨明细与待办看板首页 | 已实现 | 首页上区「库存匹配」动作卡 + 待办看板四队列:可调拨明细(GET /items/executable 全局可执行行,勾选按行生成调拨单)/待恢复异常/已人工关闭/结果未知;「最近匹配」(原"最近预检")已移除(行不迁移后匹配卡=范围实时视图,多份同 scope 匹配属重复窗口) | -| 待处理池批量操作与恢复处理 | 已实现 | 批量重查(恢复处理=行级重查原地刷新+续新鲜度,重查前证据对齐兜底)/批量关闭;blocked_file_removed 消失行 fail-closed 入异常池;匹配=评估留痕,行不迁移 | +| 待处理池批量操作与恢复处理 | 已实现 | 批量重查(恢复处理=行级重查原地刷新+续新鲜度,重查前证据对齐兜底)/批量关闭;blocked_file_removed 仅历史残留防御(2026-09-28 起不再新产生);匹配=评估留痕,行不迁移 | | 按行执行与执行门禁 | 已实现 | execute(item_ids) **202 异步**:API 两道门禁(存在可执行 + 文件版本对账,fail-closed)通过即建 queued Run + 五元组分组建票 + 一次入队,worker 逐票执行(文件对账复核 + 写前路由/库存复查——库存复查仅全量重跑路径,final_only 续跑不复查);Run 留痕不绑匹配;进度/结果无状态回读(GET /runs 轮询票清单);行级新鲜度 TTL 门禁与 ITEMS_STALE 错误码退役,TTL 降为 stale 徽标展示阈值(2026-09-25 定稿,见 features/in-transit-transfer/technical.md §6.3) | | ERP 建单写路径(票级顺序引擎,2026-09-24) | 已实现 | 写路径经集成连接器统一出口:`database` 连接器(oracle/mysql/sqlserver/postgresql 四库直连,SQL 接口 identifiers 白名单替换)+ `create_transfer` 绑定一对多有序步骤(steps_json:写 ERP 中间表 → 触发 WS);顺序引擎四规则(resume 跳过非末步/非末步失败即中止/末步映射+裁决钩子/末步超时 result_unknown);融合卡「票清单=进度=结果」、result_unknown retrigger(D11 唯一出口,禁关闭重建)、失败票人工关票(D18 行脱离回可执行)、首页「已执行」票维护区块;管理端配置配方/SOP/UAT 确认项/已知限制统一见 [features/in-transit-transfer/technical.md](features/in-transit-transfer/technical.md) §10(含 SOP 红线 §10.8;交付说明:新增依赖 pymysql/pymssql,psycopg2-binary 既有;本期零新增环境变量) | -| 收料日期默认与输入期限制 | 已实现 | 来源选择卡收料日期默认 D+1 规则日期(上海业务日 T-1);日期输入 max/min 即时限制 + 起止非法行内提示禁用确认(后端 RECEIPT_DATE_RANGE_INVALID 卡控保留双保险);「直接生成调拨单」改名「生成调拨单」 | +| 收料日期默认与输入期限制 | 已实现 | 来源选择卡收料日期默认 T+lag 成熟规则(默认业务日 T-2,可配 IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS);日期输入 max/min 即时限制 + 起止非法行内提示禁用确认(后端 RECEIPT_DATE_RANGE_INVALID 卡控保留双保险);「直接生成调拨单」改名「生成调拨单」 | | 前端 Chat 卡片/结果页与四语言 | 已实现 | `frontend/src/features/chat/` 卡片(文件进度/匹配/结果/待处理)与 admin 模块已按计划实施(结果=融合卡:202 提交后 4s 轮询票清单至严格终态) | --- diff --git a/docs/superpowers/plans/2026-09-28-in-transit-absence-survivorship-t2.md b/docs/superpowers/plans/2026-09-28-in-transit-absence-survivorship-t2.md new file mode 100644 index 00000000..e950b42f --- /dev/null +++ b/docs/superpowers/plans/2026-09-28-in-transit-absence-survivorship-t2.md @@ -0,0 +1,797 @@ +# 在途调拨:缺席存续化 + 成熟规则 T+2 实施计划 + +> **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:** 取消在途调拨「不在最新收料文件中 → blocked_file_removed」的自动判删(改为存续:换戳保留状态),并把成熟规则从 T+1 升级为可配置的 T+2(默认 2,前后端同口径),同时修复存量误标行。 + +**Architecture:** 后端日期策略集中在 `date_policy.py`(新增 `maturity_lag_days()`,app 配置优先、无上下文回退默认 2);`evidence_sync.py` STEP 4 由「缺席即失效」改为「缺席只换版本戳、状态原样保留」(保住对齐直通与执行门禁②两个消费方);存量误标行用一次性脚本恢复待查态;前端 `transferDate.ts` 镜像同口径 T-lag。无数据库 schema 变更(无需迁移)。 + +**Tech Stack:** Flask + SQLAlchemy 2.0 + pytest(pure_unit 标记);Vue 3 + TypeScript + vitest。 + +**Spec:** 本计划实现 2026-09-28 brainstorming 对话中获批准的有界设计(无独立 spec 文件);全部关键约束已固化在下节 Global Constraints。 + +## Global Constraints + +- **缺席 ≠ 删除(survivorship)**:收料 RPA 导出非全量,文件缺席不作为任何状态变更依据;真实删除唯一出口 = 人工关闭(待处理池 3/5/7 天老化兜底遗忘)。 +- **缺席行只换戳不改状态**:`raw_lines_json` 版本戳(`file_version`/`file_sha256`)换到最新文件 sha,`sheet`/`row_no` 保留;`status`/`result_code`/`result_message` 原样。否则①对齐入口 `align_scope_rows` 每次 full 重解析,②执行门禁②(`TRANSFER.FILE_CHANGED`)会把历史行永久拒绝执行。 +- **`RESULT_FILE_REMOVED` 常量与全部守卫保留**(`matching_service` 圈行过滤/invalid_count、`retry_service` 拒绝重查、前端徽标、i18n key):仅作历史残留数据防御,2026-09-28 起不再新产生。 +- **成熟规则**:`receipt ≤ T-lag → eligible`;`T-lag < receipt ≤ T → not_matured`;`receipt > T → future`。lag 默认 2,环境变量 `IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS`(放 `.env.shared`,跨环境一致;只新增整行,不改不删既有行)。 +- **前后端同口径**:前端 `eligibleReceiptDateTo` = T − 2,漂移会导致日期选择上限与后端 `TRANSFER.RECEIPT_DATE_RANGE_INVALID` 卡控不一致。 +- **13 状态冻结契约**:不新增状态值;待查态仍用 `status='matching' + result_code='pending_stock_check'`。 +- **注释纪律(AGENTS.md §5)**:改动模块的 docstring/注释必须同步更新(`date_policy`、`evidence_sync`、`matching_service`、`transferDate.ts`),禁止留下「D+1」「消失即失效」的过期描述。 +- **测试钉值纪律**:在途套件夹具按 T+1 语义构建(业务日 2026-08-06、收料 2026-08-05),套件级 conftest 把 lag 钉为 1;生产默认 2 的边界由专项用例显式设 `app.config[...]=2` 锁定,不允许被钉值掩盖。 +- **i18n 四语言**:`notMaturedCount` 文案同步改 zh-CN / zh-TW / en / th。 +- **无自动 commit**:每个任务以 `git add` 暂存结束,提交由用户批准后统一处理。 +- **测试命令**:后端 `cd backend && python -m pytest -v`(先按 AGENTS §4 激活 venv);前端 `cd frontend && npm run test:unit`、`npm run build`。 + +--- + +### Task 1: 成熟规则 T+lag 可配(date_policy + settings + 套件钉值) + +**Files:** +- Modify: `backend/app/services/in_transit_transfer/date_policy.py` +- Modify: `backend/app/core/config/settings.py:295`(`IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET` 之后插入) +- Modify: `.env.shared:240`(`IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS=7` 之后插入) +- Modify: `backend/tests/services/in_transit_transfer/test_date_policy.py` +- Modify: `backend/tests/services/in_transit_transfer/conftest.py`(`_stub_doc_sequence` 之后加 autouse 钉值 fixture) +- Modify: `backend/tests/services/in_transit_transfer/test_matching_service.py`(新增边界用例 + range 用例注释) + +**Interfaces:** +- Consumes: 无(本任务自包含)。 +- Produces: `date_policy.maturity_lag_days() -> int`;`maturity_status(receipt_date, business_date, lag_days: int | None = None) -> str`;`eligible_receipt_date_to(business_date, lag_days: int | None = None) -> date`;settings 键 `IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS`(Task 2/4 消费默认口径,Task 4 前端硬编码同一默认 2)。 + +- [ ] **Step 1: 重写 test_date_policy.py 的成熟度用例(先写失败测试)** + +替换 `test_yesterday_receipt_is_eligible`、`test_maturity_status_accepts_iso_strings`、`test_eligible_receipt_date_to_is_previous_day`,新增显式 lag 用例(其余用例不动)。模块 docstring 的「D+1」改为「T+lag(默认 T+2)」: + +```python +def test_yesterday_receipt_is_not_matured(): + """T+2 默认:昨天(T-1)收料尚未成熟(海外时差:28 号最早处理 26 号)。""" + assert maturity_status(date(2026, 8, 5), BUSINESS_T) == "not_matured" + + +def test_t_minus_2_receipt_is_eligible(): + """T+2 默认:前天(T-2)收料起可预检(纯单元无 app 上下文 → 回退默认 lag=2)。""" + assert maturity_status(date(2026, 8, 4), BUSINESS_T) == "eligible" + + +def test_maturity_status_accepts_iso_strings(): + """字符串日期与 date 对象等价。""" + assert maturity_status("2026-08-04", "2026-08-06") == "eligible" + assert maturity_status("2026-08-05", "2026-08-06") == "not_matured" + assert maturity_status("2026-08-06", "2026-08-06") == "not_matured" + + +def test_explicit_lag_days_overrides_default(): + """显式 lag=1 复现旧 T+1 口径(兼容回滚与测试钉值场景)。""" + assert maturity_status(date(2026, 8, 5), BUSINESS_T, lag_days=1) == "eligible" + assert maturity_status(date(2026, 8, 6), BUSINESS_T, lag_days=1) == "not_matured" + + +def test_eligible_receipt_date_to_is_t_minus_two(): + """可调拨收料截止日期 = 业务日期 - 2 天(默认 lag)。""" + assert eligible_receipt_date_to(BUSINESS_T) == date(2026, 8, 4) + + +def test_eligible_receipt_date_to_explicit_lag(): + """显式 lag=1 时截止 = 业务日期 - 1 天。""" + assert eligible_receipt_date_to(BUSINESS_T, lag_days=1) == date(2026, 8, 5) +``` + +- [ ] **Step 2: 运行确认失败** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_date_policy.py -v` +Expected: FAIL(`test_yesterday_receipt_is_eligible` 等按 T+1 断言的用例失败;`lag_days` 参数不存在报 TypeError) + +- [ ] **Step 3: 实现 date_policy.py** + +模块 docstring 第 3-4 行改为「实现 T+lag 成熟规则(默认 T+2:收料日期 ≤ T-2 可匹配,T-1/当天 not_matured,未来日期阻断)」;`MATURITY_FUTURE` 常量后新增默认值常量与读取函数;替换两个策略函数: + +```python +# 成熟滞后天数默认值(T+2:收料日期 ≤ T-2 才可匹配;与海外的时差余量)。 +# 可经环境变量 IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS 覆盖(settings 装载)。 +DEFAULT_MATURITY_LAG_DAYS = 2 + + +def maturity_lag_days() -> int: + """读取成熟滞后天数(app 配置优先,缺省回退 DEFAULT_MATURITY_LAG_DAYS)。 + + Returns: + 成熟滞后天数 lag;无 Flask app 上下文(纯单元测试/脚本)时回退默认值, + 保持策略函数可纯调用。 + """ + try: + from flask import current_app + return int(current_app.config.get( + "IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS") or DEFAULT_MATURITY_LAG_DAYS) + except RuntimeError: # 无 app 上下文 + return DEFAULT_MATURITY_LAG_DAYS + + +def maturity_status(receipt_date: date | str, business_date: date | str, + lag_days: int | None = None) -> str: + """按 T+lag 规则判定收料日期成熟度(默认 lag=2)。 + + Args: + receipt_date: 收料日期。 + business_date: 当前业务日期 T。 + lag_days: 显式滞后天数;None 时读 maturity_lag_days()。 + Returns: + 'eligible'(receipt ≤ T-lag)、'not_matured'(T-lag < receipt ≤ T)或 + 'future'(receipt > T,结构化阻断)。 + """ + receipt = parse_date(receipt_date) + business = parse_date(business_date) + lag = maturity_lag_days() if lag_days is None else int(lag_days) + if receipt > business: + return MATURITY_FUTURE + if receipt > business - timedelta(days=lag): + return MATURITY_NOT_MATURED + return MATURITY_ELIGIBLE + + +def eligible_receipt_date_to(business_date: date | str, lag_days: int | None = None) -> date: + """返回可进入匹配的收料截止日期(业务日期 T - lag 天,默认 T-2)。 + + Args: + business_date: 当前业务日期。 + lag_days: 显式滞后天数;None 时读 maturity_lag_days()。 + Returns: + T - lag 天。 + """ + lag = maturity_lag_days() if lag_days is None else int(lag_days) + return parse_date(business_date) - timedelta(days=lag) +``` + +- [ ] **Step 4: settings.py + .env.shared 增加变量** + +`backend/app/core/config/settings.py` 在 `IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET = ...`(约 295 行)之后插入: + +```python + IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS = int( + os.getenv('IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS', '2') or '2' + ) +``` + +`.env.shared` 在 `IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS=7`(约 240 行)之后插入(红线:只新增完整行): + +``` +IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS=2 +``` + +- [ ] **Step 5: 套件级钉值 fixture(保住存量夹具语义)** + +`backend/tests/services/in_transit_transfer/conftest.py` 在 `_stub_doc_sequence` fixture 之后新增: + +```python +@pytest.fixture(autouse=True) +def _pin_maturity_lag_legacy(request): + """在途套件钉成熟滞后=1(T+1)。 + + 用途:存量夹具生态按 T+1 语义构建(fixed_clock 业务日 2026-08-06、收料日期 + 2026-08-05=T-1);生产默认 T+2(settings IN_TRANSIT_TRANSFER_MATURITY_ + LAG_DAYS=2)的边界行为由 test_matching_service / test_date_policy 专项 + 用例显式覆盖,不被本钉值掩盖。 + 逻辑:仅对已请求 app 的用例钉值(request.fixturenames 判定),pure_unit 用例 + (如 test_date_policy)不触碰 Flask,继续走 date_policy 的无上下文回退。 + """ + if "app" in getattr(request, "fixturenames", []): + app = request.getfixturevalue("app") + app.config["IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS"] = 1 +``` + +- [ ] **Step 6: test_matching_service.py 新增生产默认边界用例 + 修正 range 用例注释** + +文件 import 区补 `from app import db` 与 `from app.models import TransferInvoiceItem`,新增用例: + +```python +def test_t_plus_2_default_boundary_yesterday_not_matured(app, dbs_ready_file): + """生产默认 lag=2 边界:昨天(T-1)收料 not_matured,改到 T-2 后可预检。 + + [断言意图] 套件 conftest 把 lag 钉为 1(存量夹具语义);本用例显式恢复生产 + 默认 2,锁定真实默认口径不被钉值掩盖(海外时差:28 号最早处理 26 号)。 + """ + deps, erp, _ = _deps(dbs_ready_file) + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") + erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") + seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") + app.config["IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS"] = 2 # 覆盖套件钉值,锁生产默认 + + result = run_matching( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + ) + # [断言意图] 夹具行收料 2026-08-05(T-1):默认 lag=2 下全部未成熟,零 ERP 调用。 + assert result.summary.counts.not_matured_count == 2 + assert result.summary.counts.executable_count == 0 + assert_erp_calls(erp, 0) + + # [边界] 收料日期改到 T-2(2026-08-04)后即可进入匹配并严格匹配成功。 + for row in TransferInvoiceItem.query.filter_by(source_code="DBS-AWSBI").all(): + row.receipt_date = "2026-08-04" + db.session.flush() + result2 = run_matching( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + ) + assert result2.summary.counts.executable_count == 2 +``` + +`test_receipt_date_range_end_beyond_d1_rejected` 的 docstring「D+1 规则(业务日期-1)」改为「成熟规则(业务日期-lag,套件钉值 lag=1)」(断言不变:`2026-08-06 > 08-05` 截止仍拒绝)。同时把文件 docstring 第 3 行「D+1 过滤」改为「T+lag 成熟过滤(套件钉 lag=1)」。 + +- [ ] **Step 7: 运行在途全文件夹测试确认全绿** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/ -v` +Expected: PASS(钉值 fixture 生效,存量用例语义不变;新增用例锁定 T+2) + +- [ ] **Step 8: 暂存** + +```bash +git add backend/app/services/in_transit_transfer/date_policy.py backend/app/core/config/settings.py .env.shared backend/tests/services/in_transit_transfer/test_date_policy.py backend/tests/services/in_transit_transfer/conftest.py backend/tests/services/in_transit_transfer/test_matching_service.py +``` + +--- + +### Task 2: evidence_sync 缺席存续化(取消自动判删) + +**Files:** +- Modify: `backend/app/services/in_transit_transfer/evidence_sync.py` +- Modify: `backend/tests/services/in_transit_transfer/test_evidence_sync.py` + +**Interfaces:** +- Consumes: Task 1 无直接依赖(独立);`matching_service.RESULT_FILE_REMOVED` 导入**保留**(STEP 2 历史残留行复现防御仍在用)。 +- Produces: `SyncOutcome.absent_kept: int`(替代 `removed` 字段;审计事件 `TRANSFER_EVIDENCE_SYNCED` 与桥日志同步更名)——Task 3 测试断言前置状态仍经 `sync_source_rows` 构造,不依赖该字段。 + +- [ ] **Step 1: 重写 test_evidence_sync.py 的缺席相关用例(先写失败测试)** + +模块 docstring 第 4 行「消失行失效」改为「缺席行存续(只换戳不改状态)」。替换三个用例、新增一个防御用例,并把 `test_sync_inserts_pending_rows_without_erp` 中 `outcome.removed == 0` 改为 `outcome.absent_kept == 0`: + +```python +def test_sync_keeps_absent_rows_and_never_touches_terminal(app, dbs_ready_file): + # [断言意图] 新版文件缺席的行 → 存续:状态/结果码原样保留,只换版本戳; + # 终态行保持既定事实。(收料 RPA 非全量导出:缺席≠删除,2026-09-28 语义) + deps, _, _ = make_transfer_deps(dbs_ready_file) + sync_source_rows(source_code="DBS-AWSBI", deps=deps, + business_date="2026-08-06", now=NOW) + doomed = TransferInvoiceItem.query.filter_by(source_code="DBS-AWSBI").first() + doomed.status = "ready_to_execute" # 模拟上一版可执行 + db.session.flush() + terminal = TransferInvoiceItem( + matching_id=None, source_code="DBS-AWSBI", invoice_no="HOX-TERMINAL", + material_no="MAT-X", material_name="n", specification="", receipt_date="2026-09-19", + status="success", result_code=None, from_warehouse="W", to_warehouse="H", + receipt_quantity="1", lot_no="L", receipt_warehouse_code="W1", unit="PCS", + raw_lines_json=[], updated_at=NOW, + ) + db.session.add(terminal) + db.session.flush() + + deps2, _, _ = make_transfer_deps(dbs_ready_file) + # 换一版不含任何行的文件:经 Fake 仓库一次性覆盖注入空 rows(新 sha)。 + repo2 = deps2.file_repository + repo2.set_next_file(source_code="DBS-AWSBI", rows=(), checksum="e" * 64) + outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps2, + business_date="2026-08-06", now=NOW) + + assert outcome is not None and outcome.absent_kept == 2 # [断言意图] 两行缺席存续 + db.session.refresh(doomed) + assert doomed.status == "ready_to_execute" # [断言意图] 状态不被缺席改写 + assert doomed.result_code == SYNC_RESULT_PENDING # [断言意图] 结果码保留 + assert doomed.raw_lines_json[0]["file_sha256"] == "e" * 64 # [断言意图] 版本戳已换新 + db.session.refresh(terminal) + assert terminal.status == "success" # [断言意图] 终态行不复活 + + +def test_absent_rows_restamped_so_align_passes_through(app, dbs_ready_file, monkeypatch): + # [断言意图] 缺席行已换最新文件戳 → align 判据 row_shas == latest_sha 直通(None)。 + deps, _, _ = make_transfer_deps(dbs_ready_file) + sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW) + deps.file_repository.set_next_file(source_code="DBS-AWSBI", rows=(), checksum="e" * 64) + sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW) + + row = TransferInvoiceItem.query.filter_by( + source_code="DBS-AWSBI", invoice_no="HOX-002").first() + assert row.result_code == SYNC_RESULT_PENDING # [断言意图] 缺席不改结果码(存续) + assert row.raw_lines_json[0]["file_sha256"] == "e" * 64 # [断言意图] 缺席行已换新戳 + + # 文件状态投影返回空 files 版 sha(align 判据输入);测试注入替身避免触碰真实表。 + monkeypatch.setattr( + "app.services.in_transit_transfer.evidence_sync.resolve_source_file_status", + lambda *, source_code: {"file_status": "ready", "has_ready_file": True, + "file_no": "REC-E", "file_sha256": "e" * 64}, + ) + outcomes = align_scope_rows(source_codes=["DBS-AWSBI"], deps=deps, + business_date="2026-08-06", now=NOW) + assert outcomes["DBS-AWSBI"] is None # [断言意图] 已对齐:直通零解析 + + +def test_reappeared_absent_rows_refresh_without_reset(app, dbs_ready_file): + # [断言意图] 缺席存续行重新出现且证据未变 → refreshed(只换戳),状态保持待查。 + deps, _, _ = make_transfer_deps(dbs_ready_file) + sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW) + deps.file_repository.set_next_file(source_code="DBS-AWSBI", rows=(), checksum="e" * 64) + absent_outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps, + business_date="2026-08-06", now=NOW) + assert absent_outcome.absent_kept == 2 # [断言意图] 前置:两行缺席存续 + + deps.file_repository.set_next_file( + source_code="DBS-AWSBI", rows=tuple(dbs_ready_file["rows"]), checksum="a" * 64) + outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps, + business_date="2026-08-06", now=NOW) + + assert outcome.refreshed == 2 # [断言意图] 复现行走刷新分支 + assert outcome.reset_pending == 0 # [断言意图] 证据未变不重置 + row = TransferInvoiceItem.query.filter_by( + source_code="DBS-AWSBI", invoice_no="HOX-002").first() + assert row.status == "matching" # [断言意图] 状态保持待查 + assert row.result_code == SYNC_RESULT_PENDING + assert row.raw_lines_json[0]["file_sha256"] == "a" * 64 # [断言意图] 已换最新戳 + + +def test_historical_removed_row_restored_on_reappear(app, dbs_ready_file): + # [断言意图] 历史残留 blocked_file_removed 行复现 → 无条件恢复待查(防御路径, + # 2026-09-28 起不再新产生,但存量行修复前仍可能命中)。 + deps, _, _ = make_transfer_deps(dbs_ready_file) + sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW) + row = TransferInvoiceItem.query.filter_by( + source_code="DBS-AWSBI", invoice_no="HOX-002").first() + row.status = "blocked_recoverable" + row.result_code = "blocked_file_removed" + row.result_message = "receipt row removed from latest file" + db.session.flush() + + deps.file_repository.set_next_file( + source_code="DBS-AWSBI", rows=tuple(dbs_ready_file["rows"]), checksum="a" * 64) + outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps, + business_date="2026-08-06", now=NOW) + + db.session.refresh(row) + assert outcome.reset_pending >= 1 # [断言意图] 复现行计入重置口径 + assert row.status == "matching" # [断言意图] 脱离 blocked + assert row.result_code == SYNC_RESULT_PENDING + assert row.result_message is None # [断言意图] 删除解释清除 +``` + +- [ ] **Step 2: 运行确认失败** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_evidence_sync.py -v` +Expected: FAIL(`absent_kept` 属性不存在;旧行为把缺席行打成 blocked) + +- [ ] **Step 3: 实现 evidence_sync.py** + +① 模块 docstring(第 7-15 行)三分类描述改为:插入待查行 / 幂等跳过 / 刷新或重置 / **缺席存续(只换版本戳到最新文件 sha,状态与结果码原样保留——收料 RPA 非全量导出,缺席≠删除;行复现时经 STEP 2 正常刷新)**;终态不触碰、历史 `blocked_file_removed` 行复现无条件恢复的描述保留。 + +② `SyncOutcome` 字段: + +```python + absent_kept: int = 0 # 文件里缺席 → 换戳保留状态(存续:缺席≠删除,2026-09-28) +``` + +③ counters 字典(原 115 行):`"removed"` 键改 `"absent_kept"`。 + +④ STEP 4(原 203-218 行)整体替换为: + +```python + # [STEP 4] 文件里缺席的非终态行 → 存续处理(2026-09-28 语义升级):收料 RPA + # 导出非全量,缺席≠删除(行业存续原则)——保留原 status/result_code/message, + # 只把版本戳换到最新文件 sha(保留 sheet/row_no 行定位):对齐入口 row_shas + # 收敛直通、执行门禁②继续放行(历史行不会被 TRANSFER.FILE_CHANGED 死锁)。 + # 行日后复现时 evaluated_sha≠新文件 sha,自然走 STEP 2 刷新/重置分支;真实 + # 删除由人工关闭兜底(待处理池 3/5/7 天老化防遗忘)。终态行不在 by_key, + # 绝不触碰。 + for key, row in by_key.items(): + if key in incoming_keys: + continue + row.raw_lines_json = [ + {**line, "file_version": ready.file_version, "file_sha256": ready.checksum} + for line in (row.raw_lines_json or []) + ] + row.updated_at = now + counters["absent_kept"] += 1 +``` + +⑤ 审计事件 after 字典(原 230-234 行)`"removed": outcome.removed` 改 `"absent_kept": outcome.absent_kept`;桥日志(原 318-320 行)`removed=%s` 改 `absent=%s`(值 `outcome.absent_kept`)。 + +⑥ STEP 2 的 `restored_from_removed` 分支(原 169-173 行)与 `RESULT_FILE_REMOVED` 导入**保留**,注释补一句「历史残留行防御(2026-09-28 起同步不再新产生该码)」。 + +- [ ] **Step 4: 运行证据同步测试确认通过** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_evidence_sync.py tests/services/in_transit_transfer/test_backlog_service.py -v` +Expected: PASS(backlog 徽标用例自构 `blocked_file_removed` 行,不受影响) + +- [ ] **Step 5: 运行在途全文件夹确认无回归** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/ -q` +Expected: PASS + +- [ ] **Step 6: 暂存** + +```bash +git add backend/app/services/in_transit_transfer/evidence_sync.py backend/tests/services/in_transit_transfer/test_evidence_sync.py +``` + +--- + +### Task 3: 存量误标行修复脚本 + 测试 + +**Files:** +- Create: `backend/scripts/restore_file_removed_transfer_rows.py` +- Test: `backend/tests/services/in_transit_transfer/test_restore_file_removed_rows.py` + +**Interfaces:** +- Consumes: `TransferInvoiceItem`(`result_code='blocked_file_removed'` 且 `status='blocked_recoverable'` 的行);脚本模块级函数 `restore_rows(*, source_code: str | None, now: datetime | None, commit: bool) -> dict`(返回 `{"restored": int}`)。 +- Produces: 可重复执行的幂等修复(修复后行 `status='matching'`、`result_code='pending_stock_check'`、`result_message=None`、`external_quantity=None`);再次执行 restored=0。 + +- [ ] **Step 1: 写失败测试(importlib 直载脚本,同 test_migration_execution 模式)** + +```python +"""存量误标行修复脚本回归(L1,SQLite 内存库)。 + +用途:锁定 restore_file_removed_transfer_rows.restore_rows 的恢复语义——只动 + blocked_file_removed 误标行,恢复待查态并作废旧库存;其他行绝不触碰。 +依赖:app fixture、dbs_ready_file、evidence_sync(构造前置状态)。 +逻辑:importlib 直载脚本模块(backend/scripts 不在包路径内),只测纯函数。 +""" + +import importlib.util +from datetime import datetime +from pathlib import Path + +import pytest + +from app import db +from app.models import TransferInvoiceItem +from app.services.in_transit_transfer.evidence_sync import sync_source_rows +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + +NOW = datetime(2026, 9, 28, 10, 0, 0) + + +def _load_script(): + """按路径加载修复脚本模块(脚本自举 sys.path,不依赖包安装)。""" + path = Path(__file__).parents[3] / "scripts" / "restore_file_removed_transfer_rows.py" + spec = importlib.util.spec_from_file_location("restore_file_removed_transfer_rows", path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +@pytest.mark.usefixtures("app") +def test_restore_flips_only_file_removed_rows(app, dbs_ready_file): + # [断言意图] 只有 blocked_file_removed 行被恢复为待查态;正常行分毫不动。 + script = _load_script() + deps, _, _ = make_transfer_deps(dbs_ready_file) + sync_source_rows(source_code="DBS-AWSBI", deps=deps, + business_date="2026-08-06", now=NOW) + good = TransferInvoiceItem.query.filter_by( + source_code="DBS-AWSBI", invoice_no="HOM-001").first() + doomed = TransferInvoiceItem.query.filter_by( + source_code="DBS-AWSBI", invoice_no="HOX-002").first() + doomed.status = "blocked_recoverable" + doomed.result_code = "blocked_file_removed" + doomed.result_message = "receipt row removed from latest file" + db.session.flush() + + result = script.restore_rows(source_code="DBS-AWSBI", now=NOW) + + assert result == {"restored": 1} # [断言意图] 只命中误标行 + db.session.refresh(doomed) + assert doomed.status == "matching" # [断言意图] 恢复待查态 + assert doomed.result_code == "pending_stock_check" + assert doomed.result_message is None # [断言意图] 删除解释清除 + assert doomed.external_quantity is None # [断言意图] 旧库存作废待重查 + db.session.refresh(good) + assert good.result_code == "pending_stock_check" # [断言意图] 正常行不触碰 + + +@pytest.mark.usefixtures("app") +def test_restore_is_idempotent(app, dbs_ready_file): + # [断言意图] 修复后再跑一遍 restored=0(无新命中),行状态不再变化。 + script = _load_script() + deps, _, _ = make_transfer_deps(dbs_ready_file) + sync_source_rows(source_code="DBS-AWSBI", deps=deps, + business_date="2026-08-06", now=NOW) + row = TransferInvoiceItem.query.filter_by( + source_code="DBS-AWSBI", invoice_no="HOX-002").first() + row.status = "blocked_recoverable" + row.result_code = "blocked_file_removed" + db.session.flush() + script.restore_rows(source_code="DBS-AWSBI", now=NOW) + + second = script.restore_rows(source_code="DBS-AWSBI", now=NOW) + + assert second == {"restored": 0} # [断言意图] 幂等:无新命中 +``` + +- [ ] **Step 2: 运行确认失败** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_restore_file_removed_rows.py -v` +Expected: FAIL(脚本文件不存在,`spec_from_file_location` 断言失败) + +- [ ] **Step 3: 实现脚本** + +```python +""" +backend/scripts/restore_file_removed_transfer_rows.py + +用途:一次性修复在途调拨存量误标行——把 result_code=blocked_file_removed 的行 + 恢复为待查态。背景:2026-09-28 存续语义上线前,收料 RPA 非全量导出导致 + 「不在最新文件」的历史未处理行被自动判删误标;恢复后行重新进入匹配管道, + 由匹配重新推导正确落位(数量阻断等)。 +依赖:Flask create_app、models.TransferInvoiceItem。 +逻辑:默认 dry-run(flush 后回滚,只打印计划);--apply 才真正提交;--source + 可按来源过滤;restore_rows 为纯函数供测试复用;幂等可重复执行。 + +用法: + cd backend + python scripts/restore_file_removed_transfer_rows.py # dry-run + python scripts/restore_file_removed_transfer_rows.py --apply + python scripts/restore_file_removed_transfer_rows.py --source DBS-AWSBI --apply +""" + +from __future__ import annotations + +import argparse +import os +import sys +from datetime import datetime +from pathlib import Path + +_BACKEND_ROOT = Path(__file__).resolve().parents[1] +_REPO_ROOT = _BACKEND_ROOT.parent +if str(_BACKEND_ROOT) not in sys.path: + sys.path.insert(0, str(_BACKEND_ROOT)) + +PENDING_STATUS = "matching" +PENDING_RESULT = "pending_stock_check" + + +def restore_rows(*, source_code: str | None = None, now: datetime | None = None, + commit: bool = False) -> dict: + """把 blocked_file_removed 误标行恢复为待查态(flush;commit 时机归调用方)。 + + Args: + source_code: 可选来源编码过滤;None=全部来源。 + now: 恢复行 updated_at 戳;None=当前 UTC。 + commit: True=提交事务;False=只 flush(dry-run 由调用方回滚)。 + Returns: + {"restored": 恢复行数}。 + """ + from app import db + from app.models import TransferInvoiceItem + + query = TransferInvoiceItem.query.filter( + TransferInvoiceItem.result_code == "blocked_file_removed", + TransferInvoiceItem.status == "blocked_recoverable", + ) + if source_code: + query = query.filter_by(source_code=source_code) + rows = query.all() + stamp = now or datetime.utcnow() + for row in rows: + row.status = PENDING_STATUS + row.result_code = PENDING_RESULT + row.result_message = None + row.external_quantity = None # 旧库存是对误标前证据查的,作废待重查 + row.updated_at = stamp + if commit: + db.session.commit() + else: + db.session.flush() + return {"restored": len(rows)} + + +def _prepare_env() -> None: + """导入 app 前固定 ENV_NAME=dev,并允许 .env.local 覆盖 DATABASE_URL。""" + os.environ.setdefault('ENV_NAME', 'dev') + try: + from dotenv import dotenv_values + except ImportError: + return + local_file = _REPO_ROOT / '.env.local' + if not local_file.exists(): + return + values = {k: v for k, v in dotenv_values(local_file).items() if v is not None} + if values.get('DATABASE_URL'): + os.environ['DATABASE_URL'] = str(values['DATABASE_URL']) + + +def main() -> int: + """解析参数并执行修复(dry-run 缺省,--apply 才写库)。""" + parser = argparse.ArgumentParser(description='Restore wrongly file-removed transfer rows') + parser.add_argument('--apply', action='store_true', help='真正写库提交(缺省 dry-run)') + parser.add_argument('--source', default=None, help='仅处理指定来源编码') + args = parser.parse_args() + + _prepare_env() + from app import create_app, db + app = create_app() + with app.app_context(): + result = restore_rows(source_code=args.source, commit=args.apply) + if not args.apply: + db.session.rollback() + mode = 'APPLIED' if args.apply else 'DRY-RUN' + print(f"[{mode}] restored={result['restored']}") + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) +``` + +- [ ] **Step 4: 运行脚本测试确认通过** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_restore_file_removed_rows.py -v` +Expected: PASS + +- [ ] **Step 5: 暂存** + +```bash +git add backend/scripts/restore_file_removed_transfer_rows.py backend/tests/services/in_transit_transfer/test_restore_file_removed_rows.py +``` + +--- + +### Task 4: 前端 T-2 同口径 + i18n 文案 + +**Files:** +- Modify: `frontend/src/features/chat/components/messages/transferDate.ts` +- Create: `frontend/src/features/chat/components/messages/transferDate.spec.ts` +- Modify: `frontend/src/locales/zh-CN/chat.json:3783`、`zh-TW/chat.json:3710`、`en/chat.json:3710`、`th/chat.json:3710` + +**Interfaces:** +- Consumes: 无(纯函数;现有 `TransferSourceSelectCard` 等调用方签名不变)。 +- Produces: `eligibleReceiptDateTo(now?)` 返回 T−2(四语言文案键 `notMaturedCount` 语义改为「未成熟收料」)。 + +- [ ] **Step 1: 写失败测试 transferDate.spec.ts** + +```typescript +/** + * features/chat/components/messages/transferDate.spec.ts + * 用途:锁定 T+2 成熟口径的截止日计算(与后端 date_policy 同口径,默认 lag=2)。 + * 依赖:被测纯函数 transferDate.ts。 + * 逻辑:直接注入 UTC 时刻构造上海业务日,断言跨日/跨月边界不漂移。 + */ +import { describe, expect, it } from 'vitest'; +import { eligibleReceiptDateTo, shanghaiBusinessDate } from './transferDate'; + +describe('eligibleReceiptDateTo(T+2 口径)', () => { + it('T=2026-09-28 → 截止 2026-09-26(T-2,海外时差)', () => { + // 上海 9-28 13:00 = UTC 05:00。 + expect(eligibleReceiptDateTo(new Date('2026-09-28T05:00:00Z'))).toBe('2026-09-26'); + }); + + it('UTC 月末跨界仍按上海业务日回退 2 天', () => { + // 上海 10-01 00:30 = UTC 9-30 16:30 → T=10-01,截止 09-29。 + expect(eligibleReceiptDateTo(new Date('2026-09-30T16:30:00Z'))).toBe('2026-09-29'); + }); + + it('shanghaiBusinessDate 返回上海业务日(UTC 17:00 = 上海次日)', () => { + expect(shanghaiBusinessDate(new Date('2026-08-05T17:00:00Z'))).toBe('2026-08-06'); + }); +}); +``` + +- [ ] **Step 2: 运行确认失败** + +Run: `cd frontend && npm run test:unit -- transferDate` +Expected: FAIL(现实现回退 1 天:`2026-09-25`) + +- [ ] **Step 3: 实现 transferDate.ts** + +文件头块注释与函数实现替换(`shanghaiBusinessDate` 不变): + +```typescript +/** + * features/chat/components/messages/transferDate.ts + * 用途:在途调拨业务日期工具——按 Asia/Shanghai 计算业务日期(T)与 + * T+lag 成熟规则的可匹配截止日(T - lag,lag 默认 2 即 T+2), + * 与后端 date_policy 完全同口径。 + * 依赖:无(纯函数,便于单测)。 + * 逻辑:浏览器本地时区不可靠(部署/用户时区任意),必须固定上海时区口径, + * 否则前端日期上限与后端 TRANSFER.RECEIPT_DATE_RANGE_INVALID 卡控会漂移。 + */ + +/** 成熟滞后天数:与后端 IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS 默认值一致(T+2,海外时差余量)。 */ +const MATURITY_LAG_DAYS = 2; + +/** Asia/Shanghai 当前业务日期(YYYY-MM-DD)。 */ +export function shanghaiBusinessDate(now: Date = new Date()): string { + // en-CA 输出恰为 ISO YYYY-MM-DD(locale 无关的稳定格式技巧)。 + return new Intl.DateTimeFormat('en-CA', { + timeZone: 'Asia/Shanghai', + year: 'numeric', + month: '2-digit', + day: '2-digit', + }).format(now); +} + +/** T+lag 规则可匹配截止日(业务日期 T - lag 天,默认 T-2,YYYY-MM-DD)。 */ +export function eligibleReceiptDateTo(now: Date = new Date()): string { + const business = new Date(`${shanghaiBusinessDate(now)}T00:00:00Z`); + business.setUTCDate(business.getUTCDate() - MATURITY_LAG_DAYS); + return business.toISOString().slice(0, 10); +} +``` + +- [ ] **Step 4: 四语言文案(T+2 下「当天收料」口径已不准确)** + +`"notMaturedCount"` 值替换: +- `zh-CN/chat.json`: `"notMaturedCount": "未成熟收料",` +- `zh-TW/chat.json`: `"notMaturedCount": "未成熟收料",` +- `en/chat.json`: `"notMaturedCount": "Immature receipts",` +- `th/chat.json`: `"notMaturedCount": "รับของที่ยังไม่ถึงกำหนด",` + +- [ ] **Step 5: 运行前端单测全量 + 构建** + +Run: `cd frontend && npm run test:unit && npm run build` +Expected: PASS(`TransferSourceSelectCard.spec` 等自引用 `eligibleReceiptDateTo()`,自动同口径) + +- [ ] **Step 6: 暂存** + +```bash +git add frontend/src/features/chat/components/messages/transferDate.ts frontend/src/features/chat/components/messages/transferDate.spec.ts frontend/src/locales/zh-CN/chat.json frontend/src/locales/zh-TW/chat.json frontend/src/locales/en/chat.json frontend/src/locales/th/chat.json +``` + +--- + +### Task 5: 文档与注释一致性 + 全量回归 + +**Files:** +- Modify: `docs/features/in-transit-transfer/technical.md`(约 87 行门禁②表格行、约 138 行证据同步描述) +- Modify: `docs/features/in-transit-transfer/minimum-implementation-spec.md`(65、694、921 行的 D+1 表述) +- Modify: `backend/app/services/in_transit_transfer/matching_service.py`(注释/文案,见 Step 2) +- Modify: `backend/app/services/in_transit_transfer/contracts.py:77`(invalid_count 注释) + +**Interfaces:** +- Consumes: Task 1-4 的最终行为。 +- Produces: 文档与代码一致;无接口变化。 + +- [ ] **Step 1: 更新 technical.md 两处** + +约 87 行门禁②行中「评估后被更新版本文件取代而**消失的 ready 行**在匹配/重查时标 `blocked_file_removed` 入异常池(fail-closed…)」改为:「2026-09-28 起收料文件按非全量导出对待(存续原则:缺席≠删除),缺席行只换版本戳保留状态,不再产生 `blocked_file_removed`;该结果码仅为历史残留数据的防御识别,真实删除走待处理池人工关闭」。 + +约 138 行证据同步描述中「文件里消失 → **`blocked_file_removed` 入待处理池出清**(换戳到最新文件 sha)」改为「文件里缺席 → **存续**(只换版本戳到最新文件 sha,状态与结果码原样保留;缺席≠删除)」。 + +- [ ] **Step 2: matching_service / contracts 注释与文案** + +`matching_service.py`: +- 第 3 行 docstring「D+1 成熟过滤」→「T+lag 成熟过滤(默认 T+2)」。 +- 第 87-88 行 RESULT_FILE_REMOVED 注释改为:`# 历史残留结果码(2026-09-28 前按"文件新版本缺失该行"自动标记;存续语义上线后不再新产生,仅作历史数据防御识别)。` +- 第 215 行注释「截止不得超出 D+1 规则(业务日期-1)」→「截止不得超出成熟规则(业务日期-lag,默认 T-2)」。 +- 第 224 行错误消息 `"receipt date range end exceeds D+1 maturity limit"` → `"receipt date range end exceeds receipt maturity limit"`(code 不变)。 +- 第 457 行 `row.result_message = "receipt not matured until next business day"` → `row.result_message = f"receipt not matured before {eligible_receipt_date_to(business_date).isoformat()}"`。 +- 第 430 行注释「(文件新版本消失)」→「(历史残留 blocked_file_removed 行防御过滤)」。 + +`contracts.py` 第 77 行注释改为:`# blocked_file_removed 行数(历史残留:存续语义上线前误标;不进默认视图/明细,修复脚本恢复后归零)。` + +- [ ] **Step 3: 更新 minimum-implementation-spec.md 三处 D+1 表述** + +65 行「按 HUB 仓收料日期执行 D+1 成熟规则」→「按 HUB 仓收料日期执行 T+lag 成熟规则(默认 T+2,`IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS` 可配)」;694 行表格「成熟规则 D+1」→「成熟规则 T+2(可配)」;921 行「D+1硬门禁」→「T+2成熟硬门禁(可配)」。 + +- [ ] **Step 4: 过期引用扫描** + +Run: `grep -rn "next business day\|D+1" backend/app/services/in_transit_transfer/ && grep -rn "文件已移除\|blocked_file_removed" docs/features/in-transit-transfer/technical.md` +Expected: 无残留的现行规则描述(历史/防御性提及允许,但必须带「2026-09-28 起不再新产生」类限定)。`docs/funclist.md` 在途段落(约 756-764 行)如命中「D+1/文件已移除」一并修正,未命中则不动。 + +- [ ] **Step 5: 全量回归** + +```bash +cd backend && python -m pytest tests/services/in_transit_transfer/ tests/test_agent_registry_in_transit_transfer.py -q +cd ../frontend && npm run test:unit && npm run build +``` + +Expected: 全部 PASS。 + +- [ ] **Step 6: 暂存** + +```bash +git add docs/features/in-transit-transfer/technical.md docs/features/in-transit-transfer/minimum-implementation-spec.md backend/app/services/in_transit_transfer/matching_service.py backend/app/services/in_transit_transfer/contracts.py docs/funclist.md +``` + +--- + +## 上线注意(非代码任务,供发布时执行) + +1. 部署后在 dev/test 各跑一次 `python scripts/restore_file_removed_transfer_rows.py`(dry-run 核对数量)→ `--apply`;prod 发布窗口同样操作。 +2. 修复后待处理池中「文件已移除」徽标行应归零;被误标的历史行回到主视图重新匹配。 +3. `.env.shared` 新增变量随代码发布即生效(默认即 2),各环境无需单独配置。 diff --git a/docs/superpowers/plans/2026-09-28-transfer-schedule-consolidation.md b/docs/superpowers/plans/2026-09-28-transfer-schedule-consolidation.md new file mode 100644 index 00000000..43e13b98 --- /dev/null +++ b/docs/superpowers/plans/2026-09-28-transfer-schedule-consolidation.md @@ -0,0 +1,1061 @@ +# 在途自动调拨排程接线与「在途收料文件抓取」下线 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:** 下线冗余的 `in-transit-receipt-file` 排程类型(职责本就在途自动调拨内建),并把 09:00 在途自动调拨排程补成"默认配置即可跑通":来源留空兜底、空数据日干净跳过、企微汇总通知真实接线、通知人下拉选项源修复、i18n 四语言补齐。 + +**Architecture:** 排程层只做参数解析与编排接线;文件就绪判定复用在途调拨域唯一的 `latest_ready_file` 谓词(`movement_file_repository.py`,来源启用+收料配置+已发布 movement 解析 Profile+当日可用文件);企微发送器实现域内既有 `notification.WeComSender` 协议,复用 `schedule_completed` 事件开关(不新增 `WECOM_NOTIFY_EVENTS` 事件名,不动 `.env.*`)。`freight-receipt-rpa` 及其测试**零改动**。 + +**Tech Stack:** Flask (Python 3.12) + SQLAlchemy 2.0 + pytest;前端 Vue3 i18n JSON(四语言)+ vite build。 + +**Spec:** 本计划实现 2026-09-28 会话中用户逐条批准的设计(bounded 路径,无独立 spec 文件);领域权威文档 `docs/features/in-transit-transfer/technical.md`。已冻结决策: +- D1:「在途收料文件抓取」整个类型删除,不设兼容层;已建过该类型排程的环境需删除重建。 +- D2:「货代收料 RPA」零改动(无条件导出+归档+推送的报表通道);"就绪复用、缺失触发 RPA"是「在途自动调拨」的内建行为(代码已存在,本计划只改描述文案)。 +- D3:任务描述不得出现硬编码时间(08:00/09:00 仅为历史文案,执行时间完全由排程 Cron 决定)。 +- D4:通知方案=配了「通知人」发领域明细汇总卡并抑制框架通用排程卡(`domain_notification_managed`,对齐立账凭证检核先例);未配则落回框架通用卡。 +- D5:09:00 排程来源留空=全部启用且已配置收料报表的来源(与货代收料 RPA 排程同口径)。 + +## Global Constraints + +- 🔒 不提交任何密钥/密码/生产地址;不改 `.env.*`(本计划复用既有事件开关,无需新增环境变量)。 +- 🌍 前端新增文案必须同时补齐 `zh-CN / zh-TW / en / th` 四语言 `admin.json`;zh-CN 值必须与 `job_registry.py` 中 `label` 兜底文案逐字一致。 +- 📝 新建/调整代码必须满足 AGENTS.md §5:文件头三要素注释(后端模块 docstring:用途/依赖/逻辑)+ 每个函数 docstring(用途、Args/Returns、AI 触发时机如适用)。 +- 🚫 禁止自动 commit(用户记忆红线):每个任务止步于 `git add <具体文件>`;提交由用户批准后进行。 +- ➕ 不新增第三方依赖。 +- 🧪 后端测试命令统一 `cd backend && python -m pytest ...`;前端验证 `cd frontend && npm run build`。 +- ⚠️ `notify_run_summary` 的既有语义不得破坏:空数据 Run 不通知(C5)、已成功投递幂等跳过、通知失败不改 `run.status`。 + +--- + +### Task 1: 下线 `in-transit-receipt-file` 排程类型 + 在途自动调拨描述改写 + +**Files:** +- Modify: `backend/app/services/schedule/job_registry.py`(删 import、删注册块、改 in-transit-transfer 描述) +- Delete: `backend/app/services/schedule/in_transit_receipt_file_job.py` +- Test: `backend/tests/services/in_transit_transfer/test_schedule_jobs.py` + +**Interfaces:** +- Produces: 注册表中不再存在 key `in-transit-receipt-file`;`in-transit-transfer` 注册保留(Task 2/5 继续改其 handler 所在模块)。后续任务依赖 `get_platform_job("in-transit-transfer")` 仍可解析。 + +- [ ] **Step 1: 改写测试(先失败)** + +将 `backend/tests/services/in_transit_transfer/test_schedule_jobs.py` 整体替换为: + +```python +"""在途调拨排程注册与执行测试。 + +用途:验证在途自动调拨 platform job 注册契约与 handler 调用形态; + in-transit-receipt-file 已于 2026-09-28 下线(文件就绪保障内建于自动调拨, + 见 job_registry 在途自动调拨描述),此处锁定其"不再注册"防回归。 +依赖:schedule.job_registry。 +逻辑:只验证注册契约与调用形态,真实排程触发由 scheduler 驱动。 +""" + +from __future__ import annotations + +from app.services.schedule.job_registry import get_platform_job, list_platform_jobs + + +def test_receipt_file_job_deregistered(): + """in-transit-receipt-file 已下线:不再注册、不可创建。""" + assert get_platform_job("in-transit-receipt-file") is None + keys = {job.key for job in list_platform_jobs()} + assert "in-transit-receipt-file" not in keys + + +def test_transfer_job_registered_with_schedule_defaults(): + """自动调拨 job 注册且含来源/恢复参数契约;描述不得硬编码时刻。""" + import re + + job = get_platform_job("in-transit-transfer") + assert job is not None + assert job.enabled + keys = {field.get("key") for field in job.params_schema} + assert {"source_codes", "recover_history"} <= keys + assert not re.search(r"\d{2}:\d{2}", job.description), "描述禁止硬编码执行时刻" + + +def test_schedule_handler_callable(): + """自动调拨 handler 可调用(返回 7 元组的契约由执行链路测试覆盖)。""" + from app.services.schedule.in_transit_transfer_job import run_in_transit_transfer_schedule + + assert callable(run_in_transit_transfer_schedule) +``` + +- [ ] **Step 2: 运行测试确认失败** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_schedule_jobs.py -q` +Expected: `test_receipt_file_job_deregistered` FAIL(当前仍注册);`test_transfer_job_registered_with_schedule_defaults` FAIL(旧描述含 "09:00" 命中时刻正则);`test_schedule_handler_callable` PASS。 + +- [ ] **Step 3: 删除注册与 import,改写描述** + +`backend/app/services/schedule/job_registry.py`: + +(a) 删除这两行 import(原 196-197 行附近,保留 `run_in_transit_transfer_schedule` 那行): + +```python + from app.services.schedule.in_transit_receipt_file_job import run_in_transit_receipt_file_schedule +``` + +(b) 整块删除 `in-transit-receipt-file` 注册(原 475-496 行): + +```python + register_platform_job(PlatformJobDefinition( + key="in-transit-receipt-file", + label="在途收料文件抓取", + handler=run_in_transit_receipt_file_schedule, + description=( + "每日 08:00 为已启用来源实例确保当日 ready 收料文件;缺文件时按来源触发收料 RPA。" + "09:00 自动调拨仍会调用统一文件准备服务,不假设本排程成功。" + ), + category="platform", + params_schema=( + { + "key": "source_codes", + "type": "multi_select", + "label": "来源实例", + "label_key": "admin.schedule.form.transferSourceCodes", + "required": False, + "default": [], + "options_source": "shipping_inventory_sources", + }, + ), + defaults={"source_codes": []}, + )) +``` + +(c) 将 `in-transit-transfer` 注册的 `description` 由: + +```python + description=( + "每日 09:00 自动处理新增可调拨项与历史可恢复异常;" + "每非空 Run 发送一条企微汇总通知;通知失败不改变 ERP 结果。" + ), +``` + +改为(去时间硬编码 + 写明内建文件就绪行为): + +```python + description=( + "自动处理可调拨项与历史可恢复异常:调拨前确保各来源当日收料文件就绪" + "(就绪复用,缺失自动触发收料 RPA),数量严格相等匹配后自动生成 ERP 调拨单;" + "每非空 Run 发送一条企微汇总通知,通知失败不改变 ERP 结果。" + "执行时间由排程配置决定,建议配置在业务期望的调拨时点之前。" + ), +``` + +- [ ] **Step 4: 删除模块文件** + +```bash +rm backend/app/services/schedule/in_transit_receipt_file_job.py +``` + +- [ ] **Step 5: 运行测试确认通过** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_schedule_jobs.py -q` +Expected: 3 passed。 + +- [ ] **Step 6: 全仓确认无残留引用** + +```bash +cd backend && grep -rn "in_transit_receipt_file_job\|in-transit-receipt-file" app/ tests/ --include="*.py" +``` +Expected: 无输出(docs 的清理在 Task 7)。 + +- [ ] **Step 7: Stage** + +```bash +git add backend/app/services/schedule/job_registry.py backend/app/services/schedule/in_transit_receipt_file_job.py backend/tests/services/in_transit_transfer/test_schedule_jobs.py +``` + +--- + +### Task 2: `list_receipt_capable_source_codes()` 助手 + 09:00 来源留空兜底 + +**Files:** +- Modify: `backend/app/services/in_transit_transfer/receipt_trigger_service.py`(新增函数) +- Modify: `backend/app/services/schedule/in_transit_transfer_job.py`(新增 `_wanted_source_codes` 并替换来源解析) +- Test: `backend/tests/services/in_transit_transfer/test_schedule_jobs.py`(追加) + +**Interfaces:** +- Produces: `receipt_trigger_service.list_receipt_capable_source_codes() -> list[str]`(enabled 库存源 ⨝ 收料报表配置,按 source_code 排序;无匹配返回空列表)。 +- Produces: `in_transit_transfer_job._wanted_source_codes(task: ScheduleTask) -> list[str]`(显式选择优先;留空调用上面的助手兜底)。Task 5 的最终版 handler 依赖它。 + +- [ ] **Step 1: 追加失败测试** + +向 `backend/tests/services/in_transit_transfer/test_schedule_jobs.py` 追加: + +```python +def _make_receipt_source(db, source_code: str, *, enabled: bool): + """创建可参与收料的最小库存源(rpa_profile_id 非空,须先建 Profile)。""" + from app.models import ShippingInventorySource, ShippingRpaProfile + + profile = ShippingRpaProfile( + profile_code=f"RPA_{source_code}", display_name=source_code, connector_type="crane", + login_url="https://test.invalid/login", login_config_json={"auth_mode": "password"}, + ) + db.session.add(profile) + db.session.flush() + source = ShippingInventorySource( + source_code=source_code, display_name=source_code, connector_type="crane", + rpa_profile_id=profile.id, warehouse_resolution_mode="fixed", enabled=enabled, + ) + db.session.add(source) + return source + + +def test_list_receipt_capable_source_codes_filters_by_enabled_and_config(app, transfer_db): + """缺省来源口径:enabled 库存源且已配置收料报表才入选;停用/无配置排除。""" + from app.models import ShippingReceiptReportConfig + from app.services.in_transit_transfer.receipt_trigger_service import list_receipt_capable_source_codes + + enabled = _make_receipt_source(transfer_db, "CRANE_SGP", enabled=True) + _make_receipt_source(transfer_db, "DBS_OFF", enabled=False) + _make_receipt_source(transfer_db, "CRANE_NOCONF", enabled=True) + transfer_db.session.flush() + transfer_db.session.add(ShippingReceiptReportConfig( + inventory_source_id=enabled.id, report_path_json={}, query_parameters_json=[], + )) + transfer_db.session.commit() + + result = list_receipt_capable_source_codes() + assert "CRANE_SGP" in result + assert "DBS_OFF" not in result + assert "CRANE_NOCONF" not in result + assert result == sorted(result) + + +def test_wanted_source_codes_falls_back_when_empty(monkeypatch): + """09:00 排程来源留空=全部启用收料来源;显式选择优先。""" + import app.services.schedule.in_transit_transfer_job as job_mod + from app.models import ScheduleTask + from app.services.schedule.in_transit_transfer_job import _wanted_source_codes + + monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP", "DBS_HUB"]) + empty = ScheduleTask(job_params={"source_codes": []}) + assert _wanted_source_codes(empty) == ["CRANE_SGP", "DBS_HUB"] + explicit = ScheduleTask(job_params={"source_codes": ["DBS_HUB"]}) + assert _wanted_source_codes(explicit) == ["DBS_HUB"] + string_param = ScheduleTask(job_params={"source_codes": "DBS_HUB"}) + assert _wanted_source_codes(string_param) == ["DBS_HUB"] +``` + +- [ ] **Step 2: 运行确认失败** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_schedule_jobs.py -q` +Expected: 新增两条 FAIL(`ImportError/cannot import name '_wanted_source_codes'` 等)。 + +- [ ] **Step 3: 实现助手函数** + +`backend/app/services/in_transit_transfer/receipt_trigger_service.py` 在 `trigger_receipt_rpa` 定义之前加入: + +```python +def list_receipt_capable_source_codes() -> list[str]: + """列出可产出收料文件的启用来源实例(enabled 库存源 + 已配置收料报表)。 + + 用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——收料文件只能 + 来自已配置收料报表的站点,与货代收料 RPA 排程的站点口径保持一致。 + Returns: + 按 source_code 排序的来源编码列表;无匹配站点时为空列表。 + """ + from app import db + from app.models import ShippingInventorySource, ShippingReceiptReportConfig + + rows = db.session.query(ShippingInventorySource.source_code).join( + ShippingReceiptReportConfig, + ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id, + ).filter(ShippingInventorySource.enabled.is_(True)).order_by(ShippingInventorySource.source_code).all() + return [str(code) for (code,) in rows] +``` + +- [ ] **Step 4: 实现排程侧兜底解析** + +`backend/app/services/schedule/in_transit_transfer_job.py`:文件头 docstring 的"依赖"行补上 `receipt_trigger_service.list_receipt_capable_source_codes(缺省来源口径)`;import 区新增: + +```python +from app.services.in_transit_transfer.receipt_trigger_service import list_receipt_capable_source_codes +``` + +并在 `_task_params` 之后新增: + +```python +def _wanted_source_codes(task: ScheduleTask) -> list[str]: + """提取结构化 source_codes;留空回落为全部启用且已配置收料报表的来源。""" + params = _task_params(task) + values = params.get("source_codes") or [] + if isinstance(values, str): + values = [values] + codes = [str(item).strip() for item in values if str(item).strip()] + if not codes: + codes = list_receipt_capable_source_codes() + return codes +``` + +(`run_in_transit_transfer_schedule` 本任务暂不改动;其内部来源解析改用 `_wanted_source_codes` 在 Task 5 随通知接线一并落地。) + +- [ ] **Step 5: 运行测试确认通过** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_schedule_jobs.py -q` +Expected: 全部 passed。 + +- [ ] **Step 6: Stage** + +```bash +git add backend/app/services/in_transit_transfer/receipt_trigger_service.py backend/app/services/schedule/in_transit_transfer_job.py backend/tests/services/in_transit_transfer/test_schedule_jobs.py +``` + +--- + +### Task 3: `run_auto_transfer` 空数据日干净跳过 + +**Files:** +- Modify: `backend/app/services/in_transit_transfer/auto_transfer.py` +- Create: `backend/tests/services/in_transit_transfer/test_auto_transfer.py` + +**Interfaces:** +- Consumes: `matching_service.create_matching(...) -> MatchingSummaryDTO`(`summary.counts.executable_count`)。 +- Produces: `run_auto_transfer(...) -> AutoTransferOutcome` 新语义——`executable_count == 0` 时直接返回(`run_no=None`、`errors` 为空),不调用 `execute_matching_items`、不通知。Task 5 的空日 warning 依赖该语义(`run_no=None` 且 `errors` 空)。 + +- [ ] **Step 1: 写失败测试(新文件)** + +创建 `backend/tests/services/in_transit_transfer/test_auto_transfer.py`: + +```python +"""自动调拨编排(run_auto_transfer)测试:空数据日跳过与正常执行透传。 + +用途:锁定 09:00 自动排程编排的阶段语义——匹配后无可执行行(含恢复后仍为 0) + 时不建票、不写 ERP、不通知、不记 error(产品决策 C5);有可执行行时把 + 执行结果透传给调用方。 +依赖:auto_transfer(monkeypatch create_matching / execute_matching_items)。 +逻辑:纯单元用例,不触库;恢复阶段用 recover_history=False 关闭。 +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import app.services.in_transit_transfer.auto_transfer as at +from app.services.in_transit_transfer.contracts import MatchingCountsDTO, MatchingSummaryDTO + + +def _summary(executable_count: int) -> MatchingSummaryDTO: + return MatchingSummaryDTO( + matching_id="MTG-20260928-ABC123", + status="matched", + business_date="2026-09-28", + eligible_receipt_date_to="2026-09-27", + expires_at="2026-09-28T10:00:00", + counts=MatchingCountsDTO(executable_count=executable_count), + estimated_transfer_quantity="0", + estimated_external_write_count=executable_count, + matching_hash="hash-x", + ) + + +def test_skips_execution_when_no_executable_items(monkeypatch): + """空数据日:不执行、不通知、不记 error,clean no-op。""" + monkeypatch.setattr(at, "create_matching", lambda **kwargs: _summary(0)) + + def _must_not_execute(**kwargs): + raise AssertionError("execute_matching_items must not be called on empty day") + + monkeypatch.setattr(at, "execute_matching_items", _must_not_execute) + + outcome = at.run_auto_transfer( + business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False, + ) + assert outcome.run_no is None + assert outcome.run_status is None + assert outcome.errors == [] + + +def test_executes_and_propagates_result_when_executable(monkeypatch): + """有可执行行:按匹配执行并透传 run_no/status。""" + monkeypatch.setattr(at, "create_matching", lambda **kwargs: _summary(3)) + captured = {} + + def _fake_execute(**kwargs): + captured.update(kwargs) + return SimpleNamespace(run_no="RUN-20260928-XYZ789", status="success") + + monkeypatch.setattr(at, "execute_matching_items", _fake_execute) + + outcome = at.run_auto_transfer( + business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False, + ) + assert captured["matching_id"] == "MTG-20260928-ABC123" + assert outcome.run_no == "RUN-20260928-XYZ789" + assert outcome.run_status == "success" + assert outcome.errors == [] +``` + +- [ ] **Step 2: 运行确认失败** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_auto_transfer.py -q` +Expected: `test_skips_execution_when_no_executable_items` FAIL(当前实现会调 execute → 门禁抛 `item_ids is required` 被记入 errors)。 + +- [ ] **Step 3: 实现跳过分支** + +`backend/app/services/in_transit_transfer/auto_transfer.py` 中,将 `create_matching(...)` 与 `execute_matching_items(...)` 之间的段落改为: + +```python + # [STEP 2] 空数据日跳过执行:匹配后无可执行行(含恢复后仍为 0)时不建票、 + # 不写 ERP、不通知(产品决策 C5);该日仅留痕 Run/Matching,不视作失败。 + if summary.counts.executable_count == 0: + return outcome + # [STEP 3] 执行不再绑定匹配确认:按匹配 scope 圈 ready 行委托 execute_items + # (两道门禁:可执行/文件版本对账;TTL 新鲜度门禁 2026-09-25 退役)。 + executed = execute_matching_items(matching_id=summary.matching_id, deps=deps) + outcome.run_no = executed.run_no + outcome.run_status = executed.status +``` + +(即删除原注释中"无可执行行时门禁抛错,与旧流程一致记入 errors 不阻断通知阶段"的旧语义,替换为上述显式跳过。) + +- [ ] **Step 4: 运行测试确认通过** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_auto_transfer.py -q` +Expected: 2 passed。 + +- [ ] **Step 5: Stage** + +```bash +git add backend/app/services/in_transit_transfer/auto_transfer.py backend/tests/services/in_transit_transfer/test_auto_transfer.py +``` + +--- + +### Task 4: `WecomSummarySender` 企微汇总发送器 + +**Files:** +- Create: `backend/app/services/in_transit_transfer/wecom_sender.py` +- Create: `backend/tests/services/in_transit_transfer/test_wecom_sender.py` + +**Interfaces:** +- Consumes: `integrations.wecom.notify.send_wecom_event_message(*, event_type, user, title, content, jump_path) -> dict`(含 `ok` 键)。 +- Produces: `wecom_sender.WecomSummarySender().send_summary(*, run_no: str, summary: dict, recipients: list[str], excel_path: str | None = None) -> dict`,返回 `{"status": "success", "delivered": n}` 或 `{"status": "failed", "error_code": "WECOM_SEND_FAILED", "error_message": str}`——满足 `notification.WeComSender` 协议。Task 5 以此注入 `run_auto_transfer(sender=...)`。 + +- [ ] **Step 1: 写失败测试(新文件)** + +创建 `backend/tests/services/in_transit_transfer/test_wecom_sender.py`: + +```python +"""企微汇总发送器(WecomSummarySender)测试。 + +用途:锁定 notify_run_summary 真实通道的投递语义——逐收件人解析 wecom_userid + 后经 schedule_completed 事件开关发送;≥1 人送达即 success;无可用收件人 + 或全部失败为 failed(由 notify_run_summary 落库,不影响 ERP 结果)。 +依赖:app fixture(SQLite)、User 行、monkeypatch send_wecom_event_message。 +逻辑:纯单元用例;不发送真实企微消息。 +""" + +from __future__ import annotations + +import pytest + +import app.services.in_transit_transfer.wecom_sender as ws + + +@pytest.fixture +def wecom_user_ids(transfer_db): + """两个用户:一个绑定企微、一个未绑定;返回 {角色: 用户id}。""" + from app.models import User + + bound = User(username="u_bound", email="u_bound@test.dev", wecom_userid="wecom_bound") + loose = User(username="u_loose", email="u_loose@test.dev", wecom_userid=None) + transfer_db.session.add_all([bound, loose]) + transfer_db.session.commit() + return {"bound": bound.id, "loose": loose.id} + + +def _summary() -> dict: + return { + "run_no": "RUN-20260928-XYZ789", + "status": "success", + "business_date": "2026-09-28", + "counts": {"file_invoice_count": 2, "matched_count": 2, "executable_count": 2}, + } + + +def test_delivers_to_wecom_bound_user_only(monkeypatch, wecom_user_ids): + """送达绑定用户计 delivered;未绑定用户跳过;≥1 送达即 success。""" + calls = [] + + def _fake(**kwargs): + calls.append(kwargs) + return {"ok": True, "trace_id": "t1"} + + monkeypatch.setattr(ws, "send_wecom_event_message", _fake) + outcome = ws.WecomSummarySender().send_summary( + run_no="RUN-20260928-XYZ789", summary=_summary(), + recipients=[str(wecom_user_ids["bound"]), str(wecom_user_ids["loose"])], + ) + assert outcome == {"status": "success", "delivered": 1} + assert len(calls) == 1 + assert calls[0]["event_type"] == "schedule_completed" + assert calls[0]["user"].wecom_userid == "wecom_bound" + assert calls[0]["title"].startswith("在途自动调拨 RUN-") + + +def test_failed_when_all_sends_fail(monkeypatch, wecom_user_ids): + """企微侧全部失败 → failed + WECOM_SEND_FAILED(交 notify_run_summary 落库)。""" + monkeypatch.setattr(ws, "send_wecom_event_message", lambda **kwargs: {"ok": False, "reason": "event_disabled"}) + outcome = ws.WecomSummarySender().send_summary( + run_no="RUN-1", summary=_summary(), recipients=[str(wecom_user_ids["bound"])], + ) + assert outcome["status"] == "failed" + assert outcome["error_code"] == "WECOM_SEND_FAILED" + assert outcome["error_message"] == "event_disabled" + + +def test_failed_when_no_wecom_bound_recipient(monkeypatch, wecom_user_ids): + """收件人全部未绑定企微 → failed(no wecom-bound recipients),不调用发送。""" + sent = [] + + monkeypatch.setattr(ws, "send_wecom_event_message", lambda **kwargs: sent.append(kwargs)) + outcome = ws.WecomSummarySender().send_summary( + run_no="RUN-1", summary=_summary(), recipients=[str(wecom_user_ids["loose"])], + ) + assert outcome["status"] == "failed" + assert outcome["error_message"] == "no wecom-bound recipients" + assert sent == [] + + +def test_non_digit_recipients_ignored(monkeypatch, wecom_user_ids): + """非数字收件人(脏数据)直接忽略,不查询不发送。""" + monkeypatch.setattr(ws, "send_wecom_event_message", lambda **kwargs: {"ok": True}) + outcome = ws.WecomSummarySender().send_summary( + run_no="RUN-1", summary=_summary(), recipients=["abc", ""], + ) + assert outcome["status"] == "failed" + assert outcome["error_message"] == "no wecom-bound recipients" +``` + +- [ ] **Step 2: 运行确认失败** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_wecom_sender.py -q` +Expected: FAIL(`ModuleNotFoundError: app.services.in_transit_transfer.wecom_sender`)。 + +- [ ] **Step 3: 实现发送器(新文件)** + +创建 `backend/app/services/in_transit_transfer/wecom_sender.py`(全文): + +```python +"""在途调拨企微汇总通知的真实通道适配(notification.WeComSender 协议实现)。 + +用途:把自动调拨 Run 汇总经企微 textcard 发给通知人,替代排程 handler 的 + sender=None 占位;通知失败只落 run.notification_status,不影响 ERP 结果。 +依赖:integrations.wecom.notify.send_wecom_event_message(事件门禁+审计)、models.User。 +逻辑:逐收件人解析 wecom_userid 后发送;复用 schedule_completed 事件开关(与排程 + 通用通知同一启停入口,不新增 WECOM_NOTIFY_EVENTS 事件名);至少一人送达即 + success,无可用收件人或全部失败为 failed,由 notify_run_summary 统一落库。 +""" + +from __future__ import annotations + +from typing import Any + +from app.services.integrations.wecom.notify import send_wecom_event_message + +# 复用排程完成事件开关:运维通过 WECOM_NOTIFY_EVENTS 的 schedule_completed +# 统一启停排程类通知,本发送器不引入独立事件名(避免各环境事件表漂移)。 +WECOM_EVENT_TYPE = "schedule_completed" + +_STATUS_LABELS = { + "success": "全部成功", + "partial_failed": "部分失败", + "failed": "失败", + "matching": "匹配中", +} + + +class WecomSummarySender: + """企微汇总通知发送器(协议见 notification.WeComSender)。 + + Args 约定:recipients 为 HXOPS 用户 id 列表(字符串/整数均可),由排程参数 + notify_user_ids(options_source=users)下发;未绑定企微的用户跳过。 + excel_path 为协议占位,当前不发送附件(异常明细以管理端已执行区块为准)。 + """ + + def send_summary(self, *, run_no: str, summary: dict[str, Any], + recipients: list[str], excel_path: str | None = None) -> dict[str, Any]: + """向通知人逐一发送一条 Run 汇总 textcard。 + + Args: + run_no: 调拨 Run 编号(RUN-YYYYMMDD-XXXXXX)。 + summary: notify_run_summary 组装的汇总(run_no/status/business_date/counts)。 + recipients: 用户 id 列表。 + excel_path: 协议占位;当前不发送附件。 + Returns: + {"status": "success", "delivered": n} 或 + {"status": "failed", "error_code": "WECOM_SEND_FAILED", "error_message": str}; + 由 notify_run_summary 写入 run.notification_* 字段。 + """ + counts = summary.get("counts") if isinstance(summary.get("counts"), dict) else {} + status = str(summary.get("status") or "") + title = f"在途自动调拨 {run_no}" + content = "\n".join([ + f"状态: {_STATUS_LABELS.get(status, status or '未知')}", + f"业务日期: {summary.get('business_date') or '-'}", + "文件票数: {tickets} 已匹配: {matched} 待查库存: {pending}".format( + tickets=counts.get("file_invoice_count", 0), + matched=counts.get("matched_count", 0), + pending=counts.get("pending_stock_check_count", 0), + ), + "可执行: {executable} 数量不符: {blocked} 未成熟: {not_matured}".format( + executable=counts.get("executable_count", 0), + blocked=counts.get("blocked_count", 0), + not_matured=counts.get("not_matured_count", 0), + ), + ]) + + user_ids = [int(item) for item in (recipients or []) if str(item).strip().isdigit()] + users = [] + if user_ids: + from app.models import User + + users = User.query.filter(User.id.in_(user_ids)).all() + + # [STEP 1] 逐收件人投递;send_wecom_event_message 内部完成事件门禁与审计落库。 + delivered = 0 + last_error = "" + for user in users: + if not user.wecom_userid: + continue + outcome = send_wecom_event_message( + event_type=WECOM_EVENT_TYPE, user=user, title=title, content=content, + jump_path="/workspace", + ) + if outcome.get("ok"): + delivered += 1 + else: + last_error = str(outcome.get("reason") or "send_failed") + + if delivered: + return {"status": "success", "delivered": delivered} + return { + "status": "failed", + "error_code": "WECOM_SEND_FAILED", + "error_message": last_error or "no wecom-bound recipients", + } +``` + +- [ ] **Step 4: 运行测试确认通过** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_wecom_sender.py -q` +Expected: 4 passed。 + +- [ ] **Step 5: Stage** + +```bash +git add backend/app/services/in_transit_transfer/wecom_sender.py backend/tests/services/in_transit_transfer/test_wecom_sender.py +``` + +--- + +### Task 5: 09:00 handler 接线(sender + 通知标记)+ `users` 选项源 + +**Files:** +- Modify: `backend/app/services/schedule/in_transit_transfer_job.py`(整文件替换为下方最终版) +- Modify: `backend/app/services/schedule/job_options.py`(注册 `users` 提供器) +- Test: `backend/tests/services/in_transit_transfer/test_schedule_jobs.py`(追加) + +**Interfaces:** +- Consumes: Task 2 `_wanted_source_codes`、Task 4 `WecomSummarySender`。 +- Produces: `run_in_transit_transfer_schedule(task, run)` 最终行为——来源留空兜底;recipients 非空时构造 sender 并置 `run.response_summary_json["domain_notification_managed"]=True`;空数据日输出 warning `no executable items; execution and notification skipped`;返回 7 元组。 +- Produces: `job_options.list_job_options("users") -> [{label, value, description}]`(active 用户,value=user.id)。 + +- [ ] **Step 1: 追加失败测试** + +向 `backend/tests/services/in_transit_transfer/test_schedule_jobs.py` 追加: + +```python +class _FakeSender: + """记录实例化的发送器替身(断言 handler 接线,不发真实消息)。""" + + instantiated = 0 + + def __init__(self): + type(self).instantiated += 1 + + +def test_handler_wires_sender_and_domain_notification(monkeypatch): + """配了通知人:构造 sender、置领域自管标记、recipients 透传。""" + import app.services.schedule.in_transit_transfer_job as job_mod + from app.models import ScheduleRun, ScheduleTask + + monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"]) + captured = {} + + def _fake_auto_transfer(**kwargs): + captured.update(kwargs) + return job_mod.AutoTransferOutcome() + + monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer) + monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None)) + + class _FakeSenderInner: + pass + + monkeypatch.setattr(job_mod, "WecomSummarySender", _FakeSenderInner) + + task = ScheduleTask(job_params={"source_codes": [], "recover_history": True, "notify_user_ids": ["7"]}) + run = ScheduleRun(run_no="RUNR-1", status="running") + total, success, failed, skipped, results, warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run) + + assert captured["source_codes"] == ["CRANE_SGP"] + assert captured["recipients"] == ["7"] + assert isinstance(captured["sender"], _FakeSenderInner) + assert run.response_summary_json["domain_notification_managed"] is True + assert (total, success, failed, skipped) == (0, 0, 0, 0) + + +def test_handler_without_recipients_skips_domain_notification(monkeypatch): + """未配通知人:sender=None、不置标记、落回框架通用通知(由框架按任务配置发送)。""" + import app.services.schedule.in_transit_transfer_job as job_mod + from app.models import ScheduleRun, ScheduleTask + + monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"]) + captured = {} + + def _fake_auto_transfer(**kwargs): + captured.update(kwargs) + return job_mod.AutoTransferOutcome() + + monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer) + monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None)) + + task = ScheduleTask(job_params={}) + run = ScheduleRun(run_no="RUNR-2", status="running") + job_mod.run_in_transit_transfer_schedule(task, run) + + assert captured["sender"] is None + assert captured["recipients"] == [] + assert not (run.response_summary_json or {}).get("domain_notification_managed") +``` + +文件头 import 区补 `from types import SimpleNamespace` 与 `from app.services.schedule.in_transit_transfer_job import AutoTransferOutcome`(若按上方代码从模块属性访问 `job_mod.AutoTransferOutcome` 则无需后者)。 + +- [ ] **Step 2: 运行确认失败** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_schedule_jobs.py -q` +Expected: 新增两条 FAIL(当前 handler 无 sender 接线、`_wanted_source_codes` 已存在但 handler 未消费)。 + +- [ ] **Step 3: 替换 handler 为最终版** + +将 `backend/app/services/schedule/in_transit_transfer_job.py` 整文件替换为: + +```python +"""自动调拨排程。 + +用途:自动处理当日新成熟可调拨项与历史可恢复异常,并发送一次企微汇总通知。 +依赖:auto_transfer、transfer deps、wecom_sender、job_registry.ScheduleExecuteResult、 + receipt_trigger_service.list_receipt_capable_source_codes(缺省来源口径)。 +逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发收料 RPA), + 不依赖其他排程成功;来源留空兜底为全部启用收料来源;配置了通知人时领域 + 自管通知(抑制通用排程完成卡片,避免同日双卡)。 +""" + +from __future__ import annotations + +from typing import Any + +from app.models import ScheduleRun, ScheduleTask +from app.services.in_transit_transfer import deps as transfer_deps +from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome, run_auto_transfer +from app.services.in_transit_transfer.date_policy import business_date_now +from app.services.in_transit_transfer.receipt_trigger_service import list_receipt_capable_source_codes +from app.services.in_transit_transfer.wecom_sender import WecomSummarySender +from app.services.schedule.job_registry import ScheduleExecuteResult + + +def _task_params(task: ScheduleTask) -> dict[str, Any]: + """读取排程结构化参数(job_params 非字典时回落空对象)。""" + return task.job_params if isinstance(task.job_params, dict) else {} + + +def _wanted_source_codes(task: ScheduleTask) -> list[str]: + """提取结构化 source_codes;留空回落为全部启用且已配置收料报表的来源。 + + Args: + task: 排程任务(job_params.source_codes 可为列表/字符串/缺省)。 + Returns: + 去空白后的来源编码列表;留空时为 list_receipt_capable_source_codes() 结果。 + """ + params = _task_params(task) + values = params.get("source_codes") or [] + if isinstance(values, str): + values = [values] + codes = [str(item).strip() for item in values if str(item).strip()] + if not codes: + codes = list_receipt_capable_source_codes() + return codes + + +def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: + """自动调拨:恢复 + 匹配(严格相等)+ 执行 + 企微汇总通知。 + + Args: + task: 排程任务(job_params: source_codes/recover_history/notify_user_ids)。 + run: 排程执行批次(领域自管通知时写入 response_summary_json 标记)。 + Returns: + ScheduleExecuteResult 七元组;空数据日 total=0 且不记 error(C5)。 + """ + params = _task_params(task) + source_codes = _wanted_source_codes(task) + recover_history = bool(params.get("recover_history", True)) + recipients = [str(item).strip() for item in (params.get("notify_user_ids") or []) if str(item).strip()] + + # 领域自管通知(对齐立账凭证检核先例):配置了通知人才发领域汇总卡, + # 并抑制通用排程完成卡片;未配置时回落通用卡片(框架按任务通知配置发送)。 + sender = None + if recipients: + sender = WecomSummarySender() + run.response_summary_json = { + **(run.response_summary_json or {}), + "domain_notification_managed": True, + } + + deps = transfer_deps.get_transfer_dependencies() + outcome = run_auto_transfer( + business_date=str(business_date_now()), + deps=deps, + source_codes=source_codes, + recover_history=recover_history, + sender=sender, + recipients=recipients, + ) + results: list[dict[str, Any]] = [] + errors: list[str] = list(outcome.errors) + recovery = outcome.recovery + warnings: list[str] = [ + f"sources={len(source_codes)} recovered={recovery.recovered_count} still_blocked={recovery.still_blocked_count}", + ] + if outcome.run_no: + results.append({ + "run_no": outcome.run_no, + "status": outcome.run_status, + "notification_status": outcome.notification_status, + }) + elif not outcome.errors: + # 空数据日:匹配后无可执行行,执行与通知按 C5 跳过,不记失败。 + warnings.append("no executable items; execution and notification skipped") + success = 1 if outcome.run_status in {"success", "partial_failed"} else 0 + return ( + success + recovery.recovered_count, + success, + recovery.still_blocked_count, + 0, + results, + warnings, + errors, + ) +``` + +- [ ] **Step 4: 注册 `users` 选项源** + +`backend/app/services/schedule/job_options.py` 在 `_shipping_receipt_sources_options` 之后新增: + +```python +def _users_options() -> list[dict[str, Any]]: + """启用中的用户列表(value=user.id),供排程通知人类参数选择。""" + from app.models import User + + users = ( + User.query.filter(User.status == "active") + .order_by(User.username.asc()) + .all() + ) + return [ + { + "label": user.real_name or user.username, + "value": user.id, + "description": None if not user.wecom_userid else "wecom", + } + for user in users + ] +``` + +并在 `_OPTIONS_PROVIDERS` 注册表中加一行: + +```python + "users": _users_options, +``` + +- [ ] **Step 5: 运行测试确认通过** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_schedule_jobs.py tests/services/in_transit_transfer/test_auto_transfer.py tests/services/in_transit_transfer/test_wecom_sender.py -q` +Expected: 全部 passed。 + +- [ ] **Step 6: Stage** + +```bash +git add backend/app/services/schedule/in_transit_transfer_job.py backend/app/services/schedule/job_options.py backend/tests/services/in_transit_transfer/test_schedule_jobs.py +``` + +--- + +### Task 6: i18n 四语言补键 + 前端 build + +**Files:** +- Modify: `frontend/src/locales/zh-CN/admin.json`、`zh-TW/admin.json`、`en/admin.json`、`th/admin.json`(各 `schedule.form` 区新增 4 键) + +**Interfaces:** +- Consumes: `job_registry.py` 中三个参数 label_key(`admin.schedule.form.transferSourceCodes / transferRecoverHistory / transferNotifyUsers`)与 file-asset-cleanup 的 label_key(`admin.schedule.form.platformJobFileAssetCleanup`)。 +- Produces: 四语言 `DynamicTaskParamsForm` 渲染文案;zh-CN 值与注册表 label 兜底逐字一致(`来源实例` / `历史可恢复异常复核` / `通知人`)。 + +- [ ] **Step 1: zh-CN 插入** + +在 `zh-CN/admin.json` 中定位行 ` "platformJobFaqHotAggregate": "FAQ 热点聚合",`(约 2366 行),在该行后插入: + +```json + "platformJobFileAssetCleanup": "临时文件资产清理", + "transferSourceCodes": "来源实例", + "transferRecoverHistory": "历史可恢复异常复核", + "transferNotifyUsers": "通知人", +``` + +- [ ] **Step 2: zh-TW 插入** + +在 `zh-TW/admin.json` 中定位行 ` "platformJobFaqHotAggregate": "FAQ 熱點聚合",`(约 2155 行),在该行后插入: + +```json + "platformJobFileAssetCleanup": "暫存檔案資產清理", + "transferSourceCodes": "來源實例", + "transferRecoverHistory": "歷史可復原異常複核", + "transferNotifyUsers": "通知人", +``` + +- [ ] **Step 3: en 插入** + +在 `en/admin.json` 中定位行 ` "platformJobFaqHotAggregate": "FAQ hot aggregate",`(约 2254 行),在该行后插入: + +```json + "platformJobFileAssetCleanup": "Temporary file asset cleanup", + "transferSourceCodes": "Source instances", + "transferRecoverHistory": "Recover retryable history", + "transferNotifyUsers": "Notify users", +``` + +- [ ] **Step 4: th 插入** + +在 `th/admin.json` 中定位行 ` "platformJobFaqHotAggregate": "FAQ hot aggregate",`(约 2150 行;该文件平台任务文案沿用英文为既有惯例),在该行后插入: + +```json + "platformJobFileAssetCleanup": "Temporary file asset cleanup", + "transferSourceCodes": "Source instances", + "transferRecoverHistory": "Recover retryable history", + "transferNotifyUsers": "Notify users", +``` + +- [ ] **Step 5: JSON 合法性校验(四语言)** + +```bash +cd frontend/src/locales && python -c " +import json +for lang in ['zh-CN', 'zh-TW', 'en', 'th']: + data = json.load(open(f'{lang}/admin.json', encoding='utf-8')) + form = data['schedule']['form'] + missing = [k for k in ['platformJobFileAssetCleanup', 'transferSourceCodes', 'transferRecoverHistory', 'transferNotifyUsers'] if k not in form] + assert not missing, (lang, missing) +print('all four locales OK') +" +``` +Expected: `all four locales OK`。 + +- [ ] **Step 6: 前端 build** + +```bash +cd frontend && npm run build +``` +Expected: build 通过(绿色)。 + +- [ ] **Step 7: 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 +``` + +--- + +### Task 7: 文档同步 + 记忆更新 + 全量回归 + +**Files:** +- Modify: `docs/features/in-transit-transfer/technical.md:15`(排程行改写) +- Modify: `docs/features/in-transit-transfer/minimum-implementation-spec.md:859`、`docs/features/in-transit-transfer/roadmap.md:385`(表格行标注下线) +- Modify: `docs/funclist.md:763`(排程/恢复/异常/通知行改写) +- Modify: `.engramory-memory/in-transit-transfer.md`(下一步区追加 2026-09-28 条目) + +**Interfaces:** +- Consumes: Task 1-6 的最终事实(类型下线、内建就绪保障、通知接线、来源兜底口径)。 + +- [ ] **Step 1: technical.md 排程行改写** + +`docs/features/in-transit-transfer/technical.md` 第 15 行由: + +```markdown +- **排程**:`in-transit-receipt-file`(08:00)与 `in-transit-transfer`(09:00)platform job(`schedule/job_registry.py`)。 +``` + +改为: + +```markdown +- **排程**:仅 `in-transit-transfer` 一个 platform job(`schedule/job_registry.py`);执行时间由排程配置决定。文件就绪保障为自动调拨内建行为(调拨前逐来源检查当日 ready 文件:就绪复用,缺失自动触发收料 RPA),独立的 `in-transit-receipt-file` 排程类型已于 2026-09-28 下线删除(不设兼容层,已建排程需删除重建)。通知:配置「通知人」后每非空 Run 发一条企微明细汇总卡(复用 `schedule_completed` 事件开关)并抑制框架通用排程卡(`domain_notification_managed`);来源留空=全部启用且已配置收料报表的来源。 +``` + +- [ ] **Step 2: spec/roadmap 两处表格行标注** + +`docs/features/in-transit-transfer/minimum-implementation-spec.md:859` 该行改为: + +```markdown +| ~~`backend/app/services/schedule/in_transit_receipt_file_job.py`~~ | 已下线(2026-09-28):文件就绪保障内建于在途自动调拨,独立排程类型删除 | +``` + +`docs/features/in-transit-transfer/roadmap.md:385` 该行改为: + +```markdown +| ~~计划新增~~ 已下线(2026-09-28) | `backend/app/services/schedule/in_transit_receipt_file_job.py` | 文件准备职责内建于在途自动调拨排程 | +``` + +- [ ] **Step 3: funclist.md 行改写** + +`docs/funclist.md` 第 763 行改为: + +```markdown +| 排程/恢复/异常/通知 | 后端已实现 | 在途自动调拨 platform job(执行时间由排程配置决定;调拨前内建当日收料文件就绪保障:就绪复用、缺失自动触发收料 RPA;原独立「在途收料文件抓取」排程类型已下线);来源留空=全部启用收料来源;待处理池 3/5/7 天老化;人工重试/关闭;七 Sheet 异常 Excel;每非空 Run 一条企微通知(失败不改 ERP 结果) | +``` + +- [ ] **Step 4: 记忆笔记更新** + +`.engramory-memory/in-transit-transfer.md` 的「下一步」区顶部追加一条(frontmatter `updated` 改为 `2026-09-28`): + +```markdown +- **2026-09-28 排程收口(本条随实施更新状态)**:①独立「在途收料文件抓取」排程类型删除(用户拍板:就绪复用/缺失触发 RPA 是自动调拨内建行为,不设兼容层);「货代收料 RPA」零改动。②09:00 排程接线:来源留空兜底=`receipt_trigger_service.list_receipt_capable_source_codes`(enabled+收料配置口径);空数据日 `executable_count==0` 干净跳过(修复原"天天报 item_ids is required");企微汇总 `WecomSummarySender`(逐收件人 textcard、复用 schedule_completed 事件开关、配通知人才发并置 domain_notification_managed 抑制通用卡);`job_options` 注册 `users` 选项源(原「通知人」下拉会报 Unknown options source)。③四语言补 `transferSourceCodes/transferRecoverHistory/transferNotifyUsers/platformJobFileAssetCleanup`。实施计划 `docs/superpowers/plans/2026-09-28-transfer-schedule-consolidation.md`。 +``` + +- [ ] **Step 5: 全量回归** + +```bash +cd backend && python -m pytest tests/services/in_transit_transfer tests/test_freight_receipt_rpa_schedule.py -q +``` +Expected: 全部 passed(`test_freight_receipt_rpa_schedule.py` 未改动且必须保持绿——它锁定"货代收料 RPA 零改动")。 + +```bash +cd backend && grep -rn "in-transit-receipt-file" app/ tests/ ../docs/features/in-transit-transfer/ --include="*.py" --include="*.md" | grep -v "已下线\|下线删除\|~~" +``` +Expected: 仅剩标注"已下线"的历史记录行。 + +- [ ] **Step 6: Stage** + +```bash +git add docs/features/in-transit-transfer/technical.md docs/features/in-transit-transfer/minimum-implementation-spec.md docs/features/in-transit-transfer/roadmap.md docs/funclist.md .engramory-memory/in-transit-transfer.md +``` + +--- + +## 验收路径(实施完成后给用户的操作说明) + +1. 管理端 → 排程管理 → 新增排程:执行模式=平台内置任务,平台任务选「在途自动调拨」;来源实例留空(=全部启用收料来源)、按需勾选「历史可恢复异常复核」与「通知人」;Cron 按业务期望配置。 +2. 「立即执行」:空数据日应看到 warning `no executable items; execution and notification skipped` 且 run 不算失败;有可执行行时 results 出现 `run_no/status/notification_status`。 +3. 配置了通知人且 Run 非空:企微收到「在途自动调拨 RUN-…」textcard(状态+票数/已匹配/待查/可执行/不符/未成熟);同日不出现框架通用排程卡。 +4. 平台任务下拉中不再出现「在途收料文件抓取」;若历史环境建过该类型排程任务,会执行报 Unknown platform job,需删除重建。 diff --git a/docs/superpowers/plans/2026-09-29-schedule-worker-manual-wake.md b/docs/superpowers/plans/2026-09-29-schedule-worker-manual-wake.md new file mode 100644 index 00000000..4de841bf --- /dev/null +++ b/docs/superpowers/plans/2026-09-29-schedule-worker-manual-wake.md @@ -0,0 +1,784 @@ +# Schedule Worker 手动入队唤醒 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:** 手动触发排程(及同属 schedule worker 消费的 Job)入队成功后立刻唤醒 `hxops-schedule-worker`,把「点一次执行 → 写出 RPA trigger」的队列空等从最多约 30s 降到通常 <1s,同时保持空闲维护节奏仍为 `SCHEDULE_WORKER_POLL_SECONDS=30`。 + +**Architecture:** 继续异步:Web API 只入队;独立 schedule worker 执行。新增 Redis List 唤醒通道(`LPUSH` / `BLPOP`):入队事务提交后 best-effort 发 wake;worker 空闲时用 `BLPOP(timeout=poll)` 替代 `time.sleep(poll)`。Redis 不可用时 fail-open,退回原 sleep/poll 行为。不把写 trigger 或整段 RPA 搬回 HTTP 线程。 + +**Tech Stack:** Flask (Python 3.12) + 现有 `redis` 客户端(`app.services.redis_client.get_redis_client`)+ pytest;Docker Compose `hxops-schedule-worker`。 + +**Spec:** 本计划实现 2026-09-29 会话批准的「方案 B:继续异步 + 手动入队唤醒」(无独立 spec 文件)。冻结决策: +- D1:空闲 `SCHEDULE_WORKER_POLL_SECONDS` 默认仍为 **30**(控制 `prepare_schedule_queue` 维护频率);唤醒只打断 sleep,不把维护打到 2s。 +- D2:唤醒通道用 Redis List + `BLPOP`(比 pub/sub 更适合「睡醒领任务」;迟到信号用 `LTRIM` 压成有界)。 +- D3:fail-open:无 `REDIS_URL` / ping 失败 / wake 关闭时行为与改前一致。 +- D4:HTTP API 契约不变(`POST /api/admin/schedules//run` 仍立即返回 `queued`);不改前端。 +- D5:YAGNI——本计划不做「同步写 trigger」、不做前端 5s 轮询提速;cron 扫描仍靠既有 poll/prepare。 + +## Global Constraints + +- 🔒 不提交密钥/密码;新增环境变量只写开关与 key 名默认值,不写真实 Redis 密码。 +- 📝 新建/调整代码必须满足 AGENTS.md §5:文件头三要素(用途/依赖/逻辑)+ 每个函数 docstring(用途、核心逻辑、Args/Returns)。 +- 🚫 禁止自动 commit:每个任务止步于 `git add <具体文件>`;提交须用户明确批准。 +- ➕ 不新增第三方依赖(复用已有 `redis`)。 +- 🧪 后端测试:`cd backend && python -m pytest -v`。 +- 🌐 环境变量:跨环境一致项进 `.env.shared`;`docker-compose.yml` 给 schedule-worker 透传;`settings.py` 提供默认值。 +- ⚠️ `enqueue(..., commit=False)` 路径禁止在 flush 后立刻 wake(worker 可能抢在 commit 前 claim);wake 必须在事务提交之后。 + +--- + +## File Map + +| 文件 | 职责 | +| --- | --- | +| `backend/app/jobs/schedule_wake.py` | **新建**:唤醒契约(是否目标队列、notify、wait);唯一 Redis key/协议实现点 | +| `backend/app/jobs/runner.py` | schedule 单队列空闲等待改为 `wait_for_schedule_wake`;其它队列仍 `time.sleep` | +| `backend/app/services/schedule/queue_service.py` | `enqueue_manual_schedule_run` 在 **commit 成功且 created=True** 后调用 `notify_schedule_worker` | +| `backend/app/jobs/queue.py` | `enqueue(..., commit=True)` 且 Job 由 schedule worker 消费时,commit 后 `notify_schedule_worker`(覆盖文件检核等) | +| `backend/app/core/config/settings.py` | 新增 `SCHEDULE_WORKER_WAKE_ENABLED` / `SCHEDULE_WORKER_WAKE_REDIS_KEY` | +| `.env.shared` | 文档化默认开关与 key(与 settings 默认一致) | +| `docker-compose.yml` | `hxops-schedule-worker` 透传上述环境变量 | +| `docs/project_context.md` | 一行说明:手动入队可 Redis 唤醒 schedule-worker | +| `backend/tests/jobs/test_schedule_wake.py` | **新建**:wake 模块单测(假 Redis / 降级) | +| `backend/tests/jobs/test_runner.py` | 增补:schedule 队列空闲走 wait 而非裸 sleep | +| `backend/tests/jobs/test_schedule_queue.py` | 增补:手动入队成功后调用 notify | + +## Interface Contract(全任务共用) + +### Redis 协议 + +- Key:`SCHEDULE_WORKER_WAKE_REDIS_KEY`,默认 `hxops:jobs:wake:schedule` +- Notify:`LPUSH key "wake"`,然后 `LTRIM key 0 7`(最多保留 8 个信号,防堆积) +- Wait:`BLPOP key timeout_seconds`;超时返回「未唤醒」,有元素返回「已唤醒」 +- 不使用 Redis Stream / pubsub(本计划范围外) + +### Python API(`app.jobs.schedule_wake`) + +```python +def targets_schedule_worker(*, domain: str | None, job_type: str | None) -> bool: + """判断该 Job 是否由 hxops-schedule-worker 消费。""" + +def notify_schedule_worker(*, reason: str = "enqueue") -> bool: + """ + Best-effort 唤醒 schedule worker。 + Returns: + True=已写入 Redis;False=跳过/失败(永不抛到业务主路径)。 + """ + +def wait_for_schedule_wake(timeout_seconds: float) -> bool: + """ + 阻塞至多 timeout_seconds 等待唤醒;Redis 不可用时等价 time.sleep(timeout)。 + Returns: + True=被信号唤醒;False=超时或降级 sleep 结束。 + """ +``` + +### `targets_schedule_worker` 判定(锁死) + +返回 True 当且仅当: + +1. `domain == "schedule"`,或 +2. `job_type` ∈ `{ "schedule_run", "file_check_run", "wecom_directory_sync" }` + +(与 `app/jobs/store.py` schedule 分支领取集合对齐;新增 schedule worker 消费类型时必须同步改此集合。) + +### HTTP / 前端契约(不变) + +| 接口 | 行为 | +| --- | --- | +| `POST /api/admin/schedules//run` | 仍立即 `200` + `serialize_run`(`status=queued`);不新增字段 | +| 排程运行列表 / Worker 心跳 API | 无变更 | +| 前端火箭按钮 | 无变更(仍调同一 run API) | + +### 环境变量契约 + +| 变量 | 默认 | 含义 | +| --- | --- | --- | +| `SCHEDULE_WORKER_POLL_SECONDS` | `30` | 空闲等待上限 / BLPOP timeout;**不改默认** | +| `SCHEDULE_WORKER_WAKE_ENABLED` | `true` | `false` 时 notify/wait 均降级为 no-op / sleep | +| `SCHEDULE_WORKER_WAKE_REDIS_KEY` | `hxops:jobs:wake:schedule` | Redis List key | + +依赖既有 `REDIS_URL`(compose 已给 schedule-worker 注入)。 + +--- + +### Task 1: `schedule_wake` 模块 + 单测 + +**Files:** +- Create: `backend/app/jobs/schedule_wake.py` +- Create: `backend/tests/jobs/test_schedule_wake.py` + +**Interfaces:** +- Consumes: `get_redis_client()`、`current_app.config` +- Produces: `targets_schedule_worker` / `notify_schedule_worker` / `wait_for_schedule_wake`(签名见上) + +- [ ] **Step 1: Write the failing tests** + +创建 `backend/tests/jobs/test_schedule_wake.py`: + +```python +""" +tests/jobs/test_schedule_wake.py + +用途:锁定 schedule worker Redis 唤醒契约(判定、notify、wait、fail-open)。 +依赖:app.jobs.schedule_wake、Flask app fixture。 +逻辑:用假 Redis 客户端替换 get_redis_client;不连真实 Redis。 +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + + +class _FakeRedis: + def __init__(self): + self.lists: dict[str, list[str]] = {} + self.ops: list[tuple] = [] + + def lpush(self, key: str, value: str): + self.ops.append(("lpush", key, value)) + self.lists.setdefault(key, []).insert(0, value) + return len(self.lists[key]) + + def ltrim(self, key: str, start: int, end: int): + self.ops.append(("ltrim", key, start, end)) + items = self.lists.get(key, []) + # redis LTRIM inclusive end + self.lists[key] = items[start : end + 1] + return True + + def blpop(self, keys, timeout: int = 0): + self.ops.append(("blpop", tuple(keys), timeout)) + key = keys[0] + items = self.lists.get(key) or [] + if items: + value = items.pop() + self.lists[key] = items + return key, value + return None + + +def test_targets_schedule_worker_matrix(): + from app.jobs.schedule_wake import targets_schedule_worker + + assert targets_schedule_worker(domain="schedule", job_type="schedule_run") is True + assert targets_schedule_worker(domain="schedule", job_type="anything") is True + assert targets_schedule_worker(domain="default", job_type="file_check_run") is True + assert targets_schedule_worker(domain="default", job_type="wecom_directory_sync") is True + assert targets_schedule_worker(domain="shipping_notice", job_type="shipping_process_gate") is False + + +def test_notify_lpush_and_ltrim(app, monkeypatch): + from app.jobs import schedule_wake + from app.services import redis_client + + fake = _FakeRedis() + monkeypatch.setattr(redis_client, "get_redis_client", lambda: fake) + with app.app_context(): + app.config["SCHEDULE_WORKER_WAKE_ENABLED"] = True + app.config["SCHEDULE_WORKER_WAKE_REDIS_KEY"] = "hxops:jobs:wake:schedule" + assert schedule_wake.notify_schedule_worker(reason="manual") is True + assert ("lpush", "hxops:jobs:wake:schedule", "wake") in fake.ops + assert ("ltrim", "hxops:jobs:wake:schedule", 0, 7) in fake.ops + + +def test_notify_disabled_returns_false(app, monkeypatch): + from app.jobs import schedule_wake + from app.services import redis_client + + fake = _FakeRedis() + monkeypatch.setattr(redis_client, "get_redis_client", lambda: fake) + with app.app_context(): + app.config["SCHEDULE_WORKER_WAKE_ENABLED"] = False + assert schedule_wake.notify_schedule_worker() is False + assert fake.ops == [] + + +def test_notify_no_redis_returns_false(app, monkeypatch): + from app.jobs import schedule_wake + from app.services import redis_client + + monkeypatch.setattr(redis_client, "get_redis_client", lambda: None) + with app.app_context(): + app.config["SCHEDULE_WORKER_WAKE_ENABLED"] = True + assert schedule_wake.notify_schedule_worker() is False + + +def test_wait_returns_true_when_signal_present(app, monkeypatch): + from app.jobs import schedule_wake + from app.services import redis_client + + fake = _FakeRedis() + fake.lpush("hxops:jobs:wake:schedule", "wake") + monkeypatch.setattr(redis_client, "get_redis_client", lambda: fake) + with app.app_context(): + app.config["SCHEDULE_WORKER_WAKE_ENABLED"] = True + app.config["SCHEDULE_WORKER_WAKE_REDIS_KEY"] = "hxops:jobs:wake:schedule" + assert schedule_wake.wait_for_schedule_wake(1.0) is True + + +def test_wait_falls_back_to_sleep_without_redis(app, monkeypatch): + from app.jobs import schedule_wake + from app.services import redis_client + + slept: list[float] = [] + monkeypatch.setattr(redis_client, "get_redis_client", lambda: None) + monkeypatch.setattr(schedule_wake.time, "sleep", lambda seconds: slept.append(seconds)) + with app.app_context(): + app.config["SCHEDULE_WORKER_WAKE_ENABLED"] = True + assert schedule_wake.wait_for_schedule_wake(2.5) is False + assert slept == [2.5] +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `cd backend && python -m pytest tests/jobs/test_schedule_wake.py -v` + +Expected: FAIL with `ModuleNotFoundError: No module named 'app.jobs.schedule_wake'`(或 import 失败) + +- [ ] **Step 3: Implement `schedule_wake.py`** + +创建 `backend/app/jobs/schedule_wake.py`: + +```python +""" +backend/app/jobs/schedule_wake.py + +用途:schedule worker 跨进程唤醒(手动/Web 入队后打断空闲 BLPOP)。 +依赖:redis_client.get_redis_client、Flask current_app.config。 +逻辑:Web/enqueue 在事务提交后 LPUSH;runner 空闲 BLPOP(timeout=poll); + Redis 不可用或开关关闭时 fail-open(notify 返回 False,wait 退回 sleep)。 +""" + +from __future__ import annotations + +import logging +import time +from typing import Final + +from flask import current_app + +from app.services.redis_client import get_redis_client + +logger = logging.getLogger(__name__) + +_DEFAULT_KEY: Final = "hxops:jobs:wake:schedule" +_WAKE_PAYLOAD: Final = "wake" +_MAX_QUEUED_SIGNALS: Final = 8 + +# 与 app.jobs.store.claim_next 的 schedule 分支领取集合对齐 +_SCHEDULE_WORKER_JOB_TYPES: Final = frozenset( + { + "schedule_run", + "file_check_run", + "wecom_directory_sync", + } +) + + +def _wake_enabled() -> bool: + if not current_app: + return False + return bool(current_app.config.get("SCHEDULE_WORKER_WAKE_ENABLED", True)) + + +def _wake_key() -> str: + raw = "" + if current_app: + raw = str(current_app.config.get("SCHEDULE_WORKER_WAKE_REDIS_KEY") or "").strip() + return raw or _DEFAULT_KEY + + +def targets_schedule_worker(*, domain: str | None, job_type: str | None) -> bool: + """ + 判断 Job 是否由 hxops-schedule-worker 消费。 + + 核心逻辑:domain=schedule 或 job_type 属于 schedule worker 领取集合。 + + Args: + domain: jobs.domain。 + job_type: jobs.job_type 字符串。 + + Returns: + True 表示入队后应尝试唤醒 schedule worker。 + """ + if str(domain or "").strip() == "schedule": + return True + return str(job_type or "").strip() in _SCHEDULE_WORKER_JOB_TYPES + + +def notify_schedule_worker(*, reason: str = "enqueue") -> bool: + """ + Best-effort 向 Redis List 写入唤醒信号。 + + 核心逻辑:开关关闭或无 Redis 时返回 False;LPUSH 后 LTRIM 限长;异常吞掉并打 warning。 + + Args: + reason: 仅用于日志,不写入 Redis(载荷固定为 wake)。 + + Returns: + True=信号已写入;False=跳过或失败。永不向调用方抛异常。 + """ + try: + if not _wake_enabled(): + return False + client = get_redis_client() + if client is None: + return False + key = _wake_key() + client.lpush(key, _WAKE_PAYLOAD) + client.ltrim(key, 0, _MAX_QUEUED_SIGNALS - 1) + logger.info("[schedule-wake] notified key=%s reason=%s", key, reason) + return True + except Exception: + logger.warning("[schedule-wake] notify failed reason=%s", reason, exc_info=True) + return False + + +def wait_for_schedule_wake(timeout_seconds: float) -> bool: + """ + 等待唤醒信号;用于 schedule worker 空闲循环替代 time.sleep。 + + 核心逻辑:timeout<=0 时立即返回 False;开关关闭或无 Redis 时 sleep(timeout); + 否则 BLPOP(key, int(ceil(timeout))),有元素返回 True。 + + Args: + timeout_seconds: 最长等待秒数(来自 SCHEDULE_WORKER_POLL_SECONDS)。 + + Returns: + True=收到信号;False=超时或降级 sleep 结束。 + """ + timeout = max(0.0, float(timeout_seconds or 0.0)) + if timeout <= 0: + return False + try: + if not _wake_enabled(): + time.sleep(timeout) + return False + client = get_redis_client() + if client is None: + time.sleep(timeout) + return False + key = _wake_key() + # redis-py blpop timeout 为整秒;至少 1,避免 0 变非阻塞空转 + blpop_timeout = max(1, int(timeout + 0.999)) + item = client.blpop([key], timeout=blpop_timeout) + return item is not None + except Exception: + logger.warning("[schedule-wake] wait failed; falling back to sleep", exc_info=True) + time.sleep(timeout) + return False +``` + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `cd backend && python -m pytest tests/jobs/test_schedule_wake.py -v` + +Expected: PASS + +- [ ] **Step 5: Stage changes** + +```bash +git add backend/app/jobs/schedule_wake.py backend/tests/jobs/test_schedule_wake.py +``` + +--- + +### Task 2: 配置项(settings / env / compose) + +**Files:** +- Modify: `backend/app/core/config/settings.py`(在 `SCHEDULE_WORKER_POLL_SECONDS` 旁新增两行) +- Modify: `.env.shared`(§9 业务模块内、货代/排程相关注释旁新增两行) +- Modify: `docker-compose.yml`(`hxops-schedule-worker.environment` 透传) + +**Interfaces:** +- Consumes: 无 +- Produces: `app.config["SCHEDULE_WORKER_WAKE_ENABLED"]` / `["SCHEDULE_WORKER_WAKE_REDIS_KEY"]` 可供 Task 1 模块读取 + +- [ ] **Step 1: Write a failing config smoke test** + +在 `backend/tests/jobs/test_schedule_wake.py` 追加: + +```python +def test_wake_settings_defaults(app): + """关键断言:唤醒开关默认开,key 默认固定字符串。""" + with app.app_context(): + assert app.config.get("SCHEDULE_WORKER_WAKE_ENABLED") is True + assert app.config.get("SCHEDULE_WORKER_WAKE_REDIS_KEY") == "hxops:jobs:wake:schedule" + assert float(app.config.get("SCHEDULE_WORKER_POLL_SECONDS")) == 30.0 +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `cd backend && python -m pytest tests/jobs/test_schedule_wake.py::test_wake_settings_defaults -v` + +Expected: FAIL(`SCHEDULE_WORKER_WAKE_ENABLED` 为 None / 缺失) + +- [ ] **Step 3: Patch settings.py** + +在 `SCHEDULE_WORKER_POLL_SECONDS` 定义后插入: + +```python + SCHEDULE_WORKER_WAKE_ENABLED = os.getenv('SCHEDULE_WORKER_WAKE_ENABLED', 'true').lower() == 'true' + SCHEDULE_WORKER_WAKE_REDIS_KEY = ( + os.getenv('SCHEDULE_WORKER_WAKE_REDIS_KEY') or 'hxops:jobs:wake:schedule' + ).strip() or 'hxops:jobs:wake:schedule' +``` + +同步更新该文件顶部 docstring 的依赖/逻辑句(若提及 schedule worker 配置)。 + +- [ ] **Step 4: Patch `.env.shared`** + +在 `# --- 9. 业务模块 ---` 下靠近货代 RPA 注释处增加(勿打乱其它域顺序): + +```bash +# 排程 worker:空闲 poll 默认 30s;手动入队后 Redis List 唤醒(无 Redis 时 fail-open) +SCHEDULE_WORKER_WAKE_ENABLED=true +SCHEDULE_WORKER_WAKE_REDIS_KEY=hxops:jobs:wake:schedule +``` + +- [ ] **Step 5: Patch `docker-compose.yml`** + +在 `hxops-schedule-worker` 的 `environment:` 中 `SCHEDULE_WORKER_POLL_SECONDS` 旁增加: + +```yaml + - SCHEDULE_WORKER_WAKE_ENABLED=${SCHEDULE_WORKER_WAKE_ENABLED:-true} + - SCHEDULE_WORKER_WAKE_REDIS_KEY=${SCHEDULE_WORKER_WAKE_REDIS_KEY:-hxops:jobs:wake:schedule} +``` + +(backend 容器若也跑入队,已通过 `env_file` 读 `.env.shared`,无需强制再写一遍;schedule-worker 显式透传避免只挂 compose environment 时漏开关。) + +- [ ] **Step 6: Run test to verify it passes** + +Run: `cd backend && python -m pytest tests/jobs/test_schedule_wake.py -v` + +Expected: PASS + +- [ ] **Step 7: Stage changes** + +```bash +git add backend/app/core/config/settings.py .env.shared docker-compose.yml backend/tests/jobs/test_schedule_wake.py +``` + +--- + +### Task 3: 入队后 notify(commit 之后) + +**Files:** +- Modify: `backend/app/services/schedule/queue_service.py`(`enqueue_manual_schedule_run`) +- Modify: `backend/app/jobs/queue.py`(`enqueue` 在 `commit=True` 成功路径末尾) +- Modify: `backend/tests/jobs/test_schedule_queue.py` + +**Interfaces:** +- Consumes: `notify_schedule_worker(reason=...)`、`targets_schedule_worker(...)` +- Produces: 手动排程与其它 schedule-worker Job 在事务可见后发出 wake + +- [ ] **Step 1: Write the failing test for manual enqueue notify** + +在 `backend/tests/jobs/test_schedule_queue.py` 追加: + +```python +def test_manual_schedule_run_notifies_wake_after_commit(app, monkeypatch): + """关键断言:手动入队 commit 成功后调用 notify;复用活动 run 时不调用。""" + from app.services.schedule import queue_service + + calls: list[str] = [] + + def _fake_notify(*, reason: str = "enqueue") -> bool: + calls.append(reason) + return True + + monkeypatch.setattr(queue_service, "notify_schedule_worker", _fake_notify) + + with app.app_context(): + task = _create_task() + run, job_id, created = enqueue_manual_schedule_run(task.id, triggered_by_user_id=task.owner_user_id) + assert created is True and job_id > 0 + assert calls == ["manual_schedule_run"] + + calls.clear() + run2, _job2, created2 = enqueue_manual_schedule_run(task.id, triggered_by_user_id=task.owner_user_id) + assert created2 is False + assert run2.id == run.id + assert calls == [] # 未新建 Job,不应唤醒 +``` + +注意:测试里通过 `queue_service.notify_schedule_worker` 打桩,因此实现时须在 `queue_service.py` **模块级 import**: + +`from app.jobs.schedule_wake import notify_schedule_worker` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `cd backend && python -m pytest tests/jobs/test_schedule_queue.py::test_manual_schedule_run_notifies_wake_after_commit -v` + +Expected: FAIL(`notify_schedule_worker` 未定义或 calls 为空) + +- [ ] **Step 3: Wire `enqueue_manual_schedule_run`** + +在 `queue_service.py` 文件头 import 区增加 `notify_schedule_worker`;更新模块 docstring「逻辑」句:手动入队 commit 后 Redis 唤醒 schedule worker。 + +将 `enqueue_manual_schedule_run` 成功新建分支改为: + +```python + run, job_id = _create_queued_run( + task, + trigger_type="manual", + triggered_by_user_id=triggered_by_user_id, + api_request_json=api_request_json, + ) + db.session.commit() + # [STEP] 事务提交后再唤醒,避免 worker 抢在 commit 前 claim 到不可见行 + notify_schedule_worker(reason="manual_schedule_run") + return run, job_id, True +``` + +同步更新该函数 docstring:说明 commit 后 best-effort wake。 + +- [ ] **Step 4: Wire generic `enqueue` (commit=True only)** + +在 `backend/app/jobs/queue.py` 的 `enqueue` 函数中,找到 `if commit: db.session.commit()`(或等价提交)成功之后、`return job.id` 之前,插入: + +```python + if commit and targets_schedule_worker(domain=normalized_domain, job_type=normalized_type): + from app.jobs.schedule_wake import notify_schedule_worker + + notify_schedule_worker(reason=f"enqueue:{normalized_type}") +``` + +要求: +- `commit=False` **绝不** notify(schedule_run 手动路径由 Task 3 Step 3 负责) +- dedupe 复用已有 queued/running Job 时:仍可 notify(幂等唤醒无害);若实现里 early-return 已有 job,也在 **该 early-return 之前已 commit/无需 commit** 的路径上对 schedule 目标调用一次 notify——保持简单:仅在「本函数刚执行了 `db.session.commit()`」之后 notify;early-return 未写库则不 notify + +在 `queue.py` 顶部或函数内 import `targets_schedule_worker`。更新 `queue.py` 文件头「逻辑」注释。 + +- [ ] **Step 5: Add enqueue commit=True unit coverage** + +在 `backend/tests/jobs/test_schedule_wake.py` 或现有 `tests/jobs/test_types.py` 旁增加轻量测(推荐放 `test_schedule_wake.py`): + +```python +def test_generic_enqueue_schedule_domain_notifies(app, monkeypatch): + """commit=True 且 domain=schedule 时,enqueue 末尾唤醒。""" + from app.jobs import queue as job_queue + from app.jobs.types import JobType + + calls: list[str] = [] + monkeypatch.setattr( + "app.jobs.schedule_wake.notify_schedule_worker", + lambda *, reason="enqueue": calls.append(reason) or True, + ) + + with app.app_context(): + job_id = job_queue.enqueue( + JobType.SCHEDULE_RUN, + {"schedule_task_id": 1, "schedule_run_id": 1, "run_no": "RUN-WAKE-TEST"}, + domain="schedule", + business_ref="schedule_run:wake-test:freight-receipt-rpa", + dedupe_active=False, + commit=True, + ) + assert job_id > 0 + assert any(c.startswith("enqueue:") for c in calls) +``` + +若 `SCHEDULE_RUN` 对 payload 有更严校验,按 `test_schedule_queue` 现有最小 payload 对齐。 + +- [ ] **Step 6: Run tests** + +Run: + +```bash +cd backend && python -m pytest tests/jobs/test_schedule_queue.py::test_manual_schedule_run_notifies_wake_after_commit tests/jobs/test_schedule_wake.py -v +``` + +Expected: PASS + +- [ ] **Step 7: Stage changes** + +```bash +git add backend/app/services/schedule/queue_service.py backend/app/jobs/queue.py backend/tests/jobs/test_schedule_queue.py backend/tests/jobs/test_schedule_wake.py +``` + +--- + +### Task 4: runner 空闲等待改为可唤醒 + +**Files:** +- Modify: `backend/app/jobs/runner.py` +- Modify: `backend/tests/jobs/test_runner.py` + +**Interfaces:** +- Consumes: `wait_for_schedule_wake(timeout_seconds: float) -> bool` +- Produces: 仅当 `queues == ['schedule']`(单队列)时用 wait;kb/shipping/contract/transfer 行为不变 + +- [ ] **Step 1: Write the failing runner test** + +在 `backend/tests/jobs/test_runner.py` 追加: + +```python +def test_schedule_queue_idle_uses_wake_wait(monkeypatch): + """关键断言:纯 schedule 队列空闲走 wait_for_schedule_wake,不直接 time.sleep。""" + from app.jobs import runner + + events: list[str] = [] + + class _Logger: + def info(self, *_a, **_k): + pass + + def exception(self, *_a, **_k): + pass + + def error(self, *_a, **_k): + pass + + monkeypatch.setattr(runner.store, "claim_next", lambda **_k: None) + monkeypatch.setattr(runner.time, "sleep", lambda *_a, **_k: events.append("sleep") or (_ for _ in ()).throw(StopIteration)) + monkeypatch.setattr( + runner, + "wait_for_schedule_wake", + lambda timeout: events.append(f"wake:{timeout}") or (_ for _ in ()).throw(StopIteration), + ) + + with pytest.raises(StopIteration): + runner.run_forever( + SimpleNamespace(extras={"queues": ["schedule"]}, config={"SCHEDULE_WORKER_POLL_SECONDS": 30}, logger=_Logger()), + poll_interval_seconds=30, + ) + + assert events == ["wake:30"] + + +def test_shipping_queue_idle_still_sleeps(monkeypatch): + """关键断言:非 schedule 单队列仍用 time.sleep,避免误绑 Redis。""" + from app.jobs import runner + + events: list[str] = [] + + class _Logger: + def info(self, *_a, **_k): + pass + + def exception(self, *_a, **_k): + pass + + def error(self, *_a, **_k): + pass + + monkeypatch.setattr(runner.store, "claim_next", lambda **_k: None) + monkeypatch.setattr(runner.time, "sleep", lambda seconds: events.append(f"sleep:{seconds}") or (_ for _ in ()).throw(StopIteration)) + monkeypatch.setattr( + runner, + "wait_for_schedule_wake", + lambda timeout: events.append(f"wake:{timeout}") or True, + ) + + with pytest.raises(StopIteration): + runner.run_forever( + SimpleNamespace(extras={"queues": ["shipping"]}, config={}, logger=_Logger()), + poll_interval_seconds=2, + ) + + assert events == ["sleep:2"] +``` + +实现时在 `runner.py` 增加: + +`from app.jobs.schedule_wake import wait_for_schedule_wake` + +以便测试可 `monkeypatch.setattr(runner, "wait_for_schedule_wake", ...)`。 + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `cd backend && python -m pytest tests/jobs/test_runner.py::test_schedule_queue_idle_uses_wake_wait tests/jobs/test_runner.py::test_shipping_queue_idle_still_sleeps -v` + +Expected: FAIL(`wait_for_schedule_wake` 未绑定到 runner 或仍走 sleep) + +- [ ] **Step 3: Implement runner idle branch** + +更新 `runner.py` 文件头「逻辑」:schedule 单队列空闲 BLPOP 唤醒。 + +把空闲分支: + +```python + time.sleep(poll) + continue +``` + +替换为: + +```python + # schedule 单队列:用 Redis BLPOP 可打断等待;其它队列保持 sleep + if queues == ["schedule"]: + wait_for_schedule_wake(poll) + else: + time.sleep(poll) + continue +``` + +`recovery_callback` 的 tick 逻辑保持在 `claim_next` 返回 None 之后、wait/sleep **之前**(与现文件顺序一致),避免唤醒后跳过超时回收过久。 + +- [ ] **Step 4: Run runner + wake + schedule_queue tests** + +Run: + +```bash +cd backend && python -m pytest tests/jobs/test_runner.py tests/jobs/test_schedule_wake.py tests/jobs/test_schedule_queue.py -v +``` + +Expected: PASS + +- [ ] **Step 5: Stage changes** + +```bash +git add backend/app/jobs/runner.py backend/tests/jobs/test_runner.py +``` + +--- + +### Task 5: 文档 + 手工验收清单 + +**Files:** +- Modify: `docs/project_context.md`(worker 列表附近补一句唤醒说明) +- Modify: 本计划文件顶部勾选状态由执行者更新(可选) + +**Interfaces:** +- Produces: 运维可读的行为说明;无新 HTTP 字段 + +- [ ] **Step 1: Update `docs/project_context.md`** + +在提及 `hxops-schedule-worker` /「排程扫描与执行由独立 worker 承担」的段落追加一句(中文): + +> 手动触发排程(及 file-check / 企微通讯录同步等由该 worker 消费的 Job)在入队事务提交后,通过 Redis List(`SCHEDULE_WORKER_WAKE_REDIS_KEY`,默认 `hxops:jobs:wake:schedule`)唤醒空闲中的 schedule-worker;无 Redis 时仍按 `SCHEDULE_WORKER_POLL_SECONDS`(默认 30s)轮询。 + +- [ ] **Step 2: Manual verification checklist(执行者在本地/测试环境勾选)** + +1. Redis 可用;`hxops-backend` + `hxops-schedule-worker` 已加载新代码。 +2. 管理台对「收料 RPA」点一次执行。 +3. 查库:`schedule_runs.created_at` 与 `started_at` 差应 **通常 < 2s**(不再稳定出现 15~30s)。 +4. 查 trigger:`FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR` 下出现 `receipt_export_batch_.json` 的时间贴近 `started_at`。 +5. 负向:设 `SCHEDULE_WORKER_WAKE_ENABLED=false` 或断开 Redis,行为回退为最多约 30s 空等,且入队 API 不报错。 +6. cron 到期任务仍能在一个 poll 周期内入队执行(唤醒非必须)。 + +- [ ] **Step 3: Stage docs** + +```bash +git add docs/project_context.md docs/superpowers/plans/2026-09-29-schedule-worker-manual-wake.md +``` + +--- + +## Self-Review + +1. **Spec coverage:** D1 空闲 30s → Task 2/4;D2 Redis List → Task 1;D3 fail-open → Task 1 测试;D4 HTTP 不变 → 无 API 任务;D5 不做同步 trigger/前端 → 明确非目标。 +2. **Placeholder scan:** 无 TBD/TODO;测试与实现代码已写出。 +3. **Type consistency:** `notify_schedule_worker(*, reason: str) -> bool`、`wait_for_schedule_wake(timeout_seconds: float) -> bool`、`targets_schedule_worker(*, domain, job_type) -> bool` 前后一致;wake 仅在 commit 之后。 + +## Out of Scope(明确不做) + +- 同步在 API 线程写 receipt/inventory trigger +- 缩短默认 `SCHEDULE_WORKER_POLL_SECONDS` +- 前端 `RUN_NOW_POLL_MS` 加速或 SSE +- Postgres `LISTEN/NOTIFY` 替代 Redis +- 拆分 `prepare_schedule_queue` 与 claim 频率(唤醒已避免为手点而把维护打到 2s) diff --git a/docs/superpowers/plans/2026-09-29-transfer-source-error-layering.md b/docs/superpowers/plans/2026-09-29-transfer-source-error-layering.md new file mode 100644 index 00000000..e406e929 --- /dev/null +++ b/docs/superpowers/plans/2026-09-29-transfer-source-error-layering.md @@ -0,0 +1,593 @@ +# 在途调拨来源错误分层(勾选门禁 + 解析失败态 + 路由行内化)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/解析失败在勾选页处理;路由失败只行内阻断;匹配卡顶栏不再承担路由/解析主叙事。 + +**Architecture:** 在现有「调拨不维护独立抓取状态表」前提下,把解析失败挂在当日可用 `ShippingReceiptReportFile` 上(可空列 `parse_failed_at` / `parse_error_code` / `parse_error_message`)。`resolve_source_file_status` 在可用文件存在且已标记解析失败时投影 `file_status=parse_failed` 且 `has_ready_file=false`。证据同步/匹配 STEP0 对齐失败时写标记;同步成功清标记。勾选确认只提交 `has_ready_file` 来源;`retry-rpa` 对 `parse_failed` 优先重跑本地 sync(修 Profile 后不必整轮 RPA)。匹配侧删除「路由失败→整源 failed」抬升。 + +**Tech Stack:** Flask + SQLAlchemy 2 + Alembic;Vue 3 + Vitest;四语言 i18n(`chat.json`)。 + +**Spec:** 2026-09-29 会话批准的设计(bounded:C + 最小分层;无独立 spec 文件)。冻结决策: +- D1:`file_status` 扩展值 `parse_failed`(非独立字段)。 +- D2:解析失败落在**当前可用收料归档文件**上,不新建调拨抓取状态表。 +- D3:路由 `blocked_route_not_resolved` 只行内;禁止整源 `TRANSFER.ROUTE_NOT_RESOLVED` 顶栏。 +- D4:勾选确认只 emit `has_ready_file===true`(静默过滤未就绪,含 `parse_failed`)。 +- D5:不做匹配卡 B 排除条、不做勾选页路由预检、不改 stale/file_current 文案(另案)。 +- D6:`parse_failed` 可重试:优先对现有文件 `sync_and_commit_for_callback`;仍失败则保持标记;无可用文件才走原 RPA 触发。 + +## Global Constraints + +- 🔒 不提交密钥;本计划无新环境变量。 +- 🧬 表结构变更必须配套 Alembic 迁移并提交。 +- 🌍 前端新增文案必须同时补齐 `zh-CN / zh-TW / en / th` 的 `chat.json`(`chat.transfer.*`)。 +- 📝 新建/调整代码满足 AGENTS.md §5 文件头 + 函数层注释。 +- 🚫 禁止自动 commit;每任务止步于 `git add <具体文件>`。 +- ➕ 不新增第三方依赖。 +- 🧪 后端 `cd backend && python -m pytest ...`;前端相关 `cd frontend && npx vitest run `;改 frontend 后 `npm run build`。 +- 🎯 YAGNI:匹配卡顶栏仍可作「匹配当轮才发现的解析失败」兜底;主路径是勾选投影。 + +## File map + +| 文件 | 职责 | +| --- | --- | +| `backend/migrations/versions/_receipt_report_parse_failed.py` | 归档文件增加解析失败三列 | +| `backend/app/models/shipping_receipt_report.py` | 模型列 | +| `backend/app/services/in_transit_transfer/source_file_status.py` | 投影 `parse_failed`;record/clear 辅助 | +| `backend/app/services/in_transit_transfer/evidence_sync.py` | sync 成败写/清标记 | +| `backend/app/services/in_transit_transfer/matching_service.py` | 去路由整源抬升;align 失败 record | +| `backend/app/api/in_transit_transfer.py` | `retry-rpa`:parse_failed 先 re-sync | +| `frontend/src/features/chat/types/transfer.types.ts` | `file_status` 联合类型 | +| `frontend/src/features/chat/components/messages/TransferSourceSelectCard.vue` | 徽标 + confirm **只 emit ready** + isRetryable | +| `frontend/src/features/chat/components/messages/TransferMatchCard.vue` | 顶栏 `failedSources` 过滤 `TRANSFER.ROUTE_NOT_RESOLVED`(含历史卡) | +| `frontend/src/locales/*/chat.json` | `fileParseFailed` 等 | +| 对应 tests | 见各 Task | + +--- + +### Task 1: 归档文件 DDL + 模型列(parse 失败标记) + +**Files:** +- Create: `backend/migrations/versions/_add_receipt_report_parse_failed.py` +- Modify: `backend/app/models/shipping_receipt_report.py`(`ShippingReceiptReportFile`) +- Test: `backend/tests/services/in_transit_transfer/test_source_file_status.py`(本任务只加列可读;投影逻辑在 Task 2) + +**Interfaces:** +- Produces: `ShippingReceiptReportFile.parse_failed_at: datetime | None`、`parse_error_code: str | None`(≤64)、`parse_error_message: str | None`(Text)。三者全空=未失败/已清除。 + +- [ ] **Step 1: 写迁移与模型** + +在 `ShippingReceiptReportFile` 增加: + +```python +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) +``` + +迁移 `upgrade`:`op.add_column` 三列,均可空;`downgrade` drop。down_revision 接当前 head(执行时用 `flask db heads` / `flask db migrate` 生成后核对单 head)。 + +- [ ] **Step 2: 本地 upgrade** + +Run: `cd backend && flask db upgrade` +Expected: 成功;表含三列。 + +- [ ] **Step 3: Stage** + +```bash +git add backend/migrations/versions/*parse_failed*.py backend/app/models/shipping_receipt_report.py +``` + +--- + +### Task 2: `resolve_source_file_status` 投影 `parse_failed` + record/clear + +**Files:** +- Modify: `backend/app/services/in_transit_transfer/source_file_status.py` +- Test: `backend/tests/services/in_transit_transfer/test_source_file_status.py` + +**Interfaces:** +- Produces: + - `resolve_source_file_status` 返回的 `file_status` 增加 `'parse_failed'`;此时 `has_ready_file=False`,仍可带 `file_no`/`file_sha256`(便于诊断)。 + - `record_receipt_parse_failure(*, report: ShippingReceiptReportFile, error_code: str, error_message: str, now: datetime | None = None) -> None`(只 flush 不 commit) + - `clear_receipt_parse_failure(*, report: ShippingReceiptReportFile) -> None`(清空三列,flush) + +- [ ] **Step 1: 写失败测试** + +在 `test_source_file_status.py` 追加(复用既有 `receipt_unit_run` fixture + `test_report_file_is_ready` 造文件模式): + +```python +def test_usable_file_with_parse_failed_at_projects_parse_failed(app, receipt_unit_run): + """可用归档文件若已标记 parse_failed_at → file_status=parse_failed 且不可当 ready。""" + from app import db + from app.models import ShippingReceiptReportFile + + receipt_unit_run.status = 'success' + digest = hashlib.sha256(b'bad workbook').hexdigest() + db.session.add(ShippingReceiptReportFile( + unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test', + storage_key='shipping/receipt/bad.xlsx', original_filename='bad.xlsx', + file_size=16, sha256=digest, + parse_failed_at=datetime.utcnow(), + parse_error_code='TRANSFER_FILE_SCHEMA_INVALID', + parse_error_message='schema', + )) + db.session.commit() + status = resolve_source_file_status(source_code=SOURCE_CODE) + assert status["file_status"] == "parse_failed" + assert status["has_ready_file"] is False + assert status["file_sha256"] == digest + + +def test_record_and_clear_parse_failure_roundtrip(app, receipt_unit_run): + """record 写入三列;clear 清空后投影回 ready。""" + from app import db + from app.models import ShippingReceiptReportFile + from app.services.in_transit_transfer.source_file_status import ( + clear_receipt_parse_failure, + record_receipt_parse_failure, + resolve_source_file_status, + ) + + receipt_unit_run.status = 'success' + digest = hashlib.sha256(b'roundtrip').hexdigest() + report = ShippingReceiptReportFile( + unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test', + storage_key='shipping/receipt/ok.xlsx', original_filename='ok.xlsx', + file_size=16, sha256=digest, + ) + db.session.add(report) + db.session.commit() + record_receipt_parse_failure( + report=report, error_code="TRANSFER_FILE_SCHEMA_INVALID", error_message="bad", + ) + db.session.commit() + assert resolve_source_file_status(source_code=SOURCE_CODE)["file_status"] == "parse_failed" + clear_receipt_parse_failure(report=report) + db.session.commit() + assert resolve_source_file_status(source_code=SOURCE_CODE)["file_status"] == "ready" +``` + +(造数口径对齐同文件 `test_report_file_is_ready`:不手写 `created_at`,依赖默认 utcnow 落在当日可用门禁。) + +- [ ] **Step 2: Run 确认失败** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_source_file_status.py::test_usable_file_with_parse_failed_at_projects_parse_failed -q` +Expected: FAIL(尚无 `parse_failed` 分支) + +- [ ] **Step 3: 实现投影与辅助函数** + +在 `resolve_source_file_status` 命中 `usable_receipt_file_condition` 的 `report` 后: + +```python +if report.parse_failed_at is not None: + return { + 'file_status': 'parse_failed', + 'has_ready_file': False, + 'file_no': report.original_filename or str(report.id), + 'file_sha256': report.sha256, + } +``` + +`record_receipt_parse_failure`:写 `parse_failed_at=now or utcnow`、`parse_error_code[:64]`、`parse_error_message[:2000]`,`db.session.flush()`。 +`clear_receipt_parse_failure`:三列置 `None`,flush。 +更新模块 docstring:状态集含 `parse_failed`。 + +- [ ] **Step 4: Run 全文件测试** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_source_file_status.py -q` +Expected: PASS + +- [ ] **Step 5: Stage** + +```bash +git add backend/app/services/in_transit_transfer/source_file_status.py backend/tests/services/in_transit_transfer/test_source_file_status.py +``` + +--- + +### Task 3: evidence_sync / 匹配 align 写清标记;路由不再整源 failed + +**Files:** +- Modify: `backend/app/services/in_transit_transfer/evidence_sync.py`(`sync_and_commit_for_callback` / `sync_source_rows` 成功清、失败记) +- Modify: `backend/app/services/in_transit_transfer/matching_service.py`(删路由抬升循环;align 的 `ReceiptFileSchemaError` 调 `record_receipt_parse_failure`) +- Test: `backend/tests/services/in_transit_transfer/test_evidence_sync.py` +- Test: `backend/tests/services/in_transit_transfer/test_matching_service.py`(改 `test_route_not_resolved_marks_source_failed`) + +**Interfaces:** +- Consumes: Task 2 的 `record_receipt_parse_failure` / `clear_receipt_parse_failure` +- Produces: 同步成功清理当前 ready 文件标记;`ReceiptFileSchemaError`(及桥内等价解析失败)写入标记;`run_matching` 路由失败时来源 `stage` 保持 `file_ready`(有文件时),行 `result=blocked_route_not_resolved` + +- [ ] **Step 1: 改写路由测试(先失败)** + +替换 `test_route_not_resolved_marks_source_failed`: + +```python +def test_route_not_resolved_stays_row_level_not_source_failed(dbs_ready_file): + """路由缺失 → 行 blocked_route_not_resolved;来源保持 file_ready(不抬升顶栏)。""" + erp = FakeCapabilityClient() + rpa = FakeRPA() + deps = TransferDeps( + file_repository=make_ready_repo(dbs_ready_file), + rpa_trigger=rpa, + route_resolver=FakeRouteResolver(routes={}), + capabilities=erp, + ) + seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") + result = run_matching( + source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps, + ) + by_source = {stage.source_code: stage for stage in result.sources} + assert by_source["DBS-AWSBI"].stage == "file_ready" + assert by_source["DBS-AWSBI"].error_code is None + assert by_source["CRANE-SZ"].stage == "waiting_rpa_callback" + assert all( + item.result == "blocked_route_not_resolved" + for item in result.items if item.source_code == "DBS-AWSBI" + ) +``` + +- [ ] **Step 2: Run 确认失败** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_matching_service.py::test_route_not_resolved_stays_row_level_not_source_failed -q` +Expected: FAIL(仍 `stage==failed`) + +- [ ] **Step 3: 删路由整源抬升** + +在 `run_matching` 中删除对 `route_failed_sources` 的 for 循环抬升;`_matching_rows` 可停止收集/返回 `route_failed_sources`(改为返回 `(items, pending_count)`,更新所有解包点与 docstring)。 + +- [ ] **Step 4: evidence_sync 成败挂钩** + +在 `sync_source_rows` 成功路径(即将 return outcome 前):若当前 usable 文件存在,`clear_receipt_parse_failure`。 + +在 `sync_and_commit_for_callback` 的 `except`:**先** `db.session.rollback()`(保持桥隔离),**再**判断是否解析失败并独立 commit 标记: + +```python +except Exception as exc: # noqa: BLE001 + current_app.logger.warning(...) + db.session.rollback() + # [parse 投影] rollback 之后再写标记,避免脏会话;仅 schema 类失败落库 + code = getattr(exc, "code", None) or "" + if code == TRANSFER_FILE_SCHEMA_INVALID or isinstance(exc, ReceiptFileSchemaError): + report = ( + ShippingReceiptReportFile.query + .join(ShippingReceiptReportFile.unit_run) + .filter( + ShippingReceiptReportFile.unit_run.has(source_code=source_code), + usable_receipt_file_condition(), + ) + .order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc()) + .first() + ) + if report is not None: + record_receipt_parse_failure( + report=report, + error_code=str(code or TRANSFER_FILE_SCHEMA_INVALID), + error_message=str(exc)[:2000], + ) + db.session.commit() + return False +``` + +`TRANSFER_FILE_SCHEMA_INVALID` 从 `contracts` 导入;`usable_receipt_file_condition` 从 `receipt_file_gate` 导入。 + +- [ ] **Step 5: matching align 失败挂钩** + +`run_matching` 中 `align_errors` 分支:在 append `SourceProgressDTO(stage="failed", ...)` 之前,若 `error_code` 表明 schema/解析失败,对 `resolve` 到的可用文件 `record_receipt_parse_failure`(flush;随 create_matching 事务提交)。 + +- [ ] **Step 6: 补 evidence 测试 + 跑套件** + +在 `test_evidence_sync.py` 增加:模拟 sync 抛 `ReceiptFileSchemaError` → 文件带 `parse_failed_at`;成功 sync → 标记被清。 +Run: + +```bash +cd backend && python -m pytest \ + tests/services/in_transit_transfer/test_matching_service.py::test_route_not_resolved_stays_row_level_not_source_failed \ + tests/services/in_transit_transfer/test_matching_service.py::test_source_isolation_dbs_failure_does_not_block_crane \ + tests/services/in_transit_transfer/test_evidence_sync.py -q +``` + +Expected: PASS + +- [ ] **Step 7: Stage** + +```bash +git add backend/app/services/in_transit_transfer/evidence_sync.py \ + backend/app/services/in_transit_transfer/matching_service.py \ + backend/tests/services/in_transit_transfer/test_matching_service.py \ + backend/tests/services/in_transit_transfer/test_evidence_sync.py +``` + +--- + +### Task 4: `retry-rpa` 对 parse_failed 先本地重解析 + +**Files:** +- Modify: `backend/app/api/in_transit_transfer.py`(`retry_source_rpa_api`,约 L723–753) +- Test: `backend/tests/api/test_in_transit_transfer_api.py`(当前无 retry-rpa 用例,本任务新增) + +**Interfaces:** +- Consumes: `resolve_source_file_status`、`sync_and_commit_for_callback`、既有 `trigger_receipt_rpa` +- Produces: 当 `file_status==parse_failed` 且有 `file_sha256`:先 `sync_and_commit_for_callback`;成功且投影 `ready` → HTTP 200、`{"ok": true, "file_status": "ready", "reparsed": true}`(**不**返回 202/fetching);仍失败 → `ok=false`、`file_status=parse_failed`、`reparsed=true`;否则走原 `trigger_receipt_rpa`(202 + fetching)。 + +- [ ] **Step 1: 写 API 测试(失败)** + +复用该文件 `API_PREFIX = "/api/in-transit-transfer"` 与 `admin_headers`;来源码用已有种子(如 `DSV360_AWSDU` 或测试里已 create 的实例)。核心断言: + +```python +def test_retry_rpa_parse_failed_reparses_existing_file( + app, client, admin_headers, monkeypatch, +): + """parse_failed 且有可用文件 → retry 先 sync,不触发 RPA。""" + called = {"rpa": 0, "sync": 0} + + def fake_sync(*, source_code, business_date, now): + called["sync"] += 1 + # 测试内把该来源文件 parse_* 清空,使后续 resolve → ready + return True + + monkeypatch.setattr( + "app.services.in_transit_transfer.evidence_sync.sync_and_commit_for_callback", + fake_sync, + ) + monkeypatch.setattr( + "app.services.in_transit_transfer.receipt_trigger_service.trigger_receipt_rpa", + lambda **kw: called.__setitem__("rpa", called["rpa"] + 1) or {"ok": True, "callback_id": "x"}, + ) + # arrange:当日 usable ReportFile + parse_failed_at(可参考 test_source_file_status 造数) + # monkeypatch resolve 第一次返回 parse_failed+sha,或真实落库后调用 + code = "DSV360_AWSDU" + resp = client.post(f"{API_PREFIX}/sources/{code}/retry-rpa", headers=admin_headers) + assert resp.status_code == 200 + body = resp.get_json()["data"] + assert body["ok"] is True + assert body["file_status"] == "ready" + assert body.get("reparsed") is True + assert called["sync"] == 1 + assert called["rpa"] == 0 +``` + +另加:`sync` 返回 True 但投影仍 `parse_failed` → `ok is False` 且 `rpa==0`。 + +- [ ] **Step 2: 实现分支** + +在 `retry_source_rpa_api` 开头(`trigger_receipt_rpa` 之前): + +```python +from datetime import datetime +from app.services.in_transit_transfer.date_policy import business_date_now +from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback +from app.services.in_transit_transfer.source_file_status import resolve_source_file_status + +source_code = str(source_code).strip() +status = resolve_source_file_status(source_code=source_code) +if status.get("file_status") == "parse_failed" and status.get("file_sha256"): + ok = sync_and_commit_for_callback( + source_code=source_code, + business_date=str(business_date_now()), + now=datetime.utcnow(), + ) + status = resolve_source_file_status(source_code=source_code) + ready = bool(ok) and status.get("file_status") == "ready" + return _ok({ + "source_code": source_code, + "ok": ready, + "file_status": status["file_status"], + "reparsed": True, + }) +# else: 既有 trigger_receipt_rpa 路径(保持 202 + fetching) +``` + +更新该函数 docstring:parse_failed 优先本地重解析。 + +- [ ] **Step 3: Run 测试** + +Run: `cd backend && python -m pytest tests/api/test_in_transit_transfer_api.py -k retry_rpa -q` +Expected: 新用例 PASS + +- [ ] **Step 4: Stage** + +```bash +git add backend/app/api/in_transit_transfer.py backend/tests/api/test_in_transit_transfer_api.py +``` + +--- + +### Task 5: 前端类型 / 勾选卡 / 匹配卡顶栏 / 四语言 + +**Files:** +- Modify: `frontend/src/features/chat/types/transfer.types.ts` +- Modify: `frontend/src/features/chat/components/messages/TransferSourceSelectCard.vue` +- Modify: `frontend/src/features/chat/components/messages/TransferMatchCard.vue`(`failedSources`) +- Modify: `frontend/src/locales/zh-CN/chat.json`、`zh-TW/chat.json`、`en/chat.json`、`th/chat.json`(`chat.transfer.fileParseFailed`) +- Test: `frontend/src/features/chat/components/messages/TransferSourceSelectCard.spec.ts` +- Create: `frontend/src/features/chat/components/messages/TransferMatchCard.spec.ts`(仅测 failedSources 过滤;无既有 spec) + +**Interfaces:** +- Consumes: API `file_status: 'parse_failed'`;匹配卡 `sources[].error_code` +- Produces: 徽标文案;`isRetryable` 含 `parse_failed`;`confirm()` **只 emit** `has_ready_file` 来源(现状是「至少一 ready 则 emit 全部勾选」——必须改);匹配卡顶栏排除 `TRANSFER.ROUTE_NOT_RESOLVED` + +- [ ] **Step 1: 写前端失败测试** + +```typescript +it('勾选 ready+parse_failed 确认时只提交 ready 来源', async () => { + const sources = [ + { source_code: 'DSV-OK', display_name: 'ok', platform: 'dbs', enabled: true, has_ready_file: true, file_status: 'ready' as const }, + { source_code: 'DSV-BAD', display_name: 'bad', platform: 'dbs', enabled: true, has_ready_file: false, file_status: 'parse_failed' as const }, + ]; + const wrapper = mountCard({}, sources); + await wrapper.find('[data-testid="transfer-source-option-DSV-OK"] input').setValue(true); + await wrapper.find('[data-testid="transfer-source-option-DSV-BAD"] input').setValue(true); + await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click'); + expect(wrapper.emitted('confirm')?.[0][0]).toEqual(['DSV-OK']); +}); + +it('parse_failed 显示解析失败徽标且可重试', async () => { + const wrapper = mountCard({}, [ + { source_code: 'DSV-BAD', display_name: 'bad', platform: 'dbs', enabled: true, has_ready_file: false, file_status: 'parse_failed' as const }, + ]); + expect(wrapper.find('[data-testid="transfer-source-status-DSV-BAD"]').text()).toBe('解析失败'); + expect((wrapper.find('[data-testid="transfer-source-retry-DSV-BAD"]').element as HTMLButtonElement).disabled).toBe(false); +}); +``` + +修改既有「全选可见再确认」用例期望:由 +`['DBS-AWSBI', 'DBS-AWSSG', 'CRANE-SZ']` → `['DBS-AWSBI', 'CRANE-SZ']`(静默丢掉无 ready)。 + +`TransferMatchCard.spec.ts`(mount 最小 props:`sources` + 空 `items`): + +```typescript +it('顶栏不展示 ROUTE_NOT_RESOLVED 来源失败(路由只行内)', () => { + const wrapper = mount(TransferMatchCard, { + props: { + summary: { + matching_id: 'MTG-T', business_date: '2026-08-06', + executable_count: 0, blocked_count: 0, not_matured_count: 0, + pending_stock_check_count: 0, invalid_count: 0, + }, + items: [], + selected: new Set(), + sources: [ + { source_code: 'A', stage: 'failed', error_code: 'TRANSFER.ROUTE_NOT_RESOLVED', error_message: 'route not resolved' }, + { source_code: 'B', stage: 'failed', error_code: 'TRANSFER_FILE_SCHEMA_INVALID', error_message: 'schema' }, + ], + }, + global: { plugins: [i18n] }, + }); + const banner = wrapper.find('[data-testid="transfer-match-failed-sources"]'); + expect(banner.exists()).toBe(true); + expect(banner.text()).not.toContain('route not resolved'); + expect(banner.text()).toContain('schema'); +}); +``` + +(`summary` 字段以 `TransferMatchingSummary` 实际必填为准;缺字段按类型补齐默认值。) + +- [ ] **Step 2: Run 确认失败** + +```bash +cd frontend && npx vitest run \ + src/features/chat/components/messages/TransferSourceSelectCard.spec.ts \ + src/features/chat/components/messages/TransferMatchCard.spec.ts +``` + +Expected: 新用例 FAIL / 全选用例 FAIL + +- [ ] **Step 3: 实现** + +1. `transfer.types.ts`:两处 `file_status` 联合类型加入 `'parse_failed'`。 +2. `confirm()` —— **相对现状的关键 diff**:现状在 `selectedHasReadyFile` 为真时 `emit('confirm', [...selected.value], ...)`(会带上无文件勾选项);改为: + +```typescript +function confirm() { + if (selectedCount.value === 0) { + notifyWarning(t('chat.transfer.needSelectSource'), t('chat.transfer.sourceSelectTitle')); + return; + } + const readyCodes = [...selected.value].filter( + (code) => props.sources.find((s) => s.source_code === code)?.has_ready_file, + ); + if (readyCodes.length === 0) { + notifyWarning(t('chat.transfer.needReadyFile'), t('chat.transfer.sourceSelectTitle')); + return; + } + emit('confirm', readyCodes, { from: dateFrom.value || undefined, to: dateTo.value || undefined }, transferType.value); +} +``` + +3. `isRetryable`:增加 `source.file_status === 'parse_failed'`;更新函数注释。 +4. 模板:`v-else-if="source.file_status === 'parse_failed'"` 徽标 + `t('chat.transfer.fileParseFailed')`(`data-testid="transfer-source-status-..."` 复用现有)。 +5. `TransferMatchCard.vue`: + +```typescript +const HIDDEN_SOURCE_BANNER_CODES = new Set(['TRANSFER.ROUTE_NOT_RESOLVED']); + +const failedSources = computed(() => + (props.sources ?? []).filter( + (source) => + (source.error_code || source.error_message) && + !HIDDEN_SOURCE_BANNER_CODES.has(String(source.error_code || '')), + ), +); +``` + +给顶栏容器加 `data-testid="transfer-match-failed-sources"`。更新文件头注释:路由失败不进顶栏。 + +6. 四语言键(放在既有 `fileFailed` / `fileExpired` 旁): + +| 语言 | `chat.transfer.fileParseFailed` | +| --- | --- | +| zh-CN | 解析失败 | +| zh-TW | 解析失敗 | +| en | Parse failed | +| th | แยกวิเคราะห์ไม่สำเร็จ | + +- [ ] **Step 4: Run vitest + build** + +```bash +cd frontend && npx vitest run \ + src/features/chat/components/messages/TransferSourceSelectCard.spec.ts \ + src/features/chat/components/messages/TransferMatchCard.spec.ts +cd frontend && npm run build +``` + +Expected: PASS / build OK + +- [ ] **Step 5: Stage** + +```bash +git add frontend/src/features/chat/types/transfer.types.ts \ + frontend/src/features/chat/components/messages/TransferSourceSelectCard.vue \ + frontend/src/features/chat/components/messages/TransferSourceSelectCard.spec.ts \ + frontend/src/features/chat/components/messages/TransferMatchCard.vue \ + frontend/src/features/chat/components/messages/TransferMatchCard.spec.ts \ + frontend/src/locales/zh-CN/chat.json frontend/src/locales/zh-TW/chat.json \ + frontend/src/locales/en/chat.json frontend/src/locales/th/chat.json +``` + +--- + +### Task 6: 文档一句 + 回归烟雾 + +**Files:** +- Modify: `docs/features/in-transit-transfer/technical.md`(来源文件状态枚举补 `parse_failed`;错误分层一句) + +- [ ] **Step 1: 更新 technical.md** + +在描述 `/sources` 或 `file_status` 处追加:`parse_failed`=当日文件在但 movement 解析失败(`has_ready_file=false`);路由失败仅行内 `blocked_route_not_resolved`,不抬升来源顶栏。 + +- [ ] **Step 2: 定向回归** + +```bash +cd backend && python -m pytest \ + tests/services/in_transit_transfer/test_source_file_status.py \ + tests/services/in_transit_transfer/test_matching_service.py \ + tests/services/in_transit_transfer/test_evidence_sync.py \ + tests/api/test_in_transit_transfer_api.py -k "retry or source" -q +cd frontend && npx vitest run src/features/chat/components/messages/TransferSourceSelectCard.spec.ts +``` + +Expected: 全绿 + +- [ ] **Step 3: Stage** + +```bash +git add docs/features/in-transit-transfer/technical.md +``` + +--- + +## Self-review + +| 设计要求 | 任务 | +| --- | --- | +| parse_failed 扩 file_status + 落库 | T1–T2 | +| sync/align 写清标记(桥 rollback 后再 commit 标记) | T3 | +| 路由只行内(去抬升) | T3 | +| 历史匹配卡顶栏过滤 ROUTE | T5 | +| retry 先 re-sync(`str(business_date_now())`) | T4 | +| 勾选徽标 + confirm **静默过滤**非 ready + i18n | T5 | +| 文档 | T6 | +| 不做 B 排除条 / 路由预检 / stale·file_current 文案 | 全局约束 D5 | + +无 TBD 占位;接口名与仓库现状对齐(`retry_source_rpa_api`、`API_PREFIX`、`TRANSFER.ROUTE_NOT_RESOLVED`)。 diff --git a/docs/tec.md b/docs/tec.md index 7baeb6b5..670f6623 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -1432,7 +1432,7 @@ Dify - HXOPS 当前只负责配置、权限、会话与上下文注入,不直接编排多个子 Agent 的回答。 - **版本化 Excel 模板与 Artifact**:`shipping_excel_templates` 保存私有 MinIO `bucket/key`、模板文件校验和及字段映射发布版本,`shipping_inventory_sources.excel_template_id` 决定新任务使用的模板;`shipping_export_artifacts` 保存每次生成文件及所锁定的 Schema、Extraction、库存解析 Profile、库存快照、输入/文件 checksum。导出运行时从 MinIO读取模板,不读取全局模板环境变量,也不回退空白工作簿。 - **库存字段目录与确定性订单/库存关联**:库存字段目录独立于 DBS、Crane 和具体库存站点,初始化为空,所有字段由管理员创建。`field_code` 仅作为不展示的审计标识,不参与匹配、解析、仓库识别或导出。解析方案以 `inventory_field_id -> 原始表头` 保存实际列映射,以 `match_keys[].inventory_field_id` 将动态订单 `field_id` 与库存字段关联;库存快照行 JSON、结构兼容指纹和发货模板均直接使用库存字段 ID。字段用途只承担能力角色:至少一个 `match_identity`、恰好一个 `inventory_quantity`,动态仓方案恰好一个 `warehouse_identity`;`general` 字段数量不限。数组顺序和字段名称均不参与匹配,多命中仅在模板所需库存字段值一致时允许合并。 -- **库存站点启用**:库存站点首次保存一律保持停用,普通保存不承担状态切换;当前已绑定方案的配置测试成功(包括已绑定解析的空库存成功)时,回调在同一事务调用 `activate_source_if_ready` 自动启用。后端阻断条件仅为可用连接、已发布库存解析方案、已发布发货模板、模板字段契约和当前配置的连接/查询测试证据;前端不得绕过或重复该判定。数据库 CheckConstraint 继续保证启用站点绑定解析方案和 Excel 模板;测试证据必须与当前站点配置版本和已绑定方案一致,编辑站点后自动失效。无库存时,行级匹配字段、数量类型、动态仓库识别均作为首次非空文件的后续验证,不阻断启用;外部仓库映射只在实际调拨前由对应流程校验,不作为站点启用条件。解析方案新发布版本与旧 published 版本并存,站点显式迁移后旧版本方可退役。 +- **库存站点启用**:库存站点首次保存一律保持停用,普通保存不承担状态切换;启用由管理端即时开关调用独立 activate/deactivate API。后端硬门槛仅为可用连接、已发布库存解析方案、已发布发货模板及模板字段契约;测试导出不再参与启用门禁,测试回调也不再自动启用站点。已启用站点允许更换解析绑定(仍走已发布方案与模板契约校验)。数据库 CheckConstraint 继续保证启用站点绑定解析方案和 Excel 模板。外部仓库映射只在实际调拨前由对应流程校验,不作为站点启用条件。解析方案新发布版本与旧 published 版本并存,站点显式迁移后旧版本方可退役。 - **库存样本结构分析**:`shipping_inventory_structure_analyses` 保存受控库存样本的文件名、checksum、工作表/候选表头、来源栏位、类型/空值统计、结构指纹和最多五行脱敏样例,不保存完整样本文件或正式库存明细。管理端样本与配置测试文件只在即时分析期间落盘,分析完成即清理;仅对话临时库存会话可在其短期确认窗口保留受控原件。`ShippingInventoryParsingProfile.sample_analysis_id` 锁定草稿/发布版本的样本证据;创建、保存和发布均要求工作表、表头和来源栏位来自该分析记录。 - **对话临时库存文件**:用户在货代对话上传 `.xls` / `.xlsx` / `.csv` 表格后,系统先保留附件,只有用户明确声明其为库存文件才创建 `FileAsset -> shipping_temporary_inventory_sessions` 短生命周期会话;绝不依据后缀猜测库存或订单。会话同时绑定 `user_id + conversation_id + asset_id`,以 `source_kind=temporary_conversation` 保存结构审计。后端只向 Dify 返回不含样例库存值的结构预览与规则建议;不创建 `shipping_inventory_files`、不写任务库存关联、不绑定库存站点。跨聊天回合时,HXOPS 从数据库恢复当前会话最新、未过期且仍待确认的临时会话号,但不会自动路由或确认;Dify 只有识别到用户明确确认本次临时使用时,才可调用确认 Tool。所有 Tool 输出先按 `text` JSON 标准化,不能依赖 Dify 隐式会话记忆或假定的 Tool 顶层字段。Dify 仅可调用创建、读取、提交候选映射和经用户明确确认后的临时使用 Tool,不能读取二进制、路径、样例值、全量行或直接宣布库存可用于匹配。已确认会话可由管理员沉淀为解析方案草稿,但不能自动发布或绑定库存站点。 - **方案复用**:结构分析与解析方案分别保存精确结构指纹和兼容指纹,均不包含库存业务数据或文件名。精确指纹覆盖格式、工作表、表头行、标准化列名及顺序;兼容判断验证既有方案实际使用的库存匹配与数量来源表头仍存在,并输出新增/缺少/顺序变化。后端不使用固定字段词典把“内部料号”猜成 `Supplier Sku`;仅当用户字段显示名称与真实表头标准化后完全相同时给出确定性预填,其他情况由管理员选择或 Dify 提供候选。管理员确认复用只写分析审计,不更新库存站点绑定。 diff --git a/frontend/src/features/admin/api/schedule.api.ts b/frontend/src/features/admin/api/schedule.api.ts index 36eefa61..80acf421 100644 --- a/frontend/src/features/admin/api/schedule.api.ts +++ b/frontend/src/features/admin/api/schedule.api.ts @@ -159,6 +159,9 @@ 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 interface RpaWorkerHeartbeatWorker { worker_id?: string; hostname?: string; @@ -178,6 +181,7 @@ export interface RpaWorkerHeartbeatWorker { } export interface RpaWorkerHeartbeatSummary { + scope?: 'inventory' | 'receipt' | string; ready: boolean; message: string; detail_message?: string; @@ -191,7 +195,7 @@ export interface RpaWorkerHeartbeatSummary { workers: RpaWorkerHeartbeatWorker[]; } -export const getAdminRpaWorkersStatus = () => - getJson('/api/admin/rpa-workers/status'); +export const getAdminRpaWorkersStatus = (scope: 'inventory' | 'receipt' = 'inventory') => + 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/schedules/components/SchedulePageHeader.vue b/frontend/src/features/admin/modules/schedules/components/SchedulePageHeader.vue index 3ea3da8b..f39c7793 100644 --- a/frontend/src/features/admin/modules/schedules/components/SchedulePageHeader.vue +++ b/frontend/src/features/admin/modules/schedules/components/SchedulePageHeader.vue @@ -36,7 +36,7 @@ const admin = useSchedulesAdminContext(); +
+

{{ $t('admin.schedule.rawReceiptZipWecomHint') }}

+ +
(null); - /** 企微深链 raw_zip=1 进入时待手动下载的执行记录 ID;普通列表浏览不展示原始库存下载入口。 */ + /** 企微深链 raw_zip=1 进入时待手动下载的执行记录 ID;普通列表浏览不展示原始库存/收料下载入口。 */ const wecomRawZipPromptRunId = ref(null); const showTestRunDialog = ref(false); diff --git a/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminDeepLink.ts b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminDeepLink.ts index 8dc3b6ec..dcdd5baa 100644 --- a/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminDeepLink.ts +++ b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminDeepLink.ts @@ -1,6 +1,6 @@ /** * features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminDeepLink.ts - * 用途:解析企微深链 query,定位排程执行记录并在登录后自动下载原始库存包。 + * 用途:解析企微深链 query,定位排程执行记录并在登录后自动下载原始库存/收料包。 * 依赖:vue-router、schedule-admin.state、useScheduleAdminRuns。 * 逻辑:SchedulesPage onMounted 在 loadAll 后调用;消费 task_id/run_id/raw_zip/download,自动下载失败时保留手动入口。 */ @@ -16,11 +16,15 @@ function parsePositiveInt(raw: unknown): number | null { /** * 根据路由 query 打开工作台执行记录;raw_zip=1 时展开 run 并保留手动下载按钮。 - * 核心逻辑:download=inventory_raw_zip 时登录后自动下载一次;若企微内置浏览器拦截,用户仍可点醒目按钮重试。 + * 核心逻辑:download=inventory_raw_zip / receipt_raw_zip 时登录后自动下载一次; + * 若企微内置浏览器拦截,用户仍可点醒目按钮重试。 */ export function useScheduleAdminDeepLink( state: ScheduleAdminState, - runs: Pick, + runs: Pick< + ScheduleAdminRuns, + 'viewScheduleRuns' | 'downloadScheduleInventoryRawZip' | 'downloadScheduleReceiptRawZip' + >, ) { const route = useRoute(); const router = useRouter(); @@ -31,7 +35,11 @@ export function useScheduleAdminDeepLink( const runId = parsePositiveInt(route.query.run_id); const rawZipPrompt = String(route.query.raw_zip || '') === '1'; - const shouldAutoDownloadRawZip = rawZipPrompt && String(route.query.download || '') === 'inventory_raw_zip'; + const downloadKind = String(route.query.download || ''); + const shouldAutoDownloadInventory = + rawZipPrompt && downloadKind === 'inventory_raw_zip'; + const shouldAutoDownloadReceipt = + rawZipPrompt && downloadKind === 'receipt_raw_zip'; state.scheduleViewMode.value = 'workbench'; state.selectedScheduleId.value = taskId; @@ -42,11 +50,15 @@ export function useScheduleAdminDeepLink( state.expandedScheduleRunId.value = runId; if (rawZipPrompt) { const target = state.selectedScheduleRuns.value.find((item) => item.id === runId); - if (target?.inventory_raw_zip_available) { + if (target?.inventory_raw_zip_available && shouldAutoDownloadInventory) { + state.wecomRawZipPromptRunId.value = runId; + await runs.downloadScheduleInventoryRawZip(runId); + } else if (target?.receipt_raw_zip_available && shouldAutoDownloadReceipt) { + state.wecomRawZipPromptRunId.value = runId; + await runs.downloadScheduleReceiptRawZip(runId); + } else if (target?.inventory_raw_zip_available || target?.receipt_raw_zip_available) { + // 深链仅 raw_zip=1 无 download 时仍展示手动入口。 state.wecomRawZipPromptRunId.value = runId; - if (shouldAutoDownloadRawZip) { - await runs.downloadScheduleInventoryRawZip(runId); - } } } } diff --git a/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminList.ts b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminList.ts index 1e4ee1d2..b66a74f9 100644 --- a/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminList.ts +++ b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminList.ts @@ -1,9 +1,11 @@ /** * features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminList.ts * 任务列表加载、概览统计、启停/立即执行/删除与视图切换。 - * 等待轮询策略:点「立即执行」后每 RUN_NOW_POLL_MS 刷新记录与列表,直到任务离开 running; - * 同一任务仅保留一个轮询(重复点击先清旧定时器)、上一轮未返回时跳过本轮, - * 并设 RUN_NOW_POLL_MAX_MS 上限,防止任务长时间不终态造成页面无限请求。 + * 等待轮询策略:点「立即执行」后只轻量刷新任务 last_status(不刷执行记录 runs), + * 直到离开 running 再拉一次 runs;与「执行记录=历史查询、不做定时刷新」对齐。 + * 同一任务仅保留一个轮询、上一轮未返回时跳过,并设 RUN_NOW_POLL_MAX_MS 上限。 + * 库存/收料 RPA 写 trigger 后会长时间保持 running(awaiting callback),旧逻辑每 5s + * 全量 runs + loading 遮罩会把收料工作台打成「正在查询记录…」连环请求。 */ import { computed } from 'vue'; import type { ComposerTranslation } from 'vue-i18n'; @@ -18,7 +20,7 @@ import { useMessage } from '@/shared/composables/useMessage'; import type { ScheduleAdminState } from './schedule-admin.state'; import type { ScheduleAdminRuns } from './useScheduleAdminRuns'; -/** 立即执行后的等待轮询间隔 */ +/** 立即执行后的等待轮询间隔(仅任务列表 last_status) */ const RUN_NOW_POLL_MS = 5_000; /** 等待轮询总上限:与服务端库存导出超时(默认 900s)对齐,超限后停止自动刷新提示手动查询 */ const RUN_NOW_POLL_MAX_MS = 15 * 60_000; @@ -47,7 +49,12 @@ export function useScheduleAdminList( const scheduleDisabledCount = computed(() => schedules.value.filter((item) => !item.enabled).length); const scheduleRunningCount = computed(() => schedules.value.filter((item) => item.last_status === 'running').length); - const loadSchedules = async () => { + /** + * 加载排程任务列表;可选顺带刷新当前工作台执行记录。 + * @param options.includeRuns - 工作台模式下是否拉取 runs;立即执行等待轮询传 false,避免连环打 API + */ + const loadSchedules = async (options?: { includeRuns?: boolean }) => { + const includeRuns = options?.includeRuns !== false; scheduleLoading.value = true; try { schedules.value = await listAdminSchedules(); @@ -62,7 +69,7 @@ export function useScheduleAdminList( if (!exists && nextScheduleId) { selectedScheduleId.value = nextScheduleId; } - if (scheduleViewMode.value === 'workbench' && nextScheduleId) { + if (includeRuns && scheduleViewMode.value === 'workbench' && nextScheduleId) { await runs.viewScheduleRuns(nextScheduleId); } } finally { @@ -83,6 +90,11 @@ export function useScheduleAdminList( scheduleViewMode.value = 'overview'; }; + /** + * 立即执行排程;等待期只轮询任务 last_status,不定时刷新执行记录。 + * 核心逻辑:触发后先拉一次 runs;之后每 RUN_NOW_POLL_MS 仅 listAdminSchedules; + * 终态或超时后再拉一次 runs。库存/收料共用,避免 RPA awaiting 长 running 连环打 runs。 + */ const runScheduleNow = async (taskId: number) => { try { await runAdminSchedule(taskId); @@ -90,8 +102,9 @@ export function useScheduleAdminList( msg.error(err?.message || t('admin.schedule.msg.runNowFailed')); return; } + // [STEP 1] 触发后立刻展示本轮记录一次;任务列表不重复带 runs await runs.viewScheduleRuns(taskId, true); - await loadSchedules(); + await loadSchedules({ includeRuns: false }); // 同一任务只保留一个等待轮询:重复点击先停旧定时器,避免多路 interval 并行放大请求频率 const previousPoll = runNowPollTimers.get(taskId); @@ -103,8 +116,8 @@ export function useScheduleAdminList( if (runNowPollsInFlight.has(taskId)) return; runNowPollsInFlight.add(taskId); try { - await runs.viewScheduleRuns(taskId, true); - await loadSchedules(); + // [STEP 2] 等待期只刷新 last_status,禁止 viewScheduleRuns(否则工作台会遮「正在查询记录…」) + await loadSchedules({ includeRuns: false }); elapsedMs += RUN_NOW_POLL_MS; const target = schedules.value.find((s: ScheduleTask) => s.id === taskId); const terminal = !!target?.last_status && target.last_status !== 'running'; @@ -112,6 +125,10 @@ export function useScheduleAdminList( if (terminal || timedOut) { clearInterval(pollInterval); runNowPollTimers.delete(taskId); + // [STEP 3] 终态/超时后再拉一次执行记录,给表格最终结果 + if (scheduleViewMode.value === 'workbench') { + await runs.viewScheduleRuns(taskId, true); + } if (timedOut && !terminal) { msg.warning(t('admin.schedule.msg.runNowWaitTimeout')); } diff --git a/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminRuns.ts b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminRuns.ts index 74b53486..87e45561 100644 --- a/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminRuns.ts +++ b/frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminRuns.ts @@ -2,15 +2,17 @@ * features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminRuns.ts * 执行批次列表:筛选、列宽、展开详情、Excel 下载、指标派生与 RPA Worker 心跳轮询。 * 轮询策略(历史查询与监控职责分离):执行记录列表是纯历史查询,仅切任务/查询/重置时按需加载; - * RPA Worker 在线状态是监控信号,仅在库存排程工作台模式下每 RPA_WORKER_STATUS_POLL_MS 静默轮询一次, + * RPA Worker 在线状态是监控信号,仅在库存/收料排程工作台模式下每 RPA_WORKER_STATUS_POLL_MS 静默轮询一次, * 后台标签页暂停、请求未返回时跳过(防堆叠),使「在线/离线」徽标及时反映心跳。 + * 收料/库存排程的跳过列与统计砖分别显示「无收料/跳过」「无库存/跳过」。 */ import { computed, onBeforeUnmount, watch, type Ref } from 'vue'; import type { ComposerTranslation } from 'vue-i18n'; -import { listAdminScheduleRuns, adminRunInventoryRawZipUrl, getAdminRpaWorkersStatus } from '@/features/admin/api/schedule.api'; +import { listAdminScheduleRuns, adminRunInventoryRawZipUrl, adminRunReceiptRawZipUrl, getAdminRpaWorkersStatus } from '@/features/admin/api/schedule.api'; import { useMessage } from '@/shared/composables/useMessage'; import { getAuthHeaders } from '@/shared/utils/auth'; import { formatDateTime } from '../../utils/schedule-format.utils'; +import { normalizePlatformJobKey } from '../../utils/schedule-job-key.utils'; import { getScheduleRunFailedCountTitle as buildScheduleRunFailedCountTitle, isScheduleRunExcelExportFailed, @@ -39,7 +41,31 @@ export function useScheduleAdminRuns( scheduleViewMode, } = state; + const selectedSchedule = computed(() => + schedules.value.find((item) => item.id === selectedScheduleId.value) || null, + ); + + const selectedScheduleJobKey = computed( + () => normalizePlatformJobKey(selectedSchedule.value?.platform_api_path), + ); + + const isInventoryRpaSchedule = computed( + () => selectedScheduleJobKey.value === 'shipping-inventory-rpa', + ); + + const isReceiptRpaSchedule = computed( + () => selectedScheduleJobKey.value === 'freight-receipt-rpa', + ); + + /** + * 同步执行记录列表表头文案;收料/库存排程的「跳过」列分别显示无收料/无库存。 + */ const syncScheduleRunColumnLabels = () => { + const skippedKey = isReceiptRpaSchedule.value + ? 'skippedCountReceipt' + : isInventoryRpaSchedule.value + ? 'skippedCountInventory' + : 'skippedCount'; const keyToI18n: Record = { run_no: 'runNo', started_at: 'startedAt', @@ -47,7 +73,7 @@ export function useScheduleAdminRuns( status: 'status', total_count: 'totalCount', success_count: 'successCount', - skipped_count: 'skippedCount', + skipped_count: skippedKey, failed_count: 'failedCount', wecom_notified: 'wecomNotified', detail: 'detail', @@ -58,7 +84,11 @@ export function useScheduleAdminRuns( if (i18nKey) col.label = t(`admin.schedule.columns.${i18nKey}`); }); }; - watch(locale, syncScheduleRunColumnLabels, { immediate: true }); + watch( + [locale, isReceiptRpaSchedule, isInventoryRpaSchedule], + syncScheduleRunColumnLabels, + { immediate: true }, + ); const onScheduleColResizeMove = (event: MouseEvent) => { const resizeState = resizingScheduleCol.value; @@ -88,10 +118,6 @@ export function useScheduleAdminRuns( window.addEventListener('mouseup', stopScheduleColResize); }; - const selectedSchedule = computed(() => - schedules.value.find((item) => item.id === selectedScheduleId.value) || null, - ); - const scheduleRunStatusOptions = computed(() => [ { value: 'all', label: t('admin.schedule.status.all') }, { value: 'success', label: t('admin.schedule.status.success') }, @@ -152,8 +178,13 @@ export function useScheduleAdminRuns( return raw ? formatDateTime(raw) : '-'; }); - const isInventoryRpaSchedule = computed( - () => selectedSchedule.value?.platform_api_path === 'shipping-inventory-rpa', + /** 库存或收料排程工作台均展示 RPA Worker 心跳徽标。 */ + const showsRpaWorkerStatus = computed( + () => isInventoryRpaSchedule.value || isReceiptRpaSchedule.value, + ); + + const rpaWorkerStatusScope = computed<'inventory' | 'receipt'>(() => + (isReceiptRpaSchedule.value ? 'receipt' : 'inventory'), ); const rpaWorkerLastHeartbeatAt = computed(() => { @@ -171,13 +202,13 @@ export function useScheduleAdminRuns( * @param silent - 静默模式:由后台轮询调用,不翻转 loading,避免徽标每轮闪烁「加载中」 */ const refreshRpaWorkerStatus = async (silent = false) => { - if (!isInventoryRpaSchedule.value) { + if (!showsRpaWorkerStatus.value) { rpaWorkerStatus.value = null; return; } if (!silent) rpaWorkerStatusLoading.value = true; try { - rpaWorkerStatus.value = await getAdminRpaWorkersStatus(); + rpaWorkerStatus.value = await getAdminRpaWorkersStatus(rpaWorkerStatusScope.value); } catch { rpaWorkerStatus.value = null; } finally { @@ -185,14 +216,14 @@ export function useScheduleAdminRuns( } }; - // ── RPA Worker 心跳轮询(监控信号,仅库存排程) ───────────────────────── + // ── RPA Worker 心跳轮询(监控信号,库存/收料排程) ─────────────────────── // 心跳由 Worker 每约 20s 上报一次(服务端 TTL 默认 90s),UI 每 10s 刷新即足够; // 2s 固定轮询只有少量时间点在变化,属于对无变化数据的过度请求。 const RPA_WORKER_STATUS_POLL_MS = 10_000; - /** 是否需要前台轮询心跳:仅工作台模式且当前排程为库存类(该徽标仅在此时可见) */ + /** 是否需要前台轮询心跳:工作台模式且当前排程为库存或收料类 */ const shouldPollRpaWorkerStatus = computed( - () => scheduleViewMode.value === 'workbench' && isInventoryRpaSchedule.value && !!selectedScheduleId.value, + () => scheduleViewMode.value === 'workbench' && showsRpaWorkerStatus.value && !!selectedScheduleId.value, ); let rpaStatusPollTimer: ReturnType | null = null; @@ -301,6 +332,27 @@ export function useScheduleAdminRuns( URL.revokeObjectURL(url); }; + /** + * 下载收料原始 ZIP;API 与文件名口径对齐库存 raw zip。 + */ + const downloadScheduleReceiptRawZip = async (runId: number) => { + const res = await fetch(adminRunReceiptRawZipUrl(runId), { headers: getAuthHeaders() }); + if (!res.ok) { + msg.error(t('admin.schedule.msg.downloadReceiptRawZipFailed')); + return; + } + const blob = await res.blob(); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + const disposition = res.headers.get('content-disposition'); + a.download = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || '收料RPA-收料.zip'; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }; + const getScheduleRunFailedCountTitle = (run: (typeof selectedScheduleRuns.value)[number]) => buildScheduleRunFailedCountTitle(run, t('admin.schedule.excelExportFailedHint')); @@ -315,12 +367,15 @@ export function useScheduleAdminRuns( selectedScheduleRunMetrics, selectedScheduleLatestRunAt, isInventoryRpaSchedule, + isReceiptRpaSchedule, + showsRpaWorkerStatus, rpaWorkerLastHeartbeatAt, refreshRpaWorkerStatus, resetScheduleRunFilters, viewScheduleRuns, downloadScheduleExcel, downloadScheduleInventoryRawZip, + downloadScheduleReceiptRawZip, startScheduleColResize, formatDateTime, isScheduleRunExcelExportFailed, diff --git a/frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue b/frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue index 33e442c1..c29e9ed6 100644 --- a/frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue +++ b/frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue @@ -124,39 +124,40 @@ - -
{{ t('admin.shippingInventory.sourceSavedDisabledHint') }}
-
@@ -166,7 +167,7 @@ -
{{ t('admin.shippingInventory.queryParameters') }}{{ t('admin.shippingInventory.receiptQueryParametersHint') }}
+
{{ t('admin.shippingInventory.queryParameters') }}
@@ -177,8 +178,7 @@
-

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

- +
@@ -356,49 +356,35 @@
{{ t('admin.shippingInventory.enabled') }}
-
-
- - - +
+ -
- {{ t('admin.shippingInventory.activationOptionalTitle') }}{{ t('admin.shippingInventory.readinessOptionalPending', { count: optionalReadinessPending }) }} -
    -
  1. - -
    {{ t(`admin.shippingInventory.activationRequirement.${check.code}`) }}{{ readinessDetail(check) }}
    -
  2. -
-
- -
-
+
@@ -412,6 +398,7 @@
+
@@ -445,7 +432,7 @@