diff --git a/.dbg/login-401.env b/.dbg/login-401.env deleted file mode 100644 index 9d3c97a9..00000000 --- a/.dbg/login-401.env +++ /dev/null @@ -1,2 +0,0 @@ -DEBUG_SERVER_URL=http://127.0.0.1:7778/event -DEBUG_SESSION_ID=login-401 diff --git a/.dbg/trae-debug-log-app-open-error.ndjson b/.dbg/trae-debug-log-app-open-error.ndjson deleted file mode 100644 index fa20368d..00000000 --- a/.dbg/trae-debug-log-app-open-error.ndjson +++ /dev/null @@ -1,2 +0,0 @@ -{"sessionId": "app-open-error", "runId": "pre-fix", "hypothesisId": "A", "location": "src/main.ts:8", "msg": "[DEBUG] Frontend bootstrap started", "data": {"href": "http://192.168.100.192:8910/config"}, "ts": 1788828493927} -{"sessionId": "app-open-error", "runId": "pre-fix", "hypothesisId": "C", "location": "src/main.ts:16", "msg": "[DEBUG] Vue app mounted", "data": {"appChildren": 1}, "ts": 1788828493938} diff --git a/.env.dev b/.env.dev index 2589e35b..dfd12de8 100644 --- a/.env.dev +++ b/.env.dev @@ -1,4 +1,4 @@ -# ============================================================================= +# ============================================================================= # Development — docker compose / deploy_compose.sh dev # Environment-specific variables stay in .env.dev/.env.test/.env.prod # - .env.dev / .env.test / .env.prod for deployment environments @@ -104,8 +104,8 @@ SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true # 复核工作台字段级 AI 建议;仅开发环境启用,建议仍须证据校验与人工裁决 SHIPPING_NOTICE_LLM_REVIEW_ENABLED=true -SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true -SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true +SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true +SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED=true SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true @@ -134,28 +134,31 @@ SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 -FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900 +FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS=900 FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3 FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30 SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx -# RPA 目录(相对 backend/ 根目录,统一 freight_rpa/{inventory,receipt,common} 三层布局) -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 +# RPA 目录(相对 backend/ 根;freight_rpa/{onhand,inbound,outbound,upload,common},2026-10-16 批次 R) +FREIGHT_RPA_SHARED_ONHAND_DROP_DIR=data/freight_rpa/onhand/drop +FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR=data/freight_rpa/onhand/triggers +FREIGHT_RPA_SHARED_INBOUND_DROP_DIR=data/freight_rpa/inbound/drop +FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR=data/freight_rpa/inbound/triggers +FREIGHT_RPA_INBOUND_ARCHIVE_DIR=data/freight_rpa/inbound/archives +FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR=data/freight_rpa/outbound/drop +FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR=data/freight_rpa/outbound/triggers +FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR=data/freight_rpa/outbound/archives +FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=data/freight_rpa/upload/queue +FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/freight_rpa/upload/triggers FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR=data/freight_rpa/common/browser_profile # AWS 库存列映射(可选 JSON 字符串) # FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"} -# 本地 RPA(scripts/freight_rpa/inventory/inventory_rpa_worker.py) +# 本地 RPA(scripts/freight_rpa/onhand/onhand_rpa_worker.py) FREIGHT_RPA_WORKER_MOCK=false # 本机无 Redis 时允许进程内存记录心跳;有 Redis 时优先写 Redis FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK=true # FREIGHT_RPA_WORKER_POLL_SECONDS=3 -# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY= +# FREIGHT_RPA_WORKER_SAMPLE_ONHAND= # --- 10. 运维、告警与维护工具 --- # 设备维保助手后端工具调用密钥 MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu diff --git a/.env.prod b/.env.prod index fda0b812..26fea92f 100644 --- a/.env.prod +++ b/.env.prod @@ -1,4 +1,4 @@ -# ============================================================================= +# ============================================================================= # Production — docker compose env_file + deploy_compose.sh prod # Environment-specific variables stay in .env.dev/.env.test/.env.prod # - .env.dev / .env.test / .env.prod for deployment environments @@ -118,8 +118,8 @@ SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true # 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享) -SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true -SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true +SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true +SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED=true # 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥) SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 @@ -142,21 +142,24 @@ SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=false FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE= # 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致) FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data -FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900 +FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS=900 FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 # 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微 FREIGHT_RPA_WORKER_ALERT_USERNAMES= FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN=true FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120 FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600 -# RPA 目录(正式环境:Ubuntu 挂载 Windows RPA 正式共享,统一 freight_rpa/{inventory,receipt,common} 三层布局) -FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/drop -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 +# RPA 目录(正式:Ubuntu 挂载 Windows 共享;freight_rpa/{onhand,inbound,outbound,upload,common}) +FREIGHT_RPA_SHARED_ONHAND_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/onhand/drop +FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/onhand/triggers +FREIGHT_RPA_SHARED_INBOUND_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inbound/drop +FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inbound/triggers +FREIGHT_RPA_INBOUND_ARCHIVE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inbound/archives +FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/outbound/drop +FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/outbound/triggers +FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/outbound/archives +FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/upload/queue +FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/upload/triggers # 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问) FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod # 订单交期回复 Agent(2026-10-10 上线边界):只同步订单日期 ≥ 起始日的订单行,早于边界的历史行随 erp_missing 语义自动移出工作台;留空/删除 = 全量同步(dev/test 不配置) diff --git a/.env.shared b/.env.shared index b362c461..e2d81f92 100644 --- a/.env.shared +++ b/.env.shared @@ -238,7 +238,6 @@ 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 2b64a2d9..155991c7 100644 --- a/.env.test +++ b/.env.test @@ -1,4 +1,4 @@ -# ============================================================================= +# ============================================================================= # Test — docker compose / deploy_compose.sh test # Environment-specific variables stay in .env.dev/.env.test/.env.prod # - .env.dev / .env.test / .env.prod for deployment environments @@ -117,8 +117,8 @@ SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true -SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true -SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true +SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true +SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED=true SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true @@ -151,8 +151,8 @@ SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data # 两域超时须覆盖最坏批次总时长(10 站串行 + 单站失败重试可达 30 分钟+), # 否则每轮对账会把仍在飞的健康批次误回收(2026-10-08 RUN20261008003113B726 实测教训) -FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=3600 -FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS=3600 +FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS=3600 +FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS=3600 FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3 FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30 FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 @@ -165,20 +165,23 @@ FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120 FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600 SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx FREIGHT_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns= -# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享,统一 freight_rpa/{inventory,receipt,common} 三层布局) -FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/drop -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 +# RPA 目录(测试:Ubuntu 挂载 Windows 共享;freight_rpa/{onhand,inbound,outbound,upload,common}) +FREIGHT_RPA_SHARED_ONHAND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/onhand/drop +FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/onhand/triggers +FREIGHT_RPA_SHARED_INBOUND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/drop +FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/triggers +FREIGHT_RPA_INBOUND_ARCHIVE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/archives +FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/outbound/drop +FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/outbound/triggers +FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/outbound/archives +FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/upload/queue +FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/upload/triggers # AWS 库存列映射(可选 JSON 字符串) # FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"} -# 本地 Mock RPA(scripts/freight_rpa/inventory/inventory_rpa_worker.py,可选) +# 本地 Mock RPA(scripts/freight_rpa/onhand/onhand_rpa_worker.py,可选) # FREIGHT_RPA_WORKER_MOCK=true # FREIGHT_RPA_WORKER_POLL_SECONDS=3 -# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY= +# FREIGHT_RPA_WORKER_SAMPLE_ONHAND= # 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问) FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test # --- 10. 运维、告警与维护工具 --- diff --git a/AGENTS.md b/AGENTS.md index f250a497..f5ad7f2c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -164,7 +164,7 @@ docker compose logs -f hxops-backend - **文件内章节顺序**:① 环境与应用标识 → ② 应用运行与进程 → ③ 公共地址与网络入口 → ④ 安全、认证与身份源 → ⑤ 数据库与基础设施 → ⑥ AI 平台、模型与内部工具 → ⑦ 企业系统集成 → ⑧ 知识库与文件处理 → ⑨ 业务模块 → ⑩ 运维、告警与维护工具;文件没有某类变量时直接省略该章节。 - **章节内组织**:先按业务域及子域聚合(如 Casdoor、MinIO、WeCom、HR、PLM、SRM、FAQ、Shipping Notice、Fixed Asset),不得把同一域拆散后做全局字母排序;同一域内按“开关/模式 → 地址 → 标识 → 凭据 → 路径 → 业务参数 → 超时/重试/并发 → 兼容/Mock”排列,同级变量再按字母排序。 - **数据库连接固定顺序**:`HOST → PORT → DATABASE/SID → USERNAME → PASSWORD → DRIVER → ENCRYPT/TRUST_CERT → TIMEOUT`;完整连接串(如 `DATABASE_URL`、`*_DSN`)置于该数据源首位。 -- **RPA 命名空间(强制,2026-09-18 修订)**:货代 RPA(库存/收料/上传及后续新增 Worker)统一使用 `FREIGHT_RPA_*`。后端业务参数使用 `FREIGHT_RPA_<配置项>`,后端与 Windows Worker 的共享目录/标识使用 `FREIGHT_RPA_SHARED_*`,Windows Worker 自身运行参数使用 `FREIGHT_RPA_WORKER_*`,平台凭据主密钥使用 `FREIGHT_RPA_CREDENTIAL_KEY`。禁止新增 `SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`。历史名称 `SHIPPING_NOTICE_RPA_*` 于 2026-09-18 未上线期一刀切废弃,**不设兼容层**;RPA 运行期数据统一存放于独立 `freight_rpa/` 根下,按 `inventory/`、`receipt/`、`common/` 分域(common 仅放跨 Worker 共享物,如 browser_profile)。 +- **RPA 命名空间(强制,2026-09-18 修订)**:货代 RPA(库存/收料/上传及后续新增 Worker)统一使用 `FREIGHT_RPA_*`。后端业务参数使用 `FREIGHT_RPA_<配置项>`,后端与 Windows Worker 的共享目录/标识使用 `FREIGHT_RPA_SHARED_*`,Windows Worker 自身运行参数使用 `FREIGHT_RPA_WORKER_*`,平台凭据主密钥使用 `FREIGHT_RPA_CREDENTIAL_KEY`。禁止新增 `SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`。历史名称 `SHIPPING_NOTICE_RPA_*` 于 2026-09-18 未上线期一刀切废弃,**不设兼容层**;RPA 运行期数据统一存放于独立 `freight_rpa/` 根下,按 `onhand/`、`inbound/`、`outbound/`(抓取域,叶目录同构 triggers/drop/logs/archives)、`upload/`(上传域,triggers/queue)、`common/`(跨 Worker 共享物,如 browser_profile)分域(2026-10-16 批次 R:原 inventory/receipt 已随迁)。 - **跨环境一致性**:`.env.dev`、`.env.test`、`.env.prod` 使用相同章节骨架;同名变量保持相同相对位置,便于审查差异;新增变量时同步检查所有适用环境文件和上述权威文档。 - **调整红线**:重排环境变量时只能移动“注释 + 完整赋值行”,禁止修改变量名或值,禁止删除变量、注释或示例;真实密码、密钥、Token、Webhook 与生产连接信息必须由系统环境变量、Jenkins/CI 或 Secret 管理机制注入。 diff --git a/backend/app/__init__.py b/backend/app/__init__.py index e9e44edd..7e658358 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -79,6 +79,20 @@ def create_app(config_name='default'): _transfer_capabilities.register_transfer_capabilities() + # onhand/inbound/outbound RPA 回调 sink 注册(幂等):按消费域分组合根—— + # onhand → shipping_notice.rpa_sinks;inbound/outbound → in_transit_transfer.rpa_sinks。 + # 进度类经 callback_sinks.dispatch_sink;文件事实经 reports.dispatch; + # 未注册 kind 显式 404(FREIGHT_RPA.SINK_NOT_REGISTERED)。 + from app.services.in_transit_transfer.rpa_sinks import ( + register_inbound_sinks, + register_outbound_sinks, + ) + from app.services.shipping_notice.rpa_sinks import register_onhand_sinks + + register_onhand_sinks() + register_inbound_sinks() + register_outbound_sinks() + # 启动时强制加载一次,避免 worker 冷启动到首个请求之间仍用镜像默认值。 with app.app_context(): _apply_persisted_settings(app, force=True) @@ -149,7 +163,7 @@ def create_app(config_name='default'): # 负责(dev Wave 4),Web 进程不再兜底扫描。 # AUTO_UPLOAD 显式开启时启动级校验货代上传 RPA(仅告警,不阻断启动)。 try: - from app.services.shipping_notice.rpa_worker_heartbeat import ( + from app.services.freight_rpa.common.worker_heartbeat import ( log_auto_upload_readiness_at_startup, ) log_auto_upload_readiness_at_startup(app) diff --git a/backend/app/api/__init__.py b/backend/app/api/__init__.py index c3d462be..5d22c7df 100644 --- a/backend/app/api/__init__.py +++ b/backend/app/api/__init__.py @@ -47,6 +47,7 @@ def register_blueprints(app: Flask) -> None: procurement_contract_bp, shipping_notice_bp, ) + from app.api.freight_rpa import freight_rpa_bp from app.api.files import files_bp from app.api.contract_payment import contract_payment_bp from app.api.equipment_acceptance import equipment_acceptance_bp @@ -71,6 +72,7 @@ def register_blueprints(app: Flask) -> None: app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs') app.register_blueprint(maintenance_bp, url_prefix='/api/maintenance') app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice') + app.register_blueprint(freight_rpa_bp, url_prefix='/api/freight-rpa') app.register_blueprint(file_check_bp, url_prefix='/api/file-check') app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context') app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance') diff --git a/backend/app/api/admin/__init__.py b/backend/app/api/admin/__init__.py index 9ce698ab..752c03a7 100644 --- a/backend/app/api/admin/__init__.py +++ b/backend/app/api/admin/__init__.py @@ -23,7 +23,8 @@ import app.api.admin.shipping_order_extraction # noqa: F401 import app.api.admin.announcements # noqa: F401 import app.api.admin.shipping_customers # noqa: F401 import app.api.admin.shipping_identity_rules # noqa: F401 -import app.api.admin.shipping_inventory # noqa: F401 +import app.api.admin.shipping_notice_admin # noqa: F401 +import app.api.admin_freight_rpa # noqa: F401 import app.api.admin.shipping_order_schema # noqa: F401 import app.api.admin.shipping_field_assets # noqa: F401 import app.api.admin.shipping_order_document_profiles # noqa: F401 @@ -32,5 +33,6 @@ import app.api.admin.shipping_process_gate # noqa: F401 import app.api.admin.linked_services # noqa: F401 import app.api.admin.procurement_contract # noqa: F401 import app.api.admin.training_configs # noqa: F401 +import app.api.admin.transfer_type # noqa: F401 __all__ = ['admin_bp'] diff --git a/backend/app/api/admin/shipping_inventory.py b/backend/app/api/admin/shipping_inventory.py deleted file mode 100644 index 27b77bfd..00000000 --- a/backend/app/api/admin/shipping_inventory.py +++ /dev/null @@ -1,617 +0,0 @@ -""" -api/admin/shipping_inventory.py - -用途:提供库存源、RPA Profile、路由规则及外部系统映射的管理 API。 -依赖:admin blueprint、require_admin、shipping_inventory_service。 -逻辑:路由只处理鉴权和 JSON 参数,业务校验、凭据加密及事务由服务层完成。 -""" - -from __future__ import annotations - -import json - -from flask import g, request, send_file - -from app.api.admin.blueprint import admin_bp -from app.core.decorators import require_admin -from app.core.errors import ConflictError -from app.core.response import ok -from app.services.admin import shipping_inventory_service -from app.services.shipping_notice.order_schema import service as order_schema_service -from app.services.shipping_notice import inventory_parsing_profile -from app.services.shipping_notice import excel_template -from app.services.shipping_notice import inventory_field_catalog -from app.services.shipping_notice import inventory_structure_analysis - - -def _actor_id() -> int | None: - """取得 require_admin 已写入请求上下文的管理员 ID。""" - return getattr(getattr(g, 'current_user', None), 'id', None) - - -def _ok(data, *, status: int = 200): - """按平台统一 envelope 返回管理 API 成功结果。""" - return ok(data, request_id=getattr(g, 'request_id', None), status=status) - - -@admin_bp.route('/shipping-notice/excel-templates', methods=['GET']) -@require_admin -def list_shipping_excel_templates(): - """列出版本化发货 Excel 模板。""" - return _ok(excel_template.list_templates()) - - -@admin_bp.route('/shipping-notice/excel-templates', methods=['POST']) -@require_admin -def create_shipping_excel_template(): - """上传 xlsx 并创建模板草稿版本。""" - try: - definition = json.loads(request.form.get('definition') or '{}') - except json.JSONDecodeError as exc: - from app.core.errors import ValidationError - raise ValidationError('definition must be valid JSON', code='SHIPPING.EXCEL_TEMPLATE_INVALID') from exc - data = { - 'template_code': request.form.get('template_code'), - 'display_name': request.form.get('display_name'), - 'definition': definition, - } - return _ok(excel_template.create_draft(request.files.get('file'), data, actor_id=_actor_id()), status=201) - - -@admin_bp.route('/shipping-notice/excel-templates/', methods=['PUT']) -@require_admin -def update_shipping_excel_template(template_id: int): - """更新 Excel 模板草稿定义。""" - return _ok(excel_template.update_draft(template_id, request.get_json(silent=True) or {})) - - -@admin_bp.route('/shipping-notice/excel-templates//layout', methods=['GET']) -@require_admin -def get_shipping_excel_template_layout(template_id: int): - """读取已保存模板的工作表和栏位,编辑时无需重新上传 Excel。""" - return _ok(excel_template.get_layout(template_id)) - - -@admin_bp.route('/shipping-notice/excel-templates//new-version', methods=['POST']) -@require_admin -def create_shipping_excel_template_version(template_id: int): - """复制现有模板文件和映射定义,创建新的草稿版本。""" - return _ok(excel_template.create_draft_from_existing(template_id, actor_id=_actor_id()), status=201) - - -@admin_bp.route('/shipping-notice/excel-templates//clone', methods=['POST']) -@require_admin -def clone_shipping_excel_template(template_id: int): - """复制已有模板为使用新编码的独立 v1 草稿。""" - return _ok(excel_template.clone_as_new_template( - template_id, request.get_json(silent=True) or {}, actor_id=_actor_id(), - ), status=201) - - -@admin_bp.route('/shipping-notice/excel-templates//publish', methods=['POST']) -@require_admin -def publish_shipping_excel_template(template_id: int): - """校验工作簿和字段映射后发布模板。""" - return _ok(excel_template.publish(template_id, actor_id=_actor_id())) - - -@admin_bp.route('/shipping-notice/excel-templates//retire', methods=['POST']) -@require_admin -def retire_shipping_excel_template(template_id: int): - """退役没有启用库存源引用的模板。""" - return _ok(excel_template.retire(template_id)) - - -@admin_bp.route('/shipping-notice/excel-templates/', methods=['DELETE']) -@require_admin -def delete_shipping_excel_template(template_id: int): - """删除从未发布且未使用的模板草稿。""" - excel_template.delete_draft(template_id) - return '', 204 - - -@admin_bp.route('/shipping-notice/rpa-profiles', methods=['GET']) -@require_admin -def list_shipping_rpa_profiles(): - """列出脱敏后的 RPA Profile 配置。""" - return _ok(shipping_inventory_service.list_profiles()) - - -@admin_bp.route('/shipping-notice/rpa-profiles', methods=['POST']) -@require_admin -def create_shipping_rpa_profile(): - """创建 RPA Profile;明文凭据仅在本次请求内用于加密。""" - return _ok(shipping_inventory_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201) - - -@admin_bp.route('/shipping-notice/rpa-profiles/', methods=['PUT']) -@require_admin -def update_shipping_rpa_profile(profile_id: int): - """更新 RPA Profile;未提交密码字段时保留既有密文。""" - return _ok(shipping_inventory_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id)) - - -@admin_bp.route('/shipping-notice/rpa-profiles/', methods=['DELETE']) -@require_admin -def delete_shipping_rpa_profile(profile_id: int): - """删除没有库存源引用的错误连接配置。""" - shipping_inventory_service.delete_profile(profile_id) - return '', 204 - - -@admin_bp.route('/shipping-notice/sources', methods=['GET']) -@require_admin -def list_shipping_inventory_sources(): - """列出库存业务来源。""" - return _ok(shipping_inventory_service.list_sources()) - - -@admin_bp.route('/shipping-notice/sources', methods=['POST']) -@require_admin -def create_shipping_inventory_source(): - """保存停用的库存站点基础配置;正式启用由独立接口控制。""" - return _ok(shipping_inventory_service.save_source( - request.get_json(silent=True) or {}, actor_id=_actor_id(), allow_enable_transition=False, - ), status=201) - - -@admin_bp.route('/shipping-notice/sources/', methods=['PUT']) -@require_admin -def update_shipping_inventory_source(source_id: int): - """更新库存站点业务配置;不能借由普通保存绕过启用门禁。""" - return _ok(shipping_inventory_service.save_source( - request.get_json(silent=True) or {}, actor_id=_actor_id(), source_id=source_id, - allow_enable_transition=False, - )) - - -@admin_bp.route('/shipping-notice/sources//receipt-report-config', methods=['GET']) -@require_admin -def get_shipping_receipt_report_config(source_id: int): - """读取站点独立收料报表配置;库存配置和收料配置永不混写。""" - return _ok(shipping_inventory_service.get_receipt_report_config(source_id)) - - -@admin_bp.route('/shipping-notice/sources//receipt-report-config', methods=['PUT']) -@require_admin -def save_shipping_receipt_report_config(source_id: int): - """保存独立收料报表配置,并由服务记录可追溯的前后快照审计。""" - return _ok(shipping_inventory_service.save_receipt_report_config( - source_id, request.get_json(silent=True) or {}, actor_id=_actor_id(), - )) - - -@admin_bp.route('/shipping-notice/sources//bind-parsing-profile', methods=['POST']) -@require_admin -def bind_shipping_inventory_source_parsing_profile(source_id: int): - """直接为停用库存站点绑定已发布解析方案;审计说明由系统自动记录。""" - payload = request.get_json(silent=True) or {} - rows = shipping_inventory_service.bind_source_parsing_profile( - [source_id], payload.get('parsing_profile_id'), actor_id=_actor_id(), - reason=str(payload.get('reason') or ''), operation='direct', - ) - return _ok(rows[0]) - - -@admin_bp.route('/shipping-notice/sources/bulk-bind-parsing-profile', methods=['POST']) -@require_admin -def bulk_bind_shipping_inventory_source_parsing_profile(): - """原子批量绑定已发布解析方案;任一站点预检失败则整批不写入。""" - payload = request.get_json(silent=True) or {} - source_ids = payload.get('source_ids') - if not isinstance(source_ids, list): - source_ids = [] - return _ok(shipping_inventory_service.bind_source_parsing_profile( - source_ids, payload.get('parsing_profile_id'), actor_id=_actor_id(), - reason=str(payload.get('reason') or ''), operation='bulk', - )) - - -@admin_bp.route('/shipping-notice/sources//parsing-binding-audits', methods=['GET']) -@require_admin -def list_shipping_inventory_source_parsing_binding_audits(source_id: int): - """返回库存站点的解析方案绑定审计,不包含任何 RPA 凭据。""" - return _ok(shipping_inventory_service.get_source_parsing_binding_audits(source_id)) - - -@admin_bp.route('/shipping-notice/sources//activate', methods=['POST']) -@require_admin -def activate_shipping_inventory_source(source_id: int): - """仅在库存站点完成测试与必需绑定后启用正式运行。""" - return _ok(shipping_inventory_service.activate_source(source_id, actor_id=_actor_id())) - - -@admin_bp.route('/shipping-notice/sources//deactivate', methods=['POST']) -@require_admin -def deactivate_shipping_inventory_source(source_id: int): - """停用库存站点而不删除已有配置和运行审计。""" - return _ok(shipping_inventory_service.deactivate_source(source_id, actor_id=_actor_id())) - - -@admin_bp.route('/shipping-notice/sources/', methods=['DELETE']) -@require_admin -def delete_shipping_inventory_source(source_id: int): - """删除无运行/路由引用的错误库存源。""" - shipping_inventory_service.delete_source(source_id) - return '', 204 - - -@admin_bp.route('/shipping-notice/sources//test-export', methods=['POST']) -@require_admin -def start_shipping_inventory_configuration_test(source_id: int): - """为停用库存站点发起异步测试导出,不产生生产库存快照。""" - from app.services.shipping_notice import inventory_configuration_test - - return _ok(inventory_configuration_test.start_test_export(source_id, actor_id=_actor_id()), status=202) - - -@admin_bp.route('/shipping-notice/source-validation-batches', methods=['POST']) -@require_admin -def start_shipping_inventory_validation_batch(): - """为多个停用且已绑定发布解析方案的站点发起批量测试验证。""" - from app.services.shipping_notice import inventory_configuration_test - - payload = request.get_json(silent=True) or {} - return _ok(inventory_configuration_test.start_batch_test_export( - payload.get('source_ids') or [], actor_id=_actor_id(), - ), status=202) - - -@admin_bp.route('/shipping-notice/source-validation-batches/latest-active', methods=['GET']) -@require_admin -def get_latest_active_shipping_inventory_validation_batch(): - """恢复最近未结束的批量验证,避免页面刷新后丢失进度。""" - from app.services.shipping_notice import inventory_configuration_test - - return _ok(inventory_configuration_test.get_latest_active_validation_batch()) - - -@admin_bp.route('/shipping-notice/source-validation-batches/', methods=['GET']) -@require_admin -def get_shipping_inventory_validation_batch(batch_id: int): - """读取批量验证汇总进度及每个站点的独立测试结果。""" - from app.services.shipping_notice import inventory_configuration_test - - return _ok(inventory_configuration_test.get_validation_batch(batch_id)) - - -@admin_bp.route('/shipping-notice/source-validation-batches//retry-failed', methods=['POST']) -@require_admin -def retry_failed_shipping_inventory_validation_batch(batch_id: int): - """只重试批次中失败或配置已过期的站点,不重复导出成功项。""" - from app.services.shipping_notice import inventory_configuration_test - - return _ok(inventory_configuration_test.retry_failed_validation_batch(batch_id, actor_id=_actor_id()), status=202) - - -@admin_bp.route('/shipping-notice/sources//test-export/latest', methods=['GET']) -@require_admin -def get_latest_shipping_inventory_configuration_test(source_id: int): - """读取当前库存站点配置对应的最近测试,使管理端可恢复异步执行状态。""" - from app.services.shipping_notice import inventory_configuration_test - - return _ok(inventory_configuration_test.get_latest_test_run(source_id)) - - -@admin_bp.route('/shipping-notice/sources//test-export/', methods=['GET']) -@require_admin -def get_shipping_inventory_configuration_test(source_id: int, run_no: str): - """读取库存站点测试导出的异步执行状态与结构识别结果。""" - from app.services.shipping_notice import inventory_configuration_test - - return _ok(inventory_configuration_test.get_test_run(source_id, run_no)) - - -@admin_bp.route('/shipping-notice/sources//test-export//confirm-profile', methods=['POST']) -@require_admin -def confirm_shipping_inventory_configuration_test_profile(source_id: int, run_no: str): - """确认测试结果采用的解析方案,并更新仍停用的库存站点绑定。""" - from app.services.shipping_notice import inventory_configuration_test - - payload = request.get_json(silent=True) or {} - return _ok(inventory_configuration_test.confirm_test_profile( - source_id, run_no, int(payload.get('profile_id') or 0), actor_id=_actor_id(), - )) - - -@admin_bp.route('/shipping-notice/snapshots', methods=['GET']) -@require_admin -def list_shipping_inventory_snapshots(): - """列出库存快照的管理端只读记录。""" - return _ok(shipping_inventory_service.list_snapshots()) - - -@admin_bp.route('/shipping-notice/snapshots//download', methods=['GET']) -@require_admin -def download_shipping_inventory_snapshot(snapshot_id: int): - """下载管理员选定的已托管库存快照,不向前端暴露服务器存储路径。""" - path, filename = shipping_inventory_service.get_snapshot_download(snapshot_id) - return send_file(path, as_attachment=True, download_name=filename) - - -@admin_bp.route('/shipping-notice/export-records', methods=['GET']) -@require_admin -def list_shipping_inventory_export_records(): - """列出 RPA 导出结果;失败后应修复配置并重新创建运行。""" - return _ok(shipping_inventory_service.list_export_records()) - - -@admin_bp.route('/shipping-notice/routing-rules', methods=['GET']) -@require_admin -def list_shipping_inventory_rules(): - """列出库存源路由规则及条件。""" - return _ok(shipping_inventory_service.list_rules()) - - -@admin_bp.route('/shipping-notice/routing-fields', methods=['GET']) -@require_admin -def list_shipping_inventory_routing_fields(): - """返回路由规则可引用的已发布订单字段;路由不再读取固定系统投影。""" - try: - contract = order_schema_service.get_published_contract() - order_fields = contract['fields'] - published = True - except ConflictError as exc: - if not isinstance(exc, ConflictError) or exc.code != 'SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED': - raise - order_fields = [] - published = False - return _ok({ - 'order_fields': order_fields, - 'order_schema_published': published, - }) - - -@admin_bp.route('/shipping-notice/inventory-fields', methods=['GET']) -@require_admin -def list_shipping_inventory_fields(): - """列出库存统一业务字段;管理工作区可查看已停用字段。""" - return _ok(inventory_field_catalog.list_fields(include_retired=request.args.get('include_retired') == 'true')) - - -@admin_bp.route('/shipping-notice/inventory-fields', methods=['POST']) -@require_admin -def create_shipping_inventory_field(): - """创建可由 DBS、Crane 等多个库存解析方案复用的扩展业务字段。""" - return _ok(inventory_field_catalog.create_field(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201) - - -@admin_bp.route('/shipping-notice/inventory-fields/', methods=['PUT']) -@require_admin -def update_shipping_inventory_field(field_id: int): - """更新库存业务字段的名称、说明、格式和展示顺序。""" - return _ok(inventory_field_catalog.update_field(field_id, request.get_json(silent=True) or {}, actor_id=_actor_id())) - - -@admin_bp.route('/shipping-notice/inventory-fields//retire', methods=['POST']) -@require_admin -def retire_shipping_inventory_field(field_id: int): - """停用无引用的扩展库存字段,核心字段始终由服务层保护。""" - return _ok(inventory_field_catalog.retire_field(field_id)) - - -@admin_bp.route('/shipping-notice/inventory-fields/', methods=['DELETE']) -@require_admin -def delete_shipping_inventory_field(field_id: int): - """删除未被配置引用的扩展库存字段。""" - inventory_field_catalog.delete_field(field_id) - return '', 204 - - -@admin_bp.route('/shipping-notice/configuration-catalog', methods=['GET']) -@require_admin -def get_shipping_inventory_configuration_catalog(): - """返回 Profile、模板和路由编辑器共用的后端受控字段目录。""" - from app.services.shipping_notice.excel_template import ( - ALLOWED_FORMATTERS, - ALLOWED_ROW_MODES, - ALLOWED_SOURCE_KINDS, - ALLOWED_SYSTEM_FACTS, - ) - try: - contract = order_schema_service.get_published_contract() - order_fields = contract['fields'] - published = True - except ConflictError as exc: - if not isinstance(exc, ConflictError) or exc.code != 'SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED': - raise - order_fields = [] - published = False - return _ok({ - 'order_fields': order_fields, - 'order_schema_published': published, - 'inventory_fields': inventory_field_catalog.list_fields(), - 'template_system_facts': sorted(ALLOWED_SYSTEM_FACTS), - 'template_source_kinds': sorted(ALLOWED_SOURCE_KINDS), - 'template_row_modes': sorted(ALLOWED_ROW_MODES), - 'template_formatters': sorted(ALLOWED_FORMATTERS), - }) - - -@admin_bp.route('/shipping-notice/movement-fields', methods=['GET']) -@require_admin -def list_movement_fields(): - """标准异动字段目录(只读领域契约,供收料异动解析规则映射表单;禁止增删)。""" - from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS - - return _ok([ - { - 'code': field.code, 'value_type': str(field.value_type), - 'required': bool(field.required), 'is_identity': bool(field.is_identity), - } - for field in MOVEMENT_FIELDS - ]) - - -@admin_bp.route('/shipping-notice/parsing-profiles', methods=['GET']) -@require_admin -def list_shipping_inventory_parsing_profiles(): - """列出可复用库存解析 Profile 版本。""" - return _ok(inventory_parsing_profile.list_profiles()) - - -@admin_bp.route('/shipping-notice/parsing-profiles', methods=['POST']) -@require_admin -def create_shipping_inventory_parsing_profile(): - """创建库存解析 Profile 草稿。""" - return _ok(inventory_parsing_profile.save_draft(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201) - - -@admin_bp.route('/shipping-notice/parsing-profiles/', methods=['PUT']) -@require_admin -def update_shipping_inventory_parsing_profile(profile_id: int): - """更新库存解析 Profile 草稿。""" - return _ok(inventory_parsing_profile.save_draft( - request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id, - )) - - -@admin_bp.route('/shipping-notice/parsing-profiles//sample-replacement-preview/', methods=['POST']) -@require_admin -def preview_shipping_inventory_sample_replacement(profile_id: int, analysis_id: int): - """比较库存映射草稿当前样本与候选样本,替换前必须由管理员确认差异。""" - return _ok(inventory_structure_analysis.preview_profile_sample_replacement( - profile_id, analysis_id, request.get_json(silent=True) or {}, - )) - - -@admin_bp.route('/shipping-notice/parsing-profiles//publish', methods=['POST']) -@require_admin -def publish_shipping_inventory_parsing_profile(profile_id: int): - """发布库存解析 Profile。""" - return _ok(inventory_parsing_profile.publish(profile_id, actor_id=_actor_id())) - - -@admin_bp.route('/shipping-notice/parsing-profiles//retire', methods=['POST']) -@require_admin -def retire_shipping_inventory_parsing_profile(profile_id: int): - """退役无库存源引用的已发布解析 Profile。""" - return _ok(inventory_parsing_profile.retire(profile_id)) - - -@admin_bp.route('/shipping-notice/parsing-profiles/', methods=['DELETE']) -@require_admin -def delete_shipping_inventory_parsing_profile(profile_id: int): - """删除从未发布的解析 Profile 草稿。""" - inventory_parsing_profile.delete_draft(profile_id) - return '', 204 - - -@admin_bp.route('/shipping-notice/inventory-structure-analyses', methods=['POST']) -@require_admin -def create_shipping_inventory_structure_analysis(): - """上传库存样本并返回后端分析出的工作表、表头、栏位和建议。""" - return _ok(inventory_structure_analysis.create_sample_upload( - request.files.get('file'), actor_id=_actor_id(), - ), status=201) - - -@admin_bp.route('/shipping-notice/inventory-structure-analyses/', methods=['GET']) -@require_admin -def get_shipping_inventory_structure_analysis(analysis_id: int): - """读取库存样本结构分析结果,供管理端继续配置解析方案。""" - return _ok(inventory_structure_analysis.get_analysis(analysis_id)) - - -@admin_bp.route('/shipping-notice/inventory-structure-analyses//create-profile-draft', methods=['POST']) -@require_admin -def create_shipping_inventory_parsing_draft_from_analysis(analysis_id: int): - """使用确认后的真实表头和匹配键创建库存文件解析方案草稿。""" - return _ok(inventory_structure_analysis.create_profile_draft( - analysis_id, request.get_json(silent=True) or {}, actor_id=_actor_id(), - ), status=201) - - -@admin_bp.route('/shipping-notice/inventory-structure-analyses//adopt-profile', methods=['POST']) -@require_admin -def adopt_shipping_inventory_parsing_profile(analysis_id: int): - """确认复用推荐的已发布库存文件解析方案,不修改库存站点绑定。""" - payload = request.get_json(silent=True) or {} - return _ok(inventory_structure_analysis.adopt_published_profile( - analysis_id, int(payload.get('profile_id') or 0), - )) - - -@admin_bp.route('/shipping-notice/temporary-inventory-sessions', methods=['GET']) -@require_admin -def list_confirmed_shipping_temporary_inventory_sessions(): - """列出已通过质量校验、可供管理员沉淀为解析方案草稿的对话临时库存会话。""" - from app.services.shipping_notice import inventory_temporary_session - - return _ok(inventory_temporary_session.list_confirmed_temporary_inventory_sessions()) - - -@admin_bp.route('/shipping-notice/temporary-inventory-sessions//create-profile-draft', methods=['POST']) -@require_admin -def create_shipping_parsing_draft_from_temporary_inventory_session(session_no: str): - """管理员将已确认临时会话锁定映射复制为解析方案草稿;发布仍走既有门禁。""" - from app.services.shipping_notice import inventory_temporary_session - - return _ok(inventory_temporary_session.create_parsing_profile_draft_from_temporary_session( - session_no, request.get_json(silent=True) or {}, actor_id=_actor_id(), - ), status=201) - - -@admin_bp.route('/shipping-notice/routing-rules', methods=['POST']) -@require_admin -def create_shipping_inventory_rule(): - """创建草稿路由规则。""" - return _ok(shipping_inventory_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201) - - -@admin_bp.route('/shipping-notice/routing-rules/', methods=['PUT']) -@require_admin -def update_shipping_inventory_rule(rule_id: int): - """更新草稿规则;已发布规则由服务层拒绝原地修改。""" - return _ok(shipping_inventory_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id(), rule_id=rule_id)) - - -@admin_bp.route('/shipping-notice/routing-rules//publish', methods=['POST']) -@require_admin -def publish_shipping_inventory_rule(rule_id: int): - """发布草稿规则并写入不可变定义快照。""" - return _ok(shipping_inventory_service.publish_rule(rule_id, actor_id=_actor_id())) - - -@admin_bp.route('/shipping-notice/routing-rules//retire', methods=['POST']) -@require_admin -def retire_shipping_inventory_rule(rule_id: int): - """归档已发布规则,保留其审计版本但停止新路由使用。""" - return _ok(shipping_inventory_service.retire_rule(rule_id, actor_id=_actor_id())) - - -@admin_bp.route('/shipping-notice/routing-rules/', methods=['DELETE']) -@require_admin -def delete_shipping_inventory_rule(rule_id: int): - """删除从未发布的草稿规则。""" - shipping_inventory_service.delete_draft_rule(rule_id) - return '', 204 - - -@admin_bp.route('/shipping-notice/external-mappings', methods=['GET']) -@require_admin -def list_shipping_inventory_external_mappings(): - """列出库存源到外部系统仓库映射。""" - return _ok(shipping_inventory_service.list_external_mappings()) - - -@admin_bp.route('/shipping-notice/external-mappings', methods=['POST']) -@require_admin -def create_shipping_inventory_external_mapping(): - """创建精确或 Source 默认外部系统映射。""" - return _ok(shipping_inventory_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201) - - -@admin_bp.route('/shipping-notice/external-mappings/', methods=['PUT']) -@require_admin -def update_shipping_inventory_external_mapping(mapping_id: int): - """更新外部系统映射,不参与任何调拨动作。""" - return _ok(shipping_inventory_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id(), mapping_id=mapping_id)) - - -@admin_bp.route('/shipping-notice/external-mappings/', methods=['DELETE']) -@require_admin -def delete_shipping_inventory_external_mapping(mapping_id: int): - """删除错误的外部系统仓库映射。""" - shipping_inventory_service.delete_external_mapping(mapping_id) - return '', 204 diff --git a/backend/app/api/admin/shipping_notice_admin.py b/backend/app/api/admin/shipping_notice_admin.py new file mode 100644 index 00000000..183169c6 --- /dev/null +++ b/backend/app/api/admin/shipping_notice_admin.py @@ -0,0 +1,126 @@ +""" +api/admin/shipping_notice_admin.py + +用途:发货通知仍留在本蓝图的管理面——Excel 模板、临时在手会话。 +依赖:admin blueprint、require_admin、excel_template、临时会话服务。 +逻辑:货代 RPA 管理路由(含 movement-fields / 报表规则)已迁至 + api/admin_freight_rpa.py 的 /api/admin/freight-rpa/;本文件不再注册那些路径。 + 临时会话只改路径段 temporary-onhand-sessions,仍挂在 /shipping-notice/。 +""" + +from __future__ import annotations + +import json + +from flask import g, request + +from app.api.admin.blueprint import admin_bp +from app.core.decorators import require_admin +from app.core.response import ok +from app.services.shipping_notice import excel_template + + +def _actor_id() -> int | None: + """取得 require_admin 已写入请求上下文的管理员 ID。""" + return getattr(getattr(g, 'current_user', None), 'id', None) + + +def _ok(data, *, status: int = 200): + """按平台统一 envelope 返回管理 API 成功结果。""" + return ok(data, request_id=getattr(g, 'request_id', None), status=status) + + +@admin_bp.route('/shipping-notice/excel-templates', methods=['GET']) +@require_admin +def list_shipping_excel_templates(): + """列出版本化发货 Excel 模板。""" + return _ok(excel_template.list_templates()) + + +@admin_bp.route('/shipping-notice/excel-templates', methods=['POST']) +@require_admin +def create_shipping_excel_template(): + """上传 xlsx 并创建模板草稿版本。""" + try: + definition = json.loads(request.form.get('definition') or '{}') + except json.JSONDecodeError as exc: + from app.core.errors import ValidationError + raise ValidationError('definition must be valid JSON', code='SHIPPING.EXCEL_TEMPLATE_INVALID') from exc + data = { + 'template_code': request.form.get('template_code'), + 'display_name': request.form.get('display_name'), + 'definition': definition, + } + return _ok(excel_template.create_draft(request.files.get('file'), data, actor_id=_actor_id()), status=201) + + +@admin_bp.route('/shipping-notice/excel-templates/', methods=['PUT']) +@require_admin +def update_shipping_excel_template(template_id: int): + """更新 Excel 模板草稿定义。""" + return _ok(excel_template.update_draft(template_id, request.get_json(silent=True) or {})) + + +@admin_bp.route('/shipping-notice/excel-templates//layout', methods=['GET']) +@require_admin +def get_shipping_excel_template_layout(template_id: int): + """读取已保存模板的工作表和栏位,编辑时无需重新上传 Excel。""" + return _ok(excel_template.get_layout(template_id)) + + +@admin_bp.route('/shipping-notice/excel-templates//new-version', methods=['POST']) +@require_admin +def create_shipping_excel_template_version(template_id: int): + """复制现有模板文件和映射定义,创建新的草稿版本。""" + return _ok(excel_template.create_draft_from_existing(template_id, actor_id=_actor_id()), status=201) + + +@admin_bp.route('/shipping-notice/excel-templates//clone', methods=['POST']) +@require_admin +def clone_shipping_excel_template(template_id: int): + """复制已有模板为使用新编码的独立 v1 草稿。""" + return _ok(excel_template.clone_as_new_template( + template_id, request.get_json(silent=True) or {}, actor_id=_actor_id(), + ), status=201) + + +@admin_bp.route('/shipping-notice/excel-templates//publish', methods=['POST']) +@require_admin +def publish_shipping_excel_template(template_id: int): + """校验工作簿和字段映射后发布模板。""" + return _ok(excel_template.publish(template_id, actor_id=_actor_id())) + + +@admin_bp.route('/shipping-notice/excel-templates//retire', methods=['POST']) +@require_admin +def retire_shipping_excel_template(template_id: int): + """退役没有启用库存源引用的模板。""" + return _ok(excel_template.retire(template_id)) + + +@admin_bp.route('/shipping-notice/excel-templates/', methods=['DELETE']) +@require_admin +def delete_shipping_excel_template(template_id: int): + """删除从未发布且未使用的模板草稿。""" + excel_template.delete_draft(template_id) + return '', 204 + + +@admin_bp.route('/shipping-notice/temporary-onhand-sessions', methods=['GET']) +@require_admin +def list_confirmed_shipping_temporary_inventory_sessions(): + """列出已通过质量校验、可供管理员沉淀为解析方案草稿的对话临时库存会话。""" + from app.services.shipping_notice import onhand_temporary_session + + return _ok(onhand_temporary_session.list_confirmed_temporary_inventory_sessions()) + + +@admin_bp.route('/shipping-notice/temporary-onhand-sessions//create-profile-draft', methods=['POST']) +@require_admin +def create_shipping_parsing_draft_from_temporary_inventory_session(session_no: str): + """管理员将已确认临时会话锁定映射复制为解析方案草稿;发布仍走既有门禁。""" + from app.services.shipping_notice import onhand_temporary_session + + return _ok(onhand_temporary_session.create_parsing_profile_draft_from_temporary_session( + session_no, request.get_json(silent=True) or {}, actor_id=_actor_id(), + ), status=201) diff --git a/backend/app/api/admin/transfer_type.py b/backend/app/api/admin/transfer_type.py new file mode 100644 index 00000000..9b292611 --- /dev/null +++ b/backend/app/api/admin/transfer_type.py @@ -0,0 +1,157 @@ +""" +api/admin/transfer_type.py + +用途:调拨类型配置的管理 API(列表/创建/更新,ADR 0002 类型配置化)。 +依赖:admin blueprint、require_admin、transfer_type_config_service(Task 4)。 +逻辑:路由只做鉴权、参数形态门禁与错误码→HTTP 状态映射;业务校验、配置 + 规范化与事务全在服务层。重复 code(服务层预检)与并发唯一键冲突 + (IntegrityError 兜底)统一映射 422 TRANSFER.TRANSFER_TYPE_CODE_EXISTS; + code 不可变 422;更新目标不存在 404。本模块是稳定错误码 → 前端四语言 + errors.json 文案的 API 侧登记点(TRANSFER_TYPE_*/SCOPE/WAREHOUSE/TRANSFORM)。 +""" + +from __future__ import annotations + +from flask import g, request +from sqlalchemy.exc import IntegrityError + +from app.api.admin.blueprint import admin_bp +from app.core.decorators import require_admin +from app.core.errors import AppError, ValidationError +from app.core.response import ok, utc_iso +from app.services.in_transit_transfer import transfer_type_config_service as service + +# 稳定错误码统一转出(服务层常量 + 引擎码 + 匹配链码),避免 API 层散落字符串。 +ERR_NOT_CONFIGURED = service.TRANSFER_TYPE_NOT_CONFIGURED +ERR_CODE_EXISTS = service.TRANSFER_TYPE_CODE_EXISTS +ERR_CODE_IMMUTABLE = service.TRANSFER_TYPE_CODE_IMMUTABLE +ERR_WAREHOUSE_INVALID = service.WAREHOUSE_CONFIG_INVALID +ERR_SCOPE_INVALID = "TRANSFER.SCOPE_RULE_INVALID" +ERR_TRANSFORM_INVALID = "TRANSFER.TRANSFORM_RULE_INVALID" + +# 服务层业务码 → HTTP 状态映射:编码冲突/不可变是语义冲突(422)、更新目标 +# 不存在(404);不在表内的码(含 VALIDATION.INVALID_PARAM 与三块配置引擎码) +# 保持 ValidationError 默认 400。 +_HTTP_STATUS_BY_CODE = { + ERR_CODE_EXISTS: 422, + ERR_CODE_IMMUTABLE: 422, + ERR_NOT_CONFIGURED: 404, +} + + +def _actor_id() -> int | None: + """取得 require_admin 已写入请求上下文的管理员 ID。""" + return getattr(getattr(g, 'current_user', None), 'id', None) + + +def _ok(data, *, status: int = 200): + """按平台统一 envelope 返回管理 API 成功结果。""" + return ok(data, request_id=getattr(g, 'request_id', None), status=status) + + +def _reraise_with_status(exc: ValidationError) -> None: + """按稳定错误码改写 HTTP 状态后重抛;表外码原样透传(保持 400)。""" + status = _HTTP_STATUS_BY_CODE.get(exc.code) + if status is None: + raise exc + raise AppError( + code=exc.code, message=exc.message, http_status=status, details=exc.details, + ) from exc + + +def _request_payload() -> dict: + """读取 JSON body 并保证是 dict(非对象形态统一 400,防下游 AttributeError)。""" + payload = request.get_json(silent=True) or {} + if not isinstance(payload, dict): + raise ValidationError("request body must be a JSON object") + return payload + + +def _enforce_field_types(payload: dict) -> None: + """API 层参数形态门禁:enabled 只接受布尔/整数、sort_order 只接受整数。 + + 防御字符串形态(如 "false")绕过 API 直达服务层被 bool() 强转为真值; + 业务校验(code 格式、names、三块配置)仍归服务层,此处只挡类型。 + """ + if "enabled" in payload and not isinstance(payload["enabled"], (bool, int)): + raise ValidationError( + "enabled must be boolean or integer", details={"enabled": payload["enabled"]}, + ) + sort_order = payload.get("sort_order") + if "sort_order" in payload and (not isinstance(sort_order, int) or isinstance(sort_order, bool)): + raise ValidationError("sort_order must be integer", details={"sort_order": sort_order}) + + +def _warehouse_role_json(role) -> dict: + """WarehouseRole → 管理端 JSON 项(与入库规范化形态读写对称)。""" + return { + "mode": role.mode, + "warehouse_code": role.warehouse_code, + "external_org": role.external_org, + } + + +def _serialize_config(dto) -> dict: + """TransferTypeConfigDTO → 管理 API 全量视图(三块配置全暴露,仅管理端可见)。""" + return { + "code": dto.code, + "names": dict(dto.names), + "enabled": dto.enabled, + "sort_order": dto.sort_order, + "scope_rules": [ + {"field": rule.field, "match": rule.match, "values": list(rule.values)} + for rule in dto.scope_rules + ], + "warehouse_config": { + "from": _warehouse_role_json(dto.warehouse_config.from_role), + "to": _warehouse_role_json(dto.warehouse_config.to_role), + }, + "transform_rules": [ + {"field": rule.field, "op": rule.op, "source": rule.source, "target": rule.target} + for rule in dto.transform_rules + ], + "description": dto.description, + "updated_at": utc_iso(dto.updated_at), + } + + +@admin_bp.route('/in-transit-transfer/transfer-types', methods=['GET']) +@require_admin +def list_transfer_types(): + """全量类型配置(含停用),sort_order 升序——管理页列表。""" + return _ok([_serialize_config(dto) for dto in service.list_configs()]) + + +@admin_bp.route('/in-transit-transfer/transfer-types', methods=['POST']) +@require_admin +def create_transfer_type(): + """创建类型配置;重复 code(预检或并发唯一键)统一 422。""" + payload = _request_payload() + _enforce_field_types(payload) + try: + dto = service.create_config(payload, operator_id=_actor_id()) + except ValidationError as exc: + _reraise_with_status(exc) + except IntegrityError as exc: + # [防御] 服务层唯一性预检在事务之前,并发窗口漏出的唯一键冲突兜底映射 + # 422,避免 500 漏给管理页(控制器裁定①)。 + raise AppError( + code=ERR_CODE_EXISTS, + message="transfer type code already exists", + http_status=422, + details={}, + ) from exc + return _ok(_serialize_config(dto), status=201) + + +@admin_bp.route('/in-transit-transfer/transfer-types/', methods=['PUT']) +@require_admin +def update_transfer_type(code: str): + """更新类型配置(部分更新;改 code → 422,目标不存在 → 404)。""" + payload = _request_payload() + _enforce_field_types(payload) + try: + dto = service.update_config(code, payload, operator_id=_actor_id()) + except ValidationError as exc: + _reraise_with_status(exc) + return _ok(_serialize_config(dto)) diff --git a/backend/app/api/admin_freight_rpa.py b/backend/app/api/admin_freight_rpa.py new file mode 100644 index 00000000..2ef4dcb5 --- /dev/null +++ b/backend/app/api/admin_freight_rpa.py @@ -0,0 +1,543 @@ +""" +api/admin_freight_rpa.py + +用途:货代 RPA 管理 API,挂在 /api/admin/freight-rpa/(站点 sources、onhand 配置、 + 入站/出站报表配置、报表规则、异动字段目录、RPA Profile)。 +依赖:admin blueprint、require_admin、freight_rpa_source_admin_service、 + shipping_onhand_admin_service、freight_rpa_report_config_service、 + freight_rpa.parsing_profile、 + onhand 字段/结构分析服务、in_transit_transfer.movement_contract。 +逻辑:路由只做鉴权与 JSON 参数;业务校验与事务留在服务层。 + 不保留 /shipping-notice/ 双路由。Excel 模板与 temporary-onhand-sessions + 仍在 admin/shipping_notice_admin.py。 +""" + +from __future__ import annotations + +from flask import g, request, send_file + +from app.api.admin.blueprint import admin_bp +from app.core.decorators import require_admin +from app.core.errors import ConflictError +from app.core.response import ok +from app.services.admin import ( + freight_rpa_report_config_service, + freight_rpa_source_admin_service, + shipping_onhand_admin_service, +) +from app.services.freight_rpa import parsing_profile as onhand_parsing_profile +from app.services.shipping_notice import onhand_field_catalog, onhand_structure_analysis +from app.services.shipping_notice.order_schema import service as order_schema_service + + +def _actor_id() -> int | None: + """取得 require_admin 已写入请求上下文的管理员 ID。""" + return getattr(getattr(g, 'current_user', None), 'id', None) + + +def _ok(data, *, status: int = 200): + """按平台统一 envelope 返回管理 API 成功结果。""" + return ok(data, request_id=getattr(g, 'request_id', None), status=status) + + +@admin_bp.route('/freight-rpa/rpa-profiles', methods=['GET']) +@require_admin +def list_shipping_rpa_profiles(): + """列出脱敏后的 RPA Profile 配置。""" + return _ok(freight_rpa_source_admin_service.list_profiles()) + + +@admin_bp.route('/freight-rpa/rpa-profiles', methods=['POST']) +@require_admin +def create_shipping_rpa_profile(): + """创建 RPA Profile;明文凭据仅在本次请求内用于加密。""" + return _ok(freight_rpa_source_admin_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201) + + +@admin_bp.route('/freight-rpa/rpa-profiles/', methods=['PUT']) +@require_admin +def update_shipping_rpa_profile(profile_id: int): + """更新 RPA Profile;未提交密码字段时保留既有密文。""" + return _ok(freight_rpa_source_admin_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id)) + + +@admin_bp.route('/freight-rpa/rpa-profiles/', methods=['DELETE']) +@require_admin +def delete_shipping_rpa_profile(profile_id: int): + """删除没有库存源引用的错误连接配置。""" + freight_rpa_source_admin_service.delete_profile(profile_id) + return '', 204 + + +@admin_bp.route('/freight-rpa/sources', methods=['GET']) +@require_admin +def list_shipping_inventory_sources(): + """列出库存业务来源。""" + return _ok(freight_rpa_source_admin_service.list_sources()) + + +@admin_bp.route('/freight-rpa/sources', methods=['POST']) +@require_admin +def create_shipping_inventory_source(): + """保存停用的库存站点基础配置;正式启用由独立接口控制。""" + return _ok(freight_rpa_source_admin_service.save_source( + request.get_json(silent=True) or {}, actor_id=_actor_id(), allow_enable_transition=False, + ), status=201) + + +@admin_bp.route('/freight-rpa/sources/', methods=['PUT']) +@require_admin +def update_shipping_inventory_source(source_id: int): + """更新库存站点业务配置;不能借由普通保存绕过启用门禁。""" + return _ok(freight_rpa_source_admin_service.save_source( + request.get_json(silent=True) or {}, actor_id=_actor_id(), source_id=source_id, + allow_enable_transition=False, + )) + + +@admin_bp.route('/freight-rpa/sources//inbound-report-config', methods=['GET']) +@require_admin +def get_shipping_inbound_report_config(source_id: int): + """读取站点独立入站报表配置;库存配置和入站配置永不混写。""" + return _ok(freight_rpa_report_config_service.get_inbound_report_config(source_id)) + + +@admin_bp.route('/freight-rpa/sources//inbound-report-config', methods=['PUT']) +@require_admin +def save_shipping_inbound_report_config(source_id: int): + """保存独立入站报表配置,并由服务记录可追溯的前后快照审计。""" + return _ok(freight_rpa_report_config_service.save_inbound_report_config( + source_id, request.get_json(silent=True) or {}, actor_id=_actor_id(), + )) + + +@admin_bp.route('/freight-rpa/sources//outbound-report-config', methods=['GET']) +@require_admin +def get_shipping_outbound_report_config(source_id: int): + """读取站点独立出站报表配置;库存/入站/出站配置永不混写。""" + return _ok(freight_rpa_report_config_service.get_outbound_report_config(source_id)) + + +@admin_bp.route('/freight-rpa/sources//outbound-report-config', methods=['PUT']) +@require_admin +def save_shipping_outbound_report_config(source_id: int): + """保存独立出站报表配置,并由服务记录可追溯的前后快照审计。""" + return _ok(freight_rpa_report_config_service.save_outbound_report_config( + source_id, request.get_json(silent=True) or {}, actor_id=_actor_id(), + )) + + +@admin_bp.route('/freight-rpa/movement-fields', methods=['GET']) +@require_admin +def list_freight_rpa_movement_fields(): + """标准异动字段目录(只读领域契约,供入站/出站报表规则映射表单)。""" + from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS + + return _ok([ + { + 'code': field.code, 'value_type': str(field.value_type), + 'required': bool(field.required), 'is_identity': bool(field.is_identity), + } + for field in MOVEMENT_FIELDS + ]) + + +@admin_bp.route('/freight-rpa/sources//bind-parsing-profile', methods=['POST']) +@require_admin +def bind_shipping_inventory_source_parsing_profile(source_id: int): + """直接为停用库存站点绑定已发布解析方案;审计说明由系统自动记录。""" + payload = request.get_json(silent=True) or {} + rows = freight_rpa_source_admin_service.bind_source_parsing_profile( + [source_id], payload.get('parsing_profile_id'), actor_id=_actor_id(), + reason=str(payload.get('reason') or ''), operation='direct', + ) + return _ok(rows[0]) + + +@admin_bp.route('/freight-rpa/sources/bulk-bind-parsing-profile', methods=['POST']) +@require_admin +def bulk_bind_shipping_inventory_source_parsing_profile(): + """原子批量绑定已发布解析方案;任一站点预检失败则整批不写入。""" + payload = request.get_json(silent=True) or {} + source_ids = payload.get('source_ids') + if not isinstance(source_ids, list): + source_ids = [] + return _ok(freight_rpa_source_admin_service.bind_source_parsing_profile( + source_ids, payload.get('parsing_profile_id'), actor_id=_actor_id(), + reason=str(payload.get('reason') or ''), operation='bulk', + )) + + +@admin_bp.route('/freight-rpa/sources//parsing-binding-audits', methods=['GET']) +@require_admin +def list_shipping_inventory_source_parsing_binding_audits(source_id: int): + """返回库存站点的解析方案绑定审计,不包含任何 RPA 凭据。""" + return _ok(freight_rpa_source_admin_service.get_source_parsing_binding_audits(source_id)) + + +@admin_bp.route('/freight-rpa/sources//activate', methods=['POST']) +@require_admin +def activate_shipping_inventory_source(source_id: int): + """仅在库存站点完成测试与必需绑定后启用正式运行。""" + return _ok(freight_rpa_source_admin_service.activate_source(source_id, actor_id=_actor_id())) + + +@admin_bp.route('/freight-rpa/sources//deactivate', methods=['POST']) +@require_admin +def deactivate_shipping_inventory_source(source_id: int): + """停用库存站点而不删除已有配置和运行审计。""" + return _ok(freight_rpa_source_admin_service.deactivate_source(source_id, actor_id=_actor_id())) + + +@admin_bp.route('/freight-rpa/sources/', methods=['DELETE']) +@require_admin +def delete_shipping_inventory_source(source_id: int): + """删除无运行/路由引用的错误库存源。""" + freight_rpa_source_admin_service.delete_source(source_id) + return '', 204 + + +@admin_bp.route('/freight-rpa/sources//test-export', methods=['POST']) +@require_admin +def start_shipping_inventory_configuration_test(source_id: int): + """为停用库存站点发起异步测试导出,不产生生产库存快照。""" + from app.services.shipping_notice import onhand_configuration_test + + return _ok(onhand_configuration_test.start_test_export(source_id, actor_id=_actor_id()), status=202) + + +@admin_bp.route('/freight-rpa/onhand/validation-batches', methods=['POST']) +@require_admin +def start_shipping_inventory_validation_batch(): + """为多个停用且已绑定发布解析方案的站点发起批量测试验证。""" + from app.services.shipping_notice import onhand_configuration_test + + payload = request.get_json(silent=True) or {} + return _ok(onhand_configuration_test.start_batch_test_export( + payload.get('source_ids') or [], actor_id=_actor_id(), + ), status=202) + + +@admin_bp.route('/freight-rpa/onhand/validation-batches/latest-active', methods=['GET']) +@require_admin +def get_latest_active_shipping_inventory_validation_batch(): + """恢复最近未结束的批量验证,避免页面刷新后丢失进度。""" + from app.services.shipping_notice import onhand_configuration_test + + return _ok(onhand_configuration_test.get_latest_active_validation_batch()) + + +@admin_bp.route('/freight-rpa/onhand/validation-batches/', methods=['GET']) +@require_admin +def get_shipping_inventory_validation_batch(batch_id: int): + """读取批量验证汇总进度及每个站点的独立测试结果。""" + from app.services.shipping_notice import onhand_configuration_test + + return _ok(onhand_configuration_test.get_validation_batch(batch_id)) + + +@admin_bp.route('/freight-rpa/onhand/validation-batches//retry-failed', methods=['POST']) +@require_admin +def retry_failed_shipping_inventory_validation_batch(batch_id: int): + """只重试批次中失败或配置已过期的站点,不重复导出成功项。""" + from app.services.shipping_notice import onhand_configuration_test + + return _ok(onhand_configuration_test.retry_failed_validation_batch(batch_id, actor_id=_actor_id()), status=202) + + +@admin_bp.route('/freight-rpa/sources//test-export/latest', methods=['GET']) +@require_admin +def get_latest_shipping_inventory_configuration_test(source_id: int): + """读取当前库存站点配置对应的最近测试,使管理端可恢复异步执行状态。""" + from app.services.shipping_notice import onhand_configuration_test + + return _ok(onhand_configuration_test.get_latest_test_run(source_id)) + + +@admin_bp.route('/freight-rpa/sources//test-export/', methods=['GET']) +@require_admin +def get_shipping_inventory_configuration_test(source_id: int, run_no: str): + """读取库存站点测试导出的异步执行状态与结构识别结果。""" + from app.services.shipping_notice import onhand_configuration_test + + return _ok(onhand_configuration_test.get_test_run(source_id, run_no)) + + +@admin_bp.route('/freight-rpa/sources//test-export//confirm-profile', methods=['POST']) +@require_admin +def confirm_shipping_inventory_configuration_test_profile(source_id: int, run_no: str): + """确认测试结果采用的解析方案,并更新仍停用的库存站点绑定。""" + from app.services.shipping_notice import onhand_configuration_test + + payload = request.get_json(silent=True) or {} + return _ok(onhand_configuration_test.confirm_test_profile( + source_id, run_no, int(payload.get('profile_id') or 0), actor_id=_actor_id(), + )) + + +@admin_bp.route('/freight-rpa/onhand/snapshots', methods=['GET']) +@require_admin +def list_shipping_inventory_snapshots(): + """列出库存快照的管理端只读记录。""" + return _ok(shipping_onhand_admin_service.list_snapshots()) + + +@admin_bp.route('/freight-rpa/onhand/snapshots//download', methods=['GET']) +@require_admin +def download_shipping_inventory_snapshot(snapshot_id: int): + """下载管理员选定的已托管库存快照,不向前端暴露服务器存储路径。""" + path, filename = shipping_onhand_admin_service.get_snapshot_download(snapshot_id) + return send_file(path, as_attachment=True, download_name=filename) + + +@admin_bp.route('/freight-rpa/onhand/export-records', methods=['GET']) +@require_admin +def list_shipping_inventory_export_records(): + """列出 RPA 导出结果;失败后应修复配置并重新创建运行。""" + return _ok(shipping_onhand_admin_service.list_export_records()) + + +@admin_bp.route('/freight-rpa/onhand/routing-rules', methods=['GET']) +@require_admin +def list_shipping_inventory_rules(): + """列出库存源路由规则及条件。""" + return _ok(shipping_onhand_admin_service.list_rules()) + + +@admin_bp.route('/freight-rpa/onhand/routing-fields', methods=['GET']) +@require_admin +def list_shipping_inventory_routing_fields(): + """返回路由规则可引用的已发布订单字段;路由不再读取固定系统投影。""" + try: + contract = order_schema_service.get_published_contract() + order_fields = contract['fields'] + published = True + except ConflictError as exc: + if not isinstance(exc, ConflictError) or exc.code != 'SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED': + raise + order_fields = [] + published = False + return _ok({ + 'order_fields': order_fields, + 'order_schema_published': published, + }) + + +@admin_bp.route('/freight-rpa/onhand/fields', methods=['GET']) +@require_admin +def list_shipping_inventory_fields(): + """列出库存统一业务字段;管理工作区可查看已停用字段。""" + return _ok(onhand_field_catalog.list_fields(include_retired=request.args.get('include_retired') == 'true')) + + +@admin_bp.route('/freight-rpa/onhand/fields', methods=['POST']) +@require_admin +def create_shipping_inventory_field(): + """创建可由 DBS、Crane 等多个库存解析方案复用的扩展业务字段。""" + return _ok(onhand_field_catalog.create_field(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201) + + +@admin_bp.route('/freight-rpa/onhand/fields/', methods=['PUT']) +@require_admin +def update_shipping_inventory_field(field_id: int): + """更新库存业务字段的名称、说明、格式和展示顺序。""" + return _ok(onhand_field_catalog.update_field(field_id, request.get_json(silent=True) or {}, actor_id=_actor_id())) + + +@admin_bp.route('/freight-rpa/onhand/fields//retire', methods=['POST']) +@require_admin +def retire_shipping_inventory_field(field_id: int): + """停用无引用的扩展库存字段,核心字段始终由服务层保护。""" + return _ok(onhand_field_catalog.retire_field(field_id)) + + +@admin_bp.route('/freight-rpa/onhand/fields/', methods=['DELETE']) +@require_admin +def delete_shipping_inventory_field(field_id: int): + """删除未被配置引用的扩展库存字段。""" + onhand_field_catalog.delete_field(field_id) + return '', 204 + + +@admin_bp.route('/freight-rpa/onhand/configuration-catalog', methods=['GET']) +@require_admin +def get_shipping_inventory_configuration_catalog(): + """返回 Profile、模板和路由编辑器共用的后端受控字段目录。""" + from app.services.shipping_notice.excel_template import ( + ALLOWED_FORMATTERS, + ALLOWED_ROW_MODES, + ALLOWED_SOURCE_KINDS, + ALLOWED_SYSTEM_FACTS, + ) + try: + contract = order_schema_service.get_published_contract() + order_fields = contract['fields'] + published = True + except ConflictError as exc: + if not isinstance(exc, ConflictError) or exc.code != 'SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED': + raise + order_fields = [] + published = False + return _ok({ + 'order_fields': order_fields, + 'order_schema_published': published, + 'inventory_fields': onhand_field_catalog.list_fields(), + 'template_system_facts': sorted(ALLOWED_SYSTEM_FACTS), + 'template_source_kinds': sorted(ALLOWED_SOURCE_KINDS), + 'template_row_modes': sorted(ALLOWED_ROW_MODES), + 'template_formatters': sorted(ALLOWED_FORMATTERS), + }) + + +@admin_bp.route('/freight-rpa/onhand/parsing-profiles', methods=['GET']) +@require_admin +def list_shipping_inventory_parsing_profiles(): + """列出可复用库存解析 Profile 版本。""" + return _ok(onhand_parsing_profile.list_profiles()) + + +@admin_bp.route('/freight-rpa/onhand/parsing-profiles', methods=['POST']) +@require_admin +def create_shipping_inventory_parsing_profile(): + """创建库存解析 Profile 草稿。""" + return _ok(onhand_parsing_profile.save_draft(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201) + + +@admin_bp.route('/freight-rpa/onhand/parsing-profiles/', methods=['PUT']) +@require_admin +def update_shipping_inventory_parsing_profile(profile_id: int): + """更新库存解析 Profile 草稿。""" + return _ok(onhand_parsing_profile.save_draft( + request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id, + )) + + +@admin_bp.route('/freight-rpa/onhand/parsing-profiles//sample-replacement-preview/', methods=['POST']) +@require_admin +def preview_shipping_inventory_sample_replacement(profile_id: int, analysis_id: int): + """比较库存映射草稿当前样本与候选样本,替换前必须由管理员确认差异。""" + return _ok(onhand_structure_analysis.preview_profile_sample_replacement( + profile_id, analysis_id, request.get_json(silent=True) or {}, + )) + + +@admin_bp.route('/freight-rpa/onhand/parsing-profiles//publish', methods=['POST']) +@require_admin +def publish_shipping_inventory_parsing_profile(profile_id: int): + """发布库存解析 Profile。""" + return _ok(onhand_parsing_profile.publish(profile_id, actor_id=_actor_id())) + + +@admin_bp.route('/freight-rpa/onhand/parsing-profiles//retire', methods=['POST']) +@require_admin +def retire_shipping_inventory_parsing_profile(profile_id: int): + """退役无库存源引用的已发布解析 Profile。""" + return _ok(onhand_parsing_profile.retire(profile_id)) + + +@admin_bp.route('/freight-rpa/onhand/parsing-profiles/', methods=['DELETE']) +@require_admin +def delete_shipping_inventory_parsing_profile(profile_id: int): + """删除从未发布的解析 Profile 草稿。""" + onhand_parsing_profile.delete_draft(profile_id) + return '', 204 + + +@admin_bp.route('/freight-rpa/onhand/structure-analyses', methods=['POST']) +@require_admin +def create_shipping_inventory_structure_analysis(): + """上传库存样本并返回后端分析出的工作表、表头、栏位和建议。""" + return _ok(onhand_structure_analysis.create_sample_upload( + request.files.get('file'), actor_id=_actor_id(), + ), status=201) + + +@admin_bp.route('/freight-rpa/onhand/structure-analyses/', methods=['GET']) +@require_admin +def get_shipping_inventory_structure_analysis(analysis_id: int): + """读取库存样本结构分析结果,供管理端继续配置解析方案。""" + return _ok(onhand_structure_analysis.get_analysis(analysis_id)) + + +@admin_bp.route('/freight-rpa/onhand/structure-analyses//create-profile-draft', methods=['POST']) +@require_admin +def create_shipping_inventory_parsing_draft_from_analysis(analysis_id: int): + """使用确认后的真实表头和匹配键创建库存文件解析方案草稿。""" + return _ok(onhand_structure_analysis.create_profile_draft( + analysis_id, request.get_json(silent=True) or {}, actor_id=_actor_id(), + ), status=201) + + +@admin_bp.route('/freight-rpa/onhand/structure-analyses//adopt-profile', methods=['POST']) +@require_admin +def adopt_shipping_inventory_parsing_profile(analysis_id: int): + """确认复用推荐的已发布库存文件解析方案,不修改库存站点绑定。""" + payload = request.get_json(silent=True) or {} + return _ok(onhand_structure_analysis.adopt_published_profile( + analysis_id, int(payload.get('profile_id') or 0), + )) + + +@admin_bp.route('/freight-rpa/onhand/routing-rules', methods=['POST']) +@require_admin +def create_shipping_inventory_rule(): + """创建草稿路由规则。""" + return _ok(shipping_onhand_admin_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201) + + +@admin_bp.route('/freight-rpa/onhand/routing-rules/', methods=['PUT']) +@require_admin +def update_shipping_inventory_rule(rule_id: int): + """更新草稿规则;已发布规则由服务层拒绝原地修改。""" + return _ok(shipping_onhand_admin_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id(), rule_id=rule_id)) + + +@admin_bp.route('/freight-rpa/onhand/routing-rules//publish', methods=['POST']) +@require_admin +def publish_shipping_inventory_rule(rule_id: int): + """发布草稿规则并写入不可变定义快照。""" + return _ok(shipping_onhand_admin_service.publish_rule(rule_id, actor_id=_actor_id())) + + +@admin_bp.route('/freight-rpa/onhand/routing-rules//retire', methods=['POST']) +@require_admin +def retire_shipping_inventory_rule(rule_id: int): + """归档已发布规则,保留其审计版本但停止新路由使用。""" + return _ok(shipping_onhand_admin_service.retire_rule(rule_id, actor_id=_actor_id())) + + +@admin_bp.route('/freight-rpa/onhand/routing-rules/', methods=['DELETE']) +@require_admin +def delete_shipping_inventory_rule(rule_id: int): + """删除从未发布的草稿规则。""" + shipping_onhand_admin_service.delete_draft_rule(rule_id) + return '', 204 + + +@admin_bp.route('/freight-rpa/onhand/external-mappings', methods=['GET']) +@require_admin +def list_shipping_inventory_external_mappings(): + """列出库存源到外部系统仓库映射。""" + return _ok(shipping_onhand_admin_service.list_external_mappings()) + + +@admin_bp.route('/freight-rpa/onhand/external-mappings', methods=['POST']) +@require_admin +def create_shipping_inventory_external_mapping(): + """创建精确或 Source 默认外部系统映射。""" + return _ok(shipping_onhand_admin_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201) + + +@admin_bp.route('/freight-rpa/onhand/external-mappings/', methods=['PUT']) +@require_admin +def update_shipping_inventory_external_mapping(mapping_id: int): + """更新外部系统映射,不参与任何调拨动作。""" + return _ok(shipping_onhand_admin_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id(), mapping_id=mapping_id)) + + +@admin_bp.route('/freight-rpa/onhand/external-mappings/', methods=['DELETE']) +@require_admin +def delete_shipping_inventory_external_mapping(mapping_id: int): + """删除错误的外部系统仓库映射。""" + shipping_onhand_admin_service.delete_external_mapping(mapping_id) + return '', 204 diff --git a/backend/app/api/freight_rpa.py b/backend/app/api/freight_rpa.py new file mode 100644 index 00000000..dac5cf04 --- /dev/null +++ b/backend/app/api/freight_rpa.py @@ -0,0 +1,255 @@ +""" +backend/app/api/freight_rpa.py + +用途:货代 RPA 回调蓝图(/api/freight-rpa/*)——Windows Worker 向后端上报心跳、 + 库存(onhand)/入站(inbound)/出站(outbound)导出结果与货代上传结果的唯一回调入口。 + 批次 R 解耦后取代旧 shipping-notice rpa 回调前缀(无双路由、无兼容层)。 +依赖:app.core.tool_auth(集成密钥鉴权)、freight_rpa.common.callback_sinks(sink 分发)、 + freight_rpa.common.worker_heartbeat(心跳)、shipping_tools。 +逻辑:before_request 统一 Bearer / X-Integration-Key 鉴权(与 Tool 蓝图同一把 key)。 + 分发策略按「处理函数当前住在哪个包」决定: + - /heartbeat 直连 freight_rpa.common.worker_heartbeat; + - /upload-complete 直连现有业务处理器(shipping_notice.tools); + - onhand-* / inbound-* / outbound-* 全部经 callback_sinks.dispatch_sink 分发, + 真实业务 sink 由组合根注册(onhand→shipping_notice.rpa_sinks; + inbound/outbound→in_transit_transfer.rpa_sinks); + 未注册的 kind 显式 404(FREIGHT_RPA.SINK_NOT_REGISTERED)。 +""" + +from __future__ import annotations + +from flask import Blueprint, jsonify, request + +from app.core.errors import ValidationError +from app.core.tool_auth import require_tool_auth +from app.services.freight_rpa.common.callback_sinks import dispatch_sink +from app.services.freight_rpa.common.worker_heartbeat import record_rpa_worker_heartbeat + +freight_rpa_bp = Blueprint('freight_rpa', __name__) + + +def _payload() -> dict: + """ + 读取回调 JSON 请求体,并剥离不可信的操作人身份字段。 + + 核心逻辑:与 shipping_notice Tool 蓝图同口径——集成密钥调用方不得通过 body + 伪造 `_trusted_user_id` / `operator_id` / `actor_id`。 + """ + raw = request.get_json(silent=True) or {} + if not isinstance(raw, dict): + return {} + payload = dict(raw) + for key in ('_trusted_user_id', 'operator_id', 'actor_id'): + payload.pop(key, None) + return payload + + +@freight_rpa_bp.before_request +def _verify_worker_access(): + """RPA Worker 回调统一 Header 鉴权;与 Tool API 共用同一集成密钥配置。""" + require_tool_auth() + return None + + +@freight_rpa_bp.route('/heartbeat', methods=['POST']) +def heartbeat(): + """ + RPA Worker 心跳上报。 + 【AI 触发时机】:非 Agent 入口;Windows Worker(库存/入站)由独立守护线程周期调用。 + + 核心逻辑:校验 payload 后写入 Redis/内存;后端在写各类 trigger 前以此做在线就绪检查。 + """ + payload = _payload() + try: + worker = record_rpa_worker_heartbeat(payload) + except ValueError as exc: + raise ValidationError(str(exc)) + # 心跳存储不可用(ServiceUnavailableError)原样上抛,由全局 AppError handler 出标准错误 envelope。 + return jsonify({'status': 'ok', 'message': 'heartbeat recorded', 'data': worker}) + + +@freight_rpa_bp.route('/onhand-ready', methods=['POST']) +def onhand_ready(): + """ + onhand 单任务导出回调(旧 inventory-ready 端点随批次 R 迁入本蓝图)。 + 【AI 触发时机】:非 Agent 入口;库存 Worker 完成单任务导出后调用。 + + 核心逻辑:dispatch_sink('onhand-ready') 分发到组合根注册的业务 sink + (onhand_rpa_workflow.rpa_report_inventory:快照落盘 + 任务状态回写), + envelope = 裸业务 tool_response dict(与旧 /rpa/inventory-ready 逐字一致)。 + """ + return jsonify(dispatch_sink('onhand-ready', **_payload())) + + +@freight_rpa_bp.route('/onhand-batch-ready', methods=['POST']) +def onhand_batch_ready(): + """ + onhand 批量导出终态回调(旧 /rpa/inventory-batch-ready)。 + 【AI 触发时机】:非 Agent 入口;库存 Worker 按排程批次完成全部站点导出后调用。 + + 核心逻辑:dispatch_sink('onhand-batch-ready') 分发;按 Warehouse 写入库存快照并 + finalize 排程 run(rpa_report_inventory_batch),envelope = 裸业务 dict。 + """ + return jsonify(dispatch_sink('onhand-batch-ready', **_payload())) + + +@freight_rpa_bp.route('/onhand-batch-claimed', methods=['POST']) +def onhand_batch_claimed(): + """ + onhand 批量领取回调(旧 /rpa/inventory-batch-claimed)。 + 【AI 触发时机】:非 Agent 入口;v2 Worker 领取批次 trigger 后立即调用。 + + 核心逻辑:dispatch_sink('onhand-batch-claimed') 分发;仅记录 Attempt 执行阶段 + (per_source_rpa_service.claim_inventory_batch),envelope = {'success':True,'data':...}。 + """ + return jsonify(dispatch_sink('onhand-batch-claimed', **_payload())) + + +@freight_rpa_bp.route('/onhand-batch-progress', methods=['POST']) +def onhand_batch_progress(): + """ + onhand 批量导出进度回调(旧 /rpa/inventory-batch-progress)。 + 【AI 触发时机】:非 Agent 入口;Worker 每完成一个站点导出后调用(非终态,以 batch-ready 为准)。 + + 核心逻辑:dispatch_sink('onhand-batch-progress') 分发;实时回写排程 run 计数 + (onhand_rpa_workflow.report_inventory_batch_progress),envelope = 裸业务 dict。 + """ + return jsonify(dispatch_sink('onhand-batch-progress', **_payload())) + + +@freight_rpa_bp.route('/onhand-configuration-test-start', methods=['POST']) +def onhand_configuration_test_start(): + """ + onhand 配置测试开始回调(旧 /rpa/inventory-configuration-test-batch-progress)。 + 【AI 触发时机】:非 Agent 入口;Worker 领取批量验证中的单个站点后立即调用。 + + 核心逻辑:dispatch_sink('onhand-configuration-test-start') 分发;把该站点测试运行写为 + processing / rpa_exporting,envelope = {'status':'ok','data':...}(旧 batch-progress 同款)。 + """ + return jsonify(dispatch_sink('onhand-configuration-test-start', **_payload())) + + +@freight_rpa_bp.route('/onhand-configuration-test-analyze', methods=['POST']) +def onhand_configuration_test_analyze(): + """ + onhand 配置测试结构分析回调(旧 /rpa/inventory-configuration-test-ready)。 + 【AI 触发时机】:非 Agent 入口;Worker 完成单站点配置测试导出后调用。 + + 核心逻辑:dispatch_sink('onhand-configuration-test-analyze') 分发;仅分析文件结构, + 不创建生产库存快照或任务关联,envelope = {'status':'ok','data':...}(旧 ready 同款)。 + """ + return jsonify(dispatch_sink('onhand-configuration-test-analyze', **_payload())) + + +@freight_rpa_bp.route('/onhand-configuration-test-complete', methods=['POST']) +def onhand_configuration_test_complete(): + """ + onhand 配置测试批次终态回调(旧 /rpa/inventory-configuration-test-batch-ready)。 + 【AI 触发时机】:非 Agent 入口;Worker 完成批量配置测试后按 validation_run_no 回传 results。 + + 核心逻辑:dispatch_sink('onhand-configuration-test-complete') 分发;独立回写每个库存站点 + 的测试结果,envelope = {'status':'ok','data':...}(旧 batch-ready 同款)。 + """ + return jsonify(dispatch_sink('onhand-configuration-test-complete', **_payload())) + + +@freight_rpa_bp.route('/onhand-repair', methods=['POST']) +def onhand_repair(): + """ + onhand 受控库存回调修复(旧 /rpa/inventory-repair)。 + 【AI 触发时机】:非 Agent 入口;人工/运维补偿链路调用,复用正式 v2 ingest 流程。 + + 核心逻辑:dispatch_sink('onhand-repair') 分发;repair 语义由 kind 承载——sink 等价于 + 旧实现 `payload['repair'] = True` 后走 batch-ready ingest,envelope = 裸业务 dict。 + """ + return jsonify(dispatch_sink('onhand-repair', **_payload())) + + +@freight_rpa_bp.route('/inbound-batch-ready', methods=['POST']) +def inbound_batch_ready(): + """ + inbound(收料)批量导出终态回调(旧 /rpa/receipt-batch-ready)。 + 【AI 触发时机】:非 Agent 入口;入站 Worker 完成报表导出并落 drop 目录后调用。 + + 核心逻辑:dispatch_sink('inbound-batch-ready') 分发到组合根 + (in_transit_transfer.rpa_sinks)注册的业务 sink——直挂 + freight_rpa.inbound.report_archive.ingest_inbound_callback 原样归档,终态 commit + 后经 ReportFact → handle_inbound_report 推进调拨并归集排程;绝不进入库存匹配链路; + envelope = {'success': True, 'data': ...}(旧端点逐字一致)。 + """ + return jsonify(dispatch_sink('inbound-batch-ready', **_payload())) + + +@freight_rpa_bp.route('/inbound-unit-progress', methods=['POST']) +def inbound_unit_progress(): + """ + inbound 单元领取/导出中回调(旧 /rpa/receipt-unit-progress)。 + 【AI 触发时机】:非 Agent 入口;入站 Worker 领取单元后调用(awaiting_rpa → processing)。 + + 核心逻辑:dispatch_sink('inbound-unit-progress') 分发到 mark_inbound_unit_processing + (Task 11 已随排程壳平移改名,现住 schedule.freight_rpa_inbound_finalize);本路由同时是收料 + 超时对账的活动锚数据源(mark 落单元 started_at)。曾因重构分叉合并丢失(2026-10-08), + Worker 上报全程 404,勿再从任何路由文件删除。 + """ + return jsonify(dispatch_sink('inbound-unit-progress', **_payload())) + + +@freight_rpa_bp.route('/inbound-batch-progress', methods=['POST']) +def inbound_batch_progress(): + """ + inbound 批量导出累计进度回调(旧 /rpa/receipt-batch-progress)。 + 【AI 触发时机】:非 Agent 入口;入站 Worker 每完成一笔导出后调用(非终态)。 + + 核心逻辑:dispatch_sink('inbound-batch-progress') 分发到 report_inbound_batch_progress + (Task 11 已随排程壳平移改名,现住 schedule.freight_rpa_inbound_finalize),回写排程 run 计数 + (对齐 onhand-batch-progress 语义)。 + """ + return jsonify(dispatch_sink('inbound-batch-progress', **_payload())) + + +@freight_rpa_bp.route('/outbound-batch-ready', methods=['POST']) +def outbound_batch_ready(): + """ + outbound(出站)批量导出终态回调。 + 【AI 触发时机】:非 Agent 入口;出站 Worker 完成报表导出并落 drop 目录后调用。 + + 核心逻辑:dispatch_sink('outbound-batch-ready') 分发到组合根或测内注册的 sink + (ingest_outbound_callback:原样归档,终态 commit 后 dispatch_report_fact + report_kind='outbound');鉴权与入站同 ToolApiKey。 + """ + return jsonify(dispatch_sink('outbound-batch-ready', **_payload())) + + +@freight_rpa_bp.route('/outbound-unit-progress', methods=['POST']) +def outbound_unit_progress(): + """ + outbound 单元领取/导出中回调。 + 【AI 触发时机】:非 Agent 入口;出站 Worker 领取单元后调用(awaiting_rpa → processing)。 + + 核心逻辑:dispatch_sink('outbound-unit-progress') 分发;鉴权与入站同 ToolApiKey。 + """ + return jsonify(dispatch_sink('outbound-unit-progress', **_payload())) + + +@freight_rpa_bp.route('/outbound-batch-progress', methods=['POST']) +def outbound_batch_progress(): + """ + outbound 批量导出累计进度回调。 + 【AI 触发时机】:非 Agent 入口;出站 Worker 每完成一笔导出后调用(非终态)。 + + 核心逻辑:dispatch_sink('outbound-batch-progress') 分发;鉴权与入站同 ToolApiKey。 + """ + return jsonify(dispatch_sink('outbound-batch-progress', **_payload())) + + +@freight_rpa_bp.route('/upload-complete', methods=['POST']) +def upload_complete(): + """ + 货代上传结果回调(旧 /rpa/upload-complete,URL 词根不变)。 + 【AI 触发时机】:非 Agent 入口;Worker 完成出货 Excel 上传(成功或失败)后调用。 + + 核心逻辑:直连 shipping_notice.tools.rpa_report_upload 回写任务状态。 + """ + from app.services.shipping_notice import tools as shipping_tools + + return jsonify(shipping_tools.rpa_report_upload(_payload())) diff --git a/backend/app/api/in_transit_transfer/__init__.py b/backend/app/api/in_transit_transfer/__init__.py index 6d7e9977..8351a0f4 100644 --- a/backend/app/api/in_transit_transfer/__init__.py +++ b/backend/app/api/in_transit_transfer/__init__.py @@ -1,14 +1,29 @@ """backend/app/api/in_transit_transfer/__init__.py 用途:在途仓自动调拨用户态 API(仓库管理人员)。 -依赖:app.core.auth.jwt、app.core.errors、app.core.response、matching_service、deps。 +依赖:app.core.auth.jwt、app.core.errors、app.core.response、matching_service、deps、 + source_file_status、inbound/outbound trigger、scope_rules、transfer_type。 逻辑:薄路由层鉴权与参数校验;成功响应统一 envelope(ok + request_id); + POST /sources//reparse 重解析当前最新可用归档(不触发 RPA); + 单源重试读 record_kind(缺省 inbound,出站另走 outbound trigger); + 批量重试带 transfer_type 时按 record_kinds_of 分组,跳过 ready/fetching/ + unconfigured 后再各写最多一个 batch; + 证据下载(POST /sources/inbound-files)按同一函数打包各来源最新可用 + 入站/出站文件;当天清单(GET /sources//evidence-files)复用可用 + 条件返回当天全部文件,并分别签发预览地址与带保存名的下载地址; 匹配创建(POST /matchings)与进度恢复(GET /matchings/{id});执行为 D8 异步契约(POST /items/execute → 202 queued + run_no,单在提交时组建); result_unknown 单人工重新触发(POST /runs/{run_no}/documents/{doc_no}/ retrigger → 202,D11 唯一出口);首页「已执行」区块:已执行单分页查询 (GET /documents,只读)与人工关闭失败单(POST /documents/{doc_no}/close, - D18 废单不废行)。 + D18 废单不废行); 调拨类型选择数据源(GET /transfer-types,仅启用、 + 最小暴露,另附 record_kinds_of(scope_rules) 推导的 record_kinds,不回传 + scope_rules / warehouse_config / description);来源列表(GET /sources) + 一次批量投影全部启用来源的入站/出站文件状态。待匹配清单只读 + (GET /backlog/pending-match,含外部单号与外部项次)。 + 2026-10-22 起不再挂「清空并重新解析」 + (原 GET/POST /backlog/pending-match/reparse*):该入口会重放保留期内 + 全部归档。重解析只保留 POST /sources//reparse(当天最新一份)。 """ from __future__ import annotations @@ -50,12 +65,34 @@ from app.services.in_transit_transfer.serializers import ( serialize_source, serialize_summary, ) +from app.services.in_transit_transfer.transfer_type_config_service import ( + get_enabled as list_enabled_transfer_types, +) in_transit_transfer_bp = Blueprint("in_transit_transfer", __name__) TRANSFER_AGENT_CODE = "in_transit_transfer" +def _parse_int_arg(name: str, default: int, *, minimum: int, maximum: int | None = None) -> int: + """解析整数查询参数(缺省回默认值;下限钳制必填,上限可选;非法 400)。 + + 分页参数统一入口(/documents、/backlog、/backlog/pending-match 共用, + 2026-10-16 由 list_documents_api 内嵌函数提升为模块级)。 + """ + raw = (request.args.get(name) or "").strip() + if not raw: + return default + try: + value = int(raw) + except ValueError as exc: + raise ValidationError(f"{name} must be an integer") from exc + value = max(minimum, value) + if maximum is not None: + value = min(maximum, value) + return value + + def _require_user(): """校验当前登录用户;未认证抛 UnauthorizedError。""" user = get_current_user() @@ -91,9 +128,10 @@ def create_matching_api(): """创建或复用一次调拨匹配(只读,不写 外部系统)。 请求体:{"source_codes": [...], "business_date": "YYYY-MM-DD"(可选), - "receipt_date_from"/"receipt_date_to"(可选), - "transfer_type": "in_transit_to_hub"(可选,缺省在途仓至HUB仓)}。 - 响应:201 envelope,data 为匹配摘要(matching_id/hash/计数/来源进度)。 + "movement_date_from"/"movement_date_to"(可选,明细异动日期范围), + "transfer_type": 必填(类型编码,配置化;缺失/未配置/停用 → 422)}。 + 响应:201 envelope,data 为匹配摘要(matching_id/hash/计数/来源进度); + 类型门禁失败 422(REQUIRED/NOT_CONFIGURED/DISABLED,规格 §11)。 """ body = request.get_json(silent=True) or {} if not isinstance(body, dict): @@ -101,15 +139,25 @@ def create_matching_api(): source_codes = body.get("source_codes") if not isinstance(source_codes, list) or not source_codes: raise ValidationError("source_codes is required") + # [D8 必填] transfer_type 缺失 fail-closed(稳定错误码,四语言已配齐); + # 存在性/启停门禁由 create_matching → resolve_transfer_type 统一裁定。 + # [规格 §11] 类型门禁(REQUIRED/NOT_CONFIGURED/DISABLED)统一 422。 + transfer_type = str(body.get("transfer_type") or "").strip() + if not transfer_type: + raise ValidationError( + "transfer_type is required", + code="TRANSFER.TRANSFER_TYPE_REQUIRED", + http_status=422, + ) business_date = str(body.get("business_date") or business_date_now()) deps = transfer_deps.get_transfer_dependencies() summary = create_matching( source_codes=[str(item).strip() for item in source_codes], business_date=business_date, deps=deps, - receipt_date_from=str(body.get("receipt_date_from")) if body.get("receipt_date_from") else None, - receipt_date_to=str(body.get("receipt_date_to")) if body.get("receipt_date_to") else None, - transfer_type=str(body.get("transfer_type")) if body.get("transfer_type") else None, + movement_date_from=str(body.get("movement_date_from")) if body.get("movement_date_from") else None, + movement_date_to=str(body.get("movement_date_to")) if body.get("movement_date_to") else None, + transfer_type=transfer_type, ) return _ok(serialize_summary(summary), status=201) @@ -117,14 +165,17 @@ def create_matching_api(): @in_transit_transfer_bp.route("/items/executable", methods=["GET"]) @require_transfer_permission def executable_items_api(): - """可调拨明细(全局可执行行队列):勾选后 POST /items/execute 按行生成调拨单。""" + """可调拨明细(全局可执行行队列):勾选后 POST /items/execute 按行生成调拨单。 + + 行上 transfer_type 是出生匹配快照的类型 code,供跨类型队列显示类别。 + """ return _ok(list_executable_items()) @in_transit_transfer_bp.route("/matchings/", methods=["GET"]) @require_transfer_permission def get_matching_api(matching_id: str): - """恢复匹配进度与明细(页面刷新/会话恢复;明细按 scope 实时圈行并装饰行级状态)。""" + """恢复匹配进度与明细(页面刷新/会话恢复;明细=匹配自有出生行(2026-10-14 出生翻转)并装饰行级状态)。""" restored = restore_matching(matching_id, deps=transfer_deps.get_transfer_dependencies()) return _ok({ "summary": serialize_summary(restored["summary"]), @@ -147,58 +198,97 @@ def requery_items_api(matching_no: str): )) -@in_transit_transfer_bp.route("/sources/receipt-files", methods=["POST"]) -@require_transfer_permission -def download_source_receipt_files_api(): - """按选中来源打包下载各自最新归档收料文件(zip);记录访问审计。""" - import io - import zipfile - from pathlib import Path as _Path +def _usable_archive_files(source_code: str, record_kind: str) -> list: + """返回某来源当天全部可用归档,最新在前。 + 用途:证据压缩包与当天清单共用同一可用条件。压缩包只取第一条,清单返回全部。 + 核心逻辑:入站过滤用 usable_inbound_file_condition;出站过滤与 + latest_usable_outbound_file 相同(未清理 + 当天业务日 + 未过保留期)。 + 不读取、不解析文件字节。 + + Args: + source_code: 来源实例编码。 + record_kind: inbound 或 outbound。 + Returns: + 归档 ORM 行列表,按 created_at、id 倒序。未知记录类型返回空列表。 + """ + from datetime import datetime + + from app.models import FreightRpaInboundReportFile, FreightRpaOutboundReportFile + from app.services.in_transit_transfer.inbound_file_gate import usable_inbound_file_condition + from app.services.in_transit_transfer.source_file_status import ( + _outbound_fresh_and_retention_valid, + ) + + if record_kind == "outbound": + model = FreightRpaOutboundReportFile + usable = ( + model.archive_deleted_at.is_(None), + _outbound_fresh_and_retention_valid(datetime.utcnow()), + ) + elif record_kind == "inbound": + model = FreightRpaInboundReportFile + usable = (usable_inbound_file_condition(),) + else: + return [] + return ( + model.query + .join(model.unit_run) + .filter(model.unit_run.has(source_code=source_code), *usable) + .order_by(model.created_at.desc(), model.id.desc()) + .all() + ) + + +def evidence_download_filename( + source_code: str, + created_at: datetime | None, + original_filename: str | None, +) -> str: + """证据单文件的保存名:库存源编码加东八区抓取日期和时分。 + + 核心逻辑:created_at 无时区时按 UTC 理解,转到 UTC+8 后取年月日和时分, + 与详情行展示的时刻一致。扩展名沿用归档原名,缺省 .xlsx。对象键哈希不进入文件名。 + + Args: + source_code: 库存源实例编码。 + created_at: 归档创建时间;naive 视为 UTC。 + original_filename: 归档原名,只取其扩展名。 + + Returns: + 如 CRANE_20261022_1057.xlsx。来源编码会收成文件名安全字符。 + """ + import re + from datetime import timezone + from pathlib import Path + + suffix = Path(original_filename or "").suffix + ext = suffix if suffix and re.fullmatch(r"\.[A-Za-z0-9]{1,8}", suffix) else ".xlsx" + label = re.sub(r"[^\w.-]+", "_", source_code or "").strip("._") or "unknown" + if created_at is None: + return f"{label}{ext}" + aware = created_at if created_at.tzinfo is not None else created_at.replace(tzinfo=timezone.utc) + stamp = aware.astimezone(timezone(timedelta(hours=8))).strftime("%Y%m%d_%H%M") + return f"{label}_{stamp}{ext}" + + +def _record_evidence_download_audit(*, aggregate_id: str) -> None: + """写入证据文件访问审计,事件类型保持 TRANSFER_INBOUND_FILES_DOWNLOADED。 + + 核心逻辑:下载与清单共用这一事件。aggregate_id 由调用方决定 + (下载为打进包的来源编码,清单为当前 source_code)。 + + Args: + aggregate_id: 审计聚合标识。 + """ from app import db - from app.models import ShippingReceiptReportFile - from app.services.file_assets.storage import file_asset_storage from app.services.in_transit_transfer.audit import build_transfer_audit_event - from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition - - body = request.get_json(silent=True) or {} - source_codes = body.get("source_codes") - if not isinstance(source_codes, list) or not [c for c in source_codes if str(c or "").strip()]: - raise ValidationError("source_codes is required") - - buffer = io.BytesIO() - included: list[str] = [] - with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive: - for code in source_codes: - code = str(code or "").strip() - if not code: - continue - report = ( - ShippingReceiptReportFile.query - .join(ShippingReceiptReportFile.unit_run) - .filter( - ShippingReceiptReportFile.unit_run.has(source_code=code), - # 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)与徽标/匹配取文件同口径, - # 单一事实来源见 receipt_file_gate。 - usable_receipt_file_condition(), - ) - .order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc()) - .first() - ) - if report is None: - continue - data = file_asset_storage.get_bytes(report.storage_key) - safe_name = _Path(report.original_filename or f"{report.id}.xlsx").name - archive.writestr(f"{code}-{safe_name}", data) - included.append(code) - if not included: - raise NotFoundError("no archived receipt files", code="SHIPPING.RECEIPT_FILE_NOT_FOUND") user = _require_user() db.session.add(build_transfer_audit_event( - event_type="TRANSFER_RECEIPT_FILES_DOWNLOADED", + event_type="TRANSFER_INBOUND_FILES_DOWNLOADED", aggregate_type="in_transit_source", - aggregate_id=",".join(included), + aggregate_id=aggregate_id, actor_type="user", actor_id=str(user.id) if user.id else None, actor_display=str(getattr(user, "name", "") or ""), @@ -206,15 +296,111 @@ def download_source_receipt_files_api(): result="success", )) db.session.commit() + + +@in_transit_transfer_bp.route("/sources/inbound-files", methods=["POST"]) +@require_transfer_permission +def download_source_inbound_files_api(): + """按调拨类型的证据流打包各来源最新可用归档。 + + 请求体:{"source_codes": [...], "transfer_type": 类型编码}。 + 证据流来自 record_kinds_of(该类型已有范围规则),没有 record_kinds 列。 + 没有 record_kind 规则时入站和出站都打包;规则等于 inbound 时只打包入站。 + 每种记录类型只取该来源最新一份可用文件。压缩包路径为 + inbound// 或 outbound//。 + 下载名 evidence-files-.zip,n 为打进包的文件数。两种都没有文件时 + 404,错误码 SHIPPING.INBOUND_FILE_NOT_FOUND。审计事件类型仍是 + TRANSFER_INBOUND_FILES_DOWNLOADED。 + """ + import io + import zipfile + from pathlib import Path as _Path + + from app.services.file_assets.storage import file_asset_storage + from app.services.in_transit_transfer.scope_rules import record_kinds_of + from app.services.in_transit_transfer.transfer_type import resolve_transfer_type + + body = request.get_json(silent=True) or {} + source_codes = body.get("source_codes") + if not isinstance(source_codes, list) or not [c for c in source_codes if str(c or "").strip()]: + raise ValidationError("source_codes is required") + config = resolve_transfer_type(str(body.get("transfer_type") or "")) + kinds = record_kinds_of(config.scope_rules) + + buffer = io.BytesIO() + packed_sources: list[str] = [] + packed = 0 + with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive: + for raw_code in source_codes: + code = str(raw_code or "").strip() + if not code: + continue + wrote = False + for kind in kinds: + files = _usable_archive_files(code, kind) + report = files[0] if files else None + if report is None: + continue + data = file_asset_storage.get_bytes(report.storage_key) + safe_name = _Path(report.original_filename or f"{report.id}.xlsx").name + archive.writestr(f"{kind}/{code}/{safe_name}", data) + packed += 1 + wrote = True + if wrote and code not in packed_sources: + packed_sources.append(code) + if packed == 0: + raise NotFoundError("no archived inbound files", code="SHIPPING.INBOUND_FILE_NOT_FOUND") + + _record_evidence_download_audit(aggregate_id=",".join(packed_sources)) buffer.seek(0) return send_file( buffer, mimetype="application/zip", as_attachment=True, - download_name=f"receipt-files-{len(included)}-source{'s' if len(included) > 1 else ''}.zip", + download_name=f"evidence-files-{packed}.zip", ) +@in_transit_transfer_bp.route("/sources//evidence-files", methods=["GET"]) +@require_transfer_permission +def list_source_evidence_files_api(source_code: str): + """返回某来源当天全部可用证据文件,并签发短期下载地址。 + + 查询参数 record_kind 缺省 inbound,只接受 inbound 或 outbound。 + 可用条件与证据压缩包相同,但返回当天全部可用文件,不只最新一份。 + 每项含 file_id、original_filename、created_at、sha256、file_size、 + presigned_url、download_url。不解析 Excel,不含行数。预览与下载各签一次 + presigned_get_url(storage_key, expires_seconds=300);下载地址额外带 + download_name(库存源_东八区年月日_时分.扩展名),避免浏览器用对象键哈希当保存名。 + 签发时写 TRANSFER_INBOUND_FILES_DOWNLOADED,aggregate_id 为 source_code。 + """ + from app.services.file_assets.storage import file_asset_storage + + kind = str(request.args.get("record_kind") or "inbound").strip() + if kind not in {"inbound", "outbound"}: + raise ValidationError("record_kind must be inbound or outbound") + code = str(source_code or "").strip() + payload = [] + for report in _usable_archive_files(code, kind): + created = report.created_at.isoformat() if report.created_at is not None else None + download_name = evidence_download_filename(code, report.created_at, report.original_filename) + payload.append({ + "file_id": report.id, + "original_filename": report.original_filename, + "created_at": created, + "sha256": report.sha256, + "file_size": report.file_size, + "presigned_url": file_asset_storage.presigned_get_url( + report.storage_key, expires_seconds=300, + ), + "download_url": file_asset_storage.presigned_get_url( + report.storage_key, expires_seconds=300, download_name=download_name, + ), + }) + _record_evidence_download_audit(aggregate_id=code) + return _ok(payload) + + @in_transit_transfer_bp.route("/runs/", methods=["GET"]) @require_transfer_permission def get_run_api(run_no: str): @@ -327,11 +513,11 @@ def list_documents_api(): Query: status_group ∈ {success, failed, executing, result_unknown}(可选,缺省全部; 非法 400);date_from/date_to=YYYY-MM-DD(可选,仅作用 orders 列表, - 按收料日期过滤——列表展示的业务日期口径,2026-09-29 由 created_at 切换); + 按异动日期过滤——列表展示的业务日期口径,2026-09-29 由 created_at 切换); page(默认 1);page_size(默认 20,上限 100)。 口径:分组计数恒全量(GROUP BY status 对全部单统计,不受筛选影响—— 失败/结果未知/执行中=未完结即待办,全量才不漏;成功=累计产出); - 列表按 收料日期→数据源→拨出/拨入库位 升序分页(2026-09-29 与可调拨 + 列表按 异动日期→数据源→拨出/拨入库位 升序分页(2026-09-29 与可调拨 明细/待处理池/结果卡统一口径,跨数据源不再乱序;执行落库时间仅作 同序兜底),cancelled 不展示(无产生路径)。 响应:{groups, total, page, page_size, orders:[serialize_executed_order 投影]}。 @@ -350,20 +536,6 @@ def list_documents_api(): except ValueError as exc: raise ValidationError(f"{name} must be YYYY-MM-DD") from exc - def _parse_int(name: str, default: int, *, minimum: int, maximum: int | None = None) -> int: - """解析整数查询参数(缺省回默认值;下限钳制必填,上限可选)。""" - raw = (request.args.get(name) or "").strip() - if not raw: - return default - try: - value = int(raw) - except ValueError as exc: - raise ValidationError(f"{name} must be an integer") from exc - value = max(minimum, value) - if maximum is not None: - value = min(maximum, value) - return value - # [STEP 1] 参数校验:status_group 白名单外 400(fail-closed)。 status_group = (request.args.get("status_group") or "").strip() if status_group and status_group not in DOCUMENT_STATUS_GROUPS: @@ -372,8 +544,9 @@ def list_documents_api(): ) date_from = _parse_date("date_from") date_to = _parse_date("date_to") - page = _parse_int("page", 1, minimum=1) - page_size = _parse_int("page_size", 20, minimum=1, maximum=100) + # 整数分页参数解析复用模块级 _parse_int_arg(2026-10-16 自本函数内嵌提升)。 + page = _parse_int_arg("page", 1, minimum=1) + page_size = _parse_int_arg("page_size", 20, minimum=1, maximum=100) # [STEP 2] 分组计数恒全量:GROUP BY status 对全部单统计,不受任何筛选影响。 counts = dict( @@ -387,21 +560,21 @@ def list_documents_api(): } # [STEP 3] 列表查询:status_group / 时间窗仅作用列表;cancelled 恒不展示。 - # [2026-09-29 口径] 时间窗按收料日期过滤(receipt_date 为 ISO 日期字符串, - # 字典序即时间序);排序与可调拨明细/结果卡统一:收料日期→数据源→库位升序, + # [2026-09-29 口径] 时间窗按异动日期过滤(movement_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.receipt_date >= date_from.isoformat()) + query = query.filter(TransferDocument.movement_date >= date_from.isoformat()) if date_to: window_end = (date_to + timedelta(days=1)).isoformat() - query = query.filter(TransferDocument.receipt_date < window_end) + query = query.filter(TransferDocument.movement_date < window_end) total = query.count() docs = ( query.order_by( - TransferDocument.receipt_date.asc(), + TransferDocument.movement_date.asc(), TransferDocument.source_code.asc(), TransferDocument.from_warehouse.asc(), TransferDocument.to_warehouse.asc(), @@ -594,10 +767,10 @@ def exceptions_excel_api(run_no: str): ) -@in_transit_transfer_bp.route("/runs//receipt-files", methods=["GET"]) +@in_transit_transfer_bp.route("/runs//inbound-files", methods=["GET"]) @require_transfer_permission -def receipt_files_api(run_no: str): - """下载本次收料来源文件(清单 + 原始行追溯,zip);记录访问审计。""" +def inbound_files_api(run_no: str): + """下载本次入站来源文件(清单 + 原始行追溯,zip);记录访问审计。""" import io import json import zipfile @@ -620,7 +793,7 @@ def receipt_files_api(run_no: str): "business_date": run.business_date, **dict(file_snapshot.get(source_code) or {}), } - archive.writestr(f"{source_code}-receipt-info.json", json.dumps(manifest, ensure_ascii=False, indent=2)) + archive.writestr(f"{source_code}-inbound-info.json", json.dumps(manifest, ensure_ascii=False, indent=2)) rows = [] for item in TransferInvoiceItem.query.filter_by(run_id=run.id).all(): for line in (item.raw_lines_json or []): @@ -633,7 +806,7 @@ def receipt_files_api(run_no: str): user = _require_user() db.session.add(build_transfer_audit_event( - event_type="TRANSFER_RECEIPT_FILES_DOWNLOADED", + event_type="TRANSFER_INBOUND_FILES_DOWNLOADED", aggregate_type="transfer_run", aggregate_id=run_no, run_no=run_no, @@ -648,7 +821,7 @@ def receipt_files_api(run_no: str): io.BytesIO(buffer.getvalue()), mimetype="application/zip", as_attachment=True, - download_name=f"receipt-files-{run_no}.zip", + download_name=f"inbound-files-{run_no}.zip", ) @@ -665,12 +838,12 @@ def erp_inventory_api(run_no: str): run = TransferRun.query.filter_by(run_no=str(run_no).strip()).first() if run is None: raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND") - lines = ["invoice_no,source_code,material_no,from_warehouse,to_warehouse,receipt_quantity,external_quantity,result,external_document_no"] + lines = ["invoice_no,source_code,material_no,from_warehouse,to_warehouse,movement_quantity,external_quantity,result,external_document_no"] for item in TransferInvoiceItem.query.filter_by(run_id=run.id).order_by(TransferInvoiceItem.invoice_no).all(): lines.append(",".join([ str(item.invoice_no), str(item.source_code), str(item.material_no), str(item.from_warehouse), str(item.to_warehouse), - str(item.receipt_quantity), str(item.external_quantity or ""), + str(item.movement_quantity), str(item.external_quantity or ""), str(item.result_code or item.status), str(item.external_document_no or ""), ])) data = ("\n".join(lines) + "\n").encode("utf-8") @@ -705,64 +878,146 @@ def transfer_metrics_api(): return _ok(collect_metrics()) +@in_transit_transfer_bp.route("/transfer-types", methods=["GET"]) +@require_transfer_permission +def transfer_types_api(): + """调拨类型配置列表(启用中,最小暴露)——匹配创建的类型选择数据源。 + + 返回 code、names、sort_order、transform_rules,以及 record_kinds。 + record_kinds 只由 record_kinds_of(dto.scope_rules) 现算,不读存储列。 + 范围规则原文、仓库定义、描述仍不暴露。enabled 由查询限定(get_enabled)、 + sort_order 升序。配置缺失返回空列表,不抛 NOT_CONFIGURED。 + """ + from app.services.in_transit_transfer.scope_rules import record_kinds_of + + return _ok([ + { + "code": dto.code, + "names": dict(dto.names), + "sort_order": dto.sort_order, + "transform_rules": [ + {"field": rule.field, "op": rule.op, "source": rule.source, "target": rule.target} + for rule in dto.transform_rules + ], + "record_kinds": list(record_kinds_of(dto.scope_rules)), + } + for dto in list_enabled_transfer_types() + ]) + + @in_transit_transfer_bp.route("/sources", methods=["GET"]) @require_transfer_permission def transfer_sources_api(): """来源实例列表(决策 3:平台 DBS/Crane 仅分组,实例为执行边界)。 - 每来源附收料文件状态(ready/parse_failed/fetching/failed/expired/none + has_ready_file), - 供前端门禁(无 ready 文件时禁止确认匹配)与状态标识;保留期已到或非当天 - (业务日)抓取且未清理均投影 expired。只读复用已启用库存来源。 + 每来源附入站与出站两条证据流 streams。每条含 record_kind、file_status、 + has_ready_file、file_no、file_sha256。扁平 file_status / has_ready_file / + file_no / file_sha256 仍等于入站流,供尚未改完的前端;出站无配置时该条 + file_status=unconfigured。保留期已到或非当天(业务日)抓取且未清理均投影 + expired。文件状态由 resolve_source_file_statuses 一次投影全部来源, + 查询次数不随来源个数增长。只读复用已启用库存来源。 """ - from app.models import ShippingInventorySource - from app.services.in_transit_transfer.source_file_status import resolve_source_file_status + from app.models import FreightRpaSource + from app.services.in_transit_transfer.source_file_status import resolve_source_file_statuses - rows = ShippingInventorySource.query.filter_by(enabled=True).order_by( - ShippingInventorySource.connector_type, ShippingInventorySource.source_code, + rows = FreightRpaSource.query.filter_by(enabled=True).order_by( + FreightRpaSource.connector_type, FreightRpaSource.source_code, ).all() - return _ok([ - { + statuses = resolve_source_file_statuses(rows) + items = [] + for source in rows: + pair = statuses[source.source_code] + inbound = pair["inbound"] + outbound = pair["outbound"] + items.append({ "source_code": source.source_code, "display_name": source.display_name, "platform": source.connector_type, "enabled": bool(source.enabled), - **resolve_source_file_status(source_code=source.source_code), - } - for source in rows - ]) + **inbound, + "streams": [ + {"record_kind": "inbound", **inbound}, + {"record_kind": "outbound", **outbound}, + ], + }) + return _ok(items) + + +@in_transit_transfer_bp.route("/sources//reparse", methods=["POST"]) +@require_transfer_permission +def reparse_current_file_api(source_code: str): + """重解析该来源当前最新可用归档,不触发 RPA。 + + body 只读 record_kind,缺省 inbound。不接受 file_id。 + """ + from app.services.in_transit_transfer.current_file_reparse import reparse_current_file + + payload = request.get_json(silent=True) or {} + if not isinstance(payload, dict): + raise ValidationError("request body must be a JSON object") + record_kind = str(payload.get("record_kind") or "inbound").strip() or "inbound" + result = reparse_current_file( + source_code=str(source_code).strip(), + record_kind=record_kind, + now=datetime.utcnow(), + ) + return _ok({ + "source_code": result.source_code, + "record_kind": result.record_kind, + "ok": result.ok, + "file_status": result.file_status, + "file_id": result.file_id, + "inserted": result.inserted, + "updated": result.updated, + "skipped": result.skipped, + "sealed_skipped": result.sealed_skipped, + "error_code": result.error_code, + "error_message": result.error_message, + }) @in_transit_transfer_bp.route("/sources//retry-rpa", methods=["POST"]) @require_transfer_permission def retry_source_rpa_api(source_code: str): - """对指定来源重新触发一次收料 RPA 抓取(复用货代收料 trigger 链路)。 + """按证据流重试一个来源:缺省入站,请求体 record_kind=outbound 走出站触发。 - 【AI 触发时机】来源收料文件不可用需要恢复时调用:解析失败(parse_failed)先 - 本地重解析已归档文件;文件缺失/失效(none/expired/failed)才重新触发 RPA 抓取。 + 【AI 触发时机】来源某一条证据流需要恢复时调用。入站解析失败(parse_failed) + 先本地重解析已归档文件;出站解析失败重新触发出站 RPA。行上重试不跳过 ready。 - 解析失败优先本地重解析(解析失败分层 2026-09-29):当日文件可用但解析失败时, - 先走 sync_and_commit_for_callback 重解析归档文件——成功且投影回 ready → + 入站解析失败分层(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)。 + (file_status=parse_failed)。其余状态按 record_kind 选择 + trigger_inbound_rpa 或 trigger_outbound_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.inbound_trigger_service import trigger_inbound_rpa + from app.services.in_transit_transfer.outbound_trigger_service import trigger_outbound_rpa from app.services.in_transit_transfer.source_file_status import resolve_source_file_status + payload = request.get_json(silent=True) or {} + if not isinstance(payload, dict): + raise ValidationError("request body must be a JSON object") + record_kind = str(payload.get("record_kind") or "inbound").strip() or "inbound" source_code = str(source_code).strip() + business_date = str(business_date_now()) - # [STEP 1] 解析失败分层:文件可用但解析失败 → 先本地重解析归档文件,不触发 RPA。 - status = resolve_source_file_status(source_code=source_code) - if status.get("file_status") == "parse_failed" and status.get("file_sha256"): + # [STEP 1] 只有入站 parse_failed 本地重解析。出站 parse_failed 落到 STEP 2 重抓。 + status = resolve_source_file_status(source_code=source_code, record_kind=record_kind) + if ( + record_kind == "inbound" + and 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()), + business_date=business_date, now=datetime.utcnow(), ) # 重解析后再取投影:以真实落库事实(而非 sync 返回值)决定 ok。 - status = resolve_source_file_status(source_code=source_code) + status = resolve_source_file_status(source_code=source_code, record_kind="inbound") ready = bool(synced) and status.get("file_status") == "ready" return _ok({ "source_code": source_code, @@ -771,13 +1026,20 @@ def retry_source_rpa_api(source_code: str): "reparsed": True, }) - # [STEP 2] 其余状态沿用原路径:重新触发一次收料 RPA 抓取(202 + fetching)。 - outcome = trigger_receipt_rpa( - source_code=source_code, - business_date=str(business_date_now()), - reason="transfer_retry_receipt", - ) - status = resolve_source_file_status(source_code=source_code) + # [STEP 2] 按证据流选择已有触发器,不合并两套实现。 + if record_kind == "outbound": + outcome = trigger_outbound_rpa( + source_code=source_code, + business_date=business_date, + reason="transfer_retry_outbound", + ) + else: + outcome = trigger_inbound_rpa( + source_code=source_code, + business_date=business_date, + reason="transfer_retry_inbound", + ) + status = resolve_source_file_status(source_code=source_code, record_kind=record_kind) if not outcome.get("ok"): return _ok({ "source_code": source_code, @@ -793,41 +1055,251 @@ def retry_source_rpa_api(source_code: str): }, status=202) +def resolve_source_file_status(*, source_code: str, record_kind: str = "inbound") -> dict: + """按证据流投影来源文件状态(路由层入口,测试可替换本函数)。 + + 核心逻辑:调用时再导入投影服务,因此服务模块上的测试替身仍然生效; + 批量重试按流入参 record_kind,缺省 inbound。 + + Args: + source_code: 来源实例编码。 + record_kind: inbound 或 outbound。 + Returns: + file_status / has_ready_file / file_no / file_sha256。 + """ + from app.services.in_transit_transfer.source_file_status import ( + resolve_source_file_status as impl, + ) + + return impl(source_code=source_code, record_kind=record_kind) + + +def trigger_inbound_rpa_batch(*, source_codes, business_date, reason="transfer_retry_inbound"): + """转发入站批量触发(不合并出站实现;测试可替换本函数)。 + + Args: + source_codes: 需要入站重试的来源编码。 + business_date: 业务日。 + reason: 写入 trigger 的原因。 + Returns: + inbound_trigger_service.trigger_inbound_rpa_batch 的返回值。 + """ + from app.services.in_transit_transfer.inbound_trigger_service import ( + trigger_inbound_rpa_batch as impl, + ) + + return impl(source_codes=source_codes, business_date=business_date, reason=reason) + + +def trigger_outbound_rpa_batch(*, source_codes, business_date, reason="transfer_retry_outbound"): + """转发出站批量触发(与入站触发分开;测试可替换本函数)。 + + Args: + source_codes: 需要出站重试的来源编码。 + business_date: 业务日。 + reason: 写入 trigger 的原因。 + Returns: + outbound_trigger_service.trigger_outbound_rpa_batch 的返回值。 + """ + from app.services.in_transit_transfer.outbound_trigger_service import ( + trigger_outbound_rpa_batch as impl, + ) + + return impl(source_codes=source_codes, business_date=business_date, reason=reason) + + +# 批量重试:已就绪或抓取中不写 trigger;未配置只记结果。可重试状态进入对应流。 +_STREAM_SKIP_STATUSES = frozenset({"ready", "fetching"}) +_STREAM_RETRY_STATUSES = frozenset({"no_data", "failed", "expired", "none", "parse_failed"}) +_STREAM_CONFIG_MISSING = { + "inbound": "RPA_INBOUND_CONFIG_MISSING", + "outbound": "RPA_OUTBOUND_CONFIG_MISSING", +} + + +def _annotate_stream_results(outcome: dict, record_kind: str, source_codes: list[str]) -> list[dict]: + """给一条证据流的批量触发结果补上 record_kind。 + + 核心逻辑:触发器已带回 results 时逐项加上记录类型;没有 results 时按本次 + 提交的来源补一行,避免这条流在响应里消失。 + + Args: + outcome: trigger_*_rpa_batch 的返回值。 + record_kind: inbound 或 outbound。 + source_codes: 本次交给该触发器的来源编码。 + Returns: + 每项都含 record_kind 的结果列表。 + """ + raw = outcome.get("results") + if not raw: + error_code = outcome.get("error_code") + raw = [] + for code in source_codes: + item: dict[str, Any] = {"source_code": code, "ok": bool(outcome.get("ok"))} + if error_code and not outcome.get("ok"): + item["error_code"] = error_code + raw.append(item) + annotated = [] + for item in raw: + row = dict(item) + row["record_kind"] = record_kind + annotated.append(row) + return annotated + + +def _append_unique(bucket: list[str], code: str) -> None: + """保序去重追加来源编码(同一流只进一次 batch)。""" + if code not in bucket: + bucket.append(code) + + @in_transit_transfer_bp.route("/sources/retry-rpa-batch", methods=["POST"]) @require_transfer_permission def retry_sources_rpa_batch_api(): - """批量重试多来源收料 RPA:全部有效来源合并写**一个** batch trigger(一文件 N units)。 + """批量重试:无 transfer_type 时整批入站;有类型时按证据流各写最多一个 batch。 - 【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个来源编码时调用; - 逐来源调用单来源端点会产生 N 个 trigger 文件,Worker 每文件开/关一次浏览器; - 合并单文件后 Worker 单次登录串行导出全部来源(与收料排程路径同效率)。 + 【AI 触发时机】聊天侧「批量重试 RPA」提交多个来源时调用。带 transfer_type + 时只重试该类型范围规则推导出的、尚未就绪、不是抓取中、且已配置的流。 - 请求体:{"source_codes": ["DSV360_AWSBI", ...]}。逐来源解析失败分层与 - fail-closed 语义同单来源端点;单源配置缺失跳过并记录,不阻断其余来源。 + 请求体:{"source_codes": [...], "transfer_type": "hub_to_hub"}。 + transfer_type 缺省时保持旧契约:source_codes 原样交给入站 batch,HTTP 200。 + 有类型时 ready/fetching 不写入结果;unconfigured 记 ok=false 与既有配置缺失码 + 且不写 trigger;no_data/failed/expired/none/parse_failed 进入对应流。 + 入站 parse_failed 仍由入站 batch 本地重解析;出站 parse_failed 重新触发出站 RPA。 + 结果每项带 record_kind。写出 trigger 时返回 202。 """ payload = request.get_json(silent=True) or {} + if not isinstance(payload, dict): + raise ValidationError("request body must be a JSON object") source_codes = [str(code).strip() for code in (payload.get("source_codes") or []) if str(code).strip()] if not source_codes: raise ValidationError("source_codes is required") - from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa_batch - outcome = trigger_receipt_rpa_batch( - source_codes=source_codes, - business_date=str(business_date_now()), - reason="transfer_retry_receipt", + transfer_type = str(payload.get("transfer_type") or "").strip() + business_date = str(business_date_now()) + # [STEP 1] 旧调用不带类型:整批入站,回传触发服务 envelope。 + if not transfer_type: + outcome = trigger_inbound_rpa_batch( + source_codes=source_codes, + business_date=business_date, + reason="transfer_retry_inbound", + ) + return _ok(outcome) + + from app.services.in_transit_transfer.scope_rules import record_kinds_of + from app.services.in_transit_transfer.transfer_type import resolve_transfer_type + + # [STEP 2] 类型门禁后按范围规则推导证据流,再按流分组。不在这里合并两个触发实现。 + config = resolve_transfer_type(transfer_type) + kinds = record_kinds_of(config.scope_rules) + inbound_codes: list[str] = [] + outbound_codes: list[str] = [] + results: list[dict[str, Any]] = [] + for code in dict.fromkeys(source_codes): + for kind in kinds: + status = resolve_source_file_status(source_code=code, record_kind=kind) + file_status = status.get("file_status") + if file_status == "unconfigured": + results.append({ + "source_code": code, + "record_kind": kind, + "ok": False, + "error_code": _STREAM_CONFIG_MISSING[kind], + }) + continue + if file_status in _STREAM_SKIP_STATUSES or file_status not in _STREAM_RETRY_STATUSES: + continue + if kind == "outbound": + _append_unique(outbound_codes, code) + else: + _append_unique(inbound_codes, code) + + # [STEP 3] 每条流最多一次 batch。没有任何 trigger 时保持 200。 + triggered = False + overall_ok = True + if inbound_codes: + outcome = trigger_inbound_rpa_batch( + source_codes=inbound_codes, + business_date=business_date, + reason="transfer_retry_inbound", + ) + triggered = triggered or bool(outcome.get("triggered")) + if not outcome.get("ok"): + overall_ok = False + results.extend(_annotate_stream_results(outcome, "inbound", inbound_codes)) + if outbound_codes: + outcome = trigger_outbound_rpa_batch( + source_codes=outbound_codes, + business_date=business_date, + reason="transfer_retry_outbound", + ) + triggered = triggered or bool(outcome.get("triggered")) + if not outcome.get("ok"): + overall_ok = False + results.extend(_annotate_stream_results(outcome, "outbound", outbound_codes)) + if any(item.get("ok") is False for item in results): + overall_ok = False + return _ok( + {"ok": overall_ok, "triggered": triggered, "results": results}, + status=202 if triggered else 200, ) - return _ok(outcome) @in_transit_transfer_bp.route("/backlog", methods=["GET"]) @require_transfer_permission def backlog_api(): - """待处理异常列表(可恢复/已关闭/结果未知 + 老化等级);查看记录访问审计。""" + """待处理异常列表(可恢复/已关闭/结果未知 + 老化等级);查看记录访问审计。 + + 行上 transfer_type 是出生匹配快照的类型 code。 + + Query(全部可选;不带 page/page_size 时保持历史行为返回全量数组——向后兼容): + page(默认 1);page_size(默认 20,上限 100)——任一提供即切换为 + 分页 envelope {items, total, page, page_size}(2026-10-16 服务端分页: + 池为无界增长集合,千行级全量拉取放大载荷与老化查询规模); + keyword(Invoice/料号/品名/来源 子串大小写不敏感,与前端池内筛选同字段集); + result_filter ∈ {all, recoverable, closed, unknown}(缺省 all,白名单外 400)。 + 注意:keyword/result_filter 仅在分页模式下生效(兼容模式下为历史行为, + 筛选参数被忽略——前端恒带分页参数,不受影响)。 + 口径:total=筛选后全量计数(供前端分页器);排序与全量版同一业务稳定键; + 老化批量查询只对当前页行执行。审计 after.item_count 记录当前页行数。 + """ from app import db from app.services.in_transit_transfer.audit import build_transfer_audit_event - from app.services.in_transit_transfer.backlog_service import list_backlog + from app.services.in_transit_transfer.backlog_service import ( + RESULT_FILTER_CHOICES, + BACKLOG_PAGE_DEFAULT, + BACKLOG_PAGE_SIZE_DEFAULT, + BACKLOG_PAGE_SIZE_MAX, + list_backlog, + list_backlog_page, + ) + + keyword = (request.args.get("keyword") or "").strip() + result_filter = (request.args.get("result_filter") or "").strip() or "all" + if result_filter not in RESULT_FILTER_CHOICES: + raise ValidationError( + f"result_filter must be one of {sorted(RESULT_FILTER_CHOICES)}", + ) + paginated = bool((request.args.get("page") or "").strip() or (request.args.get("page_size") or "").strip()) + + if paginated: + page_data = list_backlog_page( + keyword=keyword or None, + result_filter=result_filter, + page=_parse_int_arg("page", BACKLOG_PAGE_DEFAULT, minimum=1), + page_size=_parse_int_arg("page_size", BACKLOG_PAGE_SIZE_DEFAULT, minimum=1, maximum=BACKLOG_PAGE_SIZE_MAX), + ) + items = page_data.items + payload: dict[str, Any] | list[dict[str, Any]] = { + 'items': [_serialize_backlog_item(item) for item in items], + 'total': page_data.total, + 'page': page_data.page, + 'page_size': page_data.page_size, + } + else: + items = list_backlog() + payload = [_serialize_backlog_item(item) for item in items] - items = list_backlog() user = _require_user() db.session.add(build_transfer_audit_event( event_type='TRANSFER_BACKLOG_VIEWED', @@ -841,13 +1313,43 @@ def backlog_api(): after={'item_count': len(items)}, )) db.session.commit() - return _ok([_serialize_backlog_item(item) for item in items]) + return _ok(payload) + + +@in_transit_transfer_bp.route("/backlog/item-ids", methods=["GET"]) +@require_transfer_permission +def backlog_item_ids_api(): + """跨页全选支持(2026-10-22):当前筛选下全部待处理明细 id(轻量列表)。 + + Query:keyword / result_filter(与 /backlog 分页模式同口径、同白名单 400)。 + Returns:{ ids: [item_id...](升序,上限 BACKLOG_SELECT_ALL_MAX), + total: 筛选后全量计数, truncated: total > len(ids) }。 + 用途:待处理池「选择全部 N 行」——服务端分页下勾选集合默认只覆盖当前页, + 本端点按同一筛选口径取全量 id;批量端点(重查/恢复/关闭)本就按 item_ids + 列表逐行隔离,直接复用无需新批量契约。 + """ + from app.services.in_transit_transfer.backlog_service import ( + BACKLOG_SELECT_ALL_MAX, + RESULT_FILTER_CHOICES, + list_backlog_item_ids, + ) + + keyword = (request.args.get("keyword") or "").strip() + result_filter = (request.args.get("result_filter") or "").strip() or "all" + if result_filter not in RESULT_FILTER_CHOICES: + raise ValidationError( + f"result_filter must be one of {sorted(RESULT_FILTER_CHOICES)}", + ) + ids, total = list_backlog_item_ids( + keyword=keyword or None, result_filter=result_filter, limit=BACKLOG_SELECT_ALL_MAX, + ) + return _ok({"ids": ids, "total": total, "truncated": total > len(ids)}) @in_transit_transfer_bp.route("/backlog/summary", methods=["GET"]) @require_transfer_permission def backlog_summary_api(): - """待处理异常汇总(含 3/5/7 天老化分级)。""" + """待处理异常汇总(含 3/5/7 天老化分级 + 待匹配桶计数 D16)。""" from app.services.in_transit_transfer.backlog_service import backlog_summary summary = backlog_summary() @@ -855,6 +1357,10 @@ def backlog_summary_api(): 'recoverable': summary.recoverable_count, 'closed': summary.closed_count, 'unknown': summary.unknown_count, + # 首页待办看板第 4 张数字卡:与待匹配清单同一外部单号合并口径。 + 'pending_match': summary.pending_match_count, + # 库存匹配卡:与清单「当前可匹配」同一合并口径。 + 'matchable_count': summary.matchable_count, 'aging': { 'warn_3d': summary.warn_3d, 'escalate_5d': summary.escalate_5d, @@ -863,6 +1369,67 @@ def backlog_summary_api(): }) +@in_transit_transfer_bp.route("/backlog/pending-match", methods=["GET"]) +@require_transfer_permission +def backlog_pending_match_api(): + """首页待办看板「待匹配」桶清单(只读:已落档、尚未被匹配圈定的成熟出入站 + 记录,不按调拨类型范围过滤;无 item_id——不可勾选执行)。 + + Query(可选;不带 page/page_size 时保持历史行为返回全量数组——向后兼容): + page(默认 1);page_size(默认 20,上限 100)——任一提供即切换为 + 分页 envelope {records, total, page, page_size}。 + segment:all(默认,全量)/ matchable(启用类型现在圈得住)/ + outside(其余已落档)。每行带 matchable、external_doc_no。 + quantity 是同一来源、同一记录类型、同一外部单号下的数量合计; + 没有外部单号的档行仍逐行返回。不再返回 external_line_no。 + """ + from app.services.in_transit_transfer.backlog_service import ( + BACKLOG_PAGE_DEFAULT, + BACKLOG_PAGE_SIZE_DEFAULT, + BACKLOG_PAGE_SIZE_MAX, + list_pending_match_records, + list_pending_match_records_page, + ) + + segment = (request.args.get("segment") or "all").strip() + if segment not in ("all", "matchable", "outside"): + raise ValidationError("segment must be all, matchable, or outside") + paginated = bool((request.args.get("page") or "").strip() or (request.args.get("page_size") or "").strip()) + if paginated: + page_data = list_pending_match_records_page( + page=_parse_int_arg("page", BACKLOG_PAGE_DEFAULT, minimum=1), + page_size=_parse_int_arg("page_size", BACKLOG_PAGE_SIZE_DEFAULT, minimum=1, maximum=BACKLOG_PAGE_SIZE_MAX), + segment=segment, + ) + return _ok({ + 'records': [_serialize_pending_match_record(record) for record in page_data.records], + 'total': page_data.total, + 'page': page_data.page, + 'page_size': page_data.page_size, + }) + + return _ok([ + _serialize_pending_match_record(record) + for record in list_pending_match_records(segment=segment) + ]) + + +def _serialize_pending_match_record(record) -> dict[str, Any]: + """「待匹配」桶项序列化(外部单号合计后的只读投影;无项次、无 item_id)。""" + return { + 'ledger_record_id': record.ledger_record_id, + 'doc_no': record.doc_no, + 'external_doc_no': record.external_doc_no, + 'material_code': record.material_code, + 'material_name': record.material_name, + 'movement_date': record.movement_date, + 'source_code': record.source_code, + 'record_kind': record.record_kind, + 'quantity': record.quantity, + 'matchable': record.matchable, + } + + def _serialize_backlog_item(item) -> dict[str, Any]: """待处理池项序列化(明细字段与匹配窗口列一致)。""" return { @@ -875,12 +1442,13 @@ def _serialize_backlog_item(item) -> dict[str, Any]: 'age_days': item.age_days, 'aging_level': item.aging_level, 'last_attempt_at': item.last_attempt_at, - 'receipt_date': item.receipt_date, + 'movement_date': item.movement_date, 'material_name': item.material_name, 'from_warehouse': item.from_warehouse, 'to_warehouse': item.to_warehouse, 'lot_no': item.lot_no, - 'receipt_quantity': item.receipt_quantity, + 'movement_quantity': item.movement_quantity, 'external_quantity': item.external_quantity, 'result_code': item.result_code, + 'transfer_type': item.transfer_type, } diff --git a/backend/app/api/internal/jobs.py b/backend/app/api/internal/jobs.py index 983b7ca2..1b061731 100644 --- a/backend/app/api/internal/jobs.py +++ b/backend/app/api/internal/jobs.py @@ -2,7 +2,8 @@ backend/app/api/internal/jobs.py 用途:平台内置 Job 内部 API(POST /api/internal/jobs/)。 -依赖:job_registry、schedule_contract、scheduler_service。 +依赖:job_registry、schedule_contract、scheduler_service、 + freight_rpa_onhand_finalize / inbound_finalize / outbound_finalize(awaiting 延后终态)。 逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。 """ from __future__ import annotations @@ -19,15 +20,20 @@ from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot from app.services.schedule.job_registry import get_platform_job, run_platform_job from app.services.schedule.schedule_contract import normalize_job_key from app.services.schedule.scheduler_service import _generate_run_no -from app.services.schedule.shipping_inventory_rpa_finalize import ( +from app.services.schedule.freight_rpa_onhand_finalize import ( apply_deferred_schedule_run_state, recover_stale_awaiting_rpa_schedule_runs, should_defer_schedule_run_finalization, ) -from app.services.schedule.freight_receipt_rpa_finalize import ( - apply_deferred_receipt_schedule_run_state, - recover_stale_receipt_rpa_schedule_runs, - should_defer_receipt_schedule_run, +from app.services.schedule.freight_rpa_inbound_finalize import ( + apply_deferred_inbound_schedule_run_state, + recover_stale_inbound_rpa_schedule_runs, + should_defer_inbound_schedule_run, +) +from app.services.schedule.freight_rpa_outbound_finalize import ( + apply_deferred_outbound_schedule_run_state, + recover_stale_outbound_rpa_schedule_runs, + should_defer_outbound_schedule_run, ) internal_jobs_bp = Blueprint('internal_jobs', __name__) @@ -139,7 +145,8 @@ def run_internal_job(name: str): task, run = _resolve_schedule_task_and_run(key, data) recover_stale_awaiting_rpa_schedule_runs(task) - recover_stale_receipt_rpa_schedule_runs(task) + recover_stale_inbound_rpa_schedule_runs(task) + recover_stale_outbound_rpa_schedule_runs(task) try: total_count, success_count, failed_count, skipped_count, details, errors, step_logs = run_platform_job( key, task, run, data, @@ -189,8 +196,8 @@ def run_internal_job(name: str): 'awaiting_rpa_callback': True, }) - if should_defer_receipt_schedule_run(task, step_logs): - apply_deferred_receipt_schedule_run_state( + if should_defer_inbound_schedule_run(task, step_logs): + apply_deferred_inbound_schedule_run_state( run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs, ) return jsonify({ @@ -199,7 +206,20 @@ def run_internal_job(name: str): 'failed_count': failed_count, 'skipped_count': skipped_count, }, 'details': details, 'errors': errors, 'step_logs': step_logs, - 'awaiting_receipt_rpa_callback': True, + 'awaiting_inbound_rpa_callback': True, + }) + + if should_defer_outbound_schedule_run(task, step_logs): + apply_deferred_outbound_schedule_run_state( + run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs, + ) + return jsonify({ + 'summary': { + 'total_count': total_count, 'success_count': success_count, + 'failed_count': failed_count, 'skipped_count': skipped_count, + }, + 'details': details, 'errors': errors, 'step_logs': step_logs, + 'awaiting_outbound_rpa_callback': True, }) _finalize_run( diff --git a/backend/app/api/schedule/config.py b/backend/app/api/schedule/config.py index 9eb7064b..877b1b0a 100644 --- a/backend/app/api/schedule/config.py +++ b/backend/app/api/schedule/config.py @@ -67,7 +67,7 @@ def update_schedule_task_config(task_id: int): config_data = data.get('config', data) if isinstance(config_data, dict) and config_data: - # platform_job 仅白名单且 enabled 的任务(如 shipping-inventory-rpa)允许写 ScheduleTaskConfig + # platform_job 仅白名单且 enabled 的任务(如 freight-rpa-onhand)允许写 ScheduleTaskConfig if task.schedule_type != SCHEDULE_TYPE_DATA_PIPELINE and not platform_job_allows_config(task.platform_api_path): raise ValidationError( f"platform_job '{task.platform_api_path}' does not accept ScheduleTaskConfig" diff --git a/backend/app/api/schedule/rpa_workers.py b/backend/app/api/schedule/rpa_workers.py index 3f44d8dd..ba0228e9 100644 --- a/backend/app/api/schedule/rpa_workers.py +++ b/backend/app/api/schedule/rpa_workers.py @@ -1,9 +1,9 @@ """ backend/app/api/schedule/rpa_workers.py -用途:管理端查询货代库存/收料 RPA Worker 在线状态与就绪摘要。 -依赖:schedule.blueprint、rpa_worker_heartbeat.serialize_rpa_worker_status。 -逻辑:ScheduleWorkbenchPanel 在库存或收料 RPA 排程工作台展示对应 worker 心跳状态。 +用途:管理端查询货代库存/入站/出站 RPA Worker 在线状态与就绪摘要。 +依赖:schedule.blueprint、freight_rpa.common.worker_heartbeat.serialize_rpa_worker_status。 +逻辑:ScheduleWorkbenchPanel 在库存、入站或出站 RPA 排程工作台展示对应 worker 心跳状态。 """ from __future__ import annotations @@ -13,7 +13,7 @@ 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 -from app.services.shipping_notice.rpa_worker_heartbeat import serialize_rpa_worker_status +from app.services.freight_rpa.common.worker_heartbeat import serialize_rpa_worker_status @schedule_admin_bp.route('/rpa-workers/status', methods=['GET']) @@ -23,7 +23,7 @@ def get_rpa_workers_status(): 返回 RPA Worker 心跳摘要(在线/离线、最后心跳时间、就绪原因)。 Query: - scope: inventory(默认)或 receipt。 + scope: onhand(默认)、inbound 或 outbound。 """ - scope = str(request.args.get('scope') or 'inventory').strip().lower() or 'inventory' + scope = str(request.args.get('scope') or 'onhand').strip().lower() or 'onhand' return ok(serialize_rpa_worker_status(scope=scope)) diff --git a/backend/app/api/schedule/runs.py b/backend/app/api/schedule/runs.py index e7df4178..38d95fed 100644 --- a/backend/app/api/schedule/runs.py +++ b/backend/app/api/schedule/runs.py @@ -2,8 +2,10 @@ backend/app/api/schedule/runs.py 用途:排程运行触发与运行记录查询 API。 -依赖:schedule.blueprint、services/schedule/query_service、queue_service。 +依赖:schedule.blueprint、services/schedule/query_service、queue_service、 + freight_rpa inbound/outbound archive 与 trigger_io。 逻辑:手动执行仅创建 queued run/job;独立 schedule worker 承担实际运行。 + 入站/出站 raw-zip 下载与失败单元 list/retry 对照同构。 """ from __future__ import annotations @@ -18,14 +20,15 @@ from app.api.schedule.blueprint import schedule_admin_bp from app.core.auth.jwt import get_current_user from app.core.decorators import require_admin from app.core.errors import ConflictError, NotFoundError -from app.models import ScheduleRun, ScheduleTask, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun +from app.models import ScheduleRun, ScheduleTask, FreightRpaInboundUnitRun, FreightRpaOutboundUnitRun from app.services.schedule.query_service import get_run, list_runs, serialize_run from app.services.schedule.queue_service import enqueue_manual_schedule_run -from app.services.schedule.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.schedule.freight_rpa_onhand_archive import resolve_inventory_raw_zip_download +from app.services.schedule.freight_rpa_inbound_archive import resolve_inbound_raw_zip_download +from app.services.schedule.freight_rpa_outbound_archive import resolve_outbound_raw_zip_download from app.services.shipping_notice.audit_service import append_shipping_audit_event -from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger +from app.services.freight_rpa.inbound.trigger_io import SCHEMA, write_inbound_export_batch_trigger +from app.services.freight_rpa.outbound.trigger_io import SCHEMA as OUTBOUND_SCHEMA, write_outbound_export_batch_trigger @schedule_admin_bp.route('/schedules//run', methods=['POST']) @@ -44,7 +47,11 @@ def run_schedule(task_id: int): triggered_by_user_id=getattr(user, 'id', None), ) if not created: - raise ConflictError('该排程正在等待或执行中,请等待完成后再试', details={'run_id': run.id}) + raise ConflictError( + '该排程正在等待或执行中,请等待完成后再试', + code='SCHEDULE.RUN_ALREADY_ACTIVE', + details={'run_id': run.id}, + ) fresh = db.session.get(ScheduleRun, run.id) return jsonify(serialize_run(fresh)) @@ -124,18 +131,18 @@ def get_schedule_run_inventory_raw_zip(run_id: int): ) -@schedule_admin_bp.route('/schedule-runs//receipt-raw-zip', methods=['GET']) +@schedule_admin_bp.route('/schedule-runs//inbound-raw-zip', methods=['GET']) @require_admin -def get_schedule_run_receipt_raw_zip(run_id: int): +def get_schedule_run_inbound_raw_zip(run_id: int): """ - 下载收料 RPA 排程 run 的原始收料 Excel 打包(ZIP + manifest)。 + 下载入站 RPA 排程 run 的原始入站 Excel 打包(ZIP + manifest)。 - 核心逻辑:对齐 inventory-raw-zip;展示名为 收料RPA-{日期}-{时刻}-收料.zip。 + 核心逻辑:对齐 inventory-raw-zip;展示名为 入站RPA-{日期}-{时刻}-入站.zip。 """ run = get_run(run_id) if not run: raise NotFoundError('Not found') - zip_path, file_name = resolve_receipt_raw_zip_download(run) + zip_path, file_name = resolve_inbound_raw_zip_download(run) return send_file( zip_path, as_attachment=True, @@ -144,31 +151,10 @@ def get_schedule_run_receipt_raw_zip(run_id: int): ) -@schedule_admin_bp.route('/receipt-report-files//resend', methods=['POST']) +@schedule_admin_bp.route('/inbound-rpa-units', methods=['GET']) @require_admin -def resend_receipt_report_file(file_id: int): - """管理员重发已归档的收料文件;禁止借重发重新触发 RPA 导出。""" - report_file = db.session.get(ShippingReceiptReportFile, file_id) - if report_file is None or report_file.archive_deleted_at is not None: - raise NotFoundError('Receipt report file not found') - user = get_current_user() - outcome = deliver_receipt_file(report_file.id, force=True) - append_shipping_audit_event( - event_type='shipping_receipt_report_notification_resent', aggregate_type='shipping_receipt_file', - aggregate_id=str(report_file.id), actor_type='admin', actor_id=getattr(user, 'id', None), - owner_user_id=getattr(user, 'id', None), unit_id=report_file.unit_run_id, result='success', - after={'status': 'resent', 'owner_user_id': getattr(user, 'id', None)}, - artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], - metadata={'success_count': int(outcome.get('success_count', 0)), 'failed_count': int(outcome.get('failed_count', 0))}, - ) - db.session.commit() - return jsonify({'success': True, 'data': outcome}) - - -@schedule_admin_bp.route('/receipt-rpa-units', methods=['GET']) -@require_admin -def list_receipt_rpa_units(): - """管理员查看收料单元运行事实,供失败单元填写原因后人工重试。""" +def list_inbound_rpa_units(): + """管理员查看入站单元运行事实,供失败单元填写原因后人工重试。""" status = str(request.args.get('status') or '').strip().lower() if status and status not in {'queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled'}: from app.core.errors import ValidationError @@ -178,19 +164,19 @@ def list_receipt_rpa_units(): except (TypeError, ValueError): from app.core.errors import ValidationError raise ValidationError('limit is invalid') - query = ShippingReceiptRpaUnitRun.query.order_by( - ShippingReceiptRpaUnitRun.created_at.desc(), ShippingReceiptRpaUnitRun.id.desc(), + query = FreightRpaInboundUnitRun.query.order_by( + FreightRpaInboundUnitRun.created_at.desc(), FreightRpaInboundUnitRun.id.desc(), ) if status: - query = query.filter(ShippingReceiptRpaUnitRun.status == status) + query = query.filter(FreightRpaInboundUnitRun.status == status) units = query.limit(limit).all() user = get_current_user() append_shipping_audit_event( - event_type='shipping_receipt_rpa_units_listed', aggregate_type='shipping_receipt_unit_collection', + event_type='shipping_inbound_rpa_units_listed', aggregate_type='shipping_inbound_unit_collection', aggregate_id=str(getattr(user, 'id', 'admin')), actor_type='admin', actor_id=getattr(user, 'id', None), owner_user_id=getattr(user, 'id', None), result='success', after={'visible_count': len(units), 'status': status or None, 'limit': limit}, - metadata={'surface': 'workspace_receipt_report_files'}, + metadata={'surface': 'admin_inbound_rpa_units'}, ) db.session.commit() return jsonify({'success': True, 'data': {'items': [{ @@ -207,34 +193,34 @@ def list_receipt_rpa_units(): } for unit in units]}}) -@schedule_admin_bp.route('/receipt-rpa-units//retry', methods=['POST']) +@schedule_admin_bp.route('/inbound-rpa-units//retry', methods=['POST']) @require_admin -def retry_receipt_rpa_unit(unit_id: int): - """管理员为失败收料单元创建独立重试事实;旧单元永不覆盖。""" - failed = db.session.get(ShippingReceiptRpaUnitRun, unit_id) +def retry_inbound_rpa_unit(unit_id: int): + """管理员为失败入站单元创建独立重试事实;旧单元永不覆盖。""" + failed = db.session.get(FreightRpaInboundUnitRun, unit_id) if failed is None: - raise NotFoundError('Receipt RPA unit not found') + raise NotFoundError('Inbound RPA unit not found') if failed.status not in {'failed', 'cancelled'}: - raise ConflictError('Only failed receipt RPA units can be retried') + raise ConflictError('Only failed inbound RPA units can be retried') data = request.get_json(silent=True) or {} reason = str(data.get('reason') or '').strip() if not reason: from app.core.errors import ValidationError - raise ValidationError('reason is required', code='SHIPPING.RECEIPT_RETRY_REASON_REQUIRED') + raise ValidationError('reason is required', code='SHIPPING.INBOUND_RETRY_REASON_REQUIRED') user = get_current_user() - retry = ShippingReceiptRpaUnitRun( - schedule_run_id=failed.schedule_run_id, inventory_source_id=failed.inventory_source_id, + retry = FreightRpaInboundUnitRun( + schedule_run_id=failed.schedule_run_id, source_id=failed.source_id, retry_of_id=failed.id, source_code=failed.source_code, connector_type=failed.connector_type, - warehouse_id=failed.warehouse_id, callback_id=f'receipt:{uuid.uuid4().hex}', status='awaiting_rpa', + warehouse_id=failed.warehouse_id, callback_id=f'inbound:{uuid.uuid4().hex}', status='awaiting_rpa', config_snapshot_json=dict(failed.config_snapshot_json or {}), ) db.session.add(retry) db.session.flush() - source = retry.inventory_source + source = retry.source profile = source.rpa_profile if source is not None else None if source is None or profile is None or not profile.enabled: db.session.rollback() - raise ConflictError('Receipt RPA profile is unavailable') + raise ConflictError('Inbound RPA profile is unavailable') snapshot = dict(retry.config_snapshot_json or {}) trigger_unit = { 'unit_run_id': retry.id, 'callback_id': retry.callback_id, 'source_code': retry.source_code, @@ -247,20 +233,153 @@ def retry_receipt_rpa_unit(unit_id: int): } retry.trigger_snapshot_json = trigger_unit run = retry.schedule_run - trigger_path = write_receipt_export_batch_trigger( + trigger_path = write_inbound_export_batch_trigger( f'{run.run_no}-retry-{retry.id}', [trigger_unit], - {'schedule_run_id': run.id, 'schedule_task_id': run.schedule_task_id, 'schema_version': 'shipping_receipt_rpa.v1', 'retry_of_unit_id': failed.id}, + {'schedule_run_id': run.id, 'schedule_task_id': run.schedule_task_id, 'schema_version': SCHEMA, 'retry_of_unit_id': failed.id}, ) if not trigger_path: db.session.rollback() - raise ConflictError('Receipt RPA trigger directory is unavailable') + raise ConflictError('Inbound RPA trigger directory is unavailable') run.status = 'running' run.finished_at = None summary = dict(run.response_summary_json or {}) - summary['awaiting_receipt_rpa'] = True + summary['awaiting_inbound_rpa'] = True run.response_summary_json = summary append_shipping_audit_event( - event_type='shipping_receipt_rpa_unit_retried', aggregate_type='shipping_receipt_unit', + event_type='shipping_inbound_rpa_unit_retried', aggregate_type='shipping_inbound_unit', + aggregate_id=str(retry.id), actor_type='admin', actor_id=getattr(user, 'id', None), + owner_user_id=getattr(user, 'id', None), unit_id=retry.id, result='success', reason=reason, + before={'status': failed.status, 'error_code': failed.error_code}, + after={'status': retry.status, 'source_run_no': retry.callback_id, 'owner_user_id': getattr(user, 'id', None)}, + metadata={'retry_of_id': failed.id}, + ) + db.session.commit() + return jsonify({'success': True, 'data': {'unit_id': retry.id, 'retry_of_id': failed.id, 'callback_id': retry.callback_id, 'trigger_path': trigger_path}}) + + +@schedule_admin_bp.route('/schedule-runs//outbound-raw-zip', methods=['GET']) +@require_admin +def get_schedule_run_outbound_raw_zip(run_id: int): + """ + 下载出站 RPA 排程 run 的原始出站 Excel 打包(ZIP + manifest)。 + + 核心逻辑:对齐 inbound-raw-zip;展示名为 出站RPA-{日期}-{时刻}-出站.zip。 + """ + run = get_run(run_id) + if not run: + raise NotFoundError('Not found') + zip_path, file_name = resolve_outbound_raw_zip_download(run) + return send_file( + zip_path, + as_attachment=True, + download_name=file_name, + mimetype='application/zip', + ) + + +@schedule_admin_bp.route('/outbound-rpa-units', methods=['GET']) +@require_admin +def list_outbound_rpa_units(): + """管理员查出站单元运行事实,供失败单元填写原因后人工重试。""" + status = str(request.args.get('status') or '').strip().lower() + if status and status not in {'queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled'}: + from app.core.errors import ValidationError + raise ValidationError('status is invalid') + try: + limit = max(1, min(int(request.args.get('limit') or 100), 200)) + except (TypeError, ValueError): + from app.core.errors import ValidationError + raise ValidationError('limit is invalid') + query = FreightRpaOutboundUnitRun.query.order_by( + FreightRpaOutboundUnitRun.created_at.desc(), FreightRpaOutboundUnitRun.id.desc(), + ) + if status: + query = query.filter(FreightRpaOutboundUnitRun.status == status) + units = query.limit(limit).all() + user = get_current_user() + append_shipping_audit_event( + event_type='shipping_outbound_rpa_units_listed', aggregate_type='shipping_outbound_unit_collection', + aggregate_id=str(getattr(user, 'id', 'admin')), actor_type='admin', actor_id=getattr(user, 'id', None), + owner_user_id=getattr(user, 'id', None), result='success', + after={'visible_count': len(units), 'status': status or None, 'limit': limit}, + metadata={'surface': 'admin_outbound_rpa_units'}, + ) + db.session.commit() + return jsonify({'success': True, 'data': {'items': [{ + 'id': unit.id, + 'source_code': unit.source_code, + 'warehouse_id': unit.warehouse_id, + 'status': unit.status, + 'error_code': unit.error_code, + 'error_message': unit.error_message, + 'retry_of_id': unit.retry_of_id, + 'schedule_run_id': unit.schedule_run_id, + 'created_at': unit.created_at.isoformat() if unit.created_at else None, + 'finished_at': unit.finished_at.isoformat() if unit.finished_at else None, + } for unit in units]}}) + + +@schedule_admin_bp.route('/outbound-rpa-units//retry', methods=['POST']) +@require_admin +def retry_outbound_rpa_unit(unit_id: int): + """管理员为失败出站单元创建独立重试事实;旧单元永不覆盖。调拨按需单元无排程 run 时仍可重试。""" + failed = db.session.get(FreightRpaOutboundUnitRun, unit_id) + if failed is None: + raise NotFoundError('Outbound RPA unit not found') + if failed.status not in {'failed', 'cancelled'}: + raise ConflictError('Only failed outbound RPA units can be retried') + data = request.get_json(silent=True) or {} + reason = str(data.get('reason') or '').strip() + if not reason: + from app.core.errors import ValidationError + raise ValidationError('reason is required', code='SHIPPING.OUTBOUND_RETRY_REASON_REQUIRED') + user = get_current_user() + retry = FreightRpaOutboundUnitRun( + schedule_run_id=failed.schedule_run_id, source_id=failed.source_id, + retry_of_id=failed.id, source_code=failed.source_code, connector_type=failed.connector_type, + warehouse_id=failed.warehouse_id, callback_id=f'outbound:{uuid.uuid4().hex}', status='awaiting_rpa', + config_snapshot_json=dict(failed.config_snapshot_json or {}), + ) + db.session.add(retry) + db.session.flush() + source = retry.source + profile = source.rpa_profile if source is not None else None + if source is None or profile is None or not profile.enabled: + db.session.rollback() + raise ConflictError('Outbound RPA profile is unavailable') + snapshot = dict(retry.config_snapshot_json or {}) + trigger_unit = { + 'unit_run_id': retry.id, 'callback_id': retry.callback_id, 'source_code': retry.source_code, + 'connector_type': retry.connector_type, 'warehouse_id': retry.warehouse_id, + 'rpa_profile_id': profile.id, 'rpa_profile_code': profile.profile_code, 'login_url': profile.login_url, + 'login_config': dict(profile.login_config_json or {}), + 'credential_envelope': {'username_ciphertext': profile.username_ciphertext, 'password_ciphertext': profile.password_ciphertext}, + 'report_path_json': dict(snapshot.get('report_path_json') or {}), + 'query_parameters_json': list(snapshot.get('query_parameters_json') or []), 'config_snapshot': snapshot, + } + retry.trigger_snapshot_json = trigger_unit + run = retry.schedule_run + run_no = run.run_no if run is not None else f'outbound-retry-{retry.id}' + trigger_meta = { + 'schema_version': OUTBOUND_SCHEMA, 'retry_of_unit_id': failed.id, + } + if run is not None: + trigger_meta['schedule_run_id'] = run.id + trigger_meta['schedule_task_id'] = run.schedule_task_id + trigger_path = write_outbound_export_batch_trigger( + f'{run_no}-retry-{retry.id}', [trigger_unit], trigger_meta, + ) + if not trigger_path: + db.session.rollback() + raise ConflictError('Outbound RPA trigger directory is unavailable') + if run is not None: + run.status = 'running' + run.finished_at = None + summary = dict(run.response_summary_json or {}) + summary['awaiting_outbound_rpa'] = True + run.response_summary_json = summary + append_shipping_audit_event( + event_type='shipping_outbound_rpa_unit_retried', aggregate_type='shipping_outbound_unit', aggregate_id=str(retry.id), actor_type='admin', actor_id=getattr(user, 'id', None), owner_user_id=getattr(user, 'id', None), unit_id=retry.id, result='success', reason=reason, before={'status': failed.status, 'error_code': failed.error_code}, diff --git a/backend/app/api/tools/shipping_notice.py b/backend/app/api/tools/shipping_notice.py index 911427f9..bf9811cb 100644 --- a/backend/app/api/tools/shipping_notice.py +++ b/backend/app/api/tools/shipping_notice.py @@ -1,10 +1,11 @@ """ backend/app/api/tools/shipping_notice.py -用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。 -依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url。 +用途:暴露发货通知 Tool API,供 Dify Chatflow Agent 与导出下载入口调用。 +依赖:app.core.errors、app.core.tool_auth、shipping_notice.tools、query_service、openapi_spec、tool_api_url。 逻辑:register_blueprints 从 api.tools 挂载;Tool 成功响应仍用 status: ok/failed 业务 envelope; HTTP 级参数/资源错误统一 raise AppError;`_payload()` 剥离 body 中的操作人伪造字段; + RPA 回调已整体迁出至 api/freight_rpa.py(/api/freight-rpa/*,无双路由); 历史批次 Tool 已删除,订单抽取统一走 order-extraction-submissions。 """ from __future__ import annotations @@ -15,10 +16,8 @@ from app import db from app.core.errors import ( AppError, NotFoundError, - ServiceUnavailableError, - UnauthorizedError, - ValidationError, ) +from app.core.tool_auth import require_tool_auth from app.services.shipping_notice import tools as shipping_tools from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec from app.services.shipping_notice.query_service import ( @@ -28,40 +27,10 @@ from app.services.shipping_notice.query_service import ( serialize_task_summary, task_export_error_message, ) -from app.services.shipping_notice.rpa_worker_heartbeat import record_rpa_worker_heartbeat from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url shipping_notice_bp = Blueprint("shipping_notice", __name__) - -def _require_tool_auth() -> None: - """ - 校验货代 Tool API 鉴权 Header。 - 【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;当 Dify、RPA 或外部系统请求本蓝图时由 before_request 自动触发。 - - 核心逻辑:只接受 `Authorization: Bearer ` 或 `X-Integration-Key`。 - 货代专用 `SHIPPING_NOTICE_TOOL_API_KEY` 优先,未配置时回退 `INTEGRATION_API_KEY`; - 未配置任何可用 key 时报服务不可用,缺失或错误时报未授权。 - """ - configured = str( - current_app.config.get('SHIPPING_NOTICE_TOOL_API_KEY') - or current_app.config.get('INTEGRATION_API_KEY') - or '' - ).strip() - if not configured: - raise ServiceUnavailableError( - 'SHIPPING_NOTICE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured', - code='missing_auth', - ) - bearer = str(request.headers.get('Authorization') or '').strip() - token = bearer[7:].strip() if bearer.lower().startswith('bearer ') else '' - integration_key = str(request.headers.get('X-Integration-Key') or '').strip() - if configured in {token, integration_key}: - return - if not token and (not integration_key): - raise UnauthorizedError('missing_auth') - raise UnauthorizedError('invalid_auth') - def _tool_error_code(exc: AppError) -> str: """统一归一化 Tool API 的错误码,保持与文件检核 Tool 返回风格一致。""" message = str(exc.message or '').strip() @@ -84,12 +53,13 @@ def _handle_tool_app_error(exc: AppError): @shipping_notice_bp.before_request def _verify_tool_access(): """ - 对货代 Tool / RPA / 导出接口做统一 Header 鉴权。 - 核心逻辑:仅放行 OpenAPI 导入文档,其他请求都必须携带有效 Tool Key。 + 对货代 Tool / 导出接口做统一 Header 鉴权。 + 核心逻辑:仅放行 OpenAPI 导入文档,其他请求都必须携带有效 Tool Key + (鉴权实现见 app.core.tool_auth.require_tool_auth,与 freight-rpa 回调蓝图共用)。 """ if request.path.endswith('/openapi.json') or request.path.endswith('/openapi.dify.yaml'): return None - _require_tool_auth() + require_tool_auth() return None def _tool_api_base_url() -> str: @@ -229,7 +199,7 @@ def tool_ensure_inventory(): task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(), trigger='legacy_tool_ensure_inventory', operator_id=payload.get('operator_id'), - resume_gate_code='inventory_preparation', + resume_gate_code='onhand_preparation', )) @shipping_notice_bp.route('/tools/auto_progress', methods=['POST']) @@ -252,7 +222,7 @@ def tool_match_inventory(): task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(), trigger='legacy_tool_match_inventory', operator_id=payload.get('operator_id'), - resume_gate_code='inventory_matching', + resume_gate_code='onhand_matching', )) @shipping_notice_bp.route('/tools/confirm_customer', methods=['POST']) @@ -299,98 +269,6 @@ def tool_get_task_status(): _require_read_capability(payload, scope='get_shipping_status', task_no=task_no or None) return jsonify(shipping_tools.get_task_status(payload)) -@shipping_notice_bp.route('/rpa/heartbeat', methods=['POST']) -def rpa_worker_heartbeat(): - """ - RPA Worker 心跳上报。 - 核心逻辑:校验 payload 后写入 Redis/内存;供触发库存 RPA 前就绪检查使用。 - """ - payload = _payload() - try: - worker = record_rpa_worker_heartbeat(payload) - except ValueError as exc: - raise ValidationError(str(exc)) - except ServiceUnavailableError: - raise - return jsonify({'status': 'ok', 'message': 'heartbeat recorded', 'data': worker}) - - -@shipping_notice_bp.route('/rpa/inventory-ready', methods=['POST']) -def rpa_inventory_ready(): - """RPA 回调入口:上报库存导出结果并回写任务状态。""" - return jsonify(shipping_tools.rpa_report_inventory(_payload())) - -@shipping_notice_bp.route('/rpa/inventory-batch-ready', methods=['POST']) -def rpa_inventory_batch_ready(): - """RPA 批量库存导出回调:按 Warehouse 写入库存快照。""" - return jsonify(shipping_tools.rpa_report_inventory_batch(_payload())) - - -@shipping_notice_bp.route('/rpa/receipt-batch-ready', methods=['POST']) -def rpa_receipt_batch_ready(): - """收料 RPA 回调:独立归档文件,绝不进入库存回调或库存匹配链路。""" - from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback - - 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,供管理端实时看到进行中。 - - 本路由同时是收料超时对账的活动锚数据源(mark 落单元 started_at); - 曾因重构分叉合并丢失(2026-10-08),Worker 上报全程 404,勿再从旧路径文件删除。 - """ - 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(): - """收料 RPA 每完成一笔导出的累计进度回写(非终态,对齐库存 inventory-batch-progress)。""" - 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 执行阶段。""" - from app.services.shipping_notice.per_source_rpa_service import claim_inventory_batch - return jsonify({'success': True, 'data': claim_inventory_batch(_payload())}) - - -@shipping_notice_bp.route('/rpa/inventory-batch-progress', methods=['POST']) -def rpa_inventory_batch_progress(): - """RPA 批量库存导出进度回调:实时回写排程 run 计数(非终态,最终以 batch-ready 为准)。""" - from app.services.shipping_notice.inventory_rpa_workflow import report_inventory_batch_progress - return jsonify(report_inventory_batch_progress(_payload())) - - -@shipping_notice_bp.route('/rpa/inventory-configuration-test-ready', methods=['POST']) -def rpa_inventory_configuration_test_ready(): - """RPA 配置测试回调:仅分析文件结构,不创建生产库存快照或任务关联。""" - from app.services.shipping_notice import inventory_configuration_test - - return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_test_export(_payload())}) - - -@shipping_notice_bp.route('/rpa/inventory-configuration-test-batch-ready', methods=['POST']) -def rpa_inventory_configuration_test_batch_ready(): - """RPA 批量配置测试回调:按 validation_run_no 独立回写每个库存站点。""" - from app.services.shipping_notice import inventory_configuration_test - - return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_batch_test_exports(_payload())}) - - -@shipping_notice_bp.route('/rpa/inventory-configuration-test-batch-progress', methods=['POST']) -def rpa_inventory_configuration_test_batch_progress(): - """RPA 批量配置测试进度:Worker 领取单个站点后立即回写执行阶段。""" - from app.services.shipping_notice import inventory_configuration_test - - return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_batch_test_progress(_payload())}) - @shipping_notice_bp.route('/tasks//repair-inventory-attachment', methods=['POST']) def repair_task_inventory_attachment(task_no: str): """ @@ -402,19 +280,6 @@ def repair_task_inventory_attachment(task_no: str): payload.setdefault("task_id", task_no) return jsonify(shipping_tools.repair_task_inventory_attachment(payload)) - -@shipping_notice_bp.route('/rpa/inventory-repair', methods=['POST']) -def rpa_inventory_repair(): - """受控库存回调修复:复用正式 v2 ingest 链路。""" - payload = _payload() - payload['repair'] = True - return jsonify(shipping_tools.rpa_report_inventory_batch(payload)) - -@shipping_notice_bp.route('/rpa/upload-complete', methods=['POST']) -def rpa_upload_complete(): - """RPA 回调入口:上报货代上传结果并回写任务状态。""" - return jsonify(shipping_tools.rpa_report_upload(_payload())) - @shipping_notice_bp.route('/tasks//export', methods=['GET']) def download_task_export(task_no: str): """下载任务已生成的出货 Excel。""" diff --git a/backend/app/api/workspace/__init__.py b/backend/app/api/workspace/__init__.py index aaaeb6c0..e0dc462a 100644 --- a/backend/app/api/workspace/__init__.py +++ b/backend/app/api/workspace/__init__.py @@ -12,7 +12,7 @@ from app.api.workspace.shipping_notice import workspace_shipping_notice_bp from app.api.workspace.voucher_check import workspace_voucher_check_bp import app.api.workspace.shipping_process_gate # noqa: F401 -import app.api.workspace.shipping_inventory_candidates # noqa: F401 +import app.api.workspace.shipping_onhand_candidates # noqa: F401 __all__ = [ 'workspace_announcements_bp', diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index c31eda1f..d4b27ac7 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -87,34 +87,6 @@ def _ok(payload: Any, *, status: int = 200): return ok(payload, request_id=getattr(g, 'request_id', None), status=status) -@workspace_shipping_notice_bp.route('/receipt-report-files//download', methods=['GET']) -def workspace_download_receipt_report_file(file_id: int): - """下载当前接收人或管理员有权读取的原样收料报表。""" - user = _require_user() - from app.services.shipping_notice.receipt_report_access import resolve_receipt_report_download - - stream, filename, content_type = resolve_receipt_report_download(file_id, user) - response = send_file( - stream, as_attachment=True, download_name=filename, - mimetype=content_type or 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - ) - response.call_on_close(stream.close) - return response - - -@workspace_shipping_notice_bp.route('/receipt-report-files', methods=['GET']) -def workspace_list_receipt_report_files(): - """列出当前接收人或管理员可下载的收料归档文件,不返回对象存储定位。""" - user = _require_user() - try: - limit = int(request.args.get('limit') or 100) - except (TypeError, ValueError) as exc: - raise ValidationError('limit must be an integer') from exc - from app.services.shipping_notice.receipt_report_access import list_receipt_report_files - - return _ok({'items': list_receipt_report_files(user, limit=limit)}) - - def _assert_fulfillment_task_ownership(task: ShippingNotice, user_id: int) -> None: """ 履约写接口:若请求携带期望 OT/Case/Run,校验与正式 Notice 归属一致。 @@ -1308,11 +1280,11 @@ def workspace_shipping_task_inventory_file(task_no: str): task = get_task_for_user(task_no, user.id) if not task: raise NotFoundError('Not found') - from app.services.shipping_notice.inventory_file_store import resolve_task_inventory_download + from app.services.shipping_notice.onhand_file_store import resolve_task_inventory_download resolved = resolve_task_inventory_download(task) if resolved is None: - raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND') + raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_ONHAND_FILE_NOT_FOUND') path, download_name = resolved from app.services.shipping_notice.fulfillment_audit import record_access_audit record_access_audit( @@ -1338,30 +1310,31 @@ def workspace_shipping_task_line_inventory_file(task_no: str, inventory_file_no: raise NotFoundError('Not found') from pathlib import Path - from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch + from app.models import FreightRpaOnhandReportFile, ShippingNoticeLineOnhandMatch requested_file_no = str(inventory_file_no or '').strip() inventory_file = ( - ShippingInventoryFile.query + FreightRpaOnhandReportFile.query .join( - ShippingNoticeLineInventoryMatch, - ShippingNoticeLineInventoryMatch.inventory_snapshot_id == ShippingInventoryFile.id, + ShippingNoticeLineOnhandMatch, + ShippingNoticeLineOnhandMatch.onhand_snapshot_id == FreightRpaOnhandReportFile.id, ) .filter( - ShippingNoticeLineInventoryMatch.task_id == int(task.id), - ShippingNoticeLineInventoryMatch.is_current.is_(True), - ShippingNoticeLineInventoryMatch.matched_file_no == requested_file_no, - ShippingInventoryFile.inventory_file_no == requested_file_no, + ShippingNoticeLineOnhandMatch.task_id == int(task.id), + ShippingNoticeLineOnhandMatch.is_current.is_(True), + ShippingNoticeLineOnhandMatch.matched_file_no == requested_file_no, + FreightRpaOnhandReportFile.onhand_file_no == requested_file_no, ) .first() ) storage_path = str(getattr(inventory_file, 'storage_path', '') or '').strip() path = Path(storage_path).resolve() if storage_path else None if inventory_file is None or not storage_path or storage_path.startswith('failed://') or not path.is_file(): - raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND') - download_name = str( - inventory_file.source_file_name or f'{inventory_file.inventory_file_no}{path.suffix or ".xlsx"}', - ).strip() + raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_ONHAND_FILE_NOT_FOUND') + from app.services.shipping_notice.onhand_file_store import build_inventory_download_name + download_name = build_inventory_download_name( + inventory_file, source_file_name=inventory_file.source_file_name, path=path, + ) from app.services.shipping_notice.fulfillment_audit import record_access_audit record_access_audit( action='download_task_line_inventory_file', diff --git a/backend/app/api/workspace/shipping_inventory_candidates.py b/backend/app/api/workspace/shipping_onhand_candidates.py similarity index 93% rename from backend/app/api/workspace/shipping_inventory_candidates.py rename to backend/app/api/workspace/shipping_onhand_candidates.py index 05053fdf..b92ce18d 100644 --- a/backend/app/api/workspace/shipping_inventory_candidates.py +++ b/backend/app/api/workspace/shipping_onhand_candidates.py @@ -1,8 +1,8 @@ """ -backend/app/api/workspace/shipping_inventory_candidates.py +backend/app/api/workspace/shipping_onhand_candidates.py 用途:正式 Task 库存候选只读详情 API。 -依赖:workspace_shipping_notice_bp、query_service.get_task_for_user、inventory_candidate_projection。 +依赖:workspace_shipping_notice_bp、query_service.get_task_for_user、onhand_candidate_projection。 逻辑:路由层仅做鉴权与查询参数校验;当前版本缺失返回 200 + current_set=null + blocking_reason, 不把可恢复业务阻断误报成 404。 """ @@ -13,7 +13,7 @@ from flask import request from app.api.workspace.shipping_notice import _ok, _require_user, workspace_shipping_notice_bp from app.core.errors import ValidationError -from app.services.shipping_notice.inventory_candidate_projection import ( +from app.services.shipping_notice.onhand_candidate_projection import ( project_inventory_candidate_detail, ) from app.services.shipping_notice.query_service import get_task_for_user diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index 9889cdc5..46725e5e 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -299,9 +299,6 @@ class Config: 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') ) @@ -373,14 +370,18 @@ class Config: SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY = float( os.getenv('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY') or '0.98' ) - SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = ( - os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true' + SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED = ( + os.getenv('SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED', 'true').lower() == 'true' ) - FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS = int( - os.getenv('FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS') or '900' + FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS = int( + os.getenv('FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS') or '900' ) - FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS = int( - os.getenv('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS') or '900' + FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS = int( + os.getenv('FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS') or '900' + ) + # 出站抓取本期无 Worker;超时键与 inbound 同形预留,避免后续批次再改 env 骨架。 + FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS = int( + os.getenv('FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS') or '900' ) FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int( os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90' @@ -442,38 +443,51 @@ class Config: SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS = int( os.getenv('SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS') or '24' ) - SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED = ( - os.getenv('SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED', 'true').lower() == 'true' + SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED = ( + os.getenv('SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED', 'true').lower() == 'true' ) SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS') FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP') - # RPA 运行期数据目录统一为 `freight_rpa/{inventory,receipt,common}` 三层布局(与 env/ps1 三侧一致)。 - FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR = _rpa_data_path( - 'FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR', 'freight_rpa', 'inventory', 'drop' + # RPA 运行期数据目录分域(2026-10-16 批次 R): + # onhand/ inbound/ outbound/ — 抓取域,叶目录同构 triggers|drop|logs|archives + # upload/ — 上传域,叶目录 triggers|queue(与抓取域并列,勿挂 outbound 下) + # common/ — 跨 Worker 共享(browser_profile) + # outbound 本期无 Worker,仍落盘同构目录 + env,避免切换日再改骨架。 + FREIGHT_RPA_SHARED_ONHAND_DROP_DIR = _rpa_data_path( + 'FREIGHT_RPA_SHARED_ONHAND_DROP_DIR', 'freight_rpa', 'onhand', 'drop' ) - FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR = _rpa_data_path( - 'FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR', 'freight_rpa', 'inventory', 'triggers' + FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR = _rpa_data_path( + 'FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR', 'freight_rpa', 'onhand', 'triggers' ) - FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR = _rpa_data_path( - 'FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR', 'freight_rpa', 'receipt', 'drop' + FREIGHT_RPA_SHARED_INBOUND_DROP_DIR = _rpa_data_path( + 'FREIGHT_RPA_SHARED_INBOUND_DROP_DIR', 'freight_rpa', 'inbound', 'drop' ) - FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR = _rpa_data_path( - 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', 'freight_rpa', 'receipt', 'triggers' + FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR = _rpa_data_path( + 'FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR', 'freight_rpa', 'inbound', 'triggers' + ) + FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR = _rpa_data_path( + 'FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR', 'freight_rpa', 'outbound', 'drop' + ) + FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR = _rpa_data_path( + 'FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR', 'freight_rpa', 'outbound', 'triggers' ) FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = _rpa_data_path( - 'FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR', 'freight_rpa', 'inventory', 'upload_queue' + 'FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR', 'freight_rpa', 'upload', 'queue' ) FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = _rpa_data_path( - 'FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR', 'freight_rpa', 'inventory', 'upload_triggers' + 'FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR', 'freight_rpa', 'upload', 'triggers' ) FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = _rpa_data_path( 'FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR', 'freight_rpa', 'common', 'browser_profile' ) - FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = _rpa_data_path( - 'FREIGHT_RPA_INVENTORY_ARCHIVE_DIR', 'freight_rpa', 'inventory', 'archives' + FREIGHT_RPA_ONHAND_ARCHIVE_DIR = _rpa_data_path( + 'FREIGHT_RPA_ONHAND_ARCHIVE_DIR', 'freight_rpa', 'onhand', 'archives' ) - FREIGHT_RPA_RECEIPT_ARCHIVE_DIR = _rpa_data_path( - 'FREIGHT_RPA_RECEIPT_ARCHIVE_DIR', 'freight_rpa', 'receipt', 'archives' + FREIGHT_RPA_INBOUND_ARCHIVE_DIR = _rpa_data_path( + 'FREIGHT_RPA_INBOUND_ARCHIVE_DIR', 'freight_rpa', 'inbound', 'archives' + ) + FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR = _rpa_data_path( + 'FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR', 'freight_rpa', 'outbound', 'archives' ) FREIGHT_RPA_WORKER_MOCK = os.getenv('FREIGHT_RPA_WORKER_MOCK', 'false') diff --git a/backend/app/core/errors.py b/backend/app/core/errors.py index 2e17a36e..c52ef63b 100644 --- a/backend/app/core/errors.py +++ b/backend/app/core/errors.py @@ -28,11 +28,14 @@ class ValidationError(AppError): *, code: str = "VALIDATION.INVALID_PARAM", details: dict[str, Any] | None = None, + http_status: int = 400, ): super().__init__( code=code, message=message, - http_status=400, + # 默认 400(参数形态类校验);业务契约指定状态码时显式传入 + # (如调拨类型门禁 REQUIRED/NOT_CONFIGURED/DISABLED = 422,规格 §11)。 + http_status=http_status, details=details or {}, retryable=False, ) diff --git a/backend/app/core/tool_auth.py b/backend/app/core/tool_auth.py new file mode 100644 index 00000000..1620401a --- /dev/null +++ b/backend/app/core/tool_auth.py @@ -0,0 +1,45 @@ +""" +backend/app/core/tool_auth.py + +用途:集成密钥鉴权的公共实现,供所有以 Bearer / X-Integration-Key 方式接入的 + Tool / 回调蓝图共用(当前:shipping_notice Tool 蓝图、freight-rpa 回调蓝图)。 +依赖:flask.current_app/request、app.core.errors(ServiceUnavailableError / UnauthorizedError)。 +逻辑:由各蓝图 before_request 调用 require_tool_auth();本模块只做 Header 校验, + 不感知任何具体蓝图的错误 envelope(由蓝图自身 errorhandler 决定响应格式)。 +""" + +from __future__ import annotations + +from flask import current_app, request + +from app.core.errors import ServiceUnavailableError, UnauthorizedError + + +def require_tool_auth() -> None: + """ + 校验集成方 Tool / RPA 回调 API 鉴权 Header。 + 【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;当 Dify、RPA Worker 或 + 外部系统请求挂接本鉴权的蓝图时,由该蓝图的 before_request 自动触发。 + + 核心逻辑:只接受 `Authorization: Bearer ` 或 `X-Integration-Key`。 + 货代专用 `SHIPPING_NOTICE_TOOL_API_KEY` 优先,未配置时回退 `INTEGRATION_API_KEY`; + 未配置任何可用 key 时报服务不可用,缺失或错误时报未授权。 + """ + configured = str( + current_app.config.get('SHIPPING_NOTICE_TOOL_API_KEY') + or current_app.config.get('INTEGRATION_API_KEY') + or '' + ).strip() + if not configured: + raise ServiceUnavailableError( + 'SHIPPING_NOTICE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured', + code='missing_auth', + ) + bearer = str(request.headers.get('Authorization') or '').strip() + token = bearer[7:].strip() if bearer.lower().startswith('bearer ') else '' + integration_key = str(request.headers.get('X-Integration-Key') or '').strip() + if configured in {token, integration_key}: + return + if not token and (not integration_key): + raise UnauthorizedError('missing_auth') + raise UnauthorizedError('invalid_auth') diff --git a/backend/app/jobs/handlers/__init__.py b/backend/app/jobs/handlers/__init__.py index 49105fc8..49a9622d 100644 --- a/backend/app/jobs/handlers/__init__.py +++ b/backend/app/jobs/handlers/__init__.py @@ -16,7 +16,7 @@ from app.jobs.handlers import ( # noqa: F401 procurement_contract_review, schedule_run, shipping_document_layout, - shipping_inventory_callback_process, + freight_rpa_onhand_callback_process, shipping_notice_parse, shipping_notice_run, shipping_order_extraction, diff --git a/backend/app/jobs/handlers/shipping_inventory_callback_process.py b/backend/app/jobs/handlers/freight_rpa_onhand_callback_process.py similarity index 55% rename from backend/app/jobs/handlers/shipping_inventory_callback_process.py rename to backend/app/jobs/handlers/freight_rpa_onhand_callback_process.py index 0fd3fe3a..68ca3baf 100644 --- a/backend/app/jobs/handlers/shipping_inventory_callback_process.py +++ b/backend/app/jobs/handlers/freight_rpa_onhand_callback_process.py @@ -1,9 +1,13 @@ """ -backend/app/jobs/handlers/shipping_inventory_callback_process.py +backend/app/jobs/handlers/freight_rpa_onhand_callback_process.py 用途:异步处理已收件的库存 RPA batch 回调,避免 Worker HTTP 回调被 Excel 处理阻塞。 -依赖:Job 队列、inventory_rpa_workflow 的正式批量处理函数。 +依赖:Job 队列、onhand_rpa_workflow 的正式批量处理函数。 逻辑:HTTP 回调只写本 Job;shipping worker 领取后执行结构校验、库存解析、任务关联与后续推进。 + 业务失败(transport/result_status=failed)收口为不可重试;意外异常(含批量 commit 后 + onhand 事实处理函数失败的重抛)收口为可重试(Task 7 修复轮 2——文件行已提交不回滚, + 重放按幂等契约补齐候选/门禁收口);修复轮 3:投递失败重抛携带的未成功文件清单写回 + payload(retry_dispatch_files),重试经批量入口的「只重投失败文件」通道补齐。 """ from __future__ import annotations @@ -16,7 +20,7 @@ from app.jobs.types import JobType from app.models import Job -@register_handler(JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS) +@register_handler(JobType.FREIGHT_RPA_ONHAND_CALLBACK_PROCESS) def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> None: """处理一个已收件的库存 RPA 回调。 @@ -31,7 +35,7 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N owned_attempt = int(job.attempts or 0) try: - from app.services.shipping_notice.inventory_rpa_workflow import process_rpa_report_inventory_batch + from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch result = process_rpa_report_inventory_batch(dict(job.payload_json or {})) result_data = result.get('data') if isinstance(result, dict) else None @@ -44,7 +48,7 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N if transport_status == 'failed' or result_status in {'failed', 'partial_failed'}: failed_items = result_data.get('failed') if isinstance(result_data, dict) else [] first_error = failed_items[0].get('error') if isinstance(failed_items, list) and failed_items and isinstance(failed_items[0], dict) else None - from app.services.shipping_notice.inventory_rpa_workflow import settle_failed_inventory_callback + from app.services.shipping_notice.onhand_rpa_workflow import settle_failed_inventory_callback settle_failed_inventory_callback( dict(job.payload_json or {}), @@ -64,12 +68,32 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N message='库存 RPA 回调已异步处理', owned_attempt=owned_attempt, ) - except Exception as exc: # noqa: BLE001 - queue must retain retryable receipt evidence + except Exception as exc: # noqa: BLE001 - 队列收口保留可重试证据 db.session.rollback() + # 【Task 7 修复轮 3】批量 commit 后投递失败的重抛携带「未成功文件清单」—— + # 写回 Job payload(retry_dispatch_files),重试经批量入口的「只重投失败 + # 文件」通道补齐(整批重放会被 callback_id 已消费的 replay 检查跳过、 + # 已收口的排程 run 校验拦下);清单随重试结果逐轮收敛,直至全部成功或 + # attempts 耗尽。普通意外异常(无清单)仍整批自然重放。 + from app.services.shipping_notice.onhand_rpa_workflow import ( + OnhandReportDispatchAfterCommitError, + ) + + if isinstance(exc, OnhandReportDispatchAfterCommitError) and exc.failed_files: + job.payload_json = { + **(dict(job.payload_json or {})), + 'retry_dispatch_files': list(exc.failed_files), + } + db.session.commit() fail_job( job.id, error=str(exc), result={'status': 'processing_failed', 'error': str(exc)[:1000]}, - retryable=False, + # 【Task 7 修复轮 2】意外异常(含批量 commit 后 onhand 事实处理函数失败 + # ——process_rpa_report_inventory_batch 已尽力完成其余投递、排程收口与 + # drop 文件清理入队后原样重抛)必须可重试:文件行已提交不回滚,重放按 + # 幂等契约补齐收口;业务失败(transport/result_status=failed)仍走上方 + # retryable=False 分支。 + retryable=True, owned_attempt=owned_attempt, ) diff --git a/backend/app/jobs/handlers/in_transit_transfer_match.py b/backend/app/jobs/handlers/in_transit_transfer_match.py index f316d5d8..36e07ad0 100644 --- a/backend/app/jobs/handlers/in_transit_transfer_match.py +++ b/backend/app/jobs/handlers/in_transit_transfer_match.py @@ -5,6 +5,13 @@ 逻辑:领取后按 payload.matching_id 加载匹配,运行 run_matching 并回写 状态/计数/Hash;匹配不存在时 fail-closed 抛 RuntimeError。业务收尾后 handler 自行 finish_job(runner 仅兜底异常路径,正常完成不代收口)。 + 【2026-10-14 出生翻转/快照自足确认】异步重跑的全部口径从 scope_json + 快照回读——transfer_type 编码 + scope_rules/transform_rules 覆盖传入 + (不读现行配置规则,在途匹配口径不被中途改配置扰动);类型门禁按 + require_enabled=False(「停用后存量不受影响」,规格 §4.1),仅要求配置 + 仍存在(类型只有停用没有删除)。run_matching 传 matching_id:重跑圈档 + 仅补建「未被有效 items 占用」的新档记录(D17:自有 items 不重复圈定/ + 不重复评估他匹配行),并刷新本匹配自有 items。 """ from __future__ import annotations @@ -36,6 +43,8 @@ def run_in_transit_transfer_match(_ctx, payload: dict) -> None: owned_attempt = int(job_row.attempts) if job_row is not None else None deps = transfer_deps.get_transfer_dependencies() + # [快照自足] 类型/范围/转换规则全部回读 scope_json(无枚举依赖、不查现行 + # 配置规则);warehouse 路由的 fixed 定义随类型配置现行值(未入快照契约)。 scope = matching.scope_json if isinstance(matching.scope_json, dict) else {} source_codes = list(scope.get("source_codes") or []) result = run_matching( @@ -43,14 +52,18 @@ def run_in_transit_transfer_match(_ctx, payload: dict) -> None: business_date=matching.business_date, deps=deps, run_no=matching.run.run_no if matching.run else "RUN-PENDING", - # 类型范围随匹配落库回读:异步重跑与创建时口径一致(缺省回落类型1)。 transfer_type=str(scope.get("transfer_type")) if scope.get("transfer_type") else None, + matching_id=matching.id, + scope_rules_override=scope.get("scope_rules") if isinstance(scope.get("scope_rules"), list) else None, + transform_rules_override=( + scope.get("transform_rules") if isinstance(scope.get("transform_rules"), list) else None + ), + require_enabled=False, # 存量重跑:停用类型不受影响(仅要求配置仍存在) ) summary = result.summary matching.status = summary.status matching.counts_json = { "file_invoice_count": summary.counts.file_invoice_count, - "not_matured_count": summary.counts.not_matured_count, "matched_count": summary.counts.matched_count, "executable_count": summary.counts.executable_count, "blocked_count": summary.counts.blocked_count, diff --git a/backend/app/jobs/types.py b/backend/app/jobs/types.py index 91830e23..b22cbef2 100644 --- a/backend/app/jobs/types.py +++ b/backend/app/jobs/types.py @@ -3,7 +3,9 @@ backend/app/jobs/types.py 用途:Job 类型与状态枚举;KbJob.job_type 与 handler JobType 的双向映射。 逻辑:handlers 与 queue 通过 JobType 注册;store 持久化仍走 KbJob 表(Wave 2 双轨); - shipping_process_gate 由 shipping worker 与发货通知任务同队列领取。 + shipping_process_gate 由 shipping worker 与发货通知任务同队列领取; + 在手回调成员 FREIGHT_RPA_ONHAND_CALLBACK_PROCESS 的持久化值为 + freight_rpa_onhand_callback_process。 """ from __future__ import annotations @@ -20,8 +22,9 @@ class JobType(StrEnum): SHIPPING_ORDER_EXTRACTION = 'shipping_order_extraction' SHIPPING_DOCUMENT_LAYOUT = 'shipping_document_layout' SHIPPING_PROCESS_GATE = 'shipping_process_gate' - # RPA 回调 HTTP 只收件;Excel 校验、解析、任务关联由 shipping worker 异步完成。 - SHIPPING_INVENTORY_CALLBACK_PROCESS = 'shipping_inventory_callback_process' + # 在手 RPA 回调 HTTP 只收件;Excel 校验、解析、任务关联由 shipping worker 异步完成。 + # 持久化 jobs.job_type 为 freight_rpa_onhand_callback_process。 + FREIGHT_RPA_ONHAND_CALLBACK_PROCESS = 'freight_rpa_onhand_callback_process' # 统一 PDF 自动标记:按实际证据能力执行坐标重建或 XFA 多源视觉融合。 SHIPPING_PDF_AUTOMARK = 'shipping_pdf_automark' # 资格达标后的 STP 自动建单入队(先 queued,再由 worker 执行 confirm) @@ -76,7 +79,7 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = { 'shipping': frozenset({ 'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction', 'shipping_document_layout', 'shipping_process_gate', 'shipping_pdf_automark', - 'shipping_inventory_callback_process', + 'freight_rpa_onhand_callback_process', 'shipping_stp_auto_create', 'shipping_line_auto_fulfill', 'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress', }), diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index 34bd23d1..dda8657d 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -2,8 +2,9 @@ backend/app/models/__init__.py 用途:按业务域拆分的 ORM 模型包入口;聚合导出以保持 `from app.models import User` 兼容。 -依赖:models/* 子模块(含 voucher_check、equipment_acceptance)、app.extensions.db(经 base.Base)。 +依赖:models/* 子模块(含 voucher_check、equipment_acceptance、freight_rpa_*)、app.extensions.db(经 base.Base)。 逻辑:Alembic / Flask-Migrate 通过本模块 import 注册全部表元数据;业务代码继续从此处导入模型类。 + 在手/入站/出站模型导出 FreightRpa*。 """ from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest @@ -31,15 +32,15 @@ from app.models.contract_payment import ( ContractPaymentVendorRequest, ) from app.models.shipping import ( - ShippingInventoryFile, ShippingNotice, ShippingOrderCandidate, ShippingOrderDocument, ShippingOrderIntake, ShippingTaskEvent, ShippingTaskPurgeAudit, - ShippingTaskInventoryLink, + ShippingTaskOnhandLink, ) +from app.models.freight_rpa_onhand_report_file import FreightRpaOnhandReportFile from app.models.shipping_order_submission import ShippingOrderSubmission from app.models.shipping_order_task import ShippingOrderTask from app.models.shipping_order_candidate_evidence import ShippingOrderCandidateEvidence @@ -52,8 +53,8 @@ from app.models.shipping_context_provider import ShippingContextProvider, Shippi from app.models.shipping_excel_template import ShippingExcelTemplate, ShippingExportArtifact from app.models.shipping_fulfillment import ( ShippingExportArtifactLine, - ShippingInventoryVerification, - ShippingInventoryVerificationLine, + ShippingOnhandVerification, + ShippingOnhandVerificationLine, ShippingReservation, ShippingUploadAttempt, ) @@ -95,7 +96,7 @@ from app.models.shipping_order_review import ( from app.models.shipping_order_review_line_decision import ShippingOrderReviewLineDecision from app.models.shipping_order_review_wave_line import ShippingOrderReviewWaveLine from app.models.shipping_order_review_wave_idempotency import ShippingOrderReviewWaveIdempotency -from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch +from app.models.shipping_notice_line_onhand_match import ShippingNoticeLineOnhandMatch from app.models.shipping_order_review_suggestion import ShippingOrderReviewSuggestion from app.models.shipping_order_extraction_run import ( ShippingOrderExtractionDiagnosticAudit, @@ -137,27 +138,32 @@ from app.models.shipping_document_layout import ShippingDocumentLayoutVersion from app.models.shipping_eml_preview_snapshot import ShippingEmlPreviewSnapshot from app.models.shipping_xfa_structure_analysis import ShippingXfaStructureAnalysis from app.models.shipping_xfa_audit_snapshot import ShippingXfaAuditSnapshot -from app.models.shipping_inventory_config import ( - ShippingInventoryField, - ShippingInventoryExternalMapping, - ShippingInventoryConfigurationTestRun, - ShippingInventoryValidationBatch, - ShippingInventorySourceParsingBindingAudit, - ShippingInventoryParsingProfile, - ShippingInventoryRoutingRule, - ShippingInventoryRoutingRuleCondition, - ShippingInventoryRoutingRuleVersion, - ShippingInventorySource, - ShippingInventoryStructureAnalysis, - ShippingRpaProfile, +from app.models.freight_rpa_config import ( + FreightRpaOnhandField, + FreightRpaOnhandExternalMapping, + FreightRpaOnhandConfigurationTestRun, + FreightRpaOnhandValidationBatch, + FreightRpaSourceParsingBindingAudit, + FreightRpaParsingProfile, + FreightRpaOnhandRoutingRule, + FreightRpaOnhandRoutingRuleCondition, + FreightRpaOnhandRoutingRuleVersion, + FreightRpaSource, + FreightRpaOnhandReportConfig, + FreightRpaOnhandStructureAnalysis, + FreightRpaProfile, ) -from app.models.shipping_receipt_report import ( - ShippingReceiptNotificationDelivery, - ShippingReceiptReportConfig, - ShippingReceiptReportFile, - ShippingReceiptRpaUnitRun, +from app.models.freight_rpa_inbound_report import ( + FreightRpaInboundReportConfig, + FreightRpaInboundReportFile, + FreightRpaInboundUnitRun, ) -from app.models.shipping_temporary_inventory import ShippingTemporaryInventorySession +from app.models.freight_rpa_outbound_report import ( + FreightRpaOutboundReportConfig, + FreightRpaOutboundReportFile, + FreightRpaOutboundUnitRun, +) +from app.models.shipping_temporary_onhand import ShippingTemporaryOnhandSession from app.models.shipping_customer import ( ShippingBusinessSequence, ShippingCustomer, @@ -180,18 +186,18 @@ from app.models.shipping_identity_rule import ( ShippingIdentityRuleAuditEvent, ShippingIdentityRuleSet, ) -from app.models.shipping_inventory_candidates import ( - ShippingInventoryCandidateLine, - ShippingInventoryCandidateSet, - ShippingInventoryCandidateSource, +from app.models.shipping_onhand_candidates import ( + ShippingOnhandCandidateLine, + ShippingOnhandCandidateSet, + ShippingOnhandCandidateSource, ) -from app.models.shipping_task_inventory_rpa_attempts import ShippingTaskInventoryRpaAttempt +from app.models.freight_rpa_onhand_task_attempts import FreightRpaOnhandTaskAttempt from app.models.shipping_process_recovery_plan import ShippingProcessRecoveryPlan -from app.models.shipping_inventory_preparation import ( - ShippingInventoryPreparationAttempt, - ShippingInventoryPreparationSourceAttempt, +from app.models.shipping_onhand_preparation import ( + ShippingOnhandPreparationAttempt, + ShippingOnhandPreparationSourceAttempt, ) -from app.models.shipping_inventory_mapping import ShippingInventoryMapping +from app.models.freight_rpa_onhand_mapping import FreightRpaOnhandMapping from app.models.training import ( LeanTrainingCompletion, LeanTrainingReminder, @@ -208,8 +214,10 @@ from app.models.in_transit_transfer import ( TransferDocument, TransferInvoiceItem, TransferMatching, + TransferMovementLedger, TransferRun, TransferSourceJob, + TransferTypeConfig, ) from app.models.integration_connector import ( IntegrationBinding, @@ -317,7 +325,7 @@ __all__ = [ 'ShippingOrderReviewLineDecision', 'ShippingOrderReviewWaveLine', 'ShippingOrderReviewWaveIdempotency', - 'ShippingNoticeLineInventoryMatch', + 'ShippingNoticeLineOnhandMatch', 'ShippingOrderReviewSuggestion', 'ShippingOrderProcessingRun', 'ShippingOrderProcessingRunIntake', @@ -366,30 +374,33 @@ __all__ = [ 'ShippingIdentityRuleAuditEvent', 'ShippingTaskEvent', 'ShippingTaskPurgeAudit', - 'ShippingInventoryFile', - 'ShippingTaskInventoryLink', - 'ShippingRpaProfile', - 'ShippingInventorySource', - 'ShippingReceiptReportConfig', - 'ShippingReceiptRpaUnitRun', - 'ShippingReceiptReportFile', - 'ShippingReceiptNotificationDelivery', - 'ShippingInventoryField', - 'ShippingInventoryStructureAnalysis', - 'ShippingInventoryRoutingRule', - 'ShippingInventoryRoutingRuleCondition', - 'ShippingInventoryRoutingRuleVersion', - 'ShippingInventoryExternalMapping', - 'ShippingInventoryConfigurationTestRun', - 'ShippingInventoryValidationBatch', - 'ShippingInventorySourceParsingBindingAudit', - 'ShippingInventoryParsingProfile', - 'ShippingTemporaryInventorySession', + 'FreightRpaOnhandReportFile', + 'ShippingTaskOnhandLink', + 'FreightRpaProfile', + 'FreightRpaSource', + 'FreightRpaOnhandReportConfig', + 'FreightRpaInboundReportConfig', + 'FreightRpaInboundUnitRun', + 'FreightRpaInboundReportFile', + 'FreightRpaOutboundReportConfig', + 'FreightRpaOutboundUnitRun', + 'FreightRpaOutboundReportFile', + 'FreightRpaOnhandField', + 'FreightRpaOnhandStructureAnalysis', + 'FreightRpaOnhandRoutingRule', + 'FreightRpaOnhandRoutingRuleCondition', + 'FreightRpaOnhandRoutingRuleVersion', + 'FreightRpaOnhandExternalMapping', + 'FreightRpaOnhandConfigurationTestRun', + 'FreightRpaOnhandValidationBatch', + 'FreightRpaSourceParsingBindingAudit', + 'FreightRpaParsingProfile', + 'ShippingTemporaryOnhandSession', 'ShippingExcelTemplate', 'ShippingExportArtifact', 'ShippingReservation', - 'ShippingInventoryVerification', - 'ShippingInventoryVerificationLine', + 'ShippingOnhandVerification', + 'ShippingOnhandVerificationLine', 'ShippingExportArtifactLine', 'ShippingUploadAttempt', 'ShippingProcessExecution', @@ -424,10 +435,10 @@ __all__ = [ 'MaintenanceDevice', 'MaintenanceRecord', 'MaintenanceAuditLog', - 'ShippingInventoryCandidateSet', - 'ShippingInventoryCandidateSource', - 'ShippingInventoryCandidateLine', - 'ShippingTaskInventoryRpaAttempt', + 'ShippingOnhandCandidateSet', + 'ShippingOnhandCandidateSource', + 'ShippingOnhandCandidateLine', + 'FreightRpaOnhandTaskAttempt', 'VoucherCheckProfile', 'VoucherCheckRun', 'VoucherCheckSubject', @@ -456,6 +467,8 @@ __all__ = [ 'TransferAttempt', 'TransferAuditEvent', 'TransferArchive', + 'TransferTypeConfig', + 'TransferMovementLedger', 'IntegrationCredentialReference', 'IntegrationClientInstance', 'IntegrationInterfaceDefinition', diff --git a/backend/app/models/shipping_inventory_config.py b/backend/app/models/freight_rpa_config.py similarity index 68% rename from backend/app/models/shipping_inventory_config.py rename to backend/app/models/freight_rpa_config.py index b9d28d5c..481cfe28 100644 --- a/backend/app/models/shipping_inventory_config.py +++ b/backend/app/models/freight_rpa_config.py @@ -1,9 +1,11 @@ """ -models/shipping_inventory_config.py +backend/app/models/freight_rpa_config.py -用途:定义货代库存源、RPA Profile、通用路由规则及外部系统仓库映射主数据。 -依赖:models.base.Base、SQLAlchemy ORM;凭据密文由 shipping_notice.credential_crypto 读写。 -逻辑:库存运行链路以 ShippingInventorySource.source_code 为业务主键;RPA Profile 仅提供登录连接配置, +用途:定义货代库存源、RPA Profile、在手/入站/出站报表配置、通用路由规则及外部系统仓库映射主数据。 +依赖:models.base.Base、SQLAlchemy ORM;凭据密文由 freight_rpa.common.credential_crypto 读写。 +逻辑:库存运行链路以 FreightRpaSource.source_code 为业务主键;RPA Profile 仅提供登录连接配置; + 在手报表路径/查询条件/解析方案绑定自 s18 起归 FreightRpaOnhandReportConfig(站点行不再存这三列), + 入站/出站配置分别挂 inbound_report_config / outbound_report_config 一对一关系; 外部系统映射仅供后端内部复用,不承载调拨决策。 """ @@ -18,18 +20,18 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship from app.models.base import Base -class ShippingInventoryField(Base): +class FreightRpaOnhandField(Base): """用户维护的库存业务字段目录;程序仅依据字段 ID 和业务用途运行。""" - __tablename__ = 'shipping_inventory_fields' + __tablename__ = 'freight_rpa_onhand_fields' __table_args__ = ( - UniqueConstraint('field_code', name='uq_shipping_inventory_fields_code'), - UniqueConstraint('display_name', name='uq_shipping_inventory_fields_display_name'), - CheckConstraint("status IN ('active', 'retired')", name='ck_shipping_inventory_fields_status'), - CheckConstraint("value_type IN ('text', 'integer', 'decimal', 'date')", name='ck_shipping_inventory_fields_value_type'), + UniqueConstraint('field_code', name='uq_freight_rpa_onhand_fields_code'), + UniqueConstraint('display_name', name='uq_freight_rpa_onhand_fields_display_name'), + CheckConstraint("status IN ('active', 'retired')", name='ck_freight_rpa_onhand_fields_status'), + CheckConstraint("value_type IN ('text', 'integer', 'decimal', 'date')", name='ck_freight_rpa_onhand_fields_value_type'), CheckConstraint( "usage_type IN ('match_identity', 'inventory_quantity', 'warehouse_identity', 'general')", - name='ck_shipping_inventory_fields_usage_type', + name='ck_freight_rpa_onhand_fields_usage_type', ), ) @@ -48,13 +50,13 @@ class ShippingInventoryField(Base): updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) -class ShippingRpaProfile(Base): +class FreightRpaProfile(Base): """货代库存登录连接配置;凭据字段始终保存密文。""" - __tablename__ = 'shipping_rpa_profiles' + __tablename__ = 'freight_rpa_profiles' __table_args__ = ( - UniqueConstraint('profile_code', name='uq_shipping_rpa_profiles_profile_code'), - CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_shipping_rpa_profiles_connector_type'), + UniqueConstraint('profile_code', name='uq_freight_rpa_profiles_profile_code'), + CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_freight_rpa_profiles_connector_type'), ) id: Mapped[int] = mapped_column(primary_key=True) @@ -81,24 +83,24 @@ class ShippingRpaProfile(Base): created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) - sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='rpa_profile') + sources: Mapped[list['FreightRpaSource']] = relationship(back_populates='rpa_profile') -class ShippingInventorySource(Base): +class FreightRpaSource(Base): """库存业务来源;固定仓或库存行动态解析 Warehouse。""" - __tablename__ = 'shipping_inventory_sources' + __tablename__ = 'freight_rpa_sources' __table_args__ = ( - UniqueConstraint('source_code', name='uq_shipping_inventory_sources_source_code'), - CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_shipping_inventory_sources_connector_type'), + UniqueConstraint('source_code', name='uq_freight_rpa_sources_source_code'), + CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_freight_rpa_sources_connector_type'), CheckConstraint( "(warehouse_resolution_mode = 'fixed' AND fixed_warehouse_id IS NOT NULL) " "OR (warehouse_resolution_mode = 'inventory_match' AND fixed_warehouse_id IS NULL)", - name='ck_shipping_inventory_sources_warehouse_mode', + name='ck_freight_rpa_sources_warehouse_mode', ), CheckConstraint( - "enabled = false OR (parsing_profile_id IS NOT NULL AND excel_template_id IS NOT NULL)", - name='ck_shipping_inventory_sources_enabled_bindings', + "enabled = false OR excel_template_id IS NOT NULL", + name='ck_freight_rpa_sources_enabled_template', ), ) @@ -106,14 +108,12 @@ class ShippingInventorySource(Base): source_code: Mapped[str] = mapped_column(String(64), nullable=False) display_name: Mapped[str] = mapped_column(String(128), nullable=False) connector_type: Mapped[str] = mapped_column(String(32), nullable=False) - rpa_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_rpa_profiles.id'), nullable=False, index=True) - parsing_profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True) + rpa_profile_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_profiles.id'), nullable=False, index=True) excel_template_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=True, index=True) warehouse_resolution_mode: Mapped[str] = mapped_column(String(32), nullable=False) fixed_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - # 业务报表定义属于 Source;Driver 的 selector、等待与下载实现不进入数据库配置。 - report_path_json: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict, server_default=text("'{}'"), nullable=False) - query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, default=list, server_default=text("'[]'"), nullable=False) + # 业务报表定义自 s18 起搬到 FreightRpaOnhandReportConfig(路径、查询条件、解析方案绑定); + # CHECK 不能跨表,模板绑定仍留在站点行的启用约束上,解析方案存在性由保存站点的服务校验。 snapshot_ttl_seconds: Mapped[int] = mapped_column(Integer, default=86400, server_default=text('86400'), nullable=False) enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False) config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False) @@ -122,31 +122,75 @@ class ShippingInventorySource(Base): created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) - rpa_profile: Mapped[ShippingRpaProfile] = relationship(back_populates='sources') - parsing_profile: Mapped[Optional['ShippingInventoryParsingProfile']] = relationship(back_populates='sources') + rpa_profile: Mapped[FreightRpaProfile] = relationship(back_populates='sources') excel_template: Mapped[Optional['ShippingExcelTemplate']] = relationship(back_populates='sources') - external_mappings: Mapped[list['ShippingInventoryExternalMapping']] = relationship( - back_populates='inventory_source', cascade='all, delete-orphan' + onhand_report_config: Mapped[Optional['FreightRpaOnhandReportConfig']] = relationship( + back_populates='source', uselist=False, cascade='all, delete-orphan', ) - receipt_report_config: Mapped[Optional['ShippingReceiptReportConfig']] = relationship( - back_populates='inventory_source', uselist=False, cascade='all, delete-orphan', + external_mappings: Mapped[list['FreightRpaOnhandExternalMapping']] = relationship( + back_populates='source', cascade='all, delete-orphan' + ) + inbound_report_config: Mapped[Optional['FreightRpaInboundReportConfig']] = relationship( + back_populates='source', uselist=False, cascade='all, delete-orphan', + ) + outbound_report_config: Mapped[Optional['FreightRpaOutboundReportConfig']] = relationship( + back_populates='source', uselist=False, cascade='all, delete-orphan', ) -class ShippingInventorySourceParsingBindingAudit(Base): - """库存站点解析方案绑定的只追加审计;保存绑定前后快照以支持上线追溯。""" +class FreightRpaOnhandReportConfig(Base): + """库存站点的一对一在手报表配置;报表路径与查询条件归 RPA 域。 - __tablename__ = 'shipping_inventory_source_parsing_binding_audits' + 解析方案绑定随本表保存(purpose='onhand')。站点启用要求「本配置存在且 + parsing_profile_id 非空」,PostgreSQL CHECK 不能跨表,该校验由保存站点的服务执行。 + """ + + __tablename__ = 'freight_rpa_onhand_report_configs' __table_args__ = ( - Index('ix_inventory_source_parsing_binding_audit_source_created', 'inventory_source_id', 'created_at'), + UniqueConstraint('source_id', name='uq_freight_rpa_onhand_report_configs_source'), ) id: Mapped[int] = mapped_column(primary_key=True) - inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False) - previous_parsing_profile_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, + # 站点删除时配置行级联删除(与迁移端 fk_freight_rpa_onhand_report_configs_source 的 ondelete 一致)。 + source_id: Mapped[int] = mapped_column( + ForeignKey('freight_rpa_sources.id', ondelete='CASCADE'), nullable=False, index=True, ) - parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=False) + # 在手报表文件解析规则(purpose='onhand');空则站点不得启用(服务层校验)。 + parsing_profile_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('freight_rpa_parsing_profiles.id'), nullable=True, index=True, + ) + # 业务报表定义属于配置行;Driver 的 selector、等待与下载实现不进入数据库配置。 + report_path_json: Mapped[dict[str, Any]] = mapped_column( + JSON, default=dict, server_default=text("'{}'"), nullable=False, + ) + # 与入站同构:查询条件原样下发 Worker;空条件表示页面默认。 + query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column( + JSON, default=list, server_default=text("'[]'"), nullable=False, + ) + config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False) + created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + source: Mapped['FreightRpaSource'] = relationship(back_populates='onhand_report_config') + parsing_profile: Mapped[Optional['FreightRpaParsingProfile']] = relationship(back_populates='sources') + + +class FreightRpaSourceParsingBindingAudit(Base): + """库存站点解析方案绑定的只追加审计;保存绑定前后快照以支持上线追溯。""" + + __tablename__ = 'freight_rpa_onhand_source_parsing_binding_audits' + __table_args__ = ( + Index('ix_inventory_source_parsing_binding_audit_source_created', 'source_id', 'created_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False) + previous_parsing_profile_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('freight_rpa_parsing_profiles.id'), nullable=True, + ) + parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_parsing_profiles.id'), nullable=False) operation: Mapped[str] = mapped_column(String(32), nullable=False) reason: Mapped[str] = mapped_column(String(500), nullable=False) actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) @@ -157,31 +201,32 @@ class ShippingInventorySourceParsingBindingAudit(Base): created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) -class ShippingInventoryParsingProfile(Base): - """可跨源复用的通用文件解析规则(库存/异动按 purpose 区分)。 +class FreightRpaParsingProfile(Base): + """可跨源复用的通用文件解析规则(在手/入站/出站按 purpose 区分)。 - 注意:表名中的 inventory 是历史命名——本表实为"通用文件解析规则表", - 用途以 purpose 字段为准,勿按表名推断只服务库存。 - purpose='inventory':端点用 ShippingInventoryField 库存字段目录(既有语义); - purpose='movement':端点用定死领域字段(MOVEMENT_FIELDS,doc_no/line_no/.../movement_date), - 供收料/异动文件映射,不依赖库存字段目录。校验逻辑按 purpose 分支。 - 绑定入口:库存站点 ShippingInventorySource.parsing_profile_id / - 收料配置 ShippingReceiptReportConfig.parsing_profile_id(后者必须 purpose='movement')。 + 表 freight_rpa_parsing_profiles 按 purpose 服务在手/入站/出站。 + purpose='onhand':在手库存文件,端点用 FreightRpaOnhandField 库存字段目录; + purpose='inbound':入站文件,端点用定死领域字段 + (MOVEMENT_FIELDS,doc_no/line_no/.../movement_date), + 不依赖库存字段目录。校验逻辑按 purpose 分支。 + 绑定入口:在手配置 FreightRpaOnhandReportConfig.parsing_profile_id / + 入站配置 FreightRpaInboundReportConfig.parsing_profile_id(后者必须 purpose='inbound'); + purpose='outbound':出站文件,结构就位(白名单放行,暂无运行时消费方)。 """ - __tablename__ = 'shipping_inventory_parsing_profiles' + __tablename__ = 'freight_rpa_parsing_profiles' __table_args__ = ( UniqueConstraint('profile_code', 'version', name='uq_inventory_parsing_profiles_code_version'), Index('ix_inv_parse_profile_exact_fp', 'exact_structure_fingerprint'), Index('ix_inv_parse_profile_compat_fp', 'compatibility_fingerprint'), CheckConstraint( - "purpose IN ('inventory', 'movement')", - name='ck_shipping_inventory_parsing_profiles_purpose', + "purpose IN ('onhand', 'inbound', 'outbound')", + name='ck_freight_rpa_parsing_profiles_purpose', ), ) id: Mapped[int] = mapped_column(primary_key=True) - purpose: Mapped[str] = mapped_column(String(16), nullable=False, default='inventory', server_default='inventory') + purpose: Mapped[str] = mapped_column(String(16), nullable=False, default='onhand', server_default='onhand') profile_code: Mapped[str] = mapped_column(String(64), nullable=False) display_name: Mapped[str] = mapped_column(String(128), nullable=False) version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1')) @@ -195,7 +240,7 @@ class ShippingInventoryParsingProfile(Base): fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) # Draft and published definitions keep their analysed sample evidence without retaining the full uploaded workbook. sample_analysis_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True, index=True, + ForeignKey('freight_rpa_onhand_structure_analyses.id'), nullable=True, index=True, ) # Preserve every confirmed evidence switch so a draft remains explainable after samples change. sample_evidence_history_json: Mapped[list[dict[str, Any]]] = mapped_column( @@ -206,16 +251,17 @@ class ShippingInventoryParsingProfile(Base): created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) - sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='parsing_profile') - sample_analysis: Mapped[Optional['ShippingInventoryStructureAnalysis']] = relationship( + # s18 起站点行不再绑定解析方案;在手配置行(FreightRpaOnhandReportConfig)是 onhand 侧的唯一挂点。 + sources: Mapped[list['FreightRpaOnhandReportConfig']] = relationship(back_populates='parsing_profile') + sample_analysis: Mapped[Optional['FreightRpaOnhandStructureAnalysis']] = relationship( foreign_keys=[sample_analysis_id], ) -class ShippingInventoryStructureAnalysis(Base): +class FreightRpaOnhandStructureAnalysis(Base): """库存文件结构分析记录;保存脱敏结构证据,不承载正式库存快照。""" - __tablename__ = 'shipping_inventory_structure_analyses' + __tablename__ = 'freight_rpa_onhand_structure_analyses' __table_args__ = ( Index('ix_inv_structure_analysis_file_hash', 'file_checksum'), Index('ix_inv_structure_analysis_created', 'created_at'), @@ -243,24 +289,28 @@ class ShippingInventoryStructureAnalysis(Base): created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) -class ShippingInventoryConfigurationTestRun(Base): +class FreightRpaOnhandConfigurationTestRun(Base): """库存站点配置测试的异步 RPA 运行;锁定站点和连接配置版本且不进入生产库存池。""" - __tablename__ = 'shipping_inventory_configuration_test_runs' - __table_args__ = (UniqueConstraint('run_no', name='uq_inventory_configuration_test_runs_run_no'),) + __tablename__ = 'freight_rpa_onhand_configuration_test_runs' + __table_args__ = ( + UniqueConstraint('run_no', name='uq_inventory_configuration_test_runs_run_no'), + # PostgreSQL 标识符上限 63。index=True 会生成 65 字节的自动名,故用显式短名。 + Index('ix_fr_onhand_cfg_test_runs_validation_batch_id', 'validation_batch_id'), + ) id: Mapped[int] = mapped_column(primary_key=True) run_no: Mapped[str] = mapped_column(String(64), nullable=False) validation_batch_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_validation_batches.id'), nullable=True, index=True, + ForeignKey('freight_rpa_onhand_validation_batches.id'), nullable=True, ) rpa_batch_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) - inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True) + source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False, index=True) source_config_version: Mapped[int] = mapped_column(Integer, nullable=False) rpa_profile_config_version: Mapped[int] = mapped_column(Integer, nullable=False) status: Mapped[str] = mapped_column(String(32), nullable=False, default='awaiting_rpa', server_default='awaiting_rpa') stage: Mapped[str] = mapped_column(String(32), nullable=False, default='waiting_worker', server_default='waiting_worker') - analysis_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True) + analysis_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_structure_analyses.id'), nullable=True) result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) @@ -268,10 +318,10 @@ class ShippingInventoryConfigurationTestRun(Base): completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) -class ShippingInventoryValidationBatch(Base): +class FreightRpaOnhandValidationBatch(Base): """库存站点批量验证的聚合运行;逐站点结果仍由 ConfigurationTestRun 保存。""" - __tablename__ = 'shipping_inventory_validation_batches' + __tablename__ = 'freight_rpa_onhand_validation_batches' __table_args__ = (UniqueConstraint('batch_no', name='uq_inventory_validation_batches_batch_no'),) id: Mapped[int] = mapped_column(primary_key=True) @@ -284,21 +334,21 @@ class ShippingInventoryValidationBatch(Base): stale_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0')) created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) retry_of_batch_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_validation_batches.id'), nullable=True, + ForeignKey('freight_rpa_onhand_validation_batches.id'), nullable=True, ) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) -class ShippingInventoryRoutingRule(Base): +class FreightRpaOnhandRoutingRule(Base): """可版本化的库存源路由决策表;仅产出受控 Source 候选。""" - __tablename__ = 'shipping_inventory_routing_rules' + __tablename__ = 'freight_rpa_onhand_routing_rules' __table_args__ = ( - UniqueConstraint('rule_code', 'version', name='uq_shipping_inventory_routing_rules_code_version'), - CheckConstraint("scope IN ('task', 'line')", name='ck_shipping_inventory_routing_rules_scope'), - CheckConstraint("match_mode IN ('all', 'any')", name='ck_shipping_inventory_routing_rules_match_mode'), - CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_inventory_routing_rules_status'), + UniqueConstraint('rule_code', 'version', name='uq_freight_rpa_onhand_routing_rules_code_version'), + CheckConstraint("scope IN ('task', 'line')", name='ck_freight_rpa_onhand_routing_rules_scope'), + CheckConstraint("match_mode IN ('all', 'any')", name='ck_freight_rpa_onhand_routing_rules_match_mode'), + CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_freight_rpa_onhand_routing_rules_status'), ) id: Mapped[int] = mapped_column(primary_key=True) @@ -318,17 +368,17 @@ class ShippingInventoryRoutingRule(Base): created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) - conditions: Mapped[list['ShippingInventoryRoutingRuleCondition']] = relationship( - back_populates='rule', cascade='all, delete-orphan', order_by='ShippingInventoryRoutingRuleCondition.sequence' + conditions: Mapped[list['FreightRpaOnhandRoutingRuleCondition']] = relationship( + back_populates='rule', cascade='all, delete-orphan', order_by='FreightRpaOnhandRoutingRuleCondition.sequence' ) -class ShippingInventoryRoutingRuleCondition(Base): +class FreightRpaOnhandRoutingRuleCondition(Base): """库存源路由条件;仅引用已发布订单 Schema 的稳定 field_id。""" - __tablename__ = 'shipping_inventory_routing_rule_conditions' + __tablename__ = 'freight_rpa_onhand_routing_rule_conditions' __table_args__ = ( - UniqueConstraint('rule_id', 'sequence', name='uq_shipping_inventory_routing_rule_conditions_sequence'), + UniqueConstraint('rule_id', 'sequence', name='uq_freight_rpa_onhand_routing_rule_conditions_sequence'), CheckConstraint( "source_kind = 'order_field' AND order_field_id IS NOT NULL", name='ck_inventory_routing_condition_source', @@ -336,7 +386,7 @@ class ShippingInventoryRoutingRuleCondition(Base): ) id: Mapped[int] = mapped_column(primary_key=True) - rule_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_routing_rules.id'), nullable=False, index=True) + rule_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_routing_rules.id'), nullable=False, index=True) condition_group: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False) source_kind: Mapped[str] = mapped_column(String(16), nullable=False, default='order_field') order_field_id: Mapped[Optional[str]] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=True) @@ -344,24 +394,24 @@ class ShippingInventoryRoutingRuleCondition(Base): expected_value_json: Mapped[Any] = mapped_column(JSON, nullable=True) sequence: Mapped[int] = mapped_column(Integer, nullable=False) - rule: Mapped[ShippingInventoryRoutingRule] = relationship(back_populates='conditions') + rule: Mapped[FreightRpaOnhandRoutingRule] = relationship(back_populates='conditions') -class ShippingInventoryRoutingRuleVersion(Base): +class FreightRpaOnhandRoutingRuleVersion(Base): """已发布路由规则的不可变定义快照,供任务审计回放使用。""" - __tablename__ = 'shipping_inventory_routing_rule_versions' - __table_args__ = (UniqueConstraint('rule_id', 'version', name='uq_shipping_inventory_routing_rule_versions_rule_version'),) + __tablename__ = 'freight_rpa_onhand_routing_rule_versions' + __table_args__ = (UniqueConstraint('rule_id', 'version', name='uq_freight_rpa_onhand_routing_rule_versions_rule_version'),) id: Mapped[int] = mapped_column(primary_key=True) - rule_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_routing_rules.id'), nullable=False, index=True) + rule_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_routing_rules.id'), nullable=False, index=True) version: Mapped[int] = mapped_column(Integer, nullable=False) definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False) published_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) published_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) -class ShippingInventoryExternalMapping(Base): +class FreightRpaOnhandExternalMapping(Base): """库存源到外部系统仓库的映射。 freight_warehouse_id(货代仓库)为可选维度:inventory_match 源用它匹配收料文件 @@ -371,18 +421,18 @@ class ShippingInventoryExternalMapping(Base): (in_transit_transfer DefaultRouteResolver),保存端必填,库内空串仅为存量行兼容。 """ - __tablename__ = 'shipping_inventory_external_mappings' + __tablename__ = 'freight_rpa_onhand_external_mappings' __table_args__ = ( Index( 'uq_shipping_inv_ext_map_src_default_enabled', - 'inventory_source_id', + 'source_id', unique=True, postgresql_where=text('freight_warehouse_id IS NULL AND enabled = true'), sqlite_where=text('freight_warehouse_id IS NULL AND enabled = 1'), ), Index( 'uq_shipping_inv_ext_map_src_wh_enabled', - 'inventory_source_id', + 'source_id', 'freight_warehouse_id', unique=True, postgresql_where=text('freight_warehouse_id IS NOT NULL AND enabled = true'), @@ -391,7 +441,7 @@ class ShippingInventoryExternalMapping(Base): ) id: Mapped[int] = mapped_column(primary_key=True) - inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True) + source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False, index=True) freight_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) external_system_code: Mapped[str] = mapped_column(String(32), nullable=False) external_organization_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) @@ -407,4 +457,4 @@ class ShippingInventoryExternalMapping(Base): created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) - inventory_source: Mapped[ShippingInventorySource] = relationship(back_populates='external_mappings') + source: Mapped[FreightRpaSource] = relationship(back_populates='external_mappings') diff --git a/backend/app/models/freight_rpa_inbound_report.py b/backend/app/models/freight_rpa_inbound_report.py new file mode 100644 index 00000000..72b13805 --- /dev/null +++ b/backend/app/models/freight_rpa_inbound_report.py @@ -0,0 +1,128 @@ +""" +backend/app/models/freight_rpa_inbound_report.py + +用途:入站报表 RPA 的配置、运行与归档持久化模型(per-file 企微投递表已拆除,见 Task 4 迁移)。 +依赖:freight_rpa_sources、排程运行、freight_rpa_parsing_profiles、SQLAlchemy Base;完整操作追溯统一写入 ShippingAuditEvent。 +逻辑:模型只复用站点连接资料,通过独立外键与唯一约束隔离在手快照、匹配和旧 RPA Worker 链路。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Optional + +from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.models.base import Base + + +class FreightRpaInboundReportConfig(Base): + """库存站点的一对一收料报表配置;路径和条件始终独立于库存配置。""" + + __tablename__ = 'freight_rpa_inbound_report_configs' + __table_args__ = ( + UniqueConstraint('source_id', name='uq_freight_rpa_inbound_report_configs_source'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + source_id: Mapped[int] = mapped_column( + ForeignKey('freight_rpa_sources.id'), nullable=False, index=True, + ) + # 收料不设独立启停:是否运行统一由库存站点 enabled 与本配置是否存在决定。 + # 收料文件解析规则(purpose='inbound');定死领域字段端点。空则无法解析收料文件。 + parsing_profile_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('freight_rpa_parsing_profiles.id'), nullable=True, index=True, + ) + report_path_json: Mapped[dict[str, Any]] = mapped_column( + JSON, default=dict, server_default=text("'{}'"), nullable=False, + ) + query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column( + JSON, default=list, server_default=text("'[]'"), nullable=False, + ) + # 与库存同构:查询条件原样下发 Worker;空条件表示页面默认。排程一源一单元,不按仓拆分。 + config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False) + created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + source: Mapped['FreightRpaSource'] = relationship(back_populates='inbound_report_config') + parsing_profile: Mapped[Optional['FreightRpaParsingProfile']] = relationship() + + +class FreightRpaInboundUnitRun(Base): + """一次收料执行的站点或站点-Warehouse 不可重复执行单元。 + + schedule_run_id 指向排程 run;调拨按需触发(重试/预检补抓)无排程,保持 NULL。 + """ + + __tablename__ = 'freight_rpa_inbound_rpa_unit_runs' + __table_args__ = ( + UniqueConstraint('callback_id', name='uq_freight_rpa_inbound_rpa_unit_runs_callback'), + CheckConstraint( + "status IN ('queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled')", + name='ck_freight_rpa_inbound_rpa_unit_runs_status', + ), + Index('ix_shipping_receipt_unit_run_schedule_status', 'schedule_run_id', 'status'), + Index('ix_shipping_receipt_unit_run_source_created', 'source_id', 'created_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + schedule_run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_runs.id'), nullable=True, index=True) + source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False, index=True) + retry_of_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('freight_rpa_inbound_rpa_unit_runs.id'), nullable=True, index=True, + ) + source_code: Mapped[str] = mapped_column(String(64), nullable=False) + connector_type: Mapped[str] = mapped_column(String(32), nullable=False) + warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + callback_id: Mapped[str] = mapped_column(String(128), nullable=False) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued') + config_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + trigger_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + schedule_run: Mapped[Optional['ScheduleRun']] = relationship(foreign_keys=[schedule_run_id]) + source: Mapped['FreightRpaSource'] = relationship() + retry_of: Mapped[Optional['FreightRpaInboundUnitRun']] = relationship(remote_side=[id]) + files: Mapped[list['FreightRpaInboundReportFile']] = relationship( + back_populates='unit_run', cascade='all, delete-orphan', + ) + + +class FreightRpaInboundReportFile(Base): + """收料原样归档文件;保留文件身份和对象清理事实,不关联库存快照。""" + + __tablename__ = 'freight_rpa_inbound_report_files' + __table_args__ = ( + UniqueConstraint('unit_run_id', 'sha256', name='uq_freight_rpa_inbound_report_files_unit_sha256'), + CheckConstraint("file_size >= 0", name='ck_freight_rpa_inbound_report_files_size'), + Index('ix_freight_rpa_inbound_report_files_unit', 'unit_run_id'), + Index('ix_freight_rpa_inbound_report_files_expires', 'archive_expires_at', 'archive_deleted_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + unit_run_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_inbound_rpa_unit_runs.id'), nullable=False, index=True) + storage_provider: Mapped[str] = mapped_column(String(32), nullable=False) + storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False) + storage_key: Mapped[str] = mapped_column(String(1024), nullable=False) + original_filename: Mapped[str] = mapped_column(String(255), nullable=False) + content_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + file_size: Mapped[int] = mapped_column(Integer, nullable=False) + sha256: Mapped[str] = mapped_column(String(64), nullable=False) + # 解析失败分层标记:归档文件解析失败时写入;三者全空=未失败/已清除。 + parse_failed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + parse_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + parse_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + archive_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + archive_deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + archive_delete_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + unit_run: Mapped[FreightRpaInboundUnitRun] = relationship(back_populates='files') diff --git a/backend/app/models/shipping_inventory_mapping.py b/backend/app/models/freight_rpa_onhand_mapping.py similarity index 69% rename from backend/app/models/shipping_inventory_mapping.py rename to backend/app/models/freight_rpa_onhand_mapping.py index dcc8f196..8945f5dd 100644 --- a/backend/app/models/shipping_inventory_mapping.py +++ b/backend/app/models/freight_rpa_onhand_mapping.py @@ -1,8 +1,8 @@ """ -models/shipping_inventory_mapping.py +backend/app/models/freight_rpa_onhand_mapping.py 用途:保存不可变库存字段映射版本。 -依赖:ShippingInventoryFile、ShippingInventoryParsingProfile、Base。 +依赖:FreightRpaOnhandReportFile、FreightRpaParsingProfile、Base。 逻辑:每次确认/重跑创建新版本,匹配 Attempt 通过 mapping_id 精确引用。 """ @@ -17,24 +17,24 @@ from sqlalchemy.orm import Mapped, mapped_column from app.models.base import Base -class ShippingInventoryMapping(Base): +class FreightRpaOnhandMapping(Base): """库存文件的不可变字段映射版本。""" - __tablename__ = 'shipping_inventory_mappings' + __tablename__ = 'freight_rpa_onhand_mappings' __table_args__ = ( - UniqueConstraint('inventory_file_id', 'version', name='uq_shipping_inventory_mapping_file_version'), + UniqueConstraint('onhand_file_id', 'version', name='uq_shipping_inventory_mapping_file_version'), CheckConstraint("status IN ('active','superseded','invalidated')", name='ck_shipping_inventory_mapping_status'), - Index('ix_shipping_inventory_mapping_file_status', 'inventory_file_id', 'status'), + Index('ix_shipping_inventory_mapping_file_status', 'onhand_file_id', 'status'), ) id: Mapped[int] = mapped_column(Integer, primary_key=True) - inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id', ondelete='CASCADE'), nullable=False) + onhand_file_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id', ondelete='CASCADE'), nullable=False) version: Mapped[int] = mapped_column(Integer, nullable=False) status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active') - profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id', ondelete='SET NULL'), nullable=True) + profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_parsing_profiles.id', ondelete='SET NULL'), nullable=True) mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_mappings.id'), nullable=True) + superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_mappings.id'), nullable=True) created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) diff --git a/backend/app/models/freight_rpa_onhand_report_file.py b/backend/app/models/freight_rpa_onhand_report_file.py new file mode 100644 index 00000000..dceb2a78 --- /dev/null +++ b/backend/app/models/freight_rpa_onhand_report_file.py @@ -0,0 +1,123 @@ +""" +backend/app/models/freight_rpa_onhand_report_file.py + +用途:货代 RPA 抓回的在手报表文件。 +依赖:models.base.Base、shipping.py 里的 ShippingTaskOnhandLink。 +逻辑:表名 freight_rpa_onhand_report_files 不变;发货任务通过 ShippingTaskOnhandLink 引用本行。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import List, Optional + +from sqlalchemy import ( + Boolean, + DateTime, + ForeignKey, + Index, + Integer, + JSON, + String, + text, +) +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.models.base import Base + + +class FreightRpaOnhandReportFile(Base): + """货代发货批次库存快照文件,承载一次上传后可被多票任务共用的库存数据。 + + 在手文件表归货代 RPA(s18 由 shipping_onhand_files 改名而来);列不改, + 仍含解析行、字段映射与快照状态,本阶段只改表名与指向它的外键。 + """ + + __tablename__ = 'freight_rpa_onhand_report_files' + __table_args__ = ( + Index('ix_freight_rpa_onhand_report_files_user_created', 'user_id', 'created_at'), + Index( + 'ix_freight_rpa_onhand_report_files_source_snapshot', + 'source_code', + 'warehouse_id', + 'snapshot_status', + 'exported_at', + ), + Index( + 'ix_freight_rpa_onhand_report_files_source_warehouse', + 'source_code', + 'warehouse_id', + ), + Index( + 'uq_freight_rpa_onhand_report_files_rpa_identity_ready', + 'rpa_run_no', + 'source_code', + 'warehouse_id', + unique=True, + postgresql_where=text( + "snapshot_status = 'ready' AND rpa_run_no IS NOT NULL " + "AND source_code IS NOT NULL AND warehouse_id IS NOT NULL" + ), + sqlite_where=text( + "snapshot_status = 'ready' AND rpa_run_no IS NOT NULL " + "AND source_code IS NOT NULL AND warehouse_id IS NOT NULL" + ), + ), + # 动态多仓文件没有单一 Warehouse;按 RPA run + Source 保证回调重放幂等。 + Index( + 'uq_freight_rpa_onhand_report_files_rpa_dynamic_source_ready', + 'rpa_run_no', + 'source_code', + unique=True, + postgresql_where=text( + "snapshot_status = 'ready' AND rpa_run_no IS NOT NULL " + "AND source_code IS NOT NULL AND warehouse_id IS NULL" + ), + sqlite_where=text( + "snapshot_status = 'ready' AND rpa_run_no IS NOT NULL " + "AND source_code IS NOT NULL AND warehouse_id IS NULL" + ), + ), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + onhand_file_no: Mapped[str] = mapped_column(String(64), unique=True, index=True) + user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True) + source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) + storage_path: Mapped[str] = mapped_column(String(500), nullable=False) + schema_preview_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) + field_mapping_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) + mapping_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + mapping_confirmed: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false')) + onhand_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) + line_count: Mapped[int] = mapped_column(Integer, default=0) + share_mode: Mapped[str] = mapped_column(String(32), default='task_only') + warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) + warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + identity_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True) + source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) + source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + snapshot_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True) + exported_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True) + expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True) + rpa_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + schedule_run_id: Mapped[Optional[int]] = mapped_column(nullable=True, index=True) + source_query_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) + superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id'), nullable=True) + invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True) + invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True) + input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) + updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) + + links: Mapped[List['ShippingTaskOnhandLink']] = relationship( + 'ShippingTaskOnhandLink', + back_populates='inventory_file', + cascade='all, delete-orphan', + ) diff --git a/backend/app/models/shipping_task_inventory_rpa_attempts.py b/backend/app/models/freight_rpa_onhand_task_attempts.py similarity index 96% rename from backend/app/models/shipping_task_inventory_rpa_attempts.py rename to backend/app/models/freight_rpa_onhand_task_attempts.py index 4abbbd30..5633bbdb 100644 --- a/backend/app/models/shipping_task_inventory_rpa_attempts.py +++ b/backend/app/models/freight_rpa_onhand_task_attempts.py @@ -1,5 +1,5 @@ """ -models/shipping_task_inventory_rpa_attempts.py +backend/app/models/freight_rpa_onhand_task_attempts.py 用途:逐库存源的 RPA 导出 Attempt 结构化记录(决策 D1/D2 三元组幂等)。 依赖:Base、ShippingNotice(task_no FK 可选直连 id 先保留 task_no 字符串关联)、users。 @@ -47,10 +47,10 @@ PER_SOURCE_RPA_ATTEMPT_STATUSES = ( ) -class ShippingTaskInventoryRpaAttempt(Base): +class FreightRpaOnhandTaskAttempt(Base): """逐 (task_no, source_code) 的库存 RPA 导出 Attempt 记录。""" - __tablename__ = 'shipping_task_inventory_rpa_attempts' + __tablename__ = 'freight_rpa_onhand_task_rpa_attempts' __table_args__ = ( # 三元组唯一:同一运行号同一源只允许一条记录 UniqueConstraint('task_no', 'source_code', 'source_run_no', name='uq_shipping_task_inv_rpa_triplet'), @@ -87,7 +87,7 @@ class ShippingTaskInventoryRpaAttempt(Base): trigger_file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True) callback_file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True) - inventory_file_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + onhand_file_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) diff --git a/backend/app/models/freight_rpa_outbound_report.py b/backend/app/models/freight_rpa_outbound_report.py new file mode 100644 index 00000000..a78563ea --- /dev/null +++ b/backend/app/models/freight_rpa_outbound_report.py @@ -0,0 +1,129 @@ +""" +backend/app/models/freight_rpa_outbound_report.py + +用途:出站报表 RPA 的配置、运行与归档持久化模型(不建 per-file 企微投递表)。 +依赖:freight_rpa_sources、排程运行、freight_rpa_parsing_profiles、SQLAlchemy Base;完整操作追溯统一写入 ShippingAuditEvent。 +逻辑:模型只复用站点连接资料,通过独立外键与唯一约束隔离在手快照、匹配和旧 RPA Worker 链路。 + FreightRpaSource.outbound_report_config 一对一回指本配置行。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Optional + +from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.models.base import Base + + +class FreightRpaOutboundReportConfig(Base): + """库存站点的一对一出站报表配置;路径和条件始终独立于库存 / 入站配置。""" + + __tablename__ = 'freight_rpa_outbound_report_configs' + __table_args__ = ( + UniqueConstraint('source_id', name='uq_freight_rpa_outbound_report_configs_source'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + source_id: Mapped[int] = mapped_column( + ForeignKey('freight_rpa_sources.id'), nullable=False, index=True, + ) + # 出站不设独立启停:是否运行统一由库存站点 enabled 与本配置是否存在决定。 + # 出站文件解析规则(purpose='outbound');定死领域字段端点。空则无法解析出站文件。 + parsing_profile_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('freight_rpa_parsing_profiles.id'), nullable=True, index=True, + ) + report_path_json: Mapped[dict[str, Any]] = mapped_column( + JSON, default=dict, server_default=text("'{}'"), nullable=False, + ) + query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column( + JSON, default=list, server_default=text("'[]'"), nullable=False, + ) + # 与库存同构:查询条件原样下发 Worker;空条件表示页面默认。排程一源一单元,不按仓拆分。 + config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False) + created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + source: Mapped['FreightRpaSource'] = relationship(back_populates='outbound_report_config') + parsing_profile: Mapped[Optional['FreightRpaParsingProfile']] = relationship() + + +class FreightRpaOutboundUnitRun(Base): + """一次出站执行的站点或站点-Warehouse 不可重复执行单元。 + + schedule_run_id 指向排程 run;调拨按需触发(重试/预检补抓)无排程,保持 NULL。 + """ + + __tablename__ = 'freight_rpa_outbound_rpa_unit_runs' + __table_args__ = ( + UniqueConstraint('callback_id', name='uq_freight_rpa_outbound_rpa_unit_runs_callback'), + CheckConstraint( + "status IN ('queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled')", + name='ck_freight_rpa_outbound_rpa_unit_runs_status', + ), + Index('ix_freight_rpa_outbound_unit_run_schedule_status', 'schedule_run_id', 'status'), + Index('ix_freight_rpa_outbound_unit_run_source_created', 'source_id', 'created_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + schedule_run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_runs.id'), nullable=True, index=True) + source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False, index=True) + retry_of_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('freight_rpa_outbound_rpa_unit_runs.id'), nullable=True, index=True, + ) + source_code: Mapped[str] = mapped_column(String(64), nullable=False) + connector_type: Mapped[str] = mapped_column(String(32), nullable=False) + warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + callback_id: Mapped[str] = mapped_column(String(128), nullable=False) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued') + config_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + trigger_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + schedule_run: Mapped[Optional['ScheduleRun']] = relationship(foreign_keys=[schedule_run_id]) + source: Mapped['FreightRpaSource'] = relationship() + retry_of: Mapped[Optional['FreightRpaOutboundUnitRun']] = relationship(remote_side=[id]) + files: Mapped[list['FreightRpaOutboundReportFile']] = relationship( + back_populates='unit_run', cascade='all, delete-orphan', + ) + + +class FreightRpaOutboundReportFile(Base): + """出站原样归档文件;保留文件身份和对象清理事实,不关联库存快照。""" + + __tablename__ = 'freight_rpa_outbound_report_files' + __table_args__ = ( + UniqueConstraint('unit_run_id', 'sha256', name='uq_freight_rpa_outbound_report_files_unit_sha256'), + CheckConstraint("file_size >= 0", name='ck_freight_rpa_outbound_report_files_size'), + Index('ix_freight_rpa_outbound_report_files_unit', 'unit_run_id'), + Index('ix_freight_rpa_outbound_report_files_expires', 'archive_expires_at', 'archive_deleted_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + unit_run_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_outbound_rpa_unit_runs.id'), nullable=False, index=True) + storage_provider: Mapped[str] = mapped_column(String(32), nullable=False) + storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False) + storage_key: Mapped[str] = mapped_column(String(1024), nullable=False) + original_filename: Mapped[str] = mapped_column(String(255), nullable=False) + content_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + file_size: Mapped[int] = mapped_column(Integer, nullable=False) + sha256: Mapped[str] = mapped_column(String(64), nullable=False) + # 解析失败分层标记:归档文件解析失败时写入;三者全空=未失败/已清除。 + parse_failed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + parse_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + parse_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + archive_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + archive_deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + archive_delete_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + unit_run: Mapped[FreightRpaOutboundUnitRun] = relationship(back_populates='files') diff --git a/backend/app/models/in_transit_transfer.py b/backend/app/models/in_transit_transfer.py index 6a9c7fe6..797c0bf6 100644 --- a/backend/app/models/in_transit_transfer.py +++ b/backend/app/models/in_transit_transfer.py @@ -1,13 +1,22 @@ """models/in_transit_transfer.py 用途:在途仓自动调拨一期核心领域模型:Run、SourceJob、Matching、InvoiceItem、 - Document(ERP 调拨单)、Attempt、AuditEvent 与 Archive。 -依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁)。 + Document(ERP 调拨单)、Attempt、AuditEvent 与 Archive;另含调拨类型 + 配置表 TransferTypeConfig(类型配置化,ADR 0002)与库存异动档 + TransferMovementLedger(外部系统入站/出站记录镜像,ADR 0001)。 +依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁); + source_file_id 外键指向 freight_rpa_inbound_report_files(FreightRpaInboundReportFile 原样归档,入站证据)。 逻辑:Run 是异步真相源;InvoiceItem 按(matching_id, invoice_no)唯一防止重复建单; Document(单)实现「五元组一组一单」,同组未完结单唯一由部分唯一索引在 DB 层强制(D15 防双单兜底);单:Attempt=1:N,外键在 Attempt 侧(D14); Attempt 保留每次恢复/重查/执行事实,旧 Attempt 永不覆盖; - AuditEvent 保存脱敏快照与事件 Hash,禁止更新/删除。 + AuditEvent 保存脱敏快照与事件 Hash,禁止更新/删除; + transfer_runs.transfer_type 合法值由 TransferTypeConfig 配置承接 + (原枚举 CHECK 约束已移除); + TransferMovementLedger 以自然键 (source_code, record_kind, doc_no, + line_no, line_seq, in_out_flag, carton_id, lot_no) 幂等增量落地外部记录, + 已执行记录经 transfer_executed 封存(防二次调拨),来源文件删除后档事实留存 + (ON DELETE SET NULL,链接仅溯源)。 """ from __future__ import annotations @@ -34,20 +43,16 @@ from app.core.errors import ValidationError from app.models.base import Base # 与 services/in_transit_transfer/status.py 保持一致的冻结枚举(数据库级兜底)。 +# 【not_matured 已退役 2026-10-16】成熟概念删除,存量行经 tt16 重映射 cancelled。 TRANSFER_ITEM_STATUSES = ( 'file_pending', 'file_ready', 'matching', 'ready_to_execute', 'executing', - 'success', 'duplicate_success', 'blocked_recoverable', 'not_matured', + 'success', 'duplicate_success', 'blocked_recoverable', 'result_unknown', 'manually_closed', 'cancelled', 'notification_failed', ) TRANSFER_RUN_STATUSES = ( 'queued', 'preparing_files', 'matching', 'ready_to_execute', 'executing', 'success', 'partial_failed', 'failed', 'cancelled', ) -# 与 services/in_transit_transfer/transfer_type.py TransferType 保持一致的冻结枚举 -# (数据库级兜底);一期仅 in_transit_to_hub 进入处理链路,其余为占位值。 -TRANSFER_RUN_TYPES = ( - 'in_transit_to_hub', 'hub_repair_out', 'hub_to_hub', -) TRANSFER_SOURCE_JOB_STATUSES = ( 'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing', 'matching', 'executing', 'success', 'partial_failed', 'failed', 'cancelled', @@ -98,10 +103,6 @@ class TransferRun(Base): "trigger_type IN ('manual', 'schedule')", name='ck_transfer_runs_trigger_type', ), - CheckConstraint( - f"transfer_type IN ({', '.join(repr(t) for t in TRANSFER_RUN_TYPES)})", - name='ck_transfer_runs_transfer_type', - ), Index('ix_transfer_runs_status_created', 'status', 'created_at'), Index('ix_transfer_runs_business_date', 'business_date'), ) @@ -109,9 +110,11 @@ class TransferRun(Base): id: Mapped[int] = mapped_column(primary_key=True) run_no: Mapped[str] = mapped_column(String(64), nullable=False) trigger_type: Mapped[str] = mapped_column(String(16), nullable=False, default='manual', server_default='manual') - # 调拨业务类型(在途仓至HUB仓/HUB仓维修出/HUB仓间调拨);决定匹配收料数据范围。 + # 调拨业务类型(合法值由 TransferTypeConfig 配置承接,合法 code 正则 + # ^[a-z][a-z0-9_]{1,63}$ 上限 64);决定匹配入站数据范围。列宽 64 与配置表 + # code 上限对齐(终审 I2:33~64 字符 code 建匹配时写 32 宽列会 DB 500)。 transfer_type: Mapped[str] = mapped_column( - String(32), nullable=False, default='in_transit_to_hub', server_default='in_transit_to_hub', + String(64), nullable=False, default='in_transit_to_hub', server_default='in_transit_to_hub', ) business_date: Mapped[str] = mapped_column(String(16), nullable=False) status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued') @@ -215,15 +218,18 @@ class TransferMatching(Base): class TransferInvoiceItem(Base): - """匹配明细项;同一匹配内 (来源,Invoice,料号,收料日期) 唯一,保留原始行追溯。 + """匹配明细项;同一匹配内 (来源,Invoice,料号,异动日期) 唯一,保留原始行追溯。 Invoice 锚定批号(2026-09-21 业务口径):同一批号跨料号/跨日期拆分为多行。 + 【2026-10-14 出生翻转(ADR 0001/D4)】行不再由文件落地写入,而是匹配创建时 + 从库存异动档圈定生成:ledger_record_id 指向档记录(业务字段=档原值), + matching_id 创建即绑定(D17:一条档记录一生只生成一次 items 绑定)。 """ __tablename__ = 'transfer_invoice_items' __table_args__ = ( UniqueConstraint( - 'matching_id', 'source_code', 'invoice_no', 'material_no', 'receipt_date', + 'matching_id', 'source_code', 'invoice_no', 'material_no', 'movement_date', name='uq_transfer_invoice_items_matching_grain', ), CheckConstraint( @@ -236,32 +242,40 @@ class TransferInvoiceItem(Base): # 单据级执行(T10)高频「按单查行」:document_id 单列索引(控制器裁决, # 并入 tt0d1e2f3a4b 避免额外迁移节点)。 Index('ix_transfer_invoice_items_document_id', 'document_id'), + # 匹配创建圈档的占用互斥检查(D17)高频「按档记录查行」:单列索引 + # (并入 tt12c3d4e5f6a7 避免额外迁移节点)。 + Index('ix_transfer_invoice_items_ledger_record_id', 'ledger_record_id'), ) id: Mapped[int] = mapped_column(primary_key=True) - # 行归属解耦后 matching_id 仅留痕(首次创建值);落地证据同步行尚无匹配归属 - # (2026-09-25),放开非空。uq_transfer_invoice_items_matching_grain 含本列, - # NULL 行不受该唯一约束保护——同步的幂等去重由 evidence_sync 应用层按 - # (source, invoice, material, receipt_date) 四元组负责(见 evidence_sync)。 + # 【2026-10-14 出生翻转】matching_id 回归「创建即绑定」:行由匹配创建时从档 + # 圈定生成(落地不再写 items,见 evidence_sync/ADR 0001),新行恒非空 + # (模型层不强制 NOT NULL,存量兼容,服务层保证);D17 圈档互斥的占用判定 + # 以本列 + 所属匹配状态为准(取消匹配即释放占用)。 matching_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_matchings.id'), nullable=True, index=True) run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True) + # 【2026-10-14 出生翻转】行来源档记录外键(可空:隔离的历史行允许 NULL); + # 行上业务字段=档原值,批号等转换只在系统边界按匹配快照规则派生(不落库)。 + ledger_record_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('transfer_movement_ledger.id'), nullable=True, + ) source_code: Mapped[str] = mapped_column(String(64), nullable=False) invoice_no: Mapped[str] = mapped_column(String(64), nullable=False) # 批号(External ASN 等)原值;「拨入批号」展示由 WTP→HOW 转换派生,不落库。 lot_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - # 收料文件「仓库」列原值:inventory_match 源映射行匹配键(拨出库位解析审计)。 - receipt_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='') + # 入站文件「仓库」列原值:inventory_match 源映射行匹配键(拨出库位解析审计)。 + movement_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='') # 交易单位原值(movement 契约第 11 字段 unit,计划 D4):解析原样保留(仅 trim, # 不换算);空值行在匹配阶段落 blocked_missing_unit。unit 不参与匹配 Hash(口径冻结)。 unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, default='', server_default='') material_no: Mapped[str] = mapped_column(String(64), nullable=False) material_name: Mapped[str] = mapped_column(String(200), nullable=False, default='') specification: Mapped[str] = mapped_column(String(200), nullable=False, default='') - receipt_date: Mapped[Optional[str]] = mapped_column(String(16), nullable=True) + movement_date: Mapped[Optional[str]] = mapped_column(String(16), nullable=True) from_warehouse: Mapped[str] = mapped_column(String(64), nullable=False) to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False) # 数量以 Decimal 文本保存,杜绝浮点误差;比较在服务层完成。 - receipt_quantity: Mapped[str] = mapped_column(String(40), nullable=False) + movement_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 分离:证据同步换戳/存续不续期本字段, @@ -289,6 +303,12 @@ class TransferInvoiceItem(Base): # (document_id 置 NULL)回到 ready_to_execute,可被重新勾选组建新单。 document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_documents.id'), nullable=True) document: Mapped[Optional['TransferDocument']] = relationship(back_populates='items') + # 【2026-10-14 改锚(规格 §10)】行 → 档记录只读导航:file_current 门禁与行装饰 + # 的版本戳取档记录 file_sha256(档记录是证据权威)。纯 ORM relationship—— + # 不新增列/索引/约束(ledger_record_id 列与索引既有),无配套迁移。 + ledger_record: Mapped[Optional['TransferMovementLedger']] = relationship( + foreign_keys=[ledger_record_id], + ) class TransferDocument(Base): @@ -320,7 +340,7 @@ class TransferDocument(Base): # 建表同语义(部分唯一,非全组唯一)。 Index( 'uq_transfer_documents_group_live', - 'source_code', 'external_org', 'receipt_date', 'from_warehouse', 'to_warehouse', + 'source_code', 'external_org', 'movement_date', 'from_warehouse', 'to_warehouse', unique=True, postgresql_where=text(UNRESOLVED_DOC_STATUS_WHERE), sqlite_where=text(UNRESOLVED_DOC_STATUS_WHERE), @@ -333,7 +353,7 @@ class TransferDocument(Base): run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True) source_code: Mapped[str] = mapped_column(String(64), nullable=False) external_org: Mapped[str] = mapped_column(String(64), nullable=False) - receipt_date: Mapped[str] = mapped_column(String(16), nullable=False) + movement_date: Mapped[str] = mapped_column(String(16), nullable=False) from_warehouse: Mapped[str] = mapped_column(String(64), nullable=False) to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False) # 提交标识(D3 终身复用):同组复用单时保持首建值不变;唯一性由 @@ -476,6 +496,146 @@ class TransferArchive(Base): created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) +class TransferTypeConfig(Base): + """调拨类型配置(ADR 0002):编码/四语言名称/启停/排序 + 范围规则/仓库定义/转换规则。 + + code 创建后不可变(transfer_runs.transfer_type 引用);只有停用没有删除; + 配置为空时匹配链路 fail-closed(TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED)。 + """ + + __tablename__ = 'transfer_type_configs' + __table_args__ = ( + UniqueConstraint('code', name='uq_transfer_type_configs_code'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + code: Mapped[str] = mapped_column(String(64), nullable=False) + names_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict) + enabled: Mapped[bool] = mapped_column(default=False, server_default=text('false'), nullable=False) + sort_order: Mapped[int] = mapped_column(Integer, default=0, server_default=text('0'), nullable=False) + scope_rules_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list) + warehouse_config_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict) + transform_rules_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list) + description: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + +class TransferMovementLedger(Base): + """库存异动档(ADR 0001):外部系统入站/出站记录的平台镜像(参照 ERP inaj_t 形态)。 + + 用途:外部系统入站(一期)/出站(结构就位,record_kind='outbound')记录统一落档; + 匹配明细(items)由匹配创建时从档圈定生成(落地不再写 items,出生翻转)。 + 幂等增量落地:自然键 (source_code, record_kind, doc_no, line_no, line_seq, + in_out_flag, carton_id, lot_no, external_doc_no, external_line_no) 唯一约束 + 去重——不存在则插入、证据变化则原行更新、文件缺席不删(tt14 扩维:真实 WMS + 行身份=单据+行+箱/批,carton_id/lot_no 加入键防同箱/批塌缩丢行;R7 终审: + 两列同步 NOT NULL + default '',nullable 成分的 NULL 不参与 PG/SQLite 唯一 + 比对会逃逸约束,空值成分一律以空串入库保证唯一约束可比;2026-10-21 再扩维: + 外部单号/外部项次=WMS Order #/Line # 入键,外部单据身份作为档幂等主键管控); + 已执行记录 transfer_executed=true 封存(executed_doc_no 回写),永不更新、 + 永不复活、永不再次被圈定(防二次调拨,档级封存兜底)。 + 刻意双字段:record_kind(文件种类声明,权威)与 in_out_flag(数据列原值), + 两者矛盾即解析错位,由落档链路打审计事件,记录照常落档。 + 可空语义:自然键 8 成分一律 NOT NULL(line_seq/in_out_flag/carton_id/lot_no + default '' 保证唯一约束可比、防 PG NULL 逃逸唯一比对),业务/证据列一律 + nullable(外部列宽松落地);movement_date 可空——空值记录照常落档但不进 + 异动日期圈定(日期条件恒排除 NULL)。 + source_file_id ON DELETE SET NULL:来源文件被清理(文件资产保留策略)后 + 档记录必须留存(事实不随文件消失,链接仅溯源)。 + D 组 ⭐5 列(order_type/odm_id/odm_name/carton_id/pallet_id)为本期新增强 + 业务字段(进解析 Profile 可映射);🔖预留列(doc_nature/movement_type/ + reason_code/source_ref_no/partner_code/remark)出货报告确认后直接映射, + 免后续迁移。 + """ + + __tablename__ = 'transfer_movement_ledger' + __table_args__ = ( + # 自然键唯一(幂等增量落地兜底;应用层按自然键查档先行)。tt14 扩维 8 成分: + # carton_id/lot_no 进键(真实 WMS 行身份=单据+行+箱/批),R7 终审同步 + # NOT NULL + default ''(可空成分以空串入库,防 PG NULL 逃逸唯一比对)。 + # 2026-10-21 扩维 10 成分:external_doc_no/external_line_no(外部单号/ + # 外部项次,WMS Order #/Line #)进键——外部单据身份作为档幂等主键管控, + # 同一外部单号+项次的重复落档/证据更新收敛到同一档行(存量行以空串参与 + # 键;配置外部映射后重放同文件即按新键收敛,必要时走清空并重解析重建)。 + UniqueConstraint( + 'source_code', 'record_kind', 'doc_no', 'line_no', 'line_seq', 'in_out_flag', + 'carton_id', 'lot_no', 'external_doc_no', 'external_line_no', + name='uq_transfer_movement_ledger_natural_key', + ), + # 匹配创建圈档主路径:来源 + 记录种类 + 异动日期范围扫描。 + Index('ix_transfer_movement_ledger_source_kind_date', 'source_code', 'record_kind', 'movement_date'), + # 档级封存/待匹配桶扫描:按记录种类过滤已执行位。 + Index('ix_transfer_movement_ledger_kind_executed', 'record_kind', 'transfer_executed'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + # --- A 单据标识(自然键成分,NOT NULL;line_seq/in_out_flag 可空成分 default '')--- + doc_no: Mapped[str] = mapped_column(String(64), nullable=False) + line_no: Mapped[str] = mapped_column(String(32), nullable=False) + line_seq: Mapped[str] = mapped_column(String(32), nullable=False, default='', server_default='') + # 数据列原值(入站=收发标记),与 record_kind 交叉校验用,不参与权威判定。 + in_out_flag: Mapped[str] = mapped_column(String(8), nullable=False, default='', server_default='') + # --- A+ 外部单据身份(2026-10-21 起入自然键:外部单号/外部项次 = WMS Order #/ + # --- 行号;NOT NULL + default '' 与 line_seq 同口径,防 NULL 逃逸唯一比对)--- + external_doc_no: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='') + external_line_no: Mapped[str] = mapped_column(String(32), nullable=False, default='', server_default='') + # --- B 物料与数量(数量 Decimal 文本,与 items.movement_quantity 同约定)--- + material_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + material_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True) + specification: Mapped[Optional[str]] = mapped_column(String(200), nullable=True) + # 批号原值(tt14 起入自然键:NOT NULL + default '' 防 PG NULL 逃逸唯一比对; + # 空值成分以空串入库保证唯一约束可比,与 line_seq/in_out_flag 同口径)。 + lot_no: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='') + quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True) + unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + # --- C 仓储与日期(movement_date 可空:空值不进异动日期圈定)--- + warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + storage_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + movement_date: Mapped[Optional[str]] = mapped_column(String(16), nullable=True) + # --- D 业务属性(⭐本期新增强业务字段;carton_id tt14 起入自然键 NOT NULL + # --- default '';🔖预留列 nullable,出货侧直接映射)--- + order_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + odm_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + odm_name: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + # 箱号(tt14 起入自然键:NOT NULL + default '',与 lot_no 同口径,防 NULL 逃逸唯一比对)。 + carton_id: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='') + pallet_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + doc_nature: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + movement_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + reason_code: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) + source_ref_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + partner_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + # --- E 平台溯源(证据字段:evidence_sync 原行更新时整体换新)--- + source_code: Mapped[str] = mapped_column(String(64), nullable=False) + # 文件种类声明(tt14 值迁移后 'inbound'/'outbound',权威);与 in_out_flag 矛盾打审计事件。 + record_kind: Mapped[str] = mapped_column(String(16), nullable=False) + # 来源文件溯源:ON DELETE SET NULL(文件清理后档事实留存)。 + source_file_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('freight_rpa_inbound_report_files.id', ondelete='SET NULL'), nullable=True, + ) + file_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + sheet_name: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + row_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, + ) + # --- F 平台回写(档级封存:票据执行成功落单号时回写,永不解除)--- + transfer_executed: Mapped[bool] = mapped_column( + default=False, server_default=text('false'), nullable=False, + ) + executed_doc_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + + # 溯源关系:档案行 → FreightRpaInboundReportFile 原样归档文件(单向,不回挂;FreightRpaInboundReportFile + # 不感知调拨域,避免跨域 back_populates 环)。 + source_file: Mapped[Optional['FreightRpaInboundReportFile']] = relationship() + + @event.listens_for(TransferAuditEvent, 'before_update') def _reject_transfer_audit_update(_mapper, _connection, _target) -> None: """拒绝 ORM 更新,确保审计事件不可改写。""" diff --git a/backend/app/models/job.py b/backend/app/models/job.py index df7ef9cd..fd6803c4 100644 --- a/backend/app/models/job.py +++ b/backend/app/models/job.py @@ -2,7 +2,7 @@ backend/app/models/job.py 用途:通用后台任务模型,承载跨业务域的异步任务执行状态。 -依赖:models.base.Base。 +依赖:models.base.Base;候选集外键指向 shipping_onhand_candidate_sets。 逻辑:由 app.jobs.queue 写入和领取,由 worker 分发到具体业务 handler;业务模型保存业务状态,本表保存执行状态、锁、重试与结果。 """ @@ -149,7 +149,7 @@ class Job(Base): ForeignKey('shipping_process_gates.id'), nullable=True, index=True, ) candidate_set_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_candidate_sets.id'), nullable=True, index=True, + ForeignKey('shipping_onhand_candidate_sets.id'), nullable=True, index=True, ) fencing_token: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id')) diff --git a/backend/app/models/shipping.py b/backend/app/models/shipping.py index 5fbad44b..b19233ba 100644 --- a/backend/app/models/shipping.py +++ b/backend/app/models/shipping.py @@ -1,7 +1,7 @@ """ backend/app/models/shipping.py -用途:货代发货通知正式 Notice(shipping_notices)、事件、库存文件、接入记录、文档/候选与库存映射模型。 +用途:货代发货通知正式 Notice(shipping_notices)、事件、在手报表文件(freight_rpa_onhand_report_files,s18 起归 RPA,列仍含解析行与快照状态)、任务关联(shipping_task_onhand_links)、接入记录与文档/候选模型。 依赖:models.base.Base;规范订单行见 shipping_task_line;建单前 OT 见 shipping_order_task。 逻辑:co8e9f0a1b2c 已物理 DROP shipping_batches 及全表 batch_id / consumed_batch_id 列; Intake 消费绑定仅保留 consumed_task_id / consumed_at;upload_batch_id 为上传边界批次(非 shipping_batches); @@ -164,108 +164,15 @@ class ShippingTaskPurgeAudit(Base): created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) -class ShippingInventoryFile(Base): - """货代发货批次库存快照文件,承载一次上传后可被多票任务共用的库存数据。""" - - __tablename__ = 'shipping_inventory_files' - __table_args__ = ( - Index('ix_shipping_inventory_files_user_created', 'user_id', 'created_at'), - Index( - 'ix_shipping_inventory_files_source_snapshot', - 'source_code', - 'warehouse_id', - 'snapshot_status', - 'exported_at', - ), - Index( - 'ix_shipping_inventory_files_source_warehouse', - 'source_code', - 'warehouse_id', - ), - Index( - 'uq_shipping_inventory_files_rpa_identity_ready', - 'rpa_run_no', - 'source_code', - 'warehouse_id', - unique=True, - postgresql_where=text( - "snapshot_status = 'ready' AND rpa_run_no IS NOT NULL " - "AND source_code IS NOT NULL AND warehouse_id IS NOT NULL" - ), - sqlite_where=text( - "snapshot_status = 'ready' AND rpa_run_no IS NOT NULL " - "AND source_code IS NOT NULL AND warehouse_id IS NOT NULL" - ), - ), - # 动态多仓文件没有单一 Warehouse;按 RPA run + Source 保证回调重放幂等。 - Index( - 'uq_shipping_inventory_files_rpa_dynamic_source_ready', - 'rpa_run_no', - 'source_code', - unique=True, - postgresql_where=text( - "snapshot_status = 'ready' AND rpa_run_no IS NOT NULL " - "AND source_code IS NOT NULL AND warehouse_id IS NULL" - ), - sqlite_where=text( - "snapshot_status = 'ready' AND rpa_run_no IS NOT NULL " - "AND source_code IS NOT NULL AND warehouse_id IS NULL" - ), - ), - ) - - id: Mapped[int] = mapped_column(primary_key=True) - inventory_file_no: Mapped[str] = mapped_column(String(64), unique=True, index=True) - user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True) - source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) - storage_path: Mapped[str] = mapped_column(String(500), nullable=False) - schema_preview_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) - field_mapping_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) - mapping_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) - mapping_confirmed: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false')) - inventory_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True) - line_count: Mapped[int] = mapped_column(Integer, default=0) - share_mode: Mapped[str] = mapped_column(String(32), default='task_only') - warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) - warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) - identity_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True) - source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) - source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) - snapshot_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True) - exported_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True) - expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True) - rpa_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - schedule_run_id: Mapped[Optional[int]] = mapped_column(nullable=True, index=True) - source_query_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) - superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True) - invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) - invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True) - invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True) - input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) - created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) - updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) - - links: Mapped[List['ShippingTaskInventoryLink']] = relationship( - 'ShippingTaskInventoryLink', - back_populates='inventory_file', - cascade='all, delete-orphan', - ) - - -class ShippingTaskInventoryLink(Base): +class ShippingTaskOnhandLink(Base): """发货任务与库存快照的关联记录,一期每个任务只保留一条 active link。""" - __tablename__ = 'shipping_task_inventory_links' + __tablename__ = 'shipping_task_onhand_links' __table_args__ = ( - Index('ix_shipping_task_inventory_links_task_active', 'task_id', 'is_active'), - Index('ix_shipping_task_inventory_links_file_active', 'inventory_file_id', 'is_active'), + Index('ix_shipping_task_onhand_links_task_active', 'task_id', 'is_active'), + Index('ix_shipping_task_onhand_links_file_active', 'onhand_file_id', 'is_active'), Index( - 'ix_shipping_task_inventory_links_task_source', + 'ix_shipping_task_onhand_links_task_source', 'task_id', 'matched_source_code', ), @@ -273,7 +180,7 @@ class ShippingTaskInventoryLink(Base): id: Mapped[int] = mapped_column(primary_key=True) task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), index=True) - inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id'), index=True) + onhand_file_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id'), index=True) link_role: Mapped[str] = mapped_column(String(32), default='member') access_mode: Mapped[str] = mapped_column(String(32), default='readonly') is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default=text('true'), index=True) @@ -283,8 +190,8 @@ class ShippingTaskInventoryLink(Base): identity_check_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) identity_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) snapshot_age_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) - preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', use_alter=True), nullable=True, index=True) - source_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_source_attempts.id', use_alter=True), nullable=True, index=True) + preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_onhand_preparation_attempts.id', use_alter=True), nullable=True, index=True) + source_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_onhand_preparation_source_attempts.id', use_alter=True), nullable=True, index=True) invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True) invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True) @@ -294,10 +201,10 @@ class ShippingTaskInventoryLink(Base): linked_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) task: Mapped['ShippingOrderTask'] = relationship('ShippingOrderTask', foreign_keys=[task_id]) - inventory_file: Mapped['ShippingInventoryFile'] = relationship( - 'ShippingInventoryFile', + inventory_file: Mapped['FreightRpaOnhandReportFile'] = relationship( + 'FreightRpaOnhandReportFile', back_populates='links', - foreign_keys=[inventory_file_id], + foreign_keys=[onhand_file_id], ) diff --git a/backend/app/models/shipping_excel_template.py b/backend/app/models/shipping_excel_template.py index 91a069cf..f0b841c5 100644 --- a/backend/app/models/shipping_excel_template.py +++ b/backend/app/models/shipping_excel_template.py @@ -2,7 +2,7 @@ models/shipping_excel_template.py 用途:定义版本化发货 Excel 模板及不可变 Notice 导出产物。 -依赖:models.base.Base、库存源、订单 Schema、ShippingNotice 与库存快照模型。 +依赖:models.base.Base、FreightRpaSource、订单 Schema、ShippingNotice、freight_rpa_parsing_profiles 与 freight_rpa_onhand_report_files。 逻辑:库存源只绑定已发布模板版本;每次生成均新增 Artifact 并锁定输入版本与校验和; co8e9f0a1b2c 已删除 export artifact 的 batch_id 列;Artifact 直接属于一张 Notice。 """ @@ -44,7 +44,7 @@ class ShippingExcelTemplate(Base): created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) - sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='excel_template') + sources: Mapped[list['FreightRpaSource']] = relationship(back_populates='excel_template') class ShippingExportArtifact(Base): @@ -62,8 +62,8 @@ class ShippingExportArtifact(Base): template_id: Mapped[int] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=False) order_schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False) order_extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False) - inventory_parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=False) - inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True) + inventory_parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_parsing_profiles.id'), nullable=False) + inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id'), nullable=True) input_checksum: Mapped[str] = mapped_column(String(64), nullable=False) file_path: Mapped[str] = mapped_column(String(500), nullable=False) file_name: Mapped[str] = mapped_column(String(255), nullable=False) diff --git a/backend/app/models/shipping_fulfillment.py b/backend/app/models/shipping_fulfillment.py index d4323b31..68800cf6 100644 --- a/backend/app/models/shipping_fulfillment.py +++ b/backend/app/models/shipping_fulfillment.py @@ -2,7 +2,7 @@ backend/app/models/shipping_fulfillment.py 用途:保存预约单全局注册、每轮库存核验和 Excel 对预约单的不可重叠归属。 -依赖:冻结订单 Snapshot、库存文件、导出 Artifact 与 SQLAlchemy Base;Notice 主表 shipping_notices。 +依赖:冻结订单 Snapshot、freight_rpa_onhand_report_files、导出 Artifact 与 SQLAlchemy Base;核验表 shipping_notice_onhand_verifications / shipping_notice_onhand_verification_lines;Notice 主表 shipping_notices。 逻辑:Snapshot 行可保留历史预约号;全局 Reservation 决定当前有效行和履约状态,核验与 Artifact 行均追加保存。 """ @@ -46,53 +46,53 @@ class ShippingReservation(Base): updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) -class ShippingInventoryVerification(Base): +class ShippingOnhandVerification(Base): """一次任务库存核验的不可变轮次,绑定当时有效库存快照。""" - __tablename__ = 'shipping_notice_inventory_verifications' + __tablename__ = 'shipping_notice_onhand_verifications' __table_args__ = ( CheckConstraint( "status IN ('completed', 'expired', 'superseded')", - name='ck_shipping_notice_inventory_verifications_status', + name='ck_shipping_notice_onhand_verifications_status', ), - Index('ix_shipping_notice_inventory_verifications_task_created', 'task_id', 'created_at'), + Index('ix_shipping_notice_onhand_verifications_task_created', 'task_id', 'created_at'), ) id: Mapped[int] = mapped_column(primary_key=True) task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False) - inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True) + onhand_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id'), nullable=True) source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', ondelete='SET NULL'), nullable=True, index=True) + preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_onhand_preparation_attempts.id', ondelete='SET NULL'), nullable=True, index=True) matching_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True, index=True) input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_inventory_verifications.id'), nullable=True) + superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_onhand_verifications.id'), nullable=True) status: Mapped[str] = mapped_column(String(16), nullable=False, default='completed', server_default='completed') result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) - lines: Mapped[list['ShippingInventoryVerificationLine']] = relationship( - back_populates='verification', cascade='all, delete-orphan', order_by='ShippingInventoryVerificationLine.id', + lines: Mapped[list['ShippingOnhandVerificationLine']] = relationship( + back_populates='verification', cascade='all, delete-orphan', order_by='ShippingOnhandVerificationLine.id', ) -class ShippingInventoryVerificationLine(Base): +class ShippingOnhandVerificationLine(Base): """一个预约单在一轮库存中的需求、可用数量和确定性结果。""" - __tablename__ = 'shipping_notice_inventory_verification_lines' + __tablename__ = 'shipping_notice_onhand_verification_lines' __table_args__ = ( UniqueConstraint( 'verification_id', 'reservation_id', - name='uq_shipping_notice_inventory_verification_lines_reservation', + name='uq_shipping_notice_onhand_verification_lines_reservation', ), CheckConstraint( "status IN ('available', 'shortage', 'invalid')", - name='ck_shipping_notice_inventory_verification_lines_status', + name='ck_shipping_notice_onhand_verification_lines_status', ), ) id: Mapped[int] = mapped_column(primary_key=True) verification_id: Mapped[int] = mapped_column( - ForeignKey('shipping_notice_inventory_verifications.id', ondelete='CASCADE'), nullable=False, + ForeignKey('shipping_notice_onhand_verifications.id', ondelete='CASCADE'), nullable=False, ) reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False) required_qty: Mapped[Decimal] = mapped_column(Numeric(24, 8), nullable=False) @@ -100,7 +100,7 @@ class ShippingInventoryVerificationLine(Base): status: Mapped[str] = mapped_column(String(16), nullable=False) detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) - verification: Mapped['ShippingInventoryVerification'] = relationship(back_populates='lines') + verification: Mapped['ShippingOnhandVerification'] = relationship(back_populates='lines') class ShippingExportArtifactLine(Base): @@ -120,7 +120,7 @@ class ShippingExportArtifactLine(Base): ) reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False) verification_line_id: Mapped[int] = mapped_column( - ForeignKey('shipping_notice_inventory_verification_lines.id'), nullable=False, + ForeignKey('shipping_notice_onhand_verification_lines.id'), nullable=False, ) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) diff --git a/backend/app/models/shipping_notice_line.py b/backend/app/models/shipping_notice_line.py index b2d4f9d3..997f3ca0 100644 --- a/backend/app/models/shipping_notice_line.py +++ b/backend/app/models/shipping_notice_line.py @@ -2,7 +2,7 @@ backend/app/models/shipping_notice_line.py 用途:正式发货通知行(shipping_notice_lines),对齐蓝图建单后命名空间。 -依赖:shipping_notices、shipping_order_snapshot_lines、SQLAlchemy Base。 +依赖:shipping_notices、shipping_order_snapshot_lines、freight_rpa_onhand_report_files、SQLAlchemy Base。 逻辑:冻结 Snapshot 时双写;履约仍以 Snapshot 为权威,本表供 Notice 域查询与 1:N 扩展。 """ @@ -47,7 +47,7 @@ class ShippingNoticeLine(Base): # 正式履约事实按通知行固化;Notice 单头不得承载仓库或库存快照。 inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) inventory_file_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'), nullable=True, index=True, + ForeignKey('freight_rpa_onhand_report_files.id', ondelete='SET NULL'), nullable=True, index=True, ) inventory_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True) field_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) diff --git a/backend/app/models/shipping_notice_line_inventory_match.py b/backend/app/models/shipping_notice_line_onhand_match.py similarity index 84% rename from backend/app/models/shipping_notice_line_inventory_match.py rename to backend/app/models/shipping_notice_line_onhand_match.py index 32625f87..e4fdc953 100644 --- a/backend/app/models/shipping_notice_line_inventory_match.py +++ b/backend/app/models/shipping_notice_line_onhand_match.py @@ -1,9 +1,9 @@ """ -models/shipping_notice_line_inventory_match.py +models/shipping_notice_line_onhand_match.py 用途:正式 OT(ShippingNotice)行级库存匹配事实持久化——可用数量/短缺/match_result 的真相源。 -依赖:shipping_notices、shipping_inventory_files、shipping_order_review_cases(可选关联)。 -逻辑:由 inventory_matching 完成后写入;同一 OT+行+快照唯一;新快照新增行不覆盖历史; +依赖:shipping_notices、freight_rpa_onhand_report_files、shipping_order_review_cases(可选关联)。 +逻辑:由 onhand_matching 完成后写入;同一 OT+行+快照唯一;新快照新增行不覆盖历史; is_current 标记投影用的当前事实;禁止用 Job payload / line_projections 充当正式真相。 """ @@ -30,15 +30,15 @@ from sqlalchemy.orm import Mapped, mapped_column from app.models.base import Base -class ShippingNoticeLineInventoryMatch(Base): +class ShippingNoticeLineOnhandMatch(Base): """一条 OT 明细在某库存快照下的匹配事实(不可原地覆盖历史快照结果)。""" - __tablename__ = 'shipping_notice_line_inventory_matches' + __tablename__ = 'shipping_notice_line_onhand_matches' __table_args__ = ( UniqueConstraint( 'task_id', 'snapshot_line_id', - 'inventory_snapshot_id', + 'onhand_snapshot_id', name='uq_shipping_notice_line_inv_match_task_line_snap', ), # 同一 OT 行同一时刻仅一条当前事实(PostgreSQL partial unique)。 @@ -51,7 +51,7 @@ class ShippingNoticeLineInventoryMatch(Base): ), Index('ix_shipping_notice_line_inv_match_task', 'task_id'), Index('ix_shipping_notice_line_inv_match_case', 'review_case_id'), - Index('ix_shipping_notice_line_inv_match_snapshot', 'inventory_snapshot_id'), + Index('ix_shipping_notice_line_inv_match_snapshot', 'onhand_snapshot_id'), CheckConstraint( "match_result IN (" "'matched', 'not_found', 'result_missing', 'preparing', " @@ -60,7 +60,7 @@ class ShippingNoticeLineInventoryMatch(Base): name='ck_shipping_notice_line_inv_match_result', ), CheckConstraint( - "inventory_status IN (" + "onhand_status IN (" "'ready', 'preparing', 'mapping_failed', 'source_conflict', " "'unavailable', 'invalid_key', 'invalid'" ")", @@ -85,22 +85,22 @@ class ShippingNoticeLineInventoryMatch(Base): line_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1') line_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) candidate_set_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'), + ForeignKey('shipping_onhand_candidate_sets.id', ondelete='SET NULL'), nullable=True, index=True, ) candidate_set_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) candidate_line_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_candidate_lines.id', ondelete='SET NULL'), + ForeignKey('shipping_onhand_candidate_lines.id', ondelete='SET NULL'), nullable=True, index=True, ) - inventory_snapshot_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'), + onhand_snapshot_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('freight_rpa_onhand_report_files.id', ondelete='SET NULL'), nullable=True, ) match_result: Mapped[str] = mapped_column(String(32), nullable=False) - inventory_status: Mapped[str] = mapped_column(String(32), nullable=False) + onhand_status: Mapped[str] = mapped_column(String(32), nullable=False) required_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) shortage_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) @@ -111,7 +111,7 @@ class ShippingNoticeLineInventoryMatch(Base): part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) matching_rule_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) is_current: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default='true') matched_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow) detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) @@ -146,7 +146,7 @@ class ShippingNoticeLineInventoryMatch(Base): invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True) invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True) - superseded_by_match_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_line_inventory_matches.id'), nullable=True) + superseded_by_match_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_line_onhand_matches.id'), nullable=True) input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - mapping_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_mappings.id', ondelete='SET NULL'), nullable=True, index=True) - verification_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_inventory_verifications.id', ondelete='SET NULL'), nullable=True, index=True) + mapping_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_mappings.id', ondelete='SET NULL'), nullable=True, index=True) + verification_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_onhand_verifications.id', ondelete='SET NULL'), nullable=True, index=True) diff --git a/backend/app/models/shipping_inventory_candidates.py b/backend/app/models/shipping_onhand_candidates.py similarity index 86% rename from backend/app/models/shipping_inventory_candidates.py rename to backend/app/models/shipping_onhand_candidates.py index b9e8059f..eefa8cbd 100644 --- a/backend/app/models/shipping_inventory_candidates.py +++ b/backend/app/models/shipping_onhand_candidates.py @@ -1,12 +1,12 @@ """ -models/shipping_inventory_candidates.py +models/shipping_onhand_candidates.py 用途:库存候选冻结的结构化持久化——决策 C1 的正式业务真相。 - InventoryCandidateSet(候选集合)→ Source(任务级候选源)→ Line(行级候选源), + ShippingOnhandCandidateSet(候选集合)→ Source(任务级候选源)→ Line(行级候选源), 同时 ShippingOrderSnapshot.source_manifest_json['inventory_candidate_freeze'] 保存 同一时刻的完整不可变副本,用于审计与回滚。 依赖:Base、ShippingOrderTask、ShippingProcessExecution、ShippingOrderReviewCase、users、 - ShippingInventoryRoutingRule(可选外键,路由规则版本)。 + FreightRpaOnhandRoutingRule(可选外键,路由规则版本)。 逻辑:建单前复核阶段(review_case 绑定)或建单后正式推进阶段(task 绑定)都可冻结; input_fingerprint 相同的重复 freeze 直接返回旧 set_id(幂等); source_codes_json 为有序列表(路由优先级信息不能丢),禁止用 SET 类型。 @@ -39,7 +39,7 @@ def _utc_now() -> datetime: return datetime.utcnow() -class ShippingInventoryCandidateSet(Base): +class ShippingOnhandCandidateSet(Base): """ 库存候选集合(冻结真相根)。 @@ -48,7 +48,7 @@ class ShippingInventoryCandidateSet(Base): 二者至少一个非空(CheckConstraint 强制)。 """ - __tablename__ = 'shipping_inventory_candidate_sets' + __tablename__ = 'shipping_onhand_candidate_sets' __table_args__ = ( CheckConstraint( 'task_id IS NOT NULL OR review_case_id IS NOT NULL', @@ -98,7 +98,7 @@ class ShippingInventoryCandidateSet(Base): ) superseded_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) superseded_by_set_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'), nullable=True, + ForeignKey('shipping_onhand_candidate_sets.id', ondelete='SET NULL'), nullable=True, ) invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) invalidated_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True) @@ -111,19 +111,19 @@ class ShippingInventoryCandidateSet(Base): ) remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True) - sources: Mapped[list['ShippingInventoryCandidateSource']] = relationship( + sources: Mapped[list['ShippingOnhandCandidateSource']] = relationship( back_populates='candidate_set', cascade='all, delete-orphan', - order_by='ShippingInventoryCandidateSource.candidate_order', + order_by='ShippingOnhandCandidateSource.candidate_order', ) - lines: Mapped[list['ShippingInventoryCandidateLine']] = relationship( + lines: Mapped[list['ShippingOnhandCandidateLine']] = relationship( back_populates='candidate_set', cascade='all, delete-orphan', - order_by='ShippingInventoryCandidateLine.line_no', + order_by='ShippingOnhandCandidateLine.line_no', ) -class ShippingInventoryCandidateSource(Base): +class ShippingOnhandCandidateSource(Base): """ 任务级候选库存源(Set 的子级)。 @@ -132,7 +132,7 @@ class ShippingInventoryCandidateSource(Base): candidate_origin ∈ {rule, manual_override},区分是规则算出来还是人工强制指定。 """ - __tablename__ = 'shipping_inventory_candidate_sources' + __tablename__ = 'shipping_onhand_candidate_sources' __table_args__ = ( UniqueConstraint( 'candidate_set_id', 'source_code', @@ -151,13 +151,13 @@ class ShippingInventoryCandidateSource(Base): id: Mapped[int] = mapped_column(primary_key=True) candidate_set_id: Mapped[int] = mapped_column( - ForeignKey('shipping_inventory_candidate_sets.id', ondelete='CASCADE'), nullable=False, + ForeignKey('shipping_onhand_candidate_sets.id', ondelete='CASCADE'), nullable=False, ) source_code: Mapped[str] = mapped_column(String(64), nullable=False) candidate_order: Mapped[int] = mapped_column(Integer, nullable=False) candidate_origin: Mapped[str] = mapped_column(String(32), nullable=False, default='rule') routing_rule_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_routing_rules.id', ondelete='SET NULL'), nullable=True, + ForeignKey('freight_rpa_onhand_routing_rules.id', ondelete='SET NULL'), nullable=True, ) routing_rule_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) @@ -170,12 +170,12 @@ class ShippingInventoryCandidateSource(Base): DateTime, default=_utc_now, onupdate=_utc_now, nullable=False, ) - candidate_set: Mapped['ShippingInventoryCandidateSet'] = relationship( + candidate_set: Mapped['ShippingOnhandCandidateSet'] = relationship( back_populates='sources', ) -class ShippingInventoryCandidateLine(Base): +class ShippingOnhandCandidateLine(Base): """ 行级候选库存源(Set 的子级,按稳定 line_no 对齐订单行)。 @@ -185,7 +185,7 @@ class ShippingInventoryCandidateLine(Base): part_number + reservation_id,不能只依赖 Snapshot JSON 做高频查询。 """ - __tablename__ = 'shipping_inventory_candidate_lines' + __tablename__ = 'shipping_onhand_candidate_lines' __table_args__ = ( UniqueConstraint( 'candidate_set_id', 'line_no', @@ -199,7 +199,7 @@ class ShippingInventoryCandidateLine(Base): id: Mapped[int] = mapped_column(primary_key=True) candidate_set_id: Mapped[int] = mapped_column( - ForeignKey('shipping_inventory_candidate_sets.id', ondelete='CASCADE'), nullable=False, + ForeignKey('shipping_onhand_candidate_sets.id', ondelete='CASCADE'), nullable=False, ) line_no: Mapped[int] = mapped_column(Integer, nullable=False) source_line_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) @@ -215,6 +215,6 @@ class ShippingInventoryCandidateLine(Base): DateTime, default=_utc_now, onupdate=_utc_now, nullable=False, ) - candidate_set: Mapped['ShippingInventoryCandidateSet'] = relationship( + candidate_set: Mapped['ShippingOnhandCandidateSet'] = relationship( back_populates='lines', ) diff --git a/backend/app/models/shipping_inventory_preparation.py b/backend/app/models/shipping_onhand_preparation.py similarity index 77% rename from backend/app/models/shipping_inventory_preparation.py rename to backend/app/models/shipping_onhand_preparation.py index 786f0574..8ee6d471 100644 --- a/backend/app/models/shipping_inventory_preparation.py +++ b/backend/app/models/shipping_onhand_preparation.py @@ -1,8 +1,8 @@ """ -models/shipping_inventory_preparation.py +models/shipping_onhand_preparation.py 用途:表达一次任务级库存准备轮次及逐库存源状态。 -依赖:ShippingOrderTask、RecoveryPlan、RPA Attempt、InventoryFile、TaskInventoryLink、Base。 +依赖:ShippingOrderTask、RecoveryPlan、FreightRpaOnhandTaskAttempt、FreightRpaOnhandReportFile、ShippingTaskOnhandLink、Base。 逻辑:PreparationAttempt 聚合多个 SourceAttempt,支持有效源复用和问题源单独重拉。 """ @@ -17,10 +17,10 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship from app.models.base import Base -class ShippingInventoryPreparationAttempt(Base): +class ShippingOnhandPreparationAttempt(Base): """一次任务级库存准备恢复轮次。""" - __tablename__ = 'shipping_inventory_preparation_attempts' + __tablename__ = 'shipping_onhand_preparation_attempts' __table_args__ = ( UniqueConstraint('task_id', 'attempt_no', name='uq_shipping_inventory_preparation_task_attempt'), CheckConstraint( @@ -38,7 +38,7 @@ class ShippingInventoryPreparationAttempt(Base): attempt_no: Mapped[int] = mapped_column(Integer, nullable=False) status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued') combination_input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - candidate_set_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'), nullable=True) + candidate_set_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_onhand_candidate_sets.id', ondelete='SET NULL'), nullable=True) input_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) output_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) @@ -46,13 +46,13 @@ class ShippingInventoryPreparationAttempt(Base): started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) - source_attempts = relationship('ShippingInventoryPreparationSourceAttempt', back_populates='preparation_attempt', cascade='all, delete-orphan') + source_attempts = relationship('ShippingOnhandPreparationSourceAttempt', back_populates='preparation_attempt', cascade='all, delete-orphan') -class ShippingInventoryPreparationSourceAttempt(Base): +class ShippingOnhandPreparationSourceAttempt(Base): """准备轮次中某个库存源的业务状态。""" - __tablename__ = 'shipping_inventory_preparation_source_attempts' + __tablename__ = 'shipping_onhand_preparation_source_attempts' __table_args__ = ( UniqueConstraint('preparation_attempt_id', 'source_code', name='uq_shipping_inventory_preparation_source_attempt'), CheckConstraint( @@ -63,17 +63,17 @@ class ShippingInventoryPreparationSourceAttempt(Base): ) id: Mapped[int] = mapped_column(Integer, primary_key=True) - preparation_attempt_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', ondelete='CASCADE'), nullable=False) + preparation_attempt_id: Mapped[int] = mapped_column(ForeignKey('shipping_onhand_preparation_attempts.id', ondelete='CASCADE'), nullable=False) source_code: Mapped[str] = mapped_column(String(64), nullable=False) warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued') skip_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True) - rpa_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_task_inventory_rpa_attempts.id', ondelete='SET NULL'), nullable=True) - inventory_file_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'), nullable=True) - task_inventory_link_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_task_inventory_links.id', ondelete='SET NULL'), nullable=True) + rpa_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_task_rpa_attempts.id', ondelete='SET NULL'), nullable=True) + onhand_file_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id', ondelete='SET NULL'), nullable=True) + task_onhand_link_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_task_onhand_links.id', ondelete='SET NULL'), nullable=True) input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) - preparation_attempt = relationship('ShippingInventoryPreparationAttempt', back_populates='source_attempts') + preparation_attempt = relationship('ShippingOnhandPreparationAttempt', back_populates='source_attempts') diff --git a/backend/app/models/shipping_order_review_line_decision.py b/backend/app/models/shipping_order_review_line_decision.py index fb83a1e2..a770bbe0 100644 --- a/backend/app/models/shipping_order_review_line_decision.py +++ b/backend/app/models/shipping_order_review_line_decision.py @@ -32,8 +32,8 @@ class ShippingOrderReviewLineDecision(Base): ), CheckConstraint( "decision_code IN (" - "'wait_inventory', 'use_new_inventory_file', 'change_inventory_source', " - "'fulfill_complete_line_now', 'close_unfulfillable', 'reopen', 'release_inventory_shortage'" + "'wait_onhand', 'use_new_inventory_file', 'change_inventory_source', " + "'fulfill_complete_line_now', 'close_unfulfillable', 'reopen', 'release_onhand_shortage'" ")", name='ck_shipping_review_line_decisions_code', ), diff --git a/backend/app/models/shipping_order_task.py b/backend/app/models/shipping_order_task.py index 68338d0c..dfaa9d62 100644 --- a/backend/app/models/shipping_order_task.py +++ b/backend/app/models/shipping_order_task.py @@ -2,7 +2,7 @@ backend/app/models/shipping_order_task.py 用途:正式发货通知创建前的 OT(shipping_order_tasks)聚合根,对齐多 EML/PDF 蓝图。 -依赖:users、agents、shipping_order_submissions/intakes/candidates、extraction_runs。 +依赖:users、agents、shipping_order_submissions/intakes/candidates、extraction_runs、shipping_onhand_candidate_sets。 逻辑:由 Extraction Run 的 user_task_no 双写/回填;正式 ShippingNotice 通过 order_task_id 反向关联,本表不保存通知单指针。 页面链路以 task_no(OT-…)为根身份;1 OT 可对应 0..N Notice。 """ @@ -104,7 +104,7 @@ class ShippingOrderTask(Base): ForeignKey('shipping_order_snapshots.id', name='fk_shipping_order_tasks_order_snapshot', use_alter=True), nullable=True, index=True, ) active_inventory_candidate_set_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_candidate_sets.id', use_alter=True), nullable=True, index=True, + ForeignKey('shipping_onhand_candidate_sets.id', use_alter=True), nullable=True, index=True, ) step_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) active_process_execution_id: Mapped[Optional[int]] = mapped_column( diff --git a/backend/app/models/shipping_process_gate.py b/backend/app/models/shipping_process_gate.py index 33ef80fc..1dbf9f20 100644 --- a/backend/app/models/shipping_process_gate.py +++ b/backend/app/models/shipping_process_gate.py @@ -2,7 +2,7 @@ models/shipping_process_gate.py 用途:门禁级中断恢复的持久化模型——Execution / Gate / Attempt。 -依赖:SQLAlchemy Base、ReviewCase、ShippingOrderTask、Job;状态枚举与 process_gate_contract 对齐。 +依赖:SQLAlchemy Base、ReviewCase、ShippingOrderTask、Job、shipping_onhand_candidate_sets;状态枚举与 process_gate_contract 对齐。 逻辑:Execution 为业务恢复真相;Gate 保存当前门禁状态;Attempt 不可变执行尝试并承载租约。 由领域服务独占写入;Job 仅调度。 co8e9f0a1b2c:已移除对 shipping_notice_workflow_* 的硬外键(无历史兼容)。 @@ -78,7 +78,7 @@ class ShippingProcessExecution(Base): ) # 绑定候选版本,防止旧 callback/job 写入新候选链。 candidate_set_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_candidate_sets.id'), nullable=True, + ForeignKey('shipping_onhand_candidate_sets.id'), nullable=True, ) execution_revision: Mapped[int] = mapped_column( Integer, nullable=False, default=1, server_default='1', diff --git a/backend/app/models/shipping_receipt_report.py b/backend/app/models/shipping_receipt_report.py deleted file mode 100644 index 22ec2ac8..00000000 --- a/backend/app/models/shipping_receipt_report.py +++ /dev/null @@ -1,168 +0,0 @@ -""" -收料报表 RPA 的配置、运行、归档与通知投递持久化模型。 - -用途:为独立收料排程保存站点级配置、每站点/仓库执行单元、原样归档文件及企微投递事实。 -依赖:库存站点、排程运行、SQLAlchemy Base;完整操作追溯统一写入 ShippingAuditEvent。 -逻辑:模型只复用库存站点的连接资料,通过独立外键与唯一约束隔离库存快照、匹配和旧 RPA Worker 链路。 -""" - -from __future__ import annotations - -from datetime import datetime -from typing import Any, Optional - -from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text -from sqlalchemy.orm import Mapped, mapped_column, relationship - -from app.models.base import Base - - -class ShippingReceiptReportConfig(Base): - """库存站点的一对一收料报表配置;路径和条件始终独立于库存配置。""" - - __tablename__ = 'shipping_receipt_report_configs' - __table_args__ = ( - UniqueConstraint('inventory_source_id', name='uq_shipping_receipt_report_configs_source'), - ) - - id: Mapped[int] = mapped_column(primary_key=True) - inventory_source_id: Mapped[int] = mapped_column( - ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True, - ) - # 收料不设独立启停:是否运行统一由库存站点 enabled 与本配置是否存在决定。 - # 收料文件解析规则(purpose='movement');定死领域字段端点。空则无法解析收料文件。 - parsing_profile_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True, - ) - report_path_json: Mapped[dict[str, Any]] = mapped_column( - JSON, default=dict, server_default=text("'{}'"), nullable=False, - ) - query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column( - JSON, default=list, server_default=text("'[]'"), nullable=False, - ) - # 与库存同构:查询条件原样下发 Worker;空条件表示页面默认。排程一源一单元,不按仓拆分。 - config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False) - created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) - updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) - created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) - updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) - - inventory_source: Mapped['ShippingInventorySource'] = relationship(back_populates='receipt_report_config') - parsing_profile: Mapped[Optional['ShippingInventoryParsingProfile']] = relationship() - - -class ShippingReceiptRpaUnitRun(Base): - """一次收料执行的站点或站点-Warehouse 不可重复执行单元。 - - schedule_run_id 指向排程 run;调拨按需触发(重试/预检补抓)无排程,保持 NULL。 - """ - - __tablename__ = 'shipping_receipt_rpa_unit_runs' - __table_args__ = ( - UniqueConstraint('callback_id', name='uq_shipping_receipt_rpa_unit_runs_callback'), - CheckConstraint( - "status IN ('queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled')", - name='ck_shipping_receipt_rpa_unit_runs_status', - ), - Index('ix_shipping_receipt_unit_run_schedule_status', 'schedule_run_id', 'status'), - Index('ix_shipping_receipt_unit_run_source_created', 'inventory_source_id', 'created_at'), - ) - - id: Mapped[int] = mapped_column(primary_key=True) - schedule_run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_runs.id'), nullable=True, index=True) - inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True) - retry_of_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_receipt_rpa_unit_runs.id'), nullable=True, index=True, - ) - source_code: Mapped[str] = mapped_column(String(64), nullable=False) - connector_type: Mapped[str] = mapped_column(String(32), nullable=False) - warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - callback_id: Mapped[str] = mapped_column(String(128), nullable=False) - status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued') - config_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) - trigger_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) - result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) - error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) - started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) - finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) - created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) - - schedule_run: Mapped[Optional['ScheduleRun']] = relationship(foreign_keys=[schedule_run_id]) - inventory_source: Mapped['ShippingInventorySource'] = relationship() - retry_of: Mapped[Optional['ShippingReceiptRpaUnitRun']] = relationship(remote_side=[id]) - files: Mapped[list['ShippingReceiptReportFile']] = relationship( - back_populates='unit_run', cascade='all, delete-orphan', - ) - - -class ShippingReceiptReportFile(Base): - """收料原样归档文件;保留文件身份和对象清理事实,不关联库存快照。""" - - __tablename__ = 'shipping_receipt_report_files' - __table_args__ = ( - UniqueConstraint('unit_run_id', 'sha256', name='uq_shipping_receipt_report_files_unit_sha256'), - CheckConstraint("file_size >= 0", name='ck_shipping_receipt_report_files_size'), - Index('ix_shipping_receipt_report_files_unit', 'unit_run_id'), - Index('ix_shipping_receipt_report_files_expires', 'archive_expires_at', 'archive_deleted_at'), - ) - - id: Mapped[int] = mapped_column(primary_key=True) - unit_run_id: Mapped[int] = mapped_column(ForeignKey('shipping_receipt_rpa_unit_runs.id'), nullable=False, index=True) - storage_provider: Mapped[str] = mapped_column(String(32), nullable=False) - storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False) - storage_key: Mapped[str] = mapped_column(String(1024), nullable=False) - original_filename: Mapped[str] = mapped_column(String(255), nullable=False) - content_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) - file_size: Mapped[int] = mapped_column(Integer, nullable=False) - sha256: Mapped[str] = mapped_column(String(64), nullable=False) - # 解析失败分层标记:归档文件解析失败时写入;三者全空=未失败/已清除。 - parse_failed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) - parse_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - parse_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) - archive_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) - archive_deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) - archive_delete_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) - created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) - - unit_run: Mapped[ShippingReceiptRpaUnitRun] = relationship(back_populates='files') - deliveries: Mapped[list['ShippingReceiptNotificationDelivery']] = relationship( - back_populates='report_file', cascade='all, delete-orphan', - ) - - -class ShippingReceiptNotificationDelivery(Base): - """收料文件或汇总企微消息的幂等投递事实,响应仅保存脱敏摘要。""" - - __tablename__ = 'shipping_receipt_notification_deliveries' - __table_args__ = ( - UniqueConstraint('idempotency_key', name='uq_shipping_receipt_notification_deliveries_idempotency'), - CheckConstraint("message_type IN ('file', 'summary')", name='ck_shipping_receipt_notification_deliveries_type'), - CheckConstraint( - "status IN ('pending', 'sending', 'success', 'failed')", - name='ck_shipping_receipt_notification_deliveries_status', - ), - Index('ix_shipping_receipt_delivery_file_recipient', 'report_file_id', 'recipient_user_id'), - Index('ix_shipping_receipt_delivery_unit_created', 'unit_run_id', 'created_at'), - ) - - id: Mapped[int] = mapped_column(primary_key=True) - unit_run_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_receipt_rpa_unit_runs.id'), nullable=True, index=True, - ) - report_file_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_receipt_report_files.id'), nullable=True, index=True, - ) - recipient_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True) - message_type: Mapped[str] = mapped_column(String(16), nullable=False) - idempotency_key: Mapped[str] = mapped_column(String(255), nullable=False) - status: Mapped[str] = mapped_column(String(16), nullable=False, default='pending', server_default='pending') - response_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) - error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) - error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True) - sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) - created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) - updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) - - unit_run: Mapped[Optional[ShippingReceiptRpaUnitRun]] = relationship(foreign_keys=[unit_run_id]) - report_file: Mapped[Optional[ShippingReceiptReportFile]] = relationship(back_populates='deliveries') diff --git a/backend/app/models/shipping_temporary_inventory.py b/backend/app/models/shipping_temporary_onhand.py similarity index 90% rename from backend/app/models/shipping_temporary_inventory.py rename to backend/app/models/shipping_temporary_onhand.py index 3ad02321..cf0ccdd4 100644 --- a/backend/app/models/shipping_temporary_inventory.py +++ b/backend/app/models/shipping_temporary_onhand.py @@ -1,8 +1,8 @@ """ -models/shipping_temporary_inventory.py +models/shipping_temporary_onhand.py 用途:定义对话上传库存文件的临时会话,隔离其分析、确认与后续任务挂接过程。 -依赖:Base、FileAsset、ChatSession、ShippingNotice(shipping_notices)、库存结构分析记录。 +依赖:Base、FileAsset、ChatSession、ShippingNotice(shipping_notices)、freight_rpa_onhand_structure_analyses。 逻辑:Dify Tool 与工作台均先创建本会话,再由后端对受控文件资产进行结构初检; co8e9f0a1b2c 已删除 batch_id;会话仅可关联 task_id; 本表不代表库存站点配置,也不代表生产库存快照。 @@ -19,12 +19,12 @@ from sqlalchemy.orm import Mapped, mapped_column from app.models.base import Base -class ShippingTemporaryInventorySession(Base): +class ShippingTemporaryOnhandSession(Base): """对话上传库存候选文件的短生命周期会话;禁止直接成为生产库存来源。""" - __tablename__ = 'shipping_temporary_inventory_sessions' + __tablename__ = 'shipping_temporary_onhand_sessions' __table_args__ = ( - UniqueConstraint('session_no', name='uq_shipping_temporary_inventory_sessions_no'), + UniqueConstraint('session_no', name='uq_shipping_temporary_onhand_sessions_no'), Index('ix_shipping_temp_inventory_user_created', 'user_id', 'created_at'), Index('ix_shipping_temp_inventory_conversation_created', 'conversation_id', 'created_at'), Index('ix_shipping_temp_inventory_asset', 'asset_id'), @@ -37,7 +37,7 @@ class ShippingTemporaryInventorySession(Base): conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True) asset_id: Mapped[int] = mapped_column(ForeignKey('file_assets.id'), nullable=False, index=True) analysis_id: Mapped[Optional[int]] = mapped_column( - ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True, index=True, + ForeignKey('freight_rpa_onhand_structure_analyses.id'), nullable=True, index=True, ) task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True, index=True) declared_intent: Mapped[str] = mapped_column(String(32), nullable=False, default='inventory_candidate') diff --git a/backend/app/services/admin/freight_rpa_form_utils.py b/backend/app/services/admin/freight_rpa_form_utils.py new file mode 100644 index 00000000..dfbbec15 --- /dev/null +++ b/backend/app/services/admin/freight_rpa_form_utils.py @@ -0,0 +1,105 @@ +""" +services/admin/freight_rpa_form_utils.py + +用途:货代 RPA 管理端表单校验共用件(JSON 对象、报表路径、查询条件、时间序列化)。 +依赖:app.core.errors.ValidationError。 +逻辑:freight_rpa_source_admin_service(站点/连接)与 freight_rpa_report_config_service + (入站/出站报表配置)共用;错误码沿用历史 SHIPPING.ONHAND_SOURCE_CONFIG_INVALID, + 调用方可按域 remap。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from app.core.errors import ValidationError + + +def json_object(data: dict[str, Any], field: str) -> dict[str, Any]: + """读取并复制对象型 JSON 配置。 + + Args: + data: 管理 API 的请求载荷。 + field: 只允许 JSON object 的字段名。 + + Returns: + 空值规范化为空对象后的可写入配置。 + + Raises: + ValidationError: 字段不是 JSON object。 + """ + value = data.get(field, {}) + if not isinstance(value, dict): + raise ValidationError(f'{field} must be an object', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID') + return dict(value) + + +def validate_report_path(connector_type: str, report_path: dict[str, Any]) -> dict[str, str]: + """校验 DBS 四级报表路径,防止技术选择器混入业务配置。""" + allowed = {'program_group', 'program_label', 'report_group', 'report_name'} + if set(report_path) - allowed: + raise ValidationError('report_path_json contains unsupported fields', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID') + normalized = {key: str(value or '').strip() for key, value in report_path.items()} + if connector_type == 'dbs': + missing = [key for key in allowed if not normalized.get(key)] + if missing: + raise ValidationError( + 'DBS inventory source requires a complete report path', + code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID', details={'missing': sorted(missing)}, + ) + elif normalized: + raise ValidationError( + 'Only DBS inventory sources can define report_path_json', + code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID', + ) + return {key: normalized[key] for key in allowed if normalized.get(key)} + + +def validate_query_parameters(data: dict[str, Any]) -> list[dict[str, Any]]: + """校验 Source 的可视化查询参数列表,禁止保存 selector 等 Driver 实现细节。""" + raw = data.get('query_parameters_json', []) + if not isinstance(raw, list): + raise ValidationError('query_parameters_json must be a list', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID') + result: list[dict[str, Any]] = [] + seen_names: set[str] = set() + allowed = {'name', 'mode', 'values', 'required', 'select_all', 'joiner'} + for index, item in enumerate(raw): + if not isinstance(item, dict) or set(item) - allowed: + raise ValidationError( + 'query parameter contains unsupported fields', + code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID', details={'index': index}, + ) + name = str(item.get('name') or '').strip() + mode = str(item.get('mode') or 'single').strip().lower() + values = item.get('values', []) + required = item.get('required', False) + select_all = item.get('select_all', False) + if not name or name.lower() in seen_names or mode not in {'single', 'multi_text', 'multi_select'}: + raise ValidationError('query parameter name or mode is invalid', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID') + if not isinstance(values, list) or any(not isinstance(value, str) for value in values): + raise ValidationError('query parameter values must be a string list', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID') + if not isinstance(required, bool) or not isinstance(select_all, bool): + raise ValidationError('query parameter flags must be boolean', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID') + normalized_values = [value.strip() for value in values if value.strip()] + if required and not normalized_values and not select_all: + raise ValidationError('required query parameter needs values or select_all', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID') + if select_all and mode != 'multi_select': + raise ValidationError('select_all only applies to multi_select', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID') + parameter: dict[str, Any] = { + 'name': name, 'mode': mode, 'values': normalized_values, + 'required': required, 'select_all': select_all, + } + if mode == 'multi_text': + joiner = str(item.get('joiner') or ',').strip() + if not joiner: + raise ValidationError('multi_text query parameter needs joiner', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID') + parameter['joiner'] = joiner + seen_names.add(name.lower()) + result.append(parameter) + return result + + +def iso(value: datetime | None) -> str | None: + """datetime → ISO 字符串;None 保持 None。""" + return value.isoformat() if value else None diff --git a/backend/app/services/admin/freight_rpa_report_config_service.py b/backend/app/services/admin/freight_rpa_report_config_service.py new file mode 100644 index 00000000..ca8a9fd5 --- /dev/null +++ b/backend/app/services/admin/freight_rpa_report_config_service.py @@ -0,0 +1,224 @@ +""" +services/admin/freight_rpa_report_config_service.py + +用途:货代 RPA 入站 / 出站报表配置管理(GET/PUT),与在手配置解耦。 +依赖:db、FreightRpaSource / FreightRpaInboundReportConfig / FreightRpaOutboundReportConfig / + FreightRpaParsingProfile、freight_rpa_form_utils、shipping_notice.audit_service。 +逻辑:admin_freight_rpa 蓝图委托本服务;不进入来源站点启用硬门槛; + 解析绑定须 published 且 purpose 匹配 inbound/outbound。 +""" + +from __future__ import annotations + +from typing import Any + +from app.core.errors import NotFoundError, ValidationError +from app.extensions import db +from app.models import ( + FreightRpaInboundReportConfig, + FreightRpaOutboundReportConfig, + FreightRpaParsingProfile, + FreightRpaSource, +) +from app.services.admin.freight_rpa_form_utils import iso, json_object, validate_query_parameters, validate_report_path +from app.services.shipping_notice.audit_service import append_shipping_audit_event + + +def _inbound_report_config_payload(config: FreightRpaInboundReportConfig) -> dict[str, Any]: + """序列化独立入站配置,禁止把库存路径或凭据透传至管理端。""" + profile = config.parsing_profile + return { + 'id': config.id, 'source_id': config.source_id, + 'report_path_json': config.report_path_json or {}, + 'query_parameters_json': config.query_parameters_json or [], + 'parsing_profile_id': config.parsing_profile_id, + 'parsing_profile': ({ + 'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name, + 'version': profile.version, 'status': profile.status, + } if profile else None), + 'config_version': config.config_version, + 'created_at': iso(config.created_at), 'updated_at': iso(config.updated_at), + } + + +def _outbound_report_config_payload(config: FreightRpaOutboundReportConfig) -> dict[str, Any]: + """序列化独立出站配置,禁止把库存/入站路径或凭据透传至管理端。""" + profile = config.parsing_profile + return { + 'id': config.id, 'source_id': config.source_id, + 'report_path_json': config.report_path_json or {}, + 'query_parameters_json': config.query_parameters_json or [], + 'parsing_profile_id': config.parsing_profile_id, + 'parsing_profile': ({ + 'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name, + 'version': profile.version, 'status': profile.status, + } if profile else None), + 'config_version': config.config_version, + 'created_at': iso(config.created_at), 'updated_at': iso(config.updated_at), + } + + +def _validate_inbound_profile_binding(profile_id: Any) -> int | None: + """校验入站配置绑定的解析规则:必须已发布且 purpose='inbound';空值表示解绑。""" + if profile_id is None or str(profile_id).strip() == '': + return None + profile = db.session.get(FreightRpaParsingProfile, int(profile_id)) + if profile is None or profile.status != 'published' or profile.purpose != 'inbound': + raise ValidationError( + 'Inbound parsing profile must be published with purpose inbound', + code='SHIPPING.INBOUND_PROFILE_INVALID', + ) + return profile.id + + +def _validate_outbound_profile_binding(profile_id: Any) -> int | None: + """校验出站配置绑定的解析规则:必须已发布且 purpose='outbound';空值表示解绑。""" + if profile_id is None or str(profile_id).strip() == '': + return None + profile = db.session.get(FreightRpaParsingProfile, int(profile_id)) + if profile is None or profile.status != 'published' or profile.purpose != 'outbound': + raise ValidationError( + 'Outbound parsing profile must be published with purpose outbound', + code='SHIPPING.OUTBOUND_PROFILE_INVALID', + ) + return profile.id + + +def _validate_inbound_report_config( + source: FreightRpaSource, data: dict[str, Any], +) -> tuple[dict[str, str], list[dict[str, Any]]]: + """规范入站配置:路径+查询条件;日期禁填。""" + try: + parameters = validate_query_parameters(data) + except ValidationError as exc: + raise ValidationError(str(exc), code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID') from exc + if any('date' in str(item.get('name') or '').strip().lower() for item in parameters): + raise ValidationError('Inbound report date filtering is not supported', code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID') + raw_path = json_object(data, 'report_path_json') + if source.connector_type == 'dbs': + try: + path = validate_report_path('dbs', raw_path) + except ValidationError as exc: + raise ValidationError(str(exc), code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID') from exc + return path, parameters + if source.connector_type == 'crane': + if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Inbound Details'): + raise ValidationError('Crane inbound report is fixed to Inbound Details', code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID') + if parameters: + raise ValidationError( + 'Crane inbound report does not support query parameters', + code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID', + ) + return {'report_name': 'Inbound Details'}, [] + raise ValidationError('Unsupported inbound connector type', code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID') + + +def _validate_outbound_report_config( + source: FreightRpaSource, data: dict[str, Any], +) -> tuple[dict[str, str], list[dict[str, Any]]]: + """规范出站配置:路径+查询条件;日期禁填;Crane 固定 Outbound Details。""" + try: + parameters = validate_query_parameters(data) + except ValidationError as exc: + raise ValidationError(str(exc), code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID') from exc + if any('date' in str(item.get('name') or '').strip().lower() for item in parameters): + raise ValidationError('Outbound report date filtering is not supported', code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID') + raw_path = json_object(data, 'report_path_json') + if source.connector_type == 'dbs': + try: + path = validate_report_path('dbs', raw_path) + except ValidationError as exc: + raise ValidationError(str(exc), code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID') from exc + return path, parameters + if source.connector_type == 'crane': + if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Outbound Details'): + raise ValidationError('Crane outbound report is fixed to Outbound Details', code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID') + if parameters: + raise ValidationError( + 'Crane outbound report does not support query parameters', + code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID', + ) + return {'report_name': 'Outbound Details'}, [] + raise ValidationError('Unsupported outbound connector type', code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID') + + +def get_inbound_report_config(source_id: int) -> dict[str, Any] | None: + """读取站点的入站配置;不存在时返回空。""" + source = db.session.get(FreightRpaSource, source_id) + if source is None: + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') + config = FreightRpaInboundReportConfig.query.filter_by(source_id=source.id).one_or_none() + return _inbound_report_config_payload(config) if config else None + + +def save_inbound_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: + """保存站点内独立入站配置并追加配置前后快照审计。""" + source = db.session.get(FreightRpaSource, source_id) + if source is None: + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') + path, parameters = _validate_inbound_report_config(source, data) + config = FreightRpaInboundReportConfig.query.filter_by(source_id=source.id).one_or_none() + before = _inbound_report_config_payload(config) if config else None + is_new = config is None + if config is None: + config = FreightRpaInboundReportConfig(source_id=source.id) + config.created_by = actor_id + db.session.add(config) + else: + config.config_version += 1 + config.report_path_json = path + config.query_parameters_json = parameters + config.parsing_profile_id = _validate_inbound_profile_binding(data.get('parsing_profile_id')) + config.updated_by = actor_id + db.session.flush() + after = _inbound_report_config_payload(config) + append_shipping_audit_event( + event_type='shipping_inbound_report_config_saved', aggregate_type='shipping_inbound_report_config', + aggregate_id=str(source.id), actor_type='admin', actor_id=actor_id, action='create' if is_new else 'update', + result='success', before=before, after=after, + metadata={'source_id': source.id, 'connector_type': source.connector_type, + 'parsing_profile_id': config.parsing_profile_id}, + ) + db.session.commit() + return after + + +def get_outbound_report_config(source_id: int) -> dict[str, Any] | None: + """读取站点的出站配置;不存在时返回空。""" + source = db.session.get(FreightRpaSource, source_id) + if source is None: + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') + config = FreightRpaOutboundReportConfig.query.filter_by(source_id=source.id).one_or_none() + return _outbound_report_config_payload(config) if config else None + + +def save_outbound_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: + """保存站点内独立出站配置并追加配置前后快照审计。""" + source = db.session.get(FreightRpaSource, source_id) + if source is None: + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') + path, parameters = _validate_outbound_report_config(source, data) + config = FreightRpaOutboundReportConfig.query.filter_by(source_id=source.id).one_or_none() + before = _outbound_report_config_payload(config) if config else None + is_new = config is None + if config is None: + config = FreightRpaOutboundReportConfig(source_id=source.id) + config.created_by = actor_id + db.session.add(config) + else: + config.config_version += 1 + config.report_path_json = path + config.query_parameters_json = parameters + config.parsing_profile_id = _validate_outbound_profile_binding(data.get('parsing_profile_id')) + config.updated_by = actor_id + db.session.flush() + after = _outbound_report_config_payload(config) + append_shipping_audit_event( + event_type='shipping_outbound_report_config_saved', aggregate_type='shipping_outbound_report_config', + aggregate_id=str(source.id), actor_type='admin', actor_id=actor_id, action='create' if is_new else 'update', + result='success', before=before, after=after, + metadata={'source_id': source.id, 'connector_type': source.connector_type, + 'parsing_profile_id': config.parsing_profile_id}, + ) + db.session.commit() + return after diff --git a/backend/app/services/admin/freight_rpa_source_admin_service.py b/backend/app/services/admin/freight_rpa_source_admin_service.py new file mode 100644 index 00000000..8f58e135 --- /dev/null +++ b/backend/app/services/admin/freight_rpa_source_admin_service.py @@ -0,0 +1,702 @@ +""" +services/admin/freight_rpa_source_admin_service.py + +用途:货代 RPA 共用主数据管理——登录连接(FreightRpaProfile)与来源站点(FreightRpaSource), + 含站点启用门禁、在手配置行写入、解析绑定审计。 +依赖:db、FreightRpaProfile / FreightRpaSource / FreightRpaOnhandReportConfig、 + freight_rpa_form_utils、credential_crypto、parsing_profile、upload_config_validation、 + onhand_source_repository.validate_source_profile、audit_service。 +逻辑:admin_freight_rpa 蓝图的 rpa-profiles / sources / bind-parsing / activate 委托本服务; + 在手快照/路由规则/外部映射仍见 shipping_onhand_admin_service。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.extensions import db +from app.models import ( + FreightRpaOnhandExternalMapping, + FreightRpaOnhandReportConfig, + FreightRpaOnhandReportFile, + FreightRpaOnhandRoutingRule, + FreightRpaParsingProfile, + FreightRpaProfile, + FreightRpaSource, + FreightRpaSourceParsingBindingAudit, + ScheduleRun, + ShippingExcelTemplate, + ShippingNoticeLine, + ShippingNoticeLineOnhandMatch, +) +from app.services.admin.freight_rpa_form_utils import ( + iso as _iso, + json_object as _json_object, + validate_query_parameters as _validate_query_parameters, + validate_report_path as _validate_report_path, +) +from app.services.freight_rpa import parsing_profile as onhand_parsing_profile +from app.services.freight_rpa.common.credential_crypto import encrypt_credential +from app.services.shipping_notice.audit_service import append_shipping_audit_event +from app.services.shipping_notice.onhand_source_repository import validate_source_profile +from app.services.shipping_notice.upload_config_validation import validate_upload_config + + +def _text(data: dict[str, Any], field: str, *, required: bool = False) -> str | None: + """读取并清洗字符串表单字段。""" + value = str(data.get(field) or '').strip() + if required and not value: + raise ValidationError(f'{field} is required', code='VALIDATION.INVALID_PARAM', details={'field': field}) + return value or None + + +def _bool(data: dict[str, Any], field: str, default: bool = True) -> bool: + """读取布尔表单字段。""" + value = data.get(field, default) + if not isinstance(value, bool): + raise ValidationError(f'{field} must be a boolean', details={'field': field}) + return value + + + +def _validate_profile_login_config(data: dict[str, Any]) -> dict[str, str]: + """校验连接级登录配置,不接收页面选择器或报表操作字段。""" + value = data.get('login_config_json', {}) + if not isinstance(value, dict) or set(value) - {'auth_mode'}: + raise ValidationError('login_config_json is invalid', code='SHIPPING.RPA_PROFILE_CONFIG_INVALID') + auth_mode = str(value.get('auth_mode') or 'password').strip().lower() + if auth_mode != 'password': + raise ValidationError( + 'Only password authentication is currently supported', + code='SHIPPING.RPA_PROFILE_CONFIG_INVALID', + ) + return {'auth_mode': auth_mode} + + + + +def _profile_payload(profile: FreightRpaProfile) -> dict[str, Any]: + return { + 'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name, + 'connector_type': profile.connector_type, 'login_url': profile.login_url, + 'login_config_json': profile.login_config_json or {'auth_mode': 'password'}, 'enabled': bool(profile.enabled), + 'upload_config_json': profile.upload_config_json, + 'config_version': profile.config_version, 'username_masked': _mask(profile.username_ciphertext), + 'password_configured': bool(profile.password_ciphertext), 'credential_updated_at': _iso(profile.credential_updated_at), + 'created_at': _iso(profile.created_at), 'updated_at': _iso(profile.updated_at), + } + + +def _mask(ciphertext: str | None) -> str | None: + """凭据密文不支持反向展示;仅以配置状态提示管理员。""" + return 'configured' if ciphertext else None + + + + +def list_profiles() -> list[dict[str, Any]]: + """列出 Profile 元数据,不返回可恢复的凭据。""" + return [_profile_payload(item) for item in FreightRpaProfile.query.order_by(FreightRpaProfile.profile_code).all()] + + +def delete_profile(profile_id: int) -> None: + """删除未绑定库存源的错误连接配置,保留已使用连接的可追溯性。""" + profile = db.session.get(FreightRpaProfile, profile_id) + if profile is None: + raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND') + if FreightRpaSource.query.filter_by(rpa_profile_id=profile.id).count(): + raise ConflictError('RPA Profile is referenced by inventory sources', code='SHIPPING.RPA_PROFILE_DELETE_BLOCKED') + db.session.delete(profile) + db.session.commit() + + +def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]: + """创建或更新货代登录连接;密码留空表示保留既有密文。""" + profile = db.session.get(FreightRpaProfile, profile_id) if profile_id else None + if profile_id and profile is None: + raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND') + profile = profile or FreightRpaProfile(profile_code='', display_name='', connector_type='', login_url='', login_config_json={}) + # 记录“非 upload_config”的既有运行时配置快照:仅当这些字段变化才递增 config_version, + # upload_config_json 属于连接上传配置,变更不得误判库存 RPA 配置测试过期。 + prev_non_upload = ( + profile.profile_code, profile.display_name, profile.connector_type, profile.login_url, + dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled), + bool(profile.username_ciphertext), bool(profile.password_ciphertext), + ) if profile_id else None + profile.profile_code = str(_text(data, 'profile_code', required=True)).upper() + profile.display_name = str(_text(data, 'display_name', required=True)) + profile.connector_type = str(_text(data, 'connector_type', required=True)).lower() + profile.login_url = str(_text(data, 'login_url', required=True)) + profile.login_config_json = _validate_profile_login_config(data) + profile.enabled = _bool(data, 'enabled', bool(profile.enabled) if profile_id else True) + if not profile.enabled and any(source.enabled for source in profile.sources): + raise ConflictError( + 'Disable inventory sources before disabling their RPA Profile', + code='SHIPPING.RPA_PROFILE_DISABLE_BLOCKED', + ) + username = _text(data, 'username') + password = _text(data, 'password') + if username is not None: + profile.username_ciphertext = encrypt_credential(username) + if password is not None: + profile.password_ciphertext = encrypt_credential(password) + if username is not None or password is not None: + profile.credential_updated_at = datetime.utcnow() + # 连接级受控上传配置(受限 JSON);与库存 RPA 运行期配置隔离,不参与 config_version。 + if 'upload_config_json' in data: + profile.upload_config_json = validate_upload_config(profile.connector_type, data.get('upload_config_json')) + profile.updated_by = actor_id + if profile_id: + now_non_upload = ( + profile.profile_code, profile.display_name, profile.connector_type, profile.login_url, + dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled), + bool(profile.username_ciphertext), bool(profile.password_ciphertext), + ) + if now_non_upload != prev_non_upload: + profile.config_version += 1 + if not profile_id: + profile.created_by = actor_id + db.session.add(profile) + try: + db.session.commit() + except Exception as exc: + db.session.rollback() + raise ConflictError('RPA Profile code already exists', code='SHIPPING.RPA_PROFILE_CONFLICT') from exc + return _profile_payload(profile) + + +def _onhand_report_config_payload(config: FreightRpaOnhandReportConfig) -> dict[str, Any]: + """序列化站点一对一在手报表配置行,不透传解析方案定义。""" + return { + 'id': config.id, + 'report_path_json': config.report_path_json or {}, + 'query_parameters_json': config.query_parameters_json or [], + 'parsing_profile_id': config.parsing_profile_id, + } + + +def _source_payload(source: FreightRpaSource) -> dict[str, Any]: + """序列化库存站点及其是否满足正式启用前置条件。 + + s18 起报表路径/查询条件/解析方案绑定不再随站点 DTO 平铺, + 改挂在 ``onhand_report_config`` 嵌套对象(配置行不存在时为 null)。 + """ + return { + 'id': source.id, 'source_code': source.source_code, 'display_name': source.display_name, + 'connector_type': source.connector_type, 'rpa_profile_id': source.rpa_profile_id, + 'excel_template_id': source.excel_template_id, + 'warehouse_resolution_mode': source.warehouse_resolution_mode, 'fixed_warehouse_id': source.fixed_warehouse_id, + 'onhand_report_config': ( + _onhand_report_config_payload(source.onhand_report_config) + if source.onhand_report_config is not None else None + ), + 'snapshot_ttl_seconds': source.snapshot_ttl_seconds, 'enabled': bool(source.enabled), + 'config_version': source.config_version, 'created_at': _iso(source.created_at), 'updated_at': _iso(source.updated_at), + 'activation': get_source_activation_status(source), + } + + +def _validate_onhand_profile_binding(profile_id: Any) -> int | None: + """校验在手配置绑定的解析方案:必须已发布且 purpose='onhand';空值/0 表示解绑。 + + Args: + profile_id: 请求载荷中的 parsing_profile_id;None/空串/0 视为解绑(与旧站点保存语义一致)。 + + Returns: + int | None: 规整后的方案 id 或 None。 + + Raises: + ValidationError: 方案 id 非法、不存在、未发布或用途不是 onhand + (fail-closed,防误绑入站/出站方案,统一 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED)。 + """ + raw = str(profile_id).strip() if profile_id is not None else '' + if raw in {'', '0'}: + return None + if not raw.isdigit(): + raise ValidationError( + 'Onhand parsing profile must be published with purpose onhand', + code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED', + ) + profile = db.session.get(FreightRpaParsingProfile, int(raw)) + if profile is None or profile.status != 'published' or profile.purpose != 'onhand': + raise ValidationError( + 'Onhand parsing profile must be published with purpose onhand', + code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED', + ) + return profile.id + + +def _apply_onhand_report_config( + source: FreightRpaSource, data: dict[str, Any], *, actor_id: int | None, +) -> FreightRpaOnhandReportConfig: + """把手报表三字段写入手配置行(无则插入),不触碰站点行已删除的三列。 + + 核心逻辑:先全量校验路径对象/查询条件/解析绑定,失败时不留脏会话; + 校验通过后无配置行则插入(created_by=actor),有则更新并递增 config_version。 + 报表路径按原样 JSON object 存取(Driver selector 等实现细节归 Worker/模板域, + 管理端 DBS 四段路径由前端 normaliseInventoryReportPath 规整后提交)。 + + Args: + source: 已存在的库存站点(新配置行经 inventory_source 关系级联挂载)。 + data: 含 report_path_json / query_parameters_json / parsing_profile_id 的载荷。 + actor_id: 当前管理员主键,仅写审计字段。 + + Returns: + FreightRpaOnhandReportConfig: 已写入(尚未提交)的配置行。 + """ + # [STEP 1] 全量校验先行,任何失败都不会留下半写的配置行。 + report_path = _json_object(data, 'report_path_json') + # DBS 四段路径按原样 JSON object 存取(前端 normaliseInventoryReportPath 规整); + # 非 DBS(Crane)站点不得误填 DBS 报表路径(fail-closed,与列搬迁前契约一致)。 + if source.connector_type != 'dbs' and report_path: + raise ValidationError( + 'Only DBS inventory sources can define report_path_json', + code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID', + ) + parameters = _validate_query_parameters(data) + parsing_profile_id = _validate_onhand_profile_binding(data.get('parsing_profile_id')) + # [STEP 2] 校验通过后写配置行:无则插入,有则更新并递增 config_version。 + config = source.onhand_report_config + if config is None: + config = FreightRpaOnhandReportConfig(source=source) + config.created_by = actor_id + db.session.add(config) + else: + config.config_version += 1 + config.report_path_json = report_path + config.query_parameters_json = parameters + config.parsing_profile_id = parsing_profile_id + config.updated_by = actor_id + return config + + +def save_onhand_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: + """保存站点一对一在手报表配置:没有配置行时插入,有则更新并递增该行 config_version。 + + 核心逻辑:委托 _apply_onhand_report_config 校验并写行;启用中的站点借保存拆掉 + 启用门禁(缺解析绑定/模板)时由 assert_onhand_source_can_enable fail-closed 拒绝。 + + Args: + source_id: 库存站点主键,必须已存在。 + data: 含 report_path_json / query_parameters_json / parsing_profile_id 的载荷。 + actor_id: 当前管理员主键,仅写审计字段。 + + Returns: + dict[str, Any]: 配置行 DTO(id / report_path_json / query_parameters_json / parsing_profile_id)。 + + Raises: + NotFoundError: 站点不存在。 + ValidationError: 解析方案不存在/未发布/purpose 不是 onhand,或启用中站点门禁被拆。 + """ + source = db.session.get(FreightRpaSource, source_id) + if source is None: + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') + config = _apply_onhand_report_config(source, data, actor_id=actor_id) + # 启用中的站点不得借配置保存解绑解析方案(excel_template 缺失同样拒绝)。 + assert_onhand_source_can_enable(source) + db.session.commit() + return _onhand_report_config_payload(config) + + +def assert_onhand_source_can_enable(source: FreightRpaSource) -> None: + """启用中的库存站点必须已有在手配置行(含解析方案绑定)与发货模板。 + + 【AI 触发时机】:保存站点(save_source 载荷含 enabled=true 或保留启用态)、 + 保存在手配置(save_onhand_report_config 拆绑定前)时调用; + PostgreSQL CHECK 不能跨表,解析方案存在性只能由服务层执行。 + + Args: + source: 站点对象(可为未提交的暂态行,配置行经 onhand_report_config 关系读取)。 + + Returns: + None: 门禁通过(站点未启用时恒通过)。 + + Raises: + ValidationError: enabled 为真但缺配置行、配置行未绑解析方案或站点未绑模板, + 统一 code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED'。 + """ + if not source.enabled: + return + config = source.onhand_report_config + if config is None or not config.parsing_profile_id or not source.excel_template_id: + raise ValidationError( + 'Enabled inventory source requires onhand report config, parsing profile and excel template', + code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED', + ) + + +def _binding_snapshot(source: FreightRpaSource) -> dict[str, Any]: + """冻结解析绑定变更的最小站点上下文,避免审计依赖后续可变主数据。 + + s18 起解析绑定挂在 onhand_report_config 配置行上,快照同样取自配置行。 + """ + config = source.onhand_report_config + return { + 'source_id': source.id, + 'source_code': source.source_code, + 'enabled': bool(source.enabled), + 'parsing_profile_id': config.parsing_profile_id if config is not None else None, + 'parsing_profile_checksum': ( + config.parsing_profile.checksum + if config is not None and config.parsing_profile is not None else None + ), + 'excel_template_id': source.excel_template_id, + 'config_version': source.config_version, + } + + +def _validate_source_parsing_binding(source: FreightRpaSource, profile: FreightRpaParsingProfile) -> None: + """校验站点可直接采用的已发布方案与当前发货模板字段契约;启用中的站点同样允许更换解析绑定。""" + if profile.status != 'published': + raise ValidationError('Published parsing profile is required', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED') + definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} + mapping = definition.get('field_mapping') if isinstance(definition.get('field_mapping'), dict) else {} + if not mapping: + raise ValidationError('Published parsing profile is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED') + template = source.excel_template + if template is None: + return + if template.status != 'published': + raise ValidationError('Published excel template is required', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED') + template_definition = template.definition_json if isinstance(template.definition_json, dict) else {} + template_mappings = template_definition.get('mappings') if isinstance(template_definition.get('mappings'), list) else [] + missing_fields = sorted({ + str(item.get('source_key') or '') + for item in template_mappings + if isinstance(item, dict) + and item.get('source_kind') == 'inventory_field' + and str(item.get('source_key') or '') not in mapping + }) + if missing_fields: + raise ValidationError( + 'Parsing profile does not provide all inventory fields required by the excel template', + code='SHIPPING.ONHAND_SOURCE_BINDING_TEMPLATE_INVALID', details={'inventory_field_ids': missing_fields}, + ) + + +def bind_source_parsing_profile( + source_ids: list[int], profile_id: int, *, actor_id: int | None, reason: str | None = None, operation: str, +) -> list[dict[str, Any]]: + """为一个或多个库存站点原子绑定已发布解析方案并写入追加式审计(含已启用站点)。 + + Args: + source_ids: 待绑定的库存站点主键,不能为空且不得重复。 + profile_id: 必须为已发布解析方案主键。 + actor_id: 当前管理员主键,仅写入审计。 + reason: 可选的补充说明;未填写时由系统记录本次直接或批量绑定动作。 + operation: 审计操作类型,仅允许 ``direct`` 或 ``bulk``。 + + Returns: + list[dict[str, Any]]: 已更新站点的管理端 DTO。 + + Raises: + ValidationError: 任一站点、方案或模板字段契约不合法;批量请求不会部分写入。 + ConflictError: 试图变更已启用站点的正式解析方案。 + """ + try: + normalized_ids = sorted({int(item) for item in source_ids if int(item) > 0}) + except (TypeError, ValueError) as exc: + raise ValidationError('source_ids must be a non-empty unique integer list', code='VALIDATION.INVALID_PARAM') from exc + if not normalized_ids or len(normalized_ids) != len(source_ids): + raise ValidationError('source_ids must be a non-empty unique integer list', code='VALIDATION.INVALID_PARAM') + if operation not in {'direct', 'bulk'}: + raise ValidationError('Binding operation is invalid', code='VALIDATION.INVALID_PARAM') + normalized_reason = str(reason or '').strip() + if len(normalized_reason) > 500: + raise ValidationError('Binding note must not exceed 500 characters', code='VALIDATION.INVALID_PARAM') + # 审计必须保留可读动作,但不应把技术审计字段变成管理员的额外填写负担。 + if not normalized_reason: + normalized_reason = '管理员直接绑定已发布解析方案' if operation == 'direct' else '管理员批量绑定已发布解析方案' + try: + normalized_profile_id = int(profile_id) + except (TypeError, ValueError) as exc: + raise ValidationError('parsing_profile_id is required', code='VALIDATION.INVALID_PARAM') from exc + profile = db.session.get(FreightRpaParsingProfile, normalized_profile_id) + if profile is None: + raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND') + sources = [db.session.get(FreightRpaSource, source_id) for source_id in normalized_ids] + if any(source is None for source in sources): + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') + typed_sources = [source for source in sources if source is not None] + # [STEP 1] 全量预检后才变更,避免多站点操作出现部分绑定。 + for source in typed_sources: + _validate_source_parsing_binding(source, profile) + for source in typed_sources: + before = _binding_snapshot(source) + # s18 起解析绑定写 onhand_report_config 配置行(无则插入),站点行不再承载该外键。 + config = source.onhand_report_config + previous_profile_id = config.parsing_profile_id if config is not None else None + if config is None: + config = FreightRpaOnhandReportConfig(source=source) + config.created_by = actor_id + db.session.add(config) + else: + config.config_version += 1 + config.parsing_profile_id = profile.id + config.updated_by = actor_id + source.updated_by = actor_id + # 站点 config_version 仍随绑定递增:配置测试锁定版本与运行期失效判断依赖它。 + source.config_version += 1 + db.session.flush() + db.session.add(FreightRpaSourceParsingBindingAudit( + source_id=source.id, previous_parsing_profile_id=previous_profile_id, + parsing_profile_id=config.parsing_profile_id, operation=operation, reason=normalized_reason, actor_id=actor_id, + source_config_version_before=before['config_version'], source_config_version_after=source.config_version, + before_snapshot_json=before, after_snapshot_json=_binding_snapshot(source), + )) + db.session.commit() + return [_source_payload(source) for source in typed_sources] + + +def get_source_parsing_binding_audits(source_id: int) -> list[dict[str, Any]]: + """读取库存站点解析绑定审计,仅返回配置快照和操作者标识。""" + if db.session.get(FreightRpaSource, source_id) is None: + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') + rows = FreightRpaSourceParsingBindingAudit.query.filter_by( + source_id=source_id, + ).order_by(FreightRpaSourceParsingBindingAudit.id.desc()).all() + return [{ + 'id': row.id, 'operation': row.operation, 'reason': row.reason, 'actor_id': row.actor_id, + 'previous_parsing_profile_id': row.previous_parsing_profile_id, 'parsing_profile_id': row.parsing_profile_id, + 'source_config_version_before': row.source_config_version_before, + 'source_config_version_after': row.source_config_version_after, + 'before': row.before_snapshot_json, 'after': row.after_snapshot_json, + 'created_at': row.created_at.isoformat() if row.created_at else None, + } for row in rows] + + +def list_sources() -> list[dict[str, Any]]: + """列出库存源及其稳定业务配置。""" + return [_source_payload(item) for item in FreightRpaSource.query.order_by(FreightRpaSource.source_code).all()] + + +def delete_source(source_id: int) -> None: + """删除未参与映射、快照或规则的错误库存源,避免破坏历史路由身份。""" + source = db.session.get(FreightRpaSource, source_id) + if source is None: + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') + source_code = str(source.source_code or '').strip().upper() + has_mapping = FreightRpaOnhandExternalMapping.query.filter_by(source_id=source.id).count() > 0 + has_snapshot = FreightRpaOnhandReportFile.query.filter_by(source_code=source_code).count() > 0 + has_rule = any( + source_code in {str(code).strip().upper() for code in candidates} + for rule in FreightRpaOnhandRoutingRule.query.all() + for candidates in [(rule.action_payload_json or {}).get('source_codes', [])] + if isinstance(candidates, list) + ) + has_task = db.session.query(ShippingNoticeLine.id).filter( + ShippingNoticeLine.inventory_source_code == source_code, + ).first() is not None or db.session.query(ShippingNoticeLineOnhandMatch.id).filter( + ShippingNoticeLineOnhandMatch.source_code == source_code, + ).first() is not None + has_export_run = any( + source_code in {str(code).strip().upper() for code in source_codes} + for run in ScheduleRun.query.all() + for source_codes in [(run.api_request_json or {}).get('source_codes', [])] + if isinstance(source_codes, list) + ) + if has_mapping or has_snapshot or has_rule or has_task or has_export_run: + raise ConflictError('Inventory Source has operational references', code='SHIPPING.ONHAND_SOURCE_DELETE_BLOCKED') + db.session.delete(source) + db.session.commit() + + +def _template_validation_missing(source: FreightRpaSource) -> list[str]: + """确认发货模板引用的库存字段均由当前解析方案提供,避免启用后才发现字段断链。""" + template = source.excel_template + # s18 起解析方案绑定取自 onhand_report_config 配置行。 + config = source.onhand_report_config + profile = config.parsing_profile if config is not None else None + if template is None or profile is None: + return [] + definition = template.definition_json if isinstance(template.definition_json, dict) else {} + mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else [] + profile_definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} + inventory_fields = {str(field_id) for field_id in (profile_definition.get('field_mapping') or {}).keys()} + invalid = any( + isinstance(item, dict) + and item.get('source_kind') == 'inventory_field' + and str(item.get('source_key') or '') not in inventory_fields + for item in mappings + ) + return ['template_validation'] if not mappings or invalid else [] + + +def _activation_check( + code: str, *, passed: bool, action: str, evidence: dict[str, Any], status: str | None = None, + blocking: bool | None = None, +) -> dict[str, Any]: + """构造单项启用门禁结果,确保管理端只展示服务端已判定的业务事实。""" + return { + 'code': code, + 'status': status or ('passed' if passed else 'pending'), + 'blocking': not passed if blocking is None else blocking, + 'action': action, + 'evidence': evidence, + } + + +def _source_activation_checks(source: FreightRpaSource) -> list[dict[str, Any]]: + """构建库存站点启用硬门槛:可用连接、已发布解析方案、已绑定已发布发货模板及字段契约。 + + 测试导出不再参与启用门禁;启停由管理员显式开关完成。 + """ + profile_ready = source.rpa_profile is not None and bool(source.rpa_profile.enabled) + # s18 起解析方案绑定取自 onhand_report_config 配置行;配置行缺失即解析门禁未就绪。 + config = source.onhand_report_config + parsing_profile = config.parsing_profile if config is not None else None + parsing_ready = parsing_profile is not None and parsing_profile.status == 'published' + template_ready = source.excel_template is not None and source.excel_template.status == 'published' + template_invalid = bool(_template_validation_missing(source)) if template_ready and parsing_ready else False + return [ + _activation_check( + 'rpa_profile', passed=profile_ready, action='configure_connection', + evidence={'profile_id': source.rpa_profile_id, 'enabled': profile_ready}, + ), + _activation_check( + 'parsing_profile', passed=parsing_ready, action='configure_parsing_profile', + evidence={'profile_id': parsing_profile.id if parsing_profile is not None else None, 'published': parsing_ready}, + ), + _activation_check( + 'excel_template', passed=template_ready, action='configure_excel_template', + evidence={'template_id': source.excel_template_id, 'published': template_ready}, + ), + _activation_check( + 'template_validation', passed=not template_invalid, + action='configure_excel_template', evidence={}, blocking=template_invalid, + ), + ] + + +def get_source_activation_status(source: FreightRpaSource) -> dict[str, Any]: + """返回库存站点启用硬门槛的结构化结果。 + + Args: + source: 已持久化的库存站点,关联配置由当前数据库事务提供。 + + Returns: + dict[str, Any]: ``checks`` 为前端唯一的检查真相;``ready`` 为启用结论; + ``missing_requirements`` 是由 checks 派生的紧凑摘要,供现有调用方读取。 + """ + checks = _source_activation_checks(source) + missing = [item['code'] for item in checks if item['blocking']] + return { + 'ready': not missing, + 'checks': checks, + 'missing_requirements': missing, + } + + +def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]: + """启用已满足硬门槛的库存站点;未通过任一前置条件时保持停用。""" + source = db.session.get(FreightRpaSource, source_id) + if source is None: + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') + status = get_source_activation_status(source) + if not status['ready']: + raise ConflictError( + 'Inventory Source is not ready for activation', + code='SHIPPING.ONHAND_SOURCE_ACTIVATION_BLOCKED', + details=status, + ) + source.enabled = True + source.updated_by = actor_id + db.session.commit() + return _source_payload(source) + + +def deactivate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]: + """停用库存站点,保留其解析方案和历史运行审计。""" + source = db.session.get(FreightRpaSource, source_id) + if source is None: + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') + source.enabled = False + source.updated_by = actor_id + db.session.commit() + return _source_payload(source) + + +def save_source( + data: dict[str, Any], *, actor_id: int | None, source_id: int | None = None, + allow_enable_transition: bool = True, +) -> dict[str, Any]: + """保存库存站点基础配置;管理 API 不允许通过普通保存直接启用站点。 + + s18 起站点头部仅编辑 source_code / display_name / connector_type / rpa_profile_id / + excel_template_id / 仓库模式 / snapshot_ttl_seconds;报表路径、查询条件与解析方案 + 绑定经载荷内嵌的 ``onhand_report_config`` 对象写入配置行(与独立保存同一校验路径)。 + """ + source = db.session.get(FreightRpaSource, source_id) if source_id else None + if source_id and source is None: + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') + try: + profile_id = int(data.get('rpa_profile_id')) + except (TypeError, ValueError) as exc: + raise ValidationError('rpa_profile_id is required') from exc + profile = db.session.get(FreightRpaProfile, profile_id) + if profile is None: + raise ValidationError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND') + requested_enabled = _bool(data, 'enabled', bool(source.enabled) if source_id else False) + if not allow_enable_transition: + # 普通保存不承担状态切换:首次一律停用,已启用站点保留当前状态。 + enabled = bool(source.enabled) if source is not None else False + else: + enabled = requested_enabled + if enabled and not profile.enabled: + raise ValidationError( + 'Enabled Inventory Source requires an enabled RPA Profile', + code='SHIPPING.RPA_PROFILE_DISABLED', + ) + excel_template_id = data.get('excel_template_id') + excel_template = db.session.get(ShippingExcelTemplate, int(excel_template_id)) if str(excel_template_id or '').isdigit() else None + if excel_template_id not in (None, '', 0, '0') and (excel_template is None or excel_template.status != 'published'): + raise ValidationError('excel_template_id must reference a published template', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED') + is_new = source is None + source = source or FreightRpaSource( + source_code='', display_name='', connector_type='', warehouse_resolution_mode='fixed', + ) + source.source_code = str(_text(data, 'source_code', required=True)).upper() + source.display_name = str(_text(data, 'display_name', required=True)) + source.connector_type = str(_text(data, 'connector_type', required=True)).lower() + source.rpa_profile = profile + source.excel_template = excel_template + source.warehouse_resolution_mode = str(_text(data, 'warehouse_resolution_mode', required=True)).lower() + source.fixed_warehouse_id = _text(data, 'fixed_warehouse_id') + source.snapshot_ttl_seconds = int(data.get('snapshot_ttl_seconds') or 86400) + source.enabled = enabled + source.updated_by = actor_id + if source_id: + source.config_version += 1 + if is_new: + source.created_by = actor_id + db.session.add(source) + # [STEP 1] 启用门禁先行:缺模板在写库前给出可解释错误,避免撞站点行 CHECK 的 IntegrityError + # (模板缺失复用 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED,不新造码)。 + if enabled and excel_template is None: + raise ValidationError( + 'published excel_template_id is required', + code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED', + ) + try: + # flush 让 excel_template_id / 新行主键先行落位,后续门禁读取规整后的外键。 + db.session.flush() + except Exception as exc: + db.session.rollback() + raise ValidationError('Invalid Inventory Source configuration', code='SHIPPING.ONHAND_SOURCE_INVALID') from exc + # [STEP 2] 载荷内嵌 onhand_report_config 时与独立保存走同一校验/写行路径(无则插入配置行)。 + config_data = data.get('onhand_report_config') + if isinstance(config_data, dict): + _apply_onhand_report_config(source, config_data, actor_id=actor_id) + # [STEP 3] 启用门禁复核(缺配置行/解析绑定/模板统一 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED)。 + if enabled: + assert_onhand_source_can_enable(source) + validate_source_profile(source, profile) + try: + db.session.commit() + except Exception as exc: + db.session.rollback() + raise ValidationError('Invalid Inventory Source configuration', code='SHIPPING.ONHAND_SOURCE_INVALID') from exc + return _source_payload(source) + diff --git a/backend/app/services/admin/shipping_inventory_service.py b/backend/app/services/admin/shipping_inventory_service.py deleted file mode 100644 index ce074a2e..00000000 --- a/backend/app/services/admin/shipping_inventory_service.py +++ /dev/null @@ -1,1049 +0,0 @@ -""" -services/admin/shipping_inventory_service.py - -用途:管理库存源、RPA Profile、路由规则和外部系统映射主数据。 -依赖:db、库存配置模型、凭据加密、Source/Profile 校验、统一 AppError。 -逻辑:管理 API 委托本服务完成校验和事务;运行期库存匹配不从本服务读取明文凭据。 -""" - -from __future__ import annotations - -from datetime import datetime -from typing import Any - -from app.extensions import db -from app.core.errors import ConflictError, NotFoundError, ValidationError -from app.models import ( - ShippingInventoryExternalMapping, ShippingInventoryFile, ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, - ShippingInventoryRoutingRuleVersion, ShippingInventorySource, ShippingRpaProfile, ScheduleRun, ScheduleTask, ShippingNotice, - ShippingOrderField, - ShippingInventoryParsingProfile, - ShippingNoticeLine, ShippingNoticeLineInventoryMatch, - ShippingExcelTemplate, - ShippingInventorySourceParsingBindingAudit, - ShippingReceiptReportConfig, -) -from app.services.shipping_notice.audit_service import append_shipping_audit_event -from app.services.shipping_notice.credential_crypto import encrypt_credential -from app.services.shipping_notice.inventory_source_repository import validate_source_profile -from app.services.shipping_notice.upload_config_validation import validate_upload_config -from app.services.shipping_notice.routing_operators import ALLOWED_OPERATORS -from app.services.shipping_notice.inventory_routing_engine import ALLOWED_ACTIONS -from app.services.shipping_notice import inventory_parsing_profile -from app.services.shipping_notice.order_schema import service as order_schema_service - - -def _text(data: dict[str, Any], field: str, *, required: bool = False) -> str | None: - value = str(data.get(field) or '').strip() - if required and not value: - raise ValidationError(f'{field} is required', code='VALIDATION.INVALID_PARAM', details={'field': field}) - return value or None - - -def _bool(data: dict[str, Any], field: str, default: bool = True) -> bool: - value = data.get(field, default) - if not isinstance(value, bool): - raise ValidationError(f'{field} must be a boolean', details={'field': field}) - return value - - -def _json_object(data: dict[str, Any], field: str) -> dict[str, Any]: - """读取并复制对象型 JSON 配置。 - - Args: - data: 管理 API 的请求载荷。 - field: 只允许 JSON object 的字段名。 - - Returns: - dict[str, Any]: 空值规范化为空对象后的可写入配置。 - - Raises: - ValidationError: 字段不是 JSON object。 - """ - value = data.get(field, {}) - if not isinstance(value, dict): - raise ValidationError(f'{field} must be an object', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID') - return dict(value) - - -def _validate_profile_login_config(data: dict[str, Any]) -> dict[str, str]: - """校验连接级登录配置,不接收页面选择器或报表操作字段。""" - value = data.get('login_config_json', {}) - if not isinstance(value, dict) or set(value) - {'auth_mode'}: - raise ValidationError('login_config_json is invalid', code='SHIPPING.RPA_PROFILE_CONFIG_INVALID') - auth_mode = str(value.get('auth_mode') or 'password').strip().lower() - if auth_mode != 'password': - raise ValidationError( - 'Only password authentication is currently supported', - code='SHIPPING.RPA_PROFILE_CONFIG_INVALID', - ) - return {'auth_mode': auth_mode} - - -def _validate_report_path(connector_type: str, report_path: dict[str, Any]) -> dict[str, str]: - """校验 DBS 四级报表路径,防止技术选择器混入业务配置。""" - allowed = {'program_group', 'program_label', 'report_group', 'report_name'} - if set(report_path) - allowed: - raise ValidationError('report_path_json contains unsupported fields', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID') - normalized = {key: str(value or '').strip() for key, value in report_path.items()} - if connector_type == 'dbs': - missing = [key for key in allowed if not normalized.get(key)] - if missing: - raise ValidationError( - 'DBS inventory source requires a complete report path', - code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID', details={'missing': sorted(missing)}, - ) - elif normalized: - raise ValidationError( - 'Only DBS inventory sources can define report_path_json', - code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID', - ) - return {key: normalized[key] for key in allowed if normalized.get(key)} - - -def _validate_query_parameters(data: dict[str, Any]) -> list[dict[str, Any]]: - """校验 Source 的可视化查询参数列表,禁止保存 selector 等 Driver 实现细节。""" - raw = data.get('query_parameters_json', []) - if not isinstance(raw, list): - raise ValidationError('query_parameters_json must be a list', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID') - result: list[dict[str, Any]] = [] - seen_names: set[str] = set() - allowed = {'name', 'mode', 'values', 'required', 'select_all', 'joiner'} - for index, item in enumerate(raw): - if not isinstance(item, dict) or set(item) - allowed: - raise ValidationError( - 'query parameter contains unsupported fields', - code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID', details={'index': index}, - ) - name = str(item.get('name') or '').strip() - mode = str(item.get('mode') or 'single').strip().lower() - values = item.get('values', []) - required = item.get('required', False) - select_all = item.get('select_all', False) - if not name or name.lower() in seen_names or mode not in {'single', 'multi_text', 'multi_select'}: - raise ValidationError('query parameter name or mode is invalid', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID') - if not isinstance(values, list) or any(not isinstance(value, str) for value in values): - raise ValidationError('query parameter values must be a string list', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID') - if not isinstance(required, bool) or not isinstance(select_all, bool): - raise ValidationError('query parameter flags must be boolean', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID') - normalized_values = [value.strip() for value in values if value.strip()] - if required and not normalized_values and not select_all: - raise ValidationError('required query parameter needs values or select_all', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID') - if select_all and mode != 'multi_select': - raise ValidationError('select_all only applies to multi_select', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID') - parameter: dict[str, Any] = { - 'name': name, 'mode': mode, 'values': normalized_values, - 'required': required, 'select_all': select_all, - } - if mode == 'multi_text': - joiner = str(item.get('joiner') or ',').strip() - if not joiner: - raise ValidationError('multi_text query parameter needs joiner', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID') - parameter['joiner'] = joiner - seen_names.add(name.lower()) - result.append(parameter) - return result - - -def _profile_payload(profile: ShippingRpaProfile) -> dict[str, Any]: - return { - 'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name, - 'connector_type': profile.connector_type, 'login_url': profile.login_url, - 'login_config_json': profile.login_config_json or {'auth_mode': 'password'}, 'enabled': bool(profile.enabled), - 'upload_config_json': profile.upload_config_json, - 'config_version': profile.config_version, 'username_masked': _mask(profile.username_ciphertext), - 'password_configured': bool(profile.password_ciphertext), 'credential_updated_at': _iso(profile.credential_updated_at), - 'created_at': _iso(profile.created_at), 'updated_at': _iso(profile.updated_at), - } - - -def _mask(ciphertext: str | None) -> str | None: - """凭据密文不支持反向展示;仅以配置状态提示管理员。""" - return 'configured' if ciphertext else None - - -def _iso(value: datetime | None) -> str | None: - return value.isoformat() if value else None - - -def list_profiles() -> list[dict[str, Any]]: - """列出 Profile 元数据,不返回可恢复的凭据。""" - return [_profile_payload(item) for item in ShippingRpaProfile.query.order_by(ShippingRpaProfile.profile_code).all()] - - -def delete_profile(profile_id: int) -> None: - """删除未绑定库存源的错误连接配置,保留已使用连接的可追溯性。""" - profile = db.session.get(ShippingRpaProfile, profile_id) - if profile is None: - raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND') - if ShippingInventorySource.query.filter_by(rpa_profile_id=profile.id).count(): - raise ConflictError('RPA Profile is referenced by inventory sources', code='SHIPPING.RPA_PROFILE_DELETE_BLOCKED') - db.session.delete(profile) - db.session.commit() - - -def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]: - """创建或更新货代登录连接;密码留空表示保留既有密文。""" - profile = db.session.get(ShippingRpaProfile, profile_id) if profile_id else None - if profile_id and profile is None: - raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND') - profile = profile or ShippingRpaProfile(profile_code='', display_name='', connector_type='', login_url='', login_config_json={}) - # 记录“非 upload_config”的既有运行时配置快照:仅当这些字段变化才递增 config_version, - # upload_config_json 属于连接上传配置,变更不得误判库存 RPA 配置测试过期。 - prev_non_upload = ( - profile.profile_code, profile.display_name, profile.connector_type, profile.login_url, - dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled), - bool(profile.username_ciphertext), bool(profile.password_ciphertext), - ) if profile_id else None - profile.profile_code = str(_text(data, 'profile_code', required=True)).upper() - profile.display_name = str(_text(data, 'display_name', required=True)) - profile.connector_type = str(_text(data, 'connector_type', required=True)).lower() - profile.login_url = str(_text(data, 'login_url', required=True)) - profile.login_config_json = _validate_profile_login_config(data) - profile.enabled = _bool(data, 'enabled', bool(profile.enabled) if profile_id else True) - if not profile.enabled and any(source.enabled for source in profile.sources): - raise ConflictError( - 'Disable inventory sources before disabling their RPA Profile', - code='SHIPPING.RPA_PROFILE_DISABLE_BLOCKED', - ) - username = _text(data, 'username') - password = _text(data, 'password') - if username is not None: - profile.username_ciphertext = encrypt_credential(username) - if password is not None: - profile.password_ciphertext = encrypt_credential(password) - if username is not None or password is not None: - profile.credential_updated_at = datetime.utcnow() - # 连接级受控上传配置(受限 JSON);与库存 RPA 运行期配置隔离,不参与 config_version。 - if 'upload_config_json' in data: - profile.upload_config_json = validate_upload_config(profile.connector_type, data.get('upload_config_json')) - profile.updated_by = actor_id - if profile_id: - now_non_upload = ( - profile.profile_code, profile.display_name, profile.connector_type, profile.login_url, - dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled), - bool(profile.username_ciphertext), bool(profile.password_ciphertext), - ) - if now_non_upload != prev_non_upload: - profile.config_version += 1 - if not profile_id: - profile.created_by = actor_id - db.session.add(profile) - try: - db.session.commit() - except Exception as exc: - db.session.rollback() - raise ConflictError('RPA Profile code already exists', code='SHIPPING.RPA_PROFILE_CONFLICT') from exc - return _profile_payload(profile) - - -def _source_payload(source: ShippingInventorySource) -> dict[str, Any]: - """序列化库存站点及其是否满足正式启用前置条件。""" - return { - 'id': source.id, 'source_code': source.source_code, 'display_name': source.display_name, - 'connector_type': source.connector_type, 'rpa_profile_id': source.rpa_profile_id, - 'parsing_profile_id': source.parsing_profile_id, - 'excel_template_id': source.excel_template_id, - 'warehouse_resolution_mode': source.warehouse_resolution_mode, 'fixed_warehouse_id': source.fixed_warehouse_id, - 'report_path_json': source.report_path_json or {}, 'query_parameters_json': source.query_parameters_json or [], - 'snapshot_ttl_seconds': source.snapshot_ttl_seconds, 'enabled': bool(source.enabled), - 'config_version': source.config_version, 'created_at': _iso(source.created_at), 'updated_at': _iso(source.updated_at), - 'activation': get_source_activation_status(source), - } - - -def _receipt_report_config_payload(config: ShippingReceiptReportConfig) -> dict[str, Any]: - """序列化独立收料配置,禁止把库存路径或凭据透传至管理端。""" - profile = config.parsing_profile - return { - 'id': config.id, 'inventory_source_id': config.inventory_source_id, - 'report_path_json': config.report_path_json or {}, - 'query_parameters_json': config.query_parameters_json or [], - # 异动解析绑定:供抽屉回显当前规则;摘要只取展示字段,不透传定义。 - 'parsing_profile_id': config.parsing_profile_id, - 'parsing_profile': ({ - 'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name, - 'version': profile.version, 'status': profile.status, - } if profile else None), - 'config_version': config.config_version, - 'created_at': _iso(config.created_at), 'updated_at': _iso(config.updated_at), - } - - -def _validate_movement_profile_binding(profile_id: Any) -> int | None: - """校验收料配置绑定的异动解析规则:必须已发布且 purpose='movement';空值表示解绑。 - - Args: - profile_id: 请求中的 parsing_profile_id;None/空串表示解绑。 - Returns: - 规整后的规则 id 或 None。 - Raises: - ValidationError: 规则不存在/未发布/用途不是 movement(fail-closed,防误绑库存规则)。 - """ - if profile_id is None or str(profile_id).strip() == '': - return None - profile = db.session.get(ShippingInventoryParsingProfile, int(profile_id)) - if profile is None or profile.status != 'published' or profile.purpose != 'movement': - raise ValidationError( - 'Receipt movement parsing profile must be published with purpose movement', - code='SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID', - ) - return profile.id - - -def _validate_receipt_report_config( - source: ShippingInventorySource, data: dict[str, Any], -) -> tuple[dict[str, str], list[dict[str, Any]]]: - """规范收料配置,与库存同构:路径+查询条件;日期禁填。 - - DBS 的 Warehouse 等查询条件均为可选报表筛选:空条件表示 Worker 使用页面默认; - 不作为排程是否产出执行单元的门禁(一源一单元)。 - """ - try: - parameters = _validate_query_parameters(data) - except ValidationError as exc: - raise ValidationError(str(exc), code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') from exc - # 报表日期不筛选,避免管理端误传日期使跨日排程导出产生漏数。 - if any('date' in str(item.get('name') or '').strip().lower() for item in parameters): - raise ValidationError('Receipt report date filtering is not supported', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') - raw_path = _json_object(data, 'report_path_json') - if source.connector_type == 'dbs': - try: - path = _validate_report_path('dbs', raw_path) - except ValidationError as exc: - raise ValidationError(str(exc), code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') from exc - # Warehouse 等条件可选;缺失/空值允许保存,运行期原样下发或走页面默认。 - return path, parameters - if source.connector_type == 'crane': - if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Inbound Details'): - raise ValidationError('Crane receipt report is fixed to Inbound Details', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') - if parameters: - raise ValidationError( - 'Crane receipt report does not support query parameters', - code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID', - ) - return {'report_name': 'Inbound Details'}, [] - raise ValidationError('Unsupported receipt connector type', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') - - -def get_receipt_report_config(source_id: int) -> dict[str, Any] | None: - """读取站点的收料配置;不存在时返回空,供抽屉初始化而非创建库存配置。""" - source = db.session.get(ShippingInventorySource, source_id) - if source is None: - raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') - config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).one_or_none() - return _receipt_report_config_payload(config) if config else None - - -def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: - """保存站点内独立收料配置并追加配置前后快照审计,不写入库存 Source 字段。""" - source = db.session.get(ShippingInventorySource, source_id) - if source is None: - raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') - path, parameters = _validate_receipt_report_config(source, data) - config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).one_or_none() - before = _receipt_report_config_payload(config) if config else None - is_new = config is None - if config is None: - config = ShippingReceiptReportConfig(inventory_source_id=source.id) - config.created_by = actor_id - db.session.add(config) - else: - config.config_version += 1 - config.report_path_json = path - config.query_parameters_json = parameters - config.parsing_profile_id = _validate_movement_profile_binding(data.get('parsing_profile_id')) - config.updated_by = actor_id - db.session.flush() - after = _receipt_report_config_payload(config) - append_shipping_audit_event( - event_type='shipping_receipt_report_config_saved', aggregate_type='shipping_receipt_report_config', - aggregate_id=str(source.id), actor_type='admin', actor_id=actor_id, action='create' if is_new else 'update', - result='success', before=before, after=after, - metadata={'inventory_source_id': source.id, 'connector_type': source.connector_type, - 'parsing_profile_id': config.parsing_profile_id}, - ) - db.session.commit() - return after - - -def _binding_snapshot(source: ShippingInventorySource) -> dict[str, Any]: - """冻结解析绑定变更的最小站点上下文,避免审计依赖后续可变主数据。""" - return { - 'source_id': source.id, - 'source_code': source.source_code, - 'enabled': bool(source.enabled), - 'parsing_profile_id': source.parsing_profile_id, - 'parsing_profile_checksum': source.parsing_profile.checksum if source.parsing_profile else None, - 'excel_template_id': source.excel_template_id, - 'config_version': source.config_version, - } - - -def _validate_source_parsing_binding(source: ShippingInventorySource, profile: ShippingInventoryParsingProfile) -> None: - """校验站点可直接采用的已发布方案与当前发货模板字段契约;启用中的站点同样允许更换解析绑定。""" - 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 {} - mapping = definition.get('field_mapping') if isinstance(definition.get('field_mapping'), dict) else {} - if not mapping: - raise ValidationError('Published parsing profile is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED') - template = source.excel_template - if template is None: - return - if template.status != 'published': - raise ValidationError('Published excel template is required', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED') - template_definition = template.definition_json if isinstance(template.definition_json, dict) else {} - template_mappings = template_definition.get('mappings') if isinstance(template_definition.get('mappings'), list) else [] - missing_fields = sorted({ - str(item.get('source_key') or '') - for item in template_mappings - if isinstance(item, dict) - and item.get('source_kind') == 'inventory_field' - and str(item.get('source_key') or '') not in mapping - }) - if missing_fields: - raise ValidationError( - 'Parsing profile does not provide all inventory fields required by the excel template', - code='SHIPPING.INVENTORY_SOURCE_BINDING_TEMPLATE_INVALID', details={'inventory_field_ids': missing_fields}, - ) - - -def bind_source_parsing_profile( - source_ids: list[int], profile_id: int, *, actor_id: int | None, reason: str | None = None, operation: str, -) -> list[dict[str, Any]]: - """为一个或多个库存站点原子绑定已发布解析方案并写入追加式审计(含已启用站点)。 - - Args: - source_ids: 待绑定的库存站点主键,不能为空且不得重复。 - profile_id: 必须为已发布解析方案主键。 - actor_id: 当前管理员主键,仅写入审计。 - reason: 可选的补充说明;未填写时由系统记录本次直接或批量绑定动作。 - operation: 审计操作类型,仅允许 ``direct`` 或 ``bulk``。 - - Returns: - list[dict[str, Any]]: 已更新站点的管理端 DTO。 - - Raises: - ValidationError: 任一站点、方案或模板字段契约不合法;批量请求不会部分写入。 - ConflictError: 试图变更已启用站点的正式解析方案。 - """ - try: - normalized_ids = sorted({int(item) for item in source_ids if int(item) > 0}) - except (TypeError, ValueError) as exc: - raise ValidationError('source_ids must be a non-empty unique integer list', code='VALIDATION.INVALID_PARAM') from exc - if not normalized_ids or len(normalized_ids) != len(source_ids): - raise ValidationError('source_ids must be a non-empty unique integer list', code='VALIDATION.INVALID_PARAM') - if operation not in {'direct', 'bulk'}: - raise ValidationError('Binding operation is invalid', code='VALIDATION.INVALID_PARAM') - normalized_reason = str(reason or '').strip() - if len(normalized_reason) > 500: - raise ValidationError('Binding note must not exceed 500 characters', code='VALIDATION.INVALID_PARAM') - # 审计必须保留可读动作,但不应把技术审计字段变成管理员的额外填写负担。 - if not normalized_reason: - normalized_reason = '管理员直接绑定已发布解析方案' if operation == 'direct' else '管理员批量绑定已发布解析方案' - try: - normalized_profile_id = int(profile_id) - except (TypeError, ValueError) as exc: - raise ValidationError('parsing_profile_id is required', code='VALIDATION.INVALID_PARAM') from exc - profile = db.session.get(ShippingInventoryParsingProfile, normalized_profile_id) - if profile is None: - raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND') - sources = [db.session.get(ShippingInventorySource, source_id) for source_id in normalized_ids] - if any(source is None for source in sources): - raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') - typed_sources = [source for source in sources if source is not None] - # [STEP 1] 全量预检后才变更,避免多站点操作出现部分绑定。 - for source in typed_sources: - _validate_source_parsing_binding(source, profile) - for source in typed_sources: - before = _binding_snapshot(source) - previous_profile_id = source.parsing_profile_id - source.parsing_profile = profile - source.updated_by = actor_id - source.config_version += 1 - db.session.flush() - db.session.add(ShippingInventorySourceParsingBindingAudit( - inventory_source_id=source.id, previous_parsing_profile_id=previous_profile_id, - parsing_profile_id=profile.id, operation=operation, reason=normalized_reason, actor_id=actor_id, - source_config_version_before=before['config_version'], source_config_version_after=source.config_version, - before_snapshot_json=before, after_snapshot_json=_binding_snapshot(source), - )) - db.session.commit() - return [_source_payload(source) for source in typed_sources] - - -def get_source_parsing_binding_audits(source_id: int) -> list[dict[str, Any]]: - """读取库存站点解析绑定审计,仅返回配置快照和操作者标识。""" - if db.session.get(ShippingInventorySource, source_id) is None: - raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') - rows = ShippingInventorySourceParsingBindingAudit.query.filter_by( - inventory_source_id=source_id, - ).order_by(ShippingInventorySourceParsingBindingAudit.id.desc()).all() - return [{ - 'id': row.id, 'operation': row.operation, 'reason': row.reason, 'actor_id': row.actor_id, - 'previous_parsing_profile_id': row.previous_parsing_profile_id, 'parsing_profile_id': row.parsing_profile_id, - 'source_config_version_before': row.source_config_version_before, - 'source_config_version_after': row.source_config_version_after, - 'before': row.before_snapshot_json, 'after': row.after_snapshot_json, - 'created_at': row.created_at.isoformat() if row.created_at else None, - } for row in rows] - - -def list_sources() -> list[dict[str, Any]]: - """列出库存源及其稳定业务配置。""" - return [_source_payload(item) for item in ShippingInventorySource.query.order_by(ShippingInventorySource.source_code).all()] - - -def delete_source(source_id: int) -> None: - """删除未参与映射、快照或规则的错误库存源,避免破坏历史路由身份。""" - source = db.session.get(ShippingInventorySource, source_id) - if source is None: - raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') - source_code = str(source.source_code or '').strip().upper() - has_mapping = ShippingInventoryExternalMapping.query.filter_by(inventory_source_id=source.id).count() > 0 - has_snapshot = ShippingInventoryFile.query.filter_by(source_code=source_code).count() > 0 - has_rule = any( - source_code in {str(code).strip().upper() for code in candidates} - for rule in ShippingInventoryRoutingRule.query.all() - for candidates in [(rule.action_payload_json or {}).get('source_codes', [])] - if isinstance(candidates, list) - ) - has_task = db.session.query(ShippingNoticeLine.id).filter( - ShippingNoticeLine.inventory_source_code == source_code, - ).first() is not None or db.session.query(ShippingNoticeLineInventoryMatch.id).filter( - ShippingNoticeLineInventoryMatch.inventory_source_code == source_code, - ).first() is not None - has_export_run = any( - source_code in {str(code).strip().upper() for code in source_codes} - for run in ScheduleRun.query.all() - for source_codes in [(run.api_request_json or {}).get('source_codes', [])] - if isinstance(source_codes, list) - ) - if has_mapping or has_snapshot or has_rule or has_task or has_export_run: - raise ConflictError('Inventory Source has operational references', code='SHIPPING.INVENTORY_SOURCE_DELETE_BLOCKED') - db.session.delete(source) - db.session.commit() - - -def _snapshot_payload(snapshot: ShippingInventoryFile) -> dict[str, Any]: - """投影库存快照的管理端只读行,不暴露存储路径或库存明细。""" - return { - 'id': snapshot.id, 'inventory_file_no': snapshot.inventory_file_no, - 'source_code': snapshot.source_code, 'warehouse_id': snapshot.warehouse_id, - 'snapshot_status': snapshot.snapshot_status, 'identity_status': snapshot.identity_status, - 'line_count': snapshot.line_count, 'share_mode': snapshot.share_mode, - 'exported_at': _iso(snapshot.exported_at), 'expires_at': _iso(snapshot.expires_at), - 'rpa_run_no': snapshot.rpa_run_no, 'schedule_run_id': snapshot.schedule_run_id, - 'source_file_name': snapshot.source_file_name, 'created_at': _iso(snapshot.created_at), - 'download_available': bool(snapshot.storage_path and not str(snapshot.storage_path).startswith('failed://')), - 'error_message': (snapshot.schema_preview_json or {}).get('error') if snapshot.snapshot_status == 'failed' else None, - } - - -def list_snapshots(*, limit: int = 100) -> list[dict[str, Any]]: - """列出最新库存快照,供管理员确认当前可用的库存文件。""" - rows = ShippingInventoryFile.query.order_by( - ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc(), - ).limit(max(1, min(limit, 200))).all() - return [_snapshot_payload(row) for row in rows] - - -def get_snapshot_download(snapshot_id: int) -> tuple[str, str]: - """返回管理员可下载的库存快照路径及安全文件名。 - - Args: - snapshot_id: 库存快照主键。 - - Returns: - 本地托管文件绝对路径和面向下载的文件名。 - - Raises: - NotFoundError: 快照不存在或托管文件已不存在。 - """ - from pathlib import Path - - snapshot = db.session.get(ShippingInventoryFile, snapshot_id) - if snapshot is None: - raise NotFoundError('Inventory snapshot not found', code='SHIPPING.INVENTORY_SNAPSHOT_NOT_FOUND') - path = Path(str(snapshot.storage_path or '')).resolve() - if not str(snapshot.storage_path or '') or str(snapshot.storage_path).startswith('failed://') or not path.is_file(): - raise NotFoundError('Inventory snapshot file not found', code='SHIPPING.INVENTORY_SNAPSHOT_FILE_NOT_FOUND') - filename = str(snapshot.source_file_name or f'{snapshot.inventory_file_no}{path.suffix or ".xlsx"}') - return str(path), filename - - -def list_export_records(*, limit: int = 100) -> list[dict[str, Any]]: - """列出 RPA 导出记录,合并已归档文件与排程失败/跳过结果。""" - file_rows = ShippingInventoryFile.query.filter( - ShippingInventoryFile.rpa_run_no.is_not(None), - ).order_by( - ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc(), - ).limit(max(1, min(limit, 200))).all() - records = [_snapshot_payload(row) for row in file_rows] - known_identities = { - (str(item.get('rpa_run_no') or ''), str(item.get('source_code') or ''), str(item.get('warehouse_id') or '')) - for item in records - } - - # 失败或跳过的 RPA 执行不会生成库存文件,必须从 ScheduleRun 补齐审计记录。 - schedule_runs = ScheduleRun.query.join(ScheduleTask).filter( - ScheduleTask.platform_api_path == 'shipping-inventory-rpa', - ).order_by(ScheduleRun.created_at.desc()).limit(max(1, min(limit, 200))).all() - for run in schedule_runs: - response = run.api_response_json if isinstance(run.api_response_json, dict) else {} - request_data = run.api_request_json if isinstance(run.api_request_json, dict) else {} - run_no = str(response.get('run_no') or request_data.get('run_no') or run.run_no or '').strip() - items: list[tuple[str, dict[str, Any]]] = [] - for status, key in (('skipped', 'skipped'), ('failed', 'failed')): - for item in response.get(key) if isinstance(response.get(key), list) else []: - if isinstance(item, dict): - items.append((status, item)) - if not items and run.status in {'queued', 'running'}: - pending = (run.response_summary_json or {}).get('pending_details', []) - for item in pending if isinstance(pending, list) else []: - if isinstance(item, dict): - items.append(('awaiting_rpa', item)) - if not items and run.status in {'failed', 'partial_failed'}: - for source_code in request_data.get('source_codes') if isinstance(request_data.get('source_codes'), list) else []: - items.append(('failed', {'source_code': source_code, 'error_message': run.error_message})) - for status, item in items: - source_code = str(item.get('source_code') or '').strip() - warehouse_id = str(item.get('warehouse_id') or '').strip() - identity = (run_no, source_code, warehouse_id) - if identity in known_identities: - continue - known_identities.add(identity) - records.append({ - 'id': f'schedule-{run.id}-{status}-{source_code}-{warehouse_id}', - 'inventory_file_no': None, - 'source_code': source_code or None, - 'warehouse_id': warehouse_id or None, - 'snapshot_status': status, - 'export_status': status, - 'identity_status': None, - 'line_count': 0, - 'share_mode': None, - 'exported_at': _iso(run.finished_at or run.created_at), - 'expires_at': None, - 'rpa_run_no': run_no or None, - 'schedule_run_id': run.id, - 'source_file_name': None, - 'created_at': _iso(run.created_at), - 'error_message': str(item.get('error_message') or item.get('error') or run.error_message or '')[:500] or None, - }) - records.sort(key=lambda item: str(item.get('exported_at') or item.get('created_at') or ''), reverse=True) - return records[:max(1, min(limit, 200))] - - -def _template_validation_missing(source: ShippingInventorySource) -> list[str]: - """确认发货模板引用的库存字段均由当前解析方案提供,避免启用后才发现字段断链。""" - template = source.excel_template - profile = source.parsing_profile - if template is None or profile is None: - return [] - definition = template.definition_json if isinstance(template.definition_json, dict) else {} - mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else [] - profile_definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} - inventory_fields = {str(field_id) for field_id in (profile_definition.get('field_mapping') or {}).keys()} - invalid = any( - isinstance(item, dict) - and item.get('source_kind') == 'inventory_field' - and str(item.get('source_key') or '') not in inventory_fields - for item in mappings - ) - return ['template_validation'] if not mappings or invalid else [] - - -def _activation_check( - code: str, *, passed: bool, action: str, evidence: dict[str, Any], status: str | None = None, - blocking: bool | None = None, -) -> dict[str, Any]: - """构造单项启用门禁结果,确保管理端只展示服务端已判定的业务事实。""" - return { - 'code': code, - 'status': status or ('passed' if passed else 'pending'), - 'blocking': not passed if blocking is None else blocking, - 'action': action, - 'evidence': evidence, - } - - -def _source_activation_checks(source: ShippingInventorySource) -> list[dict[str, Any]]: - """构建库存站点启用硬门槛:可用连接、已发布解析方案、已绑定已发布发货模板及字段契约。 - - 测试导出不再参与启用门禁;启停由管理员显式开关完成。 - """ - profile_ready = source.rpa_profile is not None and bool(source.rpa_profile.enabled) - parsing_ready = source.parsing_profile is not None and source.parsing_profile.status == 'published' - template_ready = source.excel_template is not None and source.excel_template.status == 'published' - template_invalid = bool(_template_validation_missing(source)) if template_ready and parsing_ready else False - return [ - _activation_check( - 'rpa_profile', passed=profile_ready, action='configure_connection', - evidence={'profile_id': source.rpa_profile_id, 'enabled': profile_ready}, - ), - _activation_check( - 'parsing_profile', passed=parsing_ready, action='configure_parsing_profile', - evidence={'profile_id': source.parsing_profile_id, 'published': parsing_ready}, - ), - _activation_check( - 'excel_template', passed=template_ready, action='configure_excel_template', - evidence={'template_id': source.excel_template_id, 'published': template_ready}, - ), - _activation_check( - 'template_validation', passed=not template_invalid, - action='configure_excel_template', evidence={}, blocking=template_invalid, - ), - ] - - -def get_source_activation_status(source: ShippingInventorySource) -> dict[str, Any]: - """返回库存站点启用硬门槛的结构化结果。 - - Args: - source: 已持久化的库存站点,关联配置由当前数据库事务提供。 - - Returns: - dict[str, Any]: ``checks`` 为前端唯一的检查真相;``ready`` 为启用结论; - ``missing_requirements`` 是由 checks 派生的紧凑摘要,供现有调用方读取。 - """ - checks = _source_activation_checks(source) - missing = [item['code'] for item in checks if item['blocking']] - return { - 'ready': not missing, - 'checks': checks, - 'missing_requirements': missing, - } - - -def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]: - """启用已满足硬门槛的库存站点;未通过任一前置条件时保持停用。""" - source = db.session.get(ShippingInventorySource, source_id) - if source is None: - raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') - status = get_source_activation_status(source) - if not status['ready']: - raise ConflictError( - 'Inventory Source is not ready for activation', - code='SHIPPING.INVENTORY_SOURCE_ACTIVATION_BLOCKED', - details=status, - ) - source.enabled = True - source.updated_by = actor_id - db.session.commit() - return _source_payload(source) - - -def deactivate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]: - """停用库存站点,保留其解析方案和历史运行审计。""" - source = db.session.get(ShippingInventorySource, source_id) - if source is None: - raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') - source.enabled = False - source.updated_by = actor_id - db.session.commit() - return _source_payload(source) - - -def save_source( - data: dict[str, Any], *, actor_id: int | None, source_id: int | None = None, - allow_enable_transition: bool = True, -) -> dict[str, Any]: - """保存库存站点基础配置;管理 API 不允许通过普通保存直接启用站点。""" - source = db.session.get(ShippingInventorySource, source_id) if source_id else None - if source_id and source is None: - raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') - try: - profile_id = int(data.get('rpa_profile_id')) - except (TypeError, ValueError) as exc: - raise ValidationError('rpa_profile_id is required') from exc - profile = db.session.get(ShippingRpaProfile, profile_id) - if profile is None: - raise ValidationError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND') - requested_enabled = _bool(data, 'enabled', bool(source.enabled) if source_id else False) - if not allow_enable_transition: - # 普通保存不承担状态切换:首次一律停用,已启用站点保留当前状态。 - enabled = bool(source.enabled) if source is not None else False - else: - enabled = requested_enabled - if enabled and not profile.enabled: - raise ValidationError( - 'Enabled Inventory Source requires an enabled RPA Profile', - code='SHIPPING.RPA_PROFILE_DISABLED', - ) - parsing_profile_id = data.get('parsing_profile_id') - parsing_profile = db.session.get(ShippingInventoryParsingProfile, int(parsing_profile_id)) if str(parsing_profile_id or '').isdigit() else None - if parsing_profile_id not in (None, '', 0, '0') and (parsing_profile is None or parsing_profile.status != 'published'): - raise ValidationError('parsing_profile_id must reference a published profile', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED') - if enabled and parsing_profile is None: - raise ValidationError('published parsing_profile_id is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED') - excel_template_id = data.get('excel_template_id') - excel_template = db.session.get(ShippingExcelTemplate, int(excel_template_id)) if str(excel_template_id or '').isdigit() else None - if excel_template_id not in (None, '', 0, '0') and (excel_template is None or excel_template.status != 'published'): - raise ValidationError('excel_template_id must reference a published template', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED') - if enabled and excel_template is None: - raise ValidationError('published excel_template_id is required', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED') - is_new = source is None - source = source or ShippingInventorySource( - source_code='', display_name='', connector_type='', warehouse_resolution_mode='fixed', - ) - source.source_code = str(_text(data, 'source_code', required=True)).upper() - source.display_name = str(_text(data, 'display_name', required=True)) - source.connector_type = str(_text(data, 'connector_type', required=True)).lower() - source.rpa_profile = profile - source.parsing_profile = parsing_profile - source.excel_template = excel_template - source.warehouse_resolution_mode = str(_text(data, 'warehouse_resolution_mode', required=True)).lower() - source.fixed_warehouse_id = _text(data, 'fixed_warehouse_id') - source.report_path_json = _validate_report_path(source.connector_type, _json_object(data, 'report_path_json')) - source.query_parameters_json = _validate_query_parameters(data) - source.snapshot_ttl_seconds = int(data.get('snapshot_ttl_seconds') or 86400) - source.enabled = enabled - source.updated_by = actor_id - if source_id: - source.config_version += 1 - if is_new: - source.created_by = actor_id - db.session.add(source) - validate_source_profile(source, profile) - try: - db.session.commit() - except Exception as exc: - db.session.rollback() - raise ValidationError('Invalid Inventory Source configuration', code='SHIPPING.INVENTORY_SOURCE_INVALID') from exc - return _source_payload(source) - - -def _rule_payload(rule: ShippingInventoryRoutingRule) -> dict[str, Any]: - return { - 'id': rule.id, 'rule_code': rule.rule_code, 'rule_name': rule.rule_name, 'scope': rule.scope, - 'priority': rule.priority, 'match_mode': rule.match_mode, 'status': rule.status, - 'action_type': rule.action_type, 'action_payload_json': rule.action_payload_json or {}, 'version': rule.version, - 'conditions': [{'source_kind': c.source_kind, 'order_field_id': c.order_field_id, - 'operator': c.operator, 'expected_value_json': c.expected_value_json, - 'condition_group': c.condition_group, 'sequence': c.sequence} for c in rule.conditions], - } - - -def _validate_rule_condition_expected(operator: str, value: Any) -> Any: - """按匹配符号规范化期望值,避免自由 JSON 在运行期才暴露配置错误。""" - if operator in {'is_empty', 'is_not_empty'}: - return None - if operator in {'in', 'not_in'}: - if not isinstance(value, list): - raise ValidationError('List operator requires a string list', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID') - normalized = [str(item).strip() for item in value if str(item).strip()] - if not normalized: - raise ValidationError('List operator requires at least one value', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID') - return normalized - if operator in {'numeric_length', 'string_length'}: - try: - length = int(value) - except (TypeError, ValueError) as exc: - raise ValidationError('Length operator requires an integer', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID') from exc - if length < 0: - raise ValidationError('Length must not be negative', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID') - return length - if not isinstance(value, str) or not value.strip(): - raise ValidationError('Routing condition requires an expected value', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID') - return value.strip() - - -def list_rules() -> list[dict[str, Any]]: - """列出规则及条件,用于草稿编辑和已发布规则查看。""" - return [_rule_payload(item) for item in ShippingInventoryRoutingRule.query.order_by(ShippingInventoryRoutingRule.priority.desc()).all()] - - -def delete_draft_rule(rule_id: int) -> None: - """删除从未发布的草稿规则;发布过的规则必须归档以保留审计定义。""" - rule = db.session.get(ShippingInventoryRoutingRule, rule_id) - if rule is None: - raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND') - if rule.status != 'draft': - raise ConflictError('Only draft routing rules can be deleted', code='SHIPPING.INVENTORY_RULE_DELETE_BLOCKED') - db.session.delete(rule) - db.session.commit() - - -def retire_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]: - """归档已发布规则,使其不再参与新路由,同时保留已发布版本。""" - rule = db.session.get(ShippingInventoryRoutingRule, rule_id) - if rule is None: - raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND') - if rule.status != 'published': - raise ConflictError('Only published routing rules can be retired', code='SHIPPING.INVENTORY_RULE_RETIRE_INVALID') - rule.status = 'retired' - rule.updated_by = actor_id - db.session.commit() - return _rule_payload(rule) - - -def save_rule(data: dict[str, Any], *, actor_id: int | None, rule_id: int | None = None) -> dict[str, Any]: - """保存草稿规则;发布规则必须以新版本创建,避免篡改历史定义。""" - if rule_id: - current = db.session.get(ShippingInventoryRoutingRule, rule_id) - if current is None: - raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND') - if current.status != 'draft': - raise ConflictError('Only draft routing rules can be updated', code='SHIPPING.INVENTORY_RULE_IMMUTABLE') - rule = current if rule_id else ShippingInventoryRoutingRule( - rule_code='', rule_name='', scope='', action_type='', action_payload_json={} - ) - rule.rule_code = str(_text(data, 'rule_code', required=True)).upper() - rule.rule_name = str(_text(data, 'rule_name', required=True)) - rule.scope = str(_text(data, 'scope', required=True)).lower() - rule.priority = int(data.get('priority') or 0) - rule.match_mode = str(data.get('match_mode') or 'all').lower() - rule.status = 'draft' - rule.action_type = str(_text(data, 'action_type', required=True)).lower() - rule.action_payload_json = data.get('action_payload_json') if isinstance(data.get('action_payload_json'), dict) else {} - rule.version = int(data.get('version') or 1) - if not rule_id: - rule.created_by = actor_id - rule.updated_by = actor_id - if rule.action_type not in ALLOWED_ACTIONS or rule.scope not in {'task', 'line'} or rule.match_mode not in {'all', 'any'}: - raise ValidationError('Invalid routing rule metadata', code='SHIPPING.INVENTORY_RULE_INVALID') - conditions = data.get('conditions') - if not isinstance(conditions, list) or not conditions: - raise ValidationError('Routing rule requires conditions', code='SHIPPING.INVENTORY_RULE_CONDITIONS_REQUIRED') - # 草稿更新在同一版本内替换条件;发布后不可原地修改。 - if rule_id: - db.session.query(ShippingInventoryRoutingRuleCondition).filter_by(rule_id=rule.id).delete( - synchronize_session=False - ) - db.session.flush() - db.session.expire(rule, ['conditions']) - for index, item in enumerate(conditions, start=1): - if not isinstance(item, dict) or item.get('operator') not in ALLOWED_OPERATORS: - raise ValidationError('Routing rule condition is not allowed', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID') - source_kind = str(item.get('source_kind') or 'order_field') - order_field_id = str(item.get('order_field_id') or '') or None - field = db.session.get(ShippingOrderField, order_field_id) if order_field_id else None - if source_kind == 'order_field': - if field is None or field.status != 'active' or field.scope != rule.scope.replace('task', 'header'): - raise ValidationError('Routing order field is invalid for rule scope', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID') - published_fields = { - str(config.get('field_id')) - for config in order_schema_service.get_published_contract()['fields'] - if config.get('scope') == field.scope - } - if field.id not in published_fields: - raise ValidationError('Routing order field is not published', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID') - else: - raise ValidationError('Routing conditions must use a published order field', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID') - operator = str(item['operator']) - rule.conditions.append(ShippingInventoryRoutingRuleCondition( - condition_group=int(item.get('condition_group') or 1), source_kind=source_kind, - order_field_id=order_field_id, - operator=operator, expected_value_json=_validate_rule_condition_expected( - operator, item.get('expected_value_json'), - ), sequence=index, - )) - if not rule_id: - db.session.add(rule) - try: - db.session.commit() - except Exception as exc: - db.session.rollback() - raise ConflictError('Routing rule code and version already exist', code='SHIPPING.INVENTORY_RULE_CONFLICT') from exc - return _rule_payload(rule) - - -def publish_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]: - """发布草稿并写入不可变规则定义快照。 - - 路由规则只声明库存源候选,允许引用已配置但暂时停用的 Source;实际 - 库存 RPA 运行时仍由库存源门禁拒绝停用 Source,避免发布配置误触发 RPA。 - """ - rule = db.session.get(ShippingInventoryRoutingRule, rule_id) - if rule is None: - raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND') - if rule.status != 'draft': - raise ConflictError('Only draft routing rules can be published', code='SHIPPING.INVENTORY_RULE_PUBLISH_INVALID') - if rule.action_type in {'add_source_candidates', 'exclude_source_candidates'}: - payload = rule.action_payload_json if isinstance(rule.action_payload_json, dict) else {} - source_codes = { - str(code or '').strip().upper() - for code in payload.get('source_codes', []) - if str(code or '').strip() - } - existing_codes = { - str(code).strip().upper() - for (code,) in db.session.query(ShippingInventorySource.source_code).all() - } - missing_codes = sorted(source_codes - existing_codes) - if missing_codes: - raise ValidationError( - 'Routing rule references unavailable inventory sources', - code='SHIPPING.INVENTORY_RULE_SOURCE_INVALID', - details={'source_codes': missing_codes}, - ) - rule.status = 'published' - rule.updated_by = actor_id - db.session.add(ShippingInventoryRoutingRuleVersion( - rule_id=rule.id, version=rule.version, definition_json=_rule_payload(rule), published_by=actor_id, - )) - db.session.commit() - return _rule_payload(rule) - - -def _external_payload(mapping: ShippingInventoryExternalMapping) -> dict[str, Any]: - return { - 'id': mapping.id, 'inventory_source_id': mapping.inventory_source_id, - 'freight_warehouse_id': mapping.freight_warehouse_id, 'external_system_code': mapping.external_system_code, - 'external_organization_code': mapping.external_organization_code, 'external_site_code': mapping.external_site_code, - 'external_warehouse_code': mapping.external_warehouse_code, 'external_warehouse_name': mapping.external_warehouse_name, - 'in_transit_warehouse_code': mapping.in_transit_warehouse_code, - 'enabled': bool(mapping.enabled), 'version': mapping.version, - } - - -def list_external_mappings() -> list[dict[str, Any]]: - """列出库存源到外部系统仓库的映射,不执行调拨判断。""" - return [_external_payload(item) for item in ShippingInventoryExternalMapping.query.order_by(ShippingInventoryExternalMapping.id).all()] - - -def delete_external_mapping(mapping_id: int) -> None: - """删除错误的外部仓库映射;历史文件和任务不回写此实时配置。""" - record = db.session.get(ShippingInventoryExternalMapping, mapping_id) - if record is None: - raise NotFoundError('External mapping not found', code='SHIPPING.INVENTORY_EXTERNAL_MAPPING_NOT_FOUND') - db.session.delete(record) - db.session.commit() - - -def save_external_mapping(data: dict[str, Any], *, actor_id: int | None, mapping_id: int | None = None) -> dict[str, Any]: - """创建或更新精确/默认外部系统映射。""" - record = db.session.get(ShippingInventoryExternalMapping, mapping_id) if mapping_id else None - if mapping_id and record is None: - raise NotFoundError('External mapping not found', code='SHIPPING.INVENTORY_EXTERNAL_MAPPING_NOT_FOUND') - try: - source_id = int(data.get('inventory_source_id')) - except (TypeError, ValueError) as exc: - raise ValidationError('inventory_source_id is required') from exc - if db.session.get(ShippingInventorySource, source_id) is None: - raise ValidationError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') - record = record or ShippingInventoryExternalMapping(inventory_source_id=source_id, external_system_code='', external_warehouse_code='', external_warehouse_name='') - record.inventory_source_id = source_id - # 货代仓库改为可选维度:inventory_match 源按「收料文件仓库 == 货代仓库」匹配映射行, - # 空值即「空库位」默认映射行;归一化为大写以与收料仓库值精确比对。 - record.freight_warehouse_id = str(_text(data, 'freight_warehouse_id') or '').upper() or None - # 在途仓编码是在途调拨拨出库位来源(DefaultRouteResolver),保存端必填并大写归一。 - record.in_transit_warehouse_code = str(_text(data, 'in_transit_warehouse_code', required=True)).upper() - record.external_system_code = str(_text(data, 'external_system_code', required=True)).upper() - record.external_organization_code = _text(data, 'external_organization_code') - record.external_site_code = _text(data, 'external_site_code') - record.external_warehouse_code = str(_text(data, 'external_warehouse_code', required=True)).upper() - record.external_warehouse_name = str(_text(data, 'external_warehouse_name', required=True)) - record.enabled = _bool(data, 'enabled', bool(record.enabled) if mapping_id else True) - record.updated_by = actor_id - if not mapping_id: - record.created_by = actor_id - db.session.add(record) - try: - db.session.commit() - except Exception as exc: - db.session.rollback() - raise ConflictError('Active external mapping already exists for this freight identity', code='SHIPPING.INVENTORY_EXTERNAL_MAPPING_CONFLICT') from exc - return _external_payload(record) diff --git a/backend/app/services/admin/shipping_onhand_admin_service.py b/backend/app/services/admin/shipping_onhand_admin_service.py new file mode 100644 index 00000000..3a8b5aad --- /dev/null +++ b/backend/app/services/admin/shipping_onhand_admin_service.py @@ -0,0 +1,391 @@ +""" +services/admin/shipping_onhand_admin_service.py + +用途:在手域管理——库存快照只读、导出运行记录、路由规则、外部仓库映射。 +依赖:db、FreightRpaOnhandReportFile / FreightRpaOnhandRoutingRule / + FreightRpaOnhandExternalMapping、order_schema、routing_operators、ALLOWED_ACTIONS。 +逻辑:admin_freight_rpa 的 snapshots / export-records / rules / external-mappings 委托本服务; + 登录连接与来源站点见 freight_rpa_source_admin_service。 +""" + +from __future__ import annotations + +from typing import Any + +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.extensions import db +from app.models import ( + FreightRpaOnhandExternalMapping, + FreightRpaOnhandReportFile, + FreightRpaOnhandRoutingRule, + FreightRpaOnhandRoutingRuleCondition, + FreightRpaOnhandRoutingRuleVersion, + FreightRpaSource, + ScheduleRun, + ScheduleTask, + ShippingOrderField, +) +from app.services.admin.freight_rpa_form_utils import iso as _iso +from app.services.shipping_notice.onhand_routing_engine import ALLOWED_ACTIONS +from app.services.shipping_notice.order_schema import service as order_schema_service +from app.services.shipping_notice.routing_operators import ALLOWED_OPERATORS + + +def _text(data: dict[str, Any], field: str, *, required: bool = False) -> str | None: + """读取并清洗字符串表单字段。""" + value = str(data.get(field) or '').strip() + if required and not value: + raise ValidationError(f'{field} is required', code='VALIDATION.INVALID_PARAM', details={'field': field}) + return value or None + + +def _bool(data: dict[str, Any], field: str, default: bool = True) -> bool: + """读取布尔表单字段。""" + value = data.get(field, default) + if not isinstance(value, bool): + raise ValidationError(f'{field} must be a boolean', details={'field': field}) + return value + + +def _snapshot_payload(snapshot: FreightRpaOnhandReportFile) -> dict[str, Any]: + """投影库存快照的管理端只读行,不暴露存储路径或库存明细。""" + return { + 'id': snapshot.id, 'inventory_file_no': snapshot.onhand_file_no, + 'source_code': snapshot.source_code, 'warehouse_id': snapshot.warehouse_id, + 'snapshot_status': snapshot.snapshot_status, 'identity_status': snapshot.identity_status, + 'line_count': snapshot.line_count, 'share_mode': snapshot.share_mode, + 'exported_at': _iso(snapshot.exported_at), 'expires_at': _iso(snapshot.expires_at), + 'rpa_run_no': snapshot.rpa_run_no, 'schedule_run_id': snapshot.schedule_run_id, + 'source_file_name': snapshot.source_file_name, 'created_at': _iso(snapshot.created_at), + 'download_available': bool(snapshot.storage_path and not str(snapshot.storage_path).startswith('failed://')), + 'error_message': (snapshot.schema_preview_json or {}).get('error') if snapshot.snapshot_status == 'failed' else None, + } + + +def list_snapshots(*, limit: int = 100) -> list[dict[str, Any]]: + """列出最新库存快照,供管理员确认当前可用的库存文件。""" + rows = FreightRpaOnhandReportFile.query.order_by( + FreightRpaOnhandReportFile.exported_at.desc(), FreightRpaOnhandReportFile.id.desc(), + ).limit(max(1, min(limit, 200))).all() + return [_snapshot_payload(row) for row in rows] + + +def get_snapshot_download(snapshot_id: int) -> tuple[str, str]: + """返回管理员可下载的库存快照路径及安全文件名。 + + Args: + snapshot_id: 库存快照主键。 + + Returns: + 本地托管文件绝对路径和面向下载的文件名。 + + Raises: + NotFoundError: 快照不存在或托管文件已不存在。 + """ + from pathlib import Path + + snapshot = db.session.get(FreightRpaOnhandReportFile, snapshot_id) + if snapshot is None: + raise NotFoundError('Inventory snapshot not found', code='SHIPPING.ONHAND_SNAPSHOT_NOT_FOUND') + path = Path(str(snapshot.storage_path or '')).resolve() + if not str(snapshot.storage_path or '') or str(snapshot.storage_path).startswith('failed://') or not path.is_file(): + raise NotFoundError('Inventory snapshot file not found', code='SHIPPING.ONHAND_SNAPSHOT_FILE_NOT_FOUND') + filename = str(snapshot.source_file_name or f'{snapshot.onhand_file_no}{path.suffix or ".xlsx"}') + return str(path), filename + + +def list_export_records(*, limit: int = 100) -> list[dict[str, Any]]: + """列出 RPA 导出记录,合并已归档文件与排程失败/跳过结果。""" + file_rows = FreightRpaOnhandReportFile.query.filter( + FreightRpaOnhandReportFile.rpa_run_no.is_not(None), + ).order_by( + FreightRpaOnhandReportFile.exported_at.desc(), FreightRpaOnhandReportFile.id.desc(), + ).limit(max(1, min(limit, 200))).all() + records = [_snapshot_payload(row) for row in file_rows] + known_identities = { + (str(item.get('rpa_run_no') or ''), str(item.get('source_code') or ''), str(item.get('warehouse_id') or '')) + for item in records + } + + # 失败或跳过的 RPA 执行不会生成库存文件,必须从 ScheduleRun 补齐审计记录。 + schedule_runs = ScheduleRun.query.join(ScheduleTask).filter( + ScheduleTask.platform_api_path == 'freight-rpa-onhand', + ).order_by(ScheduleRun.created_at.desc()).limit(max(1, min(limit, 200))).all() + for run in schedule_runs: + response = run.api_response_json if isinstance(run.api_response_json, dict) else {} + request_data = run.api_request_json if isinstance(run.api_request_json, dict) else {} + run_no = str(response.get('run_no') or request_data.get('run_no') or run.run_no or '').strip() + items: list[tuple[str, dict[str, Any]]] = [] + for status, key in (('skipped', 'skipped'), ('failed', 'failed')): + for item in response.get(key) if isinstance(response.get(key), list) else []: + if isinstance(item, dict): + items.append((status, item)) + if not items and run.status in {'queued', 'running'}: + pending = (run.response_summary_json or {}).get('pending_details', []) + for item in pending if isinstance(pending, list) else []: + if isinstance(item, dict): + items.append(('awaiting_rpa', item)) + if not items and run.status in {'failed', 'partial_failed'}: + for source_code in request_data.get('source_codes') if isinstance(request_data.get('source_codes'), list) else []: + items.append(('failed', {'source_code': source_code, 'error_message': run.error_message})) + for status, item in items: + source_code = str(item.get('source_code') or '').strip() + warehouse_id = str(item.get('warehouse_id') or '').strip() + identity = (run_no, source_code, warehouse_id) + if identity in known_identities: + continue + known_identities.add(identity) + records.append({ + 'id': f'schedule-{run.id}-{status}-{source_code}-{warehouse_id}', + 'inventory_file_no': None, + 'source_code': source_code or None, + 'warehouse_id': warehouse_id or None, + 'snapshot_status': status, + 'export_status': status, + 'identity_status': None, + 'line_count': 0, + 'share_mode': None, + 'exported_at': _iso(run.finished_at or run.created_at), + 'expires_at': None, + 'rpa_run_no': run_no or None, + 'schedule_run_id': run.id, + 'source_file_name': None, + 'created_at': _iso(run.created_at), + 'error_message': str(item.get('error_message') or item.get('error') or run.error_message or '')[:500] or None, + }) + records.sort(key=lambda item: str(item.get('exported_at') or item.get('created_at') or ''), reverse=True) + return records[:max(1, min(limit, 200))] + + +def _rule_payload(rule: FreightRpaOnhandRoutingRule) -> dict[str, Any]: + return { + 'id': rule.id, 'rule_code': rule.rule_code, 'rule_name': rule.rule_name, 'scope': rule.scope, + 'priority': rule.priority, 'match_mode': rule.match_mode, 'status': rule.status, + 'action_type': rule.action_type, 'action_payload_json': rule.action_payload_json or {}, 'version': rule.version, + 'conditions': [{'source_kind': c.source_kind, 'order_field_id': c.order_field_id, + 'operator': c.operator, 'expected_value_json': c.expected_value_json, + 'condition_group': c.condition_group, 'sequence': c.sequence} for c in rule.conditions], + } + + +def _validate_rule_condition_expected(operator: str, value: Any) -> Any: + """按匹配符号规范化期望值,避免自由 JSON 在运行期才暴露配置错误。""" + if operator in {'is_empty', 'is_not_empty'}: + return None + if operator in {'in', 'not_in'}: + if not isinstance(value, list): + raise ValidationError('List operator requires a string list', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID') + normalized = [str(item).strip() for item in value if str(item).strip()] + if not normalized: + raise ValidationError('List operator requires at least one value', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID') + return normalized + if operator in {'numeric_length', 'string_length'}: + try: + length = int(value) + except (TypeError, ValueError) as exc: + raise ValidationError('Length operator requires an integer', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID') from exc + if length < 0: + raise ValidationError('Length must not be negative', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID') + return length + if not isinstance(value, str) or not value.strip(): + raise ValidationError('Routing condition requires an expected value', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID') + return value.strip() + + +def list_rules() -> list[dict[str, Any]]: + """列出规则及条件,用于草稿编辑和已发布规则查看。""" + return [_rule_payload(item) for item in FreightRpaOnhandRoutingRule.query.order_by(FreightRpaOnhandRoutingRule.priority.desc()).all()] + + +def delete_draft_rule(rule_id: int) -> None: + """删除从未发布的草稿规则;发布过的规则必须归档以保留审计定义。""" + rule = db.session.get(FreightRpaOnhandRoutingRule, rule_id) + if rule is None: + raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND') + if rule.status != 'draft': + raise ConflictError('Only draft routing rules can be deleted', code='SHIPPING.ONHAND_RULE_DELETE_BLOCKED') + db.session.delete(rule) + db.session.commit() + + +def retire_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]: + """归档已发布规则,使其不再参与新路由,同时保留已发布版本。""" + rule = db.session.get(FreightRpaOnhandRoutingRule, rule_id) + if rule is None: + raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND') + if rule.status != 'published': + raise ConflictError('Only published routing rules can be retired', code='SHIPPING.ONHAND_RULE_RETIRE_INVALID') + rule.status = 'retired' + rule.updated_by = actor_id + db.session.commit() + return _rule_payload(rule) + + +def save_rule(data: dict[str, Any], *, actor_id: int | None, rule_id: int | None = None) -> dict[str, Any]: + """保存草稿规则;发布规则必须以新版本创建,避免篡改历史定义。""" + if rule_id: + current = db.session.get(FreightRpaOnhandRoutingRule, rule_id) + if current is None: + raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND') + if current.status != 'draft': + raise ConflictError('Only draft routing rules can be updated', code='SHIPPING.ONHAND_RULE_IMMUTABLE') + rule = current if rule_id else FreightRpaOnhandRoutingRule( + rule_code='', rule_name='', scope='', action_type='', action_payload_json={} + ) + rule.rule_code = str(_text(data, 'rule_code', required=True)).upper() + rule.rule_name = str(_text(data, 'rule_name', required=True)) + rule.scope = str(_text(data, 'scope', required=True)).lower() + rule.priority = int(data.get('priority') or 0) + rule.match_mode = str(data.get('match_mode') or 'all').lower() + rule.status = 'draft' + rule.action_type = str(_text(data, 'action_type', required=True)).lower() + rule.action_payload_json = data.get('action_payload_json') if isinstance(data.get('action_payload_json'), dict) else {} + rule.version = int(data.get('version') or 1) + if not rule_id: + rule.created_by = actor_id + rule.updated_by = actor_id + if rule.action_type not in ALLOWED_ACTIONS or rule.scope not in {'task', 'line'} or rule.match_mode not in {'all', 'any'}: + raise ValidationError('Invalid routing rule metadata', code='SHIPPING.ONHAND_RULE_INVALID') + conditions = data.get('conditions') + if not isinstance(conditions, list) or not conditions: + raise ValidationError('Routing rule requires conditions', code='SHIPPING.ONHAND_RULE_CONDITIONS_REQUIRED') + # 草稿更新在同一版本内替换条件;发布后不可原地修改。 + if rule_id: + db.session.query(FreightRpaOnhandRoutingRuleCondition).filter_by(rule_id=rule.id).delete( + synchronize_session=False + ) + db.session.flush() + db.session.expire(rule, ['conditions']) + for index, item in enumerate(conditions, start=1): + if not isinstance(item, dict) or item.get('operator') not in ALLOWED_OPERATORS: + raise ValidationError('Routing rule condition is not allowed', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID') + source_kind = str(item.get('source_kind') or 'order_field') + order_field_id = str(item.get('order_field_id') or '') or None + field = db.session.get(ShippingOrderField, order_field_id) if order_field_id else None + if source_kind == 'order_field': + if field is None or field.status != 'active' or field.scope != rule.scope.replace('task', 'header'): + raise ValidationError('Routing order field is invalid for rule scope', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID') + published_fields = { + str(config.get('field_id')) + for config in order_schema_service.get_published_contract()['fields'] + if config.get('scope') == field.scope + } + if field.id not in published_fields: + raise ValidationError('Routing order field is not published', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID') + else: + raise ValidationError('Routing conditions must use a published order field', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID') + operator = str(item['operator']) + rule.conditions.append(FreightRpaOnhandRoutingRuleCondition( + condition_group=int(item.get('condition_group') or 1), source_kind=source_kind, + order_field_id=order_field_id, + operator=operator, expected_value_json=_validate_rule_condition_expected( + operator, item.get('expected_value_json'), + ), sequence=index, + )) + if not rule_id: + db.session.add(rule) + try: + db.session.commit() + except Exception as exc: + db.session.rollback() + raise ConflictError('Routing rule code and version already exist', code='SHIPPING.ONHAND_RULE_CONFLICT') from exc + return _rule_payload(rule) + + +def publish_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]: + """发布草稿并写入不可变规则定义快照。 + + 路由规则只声明库存源候选,允许引用已配置但暂时停用的 Source;实际 + 库存 RPA 运行时仍由库存源门禁拒绝停用 Source,避免发布配置误触发 RPA。 + """ + rule = db.session.get(FreightRpaOnhandRoutingRule, rule_id) + if rule is None: + raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND') + if rule.status != 'draft': + raise ConflictError('Only draft routing rules can be published', code='SHIPPING.ONHAND_RULE_PUBLISH_INVALID') + if rule.action_type in {'add_source_candidates', 'exclude_source_candidates'}: + payload = rule.action_payload_json if isinstance(rule.action_payload_json, dict) else {} + source_codes = { + str(code or '').strip().upper() + for code in payload.get('source_codes', []) + if str(code or '').strip() + } + existing_codes = { + str(code).strip().upper() + for (code,) in db.session.query(FreightRpaSource.source_code).all() + } + missing_codes = sorted(source_codes - existing_codes) + if missing_codes: + raise ValidationError( + 'Routing rule references unavailable inventory sources', + code='SHIPPING.ONHAND_RULE_SOURCE_INVALID', + details={'source_codes': missing_codes}, + ) + rule.status = 'published' + rule.updated_by = actor_id + db.session.add(FreightRpaOnhandRoutingRuleVersion( + rule_id=rule.id, version=rule.version, definition_json=_rule_payload(rule), published_by=actor_id, + )) + db.session.commit() + return _rule_payload(rule) + + +def _external_payload(mapping: FreightRpaOnhandExternalMapping) -> dict[str, Any]: + return { + 'id': mapping.id, 'source_id': mapping.source_id, + 'freight_warehouse_id': mapping.freight_warehouse_id, 'external_system_code': mapping.external_system_code, + 'external_organization_code': mapping.external_organization_code, 'external_site_code': mapping.external_site_code, + 'external_warehouse_code': mapping.external_warehouse_code, 'external_warehouse_name': mapping.external_warehouse_name, + 'in_transit_warehouse_code': mapping.in_transit_warehouse_code, + 'enabled': bool(mapping.enabled), 'version': mapping.version, + } + + +def list_external_mappings() -> list[dict[str, Any]]: + """列出库存源到外部系统仓库的映射,不执行调拨判断。""" + return [_external_payload(item) for item in FreightRpaOnhandExternalMapping.query.order_by(FreightRpaOnhandExternalMapping.id).all()] + + +def delete_external_mapping(mapping_id: int) -> None: + """删除错误的外部仓库映射;历史文件和任务不回写此实时配置。""" + record = db.session.get(FreightRpaOnhandExternalMapping, mapping_id) + if record is None: + raise NotFoundError('External mapping not found', code='SHIPPING.ONHAND_EXTERNAL_MAPPING_NOT_FOUND') + db.session.delete(record) + db.session.commit() + + +def save_external_mapping(data: dict[str, Any], *, actor_id: int | None, mapping_id: int | None = None) -> dict[str, Any]: + """创建或更新精确/默认外部系统映射。""" + record = db.session.get(FreightRpaOnhandExternalMapping, mapping_id) if mapping_id else None + if mapping_id and record is None: + raise NotFoundError('External mapping not found', code='SHIPPING.ONHAND_EXTERNAL_MAPPING_NOT_FOUND') + try: + source_id = int(data.get('source_id')) + except (TypeError, ValueError) as exc: + raise ValidationError('source_id is required') from exc + if db.session.get(FreightRpaSource, source_id) is None: + raise ValidationError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') + record = record or FreightRpaOnhandExternalMapping(source_id=source_id, external_system_code='', external_warehouse_code='', external_warehouse_name='') + record.source_id = source_id + # 货代仓库改为可选维度:inventory_match 源按「收料文件仓库 == 货代仓库」匹配映射行, + # 空值即「空库位」默认映射行;归一化为大写以与收料仓库值精确比对。 + record.freight_warehouse_id = str(_text(data, 'freight_warehouse_id') or '').upper() or None + # 在途仓编码是在途调拨拨出库位来源(DefaultRouteResolver),保存端必填并大写归一。 + record.in_transit_warehouse_code = str(_text(data, 'in_transit_warehouse_code', required=True)).upper() + record.external_system_code = str(_text(data, 'external_system_code', required=True)).upper() + record.external_organization_code = _text(data, 'external_organization_code') + record.external_site_code = _text(data, 'external_site_code') + record.external_warehouse_code = str(_text(data, 'external_warehouse_code', required=True)).upper() + record.external_warehouse_name = str(_text(data, 'external_warehouse_name', required=True)) + record.enabled = _bool(data, 'enabled', bool(record.enabled) if mapping_id else True) + record.updated_by = actor_id + if not mapping_id: + record.created_by = actor_id + db.session.add(record) + try: + db.session.commit() + except Exception as exc: + db.session.rollback() + raise ConflictError('Active external mapping already exists for this freight identity', code='SHIPPING.ONHAND_EXTERNAL_MAPPING_CONFLICT') from exc + return _external_payload(record) diff --git a/backend/app/services/agent_registry/data/catalog_manifest.yaml b/backend/app/services/agent_registry/data/catalog_manifest.yaml index bee6f5d7..feb6544a 100644 --- a/backend/app/services/agent_registry/data/catalog_manifest.yaml +++ b/backend/app/services/agent_registry/data/catalog_manifest.yaml @@ -162,6 +162,8 @@ agent_types: handler_config_schema: {} in_transit_transfer: label: 在途仓自动调拨 + # 调拨类型来自平台配置(管理端「在途调拨类型」维护,GET /transfer-types 下发), + # 本清单与提示词不硬编码类型列表;Dify 平台侧如有副本需人工同步。 conversation_mode_default: task_chat runtime_provider_default: hybrid models: diff --git a/backend/app/services/agent_registry/handlers/in_transit_transfer.py b/backend/app/services/agent_registry/handlers/in_transit_transfer.py index ead469d3..4a14eebb 100644 --- a/backend/app/services/agent_registry/handlers/in_transit_transfer.py +++ b/backend/app/services/agent_registry/handlers/in_transit_transfer.py @@ -6,6 +6,9 @@ 输出结构化 message.completed 卡片,并经 Run API 恢复;本 Handler 负责 hybrid 运行时的上下文钩子与领域 UI State 扩展位(transfer_ui_state),暂不注入 Dify Chatflow 生命周期。 + 【调拨类型语义 2026-10-14】调拨类型来自平台配置(管理端「在途调拨类型」 + 维护,`GET /api/in-transit-transfer/transfer-types` 下发);提示词与本 + Handler 一律不硬编码类型列表,Dify 平台侧如有副本需人工同步。 """ from __future__ import annotations diff --git a/backend/app/services/file_assets/storage.py b/backend/app/services/file_assets/storage.py index 3788aa1c..6fbdec82 100644 --- a/backend/app/services/file_assets/storage.py +++ b/backend/app/services/file_assets/storage.py @@ -3,7 +3,8 @@ backend/app/services/file_assets/storage.py 用途:私有 MinIO 业务文件存储适配层(与 agent-guides 公开 bucket 隔离)。 依赖:minio、app.core.config.settings、app.core.errors.ServiceUnavailableError。 -逻辑:由 file_assets.service 调用;禁止 public-read policy 与本地静默回退;读写删失败统一抛 503。 +逻辑:由 file_assets.service 与调拨证据清单调用;禁止 public-read policy 与本地静默回退; + 读写删失败统一抛 503。预签下载可附带 response-content-disposition,避免保存名落成对象键。 """ from __future__ import annotations @@ -119,13 +120,39 @@ class FileAssetStorage: except S3Error: return False - def presigned_get_url(self, storage_key: str, *, expires_seconds: int) -> str: - """生成短期受控下载 URL。""" + def presigned_get_url( + self, + storage_key: str, + *, + expires_seconds: int, + download_name: str | None = None, + ) -> str: + """生成短期受控下载 URL。 + + 核心逻辑:对象键常为内容哈希,浏览器会把它当成保存名。 + download_name 非空时把 response-content-disposition 签进 URL, + 让保存对话框使用业务文件名。预览地址不要传这个参数。 + + Args: + storage_key: MinIO 对象键。 + expires_seconds: 链接有效秒数,短于 60 秒时抬到 60。 + download_name: 附件保存名;只接受调用方已洗净的文件名。 + + Returns: + 带过期签名的 GET URL。 + """ self._ensure_bucket_exists() + response_headers = None + if download_name: + safe = download_name.replace('"', '').replace('\\', '').replace('\r', '').replace('\n', '') + response_headers = { + 'response-content-disposition': f'attachment; filename="{safe}"', + } return self.client.presigned_get_object( self.bucket_name, storage_key, expires=timedelta(seconds=max(int(expires_seconds or 60), 60)), + response_headers=response_headers, ) diff --git a/backend/app/services/freight_rpa/__init__.py b/backend/app/services/freight_rpa/__init__.py new file mode 100644 index 00000000..b4ac8792 --- /dev/null +++ b/backend/app/services/freight_rpa/__init__.py @@ -0,0 +1 @@ +"""货代 RPA 模块根:承载 freight_rpa 域代码(common/onhand/inbound/upload)。""" diff --git a/backend/app/services/freight_rpa/common/__init__.py b/backend/app/services/freight_rpa/common/__init__.py new file mode 100644 index 00000000..d51d482a --- /dev/null +++ b/backend/app/services/freight_rpa/common/__init__.py @@ -0,0 +1 @@ +"""common:域中立件(跨 RPA Worker 共用、不依赖具体业务域)。""" diff --git a/backend/app/services/freight_rpa/common/callback_sinks.py b/backend/app/services/freight_rpa/common/callback_sinks.py new file mode 100644 index 00000000..5c1e02b6 --- /dev/null +++ b/backend/app/services/freight_rpa/common/callback_sinks.py @@ -0,0 +1,58 @@ +""" +services/freight_rpa/common/callback_sinks.py + +用途:RPA 回调「进度类」sink 注册表——freight_rpa 侧的回调分发缝(批次 B Task 6 起 + 与文件事实分发分工:文件/报表就绪类回调走 freight_rpa.reports.dispatch. + dispatch_report_fact——归档入口先 db.session.commit() 再投递 ReportFact, + kind 未注册同样 404 FREIGHT_RPA.SINK_NOT_REGISTERED;进度类 kind + (inbound-unit-progress / inbound-batch-progress / onhand-batch-claimed 等) + 仍走本模块的 register_sink / dispatch_sink,不改 envelope)。 +依赖:app.core.errors.AppError。 +逻辑:Worker 回调进入 /api/freight-rpa/* 蓝图后,进度类端点按 kind 分发到 + 组合根(create_app / api 层)注册的业务处理器;未注册的 kind 显式 404, + 绝不静默吞回调。Task 9/10 落地 workflow_protocol / report_archive 时由 + 组合根调用 register_sink 注入真实业务持久化处理器。 +""" + +from __future__ import annotations + +from typing import Any, Callable + +from app.core.errors import AppError + +_SINKS: dict[str, Callable[..., Any]] = {} + + +def register_sink(kind: str, handler: Callable[..., Any]) -> None: + """ + 注册一个回调 sink 处理器(由组合根在应用启动时调用)。 + + Args: + kind: 回调种类,命名 = 回调路由名去前缀(如 "onhand-ready"、 + "onhand-configuration-test-complete");同一 kind 重复注册为覆盖。 + handler: 业务处理器;契约:接收回调载荷的关键字参数并返回可 jsonify 的业务结果。 + """ + _SINKS[kind] = handler + + +def dispatch_sink(kind: str, **payload: Any) -> Any: + """ + 按 kind 分发回调载荷到已注册 sink。 + + Args: + kind: register_sink 注册过的回调种类。 + payload: 回调载荷键值对;键必须为合法 Python 标识符(回调 schema 均为 snake_case)。 + Returns: + handler 的返回值(业务结果 dict,由蓝图 jsonify)。 + Raises: + AppError: code=FREIGHT_RPA.SINK_NOT_REGISTERED、http_status=404——kind 未注册时 + 显式失败(Task 9/10 注册真实 sink 前的既定语义)。 + """ + handler = _SINKS.get(kind) + if handler is None: + raise AppError( + code='FREIGHT_RPA.SINK_NOT_REGISTERED', + message=f'No callback sink registered for kind: {kind}', + http_status=404, + ) + return handler(**payload) diff --git a/backend/app/services/shipping_notice/credential_crypto.py b/backend/app/services/freight_rpa/common/credential_crypto.py similarity index 97% rename from backend/app/services/shipping_notice/credential_crypto.py rename to backend/app/services/freight_rpa/common/credential_crypto.py index ab1bfefb..4f860191 100644 --- a/backend/app/services/shipping_notice/credential_crypto.py +++ b/backend/app/services/freight_rpa/common/credential_crypto.py @@ -1,5 +1,5 @@ """ -services/shipping_notice/credential_crypto.py +services/freight_rpa/common/credential_crypto.py 用途:加密和解密库存 RPA Profile 的登录凭据(委托通用 core 模块,仅固定本域密钥键与错误码)。 依赖:app.core.credential_crypto(Fernet 加解密);调用方仅保存密文,不将凭据写入日志或 API 响应。 diff --git a/backend/app/services/freight_rpa/common/report_audit.py b/backend/app/services/freight_rpa/common/report_audit.py new file mode 100644 index 00000000..3d18351b --- /dev/null +++ b/backend/app/services/freight_rpa/common/report_audit.py @@ -0,0 +1,384 @@ +"""freight_rpa/common/report_audit.py + +用途:货代 RPA 域(inbound 回调归档、保留期清理、通知投递)写入 + ShippingAuditEvent 统一审计账本的唯一入口(批次 B Task 6)。 +依赖:app.models.ShippingAuditEvent(允许 import 模型)、app.core.errors. + ValidationError、SQLAlchemy 会话(app.db)。 +逻辑:替代此前对 app.services.shipping_notice.audit_service 的依赖——freight_rpa + 包禁止 import app.services.shipping_notice.*(import 边界由 tests/services/ + freight_rpa/test_import_boundary.py 的空白名单锁定),故本模块以与 + append_shipping_audit_event 相同的关键字面直接写同一个 ShippingAuditEvent + 模型,事件名(shipping_inbound_rpa_callback_received / + shipping_inbound_report_archived 等)与聚合键保持不变,避免审计查询断档。 + 与 audit_service 的有意差异(均为本域受控场景): + (1)before/after 快照不做白名单投影——本域快照键均为受控诊断键 + (status/error_code/sha256/file_size 等),原样入 snapshot 列; + (2)不做 XFA 加密完整快照(本域无敏感完整载荷); + (3)保留期恒为 None(货代统一审计账本永久保留); + (4)event_hash 以本地稳定哈希对核心字段集合计算,previous_event_hash + 取同聚合最新一条已 flush 事件的 event_hash(链结构与 audit_service 同构)。 + 本模块不提交事务,由调用方与业务写入同一事务提交;写入失败时业务不得 commit。 +""" + +from __future__ import annotations + +import hashlib +import json +from datetime import datetime +from typing import Any + +from app import db +from app.core.errors import ValidationError +from app.models import ShippingAuditEvent + +# 与 audit_service 同源的 actor/result 白名单(模型 CHECK 约束同集)。 +_ALLOWED_ACTOR_TYPES = frozenset({'user', 'system', 'rpa', 'chatflow', 'admin', 'worker'}) +_ALLOWED_RESULTS = frozenset({'success', 'failure', 'rejected', 'ignored'}) + +# 审计元数据/快照禁止键本地冻结子集(凭据 / 正文 / URL 类;自 +# shipping_notice.progress_audit_contract.AUDIT_FORBIDDEN_KEYS 裁剪,仅供本域防呆)。 +_FORBIDDEN_AUDIT_KEYS = frozenset({ + 'api_key', + 'api_base_url', + 'authorization', + 'body', + 'content', + 'document_text', + 'email_body', + 'minio', + 'object_key', + 'object_url', + 'password', + 'prompt', + 'provider_config', + 'quote', + 'raw_content', + 'raw_output', + 'secret', + 'token', + 'url', + 'user_agent', +}) + + +def _is_forbidden_audit_key(key: str) -> bool: + """键名大小写不敏感命中本地禁止键集合(与 audit_service 判定同构)。""" + return str(key or '').strip().lower() in _FORBIDDEN_AUDIT_KEYS + + +def _collect_forbidden_keys(payload: Any, *, path: str = '') -> list[str]: + """ + 递归收集命中敏感黑名单的键路径(dict/list 均遍历,嵌套路径稳定拼接)。 + + Returns: + 命中键路径列表(调用方排序后入 ValidationError.details)。 + """ + found: list[str] = [] + if isinstance(payload, dict): + for key, child in payload.items(): + key_text = str(key) + child_path = f'{path}.{key_text}' if path else key_text + if _is_forbidden_audit_key(key_text): + found.append(child_path) + found.extend(_collect_forbidden_keys(child, path=child_path)) + elif isinstance(payload, list): + for index, child in enumerate(payload): + found.extend(_collect_forbidden_keys(child, path=f'{path}[{index}]')) + return found + + +def _sanitize_metadata(metadata: dict[str, Any] | None) -> dict[str, Any]: + """验证元数据仅含脱敏诊断事实,阻断凭据、正文与 URL 进入审计账本。""" + safe = dict(metadata or {}) + forbidden = _collect_forbidden_keys(safe) + if forbidden: + raise ValidationError( + 'RPA report audit metadata contains forbidden keys', + code='SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN', + details={'forbidden_keys': sorted(set(forbidden))}, + ) + return safe + + +def _sanitize_refs(refs: list[dict[str, Any]] | None, *, field_name: str) -> list[dict[str, Any]] | None: + """校验证据/产物引用仅含标识类字段,拒绝 URL 与正文。""" + if refs is None: + return None + if not isinstance(refs, list): + raise ValidationError( + f'RPA report audit {field_name} must be a list', + code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN', + ) + forbidden = _collect_forbidden_keys(refs) + if forbidden: + raise ValidationError( + f'RPA report audit {field_name} contains forbidden keys', + code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN', + details={'forbidden_keys': sorted(set(forbidden))}, + ) + return refs + + +def _stable_hash(value: Any) -> str: + """对受控状态对象生成 SHA-256(排序键 + 紧凑分隔符,与 audit_service 同构)。""" + encoded = json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), default=str) + return hashlib.sha256(encoded.encode('ascii')).hexdigest() + + +def _snapshot_diff(before: Any, after: Any) -> dict[str, Any] | None: + """ + 计算前后快照顶层差异(changed/added/removed 三段;无变化返回 None)。 + + 核心逻辑:值均为受控诊断键原样比较(本域快照不做白名单投影,见模块 docstring)。 + """ + left = before if isinstance(before, dict) else {} + right = after if isinstance(after, dict) else {} + changed: dict[str, Any] = {} + added: dict[str, Any] = {} + removed: dict[str, Any] = {} + for key in sorted(set(left) | set(right)): + if key in left and key in right: + if left[key] != right[key]: + changed[key] = {'from': left[key], 'to': right[key]} + elif key in right: + added[key] = right[key] + else: + removed[key] = left[key] + if not changed and not added and not removed: + return None + return {'changed': changed, 'added': added, 'removed': removed} + + +def _resolve_previous_event_hash(*, aggregate_type: str, aggregate_id: str) -> str | None: + """ + 读取同聚合最新一条事件的 event_hash 作为哈希链前驱。 + + 核心逻辑:按 id 倒序取一条;缺失或旧数据无 hash 时返回 None(链从本条起锚)。 + 调用方须先 flush 保证同事务先前事件可查(与 audit_service 顺序一致)。 + """ + previous = ( + ShippingAuditEvent.query + .filter_by(aggregate_type=str(aggregate_type)[:64], aggregate_id=str(aggregate_id)[:128]) + .order_by(ShippingAuditEvent.id.desc()) + .first() + ) + if previous is None: + return None + return str(previous.event_hash) if previous.event_hash else None + + +def _event_hash_payload( + *, + event_type: str, + aggregate_type: str, + aggregate_id: str, + action: str | None, + result: str | None, + reason_code: str | None, + run_no: str | None, + task_no: str | None, + operation_id: str | None, + request_id: str | None, + actor_type: str, + actor_id: str | None, + before_snapshot: dict[str, Any] | None, + after_snapshot: dict[str, Any] | None, + diff_json: dict[str, Any] | None, + previous_event_hash: str | None, + sensitivity_level: str | None, +) -> dict[str, Any]: + """组装参与 event_hash 计算的稳定字段集合(字段集与 audit_snapshot_service 同构)。""" + return { + 'event_type': event_type, + 'aggregate_type': aggregate_type, + 'aggregate_id': aggregate_id, + 'action': action, + 'result': result, + 'reason_code': reason_code, + 'workflow_id': None, + 'workflow_item_id': None, + 'workflow_item_version_id': None, + 'version_no': None, + 'run_no': run_no, + 'document_id': None, + 'review_case_no': None, + 'task_no': task_no, + 'operation_id': operation_id, + 'request_id': request_id, + 'actor_type': actor_type, + 'actor_id': actor_id, + 'before_snapshot': before_snapshot, + 'after_snapshot': after_snapshot, + 'diff': diff_json, + 'previous_event_hash': previous_event_hash, + 'sensitivity_level': sensitivity_level, + } + + +def append_rpa_report_event( + *, + event_type: str, + aggregate_type: str, + aggregate_id: str, + run_no: str | None = None, + task_no: str | None = None, + intake_no: str | None = None, + actor_type: str = 'system', + actor_id: str | int | None = None, + actor_role: str | None = None, + actor_display: str | None = None, + request_id: str | None = None, + operation_id: str | None = None, + correlation_id: str | None = None, + source: str | None = None, + result: str | None = None, + error_code: str | None = None, + conversation_id: str | None = None, + unit_id: str | int | None = None, + document_id: str | int | None = None, + review_case_no: str | None = None, + owner_user_id: str | int | None = None, + attempt_no: int | None = None, + action: str | None = None, + reason_code: str | None = None, + reason: str | None = None, + before: Any = None, + after: Any = None, + evidence_refs: list[dict[str, Any]] | None = None, + artifact_refs: list[dict[str, Any]] | None = None, + context_refs: dict[str, Any] | None = None, + metadata: dict[str, Any] | None = None, + sensitivity_level: str | None = None, +) -> ShippingAuditEvent: + """ + 追加一条货代 RPA 审计事实(freight_rpa 域唯一审计写入口)。 + + 用途:与 shipping_notice.audit_service.append_shipping_audit_event 关键字兼容的 + RPA 域替代品——调用方(report_archive 等)自 audit_service 迁移时仅改函数名, + 事件名与聚合键原样保持,避免审计查询断档(见模块 docstring 的四处有意差异)。 + 核心逻辑:[STEP 1] 校验 actor_type/result 白名单 + 元数据/引用脱敏; + [STEP 2] 计算 before/after 稳定哈希与顶层 diff; + [STEP 3] flush 后取同聚合前驱 event_hash,对核心字段集合计算 event_hash; + [STEP 4] 写入 ShippingAuditEvent(保留期恒 None=永久)并 flush,不 commit。 + Args: + event_type: 稳定业务事件名(如 shipping_inbound_rpa_callback_received); + 禁止传入用户自由文本。 + aggregate_type/aggregate_id: 业务聚合类型与稳定编号(软引用,不使用外键)。 + run_no/task_no: 排程 run / task 软引用(截断 64)。 + actor_type/actor_id/actor_role/actor_display: 操作主体四元组 + (actor_type 必须在 user/system/rpa/chatflow/admin/worker 内)。 + result: success / failure / rejected / ignored(白名单外抛 ValidationError)。 + before/after: 受控状态快照(本域不做白名单投影,键须为诊断类,禁敏感键)。 + evidence_refs/artifact_refs: FileAsset ID、SHA-256 等标识引用;禁止 URL/正文。 + metadata: 仅允许原因码、计数等脱敏诊断事实(禁止键见 _FORBIDDEN_AUDIT_KEYS)。 + unit_id/document_id/review_case_no/owner_user_id/attempt_no: 业务关联软引用。 + action/reason_code/reason/error_code/conversation_id/correlation_id/source/ + request_id/operation_id/intake_no/sensitivity_level: 追溯与分级补充字段。 + Returns: + 尚未提交的 ShippingAuditEvent,由调用方与业务写入在同一事务提交。 + Raises: + ValidationError: actor/result 非法,或元数据/快照引用包含正文、凭据等敏感键。 + """ + # [STEP 1] 校验与脱敏(错误码与 audit_service 共用,避免同义分裂)。 + if actor_type not in _ALLOWED_ACTOR_TYPES: + raise ValidationError('Invalid shipping audit actor type', code='SHIPPING_NOTICE.AUDIT_ACTOR_INVALID') + if result is not None and result not in _ALLOWED_RESULTS: + raise ValidationError('Invalid shipping audit result', code='SHIPPING_NOTICE.AUDIT_RESULT_INVALID') + safe_metadata = _sanitize_metadata(metadata) + if before is not None and _collect_forbidden_keys(before): + raise ValidationError( + 'RPA report audit snapshot contains forbidden keys', + code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN', + details={'forbidden_keys': sorted(set(_collect_forbidden_keys(before)))}, + ) + if after is not None and _collect_forbidden_keys(after): + raise ValidationError( + 'RPA report audit snapshot contains forbidden keys', + code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN', + details={'forbidden_keys': sorted(set(_collect_forbidden_keys(after)))}, + ) + + # [STEP 2] 快照哈希与顶层差异。 + before_snapshot = before if isinstance(before, dict) else None + after_snapshot = after if isinstance(after, dict) else None + diff_json = _snapshot_diff(before, after) + + # [STEP 3] 哈希链:flush 保证同事务先前事件可查,再取前驱并计算本条 event_hash。 + db.session.flush() + previous_event_hash = _resolve_previous_event_hash( + aggregate_type=str(aggregate_type)[:64], aggregate_id=str(aggregate_id)[:128], + ) + resolved_run_no = str(run_no)[:64] if run_no else None + resolved_task_no = str(task_no)[:64] if task_no else None + resolved_actor_id = str(actor_id)[:128] if actor_id is not None else None + resolved_operation_id = str(operation_id)[:64] if operation_id else None + resolved_request_id = str(request_id)[:64] if request_id else None + resolved_sensitivity = str(sensitivity_level)[:16] if sensitivity_level else None + event_hash = _stable_hash(_event_hash_payload( + event_type=str(event_type)[:64], + aggregate_type=str(aggregate_type)[:64], + aggregate_id=str(aggregate_id)[:128], + action=str(action)[:64] if action else None, + result=result, + reason_code=str(reason_code)[:128] if reason_code else None, + run_no=resolved_run_no, + task_no=resolved_task_no, + operation_id=resolved_operation_id, + request_id=resolved_request_id, + actor_type=actor_type, + actor_id=resolved_actor_id, + before_snapshot=before_snapshot, + after_snapshot=after_snapshot, + diff_json=diff_json, + previous_event_hash=previous_event_hash, + sensitivity_level=resolved_sensitivity, + )) + + # [STEP 4] 写入事件(保留期恒 None=永久保留;不 commit,由调用方保证原子性)。 + event = ShippingAuditEvent( + event_type=str(event_type)[:64], + aggregate_type=str(aggregate_type)[:64], + aggregate_id=str(aggregate_id)[:128], + run_no=resolved_run_no, + task_no=resolved_task_no, + intake_no=str(intake_no)[:64] if intake_no else None, + actor_type=actor_type, + actor_id=resolved_actor_id, + actor_role=str(actor_role)[:64] if actor_role else None, + actor_display=str(actor_display)[:128] if actor_display else None, + request_id=resolved_request_id, + operation_id=resolved_operation_id, + correlation_id=str(correlation_id)[:64] if correlation_id else None, + source=str(source)[:32] if source else None, + result=result, + error_code=str(error_code)[:64] if error_code else None, + conversation_id=str(conversation_id)[:100] if conversation_id else None, + unit_id=str(unit_id)[:64] if unit_id is not None else None, + document_id=str(document_id)[:64] if document_id is not None else None, + review_case_no=str(review_case_no)[:64] if review_case_no else None, + owner_user_id=str(owner_user_id)[:64] if owner_user_id is not None else None, + attempt_no=int(attempt_no) if attempt_no is not None else None, + action=str(action)[:64] if action else None, + reason_code=str(reason_code)[:128] if reason_code else None, + reason=str(reason)[:2000] if reason else None, + before_hash=_stable_hash(before_snapshot) if before_snapshot is not None else None, + after_hash=_stable_hash(after_snapshot) if after_snapshot is not None else None, + before_snapshot_json=before_snapshot, + after_snapshot_json=after_snapshot, + diff_json=diff_json, + previous_event_hash=previous_event_hash, + event_hash=event_hash, + sensitivity_level=resolved_sensitivity, + evidence_refs_json=_sanitize_refs(evidence_refs, field_name='evidence_refs'), + artifact_refs_json=_sanitize_refs(artifact_refs, field_name='artifact_refs'), + context_refs_json=dict(context_refs or {}) if context_refs else None, + metadata_json=safe_metadata, + retention_expires_at=None, + ) + db.session.add(event) + db.session.flush() + return event + + +# 供测试与契约引用的冻结黑名单导出(与 audit_service.FORBIDDEN_AUDIT_METADATA_KEYS 对应的本地子集)。 +RPA_FORBIDDEN_AUDIT_KEYS = _FORBIDDEN_AUDIT_KEYS diff --git a/backend/app/services/freight_rpa/common/rpa_runtime.py b/backend/app/services/freight_rpa/common/rpa_runtime.py new file mode 100644 index 00000000..1652c658 --- /dev/null +++ b/backend/app/services/freight_rpa/common/rpa_runtime.py @@ -0,0 +1,36 @@ +""" +services/freight_rpa/common/rpa_runtime.py + +用途:RPA 运行模式(browser/mock)的展示助手——把任务回调记录或后端配置规范化为前端安全摘要。 +依赖:Flask current_app 配置(FREIGHT_RPA_WORKER_MOCK);不依赖目录 IO 与 Worker 文件契约。 +逻辑:由 shipping_notice.query_service(任务序列化注入 rpa_runtime 摘要)、 + 同包 worker_heartbeat(mock 模式下跳过真实 Worker 在线探测)消费; + 仅做展示归一,不承载触发/回调逻辑。 +""" + +from __future__ import annotations + +from typing import Any + +from flask import current_app + + +def _runtime_summary(mode: str) -> dict[str, str | bool]: + """将 browser/mock 规范化为前端安全展示摘要。""" + normalized = "mock" if str(mode or "").strip().lower() == "mock" else "browser" + mock_enabled = normalized == "mock" + return { + "mode": normalized, + "label": "Mock RPA" if mock_enabled else "真实 RPA", + "mock": mock_enabled, + } + + +def rpa_runtime_mode(runtime: dict[str, Any] | None = None) -> dict[str, str | bool]: + """返回 RPA 运行模式摘要;优先使用任务最近一次回调实际模式,兜底读取当前后端配置。""" + if isinstance(runtime, dict): + mode = str(runtime.get("mode") or runtime.get("rpa_mode") or "").strip().lower() + if mode in {"browser", "mock"}: + return _runtime_summary(mode) + raw = str(current_app.config.get("FREIGHT_RPA_WORKER_MOCK", "false") or "false").strip().lower() + return _runtime_summary("mock" if raw in {"1", "true", "yes", "on"} else "browser") diff --git a/backend/app/services/shipping_notice/rpa_worker_heartbeat.py b/backend/app/services/freight_rpa/common/worker_heartbeat.py similarity index 78% rename from backend/app/services/shipping_notice/rpa_worker_heartbeat.py rename to backend/app/services/freight_rpa/common/worker_heartbeat.py index 7868b46a..9c925a52 100644 --- a/backend/app/services/shipping_notice/rpa_worker_heartbeat.py +++ b/backend/app/services/freight_rpa/common/worker_heartbeat.py @@ -1,11 +1,14 @@ """ -services/shipping_notice/rpa_worker_heartbeat.py +services/freight_rpa/common/worker_heartbeat.py -用途:货代 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 心跳徽标。 +用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传/入站/出站就绪检查与状态查询。 +依赖:Flask current_app、redis_client、同包 rpa_runtime(mock 模式)、 + freight_rpa.onhand.trigger_io(onhand trigger 目录)、 + freight_rpa.upload.trigger_io(上传目录)、 + freight_rpa.inbound.trigger_io(inbound trigger 目录)、 + freight_rpa.outbound.trigger_io(outbound trigger 目录)。 +逻辑:Windows Worker 调 POST /api/freight-rpa/heartbeat;写 onhand/upload/inbound/outbound trigger 前强制就绪检查; + 管理端 /rpa-workers/status?scope=onhand|inbound|outbound 展示对应 Worker 心跳徽标。 """ from __future__ import annotations @@ -24,18 +27,25 @@ from flask import current_app from app.core.config.settings import _normalize_env_name from app.core.errors import ServiceUnavailableError -from app.services.shipping_notice.rpa import inventory_trigger_dir, rpa_runtime_mode +from app.services.freight_rpa.onhand.trigger_io import onhand_trigger_dir +from .rpa_runtime import rpa_runtime_mode logger = logging.getLogger(__name__) RPA_WORKER_OFFLINE_MESSAGE = "RPA Worker 未在线,请启动 Windows RPA 服务后重试" RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE = "RPA Worker 心跳存储不可用,请检查 Redis 连接" 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" +# [PROMPT_UPDATE] 2026-10-16 freight_rpa 解耦批次 R:能力串随 Worker 侧(Task 12)切换—— +# inventory_export→onhand_export、receipt_export→inbound_export;上传能力为 freight_rpa_upload; +# worker_id 后缀判定 -receipt→-inbound(ps1 注入值随发布窗口改配,见 cutover runbook)。 +ONHAND_EXPORT_CAPABILITY = "onhand_export" +FREIGHT_RPA_UPLOAD_CAPABILITY = "freight_rpa_upload" +INBOUND_EXPORT_CAPABILITY = "inbound_export" +OUTBOUND_EXPORT_CAPABILITY = "outbound_export" +# inbound Worker 由 start_inbound_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-inbound。 +INBOUND_WORKER_ID_SUFFIX = "-inbound" +# outbound Worker 由 start_outbound_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-outbound。 +OUTBOUND_WORKER_ID_SUFFIX = "-outbound" _REDIS_INDEX_KEY = "shipping:rpa:heartbeat:index" _REDIS_WORKER_KEY_PREFIX = "shipping:rpa:heartbeat:worker:" _MEMORY_STORE: dict[str, dict[str, Any]] = {} @@ -51,8 +61,10 @@ _REASON_USER_HINTS: dict[str, str] = { "shared_scope_mismatch": "共享目录 scope 与后端配置不一致", "trigger_dir_not_writable": "trigger 目录不可写", "environment_mismatch": "Worker 环境与后端环境不一致", - "missing_inventory_export_capability": "Worker 未声明 inventory_export 能力", - "missing_freight_upload_capability": "Worker 未声明 freight_upload 能力", + "missing_onhand_export_capability": "Worker 未声明 onhand_export 能力", + "missing_inbound_export_capability": "Worker 未声明 inbound_export 能力", + "missing_outbound_export_capability": "Worker 未声明 outbound_export 能力", + "missing_freight_rpa_upload_capability": "Worker 未声明 freight_rpa_upload 能力", "credential_key_missing": "未配置 FREIGHT_RPA_CREDENTIAL_KEY", "upload_queue_dir_not_configured": "未配置货代上传队列目录", "upload_queue_dir_not_accessible": "货代上传队列目录不可访问", @@ -139,7 +151,7 @@ def shared_scope_id() -> str: explicit = _config_str("FREIGHT_RPA_SHARED_SCOPE_ID", "") if explicit: return explicit - trigger_dir = inventory_trigger_dir() + trigger_dir = onhand_trigger_dir() if not trigger_dir: return "" for part in Path(trigger_dir).parts: @@ -362,7 +374,7 @@ def _verify_shared_trigger_mount( trigger_dir: Path | None, *, require_sentinel: bool = True, ) -> tuple[bool, list[str]]: """ - 校验 trigger 目录可写;默认要求共享哨兵(库存与收料同口径)。 + 校验 trigger 目录可写;默认要求共享哨兵(库存与入站同口径)。 Args: trigger_dir: 共享 trigger 目录。 @@ -400,18 +412,39 @@ def _verify_shared_trigger_mount( return not reasons, reasons -def is_receipt_rpa_worker(worker: dict[str, Any]) -> bool: +def is_inbound_rpa_worker(worker: dict[str, Any]) -> bool: """ - 判断心跳是否来自收料 Worker。 + 判断心跳是否来自 inbound(原收料)Worker。 - 优先认 <主机名>-receipt(ps1 注入);兼容未注入 FREIGHT_RPA_WORKER_ID、 - 回退为 <主机名>- 的进程——用心跳 trigger_dir 与收料目录对齐判定。 + 优先认 <主机名>-inbound(ps1 注入);兼容未注入 FREIGHT_RPA_WORKER_ID、 + 回退为 <主机名>- 的进程——用心跳 trigger_dir 与 inbound 目录对齐判定。 """ - if str(worker.get("worker_id") or "").strip().lower().endswith(RECEIPT_WORKER_ID_SUFFIX): + if str(worker.get("worker_id") or "").strip().lower().endswith(INBOUND_WORKER_ID_SUFFIX): return True - from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir + from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir - expected = receipt_trigger_dir() + expected = inbound_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 is_outbound_rpa_worker(worker: dict[str, Any]) -> bool: + """ + 判断心跳是否来自 outbound Worker。 + + 优先认 <主机名>-outbound(ps1 注入);兼容未注入 FREIGHT_RPA_WORKER_ID、 + 回退为 <主机名>- 的进程——用心跳 trigger_dir 与 outbound 目录对齐判定。 + """ + if str(worker.get("worker_id") or "").strip().lower().endswith(OUTBOUND_WORKER_ID_SUFFIX): + return True + from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir + + expected = outbound_trigger_dir() actual = str(worker.get("trigger_dir") or "").strip() if expected is None or not actual: return False @@ -437,7 +470,7 @@ def _worker_is_eligible( backend_env: str, ttl_seconds: int, now: float, - required_capability: str = INVENTORY_EXPORT_CAPABILITY, + required_capability: str = ONHAND_EXPORT_CAPABILITY, ) -> tuple[bool, list[str]]: """ 判断单 Worker 是否满足心跳新鲜度、能力声明与环境/scope 隔离。 @@ -447,7 +480,7 @@ def _worker_is_eligible( backend_env: 后端归一环境(dev/test/prod)。 ttl_seconds: 心跳 TTL。 now: 当前 epoch 秒。 - required_capability: 必选能力(inventory_export / freight_upload)。 + required_capability: 必选能力(onhand_export / inbound_export / outbound_export / freight_rpa_upload)。 Returns: (是否合格, 不合格原因列表)。 @@ -461,10 +494,7 @@ def _worker_is_eligible( capabilities = _parse_capabilities(worker.get("capabilities")) if required_capability and required_capability not in capabilities: - if required_capability == FREIGHT_UPLOAD_CAPABILITY: - reasons.append("missing_freight_upload_capability") - else: - reasons.append("missing_inventory_export_capability") + reasons.append(_missing_capability_reason(required_capability)) worker_env = str(worker.get("environment") or "").strip().lower() if worker_env and worker_env != backend_env: @@ -477,6 +507,11 @@ def _worker_is_eligible( return not reasons, reasons +def _missing_capability_reason(required_capability: str) -> str: + """按必选能力生成缺失原因码(onhand_export / inbound_export / outbound_export / freight_rpa_upload)。""" + return f"missing_{required_capability}_capability" + + def _summarize_reasons(reasons: list[str]) -> str: hints: list[str] = [] for reason in reasons: @@ -512,8 +547,8 @@ def _check_rpa_worker_ready_for_capability( trigger_dir: 待校验的共享 trigger 目录。 required_capability: 必选 Worker 能力;空字符串表示不校验能力。 extra_reasons: 调用方预检附加原因(凭据/队列等)。 - worker_predicate: 可选过滤(如仅收料 Worker);不匹配的心跳不进入列表。 - require_sentinel: 是否要求共享哨兵(库存/收料同口径均 True)。 + worker_predicate: 可选过滤(如仅入站 Worker);不匹配的心跳不进入列表。 + require_sentinel: 是否要求共享哨兵(库存/入站同口径均 True)。 Returns: RpaWorkerReadiness。 @@ -601,7 +636,7 @@ def _check_rpa_worker_ready_for_capability( message, detail_message = "ready", "ready" else: failure = RpaWorkerReadiness(ready=False, message="", reasons=sorted(set(reasons))) - if required_capability == FREIGHT_UPLOAD_CAPABILITY: + if required_capability == FREIGHT_RPA_UPLOAD_CAPABILITY: detail = _summarize_reasons(failure.reasons) message = RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE detail_message = f"{message}({detail})" if detail else message @@ -623,41 +658,41 @@ def check_inventory_rpa_worker_ready() -> RpaWorkerReadiness: 核心逻辑:Redis 可用、共享哨兵有效、最近心跳在 TTL 内、环境/scope 匹配。 """ return _check_rpa_worker_ready_for_capability( - trigger_dir=inventory_trigger_dir(), - required_capability=INVENTORY_EXPORT_CAPABILITY, + trigger_dir=onhand_trigger_dir(), + required_capability=ONHAND_EXPORT_CAPABILITY, ) -def check_receipt_rpa_worker_ready() -> RpaWorkerReadiness: +def check_inbound_rpa_worker_ready() -> RpaWorkerReadiness: """ - 检查收料 RPA Worker 是否在线(管理端徽标 + 写 trigger 前 fail-fast)。 + 检查入站 RPA Worker 是否在线(管理端徽标 + 写 trigger 前 fail-fast)。 - 核心逻辑:仅看收料 Worker 心跳(*-receipt 或 trigger_dir 对齐);要求 - receipt_export 能力;校验收料 trigger 目录可写;与库存同口径要求共享哨兵。 + 核心逻辑:仅看 inbound Worker 心跳(*-inbound 或 trigger_dir 对齐);要求 + inbound_export 能力;校验 inbound trigger 目录可写;与 onhand 同口径要求共享哨兵。 """ - from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir + from app.services.freight_rpa.inbound.trigger_io import inbound_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, + trigger_dir=inbound_trigger_dir(), + required_capability=INBOUND_EXPORT_CAPABILITY, + worker_predicate=is_inbound_rpa_worker, require_sentinel=True, ) -def assert_receipt_rpa_worker_ready() -> None: +def assert_inbound_rpa_worker_ready() -> None: """ - 写收料 trigger 前的强制就绪检查。 + 写入站 trigger 前的强制就绪检查。 核心逻辑:镜像 assert_inventory_rpa_worker_ready;离线则抛 ServiceUnavailableError, - 排程不得进入 awaiting_receipt_rpa。 + 排程不得进入 awaiting_inbound_rpa。 Raises: ServiceUnavailableError: worker 未就绪、共享目录无效或心跳存储不可用。 """ - from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir + from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir - result = check_receipt_rpa_worker_ready() + result = check_inbound_rpa_worker_ready() if result.ready: return code = 'RPA.WORKER_OFFLINE' @@ -677,7 +712,61 @@ def assert_receipt_rpa_worker_ready() -> None: 'detail_message': result.detail_message, 'checked_at': result.checked_at, 'shared_scope_id': shared_scope_id(), - 'trigger_dir': str(receipt_trigger_dir() or ''), + 'trigger_dir': str(inbound_trigger_dir() or ''), + }, + ) + + +def check_outbound_rpa_worker_ready() -> RpaWorkerReadiness: + """ + 检查出站 RPA Worker 是否在线(写 trigger 前 fail-fast)。 + + 核心逻辑:仅看 outbound Worker 心跳(*-outbound 或 trigger_dir 对齐);要求 + outbound_export 能力;校验 outbound trigger 目录可写;与 onhand/inbound 同口径要求共享哨兵。 + """ + from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir + + return _check_rpa_worker_ready_for_capability( + trigger_dir=outbound_trigger_dir(), + required_capability=OUTBOUND_EXPORT_CAPABILITY, + worker_predicate=is_outbound_rpa_worker, + require_sentinel=True, + ) + + +def assert_outbound_rpa_worker_ready() -> None: + """ + 写出站 trigger 前的强制就绪检查。 + + 核心逻辑:镜像 assert_inbound_rpa_worker_ready;离线则抛 ServiceUnavailableError, + 排程不得进入 awaiting_outbound_rpa_callback。 + + Raises: + ServiceUnavailableError: worker 未就绪、共享目录无效或心跳存储不可用。 + """ + from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir + + result = check_outbound_rpa_worker_ready() + if result.ready: + return + code = 'RPA.WORKER_OFFLINE' + if 'heartbeat_storage_unavailable' in result.reasons: + code = 'RPA.HEARTBEAT_STORAGE_UNAVAILABLE' + logger.warning( + '[rpa-heartbeat] outbound readiness blocked code=%s reasons=%s detail=%s', + code, + result.reasons, + result.detail_message, + ) + raise ServiceUnavailableError( + result.message, + code=code, + details={ + 'reasons': result.reasons, + 'detail_message': result.detail_message, + 'checked_at': result.checked_at, + 'shared_scope_id': shared_scope_id(), + 'trigger_dir': str(outbound_trigger_dir() or ''), }, ) @@ -689,7 +778,7 @@ def _freight_upload_config_reasons() -> list[str]: Returns: 不合规原因码列表(空表示静态配置通过)。 """ - from app.services.shipping_notice.rpa import upload_queue_dir, upload_trigger_dir + from app.services.freight_rpa.upload.trigger_io import upload_queue_dir, upload_trigger_dir reasons: list[str] = [] credential_key = _config_str("FREIGHT_RPA_CREDENTIAL_KEY", "") @@ -722,16 +811,16 @@ def check_freight_upload_rpa_ready() -> RpaWorkerReadiness: 检查货代上传 RPA 是否可安全自动触发。 核心逻辑:凭据/队列/回调基址预检 + 上传 trigger 共享挂载 + Worker 心跳与 - freight_upload 能力 + 环境/scope 隔离。Mock 模式跳过心跳。 + freight_rpa_upload 能力 + 环境/scope 隔离。Mock 模式跳过心跳。 Returns: RpaWorkerReadiness(含 reasons 供建单前/启动日志展示)。 """ - from app.services.shipping_notice.rpa import upload_trigger_dir + from app.services.freight_rpa.upload.trigger_io import upload_trigger_dir return _check_rpa_worker_ready_for_capability( trigger_dir=upload_trigger_dir(), - required_capability=FREIGHT_UPLOAD_CAPABILITY, + required_capability=FREIGHT_RPA_UPLOAD_CAPABILITY, extra_reasons=_freight_upload_config_reasons(), ) @@ -757,7 +846,7 @@ def assert_freight_upload_rpa_ready() -> None: result.reasons, result.detail_message, ) - from app.services.shipping_notice.rpa import upload_trigger_dir + from app.services.freight_rpa.upload.trigger_io import upload_trigger_dir raise ServiceUnavailableError( result.message, @@ -768,7 +857,7 @@ def assert_freight_upload_rpa_ready() -> None: "checked_at": result.checked_at, "shared_scope_id": shared_scope_id(), "trigger_dir": str(upload_trigger_dir() or ""), - "capability": FREIGHT_UPLOAD_CAPABILITY, + "capability": FREIGHT_RPA_UPLOAD_CAPABILITY, }, ) @@ -836,29 +925,34 @@ def assert_inventory_rpa_worker_ready() -> None: "detail_message": result.detail_message, "checked_at": result.checked_at, "shared_scope_id": shared_scope_id(), - "trigger_dir": str(inventory_trigger_dir() or ""), + "trigger_dir": str(onhand_trigger_dir() or ""), }, ) -def serialize_rpa_worker_status(*, scope: str = "inventory") -> dict[str, Any]: +def serialize_rpa_worker_status(*, scope: str = "onhand") -> dict[str, Any]: """ - 管理端展示:按 scope 返回库存或收料 Worker 心跳摘要。 + 管理端展示:按 scope 返回在手(onhand)、入站(inbound)或出站(outbound)Worker 心跳摘要。 Args: - scope: inventory(默认)或 receipt。 + scope: onhand(默认,库存 RPA 工作台)、inbound(入站)或 outbound(出站); + 取值为后端内部与前端查询参数约定,与 Worker 上报能力标识无关。 """ - from app.services.shipping_notice.rpa import upload_trigger_dir - from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir + from app.services.freight_rpa.upload.trigger_io import upload_trigger_dir + from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir + from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir - normalized = str(scope or "inventory").strip().lower() - if normalized == "receipt": - readiness = check_receipt_rpa_worker_ready() - trigger_path = str(receipt_trigger_dir() or "") + normalized = str(scope or "onhand").strip().lower() + if normalized == "inbound": + readiness = check_inbound_rpa_worker_ready() + trigger_path = str(inbound_trigger_dir() or "") + elif normalized == "outbound": + readiness = check_outbound_rpa_worker_ready() + trigger_path = str(outbound_trigger_dir() or "") else: readiness = check_inventory_rpa_worker_ready() - trigger_path = str(inventory_trigger_dir() or "") - normalized = "inventory" + trigger_path = str(onhand_trigger_dir() or "") + normalized = "onhand" freight_readiness = check_freight_upload_rpa_ready() ttl_seconds = _heartbeat_ttl_seconds() @@ -896,7 +990,7 @@ def serialize_rpa_worker_status(*, scope: str = "inventory") -> dict[str, Any]: "upload_trigger_dir": str(upload_trigger_dir() or ""), "reasons": readiness.reasons, "workers": workers, - "freight_upload": { + "freight_rpa_upload": { "ready": freight_readiness.ready, "message": freight_readiness.message, "detail_message": freight_readiness.detail_message, diff --git a/backend/app/services/shipping_notice/rpa_worker_heartbeat_alert.py b/backend/app/services/freight_rpa/common/worker_heartbeat_alert.py similarity index 98% rename from backend/app/services/shipping_notice/rpa_worker_heartbeat_alert.py rename to backend/app/services/freight_rpa/common/worker_heartbeat_alert.py index 89ff95f7..08f10676 100644 --- a/backend/app/services/shipping_notice/rpa_worker_heartbeat_alert.py +++ b/backend/app/services/freight_rpa/common/worker_heartbeat_alert.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/rpa_worker_heartbeat_alert.py +services/freight_rpa/common/worker_heartbeat_alert.py 用途:库存 RPA Worker 离线/恢复主动告警(企微 textcard + 冷却去重)。 -依赖:rpa_worker_heartbeat、redis_client、wecom_notify、models.User、models.AppSetting。 +依赖:同包 worker_heartbeat、redis_client、wecom_notify、models.User、models.AppSetting。 逻辑:由 schedule worker 每轮循环调用;默认 ALERT_ENABLED=false 不发送;DB 为告警状态权威源,Redis 仅作缓存同步。 """ @@ -21,7 +21,7 @@ from sqlalchemy.exc import IntegrityError from app import db from app.models import AppSetting, User from app.services.permission_roles.service import list_platform_admin_users -from app.services.shipping_notice.rpa_worker_heartbeat import ( +from .worker_heartbeat import ( RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE, RPA_WORKER_OFFLINE_MESSAGE, _heartbeat_check_required, diff --git a/backend/app/services/freight_rpa/inbound/__init__.py b/backend/app/services/freight_rpa/inbound/__init__.py new file mode 100644 index 00000000..0d5395de --- /dev/null +++ b/backend/app/services/freight_rpa/inbound/__init__.py @@ -0,0 +1 @@ +"""inbound:入站 RPA。""" diff --git a/backend/app/services/freight_rpa/inbound/report_archive.py b/backend/app/services/freight_rpa/inbound/report_archive.py new file mode 100644 index 00000000..40761cd6 --- /dev/null +++ b/backend/app/services/freight_rpa/inbound/report_archive.py @@ -0,0 +1,219 @@ +""" +services/freight_rpa/inbound/report_archive.py + +用途:inbound(入站,原收料)RPA 产物事实能力——Worker 回调的原样归档(xlsx 落 MinIO、 + 三年保留期、不写库存快照表)与到期对象清理(retention)。per-file 企微投递与 resend + 已拆除(Task 2);排程终态通知仍走 freight_rpa_inbound_finalize 统一出口。 +依赖:models(FreightRpaInboundReportFile / FreightRpaInboundUnitRun、ScheduleRun 经行对象访问)、 + file_assets.storage、freight_rpa.inbound.trigger_io(回调 SCHEMA 与 drop 根)、 + freight_rpa.common.report_audit(本域唯一审计写入口,批次 B Task 6 起替代 + shipping_notice.audit_service——freight_rpa 禁止 import shipping_notice 业务模块, + 边界由 tests/services/freight_rpa/test_import_boundary.py 空白名单锁定)、 + freight_rpa.reports.facts / reports.dispatch(ReportFact 事实投递,Task 6)。 +逻辑:Worker 回调进入 /api/freight-rpa/inbound-batch-ready 后由组合根注册的业务 sink + (in_transit_transfer.rpa_sinks.register_inbound_sinks)调 ingest_inbound_callback 完成原样归档, + empty/success/failed 三个终态分支各自「先 db.session.commit() 再投递事实」—— + commit 后构造 ReportFact(report_kind='inbound', ...) 调 dispatch_report_fact; + 处理函数异常原样外抛(不吞、不回滚已提交终态),kind 未注册时 404 + FREIGHT_RPA.SINK_NOT_REGISTERED;同一 unit_run_id + sha256 已有文件时不插第二行、 + 仍投递 ok=True 的事实供处理函数重试。业务收尾(推进在途调拨来源任务、调拨证据 + 同步、排程终态归集)改由 Task 7 的处理函数(handle_inbound_report 等)承担, + 本模块不 import 任何桥与 finalize——依赖方向保持 shipping_notice → freight_rpa。 +""" + +from __future__ import annotations + +import hashlib +from datetime import datetime, timedelta +from pathlib import Path +from typing import Any + +from flask import current_app + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import ( + FreightRpaInboundReportFile, + FreightRpaInboundUnitRun, +) +from app.services.file_assets.storage import file_asset_storage +from app.services.freight_rpa.common.report_audit import append_rpa_report_event +from app.services.freight_rpa.inbound.trigger_io import SCHEMA as INBOUND_TRIGGER_SCHEMA, inbound_drop_dir +from app.services.freight_rpa.reports.dispatch import dispatch_report_fact +from app.services.freight_rpa.reports.facts import ReportFact +def _read_inbound_callback_file(file_path: str) -> bytes: + """只读取 inbound 专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。 + + 路径契约为「drop 根内文件名」:Worker(Windows RPA 主机)与后端(Linux 容器)分属 + 两机,各自看到的根路径不同(C:\\HxopsRpaTest\\... vs /mnt/hxops-rpa-*-data/...), + Worker 只上报文件名,后端用自身挂载的 drop 根拼接定位;携带本机绝对路径的历史 + 载荷亦按末段文件名解析(2026-10-08 修复跨机成功回调全程 400 的事故)。 + """ + configured_root = str(inbound_drop_dir() or '').strip() + if not configured_root: + raise ValidationError('inbound callback file root is unavailable', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID') + root = Path(configured_root).resolve() + # 容忍历史载荷携带 Windows 绝对路径:先归一分隔符再取末段文件名(防遍历,单一分段)。 + name = Path(str(file_path).replace('\\', '/')).name + path = (root / name).resolve() + try: + path.relative_to(root) + except ValueError as exc: + raise ValidationError('inbound callback file is outside inbound drop root', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID') from exc + if path.suffix.lower() != '.xlsx' or not path.is_file(): + raise ValidationError('inbound callback file must be an existing xlsx', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID') + max_size = max(int(current_app.config.get('FILE_ASSET_MAX_SIZE_MB', 30) or 30), 1) * 1024 * 1024 + if path.stat().st_size > max_size: + raise ValidationError('inbound callback file exceeds configured size limit', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID') + return path.read_bytes() + + +def ingest_inbound_callback(payload: dict[str, Any]) -> dict[str, Any]: + """幂等接收单个 inbound 单元回调,原样归档三年且不写库存快照表。 + + Args: + payload: Worker 回调载荷(schema_version/callback_id/status/file_path/...)。 + Returns: + dict: unit_run_id/status[/file_id/idempotent],与拆分前逐键一致(API envelope 契约)。 + Raises: + ValidationError: 载荷非法(schema/callback_id/sha256/文件路径)——commit 之前抛出,不投递事实。 + NotFoundError: callback_id 无匹配单元——commit 之前抛出,不投递事实。 + AppError: 终态已 commit 后 kind 未注册处理函数(FREIGHT_RPA.SINK_NOT_REGISTERED, 404)。 + 业务顺序(Task 6 契约):每个终态分支先 db.session.commit() 再构造 + ReportFact(report_kind='inbound', source_code=unit.source_code, ...) 调 + dispatch_report_fact;事实恒带 unit_run_id=unit.id(Task 7 修复轮 2—— + 含 failure/empty 与幂等重放,处理函数据此精确定位本单元的排程 run); + 处理函数异常原样外抛(不吞、不回滚已提交终态); + 同一 unit_run_id + sha256 已有文件时不插第二行,仍投递 ok=True 的事实 + (供处理函数重试)。落 MinIO / 插行失败时事务回滚,同样不投递。 + """ + if payload.get('schema_version') != INBOUND_TRIGGER_SCHEMA: + raise ValidationError('inbound callback schema_version is invalid', code='SHIPPING.INBOUND_CALLBACK_INVALID') + callback_id = str(payload.get('callback_id') or '').strip() + unit = FreightRpaInboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none() + if unit is None: + raise NotFoundError('Inbound RPA unit not found', code='SHIPPING.INBOUND_UNIT_NOT_FOUND') + status = str(payload.get('status') or '').strip().lower() + before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message} + if status in {'empty', 'no_data'}: + # [STEP] 与库存 no_inventory_data 对齐:empty 是合法业务结果,落 error_code=no_inbound_data。 + unit.status = 'empty' + unit.error_code = str(payload.get('error_code') or 'no_inbound_data')[:64] + unit.error_message = str(payload.get('error_message') or 'no_inbound_data')[:2000] + unit.finished_at = datetime.utcnow() + append_rpa_report_event( + event_type='shipping_inbound_rpa_callback_received', aggregate_type='shipping_inbound_unit', + aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, + actor_type='rpa', actor_id='inbound-worker', unit_id=unit.id, result='success', + before=before, + after={ + 'status': 'empty', + 'callback_id': unit.callback_id, + 'error_code': unit.error_code, + 'error_message': unit.error_message, + }, + metadata={'callback_status': status, 'skip_reason': unit.error_code}, + ) + # [STEP] 先 commit 终态,再投递 ok=False 事实(Task 6 顺序契约);unit_run_id + # 自单元行回填(Task 7 修复轮 2——处理函数据此精确收口本单元的排程 run)。 + db.session.commit() + dispatch_report_fact(ReportFact( + report_kind='inbound', source_code=unit.source_code, file_id=None, sha256=None, ok=False, + error_code=unit.error_code or 'no_inbound_data', + error_message=unit.error_message or 'no_inbound_data', + unit_run_id=unit.id, + )) + return {'unit_run_id': unit.id, 'status': 'empty'} + if status != 'success': + unit.status = 'failed'; unit.error_code = str(payload.get('error_code') or 'RPA.INBOUND_EXPORT_FAILED')[:64]; unit.error_message = str(payload.get('error_message') or 'inbound export failed')[:2000]; unit.finished_at = datetime.utcnow() + append_rpa_report_event( + event_type='shipping_inbound_rpa_callback_received', aggregate_type='shipping_inbound_unit', + aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, + actor_type='rpa', actor_id='inbound-worker', unit_id=unit.id, result='failure', + before=before, after={'status': 'failed', 'error_code': unit.error_code, 'error_message': unit.error_message}, + metadata={'callback_status': status}, + ) + # [STEP] 先 commit 终态,再投递 ok=False 事实(Task 6 顺序契约);unit_run_id + # 自单元行回填(Task 7 修复轮 2——处理函数据此精确收口本单元的排程 run)。 + db.session.commit() + dispatch_report_fact(ReportFact( + report_kind='inbound', source_code=unit.source_code, file_id=None, sha256=None, ok=False, + error_code=unit.error_code, error_message=unit.error_message, + unit_run_id=unit.id, + )) + return {'unit_run_id': unit.id, 'status': 'failed'} + data = _read_inbound_callback_file(str(payload.get('file_path') or '')) + sha256 = hashlib.sha256(data).hexdigest() + claimed = str(payload.get('sha256') or '').lower() + if claimed and claimed != sha256: + raise ValidationError('inbound callback sha256 mismatch', code='SHIPPING.INBOUND_CALLBACK_SHA_MISMATCH') + existing = FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id, sha256=sha256).one_or_none() + if existing: + # [STEP] 幂等重放:不插第二行,仍投递 ok=True 事实(同一 file_id),供处理函数重试; + # unit_run_id 自单元行回填(Task 7 修复轮 2)。 + dispatch_report_fact(ReportFact( + report_kind='inbound', source_code=unit.source_code, file_id=existing.id, sha256=sha256, ok=True, + unit_run_id=unit.id, + )) + return {'unit_run_id': unit.id, 'status': unit.status, 'file_id': existing.id, 'idempotent': True} + filename = Path(str(payload.get('original_filename') or payload.get('file_path') or 'receipt.xlsx')).name + storage_key = f'shipping/receipt-reports/{datetime.utcnow():%Y/%m}/{unit.id}/{sha256}.xlsx' + file_asset_storage.upload_bytes(storage_key=storage_key, data=data, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') + record = FreightRpaInboundReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key, original_filename=filename, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', file_size=len(data), sha256=sha256, archive_expires_at=datetime.utcnow() + timedelta(days=365 * 3)) + db.session.add(record) + unit.status = 'success'; unit.finished_at = datetime.utcnow() + db.session.flush() + append_rpa_report_event(event_type='shipping_inbound_report_archived', aggregate_type='shipping_inbound_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='inbound-worker', unit_id=unit.id, result='success', before=before, after={'status': 'success', 'source_run_no': unit.callback_id, 'file_id': record.id, 'sha256': sha256, 'file_size': len(data)}, artifact_refs=[{'kind': 'inbound_report', 'id': str(record.id), 'sha256': sha256}], metadata={'file_size': len(data), 'retention_days': 365 * 3}) + # [STEP] 先 commit 归档,再投递 ok=True 事实(Task 6 顺序契约);unit_run_id + # 自单元行回填(Task 7 修复轮 2——处理函数据此精确收口本单元的排程 run)。 + db.session.commit() + dispatch_report_fact(ReportFact( + report_kind='inbound', source_code=unit.source_code, file_id=record.id, sha256=sha256, ok=True, + unit_run_id=unit.id, + )) + return {'unit_run_id': unit.id, 'status': 'success', 'file_id': record.id, 'idempotent': False} + + +def run_freight_rpa_inbound_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]: + """仅删除已到三年保留期的 MinIO 对象,永不删除文件事实、运行或审计。 + + Args: + task: 排程任务行(job_params.limit 提供单批上限,1..1000)。 + run: 排程执行记录(本函数不改写 run,仅按排程协议返回计数/明细/日志)。 + Returns: + 排程平台 Job 协议七元组(总查得数、成功、失败、跳过 0、明细、错误、step_logs)。 + """ + limit = max(1, min(int((getattr(task, 'job_params', {}) or {}).get('limit', 100)), 1000)) + now = datetime.utcnow() + rows = FreightRpaInboundReportFile.query.filter( + FreightRpaInboundReportFile.archive_expires_at.is_not(None), + FreightRpaInboundReportFile.archive_expires_at <= now, + FreightRpaInboundReportFile.archive_deleted_at.is_(None), + ).order_by(FreightRpaInboundReportFile.id).limit(limit).all() + success = failed = 0 + errors: list[str] = [] + for report_file in rows: + try: + file_asset_storage.delete_object(report_file.storage_key) + report_file.archive_deleted_at = now + report_file.archive_delete_result_json = {'status': 'deleted', 'deleted_at': now.isoformat()} + append_rpa_report_event( + event_type='shipping_inbound_report_archive_deleted', aggregate_type='shipping_inbound_file', + aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention', + unit_id=report_file.unit_run_id, result='success', + before={'status': 'archived'}, after={'status': 'archive_deleted'}, + artifact_refs=[{'kind': 'inbound_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], + ) + success += 1 + except Exception as exc: + errors.append(f'{report_file.id}: {exc}') + append_rpa_report_event( + event_type='shipping_inbound_report_archive_delete_attempted', aggregate_type='shipping_inbound_file', + aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention', + unit_id=report_file.unit_run_id, result='failure', + before={'status': 'archived'}, after={'status': 'archived', 'delete_error': str(exc)[:2000]}, + artifact_refs=[{'kind': 'inbound_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], + ) + failed += 1 + db.session.commit() + return len(rows), success, failed, 0, [{'file_id': row.id} for row in rows], errors, [{'step': 'inbound_retention', 'status': 'completed'}] diff --git a/backend/app/services/freight_rpa/inbound/trigger_io.py b/backend/app/services/freight_rpa/inbound/trigger_io.py new file mode 100644 index 00000000..ba94649d --- /dev/null +++ b/backend/app/services/freight_rpa/inbound/trigger_io.py @@ -0,0 +1,93 @@ +""" +services/freight_rpa/inbound/trigger_io.py + +用途:inbound(入站,原收料)RPA 的纯文件 IO——trigger/落盘目录解析、批量 trigger JSON + 原子写入,以及 Worker 触发/回调契约常量(SCHEMA/ACTION_*)。 +依赖:Flask current_app 配置、Path/JSON/文件系统工具;不 import 任何业务编排模块 + (import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。 +逻辑:由 schedule.freight_rpa_inbound_job(排程写 trigger)、api.schedule.runs(admin 单元重试)、 + in_transit_transfer.inbound_trigger_service(调拨按需/批量触发)、 + freight_rpa.common.worker_heartbeat(inbound trigger 目录探测/就绪检查)、 + freight_rpa.inbound.report_archive(drop 目录定位与回调 SCHEMA 校验,Task 10 下沉)等调用, + 与外部 RPA Worker 的文件投递目录交互;schema/action 新值以本文件常量为单一真相 + (Worker 侧 Task 12 对表:freight_rpa.inbound.v1 / inbound_export_batch)。 +""" + +from __future__ import annotations + +import json +import os +from datetime import datetime +from pathlib import Path +from typing import Any + +from flask import current_app + +# Worker 触发/回调契约常量:后端写入侧与校验侧共用单一真相,禁止再写字面量。 +# [PROMPT_UPDATE] 2026-10-16 freight_rpa 解耦批次 R:schema/action 切换为下述新值 +# (旧 receipt 时代字面量已从 backend/app 与 Worker 双侧清零,历史对照见 cutover runbook), +# 旧字符串已在 backend/app 内清零;Worker 侧由 Task 12 对齐。 +SCHEMA = "freight_rpa.inbound.v1" +ACTION_INBOUND_EXPORT_BATCH = "inbound_export_batch" + + +def _path(key: str) -> Path | None: + value = str(current_app.config.get(key) or "").strip() + if not value: + return None + return Path(value) + + +def inbound_trigger_dir() -> Path | None: + """RPA inbound 批量导出触发 JSON 目录(FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR); + 绝不回落到 onhand trigger 目录。""" + return _path("FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR") + + +def inbound_drop_dir() -> Path | None: + """RPA inbound 导出文件落盘目录(FREIGHT_RPA_SHARED_INBOUND_DROP_DIR)。""" + return _path("FREIGHT_RPA_SHARED_INBOUND_DROP_DIR") + + +def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None: + """原子发布 trigger,避免 Worker 读取到写入中的半截 JSON。""" + temp_path = path.with_name(f'.{path.name}.{os.getpid()}.tmp') + try: + with open(temp_path, 'w', encoding='utf-8') as handle: + json.dump(body, handle, ensure_ascii=False, indent=2) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temp_path, path) + finally: + if temp_path.exists(): + temp_path.unlink(missing_ok=True) + + +def write_inbound_export_batch_trigger(run_no: str, units: list[dict[str, Any]], payload: dict[str, Any] | None = None) -> str | None: + """ + 写入 inbound 批量 trigger 文件 inbound_export_batch_{run_no}.json + ([PROMPT_UPDATE] 2026-10-16 批次 R:文件名前缀随 Worker 侧 Task 12 一起由 + receipt_export_batch_* 切换为 inbound_export_batch_*;Worker 轮询 /*.json + 按内容消费,schema/action 取本文件常量新值)。 + + Args: + run_no: 批次运行号;进 body.batch_run_no 并参与文件名(安全化仅保留字母数字-_)。 + units: 触发单元载荷列表;业务约束——空列表直接返回 None(无单元不落盘)。 + payload: 调用方附加字段,合并覆盖 body 顶层键(schema_version/action 缺省取常量)。 + + Returns: + str | None: 触发文件绝对路径;目录未配置或 units 为空时返回 None。 + """ + trigger_dir = inbound_trigger_dir() + if not trigger_dir or not units: + return None + trigger_dir.mkdir(parents=True, exist_ok=True) + safe_run_no = ''.join(char for char in run_no if char.isalnum() or char in {'-', '_'}) or 'inbound' + body = { + 'schema_version': SCHEMA, 'action': ACTION_INBOUND_EXPORT_BATCH, + 'batch_run_no': run_no, 'requested_at': datetime.utcnow().isoformat(), 'units': units, + **(payload or {}), + } + path = trigger_dir / f'inbound_export_batch_{safe_run_no}.json' + _write_trigger_json_atomic(path, body) + return str(path) diff --git a/backend/app/services/freight_rpa/onhand/__init__.py b/backend/app/services/freight_rpa/onhand/__init__.py new file mode 100644 index 00000000..c88e0bbf --- /dev/null +++ b/backend/app/services/freight_rpa/onhand/__init__.py @@ -0,0 +1 @@ +"""onhand:在手库存 RPA。""" diff --git a/backend/app/services/shipping_notice/rpa_attempts.py b/backend/app/services/freight_rpa/onhand/attempts.py similarity index 74% rename from backend/app/services/shipping_notice/rpa_attempts.py rename to backend/app/services/freight_rpa/onhand/attempts.py index 9e6f950c..b933b958 100644 --- a/backend/app/services/shipping_notice/rpa_attempts.py +++ b/backend/app/services/freight_rpa/onhand/attempts.py @@ -1,9 +1,11 @@ """ -services/shipping_notice/rpa_attempts.py +services/freight_rpa/onhand/attempts.py -用途:统计任务的 RPA 库存导出与货代上传重试次数,并返回统一上限。 -依赖:ShippingNotice、ShippingTaskEvent 模型与事件查询逻辑。 -逻辑:由 inventory_rpa_workflow、fulfillment_workflow 等模块调用本文件,决定是否还能继续触发 RPA 重试。 +用途:统计任务的 onhand(库存)RPA 导出与货代上传重试次数,并返回统一上限。 +依赖:ShippingNotice、ShippingTaskEvent 模型与事件查询逻辑(仅 models,无业务编排 import)。 +逻辑:由 shipping_notice 的 onhand_rpa_workflow、fulfillment_workflow 等模块调用本文件, + 决定是否还能继续触发 RPA 重试;事件类型字符串(onhand_rpa_* 等)是落库数据值, + 随 models 命名一并留待批次 S 处理,本模块只改包归属与标识符词根。 """ from __future__ import annotations @@ -15,15 +17,15 @@ from app.models import ShippingNotice, ShippingTaskEvent DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS = 3 -_INVENTORY_SUCCESS_EVENTS = { +_ONHAND_SUCCESS_EVENTS = { "inventory_uploaded", "inventory_parsed", - "inventory_rpa_drop_ingested", - "inventory_rpa_ready", + "onhand_rpa_drop_ingested", + "onhand_rpa_ready", "inventory_template_mapping_used", } -_INVENTORY_ATTEMPT_RESET_EVENTS = _INVENTORY_SUCCESS_EVENTS | { +_ONHAND_ATTEMPT_RESET_EVENTS = _ONHAND_SUCCESS_EVENTS | { "decision_retry_rpa", } @@ -33,24 +35,24 @@ _UPLOAD_SUCCESS_EVENTS = { } -def inventory_rpa_attempts(task: ShippingNotice | None) -> int: +def onhand_rpa_attempts(task: ShippingNotice | None) -> int: """统计自上次库存成功事件以来的 RPA 库存导出触发/失败次数。""" if not task or task.id is None: return 0 last_reset = ( ShippingTaskEvent.query.filter_by(task_id=task.id) - .filter(ShippingTaskEvent.event_type.in_(_INVENTORY_ATTEMPT_RESET_EVENTS)) + .filter(ShippingTaskEvent.event_type.in_(_ONHAND_ATTEMPT_RESET_EVENTS)) .order_by(ShippingTaskEvent.id.desc()) .first() ) since: datetime | None = last_reset.created_at if last_reset else None triggered = ShippingTaskEvent.query.filter_by(task_id=task.id).filter( - ShippingTaskEvent.event_type == "inventory_rpa_triggered" + ShippingTaskEvent.event_type == "onhand_rpa_triggered" ) failed = ShippingTaskEvent.query.filter_by(task_id=task.id).filter( - ShippingTaskEvent.event_type == "inventory_rpa_failed" + ShippingTaskEvent.event_type == "onhand_rpa_failed" ) if since: triggered = triggered.filter(ShippingTaskEvent.created_at >= since) diff --git a/backend/app/services/shipping_notice/inventory_rpa_callback_cleanup.py b/backend/app/services/freight_rpa/onhand/callback_cleanup.py similarity index 93% rename from backend/app/services/shipping_notice/inventory_rpa_callback_cleanup.py rename to backend/app/services/freight_rpa/onhand/callback_cleanup.py index 2abe00d4..496151ad 100644 --- a/backend/app/services/shipping_notice/inventory_rpa_callback_cleanup.py +++ b/backend/app/services/freight_rpa/onhand/callback_cleanup.py @@ -1,9 +1,11 @@ """ -services/shipping_notice/inventory_rpa_callback_cleanup.py +services/freight_rpa/onhand/callback_cleanup.py -用途:RPA callback drop 区文件归档失败后的持久化重试队列、隔离与消费标记。 -依赖:rpa.inventory_drop_dir / inventory_processed_dir、json、uuid、Flask current_app。 -逻辑:commit 后尝试归档;失败则移入 .hxops_quarantine 并入队;scheduler/worker 启动时定期消费队列。 +用途:RPA callback drop 区文件归档失败后的持久化重试队列、隔离与消费标记 + (Task 9 自 shipping_notice.onhand_rpa_callback_cleanup 整体平移,纯协议文件 IO、零业务落盘)。 +依赖:freight_rpa.onhand.trigger_io(onhand_drop_dir / onhand_processed_dir)、json、uuid、Flask current_app。 +逻辑:commit 后由 shipping_notice 业务 sink 调用尝试归档;失败则移入 .hxops_quarantine 并入队; + scheduler/worker 启动时定期消费队列。 """ from __future__ import annotations @@ -18,7 +20,7 @@ from typing import Any from flask import current_app -from app.services.shipping_notice.rpa import inventory_drop_dir, inventory_processed_dir +from app.services.freight_rpa.onhand.trigger_io import onhand_drop_dir, onhand_processed_dir _CALLBACK_CONSUMED_SUFFIX = ".hxops_consumed" _CLEANUP_QUEUE_DIRNAME = ".cleanup_queue" @@ -30,7 +32,7 @@ _LOGGER = logging.getLogger(__name__) def callback_cleanup_queue_dir() -> Path | None: """drop 目录下 callback 归档重试队列路径。""" - drop = inventory_drop_dir() + drop = onhand_drop_dir() if not drop: return None return drop / _CLEANUP_QUEUE_DIRNAME @@ -38,7 +40,7 @@ def callback_cleanup_queue_dir() -> Path | None: def callback_cleanup_failed_dir() -> Path | None: """超过最大重试次数的 cleanup job 隔离目录。""" - drop = inventory_drop_dir() + drop = onhand_drop_dir() if not drop: return None return drop / _CLEANUP_FAILED_DIRNAME @@ -49,7 +51,7 @@ def callback_quarantine_dir() -> Path | None: Worker 不应扫描的 callback 隔离目录(drop 根目录外的子目录)。 归档失败时 HXOPS 将文件原子移入此处,避免重复上报。 """ - drop = inventory_drop_dir() + drop = onhand_drop_dir() if not drop: return None return drop / _QUARANTINE_DIRNAME @@ -243,7 +245,7 @@ def flush_callback_cleanup_queue(*, max_jobs: int = 32) -> list[str]: callback_raw = str(payload.get("callback_path") or "").strip() processed_raw = str(payload.get("processed_dir") or "").strip() callback_path = Path(callback_raw) if callback_raw else None - processed_dir = Path(processed_raw) if processed_raw else inventory_processed_dir() + processed_dir = Path(processed_raw) if processed_raw else onhand_processed_dir() if callback_path is None or processed_dir is None: try: job_path.unlink() diff --git a/backend/app/services/freight_rpa/onhand/report_store.py b/backend/app/services/freight_rpa/onhand/report_store.py new file mode 100644 index 00000000..ebc269f4 --- /dev/null +++ b/backend/app/services/freight_rpa/onhand/report_store.py @@ -0,0 +1,84 @@ +"""freight_rpa/onhand/report_store.py + +用途:freight_rpa_onhand_report_files 的写入唯一入口(阶段 B Task 5)——发货域 + (shipping_notice)与调度等其他消费方不得自行构造 FreightRpaOnhandReportFile 行, + 插入/按主键更新统一经本模块收敛,保证报表事实写入只发生在货代 RPA 域。 +依赖:app.db、app.models.FreightRpaOnhandReportFile、app.core.errors.NotFoundError。 +逻辑:insert_onhand_report 接收与 FreightRpaOnhandReportFile 列同名的关键字参数 + (storage_path、file_sha256、onhand_lines_json、field_mapping_json、 + snapshot_status、warehouse_id、source_code、rpa_run_no 等),flush 后 + 返回 file_id;update_onhand_report 按主键更新给定列。两者都【只 flush 不 + commit】——事务提交时机归属调用方;两者都【不创建任务关联】—— + shipping_task_onhand_links 等 link 表归发货域,由调用方自行维护。 + 【禁止】import app.services.shipping_notice / in_transit_transfer(import + 方向只能反过来,边界由 tests/services/shipping_notice/ + test_report_model_boundary.py 锁定)。 +""" + +from __future__ import annotations + +from typing import Any + +from app import db +from app.core.errors import NotFoundError +from app.models import FreightRpaOnhandReportFile + + +def insert_onhand_report(**columns: Any) -> int: + """插入 freight_rpa_onhand_report_files 一行并 flush。返回 file_id。不创建任务关联,不 commit。 + + 【AI 触发时机】:任何需要新增在手/库存快照文件记录的场景 + (RPA 回调入快照、人工上传保存、空快照记录)须调用本函数,禁止在 + shipping_notice 域内直接构造 FreightRpaOnhandReportFile 行。 + + 核心逻辑:[STEP 1] 以与模型列同名的关键字参数构造行; + [STEP 2] db.session.add + flush(拿到自增主键且同事务内可见); + [STEP 3] 返回 int 主键,供调用方按需经 db.session.get 取回 ORM 对象。 + + Args: + **columns: FreightRpaOnhandReportFile 的任意合法列关键字(禁止传入不存在的 + 列名,非法列名会在构造时抛 TypeError)。无默认值语义变化—— + 列默认值仍由模型定义(default=)承担。 + + Returns: + 新插入行的 file_id(int)。 + + Raises: + TypeError: 传入了模型不存在的列关键字。 + sqlalchemy.exc.IntegrityError: 唯一约束(如 onhand_file_no / RPA 幂等索引) + 冲突,由调用方决定 savepoint 回滚或复用既有行。 + """ + row = FreightRpaOnhandReportFile(**columns) + db.session.add(row) + db.session.flush() + return int(row.id) + + +def update_onhand_report(file_id: int, **columns: Any) -> None: + """按 file_id 更新该行的给定列并 flush。不 commit。 + + 【AI 触发时机】:快照过期(snapshot_status→expired)、批次同身份改写 + share_mode、identity_status 回填等针对既有在手报表行的列更新场景。 + + 核心逻辑:[STEP 1] 按主键取行(命中身份缓存即为同一 ORM 对象,调用方 + 持有的引用会同步可见更新),缺失抛 NotFoundError(fail-closed,禁止静默 + 吞掉错配);[STEP 2] 逐列 setattr;[STEP 3] flush。【不 commit】—— + 事务归属调用方;【不动任务关联】——link 表更新归发货域。 + + Args: + file_id: freight_rpa_onhand_report_files 主键(int;禁止传入非整数 ID)。 + **columns: 要更新的列名与取值(禁止传入模型不存在的列名)。 + + Raises: + NotFoundError: file_id 对应的行不存在。 + TypeError: 传入了模型不存在的列关键字。 + """ + row = db.session.get(FreightRpaOnhandReportFile, file_id) + if row is None: + raise NotFoundError( + f"Onhand report file not found: {file_id}", + details={'file_id': file_id}, + ) + for key, value in columns.items(): + setattr(row, key, value) + db.session.flush() \ No newline at end of file diff --git a/backend/app/services/freight_rpa/onhand/trigger_io.py b/backend/app/services/freight_rpa/onhand/trigger_io.py new file mode 100644 index 00000000..77f64db2 --- /dev/null +++ b/backend/app/services/freight_rpa/onhand/trigger_io.py @@ -0,0 +1,108 @@ +""" +services/freight_rpa/onhand/trigger_io.py + +用途:onhand(在手库存)RPA 的纯文件 IO——trigger/落盘目录解析、trigger JSON 原子写、 + 单任务导出 trigger 写入,以及 Worker 触发/回调契约常量(SCHEMA/ACTION_*)。 +依赖:Flask current_app 配置、Path/JSON/文件系统工具;不 import 任何业务编排模块 + (import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。 +逻辑:由 shipping_notice.onhand_trigger_batch(批量/按需编排)、onhand_rpa_workflow(回调 schema 校验)、 + per_source_rpa_service(回调 schema 校验)、freight_rpa.common.worker_heartbeat(目录探测)等调用, + 与外部 RPA Worker 的文件投递目录交互;schema/action 新值以本文件常量为单一真相 + (Worker 侧 Task 12 对表:freight_rpa.onhand.v1 / onhand_export / onhand_export_batch)。 +""" + +from __future__ import annotations + +import json +import os +from datetime import datetime +from pathlib import Path +from typing import Any + +from flask import current_app + +# Worker 触发/回调契约常量:后端写入侧与校验侧共用单一真相,禁止再写字面量。 +# [PROMPT_UPDATE] 2026-10-16 freight_rpa 解耦批次 R:schema/action 切换为下述新值 +# (旧 inventory 时代字面量已从 backend/app 与 Worker 双侧清零,历史对照见 cutover runbook), +# 旧字符串已在 backend/app 内清零;Worker 侧由 Task 12 对齐。 +SCHEMA = "freight_rpa.onhand.v1" +ACTION_ONHAND_EXPORT = "onhand_export" +ACTION_ONHAND_EXPORT_BATCH = "onhand_export_batch" + + +def _path(key: str) -> Path | None: + value = str(current_app.config.get(key) or "").strip() + if not value: + return None + return Path(value) + + +def onhand_drop_dir() -> Path | None: + """RPA onhand 库存 Excel 落盘目录(FREIGHT_RPA_SHARED_ONHAND_DROP_DIR)。""" + return _path("FREIGHT_RPA_SHARED_ONHAND_DROP_DIR") + + +def onhand_processed_dir() -> Path | None: + """已处理 onhand 文件归档子目录(drop_dir/processed)。""" + base = onhand_drop_dir() + if not base: + return None + return base / "processed" + + +def onhand_trigger_dir() -> Path | None: + """RPA onhand 导出触发 JSON 目录(FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR)。""" + return _path("FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR") + + +def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None: + """原子发布 trigger,避免 Worker 读取到写入中的半截 JSON。""" + temp_path = path.with_name(f'.{path.name}.{os.getpid()}.tmp') + try: + with open(temp_path, 'w', encoding='utf-8') as handle: + json.dump(body, handle, ensure_ascii=False, indent=2) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temp_path, path) + finally: + if temp_path.exists(): + temp_path.unlink(missing_ok=True) + + +def write_onhand_export_trigger(task_no: str, payload: dict[str, Any] | None = None) -> str | None: + """ + 写入 RPA onhand 导出触发文件 inventory_export_{task_no}.json + (文件名沿用既有 Worker 契约,仅 action 取新值 ACTION_ONHAND_EXPORT)。 + + Returns: + str | None: 触发文件绝对路径;目录未配置时返回 None。 + """ + trigger_dir = onhand_trigger_dir() + if not trigger_dir: + return None + trigger_dir.mkdir(parents=True, exist_ok=True) + body = { + "action": ACTION_ONHAND_EXPORT, + "task_no": task_no, + "run_no": f"LEGACY-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}", + "requested_at": datetime.utcnow().isoformat(), + **(payload or {}), + } + path = trigger_dir / f"inventory_export_{task_no}.json" + _write_trigger_json_atomic(path, body) + return str(path) + + +# TODO(批次S): 全仓零调用,死代码候选,收敛时删除 +def find_latest_inventory_file() -> Path | None: + """在 drop 目录中查找最新修改的 xlsx/xls/csv 库存文件。""" + drop = onhand_drop_dir() + if not drop or not drop.is_dir(): + return None + candidates = [ + p for p in drop.iterdir() + if p.is_file() and p.suffix.lower() in {".xlsx", ".xls", ".csv"} + ] + if not candidates: + return None + return max(candidates, key=lambda p: p.stat().st_mtime) diff --git a/backend/app/services/freight_rpa/onhand/workflow_protocol.py b/backend/app/services/freight_rpa/onhand/workflow_protocol.py new file mode 100644 index 00000000..7e5beafd --- /dev/null +++ b/backend/app/services/freight_rpa/onhand/workflow_protocol.py @@ -0,0 +1,349 @@ +""" +services/freight_rpa/onhand/workflow_protocol.py + +用途:onhand(在手库存)RPA 回调协议态——attempt 行记账、run_no 幂等键、轮次校验、 + 排程进度记账与超时窗口判定的纯协议层。 +依赖:app.models(ShippingTaskEvent / FreightRpaOnhandTaskAttempt / ScheduleRun)、 + app.extensions.db、freight_rpa.onhand 包内模块;**禁止 import 任何 + shipping_notice 业务模块**(import 边界由 tests/services/freight_rpa/test_import_boundary.py + AST 全包扫描锁死,含函数内延迟 import)。 +逻辑:Task 9 拆分自 shipping_notice.onhand_rpa_workflow——回调进入 + /api/freight-rpa/* 蓝图后,业务 sink(shipping_notice.rpa_sinks 注册)在原事务内 + 调用本模块完成协议记账(不改变 commit 时机),再由域内业务函数做快照落盘/ + 门禁推进/审计投影;快照、Gate、状态机等业务终态一律留在 shipping_notice。 +""" + +from __future__ import annotations + +import json +from datetime import datetime +from pathlib import Path +from typing import Any + +from app.extensions import db +from app.models import ScheduleRun, ShippingTaskEvent, FreightRpaOnhandTaskAttempt + + +def latest_task_event(task: Any, event_type: str) -> ShippingTaskEvent | None: + """返回任务最近一条指定类型的 ShippingTaskEvent(RPA 超时/重试/轮次校验用)。""" + if task.id is None: + return None + return ( + ShippingTaskEvent.query.filter_by(task_id=task.id, event_type=event_type) + .order_by(ShippingTaskEvent.id.desc()) + .first() + ) + + +def extract_run_no_from_trigger(trigger_path: str | None) -> str: + """从 trigger 文件路径或 JSON 内容提取 run_no(batch / legacy 单票均支持)。""" + path = Path(str(trigger_path or "")) + name = path.name + prefix = "inventory_export_batch_" + if name.startswith(prefix) and name.endswith(".json"): + return name[len(prefix) : -len(".json")] + if name.startswith("inventory_export_") and name.endswith(".json") and path.is_file(): + try: + payload = json.loads(path.read_text(encoding="utf-8")) + if isinstance(payload, dict): + run_no = str(payload.get("run_no") or "").strip() + if run_no: + return run_no + except (OSError, json.JSONDecodeError, TypeError, ValueError): + pass + return "" + + +def is_legacy_trigger_run_no(run_no: str) -> bool: + """判断 run_no 是否来自 legacy 单任务 trigger(worker 可能不回传 run_no)。""" + return str(run_no or "").strip().upper().startswith("LEGACY-") + + +def expected_rpa_callback_run_no(task: Any) -> str: + """读取任务最近一次 RPA 触发记录的 run_no(事件 detail 优先,缺失回退 trigger 文件)。""" + last_trigger = latest_task_event(task, "onhand_rpa_triggered") + if not last_trigger: + return "" + detail = last_trigger.detail_json if isinstance(last_trigger.detail_json, dict) else {} + run_no = str(detail.get("run_no") or "").strip() + if run_no: + return run_no + return extract_run_no_from_trigger(str(detail.get("trigger") or "")) + + +def validate_rpa_callback_run_no(task: Any, callback_run_no: str) -> str | None: + """校验回调 run_no 属于当前任务最近一次有效触发轮次。 + + Returns: + None 校验通过;否则返回拒绝原因码(no_active_trigger / run_no_missing / run_no_mismatch)。 + """ + provided = str(callback_run_no or "").strip() + expected = expected_rpa_callback_run_no(task) + if not expected: + return "no_active_trigger" + if not provided: + if is_legacy_trigger_run_no(expected): + return None + return "run_no_missing" + if provided != expected: + return "run_no_mismatch" + return None + + +def resolve_effective_callback_run_no(task: Any, payload: dict[str, Any]) -> str: + """解析回调实际归属的 run_no(显式传入优先,否则回退当前触发轮次)。""" + provided = str(payload.get("run_no") or "").strip() + if provided: + return provided + return expected_rpa_callback_run_no(task) + + +def get_consumed_inventory_rpa_run_no(task: Any) -> str: + """读取已消费(处理完成)的 RPA 轮次 run_no。""" + attempt = ( + FreightRpaOnhandTaskAttempt.query + .filter_by(task_no=str(task.task_no or ''), status='consumed') + .order_by(FreightRpaOnhandTaskAttempt.consumed_at.desc(), FreightRpaOnhandTaskAttempt.id.desc()) + .first() + ) + return str(getattr(attempt, 'source_run_no', '') or '').strip() + + +def mark_inventory_rpa_run_no_consumed(task: Any, run_no: str) -> None: + """[协议记账] 标记当前 RPA 轮次已被回调消费,防止同一 run_no 重放重复入库。 + + 核心逻辑:只改 Attempt 行(status/consumed_at),不 commit——commit 时机由调用方 + 业务事务决定,与拆分前行为一致。 + """ + effective = str(run_no or "").strip() + if not effective: + return + attempt = ( + FreightRpaOnhandTaskAttempt.query + .filter_by(task_no=str(task.task_no or ''), source_run_no=effective) + .one_or_none() + ) + if attempt is not None: + attempt.status = 'consumed' + attempt.consumed_at = datetime.utcnow() + + +def validate_rpa_callback_not_replayed(task: Any, run_no: str) -> str | None: + """拒绝同一 run_no 的重复成功/失败/跳过回调。 + + Returns: + None 允许处理;"run_no_already_consumed" 表示重放,应拒绝。 + """ + effective = str(run_no or "").strip() + consumed = get_consumed_inventory_rpa_run_no(task) + if effective and consumed and effective == consumed: + return "run_no_already_consumed" + return None + + +def validate_schedule_batch_callback_run_no( + schedule_run_id: int | None, + callback_run_no: str, + *, + require_awaiting: bool = True, +) -> str | None: + """校验定时 batch 回调 run_no 与排程 run 记录一致,防止错绑终态。 + + Args: + schedule_run_id: 排程 run 主键;None 表示非排程回调,直接通过。 + callback_run_no: Worker 上报的 batch_run_no / run_no。 + require_awaiting: True(进度/收件终态)要求仍处于 awaiting_rpa; + False(解析 Job)只校验身份,允许排程已按「文件返回」终态化。 + + Returns: + None 校验通过;否则返回拒绝原因码(schedule_run_not_found / schedule_run_no_missing / + schedule_run_no_mismatch / schedule_run_not_awaiting)。 + """ + if schedule_run_id is None: + return None + run = db.session.get(ScheduleRun, schedule_run_id) + if not run: + return "schedule_run_not_found" + expected = str(run.run_no or "").strip() + provided = str(callback_run_no or "").strip() + if not expected: + return "schedule_run_no_missing" + if provided != expected: + return "schedule_run_no_mismatch" + if not require_awaiting: + return None + summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} + if run.status != "running" or not summary.get("awaiting_rpa"): + return "schedule_run_not_awaiting" + return None + + +def record_onhand_batch_progress( + run: ScheduleRun, + run_no: str, + *, + success_count: int, + skipped_count: int, + failed_count: int, +) -> dict[str, Any]: + """[协议记账] 排程批量导出进度回写:max(现有, 上报) 防乱序回退,写后即 commit。 + + 【AI 触发时机】:onhand-batch-progress 业务 sink 已完成 schema/run 校验后调用; + 非终态记账(不修改 status/started_at/finished_at,终态仍以 batch-ready 为准)。 + + Args: + run: 已确认存在且处于 awaiting_rpa 的 ScheduleRun 行。 + run_no: 批次 run_no,写入 response_summary_json.progress 供审计。 + success_count / skipped_count / failed_count: 已按 max(0, int(x)) 归一的非负计数。 + + Returns: + dict: 提交后的最终计数 {'success_count','skipped_count','failed_count','run_no'}; + 供业务层拼装响应,键值与拆分前响应逐字一致。 + """ + 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) + summary = dict(run.response_summary_json or {}) + 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': run_no, + 'updated_at': datetime.utcnow().isoformat(), + } + run.response_summary_json = summary + # commit 时机与拆分前 onhand_rpa_workflow.report_inventory_batch_progress 完全一致: + # 校验通过、计数写完后立即提交,再由业务层构造响应。 + db.session.commit() + return { + 'run_no': run_no, + '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 compute_rpa_wait_window( + triggered_at: datetime, + timeout_seconds: int, + *, + now: datetime | None = None, +) -> tuple[int, int, int]: + """计算库存 RPA 等待窗口(elapsed / timeout / remaining 秒)。 + + 【AI 触发时机】:业务层已确认任务处于 RPA 等待态、需要判断是否超时或调度复查时调用。 + + Args: + triggered_at: 最近一次 onhand_rpa_triggered 事件的 created_at。 + timeout_seconds: 超时阈值秒数(由业务层 tool_common 读取配置)。 + now: 可注入当前时间(测试用);缺省 utcnow。 + + Returns: + tuple[int, int, int]: (elapsed_seconds, timeout_seconds, remaining_seconds); + elapsed 向下取整且不为负,remaining 不为负。 + """ + current = now or datetime.utcnow() + elapsed = max(int((current - triggered_at).total_seconds()), 0) + remaining = max(int(timeout_seconds) - elapsed, 0) + return elapsed, int(timeout_seconds), remaining + + +def resolve_shared_inventory_drop_file(raw_path: str, *, allowed_root: Path) -> Path | None: + """将 Worker 回调中的 file_path 解析为 Linux 侧共享 drop 内的真实文件。 + + Windows Worker 上报 ``C:\\HxopsRpaTest\\data\\inventory_drop\\file.xlsx``, + Ubuntu 后端通过 ``/mnt/hxops-rpa-*-data/inventory_drop/file.xlsx`` 读同一 SMB 文件。 + 安全约束:仅允许 ``allowed_root`` 下按文件名映射,拒绝路径穿越。 + + Returns: + Path | None: 解析成功且确为 allowed_root 下存在文件时返回绝对路径;否则 None。 + """ + text = str(raw_path or '').strip() + if not text: + return None + try: + root = allowed_root.resolve() + except OSError: + return None + + candidate = Path(text) + try: + resolved = candidate.resolve() + if resolved.is_file(): + resolved.relative_to(root) + return resolved + except (OSError, ValueError, RuntimeError): + pass + + name = Path(text.replace('\\', '/')).name.strip() + if not name or name in {'.', '..'} or '/' in name or '\\' in name: + return None + mapped = (root / name).resolve() + try: + mapped.relative_to(root) + except ValueError: + return None + if mapped.is_file(): + return mapped + return None + + +def normalize_inventory_result_status(payload: dict[str, Any]) -> str: + """归一化单任务 RPA 库存回调结果。 + + 核心逻辑:优先读取 worker 上报的 status;兼容旧回调仅含 success/skipped 布尔字段; + 缺省 success 视为 true(历史单任务回调兼容)。 + + Returns: + str: success | skipped | failed + """ + raw_status = str(payload.get("status") or "").strip().lower() + if raw_status in {"success", "skipped", "failed"}: + return raw_status + if payload.get("skipped"): + return "skipped" + if bool(payload.get("success", True)): + return "success" + return "failed" + + +def normalize_inventory_batch_item_status(item: dict[str, Any]) -> str: + """归一化 batch results 单条明细(比单任务更严格:缺字段不算 success)。 + + 核心逻辑:与 worker `_normalize_inventory_batch_item_status` 对齐;空 dict 或 + 缺 status/success/skipped 直接归为 failed,避免误走 success→file_missing 分支。 + + Returns: + str: success | skipped | failed + """ + raw_status = str(item.get("status") or "").strip().lower() + if raw_status in {"success", "skipped", "failed"}: + return raw_status + if item.get("skipped"): + return "skipped" + if item.get("success") is True: + return "success" + return "failed" + + +def merge_batch_callback_item(payload: dict[str, Any], item: dict[str, Any]) -> dict[str, Any]: + """合并 batch 顶层契约字段到 result item。 + + 核心逻辑:合并 batch 已认证的 schema_version / run_no / task_no;其余身份字段必须由 + Worker item 显式返回,禁止后端从任务或数据库补齐。 + + Returns: + dict: 合并后的 item 副本(不修改入参)。 + """ + merged = dict(item) + top_schema_version = str(payload.get('schema_version') or '').strip() + if top_schema_version and not str(merged.get('schema_version') or '').strip(): + merged['schema_version'] = top_schema_version + top_run_no = str(payload.get("run_no") or "").strip() + if top_run_no and not str(merged.get("run_no") or "").strip(): + merged["run_no"] = top_run_no + + task_no = str(merged.get("task_no") or payload.get("task_no") or "").strip() + if task_no and not str(merged.get("task_no") or "").strip(): + merged["task_no"] = task_no + return merged diff --git a/backend/app/services/freight_rpa/outbound/__init__.py b/backend/app/services/freight_rpa/outbound/__init__.py new file mode 100644 index 00000000..ccddbc5a --- /dev/null +++ b/backend/app/services/freight_rpa/outbound/__init__.py @@ -0,0 +1 @@ +"""outbound:出站 RPA。""" diff --git a/backend/app/services/freight_rpa/outbound/report_archive.py b/backend/app/services/freight_rpa/outbound/report_archive.py new file mode 100644 index 00000000..59746f44 --- /dev/null +++ b/backend/app/services/freight_rpa/outbound/report_archive.py @@ -0,0 +1,246 @@ +""" +services/freight_rpa/outbound/report_archive.py + +用途:outbound(出站)RPA 产物事实能力——Worker 回调的原样归档(xlsx 落 MinIO、 + 三年保留期、不写库存快照表)。 +依赖:models(FreightRpaOutboundReportFile / FreightRpaOutboundUnitRun)、 + file_assets.storage、freight_rpa.outbound.trigger_io(回调 SCHEMA 与 drop 根)、 + freight_rpa.common.report_audit(本域唯一审计写入口)、 + freight_rpa.reports.facts / reports.dispatch(ReportFact 事实投递)。 +逻辑:Worker 回调进入 /api/freight-rpa/outbound-batch-ready 后由组合根(Task 10) + 或测内临时 register 的 sink 调 ingest_outbound_callback 完成原样归档; + empty/success/failed 三个终态分支各自「先 db.session.commit() 再投递事实」—— + commit 后构造 ReportFact(report_kind='outbound', ...) 调 dispatch_report_fact; + 处理函数异常原样外抛(不吞、不回滚已提交终态);同一 unit_run_id + sha256 + 已有文件时不插第二行、仍投递 ok=True 的事实供处理函数重试。 + 跨机路径:file_path 只认 outbound drop 根内文件名,禁止把 Worker Windows + 绝对路径当 Linux 路径打开(对照 inbound._read_inbound_callback_file)。 + 本模块不 import shipping_notice / in_transit_transfer,不移植入站逐文件企微投递。 +""" + +from __future__ import annotations + +import hashlib +from datetime import datetime, timedelta +from pathlib import Path +from typing import Any + +from flask import current_app + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import ( + FreightRpaOutboundReportFile, + FreightRpaOutboundUnitRun, +) +from app.services.file_assets.storage import file_asset_storage +from app.services.freight_rpa.common.report_audit import append_rpa_report_event +from app.services.freight_rpa.outbound.trigger_io import SCHEMA as OUTBOUND_TRIGGER_SCHEMA, outbound_drop_dir +from app.services.freight_rpa.reports.dispatch import dispatch_report_fact +from app.services.freight_rpa.reports.facts import ReportFact + + +def _read_outbound_callback_file(file_path: str) -> bytes: + """只读取 outbound 专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。 + + 路径契约为「drop 根内文件名」:Worker(Windows RPA 主机)与后端(Linux 容器)分属 + 两机,各自看到的根路径不同(C:\\HxopsRpaTest\\... vs /mnt/hxops-rpa-*-data/...)。 + 一律 replace('\\','/') 后取 .name,再拼本机 FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR, + relative_to(root) 防穿越。禁止把回调串当 Linux 路径直接 open。 + """ + configured_root = str(outbound_drop_dir() or "").strip() + if not configured_root: + raise ValidationError( + "outbound callback file root is unavailable", + code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID", + ) + root = Path(configured_root).resolve() + # [STEP] 跨机:先归一分隔符再取末段文件名,绝不 Path(file_path).read_bytes()。 + name = Path(str(file_path).replace("\\", "/")).name + path = (root / name).resolve() + try: + path.relative_to(root) + except ValueError as exc: + raise ValidationError( + "outbound callback file is outside outbound drop root", + code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID", + ) from exc + if path.suffix.lower() != ".xlsx" or not path.is_file(): + raise ValidationError( + "outbound callback file must be an existing xlsx", + code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID", + ) + max_size = max(int(current_app.config.get("FILE_ASSET_MAX_SIZE_MB", 30) or 30), 1) * 1024 * 1024 + if path.stat().st_size > max_size: + raise ValidationError( + "outbound callback file exceeds configured size limit", + code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID", + ) + return path.read_bytes() + + +def ingest_outbound_callback(payload: dict[str, Any]) -> dict[str, Any]: + """幂等接收单个 outbound 单元回调,原样归档三年且不写库存快照表。 + + Args: + payload: Worker 回调载荷(schema_version/callback_id/status/file_path/...)。 + Returns: + dict: unit_run_id/status[/file_id/idempotent],供 HTTP envelope 的 data 使用。 + (brief 曾写 -> None;与入站 API envelope 对齐仍返回 dict。) + Raises: + ValidationError: 载荷非法(schema/callback_id/sha256/文件路径)——commit 之前抛出,不投递事实。 + NotFoundError: callback_id 无匹配单元——commit 之前抛出,不投递事实。 + AppError: 终态已 commit 后 kind 未注册处理函数(FREIGHT_RPA.SINK_NOT_REGISTERED, 404)。 + 业务顺序:每个终态分支先 db.session.commit() 再构造 + ReportFact(report_kind='outbound', source_code=unit.source_code, ...) 调 + dispatch_report_fact;事实恒带 unit_run_id=unit.id;处理函数异常原样外抛; + 同一 unit_run_id + sha256 已有文件时不插第二行,仍投递 ok=True 的事实。 + """ + if payload.get("schema_version") != OUTBOUND_TRIGGER_SCHEMA: + raise ValidationError( + "outbound callback schema_version is invalid", + code="SHIPPING.OUTBOUND_CALLBACK_INVALID", + ) + callback_id = str(payload.get("callback_id") or "").strip() + unit = FreightRpaOutboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none() + if unit is None: + raise NotFoundError("Outbound RPA unit not found", code="SHIPPING.OUTBOUND_UNIT_NOT_FOUND") + status = str(payload.get("status") or "").strip().lower() + before = {"status": unit.status, "error_code": unit.error_code, "error_message": unit.error_message} + if status in {"empty", "no_data"}: + # [STEP] 与入站 empty / 库存 no_inventory_data 对齐:empty 是合法业务结果。 + unit.status = "empty" + unit.error_code = str(payload.get("error_code") or "no_outbound_data")[:64] + unit.error_message = str(payload.get("error_message") or "no_outbound_data")[:2000] + unit.finished_at = datetime.utcnow() + append_rpa_report_event( + event_type="shipping_outbound_rpa_callback_received", + aggregate_type="shipping_outbound_unit", + aggregate_id=str(unit.id), + run_no=unit.schedule_run.run_no if unit.schedule_run else None, + actor_type="rpa", + actor_id="outbound-worker", + unit_id=unit.id, + result="success", + before=before, + after={ + "status": "empty", + "callback_id": unit.callback_id, + "error_code": unit.error_code, + "error_message": unit.error_message, + }, + metadata={"callback_status": status, "skip_reason": unit.error_code}, + ) + db.session.commit() + dispatch_report_fact(ReportFact( + report_kind="outbound", + source_code=unit.source_code, + file_id=None, + sha256=None, + ok=False, + error_code=unit.error_code or "no_outbound_data", + error_message=unit.error_message or "no_outbound_data", + unit_run_id=unit.id, + )) + return {"unit_run_id": unit.id, "status": "empty"} + if status != "success": + unit.status = "failed" + unit.error_code = str(payload.get("error_code") or "RPA.OUTBOUND_EXPORT_FAILED")[:64] + unit.error_message = str(payload.get("error_message") or "outbound export failed")[:2000] + unit.finished_at = datetime.utcnow() + append_rpa_report_event( + event_type="shipping_outbound_rpa_callback_received", + aggregate_type="shipping_outbound_unit", + aggregate_id=str(unit.id), + run_no=unit.schedule_run.run_no if unit.schedule_run else None, + actor_type="rpa", + actor_id="outbound-worker", + unit_id=unit.id, + result="failure", + before=before, + after={"status": "failed", "error_code": unit.error_code, "error_message": unit.error_message}, + metadata={"callback_status": status}, + ) + db.session.commit() + dispatch_report_fact(ReportFact( + report_kind="outbound", + source_code=unit.source_code, + file_id=None, + sha256=None, + ok=False, + error_code=unit.error_code, + error_message=unit.error_message, + unit_run_id=unit.id, + )) + return {"unit_run_id": unit.id, "status": "failed"} + data = _read_outbound_callback_file(str(payload.get("file_path") or "")) + sha256 = hashlib.sha256(data).hexdigest() + claimed = str(payload.get("sha256") or "").lower() + if claimed and claimed != sha256: + raise ValidationError( + "outbound callback sha256 mismatch", + code="SHIPPING.OUTBOUND_CALLBACK_SHA_MISMATCH", + ) + existing = FreightRpaOutboundReportFile.query.filter_by(unit_run_id=unit.id, sha256=sha256).one_or_none() + if existing: + dispatch_report_fact(ReportFact( + report_kind="outbound", + source_code=unit.source_code, + file_id=existing.id, + sha256=sha256, + ok=True, + unit_run_id=unit.id, + )) + return {"unit_run_id": unit.id, "status": unit.status, "file_id": existing.id, "idempotent": True} + filename = Path(str(payload.get("original_filename") or payload.get("file_path") or "outbound.xlsx")).name + storage_key = f"shipping/outbound-reports/{datetime.utcnow():%Y/%m}/{unit.id}/{sha256}.xlsx" + file_asset_storage.upload_bytes( + storage_key=storage_key, + data=data, + content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ) + record = FreightRpaOutboundReportFile( + unit_run_id=unit.id, + storage_provider="minio", + storage_bucket=file_asset_storage.bucket_name, + storage_key=storage_key, + original_filename=filename, + content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + file_size=len(data), + sha256=sha256, + archive_expires_at=datetime.utcnow() + timedelta(days=365 * 3), + ) + db.session.add(record) + unit.status = "success" + unit.finished_at = datetime.utcnow() + db.session.flush() + append_rpa_report_event( + event_type="shipping_outbound_report_archived", + aggregate_type="shipping_outbound_unit", + aggregate_id=str(unit.id), + run_no=unit.schedule_run.run_no if unit.schedule_run else None, + actor_type="rpa", + actor_id="outbound-worker", + unit_id=unit.id, + result="success", + before=before, + after={ + "status": "success", + "source_run_no": unit.callback_id, + "file_id": record.id, + "sha256": sha256, + "file_size": len(data), + }, + artifact_refs=[{"kind": "outbound_report", "id": str(record.id), "sha256": sha256}], + metadata={"file_size": len(data), "retention_days": 365 * 3}, + ) + db.session.commit() + dispatch_report_fact(ReportFact( + report_kind="outbound", + source_code=unit.source_code, + file_id=record.id, + sha256=sha256, + ok=True, + unit_run_id=unit.id, + )) + return {"unit_run_id": unit.id, "status": "success", "file_id": record.id, "idempotent": False} diff --git a/backend/app/services/freight_rpa/outbound/trigger_io.py b/backend/app/services/freight_rpa/outbound/trigger_io.py new file mode 100644 index 00000000..bab76679 --- /dev/null +++ b/backend/app/services/freight_rpa/outbound/trigger_io.py @@ -0,0 +1,92 @@ +""" +services/freight_rpa/outbound/trigger_io.py + +用途:outbound(出站)RPA 的纯文件 IO——trigger/落盘目录解析、批量 trigger JSON + 原子写入,以及 Worker 触发/回调契约常量(SCHEMA/ACTION_*)。 +依赖:Flask current_app 配置、Path/JSON/文件系统工具;不 import 任何业务编排模块 + (import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。 +逻辑:由 schedule.freight_rpa_outbound_job(排程写 trigger)、api.schedule.runs(admin 单元重试)、 + in_transit_transfer.outbound_trigger_service(调拨按需/批量触发)、 + freight_rpa.common.worker_heartbeat(outbound trigger 目录探测/就绪检查)、 + freight_rpa.outbound.report_archive(drop 目录定位与回调 SCHEMA 校验,后续任务)等调用, + 与外部 RPA Worker 的文件投递目录交互;schema/action 以本文件常量为单一真相 + (Worker 侧对表:freight_rpa.outbound.v1 / outbound_export_batch)。 +""" + +from __future__ import annotations + +import json +import os +from datetime import datetime +from pathlib import Path +from typing import Any + +from flask import current_app + +# Worker 触发/回调契约常量:后端写入侧与校验侧共用单一真相,禁止再写字面量。 +SCHEMA = "freight_rpa.outbound.v1" +ACTION_OUTBOUND_EXPORT_BATCH = "outbound_export_batch" + + +def _path(key: str) -> Path | None: + value = str(current_app.config.get(key) or "").strip() + if not value: + return None + return Path(value) + + +def outbound_trigger_dir() -> Path | None: + """RPA outbound 批量导出触发 JSON 目录(FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR); + 绝不回落到 onhand/inbound trigger 目录。""" + return _path("FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR") + + +def outbound_drop_dir() -> Path | None: + """RPA outbound 导出文件落盘目录(FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR)。""" + return _path("FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR") + + +def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None: + """原子发布 trigger,避免 Worker 读取到写入中的半截 JSON。""" + temp_path = path.with_name(f'.{path.name}.{os.getpid()}.tmp') + try: + with open(temp_path, 'w', encoding='utf-8') as handle: + json.dump(body, handle, ensure_ascii=False, indent=2) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temp_path, path) + finally: + if temp_path.exists(): + temp_path.unlink(missing_ok=True) + + +def write_outbound_export_batch_trigger( + run_no: str, + units: list[dict[str, Any]], + meta: dict[str, Any] | None = None, +) -> str | None: + """ + 写入 outbound 批量 trigger 文件 outbound_export_batch_{run_no}.json + (Worker 轮询 /*.json 按内容消费,schema/action 取本文件常量)。 + + Args: + run_no: 批次运行号;进 body.batch_run_no 并参与文件名(安全化仅保留字母数字-_)。 + units: 触发单元载荷列表;业务约束——空列表直接返回 None(无单元不落盘)。 + meta: 调用方附加字段,合并覆盖 body 顶层键(schema_version/action 缺省取常量)。 + + Returns: + str | None: 触发文件绝对路径;目录未配置或 units 为空时返回 None。 + """ + trigger_dir = outbound_trigger_dir() + if not trigger_dir or not units: + return None + trigger_dir.mkdir(parents=True, exist_ok=True) + safe_run_no = ''.join(char for char in run_no if char.isalnum() or char in {'-', '_'}) or 'outbound' + body = { + 'schema_version': SCHEMA, 'action': ACTION_OUTBOUND_EXPORT_BATCH, + 'batch_run_no': run_no, 'requested_at': datetime.utcnow().isoformat(), 'units': units, + **(meta or {}), + } + path = trigger_dir / f'outbound_export_batch_{safe_run_no}.json' + _write_trigger_json_atomic(path, body) + return str(path) diff --git a/backend/app/services/shipping_notice/inventory_parsing_profile.py b/backend/app/services/freight_rpa/parsing_profile.py similarity index 68% rename from backend/app/services/shipping_notice/inventory_parsing_profile.py rename to backend/app/services/freight_rpa/parsing_profile.py index 12b048b0..3dc38ab6 100644 --- a/backend/app/services/shipping_notice/inventory_parsing_profile.py +++ b/backend/app/services/freight_rpa/parsing_profile.py @@ -1,9 +1,16 @@ """ -backend/app/services/shipping_notice/inventory_parsing_profile.py +services/freight_rpa/parsing_profile.py -用途:管理可跨库存源复用的版本化库存解析 Profile,并为运行期提供确定性解析定义。 -依赖:ShippingInventoryParsingProfile、ShippingInventorySource、ShippingOrderField、inventory_mapping。 -逻辑:管理员保存草稿并发布不可变版本;库存源仅绑定 published Profile,解析链直接使用定义中的列映射与订单字段匹配键。 +用途:管理货代「报表规则」(FreightRpaParsingProfile)的草稿/发布与运行期定义读取。 + purpose=onhand 走库存字段目录 + match_keys;purpose=inbound/outbound 走调拨 + MOVEMENT_FIELDS 契约(与在途异动对齐)。 +依赖:FreightRpaParsingProfile、FreightRpaOnhandReportConfig、FreightRpaInboundReportConfig、 + FreightRpaOutboundReportConfig、ShippingOrderField、 + in_transit_transfer.movement_contract.MOVEMENT_FIELDS、 + shipping_notice.order_schema(仅 onhand 发布时校验订单字段)。 +逻辑:管理员保存草稿并发布不可变版本;来源站点 / 入站·出站报表配置只绑定 published + Profile;退役前检查 onhand/inbound/outbound 配置引用。管理端入口 + /api/admin/freight-rpa/.../parsing-profiles。 """ from __future__ import annotations @@ -18,47 +25,49 @@ from sqlalchemy import func from app.core.errors import ConflictError, NotFoundError, ValidationError from app.extensions import db from app.models import ( - ShippingInventoryField, - ShippingInventoryParsingProfile, - ShippingInventorySource, - ShippingInventoryStructureAnalysis, + FreightRpaOnhandField, + FreightRpaOnhandReportConfig, + FreightRpaParsingProfile, + FreightRpaOnhandStructureAnalysis, ShippingOrderField, + FreightRpaInboundReportConfig, + FreightRpaOutboundReportConfig, ) -def _catalog_fields(field_mapping: dict[str, Any]) -> dict[str, ShippingInventoryField]: +def _catalog_fields(field_mapping: dict[str, Any]) -> dict[str, FreightRpaOnhandField]: """解析字段目录 ID 并确认均为可用于新方案的启用库存业务字段。""" field_ids: list[int] = [] for raw_id in field_mapping: try: field_id = int(raw_id) except (TypeError, ValueError) as exc: - raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') from exc + raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') from exc if field_id <= 0: - raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') field_ids.append(field_id) - rows = ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(set(field_ids))).all() if field_ids else [] + rows = FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(set(field_ids))).all() if field_ids else [] fields = {str(row.id): row for row in rows if row.status == 'active'} if len(fields) != len(set(str(item) for item in field_ids)): - raise ValidationError('Parsing profile inventory field is unavailable', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + raise ValidationError('Parsing profile inventory field is unavailable', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') return fields -def _required_catalog_field_ids(fields: dict[str, ShippingInventoryField]) -> set[str]: +def _required_catalog_field_ids(fields: dict[str, FreightRpaOnhandField]) -> set[str]: """校验解析方案具备匹配与库存数量能力,不限定字段名称。""" match_ids = {field_id for field_id, row in fields.items() if row.usage_type == 'match_identity'} quantity_ids = {field_id for field_id, row in fields.items() if row.usage_type == 'inventory_quantity'} if not match_ids or len(quantity_ids) != 1: raise ValidationError( 'Parsing profile requires at least one match field and exactly one inventory quantity field', - code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID', + code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID', ) return match_ids | quantity_ids -# 异动(movement)用途的定死字段端点与必需字段集(领域定死,不依赖库存字段目录)。 +# 入站(inbound)用途的定死字段端点与必需字段集(领域定死,不依赖库存字段目录)。 def _required_movement_field_ids(definition: dict[str, Any]) -> set[str]: - """校验 movement 用途的解析定义只引用定死领域字段,且必需字段齐全。""" + """校验 inbound/outbound 用途的解析定义只引用定死领域字段,且必需字段齐全。""" from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS movement_codes = {field.code for field in MOVEMENT_FIELDS} @@ -68,37 +77,37 @@ def _required_movement_field_ids(definition: dict[str, Any]) -> set[str]: if unknown: raise ValidationError( f'Movement parsing profile references unknown field: {sorted(unknown)}', - code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID', + code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID', ) missing = {code for code in ('doc_no', 'material_code', 'quantity', 'movement_date') if code not in mapped_codes} if missing: raise ValidationError( f'Movement parsing profile requires doc_no/material_code/quantity/movement_date: {sorted(missing)}', - code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID', + code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID', ) return mapped_codes -def _validate_definition(raw: Any, *, purpose: str = 'inventory') -> dict[str, Any]: +def _validate_definition(raw: Any, *, purpose: str = 'onhand') -> dict[str, Any]: """校验字段目录 ID 到来源表头的映射及订单明细匹配键,禁止自由脚本。 Args: raw: 解析定义对象。 - purpose: 'inventory'(沿用库存字段目录与 match_keys)或 - 'movement'(端点用定死 MOVEMENT_FIELDS,无 match_keys)。 + purpose: 'onhand'(库存字段目录 + match_keys)或 + 'inbound'/'outbound'(端点用定死 MOVEMENT_FIELDS,无 match_keys)。 """ if not isinstance(raw, dict): - raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') field_mapping = raw.get('field_mapping') if not isinstance(field_mapping, dict) or not field_mapping: - raise ValidationError('Parsing profile requires complete field mapping', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + raise ValidationError('Parsing profile requires complete field mapping', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') if any(not str(value or '').strip() for value in field_mapping.values()): - raise ValidationError('Parsing profile field mapping is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + raise ValidationError('Parsing profile field mapping is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') header_row_index = raw.get('header_row_index') if header_row_index is not None and (not isinstance(header_row_index, int) or header_row_index < 1): - raise ValidationError('header_row_index is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + raise ValidationError('header_row_index is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') - if purpose == 'movement': + if purpose in {'inbound', 'outbound'}: _required_movement_field_ids(raw) return { 'sheet_name': str(raw.get('sheet_name') or '').strip() or None, @@ -111,7 +120,7 @@ def _validate_definition(raw: Any, *, purpose: str = 'inventory') -> dict[str, A _required_catalog_field_ids(catalog_fields) match_keys = raw.get('match_keys') if not isinstance(match_keys, list) or not match_keys: - raise ValidationError('Parsing profile requires match keys', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + raise ValidationError('Parsing profile requires match keys', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') normalized_keys: list[dict[str, str]] = [] seen_order_fields: set[str] = set() seen_inventory_fields: set[str] = set() @@ -123,9 +132,9 @@ def _validate_definition(raw: Any, *, purpose: str = 'inventory') -> dict[str, A field is None or field.status != 'active' or field.scope != 'line' or inventory is None or inventory.usage_type != 'match_identity' ): - raise ValidationError('Parsing profile match key is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + raise ValidationError('Parsing profile match key is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') if field.id in seen_order_fields or inventory_field in seen_inventory_fields: - raise ValidationError('Parsing profile match keys must be unique', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + raise ValidationError('Parsing profile match keys must be unique', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') seen_order_fields.add(field.id) seen_inventory_fields.add(inventory_field) normalized_keys.append({'order_field_id': field.id, 'inventory_field_id': inventory_field}) @@ -142,20 +151,20 @@ def _require_sample_evidence( definition: dict[str, Any], *, file_format: str, -) -> ShippingInventoryStructureAnalysis: +) -> FreightRpaOnhandStructureAnalysis: """校验草稿仅能使用已持久化样本证据中的工作表、表头和来源栏位。""" try: analysis_id = int(sample_analysis_id) except (TypeError, ValueError) as exc: raise ValidationError( 'Parsing profile requires sample analysis evidence', - code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED', + code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_REQUIRED', ) from exc - analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id) + analysis = db.session.get(FreightRpaOnhandStructureAnalysis, analysis_id) if analysis is None or analysis.analysis_status != 'ready' or analysis.file_format != file_format: raise ValidationError( 'Parsing profile sample analysis evidence is unavailable', - code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED', + code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_REQUIRED', ) structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {} candidates = structure.get('candidates') if isinstance(structure.get('candidates'), list) else [] @@ -165,13 +174,13 @@ def _require_sample_evidence( if not isinstance(selected, dict): raise ValidationError( 'Parsing profile worksheet or header row is not present in sample evidence', - code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID', + code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID', ) headers = {str(header).strip() for header in selected.get('headers', []) if str(header).strip()} if any(str(header or '').strip() not in headers for header in (definition.get('field_mapping') or {}).values()): raise ValidationError( 'Parsing profile mapping is not present in sample evidence', - code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID', + code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID', ) duplicates = { str(column.get('header') or '').strip() @@ -180,12 +189,12 @@ def _require_sample_evidence( if any(str(header).strip() in duplicates for header in (definition.get('field_mapping') or {}).values()): raise ValidationError( 'Parsing profile mapping uses duplicate sample headers', - code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID', + code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID', ) return analysis -def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]: +def payload(profile: FreightRpaParsingProfile) -> dict[str, Any]: """序列化解析 Profile 管理 DTO。""" sample_analysis = profile.sample_analysis return { @@ -211,49 +220,49 @@ def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]: def list_profiles() -> list[dict[str, Any]]: """列出全部解析 Profile 版本。""" - return [payload(item) for item in ShippingInventoryParsingProfile.query.order_by( - ShippingInventoryParsingProfile.profile_code, ShippingInventoryParsingProfile.version.desc(), + return [payload(item) for item in FreightRpaParsingProfile.query.order_by( + FreightRpaParsingProfile.profile_code, FreightRpaParsingProfile.version.desc(), ).all()] def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]: """创建或更新解析 Profile 草稿;必须绑定样本证据,published 版本不可原地修改。""" - profile = db.session.get(ShippingInventoryParsingProfile, profile_id) if profile_id else None + profile = db.session.get(FreightRpaParsingProfile, profile_id) if profile_id else None if profile_id and profile is None: - raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND') + raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND') if profile is not None and profile.status != 'draft': - raise ConflictError('Published parsing profile is immutable', code='SHIPPING.INVENTORY_PARSING_PROFILE_IMMUTABLE') + raise ConflictError('Published parsing profile is immutable', code='SHIPPING.ONHAND_PARSING_PROFILE_IMMUTABLE') code = str(data.get('profile_code') or '').strip().upper() if not code: - raise ValidationError('profile_code is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + raise ValidationError('profile_code is required', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') if profile is not None and code != profile.profile_code: - raise ConflictError('Draft profile_code is immutable', code='SHIPPING.INVENTORY_PARSING_PROFILE_IMMUTABLE') + raise ConflictError('Draft profile_code is immutable', code='SHIPPING.ONHAND_PARSING_PROFILE_IMMUTABLE') if profile is None: - next_version = int(db.session.query(func.max(ShippingInventoryParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1 - profile = ShippingInventoryParsingProfile(profile_code=code, version=next_version, created_by=actor_id) + next_version = int(db.session.query(func.max(FreightRpaParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1 + profile = FreightRpaParsingProfile(profile_code=code, version=next_version, created_by=actor_id) db.session.add(profile) - purpose = str(data.get('purpose') or profile.purpose or 'inventory').strip().lower() - if purpose not in {'inventory', 'movement'}: - raise ValidationError('purpose is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + purpose = str(data.get('purpose') or profile.purpose or 'onhand').strip().lower() + if purpose not in {'onhand', 'inbound', 'outbound'}: + raise ValidationError('purpose is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') if profile_id and purpose != profile.purpose: raise ValidationError( 'Draft parsing profile purpose is immutable', - code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID', + code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID', ) profile.purpose = purpose profile.display_name = str(data.get('display_name') or code).strip() requested_file_format = str(data.get('file_format') or 'xlsx').lower() if requested_file_format not in {'xls', 'xlsx', 'csv'}: - raise ValidationError('file_format is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + raise ValidationError('file_format is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') if profile_id and requested_file_format != profile.file_format: raise ValidationError( 'Draft parsing profile file format is immutable', - code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID', + code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID', ) profile.file_format = requested_file_format definition = _validate_definition(data.get('definition'), purpose=purpose) if profile.file_format == 'csv' and definition.get('sheet_name'): - raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') + raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') sample_analysis = _require_sample_evidence( data.get('sample_analysis_id', profile.sample_analysis_id), definition, file_format=profile.file_format, ) @@ -261,7 +270,7 @@ def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | if not bool(data.get('confirm_sample_replacement')): raise ValidationError( 'Replacing inventory sample evidence requires confirmation', - code='SHIPPING.INVENTORY_SAMPLE_REPLACEMENT_CONFIRMATION_REQUIRED', + code='SHIPPING.ONHAND_SAMPLE_REPLACEMENT_CONFIRMATION_REQUIRED', ) history = list(profile.sample_evidence_history_json or []) history.append({ @@ -279,23 +288,23 @@ def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]: """发布解析 Profile;既有 published 版本继续供已绑定库存源稳定使用。""" - profile = db.session.get(ShippingInventoryParsingProfile, profile_id) + profile = db.session.get(FreightRpaParsingProfile, profile_id) if profile is None: - raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND') + raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND') if profile.status != 'draft': - raise ConflictError('Only draft parsing profile can be published', code='SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID') + raise ConflictError('Only draft parsing profile can be published', code='SHIPPING.ONHAND_PARSING_PROFILE_PUBLISH_INVALID') _require_sample_evidence( profile.sample_analysis_id, profile.definition_json or {}, file_format=profile.file_format, ) from app.services.shipping_notice.order_schema import service as order_schema_service - # movement 用途无订单匹配键(端点为定死异动字段),跳过订单 Schema 契约校验;inventory 维持原约束。 + # inbound/outbound 无订单匹配键(端点为定死异动字段),跳过订单 Schema 契约校验;onhand 维持原约束。 referenced_field_ids = { str(item.get('order_field_id') or '') for item in (profile.definition_json or {}).get('match_keys', []) if isinstance(item, dict) } - if profile.purpose != 'movement': + if profile.purpose == 'onhand': published_field_ids = { str(item.get('field_id') or '') for item in order_schema_service.get_published_contract().get('fields', []) @@ -303,7 +312,7 @@ def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]: if not referenced_field_ids or not referenced_field_ids <= published_field_ids: raise ValidationError( 'Parsing profile match keys must reference the current published order schema', - code='SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID', + code='SHIPPING.ONHAND_PARSING_PROFILE_PUBLISH_INVALID', ) encoded = json.dumps(profile.definition_json, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode() profile.checksum = hashlib.sha256(encoded).hexdigest() @@ -315,14 +324,20 @@ def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]: def retire(profile_id: int) -> dict[str, Any]: - """退役无库存源引用的 published Profile,避免使现有 Source 静默失效。""" - profile = db.session.get(ShippingInventoryParsingProfile, profile_id) + """退役无库存源/入站/出站报表配置引用的 published Profile,避免使现有绑定静默失效。""" + profile = db.session.get(FreightRpaParsingProfile, profile_id) if profile is None: - raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND') + raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND') if profile.status != 'published': - raise ConflictError('Only published parsing profile can be retired', code='SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_INVALID') - if ShippingInventorySource.query.filter_by(parsing_profile_id=profile.id).count(): - raise ConflictError('Rebind inventory sources before retiring profile', code='SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_BLOCKED') + raise ConflictError('Only published parsing profile can be retired', code='SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_INVALID') + # s18 起库存站点绑定归 FreightRpaOnhandReportConfig 配置行,站点行不再承载该外键。 + bound_sources = FreightRpaOnhandReportConfig.query.filter_by(parsing_profile_id=profile.id).count() + # 入站/出站报表配置同样绑定解析 Profile:退役前必须一并核查, + # 否则入站/出站文件解析链会静默失去规则。 + bound_inbound_configs = FreightRpaInboundReportConfig.query.filter_by(parsing_profile_id=profile.id).count() + bound_outbound_configs = FreightRpaOutboundReportConfig.query.filter_by(parsing_profile_id=profile.id).count() + if bound_sources or bound_inbound_configs or bound_outbound_configs: + raise ConflictError('Rebind inventory sources before retiring profile', code='SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED') profile.status = 'retired' db.session.commit() return payload(profile) @@ -330,18 +345,20 @@ def retire(profile_id: int) -> dict[str, Any]: def delete_draft(profile_id: int) -> None: """删除从未发布的解析 Profile 草稿。""" - profile = db.session.get(ShippingInventoryParsingProfile, profile_id) + profile = db.session.get(FreightRpaParsingProfile, profile_id) if profile is None: - raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND') + raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND') if profile.status != 'draft': - raise ConflictError('Only draft parsing profile can be deleted', code='SHIPPING.INVENTORY_PARSING_PROFILE_DELETE_BLOCKED') + raise ConflictError('Only draft parsing profile can be deleted', code='SHIPPING.ONHAND_PARSING_PROFILE_DELETE_BLOCKED') db.session.delete(profile) db.session.commit() -def require_source_profile(source: Any) -> ShippingInventoryParsingProfile: +def require_source_profile(source: Any) -> FreightRpaParsingProfile: """读取库存源绑定的 published 解析 Profile;缺失或非发布状态时阻断自动解析。""" - profile = getattr(source, 'parsing_profile', None) + # s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系。 + config = getattr(source, 'onhand_report_config', None) + profile = config.parsing_profile if config is not None else None if profile is None or profile.status != 'published': - raise ConflictError('Inventory source parsing profile is not published', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED') + raise ConflictError('Inventory source parsing profile is not published', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED') return profile diff --git a/backend/app/services/freight_rpa/reports/__init__.py b/backend/app/services/freight_rpa/reports/__init__.py new file mode 100644 index 00000000..d08ec315 --- /dev/null +++ b/backend/app/services/freight_rpa/reports/__init__.py @@ -0,0 +1,51 @@ +"""freight_rpa/reports/__init__.py + +用途:报表读域——发货(shipping_notice 域)与在途调拨 + (in_transit_transfer 域)读取货代 RPA 报表事实的唯一入口包(含出站配置视图)。 +依赖:facts(报表事实与 report kind 白名单)、queries(只读查询与解析失败标记)。 +逻辑:仅做门面转发;调用方(后续 in_transit_transfer / shipping_notice) + 一律 import 本包,禁止绕过直接引用 freight_rpa 模型表。 + 本包不得 import app.services.shipping_notice 或 app.services.in_transit_transfer + (import 边界由 tests/services/freight_rpa/test_report_queries.py 与 + test_import_boundary.py 锁定)。 +""" + +from app.services.freight_rpa.reports.facts import REPORT_KINDS, ReportFact, require_report_kind +from app.services.freight_rpa.reports.queries import ( + InboundConfigView, + InboundFileView, + OnhandConfigView, + OutboundConfigView, + SiteView, + clear_inbound_parse_failure, + get_inbound_config, + get_onhand_config, + get_outbound_config, + get_site, + latest_usable_inbound_file, + list_outbound_configured_source_codes, + mark_inbound_parse_failure, + read_inbound_file_bytes, + usable_inbound_file_condition, +) + +__all__ = [ + 'REPORT_KINDS', + 'InboundConfigView', + 'InboundFileView', + 'OnhandConfigView', + 'OutboundConfigView', + 'ReportFact', + 'SiteView', + 'clear_inbound_parse_failure', + 'get_inbound_config', + 'get_onhand_config', + 'get_outbound_config', + 'get_site', + 'latest_usable_inbound_file', + 'list_outbound_configured_source_codes', + 'mark_inbound_parse_failure', + 'read_inbound_file_bytes', + 'require_report_kind', + 'usable_inbound_file_condition', +] \ No newline at end of file diff --git a/backend/app/services/freight_rpa/reports/dispatch.py b/backend/app/services/freight_rpa/reports/dispatch.py new file mode 100644 index 00000000..666712c5 --- /dev/null +++ b/backend/app/services/freight_rpa/reports/dispatch.py @@ -0,0 +1,79 @@ +"""freight_rpa/reports/dispatch.py + +用途:报表事实(ReportFact)处理函数注册表与分发缝——RPA 回调「先 commit + 终态、再投递事实」的第二段分发(批次 B Task 6)。 +依赖:app.core.errors.AppError、freight_rpa.reports.facts(ReportFact、 + require_report_kind)。 +逻辑:组合根(shipping_notice.rpa_sinks.register_onhand_sinks / + in_transit_transfer.rpa_sinks.register_inbound_sinks / + register_outbound_sinks)在应用启动时调用 register_report_handler 注入各 + kind 的业务处理函数;归档入口(如 freight_rpa.inbound.report_archive. + ingest_inbound_callback)在每个终态 db.session.commit() 之后调用 + dispatch_report_fact。kind 未注册时显式 404(FREIGHT_RPA. + SINK_NOT_REGISTERED,与 common.callback_sinks.dispatch_sink 同码), + 绝不静默吞事实;处理函数异常原样向外抛(供 Worker/上层重试整笔回调)。 + 本模块不 commit、不 rollback。 +""" + +from __future__ import annotations + +from typing import Callable + +from app.core.errors import AppError +from app.services.freight_rpa.reports.facts import ReportFact, require_report_kind + +# 报表事实处理函数契约:接收单个 ReportFact,返回 None; +# 异常由调用方外抛重试,处理函数内部禁止自行吞异常。 +Handler = Callable[[ReportFact], None] + +# kind → 处理函数注册表(模块级单例;同 kind 重复注册为覆盖)。 +_REPORT_HANDLERS: dict[str, Handler] = {} + + +def register_report_handler(report_kind: str, handler: Handler) -> None: + """ + 注册一个报表事实处理函数(由组合根在应用启动时调用)。 + + 【AI 触发时机】:组合根装配(register_onhand_sinks / register_inbound_sinks / + register_outbound_sinks)时调用;测试直接调用注入临时处理函数。 + 核心逻辑:kind 先经 require_report_kind 白名单校验(onhand / inbound / + outbound,非法即 400 fail-closed);同一 kind 重复注册为覆盖。 + Args: + report_kind: 报表种类字符串(必须在 REPORT_KINDS 白名单内)。 + handler: 处理函数(Handler 契约见模块 docstring);本模块只保存引用, + 不校验其内部行为。 + Raises: + ValidationError: report_kind 不在白名单(code=SHIPPING.INBOUND_CALLBACK_INVALID)。 + """ + kind = require_report_kind(report_kind) + _REPORT_HANDLERS[kind] = handler + + +def dispatch_report_fact(fact: ReportFact) -> None: + """ + 把已随终态 commit 的报表事实投递给对应 kind 的处理函数。 + + 【AI 触发时机】:归档入口(如 ingest_inbound_callback)在每个终态 + db.session.commit() 之后调用;禁止用于 commit 之前的路径(非法载荷 / + 单元不存在 / 落库失败均不得投递)。 + 核心逻辑:kind 经 require_report_kind 校验后查注册表;命中即调用处理函数, + 其异常原样向外抛(不包日志、不吞);未注册抛 + AppError(code='FREIGHT_RPA.SINK_NOT_REGISTERED', http_status=404)。 + 本函数不 commit、不 rollback。 + Args: + fact: 终态已落库后构造好的报表事实(report_kind/source_code/file_id/ + sha256/ok/error_code/error_message)。 + Raises: + ValidationError: fact.report_kind 不在白名单。 + AppError: kind 未注册处理函数(404;归档终态已提交不回滚, + Worker 重试整笔回调即可补投递)。 + """ + kind = require_report_kind(fact.report_kind) + handler = _REPORT_HANDLERS.get(kind) + if handler is None: + raise AppError( + code='FREIGHT_RPA.SINK_NOT_REGISTERED', + message=f'No report handler registered for kind: {kind}', + http_status=404, + ) + handler(fact) diff --git a/backend/app/services/freight_rpa/reports/facts.py b/backend/app/services/freight_rpa/reports/facts.py new file mode 100644 index 00000000..e718874a --- /dev/null +++ b/backend/app/services/freight_rpa/reports/facts.py @@ -0,0 +1,71 @@ +"""freight_rpa/reports/facts.py + +用途:定义跨域报表「事实」的传输契约——report kind 白名单与 ReportFact。 +依赖:app.core.errors.ValidationError(非法 kind 的统一失败出口)。 +逻辑:本模块是纯契约层(dataclass + 校验函数),不做任何数据库/IO 操作; + report kind 只认 onhand / inbound / outbound,非法值抛 + ValidationError(code='SHIPPING.INBOUND_CALLBACK_INVALID'), + 与收料回调契约共用既有错误码(后续任务 6/7 的回调分发依赖此约定)。 + 本模块不 import shipping_notice / in_transit_transfer。 + 【Task 7 修复轮 2】ReportFact 末位新增可选 unit_run_id——归档入口每次投递 + 必从单元行回填,供消费方处理函数精确定位本次回调收尾的执行单元。 +""" + +from __future__ import annotations + +from dataclasses import dataclass + +from app.core.errors import ValidationError + +# 【AI 触发时机】AI 或调用方在构造 ReportFact / 分发报表回调前必须先用 +# require_report_kind 归一化校验 kind;白名单之外的取值一律拒绝。 +REPORT_KINDS = ('onhand', 'inbound', 'outbound') + +# 非法 report kind 复用收料回调契约错误码:同一回调入口族共享一个客户端可辨识码, +# 避免为同一类入参错误分裂出多个近义 code。 +_INVALID_KIND_ERROR_CODE = 'SHIPPING.INBOUND_CALLBACK_INVALID' + + +@dataclass(frozen=True) +class ReportFact: + """一份回报表的事实行(跨域只读传输对象)。 + + 用途:RPA 回调归档后,由 freight_rpa 域产生、发货/调拨域消费的最小事实快照; + ok=False 时 error_code/error_message 描述失败原因。 + 约束:frozen 不可变;file_id/sha256 允许 None(抓取失败时无产物可指); + unit_run_id 为归档入口回填的执行单元主键(Task 7 修复轮 2 起每次投递 + 必带——处理函数据此精确定位「本次回调收尾的单元」,禁止按来源猜最新), + 允许 None 仅为兼容手工构造事实的旧调用方,dispatch 产线恒非空。 + """ + + report_kind: str + source_code: str + file_id: int | None + sha256: str | None + ok: bool + error_code: str | None = None + error_message: str | None = None + unit_run_id: int | None = None + + +def require_report_kind(value: str) -> str: + """校验并原样返回合法的 report kind。 + + 用途:构造 ReportFact、注册/分发报表处理器前,把 kind 校验收敛到唯一入口。 + 核心逻辑:value 不在 REPORT_KINDS 白名单(onhand / inbound / outbound)即抛 + ValidationError(code='SHIPPING.INBOUND_CALLBACK_INVALID'),fail-closed。 + + Args: + value: 待校验的报表种类字符串;空值/大小写敏感不匹配同样视为非法。 + Returns: + 原样返回通过校验的 value(不含默认值/归一化,调用方以返回值为准)。 + Raises: + ValidationError: value 不在白名单内(HTTP 400,不可重试)。 + """ + if value not in REPORT_KINDS: + raise ValidationError( + f"Unsupported report kind: {value!r}", + code=_INVALID_KIND_ERROR_CODE, + details={'report_kind': value, 'allowed': list(REPORT_KINDS)}, + ) + return value \ No newline at end of file diff --git a/backend/app/services/freight_rpa/reports/queries.py b/backend/app/services/freight_rpa/reports/queries.py new file mode 100644 index 00000000..063fa772 --- /dev/null +++ b/backend/app/services/freight_rpa/reports/queries.py @@ -0,0 +1,802 @@ +"""freight_rpa/reports/queries.py + +用途:本模块是发货与调拨读报表的唯一入口——以只读视图(View dataclass)+ + 解析失败标记的方式,向 in_transit_transfer / shipping_notice 域暴露 + freight_rpa 报表事实(站点、登录连接、在手/入站/出站报表配置、入站解析方案、 + 入站归档文件),使消费方不再直接 import freight_rpa 模型表。 +依赖:app.db、app.models(FreightRpaSource / FreightRpaOnhandReportConfig / + FreightRpaInboundReportConfig / FreightRpaOutboundReportConfig / + FreightRpaInboundReportFile;登录连接 + (RpaProfile)与解析方案(ParsingProfile)经站点/配置关系连线引用)、 + app.core.errors(NotFoundError)、 + file_assets.storage.file_asset_storage(按 storage_key 读对象字节)。 +逻辑:【禁止】import app.services.shipping_notice 或 app.services.in_transit_transfer + ——方向只能反过来(门禁模块阶段 B Task 4 起引用本模块的过滤表达式)。 + usable / expired_inbound_file_condition 是入站归档文件「可用/失效」过滤 + 表达式的唯一权威(自 in_transit_transfer/inbound_file_gate.py 迁移, + 两条件同核 _fresh_and_retention_valid 推导,规则文本只此一份):可用 = + 未删除(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取 + + 未过期(archive_expires_at 为空视为长期有效或晚于当前时刻);失效 = + 未删除 且 核心不成立。业务日窗口换算(date_policy.business_date_utc_window + 的数学)以私有 helper 内联在本文件,就是为了不 import in_transit_transfer + (import 禁令)而保持口径逐位一致。 + 【阶段 B Task 4】站点视图补主键/连接绑定/仓库识别方式与入站配置视图补 + config_id/config_version;新增登录连接(get_rpa_login_profile)、入站解析 + 方案(get_inbound_parsing_profile / get_outbound_parsing_profile)、失效文件 + 存在性(has_expired_inbound_file)、重建通道归档清单 + (list_reparseable_inbound_files / list_reparseable_outbound_files)、入站/ + 出站可用站点编码清单(list_inbound_configured_source_codes / + list_outbound_configured_source_codes)——供 in_transit_transfer 收敛为 + 「只按 source_code / file_id 读取」的只读函数消费面。 + mark/clear 解析失败只 flush 不 commit——事务提交时机归属调用方。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import datetime, timedelta +from zoneinfo import ZoneInfo + +from sqlalchemy import ColumnElement, and_, not_, or_ + +from app import db +from app.core.errors import NotFoundError +from app.models import ( + FreightRpaInboundReportConfig, + FreightRpaInboundReportFile, + FreightRpaOnhandReportConfig, + FreightRpaOutboundReportConfig, + FreightRpaOutboundReportFile, + FreightRpaSource, +) +from app.services.file_assets.storage import file_asset_storage + +# 解析失败分层三列的截断上限,对齐列宽(String(64) / Text≈2000), +# 防止上游超长错误信息把写入顶爆。 +_PARSE_ERROR_CODE_MAX = 64 +_PARSE_ERROR_MESSAGE_MAX = 2000 + +# 业务时区固定 Asia/Shanghai(与 in_transit_transfer.date_policy 同值;本包内 +# 复制而非 import,见文件头 import 禁令)。 +_SHANGHAI_TZ = ZoneInfo("Asia/Shanghai") +_UTC_TZ = ZoneInfo("UTC") + + +def _business_date_utc_window(now: datetime | None = None) -> tuple[datetime, datetime]: + """返回当前业务日期(Asia/Shanghai)在 UTC 存储时间轴上的 [起, 止) 窗口。 + + 自 in_transit_transfer/date_policy.business_date_utc_window 逐位内联(阶段 B + Task 3 修复轮 1):数据库统一存 naive UTC,直接取 .date() 与业务日比较会 + 漂移 8 小时,必须先换算窗口再比较;不能 import date_policy,故复制其数学 + 并保持口径一致(此处内联即唯一权威,门禁模块后续引用本包)。 + + Args: + now: 可选时刻;naive 按 UTC 兼容处理(与 date_policy 口径一致), + 缺省取当前 Asia/Shanghai 时刻。 + Returns: + (窗口起, 窗口止);两者均为 naive UTC datetime,止为开区间(时长 24h)。 + """ + if now is None: + now = datetime.now(_SHANGHAI_TZ) + if now.tzinfo is None: + now = now.replace(tzinfo=_UTC_TZ) + sh_now = now.astimezone(_SHANGHAI_TZ) + start_utc = ( + datetime(sh_now.year, sh_now.month, sh_now.day, tzinfo=_SHANGHAI_TZ) + .astimezone(_UTC_TZ) + .replace(tzinfo=None) + ) + return start_utc, start_utc + timedelta(hours=24) + + +def _fresh_and_retention_valid(now: datetime) -> ColumnElement: + """新鲜度 + 保留期核心条件(不含删除态;可用/失效两条件同核推导,规则文本只此一份)。""" + window_start, window_end = _business_date_utc_window(now) + return and_( + FreightRpaInboundReportFile.created_at >= window_start, + FreightRpaInboundReportFile.created_at < window_end, + or_( + FreightRpaInboundReportFile.archive_expires_at.is_(None), + FreightRpaInboundReportFile.archive_expires_at > now, + ), + ) + + +def usable_inbound_file_condition(*, now: datetime | None = None) -> ColumnElement: + """返回「当前可用的入站归档文件」SQL 条件(唯一权威,供门禁模块引用)。 + + 判定(与 in_transit_transfer/inbound_file_gate 现行口径逐位一致): + 未删除(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取 + (created_at ∈ 业务日 UTC [窗口起, 窗口止) 窗口,naive UTC 存储)+ + 未过期(archive_expires_at 为空视为长期有效,否则须晚于判定时刻)。 + 本表达式全量自 inbound_file_gate.py 复制(阶段 B Task 3),此后以此为单一 + 事实来源,门禁模块改为引用本函数(禁止反向 import 出现环)。 + + Args: + now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。 + Returns: + 可直接并入 .filter() 的单个 SQLAlchemy 条件。 + """ + now = now or datetime.utcnow() + return and_( + FreightRpaInboundReportFile.archive_deleted_at.is_(None), + _fresh_and_retention_valid(now), + ) + + +def expired_inbound_file_condition(*, now: datetime | None = None) -> ColumnElement: + """返回「文件仍在但已失效」SQL 条件(来源状态投影 expired 的依据)。 + + 判定:未删除(archive_deleted_at 为空)且 新鲜度+保留期核心不成立 + (保留期已到 或 非当天业务日抓取)——与可用条件同核(_fresh_and_retention_valid) + 推导,口径只存在一处。阶段 B Task 4 自 in_transit_transfer/inbound_file_gate + 迁移至此(语义逐位一致),此后以本文件为唯一权威;命中即提示重试重抓, + 不报 ready,也不等待保留期清理任务落位。 + + Args: + now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。 + Returns: + 可直接并入 .filter() 的单个 SQLAlchemy 条件。 + """ + now = now or datetime.utcnow() + return and_( + FreightRpaInboundReportFile.archive_deleted_at.is_(None), + not_(_fresh_and_retention_valid(now)), + ) + + +@dataclass(frozen=True) +class SiteView: + """库存站点的只读视图:连接与模板绑定、启停状态(不含报表定义,s18 起)。 + + 阶段 B Task 4 增补三字段(调拨域路由/触发按 source_code 读站点主键与识别 + 方式时不再引用站点模型):source_id(站点主键,供映射查询等 FK 路径)、 + rpa_profile_id(登录连接绑定)、warehouse_resolution_mode(仓库识别方式)。 + """ + + source_code: str + display_name: str + connector_type: str + excel_template_id: int | None + enabled: bool + source_id: int = 0 + rpa_profile_id: int = 0 + warehouse_resolution_mode: str = "" + + +@dataclass(frozen=True) +class RpaLoginProfileView: + """RPA 登录连接只读视图(freight_rpa_profiles 行)。 + + 凭据密文原样透传(username/password_ciphertext)——仅限投递 RPA Worker + trigger,禁止出现在任何日志/接口响应中。 + """ + + profile_id: int + profile_code: str + login_url: str + login_config: dict + username_ciphertext: str | None + password_ciphertext: str | None + enabled: bool + + +@dataclass(frozen=True) +class OnhandConfigView: + """在手报表配置只读视图(freight_rpa_onhand_report_configs 行)。""" + + report_path_json: dict + query_parameters_json: list + parsing_profile_id: int | None + + +@dataclass(frozen=True) +class InboundConfigView: + """入站报表配置只读视图(freight_rpa_inbound_report_configs 行),与在手同构。 + + 阶段 B Task 4 增补 config_id / config_version(调拨入站触发落可审计单元行 + 快照需要配置行主键与版本,不再引用配置模型)。 + """ + + report_path_json: dict + query_parameters_json: list + parsing_profile_id: int | None + config_id: int = 0 + config_version: int = 1 + + +@dataclass(frozen=True) +class OutboundConfigView: + """出站报表配置只读视图(freight_rpa_outbound_report_configs 行),与入站同构。 + + config_id / config_version 供调拨出站触发落可审计单元行快照使用, + 不再引用配置模型。 + """ + + report_path_json: dict + query_parameters_json: list + parsing_profile_id: int | None + config_id: int = 0 + config_version: int = 1 + + +@dataclass(frozen=True) +class InboundProfileView: + """入站解析方案只读视图(freight_rpa_parsing_profiles 行)。 + + 定义(definition_json:field_mapping / sheet_name / header_row_index 等) + 原样透出;status/purpose 的 published-inbound 门禁决策归调用方按场景 + 自行 fail-closed(运行期取数、重建、触发守卫口径一致,见各自消费方)。 + """ + + profile_id: int + profile_code: str + version: int + status: str + purpose: str + definition_json: dict + + +@dataclass(frozen=True) +class InboundFileView: + """入站归档文件的只读视图;source_code 取自其所属执行单元行。 + + parse_failed_at 为解析失败分层的事实列(None=未失败/已清除)——阶段 B + Task 4 增补,供来源状态投影与证据同步判断 parse_failed,免除调用方二次查询。 + """ + + file_id: int + source_code: str + sha256: str + storage_key: str + original_filename: str + created_at: datetime + parse_failed_at: datetime | None = None + + +def get_site(source_code: str) -> SiteView | None: + """按 source_code 返回库存站点只读视图。 + + 用途:调拨/发货域读取站点连接、模板绑定与启停(例如入站触发预检)时调用, + 替代直接查询 FreightRpaSource。 + 核心逻辑:按 source_code 精确查第一条;命中即映射为 SiteView(frozen),否则 None。 + + Args: + source_code: 站点实例编码(大小写敏感,禁止传入模糊值)。 + Returns: + SiteView;站点不存在返回 None(调用方自行 fail-closed)。 + """ + site = FreightRpaSource.query.filter_by(source_code=source_code).first() + if site is None: + return None + return SiteView( + source_code=site.source_code, + display_name=site.display_name, + connector_type=site.connector_type, + excel_template_id=site.excel_template_id, + enabled=bool(site.enabled), + # [阶段 B Task 4] 调拨域(路由解析/入站触发)所需站点主键与识别方式。 + source_id=site.id, + rpa_profile_id=site.rpa_profile_id, + warehouse_resolution_mode=str(site.warehouse_resolution_mode or ""), + ) + + +def get_onhand_config(source_code: str) -> OnhandConfigView | None: + """按 source_code 返回在手报表配置只读视图。 + + 用途:RPA 触发读路径取报表路径、查询条件与解析方案绑定(s18 起配置挂在 + freight_rpa_onhand_report_configs,站点行不再承载这三列)。 + 核心逻辑:join 站点表按 source_code 查配置行,命中即映射视图;站点或配置行 + 缺失一律返回 None(fail-closed,调用方判 None 后阻断触发)。 + + Args: + source_code: 站点实例编码。 + Returns: + OnhandConfigView;站点无配置返回 None。 + """ + config = ( + FreightRpaOnhandReportConfig.query + .join(FreightRpaSource, FreightRpaOnhandReportConfig.source_id == FreightRpaSource.id) + .filter(FreightRpaSource.source_code == source_code) + .first() + ) + if config is None: + return None + return OnhandConfigView( + report_path_json=dict(config.report_path_json or {}), + query_parameters_json=list(config.query_parameters_json or []), + parsing_profile_id=config.parsing_profile_id, + ) + + +def get_inbound_config(source_code: str) -> InboundConfigView | None: + """按 source_code 返回入站报表配置只读视图(与在手配置同构)。 + + 用途:调拨入站触发读路径取收料报表定义;收料不设独立启停,是否运行由站点 + enabled 与本配置行是否存在决定。 + 核心逻辑:join 站点表按 source_code 查 freight_rpa_inbound_report_configs 行, + 命中即映射视图;缺失返回 None。 + + Args: + source_code: 站点实例编码。 + Returns: + InboundConfigView;站点或配置不存在返回 None。 + """ + config = ( + FreightRpaInboundReportConfig.query + .join(FreightRpaSource, FreightRpaInboundReportConfig.source_id == FreightRpaSource.id) + .filter(FreightRpaSource.source_code == source_code) + .first() + ) + if config is None: + return None + return InboundConfigView( + report_path_json=dict(config.report_path_json or {}), + query_parameters_json=list(config.query_parameters_json or []), + parsing_profile_id=config.parsing_profile_id, + # [阶段 B Task 4] 触发快照(config_snapshot)所需的配置行主键与版本。 + config_id=config.id, + config_version=int(config.config_version or 1), + ) + + +def get_outbound_config(source_code: str) -> OutboundConfigView | None: + """按 source_code 返回出站报表配置只读视图(与入站配置同构)。 + + 用途:调拨出站触发读路径取出站报表定义;出站不设独立启停,是否运行由站点 + enabled 与本配置行是否存在决定。 + 核心逻辑:join 站点表按 source_code 查 freight_rpa_outbound_report_configs 行, + 命中即映射视图;缺失返回 None。 + + Args: + source_code: 站点实例编码。 + Returns: + OutboundConfigView;站点或配置不存在返回 None。 + """ + config = ( + FreightRpaOutboundReportConfig.query + .join(FreightRpaSource, FreightRpaOutboundReportConfig.source_id == FreightRpaSource.id) + .filter(FreightRpaSource.source_code == source_code) + .first() + ) + if config is None: + return None + return OutboundConfigView( + report_path_json=dict(config.report_path_json or {}), + query_parameters_json=list(config.query_parameters_json or []), + parsing_profile_id=config.parsing_profile_id, + config_id=config.id, + config_version=int(config.config_version or 1), + ) + + +def get_rpa_login_profile(source_code: str) -> RpaLoginProfileView | None: + """按 source_code 返回站点绑定的 RPA 登录连接只读视图。 + + 用途:调拨入站 RPA 触发装配 trigger unit(登录页、凭据密文信封、连接编码) + 时调用,替代直接查询站点与其登录连接模型。 + 核心逻辑:按 source_code 取站点行再走 rpa_profile 关系;站点或连接缺失一律 + 返回 None(fail-closed,调用方判 None 后阻断触发)。凭据密文 + 原样透出(仅限投递 Worker trigger,调用方禁止落日志/响应)。 + + Args: + source_code: 站点实例编码(大小写敏感)。 + Returns: + RpaLoginProfileView;站点或连接不存在返回 None。 + """ + site = FreightRpaSource.query.filter_by(source_code=source_code).first() + profile = site.rpa_profile if site is not None else None + if profile is None: + return None + return RpaLoginProfileView( + profile_id=profile.id, + profile_code=profile.profile_code, + login_url=profile.login_url, + login_config=dict(profile.login_config_json or {}), + username_ciphertext=profile.username_ciphertext, + password_ciphertext=profile.password_ciphertext, + enabled=bool(profile.enabled), + ) + + +def get_inbound_parsing_profile(source_code: str) -> InboundProfileView | None: + """按 source_code 返回入站配置绑定的解析方案只读视图。 + + 用途:调拨运行期取数(movement_file_repository)、清空重建 + (backlog_reparse_service)与 RPA 触发守卫(deps)读取入站文件解析 + 规则定义时调用,替代直接持有配置模型关系。 + 核心逻辑:站点 → 入站配置 → 配置绑定的解析方案,任一环节缺失返回 None; + 不校验 status/purpose(调用方按场景自行 fail-closed,见 + InboundProfileView docstring)。 + + Args: + source_code: 站点实例编码。 + Returns: + InboundProfileView;无配置、未绑定或方案行缺失返回 None。 + """ + site = FreightRpaSource.query.filter_by(source_code=source_code).first() + config = site.inbound_report_config if site is not None else None + profile = config.parsing_profile if config is not None else None + if profile is None: + return None + return InboundProfileView( + profile_id=profile.id, + profile_code=profile.profile_code, + version=int(profile.version or 1), + status=profile.status, + purpose=profile.purpose, + definition_json=dict(profile.definition_json or {}), + ) + + +def get_outbound_parsing_profile(source_code: str) -> InboundProfileView | None: + """按 source_code 返回出站配置绑定的解析方案只读视图(与入站同形)。 + + 用途:调拨出站运行期落档(outbound_evidence_sync)与清空重建 + (backlog_reparse_service record_kind=outbound)读取出站文件解析规则。 + 核心逻辑:站点 → 出站配置 → 配置绑定的解析方案,任一环节缺失返回 None; + 不校验 status/purpose(调用方按场景自行 fail-closed)。 + + Args: + source_code: 站点实例编码。 + Returns: + InboundProfileView(字段同入站方案视图);无配置/未绑定/方案缺失返回 None。 + """ + site = FreightRpaSource.query.filter_by(source_code=source_code).first() + config = site.outbound_report_config if site is not None else None + profile = config.parsing_profile if config is not None else None + if profile is None: + return None + return InboundProfileView( + profile_id=profile.id, + profile_code=profile.profile_code, + version=int(profile.version or 1), + status=profile.status, + purpose=profile.purpose, + definition_json=dict(profile.definition_json or {}), + ) + + +def _inbound_file_view(report: FreightRpaInboundReportFile) -> InboundFileView: + """把归档文件 ORM 行映射为冻结只读视图(本模块内唯一映射点,字段增补只改此处)。""" + return InboundFileView( + file_id=report.id, + source_code=report.unit_run.source_code, + sha256=report.sha256, + storage_key=report.storage_key, + original_filename=report.original_filename, + created_at=report.created_at, + parse_failed_at=report.parse_failed_at, + ) + + +def has_expired_inbound_file(source_code: str, *, now: datetime | None = None) -> bool: + """返回某来源是否存在「未删除但已失效」的入站归档文件(expired 投影依据)。 + + 用途:调拨来源状态投影(source_file_status.resolve_source_file_status)判断 + 该来源是否需要因文件失效(隔日旧文件 / 保留期已到但清理未落位)提示 + 重抓时调用;只读不写,判定与 usable/expired 条件同核不漂移。 + + 核心逻辑:经执行单元行的 source_code 过滤 + expired_inbound_file_condition, + 存在任一命中即 True(纯存在性判断,不取列数据不排序)。 + + Args: + source_code: 来源实例编码(写在执行单元行上)。 + now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。 + Returns: + bool:存在失效但未清理的归档文件 → True;否则 False。 + """ + expired = ( + FreightRpaInboundReportFile.query + .join(FreightRpaInboundReportFile.unit_run) + .filter( + FreightRpaInboundReportFile.unit_run.has(source_code=source_code), + expired_inbound_file_condition(now=now), + ) + .first() + ) + return expired is not None + + +def list_reparseable_inbound_files(source_code: str, *, now: datetime | None = None) -> list[InboundFileView]: + """维护通道:列出某来源全部可重建入站归档(未删除 + 未过保留期),不设当日门禁。 + + 用途:调拨待匹配桶「清空并重新解析」(movement_file_repository → + backlog_reparse_service,spec §6)按来源取重建清单时调用。 + 运行期取数(latest_usable_inbound_file)的当日 fail-closed 门禁是 + 运行期语义;本方法是显式的历史重建通道(spec §6),两者不得混用。 + + 核心逻辑:join 路径与 latest_usable_inbound_file 同款(经执行单元行 + source_code 过滤),但【刻意无当日门禁】——重建对象正是历史 + 归档;保留期口径一致(archive_expires_at 为空视为长期有效)、 + 未删除(archive_deleted_at 为空)。按 created_at/id 升序返回 + (重建必须按归档时间序重落,保证幂等重放顺序确定)。只读查询, + 不触碰对象存储字节(字节由调用方按需经 read_inbound_file_bytes 取)。 + + Args: + source_code: 来源实例编码(经执行单元行 source_code 关联)。 + now: 保留期判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。 + Returns: + InboundFileView 列表(created_at 升序;无可重建归档为空表)。 + """ + now = now or datetime.utcnow() + reports = ( + FreightRpaInboundReportFile.query + .join(FreightRpaInboundReportFile.unit_run) + .filter( + FreightRpaInboundReportFile.unit_run.has(source_code=source_code), + FreightRpaInboundReportFile.archive_deleted_at.is_(None), + or_( + FreightRpaInboundReportFile.archive_expires_at.is_(None), + FreightRpaInboundReportFile.archive_expires_at > now, + ), + ) + .order_by(FreightRpaInboundReportFile.created_at.asc(), FreightRpaInboundReportFile.id.asc()) + .all() + ) + return [_inbound_file_view(report) for report in reports] + + +def _outbound_file_view(report: FreightRpaOutboundReportFile) -> InboundFileView: + """出站归档 → 与入站同形的只读视图(重建/投影消费面字段对齐)。""" + return InboundFileView( + file_id=report.id, + source_code=report.unit_run.source_code, + sha256=report.sha256, + storage_key=report.storage_key, + original_filename=report.original_filename, + created_at=report.created_at, + parse_failed_at=report.parse_failed_at, + ) + + +def list_reparseable_outbound_files(source_code: str, *, now: datetime | None = None) -> list[InboundFileView]: + """维护通道:列出某来源全部可重建出站归档(未删除 + 未过保留期),不设当日门禁。 + + 用途:调拨待匹配桶「清空并重新解析」出站流(backlog_reparse_service + record_kind=outbound)按来源取重建清单;与 list_reparseable_inbound_files + 同口径,禁止与运行期 latest_usable_outbound_file 混用。 + + 核心逻辑:经出站执行单元行 source_code 过滤;【无当日门禁】;保留期口径 + archive_expires_at 为空视为长期有效;按 created_at/id 升序。 + + Args: + source_code: 来源实例编码。 + now: 保留期判定时刻;缺省当前 UTC。 + Returns: + InboundFileView 列表(created_at 升序;无可重建归档为空表)。 + """ + now = now or datetime.utcnow() + reports = ( + FreightRpaOutboundReportFile.query + .join(FreightRpaOutboundReportFile.unit_run) + .filter( + FreightRpaOutboundReportFile.unit_run.has(source_code=source_code), + FreightRpaOutboundReportFile.archive_deleted_at.is_(None), + or_( + FreightRpaOutboundReportFile.archive_expires_at.is_(None), + FreightRpaOutboundReportFile.archive_expires_at > now, + ), + ) + .order_by( + FreightRpaOutboundReportFile.created_at.asc(), + FreightRpaOutboundReportFile.id.asc(), + ) + .all() + ) + return [_outbound_file_view(report) for report in reports] + + +def list_inbound_configured_source_codes() -> list[str]: + """列出已配置入站报表的启用站点编码(调拨排程缺省执行范围)。 + + 用途:在途自动调拨排程 source_codes 留空时的缺省范围 + (inbound_trigger_service.list_inbound_capable_source_codes 委托本函数) + ——入站文件只能来自已配置入站报表的启用站点。 + 核心逻辑:站点 join 入站配置行、仅启用站点、按 source_code 排序;只读查询。 + + Returns: + 按 source_code 排序的来源编码列表;无匹配站点时为空列表。 + """ + rows = db.session.query(FreightRpaSource.source_code).join( + FreightRpaInboundReportConfig, + FreightRpaInboundReportConfig.source_id == FreightRpaSource.id, + ).filter(FreightRpaSource.enabled.is_(True)).order_by(FreightRpaSource.source_code).all() + return [str(code) for (code,) in rows] + + +def list_outbound_configured_source_codes() -> list[str]: + """列出已配置出站报表的启用站点编码(调拨排程缺省执行范围)。 + + 用途:在途自动调拨排程 source_codes 留空时的缺省范围 + (outbound_trigger_service.list_outbound_capable_source_codes 委托本函数) + ——出站文件只能来自已配置出站报表的启用站点。 + 核心逻辑:站点 join 出站配置行、仅启用站点、按 source_code 排序;只读查询。 + + Returns: + 按 source_code 排序的来源编码列表;无匹配站点时为空列表。 + """ + rows = db.session.query(FreightRpaSource.source_code).join( + FreightRpaOutboundReportConfig, + FreightRpaOutboundReportConfig.source_id == FreightRpaSource.id, + ).filter(FreightRpaSource.enabled.is_(True)).order_by(FreightRpaSource.source_code).all() + return [str(code) for (code,) in rows] + + +def latest_usable_inbound_file( + source_code: str, + *, + now: datetime | None = None, +) -> InboundFileView | None: + """返回某来源当前「可用」的入站归档文件只读视图,最新优先。 + + 用途:调拨匹配取文件、证据下载等读路径调用;口径与匹配链路原有 + _latest_usable_report_file 相同——经执行单元行的 source_code 过滤, + 可用门禁(未删除 + 当天业务日抓取 + 未过期,见 + usable_inbound_file_condition),按 created_at/id 倒序取第一条。 + 只读不写、不 flush 不 commit。 + + Args: + source_code: 来源实例编码(写在 FreightRpaInboundUnitRun.source_code 上)。 + now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。 + 仅供测试冻结窗口或调用方显式指定业务时刻,生产调用缺省即可。 + Returns: + InboundFileView;来源无可用文件(未抓取/已失效/已清理)返回 None。 + """ + report = ( + FreightRpaInboundReportFile.query + .join(FreightRpaInboundReportFile.unit_run) + .filter( + FreightRpaInboundReportFile.unit_run.has(source_code=source_code), + usable_inbound_file_condition(now=now), + ) + .order_by(FreightRpaInboundReportFile.created_at.desc(), FreightRpaInboundReportFile.id.desc()) + .first() + ) + if report is None: + return None + return _inbound_file_view(report) + + +def read_inbound_file_bytes(file_id: int) -> bytes: + """按 file_id 读取入站归档文件的对象字节。 + + 用途:调拨/发货域需要文件原文(匹配重解析、证据下载)时调用,替代各自 + 持有模型 + file_asset_storage 的双跳查询。 + 核心逻辑:[STEP 1] 按主键取 FreightRpaInboundReportFile,缺失抛 NotFoundError + (fail-closed);[STEP 2] 以文件的 storage_key 调 + file_asset_storage.get_bytes 读取并返回字节(不含元数据)。 + + Args: + file_id: 归档文件主键(int;禁止传入非整数 ID)。 + Returns: + 文件完整字节内容。 + Raises: + NotFoundError: file_id 对应的归档文件不存在(HTTP 404)。 + """ + report = db.session.get(FreightRpaInboundReportFile, file_id) + if report is None: + raise NotFoundError( + f"Inbound report file not found: {file_id}", + details={'file_id': file_id}, + ) + return file_asset_storage.get_bytes(report.storage_key) + + +def mark_inbound_parse_failure(file_id: int, *, error_code: str, error_message: str) -> None: + """标记一份入站归档文件解析失败(写入解析失败三分层列)。 + + 用途:入站归档文件解析(schema/字段校验)失败时把失败事实落到文件上, + 使来源状态投影为 parse_failed、阻止下游当作 ready 使用。 + 核心逻辑:[STEP 1] 按主键取文件,缺失抛 NotFoundError;[STEP 2] 只更新 + parse_failed_at(当前 UTC)/ parse_error_code(截断 64)/ + parse_error_message(截断 2000)三列;[STEP 3] db.session.flush() + 使同事务内投影立即可见。【不 commit】——调用方处于自己的事务, + 提交/回滚归属调用方,service 层禁止越权提交。 + + Args: + file_id: 归档文件主键(须已入库)。 + error_code: 机器可读错误码,超 64 字符截断(对齐列宽)。 + error_message: 人类可读错误信息,超 2000 字符截断(Text 列防御性截断)。 + Returns: + None。失败标记随调用方事务落库。 + Raises: + NotFoundError: file_id 对应的归档文件不存在。 + """ + report = db.session.get(FreightRpaInboundReportFile, file_id) + if report is None: + raise NotFoundError( + f"Inbound report file not found: {file_id}", + details={'file_id': file_id}, + ) + report.parse_failed_at = datetime.utcnow() + report.parse_error_code = (error_code or '')[:_PARSE_ERROR_CODE_MAX] + report.parse_error_message = (error_message or '')[:_PARSE_ERROR_MESSAGE_MAX] + db.session.flush() + + +def clear_inbound_parse_failure(file_id: int) -> None: + """清除一份入站归档文件的解析失败标记(三列置空),投影恢复 ready。 + + 用途:同一文件重新解析成功、或确认可恢复后调用;不要在文件已被 + 清理/过期后调用(无业务意义)。 + 核心逻辑:[STEP 1] 按主键取文件,缺失抛 NotFoundError(与其他按 id 操作 + 同口径,避免静默吞掉错配);[STEP 2] 将 parse_failed_at / + parse_error_code / parse_error_message 置 None(三者全空即未失败的 + 约定态);[STEP 3] flush。【不 commit】——事务归属调用方。 + + Args: + file_id: 归档文件主键(须已入库)。 + Returns: + None。清除随调用方事务落库。 + Raises: + NotFoundError: file_id 对应的归档文件不存在。 + """ + report = db.session.get(FreightRpaInboundReportFile, file_id) + if report is None: + raise NotFoundError( + f"Inbound report file not found: {file_id}", + details={'file_id': file_id}, + ) + report.parse_failed_at = None + report.parse_error_code = None + report.parse_error_message = None + db.session.flush() + + +def mark_outbound_parse_failure(file_id: int, *, error_code: str, error_message: str) -> None: + """标记一份出站归档文件解析失败(写入解析失败三分层列;与入站同名函数对称)。 + + 用途:出站归档文件解析(schema/字段校验)失败时把失败事实落到文件上, + 使来源出站流状态投影为 parse_failed、阻止下游当作 ready 使用 + (resolve_source_file_status(record_kind='outbound') 同一投影顺序)。 + 核心逻辑:与 mark_inbound_parse_failure 同款(错误码截 64/错误信息截 + 2000/flush 不 commit——事务归属调用方),仅目标表为 + FreightRpaOutboundReportFile。 + + Args: + file_id: 出站归档文件主键(须已入库)。 + error_code: 机器可读错误码,超 64 字符截断(对齐列宽)。 + error_message: 人类可读错误信息,超 2000 字符截断(Text 列防御性截断)。 + Returns: + None。失败标记随调用方事务落库。 + Raises: + NotFoundError: file_id 对应的出站归档文件不存在。 + """ + report = db.session.get(FreightRpaOutboundReportFile, file_id) + if report is None: + raise NotFoundError( + f"Outbound report file not found: {file_id}", + details={'file_id': file_id}, + ) + report.parse_failed_at = datetime.utcnow() + report.parse_error_code = (error_code or '')[:_PARSE_ERROR_CODE_MAX] + report.parse_error_message = (error_message or '')[:_PARSE_ERROR_MESSAGE_MAX] + db.session.flush() + + +def clear_outbound_parse_failure(file_id: int) -> None: + """清除一份出站归档文件的解析失败标记(三列置空),投影恢复 ready。 + + 用途:同一出站文件重新解析成功后调用;不要在文件已被清理/过期后调用 + (无业务意义)。与 clear_inbound_parse_failure 同款,仅目标表为 + FreightRpaOutboundReportFile。 + + Args: + file_id: 出站归档文件主键(须已入库)。 + Returns: + None。清除随调用方事务落库。 + Raises: + NotFoundError: file_id 对应的出站归档文件不存在。 + """ + report = db.session.get(FreightRpaOutboundReportFile, file_id) + if report is None: + raise NotFoundError( + f"Outbound report file not found: {file_id}", + details={'file_id': file_id}, + ) + report.parse_failed_at = None + report.parse_error_code = None + report.parse_error_message = None + db.session.flush() diff --git a/backend/app/services/freight_rpa/upload/__init__.py b/backend/app/services/freight_rpa/upload/__init__.py new file mode 100644 index 00000000..d06bbad1 --- /dev/null +++ b/backend/app/services/freight_rpa/upload/__init__.py @@ -0,0 +1 @@ +"""upload:货代上传 RPA。""" diff --git a/backend/app/services/freight_rpa/upload/trigger_io.py b/backend/app/services/freight_rpa/upload/trigger_io.py new file mode 100644 index 00000000..7a15f07c --- /dev/null +++ b/backend/app/services/freight_rpa/upload/trigger_io.py @@ -0,0 +1,144 @@ +""" +services/freight_rpa/upload/trigger_io.py + +用途:upload(货代上传)RPA 的纯文件 IO——上传队列/trigger 目录解析、Excel 复制入队、 + 上传 trigger JSON 原子写入(含凭据信封固化)。 +依赖:Flask current_app 配置、Path/shutil/uuid/JSON/文件系统工具;不 import 任何业务编排模块 + (import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。 +逻辑:由 shipping_notice.fulfillment_workflow(upload_to_freight 触发上传)、 + freight_rpa.common.worker_heartbeat(上传目录就绪探测)调用, + 与外部 RPA Worker 的文件投递目录交互;trigger 契约串以本文件常量为单一真相。 + upload 是与 onhand/inbound/outbound 同级的独立域;action 对齐心跳能力 + freight_rpa_upload(FREIGHT_RPA_UPLOAD_CAPABILITY),禁止 outbound_* / shipment_* 作为 upload action; + schema 为 freight_rpa.upload.v1(批次 R 曾误用 outbound 词根,已纠回 freight_rpa_upload)。 +""" + +from __future__ import annotations + +import json +import os +import shutil +import uuid +from datetime import datetime +from pathlib import Path +from typing import Any + +from flask import current_app + +# Worker 触发契约常量:后端写入侧单一真相,禁止再写字面量(Worker 侧常量见 +# scripts/freight_rpa/common/rpa_callbacks.py 邻域的 inbound/onhand 对齐方式)。 +SCHEMA = "freight_rpa.upload.v1" +ACTION_FREIGHT_RPA_UPLOAD = "freight_rpa_upload" + + +def _path(key: str) -> Path | None: + value = str(current_app.config.get(key) or "").strip() + if not value: + return None + return Path(value) + + +def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None: + """原子发布 trigger,避免 Worker 读取到写入中的半截 JSON。""" + temp_path = path.with_name(f'.{path.name}.{os.getpid()}.tmp') + try: + with open(temp_path, 'w', encoding='utf-8') as handle: + json.dump(body, handle, ensure_ascii=False, indent=2) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temp_path, path) + finally: + if temp_path.exists(): + temp_path.unlink(missing_ok=True) + + +def upload_queue_dir() -> Path | None: + """货代上传 Excel 队列目录(RPA 从此处读取待上传文件)。""" + return _path("FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR") + + +def upload_trigger_dir() -> Path | None: + """RPA 货代上传触发 JSON 目录。""" + return _path("FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR") + + +def write_upload_trigger( + task_no: str, + export_file_path: str, + payload: dict[str, Any] | None = None, + *, + attempt_id: int | None = None, + artifact_id: int | None = None, + connector_type: str | None = None, + upload_config: dict[str, Any] | None = None, + upload_config_hash: str | None = None, + login_url: str | None = None, + credential_envelope: dict[str, Any] | None = None, + callback_id: str | None = None, + business_no: str | None = None, +) -> tuple[str | None, str | None, str | None]: + """ + 复制发货 Excel 至共享上传队列,并以原子发布方式写入 RPA 上传触发 JSON。 + 【AI 触发时机】:upload_to_freight(mode=auto|retry_upload) 触发货代上传时调用。 + + 触发文件固化本次上传契约快照,Worker 据此进入 DSV/Crane 受控流程: + schema_version / task_no / attempt_id / artifact_id / callback_id(非空)/ + connector_type / upload_config(本次快照 + upload_config_hash)/ login_url / credential_envelope / file_path。 + 平台差异(文件选择器、提交与结果判定)由 Worker 的受控 Adapter 按 upload_config 执行。 + 写入复用“临时文件 + fsync + os.replace”原子方式,避免 Worker 读取半写 JSON。 + + Args: + task_no: 发货任务号。 + export_file_path: 待上传发货 Excel 的服务端路径。 + payload: 附加字段(如 mode),与下列具名参数合并。 + attempt_id: 本次 Upload Attempt 主键。 + artifact_id: 当前上传目标 Artifact 主键。 + connector_type: 业务连接类型(dbs / crane)。 + upload_config: 本次上传使用的连接级受控配置快照(enabled/entry_url/selector 等)。 + upload_config_hash: 该快照的 sha256,用于审计关联。 + login_url: 该连接登录地址(先登录,再访问 upload_config.entry_url 进入上传页)。 + credential_envelope: 连接凭据密文信封(Worker 据此登录)。 + callback_id: 回调幂等 ID;为空时自动生成,保证非空。 + business_no: 发货通知对外业务编号(业务单号),用于精简上传文件名;为空时回退 task_no。 + + Returns: + tuple[str | None, str | None, str | None]: (queue 文件路径, trigger 文件路径, callback_id); + 失败时 (None, None, None)。 + """ + queue = upload_queue_dir() + trigger_dir = upload_trigger_dir() + if not queue or not trigger_dir: + return None, None, None + queue.mkdir(parents=True, exist_ok=True) + trigger_dir.mkdir(parents=True, exist_ok=True) + + src = Path(export_file_path) + if not src.is_file(): + return None, None, None + # [STEP] 精简上传文件名:仅用业务编号(业务单号),避免 task_no 与导出文件名重复拼接过长; + # 业务编号为空时回退到内部任务号,扩展名沿用源文件(无扩展名时按 xlsx 兜底)。 + emit_no = str(business_no or '').strip() or task_no + suffix = str(src.suffix or '.xlsx').lower() + dest = queue / f"{emit_no}{suffix}" + shutil.copy2(src, dest) + + resolved_callback_id = str(callback_id or '').strip() or f'upload:{task_no}:{uuid.uuid4().hex[:12]}' + body = { + "action": ACTION_FREIGHT_RPA_UPLOAD, + "schema_version": SCHEMA, + "task_no": task_no, + "attempt_id": attempt_id, + "artifact_id": artifact_id, + "callback_id": resolved_callback_id, + "connector_type": str(connector_type or '').strip() or None, + "upload_config": upload_config, + "upload_config_hash": upload_config_hash, + "login_url": login_url, + "credential_envelope": credential_envelope, + "file_path": str(dest), + "requested_at": datetime.utcnow().isoformat(), + **(payload or {}), + } + trigger_path = trigger_dir / f"upload_{task_no}.json" + _write_trigger_json_atomic(trigger_path, body) + return str(dest), str(trigger_path), resolved_callback_id diff --git a/backend/app/services/in_transit_transfer/archive.py b/backend/app/services/in_transit_transfer/archive.py index ed0e261d..55f9e7a3 100644 --- a/backend/app/services/in_transit_transfer/archive.py +++ b/backend/app/services/in_transit_transfer/archive.py @@ -108,7 +108,7 @@ def archive_snapshot( """归档一份对象并持久化索引 + 审计。 Args: - object_type: 对象类型(external_inventory_snapshot / exception_excel / receipt_file)。 + object_type: 对象类型(external_inventory_snapshot / exception_excel / inbound_file)。 object_id: 业务对象编号(matching_no / run_no)。 data: 待归档字节。 original_filename: 原始文件名。 diff --git a/backend/app/services/in_transit_transfer/auto_transfer.py b/backend/app/services/in_transit_transfer/auto_transfer.py index e7e65974..8193d021 100644 --- a/backend/app/services/in_transit_transfer/auto_transfer.py +++ b/backend/app/services/in_transit_transfer/auto_transfer.py @@ -32,8 +32,9 @@ class AutoTransferOutcome: def run_auto_transfer(*, business_date: str, deps: TransferDeps, source_codes: list[str] | None = None, recover_history: bool = True, - receipt_date_from: str | None = None, - receipt_date_to: str | None = None, + movement_date_from: str | None = None, + movement_date_to: str | None = None, + transfer_type: str | None = None, sender: WeComSender | None = None, recipients: list[str] | None = None) -> AutoTransferOutcome: """执行一次自动调拨排程。 @@ -46,8 +47,10 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps, deps: 注入依赖。 source_codes: 来源实例列表(缺省全部启用来源)。 recover_history: 是否执行历史恢复。 - receipt_date_from / receipt_date_to: 可选收料日期范围(测试/排障缩小 - 匹配面;留空=全部成熟积压;非法范围由匹配层抛 ValidationError)。 + movement_date_from / movement_date_to: 可选异动日期范围(测试/排障缩小 + 匹配面;留空=全部积压;非法范围由匹配层抛 ValidationError)。 + transfer_type: 调拨类型编码(D8 匹配创建必填——排程任务参数承载; + 缺省 None 时匹配层 fail-closed 抛 TRANSFER_TYPE_REQUIRED)。 sender / recipients: 企微通知(None 则跳过通知;run_no 为空时不发送)。 Returns: AutoTransferOutcome;空数据日时 run_no/run_status 均为 None 且 errors 为空。 @@ -63,8 +66,9 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps, source_codes=source_codes or [], business_date=business_date, deps=deps, - receipt_date_from=receipt_date_from, - receipt_date_to=receipt_date_to, + movement_date_from=movement_date_from, + movement_date_to=movement_date_to, + transfer_type=transfer_type, ) # [STEP 2] 空数据日跳过执行:匹配后无可执行行(含恢复后仍为 0)时不建票、 # 不写 ERP、不通知(产品决策 C5);该日仅留痕 Run/Matching,不视作失败。 diff --git a/backend/app/services/in_transit_transfer/backlog_reparse_service.py b/backend/app/services/in_transit_transfer/backlog_reparse_service.py new file mode 100644 index 00000000..d89747fe --- /dev/null +++ b/backend/app/services/in_transit_transfer/backlog_reparse_service.py @@ -0,0 +1,371 @@ +"""services/in_transit_transfer/backlog_reparse_service.py + +用途:待匹配桶整桶重建的内部实现(spec §6/D7)。2026-10-22 起不再挂 HTTP: + 预检/执行路由已下线,待匹配界面不再提供入口。本模块仅保留给既有单测, + 锁住「先全量解析、失败一行不删」;禁止重新挂回 + /backlog/pending-match/reparse*。重解析产品入口只有当天最新归档 + (current_file_reparse)。 + 历史语义:按来源 + 记录类型把旧映射档行清空,并以当前规则重解析全部 + 可重建归档后幂等重落。 +依赖:movement_file_repository(ReparseableArchiveFile + _extract_movement_rows)、 + evidence_sync.parse_archive_to_ledger_rows(解析+组装单一口径)与 + _detect_natural_key_collapses/_natural_key_collapse_event、ledger_sync + (sync_ledger_rows / RECORD_KIND_* / FileMeta / movement_file_version)、 + matching_service. + _effective_occupancy_filter、freight_rpa.reports.queries(站点与入站/出站 + 解析方案、可重建归档清单)、file_asset_storage、audit。 +逻辑:桶数据 100% 可由 MinIO 归档重建。安全不变量:先全量预解析入内存, + 任一归档解析失败 → 整体中止 AppError(TRANSFER.REPARSE_PARSE_FAILED), + 一行不删。删除范围:source_code + record_kind + transfer_executed=false + + 未被有效 items 占用 + source_file_id ∈ 可重建归档。入站/出站分流仅体现在 + 规则门禁(published purpose)、归档清单表与落档 record_kind;其余步骤同源。 + commit 在本服务内做一次。审计 TRANSFER_PENDING_MATCH_REPARSED 含 record_kind。 +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import datetime +from typing import Any + +from sqlalchemy import func + +from app import db +from app.core.errors import AppError, ValidationError +from app.models import TransferInvoiceItem, TransferMovementLedger +from app.services.file_assets.storage import file_asset_storage +from app.services.freight_rpa.reports.queries import ( + get_inbound_parsing_profile, + get_outbound_parsing_profile, + get_site, + list_reparseable_inbound_files, + list_reparseable_outbound_files, +) +from app.services.in_transit_transfer.audit import build_transfer_audit_event +from app.services.in_transit_transfer.evidence_sync import ( + _detect_natural_key_collapses, + _natural_key_collapse_event, + parse_archive_to_ledger_rows, +) +from app.services.in_transit_transfer.ledger_sync import ( + RECORD_KIND_INBOUND, + RECORD_KIND_OUTBOUND, + FileMeta, + movement_file_version, + sync_ledger_rows, +) +from app.services.in_transit_transfer.matching_service import _effective_occupancy_filter +from app.services.in_transit_transfer.movement_file_repository import ( + ReparseableArchiveFile, + _extract_movement_rows, +) + +REPARSE_EVENT = "TRANSFER_PENDING_MATCH_REPARSED" +REPARSE_PARSE_FAILED = "TRANSFER.REPARSE_PARSE_FAILED" +_RECORD_KINDS = frozenset({RECORD_KIND_INBOUND, RECORD_KIND_OUTBOUND}) + + +@dataclass(frozen=True) +class ReparseOutcome: + """一次清空重建的结果计数与文件概要(审计/端点响应的数据源)。 + + Args: + source_code: 来源实例编码。 + record_kind: inbound 或 outbound。 + cleared / reinserted / date_skipped / kept_unrebuildable / unlinked_items / + collapses / files: 同入站重建语义。 + """ + + source_code: str + record_kind: str = RECORD_KIND_INBOUND + cleared: int = 0 + reinserted: int = 0 + date_skipped: int = 0 + kept_unrebuildable: int = 0 + unlinked_items: int = 0 + collapses: int = 0 + files: tuple[dict, ...] = field(default_factory=tuple) + + +def _normalize_record_kind(record_kind: str | None) -> str: + """规范化记录类型;非法值 fail-closed。""" + kind = str(record_kind or RECORD_KIND_INBOUND).strip() or RECORD_KIND_INBOUND + if kind not in _RECORD_KINDS: + raise ValidationError( + "record_kind must be inbound or outbound", + details={"record_kind": kind}, + ) + return kind + + +def _load_published_profile(source_code: str, record_kind: str): + """加载来源当前绑定的「已发布」解析规则(与运行期取数同口径)。 + + 核心逻辑:来源 enabled → 入站/出站配置绑定方案;须 published 且 + purpose 等于 record_kind。 + + Args: + source_code: 来源实例编码。 + record_kind: inbound 或 outbound。 + Returns: + 解析方案视图;无通道时 None。 + """ + site = get_site(source_code) + if site is None or not site.enabled: + return None + if record_kind == RECORD_KIND_OUTBOUND: + profile = get_outbound_parsing_profile(source_code) + else: + profile = get_inbound_parsing_profile(source_code) + if profile is None or profile.status != "published" or profile.purpose != record_kind: + return None + return profile + + +def _list_reparseable_files( + source_code: str, now: datetime, record_kind: str, +) -> list[ReparseableArchiveFile]: + """按记录类型列出可重建归档,映射为维护契约 ReparseableArchiveFile。""" + if record_kind == RECORD_KIND_OUTBOUND: + views = list_reparseable_outbound_files(source_code, now=now) + else: + views = list_reparseable_inbound_files(source_code, now=now) + return [ + ReparseableArchiveFile( + file_id=view.file_id, + storage_key=view.storage_key, + sha256=view.sha256, + file_version=movement_file_version(view.sha256), + archived_at=view.created_at, + original_filename=view.original_filename, + ) + for view in views + ] + + +def _partition_deletable( + source_code: str, + files: list[ReparseableArchiveFile], + record_kind: str, +) -> tuple[list[TransferMovementLedger], list[TransferMovementLedger]]: + """把「未封存且未被占用」的指定 record_kind 档行按证据可得性分成两组。""" + available_ids = {record.file_id for record in files} + candidates = ( + TransferMovementLedger.query.filter( + TransferMovementLedger.source_code == source_code, + TransferMovementLedger.record_kind == record_kind, + TransferMovementLedger.transfer_executed.is_(False), + _effective_occupancy_filter(), + ) + .all() + ) + deletable = [row for row in candidates if row.source_file_id in available_ids] + return candidates, deletable + + +def preview_pending_match_reparse( + *, source_code: str, now: datetime, record_kind: str = RECORD_KIND_INBOUND, +) -> dict: + """清空并重新解析预检(只读;按 record_kind 分流入站/出站归档与档行)。 + + 【AI 触发时机】不要调用。2026-10-22 起产品入口已下线,仅单测覆盖本函数。 + + Args: + source_code: 来源实例编码。 + now: 保留期判定时刻。 + record_kind: inbound(默认,兼容旧调用)或 outbound。 + Returns: + {record_kind, files, profile, clearable_rows, kept_rows} + """ + kind = _normalize_record_kind(record_kind) + files = _list_reparseable_files(source_code, now, kind) + profile = _load_published_profile(source_code, kind) + _candidates, deletable = _partition_deletable(source_code, files, kind) + file_ids = [record.file_id for record in files] + counts: dict[int, int] = {} + if file_ids: + counts = { + source_file_id: count + for source_file_id, count in db.session.query( + TransferMovementLedger.source_file_id, + func.count(TransferMovementLedger.id), + ) + .filter( + TransferMovementLedger.source_code == source_code, + TransferMovementLedger.record_kind == kind, + TransferMovementLedger.source_file_id.in_(file_ids), + ) + .group_by(TransferMovementLedger.source_file_id) + .all() + } + return { + "record_kind": kind, + "files": [ + { + "archived_at": record.archived_at.isoformat(), + "sha256": record.sha256, + "rows": counts.get(record.file_id, 0), + } + for record in files + ], + "profile": ( + {"code": profile.profile_code, "version": profile.version} + if profile is not None else None + ), + "clearable_rows": len(deletable), + "kept_rows": len(_candidates) - len(deletable), + } + + +def reparse_pending_match( + *, + source_code: str, + operator: str, + now: datetime, + record_kind: str = RECORD_KIND_INBOUND, +) -> ReparseOutcome: + """清空并重新解析一个来源指定记录类型的待匹配桶(单事务,本函数提交)。 + + 【AI 触发时机】不要调用。2026-10-22 起产品入口已下线,仅单测覆盖本函数。 + record_kind=outbound 时清出站档、用 purpose=outbound 规则与出站归档重建。 + + Raises: + ValidationError: record_kind 非法。 + AppError: TRANSFER.REPARSE_PARSE_FAILED——无已发布对应流解析规则,或 + 任一归档解析失败(整体中止且未删除任何行)。 + """ + kind = _normalize_record_kind(record_kind) + # [STEP 1] 重建通道与可重建文件清单。 + profile = _load_published_profile(source_code, kind) + if profile is None: + raise AppError( + code=REPARSE_PARSE_FAILED, + message=( + f"reparse aborted: no published {kind} parsing profile " + f"(source={source_code})" + ), + http_status=422, + details={ + "source_code": source_code, + "record_kind": kind, + "reason": f"no_published_{kind}_profile", + }, + ) + files = _list_reparseable_files(source_code, now, kind) + definition = profile.definition_json or {} + + # [STEP 2] 全量预解析入内存;任一失败整体中止。 + prepared: list[tuple[ReparseableArchiveFile, list[dict]]] = [] + for record in files: + try: + data = file_asset_storage.get_bytes(record.storage_key) + raw_rows = _extract_movement_rows( + data, + field_mapping=dict(definition.get("field_mapping") or {}), + sheet_name=str(definition.get("sheet_name") or "").strip() or None, + header_row_index=definition.get("header_row_index"), + ) + assembled = parse_archive_to_ledger_rows(source_code=source_code, rows=raw_rows) + except Exception as exc: # noqa: BLE001 —— 安全不变量 + raise AppError( + code=REPARSE_PARSE_FAILED, + message=f"reparse aborted: archive file failed to parse (source={source_code})", + http_status=422, + details={ + "source_code": source_code, + "record_kind": kind, + "file_id": record.file_id, + "storage_key": record.storage_key, + "sha256": record.sha256, + "reason": str(exc)[:500], + }, + ) from exc + prepared.append((record, assembled)) + + # [STEP 3] 删除可重建未占用行(先解引用废弃 items)。 + candidates, deletable = _partition_deletable(source_code, files, kind) + kept_unrebuildable = len(candidates) - len(deletable) + deletable_ids = [row.id for row in deletable] + unlinked_items = 0 + if deletable_ids: + unlinked_items = ( + TransferInvoiceItem.query + .filter(TransferInvoiceItem.ledger_record_id.in_(deletable_ids)) + .update({TransferInvoiceItem.ledger_record_id: None}, synchronize_session=False) + ) + for row in deletable: + db.session.delete(row) + db.session.flush() + + # [STEP 4] 按归档时间升序逐文件重落。 + reinserted = 0 + date_skipped = 0 + collapses = 0 + file_summaries: list[dict[str, Any]] = [] + for record, assembled in prepared: + outcome = sync_ledger_rows( + source_code=source_code, + record_kind=kind, + parsed_rows=assembled, + file_meta=FileMeta( + source_file_id=record.file_id, + file_version=record.file_version, + file_sha256=record.sha256, + ), + now=now, + ) + reinserted += outcome.inserted + date_skipped += outcome.date_skipped + if outcome.inserted or outcome.updated: + file_collapses = _detect_natural_key_collapses(assembled) + for collapse in file_collapses: + db.session.add(_natural_key_collapse_event( + source_code=source_code, collapse=collapse, record_kind=kind, + )) + collapses += len(file_collapses) + file_summaries.append({ + "file_id": record.file_id, + "sha256": record.sha256, + "archived_at": record.archived_at.isoformat(), + "inserted": outcome.inserted, + }) + + # [STEP 5] 审计 + commit。 + db.session.add(build_transfer_audit_event( + event_type=REPARSE_EVENT, + aggregate_type="transfer_source", + aggregate_id=source_code, + actor_type="user", + actor_id=operator, + actor_display=operator, + result="success", + after={ + "operator": operator, + "source_code": source_code, + "record_kind": kind, + "files": [ + {"file_id": record.file_id, "sha256": record.sha256} + for record, _assembled in prepared + ], + "profile_code": profile.profile_code, + "profile_version": profile.version, + "cleared": len(deletable), + "reinserted": reinserted, + "date_skipped": date_skipped, + "kept": kept_unrebuildable, + "unlinked_items": unlinked_items, + "collapses": collapses, + }, + )) + db.session.commit() + return ReparseOutcome( + source_code=source_code, + record_kind=kind, + cleared=len(deletable), + reinserted=reinserted, + date_skipped=date_skipped, + kept_unrebuildable=kept_unrebuildable, + unlinked_items=unlinked_items, + collapses=collapses, + files=tuple(file_summaries), + ) diff --git a/backend/app/services/in_transit_transfer/backlog_service.py b/backend/app/services/in_transit_transfer/backlog_service.py index b434e6bd..5a405b36 100644 --- a/backend/app/services/in_transit_transfer/backlog_service.py +++ b/backend/app/services/in_transit_transfer/backlog_service.py @@ -1,22 +1,43 @@ -"""在途调拨历史待处理池与老化分级。 +"""services/in_transit_transfer/backlog_service.py + +在途调拨历史待处理池与老化分级 + 首页「待匹配」桶(D16)。 用途:聚合未成功且未人工关闭的可恢复异常、已关闭与结果未知项, - 按 3/5/7 天阈值输出老化等级,防止历史失败被遗忘。 -依赖:models、status。 + 按 3/5/7 天阈值输出老化等级,防止历史失败被遗忘; + 并提供首页待办看板「待匹配」桶(已落档尚未匹配的外部出入站记录, + 规格 §10/D16:只读清单 + 计数,不可勾选执行)。 +依赖:models、status、matching_service(待匹配全量圈档 + 启用类型范围并集)。 逻辑:可恢复=blocked_recoverable;result_unknown 单独高风险展示且只读; manually_closed / success / duplicate_success 永久排除。 + 待匹配桶=成熟未占用的出入站全量(pending_ledger_query:未封存/有异动日期/ + 未被有效 items 占用/T−2,不按调拨类型范围过滤)。清单再按来源+记录类型+ + 外部单号合计数量,不再展开外部项次;没有外部单号的档行仍逐行返回。 + 首页待匹配、可匹配计数与清单行数同一合并口径。【2026-10-22 SQL 下推】 + 计数=合并键 GROUP BY 计数、清单分页=组首行锚点 OFFSET/LIMIT 后只召回 + 本页档行、行桶汇总=轻量元组单条查询;口径不变,禁止再整段装载内存切片。池行带出生匹配的 + transfer_type,供待恢复/已关闭/结果未知表展示调拨类别。可匹配=启用类型范围并集, + 供库存匹配卡计数,并给清单行打 matchable。无 item_id 不可执行; + 匹配圈定后记录离开本桶, + 取消匹配释放后回归。 """ from __future__ import annotations from dataclasses import dataclass from datetime import datetime -from typing import Optional +from decimal import Decimal, InvalidOperation +from typing import Any, Optional -from sqlalchemy import func +from sqlalchemy import String, and_, case, cast, func, literal, or_ +from sqlalchemy.orm import joinedload from app import db -from app.models import TransferAttempt, TransferInvoiceItem +from app.models import TransferAttempt, TransferInvoiceItem, TransferMovementLedger +from app.services.in_transit_transfer.matching_service import ( + circle_ledger_record_ids_scope_union, + pending_ledger_query, + transfer_type_code_of, +) from app.services.in_transit_transfer.status import TransferStatus AGING_NORMAL = "normal" @@ -28,6 +49,32 @@ AGING_CLOSED = "closed" _BACKLOG_RECOVERABLE = TransferStatus.BLOCKED_RECOVERABLE.value +# 结果筛选切片(前端首页计数卡切片与池内筛选同口径);all=三态并集。 +RESULT_FILTER_RECOVERABLE = "recoverable" +RESULT_FILTER_CLOSED = "closed" +RESULT_FILTER_UNKNOWN = "unknown" +RESULT_FILTER_ALL = "all" +_ALL_BACKLOG_STATUSES = ( + _BACKLOG_RECOVERABLE, + TransferStatus.RESULT_UNKNOWN.value, + TransferStatus.MANUALLY_CLOSED.value, +) +_RESULT_FILTER_STATUSES: dict[str, tuple[str, ...]] = { + RESULT_FILTER_ALL: _ALL_BACKLOG_STATUSES, + RESULT_FILTER_RECOVERABLE: (_BACKLOG_RECOVERABLE,), + RESULT_FILTER_CLOSED: (TransferStatus.MANUALLY_CLOSED.value,), + RESULT_FILTER_UNKNOWN: (TransferStatus.RESULT_UNKNOWN.value,), +} +RESULT_FILTER_CHOICES = (RESULT_FILTER_ALL, *_RESULT_FILTER_STATUSES.keys()) + +# 服务端分页默认值/上限(与已执行单 /documents 接口同口径:默认 20、上限 100)。 +BACKLOG_PAGE_DEFAULT = 1 +BACKLOG_PAGE_SIZE_DEFAULT = 20 +BACKLOG_PAGE_SIZE_MAX = 100 +# 跨页全选 id 上限(2026-10-22):防误拉超大规模池;超出截断并由 API 透出 +# truncated 标记(千行级池单次全量 id 拉取成本可忽略,上限为防御性兜底)。 +BACKLOG_SELECT_ALL_MAX = 5000 + @dataclass(frozen=True) class BacklogItemDTO: @@ -42,20 +89,47 @@ class BacklogItemDTO: age_days: int aging_level: str last_attempt_at: Optional[str] = None - receipt_date: Optional[str] = None + movement_date: Optional[str] = None material_name: Optional[str] = None from_warehouse: Optional[str] = None to_warehouse: Optional[str] = None lot_no: Optional[str] = None - receipt_quantity: Optional[str] = None + movement_quantity: Optional[str] = None external_quantity: Optional[str] = None # 最近一次结果码(如 blocked_file_removed);供前端区分「文件已移除」徽标 result_code: Optional[str] = None + # 出生匹配快照上的调拨类型 code。空串表示行没有匹配或快照未写类型。 + transfer_type: str = "" + + +@dataclass(frozen=True) +class PendingMatchRecordDTO: + """「待匹配」桶单项(D16):按外部单号收口后的只读投影——无 item_id,不可勾选执行。 + + 有外部单号时,同一来源、同一记录类型下的多项次合成一行。quantity 为这些档行 + 数量之和(Decimal 文本,与 items.movement_quantity 同约定)。没有外部单号的 + 档行仍逐行返回。单号/料号/品名/异动日期在组内不一致时为空,前端显示占位。 + ledger_record_id 是组内最小档 id,只作行键,不代表整组只有这一条档。 + """ + + ledger_record_id: int + doc_no: str + material_code: Optional[str] = None + material_name: Optional[str] = None + movement_date: Optional[str] = None + source_code: str = "" + # 档记录类型(inbound/outbound)。 + record_kind: str = "inbound" + # 外部单号(WMS Order #)。空串=该行没有外部单号,未与其他行合并。 + external_doc_no: str = "" + quantity: Optional[str] = None + # 当前启用类型范围并集罩得住。分段查询里同一组的标记一致。 + matchable: bool = False @dataclass class BacklogSummaryDTO: - """待处理池汇总(含老化分级计数)。""" + """待处理池汇总(含老化分级计数 + 待匹配桶计数)。""" recoverable_count: int = 0 closed_count: int = 0 @@ -63,6 +137,36 @@ class BacklogSummaryDTO: warn_3d: int = 0 escalate_5d: int = 0 critical_7d: int = 0 + # 首页「待匹配」卡:与待匹配清单同一合并口径的行数(不含类型范围)。 + pending_match_count: int = 0 + # 首页「匹配可调拨库存」卡:与清单「当前可匹配」同一合并口径的行数。 + matchable_count: int = 0 + + +@dataclass(frozen=True) +class BacklogPageDTO: + """待处理池分页结果(2026-10-16 服务端分页:池为无界增长集合, + 全量拉取在千行级放大网络载荷与老化批量查询规模;items=当前页切片, + total=筛选后全量计数供前端分页器)。""" + + items: list[BacklogItemDTO] + total: int + page: int + page_size: int + + +_PENDING_SEGMENTS = ("all", "matchable", "outside") + + +@dataclass(frozen=True) +class PendingMatchPageDTO: + """「待匹配」桶分页结果。total 与 records 都是外部单号合并后的行, + 不是档行数。没有外部单号的档行仍各占一行。""" + + records: list[PendingMatchRecordDTO] + total: int + page: int + page_size: int def aging_level_for(age_days: int, *, warn: int = 3, escalate: int = 5, critical: int = 7) -> str: @@ -100,40 +204,55 @@ def _latest_attempt_times(item_ids: list[int]) -> dict[int, datetime]: return {item_id: latest for item_id, latest in rows} -def list_backlog(*, now: datetime | None = None, source_code: str | None = None) -> list[BacklogItemDTO]: - """列出待处理池项(可恢复 + 已关闭 + 结果未知)。 +def _backlog_base_query(statuses, *, source_code: str | None = None, keyword: str | None = None): + """待处理池基础查询(状态集合 + 可选来源/关键字过滤)。 - 排序:收料日期 → 数据源 → Invoice → 创建时间(全链路统一业务稳定键, - 与可调拨明细/匹配卡视图同口径,2026-09-29 统一;与重查/恢复等操作无关)。 - 不用 updated_at 排序——它是行级新鲜度时间戳,重查/恢复会刷新它, - 以此排序会让正在处理的行在列表中跳位。 + keyword 与前端池内筛选同字段集(Invoice/料号/品名/来源,2026-10-16 随 + 服务端分页下推),大小写不敏感子串匹配(ilike)。 Args: - now: 判定时刻(默认当前时间)。 + statuses: 池内状态白名单(result_filter 切片或三态并集)。 source_code: 可选来源过滤。 + keyword: 可选关键字(子串大小写不敏感)。 Returns: - BacklogItemDTO 列表。 + 未排序的 SQLAlchemy Query(排序由调用方统一拼 _BACKLOG_ORDER_BY)。 """ - current = now or datetime.utcnow() - query = TransferInvoiceItem.query.filter( - TransferInvoiceItem.status.in_([ - _BACKLOG_RECOVERABLE, - TransferStatus.RESULT_UNKNOWN.value, - TransferStatus.MANUALLY_CLOSED.value, - ]), - ) + query = TransferInvoiceItem.query.filter(TransferInvoiceItem.status.in_(statuses)) if source_code: query = query.filter_by(source_code=source_code) - 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() - latest_map = _latest_attempt_times([row.id for row in pool_rows]) + if keyword: + like = f"%{keyword}%" + query = query.filter(or_( + TransferInvoiceItem.invoice_no.ilike(like), + TransferInvoiceItem.material_no.ilike(like), + TransferInvoiceItem.material_name.ilike(like), + TransferInvoiceItem.source_code.ilike(like), + )) + return query + + +# 全链路统一业务稳定键排序(异动日期→数据源→Invoice→创建时间→id 兜底)。 +_BACKLOG_ORDER_BY = ( + TransferInvoiceItem.movement_date.asc().nulls_last(), + TransferInvoiceItem.source_code.asc(), + TransferInvoiceItem.invoice_no.asc(), + TransferInvoiceItem.created_at.asc(), + TransferInvoiceItem.id.asc(), +) + + +def _backlog_dtos(rows: list[TransferInvoiceItem], current: datetime) -> list[BacklogItemDTO]: + """池行 → DTO 组装(老化判定需 Attempt 最近时间,批量单条 GROUP BY 查询)。 + + Args: + rows: 当前页(或全量)池行,须已按业务稳定键排序。 + current: 老化判定的当前时刻。 + Returns: + BacklogItemDTO 列表(与输入同序)。 + """ + latest_map = _latest_attempt_times([row.id for row in rows]) output: list[BacklogItemDTO] = [] - for item in pool_rows: + for item in 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)) @@ -153,33 +272,599 @@ def list_backlog(*, now: datetime | None = None, source_code: str | None = None) age_days=age, aging_level=level, last_attempt_at=latest.isoformat() if latest is not None else None, - receipt_date=item.receipt_date, + movement_date=item.movement_date, material_name=item.material_name, from_warehouse=item.from_warehouse, to_warehouse=item.to_warehouse, lot_no=item.lot_no, - receipt_quantity=str(item.receipt_quantity) if item.receipt_quantity is not None else None, + movement_quantity=str(item.movement_quantity) if item.movement_quantity is not None else None, external_quantity=str(item.external_quantity) if item.external_quantity is not None else None, result_code=item.result_code, + transfer_type=transfer_type_code_of(item), )) return output -def backlog_summary(*, now: datetime | None = None) -> BacklogSummaryDTO: - """计算待处理池汇总计数与老化分级。""" - items = list_backlog(now=now) - summary = BacklogSummaryDTO() - for item in items: - if item.status == TransferStatus.MANUALLY_CLOSED.value: - summary.closed_count += 1 - elif item.status == TransferStatus.RESULT_UNKNOWN.value: - summary.unknown_count += 1 +def list_backlog(*, now: datetime | None = None, source_code: str | None = None) -> list[BacklogItemDTO]: + """列出待处理池项(可恢复 + 已关闭 + 结果未知)——全量(兼容口径,未分页)。 + + 排序:异动日期 → 数据源 → Invoice → 创建时间(全链路统一业务稳定键, + 与可调拨明细/匹配卡视图同口径,2026-09-29 统一;与重查/恢复等操作无关)。 + 不用 updated_at 排序——它是行级新鲜度时间戳,重查/恢复会刷新它, + 以此排序会让正在处理的行在列表中跳位。 + 分页场景请用 list_backlog_page(2026-10-16),本函数保留供无参兼容调用。 + + Args: + now: 判定时刻(默认当前时间)。 + source_code: 可选来源过滤。 + Returns: + BacklogItemDTO 列表。 + """ + current = now or datetime.utcnow() + rows = ( + _backlog_base_query(_ALL_BACKLOG_STATUSES, source_code=source_code) + .options(joinedload(TransferInvoiceItem.matching)) + .order_by(*_BACKLOG_ORDER_BY) + .all() + ) + return _backlog_dtos(rows, current) + + +def list_backlog_page( + *, + now: datetime | None = None, + source_code: str | None = None, + keyword: str | None = None, + result_filter: str = RESULT_FILTER_ALL, + page: int = BACKLOG_PAGE_DEFAULT, + page_size: int = BACKLOG_PAGE_SIZE_DEFAULT, +) -> BacklogPageDTO: + """待处理池分页查询(2026-10-16 服务端分页 + 筛选下推)。 + + 【AI 触发时机】前端待处理池视图按页/筛选拉取时经 API 调用;禁止绕过 + result_filter 白名单(fail-closed,非 all/recoverable/closed/unknown 由 + API 层 400)。筛选(result_filter/keyword)与计数口径一致:total 为 + 筛选后全量计数,供前端分页器展示;老化批量查询只对当前页行执行 + (千行级池的响应规模从 O(池) 降到 O(页))。 + + Args: + now: 判定时刻(默认当前时间)。 + source_code: 可选来源过滤。 + keyword: 可选关键字(Invoice/料号/品名/来源,子串大小写不敏感)。 + result_filter: 结果切片(all/recoverable/closed/unknown)。 + page: 页码(1 起)。 + page_size: 每页行数(1..100)。 + Returns: + BacklogPageDTO(items=当前页切片,total=筛选后全量计数)。 + """ + current = now or datetime.utcnow() + statuses = _RESULT_FILTER_STATUSES.get(result_filter) + if statuses is None: + # 防御:API 层已做白名单 400,这里兜底回三态并集(service 直调场景不炸) + statuses = _ALL_BACKLOG_STATUSES + base = _backlog_base_query(statuses, source_code=source_code, keyword=keyword or None) + total = base.count() + rows = ( + base.options(joinedload(TransferInvoiceItem.matching)) + .order_by(*_BACKLOG_ORDER_BY) + .offset((page - 1) * page_size) + .limit(page_size) + .all() + ) + return BacklogPageDTO(items=_backlog_dtos(rows, current), total=total, page=page, page_size=page_size) + + +def list_backlog_item_ids( + *, + source_code: str | None = None, + keyword: str | None = None, + result_filter: str = RESULT_FILTER_ALL, + limit: int = BACKLOG_SELECT_ALL_MAX, +) -> tuple[list[int], int]: + """跨页全选支持(2026-10-22):当前筛选下全部待处理明细 id(轻量 id 列表)。 + + 【AI 触发时机】前端待处理池「选择全部 N 行」时经 API 调用——服务端分页下 + 勾选集合只能覆盖当前页,本函数按同一筛选口径取全量 id 供批量操作 + (重查/恢复/关闭端点本就按 item_ids 列表逐行隔离,无需新批量契约)。 + + Args: + source_code: 可选来源过滤。 + keyword: 可选关键字(与 list_backlog_page 同字段集)。 + result_filter: 结果切片(all/recoverable/closed/unknown)。 + limit: id 上限(防误拉超大规模池;超出截断,truncated 标记随 API 透出)。 + Returns: + (ids, total):ids=item_id 升序列表(≤limit),total=筛选后全量计数 + (含未返回部分,供前端提示截断)。 + """ + statuses = _RESULT_FILTER_STATUSES.get(result_filter) + if statuses is None: + # 防御:API 层已做白名单 400,这里兜底回三态并集(service 直调场景不炸) + statuses = _ALL_BACKLOG_STATUSES + base = _backlog_base_query(statuses, source_code=source_code, keyword=keyword or None) + total = base.count() + rows = ( + base.order_by(TransferInvoiceItem.id.asc()) + .limit(limit) + .with_entities(TransferInvoiceItem.id) + .all() + ) + return [int(row[0]) for row in rows], total + + +def _pending_match_dto(record, *, matchable_ids: set[int]) -> PendingMatchRecordDTO: + """把单条档行投影成待匹配清单项,并标出是否落在启用类型范围并集内。 + + 本函数不做外部单号合并。合并在 _aggregate_pending_match_records。 + + Args: + record: TransferMovementLedger 或带同名字段的行。 + matchable_ids: circle_ledger_record_ids_scope_union 的 id 集合。 + Returns: + 只读 PendingMatchRecordDTO。无 item_id。 + """ + return PendingMatchRecordDTO( + ledger_record_id=record.id, + doc_no=record.doc_no, + material_code=record.material_code, + material_name=record.material_name, + movement_date=record.movement_date, + source_code=record.source_code, + record_kind=str(getattr(record, "record_kind", None) or "inbound"), + external_doc_no=str(getattr(record, "external_doc_no", None) or ""), + quantity=record.quantity, + matchable=record.id in matchable_ids, + ) + + +def _uniform_text(values: list[object]) -> str | None: + """组内去掉空白后只有一个取值时返回它。 + + 核心逻辑:空串不参与比较;出现第二个不同取值即视为不一致。 + + Args: + values: 档行上的文本字段。None 与空白视为没有值。 + Returns: + 唯一非空文本;没有值或取值不一致时返回 None。 + """ + seen: list[str] = [] + for raw in values: + text = str(raw or "").strip() + if not text or text in seen: + continue + seen.append(text) + if len(seen) > 1: + return None + return seen[0] if seen else None + + +def _sum_quantity_text(values: list[object]) -> str | None: + """把一组数量文本相加,输出不带多余尾零的十进制文本。 + + 核心逻辑:能解析的按 Decimal 相加;全组都无法解析时保留第一条非空原文, + 避免把脏数据收成空白。 + + Args: + values: 档上的 quantity 文本。 + Returns: + 合计文本;全空时返回 None。 + """ + total = Decimal(0) + seen = False + fallback: str | None = None + for raw in values: + text = str(raw or "").strip() + if not text: + continue + if fallback is None: + fallback = text + try: + total += Decimal(text) + except InvalidOperation: + continue + seen = True + if not seen: + return fallback + rendered = format(total, "f") + if "." in rendered: + rendered = rendered.rstrip("0").rstrip(".") + return rendered or "0" + + +def _pending_match_group_key(record: PendingMatchRecordDTO) -> tuple: + """待匹配清单的合并键。 + + 有外部单号时按来源、记录类型、外部单号合并,项次不进键。 + 没有外部单号时每条档单独成组,避免把互无关的行加成一笔。 + + Args: + record: 尚未合并的单条档投影。 + Returns: + 可哈希分组键。 + """ + external_doc_no = record.external_doc_no.strip() + if external_doc_no: + return ("external", record.source_code, record.record_kind, external_doc_no) + return ("line", record.ledger_record_id) + + +def _collapse_pending_match_group(rows: list[PendingMatchRecordDTO]) -> PendingMatchRecordDTO: + """把同一合并键下的档行收成清单上的一行。 + + 核心逻辑:数量相加;单号、料号、品名、异动日期只在组内一致时保留。 + 行键用最小档 id,保证翻页和表格行键稳定。 + + Args: + rows: 同一组合并键下的档投影,至少一条。 + Returns: + 合并后的 PendingMatchRecordDTO。 + """ + head = rows[0] + external_doc_no = head.external_doc_no.strip() + return PendingMatchRecordDTO( + ledger_record_id=min(row.ledger_record_id for row in rows), + doc_no=_uniform_text([row.doc_no for row in rows]) or "", + material_code=_uniform_text([row.material_code for row in rows]), + material_name=_uniform_text([row.material_name for row in rows]), + movement_date=_uniform_text([row.movement_date for row in rows]), + source_code=head.source_code, + record_kind=head.record_kind, + external_doc_no=external_doc_no, + quantity=_sum_quantity_text([row.quantity for row in rows]), + matchable=all(row.matchable for row in rows), + ) + + +def _aggregate_pending_match_records(records: list[PendingMatchRecordDTO]) -> list[PendingMatchRecordDTO]: + """按外部单号合并待匹配清单,并保持档查询的先后顺序。 + + 核心逻辑:沿用 pending_ledger_query 的排序(异动日期 → 来源 → 单号 → id)。 + 一组的位置取该组第一条档的位置,这样同一外部单号不会被分页切开后再加总。 + + Args: + records: 未合并的档投影,已按圈档稳定排序。 + Returns: + 合并后的清单。没有外部单号的行原样留下。 + """ + grouped: dict[tuple, list[PendingMatchRecordDTO]] = {} + order: list[tuple] = [] + for record in records: + key = _pending_match_group_key(record) + bucket = grouped.get(key) + if bucket is None: + grouped[key] = [record] + order.append(key) else: - summary.recoverable_count += 1 - if item.aging_level == AGING_WARN_3D: + bucket.append(record) + return [_collapse_pending_match_group(grouped[key]) for key in order] + + +def _load_pending_match_records(*, segment: str, matchable_ids: set[int]) -> list[PendingMatchRecordDTO]: + """读取一段待匹配档并按外部单号合并。 + + 分页单位是合并后的外部单,所以这里先取整段再合并,不能先按档行 limit。 + + Args: + segment: all、matchable 或 outside。调用方已校验。 + matchable_ids: 启用类型范围并集的档 id。 + Returns: + 该段合并后的全量清单。 + """ + rows = pending_ledger_query(matchable_ids=matchable_ids, segment=segment).all() + return _aggregate_pending_match_records([ + _pending_match_dto(record, matchable_ids=matchable_ids) for record in rows + ]) + + +def _count_pending_match_groups(query) -> int: + """按清单合并键计数,不把档行装进内存。 + + 核心逻辑:有外部单号(去掉首尾空白后非空)时按来源、记录类型、外部单号分组; + 没有外部单号时一行一组。分组键与 _pending_match_group_key 一致。 + 查询上的排序会拿掉,否则数据库拒绝按非分组列排序。 + + Args: + query: pending_ledger_query 的某一段。 + Returns: + 合并后的行数。 + """ + external = func.trim(func.coalesce(TransferMovementLedger.external_doc_no, "")) + grouped_kind = case((external != "", literal("external")), else_=literal("line")) + grouped_source = case((external != "", TransferMovementLedger.source_code), else_=literal("")) + grouped_record_kind = case((external != "", TransferMovementLedger.record_kind), else_=literal("")) + grouped_doc = case((external != "", external), else_=cast(TransferMovementLedger.id, String)) + grouped = ( + query.order_by(None) + .with_entities(grouped_kind, grouped_source, grouped_record_kind, grouped_doc) + .group_by(grouped_kind, grouped_source, grouped_record_kind, grouped_doc) + .subquery() + ) + return int(db.session.query(func.count()).select_from(grouped).scalar() or 0) + + +def _matchable_ids() -> set[int]: + """启用类型现在圈得住的档 id。无启用类型时为空集。只取 id,不装载整行。""" + return circle_ledger_record_ids_scope_union() + + +def list_pending_match_records(*, segment: str = "all") -> list[PendingMatchRecordDTO]: + """首页待办看板「待匹配」桶清单(已抓取尚未匹配的外部异动记录,只读)。 + + 数据源=pending_ledger_query:未封存、有异动日期、未被有效 items 占用、 + movement_date ≤ T−2 的出入站记录,不按调拨类型范围过滤。 + segment=matchable 只留启用类型范围并集;segment=outside 是其余已落档。 + 每行 matchable 标记并集成员,供清单把「当前可匹配」和其余行分开。 + 【2026-10-22 清单收口】返回前按来源 + 记录类型 + 外部单号合并,quantity + 为组内数量之和;没有外部单号的档行不合并。首页计数走同一合并。 + 数字变化口径:文件落地→涨;被匹配圈定→离开(占用);取消匹配→回归; + 执行成功→封存恒排除。停用类型只减少可匹配行,不把其余行移出本桶。 + + 不可执行:记录尚未经匹配/库存核对(无 items),本桶仅提供只读清单与 + 「去匹配」引导,禁止任何勾选执行入口。 + + Args: + segment: all、matchable 或 outside。 + Returns: + 合并后的 PendingMatchRecordDTO 列表。一组的位置取其最早一条档 + (异动日期 → 来源 → 单号 → id)。 + Raises: + ValidationError: segment 不是上述三值。 + """ + from app.core.errors import ValidationError + + if segment not in _PENDING_SEGMENTS: + raise ValidationError("segment must be all, matchable, or outside") + return _load_pending_match_records(segment=segment, matchable_ids=_matchable_ids()) + + +def list_pending_match_records_page( + *, + page: int = BACKLOG_PAGE_DEFAULT, + page_size: int = BACKLOG_PAGE_SIZE_DEFAULT, + segment: str = "all", +) -> PendingMatchPageDTO: + """「待匹配」桶分页清单(服务端分页;只读语义与全量版一致)。 + + 【2026-10-22 分页下推】总数与页圈定都在 SQL 完成:total=合并键 GROUP BY + 计数(_count_pending_match_groups);本页组经 row_number 组首行锚点 + OFFSET/LIMIT 圈定(_pending_group_anchor_rows),再只召回本页组的档行做 + 合并投影(_load_page_group_records)——分页单位仍是外部单,但不能先按档行 + limit(同一外部单号会被切进两页),也不能整段装载后内存切片(千行级池上 + 每页都 O(全池))。 + + Args: + page: 页码(1 起)。 + page_size: 每页行数(1..100)。 + segment: all、matchable 或 outside。 + Returns: + PendingMatchPageDTO(records=当前页切片,total=该段合并后的行数)。 + Raises: + ValidationError: segment 不是上述三值。 + """ + from app.core.errors import ValidationError + + if segment not in _PENDING_SEGMENTS: + raise ValidationError("segment must be all, matchable, or outside") + matchable_ids = _matchable_ids() + base = pending_ledger_query(matchable_ids=matchable_ids, segment=segment) + total = _count_pending_match_groups(base) + start = (page - 1) * page_size + anchors = _pending_group_anchor_rows(base, offset=start, limit=page_size) if total > start else [] + records = _load_page_group_records(base, anchors, matchable_ids=matchable_ids) if anchors else [] + return PendingMatchPageDTO( + records=records, + total=total, + page=page, + page_size=page_size, + ) + + +def _pending_group_anchor_rows(base, *, offset: int, limit: int) -> list[Any]: + """按合并键取一页「组首行」锚点(row_number 窗口下推,不装载整段档行)。 + + 核心逻辑:分区键与 _count_pending_match_groups / _pending_match_group_key + 同一口径(外部单号去空白非空=来源+记录类型+外部单号一组;否则每行一组); + 分区排序与 pending_ledger_query 的圈档稳定排序一致(异动日期→来源→单号→ + id),rn=1 即该组在清单上的第一条档——组位置语义与 + _aggregate_pending_match_records「一组的位置取其第一条档」完全一致, + 翻页顺序与全量版逐行相同。 + + Args: + base: pending_ledger_query 的某一段(已含固定条件与分段过滤)。 + offset: 起始组数((page-1)*page_size)。 + limit: 本页组数(page_size)。 + Returns: + 锚点行列表(属性 id/movement_date/source_code/doc_no/group_kind/ + group_source/group_record_kind/group_doc),按组首行位置排序。 + """ + external = func.trim(func.coalesce(TransferMovementLedger.external_doc_no, "")) + group_kind = case((external != "", literal("external")), else_=literal("line")) + group_source = case((external != "", TransferMovementLedger.source_code), else_=literal("")) + group_record_kind = case((external != "", TransferMovementLedger.record_kind), else_=literal("")) + group_doc = case((external != "", external), else_=cast(TransferMovementLedger.id, String)) + ledger_order = ( + TransferMovementLedger.movement_date.asc(), + TransferMovementLedger.source_code.asc(), + TransferMovementLedger.doc_no.asc(), + TransferMovementLedger.id.asc(), + ) + ranked = ( + base.order_by(None) + .with_entities( + TransferMovementLedger.id.label("id"), + TransferMovementLedger.movement_date.label("movement_date"), + TransferMovementLedger.source_code.label("source_code"), + TransferMovementLedger.doc_no.label("doc_no"), + group_kind.label("group_kind"), + group_source.label("group_source"), + group_record_kind.label("group_record_kind"), + group_doc.label("group_doc"), + func.row_number().over( + partition_by=(group_kind, group_source, group_record_kind, group_doc), + order_by=ledger_order, + ).label("rn"), + ) + .subquery() + ) + return ( + db.session.query( + ranked.c.id, + ranked.c.movement_date, + ranked.c.source_code, + ranked.c.doc_no, + ranked.c.group_kind, + ranked.c.group_source, + ranked.c.group_record_kind, + ranked.c.group_doc, + ) + .filter(ranked.c.rn == 1) + .order_by( + ranked.c.movement_date.asc(), + ranked.c.source_code.asc(), + ranked.c.doc_no.asc(), + ranked.c.id.asc(), + ) + .offset(offset) + .limit(limit) + .all() + ) + + +def _load_page_group_records( + base, + anchors: list[Any], + *, + matchable_ids: set[int], +) -> list[PendingMatchRecordDTO]: + """只召回本页各组涉及的档行,复用 Python 合并投影出页内清单。 + + 核心逻辑:外部单号组按 (来源, 记录类型, trim(外部单号)) 条件召回兄弟行, + 行组按锚点 id 召回;装载量只随本页组数与组内项次数增长,不受池规模影响。 + 召回行沿用 _pending_match_dto + _aggregate_pending_match_records 收口, + 口径与全量版完全一致(含 matchable=组内全部行可匹配);最后按锚点顺序 + 还原页序(召回顺序是档序,不是组序)。 + + Args: + base: pending_ledger_query 的某一段(与锚点同一查询,口径天然一致)。 + anchors: _pending_group_anchor_rows 的本页锚点,非空。 + matchable_ids: 启用类型范围并集的档 id(matchable 标记用)。 + Returns: + 本页合并后的清单,顺序与锚点(组首行位置)一致。 + """ + external_keys: list[tuple[str, str, str]] = [] + line_ids: list[int] = [] + for anchor in anchors: + if anchor.group_kind == "external": + external_keys.append((anchor.group_source, str(anchor.group_record_kind or "inbound"), anchor.group_doc)) + else: + line_ids.append(anchor.id) + conds = [] + if external_keys: + conds.append(or_(*[ + and_( + TransferMovementLedger.source_code == source, + TransferMovementLedger.record_kind == record_kind, + func.trim(func.coalesce(TransferMovementLedger.external_doc_no, "")) == doc, + ) + for source, record_kind, doc in external_keys + ])) + if line_ids: + conds.append(TransferMovementLedger.id.in_(line_ids)) + rows = ( + base.filter(or_(*conds)) + .order_by( + TransferMovementLedger.movement_date.asc(), + TransferMovementLedger.source_code.asc(), + TransferMovementLedger.doc_no.asc(), + TransferMovementLedger.id.asc(), + ) + .all() + ) + merged = _aggregate_pending_match_records([ + _pending_match_dto(row, matchable_ids=matchable_ids) for row in rows + ]) + # 页序还原:合并键与锚点分区键同构(record_kind 与 DTO 投影同样取 + # 「空回退 inbound」),据此把组序从档序纠正回组首行位置序。 + position = { + (("external", anchor.group_source, str(anchor.group_record_kind or "inbound"), anchor.group_doc) + if anchor.group_kind == "external" else ("line", anchor.id)): index + for index, anchor in enumerate(anchors) + } + return sorted(merged, key=lambda record: position[_pending_match_group_key(record)]) + + +def _pending_match_counts() -> tuple[int, int]: + """首页待匹配、可匹配计数,与清单合并后的行数一致。 + + 核心逻辑:在数据库里按外部单号合并键计数,不把整段档行装进 Python。 + 可匹配 id 为空时直接记 0,不再扫一遍全量。 + + Returns: + (pending_match_count, matchable_count)。 + """ + matchable_ids = _matchable_ids() + pending_count = _count_pending_match_groups( + pending_ledger_query(matchable_ids=matchable_ids, segment="all"), + ) + if not matchable_ids: + return pending_count, 0 + matchable_count = _count_pending_match_groups( + pending_ledger_query(matchable_ids=matchable_ids, segment="matchable"), + ) + return pending_count, matchable_count + + +def backlog_summary(*, now: datetime | None = None) -> BacklogSummaryDTO: + """计算待处理池汇总计数、老化分级与待匹配桶计数。 + + 【2026-10-22 汇总下推】行桶汇总单条查询取 (status, 老化基准时刻) 轻量元组: + 老化基准=最近 Attempt 时刻(LEFT JOIN GROUP BY 子查询,与 + _latest_attempt_times 同口径),无 Attempt 回退 updated_at;三态计数与 + 老化分级在 Python 单趟折叠。不再经 list_backlog 整池装载 ORM 实体(含 + matching joinedload)——千行级池上 summary 的行桶部分从 O(池) 实体 + + Attempt 批查降到 1 条轻量查询。待匹配/可匹配计数走 _pending_match_counts + (SQL 按外部单号合并键计数),与清单合并后的行数一致。 + + Args: + now: 老化判定的当前时刻(默认当前时间;测试注入用)。 + Returns: + BacklogSummaryDTO(三态计数 + warn_3d/escalate_5d/critical_7d + + pending_match_count/matchable_count)。 + """ + current = now or datetime.utcnow() + summary = BacklogSummaryDTO() + latest_attempt = ( + db.session.query(TransferAttempt.item_id, func.max(TransferAttempt.created_at).label("latest")) + .group_by(TransferAttempt.item_id) + .subquery() + ) + rows = ( + db.session.query( + TransferInvoiceItem.status, + func.coalesce(latest_attempt.c.latest, TransferInvoiceItem.updated_at), + ) + .outerjoin(latest_attempt, latest_attempt.c.item_id == TransferInvoiceItem.id) + .filter(TransferInvoiceItem.status.in_(_ALL_BACKLOG_STATUSES)) + .all() + ) + for status, base_time in rows: + # [STEP 1] 三态计数:closed/unknown 单独计数且不进老化桶(与 + # _backlog_dtos 的 AGING_CLOSED/AGING_UNKNOWN 口径一致)。 + if status == TransferStatus.MANUALLY_CLOSED.value: + summary.closed_count += 1 + continue + if status == TransferStatus.RESULT_UNKNOWN.value: + summary.unknown_count += 1 + continue + # [STEP 2] 可恢复行的老化分级(天数算法与 _backlog_dtos 一致)。 + summary.recoverable_count += 1 + age = max(0, int((current - base_time).total_seconds() // 86400)) + level = aging_level_for(age) + if level == AGING_WARN_3D: summary.warn_3d += 1 - elif item.aging_level == AGING_ESCALATE_5D: + elif level == AGING_ESCALATE_5D: summary.escalate_5d += 1 - elif item.aging_level == AGING_CRITICAL_7D: + elif level == AGING_CRITICAL_7D: summary.critical_7d += 1 + # [待匹配桶计数] 与行桶相互独立,并与清单外部单号合并后的行数一致。 + summary.pending_match_count, summary.matchable_count = _pending_match_counts() return summary diff --git a/backend/app/services/in_transit_transfer/cancellation.py b/backend/app/services/in_transit_transfer/cancellation.py index 9074d503..94ebbcde 100644 --- a/backend/app/services/in_transit_transfer/cancellation.py +++ b/backend/app/services/in_transit_transfer/cancellation.py @@ -3,7 +3,13 @@ 用途:取消尚未开始的 Invoice(cancelled),已成功单据保留、不撤销; 原因必填;取消前后状态进入审计。 依赖:models、status、core.errors。 -逻辑:只作用于 ready_to_execute 且未生成单据的项;终态 Run 不可取消。 +逻辑:只作用于 ready_to_execute 且未生成单据的项;终态 Run 不可取消; + Run 转取消时其名下匹配(TransferMatching)同步转 cancelled,并按 + matching_id 圈定名下 ready 未建单行退役为 cancelled—— + 【出生翻转/D17 占用释放出口(规格 §9)】出生行 run_id=None,必须按匹配 + 圈定才能命中:ready 行退役(队列不再可见、执行门禁拒绝)+ 匹配→cancelled + (阻断行不再占用其圈定的档记录),档记录随即释放、可被后续匹配 + 重新圈定;取消路径不写档(占用释放由状态判定自然达成)。 """ from __future__ import annotations @@ -12,7 +18,7 @@ from datetime import datetime from app import db from app.core.errors import ConflictError, NotFoundError, ValidationError -from app.models import TransferInvoiceItem, TransferRun +from app.models import TransferInvoiceItem, TransferMatching, TransferRun from app.services.in_transit_transfer import status as status_machine @@ -60,6 +66,28 @@ def cancel_run(*, run_no: str, reason: str, actor_id: int | None = None, request ).count() if active == 0: run.status = status_machine.TransferRunStatus.CANCELLED.value + # [D17 占用释放 + 可执行行退役(规格 §9)] Run 取消时名下未终态匹配同步 + # 转 cancelled,并按 matching_id 圈定其名下 items 退役: + # - ready 且未建单的行 → cancelled(出生行 run_id=None,必须按匹配圈定 + # 才能命中——否则取消后行仍 ready,队列双份可见、可与重圈匹配双双 + # 执行=同批档记录二次写 ERP); + # - blocked 行保留阻断解释(不占执行面),其占用 + # 随匹配状态=cancelled 释放(占用判定见 matching_service); + # - executing/result_unknown 行不触碰(在飞/结果裁决中,既有取消语义)。 + # 取消路径不写档(占用释放由状态判定自然达成)。 + for matching in db.session.query(TransferMatching).filter_by(run_id=run.id).all(): + if matching.status in {"success", "failed", "cancelled", "expired"}: + continue + matching.status = status_machine.TransferRunStatus.CANCELLED.value + for item in db.session.query(TransferInvoiceItem).filter_by(matching_id=matching.id).all(): + if ( + item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value + and not item.external_document_no + ): + item.status = status_machine.TransferStatus.CANCELLED.value + item.result_code = "cancelled" + item.result_message = reason_value + cancelled += 1 run.completed_at = run.completed_at or datetime.utcnow() db.session.commit() return {"run_no": run.run_no, "cancelled_count": cancelled} diff --git a/backend/app/services/in_transit_transfer/contracts.py b/backend/app/services/in_transit_transfer/contracts.py index 34e36ea5..55deca59 100644 --- a/backend/app/services/in_transit_transfer/contracts.py +++ b/backend/app/services/in_transit_transfer/contracts.py @@ -14,8 +14,9 @@ from decimal import Decimal from typing import Iterable # ---- 一期冻结错误码(TDD §7.3)------------------------------------------- +# 【TRANSFER_INBOUND_NOT_MATURED 已退役 2026-10-16】成熟概念删除(未上线期不设 +# 兼容层);前端四语言 errors.json 同键一并移除。 TRANSFER_PERMISSION_DENIED = "TRANSFER_PERMISSION_DENIED" -TRANSFER_RECEIPT_NOT_MATURED = "TRANSFER_RECEIPT_NOT_MATURED" TRANSFER_FILE_NOT_READY = "TRANSFER_FILE_NOT_READY" TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID" TRANSFER_INVOICE_CONFLICT = "TRANSFER_INVOICE_CONFLICT" @@ -32,7 +33,6 @@ TRANSFER_NOTIFICATION_FAILED = "TRANSFER_NOTIFICATION_FAILED" KNOWN_TRANSFER_ERROR_CODES: frozenset[str] = frozenset({ TRANSFER_PERMISSION_DENIED, - TRANSFER_RECEIPT_NOT_MATURED, TRANSFER_FILE_NOT_READY, TRANSFER_FILE_SCHEMA_INVALID, TRANSFER_INVOICE_CONFLICT, @@ -67,7 +67,6 @@ class MatchingCountsDTO: """匹配计数。""" file_invoice_count: int = 0 - not_matured_count: int = 0 matched_count: int = 0 executable_count: int = 0 blocked_count: int = 0 @@ -101,13 +100,13 @@ class MatchingItemDTO: to_warehouse: str to_quantity: Decimal result: str - receipt_date: str | None = None + movement_date: str | None = None reason: str = "" external_document_no: str | None = None raw_lines: tuple[RawLineRefDTO, ...] = field(default_factory=tuple) lot_no: str = "" - # 收料文件「仓库」列原值:inventory_match 源映射行匹配键(明细审计与执行期重解析输入)。 - receipt_warehouse_code: str = "" + # 入站文件「仓库」列原值:inventory_match 源映射行匹配键(明细审计与执行期重解析输入)。 + movement_warehouse_code: str = "" # 交易单位原值(movement 契约第 11 字段 unit,计划 D4):展示与 ERP 写入行输入, # 不参与匹配身份与 Hash 快照;空值行在匹配阶段落 blocked_missing_unit。 unit: str = "" @@ -122,6 +121,9 @@ class MatchingItemDTO: # (execution_service.prepare_execution 同款 .strip() 口径)。匹配评估路径填齐, # 供「预计 ERP 单据数」按五元组去重与前端勾选行预估;restore 视图路径缺省 ""。 external_org: str = "" + # 出生匹配快照上的调拨类型 code。可调拨明细跨类型混排时用来展示类别; + # 无匹配或快照未写类型时为空串。 + transfer_type: str = "" @dataclass(frozen=True) @@ -129,14 +131,13 @@ class MatchingSummaryDTO: """匹配摘要(含预计调拨数量、预计 ERP 单据数与匹配 Hash)。 estimated_external_write_count(2026-10-12 口径修正):可执行行按执行建单 - 五元组 (external_org, source_code, receipt_date, from_warehouse, to_warehouse) + 五元组 (external_org, source_code, movement_date, from_warehouse, to_warehouse) 去重后的单据数,非可执行行数——同组多行在执行期合并一张 ERP 单。 """ matching_id: str status: str business_date: str - eligible_receipt_date_to: str expires_at: str counts: MatchingCountsDTO estimated_transfer_quantity: str diff --git a/backend/app/services/in_transit_transfer/current_file_reparse.py b/backend/app/services/in_transit_transfer/current_file_reparse.py new file mode 100644 index 00000000..f12ef004 --- /dev/null +++ b/backend/app/services/in_transit_transfer/current_file_reparse.py @@ -0,0 +1,171 @@ +"""services/in_transit_transfer/current_file_reparse.py + +用途:对当前最新可用入站/出站归档做一次本地重解析并落档(不触发 RPA)。 +依赖:evidence_sync.sync_source_rows、outbound_evidence_sync.sync_outbound_source_rows、 + source_file_status(latest_usable_outbound_file、resolve_source_file_status)、 + freight_rpa.reports.queries(latest_usable_inbound_file、mark_inbound_parse_failure、 + mark_outbound_parse_failure)、date_policy.business_date_now、deps.get_transfer_dependencies、 + file_parser.MovementFileSchemaError、core.errors、flask.current_app(非 schema 失败记日志)。 +逻辑:先确认可用归档与已发布规则门禁,再委托既有 sync_*_source_rows 落档并 commit; + schema 失败 rollback 后 mark 解析失败并单独 commit;无规则/无文件 fail-closed; + 其他异常(含非 NO_PROFILE 的 AppError)rollback、记日志、不标 parse_failed,返回 ok=False。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import datetime + +from flask import current_app + +from app import db +from app.core.errors import AppError, ValidationError +from app.services.freight_rpa.reports.queries import ( + latest_usable_inbound_file, + mark_inbound_parse_failure, + mark_outbound_parse_failure, +) +from app.services.in_transit_transfer.date_policy import business_date_now +from app.services.in_transit_transfer.deps import get_transfer_dependencies +from app.services.in_transit_transfer.evidence_sync import sync_source_rows +from app.services.in_transit_transfer.file_parser import MovementFileSchemaError +from app.services.in_transit_transfer.outbound_evidence_sync import sync_outbound_source_rows +from app.services.in_transit_transfer.source_file_status import ( + latest_usable_outbound_file, + resolve_source_file_status, +) + +_RECORD_KINDS = frozenset({"inbound", "outbound"}) + + +@dataclass(frozen=True) +class CurrentReparseResult: + """一次当前归档重解析的返回。""" + + source_code: str + record_kind: str + ok: bool + file_status: str + file_id: int | None + inserted: int = 0 + updated: int = 0 + skipped: int = 0 + sealed_skipped: int = 0 + error_code: str | None = None + error_message: str | None = None + + +def reparse_current_file(*, source_code: str, record_kind: str, now: datetime) -> CurrentReparseResult: + """重解析该来源当前最新可用归档并提交。 + + 核心逻辑:先取 latest usable 文件。没有文件抛 CURRENT_REPARSE_NO_FILE。 + 有文件则调用既有 sync_*_source_rows。返回 None 表示没有已发布规则,抛 + CURRENT_REPARSE_NO_PROFILE,不写 parse_failed。结构错误回滚后 mark_*_parse_failure + 并单独提交。其他异常(含非 NO_PROFILE 的 AppError,如存储不可用)只回滚、 + 记 TRANSFER_CURRENT_REPARSE_FAILED 日志,不标解析失败,返回 ok=False。 + error_message 取异常 message,为空再退回 str(exc)。成功路径由 sync 函数里的 + movement_file_version 写版本戳,本函数不拼 sha256: 前缀。 + + Args: + source_code: 来源实例编码。 + record_kind: inbound 或 outbound。 + now: 落档与新鲜度判定时刻。 + Returns: + CurrentReparseResult。结构错误和其他落档异常(含非 NO_PROFILE 的 AppError)时 ok 为 False。 + Raises: + ValidationError: record_kind 不是 inbound 或 outbound。 + AppError: 仅 TRANSFER.CURRENT_REPARSE_NO_FILE 或 TRANSFER.CURRENT_REPARSE_NO_PROFILE,HTTP 422。 + """ + kind = record_kind.strip() + if kind not in _RECORD_KINDS: + raise ValidationError("record_kind must be inbound or outbound") + + if kind == "outbound": + file_view = latest_usable_outbound_file(source_code, now=now) + else: + file_view = latest_usable_inbound_file(source_code, now=now) + + if file_view is None: + raise AppError( + code="TRANSFER.CURRENT_REPARSE_NO_FILE", + message="no usable archive file", + http_status=422, + details={"source_code": source_code, "record_kind": kind}, + ) + + file_id = file_view.file_id + + try: + if kind == "outbound": + outcome = sync_outbound_source_rows(source_code=source_code, now=now) + else: + outcome = sync_source_rows( + source_code=source_code, + deps=get_transfer_dependencies(), + business_date=business_date_now(), + now=now, + ) + + if outcome is None: + raise AppError( + code="TRANSFER.CURRENT_REPARSE_NO_PROFILE", + message="no published parsing profile", + http_status=422, + details={"source_code": source_code, "record_kind": kind}, + ) + + db.session.commit() + status = resolve_source_file_status(source_code=source_code, record_kind=kind) + return CurrentReparseResult( + source_code=source_code, + record_kind=kind, + ok=True, + file_status=str(status["file_status"]), + file_id=file_id, + inserted=outcome.inserted, + updated=outcome.updated, + skipped=outcome.skipped, + sealed_skipped=outcome.sealed_skipped, + ) + except MovementFileSchemaError as exc: + db.session.rollback() + error_message = (getattr(exc, "message", "") or str(exc))[:2000] + error_code = exc.code + if kind == "outbound": + mark_outbound_parse_failure( + file_id, error_code=error_code, error_message=error_message) + else: + mark_inbound_parse_failure( + file_id, error_code=error_code, error_message=error_message) + db.session.commit() + status = resolve_source_file_status(source_code=source_code, record_kind=kind) + return CurrentReparseResult( + source_code=source_code, + record_kind=kind, + ok=False, + file_status=str(status["file_status"]), + file_id=file_id, + error_code=error_code, + error_message=error_message, + ) + except Exception as exc: + # 无已发布规则仍是 422;其余 AppError(存储不可用等)与普通异常同一失败分支。 + if isinstance(exc, AppError) and exc.code == "TRANSFER.CURRENT_REPARSE_NO_PROFILE": + raise + db.session.rollback() + current_app.logger.exception( + "TRANSFER_CURRENT_REPARSE_FAILED source=%s kind=%s", + source_code, + kind, + ) + status = resolve_source_file_status(source_code=source_code, record_kind=kind) + error_message = (getattr(exc, "message", "") or str(exc))[:500] + return CurrentReparseResult( + source_code=source_code, + record_kind=kind, + ok=False, + file_status=str(status["file_status"]), + file_id=file_id, + error_code="TRANSFER.CURRENT_REPARSE_FAILED", + error_message=error_message, + ) diff --git a/backend/app/services/in_transit_transfer/date_policy.py b/backend/app/services/in_transit_transfer/date_policy.py index 31b9ad42..8914ca1e 100644 --- a/backend/app/services/in_transit_transfer/date_policy.py +++ b/backend/app/services/in_transit_transfer/date_policy.py @@ -1,11 +1,15 @@ -"""在途调拨业务日期与成熟度策略。 +"""在途调拨业务日期与日期解析。 -用途:固定业务时区 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(读成熟滞后配置)。 +用途:固定业务时区 Asia/Shanghai,统一 parse_date 归一化异动日期(ISO + DSV SSRS + 美式 MM/DD/YYYY[ HH:MM:SS]);提供业务日换算、UTC 存储窗口换算与可匹配 + 截止日(T−2)换算。 +依赖:标准库 zoneinfo / datetime。 逻辑:所有日期判定集中在本模块,供 matching_service / file_parser / evidence_sync 复用,避免各服务各自计算导致口径漂移。 + 【T−2 管控恢复 2026-10-21】T−2 之前的数据全部成熟,T−2 之后(T−1/当天/ + 未来)无成熟数据不可进入异动日期范围——matching_service 以 + eligible_movement_date_to 卡控范围截止;未来日期阻断(数据错误)保留。 + (2026-10-16 曾随成熟规则退役放开到「截止 ≤ 业务日期」,本次按业务口径收回。) """ from __future__ import annotations @@ -15,14 +19,9 @@ from zoneinfo import ZoneInfo SHANGHAI_TZ = ZoneInfo("Asia/Shanghai") -# 成熟度结果 -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 +# 可匹配截止滞后天数:T−2 之前数据全部成熟(与前端 transferDate.ts +# DEFAULT_LOOKBACK_DAYS 同口径,两侧须同步调整)。 +MOVEMENT_DATE_MAX_LAG_DAYS = 2 # DSV SSRS Date Received 常见美式格式(月/日/年,可选时分秒);%m/%d 亦接受单位数。 _US_DATE_FORMATS = ( @@ -35,7 +34,7 @@ _US_DATE_FORMATS = ( def parse_date(value: date | datetime | str) -> date: """将 date/datetime 或日期字符串归一化为 date。 - 核心逻辑:先认 ISO(含带时间),再认美式 MM/DD/YYYY[ HH:MM[:SS]](DSV 收料); + 核心逻辑:先认 ISO(含带时间),再认美式 MM/DD/YYYY[ HH:MM[:SS]](DSV 入站文件); 均失败则 ValueError(fail-closed)。 Args: @@ -59,7 +58,7 @@ def parse_date(value: date | datetime | str) -> date: return datetime.fromisoformat(text).date() except ValueError: pass - # [STEP] DSV SSRS 收料 Date Received:美式月/日/年(可带时分秒)。 + # [STEP] DSV SSRS 入站 Date Received:美式月/日/年(可带时分秒)。 for fmt in _US_DATE_FORMATS: try: return datetime.strptime(text, fmt).date() @@ -84,6 +83,22 @@ def business_date_now(moment: datetime | None = None) -> date: return moment.astimezone(SHANGHAI_TZ).date() +def eligible_movement_date_to(business_date: date | str, + lag_days: int = MOVEMENT_DATE_MAX_LAG_DAYS) -> date: + """返回可进入异动日期范围的截止日(业务日期 T − lag 天,默认 T−2)。 + + 【AI 触发时机】matching_service 校验异动日期范围、或任何需要「最远可选到 + 哪天」的场景;与前端 transferDate.ts defaultMovementDate 同口径。 + + Args: + business_date: 当前业务日期 T。 + lag_days: 截止滞后天数;缺省 MOVEMENT_DATE_MAX_LAG_DAYS。 + Returns: + T − lag 天。 + """ + return parse_date(business_date) - timedelta(days=lag_days) + + def business_date_utc_window(now: datetime | None = None) -> tuple[datetime, datetime]: """返回当前业务日期(Asia/Shanghai)在 UTC 存储时间轴上的 [起, 止) 窗口。 @@ -105,53 +120,3 @@ def business_date_utc_window(now: datetime | None = None) -> tuple[datetime, dat .replace(tzinfo=None) ) return start_utc, start_utc + timedelta(hours=24) - - -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) diff --git a/backend/app/services/in_transit_transfer/deps.py b/backend/app/services/in_transit_transfer/deps.py index 21b2dfba..7f6c7b1f 100644 --- a/backend/app/services/in_transit_transfer/deps.py +++ b/backend/app/services/in_transit_transfer/deps.py @@ -2,8 +2,8 @@ 用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。 依赖:movement_file_repository / capability_client / matching_service / models / Flask config。 -逻辑:默认实现直接接线真实链路 —— 收料文件行读取走 movement_file_repository - (复用货代收料归档 + movement 解析规则,无文件/无规则时返回 None 由 +逻辑:默认实现直接接线真实链路 —— 入站文件行读取走 movement_file_repository + (复用 ShippingInboundReport 归档 + inbound 解析规则,无文件/无规则时返回 None 由 匹配走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver fail-closed 拒绝;外部访问统一走 CapabilityClient(绑定缺失时 fail-closed); 策略经 _strategy_from_config 从 Flask 配置装配——IN_TRANSIT_TRANSFER_ @@ -18,9 +18,14 @@ from typing import Any from flask import current_app -from app.models import ShippingInventoryExternalMapping, ShippingInventorySource +from app.models import FreightRpaOnhandExternalMapping +from app.services.freight_rpa.reports.queries import ( + get_inbound_config, + get_inbound_parsing_profile, + get_site, +) from app.services.in_transit_transfer.capability_client import CapabilityClient -from app.services.in_transit_transfer.movement_file_repository import ShippingReceiptFileRepository +from app.services.in_transit_transfer.movement_file_repository import ShippingInboundFileRepository from app.services.in_transit_transfer.matching_service import ( RouteMapping, RouteNotResolvedError, @@ -39,7 +44,7 @@ class DefaultRouteResolver: 拨出库位 = 映射行的在途仓编码(in_transit_warehouse_code);拨入仓库 = 映射的 目标仓库代码;组织 = 映射的外部组织编码。映射行按库存源识别方式选择: - inventory_match 源优先「收料文件仓库列 == 货代仓库」精确匹配,匹配不到回退 + inventory_match 源优先「入站文件仓库列 == 货代仓库」精确匹配,匹配不到回退 货代仓库为空的默认映射行(空库位兜底);fixed 源仅一条启用映射直接取用。 不借用站点固定仓库(那是货代发货/库存导出链路的字段)。 """ @@ -47,24 +52,29 @@ class DefaultRouteResolver: def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping: """按来源识别方式选择映射行并解析路由;无法归属时抛 RouteNotResolvedError。 + 【阶段 B Task 4】站点行(主键/启停/识别方式)读取改经 + freight_rpa.reports.queries.get_site 只读视图,不再引用站点模型; + 外部仓库映射仍为调拨域自有表(freight_rpa_onhand_external_mappings + 不改归属,见计划 Global Constraints),按站点主键直查。 + Args: source_code: 来源实例编码(须启用)。 invoice_no: Invoice 单号(当前不参与匹配,保留协议兼容)。 - warehouse_code: 收料文件「仓库」列原值(inventory_match 源的映射匹配键)。 + warehouse_code: 入站文件「仓库」列原值(inventory_match 源的映射匹配键)。 Returns: RouteMapping(external_org / from_warehouse=在途仓编码 / to_warehouse)。 Raises: RouteNotResolvedError: 来源不存在、无可用映射行或在途仓编码未维护。 """ - source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() - if source is None: + site = get_site(source_code) + if site is None or not site.enabled: raise RouteNotResolvedError(source_code=source_code) - mappings = ShippingInventoryExternalMapping.query.filter_by( - inventory_source_id=source.id, enabled=True, + mappings = FreightRpaOnhandExternalMapping.query.filter_by( + source_id=site.source_id, enabled=True, ).all() selected = None - if getattr(source, 'warehouse_resolution_mode', '') == 'inventory_match': - # [匹配] 收料仓库大写归一后与货代仓库精确比对;空库位走默认映射行兜底。 + if site.warehouse_resolution_mode == 'inventory_match': + # [匹配] 入站仓库大写归一后与货代仓库精确比对;空库位走默认映射行兜底。 # 部分唯一索引保证同源「精确/默认」各最多一条启用映射,选择结果确定。 key = str(warehouse_code or '').strip().upper() if key: @@ -147,7 +157,7 @@ def get_transfer_dependencies() -> TransferDeps: if _override is not None: return _override return TransferDeps( - file_repository=ShippingReceiptFileRepository(), + file_repository=ShippingInboundFileRepository(), rpa_trigger=_DefaultRpaTrigger(), route_resolver=DefaultRouteResolver(), capabilities=_build_capability_client(), @@ -156,30 +166,30 @@ def get_transfer_dependencies() -> TransferDeps: class _DefaultRpaTrigger: - """默认收料 RPA 触发器:委托真实触发服务(trigger_receipt_rpa)。 + """默认入站 RPA 触发器:委托真实触发服务(trigger_inbound_rpa)。 - 真实链路 = 落单元行 + 原子写 trigger 文件;来源/收料配置缺失或 trigger + 真实链路 = 落单元行 + 原子写 trigger 文件;站点/入站配置缺失或 trigger 目录未配置时由触发服务返回 fail-closed(ok=False),本类只透传结果。 - 另在本类前置守卫:收料配置存在但未绑定已发布 movement 解析规则时 - 直接返回 RPA_RECEIPT_MOVEMENT_PROFILE_MISSING,不触发徒劳抓取。 + 另在本类前置守卫:入站配置存在但未绑定已发布 inbound 解析规则时 + 直接返回 RPA_INBOUND_PROFILE_MISSING,不触发徒劳抓取。 + 【阶段 B Task 4】守卫读取改经 freight_rpa.reports.queries 只读入口 + (get_site / get_inbound_config / get_inbound_parsing_profile)。 """ def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]: - from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa + from app.services.in_transit_transfer.inbound_trigger_service import trigger_inbound_rpa - # [守卫] 收料配置存在但未绑定已发布 movement 解析规则时,触发 RPA 必然徒劳: + # [守卫] 入站配置存在但未绑定已发布 inbound 解析规则时,触发 RPA 必然徒劳: # 抓回的文件无法被 latest_ready_file 复用,匹配会反复重抓。fail-closed 返回明确错误码。 - from app.models import ShippingInventorySource, ShippingReceiptReportConfig - - source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() - if source is not None: - config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first() + site = get_site(source_code) + if site is not None and site.enabled: + config = get_inbound_config(source_code) if config is not None: - profile = config.parsing_profile - if profile is None or profile.status != 'published' or profile.purpose != 'movement': - return {'ok': False, 'error_code': 'RPA_RECEIPT_MOVEMENT_PROFILE_MISSING'} + profile = get_inbound_parsing_profile(source_code) + if profile is None or profile.status != 'published' or profile.purpose != 'inbound': + return {'ok': False, 'error_code': 'RPA_INBOUND_PROFILE_MISSING'} - outcome = trigger_receipt_rpa(source_code=source_code, business_date=business_date, reason=reason) + outcome = trigger_inbound_rpa(source_code=source_code, business_date=business_date, reason=reason) return { "ok": bool(outcome.get("ok")), "callback_id": outcome.get("callback_id"), diff --git a/backend/app/services/in_transit_transfer/evidence_sync.py b/backend/app/services/in_transit_transfer/evidence_sync.py index 6f456692..5d90e92a 100644 --- a/backend/app/services/in_transit_transfer/evidence_sync.py +++ b/backend/app/services/in_transit_transfer/evidence_sync.py @@ -1,94 +1,331 @@ """services/in_transit_transfer/evidence_sync.py -用途:收料证据同步——把来源最新可用收料文件解析为调拨待办行(文件落地即写, - 主链路),并提供「行版本戳 vs 最新文件 sha」的对齐入口(匹配/重查兜底)。 -依赖:file_parser / invoice_aggregator / transfer_type / source_file_status / - matching_service(_item_evaluated_sha、_latest_usable_report_file 复用)/ - contracts / models / audit。 -逻辑:一次解析写入——文件里有、本地没有 → 插入待查行;有且 sha 未变 → - 整行跳过(幂等,不续新鲜度);sha 变了证据没变 → 刷新名称/规格展示值并只换 - 版本戳;证据变了(数量/批号/仓库)→ 刷新证据并重置回待查(旧库存是对旧数量 - 查的,作废);历史残留 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 落到当前可用文件上。 +用途:入站证据同步——把来源最新可用入站文件(freight_rpa 入站 RPA 产物)解析并镜像落档(库存异动档 + transfer_movement_ledger,主链路),一次解析、写档不写明细。 +依赖:file_parser / ledger_sync / freight_rpa.reports.queries(最新可用归档视图 + latest_usable_inbound_file 与解析失败标记 mark/clear——只读只写入口唯一权威)/ + source_file_status(状态投影)/ contracts / audit。 + 【阶段 B Task 4】文件取数不再经 matching_service._latest_usable_report_file + (该函数已删除),改按 source_code 直调 freight_rpa.reports.queries;解析失败 + 标记改按 file_id 调 mark_inbound_parse_failure / clear_inbound_parse_failure。 +逻辑:【2026-10-14 出生翻转(ADR 0001/D3/D4)】本模块不再写 transfer_invoice_items + ——items 改为匹配创建时从档圈定(见 matching_service);落地产物=档行: + ①按自然键查档不存在 → 插入(record_kind/溯源五列随行); + ②同文件重落(sha 一致)→ 幂等跳过(档无 TTL,完全不动行); + ③证据变化 → 原行更新业务镜像列 + 换溯源(ledger_sync 六分类语义); + ④文件缺席的档行保留不删(入站 RPA 非全量导出,缺席≠删除); + ⑤已执行封存行(transfer_executed=true)永不更新永不复活。 + 组装口径:解析行按调拨明细粒度 (doc_no, material_code, movement_date) + 聚合为领域行(数量相加、其余取组内首行、sheet/row_no 取首行)——与旧 + items 汇总粒度一致(档断言等价于原 items 断言),保证「档 → 匹配圈定 → + 严格数量比对」的数量语义不因翻转漂移。 + 全程零外部调用(不查 ERP、不触发 RPA);不 commit 只 flush(提交归调用 + 方:落地桥自行 commit,匹配/重查随主事务)。 + 【档自然键坍缩守卫 终审 I3】组装产物按档自然键行级六成分 (doc_no, line_no, + line_seq, in_out_flag, carton_id, lot_no) 复检:同键批内 ≥2 行且 material_code + 不同(同单号多料号且 + 行级项次全空的输入)→ 每个坍缩键写一条 ledger_natural_key_collapse 审计 + 事件(结果=第二料号行被幂等吞掉,首见为准,数据行为不变)——把静默丢行 + 变显式可观测;事件只在批内实际落档(inserted/updated>0)时打,幂等重落 + 不重复打(防只追加审计表被同文件重落刷爆,与 ledger_sync 交叉校验事件 + 同款防刷口径)。 + 【解析失败分层 2026-09-29】同步成功 = 当前可用文件解析成功 → 清除其解析 + 失败标记(parse_failed 三列置空);桥入口同步失败先 rollback(保持桥隔离), + 仅 schema 类解析失败(TRANSFER_FILE_SCHEMA_INVALID / MovementFileSchemaError) + 把失败事实独立 commit 落到当前可用文件上。 + 【对齐入口退役 2026-10-14】align_scope_rows 已删除:匹配/重查不再对文件 + 兜底重解析,改为对档对账(重查见 retry_service.requery_items 对档 reconciliation)。 + 【解析口径单一化 2026-10-15(spec §6)】「原始行→档行」的解析+组装抽为模块级 + 纯函数 parse_archive_to_ledger_rows:运行期本模块与维护重建 + (backlog_reparse_service 清空并重解析)共用同一实现,杜绝两套解析漂移; + 归档字节→原始行的提取段仍在 movement_file_repository._extract_movement_rows。 """ from __future__ import annotations from dataclasses import dataclass from datetime import datetime +from decimal import Decimal +from typing import Any, Mapping from app import db -from app.models import TransferInvoiceItem -from app.services.in_transit_transfer import status as status_machine +from app.services.freight_rpa.reports.queries import ( + clear_inbound_parse_failure, + latest_usable_inbound_file, + mark_inbound_parse_failure, +) from app.services.in_transit_transfer.audit import build_transfer_audit_event from app.services.in_transit_transfer.contracts import TRANSFER_FILE_SCHEMA_INVALID -from app.services.in_transit_transfer.file_parser import 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.file_parser import ( + MovementFileSchemaError, + ParsedMovementRow, + parse_movement_rows, ) -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.transfer_type import ( - TransferType, - filter_invoices_for_type, +from app.services.in_transit_transfer.ledger_sync import ( + RECORD_KIND_INBOUND, + FileMeta, + sync_ledger_rows, ) # 待查态结果码:13 状态冻结契约内的表达(status='matching' + 本结果码), -# 表示「收料文件已落地、库存侧尚未核对」;禁用新状态值。 +# 表示「已出生/已重置、库存侧尚未核对」;禁用新状态值。出生翻转后该态出现在 +# 匹配创建的出生行(评估前置)与重查对账的证据刷新行(重置待查)。 SYNC_RESULT_PENDING = "pending_stock_check" -# 终态集合与 matching_service 原地刷新口径一致:同步永不触碰既定事实。 -_TERMINAL_ITEM_STATUSES = frozenset({ - status_machine.TransferStatus.SUCCESS.value, - status_machine.TransferStatus.DUPLICATE_SUCCESS.value, - status_machine.TransferStatus.MANUALLY_CLOSED.value, - status_machine.TransferStatus.CANCELLED.value, - status_machine.TransferStatus.EXECUTING.value, - status_machine.TransferStatus.RESULT_UNKNOWN.value, -}) +# 档自然键坍缩审计事件 kind(终审 I3 冻结字面量;仓库事件 kind 无集中常量表, +# 行内常量惯例——ledger_sync.LEDGER_CROSS_CHECK_EVENT 同款)。与交叉校验矛盾 +# (in_out_flag 错位)分 kind:修复动作不同(前者查导出模板项次列,后者查进出 +# 库别映射),运维按 kind 检索互不干扰。 +LEDGER_NATURAL_KEY_COLLAPSE_EVENT = "ledger_natural_key_collapse" @dataclass(frozen=True) class SyncOutcome: - """一次来源同步的结果计数(审计与兜底日志的数据源)。""" + """一次来源落档的结果计数(审计与兜底日志的数据源;计数随 ledger_sync 同源, + date_skipped(异动日期空值)在 ledger_sync 落档过滤阶段消化,不透传本层)。""" source_code: str file_sha256: str - inserted: int = 0 # 文件有、本地无 → 插入待查行 - refreshed: int = 0 # sha 变了、业务值没变 → 只换版本戳,状态保留 - reset_pending: int = 0 # 业务值变了 → 刷新值 + 重置待查(旧库存作废) - absent_kept: int = 0 # 文件里缺席 → 换戳保留状态(存续:缺席≠删除,2026-09-28) - skipped: int = 0 # sha 未变的幂等跳过;终态四元组重落地亦计入(不复活) + inserted: int = 0 # 自然键不存在 → 插入新档行 + updated: int = 0 # 证据变化 → 原行更新业务镜像列 + 换溯源 + skipped: int = 0 # sha 未变的幂等跳过;封存行命中亦计入(sealed_skipped 另计) + sealed_skipped: int = 0 # 封存行(transfer_executed=true):永不更新永不复活 + cross_flagged: int = 0 # record_kind 与 in_out_flag 矛盾且本次实际落档的行数 + + +def _assemble_ledger_rows( + parsed: list[ParsedMovementRow], + raw_rows: list[Any], +) -> list[dict]: + """把解析行组装为落档领域行 dict(档断言等价于原 items 断言的粒度桥)。 + + 核心逻辑:[STEP 1] 原始行按 (sheet, row_no) 建索引——ParsedMovementRow 无扩展 + 字段槽位(Task 8 事实),扩展 7 字段(line_no/line_seq/in_out_flag/order_type/ + odm_*/carton_id/pallet_id 及 🔖预留)与外部单据身份(external_doc_no/ + external_line_no,2026-10-21 扩展)从原始领域行 dict 取。[STEP 2] 按调拨明细 + 粒度 (doc_no, material_code, movement_date, 外部单号, 外部项次) 聚合:数量 + Decimal 相加,其余字段取组内首行,sheet_name/row_no 取首行——与旧 aggregate_ + invoices 汇总键一致,保证翻转后严格数量比对(ASN 合计 vs ERP 账面)语义不变; + 外部单据身份入聚合键(2026-10-21):不同 WMS 单号/项次的行不得数量相加折叠 + (外部身份是档自然键成分,折叠即丢行)。 + 注意:原始行无「项次」且同单号多料号时,自然键 (doc_no, line_no='', ..., + carton_id 等值, lot_no 等值) 会折叠多料号行为一条档记录(档自然键不含料号, + 规格 §4.2;carton_id/lot_no 为键成分,批内等值才折叠)——真实 WMS 导出 + 携带项次列,不命中该形态;该坍缩形态由 _detect_natural_key_collapses 检测并 + 落 ledger_natural_key_collapse 审计事件(终审 I3,静默丢行 → 显式可观测)。 + + Args: + parsed: 已校验解析行(parse_movement_rows 产物)。 + raw_rows: 原始领域行 dict 列表(ReadyInboundFile.rows,扩展字段来源)。 + Returns: + 领域行 dict 列表(键=movement 契约 field code + 行级溯源 sheet_name/row_no, + 即 sync_ledger_rows 的 parsed_rows 契约)。 + """ + raw_by_key: dict[tuple[str, Any], Mapping] = {} + for raw in raw_rows or []: + if not isinstance(raw, Mapping): + continue + raw_by_key[(str(raw.get("sheet") or "").strip(), raw.get("row_no"))] = raw + + groups: dict[tuple[str, str, str, str, str], dict] = {} + ordered: list[dict] = [] + for row in parsed: + raw = raw_by_key.get((row.sheet, row.row_no)) or {} + # 聚合键含外部单据身份(2026-10-21):不同外部单号/项次不折叠、不数量相加。 + key = (row.invoice_no, row.material_no, row.movement_date.isoformat(), + _natural_key_text(raw.get("external_doc_no")), + _natural_key_text(raw.get("external_line_no"))) + group = groups.get(key) + if group is None: + group = { + "doc_no": row.invoice_no, + # 无项次列的导出按空串落自然键(可空成分 NOT NULL + default '')。 + "line_no": str(raw.get("line_no") or "").strip(), + "in_out_flag": str(raw.get("in_out_flag") or "").strip(), + "material_code": row.material_no, + "material_name": row.material_name, + "specification": row.specification, + "warehouse_code": row.warehouse_code, + "storage_code": str(raw.get("storage_code") or "").strip(), + "lot_no": row.lot_no, + "quantity": Decimal(str(row.movement_quantity)), + "unit": row.unit, + "movement_date": row.movement_date.isoformat(), + "line_seq": str(raw.get("line_seq") or "").strip(), + "order_type": str(raw.get("order_type") or "").strip(), + "odm_id": str(raw.get("odm_id") or "").strip(), + "odm_name": str(raw.get("odm_name") or "").strip(), + "carton_id": str(raw.get("carton_id") or "").strip(), + "pallet_id": str(raw.get("pallet_id") or "").strip(), + # 外部单据身份(2026-10-21 扩展:外部单号/外部项次=WMS Order #/ + # 行号)——异动档自然键成分(档幂等主键管控),缺列按空串落键。 + "external_doc_no": str(raw.get("external_doc_no") or "").strip(), + "external_line_no": str(raw.get("external_line_no") or "").strip(), + # 🔖预留列(出货报告确认后直接映射):入站侧照常透传原值。 + "doc_nature": str(raw.get("doc_nature") or "").strip(), + "movement_type": str(raw.get("movement_type") or "").strip(), + "reason_code": str(raw.get("reason_code") or "").strip(), + "source_ref_no": str(raw.get("source_ref_no") or "").strip(), + "partner_code": str(raw.get("partner_code") or "").strip(), + "remark": str(raw.get("remark") or "").strip(), + "sheet_name": row.sheet, + "row_no": row.row_no, + } + groups[key] = group + ordered.append(group) + else: + # [数量聚合] 同 (单号,料号,日期) 多行数量相加(与旧 items 汇总同口径)。 + group["quantity"] = group["quantity"] + Decimal(str(row.movement_quantity)) + + rows: list[dict] = [] + for group in ordered: + flattened = dict(group) + flattened["quantity"] = str(group["quantity"]) + rows.append(flattened) + return rows + + +def _natural_key_text(value: Any) -> str: + """自然键/料号成分归一化(与 ledger_sync._key_text 同口径):None → 空串 + strip。 + + Args: + value: 领域行 dict 成分原值。 + Returns: + 可比对的归一化文本。 + """ + return "" if value is None else str(value).strip() + + +def _detect_natural_key_collapses(rows: list[dict]) -> list[dict]: + """检测批内档自然键坍缩(终审 I3,纯函数不改行)。 + + 【AI 触发时机】sync_source_rows 组装落档前调用;不要在匹配/执行链路调用。 + 判定:档自然键行级八成分 (doc_no, line_no, line_seq, in_out_flag, carton_id, + lot_no, external_doc_no, external_line_no)(source_code/record_kind 整批恒定 + 不入键;carton_id/lot_no 随 tt14 键扩维入检;外部单据身份随 2026-10-21 键 + 扩维入检——批内等值才可能与既有档行同键)批内出现 ≥2 行且 material_code + 不同 → 该键坍缩(落地侧第二料号行必被幂等吞掉)。同料号多行不算坍缩(数量 + 聚合合法形态,且规格 §4.2 判据即料号不同)。首见序返回,保证审计内容确定。 + + Args: + rows: _assemble_ledger_rows 产物(成分已归一化)。 + Returns: + 坍缩键信息列表(仅含坍缩键):doc_no/line_no/line_seq/in_out_flag/ + carton_id/lot_no/external_doc_no/external_line_no + material_codes + (首见序全量料号)+ dropped_material_codes(首见后被吞料号)。 + """ + seen: dict[tuple[str, ...], dict] = {} + for row in rows: + key = ( + _natural_key_text(row.get("doc_no")), + _natural_key_text(row.get("line_no")), + _natural_key_text(row.get("line_seq")), + _natural_key_text(row.get("in_out_flag")), + _natural_key_text(row.get("carton_id")), + _natural_key_text(row.get("lot_no")), + _natural_key_text(row.get("external_doc_no")), + _natural_key_text(row.get("external_line_no")), + ) + material = _natural_key_text(row.get("material_code")) + entry = seen.get(key) + if entry is None: + seen[key] = {"key": key, "materials": [material], "dropped": []} + elif material not in entry["materials"]: + entry["materials"].append(material) + entry["dropped"].append(material) + return [ + { + "doc_no": entry["key"][0], "line_no": entry["key"][1], + "line_seq": entry["key"][2], "in_out_flag": entry["key"][3], + "carton_id": entry["key"][4], "lot_no": entry["key"][5], + "external_doc_no": entry["key"][6], "external_line_no": entry["key"][7], + "material_codes": entry["materials"], + "dropped_material_codes": entry["dropped"], + } + for entry in seen.values() if entry["dropped"] + ] + + +def _natural_key_collapse_event(*, source_code: str, collapse: dict, + record_kind: str = RECORD_KIND_INBOUND): + """构造档自然键坍缩审计事件(未落库,由调用方 add——build 契约同 ledger_sync)。 + + Args: + source_code: 来源实例编码(自然键成分,整批一致)。 + collapse: _detect_natural_key_collapses 的单条坍缩键信息。 + record_kind: 记录类型(入站/出站共用检测口径;聚合键与快照随流声明)。 + Returns: + 已计算 Hash 的 TransferAuditEvent(event_type=ledger_natural_key_collapse, + result='failure':数据质量降级——行被吞是既成事实,须运维介入核导出模板)。 + """ + natural_key = "/".join(( + source_code, record_kind, + collapse["doc_no"], collapse["line_no"], collapse["line_seq"], collapse["in_out_flag"], + collapse["carton_id"], collapse["lot_no"], + collapse["external_doc_no"], collapse["external_line_no"], + )) + return build_transfer_audit_event( + event_type=LEDGER_NATURAL_KEY_COLLAPSE_EVENT, + aggregate_type="transfer_movement_ledger", + # aggregate_id 列宽 String(128):超长截断防御(全量字段在 after 快照留存, + # 与 ledger_sync._cross_check_event 同款防御)。 + aggregate_id=natural_key[:128], + actor_type="system", + result="failure", + after={ + "source_code": source_code, "record_kind": record_kind, + "doc_no": collapse["doc_no"], "line_no": collapse["line_no"], + "line_seq": collapse["line_seq"], "in_out_flag": collapse["in_out_flag"], + "carton_id": collapse["carton_id"], "lot_no": collapse["lot_no"], + "external_doc_no": collapse["external_doc_no"], + "external_line_no": collapse["external_line_no"], + "material_codes": collapse["material_codes"], + "dropped_material_codes": collapse["dropped_material_codes"], + "resolution": "first_seen_wins", + }, + ) + + +def parse_archive_to_ledger_rows(*, source_code: str, rows: list[dict]) -> list[dict]: + """归档原始行 → 档行领域 dict 列表(解析+组装单一口径,运行期/重建共用)。 + + 【AI 触发时机】运行期落档(sync_source_rows)与维护重建 + (backlog_reparse_service 清空并重解析,spec §6)在把归档原始行组装为落档 + 领域行时都必须经本函数;禁止任何一方绕开自组解析(两套解析=映射漂移温床)。 + 「归档字节 → 本函数入参原始行」的提取段在 + movement_file_repository._extract_movement_rows(latest_ready_file 与重建路径 + 同一实现),本函数承接其后的行校验解析(parse_movement_rows)与明细粒度 + 聚合组装(_assemble_ledger_rows)——两段合起来才是完整的「归档字节→档行」。 + + Args: + source_code: 来源实例编码(解析行来源身份一致性校验)。 + rows: 归档原始行 dict 列表(ReadyInboundFile.rows 同构:领域字段 + + 溯源 sheet/row_no)。 + Returns: + 领域行 dict 列表(sync_ledger_rows 的 parsed_rows 契约)。 + Raises: + MovementFileSchemaError: 任一行必填缺失/非法值(调用方按场景分层处理: + 运行期落解析失败标记;重建整体中止 TRANSFER.REPARSE_PARSE_FAILED)。 + """ + parsed = parse_movement_rows(source_code=source_code, rows=rows) + return _assemble_ledger_rows(parsed, rows) def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetime) -> SyncOutcome | None: - """解析来源最新可用收料文件并三分类写入待办行(零外部调用,flush 不 commit)。 + """解析来源最新可用入站文件并幂等落档(零外部调用,flush 不 commit)。 + + 【AI 触发时机】入站 RPA 回调桥(sync_and_commit_for_callback)与来源解析 + 失败重试入口调用;不要在匹配/重查链路调用(匹配从档圈定,不写档)。 【解析失败分层 2026-09-29】成功返回前清除当前可用文件的解析失败标记 - (parse_failed 三列置空,来源投影恢复 ready)——能走到成功返回即代表该 - 文件已成功解析;无标记时为 no-op。 + (parse_failed 三列置空)——能走到成功返回即代表该文件已成功解析;无标记时 + 为 no-op。 Args: source_code: 来源实例编码。 - deps: TransferDeps(只用 file_repository 与 route_resolver)。 + deps: TransferDeps(只用 file_repository)。 business_date: 业务日期(文件仓库「当天抓取」新鲜度口径)。 - now: 新鲜度基准(显式续 updated_at,执行门禁展示依据)。 + now: 落档时间基准(插入/更新显式续 updated_at)。 Returns: SyncOutcome;来源无可用文件(未抓取/已过期/已清理)返回 None(该分支 不触碰解析失败标记——没有成功解析的事实不得清除失败标记)。 @@ -96,152 +333,46 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim ready = deps.file_repository.latest_ready_file(source_code=source_code, business_date=business_date) if ready is None: return None - parsed = parse_movement_rows(source_code=source_code, rows=ready.rows) - invoices = filter_invoices_for_type( - aggregate_invoices(parsed, file_version=ready.file_version), - TransferType.IN_TRANSIT_TO_HUB, + # [STEP 1] 解析+组装领域行(明细粒度聚合):经 parse_archive_to_ledger_rows + # 单一口径(运行期与重建共用,schema 类失败原样上抛——桥内 rollback + + # 落解析失败标记)。 + assembled = parse_archive_to_ledger_rows(source_code=source_code, rows=list(ready.rows)) + + # [STEP 2] 幂等落档;ledger_sync 只 flush 不 commit(提交归调用方:桥自行 + # commit,匹配/重查随主事务)。溯源文件 id:当前可用归档文件(Fake 仓库 + # 测试场景/文件已清理时为 None,档事实留存不依赖文件存在)。 + # 【阶段 B Task 4】文件身份改取 freight_rpa.reports.queries 只读视图(主键 file_id)。 + file_view = latest_usable_inbound_file(source_code) + outcome = sync_ledger_rows( + source_code=source_code, + record_kind=RECORD_KIND_INBOUND, + parsed_rows=assembled, + file_meta=FileMeta( + source_file_id=file_view.file_id if file_view is not None else None, + file_version=ready.file_version, + file_sha256=ready.checksum, + ), + now=now, + ) + # [档自然键坍缩守卫 终审 I3] 组装产物复检:同自然键批内料号不同(同单号多 + # 料号且项次全空)→ 每个坍缩键写一条审计事件(行处理不变,首见为准——把 + # 静默丢行变显式可观测)。只在批内实际落档(inserted/updated>0)时打事件: + # 幂等重落(sha 未变全跳过)不重复打,防只追加审计表被同文件重落刷爆 + # (与 ledger_sync 交叉校验事件「矛盾标记随落档动作发生」同款防刷口径)。 + collapses = _detect_natural_key_collapses(assembled) + if collapses and (outcome.inserted or outcome.updated): + for collapse in collapses: + db.session.add(_natural_key_collapse_event( + source_code=source_code, collapse=collapse)) + result = SyncOutcome( + source_code=source_code, + file_sha256=ready.checksum or "", + inserted=outcome.inserted, + updated=outcome.updated, + skipped=outcome.skipped, + sealed_skipped=outcome.sealed_skipped, + cross_flagged=outcome.cross_flagged, ) - - # [STEP 1] 圈定本来源全部非终态既有行,按四元组建索引(matching_id 已放开 - # 非空,落地行不受 uq_transfer_invoice_items_matching_grain 保护,幂等去重 - # 由本应用层四元组负责)。 - existing = TransferInvoiceItem.query.filter( - TransferInvoiceItem.source_code == source_code, - TransferInvoiceItem.status.not_in(_TERMINAL_ITEM_STATUSES), - ).all() - by_key = {(r.source_code, r.invoice_no, r.material_no, r.receipt_date): r for r in existing} - - # [终态去重圈] 终态行同样纳入四元组去重范围(只查四列,轻量):若只在非终态 - # 行内去重,来源全终态后同文件重落地(同日 RPA 重试再触发落地桥 / align 兜底 - # 重解析)时 quad 缺席索引会被当全新行重插 pending——已执行的调拨单「复活」 - # 回待办池,存在以新 doc_no 二次真实执行的风险。终态不复活是冻结约束: - # 重落地对终态行既不重插也不触碰。 - terminal_keys = { - tuple(r) - for r in TransferInvoiceItem.query.with_entities( - TransferInvoiceItem.source_code, - TransferInvoiceItem.invoice_no, - TransferInvoiceItem.material_no, - TransferInvoiceItem.receipt_date, - ).filter( - TransferInvoiceItem.source_code == source_code, - TransferInvoiceItem.status.in_(_TERMINAL_ITEM_STATUSES), - ).all() - } - - counters = {"inserted": 0, "refreshed": 0, "reset_pending": 0, "absent_kept": 0, "skipped": 0} - incoming_keys: set[tuple] = set() - - # [STEP 2] 文件内单逐张三分类:跳过 / 插入 / 刷新+重置。 - for invoice in invoices: - receipt_date_iso = invoice.receipt_date.isoformat() - key = (source_code, invoice.invoice_no, invoice.material_no, receipt_date_iso) - incoming_keys.add(key) - row = by_key.get(key) - # [终态不复活] 该四元组已有终态行(已执行/已关闭等):同文件重落地跳过 - # 整行——不重插新 pending 行,也不触碰终态行本身(计数归 skipped 口径)。 - # 必须在插入判定之前拦截,否则全终态来源重落地会重开已执行的调拨单。 - if row is None and key in terminal_keys: - counters["skipped"] += 1 - continue - # [证据变化判定] 只比对收料事实(数量/批号/仓库);material_name 等展示 - # 字段不触发重置(重置会作废旧库存查询,代价是重查)。 - evidence_changed = row is None or ( - str(row.receipt_quantity) != str(invoice.receipt_quantity) - or (row.lot_no or "") != (invoice.lot_no or "") - or (row.receipt_warehouse_code or "") != (invoice.warehouse_code or "") - ) - if row is not None and not evidence_changed and _item_evaluated_sha(row) == ready.checksum: - counters["skipped"] += 1 # [幂等] 同文件重复落地:零写入(不续新鲜度) - continue - if row is None: - from_wh, to_wh = _resolve_route_best_effort(deps, source_code, invoice) - db.session.add(TransferInvoiceItem( - matching_id=None, # 落地行尚无匹配归属(列已放开非空) - source_code=source_code, - invoice_no=invoice.invoice_no, - material_no=invoice.material_no, - material_name=invoice.material_name, - specification=invoice.specification, - receipt_date=receipt_date_iso, - status=status_machine.TransferStatus.MATCHING.value, - result_code=SYNC_RESULT_PENDING, - result_message=None, - from_warehouse=from_wh, - to_warehouse=to_wh, - receipt_quantity=str(invoice.receipt_quantity), - external_quantity=None, - lot_no=invoice.lot_no or "", - receipt_warehouse_code=invoice.warehouse_code or "", - unit="", # 单位只取 ERP stock_unit,匹配查询时落列 - raw_lines_json=[ - {"sheet": line.sheet, "row_no": line.row_no, - "file_version": line.file_version, "file_sha256": ready.checksum} - for line in invoice.raw_lines - ], - updated_at=now, - )) - counters["inserted"] += 1 - continue - # [Important② 复现行] 历史残留消失标记行(blocked_file_removed)重新出现 - # 在最新文件:无论证据变化与否都必须恢复待查态——其历史解释(文件里消失) - # 已失效;若只换戳不恢复,行卡在 blocked 且对齐入口直通,永久隐藏。 - # 非终态行恢复不违反终态冻结。历史残留行防御(2026-09-28 起同步不再新产生该码)。 - restored_from_removed = row.result_code == RESULT_FILE_REMOVED - # [版本戳] 行随最新文件版本刷新(复现行与普通行同路径换新戳,对齐入口 - # 据此收敛直通)。 - row.raw_lines_json = [ - {"sheet": line.sheet, "row_no": line.row_no, - "file_version": line.file_version, "file_sha256": ready.checksum} - for line in invoice.raw_lines - ] - # [Important① 展示字段] 名称/规格属展示字段:进入非跳过分支即刷新 - # (放在证据分支判断之外)——是否重置待查只由三证据字段决定,避免纯 - # 名称变更落入 refreshed 后展示值随新戳固化(align 直通后永不更新)。 - row.material_name = invoice.material_name - row.specification = invoice.specification - if evidence_changed: - # [STEP 3] 收料事实变化:刷新证据值(数量/批号/仓库)。 - row.receipt_quantity = str(invoice.receipt_quantity) - row.lot_no = invoice.lot_no or "" - row.receipt_warehouse_code = invoice.warehouse_code or "" - if evidence_changed or restored_from_removed: - # [重置/恢复] 值变 → 重置回待查(旧库存是对旧数量查的,作废); - # 复现行 → 恢复待查(重新进入待办池,计数同归 reset_pending 口径)。 - row.status = status_machine.TransferStatus.MATCHING.value - 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] 文件里缺席的非终态行 → 存续处理(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 - - # [STEP 5] 只 flush 不 commit:落地桥自行 commit,匹配/重查随主事务。 - db.session.flush() - outcome = SyncOutcome(source_code=source_code, file_sha256=ready.checksum or "", **counters) db.session.add(build_transfer_audit_event( event_type="TRANSFER_EVIDENCE_SYNCED", aggregate_type="transfer_source", @@ -249,92 +380,38 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim actor_type="system", result="success", after={ - "file_sha256": outcome.file_sha256, - "inserted": outcome.inserted, "refreshed": outcome.refreshed, - "reset_pending": outcome.reset_pending, "absent_kept": outcome.absent_kept, - "skipped": outcome.skipped, + "file_sha256": result.file_sha256, + "record_kind": RECORD_KIND_INBOUND, + "inserted": result.inserted, "updated": result.updated, + "skipped": result.skipped, "sealed_skipped": result.sealed_skipped, + "cross_flagged": result.cross_flagged, }, )) # [解析失败分层 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 - - -def align_scope_rows(*, source_codes: list[str], deps, business_date: str, now: datetime) -> dict: - """兜底对齐入口:行版本戳 ≠ 最新文件 sha 的来源才重新解析(一致直通零开销)。 - - 【AI 触发时机】:匹配(run_matching STEP 0)与重查(requery_* STEP 0)调用; - 落地同步(主链路)失败的静默兜底——稳态下 sha 一致,本函数零解析直通。 - - Args: - source_codes: 来源实例编码列表。 - deps: TransferDeps(透传 sync_source_rows)。 - business_date: 业务日期(文件新鲜度口径)。 - now: 新鲜度基准。 - Returns: - {source_code: SyncOutcome|None};None=已对齐或无可用文件(未解析)。 - """ - outcomes: dict = {} - for code in source_codes: - latest = resolve_source_file_status(source_code=code) or {} - latest_sha = latest.get("file_sha256") - if not latest_sha: - outcomes[code] = None - continue - rows = TransferInvoiceItem.query.filter( - TransferInvoiceItem.source_code == code, - TransferInvoiceItem.status.not_in(_TERMINAL_ITEM_STATUSES), - ).all() - row_shas = {_item_evaluated_sha(r) for r in rows} - if row_shas == {latest_sha}: - outcomes[code] = None # 已对齐:直通 - continue - outcomes[code] = sync_source_rows(source_code=code, deps=deps, - business_date=business_date, now=now) - return outcomes - - -def _resolve_route_best_effort(deps, source_code: str, invoice) -> tuple[str, str]: - """同步期预解析路由落列(纯配置查表);解析失败留空不阻断(匹配时再解析)。 - - Args: - deps: TransferDeps(只用 route_resolver)。 - source_code: 来源实例编码。 - invoice: AggregatedInvoice(取 invoice_no / warehouse_code)。 - Returns: - (from_warehouse, to_warehouse);未配置路由返回 ("", "")。 - """ - try: - route = deps.route_resolver.resolve( - source_code=source_code, invoice_no=invoice.invoice_no, - warehouse_code=invoice.warehouse_code or "", - ) - return route.from_warehouse, route.to_warehouse - except RouteNotResolvedError: - return "", "" + # 失败标记(若此前失败过),来源状态投影随之恢复 ready。只 flush 不 commit, + # 提交归调用方。无可用归档时为 no-op。 + if file_view is not None and file_view.parse_failed_at is not None: + clear_inbound_parse_failure(file_view.file_id) + return result def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: datetime) -> bool: - """收料回调桥专用入口:同步 + 自行 commit + 异常全吞(仅 warning 日志)。 + """入站回调桥专用入口:落档 + 自行 commit + 异常全吞(仅 warning 日志)。 - 【AI 触发时机】:收料 RPA 回调 success 终态落文件后由 - shipping_notice.receipt_report_storage 的桥函数调用——桥是记账不是收料链路 - 的正确性依赖,任何异常不得向收料归档主链路传播(B3:必须自行 commit)。 + 【AI 触发时机】:入站 RPA 回调 success 终态落文件后由 + shipping_notice 域 ShippingInboundReport 归档存储的桥函数调用——桥是记账 + 不是入站链路的正确性依赖,任何异常不得向 ShippingInboundReport 归档主链路传播(B3:必须自行 commit)。 【解析失败分层 2026-09-29】失败路径先 rollback(桥隔离),仅 schema 类 - 解析失败把失败事实(parse_failed 三列)独立 commit 落到当前可用文件上。 + 解析失败把失败事实(parse_failed 三列)独立 commit 落到当前可用文件上; + 丢失的落档由回调重试/来源「重试 RPA」入口(本地重解析)兜底 + (原 align 兜底入口已随对档对账切换退役)。 Args: - source_code: 来源实例编码(收料单元行上的 source_code)。 + source_code: 来源实例编码(入站单元行上的 source_code)。 business_date: 业务日期(文件仓库「当天抓取」新鲜度口径)。 - now: 新鲜度基准(显式续 updated_at)。 + now: 落档时间基准。 Returns: - True=同步成功或无事可做(无可用文件);False=同步失败(已记日志; + True=落档成功或无事可做(无可用文件);False=落档失败(已记日志; schema 类失败尽力把解析失败标记落库并独立提交,标记失败仅告警不影响返回)。 """ from flask import current_app @@ -344,37 +421,37 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d business_date=business_date, now=now) # [桥隔离] sync_source_rows 只 flush 不 commit;桥由回调主链路在归档 # commit 之后独立调用,提交时机不归调用方管(B3 持久性教训),必须 - # 在此自行提交,否则请求结束 session 回滚会丢掉已解析的待办行。 + # 在此自行提交,否则请求结束 session 回滚会丢掉已解析的档行。 db.session.commit() if outcome is not None: current_app.logger.info( - "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.absent_kept, outcome.skipped) + "TRANSFER_EVIDENCE_SYNC source=%s inserted=%s updated=%s skipped=%s sealed=%s cross=%s", + source_code, outcome.inserted, outcome.updated, + outcome.skipped, outcome.sealed_skipped, outcome.cross_flagged) return True except Exception as exc: # noqa: BLE001 —— 桥隔离:失败仅日志(见模块 docstring「落地桥」) - # [桥隔离] 为什么吞异常:桥是记账不是收料链路的正确性依赖,同步崩溃 - # 绝不允许波及收料归档终态;丢失的同步由对齐入口 align_scope_rows 兜底。 + # [桥隔离] 为什么吞异常:桥是记账不是入站链路的正确性依赖,落档崩溃 + # 绝不允许波及 ShippingInboundReport 归档终态;丢失的落档由回调重试/人工重取兜底。 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) + # 仅 schema 类失败(TRANSFER_FILE_SCHEMA_INVALID / MovementFileSchemaError) # 落库——通用异常(网络/DB 故障等)不是文件解析问题,不落标记。标记写入后 - # 独立 commit(B3:桥自行提交;同步数据已回滚,本次 commit 只持久化失败 + # 独立 commit(B3:桥自行提交;落档数据已回滚,本次 commit 只持久化失败 # 事实),桥隔离语义保持,仍返回 False。 # [取消息] AppError 为 dataclass(kwargs 初始化)str() 为空串:按 _matching_rows # 同款兜底链取 message 字段,保证落库的错误信息可用于诊断。 # 标记写入是尽力而为:查询/落库/提交若再抛异常(如 DB 抖动)也必须吞掉, - # B3(任何异常不得向收料归档主链路传播)优先于标记落库,丢失标记由下次重试补。 + # B3(任何异常不得向 ShippingInboundReport 归档主链路传播)优先于标记落库,丢失标记由下次重试补。 try: code = getattr(exc, "code", None) or "" - if code == TRANSFER_FILE_SCHEMA_INVALID or isinstance(exc, ReceiptFileSchemaError): + if code == TRANSFER_FILE_SCHEMA_INVALID or isinstance(exc, MovementFileSchemaError): detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__ - report = _latest_usable_report_file(source_code) - if report is not None: - record_receipt_parse_failure( - report=report, + file_view = latest_usable_inbound_file(source_code) + if file_view is not None: + mark_inbound_parse_failure( + file_view.file_id, error_code=str(code or TRANSFER_FILE_SCHEMA_INVALID), error_message=str(detail)[:2000], ) @@ -386,7 +463,7 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d def _default_deps(): - """装配默认 TransferDeps(桥入口专用:收料链路无 deps 可透传)。 + """装配默认 TransferDeps(桥入口专用:入站链路无 deps 可透传)。 Returns: TransferDeps(测试经 deps._override 注入 Fake 时返回注入值)。 diff --git a/backend/app/services/in_transit_transfer/excel_export.py b/backend/app/services/in_transit_transfer/excel_export.py index 0bf7dfb5..3e685959 100644 --- a/backend/app/services/in_transit_transfer/excel_export.py +++ b/backend/app/services/in_transit_transfer/excel_export.py @@ -82,12 +82,12 @@ def _sheet_summary(workbook: Workbook, run: TransferRun, items: list[TransferInv def _sheet_blocked(workbook: Workbook, items: list[TransferInvoiceItem], sheet_name: str, codes: set[str]) -> None: """按阻断原因归类 Sheet。""" sheet = workbook.create_sheet(sheet_name) - sheet.append(["Invoice", "来源", "料号", "收料数量", "外部系统 数量", "原因"]) + sheet.append(["Invoice", "来源", "料号", "异动数量", "外部系统 数量", "原因"]) for item in items: if (item.result_code or "") in codes or item.status in codes: sheet.append([ item.invoice_no, item.source_code, item.material_no, - item.receipt_quantity, item.external_quantity or "", + item.movement_quantity, item.external_quantity or "", item.result_message or item.result_code or item.status, ]) diff --git a/backend/app/services/in_transit_transfer/execution_service.py b/backend/app/services/in_transit_transfer/execution_service.py index f742e47e..f45f143a 100644 --- a/backend/app/services/in_transit_transfer/execution_service.py +++ b/backend/app/services/in_transit_transfer/execution_service.py @@ -2,15 +2,20 @@ 用途:在途调拨执行服务(单据级重构 + D8 异步拆分):API 同步段 prepare_execution 只做门禁 + 建 queued Run + D1 五元组分组建单 + 一次入队;worker 段 - execute_run 二次门禁复核后逐单执行(final_only 判定 → 非 final_only 写前 + execute_run 逐单执行(final_only 判定 → 非 final_only 写前 库存复查(漂移行 fail-closed 移出本单)→ create_transfer(business_ref=doc_no 透传,调用日志按单号锚定)→ 六态落位); retrigger_document 是 result_unknown 单的唯一人工出口(D11)。 依赖:orchestrator、capability_client(TransferOrder/StockTarget)、quantity (classify_quantity_match)、document_id、contracts、audit、status、 - source_file_status、matching_service(门禁/scope/路由契约)、 - jobs.queue(TRANSFER_RUN 入队)、models。 -逻辑:防双单锚定「doc_no + submit_timestamp 终身成对复用」(D3/D7):提交时按 + matching_service(scope/路由契约)、jobs.queue(TRANSFER_RUN 入队)、models。 +逻辑:执行门禁只做存在性校验(行可执行 + 匹配未取消)。文件版本对账门禁 + (TRANSFER.FILE_CHANGED,API 侧整批拒绝 + worker 侧整 Run 落败)已于 + 2026-10-22 退役——入站抓取是部分导出,新文件不含旧行 ≠ 旧行失效,按 + 最新文件 sha 对账会错误卡死未处理行;写前安全由逐单执行的写前库存 + 复查(_recheck_stock_for_document,按实时 ERP 账面严格相等核对)承担, + 行级「文件已更新」徽标保留为纯提示(matching_service._item_dto)。 + 防双单锚定「doc_no + submit_timestamp 终身成对复用」(D3/D7):提交时按 五元组建单,同组存在失败单则复用其单号/时间戳全量重跑(doc.run_id 改指新 Run,现任归属语义),存在 result_unknown/executing 单则阻断新行 (group_order_unresolved);部分唯一索引竞态以 SAVEPOINT + 复用重查重试 @@ -37,6 +42,7 @@ from app.models import ( TransferDocument, TransferInvoiceItem, TransferMatching, + TransferMovementLedger, TransferRun, User, ) @@ -56,10 +62,8 @@ from app.services.in_transit_transfer.matching_service import ( RESULT_EXECUTABLE, RouteMapping, TransferDeps, - _item_evaluated_sha, - scope_item_query, + item_external_lot_no, ) -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.orchestrator import ( create_execution_run_for_items, @@ -68,7 +72,11 @@ from app.services.in_transit_transfer.orchestrator import ( # 单投影统一走公共序列化(Task 17 重构:serializers.serialize_order 为唯一契约源; # serializers 不再顶层引用本模块,无循环导入)。 from app.services.in_transit_transfer.serializers import serialize_order -from app.services.in_transit_transfer.source_file_status import resolve_source_file_status + +# [测试补丁锚点] 文件版本对账门禁已退役(2026-10-22),本模块不再消费此符号; +# 保留导入仅为存量测试替身(conftest.patch_source_file_status 等 monkeypatch) +# 的目标地址不变。新代码禁止再消费——门禁语义见 _gated_items docstring。 +from app.services.in_transit_transfer.source_file_status import resolve_source_file_status # noqa: F401 ITEM_EXECUTION_ERROR_RESULT = "item_execution_error" # D7① 附加守卫:同组存在未了结单时新行的阻断原因码。 @@ -122,19 +130,23 @@ def _item_result_of(item: TransferInvoiceItem) -> str: # --------------------------------------------------------------------------- def _gated_items(*, item_ids: list[int], deps: TransferDeps) -> list[TransferInvoiceItem]: - """执行两道门禁(顺序校验,命中即抛、后续不执行,fail-closed 零写入)。 + """执行存在性门禁(命中即抛、后续不执行,fail-closed 零写入)。 门禁: ① 存在且可执行:id 存在且 status == ready_to_execute,否则 - ValidationError(code="TRANSFER.EXECUTE_ITEMS_INVALID")。 - ② 文件版本对账:行评估版本戳(_item_evaluated_sha)≠ 来源最新可用文件 - sha(含来源无可用文件/行无版本戳)→ ValidationError(code="TRANSFER.FILE_CHANGED")。 + ValidationError(code="TRANSFER.EXECUTE_ITEMS_INVALID");所属匹配已 + 取消的行一并拒绝(防御性双保险,规格 §9)。 - [2026-09-25 TTL 退役] 原门禁②「行级新鲜度(updated_at 距 now 超过 - confirm_ttl_seconds → TRANSFER.ITEMS_STALE)」已删除:匹配 10 分钟后必被拒 - 是 2026-09-24 事故的死锁根因;TTL 降级为纯展示阈值(stale 徽标,见 - matching_service._item_dto),防错由本函数门禁②的文件版本对账 + worker - 写前库存复查(_execute_document 的 _recheck_stock_for_document)承担。 + [2026-09-25 TTL 退役] 原门禁「行级新鲜度(updated_at 距 now 超过 + confirm_ttl_seconds → TRANSFER.ITEMS_STALE)」删除:匹配 10 分钟后必被拒 + 是 2026-09-24 事故的死锁根因;TTL 降级为纯展示阈值(stale 徽标)。 + [2026-10-22 文件版本对账门禁退役] 原「行评估 sha ≠ 证据流最新可用文件 sha + → TRANSFER.FILE_CHANGED 整批拒绝」删除:入站抓取是**部分导出**——新文件 + 不含某行 ≠ 该行失效/已处理,按「最新文件 sha」对账会把大量未处理行错误 + 卡死(业务实测 557 行积压被卡)。证据变化的保护下沉两层:①行级「文件 + 已更新」徽标(file_current=false,仅提示不拦截,见 matching_service + _item_dto);②worker 写前库存复查(_recheck_stock_for_document)——按 + 实时 ERP 账面严格相等核对,数量/批号漂移的行在写前被行级阻断,不会错写。 Returns: 去重并保持首现顺序的可执行行列表。 @@ -151,34 +163,32 @@ def _gated_items(*, item_ids: list[int], deps: TransferDeps) -> list[TransferInv ).all() by_id = {row.id: row for row in rows} ready_status = status_machine.TransferStatus.READY_TO_EXECUTE.value + # [防御性双保险(规格 §9)] 所属匹配已取消的行不得执行:取消路径已把匹配 + # 名下 ready 行退役,此处按匹配状态再拒一次(防绕过取消路径的状态组合)。 + from app.models import TransferMatching as _Matching + + row_matching_ids = {row.matching_id for row in rows if row.matching_id is not None} + cancelled_matching_ids: set[int] = set() + if row_matching_ids: + cancelled_matching_ids = { + mid for (mid,) in ( + db.session.query(_Matching.id) + .filter(_Matching.id.in_(row_matching_ids), _Matching.status == "cancelled") + .all() + ) + } invalid = [ i for i in ordered_ids - if by_id.get(i) is None or by_id[i].status != ready_status + if by_id.get(i) is None + or by_id[i].status != ready_status + or by_id[i].matching_id in cancelled_matching_ids ] if invalid: raise ValidationError( "items not executable", code="TRANSFER.EXECUTE_ITEMS_INVALID", details={"invalid_item_ids": invalid}, ) - items = [by_id[i] for i in ordered_ids] - - # [门禁②] 文件版本对账(按去重来源投影最新可用文件,行评估 sha 必须一致)。 - latest_files: dict[str, dict] = { - source_code: resolve_source_file_status(source_code=source_code) - for source_code in sorted({item.source_code for item in items}) - } - changed = [] - for item in items: - evaluated_sha = _item_evaluated_sha(item) - latest = latest_files.get(item.source_code) or {} - if not evaluated_sha or evaluated_sha != latest.get("file_sha256"): - changed.append(item.id) - if changed: - raise ValidationError( - "source receipt file changed since evaluation", code="TRANSFER.FILE_CHANGED", - details={"changed_item_ids": changed}, - ) - return items + return [by_id[i] for i in ordered_ids] def prepare_execution( @@ -197,7 +207,7 @@ def prepare_execution( 核心逻辑:[STEP 1] 两道门禁(见 _gated_items);[STEP 2] 建 queued Run 并关联 行(orchestrator);[STEP 3] 写前路由解析取 external_org,按 D1 五元组 - (external_org, source_code, receipt_date, from_warehouse, to_warehouse,全部 + (external_org, source_code, movement_date, from_warehouse, to_warehouse,全部 .strip() 规范化)分组建单(_ensure_document:新建/复用/阻断三分支); [STEP 4] TRANSFER_RUN {run_id, item_ids} 恰入队一次 → 返回 queued 摘要。 @@ -223,13 +233,13 @@ def prepare_execution( for item in items: route = deps.route_resolver.resolve( source_code=item.source_code, invoice_no=item.invoice_no, - warehouse_code=item.receipt_warehouse_code or "", + warehouse_code=item.movement_warehouse_code or "", ) org = str(route.external_org or "").strip() key = ( org, str(item.source_code or "").strip(), - str(item.receipt_date or "").strip(), + str(item.movement_date or "").strip(), str(item.from_warehouse or "").strip(), str(item.to_warehouse or "").strip(), ) @@ -302,7 +312,7 @@ def _ensure_document( ) -> tuple[TransferDocument | None, list[TransferInvoiceItem]]: """D7① 三分支组建单:同组无单新建 / 失败单复用 / result_unknown·executing 阻断。 - 组键 = D1 五元组(external_org, source_code, receipt_date, from_warehouse, + 组键 = D1 五元组(external_org, source_code, movement_date, from_warehouse, to_warehouse,全部 .strip() 规范化)。 分支语义: @@ -322,7 +332,7 @@ def _ensure_document( Returns: (单或 None, 处理后的 items)——分支③返回 (None, blocked items)。 """ - org, source_code, receipt_date, from_wh, to_wh = group_key + org, source_code, movement_date, from_wh, to_wh = group_key def _live() -> TransferDocument | None: """查同组未完结单(no_autoflush 防止半建对象提前落库干扰判定)。""" @@ -331,7 +341,7 @@ def _ensure_document( TransferDocument.query.filter( TransferDocument.source_code == source_code, TransferDocument.external_org == org, - TransferDocument.receipt_date == receipt_date, + TransferDocument.movement_date == movement_date, TransferDocument.from_warehouse == from_wh, TransferDocument.to_warehouse == to_wh, TransferDocument.status.in_(UNRESOLVED_DOC_STATUSES), @@ -347,7 +357,7 @@ def _ensure_document( # [分支①] 新建 pending 单(D2/D3 幂等锚一次生成终身复用)。 doc = TransferDocument( run_id=run.id, source_code=source_code, external_org=org, - receipt_date=receipt_date, from_warehouse=from_wh, to_warehouse=to_wh, + movement_date=movement_date, from_warehouse=from_wh, to_warehouse=to_wh, doc_no=next_document_no(org, sequence_loader=_sequence_loader), submit_timestamp=new_submit_timestamp(), status="pending", @@ -485,13 +495,12 @@ def execute_run( run.status = status_machine.TransferRunStatus.EXECUTING.value run.started_at = run.started_at or datetime.utcnow() db.session.flush() - if doc_id is None: - # [二次门禁] 文件 Hash 复核(fail-closed):失败则整 Run 落败,零外部写入。 - failure = _recheck_gates(run, deps) - if failure is not None: - _mark_recheck_failed(run, docs, failure) - db.session.commit() - return run.status + # [2026-10-22 文件版本对账门禁退役] 原 worker 二次门禁 _recheck_gates(文件 + # Hash 复核失败 → 整 Run technical_failed 零写入)随 API 侧门禁②一并退役: + # 入站抓取是部分导出,新文件不含旧行 ≠ 旧行失效,按最新文件 sha 对账会错误 + # 卡死未处理行。写前安全由逐单执行的写前库存复查(_execute_document 的 + # _recheck_stock_for_document)独立承担——按实时 ERP 账面严格相等核对, + # 数量/批号漂移的行在写前被行级阻断,不会错写。 # [逐单执行] 单间失败隔离:单单异常落 technical_failed,不影响其他单。 for doc in docs: try: @@ -513,62 +522,6 @@ def execute_run( return run.status -def _recheck_gates(run: TransferRun, deps: TransferDeps) -> tuple[str, str] | None: # noqa: ARG001 —— 本函数只做文件 Hash 门禁;库存写前复查在 _execute_document(_recheck_stock_for_document) - """worker 二次门禁复核(文件 Hash),返回 None 表示通过。 - - [2026-09-25 TTL 退役] 原新鲜度复核(updated_at 距 now 超过 - confirm_ttl_seconds → items_stale 整 Run 落败)已删除:worker 排队/等待 - 超 10 分钟即被拒是 2026-09-24 事故的死锁根因;TTL 降级为纯展示阈值 - (stale 徽标),写前安全由文件版本对账(本函数)+ 逐单执行的写前库存 - 复查(_recheck_stock_for_document)承担。 - - Args: - run: 执行 Run(其关联行即本次执行范围)。 - deps: 注入依赖(文件门禁不消费外部能力,仅为签名对称保留)。 - Returns: - None=通过;否则 (原因码, 原因消息)。 - """ - items = [ - item for item in run.items - if item.status in ( - status_machine.TransferStatus.EXECUTING.value, - status_machine.TransferStatus.READY_TO_EXECUTE.value, - ) - ] - latest_files: dict[str, dict] = { - source_code: resolve_source_file_status(source_code=source_code) - for source_code in sorted({item.source_code for item in items}) - } - for item in items: - evaluated_sha = _item_evaluated_sha(item) - latest = latest_files.get(item.source_code) or {} - if not evaluated_sha or evaluated_sha != latest.get("file_sha256"): - return ("file_changed", "source receipt file changed since evaluation") - return None - - -def _mark_recheck_failed(run: TransferRun, docs: list[TransferDocument], failure: tuple[str, str]) -> None: - """二次门禁失败落位(fail-closed):单 technical_failed、行阻断、Run failed。""" - code, message = failure - for doc in docs: - # [P2-1] pending(未起跑)与 executing(上次 worker 中途搁浅)统一落 - # technical_failed:零外部写入;stage 已成的单后续全量重跑由 stage SQL - # DELETE 同时间戳幂等兜底;落失败态使其可被 D18 关闭释放组锁,不留悬挂。 - if doc.status in ("pending", "executing"): - doc.status = "technical_failed" - doc.error_code = code - doc.error_message = message - blocked_status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value - for item in run.items: - if item.status not in _PROTECTED_ITEM_STATUSES and item.status != blocked_status: - item.status = blocked_status - item.result_code = code - item.result_message = message - run.status = status_machine.TransferRunStatus.FAILED.value - run.completed_at = run.completed_at or datetime.utcnow() - db.session.flush() - - # --------------------------------------------------------------------------- # 逐单执行(计划 [STEP 1-4] 伪码逐字落实) # --------------------------------------------------------------------------- @@ -584,7 +537,7 @@ def _recheck_stock_for_document( 【为什么】TTL 门禁退役(2026-09-25)后写前安全的最后防线:匹配到 worker 执行 之间存在时间窗,账面可能已被其他业务挪用/清零;在 create_transfer 之前按 - 「收料数量 == 账面」严格相等再裁一次,防止对错误数量建单。 + 「异动数量 == 账面」严格相等再裁一次,防止对错误数量建单。 【为什么不复查 final_only】result_unknown/executing 续跑(final_only=True)单 可能已在 ERP 建成,D7② 只触发末步——此时任何阻断都是假失败,故调用方保证 final_only 路径不进入本函数。 @@ -606,18 +559,18 @@ def _recheck_stock_for_document( """ grouped: dict[str, list[tuple[TransferInvoiceItem, RouteMapping]]] = {} for item in items: - route = deps.route_resolver.resolve( - source_code=item.source_code, invoice_no=item.invoice_no, - warehouse_code=item.receipt_warehouse_code or "", - ) + # [外部形态 + 仓库定义] 行级路由解析叠加行所属匹配类型的仓库定义 + # (fixed 覆盖映射档);批号经匹配快照转换规则派生(与匹配/重查同一口径)。 + from app.services.in_transit_transfer.retry_service import _route_for_item + + route = _route_for_item(deps, item) grouped.setdefault(str(route.external_org or "").strip(), []).append((item, route)) kept: list[TransferInvoiceItem] = [] for external_org, entries in grouped.items(): - # [外部形态] 写前复查与匹配/重查同一批号派生口径(movement_contract.external_lot_no)。 targets = [ StockTarget( material_no=item.material_no, warehouse_code=route.from_warehouse, - lot_no=external_lot_no(item.lot_no), + lot_no=item_external_lot_no(item), ) for item, route in entries ] @@ -632,7 +585,7 @@ def _recheck_stock_for_document( for item, route in entries: row = stock.lookup_row( material_no=item.material_no, - warehouse_code=route.from_warehouse, lot_no=external_lot_no(item.lot_no), + warehouse_code=route.from_warehouse, lot_no=item_external_lot_no(item), ) # [库存查得时刻] 写前复查是真实取数:无论查无/漂移/通过,随后落定的 # external_quantity 都以本次取数为准(stale 判定时钟,见 _item_dto)。 @@ -644,7 +597,7 @@ def _recheck_stock_for_document( item.result_message = "external inventory not found (write recheck)" item.external_quantity = "0" continue - if classify_quantity_match(Decimal(item.receipt_quantity), row.quantity) != RESULT_EXECUTABLE: + if classify_quantity_match(Decimal(item.movement_quantity), row.quantity) != RESULT_EXECUTABLE: # 数量漂移:原位刷新最新账面并移出本单(fail-closed,不写 ERP)。 item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value item.result_code = "blocked_quantity_mismatch" @@ -695,7 +648,7 @@ def _execute_document( continue # 人工关闭/取消行不复活(D18 语义:人工决定不被自动覆盖)。 route = deps.route_resolver.resolve( source_code=item.source_code, invoice_no=item.invoice_no, - warehouse_code=item.receipt_warehouse_code or "", + warehouse_code=item.movement_warehouse_code or "", ) if ( route.from_warehouse != item.from_warehouse @@ -746,8 +699,8 @@ def _execute_document( external_org=doc.external_org, doc_no=doc.doc_no, submit_timestamp=doc.submit_timestamp, - # D1:制单日期(gls_cm06)必须等于组收料日期;过账日期=执行当天业务日。 - doc_date=doc.receipt_date, + # D1:制单日期(gls_cm06)必须等于组异动日期;过账日期=执行当天业务日。 + doc_date=doc.movement_date, posting_date=str(business_date_now()), from_warehouse=doc.from_warehouse, to_warehouse=doc.to_warehouse, @@ -861,12 +814,12 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]: """ grouped: dict[tuple[str, str, str, str], list[TransferInvoiceItem]] = {} for item in items: - # [外部形态] 聚合键批号按 WTP→HOW 派生(movement_contract.external_lot_no): - # ERP 行粒度=外部批号身份,同一 ERP 批次不得因 WMS 前缀形态差异拆行; - # 行下传 lot_no(key[1])随键即为外部形态。 + # [外部形态] 聚合键批号经行所属匹配快照转换规则派生(类型配置驱动, + # 如 WTP→HOW):ERP 行粒度=外部批号身份,同一 ERP 批次不得因 WMS 前缀 + # 形态差异拆行;行下传 lot_no(key[1])随键即为外部形态,行落库保持原值。 key = ( str(item.material_no or "").strip(), - external_lot_no(item.lot_no), + item_external_lot_no(item), str(item.from_warehouse or "").strip(), str(item.to_warehouse or "").strip(), ) @@ -874,7 +827,7 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]: lines: list[dict] = [] for index, key in enumerate(sorted(grouped), start=1): group = grouped[key] - total = sum((Decimal(item.receipt_quantity) for item in group), Decimal("0")) + total = sum((Decimal(item.movement_quantity) for item in group), Decimal("0")) quantity = total.quantize(_QUANTITY_QUANT) unit = next((str(item.unit or "").strip() for item in group if str(item.unit or "").strip()), "") invoices = ",".join(sorted({item.invoice_no for item in group})) @@ -922,15 +875,47 @@ def _order_snapshot(*, run_no: str, order: TransferOrder, final_only: bool, line } +def _seal_ledger_records(items: list[TransferInvoiceItem], *, executed_doc_no: str | None) -> None: + """档级封存回写(规格 §9 防二次执行的档级兜底)。 + + 【AI 触发时机】仅 _apply_result 的 success/duplicate_success 分支调用——票据 + 执行成功落 ERP 单号时,把单内行关联的档记录置 transfer_executed=true + + executed_doc_no。失败/未知态不得调用(执行未成事实,记录仍可被圈定、 + 仍应可见于待匹配桶)。幂等:等值重复回写无副作用(封存位布尔语义,首次/ + 末次等效,复用单 duplicate_success 重跑恒封存);行无档关联(遗留行)跳过。 + 回写只 flush 不 commit(随调用方事务,与六态落位同生命周期)。 + + Args: + items: 本单(或遗留单行路径)参与落位的行集。 + executed_doc_no: 回写单号(ERP 单号优先,缺失回退平台单号;为空直接跳过)。 + """ + if not executed_doc_no: + return + record_ids = {item.ledger_record_id for item in items if item.ledger_record_id is not None} + if not record_ids: + return + records = ( + db.session.query(TransferMovementLedger) + .filter(TransferMovementLedger.id.in_(record_ids)) + .all() + ) + for record in records: + record.transfer_executed = True + record.executed_doc_no = executed_doc_no + db.session.flush() + + def _apply_result(*, doc: TransferDocument | None, items: list[TransferInvoiceItem], attempt: TransferAttempt, result: Any) -> None: """按写结果六态落位单、行与 Attempt(result_unknown 为终态,禁止自动重试)。 六态落位(D7②/D11): - - success / duplicate_success → 单与行推进成功族 + ERP 单号一致。 + - success / duplicate_success → 单与行推进成功族 + ERP 单号一致; + 并档级封存回写(_seal_ledger_records:items 关联档记录 + transfer_executed=true + executed_doc_no,规格 §9 防二次执行)。 - result_unknown → 单/行 result_unknown 终态(唯一出口 = 人工 retrigger)。 - business_failed / technical_failed → 行 blocked_recoverable (R6 裁决后非末步超时/失败已由引擎归 technical_failed),单保留失败态 - 待人工关闭(D18)或复用重跑(D7①②)。 + 待人工关闭(D18)或复用重跑(D7①②);档记录不封存(未成事实)。 """ attempt.response_summary_json = { "status": result.status, @@ -950,6 +935,14 @@ def _apply_result(*, doc: TransferDocument | None, items: list[TransferInvoiceIt item.external_document_no = result.document_no item.result_code = None item.result_message = None + # [档级封存回写(规格 §9)] 票据成功落 ERP 单号即封存其档记录: + # 防同一外部入站记录经新匹配二次执行;圈档/待匹配桶/队列的固定条件 + # transfer_executed=false 恒排除已封存记录。幂等等值覆盖(复用单重跑恒封存)。 + _seal_ledger_records( + items, + executed_doc_no=str(result.document_no or "").strip() + or (doc.doc_no if doc is not None else None), + ) attempt.status = "success" elif result.status == "result_unknown": for item in items: @@ -1116,7 +1109,7 @@ def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, r # [遗留兜底] 路由复查 → 单行临时单 → 写 Attempt → 调用 → 行级六态落位。 route = deps.route_resolver.resolve( source_code=item.source_code, invoice_no=item.invoice_no, - warehouse_code=item.receipt_warehouse_code or "", + warehouse_code=item.movement_warehouse_code or "", ) if route.from_warehouse != item.from_warehouse or route.to_warehouse != item.to_warehouse: _mark_recheck_blocked(item, "matching_expired", "route mapping changed since matching") @@ -1126,7 +1119,7 @@ def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, r external_org=str(route.external_org or "").strip(), doc_no=f"LEGACY-{item.id}", submit_timestamp=new_submit_timestamp(), - doc_date=item.receipt_date or "", + doc_date=item.movement_date or "", posting_date=str(business_date_now()), from_warehouse=item.from_warehouse, to_warehouse=item.to_warehouse, @@ -1204,10 +1197,10 @@ def execute_matching_items( actor_id: int | None = None, request_id: str | None = None, ) -> ExecuteOutcome: - """按匹配 scope 圈定 ready 行并按单执行(chat action / 自动排程共用入口)。 + """按匹配自有 items 圈定 ready 行并按单执行(chat action / 自动排程共用入口)。 - 行归属与匹配解耦(原地刷新)后,"这份匹配覆盖哪些行"由 scope 重新圈定 - (scope_item_query:来源 + 收料日期区间 + 调拨类型前缀);本入口按 scope 取 + 【出生翻转】行由匹配创建时从档圈定且创建即绑定(matching_id),"这份匹配 + 覆盖哪些行"=自有 items(scope_item_query 实时圈行已退役);本入口按匹配取 ready_to_execute 行(可选 invoice_nos 过滤)后委托 execute_items 执行, 两道门禁与单据级组建单由 execute_items/prepare_execution 统一裁定。 @@ -1222,8 +1215,11 @@ def execute_matching_items( raise NotFoundError("matching not found", code="TRANSFER.MATCH_NOT_FOUND") ready_status = status_machine.TransferStatus.READY_TO_EXECUTE.value ready_rows = ( - scope_item_query(matching) - .filter(TransferInvoiceItem.status == ready_status) + TransferInvoiceItem.query + .filter( + TransferInvoiceItem.matching_id == matching.id, + TransferInvoiceItem.status == ready_status, + ) .order_by(TransferInvoiceItem.id.asc()) .all() ) @@ -1277,15 +1273,15 @@ def _build_run_result(run: TransferRun) -> RunResultDTO: material_name=item.material_name, specification=item.specification, invoice_no=item.invoice_no, - receipt_date=item.receipt_date, + movement_date=item.movement_date, from_warehouse=item.from_warehouse, from_quantity=Decimal(item.external_quantity) if item.external_quantity else None, to_warehouse=item.to_warehouse, - to_quantity=Decimal(item.receipt_quantity), + to_quantity=Decimal(item.movement_quantity), result=result, reason=item.result_message or "", external_document_no=item.external_document_no, - receipt_warehouse_code=item.receipt_warehouse_code or "", + movement_warehouse_code=item.movement_warehouse_code or "", # T7 交接补齐:交易单位原值透传(执行结果视图 unit 不再恒空,计划 D4)。 unit=str(item.unit or ""), )) @@ -1305,7 +1301,7 @@ def _build_run_result(run: TransferRun) -> RunResultDTO: reason=result, # 行级人话原因(阻断单号等),前端优先展示、状态码标签兜底。 message=str(item.result_message or "").strip(), - facts=f"收料 {item.receipt_quantity}" + (f" / 外部系统 {item.external_quantity}" if item.external_quantity else ""), + facts=f"异动 {item.movement_quantity}" + (f" / 外部系统 {item.external_quantity}" if item.external_quantity else ""), )) return RunResultDTO( run_no=run.run_no, @@ -1363,7 +1359,7 @@ def serialize_run_orders(run: TransferRun) -> list[dict[str, Any]]: (D9,无独立进度卡);逐单亮 ERP 单号与状态徽标。 核心逻辑:[STEP 1] 按 run_id 取单(复用单 run_id 指现任 Run,投影不丢), - 展示序对齐可调拨明细/待处理池口径(2026-09-29 统一):收料日期 → 数据源 → + 展示序对齐可调拨明细/待处理池口径(2026-09-29 统一):异动日期 → 数据源 → 拨出/拨入库位升序,created_at/id 兜底稳定排序(跨数据源不再按建单序出现 日期乱序);[STEP 2] 每单行集取自单挂接行(document_id → items,复用单新旧行全量),按 ERP 行粒度(物料+批号+拨出/拨入库位,与 @@ -1375,7 +1371,7 @@ 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, + [{doc_no, movement_date, from_warehouse, to_warehouse, status, erp_document_no, error_message, lines: [{invoice_no, material_no, material_name, lot_no, quantity(6 位小数字符串), unit, reason}]}]。 行 reason 契约(框线图失败行原因展示,偏离 Task 11 五键字面属控制器裁决): @@ -1387,7 +1383,7 @@ def serialize_run_orders(run: TransferRun) -> list[dict[str, Any]]: docs = ( TransferDocument.query.filter_by(run_id=run.id) .order_by( - TransferDocument.receipt_date.asc(), + TransferDocument.movement_date.asc(), TransferDocument.source_code.asc(), TransferDocument.from_warehouse.asc(), TransferDocument.to_warehouse.asc(), diff --git a/backend/app/services/in_transit_transfer/field_transforms.py b/backend/app/services/in_transit_transfer/field_transforms.py new file mode 100644 index 00000000..5abf5b46 --- /dev/null +++ b/backend/app/services/in_transit_transfer/field_transforms.py @@ -0,0 +1,87 @@ +"""services/in_transit_transfer/field_transforms.py + +用途:调拨类型字段转换规则引擎——「外部系统值→ERP 值」的受控派生 + (一期仅 lot_no 前缀替换),只在系统边界生效;行与档保持文件原值。 +依赖:app.core.errors.ValidationError。 +逻辑:parse 校验白名单 → TransformRule 元组;apply 按序链式派生(未命中恒等)。 + 【AI 触发时机】任何把行上字段值发往外部系统或按派生值聚合/展示的场景 + (库存查询 targets、写前复查、建单单行、票行聚合键、前端批号展示), + 必须经本引擎按当前匹配快照的规则求值;禁止直接调用硬编码前缀转换。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Sequence + +from app.core.errors import ValidationError + +# 受控字段/转换方式词表(封闭可扩展;新增须同步管理页下拉与 technical.md)。 +TRANSFORM_FIELDS: frozenset[str] = frozenset({"lot_no"}) +TRANSFORM_OPS: frozenset[str] = frozenset({"prefix_replace"}) + + +@dataclass(frozen=True) +class TransformRule: + """单条转换规则:field 字段 / op 转换方式 / source 原前缀 / target 新前缀。""" + + field: str + op: str + source: str + target: str + + +def parse_transform_rules(raw: list[dict] | None) -> tuple[TransformRule, ...]: + """校验并解析转换规则 JSON;空列表/None = 恒等(无转换)。 + + Args: + raw: [{"field", "op", "source", "target"}],来自调拨类型配置 JSON; + 空列表/None 合法(= 该类型不做字段转换)。 + Returns: + TransformRule 元组(source/target 统一大写,保证匹配口径一致)。 + Raises: + ValidationError: field 不在 TRANSFORM_FIELDS、op 不在 TRANSFORM_OPS、 + 或 source/target 为空(code=TRANSFER.TRANSFORM_RULE_INVALID)。 + """ + rules: list[TransformRule] = [] + for item in raw or []: + field, op = str(item.get("field", "")), str(item.get("op", "")) + source, target = str(item.get("source", "")), str(item.get("target", "")) + if field not in TRANSFORM_FIELDS or op not in TRANSFORM_OPS or not source or not target: + raise ValidationError( + f"invalid transform rule: {field}/{op}", code="TRANSFER.TRANSFORM_RULE_INVALID", + details={"field": field, "op": op}, + ) + rules.append(TransformRule(field=field, op=op, source=source.upper(), target=target.upper())) + return tuple(rules) + + +def apply_field_transforms(field: str, value: str | None, rules: Sequence[TransformRule]) -> str | None: + """按规则序链式派生;未命中规则恒等返回原值(None/空串透传)。 + + Args: + field: 行字段名(仅 TRANSFORM_FIELDS 内的字段会被规则命中)。 + value: 该字段当前原值(来自行/档,永不被本函数改写——只返回新值)。 + rules: parse_transform_rules 产出的规则元组,按配置序链式生效。 + Returns: + 派生后的新值;None 与空串原样透传(不做前缀替换)。 + """ + result = value + for rule in rules: + if rule.field != field or not result: + continue + if rule.op == "prefix_replace" and result.upper().startswith(rule.source): + result = rule.target + result[len(rule.source):] + return result + + +def transform_rules_note(rules: Sequence[TransformRule]) -> str: + """转换规则审计说明。 + + Args: + rules: parse_transform_rules 产出的规则元组。 + Returns: + 如 "lot_no prefix_replace WTP->HOW THEN lot_no prefix_replace HOW->HOWX" + 的人读字符串(空规则返回空串),供审计日志/详情页展示。 + """ + return " THEN ".join(f"{r.field} {r.op} {r.source}->{r.target}" for r in rules) diff --git a/backend/app/services/in_transit_transfer/file_parser.py b/backend/app/services/in_transit_transfer/file_parser.py index dfffd6ec..9fdd8fb1 100644 --- a/backend/app/services/in_transit_transfer/file_parser.py +++ b/backend/app/services/in_transit_transfer/file_parser.py @@ -1,9 +1,12 @@ -"""在途调拨收料文件字段/结构校验。 +"""在途调拨异动文件字段/结构校验。 -用途:校验收料文件必填列(Invoice No/料号/收料日期/收料数量)、数量与日期合法性、 - 来源身份一致性,输出 ParsedReceiptRow 供 Invoice 汇总。 -依赖:app.core.errors.AppError、date_policy.parse_date、quantity.validate_receipt_quantity。 -逻辑:任何必填缺失或非法值整行阻断并携带行号细节;本模块不接触文件存储。 +用途:校验异动文件必填列(单号/异动日期/异动数量;料号为空的行静默跳过)、 + 数量与日期合法性、来源身份一致性,输出 ParsedMovementRow 供 Invoice 汇总。 +依赖:app.core.errors.AppError、date_policy.parse_date、quantity.validate_inbound_quantity。 +逻辑:必填缺失或非法值整行阻断并携带行号细节;料号空行跳过不管控不落档 + (2026-10-21 CRANE/Lognet 出站报告实测);本模块不接触文件存储。 + tt14 入站化后统一走 movement 契约字段(parse_movement_rows 单一入口, + 旧字段投影链路已并入,无兼容层)。 """ from __future__ import annotations @@ -16,14 +19,11 @@ from typing import Any, Iterable, Mapping from app.core.errors import AppError from app.services.in_transit_transfer.contracts import TRANSFER_FILE_SCHEMA_INVALID from app.services.in_transit_transfer.date_policy import parse_date -from app.services.in_transit_transfer.quantity import QuantityValidationError, validate_receipt_quantity - -REQUIRED_FIELDS = ("sheet", "row_no", "invoice_no", "material_no", "receipt_date", "receipt_quantity") - +from app.services.in_transit_transfer.quantity import QuantityValidationError, validate_inbound_quantity @dataclass(frozen=True) -class ParsedReceiptRow: - """单行已校验收料记录。""" +class ParsedMovementRow: + """单行已校验异动记录。""" source_code: str sheet: str @@ -32,20 +32,21 @@ class ParsedReceiptRow: material_no: str material_name: str specification: str - receipt_date: date - receipt_quantity: Decimal + # 异动日期/异动数量(tt14 入站化:明细方向中立,与异动档 movement_date 对齐)。 + movement_date: date + movement_quantity: Decimal lot_no: str = "" - # 收料文件「仓库」列原值(movement 契约 warehouse_code):inventory_match 源映射行匹配键。 + # 来源文件「仓库」列原值(movement 契约 warehouse_code):inventory_match 源映射行匹配键。 warehouse_code: str = "" # 交易单位列原值(movement 契约第 11 字段 unit,计划 D4):仅 trim 空白、 # 不做单位换算/清洗;空值不产生解析失败,由匹配阶段行级 blocked_missing_unit 阻断。 unit: str = "" -class ReceiptFileSchemaError(AppError): - """收料文件结构/字段校验失败(整行阻断)。""" +class MovementFileSchemaError(AppError): + """异动文件结构/字段校验失败(整行阻断)。""" - def __init__(self, message: str = "receipt file schema invalid", *, rows: list[dict[str, Any]] | None = None): + def __init__(self, message: str = "movement file schema invalid", *, rows: list[dict[str, Any]] | None = None): super().__init__( code=TRANSFER_FILE_SCHEMA_INVALID, message=message, @@ -59,48 +60,52 @@ def _fail(rows: list[dict[str, Any]], *, row_no: Any, reason: str) -> None: rows.append({"row_no": row_no, "reason": reason}) -def _is_unusable_receipt_row(date_value: Any, quantity_raw: Any) -> bool: - """判断是否为"非可用收料事实"的行:跳过,不参与匹配,也不阻断整文件。 +def _is_unusable_movement_row(date_value: Any, quantity_raw: Any) -> bool: + """判断是否为"非可用异动事实"的行:跳过,不参与匹配,也不阻断整文件。 - WMS 异动报告会携带三类非可用收料行,均不是可用的收料事实: - ① 未收料在途 ASN(Date Received 空、Qty Received 0); - ② 收料执行中(ASN Status=Executing,Qty Received 已计数但收料日期未盖章); - ③ 零数量收料行(Date Received 已盖章但 Qty Received = 0;2026-10-08 CRANE + WMS 异动报告会携带三类非可用异动行,均不是可用的异动事实: + ① 未收货在途 ASN(Date Received 空、Qty Received 0); + ② 收货执行中(ASN Status=Executing,Qty Received 已计数但收货日期未盖章); + ③ 零数量异动行(Date Received 已盖章但 Qty Received = 0;2026-10-08 CRANE WTP26082227 实测——扫码收货数量记在他行/收货取消的占位行)。 - 收料日期与正数量是行级匹配身份与成熟过滤的必要字段;此类行跳过后由下次排程 + 异动日期与正数量是行级匹配身份与日期圈定的必要字段;此类行跳过后由下次排程 抓取补齐(WMS 补数量/盖章后自然带出),不得整文件阻断。 """ if not (isinstance(date_value, (date, datetime)) or str(date_value or "").strip()): return True try: - # 只跳过恰好为 0 的零收料行;负数属数据损坏,交由 validate_receipt_quantity 阻断。 + # 只跳过恰好为 0 的零异动行;负数属数据损坏,交由 validate_inbound_quantity 阻断。 return Decimal(str(quantity_raw)) == 0 except (InvalidOperation, ValueError, TypeError): - # 数量缺失/空:日期已盖章但无数量,同为零收料家族;非数字垃圾交由 - # validate_receipt_quantity 按非法数量阻断,不在此吞掉。 + # 数量缺失/空:日期已盖章但无数量,同为零异动家族;非数字垃圾交由 + # validate_inbound_quantity 按非法数量阻断,不在此吞掉。 return not str(quantity_raw or "").strip() -def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]: +def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedMovementRow]: """把通用异动/移动字段(doc_no/line_no/in_out_flag/material_code/...)映射为调拨解析行。 字段契约(领域定死)见 movement_contract.MOVEMENT_FIELDS;映射关系: doc_no → invoice_no(幂等/汇总键) - quantity → receipt_quantity(严格数量匹配) - movement_date → receipt_date(成熟过滤) + quantity → movement_quantity(严格数量匹配) + movement_date → movement_date(日期圈定;tt14 入站化后明细侧同名对齐) 其余字段(material_code→material_no、material_name、doc_no)透传/展示保留; - warehouse_code 透传至 ParsedReceiptRow.warehouse_code(inventory_match 源路由匹配键); - unit 原值透传至 ParsedReceiptRow.unit(movement 契约第 11 字段,仅 trim, + warehouse_code 透传至 ParsedMovementRow.warehouse_code(inventory_match 源路由匹配键); + unit 原值透传至 ParsedMovementRow.unit(movement 契约第 11 字段,仅 trim, 空值不阻断解析——行级 missing_unit 阻断在匹配阶段); - storage_code 仍仅展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。 + external_doc_no/external_line_no(2026-10-21 扩展:外部单号/外部项次)经原始行 + 透传至落档组装(_assemble_ledger_rows 从原始行取扩展字段,解析行不设槽位), + 作为异动档自然键成分承担档幂等主键管控; + storage_code 仍仅展示保留。旧字段名投影链路(tt14 前的直连列名解析)已并入 + 本函数(入站化,无兼容层),校验逻辑一致。 Args: source_code: 任务来源实例(行内来源身份一致性校验)。 rows: 通用异动原始行 dict。 Returns: - 已校验的 ParsedReceiptRow 列表。 + 已校验的 ParsedMovementRow 列表。 Raises: - ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。 + MovementFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。 """ return _parse_rows( source_code=source_code, @@ -108,31 +113,8 @@ def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) projection={ "invoice_no": "doc_no", "material_no": "material_code", - "receipt_quantity": "quantity", - "receipt_date": "movement_date", - }, - ) - - -def parse_receipt_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]: - """校验并解析收料文件行。 - - Args: - source_code: 任务来源实例(用于校验行内来源身份一致性)。 - rows: 原始文件行 dict。 - Returns: - 已校验的 ParsedReceiptRow 列表。 - Raises: - ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。 - """ - return _parse_rows( - source_code=source_code, - rows=rows, - projection={ - "invoice_no": "invoice_no", - "material_no": "material_no", - "receipt_quantity": "receipt_quantity", - "receipt_date": "receipt_date", + "movement_quantity": "quantity", + "movement_date": "movement_date", }, ) @@ -142,61 +124,64 @@ def _parse_rows( source_code: str, rows: Iterable[Mapping[str, Any]], projection: Mapping[str, str], -) -> list[ParsedReceiptRow]: +) -> list[ParsedMovementRow]: """按字段名投影校验并解析原始行。 Args: source_code: 任务来源实例(行内来源身份一致性校验)。 rows: 原始文件行 dict。 - projection: 调拨语义字段(invoice_no/material_no/receipt_quantity/receipt_date) + projection: 调拨语义字段(invoice_no/material_no/movement_quantity/movement_date) 到原始行字段名的映射(如 {invoice_no: doc_no})。 Returns: - 已校验的 ParsedReceiptRow 列表("无异动日期"的在途/执行中行已跳过)。 + 已校验的 ParsedMovementRow 列表("无异动日期"的在途/执行中行已跳过)。 Raises: - ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。 + MovementFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。 """ invoice_key = str(projection.get("invoice_no") or "invoice_no") material_key = str(projection.get("material_no") or "material_no") - quantity_key = str(projection.get("receipt_quantity") or "receipt_quantity") - date_key = str(projection.get("receipt_date") or "receipt_date") + quantity_key = str(projection.get("movement_quantity") or "movement_quantity") + date_key = str(projection.get("movement_date") or "movement_date") errors: list[dict[str, Any]] = [] - parsed: list[ParsedReceiptRow] = [] + parsed: list[ParsedMovementRow] = [] for raw in rows: row = raw if isinstance(raw, Mapping) else {} row_no = row.get("row_no") invoice_no = str(row.get(invoice_key) or "").strip() material_no = str(row.get(material_key) or "").strip() sheet = str(row.get("sheet") or "").strip() - receipt_date_value = row.get(date_key) + movement_date_value = row.get(date_key) quantity_raw = row.get(quantity_key) if not sheet or not row_no: _fail(errors, row_no=row_no, reason="missing_sheet_or_row_no") continue + if not material_no: + # [料号空行跳过 2026-10-21] 料号为空=非可用异动行(CRANE/Lognet 出站 + # 报告的说明行/占位行实测):不做必填管控、不进异动表,静默跳过—— + # 与 _is_unusable_movement_row 同家族(跳过不阻断整文件)。其余必填 + #(单号)管控不变,仅对有料号的行生效。 + continue if not invoice_no: _fail(errors, row_no=row_no, reason="missing_invoice_no") continue - if not material_no: - _fail(errors, row_no=row_no, reason="missing_material_no") - continue row_source = str(row.get("source_code") or "").strip() if row_source and row_source.upper() != str(source_code).upper(): _fail(errors, row_no=row_no, reason=f"source_identity_mismatch: {row_source}") continue - if _is_unusable_receipt_row(receipt_date_value, quantity_raw): + if _is_unusable_movement_row(movement_date_value, quantity_raw): continue try: - receipt_date = parse_date(receipt_date_value) + movement_date = parse_date(movement_date_value) except ValueError: - _fail(errors, row_no=row_no, reason=f"invalid_receipt_date: {receipt_date_value!r}") + _fail(errors, row_no=row_no, reason=f"invalid_movement_date: {movement_date_value!r}") continue try: - quantity = validate_receipt_quantity(quantity_raw) + quantity = validate_inbound_quantity(quantity_raw) except QuantityValidationError as exc: _fail(errors, row_no=row_no, reason=str(exc)) continue - parsed.append(ParsedReceiptRow( + parsed.append(ParsedMovementRow( source_code=str(source_code), sheet=sheet, row_no=int(row_no), @@ -204,8 +189,8 @@ def _parse_rows( material_no=material_no, material_name=str(row.get("material_name") or "").strip(), specification=str(row.get("specification") or "").strip(), - receipt_date=receipt_date, - receipt_quantity=quantity, + movement_date=movement_date, + movement_quantity=quantity, lot_no=str(row.get("lot_no") or "").strip(), warehouse_code=str(row.get("warehouse_code") or "").strip(), # unit 原值透传(movement 契约第 11 字段):仅 trim,空值解析放行。 @@ -215,5 +200,5 @@ def _parse_rows( # 诊断落库:消息携带前 3 条行级明细(行号+原因),随 parse_error_message # 落库自描述(2026-10-08 CRANE 零数量行事故:此前只有通用消息、无法定位)。 summary = '; '.join(f"row {r.get('row_no')}: {r.get('reason')}" for r in errors[:3]) - raise ReceiptFileSchemaError(f"receipt file schema invalid: {summary}", rows=errors) + raise MovementFileSchemaError(f"movement file schema invalid: {summary}", rows=errors) return parsed diff --git a/backend/app/services/in_transit_transfer/file_preparation.py b/backend/app/services/in_transit_transfer/file_preparation.py index 61050c95..08984607 100644 --- a/backend/app/services/in_transit_transfer/file_preparation.py +++ b/backend/app/services/in_transit_transfer/file_preparation.py @@ -1,7 +1,8 @@ -"""在途调拨收料文件 Ready 复用与来源级 RPA 触发。 +"""在途调拨入站文件 Ready 复用与来源级 RPA 触发。 -用途:按 (source_code, business_date, purpose=receipt) 检查最新 ready 文件; - 存在则复用,不存在则按来源实例触发一次收料 RPA;存在活动 Source Job +用途:按 (source_code, business_date, 入站解析规则绑定) 检查最新 ready 文件; + 存在则复用,不存在则按来源实例触发一次入站 RPA(入站证据 = ShippingInboundReport RPA + 产物,shipping_notice 域术语保留);存在活动 Source Job 时绑定已有任务,保证并发请求只触发一次抓取。 依赖:typing.Protocol 依赖注入(文件仓库 / RPA 触发)。 逻辑:文件仓库与 RPA 触发均通过协议注入,测试使用 Fake 替身; @@ -19,8 +20,8 @@ STAGE_FAILED = "failed" @dataclass(frozen=True) -class ReadyReceiptFile: - """当日最新 ready 收料文件快照(含已提取行,供解析)。""" +class ReadyInboundFile: + """当日最新 ready 入站文件快照(含已提取行,供解析)。""" source_code: str business_date: str @@ -35,30 +36,30 @@ class FilePreparationResult: """来源级文件准备结果。""" stage: str - file: ReadyReceiptFile | None = None + file: ReadyInboundFile | None = None error_code: str | None = None error_message: str | None = None -class ReceiptFileRepository(Protocol): - """收料 ready 文件仓库协议。""" +class InboundFileRepository(Protocol): + """入站 ready 文件仓库协议。""" - def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None: + def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyInboundFile | None: """返回该来源当日最新 ready 文件;不存在返回 None。""" class RpaTrigger(Protocol): - """收料 RPA 触发协议(DBS/Crane 共用)。""" + """入站 RPA 触发协议(DBS/Crane 共用)。""" def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]: - """触发一次收料抓取,返回 {'ok': bool, 'callback_id'|'error_code': ...}。""" + """触发一次入站抓取,返回 {'ok': bool, 'callback_id'|'error_code': ...}。""" -def ensure_receipt_file_ready( +def ensure_inbound_file_ready( *, source_code: str, business_date: str, - repository: ReceiptFileRepository, + repository: InboundFileRepository, rpa_trigger: RpaTrigger, active_source_job_key: str | None = None, ) -> FilePreparationResult: diff --git a/backend/app/services/in_transit_transfer/receipt_callback_bridge.py b/backend/app/services/in_transit_transfer/inbound_callback_bridge.py similarity index 65% rename from backend/app/services/in_transit_transfer/receipt_callback_bridge.py rename to backend/app/services/in_transit_transfer/inbound_callback_bridge.py index 79d7ddc1..1afab2cc 100644 --- a/backend/app/services/in_transit_transfer/receipt_callback_bridge.py +++ b/backend/app/services/in_transit_transfer/inbound_callback_bridge.py @@ -1,10 +1,15 @@ -"""在途调拨收料回调桥。 +"""在途调拨入站回调桥。 -用途:货代收料 RPA 回调落文件后,按来源推进调拨等待中的 TransferSourceJob: +用途:货代入站 RPA(入站证据 = ShippingInboundReport RPA 产物,shipping_notice 域,术语保留) + 回调落文件后,按来源推进调拨等待中的 TransferSourceJob: success/有文件 → file_ready(绑定 file_no/sha256);failed/empty → failed。 依赖:models(TransferSourceJob)、datetime。 逻辑:只推进 status='waiting_rpa_callback' 的来源任务(门禁);无匹配则不动作, - 避免回调迟到误推进其他阶段任务。SourceJob 状态为字符串常量(见 models)。 + 避免回调迟到误推进其他阶段任务。生产调用方为调拨侧报表事实处理函数 + handle_inbound_report(Task 7,inbound_report_handler.py——归档终态 commit 后 + 经 dispatch_report_fact 调入;返回 None 时调用方跳过提交分支);回归测试桥 + (handle_inbound_report / 历史测试桥)仍走本函数。 + SourceJob 状态为字符串常量(见 models)。 """ from __future__ import annotations @@ -19,7 +24,7 @@ _WAITING_RPA_CALLBACK = 'waiting_rpa_callback' _FAILED = 'failed' -def advance_source_job_from_receipt_callback( +def advance_source_job_from_inbound_callback( *, source_code: str, file_no: str | None = None, file_sha256: str | None = None, callback_ok: bool = True, error_code: str | None = None, error_message: str | None = None, ) -> TransferSourceJob | None: @@ -27,8 +32,8 @@ def advance_source_job_from_receipt_callback( Args: source_code: 回调所属来源实例。 - file_no: 收料文件号(success 时)。 - file_sha256: 收料文件 sha256(success 时)。 + file_no: 入站文件号(success 时)。 + file_sha256: 入站文件 sha256(success 时)。 callback_ok / error_code / error_message: 回调终态。 Returns: 被推进的任务;无等待任务或已终态时返回 None。 @@ -50,25 +55,25 @@ def advance_source_job_from_receipt_callback( job.finished_at = datetime.utcnow() else: job.status = _FAILED - job.error_code = error_code or 'RPA_RECEIPT_CALLBACK_FAILED' - job.error_message = error_message or 'receipt rpa callback failed' + job.error_code = error_code or 'RPA_INBOUND_CALLBACK_FAILED' + job.error_message = error_message or 'inbound rpa callback failed' job.finished_at = datetime.utcnow() db.session.flush() return job def recover_stale_waiting_source_jobs() -> int: - """把超过收料回调超时仍 waiting_rpa_callback 的调拨来源任务回收为 failed。 + """把超过入站回调超时仍 waiting_rpa_callback 的调拨来源任务回收为 failed。 - 【AI 触发时机】:仅由排程队列周期扫描(queue_service)与收料超时回收同批调用; - 不自动重试 RPA——用户可在来源选择卡手动重试(与收料回收"绝不自动重试"口径一致)。 + 【AI 触发时机】:仅由排程队列周期扫描(queue_service)与入站超时回收同批调用; + 不自动重试 RPA——用户可在来源选择卡手动重试(与入站回收"绝不自动重试"口径一致)。 Returns: 本次回收的任务数。 """ from flask import current_app try: - timeout = max(60, int(current_app.config.get('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS', 900))) + timeout = max(60, int(current_app.config.get('FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS', 900))) except (TypeError, ValueError): timeout = 900 cutoff = datetime.utcnow() - timedelta(seconds=timeout) @@ -79,8 +84,8 @@ def recover_stale_waiting_source_jobs() -> int: ) for job in stale: job.status = _FAILED - job.error_code = 'RPA_RECEIPT_CALLBACK_TIMEOUT' - job.error_message = f'receipt rpa callback not received within {timeout}s' + job.error_code = 'RPA_INBOUND_CALLBACK_TIMEOUT' + job.error_message = f'inbound rpa callback not received within {timeout}s' job.finished_at = datetime.utcnow() if stale: db.session.commit() diff --git a/backend/app/services/in_transit_transfer/inbound_file_gate.py b/backend/app/services/in_transit_transfer/inbound_file_gate.py new file mode 100644 index 00000000..dc77c0dd --- /dev/null +++ b/backend/app/services/in_transit_transfer/inbound_file_gate.py @@ -0,0 +1,20 @@ +"""在途调拨入站归档文件的可用性门禁(口径唯一,语义归 freight_rpa.reports 维护)。 + +用途:把「一份入站归档文件是否可用于调拨链路」的判定收敛为 + freight_rpa/reports/queries 的权威实现,并向调拨域既有 import 路径 + (api 下载、历史消费方)透传,防止口径漂移。 +依赖:freight_rpa.reports.queries(usable / expired 过滤表达式的唯一权威)。 +逻辑:【阶段 B Task 4】本模块不再自带表达式实现,自身不 import 任何 + freight_rpa 报表模型;可用 = 未删除 + 当天(Asia/Shanghai 业务日)抓取 + + 未过保留期;已失效(expired)= 未删除 且 该核心不成立——两条件同核 + 推导,规则文本与业务日窗口换算见 queries.py(禁止反向 import 出现环)。 +""" + +from __future__ import annotations + +from app.services.freight_rpa.reports.queries import ( + expired_inbound_file_condition, + usable_inbound_file_condition, +) + +__all__ = ["expired_inbound_file_condition", "usable_inbound_file_condition"] \ No newline at end of file diff --git a/backend/app/services/in_transit_transfer/inbound_report_handler.py b/backend/app/services/in_transit_transfer/inbound_report_handler.py new file mode 100644 index 00000000..2b2d01f5 --- /dev/null +++ b/backend/app/services/in_transit_transfer/inbound_report_handler.py @@ -0,0 +1,134 @@ +""" +services/in_transit_transfer/inbound_report_handler.py + +用途:inbound 报表事实的调拨侧业务处理函数(阶段 B Task 7)——收料归档 + 终态 commit 后由 dispatch_report_fact 投递的 ReportFact 只在此推进 + 调拨自己的任务:TransferSourceJob 终态推进、调拨证据同步、收料排程收口。 +依赖:app.db、app.models(FreightRpaInboundUnitRun——执行单元读取;报表文件/ + 配置模型禁止在本包引用,边界由 test_inbound_report_read_boundary 锁定)、 + app.core.errors.ValidationError、freight_rpa.reports.facts(ReportFact / + require_report_kind——只消费事实契约,不 import freight_rpa 工作流)、 + in_transit_transfer.inbound_callback_bridge / evidence_sync(同包)。 +逻辑:由组合根(app.create_app → in_transit_transfer.rpa_sinks.register_inbound_sinks) + 注册为 'inbound' kind 处理函数;freight_rpa.inbound.report_archive. + ingest_inbound_callback 在每个终态 db.session.commit() 之后经 + dispatch_report_fact 调入本函数。处理函数只改调拨自己的行; + 【不捕获异常】——任何失败原样外抛,归档文件已提交不回滚, + Worker 重试整笔回调即可补齐推进(先 commit 再投递的顺序契约)。 +""" + +from __future__ import annotations + +from datetime import datetime + +from app import db +from app.core.errors import ValidationError +from app.models import FreightRpaInboundUnitRun +from app.services.freight_rpa.reports.facts import ReportFact, require_report_kind +from app.services.in_transit_transfer.inbound_callback_bridge import ( + advance_source_job_from_inbound_callback, +) + + +def handle_inbound_report(fact: ReportFact) -> None: + """report_kind 必须是 inbound。ok 且 file_id 有值时把等待中的 TransferSourceJob 推进到 file_ready; + ok 为假时推进到 failed。没有 waiting_rpa_callback 行则 return。第二次调用时该行已离开等待态,不再改。 + + (Task 7 契约 docstring 逐字保留如上;以下为补充说明。) + + 核心逻辑: + [STEP 1] kind 门禁(fail-closed);[STEP 2] 经桥推进等待中的来源任务(桥只改 + status='waiting_rpa_callback' 的行,无等待行返回 None——「没有等待行则 return」 + 指调拨侧无任务行可改,第二次投递时该行已离开等待态,桥天然不重复推进); + [STEP 3] 桥只 flush 不 commit,推进结果必须在此提交(B3 持久性);[STEP 4] + success 事实触发调拨证据同步(与拆分前终态收尾同口径:按 ok 触发、不依赖 + 等待任务存在——独立收料批次无调拨任务也须把最新可用文件镜像落档; + 桥内自吞异常并自行 commit,本处不包 try);[STEP 5] 精确定位「本次回调收尾的 + 执行单元」并回写收料排程进度、归集终态(finalize 函数住在 schedule 包—— + freight_rpa 禁止 import 它,只能由本处理函数调用;「仍由该处理函数调用」= 拆分 + 前每笔终态回调后的收口行为保持不变;Task 7 修复轮 2 起定位依据为 fact.unit_run_id + ——归档入口每次投递(含 failure/empty 与幂等重放)自单元行回填,success 与 + failure 同一机制,绝不按来源/错误文本猜「最新单元」)。 + 【不捕获异常】任何一步失败原样外抛供 Worker 重试。 + + Args: + fact: 终态已提交后由归档入口构造的报表事实(report_kind/source_code/ + file_id/sha256/ok/error_code/error_message)。 + Returns: + None(推进/同步/收口结果全部写库,不返回业务值)。 + Raises: + ValidationError: report_kind 非 inbound(误注册/误分发,fail-closed)。 + """ + # [STEP 1] kind 门禁:本函数只消费 inbound 事实(dispatch 已按 kind 路由, + # 此处防御性复核,防止误注册成其他 kind 的处理函数后静默错写调拨行)。 + kind = require_report_kind(fact.report_kind) + if kind != 'inbound': + raise ValidationError( + f"handle_inbound_report only accepts inbound facts, got: {kind!r}", + code='SHIPPING.INBOUND_CALLBACK_INVALID', + details={'report_kind': fact.report_kind}, + ) + + # [STEP 2] 推进等待中的调拨来源任务:ok 且 file_id 有值 → file_ready(绑定 + # 文件号/指纹);否则 → failed(带错误码/描述)。桥只改 waiting_rpa_callback 行; + # 无等待行返回 None(调拨侧无行可改,直接结束推进分支)。 + if fact.ok and fact.file_id is not None: + advanced = advance_source_job_from_inbound_callback( + source_code=fact.source_code, + file_no=str(fact.file_id), + file_sha256=fact.sha256, + callback_ok=True, + ) + else: + advanced = advance_source_job_from_inbound_callback( + source_code=fact.source_code, + callback_ok=False, + error_code=fact.error_code, + error_message=fact.error_message, + ) + + # [STEP 3] 桥只 flush 不 commit:推进落库必须在此提交,否则请求结束回滚会 + # 丢掉已推进的任务(B3 持久性——empty/failed 且后续收口提前返回时无人提交)。 + if advanced is not None: + db.session.commit() + + # [STEP 4] 证据同步:success 事实(ok 且 file_id 有值)后把该来源最新可用 + # 入站文件镜像落档。与拆分前终态收尾同口径(按 ok 触发、不依赖等待任务 + # 存在——独立收料批次没有调拨任务,但其文件仍是运行期取数的证据源)。 + # sync_and_commit_for_callback 桥内自吞异常并自行 commit;本处不包 try, + # 若有异常原样外抛(文件已提交,Worker 重试即可补齐落档)。 + if fact.ok and fact.file_id is not None: + from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback + + now = datetime.utcnow() + sync_and_commit_for_callback( + source_code=fact.source_code, + business_date=str(now.date()), + now=now, + ) + + # [STEP 5] 收料排程收口:精确定位「本次回调收尾的执行单元」的排程 run(Task 7 + # 修复轮 2——事实自带 unit_run_id(归档入口每次投递自单元行回填),不再按来源/ + # 错误文本猜单元:同来源、同错误文本的新单元存在时旧回调不得收口错误的 run)。 + schedule_run_id: int | None = None + if fact.unit_run_id is not None: + # 归档入口产线恒回填 unit_run_id;None 仅为兼容手工构造事实的旧调用方—— + # 无单元标识时不猜(跳过收口,不做任何「最新单元」式近似)。 + unit = db.session.get(FreightRpaInboundUnitRun, int(fact.unit_run_id)) + if unit is None: + # 分发紧跟终态 commit:单元行缺失属硬性不一致,fail-closed 而非静默跳过。 + from app.core.errors import NotFoundError + + raise NotFoundError( + f"Inbound RPA unit not found: {fact.unit_run_id}", + details={'unit_run_id': fact.unit_run_id}, + ) + schedule_run_id = unit.schedule_run_id + if schedule_run_id: + from app.services.schedule.freight_rpa_inbound_finalize import ( + finalize_inbound_schedule_run_if_complete, + refresh_inbound_schedule_run_progress, + ) + + refresh_inbound_schedule_run_progress(schedule_run_id) + finalize_inbound_schedule_run_if_complete(schedule_run_id) diff --git a/backend/app/services/in_transit_transfer/receipt_trigger_service.py b/backend/app/services/in_transit_transfer/inbound_trigger_service.py similarity index 63% rename from backend/app/services/in_transit_transfer/receipt_trigger_service.py rename to backend/app/services/in_transit_transfer/inbound_trigger_service.py index 6aba80a2..4a7b38af 100644 --- a/backend/app/services/in_transit_transfer/receipt_trigger_service.py +++ b/backend/app/services/in_transit_transfer/inbound_trigger_service.py @@ -1,15 +1,20 @@ -"""在途调拨真实收料 RPA 触发服务。 +"""在途调拨入站 RPA 触发服务。 -用途:为单个或多个来源触发收料/异动 RPA 抓取(复用货代收料 trigger 链路),不创建排程。 - 按来源取 ShippingInventorySource + ShippingReceiptReportConfig + rpa_profile, - 先落 ShippingReceiptRpaUnitRun(awaiting_rpa,回调按 callback_id 查库可达), - 再装配收料 trigger unit 并调用 write_receipt_export_batch_trigger 原子写 trigger。 -依赖:write_receipt_export_batch_trigger(默认 writer)、models、db。 -逻辑:list_receipt_capable_source_codes 供排程 source_codes 留空时的缺省范围; - 一源一单元,query_parameters 原样下发;来源停用/收料配置缺失/rpa_profile 缺失时 +用途:为单个或多个来源触发入站 RPA 抓取(入站证据 = freight_rpa 入站 RPA 产物, + 复用货代入站 trigger 链路),不创建排程。按来源取站点、入站配置与登录连接 + (全部经 freight_rpa.reports.queries 只读入口),先落 RPA 单元运行行 + (awaiting_rpa,回调按 callback_id 查库可达),再装配入站 trigger unit 并 + 调用 write_inbound_export_batch_trigger 原子写 trigger。 +依赖:write_inbound_export_batch_trigger(默认 writer,freight_rpa.inbound.trigger_io)、 + freight_rpa.reports.queries(get_site / get_inbound_config / get_rpa_login_profile / + list_inbound_configured_source_codes——站点、配置与登录连接读取唯一权威)、db。 +逻辑:list_inbound_capable_source_codes 供排程 source_codes 留空时的缺省范围; + 一源一单元,query_parameters 原样下发;来源停用/入站配置缺失/登录连接缺失时 fail-closed;写 trigger 失败把单元行标 failed 并 commit。 - trigger_receipt_rpa_batch(2026-10-09)把多来源合并为一个 batch trigger 文件: + trigger_inbound_rpa_batch(2026-10-09)把多来源合并为一个 batch trigger 文件: Worker 对单文件按 profile 分组共享一次浏览器会话,避免逐来源开/关浏览器。 + 【阶段 B Task 4】trigger unit 载荷键集与 Worker 契约(freight_rpa.inbound.v1) + 逐键不变;读取改走只读函数后不再引用 freight_rpa 报表模型。 """ from __future__ import annotations @@ -18,7 +23,17 @@ import uuid from datetime import datetime from typing import Any, Callable -from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger +from app.services.freight_rpa.inbound.trigger_io import ( + ACTION_INBOUND_EXPORT_BATCH, + SCHEMA, + write_inbound_export_batch_trigger, +) +from app.services.freight_rpa.reports.queries import ( + get_inbound_config, + get_rpa_login_profile, + get_site, + list_inbound_configured_source_codes, +) RouteTriggerWriter = Callable[..., str | None] @@ -26,41 +41,42 @@ 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 走页面默认。 + 【阶段 B Task 4】站点(get_site)/ 入站配置(get_inbound_config)/ 登录连接 + (get_rpa_login_profile)读取改经 freight_rpa.reports.queries 只读入口;装配出的 + unit 载荷键集与 Worker 契约逐键保持不变(快照含配置行主键与版本)。 """ - from app.models import ShippingInventorySource, ShippingReceiptReportConfig - - source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() - if source is None: + site = get_site(source_code) + if site is None or not site.enabled: raise RuntimeError(f'source not enabled: {source_code}') - config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first() + config = get_inbound_config(source_code) if config is None: - raise RuntimeError(f'receipt config missing: {source_code}') - profile = source.rpa_profile + raise RuntimeError(f'inbound config missing: {source_code}') + profile = get_rpa_login_profile(source_code) if profile is None or not profile.enabled: - raise RuntimeError(f'receipt source profile unavailable: {source_code}') + raise RuntimeError(f'inbound source profile unavailable: {source_code}') query_parameters = [ dict(item) for item in (config.query_parameters_json or []) if isinstance(item, dict) ] snapshot = { - 'config_id': config.id, 'config_version': config.config_version, - 'connector_type': source.connector_type, + 'config_id': config.config_id, 'config_version': config.config_version, + 'connector_type': site.connector_type, 'report_path_json': config.report_path_json or {}, 'query_parameters_json': query_parameters, - 'warehouse_id': None, 'rpa_profile_id': source.rpa_profile_id, + 'warehouse_id': None, 'rpa_profile_id': profile.profile_id, } return { - 'inventory_source_id': source.id, - 'callback_id': f'receipt:{uuid.uuid4().hex}', - 'source_code': source.source_code, - 'connector_type': source.connector_type, + 'source_id': site.source_id, + 'callback_id': f'inbound:{uuid.uuid4().hex}', + 'source_code': site.source_code, + 'connector_type': site.connector_type, 'warehouse_id': None, - 'rpa_profile_id': profile.id, + 'rpa_profile_id': profile.profile_id, 'rpa_profile_code': profile.profile_code, 'login_url': profile.login_url, - 'login_config': dict(profile.login_config_json or {}), + 'login_config': dict(profile.login_config or {}), 'credential_envelope': { 'username_ciphertext': profile.username_ciphertext, 'password_ciphertext': profile.password_ciphertext, @@ -73,38 +89,34 @@ def _build_trigger_unit( } -def list_receipt_capable_source_codes() -> list[str]: - """列出可产出收料文件的启用来源实例(enabled 库存源 + 已配置收料报表)。 +def list_inbound_capable_source_codes() -> list[str]: + """列出可产出入站文件的启用来源实例(已配置入站报表的启用站点)。 - 用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——收料文件只能 - 来自已配置收料报表的站点,与货代收料 RPA 排程的站点口径保持一致。 + 用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——入站文件 + 只能来自已配置入站报表的站点,与货代入站 RPA 排程的站点口径一致。 + 【阶段 B Task 4】站点×入站配置 join 查询改委托 + freight_rpa.reports.queries.list_inbound_configured_source_codes;本函数 + 保留为调拨域语义出口(既有调用方 import 路径不变)。 Returns: 按 source_code 排序的来源编码列表;无匹配站点时为空列表。 """ - from app import db - from app.models import ShippingInventorySource, ShippingReceiptReportConfig - - rows = db.session.query(ShippingInventorySource.source_code).join( - ShippingReceiptReportConfig, - ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id, - ).filter(ShippingInventorySource.enabled.is_(True)).order_by(ShippingInventorySource.source_code).all() - return [str(code) for (code,) in rows] + return list_inbound_configured_source_codes() -def trigger_receipt_rpa( +def trigger_inbound_rpa( *, source_code: str, business_date: str, - reason: str = 'transfer_retry_receipt', + reason: str = 'transfer_retry_inbound', writer: RouteTriggerWriter | None = None, ) -> dict[str, Any]: - """触发一次来源收料 RPA 抓取(先落单元行再写 trigger,保证回调可达)。 + """触发一次来源入站 RPA 抓取(先落单元行再写 trigger,保证回调可达)。 Args: source_code: 来源实例编码。 business_date: 业务日期。 reason: 触发原因(写入 trigger)。 - writer: 触发写者;缺省复用 write_receipt_export_batch_trigger。 + writer: 触发写者;缺省复用 write_inbound_export_batch_trigger。 Returns: {"ok": True, "callback_id": ..., "trigger_path": ...} 或 {"ok": False, "error_code": ...}(配置缺失 / 触发目录不可用)。 @@ -112,16 +124,16 @@ def trigger_receipt_rpa( try: unit_payload = _build_trigger_unit(source_code=source_code, business_date=business_date, reason=reason) except RuntimeError as exc: - return {"ok": False, "error_code": "RPA_RECEIPT_CONFIG_MISSING", "error_message": str(exc)} + return {"ok": False, "error_code": "RPA_INBOUND_CONFIG_MISSING", "error_message": str(exc)} # [STEP 1] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库, # 不落行则回调必然 404(与排程路径 _build_unit 同一模式)。 from app import db - from app.models import ShippingReceiptRpaUnitRun + from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun as FreightRpaInboundUnitRun - unit = ShippingReceiptRpaUnitRun( + unit = FreightRpaInboundUnitRun( # 按需触发无 ScheduleRun:schedule_run_id 保持 NULL(列可空;FK 禁止 0 占位)。 - inventory_source_id=unit_payload['inventory_source_id'], + source_id=unit_payload['source_id'], source_code=unit_payload['source_code'], connector_type=unit_payload['connector_type'], warehouse_id=unit_payload.get('warehouse_id'), @@ -135,20 +147,20 @@ def trigger_receipt_rpa( # [STEP 2] 原子写 trigger;目录不可用则单元标 failed(fail-closed,不留永久 awaiting)。 run_no = f"TRIG-{source_code}-{uuid.uuid4().hex[:8].upper()}" - writer_fn = writer or write_receipt_export_batch_trigger + writer_fn = writer or write_inbound_export_batch_trigger path = writer_fn(run_no, [unit_payload], payload={ - 'schema_version': 'shipping_receipt_rpa.v1', - 'action': 'receipt_export_batch', + 'schema_version': SCHEMA, + 'action': ACTION_INBOUND_EXPORT_BATCH, 'source_code': source_code, 'business_date': business_date, 'reason': reason, }) if not path: unit.status = 'failed' - unit.error_code = 'RPA_RECEIPT_TRIGGER_UNAVAILABLE' - unit.error_message = 'receipt trigger directory unavailable' + unit.error_code = 'RPA_INBOUND_TRIGGER_UNAVAILABLE' + unit.error_message = 'inbound trigger directory unavailable' db.session.commit() - return {"ok": False, "error_code": "RPA_RECEIPT_TRIGGER_UNAVAILABLE"} + return {"ok": False, "error_code": "RPA_INBOUND_TRIGGER_UNAVAILABLE"} # [STEP 3] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。 unit.trigger_snapshot_json = unit_payload @@ -156,28 +168,28 @@ def trigger_receipt_rpa( return {"ok": True, "callback_id": unit_payload['callback_id'], "trigger_path": path} -def trigger_receipt_rpa_batch( +def trigger_inbound_rpa_batch( *, source_codes: list[str], business_date: str, - reason: str = 'transfer_retry_receipt', + reason: str = 'transfer_retry_inbound', writer: RouteTriggerWriter | None = None, ) -> dict[str, Any]: - """批量触发多来源收料 RPA:全部有效来源合并写**一个** batch trigger 文件。 + """批量触发多来源入站 RPA:全部有效来源合并写**一个** batch trigger 文件。 【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个来源编码时调用; - 行级单来源重试仍走 trigger_receipt_rpa(一源一文件语义不变)。 + 行级单来源重试仍走 trigger_inbound_rpa(一源一文件语义不变)。 核心逻辑:逐来源装配 unit(来源级隔离——配置缺失/停用跳过并记录,不炸整批; parse_failed 先本地重解析,恢复 ready 则不触发 RPA),有效 units 先各落一行 - ShippingReceiptRpaUnitRun 再一次性 write_receipt_export_batch_trigger 原子落盘。 + RPA 单元运行行再一次性 write_inbound_export_batch_trigger 原子落盘。 Worker 对单文件按 profile 分组共享一次浏览器会话串行导出,避免逐来源开/关浏览器。 Args: source_codes: 来源实例编码列表(去重保序;空串自动剔除)。 business_date: 业务日期。 reason: 触发原因(写入 trigger payload)。 - writer: 触发写者;缺省复用 write_receipt_export_batch_trigger。 + writer: 触发写者;缺省复用 write_inbound_export_batch_trigger。 Returns: {"ok": True/False, "triggered": bool, "results": [...], "trigger_path"?/「error_code」?}。 @@ -187,13 +199,13 @@ def trigger_receipt_rpa_batch( 跳过:{source_code, ok: false, error_code, error_message})。 """ from app import db - from app.models import ShippingReceiptRpaUnitRun + from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun as FreightRpaInboundUnitRun from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback from app.services.in_transit_transfer.source_file_status import resolve_source_file_status codes = list(dict.fromkeys(str(code).strip() for code in source_codes if str(code).strip())) results: list[dict[str, Any]] = [] - units: list[ShippingReceiptRpaUnitRun] = [] + units: list[FreightRpaInboundUnitRun] = [] unit_payloads: list[dict[str, Any]] = [] # [STEP 1] 解析失败分层(对齐单来源端点)+ 逐来源装配 unit;单源失败跳过不阻断整批。 @@ -216,7 +228,7 @@ def trigger_receipt_rpa_batch( except RuntimeError as exc: results.append({ 'source_code': code, 'ok': False, - 'error_code': 'RPA_RECEIPT_CONFIG_MISSING', 'error_message': str(exc), + 'error_code': 'RPA_INBOUND_CONFIG_MISSING', 'error_message': str(exc), }) if not unit_payloads: @@ -225,12 +237,12 @@ def trigger_receipt_rpa_batch( db.session.commit() if reparse_recovered: return {"ok": True, "triggered": False, "results": results} - return {"ok": False, "triggered": False, "error_code": "RPA_RECEIPT_NO_TRIGGERABLE_SOURCE", "results": results} + return {"ok": False, "triggered": False, "error_code": "RPA_INBOUND_NO_TRIGGERABLE_SOURCE", "results": results} # [STEP 2] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库(与单来源同模式)。 for payload in unit_payloads: - unit = ShippingReceiptRpaUnitRun( - inventory_source_id=payload['inventory_source_id'], + unit = FreightRpaInboundUnitRun( + source_id=payload['source_id'], source_code=payload['source_code'], connector_type=payload['connector_type'], warehouse_id=payload.get('warehouse_id'), @@ -246,10 +258,10 @@ def trigger_receipt_rpa_batch( # [STEP 3] 一个 batch trigger 原子落盘;目录不可用则本批单元全部标 failed(不留永久 awaiting)。 run_no = f"TRIG-BATCH-{uuid.uuid4().hex[:8].upper()}" - writer_fn = writer or write_receipt_export_batch_trigger + writer_fn = writer or write_inbound_export_batch_trigger path = writer_fn(run_no, unit_payloads, payload={ - 'schema_version': 'shipping_receipt_rpa.v1', - 'action': 'receipt_export_batch', + 'schema_version': SCHEMA, + 'action': ACTION_INBOUND_EXPORT_BATCH, 'business_date': business_date, 'reason': reason, 'source_codes': [payload['source_code'] for payload in unit_payloads], @@ -257,10 +269,10 @@ def trigger_receipt_rpa_batch( if not path: for unit in units: unit.status = 'failed' - unit.error_code = 'RPA_RECEIPT_TRIGGER_UNAVAILABLE' - unit.error_message = 'receipt trigger directory unavailable' + unit.error_code = 'RPA_INBOUND_TRIGGER_UNAVAILABLE' + unit.error_message = 'inbound trigger directory unavailable' db.session.commit() - return {"ok": False, "triggered": False, "error_code": "RPA_RECEIPT_TRIGGER_UNAVAILABLE", "results": results} + return {"ok": False, "triggered": False, "error_code": "RPA_INBOUND_TRIGGER_UNAVAILABLE", "results": results} # [STEP 4] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。 for unit, payload in zip(units, unit_payloads): diff --git a/backend/app/services/in_transit_transfer/invoice_aggregator.py b/backend/app/services/in_transit_transfer/invoice_aggregator.py index c2b3e32c..f2d58a1a 100644 --- a/backend/app/services/in_transit_transfer/invoice_aggregator.py +++ b/backend/app/services/in_transit_transfer/invoice_aggregator.py @@ -1,9 +1,10 @@ """在途调拨 Invoice 多行汇总。 -用途:相同 Invoice+料号+收料日期 的多行只汇总收料数量,并永久保留原始 +用途:相同 Invoice+料号+异动日期 的多行只汇总异动数量,并永久保留原始 Sheet/行号/文件版本;同 Invoice 跨料号或跨日期自然拆分为多张发票。 依赖:app.core.errors.AppError、contracts.RawLineRefDTO。 -逻辑:汇总键 (source_code, invoice_no, material_no, receipt_date)。 +逻辑:汇总键 (source_code, invoice_no, material_no, movement_date)(tt14 入站化: + 明细字段方向中立,日期/数量键统一 movement_*)。 """ from __future__ import annotations @@ -15,7 +16,7 @@ from typing import Iterable from app.core.errors import AppError from app.services.in_transit_transfer.contracts import TRANSFER_INVOICE_CONFLICT, RawLineRefDTO -from app.services.in_transit_transfer.file_parser import ParsedReceiptRow +from app.services.in_transit_transfer.file_parser import ParsedMovementRow @dataclass(frozen=True) @@ -27,11 +28,11 @@ class AggregatedInvoice: material_no: str material_name: str specification: str - receipt_date: date - receipt_quantity: Decimal + movement_date: date + movement_quantity: Decimal raw_lines: tuple[RawLineRefDTO, ...] lot_no: str = "" - # 组内首行收料仓库值(movement 契约 warehouse_code):inventory_match 源路由匹配键。 + # 组内首行来源仓库值(movement 契约 warehouse_code):inventory_match 源路由匹配键。 warehouse_code: str = "" # 组内首行交易单位原值(movement 契约第 11 字段 unit,计划 D4):与 lot_no 同为 # 「组内首行」口径;空值在匹配阶段行级 blocked_missing_unit 阻断,不在此换算/清洗。 @@ -39,7 +40,7 @@ class AggregatedInvoice: class InvoiceConflictError(AppError): - """同一 Invoice 出现冲突(多料号/多收料日期),整单阻断。""" + """同一 Invoice 出现冲突(多料号/多异动日期),整单阻断。""" def __init__(self, message: str = "invoice conflict", *, invoice_no: str, conflict: str): super().__init__( @@ -50,11 +51,11 @@ class InvoiceConflictError(AppError): ) -def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str = "v1") -> list[AggregatedInvoice]: - """按 Invoice+料号+收料日期 汇总收料数量并保留原始行证据。 +def aggregate_invoices(rows: Iterable[ParsedMovementRow], *, file_version: str = "v1") -> list[AggregatedInvoice]: + """按 Invoice+料号+异动日期 汇总异动数量并保留原始行证据。 - 汇总键 (source_code, invoice_no, material_no, receipt_date):Invoice 语义为 - 调拨拨出单据号(如 WMS 的 External ASN #);同单号跨料号或跨收料日期时 + 汇总键 (source_code, invoice_no, material_no, movement_date):Invoice 语义为 + 调拨拨出单据号(如 WMS 的 External ASN #);同单号跨料号或跨异动日期时 自然拆分为多张发票(部分交付场景),不做整单阻断。 Args: rows: 已校验的解析行。 @@ -62,14 +63,14 @@ def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str = Returns: 汇总后的 Invoice 列表(按汇总键排序)。 """ - grouped: dict[tuple[str, str, str, date], list[ParsedReceiptRow]] = {} + grouped: dict[tuple[str, str, str, date], list[ParsedMovementRow]] = {} for row in rows: grouped.setdefault( - (row.source_code, row.invoice_no, row.material_no, row.receipt_date), [], + (row.source_code, row.invoice_no, row.material_no, row.movement_date), [], ).append(row) invoices: list[AggregatedInvoice] = [] - for (source_code, invoice_no, material_no, receipt_date), group in sorted(grouped.items()): + for (source_code, invoice_no, material_no, movement_date_key), group in sorted(grouped.items()): first = group[0] raw_lines = tuple( RawLineRefDTO(sheet=row.sheet, row_no=row.row_no, file_version=file_version) @@ -81,8 +82,8 @@ def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str = material_no=material_no, material_name=first.material_name, specification=first.specification, - receipt_date=receipt_date, - receipt_quantity=sum((row.receipt_quantity for row in group), Decimal("0")), + movement_date=movement_date_key, + movement_quantity=sum((row.movement_quantity for row in group), Decimal("0")), raw_lines=raw_lines, lot_no=first.lot_no, warehouse_code=first.warehouse_code, diff --git a/backend/app/services/in_transit_transfer/ledger_sync.py b/backend/app/services/in_transit_transfer/ledger_sync.py new file mode 100644 index 00000000..1c52fff8 --- /dev/null +++ b/backend/app/services/in_transit_transfer/ledger_sync.py @@ -0,0 +1,334 @@ +"""services/in_transit_transfer/ledger_sync.py + +用途:库存异动档落地(ADR 0001)——外部记录镜像落地:把解析产物(movement 契约 + 领域行)按自然键幂等镜像到 transfer_movement_ledger;语义与 evidence_sync + 三分类同源(插入/跳过/原行更新,ADR 0001),一期入站(record_kind='inbound'), + outbound 为预留合法值(出货侧结构就位,校验放行,不特判)。 +依赖:models/in_transit_transfer.TransferMovementLedger、audit.build_transfer_audit_event、 + movement_contract.MOVEMENT_FIELDS(档列镜像取值的唯一字段来源)。不解析文件 + (parsed_rows 由调用方/Task 11 接线从解析产物组装)、不查外部系统、零外部调用。 +逻辑:file_version 戳由 movement_file_version 统一生成(sha256: 前缀按档列宽度截断), + 入站仓库、出站落档、清空重建、匹配进度快照都调用它,禁止各处自行拼接。 + 落档前先滤 movement_date 空值行——空=未发生异动(未收 ASN/未发货订单行), + 落档即幽灵行,计入 date_skipped(解析层已滤一轮,此处为映射无关第二道防线)。 + 规格 §5 五条幂等语义——①自然键 (doc_no, line_no, line_seq, in_out_flag, + carton_id, lot_no, external_doc_no, external_line_no)(source_code/ + record_kind 整批恒定不入行内键;tt14 扩维箱号/批号;2026-10-21 扩维外部 + 单据身份=外部单号+外部项次,作档幂等主键管控)查档不存在 → 插入 + (record_kind/溯源五列随行写入);②行 + file_sha256 与来件一致 → 跳过(完全不动行,不续 updated_at——档无 TTL, + 无新鲜度概念);③证据变化 → 原行更新业务镜像列 + 换溯源(source_file_id/ + file_version/file_sha256/sheet_name/row_no/updated_at);④文件缺席的档行 + 不删(入站 RPA 非全量导出,缺席≠删除——本函数从不删除,无需显式处理); + ⑤transfer_executed=true 封存行永不更新永不复活(sealed_skipped 计数;封存 + 是最高优先事实,命中即计,与来件 sha 无关;同文件重落不产生第二行,自然键 + 唯一索引 DB 兜底)。 + record_kind 与 in_out_flag 矛盾(inbound 行出库语义 '-1')→ 计 cross_flagged + 并写 ledger_cross_check_failed 审计事件,记录照常落档;矛盾标记随落档动作 + 发生(插入/更新时)——幂等重落不重复打事件,防只追加审计表被同文件重落刷爆; + 封存行不落档故不标记(sealed_skipped 即信号)。 + 只 flush 不 commit(与 evidence_sync 同契约,提交归调用方:落地桥自行 commit, + 匹配/执行随主事务)。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import datetime +from typing import Any + +from app import db +from app.models import TransferMovementLedger +from app.services.in_transit_transfer.audit import build_transfer_audit_event +from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS + +# 契约字段 code ↔ 档列名 1:1 镜像不变式(import 期锁定;MOVEMENT_FIELDS 追加字段 +# 时必须同步 TransferMovementLedger 模型列,否则此处导入即失败——fail-fast)。 +_MOVEMENT_CODES: tuple[str, ...] = tuple(f.code for f in MOVEMENT_FIELDS) +assert set(_MOVEMENT_CODES) <= {c.name for c in TransferMovementLedger.__table__.columns} + +# record_kind='inbound' 的矛盾进出标志:入站记录出现该值即解析错位(交叉校验矛盾)。 +INBOUND_CONTRADICTORY_FLAGS: frozenset[str] = frozenset({"-1"}) +# 自然键 NOT NULL 成分(行级 8 成分;source_code/record_kind 整批恒定不入行内键): +# 镜像取值时缺值以空串落库(防 NULL 违反非空约束/逃逸唯一比对,与模型 default '' 同口径)。 +_NOT_NULL_KEY_CODES: tuple[str, ...] = ( + "doc_no", "line_no", "line_seq", "in_out_flag", + "carton_id", "lot_no", "external_doc_no", "external_line_no", +) +# 记录种类字面量:inbound=入站(ShippingInboundReport RPA 产物,shipping_notice 域术语保留); +# outbound=出站(出货侧结构就位)。 +RECORD_KIND_INBOUND = "inbound" +RECORD_KIND_OUTBOUND = "outbound" +# 交叉校验矛盾审计事件 kind(任务简报冻结字面量;仓库事件 kind 无集中常量表,行内字面量惯例)。 +LEDGER_CROSS_CHECK_EVENT = "ledger_cross_check_failed" + + +@dataclass(frozen=True) +class FileMeta: + """一次落地的来源文件证据三元组(溯源的文件级成分;Task 11 从归档文件组装)。 + + Args: + source_file_id: 入站原样归档文件 id(freight_rpa_inbound_report_files.id; + 测试/极端场景可为 None——档事实留存不依赖文件存在)。 + file_version: 文件版本号(Task 13 执行门禁 file_current 比对依据)。 + file_sha256: 文件 SHA-256(幂等跳过判定的唯一证据指纹)。 + """ + + source_file_id: int | None = None + file_version: str | None = None + file_sha256: str | None = None + + +def movement_file_version(sha256: str) -> str: + """把文件 SHA-256 摘要打成异动档 file_version 戳。 + + 核心逻辑:前缀 sha256: 加摘要后,按 TransferMovementLedger.file_version 列宽截断。 + 64 位摘要加前缀共 71 字符,超出 varchar(64) 时 PostgreSQL 会整批拒绝插入。 + 列宽取自模型,避免戳长和列定义各写一个 64。 + + Args: + sha256: 文件 SHA-256 十六进制摘要,不含前缀。 + + Returns: + 以 sha256: 开头、长度不超过档列宽度的版本戳。 + """ + limit = TransferMovementLedger.__table__.c.file_version.type.length + return f"sha256:{sha256}"[:limit] + + +@dataclass(frozen=True) +class LedgerSyncOutcome: + """一次落档的结果计数(审计与兜底日志的数据源;字段名为冻结契约,顺序自 date_skipped 引入后不再承诺)。""" + + inserted: int = 0 # 自然键不存在 → 插入新档行 + updated: int = 0 # 证据变化 → 原行更新业务镜像列 + 换溯源 + skipped: int = 0 # sha 未变的幂等跳过;同批自然键重复的后续行亦计入 + date_skipped: int = 0 # movement_date 空=未发生异动,不落档 + sealed_skipped: int = 0 # 封存行(transfer_executed=true)命中即计:永不更新永不复活 + cross_flagged: int = 0 # record_kind 与 in_out_flag 矛盾且本次实际落档的行数 + + +def _key_text(value: Any) -> str: + """自然键成分归一化:None → 空串,其余 str + strip(键成分 NOT NULL 恒有值可比)。""" + return "" if value is None else str(value).strip() + + +def _mirror_text(value: Any) -> str | None: + """业务镜像值归一化:None 保留(宽松落地可空),其余 str + strip 原样落档。""" + return None if value is None else str(value).strip() + + +def _opt_int(value: Any) -> int | None: + """可选整数(row_no):缺失/无效宽容置 None(溯源缺失不打断落地)。""" + if value is None or value == "": + return None + try: + return int(value) + except (TypeError, ValueError): + return None + + +def _cross_check_event( + *, + source_code: str, + record_kind: str, + key: tuple[str, str, str, str, str, str, str, str], + sheet_name: str | None, + row_no: int | None, + file_meta: FileMeta, +): + """构造交叉校验矛盾审计事件(未落库,由调用方 add——build 契约同 audit 模块)。 + + Args: + source_code / record_kind: 来源实例编码与记录种类。 + key: 自然键八成分 (doc_no, line_no, line_seq, in_out_flag, carton_id, + lot_no, external_doc_no, external_line_no)(已归一化;箱号/批号随 + tt14 键扩维入事件,外部单据身份随 2026-10-21 键扩维入事件,保证 + 矛盾行可唯一定位)。 + sheet_name / row_no: 行级溯源(入事件快照辅助定位来源行)。 + file_meta: 来源文件证据三元组。 + Returns: + 已计算 Hash 的 TransferAuditEvent(event_type=ledger_cross_check_failed)。 + """ + (doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no, + external_doc_no, external_line_no) = key + natural_key = "/".join(( + source_code, record_kind, doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no, + external_doc_no, external_line_no, + )) + return build_transfer_audit_event( + event_type=LEDGER_CROSS_CHECK_EVENT, + aggregate_type="transfer_movement_ledger", + # aggregate_id 列宽 String(128):超长截断防御(全量字段在 after 快照留存)。 + aggregate_id=natural_key[:128], + actor_type="system", + result="failure", + after={ + "source_code": source_code, "record_kind": record_kind, + "doc_no": doc_no, "line_no": line_no, "line_seq": line_seq, + "in_out_flag": in_out_flag, "carton_id": carton_id, "lot_no": lot_no, + "external_doc_no": external_doc_no, "external_line_no": external_line_no, + "file_version": file_meta.file_version, "file_sha256": file_meta.file_sha256, + "sheet_name": sheet_name, "row_no": row_no, + }, + ) + + +def sync_ledger_rows( + *, + source_code: str, + record_kind: str, + parsed_rows: list[dict], + file_meta: FileMeta, + now: datetime, +) -> LedgerSyncOutcome: + """按自然键幂等落地一批领域行到库存异动档(零外部调用,flush 不 commit)。 + + 【AI 触发时机】Task 11 接线后由落地主链路(evidence_sync 同步入口)在入站 + 文件落地成功时调用;未来出货报告接入时以 record_kind='outbound' 复用。 + 不要在匹配/执行链路调用本函数(匹配从档圈定,不写档)。 + + Args: + source_code: 来源实例编码(自然键成分,整批一致)。 + record_kind: 记录种类(文件种类声明,权威):'inbound' 一期(ShippingInboundReport + RPA 产物);'outbound' 出货侧(预留合法值,校验放行,不特判)。 + parsed_rows: 领域行 dict 列表,每行键=movement 契约 field code + (movement_contract.MOVEMENT_FIELDS:既有 11 + 扩展 7,与 + 档列名 1:1 镜像),值为解析原值(None=缺失,宽松落地); + 可另含可选行级溯源键 sheet_name(str)/row_no(int)(由接线方 + 从解析产物 ParsedMovementRow 组装);未知键忽略。行必含自然键 + 成分 doc_no/line_no/line_seq/in_out_flag/carton_id/lot_no + (缺失按空串落档,必填校验归解析层,本函数不做二次阻断); + movement_date 为空(None/空白)的行不入档(未发生异动, + 计入 date_skipped)。 + file_meta: 来源文件证据三元组(FileMeta);file_sha256 为 None 时无法证明 + 与档行同源,一律走更新分支(宁可重写不误跳)。 + now: 落档时间基准(插入/更新显式续 updated_at;跳过不续——完全不动行)。 + Returns: + LedgerSyncOutcome 六分类计数(inserted/updated/skipped/date_skipped/ + sealed_skipped/cross_flagged)。 + """ + counters = { + "inserted": 0, "updated": 0, "skipped": 0, + "date_skipped": 0, "sealed_skipped": 0, "cross_flagged": 0, + } + + # [STEP 0] movement_date 非空才落档:空值=未发生异动(未收 ASN/未发货订单行), + # 落档即幽灵行(永不进匹配圈档)。解析层 file_parser 已滤一轮(异动语义), + # 此处是映射无关的第二道防线:Profile 无论把哪列配到 movement_date,空值都进不了档。 + total_in = len(parsed_rows) + parsed_rows = [raw for raw in parsed_rows if _key_text(raw.get("movement_date"))] + counters["date_skipped"] = total_in - len(parsed_rows) + + # [STEP 1] 只圈定批内 doc_no 的既有档行(含封存行——封存命中必须可见),按自然键 + # 建索引;source_code/record_kind 整批恒定,键只留行级八成分(tt14 扩维: + # carton_id/lot_no——真实 WMS 行身份=单据+行+箱/批;2026-10-21 扩维: + # external_doc_no/external_line_no——外部单据身份作档幂等主键管控)。档「缺席 + # 不删、永不删除」行数单调增长(评审 Important 修复):按 source+kind 全量 + # 水化会使每次落地成本随历史线性膨胀(Task 11 接生产落地热路径),故追加 + # doc_no IN 批内过滤——批外键本就查不到、不参与任何分支,语义与全量查询 100% + # 等价;in_([]) 空批由 SQLAlchemy 渲染恒假子句,安全。 + doc_nos = sorted({_key_text(raw.get("doc_no")) for raw in parsed_rows}) + existing = ( + TransferMovementLedger.query.filter_by( + source_code=source_code, record_kind=record_kind, + ) + .filter(TransferMovementLedger.doc_no.in_(doc_nos)) + .all() + ) + by_key = { + (r.doc_no, r.line_no, r.line_seq, r.in_out_flag, r.carton_id, r.lot_no, + r.external_doc_no, r.external_line_no): r + for r in existing + } + # 同批自然键去重索引(首见为准):批内重复若不拦截,二次插入会撞 + # uq_transfer_movement_ledger_natural_key 唯一约束炸 flush。 + landed: dict[tuple[str, str, str, str, str, str, str, str], TransferMovementLedger] = {} + + # [STEP 2] 逐行六分类:日期空 → 封存 → 跳过 → 插入/更新(矛盾标记随落档动作判定)。 + for raw in parsed_rows: + doc_no = _key_text(raw.get("doc_no")) + line_no = _key_text(raw.get("line_no")) + line_seq = _key_text(raw.get("line_seq")) + in_out_flag = _key_text(raw.get("in_out_flag")) + carton_id = _key_text(raw.get("carton_id")) + lot_no = _key_text(raw.get("lot_no")) + external_doc_no = _key_text(raw.get("external_doc_no")) + external_line_no = _key_text(raw.get("external_line_no")) + key = (doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no, + external_doc_no, external_line_no) + sheet_name = _mirror_text(raw.get("sheet_name")) + row_no = _opt_int(raw.get("row_no")) + + row = by_key.get(key) or landed.get(key) + # [封存不触碰] 封存是最高优先事实:命中即计 sealed_skipped 并跳过一切写 + # (与来件 sha 无关)——永不更新、永不复活,防已执行记录被二次调拨。 + if row is not None and row.transfer_executed: + counters["sealed_skipped"] += 1 + continue + # [幂等跳过] 行 file_sha256 与来件一致 = 同一文件重落:完全不动行 + #(不续 updated_at,档无 TTL);meta 无 sha 时无法证明同源,不跳过。 + if ( + row is not None + and file_meta.file_sha256 is not None + and row.file_sha256 == file_meta.file_sha256 + ): + counters["skipped"] += 1 + continue + + # [交叉校验] inbound 行出现出库语义 '-1' 即解析错位:计 cross_flagged 并写 + # 审计事件,记录照常落档。仅在插入/更新(实际落档)时判定——幂等重落 + #(sha 未变跳过)不重复打事件,封存行不落档故不标记。 + if record_kind == RECORD_KIND_INBOUND and in_out_flag in INBOUND_CONTRADICTORY_FLAGS: + counters["cross_flagged"] += 1 + db.session.add(_cross_check_event( + source_code=source_code, record_kind=record_kind, key=key, + sheet_name=sheet_name, row_no=row_no, file_meta=file_meta, + )) + + # [镜像取值] 业务值一律从领域行 dict 按契约 code 取(扩展字段无独立槽位); + # 自然键 NOT NULL 成分缺值以空串落库(_key_text,防 NULL 违反非空约束/ + # 逃逸唯一比对——2026-10-21 外部身份扩维时修复的潜在缺陷:此前镜像缺值 + # 即 None,仅因各组装方恒给空串而未暴露)。自然键成分同源同值,插入/更新 + # 统一按全字段镜像写入(更新时键成分等值重写为无操作,SQLAlchemy 等值列 + # 不入 UPDATE)。 + mirror = { + code: (_key_text(raw.get(code)) if code in _NOT_NULL_KEY_CODES + else _mirror_text(raw.get(code))) + for code in _MOVEMENT_CODES + } + if row is None: + # [插入] 自然键不存在:新档行,record_kind + 溯源五列随行写入。 + row = TransferMovementLedger( + source_code=source_code, + record_kind=record_kind, + **mirror, + source_file_id=file_meta.source_file_id, + file_version=file_meta.file_version, + file_sha256=file_meta.file_sha256, + sheet_name=sheet_name, + row_no=row_no, + updated_at=now, + ) + db.session.add(row) + landed[key] = row + counters["inserted"] += 1 + else: + # [原行更新] 证据变化:业务镜像列整体换新 + 换溯源五件套与 updated_at + #(sha 变而业务值未变时重写等值为无操作,仅溯源换新,计数同归 updated)。 + for code, value in mirror.items(): + setattr(row, code, value) + row.source_file_id = file_meta.source_file_id + row.file_version = file_meta.file_version + row.file_sha256 = file_meta.file_sha256 + row.sheet_name = sheet_name + row.row_no = row_no + row.updated_at = now + counters["updated"] += 1 + + # [STEP 3] 缺席不删:文件里没有的自然键本函数从不触碰(入站 RPA 非全量导出, + # 缺席≠删除),无对应计数(Outcome 契约无 absent 字段)。 + # [STEP 4] 只 flush 不 commit:与 evidence_sync 同契约,提交归调用方 + #(落地桥自行 commit,匹配/执行随主事务)。 + db.session.flush() + return LedgerSyncOutcome(**counters) diff --git a/backend/app/services/in_transit_transfer/matching_service.py b/backend/app/services/in_transit_transfer/matching_service.py index 6b7e3ace..a72ad327 100644 --- a/backend/app/services/in_transit_transfer/matching_service.py +++ b/backend/app/services/in_transit_transfer/matching_service.py @@ -1,31 +1,31 @@ -"""在途调拨匹配服务。 +"""在途调拨匹配服务(匹配出生翻转:从档圈行建 items)。 -用途:编排「证据兜底对齐 → 圈行 → T+lag 成熟过滤(默认 T+2)→ 路由分组批量查 外部系统 库存 → - 严格数量比对落位 → 匹配快照与 Hash」,并支持匹配进度恢复(restore)。 -依赖:evidence_sync(STEP 0 兜底对齐)/ file_preparation(缺文件 RPA 分支)/ +用途:编排「校验类型 → 从库存异动档圈行建 items(D17 占用互斥)→ 未来日期阻断 + → 路由分组批量查 外部系统 库存 → 严格数量比对落位 → 匹配快照与 + Hash」,并支持匹配进度恢复(restore)与重查对档对账(见 retry_service)。 +依赖:transfer_type(配置门禁)/ transfer_type_config_service(resolve_warehouse)/ + scope_rules(圈档编译器)/ field_transforms(批号派生)/ ledger(档模型)/ source_file_status / capability_client / date_policy / quantity / contracts / - audit / models。 -逻辑:【语义变更 2026-09-25】文件解析已上移 evidence_sync——行由文件落地同步 - (收料回调桥,主链路)或 run_matching STEP 0 兜底对齐(备)写入 DB; - 匹配只读 DB 行并写库存侧字段(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(来源保持 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(2026-09-28 起不再新产生)仅过滤进 - invalid_count,不进明细与常规 counts; - 行交易单位(movement 契约第 11 字段 unit)只取 ERP 库存查询返回的 - stock_unit(img09,单据字段以 ERP 为唯一来源,禁用货代文件单位列): - 命中库存但 ERP 未给单位 → 行级 blocked_missing_unit(拨出/拨入仓库 - 已解析落列,行可解释可重查);unit 不参与匹配 Hash 快照,口径冻结。 + audit / models / evidence_sync(入站 ready 补落档)/ + outbound_evidence_sync(出站 ready 补落档)/ + ledger_sync.movement_file_version(进度快照的 file_version 戳)。【阶段 B Task 4】取可用入站 + 归档文件的查询已删除并收口到 freight_rpa.reports.queries;匹配不再引用 + freight_rpa 报表模型。 +逻辑:【2026-10-14 出生翻转(ADR 0001/D4/D17)】文件落地不再写 items——行由 + 本服务在匹配创建时从档圈定生成并「创建即绑定」匹配:固定条件(record_kind + ∈ record_kinds_of(类型.scope_rules);无类型对象的调用点显式 inbound + + 来源 IN + movement_date 范围 + transfer_executed=false + + movement_date 非空)+ 类型快照范围规则(apply_scope_filters 单一编译器)+ + 未被有效 items 占用(D17:ledger_record_id 引用或同匹配 grain + (source, invoice/doc_no, material, movement_date) 已被有效 item 占用; + 取消匹配即释放)。tt14 档自然键扩维后同 grain 可对应多条档(如 carton + 空→有值的重解析双行);出生前按 grain 择一建 item(不累加数量,防翻倍), + 占用亦按 grain 互斥。业务字段=档原值;仓库经 resolve_warehouse;库存评估 + 链以 items 为工作单元。create_matching 先落 Run + Matching 再驱动管道。 + 【确认匹配落档补齐 2026-10-20】UI ready≠档已写入:圈档前对所需流为 ready + 的来源做幂等落档(入站 sync_source_rows / 出站 sync_outbound_source_rows, + 只 flush 随主事务),补齐「回调落档桥未跑或部署前已就绪」的空档窗口; + parse_failed(入站/出站)均记 failed 进度,不阻断其他来源圈档。 """ from __future__ import annotations @@ -36,64 +36,77 @@ from datetime import date, datetime, timedelta from decimal import Decimal from typing import Any, Protocol -from sqlalchemy import func, false, or_ +from sqlalchemy import and_, false, func, or_ +from sqlalchemy.orm import joinedload from app import db from app.core.errors import AppError, NotFoundError, ValidationError -from app.models import ShippingReceiptReportFile, TransferInvoiceItem, TransferMatching, TransferRun +from app.models import ( + TransferInvoiceItem, + TransferMatching, + TransferMovementLedger, + 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.capability_client import ExternalQueryTimeoutError, StockTarget from app.services.in_transit_transfer.contracts import ( - TRANSFER_FILE_SCHEMA_INVALID, MatchingCountsDTO, MatchingItemDTO, MatchingSummaryDTO, RawLineRefDTO, ) from app.services.in_transit_transfer.date_policy import ( - eligible_receipt_date_to, - MATURITY_FUTURE, - MATURITY_NOT_MATURED, - maturity_status, + business_date_now, + eligible_movement_date_to, parse_date, ) -from app.services.in_transit_transfer.capability_client import ExternalQueryTimeoutError, StockTarget -from app.services.in_transit_transfer.file_parser import ReceiptFileSchemaError -from app.services.in_transit_transfer.file_preparation import ( - ReceiptFileRepository, - RpaTrigger, - ensure_receipt_file_ready, +from app.services.in_transit_transfer.field_transforms import ( + TransformRule, + apply_field_transforms, + parse_transform_rules, ) -from app.services.in_transit_transfer.movement_contract import external_lot_no +from app.services.in_transit_transfer.file_preparation import ( + InboundFileRepository, + RpaTrigger, + ensure_inbound_file_ready, +) +from app.services.in_transit_transfer.ledger_sync import movement_file_version from app.services.in_transit_transfer.quantity import classify_quantity_match -from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition +from app.services.in_transit_transfer.scope_rules import ( + ScopeRule, + apply_scope_filters, + parse_scope_rules, + record_kinds_of, + scope_rules_note, +) 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, ) -from app.services.in_transit_transfer.transfer_type import ( - IN_TRANSIT_TO_HUB_INVOICE_PREFIXES, - TransferType, - ensure_transfer_type_supported, - normalize_transfer_type, - transfer_type_scope_note, +from app.services.in_transit_transfer.transfer_type import resolve_transfer_type +from app.services.in_transit_transfer.transfer_type_config_service import ( + TransferTypeConfigDTO, + resolve_warehouse, ) ROUTE_NOT_RESOLVED_CODE = "TRANSFER.ROUTE_NOT_RESOLVED" +# ready 流在圈档前补落档:与回调桥共用解析/落档实现,匹配路径只 flush 不 commit。 +_CONFIRMABLE_SYNC_STATUSES = frozenset({"ready"}) # 明细结果值(对应 Invoice 项状态) +# 【RESULT_NOT_MATURED 已退役 2026-10-16】成熟概念删除(未上线不设兼容层)。 RESULT_EXECUTABLE = "executable" -RESULT_NOT_MATURED = "not_matured" RESULT_QUANTITY_MISMATCH = "blocked_quantity_mismatch" 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 前按"文件新版本缺失该行"自动标记;存续语义上线后不再新产生,仅作历史数据防御识别)。 +# 失效隔离结果码:档证据被新版本替换/记录消失时行退出主视图(重查对账沿用该 +# 语义,规格 §9);出生翻转后不再由落地新产生,仅作隔离出口与历史防御识别。 RESULT_FILE_REMOVED = "blocked_file_removed" # 交易单位缺失:ERP 库存行未返回单位(stock_unit 空,img09 契约恒非空——出现即 # ERP 侧数据异常):行级数据质量阻断。行在此前已完成路由解析,拨出/拨入仓库 @@ -104,7 +117,7 @@ RESULT_MISSING_UNIT = "blocked_missing_unit" # stage 保持 file_ready(有可用文件时),失败事实只落在行上。 RESULT_ROUTE_NOT_RESOLVED = "blocked_route_not_resolved" -# 匹配不触碰的行终态集合(与 evidence_sync._TERMINAL_ITEM_STATUSES 同口径): +# 匹配不触碰的行终态集合(取消匹配释放占用后行=cancelled 同样不再评估): # 已执行/人工关闭等既定事实不复活;RESULT_UNKNOWN 行处于执行结果裁决中,同样不可 # 被匹配改写(否则执行链路的结果回写会与匹配落位互相踩踏)。 _SYNC_TERMINAL_STATUSES = frozenset({ @@ -116,6 +129,9 @@ _SYNC_TERMINAL_STATUSES = frozenset({ status_machine.TransferStatus.RESULT_UNKNOWN.value, }) +# 匹配行状态的取消字面量(TRANSFER_MATCH_STATUSES 成员;D17 占用释放判据)。 +_MATCHING_STATUS_CANCELLED = "cancelled" + @dataclass(frozen=True) class RouteMapping: @@ -142,7 +158,7 @@ class RouteResolver(Protocol): """来源路由解析协议(路由归属规则冻结前由 Fake/门禁兜底)。""" def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping: - """返回 Invoice 的路由(warehouse_code 为收料文件仓库列,inventory_match 源匹配键);无法归属时抛 RouteNotResolvedError。""" + """返回 Invoice 的路由(warehouse_code 为入站文件仓库列,inventory_match 源匹配键);无法归属时抛 RouteNotResolvedError。""" @dataclass(frozen=True) @@ -165,13 +181,16 @@ class MatchingRunResult: summary: MatchingSummaryDTO items: tuple[MatchingItemDTO, ...] sources: tuple[SourceProgressDTO, ...] + # 本次运行的 scope_json 快照(7 键,规格 §9.5):create_matching 落库留痕、 + # hash 与展示的自足事实源;管道直调场景供调用方按需取用。 + scope_json: dict = field(default_factory=dict) @dataclass(frozen=True) class TransferDeps: """匹配/执行依赖集合(测试注入 Fake 替身)。""" - file_repository: ReceiptFileRepository + file_repository: InboundFileRepository rpa_trigger: RpaTrigger route_resolver: RouteResolver capabilities: Any @@ -187,36 +206,484 @@ def _summary_status(sources: tuple[SourceProgressDTO, ...], counts: MatchingCoun return "success" -def _latest_usable_report_file(source_code: str) -> ShippingReceiptReportFile | None: - """返回某来源当前「可用」(当天抓取且未清理未过期)的收料归档文件,最新优先。 +def _validate_movement_date_range( + business_date: str, movement_date_from: str | None, movement_date_to: str | None, +) -> tuple[date | None, date | None]: + """校验可选异动日期范围(纯校验无副作用;run_matching / create_matching 共用)。 - 【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。 + 【T−2 成熟封顶 2026-10-21】T−2 之前的数据全部成熟(简化成熟边界,不回退 + 2026-10-16 退役决策——无成熟行级状态):范围截止不得晚于 T−2 可匹配截止日 + (eligible_movement_date_to),T−1/当天/未来无成熟数据不可选;与前端选择器 + 上限(transferDate.ts defaultMovementDate)同口径。 Args: - source_code: 来源实例编码(收料执行单元行上的 source_code)。 + business_date: 业务日期 T(截止上限换算基准)。 + movement_date_from / movement_date_to: 可选异动日期范围(约束明细 movement_date)。 Returns: - 最新的可用 ShippingReceiptReportFile;来源无可用文件(未抓取/已失效/ - 已清理)返回 None。 + (range_from, range_to) 解析后的日期(未提供为 None)。 + Raises: + ValidationError: 起始晚于截止,或截止晚于 T−2 可匹配截止日。 + """ + range_from = parse_date(movement_date_from) if movement_date_from else None + range_to = parse_date(movement_date_to) if movement_date_to else None + if range_from and range_to and range_from > range_to: + raise ValidationError( + "movement date range is invalid", code="TRANSFER.MOVEMENT_DATE_RANGE_INVALID", + ) + matured_date_to = eligible_movement_date_to(business_date) + if range_to and range_to > matured_date_to: + raise ValidationError( + f"movement date range end is later than matured boundary {matured_date_to.isoformat()}", + code="TRANSFER.MOVEMENT_DATE_RANGE_INVALID", + ) + return range_from, range_to + + +def _item_grain_of_ledger(record: TransferMovementLedger) -> tuple[str, str, str, str]: + """档记录对应的匹配明细 grain(与 uq_transfer_invoice_items_matching_grain 对齐)。 + + Args: + record: 库存异动档行。 + Returns: + (source_code, doc_no/invoice_no, material_no, movement_date) 四元组。 """ 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() + str(record.source_code or ""), + str(record.doc_no or ""), + str(record.material_code or ""), + str(record.movement_date or ""), ) +def _prefer_ledger_for_item_grain( + current: TransferMovementLedger, candidate: TransferMovementLedger, +) -> TransferMovementLedger: + """同 grain 多档择一:优先非空 carton_id(更完整自然键),再取更大 id(更新解析)。 + + 不累加数量——同 grain 双行常见于重解析扩键(空 carton → 有 carton)的镜像分叉, + 相加会翻倍;合法同文件多箱数量已在 evidence_sync 组装期按 grain 汇总。 + """ + cur_carton = str(getattr(current, "carton_id", None) or "").strip() + cand_carton = str(getattr(candidate, "carton_id", None) or "").strip() + if bool(cand_carton) != bool(cur_carton): + return candidate if cand_carton else current + return candidate if int(candidate.id or 0) >= int(current.id or 0) else current + + +def _dedupe_ledger_records_for_item_birth( + records: list[TransferMovementLedger], +) -> list[TransferMovementLedger]: + """出生前按 item grain 去重,避免撞 uq_transfer_invoice_items_matching_grain。 + + Args: + records: 圈档结果(可含同 grain 多档)。 + Returns: + 每 grain 一条档(稳定顺序:首次出现序,值已按 _prefer_ledger_for_item_grain 择优)。 + """ + chosen: dict[tuple[str, str, str, str], TransferMovementLedger] = {} + order: list[tuple[str, str, str, str]] = [] + for record in records: + grain = _item_grain_of_ledger(record) + if grain not in chosen: + chosen[grain] = record + order.append(grain) + continue + chosen[grain] = _prefer_ledger_for_item_grain(chosen[grain], record) + return [chosen[grain] for grain in order] + + +def _effective_occupancy_filter(*, exclude_matching_id: int | None = None): + """构造「未被有效 items 占用」(D17)的 NOT EXISTS 过滤(圈档互斥单一口径)。 + + 占用定义(规格 §9 + grain 互斥):存在有效 item(所属匹配未取消、行非 + blocked_file_removed)且满足其一——(a) ledger_record_id 直指本档; + (b) 与本档同匹配 grain(source/invoice=doc_no/material/movement_date)。 + (b) 覆盖 tt14 自然键扩维后同业务 grain 的镜像分叉档,避免待匹配桶与二次 + 匹配仍圈到兄弟档。取消匹配即释放;人工关闭/成功终态不释放。 + + Args: + exclude_matching_id: 重查对账场景传入本匹配 id——本匹配自有 items 不构成 + 占用(允许刷新/补建);匹配创建圈档不传(任何有效占用都排除)。 + Returns: + SQLAlchemy NOT EXISTS 子句(作用于 TransferMovementLedger 查询)。 + """ + # material_code 可空:COALESCE 与出生侧 ``material_code or ""`` 对齐。 + # grain 互斥只认「已绑定未取消匹配」的行——出生翻转前 matching_id=NULL 的 + # 历史孤儿行不得按 grain 封死整票待匹配(本地曾因此从 ~2k 掉到 5)。 + # ledger_record_id 直指占用仍含 NULL 归属行(保持 D17 原口径)。 + grain_match = and_( + TransferInvoiceItem.matching_id.isnot(None), + TransferInvoiceItem.source_code == TransferMovementLedger.source_code, + TransferInvoiceItem.invoice_no == TransferMovementLedger.doc_no, + TransferInvoiceItem.material_no == func.coalesce(TransferMovementLedger.material_code, ""), + TransferInvoiceItem.movement_date == TransferMovementLedger.movement_date, + ) + item_conditions = [ + or_( + TransferInvoiceItem.ledger_record_id == TransferMovementLedger.id, + grain_match, + ), + # 失效隔离行不占用(消失证据不可用,记录可被重新圈定修复)。 + or_(TransferInvoiceItem.result_code.is_(None), + TransferInvoiceItem.result_code != RESULT_FILE_REMOVED), + ] + if exclude_matching_id is None: + # 匹配创建:任何未取消匹配(含无归属的历史行)的有效引用都算占用。 + item_conditions.append(or_( + TransferInvoiceItem.matching_id.is_(None), + TransferMatching.status != _MATCHING_STATUS_CANCELLED, + )) + else: + # 重查对账:仅「其他匹配」的有效引用算占用(本匹配自有 items 允许刷新)。 + item_conditions.append(and_( + TransferInvoiceItem.matching_id.isnot(None), + TransferInvoiceItem.matching_id != exclude_matching_id, + TransferMatching.status != _MATCHING_STATUS_CANCELLED, + )) + occupancy = ( + db.session.query(TransferInvoiceItem.id) + .join(TransferMatching, TransferInvoiceItem.matching_id == TransferMatching.id, isouter=True) + .filter(*item_conditions) + .exists() + ) + return ~occupancy + + +def _circle_ledger_base_query( + *, + record_kinds: tuple[str, ...], + exclude_occupied_by_matching_id: int | None = None, + matured_date_to: date | None = None, +): + """圈档固定条件底座(匹配创建圈档/重查对账/首页待匹配桶共享的唯一实现)。 + + 固定条件(规格 §6/§9):record_kind ∈ record_kinds(由调用方按类型范围规则 + 经 record_kinds_of 推导;没有类型对象时显式传入,禁止再把入站当隐式默认)、 + transfer_executed=false(档级封存防二次执行——已执行记录永不再次被圈定)、 + movement_date 非空(可空记录照常落档但不进异动日期圈定)、未被有效 items + 占用(D17,见 _effective_occupancy_filter;取消匹配即释放占用)。 + 【T−2 成熟封顶 2026-10-21】matured_date_to 传入时只圈 movement_date ≤ T−2 + 的成熟记录(T−2 之前数据全部成熟;T−1/当天未成熟不匹配,留在档内待成熟后 + 自然进圈)。匹配创建圈档与首页待匹配桶传值;重查对账不传——对账只对既有 + items 与档证据对齐,新增封顶会把存量未成熟行误判「档消失」走失效隔离。 + 【单一口径纪律】任何新的圈档消费方必须经本底座组合查询,禁止第三处手写 + 固定条件(双份维护=谓词漂移温床)。 + + Args: + record_kinds: 允许圈入的记录类型(inbound/outbound)。必传。 + exclude_occupied_by_matching_id: 重查对账时排除本匹配占用;创建圈档不传。 + matured_date_to: 可匹配截止日(eligible_movement_date_to 产物);None=不封顶。 + """ + query = TransferMovementLedger.query.filter( + TransferMovementLedger.record_kind.in_(record_kinds), + TransferMovementLedger.transfer_executed.is_(False), + TransferMovementLedger.movement_date.isnot(None), + _effective_occupancy_filter(exclude_matching_id=exclude_occupied_by_matching_id), + ) + if matured_date_to is not None: + query = query.filter(TransferMovementLedger.movement_date <= str(matured_date_to)) + return query + + +def _order_circled_ledger(query): + """圈档结果稳定排序(异动日期 → 来源 → 单号 → id,与明细视图同口径)。""" + return query.order_by( + TransferMovementLedger.movement_date.asc(), + TransferMovementLedger.source_code.asc(), + TransferMovementLedger.doc_no.asc(), + TransferMovementLedger.id.asc(), + ) + + +def _scope_union_queries(): + """范围并集的逐启用类型圈档查询生成器(行版/ID 版并集共享的唯一底座)。 + + 核心逻辑:对每个启用调拨类型按现行范围规则各建一条查询——复用 + _circle_ledger_base_query 固定条件(record_kinds_of(该类型范围规则)/ + 未封存/有异动日期/未被有效 items 占用/T−2 成熟封顶)+ apply_scope_filters + 单一编译器,与匹配创建圈档同口径,杜绝谓词漂移。无启用类型 → 空序列 + (fail-closed:无类型即无范围,与匹配创建 NOT_CONFIGURED 语义一致)。 + get_enabled 延迟导入:配置服务与本模块互相引用,顶层引入成环。 + """ + from app.services.in_transit_transfer.transfer_type_config_service import get_enabled + + matured_date_to = eligible_movement_date_to(business_date_now()) + for config in get_enabled(): + yield apply_scope_filters( + _circle_ledger_base_query( + record_kinds=record_kinds_of(config.scope_rules), + matured_date_to=matured_date_to, + ), + TransferMovementLedger, + config.scope_rules, + ) + + +def circle_ledger_record_ids_scope_union() -> set[int]: + """启用类型范围并集圈档(只取 id;首页汇总/待匹配清单 matchable 标记用)。 + + 【AI 触发时机】只需要「启用类型并集现在圈得住哪些档」的 id 集合做成员 + 判断/分段计数(backlog_service._matchable_ids → 待匹配清单 matchable + 标记、segment 计数与分页召回)时调用;需要整行清单不要用并集——首页 + 待匹配桶清单/计数走 pending_ledger_query(不按类型范围过滤,matchable + 只作标记),匹配创建圈档按所选类型单范围走 _circle_ledger_records。 + 【2026-10-22 行版退役】整行版随首页 SQL 下推退役(唯一消费方改取 id 集, + 整行装载曾是 /summary 33s 的根因之一);需要整行时经 _scope_union_queries + 自行投影,禁止复活全量 .all()。 + + 范围并集=对每个启用类型分别按其现行规则圈取后按 id 去重并集(等价实现): + 每类型查询复用 _circle_ledger_base_query 固定条件(record_kinds_of(该类型 + 范围规则)/未封存/有异动日期/未被有效 items 占用/T−2 成熟封顶)+ + apply_scope_filters 单一编译器——与匹配创建圈档同口径,杜绝谓词漂移。 + 【2026-10-21 桶口径放开】待匹配桶随类型规则推导记录类型(未钉 record_kind + 的类型=出入站双轨):出入站未匹配记录都在桶里可见(一期"只收收料记录" + 旧契约随类型配置化退役;桶=待办可见性清单,不影响各类型实际圈定匹配)。 + 【T−2 成熟封顶 2026-10-21】待匹配=可匹配:未成熟行(>T−2)不进桶,待成熟后 + 自然出现。无启用类型 → 空集(fail-closed:无类型即无范围,与匹配创建 + NOT_CONFIGURED 语义一致)。已封存记录恒不在结果中(固定条件)。 + + Returns: + 档 id 集合;无启用类型时空集(fail-closed,与匹配创建语义一致)。 + """ + ids: set[int] = set() + for query in _scope_union_queries(): + ids.update(row[0] for row in query.with_entities(TransferMovementLedger.id)) + return ids + + +def pending_ledger_query(*, matchable_ids: set[int] | None = None, segment: str = "all"): + """待匹配圈档查询:固定条件与 T−2,出入站都收,不按调拨类型范围过滤。 + + 【AI 触发时机】首页「待匹配」计数和清单需要「已落档、尚未匹配」的全量时调用。 + 库存匹配卡上的「当前可匹配」不要用本查询的 all 段,那是启用类型范围并集。 + + 核心逻辑:复用 _circle_ledger_base_query(未封存、异动日期非空、未被占用、 + movement_date ≤ T−2),record_kinds 固定为 inbound 与 outbound。 + segment=matchable 只留 matchable_ids;segment=outside 排除这些 id; + 并集为空时 matchable 段为空查询,outside 段等于 all。 + + Args: + matchable_ids: 启用类型范围并集的档 id。all 段忽略。 + segment: all、matchable 或 outside。 + + Returns: + 已按异动日期、来源、单号、id 排序的 Query。 + """ + matured_date_to = eligible_movement_date_to(business_date_now()) + query = _circle_ledger_base_query( + record_kinds=("inbound", "outbound"), + matured_date_to=matured_date_to, + ) + # [STEP 1] 类型范围只用于把全量拆成「现在可匹配」和「其余已落档」。 + ids = matchable_ids or set() + if segment == "matchable": + query = query.filter(TransferMovementLedger.id.in_(ids) if ids else false()) + elif segment == "outside" and ids: + query = query.filter(~TransferMovementLedger.id.in_(ids)) + return _order_circled_ledger(query) + + +def _circle_ledger_records( + *, + source_codes: list[str], + rules: tuple[ScopeRule, ...], + movement_date_from: str | None, + movement_date_to: str | None, + record_kinds: tuple[str, ...], + exclude_occupied_by_matching_id: int | None = None, + doc_nos: list[str] | None = None, + matured_date_to: date | None = None, +) -> list[TransferMovementLedger]: + """按快照规则+固定条件圈定档记录(匹配创建圈档与重查对账的共享底座/唯一实现)。 + + 固定条件(规格 §6/§9)见 _circle_ledger_base_query(本函数叠加:来源 IN + (所选来源)、movement_date 范围、快照范围规则(apply_scope_filters 单一 + 编译器)、可选单号过滤)——两个调用方必须复用本函数,禁止各自手写固定条件 + (双份维护=谓词漂移温床)。record_kinds 原样传给底座,本函数不另给默认。 + + Args: + source_codes: 来源实例编码列表。 + rules: 范围规则元组(parse_scope_rules 产物)。 + movement_date_from / movement_date_to: 可选异动日期范围(ISO 字符串)。 + record_kinds: 允许圈入的记录类型。有类型对象的调用方传 + record_kinds_of(config.scope_rules);没有类型对象时显式传入。必传。 + exclude_occupied_by_matching_id: 重查对账场景传入本匹配 id——本匹配自有 + items 不构成占用(允许刷新/补建);匹配创建圈档不传(任何有效占用 + 都排除)。 + doc_nos: 可选单号过滤(重查 invoice_nos 限定范围时约束补圈)。 + matured_date_to: 可匹配截止日(T−2 成熟封顶,见底座);匹配创建圈档传值, + 重查对账不传(对账不做成熟裁剪,避免存量未成熟行误判档消失)。 + Returns: + 档记录列表(异动日期 → 来源 → 单号 → id 稳定排序,与明细视图同口径)。 + """ + query = _circle_ledger_base_query( + record_kinds=record_kinds, + exclude_occupied_by_matching_id=exclude_occupied_by_matching_id, + matured_date_to=matured_date_to, + ).filter(TransferMovementLedger.source_code.in_([str(code) for code in source_codes])) + if movement_date_from: + query = query.filter(TransferMovementLedger.movement_date >= str(movement_date_from)) + if movement_date_to: + query = query.filter(TransferMovementLedger.movement_date <= str(movement_date_to)) + query = apply_scope_filters(query, TransferMovementLedger, rules) + if doc_nos: + query = query.filter(TransferMovementLedger.doc_no.in_(doc_nos)) + return _order_circled_ledger(query).all() + + +def _resolve_route_with_config( + deps: TransferDeps, config: TransferTypeConfigDTO, *, + source_code: str, invoice_no: str, warehouse_code: str, +) -> RouteMapping: + """路由映射档解析 + 类型仓库定义(mapped/fixed)落 (org, from, to)。 + + Args: + deps: 注入依赖(route_resolver=映射档解析)。 + config: 类型配置(warehouse_config 供 resolve_warehouse 按 role 取值)。 + Returns: + RouteMapping(external_org 取拨出角色解析值;fixed 非空才覆盖法人)。 + Raises: + RouteNotResolvedError: 来源映射档不可解析(fail-closed,调用方落行级阻断)。 + """ + mapped = deps.route_resolver.resolve( + source_code=source_code, invoice_no=invoice_no, warehouse_code=warehouse_code, + ) + from_org, from_wh = resolve_warehouse(mapped, config.warehouse_config, "from") + _to_org, to_wh = resolve_warehouse(mapped, config.warehouse_config, "to") + return RouteMapping(external_org=from_org, from_warehouse=from_wh, to_warehouse=to_wh) + + +def _born_item_from_record( + record: TransferMovementLedger, *, + matching_id: int | None, + route: RouteMapping | None, now: datetime, +) -> TransferInvoiceItem: + """由档记录构造出生 item(业务字段=档原值;路由失败留空待评估链落阻断)。 + + 行上批号等字段保持档原值(证据原则);批号转换只在系统边界按匹配快照规则 + 派生(见 field_transforms),不落库。 + """ + from app.services.in_transit_transfer.evidence_sync import SYNC_RESULT_PENDING + + return TransferInvoiceItem( + matching_id=matching_id, + # run_id 保持 None:执行 Run 的行关联归 orchestrator(create_execution_run_ + # for_items 以 run_id is None 圈未关联行);匹配 Run 不占用行关联。 + run_id=None, + ledger_record_id=record.id, + source_code=record.source_code, + invoice_no=record.doc_no, + material_no=record.material_code or "", + material_name=record.material_name or "", + specification=record.specification or "", + movement_date=record.movement_date, + lot_no=record.lot_no or "", + movement_warehouse_code=record.warehouse_code or "", + # 交易单位只取 ERP stock_unit(匹配评估落列),出生行置空。 + unit="", + from_warehouse=route.from_warehouse if route else "", + to_warehouse=route.to_warehouse if route else "", + movement_quantity=str(record.quantity or "0"), + external_quantity=None, + status=status_machine.TransferStatus.MATCHING.value, + result_code=SYNC_RESULT_PENDING, + result_message=None, + # 行级溯源单行(档记录的 sheet/row + 文件版本戳):file_sha256 供 + # 行当前性徽标(file_current)读取(执行门禁已退役 2026-10-22)。 + raw_lines_json=[{ + "sheet": record.sheet_name or "", + "row_no": int(record.row_no or 0), + "file_version": record.file_version or "", + "file_sha256": record.file_sha256 or "", + }], + updated_at=now, + ) + + +def matching_transform_rules(matching: TransferMatching) -> tuple[TransformRule, ...]: + """读取匹配快照的转换规则(scope_json.transform_rules;快照自足,不查配置表)。 + + 【AI 触发时机】存量匹配的重查/执行/展示需要批号外部形态时,必须经本函数取 + 「匹配创建当时」的规则(规格 §8:在途匹配口径不被中途改配置扰动); + 存量/异形快照无该键时返回空规则(=恒等,兼容旧形状)。 + """ + scope = matching.scope_json if isinstance(matching.scope_json, dict) else {} + return parse_transform_rules(scope.get("transform_rules")) + + +def item_external_lot_no(item: TransferInvoiceItem) -> str: + """行批号的外部形态派生(按行所属匹配快照的转换规则;无规则=恒等)。 + + 【AI 触发时机】任何把行上 lot_no 发往外部系统或按外部批号聚合/展示的场景 + (匹配库存查询/回查、写前复查、建单单行聚合键、单投影 join 键)必须经本 + 函数;禁止硬编码前缀转换(原 movement_contract.external_lot_no 已退役, + WTP→HOW 改为类型配置的转换规则驱动)。行上落库值保持档原形(证据原则)。 + + Args: + item: 明细行(matching_id 关联的匹配快照携带 transform_rules)。 + Returns: + 派生后的外部形态批号(None/空输入返回空串)。 + """ + matching = item.matching # relationship(transient 行允许直接赋值,测试复用) + rules = matching_transform_rules(matching) if matching is not None else () + return apply_field_transforms("lot_no", item.lot_no, rules) or "" + + +def _sync_ready_evidence_before_circle( + *, + source_code: str, + required_kinds: tuple[str, ...], + kind_status: dict[str, dict], + deps: TransferDeps, + business_date: str, + now: datetime, +) -> None: + """确认匹配前:对所需流为 ready 的证据做幂等落档(只 flush,提交归调用方)。 + + 【AI 触发时机】run_matching STEP 0 在圈档前调用——UI「就绪」只表示归档文件 + 可用,不等于 transfer_movement_ledger 已有行(出站落档桥后部署、或回调桥 + 失败时会出现空档);此处补一次与回调同口径的落档,sha 未变则幂等跳过。 + + 核心逻辑:按 required_kinds 逐流;仅 file_status==ready 触发。入站走 + evidence_sync.sync_source_rows(deps + business_date);出站走 + outbound_evidence_sync.sync_outbound_source_rows。异常只打 warning,不抛—— + 匹配主链路不得被单源落档失败整单炸掉(圈档仍按现有档事实进行;parse_failed + 由落档桥尽力标记后由下方状态分支反映)。 + + Args: + source_code: 来源实例编码。 + required_kinds: 本类型所需记录类型(inbound/outbound)。 + kind_status: 该来源各流的 resolve_source_file_status 投影。 + deps: 入站落档用的 TransferDeps(file_repository)。 + business_date: 业务日(入站新鲜度口径)。 + now: 落档时间基准。 + """ + from flask import current_app + + from app.services.in_transit_transfer.evidence_sync import sync_source_rows + from app.services.in_transit_transfer.outbound_evidence_sync import ( + sync_outbound_source_rows, + ) + + for kind in required_kinds: + status = kind_status.get(kind) or {} + if status.get("file_status") not in _CONFIRMABLE_SYNC_STATUSES: + continue + try: + if kind == "inbound": + sync_source_rows( + source_code=source_code, deps=deps, + business_date=business_date, now=now, + ) + elif kind == "outbound": + sync_outbound_source_rows(source_code=source_code, now=now) + except Exception as exc: # noqa: BLE001 —— 单源落档失败不阻断匹配 + current_app.logger.warning( + "TRANSFER_MATCH_EVIDENCE_SYNC_FAILED source=%s kind=%s error=%s", + source_code, kind, exc, + ) + + def run_matching( *, source_codes: list[str], @@ -224,20 +691,27 @@ def run_matching( deps: TransferDeps, active_source_job_key: str | None = None, run_no: str = "RUN-PENDING", - receipt_date_from: str | None = None, - receipt_date_to: str | None = None, - transfer_type: TransferType | str | None = None, + movement_date_from: str | None = None, + movement_date_to: str | None = None, + transfer_type: str | None = None, + matching_id: int | None = None, + scope_rules_override: list[dict] | None = None, + transform_rules_override: list[dict] | None = None, + require_enabled: bool = True, ) -> MatchingRunResult: - """执行一次匹配(对齐→圈行→查库存→落位;文件解析已上移 evidence_sync)。 + """执行一次匹配(校验类型 → 圈档建 items → 查库存 → 落位;文件解析在落档链路)。 - 【语义变更 2026-09-25】本函数不再解析收料文件:行由文件落地同步(收料回调桥, - 主链路)或 STEP 0 兜底对齐(备)写入 DB;本函数只做「成熟过滤 → 路由分组 - 批量查库存 → 数量比对落位」。来源无可用文件时保留既有 UX:触发 RPA 抓取 - 并按准备结果标来源阶段。【失败分层 2026-09-29】路由不可解析只落行级 - blocked_route_not_resolved(来源有可用文件时 stage 保持 file_ready,不再整源 - 抬升 failed);align 的 schema 类解析失败额外把失败事实落到来源可用文件 - (parse_failed 三列)。落库写入不在此 commit(随调用方事务:create_matching - 末尾统一提交 / 异步 Job handler 回写后提交)。 + 【出生翻转 2026-10-14】本函数不再做证据兜底对齐(align 已退役):STEP 0 改为 + 「从档圈行建 items」——按类型快照范围规则+固定条件圈定档记录并逐记录创建 + item(创建即绑定 matching_id);随后既有库存评估链不变(以 items 为工作单元)。 + 来源阶段只影响进度展示,不阻断档圈定——档是镜像事实,不随当日文件可用性消失。 + 入站 RPA 只在类型要求入站、且入站投影不是 ready / no_data / unconfigured / + parse_failed 时触发;入站已确认无数据,或类型不要求入站,不得触发入站抓取。 + 【确认匹配落档补齐】所需流为 ready 时先幂等落档再圈档(见 + _sync_ready_evidence_before_circle);所需流出站/入站 parse_failed 均记 + failed 进度。落库写入不在此 commit(随调用方事务:create_matching 末尾统一 + 提交 / 异步 Job handler 回写后提交)。圈档记录类型取 record_kinds_of(本次 + 已加载的 scope_rules):创建路径=类型现行规则,存量重跑=快照规则。 Args: source_codes: 来源实例列表(DBS/Crane 仅分组,实例为执行边界)。 @@ -245,97 +719,120 @@ def run_matching( deps: 注入的文件仓库 / RPA / 路由 / 外部系统 依赖。 active_source_job_key: 活动 Source Job 键(缺文件时绑定已有任务)。 run_no: Run 编号(契约兼容保留;当前管道不消费,仅调用方留痕)。 - receipt_date_from / receipt_date_to: 可选收料日期查询范围。 - transfer_type: 调拨业务类型(缺省在途仓至HUB仓);类型决定收料数据范围。 + movement_date_from / movement_date_to: 可选异动日期查询范围。 + transfer_type: 调拨类型编码(必填;配置驱动,见 resolve_transfer_type)。 + matching_id: 匹配行 id(出生即绑定;create_matching / 异步重跑传入)。 + 缺省时仅用于管道级直调(测试):行暂无归属,调用方负责回填。 + scope_rules_override / transform_rules_override: 存量匹配重跑的快照规则 + (快照自足,规格 §8/§9);缺省用类型配置现行值。 + require_enabled: 类型启停门禁开关(创建路径 True;存量重跑传 False—— + 「停用后存量不受影响」,规格 §4.1)。 Returns: MatchingRunResult(摘要 + 明细 + 来源进度)。 Raises: - ValidationError: source_codes 为空、日期范围非法或调拨类型非法/未支持。 + ValidationError: source_codes 为空、类型缺失/未配置/停用、日期范围非法。 """ + del run_no # 契约兼容保留(调用方留痕),管道不消费 if not source_codes: raise ValidationError("source_codes is required") - resolved_transfer_type = normalize_transfer_type(transfer_type) - ensure_transfer_type_supported(resolved_transfer_type) - # [日期范围] 可选收料日期过滤;卡控:截止不得超出成熟规则(业务日期-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: - raise ValidationError( - "receipt date range is invalid", code="TRANSFER.RECEIPT_DATE_RANGE_INVALID", - ) - if range_to and range_to > eligible_receipt_date_to(business_date): - raise ValidationError( - "receipt date range end exceeds receipt maturity limit", code="TRANSFER.RECEIPT_DATE_RANGE_INVALID", - ) + config = resolve_transfer_type(transfer_type, require_enabled=require_enabled) + _validate_movement_date_range(business_date, movement_date_from, movement_date_to) + # [快照规则] 存量重跑用快照(快照自足);创建路径用类型配置现行值。 + scope_rules = ( + parse_scope_rules(scope_rules_override) + if scope_rules_override is not None else config.scope_rules + ) + transform_rules = ( + parse_transform_rules(transform_rules_override) + if transform_rules_override is not None else config.transform_rules + ) now = datetime.utcnow() - # [STEP 0] 证据兜底对齐:sha 不一致的来源先重解析(落地同步失败的静默兜底)。 - # 逐来源调用以保留来源级隔离:单个来源解析失败(如文件格式坏)只标该来源 - # failed,不炸整批(2026-09-25 前该隔离在「解析→匹配」内实现,现前移至此)。 - align_errors: dict[str, tuple[str, str]] = {} - from app.services.in_transit_transfer.evidence_sync import align_scope_rows - - for source_code in source_codes: - try: - align_scope_rows(source_codes=[source_code], deps=deps, - business_date=business_date, now=now) - except ReceiptFileSchemaError as exc: - align_errors[source_code] = (exc.code, exc.message) - except Exception as exc: # noqa: BLE001 —— 来源级隔离,不阻断其他来源 - align_errors[source_code] = ("TRANSFER.SOURCE_MATCH_ERROR", str(exc)) - - # [文件状态快照] 逐来源判定可用文件:resolve 命中(含 sha)→ file_ready 留痕; - # 未命中 → ensure_receipt_file_ready(缺文件触发 RPA,既有 UX 保留)。仓库 - # 复用直接给出 ready 文件(状态投影延迟或测试替身场景)时同样按 file_ready - # 处理并留痕文件信息——只有拿到文件 checksum 的来源才进入本次圈行管道。 + # [STEP 0] 来源文件状态快照(进度展示;不阻断档圈定)。 + # 按类型所需证据流逐条投影。ensure_inbound_file_ready(reason= + # matching_missing_ready_file)只在「inbound ∈ required_kinds」且入站投影 + # 不是 ready / no_data / unconfigured 时调用。所需流 parse_failed(入/出站) + # 标 failed 并跳过该来源文件留痕。ready 流先幂等落档再圈档(补齐空档窗口)。 + # 入站 no_data、或不要求入站:不触发入站 RPA,进度记 file_ready(有 sha 则 + # 留痕,否则空 checksum),圈档照常进行。出站缺文件保持非阻断,这里不做出站 ensure。 + required_kinds = record_kinds_of(scope_rules) + # ready=已有文件;no_data=确认当日无记录;unconfigured=该流未配置。三者都可确认,不抓取。 + skip_inbound_ensure = {"ready", "no_data", "unconfigured"} sources: list[SourceProgressDTO] = [] file_snapshot: dict[str, Any] = {} - pipeline_codes: list[str] = [] + + def _remember_ready( + source_code: str, *, file_no: str | None, file_version: str | None, checksum: str, + ) -> None: + """把已有 checksum 的来源记入进度与 file_snapshot(不触发 RPA)。 + + Args: + source_code: 来源实例编码。 + file_no / file_version / checksum: 当前证据文件身份。 + """ + file_snapshot[source_code] = { + "file_no": file_no, + "file_version": file_version, + "checksum": checksum, + } + sources.append(SourceProgressDTO( + source_code=source_code, stage="file_ready", + file_no=file_no, file_version=file_version, checksum=checksum, + )) + 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], - ) + kind_status = { + kind: resolve_source_file_status(source_code=source_code, record_kind=kind) or {} + for kind in required_kinds + } + # [确认匹配落档补齐] ready → 幂等写入异动档(flush);失败仅日志,下方再投影。 + _sync_ready_evidence_before_circle( + source_code=source_code, + required_kinds=required_kinds, + kind_status=kind_status, + deps=deps, + business_date=business_date, + now=now, + ) + # 落档可能把 ready 标成 parse_failed:补投影后再做门禁。 + kind_status = { + kind: resolve_source_file_status(source_code=source_code, record_kind=kind) or {} + for kind in required_kinds + } + inbound_required = "inbound" in required_kinds + outbound_required = "outbound" in required_kinds + inbound_status = kind_status.get("inbound") or {} + outbound_status = kind_status.get("outbound") or {} + inbound_state = inbound_status.get("file_status") + outbound_state = outbound_status.get("file_status") + if inbound_required and inbound_state == "parse_failed": sources.append(SourceProgressDTO( source_code=source_code, stage="failed", - error_code=error_code, error_message=error_message, + error_code="TRANSFER_FILE_SCHEMA_INVALID", + error_message="inbound file parse failed; see source file status", )) continue - file_status = resolve_source_file_status(source_code=source_code) or {} - checksum = file_status.get("file_sha256") - if not checksum: - prepared = ensure_receipt_file_ready( + if outbound_required and outbound_state == "parse_failed": + sources.append(SourceProgressDTO( + source_code=source_code, stage="failed", + error_code="TRANSFER_FILE_SCHEMA_INVALID", + error_message="outbound file parse failed; see source file status", + )) + continue + if inbound_required and inbound_state not in skip_inbound_ensure: + prepared = ensure_inbound_file_ready( source_code=source_code, business_date=business_date, repository=deps.file_repository, rpa_trigger=deps.rpa_trigger, active_source_job_key=active_source_job_key, ) if prepared.stage == "file_ready" and prepared.file is not None: ready_file = prepared.file - checksum = ready_file.checksum - file_snapshot[source_code] = { - "file_no": ready_file.file_no, - "file_version": ready_file.file_version, - "checksum": ready_file.checksum, - } - sources.append(SourceProgressDTO( - source_code=source_code, stage="file_ready", - file_no=ready_file.file_no, - file_version=ready_file.file_version, - checksum=ready_file.checksum, - )) + _remember_ready( + source_code, file_no=ready_file.file_no, + file_version=ready_file.file_version, checksum=ready_file.checksum, + ) else: - # 等待 RPA 回调 / 触发失败:该来源本轮不圈行(行保持既有状态)。 + # 等待 RPA 回调 / 触发失败:该来源本轮不阻断(档照常圈定)。 sources.append(SourceProgressDTO( source_code=source_code, stage=prepared.stage, error_code=prepared.error_code, @@ -343,44 +840,97 @@ def run_matching( )) continue else: - file_snapshot[source_code] = { - "file_no": file_status.get("file_no"), - "file_version": f"sha256:{checksum}"[:64], - "checksum": checksum, - } - sources.append(SourceProgressDTO( - source_code=source_code, stage="file_ready", - file_no=file_status.get("file_no"), - file_version=f"sha256:{checksum}"[:64], - checksum=checksum, - )) - pipeline_codes.append(source_code) + # 不调用 ensure_inbound_file_ready。入站 ready 留入站 sha;仅出站且 + # 出站 ready 留出站 sha。no_data / 出站缺文件:空 checksum 的 file_ready。 + chosen: dict | None = None + if inbound_required and inbound_state == "ready": + chosen = inbound_status + elif not inbound_required and outbound_state == "ready": + chosen = outbound_status + checksum = (chosen or {}).get("file_sha256") + if checksum: + _remember_ready( + source_code, + file_no=(chosen or {}).get("file_no"), + file_version=movement_file_version(checksum), + checksum=checksum, + ) + else: + sources.append(SourceProgressDTO(source_code=source_code, stage="file_ready")) - # [失败分层 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, + # [STEP 0b 圈档建 items(出生翻转核心)] 圈定未占用档记录;同 grain 多档择一 + # 再建 item(uq_transfer_invoice_items_matching_grain;不累加防重解析翻倍)。 + # 【T−2 成熟封顶 2026-10-21】只圈 movement_date ≤ T−2 的成熟记录——T−1/当天 + # 未成熟不匹配,留在档内待成熟后自然进圈(「不回退退役决策,仅落简化成熟 + # 边界」:无成熟行级状态,不做逐行标记)。 + ledger_records = _dedupe_ledger_records_for_item_birth( + _circle_ledger_records( + source_codes=list(source_codes), rules=scope_rules, + movement_date_from=movement_date_from, movement_date_to=movement_date_to, + record_kinds=required_kinds, + matured_date_to=eligible_movement_date_to(business_date), + ) + ) + born: list[TransferInvoiceItem] = [] + for record in ledger_records: + try: + route = _resolve_route_with_config( + deps, config, + source_code=record.source_code, invoice_no=record.doc_no, + warehouse_code=record.warehouse_code or "", + ) + except RouteNotResolvedError: + # 路由不可解析:行照常出生(from/to 留空),评估链落行级 + # blocked_route_not_resolved(可解释、可重查,既有失败分层语义)。 + route = None + item = _born_item_from_record( + record, matching_id=matching_id, route=route, now=now, + ) + db.session.add(item) + born.append(item) + db.session.flush() + + # [评估工作集] 出生翻转后 items 只属于匹配:传 matching_id 时评估该匹配自有 + # 非终态非隔离 items(存量重跑=刷新自身 + 评估新圈行);管道直调(测试)评估 + # 本次出生行。终态/隔离行不触碰(既有约束)。 + if matching_id is not None: + working = ( + TransferInvoiceItem.query.filter( + TransferInvoiceItem.matching_id == matching_id, + TransferInvoiceItem.status.not_in(_SYNC_TERMINAL_STATUSES), + or_(TransferInvoiceItem.result_code.is_(None), + TransferInvoiceItem.result_code != RESULT_FILE_REMOVED), + ) + .order_by( + TransferInvoiceItem.movement_date.asc().nulls_last(), + TransferInvoiceItem.source_code.asc(), + TransferInvoiceItem.invoice_no.asc(), + TransferInvoiceItem.created_at.asc(), + TransferInvoiceItem.id.asc(), + ) + .all() + ) + else: + working = born + + items, pending_stock_check_count = _evaluate_items( + working=working, config=config, transform_rules=transform_rules, + business_date=business_date, deps=deps, file_snapshot=file_snapshot, now=now, ) # [失效行计数] 同口径独立计数:blocked_file_removed 行不进明细与常规 counts, - # 只以 invalid_count 透出(范围过滤与 _matching_rows 一致)。 - invalid_count = TransferInvoiceItem.query.filter( - TransferInvoiceItem.source_code.in_(list(source_codes)), - TransferInvoiceItem.result_code == RESULT_FILE_REMOVED, - *([] if not (receipt_date_from or receipt_date_to) else [ - *([TransferInvoiceItem.receipt_date >= str(receipt_date_from)] if receipt_date_from else []), - *([TransferInvoiceItem.receipt_date <= str(receipt_date_to)] if receipt_date_to else []), - ]), - ).count() + # 只以 invalid_count 透出(出生翻转后仅存量匹配的自有隔离行可见)。 + if matching_id is not None: + invalid_count = TransferInvoiceItem.query.filter( + TransferInvoiceItem.matching_id == matching_id, + TransferInvoiceItem.result_code == RESULT_FILE_REMOVED, + ).count() + else: + invalid_count = 0 counts = MatchingCountsDTO( file_invoice_count=sum(1 for item in items), - not_matured_count=sum(1 for item in items if item.result == RESULT_NOT_MATURED), - matched_count=sum(1 for item in items if item.result != RESULT_NOT_MATURED), + matched_count=len(items), executable_count=sum(1 for item in items if item.result == RESULT_EXECUTABLE), blocked_count=sum(1 for item in items if item.result.startswith("blocked_")), pending_stock_check_count=pending_stock_check_count, @@ -390,157 +940,112 @@ def run_matching( (item.to_quantity for item in items if item.result == RESULT_EXECUTABLE), Decimal("0") ) # [2026-10-12 单据数口径修正] 预计 ERP 单据数 ≠ 可执行行数:执行建单按五元组 - # (external_org, source_code, receipt_date, from_warehouse, to_warehouse) 分组, + # (external_org, source_code, movement_date, from_warehouse, to_warehouse) 分组, # 同组多行合并一张 ERP 单(execution_service.prepare_execution 同键同 .strip() # 规范化)。本值 = 可执行行按同款五元组去重后的组数;行上 external_org 由 - # 匹配评估随路由解析填齐(_matching_rows 评估分支)。原「= executable_count」 - # 口径在多行同组时高估单据数,误导用户。 + # 匹配评估随路由解析填齐(_evaluate_items 评估分支)。 estimated_document_keys = { ( item.external_org, str(item.source_code or "").strip(), - str(item.receipt_date or "").strip(), + str(item.movement_date or "").strip(), str(item.from_warehouse or "").strip(), str(item.to_warehouse or "").strip(), ) for item in items if item.result == RESULT_EXECUTABLE } - snapshot = { - "scope": sorted(set(source_codes)), - "business_date": business_date, - "transfer_type": resolved_transfer_type.value, - "file_snapshot": file_snapshot, - "counts": { - # [Hash 口径] 快照 counts 保持既有 5 键结构不变:pending/invalid 两桶 - # 是「落位前的瞬态口径」,纳入会使重复匹配的 Hash 漂移,破坏 - # 「相同输入可审计复算」性质(DTO/counts_json 留痕仍携带全桶)。 - "file_invoice_count": counts.file_invoice_count, - "not_matured_count": counts.not_matured_count, - "matched_count": counts.matched_count, - "executable_count": counts.executable_count, - "blocked_count": counts.blocked_count, - }, - "items": [ - { - # [Hash 口径冻结] items 快照仅含匹配身份与结果字段;unit 不参与哈希 - # (口径冻结,历史预检哈希不因本次字段追加而变化——计划 D4,2026-09-24)。 - # 【2026-09-25】快照行集 = _matching_rows 落位后的 DB 行投影(键形状不变; - # Hash 形状变化安全:hash 已是纯留痕不拦执行)。 - "source_code": item.source_code, - "invoice_no": item.invoice_no, - "from_warehouse": item.from_warehouse, - "to_warehouse": item.to_warehouse, - "receipt_quantity": str(item.to_quantity), - "external_quantity": str(item.from_quantity) if item.from_quantity is not None else None, - "result": item.result, - } - for item in items + # [scope_json 快照(规格 §9.5)] 范围规则 + 转换规则 + 类型 + 来源 + 日期。 + scope_json = { + "transfer_type": config.code, + "source_codes": [str(code) for code in source_codes], + "movement_date_from": movement_date_from, + "movement_date_to": movement_date_to, + "scope_rules": [ + {"field": rule.field, "match": rule.match, "values": list(rule.values)} + for rule in scope_rules + ], + "scope_note": scope_rules_note(scope_rules), + "transform_rules": [ + {"field": rule.field, "op": rule.op, "source": rule.source, "target": rule.target} + for rule in transform_rules ], } - matching_hash = f"sha256:{canonical_hash(snapshot)}" + # [Hash 纪律(规格 §13.2)] hash 一律从 scope_json 快照内容计算(加 + # business_date / file_snapshot——同为匹配行持久化内容,可审计复算), + # 禁止引入环境变量或全局态;counts/items 是落位前瞬态口径,不入 hash。 + matching_hash = f"sha256:{canonical_hash({ + **scope_json, + 'business_date': business_date, + 'file_snapshot': file_snapshot, + })}" sources_tuple = tuple(sources) summary = MatchingSummaryDTO( matching_id="", # 落库时回填 status=_summary_status(sources_tuple, counts), business_date=business_date, - eligible_receipt_date_to=str( - (date.fromisoformat(business_date) - timedelta(days=1)) - ), expires_at="", counts=counts, estimated_transfer_quantity=str(estimated_quantity), estimated_external_write_count=len(estimated_document_keys), matching_hash=matching_hash, ) - return MatchingRunResult(summary=summary, items=tuple(items), sources=sources_tuple) + return MatchingRunResult(summary=summary, items=tuple(items), sources=sources_tuple, + scope_json=scope_json) -def _matching_rows( +def _evaluate_items( *, - source_codes: list[str], + working: list[TransferInvoiceItem], + config: TransferTypeConfigDTO, + transform_rules: tuple[TransformRule, ...], business_date: str, deps: TransferDeps, - receipt_date_from: str | None, - receipt_date_to: str | None, file_snapshot: dict[str, Any], now: datetime, ) -> tuple[list[MatchingItemDTO], int]: - """对 scope 内全部非终态非失效行执行「成熟过滤→路由分组批量查库存→落位」。 + """对工作集 items 执行「未来日期阻断→路由分组批量查库存→落位」(既有评估链)。 - 【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)。 + 【出生翻转】工作集=匹配自有 items(或本次出生行);路由解析叠加类型仓库 + 定义(resolve_warehouse:mapped 透传映射档 / fixed 覆盖);批号查询目标经 + 匹配快照转换规则派生(行落库保持原值)。写库存侧字段(status/result_code/ + result_message/external_quantity/from_warehouse/to_warehouse/unit/updated_at); + raw_lines 版本戳归出生/重查对账所有,匹配不碰。 + 【失败分层 2026-09-29】路由不可解析只落行级 blocked_route_not_resolved。 + 【成熟过滤已退役 2026-10-16】数据无成熟属性——全部圈中行进路由解析与 ERP + 查询;仅未来异动日期仍阻断(数据错误,blocked_future_date)。 - Args: - source_codes: 本轮有可用文件的来源(无文件来源不圈行,行保持既有状态)。 - business_date: 业务日期 T(成熟过滤基准)。 - deps: 注入依赖(路由解析 / 外部系统库存查询)。 - receipt_date_from / receipt_date_to: 可选收料日期范围(ISO 字符串列比较)。 - file_snapshot: {source_code: 文件留痕}(行 DTO 文件对账装饰输入)。 - now: 落位时间(updated_at 新鲜度基准)。 Returns: - (items DTO 列表, pending_count)——pending_count=落位前的待查行数 - (counts 桶)。 + (items DTO 列表, pending_count)——pending_count=落位前的待查行数。 """ # 延迟引用(evidence_sync 顶层反向导入本模块,模块级互相引用会循环导入)。 from app.services.in_transit_transfer.evidence_sync import SYNC_RESULT_PENDING - query = TransferInvoiceItem.query.filter( - TransferInvoiceItem.source_code.in_(source_codes), - TransferInvoiceItem.status.not_in(_SYNC_TERMINAL_STATUSES), - # 失效行(历史残留 blocked_file_removed 行防御过滤)不参与匹配,也不进明细(invalid_count 单独计数)。 - or_(TransferInvoiceItem.result_code.is_(None), - TransferInvoiceItem.result_code != RESULT_FILE_REMOVED), - ) - if receipt_date_from: - 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().nulls_last(), - TransferInvoiceItem.source_code.asc(), - TransferInvoiceItem.invoice_no.asc(), - TransferInvoiceItem.created_at.asc(), - TransferInvoiceItem.id.asc(), - ).all() - - # [STEP 1] 成熟过滤与路由解析(不查询):未成熟/未来日期直接落位;成熟行 - # 逐行重解析路由(配置可能已变:以本次解析值为准,执行期写前复查兜底漂移)。 + # [STEP 1] 未来日期阻断与路由解析(不查询):异动日期晚于业务日期的行直接 + # 落位(数据错误);其余行逐行重解析路由(配置可能已变:以本次解析值为准, + # 执行期写前复查兜底漂移)。 + business_day = parse_date(business_date) pending_count = 0 - matured: list[tuple[TransferInvoiceItem, RouteMapping]] = [] + routable: list[tuple[TransferInvoiceItem, RouteMapping]] = [] output: list[MatchingItemDTO] = [] - for row in scope_rows_all: + for row in working: # [口径] 待查行计数先于落位统计(落位会改写 result_code)。 if (row.status == status_machine.TransferStatus.MATCHING.value and row.result_code == SYNC_RESULT_PENDING): pending_count += 1 - maturity = maturity_status(row.receipt_date, business_date) - if maturity == MATURITY_NOT_MATURED: - row.status = status_machine.TransferStatus.NOT_MATURED.value - row.result_code = RESULT_NOT_MATURED - 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.inventory_stale_ttl_seconds))) - continue - if maturity == MATURITY_FUTURE: + if parse_date(row.movement_date) > business_day: row.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value row.result_code = RESULT_FUTURE_DATE - row.result_message = "future receipt date" + row.result_message = "future movement date" row.updated_at = now output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now, int(deps.strategy.inventory_stale_ttl_seconds))) continue try: - route = deps.route_resolver.resolve( + route = _resolve_route_with_config( + deps, config, source_code=row.source_code, invoice_no=row.invoice_no, - warehouse_code=row.receipt_warehouse_code or "", + warehouse_code=row.movement_warehouse_code or "", ) except RouteNotResolvedError: # [2026-09-25 行级化 / 2026-09-29 失败分层] 路由不可解析:行落 @@ -555,20 +1060,21 @@ def _matching_rows( int(deps.strategy.inventory_stale_ttl_seconds))) continue row.from_warehouse, row.to_warehouse = route.from_warehouse, route.to_warehouse - matured.append((row, route)) + routable.append((row, route)) # [STEP 2] 按(来源, 外部组织)分组——来源实例为执行边界(故障域隔离: # 一个来源的网关绑定缺失不得波及同组织其他来源的查询结果)。 groups: dict[tuple[str, str], list[tuple[TransferInvoiceItem, RouteMapping]]] = {} - for row, route in matured: + for row, route in routable: groups.setdefault((row.source_code, route.external_org), []).append((row, route)) for (_group_source, external_org), entries in groups.items(): - # [外部形态] 批号经 WTP→HOW 派生后查询与回查(movement_contract.external_lot_no): - # 行上落库为 WMS 文件原形态,ERP 账面批号是 HOW 形态——原形态直查必查空(假阴性)。 + # [外部形态] 批号经匹配快照转换规则派生后查询(类型配置驱动,如 + # WTP→HOW):行上落库保持档原形态,ERP 账面批号是外部形态——原形态 + # 直查必查空(假阴性)。 targets = [ StockTarget(material_no=row.material_no, warehouse_code=route.from_warehouse, - lot_no=external_lot_no(row.lot_no)) + lot_no=apply_field_transforms("lot_no", row.lot_no, transform_rules) or "") for row, route in entries ] operation_id = f"op-{uuid.uuid4().hex[:12]}" @@ -598,9 +1104,10 @@ def _matching_rows( int(deps.strategy.inventory_stale_ttl_seconds))) continue for row, route in entries: + # [外部形态] 回查键与查询目标同用派生批号(三元组精确匹配)。 stock_row = stock.lookup_row( material_no=row.material_no, warehouse_code=route.from_warehouse, - lot_no=external_lot_no(row.lot_no), + lot_no=apply_field_transforms("lot_no", row.lot_no, transform_rules) or "", ) if stock_row is None: # 查无库存记录也是外部系统的真实答复:库存数按 0 落库展示(而非"-"), @@ -625,7 +1132,7 @@ def _matching_rows( row.inventory_checked_at = now row.unit = "" else: - match = classify_quantity_match(Decimal(row.receipt_quantity), stock_row.quantity) + match = classify_quantity_match(Decimal(row.movement_quantity), stock_row.quantity) row.external_quantity = str(stock_row.quantity) row.inventory_checked_at = now row.unit = stock_unit @@ -652,23 +1159,83 @@ def _generate_no(prefix: str, business_date: str) -> str: return f"{prefix}-{compact}-{uuid.uuid4().hex[:6].upper()}" -def _item_evaluated_sha(item: TransferInvoiceItem) -> str | None: - """读取行的文件版本戳(评估该行时所用的收料文件 checksum)。 +def _item_evidence_kind(item: TransferInvoiceItem) -> str: + """行文件对账使用的证据流。 - 用途:文件对账(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。 + 核心逻辑:有档关联时取档记录 record_kind(出站行对出站文件);无档关联回落 + 入站,与 resolve_source_file_status 的缺省一致。 Args: - item: InvoiceItem 行(raw_lines_json 首条携带 file_sha256 版本戳)。 + item: 匹配明细行(ledger_record 可空)。 Returns: - 版本戳字符串;行无 raw_lines 或存量数据缺 file_sha256 键时返回 None - (None 表示评估版本未知,调用方按各自口径处理,见上)。 + inbound 或 outbound。 """ + record = item.ledger_record + kind = record.record_kind if record is not None else None + if kind in ("inbound", "outbound"): + return kind + return "inbound" + + +def _latest_evidence_files( + items: list[TransferInvoiceItem], + *, + resolve=None, +) -> dict[tuple[str, str], dict]: + """按 (source_code, record_kind) 缓存当前可用证据文件投影。 + + 核心逻辑:同一来源的入站与出站文件分开投影。resolve 缺省用本模块的 + resolve_source_file_status;执行门禁传入自己命名空间里的同名函数,这样 + 测试替身打在调用方模块上仍然生效。 + + Args: + items: 待装饰或待门禁的明细行。 + resolve: 状态投影函数,签名 (source_code, record_kind) → dict。 + Returns: + (source_code, record_kind) → 文件状态投影。 + """ + lookup = resolve or resolve_source_file_status + keys = sorted({ + (item.source_code, _item_evidence_kind(item)) for item in items + }) + return { + (source_code, kind): lookup(source_code=source_code, record_kind=kind) or {} + for source_code, kind in keys + } + + +def _item_evaluated_sha(item: TransferInvoiceItem) -> str | None: + """读取行的文件版本戳(行当前性判定锚点,规格 §10 改锚)。 + + 【2026-10-14 改锚】行当前性从「行出生 sha vs 最新文件 sha」改为「item → 档 + 记录 file_sha256 == 该来源最新可用文件 sha」:档记录是证据权威,记录被 + 新版文件原行更新(file_sha256 换新)后行经档即见新版本——档记录无变化 + (仍持最新文件 sha)即当前,不再因行出生戳陈旧误判过期(入站 RPA 非全 + 量导出,证据未变的行重落后出生戳恒滞后)。行无档关联(隔离的历史行)回读 + raw_lines_json 首条 + file_sha256(存量兼容);档记录存在但无 sha → None(版本未知,消费方 + 按各自口径处理)。 + + 用途:行当前性徽标(file_current,restore/明细展示)据此判断 + "行所锚定的档记录是否仍在最新文件版本上"。2026-09-28 起不再用于 + 消失行标记(blocked_file_removed 仅重查对账的隔离出口与历史防御)。 + 【2026-10-22 执行门禁②退役】原 execute_items 门禁②消费方删除—— + 部分导出下按最新文件 sha 对账会错误卡死未处理行(缺席≠失效), + 本函数现仅剩展示消费方:None → file_current=False(仅提示不拦截), + 行级「文件已更新」徽标引导重查/重新匹配。 + 行新鲜度 TTL(updated_at / inventory_checked_at)机制不受本改锚影响。 + + Args: + item: InvoiceItem 行(ledger_record_id 指向档记录;raw_lines_json 首条 + 携带出生 file_sha256 兜底)。 + Returns: + 版本戳字符串;行无档关联且无 raw_lines(或存量数据缺 file_sha256 键)、 + 或档记录无 sha 时返回 None(None 表示评估版本未知,调用方按各自口径 + 处理,见上)。 + """ + record = item.ledger_record + if record is not None: + return record.file_sha256 or None lines = item.raw_lines_json or [] if not lines: return None @@ -681,38 +1248,28 @@ def create_matching( business_date: str, deps: TransferDeps, active_source_job_key: str | None = None, - receipt_date_from: str | None = None, - receipt_date_to: str | None = None, - transfer_type: TransferType | str | None = None, + movement_date_from: str | None = None, + movement_date_to: str | None = None, + transfer_type: str | None = None, ) -> MatchingSummaryDTO: - """运行匹配并落库 TransferRun + SourceJob + TransferMatching(留痕;不写行)。 + """运行匹配并落库 TransferRun + SourceJob + TransferMatching(行出生即绑定)。 - 【语义变更 2026-09-25】行落位已全部由 run_matching 完成(证据同步落地 + - 库存比对落位),本函数只负责留痕:Run / 来源级 SourceJob / Matching 记录 - (scope / file_snapshot / counts / Hash)。不再做「解析→upsert→消失行标记」。 - 【2026-09-28】evidence_sync 对缺席行改为存续只换戳,不再新产生 - blocked_file_removed(该码仅历史残留防御;匹配侧过滤/invalid_count); - 行归属 matching_id 保持首次创建值(原地刷新语义),重复匹配不迁移、不累加行。 + 【出生翻转 2026-10-14】先落 Run + Matching(flush 取 id)再驱动 run_matching: + 圈档建行时 matching_id/run_id 出生即绑定(D17 占用互斥与取消释放的归属基础), + 管道回写 status/counts/estimated/hash 后随主事务统一提交。类型必填且配置 + 驱动(REQUIRED/NOT_CONFIGURED/DISABLED fail-closed,D8)。圈档记录类型由 + run_matching 对已加载的 scope_rules 调用 record_kinds_of,不再写死入站。 Args: source_codes / business_date / deps: 同 run_matching。 - receipt_date_from / receipt_date_to / transfer_type: 同 run_matching。 + movement_date_from / movement_date_to / transfer_type: 同 run_matching。 Returns: 匹配摘要(matching_id 已回填)。 """ - resolved_transfer_type = normalize_transfer_type(transfer_type) - ensure_transfer_type_supported(resolved_transfer_type) + # [前置 fail-closed] 类型门禁与日期范围校验先于任何落库(无副作用,异常即整单拒绝)。 + config = resolve_transfer_type(transfer_type) + _validate_movement_date_range(business_date, movement_date_from, movement_date_to) run_no = _generate_no("RUN", business_date) - result = run_matching( - source_codes=source_codes, - business_date=business_date, - deps=deps, - active_source_job_key=active_source_job_key, - receipt_date_from=receipt_date_from, - receipt_date_to=receipt_date_to, - transfer_type=resolved_transfer_type, - run_no=run_no, - ) now = datetime.utcnow() run = TransferRun( run_no=run_no, @@ -720,12 +1277,58 @@ def create_matching( business_date=business_date, status="matching", source_codes_json=list(source_codes), - counts_json=asdict(result.summary.counts), - transfer_type=resolved_transfer_type.value, + counts_json={}, + transfer_type=config.code, ) db.session.add(run) db.session.flush() + matching = TransferMatching( + matching_no=_generate_no("MTG", business_date), + run_id=run.id, + business_date=business_date, + status="matching", + scope_json={}, # 管道回写前占位(scope_json 键集见 run_matching STEP 快照) + file_snapshot_json={}, + mapping_version="v0", + strategy_version="v0", + counts_json={}, + estimated_transfer_quantity="0", + estimated_external_write_count=0, + matching_hash="sha256:pending", + ) + db.session.add(matching) + db.session.flush() + + result = run_matching( + source_codes=source_codes, + business_date=business_date, + deps=deps, + active_source_job_key=active_source_job_key, + movement_date_from=movement_date_from, + movement_date_to=movement_date_to, + transfer_type=config.code, + matching_id=matching.id, + ) + # [回写] 管道结果落到匹配行(行出生已随管道事务写入,此处一并提交); + # scope_json 快照随行持久化(hash/展示/异步重跑的自足事实源)。 + matching.scope_json = result.scope_json + matching.file_snapshot_json = { + stage.source_code: { + "file_no": stage.file_no, + "file_version": stage.file_version, + "checksum": stage.checksum, + } + for stage in result.sources + if stage.file_no + } + matching.status = result.summary.status + matching.counts_json = asdict(result.summary.counts) + matching.estimated_transfer_quantity = result.summary.estimated_transfer_quantity + matching.estimated_external_write_count = result.summary.estimated_external_write_count + matching.matching_hash = result.summary.matching_hash + matching.expires_at = now + timedelta(seconds=deps.strategy.confirm_ttl_seconds) + # 来源级状态真相源:按 run 内每来源建一条 job((run_id, source_code) 唯一)。 # 来源准备流程阶段(file_ready/waiting_rpa_callback/failed 等)与 job 状态集已对齐。 from app.services.in_transit_transfer.source_job_service import create_source_job @@ -742,47 +1345,13 @@ def create_matching( error_code=job_source.error_code, error_message=job_source.error_message, ) - - matching_no = _generate_no("MTG", business_date) - matching = TransferMatching( - matching_no=matching_no, - run_id=run.id, - business_date=business_date, - status=result.summary.status, - scope_json={ - "source_codes": list(source_codes), - "receipt_date_from": receipt_date_from, - "receipt_date_to": receipt_date_to, - "transfer_type": resolved_transfer_type.value, - "transfer_type_scope": transfer_type_scope_note(resolved_transfer_type), - }, - file_snapshot_json={ - stage.source_code: { - "file_no": stage.file_no, - "file_version": stage.file_version, - "checksum": stage.checksum, - } - for stage in result.sources - if stage.file_no - }, - mapping_version="v0", - strategy_version="v0", - counts_json=asdict(result.summary.counts), - estimated_transfer_quantity=result.summary.estimated_transfer_quantity, - estimated_external_write_count=result.summary.estimated_external_write_count, - matching_hash=result.summary.matching_hash, - expires_at=now + timedelta(seconds=deps.strategy.confirm_ttl_seconds), - ) - db.session.add(matching) - db.session.flush() - # 留痕提交:行落位随本事务一并持久化(run_matching 只写不提交)。 + # 留痕提交:行出生/落位随本事务一并持久化(run_matching 只写不提交)。 db.session.commit() summary = MatchingSummaryDTO( - matching_id=matching_no, + matching_id=matching.matching_no, status=matching.status, business_date=matching.business_date, - eligible_receipt_date_to=result.summary.eligible_receipt_date_to, expires_at=matching.expires_at.isoformat() if matching.expires_at else "", counts=result.summary.counts, estimated_transfer_quantity=result.summary.estimated_transfer_quantity, @@ -800,11 +1369,12 @@ def restore_matching( ) -> dict[str, Any]: """按 matching_no 恢复匹配进度与明细(页面刷新/会话恢复)。 - 匹配卡是 scope 的实时视图:明细不读 matching.items 行归属关系(行归属与 - 匹配解耦后,"这份匹配覆盖哪些行"由 scope 重新圈定),counts 亦按 scope 行 - 实时聚合;历史残留 blocked_file_removed(2026-09-28 起不再新产生)不进 - 明细与常规 counts(只计入 counts.invalid_count);estimated_* 与 expires_at / - matching_hash 沿用匹配记录留痕展示。 + 【出生翻转】匹配卡=自有 items 视图:行由匹配创建时圈档生成且创建即绑定, + "这份匹配覆盖哪些行"=matching_id 归属(scope_item_query 实时圈行已退役); + counts 按自有行实时聚合;历史隔离行(blocked_file_removed)不进明细与常规 + counts(只计入 counts.invalid_count);estimated_* 与 expires_at / + matching_hash 沿用匹配记录留痕展示(展示不查配置表——类型值可能来自已停用 + 配置,规格 §13.1 历史展示健壮性)。 Args: matching_id: 匹配编号(MTG-...)。 @@ -830,14 +1400,13 @@ def restore_matching( if matching is None: raise NotFoundError("matching not found", code="TRANSFER.MATCH_NOT_FOUND") - # [STEP 1] 按 scope 实时圈行(来源 + 收料日期区间 + 调拨类型前缀),行归属 - # (matching_id)不参与——同一批行可被多份同 scope 匹配同时看到。 - # [统一排序] 与可调拨明细队列/待处理池同口径(2026-09-29 统一), - # 同一批行在匹配卡/可调拨明细/待处理池三处视图顺序一致。 + # [STEP 1] 自有行实时视图(创建即绑定):统一排序与可调拨明细队列/待处理池 + # 同口径(2026-09-29 统一),同一批行在匹配卡/可调拨明细/待处理池顺序一致。 rows_all = ( - scope_item_query(matching) + TransferInvoiceItem.query + .filter(TransferInvoiceItem.matching_id == matching.id) .order_by( - TransferInvoiceItem.receipt_date.asc().nulls_last(), + TransferInvoiceItem.movement_date.asc().nulls_last(), TransferInvoiceItem.source_code.asc(), TransferInvoiceItem.invoice_no.asc(), TransferInvoiceItem.created_at.asc(), @@ -845,32 +1414,24 @@ def restore_matching( ) .all() ) - # [失效行分层]【2026-09-28】历史残留 blocked_file_removed(存续语义上线后 - # 不再新产生)防御过滤:不进明细与常规 counts(与 _matching_rows 圈行 - # 口径一致),只计入 invalid_count。 + # [失效行分层] 隔离行(blocked_file_removed)不进明细与常规 counts,只计入 + # 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] rows = [row for row in rows_all if row.result_code != RESULT_FILE_REMOVED] - # [STEP 2] 文件对账映射:scope 内去重来源逐个投影当前可用文件版本, - # 行评估版本戳与之比对得 file_current(来源无可用文件 → False)。 - latest_files: dict[str, dict] = { - source_code: resolve_source_file_status(source_code=source_code) - for source_code in sorted({row.source_code for row in rows}) - } + # [STEP 2] 文件对账映射:按 (来源, 档记录 record_kind) 投影当前可用文件。 + # 无档关联回落入站。行评估版本戳与之比对得 file_current(无可用文件 → False)。 + latest_files = _latest_evidence_files(rows) - # [STEP 3] counts 按 scope 行实时聚合(行归属不参与)。 - # matched_count 为"未成熟以外"的可用总数(与 run_matching 语义一致); + # [STEP 3] counts 按自有行实时聚合。 # pending/invalid 两桶为 2026-09-25 counts 契约扩展(同口径内存计算)。 ready_status = status_machine.TransferStatus.READY_TO_EXECUTE.value blocked_status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value - not_matured_status = status_machine.TransferStatus.NOT_MATURED.value - not_matured_count = sum(1 for row in rows if row.status == not_matured_status) counts = MatchingCountsDTO( file_invoice_count=len(rows), - not_matured_count=not_matured_count, - matched_count=len(rows) - not_matured_count, + matched_count=len(rows), executable_count=sum(1 for row in rows if row.status == ready_status), blocked_count=sum(1 for row in rows if row.status == blocked_status), pending_stock_check_count=sum( @@ -884,9 +1445,6 @@ def restore_matching( matching_id=matching.matching_no, status=matching.status, business_date=matching.business_date, - eligible_receipt_date_to=str( - date.fromisoformat(matching.business_date) - timedelta(days=1) - ), expires_at=matching.expires_at.isoformat() if matching.expires_at else "", counts=counts, estimated_transfer_quantity=matching.estimated_transfer_quantity or "0", @@ -897,7 +1455,11 @@ def restore_matching( items = [] for item in rows: items.append( - _item_dto(item, latest_files.get(item.source_code) or {}, moment, ttl_seconds) + _item_dto( + item, + latest_files.get((item.source_code, _item_evidence_kind(item))) or {}, + moment, ttl_seconds, + ) ) sources = [ SourceProgressDTO( @@ -912,7 +1474,8 @@ def restore_matching( for job in (matching.run.source_jobs if matching.run else []) ] or [ SourceProgressDTO(source_code=code, stage="file_ready") - for code in (matching.scope_json.get("source_codes") or []) + for code in ((matching.scope_json or {}).get("source_codes") or []) + if isinstance(matching.scope_json, dict) ] return { "summary": summary, @@ -921,42 +1484,22 @@ def restore_matching( } -def scope_item_query(matching: TransferMatching): - """按匹配 scope_json 实时圈定其行集(不依赖行的 matching_id 归属)。 +def transfer_type_code_of(item: TransferInvoiceItem) -> str: + """读取明细行所属调拨类型编码。 - 用途:行归属与匹配解耦(原地刷新)后,"这份匹配覆盖哪些行"只能由 - scope(来源 + 收料日期区间 + 调拨类型范围)重新计算; - restore 实时视图与可调拨明细队列共用本查询。 + 核心逻辑:类型写在出生匹配的 scope_json.transfer_type,不在行上。 + 无匹配、快照不是对象或未写类型时返回空串,列表显示占位。 Args: - matching: 匹配记录(读取 scope_json 的 source_codes / receipt_date_from / - receipt_date_to / transfer_type)。 + item: 明细行。matching 关系可已预加载;未预加载时按外键懒加载。 Returns: - TransferInvoiceItem 的 BaseQuery;类型 Invoice 前缀过滤与 - invoice_in_scope 同一常量口径,占位类型恒空(无任何行)。 + 调拨类型 code;没有则空串。 """ - scope = matching.scope_json if isinstance(matching.scope_json, dict) else {} - sources = [str(code) for code in (scope.get("source_codes") or [])] - query = db.session.query(TransferInvoiceItem).filter( - TransferInvoiceItem.source_code.in_(sources), - ) - # 收料日期为 ISO 字符串列,直接用字符串区间比较(与 run_matching 的内存过滤同语义)。 - date_from = scope.get("receipt_date_from") - date_to = scope.get("receipt_date_to") - if date_from: - query = query.filter(TransferInvoiceItem.receipt_date >= str(date_from)) - if date_to: - query = query.filter(TransferInvoiceItem.receipt_date <= str(date_to)) - resolved_type = normalize_transfer_type(scope.get("transfer_type")) - if resolved_type == TransferType.IN_TRANSIT_TO_HUB: - prefixes = tuple(prefix.upper() for prefix in IN_TRANSIT_TO_HUB_INVOICE_PREFIXES) - query = query.filter(or_( - *(func.upper(TransferInvoiceItem.invoice_no).like(f"{prefix}%") for prefix in prefixes), - )) - else: - # 占位类型范围外无任何单(与 invoice_in_scope 恒 False 同口径)。 - query = query.filter(false()) - return query + matching = item.matching + scope = matching.scope_json if matching is not None else None + if not isinstance(scope, dict): + return "" + return str(scope.get("transfer_type") or "").strip() def _item_dto( @@ -970,14 +1513,15 @@ def _item_dto( Args: item: 明细行。 - latest: 该行来源当前可用文件状态投影(resolve_source_file_status 结果)。 + latest: 该行证据流的当前文件状态投影(按档 record_kind 解析;无档为入站)。 moment: 新鲜度判定基准时间。 inventory_stale_ttl_seconds: stale 展示阈值(strategy.inventory_stale_ttl_seconds; 仅驱动 stale 徽标提示,不阻断执行——2026-09-25 TTL 门禁退役)。 external_org: 路由解析所得外部组织(执行建单五元组首键,2026-10-12 单据数 口径修正);仅匹配评估路径可填,restore 视图路径缺省 ""。 Returns: - MatchingItemDTO(含 item_id / checked_at / stale / file_current / external_org)。 + MatchingItemDTO(含 item_id / checked_at / stale / file_current / external_org / + transfer_type)。 """ evaluated_sha = _item_evaluated_sha(item) inventory_checked_at = item.inventory_checked_at @@ -987,16 +1531,16 @@ def _item_dto( material_name=item.material_name, specification=item.specification, invoice_no=item.invoice_no, - receipt_date=item.receipt_date, + movement_date=item.movement_date, lot_no=item.lot_no or "", - receipt_warehouse_code=item.receipt_warehouse_code or "", + movement_warehouse_code=item.movement_warehouse_code or "", # 交易单位原值(movement 契约第 11 字段):restore/明细队列视图与 # 序列化(serializers)均已透传(T11 接线完成)。 unit=item.unit or "", from_warehouse=item.from_warehouse, from_quantity=Decimal(item.external_quantity) if item.external_quantity else None, to_warehouse=item.to_warehouse, - to_quantity=Decimal(item.receipt_quantity), + to_quantity=Decimal(item.movement_quantity), result=item.result_code or ( RESULT_EXECUTABLE if item.status == "ready_to_execute" else item.status ), @@ -1018,24 +1562,26 @@ def _item_dto( # (库存查得时刻,仅匹配评估/重查/写前复查写入)——原 updated_at 时钟 # 被证据同步换戳每日续期,徽标对老行永不触发;stale=距库存取数超过 # 展示阈值(inventory_stale_ttl_seconds),无库存数据(NULL)不判定; - # file_current=行评估版本戳仍是该来源当前可用文件 sha - # (无版本戳或无可用文件均视为不一致 → False)。 + # file_current=行评估版本戳仍是该行证据流(档 record_kind,无档则入站) + # 当前可用文件 sha(无版本戳或无可用文件均视为不一致 → False)。 item_id=item.id, 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"), external_org=external_org, + transfer_type=transfer_type_code_of(item), ) def list_executable_items(*, deps: TransferDeps | None = None, now: datetime | None = None) -> dict[str, Any]: """全局可执行明细队列(「可调拨明细」入口数据源)。 - 用途:行归属与匹配解耦后,可执行行不再依附任何匹配卡——本查询给出全部 - ready_to_execute 行(跨匹配范围,业务稳定排序),供前端勾选后按行 - 执行生成调拨单;行装饰(item_id / checked_at / stale / file_current) - 与 restore 实时视图同一口径。 + 用途:出生翻转后行仍恒属某匹配(创建即绑定),但执行为跨匹配勾选 + (execute_items 按行 ID 工作不变,规格 §10)——本查询给出全部 + ready_to_execute 行(业务稳定排序),供前端勾选后按行执行生成调拨单; + 行装饰(item_id / checked_at / stale / file_current)与 restore 实时 + 视图同一口径。transfer_type 取自出生匹配快照,供跨类型队列展示类别。 Args: deps: 注入依赖(缺省内部取 get_transfer_dependencies;只读 TTL 配置)。 @@ -1049,15 +1595,25 @@ def list_executable_items(*, deps: TransferDeps | None = None, now: datetime | N moment = now or datetime.utcnow() ttl_seconds = int(deps.strategy.inventory_stale_ttl_seconds) - # [稳定排序] 收料日期(空值最后)→ 数据源 → Invoice → 创建时间:与重查/恢复 + # [稳定排序] 异动日期(空值最后)→ 数据源 → Invoice → 创建时间:与重查/恢复 # 等操作无关的业务键——正在处理的行不会因 updated_at 被新鲜度续期而跳位; # 2026-09-29 与待处理池/匹配卡视图统一为同一口径(用户按同序处理两个池子)。 rows = ( - TransferInvoiceItem.query.filter( + TransferInvoiceItem.query + .options(joinedload(TransferInvoiceItem.matching)) + # [防御性双保险] 所属匹配已取消的行不入队:取消路径已把匹配名下 ready + # 行退役为 cancelled(cancellation.py),此处按匹配状态再拒一次—— + # 防绕过取消路径的状态组合(如手工改库/历史数据)产生可执行行。 + .outerjoin(TransferMatching, TransferInvoiceItem.matching_id == TransferMatching.id) + .filter( TransferInvoiceItem.status == status_machine.TransferStatus.READY_TO_EXECUTE.value, + or_( + TransferInvoiceItem.matching_id.is_(None), + TransferMatching.status != _MATCHING_STATUS_CANCELLED, + ), ) .order_by( - TransferInvoiceItem.receipt_date.asc().nulls_last(), + TransferInvoiceItem.movement_date.asc().nulls_last(), TransferInvoiceItem.source_code.asc(), TransferInvoiceItem.invoice_no.asc(), TransferInvoiceItem.created_at.asc(), @@ -1065,12 +1621,13 @@ def list_executable_items(*, deps: TransferDeps | None = None, now: datetime | N ) .all() ) - latest_files: dict[str, dict] = { - source_code: resolve_source_file_status(source_code=source_code) - for source_code in sorted({row.source_code for row in rows}) - } + latest_files = _latest_evidence_files(rows) items = [ - _item_dto(row, latest_files.get(row.source_code) or {}, moment, ttl_seconds) + _item_dto( + row, + latest_files.get((row.source_code, _item_evidence_kind(row))) or {}, + moment, ttl_seconds, + ) for row in rows ] return {"items": items, "counts": {"executable_count": len(rows)}} diff --git a/backend/app/services/in_transit_transfer/movement_contract.py b/backend/app/services/in_transit_transfer/movement_contract.py index dafdfe82..aac969ee 100644 --- a/backend/app/services/in_transit_transfer/movement_contract.py +++ b/backend/app/services/in_transit_transfer/movement_contract.py @@ -1,10 +1,10 @@ """在途调拨通用异动/移动表领域字段契约。 -用途:定义调拨消费的异动(入库/出库/收料/出货)文件领域字段——业务定死、不配置化。 +用途:定义调拨消费的异动(入站/出站)文件领域字段——业务定死、不配置化。 未来出货/入库 Excel 复用同一套字段,靠 in_out_flag 区分方向。 依赖:标准库 dataclasses / enum。 逻辑:字段清单是 immutable 常量;幂等键为 doc_no,严格数量字段为 quantity, - 成熟过滤字段为 movement_date;字段映射由 movement_parser 完成。 + 日期圈定过滤字段为 movement_date;字段映射由 file_parser.parse_movement_rows 完成。 """ from __future__ import annotations @@ -40,14 +40,22 @@ class MovementField: required: bool = False -# 定死的 11 个通用异动字段(领域契约,不配置化)。 -# [PROMPT_UPDATE] 2026-09-21:Invoice 保持锚定单号(doc_no,WMS 收料单号); +# 定死的通用异动字段(领域契约,不配置化):11 个核心字段 + 扩展可选维度字段。 +# [PROMPT_UPDATE] 2026-09-21:Invoice 保持锚定单号(doc_no,WMS 入站单号, ShippingInboundReport External ASN #); # 批号(lot_no)为展示维度——匹配列「拨出/拨入批号」由 lot_no 经 WTP→HOW 转换派生。 -# [PROMPT_UPDATE] 2026-09-25:WTP→HOW 派生收敛为 external_lot_no() 唯一实现—— -# 库存查询 / 建单下传 / 单行聚合 / 展示统一按外部形态;落库保持文件原形态(证据原则)。 +# [PROMPT_UPDATE] 2026-09-25:WTP→HOW 派生曾收敛为 external_lot_no() 唯一实现。 +# [PROMPT_UPDATE] 2026-10-14(Task 11 切换):external_lot_no() 硬编码退役——批号 +# 外部形态改由调拨类型配置的转换规则驱动(field_transforms 引擎,匹配快照固化), +# 行与档始终保存文件原形态(证据原则不变)。 # [PROMPT_UPDATE] 2026-09-24:追加第 11 字段 unit(交易单位,计划 D4)——ERP 写入 # 行必填(gls_cm19),但解析层放行空值(不产生解析失败),空值由匹配阶段行级 # blocked_missing_unit 阻断;unit 不参与幂等/匹配,也不进匹配 Hash 快照(口径冻结)。 +# [PROMPT_UPDATE] 2026-10-14:追加 7 个可选维度字段(Task 8,调拨类型配置化+库存 +# 异动档项目)——line_seq/specification/order_type/odm_id/odm_name/carton_id/pallet_id, +# 全部 required=False, is_identity=False,只追加不重排(unit 仍为第 11 字段); +# 解析层缺列容忍自动继承(row.get 投影,缺列不报错);幂等键 doc_no 与身份集 +# (doc_no/material_code/movement_date)不变;字段值由库存异动档按 code 取值落档 +# (Task 10),管理端字段目录/解析 Profile 映射白名单按 MOVEMENT_FIELDS 派生自动继承。 MOVEMENT_FIELDS: tuple[MovementField, ...] = ( MovementField("doc_no", "单号", MovementFieldValueType.TEXT, is_identity=True, required=True), MovementField("line_no", "项次", MovementFieldValueType.TEXT), @@ -60,6 +68,22 @@ MOVEMENT_FIELDS: tuple[MovementField, ...] = ( MovementField("quantity", "数量", MovementFieldValueType.DECIMAL, required=True), MovementField("movement_date", "异动日期", MovementFieldValueType.DATE, is_identity=True, required=True), MovementField("unit", "单位", MovementFieldValueType.TEXT), + # ---- 2026-10-14 扩展:可选维度字段(展示/圈档/异动档取值,非匹配身份) ---- + MovementField("line_seq", "项序", MovementFieldValueType.TEXT), + MovementField("specification", "规格", MovementFieldValueType.TEXT), + MovementField("order_type", "订单类型", MovementFieldValueType.TEXT), + MovementField("odm_id", "ODM编号", MovementFieldValueType.TEXT), + MovementField("odm_name", "ODM名称", MovementFieldValueType.TEXT), + MovementField("carton_id", "箱号", MovementFieldValueType.TEXT), + MovementField("pallet_id", "栈板号", MovementFieldValueType.TEXT), + # ---- 2026-10-21 扩展:外部单据身份(外部单号/外部项次;CRANE/Lognet 出站 + # 报告的 WMS Order #/行号)——解析放行空值(required=False),不进匹配身份 + #(is_identity=False:匹配 grain 仍=单号/料号/异动日期,契约测试钉死不受扰); + # 但两字段自 2026-10-21 起作为库存异动档自然键成分(模型 + # uq_transfer_movement_ledger_natural_key + ledger_sync 行级键)承担档幂等 + # 主键管控:同一外部单号+项次的重复落档/证据更新收敛到同一档行。 + MovementField("external_doc_no", "外部单号", MovementFieldValueType.TEXT), + MovementField("external_line_no", "外部项次", MovementFieldValueType.TEXT), ) @@ -81,25 +105,3 @@ def movement_identity_fields() -> set[str]: def movement_field_codes() -> set[str]: """全部定死字段名集合。""" return {field.code for field in MOVEMENT_FIELDS} - - -def external_lot_no(lot_no: str | None) -> str: - """批号外部形态派生:WMS 批号 WTP 前缀 → 外部系统真实批号 HOW 前缀。 - - 【AI 触发时机】任何把行上 lot_no 发往外部系统的场景——库存查询 targets、 - 写前库存复查、建单单行——组装参数前必须经本函数转换;单行聚合键与展示列 - 「拨出/拨入批号」同规则(前端 features/chat/components/messages/transferBatch.ts - deriveBatchNo 为本函数的展示侧镜像,改动须双侧同步)。行上落库值保持文件 - 原形态(证据原则:raw_lines 对账/审计复算以文件为准),转换只发生在外部 - 系统边界。 - - Args: - lot_no: 行上批号原值(文件证据形态;None/空白按空串处理)。 - Returns: - 外部系统批号形态:WTP 前缀识别大小写不敏感,余串逐字保留; - 非 WTP 前缀原样返回;空输入返回空串。 - """ - value = str(lot_no or "").strip() - if value.upper().startswith("WTP"): - return f"HOW{value[3:]}" - return value 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 b737c5a6..143fb583 100644 --- a/backend/app/services/in_transit_transfer/movement_file_repository.py +++ b/backend/app/services/in_transit_transfer/movement_file_repository.py @@ -1,31 +1,70 @@ -"""在途调拨真实异动(收料/出货)文件仓库。 +"""在途调拨真实异动(入站/出站)文件仓库。 -用途:读取货代收料链路已落库的 ShippingReceiptReportFile(对象存储原始 xlsx), - 用该来源收料配置绑定的 movement 解析规则(purpose='movement',端点=定死 - 领域字段 MOVEMENT_FIELDS)的 field_mapping 把列映射为领域行,产出 ReadyReceiptFile。 -依赖:ShippingReceiptReportFile / ShippingReceiptReportConfig / file_asset_storage、 - movement_contract、receipt_file_gate(可用性门禁)、openpyxl。 -逻辑:按来源取最新【当天(业务日)抓取】且未过期(未清理)的收料文件;无绑定规则、 - 文件缺失或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域 +用途:读取货代入站链路已落库的入站归档文件(入站证据 = freight_rpa 入站 + RPA 产物,对象存储原始 xlsx),用该来源入站报表配置绑定的 inbound + 解析规则(purpose='inbound',端点=定死领域字段 MOVEMENT_FIELDS)的 + field_mapping 把列映射为领域行,产出 ReadyInboundFile。 +依赖:【阶段 B Task 4】freight_rpa.reports.queries(站点 get_site / 入站配置 + get_inbound_config / 入站解析方案 get_inbound_parsing_profile / 最新可用 + 归档 latest_usable_inbound_file / 归档字节 read_inbound_file_bytes / + 维护通道清单 list_reparseable_inbound_files——只读入口唯一权威)、 + file_preparation(ReadyInboundFile 契约)、ledger_sync.movement_file_version + (file_version 戳的唯一生成处)、openpyxl。 +逻辑:按来源取站点(enabled)与配置 → 解析方案须 published inbound → 最新 + 【当天(业务日)抓取】且未过期(未清理)的入站文件;无绑定规则、文件缺失 + 或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域 字段 + 溯源字段(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整 校验由下游 file_parser 完成。表头别名匹配前归一化空白/换行(DSV SSRS 单元格内 折行如 External\\nASN #),仍以站点绑定规则别名为准,不另造硬编码模板。 + 另提供 list_reparseable_archived_files(spec §6 清空重建专用维护通道): + 委托 queries 维护通道查询(同一 join 路径但显式去掉当日门禁),仅供 + backlog_reparse_service 使用,运行期禁用。 """ from __future__ import annotations import re +from dataclasses import dataclass +from datetime import datetime from io import BytesIO from typing import Any, Mapping -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 +from app.services.freight_rpa.reports.queries import ( + get_inbound_config, + get_inbound_parsing_profile, + get_site, + latest_usable_inbound_file, + list_reparseable_inbound_files, + read_inbound_file_bytes, +) +from app.services.in_transit_transfer.file_preparation import ReadyInboundFile +from app.services.in_transit_transfer.ledger_sync import movement_file_version # 表头单元格内换行/多空白 → 单空格,使绑定别名与 SSRS 折行表头可精确匹配。 _HEADER_WS_RE = re.compile(r"\s+") +@dataclass(frozen=True) +class ReparseableArchiveFile: + """一份「可重建」归档文件的维护视图(清空重建专用记录,非运行期取数契约)。 + + Args: + file_id: 归档文件 id(入站归档文件表主键,档行溯源列同源)。 + storage_key: 对象存储键(重建时按此取归档字节)。 + sha256: 文件 SHA-256(重落幂等指纹 / FileMeta.file_sha256)。 + file_version: 文件版本戳(sha256: 前缀派生,与 latest_ready_file 同口径)。 + archived_at: 归档时间(created_at;重建按此升序重落)。 + original_filename: 原始文件名(预检清单/审计展示)。 + """ + + file_id: int + storage_key: str + sha256: str + file_version: str + archived_at: datetime + original_filename: str + + def _normalize_header_label(value: Any) -> str: """归一化表头/别名文本:去首尾空白,内部任意空白(含 \\n)压成单空格。 @@ -37,64 +76,94 @@ def _normalize_header_label(value: Any) -> str: return _HEADER_WS_RE.sub(" ", str(value or "").strip()) -class ShippingReceiptFileRepository: - """真实收料/异动 ready 文件仓库(复用货代收料归档 + movement 解析规则)。""" +class ShippingInboundFileRepository: + """真实入站/异动 ready 文件仓库(复用 freight_rpa 入站归档 + inbound 解析规则)。 - def __init__(self) -> None: - self._storage = file_asset_storage + 【阶段 B Task 4】模型/存储读取全部收敛到 freight_rpa.reports.queries 只读 + 入口,本类不再 import freight_rpa 报表模型或对象存储客户端;对调用方 + (file_preparation / deps / backlog_reparse_service)的类名与方法签名不变。 + """ - def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None: - """返回该来源最新且当天(业务日)抓取的未过期收料文件;否则返回 None。 + def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyInboundFile | None: + """返回该来源最新且当天(业务日)抓取的未过期入站文件;否则返回 None。 + + 核心逻辑:[STEP 1] 站点须启用(get_site)+ 入站配置须存在 + (get_inbound_config)+ 绑定解析方案须 published inbound + (get_inbound_parsing_profile,与运行期规则门禁同一口径); + [STEP 2] 取最新可用归档视图(latest_usable_inbound_file,当天 + fail-closed 门禁见 queries.usable_inbound_file_condition)并按 + file_id 读归档字节(read_inbound_file_bytes);[STEP 3] 按方案 + field_mapping 提取领域行。 Args: source_code: 来源实例编码。 - business_date: 业务日期(用于展示/匹配成熟度,不强制匹配文件日期)。 + business_date: 业务日期(用于展示,不强制匹配文件日期)。 Returns: - ReadyReceiptFile(rows 为领域字段 + 溯源 sheet/row_no 的 dict)或 None。 + ReadyInboundFile(rows 为领域字段 + 溯源 sheet/row_no 的 dict)或 None。 新鲜度/保留期/缺失均 fail-closed 返回 None(fail 消息由上游触发重抓)。 """ - from app.models import ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptReportFile - - source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() - if source is None: + site = get_site(source_code) + if site is None or not site.enabled: return None - config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first() + config = get_inbound_config(source_code) if config is None or config.parsing_profile_id is None: return None - profile = config.parsing_profile - if profile is None or profile.status != 'published' or profile.purpose != 'movement': + profile = get_inbound_parsing_profile(source_code) + if profile is None or profile.status != 'published' or profile.purpose != 'inbound': return None - report = ( - ShippingReceiptReportFile.query - .join(ShippingReceiptReportFile.unit_run) - .filter( - ShippingReceiptReportFile.unit_run.has(source_code=source_code), - # 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)单一事实来源见 receipt_file_gate。 - usable_receipt_file_condition(), - ) - .order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc()) - .first() - ) - if report is None: + view = latest_usable_inbound_file(source_code) + if view is None: return None - data = self._storage.get_bytes(report.storage_key) + definition = profile.definition_json or {} + data = read_inbound_file_bytes(view.file_id) rows = _extract_movement_rows( data, - field_mapping=dict((profile.definition_json or {}).get('field_mapping') or {}), - sheet_name=str((profile.definition_json or {}).get('sheet_name') or '').strip() or None, - header_row_index=(profile.definition_json or {}).get('header_row_index'), + field_mapping=dict(definition.get('field_mapping') or {}), + sheet_name=str(definition.get('sheet_name') or '').strip() or None, + header_row_index=definition.get('header_row_index'), ) - return ReadyReceiptFile( + return ReadyInboundFile( source_code=source_code, business_date=business_date, - file_no=report.original_filename or str(report.id), - file_version=f"sha256:{report.sha256}"[:64], - checksum=report.sha256, + file_no=view.original_filename or str(view.file_id), + file_version=movement_file_version(view.sha256), + checksum=view.sha256, rows=tuple(rows), ) + def list_reparseable_archived_files(self, source_code: str, now: datetime) -> list[ReparseableArchiveFile]: + """清空重建专用:该来源全部可重建归档(未清理+未过保留期),不设当日门禁。 + + 【AI 触发时机】仅待匹配「清空并重新解析」维护链路使用;运行期落档 + (evidence_sync)禁止改用本方法——当日 fail-closed 门禁是运行期语义, + 本方法是显式的历史重建通道(spec §6),两者不得混用。 + + 核心逻辑:委托 freight_rpa.reports.queries.list_reparseable_inbound_files + 维护通道查询(同一 join 路径,显式去掉「当天业务日抓取」新鲜度门禁—— + 重建对象正是历史归档;保留期口径一致),并把只读视图映射为本仓库的 + 维护契约 ReparseableArchiveFile。只读查询,不触碰对象存储字节(字节 + 由调用方按需经 file_asset_storage 取)。 + + Args: + source_code: 来源实例编码(经收料执行单元行 source_code 关联)。 + now: 保留期判定时刻。 + Returns: + ReparseableArchiveFile 列表(archived_at 升序;无可重建归档为空表)。 + """ + return [ + ReparseableArchiveFile( + file_id=view.file_id, + storage_key=view.storage_key, + sha256=view.sha256, + file_version=movement_file_version(view.sha256), + archived_at=view.created_at, + original_filename=view.original_filename, + ) + for view in list_reparseable_inbound_files(source_code, now=now) + ] + def _extract_movement_rows( data: bytes, @@ -117,7 +186,7 @@ def _extract_movement_rows( header_row_index: 1-based 表头行;空则自动探测。 """ from openpyxl import load_workbook - from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index + from app.services.shipping_notice.onhand_snapshot import find_inventory_header_row_index wb = load_workbook(filename=BytesIO(data), data_only=True, read_only=True) try: @@ -172,4 +241,4 @@ def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str if codes and index < len(row): for code in codes: output[code] = row[index] - return output + return output \ No newline at end of file diff --git a/backend/app/services/in_transit_transfer/orchestrator.py b/backend/app/services/in_transit_transfer/orchestrator.py index ea03eb92..35869765 100644 --- a/backend/app/services/in_transit_transfer/orchestrator.py +++ b/backend/app/services/in_transit_transfer/orchestrator.py @@ -5,7 +5,8 @@ 依赖:models、status、date_policy、matching_service(编号生成/TransferDeps)。 逻辑:执行 Run 与匹配解耦(不回写 matching.run_id / confirmed_at);D8 异步拆分后 Run 初始态为 queued(prepare 段只建 Run+关联行+建单,worker 段置 executing); - 行归属由调用方按 scope 圈定(见 matching_service.scope_item_query)后显式传入, + 行归属由调用方圈定(出生翻转后 items 创建即绑定 matching_id,restore/执行 + 入口按匹配自有 items 圈行)后显式传入, 本模块只负责"建 Run + 关联选中行",已关联(run_id 非空)的行跳过。 """ @@ -58,7 +59,6 @@ def create_execution_run_for_items( source_codes_json=sorted({item.source_code for item in candidates}), counts_json={ "file_invoice_count": len(candidates), - "not_matured_count": 0, "matched_count": len(candidates), "executable_count": len(candidates), "blocked_count": 0, diff --git a/backend/app/services/in_transit_transfer/outbound_evidence_sync.py b/backend/app/services/in_transit_transfer/outbound_evidence_sync.py new file mode 100644 index 00000000..7775e9be --- /dev/null +++ b/backend/app/services/in_transit_transfer/outbound_evidence_sync.py @@ -0,0 +1,223 @@ +"""services/in_transit_transfer/outbound_evidence_sync.py + +用途:出站证据同步——出站回调 success 后把该来源最新可用出站归档按 + purpose='outbound' 已发布解析规则解析、以 record_kind='outbound' 幂等落档 + (transfer_movement_ledger),与 evidence_sync(入站专用,record_kind='inbound') + 完全对称;解析失败把 parse_failed 三列独立落到出站归档文件上(2026-10-16 + 出站落档桥补齐——此前出站链路止步于归档+状态投影,异动档恒无 outbound 行)。 +依赖:ledger_sync(sync_ledger_rows / RECORD_KIND_OUTBOUND / FileMeta / + movement_file_version)、 + evidence_sync(parse_archive_to_ledger_rows 解析组装单一口径 + + _detect_natural_key_collapses/_natural_key_collapse_event 坍缩守卫 + SyncOutcome)、 + movement_file_repository._extract_movement_rows(归档字节提取)、 + source_file_status.latest_usable_outbound_file(出站可用文件视图,当天新鲜度 + 口径)、freight_rpa.reports.queries(get_outbound_config / + mark_outbound_parse_failure / clear_outbound_parse_failure)、file_asset_storage、 + models、audit、db。 +逻辑:sync_outbound_source_rows 只 flush 不 commit(提交归属调用方,契约同入站 + sync_source_rows);sync_and_commit_for_outbound_callback 桥自行 commit + + 异常全吞(B3 桥隔离——出站归档主链路不得被落档失败波及),schema 类失败 + rollback 后把失败事实独立 commit 到当前可用文件(入站同款解析失败分层)。 + 规则门禁 fail-closed:无配置 / 未绑定规则 / 规则未发布 / purpose≠outbound + → no-op(None)——规则缺失不是文件错误,不落解析失败标记(与入站仓库 + latest_ready_file 门禁同口径)。cross_flag 交叉校验沿用 ledger_sync 既有 + 口径(当前仅 inbound 定义矛盾标志,outbound 行不计数)。 +""" + +from __future__ import annotations + +from datetime import datetime + +from app import db +from app.models import FreightRpaParsingProfile +from app.services.file_assets.storage import file_asset_storage +from app.services.freight_rpa.reports.queries import ( + clear_outbound_parse_failure, + get_outbound_config, + mark_outbound_parse_failure, +) +from app.services.in_transit_transfer.audit import build_transfer_audit_event +from app.services.in_transit_transfer.evidence_sync import ( + SyncOutcome, + _detect_natural_key_collapses, + _natural_key_collapse_event, + parse_archive_to_ledger_rows, +) +from app.services.in_transit_transfer.file_parser import MovementFileSchemaError +from app.services.in_transit_transfer.ledger_sync import ( + RECORD_KIND_OUTBOUND, + FileMeta, + movement_file_version, + sync_ledger_rows, +) +from app.services.in_transit_transfer.movement_file_repository import _extract_movement_rows +from app.services.in_transit_transfer.source_file_status import latest_usable_outbound_file + +_TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID" +# schema 类解析失败判据与入站桥同一口径(code 或异常类型)。 +_SCHEMA_FAILURE_CODES = (_TRANSFER_FILE_SCHEMA_INVALID,) + + +def _load_published_outbound_profile(source_code: str) -> FreightRpaParsingProfile | None: + """加载来源出站配置绑定的「已发布 purpose='outbound'」解析规则(fail-closed 门禁)。 + + 核心逻辑:出站配置(get_outbound_config,缺失=None)→ parsing_profile_id → + 规则行须 published 且 purpose='outbound'——与运行期入站取数门禁 + (movement_file_repository.latest_ready_file 的 published inbound 校验)同构。 + + Args: + source_code: 来源实例编码。 + Returns: + FreightRpaParsingProfile;任一环节缺失或门禁不符返回 None。 + """ + config = get_outbound_config(source_code) + if config is None or config.parsing_profile_id is None: + return None + profile = db.session.get(FreightRpaParsingProfile, config.parsing_profile_id) + if profile is None or profile.status != "published" or profile.purpose != "outbound": + return None + return profile + + +def sync_outbound_source_rows(*, source_code: str, now: datetime) -> SyncOutcome | None: + """解析来源最新可用出站归档并幂等落档(零外部调用,flush 不 commit)。 + + 【AI 触发时机】出站 RPA 回调桥(sync_and_commit_for_outbound_callback)调用; + 不要在匹配/重查链路调用(匹配从档圈定,不写档)。 + + Args: + source_code: 来源实例编码。 + now: 落档时间基准(插入/更新显式续 updated_at;文件新鲜度判定时刻)。 + Returns: + SyncOutcome;无可用出站文件或无 published outbound 规则返回 None + (该分支不触碰解析失败标记——没有成功解析的事实不得清除失败标记)。 + Raises: + MovementFileSchemaError: 行必填缺失/非法(schema 类失败原样上抛——桥内 + rollback + 落解析失败标记)。 + """ + file_view = latest_usable_outbound_file(source_code, now=now) + if file_view is None: + return None + profile = _load_published_outbound_profile(source_code) + if profile is None: + return None + definition = profile.definition_json or {} + + # [STEP 1] 归档字节 → 原始行(提取口径与运行期入站/清空重建同源)→ 档行 + # (parse_archive_to_ledger_rows 解析组装单一口径;schema 类失败原样上抛)。 + data = file_asset_storage.get_bytes(file_view.storage_key) + raw_rows = _extract_movement_rows( + data, + field_mapping=dict(definition.get("field_mapping") or {}), + sheet_name=str(definition.get("sheet_name") or "").strip() or None, + header_row_index=definition.get("header_row_index"), + ) + assembled = parse_archive_to_ledger_rows(source_code=source_code, rows=raw_rows) + + # [STEP 2] 幂等落档(record_kind='outbound');溯源文件三元组取当前可用归档。 + # file_version 走 movement_file_version:出站归档无独立版本列,戳与入站仓库、 + # 清空重建、匹配进度快照同一函数,避免再在此处自行拼接超长。 + outcome = sync_ledger_rows( + source_code=source_code, + record_kind=RECORD_KIND_OUTBOUND, + parsed_rows=assembled, + file_meta=FileMeta( + source_file_id=file_view.file_id, + file_version=movement_file_version(file_view.sha256), + file_sha256=file_view.sha256, + ), + now=now, + ) + # [档自然键坍缩守卫] 与入站同口径复检(检测按行级六成分、record_kind 声明进 + # 审计聚合键);仅实际落档时打事件,幂等重落不刷审计。 + collapses = _detect_natural_key_collapses(assembled) + if collapses and (outcome.inserted or outcome.updated): + for collapse in collapses: + db.session.add(_natural_key_collapse_event( + source_code=source_code, collapse=collapse, record_kind=RECORD_KIND_OUTBOUND)) + result = SyncOutcome( + source_code=source_code, + file_sha256=file_view.sha256 or "", + inserted=outcome.inserted, + updated=outcome.updated, + skipped=outcome.skipped, + sealed_skipped=outcome.sealed_skipped, + cross_flagged=outcome.cross_flagged, + ) + db.session.add(build_transfer_audit_event( + event_type="TRANSFER_EVIDENCE_SYNCED", + aggregate_type="transfer_source", + aggregate_id=source_code, + actor_type="system", + result="success", + after={ + "file_sha256": result.file_sha256, + "record_kind": RECORD_KIND_OUTBOUND, + "inserted": result.inserted, "updated": result.updated, + "skipped": result.skipped, "sealed_skipped": result.sealed_skipped, + "cross_flagged": result.cross_flagged, + }, + )) + # [解析失败分层] 同步成功 = 当前可用文件已成功解析:清除失败标记(若此前 + # 失败过),出站流状态投影随之恢复 ready。只 flush 不 commit。 + if file_view.parse_failed_at is not None: + clear_outbound_parse_failure(file_view.file_id) + return result + + +def sync_and_commit_for_outbound_callback(*, source_code: str, now: datetime) -> bool: + """出站回调桥专用入口:落档 + 自行 commit + 异常全吞(仅 warning 日志)。 + + 【AI 触发时机】出站 RPA 回调 success 终态落文件后由 + handle_outbound_report(outbound_report_handler)调用——桥是记账不是出站 + 链路的正确性依赖,任何异常不得向出站归档主链路传播(B3:必须自行 commit)。 + 【解析失败分层】失败路径先 rollback(桥隔离),仅 schema 类解析失败把失败 + 事实(parse_failed 三列)独立 commit 落到当前可用出站文件上;丢失的落档由 + 回调重试/出站重抓兜底。 + + Args: + source_code: 来源实例编码(出站单元行上的 source_code)。 + now: 落档时间基准。 + Returns: + True=落档成功或无事可做(无可用文件/无可用规则);False=落档失败 + (已记日志;schema 类失败尽力把解析失败标记落库并独立提交,标记失败 + 仅告警不影响返回)。 + """ + from flask import current_app + + try: + outcome = sync_outbound_source_rows(source_code=source_code, now=now) + # [桥隔离] sync_outbound_source_rows 只 flush 不 commit;桥由回调事实 + # 处理在归档 commit 之后独立调用,必须在此自行提交(B3 持久性教训)。 + db.session.commit() + if outcome is not None: + current_app.logger.info( + "TRANSFER_OUTBOUND_EVIDENCE_SYNC source=%s inserted=%s updated=%s skipped=%s sealed=%s cross=%s", + source_code, outcome.inserted, outcome.updated, + outcome.skipped, outcome.sealed_skipped, outcome.cross_flagged) + return True + except Exception as exc: # noqa: BLE001 —— 桥隔离:失败仅日志 + # [桥隔离] 落档崩溃绝不波及出站归档终态;丢失的落档由回调重试/重抓兜底。 + current_app.logger.warning( + "TRANSFER_OUTBOUND_EVIDENCE_SYNC_FAILED source=%s error=%s", source_code, exc) + db.session.rollback() + # [解析失败分层] rollback 之后再写标记;仅 schema 类失败落库——通用异常 + # (网络/DB 故障等)不是文件解析问题,不落标记。标记写入后独立 commit + # (落档数据已回滚,本次 commit 只持久化失败事实),仍返回 False。 + # 标记写入是尽力而为:再抛异常也必须吞掉(B3 优先),丢失标记由下次重试补。 + try: + code = getattr(exc, "code", None) or "" + if code in _SCHEMA_FAILURE_CODES or isinstance(exc, MovementFileSchemaError): + detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__ + file_view = latest_usable_outbound_file(source_code, now=now) + if file_view is not None: + mark_outbound_parse_failure( + file_view.file_id, + error_code=str(code or _TRANSFER_FILE_SCHEMA_INVALID), + error_message=str(detail)[:2000], + ) + db.session.commit() + except Exception as mark_exc: # noqa: BLE001 —— 桥隔离:标记失败仅日志 + current_app.logger.warning( + "TRANSFER_OUTBOUND_PARSE_MARK_FAILED source=%s error=%s", source_code, mark_exc) + return False diff --git a/backend/app/services/in_transit_transfer/outbound_report_handler.py b/backend/app/services/in_transit_transfer/outbound_report_handler.py new file mode 100644 index 00000000..d7a2a3d7 --- /dev/null +++ b/backend/app/services/in_transit_transfer/outbound_report_handler.py @@ -0,0 +1,161 @@ +""" +services/in_transit_transfer/outbound_report_handler.py + +用途:outbound 报表事实的调拨侧业务处理函数——出站归档终态 commit 后由 + dispatch_report_fact 投递的 ReportFact 只在此推进调拨自己的任务: + TransferSourceJob 等待态推进、出站排程收口。 +依赖:app.db、app.models(FreightRpaOutboundUnitRun——执行单元读取)、 + app.core.errors.ValidationError、freight_rpa.reports.facts(ReportFact / + require_report_kind——只消费事实契约,不 import freight_rpa 工作流)。 +逻辑:由组合根(app.create_app → in_transit_transfer.rpa_sinks.register_outbound_sinks) + 注册为 'outbound' kind 处理函数;freight_rpa.outbound.report_archive. + ingest_outbound_callback 在每个终态 db.session.commit() 之后经 + dispatch_report_fact 调入本函数。处理函数只改调拨自己的行; + 【不捕获异常】——任何失败原样外抛,归档文件已提交不回滚, + Worker 重试整笔回调即可补齐推进(先 commit 再投递的顺序契约)。 + 状态机字段与入站同一套:waiting_rpa_callback → file_ready / failed; + 无等待任务则 no-op;第二次调用该行已离开等待态,不再改(可重入)。 + 【STEP 4 出站证据同步 2026-10-16】success 事实把最新可用出站归档按 + purpose=outbound 规则解析、record_kind='outbound' 落异动档(与入站 + handle_inbound_report STEP 4 对称;桥内自吞异常并自行 commit)。 +""" + +from __future__ import annotations + +from datetime import datetime + +from app import db +from app.core.errors import ValidationError +from app.models import FreightRpaOutboundUnitRun, TransferSourceJob +from app.services.freight_rpa.reports.facts import ReportFact, require_report_kind + +_FILE_READY = 'file_ready' +_WAITING_RPA_CALLBACK = 'waiting_rpa_callback' +_FAILED = 'failed' + + +def _advance_waiting_source_job( + *, source_code: str, file_no: str | None = None, file_sha256: str | None = None, + callback_ok: bool = True, error_code: str | None = None, error_message: str | None = None, +) -> TransferSourceJob | None: + """按来源推进最新等待回调的调拨来源任务(与入站桥同一等待态字段)。 + + 核心逻辑:只改 status='waiting_rpa_callback' 的行;无匹配则不动作, + 避免回调迟到误推进其他阶段任务。success/有文件 → file_ready;否则 → failed。 + 本函数只 flush 不 commit,提交归属 handle_outbound_report。 + + Args: + source_code: 回调所属来源实例。 + file_no: 出站文件号(success 时)。 + file_sha256: 出站文件 sha256(success 时)。 + callback_ok / error_code / error_message: 回调终态。 + Returns: + 被推进的任务;无等待任务或已终态时返回 None。 + """ + job = ( + TransferSourceJob.query + .filter_by(source_code=source_code, status=_WAITING_RPA_CALLBACK) + .order_by(TransferSourceJob.id.desc()) + .first() + ) + if job is None: + return None + if callback_ok and file_no: + job.status = _FILE_READY + job.file_no = file_no + job.file_sha256 = file_sha256 + job.error_code = None + job.error_message = None + job.finished_at = datetime.utcnow() + else: + job.status = _FAILED + job.error_code = error_code or 'RPA_OUTBOUND_CALLBACK_FAILED' + job.error_message = error_message or 'outbound rpa callback failed' + job.finished_at = datetime.utcnow() + db.session.flush() + return job + + +def handle_outbound_report(fact: ReportFact) -> None: + """report_kind 必须是 outbound。ok 且 file_id 有值时把等待中的 TransferSourceJob 推进到 file_ready; + ok 为假时推进到 failed。没有 waiting_rpa_callback 行则 return。第二次调用时该行已离开等待态,不再改。 + + 核心逻辑: + [STEP 1] kind 门禁(fail-closed);[STEP 2] 推进等待中的来源任务(只改 + status='waiting_rpa_callback' 的行,无等待行返回 None);[STEP 3] + 推进结果必须在此提交;[STEP 4] success 事实触发出站证据同步 + (outbound_evidence_sync,record_kind='outbound',与入站 STEP 4 对称); + [STEP 5] 精确定位本次回调收尾的执行单元并回写出站排程进度、归集终态。 + 【不捕获异常】任何一步失败原样外抛供 Worker 重试(STEP 4 桥内自吞)。 + + Args: + fact: 终态已提交后由归档入口构造的报表事实(report_kind/source_code/ + file_id/sha256/ok/error_code/error_message/unit_run_id)。 + Returns: + None(推进/收口结果全部写库,不返回业务值)。 + Raises: + ValidationError: report_kind 非 outbound(误注册/误分发,fail-closed)。 + """ + # [STEP 1] kind 门禁:本函数只消费 outbound 事实。 + kind = require_report_kind(fact.report_kind) + if kind != 'outbound': + raise ValidationError( + f"handle_outbound_report only accepts outbound facts, got: {kind!r}", + code='SHIPPING.OUTBOUND_CALLBACK_INVALID', + details={'report_kind': fact.report_kind}, + ) + + # [STEP 2] 推进等待中的调拨来源任务:ok 且 file_id 有值 → file_ready; + # 否则 → failed。无等待行返回 None(调拨侧无行可改,直接结束推进分支)。 + if fact.ok and fact.file_id is not None: + advanced = _advance_waiting_source_job( + source_code=fact.source_code, + file_no=str(fact.file_id), + file_sha256=fact.sha256, + callback_ok=True, + ) + else: + advanced = _advance_waiting_source_job( + source_code=fact.source_code, + callback_ok=False, + error_code=fact.error_code, + error_message=fact.error_message, + ) + + # [STEP 3] 桥只 flush 不 commit:推进落库必须在此提交。 + if advanced is not None: + db.session.commit() + + # [STEP 4] 出站证据同步:success 事实(ok 且 file_id 有值)后把该来源最新 + # 可用出站归档按 purpose=outbound 规则解析、record_kind='outbound' 落异动档 + # (与入站 handle_inbound_report STEP 4 对称:按 ok 触发、不依赖等待任务存在; + # 桥内自吞异常并自行 commit,本处不包 try——文件已提交,Worker 重试即可补齐)。 + if fact.ok and fact.file_id is not None: + from app.services.in_transit_transfer.outbound_evidence_sync import ( + sync_and_commit_for_outbound_callback, + ) + + sync_and_commit_for_outbound_callback( + source_code=fact.source_code, now=datetime.utcnow(), + ) + + # [STEP 5] 出站排程收口:按 fact.unit_run_id 精确定位本次回调收尾的执行单元。 + schedule_run_id: int | None = None + if fact.unit_run_id is not None: + unit = db.session.get(FreightRpaOutboundUnitRun, int(fact.unit_run_id)) + if unit is None: + from app.core.errors import NotFoundError + + raise NotFoundError( + f"Outbound RPA unit not found: {fact.unit_run_id}", + details={'unit_run_id': fact.unit_run_id}, + ) + schedule_run_id = unit.schedule_run_id + if schedule_run_id: + from app.services.schedule.freight_rpa_outbound_finalize import ( + finalize_outbound_schedule_run_if_complete, + refresh_outbound_schedule_run_progress, + ) + + refresh_outbound_schedule_run_progress(schedule_run_id) + finalize_outbound_schedule_run_if_complete(schedule_run_id) diff --git a/backend/app/services/in_transit_transfer/outbound_trigger_service.py b/backend/app/services/in_transit_transfer/outbound_trigger_service.py new file mode 100644 index 00000000..0ca30b24 --- /dev/null +++ b/backend/app/services/in_transit_transfer/outbound_trigger_service.py @@ -0,0 +1,261 @@ +"""在途调拨出站 RPA 触发服务。 + +用途:为单个或多个来源触发出站 RPA 抓取(出站证据 = freight_rpa 出站 RPA 产物, + 复用货代出站 trigger 链路),不创建排程。按来源取站点、出站配置与登录连接 + (全部经 freight_rpa.reports.queries 只读入口),先落 RPA 单元运行行 + (awaiting_rpa,回调按 callback_id 查库可达),再装配出站 trigger unit 并 + 调用 write_outbound_export_batch_trigger 原子写 trigger。 +依赖:write_outbound_export_batch_trigger(默认 writer,freight_rpa.outbound.trigger_io)、 + freight_rpa.reports.queries(get_site / get_outbound_config / get_rpa_login_profile / + list_outbound_configured_source_codes——站点、配置与登录连接读取唯一权威)、db。 +逻辑:list_outbound_capable_source_codes 供排程 source_codes 留空时的缺省范围; + 一源一单元,query_parameters 原样下发;来源停用/出站配置缺失/登录连接缺失时 + fail-closed;写 trigger 失败把单元行标 failed 并 commit。 + trigger_outbound_rpa_batch 把多来源合并为一个 batch trigger 文件: + Worker 对单文件按 profile 分组共享一次浏览器会话,避免逐来源开/关浏览器。 + trigger unit 载荷键集与 Worker 契约(freight_rpa.outbound.v1)逐键对齐入站。 +""" + +from __future__ import annotations + +import uuid +from typing import Any, Callable + +from app.services.freight_rpa.outbound.trigger_io import ( + ACTION_OUTBOUND_EXPORT_BATCH, + SCHEMA, + write_outbound_export_batch_trigger, +) +from app.services.freight_rpa.reports.queries import ( + get_outbound_config, + get_rpa_login_profile, + get_site, + list_outbound_configured_source_codes, +) + +RouteTriggerWriter = Callable[..., str | None] + + +def _write_outbound_trigger(run_no: str, units: list[dict[str, Any]], payload: dict[str, Any] | None = None) -> str | None: + """适配出站 IO 的 meta 形参,对外保持与入站 writer 相同的 payload= 协议。""" + return write_outbound_export_batch_trigger(run_no, units, meta=payload) + + +def _build_trigger_unit( + *, source_code: str, business_date: str, reason: str, +) -> dict[str, Any]: + """装配单来源出站 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。 + + 核心逻辑:一源一单元,query_parameters 原样下发;空条件表示 Worker 走页面默认。 + 站点(get_site)/ 出站配置(get_outbound_config)/ 登录连接 + (get_rpa_login_profile)读取改经 freight_rpa.reports.queries 只读入口;装配出的 + unit 载荷键集与 Worker 契约逐键保持不变(快照含配置行主键与版本)。 + """ + site = get_site(source_code) + if site is None or not site.enabled: + raise RuntimeError(f'source not enabled: {source_code}') + config = get_outbound_config(source_code) + if config is None: + raise RuntimeError(f'outbound config missing: {source_code}') + profile = get_rpa_login_profile(source_code) + if profile is None or not profile.enabled: + raise RuntimeError(f'outbound source profile unavailable: {source_code}') + query_parameters = [ + dict(item) for item in (config.query_parameters_json or []) if isinstance(item, dict) + ] + snapshot = { + 'config_id': config.config_id, 'config_version': config.config_version, + 'connector_type': site.connector_type, + 'report_path_json': config.report_path_json or {}, + 'query_parameters_json': query_parameters, + 'warehouse_id': None, 'rpa_profile_id': profile.profile_id, + } + return { + 'source_id': site.source_id, + 'callback_id': f'outbound:{uuid.uuid4().hex}', + 'source_code': site.source_code, + 'connector_type': site.connector_type, + 'warehouse_id': None, + 'rpa_profile_id': profile.profile_id, + 'rpa_profile_code': profile.profile_code, + 'login_url': profile.login_url, + 'login_config': dict(profile.login_config or {}), + 'credential_envelope': { + 'username_ciphertext': profile.username_ciphertext, + 'password_ciphertext': profile.password_ciphertext, + }, + 'report_path_json': dict(snapshot.get('report_path_json') or {}), + 'query_parameters_json': list(query_parameters), + 'config_snapshot': snapshot, + 'business_date': business_date, + 'reason': reason, + } + + +def list_outbound_capable_source_codes() -> list[str]: + """列出可产出出站文件的启用来源实例(已配置出站报表的启用站点)。 + + 用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——出站文件 + 只能来自已配置出站报表的站点,与货代出站 RPA 排程的站点口径一致。 + Returns: + 按 source_code 排序的来源编码列表;无匹配站点时为空列表。 + """ + return list_outbound_configured_source_codes() + + +def trigger_outbound_rpa( + *, + source_code: str, + business_date: str, + reason: str = 'transfer_retry_outbound', + writer: RouteTriggerWriter | None = None, +) -> dict[str, Any]: + """触发一次来源出站 RPA 抓取(先落单元行再写 trigger,保证回调可达)。 + + Args: + source_code: 来源实例编码。 + business_date: 业务日期。 + reason: 触发原因(写入 trigger)。 + writer: 触发写者;缺省复用 write_outbound_export_batch_trigger(payload= 协议)。 + Returns: + {"ok": True, "callback_id": ..., "trigger_path": ...} 或 + {"ok": False, "error_code": ...}(配置缺失 / 触发目录不可用)。 + """ + try: + unit_payload = _build_trigger_unit(source_code=source_code, business_date=business_date, reason=reason) + except RuntimeError as exc: + return {"ok": False, "error_code": "RPA_OUTBOUND_CONFIG_MISSING", "error_message": str(exc)} + + # [STEP 1] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库, + # 不落行则回调必然 404(与排程路径 / 入站按需触发同一模式)。 + from app import db + from app.models.freight_rpa_outbound_report import FreightRpaOutboundUnitRun as FreightRpaOutboundUnitRun + + unit = FreightRpaOutboundUnitRun( + # 按需触发无 ScheduleRun:schedule_run_id 保持 NULL(列可空;FK 禁止 0 占位)。 + source_id=unit_payload['source_id'], + source_code=unit_payload['source_code'], + connector_type=unit_payload['connector_type'], + warehouse_id=unit_payload.get('warehouse_id'), + callback_id=unit_payload['callback_id'], + status='awaiting_rpa', + config_snapshot_json=dict(unit_payload['config_snapshot']), + ) + db.session.add(unit) + db.session.flush() + unit_payload['unit_run_id'] = unit.id + + # [STEP 2] 原子写 trigger;目录不可用则单元标 failed(fail-closed,不留永久 awaiting)。 + run_no = f"TRIG-{source_code}-{uuid.uuid4().hex[:8].upper()}" + writer_fn = writer or _write_outbound_trigger + path = writer_fn(run_no, [unit_payload], payload={ + 'schema_version': SCHEMA, + 'action': ACTION_OUTBOUND_EXPORT_BATCH, + 'source_code': source_code, + 'business_date': business_date, + 'reason': reason, + }) + if not path: + unit.status = 'failed' + unit.error_code = 'RPA_OUTBOUND_TRIGGER_UNAVAILABLE' + unit.error_message = 'outbound trigger directory unavailable' + db.session.commit() + return {"ok": False, "error_code": "RPA_OUTBOUND_TRIGGER_UNAVAILABLE"} + + # [STEP 3] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。 + unit.trigger_snapshot_json = unit_payload + db.session.commit() + return {"ok": True, "callback_id": unit_payload['callback_id'], "trigger_path": path} + + +def trigger_outbound_rpa_batch( + *, + source_codes: list[str], + business_date: str, + reason: str = 'transfer_retry_outbound', + writer: RouteTriggerWriter | None = None, +) -> dict[str, Any]: + """批量触发多来源出站 RPA:全部有效来源合并写**一个** batch trigger 文件。 + + 【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个出站来源编码时调用; + 行级单来源重试仍走 trigger_outbound_rpa(一源一文件语义不变)。 + + 核心逻辑:逐来源装配 unit(来源级隔离——配置缺失/停用跳过并记录,不炸整批); + 有效 units 先各落一行 RPA 单元运行行再一次性 write_outbound_export_batch_trigger + 原子落盘。Worker 对单文件按 profile 分组共享一次浏览器会话串行导出。 + 入站 batch 的 parse_failed 本地重解析不在此复用——来源文件状态投影仅覆盖入站归档。 + + Args: + source_codes: 来源实例编码列表(去重保序;空串自动剔除)。 + business_date: 业务日期。 + reason: 触发原因(写入 trigger payload)。 + writer: 触发写者;缺省复用 write_outbound_export_batch_trigger。 + + Returns: + {"ok": True/False, "triggered": bool, "results": [...], "trigger_path"?/「error_code」?}。 + ok=本次请求产生了主效果(写盘成功);triggered=是否写了 batch trigger; + results 逐来源携带真实结果。 + """ + from app import db + from app.models.freight_rpa_outbound_report import FreightRpaOutboundUnitRun as FreightRpaOutboundUnitRun + + codes = list(dict.fromkeys(str(code).strip() for code in source_codes if str(code).strip())) + results: list[dict[str, Any]] = [] + units: list[FreightRpaOutboundUnitRun] = [] + unit_payloads: list[dict[str, Any]] = [] + + # [STEP 1] 逐来源装配 unit;单源失败跳过不阻断整批。 + for code in codes: + try: + unit_payloads.append(_build_trigger_unit(source_code=code, business_date=business_date, reason=reason)) + except RuntimeError as exc: + results.append({ + 'source_code': code, 'ok': False, + 'error_code': 'RPA_OUTBOUND_CONFIG_MISSING', 'error_message': str(exc), + }) + + if not unit_payloads: + db.session.commit() + return {"ok": False, "triggered": False, "error_code": "RPA_OUTBOUND_NO_TRIGGERABLE_SOURCE", "results": results} + + # [STEP 2] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库(与单来源同模式)。 + for payload in unit_payloads: + unit = FreightRpaOutboundUnitRun( + source_id=payload['source_id'], + source_code=payload['source_code'], + connector_type=payload['connector_type'], + warehouse_id=payload.get('warehouse_id'), + callback_id=payload['callback_id'], + status='awaiting_rpa', + config_snapshot_json=dict(payload['config_snapshot']), + ) + db.session.add(unit) + units.append(unit) + db.session.flush() + for unit, payload in zip(units, unit_payloads): + payload['unit_run_id'] = unit.id + + # [STEP 3] 一个 batch trigger 原子落盘;目录不可用则本批单元全部标 failed(不留永久 awaiting)。 + run_no = f"TRIG-BATCH-{uuid.uuid4().hex[:8].upper()}" + writer_fn = writer or _write_outbound_trigger + path = writer_fn(run_no, unit_payloads, payload={ + 'schema_version': SCHEMA, + 'action': ACTION_OUTBOUND_EXPORT_BATCH, + 'business_date': business_date, + 'reason': reason, + 'source_codes': [payload['source_code'] for payload in unit_payloads], + }) + if not path: + for unit in units: + unit.status = 'failed' + unit.error_code = 'RPA_OUTBOUND_TRIGGER_UNAVAILABLE' + unit.error_message = 'outbound trigger directory unavailable' + db.session.commit() + return {"ok": False, "triggered": False, "error_code": "RPA_OUTBOUND_TRIGGER_UNAVAILABLE", "results": results} + + # [STEP 4] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。 + for unit, payload in zip(units, unit_payloads): + unit.trigger_snapshot_json = payload + results.append({'source_code': unit.source_code, 'ok': True}) + db.session.commit() + return {"ok": True, "triggered": True, "trigger_path": path, "results": results} diff --git a/backend/app/services/in_transit_transfer/quantity.py b/backend/app/services/in_transit_transfer/quantity.py index 43bf9d48..4f7d30a1 100644 --- a/backend/app/services/in_transit_transfer/quantity.py +++ b/backend/app/services/in_transit_transfer/quantity.py @@ -1,6 +1,6 @@ """在途调拨严格数量门禁。 -用途:实现"收料数量 == 外部系统 账面库存 才可执行"的精确匹配规则, +用途:实现"异动数量 == 外部系统 账面库存 才可执行"的精确匹配规则, 禁止部分调拨、数量容差与隐式截断。 依赖:标准库 decimal。 逻辑:所有比较基于 Decimal 精确语义;非法数量(0/负数/非数字)在解析层拒绝。 @@ -18,11 +18,11 @@ MATCH_INVENTORY_NOT_FOUND = "blocked_inventory_not_found" class QuantityValidationError(ValueError): - """收料数量非法(0、负数、非数字)。""" + """入站数量非法(0、负数、非数字)。""" -def validate_receipt_quantity(value: Any) -> Decimal: - """校验并归一化收料数量。 +def validate_inbound_quantity(value: Any) -> Decimal: + """校验并归一化入站数量。 Args: value: 数字或数字字符串。 @@ -34,9 +34,9 @@ def validate_receipt_quantity(value: Any) -> Decimal: try: quantity = Decimal(str(value)) except (InvalidOperation, ValueError) as exc: - raise QuantityValidationError(f"invalid receipt quantity: {value!r}") from exc + raise QuantityValidationError(f"invalid inbound quantity: {value!r}") from exc if quantity <= 0: - raise QuantityValidationError(f"receipt quantity must be positive: {value!r}") + raise QuantityValidationError(f"inbound quantity must be positive: {value!r}") return quantity @@ -45,17 +45,17 @@ def strict_quantities_equal(left: Any, right: Any) -> bool: return Decimal(str(left)) == Decimal(str(right)) -def classify_quantity_match(receipt_quantity: Any, external_quantity: Any | None) -> str: +def classify_quantity_match(inbound_quantity: Any, external_quantity: Any | None) -> str: """按严格相等规则分类数量匹配结果。 Args: - receipt_quantity: 收料数量。 + inbound_quantity: 入站异动数量。 external_quantity: 外部系统 账面库存;None 表示无库存。 Returns: 'executable' | 'blocked_quantity_mismatch' | 'blocked_inventory_not_found'。 """ if external_quantity is None: return MATCH_INVENTORY_NOT_FOUND - if strict_quantities_equal(receipt_quantity, external_quantity): + if strict_quantities_equal(inbound_quantity, external_quantity): return MATCH_EXECUTABLE return MATCH_QUANTITY_MISMATCH diff --git a/backend/app/services/in_transit_transfer/receipt_file_gate.py b/backend/app/services/in_transit_transfer/receipt_file_gate.py deleted file mode 100644 index 7602ec74..00000000 --- a/backend/app/services/in_transit_transfer/receipt_file_gate.py +++ /dev/null @@ -1,69 +0,0 @@ -"""在途调拨收料归档文件的可用性门禁(单一事实来源)。 - -用途:把「一份 ShippingReceiptReportFile 是否可用于调拨链路」的判定收敛为本模块, - 供来源状态投影(source_file_status)、匹配取文件(movement_file_repository)、 - 收料文件下载(api/in_transit_transfer)三处统一引用,防止口径漂移。 -依赖:models(ShippingReceiptReportFile)、date_policy(业务日 UTC 窗口换算)。 -逻辑:可用 = 未清理 且 当天(Asia/Shanghai 业务日)抓取 且 未过保留期; - 已失效(expired)= 可用核心的反相(未清理 且 [保留期已到 或 非当天抓取])。 - 两函数同核推导,规则文本只存在一处。 -""" - -from __future__ import annotations - -from datetime import datetime - -from sqlalchemy import ColumnElement, and_, not_, or_ - -from app.models import ShippingReceiptReportFile -from app.services.in_transit_transfer.date_policy import business_date_utc_window - - -def _fresh_and_retention_valid(now: datetime) -> ColumnElement: - """新鲜度 + 保留期核心条件(不含清理态,供可用/失效两函数共用)。""" - window_start, window_end = business_date_utc_window(now) - return and_( - ShippingReceiptReportFile.created_at >= window_start, - ShippingReceiptReportFile.created_at < window_end, - or_( - ShippingReceiptReportFile.archive_expires_at.is_(None), - ShippingReceiptReportFile.archive_expires_at > now, - ), - ) - - -def usable_receipt_file_condition(*, now: datetime | None = None) -> ColumnElement: - """返回「当前可用的收料归档文件」SQL 条件。 - - 判定:未清理(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取 - + 未过保留期(archive_expires_at 为空视为长期有效)。匹配复用与下载 - 只认可用文件;隔日/过期文件一律 fail-closed,交由上游触发重抓。 - - Args: - now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。 - Returns: - 可直接并入 .filter() 的单个 SQLAlchemy 条件。 - """ - now = now or datetime.utcnow() - return and_( - ShippingReceiptReportFile.archive_deleted_at.is_(None), - _fresh_and_retention_valid(now), - ) - - -def expired_receipt_file_condition(*, now: datetime | None = None) -> ColumnElement: - """返回「文件仍在但已失效」SQL 条件(来源状态投影 expired 的依据)。 - - 判定:未清理 且 可用核心不成立(保留期已到 或 非当天业务日抓取)。 - 命中即提示用户重试重抓,不报 ready,也不等待保留期清理任务落位。 - - Args: - now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。 - Returns: - 可直接并入 .filter() 的单个 SQLAlchemy 条件。 - """ - now = now or datetime.utcnow() - return and_( - ShippingReceiptReportFile.archive_deleted_at.is_(None), - not_(_fresh_and_retention_valid(now)), - ) diff --git a/backend/app/services/in_transit_transfer/retry_service.py b/backend/app/services/in_transit_transfer/retry_service.py index 12cd4b31..7bc96dd5 100644 --- a/backend/app/services/in_transit_transfer/retry_service.py +++ b/backend/app/services/in_transit_transfer/retry_service.py @@ -1,22 +1,33 @@ -"""在途调拨人工重试服务(基于冻结文件仅重新查询 外部系统)。 +"""在途调拨人工重试服务(基于冻结快照仅重新查询 外部系统)。 用途:对允许的异常项执行人工重试,只创建新 Attempt 并重新查询 外部系统; Run 创建后禁止重新抓取 RPA(文件冻结);result_unknown 只读拒绝。 -依赖:models、capability_client、quantity、status、audit、matching_service.TransferDeps。 +依赖:models、capability_client、quantity、status、audit、matching_service.TransferDeps、 + scope_rules.parse_scope_rules、scope_rules.record_kinds_of。 逻辑:重试不写 外部系统、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断; 重查即续新鲜度——每次重检显式刷新行 updated_at(执行门禁行级 TTL 的续期机制); - 重查前置兜底对齐(STEP 0,同 run_matching):两个批量重查入口先 align_scope_rows - 补救落地同步失败/迟到的证据,再圈行重查(待处理池后门不得基于过期证据作答); + 【2026-10-14 对档对账(ADR 0001/规格 §9)】requery_items(匹配号入口)前置 + 「对档重圈 → 与本匹配自有 items 对账」:档新增记录 → 补建 item(绑同一 + 匹配);档证据变 → 刷新 item 证据并重置待查;档记录消失 → item 失效隔离 + (沿用 blocked_file_removed 语义退出主视图)。圈档复用匹配创建的同一函数 + (_circle_ledger_records:固定条件单点实现;记录类型取 + record_kinds_of(快照 scope_rules))+ 同一快照规则(scope_json), + D17 占用互斥排除「其他匹配」的有效占用(本匹配自有 items 不构成占用); + 终态行(已执行/人工关闭/取消/在流)绝不触碰——已执行行不得被证据刷新 + 复活(防同批档证据更新促成二次写 ERP)。 + 原 align_scope_rows 文件兜底对齐已随出生翻转退役(重查不再对文件对账); 库存查询按组织批量(2026-09-29):全部重查/恢复/单据重试入口统一经 _recheck_items_batch——路由解析按 external_org 分组,一组一次 capabilities.query_stock(与执行链写前复查同形态),行级评估 / Attempt / 审计 / 新鲜度续期保持单行粒度;N 行重查 = 每组织 1 次外部调用, 禁止回退逐行单查(N 行 N 次调用会打崩外部系统); - file_removed 失效行不可重查:匹配号圈行路径由 scope 谓词排除,按 id 直取与 + 路由解析叠加类型仓库定义(resolve_warehouse:fixed 覆盖映射档); + file_removed 失效行不可重查:匹配号圈行路径由对账口径排除,按 id 直取与 单行入口由资格门禁 _gate_retryable_item 兜底拒绝(拒绝逻辑单点闭环,消失 证据不可用旧库存翻回可执行); 交易单位唯一来源=ERP 库存行 stock_unit(img09):重查命中且数量一致但 ERP - 未给单位 → blocked_missing_unit(不落 ready,单位不得以文件值顶替)。 + 未给单位 → blocked_missing_unit(不落 ready,单位不得以文件值顶替); + 批号查询目标经行所属匹配快照的转换规则派生(item_external_lot_no)。 """ from __future__ import annotations @@ -34,20 +45,26 @@ from app.models import TransferAttempt, 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.capability_client import StockTarget -from app.services.in_transit_transfer.date_policy import business_date_now -from app.services.in_transit_transfer.evidence_sync import align_scope_rows from app.services.in_transit_transfer.matching_service import ( RESULT_EXTERNAL_QUERY_FAILED, RESULT_EXECUTABLE, RESULT_FILE_REMOVED, RESULT_MISSING_UNIT, + RESULT_ROUTE_NOT_RESOLVED, RouteMapping, TransferDeps, - scope_item_query, + _born_item_from_record, + _circle_ledger_records, + _dedupe_ledger_records_for_item_birth, + _item_grain_of_ledger, + _resolve_route_with_config, + _SYNC_TERMINAL_STATUSES, + item_external_lot_no, ) -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.scope_rules import parse_scope_rules, record_kinds_of from app.services.in_transit_transfer.serializers import DOCUMENT_STATUS_GROUPS +from app.services.in_transit_transfer.transfer_type import resolve_transfer_type RETRY_KIND_EXTERNAL_RECHECK = "external_recheck" RETRY_KIND_RPA_REFETCH = "rpa_refetch" @@ -62,6 +79,38 @@ _RETRYABLE_STATUSES = { logger = logging.getLogger(__name__) +def _route_for_item(deps: TransferDeps, item: TransferInvoiceItem) -> RouteMapping: + """行级路由解析:映射档解析 + 行所属匹配类型的仓库定义(mapped/fixed)叠加。 + + Args: + deps: 注入依赖(route_resolver=映射档解析)。 + item: 重查行(matching_id 关联的匹配快照携带 transfer_type)。 + Returns: + RouteMapping(fixed 角色按类型配置覆盖仓库/法人;无匹配或快照无类型码 + 时透传映射档——存量兼容兜底)。 + Raises: + RouteNotResolvedError / ValidationError: 映射档不可解析或类型配置脏数据 + (fail-closed,调用方按行级前置解析失败隔离)。 + """ + config = None + if item.matching_id is not None and item.matching is not None: + scope = item.matching.scope_json if isinstance(item.matching.scope_json, dict) else {} + type_code = scope.get("transfer_type") + if type_code: + # 存量重跑/重查不要求类型仍启用(「停用后存量不受影响」)。 + config = resolve_transfer_type(type_code, require_enabled=False) + if config is None: + return deps.route_resolver.resolve( + source_code=item.source_code, invoice_no=item.invoice_no, + warehouse_code=item.movement_warehouse_code or "", + ) + return _resolve_route_with_config( + deps, config, + source_code=item.source_code, invoice_no=item.invoice_no, + warehouse_code=item.movement_warehouse_code or "", + ) + + def _gate_retryable_item(item_id: int) -> TransferInvoiceItem: """单行重查资格门禁(单行与按 id 批量入口共用的拒绝单点)。 @@ -72,7 +121,7 @@ def _gate_retryable_item(item_id: int) -> TransferInvoiceItem: Raises: NotFoundError: item 不存在。 ValidationError: result_unknown 只读 / 状态不可重试 / file_removed 行 - 不可重查(消失证据不可恢复:证据行的源单已从最新收料文件中消失, + 不可重查(消失证据不可恢复:证据行的源单已从最新入站文件中消失, 重查只会用外部系统旧库存把行翻回可执行,唯一出口=人工关闭 / 等重新同步恢复该行)。 """ @@ -139,7 +188,7 @@ def _degrade_recheck_row(item: TransferInvoiceItem, *, attempt: TransferAttempt, def _apply_recheck_outcome(item: TransferInvoiceItem, *, attempt: TransferAttempt, - before_status: str, receipt_qty: Decimal, stock_row, + before_status: str, inbound_qty: Decimal, stock_row, operation_id: str, request_id: str | None) -> str: """行级评估收口:账面对照落状态/结果码/外部数量/单位,关闭 Attempt 并写审计。 @@ -147,14 +196,14 @@ def _apply_recheck_outcome(item: TransferInvoiceItem, *, attempt: TransferAttemp item: 重查行(Attempt 已创建并 flush)。 attempt: 该行本次 external_query Attempt(running 态)。 before_status: 重查前状态(审计 before)。 - receipt_qty: 行收料数量(严格相等判定的基准)。 + inbound_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: + if stock_qty is None or classify_quantity_match(inbound_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" item.result_message = "external inventory not found" if stock_qty is None else "strict quantity mismatch" @@ -232,19 +281,17 @@ def _recheck_items_batch( 行未被触碰、未建 Attempt;批量入口转为该行 ok=False,单行入口原样上抛 保持历史 fail-closed 行为)。 """ - # [STEP 1] 行级前置解析(行级隔离):路由解析 + 收料数量解析,失败行原位 - # 跳过、不拖垮整批;行仓库字段刷新为本次解析值——查询与后续执行写路径必须 - # 用同一仓库值:行上旧值可能来自更早配置(路由已漂移),也可能为空(如 - # blocked_missing_unit 行在路由解析前被阻断)。 + # [STEP 1] 行级前置解析(行级隔离):路由解析(叠加行所属匹配类型的仓库 + # 定义,fixed 覆盖映射档)+ 异动数量解析,失败行原位跳过、不拖垮整批;行仓库 + # 字段刷新为本次解析值——查询与后续执行写路径必须用同一仓库值:行上旧值可能 + # 来自更早配置(路由已漂移),也可能为空(如 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) + route = _route_for_item(deps, item) + inbound_qty = Decimal(item.movement_quantity) except Exception as exc: # noqa: BLE001 —— 行级隔离:路由漂移/缺失/脏数量只影响该行 row_errors[item.id] = exc logger.warning( @@ -255,7 +302,7 @@ def _recheck_items_batch( 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)) + resolved.append((item, route, inbound_qty)) # [STEP 2] 按组织分组(同写前复查的 external_org 分组口径):同组行共享 # 一次批量查询,N 行 = 每组织 1 次外部调用。 @@ -271,7 +318,7 @@ def _recheck_items_batch( operation_id = f"op-{uuid.uuid4().hex[:12]}" attempts: dict[int, TransferAttempt] = {} before_statuses: dict[int, str] = {} - for item, route, receipt_qty in entries: + for item, route, inbound_qty in entries: item.attempt_no += 1 before_statuses[item.id] = item.status attempts[item.id] = TransferAttempt( @@ -280,19 +327,20 @@ def _recheck_items_batch( 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), + "quantity": str(inbound_qty), }, ) db.session.add(attempts[item.id]) db.session.flush() try: - # [外部形态] 查询目标与回查同用 WTP→HOW 派生批号(movement_contract.external_lot_no)。 + # [外部形态] 查询目标与回查同用行所属匹配快照转换规则派生批号 + # (item_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], + lot_no=item_external_lot_no(item), + ) for item, route, _inbound_qty in entries], ) except Exception as exc: # noqa: BLE001 # [降级] 外部系统网关/绑定故障是组级事实:组内各行统一降级为 @@ -303,22 +351,22 @@ def _recheck_items_batch( "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: + for item, route, inbound_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: + for item, route, inbound_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), + lot_no=item_external_lot_no(item), ) 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, + inbound_qty=inbound_qty, stock_row=stock_row, operation_id=operation_id, request_id=request_id, ) db.session.commit() @@ -380,18 +428,6 @@ def requery_items_by_ids( ids = [int(x) for x in (item_ids or []) if x is not None] if not ids: raise ValidationError("item_ids is required", code="TRANSFER.BATCH_ITEMS_REQUIRED") - # [口径] 受影响来源=按 id 查回行的 source_code 去重(先查行→对齐→再重查)。 - source_rows = ( - db.session.query(TransferInvoiceItem.source_code) - .filter(TransferInvoiceItem.id.in_(ids)) - .all() - ) - affected_sources = sorted({(code or "").strip() for (code,) in source_rows}) - # [兜底对齐] 落地同步失败/迟到的静默补救:重查前先保证行对齐最新文件。 - # 对齐可能重写行集(证据变化重置回待查、消失行复现恢复),必须先于任何 - # 重查读取执行,否则待处理池后门会基于过期证据放行旧库存。 - align_scope_rows(source_codes=affected_sources, deps=deps, - business_date=str(business_date_now()), now=datetime.utcnow()) results_by_id: dict[int, dict] = {} eligible: list[TransferInvoiceItem] = [] for item_id in ids: @@ -411,19 +447,179 @@ def requery_items_by_ids( 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 圈定全部/指定的可重查行,按组织批量查询并刷新。 +def _reconcile_items_with_ledger( + matching, *, deps: TransferDeps, wanted_doc_nos: list[str] | None, +) -> None: + """对档重圈并与本匹配自有 items 对账(出生翻转后重查的前置步骤,规格 §9)。 - 圈行口径与匹配卡实时视图同源(scope_item_query:来源+收料日期区间+调拨类型), - 行归属 matching_id 不参与——行归属解耦后行不随匹配迁移,视图能看到的历史行 - (matching_id 指向旧匹配)必须同样可被本次匹配的重查触达,否则出现「卡片提示 - 重查、重查却查不到行」的死锁(2026-09-24 修复)。 + 核心逻辑:[STEP 1] 按匹配快照规则(scope_rules + 来源 + 异动日期范围)圈定 + 档记录——复用匹配创建的同一圈档函数 _circle_ledger_records(固定条件单点 + 实现,杜绝谓词漂移)。记录类型取 record_kinds_of(已解析的快照 rules) + (仅没有范围规则、也没有类型对象的调用点才显式只圈 inbound)。 + 排除已执行封存、其他匹配的有效占用(D17;本匹配自有 + items 不构成占用)。[STEP 2] 三分类对账(**终态守卫:SUCCESS/DUPLICATE_ + SUCCESS/MANUALLY_CLOSED/CANCELLED/EXECUTING/RESULT_UNKNOWN 行绝不触碰—— + 已执行行不得被证据刷新复活,否则同批档证据更新会促成二次写 ERP**): + ①档有行无(自有 items 未覆盖的圈中记录)→ 补建 item(绑同一匹配; + 类型配置缺失/路由不可解析时行级落 blocked(可解释、可重查),不影响 + 其余行——口径与 _route_for_item 的逐行兜底对齐); + ②档证据变(数量/批号/仓库与 item 不一致)→ 刷新 item 证据并重置待查 + (旧库存是对旧数量查的,作废),展示字段照常刷新(仅非终态行); + ③自有 item 的档记录消失(防御:档缺席不删,仅异常清理场景)→ 失效隔离 + (blocked_file_removed,退出主视图,恢复走人工恢复;仅非终态行)。 + 只 flush 不 commit(随调用方事务:requery_items 末尾 _recheck_items_batch + 的组粒度提交兜底持久化)。 Args: - matching_no: 匹配编号(经 scope_json 圈定行集)。 + matching: 匹配 ORM 行(scope_json 快照 + 自有 items)。 + deps: 注入依赖(路由解析)。 + wanted_doc_nos: 可选单号过滤(invoice_nos 限定重查范围时同步约束补圈)。 + """ + from app.core.errors import ValidationError as _ValidationError + from app.services.in_transit_transfer.evidence_sync import SYNC_RESULT_PENDING + from app.services.in_transit_transfer.transfer_type_config_service import ( + get_by_code as get_type_config, + ) + + scope = matching.scope_json if isinstance(matching.scope_json, dict) else {} + rules = parse_scope_rules(scope.get("scope_rules")) + now = datetime.utcnow() + + # [STEP 1] 快照规则圈档(共享圈档函数:与匹配创建同一固定条件实现)。 + sources = [str(code) for code in (scope.get("source_codes") or [])] + records: list = [] + if sources: + records = _dedupe_ledger_records_for_item_birth( + _circle_ledger_records( + source_codes=sources, + rules=rules, + movement_date_from=scope.get("movement_date_from"), + movement_date_to=scope.get("movement_date_to"), + record_kinds=record_kinds_of(rules), + exclude_occupied_by_matching_id=matching.id, + doc_nos=wanted_doc_nos, + ) + ) + + # 类型配置(仓库定义):从快照类型码读现行配置(存量不要求启用)。 + # [逐行容错] 类型缺失/脏配置不炸整次重查:config=None 时补建行走行级阻断 + # (口径与 _route_for_item 的逐行兜底对齐;类型只有停用没有删除,正常不触发)。 + type_code = str(scope.get("transfer_type") or "") + config = None + if type_code: + try: + config = get_type_config(type_code) + except _ValidationError: + config = None + + # [终态守卫·占用面] own_by_record 收全部自有行(含终态):档记录已被本匹配 + # 任一行(含已执行行)绑定时按「档有行有」处理——终态绑定永不补建第二个 item + #(否则已执行记录将以新待查行复活 → 二次写 ERP)。同 grain 兄弟档亦视为已绑。 + own_by_record = { + item.ledger_record_id: item + for item in matching.items + if item.ledger_record_id is not None + } + own_grains = { + (str(item.source_code or ""), str(item.invoice_no or ""), + str(item.material_no or ""), str(item.movement_date or "")) + for item in matching.items + } + for record in records: + item = own_by_record.get(record.id) + if item is None: + grain = _item_grain_of_ledger(record) + if grain in own_grains: + # 同 grain 已有自有 item(兄弟档 / 择优后的另一 ledger_record_id)。 + continue + # [①补建] 档新增记录:绑同一匹配(D17:本匹配占用即成立)。 + route = None + route_failed = False + try: + if config is None: + raise _ValidationError(f"transfer type config missing: {type_code}") + route = _resolve_route_with_config( + deps, config, + source_code=record.source_code, invoice_no=record.doc_no, + warehouse_code=record.warehouse_code or "", + ) + except Exception: # noqa: BLE001 —— 类型缺失/路由失败:行级阻断降级,不影响其余行 + route = None + route_failed = True + born = _born_item_from_record( + record, matching_id=matching.id, + route=route, now=now, + ) + if route_failed: + # [行级阻断] 可解释、可重查(配置/路由修复后重查即恢复)。 + born.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value + born.result_code = RESULT_ROUTE_NOT_RESOLVED + born.result_message = ( + f"transfer type config missing: {type_code}" if config is None + else f"route not resolved for source {record.source_code}" + ) + db.session.add(born) + own_grains.add(grain) + continue + # [②证据对账] 只比对异动事实(数量/批号/仓库);名称/规格为展示字段。 + # [终态守卫·刷新面] 终态行(已执行/人工关闭/取消/在流)绝不触碰(含 + # updated_at)——旧 evidence_sync「终态行绝不触碰/不复活」冻结约束在 + # 翻转后的延续(防同批档证据更新促成二次写 ERP);非终态行照常对账。 + if item.status in _SYNC_TERMINAL_STATUSES: + continue + evidence_changed = ( + str(item.movement_quantity) != str(record.quantity or "") + or (item.lot_no or "") != (record.lot_no or "") + or (item.movement_warehouse_code or "") != (record.warehouse_code or "") + ) + item.material_name = record.material_name or "" + item.specification = record.specification or "" + if evidence_changed: + item.movement_quantity = str(record.quantity or "0") + item.lot_no = record.lot_no or "" + item.movement_warehouse_code = record.warehouse_code or "" + # 重置待查:旧库存是对旧数量查的,作废;取数时刻同步置空。 + item.status = status_machine.TransferStatus.MATCHING.value + item.result_code = SYNC_RESULT_PENDING + item.result_message = None + item.external_quantity = None + item.inventory_checked_at = None + item.updated_at = now + + # [③失效隔离] 自有 item 的档记录不存在(档缺席不删,正常不触发;防御 + # 异常清理)→ 沿用 blocked_file_removed 语义退出主视图(仅非终态行; + # 终态行的既定事实永不改写)。 + from app.models import TransferMovementLedger as _Ledger + + record_ids = {record.id for record in records} + for item in matching.items: + if item.status in _SYNC_TERMINAL_STATUSES: + continue + if item.ledger_record_id is None or item.ledger_record_id in record_ids: + continue + if db.session.get(_Ledger, item.ledger_record_id) is None: + item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value + item.result_code = RESULT_FILE_REMOVED + item.result_message = "ledger record removed" + item.updated_at = now + db.session.flush() + + +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: + """批量重查 外部系统 库存:先对档对账(补建/刷新/隔离),再圈自有可重查行批量刷新。 + + 【2026-10-14 对档对账(规格 §9)】原 scope_item_query 实时圈行退役——行由 + 匹配创建时从档圈定且创建即绑定,重查改为:按匹配快照规则对档重圈 → 与本 + 匹配自有 items 对账(档新增记录补建 / 档证据变刷新重置 / 档记录消失隔离)→ + 自有可重查行按组织批量重查。重查只对账本匹配自己的 items,不受 D17 圈档 + 互斥影响(自有占用不排除)。 + + Args: + matching_no: 匹配编号(scope_json 快照供圈档规则/类型码)。 deps: 注入依赖(capabilities = 外部系统网关客户端)。 - invoice_nos: 可选,按 Invoice(单号)过滤;缺省 = 该 scope 全部可重查行。 + invoice_nos: 可选,按 Invoice(单号)过滤;缺省 = 该匹配全部可重查行 + (对账补圈同受此约束,避免范围外补建)。 actor_id / request_id: 审计上下文。 Returns: {"matching_no", "total", "results": [{invoice_no, item_id, ok, status|error}]}; @@ -434,21 +630,16 @@ def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str matching = TransferMatching.query.filter_by(matching_no=matching_no).first() if matching is None: raise NotFoundError("matching not found", code="TRANSFER.MATCH_NOT_FOUND") - # [口径一致] 受影响来源=scope_json 的 source_codes(与 scope_item_query 圈行同源, - # 提取口径同 matching_service.scope_item_query:非 dict 视为空 scope)。 - scope = matching.scope_json if isinstance(matching.scope_json, dict) else {} - affected_sources = sorted({str(code) for code in (scope.get("source_codes") or [])}) - # [兜底对齐] 落地同步失败/迟到的静默补救:重查前先保证行对齐最新文件。 - # 对齐可能重写行集(证据变化重置回待查、消失行复现恢复),必须先于 scope - # 圈行执行,否则重查会圈到过期行、基于过期证据放行旧库存。 - align_scope_rows(source_codes=affected_sources, deps=deps, - business_date=str(business_date_now()), now=datetime.utcnow()) - # [口径统一] 圈行必须与匹配卡视图同谓词(scope:来源+日期区间+类型前缀)—— - # 行归属解耦后 matching_id 停留在首次创建值,按它圈行会漏掉全部存量行。 - # file_removed 行排除:消失证据不可重查恢复(唯一出口=人工关闭/出清)。 + wanted = [str(x or "").strip() for x in (invoice_nos or []) if str(x or "").strip()] + + # [STEP A] 对档对账(补建/刷新/隔离,只 flush;持久化随后续组粒度提交)。 + _reconcile_items_with_ledger(matching, deps=deps, wanted_doc_nos=wanted or None) + + # [STEP B] 自有可重查行(阻断/可执行)批量重查;file_removed 隔离行排除 + # (消失证据不可重查恢复,唯一出口=人工关闭/等对档修复)。 query = ( - scope_item_query(matching) - .filter( + TransferInvoiceItem.query.filter( + TransferInvoiceItem.matching_id == matching.id, TransferInvoiceItem.status.in_(_RETRYABLE_STATUSES), or_( TransferInvoiceItem.result_code.is_(None), @@ -456,7 +647,6 @@ def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str ), ) ) - wanted = [str(x or "").strip() for x in (invoice_nos or []) if str(x or "").strip()] if wanted: query = query.filter(TransferInvoiceItem.invoice_no.in_(wanted)) items = query.order_by(TransferInvoiceItem.id).all() diff --git a/backend/app/services/in_transit_transfer/rpa_sinks.py b/backend/app/services/in_transit_transfer/rpa_sinks.py new file mode 100644 index 00000000..c1e41b0c --- /dev/null +++ b/backend/app/services/in_transit_transfer/rpa_sinks.py @@ -0,0 +1,149 @@ +""" +services/in_transit_transfer/rpa_sinks.py + +用途:入站 / 出站 RPA 回调与报表事实的组合根注册——把 /api/freight-rpa/inbound-*、 + outbound-* 接到 freight_rpa 归档入口与本包事实处理函数(调拨是唯一业务消费方)。 +依赖:freight_rpa.common.callback_sinks、freight_rpa.reports.dispatch、 + freight_rpa.inbound/outbound.report_archive、schedule.freight_rpa_*_finalize、 + inbound_report_handler / outbound_report_handler、models。 +逻辑:由 app.create_app 调用 register_inbound_sinks / register_outbound_sinks(幂等)。 + batch-ready:归档单元终态后立即尝试排程 finalize(文件返回= RPA/排程结束), + 再投递事实;事实处理(证据同步等)失败不得挡排程收口。不 import shipping_notice。 +""" + +from __future__ import annotations + +import logging +from typing import Any, Callable + +_LOG = logging.getLogger(__name__) + +_INBOUND_UNIT_TERMINAL = frozenset({'success', 'empty', 'failed', 'cancelled'}) +_OUTBOUND_UNIT_TERMINAL = frozenset({'success', 'empty', 'failed', 'cancelled'}) + + +def _success_data_envelope(handler: Callable[[dict[str, Any]], dict[str, Any]]) -> Callable[..., dict[str, Any]]: + """旧 inbound/outbound 进度端点 envelope:{'success':True,'data':业务结果}。""" + + def _sink(**payload: Any) -> dict[str, Any]: + return {'success': True, 'data': handler(payload)} + + return _sink + + +def _try_finalize_inbound_schedule_after_unit(payload: dict[str, Any]) -> None: + """单元已落终态后按文件返回收口入站排程;解析/证据失败不得阻塞。 + + 核心逻辑:用 callback_id 定位单元;仅当 status 已终态且挂了 schedule_run_id + 时 refresh + finalize_if_complete(幂等)。异常只记日志,不回滚已提交单元。 + """ + callback_id = str(payload.get('callback_id') or '').strip() + if not callback_id: + return + try: + from app.models import FreightRpaInboundUnitRun + from app.services.schedule.freight_rpa_inbound_finalize import ( + finalize_inbound_schedule_run_if_complete, + refresh_inbound_schedule_run_progress, + ) + + unit = FreightRpaInboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none() + if unit is None or unit.schedule_run_id is None: + return + if str(unit.status or '') not in _INBOUND_UNIT_TERMINAL: + return + refresh_inbound_schedule_run_progress(int(unit.schedule_run_id)) + finalize_inbound_schedule_run_if_complete(int(unit.schedule_run_id)) + except Exception as exc: # noqa: BLE001 - 排程收口失败不得淹没归档结果 + _LOG.warning( + 'inbound schedule finalize after unit terminal failed callback_id=%s: %s', + callback_id, + exc, + exc_info=True, + ) + + +def _try_finalize_outbound_schedule_after_unit(payload: dict[str, Any]) -> None: + """单元已落终态后按文件返回收口出站排程;解析/证据失败不得阻塞。""" + callback_id = str(payload.get('callback_id') or '').strip() + if not callback_id: + return + try: + from app.models import FreightRpaOutboundUnitRun + from app.services.schedule.freight_rpa_outbound_finalize import ( + finalize_outbound_schedule_run_if_complete, + refresh_outbound_schedule_run_progress, + ) + + unit = FreightRpaOutboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none() + if unit is None or unit.schedule_run_id is None: + return + if str(unit.status or '') not in _OUTBOUND_UNIT_TERMINAL: + return + refresh_outbound_schedule_run_progress(int(unit.schedule_run_id)) + finalize_outbound_schedule_run_if_complete(int(unit.schedule_run_id)) + except Exception as exc: # noqa: BLE001 - 排程收口失败不得淹没归档结果 + _LOG.warning( + 'outbound schedule finalize after unit terminal failed callback_id=%s: %s', + callback_id, + exc, + exc_info=True, + ) + + +def _inbound_batch_ready_sink(**payload: Any) -> dict[str, Any]: + """入站 batch-ready:归档 →(单元终态后)排程收口 → 返回;事实投递异常仍尽量收口排程。""" + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback + + try: + data = ingest_inbound_callback(payload) + return {'success': True, 'data': data} + finally: + # 单元终态已 commit 后,无论事实处理是否抛错,都按文件返回尝试排程 finalize。 + _try_finalize_inbound_schedule_after_unit(payload) + + +def _outbound_batch_ready_sink(**payload: Any) -> dict[str, Any]: + """出站 batch-ready:归档 →(单元终态后)排程收口 → 返回。""" + from app.services.freight_rpa.outbound.report_archive import ingest_outbound_callback + + try: + data = ingest_outbound_callback(payload) + return {'success': True, 'data': data} + finally: + _try_finalize_outbound_schedule_after_unit(payload) + + +def register_inbound_sinks() -> None: + """注册全部 inbound 进度 sink 与 inbound 事实处理函数(幂等)。 + + 核心逻辑:inbound-batch-ready 走归档+文件返回即排程 finalize;unit/batch-progress 挂 + schedule.freight_rpa_inbound_finalize;事实处理函数挂 handle_inbound_report(证据/ + 调拨推进;排程收口已在 batch-ready 侧完成,handler 内 finalize 仍幂等兜底)。 + """ + from app.services.freight_rpa.common.callback_sinks import register_sink + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report + from app.services.schedule import freight_rpa_inbound_finalize + + register_sink('inbound-batch-ready', _inbound_batch_ready_sink) + register_sink('inbound-unit-progress', _success_data_envelope(freight_rpa_inbound_finalize.mark_inbound_unit_processing)) + register_sink('inbound-batch-progress', _success_data_envelope(freight_rpa_inbound_finalize.report_inbound_batch_progress)) + register_report_handler('inbound', handle_inbound_report) + + +def register_outbound_sinks() -> None: + """注册全部 outbound 进度 sink 与 outbound 事实处理函数(幂等)。 + + 核心逻辑:outbound-batch-ready 走归档+文件返回即排程 finalize;unit/batch-progress 挂 + schedule.freight_rpa_outbound_finalize;事实处理函数挂 handle_outbound_report。 + """ + from app.services.freight_rpa.common.callback_sinks import register_sink + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report + from app.services.schedule import freight_rpa_outbound_finalize + + register_sink('outbound-batch-ready', _outbound_batch_ready_sink) + register_sink('outbound-unit-progress', _success_data_envelope(freight_rpa_outbound_finalize.mark_outbound_unit_processing)) + register_sink('outbound-batch-progress', _success_data_envelope(freight_rpa_outbound_finalize.report_outbound_batch_progress)) + register_report_handler('outbound', handle_outbound_report) diff --git a/backend/app/services/in_transit_transfer/scope_rules.py b/backend/app/services/in_transit_transfer/scope_rules.py new file mode 100644 index 00000000..5b0a1893 --- /dev/null +++ b/backend/app/services/in_transit_transfer/scope_rules.py @@ -0,0 +1,127 @@ +"""services/in_transit_transfer/scope_rules.py + +用途:调拨类型范围规则引擎——受控字段白名单上的「字段+匹配方式+值列表」规则, + 规则间 AND、规则内多值 OR;内存谓词与 SQL 编译双形态共用同一解析结果, + 供匹配创建圈档、重查对账、管理页校验三处单一口径。 +依赖:app.core.errors.ValidationError;SQLAlchemy Select(编译形态)。 +逻辑:parse 校验词表/匹配方式/值非空 → ScopeRule 元组;evaluate 逐规则 AND、 + 逐值 OR(prefix/contains 大小写不敏感);apply_scope_filters 生成等价 SQL; + record_kinds_of 从 record_kind 范围规则推导证据流(入站/出站)。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Mapping, Sequence + +from sqlalchemy import Select, and_, or_, func +from app.core.errors import ValidationError + +# 受控字段词表(封闭可扩展;新增字段须同步管理页下拉与 technical.md)。 +SCOPE_FIELDS: frozenset[str] = frozenset({ + "source_code", "doc_no", "warehouse_code", "storage_code", "lot_no", + "movement_date", "record_kind", "in_out_flag", "order_type", "odm_id", + "odm_name", "carton_id", "pallet_id", "material_code", "doc_nature", + "movement_type", "reason_code", "partner_code", +}) + +_MATCHES = ("prefix", "equals", "contains", "in") +_RECORD_KINDS = ("inbound", "outbound") + + +@dataclass(frozen=True) +class ScopeRule: + """单条范围规则:field 字段 / match 匹配方式 / values 值列表(规则内 OR)。""" + + field: str + match: str + values: tuple[str, ...] + + +def parse_scope_rules(raw: list[dict] | None) -> tuple[ScopeRule, ...]: + """校验并解析范围规则 JSON(管理页保存与匹配快照共用)。 + + Args: + raw: [{"field", "match", "values"}];空列表/None 合法(=不限,由调用方决定是否放行)。 + Returns: + ScopeRule 元组。 + Raises: + ValidationError: 字段不在 SCOPE_FIELDS、match 非法、values 空/非字符串。 + """ + rules: list[ScopeRule] = [] + for item in raw or []: + field, match = str(item.get("field", "")), str(item.get("match", "")) + values = item.get("values") or [] + if field not in SCOPE_FIELDS: + raise ValidationError(f"unknown scope field: {field}", code="TRANSFER.SCOPE_RULE_INVALID", details={"field": field}) + if match not in _MATCHES or not values or not all(isinstance(v, str) and v.strip() for v in values): + raise ValidationError(f"invalid scope rule: {field}/{match}", code="TRANSFER.SCOPE_RULE_INVALID", details={"field": field, "match": match}) + rules.append(ScopeRule(field=field, match=match, values=tuple(v.strip() for v in values))) + return tuple(rules) + + +def _hit(value: str | None, rule: ScopeRule) -> bool: + text = str(value or "").strip().upper() + if not text: + return False + if rule.match == "prefix": + return text.startswith(tuple(v.upper() for v in rule.values)) + if rule.match == "equals": + return text in {v.upper() for v in rule.values} + if rule.match == "contains": + return any(v.upper() in text for v in rule.values) + return text in {v.upper() for v in rule.values} # in + + +def record_kinds_of(rules: tuple[ScopeRule, ...]) -> tuple[str, ...]: + """从范围规则推导调拨类型需要的证据流(入站/出站)。 + + 核心逻辑:筛 field=record_kind 的规则;无则默认双轨。多条规则时,各规则 + 允许的 inbound/outbound 集合(与 evaluate 同口径 _hit)逐条取交集;结果按 + inbound→outbound 顺序输出,交集为空则返回空元组。 + + Args: + rules: parse_scope_rules 产出的 ScopeRule 元组。 + Returns: + 仅含 inbound/outbound 的去重元组。 + """ + kind_rules = [rule for rule in rules if rule.field == "record_kind"] + if not kind_rules: + return _RECORD_KINDS + allowed: set[str] | None = None + for rule in kind_rules: + rule_allowed = {kind for kind in _RECORD_KINDS if _hit(kind, rule)} + allowed = rule_allowed if allowed is None else allowed & rule_allowed + if not allowed: + return () + return tuple(kind for kind in _RECORD_KINDS if kind in allowed) + + +def evaluate_scope(record: Mapping[str, Any], rules: Sequence[ScopeRule]) -> bool: + """内存求值:规则间 AND、规则内多值 OR(匹配/测试/小数据场景)。""" + return all(_hit(record.get(rule.field), rule) for rule in rules) + + +def apply_scope_filters(query: Select, model: type, rules: Sequence[ScopeRule]) -> Select: + """SQL 编译(与 evaluate_scope 同口径):圈档与重查对账共用,防谓词漂移。""" + clauses = [] + for rule in rules: + col = getattr(model, rule.field) + upper = func.upper(col) + if rule.match == "prefix": + clauses.append(or_(*(upper.like(f"{v.upper()}%") for v in rule.values))) + elif rule.match == "equals": + clauses.append(upper.in_([v.upper() for v in rule.values])) + elif rule.match == "contains": + clauses.append(or_(*(upper.contains(v.upper()) for v in rule.values))) + else: + clauses.append(upper.in_([v.upper() for v in rule.values])) + return query.filter(and_(*clauses)) if clauses else query + + +def scope_rules_note(rules: Sequence[ScopeRule]) -> str: + """范围规则审计说明(写 scope_json 旁路人读字段)。""" + parts = [] + for rule in rules: + parts.append(f"{rule.field} {rule.match} {'|'.join(rule.values)}") + return " AND ".join(parts) diff --git a/backend/app/services/in_transit_transfer/serializers.py b/backend/app/services/in_transit_transfer/serializers.py index 4d7286f2..f14ff3b3 100644 --- a/backend/app/services/in_transit_transfer/serializers.py +++ b/backend/app/services/in_transit_transfer/serializers.py @@ -12,7 +12,7 @@ from __future__ import annotations from typing import Any -from app.services.in_transit_transfer.movement_contract import external_lot_no +from app.services.in_transit_transfer.matching_service import item_external_lot_no # --------------------------------------------------------------------------- # 单状态 → 展示分组映射(Task 17:首页「已执行」区块统计口径) @@ -41,11 +41,9 @@ def serialize_summary(summary) -> dict[str, Any]: "matching_id": summary.matching_id, "status": summary.status, "business_date": summary.business_date, - "eligible_receipt_date_to": summary.eligible_receipt_date_to, "expires_at": summary.expires_at, "counts": { "file_invoice_count": summary.counts.file_invoice_count, - "not_matured_count": summary.counts.not_matured_count, "matched_count": summary.counts.matched_count, "executable_count": summary.counts.executable_count, "blocked_count": summary.counts.blocked_count, @@ -74,7 +72,7 @@ def serialize_item(item) -> dict[str, Any]: "specification": item.specification, "invoice_no": item.invoice_no, "lot_no": item.lot_no, - "receipt_date": item.receipt_date, + "movement_date": item.movement_date, "from_warehouse": item.from_warehouse, "from_quantity": str(item.from_quantity) if item.from_quantity is not None else None, "to_warehouse": item.to_warehouse, @@ -94,6 +92,8 @@ def serialize_item(item) -> dict[str, Any]: "checked_at": item.checked_at, "stale": item.stale, "file_current": item.file_current, + # 出生匹配的调拨类型 code。可调拨明细跨类型混排时前端据此显示类别名称。 + "transfer_type": item.transfer_type, } @@ -137,7 +137,7 @@ def serialize_order(doc, items: list) -> dict[str, Any]: items: 单挂接行集(TransferInvoiceItem 列表,调用方保证顺序)。 Returns: - 单投影 dict(8 键):{doc_no, receipt_date, from_warehouse, to_warehouse, + 单投影 dict(8 键):{doc_no, movement_date, from_warehouse, to_warehouse, status, erp_document_no, error_message, lines}。 """ # 延迟引用 execution_service 的行聚合(模块级互相引用会循环导入; @@ -149,11 +149,11 @@ def serialize_order(doc, items: list) -> dict[str, Any]: name_by_key: dict[tuple[str, str, str, str], str] = {} reason_by_key: dict[tuple[str, str, str, str], str] = {} for item in ordered: - # [外部形态] join 键与 _build_order_lines 聚合键同形(批号 WTP→HOW 派生), - # 否则 WTP 前缀行的品名/原因投影 lookup 会 miss。 + # [外部形态] join 键与 _build_order_lines 聚合键同形(批号经行所属匹配 + # 快照转换规则派生),否则 WTP 前缀行的品名/原因投影 lookup 会 miss。 key = ( str(item.material_no or "").strip(), - external_lot_no(item.lot_no), + item_external_lot_no(item), str(item.from_warehouse or "").strip(), str(item.to_warehouse or "").strip(), ) @@ -166,7 +166,7 @@ def serialize_order(doc, items: list) -> dict[str, Any]: reason_by_key[key] = message return { "doc_no": doc.doc_no, - "receipt_date": doc.receipt_date, + "movement_date": doc.movement_date, "from_warehouse": doc.from_warehouse, "to_warehouse": doc.to_warehouse, "status": doc.status, @@ -174,7 +174,7 @@ def serialize_order(doc, items: list) -> dict[str, Any]: "error_message": doc.error_message, "lines": [ { - # 行级溯源收料通知号(2026-09-29 契约扩充,随 ERP 写入行同款口径 + # 行级溯源来源单号(2026-09-29 契约扩充,随 ERP 写入行同款口径 # 透传):业务上一行恒对应一张 invoice,前端明细表首列展示。 "invoice_no": line["invoice_no"], "material_no": line["material_no"], @@ -212,7 +212,7 @@ def serialize_executed_order(doc, items: list) -> dict[str, Any]: "submit_timestamp": doc.submit_timestamp, "status": base["status"], "status_group": order_status_group(doc.status), - "receipt_date": base["receipt_date"], + "movement_date": base["movement_date"], "from_warehouse": base["from_warehouse"], "to_warehouse": base["to_warehouse"], "erp_document_no": base["erp_document_no"], @@ -227,10 +227,10 @@ def serialize_executed_order(doc, items: list) -> dict[str, Any]: # 批号保持文件证据原形态(raw 原则);展示侧拨出批号由前端 # deriveBatchNo 镜像转换(与匹配卡/可调拨明细/待办池同规则)。 "lot_no": item.lot_no or "", - "quantity": item.receipt_quantity, + "quantity": item.movement_quantity, "unit": item.unit or "", } - # 行序对齐统一规则第三键(2026-09-29):同单内收料日期/数据源恒同 + # 行序对齐统一规则第三键(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 3aba05bf..59296ab7 100644 --- a/backend/app/services/in_transit_transfer/source_file_status.py +++ b/backend/app/services/in_transit_transfer/source_file_status.py @@ -1,161 +1,551 @@ -"""在途调拨来源收料文件状态投影服务。 +"""在途调拨来源证据文件状态投影服务。 -用途:只读货代收料链路已有事实(ShippingReceiptRpaUnitRun + ShippingReceiptReportFile), - 按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 是否解析失败 / - 无文件待触发",供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。 -依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile)、 - receipt_file_gate(可用/失效判定单一事实来源)。 -逻辑:按来源取该来源最新收料执行单元;命中可用门禁(当天业务日抓取且未过期, - 见 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,事务归属调用方)。 +用途:只读货代入站/出站链路已有事实(执行单元行 + freight_rpa 归档文件), + 按来源实例与记录类型投影"是否有 ready 文件 / 是否抓取中 / 是否失败 / + 是否解析失败 / 无文件待触发 / 出站未配置",供 /sources 接口与前端门禁使用。 + 调拨不维护独立抓取状态表(低耦合)。 +依赖:freight_rpa.reports.queries(入站最新可用归档 / 失效存在性 / + get_outbound_config,以及解析失败标记的只读写入口);入站与出站执行单元行、 + 出站归档文件模型;date_policy.business_date_utc_window(出站文件新鲜度与 + 入站可用条件同口径)。 +逻辑:resolve_source_file_status 按 record_kind 分流,缺省 inbound,既有调用方 + 不传记录类型时返回值不变。入站顺序:可用文件 → ready,但 parse_failed_at + 非空 → parse_failed;进行中单元 → fetching;最新单元空数据 → no_data; + 最新单元失败终态 → failed;文件仍在但已失效 → expired;否则 → none。 + 出站先查 get_outbound_config,缺失 → unconfigured;有配置则对出站文件表与 + FreightRpaOutboundUnitRun 走同一顺序。列表接口走 + resolve_source_file_statuses:同一顺序一次性投影全部来源,查询次数不随 + 来源个数增长。record/clear_inbound_parse_failure 仍是入站解析失败标记的 + 兼容薄壳(按主键委托 queries.mark/clear,只 flush 不 commit,事务归属调用方)。 """ from __future__ import annotations +from dataclasses import dataclass from datetime import datetime +from typing import Any, Callable -from app import db -from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun -from app.services.in_transit_transfer.receipt_file_gate import ( - expired_receipt_file_condition, - usable_receipt_file_condition, +from sqlalchemy import and_, not_, or_ + +from app.core.errors import ValidationError +from app.models.freight_rpa_inbound_report import ( + FreightRpaInboundReportFile, + FreightRpaInboundUnitRun, ) +from app.models.freight_rpa_outbound_report import ( + FreightRpaOutboundReportConfig, + FreightRpaOutboundReportFile, + FreightRpaOutboundUnitRun, +) +from app.services.freight_rpa.reports.queries import ( + clear_inbound_parse_failure as _clear_parse_failure_by_id, + expired_inbound_file_condition, + get_outbound_config, + has_expired_inbound_file, + latest_usable_inbound_file, + mark_inbound_parse_failure as _mark_parse_failure_by_id, + usable_inbound_file_condition, +) +from app.services.in_transit_transfer.date_policy import business_date_utc_window RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing') FAILED_UNIT_STATUSES = ('failed', 'cancelled') -# 空数据(no_receipt_data):抓取成功但当日无收料记录,属业务结果而非故障, -# 独立投影 no_data 供前端如实展示(2026-10-08:曾误并入 failed 致无法分辨真失败)。 +# 空数据(RPA empty 回调契约值,shipping_notice 域术语保留):抓取成功但当日无记录, +# 属业务结果而非故障,独立投影 no_data 供前端如实展示(2026-10-08:曾误并入 failed 致无法分辨真失败)。 NO_DATA_UNIT_STATUSES = ('empty',) +_RECORD_KINDS = ('inbound', 'outbound') -def resolve_source_file_status(*, source_code: str) -> dict: - """返回某来源的收料文件状态投影。 +@dataclass(frozen=True) +class _FileFact: + """批量投影用的文件身份,字段与单来源文件视图中参与状态判断的部分一致。""" - 失效判定(不依赖保留期清理任务落位,与匹配取文件/下载同口径,见 - receipt_file_gate):保留期已到 或 非当前业务日(Asia/Shanghai)抓取。 + file_id: int + original_filename: str + sha256: str + parse_failed_at: datetime | None - Returns: - {"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...}, - file_status ∈ {'ready', 'parse_failed', 'fetching', 'failed', 'no_data', 'expired', 'none'}; - parse_failed 表示文件仍可用但解析失败:has_ready_file=False, - 仍带 file_no/file_sha256 便于诊断与前端提示。 + +@dataclass(frozen=True) +class _UnitFact: + """批量投影用的执行单元,只保留状态判断需要的 status。""" + + status: str + + +@dataclass(frozen=True) +class _OutboundFileView: + """出站归档文件只读视图,字段与入站 InboundFileView 对齐,供同一投影顺序读取。""" + + file_id: int + source_code: str + sha256: str + storage_key: str + original_filename: str + created_at: datetime + parse_failed_at: datetime | None = None + + +def _outbound_fresh_and_retention_valid(now: datetime): + """出站归档的新鲜度 + 保留期条件,列与入站 _fresh_and_retention_valid 同口径。 + + 核心逻辑:业务日窗口用 date_policy.business_date_utc_window(与 queries 内联 + 数学一致);archive_expires_at 为空视为长期有效。 """ + window_start, window_end = business_date_utc_window(now) + return and_( + FreightRpaOutboundReportFile.created_at >= window_start, + FreightRpaOutboundReportFile.created_at < window_end, + or_( + FreightRpaOutboundReportFile.archive_expires_at.is_(None), + FreightRpaOutboundReportFile.archive_expires_at > now, + ), + ) + + +def _outbound_file_view(report: FreightRpaOutboundReportFile) -> _OutboundFileView: + """把出站归档 ORM 行映射为冻结只读视图。""" + return _OutboundFileView( + file_id=report.id, + source_code=report.unit_run.source_code, + sha256=report.sha256, + storage_key=report.storage_key, + original_filename=report.original_filename, + created_at=report.created_at, + parse_failed_at=report.parse_failed_at, + ) + + +def latest_usable_outbound_file( + source_code: str, + *, + now: datetime | None = None, +) -> _OutboundFileView | None: + """返回某来源当前可用的出站归档只读视图,最新优先。 + + 用途:出站证据流状态投影取文件身份;口径与 latest_usable_inbound_file 相同 + (未删除 + 当天业务日抓取 + 未过期),不读取对象存储字节。 + + 核心逻辑:经出站执行单元行的 source_code 过滤,按 created_at/id 倒序取第一条。 + + Args: + source_code: 来源实例编码(写在 FreightRpaOutboundUnitRun.source_code 上)。 + now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。 + Returns: + _OutboundFileView;无可用文件返回 None。 + """ + now = now or datetime.utcnow() report = ( - ShippingReceiptReportFile.query - .join(ShippingReceiptReportFile.unit_run) + FreightRpaOutboundReportFile.query + .join(FreightRpaOutboundReportFile.unit_run) .filter( - ShippingReceiptReportFile.unit_run.has(source_code=source_code), - usable_receipt_file_condition(), + FreightRpaOutboundReportFile.unit_run.has(source_code=source_code), + FreightRpaOutboundReportFile.archive_deleted_at.is_(None), + _outbound_fresh_and_retention_valid(now), ) - .order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc()) + .order_by(FreightRpaOutboundReportFile.created_at.desc(), FreightRpaOutboundReportFile.id.desc()) .first() ) - if report is not None: - # 解析失败分层:文件本身可用(当天抓取未过期未清理)但解析失败, - # 不得当 ready 放行,单独投影 parse_failed 并保留文件身份供诊断。 - if report.parse_failed_at is not None: + if report is None: + return None + return _outbound_file_view(report) + + +def has_expired_outbound_file(source_code: str, *, now: datetime | None = None) -> bool: + """返回某来源是否存在未删除但已失效的出站归档(expired 投影依据)。 + + 用途:出站状态投影在无可用文件、无进行中/终态单元之后,判断是否因隔日旧文件 + 或保留期已到而提示重抓。只读不写。 + + 核心逻辑:未删除且新鲜度+保留期不成立,与 has_expired_inbound_file 同核。 + + Args: + source_code: 来源实例编码。 + now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。 + Returns: + 存在失效但未清理的出站归档 → True;否则 False。 + """ + now = now or datetime.utcnow() + expired = ( + FreightRpaOutboundReportFile.query + .join(FreightRpaOutboundReportFile.unit_run) + .filter( + FreightRpaOutboundReportFile.unit_run.has(source_code=source_code), + FreightRpaOutboundReportFile.archive_deleted_at.is_(None), + not_(_outbound_fresh_and_retention_valid(now)), + ) + .first() + ) + return expired is not None + + +def _empty_status(file_status: str) -> dict: + """没有可用文件身份时的投影字典。""" + return {'file_status': file_status, 'has_ready_file': False, 'file_no': None, 'file_sha256': None} + + +def _status_from_facts( + *, + file_view: Any | None, + active_unit: Any | None, + latest_unit: Any | None, + expired: bool, +) -> dict: + """按既定优先级把已取到的文件与单元事实收成状态字典。 + + 核心逻辑:可用文件(解析失败优先于 ready)→ 进行中单元 → 最新单元空数据 → + 最新单元失败终态 → 失效文件 → none。单来源与批量投影共用,避免两条路径 + 各写一套优先级。 + + Args: + file_view: 可用文件视图;须有 original_filename、file_id、parse_failed_at、sha256。 + 没有可用文件时为 None。 + active_unit: 仍在进行的执行单元;没有时为 None。只要求对象存在。 + latest_unit: id 最大的执行单元;没有时为 None。须有 status。 + expired: 是否仍有未清理的失效归档。 + Returns: + file_status 字典,键为 file_status / has_ready_file / file_no / file_sha256。 + """ + if file_view is not None: + file_no = file_view.original_filename or str(file_view.file_id) + # 解析失败分层:文件本身可用但解析失败,不得当 ready,保留文件身份供诊断。 + if file_view.parse_failed_at is not None: return { 'file_status': 'parse_failed', 'has_ready_file': False, - 'file_no': report.original_filename or str(report.id), - 'file_sha256': report.sha256, + 'file_no': file_no, + 'file_sha256': file_view.sha256, } return { 'file_status': 'ready', 'has_ready_file': True, - 'file_no': report.original_filename or str(report.id), - 'file_sha256': report.sha256, + 'file_no': file_no, + 'file_sha256': file_view.sha256, } - - active_unit = ( - ShippingReceiptRpaUnitRun.query - .filter_by(source_code=source_code) - .filter(ShippingReceiptRpaUnitRun.status.in_(RUNNING_UNIT_STATUSES)) - .order_by(ShippingReceiptRpaUnitRun.id.desc()) - .first() - ) if active_unit is not None: - return {'file_status': 'fetching', 'has_ready_file': False, 'file_no': None, 'file_sha256': None} - - latest_unit = ( - ShippingReceiptRpaUnitRun.query - .filter_by(source_code=source_code) - .order_by(ShippingReceiptRpaUnitRun.id.desc()) - .first() - ) + return _empty_status('fetching') if latest_unit is not None and latest_unit.status in NO_DATA_UNIT_STATUSES: - # 空数据:抓取成功但当日无收料记录——如实投影 no_data,不得与抓取失败混淆。 - return {'file_status': 'no_data', 'has_ready_file': False, 'file_no': None, 'file_sha256': None} + # 空数据:抓取成功但当日无记录——如实投影 no_data,不得与抓取失败混淆。 + return _empty_status('no_data') if latest_unit is not None and latest_unit.status in FAILED_UNIT_STATUSES: - return {'file_status': 'failed', 'has_ready_file': False, 'file_no': None, 'file_sha256': None} - - # 文件仍在但已失效(保留期已到或隔日旧文件):不报 ready,单独投影 expired 提示重抓。 - expired_report = ( - ShippingReceiptReportFile.query - .join(ShippingReceiptReportFile.unit_run) - .filter( - ShippingReceiptReportFile.unit_run.has(source_code=source_code), - expired_receipt_file_condition(), - ) - .first() - ) - if expired_report is not None: - 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} + return _empty_status('failed') + if expired: + return _empty_status('expired') + return _empty_status('none') -def record_receipt_parse_failure( +def _project_file_status( + source_code: str, *, - report: ShippingReceiptReportFile, - error_code: str, - error_message: str, - now: datetime | None = None, -) -> None: - """标记一份收料归档文件解析失败(写入 parse_failed_at / parse_error_code / parse_error_message)。 + latest_file: Callable[..., Any], + unit_model: type, + has_expired: Callable[..., bool], +) -> dict: + """按入站既有顺序把文件视图与执行单元投影成文件状态。 - 【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 口径一致)。 + source_code: 来源实例编码。 + latest_file: 返回可用文件视图或 None;视图须有 original_filename、file_id、 + parse_failed_at、sha256。 + unit_model: 带 query/status/id/source_code 的执行单元模型。 + has_expired: 该来源是否仍有失效未清理文件。 Returns: - None。失败标记写在传入对象上并 flush,由调用方决定何时 commit 或回滚。 + file_status 字典,键为 file_status / has_ready_file / file_no / file_sha256。 """ - 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() + file_view = latest_file(source_code) + active_unit = None + latest_unit = None + expired = False + if file_view is None: + active_unit = ( + unit_model.query + .filter_by(source_code=source_code) + .filter(unit_model.status.in_(RUNNING_UNIT_STATUSES)) + .order_by(unit_model.id.desc()) + .first() + ) + if active_unit is None: + latest_unit = ( + unit_model.query + .filter_by(source_code=source_code) + .order_by(unit_model.id.desc()) + .first() + ) + terminal = latest_unit is not None and latest_unit.status in ( + *NO_DATA_UNIT_STATUSES, *FAILED_UNIT_STATUSES, + ) + if not terminal: + expired = has_expired(source_code) + return _status_from_facts( + file_view=file_view, + active_unit=active_unit, + latest_unit=latest_unit, + expired=expired, + ) -def clear_receipt_parse_failure(*, report: ShippingReceiptReportFile) -> None: - """清除一份收料归档文件的解析失败标记(三列置空),投影恢复 ready。 +def _latest_files_by_source(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> dict[str, _FileFact]: + """一次取出这批来源各自最新的可用归档。 + + 核心逻辑:按来源主键过滤后按创建时间、文件主键倒序,每个来源只留第一条。 + 只取状态判断用到的列,不加载执行单元上的 JSON 快照。 + + Args: + file_model: 入站或出站归档文件模型。 + unit_model: 对应的执行单元模型,用来按 source_id 过滤。 + source_ids: 要投影的来源主键。 + filters: 可用文件条件(未删除、当天业务日、未过保留期)。 + Returns: + source_code 到文件事实的映射;没有可用文件的来源不出现。 + """ + rows = ( + file_model.query + .join(unit_model, file_model.unit_run_id == unit_model.id) + .filter(unit_model.source_id.in_(source_ids), *filters) + .with_entities( + unit_model.source_code, + file_model.id, + file_model.original_filename, + file_model.sha256, + file_model.parse_failed_at, + ) + .order_by(file_model.created_at.desc(), file_model.id.desc()) + .all() + ) + picked: dict[str, _FileFact] = {} + for source_code, file_id, filename, sha256, parse_failed_at in rows: + if source_code in picked: + continue + picked[str(source_code)] = _FileFact( + file_id=file_id, + original_filename=filename, + sha256=sha256, + parse_failed_at=parse_failed_at, + ) + return picked + + +def _units_by_source(unit_model: type, source_ids: list[int]) -> tuple[dict[str, _UnitFact], dict[str, _UnitFact]]: + """一次取出这批来源的最新单元,以及仍在进行的最新单元。 + + 核心逻辑:按 id 倒序扫描,每个来源遇到的第一行就是最新单元;状态属于进行中 + 的第一行就是该来源仍在抓取的单元。较新的失败单元因此盖不住更早仍在进行的单元。 + + Args: + unit_model: 入站或出站执行单元模型。 + source_ids: 要投影的来源主键。 + Returns: + (最新单元, 进行中单元),键都是 source_code。没有单元时对应字典为空。 + """ + rows = ( + unit_model.query + .filter(unit_model.source_id.in_(source_ids)) + .with_entities(unit_model.source_code, unit_model.id, unit_model.status) + .order_by(unit_model.id.desc()) + .all() + ) + latest: dict[str, _UnitFact] = {} + active: dict[str, _UnitFact] = {} + for source_code, _unit_id, status in rows: + code = str(source_code) + if code not in latest: + latest[code] = _UnitFact(status=status) + if status in RUNNING_UNIT_STATUSES and code not in active: + active[code] = _UnitFact(status=status) + return latest, active + + +def _expired_source_codes(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> set[str]: + """一次找出仍有失效未清理归档的来源编码。 + + 核心逻辑:只判断存在性,不取文件内容。失效条件由调用方传入,与单来源 + has_expired_* 使用同一套未删除且不满足新鲜度/保留期的口径。 + + Args: + file_model: 入站或出站归档文件模型。 + unit_model: 对应的执行单元模型。 + source_ids: 要投影的来源主键。 + filters: 失效文件条件。 + Returns: + 至少有一份失效未清理归档的 source_code 集合。 + """ + rows = ( + file_model.query + .join(unit_model, file_model.unit_run_id == unit_model.id) + .filter(unit_model.source_id.in_(source_ids), *filters) + .with_entities(unit_model.source_code) + .distinct() + .all() + ) + return {str(row[0]) for row in rows} + + +def resolve_source_file_statuses(sources: list[Any]) -> dict[str, dict[str, dict]]: + """批量投影一组来源的入站与出站证据文件状态。 + + 用途:GET /sources 渲染来源选择卡。来源个数增加时仍只做固定几条查询, + 供页面同时展示调拨类型和数据源时不必按来源等待。 + + 核心逻辑:出站配置、入站/出站的可用文件、执行单元、失效文件各查一次, + 再按与 resolve_source_file_status 相同的优先级收口。没有出站配置的来源 + 直接记 unconfigured,不把入站状态抄到出站。 + + Args: + sources: 已加载的来源行,须有 id 与 source_code。空列表不查库。 + Returns: + {source_code: {"inbound": 状态字典, "outbound": 状态字典}}。 + 状态字典键与 resolve_source_file_status 相同。 + """ + if not sources: + return {} + now = datetime.utcnow() + source_ids = [int(source.id) for source in sources] + configured_outbound = { + int(row[0]) + for row in ( + FreightRpaOutboundReportConfig.query + .filter(FreightRpaOutboundReportConfig.source_id.in_(source_ids)) + .with_entities(FreightRpaOutboundReportConfig.source_id) + .all() + ) + } + inbound_files = _latest_files_by_source( + FreightRpaInboundReportFile, + FreightRpaInboundUnitRun, + source_ids, + usable_inbound_file_condition(now=now), + ) + inbound_latest, inbound_active = _units_by_source(FreightRpaInboundUnitRun, source_ids) + inbound_expired = _expired_source_codes( + FreightRpaInboundReportFile, + FreightRpaInboundUnitRun, + source_ids, + expired_inbound_file_condition(now=now), + ) + outbound_files = _latest_files_by_source( + FreightRpaOutboundReportFile, + FreightRpaOutboundUnitRun, + source_ids, + FreightRpaOutboundReportFile.archive_deleted_at.is_(None), + _outbound_fresh_and_retention_valid(now), + ) + outbound_latest, outbound_active = _units_by_source(FreightRpaOutboundUnitRun, source_ids) + outbound_expired = _expired_source_codes( + FreightRpaOutboundReportFile, + FreightRpaOutboundUnitRun, + source_ids, + FreightRpaOutboundReportFile.archive_deleted_at.is_(None), + not_(_outbound_fresh_and_retention_valid(now)), + ) + projected: dict[str, dict[str, dict]] = {} + for source in sources: + code = str(source.source_code) + inbound = _status_from_facts( + file_view=inbound_files.get(code), + active_unit=inbound_active.get(code), + latest_unit=inbound_latest.get(code), + expired=code in inbound_expired, + ) + if int(source.id) not in configured_outbound: + outbound = _empty_status('unconfigured') + else: + outbound = _status_from_facts( + file_view=outbound_files.get(code), + active_unit=outbound_active.get(code), + latest_unit=outbound_latest.get(code), + expired=code in outbound_expired, + ) + projected[code] = {'inbound': inbound, 'outbound': outbound} + return projected + + +def resolve_source_file_status(*, source_code: str, record_kind: str = 'inbound') -> dict: + """返回某来源在指定记录类型上的证据文件状态投影。 + + 用途:来源列表与重试门禁按流入站或出站询问文件是否就绪。缺省 record_kind + 为 inbound,既有只传来源的调用返回值与改造前相同。 + + 核心逻辑:record_kind 不是 inbound/outbound 时抛 ValidationError。出站先查 + get_outbound_config,没有配置行则 unconfigured,不再往下看文件或单元。 + 有配置(以及全部入站)再按同一顺序投影。失效判定不依赖保留期清理任务: + 保留期已到,或非当前业务日(Asia/Shanghai)抓取。 + + Args: + source_code: 来源实例编码。 + record_kind: inbound 或 outbound,默认 inbound。 + Returns: + {"file_status", "has_ready_file", "file_no", "file_sha256"}。 + file_status ∈ {'ready', 'parse_failed', 'fetching', 'failed', 'no_data', + 'expired', 'none', 'unconfigured'}。parse_failed 时 has_ready_file=False, + 仍带 file_no/file_sha256。unconfigured 仅出站且无出站报表配置时出现。 + Raises: + ValidationError: record_kind 不是 inbound 或 outbound。 + """ + if record_kind not in _RECORD_KINDS: + raise ValidationError( + f'unsupported record_kind: {record_kind}', + details={'record_kind': record_kind}, + ) + if record_kind == 'outbound': + if get_outbound_config(source_code) is None: + return _empty_status('unconfigured') + return _project_file_status( + source_code, + latest_file=latest_usable_outbound_file, + unit_model=FreightRpaOutboundUnitRun, + has_expired=has_expired_outbound_file, + ) + return _project_file_status( + source_code, + latest_file=latest_usable_inbound_file, + unit_model=FreightRpaInboundUnitRun, + has_expired=has_expired_inbound_file, + ) + + +def record_inbound_parse_failure( + *, + report: Any, + error_code: str, + error_message: str, +) -> None: + """标记一份入站归档文件解析失败(写入 parse_failed_at / parse_error_code / parse_error_message)。 + + 【AI 触发时机】入站归档文件解析(schema/字段校验)失败需要把失败事实落到文件上、 + 让来源状态投影为 parse_failed 阻止下游当作 ready 使用时调用;解析成功或重抓成功后 + 改调 clear_inbound_parse_failure。 + + 【阶段 B Task 4 兼容薄壳】全量语义(失败时刻取当前 UTC、错误码按 64 字符/ + 错误信息按 2000 字符截断、只 flush 不 commit——事务提交时机归属调用方)已 + 收口 freight_rpa.reports.queries.mark_inbound_parse_failure(唯一实现); + 本壳只为既有调用方按归档文件对象传参的签名而保留——取对象主键委托真实现。 + + Args: + report: 入站归档文件对象(仅取主键 .id;须已入库)。 + error_code: 机器可读错误码(真实现内按列宽截断)。 + error_message: 人类可读错误信息(真实现内做防御性截断)。 + Returns: + None。失败标记随调用方事务落库。 + """ + _mark_parse_failure_by_id(report.id, error_code=error_code, error_message=error_message) + + +def clear_inbound_parse_failure(*, report: Any) -> None: + """清除一份入站归档文件的解析失败标记(三列置空),投影恢复 ready。 【AI 触发时机】同一文件重新解析成功、或人工确认可恢复后调用,使来源状态 投影从 parse_failed 回到 ready;不要在文件已被清理/失效后调用(无意义)。 - 核心逻辑:[STEP 1] 将 parse_failed_at / parse_error_code / parse_error_message - 三列置 None(三者全空即未失败/已清除的约定态);[STEP 2] flush 使同事务内 - 投影立即可见。只 flush 不 commit,事务提交时机归调用方。 + 【阶段 B Task 4 兼容薄壳】语义收口同 record_inbound_parse_failure:取对象 + 主键委托 freight_rpa.reports.queries.clear_inbound_parse_failure(置空三列 + 后 flush,不 commit,事务归属调用方)。 Args: - report: 待清除标记的 ShippingReceiptReportFile(须已入库,主键可用)。 + report: 入站归档文件对象(仅取主键 .id;须已入库)。 Returns: - None。清除写在传入对象上并 flush,由调用方决定何时 commit 或回滚。 + None。清除随调用方事务落库。 """ - report.parse_failed_at = None - report.parse_error_code = None - report.parse_error_message = None - db.session.flush() + _clear_parse_failure_by_id(report.id) \ No newline at end of file diff --git a/backend/app/services/in_transit_transfer/status.py b/backend/app/services/in_transit_transfer/status.py index 40c741c1..f0cfc5b8 100644 --- a/backend/app/services/in_transit_transfer/status.py +++ b/backend/app/services/in_transit_transfer/status.py @@ -1,15 +1,17 @@ """在途调拨状态机与转换门禁。 -用途:定义提示词冻结的 13 个业务状态(TransferStatus)、Run 生命周期 +用途:定义提示词冻结的 12 个业务状态(TransferStatus)、Run 生命周期 (TransferRunStatus)与通知状态(TransferNotificationStatus), 并强制所有状态转换走服务端门禁。 依赖:app.core.errors.AppError。 逻辑:转换表声明即白名单,未声明的迁移一律抛 TransferStateError; result_unknown / manually_closed / success / duplicate_success / - not_matured / cancelled 为无出边终态(唯二例外均为显式人工/生命周期语义: + cancelled 为无出边终态(唯二例外均为显式人工/生命周期语义: DOCUMENT_RETRIGGER_TRANSITIONS 允许 result_unknown 单经人工 retrigger → executing,D11 唯一出口;QUEUED Run 经 worker 领取 → executing); 通知失败(notification_failed)是通知投递状态,绝不改写 外部系统 业务结果。 + 【not_matured 状态已退役 2026-10-16】成熟概念删除(数据无成熟属性, + 日期边界由调用方入参给定);存量行经 tt16 迁移重映射为 cancelled。 """ from __future__ import annotations @@ -23,7 +25,7 @@ INVALID_STATE_TRANSITION_CODE = "TRANSFER.INVALID_STATE_TRANSITION" class TransferStatus(StrEnum): - """Invoice 项业务状态(含提示词冻结的全部 13 个状态)。""" + """Invoice 项业务状态(含提示词冻结的全部 12 个状态)。""" FILE_PENDING = "file_pending" FILE_READY = "file_ready" @@ -33,7 +35,6 @@ class TransferStatus(StrEnum): SUCCESS = "success" DUPLICATE_SUCCESS = "duplicate_success" BLOCKED_RECOVERABLE = "blocked_recoverable" - NOT_MATURED = "not_matured" RESULT_UNKNOWN = "result_unknown" MANUALLY_CLOSED = "manually_closed" CANCELLED = "cancelled" @@ -72,7 +73,6 @@ TERMINAL_TRANSFER_STATUSES: frozenset[str] = frozenset({ TransferStatus.RESULT_UNKNOWN.value, TransferStatus.MANUALLY_CLOSED.value, TransferStatus.CANCELLED.value, - TransferStatus.NOT_MATURED.value, TransferStatus.NOTIFICATION_FAILED.value, }) @@ -89,7 +89,6 @@ ITEM_TRANSITIONS: dict[str, frozenset[str]] = { TransferStatus.MATCHING.value: frozenset({ TransferStatus.READY_TO_EXECUTE.value, TransferStatus.BLOCKED_RECOVERABLE.value, - TransferStatus.NOT_MATURED.value, TransferStatus.CANCELLED.value, }), TransferStatus.READY_TO_EXECUTE.value: frozenset({ @@ -114,7 +113,6 @@ ITEM_TRANSITIONS: dict[str, frozenset[str]] = { TransferStatus.MANUALLY_CLOSED.value, TransferStatus.CANCELLED.value, }), - TransferStatus.NOT_MATURED.value: frozenset(), TransferStatus.SUCCESS.value: frozenset(), TransferStatus.DUPLICATE_SUCCESS.value: frozenset(), # [T10/R7 出边] result_unknown 行唯一出边 = 人工 retrigger 驱动 → executing diff --git a/backend/app/services/in_transit_transfer/transfer_type.py b/backend/app/services/in_transit_transfer/transfer_type.py index 9de25a0d..ff8d8b34 100644 --- a/backend/app/services/in_transit_transfer/transfer_type.py +++ b/backend/app/services/in_transit_transfer/transfer_type.py @@ -1,127 +1,84 @@ -"""在途调拨类型契约。 +"""在途调拨类型契约(配置化,ADR 0002)。 -用途:定义调拨业务类型(在途仓至HUB仓 / HUB仓维修出 / HUB仓间调拨)及各类型 - 的收料数据范围规则;类型 2/3 一期占位(fail-closed 拒绝匹配,规则先冻结)。 -依赖:app.core.errors.ValidationError、invoice_aggregator.AggregatedInvoice。 -逻辑:类型决定匹配纳入哪些收料单——类型 1 只保留 INVOICE 以 HOM/HOX/WTP 开头 - 的单(大小写不敏感,范围外单与收料日期范围过滤同语义,静默排除不入明细); - 类型 2 规则已定(ODM ID=HoxinRMA)待收料文件解析层支持 odm_id 字段后启用; - 类型 3 规则待业务定义。范围判断统一走 invoice_in_scope 谓词(匹配过滤与 - scope 行圈定共用);调用方必须先 ensure_transfer_type_supported 再过滤。 +用途:匹配链路的类型门禁唯一入口——把 API/服务传入的类型编码解析为 + transfer_type_configs 配置 DTO(存在性/启停校验 fail-closed)。 +依赖:transfer_type_config_service(get_by_code,唯一读取口径)、app.core.errors。 +逻辑:【2026-10-14 配置化切换】类型不再硬编码枚举:合法值=配置表 code, + 数据范围/仓库定义/转换规则全部随配置(scope_rules / warehouse_config / + transform_rules),匹配创建时快照进 scope_json。本模块只做「编码 → 配置 + DTO」的门禁解析:None/空 → REQUIRED;无此码(含空配置表)→ NOT_CONFIGURED; + 停用 → DISABLED(require_enabled=False 供存量匹配的重跑/重查使用—— + 「停用后新匹配不可选,存量不受影响」,规格 §4.1)。 + 旧枚举/前缀常量/谓词(TransferType / SUPPORTED_TRANSFER_TYPES / + normalize_transfer_type / ensure_transfer_type_supported / invoice_in_scope / + filter_invoices_for_type / transfer_type_scope_note)已随翻转退役: + 范围职责移交 scope_rules 引擎 + 匹配快照,批号转换移交 field_transforms。 """ from __future__ import annotations -from enum import StrEnum -from typing import Iterable - from app.core.errors import ValidationError -from app.services.in_transit_transfer.invoice_aggregator import AggregatedInvoice +from app.services.in_transit_transfer.transfer_type_config_service import ( + TransferTypeConfigDTO, + get_by_code, +) -# 类型不支持(占位类型被调用)时的稳定错误码。 -TRANSFER_TYPE_NOT_SUPPORTED = "TRANSFER.TRANSFER_TYPE_NOT_SUPPORTED" +# 匹配创建未携带类型编码(必填缺失)的稳定错误码(规格 §11,四语言已配齐)。 +TRANSFER_TYPE_REQUIRED = "TRANSFER.TRANSFER_TYPE_REQUIRED" +# 配置表为空或无此编码(fail-closed,D8 不做种子数据)。 +TRANSFER_TYPE_NOT_CONFIGURED = "TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED" +# 类型存在但已停用(停用后新匹配不可选)。 +TRANSFER_TYPE_DISABLED = "TRANSFER.TRANSFER_TYPE_DISABLED" -class TransferType(StrEnum): - """调拨业务类型(值与前端/i18n、transfer_runs.transfer_type 列一致)。""" +def resolve_transfer_type(code: str | None, *, require_enabled: bool = True) -> TransferTypeConfigDTO: + """把类型编码解析为配置 DTO(匹配链路的类型门禁唯一入口)。 - IN_TRANSIT_TO_HUB = "in_transit_to_hub" # 在途仓至HUB仓 - HUB_REPAIR_OUT = "hub_repair_out" # HUB仓维修出(占位) - HUB_TO_HUB = "hub_to_hub" # HUB仓间调拨(占位) - - -# 一期已实现匹配/执行链路的类型;其余类型 fail-closed(占位,防止误生成 外部系统 单)。 -SUPPORTED_TRANSFER_TYPES: frozenset[TransferType] = frozenset({TransferType.IN_TRANSIT_TO_HUB}) - -# 类型 1(在途仓至HUB仓)数据范围:INVOICE 开头前缀(大小写不敏感)。 -IN_TRANSIT_TO_HUB_INVOICE_PREFIXES: tuple[str, ...] = ("HOM", "HOX", "WTP") - -# 类型 2(HUB仓维修出)数据范围:ODM ID 精确值;待 movement 文件暴露 odm_id 后启用。 -HUB_REPAIR_OUT_ODM_ID = "HoxinRMA" - - -def normalize_transfer_type(value: str | TransferType | None) -> TransferType: - """规范化调拨类型入参;缺省/空值回落到类型 1(存量调用方语义不变)。 + 【AI 触发时机】匹配创建(run_matching / create_matching / API 必填校验)与 + 存量匹配的重跑/重查需要类型配置(范围规则/仓库定义/转换规则)时, + 必须经本函数解析;禁止绕过配置直取编码或假设固定类型。 Args: - value: 前端/API 传入的调拨类型值。 + code: 类型编码(transfer_type_configs.code,创建后不可变)。 + require_enabled: True(默认)=停用类型拒绝(新匹配路径);False=存量 + 匹配的重跑/重查放行停用类型(「存量不受影响」语义)。 Returns: - TransferType 枚举。 + TransferTypeConfigDTO(scope_rules/warehouse_config/transform_rules 均为 + 引擎解析后的受控对象)。 Raises: - ValidationError: 非法类型值(不在枚举内)。 + ValidationError: code 为 None/空白 → TRANSFER.TRANSFER_TYPE_REQUIRED; + 配置表无此码(含空表)→ TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED; + 停用且 require_enabled → TRANSFER.TRANSFER_TYPE_DISABLED。 """ - raw = str(value.value if isinstance(value, TransferType) else (value or "")).strip() - if not raw: - return TransferType.IN_TRANSIT_TO_HUB - try: - return TransferType(raw) - except ValueError as exc: + cleaned = str(code or "").strip() + if not cleaned: raise ValidationError( - f"unknown transfer type: {raw}", - code="TRANSFER.TRANSFER_TYPE_INVALID", - details={"transfer_type": raw}, - ) from exc - - -def ensure_transfer_type_supported(transfer_type: TransferType) -> None: - """占位类型 fail-closed:类型 2/3 处理链路未实现前禁止进入匹配。 - - Args: - transfer_type: 已规范化的调拨类型。 - Raises: - ValidationError: 类型未实现(TRANSFER_TYPE_NOT_SUPPORTED)。 - """ - if transfer_type not in SUPPORTED_TRANSFER_TYPES: - raise ValidationError( - f"transfer type not supported yet: {transfer_type.value}", - code=TRANSFER_TYPE_NOT_SUPPORTED, - details={"transfer_type": transfer_type.value}, + "transfer_type is required", + code=TRANSFER_TYPE_REQUIRED, + http_status=422, # 规格 §11:匹配创建类型门禁统一 422 ) + # 复用配置服务的唯一读取口径:脏配置在其读取侧已被引擎拦截(fail-closed)。 + from app.services.in_transit_transfer.transfer_type_config_service import ( + TRANSFER_TYPE_NOT_CONFIGURED as _NOT_CONFIGURED, + ) - -def invoice_in_scope(invoice_no: str, transfer_type: TransferType | str | None) -> bool: - """判断 Invoice 单号是否落在调拨类型的收料数据范围内(单一判断口径)。 - - 用途:匹配过滤(filter_invoices_for_type)与 scope 行圈定(matching_service - 的 scope_item_query)共用本谓词,避免"单过滤"与"行圈定"口径漂移。 - - Args: - invoice_no: 收料单单号(大小写不敏感,前后空白忽略;空值恒 False)。 - transfer_type: 调拨类型(未规范化值允许,缺省/空回落类型 1)。 - Returns: - True 表示该单在类型范围内(应纳入匹配/scope 查询); - 占位类型(规则未启用)恒 False。 - """ - resolved = normalize_transfer_type(transfer_type) - if resolved == TransferType.IN_TRANSIT_TO_HUB: - prefixes = tuple(prefix.upper() for prefix in IN_TRANSIT_TO_HUB_INVOICE_PREFIXES) - return str(invoice_no or "").strip().upper().startswith(prefixes) - # 类型 2/3 的范围规则在启用时补齐(此前 ensure_transfer_type_supported 已拦截)。 - return False - - -def filter_invoices_for_type( - invoices: Iterable[AggregatedInvoice], - transfer_type: TransferType, -) -> list[AggregatedInvoice]: - """按类型的收料数据范围过滤汇总单(返回保留项,保持原顺序)。 - - Args: - invoices: 已汇总的收料单。 - transfer_type: 已规范化且已确认支持的调拨类型。 - Returns: - 类型范围内的单列表(判断口径统一走 invoice_in_scope)。 - """ - return [ - invoice for invoice in invoices - if invoice_in_scope(invoice.invoice_no, transfer_type) - ] - - -def transfer_type_scope_note(transfer_type: TransferType) -> str: - """类型的范围规则说明(写入 TransferMatching.scope_json 供审计追溯)。""" - if transfer_type == TransferType.IN_TRANSIT_TO_HUB: - return f"invoice_prefix:{'+'.join(IN_TRANSIT_TO_HUB_INVOICE_PREFIXES).lower()}" - if transfer_type == TransferType.HUB_REPAIR_OUT: - return f"odm_id:{HUB_REPAIR_OUT_ODM_ID}" - return "pending_rule" + try: + config = get_by_code(cleaned) + except ValidationError as exc: + if exc.code == _NOT_CONFIGURED: + # 归一为本模块稳定错误码(匹配链路与 API 复用同一码面)。 + raise ValidationError( + f"transfer type not configured: {cleaned}", + code=TRANSFER_TYPE_NOT_CONFIGURED, + details={"transfer_type": cleaned}, + http_status=422, # 规格 §11:空配置/停用类型 → 422 + ) from exc + raise + if require_enabled and not config.enabled: + raise ValidationError( + f"transfer type is disabled: {cleaned}", + code=TRANSFER_TYPE_DISABLED, + details={"transfer_type": cleaned}, + http_status=422, # 规格 §11:空配置/停用类型 → 422 + ) + return config diff --git a/backend/app/services/in_transit_transfer/transfer_type_config_service.py b/backend/app/services/in_transit_transfer/transfer_type_config_service.py new file mode 100644 index 00000000..4ffb4b82 --- /dev/null +++ b/backend/app/services/in_transit_transfer/transfer_type_config_service.py @@ -0,0 +1,459 @@ +"""services/in_transit_transfer/transfer_type_config_service.py + +用途:调拨类型配置域服务(ADR 0002)——transfer_type_configs 表的唯一 CRUD 入口: + 列表/启用列表/按码读取/创建/更新(code 创建后不可变,只有停用没有删除), + 以及 mapped/fixed 双模式仓库角色解析 resolve_warehouse(Task 11 路由接入、 + Task 5 管理 API 消费)。 +依赖:models.in_transit_transfer.TransferTypeConfig、app.db(db.session)、 + scope_rules.parse_scope_rules、field_transforms.parse_transform_rules、 + app.core.errors.ValidationError;RouteMapping 仅类型标注(TYPE_CHECKING)。 +逻辑:写路径先过三块配置 parse 门禁(范围规则/仓库定义/转换规则)→ 组装规范化 + JSON 后走 ORM 插入/更新(JSON 四列无 server_default,禁止原生 SQL 插入); + 读路径 DTO 组装同样全部走 parse——库内脏数据在读取侧也被拦截(fail-closed); + resolve_warehouse 按 role 取 from/to 角色:mapped 透传 RouteMapping, + fixed 覆盖仓库、external_org 非空才覆盖法人。 +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from datetime import datetime +from typing import TYPE_CHECKING, Any + +from app import db +from app.core.errors import ValidationError +from app.models.in_transit_transfer import TransferTypeConfig +from app.services.in_transit_transfer.field_transforms import TransformRule, parse_transform_rules +from app.services.in_transit_transfer.scope_rules import ScopeRule, parse_scope_rules + +if TYPE_CHECKING: + from app.services.in_transit_transfer.matching_service import RouteMapping + +# 稳定错误码(Task 5 同步四语言 errors.json;参数形态类失败走既有通用码)。 +TRANSFER_TYPE_NOT_CONFIGURED = "TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED" +TRANSFER_TYPE_CODE_EXISTS = "TRANSFER.TRANSFER_TYPE_CODE_EXISTS" +TRANSFER_TYPE_CODE_IMMUTABLE = "TRANSFER.TRANSFER_TYPE_CODE_IMMUTABLE" +WAREHOUSE_CONFIG_INVALID = "TRANSFER.WAREHOUSE_CONFIG_INVALID" + +# code 契约:小写字母开头,仅小写字母/数字/下划线,总长 2..64(与列宽一致)。 +CODE_PATTERN = re.compile(r"^[a-z][a-z0-9_]{1,63}$") + +# 参数形态类校验失败复用既有通用码(不新增四语言条目,管理页表单层先行拦截)。 +_PARAM_INVALID = "VALIDATION.INVALID_PARAM" + +_WAREHOUSE_MODES = ("mapped", "fixed") +_WAREHOUSE_ROLE_KEYS = {"from": "from_role", "to": "to_role"} + + +@dataclass(frozen=True) +class WarehouseRole: + """单角色仓库定义:mapped=沿用来源映射档;fixed=类型固定仓库(可覆盖法人)。""" + + mode: str + warehouse_code: str | None = None + external_org: str | None = None + + +@dataclass(frozen=True) +class WarehouseConfig: + """类型仓库定义:拨出(from)/拨入(to)两角色各自 mapped 或 fixed。""" + + from_role: WarehouseRole + to_role: WarehouseRole + + +@dataclass(frozen=True) +class TransferTypeConfigDTO: + """调拨类型配置读取视图:三块配置均为引擎解析后的受控对象(非原始 JSON)。""" + + code: str + names: dict[str, Any] + enabled: bool + sort_order: int + scope_rules: tuple[ScopeRule, ...] + warehouse_config: WarehouseConfig + transform_rules: tuple[TransformRule, ...] + description: str | None + updated_at: datetime + + +def _reject_param(message: str, **details: Any) -> ValidationError: + """参数形态类校验失败的统一出口(通用码 + 定位详情)。""" + return ValidationError(message, code=_PARAM_INVALID, details=details) + + +def _clean_str(value: Any) -> str | None: + """字符串规范化:非字符串 → None;空白串 → None;其余去首尾空白。""" + if not isinstance(value, str): + return None + return value.strip() or None + + +def _parse_warehouse_config(raw: dict | None) -> WarehouseConfig: + """校验并规范化仓库定义 JSON(保存与读取共用;非法 fail-closed)。 + + Args: + raw: {"from": {...}, "to": {...}},角色项缺省视为 mapped(沿用映射档); + mapped 项不消费固定仓库值(规范化为纯 {"mode": "mapped"})。 + Returns: + 规范化后的 WarehouseConfig。 + Raises: + ValidationError: code=TRANSFER.WAREHOUSE_CONFIG_INVALID——mode 不在白名单、 + fixed 缺非空 warehouse_code、或结构非 dict。 + """ + if raw is None: + raw = {} + if not isinstance(raw, dict): + raise ValidationError( + "warehouse_config must be an object", code=WAREHOUSE_CONFIG_INVALID, + ) + + def _role(role_key: str) -> WarehouseRole: + entry = raw.get(role_key) + if entry is None: + return WarehouseRole(mode="mapped") + if not isinstance(entry, dict): + raise ValidationError( + f"warehouse role {role_key} must be an object", code=WAREHOUSE_CONFIG_INVALID, + details={"role": role_key}, + ) + mode = str(entry.get("mode", "")) + if mode not in _WAREHOUSE_MODES: + raise ValidationError( + f"invalid warehouse mode: {mode}", code=WAREHOUSE_CONFIG_INVALID, + details={"role": role_key, "mode": mode}, + ) + if mode != "fixed": + return WarehouseRole(mode="mapped") + warehouse_code = _clean_str(entry.get("warehouse_code")) + if not warehouse_code: + raise ValidationError( + f"fixed warehouse role requires warehouse_code: {role_key}", + code=WAREHOUSE_CONFIG_INVALID, details={"role": role_key}, + ) + return WarehouseRole( + mode="fixed", warehouse_code=warehouse_code, + external_org=_clean_str(entry.get("external_org")), + ) + + return WarehouseConfig(from_role=_role("from"), to_role=_role("to")) + + +def _warehouse_role_json(role: WarehouseRole) -> dict[str, Any]: + """WarehouseRole → 规范化 JSON 项(mapped 固化空值,保证读写对称)。""" + return {"mode": role.mode, "warehouse_code": role.warehouse_code, "external_org": role.external_org} + + +def _warehouse_config_json(config: WarehouseConfig) -> dict[str, Any]: + """WarehouseConfig → 入库 JSON(from/to 键与规格 §7 示例一致)。""" + return { + "from": _warehouse_role_json(config.from_role), + "to": _warehouse_role_json(config.to_role), + } + + +def _to_dto(row: TransferTypeConfig) -> TransferTypeConfigDTO: + """ORM 行 → DTO;三块配置全部重走 parse,库内脏数据在读取侧被拦截。 + + Raises: + ValidationError: 脏数据命中任一引擎白名单校验(SCOPE/WAREHOUSE/TRANSFORM)。 + """ + return TransferTypeConfigDTO( + code=row.code, + names=dict(row.names_json or {}), + enabled=bool(row.enabled), + sort_order=int(row.sort_order or 0), + scope_rules=parse_scope_rules(row.scope_rules_json), + warehouse_config=_parse_warehouse_config(row.warehouse_config_json), + transform_rules=parse_transform_rules(row.transform_rules_json), + description=row.description, + updated_at=row.updated_at, + ) + + +def _query_by_code(code: str) -> TransferTypeConfig | None: + """按 code 精确查询(入参去首尾空白;不查 None/空串)。""" + cleaned = str(code or "").strip() + if not cleaned: + return None + return db.session.query(TransferTypeConfig).filter(TransferTypeConfig.code == cleaned).one_or_none() + + +def _scope_rules_of(payload: dict) -> tuple[ScopeRule, ...]: + """解析 payload 中的范围规则(parse 门禁复用 Task 2 引擎,非法透传其错误码)。 + + Raises: + ValidationError: TRANSFER.SCOPE_RULE_INVALID(规则字段/匹配方式/值非法)。 + """ + return parse_scope_rules(payload.get("scope_rules")) + + +def _enforce_scope_policy(payload: dict, rules: tuple[ScopeRule, ...]) -> None: + """空规则默认拒绝(防误圈全量);payload 显式确认(allow_empty_scope_rules)才放行。 + + [规格 §6] 是否允许「空=不限」由管理页显式确认——本服务默认要求至少一条。 + """ + if rules or payload.get("allow_empty_scope_rules") is True: + return + raise _reject_param("scope_rules requires at least one rule unless explicitly confirmed") + + +def _validated_names(payload: dict, *, required: bool) -> dict[str, Any] | None: + """校验 names:dict 且含非空 zh-CN(四语言名称的门禁底线)。 + + Args: + payload: 创建/更新载荷。 + required: 创建恒为 True(names_json 必须含非空 zh-CN,缺 key 同拒); + 更新为 False(未提供保持原值,提供则同门禁校验)。 + Returns: + names dict(更新未提供时 None,由调用方保持原值)。 + Raises: + ValidationError: required 且缺 key、非 dict、缺 zh-CN 或 zh-CN 非非空字符串。 + """ + if "names" not in payload: + if required: + raise _reject_param("names is required with non-empty zh-CN") + return None + names = payload.get("names") + zh = names.get("zh-CN") if isinstance(names, dict) else None + if not isinstance(zh, str) or not zh.strip(): + raise _reject_param("names requires non-empty zh-CN", names=names) + return dict(names) + + +def _coerce_sort_order(value: Any) -> int: + """sort_order 宽松转 int(JSON 数字/数字字符串),失败走参数校验码。""" + try: + return int(value) + except (TypeError, ValueError) as exc: + raise _reject_param(f"invalid sort_order: {value!r}", sort_order=value) from exc + + +def list_configs() -> list[TransferTypeConfigDTO]: + """全量类型配置(含停用),按 sort_order 升序、code 次序稳定排序。 + + Returns: + TransferTypeConfigDTO 列表(管理页列表用;含停用项)。 + Raises: + ValidationError: 任一行的范围规则/仓库定义/转换规则为脏数据时,经 _to_dto + 抛对应引擎错误码(TRANSFER.SCOPE_RULE_INVALID / + TRANSFER.WAREHOUSE_CONFIG_INVALID / TRANSFER.TRANSFORM_RULE_INVALID, + fail-closed,不降级返回脏配置)。 + """ + rows = ( + db.session.query(TransferTypeConfig) + .order_by(TransferTypeConfig.sort_order.asc(), TransferTypeConfig.code.asc()) + .all() + ) + return [_to_dto(row) for row in rows] + + +def get_enabled() -> list[TransferTypeConfigDTO]: + """启用中的类型配置,按 sort_order 升序(chat 侧类型列表与 Task 5 公开接口用)。 + + Returns: + 仅 enabled 的 TransferTypeConfigDTO 列表。 + Raises: + ValidationError: 脏数据同 list_configs——读取侧 parse fail-closed + (对应引擎错误码,不降级返回脏配置)。 + """ + rows = ( + db.session.query(TransferTypeConfig) + .filter(TransferTypeConfig.enabled.is_(True)) + .order_by(TransferTypeConfig.sort_order.asc(), TransferTypeConfig.code.asc()) + .all() + ) + return [_to_dto(row) for row in rows] + + +def get_by_code(code: str) -> TransferTypeConfigDTO: + """按 code 读取单个类型配置。 + + Args: + code: 类型编码(创建后不可变的业务主键)。 + Returns: + TransferTypeConfigDTO。 + Raises: + ValidationError: 不存在 → TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED(匹配链 + fail-closed 同码);脏配置 → 对应引擎错误码。 + """ + row = _query_by_code(code) + if row is None: + raise ValidationError( + f"transfer type not configured: {code}", code=TRANSFER_TYPE_NOT_CONFIGURED, + details={"code": code}, + ) + return _to_dto(row) + + +def create_config(payload: dict, operator_id: int | None = None) -> TransferTypeConfigDTO: + """创建类型配置(写入唯一入口;JSON 四列必须经 ORM 插入,无 server_default)。 + + Args: + payload: {code, names, enabled?, sort_order?, scope_rules?, warehouse_config?, + transform_rules?, description?, allow_empty_scope_rules?}。 + operator_id: 创建人 users.id(可空,系统初始化场景)。 + Returns: + 新建配置的 TransferTypeConfigDTO。 + Raises: + ValidationError: code 重复 → TRANSFER.TRANSFER_TYPE_CODE_EXISTS;code 格式 + 非法/缺 zh-CN/空 scope_rules 未显式确认 → 通用参数码; + 规则/仓库/转换非法 → 对应引擎错误码。 + """ + if not isinstance(payload, dict): + raise _reject_param("payload must be an object") + + # [STEP 1] code 契约:格式先行(唯一性后置到 DB 前查重)。 + code = _clean_str(payload.get("code")) + if not code or not CODE_PATTERN.match(code): + raise _reject_param(f"invalid transfer type code: {code!r}", code=code) + + # [STEP 2] names 必填且含非空 zh-CN(创建路径硬门禁,缺 key 同拒)。 + names = _validated_names(payload, required=True) + + # [STEP 3] 三块配置 parse 门禁:范围规则(含空规则默认拒绝)、仓库定义、转换规则。 + scope_rules = _scope_rules_of(payload) + _enforce_scope_policy(payload, scope_rules) + warehouse_config = _parse_warehouse_config(payload.get("warehouse_config")) + transform_rules = parse_transform_rules(payload.get("transform_rules")) + + # [STEP 4] 唯一性预检(并发窗口由 uq_transfer_type_configs_code 兜底)。 + if _query_by_code(code) is not None: + raise ValidationError( + f"transfer type code already exists: {code}", code=TRANSFER_TYPE_CODE_EXISTS, + details={"code": code}, + ) + + # [STEP 5] ORM 插入:JSON 列写入规范化结果(读回必可 parse,读写对称)。 + row = TransferTypeConfig( + code=code, + names_json=names, + enabled=bool(payload.get("enabled", False)), + sort_order=_coerce_sort_order(payload.get("sort_order", 0)), + scope_rules_json=[ + {"field": r.field, "match": r.match, "values": list(r.values)} for r in scope_rules + ], + warehouse_config_json=_warehouse_config_json(warehouse_config), + transform_rules_json=[ + {"field": r.field, "op": r.op, "source": r.source, "target": r.target} + for r in transform_rules + ], + description=_clean_str(payload.get("description")), + created_by=operator_id, + updated_by=operator_id, + ) + db.session.add(row) + db.session.commit() + return _to_dto(row) + + +def update_config(code: str, payload: dict, operator_id: int | None = None) -> TransferTypeConfigDTO: + """更新类型配置(部分更新:payload 未提供的字段保持原值;code 不可变)。 + + 原子校验:所有提供的键先全量 parse/校验,全部通过后才统一赋值提交—— + 任一键非法时整单拒绝且行保持原值(不落半截变更,评审 Finding 2 契约)。 + + Args: + code: 目标类型编码(路径参数)。 + payload: 待更新字段;含 code 且与目标不等 → 改名被拒。 + operator_id: 更新人 users.id(可空)。 + Returns: + 更新后的 TransferTypeConfigDTO。 + Raises: + ValidationError: 不存在 → TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED;改 code → + TRANSFER.TRANSFER_TYPE_CODE_IMMUTABLE;字段校验失败同 create + (引擎错误码或参数形态码),抛出时行未被修改。 + """ + if not isinstance(payload, dict): + raise _reject_param("payload must be an object") + row = _query_by_code(code) + if row is None: + raise ValidationError( + f"transfer type not configured: {code}", code=TRANSFER_TYPE_NOT_CONFIGURED, + details={"code": code}, + ) + + # [STEP 1] code 不可变(transfer_runs.transfer_type 引用它,改名即断链)。 + payload_code = payload.get("code") + if payload_code is not None and str(payload_code).strip() != row.code: + raise ValidationError( + f"transfer type code is immutable: {row.code}", code=TRANSFER_TYPE_CODE_IMMUTABLE, + details={"code": row.code, "attempted": payload_code}, + ) + + # [STEP 2] 全量预校验(与 create 同构):所有可更新键先 parse/校验到 updates, + # 任一非法即整体抛出——此阶段不触碰 ORM 行,杜绝半截变更残留 session + # (评审 Finding 2:形如 {"description": 新值, "transform_rules": 非法} + # 的载荷禁止先改 description 再抛错)。 + updates: dict[str, Any] = {} + names = _validated_names(payload, required=False) + if names is not None: + updates["names_json"] = names + if "scope_rules" in payload: + scope_rules = _scope_rules_of(payload) + _enforce_scope_policy(payload, scope_rules) + updates["scope_rules_json"] = [ + {"field": r.field, "match": r.match, "values": list(r.values)} for r in scope_rules + ] + if "warehouse_config" in payload: + warehouse_config = _parse_warehouse_config(payload.get("warehouse_config")) + updates["warehouse_config_json"] = _warehouse_config_json(warehouse_config) + if "transform_rules" in payload: + transform_rules = parse_transform_rules(payload.get("transform_rules")) + updates["transform_rules_json"] = [ + {"field": r.field, "op": r.op, "source": r.source, "target": r.target} + for r in transform_rules + ] + if "enabled" in payload: + updates["enabled"] = bool(payload.get("enabled")) + if "sort_order" in payload: + updates["sort_order"] = _coerce_sort_order(payload.get("sort_order")) + if "description" in payload: + updates["description"] = _clean_str(payload.get("description")) + + # [STEP 3] 全部通过后统一赋值(键为本函数白名单字面量)+ updated_by,一次提交。 + for attr, value in updates.items(): + setattr(row, attr, value) + row.updated_by = operator_id + + db.session.commit() + return _to_dto(row) + + +def resolve_warehouse( + route_mapped: "RouteMapping", config: WarehouseConfig, role: str, +) -> tuple[str, str]: + """按角色解析运行期 (external_org, warehouse_code):mapped 透传、fixed 覆盖。 + + 【AI 触发时机】匹配圈档/建单/库存查询需要「拨出仓、拨入仓、法人」三元组时, + 必须经本函数按类型配置解析;禁止绕过配置直取 RouteMapping 或硬编码仓库。 + + Args: + route_mapped: 来源路由映射档解析结果(DefaultRouteResolver 产物)。 + config: 类型配置的仓库定义(WarehouseConfig)。 + role: "from"(拨出)或 "to"(拨入),其他值 fail-closed。 + Returns: + (external_org, warehouse_code):mapped 双双透传映射档;fixed 取配置仓库, + external_org 非空覆盖法人、为空沿用映射档。 + Raises: + ValidationError: role 非法,或 fixed 角色缺 warehouse_code + (TRANSFER.WAREHOUSE_CONFIG_INVALID;解析侧兜底防线)。 + """ + if role == "from": + role_config = config.from_role + elif role == "to": + role_config = config.to_role + else: + raise ValidationError( + f"unknown warehouse role: {role}", code=WAREHOUSE_CONFIG_INVALID, details={"role": role}, + ) + if role_config.mode == "fixed": + if not role_config.warehouse_code: + raise ValidationError( + f"fixed warehouse role requires warehouse_code: {role}", + code=WAREHOUSE_CONFIG_INVALID, details={"role": role}, + ) + return (role_config.external_org or route_mapped.external_org, role_config.warehouse_code) + warehouse = route_mapped.from_warehouse if role == "from" else route_mapped.to_warehouse + return (route_mapped.external_org, warehouse) diff --git a/backend/app/services/in_transit_transfer/wecom_sender.py b/backend/app/services/in_transit_transfer/wecom_sender.py index 08cf8215..59b1a85c 100644 --- a/backend/app/services/in_transit_transfer/wecom_sender.py +++ b/backend/app/services/in_transit_transfer/wecom_sender.py @@ -59,10 +59,9 @@ class WecomSummarySender: matched=counts.get("matched_count", 0), pending=counts.get("pending_stock_check_count", 0), ), - "可执行: {executable} 数量不符: {blocked} 未成熟: {not_matured}".format( + "可执行: {executable} 数量不符: {blocked}".format( executable=counts.get("executable_count", 0), blocked=counts.get("blocked_count", 0), - not_matured=counts.get("not_matured_count", 0), ), ]) diff --git a/backend/app/services/schedule/__init__.py b/backend/app/services/schedule/__init__.py index 5e2330ab..eeda8605 100644 --- a/backend/app/services/schedule/__init__.py +++ b/backend/app/services/schedule/__init__.py @@ -343,11 +343,13 @@ def _register_headers_from_config() -> None: for name, cfg in get_all_schedule_sql_configs().items(): if cfg.alias_order and cfg.header_labels: register_schedule_header(name, cfg.alias_order, cfg.header_labels) - from app.services.schedule.shipping_inventory_rpa_finalize import register_inventory_rpa_excel_headers - from app.services.schedule.freight_receipt_rpa_finalize import register_receipt_rpa_excel_headers + from app.services.schedule.freight_rpa_onhand_finalize import register_inventory_rpa_excel_headers + from app.services.schedule.freight_rpa_inbound_finalize import register_inbound_rpa_excel_headers + from app.services.schedule.freight_rpa_outbound_finalize import register_outbound_rpa_excel_headers register_inventory_rpa_excel_headers() - register_receipt_rpa_excel_headers() + register_inbound_rpa_excel_headers() + register_outbound_rpa_excel_headers() def reload_config() -> dict[str, Any]: diff --git a/backend/app/services/schedule/freight_receipt_rpa_retention_job.py b/backend/app/services/schedule/freight_receipt_rpa_retention_job.py deleted file mode 100644 index 4f0513c5..00000000 --- a/backend/app/services/schedule/freight_receipt_rpa_retention_job.py +++ /dev/null @@ -1,49 +0,0 @@ -"""收料原样归档三年到期对象清理。""" - -from __future__ import annotations - -from datetime import datetime -from typing import Any - -from app import db -from app.models import ShippingReceiptReportFile -from app.services.file_assets.storage import file_asset_storage -from app.services.shipping_notice.audit_service import append_shipping_audit_event - - -def run_freight_receipt_rpa_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]: - """仅删除已到三年保留期的 MinIO 对象,永不删除文件事实、运行或审计。""" - limit = max(1, min(int((getattr(task, 'job_params', {}) or {}).get('limit', 100)), 1000)) - now = datetime.utcnow() - rows = ShippingReceiptReportFile.query.filter( - ShippingReceiptReportFile.archive_expires_at.is_not(None), - ShippingReceiptReportFile.archive_expires_at <= now, - ShippingReceiptReportFile.archive_deleted_at.is_(None), - ).order_by(ShippingReceiptReportFile.id).limit(limit).all() - success = failed = 0 - errors: list[str] = [] - for report_file in rows: - try: - file_asset_storage.delete_object(report_file.storage_key) - report_file.archive_deleted_at = now - report_file.archive_delete_result_json = {'status': 'deleted', 'deleted_at': now.isoformat()} - append_shipping_audit_event( - event_type='shipping_receipt_report_archive_deleted', aggregate_type='shipping_receipt_file', - aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention', - unit_id=report_file.unit_run_id, result='success', - before={'status': 'archived'}, after={'status': 'archive_deleted'}, - artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], - ) - success += 1 - except Exception as exc: - errors.append(f'{report_file.id}: {exc}') - append_shipping_audit_event( - event_type='shipping_receipt_report_archive_delete_attempted', aggregate_type='shipping_receipt_file', - aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention', - unit_id=report_file.unit_run_id, result='failure', - before={'status': 'archived'}, after={'status': 'archived', 'delete_error': str(exc)[:2000]}, - artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], - ) - failed += 1 - db.session.commit() - return len(rows), success, failed, 0, [{'file_id': row.id} for row in rows], errors, [{'step': 'receipt_retention', 'status': 'completed'}] diff --git a/backend/app/services/schedule/shipping_receipt_rpa_archive.py b/backend/app/services/schedule/freight_rpa_inbound_archive.py similarity index 66% rename from backend/app/services/schedule/shipping_receipt_rpa_archive.py rename to backend/app/services/schedule/freight_rpa_inbound_archive.py index b43ea9c9..cd25799e 100644 --- a/backend/app/services/schedule/shipping_receipt_rpa_archive.py +++ b/backend/app/services/schedule/freight_rpa_inbound_archive.py @@ -1,11 +1,11 @@ """ -backend/app/services/schedule/shipping_receipt_rpa_archive.py +backend/app/services/schedule/freight_rpa_inbound_archive.py -用途:货代收料 RPA 排程 run 的原始收料 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。 -依赖:ScheduleRun、ShippingReceiptReportFile / ShippingReceiptRpaUnitRun、 - file_asset_storage、timezone_util、freight_receipt_rpa_finalize.is_freight_receipt_rpa_task。 -逻辑:finalize 调用 persist_receipt_rpa_raw_zip_archive 写入磁盘与 summary; - 企微/下载展示名用「收料RPA-日期-时刻-收料」;包内条目 `{序号}_{source_code}.xlsx`; +用途:货代入站 RPA 排程 run 的原始入站 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。 +依赖:ScheduleRun、FreightRpaInboundReportFile / FreightRpaInboundUnitRun、 + file_asset_storage、timezone_util、freight_rpa_inbound_finalize.is_freight_inbound_rpa_task。 +逻辑:finalize 调用 persist_inbound_rpa_raw_zip_archive 写入磁盘与 summary; + 企微/下载展示名用「入站RPA-日期-时刻-入站」;包内条目 `{序号}_{source_code}.xlsx`; warehouse_id / file_id 只写在 manifest.json;磁盘归档键为 {run_no}.zip。 """ @@ -21,37 +21,37 @@ from typing import Any from flask import current_app from app.core.errors import NotFoundError -from app.models import ScheduleRun, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun +from app.models import ScheduleRun, FreightRpaInboundReportFile, FreightRpaInboundUnitRun from app.services.file_assets.storage import file_asset_storage -from app.services.schedule.freight_receipt_rpa_finalize import is_freight_receipt_rpa_task +from app.services.schedule.freight_rpa_inbound_finalize import is_freight_inbound_rpa_task from app.services.schedule.timezone_util import resolve_schedule_tzinfo -_RAW_ZIP_NOT_FOUND_MESSAGE = '原始收料包不存在,请重新执行或联系管理员' +_RAW_ZIP_NOT_FOUND_MESSAGE = '原始入站包不存在,请重新执行或联系管理员' _EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = { - 'raw_receipt_zip_available': False, - 'raw_receipt_zip_path': None, - 'raw_receipt_file_count': 0, - 'raw_receipt_file_ids': [], - 'raw_receipt_zip_size': 0, + 'raw_inbound_zip_available': False, + 'raw_inbound_zip_path': None, + 'raw_inbound_file_count': 0, + 'raw_inbound_file_ids': [], + 'raw_inbound_zip_size': 0, } -def get_receipt_archive_dir() -> str: +def get_inbound_archive_dir() -> str: """ - 返回收料 RPA 原始 ZIP 归档根目录(自动创建)。 + 返回入站 RPA 原始 ZIP 归档根目录(自动创建)。 核心逻辑:优先读 Flask config;值为 None/空时回落到 Config 默认路径, 避免 Path(None) 在 finalize 阶段把整次 ZIP 归档打成空 summary。 """ configured = '' if current_app: - raw = current_app.config.get('FREIGHT_RPA_RECEIPT_ARCHIVE_DIR') + raw = current_app.config.get('FREIGHT_RPA_INBOUND_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() + configured = str(Config.FREIGHT_RPA_INBOUND_ARCHIVE_DIR or '').strip() archive_dir = Path(configured) archive_dir.mkdir(parents=True, exist_ok=True) return str(archive_dir) @@ -87,9 +87,9 @@ def _attachment_when_from_run(run: ScheduleRun) -> datetime: return when_utc.astimezone(tz) -def receipt_rpa_attachment_stem(run: ScheduleRun) -> str: +def inbound_rpa_attachment_stem(run: ScheduleRun) -> str: """ - 收料 RPA 企微附件共用前缀:收料RPA-{yyyyMMdd}-{HHmm}(业务时区当地时间)。 + 入站 RPA 企微附件共用前缀:入站RPA-{yyyyMMdd}-{HHmm}(业务时区当地时间)。 Args: run: 排程执行记录。 @@ -98,84 +98,84 @@ def receipt_rpa_attachment_stem(run: ScheduleRun) -> str: 不含角色后缀与扩展名的展示名前缀。 """ when = _attachment_when_from_run(run) - return f"收料RPA-{when.strftime('%Y%m%d')}-{when.strftime('%H%M')}" + return f"入站RPA-{when.strftime('%Y%m%d')}-{when.strftime('%H%M')}" -def receipt_raw_zip_download_name(run: ScheduleRun) -> str: +def inbound_raw_zip_download_name(run: ScheduleRun) -> str: """ - 收料 ZIP 的企微/浏览器下载展示名。 + 入站 ZIP 的企微/浏览器下载展示名。 核心逻辑:磁盘归档仍为 {run_no}.zip;本函数只影响 Content-Disposition 与企微 filename。 """ - return f'{receipt_rpa_attachment_stem(run)}-收料.zip' + return f'{inbound_rpa_attachment_stem(run)}-入站.zip' -def receipt_rpa_result_excel_name(run: ScheduleRun) -> str: - """收料 RPA 结果 Excel 的企微/下载展示名(对齐库存 inventory_rpa_result_excel_name)。""" - return f'{receipt_rpa_attachment_stem(run)}-结果.xlsx' +def inbound_rpa_result_excel_name(run: ScheduleRun) -> str: + """入站 RPA 结果 Excel 的企微/下载展示名(对齐库存 onhand_rpa_result_excel_name)。""" + return f'{inbound_rpa_attachment_stem(run)}-结果.xlsx' -def _receipt_raw_zip_archive_path(run_no: str) -> Path: +def _inbound_raw_zip_archive_path(run_no: str) -> Path: """磁盘归档路径:/.zip。""" - return Path(get_receipt_archive_dir()) / f'{run_no}.zip' + return Path(get_inbound_archive_dir()) / f'{run_no}.zip' -def _iter_packable_receipt_files(run: ScheduleRun): +def _iter_packable_inbound_files(run: ScheduleRun): """ 遍历该 run 下可打包的收料归档文件。 核心逻辑:join unit_run,过滤 archive_deleted_at 为空;按 file id 升序稳定序号。 Yields: - ShippingReceiptReportFile: 可从 MinIO 读取的归档记录。 + FreightRpaInboundReportFile: 可从 MinIO 读取的归档记录。 """ - if not is_freight_receipt_rpa_task(getattr(run, 'task', None)): + if not is_freight_inbound_rpa_task(getattr(run, 'task', None)): return rows = ( - ShippingReceiptReportFile.query.join( - ShippingReceiptRpaUnitRun, - ShippingReceiptReportFile.unit_run_id == ShippingReceiptRpaUnitRun.id, + FreightRpaInboundReportFile.query.join( + FreightRpaInboundUnitRun, + FreightRpaInboundReportFile.unit_run_id == FreightRpaInboundUnitRun.id, ) .filter( - ShippingReceiptRpaUnitRun.schedule_run_id == run.id, - ShippingReceiptReportFile.archive_deleted_at.is_(None), + FreightRpaInboundUnitRun.schedule_run_id == run.id, + FreightRpaInboundReportFile.archive_deleted_at.is_(None), ) - .order_by(ShippingReceiptReportFile.id.asc()) + .order_by(FreightRpaInboundReportFile.id.asc()) .all() ) for report_file in rows: yield report_file -def receipt_raw_zip_available_from_summary(summary: dict[str, Any] | None) -> bool: +def inbound_raw_zip_available_from_summary(summary: dict[str, Any] | None) -> bool: """ - 从 response_summary_json 读取原始收料 ZIP 是否可下载。 + 从 response_summary_json 读取原始入站 ZIP 是否可下载。 核心逻辑:列表序列化只读 summary,不查库、不访问磁盘。 """ if not isinstance(summary, dict): return False - return bool(summary.get('raw_receipt_zip_available')) + return bool(summary.get('raw_inbound_zip_available')) -def persist_receipt_rpa_raw_zip_archive(run: ScheduleRun) -> dict[str, Any]: +def persist_inbound_rpa_raw_zip_archive(run: ScheduleRun) -> dict[str, Any]: """ - finalize 阶段预生成原始收料 ZIP 归档并返回 summary 字段。 + finalize 阶段预生成原始入站 ZIP 归档并返回 summary 字段。 核心逻辑:从 MinIO 拉取各单元归档字节 → 写入 /.zip - (含 manifest.json);无可用文件时返回 raw_receipt_zip_available=false。 + (含 manifest.json);无可用文件时返回 raw_inbound_zip_available=false。 Args: - run: 收料 RPA ScheduleRun。 + run: 入站 RPA ScheduleRun。 Returns: - dict: raw_receipt_zip_available / path / file_count / file_ids / zip_size。 + dict: raw_inbound_zip_available / path / file_count / file_ids / zip_size。 """ - packable_files = list(_iter_packable_receipt_files(run)) + packable_files = list(_iter_packable_inbound_files(run)) if not packable_files: return dict(_EMPTY_ARCHIVE_SUMMARY) - archive_path = _receipt_raw_zip_archive_path(run.run_no) + archive_path = _inbound_raw_zip_archive_path(run.run_no) files_manifest: list[dict[str, Any]] = [] with zipfile.ZipFile(archive_path, 'w', compression=zipfile.ZIP_DEFLATED) as archive: @@ -217,19 +217,19 @@ def persist_receipt_rpa_raw_zip_archive(run: ScheduleRun) -> dict[str, Any]: ) return { - 'raw_receipt_zip_available': True, - 'raw_receipt_zip_path': str(archive_path.resolve()), - 'raw_receipt_file_count': len(files_manifest), - 'raw_receipt_file_ids': [item['file_id'] for item in files_manifest], - 'raw_receipt_zip_size': int(archive_path.stat().st_size), + 'raw_inbound_zip_available': True, + 'raw_inbound_zip_path': str(archive_path.resolve()), + 'raw_inbound_file_count': len(files_manifest), + 'raw_inbound_file_ids': [item['file_id'] for item in files_manifest], + 'raw_inbound_zip_size': int(archive_path.stat().st_size), } -def _is_allowed_receipt_archive_path(zip_path: Path) -> bool: +def _is_allowed_inbound_archive_path(zip_path: Path) -> bool: """ 校验归档 ZIP 路径是否安全可下载。 - 核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_RECEIPT_ARCHIVE_DIR 内。 + 核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_INBOUND_ARCHIVE_DIR 内。 """ resolved = zip_path.resolve() if resolved.suffix.lower() != '.zip': @@ -237,7 +237,7 @@ def _is_allowed_receipt_archive_path(zip_path: Path) -> bool: if not resolved.is_file(): return False - archive_dir = Path(get_receipt_archive_dir()).resolve() + archive_dir = Path(get_inbound_archive_dir()).resolve() try: resolved.relative_to(archive_dir) except ValueError: @@ -245,12 +245,12 @@ def _is_allowed_receipt_archive_path(zip_path: Path) -> bool: return True -def resolve_receipt_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]: +def resolve_inbound_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]: """ - 解析 run 已归档的原始收料 ZIP 路径供下载接口 send_file。 + 解析 run 已归档的原始入站 ZIP 路径供下载接口 send_file。 - 核心逻辑:读取 summary.raw_receipt_zip_path,校验文件存在、后缀为 .zip、 - 且真实路径位于 FREIGHT_RPA_RECEIPT_ARCHIVE_DIR 内;任一不满足则 404。 + 核心逻辑:读取 summary.raw_inbound_zip_path,校验文件存在、后缀为 .zip、 + 且真实路径位于 FREIGHT_RPA_INBOUND_ARCHIVE_DIR 内;任一不满足则 404。 Returns: tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。 @@ -259,18 +259,18 @@ def resolve_receipt_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]: NotFoundError: summary 未标记可用、路径非法或归档文件已丢失。 """ summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} - if not receipt_raw_zip_available_from_summary(summary): + if not inbound_raw_zip_available_from_summary(summary): raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE) - zip_path_raw = str(summary.get('raw_receipt_zip_path') or '').strip() + zip_path_raw = str(summary.get('raw_inbound_zip_path') or '').strip() if not zip_path_raw: raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE) zip_path = Path(zip_path_raw) - if not _is_allowed_receipt_archive_path(zip_path): + if not _is_allowed_inbound_archive_path(zip_path): raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE) - return zip_path.resolve(), receipt_raw_zip_download_name(run) + return zip_path.resolve(), inbound_raw_zip_download_name(run) def _sanitize_zip_segment(value: str) -> str: diff --git a/backend/app/services/schedule/freight_receipt_rpa_finalize.py b/backend/app/services/schedule/freight_rpa_inbound_finalize.py similarity index 58% rename from backend/app/services/schedule/freight_receipt_rpa_finalize.py rename to backend/app/services/schedule/freight_rpa_inbound_finalize.py index 6dc04d8d..83c742a3 100644 --- a/backend/app/services/schedule/freight_receipt_rpa_finalize.py +++ b/backend/app/services/schedule/freight_rpa_inbound_finalize.py @@ -1,9 +1,11 @@ """ -backend/app/services/schedule/freight_receipt_rpa_finalize.py +backend/app/services/schedule/freight_rpa_inbound_finalize.py -用途:独立收料 RPA 排程等待态收口——进度回写、全单元终态后写计数、预生成 ZIP、发企微。 -依赖:ShippingReceiptRpaUnitRun、shipping_receipt_rpa_archive、scheduler_service 企微通知。 -逻辑:每笔回调 → refresh 进度计数 → 全终态时 persist ZIP → _notify_schedule_run_wecom。 +用途:独立入站 RPA 排程等待态收口——进度回写、全单元终态后写计数、预生成 ZIP、发企微; + 另含超时对账:排程 run 级(每轮 tick)与按需触发孤儿单元级(schedule_run_id=NULL)。 +依赖:FreightRpaInboundUnitRun、freight_rpa_inbound_archive、scheduler_service 企微通知。 +逻辑:每笔回调 → refresh 进度计数 → 全终态时 persist ZIP → _notify_schedule_run_wecom; + 超时对账只终态化失败,绝不自动重试或重发(恢复走人工显式重试入口)。 """ from __future__ import annotations @@ -12,56 +14,58 @@ from datetime import datetime, timedelta from typing import Any from flask import current_app +from sqlalchemy import func from app import db from app.models import ScheduleRun, ScheduleTask -from app.models import ShippingReceiptRpaUnitRun +from app.models import FreightRpaInboundUnitRun from app.services.schedule import normalize_platform_api_path, register_schedule_header, resolve_schedule_header from app.services.schedule.excel_service import export_schedule_result_excel -from app.services.schedule.freight_receipt_rpa_job import AWAITING_RECEIPT_RPA_CALLBACK_STATUS, RECEIPT_RPA_JOB_KEY +from app.services.schedule.freight_rpa_inbound_job import AWAITING_INBOUND_RPA_CALLBACK_STATUS, INBOUND_RPA_JOB_KEY +from app.services.freight_rpa.inbound.trigger_io import SCHEMA as INBOUND_TRIGGER_SCHEMA from app.services.shipping_notice.audit_service import append_shipping_audit_event _RECEIPT_RPA_HEADER_ORDER = [ "source_code", "warehouse_id", "connector_type", - "receipt_file_count", + "inbound_file_count", "export_status", "skip_reason", "error_message", ] _RECEIPT_RPA_HEADER_LABELS = { - "source_code": "收料源", + "source_code": "入站源", "warehouse_id": "仓库", "connector_type": "连接器", - "receipt_file_count": "归档文件数", + "inbound_file_count": "归档文件数", "export_status": "导出状态", "skip_reason": "跳过原因", "error_message": "错误原因", } -def register_receipt_rpa_excel_headers() -> None: +def register_inbound_rpa_excel_headers() -> None: """ - 注册货代收料 RPA 排程 Excel 列头(幂等)。 + 注册货代入站 RPA 排程 Excel 列头(幂等)。 核心逻辑:由 schedule.__init__._register_headers_from_config 在 reload 后调用,避免被 clear 冲掉。 """ register_schedule_header( - RECEIPT_RPA_JOB_KEY, + INBOUND_RPA_JOB_KEY, _RECEIPT_RPA_HEADER_ORDER, _RECEIPT_RPA_HEADER_LABELS, ) -def _build_receipt_finalize_details(units: list[ShippingReceiptRpaUnitRun]) -> list[dict[str, Any]]: +def _build_inbound_finalize_details(units: list[FreightRpaInboundUnitRun]) -> list[dict[str, Any]]: """ - 收料单元 → 排程 Excel 明细行(对齐库存 finalize 的行结构)。 + 入站单元 → 排程 Excel 明细行(对齐库存 finalize 的行结构)。 核心逻辑:empty 归一为 skipped、cancelled 归一为 failed,与卡片 计数口径一致; - 归档文件数便于与原始收料包内 {序号}_{source_code}.xlsx 条目对账。 + 归档文件数便于与原始入站包内 {序号}_{source_code}.xlsx 条目对账。 Args: - units: 该 run 的全部收料单元(已全部终态)。 + units: 该 run 的全部入站单元(已全部终态)。 Returns: list[dict]: 按 unit.id 升序的明细行。 @@ -79,7 +83,7 @@ def _build_receipt_finalize_details(units: list[ShippingReceiptRpaUnitRun]) -> l 'source_code': unit.source_code, 'warehouse_id': unit.warehouse_id or '', 'connector_type': unit.connector_type or '', - 'receipt_file_count': len(unit.files or []), + 'inbound_file_count': len(unit.files or []), 'export_status': export_status, 'skip_reason': str(unit.error_code or '') if export_status == 'skipped' else '', 'error_message': str(unit.error_message or '')[:500] if export_status == 'failed' else '', @@ -87,25 +91,25 @@ def _build_receipt_finalize_details(units: list[ShippingReceiptRpaUnitRun]) -> l return rows -def should_defer_receipt_schedule_run(task: ScheduleTask, step_logs: list | None) -> bool: - """仅当独立收料 job 成功写入 trigger 后延后终态,避免影响库存 job 判断。""" +def should_defer_inbound_schedule_run(task: ScheduleTask, step_logs: list | None) -> bool: + """仅当独立入站 job 成功写入 trigger 后延后终态,避免影响库存 job 判断。""" return bool( task.schedule_type == 'platform_job' - and normalize_platform_api_path(task.platform_api_path) == RECEIPT_RPA_JOB_KEY - and any(isinstance(row, dict) and row.get('status') == AWAITING_RECEIPT_RPA_CALLBACK_STATUS for row in step_logs or []) + and normalize_platform_api_path(task.platform_api_path) == INBOUND_RPA_JOB_KEY + and any(isinstance(row, dict) and row.get('status') == AWAITING_INBOUND_RPA_CALLBACK_STATUS for row in step_logs or []) ) -def is_awaiting_receipt_rpa_schedule_run(run: ScheduleRun | None) -> bool: - """判断 run 是否为独立收料 callback 等待态,供 worker 启动恢复时保护。""" +def is_awaiting_inbound_rpa_schedule_run(run: ScheduleRun | None) -> bool: + """判断 run 是否为独立入站 callback 等待态,供 worker 启动恢复时保护。""" summary = run.response_summary_json if run is not None and isinstance(run.response_summary_json, dict) else {} - return bool(run is not None and run.status == 'running' and summary.get('awaiting_receipt_rpa')) + return bool(run is not None and run.status == 'running' and summary.get('awaiting_inbound_rpa')) -def apply_deferred_receipt_schedule_run_state( +def apply_deferred_inbound_schedule_run_state( run: ScheduleRun, task: ScheduleTask, *, total_count: int, details: list[dict], errors: list[str], step_logs: list[dict], ) -> ScheduleRun: - """将收料 run 保持为 awaiting callback,终态由所有收料单元回调完成后专用服务写入。""" + """将收料 run 保持为 awaiting callback,终态由所有入站单元回调完成后专用服务写入。""" run.status = 'running' run.started_at = run.started_at or datetime.utcnow() run.total_count = total_count @@ -114,18 +118,18 @@ def apply_deferred_receipt_schedule_run_state( run.skipped_count = 0 run.finished_at = None run.step_logs = step_logs - run.response_summary_json = {'awaiting_receipt_rpa': True, 'pending_details': details, 'errors': errors[:20]} + run.response_summary_json = {'awaiting_inbound_rpa': True, 'pending_details': details, 'errors': errors[:20]} db.session.commit() return run -def refresh_receipt_schedule_run_progress(schedule_run_id: int) -> dict: +def refresh_inbound_schedule_run_progress(schedule_run_id: int) -> dict: """ - 收料单元每笔回调后回写排程 run 进度计数(非终态,对齐库存 inventory-batch-progress)。 + 入站单元每笔回调后回写排程 run 进度计数(非终态,对齐库存 inventory-batch-progress)。 - 核心逻辑:仅在 awaiting_receipt_rpa 时,按已终态单元聚合 success/empty/failed 写入 + 核心逻辑:仅在 awaiting_inbound_rpa 时,按已终态单元聚合 success/empty/failed 写入 ScheduleRun 计数与 response_summary_json.progress;不改 status/finished_at, - 终态仍由 finalize_receipt_schedule_run_if_complete 负责。 + 终态仍由 finalize_inbound_schedule_run_if_complete 负责。 Args: schedule_run_id: 排程执行记录主键。 @@ -137,10 +141,10 @@ def refresh_receipt_schedule_run_progress(schedule_run_id: int) -> dict: if run is None: return {'updated': False, 'reason': 'schedule_run_not_found'} summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} - if run.status != 'running' or not summary.get('awaiting_receipt_rpa'): - return {'updated': False, 'reason': 'not_awaiting_receipt_callback'} + if run.status != 'running' or not summary.get('awaiting_inbound_rpa'): + return {'updated': False, 'reason': 'not_awaiting_inbound_callback'} - units = ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).all() + units = FreightRpaInboundUnitRun.query.filter_by(schedule_run_id=run.id).all() success_count = sum(unit.status == 'success' for unit in units) skipped_count = sum(unit.status == 'empty' for unit in units) failed_count = sum(unit.status in {'failed', 'cancelled'} for unit in units) @@ -169,11 +173,11 @@ def refresh_receipt_schedule_run_progress(schedule_run_id: int) -> dict: } -def report_receipt_batch_progress(payload: dict) -> dict: +def report_inbound_batch_progress(payload: dict) -> dict: """ - Worker 每完成一笔收料导出后的实时进度回写(非终态,对齐 inventory-batch-progress)。 + Worker 每完成一笔入站导出后的实时进度回写(非终态,对齐 inventory-batch-progress)。 - 核心逻辑:校验 schema + schedule_run_id;仅 awaiting_receipt_rpa 时抬升 + 核心逻辑:校验 schema + schedule_run_id;仅 awaiting_inbound_rpa 时抬升 ScheduleRun 计数;最终以 unit 终态回调 + finalize 为准。 Args: @@ -182,7 +186,7 @@ def report_receipt_batch_progress(payload: dict) -> dict: Returns: dict: updated / rejected 及当前计数。 """ - if payload.get('schema_version') != 'shipping_receipt_rpa.v1': + if payload.get('schema_version') != INBOUND_TRIGGER_SCHEMA: return {'updated': False, 'reason': 'callback_schema_invalid'} try: schedule_run_id = int(payload.get('schedule_run_id')) if payload.get('schedule_run_id') is not None else None @@ -195,8 +199,8 @@ def report_receipt_batch_progress(payload: dict) -> dict: if run is None: return {'updated': False, 'reason': 'schedule_run_not_found'} summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} - if run.status != 'running' or not summary.get('awaiting_receipt_rpa'): - return {'updated': False, 'reason': 'not_awaiting_receipt_callback'} + if run.status != 'running' or not summary.get('awaiting_inbound_rpa'): + return {'updated': False, 'reason': 'not_awaiting_inbound_callback'} incoming = { 'success_count': max(0, int(payload.get('success_count') or 0)), @@ -224,18 +228,18 @@ def report_receipt_batch_progress(payload: dict) -> dict: } -def mark_receipt_unit_processing(payload: dict) -> dict: +def mark_inbound_unit_processing(payload: dict) -> dict: """ - Worker 开始导出某收料单元时标记 processing(对齐库存 claimed / rpa_exporting)。 + Worker 开始导出某入站单元时标记 processing(对齐库存 claimed / rpa_exporting)。 核心逻辑:仅 awaiting_rpa → processing;已终态或已 processing 幂等返回。 """ - if payload.get('schema_version') != 'shipping_receipt_rpa.v1': + if payload.get('schema_version') != INBOUND_TRIGGER_SCHEMA: return {'updated': False, 'reason': 'callback_schema_invalid'} callback_id = str(payload.get('callback_id') or '').strip() if not callback_id: return {'updated': False, 'reason': 'callback_id_required'} - unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=callback_id).one_or_none() + unit = FreightRpaInboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none() if unit is None: return {'updated': False, 'reason': 'unit_not_found'} if unit.status in {'success', 'empty', 'failed', 'cancelled'}: @@ -243,28 +247,28 @@ def mark_receipt_unit_processing(payload: dict) -> dict: if unit.status == 'processing': return {'updated': True, 'status': 'processing', 'idempotent': True} unit.status = 'processing' - # started_at 是收料超时对账的活动锚(_receipt_last_activity):在飞单元必须有 + # started_at 是入站超时对账的活动锚(_inbound_last_activity):在飞单元必须有 # 开始时间,否则长静默批次无法区分"在跑"与"worker 已死"。 unit.started_at = datetime.utcnow() db.session.commit() if unit.schedule_run_id: - refresh_receipt_schedule_run_progress(unit.schedule_run_id) + refresh_inbound_schedule_run_progress(unit.schedule_run_id) return {'updated': True, 'status': 'processing', 'unit_run_id': unit.id} -def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict: +def finalize_inbound_schedule_run_if_complete(schedule_run_id: int) -> dict: """ 当收料 run 的全部单元已回调后写入独立排程终态,不读取库存回调结果。 - 核心逻辑:聚合单元计数 → 预生成原始收料 ZIP 写入 summary → 企微发 textcard+单 ZIP。 + 核心逻辑:聚合单元计数 → 预生成原始入站 ZIP 写入 summary → 企微发 textcard+单 ZIP。 """ run = db.session.get(ScheduleRun, schedule_run_id) if run is None: return {'finalized': False, 'reason': 'schedule_run_not_found'} summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} - if not summary.get('awaiting_receipt_rpa'): - return {'finalized': False, 'reason': 'not_awaiting_receipt_callback'} - units = ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).all() + if not summary.get('awaiting_inbound_rpa'): + return {'finalized': False, 'reason': 'not_awaiting_inbound_callback'} + units = FreightRpaInboundUnitRun.query.filter_by(schedule_run_id=run.id).all() terminal = {'success', 'empty', 'failed', 'cancelled'} if any(unit.status not in terminal for unit in units): return {'finalized': False, 'reason': 'units_pending'} @@ -280,9 +284,9 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict: run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed' run.error_message = '; '.join(filter(None, (unit.error_message for unit in units if unit.status == 'failed')))[:2000] or None - # [STEP] 对齐库存 finalize:终态前生成收料汇总 Excel,企微在 textcard+ZIP 之外多发一条 [文件] 消息。 - register_receipt_rpa_excel_headers() - header_order, header_labels = resolve_schedule_header(RECEIPT_RPA_JOB_KEY) + # [STEP] 对齐库存 finalize:终态前生成入站汇总 Excel,企微在 textcard+ZIP 之外多发一条 [文件] 消息。 + register_inbound_rpa_excel_headers() + header_order, header_labels = resolve_schedule_header(INBOUND_RPA_JOB_KEY) excel_export_ok = True excel_data, excel_name, excel_size = None, None, 0 try: @@ -296,49 +300,49 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict: 'failed_count': failed_count, 'duration_ms': run.duration_ms, }, - details=_build_receipt_finalize_details(units), + details=_build_inbound_finalize_details(units), header_order=header_order, header_labels=header_labels, ) except Exception as excel_exc: excel_export_ok = False current_app.logger.error( - '[schedule-run] receipt RPA excel export failed for run %s: %s', run.run_no, excel_exc, + '[schedule-run] inbound RPA excel export failed for run %s: %s', run.run_no, excel_exc, ) # 对齐库存:全成功批次的 Excel 失败要降级,不得让收件人误以为一切正常。 if run.status == 'success': run.status = 'partial_failed' run.error_message = '; '.join(filter(None, [run.error_message, f'Excel导出失败: {excel_exc}']))[:2000] else: - # 企微/下载展示名:收料RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。 - from app.services.schedule.shipping_receipt_rpa_archive import receipt_rpa_result_excel_name + # 企微/下载展示名:入站RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。 + from app.services.schedule.freight_rpa_inbound_archive import inbound_rpa_result_excel_name - excel_name = receipt_rpa_result_excel_name(run) + excel_name = inbound_rpa_result_excel_name(run) run.excel_file_data = excel_data run.excel_file_name = excel_name if excel_data else None run.excel_file_size = excel_size or 0 - # [STEP] 对齐库存:终态前预生成原始收料 ZIP,企微只发一个包。 + # [STEP] 对齐库存:终态前预生成原始入站 ZIP,企微只发一个包。 archive_summary = { - 'raw_receipt_zip_available': False, - 'raw_receipt_zip_path': None, - 'raw_receipt_file_count': 0, - 'raw_receipt_file_ids': [], - 'raw_receipt_zip_size': 0, + 'raw_inbound_zip_available': False, + 'raw_inbound_zip_path': None, + 'raw_inbound_file_count': 0, + 'raw_inbound_file_ids': [], + 'raw_inbound_zip_size': 0, } try: - from app.services.schedule.shipping_receipt_rpa_archive import persist_receipt_rpa_raw_zip_archive + from app.services.schedule.freight_rpa_inbound_archive import persist_inbound_rpa_raw_zip_archive - archive_summary = persist_receipt_rpa_raw_zip_archive(run) + archive_summary = persist_inbound_rpa_raw_zip_archive(run) except Exception as archive_exc: current_app.logger.error( - '[schedule-run] receipt RPA zip archive failed for run %s: %s', + '[schedule-run] inbound RPA zip archive failed for run %s: %s', run.run_no, archive_exc, ) run.response_summary_json = { **summary, - 'awaiting_receipt_rpa': False, + 'awaiting_inbound_rpa': False, 'success_count': success_count, 'empty_count': skipped_count, 'failed_count': failed_count, @@ -347,7 +351,7 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict: **archive_summary, } db.session.commit() - # 通知与库存 RPA 完全同构:run 终态后走通用排程出口一次性发 textcard+收料 ZIP。 + # 通知与库存 RPA 完全同构:run 终态后走通用排程出口一次性发 textcard+入站 ZIP。 try: task = run.task if task is not None and task.notify_enabled: @@ -356,32 +360,32 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict: _notify_schedule_run_wecom(task, run) db.session.commit() except Exception as wecom_exc: - current_app.logger.error('[schedule-run] receipt RPA wecom notify failed: %s', wecom_exc) + current_app.logger.error('[schedule-run] inbound RPA wecom notify failed: %s', wecom_exc) return {'finalized': True, 'status': run.status} -def _receipt_timeout_seconds() -> int: - """读取收料回调等待上限;超时只标记失败,不会自动重试或重发。""" +def _inbound_timeout_seconds() -> int: + """读取入站回调等待上限;超时只标记失败,不会自动重试或重发。""" try: - return max(60, int(current_app.config.get('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS', 900))) + return max(60, int(current_app.config.get('FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS', 900))) except (TypeError, ValueError): return 900 -def is_freight_receipt_rpa_task(task: ScheduleTask | None) -> bool: - """识别独立收料 RPA 排程,避免超时回收影响库存或其他平台任务。""" +def is_freight_inbound_rpa_task(task: ScheduleTask | None) -> bool: + """识别独立入站 RPA 排程,避免超时回收影响库存或其他平台任务。""" return bool( task and task.schedule_type == 'platform_job' - and normalize_platform_api_path(task.platform_api_path) == RECEIPT_RPA_JOB_KEY + and normalize_platform_api_path(task.platform_api_path) == INBOUND_RPA_JOB_KEY ) -def _receipt_last_activity(run: ScheduleRun, units: list[ShippingReceiptRpaUnitRun]) -> datetime: +def _inbound_last_activity(run: ScheduleRun, units: list[FreightRpaInboundUnitRun]) -> datetime: """收料 run 的最后活动锚:run 开始时间与全部单元 started/finished 时间的最大值。 语义为「笔间静默」:worker 每开始/完成一笔都会推进锚点,锚点静默超过 - FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS 才判定 worker 不再活动。刻意不含单元 + FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS 才判定 worker 不再活动。刻意不含单元 created_at——批量 trigger 中排队单元的创建时间不代表活动,否则整批永不超时。 极端长单笔(单站点导出超过 timeout)会被判超时,需按最慢单笔调大该配置。 """ @@ -394,57 +398,78 @@ def _receipt_last_activity(run: ScheduleRun, units: list[ShippingReceiptRpaUnitR return max(stamps) -def _recover_stale_receipt_run(run: ScheduleRun, *, cutoff: datetime, timeout_seconds: int) -> bool: - """将无回调的独立收料运行收口为失败,保留其单元与触发审计事实。 +def _fail_inbound_unit_with_timeout( + unit: FreightRpaInboundUnitRun, *, now: datetime, timeout_seconds: int, + run_no: str | None = None, +) -> None: + """单个入站单元回调超时收口为失败并写审计(run 级与孤儿级回收共用的唯一实现)。 - 截止判据为最后活动锚(_receipt_last_activity)而非 run.started_at—— + 核心逻辑:错误码/错误文案/审计事件三者的单一事实来源——run 级扫描与孤儿 + 单元扫描共用本函数收口单元,防止两条路径语义漂移。只改单元不 commit, + 事务归属调用方。 + + Args: + unit: 待收口的非终态入站单元。 + now: 收口时刻(同批单元共享同一时间戳)。 + timeout_seconds: 超时窗(写入错误文案与审计 metadata)。 + run_no: 所属排程 run 号(run 级回收传实;孤儿单元无排程,保持 None)。 + Returns: + None。 + """ + before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message} + unit.status = 'failed' + unit.error_code = 'RPA.INBOUND_CALLBACK_TIMEOUT' + unit.error_message = f'Inbound RPA callback timed out after {timeout_seconds} seconds' + unit.finished_at = now + append_shipping_audit_event( + event_type='shipping_inbound_rpa_callback_timeout', aggregate_type='shipping_inbound_unit', + aggregate_id=str(unit.id), run_no=run_no, actor_type='worker', actor_id='schedule-recovery', + unit_id=unit.id, result='failure', before=before, + after={'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}, + metadata={'timeout_seconds': timeout_seconds}, + ) + + +def _recover_stale_inbound_run(run: ScheduleRun, *, cutoff: datetime, timeout_seconds: int) -> bool: + """将无回调的独立入站运行收口为失败,保留其单元与触发审计事实。 + + 截止判据为最后活动锚(_inbound_last_activity)而非 run.started_at—— 串行长批次(>timeout)只要仍有笔间活动就不得被误杀。 """ summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} - if not summary.get('awaiting_receipt_rpa') or run.status != 'running' or not run.started_at: + if not summary.get('awaiting_inbound_rpa') or run.status != 'running' or not run.started_at: return False task = run.task or db.session.get(ScheduleTask, run.schedule_task_id) - if not is_freight_receipt_rpa_task(task): + if not is_freight_inbound_rpa_task(task): return False - units = ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).all() - if _receipt_last_activity(run, units) > cutoff: + units = FreightRpaInboundUnitRun.query.filter_by(schedule_run_id=run.id).all() + if _inbound_last_activity(run, units) > cutoff: return False now = datetime.utcnow() pending = [unit for unit in units if unit.status in {'queued', 'awaiting_rpa', 'processing'}] for unit in pending: - before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message} - unit.status = 'failed' - unit.error_code = 'RPA.RECEIPT_CALLBACK_TIMEOUT' - unit.error_message = f'Receipt RPA callback timed out after {timeout_seconds} seconds' - unit.finished_at = now - append_shipping_audit_event( - event_type='shipping_receipt_rpa_callback_timeout', aggregate_type='shipping_receipt_unit', - aggregate_id=str(unit.id), run_no=run.run_no, actor_type='worker', actor_id='schedule-recovery', - unit_id=unit.id, result='failure', before=before, - after={'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}, - metadata={'timeout_seconds': timeout_seconds}, - ) + _fail_inbound_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds, run_no=run.run_no) run.status = 'failed' run.finished_at = now run.duration_ms = int((now - run.started_at).total_seconds() * 1000) run.failed_count = len(pending) or max(1, int(run.failed_count or 0)) - run.error_message = f'收料 RPA 回调等待超时({timeout_seconds} 秒)' + run.error_message = f'入站 RPA 回调等待超时({timeout_seconds} 秒)' run.step_logs = [*(run.step_logs or []), { - 'step': 'freight_receipt_rpa', 'status': 'failed', + 'step': 'freight_inbound_rpa', 'status': 'failed', 'detail': {'message': run.error_message, 'timeout_seconds': timeout_seconds}, }] - run.response_summary_json = {**summary, 'awaiting_receipt_rpa': False, 'recovered_reason': 'receipt_rpa_callback_timeout'} + run.response_summary_json = {**summary, 'awaiting_inbound_rpa': False, 'recovered_reason': 'inbound_rpa_callback_timeout'} return True -def recover_stale_receipt_rpa_schedule_runs(task: ScheduleTask) -> int: - """在同一收料排程开始前回收超时运行,解除后续 Cron/手动执行的互斥。""" - if not is_freight_receipt_rpa_task(task): +def recover_stale_inbound_rpa_schedule_runs(task: ScheduleTask) -> int: + """在同一入站排程开始前回收超时运行,解除后续 Cron/手动执行的互斥。""" + if not is_freight_inbound_rpa_task(task): return 0 - timeout_seconds = _receipt_timeout_seconds() + timeout_seconds = _inbound_timeout_seconds() cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds) recovered = sum( - _recover_stale_receipt_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds) + _recover_stale_inbound_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds) for run in ScheduleRun.query.filter_by(schedule_task_id=task.id, status='running').all() ) if recovered: @@ -452,14 +477,57 @@ def recover_stale_receipt_rpa_schedule_runs(task: ScheduleTask) -> int: return recovered -def recover_all_stale_receipt_rpa_schedule_runs() -> int: - """Worker 启动时扫描全部超时收料回调,避免重启后运行永久卡住。""" - timeout_seconds = _receipt_timeout_seconds() +def recover_all_stale_inbound_rpa_schedule_runs() -> int: + """Worker 启动时扫描全部超时入站回调,避免重启后运行永久卡住。""" + timeout_seconds = _inbound_timeout_seconds() cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds) recovered = sum( - _recover_stale_receipt_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds) + _recover_stale_inbound_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds) for run in ScheduleRun.query.filter_by(status='running').all() ) if recovered: db.session.commit() return recovered + + +def recover_all_stale_orphan_inbound_units() -> int: + """回收按需触发(无排程绑定)的超时入站单元,解除来源投影永久 fetching。 + + 【AI 触发时机】仅由排程队列每轮领取维护(queue_service)调用。调拨工作台 + 重试/自动调拨补抓创建的单元 schedule_run_id 为 NULL(见 inbound_trigger_service), + 不在 run 级扫描(recover_all_stale_inbound_rpa_schedule_runs 按 run 遍历)范围内; + Worker 网页异常关闭后回调永不到达,若不回收则来源投影(source_file_status) + 永久 fetching、前端重试按钮永久锁死(2026-10-16 事故根因)。 + + 核心逻辑:[STEP 1] 扫 schedule_run_id IS NULL、状态非终态、活动锚 + (coalesce(started_at, created_at):与 run 级同为活动锚思想,单元未被领取 + 无 started_at 时以 created_at 兜底;注意 run 级 _inbound_last_activity 是 + 笔间静默口径、刻意不含 created_at,两者语义不同)超过 + FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS 的单元;admin 单元重试(retry_inbound_rpa_unit) + 原样复制 schedule_run_id,其 retry 单元同为孤儿,一并覆盖。 + [STEP 2] 逐单元经 _fail_inbound_unit_with_timeout 收口(failed + + RPA.INBOUND_CALLBACK_TIMEOUT + 审计,与 run 级扫描同一实现零漂移); + 绝不自动重试或重发——恢复走调拨工作台显式「重试 RPA」 + (与 recover_stale_waiting_source_jobs 口径一致)。 + + Returns: + 本次回收的单元数。 + """ + timeout_seconds = _inbound_timeout_seconds() + cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds) + orphans = ( + FreightRpaInboundUnitRun.query + .filter( + FreightRpaInboundUnitRun.schedule_run_id.is_(None), + FreightRpaInboundUnitRun.status.in_(('queued', 'awaiting_rpa', 'processing')), + func.coalesce(FreightRpaInboundUnitRun.started_at, FreightRpaInboundUnitRun.created_at) < cutoff, + ) + .all() + ) + if not orphans: + return 0 + now = datetime.utcnow() + for unit in orphans: + _fail_inbound_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds) + db.session.commit() + return len(orphans) diff --git a/backend/app/services/schedule/freight_receipt_rpa_job.py b/backend/app/services/schedule/freight_rpa_inbound_job.py similarity index 59% rename from backend/app/services/schedule/freight_receipt_rpa_job.py rename to backend/app/services/schedule/freight_rpa_inbound_job.py index 9e714374..51250d56 100644 --- a/backend/app/services/schedule/freight_receipt_rpa_job.py +++ b/backend/app/services/schedule/freight_rpa_inbound_job.py @@ -1,12 +1,12 @@ """ -backend/app/services/schedule/freight_receipt_rpa_job.py +backend/app/services/schedule/freight_rpa_inbound_job.py -用途:独立收料 RPA 排程——按勾选库存源一对一冻结执行单元并写 receipt trigger。 -依赖:receipt_rpa.write_receipt_export_batch_trigger、assert_receipt_rpa_worker_ready、 - ShippingInventorySource / ShippingReceiptReportConfig / ShippingReceiptRpaUnitRun、 +用途:独立入站 RPA 排程——按勾选来源站点一对一冻结执行单元并写 inbound trigger。 +依赖:freight_rpa.inbound.trigger_io.write_inbound_export_batch_trigger、assert_inbound_rpa_worker_ready、 + FreightRpaSource / FreightRpaInboundReportConfig / FreightRpaInboundUnitRun、 ScheduleTask/Run。 -逻辑:job_registry 的 freight-receipt-rpa 调用本 handler;写 trigger 前 fail-fast; - 口径与库存排程一致(选中 N 源 → N unit),query_parameters 原样下发。 +逻辑:job_registry 的 freight-rpa-inbound 调用本 handler;写 trigger 前 fail-fast; + 口径与 onhand 排程一致(选中 N 源 → N unit),query_parameters 原样下发。 """ from __future__ import annotations @@ -16,20 +16,20 @@ 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 write_receipt_export_batch_trigger -from app.services.shipping_notice.rpa_worker_heartbeat import ( +from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportConfig, FreightRpaInboundUnitRun +from app.services.freight_rpa.inbound.trigger_io import SCHEMA, write_inbound_export_batch_trigger +from app.services.freight_rpa.common.worker_heartbeat import ( RPA_WORKER_OFFLINE_MESSAGE, - assert_receipt_rpa_worker_ready, + assert_inbound_rpa_worker_ready, ) -RECEIPT_RPA_JOB_KEY = 'freight-receipt-rpa' -AWAITING_RECEIPT_RPA_CALLBACK_STATUS = 'awaiting_receipt_rpa_callback' +INBOUND_RPA_JOB_KEY = 'freight-rpa-inbound' +AWAITING_INBOUND_RPA_CALLBACK_STATUS = 'awaiting_inbound_rpa_callback' ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]] def _wanted_source_codes(task: ScheduleTask) -> set[str]: - """提取结构化 source_codes;留空代表全部具备有效收料配置的站点。""" + """提取结构化 source_codes;留空代表全部具备有效入站配置的站点。""" params = task.job_params if isinstance(task.job_params, dict) else {} values = params.get('source_codes') or [] if isinstance(values, str): @@ -37,17 +37,17 @@ def _wanted_source_codes(task: ScheduleTask) -> set[str]: return {str(value).strip().upper() for value in values if str(value).strip()} -def _eligible_sources(task: ScheduleTask) -> list[tuple[ShippingInventorySource, ShippingReceiptReportConfig]]: - """读取已启用且已配置收料报表的站点;不依赖库存报表路径、解析绑定或 Warehouse 条件。""" +def _eligible_sources(task: ScheduleTask) -> list[tuple[FreightRpaSource, FreightRpaInboundReportConfig]]: + """读取已启用且已配置入站报表的站点;不依赖库存报表路径、解析绑定或 Warehouse 条件。""" wanted = _wanted_source_codes(task) - rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join( - ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id, - ).filter(ShippingInventorySource.enabled.is_(True)).all() + rows = db.session.query(FreightRpaSource, FreightRpaInboundReportConfig).join( + FreightRpaInboundReportConfig, FreightRpaInboundReportConfig.source_id == FreightRpaSource.id, + ).filter(FreightRpaSource.enabled.is_(True)).all() return [(source, config) for source, config in rows if not wanted or source.source_code.upper() in wanted] -def _copy_query_parameters(config: ShippingReceiptReportConfig) -> list[dict[str, Any]]: - """浅拷贝收料查询条件原样入快照;空列表表示 Worker 使用页面默认、不填 Warehouse。""" +def _copy_query_parameters(config: FreightRpaInboundReportConfig) -> list[dict[str, Any]]: + """浅拷贝入站查询条件原样入快照;空列表表示 Worker 使用页面默认、不填 Warehouse。""" return [ dict(item) for item in (config.query_parameters_json or []) if isinstance(item, dict) @@ -55,25 +55,25 @@ def _copy_query_parameters(config: ShippingReceiptReportConfig) -> list[dict[str def _build_unit( - source: ShippingInventorySource, config: ShippingReceiptReportConfig, schedule_run_id: int, -) -> ShippingReceiptRpaUnitRun: - """冻结可审计的收料执行单元(一源一单元);DBS 日期字段不进入查询快照。""" - callback_id = f'receipt:{uuid.uuid4().hex}' + source: FreightRpaSource, config: FreightRpaInboundReportConfig, schedule_run_id: int, +) -> FreightRpaInboundUnitRun: + """冻结可审计的入站执行单元(一源一单元);DBS 日期字段不进入查询快照。""" + callback_id = f'inbound:{uuid.uuid4().hex}' snapshot = { 'config_id': config.id, 'config_version': config.config_version, 'connector_type': source.connector_type, 'report_path_json': config.report_path_json or {}, 'query_parameters_json': _copy_query_parameters(config), 'warehouse_id': None, 'rpa_profile_id': source.rpa_profile_id, } - return ShippingReceiptRpaUnitRun( - schedule_run_id=schedule_run_id, inventory_source_id=source.id, source_code=source.source_code, + return FreightRpaInboundUnitRun( + schedule_run_id=schedule_run_id, source_id=source.id, source_code=source.source_code, connector_type=source.connector_type, warehouse_id=None, callback_id=callback_id, status='awaiting_rpa', config_snapshot_json=snapshot, ) -def _serialize_trigger_unit(unit: ShippingReceiptRpaUnitRun) -> dict[str, Any]: +def _serialize_trigger_unit(unit: FreightRpaInboundUnitRun) -> dict[str, Any]: """生成 Worker 唯一可见的冻结执行载荷;密文凭据只随 receipt trigger 下发。""" - source = unit.inventory_source + source = unit.source profile = source.rpa_profile if source is not None else None if source is None or profile is None or not profile.enabled: raise RuntimeError(f'receipt source profile unavailable: {unit.source_code}') @@ -98,27 +98,27 @@ def _serialize_trigger_unit(unit: ShippingReceiptRpaUnitRun) -> dict[str, Any]: } -def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: +def run_freight_rpa_inbound_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: """ - 写独立收料 trigger;每个勾选站点对应一个执行单元(与库存 RPA 同口径)。 + 写独立入站 trigger;每个勾选站点对应一个执行单元(与 onhand RPA 同口径)。 - 核心逻辑:写 trigger 前 assert_receipt_rpa_worker_ready;离线立即 failed, - 不创建 unit、不进入 awaiting_receipt_rpa。 + 核心逻辑:写 trigger 前 assert_inbound_rpa_worker_ready;离线立即 failed, + 不创建 unit、不进入 awaiting_inbound_rpa。 """ - units: list[ShippingReceiptRpaUnitRun] = [ + units: list[FreightRpaInboundUnitRun] = [ _build_unit(source, config, run.id) for source, config in _eligible_sources(task) ] if not units: - return 0, 0, 0, 1, [], ['no enabled receipt report sources'], [{'step': 'freight_receipt_rpa', 'status': 'skipped'}] + return 0, 0, 0, 1, [], ['no enabled inbound report sources'], [{'step': 'freight_inbound_rpa', 'status': 'skipped'}] # [STEP] 写 trigger / 入库 unit 前 fail-fast,避免 Worker 离线干等到超时。 try: - assert_receipt_rpa_worker_ready() + assert_inbound_rpa_worker_ready() except ServiceUnavailableError as exc: message = str(exc.message or RPA_WORKER_OFFLINE_MESSAGE) detail_message = str((exc.details or {}).get('detail_message') or message) return len(units), 0, len(units), 0, [], [detail_message], [{ - 'step': 'freight_receipt_rpa', + 'step': 'freight_inbound_rpa', 'status': 'failed', 'detail': { 'message': message, @@ -134,23 +134,23 @@ def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc trigger_units = [_serialize_trigger_unit(unit) for unit in units] except RuntimeError as exc: for unit in units: - unit.status = 'failed'; unit.error_code = 'RPA.RECEIPT_PROFILE_UNAVAILABLE'; unit.error_message = str(exc) + unit.status = 'failed'; unit.error_code = 'RPA.INBOUND_PROFILE_UNAVAILABLE'; unit.error_message = str(exc) db.session.commit() - return len(units), 0, len(units), 0, [], [str(exc)], [{'step': 'freight_receipt_rpa', 'status': 'failed'}] + return len(units), 0, len(units), 0, [], [str(exc)], [{'step': 'freight_inbound_rpa', 'status': 'failed'}] for unit, trigger_unit in zip(units, trigger_units): unit.trigger_snapshot_json = trigger_unit - trigger_path = write_receipt_export_batch_trigger(run.run_no, trigger_units, { - 'schedule_run_id': run.id, 'schedule_task_id': task.id, 'schema_version': 'shipping_receipt_rpa.v1', + trigger_path = write_inbound_export_batch_trigger(run.run_no, trigger_units, { + 'schedule_run_id': run.id, 'schedule_task_id': task.id, 'schema_version': SCHEMA, }) if not trigger_path: for unit in units: - unit.status = 'failed'; unit.error_code = 'RPA.RECEIPT_TRIGGER_UNAVAILABLE'; unit.error_message = 'receipt trigger directory unavailable' + unit.status = 'failed'; unit.error_code = 'RPA.INBOUND_TRIGGER_UNAVAILABLE'; unit.error_message = 'inbound trigger directory unavailable' db.session.commit() - return len(units), 0, len(units), 0, [], ['receipt trigger directory unavailable'], [{'step': 'freight_receipt_rpa', 'status': 'failed'}] + return len(units), 0, len(units), 0, [], ['inbound trigger directory unavailable'], [{'step': 'freight_inbound_rpa', 'status': 'failed'}] details = [{'source_code': unit.source_code, 'warehouse_id': unit.warehouse_id, 'callback_id': unit.callback_id} for unit in units] run.api_request_json = {'run_no': run.run_no, 'trigger_path': trigger_path, 'source_codes': sorted({unit.source_code for unit in units})} db.session.commit() return len(units), 0, 0, 0, details, [], [{ - 'step': 'freight_receipt_rpa', 'status': AWAITING_RECEIPT_RPA_CALLBACK_STATUS, + 'step': 'freight_inbound_rpa', 'status': AWAITING_INBOUND_RPA_CALLBACK_STATUS, 'detail': {'trigger_path': trigger_path, 'unit_count': len(units)}, }] diff --git a/backend/app/services/schedule/freight_rpa_inbound_retention.py b/backend/app/services/schedule/freight_rpa_inbound_retention.py new file mode 100644 index 00000000..c8bd2734 --- /dev/null +++ b/backend/app/services/schedule/freight_rpa_inbound_retention.py @@ -0,0 +1,23 @@ +"""收料原样归档三年到期对象清理(排程壳)。 + +批次 R Task 10 起,清理能力本体已下沉 freight_rpa.inbound.report_archive +(run_freight_rpa_inbound_retention_schedule,函数名 receipt 词根→inbound); +本文件仅保留排程平台 Job 处理器接缝(job_registry 按 schedule 包路径注册, +Task 11 已随排程壳平移改名为 freight_rpa_inbound_retention,git mv 保留历史)。 +""" + +from __future__ import annotations + +from typing import Any + + +def run_freight_rpa_inbound_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]: + """排程壳:委托 freight_rpa.inbound.report_archive 执行三年保留清理(行为不变)。 + + 核心逻辑:本函数与 archive 同名;必须 as 别名导入,避免递归调用自身。 + """ + from app.services.freight_rpa.inbound.report_archive import ( + run_freight_rpa_inbound_retention_schedule as _run_inbound_archive_retention, + ) + + return _run_inbound_archive_retention(task, run) diff --git a/backend/app/services/schedule/shipping_inventory_rpa_archive.py b/backend/app/services/schedule/freight_rpa_onhand_archive.py similarity index 83% rename from backend/app/services/schedule/shipping_inventory_rpa_archive.py rename to backend/app/services/schedule/freight_rpa_onhand_archive.py index 71514c39..bdf4b4ad 100644 --- a/backend/app/services/schedule/shipping_inventory_rpa_archive.py +++ b/backend/app/services/schedule/freight_rpa_onhand_archive.py @@ -1,8 +1,8 @@ """ -backend/app/services/schedule/shipping_inventory_rpa_archive.py +backend/app/services/schedule/freight_rpa_onhand_archive.py 用途:货代库存 RPA 排程 run 的原始库存 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。 -依赖:ScheduleRun、ShippingInventoryFile、shipping_inventory_rpa_finalize.is_shipping_inventory_rpa_task。 +依赖:ScheduleRun、FreightRpaOnhandReportFile、freight_rpa_onhand_finalize.is_shipping_inventory_rpa_task。 逻辑:finalize 调用 persist_inventory_rpa_raw_zip_archive 写入磁盘与 summary; 企微/下载展示名用「库存RPA-日期-时刻-结果|库存」;包内条目仅「序号_仓码」; 完整 source_code / inventory_file_no 只写在 manifest.json;磁盘归档键仍为 {run_no}.zip。 @@ -21,8 +21,8 @@ from flask import current_app from app import db from app.core.errors import NotFoundError -from app.models import ScheduleRun, ShippingInventoryFile -from app.services.schedule.shipping_inventory_rpa_finalize import is_shipping_inventory_rpa_task +from app.models import ScheduleRun, FreightRpaOnhandReportFile +from app.services.schedule.freight_rpa_onhand_finalize import is_shipping_inventory_rpa_task from app.services.schedule.timezone_util import resolve_schedule_tzinfo _RAW_ZIP_NOT_FOUND_MESSAGE = "原始库存包不存在,请重新执行或联系管理员" @@ -39,14 +39,14 @@ _EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = { def get_inventory_archive_dir() -> str: """返回库存 RPA 原始 ZIP 归档根目录(自动创建)。""" archive_dir = Path( - current_app.config.get("FREIGHT_RPA_INVENTORY_ARCHIVE_DIR") + current_app.config.get("FREIGHT_RPA_ONHAND_ARCHIVE_DIR") if current_app else "" ) if not str(archive_dir): from app.core.config.settings import Config - archive_dir = Path(Config.FREIGHT_RPA_INVENTORY_ARCHIVE_DIR) + archive_dir = Path(Config.FREIGHT_RPA_ONHAND_ARCHIVE_DIR) archive_dir.mkdir(parents=True, exist_ok=True) return str(archive_dir) @@ -137,12 +137,13 @@ def _iter_packable_inventory_files( created: list[dict[str, Any]] | None = None, ): """ - 遍历可实际打包的库存快照。 + 遍历可实际打包的库存文件。 - 核心逻辑:需存在 ShippingInventoryFile 且 storage_path 指向可读文件。 + 核心逻辑:优先 FreightRpaOnhandReportFile(解析入库后);若无 inventory_file_no + 则回退 created.file_path(HTTP 文件返回即终态时的收件副本)。 Yields: - tuple[dict, ShippingInventoryFile, Path]: created 项、快照记录、可读路径。 + tuple[dict, FreightRpaOnhandReportFile | None, Path]: created 项、快照记录(可空)、可读路径。 """ if not is_shipping_inventory_rpa_task(getattr(run, "task", None)): return @@ -150,22 +151,28 @@ def _iter_packable_inventory_files( items = _normalize_created_items(created) if created is not None else _api_response_created(run) for item in items: inventory_file_no = str(item.get("inventory_file_no") or "").strip() - if not inventory_file_no: + if inventory_file_no: + inv_file = ( + db.session.query(FreightRpaOnhandReportFile) + .filter(FreightRpaOnhandReportFile.onhand_file_no == inventory_file_no) + .first() + ) + if not inv_file: + continue + storage_path = Path(str(inv_file.storage_path or "").strip()) + if not storage_path.is_file(): + continue + yield item, inv_file, storage_path continue - inv_file = ( - db.session.query(ShippingInventoryFile) - .filter(ShippingInventoryFile.inventory_file_no == inventory_file_no) - .first() - ) - if not inv_file: + # RPA 文件返回即终态:尚无快照号时用回调/收件副本路径打包。 + file_path = str(item.get("file_path") or "").strip() + if not file_path: continue - - storage_path = Path(str(inv_file.storage_path or "").strip()) + storage_path = Path(file_path) if not storage_path.is_file(): continue - - yield item, inv_file, storage_path + yield item, None, storage_path def inventory_raw_zip_available_from_summary(summary: dict[str, Any] | None) -> bool: @@ -208,8 +215,12 @@ def persist_inventory_rpa_raw_zip_archive( with zipfile.ZipFile(archive_path, "w", compression=zipfile.ZIP_DEFLATED) as archive: for zip_index, (item, inv_file, storage_path) in enumerate(packable_files, start=1): inventory_file_no = str(item.get("inventory_file_no") or "").strip() - source_code = str(item.get("source_code") or inv_file.source_code or "").strip() - warehouse_id = str(item.get("warehouse_id") or inv_file.warehouse_id or "").strip() + source_code = str( + item.get("source_code") or (getattr(inv_file, "source_code", None) or "") + ).strip() + warehouse_id = str( + item.get("warehouse_id") or (getattr(inv_file, "warehouse_id", None) or "") + ).strip() entry_name = _build_zip_entry_name( index=zip_index, source_code=source_code, @@ -217,12 +228,16 @@ def persist_inventory_rpa_raw_zip_archive( original_suffix=storage_path.suffix or ".xlsx", ) archive.write(storage_path, arcname=entry_name) + original_name = ( + str(getattr(inv_file, "source_file_name", None) or "").strip() + or storage_path.name + ) files_manifest.append({ "inventory_file_no": inventory_file_no, "source_code": source_code, "warehouse_id": warehouse_id, "file_name": entry_name, - "original_file_name": inv_file.source_file_name or storage_path.name, + "original_file_name": original_name, }) manifest = { @@ -251,7 +266,7 @@ def _is_allowed_inventory_archive_path(zip_path: Path) -> bool: """ 校验归档 ZIP 路径是否安全可下载。 - 核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内。 + 核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_ONHAND_ARCHIVE_DIR 内。 """ resolved = zip_path.resolve() if resolved.suffix.lower() != ".zip": @@ -272,7 +287,7 @@ def resolve_inventory_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]: 解析 run 已归档的原始库存 ZIP 路径供下载接口 send_file。 核心逻辑:读取 summary.raw_inventory_zip_path,校验文件存在、后缀为 .zip、 - 且真实路径位于 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内;任一不满足则 404。 + 且真实路径位于 FREIGHT_RPA_ONHAND_ARCHIVE_DIR 内;任一不满足则 404。 Returns: tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。 diff --git a/backend/app/services/schedule/shipping_inventory_rpa_finalize.py b/backend/app/services/schedule/freight_rpa_onhand_finalize.py similarity index 85% rename from backend/app/services/schedule/shipping_inventory_rpa_finalize.py rename to backend/app/services/schedule/freight_rpa_onhand_finalize.py index 077a42c9..e8a39c96 100644 --- a/backend/app/services/schedule/shipping_inventory_rpa_finalize.py +++ b/backend/app/services/schedule/freight_rpa_onhand_finalize.py @@ -1,10 +1,12 @@ """ -backend/app/services/schedule/shipping_inventory_rpa_finalize.py +backend/app/services/schedule/freight_rpa_onhand_finalize.py 用途:货代库存 RPA 排程异步终态(defer / finalize / 超时回收)。 -依赖:ScheduleRun/ScheduleTask、excel_service、kb_sync、scheduler_service 企微通知、tool_common。 -逻辑:shipping_inventory_rpa_job 写 trigger 后 defer;inventory_rpa_workflow 回调后 finalize; - run_task_now / cron 调度循环启动前回收超时 awaiting run;服务重启跳过 awaiting RPA run。 +依赖:ScheduleRun/ScheduleTask、excel_service、kb_sync、scheduler_service 企微通知、tool_common、 + freight_rpa.onhand.workflow_protocol(结果状态归一)。 +逻辑:freight_rpa_onhand_job 写 trigger 后 defer;HTTP batch-ready 按 RPA 导出结果 finalize + (文件返回即 RPA/排程结束);解析 Job 可后置且不得重新打开 awaiting; + run_task_now / cron 启动前回收超时 awaiting run。 """ from __future__ import annotations @@ -21,7 +23,7 @@ from app.services.schedule.excel_service import export_schedule_result_excel from app.services.schedule import normalize_platform_api_path from app.services.shipping_notice.tool_common import rpa_inventory_timeout_seconds -SHIPPING_INVENTORY_RPA_JOB_KEY = "shipping-inventory-rpa" +ONHAND_RPA_JOB_KEY = "freight-rpa-onhand" AWAITING_RPA_CALLBACK_STATUS = "awaiting_rpa_callback" FinalizeScheduleRunResult = dict[str, Any] @@ -52,7 +54,7 @@ def register_inventory_rpa_excel_headers() -> None: 核心逻辑:由 schedule.__init__._register_headers_from_config 在 reload 后调用,避免被 clear 冲掉。 """ register_schedule_header( - SHIPPING_INVENTORY_RPA_JOB_KEY, + ONHAND_RPA_JOB_KEY, _INVENTORY_RPA_HEADER_ORDER, _INVENTORY_RPA_HEADER_LABELS, ) @@ -78,7 +80,7 @@ def is_shipping_inventory_rpa_task(task: ScheduleTask | None) -> bool: """判断是否为货代库存 RPA 平台排程任务。""" if not task or task.schedule_type != "platform_job": return False - return normalize_platform_api_path(task.platform_api_path) == SHIPPING_INVENTORY_RPA_JOB_KEY + return normalize_platform_api_path(task.platform_api_path) == ONHAND_RPA_JOB_KEY def is_awaiting_rpa_callback(step_logs: list | None) -> bool: @@ -111,6 +113,82 @@ def _compute_run_status(*, total_count: int, success_count: int, failed_count: i return "partial_failed" +def map_rpa_batch_results_for_schedule_finalize( + results: list[Any] | None, +) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]: + """把 Worker batch results 映射为排程 finalize 的 created/failed/skipped。 + + 【AI 触发时机】:HTTP onhand-batch-ready 收件后、入队解析 Job 前调用; + 只认 RPA 导出成败(含 file_path),不依赖解析入库后的 inventory_file_no。 + + Args: + results: Worker 回调 results 列表。 + + Returns: + (created, failed, skipped):供 finalize_shipping_inventory_schedule_run 使用。 + """ + from app.services.freight_rpa.onhand.workflow_protocol import normalize_inventory_batch_item_status + + created: list[dict[str, Any]] = [] + failed: list[dict[str, Any]] = [] + skipped: list[dict[str, Any]] = [] + for raw in results or []: + if not isinstance(raw, dict): + continue + source_code = str(raw.get("source_code") or "").strip().upper() + warehouse_id = str(raw.get("warehouse_id") or "").strip().upper() + status = normalize_inventory_batch_item_status(raw) + if status == "success": + created.append({ + "source_code": source_code, + "warehouse_id": warehouse_id, + "inventory_file_no": str(raw.get("inventory_file_no") or "").strip(), + "file_path": str(raw.get("file_path") or "").strip(), + }) + continue + if status == "skipped": + skipped.append({ + "source_code": source_code, + "warehouse_id": warehouse_id, + "skip_reason": str(raw.get("skip_reason") or raw.get("reason") or "skipped")[:200], + "message": str(raw.get("message") or raw.get("error_message") or "")[:500], + }) + continue + failed.append({ + "source_code": source_code, + "warehouse_id": warehouse_id, + "error": str( + raw.get("error") or raw.get("error_message") or raw.get("message") or "rpa_export_failed" + )[:500], + }) + return created, failed, skipped + + +def finalize_shipping_inventory_schedule_run_from_rpa_results( + schedule_run_id: int, + payload: dict[str, Any], +) -> FinalizeScheduleRunResult: + """按 RPA 导出结果终态化排程(文件返回即结束,不等解析)。 + + 核心逻辑:map Worker results → finalize;解析 Job 稍后仍可入库,但不得重新 awaiting。 + + Args: + schedule_run_id: ScheduleRun 主键。 + payload: 已收件的 batch-ready 载荷(含 results)。 + + Returns: + FinalizeScheduleRunResult: 与 finalize_shipping_inventory_schedule_run 同形。 + """ + created, failed, skipped = map_rpa_batch_results_for_schedule_finalize(payload.get("results")) + return finalize_shipping_inventory_schedule_run( + schedule_run_id, + created=created, + failed=failed, + skipped=skipped, + payload=payload, + ) + + def _build_finalize_details( pending_details: list[dict[str, Any]], *, @@ -276,7 +354,7 @@ def _try_recover_stale_awaiting_run( finished_at = datetime.utcnow() step_logs = list(run.step_logs or []) step_logs.append({ - "step": "shipping_inventory_rpa", + "step": "freight_rpa_onhand", "status": "failed", "detail": {"message": "RPA 库存导出等待超时", "timeout_seconds": timeout_seconds}, }) @@ -468,7 +546,7 @@ def _finalize_shipping_inventory_schedule_run_impl( ) register_inventory_rpa_excel_headers() - header_order, header_labels = resolve_schedule_header(SHIPPING_INVENTORY_RPA_JOB_KEY) + header_order, header_labels = resolve_schedule_header(ONHAND_RPA_JOB_KEY) excel_export_ok = True try: file_data, file_name, file_size = export_schedule_result_excel( @@ -495,13 +573,13 @@ def _finalize_shipping_inventory_schedule_run_impl( status = "partial_failed" else: # 企微/下载展示名:库存RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。 - from app.services.schedule.shipping_inventory_rpa_archive import inventory_rpa_result_excel_name + from app.services.schedule.freight_rpa_onhand_archive import inventory_rpa_result_excel_name file_name = inventory_rpa_result_excel_name(run) step_logs = list(run.step_logs or []) step_logs.append({ - "step": "shipping_inventory_rpa", + "step": "freight_rpa_onhand", "status": "success" if status == "success" else "failed" if status == "failed" else "partial_failed", "detail": { "created_count": success_count, @@ -537,7 +615,7 @@ def _finalize_shipping_inventory_schedule_run_impl( "raw_inventory_zip_size": 0, } try: - from app.services.schedule.shipping_inventory_rpa_archive import persist_inventory_rpa_raw_zip_archive + from app.services.schedule.freight_rpa_onhand_archive import persist_inventory_rpa_raw_zip_archive archive_summary = persist_inventory_rpa_raw_zip_archive(run, created=created) except Exception as archive_exc: diff --git a/backend/app/services/schedule/shipping_inventory_rpa_job.py b/backend/app/services/schedule/freight_rpa_onhand_job.py similarity index 82% rename from backend/app/services/schedule/shipping_inventory_rpa_job.py rename to backend/app/services/schedule/freight_rpa_onhand_job.py index 8447d2be..dd91e113 100644 --- a/backend/app/services/schedule/shipping_inventory_rpa_job.py +++ b/backend/app/services/schedule/freight_rpa_onhand_job.py @@ -1,10 +1,10 @@ """ -backend/app/services/schedule/shipping_inventory_rpa_job.py +backend/app/services/schedule/freight_rpa_onhand_job.py 用途:排程触发货代库存 RPA 批量导出(每个 Inventory Source 一次执行)。 -依赖:inventory_source_repository、rpa.write_inventory_export_batch_trigger、ScheduleTask/ScheduleRun。 -逻辑:platform_api_path=shipping-inventory-rpa 时由 job_registry 调用; - 写 trigger 后返回 awaiting_rpa_callback;终态由 shipping_inventory_rpa_finalize 在 RPA 回调时写入。 +依赖:onhand_source_repository、rpa.write_inventory_export_batch_trigger、ScheduleTask/ScheduleRun。 +逻辑:platform_api_path=freight-rpa-onhand 时由 job_registry 调用; + 写 trigger 后返回 awaiting_rpa_callback;终态由 freight_rpa_onhand_finalize 在 RPA 回调时写入。 """ from __future__ import annotations @@ -16,10 +16,10 @@ from typing import Any from app import db from app.core.errors import ServiceUnavailableError from app.models import ScheduleRun, ScheduleTask -from app.services.schedule.shipping_inventory_rpa_finalize import AWAITING_RPA_CALLBACK_STATUS -from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources -from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger -from app.services.shipping_notice.rpa_worker_heartbeat import ( +from app.services.schedule.freight_rpa_onhand_finalize import AWAITING_RPA_CALLBACK_STATUS +from app.services.shipping_notice.onhand_source_repository import list_database_inventory_sources +from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger +from app.services.freight_rpa.common.worker_heartbeat import ( RPA_WORKER_OFFLINE_MESSAGE, assert_inventory_rpa_worker_ready, ) @@ -105,21 +105,21 @@ def _filter_sources(task: ScheduleTask) -> list[dict[str, Any]]: return enabled -def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: +def run_freight_rpa_onhand_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: """ 写入批量库存 RPA trigger,由 worker 异步导出并在 callback 入库。 核心逻辑:写 trigger 后返回 awaiting_rpa_callback;终态由 finalize 在回调时写入。 """ sources = _filter_sources(task) step_logs: list[dict[str, Any]] = [{ - "step": "shipping_inventory_rpa", + "step": "freight_rpa_onhand", "status": "started", "detail": {"source_count": len(sources)}, }] if not sources: message = "no enabled inventory sources" - step_logs.append({"step": "shipping_inventory_rpa", "status": "skipped", "detail": {"message": message}}) + step_logs.append({"step": "freight_rpa_onhand", "status": "skipped", "detail": {"message": message}}) return 0, 0, 0, 1, [], [message], step_logs run_no = run.run_no or f"RUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}" @@ -139,7 +139,7 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> message = str(exc.message or RPA_WORKER_OFFLINE_MESSAGE) detail_message = str((exc.details or {}).get("detail_message") or message) step_logs.append({ - "step": "shipping_inventory_rpa", + "step": "freight_rpa_onhand", "status": "failed", "detail": { "message": message, @@ -151,7 +151,7 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> return len(sources), 0, len(sources), 0, [], [detail_message], step_logs if not trigger_path: message = "inventory RPA trigger dir not configured" - step_logs.append({"step": "shipping_inventory_rpa", "status": "failed", "detail": {"message": message}}) + step_logs.append({"step": "freight_rpa_onhand", "status": "failed", "detail": {"message": message}}) return len(sources), 0, len(sources), 0, [], [message], step_logs run.api_request_json = { @@ -162,7 +162,7 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> db.session.commit() step_logs.append({ - "step": "shipping_inventory_rpa", + "step": "freight_rpa_onhand", "status": AWAITING_RPA_CALLBACK_STATUS, "detail": {"trigger_path": trigger_path, "run_no": run_no}, }) diff --git a/backend/app/services/schedule/freight_rpa_outbound_archive.py b/backend/app/services/schedule/freight_rpa_outbound_archive.py new file mode 100644 index 00000000..95b55d2b --- /dev/null +++ b/backend/app/services/schedule/freight_rpa_outbound_archive.py @@ -0,0 +1,311 @@ +""" +backend/app/services/schedule/freight_rpa_outbound_archive.py + +用途:货代出站 RPA 排程 run 的原始出站 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。 +依赖:ScheduleRun、FreightRpaOutboundReportFile / FreightRpaOutboundUnitRun、 + file_asset_storage、timezone_util、freight_rpa_outbound_finalize.is_freight_outbound_rpa_task。 +逻辑:finalize 调用 persist_outbound_rpa_raw_zip_archive 写入磁盘与 summary; + 企微/下载展示名用「出站RPA-日期-时刻-出站」;包内条目 `{序号}_{source_code}.xlsx`; + warehouse_id / file_id 只写在 manifest.json;磁盘归档键为 {run_no}.zip。 +""" + +from __future__ import annotations + +import json +import re +import zipfile +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +from flask import current_app + +from app.core.errors import NotFoundError +from app.models import ScheduleRun, FreightRpaOutboundReportFile, FreightRpaOutboundUnitRun +from app.services.file_assets.storage import file_asset_storage +from app.services.schedule.freight_rpa_outbound_finalize import is_freight_outbound_rpa_task +from app.services.schedule.timezone_util import resolve_schedule_tzinfo + +_RAW_ZIP_NOT_FOUND_MESSAGE = '原始出站包不存在,请重新执行或联系管理员' + +_EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = { + 'raw_outbound_zip_available': False, + 'raw_outbound_zip_path': None, + 'raw_outbound_file_count': 0, + 'raw_outbound_file_ids': [], + 'raw_outbound_zip_size': 0, +} + + +def get_outbound_archive_dir() -> str: + """ + 返回出站 RPA 原始 ZIP 归档根目录(自动创建)。 + + 核心逻辑:优先读 Flask config;值为 None/空时回落到 Config 默认路径, + 避免 Path(None) 在 finalize 阶段把整次 ZIP 归档打成空 summary。 + """ + configured = '' + if current_app: + raw = current_app.config.get('FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR') + configured = str(raw).strip() if raw is not None else '' + if not configured: + from app.core.config.settings import Config + + configured = str(Config.FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR or '').strip() + archive_dir = Path(configured) + archive_dir.mkdir(parents=True, exist_ok=True) + return str(archive_dir) + + +def _attachment_when_from_run(run: ScheduleRun) -> datetime: + """ + 推导企微/下载展示名中的当地时刻。 + + 核心逻辑:与库存归档同构——started_at → created_at → finished_at → + 解析 RUN{yyyyMMddHHmmss}* → utcnow;再转到任务 schedule_timezone。 + """ + when_utc: datetime | None = None + for value in (run.started_at, run.created_at, run.finished_at): + if isinstance(value, datetime): + when_utc = value + break + if when_utc is None: + match = re.match(r'^RUN(\d{14})', str(run.run_no or '').strip()) + if match: + try: + when_utc = datetime.strptime(match.group(1), '%Y%m%d%H%M%S') + except ValueError: + when_utc = None + if when_utc is None: + when_utc = datetime.now(timezone.utc).replace(tzinfo=None) + + task = getattr(run, 'task', None) + tz_name = getattr(task, 'schedule_timezone', None) if task is not None else None + tz = resolve_schedule_tzinfo(tz_name) + if when_utc.tzinfo is None: + when_utc = when_utc.replace(tzinfo=timezone.utc) + return when_utc.astimezone(tz) + + +def outbound_rpa_attachment_stem(run: ScheduleRun) -> str: + """ + 出站 RPA 企微附件共用前缀:出站RPA-{yyyyMMdd}-{HHmm}(业务时区当地时间)。 + + Args: + run: 排程执行记录。 + + Returns: + 不含角色后缀与扩展名的展示名前缀。 + """ + when = _attachment_when_from_run(run) + return f"出站RPA-{when.strftime('%Y%m%d')}-{when.strftime('%H%M')}" + + +def outbound_raw_zip_download_name(run: ScheduleRun) -> str: + """ + 出站 ZIP 的企微/浏览器下载展示名。 + + 核心逻辑:磁盘归档仍为 {run_no}.zip;本函数只影响 Content-Disposition 与企微 filename。 + """ + return f'{outbound_rpa_attachment_stem(run)}-出站.zip' + + +def outbound_rpa_result_excel_name(run: ScheduleRun) -> str: + """出站 RPA 结果 Excel 的企微/下载展示名(对齐入站 inbound_rpa_result_excel_name)。""" + return f'{outbound_rpa_attachment_stem(run)}-结果.xlsx' + + +def _outbound_raw_zip_archive_path(run_no: str) -> Path: + """磁盘归档路径:/.zip。""" + return Path(get_outbound_archive_dir()) / f'{run_no}.zip' + + +def _iter_packable_outbound_files(run: ScheduleRun): + """ + 遍历该 run 下可打包的出站归档文件。 + + 核心逻辑:join unit_run,过滤 archive_deleted_at 为空;按 file id 升序稳定序号。 + + Yields: + FreightRpaOutboundReportFile: 可从 MinIO 读取的归档记录。 + """ + if not is_freight_outbound_rpa_task(getattr(run, 'task', None)): + return + rows = ( + FreightRpaOutboundReportFile.query.join( + FreightRpaOutboundUnitRun, + FreightRpaOutboundReportFile.unit_run_id == FreightRpaOutboundUnitRun.id, + ) + .filter( + FreightRpaOutboundUnitRun.schedule_run_id == run.id, + FreightRpaOutboundReportFile.archive_deleted_at.is_(None), + ) + .order_by(FreightRpaOutboundReportFile.id.asc()) + .all() + ) + for report_file in rows: + yield report_file + + +def outbound_raw_zip_available_from_summary(summary: dict[str, Any] | None) -> bool: + """ + 从 response_summary_json 读取原始出站 ZIP 是否可下载。 + + 核心逻辑:列表序列化只读 summary,不查库、不访问磁盘。 + """ + if not isinstance(summary, dict): + return False + return bool(summary.get('raw_outbound_zip_available')) + + +def persist_outbound_rpa_raw_zip_archive(run: ScheduleRun) -> dict[str, Any]: + """ + finalize 阶段预生成原始出站 ZIP 归档并返回 summary 字段。 + + 核心逻辑:从 MinIO 拉取各单元归档字节 → 写入 /.zip + (含 manifest.json);无可用文件时返回 raw_outbound_zip_available=false。 + + Args: + run: 出站 RPA ScheduleRun。 + + Returns: + dict: raw_outbound_zip_available / path / file_count / file_ids / zip_size。 + """ + packable_files = list(_iter_packable_outbound_files(run)) + if not packable_files: + return dict(_EMPTY_ARCHIVE_SUMMARY) + + archive_path = _outbound_raw_zip_archive_path(run.run_no) + files_manifest: list[dict[str, Any]] = [] + + with zipfile.ZipFile(archive_path, 'w', compression=zipfile.ZIP_DEFLATED) as archive: + for zip_index, report_file in enumerate(packable_files, start=1): + unit = report_file.unit_run + source_code = str(getattr(unit, 'source_code', None) or '').strip() + warehouse_id = str(getattr(unit, 'warehouse_id', None) or '').strip() + original_name = str(report_file.original_filename or '').strip() or 'outbound.xlsx' + suffix = Path(original_name).suffix or '.xlsx' + entry_name = _build_zip_entry_name( + index=zip_index, + source_code=source_code, + warehouse_id=warehouse_id, + original_suffix=suffix, + ) + # [STEP] 出站归档在 MinIO:读字节后 writestr,不依赖本地 storage_path。 + data = file_asset_storage.get_bytes(report_file.storage_key) + archive.writestr(entry_name, data) + files_manifest.append({ + 'file_id': report_file.id, + 'source_code': source_code, + 'warehouse_id': warehouse_id, + 'file_name': entry_name, + 'original_file_name': original_name, + 'sha256': report_file.sha256, + }) + + manifest = { + 'run_no': run.run_no, + 'total_count': int(run.total_count or 0), + 'success_count': int(run.success_count or 0), + 'skipped_count': int(run.skipped_count or 0), + 'failed_count': int(run.failed_count or 0), + 'files': files_manifest, + } + archive.writestr( + 'manifest.json', + json.dumps(manifest, ensure_ascii=False, indent=2), + ) + + return { + 'raw_outbound_zip_available': True, + 'raw_outbound_zip_path': str(archive_path.resolve()), + 'raw_outbound_file_count': len(files_manifest), + 'raw_outbound_file_ids': [item['file_id'] for item in files_manifest], + 'raw_outbound_zip_size': int(archive_path.stat().st_size), + } + + +def _is_allowed_outbound_archive_path(zip_path: Path) -> bool: + """ + 校验归档 ZIP 路径是否安全可下载。 + + 核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR 内。 + """ + resolved = zip_path.resolve() + if resolved.suffix.lower() != '.zip': + return False + if not resolved.is_file(): + return False + + archive_dir = Path(get_outbound_archive_dir()).resolve() + try: + resolved.relative_to(archive_dir) + except ValueError: + return False + return True + + +def resolve_outbound_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]: + """ + 解析 run 已归档的原始出站 ZIP 路径供下载接口 send_file。 + + 核心逻辑:读取 summary.raw_outbound_zip_path,校验文件存在、后缀为 .zip、 + 且真实路径位于 FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR 内;任一不满足则 404。 + + Returns: + tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。 + + Raises: + NotFoundError: summary 未标记可用、路径非法或归档文件已丢失。 + """ + summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} + if not outbound_raw_zip_available_from_summary(summary): + raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE) + + zip_path_raw = str(summary.get('raw_outbound_zip_path') or '').strip() + if not zip_path_raw: + raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE) + + zip_path = Path(zip_path_raw) + if not _is_allowed_outbound_archive_path(zip_path): + raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE) + + return zip_path.resolve(), outbound_raw_zip_download_name(run) + + +def _sanitize_zip_segment(value: str) -> str: + """ZIP 内文件名片段安全化,避免路径穿越与非法字符。""" + cleaned = re.sub(r'[^\w\-.]+', '_', str(value or '').strip()) + return cleaned or 'unknown' + + +def _zip_entry_label(*, source_code: str, warehouse_id: str) -> str: + """ + 包内短标签:优先 source_code;无则回退仓码;再否则 outbound。 + + warehouse_id / file_id 已写入 manifest.json;条目名不必再叠仓码。 + """ + source = str(source_code or '').strip() + if source: + return source + warehouse = str(warehouse_id or '').strip() + if warehouse and warehouse.lower() not in {'unknown', 'na'}: + return warehouse + return 'outbound' + + +def _build_zip_entry_name( + *, + index: int, + source_code: str, + warehouse_id: str, + original_suffix: str, +) -> str: + """ + 生成 ZIP 内单文件条目名(不含目录)。 + + 核心逻辑:`{序号}_{source_code}.{ext}`;序号保证极端撞名时仍唯一。 + """ + label = _sanitize_zip_segment(_zip_entry_label(source_code=source_code, warehouse_id=warehouse_id)) + suffix = original_suffix if original_suffix.startswith('.') else f'.{original_suffix}' + return f'{index:03d}_{label}{suffix}' diff --git a/backend/app/services/schedule/freight_rpa_outbound_finalize.py b/backend/app/services/schedule/freight_rpa_outbound_finalize.py new file mode 100644 index 00000000..7f1f45bd --- /dev/null +++ b/backend/app/services/schedule/freight_rpa_outbound_finalize.py @@ -0,0 +1,532 @@ +""" +backend/app/services/schedule/freight_rpa_outbound_finalize.py + +用途:独立出站 RPA 排程等待态收口——进度回写、全单元终态后写计数、预生成 ZIP、发企微; + 另含超时对账:排程 run 级(每轮 tick)与按需触发孤儿单元级(schedule_run_id=NULL)。 +依赖:FreightRpaOutboundUnitRun、freight_rpa_outbound_archive、scheduler_service 企微通知。 +逻辑:每笔回调 → refresh 进度计数 → 全终态时 persist ZIP → _notify_schedule_run_wecom; + 超时对账只终态化失败,绝不自动重试或重发(恢复走人工显式重试入口)。 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta +from typing import Any + +from flask import current_app +from sqlalchemy import func + +from app import db +from app.models import ScheduleRun, ScheduleTask +from app.models import FreightRpaOutboundUnitRun +from app.services.schedule import normalize_platform_api_path, register_schedule_header, resolve_schedule_header +from app.services.schedule.excel_service import export_schedule_result_excel +from app.services.schedule.freight_rpa_outbound_job import AWAITING_OUTBOUND_RPA_CALLBACK_STATUS, OUTBOUND_RPA_JOB_KEY +from app.services.freight_rpa.outbound.trigger_io import SCHEMA as OUTBOUND_TRIGGER_SCHEMA +from app.services.shipping_notice.audit_service import append_shipping_audit_event + +_OUTBOUND_RPA_HEADER_ORDER = [ + "source_code", + "warehouse_id", + "connector_type", + "outbound_file_count", + "export_status", + "skip_reason", + "error_message", +] +_OUTBOUND_RPA_HEADER_LABELS = { + "source_code": "出站源", + "warehouse_id": "仓库", + "connector_type": "连接器", + "outbound_file_count": "归档文件数", + "export_status": "导出状态", + "skip_reason": "跳过原因", + "error_message": "错误原因", +} + + +def register_outbound_rpa_excel_headers() -> None: + """ + 注册货代出站 RPA 排程 Excel 列头(幂等)。 + 核心逻辑:由 schedule.__init__._register_headers_from_config 在 reload 后调用,避免被 clear 冲掉。 + """ + register_schedule_header( + OUTBOUND_RPA_JOB_KEY, + _OUTBOUND_RPA_HEADER_ORDER, + _OUTBOUND_RPA_HEADER_LABELS, + ) + + +def _build_outbound_finalize_details(units: list[FreightRpaOutboundUnitRun]) -> list[dict[str, Any]]: + """ + 出站单元 → 排程 Excel 明细行(对齐入站 finalize 的行结构)。 + + 核心逻辑:empty 归一为 skipped、cancelled 归一为 failed,与卡片计数口径一致; + 归档文件数便于与原始出站包内 {序号}_{source_code}.xlsx 条目对账。 + + Args: + units: 该 run 的全部出站单元(已全部终态)。 + + Returns: + list[dict]: 按 unit.id 升序的明细行。 + """ + rows: list[dict[str, Any]] = [] + for unit in sorted(units, key=lambda item: item.id): + status = unit.status + if status == 'empty': + export_status = 'skipped' + elif status == 'cancelled': + export_status = 'failed' + else: + export_status = status + rows.append({ + 'source_code': unit.source_code, + 'warehouse_id': unit.warehouse_id or '', + 'connector_type': unit.connector_type or '', + 'outbound_file_count': len(unit.files or []), + 'export_status': export_status, + 'skip_reason': str(unit.error_code or '') if export_status == 'skipped' else '', + 'error_message': str(unit.error_message or '')[:500] if export_status == 'failed' else '', + }) + return rows + + +def should_defer_outbound_schedule_run(task: ScheduleTask, step_logs: list | None) -> bool: + """仅当独立出站 job 成功写入 trigger 后延后终态,避免影响库存/入站 job 判断。""" + return bool( + task.schedule_type == 'platform_job' + and normalize_platform_api_path(task.platform_api_path) == OUTBOUND_RPA_JOB_KEY + and any(isinstance(row, dict) and row.get('status') == AWAITING_OUTBOUND_RPA_CALLBACK_STATUS for row in step_logs or []) + ) + + +def is_awaiting_outbound_rpa_schedule_run(run: ScheduleRun | None) -> bool: + """判断 run 是否为独立出站 callback 等待态,供 worker 启动恢复时保护。""" + summary = run.response_summary_json if run is not None and isinstance(run.response_summary_json, dict) else {} + return bool(run is not None and run.status == 'running' and summary.get('awaiting_outbound_rpa')) + + +def apply_deferred_outbound_schedule_run_state( + run: ScheduleRun, task: ScheduleTask, *, total_count: int, details: list[dict], errors: list[str], step_logs: list[dict], +) -> ScheduleRun: + """将出站 run 保持为 awaiting callback,终态由所有出站单元回调完成后专用服务写入。""" + run.status = 'running' + run.started_at = run.started_at or datetime.utcnow() + run.total_count = total_count + run.success_count = 0 + run.failed_count = 0 + run.skipped_count = 0 + run.finished_at = None + run.step_logs = step_logs + run.response_summary_json = {'awaiting_outbound_rpa': True, 'pending_details': details, 'errors': errors[:20]} + db.session.commit() + return run + + +def refresh_outbound_schedule_run_progress(schedule_run_id: int) -> dict: + """ + 出站单元每笔回调后回写排程 run 进度计数(非终态,对齐库存 inventory-batch-progress)。 + + 核心逻辑:仅在 awaiting_outbound_rpa 时,按已终态单元聚合 success/empty/failed 写入 + ScheduleRun 计数与 response_summary_json.progress;不改 status/finished_at, + 终态仍由 finalize_outbound_schedule_run_if_complete 负责。 + + Args: + schedule_run_id: 排程执行记录主键。 + + Returns: + dict: updated=True/False 及当前计数;非等待态返回 reason。 + """ + run = db.session.get(ScheduleRun, schedule_run_id) + if run is None: + return {'updated': False, 'reason': 'schedule_run_not_found'} + summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} + if run.status != 'running' or not summary.get('awaiting_outbound_rpa'): + return {'updated': False, 'reason': 'not_awaiting_outbound_callback'} + + units = FreightRpaOutboundUnitRun.query.filter_by(schedule_run_id=run.id).all() + success_count = sum(unit.status == 'success' for unit in units) + skipped_count = sum(unit.status == 'empty' for unit in units) + failed_count = sum(unit.status in {'failed', 'cancelled'} for unit in units) + + # [STEP] 与库存进度同口径:只抬升计数,防乱序回调把笔数打回去。 + run.success_count = max(int(run.success_count or 0), success_count) + run.skipped_count = max(int(run.skipped_count or 0), skipped_count) + run.failed_count = max(int(run.failed_count or 0), failed_count) + if run.total_count is None or int(run.total_count or 0) < len(units): + run.total_count = len(units) + summary = dict(summary) + summary['progress'] = { + 'success_count': int(run.success_count or 0), + 'skipped_count': int(run.skipped_count or 0), + 'failed_count': int(run.failed_count or 0), + 'processing_count': sum(unit.status == 'processing' for unit in units), + 'updated_at': datetime.utcnow().isoformat(), + } + run.response_summary_json = summary + db.session.commit() + return { + 'updated': True, + 'success_count': int(run.success_count or 0), + 'skipped_count': int(run.skipped_count or 0), + 'failed_count': int(run.failed_count or 0), + } + + +def report_outbound_batch_progress(payload: dict) -> dict: + """ + Worker 每完成一笔出站导出后的实时进度回写(非终态,对齐 inventory-batch-progress)。 + + 核心逻辑:校验 schema + schedule_run_id;仅 awaiting_outbound_rpa 时抬升 + ScheduleRun 计数;最终以 unit 终态回调 + finalize 为准。 + + Args: + payload: Worker 上报的累计 success/skipped/failed 与 schedule_run_id。 + + Returns: + dict: updated / rejected 及当前计数。 + """ + if payload.get('schema_version') != OUTBOUND_TRIGGER_SCHEMA: + return {'updated': False, 'reason': 'callback_schema_invalid'} + try: + schedule_run_id = int(payload.get('schedule_run_id')) if payload.get('schedule_run_id') is not None else None + except (TypeError, ValueError): + schedule_run_id = None + if not schedule_run_id: + return {'updated': False, 'reason': 'schedule_run_id_required'} + + run = db.session.get(ScheduleRun, schedule_run_id) + if run is None: + return {'updated': False, 'reason': 'schedule_run_not_found'} + summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} + if run.status != 'running' or not summary.get('awaiting_outbound_rpa'): + return {'updated': False, 'reason': 'not_awaiting_outbound_callback'} + + incoming = { + 'success_count': max(0, int(payload.get('success_count') or 0)), + 'skipped_count': max(0, int(payload.get('skipped_count') or 0)), + 'failed_count': max(0, int(payload.get('failed_count') or 0)), + } + run.success_count = max(int(run.success_count or 0), incoming['success_count']) + run.skipped_count = max(int(run.skipped_count or 0), incoming['skipped_count']) + run.failed_count = max(int(run.failed_count or 0), incoming['failed_count']) + summary = dict(summary) + summary['progress'] = { + 'success_count': int(run.success_count or 0), + 'skipped_count': int(run.skipped_count or 0), + 'failed_count': int(run.failed_count or 0), + 'batch_run_no': str(payload.get('batch_run_no') or payload.get('run_no') or ''), + 'updated_at': datetime.utcnow().isoformat(), + } + run.response_summary_json = summary + db.session.commit() + return { + 'updated': True, + 'success_count': int(run.success_count or 0), + 'skipped_count': int(run.skipped_count or 0), + 'failed_count': int(run.failed_count or 0), + } + + +def mark_outbound_unit_processing(payload: dict) -> dict: + """ + Worker 开始导出某出站单元时标记 processing(对齐库存 claimed / rpa_exporting)。 + + 核心逻辑:仅 awaiting_rpa → processing;已终态或已 processing 幂等返回。 + """ + if payload.get('schema_version') != OUTBOUND_TRIGGER_SCHEMA: + return {'updated': False, 'reason': 'callback_schema_invalid'} + callback_id = str(payload.get('callback_id') or '').strip() + if not callback_id: + return {'updated': False, 'reason': 'callback_id_required'} + unit = FreightRpaOutboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none() + if unit is None: + return {'updated': False, 'reason': 'unit_not_found'} + if unit.status in {'success', 'empty', 'failed', 'cancelled'}: + return {'updated': False, 'reason': 'already_terminal', 'status': unit.status} + if unit.status == 'processing': + return {'updated': True, 'status': 'processing', 'idempotent': True} + unit.status = 'processing' + # started_at 是出站超时对账的活动锚(_outbound_last_activity):在飞单元必须有 + # 开始时间,否则长静默批次无法区分"在跑"与"worker 已死"。 + unit.started_at = datetime.utcnow() + db.session.commit() + if unit.schedule_run_id: + refresh_outbound_schedule_run_progress(unit.schedule_run_id) + return {'updated': True, 'status': 'processing', 'unit_run_id': unit.id} + + +def finalize_outbound_schedule_run_if_complete(schedule_run_id: int) -> dict: + """ + 当出站 run 的全部单元已回调后写入独立排程终态,不读取库存/入站回调结果。 + + 核心逻辑:聚合单元计数 → 预生成原始出站 ZIP 写入 summary → 企微发 textcard+单 ZIP。 + """ + run = db.session.get(ScheduleRun, schedule_run_id) + if run is None: + return {'finalized': False, 'reason': 'schedule_run_not_found'} + summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} + if not summary.get('awaiting_outbound_rpa'): + return {'finalized': False, 'reason': 'not_awaiting_outbound_callback'} + units = FreightRpaOutboundUnitRun.query.filter_by(schedule_run_id=run.id).all() + terminal = {'success', 'empty', 'failed', 'cancelled'} + if any(unit.status not in terminal for unit in units): + return {'finalized': False, 'reason': 'units_pending'} + success_count = sum(unit.status == 'success' for unit in units) + skipped_count = sum(unit.status == 'empty' for unit in units) + failed_count = sum(unit.status in {'failed', 'cancelled'} for unit in units) + run.total_count = len(units) + run.success_count = success_count + run.skipped_count = skipped_count + run.failed_count = failed_count + run.finished_at = datetime.utcnow() + run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000) if run.started_at else 0 + run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed' + run.error_message = '; '.join(filter(None, (unit.error_message for unit in units if unit.status == 'failed')))[:2000] or None + + # [STEP] 对齐入站 finalize:终态前生成出站汇总 Excel,企微在 textcard+ZIP 之外多发一条 [文件] 消息。 + register_outbound_rpa_excel_headers() + header_order, header_labels = resolve_schedule_header(OUTBOUND_RPA_JOB_KEY) + excel_export_ok = True + excel_data, excel_name, excel_size = None, None, 0 + try: + excel_data, _excel_name, excel_size = export_schedule_result_excel( + run_no=run.run_no, + summary={ + 'status': run.status, + 'total_count': len(units), + 'success_count': success_count, + 'skipped_count': skipped_count, + 'failed_count': failed_count, + 'duration_ms': run.duration_ms, + }, + details=_build_outbound_finalize_details(units), + header_order=header_order, + header_labels=header_labels, + ) + except Exception as excel_exc: + excel_export_ok = False + current_app.logger.error( + '[schedule-run] outbound RPA excel export failed for run %s: %s', run.run_no, excel_exc, + ) + # 对齐库存:全成功批次的 Excel 失败要降级,不得让收件人误以为一切正常。 + if run.status == 'success': + run.status = 'partial_failed' + run.error_message = '; '.join(filter(None, [run.error_message, f'Excel导出失败: {excel_exc}']))[:2000] + else: + # 企微/下载展示名:出站RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。 + from app.services.schedule.freight_rpa_outbound_archive import outbound_rpa_result_excel_name + + excel_name = outbound_rpa_result_excel_name(run) + run.excel_file_data = excel_data + run.excel_file_name = excel_name if excel_data else None + run.excel_file_size = excel_size or 0 + + # [STEP] 对齐入站:终态前预生成原始出站 ZIP,企微只发一个包。 + archive_summary = { + 'raw_outbound_zip_available': False, + 'raw_outbound_zip_path': None, + 'raw_outbound_file_count': 0, + 'raw_outbound_file_ids': [], + 'raw_outbound_zip_size': 0, + } + try: + from app.services.schedule.freight_rpa_outbound_archive import persist_outbound_rpa_raw_zip_archive + + archive_summary = persist_outbound_rpa_raw_zip_archive(run) + except Exception as archive_exc: + current_app.logger.error( + '[schedule-run] outbound RPA zip archive failed for run %s: %s', + run.run_no, archive_exc, + ) + + run.response_summary_json = { + **summary, + 'awaiting_outbound_rpa': False, + 'success_count': success_count, + 'empty_count': skipped_count, + 'failed_count': failed_count, + 'excel_export_status': 'ok' if excel_export_ok else 'failed', + 'excel_failed': not excel_export_ok, + **archive_summary, + } + db.session.commit() + # 通知与入站 RPA 完全同构:run 终态后走通用排程出口一次性发 textcard+出站 ZIP。 + try: + task = run.task + if task is not None and task.notify_enabled: + from app.services.schedule.scheduler_service import _notify_schedule_run_wecom + + _notify_schedule_run_wecom(task, run) + db.session.commit() + except Exception as wecom_exc: + current_app.logger.error('[schedule-run] outbound RPA wecom notify failed: %s', wecom_exc) + return {'finalized': True, 'status': run.status} + + +def _outbound_timeout_seconds() -> int: + """读取出站回调等待上限;超时只标记失败,不会自动重试或重发。""" + try: + return max(60, int(current_app.config.get('FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS', 900))) + except (TypeError, ValueError): + return 900 + + +def is_freight_outbound_rpa_task(task: ScheduleTask | None) -> bool: + """识别独立出站 RPA 排程,避免超时回收影响库存或其他平台任务。""" + return bool( + task + and task.schedule_type == 'platform_job' + and normalize_platform_api_path(task.platform_api_path) == OUTBOUND_RPA_JOB_KEY + ) + + +def _outbound_last_activity(run: ScheduleRun, units: list[FreightRpaOutboundUnitRun]) -> datetime: + """出站 run 的最后活动锚:run 开始时间与全部单元 started/finished 时间的最大值。 + + 语义为「笔间静默」:worker 每开始/完成一笔都会推进锚点,锚点静默超过 + FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS 才判定 worker 不再活动。刻意不含单元 + created_at——批量 trigger 中排队单元的创建时间不代表活动,否则整批永不超时。 + 极端长单笔(单站点导出超过 timeout)会被判超时,需按最慢单笔调大该配置。 + """ + stamps = [run.started_at] if run.started_at else [] + for unit in units: + if unit.started_at: + stamps.append(unit.started_at) + if unit.finished_at: + stamps.append(unit.finished_at) + return max(stamps) + + +def _fail_outbound_unit_with_timeout( + unit: FreightRpaOutboundUnitRun, *, now: datetime, timeout_seconds: int, + run_no: str | None = None, +) -> None: + """单个出站单元回调超时收口为失败并写审计(run 级与孤儿级回收共用的唯一实现)。 + + 核心逻辑:错误码/错误文案/审计事件三者的单一事实来源——run 级扫描与孤儿 + 单元扫描共用本函数收口单元,防止两条路径语义漂移。只改单元不 commit, + 事务归属调用方。 + + Args: + unit: 待收口的非终态出站单元。 + now: 收口时刻(同批单元共享同一时间戳)。 + timeout_seconds: 超时窗(写入错误文案与审计 metadata)。 + run_no: 所属排程 run 号(run 级回收传实;孤儿单元无排程,保持 None)。 + Returns: + None。 + """ + before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message} + unit.status = 'failed' + unit.error_code = 'RPA.OUTBOUND_CALLBACK_TIMEOUT' + unit.error_message = f'Outbound RPA callback timed out after {timeout_seconds} seconds' + unit.finished_at = now + append_shipping_audit_event( + event_type='shipping_outbound_rpa_callback_timeout', aggregate_type='shipping_outbound_unit', + aggregate_id=str(unit.id), run_no=run_no, actor_type='worker', actor_id='schedule-recovery', + unit_id=unit.id, result='failure', before=before, + after={'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}, + metadata={'timeout_seconds': timeout_seconds}, + ) + + +def _recover_stale_outbound_run(run: ScheduleRun, *, cutoff: datetime, timeout_seconds: int) -> bool: + """将无回调的独立出站运行收口为失败,保留其单元与触发审计事实。 + + 截止判据为最后活动锚(_outbound_last_activity)而非 run.started_at—— + 串行长批次(>timeout)只要仍有笔间活动就不得被误杀。 + """ + summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} + if not summary.get('awaiting_outbound_rpa') or run.status != 'running' or not run.started_at: + return False + task = run.task or db.session.get(ScheduleTask, run.schedule_task_id) + if not is_freight_outbound_rpa_task(task): + return False + units = FreightRpaOutboundUnitRun.query.filter_by(schedule_run_id=run.id).all() + if _outbound_last_activity(run, units) > cutoff: + return False + now = datetime.utcnow() + pending = [unit for unit in units if unit.status in {'queued', 'awaiting_rpa', 'processing'}] + for unit in pending: + _fail_outbound_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds, run_no=run.run_no) + run.status = 'failed' + run.finished_at = now + run.duration_ms = int((now - run.started_at).total_seconds() * 1000) + run.failed_count = len(pending) or max(1, int(run.failed_count or 0)) + run.error_message = f'出站 RPA 回调等待超时({timeout_seconds} 秒)' + run.step_logs = [*(run.step_logs or []), { + 'step': 'freight_outbound_rpa', 'status': 'failed', + 'detail': {'message': run.error_message, 'timeout_seconds': timeout_seconds}, + }] + run.response_summary_json = {**summary, 'awaiting_outbound_rpa': False, 'recovered_reason': 'outbound_rpa_callback_timeout'} + return True + + +def recover_stale_outbound_rpa_schedule_runs(task: ScheduleTask) -> int: + """在同一出站排程开始前回收超时运行,解除后续 Cron/手动执行的互斥。""" + if not is_freight_outbound_rpa_task(task): + return 0 + timeout_seconds = _outbound_timeout_seconds() + cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds) + recovered = sum( + _recover_stale_outbound_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds) + for run in ScheduleRun.query.filter_by(schedule_task_id=task.id, status='running').all() + ) + if recovered: + db.session.commit() + return recovered + + +def recover_all_stale_outbound_rpa_schedule_runs() -> int: + """Worker 启动时扫描全部超时出站回调,避免重启后运行永久卡住。""" + timeout_seconds = _outbound_timeout_seconds() + cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds) + recovered = sum( + _recover_stale_outbound_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds) + for run in ScheduleRun.query.filter_by(status='running').all() + ) + if recovered: + db.session.commit() + return recovered + + +def recover_all_stale_orphan_outbound_units() -> int: + """回收按需触发(无排程绑定)的超时出站单元,解除来源投影永久 fetching。 + + 【AI 触发时机】仅由排程队列每轮领取维护(queue_service)调用。调拨工作台 + 重试/自动调拨补抓创建的单元 schedule_run_id 为 NULL(见 outbound_trigger_service), + 不在 run 级扫描(recover_all_stale_outbound_rpa_schedule_runs 按 run 遍历)范围内; + Worker 网页异常关闭后回调永不到达,若不回收则来源投影(source_file_status) + 永久 fetching、前端重试按钮永久锁死。 + + 核心逻辑:[STEP 1] 扫 schedule_run_id IS NULL、状态非终态、活动锚 + (coalesce(started_at, created_at):与 run 级同为活动锚思想,单元未被领取 + 无 started_at 时以 created_at 兜底;注意 run 级 _outbound_last_activity 是 + 笔间静默口径、刻意不含 created_at,两者语义不同)超过 + FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS 的单元;admin 单元重试 + 原样复制 schedule_run_id,其 retry 单元同为孤儿,一并覆盖。 + [STEP 2] 逐单元经 _fail_outbound_unit_with_timeout 收口(failed + + RPA.OUTBOUND_CALLBACK_TIMEOUT + 审计,与 run 级扫描同一实现零漂移); + 绝不自动重试或重发——恢复走调拨工作台显式「重试 RPA」。 + + Returns: + 本次回收的单元数。 + """ + timeout_seconds = _outbound_timeout_seconds() + cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds) + orphans = ( + FreightRpaOutboundUnitRun.query + .filter( + FreightRpaOutboundUnitRun.schedule_run_id.is_(None), + FreightRpaOutboundUnitRun.status.in_(('queued', 'awaiting_rpa', 'processing')), + func.coalesce(FreightRpaOutboundUnitRun.started_at, FreightRpaOutboundUnitRun.created_at) < cutoff, + ) + .all() + ) + if not orphans: + return 0 + now = datetime.utcnow() + for unit in orphans: + _fail_outbound_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds) + db.session.commit() + return len(orphans) diff --git a/backend/app/services/schedule/freight_rpa_outbound_job.py b/backend/app/services/schedule/freight_rpa_outbound_job.py new file mode 100644 index 00000000..96b5ae7a --- /dev/null +++ b/backend/app/services/schedule/freight_rpa_outbound_job.py @@ -0,0 +1,156 @@ +""" +backend/app/services/schedule/freight_rpa_outbound_job.py + +用途:独立出站 RPA 排程——按勾选库存源一对一冻结执行单元并写 outbound trigger。 +依赖:freight_rpa.outbound.trigger_io.write_outbound_export_batch_trigger、assert_outbound_rpa_worker_ready、 + FreightRpaSource / FreightRpaOutboundReportConfig / FreightRpaOutboundUnitRun、 + ScheduleTask/Run。 +逻辑:job_registry 的 freight-rpa-outbound 调用本 handler;写 trigger 前 fail-fast; + 口径与入站排程一致(选中 N 源 → N unit),query_parameters 原样下发。 +""" + +from __future__ import annotations + +import uuid +from typing import Any + +from app import db +from app.core.errors import ServiceUnavailableError +from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaOutboundReportConfig, FreightRpaOutboundUnitRun +from app.services.freight_rpa.outbound.trigger_io import SCHEMA, write_outbound_export_batch_trigger +from app.services.freight_rpa.common.worker_heartbeat import ( + RPA_WORKER_OFFLINE_MESSAGE, + assert_outbound_rpa_worker_ready, +) + +OUTBOUND_RPA_JOB_KEY = 'freight-rpa-outbound' +AWAITING_OUTBOUND_RPA_CALLBACK_STATUS = 'awaiting_outbound_rpa_callback' +ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]] + + +def _wanted_source_codes(task: ScheduleTask) -> set[str]: + """提取结构化 source_codes;留空代表全部具备有效出站配置的站点。""" + params = task.job_params if isinstance(task.job_params, dict) else {} + values = params.get('source_codes') or [] + if isinstance(values, str): + values = [values] + return {str(value).strip().upper() for value in values if str(value).strip()} + + +def _eligible_sources(task: ScheduleTask) -> list[tuple[FreightRpaSource, FreightRpaOutboundReportConfig]]: + """读取已启用且已配置出站报表的站点;不依赖库存报表路径、解析绑定或 Warehouse 条件。""" + wanted = _wanted_source_codes(task) + rows = db.session.query(FreightRpaSource, FreightRpaOutboundReportConfig).join( + FreightRpaOutboundReportConfig, FreightRpaOutboundReportConfig.source_id == FreightRpaSource.id, + ).filter(FreightRpaSource.enabled.is_(True)).all() + return [(source, config) for source, config in rows if not wanted or source.source_code.upper() in wanted] + + +def _copy_query_parameters(config: FreightRpaOutboundReportConfig) -> list[dict[str, Any]]: + """浅拷贝出站查询条件原样入快照;空列表表示 Worker 使用页面默认、不填 Warehouse。""" + return [ + dict(item) for item in (config.query_parameters_json or []) + if isinstance(item, dict) + ] + + +def _build_unit( + source: FreightRpaSource, config: FreightRpaOutboundReportConfig, schedule_run_id: int, +) -> FreightRpaOutboundUnitRun: + """冻结可审计的出站执行单元(一源一单元);DBS 日期字段不进入查询快照。""" + callback_id = f'outbound:{uuid.uuid4().hex}' + snapshot = { + 'config_id': config.id, 'config_version': config.config_version, 'connector_type': source.connector_type, + 'report_path_json': config.report_path_json or {}, 'query_parameters_json': _copy_query_parameters(config), + 'warehouse_id': None, 'rpa_profile_id': source.rpa_profile_id, + } + return FreightRpaOutboundUnitRun( + schedule_run_id=schedule_run_id, source_id=source.id, source_code=source.source_code, + connector_type=source.connector_type, warehouse_id=None, callback_id=callback_id, + status='awaiting_rpa', config_snapshot_json=snapshot, + ) + + +def _serialize_trigger_unit(unit: FreightRpaOutboundUnitRun) -> dict[str, Any]: + """生成 Worker 唯一可见的冻结执行载荷;密文凭据只随 outbound trigger 下发。""" + source = unit.source + profile = source.rpa_profile if source is not None else None + if source is None or profile is None or not profile.enabled: + raise RuntimeError(f'outbound source profile unavailable: {unit.source_code}') + snapshot = dict(unit.config_snapshot_json or {}) + return { + 'unit_run_id': unit.id, + 'callback_id': unit.callback_id, + 'source_code': unit.source_code, + 'connector_type': unit.connector_type, + 'warehouse_id': unit.warehouse_id, + 'rpa_profile_id': profile.id, + 'rpa_profile_code': profile.profile_code, + 'login_url': profile.login_url, + 'login_config': dict(profile.login_config_json or {}), + 'credential_envelope': { + 'username_ciphertext': profile.username_ciphertext, + 'password_ciphertext': profile.password_ciphertext, + }, + 'report_path_json': dict(snapshot.get('report_path_json') or {}), + 'query_parameters_json': list(snapshot.get('query_parameters_json') or []), + 'config_snapshot': snapshot, + } + + +def run_freight_rpa_outbound_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: + """ + 写独立出站 trigger;每个勾选站点对应一个执行单元(与入站 RPA 同口径)。 + + 核心逻辑:写 trigger 前 assert_outbound_rpa_worker_ready;离线立即 failed, + 不创建 unit、不进入 awaiting_outbound_rpa_callback。 + """ + units: list[FreightRpaOutboundUnitRun] = [ + _build_unit(source, config, run.id) for source, config in _eligible_sources(task) + ] + if not units: + return 0, 0, 0, 1, [], ['no enabled outbound report sources'], [{'step': 'freight_outbound_rpa', 'status': 'skipped'}] + + # [STEP] 写 trigger / 入库 unit 前 fail-fast,避免 Worker 离线干等到超时。 + try: + assert_outbound_rpa_worker_ready() + except ServiceUnavailableError as exc: + message = str(exc.message or RPA_WORKER_OFFLINE_MESSAGE) + detail_message = str((exc.details or {}).get('detail_message') or message) + return len(units), 0, len(units), 0, [], [detail_message], [{ + 'step': 'freight_outbound_rpa', + 'status': 'failed', + 'detail': { + 'message': message, + 'detail_message': detail_message, + 'error_code': exc.code, + 'reasons': (exc.details or {}).get('reasons') or [], + }, + }] + + db.session.add_all(units) + db.session.flush() + try: + trigger_units = [_serialize_trigger_unit(unit) for unit in units] + except RuntimeError as exc: + for unit in units: + unit.status = 'failed'; unit.error_code = 'RPA.OUTBOUND_PROFILE_UNAVAILABLE'; unit.error_message = str(exc) + db.session.commit() + return len(units), 0, len(units), 0, [], [str(exc)], [{'step': 'freight_outbound_rpa', 'status': 'failed'}] + for unit, trigger_unit in zip(units, trigger_units): + unit.trigger_snapshot_json = trigger_unit + trigger_path = write_outbound_export_batch_trigger(run.run_no, trigger_units, { + 'schedule_run_id': run.id, 'schedule_task_id': task.id, 'schema_version': SCHEMA, + }) + if not trigger_path: + for unit in units: + unit.status = 'failed'; unit.error_code = 'RPA.OUTBOUND_TRIGGER_UNAVAILABLE'; unit.error_message = 'outbound trigger directory unavailable' + db.session.commit() + return len(units), 0, len(units), 0, [], ['outbound trigger directory unavailable'], [{'step': 'freight_outbound_rpa', 'status': 'failed'}] + details = [{'source_code': unit.source_code, 'warehouse_id': unit.warehouse_id, 'callback_id': unit.callback_id} for unit in units] + run.api_request_json = {'run_no': run.run_no, 'trigger_path': trigger_path, 'source_codes': sorted({unit.source_code for unit in units})} + db.session.commit() + return len(units), 0, 0, 0, details, [], [{ + 'step': 'freight_outbound_rpa', 'status': AWAITING_OUTBOUND_RPA_CALLBACK_STATUS, + 'detail': {'trigger_path': trigger_path, 'unit_count': len(units)}, + }] diff --git a/backend/app/services/schedule/freight_rpa_outbound_retention.py b/backend/app/services/schedule/freight_rpa_outbound_retention.py new file mode 100644 index 00000000..d8a1ef75 --- /dev/null +++ b/backend/app/services/schedule/freight_rpa_outbound_retention.py @@ -0,0 +1,66 @@ +""" +backend/app/services/schedule/freight_rpa_outbound_retention.py + +用途:出站原样归档三年到期对象清理(排程壳 + 本阶段清理本体)。 +依赖:FreightRpaOutboundReportFile、file_asset_storage、freight_rpa.common.report_audit。 +逻辑:job_registry 的 freight-rpa-outbound-retention 调用本 handler;仅删除已过保留期的 + MinIO 对象,保留运行、文件事实和审计记录。Task 9 可将本体下沉 outbound.report_archive, + 本文件届时改回薄接缝(对照 inbound_retention)。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from app import db +from app.models import FreightRpaOutboundReportFile +from app.services.file_assets.storage import file_asset_storage +from app.services.freight_rpa.common.report_audit import append_rpa_report_event + +OUTBOUND_RETENTION_JOB_KEY = 'freight-rpa-outbound-retention' + + +def run_freight_rpa_outbound_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]: + """仅删除已到三年保留期的 MinIO 对象,永不删除文件事实、运行或审计。 + + Args: + task: 排程任务行(job_params.limit 提供单批上限,1..1000)。 + run: 排程执行记录(本函数不改写 run,仅按排程协议返回计数/明细/日志)。 + Returns: + 排程平台 Job 协议七元组(总查得数、成功、失败、跳过 0、明细、错误、step_logs)。 + """ + limit = max(1, min(int((getattr(task, 'job_params', {}) or {}).get('limit', 100)), 1000)) + now = datetime.utcnow() + rows = FreightRpaOutboundReportFile.query.filter( + FreightRpaOutboundReportFile.archive_expires_at.is_not(None), + FreightRpaOutboundReportFile.archive_expires_at <= now, + FreightRpaOutboundReportFile.archive_deleted_at.is_(None), + ).order_by(FreightRpaOutboundReportFile.id).limit(limit).all() + success = failed = 0 + errors: list[str] = [] + for report_file in rows: + try: + file_asset_storage.delete_object(report_file.storage_key) + report_file.archive_deleted_at = now + report_file.archive_delete_result_json = {'status': 'deleted', 'deleted_at': now.isoformat()} + append_rpa_report_event( + event_type='shipping_outbound_report_archive_deleted', aggregate_type='shipping_outbound_file', + aggregate_id=str(report_file.id), actor_type='worker', actor_id='outbound-retention', + unit_id=report_file.unit_run_id, result='success', + before={'status': 'archived'}, after={'status': 'archive_deleted'}, + artifact_refs=[{'kind': 'outbound_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], + ) + success += 1 + except Exception as exc: + errors.append(f'{report_file.id}: {exc}') + append_rpa_report_event( + event_type='shipping_outbound_report_archive_delete_attempted', aggregate_type='shipping_outbound_file', + aggregate_id=str(report_file.id), actor_type='worker', actor_id='outbound-retention', + unit_id=report_file.unit_run_id, result='failure', + before={'status': 'archived'}, after={'status': 'archived', 'delete_error': str(exc)[:2000]}, + artifact_refs=[{'kind': 'outbound_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], + ) + failed += 1 + db.session.commit() + return len(rows), success, failed, 0, [{'file_id': row.id} for row in rows], errors, [{'step': 'outbound_retention', 'status': 'completed'}] diff --git a/backend/app/services/schedule/in_transit_transfer_job.py b/backend/app/services/schedule/in_transit_transfer_job.py index 04cd90c3..91a0a6a4 100644 --- a/backend/app/services/schedule/in_transit_transfer_job.py +++ b/backend/app/services/schedule/in_transit_transfer_job.py @@ -1,15 +1,19 @@ """自动调拨排程。 -用途:自动处理当日新成熟可调拨项与历史可恢复异常;执行结果通知统一走 +用途:自动处理可调拨异动与历史可恢复异常;执行结果通知统一走 排程「启用通知」通用企微通知,本任务不自建领域通知。 依赖:auto_transfer、transfer deps、job_registry.ScheduleExecuteResult、 - receipt_trigger_service.list_receipt_capable_source_codes(缺省来源口径)、 + inbound_trigger_service.list_inbound_capable_source_codes(缺省来源口径)、 date_policy(业务日与日期解析)。 -逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发收料 RPA), - 不依赖其他排程成功;来源留空兜底为全部启用收料来源;可选收料日期范围 - 以「T−N 偏移天数」配置,执行时按当日业务日换算为具体日期透传匹配层; - 空数据日(无 run_no 且无 errors)置 domain_notification_managed 保持 - 静默(C5),有 Run 或硬失败交由框架完成卡按排程「启用通知」发送。 +逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发入站 RPA), + 不依赖其他排程成功;来源留空兜底为全部启用入站来源;可选异动日期范围 + 以「T−N 偏移天数」配置,执行时按当日业务日换算为具体日期透传匹配层—— + 该偏移参数是自动处理面的唯一日期边界;【T−2 成熟封顶 2026-10-21】引擎 + 只圈 movement_date ≤ T−2 的成熟记录(T−2 之前数据全部成熟),未配置 + 偏移即处理全部成熟积压;偏移终点落在 T−1/当天(0/1)会被匹配层 + MOVEMENT_DATE_RANGE_INVALID 拒绝(快速失败交框架通知);空数据日(无 + run_no 且无 errors)置 domain_notification_managed 保持静默(C5),有 + Run 或硬失败交由框架完成卡按排程「启用通知」发送。 """ from __future__ import annotations @@ -21,7 +25,7 @@ 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, parse_date -from app.services.in_transit_transfer.receipt_trigger_service import list_receipt_capable_source_codes +from app.services.in_transit_transfer.inbound_trigger_service import list_inbound_capable_source_codes from app.services.schedule.job_registry import ScheduleExecuteResult @@ -31,12 +35,12 @@ def _task_params(task: ScheduleTask) -> dict[str, Any]: def _wanted_source_codes(task: ScheduleTask) -> list[str]: - """提取结构化 source_codes;留空回落为全部启用且已配置收料报表的来源。 + """提取结构化 source_codes;留空回落为全部启用且已配置收料报表(入站证据)的来源。 Args: task: 排程任务(job_params.source_codes 可为列表/字符串/缺省)。 Returns: - 去空白后的来源编码列表;留空时为 list_receipt_capable_source_codes() 结果。 + 去空白后的来源编码列表;留空时为 list_inbound_capable_source_codes() 结果。 """ params = _task_params(task) values = params.get("source_codes") or [] @@ -44,12 +48,12 @@ def _wanted_source_codes(task: ScheduleTask) -> list[str]: values = [values] codes = [str(item).strip() for item in values if str(item).strip()] if not codes: - codes = list_receipt_capable_source_codes() + codes = list_inbound_capable_source_codes() return codes def _offset_to_date(business_date: str, offset_days: Any, label: str, errors: list[str]) -> str | None: - """把「T−N 偏移天数」参数换算为执行日口径的具体收料日期(T−N)。 + """把「T−N 偏移天数」参数换算为执行日口径的具体异动日期(T−N)。 Args: business_date: 业务日期 T(YYYY-MM-DD)。 @@ -79,10 +83,11 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc 底部「启用通知」配置);仅在空数据日(无 run_no 且无 errors)置 domain_notification_managed 抑制框架完成卡(C5 空数据日静默); 有 run_no(成功/部分失败)或硬失败时框架卡照常发送/兜底。 - 可选收料日期范围以「T−N 偏移天数」配置(receipt_from/to_offset_days), + 可选异动日期范围以「T−N 偏移天数」配置(receipt_from/to_offset_days), 执行时按当日业务日换算为具体日期透传匹配层,供测试/排障缩小本轮处理面; - 偏移非法(负数/小数/非数字)快速失败不执行;范围越界由匹配层 - ValidationError 落 errors 走硬失败路径。 + 【T−2 成熟封顶 2026-10-21】引擎只圈 ≤T−2 成熟记录,未配置偏移即处理全部 + 成熟积压,偏移终点 0/1(T−1/当天)由匹配层 ValidationError 落 errors 走 + 硬失败路径;偏移非法(负数/小数/非数字)同样快速失败不执行。 Args: task: 排程任务(job_params: source_codes/recover_history/ @@ -99,21 +104,27 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc # [STEP] T−N 偏移换算:非法配置快速失败(不执行、交框架失败通知), # 防止坏参数被静默忽略后退化成全量积压处理。 param_errors: list[str] = [] - receipt_date_from = _offset_to_date( - business_date, params.get("receipt_from_offset_days"), "收料日期起点", param_errors) - receipt_date_to = _offset_to_date( - business_date, params.get("receipt_to_offset_days"), "收料日期终点", param_errors) + movement_date_from = _offset_to_date( + business_date, params.get("receipt_from_offset_days"), "异动日期起点", param_errors) + movement_date_to = _offset_to_date( + business_date, params.get("receipt_to_offset_days"), "异动日期终点", param_errors) if param_errors: return (0, 0, 0, 0, [], [f"sources={len(source_codes)}"], param_errors) deps = transfer_deps.get_transfer_dependencies() + # [出生翻转 2026-10-14] 调拨类型配置化(D8 匹配创建必填):排程参数 + # job_params.transfer_type 承载类型编码,原样透传匹配层;缺省 None 时 + # 匹配层 fail-closed(TRANSFER_TYPE_REQUIRED 随 errors 硬失败透出), + # 不回落固定类型(类型=平台配置,排程不隐式假设)。 + transfer_type = str(params.get("transfer_type") or "").strip() or None outcome = run_auto_transfer( business_date=business_date, deps=deps, source_codes=source_codes, recover_history=recover_history, - receipt_date_from=receipt_date_from, - receipt_date_to=receipt_date_to, + movement_date_from=movement_date_from, + movement_date_to=movement_date_to, + transfer_type=transfer_type, ) # [STEP] 空数据日静默门禁:无 run 且无错误(匹配后无可执行行,C5)时置 diff --git a/backend/app/services/schedule/job_options.py b/backend/app/services/schedule/job_options.py index 63fb0b38..3ce9ec26 100644 --- a/backend/app/services/schedule/job_options.py +++ b/backend/app/services/schedule/job_options.py @@ -2,9 +2,10 @@ backend/app/services/schedule/job_options.py 用途:平台任务参数 schema 的动态选项来源(options_source → 统一 label/value 列表)。 -依赖:models.Agent、shipping_notice.inventory_source_repository。 +依赖:models.Agent、shipping_notice.onhand_source_repository。 逻辑:api/schedule/platform_tasks.py options 接口与 job_params 选项范围校验调用; 前端只认识 options_source 字符串,不感知数据来自哪张表/哪个配置文件。 + 货代 RPA 注册键为 freight_rpa_sources、freight_rpa_inbound_sources 与 freight_rpa_outbound_sources。 """ from __future__ import annotations @@ -33,9 +34,9 @@ def _agent_apps_options() -> list[dict[str, Any]]: ] -def _shipping_inventory_sources_options() -> list[dict[str, Any]]: - """启用中的货代库存源(value=source_code,来自数据库主数据)。""" - from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources +def _freight_rpa_sources_options() -> list[dict[str, Any]]: + """启用中的货代来源站点(value=source_code,来自数据库主数据;供 onhand 排程选源)。""" + from app.services.shipping_notice.onhand_source_repository import list_database_inventory_sources return [ { @@ -51,16 +52,29 @@ def _shipping_inventory_sources_options() -> list[dict[str, Any]]: ] -def _shipping_receipt_sources_options() -> list[dict[str, Any]]: - """已启用且已配置收料报表的站点,供独立收料排程选择。""" - from app.models import ShippingInventorySource, ShippingReceiptReportConfig +def _freight_rpa_inbound_sources_options() -> list[dict[str, Any]]: + """已启用且已配置入站报表的站点,供独立入站排程选择。""" + from app.models import FreightRpaSource, FreightRpaInboundReportConfig - rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join( - ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id, - ).filter(ShippingInventorySource.enabled.is_(True)).all() + rows = db.session.query(FreightRpaSource, FreightRpaInboundReportConfig).join( + FreightRpaInboundReportConfig, FreightRpaInboundReportConfig.source_id == FreightRpaSource.id, + ).filter(FreightRpaSource.enabled.is_(True)).all() return [{ 'label': source.display_name or source.source_code, 'value': source.source_code, - 'description': f'{source.connector_type} · 收料已配置', + 'description': f'{source.connector_type} · 入站已配置', + } for source, _config in rows] + + +def _freight_rpa_outbound_sources_options() -> list[dict[str, Any]]: + """已启用且已配置出站报表的站点,供独立出站排程选择。""" + from app.models import FreightRpaSource, FreightRpaOutboundReportConfig + + rows = db.session.query(FreightRpaSource, FreightRpaOutboundReportConfig).join( + FreightRpaOutboundReportConfig, FreightRpaOutboundReportConfig.source_id == FreightRpaSource.id, + ).filter(FreightRpaSource.enabled.is_(True)).all() + return [{ + 'label': source.display_name or source.source_code, 'value': source.source_code, + 'description': f'{source.connector_type} · 出站已配置', } for source, _config in rows] @@ -101,8 +115,9 @@ def _users_options() -> list[dict[str, Any]]: # options_source 注册表:新增来源只需在此登记 provider,不动 API 层 _OPTIONS_PROVIDERS: dict[str, Callable[[], list[dict[str, Any]]]] = { "agent_apps": _agent_apps_options, - "shipping_inventory_sources": _shipping_inventory_sources_options, - "shipping_receipt_sources": _shipping_receipt_sources_options, + "freight_rpa_sources": _freight_rpa_sources_options, + "freight_rpa_inbound_sources": _freight_rpa_inbound_sources_options, + "freight_rpa_outbound_sources": _freight_rpa_outbound_sources_options, "hxops_users": _hxops_users_options, "users": _users_options, } diff --git a/backend/app/services/schedule/job_params.py b/backend/app/services/schedule/job_params.py index d8ec3d8e..3a79deb3 100644 --- a/backend/app/services/schedule/job_params.py +++ b/backend/app/services/schedule/job_params.py @@ -133,7 +133,7 @@ def validate_task_params( [STEP 4] check_options=True 时校验 select/multi_select 值在选项范围内。 Args: - task_type: platform job key(如 shipping-inventory-rpa)。 + task_type: platform job key(如 freight-rpa-onhand)。 job_params: 前端提交或 task.job_params 存储的参数 dict;None 视为空。 check_options: 是否联动 options_source 校验取值范围;执行期建议 False(选项可能漂移)。 diff --git a/backend/app/services/schedule/job_registry.py b/backend/app/services/schedule/job_registry.py index f1124232..580fae9c 100644 --- a/backend/app/services/schedule/job_registry.py +++ b/backend/app/services/schedule/job_registry.py @@ -2,7 +2,7 @@ backend/app/services/schedule/job_registry.py 用途:平台内置排程 Job Registry(任务契约中心:key → handler + 展示信息 + params_schema + defaults)。 -依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、voucher_po_print_job、voucher_oa_sales_release_job、job_params。 +依赖:freight_rpa_onhand_job、freight_rpa_inbound_job、freight_rpa_outbound_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、voucher_po_print_job、voucher_oa_sales_release_job、job_params。 逻辑:internal_jobs API 与 platform_job 排程通过 platform_api_path 引用已注册 key; api/schedule/platform_tasks.py 下发 params_schema 供前端 DynamicTaskParamsForm 通用渲染。 """ @@ -34,7 +34,7 @@ class PlatformJobDefinition: "label_key": "...", # 前端 i18n key(可选) "required": False, "default": [], - "options_source": "shipping_inventory_sources", # select/multi_select 动态选项来源(可选) + "options_source": "freight_rpa_sources", # select/multi_select 动态选项来源(可选) "placeholder": "...", "placeholder_key": "...", "help": "...", "help_key": "...", } @@ -44,7 +44,7 @@ class PlatformJobDefinition: label: str handler: PlatformJobHandler description: str = "" - # 前端 i18n key(如 admin.schedule.form.platformJobShippingInventory); + # 前端 i18n key(如 admin.schedule.form.platformJobFreightRpaOnhand); # 前端下拉优先 $t(label_key),label 仅作 fallback/debug。 label_key: str = "" description_key: str = "" @@ -132,9 +132,11 @@ def _register_builtin_platform_jobs() -> None: from app.services.schedule.file_asset_cleanup_job import run_file_asset_cleanup_schedule from app.services.schedule.fixed_assets_snapshot_job import run_fixed_assets_snapshot_schedule from app.services.schedule.shipping_audit_retention_job import run_shipping_audit_retention_schedule - from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule - from app.services.schedule.freight_receipt_rpa_job import run_freight_receipt_rpa_schedule - from app.services.schedule.freight_receipt_rpa_retention_job import run_freight_receipt_rpa_retention_schedule + from app.services.schedule.freight_rpa_onhand_job import run_freight_rpa_onhand_schedule + from app.services.schedule.freight_rpa_inbound_job import run_freight_rpa_inbound_schedule + from app.services.schedule.freight_rpa_inbound_retention import run_freight_rpa_inbound_retention_schedule + from app.services.schedule.freight_rpa_outbound_job import run_freight_rpa_outbound_schedule + from app.services.schedule.freight_rpa_outbound_retention import run_freight_rpa_outbound_retention_schedule from app.services.schedule.shipping_order_extraction_progress_cleanup_job import run_shipping_order_extraction_progress_cleanup_schedule from app.services.schedule.shipping_post_ot_auto_fulfill_compensation_job import ( run_shipping_post_ot_auto_fulfill_compensation_schedule, @@ -371,48 +373,67 @@ def _register_builtin_platform_jobs() -> None: defaults={"hash_sample_limit": 500, "dry_run": True, "limit": 1}, )) register_platform_job(PlatformJobDefinition( - key="shipping-inventory-rpa", + key="freight-rpa-onhand", label="货代库存 RPA", - label_key="admin.schedule.form.platformJobShippingInventory", - handler=run_shipping_inventory_rpa_schedule, + label_key="admin.schedule.form.platformJobFreightRpaOnhand", + handler=run_freight_rpa_onhand_schedule, description="按计划从配置的库存源抓取库存数据,由 freight_rpa_worker 异步导出。", - description_key="admin.schedule.form.shippingInventoryJobHint", + description_key="admin.schedule.form.freightRpaOnhandJobHint", category="shipping", params_schema=( { "key": "source_codes", "type": "multi_select", "label": "库存源", - "label_key": "admin.schedule.form.shippingInventorySources", + "label_key": "admin.schedule.form.freightRpaSources", # 兼容历史任务语义:留空 = 导出全部启用库存源,故不设 required "required": False, "default": [], - "options_source": "shipping_inventory_sources", + "options_source": "freight_rpa_sources", "placeholder": "留空则导出全部启用库存源", - "placeholder_key": "admin.schedule.form.shippingInventorySourcesPlaceholder", + "placeholder_key": "admin.schedule.form.freightRpaSourcesPlaceholder", "help": "选择需要执行的库存源;选项来自库存源配置,留空则全部执行。", - "help_key": "admin.schedule.form.shippingInventorySourcesHelp", + "help_key": "admin.schedule.form.freightRpaSourcesHelp", }, ), defaults={"source_codes": []}, )) register_platform_job(PlatformJobDefinition( - key="freight-receipt-rpa", - label="货代收料 RPA", - handler=run_freight_receipt_rpa_schedule, - description="按计划从已配置收料报表的站点导出并归档收料文件。", + key="freight-rpa-inbound", + label="货代入站 RPA", + handler=run_freight_rpa_inbound_schedule, + description="按计划从已配置入站报表的站点导出并归档入站文件。", category="shipping", params_schema=({ - "key": "source_codes", "type": "multi_select", "label": "收料站点", "required": False, - "default": [], "options_source": "shipping_receipt_sources", - "help": "选择需要执行的收料站点;留空则执行所有已启用收料配置。", + "key": "source_codes", "type": "multi_select", "label": "入站站点", "required": False, + "default": [], "options_source": "freight_rpa_inbound_sources", + "help": "选择需要执行的入站站点;留空则执行所有已启用入站配置。", },), defaults={"source_codes": []}, )) register_platform_job(PlatformJobDefinition( - key='freight-receipt-rpa-retention', label='货代收料归档到期清理', - handler=run_freight_receipt_rpa_retention_schedule, - description='仅删除已过三年保留期的收料对象,保留运行、文件事实和审计记录。', category='shipping', + key='freight-rpa-inbound-retention', label='货代入站归档到期清理', + handler=run_freight_rpa_inbound_retention_schedule, + description='仅删除已过三年保留期的入站对象,保留运行、文件事实和审计记录。', category='shipping', + params_schema=({'key': 'limit', 'type': 'number', 'label': '单批上限', 'required': False, 'default': 100},), defaults={'limit': 100}, + )) + register_platform_job(PlatformJobDefinition( + key="freight-rpa-outbound", + label="货代出站 RPA", + handler=run_freight_rpa_outbound_schedule, + description="按计划从已配置出站报表的站点导出并归档出站文件。", + category="shipping", + params_schema=({ + "key": "source_codes", "type": "multi_select", "label": "出站站点", "required": False, + "default": [], "options_source": "freight_rpa_outbound_sources", + "help": "选择需要执行的出站站点;留空则执行所有已启用出站配置。", + },), + defaults={"source_codes": []}, + )) + register_platform_job(PlatformJobDefinition( + key='freight-rpa-outbound-retention', label='货代出站归档到期清理', + handler=run_freight_rpa_outbound_retention_schedule, + description='仅删除已过三年保留期的出站对象,保留运行、文件事实和审计记录。', category='shipping', params_schema=({'key': 'limit', 'type': 'number', 'label': '单批上限', 'required': False, 'default': 100},), defaults={'limit': 100}, )) register_platform_job(PlatformJobDefinition( @@ -596,7 +617,7 @@ def _register_builtin_platform_jobs() -> None: "label_key": "admin.schedule.form.transferSourceCodes", "required": False, "default": [], - "options_source": "shipping_inventory_sources", + "options_source": "freight_rpa_sources", }, { "key": "recover_history", @@ -612,7 +633,7 @@ def _register_builtin_platform_jobs() -> None: "label": "收料日期起(T-N)", "label_key": "admin.schedule.form.transferReceiptDateFrom", "required": False, - "help": "填天数 N,按执行日换算收料日期下限 T−N;例:4=从 T−4 起。留空=全部成熟积压(默认 ≤ T-2)。", + "help": "填天数 N,按执行日换算异动日期下限 T−N;例:4=从 T−4 起。留空=全部积压。", }, { "key": "receipt_to_offset_days", @@ -620,7 +641,7 @@ def _register_builtin_platform_jobs() -> None: "label": "收料日期止(T-N)", "label_key": "admin.schedule.form.transferReceiptDateTo", "required": False, - "help": "填天数 N,按执行日换算收料日期上限 T−N;例:起4止2=只处理 T−4~T−2。不得晚于成熟上限(默认 T-2)。", + "help": "填天数 N,按执行日换算异动日期上限 T−N;例:起4止2=只处理 T−4~T−2。不得晚于执行日业务日期。", }, ), defaults={"source_codes": [], "recover_history": True}, diff --git a/backend/app/services/schedule/query_service.py b/backend/app/services/schedule/query_service.py index 837af26a..39e19694 100644 --- a/backend/app/services/schedule/query_service.py +++ b/backend/app/services/schedule/query_service.py @@ -1,3 +1,11 @@ +""" +backend/app/services/schedule/query_service.py + +用途:排程任务与运行记录的查询/序列化。 +依赖:ScheduleRun / ScheduleTask、库存/入站/出站 raw-zip 可用性判定。 +逻辑:list_tasks / get_run / serialize_run 供管理端排程工作台与下载按钮读取。 + 执行记录日期窗用 coalesce(started_at, created_at),排队中尚未开始的 run 仍落在创建日。 +""" from __future__ import annotations from datetime import datetime, timezone @@ -9,8 +17,9 @@ from sqlalchemy.orm import joinedload from app import db from app.models import ScheduleRun, ScheduleTask from app.core.response import utc_iso -from app.services.schedule.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.freight_rpa_onhand_archive import inventory_raw_zip_available_from_summary +from app.services.schedule.freight_rpa_inbound_archive import inbound_raw_zip_available_from_summary +from app.services.schedule.freight_rpa_outbound_archive import outbound_raw_zip_available_from_summary from app.services.schedule.timezone_util import ( DEFAULT_SCHEDULE_TIMEZONE, compute_next_run_at, @@ -61,6 +70,7 @@ def serialize_task(task: ScheduleTask, *, last_status: str | None = None) -> dic def serialize_run(run: ScheduleRun) -> dict: + """序列化单条运行记录;附带库存/入站/出站 raw-zip 是否可下载。""" summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} return { 'id': run.id, @@ -86,7 +96,8 @@ def serialize_run(run: ScheduleRun) -> dict: 'excel_file_name': run.excel_file_name, 'excel_file_size': run.excel_file_size, 'inventory_raw_zip_available': inventory_raw_zip_available_from_summary(summary), - 'receipt_raw_zip_available': receipt_raw_zip_available_from_summary(summary), + 'inbound_raw_zip_available': inbound_raw_zip_available_from_summary(summary), + 'outbound_raw_zip_available': outbound_raw_zip_available_from_summary(summary), 'kb_sync_status': run.kb_sync_status, 'kb_group_id': run.kb_group_id, 'kb_document_id': run.kb_document_id, @@ -149,6 +160,15 @@ def list_runs( started_before: Optional[datetime] = None, limit: int = 100, ) -> list[dict]: + """ + 按任务、状态与时间窗列出执行记录。 + + 核心逻辑:时间窗比较 coalesce(started_at, created_at)。手动入队时 started_at 仍为空, + 若只比 started_at,工作台默认「今天」会把排队中的 run 滤掉,再次点击则因活动 run 冲突。 + + Returns: + 序列化后的运行记录,按 created_at 倒序,最多 500 条。 + """ query = db.session.query(ScheduleRun).options(joinedload(ScheduleRun.task)).join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id) if task_id is not None: query = query.filter(ScheduleRun.schedule_task_id == task_id) @@ -156,10 +176,12 @@ def list_runs( query = query.filter(ScheduleTask.name.ilike(f'%{schedule_name}%')) if status: query = query.filter(ScheduleRun.status == status) + # 排队 run 还没有 started_at,用创建时间落入同一日期窗,避免工作台看起来像没触发。 + activity_at = func.coalesce(ScheduleRun.started_at, ScheduleRun.created_at) if started_after is not None: - query = query.filter(ScheduleRun.started_at >= _as_naive_utc(started_after)) + query = query.filter(activity_at >= _as_naive_utc(started_after)) if started_before is not None: - query = query.filter(ScheduleRun.started_at < _as_naive_utc(started_before)) + query = query.filter(activity_at < _as_naive_utc(started_before)) if owner_user_id is not None: query = query.filter(ScheduleTask.owner_user_id == owner_user_id) if notify_user_id is not None: diff --git a/backend/app/services/schedule/queue_service.py b/backend/app/services/schedule/queue_service.py index c1630854..372e1a99 100644 --- a/backend/app/services/schedule/queue_service.py +++ b/backend/app/services/schedule/queue_service.py @@ -2,7 +2,8 @@ backend/app/services/schedule/queue_service.py 用途:把手动与 Cron 排程统一写入通用 Job 队列,并维护 ScheduleRun 业务状态。 -依赖:models.ScheduleTask/ScheduleRun、jobs.queue、schedule timezone 与 RPA 收口服务。 +依赖:models.ScheduleTask/ScheduleRun、jobs.queue、schedule timezone 与 RPA 收口服务 + (onhand / inbound / outbound finalize 超时回收)。 逻辑:API 只创建 queued run;独立 schedule worker 扫描到期任务、领取 Job 后执行 scheduler_service。 domain/job_type 固定 schedule/schedule_run 供 worker 认领;业务身份写入 business_ref(schedule_run:{id}:{platform_api_path})、payload 与 message。 @@ -19,14 +20,20 @@ from app import db from app.jobs.queue import enqueue, fail_job, finish_job, recover_stale_jobs from app.jobs.types import JobType from app.models import Job, ScheduleRun, ScheduleTask -from app.services.schedule.shipping_inventory_rpa_finalize import ( +from app.services.schedule.freight_rpa_onhand_finalize import ( recover_all_stale_awaiting_rpa_schedule_runs, recover_stale_awaiting_rpa_schedule_runs, ) -from app.services.schedule.freight_receipt_rpa_finalize import ( - recover_all_stale_receipt_rpa_schedule_runs, - recover_stale_receipt_rpa_schedule_runs, - is_awaiting_receipt_rpa_schedule_run, +from app.services.schedule.freight_rpa_inbound_finalize import ( + recover_all_stale_orphan_inbound_units, + recover_all_stale_inbound_rpa_schedule_runs, + recover_stale_inbound_rpa_schedule_runs, + is_awaiting_inbound_rpa_schedule_run, +) +from app.services.schedule.freight_rpa_outbound_finalize import ( + recover_all_stale_orphan_outbound_units, + recover_all_stale_outbound_rpa_schedule_runs, + recover_stale_outbound_rpa_schedule_runs, ) from app.services.schedule.timezone_util import compute_next_run_at, utc_now_naive @@ -232,7 +239,8 @@ def enqueue_manual_schedule_run( if task is None: raise LookupError(f"schedule task {task_id} not found") recover_stale_awaiting_rpa_schedule_runs(task) - recover_stale_receipt_rpa_schedule_runs(task) + recover_stale_inbound_rpa_schedule_runs(task) + recover_stale_outbound_rpa_schedule_runs(task) active = _active_run(task.id) if active is not None: job = ( @@ -286,7 +294,8 @@ def enqueue_due_schedule_runs(*, limit: int = 5) -> int: # 每轮都回收当前任务已超时的外部 RPA 回调,不能仅依赖 worker 启动时扫一次; # 这只是终态化失败,不会自动重新导出。 recover_stale_awaiting_rpa_schedule_runs(task) - recover_stale_receipt_rpa_schedule_runs(task) + recover_stale_inbound_rpa_schedule_runs(task) + recover_stale_outbound_rpa_schedule_runs(task) if _active_run(task.id) is None: _create_queued_run(task, trigger_type="cron", triggered_by_user_id=None) _advance_next_run(task) @@ -331,12 +340,12 @@ def prepare_schedule_queue() -> int: if not _worker_initialized: # [STEP 1] 兼容升级前由 Web 线程留下的 running 记录;无活动 Job 承接时标记中断。 - from app.services.schedule.shipping_inventory_rpa_finalize import is_awaiting_rpa_schedule_run + from app.services.schedule.freight_rpa_onhand_finalize import is_awaiting_rpa_schedule_run legacy_running = db.session.query(ScheduleRun).filter(ScheduleRun.status == "running").all() interrupted = 0 for run in legacy_running: - if is_awaiting_rpa_schedule_run(run) or is_awaiting_receipt_rpa_schedule_run(run): + if is_awaiting_rpa_schedule_run(run) or is_awaiting_inbound_rpa_schedule_run(run): continue active_job = ( query_jobs_for_schedule_run(run.id) @@ -357,7 +366,7 @@ def prepare_schedule_queue() -> int: recovered = recover_all_stale_awaiting_rpa_schedule_runs() if recovered: current_app.logger.info("[schedule-worker] recovered %d stale awaiting RPA runs", recovered) - from app.services.shipping_notice.inventory_rpa_callback_cleanup import ( + from app.services.freight_rpa.onhand.callback_cleanup import ( recover_pending_rpa_callback_cleanup_jobs, ) @@ -370,7 +379,7 @@ def prepare_schedule_queue() -> int: # 调拨来源等待回调 Job 的超时回收与下方 RPA 心跳告警同属每轮领取维护: # 不能挂在 worker 启动一次性分支里,否则进程长期驻留期间超时任务永远无法终态化。 - from app.services.in_transit_transfer.receipt_callback_bridge import recover_stale_waiting_source_jobs + from app.services.in_transit_transfer.inbound_callback_bridge import recover_stale_waiting_source_jobs transfer_stale = recover_stale_waiting_source_jobs() if transfer_stale: @@ -378,13 +387,28 @@ def prepare_schedule_queue() -> int: # 收料 run 超时对账同为每轮领取维护(2026-10-07 从启动一次性分支迁出): # 此前长驻进程期间超时 run 永不终态(RUN20261001131705E5E5 卡执行中的根因)。 - # 回收判据为最后活动锚(笔间静默),健康长批次不被误杀,见 freight_receipt_rpa_finalize。 - receipt_stale = recover_all_stale_receipt_rpa_schedule_runs() - if receipt_stale: - current_app.logger.info("[schedule-worker] recovered %d stale receipt RPA runs", receipt_stale) + # 回收判据为最后活动锚(笔间静默),健康长批次不被误杀,见 freight_rpa_inbound_finalize。 + inbound_stale = recover_all_stale_inbound_rpa_schedule_runs() + if inbound_stale: + current_app.logger.info("[schedule-worker] recovered %d stale inbound RPA runs", inbound_stale) + + # 按需触发(无排程)孤儿单元同口径回收(2026-10-16):调拨工作台重试/自动调拨 + # 补抓创建的单元 schedule_run_id 为 NULL,上方 run 级扫描按 run 遍历覆盖不到; + # 网页异常关闭后回调永不到达,不回收则来源投影永久 fetching、重试按钮永久锁死。 + orphan_stale = recover_all_stale_orphan_inbound_units() + if orphan_stale: + current_app.logger.info("[schedule-worker] recovered %d stale orphan inbound RPA units", orphan_stale) + + # 出站 run / 孤儿单元超时对账与入站同属每轮领取维护,不得挂启动一次性分支。 + outbound_stale = recover_all_stale_outbound_rpa_schedule_runs() + if outbound_stale: + current_app.logger.info("[schedule-worker] recovered %d stale outbound RPA runs", outbound_stale) + outbound_orphan_stale = recover_all_stale_orphan_outbound_units() + if outbound_orphan_stale: + current_app.logger.info("[schedule-worker] recovered %d stale orphan outbound RPA units", outbound_orphan_stale) try: - from app.services.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status + from app.services.freight_rpa.common.worker_heartbeat_alert import maybe_alert_rpa_worker_status maybe_alert_rpa_worker_status(force=False) except Exception as exc: diff --git a/backend/app/services/schedule/schedule_contract.py b/backend/app/services/schedule/schedule_contract.py index 44c69327..ad90d754 100644 --- a/backend/app/services/schedule/schedule_contract.py +++ b/backend/app/services/schedule/schedule_contract.py @@ -23,13 +23,14 @@ VALID_DATA_PIPELINE_SOURCES = frozenset({DATA_SOURCE_DATABASE, DATA_SOURCE_EXTER LEGACY_SCHEDULE_TYPES = frozenset({"platform_app", "dify_app"}) +# 仍在导入 JSON 里出现的历史 data_source。货代在手任务的旧键已由 s17c 整列改写, +# 运行期只认 platform job key freight-rpa-onhand。 LEGACY_DATA_SOURCE_TO_PLATFORM_JOB = { - "shipping_inventory_rpa": "shipping-inventory-rpa", "faq_hot_aggregate": "faq-aggregate-hot", } # 允许写 ScheduleTaskConfig 的 platform_job(其余平台任务仅存 cron + job key,禁配置) -PLATFORM_JOBS_ALLOWING_CONFIG = frozenset({"shipping-inventory-rpa"}) +PLATFORM_JOBS_ALLOWING_CONFIG = frozenset({"freight-rpa-onhand"}) def platform_job_allows_config(key: str | None) -> bool: diff --git a/backend/app/services/schedule/scheduler_service.py b/backend/app/services/schedule/scheduler_service.py index b2059780..d8bb7012 100644 --- a/backend/app/services/schedule/scheduler_service.py +++ b/backend/app/services/schedule/scheduler_service.py @@ -2,7 +2,9 @@ backend/app/services/schedule/scheduler_service.py 用途:排程任务生命周期(创建/更新)与单次运行执行器。 -依赖:schedule_contract、job_params、cron_util、timezone_util、excel_service、wecom_notify、kb_sync。 +依赖:schedule_contract、job_params、cron_util、timezone_util、excel_service、wecom_notify、kb_sync、 + freight_rpa_onhand_finalize / inbound_finalize / outbound_finalize(awaiting 延后终态与超时回收)、 + onhand / inbound / outbound archive raw-zip 可用性(企微深链 download 意图)。 逻辑:api/schedule/tasks.py 与 import_service 调用 create_task/update_task/enable_task; job_params 在本层经 normalize_job_params_for_contract 唯一归一化(含切换 platform_api_path 未传参时重置默认值);schedule worker 调用 run_task_now 并经 resolve_schedule_executor 分发 handler; @@ -18,22 +20,27 @@ from typing import Any from flask import current_app from app import db -from app.models import ScheduleRun, ScheduleTask, ShippingReceiptReportFile, User +from app.models import ScheduleRun, ScheduleTask, FreightRpaInboundReportFile, User from app.services.schedule.cron_util import normalize_cron_expr from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot from app.services.schedule.excel_service import export_schedule_result_excel from app.services.schedule import resolve_schedule_executor, resolve_schedule_header, normalize_platform_api_path -from app.services.schedule.freight_receipt_rpa_job import RECEIPT_RPA_JOB_KEY -from app.services.schedule.shipping_inventory_rpa_finalize import ( +from app.services.schedule.freight_rpa_inbound_job import INBOUND_RPA_JOB_KEY +from app.services.schedule.freight_rpa_onhand_finalize import ( apply_deferred_schedule_run_state, is_awaiting_rpa_schedule_run, recover_stale_awaiting_rpa_schedule_runs, should_defer_schedule_run_finalization, ) -from app.services.schedule.freight_receipt_rpa_finalize import ( - apply_deferred_receipt_schedule_run_state, - recover_stale_receipt_rpa_schedule_runs, - should_defer_receipt_schedule_run, +from app.services.schedule.freight_rpa_inbound_finalize import ( + apply_deferred_inbound_schedule_run_state, + recover_stale_inbound_rpa_schedule_runs, + should_defer_inbound_schedule_run, +) +from app.services.schedule.freight_rpa_outbound_finalize import ( + apply_deferred_outbound_schedule_run_state, + recover_stale_outbound_rpa_schedule_runs, + should_defer_outbound_schedule_run, ) from app.services.schedule.job_params import normalize_job_params_for_contract from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id @@ -103,11 +110,12 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun) """ 构造排程企微 textcard 跳转 query 参数。 - 核心逻辑:指向管理端 /admin/schedules;有原始库存/收料归档时附加 raw_zip=1 + 核心逻辑:指向管理端 /admin/schedules;有原始库存/入站/出站归档时附加 raw_zip=1 与对应 download 意图,由前端登录后自动触发一次下载,失败时保留手动入口。 """ - from app.services.schedule.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.freight_rpa_onhand_archive import inventory_raw_zip_available_from_summary + from app.services.schedule.freight_rpa_inbound_archive import inbound_raw_zip_available_from_summary + from app.services.schedule.freight_rpa_outbound_archive import outbound_raw_zip_available_from_summary summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} params: dict[str, Any] = { @@ -117,38 +125,41 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun) if inventory_raw_zip_available_from_summary(summary): params['raw_zip'] = '1' params['download'] = 'inventory_raw_zip' - elif receipt_raw_zip_available_from_summary(summary): + elif inbound_raw_zip_available_from_summary(summary): params['raw_zip'] = '1' - params['download'] = 'receipt_raw_zip' + params['download'] = 'inbound_raw_zip' + elif outbound_raw_zip_available_from_summary(summary): + params['raw_zip'] = '1' + params['download'] = 'outbound_raw_zip' return params -def _receipt_report_files_for_run(run: ScheduleRun) -> list[ShippingReceiptReportFile]: +def _inbound_report_files_for_run(run: ScheduleRun) -> list[FreightRpaInboundReportFile]: """ - 收集收料排程 run 名下可投递的收料报表文件;非收料任务返回空列表。 + 收集入站排程 run 名下可投递的入站报表文件;非收料任务返回空列表。 - 核心逻辑:按 platform_api_path 识别收料排程,返回该 run 全部单元已归档且 + 核心逻辑:按 platform_api_path 识别入站排程,返回该 run 全部单元已归档且 未被清理(archive_deleted_at 为空)的报表文件。企微完成通知已改为发 ZIP, 本函数保留给管理员单文件重发等旁路读取。 """ - from app.models import ShippingReceiptRpaUnitRun + from app.models import FreightRpaInboundUnitRun task = run.task if ( task is None or task.schedule_type != 'platform_job' - or normalize_platform_api_path(task.platform_api_path) != RECEIPT_RPA_JOB_KEY + or normalize_platform_api_path(task.platform_api_path) != INBOUND_RPA_JOB_KEY ): return [] return ( - ShippingReceiptReportFile.query.join( - ShippingReceiptRpaUnitRun, ShippingReceiptReportFile.unit_run_id == ShippingReceiptRpaUnitRun.id, + FreightRpaInboundReportFile.query.join( + FreightRpaInboundUnitRun, FreightRpaInboundReportFile.unit_run_id == FreightRpaInboundUnitRun.id, ) .filter( - ShippingReceiptRpaUnitRun.schedule_run_id == run.id, - ShippingReceiptReportFile.archive_deleted_at.is_(None), + FreightRpaInboundUnitRun.schedule_run_id == run.id, + FreightRpaInboundReportFile.archive_deleted_at.is_(None), ) - .order_by(ShippingReceiptReportFile.id) + .order_by(FreightRpaInboundReportFile.id) .all() ) @@ -158,7 +169,7 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str: 组装排程完成企微 textcard 正文。 核心逻辑:与管理端统计口径一致,展示 total/success/skipped/failed 四列计数; - 有原始库存/收料归档时提示包已随通知发送或可点击下载。 + 有原始库存/入站/出站归档时提示包已随通知发送或可点击下载。 """ status_label = _WECOM_STATUS_LABEL.get(run.status, run.status) skipped_count = int(run.skipped_count or 0) @@ -171,13 +182,16 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str: summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} if summary.get('excel_failed') or summary.get('excel_export_status') == 'failed': description += '\n备注: 库存源已成功,但排程 Excel 生成失败' - from app.services.schedule.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.freight_rpa_onhand_archive import inventory_raw_zip_available_from_summary + from app.services.schedule.freight_rpa_inbound_archive import inbound_raw_zip_available_from_summary + from app.services.schedule.freight_rpa_outbound_archive import outbound_raw_zip_available_from_summary if inventory_raw_zip_available_from_summary(summary): description += '\n原始库存包:点击本通知,登录 HXOPS 后自动下载' - if receipt_raw_zip_available_from_summary(summary): - description += '\n原始收料包:已随本通知发送;亦可点击本通知登录后下载' + if inbound_raw_zip_available_from_summary(summary): + description += '\n原始入站包:已随本通知发送;亦可点击本通知登录后下载' + if outbound_raw_zip_available_from_summary(summary): + description += '\n原始出站包:已随本通知发送;亦可点击本通知登录后下载' return description @@ -186,8 +200,8 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None: 排程完成后的通用企微通知。 核心逻辑:若 response_summary_json.domain_notification_managed=true(如立账凭证检核), 则跳过以免与领域缺件/失败告警重复。 - 库存与收料 RPA 共用本出口与同一套门禁:库存附加排程 Excel 与原始库存包; - 收料附加该 run 的原始收料 ZIP(不再逐文件推送)。 + 库存、入站、出站 RPA 共用本出口与同一套门禁:库存附加排程 Excel 与原始库存包; + 入站/出站附加该 run 的原始 ZIP(不再逐文件推送)。 """ from app.services.integrations.wecom.notify import ( upload_wecom_temp_media, @@ -238,7 +252,7 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None: raw_zip_media_id = None raw_zip_file_name = None try: - from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download + from app.services.schedule.freight_rpa_onhand_archive import resolve_inventory_raw_zip_download raw_zip_path, raw_zip_file_name = resolve_inventory_raw_zip_download(run) raw_zip_media_id = upload_wecom_temp_media(raw_zip_path.read_bytes(), raw_zip_file_name) @@ -248,18 +262,33 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None: run.run_no, exc, ) - receipt_zip_media_id = None - receipt_zip_file_name = None + inbound_zip_media_id = None + inbound_zip_file_name = None try: - from app.services.schedule.shipping_receipt_rpa_archive import resolve_receipt_raw_zip_download + from app.services.schedule.freight_rpa_inbound_archive import resolve_inbound_raw_zip_download - receipt_zip_path, receipt_zip_file_name = resolve_receipt_raw_zip_download(run) - receipt_zip_media_id = upload_wecom_temp_media( - receipt_zip_path.read_bytes(), receipt_zip_file_name, + inbound_zip_path, inbound_zip_file_name = resolve_inbound_raw_zip_download(run) + inbound_zip_media_id = upload_wecom_temp_media( + inbound_zip_path.read_bytes(), inbound_zip_file_name, ) except Exception as exc: current_app.logger.info( - '[wecom-schedule] raw receipt zip media skipped for run %s: %s', + '[wecom-schedule] raw inbound zip media skipped for run %s: %s', + run.run_no, exc, + ) + + outbound_zip_media_id = None + outbound_zip_file_name = None + try: + from app.services.schedule.freight_rpa_outbound_archive import resolve_outbound_raw_zip_download + + outbound_zip_path, outbound_zip_file_name = resolve_outbound_raw_zip_download(run) + outbound_zip_media_id = upload_wecom_temp_media( + outbound_zip_path.read_bytes(), outbound_zip_file_name, + ) + except Exception as exc: + current_app.logger.info( + '[wecom-schedule] raw outbound zip media skipped for run %s: %s', run.run_no, exc, ) @@ -318,23 +347,41 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None: except Exception as exc: errors.append(f'{u.real_name or u.username}: raw zip exception={exc}') - if receipt_zip_media_id: + if inbound_zip_media_id: try: - receipt_zip_audit = _create_audit( - f'{_WECOM_EVENT_TYPE}_receipt_raw_zip', u, - title, f'[原始收料包] {receipt_zip_file_name}', uuid.uuid4().hex, + inbound_zip_audit = _create_audit( + f'{_WECOM_EVENT_TYPE}_inbound_raw_zip', u, + title, f'[原始入站包] {inbound_zip_file_name}', uuid.uuid4().hex, ) - receipt_zip_data = send_wecom_file_message(u.wecom_userid, receipt_zip_media_id) - if receipt_zip_data.get('errcode') == 0: - receipt_zip_audit.status = 'sent' + inbound_zip_data = send_wecom_file_message(u.wecom_userid, inbound_zip_media_id) + if inbound_zip_data.get('errcode') == 0: + inbound_zip_audit.status = 'sent' else: - receipt_zip_audit.error_code = str(receipt_zip_data.get('errcode')) - receipt_zip_audit.error_message = str(receipt_zip_data.get('errmsg', 'unknown'))[:255] + inbound_zip_audit.error_code = str(inbound_zip_data.get('errcode')) + inbound_zip_audit.error_message = str(inbound_zip_data.get('errmsg', 'unknown'))[:255] errors.append( - f'{u.real_name or u.username}: receipt zip errcode={receipt_zip_data.get("errcode")}' + f'{u.real_name or u.username}: inbound zip errcode={inbound_zip_data.get("errcode")}' ) except Exception as exc: - errors.append(f'{u.real_name or u.username}: receipt zip exception={exc}') + errors.append(f'{u.real_name or u.username}: inbound zip exception={exc}') + + if outbound_zip_media_id: + try: + outbound_zip_audit = _create_audit( + f'{_WECOM_EVENT_TYPE}_outbound_raw_zip', u, + title, f'[原始出站包] {outbound_zip_file_name}', uuid.uuid4().hex, + ) + outbound_zip_data = send_wecom_file_message(u.wecom_userid, outbound_zip_media_id) + if outbound_zip_data.get('errcode') == 0: + outbound_zip_audit.status = 'sent' + else: + outbound_zip_audit.error_code = str(outbound_zip_data.get('errcode')) + outbound_zip_audit.error_message = str(outbound_zip_data.get('errmsg', 'unknown'))[:255] + errors.append( + f'{u.real_name or u.username}: outbound zip errcode={outbound_zip_data.get("errcode")}' + ) + except Exception as exc: + errors.append(f'{u.real_name or u.username}: outbound zip exception={exc}') if textcard_ok_count > 0: run.wecom_notified = True @@ -570,7 +617,8 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: 该路径原先只写库不打日志,worker 汇总行看不到失败原因。 """ recover_stale_awaiting_rpa_schedule_runs(task) - recover_stale_receipt_rpa_schedule_runs(task) + recover_stale_inbound_rpa_schedule_runs(task) + recover_stale_outbound_rpa_schedule_runs(task) if run is None: existing = db.session.query(ScheduleRun).filter( @@ -640,8 +688,12 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: errors=errors, step_logs=step_logs, ) - if should_defer_receipt_schedule_run(task, step_logs): - return apply_deferred_receipt_schedule_run_state( + if should_defer_inbound_schedule_run(task, step_logs): + return apply_deferred_inbound_schedule_run_state( + run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs, + ) + if should_defer_outbound_schedule_run(task, step_logs): + return apply_deferred_outbound_schedule_run_state( run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs, ) diff --git a/backend/app/services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py b/backend/app/services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py index 37dfb9a0..bc052a85 100644 --- a/backend/app/services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py +++ b/backend/app/services/schedule/shipping_post_ot_auto_fulfill_compensation_job.py @@ -16,7 +16,7 @@ from app.services.shipping_notice.line_auto_fulfill_coordinator import ( coordinate_post_ot_auto_fulfill, enqueue_post_ot_auto_fulfill_job, ) -from app.services.shipping_notice.line_inventory_match_projection import line_auto_fulfill_enabled +from app.services.shipping_notice.line_onhand_match_projection import line_auto_fulfill_enabled from app.services.shipping_notice.post_ot_fulfillment_wave_service import ( list_eligible_post_ot_snapshot_line_ids, ) diff --git a/backend/app/services/shipping_notice/auto_progress_controller.py b/backend/app/services/shipping_notice/auto_progress_controller.py index 2f8a1b8a..e82a952e 100644 --- a/backend/app/services/shipping_notice/auto_progress_controller.py +++ b/backend/app/services/shipping_notice/auto_progress_controller.py @@ -5,7 +5,7 @@ services/shipping_notice/auto_progress_controller.py 依赖:Job transactional outbox、ShippingProcessExecution/Gate、CandidateSet、现有库存/RPA、匹配和 Excel 服务; process_gate_job_service.cancel_inventory_external_wait_polls(显式回到库存准备时终止轮询)。 逻辑:入口只创建或复用一个 Task 活动 Job;Worker 每次仅评估一个正式 Gate,Gate passed 与后继 Job - 在同一数据库事务落库。retry_rpa 或 manual_override_source 定向回 inventory_preparation 时 + 在同一数据库事务落库。retry_rpa 或 manual_override_source 定向回 onhand_preparation 时 覆盖 waiting_external 残留 poll 并入队准备动作(改源默认 auto 复用指定源快照)。 库存源 RPA Attempt 仍由既有 per_source_rpa_service 独立并行执行。 """ @@ -22,7 +22,7 @@ from app import db from app.jobs.queue import enqueue from app.jobs.types import JobType from app.models import Job, ShippingOrderTask, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt -from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set +from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_set from app.services.shipping_notice.process_gate_contract import action_belongs_to_gate from app.services.shipping_notice.tool_common import log_task_event @@ -149,8 +149,8 @@ def determine_formal_start_gate( return 'field_conflict_resolution' candidate = candidate_set if candidate_set is not None else get_active_candidate_set(task) if candidate is None or str(getattr(candidate, 'lifecycle_status', '') or '').lower() != 'frozen': - return 'inventory_source_routing' - return 'inventory_preparation' + return 'onhand_source_routing' + return 'onhand_preparation' def _create_formal_execution_for_task( @@ -418,7 +418,7 @@ def submit_auto_progress( # (manual_override_source)。后者 inventory_mode 可为 auto(复用指定源快照), # 但仍须取消残留 poll / 活动 Attempt,否则会只读轮询、不按新源取数。 explicit_inventory_retry = ( - str(resume_gate_code or '').strip() == 'inventory_preparation' + str(resume_gate_code or '').strip() == 'onhand_preparation' and ( str(inventory_mode or '').strip() == 'retry_rpa' or str(trigger or '').strip() == 'manual_override_source' @@ -433,7 +433,7 @@ def submit_auto_progress( db.session.flush() execution = ShippingProcessExecution.query.filter_by(id=int(execution.id)).with_for_update().one() current_gate = ( - 'inventory_preparation' + 'onhand_preparation' if explicit_inventory_retry else str(execution.current_gate_code or '').strip() or None ) @@ -479,16 +479,16 @@ def submit_auto_progress( stale_job.message = '显式库存重抓:取消残留活动 Job' gate.status = 'blocked_retryable' gate.passed_at = None - gate.blocking_reason_code = 'inventory_rpa_retry_requested' - gate.next_action_code = 'retry_inventory_preparation' + gate.blocking_reason_code = 'onhand_rpa_retry_requested' + gate.next_action_code = 'retry_onhand_preparation' gate.evaluation_version = int(gate.evaluation_version) + 1 gate.lock_version = int(gate.lock_version) + 1 gate.updated_at = _utc_now() - execution.current_gate_code = 'inventory_preparation' + execution.current_gate_code = 'onhand_preparation' # 阶段能力回退同时切换责任方;保留旧 Gate 的 owner 会使技术 Gate # 被 submit_auto_progress 误判为人工节点,从而跳过 Attempt/RPA 入队。 execution.responsible_party = 'worker' - execution.primary_next_action_code = 'retry_inventory_preparation' + execution.primary_next_action_code = 'retry_onhand_preparation' execution.updated_at = _utc_now() db.session.flush() active_attempt = ( @@ -532,7 +532,7 @@ def submit_auto_progress( # 无主动作或人工 Gate 均停留在 Projection;只有服务端已下发动作的 # system/worker Gate 才可自动创建 Attempt 并入队。 # 责任方只描述 Gate 的默认归属,不代表当前动作可由 Worker 执行。 - # upload_inventory_file 等导航动作必须保留给用户;否则成功回调已同步 + # upload_onhand_file 等导航动作必须保留给用户;否则成功回调已同步 # 的库存事实会被旧人工阻断动作再次覆盖。 if ( gate is not None diff --git a/backend/app/services/shipping_notice/batch_orchestrator.py b/backend/app/services/shipping_notice/batch_orchestrator.py index ae577d7a..6167bc84 100644 --- a/backend/app/services/shipping_notice/batch_orchestrator.py +++ b/backend/app/services/shipping_notice/batch_orchestrator.py @@ -57,7 +57,7 @@ def _unmark_running(bucket: set[str], key: str) -> None: def _should_orchestrate_task(task: Any) -> bool: from app.services.shipping_notice.task_disposition_service import task_is_active - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task if not task_is_active(task): return False @@ -100,7 +100,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]: return {"status": "skipped", "message": "task already running"} try: - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task task = get_task_by_ref(normalized_task_no) if not task: @@ -130,7 +130,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]: ): # [STEP] 先做一次同步超时复查:单次 RPA 触发已过期且无成功回执时直接落 # rpa_exhausted(needs_human),避免仅依赖异步 Gate 轮询导致单票卡在 running。 - from app.services.shipping_notice.inventory_rpa_workflow import maybe_recheck_inventory_rpa_wait + from app.services.shipping_notice.onhand_rpa_workflow import maybe_recheck_inventory_rpa_wait recheck = maybe_recheck_inventory_rpa_wait(task, source='batch_orchestrator') if recheck is not None: diff --git a/backend/app/services/shipping_notice/conversation_processing_projection.py b/backend/app/services/shipping_notice/conversation_processing_projection.py index 9f1a65f0..9a91937a 100644 --- a/backend/app/services/shipping_notice/conversation_processing_projection.py +++ b/backend/app/services/shipping_notice/conversation_processing_projection.py @@ -65,7 +65,7 @@ _PROCESSING_ITEM_LIFECYCLES = frozenset({ 'layout_parsing', 'extracting', 'building_order', - 'inventory_matching', + 'onhand_matching', 'generating_excel', }) diff --git a/backend/app/services/shipping_notice/dify_inputs.py b/backend/app/services/shipping_notice/dify_inputs.py index 3bfe2ba1..979c2c62 100644 --- a/backend/app/services/shipping_notice/dify_inputs.py +++ b/backend/app/services/shipping_notice/dify_inputs.py @@ -13,7 +13,7 @@ from __future__ import annotations from datetime import datetime from typing import Any -from app.models import ShippingOrderTask, ShippingTemporaryInventorySession +from app.models import ShippingOrderTask, ShippingTemporaryOnhandSession from app.services.agent_runtime_context.builder import serialize_for_dify from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_INPUT from app.services.shipping_notice.runtime_context import build_shipping_runtime_context @@ -40,18 +40,18 @@ def _latest_pending_temporary_inventory_session(conversation_id: str) -> str | N normalized = str(conversation_id or '').strip() if not normalized: return None - item = ShippingTemporaryInventorySession.query.filter( - ShippingTemporaryInventorySession.conversation_id == normalized, - ShippingTemporaryInventorySession.status.in_([ + item = ShippingTemporaryOnhandSession.query.filter( + ShippingTemporaryOnhandSession.conversation_id == normalized, + ShippingTemporaryOnhandSession.status.in_([ 'created', 'awaiting_profile_confirmation', 'awaiting_mapping_suggestion', 'awaiting_mapping_confirmation', ]), - ShippingTemporaryInventorySession.expires_at > datetime.utcnow(), + ShippingTemporaryOnhandSession.expires_at > datetime.utcnow(), ).order_by( - ShippingTemporaryInventorySession.updated_at.desc(), - ShippingTemporaryInventorySession.id.desc(), + ShippingTemporaryOnhandSession.updated_at.desc(), + ShippingTemporaryOnhandSession.id.desc(), ).first() return str(item.session_no or '').strip().upper() or None if item else None diff --git a/backend/app/services/shipping_notice/error_explainability_contract.py b/backend/app/services/shipping_notice/error_explainability_contract.py index f8bc8091..81f29477 100644 --- a/backend/app/services/shipping_notice/error_explainability_contract.py +++ b/backend/app/services/shipping_notice/error_explainability_contract.py @@ -145,7 +145,7 @@ INVENTORY_SOURCE_LINE_BLOCK_REASON_CODES: Final[frozenset[str]] = frozenset({ 'manual_inventory_source_invalid', 'inventory_source_conflicted', 'inventory_source_changed', - 'inventory_source_identity_mismatch', + 'onhand_source_identity_mismatch', }) # 库存源路由 — 单源不可用明细(写入 unavailable_reasons[source_code]) @@ -162,11 +162,11 @@ INVENTORY_SOURCE_UNAVAILABLE_REASON_CODES: Final[frozenset[str]] = frozenset({ INVENTORY_PREP_REASON_CODES: Final[frozenset[str]] = frozenset({ 'inventory_preparation_waiting', 'inventory_preparation_failed', - 'inventory_rpa_queued', - 'inventory_rpa_timeout', - 'inventory_rpa_login_failed', - 'inventory_rpa_export_failed', - 'inventory_rpa_exhausted', + 'onhand_rpa_queued', + 'onhand_rpa_timeout', + 'onhand_rpa_login_failed', + 'onhand_rpa_export_failed', + 'onhand_rpa_exhausted', 'inventory_file_missing', 'inventory_file_identity_mismatch', 'inventory_file_empty', @@ -292,7 +292,7 @@ INVENTORY_SOURCE_LINE_BLOCK_REASON_CODES_EMITTED: Final[frozenset[str]] = frozen 'manual_inventory_source_invalid', 'inventory_source_conflicted', 'inventory_source_changed', - 'inventory_source_identity_mismatch', + 'onhand_source_identity_mismatch', }) # 附件告警已映射并可出现在审计 / Intake 投影中的子集 @@ -310,11 +310,11 @@ ATTACHMENT_REASON_CODES_EMITTED: Final[frozenset[str]] = frozenset({ INVENTORY_PREP_REASON_CODES_EMITTED: Final[frozenset[str]] = frozenset({ 'inventory_preparation_waiting', 'inventory_preparation_failed', - 'inventory_rpa_queued', - 'inventory_rpa_timeout', - 'inventory_rpa_login_failed', - 'inventory_rpa_export_failed', - 'inventory_rpa_exhausted', + 'onhand_rpa_queued', + 'onhand_rpa_timeout', + 'onhand_rpa_login_failed', + 'onhand_rpa_export_failed', + 'onhand_rpa_exhausted', 'inventory_file_missing', 'inventory_file_empty', 'inventory_file_identity_mismatch', @@ -560,25 +560,25 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = { 'source_excel_template_unavailable': _meta('admin', 'retry_with_latest_rules', '库存 Excel 模板未发布'), 'inventory_source_conflicted': _meta('system', 'retry_with_latest_rules', '多条规则产生冲突,需修复规则后自动重新裁决'), 'inventory_source_changed': _meta('system', 'retry_with_latest_rules', '库存源配置已变化,系统将重新裁决'), - 'inventory_source_identity_mismatch': _meta('system', 'retry_with_latest_rules', '当前任务与库存源身份不一致,需修复规则或订单事实'), + 'onhand_source_identity_mismatch': _meta('system', 'retry_with_latest_rules', '当前任务与库存源身份不一致,需修复规则或订单事实'), 'effective_reservation_missing': _meta('owner', 'edit_reservation', '缺少有效的预约单号'), # 库存准备 / RPA / 匹配 / Excel / 上传 - 'inventory_preparation_waiting': _meta('worker', 'poll_inventory_preparation', '库存文件准备中,请稍后刷新'), - 'inventory_preparation_failed': _meta('owner', 'retry_inventory_preparation', '库存准备失败,请重试或上传库存文件'), - 'inventory_rpa_queued': _meta('worker', 'poll_inventory_preparation', 'RPA 任务已排队等待执行'), - 'inventory_rpa_timeout': _meta('worker', 'reload_inventory_result', 'RPA 执行超时'), - 'inventory_rpa_login_failed': _meta('admin', 'retry_inventory_preparation', '库存平台登录失败'), - 'inventory_rpa_export_failed': _meta('worker', 'retry_inventory_preparation', '库存报表导出失败'), - 'inventory_rpa_exhausted': _meta('owner', 'reload_inventory_result', '库存源重试次数已耗尽'), - 'inventory_file_missing': _meta('owner', 'retry_inventory_preparation', '未生成库存文件'), + 'inventory_preparation_waiting': _meta('worker', 'poll_onhand_preparation', '库存文件准备中,请稍后刷新'), + 'inventory_preparation_failed': _meta('owner', 'retry_onhand_preparation', '库存准备失败,请重试或上传库存文件'), + 'onhand_rpa_queued': _meta('worker', 'poll_onhand_preparation', 'RPA 任务已排队等待执行'), + 'onhand_rpa_timeout': _meta('worker', 'reload_onhand_result', 'RPA 执行超时'), + 'onhand_rpa_login_failed': _meta('admin', 'retry_onhand_preparation', '库存平台登录失败'), + 'onhand_rpa_export_failed': _meta('worker', 'retry_onhand_preparation', '库存报表导出失败'), + 'onhand_rpa_exhausted': _meta('owner', 'reload_onhand_result', '库存源重试次数已耗尽'), + 'inventory_file_missing': _meta('owner', 'retry_onhand_preparation', '未生成库存文件'), 'inventory_candidates_missing': _meta('system', 'retry_with_latest_rules', '正式库存候选版本缺失'), 'inventory_candidate_data_incomplete': _meta('system', 'retry_with_latest_rules', '库存候选事实不完整'), 'inventory_candidate_version_stale': _meta('system', 'retry_with_latest_rules', '库存候选版本已切换'), 'inventory_match_out_of_candidate_scope': _meta('system', 'retry_with_latest_rules', '库存命中超出当前候选范围'), - 'inventory_file_identity_mismatch': _meta('owner', 'retry_inventory_preparation', '返回文件与所选库存源不一致'), - 'inventory_file_empty': _meta('owner', 'retry_inventory_preparation', '库存文件为空或没有有效库存记录'), - 'inventory_mapping_required': _meta('system', 'retry_inventory_field_mapping', '库存字段映射待自动校验'), - 'inventory_match_failed': _meta('owner', 'open_inventory_match_review', '库存匹配失败'), + 'inventory_file_identity_mismatch': _meta('owner', 'retry_onhand_preparation', '返回文件与所选库存源不一致'), + 'inventory_file_empty': _meta('owner', 'retry_onhand_preparation', '库存文件为空或没有有效库存记录'), + 'inventory_mapping_required': _meta('system', 'retry_onhand_field_mapping', '库存字段映射待自动校验'), + 'inventory_match_failed': _meta('owner', 'open_onhand_match_review', '库存匹配失败'), 'inventory_insufficient': _meta('owner', 'open_shortage_review', '库存不足'), 'inventory_shortage_review_required': _meta('owner', 'open_shortage_review', '存在库存缺口,需要人工处理'), 'excel_not_ready': _meta('system', 'recheck_excel_readiness', '当前尚不满足 Excel 生成条件'), @@ -607,13 +607,13 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = { 'excel_template_missing': _meta('admin', 'recheck_excel_readiness', '发货 Excel 模板缺失'), 'excel_input_incomplete': _meta('owner', 'recheck_excel_readiness', '生成 Excel 所需输入不完整'), 'artifact_validation_failed': _meta('system', 'regenerate_excel_artifact', 'Excel 产物校验失败'), - 'inventory_required_column_missing': _meta('system', 'retry_inventory_field_mapping', '库存文件缺少必填列'), - 'inventory_column_ambiguous': _meta('system', 'retry_inventory_field_mapping', '库存列映射存在歧义'), - 'inventory_sku_not_found': _meta('owner', 'open_inventory_match_review', '库存中未找到对应 SKU'), - 'inventory_reservation_not_found': _meta('owner', 'open_inventory_match_review', '库存中未找到对应 Reservation'), - 'inventory_warehouse_mismatch': _meta('owner', 'open_inventory_match_review', '仓库与订单要求不一致'), - 'inventory_uom_conversion_failed': _meta('owner', 'open_inventory_match_review', '单位换算失败'), - 'inventory_multi_file_conflict': _meta('owner', 'override_line_inventory_source', '多库存文件结果冲突'), + 'inventory_required_column_missing': _meta('system', 'retry_onhand_field_mapping', '库存文件缺少必填列'), + 'inventory_column_ambiguous': _meta('system', 'retry_onhand_field_mapping', '库存列映射存在歧义'), + 'inventory_sku_not_found': _meta('owner', 'open_onhand_match_review', '库存中未找到对应 SKU'), + 'inventory_reservation_not_found': _meta('owner', 'open_onhand_match_review', '库存中未找到对应 Reservation'), + 'inventory_warehouse_mismatch': _meta('owner', 'open_onhand_match_review', '仓库与订单要求不一致'), + 'inventory_uom_conversion_failed': _meta('owner', 'open_onhand_match_review', '单位换算失败'), + 'inventory_multi_file_conflict': _meta('owner', 'override_line_onhand_source', '多库存文件结果冲突'), } @@ -970,7 +970,7 @@ AUDIT_COVERAGE_MATRIX: Final[tuple[dict[str, Any], ...]] = ( 'node': 'late_rpa_callback_ignored', 'event_type': 'rpa_callback_rejected', 'reason_code': 'late_callback_ignored', - 'source_module': 'inventory_rpa_workflow.py', + 'source_module': 'onhand_rpa_workflow.py', 'wire_marker': '"reason_code": "late_callback_ignored"', 'allow_empty': False, }, @@ -1035,8 +1035,8 @@ def assert_error_explainability_contract_integrity() -> None: 'inventory_source_unavailable', 'require_manual_review', ): - assert PROCESS_GATE_REASON_OWNING_GATE.get(code) == 'inventory_source_routing', ( - f'{code} must own inventory_source_routing' + assert PROCESS_GATE_REASON_OWNING_GATE.get(code) == 'onhand_source_routing', ( + f'{code} must own onhand_source_routing' ) # [STEP 4] meta 责任方与动作合法性 diff --git a/backend/app/services/shipping_notice/excel_template.py b/backend/app/services/shipping_notice/excel_template.py index 53f78b5a..2dc569ab 100644 --- a/backend/app/services/shipping_notice/excel_template.py +++ b/backend/app/services/shipping_notice/excel_template.py @@ -26,8 +26,8 @@ from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( ShippingExcelTemplate, ShippingExportArtifact, - ShippingInventoryField, - ShippingInventorySource, + FreightRpaOnhandField, + FreightRpaSource, ShippingOrderField, ) from app.services.file_assets.storage import file_asset_storage @@ -327,7 +327,7 @@ def _validate_definition(item: ShippingExcelTemplate) -> dict[str, Any]: inventory_field_id = int(source_key) except (TypeError, ValueError) as exc: raise ValidationError('Inventory field is invalid', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID') from exc - inventory_field = db.session.get(ShippingInventoryField, inventory_field_id) + inventory_field = db.session.get(FreightRpaOnhandField, inventory_field_id) if inventory_field is None or inventory_field.status != 'active': raise ValidationError('Inventory field is unavailable', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID') source_key = str(inventory_field.id) @@ -371,7 +371,7 @@ def retire(template_id: int) -> dict[str, Any]: raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND') if item.status != 'published': raise ConflictError('Only published template can be retired', code='SHIPPING.EXCEL_TEMPLATE_RETIRE_INVALID') - if ShippingInventorySource.query.filter_by(excel_template_id=item.id).count(): + if FreightRpaSource.query.filter_by(excel_template_id=item.id).count(): raise ConflictError('Rebind inventory sources first', code='SHIPPING.EXCEL_TEMPLATE_RETIRE_BLOCKED') item.status = 'retired' db.session.commit() diff --git a/backend/app/services/shipping_notice/export.py b/backend/app/services/shipping_notice/export.py index b26caaac..1ca2622b 100644 --- a/backend/app/services/shipping_notice/export.py +++ b/backend/app/services/shipping_notice/export.py @@ -33,9 +33,9 @@ from app.models import ( ShippingExcelTemplate, ShippingExportArtifact, ShippingNoticeLine, - ShippingNoticeLineInventoryMatch, - ShippingInventoryField, - ShippingInventorySource, + ShippingNoticeLineOnhandMatch, + FreightRpaOnhandField, + FreightRpaSource, ShippingOrderSnapshot, ShippingOrderField, ShippingNotice, @@ -58,11 +58,11 @@ def _notice_source_code(task: ShippingNotice) -> str | None: task_id = int(task_id) codes = [ str(row[0]).strip().upper() - for row in db.session.query(ShippingNoticeLineInventoryMatch.inventory_source_code).filter( - ShippingNoticeLineInventoryMatch.task_id == task_id, - ShippingNoticeLineInventoryMatch.is_current.is_(True), - ShippingNoticeLineInventoryMatch.match_result == 'matched', - ShippingNoticeLineInventoryMatch.inventory_source_code.isnot(None), + for row in db.session.query(ShippingNoticeLineOnhandMatch.source_code).filter( + ShippingNoticeLineOnhandMatch.task_id == task_id, + ShippingNoticeLineOnhandMatch.is_current.is_(True), + ShippingNoticeLineOnhandMatch.match_result == 'matched', + ShippingNoticeLineOnhandMatch.source_code.isnot(None), ).distinct().all() if row[0] ] @@ -76,10 +76,10 @@ def _notice_chosen_odm(task: ShippingNotice) -> str | None: return None values = [ str(row[0]).strip() - for row in db.session.query(ShippingNoticeLineInventoryMatch.chosen_odm_id).filter( - ShippingNoticeLineInventoryMatch.task_id == int(task_id), - ShippingNoticeLineInventoryMatch.is_current.is_(True), - ShippingNoticeLineInventoryMatch.chosen_odm_id.isnot(None), + for row in db.session.query(ShippingNoticeLineOnhandMatch.chosen_odm_id).filter( + ShippingNoticeLineOnhandMatch.task_id == int(task_id), + ShippingNoticeLineOnhandMatch.is_current.is_(True), + ShippingNoticeLineOnhandMatch.chosen_odm_id.isnot(None), ).distinct().all() if row[0] ] @@ -93,11 +93,11 @@ def _notice_inventory_file_id(task: ShippingNotice) -> int | None: return None task_id = int(task_id) ids = [ - int(row[0]) for row in db.session.query(ShippingNoticeLineInventoryMatch.inventory_snapshot_id).filter( - ShippingNoticeLineInventoryMatch.task_id == task_id, - ShippingNoticeLineInventoryMatch.is_current.is_(True), - ShippingNoticeLineInventoryMatch.match_result == 'matched', - ShippingNoticeLineInventoryMatch.inventory_snapshot_id.isnot(None), + int(row[0]) for row in db.session.query(ShippingNoticeLineOnhandMatch.onhand_snapshot_id).filter( + ShippingNoticeLineOnhandMatch.task_id == task_id, + ShippingNoticeLineOnhandMatch.is_current.is_(True), + ShippingNoticeLineOnhandMatch.match_result == 'matched', + ShippingNoticeLineOnhandMatch.onhand_snapshot_id.isnot(None), ).distinct().all() ] return ids[0] if len(ids) == 1 else None @@ -395,8 +395,8 @@ def _inventory_fields_by_mode(mappings: list[dict[str, Any]], row_mode: str) -> ids = {int(item) for item in raw_ids if item.isdigit()} if len(ids) != len(raw_ids): raise ValueError('发货模板引用的库存字段无效') - rows = ShippingInventoryField.query.filter( - ShippingInventoryField.id.in_(ids), ShippingInventoryField.status == 'active', + rows = FreightRpaOnhandField.query.filter( + FreightRpaOnhandField.id.in_(ids), FreightRpaOnhandField.status == 'active', ).all() if ids else [] if len(rows) != len(ids): raise ValueError('发货模板引用的库存字段已不存在') @@ -407,7 +407,7 @@ def _inventory_field_user_label(field_id: str) -> str: """把库存字段主键转换为用户可读中文名,禁止在业务错误中直接暴露「字段 6」。""" normalized = str(field_id or '').strip() if normalized.isdigit(): - row = ShippingInventoryField.query.filter_by(id=int(normalized)).first() + row = FreightRpaOnhandField.query.filter_by(id=int(normalized)).first() display_name = str(getattr(row, 'display_name', '') or '').strip() if row else '' if display_name: return display_name @@ -572,17 +572,20 @@ def _filename( def _input_checksum( - task: ShippingNotice, source: ShippingInventorySource, template: ShippingExcelTemplate, + task: ShippingNotice, source: FreightRpaSource, template: ShippingExcelTemplate, snapshot: ShippingOrderSnapshot, header: dict[str, Any], lines: list[dict[str, Any]], inventory_lines: list[dict[str, Any]], notice_id: int | None = None, ) -> str: """以本次实际导出库存行计算输入指纹,保证 Artifact 内容与审计事实一致。""" + # s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该外键。 + report_config = source.onhand_report_config payload = { 'task_id': task.id, 'source_id': source.id, 'template_id': template.id, 'template_checksum': template.file_checksum, 'definition_checksum': template.definition_checksum, 'schema_version_id': snapshot.schema_version_id, 'snapshot_id': snapshot.id, - 'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': _notice_inventory_file_id(task), + 'parsing_profile_id': report_config.parsing_profile_id if report_config is not None else None, + 'inventory_snapshot_id': _notice_inventory_file_id(task), 'order_header': header, 'order_lines': lines, 'inventory_lines': inventory_lines, 'notice_id': notice_id, } @@ -592,7 +595,7 @@ def _input_checksum( def _resolve_odm_inventory_field_id() -> int | None: """返回 odm_id 库存字段目录 ID;目录未配置或已停用时返回 None(整单 ODM 裁决整体跳过)。""" - field = ShippingInventoryField.query.filter_by(field_code='odm_id', status='active').first() + field = FreightRpaOnhandField.query.filter_by(field_code='odm_id', status='active').first() return int(field.id) if field is not None else None @@ -610,7 +613,7 @@ def _normalize_match_keys(match_keys: list[dict[str, Any]]) -> list[dict[str, st } catalog = { str(item.id): str(item.id) - for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(ids)).all() + for item in FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(ids)).all() } normalized_keys: list[dict[str, str]] = [] for item in match_keys: @@ -673,9 +676,9 @@ def _adjudicate_notice_odm( """ 整单(Notice)级 ODM 收敛裁决;模板不消费 odm 字段时直接跳过。 - 逻辑:客户 ODM ID 范围非空先过滤;用户选择(OT.chosen_odm_id)次之; - 无范围且无选择时,各导出行命中 odm 交集唯一则自动收敛(唯一可行解,无需人工)。 - 多值并存时不过滤,由逐行折叠按现有契约阻断,并由工作台下发候选供用户选择。 + 逻辑:各行命中 odm 交集恰一个值(唯一可行解)时直接收敛并跳过客户 odm_ids + 白名单(2026-10-20 白名单降级);多值时客户 ODM ID 范围非空先过滤,用户选择 + (OT.chosen_odm_id)次之;范围排除全部命中或选择已失效时抛 ValueError。 Returns: {'inventory_lines': 收敛后的库存行, 'feasible_odm_ids': 排序候选, @@ -708,8 +711,13 @@ def _adjudicate_notice_odm( result['chosen_odm_id'] = odm_display.get(chosen_odm, str(chosen_odm_raw).strip()) if chosen_odm else None normalized_keys = _normalize_match_keys(match_keys) pre_odm_sets = _per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key) + # [STEP] 唯一命中优先(2026-10-20 白名单降级):各行命中的 ODM 交集恰一个值时 + # 直接取用,不再套客户 odm_ids 白名单——客户主数据与库存文件的口径漂移不应 + # 拦下「Excel 里只有一个 ODM」的确定事实(回归 OT-20261017-184D440D)。 + unique_feasible = _intersect_odm_sets(pre_odm_sets) + unique_hit = len(unique_feasible) == 1 - if customer_odm_ids: + if customer_odm_ids and not unique_hit: result['whitelist_applied'] = True scope = set(customer_odm_ids) inventory_lines = [row for row in inventory_lines if _match_text(row.get(odm_key)) in scope] @@ -717,20 +725,18 @@ def _adjudicate_notice_odm( # 避免回落成误导性的「没有匹配的库存记录」。 if any(pre_odm_sets) and not any(_per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)): raise ValueError('订单行命中的库存记录 ODM ID 不在客户数据维护的 ODM ID 范围内,请检查客户数据或库存文件') + elif unique_hit: + # 唯一命中即唯一可行解:绕过白名单直接收敛,多值时白名单才参与收敛。 + inventory_lines = [row for row in inventory_lines if _match_text(row.get(odm_key)) in unique_feasible] # 逐行候选取「客户范围过滤后、选择收敛前」的集合:用户在任何一行改选,候选都来自同一口径。 scoped_sets = ( _per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key) - if customer_odm_ids else pre_odm_sets + if (customer_odm_ids and not unique_hit) else pre_odm_sets ) if chosen_odm: inventory_lines = [row for row in inventory_lines if _match_text(row.get(odm_key)) == chosen_odm] if any(pre_odm_sets) and not any(_per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)): raise ValueError('发货通知已选择的 ODM ID 在当前库存中不存在,请重新选择') - elif not customer_odm_ids: - # 无范围、无选择:交集唯一即唯一可行解,自动收敛;多值留给折叠阻断 + 人工选择。 - feasible = _intersect_odm_sets(pre_odm_sets) - if len(feasible) == 1: - inventory_lines = [row for row in inventory_lines if _match_text(row.get(odm_key)) in feasible] result['inventory_lines'] = inventory_lines result['per_line_odm_ids'] = [ sorted(odm_display.get(value, value) for value in line_set) @@ -762,7 +768,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]: ) # [T6 E2] 滚动履约只导出当前可用行;短缺/冲突行由下方 Reservation 资格筛选排除。 source_code = str(_notice_source_code(task) or '').strip().upper() - source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first() + source = FreightRpaSource.query.filter_by(source_code=source_code, enabled=True).first() if source is None: source = None if source is None: @@ -770,7 +776,10 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]: template = source.excel_template if template is None or template.status != 'published': raise ValueError('库存源未绑定已发布的发货 Excel 模板') - if source.parsing_profile is None or source.parsing_profile.status != 'published': + # s18 起解析方案绑定归 onhand_report_config 配置行;配置行缺失即未绑定。 + report_config = source.onhand_report_config + profile = report_config.parsing_profile if report_config is not None else None + if profile is None or profile.status != 'published': raise ValueError('库存源未绑定已发布的库存解析模板') definition = template.definition_json or {} mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else [] @@ -784,7 +793,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]: raise ValueError('任务没有可用于导出的冻结订单快照') from app.services.shipping_notice.effective_order_view import effective_order_field_values header_values, all_line_values = effective_order_field_values(task) - profile_definition = source.parsing_profile.definition_json if isinstance(source.parsing_profile.definition_json, dict) else {} + profile_definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} match_keys = profile_definition.get('match_keys') if isinstance(profile_definition.get('match_keys'), list) else [] line_inventory_fields = _inventory_fields_by_mode(mappings, 'line') header_inventory_fields = _inventory_fields_by_mode(mappings, 'header') @@ -801,7 +810,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]: .filter( ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id), ShippingOrderReviewLineDecision.is_active.is_(True), - ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage', + ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage', ) .all() ) @@ -861,7 +870,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]: row['__order_line_index'] = source_index row['__snapshot_line_id'] = int(line.id) line_values.append(row) - from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution + from app.services.shipping_notice.onhand_file_store import resolve_inventory_lines_for_execution # [STEP 3] 活动库存 Link 为事实源;先按本单 match_keys(通常 reservation+part) # 裁成候选子集,再做模板字段匹配——禁止上万行全量快照进入逐行匹配。 @@ -874,7 +883,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]: } catalog = { str(item.id): str(item.id) - for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(match_field_ids)).all() + for item in FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(match_field_ids)).all() } if match_field_ids else {} order_field_ids: list[str] = [] inventory_field_keys: list[str] = [] @@ -958,6 +967,8 @@ def generate_shipment_excel( assert_notice_has_no_export_artifact(task) inputs = prepare_export_match_inputs(task) source = inputs['source'] + # s18 起解析方案绑定归 onhand_report_config 配置行;Artifact 审计外键同样取自配置行。 + report_config = source.onhand_report_config template = inputs['template'] snapshot = inputs['snapshot'] mappings = inputs['mappings'] @@ -1090,7 +1101,8 @@ def generate_shipment_excel( artifact_no=artifact_no, task_id=task.id, template_id=template.id, order_schema_version_id=snapshot.schema_version_id, order_extraction_id=snapshot.extraction_id, - inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=_notice_inventory_file_id(task), + inventory_parsing_profile_id=report_config.parsing_profile_id if report_config is not None else None, + inventory_snapshot_id=_notice_inventory_file_id(task), input_checksum=_input_checksum( task, source, template, snapshot, header_values, line_values, inventory_lines, notice_id=int(task.id), diff --git a/backend/app/services/shipping_notice/field_alignment_summary.py b/backend/app/services/shipping_notice/field_alignment_summary.py index 53fba6ce..4ae09739 100644 --- a/backend/app/services/shipping_notice/field_alignment_summary.py +++ b/backend/app/services/shipping_notice/field_alignment_summary.py @@ -3,7 +3,7 @@ services/shipping_notice/field_alignment_summary.py 用途:把库存字段对齐结果格式化成适合聊天区和人工确认的摘要文本。 依赖:shipping_notice.i18n、多语言文案与字段对齐 payload。 -逻辑:由 inventory_mapping_workflow 或前端映射确认链路调用本文件,生成给用户确认映射的说明文本。 +逻辑:由 onhand_mapping_workflow 或前端映射确认链路调用本文件,生成给用户确认映射的说明文本。 """ from __future__ import annotations diff --git a/backend/app/services/shipping_notice/field_impact_analysis.py b/backend/app/services/shipping_notice/field_impact_analysis.py index 3e74806c..d0cf2bac 100644 --- a/backend/app/services/shipping_notice/field_impact_analysis.py +++ b/backend/app/services/shipping_notice/field_impact_analysis.py @@ -15,9 +15,9 @@ from typing import Any from app.extensions import db from app.models import ( ShippingExcelTemplate, - ShippingInventoryParsingProfile, - ShippingInventoryRoutingRule, - ShippingInventoryRoutingRuleCondition, + FreightRpaParsingProfile, + FreightRpaOnhandRoutingRule, + FreightRpaOnhandRoutingRuleCondition, ShippingOrderDocumentProfile, ShippingOrderField, ShippingOrderFieldDecision, @@ -93,11 +93,11 @@ def list_field_runtime_references(field_id: str) -> list[dict[str, Any]]: # [STEP 1] 库存路由条件 routing_rows = ( - db.session.query(ShippingInventoryRoutingRuleCondition, ShippingInventoryRoutingRule) - .join(ShippingInventoryRoutingRule) + db.session.query(FreightRpaOnhandRoutingRuleCondition, FreightRpaOnhandRoutingRule) + .join(FreightRpaOnhandRoutingRule) .filter( - ShippingInventoryRoutingRuleCondition.order_field_id == field_id, - ShippingInventoryRoutingRule.status.in_(['draft', 'published']), + FreightRpaOnhandRoutingRuleCondition.order_field_id == field_id, + FreightRpaOnhandRoutingRule.status.in_(['draft', 'published']), ) .all() ) @@ -114,8 +114,8 @@ def list_field_runtime_references(field_id: str) -> list[dict[str, Any]]: )) # [STEP 2] 库存解析档案 match_keys - for profile in ShippingInventoryParsingProfile.query.filter( - ShippingInventoryParsingProfile.status.in_(['draft', 'published']), + for profile in FreightRpaParsingProfile.query.filter( + FreightRpaParsingProfile.status.in_(['draft', 'published']), ).all(): for index, item in enumerate((profile.definition_json or {}).get('match_keys', []) or []): if not isinstance(item, dict): @@ -123,7 +123,7 @@ def list_field_runtime_references(field_id: str) -> list[dict[str, Any]]: if str(item.get('order_field_id') or '') != field_id: continue references.append(_ref( - kind='inventory_parsing_profile', + kind='onhand_parsing_profile', object_id=profile.id, display_name=profile.display_name or profile.profile_code, status=profile.status, diff --git a/backend/app/services/shipping_notice/fulfillment_workflow.py b/backend/app/services/shipping_notice/fulfillment_workflow.py index 423469da..50c7a3ea 100644 --- a/backend/app/services/shipping_notice/fulfillment_workflow.py +++ b/backend/app/services/shipping_notice/fulfillment_workflow.py @@ -2,8 +2,8 @@ services/shipping_notice/fulfillment_workflow.py 用途:发货通知履约阶段 — 库存匹配、Excel 导出、货代上传(RPA/人工)与下游衔接入口。 -依赖:customer_identity_gate、reservation_gate、match、export、query_service、inventory_workflow、 - inventory_mapping_workflow、stp_line_inventory_match、upload_attempt_service、rpa.write_upload_trigger、 +依赖:customer_identity_gate、reservation_gate、match、export、query_service、onhand_workflow、 + onhand_mapping_workflow、stp_line_onhand_match、upload_attempt_service、freight_rpa.upload.trigger_io、 tool_common、tool_response、fulfillment_audit、task_workflow(Excel 就绪清失效)、 order_task_stage_machine。 逻辑:tools.py 门面 re-export;匹配成功后 Gate 路径禁止 try_auto_chain 内嵌 generate/upload, @@ -29,14 +29,14 @@ from flask import current_app from app import db from app.core.errors import ConflictError, ServiceUnavailableError, ValidationError -from app.models import ShippingNotice, ShippingNoticeLineInventoryMatch, ShippingOrderTask +from app.models import ShippingNotice, ShippingNoticeLineOnhandMatch, ShippingOrderTask from app.services.shipping_notice.constants import POSITION_UPLOADED from app.services.shipping_notice.export import generate_shipment_excel, order_field_id_values -from app.services.shipping_notice.inventory_file_store import ( +from app.services.shipping_notice.onhand_file_store import ( active_inventory_file_for_task, resolve_inventory_lines_for_execution, ) -from app.services.shipping_notice.inventory_workflow import ( +from app.services.shipping_notice.onhand_workflow import ( ensure_inventory, parse_inventory_lines, ) @@ -65,15 +65,15 @@ from app.services.shipping_notice.upload_attempt_service import ( record_manual_upload, start_rpa_attempt, ) -from app.services.shipping_notice.rpa import write_upload_trigger -from app.services.shipping_notice.rpa_attempts import ( +from app.services.freight_rpa.onhand.attempts import ( max_rpa_upload_attempts, upload_rpa_attempts, ) -from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source -from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source +from app.services.freight_rpa.upload.trigger_io import write_upload_trigger +from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source +from app.services.shipping_notice.onhand_source_repository import get_rpa_trigger_inventory_source from app.services.shipping_notice.upload_config_validation import compute_upload_config_hash -from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable +from app.services.shipping_notice.onhand_source_gate import assert_inventory_source_gate, is_inventory_source_stable from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition from app.services.shipping_notice.tool_common import log_task_event, prepend_tool_message, set_task_step_progress @@ -83,9 +83,9 @@ from app.services.shipping_notice.task_disposition_service import task_execution def _single_candidate_source_code(task: ShippingNotice) -> str | None: """返回当前 CandidateSet 的唯一源;多源由行级匹配事实决定,不能伪造任务级源。""" - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes - source_codes = task_frozen_inventory_source_codes(task) + source_codes = task_frozen_onhand_source_codes(task) return source_codes[0] if len(source_codes) == 1 else None @@ -465,7 +465,7 @@ def _trigger_freight_upload_rpa( # [STEP] 自动上传前强制系统级就绪:Worker / 凭据 / 共享目录 / 环境隔离 / 回调基址。 try: - from app.services.shipping_notice.rpa_worker_heartbeat import assert_freight_upload_rpa_ready + from app.services.freight_rpa.common.worker_heartbeat import assert_freight_upload_rpa_ready assert_freight_upload_rpa_ready() except ServiceUnavailableError as exc: @@ -684,15 +684,33 @@ def _sync_workflow_stage( ) +def _facts_order_task(task: ShippingNotice) -> ShippingOrderTask | None: + """返回匹配/放行/结案事实归属的 OT:正式 Notice 经 order_task_id 回链,OT 原样返回。 + + 核心逻辑:行级匹配事实与复核 Case 的 confirmed_task_id 都按 OT 主键落库; + Excel 生成链物化正式 Notice 后会以 Notice 对象复评满足性门禁,读取端必须统一 + 回链 OT,否则已放行/已满足事实不可见(回归 2026-10-17 OT-20261017-364C7BF2: + 已自动放行的短缺单在 Excel 生成时被误判「尚未完成库存匹配」)。 + """ + if task is None or getattr(task, 'id', None) is None: + return None + linked_id = getattr(task, 'order_task_id', None) + if linked_id is None: + return task if isinstance(task, ShippingOrderTask) else None + return db.session.get(ShippingOrderTask, int(linked_id)) + + def _released_snapshot_line_ids_for_task(task: ShippingNotice) -> set[int]: """读取当前任务已审计的短缺放行冻结行 ID,供满足性与聚合重算共用。 - 核心逻辑:只认活动 ``release_inventory_shortage`` 决定;无放行事实时返回空集, + 核心逻辑:只认活动 ``release_onhand_shortage`` 决定;无放行事实时返回空集, 保证聚合重算与 ``match_completed`` 读到的放行语义完全一致,避免两处分裂。 + 读取身份经 :func:`_facts_order_task` 回链 OT,OT/Notice 两态结果一致。 """ from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision - if task.id is None: + task = _facts_order_task(task) + if task is None: return set() if not getattr(task, 'order_snapshot_id', None): return set() @@ -702,7 +720,7 @@ def _released_snapshot_line_ids_for_task(task: ShippingNotice) -> set[int]: .filter( ShippingOrderReviewCase.confirmed_task_id == int(task.id), ShippingOrderReviewLineDecision.is_active.is_(True), - ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage', + ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage', ) .all() ) @@ -723,10 +741,12 @@ def _closed_snapshot_line_ids_for_task(task: ShippingNotice) -> set[int]: 核心逻辑:与 ``_released_snapshot_line_ids_for_task`` 同源同口径——只认活动决定, 经 line_index 映射快照行;结案行不再是履约要求,在满足性/建单/导出各处按豁免处理。 + 读取身份同样经 :func:`_facts_order_task` 回链 OT。 """ from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision - if task.id is None: + task = _facts_order_task(task) + if task is None: return set() if not getattr(task, 'order_snapshot_id', None): return set() @@ -759,12 +779,14 @@ def match_completed(task: ShippingNotice) -> bool: 核心逻辑:该函数只代表整单满足性,不代表滚动 Excel 是否存在可导出行。 已人工放行的短缺行视同满足;已结案(close_unfulfillable)行不再是履约要求, 从覆盖校验与逐行判定中双重豁免;全部行结案时无剩余履约内容,按不通过处理。 + 事实读取身份经 :func:`_facts_order_task` 回链 OT,OT/Notice 两态结果一致。 """ - from app.models import ShippingNoticeLineInventoryMatch + from app.models import ShippingNoticeLineOnhandMatch - if task.id is None: + task = _facts_order_task(task) + if task is None: return False - rows = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all() + rows = ShippingNoticeLineOnhandMatch.query.filter_by(task_id=int(task.id), is_current=True).all() if not rows: return False from app.models import ShippingOrderSnapshot @@ -802,14 +824,15 @@ def match_completed(task: ShippingNotice) -> bool: def inventory_match_facts_complete(task: ShippingNotice) -> bool: """判断当前行级匹配是否覆盖冻结订单全部项次且不再处于准备中。""" - from app.models import ShippingNoticeLineInventoryMatch, ShippingOrderSnapshot + from app.models import ShippingNoticeLineOnhandMatch, ShippingOrderSnapshot - if task.id is None or not getattr(task, 'order_snapshot_id', None): + task = _facts_order_task(task) + if task is None or not getattr(task, 'order_snapshot_id', None): return False snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id)) if snapshot is None or not snapshot.lines: return False - rows = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all() + rows = ShippingNoticeLineOnhandMatch.query.filter_by(task_id=int(task.id), is_current=True).all() by_line_id = { int(row.snapshot_line_id): row for row in rows @@ -822,24 +845,29 @@ def inventory_match_facts_complete(task: ShippingNotice) -> bool: def _released_snapshot_line_ids_for_export(task: ShippingNotice) -> set[int]: - """读取当前任务已审计的短缺放行行,供滚动 Excel 资格筛选使用。""" + """读取当前任务已审计的短缺放行行,供滚动 Excel 资格筛选使用。 + + 核心逻辑:决定 join 必须用 OT 主键(owner.id)——复核 Case 的 confirmed_task_id + 按 OT 落库,而 source_notice 在 Notice 物化后是 Notice 对象,用它 join 会永远 + 读不到放行(回归 2026-10-17 OT-20261017-364C7BF2);快照同样取自 owner。 + """ from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision, ShippingOrderSnapshot from app.services.shipping_notice.export import _source_notice_for_order_facts source_notice = _source_notice_for_order_facts(task) from app.models import ShippingOrderTask owner = db.session.get(ShippingOrderTask, source_notice.order_task_id) if getattr(source_notice, 'order_task_id', None) else source_notice - snapshot_id = getattr(owner, 'order_snapshot_id', None) + snapshot_id = getattr(owner, 'order_snapshot_id', None) if owner is not None else None snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None - if snapshot is None or source_notice.id is None: + if snapshot is None or owner is None or getattr(owner, 'id', None) is None: return set() decisions = ( ShippingOrderReviewLineDecision.query .join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id) .filter( - ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id), + ShippingOrderReviewCase.confirmed_task_id == int(owner.id), ShippingOrderReviewLineDecision.is_active.is_(True), - ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage', + ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage', ) .all() ) @@ -916,14 +944,16 @@ def excel_gate_error(task: ShippingNotice) -> str | None: """校验 generate_excel 前置条件;不满足时返回中文错误提示,满足时返回 None。""" # 库存准备失败是硬门禁:即使任务上残留旧的 match/export 投影,也不得继续生成 # 发货 Excel。恢复只能由显式库存准备重试或人工上传重新建立成功事实。 - from app.models import ShippingInventoryPreparationAttempt + # 准备轮次按 OT 主键落库;Notice 身份进入本门禁时须回链 OT,防止漏检硬失败。 + from app.models import ShippingOnhandPreparationAttempt + facts_task = _facts_order_task(task) latest_preparation = ( - ShippingInventoryPreparationAttempt.query - .filter_by(task_id=int(task.id)) - .order_by(ShippingInventoryPreparationAttempt.attempt_no.desc()) + ShippingOnhandPreparationAttempt.query + .filter_by(task_id=int(facts_task.id)) + .order_by(ShippingOnhandPreparationAttempt.attempt_no.desc()) .first() - ) + ) if facts_task is not None else None if latest_preparation is not None and str(latest_preparation.status or '').strip().lower() == 'failed': return 'workflow.fulfillment.inventory_preparation_failed' if _upload_status(task) == 'uploaded' and _export_file_path(task): @@ -1060,7 +1090,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str, task_no, trigger=trigger, expected_version=None, idempotency_key=str(payload.get('idempotency_key') or '').strip() or None, - resume_gate_code='inventory_matching', + resume_gate_code='onhand_matching', operator_id=operator_id, line_scope_key=str(line_no) if line_no is not None else None, ) @@ -1076,7 +1106,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str, if not task: return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang)) # 正式候选冻结任务必须绑定当前 frozen CandidateSet;缺失时禁止回退旧单源/JSON 路径。 - from app.services.shipping_notice.inventory_candidate_projection import ( + from app.services.shipping_notice.onhand_candidate_projection import ( build_inventory_candidate_blocking_reason, build_inventory_candidate_primary_action, get_active_candidate_set, @@ -1150,7 +1180,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str, if str(code).strip() ] if not scoped_codes: - from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines + from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_lines candidate_line = next( ( line for line in get_active_candidate_lines(task) @@ -1181,11 +1211,11 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str, position="inventory_source_review", stop_agent_turn=True, ) - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes - from app.services.shipping_notice.stp_line_inventory_match import ( + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes + from app.services.shipping_notice.stp_line_onhand_match import ( attach_candidate_scope_to_order_lines, apply_forced_match_source_filter, - apply_line_inventory_resolutions, + apply_line_onhand_resolutions, match_order_lines_across_candidates, snapshot_header_reservation_id, ) @@ -1229,7 +1259,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str, _sync_workflow_stage( task, - lifecycle_status='inventory_matching', + lifecycle_status='onhand_matching', event_code='inventory_match_line_started', actor_id=actor_id, payload={'task_no': task.task_no, 'line_no': target_line_no, 'line_index': orig_idx}, @@ -1266,7 +1296,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str, if isinstance(res, dict): res['line_no'] = target_line_no # [STEP 4] 持久化仅本行(其他行 is_current 保持不变) - from app.services.shipping_notice.line_inventory_match_persistence import ( + from app.services.shipping_notice.line_onhand_match_persistence import ( persist_line_inventory_match_facts, ) persist_line_inventory_match_facts( @@ -1299,7 +1329,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str, line_result_status = str(match_payload.get('match_status') or 'unfulfillable') set_task_step_progress( task, - stage="inventory_matching", + stage="onhand_matching", step_title="匹配库存", status="running", message=t("workflow.fulfillment.match_running", lang=lang), @@ -1391,14 +1421,14 @@ def _merge_line_inventory_resolutions( def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dict[str, Any]]]: """根据当前 LineMatch 重新计算门禁结果(fulfillable/partial/unfulfillable)与缺口。 - 核心逻辑:与 ``match_completed`` 同款放行语义——已人工放行(release_inventory_shortage) + 核心逻辑:与 ``match_completed`` 同款放行语义——已人工放行(release_onhand_shortage) 且仍有缺口的行视同满足,不再计入 has_block/缺货;否则会与 Excel 门禁分裂, 出现"Gate 认为满足、任务却仍标 unfulfillable"的矛盾。 已结案(close_unfulfillable)行不再是履约要求:不阻断、不进缺货列表, 但也不计入满足(结案行非可履约内容),全结案 ⇒ unfulfillable,与 match_completed 口径一致。 """ rows = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=int(task.id), is_current=True) .all() ) @@ -1423,7 +1453,7 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic 'part_number': getattr(row, 'part_number', None), 'reservation_id': getattr(row, 'reservation_id', None), 'unit': getattr(row, 'unit', None), - 'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None), + 'resolved_inventory_source_code': getattr(row, 'source_code', None), 'required_qty': float(required_qty) if required_qty is not None else 0.0, 'available_qty': float(available_qty) if available_qty is not None else 0.0, 'shortage_qty': float(shortage_qty) if shortage_qty is not None else 0.0, @@ -1474,9 +1504,9 @@ def _current_line_results(task: ShippingNotice) -> list[dict[str, Any]]: """返回当前行级 Match 聚合结果;OT 不回读 step_payload_json 缓存。""" if task.__class__.__name__ == 'ShippingOrderTask': rows = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=int(task.id), is_current=True) - .order_by(ShippingNoticeLineInventoryMatch.line_no.asc()) + .order_by(ShippingNoticeLineOnhandMatch.line_no.asc()) .all() ) return [ @@ -1486,21 +1516,21 @@ def _current_line_results(task: ShippingNotice) -> list[dict[str, Any]]: 'snapshot_line_id': getattr(row, 'snapshot_line_id', None), 'disposition': getattr(row, 'match_result', None), 'match_result': getattr(row, 'match_result', None), - 'inventory_status': getattr(row, 'inventory_status', None), + 'inventory_status': getattr(row, 'onhand_status', None), 'part_number': getattr(row, 'part_number', None), 'reservation_id': getattr(row, 'reservation_id', None), 'required_qty': getattr(row, 'required_qty', None), 'available_qty': getattr(row, 'available_qty', None), 'shortage_qty': getattr(row, 'shortage_qty', None), - 'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None), + 'resolved_inventory_source_code': getattr(row, 'source_code', None), 'candidate_source_codes': list(getattr(row, 'allowed_source_codes_snapshot', None) or []), } for row in rows ] rows = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=int(task.id), is_current=True) - .order_by(ShippingNoticeLineInventoryMatch.line_no.asc()) + .order_by(ShippingNoticeLineOnhandMatch.line_no.asc()) .all() ) return [ @@ -1510,13 +1540,13 @@ def _current_line_results(task: ShippingNotice) -> list[dict[str, Any]]: 'snapshot_line_id': getattr(row, 'snapshot_line_id', None), 'disposition': getattr(row, 'match_result', None), 'match_result': getattr(row, 'match_result', None), - 'inventory_status': getattr(row, 'inventory_status', None), + 'inventory_status': getattr(row, 'onhand_status', None), 'part_number': getattr(row, 'part_number', None), 'reservation_id': getattr(row, 'reservation_id', None), 'required_qty': getattr(row, 'required_qty', None), 'available_qty': getattr(row, 'available_qty', None), 'shortage_qty': getattr(row, 'shortage_qty', None), - 'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None), + 'resolved_inventory_source_code': getattr(row, 'source_code', None), } for row in rows ] @@ -1618,7 +1648,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: task_no, trigger=trigger, expected_version=None, idempotency_key=str(payload.get('idempotency_key') or '').strip() or None, - resume_gate_code='inventory_matching', + resume_gate_code='onhand_matching', operator_id=operator_id, ) lang = resolve_lang(payload) @@ -1698,14 +1728,14 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: total_notice_lines = len(order_field_lines) _sync_workflow_stage( task, - lifecycle_status='inventory_matching', + lifecycle_status='onhand_matching', event_code='inventory_match_started', actor_id=actor_id, payload={'task_no': task.task_no}, ) set_task_step_progress( task, - stage="inventory_matching", + stage="onhand_matching", step_title="匹配库存", status="running", message=t("workflow.fulfillment.match_running", lang=lang), @@ -1726,11 +1756,11 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: stop_agent_turn=True, ) - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes - from app.services.shipping_notice.stp_line_inventory_match import ( + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes + from app.services.shipping_notice.stp_line_onhand_match import ( attach_candidate_scope_to_order_lines, apply_forced_match_source_filter, - apply_line_inventory_resolutions, + apply_line_onhand_resolutions, match_order_lines_across_candidates, snapshot_header_reservation_id, ) @@ -1739,7 +1769,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: # 人工指定源后仅保留 forced_match_source_code 对应库存行,消解多源/多文件冲突。 inventory_lines = apply_forced_match_source_filter(inventory_lines or [], task=task) use_stp_cross_match = ( - len(task_frozen_inventory_source_codes(task)) >= 1 + len(task_frozen_onhand_source_codes(task)) >= 1 or any(isinstance(row, dict) and row.get('__source_code') for row in (inventory_lines or [])) ) if use_stp_cross_match: @@ -1775,9 +1805,9 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: inventory_lines=inventory_lines or [], header_reservation_id=header_reservation, ) - apply_line_inventory_resolutions(task, match_payload) + apply_line_onhand_resolutions(task, match_payload) # [STEP] Slice 1:持久化 OT 行匹配事实(ready+not_found=0;缺键→invalid_key) - from app.services.shipping_notice.line_inventory_match_persistence import ( + from app.services.shipping_notice.line_onhand_match_persistence import ( persist_line_inventory_match_facts, ) persist_line_inventory_match_facts( @@ -1808,7 +1838,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: ) set_task_step_progress( task, - stage="inventory_matching", + stage="onhand_matching", step_title="匹配库存", **_match_step_progress_fields( match_status=match_status, @@ -1887,7 +1917,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: percent = 10 if total <= 0 else min(95, max(10, int(processed * 100 / total))) set_task_step_progress( task, - stage="inventory_matching", + stage="onhand_matching", step_title="匹配库存", status="running", message=t("workflow.fulfillment.match_running", lang=lang), @@ -1899,20 +1929,23 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: if processed == total or processed % 50 == 0: db.session.flush() - from app.models import ShippingInventoryField, ShippingInventorySource + from app.models import FreightRpaOnhandField, FreightRpaSource source_code = _single_candidate_source_code(task) - source = ShippingInventorySource.query.filter_by(source_code=source_code).first() - definition = source.parsing_profile.definition_json if source and source.parsing_profile else {} + source = FreightRpaSource.query.filter_by(source_code=source_code).first() + # s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系。 + config = source.onhand_report_config if source is not None else None + profile = config.parsing_profile if config is not None else None + definition = profile.definition_json if profile is not None else {} match_keys = definition.get('match_keys') if isinstance(definition, dict) else [] mapped_field_ids = [ int(field_id) for field_id in (definition.get('field_mapping') or {}) if str(field_id).isdigit() ] if isinstance(definition, dict) else [] - quantity_fields = ShippingInventoryField.query.filter( - ShippingInventoryField.id.in_(mapped_field_ids), - ShippingInventoryField.status == 'active', - ShippingInventoryField.usage_type == 'inventory_quantity', + quantity_fields = FreightRpaOnhandField.query.filter( + FreightRpaOnhandField.id.in_(mapped_field_ids), + FreightRpaOnhandField.status == 'active', + FreightRpaOnhandField.usage_type == 'inventory_quantity', ).all() if mapped_field_ids else [] if len(quantity_fields) != 1: raise ValueError('库存解析方案必须且只能配置一个库存数量字段') @@ -1925,7 +1958,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: ) # 整单匹配与行级匹配必须写入同一结构化事实表;Review Projection 只读取该表。 # 仅更新 line_results_json 会导致订单明细继续显示“待确认”。 - from app.services.shipping_notice.line_inventory_match_persistence import ( + from app.services.shipping_notice.line_onhand_match_persistence import ( persist_line_inventory_match_facts, ) persist_line_inventory_match_facts( @@ -1944,7 +1977,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: ) set_task_step_progress( task, - stage="inventory_matching", + stage="onhand_matching", step_title="匹配库存", **_match_step_progress_fields( match_status=match_status, diff --git a/backend/app/services/shipping_notice/i18n.py b/backend/app/services/shipping_notice/i18n.py index 85cd4c17..be190663 100644 --- a/backend/app/services/shipping_notice/i18n.py +++ b/backend/app/services/shipping_notice/i18n.py @@ -82,7 +82,7 @@ _MESSAGES: dict[str, dict[str, str]] = { "workflow.decision.shortage_confirm_blocked": "库存不足,无法使用 confirm 整单确认。请 reparse_inventory、rematch 或 reject。", "workflow.decision.parse_confirmed_next": "发货通知已确认。请继续在当前任务中补充库存或等待后端继续处理,并稍后刷新任务状态。", "workflow.decision.parse_confirmed_wait": "等待后台继续处理或稍后刷新任务状态", - "workflow.decision.parse_confirmed_manual_next": "ensure_inventory 或 parse_inventory", + "workflow.decision.parse_confirmed_manual_next": "ensure_onhand 或 parse_inventory", "workflow.decision.matched_confirmed": "已确认,可继续生成 Excel 并上传货代系统。", "workflow.decision.confirm_invalid_state": "当前状态无法使用确认。请先完成库存匹配,或选择重新解析订单。", "workflow.decision.inventory_cleared": "已清除库存快照。请重新上传或粘贴库存,后续继续在当前任务中处理。", @@ -208,7 +208,7 @@ _MESSAGES: dict[str, dict[str, str]] = { "workflow.decision.shortage_confirm_blocked": "Inventory is insufficient. You cannot use confirm for the whole task. Please use reparse_inventory, rematch, or reject.", "workflow.decision.parse_confirmed_next": "The shipping notice is confirmed. Please continue with inventory for the current task or wait for the backend to continue, then refresh the task status later.", "workflow.decision.parse_confirmed_wait": "Wait for backend processing or refresh the task status later.", - "workflow.decision.parse_confirmed_manual_next": "ensure_inventory or parse_inventory", + "workflow.decision.parse_confirmed_manual_next": "ensure_onhand or parse_inventory", "workflow.decision.matched_confirmed": "Confirmed. You may continue to generate the Excel and upload to the freight system.", "workflow.decision.confirm_invalid_state": "Confirm cannot be used in the current state. Complete inventory matching first, or reparse the order.", "workflow.decision.inventory_cleared": "The inventory snapshot has been cleared. Please re-upload or paste inventory data, then continue in the current task.", @@ -334,7 +334,7 @@ _MESSAGES: dict[str, dict[str, str]] = { "workflow.decision.shortage_confirm_blocked": "สต็อกไม่เพียงพอ จึงไม่สามารถใช้ confirm เพื่อยืนยันทั้งงานได้ โปรดใช้ reparse_inventory, rematch หรือ reject", "workflow.decision.parse_confirmed_next": "ยืนยันใบแจ้งส่งสินค้าแล้ว โปรดดำเนินการเรื่องสต็อกในงานปัจจุบันต่อ หรือรอให้ระบบหลังบ้านทำต่อ แล้วค่อยรีเฟรชสถานะงาน", "workflow.decision.parse_confirmed_wait": "รอให้ระบบหลังบ้านดำเนินการต่อ หรือกลับมาตรวจสอบสถานะงานภายหลัง", - "workflow.decision.parse_confirmed_manual_next": "ensure_inventory หรือ parse_inventory", + "workflow.decision.parse_confirmed_manual_next": "ensure_onhand หรือ parse_inventory", "workflow.decision.matched_confirmed": "ยืนยันแล้ว สามารถดำเนินการสร้างไฟล์ Excel และอัปโหลดไปยังระบบขนส่งต่อได้", "workflow.decision.confirm_invalid_state": "ไม่สามารถยืนยันในสถานะปัจจุบันได้ โปรดจับคู่สต็อกให้เสร็จก่อน หรือแยกวิเคราะห์คำสั่งซื้อใหม่", "workflow.decision.inventory_cleared": "ล้าง snapshot สต็อกแล้ว โปรดอัปโหลดใหม่หรือวางข้อมูลสต็อก แล้วดำเนินการต่อในงานปัจจุบัน", diff --git a/backend/app/services/shipping_notice/lifecycle_projection.py b/backend/app/services/shipping_notice/lifecycle_projection.py index 08377db7..1f933f58 100644 --- a/backend/app/services/shipping_notice/lifecycle_projection.py +++ b/backend/app/services/shipping_notice/lifecycle_projection.py @@ -42,11 +42,11 @@ LIFECYCLE_STAGE_BY_GATE: dict[str, str] = { # 用户在复核并决定标记非订单/修订草稿之前,订单尚未正式创建。 'order_review_build': 'order_review', 'task_creation': 'order_review', - 'inventory_source_routing': 'fulfillment_prep', - 'inventory_preparation': 'fulfillment_prep', - 'inventory_field_mapping': 'fulfillment_prep', - 'inventory_matching': 'fulfillment_prep', - 'inventory_sufficiency': 'fulfillment_prep', + 'onhand_source_routing': 'fulfillment_prep', + 'onhand_preparation': 'fulfillment_prep', + 'onhand_field_mapping': 'fulfillment_prep', + 'onhand_matching': 'fulfillment_prep', + 'onhand_sufficiency': 'fulfillment_prep', 'excel_readiness': 'fulfillment_prep', 'artifact_generation': 'fulfillment_prep', 'freight_upload_rpa': 'freight_upload', @@ -65,12 +65,12 @@ LIFECYCLE_STAGE_BY_PROCESSING_STAGE: dict[str, str] = { 'waiting_review': 'order_review', 'customer_resolving': 'order_review', 'duplicate_checking': 'order_review', - 'inventory_source_resolving': 'fulfillment_prep', + 'onhand_source_resolving': 'fulfillment_prep', 'order_creating': 'fulfillment_prep', - 'inventory_fetching': 'fulfillment_prep', - 'inventory_preparation': 'fulfillment_prep', - 'inventory_matching': 'fulfillment_prep', - 'inventory_sufficiency': 'fulfillment_prep', + 'onhand_fetching': 'fulfillment_prep', + 'onhand_preparation': 'fulfillment_prep', + 'onhand_matching': 'fulfillment_prep', + 'onhand_sufficiency': 'fulfillment_prep', 'excel_generating': 'fulfillment_prep', 'freight_uploading': 'freight_upload', 'manual_upload_handoff': 'freight_upload', diff --git a/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py b/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py index be7ff00b..75fc97c8 100644 --- a/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py +++ b/backend/app/services/shipping_notice/line_auto_fulfill_coordinator.py @@ -3,9 +3,9 @@ services/shipping_notice/line_auto_fulfill_coordinator.py 用途:OT 后行级自动履约幂等协调器——统一 matching ready / OT 回调 / 补偿入口。 依赖:line_auto_fulfill_enabled、post_ot_fulfillment_wave_service、post_ot_wave_progress_service、 - ShippingNoticeLineInventoryMatch / LineDecision snapshot。 + ShippingNoticeLineOnhandMatch / LineDecision snapshot。 逻辑:flag 关闭时 skipped;开启时整波创建+专用推进;失败整波回滚后独立写 auto_fulfill_failed 列; - 不创建 wait_inventory 半成品决定;trigger=ot_created|compensation 由确认/STP/补偿排程接线。 + 不创建 wait_onhand 半成品决定;trigger=ot_created|compensation 由确认/STP/补偿排程接线。 """ from __future__ import annotations @@ -16,12 +16,12 @@ from typing import Any from app import db from app.models import ( ShippingNotice, - ShippingNoticeLineInventoryMatch, + ShippingNoticeLineOnhandMatch, ShippingOrderReviewCase, ShippingOrderReviewLineDecision, ) -from app.services.shipping_notice.line_inventory_match_persistence import resolve_review_case_for_task -from app.services.shipping_notice.line_inventory_match_projection import line_auto_fulfill_enabled +from app.services.shipping_notice.line_onhand_match_persistence import resolve_review_case_for_task +from app.services.shipping_notice.line_onhand_match_projection import line_auto_fulfill_enabled from app.services.shipping_notice.post_ot_fulfillment_wave_service import ( create_post_ot_fulfillment_wave, list_eligible_post_ot_snapshot_line_ids, @@ -40,9 +40,9 @@ def _mark_auto_fulfill_failed( message: str, ) -> None: """ - 独立事务内写入失败事实:匹配事实表列优先;活动决定仅补 snapshot,不新建 wait_inventory。 + 独立事务内写入失败事实:匹配事实表列优先;活动决定仅补 snapshot,不新建 wait_onhand。 - 核心逻辑:写 ShippingNoticeLineInventoryMatch.auto_fulfill_failed* 列;可选同步 snapshot。 + 核心逻辑:写 ShippingNoticeLineOnhandMatch.auto_fulfill_failed* 列;可选同步 snapshot。 """ now = datetime.utcnow() formal_task_id = getattr(case, 'confirmed_task_id', None) @@ -56,7 +56,7 @@ def _mark_auto_fulfill_failed( key_s = str(key) if formal_task_id is not None: fact = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=int(formal_task_id), snapshot_line_id=int(key_s), is_current=True) .first() ) diff --git a/backend/app/services/shipping_notice/line_inventory_match_persistence.py b/backend/app/services/shipping_notice/line_onhand_match_persistence.py similarity index 87% rename from backend/app/services/shipping_notice/line_inventory_match_persistence.py rename to backend/app/services/shipping_notice/line_onhand_match_persistence.py index 2ef9fc87..6b11cf2b 100644 --- a/backend/app/services/shipping_notice/line_inventory_match_persistence.py +++ b/backend/app/services/shipping_notice/line_onhand_match_persistence.py @@ -1,11 +1,11 @@ """ -services/shipping_notice/line_inventory_match_persistence.py +services/shipping_notice/line_onhand_match_persistence.py -用途:inventory_matching 完成后把逐行结果写入 OT 行库存匹配事实表(Slice 1)。 -依赖:ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、normalize 投影语义。 +用途:onhand_matching 完成后把逐行结果写入 OT 行库存匹配事实表(Slice 1)。 +依赖:ShippingNoticeLineOnhandMatch、ShippingOrderReviewCase、normalize 投影语义。 逻辑:由 fulfillment_workflow.match_inventory 调用;按冻结订单行 snapshot_line_id 落库; 新快照新增行并切换 is_current;不覆盖历史快照事实。 - 行级 inventory_snapshot_id 按匹配结果自带的 inventory_file_no 归因到「命中文件」; + 行级 onhand_snapshot_id 按匹配结果自带的 inventory_file_no 归因到「命中文件」; 仅行结果未回填文件号(如 not_found)时才回退任务级锚点快照——多源池下锚点文件 ≠命中文件,混用会导致 Excel 仓库列写成锚点仓(历史缺陷:AWSCV 单写成 CMH01)。 匹配器下发的料号兜底总量 part_available_qty(Task 1)随行事实字符串化落列, @@ -20,12 +20,12 @@ from typing import Any from app import db from app.models import ( - ShippingInventoryFile, + FreightRpaOnhandReportFile, ShippingNotice, - ShippingNoticeLineInventoryMatch, + ShippingNoticeLineOnhandMatch, ShippingOrderReviewCase, ) -from app.services.shipping_notice.inventory_candidate_projection import ( +from app.services.shipping_notice.onhand_candidate_projection import ( get_active_candidate_lines, get_active_candidate_set, ) @@ -87,9 +87,9 @@ def _line_resolved_source_code(task: ShippingNotice, result: dict[str, Any]) -> src = str(result.get('resolved_inventory_source_code') or '')[:64] or None if src: return src - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes - source_codes = task_frozen_inventory_source_codes(task) + source_codes = task_frozen_onhand_source_codes(task) if len(source_codes) == 1: return source_codes[0][:64] return None @@ -101,7 +101,7 @@ def persist_line_inventory_match_facts( match_payload: dict[str, Any], inventory_snapshot_id: int | None = None, matching_rule_version: str | None = 'stp_line_v2', -) -> list[ShippingNoticeLineInventoryMatch]: +) -> list[ShippingNoticeLineOnhandMatch]: """ 将 match_order_lines_across_candidates 结果持久化为当前事实。 @@ -111,14 +111,14 @@ def persist_line_inventory_match_facts( case = resolve_review_case_for_task(task) snap_id = inventory_snapshot_id if snap_id is None: - from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts + from app.services.shipping_notice.onhand_candidate_projection import active_inventory_runtime_facts snap_id = active_inventory_runtime_facts(task).get('inventory_file_id') # 任务级锚点快照仅作行结果缺文件号时的回退身份;命中文件归因在行循环内逐行解析。 snapshot_file_no = None if snap_id is not None: - snapshot = ShippingInventoryFile.query.get(int(snap_id)) - snapshot_file_no = str(getattr(snapshot, 'inventory_file_no', '') or '').strip() or None + snapshot = FreightRpaOnhandReportFile.query.get(int(snap_id)) + snapshot_file_no = str(getattr(snapshot, 'onhand_file_no', '') or '').strip() or None # 命中文件号 → 文件 ID 缓存;文件号查不到文件时缓存 None,本行回退锚点快照 # (命中证据仍以 matched_file_no 为准,不把锚点伪装成命中文件)。 file_id_by_no: dict[str, int | None] = {} @@ -135,7 +135,7 @@ def persist_line_inventory_match_facts( if item.get('line_index') is not None } - written: list[ShippingNoticeLineInventoryMatch] = [] + written: list[ShippingNoticeLineOnhandMatch] = [] now = datetime.utcnow() current_candidate_set = get_active_candidate_set(task) candidate_lines_by_no = { @@ -169,8 +169,8 @@ def persist_line_inventory_match_facts( if line_file_no is not None: if line_file_no not in file_id_by_no: hit_file = ( - ShippingInventoryFile.query - .filter_by(inventory_file_no=line_file_no) + FreightRpaOnhandReportFile.query + .filter_by(onhand_file_no=line_file_no) .first() ) file_id_by_no[line_file_no] = int(hit_file.id) if hit_file is not None else None @@ -221,32 +221,32 @@ def persist_line_inventory_match_facts( existing = None if line_snap_id is not None: existing = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by( task_id=int(task.id), snapshot_line_id=snapshot_line_id, line_no=line_no, - inventory_snapshot_id=int(line_snap_id), + onhand_snapshot_id=int(line_snap_id), ) .first() ) if existing is None and line_snap_id is None: existing = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=int(task.id), snapshot_line_id=snapshot_line_id, is_current=True) - .filter(ShippingNoticeLineInventoryMatch.inventory_snapshot_id.is_(None)) + .filter(ShippingNoticeLineOnhandMatch.onhand_snapshot_id.is_(None)) .first() ) if existing is None: ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=int(task.id), snapshot_line_id=snapshot_line_id, is_current=True) .update({'is_current': False, 'updated_at': now}, synchronize_session=False) ) # 同一订单行按稳定 line_index 关闭旧事实,避免多个 current 投影。 ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=int(task.id), line_index=index, is_current=True) .update({'is_current': False, 'updated_at': now}, synchronize_session=False) ) @@ -278,7 +278,7 @@ def persist_line_inventory_match_facts( 'snapshot_missing': line_snap_id is None, 'evidence_ref_plain': evidence_plain if evidence_ref else None, } - row = ShippingNoticeLineInventoryMatch( + row = ShippingNoticeLineOnhandMatch( task_id=int(task.id), review_case_id=int(case.id) if case is not None else None, snapshot_line_id=snapshot_line_id, @@ -295,9 +295,9 @@ def persist_line_inventory_match_facts( else None ), candidate_line_id=int(candidate_line.id) if candidate_line is not None else None, - inventory_snapshot_id=int(line_snap_id) if line_snap_id is not None else None, + onhand_snapshot_id=int(line_snap_id) if line_snap_id is not None else None, match_result=match_result, - inventory_status=inventory_status, + onhand_status=inventory_status, required_qty=str(required) if required is not None else None, available_qty=str(available) if available is not None else None, shortage_qty=str(shortage) if shortage is not None else None, @@ -311,7 +311,7 @@ def persist_line_inventory_match_facts( part_number=pn, unit=unit_value, matching_rule_version=str(matching_rule_version or '')[:64] or None, - inventory_source_code=src_code, + source_code=src_code, is_current=True, matched_at=now, # T6 行级证据 @@ -368,7 +368,7 @@ def persist_line_inventory_match_facts( 'evidence_ref_plain': evidence_plain if evidence_ref else None, } existing.match_result = match_result - existing.inventory_status = inventory_status + existing.onhand_status = inventory_status existing.required_qty = str(required) if required is not None else None existing.available_qty = str(available) if available is not None else None existing.shortage_qty = str(shortage) if shortage is not None else None @@ -381,7 +381,7 @@ def persist_line_inventory_match_facts( existing.part_number = pn existing.unit = unit_value existing.matching_rule_version = str(matching_rule_version or '')[:64] or None - existing.inventory_source_code = src_code + existing.source_code = src_code existing.is_current = True existing.invalidated_at = None existing.invalidated_by_attempt_id = None @@ -415,23 +415,23 @@ def persist_line_inventory_match_facts( existing.detail_json = detail_json # 确保同 task+line 仅本条 current ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter( - ShippingNoticeLineInventoryMatch.task_id == int(task.id), - ShippingNoticeLineInventoryMatch.snapshot_line_id == snapshot_line_id, - ShippingNoticeLineInventoryMatch.id != int(existing.id), - ShippingNoticeLineInventoryMatch.is_current.is_(True), + ShippingNoticeLineOnhandMatch.task_id == int(task.id), + ShippingNoticeLineOnhandMatch.snapshot_line_id == snapshot_line_id, + ShippingNoticeLineOnhandMatch.id != int(existing.id), + ShippingNoticeLineOnhandMatch.is_current.is_(True), ) .update({'is_current': False, 'updated_at': now}, synchronize_session=False) ) # 同一订单行更新时关闭旧事实,保证 current 投影唯一。 ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter( - ShippingNoticeLineInventoryMatch.task_id == int(task.id), - ShippingNoticeLineInventoryMatch.line_index == index, - ShippingNoticeLineInventoryMatch.id != int(existing.id), - ShippingNoticeLineInventoryMatch.is_current.is_(True), + ShippingNoticeLineOnhandMatch.task_id == int(task.id), + ShippingNoticeLineOnhandMatch.line_index == index, + ShippingNoticeLineOnhandMatch.id != int(existing.id), + ShippingNoticeLineOnhandMatch.is_current.is_(True), ) .update({'is_current': False, 'updated_at': now}, synchronize_session=False) ) diff --git a/backend/app/services/shipping_notice/line_inventory_match_projection.py b/backend/app/services/shipping_notice/line_onhand_match_projection.py similarity index 95% rename from backend/app/services/shipping_notice/line_inventory_match_projection.py rename to backend/app/services/shipping_notice/line_onhand_match_projection.py index 8a150b4b..9da98c9e 100644 --- a/backend/app/services/shipping_notice/line_inventory_match_projection.py +++ b/backend/app/services/shipping_notice/line_onhand_match_projection.py @@ -1,15 +1,15 @@ """ -services/shipping_notice/line_inventory_match_projection.py +services/shipping_notice/line_onhand_match_projection.py 用途:将 OT 行库存匹配事实规范为复核明细可消费的库存/履约投影。 -依赖:ShippingNoticeLineInventoryMatch、ShippingTaskInventoryRpaAttempt、Config 自动履约开关。 +依赖:ShippingNoticeLineOnhandMatch、FreightRpaOnhandTaskAttempt、Config 自动履约开关。 逻辑:由 order_review_fulfillment_decision_service / ui_state._build_stage_context 调用; ready+not_found→available=0;result_missing 不得转 0; part_available_qty(料号兜底总量)仅 inventory_status==ready 时透出,否则 None, 不派生「可兜底放行」布尔(自动放行判定在 Task 7 服务内基于行事实现算); inventory_allowed_actions / line_allowed_actions 分域下发(禁止前端自推按钮); line_allowed_actions 仅 close_unfulfillable,不再下发 view_fulfillment_detail; - load_current_match_facts_by_task / inventory_rpa_is_running 在同一 HTTP 请求内 memo, + load_current_match_facts_by_task / onhand_rpa_is_running 在同一 HTTP 请求内 memo, 禁止按行重复查库。 """ @@ -19,9 +19,9 @@ from decimal import Decimal, InvalidOperation from typing import Any from app.models import ( - ShippingInventoryFile, - ShippingNoticeLineInventoryMatch, - ShippingTaskInventoryRpaAttempt, + FreightRpaOnhandReportFile, + ShippingNoticeLineOnhandMatch, + FreightRpaOnhandTaskAttempt, ) @@ -41,10 +41,10 @@ STATUS_SOURCE_CONFLICT = 'source_conflict' STATUS_UNAVAILABLE = 'unavailable' STATUS_INVALID_KEY = 'invalid_key' -ACTION_RETRY_PREPARATION = 'retry_inventory_preparation' -ACTION_RETRY_MATCHING = 'retry_inventory_matching' +ACTION_RETRY_PREPARATION = 'retry_onhand_preparation' +ACTION_RETRY_MATCHING = 'retry_onhand_matching' ACTION_CLOSE = 'close_unfulfillable' -ACTION_RELEASE_SHORTAGE = 'release_inventory_shortage' +ACTION_RELEASE_SHORTAGE = 'release_onhand_shortage' ACTION_VIEW_FULFILLMENT = 'view_fulfillment_detail' # 已下线:不得再下发 UI @@ -455,10 +455,10 @@ def inventory_rpa_is_running(task: Any) -> bool: try: running = ( - ShippingTaskInventoryRpaAttempt.query + FreightRpaOnhandTaskAttempt.query .filter( - ShippingTaskInventoryRpaAttempt.task_no == task_no, - ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')), + FreightRpaOnhandTaskAttempt.task_no == task_no, + FreightRpaOnhandTaskAttempt.status.in_(('queued', 'running')), ) .first() is not None @@ -496,7 +496,7 @@ def load_current_match_facts_by_task(task_id: int | None) -> dict[int, dict[str, cache = None rows = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=key, is_current=True) .all() ) @@ -519,7 +519,7 @@ def load_current_match_facts_by_line_index(task_id: int | None) -> dict[int, dic if task_id is None: return {} rows = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=int(task_id), is_current=True) .all() ) @@ -543,11 +543,11 @@ def aggregate_match_status_for_task(task_id: int | None) -> str | None: return 'unfulfillable' if blocked else 'fulfillable' -def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any]: +def serialize_match_fact(row: ShippingNoticeLineOnhandMatch) -> dict[str, Any]: """将 ORM 行序列化为投影输入。""" snapshot = ( - ShippingInventoryFile.query.get(int(row.inventory_snapshot_id)) - if row.inventory_snapshot_id is not None else None + FreightRpaOnhandReportFile.query.get(int(row.onhand_snapshot_id)) + if row.onhand_snapshot_id is not None else None ) return { 'id': int(row.id), @@ -557,10 +557,10 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any 'line_no': int(row.line_no), 'line_index': row.line_index, 'inventory_snapshot_id': ( - int(row.inventory_snapshot_id) if row.inventory_snapshot_id is not None else None + int(row.onhand_snapshot_id) if row.onhand_snapshot_id is not None else None ), 'match_result': str(row.match_result or ''), - 'inventory_status': str(row.inventory_status or ''), + 'inventory_status': str(row.onhand_status or ''), 'required_qty': row.required_qty, 'available_qty': row.available_qty, 'shortage_qty': row.shortage_qty, @@ -569,7 +569,7 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any 'part_number': row.part_number, 'unit': row.unit, 'matching_rule_version': row.matching_rule_version, - 'inventory_source_code': row.inventory_source_code, + 'inventory_source_code': row.source_code, 'allowed_source_codes_snapshot': list(getattr(row, 'allowed_source_codes_snapshot', None) or []), 'inventory_file_no': getattr(row, 'matched_file_no', None), 'inventory_file_sha256': ( diff --git a/backend/app/services/shipping_notice/match_rule_desc.py b/backend/app/services/shipping_notice/match_rule_desc.py index a9481271..578067cc 100644 --- a/backend/app/services/shipping_notice/match_rule_desc.py +++ b/backend/app/services/shipping_notice/match_rule_desc.py @@ -3,7 +3,7 @@ services/shipping_notice/match_rule_desc.py 用途:根据已确认的库存栏位映射生成用户可读的匹配规则说明。 依赖:标准类型能力。 -逻辑:由 inventory_mapping、field_alignment_summary 等模块调用,说明订单字段与库存栏位的确定性对应关系。 +逻辑:由 onhand_mapping、field_alignment_summary 等模块调用,说明订单字段与库存栏位的确定性对应关系。 """ from __future__ import annotations diff --git a/backend/app/services/shipping_notice/notice_line_table.py b/backend/app/services/shipping_notice/notice_line_table.py index 8b98a9a2..4a0d3379 100644 --- a/backend/app/services/shipping_notice/notice_line_table.py +++ b/backend/app/services/shipping_notice/notice_line_table.py @@ -2,7 +2,7 @@ services/shipping_notice/notice_line_table.py 用途:从发货通知表格文本或二维行数据中解析订单行。 -依赖:notice_line_values、动态 Schema 表头契约、reservation_id、inventory_snapshot(懒加载表格拆行)。 +依赖:notice_line_values、动态 Schema 表头契约、reservation_id、onhand_snapshot(懒加载表格拆行)。 逻辑:调用方显式传入冻结契约;歧义表头不静默选列,输出诊断供 Run 进入复核。 """ @@ -229,7 +229,7 @@ def inspect_notice_table_text( Returns: `lines`、`header_found`、`ambiguous_fields` 和表头索引。 """ - from app.services.shipping_notice.inventory_snapshot import _rows_from_table_text + from app.services.shipping_notice.onhand_snapshot import _rows_from_table_text text = str(raw_text or '').strip() if not text or contract is None: @@ -257,6 +257,6 @@ def parse_notice_table_text( """ 从发货通知原始文本中的表格片段解析订单行。 - 核心逻辑:先借助 inventory_snapshot 的通用表格拆行工具得到二维表,再识别表头并解析数据行。 + 核心逻辑:先借助 onhand_snapshot 的通用表格拆行工具得到二维表,再识别表头并解析数据行。 """ return list(inspect_notice_table_text(raw_text, contract=contract)['lines']) diff --git a/backend/app/services/shipping_notice/notice_odm_choice_service.py b/backend/app/services/shipping_notice/notice_odm_choice_service.py index 38eef103..dd4f6eff 100644 --- a/backend/app/services/shipping_notice/notice_odm_choice_service.py +++ b/backend/app/services/shipping_notice/notice_odm_choice_service.py @@ -2,10 +2,11 @@ services/shipping_notice/notice_odm_choice_service.py 用途:发货通知整单(Notice)级 ODM ID 的逐行候选投影与用户选择持久化。 -依赖:export(prepare_export_match_inputs/_adjudicate_notice_odm)、ShippingNoticeLineInventoryMatch、AppError。 -逻辑:候选 = 各导出行命中 odm(先经客户 odm_ids 范围过滤)的交集,与导出收敛共用同一 +依赖:export(prepare_export_match_inputs/_adjudicate_notice_odm)、ShippingNoticeLineOnhandMatch、AppError。 +逻辑:候选 = 各导出行命中 odm 的交集(多值时先经客户 odm_ids 范围过滤,唯一命中 + 免白名单,与导出降级口径一致),与导出收敛共用同一 事实源(prepare_export_match_inputs);选择写在当前行级匹配事实行 - (shipping_notice_line_inventory_matches.chosen_odm_id)上,按「同一库存快照文件」 + (shipping_notice_line_onhand_matches.chosen_odm_id)上,按「同一库存快照文件」 圈同步范围——改任一行,同文件全部 is_current 行统一变更(Header 契约是整单一个值); 重匹配产生新匹配轮次后旧选择自然失效。实际收敛由导出裁决执行,本服务只投影与落库。 """ @@ -16,7 +17,7 @@ from typing import Any from app import db from app.core.errors import AppError -from app.models import ShippingCustomer, ShippingNoticeLineInventoryMatch +from app.models import ShippingCustomer, ShippingNoticeLineOnhandMatch _ODM_CHOICE_INVALID_CODE = 'SHIPPING.NOTICE_ODM_CHOICE_INVALID' @@ -127,7 +128,7 @@ def set_notice_odm_choice(task, *, snapshot_line_id: int, odm_id: str) -> dict[s http_status=409, ) target_row = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by( task_id=int(task_id), snapshot_line_id=int(snapshot_line_id or 0), @@ -144,11 +145,11 @@ def set_notice_odm_choice(task, *, snapshot_line_id: int, odm_id: str) -> dict[s ) # 同步范围:与目标行关联同一快照文件的全部当前匹配行。 scope_rows = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=int(task_id), is_current=True) - .filter(ShippingNoticeLineInventoryMatch.inventory_snapshot_id == target_row.inventory_snapshot_id) + .filter(ShippingNoticeLineOnhandMatch.onhand_snapshot_id == target_row.onhand_snapshot_id) .all() - ) if target_row.inventory_snapshot_id is not None else [target_row] + ) if target_row.onhand_snapshot_id is not None else [target_row] lines_by_sid = { str(item.get('snapshot_line_id')): item for item in options.get('lines') or [] } diff --git a/backend/app/services/shipping_notice/inventory_candidate_freeze_service.py b/backend/app/services/shipping_notice/onhand_candidate_freeze_service.py similarity index 88% rename from backend/app/services/shipping_notice/inventory_candidate_freeze_service.py rename to backend/app/services/shipping_notice/onhand_candidate_freeze_service.py index ecfd5780..1f937ea5 100644 --- a/backend/app/services/shipping_notice/inventory_candidate_freeze_service.py +++ b/backend/app/services/shipping_notice/onhand_candidate_freeze_service.py @@ -1,13 +1,13 @@ """ -services/shipping_notice/inventory_candidate_freeze_service.py +services/shipping_notice/onhand_candidate_freeze_service.py 用途:库存候选冻结的统一写入服务——将路由评估结果写入 Set/Source/Line 三张结构化表 (T2 新建,决策 C1 的正式业务真相),并同步写 ShippingOrderSnapshot.source_manifest_json 作为不可变审计副本。 -依赖:app.models.shipping_inventory_candidates(Set/Source/Line)、inventory_source_rules、 - inventory_source_repository、ShippingOrderSnapshot(source_manifest_json 快照)。 +依赖:app.models.shipping_onhand_candidates(Set/Source/Line)、onhand_source_rules、 + onhand_source_repository、ShippingOrderSnapshot(source_manifest_json 快照)。 逻辑:由 adjudicate_and_apply_inventory_source(裁决阶段 ambiguous→candidates_frozen) - 与 STP 建单 freeze_stp_inventory_candidates_on_task 两条路径调用; + 与 STP 建单 freeze_stp_onhand_candidates_on_task 两条路径调用; input_fingerprint 相同则直接返回旧 set_id(幂等),冻结结果不可变。 """ @@ -26,17 +26,17 @@ from sqlalchemy.orm import Session from app import db from app.models import ( - ShippingInventoryCandidateLine, - ShippingInventoryCandidateSet, - ShippingInventoryCandidateSource, + ShippingOnhandCandidateLine, + ShippingOnhandCandidateSet, + ShippingOnhandCandidateSource, ShippingNotice, ShippingOrderSnapshot, ) -from app.services.shipping_notice.inventory_source_repository import ( +from app.services.shipping_notice.onhand_source_repository import ( get_database_inventory_source, inventory_sources_runtime_version, ) -from app.services.shipping_notice.inventory_source_rules import ( +from app.services.shipping_notice.onhand_source_rules import ( InventorySourceAdjudication, _task_routing_lines, compute_routing_fingerprint, @@ -90,9 +90,9 @@ def _build_input_fingerprint( def _build_manifest_snapshot( *, task: ShippingNotice, - set_db: ShippingInventoryCandidateSet, - sources_db: list[ShippingInventoryCandidateSource], - lines_db: list[ShippingInventoryCandidateLine], + set_db: ShippingOnhandCandidateSet, + sources_db: list[ShippingOnhandCandidateSource], + lines_db: list[ShippingOnhandCandidateLine], routing_rule_version_json: dict[str, Any] | None, ) -> dict[str, Any]: """ @@ -215,35 +215,35 @@ def _find_existing_frozen_set( review_case_id: int | None, input_fingerprint: str, session: Session, -) -> ShippingInventoryCandidateSet | None: +) -> ShippingOnhandCandidateSet | None: """ 根据幂等键查找已存在的冻结 Set(task 绑定或 review_case 绑定分别查询)。 PostgreSQL 部分唯一索引保证每个绑定维度的 fingerprint 唯一。 """ if task_id is not None: return ( - session.query(ShippingInventoryCandidateSet) + session.query(ShippingOnhandCandidateSet) .filter( and_( - ShippingInventoryCandidateSet.task_id == task_id, - ShippingInventoryCandidateSet.input_fingerprint == input_fingerprint, - ShippingInventoryCandidateSet.lifecycle_status == 'frozen', + ShippingOnhandCandidateSet.task_id == task_id, + ShippingOnhandCandidateSet.input_fingerprint == input_fingerprint, + ShippingOnhandCandidateSet.lifecycle_status == 'frozen', ) ) - .order_by(ShippingInventoryCandidateSet.id.desc()) + .order_by(ShippingOnhandCandidateSet.id.desc()) .first() ) if review_case_id is not None: return ( - session.query(ShippingInventoryCandidateSet) + session.query(ShippingOnhandCandidateSet) .filter( and_( - ShippingInventoryCandidateSet.review_case_id == review_case_id, - ShippingInventoryCandidateSet.input_fingerprint == input_fingerprint, - ShippingInventoryCandidateSet.lifecycle_status == 'frozen', + ShippingOnhandCandidateSet.review_case_id == review_case_id, + ShippingOnhandCandidateSet.input_fingerprint == input_fingerprint, + ShippingOnhandCandidateSet.lifecycle_status == 'frozen', ) ) - .order_by(ShippingInventoryCandidateSet.id.desc()) + .order_by(ShippingOnhandCandidateSet.id.desc()) .first() ) return None @@ -252,8 +252,8 @@ def _find_existing_frozen_set( def _next_task_set_version(*, task_id: int, session: Session) -> int: """计算 Task 维度下一个 CandidateSet.version。""" current_max = ( - session.query(func.max(ShippingInventoryCandidateSet.set_version)) - .filter(ShippingInventoryCandidateSet.task_id == int(task_id)) + session.query(func.max(ShippingOnhandCandidateSet.set_version)) + .filter(ShippingOnhandCandidateSet.task_id == int(task_id)) .scalar() ) return int(current_max or 0) + 1 @@ -269,10 +269,10 @@ def _invalidate_task_candidate_outputs( """ from app.models import ( ShippingExportArtifact, - ShippingInventoryPreparationAttempt, - ShippingNoticeLineInventoryMatch, + ShippingOnhandPreparationAttempt, + ShippingNoticeLineOnhandMatch, ShippingProcessRecoveryPlan, - ShippingTaskInventoryRpaAttempt, + FreightRpaOnhandTaskAttempt, ShippingUploadAttempt, ) @@ -285,18 +285,18 @@ def _invalidate_task_candidate_outputs( task.step_payload_json = payload if task.__class__.__name__ != 'ShippingOrderTask' else {key: value for key, value in payload.items() if key in {'current_step_progress', 'parse_validation'}} ( - session.query(ShippingNoticeLineInventoryMatch) + session.query(ShippingNoticeLineOnhandMatch) .filter( - ShippingNoticeLineInventoryMatch.task_id == int(task.id), - ShippingNoticeLineInventoryMatch.is_current.is_(True), + ShippingNoticeLineOnhandMatch.task_id == int(task.id), + ShippingNoticeLineOnhandMatch.is_current.is_(True), ) .update({'is_current': False, 'updated_at': datetime.utcnow()}, synchronize_session=False) ) ( - session.query(ShippingTaskInventoryRpaAttempt) + session.query(FreightRpaOnhandTaskAttempt) .filter( - ShippingTaskInventoryRpaAttempt.task_no == str(task.task_no or ''), - ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')), + FreightRpaOnhandTaskAttempt.task_no == str(task.task_no or ''), + FreightRpaOnhandTaskAttempt.status.in_(('queued', 'running')), ) .update({'status': 'superseded', 'updated_at': datetime.utcnow()}, synchronize_session=False) ) @@ -326,19 +326,19 @@ def _invalidate_task_candidate_outputs( 'finished_at': datetime.utcnow(), 'error_code': 'candidate_set_refrozen', }, synchronize_session=False) - prep_query = session.query(ShippingInventoryPreparationAttempt).filter( - ShippingInventoryPreparationAttempt.task_id == int(task.id), - ShippingInventoryPreparationAttempt.status.in_(('queued', 'running', 'waiting_external', 'waiting_manual')), + prep_query = session.query(ShippingOnhandPreparationAttempt).filter( + ShippingOnhandPreparationAttempt.task_id == int(task.id), + ShippingOnhandPreparationAttempt.status.in_(('queued', 'running', 'waiting_external', 'waiting_manual')), ) if old_candidate_set_id is not None: prep_query = prep_query.filter( - ShippingInventoryPreparationAttempt.candidate_set_id == int(old_candidate_set_id) + ShippingOnhandPreparationAttempt.candidate_set_id == int(old_candidate_set_id) ) prep_query.update({'status': 'superseded'}, synchronize_session=False) active_execution_ids = [ - row[0] for row in session.query(ShippingInventoryPreparationAttempt.execution_id).filter( - ShippingInventoryPreparationAttempt.task_id == int(task.id), - ShippingInventoryPreparationAttempt.candidate_set_id == old_candidate_set_id, + row[0] for row in session.query(ShippingOnhandPreparationAttempt.execution_id).filter( + ShippingOnhandPreparationAttempt.task_id == int(task.id), + ShippingOnhandPreparationAttempt.candidate_set_id == old_candidate_set_id, ).all() if row[0] ] if active_execution_ids: @@ -395,7 +395,7 @@ def freeze_candidates_for_task( session = session or db.session if adjudication is None: - from app.services.shipping_notice.inventory_source_rules import adjudicate_inventory_source + from app.services.shipping_notice.onhand_source_rules import adjudicate_inventory_source adjudication = adjudicate_inventory_source(task) @@ -478,7 +478,7 @@ def freeze_candidates_for_task( 'adjudication_reason': adjudication.reason, } existing_active = ( - session.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id)) + session.get(ShippingOnhandCandidateSet, int(task.active_inventory_candidate_set_id)) if getattr(task, 'active_inventory_candidate_set_id', None) is not None and getattr(task, 'id', None) is not None else None ) @@ -487,7 +487,7 @@ def freeze_candidates_for_task( if getattr(task, 'id', None) is not None else 1 ) - new_set = ShippingInventoryCandidateSet( + new_set = ShippingOnhandCandidateSet( task_id=task.id, review_case_id=review_case_id, execution_id=execution_id, @@ -503,7 +503,7 @@ def freeze_candidates_for_task( session.add(new_set) session.flush() - created_sources: list[ShippingInventoryCandidateSource] = [] + created_sources: list[ShippingOnhandCandidateSource] = [] for idx, code in enumerate(task_source_codes_ordered): src_cfg = get_database_inventory_source(code) rule_id: int | None = None @@ -514,13 +514,13 @@ def freeze_candidates_for_task( if isinstance(matched_rule_ids, list) and matched_rule_ids: try: _rule_ids_int = int(matched_rule_ids[0]) - from app.models.shipping_inventory_config import ShippingInventoryRoutingRule + from app.models.freight_rpa_config import FreightRpaOnhandRoutingRule rule_row = ( session.query( - ShippingInventoryRoutingRule.id, - ShippingInventoryRoutingRule.version, + FreightRpaOnhandRoutingRule.id, + FreightRpaOnhandRoutingRule.version, ) - .filter(ShippingInventoryRoutingRule.id == _rule_ids_int) + .filter(FreightRpaOnhandRoutingRule.id == _rule_ids_int) .one_or_none() ) if rule_row is not None: @@ -529,7 +529,7 @@ def freeze_candidates_for_task( except (TypeError, ValueError): rule_id = None rule_version = None - source = ShippingInventoryCandidateSource( + source = ShippingOnhandCandidateSource( candidate_set_id=new_set.id, source_code=code, candidate_order=idx + 1, @@ -550,7 +550,7 @@ def freeze_candidates_for_task( for line in debug_env.read_text(encoding='utf-8').splitlines() if '=' in line } - urllib.request.urlopen(urllib.request.Request(debug_values.get('DEBUG_SERVER_URL', 'http://127.0.0.1:7777/event'), data=json.dumps({'sessionId': debug_values.get('DEBUG_SESSION_ID', 'integer-routing-version'), 'runId': 'post-fix', 'hypothesisId': 'A/C/E', 'location': 'inventory_candidate_freeze_service.py:545', 'msg': '[DEBUG] candidate source version before flush', 'data': {'routing_rule_id': rule_id, 'routing_rule_version': rule_version, 'config_version': config_version, 'persisted_routing_rule_version': source.routing_rule_version, 'source_code': code}}).encode(), headers={'Content-Type': 'application/json'}), timeout=1).read() + urllib.request.urlopen(urllib.request.Request(debug_values.get('DEBUG_SERVER_URL', 'http://127.0.0.1:7777/event'), data=json.dumps({'sessionId': debug_values.get('DEBUG_SESSION_ID', 'integer-routing-version'), 'runId': 'post-fix', 'hypothesisId': 'A/C/E', 'location': 'onhand_candidate_freeze_service.py:545', 'msg': '[DEBUG] candidate source version before flush', 'data': {'routing_rule_id': rule_id, 'routing_rule_version': rule_version, 'config_version': config_version, 'persisted_routing_rule_version': source.routing_rule_version, 'source_code': code}}).encode(), headers={'Content-Type': 'application/json'}), timeout=1).read() except Exception: pass # #endregion @@ -558,10 +558,10 @@ def freeze_candidates_for_task( created_sources.append(source) session.flush(created_sources) - created_lines: list[ShippingInventoryCandidateLine] = [] + created_lines: list[ShippingOnhandCandidateLine] = [] for sig in signatures: line_no, source_line_no, pn, resv, codes_ordered = sig - line_entity = ShippingInventoryCandidateLine( + line_entity = ShippingOnhandCandidateLine( candidate_set_id=new_set.id, line_no=line_no, source_line_no=source_line_no, @@ -671,7 +671,7 @@ def freeze_manual_line_source_selection( raise ValueError('未找到该订单项次') active_set = ( - session.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id)) + session.get(ShippingOnhandCandidateSet, int(task.active_inventory_candidate_set_id)) if task.active_inventory_candidate_set_id is not None else None ) existing_codes = { @@ -733,7 +733,7 @@ def active_candidate_set_is_manually_pinned( """ sess = session or db.session active_set = ( - sess.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id)) + sess.get(ShippingOnhandCandidateSet, int(task.active_inventory_candidate_set_id)) if getattr(task, 'active_inventory_candidate_set_id', None) is not None else None ) @@ -759,8 +759,8 @@ def refresh_candidates_from_current_routing( 禁止在轮询(poll)、自动首投路径调用——刷新是显式人工动作的伴随效果,不是隐式自动行为。 核心逻辑: - [守卫 1] 仅多候选未定源可刷新(task_frozen_inventory_source_codes > 1);源已定单 - 不得自动改源,换源走 override_line_inventory_source 行级覆写。 + [守卫 1] 仅多候选未定源可刷新(task_frozen_onhand_source_codes > 1);源已定单 + 不得自动改源,换源走 override_line_onhand_source 行级覆写。 [守卫 2] 活动候选集含人工选源(frozen_by_id / candidate_origin='manual_override') 时跳过:人工指定即定论,禁止重路由洗掉人工裁决。 [STEP 1] 记录当前活动 set_id。 @@ -778,12 +778,12 @@ def refresh_candidates_from_current_routing( Returns: bool: True=产生新版本候选集(调用方随后沿用既有失效与重取链);False=无变化或不适用。 """ - from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set - from app.services.shipping_notice.inventory_source_gate import adjudicate_and_apply_inventory_source - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_set + from app.services.shipping_notice.onhand_source_gate import adjudicate_and_apply_inventory_source + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes sess = session or db.session - if len(task_frozen_inventory_source_codes(task)) <= 1: + if len(task_frozen_onhand_source_codes(task)) <= 1: return False if active_candidate_set_is_manually_pinned(task, session=sess): return False @@ -804,7 +804,7 @@ def refresh_candidates_from_current_routing( 'scope': 'task', 'previous_set_id': before_set_id, 'new_set_id': after_set_id, - 'source_codes': task_frozen_inventory_source_codes(task), + 'source_codes': task_frozen_onhand_source_codes(task), }, source='system', ) @@ -820,7 +820,7 @@ def refresh_line_candidates_from_current_routing( ) -> bool: """ 行级:按当前库存源主数据与路由规则重评单个订单行的候选源并重冻结候选集;返回是否产生新版本。 - 【AI 触发时机】:仅「重新获取库存(RPA)」的行级重抓(retry_inventory_preparation 携带 + 【AI 触发时机】:仅「重新获取库存(RPA)」的行级重抓(retry_onhand_preparation 携带 line_scope)作为前置步骤调用;禁止在轮询/自动首投路径调用。 核心逻辑: @@ -844,12 +844,12 @@ def refresh_line_candidates_from_current_routing( Returns: bool: True=产生新版本候选集(调用方随后沿用既有失效与重取链);False=无变化或不适用。 """ - from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set - from app.services.shipping_notice.inventory_source_repository import ( + from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_set + from app.services.shipping_notice.onhand_source_repository import ( get_database_inventory_source, inventory_sources_runtime_version, ) - from app.services.shipping_notice.inventory_source_rules import ( + from app.services.shipping_notice.onhand_source_rules import ( _task_routing_lines, compute_routing_fingerprint, evaluate_inventory_source_rules, @@ -990,7 +990,7 @@ def freeze_wave_notice_routing( """ from app.models.shipping_notice_line import ShippingNoticeLine from app.services.shipping_notice.export import order_field_id_values - from app.services.shipping_notice.inventory_routing_engine import ( + from app.services.shipping_notice.onhand_routing_engine import ( evaluate_inventory_source_rules_for_field_values, ) @@ -1048,7 +1048,7 @@ def freeze_wave_notice_routing( if not task_codes: return None - from app.services.shipping_notice.inventory_source_rules import ( + from app.services.shipping_notice.onhand_source_rules import ( InventorySourceAdjudication, _candidate, compute_routing_fingerprint, diff --git a/backend/app/services/shipping_notice/inventory_candidate_projection.py b/backend/app/services/shipping_notice/onhand_candidate_projection.py similarity index 82% rename from backend/app/services/shipping_notice/inventory_candidate_projection.py rename to backend/app/services/shipping_notice/onhand_candidate_projection.py index 68dd12a2..0905f01a 100644 --- a/backend/app/services/shipping_notice/inventory_candidate_projection.py +++ b/backend/app/services/shipping_notice/onhand_candidate_projection.py @@ -1,9 +1,9 @@ """ -services/shipping_notice/inventory_candidate_projection.py +services/shipping_notice/onhand_candidate_projection.py 用途:统一读取正式 CandidateSet 真相,并投影为任务/工作台/聊天共用的候选事实 DTO。 -依赖:ShippingOrderTask、ShippingInventoryCandidateSet/Source/Line、ShippingNoticeLineInventoryMatch、 - ShippingTaskInventoryRpaAttempt。 +依赖:ShippingOrderTask、ShippingOnhandCandidateSet/Source/Line、ShippingNoticeLineOnhandMatch、 + FreightRpaOnhandTaskAttempt。 逻辑:正式 OT 一律通过 active_inventory_candidate_set_id 读取当前 frozen Set;缺失、 坏链、旧版本匹配引用或越界匹配统一产出 fail-closed 诊断,供 Gate / Projection / API 复用。 """ @@ -17,14 +17,14 @@ from sqlalchemy.orm import Session from app import db from app.models import ( - ShippingInventoryCandidateLine, - ShippingInventoryCandidateSet, - ShippingInventoryCandidateSource, - ShippingInventoryFile, + ShippingOnhandCandidateLine, + ShippingOnhandCandidateSet, + ShippingOnhandCandidateSource, + FreightRpaOnhandReportFile, ShippingNotice, ShippingOrderTask, - ShippingNoticeLineInventoryMatch, - ShippingTaskInventoryRpaAttempt, + ShippingNoticeLineOnhandMatch, + FreightRpaOnhandTaskAttempt, ) @@ -60,23 +60,23 @@ def _candidate_set_filter( *, include_drafts: bool = False, session: Session | None = None, -) -> list[ShippingInventoryCandidateSet]: +) -> list[ShippingOnhandCandidateSet]: """按 Task 读取候选版本列表;默认隐藏 draft。""" if getattr(task, 'id', None) is None: return [] query = ( _session(session) - .query(ShippingInventoryCandidateSet) - .filter(ShippingInventoryCandidateSet.task_id == int(task.id)) + .query(ShippingOnhandCandidateSet) + .filter(ShippingOnhandCandidateSet.task_id == int(task.id)) ) if not include_drafts: query = query.filter( - ShippingInventoryCandidateSet.lifecycle_status != INVENTORY_CANDIDATE_LIFECYCLE_DRAFT, + ShippingOnhandCandidateSet.lifecycle_status != INVENTORY_CANDIDATE_LIFECYCLE_DRAFT, ) rows = ( query.order_by( - ShippingInventoryCandidateSet.set_version.desc(), - ShippingInventoryCandidateSet.id.desc(), + ShippingOnhandCandidateSet.set_version.desc(), + ShippingOnhandCandidateSet.id.desc(), ) .all() ) @@ -114,7 +114,7 @@ def get_active_candidate_set( task: ShippingOrderTask | ShippingNotice, *, session: Session | None = None, -) -> ShippingInventoryCandidateSet | None: +) -> ShippingOnhandCandidateSet | None: """ 读取正式 Task 当前 frozen CandidateSet。 @@ -126,7 +126,7 @@ def get_active_candidate_set( candidate_set_id = getattr(task, 'active_inventory_candidate_set_id', None) if candidate_set_id is None: return None - row = _session(session).get(ShippingInventoryCandidateSet, int(candidate_set_id)) + row = _session(session).get(ShippingOnhandCandidateSet, int(candidate_set_id)) if row is None: return None if int(getattr(row, 'task_id', 0) or 0) != int(getattr(task, 'id', 0) or 0): @@ -140,18 +140,18 @@ def get_active_candidate_sources( task: ShippingOrderTask, *, session: Session | None = None, -) -> list[ShippingInventoryCandidateSource]: +) -> list[ShippingOnhandCandidateSource]: """读取当前 frozen Set 的任务级候选源。""" current = get_active_candidate_set(task, session=session) if current is None: return [] rows = ( _session(session) - .query(ShippingInventoryCandidateSource) - .filter(ShippingInventoryCandidateSource.candidate_set_id == int(current.id)) + .query(ShippingOnhandCandidateSource) + .filter(ShippingOnhandCandidateSource.candidate_set_id == int(current.id)) .order_by( - ShippingInventoryCandidateSource.candidate_order.asc(), - ShippingInventoryCandidateSource.id.asc(), + ShippingOnhandCandidateSource.candidate_order.asc(), + ShippingOnhandCandidateSource.id.asc(), ) .all() ) @@ -162,18 +162,18 @@ def get_active_candidate_lines( task: ShippingOrderTask, *, session: Session | None = None, -) -> list[ShippingInventoryCandidateLine]: +) -> list[ShippingOnhandCandidateLine]: """读取当前 frozen Set 的行级候选。""" current = get_active_candidate_set(task, session=session) if current is None: return [] rows = ( _session(session) - .query(ShippingInventoryCandidateLine) - .filter(ShippingInventoryCandidateLine.candidate_set_id == int(current.id)) + .query(ShippingOnhandCandidateLine) + .filter(ShippingOnhandCandidateLine.candidate_set_id == int(current.id)) .order_by( - ShippingInventoryCandidateLine.line_no.asc(), - ShippingInventoryCandidateLine.id.asc(), + ShippingOnhandCandidateLine.line_no.asc(), + ShippingOnhandCandidateLine.id.asc(), ) .all() ) @@ -198,7 +198,7 @@ def active_inventory_runtime_facts( Returns: source_codes、source_config_version、inventory_file_id 与 active_link 等当前事实。 """ - from app.models import ShippingTaskInventoryLink + from app.models import ShippingTaskOnhandLink sess = _session(session) candidate_set = get_active_candidate_set(task, session=sess) @@ -206,9 +206,9 @@ def active_inventory_runtime_facts( source_codes = [str(row.source_code or '').strip().upper() for row in sources if str(row.source_code or '').strip()] versions = [str(row.source_config_version or '').strip() for row in sources if str(row.source_config_version or '').strip()] link = ( - sess.query(ShippingTaskInventoryLink) - .filter(ShippingTaskInventoryLink.task_id == int(task.id), ShippingTaskInventoryLink.is_active.is_(True)) - .order_by(ShippingTaskInventoryLink.id.desc()) + sess.query(ShippingTaskOnhandLink) + .filter(ShippingTaskOnhandLink.task_id == int(task.id), ShippingTaskOnhandLink.is_active.is_(True)) + .order_by(ShippingTaskOnhandLink.id.desc()) .first() if getattr(task, 'id', None) is not None else None ) @@ -218,7 +218,7 @@ def active_inventory_runtime_facts( 'source_codes': source_codes, 'source_config_version': versions[0] if len(set(versions)) == 1 and versions else None, 'active_link': link, - 'inventory_file_id': getattr(link, 'inventory_file_id', None), + 'inventory_file_id': getattr(link, 'onhand_file_id', None), 'inventory_file': getattr(link, 'inventory_file', None), } @@ -229,26 +229,26 @@ def get_candidate_set_by_version( *, include_drafts: bool = False, session: Session | None = None, -) -> ShippingInventoryCandidateSet | None: +) -> ShippingOnhandCandidateSet | None: """按 Task + set_version 读取指定候选版本。""" if getattr(task, 'id', None) is None: return None query = ( _session(session) - .query(ShippingInventoryCandidateSet) + .query(ShippingOnhandCandidateSet) .filter( - ShippingInventoryCandidateSet.task_id == int(task.id), - ShippingInventoryCandidateSet.set_version == int(version), + ShippingOnhandCandidateSet.task_id == int(task.id), + ShippingOnhandCandidateSet.set_version == int(version), ) ) if not include_drafts: query = query.filter( - ShippingInventoryCandidateSet.lifecycle_status != INVENTORY_CANDIDATE_LIFECYCLE_DRAFT, + ShippingOnhandCandidateSet.lifecycle_status != INVENTORY_CANDIDATE_LIFECYCLE_DRAFT, ) - return query.order_by(ShippingInventoryCandidateSet.id.desc()).first() + return query.order_by(ShippingOnhandCandidateSet.id.desc()).first() -def serialize_candidate_set_summary(row: ShippingInventoryCandidateSet | None) -> dict[str, Any] | None: +def serialize_candidate_set_summary(row: ShippingOnhandCandidateSet | None) -> dict[str, Any] | None: """序列化 CandidateSet 摘要供 API / Projection 复用。""" if row is None: return None @@ -268,7 +268,7 @@ def serialize_candidate_set_summary(row: ShippingInventoryCandidateSet | None) - } -def serialize_candidate_source(row: ShippingInventoryCandidateSource) -> dict[str, Any]: +def serialize_candidate_source(row: ShippingOnhandCandidateSource) -> dict[str, Any]: """序列化任务级候选源。""" return { 'id': int(row.id), @@ -284,7 +284,7 @@ def serialize_candidate_source(row: ShippingInventoryCandidateSource) -> dict[st } -def serialize_candidate_line(row: ShippingInventoryCandidateLine) -> dict[str, Any]: +def serialize_candidate_line(row: ShippingOnhandCandidateLine) -> dict[str, Any]: """序列化行级候选源与稳定行标识。""" return { 'candidate_line_id': int(row.id), @@ -300,20 +300,20 @@ def serialize_candidate_line(row: ShippingInventoryCandidateLine) -> dict[str, A def _candidate_sources_for_set( - candidate_set: ShippingInventoryCandidateSet | None, + candidate_set: ShippingOnhandCandidateSet | None, *, session: Session | None = None, -) -> list[ShippingInventoryCandidateSource]: +) -> list[ShippingOnhandCandidateSource]: """读取指定 CandidateSet 的任务级候选源。""" if candidate_set is None: return [] rows = ( _session(session) - .query(ShippingInventoryCandidateSource) - .filter(ShippingInventoryCandidateSource.candidate_set_id == int(candidate_set.id)) + .query(ShippingOnhandCandidateSource) + .filter(ShippingOnhandCandidateSource.candidate_set_id == int(candidate_set.id)) .order_by( - ShippingInventoryCandidateSource.candidate_order.asc(), - ShippingInventoryCandidateSource.id.asc(), + ShippingOnhandCandidateSource.candidate_order.asc(), + ShippingOnhandCandidateSource.id.asc(), ) .all() ) @@ -321,20 +321,20 @@ def _candidate_sources_for_set( def _candidate_lines_for_set( - candidate_set: ShippingInventoryCandidateSet | None, + candidate_set: ShippingOnhandCandidateSet | None, *, session: Session | None = None, -) -> list[ShippingInventoryCandidateLine]: +) -> list[ShippingOnhandCandidateLine]: """读取指定 CandidateSet 的行级候选。""" if candidate_set is None: return [] rows = ( _session(session) - .query(ShippingInventoryCandidateLine) - .filter(ShippingInventoryCandidateLine.candidate_set_id == int(candidate_set.id)) + .query(ShippingOnhandCandidateLine) + .filter(ShippingOnhandCandidateLine.candidate_set_id == int(candidate_set.id)) .order_by( - ShippingInventoryCandidateLine.line_no.asc(), - ShippingInventoryCandidateLine.id.asc(), + ShippingOnhandCandidateLine.line_no.asc(), + ShippingOnhandCandidateLine.id.asc(), ) .all() ) @@ -373,15 +373,15 @@ def _latest_attempts_by_source(task: ShippingOrderTask, source_codes: list[str], return {} rows = ( _session(session) - .query(ShippingTaskInventoryRpaAttempt) + .query(FreightRpaOnhandTaskAttempt) .filter( - ShippingTaskInventoryRpaAttempt.task_no == task_no, - ShippingTaskInventoryRpaAttempt.source_code.in_(source_codes), + FreightRpaOnhandTaskAttempt.task_no == task_no, + FreightRpaOnhandTaskAttempt.source_code.in_(source_codes), ) .order_by( - ShippingTaskInventoryRpaAttempt.source_code.asc(), - ShippingTaskInventoryRpaAttempt.attempt_no.desc(), - ShippingTaskInventoryRpaAttempt.id.desc(), + FreightRpaOnhandTaskAttempt.source_code.asc(), + FreightRpaOnhandTaskAttempt.attempt_no.desc(), + FreightRpaOnhandTaskAttempt.id.desc(), ) .all() ) @@ -397,7 +397,7 @@ def _latest_attempts_by_source(task: ShippingOrderTask, source_codes: list[str], 'run_no': str(row.run_no or ''), 'error_code': getattr(row, 'error_code', None), 'error_message': getattr(row, 'error_message', None), - 'inventory_file_no': getattr(row, 'inventory_file_no', None), + 'inventory_file_no': getattr(row, 'onhand_file_no', None), 'updated_at': _iso(getattr(row, 'updated_at', None)), } return out @@ -419,20 +419,20 @@ def _classify_sources(source_codes: list[str], attempt_map: dict[str, dict[str, return prepared, pending, failed -def _current_match_rows(task: ShippingOrderTask, *, session: Session | None = None) -> list[ShippingNoticeLineInventoryMatch]: +def _current_match_rows(task: ShippingOrderTask, *, session: Session | None = None) -> list[ShippingNoticeLineOnhandMatch]: """读取任务当前生效的行级匹配事实。""" if getattr(task, 'id', None) is None: return [] rows = ( _session(session) - .query(ShippingNoticeLineInventoryMatch) + .query(ShippingNoticeLineOnhandMatch) .filter( - ShippingNoticeLineInventoryMatch.task_id == int(task.id), - ShippingNoticeLineInventoryMatch.is_current.is_(True), + ShippingNoticeLineOnhandMatch.task_id == int(task.id), + ShippingNoticeLineOnhandMatch.is_current.is_(True), ) .order_by( - ShippingNoticeLineInventoryMatch.line_index.asc(), - ShippingNoticeLineInventoryMatch.id.asc(), + ShippingNoticeLineOnhandMatch.line_index.asc(), + ShippingNoticeLineOnhandMatch.id.asc(), ) .all() ) @@ -548,20 +548,20 @@ def project_inventory_candidate_facts( current_match_rows = _current_match_rows(task, session=sess) # [BE-性能] 批量预取当前匹配行引用的库存快照,避免循环内逐行 sess.get() 造成 N+1。 snapshot_ids = { - int(row.inventory_snapshot_id) + int(row.onhand_snapshot_id) for row in current_match_rows - if getattr(row, 'inventory_snapshot_id', None) is not None + if getattr(row, 'onhand_snapshot_id', None) is not None } snapshot_by_id: dict[int, Any] = {} if snapshot_ids: snapshot_by_id = { int(item.id): item - for item in sess.query(ShippingInventoryFile).filter(ShippingInventoryFile.id.in_(snapshot_ids)).all() + for item in sess.query(FreightRpaOnhandReportFile).filter(FreightRpaOnhandReportFile.id.in_(snapshot_ids)).all() } for row in current_match_rows: snapshot = ( - snapshot_by_id.get(int(row.inventory_snapshot_id)) - if getattr(row, 'inventory_snapshot_id', None) is not None else None + snapshot_by_id.get(int(row.onhand_snapshot_id)) + if getattr(row, 'onhand_snapshot_id', None) is not None else None ) allowed_codes = _normalized_codes(getattr(row, 'allowed_source_codes_snapshot', None)) serialized = { @@ -577,11 +577,11 @@ def project_inventory_candidate_facts( # [Approach 1] 行匹配记录未回填源、但行允许源为单一源时(如 shortages 匹配、覆写单源), # 用该单一源回填 resolved_inventory_source_code,保证行级源诚实展示(D7 Excel 前可改)。 'resolved_inventory_source_code': ( - getattr(row, 'inventory_source_code', None) + getattr(row, 'source_code', None) or (allowed_codes[0] if len(allowed_codes) == 1 else None) ), 'inventory_file_no': getattr(row, 'matched_file_no', None), - 'inventory_snapshot_id': getattr(row, 'inventory_snapshot_id', None), + 'inventory_snapshot_id': getattr(row, 'onhand_snapshot_id', None), 'inventory_row_ref': (dict(getattr(row, 'detail_json', None) or {}).get('inventory_row_ref')), 'inventory_file_sha256': ( dict(getattr(row, 'detail_json', None) or {}).get('file_sha256') @@ -619,9 +619,9 @@ def project_inventory_candidate_facts( 'operation_id': f'match-line:{int(row.id)}', } elif ( - str(getattr(row, 'inventory_source_code', '') or '').strip().upper() + str(getattr(row, 'source_code', '') or '').strip().upper() and allowed_codes - and str(getattr(row, 'inventory_source_code', '') or '').strip().upper() not in allowed_codes + and str(getattr(row, 'source_code', '') or '').strip().upper() not in allowed_codes ): out_of_scope_details = { 'candidate_line_id': int(candidate_line_id), @@ -631,7 +631,7 @@ def project_inventory_candidate_facts( 'actual_candidate_set_version': getattr(row, 'candidate_set_version', None), 'detected_at': datetime.utcnow().isoformat(), 'operation_id': f'match-line:{int(row.id)}', - 'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None), + 'resolved_inventory_source_code': getattr(row, 'source_code', None), 'allowed_source_codes_snapshot': allowed_codes, } diff --git a/backend/app/services/shipping_notice/inventory_combination_fingerprint.py b/backend/app/services/shipping_notice/onhand_combination_fingerprint.py similarity index 95% rename from backend/app/services/shipping_notice/inventory_combination_fingerprint.py rename to backend/app/services/shipping_notice/onhand_combination_fingerprint.py index 4ee2d573..7ea37d31 100644 --- a/backend/app/services/shipping_notice/inventory_combination_fingerprint.py +++ b/backend/app/services/shipping_notice/onhand_combination_fingerprint.py @@ -1,5 +1,5 @@ """ -services/shipping_notice/inventory_combination_fingerprint.py +services/shipping_notice/onhand_combination_fingerprint.py 用途:为多源库存准备轮次生成稳定组合输入指纹。 依赖:标准库 hashlib/json。 diff --git a/backend/app/services/shipping_notice/inventory_configuration_test.py b/backend/app/services/shipping_notice/onhand_configuration_test.py similarity index 68% rename from backend/app/services/shipping_notice/inventory_configuration_test.py rename to backend/app/services/shipping_notice/onhand_configuration_test.py index c6c80fa8..b53fa174 100644 --- a/backend/app/services/shipping_notice/inventory_configuration_test.py +++ b/backend/app/services/shipping_notice/onhand_configuration_test.py @@ -1,5 +1,5 @@ """ -services/shipping_notice/inventory_configuration_test.py +services/shipping_notice/onhand_configuration_test.py 用途:编排库存站点测试导出、RPA 回调文件分析(可选运维工具,不参与启用门禁)。 依赖:库存站点/RPA trigger、库存结构分析、库存解析方案模型。 @@ -16,17 +16,18 @@ from flask import current_app from app.core.errors import ConflictError, NotFoundError, ValidationError from app.extensions import db from app.models import ( - ShippingInventoryConfigurationTestRun, - ShippingInventoryParsingProfile, - ShippingInventorySource, - ShippingInventoryValidationBatch, + FreightRpaOnhandConfigurationTestRun, + FreightRpaOnhandReportConfig, + FreightRpaParsingProfile, + FreightRpaSource, + FreightRpaOnhandValidationBatch, ) -def _payload(run: ShippingInventoryConfigurationTestRun) -> dict[str, Any]: +def _payload(run: FreightRpaOnhandConfigurationTestRun) -> dict[str, Any]: """投影测试运行状态,避免暴露 RPA 文件的服务器路径。""" return { - 'id': run.id, 'run_no': run.run_no, 'inventory_source_id': run.inventory_source_id, + 'id': run.id, 'run_no': run.run_no, 'source_id': run.source_id, 'validation_batch_id': run.validation_batch_id, 'rpa_batch_run_no': run.rpa_batch_run_no, 'source_config_version': run.source_config_version, 'rpa_profile_config_version': run.rpa_profile_config_version, 'status': run.status, 'stage': run.stage, @@ -36,10 +37,10 @@ def _payload(run: ShippingInventoryConfigurationTestRun) -> dict[str, Any]: } -def _batch_payload(batch: ShippingInventoryValidationBatch) -> dict[str, Any]: +def _batch_payload(batch: FreightRpaOnhandValidationBatch) -> dict[str, Any]: """投影批量验证进度及其逐站点运行,供管理端按批次轮询。""" - runs = ShippingInventoryConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).order_by( - ShippingInventoryConfigurationTestRun.id.asc(), + runs = FreightRpaOnhandConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).order_by( + FreightRpaOnhandConfigurationTestRun.id.asc(), ).all() return { 'id': batch.id, 'batch_no': batch.batch_no, 'status': batch.status, @@ -57,10 +58,10 @@ def _refresh_batch(batch_id: int | None) -> None: """按逐站点终态重算批次汇总;一个站点失败绝不覆盖其他站点结果。""" if not batch_id: return - batch = db.session.get(ShippingInventoryValidationBatch, batch_id) + batch = db.session.get(FreightRpaOnhandValidationBatch, batch_id) if batch is None: return - runs = ShippingInventoryConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).all() + runs = FreightRpaOnhandConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).all() terminal = {'completed', 'completed_empty', 'failed'} batch.total_count = len(runs) batch.success_count = sum(run.status == 'completed' for run in runs) @@ -84,58 +85,61 @@ def _refresh_batch(batch_id: int | None) -> None: batch.completed_at = datetime.utcnow() -def _validate_batch_sources(source_ids: list[int]) -> list[ShippingInventorySource]: +def _validate_batch_sources(source_ids: list[int]) -> list[FreightRpaSource]: """预检批量验证站点,强制使用已发布解析定义以明确空库存的业务语义。""" ids: list[int] = [] for source_id in source_ids: try: value = int(source_id) except (TypeError, ValueError): - raise ValidationError('Inventory source ids must be positive integers', code='SHIPPING.INVENTORY_BATCH_SOURCE_REQUIRED') + raise ValidationError('Inventory source ids must be positive integers', code='SHIPPING.ONHAND_BATCH_SOURCE_REQUIRED') if value > 0 and value not in ids: ids.append(value) if not ids: - raise ValidationError('At least one inventory source is required', code='SHIPPING.INVENTORY_BATCH_SOURCE_REQUIRED') - sources = ShippingInventorySource.query.filter(ShippingInventorySource.id.in_(ids)).all() + raise ValidationError('At least one inventory source is required', code='SHIPPING.ONHAND_BATCH_SOURCE_REQUIRED') + sources = FreightRpaSource.query.filter(FreightRpaSource.id.in_(ids)).all() by_id = {source.id: source for source in sources} if len(by_id) != len(ids): - raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') ordered = [by_id[source_id] for source_id in ids] for source in ordered: if source.enabled: - raise ConflictError('Disable inventory source before configuration test', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_INVALID') + raise ConflictError('Disable inventory source before configuration test', code='SHIPPING.ONHAND_CONFIGURATION_TEST_INVALID') if source.rpa_profile is None or not source.rpa_profile.enabled: raise ValidationError('Enabled RPA Profile is required', code='SHIPPING.RPA_PROFILE_DISABLED') - if source.parsing_profile is None or source.parsing_profile.status != 'published': - raise ValidationError('Published parsing profile is required for batch test', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED') + # s18 起解析方案绑定归 onhand_report_config 配置行;配置行缺失即未绑定。 + config = source.onhand_report_config + profile = config.parsing_profile if config is not None else None + if profile is None or profile.status != 'published': + raise ValidationError('Published parsing profile is required for batch test', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED') _expire_timed_out_runs(source) - active = ShippingInventoryConfigurationTestRun.query.filter( - ShippingInventoryConfigurationTestRun.inventory_source_id == source.id, - ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']), + active = FreightRpaOnhandConfigurationTestRun.query.filter( + FreightRpaOnhandConfigurationTestRun.source_id == source.id, + FreightRpaOnhandConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']), ).first() if active: - raise ConflictError('Inventory source already has an active configuration test', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_ACTIVE') + raise ConflictError('Inventory source already has an active configuration test', code='SHIPPING.ONHAND_CONFIGURATION_TEST_ACTIVE') return ordered def start_batch_test_export(source_ids: list[int], *, actor_id: int | None, retry_of_batch_id: int | None = None) -> dict[str, Any]: """创建批量验证并按连接配置分组投递 RPA;每站点保留独立运行与回调结果。""" sources = _validate_batch_sources(source_ids) - from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source - from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger + from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source + from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger stamp = datetime.utcnow().strftime('%Y%m%d%H%M%S%f') - batch = ShippingInventoryValidationBatch( + batch = FreightRpaOnhandValidationBatch( batch_no=f'CONFIG-BATCH-{stamp}', status='queued', total_count=len(sources), created_by=actor_id, retry_of_batch_id=retry_of_batch_id, ) db.session.add(batch) db.session.flush() - grouped: dict[tuple[int, str], list[tuple[ShippingInventoryConfigurationTestRun, dict[str, Any]]]] = {} + grouped: dict[tuple[int, str], list[tuple[FreightRpaOnhandConfigurationTestRun, dict[str, Any]]]] = {} for source in sources: - run = ShippingInventoryConfigurationTestRun( + run = FreightRpaOnhandConfigurationTestRun( run_no=f'CONFIG-{source.source_code}-{stamp}-{source.id}', validation_batch_id=batch.id, - inventory_source_id=source.id, + source_id=source.id, source_config_version=source.config_version, rpa_profile_config_version=source.rpa_profile.config_version, status='awaiting_rpa', stage='waiting_worker', result_json={}, created_by=actor_id, ) @@ -143,7 +147,7 @@ def start_batch_test_export(source_ids: list[int], *, actor_id: int | None, retr db.session.flush() source_payload = get_database_inventory_source(source.source_code, enabled_only=False) if source_payload is None: - raise ValidationError('Inventory Source is invalid', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID') + raise ValidationError('Inventory Source is invalid', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID') source_payload = {**source_payload, 'validation_run_no': run.run_no} grouped.setdefault((source.rpa_profile_id, source.connector_type), []).append((run, source_payload)) db.session.commit() @@ -171,11 +175,11 @@ def start_batch_test_export(source_ids: list[int], *, actor_id: int | None, retr def get_validation_batch(batch_id: int) -> dict[str, Any]: """返回批量验证当前汇总与逐站点结果,读取时同时收口超时任务。""" - batch = db.session.get(ShippingInventoryValidationBatch, batch_id) + batch = db.session.get(FreightRpaOnhandValidationBatch, batch_id) if batch is None: - raise NotFoundError('Inventory validation batch not found', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NOT_FOUND') - for run in ShippingInventoryConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).all(): - source = db.session.get(ShippingInventorySource, run.inventory_source_id) + raise NotFoundError('Inventory validation batch not found', code='SHIPPING.ONHAND_VALIDATION_BATCH_NOT_FOUND') + for run in FreightRpaOnhandConfigurationTestRun.query.filter_by(validation_batch_id=batch.id).all(): + source = db.session.get(FreightRpaSource, run.source_id) if source is not None: _expire_timed_out_runs(source) _refresh_batch(batch.id) @@ -185,26 +189,26 @@ def get_validation_batch(batch_id: int) -> dict[str, Any]: def get_latest_active_validation_batch() -> dict[str, Any] | None: """恢复最近仍在执行的批量验证,供管理端刷新后继续查看真实进度。""" - batch = ShippingInventoryValidationBatch.query.filter( - ShippingInventoryValidationBatch.status.in_(['queued', 'running']), - ).order_by(ShippingInventoryValidationBatch.id.desc()).first() + batch = FreightRpaOnhandValidationBatch.query.filter( + FreightRpaOnhandValidationBatch.status.in_(['queued', 'running']), + ).order_by(FreightRpaOnhandValidationBatch.id.desc()).first() return get_validation_batch(batch.id) if batch is not None else None def retry_failed_validation_batch(batch_id: int, *, actor_id: int | None) -> dict[str, Any]: """仅重新投递失败或配置已变更的站点,已成功及空库存站点不重复执行。""" - batch = db.session.get(ShippingInventoryValidationBatch, batch_id) + batch = db.session.get(FreightRpaOnhandValidationBatch, batch_id) if batch is None: - raise NotFoundError('Inventory validation batch not found', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NOT_FOUND') - failed_ids = [run.inventory_source_id for run in ShippingInventoryConfigurationTestRun.query.filter_by( + raise NotFoundError('Inventory validation batch not found', code='SHIPPING.ONHAND_VALIDATION_BATCH_NOT_FOUND') + failed_ids = [run.source_id for run in FreightRpaOnhandConfigurationTestRun.query.filter_by( validation_batch_id=batch.id, status='failed', ).all()] if not failed_ids: - raise ConflictError('No failed inventory validation runs to retry', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NO_FAILURE') + raise ConflictError('No failed inventory validation runs to retry', code='SHIPPING.ONHAND_VALIDATION_BATCH_NO_FAILURE') return start_batch_test_export(failed_ids, actor_id=actor_id, retry_of_batch_id=batch.id) -def _matches_current_configuration(run: ShippingInventoryConfigurationTestRun, source: ShippingInventorySource) -> bool: +def _matches_current_configuration(run: FreightRpaOnhandConfigurationTestRun, source: FreightRpaSource) -> bool: """判断测试运行是否仍对应当前站点与 RPA 连接配置,避免旧任务阻塞新配置测试。""" return bool( source.rpa_profile @@ -213,23 +217,23 @@ def _matches_current_configuration(run: ShippingInventoryConfigurationTestRun, s ) -def _expire_timed_out_runs(source: ShippingInventorySource) -> None: +def _expire_timed_out_runs(source: FreightRpaSource) -> None: """按批量队列长度延长等待窗口,避免串行站点被单站超时误判。 同一 RPA Profile 的批量站点由 Windows Worker 串行执行。每个站点沿用单站 等待窗口会让排在后面的站点尚未被领取就超时,因此同组按站点数量线性扩展。 """ - timeout = max(1, int(current_app.config['FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS'])) - runs = ShippingInventoryConfigurationTestRun.query.filter( - ShippingInventoryConfigurationTestRun.inventory_source_id == source.id, - ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']), + timeout = max(1, int(current_app.config['FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS'])) + runs = FreightRpaOnhandConfigurationTestRun.query.filter( + FreightRpaOnhandConfigurationTestRun.source_id == source.id, + FreightRpaOnhandConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']), ).all() for run in runs: multiplier = 1 if run.validation_batch_id: - same_worker_queue = ShippingInventoryConfigurationTestRun.query.filter( - ShippingInventoryConfigurationTestRun.validation_batch_id == run.validation_batch_id, - ShippingInventoryConfigurationTestRun.rpa_batch_run_no == run.rpa_batch_run_no, + same_worker_queue = FreightRpaOnhandConfigurationTestRun.query.filter( + FreightRpaOnhandConfigurationTestRun.validation_batch_id == run.validation_batch_id, + FreightRpaOnhandConfigurationTestRun.rpa_batch_run_no == run.rpa_batch_run_no, ).count() multiplier = max(1, same_worker_queue) deadline = datetime.utcnow() - timedelta(seconds=timeout * multiplier) @@ -243,43 +247,43 @@ def _expire_timed_out_runs(source: ShippingInventorySource) -> None: def get_latest_test_run(source_id: int) -> dict[str, Any] | None: """返回站点当前配置对应的最近测试运行,供管理端刷新或重开抽屉后恢复真实状态。""" - source = db.session.get(ShippingInventorySource, source_id) + source = db.session.get(FreightRpaSource, source_id) if source is None: - raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') _expire_timed_out_runs(source) db.session.commit() - run = ShippingInventoryConfigurationTestRun.query.filter_by( - inventory_source_id=source.id, + run = FreightRpaOnhandConfigurationTestRun.query.filter_by( + source_id=source.id, source_config_version=source.config_version, rpa_profile_config_version=source.rpa_profile.config_version if source.rpa_profile else -1, - ).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first() + ).order_by(FreightRpaOnhandConfigurationTestRun.id.desc()).first() return _payload(run) if run else None def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any]: """为停用库存站点写入专用测试 trigger;仅复用同一配置版本仍在运行的任务。""" - source = db.session.get(ShippingInventorySource, source_id) + source = db.session.get(FreightRpaSource, source_id) if source is None: - raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') + raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND') if source.enabled: - raise ConflictError('Disable inventory source before configuration test', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_INVALID') + raise ConflictError('Disable inventory source before configuration test', code='SHIPPING.ONHAND_CONFIGURATION_TEST_INVALID') if source.rpa_profile is None or not source.rpa_profile.enabled: raise ValidationError('Enabled RPA Profile is required', code='SHIPPING.RPA_PROFILE_DISABLED') _expire_timed_out_runs(source) - active = ShippingInventoryConfigurationTestRun.query.filter( - ShippingInventoryConfigurationTestRun.inventory_source_id == source.id, - ShippingInventoryConfigurationTestRun.source_config_version == source.config_version, - ShippingInventoryConfigurationTestRun.rpa_profile_config_version == source.rpa_profile.config_version, - ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']), - ).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first() + active = FreightRpaOnhandConfigurationTestRun.query.filter( + FreightRpaOnhandConfigurationTestRun.source_id == source.id, + FreightRpaOnhandConfigurationTestRun.source_config_version == source.config_version, + FreightRpaOnhandConfigurationTestRun.rpa_profile_config_version == source.rpa_profile.config_version, + FreightRpaOnhandConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']), + ).order_by(FreightRpaOnhandConfigurationTestRun.id.desc()).first() if active: return _payload(active) - from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger - from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger + from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source run_no = f'CONFIG-{source.source_code}-{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}' - run = ShippingInventoryConfigurationTestRun( - run_no=run_no, inventory_source_id=source.id, source_config_version=source.config_version, + run = FreightRpaOnhandConfigurationTestRun( + run_no=run_no, source_id=source.id, source_config_version=source.config_version, rpa_profile_config_version=source.rpa_profile.config_version, status='awaiting_rpa', stage='waiting_worker', result_json={}, created_by=actor_id, ) @@ -287,7 +291,7 @@ def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any] db.session.flush() source_payload = get_database_inventory_source(source.source_code, enabled_only=False) if source_payload is None: - raise ValidationError('Inventory Source is invalid', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID') + raise ValidationError('Inventory Source is invalid', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID') try: trigger = write_inventory_export_batch_trigger(run_no, [source_payload], payload={ 'trigger_type': 'configuration_test', 'configuration_test_run_id': run.id, @@ -297,7 +301,7 @@ def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any] raise if not trigger: db.session.rollback() - raise ConflictError('RPA Worker is not ready', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_UNAVAILABLE') + raise ConflictError('RPA Worker is not ready', code='SHIPPING.ONHAND_CONFIGURATION_TEST_UNAVAILABLE') run.result_json = {'trigger_written': True} db.session.commit() return _payload(run) @@ -305,12 +309,12 @@ def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any] def get_test_run(source_id: int, run_no: str) -> dict[str, Any]: """读取指定库存站点的测试运行,防止跨站点查看结果。""" - run = ShippingInventoryConfigurationTestRun.query.filter_by( - inventory_source_id=source_id, run_no=str(run_no or '').strip(), + run = FreightRpaOnhandConfigurationTestRun.query.filter_by( + source_id=source_id, run_no=str(run_no or '').strip(), ).first() if run is None: - raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND') - source = db.session.get(ShippingInventorySource, source_id) + raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.ONHAND_CONFIGURATION_TEST_NOT_FOUND') + source = db.session.get(FreightRpaSource, source_id) if source is not None: _expire_timed_out_runs(source) db.session.commit() @@ -320,12 +324,12 @@ def get_test_run(source_id: int, run_no: str) -> dict[str, Any]: def report_test_export(payload: dict[str, Any]) -> dict[str, Any]: """处理 Worker 测试回调:分析文件并生成推荐,绝不创建生产库存快照。""" run_no = str(payload.get('run_no') or '').strip() - run = ShippingInventoryConfigurationTestRun.query.filter_by(run_no=run_no).first() + run = FreightRpaOnhandConfigurationTestRun.query.filter_by(run_no=run_no).first() if run is None: - raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND') + raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.ONHAND_CONFIGURATION_TEST_NOT_FOUND') if run.status in {'completed', 'completed_empty', 'failed'}: return _payload(run) - source = db.session.get(ShippingInventorySource, run.inventory_source_id) + source = db.session.get(FreightRpaSource, run.source_id) if source is None or not _matches_current_configuration(run, source): run.status = 'failed'; run.stage = 'failed'; run.error_message = '库存站点配置已变更,请重新测试'; run.completed_at = datetime.utcnow() run.result_json = {**(run.result_json or {}), 'stale_configuration': True} @@ -335,7 +339,10 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]: status = str(payload.get('status') or 'success').lower() if status == 'empty': # 空库存是查询业务结果,不代表登录、报表路径或 RPA 执行失败。 - if source.parsing_profile is None or source.parsing_profile.status != 'published': + # s18 起解析方案绑定归 onhand_report_config 配置行;配置行缺失即未绑定。 + config = source.onhand_report_config + profile = config.parsing_profile if config is not None else None + if profile is None or profile.status != 'published': run.status = 'failed'; run.stage = 'failed'; run.error_message = '测试导出无库存数据,且尚未绑定已发布库存解析方案'; run.completed_at = datetime.utcnow() else: run.status = 'completed_empty'; run.stage = 'empty_data_pending_validation' @@ -343,8 +350,8 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]: 'export_result': 'empty', 'structure_validation': 'not_observed', 'data_validation': 'pending_first_non_empty_export', 'message': str(payload.get('message') or '库存查询成功但当前无库存数据')[:500], - 'confirmed_profile_id': source.parsing_profile_id, - 'confirmed_profile_checksum': source.parsing_profile.checksum, + 'confirmed_profile_id': profile.id, + 'confirmed_profile_checksum': profile.checksum, } run.completed_at = datetime.utcnow() db.session.commit() @@ -354,14 +361,14 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]: db.session.commit() return _payload(run) # Windows Worker 回传 C:\HxopsRpa...\inventory_drop\file.xlsx;Linux 后端必须映射到 - # FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR 下同名文件,否则 Path(windows).is_file() 恒假。 + # FREIGHT_RPA_SHARED_ONHAND_DROP_DIR 下同名文件,否则 Path(windows).is_file() 恒假。 raw_file_path = str(payload.get('file_path') or '').strip() path: Path | None = None - from app.services.shipping_notice.rpa import inventory_drop_dir - from app.services.shipping_notice.inventory_rpa_workflow import _resolve_shared_inventory_drop_file - drop_root = inventory_drop_dir() + from app.services.freight_rpa.onhand.trigger_io import onhand_drop_dir + from app.services.freight_rpa.onhand.workflow_protocol import resolve_shared_inventory_drop_file + drop_root = onhand_drop_dir() if drop_root is not None: - path = _resolve_shared_inventory_drop_file(raw_file_path, allowed_root=drop_root) + path = resolve_shared_inventory_drop_file(raw_file_path, allowed_root=drop_root) if path is None: candidate = Path(raw_file_path) if candidate.is_file(): @@ -370,12 +377,12 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]: run.status = 'failed'; run.stage = 'failed'; run.error_message = '测试导出文件不存在'; run.completed_at = datetime.utcnow() db.session.commit() return _payload(run) - from app.services.shipping_notice.inventory_structure_analysis import _analyse_path, serialize_analysis - from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix - from app.models import ShippingInventoryStructureAnalysis + from app.services.shipping_notice.onhand_structure_analysis import _analyse_path, serialize_analysis + from app.services.shipping_notice.onhand_file_store import resolve_inventory_upload_suffix + from app.models import FreightRpaOnhandStructureAnalysis import hashlib - from app.services.shipping_notice.inventory_structure_fingerprint import compatibility_fingerprint, exact_fingerprint, structure_definition - from app.services.shipping_notice.inventory_profile_matching import recommend_profiles + from app.services.shipping_notice.onhand_structure_fingerprint import compatibility_fingerprint, exact_fingerprint, structure_definition + from app.services.shipping_notice.onhand_profile_matching import recommend_profiles run.status = 'processing'; run.stage = 'analysing_structure'; db.session.flush() suffix = resolve_inventory_upload_suffix(path.name) @@ -384,7 +391,7 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]: # The RPA download is only read for analysis; configuration evidence never retains a second full workbook copy. structure, suggested, summary, warnings = _analyse_path(path, suffix) definition = structure_definition(file_format=suffix.lstrip('.'), sheet_name=structure.get('selected_sheet_name'), header_row_index=structure.get('selected_header_row_index') or 1, headers=structure.get('selected_headers', [])) - analysis = ShippingInventoryStructureAnalysis( + analysis = FreightRpaOnhandStructureAnalysis( source_kind='configuration_test', source_file_name=path.name, storage_path=None, file_checksum=hashlib.sha256(raw).hexdigest(), file_format=suffix.lstrip('.'), analysis_status='ready', structure_json=structure, suggested_mapping_json=suggested, validation_summary_json=summary, sample_rows_json=list(structure.get('selected_sample_rows') or []), warning_json=warnings, created_by=run.created_by, @@ -392,18 +399,22 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]: ) db.session.add(analysis); db.session.flush() analysis.match_result_json = recommend_profiles({'structure': structure, 'suggested_mapping': suggested, 'exact_structure_fingerprint': analysis.exact_structure_fingerprint, 'compatibility_fingerprint': analysis.compatibility_fingerprint}) + # s18 起当前绑定取自 onhand_report_config 配置行;配置行缺失即无当前方案可比。 + config = source.onhand_report_config + current_profile_id = config.parsing_profile_id if config is not None else None current_profile_candidate = next(( candidate for candidate in (analysis.match_result_json.get('candidates') or []) - if int(candidate.get('profile_id') or 0) == int(source.parsing_profile_id or 0) + if int(candidate.get('profile_id') or 0) == int(current_profile_id or 0) ), None) run.analysis_id = analysis.id; run.status = 'completed' if current_profile_candidate is not None: # 当前绑定的方案已验证时,直接写入确认事实;启用仍由管理员显式开关完成。 + current_profile = config.parsing_profile if config is not None else None run.stage = 'current_profile_verified' run.result_json = { 'analysis': serialize_analysis(analysis), - 'confirmed_profile_id': source.parsing_profile_id, - 'confirmed_profile_checksum': source.parsing_profile.checksum if source.parsing_profile else None, + 'confirmed_profile_id': current_profile_id, + 'confirmed_profile_checksum': current_profile.checksum if current_profile is not None else None, 'current_profile_verified': True, 'profile_match_level': current_profile_candidate.get('level'), } @@ -421,12 +432,12 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]: def report_batch_test_exports(payload: dict[str, Any]) -> dict[str, Any]: """接收批量 Worker 回调并逐项回写;未知运行标识只忽略,不影响同批其他站点。""" batch_id = int(payload.get('validation_batch_id') or 0) - batch = db.session.get(ShippingInventoryValidationBatch, batch_id) + batch = db.session.get(FreightRpaOnhandValidationBatch, batch_id) if batch is None: - raise NotFoundError('Inventory validation batch not found', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NOT_FOUND') + raise NotFoundError('Inventory validation batch not found', code='SHIPPING.ONHAND_VALIDATION_BATCH_NOT_FOUND') results = payload.get('results') or [] if not isinstance(results, list): - raise ValidationError('Batch results must be a list', code='SHIPPING.INVENTORY_VALIDATION_BATCH_INVALID') + raise ValidationError('Batch results must be a list', code='SHIPPING.ONHAND_VALIDATION_BATCH_INVALID') updated: list[dict[str, Any]] = [] ignored = 0 for item in results: @@ -434,7 +445,7 @@ def report_batch_test_exports(payload: dict[str, Any]) -> dict[str, Any]: ignored += 1 continue run_no = str(item.get('validation_run_no') or '').strip() - run = ShippingInventoryConfigurationTestRun.query.filter_by( + run = FreightRpaOnhandConfigurationTestRun.query.filter_by( run_no=run_no, validation_batch_id=batch.id, ).first() if run is None: @@ -459,22 +470,22 @@ def report_batch_test_progress(payload: dict[str, Any]) -> dict[str, Any]: batch_id = int(payload.get('validation_batch_id') or 0) run_no = str(payload.get('validation_run_no') or '').strip() if not batch_id or not run_no: - raise ValidationError('Batch id and validation run number are required', code='SHIPPING.INVENTORY_VALIDATION_PROGRESS_INVALID') - batch = db.session.get(ShippingInventoryValidationBatch, batch_id) + raise ValidationError('Batch id and validation run number are required', code='SHIPPING.ONHAND_VALIDATION_PROGRESS_INVALID') + batch = db.session.get(FreightRpaOnhandValidationBatch, batch_id) if batch is None: - raise NotFoundError('Inventory validation batch not found', code='SHIPPING.INVENTORY_VALIDATION_BATCH_NOT_FOUND') - run = ShippingInventoryConfigurationTestRun.query.filter_by( + raise NotFoundError('Inventory validation batch not found', code='SHIPPING.ONHAND_VALIDATION_BATCH_NOT_FOUND') + run = FreightRpaOnhandConfigurationTestRun.query.filter_by( run_no=run_no, validation_batch_id=batch.id, ).first() if run is None: - raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND') + raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.ONHAND_CONFIGURATION_TEST_NOT_FOUND') if run.status in {'completed', 'completed_empty', 'failed'}: return _payload(run) # 仅接受 Worker 领取后的执行阶段,防止外部回调任意覆盖运行状态。 stage = str(payload.get('stage') or 'rpa_exporting').strip().lower() if stage not in {'rpa_exporting'}: - raise ValidationError('Unsupported inventory validation progress stage', code='SHIPPING.INVENTORY_VALIDATION_PROGRESS_INVALID') + raise ValidationError('Unsupported inventory validation progress stage', code='SHIPPING.ONHAND_VALIDATION_PROGRESS_INVALID') run.status = 'processing' run.stage = stage run.result_json = {**(run.result_json or {}), 'worker_claimed_at': datetime.utcnow().isoformat()} @@ -485,28 +496,38 @@ def report_batch_test_progress(payload: dict[str, Any]) -> dict[str, Any]: def confirm_test_profile(source_id: int, run_no: str, profile_id: int, *, actor_id: int | None) -> dict[str, Any]: """管理员确认测试结果使用的已发布方案,才更新停用库存站点的解析方案绑定。""" - run = ShippingInventoryConfigurationTestRun.query.filter_by(inventory_source_id=source_id, run_no=run_no).first() + run = FreightRpaOnhandConfigurationTestRun.query.filter_by(source_id=source_id, run_no=run_no).first() if run is None or run.status != 'completed' or run.analysis_id is None: - raise ConflictError('Configuration test is not ready for confirmation', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_READY') - source = db.session.get(ShippingInventorySource, source_id) - profile = db.session.get(ShippingInventoryParsingProfile, profile_id) + raise ConflictError('Configuration test is not ready for confirmation', code='SHIPPING.ONHAND_CONFIGURATION_TEST_NOT_READY') + source = db.session.get(FreightRpaSource, source_id) + profile = db.session.get(FreightRpaParsingProfile, profile_id) if source is None or profile is None or profile.status != 'published': - raise ValidationError('Published parsing profile is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED') + raise ValidationError('Published parsing profile is required', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED') if ( source.enabled or source.config_version != run.source_config_version or source.rpa_profile is None or source.rpa_profile.config_version != run.rpa_profile_config_version ): - raise ConflictError('Inventory Source configuration changed', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_STALE') - from app.services.shipping_notice.inventory_structure_analysis import adopt_published_profile + raise ConflictError('Inventory Source configuration changed', code='SHIPPING.ONHAND_CONFIGURATION_TEST_STALE') + from app.services.shipping_notice.onhand_structure_analysis import adopt_published_profile adopt_published_profile(run.analysis_id, profile_id) - source.parsing_profile_id = profile.id + # s18 起解析绑定写 onhand_report_config 配置行(无则插入),站点行不再承载该外键; + # 与 freight_rpa_source_admin_service.bind_source_parsing_profile 的批量绑定写序保持同构。 + config = source.onhand_report_config + if config is None: + config = FreightRpaOnhandReportConfig(source=source) + config.created_by = actor_id + db.session.add(config) + else: + config.config_version += 1 + config.parsing_profile_id = profile.id + config.updated_by = actor_id source.updated_by = actor_id source.config_version += 1 run.source_config_version = source.config_version run.rpa_profile_config_version = source.rpa_profile.config_version run.result_json = {**(run.result_json or {}), 'confirmed_profile_id': profile.id, 'confirmed_profile_checksum': profile.checksum} db.session.commit() - return {'test_run': _payload(run), 'parsing_profile_id': source.parsing_profile_id} + return {'test_run': _payload(run), 'parsing_profile_id': config.parsing_profile_id} diff --git a/backend/app/services/shipping_notice/inventory_external_mapping.py b/backend/app/services/shipping_notice/onhand_external_mapping.py similarity index 71% rename from backend/app/services/shipping_notice/inventory_external_mapping.py rename to backend/app/services/shipping_notice/onhand_external_mapping.py index 9e0ef723..2836c9b1 100644 --- a/backend/app/services/shipping_notice/inventory_external_mapping.py +++ b/backend/app/services/shipping_notice/onhand_external_mapping.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/inventory_external_mapping.py +services/shipping_notice/onhand_external_mapping.py 用途:解析库存来源与已确定 Warehouse 对应的外部系统仓库。 -依赖:ShippingInventoryExternalMapping、ShippingInventorySource。 +依赖:FreightRpaOnhandExternalMapping、FreightRpaSource。 逻辑:Excel 与后续调拨 Agent 可复用本内部服务;本模块不提供 Tool API,也不决定是否调拨。 """ @@ -10,7 +10,7 @@ from __future__ import annotations from typing import Any -from app.models import ShippingInventoryExternalMapping, ShippingInventorySource +from app.models import FreightRpaOnhandExternalMapping, FreightRpaSource def resolve_external_warehouse(*, source_code: str | None, freight_warehouse_id: str | None) -> dict[str, Any] | None: @@ -19,12 +19,12 @@ def resolve_external_warehouse(*, source_code: str | None, freight_warehouse_id: warehouse = str(freight_warehouse_id or '').strip().upper() if not code: return None - source = ShippingInventorySource.query.filter_by(source_code=code, enabled=True).first() + source = FreightRpaSource.query.filter_by(source_code=code, enabled=True).first() if source is None: return None - query = ShippingInventoryExternalMapping.query.filter_by(inventory_source_id=source.id, enabled=True) + query = FreightRpaOnhandExternalMapping.query.filter_by(source_id=source.id, enabled=True) mapping = query.filter_by(freight_warehouse_id=warehouse).first() if warehouse else None - mapping = mapping or query.filter(ShippingInventoryExternalMapping.freight_warehouse_id.is_(None)).first() + mapping = mapping or query.filter(FreightRpaOnhandExternalMapping.freight_warehouse_id.is_(None)).first() if mapping is None: return None return { diff --git a/backend/app/services/shipping_notice/inventory_field_catalog.py b/backend/app/services/shipping_notice/onhand_field_catalog.py similarity index 77% rename from backend/app/services/shipping_notice/inventory_field_catalog.py rename to backend/app/services/shipping_notice/onhand_field_catalog.py index 08312c6a..f81baecc 100644 --- a/backend/app/services/shipping_notice/inventory_field_catalog.py +++ b/backend/app/services/shipping_notice/onhand_field_catalog.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/inventory_field_catalog.py +services/shipping_notice/onhand_field_catalog.py 用途:维护货代库存统一业务字段目录,供后续库存解析方案和发货模板安全引用。 -依赖:ShippingInventoryField、统一业务异常和 SQLAlchemy 事务。 +依赖:FreightRpaOnhandField、统一业务异常和 SQLAlchemy 事务。 逻辑:目录初始为空;管理员维护字段名称与业务用途,引用保护只依据实际配置和历史使用情况。 """ @@ -14,14 +14,14 @@ from typing import Any from app.core.errors import ConflictError, NotFoundError, ValidationError from app.extensions import db -from app.models import ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryParsingProfile +from app.models import ShippingExcelTemplate, FreightRpaOnhandField, FreightRpaParsingProfile ALLOWED_VALUE_TYPES = {'text', 'integer', 'decimal', 'date'} ALLOWED_USAGE_TYPES = {'match_identity', 'inventory_quantity', 'warehouse_identity', 'general'} -def _payload(item: ShippingInventoryField) -> dict[str, Any]: +def _payload(item: FreightRpaOnhandField) -> dict[str, Any]: """输出业务字段目录记录,不向管理端暴露内部字段编码。""" return { 'id': item.id, @@ -38,15 +38,15 @@ def _payload(item: ShippingInventoryField) -> dict[str, Any]: def list_fields(*, include_retired: bool = False) -> list[dict[str, Any]]: """按业务展示顺序返回库存字段目录;当前配置默认不显示已归档字段。""" - query = ShippingInventoryField.query + query = FreightRpaOnhandField.query if not include_retired: query = query.filter_by(status='active') return [_payload(item) for item in query.order_by( - ShippingInventoryField.sort_order, ShippingInventoryField.id, + FreightRpaOnhandField.sort_order, FreightRpaOnhandField.id, ).all()] -def _normalized_payload(data: dict[str, Any], *, existing: ShippingInventoryField | None = None) -> dict[str, Any]: +def _normalized_payload(data: dict[str, Any], *, existing: FreightRpaOnhandField | None = None) -> dict[str, Any]: """校验管理员输入,稳定编码只在创建时由显示名称生成并在后台保存。""" display_name = str(data.get('display_name') or '').strip() description = str(data.get('description') or '').strip() or None @@ -55,11 +55,11 @@ def _normalized_payload(data: dict[str, Any], *, existing: ShippingInventoryFiel try: sort_order = int(data.get('sort_order') if data.get('sort_order') is not None else 100) except (TypeError, ValueError) as exc: - raise ValidationError('Inventory field sort_order is invalid', code='SHIPPING.INVENTORY_FIELD_INVALID') from exc + raise ValidationError('Inventory field sort_order is invalid', code='SHIPPING.ONHAND_FIELD_INVALID') from exc if not display_name or len(display_name) > 128 or value_type not in ALLOWED_VALUE_TYPES or usage_type not in ALLOWED_USAGE_TYPES: - raise ValidationError('Inventory field data is invalid', code='SHIPPING.INVENTORY_FIELD_INVALID') + raise ValidationError('Inventory field data is invalid', code='SHIPPING.ONHAND_FIELD_INVALID') if sort_order < 0 or sort_order > 9999: - raise ValidationError('Inventory field sort_order is invalid', code='SHIPPING.INVENTORY_FIELD_INVALID') + raise ValidationError('Inventory field sort_order is invalid', code='SHIPPING.ONHAND_FIELD_INVALID') return { 'display_name': display_name, 'description': description, @@ -78,7 +78,7 @@ def _field_code(display_name: str) -> str: stem = stem[:52] code = stem sequence = 2 - while ShippingInventoryField.query.filter_by(field_code=code).first() is not None: + while FreightRpaOnhandField.query.filter_by(field_code=code).first() is not None: suffix = f'_{sequence}' code = f'{stem[:64 - len(suffix)]}{suffix}' sequence += 1 @@ -88,9 +88,9 @@ def _field_code(display_name: str) -> str: def create_field(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: """创建用户定义的库存字段;内部编码仅供审计,不参与运行判断。""" values = _normalized_payload(data) - if ShippingInventoryField.query.filter_by(display_name=values['display_name']).first() is not None: - raise ConflictError('Inventory field display name already exists', code='SHIPPING.INVENTORY_FIELD_CONFLICT') - item = ShippingInventoryField( + if FreightRpaOnhandField.query.filter_by(display_name=values['display_name']).first() is not None: + raise ConflictError('Inventory field display name already exists', code='SHIPPING.ONHAND_FIELD_CONFLICT') + item = FreightRpaOnhandField( field_code=_field_code(values['display_name']), status='active', created_by=actor_id, updated_by=actor_id, **values, ) @@ -101,24 +101,24 @@ def create_field(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any def update_field(field_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: """更新未退役字段;存在运行配置引用时禁止改变数据格式或业务用途。""" - item = db.session.get(ShippingInventoryField, field_id) + item = db.session.get(FreightRpaOnhandField, field_id) if item is None: - raise NotFoundError('Inventory field not found', code='SHIPPING.INVENTORY_FIELD_NOT_FOUND') + raise NotFoundError('Inventory field not found', code='SHIPPING.ONHAND_FIELD_NOT_FOUND') if item.status != 'active': - raise ConflictError('Retired inventory field cannot be edited', code='SHIPPING.INVENTORY_FIELD_IMMUTABLE') + raise ConflictError('Retired inventory field cannot be edited', code='SHIPPING.ONHAND_FIELD_IMMUTABLE') values = _normalized_payload(data, existing=item) references = _runtime_references(item.id) if references and (values['value_type'] != item.value_type or values['usage_type'] != item.usage_type): raise ConflictError( 'Referenced inventory field type or usage cannot be changed', - code='SHIPPING.INVENTORY_FIELD_IMMUTABLE', details={'references': references}, + code='SHIPPING.ONHAND_FIELD_IMMUTABLE', details={'references': references}, ) - duplicate = ShippingInventoryField.query.filter( - ShippingInventoryField.display_name == values['display_name'], - ShippingInventoryField.id != item.id, + duplicate = FreightRpaOnhandField.query.filter( + FreightRpaOnhandField.display_name == values['display_name'], + FreightRpaOnhandField.id != item.id, ).first() if duplicate is not None: - raise ConflictError('Inventory field display name already exists', code='SHIPPING.INVENTORY_FIELD_CONFLICT') + raise ConflictError('Inventory field display name already exists', code='SHIPPING.ONHAND_FIELD_CONFLICT') for key, value in values.items(): setattr(item, key, value) item.updated_by = actor_id @@ -128,14 +128,14 @@ def update_field(field_id: int, data: dict[str, Any], *, actor_id: int | None) - def delete_field(field_id: int) -> dict[str, Any]: """物理删除从未被配置引用的用户字段。""" - item = db.session.get(ShippingInventoryField, field_id) + item = db.session.get(FreightRpaOnhandField, field_id) if item is None: - raise NotFoundError('Inventory field not found', code='SHIPPING.INVENTORY_FIELD_NOT_FOUND') + raise NotFoundError('Inventory field not found', code='SHIPPING.ONHAND_FIELD_NOT_FOUND') references = _runtime_references(item.id) if references: raise ConflictError( 'Inventory field is referenced by runtime configuration', - code='SHIPPING.INVENTORY_FIELD_DELETE_BLOCKED', details={'references': references}, + code='SHIPPING.ONHAND_FIELD_DELETE_BLOCKED', details={'references': references}, ) db.session.delete(item) db.session.commit() @@ -144,14 +144,14 @@ def delete_field(field_id: int) -> dict[str, Any]: def retire_field(field_id: int) -> dict[str, Any]: """退役不再用于新配置的用户字段;被当前配置引用时必须先解除引用。""" - item = db.session.get(ShippingInventoryField, field_id) + item = db.session.get(FreightRpaOnhandField, field_id) if item is None: - raise NotFoundError('Inventory field not found', code='SHIPPING.INVENTORY_FIELD_NOT_FOUND') + raise NotFoundError('Inventory field not found', code='SHIPPING.ONHAND_FIELD_NOT_FOUND') references = _runtime_references(item.id) if references: raise ConflictError( 'Inventory field is referenced by runtime configuration', - code='SHIPPING.INVENTORY_FIELD_RETIRE_BLOCKED', details={'references': references}, + code='SHIPPING.ONHAND_FIELD_RETIRE_BLOCKED', details={'references': references}, ) item.status = 'retired' db.session.commit() @@ -163,8 +163,8 @@ def _runtime_references(field_id: int) -> list[str]: reference = str(field_id) parsing_profiles = [ f'parsing_profile:{item.profile_code}:v{item.version}' - for item in ShippingInventoryParsingProfile.query.filter( - ShippingInventoryParsingProfile.status.in_(['draft', 'published']), + for item in FreightRpaParsingProfile.query.filter( + FreightRpaParsingProfile.status.in_(['draft', 'published']), ).all() if reference in { str(key) for key in ((item.definition_json or {}).get('field_mapping') or {}).keys() diff --git a/backend/app/services/shipping_notice/inventory_file_identity.py b/backend/app/services/shipping_notice/onhand_file_identity.py similarity index 97% rename from backend/app/services/shipping_notice/inventory_file_identity.py rename to backend/app/services/shipping_notice/onhand_file_identity.py index 95317804..2ada90e3 100644 --- a/backend/app/services/shipping_notice/inventory_file_identity.py +++ b/backend/app/services/shipping_notice/onhand_file_identity.py @@ -1,5 +1,5 @@ """ -services/shipping_notice/inventory_file_identity.py +services/shipping_notice/onhand_file_identity.py 用途:校验库存 Excel/CSV 文件内容与任务/快照预期库位是否一致。 依赖:openpyxl、xlrd、csv、app.core.errors.AppError。 @@ -301,7 +301,7 @@ def assert_inventory_excel_warehouse_identity( expected = str(expected_warehouse_id or "").strip().upper() if not expected: raise AppError( - code="SHIPPING.INVENTORY_IDENTITY_MISMATCH", + code="SHIPPING.ONHAND_IDENTITY_MISMATCH", message="预期库位为空,无法校验库存文件内容", http_status=409, details={"operation": operation}, @@ -310,7 +310,7 @@ def assert_inventory_excel_warehouse_identity( suffix = path.suffix.lower() if suffix not in {".xls", ".xlsx", ".csv"}: raise AppError( - code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED", + code="SHIPPING.ONHAND_FILE_FORMAT_UNSUPPORTED", message="库存源身份校验仅支持 .xls / .xlsx / .csv", http_status=409, details={"operation": operation, "file_suffix": suffix}, @@ -319,14 +319,14 @@ def assert_inventory_excel_warehouse_identity( found = extract_warehouse_ids_from_inventory_excel(path) if not found: raise AppError( - code="SHIPPING.INVENTORY_FILE_WAREHOUSE_MISSING", + code="SHIPPING.ONHAND_FILE_WAREHOUSE_MISSING", message="库存文件缺少可识别的 Warehouse ID 列或数据,已拒绝入库", http_status=409, details={"operation": operation, "expected_warehouse_id": expected}, ) if len(found) > 1: raise AppError( - code="SHIPPING.INVENTORY_FILE_WAREHOUSE_MIXED", + code="SHIPPING.ONHAND_FILE_WAREHOUSE_MIXED", message="库存文件包含多个 Warehouse ID,已拒绝入库", http_status=409, details={ @@ -338,7 +338,7 @@ def assert_inventory_excel_warehouse_identity( actual = next(iter(found)) if actual != expected: raise AppError( - code="SHIPPING.INVENTORY_IDENTITY_MISMATCH", + code="SHIPPING.ONHAND_IDENTITY_MISMATCH", message=f"库存文件 Warehouse ID={actual} 与任务预期库位 {expected} 不一致,已拒绝入库", http_status=409, details={ diff --git a/backend/app/services/shipping_notice/inventory_file_store.py b/backend/app/services/shipping_notice/onhand_file_store.py similarity index 72% rename from backend/app/services/shipping_notice/inventory_file_store.py rename to backend/app/services/shipping_notice/onhand_file_store.py index 3961be88..f32a8a41 100644 --- a/backend/app/services/shipping_notice/inventory_file_store.py +++ b/backend/app/services/shipping_notice/onhand_file_store.py @@ -1,9 +1,11 @@ """ -services/shipping_notice/inventory_file_store.py +services/shipping_notice/onhand_file_store.py -用途:管理货代发货任务库存快照文件、任务 link 与解析结果投影。 -依赖:models.ShippingInventoryFile/ShippingTaskInventoryLink、inventory_snapshot、export._storage_root。 -逻辑:inventory_workflow 上传或解析库存时写入库存快照(Link 挂在正式 OT); +用途:管理货代发货任务库存快照文件、任务 link 与解析结果投影;构造下载展示名 + (build_inventory_download_name:企微压缩包短名规则 + exported_at 数据截止时间点)。 +依赖:models.FreightRpaOnhandReportFile/ShippingTaskOnhandLink(只读/查询取回,禁止构造)、 + freight_rpa/onhand/report_store(快照行插入唯一入口)、onhand_snapshot、export._storage_root。 +逻辑:onhand_workflow 上传或解析库存时写入库存快照(Link 挂在正式 OT); fulfillment_workflow / Excel 导出经 resolve_inventory_lines_for_execution: 冻结候选读所属 OT 的 prepare 合并行(传入 Notice 时回源 order_task_id),单源读 active Link 文件; 禁止用 Notice.id 漏读 OT Link,导出数据源不得偏离行级匹配门禁命中的候选事实。 @@ -15,6 +17,7 @@ import re import hashlib import shutil import uuid +from datetime import datetime from pathlib import Path from typing import Any @@ -23,24 +26,25 @@ from werkzeug.datastructures import FileStorage from app import db from app.core.errors import AppError from app.models import ( - ShippingInventoryFile, + FreightRpaOnhandReportFile, ShippingNotice, - ShippingNoticeLineInventoryMatch, + ShippingNoticeLineOnhandMatch, ShippingOrderSnapshot, ShippingTaskEvent, - ShippingTaskInventoryLink, + ShippingTaskOnhandLink, ) from app.services.shipping_notice.tool_common import task_event_task_id +from app.services.freight_rpa.onhand.report_store import insert_onhand_report, update_onhand_report from app.services.shipping_notice.export import _storage_root -from app.services.shipping_notice.inventory_snapshot import ( +from app.services.shipping_notice.onhand_snapshot import ( parse_inventory_excel_with_meta, read_inventory_schema_preview, ) -from app.services.shipping_notice.inventory_source_gate import ( +from app.services.shipping_notice.onhand_source_gate import ( is_inventory_source_stable, task_inventory_identity, ) -from app.services.shipping_notice.inventory_source_repository import ( +from app.services.shipping_notice.onhand_source_repository import ( get_database_inventory_source, inventory_sources_runtime_version, ) @@ -77,7 +81,7 @@ def resolve_inventory_upload_suffix(filename: str) -> str: name = str(filename or "").strip().lower() if not name or "." not in name: raise AppError( - code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED", + code="SHIPPING.ONHAND_FILE_FORMAT_UNSUPPORTED", message="库存上传缺少可识别的文件后缀", http_status=409, ) @@ -88,7 +92,7 @@ def resolve_inventory_upload_suffix(filename: str) -> str: if name.endswith(".xls"): return ".xls" raise AppError( - code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED", + code="SHIPPING.ONHAND_FILE_FORMAT_UNSUPPORTED", message="库存上传仅支持 .xls / .xlsx / .csv", http_status=409, ) @@ -143,11 +147,11 @@ def delete_inventory_storage_path(storage_path: str | Path | None) -> None: pass -def active_inventory_file_for_task(task: ShippingNotice) -> ShippingInventoryFile | None: +def active_inventory_file_for_task(task: ShippingNotice) -> FreightRpaOnhandReportFile | None: """ 读取任务当前 active link 指向的库存快照。 - 核心逻辑:``ShippingTaskInventoryLink.task_id`` 挂在正式 OT 上;传入 + 核心逻辑:``ShippingTaskOnhandLink.task_id`` 挂在正式 OT 上;传入 ``ShippingNotice`` 时使用 ``order_task_id``,OT 自身使用 ``id``。 Args: @@ -161,12 +165,12 @@ def active_inventory_file_for_task(task: ShippingNotice) -> ShippingInventoryFil if task_id is None: return None link = ( - ShippingTaskInventoryLink.query.filter_by( + ShippingTaskOnhandLink.query.filter_by( task_id=int(task_id), is_active=True, invalidated_at=None, ) - .order_by(ShippingTaskInventoryLink.id.desc()) + .order_by(ShippingTaskOnhandLink.id.desc()) .first() ) return link.inventory_file if link else None @@ -190,14 +194,92 @@ def resolve_task_inventory_download(task: ShippingNotice) -> tuple[Path, str] | path = Path(storage_path).resolve() if not path.is_file(): return None - filename = str(inv_file.source_file_name or f'{inv_file.inventory_file_no}{path.suffix or ".xlsx"}').strip() + filename = build_inventory_download_name( + inv_file, source_file_name=inv_file.source_file_name, path=path, + ) return path, filename -def read_inventory_file_lines(inv_file: ShippingInventoryFile) -> tuple[list[dict[str, Any]], dict[str, Any]]: +_DOWNLOAD_SEQ_PREFIX_RE = re.compile(r'^(\d{1,4})_') +_DOWNLOAD_RUN_TS_RE = re.compile(r'RUN(\d{8,14})') +# 规范名形态:{seq}_{source}_{warehouse}_{12位时间}.<后缀>。source/warehouse 为单 token +# ([^_]+,\w 会把下划线吞进段里导致 worker 长名被误判为规范名);时间固定 12 位 +# (exported_at / rpa_run_no / mtime 三条回退路径均格式化为 %Y%m%d%H%M)。命中即原样返回。 +_DOWNLOAD_CANONICAL_RE = re.compile(r'^\d{1,4}_[^_]+_[^_]+_\d{12}\.[A-Za-z0-9]{3,5}$') +_DOWNLOAD_NAME_SANITIZE_RE = re.compile(r'[^\w.\-]+') + + +def build_inventory_download_name( + inv_file: FreightRpaOnhandReportFile, + *, + source_file_name: str | None, + path: Path | None = None, +) -> str: + """构造库存快照的下载展示名:复用企微压缩包短名规则并附加数据截止时间点。 + + 【AI 触发时机】:任务级/行级库存文件下载接口构造 download_name 时调用; + 上传、解析、匹配链路禁止使用——登记名 source_file_name 保持 worker 原始名作审计。 + + 核心逻辑:目标格式 `{seq}_{source}_{warehouse}_{yyyyMMddHHmm}.xlsx`(seq 取 worker + 原名前缀,与企微压缩包内文件一一对应,取不到则省略);时间点取 exported_at + (数据截止时刻),缺失时回退 rpa_run_no 内嵌 RUN 时间戳,再回退托管文件 mtime; + warehouse 连续重复段去重(AWSDU_AWSDU → AWSDU);已是规范名或 source/warehouse + 信息不足时原样返回(幂等,禁止凭空造名)。 + + Args: + inv_file: 库存快照行(source_code/warehouse_id/warehouse_code/exported_at/rpa_run_no)。 + source_file_name: worker 原始文件名(如 006_inventory_RUN…_DSV360_AWSDU_AWSDU_….xlsx)。 + path: 托管文件路径;exported_at 与 rpa_run_no 均缺失时用其 mtime 兜底时间点。 + + Returns: + 下载展示文件名;worker 原始名缺失时回退 inventory_file_no + 后缀(既有行为)。 + """ + base = str(source_file_name or '').strip() + if not base: + suffix = Path(path or base).suffix or '.xlsx' + return f'{inv_file.onhand_file_no}{suffix.lower()}' + if _DOWNLOAD_CANONICAL_RE.match(base): + return base + seq_match = _DOWNLOAD_SEQ_PREFIX_RE.match(base) + seq = f"{int(seq_match.group(1)):03d}" if seq_match else '' + source = str(inv_file.source_code or '').strip() + warehouse_candidates = [ + str(inv_file.warehouse_id or '').strip(), + str(inv_file.warehouse_code or '').strip(), + ] + warehouse = next((item for item in warehouse_candidates if item), '') + timestamp = '' + if inv_file.exported_at is not None: + timestamp = inv_file.exported_at.strftime('%Y%m%d%H%M') + if not timestamp: + run_ts = _DOWNLOAD_RUN_TS_RE.search(str(inv_file.rpa_run_no or '')) + if run_ts: + timestamp = run_ts.group(1)[:12] + if not timestamp and path is not None: + try: + timestamp = datetime.fromtimestamp(path.stat().st_mtime).strftime('%Y%m%d%H%M') + except OSError: + timestamp = '' + parts = [part for part in (seq, source, warehouse, timestamp) if part] + if not source or not warehouse or not timestamp or not parts: + # source/warehouse/时间点任一缺失都不足以构造规范名,保持原名避免误导。 + return base + sanitized = [_DOWNLOAD_NAME_SANITIZE_RE.sub('_', part).strip('_') for part in parts] + # token 级连续重复去重(worker 曾把 site+warehouse 同值拼成 AWSDU_AWSDU): + # 按下划线拆开折叠相邻重复段,同时覆盖段内与跨段重复。 + tokens: list[str] = [] + for part in sanitized: + for token in part.split('_'): + if token and (not tokens or tokens[-1] != token): + tokens.append(token) + suffix = Path(base).suffix or '.xlsx' + return "_".join(tokens) + suffix.lower() + + +def read_inventory_file_lines(inv_file: FreightRpaOnhandReportFile) -> tuple[list[dict[str, Any]], dict[str, Any]]: """读取库存文件的唯一行事实;缓存为空时按已发布解析方案解析并固化到文件层。""" cached_rows = [ - row for row in (inv_file.inventory_lines_json or []) if isinstance(row, dict) + row for row in (inv_file.onhand_lines_json or []) if isinstance(row, dict) ] if cached_rows: return cached_rows, {'source': 'inventory_file_cache'} @@ -205,7 +287,7 @@ def read_inventory_file_lines(inv_file: ShippingInventoryFile) -> tuple[list[dic rows, column_meta = parse_inventory_snapshot_file(inv_file) rows = [row for row in rows if isinstance(row, dict)] if rows: - inv_file.inventory_lines_json = rows + inv_file.onhand_lines_json = rows inv_file.line_count = len(rows) db.session.flush() return rows, column_meta @@ -231,7 +313,7 @@ def resolve_inventory_lines_for_execution( """ 解析库存匹配与导出的统一运行输入。 - 核心逻辑:已冻结候选源时优先 ``prepare_candidate_inventory_lines`` 合并各源 + 核心逻辑:已冻结候选源时优先 ``prepare_candidate_onhand_lines`` 合并各源 ready 快照(带 ``__source_code``),避免依赖把合并行写进单份共享 File; 否则读当前 active Link 文件行;无 Link 时才允许 legacy payload。 @@ -246,19 +328,19 @@ def resolve_inventory_lines_for_execution( # Notice 主键 ≠ OT 且不带候选集指针;冻结候选事实统一回源所属 OT 读取, # 防止导出路径把多源任务退化成单源 Link,出现「行匹配过门禁但生成 Excel 失败」。 from app.models import ShippingOrderTask - from app.services.shipping_notice.stp_inventory_freeze import ( - task_frozen_inventory_source_codes, + from app.services.shipping_notice.stp_onhand_freeze import ( + task_frozen_onhand_source_codes, ) - from app.services.shipping_notice.stp_line_inventory_match import ( - prepare_candidate_inventory_lines, + from app.services.shipping_notice.stp_line_onhand_match import ( + prepare_candidate_onhand_lines, ) owner_task = task order_task_id = getattr(task, 'order_task_id', None) if order_task_id: owner_task = db.session.get(ShippingOrderTask, int(order_task_id)) or task - if len(task_frozen_inventory_source_codes(owner_task)) >= 1: - prep = prepare_candidate_inventory_lines(owner_task) + if len(task_frozen_onhand_source_codes(owner_task)) >= 1: + prep = prepare_candidate_onhand_lines(owner_task) if prep.get('status') == 'ready': rows = [row for row in list(prep.get('lines') or []) if isinstance(row, dict)] if rows: @@ -293,12 +375,12 @@ def has_ready_inventory_file_for_task(task: ShippingNotice) -> bool: ) -def current_inventory_matches_for_task(task: ShippingNotice) -> list[ShippingNoticeLineInventoryMatch]: +def current_inventory_matches_for_task(task: ShippingNotice) -> list[ShippingNoticeLineOnhandMatch]: """读取 OT 当前有效的行级库存匹配事实。""" task_id = getattr(task, 'id', None) if task_id is None: return [] - return ShippingNoticeLineInventoryMatch.query.filter_by( + return ShippingNoticeLineOnhandMatch.query.filter_by( task_id=int(task_id), is_current=True, ).all() @@ -348,7 +430,7 @@ def _same_stable_inventory_identity(lhs: ShippingNotice, rhs: ShippingNotice) -> ) -def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> ShippingInventoryFile: +def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> FreightRpaOnhandReportFile: """ 保存库存 Excel 并创建任务级库存快照。 @@ -358,7 +440,7 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi """ if not is_inventory_source_stable(task): raise AppError( - code="SHIPPING.INVENTORY_SOURCE_GATE_BLOCKED", + code="SHIPPING.ONHAND_SOURCE_GATE_BLOCKED", message="库存源尚未稳定,拒绝保存库存上传文件", http_status=409, ) @@ -374,7 +456,7 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi path.parent.mkdir(parents=True, exist_ok=True) try: upload.save(str(path)) - from app.services.shipping_notice.inventory_structure_drift import validate_production_inventory_structure + from app.services.shipping_notice.onhand_structure_drift import validate_production_inventory_structure structure_check = validate_production_inventory_structure(source_code=source_code, path=path) inventory_lines, column_meta = parse_inventory_excel_with_meta( @@ -395,7 +477,7 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi }) if not inventory_lines: raise AppError( - code='SHIPPING.INVENTORY_FILE_EMPTY', + code='SHIPPING.ONHAND_FILE_EMPTY', message='库存文件没有可用于匹配的有效库存数据', http_status=409, ) @@ -422,8 +504,10 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi pass raise - inv_file = ShippingInventoryFile( - inventory_file_no=inventory_file_no, + # [STEP] 阶段 B Task 5:快照行插入收敛进 freight_rpa/onhand/report_store(只 flush 不 commit), + # 本模块拿回 file_id 后按主键取回 ORM 对象,身份校验失败回滚删除仍按 ORM 行操作。 + saved_file_id = insert_onhand_report( + onhand_file_no=inventory_file_no, user_id=task.user_id, source_file_name=str(upload.filename or "").strip() or path.name, storage_path=str(path), @@ -431,7 +515,7 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi schema_preview_json=preview, share_mode="task_only", line_count=len(inventory_lines), - inventory_lines_json=inventory_lines, + onhand_lines_json=inventory_lines, field_mapping_json=dict(structure_check['field_mapping']), mapping_source='parsing_profile', mapping_confirmed=True, @@ -446,8 +530,7 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi snapshot_status="ready", exported_at=datetime.utcnow(), ) - db.session.add(inv_file) - db.session.flush() + inv_file = db.session.get(FreightRpaOnhandReportFile, saved_file_id) candidates = [task] linked_tasks = [ @@ -455,9 +538,9 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi for item in candidates if _can_relink_inventory(item) and _same_stable_inventory_identity(task, item) ] - from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task + from app.services.shipping_notice.onhand_snapshot_store import link_snapshot_to_task - created_links: list[ShippingTaskInventoryLink] = [] + created_links: list[ShippingTaskOnhandLink] = [] for item in linked_tasks: link = link_snapshot_to_task( item, @@ -481,13 +564,14 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi "failed to delete inventory upload after link failure %s", path ) raise AppError( - code="SHIPPING.INVENTORY_IDENTITY_MISMATCH", + code="SHIPPING.ONHAND_IDENTITY_MISMATCH", message=f"任务 {item.task_no} 与库存快照身份不一致,已拒绝快照绑定", http_status=409, ) created_links.append(link) if len(linked_tasks) > 1: - inv_file.share_mode = "batch_same_identity" + # [STEP] 阶段 B Task 5:多票同身份共用时改写 share_mode 也经 report_store 更新(同一 ORM 对象,行为不变)。 + update_onhand_report(inv_file.id, share_mode="batch_same_identity") return inv_file @@ -496,13 +580,13 @@ def save_task_inventory_file_from_local_path( source_path: str | Path, *, source_file_name: str | None = None, -) -> ShippingInventoryFile: +) -> FreightRpaOnhandReportFile: """ 将本地已有库存文件纳入统一库存快照模型,并为当前任务建立 active link。 - 【AI 触发时机】:RPA 回调或后台导入已拿到本地 Excel,需要补建 ShippingInventoryFile 记录时调用。 + 【AI 触发时机】:RPA 回调或后台导入已拿到本地 Excel,需要补建 FreightRpaOnhandReportFile 记录时调用。 核心逻辑:复制本地文件到 inventory_file_no 对应标准目录,生成 schema preview, - 再创建 task_only 的 ShippingInventoryFile 与 active ShippingTaskInventoryLink。 + 再创建 task_only 的 FreightRpaOnhandReportFile 与 active ShippingTaskOnhandLink。 Args: task: 当前发货任务,用于绑定 user/batch 与 active link。 @@ -510,7 +594,7 @@ def save_task_inventory_file_from_local_path( source_file_name: 展示给用户/审计的原始文件名;为空时回退源文件名。 Returns: - ShippingInventoryFile: 已持久化的库存快照对象。 + FreightRpaOnhandReportFile: 已持久化的库存快照对象。 Raises: FileNotFoundError: 源文件不存在时抛出。 @@ -527,8 +611,10 @@ def save_task_inventory_file_from_local_path( preview = read_inventory_schema_preview(path) preview["upload_filename"] = str(source_file_name or source.name or path.name).strip() or path.name - inv_file = ShippingInventoryFile( - inventory_file_no=inventory_file_no, + # [STEP] 阶段 B Task 5:行插入收敛进 freight_rpa/onhand/report_store(只 flush 不 commit), + # 拿回 file_id 后取回 ORM 对象并交由 replace_task_inventory_link 建立 active link(link 表留在发货域)。 + saved_file_id = insert_onhand_report( + onhand_file_no=inventory_file_no, user_id=task.user_id, source_file_name=str(source_file_name or source.name or path.name).strip() or path.name, storage_path=str(path), @@ -538,27 +624,26 @@ def save_task_inventory_file_from_local_path( line_count=0, source_query_json={'trigger_type': 'manual_upload'}, ) - db.session.add(inv_file) - db.session.flush() + inv_file = db.session.get(FreightRpaOnhandReportFile, saved_file_id) replace_task_inventory_link(task, inv_file, role="owner") return inv_file def replace_task_inventory_link( task: ShippingNotice, - inv_file: ShippingInventoryFile, + inv_file: FreightRpaOnhandReportFile, *, role: str = "member", -) -> ShippingTaskInventoryLink: +) -> ShippingTaskOnhandLink: """替换任务 active 库存 link,保留历史 link 审计。""" if task.id is None: db.session.flush() - existing = ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).all() + existing = ShippingTaskOnhandLink.query.filter_by(task_id=task.id, is_active=True).all() for link in existing: link.is_active = False - new_link = ShippingTaskInventoryLink( + new_link = ShippingTaskOnhandLink( task_id=task.id, - inventory_file_id=inv_file.id, + onhand_file_id=inv_file.id, link_role=role, access_mode="readonly", linked_by_user_id=inv_file.user_id, @@ -569,7 +654,7 @@ def replace_task_inventory_link( task_id=task_event_task_id(task), event_type="inventory_file_linked", detail_json={ - "inventory_file_no": inv_file.inventory_file_no, + "inventory_file_no": inv_file.onhand_file_no, "role": role, "share_mode": inv_file.share_mode, }, @@ -587,14 +672,14 @@ def read_linked_inventory_schema_preview(task: ShippingNotice) -> dict[str, Any] return dict(inv_file.schema_preview_json) path = Path(inv_file.storage_path) if not path.is_file(): - raise FileNotFoundError(f"未找到库存快照文件 {inv_file.inventory_file_no}") + raise FileNotFoundError(f"未找到库存快照文件 {inv_file.onhand_file_no}") preview = read_inventory_schema_preview(path) preview["upload_filename"] = inv_file.source_file_name or path.name inv_file.schema_preview_json = preview return preview -def parse_inventory_snapshot_file(inv_file: ShippingInventoryFile) -> tuple[list[dict[str, Any]], dict[str, Any]]: +def parse_inventory_snapshot_file(inv_file: FreightRpaOnhandReportFile) -> tuple[list[dict[str, Any]], dict[str, Any]]: """以快照所属库存站点的已发布解析方案重读文件,禁止正式快照猜列。 仅供快照复用、动态仓识别和路由证据恢复调用。不存在已发布方案时直接失败, @@ -602,18 +687,18 @@ def parse_inventory_snapshot_file(inv_file: ShippingInventoryFile) -> tuple[list """ path = Path(inv_file.storage_path) if not path.is_file(): - raise FileNotFoundError(f"未找到库存快照文件 {inv_file.inventory_file_no}") - from app.models import ShippingInventorySource - from app.services.shipping_notice.inventory_parsing_profile import require_source_profile + raise FileNotFoundError(f"未找到库存快照文件 {inv_file.onhand_file_no}") + from app.models import FreightRpaSource + from app.services.freight_rpa.parsing_profile import require_source_profile from app.core.errors import ValidationError - source = ShippingInventorySource.query.filter_by(source_code=inv_file.source_code).first() + source = FreightRpaSource.query.filter_by(source_code=inv_file.source_code).first() profile = require_source_profile(source) actual_format = path.suffix.lower().lstrip('.') if actual_format != profile.file_format: raise ValidationError( f'Inventory file format {actual_format} does not match parsing profile {profile.file_format}', - code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID', + code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID', ) definition = dict(profile.definition_json or {}) return parse_inventory_excel_with_meta( @@ -626,7 +711,7 @@ def parse_inventory_snapshot_file(inv_file: ShippingInventoryFile) -> tuple[list def apply_inventory_parse_result_to_linked_tasks( - inv_file: ShippingInventoryFile, + inv_file: FreightRpaOnhandReportFile, inventory_lines: list[dict[str, Any]], *, field_mapping: dict[str, str] | None = None, @@ -634,7 +719,7 @@ def apply_inventory_parse_result_to_linked_tasks( mapping_confirmed: bool = False, ) -> list[ShippingNotice]: """把库存快照解析结果写到文件层,并同步投影到所有 active link 任务。""" - inv_file.inventory_lines_json = inventory_lines + inv_file.onhand_lines_json = inventory_lines inv_file.line_count = len(inventory_lines) if field_mapping: inv_file.field_mapping_json = field_mapping @@ -652,7 +737,7 @@ def apply_inventory_parse_result_to_linked_tasks( return linked_tasks -def linked_task_nos_for_inventory_file(inv_file: ShippingInventoryFile | None) -> list[str]: +def linked_task_nos_for_inventory_file(inv_file: FreightRpaOnhandReportFile | None) -> list[str]: """返回库存快照当前 active link 关联的任务编号列表。""" if not inv_file: return [] @@ -663,7 +748,7 @@ def linked_task_nos_for_inventory_file(inv_file: ShippingInventoryFile | None) - return sorted(set(task_nos)) -def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) -> bool: +def start_inventory_file_linked_tasks(inv_file: FreightRpaOnhandReportFile | None) -> bool: """ 按库存快照关联任务批量入队续跑。 @@ -695,7 +780,7 @@ def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) -> if task.task_no in task_nos and not current_inventory_matches_for_task(task) and not has_verified_upload_success(task): set_task_step_progress( task, - stage="inventory_matching", + stage="onhand_matching", step_title="匹配库存", status="running", message="本批库存快照已确认,等待匹配库存", diff --git a/backend/app/services/shipping_notice/inventory_mapping.py b/backend/app/services/shipping_notice/onhand_mapping.py similarity index 92% rename from backend/app/services/shipping_notice/inventory_mapping.py rename to backend/app/services/shipping_notice/onhand_mapping.py index f124f1e4..365df70a 100644 --- a/backend/app/services/shipping_notice/inventory_mapping.py +++ b/backend/app/services/shipping_notice/onhand_mapping.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/inventory_mapping.py +services/shipping_notice/onhand_mapping.py 用途:按用户维护的库存字段 ID 标准化列映射,并校验字段能力是否完整。 -依赖:ShippingInventoryField、match_rule_desc、标准 `json`/`typing` 能力。 +依赖:FreightRpaOnhandField、match_rule_desc、标准 `json`/`typing` 能力。 逻辑:正式库存链始终保留字段 ID;临时候选也只能引用库存字段目录 ID。 """ @@ -11,7 +11,7 @@ from __future__ import annotations import re from typing import Any -from app.models import ShippingInventoryField +from app.models import FreightRpaOnhandField from app.services.shipping_notice.match_rule_desc import resolve_match_rule @@ -19,7 +19,7 @@ LEGACY_SYSTEM_FIELDS = ("part_number", "aws_part_number", "reservation_id", "ava LEGACY_REQUIRED_FIELDS = ("part_number", "reservation_id", "available_qty") -def _catalog_by_id(field_mapping: dict[str, Any]) -> dict[str, ShippingInventoryField]: +def _catalog_by_id(field_mapping: dict[str, Any]) -> dict[str, FreightRpaOnhandField]: """读取映射中的库存字段目录记录;非 ID 映射仅保留给临时上传的旧链路。""" try: ids = {int(key) for key in field_mapping} @@ -27,8 +27,8 @@ def _catalog_by_id(field_mapping: dict[str, Any]) -> dict[str, ShippingInventory return {} if not ids or any(item <= 0 for item in ids): return {} - rows = ShippingInventoryField.query.filter( - ShippingInventoryField.id.in_(ids), ShippingInventoryField.status == 'active', + rows = FreightRpaOnhandField.query.filter( + FreightRpaOnhandField.id.in_(ids), FreightRpaOnhandField.status == 'active', ).all() return {str(row.id): row for row in rows} @@ -43,7 +43,7 @@ def _uses_catalog_ids(field_mapping: dict[str, Any]) -> bool: return False -def runtime_field_mapping(field_mapping: dict[str, str]) -> tuple[dict[str, str], dict[str, ShippingInventoryField]]: +def runtime_field_mapping(field_mapping: dict[str, str]) -> tuple[dict[str, str], dict[str, FreightRpaOnhandField]]: """验证“目录 ID → 原始表头”并保留字段 ID,禁止运行期依赖字段名称或内部编码。""" catalog = _catalog_by_id(field_mapping) if _uses_catalog_ids(field_mapping): @@ -56,8 +56,8 @@ def runtime_field_mapping(field_mapping: dict[str, str]) -> tuple[dict[str, str] def usage_field_ids() -> dict[str, set[str]]: """按业务用途返回启用字段 ID;程序校验能力角色而不限定字段名称。""" - rows = ShippingInventoryField.query.filter( - ShippingInventoryField.status == 'active', + rows = FreightRpaOnhandField.query.filter( + FreightRpaOnhandField.status == 'active', ).all() result: dict[str, set[str]] = {} for row in rows: @@ -99,7 +99,7 @@ def normalize_field_mapping(raw: Any) -> dict[str, str] | None: def _suggest_runtime_field_mapping(headers: list[str]) -> dict[str, str]: """基于表头名称的规则推断列映射(LLM 不可用时的 fallback)。""" - from app.services.shipping_notice.inventory_snapshot import _column_map, _map_header + from app.services.shipping_notice.onhand_snapshot import _column_map, _map_header col_map = _column_map() norm_headers = [str(h or "").strip() for h in headers] @@ -165,9 +165,9 @@ def suggest_field_mapping(headers: list[str], *, as_catalog: bool = False) -> di """按用户字段显示名称确定性推荐表头;正式配置不内置任何字段名称词典。""" if not as_catalog: return _suggest_runtime_field_mapping(headers) - from app.services.shipping_notice.inventory_structure_fingerprint import normalise_header + from app.services.shipping_notice.onhand_structure_fingerprint import normalise_header - rows = ShippingInventoryField.query.filter_by(status='active').all() + rows = FreightRpaOnhandField.query.filter_by(status='active').all() header_by_name: dict[str, list[str]] = {} for header in headers: normalized = normalise_header(header) diff --git a/backend/app/services/shipping_notice/inventory_mapping_workflow.py b/backend/app/services/shipping_notice/onhand_mapping_workflow.py similarity index 90% rename from backend/app/services/shipping_notice/inventory_mapping_workflow.py rename to backend/app/services/shipping_notice/onhand_mapping_workflow.py index 29eb6c3f..fd7c6043 100644 --- a/backend/app/services/shipping_notice/inventory_mapping_workflow.py +++ b/backend/app/services/shipping_notice/onhand_mapping_workflow.py @@ -1,10 +1,10 @@ """ -services/shipping_notice/inventory_mapping_workflow.py +services/shipping_notice/onhand_mapping_workflow.py 用途:将已按 published Profile 解析完成的正式库存写回任务并推进到待匹配状态。 -依赖:inventory_file_store、inventory_snapshot、query_service、state_machine、tool_common。 +依赖:onhand_file_store、onhand_snapshot、query_service、state_machine、tool_common。 逻辑:正式库存不存在任务级字段推断或映射确认;调用方必须先完成结构校验和确定性解析; - 快照复用路径可传 persist_lines=False,只推进状态、不覆盖共享 File 的 inventory_lines_json。 + 快照复用路径可传 persist_lines=False,只推进状态、不覆盖共享 File 的 onhand_lines_json。 """ from __future__ import annotations @@ -13,13 +13,13 @@ from typing import Any from app import db from app.models import ShippingNotice -from app.services.shipping_notice.inventory_file_store import ( +from app.services.shipping_notice.onhand_file_store import ( _can_relink_inventory, active_inventory_file_for_task, apply_inventory_parse_result_to_linked_tasks, start_inventory_file_linked_tasks, ) -from app.services.shipping_notice.inventory_snapshot import build_field_alignment_preview +from app.services.shipping_notice.onhand_snapshot import build_field_alignment_preview from app.services.shipping_notice.query_service import serialize_task_for_tool from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition from app.services.shipping_notice.order_field_purposes import task_line_purpose_values @@ -44,7 +44,7 @@ def inventory_loaded_response( 将正式库存推进到待匹配状态;可选把解析行写入当前绑定的库存文件。 核心逻辑:必须已有 active Link。``persist_lines=True``(上传/RPA 首次落库) - 写回 ``inventory_lines_json``;``False``(快照复用)只收集关联任务并推进状态, + 写回 ``onhand_lines_json``;``False``(快照复用)只收集关联任务并推进状态, 禁止覆盖共享 File 上已有行缓存。 Args: @@ -57,7 +57,7 @@ def inventory_loaded_response( field_mapping: published Profile 的字段映射快照。 mapping_source: 必须由调用方标明的映射来源,正式文件通常为 parsing_profile。 commit: False 时仅 flush,供批量回调维持外层事务边界。 - persist_lines: False 时不写 File.inventory_lines_json(复用路径)。 + persist_lines: False 时不写 File.onhand_lines_json(复用路径)。 Returns: Tool 标准响应;成功后任务可直接进入库存匹配。 @@ -101,7 +101,7 @@ def inventory_loaded_response( ) set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title="获取库存", status="completed", message=f"已载入库存 {len(inventory_lines)} 行", @@ -138,7 +138,7 @@ def inventory_loaded_response( "warnings": warnings or [], "source": source, "column_meta": column_meta, - "inventory_file_no": inv_file.inventory_file_no if inv_file else None, + "inventory_file_no": inv_file.onhand_file_no if inv_file else None, "linked_task_nos": [item.task_no for item in linked_tasks], "persist_lines": bool(persist_lines), }, diff --git a/backend/app/services/shipping_notice/inventory_profile_matching.py b/backend/app/services/shipping_notice/onhand_profile_matching.py similarity index 82% rename from backend/app/services/shipping_notice/inventory_profile_matching.py rename to backend/app/services/shipping_notice/onhand_profile_matching.py index 5b25dd7f..3992705b 100644 --- a/backend/app/services/shipping_notice/inventory_profile_matching.py +++ b/backend/app/services/shipping_notice/onhand_profile_matching.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/inventory_profile_matching.py +services/shipping_notice/onhand_profile_matching.py 用途:将库存文件结构分析与已发布库存文件解析方案进行确定性比对。 -依赖:ShippingInventoryParsingProfile、库存结构指纹服务。 +依赖:FreightRpaParsingProfile、库存结构指纹服务。 逻辑:返回完全相同、结构兼容、需要新版本或无匹配;只提供管理员建议,绝不自动绑定库存站点。 """ @@ -10,17 +10,17 @@ from __future__ import annotations from typing import Any -from app.models import ShippingInventoryParsingProfile -from app.services.shipping_notice.inventory_structure_fingerprint import normalise_header +from app.models import FreightRpaParsingProfile +from app.services.shipping_notice.onhand_structure_fingerprint import normalise_header -def _profile_headers(profile: ShippingInventoryParsingProfile) -> list[str]: +def _profile_headers(profile: FreightRpaParsingProfile) -> list[str]: """读取已发布方案保存的结构表头,缺失时不参与新方案复用推荐。""" structure = profile.structure_definition_json if isinstance(profile.structure_definition_json, dict) else {} return [str(header) for header in structure.get('headers', [])] -def _difference(analysis: dict[str, Any], profile: ShippingInventoryParsingProfile) -> dict[str, list[str]]: +def _difference(analysis: dict[str, Any], profile: FreightRpaParsingProfile) -> dict[str, list[str]]: """以业务栏位名称展示新增、缺少和顺序变化,避免只给相似度百分比。""" structure = analysis.get('structure') if isinstance(analysis.get('structure'), dict) else {} observed = [normalise_header(header) for header in structure.get('selected_headers', [])] @@ -32,9 +32,9 @@ def _difference(analysis: dict[str, Any], profile: ShippingInventoryParsingProfi } -def _core_mapping_matches(analysis: dict[str, Any], profile: ShippingInventoryParsingProfile) -> bool: +def _core_mapping_matches(analysis: dict[str, Any], profile: FreightRpaParsingProfile) -> bool: """确认既有方案的匹配与数量来源表头仍存在,不依赖字段名称猜测。""" - from app.services.shipping_notice.inventory_mapping import runtime_field_mapping, usage_field_ids + from app.services.shipping_notice.onhand_mapping import runtime_field_mapping, usage_field_ids structure = analysis.get('structure') if isinstance(analysis.get('structure'), dict) else {} observed_headers = {normalise_header(header) for header in structure.get('selected_headers', [])} @@ -53,7 +53,7 @@ def recommend_profiles(analysis: dict[str, Any]) -> dict[str, Any]: """查找已发布方案并返回可解释推荐;库存数据内容、文件名和内容 hash 均不参与判断。""" exact = str(analysis.get('exact_structure_fingerprint') or '') compatible = str(analysis.get('compatibility_fingerprint') or '') - profiles = ShippingInventoryParsingProfile.query.filter_by(status='published').all() + profiles = FreightRpaParsingProfile.query.filter_by(status='published').all() candidates: list[dict[str, Any]] = [] for profile in profiles: level = None diff --git a/backend/app/services/shipping_notice/inventory_recovery_service.py b/backend/app/services/shipping_notice/onhand_recovery_service.py similarity index 50% rename from backend/app/services/shipping_notice/inventory_recovery_service.py rename to backend/app/services/shipping_notice/onhand_recovery_service.py index 0271b1f4..219e9ca3 100644 --- a/backend/app/services/shipping_notice/inventory_recovery_service.py +++ b/backend/app/services/shipping_notice/onhand_recovery_service.py @@ -1,9 +1,14 @@ """ -services/shipping_notice/inventory_recovery_service.py +services/shipping_notice/onhand_recovery_service.py -用途:创建库存准备轮次及逐源准备事实,支持有效源复用和问题源重拉。 +用途:创建库存准备轮次及逐源准备事实,支持有效源复用和问题源重拉;阶段 B Task 7 + 修复轮新增 onhand 报表事实落地后的候选 settle(settle_preparation_source_ + from_onhand_report)与等待任务反查(waiting_preparation_source_task_ids)。 依赖:PreparationAttempt/SourceAttempt、候选冻结、InventoryFile/TaskLink。 -逻辑:本服务只创建持久化准备状态,不在数据库事务中直接触发外部 RPA。 +逻辑:本服务只创建持久化准备状态,不在数据库事务中直接触发外部 RPA。SourceAttempt + 被 settle 后的 PreparationAttempt 聚合(含 RecoveryPlan 收口)收敛到 + _aggregate_preparation_after_source_settle——per-source RPA 回调与 onhand + 事实处理函数(handle_onhand_report)共用同一聚合出口,防两路语义漂移。 """ from __future__ import annotations @@ -13,30 +18,30 @@ from typing import Any from app import db from app.models import ( - ShippingInventoryFile, - ShippingInventoryPreparationAttempt, - ShippingInventoryPreparationSourceAttempt, + FreightRpaOnhandReportFile, + ShippingOnhandPreparationAttempt, + ShippingOnhandPreparationSourceAttempt, ShippingOrderTask, ShippingOrderCandidate, - ShippingTaskInventoryLink, + ShippingTaskOnhandLink, ) -from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task -from app.services.shipping_notice.inventory_combination_fingerprint import build_inventory_combination_fingerprint -from app.services.shipping_notice.inventory_snapshot_reuse_policy import check_inventory_snapshot_reusable -from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes -from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts +from app.services.shipping_notice.onhand_file_store import active_inventory_file_for_task +from app.services.shipping_notice.onhand_combination_fingerprint import build_inventory_combination_fingerprint +from app.services.shipping_notice.onhand_snapshot_reuse_policy import check_inventory_snapshot_reusable +from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes +from app.services.shipping_notice.onhand_candidate_projection import active_inventory_runtime_facts def create_inventory_preparation_round( *, task: ShippingOrderTask, execution_id: int | None, recovery_plan_id: int | None, action_code: str, source_codes: list[str] | None = None, operation_id: str | None = None, gate_attempt_id: int | None = None, -) -> ShippingInventoryPreparationAttempt: +) -> ShippingOnhandPreparationAttempt: """创建一次任务级准备轮次;同一任务按 attempt_no 递增。""" - last = ShippingInventoryPreparationAttempt.query.filter_by(task_id=int(task.id)).order_by( - ShippingInventoryPreparationAttempt.attempt_no.desc(), + last = ShippingOnhandPreparationAttempt.query.filter_by(task_id=int(task.id)).order_by( + ShippingOnhandPreparationAttempt.attempt_no.desc(), ).first() - round_row = ShippingInventoryPreparationAttempt( + round_row = ShippingOnhandPreparationAttempt( task_id=int(task.id), execution_id=execution_id, gate_attempt_id=gate_attempt_id, recovery_plan_id=recovery_plan_id, attempt_no=(int(last.attempt_no) + 1 if last else 1), status='queued', @@ -53,7 +58,7 @@ def create_inventory_preparation_round( db.session.flush() codes = [str(code).strip().upper() for code in (source_codes or []) if str(code).strip()] if not codes: - codes = task_frozen_inventory_source_codes(task) + codes = task_frozen_onhand_source_codes(task) active_file = active_inventory_file_for_task(task) for source_code in codes: reusable, _reuse_reasons = check_inventory_snapshot_reusable( @@ -65,15 +70,15 @@ def create_inventory_preparation_round( parser_version=getattr(active_file, 'parser_version', None) if active_file else None, mapping_version=getattr(active_file, 'mapping_version', None) if active_file else None, ) - reusable = bool(action_code == 'retry_inventory_from_field_mapping' and reusable) - link = ShippingTaskInventoryLink.query.filter_by( + reusable = bool(action_code == 'retry_onhand_from_field_mapping' and reusable) + link = ShippingTaskOnhandLink.query.filter_by( task_id=int(task.id), matched_source_code=source_code, is_active=True, - ).order_by(ShippingTaskInventoryLink.id.desc()).first() - source = ShippingInventoryPreparationSourceAttempt( + ).order_by(ShippingTaskOnhandLink.id.desc()).first() + source = ShippingOnhandPreparationSourceAttempt( preparation_attempt_id=int(round_row.id), source_code=source_code, status='reusable' if reusable else 'queued', - inventory_file_id=int(active_file.id) if reusable and active_file else None, - task_inventory_link_id=int(link.id) if reusable and link else None, + onhand_file_id=int(active_file.id) if reusable and active_file else None, + task_onhand_link_id=int(link.id) if reusable and link else None, operation_id=operation_id, ) db.session.add(source) @@ -90,18 +95,18 @@ def create_inventory_preparation_round( sources=[ { 'source_code': str(item.source_code), - 'snapshot_id': item.inventory_file_id, + 'snapshot_id': item.onhand_file_id, 'snapshot_hash': ( - getattr(db.session.get(ShippingInventoryFile, int(item.inventory_file_id)), 'file_sha256', None) - if item.inventory_file_id else None + getattr(db.session.get(FreightRpaOnhandReportFile, int(item.onhand_file_id)), 'file_sha256', None) + if item.onhand_file_id else None ), 'parser_version': ( - getattr(db.session.get(ShippingInventoryFile, int(item.inventory_file_id)), 'parser_version', None) - if item.inventory_file_id else None + getattr(db.session.get(FreightRpaOnhandReportFile, int(item.onhand_file_id)), 'parser_version', None) + if item.onhand_file_id else None ), 'mapping_version': ( - getattr(db.session.get(ShippingInventoryFile, int(item.inventory_file_id)), 'mapping_version', None) - if item.inventory_file_id else None + getattr(db.session.get(FreightRpaOnhandReportFile, int(item.onhand_file_id)), 'mapping_version', None) + if item.onhand_file_id else None ), } for item in round_row.source_attempts @@ -114,8 +119,8 @@ def create_inventory_preparation_round( def sync_inventory_preparation_round( - *, preparation_attempt: ShippingInventoryPreparationAttempt, result: Any, -) -> ShippingInventoryPreparationAttempt: + *, preparation_attempt: ShippingOnhandPreparationAttempt, result: Any, +) -> ShippingOnhandPreparationAttempt: """将 RPA 准备结果回写当前 PreparationAttempt,供 Projection/Gate 使用同一事实源。""" def _read(name: str, default: Any) -> Any: return result.get(name, default) if isinstance(result, dict) else getattr(result, name, default) @@ -151,29 +156,24 @@ def sync_inventory_preparation_round( return preparation_attempt -def sync_preparation_source_from_rpa_attempt( - *, rpa_attempt_id: int, rpa_status: str, inventory_file_id: int | None = None, -) -> None: - """由 RPA 回调回写绑定 SourceAttempt,并聚合其 PreparationAttempt 状态。 +def _aggregate_preparation_after_source_settle(preparation: ShippingOnhandPreparationAttempt) -> None: + """按 SourceAttempt 状态聚合 PreparationAttempt 终态并收口绑定的 RecoveryPlan(只 flush 不 commit)。 - SourceAttempt 以不可变 RPA Attempt 主键关联;迟到/无关联回调不创建新业务轮次, - 因而不会污染当前 GateAttempt 对应的 PreparationAttempt。 + 用途:SourceAttempt 被 settle(ready/failed/waiting)后的统一聚合出口—— + per-source RPA 回调(sync_preparation_source_from_rpa_attempt)与 + onhand 报表事实处理函数(settle_preparation_source_from_onhand_report, + 阶段 B Task 7 修复轮)共用同一聚合语义,防止两条路径漂移。 + 核心逻辑:任一 failed → failed;仍有 queued/running/waiting → waiting_external; + 全部 ready/reusable/skipped → succeeded(记 completed_at);聚合到终态后 + 同步收口绑定的 RecoveryPlan(succeeded/failed + 时间戳 + 失败码), + 避免已完成的计划继续占用 active-plan 互斥位。 + Args: + preparation: SourceAttempt 已更新的准备轮次行。 + Returns: + None。只 flush——事务提交时机归属调用方。 """ - source = ShippingInventoryPreparationSourceAttempt.query.filter_by( - rpa_attempt_id=int(rpa_attempt_id), - ).order_by(ShippingInventoryPreparationSourceAttempt.id.desc()).first() - if source is None: + if preparation is None: return - status = str(rpa_status or '').strip().lower() - if status in {'succeeded', 'consumed'}: - source.status = 'ready' - if inventory_file_id: - source.inventory_file_id = int(inventory_file_id) - elif status in {'failed', 'exhausted'}: - source.status = 'failed' - elif status in {'queued', 'running'}: - source.status = 'waiting' - preparation = source.preparation_attempt rows = list(getattr(preparation, 'source_attempts', []) or []) if any(row.status == 'failed' for row in rows): preparation.status = 'failed' @@ -201,4 +201,105 @@ def sync_preparation_source_from_rpa_attempt( if preparation.status == 'failed': plan.failure_code = 'inventory_preparation_failed' plan.failure_detail_json = {'message': '库存准备 RPA 回调失败'} + + +def settle_preparation_source_from_onhand_report( + *, source_code: str, onhand_file_id: int, +) -> list[ShippingOnhandPreparationAttempt]: + """onhand 报表事实落地后:把该来源等待中的 SourceAttempt settle 为 ready 并绑定文件。 + + 【AI 触发时机】:onhand 事实处理函数(shipping_notice.onhand_report_handler. + handle_onhand_report)在文件行 commit 后投递 ok=True 事实时调用——共享快照 + 模型下「该来源已有可用快照」对所有等待该来源的候选准备成立。 + + 核心逻辑:[STEP 1] 取该来源 status ∈ queued/running/waiting 且未绑定文件的 + SourceAttempt(幂等集:已 ready/已绑定的行不在集合内,重复投递零副作用、 + 绝不重复候选行);[STEP 2] 逐行 ready + 绑定 onhand_file_id; + [STEP 3] 对受影响的 PreparationAttempt 逐一聚合终态 + (_aggregate_preparation_after_source_settle,含 RecoveryPlan 收口)。 + 只 flush 不 commit——事务提交时机归属调用方(处理函数)。 + + Args: + source_code: 库存来源编码(与 SourceAttempt.source_code 精确匹配)。 + onhand_file_id: 已提交的 freight_rpa_onhand_report_files 主键。 + Returns: + 受影响(发生了 settle)的 PreparationAttempt 列表;无等待行时为空表。 + """ + waiting = ( + ShippingOnhandPreparationSourceAttempt.query + .filter( + ShippingOnhandPreparationSourceAttempt.source_code == str(source_code or '').strip(), + ShippingOnhandPreparationSourceAttempt.status.in_(('queued', 'running', 'waiting')), + ShippingOnhandPreparationSourceAttempt.onhand_file_id.is_(None), + ) + .all() + ) + affected: dict[int, ShippingOnhandPreparationAttempt] = {} + for row in waiting: + row.status = 'ready' + row.onhand_file_id = int(onhand_file_id) + preparation = row.preparation_attempt + if preparation is not None: + affected[int(preparation.id)] = preparation + for preparation in affected.values(): + _aggregate_preparation_after_source_settle(preparation) + if waiting: + db.session.flush() + return list(affected.values()) + + +def waiting_preparation_source_task_ids(*, source_code: str) -> list[int]: + """列出「仍在等待该来源库存」的准备轮次任务 ID(onhand 事实处理函数门禁重投影用)。 + + 用途:onhand 失败/空事实(无文件身份)时,处理函数只对等待该来源的任务重投影 + 履约门禁(回调失败路径的门禁更新归处理函数),不发明/改写任何候选行。 + 核心逻辑:按 source_code 取 status ∈ queued/running/waiting 的 SourceAttempt, + 经其准备轮次收集去重 task_id;只读查询。 + Args: + source_code: 库存来源编码。 + Returns: + 去重后的 ShippingOrderTask.id 列表(无等待行时为空表)。 + """ + rows = ( + ShippingOnhandPreparationSourceAttempt.query + .filter( + ShippingOnhandPreparationSourceAttempt.source_code == str(source_code or '').strip(), + ShippingOnhandPreparationSourceAttempt.status.in_(('queued', 'running', 'waiting')), + ) + .all() + ) + task_ids: list[int] = [] + for row in rows: + preparation = row.preparation_attempt + if preparation is not None and preparation.task_id and int(preparation.task_id) not in task_ids: + task_ids.append(int(preparation.task_id)) + return task_ids + + +def sync_preparation_source_from_rpa_attempt( + *, rpa_attempt_id: int, rpa_status: str, inventory_file_id: int | None = None, +) -> None: + """由 RPA 回调回写绑定 SourceAttempt,并聚合其 PreparationAttempt 状态。 + + SourceAttempt 以不可变 RPA Attempt 主键关联;迟到/无关联回调不创建新业务轮次, + 因而不会污染当前 GateAttempt 对应的 PreparationAttempt。聚合语义自阶段 B + Task 7 修复轮起收敛到 _aggregate_preparation_after_source_settle(与 + settle_preparation_source_from_onhand_report 共用同一出口)。 + """ + source = ShippingOnhandPreparationSourceAttempt.query.filter_by( + rpa_attempt_id=int(rpa_attempt_id), + ).order_by(ShippingOnhandPreparationSourceAttempt.id.desc()).first() + if source is None: + return + status = str(rpa_status or '').strip().lower() + if status in {'succeeded', 'consumed'}: + source.status = 'ready' + if inventory_file_id: + source.onhand_file_id = int(inventory_file_id) + elif status in {'failed', 'exhausted'}: + source.status = 'failed' + elif status in {'queued', 'running'}: + source.status = 'waiting' + preparation = source.preparation_attempt + _aggregate_preparation_after_source_settle(preparation) db.session.flush() diff --git a/backend/app/services/shipping_notice/onhand_report_handler.py b/backend/app/services/shipping_notice/onhand_report_handler.py new file mode 100644 index 00000000..d3754593 --- /dev/null +++ b/backend/app/services/shipping_notice/onhand_report_handler.py @@ -0,0 +1,157 @@ +""" +services/shipping_notice/onhand_report_handler.py + +用途:onhand(在手库存)报表事实的发货侧业务处理函数(阶段 B Task 7)—— + 在手文件归档终态 commit 后由 dispatch_report_fact 投递的 ReportFact + 只在此更新发货自己的门禁与候选相关状态,绝不写调拨或 RPA 侧事实。 +依赖:app.db、app.models(FreightRpaOnhandReportFile 只读行获取 / ShippingTaskOnhandLink / + ShippingOrderTask / ShippingProcessExecution)、app.core.errors + (ValidationError / NotFoundError)、freight_rpa.reports.facts(ReportFact / + require_report_kind——只消费事实契约,不 import freight_rpa 工作流)、 + onhand_recovery_service(候选准备 settle/聚合/等待任务反查)、 + process_gate_bridge(门禁同步)。 +逻辑:由组合根(app.create_app → shipping_notice.rpa_sinks.register_onhand_sinks; + 入站/出站另见 in_transit_transfer.rpa_sinks) + 注册为 'onhand' kind 处理函数;onhand_rpa_workflow 的单回调 + (rpa_report_inventory)与批量 worker(process_rpa_report_inventory_batch) + 在文件行 commit 后逐文件投递 ok=True 事实(先 commit 再投递——Task 7 修复轮 + 接线;HTTP 收件入口 rpa_report_inventory_batch 只入队 Job、不 commit 文件, + 故不投递)。处理函数只改发货自己的行:[候选] settle 等待该来源的 + SourceAttempt 并绑定该文件(共享快照模型);[门禁] 对受影响的准备轮次任务与 + 挂接该文件的任务重投影履约门禁;[提交] 处理函数自行 commit(文件行已由归档方 + 提交,绝不回滚)。行插入唯一入口在 freight_rpa/onhand/report_store(本模块 + 【禁止】构造 FreightRpaOnhandReportFile 行,边界由 test_report_model_boundary 锁定); + TransferSourceJob 归调拨域(本模块不写)。 +""" + +from __future__ import annotations + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import FreightRpaOnhandReportFile, ShippingTaskOnhandLink +from app.services.freight_rpa.reports.facts import ReportFact, require_report_kind + + +def _sync_gates_for_task_ids(task_ids: list[int]) -> None: + """对给定任务逐一重投影履约门禁(活动、非 superseded 执行链;幂等可重放)。 + + 核心逻辑:按主键取任务与活动执行链——执行链缺失/已 superseded 时跳过 + (重冻结/复活链路上 Task 指针可能短暂指向旧执行链:迟到事实只保留原始 + 审计,不得回写已废弃执行的 Gate);命中即 sync_fulfillment_gates_from_task + (域事实投影为 Gate 结果,重复投递重投影同值,不产生重复行)。 + 只写不 commit——事务提交时机归属调用方(handle_onhand_report)。 + """ + from app.models import ShippingOrderTask, ShippingProcessExecution + from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task + + seen: set[int] = set() + for task_id in task_ids: + if task_id in seen: + continue + seen.add(task_id) + task = db.session.get(ShippingOrderTask, int(task_id)) + if task is None or not getattr(task, 'active_process_execution_id', None): + continue + execution = db.session.get( + ShippingProcessExecution, int(task.active_process_execution_id), + ) + if execution is not None and str(execution.status or '').strip().lower() != 'superseded': + sync_fulfillment_gates_from_task(execution=execution, actor_type='system') + + +def handle_onhand_report(fact: ReportFact) -> None: + """report_kind 必须是 onhand。用 fact.file_id 更新发货门禁与候选。不写 TransferSourceJob。 + 不插入 freight_rpa_onhand_report_files。 + + (Task 7 契约 docstring 逐字保留如上;修复轮补充说明见下。) + + 核心逻辑: + [STEP 1] kind 门禁(fail-closed,防误注册/误分发); + [STEP 2] success 事实(ok 且 file_id 有值):按主键取回已提交的 onhand 报表行 + (只读——行由 freight_rpa/onhand/report_store 收敛写入,本模块只消费;缺失即 + fail-closed 抛 NotFoundError); + [STEP 3 候选] settle 等待该来源的候选准备行并绑定该文件 + (onhand_recovery_service.settle_preparation_source_from_onhand_report——共享 + 快照模型:该来源已有可用快照即对所有等待该来源的候选准备成立;幂等—— + 已 ready/已绑定的行不在等待集,重复投递零副作用、不重复候选行); + [STEP 4 门禁] 对受影响的准备轮次任务 + 挂接该文件(active link)的任务重投影 + 履约门禁(sync_fulfillment_gates_from_task,幂等可重放); + [STEP 5] db.session.commit()——处理函数提交自己的候选/门禁写(文件行已由 + 归档方提交,绝不回滚)。 + 失败/空事实(ok=False 或 file_id=None):无文件身份——不发明候选行、不 settle + 任何 SourceAttempt;仅对仍在等待该来源库存的任务重投影门禁(回调失败路径的 + 门禁更新归本处理函数),随后同样 commit。 + 【不写 TransferSourceJob】(归 in_transit_transfer 域);【不构造 + freight_rpa_onhand_report_files 行】(归 freight_rpa 域唯一写入口)。 + 异常原样外抛(不捕获):文件行已提交不回滚,Worker 重试整笔回调补齐。 + + Args: + fact: 终态已提交后由归档入口构造的报表事实(report_kind='onhand'/ + source_code/file_id/sha256/ok/error_code/error_message)。 + Returns: + None(候选/门禁写库,不返回业务值)。 + Raises: + ValidationError: report_kind 非 onhand(误注册/误分发,fail-closed)。 + NotFoundError: fact.file_id 对应的在手报表行不存在(事实先于文件提交 + 属硬性不一致,fail-closed 而非静默跳过)。 + """ + # [STEP 1] kind 门禁:本函数只消费 onhand 事实(dispatch 已按 kind 路由, + # 防御性复核,防止误注册成其他 kind 的处理函数后静默错写发货行)。 + kind = require_report_kind(fact.report_kind) + if kind != 'onhand': + raise ValidationError( + f"handle_onhand_report only accepts onhand facts, got: {kind!r}", + code='SHIPPING.INBOUND_CALLBACK_INVALID', + details={'report_kind': fact.report_kind}, + ) + + from app.services.shipping_notice.onhand_recovery_service import ( + settle_preparation_source_from_onhand_report, + waiting_preparation_source_task_ids, + ) + + source_code = str(fact.source_code or '').strip() + affected_task_ids: list[int] = [] + + if not fact.ok or fact.file_id is None: + # [STEP 2·失败/空分支] 无文件身份:不发明候选行、不 settle 任何 SourceAttempt; + # 仅对仍在等待该来源库存的任务重投影门禁(失败路径门禁更新归本处理函数)。 + affected_task_ids.extend(waiting_preparation_source_task_ids(source_code=source_code)) + else: + # [STEP 2·success 分支] 只读取回已提交的在手报表行(构造禁走 report_store; + # 读取按主键)。 + inv_file = db.session.get(FreightRpaOnhandReportFile, int(fact.file_id)) + if inv_file is None: + raise NotFoundError( + f"Onhand report file not found: {fact.file_id}", + details={'file_id': fact.file_id}, + ) + file_source = str(inv_file.source_code or source_code).strip() + + # [STEP 3·候选] settle 等待该来源的候选准备行并绑定该文件(幂等)。 + settled = ( + settle_preparation_source_from_onhand_report( + source_code=file_source, onhand_file_id=int(inv_file.id), + ) + if file_source + else [] + ) + for preparation in settled: + if preparation.task_id: + affected_task_ids.append(int(preparation.task_id)) + + # [STEP 4·门禁] 挂接该文件(active link)的任务一并重投影门禁。 + links = ( + ShippingTaskOnhandLink.query + .filter_by(onhand_file_id=inv_file.id, is_active=True) + .all() + ) + for link in links: + if link.task_id: + affected_task_ids.append(int(link.task_id)) + + _sync_gates_for_task_ids(affected_task_ids) + + # [STEP 5] 处理函数提交自己的候选/门禁写(sync_fulfillment_gates_from_task + # 不 commit——不提交则请求结束回滚会丢掉这些写;文件行已提交,不受影响)。 + db.session.commit() diff --git a/backend/app/services/shipping_notice/inventory_routing_engine.py b/backend/app/services/shipping_notice/onhand_routing_engine.py similarity index 94% rename from backend/app/services/shipping_notice/inventory_routing_engine.py rename to backend/app/services/shipping_notice/onhand_routing_engine.py index 657512a9..aaf0074b 100644 --- a/backend/app/services/shipping_notice/inventory_routing_engine.py +++ b/backend/app/services/shipping_notice/onhand_routing_engine.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/inventory_routing_engine.py +services/shipping_notice/onhand_routing_engine.py 用途:执行已发布的通用库存源路由规则并生成可解释的 Source 候选。 -依赖:库存路由模型、冻结订单 Snapshot、routing_operators、inventory_source_repository。 +依赖:库存路由模型、冻结订单 Snapshot、routing_operators、onhand_source_repository。 逻辑:行级评估先做「库存源线索直连」(冻结行 inventory_source_hint 经精确/唯一后缀解析启用源, 命中即 resolved,跳过全部规则层——含预约单号兜底规则;未命中 fail-open 落回规则层); 随后只评估最高优先级命中的规则层;规则仅输出候选或人工复核,不执行 RPA 或 Warehouse 判定。 @@ -16,8 +16,8 @@ from dataclasses import dataclass from datetime import datetime from typing import Any -from app.models import ShippingInventoryRoutingRule, ShippingOrderSnapshot -from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources +from app.models import FreightRpaOnhandRoutingRule, ShippingOrderSnapshot +from app.services.shipping_notice.onhand_source_repository import list_database_inventory_sources from app.services.shipping_notice.routing_operators import matches_operator @@ -76,7 +76,7 @@ class InventoryRoutingResult: ) -def _matched_rule_summaries(rules: list[ShippingInventoryRoutingRule]) -> tuple[dict[str, Any], ...]: +def _matched_rule_summaries(rules: list[FreightRpaOnhandRoutingRule]) -> tuple[dict[str, Any], ...]: """将命中规则折叠为可审计、可序列化的摘要元组。""" return tuple( { @@ -177,7 +177,7 @@ def _condition_value_from_maps( def _rule_matches( - rule: ShippingInventoryRoutingRule, + rule: FreightRpaOnhandRoutingRule, *, value_reader, ) -> bool: @@ -191,7 +191,7 @@ def _rule_matches( return all(results) if rule.match_mode == 'all' else any(results) -def _evaluate_matched_rules(top_rules: list[ShippingInventoryRoutingRule], *, priority: int) -> InventoryRoutingResult: +def _evaluate_matched_rules(top_rules: list[FreightRpaOnhandRoutingRule], *, priority: int) -> InventoryRoutingResult: """ 将同优先级命中规则折叠为候选集合与建单资格。 @@ -250,13 +250,13 @@ def _evaluate_matched_rules(top_rules: list[ShippingInventoryRoutingRule], *, pr ) -def _published_rules(*, scope: str, now: datetime) -> list[ShippingInventoryRoutingRule]: +def _published_rules(*, scope: str, now: datetime) -> list[FreightRpaOnhandRoutingRule]: """加载当前时刻有效的已发布规则,按优先级降序。""" - query = ShippingInventoryRoutingRule.query.filter_by(status='published', scope=scope) + query = FreightRpaOnhandRoutingRule.query.filter_by(status='published', scope=scope) return [ rule for rule in query.order_by( - ShippingInventoryRoutingRule.priority.desc(), - ShippingInventoryRoutingRule.id.asc(), + FreightRpaOnhandRoutingRule.priority.desc(), + FreightRpaOnhandRoutingRule.id.asc(), ).all() if (rule.effective_from is None or rule.effective_from <= now) and (rule.effective_to is None or rule.effective_to >= now) diff --git a/backend/app/services/shipping_notice/inventory_rpa_workflow.py b/backend/app/services/shipping_notice/onhand_rpa_workflow.py similarity index 81% rename from backend/app/services/shipping_notice/inventory_rpa_workflow.py rename to backend/app/services/shipping_notice/onhand_rpa_workflow.py index ff54b90d..27e69d30 100644 --- a/backend/app/services/shipping_notice/inventory_rpa_workflow.py +++ b/backend/app/services/shipping_notice/onhand_rpa_workflow.py @@ -1,42 +1,58 @@ """ -services/shipping_notice/inventory_rpa_workflow.py +services/shipping_notice/onhand_rpa_workflow.py -用途:发货通知库存 RPA 编排(触发导出、等待/超时、回调落盘)。 -依赖:customer_identity_gate、reservation_gate、rpa、rpa_attempts、inventory_snapshot、 - inventory_mapping_workflow、query_service、动态订单字段、tool_common、state_machine、tool_response。 -逻辑:inventory_workflow.ensure_inventory 在 auto 时仅复用快照、在 retry_rpa 时委托本模块触发刷新; +用途:发货通知库存 RPA 业务编排(触发导出、等待/超时、回调落盘、快照与门禁推进)。 +依赖:customer_identity_gate、reservation_gate、freight_rpa.onhand(trigger_io 目录/attempts 计数/ + workflow_protocol 协议记账)、onhand_snapshot、onhand_mapping_workflow、query_service、 + 动态订单字段、tool_common、state_machine、tool_response。 +逻辑:onhand_workflow.ensure_onhand 在 auto 时仅复用快照、在 retry_rpa 时委托本模块触发刷新; 库存源始终由规则 Gate 自动裁决;Reservation 门禁从当前 Extraction 的动态 FieldValue 读取; 复用 ready 快照走 link_snapshot_to_task_for_preparation(动态仓未决可 pending_matching)。 + Task 9 拆分:attempt 行记账/run_no 幂等键/轮次与排程校验/批量进度记账/超时窗口数学/ + 回调契约归一化等纯协议态下沉 freight_rpa.onhand.workflow_protocol(零 shipping_notice + import); 快照落盘、ScheduleRun finalize、ProcessGate/Execution 推进、审计投影与状态机 + 留守本文件(事务边界与 commit 时机与拆分前逐点等价)。下方旧私有名以模块别名 re-export, + 既有同包调用与测试 import(含 monkeypatch 接缝)不换名。 + 【阶段 B Task 7 修复】单回调(rpa_report_inventory)与批量 worker + (process_rpa_report_inventory_batch)在文件行 commit 后逐文件投递 onhand 报表事实 + (dispatch_report_fact(ReportFact(report_kind='onhand', ...))——先 commit 再投递; + 处理函数异常原样外抛、不折进 warnings;HTTP 收件入口 rpa_report_inventory_batch 只入队 + Job、不 commit 文件故不投递;空结果审计快照不投递——不作可用库存复用)。候选 settle + 与门禁同步由 handle_onhand_report 承担(见 onhand_report_handler.py)。修复轮 2/3:批量内 + 单文件处理函数失败先回滚未提交会话(半途写不得被后续 commit 持久化)并继续投递其余 + 已提交文件,排程 finalize 与 drop 文件清理入队照常执行,之后以 + OnhandReportDispatchAfterCommitError 携带未成功文件清单原样重抛;Job 处理器把清单写回 + payload(retry_dispatch_files)并 requeue,重试经「只重投失败文件」通道 + (_dispatch_retry_onhand_report_files)补齐,全部成功前绝不返回 ok。 """ from __future__ import annotations import hashlib -import json import logging import shutil -from datetime import datetime, timedelta, timezone +from datetime import datetime, timedelta from pathlib import Path from typing import Any from app import db from app.core.errors import AppError, ServiceUnavailableError -from app.models import ShippingInventoryFile, ShippingNotice, ShippingOrderTask, ShippingTaskEvent +from app.models import FreightRpaOnhandReportFile, ShippingNotice, ShippingOrderTask from app.services.shipping_notice.constants import POSITION_UPLOAD_REQ, PH_RPA_PENDING -from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file -from app.services.shipping_notice.inventory_snapshot_store import ( +from app.services.shipping_notice.onhand_snapshot import ingest_inventory_file +from app.services.shipping_notice.onhand_snapshot_store import ( find_latest_ready_snapshot, get_or_create_rpa_inventory_snapshot, link_snapshot_to_task, link_snapshot_to_task_for_preparation, ) -from app.services.shipping_notice.inventory_upload import ( +from app.services.shipping_notice.onhand_upload import ( delete_staged_task_inventory_file, promote_staged_task_inventory_file, rebuild_task_inventory_attachment_from_snapshot, stage_task_inventory_callback_file, ) -from app.services.shipping_notice.inventory_rpa_callback_cleanup import ( +from app.services.freight_rpa.onhand.callback_cleanup import ( enqueue_callback_file_move, flush_callback_cleanup_queue, mark_callback_drop_file_consumed, @@ -44,12 +60,12 @@ from app.services.shipping_notice.inventory_rpa_callback_cleanup import ( quarantine_callback_drop_file, recover_pending_rpa_callback_cleanup_jobs, ) -from app.services.shipping_notice.inventory_source_gate import ( +from app.services.shipping_notice.onhand_source_gate import ( assert_inventory_source_gate, inventory_identities_match, is_inventory_source_stable, ) -from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source +from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source from app.services.shipping_notice.customer_identity_gate import ( assert_customer_identity_gate, customer_gate_tool_response, @@ -60,15 +76,34 @@ from app.services.shipping_notice.query_service import ( ) from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues from app.services.shipping_notice.task_field_gate import field_conflict_gate_response -from app.services.shipping_notice.rpa import ( - inventory_drop_dir, - inventory_processed_dir, +from app.services.freight_rpa.onhand.attempts import onhand_rpa_attempts +from app.services.freight_rpa.onhand.trigger_io import ( + SCHEMA, + onhand_drop_dir, + onhand_processed_dir, +) +from app.services.freight_rpa.onhand.workflow_protocol import ( + compute_rpa_wait_window, + expected_rpa_callback_run_no, + extract_run_no_from_trigger, + get_consumed_inventory_rpa_run_no, + is_legacy_trigger_run_no, + latest_task_event, + mark_inventory_rpa_run_no_consumed, + merge_batch_callback_item, + normalize_inventory_batch_item_status, + normalize_inventory_result_status, + record_onhand_batch_progress, + resolve_effective_callback_run_no, + resolve_shared_inventory_drop_file, + validate_rpa_callback_not_replayed, + validate_rpa_callback_run_no, + validate_schedule_batch_callback_run_no, +) +from app.services.shipping_notice.onhand_trigger_batch import ( write_inventory_export_trigger_for_task, ) -from app.services.shipping_notice.rpa_worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE -from app.services.shipping_notice.rpa_attempts import ( - inventory_rpa_attempts, -) +from app.services.freight_rpa.common.worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition from app.services.shipping_notice.tool_common import ( log_task_event, @@ -78,6 +113,23 @@ from app.services.shipping_notice.tool_common import ( from app.services.shipping_notice.tool_response import tool_response from app.services.shipping_notice.task_disposition_service import task_execution_block_reason +# [协议态 re-export] Task 9 下沉 freight_rpa.onhand.workflow_protocol 的函数在本模块保留旧私有名 +# 别名:既有同包调用与测试(tests/test_shipping_process_recovery_plan 等直接 import 旧名) +# 不换名;monkeypatch 接缝仍以本模块全局名为准。 +_extract_run_no_from_trigger = extract_run_no_from_trigger +_is_legacy_trigger_run_no = is_legacy_trigger_run_no +_expected_rpa_callback_run_no = expected_rpa_callback_run_no +_validate_rpa_callback_run_no = validate_rpa_callback_run_no +_resolve_effective_callback_run_no = resolve_effective_callback_run_no +_get_consumed_inventory_rpa_run_no = get_consumed_inventory_rpa_run_no +_mark_inventory_rpa_run_no_consumed = mark_inventory_rpa_run_no_consumed +_validate_rpa_callback_not_replayed = validate_rpa_callback_not_replayed +_validate_schedule_batch_callback_run_no = validate_schedule_batch_callback_run_no +_resolve_shared_inventory_drop_file = resolve_shared_inventory_drop_file +_normalize_rpa_inventory_result_status = normalize_inventory_result_status +_normalize_rpa_inventory_batch_item_status = normalize_inventory_batch_item_status +_merge_batch_callback_item = merge_batch_callback_item + def _workflow_owner(task: ShippingNotice | ShippingOrderTask) -> ShippingNotice | ShippingOrderTask: """将正式 Notice 输入解析为 OT owner;库存运行事实统一写入 OT。""" @@ -103,17 +155,6 @@ def _workflow_error(task: ShippingNotice | ShippingOrderTask) -> str | None: return getattr(_workflow_owner(task), 'error_message', None) -def latest_task_event(task: ShippingNotice, event_type: str) -> ShippingTaskEvent | None: - """返回任务最近一条指定类型的 ShippingTaskEvent(RPA 超时/重试用)。""" - if task.id is None: - return None - return ( - ShippingTaskEvent.query.filter_by(task_id=task.id, event_type=event_type) - .order_by(ShippingTaskEvent.id.desc()) - .first() - ) - - def _inventory_rpa_attempt_label(*, attempt_no: int, max_attempts: int, manual_retry_round: bool) -> str: """ 生成库存 RPA 尝试状态文案。 @@ -156,7 +197,7 @@ def _try_reuse_inventory_snapshot( if mode == "retry_rpa": return None - from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response + from app.services.shipping_notice.onhand_mapping_workflow import inventory_loaded_response snapshot = find_latest_ready_snapshot( str(rpa_source.get("source_code") or ""), @@ -178,7 +219,7 @@ def _try_reuse_inventory_snapshot( task, "inventory_snapshot_reused", { - "inventory_file_no": snapshot.inventory_file_no, + "inventory_file_no": snapshot.onhand_file_no, "source_code": snapshot.source_code, "warehouse_id": snapshot.warehouse_id, "snapshot_age_seconds": link.snapshot_age_seconds, @@ -186,7 +227,7 @@ def _try_reuse_inventory_snapshot( ) db.session.flush() - from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines + from app.services.shipping_notice.onhand_file_store import read_inventory_file_lines try: lines, column_meta = read_inventory_file_lines(snapshot) except (OSError, ValueError, AppError): @@ -268,18 +309,18 @@ def inventory_rpa_wait_seconds(task: ShippingNotice) -> tuple[int | None, int | Returns: tuple[int | None, int | None, int | None]: (elapsed_seconds, timeout_seconds, remaining_seconds)。 """ - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task from app.services.shipping_notice.process_gate_projection import task_blocking_reason if task_blocking_reason(task) != PH_RPA_PENDING or has_ready_inventory_file_for_task(task): return None, None, None - last_trigger = latest_task_event(task, "inventory_rpa_triggered") + last_trigger = latest_task_event(task, "onhand_rpa_triggered") if not last_trigger or not isinstance(last_trigger.created_at, datetime): return None, None, None + # 超时窗口数学为协议态(workflow_protocol.compute_rpa_wait_window); + # 业务门禁(blocking reason / ready 文件)与超时阈值配置(tool_common)留守本域。 timeout_seconds = rpa_inventory_timeout_seconds() - elapsed = max(int((datetime.utcnow() - last_trigger.created_at).total_seconds()), 0) - remaining = max(timeout_seconds - elapsed, 0) - return elapsed, timeout_seconds, remaining + return compute_rpa_wait_window(last_trigger.created_at, timeout_seconds) def next_inventory_rpa_recheck_at(task: ShippingNotice) -> datetime | None: @@ -314,14 +355,14 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor return None log_task_event( task, - "inventory_rpa_wait_rechecked", + "onhand_rpa_wait_rechecked", {"source": source, "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds}, ) # [STEP] 单次 RPA 触发已超时且无更晚成功回执:不做自动重试,记录超时失败并落 # rpa_exhausted 人工接管;两个事件供审计/前端识别“等待超时 → 重试耗尽”。 log_task_event( task, - "inventory_rpa_failed", + "onhand_rpa_failed", { "error": "timeout", "elapsed_seconds": elapsed, @@ -330,7 +371,7 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor ) log_task_event( task, - "inventory_rpa_exhausted", + "onhand_rpa_exhausted", {"source": source, "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds}, ) db.session.flush() @@ -348,7 +389,7 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor def _expected_snapshot_identity_from_task(task: ShippingNotice) -> tuple[str, str]: """从任务正式库存身份推导快照预期二元组。""" - from app.services.shipping_notice.inventory_source_gate import task_inventory_identity + from app.services.shipping_notice.onhand_source_gate import task_inventory_identity identity = task_inventory_identity(task) return ( @@ -379,7 +420,7 @@ def _rollback_orphan_inventory_snapshot( return from sqlalchemy import inspect as sa_inspect - from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path + from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path for raw in paths: delete_inventory_storage_path(raw) @@ -416,12 +457,12 @@ def _inventory_file_sha256(path: Path) -> str: def _validate_reused_snapshot_callback_file( - inv_file: ShippingInventoryFile, + inv_file: FreightRpaOnhandReportFile, callback_path: Path, ) -> str | None: """ 校验复用快照时回调落盘文件与托管 storage_path 内容一致。 - 核心逻辑:不一致时拒绝复用,避免 inventory_lines_json 与 storage_path 文件分叉。 + 核心逻辑:不一致时拒绝复用,避免 onhand_lines_json 与 storage_path 文件分叉。 """ storage_path = Path(str(inv_file.storage_path or "")) if not storage_path.is_file(): @@ -433,11 +474,11 @@ def _validate_reused_snapshot_callback_file( return None -def _snapshot_ingest_path(inv_file: ShippingInventoryFile) -> Path: +def _snapshot_ingest_path(inv_file: FreightRpaOnhandReportFile) -> Path: """返回应解析的库存快照托管路径(复用与新建均读 storage_path)。""" path = Path(str(inv_file.storage_path or "")) if not path.is_file() or str(inv_file.storage_path or "").startswith("failed://"): - raise FileNotFoundError(f"库存快照托管文件不存在: {inv_file.inventory_file_no}") + raise FileNotFoundError(f"库存快照托管文件不存在: {inv_file.onhand_file_no}") return path @@ -545,7 +586,7 @@ def _flush_pending_callback_moves( def _try_rebuild_task_inventory_attachment( task: ShippingNotice, - inv_file: ShippingInventoryFile, + inv_file: FreightRpaOnhandReportFile, post_commit_warnings: list[str], ) -> bool: """ @@ -603,65 +644,6 @@ def _persist_post_commit_task_event( ) -def _extract_run_no_from_trigger(trigger_path: str | None) -> str: - """从 trigger 文件路径或 JSON 内容提取 run_no(batch / legacy 均支持)。""" - path = Path(str(trigger_path or "")) - name = path.name - prefix = "inventory_export_batch_" - if name.startswith(prefix) and name.endswith(".json"): - return name[len(prefix) : -len(".json")] - if name.startswith("inventory_export_") and name.endswith(".json") and path.is_file(): - try: - payload = json.loads(path.read_text(encoding="utf-8")) - if isinstance(payload, dict): - run_no = str(payload.get("run_no") or "").strip() - if run_no: - return run_no - except (OSError, json.JSONDecodeError, TypeError, ValueError): - pass - return "" - - -def _is_legacy_trigger_run_no(run_no: str) -> bool: - """判断 run_no 是否来自 legacy 单任务 trigger(worker 可能不回传)。""" - return str(run_no or "").strip().upper().startswith("LEGACY-") - - -def _expected_rpa_callback_run_no(task: ShippingNotice) -> str: - """读取任务最近一次 RPA 触发记录的 run_no。""" - last_trigger = latest_task_event(task, "inventory_rpa_triggered") - if not last_trigger: - return "" - detail = last_trigger.detail_json if isinstance(last_trigger.detail_json, dict) else {} - run_no = str(detail.get("run_no") or "").strip() - if run_no: - return run_no - return _extract_run_no_from_trigger(str(detail.get("trigger") or "")) - - -def _validate_rpa_callback_run_no(task: ShippingNotice, callback_run_no: str) -> str | None: - """校验回调 run_no 属于当前任务最近一次有效触发轮次。""" - provided = str(callback_run_no or "").strip() - expected = _expected_rpa_callback_run_no(task) - if not expected: - return "no_active_trigger" - if not provided: - if _is_legacy_trigger_run_no(expected): - return None - return "run_no_missing" - if provided != expected: - return "run_no_mismatch" - return None - - -def _resolve_effective_callback_run_no(task: ShippingNotice, payload: dict[str, Any]) -> str: - """解析回调实际归属的 run_no(显式传入优先,否则回退当前触发轮次)。""" - provided = str(payload.get("run_no") or "").strip() - if provided: - return provided - return _expected_rpa_callback_run_no(task) - - def _lock_task_for_rpa_callback(task: ShippingOrderTask) -> ShippingOrderTask: """对订单任务行加悲观锁,防止并发回调重复消费同一轮次。""" if task.id is None: @@ -674,45 +656,6 @@ def _lock_task_for_rpa_callback(task: ShippingOrderTask) -> ShippingOrderTask: ) -def _get_consumed_inventory_rpa_run_no(task: ShippingNotice) -> str: - """读取已消费(处理完成)的 RPA 轮次 run_no。""" - from app.models import ShippingTaskInventoryRpaAttempt - - attempt = ( - ShippingTaskInventoryRpaAttempt.query - .filter_by(task_no=str(task.task_no or ''), status='consumed') - .order_by(ShippingTaskInventoryRpaAttempt.consumed_at.desc(), ShippingTaskInventoryRpaAttempt.id.desc()) - .first() - ) - return str(getattr(attempt, 'source_run_no', '') or '').strip() - - -def _mark_inventory_rpa_run_no_consumed(task: ShippingNotice, run_no: str) -> None: - """标记当前 RPA 轮次已被回调消费,防止同一 run_no 重放重复入库。""" - effective = str(run_no or "").strip() - if not effective: - return - from app.models import ShippingTaskInventoryRpaAttempt - - attempt = ( - ShippingTaskInventoryRpaAttempt.query - .filter_by(task_no=str(task.task_no or ''), source_run_no=effective) - .one_or_none() - ) - if attempt is not None: - attempt.status = 'consumed' - attempt.consumed_at = datetime.utcnow() - - -def _validate_rpa_callback_not_replayed(task: ShippingNotice, run_no: str) -> str | None: - """拒绝同一 run_no 的重复成功/失败/跳过回调。""" - effective = str(run_no or "").strip() - consumed = _get_consumed_inventory_rpa_run_no(task) - if effective and consumed and effective == consumed: - return "run_no_already_consumed" - return None - - def _validate_rpa_callback_round(task: ShippingNotice, payload: dict[str, Any]) -> dict[str, Any] | None: """ 校验 RPA 回调轮次契约(run_no + 幂等)。 @@ -723,12 +666,12 @@ def _validate_rpa_callback_round(task: ShippingNotice, payload: dict[str, Any]) # per-source 已成功后又被 task-level batch_run_no 的旧 trigger 校验否决。 source_run_no = str(payload.get('source_run_no') or '').strip() if source_run_no: - from app.models import ShippingTaskInventoryRpaAttempt + from app.models import FreightRpaOnhandTaskAttempt current_attempt = ( - db.session.query(ShippingTaskInventoryRpaAttempt) + db.session.query(FreightRpaOnhandTaskAttempt) .filter_by(task_no=task.task_no, source_run_no=source_run_no) - .order_by(ShippingTaskInventoryRpaAttempt.id.desc()) + .order_by(FreightRpaOnhandTaskAttempt.id.desc()) .first() ) if current_attempt and str(current_attempt.status or '').lower() in {'queued', 'running', 'succeeded'}: @@ -740,12 +683,12 @@ def _validate_rpa_callback_round(task: ShippingNotice, payload: dict[str, Any]) # source_run_no 是本次 Attempt 的正式身份,匹配最新 queued/running Attempt # 时允许该批次回调继续入库,避免已生成的 Excel 被错误当作迟到回调丢弃。 if source_run_no: - from app.models import ShippingTaskInventoryRpaAttempt + from app.models import FreightRpaOnhandTaskAttempt current_attempt = ( - db.session.query(ShippingTaskInventoryRpaAttempt) + db.session.query(FreightRpaOnhandTaskAttempt) .filter_by(task_no=task.task_no, source_run_no=source_run_no) - .order_by(ShippingTaskInventoryRpaAttempt.id.desc()) + .order_by(FreightRpaOnhandTaskAttempt.id.desc()) .first() ) if current_attempt and str(current_attempt.status or '').lower() in {'queued', 'running'}: @@ -879,9 +822,9 @@ def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[ 核心逻辑:动态 Source 的 Warehouse 由库存行按 Reservation + PN 解析,回调不预先裁决。 """ callback_source = str(payload.get("source_code") or "").strip().upper() - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes - task_sources = set(task_frozen_inventory_source_codes(task)) + task_sources = set(task_frozen_onhand_source_codes(task)) if not callback_source: return tool_response( status="failed", @@ -897,12 +840,12 @@ def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[ data=serialize_task_for_tool(task), ) - from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source source = get_database_inventory_source(callback_source) is_fixed = source and str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed' callback_wh = str(payload.get("warehouse_id") or "").strip().upper() - from app.services.shipping_notice.inventory_source_gate import resolve_inventory_source_warehouse_id + from app.services.shipping_notice.onhand_source_gate import resolve_inventory_source_warehouse_id task_wh = resolve_inventory_source_warehouse_id(task, source=source) or '' if is_fixed and (not callback_wh or callback_wh != task_wh): @@ -918,7 +861,7 @@ def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[ def _validate_single_source_v2_contract(task: ShippingNotice, payload: dict[str, Any]) -> dict[str, Any] | None: """强制单源库存成功回调携带 v2 身份围栏,禁止旧 payload 写入库存事实。 - 单源 Worker 与批量 Worker 共用 ``shipping_inventory_rpa.v2``;缺少任一 + 单源 Worker 与批量 Worker 共用 ``freight_rpa.onhand.v1``;缺少任一 Attempt/Execution 身份时直接拒绝,避免回调按 Task 级旧 run_no 错绑轮次。 """ if str(payload.get('status') or '').strip().lower() != 'success': @@ -935,7 +878,7 @@ def _validate_single_source_v2_contract(task: ShippingNotice, payload: dict[str, 'gate_id': payload.get('gate_id'), } missing = [key for key, value in required.items() if value in (None, '')] - if required['schema_version'] != 'shipping_inventory_rpa.v2' or missing: + if required['schema_version'] != SCHEMA or missing: return tool_response( status='failed', task=task, @@ -949,47 +892,6 @@ def _validate_single_source_v2_contract(task: ShippingNotice, payload: dict[str, return None -def _merge_batch_callback_item(payload: dict[str, Any], item: dict[str, Any]) -> dict[str, Any]: - """ - 合并 batch 顶层契约字段到 result item。 - 核心逻辑:合并 batch 已认证的 schema_version / run_no / task_no;其余身份字段必须由 - Worker item 显式返回,禁止后端从任务或数据库补齐。 - """ - merged = dict(item) - top_schema_version = str(payload.get('schema_version') or '').strip() - if top_schema_version and not str(merged.get('schema_version') or '').strip(): - merged['schema_version'] = top_schema_version - top_run_no = str(payload.get("run_no") or "").strip() - if top_run_no and not str(merged.get("run_no") or "").strip(): - merged["run_no"] = top_run_no - - task_no = str(merged.get("task_no") or payload.get("task_no") or "").strip() - if task_no and not str(merged.get("task_no") or "").strip(): - merged["task_no"] = task_no - return merged - - -def _validate_schedule_batch_callback_run_no(schedule_run_id: int | None, callback_run_no: str) -> str | None: - """校验定时 batch 回调 run_no 与排程 run 记录一致,防止错绑终态。""" - if schedule_run_id is None: - return None - from app.models import ScheduleRun - - run = db.session.get(ScheduleRun, schedule_run_id) - if not run: - return "schedule_run_not_found" - expected = str(run.run_no or "").strip() - provided = str(callback_run_no or "").strip() - if not expected: - return "schedule_run_no_missing" - if provided != expected: - return "schedule_run_no_mismatch" - summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {} - if run.status != "running" or not summary.get("awaiting_rpa"): - return "schedule_run_not_awaiting" - return None - - def report_inventory_batch_progress(payload: dict[str, Any]) -> dict[str, Any]: """ RPA 批量导出进度回调:实时回写排程 run 的成功/跳过/失败笔数(非终态)。 @@ -998,13 +900,14 @@ def report_inventory_batch_progress(payload: dict[str, Any]) -> dict[str, Any]: 展示"执行中"run 的笔数;最终计数仍以 inventory-batch-ready 回调为准(终态化时重算覆盖)。 核心逻辑:校验 schema_version、schedule_run_id 与 run_no 匹配且 run 仍处于 awaiting_rpa; - 仅更新计数列与 response_summary_json.progress,不修改 status/started_at/finished_at, - 不影响超时回收与最终终态化。计数采用 max(现有, 上报) 防乱序回退。 + 计数写入与提交下沉 freight_rpa.onhand.workflow_protocol.record_onhand_batch_progress + (max(现有, 上报) 防乱序回退,commit 时机与拆分前一致:校验通过、计数写完后立即提交), + 本函数只保留业务响应 envelope(tool_response)。 Returns: tool_response: 进度已回写为 ok;无效/非等待态为 failed(不改变 run 状态)。 """ - if payload.get('schema_version') != 'shipping_inventory_rpa.v2': + if payload.get('schema_version') != SCHEMA: return tool_response(status='failed', message='callback_schema_invalid', data={ 'progress_status': 'invalid', 'error_code': 'callback_schema_invalid', }) @@ -1018,7 +921,7 @@ def report_inventory_batch_progress(payload: dict[str, Any]) -> dict[str, Any]: return tool_response(status='failed', message='progress_schema_invalid', data={ 'progress_status': 'invalid', 'error_code': 'callback_schema_invalid', }) - schedule_run_error = _validate_schedule_batch_callback_run_no(schedule_run_id, run_no) + schedule_run_error = validate_schedule_batch_callback_run_no(schedule_run_id, run_no) if schedule_run_error: return tool_response(status='failed', message=f'排程进度回调无效: {schedule_run_error}', data={ 'progress_status': 'rejected', 'schedule_run_error': schedule_run_error, @@ -1030,30 +933,16 @@ def report_inventory_batch_progress(payload: dict[str, Any]) -> dict[str, Any]: return tool_response(status='failed', message='schedule_run_not_found', data={ 'progress_status': 'rejected', 'schedule_run_error': 'schedule_run_not_found', }) - 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(run.response_summary_json or {}) - 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': run_no, - 'updated_at': datetime.utcnow().isoformat(), - } - run.response_summary_json = summary - db.session.commit() + counts = record_onhand_batch_progress( + run, + run_no, + 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)), + ) return tool_response(status='ok', message='库存 RPA 导出进度已回写', data={ 'progress_status': 'updated', - 'run_no': run_no, - 'success_count': int(run.success_count or 0), - 'skipped_count': int(run.skipped_count or 0), - 'failed_count': int(run.failed_count or 0), + **counts, }) @@ -1084,7 +973,7 @@ def _resolve_batch_callback_source( source_code = str(item.get("source_code") or "").strip().upper() if not source_code: return None - from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source return get_database_inventory_source(source_code) @@ -1098,7 +987,7 @@ def _batch_snapshot_verify_warehouse_id( if str(source.get('warehouse_resolution_mode') or '').lower() == 'inventory_match': return None if task: - from app.services.shipping_notice.inventory_source_gate import resolve_inventory_source_warehouse_id + from app.services.shipping_notice.onhand_source_gate import resolve_inventory_source_warehouse_id warehouse_id = resolve_inventory_source_warehouse_id(task, source=source) or '' return warehouse_id or None @@ -1143,14 +1032,14 @@ def ensure_inventory_via_rpa( allow_auto_retry: bool = True, source_codes: list[str] | None = None, ) -> dict[str, Any]: - """触发或轮询 RPA 库存导出;成功落盘时委托 inventory_workflow.inventory_loaded_response。 + """触发或轮询 RPA 库存导出;成功落盘时委托 onhand_workflow.inventory_loaded_response。 Args: allow_auto_retry: 只读轮询开关,透传 ensure_all_required_sources_prepared。 - poll_inventory_preparation 查询路径必须传 False,禁止轮询自动新建 RPA Attempt。 + poll_onhand_preparation 查询路径必须传 False,禁止轮询自动新建 RPA Attempt。 source_codes: 可选行级库存源;有值时只为这些源准备/触发 RPA,不跑整单冻结源。 """ - from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response + from app.services.shipping_notice.onhand_mapping_workflow import inventory_loaded_response manual_retry_round = mode == "retry_rpa" disposition_reason = task_execution_block_reason(task) @@ -1197,7 +1086,7 @@ def ensure_inventory_via_rpa( except AppError: apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW) # OT 在正式 Notice 创建前只保存阶段;不得写 Notice 专属 current_step。 - task.stage = "inventory_source_resolving" + task.stage = "onhand_source_resolving" _set_workflow_error(task, "库存源尚未确定,无法启动 RPA") db.session.commit() return tool_response( @@ -1230,7 +1119,7 @@ def ensure_inventory_via_rpa( _set_workflow_error(task, None) set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title='获取库存', status='running', message='已重新触发库存获取,等待各库存源回调。' if manual_retry_round else '已触发库存获取,等待各库存源回调。', @@ -1258,7 +1147,7 @@ def ensure_inventory_via_rpa( poll_read_only = not allow_auto_retry set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title='获取库存', status='needs_human', message='库存 RPA 未能为全部库存源生成结果。', @@ -1287,15 +1176,15 @@ def ensure_inventory_via_rpa( # [STEP 1] 先检查当前是否已有进行中的 RPA 导出。 # 若仍在超时窗口内,则返回 running 轮询信息;超时则补记失败事件,避免重复无脑触发。 timeout_seconds = rpa_inventory_timeout_seconds() - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task from app.services.shipping_notice.process_gate_projection import task_blocking_reason if task_blocking_reason(task) == PH_RPA_PENDING and not has_ready_inventory_file_for_task(task): - last_trigger = latest_task_event(task, "inventory_rpa_triggered") + last_trigger = latest_task_event(task, "onhand_rpa_triggered") if last_trigger and isinstance(last_trigger.created_at, datetime): elapsed = int((datetime.utcnow() - last_trigger.created_at).total_seconds()) if elapsed < timeout_seconds: - attempts = inventory_rpa_attempts(task) + attempts = onhand_rpa_attempts(task) return tool_response( status="running", task_id=task.task_no, @@ -1312,12 +1201,12 @@ def ensure_inventory_via_rpa( }, }, ) - last_failed = latest_task_event(task, "inventory_rpa_failed") + last_failed = latest_task_event(task, "onhand_rpa_failed") if not last_failed or (last_failed.created_at < last_trigger.created_at): _set_workflow_error(task, "RPA 库存导出等待超时") log_task_event( task, - "inventory_rpa_failed", + "onhand_rpa_failed", { "error": "timeout", "elapsed_seconds": elapsed, @@ -1338,7 +1227,7 @@ def ensure_inventory_via_rpa( # [STEP 2] 仅本次用户或系统明确触发可创建一次 RPA 尝试。 # 禁止消费全局 drop 目录未校验文件,必须等待 RPA 回调或复用正式快照。 - attempts = inventory_rpa_attempts(task) + attempts = onhand_rpa_attempts(task) # [STEP 3] 触发下一次 RPA 导出或给出人工兜底提示。 # 触发成功则推进到 pending;触发失败则明确要求用户改走手工上传。 @@ -1371,7 +1260,7 @@ def ensure_inventory_via_rpa( ) set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title="获取库存", status="running", message=progress_message, @@ -1383,7 +1272,7 @@ def ensure_inventory_via_rpa( ) log_task_event( task, - "inventory_rpa_triggered", + "onhand_rpa_triggered", { "trigger": trigger, "run_no": _extract_run_no_from_trigger(trigger), @@ -1421,7 +1310,7 @@ def ensure_inventory_via_rpa( _set_workflow_error(task, human_message[:500]) set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title="获取库存", status="needs_human", message=human_message, @@ -1430,7 +1319,7 @@ def ensure_inventory_via_rpa( total=max_attempts, detail=detail, ) - log_task_event(task, "inventory_rpa_retry_requested", {"reason": "trigger_failed"}) + log_task_event(task, "onhand_rpa_retry_requested", {"reason": "trigger_failed"}) db.session.commit() return tool_response( status="needs_human", @@ -1441,46 +1330,6 @@ def ensure_inventory_via_rpa( ) -def _normalize_rpa_inventory_result_status(payload: dict[str, Any]) -> str: - """ - 归一化单任务 RPA 库存回调结果。 - - 核心逻辑:优先读取 worker 上报的 status;兼容旧回调仅含 success/skipped 布尔字段; - 缺省 success 视为 true(历史单任务回调兼容)。 - - Returns: - str: success | skipped | failed - """ - raw_status = str(payload.get("status") or "").strip().lower() - if raw_status in {"success", "skipped", "failed"}: - return raw_status - if payload.get("skipped"): - return "skipped" - if bool(payload.get("success", True)): - return "success" - return "failed" - - -def _normalize_rpa_inventory_batch_item_status(item: dict[str, Any]) -> str: - """ - 归一化 batch results 单条明细(比单任务更严格:缺字段不算 success)。 - - 核心逻辑:与 worker `_normalize_inventory_batch_item_status` 对齐;空 dict 或 - 缺 status/success/skipped 直接归为 failed,避免误走 success→file_missing 分支。 - - Returns: - str: success | skipped | failed - """ - raw_status = str(item.get("status") or "").strip().lower() - if raw_status in {"success", "skipped", "failed"}: - return raw_status - if item.get("skipped"): - return "skipped" - if item.get("success") is True: - return "success" - return "failed" - - def _summarize_rpa_inventory_batch_outcome( *, created: list[Any], @@ -1571,7 +1420,7 @@ def _handle_rpa_inventory_skipped( _set_workflow_error(task, None) set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title="获取库存", status="needs_human", message="货代系统当前无可用库存", @@ -1580,7 +1429,7 @@ def _handle_rpa_inventory_skipped( ) log_task_event( task, - "inventory_rpa_skipped", + "onhand_rpa_skipped", { "skip_reason": skip_reason, "message": detail or message, @@ -1611,14 +1460,14 @@ def _handle_rpa_inventory_failed( """处理 failed 回调:记录失败事实并保留用户可重试/上传的恢复入口。""" apply_task_transition(task, TaskTransition.INV_UNAVAIL) _set_workflow_error(task, str(payload.get("error_message") or "RPA inventory export failed")[:500]) - log_task_event(task, "inventory_rpa_failed", { + log_task_event(task, "onhand_rpa_failed", { "error": _workflow_error(task), "error_code": str(payload.get("error_code") or "rpa_export_failed"), "rpa_runtime": runtime, }) set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title='获取库存', status='needs_human', message=_workflow_error(task), @@ -1682,7 +1531,7 @@ def settle_failed_inventory_callback(payload: dict[str, Any], *, error: str) -> def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: """RPA 库存导出完成回调:落盘 Excel 并进入字段映射确认。""" - from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response + from app.services.shipping_notice.onhand_mapping_workflow import inventory_loaded_response from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler cleanup_retry_warnings = flush_callback_cleanup_queue() @@ -1736,7 +1585,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: # callback_id 已归属于其他 Attempt;不得继续走兼容入口写入库存正式事实。 log_task_event( task, - 'shipping_inventory_callback_ignored', + 'freight_rpa_onhand_callback_ignored', { 'run_no': run_no_raw, 'source_code': source_code_from_run, @@ -1865,7 +1714,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: if not path.is_file(): return tool_response(status="failed", task_id=task.task_no, message="库存文件不存在") - processed = inventory_processed_dir() + processed = onhand_processed_dir() rpa_source = task_rpa_inventory_source(task) if not rpa_source or not rpa_source.get("source_code"): return tool_response( @@ -1876,7 +1725,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: ) staging_path: Path | None = None - inv_file: ShippingInventoryFile | None = None + inv_file: FreightRpaOnhandReportFile | None = None created_new = False orphan_paths: list[str | Path] = [] try: @@ -1942,7 +1791,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: if link is None: raise _RpaCallbackItemAbort("inventory_identity_mismatch") - from app.services.shipping_notice.inventory_structure_drift import validate_production_inventory_structure + from app.services.shipping_notice.onhand_structure_drift import validate_production_inventory_structure structure_check = validate_production_inventory_structure( source_code=str(rpa_source['source_code']), path=ingest_path, @@ -1970,7 +1819,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: } set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title="获取库存", status="running", message="RPA 库存文件已返回,正在读取库存快照", @@ -1986,7 +1835,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: "upload_filename": ingest_path.name, "upload_path": str(ingest_path), "origin_file_path": str(path), - "inventory_file_no": inv_file.inventory_file_no, + "inventory_file_no": inv_file.onhand_file_no, "reused_existing_snapshot": not created_new, "structure_validation": column_meta.get('structure_validation'), }, @@ -1997,7 +1846,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: lines, column_meta=column_meta, source="rpa_callback", - event_type="inventory_rpa_ready", + event_type="onhand_rpa_ready", field_mapping=dict(structure_check['field_mapping']), mapping_source='parsing_profile', commit=False, @@ -2047,7 +1896,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: path, run_no=run_no, task_no=task.task_no, - inventory_file_no=inv_file.inventory_file_no, + inventory_file_no=inv_file.onhand_file_no, ) promote_ok = False try: @@ -2068,13 +1917,13 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: processed, run_no=run_no, task_no=task.task_no, - inventory_file_no=inv_file.inventory_file_no, + inventory_file_no=inv_file.onhand_file_no, ) if move_warning: post_commit_warnings.append(f"move_callback_file_failed:{move_warning}") try: - from app.services.shipping_notice.inventory_file_store import start_inventory_file_linked_tasks + from app.services.shipping_notice.onhand_file_store import start_inventory_file_linked_tasks start_inventory_file_linked_tasks(inv_file) except Exception as exc: @@ -2088,10 +1937,25 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: if post_commit_warnings: _persist_post_commit_task_event( task, - "inventory_rpa_post_commit_warning", - {"warnings": post_commit_warnings, "inventory_file_no": inv_file.inventory_file_no}, + "onhand_rpa_post_commit_warning", + {"warnings": post_commit_warnings, "inventory_file_no": inv_file.onhand_file_no}, ) + # [STEP 阶段 B Task 7 修复] 文件行已随上方 db.session.commit() 提交——同请求投递 + # onhand 报表事实(先 commit 再投递)。处理函数异常必须原样外抛:绝不折进 + # post_commit_warnings、不吞——已提交文件行保留,Worker 重试整笔回调即可补齐 + # 候选 settle 与门禁收口(处理函数幂等:重复投递不重复候选行)。 + from app.services.freight_rpa.reports.dispatch import dispatch_report_fact + from app.services.freight_rpa.reports.facts import ReportFact + + dispatch_report_fact(ReportFact( + report_kind='onhand', + source_code=str(inv_file.source_code or ''), + file_id=int(inv_file.id), + sha256=str(inv_file.file_sha256 or '') or None, + ok=True, + )) + if response is None: return tool_response(status="failed", task=task, message="RPA 回调处理未完成") if post_commit_warnings: @@ -2101,12 +1965,13 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: - """快速收件库存 RPA batch 回调,并将业务处理交给 shipping worker。 + """快速收件库存 RPA batch 回调:排程按文件返回终态化,解析交给 shipping worker。 【AI 触发时机】:freight_rpa_worker 已完成库存文件导出、需要确认 HXOPS 已接收回调时调用。 - 本函数只验证回调信封并持久化 Job;禁止在 HTTP 请求内解析 Excel、关联任务或推进 Gate。 + 核心逻辑:校验收件信封 → 复制到受控区 → 若含 schedule_run_id 则按 RPA 导出结果 + finalize 排程(文件返回= RPA/排程结束)→ 再入队解析 Job;禁止在 HTTP 内解析 Excel。 """ - if payload.get('schema_version') != 'shipping_inventory_rpa.v2': + if payload.get('schema_version') != SCHEMA: return tool_response(status='failed', message='callback_schema_invalid', data={ 'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_schema_invalid', }) @@ -2125,7 +1990,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: existing_job = ( Job.query.filter( Job.domain == 'shipping_notice', - Job.job_type == 'shipping_inventory_callback_process', + Job.job_type == 'freight_rpa_onhand_callback_process', Job.business_ref == f'inventory-callback:{callback_id}', Job.status.in_(('queued', 'running')), ) @@ -2154,68 +2019,69 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: 'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_file_receipt_failed', }) + # [STEP] 排程:文件成功返回即按 RPA 导出结果终态化,解析成败不阻塞排程收口。 + finalize_result: dict[str, Any] = {"ok": False, "schedule_finalize_status": "skipped"} + schedule_run_id = receipt_payload.get("schedule_run_id") + try: + schedule_run_id = int(schedule_run_id) if schedule_run_id is not None else None + except (TypeError, ValueError): + schedule_run_id = None + if schedule_run_id is not None: + schedule_run_error = _validate_schedule_batch_callback_run_no(schedule_run_id, batch_run_no) + if schedule_run_error: + return tool_response( + status="failed", + message="排程 RPA 回调 run_no 无效或与当前等待轮次不一致", + data={ + "schedule_run_error": schedule_run_error, + "batch_run_no": batch_run_no, + "transport_status": "invalid", + "business_status": "rejected", + "error_code": schedule_run_error, + }, + ) + from app.services.schedule.freight_rpa_onhand_finalize import ( + finalize_shipping_inventory_schedule_run_from_rpa_results, + ) + + finalize_result = finalize_shipping_inventory_schedule_run_from_rpa_results( + schedule_run_id, + receipt_payload, + ) + from app.jobs.queue import enqueue from app.jobs.types import JobType job_id = enqueue( - JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS, + JobType.FREIGHT_RPA_ONHAND_CALLBACK_PROCESS, receipt_payload, domain='shipping_notice', business_ref=f'inventory-callback:{callback_id}', - message='库存 RPA 回调已收件,等待异步处理', + message='库存 RPA 回调已收件,等待异步解析处理', max_attempts=3, commit=True, ) + response_data: dict[str, Any] = { + 'job_id': int(job_id), + 'batch_run_no': batch_run_no, + 'result_status': 'accepted', + 'callback_result_status': 'accepted', + 'schedule_finalize_status': finalize_result.get('schedule_finalize_status'), + } + if finalize_result.get('error'): + response_data['schedule_finalize_error'] = finalize_result.get('error') + if finalize_result.get('manual_retryable'): + response_data['schedule_finalize_manual_retryable'] = True + if finalize_result.get('run_status'): + response_data['run_status'] = finalize_result.get('run_status') return tool_response( status='ok', - message='库存 RPA 回调已收件,正在异步处理库存文件。', - data={ - 'job_id': int(job_id), - 'batch_run_no': batch_run_no, - 'result_status': 'accepted', - 'callback_result_status': 'accepted', - }, + message='库存 RPA 回调已收件;排程已按导出结果收口(若适用),解析异步处理中。', + data=response_data, extra={'result_status': 'accepted'}, ) -def _resolve_shared_inventory_drop_file(raw_path: str, *, allowed_root: Path) -> Path | None: - """将 Worker 回调中的 file_path 解析为 Linux 侧共享 drop 内的真实文件。 - - Windows Worker 上报 ``C:\\HxopsRpaTest\\data\\inventory_drop\\file.xlsx``, - Ubuntu 后端通过 ``/mnt/hxops-rpa-*-data/inventory_drop/file.xlsx`` 读同一 SMB 文件。 - 安全约束:仅允许 ``allowed_root`` 下按文件名映射,拒绝路径穿越。 - """ - text = str(raw_path or '').strip() - if not text: - return None - try: - root = allowed_root.resolve() - except OSError: - return None - - candidate = Path(text) - try: - resolved = candidate.resolve() - if resolved.is_file(): - resolved.relative_to(root) - return resolved - except (OSError, ValueError, RuntimeError): - pass - - name = Path(text.replace('\\', '/')).name.strip() - if not name or name in {'.', '..'} or '/' in name or '\\' in name: - return None - mapped = (root / name).resolve() - try: - mapped.relative_to(root) - except ValueError: - return None - if mapped.is_file(): - return mapped - return None - - def _persist_batch_callback_receipt( payload: dict[str, Any], *, @@ -2230,7 +2096,7 @@ def _persist_batch_callback_receipt( Returns: 用受控副本路径替换成功项 ``file_path`` 后的 payload;无法安全收件时返回 None。 """ - allowed_root = inventory_drop_dir() + allowed_root = onhand_drop_dir() if allowed_root is None: return None try: @@ -2296,7 +2162,7 @@ def _received_batch_callback_file_path( ).strip('_') or 'unknown' receipt_root = (_storage_root() / 'rpa_callback_receipts' / safe_callback_id).resolve() - drop_dir = inventory_drop_dir() + drop_dir = onhand_drop_dir() if drop_dir is not None: mapped = _resolve_shared_inventory_drop_file(file_path, allowed_root=drop_dir) if mapped is not None: @@ -2318,20 +2184,113 @@ def _received_batch_callback_file_path( return None +class OnhandReportDispatchAfterCommitError(RuntimeError): + """批量 commit 后 onhand 事实投递失败(Task 7 修复轮 3)。 + + 用途:process_rpa_report_inventory_batch 在排程收口与 drop 文件清理入队完成后, + 把首轮投递的首个异常连同「未成功文件清单」一并外抛——Job 处器捕获后把清单写回 + payload(retry_dispatch_files)并 fail_job(retryable=True),重试经「只重投失败 + 文件」通道(_dispatch_retry_onhand_report_files)补齐,不再整批重放(整批重放 + 会被 callback_id 已消费的 replay 检查跳过、且已收口的排程 run 校验会拦下)。 + 继承 RuntimeError:与既有 RuntimeError 契约(测试 match / 调用方捕获)兼容。 + """ + + def __init__(self, message: str, *, failed_files: list[dict[str, Any]]) -> None: + super().__init__(message) + self.failed_files = list(failed_files) + + +def _dispatch_retry_onhand_report_files(retry_files: list[Any]) -> dict[str, Any]: + """Job 重试通道:只对首轮投递失败的已提交文件重投 onhand 事实(不重放整批)。 + + 【AI 触发时机】:仅由 process_rpa_report_inventory_batch 在 payload 携带 + retry_dispatch_files(Job 处理器自 OnhandReportDispatchAfterCommitError 清单写回) + 时调用;普通 Worker 回调载荷不含该键,永不进入本通道。 + 核心逻辑:逐文件 dispatch_report_fact;单文件处理函数失败先回滚未提交会话 + (半途写不得被后续 commit 持久化、PendingRollback 不得拖垮后续投递)并收集 + 首个异常与未成功清单;任一失败即携带清单重抛(重试绝不在处理函数未完成时 + 返回 ok);全部成功才返回 ok(result_status='retried'——Job 处理器据此 + finish_job,且仅在此即全部处理函数已完成的情形下才标记成功)。 + Args: + retry_files: 首轮未成功文件清单({source_code, file_id, sha256} 字典列表)。 + Returns: + tool_response:status='ok'、data.result_status='retried'(非 failed/ + partial_failed,Job 处理器走 finish_job 成功收口)。 + Raises: + OnhandReportDispatchAfterCommitError: 仍有文件投递失败(携带未成功清单, + 供 Job 处理器更新 payload 继续重试,直至 attempts 耗尽落终态 failed)。 + """ + from app.services.freight_rpa.reports.dispatch import dispatch_report_fact + from app.services.freight_rpa.reports.facts import ReportFact + + dispatch_error: Exception | None = None + remaining: list[dict[str, Any]] = [] + for item in retry_files: + if not isinstance(item, dict): + continue + try: + file_id = int(item.get('file_id')) + except (TypeError, ValueError): + continue + marker = { + 'source_code': str(item.get('source_code') or ''), + 'file_id': file_id, + 'sha256': item.get('sha256'), + } + try: + dispatch_report_fact(ReportFact( + report_kind='onhand', + source_code=marker['source_code'], + file_id=marker['file_id'], + sha256=marker['sha256'] if isinstance(marker['sha256'], str) else None, + ok=True, + )) + except Exception as exc: # noqa: BLE001 —— 回滚+只收集不中断:其余文件必须继续投递,未成功清单随专用异常重抛 + db.session.rollback() + if dispatch_error is None: + dispatch_error = exc + remaining.append(marker) + logging.getLogger(__name__).warning( + 'RPA onhand report fact retry dispatch failed: file_id=%s error=%s', + marker['file_id'], exc, exc_info=exc, + ) + if dispatch_error is not None: + raise OnhandReportDispatchAfterCommitError( + f'RPA onhand report fact retry dispatch failed: {dispatch_error}', + failed_files=remaining, + ) + return tool_response( + status='ok', + message=f'库存 RPA 回调重试完成:已补齐投递 {len(retry_files)} 个失败文件。', + data={'result_status': 'retried', 'retry_dispatch_count': len(retry_files)}, + extra={'result_status': 'retried', 'retry_dispatch_count': len(retry_files)}, + ) + + def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: """ RPA 批量库存导出回调:为每个 Warehouse 创建库存快照,可选关联发货任务。 【AI 触发时机】:freight_rpa_worker 完成 inventory_export_batch 后 POST 本接口。 核心逻辑:遍历 results;定时任务只入库;带 task_no 的成功项关联对应任务; - 含 schedule_run_id 时委托 finalize 终态化排程 run。 + 含 schedule_run_id 时:若 HTTP 已按文件返回终态化则幂等跳过 finalize, + 仍 awaiting 时才委托 finalize(兼容旧同步路径/终态失败重试)。 响应:tool_response.status 恒为 ok(payload 合法且处理完成);业务成败看 result_status。 """ - from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response + from app.services.shipping_notice.onhand_mapping_workflow import inventory_loaded_response cleanup_retry_warnings = flush_callback_cleanup_queue() - if payload.get('schema_version') != 'shipping_inventory_rpa.v2': + # [STEP 阶段 B Task 7 修复轮 3] Job 重试「只重投失败文件」通道:首轮投递失败后, + # Job 处理器把未成功文件清单写回 payload(retry_dispatch_files);重试不再整批 + # 重放(task-linked 项的 Attempt 已消费 callback_id 会被 replay 检查跳过、已收口 + # 的排程 run 校验也会拦下整批),只对清单内已提交文件重投事实(处理函数幂等)。 + # 普通回调载荷不含该键,永不进入本通道。 + retry_files = payload.get('retry_dispatch_files') if isinstance(payload, dict) else None + if retry_files: + return _dispatch_retry_onhand_report_files(retry_files) + + if payload.get('schema_version') != SCHEMA: return tool_response(status='failed', message='callback_schema_invalid', data={ 'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_schema_invalid', }) @@ -2348,7 +2307,10 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any except (TypeError, ValueError): schedule_run_id = None - schedule_run_error = _validate_schedule_batch_callback_run_no(schedule_run_id, run_no) + # 解析 Job:只校验 run 身份;排程可能已在 HTTP 收件时按 RPA 文件返回终态化。 + schedule_run_error = _validate_schedule_batch_callback_run_no( + schedule_run_id, run_no, require_awaiting=False, + ) if schedule_run_error: return tool_response( status="failed", @@ -2365,6 +2327,9 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any skipped: list[dict[str, Any]] = [] batch_new_storage_paths: list[str] = [] pending_callback_moves: list[dict[str, Any]] = [] + # [STEP 阶段 B Task 7 修复] 整批事务内落地的 onhand 报表文件清单——随 created + # 同步追加/回退(单项保存点回滚时该文件行一并消失),整批 commit 后逐文件投递事实。 + landed_onhand_files: list[dict[str, Any]] = [] try: for item in results: @@ -2386,8 +2351,8 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any if not item_callback_id and source_run_no_item: item_callback_id = f"{callback_id}:{source_run_no_item}:C1" if item_callback_id: - from app.models import ShippingTaskInventoryRpaAttempt - replay_attempt = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by(callback_id=item_callback_id).one_or_none() + from app.models import FreightRpaOnhandTaskAttempt + replay_attempt = db.session.query(FreightRpaOnhandTaskAttempt).filter_by(callback_id=item_callback_id).one_or_none() if replay_attempt is not None: skipped.append({"source_code": source_code, "task_no": task_no or None, "source_run_no": source_run_no_item, "callback_id": item_callback_id, "reason": "replayed", "original_business_status": replay_attempt.transaction_status or replay_attempt.status, "replayed": True}) continue @@ -2581,7 +2546,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any # 调度空结果保留为审计快照,但绝不链接给任务或作为 ready 库存复用。 source = _resolve_batch_callback_source(None, merged_item) if source and not task_no: - from app.services.shipping_notice.inventory_snapshot_store import create_empty_rpa_inventory_snapshot + from app.services.shipping_notice.onhand_snapshot_store import create_empty_rpa_inventory_snapshot snapshot = create_empty_rpa_inventory_snapshot( source=source, rpa_run_no=run_no or None, schedule_run_id=schedule_run_id, @@ -2590,7 +2555,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any ) skipped.append({ 'source_code': source_code, 'warehouse_id': warehouse_id, - 'skip_reason': 'no_inventory_data', 'inventory_file_no': snapshot.inventory_file_no, + 'skip_reason': 'no_inventory_data', 'inventory_file_no': snapshot.onhand_file_no, }) continue @@ -2626,8 +2591,8 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any "error": "file_missing", }) if task_no and source_run_no_item: - from app.models import ShippingTaskInventoryRpaAttempt - _att = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by(task_no=task_no, source_code=source_code, source_run_no=source_run_no_item).one_or_none() + from app.models import FreightRpaOnhandTaskAttempt + _att = db.session.query(FreightRpaOnhandTaskAttempt).filter_by(task_no=task_no, source_code=source_code, source_run_no=source_run_no_item).one_or_none() if _att: _att.callback_id = item_callback_id or callback_id _att.callback_received_at = datetime.utcnow(); _att.file_generated = False; _att.file_exists_at_callback = False @@ -2675,7 +2640,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any item_savepoint = db.session.begin_nested() item_orphan_path: str | None = None created_new = False - inv_file: ShippingInventoryFile | None = None + inv_file: FreightRpaOnhandReportFile | None = None created_entry: dict[str, Any] | None = None try: try: @@ -2704,7 +2669,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any ): item_orphan_path = str(inv_file.storage_path) - from app.services.shipping_notice.inventory_structure_drift import validate_production_inventory_structure + from app.services.shipping_notice.onhand_structure_drift import validate_production_inventory_structure ingest_path = _snapshot_ingest_path(inv_file) structure_check = validate_production_inventory_structure( @@ -2715,7 +2680,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any inv_file.mapping_source = 'parsing_profile' inv_file.mapping_confirmed = True created_entry = { - "inventory_file_no": inv_file.inventory_file_no, + "inventory_file_no": inv_file.onhand_file_no, "source_code": inv_file.source_code or source_code, "warehouse_id": inv_file.warehouse_id or warehouse_id, "reused_existing_snapshot": not created_new, @@ -2728,6 +2693,13 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any }, } created.append(created_entry) + # [STEP 阶段 B Task 7 修复] 记录落地文件(含复用行——同样随整批事务提交), + # 供整批 commit 后投递 onhand 报表事实;except 分支随 created 一并回退。 + landed_onhand_files.append({ + 'source_code': str(inv_file.source_code or source_code or ''), + 'file_id': int(inv_file.id), + 'sha256': str(inv_file.file_sha256 or '') or None, + }) if item_orphan_path: batch_new_storage_paths.append(item_orphan_path) @@ -2761,7 +2733,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any lines, column_meta=column_meta, source="rpa_batch_callback", - event_type="inventory_rpa_ready", + event_type="onhand_rpa_ready", field_mapping=dict(structure_check['field_mapping']), mapping_source='parsing_profile', commit=False, @@ -2782,7 +2754,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any run_no=source_run_no_item, callback_payload={ **dict(merged_item), - 'inventory_file_no': inv_file.inventory_file_no, + 'inventory_file_no': inv_file.onhand_file_no, }, ) if final_code != 'succeeded': @@ -2790,7 +2762,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any f'per_source_callback_confirmation_failed:{final_code}' ) - drop_dir = inventory_drop_dir() + drop_dir = onhand_drop_dir() is_drop_file = False if drop_dir is not None: try: @@ -2804,20 +2776,24 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any "run_no": run_no or None, "task_no": task_no or None, "schedule_run_id": schedule_run_id, - "inventory_file_no": inv_file.inventory_file_no, + "inventory_file_no": inv_file.onhand_file_no, }) item_savepoint.commit() except _RpaCallbackItemAbort as abort: item_savepoint.rollback() if item_orphan_path: - from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path + from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path delete_inventory_storage_path(item_orphan_path) if batch_new_storage_paths and batch_new_storage_paths[-1] == item_orphan_path: batch_new_storage_paths.pop() if created_entry and created and created[-1] is created_entry: created.pop() + # [STEP 阶段 B Task 7 修复] 随 created 一并回退落地文件记录 + # (保存点回滚后该文件行已消失,不得再投递其事实)。 + if landed_onhand_files: + landed_onhand_files.pop() failed.append({ "source_code": source_code, "warehouse_id": warehouse_id, @@ -2828,13 +2804,17 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any except Exception as exc: item_savepoint.rollback() if item_orphan_path: - from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path + from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path delete_inventory_storage_path(item_orphan_path) if batch_new_storage_paths and batch_new_storage_paths[-1] == item_orphan_path: batch_new_storage_paths.pop() if created_entry and created and created[-1] is created_entry: created.pop() + # [STEP 阶段 B Task 7 修复] 随 created 一并回退落地文件记录 + # (保存点回滚后该文件行已消失,不得再投递其事实)。 + if landed_onhand_files: + landed_onhand_files.pop() failed.append({ "source_code": source_code, "warehouse_id": warehouse_id, @@ -2860,7 +2840,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any db.session.commit() except Exception as exc: db.session.rollback() - from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path + from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path for storage_path in batch_new_storage_paths: delete_inventory_storage_path(storage_path) @@ -2873,9 +2853,47 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any }, ) + # [STEP 阶段 B Task 7 修复轮 2/3] 整批文件行已随上方 db.session.commit() 提交——同一 + # worker 调用内逐文件投递 onhand 报表事实(先 commit 再投递)。必须放在外层 + # except 之后:处理函数异常若落入该 except 会误删已提交文件的存储对象。 + # 单文件处理函数失败只收集首个异常并继续投递其余已提交文件(不得因一文件失败 + # 跳过其余文件的候选/门禁收口);【修复轮 3】失败点先回滚未提交会话——丢弃该次 + # 处理函数半途 flush 的候选/门禁写(否则会被下一个处理函数的 commit / finalize + # 的 commit 误持久化,且数据库错误后的 PendingRollback 会拖垮后续投递与收口), + # 已 commit 的文件行不受影响(rollback 只丢弃未提交变更)。首个异常与未成功 + # 文件清单在排程收口、drop 文件清理入队之后携带在专用异常上原样重抛(见下)—— + # 调用方见到失败、文件行保留,Job 按 retryable=True 契约经「只重投失败文件」 + # 通道补齐(处理函数幂等:重复投递不重复候选行)。空结果审计快照 + # (create_empty_rpa_inventory_snapshot,no_inventory_data 分支)不投递——其明令 + # 不作为可用库存复用,投递 ok=True 事实会错误 settle 等待中的候选准备。 + from app.services.freight_rpa.reports.dispatch import dispatch_report_fact + from app.services.freight_rpa.reports.facts import ReportFact + + dispatch_error: Exception | None = None + failed_dispatch_files: list[dict[str, Any]] = [] + for landed in landed_onhand_files: + try: + dispatch_report_fact(ReportFact( + report_kind='onhand', + source_code=str(landed['source_code'] or ''), + file_id=int(landed['file_id']), + sha256=landed['sha256'], + ok=True, + )) + except Exception as exc: # noqa: BLE001 —— 回滚+只收集不中断:其余已提交文件必须继续投递,首个异常携带未成功清单在收口/清理之后重抛 + # [修复轮 3] 回滚未提交会话:半途写不得被后续 commit 持久化;PendingRollback 解除。 + db.session.rollback() + if dispatch_error is None: + dispatch_error = exc + failed_dispatch_files.append(dict(landed)) + logging.getLogger(__name__).warning( + 'RPA onhand report fact dispatch failed after batch commit: file_id=%s error=%s', + landed['file_id'], exc, exc_info=exc, + ) + finalize_result: dict[str, Any] = {"ok": False, "schedule_finalize_status": "skipped"} if schedule_run_id is not None: - from app.services.schedule.shipping_inventory_rpa_finalize import finalize_shipping_inventory_schedule_run + from app.services.schedule.freight_rpa_onhand_finalize import finalize_shipping_inventory_schedule_run finalize_result = finalize_shipping_inventory_schedule_run( schedule_run_id, @@ -2890,10 +2908,22 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any callback_move_warnings.extend( _flush_pending_callback_moves( pending_callback_moves, - inventory_processed_dir(), + onhand_processed_dir(), ), ) + # [STEP 阶段 B Task 7 修复轮 3] drop 文件清理已先行入队/移动(不得因重抛被跳过 + # ——清理只在 _flush_pending_callback_moves 内写消费标记/入队,先于此处执行): + # 首个投递异常携带未成功文件清单在专用异常上原样重抛——调用方(Job/Worker) + # 见到失败、已提交文件行保留;Job 处理器把清单写回 payload(retry_dispatch_files) + # 后 fail_job(retryable=True),重试经「只重投失败文件」通道补齐(见函数头部), + # 全部投递成功前绝不返回 ok(重试不得在处理函数未完成时被记成功)。 + if dispatch_error is not None: + raise OnhandReportDispatchAfterCommitError( + f'RPA onhand report fact dispatch failed after batch commit: {dispatch_error}', + failed_files=failed_dispatch_files, + ) + response_data = { "run_no": run_no, "created": created, @@ -2942,7 +2972,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any def _validate_repair_inventory_snapshot( task: ShippingNotice, - inv_file: ShippingInventoryFile | None, + inv_file: FreightRpaOnhandReportFile | None, *, requested_file_no: str | None = None, ) -> str | None: @@ -2950,10 +2980,10 @@ def _validate_repair_inventory_snapshot( 校验修复接口允许使用的库存快照。 核心逻辑:默认仅 active link;显式 file_no 必须与 active 一致,且 ready/未过期/身份匹配。 """ - from app.models import ShippingTaskInventoryLink - from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task - from app.services.shipping_notice.inventory_snapshot_store import is_snapshot_fresh - from app.services.shipping_notice.inventory_source_gate import ( + from app.models import ShippingTaskOnhandLink + from app.services.shipping_notice.onhand_file_store import active_inventory_file_for_task + from app.services.shipping_notice.onhand_snapshot_store import is_snapshot_fresh + from app.services.shipping_notice.onhand_source_gate import ( inventory_identities_match, is_inventory_source_stable, ) @@ -2965,12 +2995,12 @@ def _validate_repair_inventory_snapshot( return "no_active_snapshot" if inv_file.id != active.id: return "snapshot_not_active_for_task" - if requested_file_no and active.inventory_file_no != requested_file_no: + if requested_file_no and active.onhand_file_no != requested_file_no: return "snapshot_not_active_for_task" if task.id is not None: - link = ShippingTaskInventoryLink.query.filter_by( + link = ShippingTaskOnhandLink.query.filter_by( task_id=task.id, - inventory_file_id=inv_file.id, + onhand_file_id=inv_file.id, is_active=True, ).first() if link is None: @@ -2981,7 +3011,7 @@ def _validate_repair_inventory_snapshot( return "snapshot_expired" if not is_inventory_source_stable(task): return "inventory_source_unstable" - from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source source = get_database_inventory_source(inv_file.source_code) if source and str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed': @@ -3005,7 +3035,7 @@ def repair_task_inventory_attachment(payload: dict[str, Any]) -> dict[str, Any]: Returns: tool_response:含 attachment_path 与 inventory_file_no。 """ - from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import active_inventory_file_for_task task = resolve_task_from_payload(payload) if not task: @@ -3020,7 +3050,7 @@ def repair_task_inventory_attachment(payload: dict[str, Any]) -> dict[str, Any]: message="任务无可用库存快照,无法重建附件", data=serialize_task_for_tool(task), ) - if inv_file_no and inv_file.inventory_file_no != inv_file_no: + if inv_file_no and inv_file.onhand_file_no != inv_file_no: return tool_response( status="failed", task=task, @@ -3055,7 +3085,7 @@ def repair_task_inventory_attachment(payload: dict[str, Any]) -> dict[str, Any]: task, "inventory_attachment_repaired", { - "inventory_file_no": inv_file.inventory_file_no, + "inventory_file_no": inv_file.onhand_file_no, "attachment_path": str(attachment_path), "source": str(payload.get("source") or "manual_repair"), }, @@ -3077,7 +3107,7 @@ def repair_task_inventory_attachment(payload: dict[str, Any]) -> dict[str, Any]: message="任务库存附件已从快照重建", data={ **serialize_task_for_tool(task), - "inventory_file_no": inv_file.inventory_file_no, + "inventory_file_no": inv_file.onhand_file_no, "attachment_path": str(attachment_path), }, ) diff --git a/backend/app/services/shipping_notice/inventory_snapshot.py b/backend/app/services/shipping_notice/onhand_snapshot.py similarity index 96% rename from backend/app/services/shipping_notice/inventory_snapshot.py rename to backend/app/services/shipping_notice/onhand_snapshot.py index af621fdd..2b696a75 100644 --- a/backend/app/services/shipping_notice/inventory_snapshot.py +++ b/backend/app/services/shipping_notice/onhand_snapshot.py @@ -1,9 +1,9 @@ """ -services/shipping_notice/inventory_snapshot.py +services/shipping_notice/onhand_snapshot.py 用途:解析库存 Excel/文本快照,抽取表头、库存行与字段对齐预览,为库存映射与匹配流程提供基础数据。 依赖:openpyxl、xlrd、reservation_id、Flask current_app 配置、Path 文件操作。 -逻辑:由 inventory_workflow、inventory_mapping_workflow 等上游模块调用本文件读取库存附件,再把解析结果传给字段映射确认和库存匹配链路。 +逻辑:由 onhand_workflow、onhand_mapping_workflow 等上游模块调用本文件读取库存附件,再把解析结果传给字段映射确认和库存匹配链路。 """ from __future__ import annotations @@ -187,12 +187,12 @@ def _normalize_inventory_row( # Published profiles use inventory field IDs as row keys. Field purpose and # value type come from the user-maintained catalog, never from a fixed code. if configured_mapping and columns and all(str(field_id).isdigit() for field_id in columns): - from app.models import ShippingInventoryField + from app.models import FreightRpaOnhandField field_ids = {int(field_id) for field_id in columns if str(field_id).isdigit()} catalog = { str(item.id): item - for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all() + for item in FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(field_ids)).all() } parsed = { field_id: _cell(row, index) @@ -334,7 +334,7 @@ def _load_excel_rows( """Load configured worksheet or CSV rows; returns rows and total row count hint.""" suffix = path.suffix.lower() if suffix == ".csv": - from app.services.shipping_notice.inventory_file_identity import load_inventory_csv_rows + from app.services.shipping_notice.onhand_file_identity import load_inventory_csv_rows rows = load_inventory_csv_rows(path, max_rows=max_rows) try: @@ -422,7 +422,7 @@ def describe_inventory_columns( ) -> dict[str, Any]: """根据规则建议或已发布方案生成库存栏位与匹配规则的审计描述。""" if field_mapping: - from app.services.shipping_notice.inventory_mapping import build_column_meta_from_mapping + from app.services.shipping_notice.onhand_mapping import build_column_meta_from_mapping return build_column_meta_from_mapping( headers, @@ -587,7 +587,7 @@ def parse_inventory_rows( ) -> list[dict[str, Any]]: """按表头与数据行解析库存表格(Excel 或文档提取文本共用)。""" if field_mapping: - from app.services.shipping_notice.inventory_mapping import resolve_columns_from_field_mapping + from app.services.shipping_notice.onhand_mapping import resolve_columns_from_field_mapping columns = resolve_columns_from_field_mapping(headers, field_mapping) else: @@ -627,7 +627,7 @@ def parse_inventory_text( header = rows[0] if field_mapping: - from app.services.shipping_notice.inventory_mapping import resolve_columns_from_field_mapping + from app.services.shipping_notice.onhand_mapping import resolve_columns_from_field_mapping has_header = True column_meta = describe_inventory_columns( @@ -659,7 +659,7 @@ def read_inventory_schema_preview( max_sample_rows: int = 5, ) -> dict[str, Any]: """仅读取表头与样本行(供 LLM 推断列映射,不加载全量数据)。""" - from app.services.shipping_notice.inventory_mapping import suggest_field_mapping + from app.services.shipping_notice.onhand_mapping import suggest_field_mapping scan_rows, total_rows = _load_excel_rows(path, max_rows=40) if not scan_rows: @@ -724,7 +724,7 @@ def parse_inventory_excel_with_meta( headers = [str(c or "").strip() for c in rows[header_idx]] data_rows = [list(r) for r in rows[header_idx + 1 :] if r] if not field_mapping: - from app.services.shipping_notice.inventory_mapping import suggest_field_mapping + from app.services.shipping_notice.onhand_mapping import suggest_field_mapping suggested = suggest_field_mapping(headers) if suggested.get("part_number") and suggested.get("available_qty"): diff --git a/backend/app/services/shipping_notice/inventory_snapshot_reuse_policy.py b/backend/app/services/shipping_notice/onhand_snapshot_reuse_policy.py similarity index 95% rename from backend/app/services/shipping_notice/inventory_snapshot_reuse_policy.py rename to backend/app/services/shipping_notice/onhand_snapshot_reuse_policy.py index c6b4c354..1dd729c2 100644 --- a/backend/app/services/shipping_notice/inventory_snapshot_reuse_policy.py +++ b/backend/app/services/shipping_notice/onhand_snapshot_reuse_policy.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/inventory_snapshot_reuse_policy.py +services/shipping_notice/onhand_snapshot_reuse_policy.py 用途:统一判断库存快照是否可被当前任务复用。 -依赖:ShippingInventoryFile、ShippingNotice、候选冻结事实。 +依赖:FreightRpaOnhandReportFile、ShippingNotice、候选冻结事实。 逻辑:所有关键身份和版本条件均 fail-closed;返回结构化原因供审计和 Projection 使用。 """ diff --git a/backend/app/services/shipping_notice/inventory_snapshot_store.py b/backend/app/services/shipping_notice/onhand_snapshot_store.py similarity index 79% rename from backend/app/services/shipping_notice/inventory_snapshot_store.py rename to backend/app/services/shipping_notice/onhand_snapshot_store.py index 9d12e71f..9c3037f7 100644 --- a/backend/app/services/shipping_notice/inventory_snapshot_store.py +++ b/backend/app/services/shipping_notice/onhand_snapshot_store.py @@ -1,9 +1,12 @@ """ -services/shipping_notice/inventory_snapshot_store.py +services/shipping_notice/onhand_snapshot_store.py 用途:库存快照查询、TTL 复用、RPA 入库与任务关联审计。 -依赖:models.ShippingInventoryFile/ShippingTaskInventoryLink、inventory_file_store、Flask config。 -逻辑:ensure_inventory 优先调用本模块查找未过期快照;RPA batch callback 创建快照记录。 +依赖:models.FreightRpaOnhandReportFile/ShippingTaskOnhandLink(只读取回行,禁止构造)、 + freight_rpa/onhand/report_store(快照行插入唯一入口)、onhand_file_store、Flask config。 +逻辑:ensure_onhand 优先调用本模块查找未过期快照;RPA batch callback 创建快照记录; + 阶段 B Task 5 起新建/空快照行一律经 report_store.insert_onhand_report 插入, + 本模块只在拿回 file_id 后按主键取回 ORM 对象并维护任务 link(关联表留在发货域)。 """ from __future__ import annotations @@ -19,36 +22,37 @@ from sqlalchemy.orm import Session from app import db from app.core.errors import AppError -from app.models import ShippingInventoryFile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink +from app.models import FreightRpaOnhandReportFile, ShippingNotice, ShippingTaskEvent, ShippingTaskOnhandLink from app.services.shipping_notice.tool_common import task_event_task_id -from app.services.shipping_notice.inventory_file_store import ( +from app.services.freight_rpa.onhand.report_store import insert_onhand_report +from app.services.shipping_notice.onhand_file_store import ( _can_relink_inventory, generate_inventory_file_no, inventory_file_upload_path, inventory_storage_suffix_for_path, replace_task_inventory_link, ) -from app.services.shipping_notice.inventory_snapshot import read_inventory_schema_preview +from app.services.shipping_notice.onhand_snapshot import read_inventory_schema_preview _SNAPSHOT_STATUS_READY = "ready" _SNAPSHOT_STATUS_EMPTY = "empty" _SNAPSHOT_STATUS_FAILED = "failed" _SNAPSHOT_STATUS_EXPIRED = "expired" -# 请求内只读缓存(key: (source_code, warehouse_id) → ShippingInventoryFile | None)。 +# 请求内只读缓存(key: (source_code, warehouse_id) → FreightRpaOnhandReportFile | None)。 # 同一请求内 _build_stp_facts / _build_stage_context / 行级匹配会重复查询同一 # (source, warehouse) 的最新 ready 快照(实测 task detail 一次请求重复 3 次)。 # 任何快照行写入(新建/过期/更新)都会由 after_flush 事件失效,保证写后读可见。 -_READ_CACHE_KEY = "shipping_inventory_snapshot_read_cache" +_READ_CACHE_KEY = "shipping_onhand_snapshot_read_cache" @_sa_event.listens_for(Session, "after_flush") def _clear_snapshot_read_cache_on_write(session, flush_context): # noqa: ANN001 """快照写入路径统一失效点:覆盖全部创建/过期/更新调用方,无需逐处接线。""" touched = ( - any(isinstance(obj, ShippingInventoryFile) for obj in session.new) - or any(isinstance(obj, ShippingInventoryFile) for obj in session.dirty) - or any(isinstance(obj, ShippingInventoryFile) for obj in session.deleted) + any(isinstance(obj, FreightRpaOnhandReportFile) for obj in session.new) + or any(isinstance(obj, FreightRpaOnhandReportFile) for obj in session.dirty) + or any(isinstance(obj, FreightRpaOnhandReportFile) for obj in session.deleted) ) if touched: session.info.pop(_READ_CACHE_KEY, None) @@ -80,10 +84,10 @@ def snapshot_expires_at(exported_at: datetime | None = None) -> datetime: return base + timedelta(hours=inventory_snapshot_ttl_hours()) -def is_snapshot_fresh(inv_file: ShippingInventoryFile, *, now: datetime | None = None) -> bool: +def is_snapshot_fresh(inv_file: FreightRpaOnhandReportFile, *, now: datetime | None = None) -> bool: """ 判断库存快照是否仍处于 ready 且未过期。 - 【AI 触发时机】:ensure_inventory 决定是否复用已有快照前调用。 + 【AI 触发时机】:ensure_onhand 决定是否复用已有快照前调用。 """ if not inv_file or str(inv_file.snapshot_status or "").strip().lower() != _SNAPSHOT_STATUS_READY: return False @@ -99,7 +103,7 @@ def is_snapshot_fresh(inv_file: ShippingInventoryFile, *, now: datetime | None = def find_latest_ready_snapshot( source_code: str | None, warehouse_id: str | None = None, -) -> ShippingInventoryFile | None: +) -> FreightRpaOnhandReportFile | None: """ 查找指定 Source 的最新 ready 且未过期库存快照。 核心逻辑:固定 Source 限定 Warehouse;动态 Source 先复用文件,再由 reservation + PN 匹配确定 Warehouse。 @@ -119,14 +123,14 @@ def find_latest_ready_snapshot( if cache_key in read_cache: return read_cache[cache_key] - query = ShippingInventoryFile.query.filter_by( + query = FreightRpaOnhandReportFile.query.filter_by( source_code=code, snapshot_status=_SNAPSHOT_STATUS_READY, ) if warehouse: query = query.filter_by(warehouse_id=warehouse) - rows = query.order_by(ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc()).limit(5).all() + rows = query.order_by(FreightRpaOnhandReportFile.exported_at.desc(), FreightRpaOnhandReportFile.id.desc()).limit(5).all() result = None for row in rows: if is_snapshot_fresh(row): @@ -141,7 +145,7 @@ def find_ready_rpa_inventory_snapshot( rpa_run_no: str, source_code: str, warehouse_id: str, -) -> ShippingInventoryFile | None: +) -> FreightRpaOnhandReportFile | None: """ 按 RPA 轮次 + Source/Warehouse 身份查找已入库 ready 快照。 核心逻辑:定时 finalize 重试或并发回调时复用同一快照,避免重复落盘。 @@ -152,13 +156,13 @@ def find_ready_rpa_inventory_snapshot( if not run_no or not code or not warehouse: return None return ( - ShippingInventoryFile.query.filter_by( + FreightRpaOnhandReportFile.query.filter_by( rpa_run_no=run_no, source_code=code, warehouse_id=warehouse, snapshot_status=_SNAPSHOT_STATUS_READY, ) - .order_by(ShippingInventoryFile.id.desc()) + .order_by(FreightRpaOnhandReportFile.id.desc()) .first() ) @@ -177,13 +181,13 @@ def get_or_create_rpa_inventory_snapshot( batch_id: int | None = None, share_mode: str | None = None, verify_warehouse_id: str | None = None, -) -> tuple[ShippingInventoryFile, bool]: +) -> tuple[FreightRpaOnhandReportFile, bool]: """ 幂等创建 RPA 库存快照:同 run_no + 身份已存在时直接复用。 核心逻辑:先查后建;并发插入冲突时回退到 savepoint 并复用已有记录。 Returns: - tuple[ShippingInventoryFile, bool]: (快照, 是否新建)。 + tuple[FreightRpaOnhandReportFile, bool]: (快照, 是否新建)。 """ from sqlalchemy.exc import IntegrityError @@ -224,7 +228,7 @@ def get_or_create_rpa_inventory_snapshot( except IntegrityError: savepoint.rollback() if orphan_storage_path: - from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path + from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path delete_inventory_storage_path(orphan_storage_path) if run_no and code and warehouse: @@ -239,7 +243,7 @@ def get_or_create_rpa_inventory_snapshot( except Exception: savepoint.rollback() if orphan_storage_path: - from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path + from app.services.shipping_notice.onhand_file_store import delete_inventory_storage_path delete_inventory_storage_path(orphan_storage_path) raise @@ -250,18 +254,18 @@ def list_available_snapshots( source_code: str | None = None, warehouse_id: str | None = None, limit: int = 20, -) -> list[ShippingInventoryFile]: +) -> list[FreightRpaOnhandReportFile]: """列出未过期 ready 快照,供工作台查询。""" - query = ShippingInventoryFile.query.filter_by(snapshot_status=_SNAPSHOT_STATUS_READY) + query = FreightRpaOnhandReportFile.query.filter_by(snapshot_status=_SNAPSHOT_STATUS_READY) if source_code: query = query.filter_by(source_code=str(source_code).strip().upper()) if warehouse_id: query = query.filter_by(warehouse_id=str(warehouse_id).strip().upper()) - rows = query.order_by(ShippingInventoryFile.exported_at.desc()).limit(max(limit, 1)).all() + rows = query.order_by(FreightRpaOnhandReportFile.exported_at.desc()).limit(max(limit, 1)).all() return [row for row in rows if is_snapshot_fresh(row)] -def expire_snapshot(inv_file: ShippingInventoryFile, reason: str) -> None: +def expire_snapshot(inv_file: FreightRpaOnhandReportFile, reason: str) -> None: """将快照标记为 expired。""" inv_file.snapshot_status = _SNAPSHOT_STATUS_EXPIRED inv_file.updated_at = datetime.utcnow() @@ -274,7 +278,7 @@ def _normalize_header_key(value: Any) -> str: def _extract_warehouse_id_from_inventory_excel(path: Path) -> str: """从库存 Excel 提取首个 Warehouse ID(兼容旧调用)。""" - from app.services.shipping_notice.inventory_file_identity import extract_warehouse_ids_from_inventory_excel + from app.services.shipping_notice.onhand_file_identity import extract_warehouse_ids_from_inventory_excel values = extract_warehouse_ids_from_inventory_excel(path) if not values: @@ -298,7 +302,7 @@ def create_inventory_snapshot_from_rpa( batch_id: int | None = None, share_mode: str | None = None, verify_warehouse_id: str | None = None, -) -> ShippingInventoryFile: +) -> FreightRpaOnhandReportFile: """ 从 RPA 导出文件创建库存快照记录。 【AI 触发时机】:RPA 单条或 batch 回调成功/失败时调用;定时任务只入库不绑定发货任务。 @@ -310,7 +314,7 @@ def create_inventory_snapshot_from_rpa( success: False 时写入 failed 快照,不复制文件到标准目录。 Returns: - ShippingInventoryFile: 已持久化的快照对象。 + FreightRpaOnhandReportFile: 已持久化的快照对象。 """ exported_at = datetime.utcnow() inventory_file_no = generate_inventory_file_no() @@ -328,7 +332,7 @@ def create_inventory_snapshot_from_rpa( local = Path(local_path) # 仅采集文件中的 Warehouse 作为审计信息,不将外部编码与 HXOPS 配置编码做一致性拦截。 try: - from app.services.shipping_notice.inventory_file_identity import extract_warehouse_ids_from_inventory_excel + from app.services.shipping_notice.onhand_file_identity import extract_warehouse_ids_from_inventory_excel excel_warehouse_ids = extract_warehouse_ids_from_inventory_excel(local) if len(excel_warehouse_ids) == 1: @@ -354,10 +358,13 @@ def create_inventory_snapshot_from_rpa( snapshot_status = _SNAPSHOT_STATUS_FAILED storage_path = str(path) if path and path.is_file() else "" - from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version + from app.services.shipping_notice.onhand_source_repository import inventory_sources_runtime_version - inv_file = ShippingInventoryFile( - inventory_file_no=inventory_file_no, + # [STEP] 阶段 B Task 5:行插入收敛进 freight_rpa/onhand/report_store(只 flush 不 commit), + # 本模块只在拿到 file_id 后取回 ORM 对象;先 flush 再落盘的语义由 report_store 保持, + # 唯一约束冲突时同样不会留下已复制的孤儿文件。 + file_id = insert_onhand_report( + onhand_file_no=inventory_file_no, user_id=user_id, source_file_name=str(source_file_name or (path.name if path else "")).strip() or None, storage_path=storage_path or f"failed://{inventory_file_no}", @@ -399,9 +406,8 @@ def create_inventory_snapshot_from_rpa( "trigger_type": trigger_type, }, ) - db.session.add(inv_file) - db.session.flush() - # [STEP] 先 flush 再落盘:唯一约束冲突时不会留下已复制的孤儿文件。 + inv_file = db.session.get(FreightRpaOnhandReportFile, file_id) + # [STEP] flush 已在 report_store 内完成,此处先落盘再返回:唯一约束冲突(上面 insert 抛出)时不会留下已复制的孤儿文件。 if success and storage_path and not str(storage_path).startswith("failed://"): path = Path(storage_path) path.parent.mkdir(parents=True, exist_ok=True) @@ -420,25 +426,26 @@ def create_inventory_snapshot_from_rpa( def create_empty_rpa_inventory_snapshot( *, source: dict[str, Any], rpa_run_no: str | None, schedule_run_id: int | None, trigger_type: str, message: str | None = None, -) -> ShippingInventoryFile: +) -> FreightRpaOnhandReportFile: """记录 RPA 已成功执行但没有库存行的空快照;空快照永不参与库存匹配。""" exported_at = datetime.utcnow() - from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version + from app.services.shipping_notice.onhand_source_repository import inventory_sources_runtime_version source_code = str(source.get('source_code') or '').strip().upper() warehouse_id = str(source.get('warehouse_id') or '').strip().upper() or None run_no = str(rpa_run_no or '').strip() or None if run_no and source_code: - existing = ShippingInventoryFile.query.filter_by( + existing = FreightRpaOnhandReportFile.query.filter_by( rpa_run_no=run_no, source_code=source_code, warehouse_id=warehouse_id, snapshot_status=_SNAPSHOT_STATUS_EMPTY, - ).order_by(ShippingInventoryFile.id.desc()).first() + ).order_by(FreightRpaOnhandReportFile.id.desc()).first() if existing is not None: return existing - inv_file = ShippingInventoryFile( - inventory_file_no=generate_inventory_file_no(), storage_path=f'empty://{source_code or "inventory"}', + # [STEP] 阶段 B Task 5:空快照行同样经 report_store 插入(列集与原构造逐项一致;只 flush 不 commit)。 + file_id = insert_onhand_report( + onhand_file_no=generate_inventory_file_no(), storage_path=f'empty://{source_code or "inventory"}', schema_preview_json={'export_result': 'empty', 'message': str(message or '库存查询成功但当前无库存数据')[:500]}, - share_mode='warehouse_pool', line_count=0, inventory_lines_json=[], warehouse_id=warehouse_id, + share_mode='warehouse_pool', line_count=0, onhand_lines_json=[], warehouse_id=warehouse_id, warehouse_code=warehouse_id, source_code=source_code or None, source_type=str(source.get('connector_type') or '').strip() or None, # 空快照没有可验证的行级身份;使用数据库枚举中的 unknown,避免审计入库失败。 @@ -447,41 +454,39 @@ def create_empty_rpa_inventory_snapshot( rpa_run_no=run_no, schedule_run_id=schedule_run_id, source_query_json={'trigger_type': trigger_type, 'export_result': 'empty'}, ) - db.session.add(inv_file) - db.session.flush() - return inv_file + return db.session.get(FreightRpaOnhandReportFile, file_id) def link_snapshot_to_task( task: ShippingNotice, - inv_file: ShippingInventoryFile, + inv_file: FreightRpaOnhandReportFile, *, reason: str, role: str = "member", audit_payload: dict[str, Any] | None = None, -) -> ShippingTaskInventoryLink | None: +) -> ShippingTaskOnhandLink | None: """ 将 ready 库存快照关联到发货任务并写入审计字段。 - 【AI 触发时机】:ensure_inventory 复用快照或 RPA 回调带 task_no 时调用。 + 【AI 触发时机】:ensure_onhand 复用快照或 RPA 回调带 task_no 时调用。 Returns: - ShippingTaskInventoryLink | None: 终态任务不允许 relink 时返回 None。 + ShippingTaskOnhandLink | None: 终态任务不允许 relink 时返回 None。 """ if not _can_relink_inventory(task): return None if not is_snapshot_fresh(inv_file): return None - from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source source = get_database_inventory_source(inv_file.source_code) if source is None: return None resolved_warehouse_id = inv_file.warehouse_id if str(source.get('warehouse_resolution_mode') or '').strip().lower() == 'inventory_match': - from app.services.shipping_notice.inventory_warehouse_resolution import resolve_dynamic_warehouse + from app.services.shipping_notice.onhand_warehouse_resolution import resolve_dynamic_warehouse - from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines + from app.services.shipping_notice.onhand_file_store import read_inventory_file_lines try: lines, _column_meta = read_inventory_file_lines(inv_file) @@ -508,7 +513,7 @@ def link_snapshot_to_task( if inv_file.exported_at: age_seconds = max(int((datetime.utcnow() - inv_file.exported_at).total_seconds()), 0) - from app.services.shipping_notice.inventory_source_gate import inventory_identities_match + from app.services.shipping_notice.onhand_source_gate import inventory_identities_match identity_ok = inventory_identities_match( task, @@ -532,7 +537,7 @@ def link_snapshot_to_task( "warehouse_id": resolved_warehouse_id, "exported_at": inv_file.exported_at.isoformat() if inv_file.exported_at else None, "expires_at": inv_file.expires_at.isoformat() if inv_file.expires_at else None, - "inventory_file_no": inv_file.inventory_file_no, + "inventory_file_no": inv_file.onhand_file_no, "trigger_type": (inv_file.source_query_json or {}).get("trigger_type"), } db.session.add( @@ -540,7 +545,7 @@ def link_snapshot_to_task( task_id=task_event_task_id(task), event_type="inventory_snapshot_linked", detail_json={ - "inventory_file_no": inv_file.inventory_file_no, + "inventory_file_no": inv_file.onhand_file_no, "link_reason": reason, "snapshot_age_seconds": age_seconds, "warehouse_id": resolved_warehouse_id, @@ -553,11 +558,11 @@ def link_snapshot_to_task( def link_snapshot_to_task_for_preparation( task: ShippingNotice, - inv_file: ShippingInventoryFile, + inv_file: FreightRpaOnhandReportFile, *, reason: str, audit_payload: dict[str, Any] | None = None, -) -> ShippingTaskInventoryLink | None: +) -> ShippingTaskOnhandLink | None: """将 RPA 已准备快照关联任务;动态仓身份待匹配时保留文件事实。 动态仓的 Warehouse 只能由下一阶段用订单键匹配库存行得出。若该匹配尚无结论, @@ -573,7 +578,7 @@ def link_snapshot_to_task_for_preparation( if link is not None: return link - from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source source = get_database_inventory_source(inv_file.source_code) if ( @@ -584,7 +589,7 @@ def link_snapshot_to_task_for_preparation( ): return None - from app.services.shipping_notice.inventory_file_store import replace_task_inventory_link + from app.services.shipping_notice.onhand_file_store import replace_task_inventory_link link = replace_task_inventory_link(task, inv_file) link.link_reason = f'{reason}_pending_matching' @@ -593,7 +598,7 @@ def link_snapshot_to_task_for_preparation( link.audit_payload_json = { **(audit_payload or {}), 'source_code': inv_file.source_code, - 'inventory_file_no': inv_file.inventory_file_no, + 'inventory_file_no': inv_file.onhand_file_no, 'identity_status': inv_file.identity_status, } return link @@ -604,8 +609,8 @@ def serialize_inventory_snapshot_link(task: ShippingNotice) -> dict[str, Any] | if task.id is None: return None link = ( - ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True) - .order_by(ShippingTaskInventoryLink.id.desc()) + ShippingTaskOnhandLink.query.filter_by(task_id=task.id, is_active=True) + .order_by(ShippingTaskOnhandLink.id.desc()) .first() ) if not link or not link.inventory_file: @@ -613,7 +618,7 @@ def serialize_inventory_snapshot_link(task: ShippingNotice) -> dict[str, Any] | inv_file = link.inventory_file trigger_type = (inv_file.source_query_json or {}).get("trigger_type") if isinstance(inv_file.source_query_json, dict) else None return { - "inventory_file_no": inv_file.inventory_file_no, + "inventory_file_no": inv_file.onhand_file_no, "source_code": inv_file.source_code, "warehouse_id": link.matched_warehouse_id or inv_file.warehouse_id, "warehouse_code": inv_file.warehouse_code, diff --git a/backend/app/services/shipping_notice/inventory_source_gate.py b/backend/app/services/shipping_notice/onhand_source_gate.py similarity index 87% rename from backend/app/services/shipping_notice/inventory_source_gate.py rename to backend/app/services/shipping_notice/onhand_source_gate.py index 8ae4d075..a18ac272 100644 --- a/backend/app/services/shipping_notice/inventory_source_gate.py +++ b/backend/app/services/shipping_notice/onhand_source_gate.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/inventory_source_gate.py +services/shipping_notice/onhand_source_gate.py 用途:库存源稳定性门禁;路由真相由 CandidateSet 承接,库存文件由 Link 承接。 -依赖:inventory_source_rules、inventory_source_repository、models.ShippingOrderTask、core.errors。 +依赖:onhand_source_rules、onhand_source_repository、models.ShippingOrderTask、core.errors。 逻辑:动态订单抽取先裁决线索;STP 建单可冻结单/多候选(candidates_frozen 视为可进入库存准备); apply 仅冻结 resolved/ambiguous/candidates_frozen;unresolved 不得写入全源 CandidateSet; 解析确认通过后未稳定才进入 inventory_source_review;RPA/库存/匹配/导出统一经本模块硬门禁。 @@ -14,30 +14,31 @@ from typing import Any from app.core.errors import AppError from app.models import ShippingOrderTask -from app.services.shipping_notice.inventory_source_rules import ( +from app.services.shipping_notice.onhand_source_rules import ( InventorySourceAdjudication, adjudicate_inventory_source, compute_routing_fingerprint, extract_routing_context, resolve_ambiguous_source_from_ready_snapshots, ) -from app.services.shipping_notice.inventory_candidate_freeze_service import ( +from app.services.shipping_notice.onhand_candidate_freeze_service import ( freeze_candidates_for_task, ) -from app.services.shipping_notice.inventory_source_repository import ( +from app.services.shipping_notice.onhand_source_repository import ( get_database_inventory_source, inventory_sources_runtime_version, ) +# 发货通知业务错误码,族名为 SHIPPING.ONHAND_*。货代 RPA 模块错误使用 FREIGHT_RPA_*。 INVENTORY_SOURCE_ERROR_CODES = { - "unresolved": "SHIPPING.INVENTORY_SOURCE_UNRESOLVED", - "ambiguous": "SHIPPING.INVENTORY_SOURCE_AMBIGUOUS", - "invalid": "SHIPPING.INVENTORY_SOURCE_INVALID", - "conflicted": "SHIPPING.INVENTORY_SOURCE_CONFLICTED", - "changed": "SHIPPING.INVENTORY_SOURCE_CHANGED", - "identity_mismatch": "SHIPPING.INVENTORY_IDENTITY_MISMATCH", - "gate_blocked": "SHIPPING.INVENTORY_SOURCE_GATE_BLOCKED", + "unresolved": "SHIPPING.ONHAND_SOURCE_UNRESOLVED", + "ambiguous": "SHIPPING.ONHAND_SOURCE_AMBIGUOUS", + "invalid": "SHIPPING.ONHAND_SOURCE_INVALID", + "conflicted": "SHIPPING.ONHAND_SOURCE_CONFLICTED", + "changed": "SHIPPING.ONHAND_SOURCE_CHANGED", + "identity_mismatch": "SHIPPING.ONHAND_IDENTITY_MISMATCH", + "gate_blocked": "SHIPPING.ONHAND_SOURCE_GATE_BLOCKED", } @@ -49,10 +50,10 @@ def is_inventory_source_stable(task: ShippingOrderTask) -> bool: STP 多候选冻结(candidates_frozen)在候选非空且各候选源存在时视为稳定。 不比对全局配置版本 hash 或路由指纹——无关库存源的改动不使本任务失效。 """ - from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_lines + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes - codes = task_frozen_inventory_source_codes(task) + codes = task_frozen_onhand_source_codes(task) lines = get_active_candidate_lines(task) if not codes or not lines or any(not list(row.source_codes_json or []) for row in lines): return False @@ -67,7 +68,7 @@ def is_inventory_source_stable(task: ShippingOrderTask) -> bool: def routing_fingerprint_changed(task: ShippingOrderTask, context: dict[str, Any]) -> bool: """比较当前路由上下文与任务已存指纹,判断库存源裁决是否因事实变化失效。""" - from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set + from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_set current = get_active_candidate_set(task) previous = str((getattr(current, 'routing_rule_version_json', None) or {}).get('routing_fingerprint') or '').strip() @@ -206,7 +207,7 @@ def transition_task_to_inventory_source_review( apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW) # OT 的流程阶段字段是 stage;current_step 属于已创建 Notice 的历史工作流, # 不能在通知准备前写入 OT。 - task.stage = "inventory_source_resolving" + task.stage = "onhand_source_resolving" task.error_message = error_message or "无法根据发货通知唯一确定库存查询来源" payload = dict(getattr(task, 'step_payload_json', None) or {}) payload["inventory_source_resolution"] = { @@ -227,7 +228,7 @@ def ensure_inventory_source_review_state(task: ShippingOrderTask) -> InventorySo """ 对已通过解析确认但库存源仍不稳定的任务,补做规则裁决并落库到内部恢复检查点。 - 【AI 触发时机】:confirm_parse / auto_progress / ensure_inventory 等入口发现门禁未通过时调用。 + 【AI 触发时机】:confirm_parse / auto_progress / ensure_onhand 等入口发现门禁未通过时调用。 核心逻辑:新业务顺序固定为先完成解析复核,再进入库存源自动裁决。 """ adjudication = adjudicate_and_apply_inventory_source(task) @@ -281,11 +282,11 @@ def task_inventory_identity(task: ShippingOrderTask) -> dict[str, str | None]: 传入 ShippingNotice 时先归一为其 order_task(库存 Link 挂在 OT 上)。 """ - from app.services.shipping_notice.inventory_candidate_projection import resolve_inventory_fact_task - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.onhand_candidate_projection import resolve_inventory_fact_task + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes task = resolve_inventory_fact_task(task) - source_codes = task_frozen_inventory_source_codes(task) + source_codes = task_frozen_onhand_source_codes(task) source_code = source_codes[0] if len(source_codes) == 1 else None source = get_database_inventory_source(source_code) if source_code else None return { @@ -309,20 +310,20 @@ def resolve_inventory_source_warehouse_id( if mode == 'fixed': return str(source.get('fixed_warehouse_id') or '').strip().upper() or None - from app.services.shipping_notice.inventory_candidate_projection import resolve_inventory_fact_task + from app.services.shipping_notice.onhand_candidate_projection import resolve_inventory_fact_task task = resolve_inventory_fact_task(task) task_id = getattr(task, 'id', None) source_code = str(source.get('source_code') or '').strip().upper() if not task_id or not source_code: return None - from app.models import ShippingTaskInventoryLink + from app.models import ShippingTaskOnhandLink - link = ShippingTaskInventoryLink.query.filter_by( + link = ShippingTaskOnhandLink.query.filter_by( task_id=int(task_id), matched_source_code=source_code, is_active=True, - ).order_by(ShippingTaskInventoryLink.id.desc()).first() + ).order_by(ShippingTaskOnhandLink.id.desc()).first() if link is None: return None return ( @@ -354,9 +355,9 @@ def inventory_identities_match( if expected_code != task_code: return False else: - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes - frozen = set(task_frozen_inventory_source_codes(task)) + frozen = set(task_frozen_onhand_source_codes(task)) if expected_code not in frozen: return False diff --git a/backend/app/services/shipping_notice/inventory_source_identity.py b/backend/app/services/shipping_notice/onhand_source_identity.py similarity index 98% rename from backend/app/services/shipping_notice/inventory_source_identity.py rename to backend/app/services/shipping_notice/onhand_source_identity.py index df52a012..500e3360 100644 --- a/backend/app/services/shipping_notice/inventory_source_identity.py +++ b/backend/app/services/shipping_notice/onhand_source_identity.py @@ -1,5 +1,5 @@ """ -services/shipping_notice/inventory_source_identity.py +services/shipping_notice/onhand_source_identity.py 用途:校验库存源与 Warehouse 的两段式身份。 依赖:无业务模块反向依赖。 diff --git a/backend/app/services/shipping_notice/inventory_source_repository.py b/backend/app/services/shipping_notice/onhand_source_repository.py similarity index 74% rename from backend/app/services/shipping_notice/inventory_source_repository.py rename to backend/app/services/shipping_notice/onhand_source_repository.py index b7ac5ae2..3063bbcc 100644 --- a/backend/app/services/shipping_notice/inventory_source_repository.py +++ b/backend/app/services/shipping_notice/onhand_source_repository.py @@ -1,18 +1,21 @@ """ -services/shipping_notice/inventory_source_repository.py +services/shipping_notice/onhand_source_repository.py 用途:提供库存源主数据的最小一致性校验和受控读取入口。 -依赖:models.ShippingInventorySource/ShippingRpaProfile、core.errors.ValidationError。 +依赖:models.FreightRpaSource/FreightRpaProfile/FreightRpaOnhandReportConfig、core.errors.ValidationError。 逻辑:管理服务保存 Source 前调用本模块校验 Source 与 Profile 的 Driver 一致;后续库存路由、排程与手动刷新统一复用读取入口。 + s18 起在手报表路径/查询条件/解析方案绑定归 FreightRpaOnhandReportConfig 配置行, + 本模块非敏感快照与运行时版本指纹均改读配置行;配置行缺失即「站点未就绪」, + 沿用返回 None 的既有跳过/失败语义,不新造错误码。 """ from __future__ import annotations from app.core.errors import ValidationError -from app.models import ShippingInventorySource, ShippingRpaProfile +from app.models import FreightRpaSource, FreightRpaProfile -def validate_source_profile(source: ShippingInventorySource, profile: ShippingRpaProfile) -> None: +def validate_source_profile(source: FreightRpaSource, profile: FreightRpaProfile) -> None: """ 校验库存源引用的 RPA Profile 与其 Driver 类型一致。 @@ -26,11 +29,11 @@ def validate_source_profile(source: ShippingInventorySource, profile: ShippingRp source_type = str(source.connector_type or '').strip().lower() profile_type = str(profile.connector_type or '').strip().lower() if source_type not in {'dbs', 'crane'} or profile_type not in {'dbs', 'crane'}: - raise ValidationError('Unsupported inventory connector type', code='SHIPPING.INVENTORY_CONNECTOR_INVALID') + raise ValidationError('Unsupported inventory connector type', code='SHIPPING.ONHAND_CONNECTOR_INVALID') if source_type != profile_type: raise ValidationError( 'Inventory Source connector_type must match its RPA Profile', - code='SHIPPING.INVENTORY_PROFILE_CONNECTOR_MISMATCH', + code='SHIPPING.ONHAND_PROFILE_CONNECTOR_MISMATCH', ) @@ -48,7 +51,7 @@ def get_database_inventory_source(source_code: str, *, enabled_only: bool = True code = str(source_code or '').strip().upper() if not code: return None - source = ShippingInventorySource.query.filter_by(source_code=code).first() + source = FreightRpaSource.query.filter_by(source_code=code).first() if source is None or (enabled_only and not source.enabled): return None profile = source.rpa_profile @@ -57,9 +60,14 @@ def get_database_inventory_source(source_code: str, *, enabled_only: bool = True login_config = dict(profile.login_config_json or {'auth_mode': 'password'}) if login_config.get('auth_mode') != 'password': return None + # s18 起报表路径/查询条件/解析方案绑定归 onhand_report_config 配置行; + # 配置行缺失即「站点未就绪」,沿用返回 None 的既有跳过/失败语义,不新造错误码。 + config = source.onhand_report_config + if config is None: + return None # Source owns report navigation and business query values. Driver behavior is # code/template-owned and never travels through a login connection profile. - source_navigation = dict(source.report_path_json or {}) if source.connector_type == 'dbs' else {} + source_navigation = dict(config.report_path_json or {}) if source.connector_type == 'dbs' else {} return { 'source_code': source.source_code, 'display_name': source.display_name, @@ -70,17 +78,17 @@ def get_database_inventory_source(source_code: str, *, enabled_only: bool = True 'warehouse_id': source.fixed_warehouse_id, 'snapshot_ttl_seconds': source.snapshot_ttl_seconds, 'config_version': source.config_version, - 'parsing_profile_id': source.parsing_profile_id, + 'parsing_profile_id': config.parsing_profile_id, 'excel_template_id': source.excel_template_id, - 'report_path_json': dict(source.report_path_json or {}), - 'query_parameters_json': list(source.query_parameters_json or []), + 'report_path_json': dict(config.report_path_json or {}), + 'query_parameters_json': list(config.query_parameters_json or []), 'rpa_profile_code': profile.profile_code, # 连接级受控上传配置(受限 JSON):Worker 用 login_url 登录后访问 upload_config.entry_url 上传页, # 平台差异(文件选择、提交与结果判定)由 Worker 受控 Adapter 固化。 'upload_config_json': profile.upload_config_json, # 与既有 worker 契约的适配层:不再从 Profile 取报表路径或查询参数。 'navigation': source_navigation, - 'parameters': list(source.query_parameters_json or []), + 'parameters': list(config.query_parameters_json or []), 'query': {}, 'login_url': profile.login_url, 'login_config': login_config, @@ -92,7 +100,7 @@ def get_rpa_trigger_inventory_source(source_code: str, *, enabled_only: bool = T source_config = get_database_inventory_source(source_code, enabled_only=enabled_only) if source_config is None: return None - source = ShippingInventorySource.query.filter_by(source_code=source_config['source_code']).first() + source = FreightRpaSource.query.filter_by(source_code=source_config['source_code']).first() profile = source.rpa_profile if source else None if profile is None or (enabled_only and not profile.enabled): return None @@ -106,7 +114,7 @@ def get_rpa_trigger_inventory_source(source_code: str, *, enabled_only: bool = T def list_database_inventory_sources(*, enabled_only: bool = True) -> list[dict]: """列出数据库库存源的非敏感运行时快照,供路由和排程按 Source 选择。""" - query = ShippingInventorySource.query.order_by(ShippingInventorySource.source_code) + query = FreightRpaSource.query.order_by(FreightRpaSource.source_code) if enabled_only: query = query.filter_by(enabled=True) result = [] @@ -123,8 +131,10 @@ def inventory_sources_runtime_version() -> str: import json rows = [] - for source in ShippingInventorySource.query.order_by(ShippingInventorySource.source_code).all(): + for source in FreightRpaSource.query.order_by(FreightRpaSource.source_code).all(): profile = source.rpa_profile + # s18 起报表路径/查询条件归 onhand_report_config 配置行;配置行缺失按空配置参与指纹。 + config = source.onhand_report_config rows.append({ 'source_code': source.source_code, 'source_version': source.config_version, @@ -136,8 +146,8 @@ def inventory_sources_runtime_version() -> str: 'connector_type': source.connector_type, 'warehouse_resolution_mode': source.warehouse_resolution_mode, 'fixed_warehouse_id': source.fixed_warehouse_id, - 'report_path_json': source.report_path_json or {}, - 'query_parameters_json': source.query_parameters_json or [], + 'report_path_json': (config.report_path_json or {}) if config is not None else {}, + 'query_parameters_json': (config.query_parameters_json or []) if config is not None else [], 'snapshot_ttl_seconds': source.snapshot_ttl_seconds, }, 'profile_config': { diff --git a/backend/app/services/shipping_notice/inventory_source_rules.py b/backend/app/services/shipping_notice/onhand_source_rules.py similarity index 92% rename from backend/app/services/shipping_notice/inventory_source_rules.py rename to backend/app/services/shipping_notice/onhand_source_rules.py index 44e34072..fccde009 100644 --- a/backend/app/services/shipping_notice/inventory_source_rules.py +++ b/backend/app/services/shipping_notice/onhand_source_rules.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/inventory_source_rules.py +services/shipping_notice/onhand_source_rules.py 用途:将通用路由规则的 Source 候选转为任务可持久化的裁决结果。 -依赖:inventory_routing_engine、inventory_source_repository、order_field_purposes。 +依赖:onhand_routing_engine、onhand_source_repository、order_field_purposes。 逻辑:规则只决定 Source;建单前多候选由资格服务按 can_build 放行; 行级一致的 ambiguous/resolved/conflicted 可上收为任务裁决;unresolved 禁止兜底全部启用源; Warehouse 由 Source/匹配决定。 @@ -18,9 +18,9 @@ from typing import Any from app import db from app.models import ShippingNotice, ShippingOrderSnapshot -from app.services.shipping_notice.inventory_routing_engine import evaluate_inventory_source_rules -from app.services.shipping_notice.inventory_source_identity import resolve_inventory_source_identity -from app.services.shipping_notice.inventory_source_repository import ( +from app.services.shipping_notice.onhand_routing_engine import evaluate_inventory_source_rules +from app.services.shipping_notice.onhand_source_identity import resolve_inventory_source_identity +from app.services.shipping_notice.onhand_source_repository import ( get_database_inventory_source, inventory_sources_runtime_version, list_database_inventory_sources, @@ -181,8 +181,8 @@ def resolve_ambiguous_source_from_ready_snapshots( if len(order_keys) != len(order_lines): return adjudication - from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines - from app.services.shipping_notice.inventory_snapshot_store import find_latest_ready_snapshot + from app.services.shipping_notice.onhand_file_store import read_inventory_file_lines + from app.services.shipping_notice.onhand_snapshot_store import find_latest_ready_snapshot matched: list[tuple[dict[str, Any], Any]] = [] checked: list[dict[str, Any]] = [] @@ -206,7 +206,7 @@ def resolve_ambiguous_source_from_ready_snapshots( is_match = order_keys.issubset(inventory_keys) checked.append({ 'source_code': source_code, - 'inventory_file_no': snapshot.inventory_file_no, + 'inventory_file_no': snapshot.onhand_file_no, 'matched': is_match, }) if is_match: @@ -236,7 +236,7 @@ def resolve_ambiguous_source_from_ready_snapshots( candidates=adjudication.candidates, destination_candidates=adjudication.destination_candidates, evidence=evidence, - reason=f'unique_ready_snapshot:{snapshot.inventory_file_no}', + reason=f'unique_ready_snapshot:{snapshot.onhand_file_no}', ) @@ -288,9 +288,9 @@ def resolve_inventory_source(task: ShippingNotice) -> InventorySourceAdjudicatio def task_rpa_inventory_source(task: ShippingNotice) -> dict[str, Any] | None: """按当前冻结 CandidateSet 的首个可用源读取 RPA/快照配置。""" - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes - for code in task_frozen_inventory_source_codes(task): + for code in task_frozen_onhand_source_codes(task): item = get_database_inventory_source(code) if item is not None: return item @@ -299,7 +299,7 @@ def task_rpa_inventory_source(task: ShippingNotice) -> dict[str, Any] | None: def save_task_rpa_inventory_source(task: ShippingNotice, source: dict[str, Any], *, resolution: InventorySourceAdjudication | None = None) -> None: """持久化规则裁决结果到 CandidateSet;禁止调用方直接写 OT。""" - from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication + from app.services.shipping_notice.onhand_source_gate import apply_inventory_source_adjudication del source selected = resolution or adjudicate_inventory_source(task) @@ -308,6 +308,6 @@ def save_task_rpa_inventory_source(task: ShippingNotice, source: dict[str, Any], def mark_inventory_source_review(task: ShippingNotice, resolution: InventorySourceAdjudication) -> None: """兼容旧入口,写入规则裁决候选;不触发人工库存源确认。""" - from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication + from app.services.shipping_notice.onhand_source_gate import apply_inventory_source_adjudication apply_inventory_source_adjudication(task, resolution) diff --git a/backend/app/services/shipping_notice/inventory_structure_analysis.py b/backend/app/services/shipping_notice/onhand_structure_analysis.py similarity index 87% rename from backend/app/services/shipping_notice/inventory_structure_analysis.py rename to backend/app/services/shipping_notice/onhand_structure_analysis.py index bf08b51b..4b06e72a 100644 --- a/backend/app/services/shipping_notice/inventory_structure_analysis.py +++ b/backend/app/services/shipping_notice/onhand_structure_analysis.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/inventory_structure_analysis.py +services/shipping_notice/onhand_structure_analysis.py 用途:安全分析库存样本文件的工作表、表头、列统计和字段建议。 -依赖:openpyxl、inventory_snapshot 的受控表头词典、库存解析 Profile 服务、结构分析 ORM 模型。 +依赖:openpyxl、onhand_snapshot 的受控表头词典、库存解析 Profile 服务、结构分析 ORM 模型。 逻辑:管理端上传 .xls/.xlsx/.csv 样本后调用本服务生成后端权威分析记录;后续 RPA 测试与运行期漂移检查复用同一分析契约。 """ @@ -24,11 +24,11 @@ from werkzeug.datastructures import FileStorage from app.core.errors import NotFoundError, ValidationError from app.extensions import db -from app.models import ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventoryStructureAnalysis -from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix -from app.services.shipping_notice.inventory_mapping import suggest_field_mapping -from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index -from app.services.shipping_notice.inventory_structure_fingerprint import ( +from app.models import FreightRpaOnhandField, FreightRpaParsingProfile, FreightRpaOnhandStructureAnalysis +from app.services.shipping_notice.onhand_file_store import resolve_inventory_upload_suffix +from app.services.shipping_notice.onhand_mapping import suggest_field_mapping +from app.services.shipping_notice.onhand_snapshot import find_inventory_header_row_index +from app.services.shipping_notice.onhand_structure_fingerprint import ( compatibility_fingerprint, exact_fingerprint, normalise_header, @@ -44,8 +44,8 @@ _SOURCE_KINDS = {'sample_upload', 'configuration_test', 'production_snapshot', ' def _has_required_suggestions(mapping: dict[str, str]) -> bool: """确认自动建议至少覆盖一个匹配字段和一个库存数量字段。""" - rows = ShippingInventoryField.query.filter( - ShippingInventoryField.status == 'active', ShippingInventoryField.id.in_([ + rows = FreightRpaOnhandField.query.filter( + FreightRpaOnhandField.status == 'active', FreightRpaOnhandField.id.in_([ int(field_id) for field_id in mapping if str(field_id).isdigit() ]), ).all() if mapping else [] @@ -118,7 +118,7 @@ def _column_summary(headers: list[str], sample_rows: list[list[Any]]) -> list[di """生成来源栏位的业务预览,包括样例、空值率和建议字段。""" suggestions = suggest_field_mapping(headers, as_catalog=True) catalog = { - str(item.id): item for item in ShippingInventoryField.query.filter_by(status='active').all() + str(item.id): item for item in FreightRpaOnhandField.query.filter_by(status='active').all() } reverse_suggestions = {header: catalog[field_id].display_name for field_id, header in suggestions.items() if field_id in catalog} duplicates = Counter(header for header in headers if header) @@ -206,7 +206,7 @@ def _build_workbook_structure( if headers: candidates.append(candidate) if not candidates: - raise ValidationError('Inventory file has no analysable worksheet', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') + raise ValidationError('Inventory file has no analysable worksheet', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_INVALID') # Prefer a populated detail sheet over a same-score cover/summary sheet. selected = max(candidates, key=lambda item: ( item['score'], item['sample_row_count'], sum(1 for header in item['headers'] if header), @@ -259,9 +259,9 @@ def _csv_structure(path: Path) -> tuple[dict[str, Any], dict[str, str], dict[str with path.open('r', encoding='utf-8-sig', errors='replace', newline='') as handle: rows = [row for _, row in zip(range(MAX_SCAN_ROWS), csv.reader(handle))] except OSError as exc: - raise ValidationError('Inventory CSV cannot be read', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') from exc + raise ValidationError('Inventory CSV cannot be read', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_INVALID') from exc if not rows: - raise ValidationError('Inventory file is empty', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') + raise ValidationError('Inventory file is empty', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_INVALID') header_index = find_inventory_header_row_index(rows) headers = [_normalise_header(value) for value in rows[header_index]] samples = rows[header_index + 1:header_index + 1 + MAX_SAMPLE_ROWS] @@ -294,10 +294,10 @@ def _analyse_path(path: Path, suffix: str) -> tuple[dict[str, Any], dict[str, st return _xls_structure(path) if suffix == '.csv': return _csv_structure(path) - raise ValidationError('Inventory file format is unsupported', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') + raise ValidationError('Inventory file format is unsupported', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_INVALID') -def serialize_analysis(item: ShippingInventoryStructureAnalysis) -> dict[str, Any]: +def serialize_analysis(item: FreightRpaOnhandStructureAnalysis) -> dict[str, Any]: """输出管理端需要的分析结果,不暴露服务器存储路径。""" return { 'id': item.id, @@ -319,13 +319,13 @@ def serialize_analysis(item: ShippingInventoryStructureAnalysis) -> dict[str, An def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) -> dict[str, Any]: """上传并分析管理员库存样本,只持久化脱敏结构证据且立即清理完整原件。""" if upload is None or not str(upload.filename or '').strip(): - raise ValidationError('Inventory sample file is required', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_FILE_REQUIRED') + raise ValidationError('Inventory sample file is required', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_FILE_REQUIRED') suffix = resolve_inventory_upload_suffix(str(upload.filename)) raw = upload.stream.read(MAX_UPLOAD_BYTES + 1) if len(raw) > MAX_UPLOAD_BYTES: - raise ValidationError('Inventory sample file is too large', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_FILE_TOO_LARGE') + raise ValidationError('Inventory sample file is too large', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_FILE_TOO_LARGE') if not raw: - raise ValidationError('Inventory sample file is empty', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') + raise ValidationError('Inventory sample file is empty', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_INVALID') analysis_dir = _analysis_root() / uuid.uuid4().hex analysis_dir.mkdir(parents=True, exist_ok=False) path = analysis_dir / f'sample{suffix}' @@ -337,13 +337,13 @@ def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) -> raise except Exception as exc: shutil.rmtree(analysis_dir, ignore_errors=True) - raise ValidationError('Inventory sample file cannot be analysed', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') from exc + raise ValidationError('Inventory sample file cannot be analysed', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_INVALID') from exc selected_headers = structure.get('selected_headers', []) selected_definition = structure_definition( file_format=suffix.lstrip('.'), sheet_name=structure.get('selected_sheet_name'), header_row_index=structure.get('selected_header_row_index') or 1, headers=selected_headers, ) - item = ShippingInventoryStructureAnalysis( + item = FreightRpaOnhandStructureAnalysis( source_kind='sample_upload', source_file_name=_safe_filename(str(upload.filename)), storage_path=None, file_checksum=hashlib.sha256(raw).hexdigest(), file_format=suffix.lstrip('.'), analysis_status='ready', structure_json=structure, suggested_mapping_json=suggested, validation_summary_json=summary, @@ -355,7 +355,7 @@ def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) -> ) db.session.add(item) db.session.flush() - from app.services.shipping_notice.inventory_profile_matching import recommend_profiles + from app.services.shipping_notice.onhand_profile_matching import recommend_profiles item.match_result_json = recommend_profiles({ 'structure': structure, @@ -373,22 +373,22 @@ def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) -> def get_analysis(analysis_id: int) -> dict[str, Any]: """读取既有结构分析,供管理员选择工作表、表头和来源栏位。""" - item = db.session.get(ShippingInventoryStructureAnalysis, analysis_id) + item = db.session.get(FreightRpaOnhandStructureAnalysis, analysis_id) if item is None: - raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_NOT_FOUND') + raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_NOT_FOUND') return serialize_analysis(item) def preview_profile_sample_replacement(profile_id: int, analysis_id: int, data: dict[str, Any] | None = None) -> dict[str, Any]: """比较草稿当前样本和候选样本,明确列出需要管理员确认的结构变化。""" - profile = db.session.get(ShippingInventoryParsingProfile, profile_id) - analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id) + profile = db.session.get(FreightRpaParsingProfile, profile_id) + analysis = db.session.get(FreightRpaOnhandStructureAnalysis, analysis_id) if profile is None: - raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND') + raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND') if profile.status != 'draft': - raise ValidationError('Only draft parsing profile can replace sample evidence', code='SHIPPING.INVENTORY_PARSING_PROFILE_IMMUTABLE') + raise ValidationError('Only draft parsing profile can replace sample evidence', code='SHIPPING.ONHAND_PARSING_PROFILE_IMMUTABLE') if analysis is None or analysis.analysis_status != 'ready': - raise ValidationError('Inventory sample analysis evidence is unavailable', code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED') + raise ValidationError('Inventory sample analysis evidence is unavailable', code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_REQUIRED') previous = profile.sample_analysis old_headers = list((previous.structure_json or {}).get('selected_headers') or []) if previous else [] new_headers = list((analysis.structure_json or {}).get('selected_headers') or []) @@ -419,14 +419,14 @@ def preview_profile_sample_replacement(profile_id: int, analysis_id: int, data: def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: """用已分析样本证据创建或更新草稿,禁止前端编造来源栏位或脱离样本保存。""" - analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id) + analysis = db.session.get(FreightRpaOnhandStructureAnalysis, analysis_id) if analysis is None: - raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_NOT_FOUND') - existing_profile = db.session.get(ShippingInventoryParsingProfile, data.get('profile_id')) if data.get('profile_id') else None + raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_NOT_FOUND') + existing_profile = db.session.get(FreightRpaParsingProfile, data.get('profile_id')) if data.get('profile_id') else None if existing_profile is not None and existing_profile.file_format != analysis.file_format: raise ValidationError( 'Draft parsing profile file format is immutable', - code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID', + code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID', ) structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {} sheet_name = str(data.get('sheet_name') or structure.get('selected_sheet_name') or '').strip() or None @@ -436,24 +436,24 @@ def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: in if candidate is None and sheet_name is None: candidate = next((item for item in candidates if isinstance(item, dict) and item.get('sheet_name') is None and item.get('header_row_index') == header_row_index), None) if not isinstance(candidate, dict): - raise ValidationError('Selected worksheet or header row is not in the analysis', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID') + raise ValidationError('Selected worksheet or header row is not in the analysis', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_SELECTION_INVALID') headers = {str(value).strip() for value in candidate.get('headers', []) if str(value).strip()} mapping = data.get('field_mapping') if isinstance(data.get('field_mapping'), dict) else analysis.suggested_mapping_json or {} if any(str(value or '').strip() not in headers for value in mapping.values()): - raise ValidationError('Parsing field mapping must use analysed headers', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID') + raise ValidationError('Parsing field mapping must use analysed headers', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_SELECTION_INVALID') duplicates = { str(column.get('header') or '').strip() for column in candidate.get('columns', []) if isinstance(column, dict) and column.get('duplicate') } if any(str(value or '').strip() in duplicates for value in mapping.values()): - raise ValidationError('Parsing field mapping cannot use duplicate headers', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID') - from app.services.shipping_notice import inventory_parsing_profile + raise ValidationError('Parsing field mapping cannot use duplicate headers', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_SELECTION_INVALID') + from app.services.freight_rpa import parsing_profile as onhand_parsing_profile - saved = inventory_parsing_profile.save_draft({ + saved = onhand_parsing_profile.save_draft({ 'profile_code': data.get('profile_code'), 'display_name': data.get('display_name'), - # 用途随请求透传(缺省沿用既有草稿/默认 inventory):movement 草稿端点为定死领域字段。 + # 用途随请求透传(缺省沿用既有草稿/默认 onhand):inbound 草稿端点为定死领域字段。 'purpose': data.get('purpose'), 'file_format': analysis.file_format, 'sample_analysis_id': analysis.id, @@ -465,7 +465,7 @@ def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: in 'match_keys': data.get('match_keys'), }, }, actor_id=actor_id, profile_id=data.get('profile_id')) - profile = db.session.get(ShippingInventoryParsingProfile, saved['id']) + profile = db.session.get(FreightRpaParsingProfile, saved['id']) selected_definition = structure_definition( file_format=analysis.file_format, sheet_name=sheet_name, header_row_index=header_row_index, headers=[str(value) for value in candidate.get('headers', [])], @@ -478,17 +478,17 @@ def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: in ) profile.fingerprint_version = selected_definition['fingerprint_version'] db.session.commit() - return inventory_parsing_profile.payload(profile) + return onhand_parsing_profile.payload(profile) def adopt_published_profile(analysis_id: int, profile_id: int) -> dict[str, Any]: """确认分析结果采用指定已发布方案;只记录确认,不自动绑定任何库存站点。""" - analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id) + analysis = db.session.get(FreightRpaOnhandStructureAnalysis, analysis_id) if analysis is None: - raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_NOT_FOUND') - profile = db.session.get(ShippingInventoryParsingProfile, profile_id) + raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_NOT_FOUND') + profile = db.session.get(FreightRpaParsingProfile, profile_id) if profile is None or profile.status != 'published': - raise ValidationError('Published parsing profile is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED') + raise ValidationError('Published parsing profile is required', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED') match = analysis.match_result_json if isinstance(analysis.match_result_json, dict) else {} candidate_ids = {int(item.get('profile_id')) for item in match.get('candidates', []) if isinstance(item, dict) and item.get('profile_id')} same_test_structure = bool( @@ -496,7 +496,7 @@ def adopt_published_profile(analysis_id: int, profile_id: int) -> dict[str, Any] and analysis.exact_structure_fingerprint == profile.exact_structure_fingerprint ) if profile_id not in candidate_ids and not same_test_structure: - raise ValidationError('Profile is not a compatible recommendation', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID') + raise ValidationError('Profile is not a compatible recommendation', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_SELECTION_INVALID') analysis.match_result_json = { **match, 'adopted_profile_id': profile.id, diff --git a/backend/app/services/shipping_notice/inventory_structure_drift.py b/backend/app/services/shipping_notice/onhand_structure_drift.py similarity index 77% rename from backend/app/services/shipping_notice/inventory_structure_drift.py rename to backend/app/services/shipping_notice/onhand_structure_drift.py index b292b828..142fb2cc 100644 --- a/backend/app/services/shipping_notice/inventory_structure_drift.py +++ b/backend/app/services/shipping_notice/onhand_structure_drift.py @@ -1,5 +1,5 @@ """ -services/shipping_notice/inventory_structure_drift.py +services/shipping_notice/onhand_structure_drift.py 用途:在正式库存文件入库前核验其结构是否仍符合库存站点已绑定的解析方案。 依赖:库存源/解析方案模型、库存结构分析和方案复用服务。 @@ -12,7 +12,7 @@ from pathlib import Path from typing import Any from app.core.errors import ConflictError -from app.models import ShippingInventorySource +from app.models import FreightRpaSource def validate_production_inventory_structure(*, source_code: str, path: Path) -> dict[str, Any]: @@ -28,20 +28,22 @@ def validate_production_inventory_structure(*, source_code: str, path: Path) -> Raises: ConflictError: 文件结构缺关键栏位、格式不一致或与已绑定方案不兼容时抛出。 """ - source = ShippingInventorySource.query.filter_by(source_code=str(source_code or '').strip().upper()).first() - profile = source.parsing_profile if source is not None else None + source = FreightRpaSource.query.filter_by(source_code=str(source_code or '').strip().upper()).first() + # s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系。 + config = source.onhand_report_config if source is not None else None + profile = config.parsing_profile if config is not None else None if source is None or not source.enabled or profile is None or profile.status != 'published': - raise ConflictError('Inventory source parsing profile is unavailable', code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED') + raise ConflictError('Inventory source parsing profile is unavailable', code='SHIPPING.ONHAND_STRUCTURE_DRIFT_BLOCKED') - from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix - from app.services.shipping_notice.inventory_structure_analysis import _analyse_path - from app.services.shipping_notice.inventory_structure_fingerprint import exact_fingerprint, structure_definition - from app.services.shipping_notice.inventory_profile_matching import recommend_profiles + from app.services.shipping_notice.onhand_file_store import resolve_inventory_upload_suffix + from app.services.shipping_notice.onhand_structure_analysis import _analyse_path + from app.services.shipping_notice.onhand_structure_fingerprint import exact_fingerprint, structure_definition + from app.services.shipping_notice.onhand_profile_matching import recommend_profiles suffix = resolve_inventory_upload_suffix(path.name) actual_format = suffix.lstrip('.') if actual_format != profile.file_format: - raise ConflictError('Inventory file format changed', code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED') + raise ConflictError('Inventory file format changed', code='SHIPPING.ONHAND_STRUCTURE_DRIFT_BLOCKED') structure, suggested, _summary, warnings = _analyse_path(path, suffix) configured = profile.definition_json if isinstance(profile.definition_json, dict) else {} expected_sheet = configured.get('sheet_name') @@ -53,14 +55,14 @@ def validate_production_inventory_structure(*, source_code: str, path: Path) -> if selected is None: raise ConflictError( 'Configured inventory worksheet or header row is unavailable', - code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED', + code='SHIPPING.ONHAND_STRUCTURE_DRIFT_BLOCKED', details={'source_code': source.source_code, 'profile_id': profile.id}, ) # Compare the configured worksheet rather than the analyser's best guess. structure = {**structure, 'selected_sheet_name': selected['sheet_name'], 'selected_header_row_index': selected['header_row_index'], 'selected_headers': selected.get('headers', []), 'selected_columns': selected.get('columns', [])} - from app.services.shipping_notice.inventory_mapping import suggest_field_mapping + from app.services.shipping_notice.onhand_mapping import suggest_field_mapping suggested = suggest_field_mapping(structure['selected_headers'], as_catalog=True) definition = structure_definition( @@ -79,7 +81,7 @@ def validate_production_inventory_structure(*, source_code: str, path: Path) -> if candidate is None: raise ConflictError( 'Inventory file structure is incompatible with the bound parsing profile', - code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED', + code='SHIPPING.ONHAND_STRUCTURE_DRIFT_BLOCKED', details={'source_code': source.source_code, 'profile_id': profile.id, 'warnings': warnings}, ) return { diff --git a/backend/app/services/shipping_notice/inventory_structure_fingerprint.py b/backend/app/services/shipping_notice/onhand_structure_fingerprint.py similarity index 91% rename from backend/app/services/shipping_notice/inventory_structure_fingerprint.py rename to backend/app/services/shipping_notice/onhand_structure_fingerprint.py index 13eaf036..5bda791d 100644 --- a/backend/app/services/shipping_notice/inventory_structure_fingerprint.py +++ b/backend/app/services/shipping_notice/onhand_structure_fingerprint.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/inventory_structure_fingerprint.py +services/shipping_notice/onhand_structure_fingerprint.py 用途:为库存文件结构和解析定义生成稳定、可审计的指纹。 -依赖:标准 hashlib/json/unicodedata;输入来自 inventory_structure_analysis 与 inventory_parsing_profile。 +依赖:标准 hashlib/json/unicodedata;输入来自 onhand_structure_analysis 与 onhand_parsing_profile。 逻辑:精确指纹判断文件布局相同;兼容指纹只保留核心栏位,用于推荐而非自动绑定。 """ @@ -47,7 +47,7 @@ def exact_fingerprint(definition: dict[str, Any]) -> str: def compatibility_fingerprint(*, definition: dict[str, Any], field_mapping: dict[str, str], match_keys: list[dict[str, Any]]) -> str: """按匹配与数量用途生成兼容指纹,忽略普通导出列但保留用户字段 ID。""" - from app.services.shipping_notice.inventory_mapping import runtime_field_mapping, usage_field_ids + from app.services.shipping_notice.onhand_mapping import runtime_field_mapping, usage_field_ids runtime_mapping, catalog = runtime_field_mapping(field_mapping) usages = usage_field_ids() diff --git a/backend/app/services/shipping_notice/inventory_temporary_session.py b/backend/app/services/shipping_notice/onhand_temporary_session.py similarity index 81% rename from backend/app/services/shipping_notice/inventory_temporary_session.py rename to backend/app/services/shipping_notice/onhand_temporary_session.py index 314904b2..399f0b45 100644 --- a/backend/app/services/shipping_notice/inventory_temporary_session.py +++ b/backend/app/services/shipping_notice/onhand_temporary_session.py @@ -1,5 +1,5 @@ """ -services/shipping_notice/inventory_temporary_session.py +services/shipping_notice/onhand_temporary_session.py 用途:处理对话上传库存候选文件的身份初检与临时会话状态。 依赖:ChatSession、FileAsset、库存结构分析、库存站点模型、FileAsset 私有存储服务。 @@ -24,33 +24,33 @@ from app.models import ( Agent, ChatSession, FileAsset, - ShippingInventoryStructureAnalysis, - ShippingTemporaryInventorySession, - ShippingInventoryField, - ShippingInventoryParsingProfile, + FreightRpaOnhandStructureAnalysis, + ShippingTemporaryOnhandSession, + FreightRpaOnhandField, + FreightRpaParsingProfile, ) from app.services.agent_runtime_context.parser import parse_agent_runtime_context from app.services.file_assets.service import read_asset_bytes -from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix -from app.services.shipping_notice.inventory_structure_analysis import ( +from app.services.shipping_notice.onhand_file_store import resolve_inventory_upload_suffix +from app.services.shipping_notice.onhand_structure_analysis import ( MAX_UPLOAD_BYTES, _analyse_path, _analysis_root, _safe_filename, serialize_analysis, ) -from app.services.shipping_notice.inventory_structure_fingerprint import ( +from app.services.shipping_notice.onhand_structure_fingerprint import ( compatibility_fingerprint, exact_fingerprint, structure_definition, ) -from app.services.shipping_notice.inventory_mapping import ( +from app.services.shipping_notice.onhand_mapping import ( mapping_is_complete, runtime_field_mapping, suggest_field_mapping, validate_field_mapping_against_headers, ) -from app.services.shipping_notice.inventory_snapshot import parse_inventory_excel_with_meta +from app.services.shipping_notice.onhand_snapshot import parse_inventory_excel_with_meta _CONTEXT_PATHS = ['agent_code', 'platform.session_id'] _TTL_HOURS = 24 @@ -59,7 +59,7 @@ def _runtime_session(raw_context: str | dict[str, Any]) -> ChatSession: parsed = parse_agent_runtime_context(raw_context, _CONTEXT_PATHS) values = parsed.get('data') if isinstance(parsed.get('data'), dict) else {} if str(values.get('agent_code') or '') != 'shipping_notice': - raise ForbiddenError('Current context is not shipping notice', code='SHIPPING.TEMP_INVENTORY_CONTEXT_INVALID') + raise ForbiddenError('Current context is not shipping notice', code='SHIPPING.TEMP_ONHAND_CONTEXT_INVALID') session_id = str(values.get('platform.session_id') or '').strip() session = ( db.session.query(ChatSession) @@ -68,7 +68,7 @@ def _runtime_session(raw_context: str | dict[str, Any]) -> ChatSession: .one_or_none() ) if session is None: - raise NotFoundError('Shipping chat session not found', code='SHIPPING.TEMP_INVENTORY_CONTEXT_INVALID') + raise NotFoundError('Shipping chat session not found', code='SHIPPING.TEMP_ONHAND_CONTEXT_INVALID') return session @@ -77,9 +77,9 @@ def _session_no() -> str: return f'TIS-{datetime.utcnow().strftime("%Y%m%d")}-{uuid.uuid4().hex[:10].upper()}' -def _serialize(item: ShippingTemporaryInventorySession) -> dict[str, Any]: +def _serialize(item: ShippingTemporaryOnhandSession) -> dict[str, Any]: """输出 Dify 和工作台可消费的临时会话,不泄露对象存储路径和完整库存行。""" - analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None + analysis = db.session.get(FreightRpaOnhandStructureAnalysis, item.analysis_id) if item.analysis_id else None return { 'session_no': item.session_no, 'status': item.status, @@ -101,19 +101,19 @@ def _available_inventory_fields() -> list[dict[str, Any]]: 'description': item.description or '', 'value_type': item.value_type, 'usage_type': item.usage_type, - } for item in ShippingInventoryField.query.filter_by(status='active').order_by( - ShippingInventoryField.sort_order, ShippingInventoryField.id, + } for item in FreightRpaOnhandField.query.filter_by(status='active').order_by( + FreightRpaOnhandField.sort_order, FreightRpaOnhandField.id, ).all()] -def _mapping_suggestion(item: ShippingTemporaryInventorySession) -> dict[str, Any] | None: +def _mapping_suggestion(item: ShippingTemporaryOnhandSession) -> dict[str, Any] | None: """提取已保存的候选映射;未建议时返回空,不伪造可运行的映射。""" result = item.result_json if isinstance(item.result_json, dict) else {} value = result.get('mapping_suggestion') return value if isinstance(value, dict) else None -def _confirmed_usage(item: ShippingTemporaryInventorySession) -> dict[str, Any] | None: +def _confirmed_usage(item: ShippingTemporaryOnhandSession) -> dict[str, Any] | None: """输出已确认的临时使用摘要,不返回库存行或文件内部路径。""" result = item.result_json if isinstance(item.result_json, dict) else {} value = result.get('confirmed_usage') @@ -128,7 +128,7 @@ def _confirmed_usage(item: ShippingTemporaryInventorySession) -> dict[str, Any] } -def _serialize_dify_analysis_preview(analysis: ShippingInventoryStructureAnalysis) -> dict[str, Any]: +def _serialize_dify_analysis_preview(analysis: FreightRpaOnhandStructureAnalysis) -> dict[str, Any]: """返回给 Dify 的库存结构预览,移除所有样例值以避免暴露库存明细。""" preview = copy.deepcopy(serialize_analysis(analysis)) structure = preview.get('structure') @@ -146,12 +146,12 @@ def _serialize_dify_analysis_preview(analysis: ShippingInventoryStructureAnalysi return preview -def _persist_analysis(*, asset: FileAsset, owner_id: int) -> ShippingInventoryStructureAnalysis: +def _persist_analysis(*, asset: FileAsset, owner_id: int) -> FreightRpaOnhandStructureAnalysis: """对私有文件资产执行受控结构分析,仅保留结构、有限样例及字段建议。""" if int(asset.file_size or 0) > MAX_UPLOAD_BYTES: raise ValidationError( 'Temporary inventory file is too large', - code='SHIPPING.TEMP_INVENTORY_FILE_TOO_LARGE', + code='SHIPPING.TEMP_ONHAND_FILE_TOO_LARGE', ) suffix = resolve_inventory_upload_suffix(asset.original_filename) raw = read_asset_bytes(asset) @@ -168,7 +168,7 @@ def _persist_analysis(*, asset: FileAsset, owner_id: int) -> ShippingInventorySt shutil.rmtree(analysis_dir, ignore_errors=True) raise ValidationError( 'Temporary inventory file cannot be analysed', - code='SHIPPING.TEMP_INVENTORY_ANALYSIS_INVALID', + code='SHIPPING.TEMP_ONHAND_ANALYSIS_INVALID', ) from exc # 临时会话与正式配置一致地保留目录字段 ID,不生成固定运行字段名称。 suggested, _catalog = runtime_field_mapping(suggested_catalog) @@ -177,7 +177,7 @@ def _persist_analysis(*, asset: FileAsset, owner_id: int) -> ShippingInventorySt header_row_index=structure.get('selected_header_row_index') or 1, headers=structure.get('selected_headers', []), ) - analysis = ShippingInventoryStructureAnalysis( + analysis = FreightRpaOnhandStructureAnalysis( source_kind='temporary_conversation', source_file_name=_safe_filename(asset.original_filename), storage_path=str(path), file_checksum=hashlib.sha256(raw).hexdigest(), file_format=suffix.lstrip('.'), analysis_status='ready', structure_json=structure, suggested_mapping_json=suggested, @@ -189,7 +189,7 @@ def _persist_analysis(*, asset: FileAsset, owner_id: int) -> ShippingInventorySt ) db.session.add(analysis) db.session.flush() - from app.services.shipping_notice.inventory_profile_matching import recommend_profiles + from app.services.shipping_notice.onhand_profile_matching import recommend_profiles analysis.match_result_json = recommend_profiles({ 'structure': structure, @@ -200,7 +200,7 @@ def _persist_analysis(*, asset: FileAsset, owner_id: int) -> ShippingInventorySt return analysis -def _classify(analysis: ShippingInventoryStructureAnalysis) -> tuple[str, str]: +def _classify(analysis: FreightRpaOnhandStructureAnalysis) -> tuple[str, str]: """在用户已明确声明库存文件后,仅按通用表格结构判断是否可进入候选映射。""" structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {} headers = structure.get('selected_headers') if isinstance(structure.get('selected_headers'), list) else [] @@ -230,27 +230,27 @@ def create_temporary_inventory_session(payload: dict[str, Any]) -> dict[str, Any session = _runtime_session(payload.get('agent_runtime_context')) asset_no = str(payload.get('asset_no') or '').strip().upper() if not asset_no: - raise ValidationError('Temporary inventory asset is required', code='SHIPPING.TEMP_INVENTORY_ASSET_REQUIRED') + raise ValidationError('Temporary inventory asset is required', code='SHIPPING.TEMP_ONHAND_ASSET_REQUIRED') asset = FileAsset.query.filter_by(asset_no=asset_no, deleted_at=None).one_or_none() if asset is None or int(asset.owner_user_id) != int(session.user_id): - raise NotFoundError('Temporary inventory asset not found', code='SHIPPING.TEMP_INVENTORY_ASSET_NOT_FOUND') + raise NotFoundError('Temporary inventory asset not found', code='SHIPPING.TEMP_ONHAND_ASSET_NOT_FOUND') if str(asset.upload_status or '') != 'ready': - raise ConflictError('Temporary inventory asset is not ready', code='SHIPPING.TEMP_INVENTORY_ASSET_NOT_READY') + raise ConflictError('Temporary inventory asset is not ready', code='SHIPPING.TEMP_ONHAND_ASSET_NOT_READY') try: resolve_inventory_upload_suffix(asset.original_filename) except Exception as exc: - raise ValidationError('Temporary inventory only supports xls, xlsx or csv', code='SHIPPING.TEMP_INVENTORY_FILE_TYPE_INVALID') from exc + raise ValidationError('Temporary inventory only supports xls, xlsx or csv', code='SHIPPING.TEMP_ONHAND_FILE_TYPE_INVALID') from exc - active = ShippingTemporaryInventorySession.query.filter( - ShippingTemporaryInventorySession.user_id == session.user_id, - ShippingTemporaryInventorySession.conversation_id == session.session_id, - ShippingTemporaryInventorySession.asset_id == asset.id, - ShippingTemporaryInventorySession.status.in_([ + active = ShippingTemporaryOnhandSession.query.filter( + ShippingTemporaryOnhandSession.user_id == session.user_id, + ShippingTemporaryOnhandSession.conversation_id == session.session_id, + ShippingTemporaryOnhandSession.asset_id == asset.id, + ShippingTemporaryOnhandSession.status.in_([ 'created', 'awaiting_profile_confirmation', 'awaiting_mapping_suggestion', 'awaiting_mapping_confirmation', ]), - ShippingTemporaryInventorySession.expires_at > datetime.utcnow(), - ).order_by(ShippingTemporaryInventorySession.id.desc()).first() + ShippingTemporaryOnhandSession.expires_at > datetime.utcnow(), + ).order_by(ShippingTemporaryOnhandSession.id.desc()).first() if active: return _serialize(active) @@ -262,7 +262,7 @@ def create_temporary_inventory_session(payload: dict[str, Any]) -> dict[str, Any asset.expires_at = expires_at match_result = analysis.match_result_json if isinstance(analysis.match_result_json, dict) else {} has_exact_profile = classification == 'inventory_candidate' and str(match_result.get('status') or '') == 'exact' - item = ShippingTemporaryInventorySession( + item = ShippingTemporaryOnhandSession( session_no=_session_no(), user_id=int(session.user_id), conversation_id=session.session_id, asset_id=int(asset.id), analysis_id=analysis.id, declared_intent='inventory_candidate', file_classification_status=classification, @@ -291,11 +291,11 @@ def get_temporary_inventory_session(payload: dict[str, Any]) -> dict[str, Any]: """ session = _runtime_session(payload.get('agent_runtime_context')) session_no = str(payload.get('temporary_session_no') or '').strip().upper() - item = ShippingTemporaryInventorySession.query.filter_by( + item = ShippingTemporaryOnhandSession.query.filter_by( session_no=session_no, user_id=int(session.user_id), conversation_id=session.session_id, ).one_or_none() if item is None: - raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND') + raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_ONHAND_SESSION_NOT_FOUND') if item.expires_at <= datetime.utcnow() and item.status not in {'rejected', 'expired'}: item.status = 'expired' db.session.commit() @@ -317,31 +317,31 @@ def submit_temporary_inventory_mapping_suggestion(payload: dict[str, Any]) -> di """ session = _runtime_session(payload.get('agent_runtime_context')) session_no = str(payload.get('temporary_session_no') or '').strip().upper() - item = ShippingTemporaryInventorySession.query.filter_by( + item = ShippingTemporaryOnhandSession.query.filter_by( session_no=session_no, user_id=int(session.user_id), conversation_id=session.session_id, ).one_or_none() if item is None: - raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND') + raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_ONHAND_SESSION_NOT_FOUND') if item.status != 'awaiting_mapping_suggestion': - raise ConflictError('Temporary inventory session cannot accept a mapping suggestion', code='SHIPPING.TEMP_INVENTORY_MAPPING_STATE_INVALID') + raise ConflictError('Temporary inventory session cannot accept a mapping suggestion', code='SHIPPING.TEMP_ONHAND_MAPPING_STATE_INVALID') raw_mapping = payload.get('field_mapping') if not isinstance(raw_mapping, dict) or not raw_mapping: - raise ValidationError('Temporary inventory mapping suggestion is required', code='SHIPPING.TEMP_INVENTORY_MAPPING_INVALID') + raise ValidationError('Temporary inventory mapping suggestion is required', code='SHIPPING.TEMP_ONHAND_MAPPING_INVALID') mapping = { str(field_id).strip(): str(header).strip() for field_id, header in raw_mapping.items() if str(field_id).strip() and str(header).strip() } - analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None + analysis = db.session.get(FreightRpaOnhandStructureAnalysis, item.analysis_id) if item.analysis_id else None structure = analysis.structure_json if analysis and isinstance(analysis.structure_json, dict) else {} headers = [str(header).strip() for header in structure.get('selected_headers', []) if str(header).strip()] if not headers or len(mapping) != len(raw_mapping) or len(set(mapping.values())) != len(mapping): - raise ValidationError('Temporary inventory mapping suggestion is invalid', code='SHIPPING.TEMP_INVENTORY_MAPPING_INVALID') + raise ValidationError('Temporary inventory mapping suggestion is invalid', code='SHIPPING.TEMP_ONHAND_MAPPING_INVALID') errors = validate_field_mapping_against_headers(headers, mapping) if errors or not mapping_is_complete(mapping): raise ValidationError( 'Temporary inventory mapping suggestion is incomplete or invalid', - code='SHIPPING.TEMP_INVENTORY_MAPPING_INVALID', details={'errors': errors}, + code='SHIPPING.TEMP_ONHAND_MAPPING_INVALID', details={'errors': errors}, ) item.result_json = { **(item.result_json if isinstance(item.result_json, dict) else {}), @@ -353,19 +353,19 @@ def submit_temporary_inventory_mapping_suggestion(payload: dict[str, Any]) -> di def _select_confirmed_mapping( - item: ShippingTemporaryInventorySession, + item: ShippingTemporaryOnhandSession, *, selected_profile_id: Any, ) -> tuple[dict[str, str], str, int | None]: """按会话状态选择 exact 已发布方案或已校验建议,禁止请求直接传映射覆盖。""" - analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None + analysis = db.session.get(FreightRpaOnhandStructureAnalysis, item.analysis_id) if item.analysis_id else None if analysis is None: - raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID') + raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_ONHAND_CONFIRMATION_INVALID') if item.status == 'awaiting_profile_confirmation': try: profile_id = int(selected_profile_id) except (TypeError, ValueError) as exc: - raise ValidationError('A published parsing profile must be selected', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID') from exc + raise ValidationError('A published parsing profile must be selected', code='SHIPPING.TEMP_ONHAND_CONFIRMATION_INVALID') from exc candidates = (analysis.match_result_json or {}).get('candidates', []) if isinstance(analysis.match_result_json, dict) else [] exact_ids = { int(candidate.get('profile_id')) @@ -373,17 +373,17 @@ def _select_confirmed_mapping( and str(candidate.get('level') or '') == 'exact' and str(candidate.get('profile_id') or '').isdigit() } - profile = db.session.get(ShippingInventoryParsingProfile, profile_id) + profile = db.session.get(FreightRpaParsingProfile, profile_id) if profile is None or profile.status != 'published' or profile_id not in exact_ids: - raise ValidationError('Selected parsing profile is not an exact published candidate', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID') + raise ValidationError('Selected parsing profile is not an exact published candidate', code='SHIPPING.TEMP_ONHAND_CONFIRMATION_INVALID') return dict((profile.definition_json or {}).get('field_mapping') or {}), f'published_profile:{profile.profile_code}:v{profile.version}', profile.id if item.status == 'awaiting_mapping_confirmation': suggestion = _mapping_suggestion(item) or {} mapping = suggestion.get('field_mapping') if isinstance(suggestion.get('field_mapping'), dict) else {} if not mapping: - raise ConflictError('Temporary inventory mapping suggestion is missing', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID') + raise ConflictError('Temporary inventory mapping suggestion is missing', code='SHIPPING.TEMP_ONHAND_CONFIRMATION_INVALID') return dict(mapping), 'dify_candidate', None - raise ConflictError('Temporary inventory session cannot be confirmed', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID') + raise ConflictError('Temporary inventory session cannot be confirmed', code='SHIPPING.TEMP_ONHAND_CONFIRMATION_INVALID') def _quality_report(lines: list[dict[str, Any]], field_mapping: dict[str, str]) -> dict[str, Any]: @@ -419,7 +419,7 @@ def confirm_temporary_inventory_use(payload: dict[str, Any]) -> dict[str, Any]: 【AI 触发时机】:仅在用户明确确认“本次使用此库存文件/方案”后调用,Dify 不得自行确认。 核心逻辑:选择 exact published 方案或已校验映射,重新解析受控原文件并执行质量门禁; - 只写临时会话审计,不创建 ShippingInventoryFile、不修改库存站点、不回填任务库存行、不执行匹配。 + 只写临时会话审计,不创建 FreightRpaOnhandReportFile、不修改库存站点、不回填任务库存行、不执行匹配。 Args: payload: 必须含 agent_runtime_context、temporary_session_no;exact 方案需 selected_profile_id。 @@ -429,19 +429,19 @@ def confirm_temporary_inventory_use(payload: dict[str, Any]) -> dict[str, Any]: """ session = _runtime_session(payload.get('agent_runtime_context')) session_no = str(payload.get('temporary_session_no') or '').strip().upper() - item = ShippingTemporaryInventorySession.query.filter_by( + item = ShippingTemporaryOnhandSession.query.filter_by( session_no=session_no, user_id=int(session.user_id), conversation_id=session.session_id, ).one_or_none() if item is None: - raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND') + raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_ONHAND_SESSION_NOT_FOUND') if item.expires_at <= datetime.utcnow(): item.status = 'expired' db.session.commit() - raise ConflictError('Temporary inventory session has expired', code='SHIPPING.TEMP_INVENTORY_SESSION_EXPIRED') + raise ConflictError('Temporary inventory session has expired', code='SHIPPING.TEMP_ONHAND_SESSION_EXPIRED') mapping, mapping_origin, profile_id = _select_confirmed_mapping(item, selected_profile_id=payload.get('selected_profile_id')) - analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None + analysis = db.session.get(FreightRpaOnhandStructureAnalysis, item.analysis_id) if item.analysis_id else None if analysis is None: - raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID') + raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_ONHAND_CONFIRMATION_INVALID') structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {} try: lines, column_meta = parse_inventory_excel_with_meta( @@ -449,10 +449,10 @@ def confirm_temporary_inventory_use(payload: dict[str, Any]) -> dict[str, Any]: header_row_index=structure.get('selected_header_row_index'), sheet_name=structure.get('selected_sheet_name'), ) except Exception as exc: - raise ValidationError('Temporary inventory file cannot pass deterministic parsing', code='SHIPPING.TEMP_INVENTORY_QUALITY_INVALID') from exc + raise ValidationError('Temporary inventory file cannot pass deterministic parsing', code='SHIPPING.TEMP_ONHAND_QUALITY_INVALID') from exc quality = _quality_report(lines, mapping) if not quality['passed']: - raise ValidationError('Temporary inventory file does not meet quality requirements', code='SHIPPING.TEMP_INVENTORY_QUALITY_INVALID', details={'quality': quality}) + raise ValidationError('Temporary inventory file does not meet quality requirements', code='SHIPPING.TEMP_ONHAND_QUALITY_INVALID', details={'quality': quality}) item.task_id = None item.result_json = { **(item.result_json if isinstance(item.result_json, dict) else {}), @@ -470,12 +470,12 @@ def confirm_temporary_inventory_use(payload: dict[str, Any]) -> dict[str, Any]: def list_confirmed_temporary_inventory_sessions(*, limit: int = 100) -> list[dict[str, Any]]: """返回管理员可沉淀为解析方案草稿的已确认临时会话,不暴露库存行或对象存储路径。""" - rows = ShippingTemporaryInventorySession.query.filter_by( + rows = ShippingTemporaryOnhandSession.query.filter_by( status='confirmed_for_temporary_use', - ).order_by(ShippingTemporaryInventorySession.updated_at.desc()).limit(max(1, min(int(limit or 100), 200))).all() + ).order_by(ShippingTemporaryOnhandSession.updated_at.desc()).limit(max(1, min(int(limit or 100), 200))).all() result: list[dict[str, Any]] = [] for item in rows: - analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None + analysis = db.session.get(FreightRpaOnhandStructureAnalysis, item.analysis_id) if item.analysis_id else None confirmed = _confirmed_usage(item) result.append({ 'session_no': item.session_no, @@ -513,24 +513,24 @@ def create_parsing_profile_draft_from_temporary_session( 新建的库存文件解析方案草稿。 """ normalized_no = str(session_no or '').strip().upper() - item = ShippingTemporaryInventorySession.query.filter_by(session_no=normalized_no).one_or_none() + item = ShippingTemporaryOnhandSession.query.filter_by(session_no=normalized_no).one_or_none() if item is None: - raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND') + raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_ONHAND_SESSION_NOT_FOUND') if item.status != 'confirmed_for_temporary_use': - raise ConflictError('Temporary inventory session is not confirmed', code='SHIPPING.TEMP_INVENTORY_PROMOTION_INVALID') + raise ConflictError('Temporary inventory session is not confirmed', code='SHIPPING.TEMP_ONHAND_PROMOTION_INVALID') confirmed = (item.result_json or {}).get('confirmed_usage') if isinstance(item.result_json, dict) else None if not isinstance(confirmed, dict) or not isinstance(confirmed.get('field_mapping'), dict): - raise ConflictError('Temporary inventory confirmation is incomplete', code='SHIPPING.TEMP_INVENTORY_PROMOTION_INVALID') + raise ConflictError('Temporary inventory confirmation is incomplete', code='SHIPPING.TEMP_ONHAND_PROMOTION_INVALID') existing_draft_id = (item.result_json or {}).get('promoted_profile_draft_id') if isinstance(item.result_json, dict) else None if existing_draft_id: - existing_draft = db.session.get(ShippingInventoryParsingProfile, existing_draft_id) + existing_draft = db.session.get(FreightRpaParsingProfile, existing_draft_id) if existing_draft is not None: - from app.services.shipping_notice.inventory_parsing_profile import payload as profile_payload + from app.services.freight_rpa.parsing_profile import payload as profile_payload return profile_payload(existing_draft) - analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None + analysis = db.session.get(FreightRpaOnhandStructureAnalysis, item.analysis_id) if item.analysis_id else None if analysis is None: - raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_INVENTORY_PROMOTION_INVALID') + raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_ONHAND_PROMOTION_INVALID') structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {} payload = { 'profile_code': data.get('profile_code'), @@ -540,9 +540,9 @@ def create_parsing_profile_draft_from_temporary_session( 'field_mapping': confirmed['field_mapping'], 'match_keys': data.get('match_keys'), } - from app.services.shipping_notice import inventory_structure_analysis + from app.services.shipping_notice import onhand_structure_analysis - draft = inventory_structure_analysis.create_profile_draft(analysis.id, payload, actor_id=actor_id) + draft = onhand_structure_analysis.create_profile_draft(analysis.id, payload, actor_id=actor_id) item.result_json = { **(item.result_json if isinstance(item.result_json, dict) else {}), 'promoted_profile_draft_id': draft['id'], diff --git a/backend/app/services/shipping_notice/onhand_trigger_batch.py b/backend/app/services/shipping_notice/onhand_trigger_batch.py new file mode 100644 index 00000000..0a33be48 --- /dev/null +++ b/backend/app/services/shipping_notice/onhand_trigger_batch.py @@ -0,0 +1,203 @@ +""" +services/shipping_notice/onhand_trigger_batch.py + +用途:onhand(在手库存)RPA 的批量/按需导出编排——组装逐源凭据与身份键、写批量 trigger、 + 单票按需触发的 fail-closed 入口。 +依赖:Flask current_app 配置、freight_rpa.onhand.trigger_io(目录解析/原子写/SCHEMA/ACTION 常量)、 + shipping_notice.onhand_source_repository(按源补 Profile 密文,函数内延迟 import)。 +逻辑:由 schedule.freight_rpa_onhand_job(定时批量)、onhand_configuration_test(配置测试)、 + onhand_rpa_workflow / per_source_rpa_service(按需触发)调用, + 与 freight_rpa.onhand.trigger_io 的纯文件 IO 分层:本文件管业务编排,目录与 JSON 原子写下沉包内。 + s18 起 report_path_json / query_parameters_json / parsing_profile_id 改由仓库快照取自 + source.onhand_report_config 配置行(navigation/parameters 由此派生);配置行缺失时 + 仓库返回 None,沿用「站点未就绪」的跳过/回退语义,不新造错误码。 +""" + +from __future__ import annotations + +import os +from datetime import datetime +from typing import Any + +from flask import current_app +from app.core.errors import ValidationError +from app.services.freight_rpa.onhand.trigger_io import ( + ACTION_ONHAND_EXPORT_BATCH, + SCHEMA, + _write_trigger_json_atomic, + onhand_trigger_dir, +) + + +def write_inventory_export_batch_trigger( + run_no: str, + sources: list[dict[str, Any]], + *, + payload: dict[str, Any] | None = None, +) -> str | None: + """ + 写入批量库存导出 trigger(DSV/Crane 一次登录多 Warehouse)。 + 【AI 触发时机】:定时排程或后台批量预热库存快照时调用。 + + Args: + run_no: RPA 批次号,写入回调 audit。 + sources: build_rpa_inventory_source 构造的源列表。 + payload: 额外字段(trigger_type、schedule_run_id 等)。 + + Returns: + str | None: 触发文件绝对路径。 + """ + trigger_dir = onhand_trigger_dir() + if not trigger_dir or not sources: + return None + trigger_dir.mkdir(parents=True, exist_ok=True) + inventory_sources = [] + for source in sources: + if not isinstance(source, dict) or not source.get("source_code"): + continue + # 调用方只持有非敏感快照;写 trigger 前在服务端按 Source 补入 Profile 密文。 + from app.services.shipping_notice.onhand_source_repository import get_rpa_trigger_inventory_source + configuration_test = str((payload or {}).get('trigger_type') or '') in {'configuration_test', 'configuration_test_batch'} + trigger_source = get_rpa_trigger_inventory_source( + str(source["source_code"]), enabled_only=not configuration_test, + ) or source + # s18 起合并进来的 report_path_json / query_parameters_json / parsing_profile_id + # 均取自 source.onhand_report_config 配置行(仓库快照),配置缺失时上面已回退到 + # 调用方传入的非敏感快照,沿用「站点未就绪」既有语义。 + source = {**source, **trigger_source} + business_connector = str(source.get("connector_type") or "").strip().lower() + worker_connector = {"dbs": "dsv360", "crane": "crane_footprint"}.get(business_connector, business_connector) + item = { + "source_code": source.get("source_code"), + "connector_type": business_connector, + "worker_connector_type": worker_connector, + "rpa_profile_code": source.get("rpa_profile_code"), + "warehouse_id": source.get("fixed_warehouse_id") or source.get("warehouse_id"), + "login_url": source.get("login_url"), + "entry_url": source.get("login_url"), + "navigation": source.get("navigation") or {}, + "parameters": source.get("parameters") or [], + "query": source.get("query") or {}, + "credential_envelope": source.get("credential_envelope") or {}, + # 配置测试回调据此将批次结果精确回写到各自站点运行。 + "validation_run_no": source.get("validation_run_no"), + } + # v2 逐源身份必须由后端显式写入,Worker 不得重新生成。 + for identity_key in ( + "callback_id", "task_no", "attempt_no", "source_run_no", "candidate_set_id", "candidate_set_version", + "execution_id", "gate_id", "expected_warehouse_id", "lease_token", + ): + if source.get(identity_key) is not None: + item[identity_key] = source[identity_key] + if not item.get('callback_id') and item.get('source_run_no'): + item['callback_id'] = f"{item['source_run_no']}:C1" + inventory_sources.append(item) + if not inventory_sources: + return None + + body = { + "action": ACTION_ONHAND_EXPORT_BATCH, + "schema_version": SCHEMA, + "callback_id": f"{run_no}:batch:C1", + "batch_run_no": run_no, + "run_no": run_no, # 旧排程读取兼容;新回调不得依赖该字段 + "trigger_type": "scheduled", + "requested_at": datetime.utcnow().isoformat(), + "inventory_sources": inventory_sources, + **(payload or {}), + } + safe_run = "".join(ch for ch in run_no if ch.isalnum() or ch in {"-", "_"}) or "batch" + path = trigger_dir / f"inventory_export_batch_{safe_run}.json" + _write_trigger_json_atomic(path, body) + return str(path) + + +def onhand_rpa_batch_enabled() -> bool: + """是否启用按需单票走 batch trigger 统一路径(Flask config 优先于环境变量)。""" + raw = current_app.config.get("SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED") + if raw is None: + raw = os.getenv("SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED", "true") + return str(raw).strip().lower() in {"1", "true", "yes", "on"} + + +def build_on_demand_inventory_trigger_source( + task_no: str, + rpa_source: dict[str, Any], + *, + body: dict[str, Any], +) -> dict[str, Any]: + """ + 构造按需库存导出批次触发内的单源条目(含 Profile 凭据与逐源身份键)。 + 【AI 触发时机】:单源 on-demand 触发与多候选合并批次触发(per_source_rpa_service)共用本构造, + 保证两条路径投递给 Worker 的输入契约完全一致。 + + Args: + task_no: 发货任务号。 + rpa_source: 调用方持有的非敏感源快照(含 source_code);DB 配置/Profile 存在时以其为准。 + body: 触发载荷,提供 callback_id/source_run_no/attempt_no/lease_token 等逐源身份键。 + + Returns: + 可直接传入 write_inventory_export_batch_trigger 的单源条目。 + """ + from app.services.shipping_notice.onhand_source_repository import get_rpa_trigger_inventory_source + + source_code = str(rpa_source.get('source_code') or '').strip() + rpa_source = get_rpa_trigger_inventory_source(source_code) or rpa_source + # Legacy 单票 trigger 与 batch trigger 必须共享 worker 输入契约。 + rpa_source = dict(rpa_source) + business_connector = str(rpa_source.get('connector_type') or '').strip().lower() + rpa_source.setdefault('worker_connector_type', {'dbs': 'dsv360', 'crane': 'crane_footprint'}.get(business_connector, business_connector)) + rpa_source.setdefault('entry_url', rpa_source.get('login_url')) + rpa_source.setdefault('credential_envelope', {}) + source_item = dict(rpa_source) + source_item.update({ + "source_code": source_code, + "callback_id": body.get("callback_id") or ( + f"{body.get('source_run_no')}:C1" if body.get('source_run_no') else None + ), + "task_no": task_no, + # 按需逐源回调必须携带 Attempt 身份;仅写在 batch 顶层会导致 + # Worker 结果丢失 source_run_no,后端无法把 Excel 绑定到最新 Attempt。 + "attempt_no": body.get("attempt_no") or body.get("attempt"), + "source_run_no": body.get("source_run_no"), + "candidate_set_id": body.get("candidate_set_id"), + "candidate_set_version": body.get("candidate_set_version"), + "execution_id": body.get("execution_id"), + "gate_id": body.get("gate_id"), + "expected_warehouse_id": body.get("expected_warehouse_id"), + "lease_token": body.get("lease_token"), + }) + return source_item + + +def write_inventory_export_trigger_for_task( + task_no: str, + rpa_source: dict[str, Any], + *, + payload: dict[str, Any] | None = None, +) -> str | None: + """ + 写入按需库存 RPA trigger;batch 开启时包装为单源 batch trigger,与定时导出共用 worker 路径。 + 【AI 触发时机】:ensure_inventory_via_rpa 触发单票 RPA 导出时调用。 + + 核心逻辑:仅允许 v2 batch 模式写 inventory_export_batch;关闭时 fail-closed, + 不再生成 legacy inventory_export trigger。 + """ + body = dict(payload or {}) + if onhand_rpa_batch_enabled(): + run_no = str(body.get("batch_run_no") or f"BATCH-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}") + source_item = build_on_demand_inventory_trigger_source(task_no, rpa_source, body=body) + return write_inventory_export_batch_trigger( + run_no, + [source_item], + payload={ + "schema_version": SCHEMA, + "trigger_type": "on_demand", + "task_no": task_no, + **body, + }, + ) + raise ValidationError( + 'shipping inventory RPA v2 batch trigger is required', + code='SHIPPING.ONHAND_RPA_V2_REQUIRED', + ) diff --git a/backend/app/services/shipping_notice/inventory_upload.py b/backend/app/services/shipping_notice/onhand_upload.py similarity index 95% rename from backend/app/services/shipping_notice/inventory_upload.py rename to backend/app/services/shipping_notice/onhand_upload.py index 5de59882..b9d2f74a 100644 --- a/backend/app/services/shipping_notice/inventory_upload.py +++ b/backend/app/services/shipping_notice/onhand_upload.py @@ -1,9 +1,9 @@ """ -services/shipping_notice/inventory_upload.py +services/shipping_notice/onhand_upload.py 用途:管理任务级库存附件上传、落盘、schema preview 读取与文本长度限制。 -依赖:inventory_snapshot、export._storage_root、Werkzeug FileStorage、Flask current_app 配置。 -逻辑:由 inventory_workflow、task_workflow 与工作台上传入口调用本文件,把库存文件保存到任务目录并读取预览信息; +依赖:onhand_snapshot、export._storage_root、Werkzeug FileStorage、Flask current_app 配置。 +逻辑:由 onhand_workflow、task_workflow 与工作台上传入口调用本文件,把库存文件保存到任务目录并读取预览信息; 正式附件使用版本化文件名 + .current_inventory 原子指针,避免多格式并存或崩溃后误读旧文件。 """ @@ -19,9 +19,9 @@ from typing import Any from flask import current_app from werkzeug.datastructures import FileStorage -from app.models import ShippingInventoryFile, ShippingNotice, ShippingOrderTask +from app.models import FreightRpaOnhandReportFile, ShippingNotice, ShippingOrderTask from app.services.shipping_notice.export import _storage_root -from app.services.shipping_notice.inventory_file_store import inventory_storage_suffix_for_path +from app.services.shipping_notice.onhand_file_store import inventory_storage_suffix_for_path _TASK_INVENTORY_SUFFIXES = (".xls", ".xlsx", ".csv") _TASK_INVENTORY_MARKER = ".current_inventory" _TASK_INVENTORY_VERSION_PREFIX = "inventory_" @@ -164,7 +164,7 @@ def install_task_inventory_attachment_from_file( def rebuild_task_inventory_attachment_from_snapshot( task: ShippingOrderTask | ShippingNotice | str, - inv_file: ShippingInventoryFile, + inv_file: FreightRpaOnhandReportFile, ) -> Path: """ 从已提交库存快照 storage_path 幂等重建任务正式附件。 @@ -183,7 +183,7 @@ def rebuild_task_inventory_attachment_from_snapshot( storage_path = Path(str(inv_file.storage_path or "")) if not storage_path.is_file() or str(inv_file.storage_path or "").startswith("failed://"): raise FileNotFoundError( - f"库存快照托管文件不存在: {inv_file.inventory_file_no}", + f"库存快照托管文件不存在: {inv_file.onhand_file_no}", ) return install_task_inventory_attachment_from_file( task_no, diff --git a/backend/app/services/shipping_notice/inventory_warehouse_resolution.py b/backend/app/services/shipping_notice/onhand_warehouse_resolution.py similarity index 78% rename from backend/app/services/shipping_notice/inventory_warehouse_resolution.py rename to backend/app/services/shipping_notice/onhand_warehouse_resolution.py index f5e16c2b..9250a723 100644 --- a/backend/app/services/shipping_notice/inventory_warehouse_resolution.py +++ b/backend/app/services/shipping_notice/onhand_warehouse_resolution.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/inventory_warehouse_resolution.py +services/shipping_notice/onhand_warehouse_resolution.py 用途:按库存解析方案的匹配关系,从订单行与库存行确定动态 Warehouse。 -依赖:ShippingInventoryField/Source、动态订单字段投影。 +依赖:FreightRpaOnhandField/Source、动态订单字段投影。 逻辑:仅在 inventory_match Source 链接库存快照时调用;字段 ID 和用途决定匹配及仓库取值。 """ @@ -11,7 +11,7 @@ from __future__ import annotations from dataclasses import dataclass from typing import Any -from app.models import ShippingInventoryField, ShippingInventorySource +from app.models import FreightRpaOnhandField, FreightRpaSource from app.services.shipping_notice.export import order_field_id_values @@ -31,8 +31,11 @@ def _key(row: dict[str, Any], fields: list[str]) -> tuple[str, ...] | None: def resolve_dynamic_warehouse(*, task: Any, inventory_lines: list[dict[str, Any]], fallback_warehouse_id: str | None = None, source_code: str | None = None) -> WarehouseResolution: """按站点已发布解析方案为全部订单行寻找唯一 Warehouse。""" - source = ShippingInventorySource.query.filter_by(source_code=source_code).first() - definition = source.parsing_profile.definition_json if source and source.parsing_profile else {} + source = FreightRpaSource.query.filter_by(source_code=source_code).first() + # s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系。 + config = source.onhand_report_config if source is not None else None + profile = config.parsing_profile if config is not None else None + definition = profile.definition_json if profile is not None else {} match_keys = definition.get('match_keys') if isinstance(definition, dict) else [] order_fields = [str(item.get('order_field_id') or '') for item in match_keys if isinstance(item, dict)] inventory_fields = [str(item.get('inventory_field_id') or '') for item in match_keys if isinstance(item, dict)] @@ -40,9 +43,9 @@ def resolve_dynamic_warehouse(*, task: Any, inventory_lines: list[dict[str, Any] int(field_id) for field_id in (definition.get('field_mapping') or {}) if str(field_id).isdigit() } if isinstance(definition, dict) else set() - warehouse_fields = ShippingInventoryField.query.filter( - ShippingInventoryField.id.in_(mapped_ids), ShippingInventoryField.status == 'active', - ShippingInventoryField.usage_type == 'warehouse_identity', + warehouse_fields = FreightRpaOnhandField.query.filter( + FreightRpaOnhandField.id.in_(mapped_ids), FreightRpaOnhandField.status == 'active', + FreightRpaOnhandField.usage_type == 'warehouse_identity', ).all() if mapped_ids else [] if not order_fields or len(order_fields) != len(inventory_fields) or len(warehouse_fields) != 1: return WarehouseResolution(None, 'warehouse_configuration_invalid') diff --git a/backend/app/services/shipping_notice/inventory_workflow.py b/backend/app/services/shipping_notice/onhand_workflow.py similarity index 89% rename from backend/app/services/shipping_notice/inventory_workflow.py rename to backend/app/services/shipping_notice/onhand_workflow.py index fe422e11..e66187d7 100644 --- a/backend/app/services/shipping_notice/inventory_workflow.py +++ b/backend/app/services/shipping_notice/onhand_workflow.py @@ -1,11 +1,11 @@ """ -services/shipping_notice/inventory_workflow.py +services/shipping_notice/onhand_workflow.py -用途:发货通知正式库存阶段编排(上传、复用已解析库存文件);RPA 见 inventory_rpa_workflow。 -依赖:customer_identity_gate、reservation_gate、inventory_file_store、inventory_mapping_workflow、 - inventory_snapshot_store、query_service、state_machine、动态订单字段、per_source_rpa_service。 +用途:发货通知正式库存阶段编排(上传、复用已解析库存文件);RPA 见 onhand_rpa_workflow。 +依赖:customer_identity_gate、reservation_gate、onhand_file_store、onhand_mapping_workflow、 + onhand_snapshot_store、query_service、state_machine、动态订单字段、per_source_rpa_service。 逻辑:正式库存仅按库存站点 published Profile 确定性解析;任务级列推断和映射确认入口已移除; - payload.source_codes 可收窄 ensure_inventory / RPA 作用源(行级重抓); + payload.source_codes 可收窄 ensure_inventory(持久化阶段码 ensure_onhand)/ RPA 作用源(行级重抓); STP 冻结源 ready 复用必须先 link 快照再推进状态(persist_lines=False),禁止未绑定或覆盖共享 File; 动态仓复用走 link_snapshot_to_task_for_preparation,仓未决不得谎称库存文件缺失。 """ @@ -21,8 +21,8 @@ from app.models import ShippingOrderTask from app.services.shipping_notice.constants import ( POSITION_INVENTORY_SOURCE_REVIEW, ) -from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response -from app.services.shipping_notice.inventory_file_store import save_task_inventory_upload +from app.services.shipping_notice.onhand_mapping_workflow import inventory_loaded_response +from app.services.shipping_notice.onhand_file_store import save_task_inventory_upload from app.services.shipping_notice.query_service import ( get_task_by_ref, resolve_task_from_payload, @@ -31,7 +31,7 @@ from app.services.shipping_notice.query_service import ( from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues from app.services.shipping_notice.task_field_gate import field_conflict_gate_response from app.services.shipping_notice.i18n import resolve_lang, t -from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable +from app.services.shipping_notice.onhand_source_gate import assert_inventory_source_gate, is_inventory_source_stable from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response from app.services.shipping_notice.state_machine import resolve_task_ui_state from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition @@ -67,20 +67,20 @@ def _link_ready_candidate_prep_or_block( 核心逻辑:已有 active link 直接放行;否则取 evidence(或行标签)中首个 loaded 快照并 ``link_snapshot_to_task_for_preparation``。动态仓仓库识别失败时仍保留文件绑定 - (pending_matching),仓/匹配问题留给 inventory_matching,禁止把「有文件」投影成 + (pending_matching),仓/匹配问题留给 onhand_matching,禁止把「有文件」投影成 inventory_file_missing。仅当真的无法绑定文件时才 needs_human。 Args: task: 已冻结候选源的订单任务。 - prep: ``prepare_candidate_inventory_lines`` 的 ready 结果。 + prep: ``prepare_candidate_onhand_lines`` 的 ready 结果。 lang: 文案语言。 Returns: None 表示可继续 ``inventory_loaded_response(persist_lines=False)``;dict 为 tool_response 阻断结果。 """ - from app.models import ShippingInventoryFile - from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task - from app.services.shipping_notice.inventory_snapshot_store import ( + from app.models import FreightRpaOnhandReportFile + from app.services.shipping_notice.onhand_file_store import active_inventory_file_for_task + from app.services.shipping_notice.onhand_snapshot_store import ( link_snapshot_to_task_for_preparation, ) @@ -107,7 +107,7 @@ def _link_ready_candidate_prep_or_block( break inv_file = ( - ShippingInventoryFile.query.filter_by(inventory_file_no=file_no).first() + FreightRpaOnhandReportFile.query.filter_by(onhand_file_no=file_no).first() if file_no else None ) @@ -132,7 +132,7 @@ def _link_ready_candidate_prep_or_block( apply_task_transition(task, TaskTransition.INV_UNAVAIL) set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title='获取库存', status='needs_human', message=t('workflow.inventory.unavailable', lang=lang), @@ -221,10 +221,10 @@ def _inventory_source_gate_response(task: ShippingOrderTask, *, operation: str, reservation_gate = _reservation_gate_response(task, lang=lang) if reservation_gate is not None: return reservation_gate - if operation == "ensure_inventory": + if operation == "ensure_onhand": # [STEP 0A] 库存准备只能消费已经冻结的路由事实;不得在本阶段补做裁决或 # 触发 RPA。CandidateSet、Source、Line 任一缺失都必须停留在 routing Gate。 - from app.services.shipping_notice.inventory_candidate_projection import ( + from app.services.shipping_notice.onhand_candidate_projection import ( get_active_candidate_lines, get_active_candidate_set, get_active_candidate_sources, @@ -251,7 +251,7 @@ def _inventory_source_gate_response(task: ShippingOrderTask, *, operation: str, message="库存源候选集尚未冻结完成,暂不能准备库存。", data={ **serialize_task_for_tool(task), - "error_code": "SHIPPING.INVENTORY_SOURCE_ROUTING_REQUIRED", + "error_code": "SHIPPING.ONHAND_SOURCE_ROUTING_REQUIRED", "position": POSITION_INVENTORY_SOURCE_REVIEW, }, position=POSITION_INVENTORY_SOURCE_REVIEW, @@ -281,7 +281,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]: if not task: return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang="zh")) lang = resolve_lang({"lang": None}) - gate_resp = _inventory_source_gate_response(task, operation="upload_inventory_file", lang=lang) + gate_resp = _inventory_source_gate_response(task, operation="upload_onhand_file", lang=lang) if gate_resp is not None: return gate_resp from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success @@ -312,7 +312,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]: try: set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title="获取库存", status="running", message=t("workflow.inventory.uploading", lang=lang), @@ -322,13 +322,13 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]: db.session.flush() inv_file = save_task_inventory_upload(task, upload) inventory_lines = [ - item for item in (inv_file.inventory_lines_json or []) if isinstance(item, dict) + item for item in (inv_file.onhand_lines_json or []) if isinstance(item, dict) ] preview = dict(inv_file.schema_preview_json or {}) except AppError as exc: db.session.rollback() message = str(exc.message or "库存上传被拒绝") - if exc.code == 'SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED': + if exc.code == 'SHIPPING.ONHAND_STRUCTURE_DRIFT_BLOCKED': message = '库存文件结构与该库存站点已发布的解析方案不一致,请重新导出正确文件或由管理员发布新方案。' return tool_response( status="failed", @@ -362,7 +362,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]: task, "inventory_snapshot_created", { - "inventory_file_no": inv_file.inventory_file_no, + "inventory_file_no": inv_file.onhand_file_no, "share_mode": inv_file.share_mode, }, ) @@ -397,7 +397,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: task_no, trigger=trigger, expected_version=None, idempotency_key=str(payload.get('idempotency_key') or '').strip() or None, - resume_gate_code='inventory_preparation', + resume_gate_code='onhand_preparation', operator_id=operator_id, inventory_mode=str(payload.get('mode') or 'auto').strip().lower() or 'auto', line_scope_key=( @@ -415,7 +415,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang)) # [STEP 0] 与 parse/upload 共用客户、Reservation、库存源门禁,避免旁路入口绕过订单侧闸门。 - gate_resp = _inventory_source_gate_response(task, operation="ensure_inventory", lang=lang) + gate_resp = _inventory_source_gate_response(task, operation="ensure_onhand", lang=lang) if gate_resp is not None: return gate_resp @@ -441,27 +441,27 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: # [STEP 2] 正常流程优先复用已完成的库存快照;缺少快照时自动进入库存 RPA。 if mode == "retry_rpa": - from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa + from app.services.shipping_notice.onhand_rpa_workflow import ensure_inventory_via_rpa return ensure_inventory_via_rpa( task, mode=mode, source_codes=scoped_source_codes, ) if mode == "auto": - from app.services.shipping_notice.inventory_rpa_workflow import _try_reuse_inventory_snapshot - from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes - from app.services.shipping_notice.stp_line_inventory_match import prepare_candidate_inventory_lines + from app.services.shipping_notice.onhand_rpa_workflow import _try_reuse_inventory_snapshot + from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes + from app.services.shipping_notice.stp_line_onhand_match import prepare_candidate_onhand_lines # [STEP] STP 多候选:准备全部冻结源快照;缺文件则停在库存等待,不隐式触发 RPA。 - frozen_codes = task_frozen_inventory_source_codes(task) + frozen_codes = task_frozen_onhand_source_codes(task) if len(frozen_codes) >= 1: - prep = prepare_candidate_inventory_lines(task) + prep = prepare_candidate_onhand_lines(task) if prep.get('status') == 'blocked' and prep.get('error_code') == 'inventory_candidates_missing': apply_task_transition(task, TaskTransition.INV_UNAVAIL) set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title="获取库存", status="needs_human", message=t("workflow.inventory.unavailable", lang=lang), @@ -502,7 +502,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: task.error_message = None set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title="获取库存", status="running", message="已触发库存获取,等待各库存源回调。", @@ -521,7 +521,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: ) if probe.all_prepared: # 探测期间快照已就绪(竞态收敛):重载一次候选行后走正常加载。 - prep = prepare_candidate_inventory_lines(task) + prep = prepare_candidate_onhand_lines(task) else: # 探测无 pending(trigger 写入失败/无可用源):明确 needs_human 兜底。 log_task_event(task, "inventory_probe_failed", { @@ -530,7 +530,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: apply_task_transition(task, TaskTransition.INV_UNAVAIL) set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title="获取库存", status="needs_human", message="库存 RPA 未能为全部库存源生成结果。", @@ -556,7 +556,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: apply_task_transition(task, TaskTransition.INV_UNAVAIL) set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title="获取库存", status="needs_human", message=t("workflow.inventory.unavailable", lang=lang), @@ -599,7 +599,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: # 库存源已确定但没有可复用快照时,自动推进必须启动一次 RPA, # 否则任务会错误停在人审且没有可执行的恢复动作。 - from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa + from app.services.shipping_notice.onhand_rpa_workflow import ensure_inventory_via_rpa return ensure_inventory_via_rpa( task, @@ -610,7 +610,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: # [STEP 3] 最后处理已有任务库存与彻底缺库存两种兜底分支。 # 已有库存则推进到 inventory_ready;仍无库存则明确停在人审提示用户补数据。 - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task if has_ready_inventory_file_for_task(task): apply_task_transition(task, TaskTransition.INVENTORY_READY) @@ -625,7 +625,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: apply_task_transition(task, TaskTransition.INV_UNAVAIL) set_task_step_progress( task, - stage="inventory_fetching", + stage="onhand_fetching", step_title="获取库存", status="needs_human", message=t("workflow.inventory.unavailable", lang=lang), diff --git a/backend/app/services/shipping_notice/order_build_eligibility_service.py b/backend/app/services/shipping_notice/order_build_eligibility_service.py index 7754ad4c..b6118190 100644 --- a/backend/app/services/shipping_notice/order_build_eligibility_service.py +++ b/backend/app/services/shipping_notice/order_build_eligibility_service.py @@ -4,9 +4,9 @@ services/shipping_notice/order_build_eligibility_service.py 用途:汇总建单前资格:客户/订单字段、有效 Reservation、行级库存源候选,以及 Candidate Qualification 统一自动建单检查。 依赖:candidate_qualification_service(含 confidence_policy)、candidate_validation、field_rules、 - inventory_routing_engine、inventory_source_repository、 + onhand_routing_engine、onhand_source_repository、 ShippingOrderCandidate / ShippingOrderProcessingUnit / ShippingOrderProcessingRun、 - ShippingInventorySource、process_gate_contract(原因唯一归属)。 + FreightRpaSource、process_gate_contract(原因唯一归属)。 逻辑:由 Draft 校验与确认建单调用;多候选不阻断;零候选或强制人工复核不阻断正式 OT 创建(库存路由属可人工修正事实,行级仍记录 block_reason 供自动建单/复核门禁消费); 人工已选候选(含原因)可覆盖规则零候选且优先于自动建议;规则原始候选与当前有效候选分离; 停用 / Profile 未启用 / 无已发布解析 Profile / Excel 模板未发布的 Source 不进入有效候选, @@ -20,7 +20,7 @@ from __future__ import annotations from typing import Any -from app.models import ShippingInventorySource +from app.models import FreightRpaSource from app.services.shipping_notice.candidate_qualification_contract import ( CANDIDATE_QUALIFICATION_GATE_KEYS, CANDIDATE_QUALIFICATION_GATE_REASON_CODES, @@ -30,11 +30,11 @@ from app.services.shipping_notice.candidate_qualification_service import ( ) from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary from app.services.shipping_notice.error_explainability_contract import build_explainability_reason -from app.services.shipping_notice.inventory_routing_engine import ( +from app.services.shipping_notice.onhand_routing_engine import ( InventoryRoutingResult, evaluate_inventory_source_rules_for_field_values, ) -from app.services.shipping_notice.inventory_source_repository import ( +from app.services.shipping_notice.onhand_source_repository import ( get_database_inventory_source, list_database_inventory_sources, ) @@ -175,7 +175,7 @@ def classify_inventory_source_codes(codes: list[str]) -> dict[str, Any]: reasons: dict[str, str] = {} for code in _normalize_manual_codes(codes): # [STEP 1] 源不存在 - source = ShippingInventorySource.query.filter_by(source_code=code).first() + source = FreightRpaSource.query.filter_by(source_code=code).first() if source is None: unavailable.append(code) reasons[code] = 'source_not_found' @@ -197,8 +197,9 @@ def classify_inventory_source_codes(codes: list[str]) -> dict[str, Any]: unavailable.append(code) reasons[code] = 'source_runtime_unavailable' continue - # [STEP 5] 解析 Profile 未发布 - parsing = source.parsing_profile + # [STEP 5] 解析 Profile 未发布(s18 起绑定归 onhand_report_config 配置行;配置行缺失即未绑定) + config = source.onhand_report_config + parsing = config.parsing_profile if config is not None else None if parsing is None or str(getattr(parsing, 'status', '') or '') != 'published': unavailable.append(code) reasons[code] = 'parsing_profile_unavailable' @@ -539,7 +540,7 @@ def assess_order_build_eligibility( 'draft_line_id': meta.get('draft_line_id'), 'line_index': index, 'severity': 'blocking', - 'owning_gate_code': 'inventory_source_routing', + 'owning_gate_code': 'onhand_source_routing', 'candidate_inventory_source_codes': routing.get('candidate_inventory_source_codes') or [], 'unavailable_source_codes': routing.get('unavailable_source_codes') or [], 'unavailable_reasons': routing.get('unavailable_reasons') or {}, @@ -578,7 +579,7 @@ def assess_order_build_eligibility( # 库存源路由属于通知准备阶段可人工修正的事实,不阻断正式 OT 创建。 build_blocking_issues = [ item for item in issues - if str(item.get('owning_gate_code') or '') != 'inventory_source_routing' + if str(item.get('owning_gate_code') or '') != 'onhand_source_routing' ] can_build = ( bool(customer_resolved) diff --git a/backend/app/services/shipping_notice/order_candidate_builder.py b/backend/app/services/shipping_notice/order_candidate_builder.py index 2f314362..e51bcbc3 100644 --- a/backend/app/services/shipping_notice/order_candidate_builder.py +++ b/backend/app/services/shipping_notice/order_candidate_builder.py @@ -12,7 +12,7 @@ import re from decimal import Decimal, InvalidOperation from typing import Any -from app.services.shipping_notice.inventory_snapshot import _rows_from_table_text +from app.services.shipping_notice.onhand_snapshot import _rows_from_table_text from app.services.shipping_notice.notice_line_table import ( find_notice_header_row_index, parse_notice_row, diff --git a/backend/app/services/shipping_notice/order_review_confirmation_service.py b/backend/app/services/shipping_notice/order_review_confirmation_service.py index 9b57481f..d73c2852 100644 --- a/backend/app/services/shipping_notice/order_review_confirmation_service.py +++ b/backend/app/services/shipping_notice/order_review_confirmation_service.py @@ -16,7 +16,7 @@ backend/app/services/shipping_notice/order_review_confirmation_service.py 豁免精确文件哈希重复检查;波次行写入不可变 wave_lines 唯一约束; 新建 Task 完成客户绑定后立即冻结订单快照;冻结失败时整笔确认回滚,禁止把无快照 Task 推入库存/RPA。库存源候选的裁决/冻结不在确认流程内,由确认后 OT 进入的 - 正式 inventory_source_routing Gate 负责; + 正式 onhand_source_routing Gate 负责; 成功确认镜像 review_confirmed 到订单抽取进度流;校验 WorkflowItem 当前版本后推进至 building_order(不关闭);同步 Process Execution 推进至 task_creation 通过, 避免重复冻结资格阻断;与确认同事务入队 shipping_notice_run(待推进 Outbox), @@ -1440,7 +1440,7 @@ def _task_needs_post_confirm_auto_progress(task: ShippingOrderTask | None) -> bo upload_status = getattr(latest_upload_attempt(task), 'status', None) # 仅已定义且已持久化的业务事实才能阻止自动推进。禁止把 ORM mock、关系代理等 # 任意 Python 真值误判为已进入后续阶段,避免 confirmed OT 停在 created。 - from app.services.shipping_notice.inventory_file_store import ( + from app.services.shipping_notice.onhand_file_store import ( current_inventory_matches_for_task, has_ready_inventory_file_for_task, ) diff --git a/backend/app/services/shipping_notice/order_review_draft_service.py b/backend/app/services/shipping_notice/order_review_draft_service.py index 8ad0f96f..43eb9bb5 100644 --- a/backend/app/services/shipping_notice/order_review_draft_service.py +++ b/backend/app/services/shipping_notice/order_review_draft_service.py @@ -656,7 +656,7 @@ def _validation( # 否则"仅库存源未定"的订单会再次被判 needs_review,与"确认只确认订单信息"冲突。 can_build = bool(eligibility.get('can_build')) and not any( str(item.get('severity') or '') == 'blocking' - and str(item.get('owning_gate_code') or '') != 'inventory_source_routing' + and str(item.get('owning_gate_code') or '') != 'onhand_source_routing' for item in issues ) # [STEP 2] 为缺失/无效字段补齐 field_code + display_name,禁止只返回裸 code。 @@ -1574,7 +1574,7 @@ def _sync_review_gates_safe( details=sync_details, ) - inventory_issues = _blocking_issues_for_gate(result, 'inventory_source_routing') + inventory_issues = _blocking_issues_for_gate(result, 'onhand_source_routing') if not inventory_issues: # 复核草稿阶段只能评估路由结果,正式 CandidateSet 需绑定确认后的 Task; # 因此不得在 draft_validated 时提前通过正式 inventory_source_routing Gate。 diff --git a/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py b/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py index d8a18cdc..f0cdd258 100644 --- a/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py +++ b/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py @@ -4,7 +4,7 @@ services/shipping_notice/order_review_fulfillment_decision_service.py 用途:行级履约决定(等待补货 / 完整行先行 / 关闭 / 重开)与履约波次投影。 依赖:ShippingOrderReviewLineDecision、order_review_confirmation_service、 order_review_draft_service、order_review_workbench_projection、 - line_inventory_match_projection(OT 行匹配事实)、fulfillment_audit、 + line_onhand_match_projection(OT 行匹配事实)、fulfillment_audit、 order_review_resume_service。 逻辑:禁止拆分数量;活动决定版本化;投影叠加 inventory_status/match_result/allowed_actions; 订单级聚合计数供侧栏主卡;OT 后波次由确认服务统一创建;履约「料号」= @@ -20,17 +20,17 @@ from typing import Any from app import db from app.core.errors import ConflictError, NotFoundError, ValidationError from app.models import ( - ShippingInventoryField, - ShippingInventoryFile, - ShippingInventorySource, + FreightRpaOnhandField, + FreightRpaOnhandReportFile, + FreightRpaSource, ShippingOrderReviewCase, ShippingOrderReviewLineDecision, ShippingOrderReviewWaveLine, ShippingNotice, ShippingOrderTask, - ShippingTaskInventoryRpaAttempt, + FreightRpaOnhandTaskAttempt, ) -from app.services.shipping_notice.line_inventory_match_persistence import ( +from app.services.shipping_notice.line_onhand_match_persistence import ( resolve_review_case_for_task, ) from app.services.shipping_notice.workflow_ledger_service import ( @@ -44,13 +44,13 @@ def _get_soft_loader(): return soft_load_review_case_for_audit -DECISION_WAIT = 'wait_inventory' +DECISION_WAIT = 'wait_onhand' DECISION_FULFILL = 'fulfill_complete_line_now' DECISION_CLOSE = 'close_unfulfillable' DECISION_REOPEN = 'reopen' DECISION_USE_NEW_FILE = 'use_new_inventory_file' DECISION_CHANGE_SOURCE = 'change_inventory_source' -DECISION_RELEASE_SHORTAGE = 'release_inventory_shortage' +DECISION_RELEASE_SHORTAGE = 'release_onhand_shortage' ALLOWED_DECISIONS = frozenset({ DECISION_WAIT, @@ -171,7 +171,7 @@ def _release_template_inventory_fields( 'field_id': field_id, 'display_name': field_labels.get(field_id) or f'库存字段(编号 {field_id})', 'value': value, - 'value_source': 'inventory_snapshot' if value is not None else 'manual_required', + 'value_source': 'onhand_snapshot' if value is not None else 'manual_required', 'requires_manual': value is None, }) return fields @@ -278,7 +278,7 @@ def _is_shortage_match_fact(fact: Any) -> bool: def _has_terminal_inventory_rpa_failure( task: ShippingNotice, *, - attempts: list[ShippingTaskInventoryRpaAttempt] | None = None, + attempts: list[FreightRpaOnhandTaskAttempt] | None = None, ) -> bool: """仅在已投递的库存 RPA 全部终态失败且无活动 Attempt 时允许无快照人工放行。""" task_no = str(getattr(task, 'task_no', '') or '').strip() @@ -286,20 +286,20 @@ def _has_terminal_inventory_rpa_failure( return False source_codes: set[str] = set() try: - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes - source_codes = {str(item or '').strip().upper() for item in task_frozen_inventory_source_codes(task)} + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes + source_codes = {str(item or '').strip().upper() for item in task_frozen_onhand_source_codes(task)} except Exception: # noqa: BLE001 - 放行资格宁可拒绝,不能因冻结读取异常绕过。 source_codes = set() rows = attempts if attempts is not None else ( - ShippingTaskInventoryRpaAttempt.query + FreightRpaOnhandTaskAttempt.query .filter_by(task_no=task_no) - .order_by(ShippingTaskInventoryRpaAttempt.attempt_no.desc(), ShippingTaskInventoryRpaAttempt.id.desc()) + .order_by(FreightRpaOnhandTaskAttempt.attempt_no.desc(), FreightRpaOnhandTaskAttempt.id.desc()) .all() ) relevant = [row for row in rows if not source_codes or str(getattr(row, 'source_code', '') or '').strip().upper() in source_codes] if not relevant or any(str(getattr(row, 'status', '') or '').lower() in {'queued', 'running'} for row in relevant): return False - latest_by_source: dict[str, ShippingTaskInventoryRpaAttempt] = {} + latest_by_source: dict[str, FreightRpaOnhandTaskAttempt] = {} for row in relevant: code = str(getattr(row, 'source_code', '') or '').strip().upper() if code and code not in latest_by_source: @@ -314,6 +314,61 @@ def _has_terminal_inventory_rpa_failure( ) +def _line_hit_odm_multiple( + *, + onhand_snapshot_id: Any, + reservation_id: Any, + part_number: Any, +) -> bool: + """判断预约+料号命中库存行(0 命中时回退料号命中行)的 ODM ID 是否多值。 + + 核心逻辑:自动放行以「放行后 Excel 可生成」为前提;导出侧 ODM 裁决只在命中 + ODM 唯一时免白名单收敛(2026-10-20 降级规则),多值时放行必然导致生成失败, + 因此多值行保持人工路径。ODM 字段目录未启用、快照不可读或命中行无 ODM 值时 + 不设前置(返回 False,维持既有放行行为,避免误伤无 ODM 语义的客户/模板)。 + """ + from app.models import FreightRpaOnhandField, FreightRpaOnhandReportFile + from app.services.shipping_notice.onhand_file_store import read_inventory_file_lines + + odm_field = FreightRpaOnhandField.query.filter_by(field_code='odm_id', status='active').first() + if odm_field is None: + return False + snapshot = ( + db.session.get(FreightRpaOnhandReportFile, int(onhand_snapshot_id)) + if onhand_snapshot_id else None + ) + if snapshot is None: + return False + try: + lines, _meta = read_inventory_file_lines(snapshot) + except (OSError, ValueError, AppError): + return False + part_field = FreightRpaOnhandField.query.filter_by(field_code='part_number').first() + reservation_field = FreightRpaOnhandField.query.filter_by(field_code='reservation_id').first() + part = str(part_number or '').strip().upper() + reservation = str(reservation_id or '').strip() + part_key = str(part_field.id) if part_field is not None else 'part_number' + reservation_key = str(reservation_field.id) if reservation_field is not None else 'reservation_id' + odm_key = str(odm_field.id) + + def _hits(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: + return [ + row for row in rows + if part and str(row.get(part_key) or '').strip().upper() == part + and (not reservation or str(row.get(reservation_key) or '').strip() == reservation) + ] + + hits = _hits(lines) or [ + row for row in lines + if part and str(row.get(part_key) or '').strip().upper() == part + ] + odm_values = {str(row.get(odm_key) or '').strip() for row in hits} - {''} + import os as _os + if _os.environ.get('ODM_DEBUG'): + print('ODM_DEBUG hits=%d values=%r part=%r resv=%r snap=%r' % (len(hits), odm_values, part, reservation, onhand_snapshot_id)) + return len(odm_values) > 1 + + def _shortage_release_required_fields( *, task: ShippingNotice, @@ -325,7 +380,7 @@ def _shortage_release_required_fields( Returns: (fields, evidence_scope) 元组:fields 为模板库存字段投影(快照唯一值只读, - 其余 requires_manual);evidence_scope ∈ {'inventory_snapshot', 'part_fallback'}, + 其余 requires_manual);evidence_scope ∈ {'onhand_snapshot', 'part_fallback'}, 'part_fallback' 表示预约键在库存快照 0 行命中、已按料号键重筛带出(审计口径)。 """ if line_index is None: @@ -333,20 +388,20 @@ def _shortage_release_required_fields( 'Current line inventory evidence is unavailable', code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED', ) - snapshot = db.session.get(ShippingInventoryFile, int(inventory_snapshot_id)) if inventory_snapshot_id is not None else None + snapshot = db.session.get(FreightRpaOnhandReportFile, int(inventory_snapshot_id)) if inventory_snapshot_id is not None else None if inventory_snapshot_id is not None and snapshot is None: raise ConflictError( 'Current inventory snapshot is unavailable', code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED', ) - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes resolved_source_code = _resolve_shortage_release_inventory_source( fact_source_code=inventory_source_code, snapshot_source_code=getattr(snapshot, 'source_code', None) if snapshot is not None else None, candidate_source_codes={ str(code or '').strip().upper() - for code in task_frozen_inventory_source_codes(task) + for code in task_frozen_onhand_source_codes(task) if str(code or '').strip() }, ) @@ -355,7 +410,7 @@ def _shortage_release_required_fields( 'Current line inventory evidence is unavailable', code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED', ) - source = ShippingInventorySource.query.filter_by( + source = FreightRpaSource.query.filter_by( source_code=resolved_source_code, enabled=True, ).first() template = getattr(source, 'excel_template', None) if source is not None else None @@ -379,9 +434,9 @@ def _shortage_release_required_fields( and item.get('source_kind') == 'inventory_field' and str(item.get('source_key') or '').strip().isdigit() } - labels = {str(row.id): str(row.display_name or '').strip() for row in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all()} if field_ids else {} + labels = {str(row.id): str(row.display_name or '').strip() for row in FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(field_ids)).all()} if field_ids else {} # 无快照即无库存证据:全部模板库存字段人工补录,证据范围维持快照口径。 - return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels), 'inventory_snapshot' + return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels), 'onhand_snapshot' definition = profile.definition_json if isinstance(profile.definition_json, dict) else {} match_keys = definition.get('match_keys') if isinstance(definition.get('match_keys'), list) else [] expected = [ @@ -393,7 +448,7 @@ def _shortage_release_required_fields( 'Inventory matching keys are unavailable', code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED', ) - from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines + from app.services.shipping_notice.onhand_file_store import read_inventory_file_lines try: inventory_lines, _column_meta = read_inventory_file_lines(snapshot) except (OSError, ValueError, AppError) as exc: @@ -405,7 +460,7 @@ def _shortage_release_required_fields( dict(row) for row in inventory_lines if all(_match_text(row.get(inventory_field)) == value for inventory_field, value in expected) ] - evidence_scope = 'inventory_snapshot' + evidence_scope = 'onhand_snapshot' if not candidates: # [STEP] 料号兜底(2026-10 需求):预约键在库存快照 0 行命中时,按料号键重筛证据行, # 能唯一取值的字段不再要求人工手填。仅识别 field_code='part_number' 的匹配键; @@ -413,7 +468,7 @@ def _shortage_release_required_fields( part_field_ids = { int(field_id) for field_id, _value in expected if str(field_id).strip().isdigit() - and str(getattr(db.session.get(ShippingInventoryField, int(field_id)), 'field_code', '') or '') == 'part_number' + and str(getattr(db.session.get(FreightRpaOnhandField, int(field_id)), 'field_code', '') or '') == 'part_number' } if part_field_ids: candidates = [ @@ -433,7 +488,7 @@ def _shortage_release_required_fields( } labels = { str(row.id): str(row.display_name or '').strip() - for row in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all() + for row in FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(field_ids)).all() } if field_ids else {} return _release_template_inventory_fields( mappings=mappings, @@ -481,7 +536,7 @@ def _sync_confirmed_task_fulfillment_gates( # 出现"Excel 已生成但任务仍显示库存不足/缺货"的矛盾。仅当任务确有匹配行事实时重算, # 空事实任务不得被误标为缺货。 if getattr(task, 'id', None) is not None: - from app.models import ShippingNoticeLineInventoryMatch as _MatchRow + from app.models import ShippingNoticeLineOnhandMatch as _MatchRow has_match_rows = ( _MatchRow.query.filter_by(task_id=int(task.id), is_current=True).first() is not None @@ -592,11 +647,11 @@ def _assess_line_fulfill_complete( return False, 'SHIPPING.REVIEW_LINE_RESERVATION_REQUIRED', req, avail block_reason = str(proj.get('block_reason') or '').lower() if 'shortage' in block_reason or 'insufficient' in block_reason: - return False, 'SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY', req, avail + return False, 'SHIPPING.REVIEW_LINE_INSUFFICIENT_ONHAND', req, avail if avail is None: - return False, 'SHIPPING.REVIEW_LINE_INVENTORY_UNKNOWN', req, None + return False, 'SHIPPING.REVIEW_LINE_ONHAND_UNKNOWN', req, None if avail < req: - return False, 'SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY', req, avail + return False, 'SHIPPING.REVIEW_LINE_INSUFFICIENT_ONHAND', req, avail return True, None, req, avail @@ -621,7 +676,7 @@ def _assert_line_can_fulfill_complete( if not ok or req is None or avail is None: raise ConflictError( 'Line cannot fulfill complete quantity with current inventory', - code=str(code or 'SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY'), + code=str(code or 'SHIPPING.REVIEW_LINE_INSUFFICIENT_ONHAND'), details={'draft_line_id': draft_line_id}, ) return req, avail @@ -791,13 +846,13 @@ def project_review_case_line_decisions( Args: case: 复核 Case。 schema_fields: 可选;优先使用 serialize_review_case 已解析的字段列表。 - inventory_rpa_running: 库存 RPA 是否执行中(禁止重复获取动作)。 + onhand_rpa_running: 库存 RPA 是否执行中(禁止重复获取动作)。 source_labels: code→显示名映射。 Returns: lines(含 inventory_source / 分域 actions)与聚合计数。 """ - from app.services.shipping_notice.line_inventory_match_projection import ( + from app.services.shipping_notice.line_onhand_match_projection import ( line_auto_fulfill_enabled, project_line_inventory_view, ) @@ -816,13 +871,13 @@ def project_review_case_line_decisions( task = db.session.get(ShippingOrderTask, int(case.confirmed_task_id)) rpa_failure_release_allowed = bool(task is not None and _has_terminal_inventory_rpa_failure(task)) # [STEP] 构造 CandidateSet 回退事实(行级匹配缺失时仅影响展示)。 - from app.services.shipping_notice.stp_inventory_freeze import ( - task_frozen_inventory_source_codes, + from app.services.shipping_notice.stp_onhand_freeze import ( + task_frozen_onhand_source_codes, ) fallback_inventory_source: dict[str, Any] | None = None if task is not None: - frozen_codes = task_frozen_inventory_source_codes(task) + frozen_codes = task_frozen_onhand_source_codes(task) if len(frozen_codes) == 1: fallback_inventory_source = { 'code': frozen_codes[0], @@ -846,7 +901,7 @@ def project_review_case_line_decisions( 'source': 'inventory_source_clue', } # [BE-键修复] Case 草稿行只有 _line_index;补一条按行号索引的事实通道。 - from app.services.shipping_notice.line_inventory_match_projection import ( + from app.services.shipping_notice.line_onhand_match_projection import ( load_current_match_facts_by_line_index, ) match_facts_by_line = load_current_match_facts_by_line_index(formal_ot.get('task_id')) @@ -1058,7 +1113,7 @@ def build_inventory_issue_fallback( Case 级库存兜底:仅无有效行投影且库存系统失败时返回。 核心逻辑:有行投影→None;系统等待/RPA 运行中→None;失败时最多下发 - retry_inventory_preparation。 + retry_onhand_preparation。 Returns: fallback 字典或 None。 @@ -1088,8 +1143,8 @@ def build_inventory_issue_fallback( 'inventory_file_missing', 'inventory_source_unavailable', 'inventory_preparation_failed', - 'inventory_rpa_timeout', - 'inventory_rpa_export_failed', + 'onhand_rpa_timeout', + 'onhand_rpa_export_failed', 'inventory_file_empty', } if auto_status not in {'failed', 'error'} and reason not in failed_reasons: @@ -1101,7 +1156,7 @@ def build_inventory_issue_fallback( 'reason_label_key': kind, 'affected_line_count': 0, 'file_count': 0, - 'allowed_actions': ['retry_inventory_preparation'], + 'allowed_actions': ['retry_onhand_preparation'], } @@ -1122,7 +1177,7 @@ def _apply_shortage_line_release( 版本化落库、同步正式 OT 门禁并写审计。 核心逻辑:从 decide_review_line_fulfillment 放行分支原样提取(行为不变)。 - 证据字段按行事实快照解析(预约键命中 → inventory_snapshot;预约键 0 行命中 + 证据字段按行事实快照解析(预约键命中 → onhand_snapshot;预约键 0 行命中 按料号键重筛 → part_fallback);落库快照 release_field_values 为「自动带出 + 人工补录」全量字段值字典(导出覆盖唯一来源);落库后立即重算任务履约态并 同步门禁/自动履约入队,与人工放行完全一致。终态/已决定行必须由调用方先跳过, @@ -1161,10 +1216,10 @@ def _apply_shortage_line_release( raise ConflictError('Review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND') key, draft_line = pair - from app.models import ShippingNoticeLineInventoryMatch + from app.models import ShippingNoticeLineOnhandMatch fact = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=int(task.id), line_index=int(line_index), is_current=True) .first() if getattr(task, 'id', None) is not None else None @@ -1173,10 +1228,10 @@ def _apply_shortage_line_release( release_template_fields, resolved_scope = _shortage_release_required_fields( task=task, line_index=release_line_index, - inventory_snapshot_id=getattr(fact, 'inventory_snapshot_id', None) if fact is not None else None, - inventory_source_code=getattr(fact, 'inventory_source_code', None) if fact is not None else None, + inventory_snapshot_id=getattr(fact, 'onhand_snapshot_id', None) if fact is not None else None, + inventory_source_code=getattr(fact, 'source_code', None) if fact is not None else None, ) - release_evidence_scope = str(evidence_scope or resolved_scope or 'inventory_snapshot') + release_evidence_scope = str(evidence_scope or resolved_scope or 'onhand_snapshot') release_required_fields = _manual_required_release_fields(release_template_fields) release_values = _validate_inventory_shortage_release_fields( required_fields=release_required_fields, @@ -1241,7 +1296,7 @@ def _apply_shortage_line_release( 'draft_line_id': key, 'release_field_values': release_values, 'release_required_fields': release_required_fields, - # 审计口径:放行证据来自预约匹配快照(inventory_snapshot)还是料号兜底重筛(part_fallback)。 + # 审计口径:放行证据来自预约匹配快照(onhand_snapshot)还是料号兜底重筛(part_fallback)。 'release_evidence_scope': release_evidence_scope, **({'auto_release': True} if auto_release else {}), }, @@ -1300,7 +1355,7 @@ def decide_review_line_fulfillment( 核心逻辑:停用旧活动决定;task_created/fulfilled 不可逆; reopen 仅 closed_unfulfillable 且管理员;fulfill 强制最新库存充足; - release_inventory_shortage 必须留下原因、模板库存补录字段且仅能用于当前库存不足行。 + release_onhand_shortage 必须留下原因、模板库存补录字段且仅能用于当前库存不足行。 Args: user_id: 操作人。 @@ -1310,7 +1365,7 @@ def decide_review_line_fulfillment( reason: 关闭/重开必填原因;短缺放行可选(人工放行事实由审计链记录)。 release_field_values: 短缺放行时模板行级库存字段的人工补录值;落库快照 release_field_values 为「自动带出 + 人工补录」全量字段值字典(导出覆盖唯一来源), - release_evidence_scope 记录证据范围(inventory_snapshot / part_fallback)。 + release_evidence_scope 记录证据范围(onhand_snapshot / part_fallback)。 expected_draft_version: 可选草稿乐观锁。 actor_is_admin: 是否管理员(重开授权)。 @@ -1392,12 +1447,12 @@ def decide_review_line_fulfillment( schema_fields=schema_fields, ) if code == DECISION_RELEASE_SHORTAGE: - from app.models import ShippingNoticeLineInventoryMatch + from app.models import ShippingNoticeLineOnhandMatch task_id = getattr(case, 'confirmed_task_id', None) task = db.session.get(ShippingOrderTask, int(task_id)) if task_id is not None else None fact = ( - ShippingNoticeLineInventoryMatch.query + ShippingNoticeLineOnhandMatch.query .filter_by(task_id=int(task.id), line_index=int(draft_line.get('_line_index')), is_current=True) .first() if task is not None else None @@ -1557,11 +1612,13 @@ def auto_release_part_fallback_shortages( """ 匹配落库后按料号兜底自动放行缺口行(用户确认语义:满足即自动放行,非仅可放行)。 - 核心逻辑:仅处理「ready + 缺口 + 料号总量≥需求 + 无活动决定 + 证据字段全部可 - 自动取值」的行;任一条件不满足(含证据解析 ConflictError)一律跳过并保持人工 - 路径,fail-closed 不变。复用 _apply_shortage_line_release,审计/门禁同步/自动 - 履约入队与人工放行完全一致;幂等由「无活动决定的行才处理」保证,不自动撤销 - 既有放行。注意:行匹配事实以 snapshot_line_id 为键,行号取自 fact['line_index']。 + 核心逻辑:仅处理「ready + 缺口 + 料号总量≥需求 + 命中行 ODM 唯一 + 无活动决定 + + 证据字段全部可自动取值」的行;任一条件不满足(含证据解析 ConflictError)一律 + 跳过并保持人工路径,fail-closed 不变。ODM 唯一前置保证放行后导出可收敛(唯一 + ODM 免白名单,2026-10-20 需求)。复用 _apply_shortage_line_release,审计/门禁 + 同步/自动履约入队与人工放行完全一致;幂等由「无活动决定的行才处理」保证,不 + 自动撤销既有放行。注意:行匹配事实以 snapshot_line_id 为键,行号取自 + fact['line_index']。 Args: task: 正式任务聚合根(OT 或正式 Notice,须含 id 与 order_snapshot_id)。 @@ -1570,7 +1627,7 @@ def auto_release_part_fallback_shortages( Returns: 自动放行的 line_index 列表(按行号升序)。 """ - from app.services.shipping_notice.line_inventory_match_projection import ( + from app.services.shipping_notice.line_onhand_match_projection import ( load_current_match_facts_by_task, ) @@ -1598,6 +1655,14 @@ def auto_release_part_fallback_shortages( if required is None or part_total is None or part_total < required: # 料号兜底量缺失或不足 → 维持人工待处置(不得任取部分数量放行)。 continue + if _line_hit_odm_multiple( + onhand_snapshot_id=fact.get('inventory_snapshot_id'), + reservation_id=fact.get('reservation_id'), + part_number=fact.get('part_number'), + ): + # 命中行 ODM 多值:导出侧无法唯一收敛(多值时白名单未必可救), + # 放行后 Excel 仍会失败,保持人工路径(2026-10-20 需求)。 + continue fields, evidence_scope = _shortage_release_required_fields( task=task, line_index=line_index, diff --git a/backend/app/services/shipping_notice/order_review_projection.py b/backend/app/services/shipping_notice/order_review_projection.py index c4a330df..df594d5e 100644 --- a/backend/app/services/shipping_notice/order_review_projection.py +++ b/backend/app/services/shipping_notice/order_review_projection.py @@ -60,7 +60,7 @@ from app.models import ( ShippingProcessGate, ShippingProcessGateAttempt, ) -from app.services.shipping_notice.line_inventory_match_projection import ( +from app.services.shipping_notice.line_onhand_match_projection import ( inventory_rpa_is_running as _inventory_rpa_is_running, ) diff --git a/backend/app/services/shipping_notice/order_review_workbench_projection.py b/backend/app/services/shipping_notice/order_review_workbench_projection.py index a0506d34..5a7da034 100644 --- a/backend/app/services/shipping_notice/order_review_workbench_projection.py +++ b/backend/app/services/shipping_notice/order_review_workbench_projection.py @@ -70,16 +70,16 @@ _PRE_OT_BLOCKING_GATE_CODES: frozenset[str] = frozenset({ # Worker 等待类库存准备:即使存在 Gate 行,也不得投影为人工待办。 _SYSTEM_WAIT_INVENTORY_GATES: frozenset[str] = frozenset({ - 'inventory_preparation', + 'onhand_preparation', }) # 库存/履约域(正式 OT 后允许在 owner_type=human 时成为当前阻断)。 _POST_OT_INVENTORY_FULFILLMENT_GATES: frozenset[str] = frozenset({ - 'inventory_source_routing', + 'onhand_source_routing', 'reservation_validation', - 'inventory_field_mapping', - 'inventory_matching', - 'inventory_sufficiency', + 'onhand_field_mapping', + 'onhand_matching', + 'onhand_sufficiency', 'line_fulfillment', 'shortage_review', 'fulfillment_decision', @@ -486,7 +486,7 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str from app.services.shipping_notice.upload_attempt_service import latest_export_artifact export_file_path = getattr(latest_export_artifact(task), 'file_path', None) if isinstance(task, ShippingOrderTask): - from app.services.shipping_notice.inventory_file_store import ( + from app.services.shipping_notice.onhand_file_store import ( current_inventory_matches_for_task, has_ready_inventory_file_for_task, ) @@ -494,8 +494,8 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str has_match = bool(current_inventory_matches_for_task(task)) has_inventory = has_ready_inventory_file_for_task(task) else: - from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task match_status = aggregate_match_status_for_task(getattr(task, 'order_task_id', None) or getattr(task, 'id', None)) has_match = bool(match_status) has_inventory = has_ready_inventory_file_for_task(task) @@ -690,7 +690,7 @@ def project_stage_for_task( from app.services.shipping_notice.processing_projection_invariants import ( map_notice_to_processing_status_stage, ) - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task from app.services.shipping_notice.upload_attempt_service import ( has_verified_upload_success, @@ -704,12 +704,12 @@ def project_stage_for_task( owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task verified_upload_success = has_verified_upload_success(task) if isinstance(owner, ShippingOrderTask): - from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task match_facts = list(load_current_match_facts_by_task(getattr(owner, 'id', None)).values()) has_task_match = bool(match_facts) else: - from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task has_task_match = bool(aggregate_match_status_for_task(getattr(task, 'order_task_id', None) or getattr(task, 'id', None))) progress_state = ( 'uploaded' if verified_upload_success @@ -758,13 +758,13 @@ def project_stage_for_task( # Notice 已到 waiting_inventory/parsed 时跟 notice 映射;仍为 created 时推进到 inventory_fetching。 if ot_stage == 'order_creating': if progress_state in {'inventory_ready'}: - return _with_label('inventory_fetching', source='notice_inventory') + return _with_label('onhand_fetching', source='notice_inventory') if progress_state in {'matched', 'export_ready'}: _status, mapped = map_notice_to_processing_status_stage(task) - code = str(mapped or 'inventory_matching').strip() or 'inventory_matching' + code = str(mapped or 'onhand_matching').strip() or 'onhand_matching' return _with_label(code, source='notice_map') if progress_state in {None, '', 'not_started'}: - return _with_label('inventory_fetching', source='post_ot_inventory') + return _with_label('onhand_fetching', source='post_ot_inventory') return _with_label(ot_stage, source='order_task') # [STEP 2] Notice 尚无履约领域事实:统一 order_creating。 diff --git a/backend/app/services/shipping_notice/order_task_stage_machine.py b/backend/app/services/shipping_notice/order_task_stage_machine.py index ebbbb93e..02ab7245 100644 --- a/backend/app/services/shipping_notice/order_task_stage_machine.py +++ b/backend/app/services/shipping_notice/order_task_stage_machine.py @@ -65,11 +65,11 @@ _PROGRESS_EVENT_TO_PROCESSING_STAGE: dict[str, str] = { # 正式 Process Gate 的库存履约阶段 → 统一 15 阶投影阶段。 # Gate 码不是 15 阶成员,必须在写路径转换后再回写 OT,避免已建单任务残留建单前 stage。 _PROCESS_GATE_TO_PROCESSING_STAGE: dict[str, str] = { - 'inventory_source_routing': 'inventory_source_resolving', - 'inventory_preparation': 'inventory_fetching', - 'inventory_field_mapping': 'inventory_fetching', - 'inventory_matching': 'inventory_matching', - 'inventory_sufficiency': 'inventory_matching', + 'onhand_source_routing': 'onhand_source_resolving', + 'onhand_preparation': 'onhand_fetching', + 'onhand_field_mapping': 'onhand_fetching', + 'onhand_matching': 'onhand_matching', + 'onhand_sufficiency': 'onhand_matching', 'excel_readiness': 'excel_generating', 'artifact_generation': 'excel_generating', 'freight_upload_rpa': 'freight_uploading', @@ -220,7 +220,7 @@ def resolve_pre_confirm_stage( 根据 Candidate 资格评估结果解析确认建单前的 OT (stage, status)。 核心逻辑:客户未确认 → customer_resolving;查重未清 → duplicate_checking; - 库存源阻断 → inventory_source_resolving;否则 waiting_review。 + 库存源阻断 → onhand_source_resolving;否则 waiting_review。 prefer_waiting_review 仅在无阻断时抬升到 waiting_review,不得覆盖前置业务阻断。 Args: @@ -258,7 +258,7 @@ def resolve_pre_confirm_stage( return 'duplicate_checking', 'waiting_review' if any('inventory' in code for code in blocking): - return 'inventory_source_resolving', 'waiting_review' + return 'onhand_source_resolving', 'waiting_review' # [BE-02] prefer_waiting_review 不得跳过客户/查重/库存源阻断;无阻断时才落到复核。 return 'waiting_review', 'waiting_review' @@ -373,7 +373,7 @@ def sync_order_task_stage_for_notice( stage = gate_stage status = 'blocked' if stage not in SHIPPING_PROCESSING_STAGES: - stage = 'inventory_matching' + stage = 'onhand_matching' return sync_order_task_processing_state( ot, stage=stage, diff --git a/backend/app/services/shipping_notice/per_source_rpa_service.py b/backend/app/services/shipping_notice/per_source_rpa_service.py index 78d35e2f..fda20a23 100644 --- a/backend/app/services/shipping_notice/per_source_rpa_service.py +++ b/backend/app/services/shipping_notice/per_source_rpa_service.py @@ -2,10 +2,10 @@ services/shipping_notice/per_source_rpa_service.py 用途:逐 (task_no, source_code) 维度的库存 RPA Attempt 结构化管理(决策 D1/D2/D3)。 -依赖:models.ShippingTaskInventoryRpaAttempt、inventory_candidate_freeze_service(取候选源)、 +依赖:models.FreightRpaOnhandTaskAttempt、onhand_candidate_freeze_service(取候选源)、 rpa.write_inventory_export_batch_trigger(批次 trigger 文件写入,单文件多源)与 rpa.build_on_demand_inventory_trigger_source(逐源条目构造)、 - inventory_snapshot_store(快照复用判断)。 + onhand_snapshot_store(快照复用判断)。 逻辑:T4 新增的结构化表是正式 Attempt 计数真相;旧的 ShippingTaskEvent 统计作为兼容层, 新的调用方(auto_progress Orchestrator、Gate handler、回调入口)逐步迁移到本模块。 三元组 (task_no, source_code, run_no) 幂等定位;迟到回调标记 superseded 不回写业务。 @@ -27,24 +27,25 @@ from sqlalchemy.orm import Session from app import db from app.models import ( - ShippingInventoryFile, + FreightRpaOnhandReportFile, ShippingNotice, - ShippingTaskInventoryRpaAttempt, + FreightRpaOnhandTaskAttempt, ) -from app.services.shipping_notice.stp_inventory_freeze import ( - task_frozen_inventory_source_codes, +from app.services.shipping_notice.stp_onhand_freeze import ( + task_frozen_onhand_source_codes, ) -from app.services.shipping_notice.inventory_snapshot_store import ( +from app.services.shipping_notice.onhand_snapshot_store import ( find_latest_ready_snapshot, is_snapshot_fresh, ) -from app.services.shipping_notice.rpa import ( +from app.services.shipping_notice.onhand_trigger_batch import ( build_on_demand_inventory_trigger_source, write_inventory_export_batch_trigger, ) +from app.services.freight_rpa.onhand.trigger_io import SCHEMA -def _archive_unclaimed_trigger(attempt: ShippingTaskInventoryRpaAttempt) -> str | None: +def _archive_unclaimed_trigger(attempt: FreightRpaOnhandTaskAttempt) -> str | None: """将仍在 trigger 根目录的未领取文件移入 failed;Worker 已领取/移走时安全忽略。""" if str(getattr(attempt, 'status', '') or '') != 'queued': return None @@ -69,7 +70,7 @@ def _archive_unclaimed_trigger(attempt: ShippingTaskInventoryRpaAttempt) -> str def _attempt_ref_has_ready_snapshot( - attempt: ShippingTaskInventoryRpaAttempt, + attempt: FreightRpaOnhandTaskAttempt, *, session: Session | None = None, ) -> bool: @@ -79,12 +80,12 @@ def _attempt_ref_has_ready_snapshot( 被误判为 prepared 而绕过有效库存门禁。 """ sess = session or db.session - file_no = str(getattr(attempt, 'inventory_file_no', '') or '').strip() + file_no = str(getattr(attempt, 'onhand_file_no', '') or '').strip() if not file_no: return False inv_file = ( - sess.query(ShippingInventoryFile) - .filter(ShippingInventoryFile.inventory_file_no == file_no) + sess.query(FreightRpaOnhandReportFile) + .filter(FreightRpaOnhandReportFile.onhand_file_no == file_no) .one_or_none() ) return is_snapshot_fresh(inv_file) @@ -93,13 +94,13 @@ def _attempt_ref_has_ready_snapshot( def _validate_callback_attempt_identity( *, task: ShippingNotice, - attempt: ShippingTaskInventoryRpaAttempt, + attempt: FreightRpaOnhandTaskAttempt, callback_payload: dict[str, Any], ) -> bool: """校验回调身份与已冻结 Attempt/当前 CandidateSet/正式 Execution 一致。""" required = ('schema_version', 'callback_id', 'source_run_no', 'attempt_no', 'lease_token', 'candidate_set_id', 'execution_id', 'gate_id') - if str(callback_payload.get('schema_version') or '') != 'shipping_inventory_rpa.v2': + if str(callback_payload.get('schema_version') or '') != SCHEMA: return False if any(callback_payload.get(key) in (None, '') for key in required): return False @@ -146,7 +147,7 @@ class PerSourcePrepareResult: source_attempts: dict[str, dict[str, Any]] # source_code → {attempt_no, status, run_no, error} -def _per_source_run_no(attempt: ShippingTaskInventoryRpaAttempt) -> str: +def _per_source_run_no(attempt: FreightRpaOnhandTaskAttempt) -> str: """ 构造 per-source 唯一 run_no:PSR-(dumb ID)。 @@ -165,20 +166,20 @@ def _latest_attempt( source_code: str, *, session: Session | None = None, -) -> ShippingTaskInventoryRpaAttempt | None: +) -> FreightRpaOnhandTaskAttempt | None: """查询 (task, source) 维度最新的 Attempt(按 attempt_no desc, id desc)。""" sess = session or db.session return ( - sess.query(ShippingTaskInventoryRpaAttempt) + sess.query(FreightRpaOnhandTaskAttempt) .filter( and_( - ShippingTaskInventoryRpaAttempt.task_no == task_no, - ShippingTaskInventoryRpaAttempt.source_code == source_code, + FreightRpaOnhandTaskAttempt.task_no == task_no, + FreightRpaOnhandTaskAttempt.source_code == source_code, ) ) .order_by( - ShippingTaskInventoryRpaAttempt.attempt_no.desc(), - ShippingTaskInventoryRpaAttempt.id.desc(), + FreightRpaOnhandTaskAttempt.attempt_no.desc(), + FreightRpaOnhandTaskAttempt.id.desc(), ) .first() ) @@ -193,12 +194,12 @@ def _consumed_run_nos( """查询 (task, source) 维度已 consumed/superseded 的 run_no 集合,用于回调幂等/迟到判断。""" sess = session or db.session rows = ( - sess.query(ShippingTaskInventoryRpaAttempt.run_no) + sess.query(FreightRpaOnhandTaskAttempt.run_no) .filter( and_( - ShippingTaskInventoryRpaAttempt.task_no == task_no, - ShippingTaskInventoryRpaAttempt.source_code == source_code, - ShippingTaskInventoryRpaAttempt.status.in_(('consumed', 'superseded')), + FreightRpaOnhandTaskAttempt.task_no == task_no, + FreightRpaOnhandTaskAttempt.source_code == source_code, + FreightRpaOnhandTaskAttempt.status.in_(('consumed', 'superseded')), ) ) .all() @@ -218,25 +219,25 @@ def _next_attempt_no( """ sess = session or db.session last_success = ( - sess.query(ShippingTaskInventoryRpaAttempt) + sess.query(FreightRpaOnhandTaskAttempt) .filter( and_( - ShippingTaskInventoryRpaAttempt.task_no == task_no, - ShippingTaskInventoryRpaAttempt.source_code == source_code, - ShippingTaskInventoryRpaAttempt.status.in_(('succeeded', 'consumed')), + FreightRpaOnhandTaskAttempt.task_no == task_no, + FreightRpaOnhandTaskAttempt.source_code == source_code, + FreightRpaOnhandTaskAttempt.status.in_(('succeeded', 'consumed')), ) ) - .order_by(ShippingTaskInventoryRpaAttempt.attempt_no.desc()) + .order_by(FreightRpaOnhandTaskAttempt.attempt_no.desc()) .first() ) base_no = last_success.attempt_no if last_success else 0 subsequent_count = ( - sess.query(func.count(ShippingTaskInventoryRpaAttempt.id)) + sess.query(func.count(FreightRpaOnhandTaskAttempt.id)) .filter( and_( - ShippingTaskInventoryRpaAttempt.task_no == task_no, - ShippingTaskInventoryRpaAttempt.source_code == source_code, - ShippingTaskInventoryRpaAttempt.attempt_no > base_no, + FreightRpaOnhandTaskAttempt.task_no == task_no, + FreightRpaOnhandTaskAttempt.source_code == source_code, + FreightRpaOnhandTaskAttempt.attempt_no > base_no, ) ) .scalar() @@ -263,7 +264,7 @@ def _snapshot_ready_for_source( snap = find_latest_ready_snapshot(source_code, warehouse_id) except Exception: snap = None - from app.services.shipping_notice.inventory_snapshot_reuse_policy import check_inventory_snapshot_reusable + from app.services.shipping_notice.onhand_snapshot_reuse_policy import check_inventory_snapshot_reusable source_config_version = None if isinstance(rpa_source, dict): source_config_version = rpa_source.get('source_config_version') or rpa_source.get('config_version') @@ -313,7 +314,7 @@ def ensure_all_required_sources_prepared( ) -> PerSourcePrepareResult: """ 遍历 frozen 候选库存源,逐源 check 快照;未命中则触发 RPA(每源独立 attempt_no/run_no)。 - 【AI 触发时机】:inventory_preparation Gate handler、AutoProgress Orchestrator 库存准备阶段调用。 + 【AI 触发时机】:onhand_preparation Gate handler、AutoProgress Orchestrator 库存准备阶段调用。 核心逻辑: [STEP 1] 从 T3 冻结表/兼容 step_payload 读取候选 source_codes(保序)。 @@ -324,10 +325,10 @@ def ensure_all_required_sources_prepared( - succeeded/consumed → 已 prepared - 从未 attempt → 首次触发新 attempt(queued 新 run) - failed/exhausted → 仅用户显式 retry_rpa 才触发下一 Attempt - c. 写 ShippingTaskInventoryRpaAttempt 记录 + trigger 文件 + c. 写 FreightRpaOnhandTaskAttempt 记录 + trigger 文件 Args: - allow_auto_retry: 只读轮询开关。poll_inventory_preparation 等查询路径必须传 False: + allow_auto_retry: 只读轮询开关。poll_onhand_preparation 等查询路径必须传 False: 轮询只消费 Attempt 事实(快照复用/pending/failed 上报),禁止自动新建 Attempt。 无论此开关取值,失败后的重试都只能由用户显式动作(mode='retry_rpa')发起, 避免 RPA Worker 离线时形成“失败→重试→再失败”的无人值守空转环。 @@ -348,7 +349,7 @@ def ensure_all_required_sources_prepared( # SQLite/无事务测试环境不支持行锁时继续走现有幂等约束。 pass source_codes = [ - str(code).strip().upper() for code in (source_codes or task_frozen_inventory_source_codes(task)) + str(code).strip().upper() for code in (source_codes or task_frozen_onhand_source_codes(task)) if str(code).strip() ] if not source_codes: @@ -358,14 +359,14 @@ def ensure_all_required_sources_prepared( failed_source_codes=[], source_attempts={}, ) - from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source prepared: list[str] = [] pending: list[str] = [] failed: list[str] = [] # 本轮待触发源的单源条目与对应 Attempt;循环后合并写入单个批次 trigger。 pending_payloads: list[dict[str, Any]] = [] - pending_attempts: list[ShippingTaskInventoryRpaAttempt] = [] + pending_attempts: list[FreightRpaOnhandTaskAttempt] = [] for source_code in source_codes: rpa_source = get_database_inventory_source(source_code) or {'source_code': source_code} @@ -385,8 +386,8 @@ def ensure_all_required_sources_prepared( # 再次确认 (task_no, source_code) 的最新状态不为 queued/running,避免“双请求同时通过 _latest_attempt, # 都判成 failed → 都创建新 Attempt”的竞态。仍以 DB 部分唯一索引作为最后兜底。 if mode == 'retry_rpa' or current_status in {'failed', 'exhausted'}: - from app.models.shipping_task_inventory_rpa_attempts import ( - ShippingTaskInventoryRpaAttempt as _Attempt2, + from app.models.freight_rpa_onhand_task_attempts import ( + FreightRpaOnhandTaskAttempt as _Attempt2, ) q = ( sess.query(_Attempt2) @@ -432,7 +433,7 @@ def ensure_all_required_sources_prepared( next_att_no = _next_attempt_no(task_no, source_code, session=sess) # [STEP 2c] 新建 Attempt + 写 trigger 文件 - new_att = ShippingTaskInventoryRpaAttempt( + new_att = FreightRpaOnhandTaskAttempt( task_no=task_no, source_code=source_code, attempt_no=next_att_no, @@ -449,7 +450,7 @@ def ensure_all_required_sources_prepared( sess.flush([new_att]) try: - from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source + from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source from app.models import ShippingProcessExecution, ShippingProcessGate legacy_rpa_source = task_rpa_inventory_source(task) or dict(rpa_source) @@ -521,7 +522,7 @@ def ensure_all_required_sources_prepared( batch_run_no, pending_payloads, payload={ - 'schema_version': 'shipping_inventory_rpa.v2', + 'schema_version': SCHEMA, 'trigger_type': 'on_demand', 'task_no': task_no, 'mode': mode, @@ -564,7 +565,7 @@ def per_source_callback_handler( run_no: str, callback_payload: dict[str, Any], session: Session | None = None, -) -> tuple[str, ShippingTaskInventoryRpaAttempt | None]: +) -> tuple[str, FreightRpaOnhandTaskAttempt | None]: """ 处理 per-source 库存 RPA 回调(三元组幂等 + 迟到保护 + Task 全局状态保护)。 【AI 触发时机】:RPA Dropzone 回调入口、手动 ingest API、Worker 补录回调统一调用本函数。 @@ -585,7 +586,7 @@ def per_source_callback_handler( session: 可选 Session。 Returns: - (result_code: str, attempt: ShippingTaskInventoryRpaAttempt | None) + (result_code: str, attempt: FreightRpaOnhandTaskAttempt | None) result_code ∈ {not_found, idempotent_ok, superseded_late, task_terminal, validated, succeeded, failed} """ sess = session or db.session @@ -597,7 +598,7 @@ def per_source_callback_handler( callback_id = str((callback_payload or {}).get('callback_id') or '').strip() if callback_id: callback_attempt = ( - sess.query(ShippingTaskInventoryRpaAttempt) + sess.query(FreightRpaOnhandTaskAttempt) .filter_by(callback_id=callback_id) .one_or_none() ) @@ -613,12 +614,12 @@ def per_source_callback_handler( # [STEP 2] 三元组定位 attempt = ( - sess.query(ShippingTaskInventoryRpaAttempt) + sess.query(FreightRpaOnhandTaskAttempt) .filter( and_( - ShippingTaskInventoryRpaAttempt.task_no == task_no, - ShippingTaskInventoryRpaAttempt.source_code == source_code_up, - ShippingTaskInventoryRpaAttempt.run_no == run_no, + FreightRpaOnhandTaskAttempt.task_no == task_no, + FreightRpaOnhandTaskAttempt.source_code == source_code_up, + FreightRpaOnhandTaskAttempt.run_no == run_no, ) ) .one_or_none() @@ -637,7 +638,7 @@ def per_source_callback_handler( attempt.error_code = 'trigger_identity_invalid' attempt.error_message = str((callback_payload or {}).get('error_message') or 'RPA trigger identity is invalid.')[:2000] attempt.updated_at = datetime.utcnow() - from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt + from app.services.shipping_notice.onhand_recovery_service import sync_preparation_source_from_rpa_attempt sync_preparation_source_from_rpa_attempt(rpa_attempt_id=int(attempt.id), rpa_status='failed') sess.flush([attempt]) return 'failed', attempt @@ -663,13 +664,13 @@ def per_source_callback_handler( except (TypeError, ValueError): current_attempt_no = 0 newer_count = ( - sess.query(func.count(ShippingTaskInventoryRpaAttempt.id)) + sess.query(func.count(FreightRpaOnhandTaskAttempt.id)) .filter( and_( - ShippingTaskInventoryRpaAttempt.task_no == task_no, - ShippingTaskInventoryRpaAttempt.source_code == source_code_up, - ShippingTaskInventoryRpaAttempt.attempt_no > current_attempt_no, - ShippingTaskInventoryRpaAttempt.status.in_(('consumed', 'superseded', 'succeeded')), + FreightRpaOnhandTaskAttempt.task_no == task_no, + FreightRpaOnhandTaskAttempt.source_code == source_code_up, + FreightRpaOnhandTaskAttempt.attempt_no > current_attempt_no, + FreightRpaOnhandTaskAttempt.status.in_(('consumed', 'superseded', 'succeeded')), ) ) .scalar() @@ -713,7 +714,7 @@ def per_source_callback_handler( attempt.callback_file_path = str(callback_payload.get('callback_file_path') or '').strip() or None inventory_file_no = str(callback_payload.get('inventory_file_no') or '').strip() or None if inventory_file_no: - attempt.inventory_file_no = inventory_file_no + attempt.onhand_file_no = inventory_file_no error_code = str(callback_payload.get('error_code') or '').strip() or None error_message = str(callback_payload.get('error_message') or '').strip() or None @@ -722,15 +723,15 @@ def per_source_callback_handler( attempt.transaction_status = 'rejected' attempt.error_code = error_code attempt.error_message = error_message[:2000] if error_message else None - from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt + from app.services.shipping_notice.onhand_recovery_service import sync_preparation_source_from_rpa_attempt sync_preparation_source_from_rpa_attempt(rpa_attempt_id=int(attempt.id), rpa_status='failed') sess.flush([attempt]) return 'failed', attempt # 回调标称成功,但必须二次验证快照已真实入库且 ready,否则仍然算失败(防止 RPA 伪成功) if inventory_file_no: _inv = ( - sess.query(ShippingInventoryFile) - .filter(ShippingInventoryFile.inventory_file_no == inventory_file_no) + sess.query(FreightRpaOnhandReportFile) + .filter(FreightRpaOnhandReportFile.onhand_file_no == inventory_file_no) .one_or_none() ) if _inv is None or not is_snapshot_fresh(_inv): @@ -748,13 +749,13 @@ def per_source_callback_handler( attempt.error_message = ( f"回调返回成功但关联库存快照未通过门禁校验:{missing_reason}"[:2000] ) - from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt + from app.services.shipping_notice.onhand_recovery_service import sync_preparation_source_from_rpa_attempt sync_preparation_source_from_rpa_attempt(rpa_attempt_id=int(attempt.id), rpa_status='failed') sess.flush([attempt]) return 'failed', attempt attempt.status = 'succeeded' attempt.transaction_status = 'succeeded' - from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt + from app.services.shipping_notice.onhand_recovery_service import sync_preparation_source_from_rpa_attempt sync_preparation_source_from_rpa_attempt( rpa_attempt_id=int(attempt.id), rpa_status='succeeded', @@ -765,13 +766,13 @@ def per_source_callback_handler( # 调用方在同一事务提交后,Job 才对 Worker 可见。 from app.services.shipping_notice.auto_progress_controller import submit_auto_progress - submit_auto_progress(task=task, trigger='inventory_rpa_callback_succeeded', commit=False) + submit_auto_progress(task=task, trigger='onhand_rpa_callback_succeeded', commit=False) return 'succeeded', attempt def claim_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: """记录 Worker 领取的逐源 Attempt,不推进 Snapshot、Link 或 Gate。""" - if payload.get('schema_version') != 'shipping_inventory_rpa.v2' or not isinstance(payload.get('items'), list): + if payload.get('schema_version') != SCHEMA or not isinstance(payload.get('items'), list): return {'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_schema_invalid'} worker_id = str(payload.get('worker_id') or '').strip() or None now = datetime.utcnow() @@ -784,7 +785,7 @@ def claim_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: source_code = str(item.get('source_code') or '').strip().upper() source_run_no = str(item.get('source_run_no') or '').strip() lease_token = str(item.get('lease_token') or '').strip() - attempt = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by( + attempt = db.session.query(FreightRpaOnhandTaskAttempt).filter_by( task_no=task_no, source_code=source_code, source_run_no=source_run_no, ).one_or_none() if attempt is None or str(attempt.lease_token or '') != lease_token: @@ -828,15 +829,15 @@ def per_source_timeout_scan( task_no = str(task.task_no or '').strip() threshold = datetime.utcnow() - timedelta(seconds=max(int(timeout_seconds), 1)) candidates = ( - sess.query(ShippingTaskInventoryRpaAttempt) + sess.query(FreightRpaOnhandTaskAttempt) .filter( and_( - ShippingTaskInventoryRpaAttempt.task_no == task_no, - ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')), + FreightRpaOnhandTaskAttempt.task_no == task_no, + FreightRpaOnhandTaskAttempt.status.in_(('queued', 'running')), or_( - ShippingTaskInventoryRpaAttempt.triggered_at <= threshold, - ShippingTaskInventoryRpaAttempt.leased_at <= threshold, - ShippingTaskInventoryRpaAttempt.created_at <= threshold, + FreightRpaOnhandTaskAttempt.triggered_at <= threshold, + FreightRpaOnhandTaskAttempt.leased_at <= threshold, + FreightRpaOnhandTaskAttempt.created_at <= threshold, ), ) ) @@ -867,7 +868,7 @@ def per_source_timeout_scan( att.extra_json = extra # 超时扫描与正式回调共享同一准备轮次事实;否则 Attempt 已失败而 # PreparationAttempt 仍停在 waiting_external,工作台会错误禁用重试。 - from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt + from app.services.shipping_notice.onhand_recovery_service import sync_preparation_source_from_rpa_attempt sync_preparation_source_from_rpa_attempt( rpa_attempt_id=int(att.id), diff --git a/backend/app/services/shipping_notice/post_ot_fulfillment_wave_service.py b/backend/app/services/shipping_notice/post_ot_fulfillment_wave_service.py index 32d675ba..9a670517 100644 --- a/backend/app/services/shipping_notice/post_ot_fulfillment_wave_service.py +++ b/backend/app/services/shipping_notice/post_ot_fulfillment_wave_service.py @@ -66,7 +66,7 @@ def _assert_fact_allows_fulfill(line: dict[str, Any]) -> tuple[Decimal, Decimal] if str(line.get('inventory_status') or '') != 'ready': raise ConflictError( 'Inventory not ready for post-OT wave', - code='SHIPPING.REVIEW_LINE_INVENTORY_NOT_READY', + code='SHIPPING.REVIEW_LINE_ONHAND_NOT_READY', details={'snapshot_line_id': line.get('snapshot_line_id'), 'inventory_status': line.get('inventory_status')}, ) if str(line.get('match_result') or '') != 'matched': @@ -75,11 +75,11 @@ def _assert_fact_allows_fulfill(line: dict[str, Any]) -> tuple[Decimal, Decimal] code='SHIPPING.REVIEW_LINE_MATCH_NOT_FULFILLABLE', details={'snapshot_line_id': line.get('snapshot_line_id'), 'match_result': line.get('match_result')}, ) - is_released_shortage = str((line.get('decision') or {}).get('decision_code') or '') == 'release_inventory_shortage' + is_released_shortage = str((line.get('decision') or {}).get('decision_code') or '') == 'release_onhand_shortage' if line.get('is_shortage') and not is_released_shortage: raise ConflictError( 'Line has inventory shortage', - code='SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY', + code='SHIPPING.REVIEW_LINE_INSUFFICIENT_ONHAND', details={'snapshot_line_id': line.get('snapshot_line_id')}, ) req = _parse_qty(line.get('required_qty')) @@ -87,7 +87,7 @@ def _assert_fact_allows_fulfill(line: dict[str, Any]) -> tuple[Decimal, Decimal] if req is None or (avail is None and not is_released_shortage) or (avail is not None and avail < req and not is_released_shortage): raise ConflictError( 'Line cannot fulfill complete quantity with current inventory facts', - code='SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY', + code='SHIPPING.REVIEW_LINE_INSUFFICIENT_ONHAND', details={'snapshot_line_id': line.get('snapshot_line_id')}, ) return req, avail @@ -311,13 +311,13 @@ def create_post_ot_fulfillment_wave( revision_id=None, ) # [D8] 波次按自身行重跑路由冻结(不继承首通知源);复用库存候选冻结链路。 - from app.services.shipping_notice.inventory_candidate_freeze_service import freeze_wave_notice_routing + from app.services.shipping_notice.onhand_candidate_freeze_service import freeze_wave_notice_routing routing_result = freeze_wave_notice_routing(notice, source_notice=None) if routing_result is None or not routing_result.source_codes: raise ConflictError( 'Inventory source routing is unresolved for selected fulfillment lines', - code='SHIPPING.REVIEW_LINE_INVENTORY_SOURCE_UNRESOLVED', + code='SHIPPING.REVIEW_LINE_ONHAND_SOURCE_UNRESOLVED', details={'snapshot_line_ids': [int(item) for item in selected_snapshot_line_ids]}, ) db.session.flush() @@ -351,7 +351,7 @@ def create_post_ot_fulfillment_wave( if ( key in accepted_snapshot_line_ids and current is not None - and current.decision_code == 'release_inventory_shortage' + and current.decision_code == 'release_onhand_shortage' ): current.line_status = 'task_created' current.task_id = int(order_task.id) @@ -476,7 +476,7 @@ def list_eligible_post_ot_snapshot_line_ids(case: ShippingOrderReviewCase) -> li 列出可自动/人工履约的行(ready+matched+未关闭+未终态)。 核心逻辑:库存充足行可直接入 wave;库存不足行只有在已留下 - ``release_inventory_shortage`` 审计决定后才能入 wave,不能因库存事实本身被放宽。 + ``release_onhand_shortage`` 审计决定后才能入 wave,不能因库存事实本身被放宽。 Args: case: 复核 Case。 @@ -496,7 +496,7 @@ def list_eligible_post_ot_snapshot_line_ids(case: ShippingOrderReviewCase) -> li if str(item.get('match_result') or '') != 'matched': continue decision_code = str((item.get('decision') or {}).get('decision_code') or '') - if item.get('is_shortage') and decision_code != 'release_inventory_shortage': + if item.get('is_shortage') and decision_code != 'release_onhand_shortage': continue if item.get('user_line_status') == 'auto_fulfill_failed': continue @@ -504,7 +504,7 @@ def list_eligible_post_ot_snapshot_line_ids(case: ShippingOrderReviewCase) -> li continue req = _parse_qty(item.get('required_qty')) avail = _parse_qty(item.get('available_qty')) - is_released_shortage = decision_code == 'release_inventory_shortage' + is_released_shortage = decision_code == 'release_onhand_shortage' if req is None or (avail is None and not is_released_shortage) or ( avail is not None and avail < req and not is_released_shortage ): diff --git a/backend/app/services/shipping_notice/process_gate_bridge.py b/backend/app/services/shipping_notice/process_gate_bridge.py index 96e1fea6..f01850e5 100644 --- a/backend/app/services/shipping_notice/process_gate_bridge.py +++ b/backend/app/services/shipping_notice/process_gate_bridge.py @@ -3,7 +3,7 @@ services/shipping_notice/process_gate_bridge.py 用途:业务路径与统一门禁领域服务之间的桥接:定位/创建 Execution、 将业务评估结果写入 Gate,人工确认后推进冻结/建单门禁,以及履约后段门禁同步。 -依赖:process_gate_service、process_gate_contract、constants、inventory_rpa_workflow、 +依赖:process_gate_service、process_gate_contract、constants、onhand_rpa_workflow、 ShippingProcessExecution、ShippingOrderReviewCase、ShippingNotice。 逻辑:由 order_extraction_run_service / order_review_confirmation_service / order_review_draft_service / progress_workflow / process_gate_executor 调用; @@ -11,9 +11,9 @@ services/shipping_notice/process_gate_bridge.py 复核草稿经 sync_review_gate_for_case 同步客户/Reservation/库存路由等 findings.details; 确认建单后 sync_execution_after_review_confirm:多波次不覆盖首波 Task 绑定; 禁止业务代码直接改 Gate.status;履约库存准备失败映射细粒度 reason_code; - 建单后尚无库存事实时不投影 inventory_file_empty,仅露出 retry_inventory_preparation - 供 ensure_inventory(复用未过期快照或触发 RPA);库存已就绪但尚无匹配行时, - 不把 inventory_matching 伪造成 inventory_match_failed(避免可用数量显示 --)。 + 建单后尚无库存事实时不投影 inventory_file_empty,仅露出 retry_onhand_preparation + 供 ensure_onhand(复用未过期快照或触发 RPA);库存已就绪但尚无匹配行时, + 不把 onhand_matching 伪造成 inventory_match_failed(避免可用数量显示 --)。 """ from __future__ import annotations @@ -60,7 +60,7 @@ def _derived_fulfillment_status(task: ShippingOrderTask | ShippingNotice) -> str if upload_status == 'failed': return 'upload_failed' if isinstance(task, ShippingOrderTask): - from app.services.shipping_notice.inventory_file_store import ( + from app.services.shipping_notice.onhand_file_store import ( current_inventory_matches_have_shortage, inventory_matches_complete_for_task, has_ready_inventory_file_for_task, @@ -69,12 +69,12 @@ def _derived_fulfillment_status(task: ShippingOrderTask | ShippingNotice) -> str if inventory_matches_complete_for_task(task): return 'shortage_review' if current_inventory_matches_have_shortage(task) else 'matched' return 'inventory_ready' if has_ready_inventory_file_for_task(task) else 'created' - from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task match_task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None) match_status = aggregate_match_status_for_task(match_task_id) or '' if match_status in {'fulfillable', 'partial', 'unfulfillable'}: return 'matched' - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task if has_ready_inventory_file_for_task(task): return 'inventory_ready' return 'created' @@ -84,32 +84,32 @@ def inventory_preparation_reason_code(task: ShippingOrderTask | ShippingNotice) """ 由任务事实推导库存准备门禁阻断原因码。 - 核心逻辑:pending_human_reason、最近 inventory_rpa_failed 事件与逐源 Attempt + 核心逻辑:pending_human_reason、最近 onhand_rpa_failed 事件与逐源 Attempt 失败事实优先于泛化 inventory_preparation_failed,区分排队/超时/登录/导出/耗尽/缺文件。 - 惰性导入 constants / inventory_rpa_workflow,避免与桥接模块循环依赖。 + 惰性导入 constants / onhand_rpa_workflow,避免与桥接模块循环依赖。 Args: task: 履约任务。 Returns: - 稳定阻断原因码(归属 inventory_preparation)。 + 稳定阻断原因码(归属 onhand_preparation)。 """ from app.services.shipping_notice.constants import ( PH_INV_UNAVAIL, PH_RPA_EXHAUSTED, PH_RPA_PENDING, ) - from app.services.shipping_notice.inventory_rpa_workflow import latest_task_event + from app.services.shipping_notice.onhand_rpa_workflow import latest_task_event from app.services.shipping_notice.process_gate_projection import task_blocking_reason pending = str(task_blocking_reason(task) or '').strip() if pending == PH_RPA_PENDING: - return 'inventory_rpa_queued' + return 'onhand_rpa_queued' if pending == PH_RPA_EXHAUSTED: - return 'inventory_rpa_exhausted' + return 'onhand_rpa_exhausted' if getattr(task, 'id', None) is not None: - failed = latest_task_event(task, 'inventory_rpa_failed') + failed = latest_task_event(task, 'onhand_rpa_failed') if failed is not None: payload = getattr(failed, 'detail_json', None) if not isinstance(payload, dict): @@ -119,29 +119,29 @@ def inventory_preparation_reason_code(task: ShippingOrderTask | ShippingNotice) code = str(payload.get('error_code') or '').strip().lower() blob = f'{err} {code}' if 'timeout' in blob or ('not ready' in blob and 'within' in blob): - return 'inventory_rpa_timeout' + return 'onhand_rpa_timeout' if 'login' in blob or 'auth' in blob: - return 'inventory_rpa_login_failed' + return 'onhand_rpa_login_failed' if 'export' in blob or 'rpa_export' in blob: - return 'inventory_rpa_export_failed' + return 'onhand_rpa_export_failed' if 'empty' in blob: return 'inventory_file_empty' if 'identity' in blob or 'mismatch' in blob: return 'inventory_file_identity_mismatch' - return 'inventory_rpa_export_failed' + return 'onhand_rpa_export_failed' # 逐源 Attempt 是当前库存 RPA 的正式失败事实;超时扫描不一定会留下旧 # ShippingTaskEvent,Gate 不能因此退化为“库存文件为空/缺失”。 - from app.models import ShippingTaskInventoryRpaAttempt + from app.models import FreightRpaOnhandTaskAttempt latest_attempt = ( - ShippingTaskInventoryRpaAttempt.query + FreightRpaOnhandTaskAttempt.query .filter( - ShippingTaskInventoryRpaAttempt.task_no == str(task.task_no or '').strip(), + FreightRpaOnhandTaskAttempt.task_no == str(task.task_no or '').strip(), ) .order_by( - ShippingTaskInventoryRpaAttempt.attempt_no.desc(), - ShippingTaskInventoryRpaAttempt.id.desc(), + FreightRpaOnhandTaskAttempt.attempt_no.desc(), + FreightRpaOnhandTaskAttempt.id.desc(), ) .first() ) @@ -152,16 +152,16 @@ def inventory_preparation_reason_code(task: ShippingOrderTask | ShippingNotice) str(latest_attempt.error_message or '').strip().lower(), ]) if 'exhausted' in blob: - return 'inventory_rpa_exhausted' + return 'onhand_rpa_exhausted' if 'timeout' in blob or ('not ready' in blob and 'within' in blob): - return 'inventory_rpa_timeout' + return 'onhand_rpa_timeout' if 'login' in blob or 'auth' in blob: - return 'inventory_rpa_login_failed' + return 'onhand_rpa_login_failed' if 'empty' in blob: return 'inventory_file_empty' if 'identity' in blob or 'mismatch' in blob: return 'inventory_file_identity_mismatch' - return 'inventory_rpa_export_failed' + return 'onhand_rpa_export_failed' # inv_unavail 仅说明当前没有可用库存文件;若本轮没有 RPA 失败审计, # 才使用该泛化原因,不能覆盖已记录的下载超时/登录/导出失败。 @@ -174,7 +174,7 @@ def inventory_preparation_reason_code(task: ShippingOrderTask | ShippingNotice) return 'inventory_file_missing' # [STEP] 活动库存快照是运行事实;任务字段仅为历史兼容投影。 - from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task + from app.services.shipping_notice.onhand_file_store import active_inventory_lines_for_task active_lines = active_inventory_lines_for_task(task) if isinstance(active_lines, list): @@ -216,7 +216,7 @@ def manual_upload_reason_code(task: ShippingOrderTask | ShippingNotice) -> str: return 'upload_rpa_pending' if pending == PH_UPLOAD_RPA_FAILED or status == 'upload_failed': # [STEP] 登录失败优先于泛化 upload_rpa_failed,便于责任方落到 admin - from app.services.shipping_notice.inventory_rpa_workflow import latest_task_event + from app.services.shipping_notice.onhand_rpa_workflow import latest_task_event if getattr(task, 'id', None) is not None: failed = latest_task_event(task, 'upload_rpa_failed') or latest_task_event( @@ -532,26 +532,26 @@ def sync_execution_after_review_confirm( ) # [STEP] Task 与 Snapshot 已在确认事务中完成后,才执行正式库存源裁决。 # CandidateSet 是 inventory_source_routing 通过的必要业务事实。 - from app.services.shipping_notice.inventory_source_gate import adjudicate_and_apply_inventory_source + from app.services.shipping_notice.onhand_source_gate import adjudicate_and_apply_inventory_source adjudication = adjudicate_and_apply_inventory_source( task, execution_id=int(execution.id), ) - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes - if not task_frozen_inventory_source_codes(task): + if not task_frozen_onhand_source_codes(task): # 无候选时不放行 routing;保留当前 Gate 事实,交由规则恢复动作处理。 return execution apply_gate_outcome( execution=execution, - gate_code='inventory_source_routing', + gate_code='onhand_source_routing', passed=True, effective_result={ 'findings': [], 'candidate_set_id': int(task.active_inventory_candidate_set_id), - 'source_codes': task_frozen_inventory_source_codes(task), + 'source_codes': task_frozen_onhand_source_codes(task), 'status': str(adjudication.status or 'resolved'), }, actor_type='user', @@ -673,14 +673,14 @@ def sync_inventory_routing_gate_for_case( blocking_reason_code: str | None = None, ) -> ShippingProcessGate | None: """ - 将库存源路由业务结果同步到 inventory_source_routing Gate。 + 将库存源路由业务结果同步到 onhand_source_routing Gate。 Returns: 更新后的 Gate;无 Execution 时尝试创建后同步。 """ return sync_review_gate_for_case( case=case, - gate_code='inventory_source_routing', + gate_code='onhand_source_routing', passed=passed, actor_id=actor_id, details=details, @@ -900,8 +900,8 @@ def _supersede_auto_inventory_poll_for_rpa_failure( 自动轮询 Attempt 不产生新的库存事实;其在 RPA 已失败后继续 queued/running 会使 sync_gate_from_business_result 早退,Gate 永久停留 waiting_external。 - 仅处理 trigger_type=auto 且 action_code=poll_inventory_preparation,绝不终止 - 用户主动 retry_inventory_preparation。 + 仅处理 trigger_type=auto 且 action_code=poll_onhand_preparation,绝不终止 + 用户主动 retry_onhand_preparation。 """ from app import db from app.models import ShippingProcessGateAttempt @@ -915,7 +915,7 @@ def _supersede_auto_inventory_poll_for_rpa_failure( ): return gate = ShippingProcessGate.query.filter_by( - execution_id=int(execution.id), gate_code='inventory_preparation', + execution_id=int(execution.id), gate_code='onhand_preparation', ).with_for_update().first() if gate is None: return @@ -932,7 +932,7 @@ def _supersede_auto_inventory_poll_for_rpa_failure( now = datetime.utcnow() for attempt in active_attempts: snapshot = attempt.input_snapshot_json if isinstance(attempt.input_snapshot_json, dict) else {} - if str(snapshot.get('action_code') or '').strip() != 'poll_inventory_preparation': + if str(snapshot.get('action_code') or '').strip() != 'poll_onhand_preparation': continue before = {'status': attempt.status, 'gate_code': gate.gate_code} attempt.status = 'superseded' @@ -965,10 +965,10 @@ def sync_fulfillment_gates_from_task( actor_id: str | int | None = None, ) -> None: """ - 按 ShippingNotice 履约状态同步 inventory_preparation→freight_upload_rpa→manual_upload_handoff。 + 按 ShippingNotice 履约状态同步 onhand_preparation→freight_upload_rpa→manual_upload_handoff。 核心逻辑:将库存、匹配、上传等领域事实投影为 Gate 结果; - 建单后尚无库存行时不投影假失败,只露出 retry_inventory_preparation 供自动取数; + 建单后尚无库存行时不投影假失败,只露出 retry_onhand_preparation 供自动取数; RPA 等待/失败写入 freight_upload_rpa(非人工交接);真正待人工上传才阻断 manual_upload_handoff;仅阻断当前业务真实卡住的第一道履约门禁。 由 auto_progress 与 Gate 恢复执行器在履约动作后调用。 @@ -995,7 +995,7 @@ def sync_fulfillment_gates_from_task( match_completed, ) from app.services.shipping_notice.process_gate_projection import task_blocking_reason - from app.services.shipping_notice.inventory_file_store import ( + from app.services.shipping_notice.onhand_file_store import ( active_inventory_file_for_task, active_inventory_lines_for_task, ) @@ -1087,18 +1087,18 @@ def sync_fulfillment_gates_from_task( # 存在对应轮次时使用,避免旧任务的孤立轮次污染正式链。 preparation = None try: - from app.models import ShippingInventoryPreparationAttempt + from app.models import ShippingOnhandPreparationAttempt prep_query = ( - ShippingInventoryPreparationAttempt.query + ShippingOnhandPreparationAttempt.query .filter_by(task_id=int(task.id), execution_id=int(execution.id)) - .filter(ShippingInventoryPreparationAttempt.status != 'superseded') + .filter(ShippingOnhandPreparationAttempt.status != 'superseded') ) if execution.candidate_set_id is not None: prep_query = prep_query.filter( - ShippingInventoryPreparationAttempt.candidate_set_id == int(execution.candidate_set_id) + ShippingOnhandPreparationAttempt.candidate_set_id == int(execution.candidate_set_id) ) - preparation = prep_query.order_by(ShippingInventoryPreparationAttempt.attempt_no.desc()).first() + preparation = prep_query.order_by(ShippingOnhandPreparationAttempt.attempt_no.desc()).first() except Exception: # noqa: BLE001 preparation = None # 已绑定库存行代表正式快照已成功落库;历史 PreparationAttempt 即使仍标为 @@ -1122,7 +1122,7 @@ def sync_fulfillment_gates_from_task( task_rpa_exhausted = str(task_blocking_reason(task) or '').strip() == 'rpa_exhausted' if not task_rpa_exhausted and (preparation.status in {'queued', 'running', 'waiting_external'} or pending): apply_gate_outcome( - execution=execution, gate_code='inventory_preparation', passed=False, + execution=execution, gate_code='onhand_preparation', passed=False, outcome='waiting_external', effective_result={'findings': [], **task_facts}, blocking_reason_code='inventory_preparation_waiting', actor_type=actor_type, actor_id=actor_id, @@ -1138,7 +1138,7 @@ def sync_fulfillment_gates_from_task( or 'inventory_preparation_failed' ) apply_gate_outcome( - execution=execution, gate_code='inventory_preparation', passed=False, + execution=execution, gate_code='onhand_preparation', passed=False, outcome='blocked_retryable', effective_result={'findings': [], **task_facts}, blocking_reason_code=preparation_reason, actor_type=actor_type, actor_id=actor_id, @@ -1147,7 +1147,7 @@ def sync_fulfillment_gates_from_task( return if preparation.status == 'succeeded' and required and len(prepared) == len(required): apply_gate_outcome( - execution=execution, gate_code='inventory_preparation', passed=True, + execution=execution, gate_code='onhand_preparation', passed=True, effective_result=task_facts, actor_type=actor_type, actor_id=actor_id, idempotency_key=f'fulfill:invprep:{execution.execution_no}:prep:{preparation.id}:passed', force=True, ) @@ -1160,22 +1160,22 @@ def sync_fulfillment_gates_from_task( # 必须退出自动处理中,回到可重试 Gate,不能因同一等待事实再次自动入队。 if pending_reason == PH_RPA_PENDING: outcome = 'waiting_external' - waiting_reason = 'inventory_rpa_queued' + waiting_reason = 'onhand_rpa_queued' elif pending_reason == PH_RPA_EXHAUSTED: # 兼容历史 rpa_exhausted:自动次数上限不得限制用户再次发起库存准备。 outcome = 'blocked_retryable' - waiting_reason = 'inventory_rpa_exhausted' + waiting_reason = 'onhand_rpa_exhausted' else: outcome = 'blocked_retryable' waiting_reason = inventory_preparation_reason_code(task) or 'inventory_preparation_failed' apply_gate_outcome( execution=execution, - gate_code='inventory_preparation', + gate_code='onhand_preparation', passed=False, outcome=outcome, effective_result={ 'findings': _fulfillment_blocking_finding( - gate_code='inventory_preparation', + gate_code='onhand_preparation', reason_code=waiting_reason, details=task_facts, ), @@ -1194,7 +1194,7 @@ def sync_fulfillment_gates_from_task( if not has_inventory_lines and status == 'created': prep_gate = ( ShippingProcessGate.query - .filter_by(execution_id=int(execution.id), gate_code='inventory_preparation') + .filter_by(execution_id=int(execution.id), gate_code='onhand_preparation') .first() ) if prep_gate is not None and str(prep_gate.status or '').strip().lower() in { @@ -1206,10 +1206,10 @@ def sync_fulfillment_gates_from_task( ) prep_gate.next_action_code = ( primary_next_action_for_gate( - gate_code='inventory_preparation', + gate_code='onhand_preparation', status='blocked_retryable', ) - or 'retry_inventory_preparation' + or 'retry_onhand_preparation' ) prep_gate.updated_at = datetime.utcnow() from app.services.shipping_notice.process_gate_service import ( @@ -1223,13 +1223,13 @@ def sync_fulfillment_gates_from_task( inv_prep_reason = None if inv_prep_passed else inventory_preparation_reason_code(task) apply_gate_outcome( execution=execution, - gate_code='inventory_preparation', + gate_code='onhand_preparation', passed=inv_prep_passed, outcome=None if inv_prep_passed else 'blocked_retryable', effective_result={ 'findings': ( [] if inv_prep_passed else _fulfillment_blocking_finding( - gate_code='inventory_preparation', + gate_code='onhand_preparation', reason_code=str(inv_prep_reason or 'inventory_preparation_failed'), details=task_facts, ) @@ -1250,13 +1250,13 @@ def sync_fulfillment_gates_from_task( mapping_reason = 'inventory_mapping_required' if mapping_needed else None apply_gate_outcome( execution=execution, - gate_code='inventory_field_mapping', + gate_code='onhand_field_mapping', passed=not mapping_needed, outcome='blocked_retryable' if mapping_needed else None, effective_result={ 'findings': ( [] if not mapping_needed else _fulfillment_blocking_finding( - gate_code='inventory_field_mapping', + gate_code='onhand_field_mapping', reason_code=mapping_reason or 'inventory_mapping_required', details={ **task_facts, @@ -1281,8 +1281,8 @@ def sync_fulfillment_gates_from_task( classify_inventory_match_reason, ) - from app.models import ShippingNoticeLineInventoryMatch - current_match_rows = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all() + from app.models import ShippingNoticeLineOnhandMatch + current_match_rows = ShippingNoticeLineOnhandMatch.query.filter_by(task_id=int(task.id), is_current=True).all() line_results = [{'disposition': row.match_result} for row in current_match_rows] # 库存已就绪但尚无匹配行:匹配 Gate 若仍是 pending/queued/running,说明匹配尚未执行完, # 不得投影成 inventory_match_failed(界面会显示 --,并与 auto-progress 并发踩踏)。 @@ -1290,13 +1290,13 @@ def sync_fulfillment_gates_from_task( if not match_passed and not current_match_rows: match_gate = ( ShippingProcessGate.query - .filter_by(execution_id=int(execution.id), gate_code='inventory_matching') + .filter_by(execution_id=int(execution.id), gate_code='onhand_matching') .first() ) match_gate_status = str(getattr(match_gate, 'status', '') or '').strip().lower() if match_gate else '' if match_gate is not None and match_gate_status in {'pending', 'queued', 'running'}: if not str(match_gate.next_action_code or '').strip(): - match_gate.next_action_code = 'retry_inventory_matching' + match_gate.next_action_code = 'retry_onhand_matching' match_gate.updated_at = datetime.utcnow() from app.services.shipping_notice.process_gate_service import ( _refresh_execution_pointers, @@ -1309,14 +1309,14 @@ def sync_fulfillment_gates_from_task( ) apply_gate_outcome( execution=execution, - gate_code='inventory_matching', + gate_code='onhand_matching', passed=match_passed, # 匹配已执行过但仍无终态事实时,才投影可重试失败并露出 retry_inventory_matching。 outcome='blocked_retryable' if not match_passed else None, effective_result={ 'findings': ( [] if match_passed else _fulfillment_blocking_finding( - gate_code='inventory_matching', + gate_code='onhand_matching', reason_code=str(match_reason or 'inventory_match_failed'), details={ **task_facts, @@ -1351,13 +1351,13 @@ def sync_fulfillment_gates_from_task( ) apply_gate_outcome( execution=execution, - gate_code='inventory_sufficiency', + gate_code='onhand_sufficiency', passed=sufficiency_ok, outcome='blocked_manual' if shortage else None, effective_result={ 'findings': ( [] if sufficiency_ok else _fulfillment_blocking_finding( - gate_code='inventory_sufficiency', + gate_code='onhand_sufficiency', reason_code=str(shortage_reason or 'inventory_insufficient'), details={**task_facts, 'match_status': match_status or None}, ) diff --git a/backend/app/services/shipping_notice/process_gate_contract.py b/backend/app/services/shipping_notice/process_gate_contract.py index 81c210aa..8eac46fb 100644 --- a/backend/app/services/shipping_notice/process_gate_contract.py +++ b/backend/app/services/shipping_notice/process_gate_contract.py @@ -223,7 +223,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( }, }, { - 'gate_code': 'inventory_source_routing', + 'gate_code': 'onhand_source_routing', 'sequence_no': 12, 'label': '库存源路由', 'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'inventory_source'}, @@ -236,56 +236,56 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( }, }, { - 'gate_code': 'inventory_preparation', + 'gate_code': 'onhand_preparation', 'sequence_no': 13, 'label': '库存文件或快照准备', - 'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'inventory_preparation'}, + 'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'onhand_preparation'}, 'responsible_party': 'worker', 'implementation_status': 'implemented', 'recoverable': True, 'default_next_actions': { - 'blocked_retryable': 'retry_inventory_preparation', - 'waiting_external': 'poll_inventory_preparation', - 'blocked_manual': 'retry_inventory_preparation', + 'blocked_retryable': 'retry_onhand_preparation', + 'waiting_external': 'poll_onhand_preparation', + 'blocked_manual': 'retry_onhand_preparation', }, }, { - 'gate_code': 'inventory_field_mapping', + 'gate_code': 'onhand_field_mapping', 'sequence_no': 14, 'label': '库存字段映射', - 'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'inventory_field_mapping'}, + 'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'onhand_field_mapping'}, 'responsible_party': 'system', 'implementation_status': 'implemented', 'recoverable': True, 'default_next_actions': { - 'blocked_retryable': 'retry_inventory_field_mapping', + 'blocked_retryable': 'retry_onhand_field_mapping', # 字段映射是库存模板治理,不允许用户确认技术映射。 - 'blocked_manual': 'retry_inventory_field_mapping', + 'blocked_manual': 'retry_onhand_field_mapping', }, }, { - 'gate_code': 'inventory_matching', + 'gate_code': 'onhand_matching', 'sequence_no': 15, 'label': 'Reservation + 料号匹配', - 'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'inventory_matching'}, + 'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'onhand_matching'}, 'responsible_party': 'worker', 'implementation_status': 'implemented', 'recoverable': True, 'default_next_actions': { - 'blocked_retryable': 'retry_inventory_matching', - 'blocked_manual': 'open_inventory_match_review', + 'blocked_retryable': 'retry_onhand_matching', + 'blocked_manual': 'open_onhand_match_review', }, }, { - 'gate_code': 'inventory_sufficiency', + 'gate_code': 'onhand_sufficiency', 'sequence_no': 16, 'label': '库存满足性', - 'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'inventory_sufficiency'}, + 'ui_placement': {'target_surface': 'fulfillment_prep', 'target_anchor': 'onhand_sufficiency'}, 'responsible_party': 'owner', 'implementation_status': 'implemented', 'recoverable': True, 'default_next_actions': { - 'blocked_retryable': 'recheck_inventory_sufficiency', + 'blocked_retryable': 'recheck_onhand_sufficiency', 'blocked_manual': 'open_shortage_review', }, }, @@ -366,17 +366,17 @@ PROCESS_GATE_ACTION_CODES: Final[frozenset[str]] = frozenset({ 'retry_with_latest_rules', 'recheck_freeze_readiness', 'retry_task_creation', - 'retry_inventory_preparation', - 'reload_inventory_result', - 'poll_inventory_preparation', - 'retry_inventory_field_mapping', - 'retry_inventory_matching', - 'retry_inventory_from_preparation', - 'retry_inventory_from_field_mapping', - 'retry_inventory_from_matching', - 'override_line_inventory_source', - 'open_inventory_match_review', - 'recheck_inventory_sufficiency', + 'retry_onhand_preparation', + 'reload_onhand_result', + 'poll_onhand_preparation', + 'retry_onhand_field_mapping', + 'retry_onhand_matching', + 'retry_onhand_from_preparation', + 'retry_onhand_from_field_mapping', + 'retry_onhand_from_matching', + 'override_line_onhand_source', + 'open_onhand_match_review', + 'recheck_onhand_sufficiency', 'open_shortage_review', 'recheck_excel_readiness', 'regenerate_excel_artifact', @@ -405,7 +405,7 @@ PROCESS_GATE_ACTION_PRESENTATION: Final[dict[str, dict[str, str]]] = { for _code in { 'open_order_review', 'open_profile_review', 'edit_order_fields', 'edit_reservation', 'confirm_customer', 'adjudicate_duplicate', 'resolve_field_conflicts', - 'open_inventory_match_review', 'open_shortage_review', + 'open_onhand_match_review', 'open_shortage_review', }: PROCESS_GATE_ACTION_PRESENTATION[_code]['dispatch'] = 'navigation' # ``ui_handler`` 是页面宿主能力标识,不参与动作授权或业务裁决。后端在这里声明 @@ -418,16 +418,16 @@ for _code, _ui_handler in { 'confirm_customer': {'ui_handler': 'customer_resolution'}, 'adjudicate_duplicate': {'ui_handler': 'duplicate_review'}, 'resolve_field_conflicts': {'ui_handler': 'field_conflicts'}, - 'open_inventory_match_review': {'ui_handler': 'inventory_match_review'}, + 'open_onhand_match_review': {'ui_handler': 'inventory_match_review'}, 'open_shortage_review': {'ui_handler': 'shortage_review'}, }.items(): PROCESS_GATE_ACTION_PRESENTATION[_code].update(_ui_handler) # 人工上传确认由 Gate 授权后打开既有对话框;它不是普通 Gate mutation。 PROCESS_GATE_ACTION_PRESENTATION['mark_manual_uploaded']['dispatch'] = 'dialog' PROCESS_GATE_ACTION_PRESENTATION['mark_manual_uploaded']['ui_handler'] = 'manual_upload_confirmation' -for _code in {'retry_inventory_from_preparation', 'retry_inventory_from_field_mapping', 'retry_inventory_from_matching'}: +for _code in {'retry_onhand_from_preparation', 'retry_onhand_from_field_mapping', 'retry_onhand_from_matching'}: PROCESS_GATE_ACTION_PRESENTATION[_code]['kind'] = 'recovery' -for _code in {'poll_inventory_preparation', 'poll_freight_upload_rpa'}: +for _code in {'poll_onhand_preparation', 'poll_freight_upload_rpa'}: PROCESS_GATE_ACTION_PRESENTATION[_code]['dispatch'] = 'refresh' def action_presentation( @@ -478,25 +478,25 @@ def inventory_preparation_primary_action( """裁决库存准备 Gate 面向业务用户的主动作。 单源合并(用户拍板):库存失败只保留 2 个按钮 —— - ``retry_inventory_preparation``(显式重跑 RPA)与 ``retry_inventory_matching`` + ``retry_onhand_preparation``(显式重跑 RPA)与 ``retry_onhand_matching`` (复用已抓取库存与字段映射并重匹配,不重抓,见 execute_stage_capability_rematch)。 - 已下线的 ``reload_inventory_result``(只重读)不再独立成主动作,其「复用快照」行为已并入 - ``retry_inventory_matching``。 - 边界(STP 多候选,ensure_inventory auto 模式):缺快照停人工待处理、不隐式触发 RPA。 - 因此获取库存未成功(无行级匹配结果)时,``retry_inventory_matching`` 由阶段能力禁用 + 已下线的 ``reload_onhand_result``(只重读)不再独立成主动作,其「复用快照」行为已并入 + ``retry_onhand_matching``。 + 边界(STP 多候选,ensure_onhand auto 模式):缺快照停人工待处理、不隐式触发 RPA。 + 因此获取库存未成功(无行级匹配结果)时,``retry_onhand_matching`` 由阶段能力禁用 (disabled_reason=no_match_result,见 ui_state._stage_capabilities_for_task), - 重抓必须走显式的 ``retry_inventory_preparation``;本函数只裁决按钮位次,不禁用按钮。 + 重抓必须走显式的 ``retry_onhand_preparation``;本函数只裁决按钮位次,不禁用按钮。 """ normalized_status = str(status or '').strip().lower() normalized_reason = str(blocking_reason_code or '').strip().lower() if normalized_status == 'waiting_external': - return 'poll_inventory_preparation' - if normalized_reason in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'}: + return 'poll_onhand_preparation' + if normalized_reason in {'onhand_rpa_timeout', 'onhand_rpa_exhausted'}: # [MERGE] 超时/耗尽:优先复用已有快照重匹配;无匹配结果时该按钮由阶段能力 # 禁用(no_match_result),显式重抓走侧路 retry_inventory_preparation。 - return 'retry_inventory_matching' + return 'retry_onhand_matching' if normalized_status in {'blocked_manual', 'blocked_retryable'}: - return 'retry_inventory_preparation' + return 'retry_onhand_preparation' return None @@ -534,10 +534,10 @@ def gate_side_recovery_actions( # [STEP] 库存准备 RPA 超时/耗尽:主恢复已合并为 retry_inventory_matching(优先复用已有快照 # 重匹配,无快照则回退 RPA);侧路保留显式 retry_inventory_preparation(强制重抓)供用户选择。 if ( - code == 'inventory_preparation' - and reason in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'} + code == 'onhand_preparation' + and reason in {'onhand_rpa_timeout', 'onhand_rpa_exhausted'} ): - sides.append('retry_inventory_preparation') + sides.append('retry_onhand_preparation') # [STEP] 人工上传交接(Gate 20):主动作是凭据登记,货代 RPA 仍允许用户显式重试。 if ( code == 'manual_upload_handoff' @@ -547,8 +547,8 @@ def gate_side_recovery_actions( # [STEP] 行级库存源人工覆写(方案 3·放开):通知准备(Excel 生成前)与库存匹配阶段 # 均允许用户把某行库存源覆写为任一已启用源后再重匹配;Excel 锁与源启用校验由执行器负责。 # 已取代旧 D5 多文件冲突逐行选源(select_line_inventory_source,已下线)。 - if code in {'inventory_source_routing', 'inventory_preparation', 'inventory_matching'}: - sides.append('override_line_inventory_source') + if code in {'onhand_source_routing', 'onhand_preparation', 'onhand_matching'}: + sides.append('override_line_onhand_source') return tuple(sides) @@ -582,7 +582,7 @@ PROCESS_GATE_BLOCKING_REASON_CODES: Final[frozenset[str]] = frozenset({ 'inventory_source_unavailable', 'inventory_source_conflicted', 'inventory_source_changed', - 'inventory_source_identity_mismatch', + 'onhand_source_identity_mismatch', 'inventory_multi_file_conflict', 'inventory_sku_not_found', 'inventory_reservation_not_found', @@ -623,11 +623,11 @@ PROCESS_GATE_BLOCKING_REASON_CODES: Final[frozenset[str]] = frozenset({ 'task_creation_failed', 'inventory_preparation_failed', 'inventory_preparation_waiting', - 'inventory_rpa_queued', - 'inventory_rpa_timeout', - 'inventory_rpa_login_failed', - 'inventory_rpa_export_failed', - 'inventory_rpa_exhausted', + 'onhand_rpa_queued', + 'onhand_rpa_timeout', + 'onhand_rpa_login_failed', + 'onhand_rpa_export_failed', + 'onhand_rpa_exhausted', 'inventory_file_missing', 'inventory_file_empty', 'inventory_file_identity_mismatch', @@ -693,18 +693,18 @@ PROCESS_GATE_REASON_OWNING_GATE: Final[dict[str, str]] = { 'cross_source_conflict': 'field_conflict_resolution', 'pdf_preferred_critical_conflict': 'field_conflict_resolution', 'pdf_preferred': 'field_conflict_resolution', - 'no_inventory_source_candidates': 'inventory_source_routing', - 'require_manual_review': 'inventory_source_routing', - 'inventory_source_unavailable': 'inventory_source_routing', - 'inventory_source_conflicted': 'inventory_source_routing', - 'inventory_source_changed': 'inventory_source_routing', - 'inventory_source_identity_mismatch': 'inventory_source_routing', - 'inventory_multi_file_conflict': 'inventory_matching', - 'inventory_sku_not_found': 'inventory_matching', - 'inventory_reservation_not_found': 'inventory_matching', - 'inventory_warehouse_mismatch': 'inventory_matching', - 'inventory_required_column_missing': 'inventory_field_mapping', - 'inventory_column_ambiguous': 'inventory_field_mapping', + 'no_inventory_source_candidates': 'onhand_source_routing', + 'require_manual_review': 'onhand_source_routing', + 'inventory_source_unavailable': 'onhand_source_routing', + 'inventory_source_conflicted': 'onhand_source_routing', + 'inventory_source_changed': 'onhand_source_routing', + 'onhand_source_identity_mismatch': 'onhand_source_routing', + 'inventory_multi_file_conflict': 'onhand_matching', + 'inventory_sku_not_found': 'onhand_matching', + 'inventory_reservation_not_found': 'onhand_matching', + 'inventory_warehouse_mismatch': 'onhand_matching', + 'inventory_required_column_missing': 'onhand_field_mapping', + 'inventory_column_ambiguous': 'onhand_field_mapping', 'excel_template_missing': 'excel_readiness', 'excel_input_incomplete': 'excel_readiness', 'artifact_validation_failed': 'artifact_generation', @@ -753,20 +753,20 @@ PROCESS_GATE_REASON_OWNING_GATE: Final[dict[str, str]] = { 'run_cancelled': 'order_freeze_readiness', 'pending_orders_present': 'order_freeze_readiness', 'task_creation_failed': 'task_creation', - 'inventory_preparation_failed': 'inventory_preparation', - 'inventory_preparation_waiting': 'inventory_preparation', - 'inventory_rpa_queued': 'inventory_preparation', - 'inventory_rpa_timeout': 'inventory_preparation', - 'inventory_rpa_login_failed': 'inventory_preparation', - 'inventory_rpa_export_failed': 'inventory_preparation', - 'inventory_rpa_exhausted': 'inventory_preparation', - 'inventory_file_missing': 'inventory_preparation', - 'inventory_file_empty': 'inventory_preparation', - 'inventory_file_identity_mismatch': 'inventory_preparation', - 'inventory_mapping_required': 'inventory_field_mapping', - 'inventory_match_failed': 'inventory_matching', - 'inventory_insufficient': 'inventory_sufficiency', - 'inventory_shortage_review_required': 'inventory_sufficiency', + 'inventory_preparation_failed': 'onhand_preparation', + 'inventory_preparation_waiting': 'onhand_preparation', + 'onhand_rpa_queued': 'onhand_preparation', + 'onhand_rpa_timeout': 'onhand_preparation', + 'onhand_rpa_login_failed': 'onhand_preparation', + 'onhand_rpa_export_failed': 'onhand_preparation', + 'onhand_rpa_exhausted': 'onhand_preparation', + 'inventory_file_missing': 'onhand_preparation', + 'inventory_file_empty': 'onhand_preparation', + 'inventory_file_identity_mismatch': 'onhand_preparation', + 'inventory_mapping_required': 'onhand_field_mapping', + 'inventory_match_failed': 'onhand_matching', + 'inventory_insufficient': 'onhand_sufficiency', + 'inventory_shortage_review_required': 'onhand_sufficiency', 'excel_not_ready': 'excel_readiness', 'artifact_generation_failed': 'artifact_generation', 'manual_upload_pending': 'manual_upload_handoff', @@ -884,16 +884,16 @@ def action_belongs_to_gate(*, gate_code: str, action_code: str) -> bool: if recovery_plan_for_action(current_gate=code, action_code=action) is not None: return True - if action == 'retry_inventory_matching' and code in { - 'inventory_preparation', 'inventory_matching', 'inventory_sufficiency', + if action == 'retry_onhand_matching' and code in { + 'onhand_preparation', 'onhand_matching', 'onhand_sufficiency', }: return True - if action == 'reload_inventory_result' and code == 'inventory_preparation': + if action == 'reload_onhand_result' and code == 'onhand_preparation': return True # 人工覆写行级库存源(方案 3·放开):通知准备(取数失败/多候选)与匹配阶段(Excel 前)均可。 # 已取代旧 D5 逐行选源(select_line_inventory_source,已下线)。 - if action == 'override_line_inventory_source' and code in { - 'inventory_source_routing', 'inventory_preparation', 'inventory_matching', + if action == 'override_line_onhand_source' and code in { + 'onhand_source_routing', 'onhand_preparation', 'onhand_matching', }: return True navigation_owners = { @@ -904,8 +904,8 @@ def action_belongs_to_gate(*, gate_code: str, action_code: str) -> bool: 'confirm_customer': {'customer_resolution'}, 'adjudicate_duplicate': {'duplicate_detection'}, 'resolve_field_conflicts': {'field_conflict_resolution'}, - 'open_inventory_match_review': {'inventory_matching'}, - 'open_shortage_review': {'inventory_sufficiency'}, + 'open_onhand_match_review': {'onhand_matching'}, + 'open_shortage_review': {'onhand_sufficiency'}, 'regenerate_manual_upload_todo': {'manual_upload_handoff'}, } # 人工交接 Gate 可由用户显式重新发起 RPA;自动上传开关不影响该恢复入口。 @@ -1153,17 +1153,17 @@ BLOCKING_REASON_TO_USER_MODE: Final[dict[str, str]] = { 'inventory_source_unavailable': 'needs_human', # 候选源配置被禁用(需人工改路由) 'inventory_source_conflicted': 'needs_human', # 路由规则冲突 'inventory_source_changed': 'retryable_tech', # 配置漂移,可重跑规则 - 'inventory_source_identity_mismatch': 'needs_human', # 仓库身份不匹配,需人工确认 + 'onhand_source_identity_mismatch': 'needs_human', # 仓库身份不匹配,需人工确认 'retry_with_latest_rules': 'retryable_tech', # --- 库存准备 / RPA --- 'inventory_preparation_failed': 'retryable_tech', 'inventory_preparation_waiting': 'retryable_tech', - 'inventory_rpa_queued': 'retryable_tech', - 'inventory_rpa_timeout': 'retryable_tech', - 'inventory_rpa_login_failed': 'retryable_tech', - 'inventory_rpa_export_failed': 'retryable_tech', - 'inventory_rpa_exhausted': 'needs_human', # RPA 重试耗尽 → 人工上传 + 'onhand_rpa_queued': 'retryable_tech', + 'onhand_rpa_timeout': 'retryable_tech', + 'onhand_rpa_login_failed': 'retryable_tech', + 'onhand_rpa_export_failed': 'retryable_tech', + 'onhand_rpa_exhausted': 'needs_human', # RPA 重试耗尽 → 人工上传 'inventory_file_missing': 'retryable_tech', 'inventory_file_empty': 'retryable_tech', 'inventory_file_identity_mismatch': 'needs_human', @@ -1244,9 +1244,9 @@ BLOCKING_REASON_TO_USER_MODE: Final[dict[str, str]] = { INVENTORY_MAIN_GATES: Final[tuple[str, ...]] = ( 'order_freeze_readiness', # 订单 Snapshot 冻结(sub_stage=frozen) - 'inventory_source_routing', # CandidateSet 路由裁决与冻结(sub_stage=calculated) - 'inventory_preparation', # 多源快照准备(sub_stage=snapshots_ready) - 'inventory_matching', # 跨源匹配 & 短缺/冲突(sub_stage=matched / blocking) + 'onhand_source_routing', # CandidateSet 路由裁决与冻结(sub_stage=calculated) + 'onhand_preparation', # 多源快照准备(sub_stage=snapshots_ready) + 'onhand_matching', # 跨源匹配 & 短缺/冲突(sub_stage=matched / blocking) ) INVENTORY_SUB_STAGES: Final[frozenset[str]] = frozenset({ @@ -1369,9 +1369,9 @@ def derive_position(*, gate_code: str | None, review_status: str | None) -> str 'order_field_extraction': 'parse_review', 'customer_resolution': 'customer_review', 'reservation_validation': 'rsv_req', - 'inventory_preparation': 'inventory_pending', - 'inventory_matching': 'ready_to_match', - 'inventory_sufficiency': 'shortage_review', + 'onhand_preparation': 'inventory_pending', + 'onhand_matching': 'ready_to_match', + 'onhand_sufficiency': 'shortage_review', 'order_freeze_readiness': 'order_freeze', 'excel_readiness': 'ready_to_export', 'artifact_generation': 'export_ready', @@ -1404,44 +1404,44 @@ def derive_todo_category(*, user_mode: str, position: str | None = None) -> str: # ============================================================ STAGE_CAPABILITY_DEFINITIONS: Final[dict[str, dict[str, Any]]] = { - 'override_line_inventory_source': { + 'override_line_onhand_source': { 'stage': 'fulfillment_prep', 'scope': 'line', - 'action_code': 'override_line_inventory_source', + 'action_code': 'override_line_onhand_source', 'invalidate': { - 'inventory_field_mapping', 'inventory_matching', - 'inventory_sufficiency', 'excel_readiness', 'artifact_generation', + 'onhand_field_mapping', 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', }, - 'reset_to': 'inventory_preparation', + 'reset_to': 'onhand_preparation', }, - 'retry_inventory_preparation': { + 'retry_onhand_preparation': { 'stage': 'fulfillment_prep', 'scope': 'task', - 'action_code': 'retry_inventory_preparation', + 'action_code': 'retry_onhand_preparation', 'invalidate': { - 'inventory_field_mapping', 'inventory_matching', - 'inventory_sufficiency', 'excel_readiness', 'artifact_generation', + 'onhand_field_mapping', 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', }, - 'reset_to': 'inventory_preparation', + 'reset_to': 'onhand_preparation', }, # 重新匹配库存:只在通知准备阶段内、已有匹配结果(且 Excel 未生成)时可用。 # 与「重抓」不同,它保留已抓取库存与字段映射,仅重算匹配及下游满足性/Excel, # 因此不重置回 inventory_preparation,也不作废上游 source/mapping。 - 'retry_inventory_matching': { + 'retry_onhand_matching': { 'stage': 'fulfillment_prep', 'scope': 'task', - 'action_code': 'retry_inventory_matching', + 'action_code': 'retry_onhand_matching', 'invalidate': { - 'inventory_matching', 'inventory_sufficiency', + 'onhand_matching', 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', }, 'invalidate_change_type': 'inventory_field_mapping_changed', - 'reset_to': 'inventory_matching', + 'reset_to': 'onhand_matching', }, - 'reload_inventory_result': { + 'reload_onhand_result': { 'stage': 'fulfillment_prep', 'scope': 'task', - 'action_code': 'reload_inventory_result', + 'action_code': 'reload_onhand_result', 'invalidate': frozenset(), 'reset_to': None, }, diff --git a/backend/app/services/shipping_notice/process_gate_dependency.py b/backend/app/services/shipping_notice/process_gate_dependency.py index c1449f33..5c0e4280 100644 --- a/backend/app/services/shipping_notice/process_gate_dependency.py +++ b/backend/app/services/shipping_notice/process_gate_dependency.py @@ -21,13 +21,13 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = { 'customer_resolution', 'duplicate_detection', 'field_conflict_resolution', - 'inventory_source_routing', + 'onhand_source_routing', 'order_freeze_readiness', 'task_creation', - 'inventory_preparation', - 'inventory_field_mapping', - 'inventory_matching', - 'inventory_sufficiency', + 'onhand_preparation', + 'onhand_field_mapping', + 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', 'freight_upload_rpa', @@ -36,8 +36,8 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = { 'reservation_changed': ( 'duplicate_detection', 'order_freeze_readiness', - 'inventory_matching', - 'inventory_sufficiency', + 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', 'freight_upload_rpa', @@ -45,8 +45,8 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = { ), 'part_number_changed': ( 'order_freeze_readiness', - 'inventory_matching', - 'inventory_sufficiency', + 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', 'freight_upload_rpa', @@ -54,8 +54,8 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = { ), 'quantity_changed': ( 'order_freeze_readiness', - 'inventory_matching', - 'inventory_sufficiency', + 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', 'freight_upload_rpa', @@ -65,37 +65,37 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = { 'duplicate_detection', 'order_freeze_readiness', 'task_creation', - 'inventory_preparation', - 'inventory_field_mapping', - 'inventory_matching', - 'inventory_sufficiency', + 'onhand_preparation', + 'onhand_field_mapping', + 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', 'freight_upload_rpa', 'manual_upload_handoff', ), 'inventory_source_changed': ( - 'inventory_preparation', - 'inventory_field_mapping', - 'inventory_matching', - 'inventory_sufficiency', + 'onhand_preparation', + 'onhand_field_mapping', + 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', 'freight_upload_rpa', 'manual_upload_handoff', ), 'inventory_file_changed': ( - 'inventory_field_mapping', - 'inventory_matching', - 'inventory_sufficiency', + 'onhand_field_mapping', + 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', 'freight_upload_rpa', 'manual_upload_handoff', ), 'inventory_field_mapping_changed': ( - 'inventory_matching', - 'inventory_sufficiency', + 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', 'freight_upload_rpa', @@ -113,7 +113,7 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = { 'task_creation', ), 'field_conflict_resolved': ( - 'inventory_source_routing', + 'onhand_source_routing', 'order_freeze_readiness', 'task_creation', ), @@ -125,15 +125,15 @@ PROCESS_GATE_INVALIDATION_RULES: Final[dict[str, tuple[str, ...]]] = { 'reservation_confirmed': ( 'duplicate_detection', 'order_freeze_readiness', - 'inventory_matching', - 'inventory_sufficiency', + 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', 'freight_upload_rpa', 'manual_upload_handoff', ), 'line_fulfillment_decision_changed': ( - 'inventory_sufficiency', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', 'freight_upload_rpa', @@ -153,13 +153,13 @@ PROCESS_GATE_PREREQUISITES: Final[dict[str, tuple[str, ...]]] = { 'field_conflict_resolution': ('duplicate_detection',), 'task_creation': ('field_conflict_resolution',), 'order_freeze_readiness': ('task_creation',), - 'inventory_source_routing': ('order_freeze_readiness',), - 'inventory_preparation': ('inventory_source_routing',), - 'inventory_field_mapping': ('inventory_preparation',), - 'inventory_matching': ('inventory_field_mapping',), - 'inventory_sufficiency': ('inventory_matching',), + 'onhand_source_routing': ('order_freeze_readiness',), + 'onhand_preparation': ('onhand_source_routing',), + 'onhand_field_mapping': ('onhand_preparation',), + 'onhand_matching': ('onhand_field_mapping',), + 'onhand_sufficiency': ('onhand_matching',), # 滚动导出仅要求已完成库存匹配;库存不足仍由 inventory_sufficiency 独立阻断未导出行。 - 'excel_readiness': ('inventory_matching',), + 'excel_readiness': ('onhand_matching',), 'artifact_generation': ('excel_readiness',), 'freight_upload_rpa': ('artifact_generation',), 'manual_upload_handoff': ('freight_upload_rpa',), @@ -217,5 +217,5 @@ def assert_process_gate_dependency_integrity() -> None: ) # 仅重新生成 Excel 不得失效库存匹配。 excel_only = set(PROCESS_GATE_INVALIDATION_RULES['excel_regeneration_only']) - assert 'inventory_matching' not in excel_only + assert 'onhand_matching' not in excel_only assert 'artifact_generation' in excel_only diff --git a/backend/app/services/shipping_notice/process_gate_executor.py b/backend/app/services/shipping_notice/process_gate_executor.py index efd03c70..646eff2f 100644 --- a/backend/app/services/shipping_notice/process_gate_executor.py +++ b/backend/app/services/shipping_notice/process_gate_executor.py @@ -3,9 +3,9 @@ services/shipping_notice/process_gate_executor.py 用途:将门禁恢复动作码路由到真实业务执行器(同步适配或异步履约)。 依赖:process_gate_service、order_review_draft_service、freeze_readiness_service、 - inventory_workflow、fulfillment_workflow、progress_workflow、order_extraction_run_service、 + onhand_workflow、fulfillment_workflow、progress_workflow、order_extraction_run_service、 document_layout.lifecycle、process_gate_contract、process_gate_bridge、 - inventory_candidate_projection、recovery_invalidation_service。 + onhand_candidate_projection、recovery_invalidation_service。 逻辑:由 Gate Job Handler 或同步恢复路径调用;禁止客户端传入目标状态; 库存源 adopt/keep/reroute 委托 Draft 服务;技术重试委托既有 Run/版面路径; co8 后文档/Run 解析仅经 review_case_id / task_id,不再读 WorkflowItem; @@ -73,7 +73,7 @@ _SYNC_ACTIONS: frozenset[str] = frozenset({ 'confirm_customer', 'adjudicate_duplicate', 'resolve_field_conflicts', - 'open_inventory_match_review', + 'open_onhand_match_review', 'open_shortage_review', 'regenerate_manual_upload_todo', }) @@ -81,8 +81,8 @@ _SYNC_ACTIONS: frozenset[str] = frozenset({ # 库存准备:仅这些已有动作码强制 mode=retry_rpa(跳过快照复用、新建 Attempt)。 # poll / 首次自动投递不得落入此集合;禁止「人工入口一律 retry_rpa」。 _FORCE_INVENTORY_RPA_ACTION_CODES: frozenset[str] = frozenset({ - 'retry_inventory_preparation', - 'retry_inventory_from_preparation', + 'retry_onhand_preparation', + 'retry_onhand_from_preparation', }) # 人工入口:前端应导航,不把业务状态改为 passed。 @@ -94,7 +94,7 @@ _NAVIGATION_ACTIONS: frozenset[str] = frozenset({ 'confirm_customer', 'adjudicate_duplicate', 'resolve_field_conflicts', - 'open_inventory_match_review', + 'open_onhand_match_review', 'open_shortage_review', }) @@ -191,16 +191,16 @@ def _dispatch_action( 'retry_customer_resolution': _handle_recheck_task_gates, 'retry_duplicate_detection': _handle_recheck_task_gates, 'retry_task_creation': _handle_retry_task_creation, - 'retry_inventory_preparation': _handle_retry_inventory_preparation, - 'reload_inventory_result': _handle_reload_inventory_result, - 'poll_inventory_preparation': _handle_retry_inventory_preparation, - 'retry_inventory_field_mapping': _handle_retry_inventory_field_mapping, - 'retry_inventory_matching': _handle_retry_inventory_matching, - 'retry_inventory_from_preparation': _handle_retry_inventory_preparation, - 'retry_inventory_from_field_mapping': _handle_retry_inventory_from_field_mapping, - 'retry_inventory_from_matching': _handle_retry_inventory_from_matching, - 'override_line_inventory_source': _handle_override_line_inventory_source, - 'recheck_inventory_sufficiency': _handle_recheck_inventory_sufficiency, + 'retry_onhand_preparation': _handle_retry_inventory_preparation, + 'reload_onhand_result': _handle_reload_inventory_result, + 'poll_onhand_preparation': _handle_retry_inventory_preparation, + 'retry_onhand_field_mapping': _handle_retry_inventory_field_mapping, + 'retry_onhand_matching': _handle_retry_inventory_matching, + 'retry_onhand_from_preparation': _handle_retry_inventory_preparation, + 'retry_onhand_from_field_mapping': _handle_retry_inventory_from_field_mapping, + 'retry_onhand_from_matching': _handle_retry_inventory_from_matching, + 'override_line_onhand_source': _handle_override_line_inventory_source, + 'recheck_onhand_sufficiency': _handle_recheck_inventory_sufficiency, 'recheck_excel_readiness': _handle_recheck_excel_readiness, 'regenerate_excel_artifact': _handle_regenerate_excel, 'poll_freight_upload_rpa': _handle_freight_upload_rpa, @@ -213,8 +213,8 @@ def _dispatch_action( 'confirm_customer': _manual_open('confirm_customer', 'customer_resolution'), 'adjudicate_duplicate': _manual_open('adjudicate_duplicate', 'duplicate_detection'), 'resolve_field_conflicts': _manual_open('resolve_field_conflicts', 'field_conflict_resolution'), - 'open_inventory_match_review': _manual_open('open_inventory_match_review', 'inventory_matching'), - 'open_shortage_review': _manual_open('open_shortage_review', 'inventory_sufficiency'), + 'open_onhand_match_review': _manual_open('open_onhand_match_review', 'onhand_matching'), + 'open_shortage_review': _manual_open('open_shortage_review', 'onhand_sufficiency'), } handler = handlers.get(action_code) if handler is None: @@ -374,7 +374,7 @@ def _resolve_line_inventory_scope( 由 snapshot_line_id / line_scope_key 解析行级库存作用域。 核心逻辑:snapshot_line_id → SnapshotLine.line_no → CandidateLine.source_codes_json。 - Gate 直调 ensure_inventory 时绕过 progress_workflow,必须在此收窄源范围。 + Gate 直调 ensure_onhand 时绕过 progress_workflow,必须在此收窄源范围。 Args: task: 当前 OT / 兼容 Notice owner。 @@ -396,7 +396,7 @@ def _resolve_line_inventory_scope( return None from app.models import ShippingOrderSnapshot - from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines + from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_lines snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id)) scoped_line = next( @@ -819,10 +819,10 @@ def _handle_retry_inventory_preparation( """ 重试/轮询库存准备。 - 核心逻辑:按已有动作码映射 ensure_inventory mode(retry_inventory_preparation → + 核心逻辑:按已有动作码映射 ensure_inventory mode(retry_onhand_preparation → retry_rpa;poll → auto + allow_auto_retry=False;首次 gate_attempt_passed 保持 auto); 若携带 line_scope_key/snapshot_line_id,则按该行 candidate.source_codes_json 收窄 - RPA/失效范围,且不触碰已产生发货通知行。调用 ensure_inventory 后按任务事实推导 + RPA/失效范围,且不触碰已产生发货通知行。调用 ensure_inventory(阶段码 ensure_onhand)后按任务事实推导 细粒度阻断码,再同步履约门禁。 Args: @@ -834,8 +834,8 @@ def _handle_retry_inventory_preparation( Gate Attempt outcome 字典(outcome / blocking_reason_code / effective_result_json 等)。 """ from app.models import ShippingNotice - from app.services.shipping_notice.inventory_workflow import ensure_inventory - from app.services.shipping_notice.inventory_recovery_service import create_inventory_preparation_round + from app.services.shipping_notice.onhand_workflow import ensure_inventory + from app.services.shipping_notice.onhand_recovery_service import create_inventory_preparation_round from app.services.shipping_notice.recovery_invalidation_service import invalidate_inventory_downstream from app.services.shipping_notice.process_gate_bridge import ( inventory_preparation_reason_code, @@ -854,7 +854,7 @@ def _handle_retry_inventory_preparation( # [STEP 0A] inventory_preparation 只消费 routing 已冻结的 CandidateSet。 # 若历史数据越过 routing,直接阻断,不在库存准备阶段偷偷补做裁决。 if task is not None: - from app.services.shipping_notice.inventory_candidate_projection import ( + from app.services.shipping_notice.onhand_candidate_projection import ( get_active_candidate_lines, get_active_candidate_set, get_active_candidate_sources, @@ -874,26 +874,26 @@ def _handle_retry_inventory_preparation( 'blocking_reason_code': 'inventory_source_routing_required', 'effective_result_json': {'findings': [], 'routing_required': True}, 'output_snapshot': { - 'action_code': str(payload.get('action_code') or 'retry_inventory_preparation'), + 'action_code': str(payload.get('action_code') or 'retry_onhand_preparation'), 'routing_required': True, }, } - if task is not None and payload.get('action_code') == 'poll_inventory_preparation': + if task is not None and payload.get('action_code') == 'poll_onhand_preparation': # 回调已将本轮准备收口为失败后,已排队的旧 poll 只能重投影正式 Gate。 # 若继续调用 ensure_inventory,会把精确的 RPA 超时覆盖为泛化的缺库存文件。 - from app.models import ShippingInventoryPreparationAttempt + from app.models import ShippingOnhandPreparationAttempt - failed_preparation_query = ShippingInventoryPreparationAttempt.query.filter_by( + failed_preparation_query = ShippingOnhandPreparationAttempt.query.filter_by( task_id=int(task.id), execution_id=int(execution.id), status='failed', ) if execution.candidate_set_id is not None: failed_preparation_query = failed_preparation_query.filter( - ShippingInventoryPreparationAttempt.candidate_set_id == int(execution.candidate_set_id) + ShippingOnhandPreparationAttempt.candidate_set_id == int(execution.candidate_set_id) ) failed_preparation = failed_preparation_query.order_by( - ShippingInventoryPreparationAttempt.attempt_no.desc() + ShippingOnhandPreparationAttempt.attempt_no.desc() ).first() if failed_preparation is not None: prep_reason = inventory_preparation_reason_code(task) @@ -907,7 +907,7 @@ def _handle_retry_inventory_preparation( 'poll_skipped_after_callback_failure': True, }, 'output_snapshot': { - 'action_code': 'poll_inventory_preparation', + 'action_code': 'poll_onhand_preparation', 'poll_skipped_after_callback_failure': True, }, } @@ -925,7 +925,7 @@ def _handle_retry_inventory_preparation( else payload.get('snapshot_line_id') ), ) - if task is not None and payload.get('action_code') != 'poll_inventory_preparation' and not is_initial_auto_dispatch: + if task is not None and payload.get('action_code') != 'poll_onhand_preparation' and not is_initial_auto_dispatch: # 历史 Task 可能在正式建单后遗漏快照。所有 Gate 恢复入口必须先补齐该履约事实, # 不能依赖某一个旧 Workspace/Chat 重试入口,否则同一个按钮会持续卡在 order_freeze。 if not task.order_snapshot_id: @@ -948,11 +948,11 @@ def _handle_retry_inventory_preparation( # override_line_inventory_source)。 # 行键失效(line_scope_key/snapshot_line_id 解析不到行)时 _resolve_line_inventory_scope # 返回 None,按既有降级语义走任务级刷新(升级前行为一致)。 - if str(payload.get('action_code') or '').strip() == 'retry_inventory_preparation': + if str(payload.get('action_code') or '').strip() == 'retry_onhand_preparation': from app.services.shipping_notice.upload_attempt_service import latest_export_artifact if latest_export_artifact(task) is None: - from app.services.shipping_notice.inventory_candidate_freeze_service import ( + from app.services.shipping_notice.onhand_candidate_freeze_service import ( refresh_candidates_from_current_routing, refresh_line_candidates_from_current_routing, ) @@ -975,9 +975,9 @@ def _handle_retry_inventory_preparation( if refreshed_scope is not None: line_scope = refreshed_scope if payload.get('action_code') in { - 'retry_inventory_preparation', - 'retry_inventory_from_preparation', - 'retry_inventory_from_field_mapping', + 'retry_onhand_preparation', + 'retry_onhand_from_preparation', + 'retry_onhand_from_field_mapping', }: invalidate_inventory_downstream( execution=execution, @@ -991,7 +991,7 @@ def _handle_retry_inventory_preparation( task=task, execution_id=int(execution.id), recovery_plan_id=int(recovery_plan_id) if recovery_plan_id else None, - action_code=str(payload.get('action_code') or 'retry_inventory_preparation'), + action_code=str(payload.get('action_code') or 'retry_onhand_preparation'), operation_id=str(payload.get('operation_id') or '').strip() or None, gate_attempt_id=int(payload.get('attempt_id')) if payload.get('attempt_id') else None, ) @@ -1016,13 +1016,13 @@ def _handle_retry_inventory_preparation( inventory_payload['mode'] = 'auto' else: inventory_payload['mode'] = 'retry_rpa' - if action_code == 'poll_inventory_preparation': + if action_code == 'poll_onhand_preparation': # [只读轮询] 轮询仅查询 RPA 结果:RPA Attempt 失败(含超时扫描收口)时禁止自动重试, # 由本轮结果把 Gate 收口为人工阻断,重试必须由用户在当前 Gate 显式发起。 inventory_payload['allow_auto_retry'] = False response = ensure_inventory(inventory_payload) if preparation_round is not None: - from app.services.shipping_notice.inventory_recovery_service import sync_inventory_preparation_round + from app.services.shipping_notice.onhand_recovery_service import sync_inventory_preparation_round rpa_result = ((response.get('data') or {}).get('rpa') or {}) if isinstance(response, dict) else {} sync_inventory_preparation_round(preparation_attempt=preparation_round, result=rpa_result) @@ -1032,7 +1032,7 @@ def _handle_retry_inventory_preparation( else 'inventory_preparation_failed' ) outcome = _tool_outcome( - action_code='retry_inventory_preparation', + action_code='retry_onhand_preparation', response=response, # 用户触发的重新获取库存不能把“已提交但未确认”伪装成业务完成; # Gate 仍可记录 waiting_external,调用方可据此轮询,但测试/审计需区分 @@ -1057,7 +1057,7 @@ def _handle_override_line_inventory_source( 校验顺序:Excel 锁 → 源存在且启用 → 定位行候选 → 覆写; 覆写后把该行候选钉为所选源。人工指定即定论:不再重跑路由规则。 - 当前在 routing:passed 后由 complete → enqueue 首投库存准备(按冻结源取数)。 - - 当前在准备/匹配:定向回 inventory_preparation,mode=auto(有快照复用,无则 RPA)。 + - 当前在准备/匹配:定向回 onhand_preparation,mode=auto(有快照复用,无则 RPA)。 Args: execution: 门禁执行上下文。 @@ -1069,12 +1069,12 @@ def _handle_override_line_inventory_source( """ from app.core.errors import ConflictError, ValidationError from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit - from app.services.shipping_notice.inventory_source_repository import ( + from app.services.shipping_notice.onhand_source_repository import ( get_database_inventory_source, list_database_inventory_sources, ) from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task - from app.services.shipping_notice.inventory_candidate_freeze_service import ( + from app.services.shipping_notice.onhand_candidate_freeze_service import ( freeze_manual_line_source_selection, ) @@ -1123,7 +1123,7 @@ def _handle_override_line_inventory_source( event_type='review_line_source_overridden', aggregate_type='shipping_notice', aggregate_id=str(task.task_no), - action='override_line_inventory_source', + action='override_line_onhand_source', actor_type='user' if actor_id else 'system', actor_id=actor_id, task_no=task.task_no, @@ -1139,7 +1139,7 @@ def _handle_override_line_inventory_source( 'selected_line_no': line_no, 'all_lines_selected': False, }, 'output_snapshot': { - 'action_code': 'override_line_inventory_source', + 'action_code': 'override_line_onhand_source', 'candidate_set_id': candidate_result.candidate_set_id, 'all_lines_selected': False, }, @@ -1148,7 +1148,7 @@ def _handle_override_line_inventory_source( # 人工指定源即定论:冻结候选后不再重跑路由规则。routing Gate 以 passed 收口, # complete_gate_attempt → _enqueue_auto_progress_after_gate_pass 首投 inventory_preparation #(按已冻结源取数:有 ready 快照复用,否则再 RPA)。禁止在本 Attempt 内递归推进。 - if gate.gate_code == 'inventory_source_routing': + if gate.gate_code == 'onhand_source_routing': return { 'outcome': 'passed', 'effective_result_json': { @@ -1156,7 +1156,7 @@ def _handle_override_line_inventory_source( 'selected_line_no': line_no, 'all_lines_selected': True, }, 'output_snapshot': { - 'action_code': 'override_line_inventory_source', + 'action_code': 'override_line_onhand_source', 'candidate_set_id': candidate_result.candidate_set_id, 'all_lines_selected': True, }, @@ -1172,7 +1172,7 @@ def _handle_override_line_inventory_source( task.task_no, trigger='manual_override_source', operator_id=actor_id, - resume_gate_code='inventory_preparation', + resume_gate_code='onhand_preparation', inventory_mode='auto', ) sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=actor_id) @@ -1181,7 +1181,7 @@ def _handle_override_line_inventory_source( # RPA 失败则保留 inventory_preparation 的人工恢复入口,后续 Gate 不得被放行。 db.session.flush() preparation_gate = ShippingProcessGate.query.filter_by( - execution_id=int(execution.id), gate_code='inventory_preparation', + execution_id=int(execution.id), gate_code='onhand_preparation', ).first() gate_status = str(getattr(preparation_gate, 'status', '') or '').strip().lower() reason_code = str(getattr(preparation_gate, 'blocking_reason_code', '') or '').strip() or None @@ -1201,7 +1201,7 @@ def _handle_override_line_inventory_source( 'inventory_preparation_status': gate_status or 'blocked_retryable', }, 'output_snapshot': { - 'action_code': 'override_line_inventory_source', + 'action_code': 'override_line_onhand_source', 'inventory_preparation_status': gate_status or 'blocked_retryable', }, } @@ -1216,14 +1216,14 @@ def _task_has_frozen_inventory_source(task: ShippingOrderTask) -> bool: """ 任务是否已冻结库存源候选(CandidateSet 已存在且至少有一个 Source)。 - 【AI 触发时机】:inventory_preparation Gate 执行前判断是否需要补做路由裁决。 + 【AI 触发时机】:onhand_preparation Gate 执行前判断是否需要补做路由裁决。 核心逻辑:统一以冻结 CandidateSet 为库存源真相;有候选源即视为已裁决/冻结, 没有则说明 routing Gate 虽被复核门禁同步判为 passed,但候选从未落库,需补裁决。 """ - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes - return bool(task_frozen_inventory_source_codes(task)) + return bool(task_frozen_onhand_source_codes(task)) def _resolve_shipping_notice(execution: ShippingProcessExecution) -> ShippingNotice | None: @@ -1247,8 +1247,8 @@ def _handle_reload_inventory_result( RPA 超时阻断,让用户明确选择“重新获取库存”或上传库存文件。 """ from app.models import ShippingNotice - from app.services.shipping_notice.inventory_rpa_workflow import _try_reuse_inventory_snapshot - from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source + from app.services.shipping_notice.onhand_rpa_workflow import _try_reuse_inventory_snapshot + from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source from app.services.shipping_notice.process_gate_bridge import ( inventory_preparation_reason_code, sync_fulfillment_gates_from_task, @@ -1260,7 +1260,7 @@ def _handle_reload_inventory_result( 'outcome': 'blocked_retryable', 'blocking_reason_code': 'inventory_preparation_failed', 'effective_result_json': {'findings': []}, - 'output_snapshot': {'action_code': 'reload_inventory_result', 'snapshot_found': False}, + 'output_snapshot': {'action_code': 'reload_onhand_result', 'snapshot_found': False}, } response = _try_reuse_inventory_snapshot( task, @@ -1280,7 +1280,7 @@ def _handle_reload_inventory_result( 'outcome': 'blocked_retryable', 'blocking_reason_code': inventory_preparation_reason_code(task), 'effective_result_json': {'findings': [], 'snapshot_found': False}, - 'output_snapshot': {'action_code': 'reload_inventory_result', 'snapshot_found': False}, + 'output_snapshot': {'action_code': 'reload_onhand_result', 'snapshot_found': False}, } sync_fulfillment_gates_from_task( execution=execution, @@ -1288,7 +1288,7 @@ def _handle_reload_inventory_result( actor_id=payload.get('actor_user_id'), ) return _tool_outcome( - action_code='reload_inventory_result', + action_code='reload_onhand_result', response=response, blocking_reason_code=inventory_preparation_reason_code(task), ) @@ -1304,7 +1304,7 @@ def _handle_retry_inventory_field_mapping( 重试库存字段映射:检查活跃库存文件 mapping_confirmed / 已解析行,不重跑库存准备。 """ from app.models import ShippingNotice - from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import active_inventory_file_for_task from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome task = _resolve_order_task(execution) @@ -1313,10 +1313,10 @@ def _handle_retry_inventory_field_mapping( 'outcome': 'blocked_retryable', 'blocking_reason_code': 'inventory_mapping_required', 'effective_result_json': {'findings': []}, - 'output_snapshot': {'action_code': 'retry_inventory_field_mapping'}, + 'output_snapshot': {'action_code': 'retry_onhand_field_mapping'}, } inv_file = active_inventory_file_for_task(task) - from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task + from app.services.shipping_notice.onhand_file_store import active_inventory_lines_for_task mapped = bool( inv_file is not None @@ -1325,7 +1325,7 @@ def _handle_retry_inventory_field_mapping( ) apply_gate_outcome( execution=execution, - gate_code='inventory_field_mapping', + gate_code='onhand_field_mapping', passed=mapped, # 映射来自已发布库存模板,缺失或不确定只能由系统重试/配置治理解决, # 不能把技术映射确认伪装为人工业务操作。 @@ -1345,13 +1345,13 @@ def _handle_retry_inventory_field_mapping( return { 'outcome': 'passed', 'effective_result_json': {'findings': [], 'mapping_confirmed': True}, - 'output_snapshot': {'action_code': 'retry_inventory_field_mapping', 'passed': True}, + 'output_snapshot': {'action_code': 'retry_onhand_field_mapping', 'passed': True}, } return { 'outcome': 'blocked_retryable', 'blocking_reason_code': 'inventory_mapping_required', 'effective_result_json': {'findings': []}, - 'output_snapshot': {'action_code': 'retry_inventory_field_mapping', 'passed': False}, + 'output_snapshot': {'action_code': 'retry_onhand_field_mapping', 'passed': False}, } @@ -1364,14 +1364,14 @@ def _handle_retry_inventory_from_field_mapping( """ 从库存字段映射恢复:失效匹配下游后重跑映射;映射通过后仍同 Attempt 嵌套匹配。 - Follow-up P1:映射 Attempt 应收口后仅 enqueue ``inventory_matching`` Attempt, + Follow-up P1:映射 Attempt 应收口后仅 enqueue ``onhand_matching`` Attempt, 禁止在本函数内直接调用 ``_handle_retry_inventory_matching``(跨 Gate 嵌套债务)。 """ from app.services.shipping_notice.recovery_invalidation_service import invalidate_inventory_downstream invalidate_inventory_downstream( execution=execution, - action_code='retry_inventory_from_field_mapping', + action_code='retry_onhand_from_field_mapping', attempt_id=payload.get('attempt_id'), actor_id=payload.get('actor_user_id'), ) @@ -1401,11 +1401,11 @@ def _handle_retry_inventory_matching( 核心逻辑:``match_inventory`` 的 ``needs_human`` 同时覆盖“匹配失败”和 “匹配成功但库存不足”。匹配成功但库存不足时,前置的 - ``sync_fulfillment_gates_from_task`` 已将缺口写入 inventory_sufficiency; - 当前 inventory_matching Attempt 必须以 passed 收口,否则会覆盖正确的 + ``sync_fulfillment_gates_from_task`` 已将缺口写入 onhand_sufficiency; + 当前 onhand_matching Attempt 必须以 passed 收口,否则会覆盖正确的 满足性 Gate 归属并再次显示“进入库存匹配处理”。 行级点击(line_scope_key/snapshot_line_id)走 match_inventory_line,并在回退 - ensure_inventory 时携带该行 source_codes。 + ensure_onhand 时携带该行 source_codes。 """ from app.services.shipping_notice.fulfillment_workflow import match_inventory, match_inventory_line from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task @@ -1438,7 +1438,7 @@ def _handle_retry_inventory_matching( sufficient = bool(task is not None and match_completed(task)) match_status = 'fulfillable' if sufficient else ('unfulfillable' if match_complete else '') has_shortage = match_complete and not sufficient - from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task shortage = [ row for row in load_current_match_facts_by_task(getattr(task, 'id', None)).values() @@ -1455,7 +1455,7 @@ def _handle_retry_inventory_matching( 'shortage': shortage, }, 'output_snapshot': { - 'action_code': 'retry_inventory_matching', + 'action_code': 'retry_onhand_matching', 'tool_status': 'passed', 'business_result': 'fulfillable', }, @@ -1473,13 +1473,13 @@ def _handle_retry_inventory_matching( 'shortage': shortage, }, 'output_snapshot': { - 'action_code': 'retry_inventory_matching', + 'action_code': 'retry_onhand_matching', 'tool_status': 'needs_human', 'business_result': 'inventory_shortage', }, } outcome = _tool_outcome( - action_code='retry_inventory_matching', + action_code='retry_onhand_matching', response=response, blocking_reason_code='inventory_match_failed', invalidate_change_type=None, @@ -1498,7 +1498,7 @@ def _handle_retry_inventory_from_matching( invalidate_inventory_downstream( execution=execution, - action_code='retry_inventory_from_matching', + action_code='retry_onhand_from_matching', attempt_id=payload.get('attempt_id'), actor_id=payload.get('actor_user_id'), ) @@ -1529,11 +1529,11 @@ def _handle_recheck_inventory_sufficiency( 'blocking_reason_code': 'inventory_insufficient', 'recommendation_json': {'navigation_action': 'open_shortage_review', 'dispatch_mode': 'navigate'}, 'effective_result_json': {'findings': []}, - 'output_snapshot': {'action_code': 'recheck_inventory_sufficiency'}, + 'output_snapshot': {'action_code': 'recheck_onhand_sufficiency'}, } # [BE-满足性复盘] 复核先按当前放行/匹配事实重算任务级履约态,避免"Gate 认为满足、 # 任务却仍标 unfulfillable/shortage"的旧状态残留。仅在确有匹配行时重算(空事实不误标缺货)。 - from app.models import ShippingNoticeLineInventoryMatch as _MatchRow + from app.models import ShippingNoticeLineOnhandMatch as _MatchRow if getattr(task, 'id', None) is not None and ( _MatchRow.query.filter_by(task_id=int(task.id), is_current=True).first() is not None @@ -1542,16 +1542,16 @@ def _handle_recheck_inventory_sufficiency( from app.services.shipping_notice.fulfillment_workflow import match_completed sufficient = match_completed(task) - from app.models import ShippingNoticeLineInventoryMatch + from app.models import ShippingNoticeLineOnhandMatch shortage = [ {'snapshot_line_id': row.snapshot_line_id, 'shortage_qty': row.shortage_qty} - for row in ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all() + for row in ShippingNoticeLineOnhandMatch.query.filter_by(task_id=int(task.id), is_current=True).all() if str(row.shortage_qty or '').strip() not in {'', '0', '0.0', '0.00'} ] match_status = 'fulfillable' if sufficient else 'unfulfillable' apply_gate_outcome( execution=execution, - gate_code='inventory_sufficiency', + gate_code='onhand_sufficiency', passed=sufficient, outcome=None if sufficient else 'blocked_manual', effective_result={ @@ -1569,14 +1569,14 @@ def _handle_recheck_inventory_sufficiency( return { 'outcome': 'passed', 'effective_result_json': {'findings': [], 'match_status': match_status}, - 'output_snapshot': {'action_code': 'recheck_inventory_sufficiency', 'passed': True}, + 'output_snapshot': {'action_code': 'recheck_onhand_sufficiency', 'passed': True}, } return { 'outcome': 'blocked_manual', 'blocking_reason_code': 'inventory_insufficient', 'recommendation_json': {'navigation_action': 'open_shortage_review', 'dispatch_mode': 'navigate'}, 'effective_result_json': {'findings': [], 'shortage': shortage}, - 'output_snapshot': {'action_code': 'recheck_inventory_sufficiency', 'passed': False}, + 'output_snapshot': {'action_code': 'recheck_onhand_sufficiency', 'passed': False}, } @@ -1786,7 +1786,7 @@ def _handle_inventory_reroute( from app.models import ShippingOrderReviewCase from app.services.shipping_notice.order_review_draft_service import reroute_inventory_routing - if gate.gate_code != 'inventory_source_routing': + if gate.gate_code != 'onhand_source_routing': raise ValidationError( 'Action does not belong to this gate', code='SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED', diff --git a/backend/app/services/shipping_notice/process_gate_job_service.py b/backend/app/services/shipping_notice/process_gate_job_service.py index ff00fd24..71cddbb2 100644 --- a/backend/app/services/shipping_notice/process_gate_job_service.py +++ b/backend/app/services/shipping_notice/process_gate_job_service.py @@ -75,7 +75,7 @@ def cancel_inventory_external_wait_polls(*, gate_id: int, reason: str) -> int: 其执行入口会再次读取 Gate 并自行停止。 Args: - gate_id: inventory_preparation Gate 主键。 + gate_id: onhand_preparation Gate 主键。 reason: 取消原因,写入 Job message 供审计排查。 Returns: @@ -238,13 +238,13 @@ def schedule_waiting_external_poll( execution = db.session.get(ShippingProcessExecution, int(gate.execution_id)) if execution is None: return None - if str(gate.gate_code or '').strip() == 'inventory_preparation' and execution.task_id: + if str(gate.gate_code or '').strip() == 'onhand_preparation' and execution.task_id: from app.models import ShippingNotice from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task from app.models import ShippingOrderTask task = db.session.get(ShippingOrderTask, int(execution.task_id)) - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task has_inventory_lines = bool(task is not None and has_ready_inventory_file_for_task(task)) if task is not None and has_inventory_lines: @@ -257,8 +257,8 @@ def schedule_waiting_external_poll( # 外部轮询超时是新的、可恢复的业务事实;不能保留原来的 # inventory_rpa_queued,否则页面会同时显示“等待外部”和“人工处理”。 timeout_reason = ( - 'inventory_rpa_timeout' - if str(gate.gate_code or '').strip() == 'inventory_preparation' + 'onhand_rpa_timeout' + if str(gate.gate_code or '').strip() == 'onhand_preparation' else (gate.blocking_reason_code or 'gate_invalidated') ) timeout_action = primary_next_action_for_gate( @@ -314,11 +314,11 @@ def schedule_waiting_external_poll( # (例如从 inventory_matching 回到 inventory_preparation)完成后,原 Gate # 可能短暂保留 waiting_external,但不能把准备阶段的轮询动作投递到该原 Gate; # 否则 executor 的归属校验会把过期 poll 误记为技术失败。 - if not action and str(gate.gate_code or '').strip() == 'inventory_preparation': - action = 'poll_inventory_preparation' + if not action and str(gate.gate_code or '').strip() == 'onhand_preparation': + action = 'poll_onhand_preparation' if ( - str(gate.gate_code or '').strip() != 'inventory_preparation' - and str(action or '').strip() == 'poll_inventory_preparation' + str(gate.gate_code or '').strip() != 'onhand_preparation' + and str(action or '').strip() == 'poll_onhand_preparation' ): _LOGGER.info( 'skip stale inventory-preparation poll: gate_id=%s gate_code=%s', @@ -344,7 +344,7 @@ def schedule_waiting_external_poll( execution = db.session.get(ShippingProcessExecution, int(gate.execution_id)) if execution is None: return None - if str(gate.gate_code or '').strip() == 'inventory_preparation': + if str(gate.gate_code or '').strip() == 'onhand_preparation': poll_count = int(effective.get('poll_count') or 0) + 1 effective['poll_count'] = poll_count gate.effective_result_json = effective @@ -391,7 +391,7 @@ def run_inventory_external_wait_poll(*, gate_id: int) -> dict[str, Any]: outcome = _handle_retry_inventory_preparation( execution=execution, gate=gate, - payload={'action_code': 'poll_inventory_preparation'}, + payload={'action_code': 'poll_onhand_preparation'}, ) db.session.flush() db.session.refresh(gate) diff --git a/backend/app/services/shipping_notice/process_gate_projection.py b/backend/app/services/shipping_notice/process_gate_projection.py index 933e53f7..91852971 100644 --- a/backend/app/services/shipping_notice/process_gate_projection.py +++ b/backend/app/services/shipping_notice/process_gate_projection.py @@ -49,7 +49,7 @@ _PROCESS_GATE_REVIEW_NAVIGATION_ACTIONS: frozenset[str] = frozenset({ 'confirm_customer', 'adjudicate_duplicate', 'resolve_field_conflicts', - 'open_inventory_match_review', + 'open_onhand_match_review', 'open_shortage_review', }) @@ -63,7 +63,7 @@ _ACTION_NAVIGATION_FOCUS: dict[str, str] = { 'confirm_customer': 'draft', 'adjudicate_duplicate': 'draft', 'resolve_field_conflicts': 'evidence', - 'open_inventory_match_review': 'draft', + 'open_onhand_match_review': 'draft', 'open_shortage_review': 'draft', } @@ -134,8 +134,8 @@ def _resolve_recovery_next_action( """ 单一裁决:由阻断原因码 / Gate 状态推导业务用户主恢复动作。 - [STEP 1] 库存 RPA 超时/耗尽下发 ``retry_inventory_matching``(优先复用已有快照重匹配, - 无快照则回退 RPA);其他库存准备失败下发 ``retry_inventory_preparation``,由用户明确重新触发 RPA。 + [STEP 1] 库存 RPA 超时/耗尽下发 ``retry_onhand_matching``(优先复用已有快照重匹配, + 无快照则回退 RPA);其他库存准备失败下发 ``retry_onhand_preparation``,由用户明确重新触发 RPA。 [STEP 2] 货代上传 RPA 失败保持 RPA 重试;人工交接只下发凭据登记入口。 [STEP 3] 其余沿用 Gate 合同默认 next_action(primary 或按 status 推导),并保留 RecoveryPlan 复核入口兜底;技术责任方的 retry_* 仍默认仅作系统执行动作。 @@ -148,27 +148,27 @@ def _resolve_recovery_next_action( has_formal_task = bool(execution and getattr(execution, 'task_id', None)) # [STEP 1] RPA 超时/耗尽时先重读已有结果,其他库存准备失败仍允许重新运行 RPA。 - if blocking_gate_code == 'inventory_preparation': + if blocking_gate_code == 'onhand_preparation': inventory_action = inventory_preparation_primary_action(status, normalized_reason) if inventory_action: return inventory_action, False # 库存匹配失败属于业务可恢复阻断;即使 Gate 责任方是 worker, # 业务用户仍必须能重新提交匹配,不能只投影“可重试”状态而隐藏按钮。 - if blocking_gate_code == 'inventory_matching' and ( + if blocking_gate_code == 'onhand_matching' and ( has_formal_task or status == 'blocked_retryable' ): - return 'retry_inventory_matching', False + return 'retry_onhand_matching', False # 库存不足只阻断履约决策,不能把已经确认的活动 Excel 误判为库存源失效。 # 因此默认复用该快照执行重匹配;用户若明确选择重新获取库存,再由 RecoveryPlan # 回到 inventory_preparation 强制触发 RPA。 if ( - blocking_gate_code == 'inventory_sufficiency' + blocking_gate_code == 'onhand_sufficiency' and has_formal_task and _has_confirmed_inventory_for_matching(execution) ): - return 'retry_inventory_matching', False + return 'retry_onhand_matching', False # [STEP 2] 货代上传 RPA 失败 / 人工交接失败:保持统一的 RPA 重试入口。 if ( @@ -203,15 +203,15 @@ def _resolve_recovery_next_action( # 正式 OT 的库存匹配只能重试,不能下发无写操作的复核导航入口。 if not next_action: recovery_targets = full.get('recovery_targets') or [] - if recovery_targets and blocking_gate_code == 'inventory_matching' and not has_formal_task: - next_action = 'open_inventory_match_review' + if recovery_targets and blocking_gate_code == 'onhand_matching' and not has_formal_task: + next_action = 'open_onhand_match_review' technical_auto_only = False - elif recovery_targets and blocking_gate_code == 'inventory_sufficiency': + elif recovery_targets and blocking_gate_code == 'onhand_sufficiency': next_action = 'open_shortage_review' technical_auto_only = False # 库存准备/匹配/货代上传 RPA 在 blocked_retryable 时仍允许业务用户恢复。 if not next_action and blocking_gate_code in { - 'inventory_preparation', 'inventory_matching', 'freight_upload_rpa', + 'onhand_preparation', 'onhand_matching', 'freight_upload_rpa', }: candidate = _projection_primary_next_action( gate_code=blocking_gate_code, status=status, @@ -531,7 +531,7 @@ def _has_confirmed_inventory_for_matching(execution: ShippingProcessExecution) - """判断正式任务是否已有可复用、未失效的已确认库存快照。""" if not execution.task_id: return False - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task task = ShippingOrderTask.query.get(int(execution.task_id)) return bool(task is not None and has_ready_inventory_file_for_task(task)) @@ -573,12 +573,12 @@ def _ensure_editable_row_source_actions( if not _row_source_editable(execution): return code = str(gate_code or '').strip().lower() - if code not in {'inventory_preparation', 'inventory_matching'}: + if code not in {'onhand_preparation', 'onhand_matching'}: return # 方案 3·放开:覆写(任意已启用源)作为**唯一**行源编辑动作;D5 的「选定」不再作为独立入口, # 多源歧义行也由覆写下拉承担(覆写接受任意已启用源),避免两处选源入口重复(问题 3/4)。 # retry_inventory_* 仍按其门禁语义在 blocking 分支授权,避免在推进态错误暴露重试入口。 - for side in ('override_line_inventory_source',): + for side in ('override_line_onhand_source',): if side not in allowed_actions and is_business_user_action(side): allowed_actions.append(side) @@ -630,12 +630,12 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, blocking = None if ( isinstance(current, dict) - and str(current.get('gate_code') or '').strip().lower() == 'inventory_matching' + and str(current.get('gate_code') or '').strip().lower() == 'onhand_matching' and str(current.get('status') or '').strip().lower() == 'pending' and _has_confirmed_inventory_for_matching(execution) ): # 库存快照已确认但匹配未落终态,说明自动推进已中断;不能继续显示系统处理中。 - current = {**current, 'status': 'blocked_retryable', 'next_action_code': 'retry_inventory_matching'} + current = {**current, 'status': 'blocked_retryable', 'next_action_code': 'retry_onhand_matching'} if current and current.get('status') in PROCESS_GATE_RECOVERABLE_STATUSES | { 'blocked_retryable', 'blocked_manual', 'waiting_external', 'failed_terminal', 'invalidated', }: @@ -686,23 +686,23 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, action_items: list[dict[str, str]] = [] is_formal_inventory_matching = bool( getattr(execution, 'task_id', None) - and str((blocking or {}).get('gate_code') or '').strip().lower() == 'inventory_matching' + and str((blocking or {}).get('gate_code') or '').strip().lower() == 'onhand_matching' ) is_formal_inventory_sufficiency = bool( getattr(execution, 'task_id', None) - and str((blocking or {}).get('gate_code') or '').strip().lower() == 'inventory_sufficiency' + and str((blocking or {}).get('gate_code') or '').strip().lower() == 'onhand_sufficiency' ) recovery_targets = full.get('recovery_targets') or [] if is_formal_inventory_matching: recovery_targets = [ target for target in recovery_targets - if str(target.get('action_code') or '').strip() == 'retry_inventory_from_preparation' + if str(target.get('action_code') or '').strip() == 'retry_onhand_from_preparation' ] elif is_formal_inventory_sufficiency: # Gate 16 对用户只公开稳定动作码:重匹配复用当前快照;重新获取库存才回到 RPA。 recovery_targets = [ target for target in recovery_targets - if str(target.get('action_code') or '').strip() == 'retry_inventory_preparation' + if str(target.get('action_code') or '').strip() == 'retry_onhand_preparation' ] # 一个 Notice 只能有一个 Excel;错误导出需要创建新的 Notice,而非替代旧 Artifact。 recovery_targets = [ diff --git a/backend/app/services/shipping_notice/process_gate_recovery_service.py b/backend/app/services/shipping_notice/process_gate_recovery_service.py index 845f8f63..8a82dcae 100644 --- a/backend/app/services/shipping_notice/process_gate_recovery_service.py +++ b/backend/app/services/shipping_notice/process_gate_recovery_service.py @@ -122,21 +122,21 @@ def _primary_recovery_action( *, execution: ShippingProcessExecution, gate: ShippingProcessGate, ) -> str | None: """按用户投影同一事实裁决当前 Gate 的可提交主恢复动作。""" - if gate.gate_code == 'inventory_preparation': + if gate.gate_code == 'onhand_preparation': return inventory_preparation_primary_action(gate.status, gate.blocking_reason_code) # 正式 OT 的库存匹配不再接受仅导航的旧 Gate 动作;历史行仍保留原值供审计。 - if gate.gate_code == 'inventory_matching' and execution.task_id: - return 'retry_inventory_matching' - if gate.gate_code == 'inventory_sufficiency' and execution.task_id: + if gate.gate_code == 'onhand_matching' and execution.task_id: + return 'retry_onhand_matching' + if gate.gate_code == 'onhand_sufficiency' and execution.task_id: from app.models import ShippingOrderTask - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task task = ShippingOrderTask.query.get(int(execution.task_id)) if ( task is not None and has_ready_inventory_file_for_task(task) ): - return 'retry_inventory_matching' + return 'retry_onhand_matching' return gate.next_action_code or primary_next_action_for_gate( gate_code=gate.gate_code, status=gate.status, ) @@ -196,6 +196,7 @@ def request_gate_action( 核心逻辑:校验 action 属于契约且与当前门禁主要动作一致(或为同门禁允许的附属动作); 创建 queued Attempt 后,同步动作立即 execute_queued_attempt,异步动作入队 Gate Job。 客户端禁止提交起始阶段/目标状态/Worker 名。 + retry_onhand_from_* 打在错误 Gate 上时返回 SHIPPING.RECOVERY_TARGET_INVALID。 Args: execution_no / gate_code: 定位目标。 @@ -246,7 +247,7 @@ def request_gate_action( # 跨阶段恢复目标先做 Gate 归属校验;错误 Gate 必须返回稳定的 # RECOVERY_TARGET_INVALID,而不是被普通技术动作权限错误遮蔽。 recovery_definition = recovery_plan_for_action(current_gate=gate.gate_code, action_code=action) - if action.startswith('retry_inventory_from_') and recovery_definition is None: + if action.startswith('retry_onhand_from_') and recovery_definition is None: raise ValidationError( 'Recovery target is not allowed for current gate', code='SHIPPING.RECOVERY_TARGET_INVALID', @@ -310,14 +311,14 @@ def request_gate_action( # 「重新匹配库存」用专用重匹配编排(只作废匹配下游、经 inventory_matching 重跑), # 避免走 execute_stage_capability 的「宽作废 + 重抓 RPA」,否则会错误重抓库存。 if stage_exempt: - if action == 'retry_inventory_matching': + if action == 'retry_onhand_matching': result = execute_stage_capability_rematch( execution=execution, actor_type=actor_type, actor_id=actor_id, idempotency_key=idempotency_key, ) - elif action == 'override_line_inventory_source': + elif action == 'override_line_onhand_source': # [ROOT CAUSE FIX] 行级覆写必须携带用户选定的 line_no/source_code;通用 # execute_stage_capability 不接收 payload 会丢弃这两个关键字段,导致「操作成功」 # 后选源不落库、不触发 RPA、刷新回原样。此处委托专门的负载透传执行器。 diff --git a/backend/app/services/shipping_notice/process_gate_service.py b/backend/app/services/shipping_notice/process_gate_service.py index 5080cb3b..9fef160e 100644 --- a/backend/app/services/shipping_notice/process_gate_service.py +++ b/backend/app/services/shipping_notice/process_gate_service.py @@ -953,10 +953,10 @@ def _abort_active_attempt_as_superseded( """把占位活动 Attempt 收口为 superseded,并将 Gate 复位为可重评状态。 触发时机:业务事实已判定为 passed,但该 Gate 上存在一个非本轮自动轮询、 - 且不能伪造成 passed 的并活动 Attempt(例如并发用户 override_line_inventory_source)。 + 且不能伪造成 passed 的并活动 Attempt(例如并发用户 override_line_onhand_source)。 仅将 Attempt 置为 superseded、清空租约,并把 Gate 状态回退到 pending,让下方 常规 queue+complete 写入 passed;否则静默丢弃 passed,或被该 Attempt 的后续失败 - 覆盖成 blocked_retryable(真实任务 SN-20260831-9F25A698 / inventory_matching 曾因此永卡失败态)。 + 覆盖成 blocked_retryable(真实任务 SN-20260831-9F25A698 / onhand_matching 曾因此永卡失败态)。 """ now = _utc_now() active_attempt.status = 'superseded' @@ -1090,8 +1090,8 @@ def _enqueue_auto_progress_after_gate_pass( """门禁通过后为绑定任务提交下一 Gate 的唯一 AutoProgress Attempt/Job。 核心逻辑:刷新指针后对「当前未通过 Gate」入队唯一 Attempt/Job。典型场景: - 人工指定库存源使 ``inventory_source_routing`` passed 后,下一道仍是 - ``pending`` 且 ``next_action_code`` 为空的 ``inventory_preparation``——必须在此 + 人工指定库存源使 ``onhand_source_routing`` passed 后,下一道仍是 + ``pending`` 且 ``next_action_code`` 为空的 ``onhand_preparation``——必须在此 补种首投动作并入队,按已冻结源取数,禁止静默 return 导致永久「库存文件未准备」。 """ try: @@ -1154,8 +1154,8 @@ def _enqueue_auto_progress_after_gate_pass( # 初次进入库存准备也使用 retry_inventory_preparation 执行器;仅当还未创建 # 本 Execution 的库存 RPA Attempt 时自动投递一次。失败后的同一动作保留人工重试, # 不能由 AutoProgress 无限重放。 - if next_gate.next_action_code == 'retry_inventory_preparation': - from app.models import ShippingTaskInventoryRpaAttempt + if next_gate.next_action_code == 'retry_onhand_preparation': + from app.models import FreightRpaOnhandTaskAttempt from app.models import ShippingOrderTask task = db.session.get(ShippingOrderTask, int(execution.task_id)) @@ -1164,7 +1164,7 @@ def _enqueue_auto_progress_after_gate_pass( return task_no = str(getattr(task, 'task_no', '') or '').strip() existing = ( - ShippingTaskInventoryRpaAttempt.query + FreightRpaOnhandTaskAttempt.query .filter_by(task_no=task_no) .first() if task_no else None @@ -1173,7 +1173,7 @@ def _enqueue_auto_progress_after_gate_pass( return if ( ( - next_gate.next_action_code in {'retry_inventory_matching'} + next_gate.next_action_code in {'retry_onhand_matching'} and not _auto_match_enabled() ) or ( @@ -1312,8 +1312,8 @@ def sync_gate_from_business_result( 核心逻辑:无活动 Attempt 时自动 queue+complete;用于业务接线接入统一服务。 已通过门禁在 allow_repass 时先置 invalidated 再重评(输入变化重跑)。 - 已有活动 Attempt 时:仅 auto poll_inventory_preparation 可提前收口; - 其余(含库存就绪的 retry_inventory_preparation)留给外层 Attempt 统一 complete。 + 已有活动 Attempt 时:仅 auto poll_onhand_preparation 可提前收口; + 其余(含库存就绪的 retry_onhand_preparation)留给外层 Attempt 统一 complete。 Args: invalidate_change_type: 通过后失效类型;None 时库存源路由默认 inventory_source_changed。 @@ -1358,7 +1358,7 @@ def sync_gate_from_business_result( ) is_auto_poll = ( active_attempt.trigger_type == 'auto' - and str(snapshot.get('action_code') or '').strip() == 'poll_inventory_preparation' + and str(snapshot.get('action_code') or '').strip() == 'poll_onhand_preparation' ) if is_auto_poll and passed: return complete_gate_attempt( @@ -1378,7 +1378,7 @@ def sync_gate_from_business_result( is_conflicting_user_line_action = ( active_attempt.trigger_type in {'user_manual', 'user_retry'} and str(snapshot.get('action_code') or '').strip() in { - 'override_line_inventory_source', + 'override_line_onhand_source', } ) if is_conflicting_user_line_action and passed: @@ -1430,7 +1430,7 @@ def sync_gate_from_business_result( 'blocked_manual' if blocking_reason_code else 'blocked_retryable' ) resolved_invalidate = invalidate_change_type - if resolved_invalidate is None and passed and gate_code == 'inventory_source_routing': + if resolved_invalidate is None and passed and gate_code == 'onhand_source_routing': resolved_invalidate = 'inventory_source_changed' return complete_gate_attempt( attempt_id=int(attempt.id), @@ -1475,7 +1475,7 @@ def execute_stage_capability( 核心步骤: [STEP 1] 作废下游门禁:按 inventory_source_changed 失效链重算(容量声明 invalidate - 时才作废;如 reload_inventory_result 声明为空集合则跳过,直接重读)。 + 时才作废;如 reload_onhand_result 声明为空集合则跳过,直接重读)。 [STEP 2] 重置执行指针:若有 reset_to,把 execution 拉回能力定义的起始 gate。 [STEP 3] 幂等重跑:解析 notice task_no 后调用 run_task_auto_progress 推进;失败判定 以返回值(status=failed / status=conflict)或异常为准,二者均置 reran=False @@ -1522,7 +1522,7 @@ def execute_stage_capability( # 用户点击「重新获取库存」必须作为定向人工恢复进入库存准备 Gate; # 否则 AutoProgress 会把历史 RPA 失败当作自动重试而拒绝入队。 resume_gate_code=str(reset_to or '').strip() or None, - inventory_mode='retry_rpa' if reset_to == 'inventory_preparation' else 'auto', + inventory_mode='retry_rpa' if reset_to == 'onhand_preparation' else 'auto', line_scope_key=str(line_scope_key).strip() or None, ) # run_task_auto_progress 对失败返回 dict(status=failed / status=conflict),并非抛异常; @@ -1561,7 +1561,7 @@ def execute_stage_capability_rematch( 【AI 触发时机】:通知准备阶段用户点击「重新匹配库存」(即使 Gate 已推进到满足性/Excel 生成) 时由 request_gate_action 调用;与 execute_stage_capability 的「宽作废 + 重抓」不同,此处 保留已抓取库存与字段映射,只作废匹配及下游(inventory_field_mapping_changed),再经 - inventory_matching Gate 的既有 Attempt 通道重跑匹配(match_inventory + 重同步满足性/Excel), + onhand_matching Gate 的既有 Attempt 通道重跑匹配(match_inventory + 重同步满足性/Excel), 避免错误重抓 RPA 或重做字段映射。 Args: @@ -1584,27 +1584,27 @@ def execute_stage_capability_rematch( )) match_gate = ( ShippingProcessGate.query - .filter_by(execution_id=int(execution.id), gate_code='inventory_matching') + .filter_by(execution_id=int(execution.id), gate_code='onhand_matching') .first() ) if match_gate is None: db.session.flush() return { 'invalidated_gates': invalidated, - 'reset_to': 'inventory_matching', + 'reset_to': 'onhand_matching', 'reran': False, 'reran_reason': 'inventory_matching_gate_missing', } attempt = queue_gate_attempt( execution_no=str(execution.execution_no), - gate_code='inventory_matching', + gate_code='onhand_matching', trigger_type='user_retry', actor_type=actor_type, actor_id=actor_id, idempotency_key=str(idempotency_key or ''), expected_gate_version=None, input_snapshot={ - 'action_code': 'retry_inventory_matching', + 'action_code': 'retry_onhand_matching', 'payload': { 'actor_user_id': actor_id, 'idempotency_key': str(idempotency_key or ''), @@ -1619,7 +1619,7 @@ def execute_stage_capability_rematch( db.session.flush() return { 'invalidated_gates': invalidated, - 'reset_to': 'inventory_matching', + 'reset_to': 'onhand_matching', 'reran': False, 'reran_reason': f'{type(exc).__name__}: {str(exc)[:200]}', } @@ -1628,7 +1628,7 @@ def execute_stage_capability_rematch( db.session.flush() return { 'invalidated_gates': invalidated, - 'reset_to': 'inventory_matching', + 'reset_to': 'onhand_matching', 'reran': reran, 'gate_status': updated_gate.status, 'current_gate_code': execution.current_gate_code, @@ -1647,13 +1647,13 @@ def execute_stage_capability_override_source( """执行「行级库存源覆写」阶段能力:作废库存下游 → 重置回准备 → 按用户所选源冻结该行并重跑。 【AI 触发时机】:通知准备阶段用户在某行「选择库存源」下拉选定后点击勾勾(提交 - override_line_inventory_source)时由 request_gate_action 调用。 + override_line_onhand_source)时由 request_gate_action 调用。 关键差异 / root cause 说明: - - `override_line_inventory_source` 是「行级」动作,必须携带用户选定的 ``line_no`` / + - `override_line_onhand_source` 是「行级」动作,必须携带用户选定的 ``line_no`` / ``source_code``;而通用 ``execute_stage_capability`` 的签名不接收 payload,会把这两个 关键字段静默丢弃,导致「操作成功」弹窗后选源既不落库、也不触发 RPA、刷新回原样。 - - 本函数保留通用能力「作废下游 + 重置回 inventory_preparation + 幂等重跑」的语义, + - 本函数保留通用能力「作废下游 + 重置回 onhand_preparation + 幂等重跑」的语义, 但把选源通过 executor 的 ``_handle_override_line_inventory_source`` 真正冻结到 CandidateSet(freeze_manual_line_source_selection),再交由 run_task_auto_progress 按新候选重取/匹配库存,从而让 RPA 正常触发。 @@ -1678,10 +1678,10 @@ def execute_stage_capability_override_source( actor_type=actor_type, actor_id=actor_id, # 重新获取库存的起始 Gate 必须保留为可执行状态;只作废其下游。 - exclude_gate_codes={'inventory_preparation'} - {''}, + exclude_gate_codes={'onhand_preparation'} - {''}, )) - # 与 STAGE_CAPABILITY_DEFINITIONS['override_line_inventory_source'] 保持一致。 - execution.current_gate_code = 'inventory_preparation' + # 与 STAGE_CAPABILITY_DEFINITIONS['override_line_onhand_source'] 保持一致。 + execution.current_gate_code = 'onhand_preparation' prepared_payload = dict(payload or {}) prepared_payload.setdefault('idempotency_key', str(idempotency_key or '')) try: @@ -1694,7 +1694,7 @@ def execute_stage_capability_override_source( idempotency_key=str(idempotency_key or ''), expected_gate_version=None, input_snapshot={ - 'action_code': 'override_line_inventory_source', + 'action_code': 'override_line_onhand_source', 'payload': prepared_payload, }, ) @@ -1704,7 +1704,7 @@ def execute_stage_capability_override_source( db.session.flush() return { 'invalidated_gates': invalidated, - 'reset_to': 'inventory_preparation', + 'reset_to': 'onhand_preparation', 'reran': False, 'reran_reason': f'{type(exc).__name__}: {str(exc)[:200]}', } @@ -1712,7 +1712,7 @@ def execute_stage_capability_override_source( db.session.flush() return { 'invalidated_gates': invalidated, - 'reset_to': 'inventory_preparation', + 'reset_to': 'onhand_preparation', 'reran': reran, 'gate_status': updated_gate.status, 'current_gate_code': execution.current_gate_code, diff --git a/backend/app/services/shipping_notice/processing_projection_invariants.py b/backend/app/services/shipping_notice/processing_projection_invariants.py index 35a3e855..9bb468bd 100644 --- a/backend/app/services/shipping_notice/processing_projection_invariants.py +++ b/backend/app/services/shipping_notice/processing_projection_invariants.py @@ -42,10 +42,10 @@ _WRITE_ACTION_CODES = frozenset({ 'adjudicate_duplicate', 'reconcile_and_progress', 'open_profile_review', - 'open_inventory_match_review', + 'open_onhand_match_review', 'open_shortage_review', - 'upload_inventory_file', - 'retry_inventory_preparation', + 'upload_onhand_file', + 'retry_onhand_preparation', 'retry_parse', 'retry_failed_documents', 'regenerate_excel', @@ -58,9 +58,9 @@ _WRITE_ACTION_CODES = frozenset({ # 建单前禁止下发的履约写动作(匹配 / Excel / 上传等)。 _POST_CREATE_ONLY_ACTION_CODES = frozenset({ - 'open_inventory_match_review', + 'open_onhand_match_review', 'open_shortage_review', - 'upload_inventory_file', + 'upload_onhand_file', 'regenerate_excel', 'download_excel', 'open_manual_upload', @@ -68,8 +68,8 @@ _POST_CREATE_ONLY_ACTION_CODES = frozenset({ _POST_CREATE_STAGES = frozenset({ 'order_creating', - 'inventory_fetching', - 'inventory_matching', + 'onhand_fetching', + 'onhand_matching', 'excel_generating', 'freight_uploading', 'completed', @@ -89,8 +89,8 @@ _ACTION_CODE_ALIASES: dict[str, str] = { 'mark_manual_uploaded': 'open_manual_upload', 'regenerate_manual_upload_todo': 'open_manual_upload', # [BE-05] Notice ui_state / Gate 业务动作收口到统一契约意图。 - 'rematch': 'open_inventory_match_review', - 'match_inventory': 'open_inventory_match_review', + 'rematch': 'open_onhand_match_review', + 'match_inventory': 'open_onhand_match_review', 'generate_excel': 'regenerate_excel', 'confirm_inventory_source': 'open_inventory_source_review', # 正式 Process Gate 动作投影到旧工作台的同一业务意图;真实写动作仍由 @@ -196,8 +196,8 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]: 核心逻辑:仅可审计的上传成功 → completed;上传中、待登记及历史无证据上传 → freight_uploading; - 导出/Excel → excel_generating;waiting_inventory/parsed → inventory_fetching; - matching/inventory_ready/matched → inventory_matching;建单中 → order_creating。 + 导出/Excel → excel_generating;waiting_inventory/parsed → onhand_fetching; + matching/inventory_ready/matched → onhand_matching;建单中 → order_creating。 领域映射唯一来源,禁止写状态机反向依赖投影私有函数。 Args: @@ -221,7 +221,7 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]: export_path = '' projected_upload = None try: - from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task match = str(aggregate_match_status_for_task(int(owner.id)) or '').strip().lower() if owner.id else '' from app.services.shipping_notice.upload_attempt_service import ( latest_export_artifact, @@ -270,20 +270,20 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]: if ps == 'matched' and export_path: return ('automating', 'excel_generating') - if ps in {'matching', 'inventory_ready', 'matched'} or step == 'inventory_matching': - return ('automating', 'inventory_matching') + if ps in {'matching', 'inventory_ready', 'matched'} or step == 'onhand_matching': + return ('automating', 'onhand_matching') # 正式建单后的库存获取:waiting_inventory / parsed → 获取库存(禁止仍映射到 matching)。 - if ps in {'waiting_inventory', 'parsed'} or step == 'inventory_fetching': - return ('automating', 'inventory_fetching') + if ps in {'waiting_inventory', 'parsed'} or step == 'onhand_fetching': + return ('automating', 'onhand_fetching') if ps == 'pending_review': return ('waiting_review', 'waiting_review') if ps in {'creating', 'order_creating', 'confirming'} or step == 'order_creating': return ('automating', 'order_creating') - if ps in {'fetching_inventory', 'inventory_fetching'}: - return ('automating', 'inventory_fetching') + if ps in {'fetching_inventory', 'onhand_fetching'}: + return ('automating', 'onhand_fetching') if ps in {'parsing', 'parsed_pending'}: return ('automating', 'order_creating') # [BE-03] 未知状态 fail-closed:禁止猜测为正常「创建订单中」。 @@ -560,11 +560,11 @@ def reconcile_processing_projection_facts( gate_stage = { # 正式 20-Gate 进入履约后,兼容 OT 字段可能尚未被旧写路径同步。 # 读投影必须以 Gate 统一覆盖,避免历史 waiting_review 重新污染批次中心。 - 'inventory_source_routing': 'inventory_source_resolving', - 'inventory_preparation': 'inventory_fetching', - 'inventory_field_mapping': 'inventory_fetching', - 'inventory_matching': 'inventory_matching', - 'inventory_sufficiency': 'inventory_matching', + 'onhand_source_routing': 'onhand_source_resolving', + 'onhand_preparation': 'onhand_fetching', + 'onhand_field_mapping': 'onhand_fetching', + 'onhand_matching': 'onhand_matching', + 'onhand_sufficiency': 'onhand_matching', 'excel_readiness': 'excel_generating', 'artifact_generation': 'excel_generating', 'freight_upload_rpa': 'freight_uploading', @@ -687,8 +687,8 @@ _USER_STAGE_TO_CODE: dict[str, str] = { 'document_parsing': 'document_parsing', 'order_creating': 'order_creating', 'waiting_review': 'waiting_human_review', - 'inventory_fetching': 'inventory_fetch', - 'inventory_matching': 'inventory_match', + 'onhand_fetching': 'inventory_fetch', + 'onhand_matching': 'inventory_match', 'excel_generating': 'excel_generate', 'freight_uploading': 'freight_upload', 'completed': 'completed', @@ -851,9 +851,9 @@ def apply_user_projection_fields( if user_stage is None: if old_stage in {'document_parsing', 'order_creating'}: user_stage = 'document_parsing' - elif old_stage in {'inventory_fetching'}: + elif old_stage in {'onhand_fetching'}: user_stage = 'inventory_fetch' - elif old_stage in {'inventory_matching'}: + elif old_stage in {'onhand_matching'}: user_stage = 'inventory_match' elif old_stage in {'excel_generating'}: user_stage = 'excel_generate' @@ -980,9 +980,9 @@ def apply_user_projection_fields( # ===== [STEP 7] 计算 primary_action: {code, i18n_key, parameters} 或 None ===== _ACTION_CODE_TO_GATE_I18N_KEY: dict[str, str] = { - 'retry_inventory_preparation': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation', - 'retry_inventory_matching': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryMatching', - 'open_inventory_match_review': 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview', + 'retry_onhand_preparation': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation', + 'retry_onhand_matching': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryMatching', + 'open_onhand_match_review': 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview', 'open_order_review': 'workspace.shippingNotice.processGate.actionCodes.open_order_review', 'retry_freight_upload_rpa': 'workspace.shippingNotice.processGate.actionCodes.retry_freight_upload_rpa', 'regenerate_excel': 'workspace.shippingNotice.processGate.actionCodes.regenerate_excel_artifact', @@ -991,8 +991,8 @@ def apply_user_projection_fields( 'open_profile_review': 'workspace.shippingNotice.processGate.actionCodes.open_profile_review', } _ACTION_CODE_TO_CHAT_I18N_FALLBACK: dict[str, str] = { - 'retry_inventory_preparation': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation', - 'open_inventory_match_review': 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview', + 'retry_onhand_preparation': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation', + 'open_onhand_match_review': 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview', 'open_order_review': 'chat.shippingProcessing.action.open_order_review', 'retry_freight_upload_rpa': 'chat.shippingProcessing.action.retry_freight_upload_rpa', 'match_inventory': 'chat.shippingProcessing.action.match_inventory', @@ -1031,7 +1031,7 @@ def apply_user_projection_fields( # waiting_human 仅按 Gate/领域阻断映射精确业务入口。 if user_status == 'waiting_human': if bcode in {'inventory_shortage', 'inventory_multi_file_conflict', 'inventory_source_conflict'}: - code = 'open_inventory_match_review' + code = 'open_onhand_match_review' return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} if bcode in {'order_review_required', 'freeze_not_ready'}: code = 'open_order_review' @@ -1113,11 +1113,11 @@ def apply_user_projection_fields( # 仅依据正式 current_gate 的顺序和已投影事实派生,避免重新引入 APX 六 Gate。 gate_code = str((payload.get('current_gate') or {}).get('gate_code') or '').strip() gate_order = { - 'inventory_source_routing': 0, - 'inventory_preparation': 1, - 'inventory_field_mapping': 2, - 'inventory_matching': 3, - 'inventory_sufficiency': 4, + 'onhand_source_routing': 0, + 'onhand_preparation': 1, + 'onhand_field_mapping': 2, + 'onhand_matching': 3, + 'onhand_sufficiency': 4, 'excel_readiness': 5, 'artifact_generation': 6, 'manual_upload_handoff': 7, @@ -1138,7 +1138,7 @@ def apply_user_projection_fields( # 正式 OT 的库存事实只从 CandidateSet、Preparation/Link/File、LineMatch 与 Gate # 读取;step_payload_json 不再作为库存运行事实或恢复动作来源。 try: - from app.services.shipping_notice.inventory_candidate_projection import ( + from app.services.shipping_notice.onhand_candidate_projection import ( project_inventory_candidate_facts, ) candidate_facts = project_inventory_candidate_facts(order_task) @@ -1163,8 +1163,8 @@ def apply_user_projection_fields( payload['projection_data_inconsistent'] = True # P0-2:逐源 Attempt 执行事实只读投影,前端不得从旧 status 猜测。 try: - from app.models import ShippingTaskInventoryRpaAttempt - attempts = ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=str(getattr(order_task or notice, 'task_no', '') or '')).all() + from app.models import FreightRpaOnhandTaskAttempt + attempts = FreightRpaOnhandTaskAttempt.query.filter_by(task_no=str(getattr(order_task or notice, 'task_no', '') or '')).all() facts['rpa_attempts'] = [{ 'source_code': a.source_code, 'attempt_no': a.attempt_no, 'source_run_no': a.source_run_no, 'status': a.status, diff --git a/backend/app/services/shipping_notice/progress_audit_contract.py b/backend/app/services/shipping_notice/progress_audit_contract.py index c2c6a03b..bfda969f 100644 --- a/backend/app/services/shipping_notice/progress_audit_contract.py +++ b/backend/app/services/shipping_notice/progress_audit_contract.py @@ -41,7 +41,7 @@ WORKFLOW_ITEM_LIFECYCLE_STATUSES: Final[frozenset[str]] = frozenset({ 'extracting', 'pending_review', 'building_order', - 'inventory_matching', + 'onhand_matching', 'generating_excel', 'manual_upload_pending', 'reparse_failed', @@ -242,11 +242,11 @@ SHIPPING_PROCESSING_STAGES: Final[tuple[str, ...]] = ( 'candidate_creating', 'customer_resolving', 'duplicate_checking', - 'inventory_source_resolving', + 'onhand_source_resolving', 'waiting_review', 'order_creating', - 'inventory_fetching', - 'inventory_matching', + 'onhand_fetching', + 'onhand_matching', 'excel_generating', 'freight_uploading', 'completed', @@ -283,11 +283,11 @@ SHIPPING_PROCESSING_ACTION_INTENTS: Final[tuple[str, ...]] = ( 'resolve_field_conflicts', 'adjudicate_duplicate', 'open_inventory_source_review', - 'open_inventory_match_review', + 'open_onhand_match_review', 'open_shortage_review', - 'upload_inventory_file', - 'retry_inventory_preparation', - 'retry_inventory_matching', + 'upload_onhand_file', + 'retry_onhand_preparation', + 'retry_onhand_matching', 'retry_parse', 'retry_failed_documents', 'retry_failed_attachments', @@ -916,7 +916,7 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({ 'path_id_hash', 'revision_no', # 独立收料报表配置快照:路径与受控条件(含 Warehouse 拆分条件)均不含 selector、凭据、日期筛选或启停字段。 - 'inventory_source_id', + 'source_id', 'connector_type', 'config_version', 'report_path_json', @@ -987,11 +987,11 @@ I18N_KEY_INVENTORY: Final[tuple[str, ...]] = ( 'chat.shippingProcessing.stage.candidate_creating', 'chat.shippingProcessing.stage.customer_resolving', 'chat.shippingProcessing.stage.duplicate_checking', - 'chat.shippingProcessing.stage.inventory_source_resolving', + 'chat.shippingProcessing.stage.onhand_source_resolving', 'chat.shippingProcessing.stage.waiting_review', 'chat.shippingProcessing.stage.order_creating', - 'chat.shippingProcessing.stage.inventory_fetching', - 'chat.shippingProcessing.stage.inventory_matching', + 'chat.shippingProcessing.stage.onhand_fetching', + 'chat.shippingProcessing.stage.onhand_matching', 'chat.shippingProcessing.stage.excel_generating', 'chat.shippingProcessing.stage.freight_uploading', 'chat.shippingProcessing.stage.completed', @@ -1004,9 +1004,9 @@ I18N_KEY_INVENTORY: Final[tuple[str, ...]] = ( 'chat.shippingProcessing.action.none', 'chat.shippingProcessing.action.open_order_review', 'chat.shippingProcessing.action.edit_formal_task', - 'chat.shippingProcessing.action.open_inventory_match_review', + 'chat.shippingProcessing.action.open_onhand_match_review', 'chat.shippingProcessing.action.open_shortage_review', - 'chat.shippingProcessing.action.upload_inventory_file', + 'chat.shippingProcessing.action.upload_onhand_file', 'chat.shippingProcessing.action.retry', 'chat.shippingProcessing.action.refresh', 'chat.shippingProcessing.action.regenerate_excel', diff --git a/backend/app/services/shipping_notice/progress_workflow.py b/backend/app/services/shipping_notice/progress_workflow.py index c312255b..5aba8258 100644 --- a/backend/app/services/shipping_notice/progress_workflow.py +++ b/backend/app/services/shipping_notice/progress_workflow.py @@ -2,14 +2,14 @@ services/shipping_notice/progress_workflow.py 用途:承接发货通知任务的自动推进提交,包括解析确认检查、正式库存准备与履约侧串联。 -依赖:customer_identity_gate、tool_common、query_service、inventory_workflow、fulfillment_workflow、 +依赖:customer_identity_gate、tool_common、query_service、onhand_workflow、fulfillment_workflow、 process_gate_contract.derive_user_mode、ui_state._process_gate_user_summary_for_task、 state_machine(双读回退)、tool_response、process_gate_bridge。 逻辑:由 task_workflow / 复核确认 / STP 直通落库对外转调本文件;P0-3 起正式入口只提交 当前最早未通过 Gate,Worker 负责单 Gate 执行与下一 Job 的事务性入队;历史私有实现暂保留 供兼容调用方,但不得再由本 facade 直接跨 Gate 调度; 早停粗分类优先 Gate derive_user_mode,无 Execution 时回退 resolve_task_ui_state; - inventory_preparation 的 retryable_tech 阻断不早停,交给 ensure_inventory(复用快照或 RPA)。 + onhand_preparation 的 retryable_tech 阻断不早停,交给 ensure_onhand(复用快照或 RPA)。 """ from __future__ import annotations @@ -29,11 +29,11 @@ from app.services.shipping_notice.constants import ( RS_PARSE_REVIEW, RS_RSV_REQ, ) -from app.services.shipping_notice.inventory_source_gate import ( +from app.services.shipping_notice.onhand_source_gate import ( is_inventory_source_stable, ensure_inventory_source_review_state, ) -from app.services.shipping_notice.inventory_workflow import ensure_inventory as _legacy_ensure_inventory +from app.services.shipping_notice.onhand_workflow import ensure_inventory as _legacy_ensure_inventory from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool from app.services.shipping_notice.state_machine import resolve_task_ui_state from app.services.shipping_notice.tool_common import auto_progress_enabled, log_task_event @@ -46,8 +46,8 @@ def _entry_user_mode(task) -> str: 自动推进入口早停:从 Gate 推导用户处置模式。 无活动 Execution 时回退 resolve_task_ui_state.user_mode。 - inventory_preparation 上 retryable_tech 阻断(如尚未取到库存文件)由 Worker - 继续走 ensure_inventory(先复用未过期快照,否则触发 RPA),不得判 must_human 早停。 + onhand_preparation 上 retryable_tech 阻断(如尚未取到库存文件)由 Worker + 继续走 ensure_onhand(先复用未过期快照,否则触发 RPA),不得判 must_human 早停。 """ from app.services.shipping_notice.process_gate_contract import ( derive_user_mode, @@ -73,7 +73,7 @@ def _entry_user_mode(task) -> str: # blocked_retryable + inventory_file_empty;契约上属 retryable_tech,应由 # submit_auto_progress 入队 ensure_inventory,而不是入口 must_human 停机。 if ( - gate_code == 'inventory_preparation' + gate_code == 'onhand_preparation' and status == 'blocked_retryable' and user_mode_for_blocking_reason(reason_code) == 'retryable_tech' ): @@ -131,10 +131,10 @@ def _entry_position(task) -> str | None: # --------------------------------------------------------------------------- _RESUME_GATE_CODE_LEGACY_ENTRY = { - # inventory_preparation → 调 inventory_workflow.ensure_inventory 逻辑(复用旧实现) - 'inventory_preparation': 'ensure_inventory', + # inventory_preparation → 调 onhand_workflow.ensure_inventory 逻辑(复用旧实现) + 'onhand_preparation': 'ensure_onhand', # inventory_matching → 调 fulfillment_workflow.match_inventory(整单)或 match_inventory_line(行级,需 line_scope_key=订单项次) - 'inventory_matching': 'match_inventory', + 'onhand_matching': 'match_inventory', # None 或 'auto' → 走完整 auto_progress 串联链(解析→库存→匹配→导出→上传) 'auto': 'auto_progress_full', None: 'auto_progress_full', @@ -223,18 +223,18 @@ def _dispatch_legacy_orchestration( 'resume_gate_code': resume_gate_code, 'mode': inventory_mode, } - if entry == 'ensure_inventory': + if entry == 'ensure_onhand': # [T4 集成] 库存准备:如果存在 per-source 候选冻结,优先走 per_source_rpa_service 逐源准备 from app.services.shipping_notice.per_source_rpa_service import ensure_all_required_sources_prepared - from app.services.shipping_notice.stp_inventory_freeze import ( - task_frozen_inventory_source_codes, + from app.services.shipping_notice.stp_onhand_freeze import ( + task_frozen_onhand_source_codes, ) - frozen_sources = task_frozen_inventory_source_codes(task) + frozen_sources = task_frozen_onhand_source_codes(task) if frozen_sources and len(frozen_sources) >= 1: scoped_source_codes: list[str] | None = None scope_key = str(line_scope_key or '').strip() if scope_key: - from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines + from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_lines try: scoped_line_id = int(scope_key) @@ -342,7 +342,7 @@ def run_task_auto_progress( """ 唯一 AutoProgress Orchestrator Facade。 【AI 触发时机】:所有需要推进发货任务状态的入口(Tool API、Batch Orchestrator、Retry Decision、 - Gate Handler post-action)均应调用本函数;禁止直接调 inventory_workflow.ensure_inventory + Gate Handler post-action)均应调用本函数;禁止直接调 onhand_workflow.ensure_onhand 或 fulfillment_workflow.match_inventory 绕过并发锁。 核心步骤: @@ -777,7 +777,7 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: ) # [STEP 2] 保证库存已经就绪(仅复用已有库存快照;不得隐式触发库存 RPA)。 - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task if not has_ready_inventory_file_for_task(task): lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip() inv_payload: dict[str, Any] = {"task_id": task.task_no, "mode": "auto"} diff --git a/backend/app/services/shipping_notice/query_service.py b/backend/app/services/shipping_notice/query_service.py index 683fb292..24bf903b 100644 --- a/backend/app/services/shipping_notice/query_service.py +++ b/backend/app/services/shipping_notice/query_service.py @@ -3,7 +3,7 @@ services/shipping_notice/query_service.py 用途:发货通知读模型 — 任务查询、排序与序列化投影(含版本链、待办分类与任务中心字段)。 依赖:ShippingOrderCandidate、ShippingNotice、ShippingTaskEvent、 - ShippingReservation、ShippingNoticeLine、ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、ShippingOrderProcessingRun、 + ShippingReservation、ShippingNoticeLine、ShippingNoticeLineOnhandMatch、ShippingOrderReviewCase、ShippingOrderProcessingRun、 ShippingOrderIntake / ShippingOrderProcessingRunIntake / FileAsset、state_machine、动态订单字段编辑器、 order_review_projection(任务中心 STP retry 动作投影)。 逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块; @@ -43,8 +43,8 @@ from app.models import ( FileAsset, ShippingExportArtifact, ShippingExportArtifactLine, - ShippingInventoryVerification, - ShippingInventoryFile, + ShippingOnhandVerification, + FreightRpaOnhandReportFile, ShippingOrderCandidate, ShippingOrderDocument, ShippingOrderIntake, @@ -64,9 +64,9 @@ from app.models import ( ShippingCustomerShadowResolution, ShippingProcessExecution, ShippingProcessGate, - ShippingTaskInventoryLink, + ShippingTaskOnhandLink, ShippingNoticeLine, - ShippingNoticeLineInventoryMatch, + ShippingNoticeLineOnhandMatch, ShippingTaskEvent, ShippingUploadAttempt, ) @@ -125,9 +125,9 @@ _REVIEW_TODO_GATE_CODES = frozenset({ 'reservation_validation', }) _EXCEPTION_TODO_GATE_CODES = frozenset({ - 'inventory_sufficiency', + 'onhand_sufficiency', 'freight_upload_rpa', - 'inventory_source_routing', + 'onhand_source_routing', 'excel_readiness', }) _RUNNING_EXECUTION_STATUSES = frozenset({'active', 'waiting_external'}) @@ -281,8 +281,8 @@ class TaskProjection(str, Enum): def _fulfillment_timeline(task: ShippingNotice) -> dict[str, list[dict[str, Any]]]: """为工作台投影库存核验、滚动 Artifact 与上传 Attempt,所有事实只读且按时间排序。""" inventory_task_id = int(getattr(task, 'order_task_id', None) or task.id) - verifications = ShippingInventoryVerification.query.filter_by(task_id=inventory_task_id).order_by( - ShippingInventoryVerification.created_at, ShippingInventoryVerification.id, + verifications = ShippingOnhandVerification.query.filter_by(task_id=inventory_task_id).order_by( + ShippingOnhandVerification.created_at, ShippingOnhandVerification.id, ).all() artifacts = [] if isinstance(task, ShippingNotice): @@ -307,7 +307,7 @@ def _fulfillment_timeline(task: ShippingNotice) -> dict[str, list[dict[str, Any] ).order_by(ShippingUploadAttempt.created_at, ShippingUploadAttempt.id).all() if artifact_ids else [] return { 'inventory_verifications': [{ - 'id': item.id, 'status': item.status, 'inventory_snapshot_id': item.inventory_snapshot_id, + 'id': item.id, 'status': item.status, 'inventory_snapshot_id': item.onhand_snapshot_id, 'source_config_version': item.source_config_version, 'created_at': item.created_at.isoformat() if item.created_at else None, 'lines': [{ 'reservation_id': reservation_ids.get(int(line.reservation_id), str(line.reservation_id)), 'required_qty': str(line.required_qty), @@ -486,7 +486,7 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]: """Tool data 基础字段(裁剪前)。""" if isinstance(task, ShippingOrderTask): header, lines, _field_display = _order_values_for_projection(task) - from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task match_facts = list(load_current_match_facts_by_task(task.id).values()) customer = _order_task_customer_projection(task) @@ -517,10 +517,10 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]: 'conversation_id': task.conversation_id, 'step_payload': task.step_payload_json or {}, **inventory, - 'inventory_snapshot': _serialize_inventory_snapshot(task), + 'onhand_snapshot': _serialize_inventory_snapshot(task), } from app.services.shipping_notice.notice_upload import max_notice_chars - from app.services.shipping_notice.rpa import rpa_runtime_mode + from app.services.freight_rpa.common.rpa_runtime import rpa_runtime_mode workflow_owner = ( db.session.get(ShippingOrderTask, int(task.order_task_id)) @@ -560,9 +560,9 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]: } raw_content = str(getattr(workflow_owner, 'raw_content', None) or "").strip() lines = payload["lines"] - from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link + from app.services.shipping_notice.onhand_snapshot_store import serialize_inventory_snapshot_link - payload["inventory_snapshot"] = serialize_inventory_snapshot_link(task) + payload["onhand_snapshot"] = serialize_inventory_snapshot_link(task) # Dify 画布 LLM 字段抽取需要正文;已落库订单行后不再重复下发全文。 if raw_content and not lines: limit = max_notice_chars() @@ -574,7 +574,7 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]: def _current_match_projection(task: ShippingNotice | ShippingOrderTask) -> dict[str, Any]: """从关联 OT 的行级 Match 生成通知准备读模型,禁止读取 Notice 聚合缓存。""" - from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None) rows = list(load_current_match_facts_by_task(task_id).values()) @@ -652,7 +652,7 @@ def _order_values_for_projection(task: ShippingOrderTask | ShippingNotice) -> tu def _serialize_inventory_snapshot(task: ShippingNotice) -> dict[str, Any] | None: """工作台任务摘要中的库存快照投影。""" - from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link + from app.services.shipping_notice.onhand_snapshot_store import serialize_inventory_snapshot_link return serialize_inventory_snapshot_link(task) @@ -675,7 +675,7 @@ def _order_task_customer_projection(task: ShippingOrderTask) -> dict[str, Any]: def _order_task_inventory_projection(task: ShippingOrderTask) -> dict[str, Any]: """从 CandidateSet 与行级 Match 读取 OT 库存路由投影,禁止读 OT 旧列。""" - from app.services.shipping_notice.inventory_candidate_projection import project_inventory_candidate_facts + from app.services.shipping_notice.onhand_candidate_projection import project_inventory_candidate_facts facts = project_inventory_candidate_facts(task) sources = list(facts.get('sources') or []) @@ -787,7 +787,7 @@ def _serialize_source_candidate_projection(task: ShippingNotice) -> dict[str, An def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str, Any]: """按投影类型序列化任务;TOOL 会剔除 Agent 不应复述的内部状态码。""" - from app.services.shipping_notice.rpa import rpa_runtime_mode + from app.services.freight_rpa.common.rpa_runtime import rpa_runtime_mode workflow_owner = ( db.session.get(ShippingOrderTask, int(task.order_task_id)) @@ -816,7 +816,7 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str for result in (task_disposition_capability(task, action),) } step_payload = task.step_payload_json or {} - from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task match_facts = list(load_current_match_facts_by_task(task.id).values()) from app.services.shipping_notice.process_gate_projection import task_blocking_reason @@ -852,7 +852,7 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str 'destination_country': header.get('destination_country'), 'warehouse_hint': header.get('warehouse_hint'), **inventory, - 'inventory_snapshot': _serialize_inventory_snapshot(task), + 'onhand_snapshot': _serialize_inventory_snapshot(task), 'shortage': {'lines': [row for row in match_facts if str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'}]}, 'line_results': match_facts, 'order_snapshot_id': getattr(workflow_owner, 'order_snapshot_id', None), @@ -864,13 +864,13 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str workflow_payload = getattr(workflow_owner, 'step_payload_json', None) or {} step_payload = workflow_payload header = current_header_field_values_or_empty(workflow_owner) - from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.onhand_candidate_projection import active_inventory_runtime_facts + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes inventory_facts = active_inventory_runtime_facts(workflow_owner) - source_codes = task_frozen_inventory_source_codes(workflow_owner) + source_codes = task_frozen_onhand_source_codes(workflow_owner) routing = (getattr(inventory_facts.get('candidate_set'), 'routing_rule_version_json', None) or {}) - from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task match_task_id = getattr(workflow_owner, 'id', None) or task.id match_facts = list(load_current_match_facts_by_task(match_task_id).values()) match_status_projection = ( @@ -931,7 +931,7 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str "inventory_source_method": routing.get('adjudication_method'), "inventory_source_config_version": inventory_facts.get('source_config_version'), "inventory_routing_fingerprint": routing.get('routing_fingerprint'), - "inventory_snapshot": _serialize_inventory_snapshot(workflow_owner), + "onhand_snapshot": _serialize_inventory_snapshot(workflow_owner), "shortage": {'lines': [row for row in match_facts if str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'}]}, "line_results": match_facts, "created_at": task.created_at.isoformat() if task.created_at else None, @@ -1424,9 +1424,9 @@ def _notice_line_summary_for_task(task: ShippingNotice) -> list[dict[str, Any]]: if snapshot is not None: matches_by_snapshot_line_id = { int(item.snapshot_line_id): item - for item in ShippingNoticeLineInventoryMatch.query.filter( - ShippingNoticeLineInventoryMatch.task_id == int(owner.id), - ShippingNoticeLineInventoryMatch.is_current.is_(True), + for item in ShippingNoticeLineOnhandMatch.query.filter( + ShippingNoticeLineOnhandMatch.task_id == int(owner.id), + ShippingNoticeLineOnhandMatch.is_current.is_(True), ).all() if item.snapshot_line_id is not None } @@ -1434,9 +1434,9 @@ def _notice_line_summary_for_task(task: ShippingNotice) -> list[dict[str, Any]]: # 必须来自本 Notice 的 ShippingNoticeLine,避免不同通知波次串行。 matches_by_snapshot_line_id = { int(item.snapshot_line_id): item - for item in ShippingNoticeLineInventoryMatch.query.filter( - ShippingNoticeLineInventoryMatch.task_id == int(task.id), - ShippingNoticeLineInventoryMatch.is_current.is_(True), + for item in ShippingNoticeLineOnhandMatch.query.filter( + ShippingNoticeLineOnhandMatch.task_id == int(task.id), + ShippingNoticeLineOnhandMatch.is_current.is_(True), ).all() if item.snapshot_line_id is not None } @@ -1453,7 +1453,7 @@ def _notice_line_summary_for_task(task: ShippingNotice) -> list[dict[str, Any]]: if item.snapshot_line_id is not None and matches_by_snapshot_line_id.get(int(item.snapshot_line_id)) is not None else None, 'shortage_qty': matches_by_snapshot_line_id.get(int(item.snapshot_line_id)).shortage_qty if item.snapshot_line_id is not None and matches_by_snapshot_line_id.get(int(item.snapshot_line_id)) is not None else None, - 'inventory_status': matches_by_snapshot_line_id.get(int(item.snapshot_line_id)).inventory_status + 'inventory_status': matches_by_snapshot_line_id.get(int(item.snapshot_line_id)).onhand_status if item.snapshot_line_id is not None and matches_by_snapshot_line_id.get(int(item.snapshot_line_id)) is not None else None, } for item in rows] @@ -2175,15 +2175,15 @@ def _order_task_todo_category_sql_expr(): reason = db.func.lower(db.func.coalesce(ShippingOrderTask.pending_human_reason, "")) ready_file = exists( select(1) - .select_from(ShippingTaskInventoryLink) - .join(ShippingInventoryFile, ShippingInventoryFile.id == ShippingTaskInventoryLink.inventory_file_id) + .select_from(ShippingTaskOnhandLink) + .join(FreightRpaOnhandReportFile, FreightRpaOnhandReportFile.id == ShippingTaskOnhandLink.onhand_file_id) .where( - ShippingTaskInventoryLink.task_id == ShippingOrderTask.id, - ShippingTaskInventoryLink.is_active.is_(True), - ShippingTaskInventoryLink.invalidated_at.is_(None), - ShippingInventoryFile.snapshot_status == 'ready', - ShippingInventoryFile.invalidated_at.is_(None), - ShippingInventoryFile.line_count > 0, + ShippingTaskOnhandLink.task_id == ShippingOrderTask.id, + ShippingTaskOnhandLink.is_active.is_(True), + ShippingTaskOnhandLink.invalidated_at.is_(None), + FreightRpaOnhandReportFile.snapshot_status == 'ready', + FreightRpaOnhandReportFile.invalidated_at.is_(None), + FreightRpaOnhandReportFile.line_count > 0, ) ) incomplete_match = exists( @@ -2192,24 +2192,24 @@ def _order_task_todo_category_sql_expr(): .where( ShippingOrderSnapshotLine.snapshot_id == ShippingOrderTask.order_snapshot_id, ~exists( - select(1).select_from(ShippingNoticeLineInventoryMatch).where( - ShippingNoticeLineInventoryMatch.task_id == ShippingOrderTask.id, - ShippingNoticeLineInventoryMatch.snapshot_line_id == ShippingOrderSnapshotLine.id, - ShippingNoticeLineInventoryMatch.is_current.is_(True), - ShippingNoticeLineInventoryMatch.match_result != 'preparing', + select(1).select_from(ShippingNoticeLineOnhandMatch).where( + ShippingNoticeLineOnhandMatch.task_id == ShippingOrderTask.id, + ShippingNoticeLineOnhandMatch.snapshot_line_id == ShippingOrderSnapshotLine.id, + ShippingNoticeLineOnhandMatch.is_current.is_(True), + ShippingNoticeLineOnhandMatch.match_result != 'preparing', ) ), ) ) has_shortage = exists( - select(1).select_from(ShippingNoticeLineInventoryMatch).where( - ShippingNoticeLineInventoryMatch.task_id == ShippingOrderTask.id, - ShippingNoticeLineInventoryMatch.is_current.is_(True), + select(1).select_from(ShippingNoticeLineOnhandMatch).where( + ShippingNoticeLineOnhandMatch.task_id == ShippingOrderTask.id, + ShippingNoticeLineOnhandMatch.is_current.is_(True), db.or_( - ShippingNoticeLineInventoryMatch.match_result != 'matched', + ShippingNoticeLineOnhandMatch.match_result != 'matched', db.and_( - ShippingNoticeLineInventoryMatch.shortage_qty.isnot(None), - ShippingNoticeLineInventoryMatch.shortage_qty.notin_(('', '0', '0.0', '0.00', '0.00000000')), + ShippingNoticeLineOnhandMatch.shortage_qty.isnot(None), + ShippingNoticeLineOnhandMatch.shortage_qty.notin_(('', '0', '0.0', '0.00', '0.00000000')), ), ), ) @@ -2242,7 +2242,7 @@ def _order_task_todo_category_sql_expr(): ), literal("in_progress"), ), - (stage.in_(("inventory_source_resolving", "notification_preparation", "inventory_fetching", "inventory_matching", "order_creating")), literal("in_progress")), + (stage.in_(("onhand_source_resolving", "notification_preparation", "onhand_fetching", "onhand_matching", "order_creating")), literal("in_progress")), else_=literal("exception"), ) @@ -2623,10 +2623,10 @@ def _todo_category_sql_filter(allowed: frozenset[str]): clauses.append( db.or_( workflow_current_step.isnot(None), - exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where( - ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, - ShippingNoticeLineInventoryMatch.is_current.is_(True), - ShippingNoticeLineInventoryMatch.inventory_snapshot_id.isnot(None), + exists(select(1).select_from(ShippingNoticeLineOnhandMatch).where( + ShippingNoticeLineOnhandMatch.task_id == ShippingNotice.order_task_id, + ShippingNoticeLineOnhandMatch.is_current.is_(True), + ShippingNoticeLineOnhandMatch.onhand_snapshot_id.isnot(None), )), artifact_exists, upload_pending, @@ -2705,9 +2705,9 @@ def _task_todo_category_sql_expr(): artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(("ready", "uploading", "uploaded")))) upload_success = _verified_upload_success_sql_expr() upload_pending = exists(select(1).select_from(ShippingUploadAttempt).join(ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingUploadAttempt.status.in_(("pending", "running", "failed", "unknown")))) - match_exists = exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where( - ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, - ShippingNoticeLineInventoryMatch.is_current.is_(True), + match_exists = exists(select(1).select_from(ShippingNoticeLineOnhandMatch).where( + ShippingNoticeLineOnhandMatch.task_id == ShippingNotice.order_task_id, + ShippingNoticeLineOnhandMatch.is_current.is_(True), )) return case( (upload_success, literal("done")), @@ -2847,7 +2847,7 @@ def _todo_tasks_base_query( workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery() artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded')))) upload_success = _verified_upload_success_sql_expr() - match_exists = exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where(ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, ShippingNoticeLineInventoryMatch.is_current.is_(True))) + match_exists = exists(select(1).select_from(ShippingNoticeLineOnhandMatch).where(ShippingNoticeLineOnhandMatch.task_id == ShippingNotice.order_task_id, ShippingNoticeLineOnhandMatch.is_current.is_(True))) if task_no: q = q.filter(ShippingNotice.task_no == str(task_no).strip()) if customer_needle: @@ -3259,7 +3259,7 @@ def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, Any]: workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery() artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded')))) upload_success = _verified_upload_success_sql_expr() - match_exists = exists(select(1).select_from(ShippingNoticeLineInventoryMatch).where(ShippingNoticeLineInventoryMatch.task_id == ShippingNotice.order_task_id, ShippingNoticeLineInventoryMatch.is_current.is_(True))) + match_exists = exists(select(1).select_from(ShippingNoticeLineOnhandMatch).where(ShippingNoticeLineOnhandMatch.task_id == ShippingNotice.order_task_id, ShippingNoticeLineOnhandMatch.is_current.is_(True))) pending = _visible_open_review_cases_query(user_id, is_admin=is_admin).count() pending += _visible_orphan_intakes_query(user_id, is_admin=is_admin).count() category_expr = _task_todo_category_sql_expr() diff --git a/backend/app/services/shipping_notice/queue_service.py b/backend/app/services/shipping_notice/queue_service.py index c0943cf7..1dacfaa8 100644 --- a/backend/app/services/shipping_notice/queue_service.py +++ b/backend/app/services/shipping_notice/queue_service.py @@ -94,7 +94,7 @@ def _should_requeue_waiting_external_result(task_no: str) -> bool: return False from app.services.shipping_notice.process_gate_projection import task_blocking_reason pending_reason = str(task_blocking_reason(task) or '').strip() - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task return ( pending_reason == PH_RPA_PENDING @@ -112,7 +112,7 @@ def _requeue_external_wait_job(task_no: str, *, job: Job | None = None) -> None: task = get_task_by_ref(task_no) from app.services.shipping_notice.process_gate_projection import task_blocking_reason if task and str(task_blocking_reason(task) or '').strip() == PH_RPA_PENDING: - from app.services.shipping_notice.inventory_rpa_workflow import next_inventory_rpa_recheck_at + from app.services.shipping_notice.onhand_rpa_workflow import next_inventory_rpa_recheck_at scheduled_at = next_inventory_rpa_recheck_at(task) if scheduled_at is None: @@ -147,7 +147,7 @@ def recover_stale_shipping_notice_jobs() -> tuple[int, str]: from app.services.shipping_notice.intake_parse_workflow import ( sync_intake_after_parse_job_recovery, ) - from app.services.shipping_notice.inventory_rpa_callback_cleanup import ( + from app.services.freight_rpa.onhand.callback_cleanup import ( recover_pending_rpa_callback_cleanup_jobs, ) @@ -224,7 +224,7 @@ def claim_next_shipping_notice_job() -> Job | None: JobType.SHIPPING_ORDER_EXTRACTION, JobType.SHIPPING_DOCUMENT_LAYOUT, JobType.SHIPPING_PROCESS_GATE, - JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS, + JobType.FREIGHT_RPA_ONHAND_CALLBACK_PROCESS, JobType.SHIPPING_PDF_AUTOMARK, JobType.SHIPPING_STP_AUTO_CREATE, JobType.SHIPPING_LINE_AUTO_FULFILL, diff --git a/backend/app/services/shipping_notice/receipt_report_access.py b/backend/app/services/shipping_notice/receipt_report_access.py deleted file mode 100644 index e7d54771..00000000 --- a/backend/app/services/shipping_notice/receipt_report_access.py +++ /dev/null @@ -1,90 +0,0 @@ -"""收料归档文件的授权下载服务。""" - -from __future__ import annotations - -from io import BytesIO -from typing import Any - -from app import db -from app.core.errors import ForbiddenError, NotFoundError -from app.models import ShippingReceiptReportFile, User -from app.services.file_assets.storage import file_asset_storage -from app.services.shipping_notice.audit_service import append_shipping_audit_event - - -def _is_admin(user: User) -> bool: - """判断用户是否为收料报表管理角色。""" - return bool(user.is_platform_admin()) - - -def can_download_receipt_report_file(report_file: ShippingReceiptReportFile, user: User) -> bool: - """仅允许管理员或所属排程通知接收人读取收料归档。""" - if _is_admin(user): - return True - run = report_file.unit_run.schedule_run - task = run.task if run is not None else None - return task is not None and int(user.id) in { - int(value) for value in (task.notify_user_ids_json or []) if str(value).isdigit() - } - - -def _serialize_receipt_report_file(report_file: ShippingReceiptReportFile) -> dict[str, Any]: - """输出可下载收料文件的脱敏列表投影,永不暴露对象存储 bucket 或 key。""" - unit = report_file.unit_run - run = unit.schedule_run if unit is not None else None - return { - 'id': report_file.id, - 'original_filename': report_file.original_filename, - 'content_type': report_file.content_type, - 'file_size': report_file.file_size, - 'sha256': report_file.sha256, - 'source_code': unit.source_code if unit is not None else None, - 'warehouse_id': unit.warehouse_id if unit is not None else None, - 'schedule_run_no': run.run_no if run is not None else None, - 'archive_expires_at': report_file.archive_expires_at.isoformat() if report_file.archive_expires_at else None, - 'created_at': report_file.created_at.isoformat() if report_file.created_at else None, - 'download_url': f'/api/workspace/receipt-report-files/{report_file.id}/download', - } - - -def list_receipt_report_files(user: User, *, limit: int = 100) -> list[dict[str, Any]]: - """列出管理员或当前排程接收人可见的未清理收料归档,并留存读取审计。""" - bounded_limit = max(1, min(int(limit), 200)) - rows = ShippingReceiptReportFile.query.filter( - ShippingReceiptReportFile.archive_deleted_at.is_(None), - ).order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc()).all() - # 先按授权过滤再截断:不能因为前 100 条属于其他排程而遗漏当前接收人的历史文件。 - visible = [item for item in rows if can_download_receipt_report_file(item, user)][:bounded_limit] - append_shipping_audit_event( - event_type='shipping_receipt_report_files_listed', aggregate_type='shipping_receipt_file_collection', - aggregate_id=str(user.id), actor_type='user', actor_id=user.id, owner_user_id=user.id, - result='success', after={'visible_count': len(visible), 'limit': bounded_limit}, - metadata={'surface': 'workspace_receipt_report_files'}, - ) - db.session.commit() - return [_serialize_receipt_report_file(item) for item in visible] - - -def resolve_receipt_report_download(file_id: int, user: User) -> tuple[BytesIO, str, str | None]: - """授权读取私有对象并记录允许或拒绝的下载审计。""" - report_file = db.session.get(ShippingReceiptReportFile, file_id) - if report_file is None or report_file.archive_deleted_at is not None: - raise NotFoundError('Receipt report file not found', code='SHIPPING.RECEIPT_REPORT_FILE_NOT_FOUND') - if not can_download_receipt_report_file(report_file, user): - append_shipping_audit_event( - event_type='shipping_receipt_report_download_rejected', aggregate_type='shipping_receipt_file', - aggregate_id=str(report_file.id), actor_type='user', actor_id=user.id, owner_user_id=user.id, - unit_id=report_file.unit_run_id, result='rejected', reason_code='recipient_not_authorized', - after={'status': 'rejected', 'owner_user_id': user.id}, artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], - ) - db.session.commit() - raise ForbiddenError('You are not authorized to download this receipt report') - data = file_asset_storage.get_bytes(report_file.storage_key) - append_shipping_audit_event( - event_type='shipping_receipt_report_downloaded', aggregate_type='shipping_receipt_file', - aggregate_id=str(report_file.id), actor_type='user', actor_id=user.id, owner_user_id=user.id, - unit_id=report_file.unit_run_id, result='success', - after={'status': 'downloaded', 'owner_user_id': user.id}, artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], - ) - db.session.commit() - return BytesIO(data), report_file.original_filename, report_file.content_type diff --git a/backend/app/services/shipping_notice/receipt_report_notification.py b/backend/app/services/shipping_notice/receipt_report_notification.py deleted file mode 100644 index ff61a471..00000000 --- a/backend/app/services/shipping_notice/receipt_report_notification.py +++ /dev/null @@ -1,93 +0,0 @@ -"""收料报表企微通知的管理员重发通道。 - -用途:收料排程的正常通知已统一并入排程通用出口——run 终态后一次性发送 - textcard 汇总 + 原始收料 ZIP(scheduler_service._notify_schedule_run_wecom, - 与库存 RPA 同门禁同出口);本模块只保留管理员对单个已归档收料文件的 - 强制重发能力(POST /receipt-report-files//resend),不触发 RPA。 -依赖:models、file_asset_storage、audit_service、integrations.wecom.notify。 -逻辑:deliver_receipt_file 幂等投递单文件并落 ShippingReceiptNotificationDelivery - 与 shipping 审计;force=True 供管理员补偿重发,绕过成功幂等但仍受通知开关约束。 -""" - -from __future__ import annotations - -from datetime import datetime - -from app import db -from app.models import ShippingReceiptNotificationDelivery, ShippingReceiptReportFile, User -from app.services.file_assets.storage import file_asset_storage -from app.services.integrations.wecom.notify import send_wecom_file_message, upload_wecom_temp_media -from app.services.shipping_notice.audit_service import append_shipping_audit_event - - -def _recipient_ids(report_file: ShippingReceiptReportFile) -> list[int]: - """从所属排程冻结的接收人列表取目标用户;停用通知时返回空。""" - run = report_file.unit_run.schedule_run - task = run.task if run else None - if task is None or not task.notify_enabled: - return [] - return sorted({int(user_id) for user_id in (task.notify_user_ids_json or []) if str(user_id).isdigit()}) - - -def deliver_receipt_file(file_id: int, *, force: bool = False) -> dict: - """向排程接收人逐一投递原样收料文件;同文件用户的成功投递可幂等重放。""" - report_file = db.session.get(ShippingReceiptReportFile, file_id) - if report_file is None: - return {'success_count': 0, 'failed_count': 0, 'reason': 'file_not_found'} - success_count = failed_count = 0 - for user_id in _recipient_ids(report_file): - key = f'receipt:file:{report_file.id}:user:{user_id}' - delivery = ShippingReceiptNotificationDelivery.query.filter_by(idempotency_key=key).one_or_none() - if delivery and delivery.status == 'success' and not force: - success_count += 1 - continue - if delivery is None: - delivery = ShippingReceiptNotificationDelivery( - unit_run_id=report_file.unit_run_id, report_file_id=report_file.id, recipient_user_id=user_id, - message_type='file', idempotency_key=key, status='pending', - ) - db.session.add(delivery) - db.session.flush() - user = db.session.get(User, user_id) - if user is None or not user.wecom_userid: - delivery.status = 'failed'; delivery.error_code = 'WECOM_USER_UNBOUND'; delivery.error_message = 'recipient has no wecom binding' - failed_count += 1 - append_shipping_audit_event( - event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_file', - aggregate_id=str(report_file.id), actor_type='system', owner_user_id=user_id, - unit_id=report_file.unit_run_id, result='failure', - before={'delivery_status': 'pending'}, - after={'delivery_status': delivery.status, 'error_code': delivery.error_code}, - artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], - metadata={'delivery_id': delivery.id, 'message_type': 'file'}, - ) - continue - try: - media_id = upload_wecom_temp_media(file_asset_storage.get_bytes(report_file.storage_key), report_file.original_filename) - result = send_wecom_file_message(user.wecom_userid, media_id) - if int(result.get('errcode', -1)) != 0: - raise RuntimeError(str(result.get('errmsg') or result.get('errcode'))) - delivery.status = 'success'; delivery.sent_at = datetime.utcnow(); delivery.error_code = None; delivery.error_message = None - delivery.response_summary_json = {'media_uploaded': True, 'errcode': 0} - success_count += 1 - append_shipping_audit_event( - event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_file', aggregate_id=str(report_file.id), - actor_type='system', owner_user_id=user_id, unit_id=report_file.unit_run_id, result='success', - before={'delivery_status': 'pending'}, after={'delivery_status': delivery.status, 'sent_at': delivery.sent_at.isoformat() if delivery.sent_at else None}, - artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], - metadata={'delivery_id': delivery.id, 'message_type': 'file'}, - ) - except Exception as exc: - delivery.status = 'failed'; delivery.error_code = 'WECOM_SEND_FAILED'; delivery.error_message = str(exc)[:2000] - failed_count += 1 - append_shipping_audit_event( - event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_file', - aggregate_id=str(report_file.id), actor_type='system', owner_user_id=user_id, - unit_id=report_file.unit_run_id, result='failure', - before={'delivery_status': 'pending'}, - after={'delivery_status': delivery.status, 'error_code': delivery.error_code, 'error_message': delivery.error_message}, - artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}], - metadata={'delivery_id': delivery.id, 'message_type': 'file'}, - ) - db.session.commit() - return {'success_count': success_count, 'failed_count': failed_count} diff --git a/backend/app/services/shipping_notice/receipt_report_storage.py b/backend/app/services/shipping_notice/receipt_report_storage.py deleted file mode 100644 index 2ad47d85..00000000 --- a/backend/app/services/shipping_notice/receipt_report_storage.py +++ /dev/null @@ -1,190 +0,0 @@ -"""收料 RPA callback 的原样归档服务。 - -用途:接收收料 RPA 单元回调,原样归档文件三年且不写库存快照表;终态落库后 - 通过收料回调桥推进在途调拨的 waiting_rpa_callback 来源任务(B3 接线); - 每笔终态回调回写 ScheduleRun 进度计数(对齐库存 inventory-batch-progress)。 -依赖:models(ShippingReceiptReportFile/ShippingReceiptRpaUnitRun)、file_asset_storage、 - 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; - empty 落库 error_code=no_receipt_data(对齐库存 no_inventory_data); - 有 schedule_run_id 时 refresh 进度再 finalize;success 分支再触发调拨证据同步; - 两座桥都是记账不是收料链路的正确性依赖,桥内异常只记日志绝不回滚归档终态。 -""" - -from __future__ import annotations - -import hashlib -from datetime import datetime, timedelta -from pathlib import Path -from typing import Any - -from flask import current_app - -from app import db -from app.core.errors import NotFoundError, ValidationError -from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun -from app.services.file_assets.storage import file_asset_storage -from app.services.shipping_notice.audit_service import append_shipping_audit_event - - -def _read_receipt_callback_file(file_path: str) -> bytes: - """只读取收料专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。 - - 路径契约为「drop 根内文件名」:Worker(Windows RPA 主机)与后端(Linux 容器)分属 - 两机,各自看到的根路径不同(C:\\HxopsRpaTest\\... vs /mnt/hxops-rpa-*-data/...), - Worker 只上报文件名,后端用自身挂载的 drop 根拼接定位;携带本机绝对路径的历史 - 载荷亦按末段文件名解析(2026-10-08 修复跨机成功回调全程 400 的事故)。 - """ - configured_root = str(current_app.config.get('FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR') or '').strip() - if not configured_root: - raise ValidationError('receipt callback file root is unavailable', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID') - root = Path(configured_root).resolve() - # 容忍历史载荷携带 Windows 绝对路径:先归一分隔符再取末段文件名(防遍历,单一分段)。 - name = Path(str(file_path).replace('\\', '/')).name - path = (root / name).resolve() - try: - path.relative_to(root) - except ValueError as exc: - raise ValidationError('receipt callback file is outside receipt drop root', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID') from exc - if path.suffix.lower() != '.xlsx' or not path.is_file(): - raise ValidationError('receipt callback file must be an existing xlsx', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID') - max_size = max(int(current_app.config.get('FILE_ASSET_MAX_SIZE_MB', 30) or 30), 1) * 1024 * 1024 - if path.stat().st_size > max_size: - raise ValidationError('receipt callback file exceeds configured size limit', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID') - return path.read_bytes() - - -def _advance_transfer_source_job( - unit: 'ShippingReceiptRpaUnitRun', *, ok: bool, - file_no: str | None = None, file_sha256: str | None = None, - error_code: str | None = None, error_message: str | None = None, -) -> None: - """收料回调终态推进调拨来源任务;失败只记日志,绝不回滚收料归档终态。 - - Args: - unit: 已落终态的收料单元行(用其 source_code 定位调拨任务)。 - ok: 回调是否成功(True 仅在 success 且带 file_no 时推进 file_ready)。 - file_no / file_sha256: success 时绑定的归档文件号与指纹。 - error_code / error_message: 失败时的错误码与描述。 - """ - try: - from app import db - from app.services.in_transit_transfer.receipt_callback_bridge import advance_source_job_from_receipt_callback - advanced = advance_source_job_from_receipt_callback( - source_code=unit.source_code, file_no=file_no, file_sha256=file_sha256, - callback_ok=ok, error_code=error_code, error_message=error_message, - ) - if advanced is not None: - # 桥内只 flush 不 commit;empty/failed 且 finalize 提前返回时无人提交, - # 必须在此 commit,否则请求结束回滚会丢掉已推进的任务(B3 持久性)。 - db.session.commit() - except Exception as exc: # noqa: BLE001 —— 桥是记账,不是收料链路的正确性依赖 - from flask import current_app - current_app.logger.warning('[receipt-callback] advance transfer source job failed: %s', exc) - - -def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]: - """幂等接收单个收料单元回调,原样归档三年且不写库存快照表。""" - if payload.get('schema_version') != 'shipping_receipt_rpa.v1': - raise ValidationError('receipt callback schema_version is invalid', code='SHIPPING.RECEIPT_CALLBACK_INVALID') - callback_id = str(payload.get('callback_id') or '').strip() - unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=callback_id).one_or_none() - if unit is None: - raise NotFoundError('Receipt RPA unit not found', code='SHIPPING.RECEIPT_UNIT_NOT_FOUND') - status = str(payload.get('status') or '').strip().lower() - before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message} - if status in {'empty', 'no_data'}: - # [STEP] 与库存 no_inventory_data 对齐:empty 是合法业务结果,落 error_code=no_receipt_data。 - 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, - '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=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': - unit.status = 'failed'; unit.error_code = str(payload.get('error_code') or 'RPA.RECEIPT_EXPORT_FAILED')[:64]; unit.error_message = str(payload.get('error_message') or 'receipt export failed')[:2000]; unit.finished_at = datetime.utcnow() - append_shipping_audit_event( - event_type='shipping_receipt_rpa_callback_received', aggregate_type='shipping_receipt_unit', - aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, - actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='failure', - before=before, after={'status': 'failed', 'error_code': unit.error_code, 'error_message': unit.error_message}, - metadata={'callback_status': status}, - ) - 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, - 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 '')) - sha256 = hashlib.sha256(data).hexdigest() - claimed = str(payload.get('sha256') or '').lower() - if claimed and claimed != sha256: - raise ValidationError('receipt callback sha256 mismatch', code='SHIPPING.RECEIPT_CALLBACK_SHA_MISMATCH') - existing = ShippingReceiptReportFile.query.filter_by(unit_run_id=unit.id, sha256=sha256).one_or_none() - if existing: - return {'unit_run_id': unit.id, 'status': unit.status, 'file_id': existing.id, 'idempotent': True} - filename = Path(str(payload.get('original_filename') or payload.get('file_path') or 'receipt.xlsx')).name - storage_key = f'shipping/receipt-reports/{datetime.utcnow():%Y/%m}/{unit.id}/{sha256}.xlsx' - file_asset_storage.upload_bytes(storage_key=storage_key, data=data, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') - record = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key, original_filename=filename, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', file_size=len(data), sha256=sha256, archive_expires_at=datetime.utcnow() + timedelta(days=365 * 3)) - db.session.add(record) - unit.status = 'success'; unit.finished_at = datetime.utcnow() - db.session.flush() - append_shipping_audit_event(event_type='shipping_receipt_report_archived', aggregate_type='shipping_receipt_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success', before=before, after={'status': 'success', 'source_run_no': unit.callback_id, 'file_id': record.id, 'sha256': sha256, 'file_size': len(data)}, artifact_refs=[{'kind': 'receipt_report', 'id': str(record.id), 'sha256': sha256}], metadata={'file_size': len(data), 'retention_days': 365 * 3}) - db.session.commit() - _advance_transfer_source_job(unit, ok=True, file_no=str(record.id), file_sha256=sha256) - # [调拨证据同步·主链路] success 终态文件落地即解析写调拨待办(本分支专属; - # empty/failed 分支不触发同步)。桥模式失败仅日志,绝不影响收料归档主链路 - # (语义见 in_transit_transfer/evidence_sync.sync_and_commit_for_callback)。 - try: - from datetime import datetime as _dt - - from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback - - sync_and_commit_for_callback( - source_code=unit.source_code, business_date=str(_dt.utcnow().date()), now=_dt.utcnow(), - ) - except Exception as exc: # noqa: BLE001 —— 双保险:桥内部已吞异常 - current_app.logger.warning('[receipt-callback] transfer evidence sync failed: %s', exc) - from app.services.schedule.freight_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 deleted file mode 100644 index 77a0f9aa..00000000 --- a/backend/app/services/shipping_notice/receipt_rpa.py +++ /dev/null @@ -1,56 +0,0 @@ -""" -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 - -import json -import os -import tempfile -from datetime import datetime -from pathlib import Path -from typing import Any - -from flask import current_app - - -def receipt_trigger_dir() -> Path | None: - """返回收料专用 trigger 目录;绝不回落到库存 trigger 目录。""" - value = str(current_app.config.get('FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR') or '').strip() - return Path(value) if value else None - - -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() - if trigger_dir is None or not units: - return None - trigger_dir.mkdir(parents=True, exist_ok=True) - safe_run_no = ''.join(char for char in run_no if char.isalnum() or char in {'-', '_'}) or 'receipt' - body = { - 'schema_version': 'shipping_receipt_rpa.v1', 'action': 'receipt_export_batch', - 'batch_run_no': run_no, 'requested_at': datetime.utcnow().isoformat(), 'units': units, - **(payload or {}), - } - path = trigger_dir / f'receipt_export_batch_{safe_run_no}.json' - # Worker 轮询 *.json;必须先写入同目录临时文件后原子替换,不能让 Worker - # 领取到半截 JSON 并误入 failed/,这不会影响库存 trigger 的既有实现。 - fd, temp_name = tempfile.mkstemp(prefix=f'.{path.stem}.', suffix='.tmp', dir=str(trigger_dir)) - try: - with os.fdopen(fd, 'w', encoding='utf-8') as handle: - handle.write(json.dumps(body, ensure_ascii=False, indent=2)) - handle.flush() - os.fsync(handle.fileno()) - os.replace(temp_name, path) - except Exception: - try: - Path(temp_name).unlink(missing_ok=True) - except OSError: - pass - raise - return str(path) diff --git a/backend/app/services/shipping_notice/recovery_invalidation_service.py b/backend/app/services/shipping_notice/recovery_invalidation_service.py index ce987717..6254837b 100644 --- a/backend/app/services/shipping_notice/recovery_invalidation_service.py +++ b/backend/app/services/shipping_notice/recovery_invalidation_service.py @@ -15,11 +15,11 @@ from sqlalchemy import false from app import db from app.models import ( ShippingExportArtifact, - ShippingInventoryVerification, - ShippingInventoryMapping, - ShippingNoticeLineInventoryMatch, + ShippingOnhandVerification, + FreightRpaOnhandMapping, + ShippingNoticeLineOnhandMatch, ShippingProcessExecution, - ShippingTaskInventoryLink, + ShippingTaskOnhandLink, ShippingUploadAttempt, ShippingNotice, ) @@ -43,10 +43,10 @@ def _noticed_snapshot_line_ids(task_id: int) -> set[int]: return {int(row[0]) for row in rows if row[0] is not None} -def _match_row_source_codes(row: ShippingNoticeLineInventoryMatch) -> set[str]: +def _match_row_source_codes(row: ShippingNoticeLineOnhandMatch) -> set[str]: """从匹配事实抽取规范化库存源集合,供行级失效过滤。""" codes: set[str] = set() - primary = str(getattr(row, 'inventory_source_code', '') or '').strip().upper() + primary = str(getattr(row, 'source_code', '') or '').strip().upper() if primary: codes.add(primary) for raw in list(getattr(row, 'allowed_source_codes_snapshot', None) or []): @@ -89,10 +89,10 @@ def invalidate_inventory_downstream( task = db.session.get(ShippingOrderTask, task_id) result: dict[str, list[int] | list[str]] = {'gates': [], 'links': [], 'mappings': [], 'matches': [], 'verifications': [], 'artifacts': [], 'uploads': []} change_type = { - 'retry_inventory_preparation': 'inventory_file_changed', - 'retry_inventory_from_preparation': 'inventory_file_changed', - 'retry_inventory_from_field_mapping': 'inventory_field_mapping_changed', - 'retry_inventory_from_matching': 'inventory_matching_changed', + 'retry_onhand_preparation': 'inventory_file_changed', + 'retry_onhand_from_preparation': 'inventory_file_changed', + 'retry_onhand_from_field_mapping': 'inventory_field_mapping_changed', + 'retry_onhand_from_matching': 'inventory_matching_changed', }.get(action_code, 'inventory_matching_changed') result['gates'] = invalidate_downstream_gates(execution=execution, change_type=change_type, actor_id=actor_id) scoped_codes = { @@ -103,8 +103,8 @@ def invalidate_inventory_downstream( line_scoped = bool(scoped_codes) protected_line_ids = _noticed_snapshot_line_ids(task_id) if line_scoped else set() scoped_snapshot_line_id = int(snapshot_line_id) if snapshot_line_id is not None else None - if action_code in {'retry_inventory_preparation', 'retry_inventory_from_preparation'}: - links = ShippingTaskInventoryLink.query.filter_by(task_id=task_id, is_active=True).with_for_update().all() + if action_code in {'retry_onhand_preparation', 'retry_onhand_from_preparation'}: + links = ShippingTaskOnhandLink.query.filter_by(task_id=task_id, is_active=True).with_for_update().all() for link in links: link_code = str(getattr(link, 'matched_source_code', '') or '').strip().upper() if line_scoped and link_code and link_code not in scoped_codes: @@ -118,26 +118,26 @@ def invalidate_inventory_downstream( link.invalidation_reason = action_code result['links'].append(int(link.id)) affected_file_ids = [ - int(link.inventory_file_id) - for link in ShippingTaskInventoryLink.query.filter_by(task_id=task_id).all() - if link.inventory_file_id and ( + int(link.onhand_file_id) + for link in ShippingTaskOnhandLink.query.filter_by(task_id=task_id).all() + if link.onhand_file_id and ( not line_scoped or str(getattr(link, 'matched_source_code', '') or '').strip().upper() in scoped_codes ) ] if action_code in { - 'retry_inventory_preparation', - 'retry_inventory_from_preparation', - 'retry_inventory_from_field_mapping', + 'retry_onhand_preparation', + 'retry_onhand_from_preparation', + 'retry_onhand_from_field_mapping', } and affected_file_ids: - mappings = ShippingInventoryMapping.query.filter( - ShippingInventoryMapping.inventory_file_id.in_(affected_file_ids), - ShippingInventoryMapping.status == 'active', + mappings = FreightRpaOnhandMapping.query.filter( + FreightRpaOnhandMapping.onhand_file_id.in_(affected_file_ids), + FreightRpaOnhandMapping.status == 'active', ).with_for_update().all() for mapping in mappings: mapping.status = 'invalidated' result['mappings'].append(int(mapping.id)) - matches = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=task_id, is_current=True).with_for_update().all() + matches = ShippingNoticeLineOnhandMatch.query.filter_by(task_id=task_id, is_current=True).with_for_update().all() for row in matches: row_line_id = int(getattr(row, 'snapshot_line_id', 0) or 0) if line_scoped and row_line_id in protected_line_ids: @@ -154,7 +154,7 @@ def invalidate_inventory_downstream( row.invalidation_reason = action_code result['matches'].append(int(row.id)) if not line_scoped: - verifications = ShippingInventoryVerification.query.filter_by(task_id=task_id, status='completed').with_for_update().all() + verifications = ShippingOnhandVerification.query.filter_by(task_id=task_id, status='completed').with_for_update().all() for verification in verifications: verification.status = 'superseded' result['verifications'].append(int(verification.id)) diff --git a/backend/app/services/shipping_notice/recovery_plan_contract.py b/backend/app/services/shipping_notice/recovery_plan_contract.py index 4f549e5f..cf3e623e 100644 --- a/backend/app/services/shipping_notice/recovery_plan_contract.py +++ b/backend/app/services/shipping_notice/recovery_plan_contract.py @@ -12,50 +12,50 @@ from typing import Any RECOVERY_PLAN_ACTIONS: dict[str, dict[str, dict[str, Any]]] = { - 'inventory_matching': { - 'retry_inventory_from_preparation': { - 'target_gate': 'inventory_preparation', - 'resume_after_gate': 'inventory_matching', - 'allowed_intermediate_gates': ('inventory_field_mapping',), + 'onhand_matching': { + 'retry_onhand_from_preparation': { + 'target_gate': 'onhand_preparation', + 'resume_after_gate': 'onhand_matching', + 'allowed_intermediate_gates': ('onhand_field_mapping',), 'invalidate_change_type': 'inventory_file_changed', - 'invalidates': ('inventory_snapshot', 'inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'), + 'invalidates': ('onhand_snapshot', 'onhand_mapping', 'onhand_matching', 'onhand_sufficiency', 'excel', 'upload'), 'permission': 'owner_or_admin', }, - 'retry_inventory_from_field_mapping': { - 'target_gate': 'inventory_field_mapping', - 'resume_after_gate': 'inventory_matching', + 'retry_onhand_from_field_mapping': { + 'target_gate': 'onhand_field_mapping', + 'resume_after_gate': 'onhand_matching', 'allowed_intermediate_gates': (), 'invalidate_change_type': 'inventory_field_mapping_changed', - 'invalidates': ('inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'), + 'invalidates': ('onhand_mapping', 'onhand_matching', 'onhand_sufficiency', 'excel', 'upload'), 'permission': 'owner_or_admin', }, }, # 库存有缺口时仍由 Gate 16 负责恢复入口;数量事实只读,恢复动作回到正式库存链路。 - 'inventory_sufficiency': { + 'onhand_sufficiency': { # 公开动作:用户明确选择“重新获取库存”时回到准备 Gate,强制创建新的 RPA # Attempt;不能要求客户端传递内部的 retry_inventory_from_preparation。 - 'retry_inventory_preparation': { - 'target_gate': 'inventory_preparation', - 'resume_after_gate': 'inventory_sufficiency', - 'allowed_intermediate_gates': ('inventory_field_mapping', 'inventory_matching'), + 'retry_onhand_preparation': { + 'target_gate': 'onhand_preparation', + 'resume_after_gate': 'onhand_sufficiency', + 'allowed_intermediate_gates': ('onhand_field_mapping', 'onhand_matching'), 'invalidate_change_type': 'inventory_file_changed', - 'invalidates': ('inventory_snapshot', 'inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'), + 'invalidates': ('onhand_snapshot', 'onhand_mapping', 'onhand_matching', 'onhand_sufficiency', 'excel', 'upload'), 'permission': 'owner_or_admin', }, - 'retry_inventory_from_preparation': { - 'target_gate': 'inventory_preparation', - 'resume_after_gate': 'inventory_sufficiency', - 'allowed_intermediate_gates': ('inventory_field_mapping', 'inventory_matching'), + 'retry_onhand_from_preparation': { + 'target_gate': 'onhand_preparation', + 'resume_after_gate': 'onhand_sufficiency', + 'allowed_intermediate_gates': ('onhand_field_mapping', 'onhand_matching'), 'invalidate_change_type': 'inventory_file_changed', - 'invalidates': ('inventory_snapshot', 'inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'), + 'invalidates': ('onhand_snapshot', 'onhand_mapping', 'onhand_matching', 'onhand_sufficiency', 'excel', 'upload'), 'permission': 'owner_or_admin', }, - 'retry_inventory_from_matching': { - 'target_gate': 'inventory_matching', - 'resume_after_gate': 'inventory_sufficiency', + 'retry_onhand_from_matching': { + 'target_gate': 'onhand_matching', + 'resume_after_gate': 'onhand_sufficiency', 'allowed_intermediate_gates': (), 'invalidate_change_type': 'inventory_matching_changed', - 'invalidates': ('inventory_matching', 'inventory_sufficiency', 'excel', 'upload'), + 'invalidates': ('onhand_matching', 'onhand_sufficiency', 'excel', 'upload'), 'permission': 'owner_or_admin', }, }, diff --git a/backend/app/services/shipping_notice/recovery_plan_service.py b/backend/app/services/shipping_notice/recovery_plan_service.py index cda86b68..90fafb1e 100644 --- a/backend/app/services/shipping_notice/recovery_plan_service.py +++ b/backend/app/services/shipping_notice/recovery_plan_service.py @@ -107,8 +107,8 @@ def complete_recovery_plan_for_attempt( resolved_outcome = str(outcome) rematch_reached_shortage_review = ( resolved_outcome == 'blocked_manual' - and str(plan.action_code or '') == 'retry_inventory_from_matching' - and str(plan.resume_after_gate or '') == 'inventory_sufficiency' + and str(plan.action_code or '') == 'retry_onhand_from_matching' + and str(plan.resume_after_gate or '') == 'onhand_sufficiency' and str(business_result_code or '') == 'inventory_shortage_review_required' ) excel_regeneration_reached_manual_upload = ( diff --git a/backend/app/services/shipping_notice/reference_context.py b/backend/app/services/shipping_notice/reference_context.py index a54ce91a..da3610e4 100644 --- a/backend/app/services/shipping_notice/reference_context.py +++ b/backend/app/services/shipping_notice/reference_context.py @@ -103,7 +103,7 @@ def _task_failure_descriptor(task: ShippingNotice | None) -> dict[str, str] | No from app.models import ShippingOrderTask owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task review_status = _clean_text(getattr(owner, "review_status", None)).lower() - from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task match_task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None) match_status = _clean_text(aggregate_match_status_for_task(match_task_id)).lower() pending_reason = _clean_text(getattr(owner, "pending_human_reason", None)).lower() diff --git a/backend/app/services/shipping_notice/reservation_id.py b/backend/app/services/shipping_notice/reservation_id.py index 00aa364a..75e5253c 100644 --- a/backend/app/services/shipping_notice/reservation_id.py +++ b/backend/app/services/shipping_notice/reservation_id.py @@ -3,7 +3,7 @@ services/shipping_notice/reservation_id.py 用途:提取、标准化并校验发货通知与库存中的 Reservation ID。 依赖:正则表达式与标准 `typing` 工具;裸数字兜底扫描惰性依赖版面 HTML 网格解析。 -逻辑:由 notice_lines、inventory_snapshot、match、extract、EML 补充解析等多个模块复用; +逻辑:由 notice_lines、onhand_snapshot、match、extract、EML 补充解析等多个模块复用; 归一结果恒为 5/10 位纯数字(可剥括号备注、@ 前缀、短数字行序后缀如 35354-1)。 另提供「裸数字兜底」:正文数据表无表头且常规证据缺失时,扫描「整格恰好为 5/10 位纯数字」的 HTML 表格单元格候选(供 order_supplement_merge 在合并 diff --git a/backend/app/services/shipping_notice/reservation_service.py b/backend/app/services/shipping_notice/reservation_service.py index 658de766..eda02bf1 100644 --- a/backend/app/services/shipping_notice/reservation_service.py +++ b/backend/app/services/shipping_notice/reservation_service.py @@ -17,8 +17,8 @@ from app.core.errors import ConflictError, ValidationError from app.models import ( ShippingExportArtifact, ShippingExportArtifactLine, - ShippingInventoryVerification, - ShippingInventoryVerificationLine, + ShippingOnhandVerification, + ShippingOnhandVerificationLine, ShippingOrderSnapshot, ShippingOrderTask, ShippingReservation, @@ -190,12 +190,12 @@ def _transfer_confirmed_revision( def record_inventory_verification( task: ShippingNotice, *, inventory_snapshot_id: int | None, source_config_version: str | None, line_results: list[dict[str, Any]], -) -> ShippingInventoryVerification: +) -> ShippingOnhandVerification: """把一轮库存匹配追加为核验事实,并仅将完整满足的 pending 预约单标记 available。""" reservations = ensure_task_reservations(task) by_key = {row.reservation_id: row for row in reservations} - verification = ShippingInventoryVerification( - task_id=task.id, inventory_snapshot_id=inventory_snapshot_id, + verification = ShippingOnhandVerification( + task_id=task.id, onhand_snapshot_id=inventory_snapshot_id, source_config_version=source_config_version, status='completed', result_json={'line_count': len(line_results)}, ) db.session.add(verification) @@ -218,7 +218,7 @@ def record_inventory_verification( seen_reservation_ids.add(reservation_id) available = _decimal(item.get('available_qty')) if Decimal(str(item.get('available_qty') or 0)) > 0 else Decimal('0') status = 'available' if available >= required else 'shortage' - db.session.add(ShippingInventoryVerificationLine( + db.session.add(ShippingOnhandVerificationLine( verification_id=verification.id, reservation_id=reservation.id, required_qty=required, available_qty=available, status=status, detail_json={'line_status': item.get('line_status')}, )) @@ -236,7 +236,7 @@ def reserve_available_for_artifact( task: ShippingNotice, *, artifact: ShippingExportArtifact, - verification: ShippingInventoryVerification, + verification: ShippingOnhandVerification, released_snapshot_line_ids: set[int] | None = None, selected_snapshot_line_ids: set[int] | None = None, ) -> list[ShippingReservation]: @@ -244,7 +244,7 @@ def reserve_available_for_artifact( 锁定本轮可用或已审计短缺放行的预约单,并写入 Artifact 行。 核心逻辑:默认只消费 ``available`` Reservation;调用方仅可传入从活动 - ``release_inventory_shortage`` 决定解析出的冻结行 ID,使该行的 shortage + ``release_onhand_shortage`` 决定解析出的冻结行 ID,使该行的 shortage Verification 作为放行审计的一部分绑定到 Artifact,其他 shortage 不得被捎带导出。 Args: @@ -311,7 +311,7 @@ def current_available_snapshot_line_ids( released_snapshot_line_ids: set[int] | None = None, selected_snapshot_line_ids: set[int] | None = None, closed_snapshot_line_ids: set[int] | None = None, -) -> tuple[ShippingInventoryVerification, set[int]]: +) -> tuple[ShippingOnhandVerification, set[int]]: """ 取得最新核验中可导出的冻结订单行。 @@ -328,8 +328,8 @@ def current_available_snapshot_line_ids( (最新核验轮次, 本次可导出的冻结订单行 ID)。 """ verification = ( - ShippingInventoryVerification.query.filter_by(task_id=_inventory_task_id(task), status='completed') - .order_by(ShippingInventoryVerification.id.desc()).first() + ShippingOnhandVerification.query.filter_by(task_id=_inventory_task_id(task), status='completed') + .order_by(ShippingOnhandVerification.id.desc()).first() ) if verification is None: raise ConflictError('No inventory verification is available', code='SHIPPING.ROLLING_EXPORT_NOT_READY') diff --git a/backend/app/services/shipping_notice/routing_operators.py b/backend/app/services/shipping_notice/routing_operators.py index 374ca01d..01b4117c 100644 --- a/backend/app/services/shipping_notice/routing_operators.py +++ b/backend/app/services/shipping_notice/routing_operators.py @@ -2,7 +2,7 @@ services/shipping_notice/routing_operators.py 用途:执行库存源路由规则允许的比较操作。 -依赖:无业务服务依赖;由 inventory_routing_engine 调用。 +依赖:无业务服务依赖;由 onhand_routing_engine 调用。 逻辑:操作符白名单限制规则表达能力,避免管理员配置任意代码、SQL 或正则执行。 """ diff --git a/backend/app/services/shipping_notice/rpa.py b/backend/app/services/shipping_notice/rpa.py deleted file mode 100644 index 8d36cfc4..00000000 --- a/backend/app/services/shipping_notice/rpa.py +++ /dev/null @@ -1,380 +0,0 @@ -""" -services/shipping_notice/rpa.py - -用途:管理库存导出与货代上传相关的 RPA 目录、触发文件和落盘辅助逻辑。 -依赖:Flask current_app 配置、Path/JSON/文件系统工具。 -逻辑:由 inventory_rpa_workflow、fulfillment_workflow 等上游模块调用本文件,与外部 RPA 文件投递目录进行交互。 -""" - -from __future__ import annotations - -import json -import os -import shutil -import uuid -from datetime import datetime -from pathlib import Path -from typing import Any - -from flask import current_app -from app.core.errors import ValidationError - - -def _runtime_summary(mode: str) -> dict[str, str | bool]: - """将 browser/mock 规范化为前端安全展示摘要。""" - normalized = "mock" if str(mode or "").strip().lower() == "mock" else "browser" - mock_enabled = normalized == "mock" - return { - "mode": normalized, - "label": "Mock RPA" if mock_enabled else "真实 RPA", - "mock": mock_enabled, - } - - -def rpa_runtime_mode(runtime: dict[str, Any] | None = None) -> dict[str, str | bool]: - """返回 RPA 运行模式摘要;优先使用任务最近一次回调实际模式,兜底读取当前后端配置。""" - if isinstance(runtime, dict): - mode = str(runtime.get("mode") or runtime.get("rpa_mode") or "").strip().lower() - if mode in {"browser", "mock"}: - return _runtime_summary(mode) - raw = str(current_app.config.get("FREIGHT_RPA_WORKER_MOCK", "false") or "false").strip().lower() - return _runtime_summary("mock" if raw in {"1", "true", "yes", "on"} else "browser") - - -def _path(key: str) -> Path | None: - value = str(current_app.config.get(key) or "").strip() - if not value: - return None - return Path(value) - - -def inventory_drop_dir() -> Path | None: - """RPA 库存 Excel 落盘目录(FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR)。""" - return _path("FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR") - - -def inventory_processed_dir() -> Path | None: - """已处理库存文件归档子目录(drop_dir/processed)。""" - base = inventory_drop_dir() - if not base: - return None - return base / "processed" - - -def inventory_trigger_dir() -> Path | None: - """RPA 库存导出触发 JSON 目录。""" - return _path("FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR") - - -def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None: - """原子发布 trigger,避免 Worker 读取到写入中的半截 JSON。""" - temp_path = path.with_name(f'.{path.name}.{os.getpid()}.tmp') - try: - with open(temp_path, 'w', encoding='utf-8') as handle: - json.dump(body, handle, ensure_ascii=False, indent=2) - handle.flush() - os.fsync(handle.fileno()) - os.replace(temp_path, path) - finally: - if temp_path.exists(): - temp_path.unlink(missing_ok=True) - - -def upload_queue_dir() -> Path | None: - """货代上传 Excel 队列目录(RPA 从此处读取待上传文件)。""" - return _path("FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR") - - -def upload_trigger_dir() -> Path | None: - """RPA 货代上传触发 JSON 目录。""" - return _path("FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR") - - -def write_inventory_export_trigger(task_no: str, payload: dict[str, Any] | None = None) -> str | None: - """ - 写入 RPA 库存导出触发文件 inventory_export_{task_no}.json。 - - Returns: - str | None: 触发文件绝对路径;目录未配置时返回 None。 - """ - trigger_dir = inventory_trigger_dir() - if not trigger_dir: - return None - trigger_dir.mkdir(parents=True, exist_ok=True) - body = { - "action": "inventory_export", - "task_no": task_no, - "run_no": f"LEGACY-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}", - "requested_at": datetime.utcnow().isoformat(), - **(payload or {}), - } - path = trigger_dir / f"inventory_export_{task_no}.json" - _write_trigger_json_atomic(path, body) - return str(path) - - -def write_inventory_export_batch_trigger( - run_no: str, - sources: list[dict[str, Any]], - *, - payload: dict[str, Any] | None = None, -) -> str | None: - """ - 写入批量库存导出 trigger(DSV/Crane 一次登录多 Warehouse)。 - 【AI 触发时机】:定时排程或后台批量预热库存快照时调用。 - - Args: - run_no: RPA 批次号,写入回调 audit。 - sources: build_rpa_inventory_source 构造的源列表。 - payload: 额外字段(trigger_type、schedule_run_id 等)。 - - Returns: - str | None: 触发文件绝对路径。 - """ - trigger_dir = inventory_trigger_dir() - if not trigger_dir or not sources: - return None - trigger_dir.mkdir(parents=True, exist_ok=True) - inventory_sources = [] - for source in sources: - if not isinstance(source, dict) or not source.get("source_code"): - continue - # 调用方只持有非敏感快照;写 trigger 前在服务端按 Source 补入 Profile 密文。 - from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source - configuration_test = str((payload or {}).get('trigger_type') or '') in {'configuration_test', 'configuration_test_batch'} - trigger_source = get_rpa_trigger_inventory_source( - str(source["source_code"]), enabled_only=not configuration_test, - ) or source - source = {**source, **trigger_source} - business_connector = str(source.get("connector_type") or "").strip().lower() - worker_connector = {"dbs": "dsv360", "crane": "crane_footprint"}.get(business_connector, business_connector) - item = { - "source_code": source.get("source_code"), - "connector_type": business_connector, - "worker_connector_type": worker_connector, - "rpa_profile_code": source.get("rpa_profile_code"), - "warehouse_id": source.get("fixed_warehouse_id") or source.get("warehouse_id"), - "login_url": source.get("login_url"), - "entry_url": source.get("login_url"), - "navigation": source.get("navigation") or {}, - "parameters": source.get("parameters") or [], - "query": source.get("query") or {}, - "credential_envelope": source.get("credential_envelope") or {}, - # 配置测试回调据此将批次结果精确回写到各自站点运行。 - "validation_run_no": source.get("validation_run_no"), - } - # v2 逐源身份必须由后端显式写入,Worker 不得重新生成。 - for identity_key in ( - "callback_id", "task_no", "attempt_no", "source_run_no", "candidate_set_id", "candidate_set_version", - "execution_id", "gate_id", "expected_warehouse_id", "lease_token", - ): - if source.get(identity_key) is not None: - item[identity_key] = source[identity_key] - if not item.get('callback_id') and item.get('source_run_no'): - item['callback_id'] = f"{item['source_run_no']}:C1" - inventory_sources.append(item) - if not inventory_sources: - return None - - body = { - "action": "inventory_export_batch", - "schema_version": "shipping_inventory_rpa.v2", - "callback_id": f"{run_no}:batch:C1", - "batch_run_no": run_no, - "run_no": run_no, # 旧排程读取兼容;新回调不得依赖该字段 - "trigger_type": "scheduled", - "requested_at": datetime.utcnow().isoformat(), - "inventory_sources": inventory_sources, - **(payload or {}), - } - safe_run = "".join(ch for ch in run_no if ch.isalnum() or ch in {"-", "_"}) or "batch" - path = trigger_dir / f"inventory_export_batch_{safe_run}.json" - _write_trigger_json_atomic(path, body) - return str(path) - - -def inventory_rpa_batch_enabled() -> bool: - """是否启用按需单票走 batch trigger 统一路径(Flask config 优先于环境变量)。""" - raw = current_app.config.get("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED") - if raw is None: - raw = os.getenv("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", "true") - return str(raw).strip().lower() in {"1", "true", "yes", "on"} - - -def build_on_demand_inventory_trigger_source( - task_no: str, - rpa_source: dict[str, Any], - *, - body: dict[str, Any], -) -> dict[str, Any]: - """ - 构造按需库存导出批次触发内的单源条目(含 Profile 凭据与逐源身份键)。 - 【AI 触发时机】:单源 on-demand 触发与多候选合并批次触发(per_source_rpa_service)共用本构造, - 保证两条路径投递给 Worker 的输入契约完全一致。 - - Args: - task_no: 发货任务号。 - rpa_source: 调用方持有的非敏感源快照(含 source_code);DB 配置/Profile 存在时以其为准。 - body: 触发载荷,提供 callback_id/source_run_no/attempt_no/lease_token 等逐源身份键。 - - Returns: - 可直接传入 write_inventory_export_batch_trigger 的单源条目。 - """ - from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source - - source_code = str(rpa_source.get('source_code') or '').strip() - rpa_source = get_rpa_trigger_inventory_source(source_code) or rpa_source - # Legacy 单票 trigger 与 batch trigger 必须共享 worker 输入契约。 - rpa_source = dict(rpa_source) - business_connector = str(rpa_source.get('connector_type') or '').strip().lower() - rpa_source.setdefault('worker_connector_type', {'dbs': 'dsv360', 'crane': 'crane_footprint'}.get(business_connector, business_connector)) - rpa_source.setdefault('entry_url', rpa_source.get('login_url')) - rpa_source.setdefault('credential_envelope', {}) - source_item = dict(rpa_source) - source_item.update({ - "source_code": source_code, - "callback_id": body.get("callback_id") or ( - f"{body.get('source_run_no')}:C1" if body.get('source_run_no') else None - ), - "task_no": task_no, - # 按需逐源回调必须携带 Attempt 身份;仅写在 batch 顶层会导致 - # Worker 结果丢失 source_run_no,后端无法把 Excel 绑定到最新 Attempt。 - "attempt_no": body.get("attempt_no") or body.get("attempt"), - "source_run_no": body.get("source_run_no"), - "candidate_set_id": body.get("candidate_set_id"), - "candidate_set_version": body.get("candidate_set_version"), - "execution_id": body.get("execution_id"), - "gate_id": body.get("gate_id"), - "expected_warehouse_id": body.get("expected_warehouse_id"), - "lease_token": body.get("lease_token"), - }) - return source_item - - -def write_inventory_export_trigger_for_task( - task_no: str, - rpa_source: dict[str, Any], - *, - payload: dict[str, Any] | None = None, -) -> str | None: - """ - 写入按需库存 RPA trigger;batch 开启时包装为单源 batch trigger,与定时导出共用 worker 路径。 - 【AI 触发时机】:ensure_inventory_via_rpa 触发单票 RPA 导出时调用。 - - 核心逻辑:仅允许 v2 batch 模式写 inventory_export_batch;关闭时 fail-closed, - 不再生成 legacy inventory_export trigger。 - """ - body = dict(payload or {}) - if inventory_rpa_batch_enabled(): - run_no = str(body.get("batch_run_no") or f"BATCH-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}") - source_item = build_on_demand_inventory_trigger_source(task_no, rpa_source, body=body) - return write_inventory_export_batch_trigger( - run_no, - [source_item], - payload={ - "schema_version": "shipping_inventory_rpa.v2", - "trigger_type": "on_demand", - "task_no": task_no, - **body, - }, - ) - raise ValidationError( - 'shipping inventory RPA v2 batch trigger is required', - code='SHIPPING.INVENTORY_RPA_V2_REQUIRED', - ) - - -def write_upload_trigger( - task_no: str, - export_file_path: str, - payload: dict[str, Any] | None = None, - *, - attempt_id: int | None = None, - artifact_id: int | None = None, - connector_type: str | None = None, - upload_config: dict[str, Any] | None = None, - upload_config_hash: str | None = None, - login_url: str | None = None, - credential_envelope: dict[str, Any] | None = None, - callback_id: str | None = None, - business_no: str | None = None, -) -> tuple[str | None, str | None, str | None]: - """ - 复制发货 Excel 至共享上传队列,并以原子发布方式写入 RPA 上传触发 JSON。 - 【AI 触发时机】:upload_to_freight(mode=auto|retry_upload) 触发货代上传时调用。 - - 触发文件固化本次上传契约快照,Worker 据此进入 DSV/Crane 受控流程: - schema_version / task_no / attempt_id / artifact_id / callback_id(非空)/ - connector_type / upload_config(本次快照 + upload_config_hash)/ login_url / credential_envelope / file_path。 - 平台差异(文件选择器、提交与结果判定)由 Worker 的受控 Adapter 按 upload_config 执行。 - 写入复用“临时文件 + fsync + os.replace”原子方式,避免 Worker 读取半写 JSON。 - - Args: - task_no: 发货任务号。 - export_file_path: 待上传发货 Excel 的服务端路径。 - payload: 附加字段(如 mode),与下列具名参数合并。 - attempt_id: 本次 Upload Attempt 主键。 - artifact_id: 当前上传目标 Artifact 主键。 - connector_type: 业务连接类型(dbs / crane)。 - upload_config: 本次上传使用的连接级受控配置快照(enabled/entry_url/selector 等)。 - upload_config_hash: 该快照的 sha256,用于审计关联。 - login_url: 该连接登录地址(先登录,再访问 upload_config.entry_url 进入上传页)。 - credential_envelope: 连接凭据密文信封(Worker 据此登录)。 - callback_id: 回调幂等 ID;为空时自动生成,保证非空。 - business_no: 发货通知对外业务编号(业务单号),用于精简上传文件名;为空时回退 task_no。 - - Returns: - tuple[str | None, str | None, str | None]: (queue 文件路径, trigger 文件路径, callback_id); - 失败时 (None, None, None)。 - """ - queue = upload_queue_dir() - trigger_dir = upload_trigger_dir() - if not queue or not trigger_dir: - return None, None, None - queue.mkdir(parents=True, exist_ok=True) - trigger_dir.mkdir(parents=True, exist_ok=True) - - src = Path(export_file_path) - if not src.is_file(): - return None, None, None - # [STEP] 精简上传文件名:仅用业务编号(业务单号),避免 task_no 与导出文件名重复拼接过长; - # 业务编号为空时回退到内部任务号,扩展名沿用源文件(无扩展名时按 xlsx 兜底)。 - emit_no = str(business_no or '').strip() or task_no - suffix = str(src.suffix or '.xlsx').lower() - dest = queue / f"{emit_no}{suffix}" - shutil.copy2(src, dest) - - resolved_callback_id = str(callback_id or '').strip() or f'upload:{task_no}:{uuid.uuid4().hex[:12]}' - body = { - "action": "shipment_upload", - "schema_version": "shipping_notice_upload_rpa.v1", - "task_no": task_no, - "attempt_id": attempt_id, - "artifact_id": artifact_id, - "callback_id": resolved_callback_id, - "connector_type": str(connector_type or '').strip() or None, - "upload_config": upload_config, - "upload_config_hash": upload_config_hash, - "login_url": login_url, - "credential_envelope": credential_envelope, - "file_path": str(dest), - "requested_at": datetime.utcnow().isoformat(), - **(payload or {}), - } - trigger_path = trigger_dir / f"upload_{task_no}.json" - _write_trigger_json_atomic(trigger_path, body) - return str(dest), str(trigger_path), resolved_callback_id - - -def find_latest_inventory_file() -> Path | None: - """在 drop 目录中查找最新修改的 xlsx/xls/csv 库存文件。""" - drop = inventory_drop_dir() - if not drop or not drop.is_dir(): - return None - candidates = [ - p for p in drop.iterdir() - if p.is_file() and p.suffix.lower() in {".xlsx", ".xls", ".csv"} - ] - if not candidates: - return None - return max(candidates, key=lambda p: p.stat().st_mtime) diff --git a/backend/app/services/shipping_notice/rpa_sinks.py b/backend/app/services/shipping_notice/rpa_sinks.py new file mode 100644 index 00000000..6921e8dd --- /dev/null +++ b/backend/app/services/shipping_notice/rpa_sinks.py @@ -0,0 +1,85 @@ +""" +services/shipping_notice/rpa_sinks.py + +用途:onhand(在手库存)RPA 回调与报表事实的组合根注册——把 /api/freight-rpa/onhand-* + 接到发货域业务处理器。入站 / 出站注册见 in_transit_transfer.rpa_sinks。 +依赖:freight_rpa.common.callback_sinks、freight_rpa.reports.dispatch、 + onhand_rpa_workflow、per_source_rpa_service、onhand_configuration_test、 + onhand_report_handler。 +逻辑:由 app.create_app 调用 register_onhand_sinks()(幂等)。进度类 sink 复刻旧 + shipping-notice rpa 回调 envelope;onhand-repair 注入 payload['repair']=True; + 文件事实经 register_report_handler('onhand', handle_onhand_report) 注册。 +""" + +from __future__ import annotations + +from typing import Any, Callable + + +def _bare(handler: Callable[[dict[str, Any]], dict[str, Any]]) -> Callable[..., dict[str, Any]]: + """旧端点直接 jsonify(业务函数返回值)——裸业务 dict envelope(inventory-ready 同款)。""" + + def _sink(**payload: Any) -> dict[str, Any]: + return handler(payload) + + return _sink + + +def _ok_data_envelope(handler: Callable[[dict[str, Any]], dict[str, Any]]) -> Callable[..., dict[str, Any]]: + """旧 /rpa/inventory-configuration-test-* 的 envelope:{'status':'ok','data':业务结果}。""" + + def _sink(**payload: Any) -> dict[str, Any]: + return {'status': 'ok', 'data': handler(payload)} + + return _sink + + +def _success_data_envelope(handler: Callable[[dict[str, Any]], dict[str, Any]]) -> Callable[..., dict[str, Any]]: + """旧 /rpa/inventory-batch-claimed 的 envelope:{'success':True,'data':业务结果}。""" + + def _sink(**payload: Any) -> dict[str, Any]: + return {'success': True, 'data': handler(payload)} + + return _sink + + +def _onhand_repair_sink(**payload: Any) -> dict[str, Any]: + """受控库存回调修复:等价旧 /rpa/inventory-repair——payload['repair']=True 后走 batch-ready ingest。""" + from app.services.shipping_notice.onhand_rpa_workflow import rpa_report_inventory_batch + + payload['repair'] = True + return rpa_report_inventory_batch(payload) + + +def register_onhand_sinks() -> None: + """组合根入口:注册全部 onhand 回调 sink 与 onhand 事实处理函数(幂等;create_app 每次启动调用)。 + + 核心逻辑:进度类 kind 命名 = /api/freight-rpa/* 回调路由名去前缀,被包装函数全部住在 + shipping_notice(业务落盘留守域)——认领(claim_inventory_batch)与批量编排留 + per_source_rpa_service,本层只做 envelope 复刻与分发接线;文件事实处理函数走 + reports.dispatch:'onhand' kind 注册 handle_onhand_report。 + """ + from app.services.freight_rpa.common.callback_sinks import register_sink + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.shipping_notice import onhand_configuration_test, onhand_rpa_workflow + from app.services.shipping_notice.onhand_report_handler import handle_onhand_report + from app.services.shipping_notice.per_source_rpa_service import claim_inventory_batch + + register_sink('onhand-ready', _bare(onhand_rpa_workflow.rpa_report_inventory)) + register_sink('onhand-batch-ready', _bare(onhand_rpa_workflow.rpa_report_inventory_batch)) + register_sink('onhand-batch-claimed', _success_data_envelope(claim_inventory_batch)) + register_sink('onhand-batch-progress', _bare(onhand_rpa_workflow.report_inventory_batch_progress)) + register_sink( + 'onhand-configuration-test-start', + _ok_data_envelope(onhand_configuration_test.report_batch_test_progress), + ) + register_sink( + 'onhand-configuration-test-analyze', + _ok_data_envelope(onhand_configuration_test.report_test_export), + ) + register_sink( + 'onhand-configuration-test-complete', + _ok_data_envelope(onhand_configuration_test.report_batch_test_exports), + ) + register_sink('onhand-repair', _onhand_repair_sink) + register_report_handler('onhand', handle_onhand_report) diff --git a/backend/app/services/shipping_notice/runtime_context.py b/backend/app/services/shipping_notice/runtime_context.py index d03bdb00..78f1529e 100644 --- a/backend/app/services/shipping_notice/runtime_context.py +++ b/backend/app/services/shipping_notice/runtime_context.py @@ -120,7 +120,7 @@ def _build_state_hint(task: ShippingNotice | None) -> dict[str, Any]: owner = task if isinstance(task, ShippingNotice) and task.order_task_id: owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task - from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt match_status = aggregate_match_status_for_task(getattr(owner, 'id', None)) or '' upload_status = str(getattr(latest_upload_attempt(task), 'status', None) or '').strip() diff --git a/backend/app/services/shipping_notice/shipping_notice_creation_service.py b/backend/app/services/shipping_notice/shipping_notice_creation_service.py index 2f2c76f3..55ed4598 100644 --- a/backend/app/services/shipping_notice/shipping_notice_creation_service.py +++ b/backend/app/services/shipping_notice/shipping_notice_creation_service.py @@ -88,8 +88,8 @@ def create_shipping_notice_after_inventory_gate( # 正式 Notice 只能建立在当前库存匹配事实完整通过之后;库存准备失败或仍有未处理行时, # OT 必须停留在通知准备阶段,不得产生 Notice/NoticeLine。 - from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch, ShippingTaskInventoryLink - fact_rows = ShippingNoticeLineInventoryMatch.query.filter_by( + from app.models import FreightRpaOnhandReportFile, ShippingNoticeLineOnhandMatch, ShippingTaskOnhandLink + fact_rows = ShippingNoticeLineOnhandMatch.query.filter_by( task_id=int(order_task.id), is_current=True, ).all() by_line = {int(row.snapshot_line_id): row for row in fact_rows if row.snapshot_line_id is not None} @@ -106,7 +106,7 @@ def create_shipping_notice_after_inventory_gate( or ( not ( str(by_line[int(line_id)].match_result or '').strip().lower() == 'matched' - and str(by_line[int(line_id)].inventory_status or '').strip().lower() == 'ready' + and str(by_line[int(line_id)].onhand_status or '').strip().lower() == 'ready' ) and int(line_id) not in released_ids ) @@ -114,29 +114,29 @@ def create_shipping_notice_after_inventory_gate( ): raise ConflictError( "Inventory matching must pass before creating a shipping notice", - code="SHIPPING.INVENTORY_GATE_NOT_PASSED", + code="SHIPPING.ONHAND_GATE_NOT_PASSED", ) inventory_facts_by_snapshot_line_id: dict[int, dict[str, object]] = {} for snapshot_line_id in target_ids: match = by_line[int(snapshot_line_id)] inventory_file = ( - db.session.get(ShippingInventoryFile, int(match.inventory_snapshot_id)) - if match.inventory_snapshot_id is not None + db.session.get(FreightRpaOnhandReportFile, int(match.onhand_snapshot_id)) + if match.onhand_snapshot_id is not None else None ) link = ( - ShippingTaskInventoryLink.query.filter_by( + ShippingTaskOnhandLink.query.filter_by( task_id=int(order_task.id), - inventory_file_id=int(inventory_file.id), - matched_source_code=match.inventory_source_code, + onhand_file_id=int(inventory_file.id), + matched_source_code=match.source_code, is_active=True, - ).order_by(ShippingTaskInventoryLink.id.desc()).first() + ).order_by(ShippingTaskOnhandLink.id.desc()).first() if inventory_file is not None else None ) inventory_facts_by_snapshot_line_id[int(snapshot_line_id)] = { - 'inventory_source_code': match.inventory_source_code, + 'inventory_source_code': match.source_code, 'inventory_file_id': int(inventory_file.id) if inventory_file is not None else None, 'inventory_warehouse_id': ( str(getattr(link, 'matched_warehouse_id', '') or '').strip().upper() diff --git a/backend/app/services/shipping_notice/shipping_processing_projection.py b/backend/app/services/shipping_notice/shipping_processing_projection.py index 4018b62f..062b3380 100644 --- a/backend/app/services/shipping_notice/shipping_processing_projection.py +++ b/backend/app/services/shipping_notice/shipping_processing_projection.py @@ -104,6 +104,9 @@ class _ConversationProjectionLoadContext: # 冻结选择计划中每个 Intake 的附件项(含已选/跳过状态),用于把尚未物化的 # 「已选但未识别」附件展示出来,便于排查未识别原因。 planned_attachments_by_intake_no: dict[str, list[dict[str, Any]]] + # reparse_pending Case 且后继 Run 仍 queued/processing 的文档 id 集合; + # EML 聚合叶子据此把在途重识别投影为 processing(与摘要 _status 同判词)。 + active_reparse_document_ids: set[int] prefetched_gate_attempts: list[ShippingProcessGateAttempt] read_cache: dict[str, Any] @@ -346,12 +349,32 @@ def _conversation_projection_load_context( str(getattr(intake, 'source_type', '') or '').strip().lower() == 'eml' for intake in intakes ) + # [STEP] 在途重解析文档集:reparse_pending Case 的后继 Run 仍 queued/processing + # 时系统正在重新识别该文件。EML 聚合叶子据此统一改判 processing,避免 Case + # 被排除后退化成无入口 waiting_human(与摘要 _status 同判词,回归盲窗)。 + active_reparse_document_ids: set[int] = set() + reparse_source_run_ids = { + int(case.run_id) + for case in read_cache['current_case_by_document_id'].values() + if case.confirmed_task_id is None + and case.run_id is not None + and str(case.status or '').strip().lower() == 'reparse_pending' + } + if reparse_source_run_ids: + for successor in ShippingOrderProcessingRun.query.filter( + ShippingOrderProcessingRun.reparse_of_run_id.in_(reparse_source_run_ids), + ShippingOrderProcessingRun.status.in_(('queued', 'processing')), + ).all(): + marker = (successor.input_snapshot_json or {}).get('review_reparse') + if isinstance(marker, dict) and int(marker.get('document_id') or 0) > 0: + active_reparse_document_ids.add(int(marker['document_id'])) return _ConversationProjectionLoadContext( documents_by_intake_id=documents_by_intake_id, intakes_by_no={str(intake.intake_no): intake for intake in intakes}, planned_attachments_by_intake_no=( _frozen_attachment_plan_by_intake(intake_ids) if has_eml_intake else {} ), + active_reparse_document_ids=active_reparse_document_ids, prefetched_gate_attempts=prefetched_gate_attempts, read_cache=read_cache, ) @@ -466,9 +489,9 @@ _ACTIVITY_TO_PROCESSING_STAGE: dict[str, str] = { 'review_required': 'waiting_review', 'waiting_review': 'waiting_review', 'order_creating': 'order_creating', - 'inventory_source_resolving': 'inventory_source_resolving', - 'inventory_fetching': 'inventory_fetching', - 'inventory_matching': 'inventory_matching', + 'onhand_source_resolving': 'onhand_source_resolving', + 'onhand_fetching': 'onhand_fetching', + 'onhand_matching': 'onhand_matching', 'excel_generating': 'excel_generating', 'freight_uploading': 'freight_uploading', 'completed': 'completed', @@ -2069,14 +2092,14 @@ def _project_order_task_work_item( inventory_preparation = None if notice is not None: try: - from app.models import ShippingInventoryPreparationAttempt + from app.models import ShippingOnhandPreparationAttempt preparation_task_id = getattr(order_task, 'id', None) if order_task is not None else getattr(notice, 'order_task_id', None) preparation = ( - ShippingInventoryPreparationAttempt.query + ShippingOnhandPreparationAttempt.query .filter_by(task_id=int(preparation_task_id)) - .filter(ShippingInventoryPreparationAttempt.status != 'superseded') - .order_by(ShippingInventoryPreparationAttempt.attempt_no.desc()) + .filter(ShippingOnhandPreparationAttempt.status != 'superseded') + .order_by(ShippingOnhandPreparationAttempt.attempt_no.desc()) .first() ) source_attempts = list(getattr(preparation, 'source_attempts', []) or []) if preparation else [] @@ -2090,7 +2113,7 @@ def _project_order_task_work_item( 'attempt_no': int(preparation.attempt_no), 'status': row.status, 'rpa_attempt_id': row.rpa_attempt_id, - 'inventory_file_id': row.inventory_file_id, + 'inventory_file_id': row.onhand_file_id, } for row in source_attempts } @@ -2114,7 +2137,7 @@ def _project_order_task_work_item( # PreparationAttempt 读取发生在首次用户态归一化之后;立即重新应用 # fail-closed 规则,防止异常分支保留旧 primary_action/available_actions。 payload = apply_user_projection_fields(payload, notice=notice, order_task=order_task) - payload['inventory_preparation'] = inventory_preparation + payload['onhand_preparation'] = inventory_preparation # pre_ot_stp 是内部责任阶段,不是会话时间线展示枚举;最终输出统一为正式建单节点。 if str(payload.get('user_stage') or '').strip().lower() == 'pre_ot_stp': @@ -2721,6 +2744,25 @@ def _eml_aggregate_document_children( summary['candidate_count'] = int( has_current_candidate ) + if ( + existing is None + and load_context is not None + and int(document.id) in load_context.active_reparse_document_ids + ): + # [STEP] 重解析后继 Run 在途:该文档正在重新识别。无 OT 叶子按旧 + # Case/Unit 事实会退化成无入口 waiting_human(回归盲窗),这里与摘要 + # _status 同判词改判 processing,保留接收解析阶段入口、不下发任何动作。 + leaf.update({ + 'status': 'processing', + 'stage': 'document_parsing', + 'user_status': 'running', + 'user_stage': 'document_parsing', + 'user_group': 'processing', + 'blocking_reason': None, + 'available_actions': [], + 'primary_action': None, + 'intake_parse_authorized': True, + }) leaf['source_summary'] = summary # 文件主动作保留 Case / Gate 已裁决的真实动作码。生命周期导航由 # ui_state.lifecycle_entries 单独表达,不能为消除重复而篡改业务动作。 @@ -3288,8 +3330,8 @@ def _action_lifecycle_target(action_code: Any, *, lifecycle_stage: str | None) - # 空 Candidate Case 的同一入口用于解析处置;不得借动作码跳到订单复核。 return 'order_review' if lifecycle_stage == 'order_review' else 'intake_parse' if code in { - 'open_inventory_match_review', 'match_inventory', 'rematch', 'open_shortage_review', - 'upload_inventory_file', 'retry_inventory_preparation', 'regenerate_excel', 'generate_excel', + 'open_onhand_match_review', 'match_inventory', 'rematch', 'open_shortage_review', + 'upload_onhand_file', 'retry_onhand_preparation', 'regenerate_excel', 'generate_excel', }: return 'fulfillment_prep' if code in { @@ -4053,7 +4095,8 @@ def project_conversation_processing_summary( 绑定的可复核 Candidate;不得用「Case 存在」或「文档上另有未绑定 Candidate」 抬升 candidate_count / waiting_review→order_review。 - 开放 Case 的用户态须先认活跃 STP Job(queued/running → running),再认草稿 + 开放 Case 的用户态须先认在途重解析后继 Run(reparse_pending → running), + 再认活跃 STP Job(queued/running → running),再认草稿 can_auto_create+can_build 未超时(waiting_to_start → running),与工作台 project_case_user_status 同源;不得仅因 Case 未确认就判 waiting_human。 """ @@ -4310,6 +4353,39 @@ def project_conversation_processing_summary( ) } + # [STEP] 开放 Case 的在途重解析探测:reparse_pending Case 的后继 Run + # (reparse_of_run_id 指向源 Run)仍 queued/processing 时,系统正在重新识别 + # 该文件。摘要首屏禁止加载 Plan/Unit,故只按谱系列 + 快照标记判定,命中即判 + # processing(回归 2026-10-14 批次中心重解析盲窗:五阶段按钮全消 + 冻结待人工)。 + active_reparse_by_document_id: dict[int, str] = {} + reparse_source_run_ids = { + int(case.run_id) + for case in current_case_by_document_id.values() + if case.confirmed_task_id is None + and case.run_id is not None + and str(case.status or '').strip().lower() == 'reparse_pending' + } + if reparse_source_run_ids: + for successor in ( + ShippingOrderProcessingRun.query.options(load_only( + ShippingOrderProcessingRun.id, + ShippingOrderProcessingRun.reparse_of_run_id, + ShippingOrderProcessingRun.status, + ShippingOrderProcessingRun.input_snapshot_json, + )).filter( + ShippingOrderProcessingRun.reparse_of_run_id.in_(reparse_source_run_ids), + ShippingOrderProcessingRun.status.in_(('queued', 'processing')), + ).order_by(ShippingOrderProcessingRun.id.desc()).all() + ): + marker = (successor.input_snapshot_json or {}).get('review_reparse') + if not isinstance(marker, dict): + continue + reparse_document_id = int(marker.get('document_id') or 0) + if reparse_document_id > 0: + active_reparse_by_document_id.setdefault( + reparse_document_id, str(successor.status or ''), + ) + # [STEP] 开放 Case 批量预取活跃 STP Job(与 full 会话投影同构前缀), # 供摘要 _status 在判 waiting_human 前与工作台同源认「系统仍在建单」。 _OPEN_CASE_STATUSES_FOR_STP = { @@ -4446,6 +4522,10 @@ def project_conversation_processing_summary( if case is not None and case.confirmed_task_id is None and case_status in _OPEN_CASE_STATUSES_FOR_STP: # 活跃 STP 或 waiting_to_start = 系统仍在建单;与 project_case_user_status 对齐。 doc_id = int(case.document_id) if case.document_id is not None else int(document.id) + if doc_id in active_reparse_by_document_id: + # 重解析后继 Run 在途(queued/processing):系统正在重新识别本文件, + # 先于 STP/草稿判 running;终态由 finalize_document_reparse 收口改判。 + return 'running', 'document_parsing', None stp_status = active_stp_status_by_document_id.get(doc_id) if stp_status in {'queued', 'running'}: mapped = project_case_user_status(case, {'status': stp_status}) @@ -4618,6 +4698,12 @@ def project_conversation_processing_summary( 'variant': 'primary', 'label_key': 'shipping.actions.open_order_review', } + if int(document.id) in active_reparse_by_document_id: + # 重解析在途:不下发任何动作(服务端幂等复用在途后继),但保留接收解析 + # 阶段入口,否则批次中心该行会退化成无五阶段按钮的 waiting_human。 + available_actions = [] + primary_action = None + intake_parse_authorized = True leaf = { 'work_item_type': 'order_task', 'work_item_no': f'DOCUMENT:{document.id}', diff --git a/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py b/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py index 7c9ec858..c1835b6c 100644 --- a/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py +++ b/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py @@ -14,7 +14,7 @@ import logging from flask import current_app from app import db -from app.models import ShippingOrderTask, ShippingTaskInventoryRpaAttempt +from app.models import ShippingOrderTask, FreightRpaOnhandTaskAttempt _LOGGER = logging.getLogger(__name__) @@ -36,7 +36,7 @@ def shipping_recovery_tick() -> int: # 根据最新 Attempt/Gate 状态刷新按钮与阻断原因。 inventory_timeout_seconds = max(int(getattr( current_app.config, - 'FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS', + 'FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS', 900, ) or 900), 1) inventory_scan_count = _scan_stale_inventory_attempts( @@ -67,8 +67,8 @@ def _scan_stale_inventory_attempts(*, timeout_seconds: int) -> int: """ task_nos = [ str(row[0]) - for row in db.session.query(ShippingTaskInventoryRpaAttempt.task_no) - .filter(ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running'))) + for row in db.session.query(FreightRpaOnhandTaskAttempt.task_no) + .filter(FreightRpaOnhandTaskAttempt.status.in_(('queued', 'running'))) .distinct() .all() ] diff --git a/backend/app/services/shipping_notice/state_machine.py b/backend/app/services/shipping_notice/state_machine.py index ea85d0dc..76302cee 100644 --- a/backend/app/services/shipping_notice/state_machine.py +++ b/backend/app/services/shipping_notice/state_machine.py @@ -364,7 +364,7 @@ def apply_task_transition(task: ShippingNotice, transition: TaskTransition) -> N 将命名业务事实迁移写入 ShippingNotice 的领域结果字段与 review/pending 事实。 核心逻辑:查 TASK_TRANSITIONS 表驱动字段更新;所有 Tool 写库须经本函数,禁止散落赋值。 - 库存相关迁移后同步挂接 OT 的 stage(waiting_inventory → inventory_fetching 等)。 + 库存相关迁移后同步挂接 OT 的 stage(waiting_inventory → onhand_fetching 等)。 Args: task: 待更新的 ShippingNotice 实例(尚未 commit)。 diff --git a/backend/app/services/shipping_notice/stp_line_inventory_match.py b/backend/app/services/shipping_notice/stp_line_onhand_match.py similarity index 94% rename from backend/app/services/shipping_notice/stp_line_inventory_match.py rename to backend/app/services/shipping_notice/stp_line_onhand_match.py index a246421e..18b08f1d 100644 --- a/backend/app/services/shipping_notice/stp_line_inventory_match.py +++ b/backend/app/services/shipping_notice/stp_line_onhand_match.py @@ -1,10 +1,10 @@ """ -services/shipping_notice/stp_line_inventory_match.py +services/shipping_notice/stp_line_onhand_match.py 用途:STP 阶段 4 跨冻结候选库存源按有效 Reservation + Part Number 匹配并落实行级裁决。 -依赖:stp_inventory_freeze、reservation_id、inventory_snapshot_store、inventory_source_repository、 - inventory_source_rules、ShippingOrderSnapshot。 -逻辑:ensure_inventory 合并候选快照行;match 按 Reservation+Part(可选单位)检索,库存行不强制 +依赖:stp_onhand_freeze、reservation_id、onhand_snapshot_store、onhand_source_repository、 + onhand_source_rules、ShippingOrderSnapshot。 +逻辑:ensure_onhand 合并候选快照行;match 按 Reservation+Part(可选单位)检索,库存行不强制 __source_code(源已在选源/载入 Excel 时确定);多文件命中为冲突;唯一命中且数量充足则冻结 resolved 源与行证据;多源可履约行暂停 Excel(step_payload 标记);人工指定源后 forced_match_source_code 过滤库存行再匹配;结果写入 step_payload / line_results_json。 @@ -18,21 +18,21 @@ from typing import Any from app import db from app.models import ShippingOrderSnapshot, ShippingNotice -from app.services.shipping_notice.inventory_candidate_projection import ( +from app.services.shipping_notice.onhand_candidate_projection import ( get_active_candidate_lines, get_active_candidate_set, ) -from app.services.shipping_notice.inventory_source_repository import ( +from app.services.shipping_notice.onhand_source_repository import ( get_database_inventory_source, inventory_sources_runtime_version, ) -from app.services.shipping_notice.inventory_source_rules import ( +from app.services.shipping_notice.onhand_source_rules import ( compute_routing_fingerprint, extract_routing_context, ) from app.services.shipping_notice.order_schema.field_rules import compute_effective_reservation_id from app.services.shipping_notice.reservation_id import validated_reservation_id -from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes +from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes def _norm_part(value: Any) -> str: @@ -142,7 +142,7 @@ def snapshot_header_reservation_id(snapshot: ShippingOrderSnapshot | None) -> st return validated_reservation_id(header_values.get('reservation_id')) -def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]: +def prepare_candidate_onhand_lines(task: ShippingNotice) -> dict[str, Any]: """ 为任务准备全部冻结候选源的有效库存行(打上 __source_code 标签)。 @@ -156,8 +156,8 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]: Returns: status / lines / missing_source_codes / loaded_source_codes / evidence。 """ - from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines - from app.services.shipping_notice.inventory_snapshot_store import find_latest_ready_snapshot + from app.services.shipping_notice.onhand_file_store import read_inventory_file_lines + from app.services.shipping_notice.onhand_snapshot_store import find_latest_ready_snapshot current_set = get_active_candidate_set(task) if current_set is None: @@ -174,7 +174,7 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]: } candidate_lines = get_active_candidate_lines(task) - task_level_codes = list(task_frozen_inventory_source_codes(task)) + task_level_codes = list(task_frozen_onhand_source_codes(task)) required_codes: list[str] = [] for line in candidate_lines: for raw in list(getattr(line, 'source_codes_json', None) or []): @@ -225,21 +225,21 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]: evidence.append({ 'source_code': code, 'status': 'snapshot_empty', - 'inventory_file_no': snapshot.inventory_file_no, + 'inventory_file_no': snapshot.onhand_file_no, 'required': in_required, }) continue for row in lines: tagged = dict(row) tagged['__source_code'] = code - tagged['__inventory_file_no'] = snapshot.inventory_file_no + tagged['__inventory_file_no'] = snapshot.onhand_file_no merged.append(tagged) loaded.append(code) evidence.append({ 'source_code': code, 'status': 'loaded', 'candidate_set_id': int(current_set.id), - 'inventory_file_no': snapshot.inventory_file_no, + 'inventory_file_no': snapshot.onhand_file_no, 'line_count': len(lines), 'required': in_required, }) @@ -540,7 +540,7 @@ def match_order_lines_across_candidates( } -def apply_line_inventory_resolutions(task: ShippingNotice, match_payload: dict[str, Any]) -> None: +def apply_line_onhand_resolutions(task: ShippingNotice, match_payload: dict[str, Any]) -> None: """ 将跨候选匹配结果交给行级 Match 持久化;不再把库存匹配事实写入 OT.step_payload_json。 """ @@ -556,10 +556,10 @@ def multi_source_recovery_source_codes(task: ShippingNotice) -> list[str]: candidate_hit_source_codes;若冲突行缺失该候选(如历史事实未记录),回退为全部可用 库存源(list_database_inventory_sources)兜底,保证用户在候选缺失时仍能指定库存源。 """ - from app.services.shipping_notice.inventory_source_repository import ( + from app.services.shipping_notice.onhand_source_repository import ( list_database_inventory_sources, ) - from app.services.shipping_notice.line_inventory_match_projection import ( + from app.services.shipping_notice.line_onhand_match_projection import ( load_current_match_facts_by_task, ) codes: list[str] = [] @@ -603,7 +603,7 @@ def apply_forced_match_source_filter( 过滤后的库存行;无强制源时原样返回。 """ if task.__class__.__name__ == 'ShippingOrderTask': - from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines + from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_lines selected = set() for row in get_active_candidate_lines(task): selected.update(str(code or '').strip().upper() for code in (getattr(row, 'source_codes_json', None) or []) if str(code or '').strip()) diff --git a/backend/app/services/shipping_notice/stp_inventory_freeze.py b/backend/app/services/shipping_notice/stp_onhand_freeze.py similarity index 91% rename from backend/app/services/shipping_notice/stp_inventory_freeze.py rename to backend/app/services/shipping_notice/stp_onhand_freeze.py index 5458af24..dd6855ce 100644 --- a/backend/app/services/shipping_notice/stp_inventory_freeze.py +++ b/backend/app/services/shipping_notice/stp_onhand_freeze.py @@ -1,8 +1,8 @@ """ -services/shipping_notice/stp_inventory_freeze.py +services/shipping_notice/stp_onhand_freeze.py 用途:建单时将资格服务的行级库存源候选冻结到 CandidateSet,供后续库存准备消费。 -依赖:inventory_source_gate、inventory_source_repository、inventory_source_rules、tool_common。 +依赖:onhand_source_gate、onhand_source_repository、onhand_source_rules、tool_common。 逻辑:由 confirm_review_case / STP 自动建单调用;单候选直接 resolved; 多候选写入 candidates_frozen(视为可进入库存准备,不再强制 inventory_source_review); 冻结结果写入 ShippingTaskEvent(candidates_frozen / inventory_source_resolved_at_build)。 @@ -13,18 +13,18 @@ from __future__ import annotations from typing import Any from app.models import ShippingNotice -from app.services.shipping_notice.inventory_candidate_freeze_service import ( +from app.services.shipping_notice.onhand_candidate_freeze_service import ( freeze_candidates_for_task, ) -from app.services.shipping_notice.inventory_candidate_projection import ( +from app.services.shipping_notice.onhand_candidate_projection import ( get_active_candidate_sources, ) -from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication -from app.services.shipping_notice.inventory_source_repository import ( +from app.services.shipping_notice.onhand_source_gate import apply_inventory_source_adjudication +from app.services.shipping_notice.onhand_source_repository import ( get_database_inventory_source, inventory_sources_runtime_version, ) -from app.services.shipping_notice.inventory_source_rules import ( +from app.services.shipping_notice.onhand_source_rules import ( InventorySourceAdjudication, _candidate, compute_routing_fingerprint, @@ -56,7 +56,7 @@ def collect_frozen_candidate_codes(line_projections: list[dict[str, Any]] | None return codes -def freeze_stp_inventory_candidates_on_task( +def freeze_stp_onhand_candidates_on_task( task: ShippingNotice, *, line_projections: list[dict[str, Any]] | None, @@ -183,7 +183,7 @@ def freeze_stp_inventory_candidates_on_task( return adjudication -def task_frozen_inventory_source_codes(task: ShippingNotice) -> list[str]: +def task_frozen_onhand_source_codes(task: ShippingNotice) -> list[str]: """ 读取任务上冻结的候选库存源(单源任务则回退 inventory_source_code)。 diff --git a/backend/app/services/shipping_notice/stp_progress_contract.py b/backend/app/services/shipping_notice/stp_progress_contract.py index 669c5204..da7b7fec 100644 --- a/backend/app/services/shipping_notice/stp_progress_contract.py +++ b/backend/app/services/shipping_notice/stp_progress_contract.py @@ -103,7 +103,7 @@ def project_task_progress_nodes(task: Any) -> list[dict[str, Any]]: ).strip().lower() direct_match_status = getattr(task, 'match_status', None) if direct_match_status is None and task.__class__.__name__ == 'ShippingOrderTask': - from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task match_facts = list(load_current_match_facts_by_task(getattr(task, 'id', None)).values()) match_status = 'matched' if match_facts and all( @@ -112,7 +112,7 @@ def project_task_progress_nodes(task: Any) -> list[dict[str, Any]]: for row in match_facts ) else ('shortage' if match_facts else '') elif direct_match_status is None: - from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task match_status = str(aggregate_match_status_for_task(getattr(task, 'order_task_id', None) or getattr(task, 'id', None)) or '').strip().lower() else: match_status = str(direct_match_status or '').strip().lower() @@ -128,7 +128,7 @@ def project_task_progress_nodes(task: Any) -> list[dict[str, Any]]: artifact = latest_export_artifact(task) has_export = bool(str(getattr(artifact, 'file_name', '') or '').strip()) projected_upload = project_notice_upload_status(task) - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task progress_state = ( 'uploaded' if projected_upload == 'uploaded' else 'upload_failed' if projected_upload == 'failed' else diff --git a/backend/app/services/shipping_notice/task_candidate_reconciliation.py b/backend/app/services/shipping_notice/task_candidate_reconciliation.py index be308e4c..91359f89 100644 --- a/backend/app/services/shipping_notice/task_candidate_reconciliation.py +++ b/backend/app/services/shipping_notice/task_candidate_reconciliation.py @@ -93,7 +93,7 @@ def _target_is_safe(task: ShippingNotice) -> bool: if str(task_blocking_reason(task) or '').strip().lower() != PH_RSV_REQ: return False - from app.services.shipping_notice.inventory_file_store import ( + from app.services.shipping_notice.onhand_file_store import ( current_inventory_matches_for_task, has_ready_inventory_file_for_task, ) diff --git a/backend/app/services/shipping_notice/task_disposition_service.py b/backend/app/services/shipping_notice/task_disposition_service.py index 7157ad02..4e49fe5f 100644 --- a/backend/app/services/shipping_notice/task_disposition_service.py +++ b/backend/app/services/shipping_notice/task_disposition_service.py @@ -25,9 +25,9 @@ from app.models import ( ShippingCustomerShadowResolution, ShippingNotice, ShippingTaskEvent, - ShippingTaskInventoryLink, + ShippingTaskOnhandLink, ShippingTaskPurgeAudit, - ShippingNoticeLineInventoryMatch, + ShippingNoticeLineOnhandMatch, ) from app.models.shipping_task_line import ShippingTaskFieldConflict @@ -307,8 +307,8 @@ def move_task_to_recycle_bin( ).filter(ShippingCustomerShadowResolution.confirmed_customer_id.isnot(None)).first() ) or getattr(owner_task, 'candidate_id', None) - or bool(db.session.query(ShippingNoticeLineInventoryMatch.id).filter_by(task_id=int(owner_task.id), is_current=True).first()) - or db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(owner_task.id)).first() + or bool(db.session.query(ShippingNoticeLineOnhandMatch.id).filter_by(task_id=int(owner_task.id), is_current=True).first()) + or db.session.query(ShippingTaskOnhandLink.id).filter_by(task_id=int(owner_task.id)).first() or db.session.query(ShippingOrderCandidate.id).filter_by(consumed_task_id=int(owner_task.id)).first() or ( isinstance(task, ShippingNotice) @@ -442,11 +442,11 @@ def purge_task_permanently( if isinstance(task, ShippingOrderTask): blocking_counts = { 'current_order_extraction': int(bool(task.current_order_extraction_id)), - 'inventory_snapshot': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(), + 'onhand_snapshot': db.session.query(ShippingTaskOnhandLink.id).filter_by(task_id=int(task.id)).count(), 'candidate_consumed': db.session.query(ShippingOrderCandidate.id).filter_by(consumed_task_id=int(task.id)).count(), 'intake_consumed': db.session.query(ShippingOrderIntake.id).filter_by(consumed_task_id=int(task.id)).count(), 'order_extraction': db.session.query(ShippingOrderExtraction.id).filter_by(task_id=int(task.id)).count(), - 'inventory_link': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(), + 'inventory_link': db.session.query(ShippingTaskOnhandLink.id).filter_by(task_id=int(task.id)).count(), 'field_conflict': db.session.query(ShippingTaskFieldConflict.id).filter_by(task_id=int(task.id)).count(), } blocking = {key: value for key, value in blocking_counts.items() if value} @@ -465,7 +465,7 @@ def purge_task_permanently( )) return - from app.models import ShippingTemporaryInventorySession + from app.models import ShippingTemporaryOnhandSession # [STEP 1] 不依赖前端预检,事务内重新统计全部会破坏可追溯性的引用。 owner = task if hasattr(task, 'current_order_extraction_id') else None @@ -481,19 +481,19 @@ def purge_task_permanently( 'source_intake': int(bool(task.source_intake_id)), 'source_candidate': int(bool(task.source_candidate_id)), 'current_order_extraction': int(bool(task.current_order_extraction_id)), - 'inventory_snapshot': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(), + 'onhand_snapshot': db.session.query(ShippingTaskOnhandLink.id).filter_by(task_id=int(task.id)).count(), 'successor': int(_has_successor(task)), 'duplicate_link': int(bool(task.duplicate_source_task_id)), 'duplicate_source_for_other_task': db.session.query(ShippingNotice.id).filter( ShippingNotice.duplicate_source_task_id == int(task.id), ).count(), 'external_upload_fact': int(_has_external_fulfillment(task)), - 'inventory_link': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(), + 'inventory_link': db.session.query(ShippingTaskOnhandLink.id).filter_by(task_id=int(task.id)).count(), 'export_artifact': db.session.query(ShippingExportArtifact.id).filter_by(task_id=int(task.id)).count(), 'candidate_consumed': db.session.query(ShippingOrderCandidate.id).filter_by(consumed_task_id=int(task.id)).count(), 'intake_consumed': db.session.query(ShippingOrderIntake.id).filter_by(consumed_task_id=int(task.id)).count(), 'order_extraction': db.session.query(ShippingOrderExtraction.id).filter_by(task_id=int(task.id)).count(), - 'temporary_inventory_session': db.session.query(ShippingTemporaryInventorySession.id).filter_by(task_id=int(task.id)).count(), + 'temporary_inventory_session': db.session.query(ShippingTemporaryOnhandSession.id).filter_by(task_id=int(task.id)).count(), 'field_conflict': db.session.query(ShippingTaskFieldConflict.id).filter_by(task_id=int(task.id)).count(), 'non_disposition_event': db.session.query(ShippingTaskEvent.id).filter( ShippingTaskEvent.task_id == int(task.id), diff --git a/backend/app/services/shipping_notice/task_field_gate.py b/backend/app/services/shipping_notice/task_field_gate.py index 7e14be0b..a1f59044 100644 --- a/backend/app/services/shipping_notice/task_field_gate.py +++ b/backend/app/services/shipping_notice/task_field_gate.py @@ -3,7 +3,7 @@ backend/app/services/shipping_notice/task_field_gate.py 用途:未解决订单字段冲突门禁,阻断库存/匹配/导出下游副作用。 依赖:task_field_conflict_service、i18n、tool_response、query_service.serialize_task_for_tool。 -逻辑:inventory_workflow / inventory_rpa_workflow / fulfillment_workflow 在副作用前调用。 +逻辑:onhand_workflow / onhand_rpa_workflow / fulfillment_workflow 在副作用前调用。 """ from __future__ import annotations diff --git a/backend/app/services/shipping_notice/task_workflow.py b/backend/app/services/shipping_notice/task_workflow.py index 063f2a77..2f642678 100644 --- a/backend/app/services/shipping_notice/task_workflow.py +++ b/backend/app/services/shipping_notice/task_workflow.py @@ -45,7 +45,7 @@ from app.services.shipping_notice.state_machine import TaskTransition, apply_tas from app.services.shipping_notice.tool_response import tool_response from app.services.shipping_notice.user_facing_status import user_facing_task_stage -from app.services.shipping_notice.inventory_workflow import ensure_inventory +from app.services.shipping_notice.onhand_workflow import ensure_inventory from app.services.shipping_notice.batch_create_idempotency import ( acquire_notice_create_locks, assert_no_exact_duplicate_notices, @@ -65,7 +65,7 @@ from app.models import ShippingOrderCandidate, ShippingOrderReviewEvent def _has_ready_inventory_file(task: ShippingNotice | ShippingOrderTask) -> bool: """读取活动 Link 指向的 ready 文件,作为重试审计中的库存事实。""" - from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task + from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task return has_ready_inventory_file_for_task(task) @@ -352,8 +352,8 @@ def _apply_notice_edit_change_effects( 按 Schema change_effect 选择性失效下游;无 legacy 全量 reset。 核心逻辑: - rerun_inventory_source_resolution → 清匹配/导出、重裁库存源、OT inventory_source_resolving; - rerun_inventory_matching → 清匹配/导出、OT inventory_matching; + rerun_inventory_source_resolution → 清匹配/导出、重裁库存源、OT onhand_source_resolving; + rerun_inventory_matching → 清匹配/导出、OT onhand_matching; regenerate_excel → 仅清导出、OT excel_generating; require_revision → 全量下游 reset; none → 跳过重型 reset(Excel 冻结由 assert_formal_task_not_excel_frozen 拦截)。 @@ -368,7 +368,7 @@ def _apply_notice_edit_change_effects( """ from app.services.shipping_notice.schema_edit_policy import collect_change_effects_for_fields from app.services.shipping_notice.order_task_service import sync_order_task_processing_state - from app.services.shipping_notice.inventory_source_gate import ( + from app.services.shipping_notice.onhand_source_gate import ( adjudicate_and_apply_inventory_source, clear_inventory_source_confirmation, ) @@ -394,23 +394,23 @@ def _apply_notice_edit_change_effects( if 'rerun_inventory_source_resolution' in effects: clear_inventory_source_confirmation(task) _reset_notice_export_downstream(task) - _set_notice_invalidated_from_stage(task, 'inventory_source_resolving') + _set_notice_invalidated_from_stage(task, 'onhand_source_resolving') adjudication = adjudicate_and_apply_inventory_source(task) - from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable + from app.services.shipping_notice.onhand_source_gate import is_inventory_source_stable stable = is_inventory_source_stable(task) if order_task is not None: if stable: sync_order_task_processing_state( order_task, - stage='inventory_fetching', + stage='onhand_fetching', status='processing', ) _clear_notice_invalidated_from_stage(task) else: sync_order_task_processing_state( order_task, - stage='inventory_source_resolving', + stage='onhand_source_resolving', status='blocked', ) applied.add('rerun_inventory_source_resolution') @@ -418,11 +418,11 @@ def _apply_notice_edit_change_effects( if 'rerun_inventory_matching' in effects: _reset_notice_export_downstream(task) - _set_notice_invalidated_from_stage(task, 'inventory_matching') + _set_notice_invalidated_from_stage(task, 'onhand_matching') if order_task is not None: sync_order_task_processing_state( order_task, - stage='inventory_matching', + stage='onhand_matching', status='processing', ) applied.add('rerun_inventory_matching') @@ -881,7 +881,7 @@ def _order_task_match_status_for_audit(order_task: ShippingOrderTask | None) -> """ if order_task is None: return None - from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task + from app.services.shipping_notice.line_onhand_match_projection import load_current_match_facts_by_task facts = list(load_current_match_facts_by_task(order_task.id).values()) if not facts: diff --git a/backend/app/services/shipping_notice/tool_common.py b/backend/app/services/shipping_notice/tool_common.py index c27d86b9..edab89c3 100644 --- a/backend/app/services/shipping_notice/tool_common.py +++ b/backend/app/services/shipping_notice/tool_common.py @@ -3,8 +3,8 @@ services/shipping_notice/tool_common.py 用途:发货通知 Tool 链共享配置、payload 合并、消息拼接与任务事件写入(无阶段业务编排)。 依赖:constants、models.ShippingTaskEvent、fulfillment_audit、stp_progress_contract、progress_audit_contract。 -逻辑:task_workflow / inventory_workflow / fulfillment_workflow / decision_workflow 共用; - log_task_event 对 inventory_rpa_/inventory_source_/export_/notice_replace/ +逻辑:task_workflow / onhand_workflow / fulfillment_workflow / decision_workflow 共用; + log_task_event 对 onhand_rpa_/inventory_source_/export_/notice_replace/ freight_cancellation_/STP 事件同步投影到 ShippingAuditEvent; 另提供 generic/XFA/LLM 等主链灰度开关读取。 """ @@ -76,14 +76,14 @@ def auto_progress_enabled() -> bool: return cfg_bool("SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED", False) -def auto_rpa_inventory_enabled() -> bool: - """是否允许自动触发 RPA 导出库存。""" - return cfg_bool("SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED", True) +def auto_rpa_onhand_enabled() -> bool: + """是否允许自动触发 RPA 导出在手库存(SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED)。""" + return cfg_bool("SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED", True) def rpa_inventory_timeout_seconds() -> int: """RPA 库存导出等待超时秒数。""" - return cfg_int("FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS", 900, min_value=5) + return cfg_int("FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS", 900, min_value=5) def auto_mapping_allow_llm() -> bool: @@ -236,7 +236,7 @@ def set_task_step_progress( stage 序号不小于旧值才覆盖,保证进度上报永远不会把订单拉回早期阶段。 Args: - stage: 15 阶契约码(如 inventory_fetching / inventory_matching / + stage: 15 阶契约码(如 onhand_fetching / onhand_matching / excel_generating / freight_uploading);禁止传入 CheckPoint 时代 stepN_* 遗留键(已全部清除)。 step_title: 展示用步骤名。 @@ -404,7 +404,7 @@ def log_task_event( event_name = str(event_type or '') dual_write = event_name.startswith(( - 'inventory_rpa_', + 'onhand_rpa_', 'inventory_source_', 'export_', 'notice_replace', @@ -512,11 +512,11 @@ def _audit_reason_code_for_task_event(event_type: str, detail: dict[str, Any]) - name = str(event_type or '').strip() err_blob = f"{detail.get('error') or ''} {detail.get('error_code') or ''}".lower() mapping = { - 'inventory_rpa_queued': 'inventory_rpa_queued', - 'inventory_rpa_started': 'inventory_rpa_queued', - 'inventory_rpa_timeout': 'inventory_rpa_timeout', - 'inventory_rpa_exhausted': 'inventory_rpa_exhausted', - 'inventory_rpa_failed': 'inventory_rpa_export_failed', + 'onhand_rpa_queued': 'onhand_rpa_queued', + 'onhand_rpa_started': 'onhand_rpa_queued', + 'onhand_rpa_timeout': 'onhand_rpa_timeout', + 'onhand_rpa_exhausted': 'onhand_rpa_exhausted', + 'onhand_rpa_failed': 'onhand_rpa_export_failed', 'notice_replaced': 'attachment_replaced', 'notice_replace_extract_failed': 'document_text_unavailable', 'freight_cancellation_completed': 'task_voided_for_correction', @@ -528,14 +528,14 @@ def _audit_reason_code_for_task_event(event_type: str, detail: dict[str, Any]) - } if name in mapping: code = mapping[name] - if name == 'inventory_rpa_failed': + if name == 'onhand_rpa_failed': if 'timeout' in err_blob or ('not ready' in err_blob and 'within' in err_blob): - return 'inventory_rpa_timeout' + return 'onhand_rpa_timeout' if 'login' in err_blob or 'auth' in err_blob: - return 'inventory_rpa_login_failed' + return 'onhand_rpa_login_failed' if 'export' in err_blob: - return 'inventory_rpa_export_failed' - return 'inventory_rpa_export_failed' + return 'onhand_rpa_export_failed' + return 'onhand_rpa_export_failed' if name == 'notice_replace_extract_failed': from app.services.shipping_notice.error_explainability_contract import ( primary_attachment_reason_from_warnings, @@ -545,8 +545,8 @@ def _audit_reason_code_for_task_event(event_type: str, detail: dict[str, Any]) - ) return from_warnings or code return code - if name.startswith('inventory_rpa_') and name.endswith('_failed'): - return 'inventory_rpa_export_failed' + if name.startswith('onhand_rpa_') and name.endswith('_failed'): + return 'onhand_rpa_export_failed' if name.startswith('upload_rpa') and 'fail' in name: return 'upload_rpa_failed' return None diff --git a/backend/app/services/shipping_notice/tool_response.py b/backend/app/services/shipping_notice/tool_response.py index b7b8b700..695da145 100644 --- a/backend/app/services/shipping_notice/tool_response.py +++ b/backend/app/services/shipping_notice/tool_response.py @@ -3,7 +3,7 @@ services/shipping_notice/tool_response.py 用途:统一构建发货通知 Tool 的 JSON 响应结构。 依赖:state_machine.resolve_task_ui_state(位置派生);ShippingProcessExecution。 -逻辑:由 task_workflow、inventory_workflow、fulfillment_workflow 等 workflow 调用本文件,把状态机信息整理成一致的 Tool 响应; +逻辑:由 task_workflow、onhand_workflow、fulfillment_workflow 等 workflow 调用本文件,把状态机信息整理成一致的 Tool 响应; 已绑定 ProcessExecution 的任务不再下发旧动作字段(恢复仅由 Gate 驱动)。 """ diff --git a/backend/app/services/shipping_notice/tools.py b/backend/app/services/shipping_notice/tools.py index 6e38cc90..b70bca39 100644 --- a/backend/app/services/shipping_notice/tools.py +++ b/backend/app/services/shipping_notice/tools.py @@ -2,7 +2,7 @@ services/shipping_notice/tools.py 用途:发货通知 Agent Tool 统一门面(API 唯一业务入口,无编排实现)。 -依赖:customer_identity_gate、task_workflow、inventory_workflow、inventory_rpa_workflow、fulfillment_workflow。 +依赖:customer_identity_gate、task_workflow、onhand_workflow、onhand_rpa_workflow、fulfillment_workflow。 逻辑:shipping_notice_tools / workspace_shipping_notice 仅 import 本模块公开符号。 """ @@ -10,8 +10,8 @@ from __future__ import annotations from app.services.shipping_notice import ( fulfillment_workflow, - inventory_rpa_workflow, - inventory_workflow, + onhand_rpa_workflow, + onhand_workflow, task_workflow, ) from app.services.shipping_notice import customer_identity_gate @@ -29,37 +29,37 @@ remove_notice_line = task_workflow.remove_notice_line confirm_customer = customer_identity_gate.confirm_customer # 库存阶段 -ensure_inventory = inventory_workflow.ensure_inventory -upload_inventory_file = inventory_workflow.upload_inventory_file -rpa_report_inventory = inventory_rpa_workflow.rpa_report_inventory -rpa_report_inventory_batch = inventory_rpa_workflow.rpa_report_inventory_batch -repair_task_inventory_attachment = inventory_rpa_workflow.repair_task_inventory_attachment +ensure_inventory = onhand_workflow.ensure_inventory +upload_inventory_file = onhand_workflow.upload_inventory_file +rpa_report_inventory = onhand_rpa_workflow.rpa_report_inventory +rpa_report_inventory_batch = onhand_rpa_workflow.rpa_report_inventory_batch +repair_task_inventory_attachment = onhand_rpa_workflow.repair_task_inventory_attachment def create_temporary_inventory_session(payload: dict): """创建对话上传库存候选会话;仅供 Dify 临时库存固定分支调用。""" - from app.services.shipping_notice.inventory_temporary_session import create_temporary_inventory_session as _create + from app.services.shipping_notice.onhand_temporary_session import create_temporary_inventory_session as _create return _create(payload) def get_temporary_inventory_session(payload: dict): """读取临时库存候选会话的脱敏结构预览;仅供 Dify 固定分支调用。""" - from app.services.shipping_notice.inventory_temporary_session import get_temporary_inventory_session as _get + from app.services.shipping_notice.onhand_temporary_session import get_temporary_inventory_session as _get return _get(payload) def submit_temporary_inventory_mapping_suggestion(payload: dict): """保存 Dify 临时库存映射候选;后端校验后仍须由用户确认。""" - from app.services.shipping_notice.inventory_temporary_session import submit_temporary_inventory_mapping_suggestion as _submit + from app.services.shipping_notice.onhand_temporary_session import submit_temporary_inventory_mapping_suggestion as _submit return _submit(payload) def confirm_temporary_inventory_use(payload: dict): """确认当前会话临时库存使用并执行后端确定性质量校验。""" - from app.services.shipping_notice.inventory_temporary_session import confirm_temporary_inventory_use as _confirm + from app.services.shipping_notice.onhand_temporary_session import confirm_temporary_inventory_use as _confirm return _confirm(payload) diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index 76d4bceb..d7b5d9f0 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -4,9 +4,9 @@ services/shipping_notice/ui_state.py 用途:发货通知任务 UI 状态读模型,作为通知摘要、人工复核与任务工作台的统一状态来源。 依赖:models.ShippingNotice/ShippingOrderTask/ShippingProcessExecution、state_machine(UserMode/位置回退)、 query_service、constants.POSITION_*、process_gate_contract.derive_*/STAGE_CAPABILITY_DEFINITIONS、 - process_gate_projection、line_inventory_match_projection、inventory_candidate_projection、 + process_gate_projection、line_onhand_match_projection、onhand_candidate_projection、 order_review_fulfillment_decision_service(短缺放行模板字段)、 - order_review_workbench_projection、inventory_source_repository(preparation.source_options)。 + order_review_workbench_projection、onhand_source_repository(preparation.source_options)。 逻辑:优先 Gate 位置/用户模式投影 summary/entry_surface(flat position + user_mode); Gate 摘要经 Notice.order_task_id→OT 查 Execution(禁止用 Notice.id); 五阶段 processing_stage 同样经 Notice→OT.stage(Notice 无 stage 列), @@ -56,7 +56,7 @@ from app.services.shipping_notice.constants import ( RS_PARSE_REVIEW, RS_SHORTAGE_REVIEW, ) -from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable +from app.services.shipping_notice.onhand_source_gate import is_inventory_source_stable from app.services.shipping_notice.lifecycle_projection import ( LIFECYCLE_STAGES, project_lifecycle, @@ -90,7 +90,7 @@ _REVIEW_ENTRY_POSITIONS = { } _NEXT_AUTO_STEP_BY_POSITION: dict[str, str] = { - POSITION_INVENTORY_PENDING: "ensure_inventory", + POSITION_INVENTORY_PENDING: "ensure_onhand", POSITION_ORDER_FREEZE: "freeze_order", POSITION_READY_MATCH: "match_inventory", POSITION_READY_EXPORT: "generate_excel", @@ -407,12 +407,12 @@ def _derived_entry_surface( if user_mode in {'must_human', 'wait_manual_upload'}: return 'task_workbench' if code in { - 'inventory_preparation', - 'inventory_matching', - 'inventory_sufficiency', + 'onhand_preparation', + 'onhand_matching', + 'onhand_sufficiency', 'excel_readiness', 'artifact_generation', - 'inventory_source_routing', + 'onhand_source_routing', 'order_freeze_readiness', }: return 'task_workbench' @@ -467,11 +467,11 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: """ from app import db from app.models import ShippingOrderTask - from app.services.shipping_notice.inventory_candidate_projection import ( + from app.services.shipping_notice.onhand_candidate_projection import ( project_inventory_candidate_facts, ) - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes - from app.services.shipping_notice.stp_line_inventory_match import multi_source_recovery_source_codes + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes + from app.services.shipping_notice.stp_line_onhand_match import multi_source_recovery_source_codes from app.services.shipping_notice.stp_progress_contract import STP_FACTS_ALLOWED_KEYS owner = task @@ -488,7 +488,7 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: ) status = 'candidates_frozen' if candidate_projection.get('current_set') else '' method = 'candidate_set' if candidate_projection.get('current_set') else '' - frozen_codes = list(candidate_projection.get('candidate_source_codes') or []) or task_frozen_inventory_source_codes(owner) + frozen_codes = list(candidate_projection.get('candidate_source_codes') or []) or task_frozen_onhand_source_codes(owner) has_stp = ( status in {'candidates_frozen', 'resolved'} or method.startswith('stp') @@ -503,7 +503,7 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: compact_resolutions: list[dict[str, Any]] = [] resolution_source = list(candidate_projection.get('line_resolutions') or []) if not resolution_source and getattr(owner, 'id', None) is not None: - from app.models import ShippingNoticeLineInventoryMatch + from app.models import ShippingNoticeLineOnhandMatch resolution_source = [{ 'line_index': row.line_index, @@ -511,7 +511,7 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: 'disposition': row.match_result, 'effective_reservation_id': row.reservation_id, 'part_number': row.part_number, - 'resolved_inventory_source_code': row.inventory_source_code, + 'resolved_inventory_source_code': row.source_code, 'inventory_file_no': row.matched_file_no, 'inventory_row_index': row.matched_row_index, 'match_attempt_id': row.match_attempt_id, @@ -519,9 +519,9 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: 'matched_qty': row.matched_qty or row.available_qty, 'shortage_qty': row.shortage_qty, 'inventory_row_ref': dict(row.detail_json or {}).get('inventory_row_ref'), - } for row in ShippingNoticeLineInventoryMatch.query.filter_by( + } for row in ShippingNoticeLineOnhandMatch.query.filter_by( task_id=int(owner.id), is_current=True, - ).order_by(ShippingNoticeLineInventoryMatch.line_no, ShippingNoticeLineInventoryMatch.id).all()] + ).order_by(ShippingNoticeLineOnhandMatch.line_no, ShippingNoticeLineOnhandMatch.id).all()] for item in resolution_source: disposition = str(item.get('disposition') or 'unknown') counts[disposition] = counts.get(disposition, 0) + 1 @@ -778,19 +778,19 @@ def _stage_capabilities_for_task( } if source_locked: cap.update(disabled('excel_locked')) - elif code == 'retry_inventory_preparation': + elif code == 'retry_onhand_preparation': # 重抓:候选源或失败源任一在场即可重试(库存文件未准备时通常走候选源)。 retry_available = has_candidates or bool(failed_codes) cap['enabled'] = retry_available cap['disabled_reason'] = None if retry_available else 'no_candidates' - elif code == 'override_line_inventory_source': + elif code == 'override_line_onhand_source': cap['enabled'] = has_candidates cap['disabled_reason'] = None if has_candidates else 'no_candidates' - elif code == 'reload_inventory_result': + elif code == 'reload_onhand_result': has_prior = bool(resolved_codes) cap['enabled'] = has_prior cap['disabled_reason'] = None if has_prior else 'no_prior_result' - elif code == 'retry_inventory_matching': + elif code == 'retry_onhand_matching': cap['enabled'] = has_match_result cap['disabled_reason'] = None if has_match_result else 'no_match_result' result.append(cap) @@ -814,15 +814,15 @@ def _build_stage_context( preparation.source_options 下发全部已启用库存源,供 Excel 未锁定时行级覆写下拉; preparation.capabilities 由 `_stage_capabilities_for_task` 追加(点击 bypass,不进右卡渲染); Excel/上传 Attempt 仍按入参实体(Notice 或 OT)查询; - inventory_rpa_is_running 在行循环外算一次(请求级 memo),禁止逐行查 RPA Attempt。 + onhand_rpa_is_running 在行循环外算一次(请求级 memo),禁止逐行查 RPA Attempt。 """ from app import db from app.models import ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask from app.models.shipping_excel_template import ShippingExportArtifact from app.models.shipping_fulfillment import ShippingUploadAttempt from app.core.errors import ConflictError - from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines - from app.services.shipping_notice.line_inventory_match_projection import ( + from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_lines + from app.services.shipping_notice.line_onhand_match_projection import ( inventory_rpa_is_running, load_current_match_facts_by_task, project_line_inventory_view, @@ -1014,27 +1014,27 @@ def _build_stage_context( inventory_sources: list[dict[str, Any]] = [] latest_preparation = None if getattr(order_task, 'id', None): - from app.models.shipping_inventory_preparation import ShippingInventoryPreparationAttempt + from app.models.shipping_onhand_preparation import ShippingOnhandPreparationAttempt latest_preparation = ( - ShippingInventoryPreparationAttempt.query + ShippingOnhandPreparationAttempt.query .filter_by(task_id=int(order_task.id)) - .filter(ShippingInventoryPreparationAttempt.status != 'superseded') - .order_by(ShippingInventoryPreparationAttempt.attempt_no.desc()) + .filter(ShippingOnhandPreparationAttempt.status != 'superseded') + .order_by(ShippingOnhandPreparationAttempt.attempt_no.desc()) .first() ) - from app.services.shipping_notice.inventory_file_store import resolve_task_inventory_download + from app.services.shipping_notice.onhand_file_store import resolve_task_inventory_download downloadable_inventory = resolve_task_inventory_download(order_task) for source_attempt in (getattr(latest_preparation, 'source_attempts', None) or []): inventory_sources.append({ 'source_code': source_attempt.source_code, 'status': source_attempt.status, - 'inventory_file_id': source_attempt.inventory_file_id, + 'inventory_file_id': source_attempt.onhand_file_id, }) # [STEP] 人工覆写库存源:下发全部已启用源,供前端行级下拉(override_line_inventory_source)。 - from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources + from app.services.shipping_notice.onhand_source_repository import list_database_inventory_sources source_options = [ { @@ -1352,7 +1352,7 @@ def _process_gate_user_summary_for_task(task: ShippingNotice) -> dict[str, Any] 核心逻辑:先把 Notice 解析到 order_task_id 对应的 OT,再优先读 active_process_execution_id,回退按 OT.id 取最新非 superseded Execution; - 套用 apply_post_ot_gate_rules,使 inventory_preparation 等系统等待 + 套用 apply_post_ot_gate_rules,使 onhand_preparation 等系统等待 不进入 current_blocking_gate。货代上传聚合的 available_actions 依赖此路径。 同一 HTTP 请求内按 task 主键 memo,避免 build_task_ui_state / resolve 等路径重复查库。 diff --git a/backend/app/services/shipping_notice/workflow_ledger_service.py b/backend/app/services/shipping_notice/workflow_ledger_service.py index 03f87138..d40d8b6e 100644 --- a/backend/app/services/shipping_notice/workflow_ledger_service.py +++ b/backend/app/services/shipping_notice/workflow_ledger_service.py @@ -336,7 +336,7 @@ def task_has_entered_inventory_match(task: ShippingNotice) -> bool: Returns: True 表示已进入 matched 或更后阶段。 """ - from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task + from app.services.shipping_notice.line_onhand_match_projection import aggregate_match_status_for_task match_task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None) match_status = aggregate_match_status_for_task(match_task_id) or '' from app.services.shipping_notice.upload_attempt_service import latest_export_artifact, latest_upload_attempt diff --git a/backend/config/shipping_inventory_sources.yaml b/backend/config/shipping_inventory_sources.yaml deleted file mode 100644 index f8f961c0..00000000 --- a/backend/config/shipping_inventory_sources.yaml +++ /dev/null @@ -1,648 +0,0 @@ -# backend/config/shipping_inventory_sources.yaml -# 历史库存源配置:仅用于期初数据导入和人工核对,不能恢复为运行时真相源。 -# 新增或修改库存源、报表路径、查询参数和别名必须维护在数据库后台。 -# 本文件保留 site_id、selector 等旧字段,导入时需显式映射或丢弃;新运行时不得读取。 - -version: 2 -sources: -- source_code: DSV360_AWSBI_BYAWSATL01 - display_name: DSV 360 / Bison / AWSBI / BYAWSATL01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - warehouse_id: BYAWSATL01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSATL01 - required: true - match_aliases: - - BYAWSATL01 - - ATL01 -- source_code: DSV360_AWSBI_BYAWSAVP01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSAVP01 - warehouse_id: BYAWSAVP01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSAVP01 - required: true - match_aliases: - - BYAWSAVP01 -- source_code: DSV360_AWSBI_BYAWSAZA01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSAZA01 - warehouse_id: BYAWSAZA01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSAZA01 - required: true - match_aliases: - - BYAWSAZA01 -- source_code: DSV360_AWSBI_BYAWSCMH01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSCMH01 - warehouse_id: BYAWSCMH01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSCMH01 - required: true - match_aliases: - - BYAWSCMH01 - - CMH -- source_code: DSV360_AWSBI_BYAWSCMN01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSCMN01 - warehouse_id: BYAWSCMN01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSCMN01 - required: true - match_aliases: - - BYAWSCMN01 - - CMN -- source_code: DSV360_AWSBI_BYAWSEZE01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSEZE01 - warehouse_id: BYAWSEZE01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSEZE01 - required: true - match_aliases: - - BYAWSEZE01 - - EZE -- source_code: DSV360_AWSBI_BYAWSFRA01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSFRA01 - warehouse_id: BYAWSFRA01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSFRA01 - required: true - match_aliases: - - BYAWSFRA01 -- source_code: DSV360_AWSBI_BYAWSGRU01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSGRU01 - warehouse_id: BYAWSGRU01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSGRU01 - required: true - match_aliases: - - BYAWSGRU01 -- source_code: DSV360_AWSBI_BYAWSIAD01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSIAD01 - warehouse_id: BYAWSIAD01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSIAD01 - required: true - match_aliases: - - BYAWSIAD01 -- source_code: DSV360_AWSBI_BYAWSJAN01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSJAN01 - warehouse_id: BYAWSJAN01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSJAN01 - required: true - match_aliases: - - BYAWSJAN01 -- source_code: DSV360_AWSBI_BYAWSLTN01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSLTN01 - warehouse_id: BYAWSLTN01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSLTN01 - required: true - match_aliases: - - BYAWSLTN01 -- source_code: DSV360_AWSBI_BYAWSMEL01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSMEL01 - warehouse_id: BYAWSMEL01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSMEL01 - required: true - match_aliases: - - BYAWSMEL01 -- source_code: DSV360_AWSBI_BYAWSNRT01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSNRT01 - warehouse_id: BYAWSNRT01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSNRT01 - required: true - match_aliases: - - BYAWSNRT01 -- source_code: DSV360_AWSBI_BYAWSPHX01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSPHX01 - warehouse_id: BYAWSPHX01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSPHX01 - required: true - match_aliases: - - BYAWSPHX01 -- source_code: DSV360_AWSBI_BYAWSPNE01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSPNE01 - warehouse_id: BYAWSPNE01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSPNE01 - required: true - match_aliases: - - BYAWSPNE01 -- source_code: DSV360_AWSBI_BYAWSPRD01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSPRD01 - warehouse_id: BYAWSPRD01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSPRD01 - required: true - match_aliases: - - BYAWSPRD01 -- source_code: DSV360_AWSBI_BYAWSPSC01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSPSC01 - warehouse_id: BYAWSPSC01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSPSC01 - required: true - match_aliases: - - BYAWSPSC01 -- source_code: DSV360_AWSBI_BYAWSQRO01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSQRO01 - warehouse_id: BYAWSQRO01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSQRO01 - required: true - match_aliases: - - BYAWSQRO01 -- source_code: DSV360_AWSBI_BYAWSRIC01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSRIC01 - warehouse_id: BYAWSRIC01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSRIC01 - required: true - match_aliases: - - BYAWSRIC01 -- source_code: DSV360_AWSBI_BYAWSRNO01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSRNO01 - warehouse_id: BYAWSRNO01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSRNO01 - required: true - match_aliases: - - BYAWSRNO01 -- source_code: DSV360_AWSBI_BYAWSRUH01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSRUH01 - warehouse_id: BYAWSRUH01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSRUH01 - required: true - match_aliases: - - BYAWSRUH01 -- source_code: DSV360_AWSBI_BYAWSSBN01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSSBN01 - warehouse_id: BYAWSSBN01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSSBN01 - required: true - match_aliases: - - BYAWSSBN01 -- source_code: DSV360_AWSBI_BYAWSSCL01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSSCL01 - warehouse_id: BYAWSSCL01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSSCL01 - required: true - match_aliases: - - BYAWSSCL01 -- source_code: DSV360_AWSBI_BYAWSYYZ01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSYYZ01 - warehouse_id: BYAWSYYZ01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSYYZ01 - required: true - match_aliases: - - BYAWSYYZ01 -- source_code: DSV360_AWSBI_BYAWSZAZ01 - enabled: true - connector_type: dsv360 - site_id: AWSBI - display_name: DSV 360 / Bison / AWSBI / BYAWSZAZ01 - warehouse_id: BYAWSZAZ01 - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Bison - program_label: AWSBI - report_group: Inventory - report_name: On Hand Inventory By Location 3lv - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: single - values: - - BYAWSZAZ01 - required: true - match_aliases: - - BYAWSZAZ01 -- source_code: DSV360_AWSCV - enabled: true - connector_type: dsv360 - site_id: AWSCV - warehouse_id: AWSCV - display_name: DSV 360 / Cincinnati / AWSCV - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Cincinnati - program_label: AWSCV - report_group: Inventory - report_name: On Hand Inventory by Location - match_aliases: - - CINCINNATI - - CVG - - AWSCV -- source_code: DSV360_AWSDU - enabled: true - connector_type: dsv360 - site_id: AWSDU - warehouse_id: AWSDU - display_name: DSV 360 / Dublin / AWSDU - Prod (JDA) - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Dublin - program_label: AWSDU - Prod (JDA) - report_group: Inventory - report_name: On Hand Inventory by Location - match_aliases: - - DBS DUB - - DUB - - DUBLIN -- source_code: DSV360_AWSAMS - enabled: true - connector_type: dsv360 - site_id: AWSAMS - warehouse_id: RTM - display_name: DSV 360 / Moerdijk / AWSAMS - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Moerdijk - program_label: AWSAMS - report_group: Inventory - report_name: On Hand Inventory by Location - parameters: - - name: Warehouse - selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR - mode: multi_select - select_all: true - selectors: - text: '#ReportViewerMain_ctl08_ctl17_txtValue' - toggle: '#ReportViewerMain_ctl08_ctl17_ctl01' - dropdown: '#ReportViewerMain_ctl08_ctl17_divDropDown' - values: - - RTM - required: true - match_aliases: - - MOERDIJK - - AMS - - AWSAMS -- source_code: DSV360_AWSSL - enabled: true - connector_type: dsv360 - site_id: AWSSL - warehouse_id: AWSSL - display_name: DSV 360 / Salt Lake City / AWSSL - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Salt Lake City - program_label: AWSSL - report_group: Inventory - report_name: On Hand Inventory by Location - match_aliases: - - USLCK - - SALT LAKE CITY - - SALTLAKECITY -- source_code: DSV360_AWSSG - enabled: true - connector_type: dsv360 - site_id: AWSSG - warehouse_id: AWSSG - display_name: DSV 360 / Singapore / AWSSG - Prod (JDA) - entry_url: https://s360.dbschenker.com/ - navigation: - program_group: Singapore - program_label: AWSSG - Prod (JDA) - report_group: Inventory - report_name: On Hand Inventory by Location - match_aliases: - - SINGAPORE HUB - - SINGAPORE - - SG - - VMI-SIN -- source_code: CRANE - enabled: true - connector_type: crane_footprint - site_id: CRANE - warehouse_resolution: alias_match - display_name: Crane FootPrint - entry_url: https://wms-portal.craneww.com/#/on-hand-details-query - navigation: - report_name: On Hand Details Query - download_mode: scheduled_report - parameters: [] - match_aliases: - - TZR - - TZR2 - - TZR3 - allowed_warehouse_ids: - - TZR - - TZR2 - - TZR3 diff --git a/backend/migrations/versions/mh15f6a7b8c9_merge_equipment_acceptance_and_transfer_heads.py b/backend/migrations/versions/mh15f6a7b8c9_merge_equipment_acceptance_and_transfer_heads.py new file mode 100644 index 00000000..8e50b8e0 --- /dev/null +++ b/backend/migrations/versions/mh15f6a7b8c9_merge_equipment_acceptance_and_transfer_heads.py @@ -0,0 +1,30 @@ +"""合并设备验收发送归档与调拨类型列宽两条 Alembic 头。 + +Revision ID: mh15f6a7b8c9 +Revises: eah8c9d0e1f2, tt13d4e5f6a7b8 +Create Date: 2026-10-15 13:20:00.000000 + +用途:将 ``eah8c9d0e1f2``(设备验收企微事件、第 4 轮开关与 Excel 归档)与 + ``tt13d4e5f6a7b8``(transfer_runs.transfer_type 放宽至 String(64)) + 收成单一升级路径,避免 ``flask db upgrade`` / pre-push 因多 head 失败。 +依赖:``eah8c9d0e1f2``、``tt13d4e5f6a7b8``。 +逻辑:不修改业务表,只声明两条已完成迁移线在此收敛。 +""" + +from alembic import op # noqa: F401 - Alembic migration module contract + + +revision = "mh15f6a7b8c9" +down_revision = ("eah8c9d0e1f2", "tt13d4e5f6a7b8") +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """合并设备验收 head 与调拨类型列宽 head,不执行数据库结构变更。""" + pass + + +def downgrade() -> None: + """撤销合并节点;不会回滚两个父分支的业务变更。""" + pass diff --git a/backend/migrations/versions/s17b1c2d3e4f5a_freight_rpa_batch_s_rename_tables.py b/backend/migrations/versions/s17b1c2d3e4f5a_freight_rpa_batch_s_rename_tables.py new file mode 100644 index 00000000..73159c52 --- /dev/null +++ b/backend/migrations/versions/s17b1c2d3e4f5a_freight_rpa_batch_s_rename_tables.py @@ -0,0 +1,564 @@ +""" +migrations/versions/s17b1c2d3e4f5a_freight_rpa_batch_s_rename_tables.py + +用途:批次 S 只改表结构——29 张货代 RPA / 发货库存表一次 rename,并改写这些表上的 + inventory/receipt 列名,以及名称里含旧表名的索引、主键、唯一、检查、外键。 + 模型类与 __tablename__ 仍用旧名,留到后续任务。 +依赖:alembic.op、SQLAlchemy 反射;down_revision 为当前单 head tt16c7d8e9f0a1b2。 +逻辑:先按列规则改列,再 rename_table(PG/SQLite 都会改外键指向的表),最后扫全库 + 对象名,把旧表名替换成新表名。验证批次索引 + ix_inventory_test_run_validation_batch 一对一改成 + ix_fr_onhand_cfg_test_runs_validation_batch_id。历史迁移没有单列 + recipient 索引,升级在新表上补建 ix_fr_inbound_notif_deliveries_recipient_user_id, + 降级删掉,不还原一个不存在的旧名。复合索引 + ix_shipping_receipt_delivery_file_recipient 不含完整旧表名,不改。 + PostgreSQL 用 ALTER ... RENAME;SQLite 对索引是重建,对表内约束是 batch 重建。 + downgrade 按相反顺序还原。不改 29 张以外的表(含 shipping_notice_freight_cancellations)上的列。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = "s17b1c2d3e4f5a" +down_revision = "tt16c7d8e9f0a1b2" +branch_labels = None +depends_on = None + +# PostgreSQL 标识符上限(NAMEDATALEN-1)。ASCII 名称按字符计即按字节计。 +_MAX_IDENTIFIER_LENGTH = 63 + +# (旧表, 新表)。顺序与批次 S 任务书一致。 +_TABLE_RENAMES: list[tuple[str, str]] = [ + ("shipping_inventory_sources", "freight_rpa_sources"), + ("shipping_rpa_profiles", "freight_rpa_profiles"), + ("shipping_inventory_fields", "freight_rpa_onhand_fields"), + ("shipping_inventory_source_parsing_binding_audits", "freight_rpa_onhand_source_parsing_binding_audits"), + ("shipping_inventory_parsing_profiles", "freight_rpa_parsing_profiles"), + ("shipping_inventory_structure_analyses", "freight_rpa_onhand_structure_analyses"), + ("shipping_inventory_configuration_test_runs", "freight_rpa_onhand_configuration_test_runs"), + ("shipping_inventory_validation_batches", "freight_rpa_onhand_validation_batches"), + ("shipping_inventory_routing_rules", "freight_rpa_onhand_routing_rules"), + ("shipping_inventory_routing_rule_conditions", "freight_rpa_onhand_routing_rule_conditions"), + ("shipping_inventory_routing_rule_versions", "freight_rpa_onhand_routing_rule_versions"), + ("shipping_inventory_external_mappings", "freight_rpa_onhand_external_mappings"), + ("shipping_inventory_mappings", "freight_rpa_onhand_mappings"), + ("shipping_task_inventory_rpa_attempts", "freight_rpa_onhand_task_rpa_attempts"), + ("shipping_receipt_report_configs", "freight_rpa_inbound_report_configs"), + ("shipping_receipt_rpa_unit_runs", "freight_rpa_inbound_rpa_unit_runs"), + ("shipping_receipt_report_files", "freight_rpa_inbound_report_files"), + ("shipping_receipt_notification_deliveries", "freight_rpa_inbound_notification_deliveries"), + ("shipping_inventory_files", "shipping_onhand_files"), + ("shipping_inventory_candidate_sets", "shipping_onhand_candidate_sets"), + ("shipping_inventory_candidate_sources", "shipping_onhand_candidate_sources"), + ("shipping_inventory_candidate_lines", "shipping_onhand_candidate_lines"), + ("shipping_inventory_preparation_attempts", "shipping_onhand_preparation_attempts"), + ("shipping_inventory_preparation_source_attempts", "shipping_onhand_preparation_source_attempts"), + ("shipping_task_inventory_links", "shipping_task_onhand_links"), + ("shipping_temporary_inventory_sessions", "shipping_temporary_onhand_sessions"), + ("shipping_notice_line_inventory_matches", "shipping_notice_line_onhand_matches"), + ("shipping_notice_inventory_verifications", "shipping_notice_onhand_verifications"), + ("shipping_notice_inventory_verification_lines", "shipping_notice_onhand_verification_lines"), +] + +# 显式列对照优先于「名字里的 inventory 换成 onhand」。 +_EXPLICIT_COLUMNS = { + "inventory_source_id": "source_id", + "inventory_snapshot_id": "onhand_snapshot_id", + "inventory_file_id": "onhand_file_id", + "inventory_source_code": "source_code", + "active_inventory_candidate_set_id": "active_onhand_candidate_set_id", +} + +_RECEIPT_TABLES = frozenset({ + "shipping_receipt_report_configs", + "shipping_receipt_rpa_unit_runs", + "shipping_receipt_report_files", + "shipping_receipt_notification_deliveries", +}) + +# 替换后超过 63 字节、降级必须回到原名的对象。其余名称不截断。 +_EXACT_ORIGINS = ( + "shipping_receipt_notification_deliveries_recipient_user_id_fkey", +) + +# 只映射历史迁移真正建过的索引。aa1 的验证批次索引一对一换成模型短名。 +# 不收录 SQLAlchemy index=True 的自动名:库里没有那条 65 字节索引。 +_EXPLICIT_INDEX_NAMES = { + "ix_inventory_test_run_validation_batch": "ix_fr_onhand_cfg_test_runs_validation_batch_id", +} + +# hi3 只建了复合索引 ix_shipping_receipt_delivery_file_recipient,没有单列 recipient 索引。 +# 升级在已改名的表上补建模型短名;降级删除,不假装有旧名可还原。 +_CREATED_RECIPIENT_INDEX = "ix_fr_inbound_notif_deliveries_recipient_user_id" +_CREATED_RECIPIENT_TABLE = "freight_rpa_inbound_notification_deliveries" +_CREATED_RECIPIENT_COLUMNS = ["recipient_user_id"] + + +def _quote_ident(name: str) -> str: + """给 SQL 标识符加双引号,内部引号按标准加倍。 + + Args: + name: 表、索引或约束名。 + + Returns: + 可拼进 DDL 的引用标识符。 + """ + return '"' + name.replace('"', '""') + '"' + + +def _substitute(name: str, pairs: list[tuple[str, str]]) -> str: + """把对象名中的表名 token 换成对照表里的另一个名字。 + + 核心逻辑:按源 token 长度降序替换,避免短表名吃掉更长表名的前缀。 + 调用方保证这 29 个旧名彼此不是子串,新名同理。 + + Args: + name: 当前索引或约束名。 + pairs: (被替换的表名, 替换后的表名)。升级用旧→新,降级用新→旧。 + + Returns: + 替换后的对象名(尚未按 63 字节截断)。 + """ + updated = name + for source, destination in sorted(pairs, key=lambda item: len(item[0]), reverse=True): + updated = updated.replace(source, destination) + return updated + + +def _clip(name: str) -> str: + """把标识符限制在 PostgreSQL 的 63 字节以内。 + + Args: + name: 已完成表名替换的对象名。 + + Returns: + 长度不超过 63 的名字。未超长时原样返回。 + """ + if len(name) <= _MAX_IDENTIFIER_LENGTH: + return name + return name[:_MAX_IDENTIFIER_LENGTH] + + +def _target_name(current: str, pairs: list[tuple[str, str]], *, reverse: bool) -> str: + """计算对象改名的目标。 + + 核心逻辑:_EXPLICIT_INDEX_NAMES 一对一改名,降级回到唯一的旧名。 + 其余正向是表名替换再截断。反向时,若当前名正是某个已知超长原名的截断结果, + 则回到那个原名,避免降级丢掉被切掉的后缀。 + + Args: + current: 库里现在的对象名。 + pairs: 本方向的表名替换对。 + reverse: True 表示 downgrade。 + + Returns: + 应改成的对象名。与 current 相同表示不用改。 + """ + if reverse: + for origin, short in _EXPLICIT_INDEX_NAMES.items(): + if current == short: + return origin + for origin in _EXACT_ORIGINS: + if _clip(_substitute(origin, _TABLE_RENAMES)) == current: + return origin + elif current in _EXPLICIT_INDEX_NAMES: + return _EXPLICIT_INDEX_NAMES[current] + return _clip(_substitute(current, pairs)) + + +def _forward_column_name(table: str, column: str) -> str: + """按批次 S 列规则计算升级后的列名。 + + 核心逻辑:五条显式对照优先;其余列名中的 inventory 换成 onhand; + 仅四张原 shipping_receipt_* 表再把 receipt 换成 inbound。 + + Args: + table: 仍是旧表名的表。 + column: 当前列名。 + + Returns: + 新列名。无需改名时与 column 相同。 + """ + renamed = _EXPLICIT_COLUMNS.get(column) + if renamed is None: + renamed = column.replace("inventory", "onhand") if "inventory" in column else column + if table in _RECEIPT_TABLES and "receipt" in renamed: + renamed = renamed.replace("receipt", "inbound") + return renamed + + +def _reverse_column_name(table: str, column: str) -> str: + """按升级规则的逆运算还原列名。 + + 核心逻辑:先在四张 receipt 表上把 inbound 换回 receipt,再还原显式对照。 + source_code 只有 shipping_notice_line_inventory_matches 来自 inventory_source_code; + 其他表上本来就有的 source_code 必须留下。其余 onhand 换回 inventory。 + + Args: + table: 已经改回旧表名的表。 + column: 升级后的列名。 + + Returns: + 升级前的列名。 + """ + name = column + if table in _RECEIPT_TABLES and "inbound" in name: + name = name.replace("inbound", "receipt") + if name == "source_id": + return "inventory_source_id" + if name == "source_code" and table == "shipping_notice_line_inventory_matches": + return "inventory_source_code" + if "onhand" in name: + return name.replace("onhand", "inventory") + return name + + +def _rename_columns(table: str, renamer) -> None: + """把一张表上需要改名的列一次改完,目标名冲突则中止。 + + 核心逻辑:先根据反射列算出对照,目标名彼此重复或撞上保留列就抛错, + 避免 ALTER 中途把两列收成同名。SQLite 与 PostgreSQL 都走 op.alter_column。 + + Args: + table: 当前表名。 + renamer: 接受列名、返回新列名的函数。 + + Raises: + RuntimeError: 目标列名已存在或两条列改到同一个名字。 + """ + columns = sa.inspect(op.get_bind()).get_columns(table) + planned: list[tuple[dict, str]] = [] + for column in columns: + target = renamer(column["name"]) + if target != column["name"]: + planned.append((column, target)) + staying = {column["name"] for column in columns} - {column["name"] for column, _target in planned} + targets = [target for _column, target in planned] + duplicates = sorted({name for name in targets if targets.count(name) > 1}) + occupied = sorted(target for target in targets if target in staying) + if duplicates or occupied: + raise RuntimeError( + f"column rename collision on {table}: duplicates={duplicates} occupied={occupied}" + ) + for column, target in planned: + op.alter_column( + table, + column["name"], + new_column_name=target, + existing_type=column["type"], + existing_nullable=column["nullable"], + ) + + +def _iter_constraints(inspector, table: str): + """列出一张表上带名字的外键、唯一、检查和主键约束。 + + Args: + inspector: 当前连接的 SQLAlchemy Inspector。 + table: 表名。 + + Yields: + (kind, name, payload)。kind 使用 alembic batch 的 type_ 取值。 + 外键 payload 是反射字典,唯一/主键 payload 是列名列表,检查 payload 是表达式。 + """ + for foreign_key in inspector.get_foreign_keys(table) or []: + yield "foreignkey", foreign_key.get("name"), foreign_key + for unique in inspector.get_unique_constraints(table) or []: + yield "unique", unique.get("name"), list(unique.get("column_names") or []) + for check in inspector.get_check_constraints(table) or []: + yield "check", check.get("name"), check.get("sqltext") + primary = inspector.get_pk_constraint(table) or {} + yield "primary", primary.get("name"), list(primary.get("constrained_columns") or []) + + +def _collect_renames(bind, pairs: list[tuple[str, str]], *, reverse: bool) -> dict: + """扫描全库,收集名称中含表名 token、因而需要改名的索引和约束。 + + 核心逻辑:PostgreSQL 上唯一/主键约束与其支撑索引同名,只改约束 + (RENAME CONSTRAINT 会带走索引)。SQLite 上独立索引用重建, + 表内约束才进 batch;同名时以索引为准,避免拆掉已经改过的索引。 + + Args: + bind: 当前迁移连接。 + pairs: 本方向的表名替换对。 + reverse: True 表示 downgrade。 + + Returns: + {表名: (索引列表[(旧, 新)], 约束列表[(kind, 旧, 新, payload)])}。 + """ + inspector = sa.inspect(bind) + dialect = bind.dialect.name + planned: dict[str, tuple[list, list]] = {} + for table in inspector.get_table_names(): + if table.startswith("sqlite_"): + continue + raw_indexes = [] + for index in inspector.get_indexes(table) or []: + name = index.get("name") + if name and not str(name).startswith("sqlite_"): + raw_indexes.append(name) + raw_constraints = [] + for kind, name, payload in _iter_constraints(inspector, table): + if name and not str(name).startswith("sqlite_"): + raw_constraints.append((kind, name, payload)) + + index_rows: list[tuple[str, str]] = [] + constraint_rows: list[tuple[str, str, str, object]] = [] + if dialect == "postgresql": + constraint_names = {name for _kind, name, _payload in raw_constraints} + for kind, name, payload in raw_constraints: + target = _target_name(name, pairs, reverse=reverse) + if target != name: + constraint_rows.append((kind, name, target, payload)) + for name in raw_indexes: + if name in constraint_names: + continue + target = _target_name(name, pairs, reverse=reverse) + if target != name: + index_rows.append((name, target)) + else: + index_names = set(raw_indexes) + for name in raw_indexes: + target = _target_name(name, pairs, reverse=reverse) + if target != name: + index_rows.append((name, target)) + for kind, name, payload in raw_constraints: + if name in index_names: + continue + target = _target_name(name, pairs, reverse=reverse) + if target != name: + constraint_rows.append((kind, name, target, payload)) + if index_rows or constraint_rows: + planned[table] = (index_rows, constraint_rows) + _reject_collisions(planned, _existing_object_names(inspector)) + return planned + + +def _existing_object_names(inspector) -> set[str]: + """收集当前库里全部索引名和约束名,供目标名冲突检查。 + + Args: + inspector: 当前连接的 Inspector。 + + Returns: + 已占用的对象名集合。 + """ + found: set[str] = set() + for table in inspector.get_table_names(): + if table.startswith("sqlite_"): + continue + for index in inspector.get_indexes(table) or []: + if index.get("name"): + found.add(index["name"]) + for _kind, name, _payload in _iter_constraints(inspector, table): + if name: + found.add(name) + return found + + +def _reject_collisions(planned: dict, existing: set[str]) -> None: + """目标对象名不能互相重复,也不能盖住一个本次不改名的既有对象。 + + Args: + planned: _collect_renames 的结果。 + existing: 当前已占用的对象名。 + + Raises: + RuntimeError: 两个对象要改成同一个名字,或目标名已被占用。 + """ + sources: list[str] = [] + targets: list[str] = [] + for index_rows, constraint_rows in planned.values(): + for old, new in index_rows: + sources.append(old) + targets.append(new) + for _kind, old, new, _payload in constraint_rows: + sources.append(old) + targets.append(new) + if len(targets) != len(set(targets)): + raise RuntimeError(f"object rename target collision: {targets}") + source_set = set(sources) + occupied = sorted(target for target in targets if target in existing and target not in source_set) + if occupied: + raise RuntimeError(f"object rename would overwrite existing names: {occupied}") + + +def _rename_index(bind, old_name: str, new_name: str) -> None: + """改索引名。PostgreSQL 用 ALTER INDEX;SQLite 按 sqlite_master 重建。 + + Args: + bind: 当前迁移连接。 + old_name: 现名。 + new_name: 新名。 + + Raises: + RuntimeError: SQLite 找不到可重建的 CREATE INDEX 语句。 + """ + if bind.dialect.name == "postgresql": + op.execute(sa.text( + f"ALTER INDEX {_quote_ident(old_name)} RENAME TO {_quote_ident(new_name)}" + )) + return + row = bind.execute( + sa.text("SELECT sql FROM sqlite_master WHERE type = 'index' AND name = :name"), + {"name": old_name}, + ).fetchone() + if row is None or not row[0]: + raise RuntimeError(f"sqlite index {old_name} has no SQL to rebuild") + sql = row[0] + quoted = f'"{old_name}"' + if quoted in sql: + rebuilt = sql.replace(quoted, _quote_ident(new_name), 1) + elif old_name in sql: + rebuilt = sql.replace(old_name, new_name, 1) + else: + raise RuntimeError(f"index SQL does not contain {old_name}: {sql}") + op.execute(sa.text(f"DROP INDEX {_quote_ident(old_name)}")) + op.execute(sa.text(rebuilt)) + + +def _rename_constraints(bind, table: str, constraints: list) -> None: + """改一张表上的约束名。 + + 核心逻辑:PostgreSQL 只 RENAME CONSTRAINT,不重建表。SQLite 没有 + RENAME CONSTRAINT,用一次 batch 先删后建,保留列、删除动作和外键目标。 + + Args: + bind: 当前迁移连接。 + table: 约束所在表(已经是本阶段的表名)。 + constraints: (kind, 旧名, 新名, payload) 列表。 + """ + if not constraints: + return + if bind.dialect.name == "postgresql": + for _kind, old_name, new_name, _payload in constraints: + op.execute(sa.text( + f"ALTER TABLE {_quote_ident(table)} " + f"RENAME CONSTRAINT {_quote_ident(old_name)} TO {_quote_ident(new_name)}" + )) + return + with op.batch_alter_table(table) as batch: + for kind, old_name, _new_name, _payload in constraints: + batch.drop_constraint(old_name, type_=kind) + for kind, _old_name, new_name, payload in constraints: + if kind == "foreignkey": + options = payload.get("options") or {} + batch.create_foreign_key( + new_name, + payload["referred_table"], + payload["constrained_columns"], + payload["referred_columns"], + ondelete=options.get("ondelete"), + onupdate=options.get("onupdate"), + deferrable=options.get("deferrable"), + initially=options.get("initially"), + match=options.get("match"), + referent_schema=payload.get("referred_schema"), + ) + elif kind == "unique": + batch.create_unique_constraint(new_name, payload) + elif kind == "check": + batch.create_check_constraint(new_name, payload) + elif kind == "primary": + batch.create_primary_key(new_name, payload) + else: + raise RuntimeError(f"unsupported constraint kind {kind}") + + +def _rewrite_object_names(pairs: list[tuple[str, str]], *, reverse: bool) -> None: + """改写全库里名称包含旧/新表名的索引和约束。 + + 核心逻辑:SQLite 先改索引再 batch 约束,这样 batch 反射到的是新索引名。 + PostgreSQL 先改约束(连带支撑索引),再改剩余普通索引。 + + Args: + pairs: 本方向的表名替换对。 + reverse: True 表示 downgrade。 + """ + bind = op.get_bind() + planned = _collect_renames(bind, pairs, reverse=reverse) + if bind.dialect.name == "postgresql": + for table, (_indexes, constraints) in planned.items(): + _rename_constraints(bind, table, constraints) + for _table, (indexes, _constraints) in planned.items(): + for old_name, new_name in indexes: + _rename_index(bind, old_name, new_name) + return + for _table, (indexes, _constraints) in planned.items(): + for old_name, new_name in indexes: + _rename_index(bind, old_name, new_name) + refreshed = _collect_renames(bind, pairs, reverse=reverse) + for table, (_indexes, constraints) in refreshed.items(): + _rename_constraints(bind, table, constraints) + + +def _index_names(table: str) -> set[str]: + """列出一张表上当前的索引名。 + + Args: + table: 当前表名。 + + Returns: + 非空索引名集合。表不存在时返回空集。 + """ + bind = op.get_bind() + inspector = sa.inspect(bind) + if table not in set(inspector.get_table_names()): + return set() + return {index["name"] for index in inspector.get_indexes(table) or [] if index.get("name")} + + +def _ensure_recipient_index() -> None: + """补建入站投递单列索引,名字与模型一致。 + + 核心逻辑:历史迁移没有这条索引。表已经改成新名之后,短名不存在才创建, + 避免重复升级再插一条同名索引。 + """ + if _CREATED_RECIPIENT_INDEX not in _index_names(_CREATED_RECIPIENT_TABLE): + op.create_index( + _CREATED_RECIPIENT_INDEX, + _CREATED_RECIPIENT_TABLE, + _CREATED_RECIPIENT_COLUMNS, + ) + + +def _drop_recipient_index() -> None: + """删掉升级补建的入站投递单列索引。 + + 核心逻辑:这条索引没有旧名。降级开始时表仍是新名,按短名删除;不存在则跳过。 + """ + if _CREATED_RECIPIENT_INDEX in _index_names(_CREATED_RECIPIENT_TABLE): + op.drop_index(_CREATED_RECIPIENT_INDEX, table_name=_CREATED_RECIPIENT_TABLE) + + +def upgrade() -> None: + """29 表升级:改列、改表名、再改索引与约束名。 + + 核心逻辑:列改名发生在旧表名上,这样 receipt 表仍能被识别。 + rename_table 之后外键指向的表已经是新名,对象名扫描只改名字不改指向。 + 最后补建历史迁移里不存在的单列 recipient 索引。 + """ + for old, _new in _TABLE_RENAMES: + _rename_columns(old, lambda column, table=old: _forward_column_name(table, column)) + for old, new in _TABLE_RENAMES: + op.rename_table(old, new) + _rewrite_object_names(_TABLE_RENAMES, reverse=False) + _ensure_recipient_index() + + +def downgrade() -> None: + """按升级的相反顺序还原对象名、表名和列名。 + + 核心逻辑:先删掉升级补建的单列索引,再还原其余对象名。验证批次索引 + 经 _EXPLICIT_INDEX_NAMES 回到 ix_inventory_test_run_validation_batch。 + """ + _drop_recipient_index() + reverse_pairs = [(new, old) for old, new in _TABLE_RENAMES] + _rewrite_object_names(reverse_pairs, reverse=True) + for old, new in reversed(_TABLE_RENAMES): + op.rename_table(new, old) + for old, _new in reversed(_TABLE_RENAMES): + _rename_columns(old, lambda column, table=old: _reverse_column_name(table, column)) diff --git a/backend/migrations/versions/s17c2d3e4f5a6_freight_rpa_batch_s_enum_data.py b/backend/migrations/versions/s17c2d3e4f5a6_freight_rpa_batch_s_enum_data.py new file mode 100644 index 00000000..62f927c8 --- /dev/null +++ b/backend/migrations/versions/s17c2d3e4f5a6_freight_rpa_batch_s_enum_data.py @@ -0,0 +1,481 @@ +""" +migrations/versions/s17c2d3e4f5a6_freight_rpa_batch_s_enum_data.py + +用途:批次 S 第二段,只改存量字符串,不改 s17b 的表结构。 + 把 job_type、options_source、权限模块键、审计/任务事件名、 + step/stage/action 契约码从 inventory/receipt 词根改成 onhand/inbound。 +依赖:alembic.op、SQLAlchemy;down_revision 为 s17b1c2d3e4f5a。 +逻辑:按词边界替换已知列里的文本(JSON 先转成文本再写回,避免改格式)。 + 权限模块键只替换 JSON 键 "shipping_inventory",并写入私有标记 + __s17c_perm_module;降级只回滚带该标记的行。 + PostgreSQL 上 shipping_audit_events 的 UPDATE 触发器在本迁移语句内临时关闭。 + 改写审计字段后用 audit_snapshot_service 的同一套哈希重算 event_hash。 + 不改 shipment_* / freight_upload*,也不改 s17b。 + schedule_tasks.data_source_type 的历史整值改成现行 job key freight-rpa-onhand。 +""" + +from __future__ import annotations + +import json +import re + +import sqlalchemy as sa +from alembic import op + + +revision = "s17c2d3e4f5a6" +down_revision = "s17b1c2d3e4f5a" +branch_labels = None +depends_on = None + +# 升级方向。更长的旧词必须排在前面,避免短词先吃掉长词的一部分。 +_EXACT_PAIRS: tuple[tuple[str, str], ...] = ( + ("retry_inventory_from_field_mapping", "retry_onhand_from_field_mapping"), + ("retry_inventory_from_preparation", "retry_onhand_from_preparation"), + ("retry_inventory_from_matching", "retry_onhand_from_matching"), + ("refresh_inventory_candidate_projection", "refresh_onhand_candidate_projection"), + ("override_line_inventory_source", "override_line_onhand_source"), + ("recheck_inventory_sufficiency", "recheck_onhand_sufficiency"), + ("retry_inventory_field_mapping", "retry_onhand_field_mapping"), + ("retry_inventory_preparation", "retry_onhand_preparation"), + ("poll_inventory_preparation", "poll_onhand_preparation"), + ("open_inventory_match_review", "open_onhand_match_review"), + ("retry_inventory_matching", "retry_onhand_matching"), + ("reload_inventory_result", "reload_onhand_result"), + ("download_inventory_file", "download_onhand_file"), + ("release_inventory_shortage", "release_onhand_shortage"), + ("upload_inventory_file", "upload_onhand_file"), + ("inventory_source_resolving", "onhand_source_resolving"), + ("inventory_source_routing", "onhand_source_routing"), + ("inventory_field_mapping", "onhand_field_mapping"), + ("inventory_preparation", "onhand_preparation"), + ("inventory_sufficiency", "onhand_sufficiency"), + ("shipping_inventory_callback_process", "freight_rpa_onhand_callback_process"), + ("shipping_inventory_callback_ignored", "freight_rpa_onhand_callback_ignored"), + ("shipping_inventory_sources", "freight_rpa_sources"), + ("shipping_receipt_sources", "freight_rpa_inbound_sources"), + ("shipping_receipt_rpa_callback_received", "shipping_inbound_rpa_callback_received"), + ("shipping_receipt_rpa_callback_timeout", "shipping_inbound_rpa_callback_timeout"), + ("shipping_receipt_rpa_units_listed", "shipping_inbound_rpa_units_listed"), + ("shipping_receipt_rpa_unit_retried", "shipping_inbound_rpa_unit_retried"), + ("rpa_report_inventory", "rpa_report_onhand"), + ("step3_inventory_prepare", "step3_onhand_prepare"), + ("step5_match_inventory", "step5_match_onhand"), + ("inventory_fetching", "onhand_fetching"), + ("inventory_matching", "onhand_matching"), + ("wait_inventory", "wait_onhand"), + ("ensure_inventory", "ensure_onhand"), +) + +# 权限模块 JSON 键。降级只认本迁移写入的标记,避免把 Task 5 已有的 freight_rpa 改回去。 +_PERMISSION_MARKER = "__s17c_perm_module" + +# (表, 列, 是否 JSON)。缺表或缺列则跳过。 +_COLUMNS: tuple[tuple[str, str, bool], ...] = ( + ("jobs", "job_type", False), + ("jobs", "payload_json", True), + ("jobs", "result_json", True), + ("jobs", "message", False), + ("jobs", "error_message", False), + ("kb_jobs", "job_type", False), + ("schedule_tasks", "job_params", True), + ("shipping_order_tasks", "stage", False), + ("shipping_order_tasks", "current_step", False), + ("shipping_order_tasks", "pending_human_reason", False), + ("shipping_order_tasks", "error_code", False), + ("shipping_order_tasks", "step_payload_json", True), + ("shipping_order_processing_runs", "current_stage_code", False), + ("shipping_order_processing_runs", "progress_summary_json", True), + ("shipping_task_events", "event_type", False), + ("shipping_task_events", "source", False), + ("shipping_task_events", "detail_json", True), + ("shipping_task_events", "before_json", True), + ("shipping_task_events", "after_json", True), + ("shipping_audit_events", "event_type", False), + ("shipping_audit_events", "source", False), + ("shipping_audit_events", "action", False), + ("shipping_audit_events", "reason_code", False), + ("shipping_audit_events", "error_code", False), + ("shipping_audit_events", "before_snapshot_json", True), + ("shipping_audit_events", "after_snapshot_json", True), + ("shipping_audit_events", "diff_json", True), + ("shipping_audit_events", "metadata_json", True), + ("shipping_audit_events", "context_refs_json", True), + ("shipping_process_executions", "current_gate_code", False), + ("shipping_process_executions", "last_passed_gate_code", False), + ("shipping_process_executions", "primary_next_action_code", False), + ("shipping_process_gates", "gate_code", False), + ("shipping_process_gates", "next_action_code", False), + ("shipping_process_gates", "blocking_reason_code", False), + ("shipping_process_gates", "blocking_reason_json", True), + ("shipping_process_gates", "recommendation_json", True), + ("shipping_process_gates", "effective_result_json", True), + ("shipping_process_gate_attempts", "input_snapshot_json", True), + ("shipping_process_gate_attempts", "output_snapshot_json", True), + ("shipping_process_gate_attempts", "rule_snapshot_json", True), + ("shipping_process_gate_attempts", "error_code", False), + ("shipping_process_recovery_plans", "current_gate", False), + ("shipping_process_recovery_plans", "action_code", False), + ("shipping_process_recovery_plans", "target_gate", False), + ("shipping_process_recovery_plans", "resume_after_gate", False), + ("shipping_process_recovery_plans", "failure_code", False), + ("shipping_process_recovery_plans", "invalidation_plan_json", True), + ("shipping_process_recovery_plans", "failure_detail_json", True), + ("shipping_onhand_preparation_attempts", "input_snapshot_json", True), + ("shipping_onhand_preparation_attempts", "output_snapshot_json", True), + ("shipping_onhand_preparation_source_attempts", "skip_reason", False), + ("freight_rpa_onhand_task_rpa_attempts", "error_code", False), + ("freight_rpa_onhand_task_rpa_attempts", "error_message", False), + ("freight_rpa_onhand_task_rpa_attempts", "callback_payload_json", True), + ("freight_rpa_onhand_task_rpa_attempts", "extra_json", True), +) + +_PERMISSION_COLUMNS: tuple[tuple[str, str, bool], ...] = ( + ("users", "feature_permissions", True), + ("permission_roles", "feature_permissions", True), + ("app_settings", "value", False), +) + +_AUDIT_TRIGGER = "trg_shipping_audit_events_no_update" + +# 排程 data_source_type 的整列等值。不是子串替换,避免把现行 platform_api_path 改回去。 +_LEGACY_ONHAND_DATA_SOURCE = "shipping_inventory_rpa" +_ONHAND_PLATFORM_JOB_KEY = "freight-rpa-onhand" + + +def _pairs(direction: str) -> tuple[tuple[str, str], ...]: + """返回某一方向的整词对照,按旧词长度降序。""" + pairs = _EXACT_PAIRS if direction == "upgrade" else tuple((new, old) for old, new in _EXACT_PAIRS) + return tuple(sorted(pairs, key=lambda item: len(item[0]), reverse=True)) + + +def _apply_permission_module(value: str, direction: str) -> str: + """ + 只改权限模块 JSON 键 "shipping_inventory" ↔ "freight_rpa"。 + + 核心逻辑:升级替换带引号且后接冒号的键,并写入 __s17c_perm_module。 + 降级仅当标记还在时把该键改回并删掉标记。不改 freight_rpa_sources 等更长标识, + 也不改升级之前就已经是 "freight_rpa" 的行。 + """ + if direction == "upgrade": + pattern = re.compile(r'"shipping_inventory"(\s*:)') + if pattern.search(value) is None: + return value + updated = pattern.sub(r'"freight_rpa"\1', value) + if f'"{_PERMISSION_MARKER}"' in updated: + return updated + stripped = updated.rstrip() + if not stripped.endswith("}"): + return updated + body = stripped[:-1].rstrip() + comma = "" if body.endswith("{") else "," + return f'{body}{comma}"{_PERMISSION_MARKER}":true}}' + if f'"{_PERMISSION_MARKER}"' not in value: + return value + updated = re.sub(r'"freight_rpa"(\s*:)', r'"shipping_inventory"\1', value) + updated = re.sub( + rf',?\s*"{re.escape(_PERMISSION_MARKER)}"\s*:\s*true', + "", + updated, + ) + updated = re.sub(r"\{\s*,", "{", updated) + updated = re.sub(r",\s*\}", "}", updated) + return updated + + +def _prefix_pattern(direction: str) -> re.Pattern[str]: + """inventory_rpa_* / onhand_rpa_* 前缀。不吃模块名 inventory_rpa_workflow。""" + if direction == "upgrade": + return re.compile(r"(? str | None: + """ + 按词边界把存量契约字符串换成目标词根。 + + 核心逻辑:整词优先(长词在前),再替换 inventory_rpa_ / onhand_rpa_ 前缀。 + 路径片段(前有 / 或 \\,或后接 .py)和 ensure_inventory_via_rpa 这类更长标识不改。 + permission=True 时只改带引号的权限模块 JSON 键,降级依赖 __s17c_perm_module 标记。 + + Args: + value: 列的原始文本。None 原样返回。 + direction: upgrade 或 downgrade。 + permission: 是否对本列应用权限模块键。 + + Returns: + 替换后的文本;无变化时与输入相同。 + """ + if value is None: + return None + updated = str(value) + for old, new in _pairs(direction): + updated = re.sub( + rf"(? str: + """给表名或列名加双引号,避免 key 这类保留字。""" + return '"' + name.replace('"', "") + '"' + + +def _set_audit_update_trigger(connection, enabled: bool) -> None: + """PostgreSQL 上临时开关审计表的禁更新触发器。其它方言无此触发器。""" + if connection.dialect.name != "postgresql": + return + if not connection.execute( + sa.text("SELECT 1 FROM pg_trigger WHERE tgname = :name"), + {"name": _AUDIT_TRIGGER}, + ).scalar(): + return + verb = "ENABLE" if enabled else "DISABLE" + connection.execute(sa.text( + f"ALTER TABLE shipping_audit_events {verb} TRIGGER {_AUDIT_TRIGGER}" + )) + + +def _rewrite_column(connection, table: str, column: str, is_json: bool, *, permission: bool, direction: str) -> None: + """ + 重写一张表的一列。表或列不存在则跳过。 + + 核心逻辑:只选出文本里带 inventory、receipt RPA、receipt options_source 或降级新词的行, + 词边界替换后按主键写回。JSON 列在 PostgreSQL 上 CAST 回 JSON。 + """ + inspector = sa.inspect(connection) + if table not in inspector.get_table_names(): + return + column_names = {item["name"] for item in inspector.get_columns(table)} + if column not in column_names: + return + pk_cols = inspector.get_pk_constraint(table).get("constrained_columns") or [] + if len(pk_cols) != 1: + return + pk = pk_cols[0] + if direction == "upgrade": + needles = ("%inventory%", "%shipping_receipt_rpa_%", "%shipping_receipt_sources%") + else: + needles = ("%onhand%", "%shipping_inbound_rpa_%", "%freight_rpa%") + rows = connection.execute(sa.text( + f"SELECT {_quote(pk)}, CAST({_quote(column)} AS TEXT) " + f"FROM {_quote(table)} " + f"WHERE CAST({_quote(column)} AS TEXT) LIKE :needle " + f"OR CAST({_quote(column)} AS TEXT) LIKE :receipt " + f"OR CAST({_quote(column)} AS TEXT) LIKE :perm" + ), {"needle": needles[0], "receipt": needles[1], "perm": needles[2]}).fetchall() + dialect = connection.dialect.name + for row_id, raw in rows: + rewritten = rewrite_persisted_text(raw, direction=direction, permission=permission) + if rewritten is None or rewritten == raw: + continue + if dialect == "postgresql" and is_json: + statement = ( + f"UPDATE {_quote(table)} SET {_quote(column)} = CAST(:value AS JSON) " + f"WHERE {_quote(pk)} = :row_id" + ) + else: + statement = ( + f"UPDATE {_quote(table)} SET {_quote(column)} = :value " + f"WHERE {_quote(pk)} = :row_id" + ) + connection.execute(sa.text(statement), {"value": rewritten, "row_id": row_id}) + + +_AUDIT_HASH_FIELDS = ( + "id", + "event_type", + "aggregate_type", + "aggregate_id", + "action", + "result", + "reason_code", + "workflow_id", + "workflow_item_id", + "workflow_item_version_id", + "version_no", + "run_no", + "document_id", + "review_case_no", + "task_no", + "operation_id", + "request_id", + "actor_type", + "actor_id", + "before_snapshot_json", + "after_snapshot_json", + "diff_json", + "previous_event_hash", + "event_hash", + "sensitivity_level", +) + + +def _json_object(raw: object) -> dict | None: + """把审计快照列还原成 dict;空值或非对象返回 None。""" + if raw is None or raw == "": + return None + if isinstance(raw, dict): + return raw + try: + parsed = json.loads(str(raw)) + except (TypeError, ValueError): + return None + return parsed if isinstance(parsed, dict) else None + + +def _rehash_shipping_audit_events(connection) -> None: + """ + 用生产同一套 build_event_hash_payload / compute_event_hash 重算审计哈希。 + + 核心逻辑:按聚合 id 升序走链。本行内容变了就重算 event_hash; + 前一行哈希变了就把本行 previous_event_hash 接上再重算,避免链断裂。 + 缺 event_hash 列则跳过。 + """ + inspector = sa.inspect(connection) + if "shipping_audit_events" not in inspector.get_table_names(): + return + present = {item["name"] for item in inspector.get_columns("shipping_audit_events")} + if "id" not in present or "event_hash" not in present or "event_type" not in present: + return + from app.services.shipping_notice.audit_snapshot_service import ( + build_event_hash_payload, + compute_event_hash, + ) + + selected = [name for name in _AUDIT_HASH_FIELDS if name in present] + rows = connection.execute(sa.text( + "SELECT " + ", ".join(_quote(name) for name in selected) + " FROM shipping_audit_events ORDER BY " + + ("aggregate_type, aggregate_id, " if "aggregate_type" in present and "aggregate_id" in present else "") + + "id" + )).mappings().all() + running_hash: str | None = None + current_group: tuple[str, str] | None = None + for row in rows: + group = ( + str(row.get("aggregate_type") or ""), + str(row.get("aggregate_id") or ""), + ) + if group != current_group: + current_group = group + running_hash = None + previous_for_hash = row.get("previous_event_hash") + else: + previous_for_hash = running_hash + payload = build_event_hash_payload( + event_type=str(row.get("event_type") or ""), + aggregate_type=str(row.get("aggregate_type") or ""), + aggregate_id=str(row.get("aggregate_id") or ""), + action=row.get("action"), + result=row.get("result"), + reason_code=row.get("reason_code"), + workflow_id=row.get("workflow_id"), + workflow_item_id=row.get("workflow_item_id"), + workflow_item_version_id=row.get("workflow_item_version_id"), + version_no=row.get("version_no"), + run_no=row.get("run_no"), + document_id=row.get("document_id"), + review_case_no=row.get("review_case_no"), + task_no=row.get("task_no"), + operation_id=row.get("operation_id"), + request_id=row.get("request_id"), + actor_type=str(row.get("actor_type") or "system"), + actor_id=row.get("actor_id"), + before_snapshot=_json_object(row.get("before_snapshot_json")), + after_snapshot=_json_object(row.get("after_snapshot_json")), + diff_json=_json_object(row.get("diff_json")), + previous_event_hash=previous_for_hash, + sensitivity_level=row.get("sensitivity_level"), + ) + new_hash = compute_event_hash(payload) + if new_hash != row.get("event_hash") or previous_for_hash != row.get("previous_event_hash"): + if "previous_event_hash" in present: + connection.execute(sa.text( + "UPDATE shipping_audit_events SET event_hash = :event_hash, " + "previous_event_hash = :previous_event_hash WHERE id = :row_id" + ), { + "event_hash": new_hash, + "previous_event_hash": previous_for_hash, + "row_id": row["id"], + }) + else: + connection.execute(sa.text( + "UPDATE shipping_audit_events SET event_hash = :event_hash WHERE id = :row_id" + ), {"event_hash": new_hash, "row_id": row["id"]}) + running_hash = new_hash + + +def _rewrite_legacy_onhand_data_source(connection, direction: str) -> None: + """ + 把 schedule_tasks.data_source_type 的历史整值改成现行 platform job key。 + + 核心逻辑:只匹配整列相等,不扫描其它列里的 freight-rpa-onhand。 + 升级同时把 schedule_type / platform_api_path 拨到 platform_job。 + 降级只把 data_source_type 从现行 job key 改回历史整值。 + + Args: + connection: Alembic 绑定的连接。 + direction: upgrade 或 downgrade。 + """ + inspector = sa.inspect(connection) + if "schedule_tasks" not in inspector.get_table_names(): + return + columns = {item["name"] for item in inspector.get_columns("schedule_tasks")} + if "data_source_type" not in columns: + return + if direction == "upgrade": + assignments = [f"{_quote('data_source_type')} = :new_source"] + params: dict[str, str] = { + "old_source": _LEGACY_ONHAND_DATA_SOURCE, + "new_source": _ONHAND_PLATFORM_JOB_KEY, + } + if "schedule_type" in columns: + assignments.append(f"{_quote('schedule_type')} = 'platform_job'") + if "platform_api_path" in columns: + assignments.append(f"{_quote('platform_api_path')} = :new_source") + connection.execute(sa.text( + f"UPDATE {_quote('schedule_tasks')} SET {', '.join(assignments)} " + f"WHERE {_quote('data_source_type')} = :old_source" + ), params) + return + connection.execute(sa.text( + f"UPDATE {_quote('schedule_tasks')} SET {_quote('data_source_type')} = :old_source " + f"WHERE {_quote('data_source_type')} = :new_source" + ), { + "old_source": _LEGACY_ONHAND_DATA_SOURCE, + "new_source": _ONHAND_PLATFORM_JOB_KEY, + }) + + +def _rewrite_all(connection, direction: str) -> None: + """按列清单重写契约字符串。审计表在 PostgreSQL 上先关禁更新触发器。""" + _set_audit_update_trigger(connection, enabled=False) + try: + _rewrite_legacy_onhand_data_source(connection, direction) + for table, column, is_json in _COLUMNS: + _rewrite_column( + connection, table, column, is_json, permission=False, direction=direction, + ) + for table, column, is_json in _PERMISSION_COLUMNS: + _rewrite_column( + connection, table, column, is_json, permission=True, direction=direction, + ) + _rehash_shipping_audit_events(connection) + finally: + _set_audit_update_trigger(connection, enabled=True) + + +def upgrade() -> None: + """把存量枚举、事件名、job_type、options_source 和权限模块键改成新词。""" + _rewrite_all(op.get_bind(), "upgrade") + + +def downgrade() -> None: + """按同一对照表把新词改回旧词。""" + _rewrite_all(op.get_bind(), "downgrade") diff --git a/backend/migrations/versions/s18d1e2f3a4b5_freight_rpa_phase_b_report_ownership.py b/backend/migrations/versions/s18d1e2f3a4b5_freight_rpa_phase_b_report_ownership.py new file mode 100644 index 00000000..e6e65aa3 --- /dev/null +++ b/backend/migrations/versions/s18d1e2f3a4b5_freight_rpa_phase_b_report_ownership.py @@ -0,0 +1,563 @@ +""" +migrations/versions/s18d1e2f3a4b5_freight_rpa_phase_b_report_ownership.py + +用途:货代 RPA 阶段 B 第一段——新建在手报表配置表 freight_rpa_onhand_report_configs, + 把站点表 freight_rpa_sources 上的 report_path_json / query_parameters_json / + parsing_profile_id 三列搬进该表,把启用检查约束换成只看 excel_template_id 的 + 模板版本(CHECK 不能跨表),再把 shipping_onhand_files 改名为 + freight_rpa_onhand_report_files,并按 s17b 的手法重写名字含旧表名的 + 索引 / 约束对象名(列名一概不改)。 +依赖:alembic.op、SQLAlchemy 反射;down_revision 为批次 S 第二段 s17c2d3e4f5a6。 + 解析方案表已在 s17b 落到 freight_rpa_parsing_profiles,本迁移不再出现 + 解析方案表的第二条改名,禁止出现 freight_rpa_onhand_parsing_profiles。 +逻辑:先建配置表(外键到 freight_rpa_sources / freight_rpa_parsing_profiles / users, + source_id 唯一),再把三列数据 INSERT 过去;然后用 batch_alter_table + (PostgreSQL 直发 ALTER,SQLite 走重建)删旧启用约束、删三列、建模板约束; + rename_table 之后扫全库对象名,把 shipping_onhand_files token 替换为 + freight_rpa_onhand_report_files,超过 PostgreSQL 63 字节的沿用 s17b 的截断。 + downgrade 按相反顺序还原:文件表改回旧名并回滚对象名,三列加回站点行, + 从配置表 UPDATE 回数据(无配置行的站点两列 JSON 用 COALESCE 回填 '{}' / '[]', + 避免 NULL 写入 NOT NULL 列),删掉配置表,最后恢复 + ck_freight_rpa_sources_enabled_bindings 原文(双绑定表达式)。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = "s18d1e2f3a4b5" +down_revision = "s17c2d3e4f5a6" +branch_labels = None +depends_on = None + +# PostgreSQL 标识符上限(NAMEDATALEN-1),与 s17b 一致。 +_MAX_IDENTIFIER_LENGTH = 63 + +_SOURCES_TABLE = "freight_rpa_sources" +_CONFIG_TABLE = "freight_rpa_onhand_report_configs" +_FILES_TABLE_OLD = "shipping_onhand_files" +_FILES_TABLE_NEW = "freight_rpa_onhand_report_files" + +# c27e 创建、s17b 改到新表名词根的启用约束,及其双绑定原文与模板版替代。 +_ENABLED_BINDINGS_CHECK = "ck_freight_rpa_sources_enabled_bindings" +_ENABLED_TEMPLATE_CHECK = "ck_freight_rpa_sources_enabled_template" +_ENABLED_BINDINGS_SQL = ( + "enabled = false OR (parsing_profile_id IS NOT NULL AND excel_template_id IS NOT NULL)" +) +_ENABLED_TEMPLATE_SQL = "enabled = false OR excel_template_id IS NOT NULL" +# b17 建出的站点→解析方案外键名(不含旧表名词根,s17b 未改名),降级按原名还原。 +_SOURCES_PARSING_FK = "fk_inventory_sources_parsing_profile" +# 站点→解析方案列的自动索引名(模型 index=True;s17b 换到新表名词根),降级补回。 +_SOURCES_PARSING_INDEX = "ix_freight_rpa_sources_parsing_profile_id" +# 本期搬离站点行的三列。 +_MOVED_COLUMNS = ("report_path_json", "query_parameters_json", "parsing_profile_id") + + +def _quote_ident(name: str) -> str: + """给 SQL 标识符加双引号,内部引号按标准加倍。 + + Args: + name: 表、索引或约束名。 + + Returns: + 可拼进 DDL 的引用标识符。 + """ + return '"' + name.replace('"', '""') + '"' + + +def _substitute(name: str, pairs: list[tuple[str, str]]) -> str: + """把对象名中的表名 token 换成对照表里的另一个名字。 + + 核心逻辑:按源 token 长度降序替换,避免短表名吃掉更长表名的前缀。 + 本迁移只有一对 token(文件表新旧名),直接替换。 + + Args: + name: 当前索引或约束名。 + pairs: (被替换的表名, 替换后的表名)。升级用旧→新,降级用新→旧。 + + Returns: + 替换后的对象名(尚未按 63 字节截断)。 + """ + updated = name + for source, destination in sorted(pairs, key=lambda item: len(item[0]), reverse=True): + updated = updated.replace(source, destination) + return updated + + +def _clip(name: str) -> str: + """把标识符限制在 PostgreSQL 的 63 字节以内(沿用 s17b 的截断函数)。 + + Args: + name: 已完成表名替换的对象名。 + + Returns: + 长度不超过 63 的名字。未超长时原样返回。 + """ + if len(name) <= _MAX_IDENTIFIER_LENGTH: + return name + return name[:_MAX_IDENTIFIER_LENGTH] + + +def _iter_constraints(inspector, table: str): + """列出一张表上带名字的外键、唯一、检查和主键约束。 + + Args: + inspector: 当前连接的 SQLAlchemy Inspector。 + table: 表名。 + + Yields: + (kind, name, payload)。kind 使用 alembic batch 的 type_ 取值。 + 外键 payload 是反射字典,唯一/主键 payload 是列名列表,检查 payload 是表达式。 + """ + for foreign_key in inspector.get_foreign_keys(table) or []: + yield "foreignkey", foreign_key.get("name"), foreign_key + for unique in inspector.get_unique_constraints(table) or []: + yield "unique", unique.get("name"), list(unique.get("column_names") or []) + for check in inspector.get_check_constraints(table) or []: + yield "check", check.get("name"), check.get("sqltext") + primary = inspector.get_pk_constraint(table) or {} + yield "primary", primary.get("name"), list(primary.get("constrained_columns") or []) + + +def _target_name(current: str, pairs: list[tuple[str, str]]) -> str: + """计算对象改名的目标:表名替换再截断。 + + Args: + current: 库里现在的对象名。 + pairs: 本方向的表名替换对。 + + Returns: + 应改成的对象名。与 current 相同表示不用改。 + """ + return _clip(_substitute(current, pairs)) + + +def _existing_object_names(inspector) -> set[str]: + """收集当前库里全部索引名和约束名,供目标名冲突检查。 + + Args: + inspector: 当前连接的 Inspector。 + + Returns: + 已占用的对象名集合。 + """ + found: set[str] = set() + for table in inspector.get_table_names(): + if table.startswith("sqlite_"): + continue + for index in inspector.get_indexes(table) or []: + if index.get("name"): + found.add(index["name"]) + for _kind, name, _payload in _iter_constraints(inspector, table): + if name: + found.add(name) + return found + + +def _reject_collisions(planned: dict, existing: set[str]) -> None: + """目标对象名不能互相重复,也不能盖住一个本次不改名的既有对象。 + + Args: + planned: {表名: (索引列表, 约束列表)} 形态的改名计划。 + existing: 当前已占用的对象名。 + + Raises: + RuntimeError: 两个对象要改成同一个名字,或目标名已被占用。 + """ + sources: list[str] = [] + targets: list[str] = [] + for index_rows, constraint_rows in planned.values(): + for old_name, new_name in index_rows: + sources.append(old_name) + targets.append(new_name) + for _kind, old_name, new_name, _payload in constraint_rows: + sources.append(old_name) + targets.append(new_name) + if len(targets) != len(set(targets)): + raise RuntimeError(f"object rename target collision: {targets}") + source_set = set(sources) + occupied = sorted(target for target in targets if target in existing and target not in source_set) + if occupied: + raise RuntimeError(f"object rename would overwrite existing names: {occupied}") + + +def _collect_renames(bind, pairs: list[tuple[str, str]]) -> dict: + """扫描全库,收集名称中含表名 token、因而需要改名的索引和约束。 + + 核心逻辑(沿用 s17b):PostgreSQL 上唯一/主键约束与其支撑索引同名, + 只走约束(RENAME CONSTRAINT 会带走索引);SQLite 上独立索引用重建, + 表内约束才进 batch,同名时以索引为准,避免拆掉已改过的索引。 + + Args: + bind: 当前迁移连接。 + pairs: 本方向的表名替换对。 + + Returns: + {表名: (索引列表[(旧, 新)], 约束列表[(kind, 旧, 新, payload)])}。 + """ + inspector = sa.inspect(bind) + dialect = bind.dialect.name + planned: dict[str, tuple[list, list]] = {} + for table in inspector.get_table_names(): + if table.startswith("sqlite_"): + continue + raw_indexes: list[str] = [] + for index in inspector.get_indexes(table) or []: + name = index.get("name") + if name and not str(name).startswith("sqlite_"): + raw_indexes.append(name) + raw_constraints = [] + for kind, name, payload in _iter_constraints(inspector, table): + if name and not str(name).startswith("sqlite_"): + raw_constraints.append((kind, name, payload)) + + index_rows: list[tuple[str, str]] = [] + constraint_rows: list[tuple[str, str, str, object]] = [] + if dialect == "postgresql": + constraint_names = {name for _kind, name, _payload in raw_constraints} + for kind, name, payload in raw_constraints: + target = _target_name(name, pairs) + if target != name: + constraint_rows.append((kind, name, target, payload)) + for name in raw_indexes: + if name in constraint_names: + continue + target = _target_name(name, pairs) + if target != name: + index_rows.append((name, target)) + else: + index_names = set(raw_indexes) + for name in raw_indexes: + target = _target_name(name, pairs) + if target != name: + index_rows.append((name, target)) + for kind, name, payload in raw_constraints: + if name in index_names: + continue + target = _target_name(name, pairs) + if target != name: + constraint_rows.append((kind, name, target, payload)) + if index_rows or constraint_rows: + planned[table] = (index_rows, constraint_rows) + _reject_collisions(planned, _existing_object_names(inspector)) + return planned + + +def _rename_index(bind, old_name: str, new_name: str) -> None: + """改索引名。PostgreSQL 用 ALTER INDEX;SQLite 按 sqlite_master 重建。 + + Args: + bind: 当前迁移连接。 + old_name: 现名。 + new_name: 新名。 + + Raises: + RuntimeError: SQLite 找不到可重建的 CREATE INDEX 语句。 + """ + if bind.dialect.name == "postgresql": + op.execute(sa.text( + f"ALTER INDEX {_quote_ident(old_name)} RENAME TO {_quote_ident(new_name)}" + )) + return + row = bind.execute( + sa.text("SELECT sql FROM sqlite_master WHERE type = 'index' AND name = :name"), + {"name": old_name}, + ).fetchone() + if row is None or not row[0]: + raise RuntimeError(f"sqlite index {old_name} has no SQL to rebuild") + sql = row[0] + quoted = f'"{old_name}"' + if quoted in sql: + rebuilt = sql.replace(quoted, _quote_ident(new_name), 1) + elif old_name in sql: + rebuilt = sql.replace(old_name, new_name, 1) + else: + raise RuntimeError(f"index SQL does not contain {old_name}: {sql}") + op.execute(sa.text(f"DROP INDEX {_quote_ident(old_name)}")) + op.execute(sa.text(rebuilt)) + + +def _rename_constraints(bind, table: str, constraints: list) -> None: + """改一张表上的约束名。 + + 核心逻辑(沿用 s17b):PostgreSQL 只 RENAME CONSTRAINT,不重建表; + SQLite 没有 RENAME CONSTRAINT,用一次 batch 先删后建, + 保留列、外键目标与删除动作。 + + Args: + bind: 当前迁移连接。 + table: 约束所在表(已经是本阶段的表名)。 + constraints: (kind, 旧名, 新名, payload) 列表。 + """ + if not constraints: + return + if bind.dialect.name == "postgresql": + for _kind, old_name, new_name, _payload in constraints: + op.execute(sa.text( + f"ALTER TABLE {_quote_ident(table)} " + f"RENAME CONSTRAINT {_quote_ident(old_name)} TO {_quote_ident(new_name)}" + )) + return + with op.batch_alter_table(table) as batch: + for kind, old_name, _new_name, _payload in constraints: + batch.drop_constraint(old_name, type_=kind) + for kind, _old_name, new_name, payload in constraints: + if kind == "foreignkey": + options = payload.get("options") or {} + batch.create_foreign_key( + new_name, + payload["referred_table"], + payload["constrained_columns"], + payload["referred_columns"], + ondelete=options.get("ondelete"), + onupdate=options.get("onupdate"), + deferrable=options.get("deferrable"), + initially=options.get("initially"), + match=options.get("match"), + referent_schema=payload.get("referred_schema"), + ) + elif kind == "unique": + batch.create_unique_constraint(new_name, payload) + elif kind == "check": + batch.create_check_constraint(new_name, payload) + elif kind == "primary": + batch.create_primary_key(new_name, payload) + else: + raise RuntimeError(f"unsupported constraint kind {kind}") + + +def _rewrite_object_names(pairs: list[tuple[str, str]]) -> None: + """改写全库里名称包含旧/新文件表名的索引和约束。 + + 核心逻辑(沿用 s17b):SQLite 先改索引再 batch 约束,这样 batch + 反射到的是新索引名;PostgreSQL 先改约束(连带支撑索引), + 再改剩余普通索引。 + + Args: + pairs: 本方向的表名替换对。 + """ + bind = op.get_bind() + planned = _collect_renames(bind, pairs) + if bind.dialect.name == "postgresql": + for table, (_indexes, constraints) in planned.items(): + _rename_constraints(bind, table, constraints) + for _table, (indexes, _constraints) in planned.items(): + for old_name, new_name in indexes: + _rename_index(bind, old_name, new_name) + return + for _table, (indexes, _constraints) in planned.items(): + for old_name, new_name in indexes: + _rename_index(bind, old_name, new_name) + refreshed = _collect_renames(op.get_bind(), pairs) + for table, (_indexes, constraints) in refreshed.items(): + _rename_constraints(op.get_bind(), table, constraints) + + +def _enabled_bindings_constraint_name(bind) -> str | None: + """找到站点表上现存的旧启用检查约束名。 + + 核心逻辑:优先按 s17b 之后的既定名 ck_freight_rpa_sources_enabled_bindings + 命中;若历史库上的名字仍是改名前的其它拼写,则按「定义里同时含 + parsing_profile_id 与 excel_template_id」反射定位那一条再删。 + + Args: + bind: 当前迁移连接。 + + Returns: + 约束名;站点上没有该约束时返回 None。 + """ + checks = sa.inspect(bind).get_check_constraints(_SOURCES_TABLE) or [] + for item in checks: + if item.get("name") == _ENABLED_BINDINGS_CHECK: + return item["name"] + for item in checks: + sqltext = str(item.get("sqltext") or "") + if "parsing_profile_id" in sqltext and "excel_template_id" in sqltext: + return item.get("name") + return None + + +def _create_config_table() -> None: + """新建在手报表配置表,形状与 ShippingOnhandReportConfig 模型一致。 + + 核心逻辑:source_id 唯一且指向站点(级联删除);parsing_profile_id + 可空,指向 s17b 落定的 freight_rpa_parsing_profiles;created_by / + updated_by 指向 users。JSON 两列与 config_version 同入站配置表风格。 + """ + op.create_table( + _CONFIG_TABLE, + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("source_id", sa.Integer(), nullable=False), + sa.Column("parsing_profile_id", sa.Integer(), nullable=True), + sa.Column("report_path_json", sa.JSON(), nullable=False, server_default=sa.text("'{}'")), + sa.Column("query_parameters_json", sa.JSON(), nullable=False, server_default=sa.text("'[]'")), + sa.Column("config_version", sa.Integer(), nullable=False, server_default=sa.text("1")), + sa.Column("created_by", sa.Integer(), nullable=True), + sa.Column("updated_by", sa.Integer(), nullable=True), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.Column("updated_at", sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint( + ["source_id"], ["freight_rpa_sources.id"], + name="fk_freight_rpa_onhand_report_configs_source", ondelete="CASCADE", + ), + sa.ForeignKeyConstraint( + ["parsing_profile_id"], ["freight_rpa_parsing_profiles.id"], + name="fk_freight_rpa_onhand_report_configs_parsing_profile", + ), + sa.ForeignKeyConstraint(["created_by"], ["users.id"]), + sa.ForeignKeyConstraint(["updated_by"], ["users.id"]), + sa.UniqueConstraint("source_id", name="uq_freight_rpa_onhand_report_configs_source"), + ) + op.create_index( + "ix_freight_rpa_onhand_report_configs_source_id", _CONFIG_TABLE, ["source_id"], + ) + op.create_index( + "ix_freight_rpa_onhand_report_configs_parsing_profile_id", + _CONFIG_TABLE, + ["parsing_profile_id"], + ) + + +def _moved_column_dependents(bind) -> tuple[list[str], list[str]]: + """列出站点表上直接依赖三列中任一列的索引与外键名。 + + 核心逻辑:SQLite batch 重建不会自动放弃被删列上的索引(alembic 会按原样重建), + PostgreSQL 虽随列自动删除,但先显式 DROP 也不冲突;故两侧统一先删。 + 只有约束列与被删列相交的对象算依赖,excel_template 等其余外键不动。 + + Args: + bind: 当前迁移连接。 + + Returns: + (索引名列表, 外键名列表)。无名的内部对象反射不出名字,本就不在重建范围。 + """ + inspector = sa.inspect(bind) + dropped = set(_MOVED_COLUMNS) + index_names = [ + str(item["name"]) + for item in inspector.get_indexes(_SOURCES_TABLE) or [] + if item.get("name") + and set(item.get("column_names") or []) & dropped + ] + foreign_key_names = [ + str(item["name"]) + for item in inspector.get_foreign_keys(_SOURCES_TABLE) or [] + if item.get("name") + and set(item.get("constrained_columns") or []) & dropped + ] + return index_names, foreign_key_names + + +def _move_columns_off_source() -> None: + """删站点上三列,替换启用约束为模板版。 + + 核心逻辑:数据已 INSERT 到配置表后才执行。batch_alter_table 在 + PostgreSQL 直发 ALTER,在 SQLite 走重建;解析方案外键与其索引随 + parsing_profile_id 列一并消失。 + """ + bind = op.get_bind() + old_check = _enabled_bindings_constraint_name(bind) + moved_indexes, moved_keys = _moved_column_dependents(bind) + checks = { + item.get("name") + for item in sa.inspect(bind).get_check_constraints(_SOURCES_TABLE) or [] + } + with op.batch_alter_table(_SOURCES_TABLE) as batch: + # 被删列上的索引/外键先显式退场,SQLite 重建才不会引用已不存在的列。 + for index_name in moved_indexes: + batch.drop_index(index_name) + for foreign_key_name in moved_keys: + batch.drop_constraint(foreign_key_name, type_="foreignkey") + if old_check: + batch.drop_constraint(old_check, type_="check") + batch.drop_column("report_path_json") + batch.drop_column("query_parameters_json") + batch.drop_column("parsing_profile_id") + if _ENABLED_TEMPLATE_CHECK not in checks: + batch.create_check_constraint(_ENABLED_TEMPLATE_CHECK, _ENABLED_TEMPLATE_SQL) + + +def _restore_columns_on_source() -> None: + """把三列按原可空性与默认值加回站点行,并去掉模板版启用约束。 + + 核心逻辑:downgrade 专用。parsing_profile_id 外键按 b17 的原名 + fk_inventory_sources_parsing_profile 还原(s17b 未改过该名)。 + """ + bind = op.get_bind() + checks = { + item.get("name") + for item in sa.inspect(bind).get_check_constraints(_SOURCES_TABLE) or [] + } + with op.batch_alter_table(_SOURCES_TABLE) as batch: + if _ENABLED_TEMPLATE_CHECK in checks: + batch.drop_constraint(_ENABLED_TEMPLATE_CHECK, type_="check") + batch.add_column(sa.Column( + "report_path_json", sa.JSON(), nullable=False, server_default=sa.text("'{}'"), + )) + batch.add_column(sa.Column( + "query_parameters_json", sa.JSON(), nullable=False, server_default=sa.text("'[]'"), + )) + batch.add_column(sa.Column("parsing_profile_id", sa.Integer(), nullable=True)) + batch.create_foreign_key( + _SOURCES_PARSING_FK, "freight_rpa_parsing_profiles", + ["parsing_profile_id"], ["id"], + ) + batch.create_index(_SOURCES_PARSING_INDEX, ["parsing_profile_id"]) + + +def upgrade() -> None: + """建在手报表配置表、搬三列、换启用约束、改文件表名并重写对象名。 + + 核心逻辑:顺序不可颠倒——配置表必须先于数据搬移存在;三列必须先搬 + 数据再删;文件表改名后 object 名扫描才能扫到旧 token 的索引/约束。 + """ + # [STEP 1] 配置表就位并把站点三列数据搬到新表(created_by/updated_by 留空)。 + _create_config_table() + op.execute(sa.text( + "INSERT INTO freight_rpa_onhand_report_configs " + "(source_id, report_path_json, query_parameters_json, parsing_profile_id, " + "config_version, created_at, updated_at) " + "SELECT id, report_path_json, query_parameters_json, parsing_profile_id, " + "config_version, created_at, updated_at FROM freight_rpa_sources" + )) + # [STEP 2] 站点行删三列,启用约束换成只看 excel_template_id 的模板版。 + _move_columns_off_source() + # [STEP 3] 在手文件表归 RPA:改表名并重写名字含旧表名的索引/约束对象名。 + op.rename_table(_FILES_TABLE_OLD, _FILES_TABLE_NEW) + _rewrite_object_names([(_FILES_TABLE_OLD, _FILES_TABLE_NEW)]) + + +def downgrade() -> None: + """按升级相反顺序还原:文件表名、三列、数据、配置表与旧启用约束。 + + 核心逻辑:先改回文件表并回滚对象名;再在站点上恢复三列与外键, + 从配置表 UPDATE 回数据后删表;最后重建 ck_freight_rpa_sources_enabled_bindings + 原文(parsing_profile + excel_template 双绑定)。 + """ + # [STEP 1] 在手文件表名与对象名回滚。 + op.rename_table(_FILES_TABLE_NEW, _FILES_TABLE_OLD) + _rewrite_object_names([(_FILES_TABLE_NEW, _FILES_TABLE_OLD)]) + # [STEP 2] 站点行加回三列与解析方案外键,模板版启用约束退场。 + _restore_columns_on_source() + # [STEP 3] 把配置行数据 UPDATE 回站点行。站点没有配置行时子查询返回 NULL, + # 两列 JSON 在站点行上是 NOT NULL,必须 COALESCE 回 server_default 形态; + # parsing_profile_id 可空,允许保持 NULL。 + op.execute(sa.text( + "UPDATE freight_rpa_sources SET " + "report_path_json = COALESCE((" + "SELECT c.report_path_json FROM freight_rpa_onhand_report_configs c " + "WHERE c.source_id = freight_rpa_sources.id), '{}'), " + "query_parameters_json = COALESCE((" + "SELECT c.query_parameters_json FROM freight_rpa_onhand_report_configs c " + "WHERE c.source_id = freight_rpa_sources.id), '[]'), " + "parsing_profile_id = (" + "SELECT c.parsing_profile_id FROM freight_rpa_onhand_report_configs c " + "WHERE c.source_id = freight_rpa_sources.id)" + )) + # [STEP 4] 配置表退役。 + op.drop_table(_CONFIG_TABLE) + # [STEP 5] 恢复双绑定的原启用约束。 + with op.batch_alter_table(_SOURCES_TABLE) as batch: + batch.create_check_constraint(_ENABLED_BINDINGS_CHECK, _ENABLED_BINDINGS_SQL) \ No newline at end of file diff --git a/backend/migrations/versions/s19a0b1c2d3e4_freight_rpa_outbound_and_inbound_slim.py b/backend/migrations/versions/s19a0b1c2d3e4_freight_rpa_outbound_and_inbound_slim.py new file mode 100644 index 00000000..cb89f06e --- /dev/null +++ b/backend/migrations/versions/s19a0b1c2d3e4_freight_rpa_outbound_and_inbound_slim.py @@ -0,0 +1,275 @@ +""" +migrations/versions/s19a0b1c2d3e4_freight_rpa_outbound_and_inbound_slim.py + +用途:新建出站 RPA 三表,并拆除入站 per-file 企微投递表 + freight_rpa_inbound_notification_deliveries(Task 2 已删 Python 模型)。 +依赖:alembic.op、SQLAlchemy;down_revision 为实施时单 head s18d1e2f3a4b5。 +逻辑:autogenerate 噪声过大(无关 drop / 历史索引改名),故手写本 revision。 + 升级先 drop 投递表及其历史索引,再按 ORM 同构建 + configs → unit_runs → files;降级先拆出站三表,再按 s17b 后的现行结构 + 还原投递表(不恢复投递数据)。 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = "s19a0b1c2d3e4" +down_revision = "s18d1e2f3a4b5" +branch_labels = None +depends_on = None + +_DELIVERIES_TABLE = "freight_rpa_inbound_notification_deliveries" +_DELIVERIES_INDEXES = ( + "ix_fr_inbound_notif_deliveries_recipient_user_id", + "ix_shipping_receipt_delivery_file_recipient", + "ix_shipping_receipt_delivery_unit_created", +) + + +def upgrade() -> None: + """Drop inbound notification deliveries, then create outbound config / run / file tables.""" + # [STEP 1] 入站投递账本:索引名含 s17b 未改的 shipping_receipt_delivery_* 与补建短名。 + for index_name in _DELIVERIES_INDEXES: + op.drop_index(index_name, table_name=_DELIVERIES_TABLE) + op.drop_table(_DELIVERIES_TABLE) + + # [STEP 2] 出站配置:站点一对一,字段与入站配置同构,无独立启停列。 + op.create_table( + "freight_rpa_outbound_report_configs", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("source_id", sa.Integer(), nullable=False), + sa.Column("parsing_profile_id", sa.Integer(), nullable=True), + sa.Column("report_path_json", sa.JSON(), server_default=sa.text("'{}'"), nullable=False), + sa.Column("query_parameters_json", sa.JSON(), server_default=sa.text("'[]'"), nullable=False), + sa.Column("config_version", sa.Integer(), server_default=sa.text("1"), nullable=False), + sa.Column("created_by", sa.Integer(), nullable=True), + sa.Column("updated_by", sa.Integer(), nullable=True), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.Column("updated_at", sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(["created_by"], ["users.id"]), + sa.ForeignKeyConstraint(["parsing_profile_id"], ["freight_rpa_parsing_profiles.id"]), + sa.ForeignKeyConstraint(["source_id"], ["freight_rpa_sources.id"]), + sa.ForeignKeyConstraint(["updated_by"], ["users.id"]), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("source_id", name="uq_freight_rpa_outbound_report_configs_source"), + ) + op.create_index( + "ix_freight_rpa_outbound_report_configs_parsing_profile_id", + "freight_rpa_outbound_report_configs", + ["parsing_profile_id"], + unique=False, + ) + op.create_index( + "ix_freight_rpa_outbound_report_configs_source_id", + "freight_rpa_outbound_report_configs", + ["source_id"], + unique=False, + ) + + # [STEP 3] 出站执行单元:回调幂等;schedule_run_id 可空以支持按需触发。 + op.create_table( + "freight_rpa_outbound_rpa_unit_runs", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("schedule_run_id", sa.Integer(), nullable=True), + sa.Column("source_id", sa.Integer(), nullable=False), + sa.Column("retry_of_id", sa.Integer(), nullable=True), + sa.Column("source_code", sa.String(length=64), nullable=False), + sa.Column("connector_type", sa.String(length=32), nullable=False), + sa.Column("warehouse_id", sa.String(length=64), nullable=True), + sa.Column("callback_id", sa.String(length=128), nullable=False), + sa.Column("status", sa.String(length=32), server_default="queued", nullable=False), + sa.Column("config_snapshot_json", sa.JSON(), nullable=False), + sa.Column("trigger_snapshot_json", sa.JSON(), nullable=False), + sa.Column("result_json", sa.JSON(), nullable=False), + sa.Column("error_code", sa.String(length=64), nullable=True), + sa.Column("error_message", sa.Text(), nullable=True), + sa.Column("started_at", sa.DateTime(), nullable=True), + sa.Column("finished_at", sa.DateTime(), nullable=True), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.CheckConstraint( + "status IN ('queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled')", + name="ck_freight_rpa_outbound_rpa_unit_runs_status", + ), + sa.ForeignKeyConstraint(["retry_of_id"], ["freight_rpa_outbound_rpa_unit_runs.id"]), + sa.ForeignKeyConstraint(["schedule_run_id"], ["schedule_runs.id"]), + sa.ForeignKeyConstraint(["source_id"], ["freight_rpa_sources.id"]), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("callback_id", name="uq_freight_rpa_outbound_rpa_unit_runs_callback"), + ) + op.create_index( + "ix_freight_rpa_outbound_rpa_unit_runs_retry_of_id", + "freight_rpa_outbound_rpa_unit_runs", + ["retry_of_id"], + unique=False, + ) + op.create_index( + "ix_freight_rpa_outbound_rpa_unit_runs_schedule_run_id", + "freight_rpa_outbound_rpa_unit_runs", + ["schedule_run_id"], + unique=False, + ) + op.create_index( + "ix_freight_rpa_outbound_rpa_unit_runs_source_id", + "freight_rpa_outbound_rpa_unit_runs", + ["source_id"], + unique=False, + ) + op.create_index( + "ix_freight_rpa_outbound_unit_run_schedule_status", + "freight_rpa_outbound_rpa_unit_runs", + ["schedule_run_id", "status"], + unique=False, + ) + op.create_index( + "ix_freight_rpa_outbound_unit_run_source_created", + "freight_rpa_outbound_rpa_unit_runs", + ["source_id", "created_at"], + unique=False, + ) + + # [STEP 4] 出站归档文件:含解析失败分层列,不建 notification_deliveries。 + op.create_table( + "freight_rpa_outbound_report_files", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("unit_run_id", sa.Integer(), nullable=False), + sa.Column("storage_provider", sa.String(length=32), nullable=False), + sa.Column("storage_bucket", sa.String(length=128), nullable=False), + sa.Column("storage_key", sa.String(length=1024), nullable=False), + sa.Column("original_filename", sa.String(length=255), nullable=False), + sa.Column("content_type", sa.String(length=128), nullable=True), + sa.Column("file_size", sa.Integer(), nullable=False), + sa.Column("sha256", sa.String(length=64), nullable=False), + sa.Column("parse_failed_at", sa.DateTime(), nullable=True), + sa.Column("parse_error_code", sa.String(length=64), nullable=True), + sa.Column("parse_error_message", sa.Text(), nullable=True), + sa.Column("archive_expires_at", sa.DateTime(), nullable=True), + sa.Column("archive_deleted_at", sa.DateTime(), nullable=True), + sa.Column("archive_delete_result_json", sa.JSON(), nullable=False), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.CheckConstraint("file_size >= 0", name="ck_freight_rpa_outbound_report_files_size"), + sa.ForeignKeyConstraint(["unit_run_id"], ["freight_rpa_outbound_rpa_unit_runs.id"]), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("unit_run_id", "sha256", name="uq_freight_rpa_outbound_report_files_unit_sha256"), + ) + op.create_index( + "ix_freight_rpa_outbound_report_files_expires", + "freight_rpa_outbound_report_files", + ["archive_expires_at", "archive_deleted_at"], + unique=False, + ) + op.create_index( + "ix_freight_rpa_outbound_report_files_unit", + "freight_rpa_outbound_report_files", + ["unit_run_id"], + unique=False, + ) + op.create_index( + "ix_freight_rpa_outbound_report_files_unit_run_id", + "freight_rpa_outbound_report_files", + ["unit_run_id"], + unique=False, + ) + + +def downgrade() -> None: + """Drop outbound tables, then restore the inbound deliveries table structure (empty).""" + op.drop_index( + "ix_freight_rpa_outbound_report_files_unit_run_id", + table_name="freight_rpa_outbound_report_files", + ) + op.drop_index( + "ix_freight_rpa_outbound_report_files_unit", + table_name="freight_rpa_outbound_report_files", + ) + op.drop_index( + "ix_freight_rpa_outbound_report_files_expires", + table_name="freight_rpa_outbound_report_files", + ) + op.drop_table("freight_rpa_outbound_report_files") + + op.drop_index( + "ix_freight_rpa_outbound_unit_run_source_created", + table_name="freight_rpa_outbound_rpa_unit_runs", + ) + op.drop_index( + "ix_freight_rpa_outbound_unit_run_schedule_status", + table_name="freight_rpa_outbound_rpa_unit_runs", + ) + op.drop_index( + "ix_freight_rpa_outbound_rpa_unit_runs_source_id", + table_name="freight_rpa_outbound_rpa_unit_runs", + ) + op.drop_index( + "ix_freight_rpa_outbound_rpa_unit_runs_schedule_run_id", + table_name="freight_rpa_outbound_rpa_unit_runs", + ) + op.drop_index( + "ix_freight_rpa_outbound_rpa_unit_runs_retry_of_id", + table_name="freight_rpa_outbound_rpa_unit_runs", + ) + op.drop_table("freight_rpa_outbound_rpa_unit_runs") + + op.drop_index( + "ix_freight_rpa_outbound_report_configs_source_id", + table_name="freight_rpa_outbound_report_configs", + ) + op.drop_index( + "ix_freight_rpa_outbound_report_configs_parsing_profile_id", + table_name="freight_rpa_outbound_report_configs", + ) + op.drop_table("freight_rpa_outbound_report_configs") + + # 还原投递表结构供降级路径;不回填 Task 2 之后的投递行。 + op.create_table( + _DELIVERIES_TABLE, + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("unit_run_id", sa.Integer(), nullable=True), + sa.Column("report_file_id", sa.Integer(), nullable=True), + sa.Column("recipient_user_id", sa.Integer(), nullable=False), + sa.Column("message_type", sa.String(length=16), nullable=False), + sa.Column("idempotency_key", sa.String(length=255), nullable=False), + sa.Column("status", sa.String(length=16), server_default=sa.text("'pending'"), nullable=False), + sa.Column("response_summary_json", sa.JSON(), server_default=sa.text("'{}'"), nullable=False), + sa.Column("error_code", sa.String(length=64), nullable=True), + sa.Column("error_message", sa.Text(), nullable=True), + sa.Column("sent_at", sa.DateTime(), nullable=True), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.Column("updated_at", sa.DateTime(), nullable=False), + sa.CheckConstraint( + "message_type IN ('file', 'summary')", + name="ck_freight_rpa_inbound_notification_deliveries_type", + ), + sa.CheckConstraint( + "status IN ('pending', 'sending', 'success', 'failed')", + name="ck_freight_rpa_inbound_notification_deliveries_status", + ), + sa.ForeignKeyConstraint(["unit_run_id"], ["freight_rpa_inbound_rpa_unit_runs.id"]), + sa.ForeignKeyConstraint(["report_file_id"], ["freight_rpa_inbound_report_files.id"]), + sa.ForeignKeyConstraint(["recipient_user_id"], ["users.id"]), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint( + "idempotency_key", + name="uq_freight_rpa_inbound_notification_deliveries_idempotency", + ), + ) + op.create_index( + "ix_fr_inbound_notif_deliveries_recipient_user_id", + _DELIVERIES_TABLE, + ["recipient_user_id"], + unique=False, + ) + op.create_index( + "ix_shipping_receipt_delivery_file_recipient", + _DELIVERIES_TABLE, + ["report_file_id", "recipient_user_id"], + unique=False, + ) + op.create_index( + "ix_shipping_receipt_delivery_unit_created", + _DELIVERIES_TABLE, + ["unit_run_id", "created_at"], + unique=False, + ) diff --git a/backend/migrations/versions/tt10a1b2c3d4e_transfer_type_configs.py b/backend/migrations/versions/tt10a1b2c3d4e_transfer_type_configs.py new file mode 100644 index 00000000..6c64fcd4 --- /dev/null +++ b/backend/migrations/versions/tt10a1b2c3d4e_transfer_type_configs.py @@ -0,0 +1,57 @@ +"""transfer_type_configs 建表并移除 transfer_runs 类型枚举 CHECK + +Revision ID: tt10a1b2c3d4e +Revises: b7a2b2155155 +Create Date: 2026-10-14 12:00:00.000000 + +用途:调拨类型配置化(ADR 0002)第一步:新建 transfer_type_configs(编码/ + 四语言名称/启停/排序 + 范围规则/仓库定义/转换规则);同时移除 + transfer_runs.transfer_type 的枚举 CHECK 约束(类型合法性此后由配置表 + 校验,服务层接线由后续任务完成)。 +依赖:b7a2b2155155 为实施时 flask db heads 显示的实际 head(已确认单 head)。 +逻辑:新表与 ORM 模型 TransferTypeConfig 同构(uq_transfer_type_configs_code + 唯一,JSON 列沿用本目录惯例不带 server_default);transfer_type 列本身 + 保留不动,仅去 CHECK;downgrade 按 tt3d4e5f6a7b 原始字面量重建 CHECK, + 保证回滚零漂移。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'tt10a1b2c3d4e' +down_revision = 'b7a2b2155155' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """建类型配置表;移除 transfer_runs.transfer_type 枚举 CHECK(列保留)。""" + op.create_table( + 'transfer_type_configs', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('code', sa.String(length=64), nullable=False), + sa.Column('names_json', sa.JSON(), nullable=False), + sa.Column('enabled', sa.Boolean(), nullable=False, server_default=sa.false()), + sa.Column('sort_order', sa.Integer(), nullable=False, server_default='0'), + sa.Column('scope_rules_json', sa.JSON(), nullable=False), + sa.Column('warehouse_config_json', sa.JSON(), nullable=False), + sa.Column('transform_rules_json', sa.JSON(), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('created_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('updated_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.UniqueConstraint('code', name='uq_transfer_type_configs_code'), + ) + op.drop_constraint('ck_transfer_runs_transfer_type', 'transfer_runs', type_='check') + + +def downgrade() -> None: + """回滚:删配置表;按 tt3d4e5f6a7b 原始字面量重建 transfer_type CHECK。""" + op.drop_table('transfer_type_configs') + op.create_check_constraint( + 'ck_transfer_runs_transfer_type', + 'transfer_runs', + "transfer_type IN ('in_transit_to_hub', 'hub_repair_out', 'hub_to_hub')", + ) diff --git a/backend/migrations/versions/tt11b2c3d4e5f_transfer_movement_ledger.py b/backend/migrations/versions/tt11b2c3d4e5f_transfer_movement_ledger.py new file mode 100644 index 00000000..8ae90011 --- /dev/null +++ b/backend/migrations/versions/tt11b2c3d4e5f_transfer_movement_ledger.py @@ -0,0 +1,106 @@ +"""transfer_movement_ledger 库存异动档建表 + +Revision ID: tt11b2c3d4e5f +Revises: tt10a1b2c3d4e +Create Date: 2026-10-14 14:00:00.000000 + +用途:库存异动档(ADR 0001,规格 §4.2)第一步:新建 transfer_movement_ledger—— + 外部系统收料/出货记录的平台镜像;本期收料全量落档,出货侧结构与模型就位 + (record_kind='shipment' + 🔖预留列),匹配明细改为匹配时从档圈定。 +依赖:tt10a1b2c3d4e 为实施时 flask db heads 显示的实际 head(已确认单 head)。 +逻辑:新表与 ORM 模型 TransferMovementLedger 同构——自然键六成分 + (source_code, record_kind, doc_no, line_no, line_seq, in_out_flag) 全部 + NOT NULL(可空成分 server_default '')+ uq_transfer_movement_ledger_ + natural_key 唯一(幂等增量落地);业务/证据列一律 nullable(外部列宽松 + 落地,movement_date 可空=不进收料日期圈定);source_file_id FK + ON DELETE SET NULL(来源文件清理后档事实留存);transfer_executed + 封存位 default false(已执行记录防二次调拨)。索引两条: + 圈档主路径 (source_code, record_kind, movement_date) 与封存扫描 + (record_kind, transfer_executed)。D15 无存量数据,无回填。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'tt11b2c3d4e5f' +down_revision = 'tt10a1b2c3d4e' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """建库存异动档表与两条索引(与 TransferMovementLedger 模型同构)。""" + op.create_table( + 'transfer_movement_ledger', + # A 单据标识(自然键成分,NOT NULL;可空成分 default '') + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('doc_no', sa.String(length=64), nullable=False), + sa.Column('line_no', sa.String(length=32), nullable=False), + sa.Column('line_seq', sa.String(length=32), nullable=False, server_default=''), + sa.Column('in_out_flag', sa.String(length=8), nullable=False, server_default=''), + # B 物料与数量(数量 Decimal 文本,与 transfer_invoice_items.receipt_quantity 同约定) + sa.Column('material_code', sa.String(length=64), nullable=True), + sa.Column('material_name', sa.String(length=200), nullable=True), + sa.Column('specification', sa.String(length=200), nullable=True), + sa.Column('lot_no', sa.String(length=64), nullable=True), + sa.Column('quantity', sa.String(length=40), nullable=True), + sa.Column('unit', sa.String(length=32), nullable=True), + # C 仓储与日期(movement_date 可空:空值记录照常落档,不进收料日期圈定) + sa.Column('warehouse_code', sa.String(length=64), nullable=True), + sa.Column('storage_code', sa.String(length=64), nullable=True), + sa.Column('movement_date', sa.String(length=16), nullable=True), + # D 业务属性(⭐本期新增强业务字段;🔖预留列,nullable,出货侧直接映射) + sa.Column('order_type', sa.String(length=64), nullable=True), + sa.Column('odm_id', sa.String(length=64), nullable=True), + sa.Column('odm_name', sa.String(length=128), nullable=True), + sa.Column('carton_id', sa.String(length=64), nullable=True), + sa.Column('pallet_id', sa.String(length=64), nullable=True), + sa.Column('doc_nature', sa.String(length=64), nullable=True), + sa.Column('movement_type', sa.String(length=64), nullable=True), + sa.Column('reason_code', sa.String(length=32), nullable=True), + sa.Column('source_ref_no', sa.String(length=64), nullable=True), + sa.Column('partner_code', sa.String(length=64), nullable=True), + sa.Column('remark', sa.Text(), nullable=True), + # E 平台溯源(证据字段:evidence_sync 原行更新时整体换新) + sa.Column('source_code', sa.String(length=64), nullable=False), + sa.Column('record_kind', sa.String(length=16), nullable=False), + sa.Column( + 'source_file_id', sa.Integer(), + sa.ForeignKey('shipping_receipt_report_files.id', ondelete='SET NULL'), + nullable=True, + ), + sa.Column('file_version', sa.String(length=64), nullable=True), + sa.Column('file_sha256', sa.String(length=64), nullable=True), + sa.Column('sheet_name', sa.String(length=128), nullable=True), + sa.Column('row_no', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + # F 平台回写(档级封存:票据执行成功落单号时回写,永不解除) + sa.Column('transfer_executed', sa.Boolean(), nullable=False, server_default=sa.false()), + sa.Column('executed_doc_no', sa.String(length=64), nullable=True), + # 自然键唯一(幂等增量落地兜底) + sa.UniqueConstraint( + 'source_code', 'record_kind', 'doc_no', 'line_no', 'line_seq', 'in_out_flag', + name='uq_transfer_movement_ledger_natural_key', + ), + ) + # 匹配创建圈档主路径:来源 + 记录种类 + 收料日期范围扫描。 + op.create_index( + 'ix_transfer_movement_ledger_source_kind_date', + 'transfer_movement_ledger', + ['source_code', 'record_kind', 'movement_date'], + ) + # 档级封存/待匹配桶扫描:按记录种类过滤已执行位。 + op.create_index( + 'ix_transfer_movement_ledger_kind_executed', + 'transfer_movement_ledger', + ['record_kind', 'transfer_executed'], + ) + + +def downgrade() -> None: + """回滚:删索引与档表(D15 无存量数据,直接 drop 零损失)。""" + op.drop_index('ix_transfer_movement_ledger_kind_executed', table_name='transfer_movement_ledger') + op.drop_index('ix_transfer_movement_ledger_source_kind_date', table_name='transfer_movement_ledger') + op.drop_table('transfer_movement_ledger') diff --git a/backend/migrations/versions/tt12c3d4e5f6a7_item_ledger_record_fk.py b/backend/migrations/versions/tt12c3d4e5f6a7_item_ledger_record_fk.py new file mode 100644 index 00000000..0580b68b --- /dev/null +++ b/backend/migrations/versions/tt12c3d4e5f6a7_item_ledger_record_fk.py @@ -0,0 +1,57 @@ +"""transfer_invoice_items 加 ledger_record_id 外键(匹配出生翻转) + +Revision ID: tt12c3d4e5f6a7 +Revises: tt11b2c3d4e5f +Create Date: 2026-10-14 16:00:00.000000 + +用途:匹配明细出生翻转(ADR 0001/D4,规格 §4.3)——transfer_invoice_items 增 + ledger_record_id FK → transfer_movement_ledger.id(nullable + 索引):行由 + 匹配创建时从档圈定生成,ledger_record_id 指向来源档记录(业务字段=档原值)。 + 可空语义:隔离的历史行允许 NULL(D15 无存量数据,本列为纯前瞻结构)。 +依赖:tt11b2c3d4e5f 为实施时 flask db heads 显示的实际 head(已确认单 head)。 +逻辑:加列(nullable,不强制 NOT NULL——存量兼容,服务层保证新行恒非空)+ + 单列索引 ix_transfer_invoice_items_ledger_record_id(D17 圈档互斥的 + 「按档记录查占用行」高频检查走索引)。D15 无存量数据,无回填。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'tt12c3d4e5f6a7' +down_revision = 'tt11b2c3d4e5f' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """加 ledger_record_id FK 列与占用互斥检查索引(与模型同构)。 + + batch_alter_table:PostgreSQL(目标环境)渲染为普通 ALTER TABLE; + SQLite(本地/测试)经 copy-and-move 支持 ADD COLUMN 带 FK 约束。 + """ + with op.batch_alter_table("transfer_invoice_items") as batch_op: + batch_op.add_column( + sa.Column( + "ledger_record_id", sa.Integer(), + # 显式命名 FK:batch 模式(SQLite copy-and-move)要求约束具名; + # PostgreSQL 渲染为命名 ADD CONSTRAINT。 + sa.ForeignKey( + "transfer_movement_ledger.id", + name="fk_transfer_invoice_items_ledger_record_id", + ), + nullable=True, + ), + ) + op.create_index( + "ix_transfer_invoice_items_ledger_record_id", + "transfer_invoice_items", + ["ledger_record_id"], + ) + + +def downgrade() -> None: + """回滚:删索引与列(D15 无存量数据,直接 drop 零损失)。""" + op.drop_index("ix_transfer_invoice_items_ledger_record_id", table_name="transfer_invoice_items") + with op.batch_alter_table("transfer_invoice_items") as batch_op: + batch_op.drop_column("ledger_record_id") diff --git a/backend/migrations/versions/tt13d4e5f6a7b8_widen_transfer_run_type.py b/backend/migrations/versions/tt13d4e5f6a7b8_widen_transfer_run_type.py new file mode 100644 index 00000000..75da6a52 --- /dev/null +++ b/backend/migrations/versions/tt13d4e5f6a7b8_widen_transfer_run_type.py @@ -0,0 +1,56 @@ +"""transfer_runs.transfer_type 列宽放宽 String(32) → String(64) + +Revision ID: tt13d4e5f6a7b8 +Revises: tt12c3d4e5f6a7 +Create Date: 2026-10-14 23:50:00.000000 + +用途:终审 I2 修复——消除「类型配置 code 与 Run 落库列宽」错位:配置表 + transfer_type_configs.code 允许 ≤64 字符(正则 ^[a-z][a-z0-9_]{1,63}$), + 而 transfer_runs.transfer_type 只有 String(32)——33~64 字符的 code 一旦建 + 匹配,Run 写入即超长(SQLite 静默截断 / PostgreSQL 直接 500)。 +依赖:tt12c3d4e5f6a7 为实施时 flask db heads 显示的实际单 head(已确认)。 +逻辑:alter_column 放宽到 String(64);nullable=False 与 server_default + 'in_transit_to_hub' 保持建列(tt3d4e5f6a7b)初值不变——默认值是上线 SOP + 的依赖(配置为空时 Run 默认归「在途仓至HUB仓」,规格 §7)。batch 模式下 + PostgreSQL 渲染为普通 ALTER TYPE(varchar 放宽为元数据级变更,不重写表), + SQLite(本地/测试)经 copy-and-move 重建,故两侧都显式传 server_default + 防默认值丢失;downgrade 收回 32(回滚前须确认无 >32 字符 code 的存量 Run, + 否则 PG 收窄会截断报错——fail-closed 可接受)。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = 'tt13d4e5f6a7b8' +down_revision = 'tt12c3d4e5f6a7' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """transfer_runs.transfer_type 放宽至 String(64)(与配置表 code 上限对齐)。""" + with op.batch_alter_table("transfer_runs") as batch_op: + batch_op.alter_column( + "transfer_type", + existing_type=sa.String(length=32), + type_=sa.String(length=64), + existing_nullable=False, + nullable=False, + # SQLite copy-and-move 重建表时 server_default 必须显式携带,否则丢失; + # PostgreSQL 渲染为等值 SET DEFAULT(幂等无害)。 + server_default='in_transit_to_hub', + ) + + +def downgrade() -> None: + """回滚:收回 String(32)(tt3d4e5f6a7b 建列字面量;server_default 同步保持)。""" + with op.batch_alter_table("transfer_runs") as batch_op: + batch_op.alter_column( + "transfer_type", + existing_type=sa.String(length=64), + type_=sa.String(length=32), + existing_nullable=False, + nullable=False, + server_default='in_transit_to_hub', + ) diff --git a/backend/migrations/versions/tt14a5f6a7b8c9_inbound_rename_and_ledger_key.py b/backend/migrations/versions/tt14a5f6a7b8c9_inbound_rename_and_ledger_key.py new file mode 100644 index 00000000..52aeb7a3 --- /dev/null +++ b/backend/migrations/versions/tt14a5f6a7b8c9_inbound_rename_and_ledger_key.py @@ -0,0 +1,89 @@ +"""tt14 入站化:receipt_* 列更名 movement_*、record_kind 值迁移、自然键扩 8 成分 + +Revision ID: tt14a5f6a7b8c9 +Revises: mh15f6a7b8c9 +Create Date: 2026-10-15 10:00:00.000000 + +用途:落实 spec D1/D6——真实 WMS 文件行身份是「单据+行+箱/批」,自然键扩 + carton_id+lot_no;receipt 说辞一次性更名(无兼容层)。明细/单据列是方向 + 中立(出站调拨同样产生明细),按控制器裁决用 movement_*(与异动档 + transfer_movement_ledger.movement_date 命名对齐),不用 inbound_*。 +依赖:mh15f6a7b8c9 为实施时 flask db heads 显示的实际单 head(并行会话已把 + eah8c9d0e1f2 与 tt13d4e5f6a7b8 合并,本迁移链接其后避免双头)。 +逻辑:batch_alter_table 完成 RENAME(PG/SQLite 双兼容);record_kind 值迁移为 + 数据 UPDATE(未上线为空操作,test 环境兜底);唯一约束按 8 成分重建, + 进键维度列 carton_id/lot_no 同步 NOT NULL + default ''(R7 终审:nullable + 成分的 NULL 不参与唯一比对会逃逸约束;落档链路恒写 '',无存量 NULL)。 + 列类型取自建表迁移(it1a2b3c4d5e/it2c3d4e5f6a7/tt0d1e2f3a4b)逐一核对。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = "tt14a5f6a7b8c9" +down_revision = "mh15f6a7b8c9" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """receipt_* 列更名 movement_*、record_kind 值迁移 receipt→inbound、自然键扩 8 成分。""" + with op.batch_alter_table("transfer_invoice_items") as batch: + batch.alter_column("receipt_date", new_column_name="movement_date", + existing_type=sa.String(length=16), existing_nullable=True) + batch.alter_column("receipt_quantity", new_column_name="movement_quantity", + existing_type=sa.String(length=40), existing_nullable=False) + batch.alter_column("receipt_warehouse_code", new_column_name="movement_warehouse_code", + existing_type=sa.String(length=64), existing_nullable=False) + with op.batch_alter_table("transfer_documents") as batch: + batch.alter_column("receipt_date", new_column_name="movement_date", + existing_type=sa.String(length=16), existing_nullable=False) + op.execute("UPDATE transfer_movement_ledger SET record_kind='inbound' WHERE record_kind='receipt'") + op.execute("UPDATE transfer_movement_ledger SET record_kind='outbound' WHERE record_kind='shipment'") + with op.batch_alter_table("transfer_movement_ledger") as batch: + # R7(终审修复):carton_id/lot_no 进键即 NOT NULL + default ''——nullable + # 成分在 PG/SQLite 唯一比对中 NULL≠NULL,会逃逸唯一约束(同箱同批塌缩)。 + # 落档链路恒写 '',无存量 NULL(未上线),SET NOT NULL 安全。 + batch.alter_column("carton_id", existing_type=sa.String(length=64), + nullable=False, server_default='', existing_server_default=None) + batch.alter_column("lot_no", existing_type=sa.String(length=64), + nullable=False, server_default='', existing_server_default=None) + batch.drop_constraint("uq_transfer_movement_ledger_natural_key", type_="unique") + batch.create_unique_constraint( + "uq_transfer_movement_ledger_natural_key", + ["source_code", "record_kind", "doc_no", "line_no", "line_seq", + "in_out_flag", "carton_id", "lot_no"], + ) + + +def downgrade() -> None: + """回滚:自然键收回 6 成分、维度列还原可空无默认、record_kind 值还原、列名还原。 + + 注意:收窄为 6 成分唯一约束时,要求不存在同 6 元组异 carton/lot 并存数据, + 否则约束重建 IntegrityError(固有语义,非缺陷——6 成分键本就无法区分同键多箱/批)。 + """ + with op.batch_alter_table("transfer_movement_ledger") as batch: + # 对称还原 tt14 upgrade:server_default=None 渲染 DROP DEFAULT(PG),SQLite + # batch 重建表时不携带默认值(alembic 1.19 语义,False=不动、None=移除)。 + batch.alter_column("carton_id", existing_type=sa.String(length=64), + nullable=True, server_default=None, existing_server_default='') + batch.alter_column("lot_no", existing_type=sa.String(length=64), + nullable=True, server_default=None, existing_server_default='') + batch.drop_constraint("uq_transfer_movement_ledger_natural_key", type_="unique") + batch.create_unique_constraint( + "uq_transfer_movement_ledger_natural_key", + ["source_code", "record_kind", "doc_no", "line_no", "line_seq", "in_out_flag"], + ) + op.execute("UPDATE transfer_movement_ledger SET record_kind='receipt' WHERE record_kind='inbound'") + op.execute("UPDATE transfer_movement_ledger SET record_kind='shipment' WHERE record_kind='outbound'") + with op.batch_alter_table("transfer_documents") as batch: + batch.alter_column("movement_date", new_column_name="receipt_date", + existing_type=sa.String(length=16), existing_nullable=False) + with op.batch_alter_table("transfer_invoice_items") as batch: + batch.alter_column("movement_date", new_column_name="receipt_date", + existing_type=sa.String(length=16), existing_nullable=True) + batch.alter_column("movement_quantity", new_column_name="receipt_quantity", + existing_type=sa.String(length=40), existing_nullable=False) + batch.alter_column("movement_warehouse_code", new_column_name="receipt_warehouse_code", + existing_type=sa.String(length=64), existing_nullable=False) diff --git a/backend/migrations/versions/tt15b6a7b8c9d0_parsing_purpose_onhand_inbound_outbound.py b/backend/migrations/versions/tt15b6a7b8c9d0_parsing_purpose_onhand_inbound_outbound.py new file mode 100644 index 00000000..874862e2 --- /dev/null +++ b/backend/migrations/versions/tt15b6a7b8c9d0_parsing_purpose_onhand_inbound_outbound.py @@ -0,0 +1,66 @@ +"""tt15 purpose 枚举改版:inventory/movement → onhand/inbound/outbound + +Revision ID: tt15b6a7b8c9d0 +Revises: tt14a5f6a7b8c9 +Create Date: 2026-10-15 12:00:00.000000 + +用途:通用文件解析规则表 shipping_inventory_parsing_profiles.purpose 由二值 + (inventory / movement)扩为方向化三元枚举(onhand / inbound / outbound): + onhand=在手库存文件(原 inventory),inbound=入站收料文件(原 movement), + outbound=出站文件(结构就位,暂无运行时消费方)。 +依赖:tt14a5f6a7b8c9 为实施时 flask db heads 显示的实际单 head;purpose 列与旧 + CHECK 由 b17e3d4c5a60 / if1b2c3d4e5g 建立。 +逻辑:四个操作按序执行——DROP 旧 CHECK → 数据 UPDATE(inventory→onhand、 + movement→inbound)→ ADD 新 CHECK → SET DEFAULT 'onhand'。SQLite 不支持裸 + ALTER TABLE DROP CONSTRAINT / ALTER COLUMN SET DEFAULT,故 DDL 全部走 + batch_alter_table(batch 重建表,SQLite 往返可执行),PG 端渲染等价于裸 + ALTER 语句;数据 UPDATE 用 op.execute 独立执行(不进 batch)。 + downgrade 对称:outbound 行无 1:1 旧值,迁移到 'movement'(结构就位语义最接近)。 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = "tt15b6a7b8c9d0" +down_revision = "tt14a5f6a7b8c9" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + """purpose 枚举改版:换 CHECK、迁移存量值、default 置 'onhand'。""" + with op.batch_alter_table("shipping_inventory_parsing_profiles") as batch: + batch.drop_constraint( + "ck_shipping_inventory_parsing_profiles_purpose", type_="check", + ) + op.execute("UPDATE shipping_inventory_parsing_profiles SET purpose='onhand' WHERE purpose='inventory'") + op.execute("UPDATE shipping_inventory_parsing_profiles SET purpose='inbound' WHERE purpose='movement'") + with op.batch_alter_table("shipping_inventory_parsing_profiles") as batch: + batch.create_check_constraint( + "ck_shipping_inventory_parsing_profiles_purpose", + "purpose IN ('onhand', 'inbound', 'outbound')", + ) + batch.alter_column( + "purpose", existing_type=sa.String(length=16), existing_nullable=False, + server_default="onhand", existing_server_default="inventory", + ) + + +def downgrade() -> None: + """回滚:default 还原 'inventory'、换回旧 CHECK,存量值对称还原(outbound→movement)。""" + with op.batch_alter_table("shipping_inventory_parsing_profiles") as batch: + batch.drop_constraint( + "ck_shipping_inventory_parsing_profiles_purpose", type_="check", + ) + batch.alter_column( + "purpose", existing_type=sa.String(length=16), existing_nullable=False, + server_default="inventory", existing_server_default="onhand", + ) + op.execute("UPDATE shipping_inventory_parsing_profiles SET purpose='inventory' WHERE purpose='onhand'") + op.execute("UPDATE shipping_inventory_parsing_profiles SET purpose='movement' WHERE purpose IN ('inbound', 'outbound')") + with op.batch_alter_table("shipping_inventory_parsing_profiles") as batch: + batch.create_check_constraint( + "ck_shipping_inventory_parsing_profiles_purpose", + "purpose IN ('inventory', 'movement')", + ) diff --git a/backend/migrations/versions/tt16a7b8c9d0e1f2_retire_not_matured_item_status.py b/backend/migrations/versions/tt16a7b8c9d0e1f2_retire_not_matured_item_status.py new file mode 100644 index 00000000..551fe44c --- /dev/null +++ b/backend/migrations/versions/tt16a7b8c9d0e1f2_retire_not_matured_item_status.py @@ -0,0 +1,62 @@ +"""retire not_matured item status (maturity concept removal 2026-10-16) + +Revision ID: tt16a7b8c9d0e1f2 +Revises: tt15b6a7b8c9d0 +Create Date: 2026-10-16 + +用途:「成熟」概念退役(用户裁定:数据无成熟属性,日期边界由调用方入参严格 + 给定)——transfer_invoice_items.status 冻结枚举删去 'not_matured' + (13 态 → 12 态),CHECK 约束 ck_transfer_invoice_items_status 同步重建。 +数据迁移:存量 not_matured 行重映射为 'cancelled'(语义最近=未进入执行且不再 + 可执行;D17 占用过滤本就排除 cancelled,占用随之自然释放)。result_code + 保留历史值 'not_matured' 不改写(无约束的自由文本,留审计溯源)。 +降级:仅重建旧 CHECK(含 not_matured);已重映射的行无法还原原状态(dev 数据, + 有损降级,docstring 如实声明)。 +依赖:无数据依赖;与 tt14/tt15 并行域迁移同链(单 head 顺序 tt14→tt15→tt16)。 +""" + +from alembic import op + +revision = 'tt16a7b8c9d0e1f2' +down_revision = 'tt15b6a7b8c9d0' +branch_labels = None +depends_on = None + +# 12 态枚举(与 app.models.in_transit_transfer.TRANSFER_ITEM_STATUSES 同步; +# 迁移文件不 import 应用模型,避免迁移期模型漂移牵连)。 +_ITEM_STATUSES_V12 = ( + 'file_pending', 'file_ready', 'matching', 'ready_to_execute', 'executing', + 'success', 'duplicate_success', 'blocked_recoverable', + 'result_unknown', 'manually_closed', 'cancelled', 'notification_failed', +) +_ITEM_STATUSES_V13 = ('not_matured',) + _ITEM_STATUSES_V12[:8] + _ITEM_STATUSES_V12[8:] + + +def _statuses_sql(statuses: tuple[str, ...]) -> str: + return ', '.join(repr(s) for s in statuses) + + +def upgrade() -> None: + # [STEP 1] 存量 not_matured 行重映射 cancelled(必须先于 CHECK 重建,否则 + # 旧值撞新约束);占用释放由 D17 占用过滤排除 cancelled 自然达成。 + op.execute( + "UPDATE transfer_invoice_items SET status = 'cancelled' " + "WHERE status = 'not_matured'" + ) + # [STEP 2] CHECK 重建:旧约束 → 12 态新约束。 + op.drop_constraint('ck_transfer_invoice_items_status', 'transfer_invoice_items', type_='check') + op.create_check_constraint( + 'ck_transfer_invoice_items_status', + 'transfer_invoice_items', + f"status IN ({_statuses_sql(_ITEM_STATUSES_V12)})", + ) + + +def downgrade() -> None: + # [STEP 1] CHECK 回退到 13 态(已重映射的 cancelled 行无法识别还原,有损降级)。 + op.drop_constraint('ck_transfer_invoice_items_status', 'transfer_invoice_items', type_='check') + op.create_check_constraint( + 'ck_transfer_invoice_items_status', + 'transfer_invoice_items', + f"status IN ({_statuses_sql(_ITEM_STATUSES_V13)})", + ) diff --git a/backend/migrations/versions/tt16c7d8e9f0a1b2_rename_freight_rpa_job_keys.py b/backend/migrations/versions/tt16c7d8e9f0a1b2_rename_freight_rpa_job_keys.py new file mode 100644 index 00000000..dff99daa --- /dev/null +++ b/backend/migrations/versions/tt16c7d8e9f0a1b2_rename_freight_rpa_job_keys.py @@ -0,0 +1,54 @@ +"""tt16:RPA 排程任务 key 更名(批次 R,随代码同窗口发布) + +Revision ID: tt16c7d8e9f0a1b2 +Revises: tt16a7b8c9d0e1f2 +Create Date: 2026-10-16 + +用途:schedule_tasks.platform_api_path 存量的三个 RPA 平台 job key 入站化改名—— + shipping-inventory-rpa→freight-rpa-onhand(在手/库存)、 + freight-receipt-rpa→freight-rpa-inbound(入站/收料)、 + freight-receipt-rpa-retention→freight-rpa-inbound-retention(入站归档保留期清理), + 与 job_registry.py / freight_rpa_onhand_*、freight_rpa_inbound_* 排程壳改名同窗口发布。 +依赖:实施时 flask db heads 的单 head 为 tt16a7b8c9d0e1f2(调拨域迁移,其上游即 + tt15b6a7b8c9d0);本迁移若直挂 tt15 会产生双 head,故按单 head 纪律链在其上。 +逻辑:列为 platform_api_path(String(500),承载归一化 job key——自 b9c0d1e2f3a4 起 + 排程表无独立 job_key 列,运行时一律读写 platform_api_path,见 + schedule_contract.normalize_job_key);三键 UPDATE; + options_source 键(shipping_inventory_sources / shipping_receipt_sources) + 绑定业务表名,本批不动(批次 S)。 +降级:反向映射对称 UPDATE,逐键还原;无表结构变更,SQLite/PG 语句通用。 +Fix round 1:SQL 列名由计划骨架误写的 job_key 修正为真实列 platform_api_path + (计划骨架错误,控制方已认领;契约测试桩表同步改真实列名)。 +""" + +from alembic import op + +revision = "tt16c7d8e9f0a1b2" +down_revision = "tt16a7b8c9d0e1f2" +branch_labels = None +depends_on = None + +# 升级方向三键对照;downgrade 取反。键值与 job_registry.register_platform_job 一致。 +_MAPPING = { + "shipping-inventory-rpa": "freight-rpa-onhand", + "freight-receipt-rpa": "freight-rpa-inbound", + "freight-receipt-rpa-retention": "freight-rpa-inbound-retention", +} + + +def upgrade() -> None: + """job key 三键前向改名:platform_api_path 旧行 UPDATE 为新键(无表结构变更)。""" + for old_key, new_key in _MAPPING.items(): + op.execute( + f"UPDATE schedule_tasks SET platform_api_path='{new_key}' " + f"WHERE platform_api_path='{old_key}'" + ) + + +def downgrade() -> None: + """job key 三键反向还原:platform_api_path 新键 UPDATE 回旧键(与 upgrade 对称)。""" + for old_key, new_key in _MAPPING.items(): + op.execute( + f"UPDATE schedule_tasks SET platform_api_path='{old_key}' " + f"WHERE platform_api_path='{new_key}'" + ) diff --git a/backend/migrations/versions/tt21c8d9e0f1a2_ledger_external_doc_line_natural_key.py b/backend/migrations/versions/tt21c8d9e0f1a2_ledger_external_doc_line_natural_key.py new file mode 100644 index 00000000..ae341564 --- /dev/null +++ b/backend/migrations/versions/tt21c8d9e0f1a2_ledger_external_doc_line_natural_key.py @@ -0,0 +1,52 @@ +"""transfer_movement_ledger 增加外部单号/外部项次并扩自然键唯一约束(2026-10-21) + +Revision ID: tt21c8d9e0f1a2 +Revises: s19a0b1c2d3e4 +Create Date: 2026-10-21 + +用途:库存异动档新增外部单据身份两列(external_doc_no/external_line_no,对应 + CRANE/Lognet 出站报告的 WMS Order #/行号),并把两列加入自然键唯一约束 + uq_transfer_movement_ledger_natural_key(8→10 成分)——外部单号+项次作为 + 档幂等主键管控:同一外部单号+项次的重复落档/证据更新收敛到同一档行。 +依赖:movement_contract.MOVEMENT_FIELDS 追加同名契约字段(模型列 1:1 镜像断言 + 在 ledger_sync 导入期 fail-fast)。 +逻辑:两列 NOT NULL + server_default ''(自然键可空成分以空串参与唯一比对, + 防 PG NULL 逃逸);约束先删后建(PG/SQLite 通用)。存量行两列填默认空串 + 参与键;来源配置外部映射后重放同文件即按新键收敛,必要时走「清空并重解析」 + 重建(backlog_reparse_service)。 +""" +from alembic import op +import sqlalchemy as sa + +# revision identifiers, used by Alembic. +revision = "tt21c8d9e0f1a2" +down_revision = "s19a0b1c2d3e4" +branch_labels = None +depends_on = None + +_TABLE = "transfer_movement_ledger" +_NATURAL_KEY = "uq_transfer_movement_ledger_natural_key" +_NATURAL_KEY_COLUMNS = ( + "source_code", "record_kind", "doc_no", "line_no", "line_seq", "in_out_flag", + "carton_id", "lot_no", "external_doc_no", "external_line_no", +) + + +def upgrade() -> None: + """加两列(NOT NULL + server_default '',存量行回填空串)并扩自然键唯一约束。""" + op.add_column(_TABLE, sa.Column("external_doc_no", sa.String(64), nullable=False, server_default="")) + op.add_column(_TABLE, sa.Column("external_line_no", sa.String(32), nullable=False, server_default="")) + op.drop_constraint(_NATURAL_KEY, _TABLE, type_="unique") + op.create_unique_constraint(_NATURAL_KEY, _TABLE, list(_NATURAL_KEY_COLUMNS)) + + +def downgrade() -> None: + """回退:恢复 8 成分唯一约束并删两列(外部身份列数据随列删除,不留残档)。""" + op.drop_constraint(_NATURAL_KEY, _TABLE, type_="unique") + op.create_unique_constraint( + _NATURAL_KEY, _TABLE, + ["source_code", "record_kind", "doc_no", "line_no", "line_seq", "in_out_flag", + "carton_id", "lot_no"], + ) + op.drop_column(_TABLE, "external_line_no") + op.drop_column(_TABLE, "external_doc_no") diff --git a/backend/scripts/_perf_summary_tmp.py b/backend/scripts/_perf_summary_tmp.py new file mode 100644 index 00000000..70957fbf --- /dev/null +++ b/backend/scripts/_perf_summary_tmp.py @@ -0,0 +1,22 @@ +"""[DEBUG-perf1] 首页 /summary 计时基线(临时,诊断后删除)。""" +from time import perf_counter + +from app import create_app +from app.services.in_transit_transfer.backlog_service import ( + _pending_match_counts, + backlog_summary, + list_backlog, +) + +app = create_app() +with app.app_context(): + t0 = perf_counter() + items = list_backlog() + t1 = perf_counter() + pm, m = _pending_match_counts() + t2 = perf_counter() + s = backlog_summary() + t3 = perf_counter() + print(f"[DEBUG-perf1] list_backlog rows={len(items)}: {t1 - t0:.2f}s") + print(f"[DEBUG-perf1] _pending_match_counts pending={pm} matchable={m}: {t2 - t1:.2f}s") + print(f"[DEBUG-perf1] backlog_summary total: {t3 - t2:.2f}s (pending={s.pending_match_count}, matchable={s.matchable_count})") diff --git a/backend/scripts/import_shipping_inventory_sources.py b/backend/scripts/import_shipping_inventory_sources.py deleted file mode 100644 index 27f4343c..00000000 --- a/backend/scripts/import_shipping_inventory_sources.py +++ /dev/null @@ -1,165 +0,0 @@ -"""Import legacy YAML inventory sources into the shipping configuration database. - -Purpose: migrate business report paths, query inputs, aliases, and warehouse policies from -``config/shipping_inventory_sources.yaml`` into the new source master data. -Dependencies: Flask app context, SQLAlchemy models, PyYAML. -Flow: reuses connections by platform and login URL, keeps all imported sources disabled, and -never imports YAML selectors or credentials because those are worker implementation/secrets. -""" - -from __future__ import annotations - -import argparse -from pathlib import Path -from typing import Any - -import yaml - -from app import create_app -from app.extensions import db -from app.models import ShippingInventorySource, ShippingRpaProfile - - -CONNECTOR_TYPES = {"dsv360": "dbs", "crane_footprint": "crane"} - - -def _source_payload(raw: dict[str, Any]) -> dict[str, Any]: - """Convert one legacy source while excluding worker-only selector configuration. - - Args: - raw: A source item from the legacy YAML document. - - Returns: - Normalized source fields suitable for ``ShippingInventorySource``. - """ - connector_type = CONNECTOR_TYPES.get(str(raw.get("connector_type") or "").strip().lower()) - if connector_type is None: - raise ValueError(f"Unsupported connector_type: {raw.get('connector_type')!r}") - navigation = raw.get("navigation") if isinstance(raw.get("navigation"), dict) else {} - parameters: list[dict[str, Any]] = [] - for parameter in raw.get("parameters") or []: - if not isinstance(parameter, dict): - continue - parameters.append({ - "name": str(parameter.get("name") or "").strip(), - "mode": str(parameter.get("mode") or "single").strip(), - "values": [str(value).strip() for value in parameter.get("values") or [] if str(value).strip()], - "required": bool(parameter.get("required", False)), - "select_all": bool(parameter.get("select_all", False)), - **({"joiner": str(parameter.get("joiner") or ",")} if str(parameter.get("mode") or "") == "multi_text" else {}), - }) - dynamic = str(raw.get("warehouse_resolution") or "").strip() == "alias_match" - return { - "source_code": str(raw["source_code"]).strip().upper(), - "display_name": str(raw.get("display_name") or raw["source_code"]).strip(), - "connector_type": connector_type, - "login_url": str(raw.get("entry_url") or "").strip(), - "warehouse_resolution_mode": "inventory_match" if dynamic else "fixed", - "fixed_warehouse_id": None if dynamic else str(raw.get("warehouse_id") or "").strip() or None, - "report_path_json": ({ - key: str(navigation.get(key) or "").strip() - for key in ("program_group", "program_label", "report_group", "report_name") - } if connector_type == "dbs" else {}), - "query_parameters_json": parameters, - } - - -def _connection_for(source: dict[str, Any]) -> ShippingRpaProfile: - """Return a compatible connection, reusing configured credentials whenever possible.""" - profile = ShippingRpaProfile.query.filter_by( - connector_type=source["connector_type"], login_url=source["login_url"], - ).order_by(ShippingRpaProfile.id).first() - if profile is not None and (profile.username_ciphertext or profile.password_ciphertext): - return profile - # Legacy YAML stores the portal root while a configured DBS connection can use a portal path. - # Prefer an existing credential-bearing platform connection instead of creating an unusable duplicate. - if source["connector_type"] == "dbs": - profile = ShippingRpaProfile.query.filter_by(connector_type="dbs").filter( - (ShippingRpaProfile.username_ciphertext.is_not(None)) | (ShippingRpaProfile.password_ciphertext.is_not(None)) - ).order_by(ShippingRpaProfile.credential_updated_at.desc(), ShippingRpaProfile.id).first() - if profile is not None: - return profile - if profile is not None: - return profile - # The historical Crane connection was initially stored as DBS before source master data existed. - if source["connector_type"] == "crane": - profile = ShippingRpaProfile.query.filter_by(profile_code="CRANE").first() - if profile is not None: - profile.connector_type = "crane" - profile.login_url = source["login_url"] - return profile - code = "DBS_S360" if source["connector_type"] == "dbs" else "CRANE" - profile = ShippingRpaProfile( - profile_code=code, - display_name="DBS 平台" if source["connector_type"] == "dbs" else "Crane 平台", - connector_type=source["connector_type"], - login_url=source["login_url"], - login_config_json={"auth_mode": "password"}, - enabled=True, - ) - db.session.add(profile) - db.session.flush() - return profile - - -def import_sources(path: Path) -> tuple[int, int]: - """Idempotently insert/update YAML source master data with imported rows disabled. - - Returns: - A pair of ``(created, updated)`` counts. - """ - document = yaml.safe_load(path.read_text(encoding="utf-8")) or {} - rows = document.get("sources") if isinstance(document, dict) else None - if not isinstance(rows, list): - raise ValueError("YAML must contain a sources list") - created = updated = 0 - for raw in rows: - if not isinstance(raw, dict): - continue - data = _source_payload(raw) - profile = _connection_for(data) - source = ShippingInventorySource.query.filter_by(source_code=data["source_code"]).first() - if source is None: - source = ShippingInventorySource( - source_code=data["source_code"], display_name=data["display_name"], - connector_type=data["connector_type"], rpa_profile=profile, - warehouse_resolution_mode=data["warehouse_resolution_mode"], enabled=False, - ) - db.session.add(source) - created += 1 - else: - updated += 1 - source.display_name = data["display_name"] - source.connector_type = data["connector_type"] - source.rpa_profile = profile - source.parsing_profile_id = None - source.excel_template_id = None - source.warehouse_resolution_mode = data["warehouse_resolution_mode"] - source.fixed_warehouse_id = data["fixed_warehouse_id"] - source.report_path_json = data["report_path_json"] - source.query_parameters_json = data["query_parameters_json"] - source.snapshot_ttl_seconds = 86400 - # Templates are not present in legacy YAML; activation requires published bindings. - source.enabled = False - db.session.commit() - # A previous run may have created this deterministic placeholder before a configured DBS connection was found. - placeholder = ShippingRpaProfile.query.filter_by(profile_code="DBS_S360").first() - if placeholder and not placeholder.sources and not placeholder.username_ciphertext and not placeholder.password_ciphertext: - db.session.delete(placeholder) - db.session.commit() - return created, updated - - -def main() -> None: - """Run the controlled YAML import and print counts without exposing credentials.""" - parser = argparse.ArgumentParser(description="Import legacy shipping inventory sources") - parser.add_argument("--file", type=Path, default=Path("config/shipping_inventory_sources.yaml")) - args = parser.parse_args() - app = create_app() - with app.app_context(): - created, updated = import_sources(args.file) - print(f"Imported inventory sources: created={created}, updated={updated}") - - -if __name__ == "__main__": - main() diff --git a/backend/tests/api/test_freight_rpa_api.py b/backend/tests/api/test_freight_rpa_api.py new file mode 100644 index 00000000..380d6f15 --- /dev/null +++ b/backend/tests/api/test_freight_rpa_api.py @@ -0,0 +1,306 @@ +""" +tests/api/test_freight_rpa_api.py + +用途:/api/freight-rpa/* 回调蓝图的 HTTP 契约测试(批次 R Task 8 建立、Task 9 补 sink 注册后契约)。 +依赖:tests/conftest.py 的 app/client fixture;freight_rpa.common.callback_sinks。 +逻辑:锁定四条关键契约——① 心跳新路由鉴权必备;② 旧 shipping-notice rpa 回调前缀无双路由 + (脏回调显式 404);③ 未注册 sink 的 kind 显式 404 且错误码 FREIGHT_RPA.SINK_NOT_REGISTERED + (分发层语义,用自造 kind 单测锁定);④ Task 9 组合根注册真实 sink 后,8 个 onhand 端点 + 的响应 envelope 与旧 shipping-notice rpa 回调端点逐 kind 逐字一致(禁止统一 envelope): + inventory-ready / batch-ready / batch-progress 返回裸业务 tool_response dict, + batch-claimed 返回 {'success':True,'data':...},configuration-test-* 返回 {'status':'ok','data':...}; + ⑤ Task 10 注册 inbound sink 后,3 个 inbound 端点维持 {'success':True,'data':...} 旧形态, + 业务校验路径(400/404 错误码)与拆分前直连逐字一致。 +""" + +from __future__ import annotations + +from datetime import datetime + +import pytest + + +TEST_TOOL_KEY = 'test-tool-key' + + +@pytest.fixture +def tool_auth_headers(app): + """以测试 integration key 生成 Bearer 鉴权头(与生产 Worker 的 Bearer 形态一致)。""" + app.config['SHIPPING_NOTICE_TOOL_API_KEY'] = TEST_TOOL_KEY + return {'Authorization': f'Bearer {TEST_TOOL_KEY}'} + + +@pytest.fixture +def terminal_configuration_test_run(app): + """预置一个已终态的配置测试运行 + 批次,供 configuration-test 三端点走 OK envelope 路径。""" + from app import db + from app.models import ( + FreightRpaOnhandConfigurationTestRun, + FreightRpaSource, + FreightRpaOnhandValidationBatch, + ) + + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + batch = FreightRpaOnhandValidationBatch(batch_no='CONFIG-BATCH-ENV-TEST', status='running', total_count=1) + db.session.add(batch) + db.session.flush() + run = FreightRpaOnhandConfigurationTestRun( + run_no='CONFIG-ENV-TEST-RUN', validation_batch_id=batch.id, source_id=source.id, + source_config_version=source.config_version, + rpa_profile_config_version=source.rpa_profile.config_version, + status='completed', stage='current_profile_verified', result_json={}, + completed_at=datetime.utcnow(), + ) + db.session.add(run) + db.session.commit() + return {'batch_id': batch.id, 'run_no': run.run_no} + + +def test_heartbeat_requires_auth(client, app): + """heartbeat 走新路由且鉴权必备:无 Header 必须 401,绝不能匿名写心跳。""" + app.config['SHIPPING_NOTICE_TOOL_API_KEY'] = TEST_TOOL_KEY + assert client.post("/api/freight-rpa/heartbeat", json={}).status_code == 401 + + +def test_legacy_rpa_routes_removed(client): + """旧路由已死(无兼容层,脏回调显式 404):旧 URL 不得再被任何蓝图接住。""" + assert client.post("/api/shipping-notice" + "/rpa/heartbeat", json={}).status_code == 404 + + +def test_onhand_ready_registered_sink_returns_tool_envelope(client, tool_auth_headers): + """Task 9 注册 sink 后 onhand-ready 可达:空载荷走业务失败分支,envelope 与旧 + /rpa/inventory-ready 的裸 tool_response dict 逐字一致(status/message/data 顶层键)。""" + resp = client.post("/api/freight-rpa/onhand-ready", json={}, headers=tool_auth_headers) + assert resp.status_code == 200 + body = resp.get_json() + # [断言意图] 旧端点 = jsonify(rpa_report_inventory(payload)),tool_response 顶层键固定为 + # status/message/data;失败文案必须保留旧值「未找到任务编号」。 + assert set(body) == {"status", "message", "data"} + assert body["status"] == "failed" + assert body["message"] == "未找到任务编号" + assert body["data"] == {} + + +def test_unauthenticated_sink_endpoint_is_401_not_404(client, app): + """鉴权先于分发:未携带 key 打 sink 端点是 401(未授权),不能泄漏 404 分发语义。""" + app.config['SHIPPING_NOTICE_TOOL_API_KEY'] = TEST_TOOL_KEY + assert client.post("/api/freight-rpa/onhand-ready", json={}).status_code == 401 + + +# --------------------------------------------------------------------------- +# Task 9 envelope 逐 kind 契约:以 git HEAD 旧端点实现为基准写死期望 shape。 +# --------------------------------------------------------------------------- + +def test_onhand_batch_ready_envelope_matches_legacy(client, tool_auth_headers): + """onhand-batch-ready(旧 /rpa/inventory-batch-ready = jsonify(rpa_report_inventory(...))): + 裸业务 dict;schema 非法分支 data 内 transport_status/business_status/error_code 三键。""" + resp = client.post("/api/freight-rpa/onhand-batch-ready", json={}, headers=tool_auth_headers) + assert resp.status_code == 200 + body = resp.get_json() + assert set(body) == {"status", "message", "data"} + assert body["status"] == "failed" + assert body["message"] == "callback_schema_invalid" + assert body["data"] == { + "transport_status": "invalid", + "business_status": "rejected", + "error_code": "callback_schema_invalid", + } + + +def test_onhand_batch_claimed_envelope_matches_legacy(client, tool_auth_headers): + """onhand-batch-claimed(旧 /rpa/inventory-batch-claimed): + envelope = {'success': True, 'data': claim_inventory_batch(payload)},禁止裸 dict。""" + resp = client.post("/api/freight-rpa/onhand-batch-claimed", json={}, headers=tool_auth_headers) + assert resp.status_code == 200 + body = resp.get_json() + # [断言意图] 旧端点包裹 {'success': True, 'data': ...};schema 非法时业务层返回三键拒绝体。 + assert set(body) == {"success", "data"} + assert body["success"] is True + assert body["data"] == { + "transport_status": "invalid", + "business_status": "rejected", + "error_code": "callback_schema_invalid", + } + + +def test_onhand_batch_progress_envelope_matches_legacy(client, tool_auth_headers): + """onhand-batch-progress(旧 /rpa/inventory-batch-progress): + 裸业务 dict;schema 非法分支 data.progress_status='invalid'。""" + resp = client.post("/api/freight-rpa/onhand-batch-progress", json={}, headers=tool_auth_headers) + assert resp.status_code == 200 + body = resp.get_json() + assert set(body) == {"status", "message", "data"} + assert body["status"] == "failed" + assert body["message"] == "callback_schema_invalid" + assert body["data"] == { + "progress_status": "invalid", + "error_code": "callback_schema_invalid", + } + + +def test_onhand_configuration_test_start_envelope_matches_legacy(client, tool_auth_headers, terminal_configuration_test_run): + """onhand-configuration-test-start(旧 /rpa/inventory-configuration-test-batch-progress = + report_batch_test_progress):envelope = {'status':'ok','data':测试运行投影}。""" + resp = client.post( + "/api/freight-rpa/onhand-configuration-test-start", + json={ + 'validation_batch_id': terminal_configuration_test_run['batch_id'], + 'validation_run_no': terminal_configuration_test_run['run_no'], + }, + headers=tool_auth_headers, + ) + assert resp.status_code == 200 + body = resp.get_json() + # [断言意图] 旧端点 = jsonify({'status':'ok','data': report_batch_test_progress(...)}); + # 终态 run 早退分支返回 _payload(run)(含 id/run_no/status)。 + assert set(body) == {"status", "data"} + assert body["status"] == "ok" + assert body["data"]["run_no"] == terminal_configuration_test_run['run_no'] + assert body["data"]["status"] == "completed" + + +def test_onhand_configuration_test_analyze_envelope_matches_legacy(client, tool_auth_headers, terminal_configuration_test_run): + """onhand-configuration-test-analyze(旧 /rpa/inventory-configuration-test-ready = + report_test_export):envelope = {'status':'ok','data':测试运行投影}。""" + resp = client.post( + "/api/freight-rpa/onhand-configuration-test-analyze", + json={'run_no': terminal_configuration_test_run['run_no']}, + headers=tool_auth_headers, + ) + assert resp.status_code == 200 + body = resp.get_json() + assert set(body) == {"status", "data"} + assert body["status"] == "ok" + assert body["data"]["run_no"] == terminal_configuration_test_run['run_no'] + + +def test_onhand_configuration_test_complete_envelope_matches_legacy(client, tool_auth_headers, terminal_configuration_test_run): + """onhand-configuration-test-complete(旧 /rpa/inventory-configuration-test-batch-ready = + report_batch_test_exports):envelope = {'status':'ok','data':批次投影+updated/ignored 计数}。""" + resp = client.post( + "/api/freight-rpa/onhand-configuration-test-complete", + json={'validation_batch_id': terminal_configuration_test_run['batch_id'], 'results': []}, + headers=tool_auth_headers, + ) + assert resp.status_code == 200 + body = resp.get_json() + assert set(body) == {"status", "data"} + assert body["status"] == "ok" + assert body["data"]["updated_count"] == 0 + assert body["data"]["ignored_count"] == 0 + assert body["data"]["batch_no"] == "CONFIG-BATCH-ENV-TEST" + + +def test_onhand_repair_envelope_matches_legacy(client, tool_auth_headers): + """onhand-repair(旧 /rpa/inventory-repair = repair=True 后 jsonify(rpa_report_inventory(...))): + 裸业务 dict,schema 非法分支与 batch-ready 同形。""" + resp = client.post("/api/freight-rpa/onhand-repair", json={}, headers=tool_auth_headers) + assert resp.status_code == 200 + body = resp.get_json() + assert set(body) == {"status", "message", "data"} + assert body["status"] == "failed" + assert body["data"] == { + "transport_status": "invalid", + "business_status": "rejected", + "error_code": "callback_schema_invalid", + } + + +# --------------------------------------------------------------------------- +# Task 10 inbound sink 注册后契约:三端点改 dispatch_sink 后 envelope 与拆分前直连 +# 形态(jsonify({'success': True, 'data': 业务结果}))逐字一致,禁止裸 dict / 统一 envelope。 +# --------------------------------------------------------------------------- + +def test_inbound_unit_progress_envelope_matches_legacy(client, tool_auth_headers): + """inbound-unit-progress(旧直连 jsonify({'success':True,'data':mark_inbound_unit_processing(p)})): + schema 非法分支 data={'updated':False,'reason':'callback_schema_invalid'},证明 sink 已注册 + (未注册会是 404 FREIGHT_RPA.SINK_NOT_REGISTERED)且 envelope 未漂移。""" + resp = client.post("/api/freight-rpa/inbound-unit-progress", json={}, headers=tool_auth_headers) + assert resp.status_code == 200 + body = resp.get_json() + assert set(body) == {"success", "data"} + assert body["success"] is True + assert body["data"] == {"updated": False, "reason": "callback_schema_invalid"} + + +def test_inbound_batch_progress_envelope_matches_legacy(client, tool_auth_headers): + """inbound-batch-progress(旧直连同款 envelope):schema 非法分支与 unit-progress 同形。""" + resp = client.post("/api/freight-rpa/inbound-batch-progress", json={}, headers=tool_auth_headers) + assert resp.status_code == 200 + body = resp.get_json() + assert set(body) == {"success", "data"} + assert body["success"] is True + assert body["data"] == {"updated": False, "reason": "callback_schema_invalid"} + + +def test_inbound_batch_ready_schema_invalid_reaches_business_validation(client, tool_auth_headers): + """inbound-batch-ready sink 已注册:schema 非法穿透到业务校验(400 + + SHIPPING.INBOUND_CALLBACK_INVALID),而非未注册 404;错误 envelope 与拆分前同形 + (旧端点在 jsonify 之前由 ingest 抛 ValidationError → 全局 AppError handler)。""" + resp = client.post("/api/freight-rpa/inbound-batch-ready", json={}, headers=tool_auth_headers) + assert resp.status_code == 400 + body = resp.get_json() + assert body["success"] is False + assert body["error"]["code"] == "SHIPPING.INBOUND_CALLBACK_INVALID" + + +def test_inbound_batch_ready_unknown_unit_is_404(client, tool_auth_headers): + """inbound-batch-ready 未知 callback_id:404 + SHIPPING.INBOUND_UNIT_NOT_FOUND, + 与拆分前 ingest 直连时的 NotFoundError 路径逐字一致。""" + resp = client.post( + "/api/freight-rpa/inbound-batch-ready", + json={"schema_version": "freight_rpa.inbound.v1", "callback_id": "no-such-callback"}, + headers=tool_auth_headers, + ) + assert resp.status_code == 404 + body = resp.get_json() + assert body["error"]["code"] == "SHIPPING.INBOUND_UNIT_NOT_FOUND" + + +@pytest.mark.pure_unit +def test_dispatch_sink_unregistered_raises_app_error(): + """注册表单测:未注册 kind 抛 AppError(404, FREIGHT_RPA.SINK_NOT_REGISTERED),不静默吞回调。""" + from app.core.errors import AppError + from app.services.freight_rpa.common.callback_sinks import dispatch_sink, register_sink + + seen: dict[str, object] = {} + + def _handler(**payload): + seen.update(payload) + return {'ok': True} + + register_sink('unit-test-kind', _handler) + assert dispatch_sink('unit-test-kind', callback_id='cb-1') == {'ok': True} + assert seen == {'callback_id': 'cb-1'} + + with pytest.raises(AppError) as excinfo: + dispatch_sink('never-registered-kind', callback_id='cb-2') + assert excinfo.value.code == 'FREIGHT_RPA.SINK_NOT_REGISTERED' + assert excinfo.value.http_status == 404 + + +def test_admin_rpa_profiles_routes_migrated(app, client): + """admin rpa-profiles 已迁 /api/admin/freight-rpa/*:管理员可达、旧 URL 404、普通用户 403。""" + from app import db + from app.models import User + + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + db.session.add_all([ + User(username='rpa-admin', email='rpa-admin@example.com', role='admin', status='active'), + User(username='rpa-user', email='rpa-user@example.com', role='user', status='active'), + ]) + db.session.commit() + + admin_headers = {'X-Username': 'rpa-admin', 'X-Role': 'admin'} + user_headers = {'X-Username': 'rpa-user', 'X-Role': 'user'} + + migrated = client.get('/api/admin/freight-rpa/rpa-profiles', headers=admin_headers) + assert migrated.status_code == 200 + assert migrated.get_json()['success'] is True + + # [断言意图] 普通用户必须被 require_admin 拦截(迁移未放松权限)。 + assert client.get('/api/admin/freight-rpa/rpa-profiles', headers=user_headers).status_code == 403 + + # [断言意图] 旧 admin URL 无双路由:脏调用显式 404(前端已同窗口切换)。 + assert client.get('/api/admin/shipping-notice/rpa-profiles', headers=admin_headers).status_code == 404 diff --git a/backend/tests/api/test_in_transit_transfer_api.py b/backend/tests/api/test_in_transit_transfer_api.py index e0543465..883a07cf 100644 --- a/backend/tests/api/test_in_transit_transfer_api.py +++ b/backend/tests/api/test_in_transit_transfer_api.py @@ -1,14 +1,19 @@ """在途调拨匹配 API 契约测试(L2,Flask test client)。 用途:验证 POST /matchings 创建(含 envelope/权限/参数校验)与 - GET /matchings/{id} 进度恢复;无权限 403、未认证 401。 -依赖:app fixture、client、issue_local_access_token、fakes/repo_fakes。 + GET /matchings/{id} 进度恢复;无权限 403、未认证 401; + 待匹配清单按外部单号合计数量,不再投影外部项次; + 证据压缩包路径与当天清单(Task 5)。 +依赖:app fixture、client、issue_local_access_token、fakes/repo_fakes、factories。 逻辑:API 依赖经 deps._override 注入 Fake 替身;权限按 admin 放行或 - in_transit_transfer Agent 授权校验。 + in_transit_transfer Agent 授权校验。证据下载用内存字节替换 + file_asset_storage.get_bytes,清单用 presigned_get_url 替身。 """ from __future__ import annotations +from datetime import datetime + import pytest from app import db @@ -25,6 +30,14 @@ def _jwt_headers(user: User) -> dict: return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} +@pytest.fixture(autouse=True) +def _seed_transfer_type(app): + """类型配置化(Task 11/D8):API 域用例预置默认启用类型(匹配创建必填)。""" + from tests.services.in_transit_transfer.factories import seed_transfer_type_config + + seed_transfer_type_config() + + @pytest.fixture def transfer_deps(app, monkeypatch, dbs_ready_file): """注入 Fake 匹配依赖,预置可执行库存,并把执行文件对账投影替换为 ready(sha=夹具 checksum)。 @@ -38,8 +51,9 @@ def transfer_deps(app, monkeypatch, dbs_ready_file): seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps) - def _resolve(*, source_code: str) -> dict: + def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict: # 执行门禁②(文件版本对账)替身:来源恒 ready 且 sha 与夹具行版本戳同源。 + del record_kind return {"file_status": "ready", "has_ready_file": True, "file_no": "REC-TEST", "file_sha256": "d" * 64} monkeypatch.setattr( @@ -114,7 +128,7 @@ def test_create_matching_returns_envelope_with_matching_id(app, client, admin_he """POST /matchings → 201 envelope,data 含 matching_id/hash/计数。""" response = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={ "source_codes": ["DBS-AWSBI"], - "business_date": "2026-08-06", + "business_date": "2026-08-06", "transfer_type": "in_transit_to_hub" }) assert response.status_code == 201 body = response.get_json() @@ -129,7 +143,7 @@ def test_create_matching_returns_envelope_with_matching_id(app, client, admin_he def test_create_matching_requires_authentication(client): """未认证 → 401(envelope error)。""" - response = client.post(f"{API_PREFIX}/matchings", json={"source_codes": ["DBS-AWSBI"]}) + response = client.post(f"{API_PREFIX}/matchings", json={"source_codes": ["DBS-AWSBI"], "transfer_type": "in_transit_to_hub"}) assert response.status_code == 401 assert response.get_json()["success"] is False @@ -137,7 +151,7 @@ def test_create_matching_requires_authentication(client): def test_create_matching_forbidden_without_agent_permission(client, unauthorized_headers): """无 in_transit_transfer Agent 权限 → 403。""" response = client.post(f"{API_PREFIX}/matchings", headers=unauthorized_headers, json={ - "source_codes": ["DBS-AWSBI"], + "source_codes": ["DBS-AWSBI"], "transfer_type": "in_transit_to_hub" }) assert response.status_code == 403 assert response.get_json()["error"]["code"] == "AUTH.FORBIDDEN" @@ -147,7 +161,7 @@ def test_create_matching_warehouse_manager_allowed(app, client, warehouse_header """持有 Agent 权限的仓库管理员可创建匹配。""" response = client.post(f"{API_PREFIX}/matchings", headers=warehouse_headers, json={ "source_codes": ["DBS-AWSBI"], - "business_date": "2026-08-06", + "business_date": "2026-08-06", "transfer_type": "in_transit_to_hub" }) assert response.status_code == 201 assert response.get_json()["data"]["matching_id"] @@ -155,13 +169,13 @@ def test_create_matching_warehouse_manager_allowed(app, client, warehouse_header def test_create_matching_validates_source_codes(app, client, admin_headers, transfer_deps): """缺少 source_codes → 400 参数错误。""" - response = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={"business_date": "2026-08-06"}) + response = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={"business_date": "2026-08-06", "transfer_type": "in_transit_to_hub"}) assert response.status_code == 400 assert response.get_json()["success"] is False def test_create_matching_accepts_transfer_type_and_rejects_placeholder(app, client, admin_headers, transfer_deps): - """transfer_type 合法值放行;占位类型(类型2/3)与非法值 → 400 fail-closed。""" + """transfer_type 合法值放行;未配置编码 → 422 NOT_CONFIGURED(D8/规格 §11)。""" created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={ "source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06", @@ -169,21 +183,38 @@ def test_create_matching_accepts_transfer_type_and_rejects_placeholder(app, clie }) assert created.status_code == 201 + # [语义平移] 旧「占位类型/非法值 NOT_SUPPORTED/INVALID」随配置化退役: + # 类型合法值=配置表 code,无此码统一 NOT_CONFIGURED(启用/停用门禁见服务用例)。 for bad_type in ("hub_repair_out", "hub_to_hub", "bogus_type"): response = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={ "source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06", "transfer_type": bad_type, }) - assert response.status_code == 400, bad_type - assert response.get_json()["success"] is False + assert response.status_code == 422, bad_type # [规格 §11] 类型门禁统一 422 + body = response.get_json() + assert body["success"] is False + assert body["error"]["code"] == "TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED" + + +def test_create_matching_requires_transfer_type(app, client, admin_headers, transfer_deps): + """transfer_type 缺失 → 422 TRANSFER_TYPE_REQUIRED(D8 必填,规格 §11)。""" + response = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={ + "source_codes": ["DBS-AWSBI"], + "business_date": "2026-08-06", + }) + assert response.status_code == 422 # [规格 §11] 类型门禁统一 422 + body = response.get_json() + # [断言意图] 必填缺失独立成码(与 NOT_CONFIGURED 区分),前端可精确提示。 + assert body["success"] is False + assert body["error"]["code"] == "TRANSFER.TRANSFER_TYPE_REQUIRED" def test_restore_matching_progress(app, client, admin_headers, transfer_deps): """GET /matchings/{id} 恢复匹配进度(Hash/明细一致)。""" created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={ "source_codes": ["DBS-AWSBI"], - "business_date": "2026-08-06", + "business_date": "2026-08-06", "transfer_type": "in_transit_to_hub" }).get_json()["data"] restored = client.get(f"{API_PREFIX}/matchings/{created['matching_id']}", headers=admin_headers) assert restored.status_code == 200 @@ -205,7 +236,7 @@ def test_executable_items_lists_ready_rows_with_decoration( # 行装饰的文件对账在 matching_service 命名空间——与执行门禁②同口径替身。 monkeypatch.setattr( "app.services.in_transit_transfer.matching_service.resolve_source_file_status", - lambda *, source_code: {"file_status": "ready", "has_ready_file": True, + lambda *, source_code, record_kind="inbound": {"file_status": "ready", "has_ready_file": True, "file_no": "REC-TEST", "file_sha256": "d" * 64}, ) _create_matching(client, admin_headers) @@ -219,6 +250,8 @@ def test_executable_items_lists_ready_rows_with_decoration( assert item["stale"] is False assert item["file_current"] is True assert item["checked_at"] + # [断言意图] 可调拨明细跨类型混排,行上要带回出生匹配的类型 code。 + assert item["transfer_type"] == "in_transit_to_hub" def test_executable_items_requires_authentication(client): @@ -230,7 +263,7 @@ def _create_matching(client, admin_headers) -> str: """创建匹配并返回 matching_no。""" created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={ "source_codes": ["DBS-AWSBI"], - "business_date": "2026-08-06", + "business_date": "2026-08-06", "transfer_type": "in_transit_to_hub" }) assert created.status_code == 201 return created.get_json()["data"]["matching_id"] @@ -346,7 +379,7 @@ def test_manual_close_item_requires_reason(app, client, admin_headers, transfer_ """人工关闭缺少原因 → 400。""" created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={ "source_codes": ["DBS-AWSBI"], - "business_date": "2026-08-06", + "business_date": "2026-08-06", "transfer_type": "in_transit_to_hub" }).get_json()["data"] with app.app_context(): from app.models import TransferInvoiceItem @@ -364,7 +397,7 @@ def test_manual_close_item_success(app, client, admin_headers, transfer_deps): """人工关闭成功 → 状态 manually_closed。""" created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={ "source_codes": ["DBS-AWSBI"], - "business_date": "2026-08-06", + "business_date": "2026-08-06", "transfer_type": "in_transit_to_hub" }).get_json()["data"] with app.app_context(): from app.models import TransferInvoiceItem @@ -397,18 +430,18 @@ def test_exceptions_excel_download(app, transfer_db, client, admin_headers, tran assert audit.run_no == run_no -def test_receipt_files_download_records_access_audit(app, transfer_db, client, admin_headers, transfer_deps): - """下载收料来源文件 → 200(zip),记录访问审计。""" +def test_inbound_files_download_records_access_audit(app, transfer_db, client, admin_headers, transfer_deps): + """下载出入站来源文件 → 200(zip),记录访问审计。""" _create_matching(client, admin_headers) executed = _execute_ready_items(app, client, admin_headers) run_no = executed.get_json()["data"]["run_no"] - response = client.get(f"{API_PREFIX}/runs/{run_no}/receipt-files", headers=admin_headers) + response = client.get(f"{API_PREFIX}/runs/{run_no}/inbound-files", headers=admin_headers) assert response.status_code == 200 assert response.content_type.startswith("application/zip") with app.app_context(): from app.models import TransferAuditEvent - audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_RECEIPT_FILES_DOWNLOADED").first() + audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_INBOUND_FILES_DOWNLOADED").first() assert audit is not None @@ -433,7 +466,7 @@ def test_downloads_forbidden_without_permission(app, transfer_db, client, admin_ _create_matching(client, admin_headers) executed = _execute_ready_items(app, client, admin_headers) run_no = executed.get_json()["data"]["run_no"] - for path in (f"{API_PREFIX}/runs/{run_no}/receipt-files", + for path in (f"{API_PREFIX}/runs/{run_no}/inbound-files", f"{API_PREFIX}/runs/{run_no}/external-inventory", f"{API_PREFIX}/runs/{run_no}/exceptions.xlsx"): response = client.get(path, headers=unauthorized_headers) @@ -458,7 +491,7 @@ def test_backlog_list_and_summary(app, transfer_db, client, admin_headers, trans # 匹配含 1 个数量不一致(blocked)项 created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={ "source_codes": ["DBS-AWSBI"], - "business_date": "2026-08-06", + "business_date": "2026-08-06", "transfer_type": "in_transit_to_hub" }).get_json()["data"] with app.app_context(): from app.models import TransferInvoiceItem @@ -475,6 +508,9 @@ def test_backlog_list_and_summary(app, transfer_db, client, admin_headers, trans assert "HOM-001" in invoice_set assert "HOX-002" not in invoice_set # 可执行项不在待处理池 assert listed.get_json()["data"][0]["aging_level"] in {"normal", "warn_3d", "escalate_5d", "critical_7d"} + blocked = next(entry for entry in listed.get_json()["data"] if entry["invoice_no"] == "HOM-001") + # [断言意图] 待恢复行要带回出生匹配的类型 code,表格才能显示类别而不是只看仓库。 + assert blocked["transfer_type"] == "in_transit_to_hub" summary = client.get(f"{API_PREFIX}/backlog/summary", headers=admin_headers) assert summary.status_code == 200 @@ -487,14 +523,188 @@ def test_backlog_forbidden_without_permission(app, transfer_db, client, unauthor assert response.status_code == 403 +def test_backlog_pagination_envelope_and_compat(app, transfer_db, client, admin_headers, transfer_deps): + """GET /backlog 分页 envelope 与无参兼容:带 page/page_size 回 + {items,total,page,page_size},无参保持历史全量数组(向后兼容口径)。""" + _create_matching(client, admin_headers) + with app.app_context(): + from app.models import TransferInvoiceItem + + item = TransferInvoiceItem.query.filter_by(invoice_no="HOM-001").first() + item.status = "blocked_recoverable" + item.result_code = "blocked_quantity_mismatch" + db.session.commit() + + # 无参 → 历史数组形状(向后兼容;现有前端/测试依赖不破)。 + legacy = client.get(f"{API_PREFIX}/backlog", headers=admin_headers) + assert legacy.status_code == 200 + assert isinstance(legacy.get_json()["data"], list) + + # 带分页参数 → envelope;单行池:首页 1 行、total=1。 + paged = client.get( + f"{API_PREFIX}/backlog?page=1&page_size=1&result_filter=recoverable", + headers=admin_headers, + ) + assert paged.status_code == 200 + data = paged.get_json()["data"] + assert set(data.keys()) == {"items", "total", "page", "page_size"} + assert len(data["items"]) == 1 and data["items"][0]["invoice_no"] == "HOM-001" + assert data["total"] == 1 and data["page"] == 1 and data["page_size"] == 1 + # 越界页:offset 超出 total → 空切片(分页推进语义)。 + page2 = client.get( + f"{API_PREFIX}/backlog?page=2&page_size=1&result_filter=recoverable", + headers=admin_headers, + ).get_json()["data"] + assert page2["items"] == [] and page2["total"] == 1 + + +def test_backlog_result_filter_and_keyword_pushdown(app, transfer_db, client, admin_headers, transfer_deps): + """GET /backlog 筛选下推:result_filter 白名单切片、keyword 跨四字段子串、 + 白名单外 400(fail-closed)。""" + _create_matching(client, admin_headers) + with app.app_context(): + from app.models import TransferInvoiceItem + + first = TransferInvoiceItem.query.filter_by(invoice_no="HOM-001").first() + first.status = "blocked_recoverable" + first.result_code = "blocked_quantity_mismatch" + # 第二种池内状态:把可执行行翻成人工关闭(进池、落 closed 切片)。 + second = TransferInvoiceItem.query.filter_by(invoice_no="HOX-002").first() + second.status = "manually_closed" + second.result_message = "线下处理" + db.session.commit() + + recoverable = client.get( + f"{API_PREFIX}/backlog?page=1&page_size=50&result_filter=recoverable", + headers=admin_headers, + ).get_json()["data"] + assert {entry["invoice_no"] for entry in recoverable["items"]} == {"HOM-001"} + assert recoverable["total"] == 1 + + closed = client.get( + f"{API_PREFIX}/backlog?page=1&page_size=50&result_filter=closed", + headers=admin_headers, + ).get_json()["data"] + assert {entry["invoice_no"] for entry in closed["items"]} == {"HOX-002"} + + keyword = client.get( + f"{API_PREFIX}/backlog?page=1&page_size=50&keyword=HOX-002", + headers=admin_headers, + ).get_json()["data"] + assert {entry["invoice_no"] for entry in keyword["items"]} == {"HOX-002"} + + invalid = client.get( + f"{API_PREFIX}/backlog?page=1&result_filter=bogus", + headers=admin_headers, + ) + assert invalid.status_code == 400 + + +def test_backlog_item_ids_for_cross_page_select_all(app, transfer_db, client, admin_headers, transfer_deps): + """GET /backlog/item-ids 跨页全选支持:按筛选口径回全量 item_id(升序) + + total + truncated 标记;result_filter 白名单外 400(与 /backlog 同口径)。""" + _create_matching(client, admin_headers) + with app.app_context(): + from app import db as _db + from app.models import TransferInvoiceItem + + first = TransferInvoiceItem.query.filter_by(invoice_no="HOM-001").first() + first.status = "blocked_recoverable" + first.result_code = "blocked_quantity_mismatch" + second = TransferInvoiceItem.query.filter_by(invoice_no="HOX-002").first() + second.status = "manually_closed" + second.result_message = "线下处理" + _db.session.commit() + expected = sorted( + item.id for item in TransferInvoiceItem.query.filter( + TransferInvoiceItem.status.in_(["blocked_recoverable", "manually_closed"]) + ).all() + ) + + data = client.get(f"{API_PREFIX}/backlog/item-ids", headers=admin_headers).get_json()["data"] + assert set(data.keys()) == {"ids", "total", "truncated"} + assert data["ids"] == expected # [断言意图] 全量 id 升序(两态并集) + assert data["total"] == len(expected) and data["truncated"] is False + + # 切片口径:recoverable 只回可恢复行的 id。 + recoverable = client.get( + f"{API_PREFIX}/backlog/item-ids?result_filter=recoverable", headers=admin_headers, + ).get_json()["data"] + assert len(recoverable["ids"]) == 1 and recoverable["total"] == 1 + + invalid = client.get(f"{API_PREFIX}/backlog/item-ids?result_filter=bogus", headers=admin_headers) + assert invalid.status_code == 400 + + +def test_pending_match_pagination_envelope_and_compat(app, transfer_db, client, admin_headers): + """GET /backlog/pending-match 分页 envelope 与无参兼容:带参回 + {records,total,page,page_size},无参保持历史数组(真实落档 25 行走 + SQL 分页下推链路:GROUP BY 计数 + 组首行锚点切片,验证稳定排序)。""" + from app.models import TransferMovementLedger + + for i in range(25): + transfer_db.session.add(TransferMovementLedger( + source_code="DBS-AWSBI", record_kind="inbound", + doc_no=f"HOM-{900 + i}", line_no=str(i + 1), line_seq="", in_out_flag="", + material_code=f"MAT-{i}", material_name="未匹配物料", specification="", + external_doc_no=f"EXT-{i}", external_line_no=str(i + 1), + lot_no="LOT-1", quantity="1", unit="PCS", + warehouse_code="", storage_code="", movement_date="2026-08-05", + source_file_id=None, file_version="v1", file_sha256="a" * 64, + sheet_name="Receipt", row_no=i + 1, + transfer_executed=False, executed_doc_no=None, + )) + transfer_db.session.flush() + + legacy = client.get(f"{API_PREFIX}/backlog/pending-match", headers=admin_headers) + assert legacy.status_code == 200 + assert isinstance(legacy.get_json()["data"], list) + assert len(legacy.get_json()["data"]) == 25 + + paged = client.get( + f"{API_PREFIX}/backlog/pending-match?page=2&page_size=20", + headers=admin_headers, + ) + assert paged.status_code == 200 + data = paged.get_json()["data"] + assert set(data.keys()) == {"records", "total", "page", "page_size"} + assert len(data["records"]) == 5 # 25 行第 2 页余量 + assert data["total"] == 25 and data["page"] == 2 and data["page_size"] == 20 + assert data["records"][0]["doc_no"] == "HOM-920" # 第 21 行(稳定排序切片) + # [断言意图] 清单带出外部单号和数量,不再返回外部项次。 + assert data["records"][0]["external_doc_no"] == "EXT-20" + assert data["records"][0]["quantity"] == "1" + assert "external_line_no" not in data["records"][0] + + def test_list_transfer_sources(app, client, admin_headers): - """来源实例列表:返回启用来源(平台=connector_type,来源实例为执行边界)。""" + """来源实例列表:返回启用来源,并附入站/出站两条证据流。 + + 扁平 file_status / has_ready_file 必须等于入站那条,供尚未改完的前端。 + 生产侧漏掉 streams、把两条合成一条、或扁平字段改读出站,本用例都会失败。 + """ response = client.get(f"{API_PREFIX}/sources", headers=admin_headers) assert response.status_code == 200 sources = response.get_json()["data"] assert isinstance(sources, list) # 测试种子来源 DSV360_AWSDU(dbs)应在列表中 - assert any(item["source_code"] == "DSV360_AWSDU" for item in sources) + dsv = next(item for item in sources if item["source_code"] == "DSV360_AWSDU") + # 两条都返回且入站在前:前端按 record_kind 过滤,扁平字段仍跟入站。 + # 种子来源没有出站报表配置,出站必须是 unconfigured,不能抄入站投影。 + assert len(dsv["streams"]) == 2 + assert dsv["streams"][0]["record_kind"] == "inbound" + assert set(dsv["streams"][0]) == { + "record_kind", "file_status", "has_ready_file", "file_no", "file_sha256", + } + assert dsv["streams"][1] == { + "record_kind": "outbound", + "file_status": "unconfigured", + "has_ready_file": False, + "file_no": None, + "file_sha256": None, + } + assert dsv["file_status"] == dsv["streams"][0]["file_status"] + assert dsv["has_ready_file"] == dsv["streams"][0]["has_ready_file"] for item in sources: assert item["source_code"] assert item["platform"] in {"dbs", "crane"} @@ -507,12 +717,33 @@ def test_list_transfer_sources_forbidden(app, client, unauthorized_headers): assert response.status_code == 403 +def test_reparse_current_without_file_returns_422(client, admin_headers): + # [断言意图] 没有出站归档时重解析是 422,不是 202 抓取中。 + response = client.post( + f"{API_PREFIX}/sources/DSV360_AWSDU/reparse", + headers=admin_headers, + json={"record_kind": "outbound"}, + ) + assert response.status_code == 422 + assert response.get_json()["error"]["code"] == "TRANSFER.CURRENT_REPARSE_NO_FILE" + + +def test_reparse_current_forbidden(client, unauthorized_headers): + # [断言意图] 无调拨权限不能重解析。 + response = client.post( + f"{API_PREFIX}/sources/DSV360_AWSDU/reparse", + headers=unauthorized_headers, + json={"record_kind": "inbound"}, + ) + 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): +def _seed_parse_failed_inbound_file(source_code: str): """造一条「当日可用但解析失败」的收料归档文件(success 单元 + parse_failed 三列)。 与 tests/services/in_transit_transfer/test_source_file_status.py 同款最小造数: @@ -524,21 +755,21 @@ def _seed_parse_failed_receipt_file(source_code: str): from uuid import uuid4 from app.models import ( - ShippingInventorySource, - ShippingReceiptReportFile, - ShippingReceiptRpaUnitRun, + FreightRpaSource, + FreightRpaInboundReportFile, + FreightRpaInboundUnitRun, ) - source = ShippingInventorySource.query.filter_by(source_code=source_code).one() - unit = ShippingReceiptRpaUnitRun( - inventory_source_id=source.id, source_code=source.source_code, + source = FreightRpaSource.query.filter_by(source_code=source_code).one() + unit = FreightRpaInboundUnitRun( + source_id=source.id, source_code=source.source_code, connector_type=source.connector_type, warehouse_id=source.fixed_warehouse_id, callback_id=f"receipt-retry-{uuid4().hex[:12]}", status="success", config_snapshot_json={}, ) db.session.add(unit) db.session.flush() - report = ShippingReceiptReportFile( + report = FreightRpaInboundReportFile( unit_run_id=unit.id, storage_provider="minio", storage_bucket="test", storage_key=f"shipping/receipt/retry-{unit.id}.xlsx", original_filename="retry.xlsx", file_size=16, @@ -554,23 +785,23 @@ def _seed_parse_failed_receipt_file(source_code: str): 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") + _seed_parse_failed_inbound_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 + from app.models import FreightRpaInboundReportFile + from app.services.in_transit_transfer.source_file_status import clear_inbound_parse_failure called["sync"] += 1 file = ( - ShippingReceiptReportFile.query - .join(ShippingReceiptReportFile.unit_run) - .filter(ShippingReceiptReportFile.unit_run.has(source_code=source_code)) + FreightRpaInboundReportFile.query + .join(FreightRpaInboundReportFile.unit_run) + .filter(FreightRpaInboundReportFile.unit_run.has(source_code=source_code)) .first() ) if file is not None: - clear_receipt_parse_failure(report=file) + clear_inbound_parse_failure(report=file) db.session.commit() return True @@ -579,7 +810,7 @@ def test_retry_rpa_parse_failed_reparses_existing_file(app, client, admin_header fake_sync, ) monkeypatch.setattr( - "app.services.in_transit_transfer.receipt_trigger_service.trigger_receipt_rpa", + "app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_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) @@ -598,7 +829,7 @@ def test_retry_rpa_parse_failed_reparses_existing_file(app, client, admin_header 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") + _seed_parse_failed_inbound_file("DSV360_AWSDU") def fake_sync(*, source_code, business_date, now): # 断言意图:sync 返回 True 不代表投影恢复——标记未清除时端点必须如实报 @@ -611,7 +842,7 @@ def test_retry_rpa_parse_failed_still_failed_reports_not_ok(app, client, admin_h fake_sync, ) monkeypatch.setattr( - "app.services.in_transit_transfer.receipt_trigger_service.trigger_receipt_rpa", + "app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_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) @@ -635,7 +866,7 @@ def test_retry_rpa_batch_requires_source_codes(app, client, admin_headers): def test_retry_rpa_batch_delegates_to_batch_trigger_service(app, client, admin_headers, monkeypatch): - """批量端点把 source_codes 原样交给 trigger_receipt_rpa_batch 并回传结果 envelope。""" + """批量端点把 source_codes 原样交给 trigger_inbound_rpa_batch 并回传结果 envelope。""" captured: dict = {} def fake_batch(*, source_codes, business_date, reason): @@ -646,7 +877,7 @@ def test_retry_rpa_batch_delegates_to_batch_trigger_service(app, client, admin_h } monkeypatch.setattr( - "app.services.in_transit_transfer.receipt_trigger_service.trigger_receipt_rpa_batch", fake_batch, + "app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_rpa_batch", fake_batch, ) response = client.post( f"{API_PREFIX}/sources/retry-rpa-batch", headers=admin_headers, @@ -656,11 +887,315 @@ def test_retry_rpa_batch_delegates_to_batch_trigger_service(app, client, admin_h body = response.get_json()["data"] # [断言意图] 端点只做参数卡控与转发:来源列表原样下传、reason 固定业务语义。 assert captured["source_codes"] == ["DSV360_AWSDU", "DSV360_AWSSG"] - assert captured["reason"] == "transfer_retry_receipt" + assert captured["reason"] == "transfer_retry_inbound" assert body["ok"] is True and body["triggered"] is True assert [item["source_code"] for item in body["results"]] == ["DSV360_AWSDU", "DSV360_AWSSG"] +def _ensure_hub_to_hub_both_streams(): + """启用 hub_to_hub,范围规则显式包含入站与出站两条证据流。 + + 核心逻辑:类型表没有 record_kinds 列。record_kinds_of 从 record_kind + 规则推导;不写该规则时也会得到双流。这里用 match=in 写明两个值, + 批量重试才能同时看到入站与出站。已存在则直接复用。 + """ + from app.core.errors import ValidationError + from app.services.in_transit_transfer.transfer_type_config_service import ( + create_config, + get_by_code, + ) + + try: + return get_by_code("hub_to_hub") + except ValidationError: + return create_config({ + "code": "hub_to_hub", + "names": {"zh-CN": "仓间调拨"}, + "enabled": True, + "scope_rules": [ + {"field": "record_kind", "match": "in", "values": ["inbound", "outbound"]}, + ], + }) + + +def _stream_status(file_status: str) -> dict: + """投影替身的最小状态字典(与 resolve_source_file_status 四键一致)。""" + ready = file_status == "ready" + return { + "file_status": file_status, + "has_ready_file": ready, + "file_no": "a.xlsx" if ready else None, + "file_sha256": "abc" if ready or file_status == "parse_failed" else None, + } + + +def test_batch_retry_skips_ready_inbound_and_triggers_outbound(app, client, admin_headers, monkeypatch): + """HUB 仓间调拨:入站已就绪不重抓,出站未就绪才触发。""" + import app.api.in_transit_transfer as api_module + + _ensure_hub_to_hub_both_streams() + + def fail_inbound(**kwargs): + raise AssertionError("inbound batch") + + called = {} + + def record_outbound(**kwargs): + called["codes"] = kwargs["source_codes"] + return {"ok": True, "triggered": True} + + def status(*, source_code, record_kind="inbound"): + if record_kind == "outbound": + return {"file_status": "none", "has_ready_file": False, "file_no": None, "file_sha256": None} + return {"file_status": "ready", "has_ready_file": True, "file_no": "a.xlsx", "file_sha256": "abc"} + + monkeypatch.setattr(api_module, "trigger_inbound_rpa_batch", fail_inbound) + monkeypatch.setattr(api_module, "trigger_outbound_rpa_batch", record_outbound) + monkeypatch.setattr(api_module, "resolve_source_file_status", status) + response = client.post("/api/in-transit-transfer/sources/retry-rpa-batch", json={ + "source_codes": ["DSV360_AWSBI"], + "transfer_type": "hub_to_hub", + }, headers=admin_headers) + # 断言意图:入站 ready 不进 trigger;出站 none 只写出站 batch,并回 202。 + assert response.status_code == 202 + assert called["codes"] == ["DSV360_AWSBI"] + + +def test_retry_rpa_outbound_triggers_outbound_rpa(app, client, admin_headers, monkeypatch): + """单源重试带 record_kind=outbound 时走出站触发,不碰入站。""" + called = {} + + def fail_inbound(**kwargs): + raise AssertionError("inbound") + + def record_outbound(**kwargs): + called["source_code"] = kwargs["source_code"] + called["reason"] = kwargs["reason"] + return {"ok": True, "callback_id": "cb-out"} + + monkeypatch.setattr( + "app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_rpa", + fail_inbound, + ) + monkeypatch.setattr( + "app.services.in_transit_transfer.outbound_trigger_service.trigger_outbound_rpa", + record_outbound, + ) + monkeypatch.setattr( + "app.services.in_transit_transfer.source_file_status.resolve_source_file_status", + lambda *, source_code, record_kind="inbound": _stream_status("none"), + ) + response = client.post( + f"{API_PREFIX}/sources/DSV360_AWSBI/retry-rpa", + headers=admin_headers, + json={"record_kind": "outbound"}, + ) + # 断言意图:缺省才是入站;显式 outbound 必须 202 且 reason 为出站重试。 + assert response.status_code == 202 + assert called["source_code"] == "DSV360_AWSBI" + assert called["reason"] == "transfer_retry_outbound" + assert response.get_json()["data"]["file_status"] == "fetching" + + +def test_retry_rpa_outbound_parse_failed_retriggers_outbound_rpa(app, client, admin_headers, monkeypatch): + """出站 parse_failed 重新触发出站 RPA,不走入站本地重解析。""" + called = {"sync": 0, "outbound": 0} + + def status(*, source_code, record_kind="inbound"): + if record_kind == "outbound": + return _stream_status("parse_failed") + return _stream_status("ready") + + def fake_sync(**kwargs): + called["sync"] += 1 + return True + + def fail_inbound(**kwargs): + raise AssertionError("inbound") + + def record_outbound(**kwargs): + called["outbound"] += 1 + return {"ok": True, "callback_id": "cb-out"} + + monkeypatch.setattr( + "app.services.in_transit_transfer.source_file_status.resolve_source_file_status", + status, + ) + monkeypatch.setattr( + "app.services.in_transit_transfer.evidence_sync.sync_and_commit_for_callback", + fake_sync, + ) + monkeypatch.setattr( + "app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_rpa", + fail_inbound, + ) + monkeypatch.setattr( + "app.services.in_transit_transfer.outbound_trigger_service.trigger_outbound_rpa", + record_outbound, + ) + response = client.post( + f"{API_PREFIX}/sources/DSV360_AWSBI/retry-rpa", + headers=admin_headers, + json={"record_kind": "outbound"}, + ) + # 断言意图:本地重解析只留给入站;出站解析失败仍是一次 RPA 重抓。 + assert response.status_code == 202 + assert called["sync"] == 0 + assert called["outbound"] == 1 + + +def test_batch_retry_records_unconfigured_without_trigger(app, client, admin_headers, monkeypatch): + """未配置的流不写 trigger,结果 ok=false 且沿用既有配置缺失码。""" + _ensure_hub_to_hub_both_streams() + called = {} + + def record_inbound(**kwargs): + called["inbound"] = list(kwargs["source_codes"]) + return {"ok": True, "triggered": True, "results": []} + + def record_outbound(**kwargs): + called["outbound"] = list(kwargs["source_codes"]) + return {"ok": True, "triggered": True, "results": []} + + monkeypatch.setattr( + "app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_rpa_batch", + record_inbound, + ) + monkeypatch.setattr( + "app.services.in_transit_transfer.outbound_trigger_service.trigger_outbound_rpa_batch", + record_outbound, + ) + monkeypatch.setattr( + "app.services.in_transit_transfer.source_file_status.resolve_source_file_status", + lambda *, source_code, record_kind="inbound": _stream_status("unconfigured"), + ) + response = client.post( + f"{API_PREFIX}/sources/retry-rpa-batch", + headers=admin_headers, + json={"source_codes": ["DSV360_AWSBI"], "transfer_type": "hub_to_hub"}, + ) + # 断言意图:两条流都是 unconfigured 时两个 batch 都不写,并各记配置缺失码。 + assert response.status_code == 200 + assert "inbound" not in called and "outbound" not in called + body = response.get_json()["data"] + assert body["ok"] is False + assert body["triggered"] is False + assert body["results"] == [ + { + "source_code": "DSV360_AWSBI", + "record_kind": "inbound", + "ok": False, + "error_code": "RPA_INBOUND_CONFIG_MISSING", + }, + { + "source_code": "DSV360_AWSBI", + "record_kind": "outbound", + "ok": False, + "error_code": "RPA_OUTBOUND_CONFIG_MISSING", + }, + ] + + +def test_batch_retry_skips_fetching_stream(app, client, admin_headers, monkeypatch): + """抓取中的流不写入 trigger。""" + _ensure_hub_to_hub_both_streams() + called = {} + + def record(**kwargs): + called["codes"] = list(kwargs["source_codes"]) + return {"ok": True, "triggered": True, "results": []} + + monkeypatch.setattr( + "app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_rpa_batch", + record, + ) + monkeypatch.setattr( + "app.services.in_transit_transfer.outbound_trigger_service.trigger_outbound_rpa_batch", + record, + ) + + def status(*, source_code, record_kind="inbound"): + if record_kind == "outbound": + return _stream_status("fetching") + return _stream_status("ready") + + monkeypatch.setattr( + "app.services.in_transit_transfer.source_file_status.resolve_source_file_status", + status, + ) + response = client.post( + f"{API_PREFIX}/sources/retry-rpa-batch", + headers=admin_headers, + json={"source_codes": ["DSV360_AWSBI"], "transfer_type": "hub_to_hub"}, + ) + # 断言意图:ready 与 fetching 都跳过,不回 202,结果为空。 + assert response.status_code == 200 + assert called == {} + body = response.get_json()["data"] + assert body["ok"] is True + assert body["triggered"] is False + assert body["results"] == [] + + +def test_batch_retry_groups_one_batch_per_stream(app, client, admin_headers, monkeypatch): + """同一请求最多一个入站 batch 和一个出站 batch,结果带 record_kind。""" + _ensure_hub_to_hub_both_streams() + calls = [] + + def record_inbound(**kwargs): + calls.append(("inbound", list(kwargs["source_codes"]), kwargs["reason"])) + return { + "ok": True, + "triggered": True, + "results": [{"source_code": code, "ok": True} for code in kwargs["source_codes"]], + } + + def record_outbound(**kwargs): + calls.append(("outbound", list(kwargs["source_codes"]), kwargs["reason"])) + return { + "ok": True, + "triggered": True, + "results": [{"source_code": code, "ok": True} for code in kwargs["source_codes"]], + } + + monkeypatch.setattr( + "app.services.in_transit_transfer.inbound_trigger_service.trigger_inbound_rpa_batch", + record_inbound, + ) + monkeypatch.setattr( + "app.services.in_transit_transfer.outbound_trigger_service.trigger_outbound_rpa_batch", + record_outbound, + ) + monkeypatch.setattr( + "app.services.in_transit_transfer.source_file_status.resolve_source_file_status", + lambda *, source_code, record_kind="inbound": _stream_status("none"), + ) + response = client.post( + f"{API_PREFIX}/sources/retry-rpa-batch", + headers=admin_headers, + json={ + "source_codes": ["DSV360_AWSBI", "DSV360_AWSDU"], + "transfer_type": "hub_to_hub", + }, + ) + # 断言意图:两个来源按流合并成各一次 batch,而不是逐来源各写一个文件。 + assert response.status_code == 202 + assert calls == [ + ("inbound", ["DSV360_AWSBI", "DSV360_AWSDU"], "transfer_retry_inbound"), + ("outbound", ["DSV360_AWSBI", "DSV360_AWSDU"], "transfer_retry_outbound"), + ] + pairs = { + (item["source_code"], item["record_kind"]) + for item in response.get_json()["data"]["results"] + } + assert pairs == { + ("DSV360_AWSBI", "inbound"), + ("DSV360_AWSBI", "outbound"), + ("DSV360_AWSDU", "inbound"), + ("DSV360_AWSDU", "outbound"), + } + + def test_metrics_endpoint(app, transfer_db, client, admin_headers, transfer_deps): """运营指标端点:返回 Run/明细/待处理/通知失败结构。""" response = client.get(f"{API_PREFIX}/metrics", headers=admin_headers) @@ -685,7 +1220,7 @@ def test_requery_items_returns_envelope(app, client, admin_headers, monkeypatch, created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={ "source_codes": ["DBS-AWSBI"], - "business_date": "2026-08-06", + "business_date": "2026-08-06", "transfer_type": "in_transit_to_hub" }) matching_no = created.get_json()["data"]["matching_id"] @@ -808,7 +1343,7 @@ def test_retrigger_endpoint_requires_authentication(client): # T11:202 契约收口 + GET /runs/{run_no} 调拨单清单(orders)投影(D9 融合卡数据源) # --------------------------------------------------------------------------- -def _receipt_row(row_no: int, doc_no: str, lot_no: str, material: str, +def _movement_row(row_no: int, doc_no: str, lot_no: str, material: str, movement_date: str, quantity: str, *, unit: str = "PCS", material_name: str | None = None) -> dict: """构造一条收料文件行(movement 字段键;多单场景自定义行集用)。""" @@ -828,7 +1363,7 @@ def _custom_transfer_deps(monkeypatch, rows: list[dict], stocks: list[tuple[str, """ file_payload = { "source_code": "DBS-AWSBI", "business_date": "2026-08-06", - "file_purpose": "receipt", "file_no": "REC-T11", "file_version": "v11", + "file_purpose": "inbound", "file_no": "REC-T11", "file_version": "v11", "checksum": "d" * 64, "status": "ready", "rows": rows, } deps, erp, _ = make_transfer_deps(file_payload) @@ -838,8 +1373,9 @@ def _custom_transfer_deps(monkeypatch, rows: list[dict], stocks: list[tuple[str, seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps) - def _resolve(*, source_code: str) -> dict: + def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict: # 执行门禁②(文件版本对账)替身:与 transfer_deps 夹具同语义。 + del record_kind return {"file_status": "ready", "has_ready_file": True, "file_no": "REC-TEST", "file_sha256": "d" * 64} @@ -888,9 +1424,10 @@ def test_run_projection_returns_order_list_with_multi_status( monkeypatch, rows=[ # 三张单:收料日期入 D1 组键 → 三个组各一单(组建单按组键升序)。 - _receipt_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500", unit="个"), - _receipt_row(2, "HOX-B", "LOT-20", "MAT-002", "2026-08-04", "700", unit="PCS"), - _receipt_row(3, "HOX-C", "LOT-30", "MAT-003", "2026-08-03", "300.25", unit="KG"), + # 日期均 ≤ 业务日 08-06 的 T−2 成熟边界(08-05 为 T−1 会被圈档封顶排除)。 + _movement_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-04", "500", unit="个"), + _movement_row(2, "HOX-B", "LOT-20", "MAT-002", "2026-08-03", "700", unit="PCS"), + _movement_row(3, "HOX-C", "LOT-30", "MAT-003", "2026-08-02", "300.25", unit="KG"), ], stocks=[("MAT-001", "LOT-10", "500"), ("MAT-002", "LOT-20", "700"), ("MAT-003", "LOT-30", "300.25")], @@ -912,7 +1449,7 @@ def test_run_projection_returns_order_list_with_multi_status( assert len(orders) == 3 # 断言意图:单序稳定(2026-09-29 投影排序=收料日期→数据源→库位;本例同数据源, # 收料日期升序,与建单的组键序一致)。 - assert [t["receipt_date"] for t in orders] == ["2026-08-03", "2026-08-04", "2026-08-05"] + assert [t["movement_date"] for t in orders] == ["2026-08-02", "2026-08-03", "2026-08-04"] by_status = {t["status"]: t for t in orders} assert set(by_status) == {"success", "business_failed", "result_unknown"} @@ -922,11 +1459,11 @@ def test_run_projection_returns_order_list_with_multi_status( # (+invoice_no:行级溯源收料通知号 2026-09-29 契约扩充;含 reason:框线图 # 失败行原因展示契约,控制器裁决扩充,T13-3)。 assert set(success.keys()) == { - "doc_no", "receipt_date", "from_warehouse", "to_warehouse", + "doc_no", "movement_date", "from_warehouse", "to_warehouse", "status", "erp_document_no", "error_message", "lines", } assert success["doc_no"].startswith("HX-CN01-OR-") - assert success["receipt_date"] == "2026-08-05" + assert success["movement_date"] == "2026-08-04" assert success["from_warehouse"] == "DBS-TRANSIT" assert success["to_warehouse"] == "HUB-CN01" assert success["erp_document_no"] @@ -972,7 +1509,7 @@ def test_run_projection_order_lines_include_reused_order_old_and_new_rows( """复用单行集全量投影:失败单复用后,旧行与新行都在 orders.lines(D7①②)。""" deps, erp = _custom_transfer_deps( monkeypatch, - rows=[_receipt_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500", unit="个")], + rows=[_movement_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-04", "500", unit="个")], stocks=[("MAT-001", "LOT-10", "500")], ) erp.write_scenarios["HOM-A"] = "business_failed" @@ -989,8 +1526,8 @@ def test_run_projection_order_lines_include_reused_order_old_and_new_rows( _custom_transfer_deps( monkeypatch, rows=[ - _receipt_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500", unit="个"), - _receipt_row(3, "HOM-C", "LOT-30", "MAT-003", "2026-08-05", "300", unit="PCS"), + _movement_row(1, "HOM-A", "LOT-10", "MAT-001", "2026-08-04", "500", unit="个"), + _movement_row(3, "HOM-C", "LOT-30", "MAT-003", "2026-08-04", "300", unit="PCS"), ], stocks=[("MAT-001", "LOT-10", "500"), ("MAT-003", "LOT-30", "300")], ) @@ -1047,7 +1584,7 @@ def _seed_document( five = {key: (group or {}).get(key) or default for key, default in ( ("source_code", "DBS-AWSBI"), ("external_org", "ORGA"), - ("receipt_date", "2026-08-05"), + ("movement_date", "2026-08-05"), ("from_warehouse", "DBS-TRANSIT"), ("to_warehouse", f"HUB-{doc_no}"), )} @@ -1071,10 +1608,10 @@ def _seed_document( material_no=spec.get("material_no", f"MAT-{index}"), material_name=spec.get("material_name", f"物料{index}"), lot_no=spec.get("lot_no", "LOT-1"), - receipt_date=five["receipt_date"], + movement_date=five["movement_date"], from_warehouse=five["from_warehouse"], to_warehouse=five["to_warehouse"], - receipt_quantity=spec.get("quantity", "10"), + movement_quantity=spec.get("quantity", "10"), unit=spec.get("unit", "PCS"), status=spec.get("status", "executing"), result_code=spec.get("result_code"), @@ -1170,7 +1707,7 @@ def test_list_documents_order_projection_and_items(app, transfer_db, client, adm assert data["total"] == 1 order = data["orders"][0] # 断言意图:计划 Task 17 响应契约逐键——单头字段 + items(invoice 粒度)。 - for key in ("doc_no", "submit_timestamp", "status", "status_group", "receipt_date", + for key in ("doc_no", "submit_timestamp", "status", "status_group", "movement_date", "from_warehouse", "to_warehouse", "erp_document_no", "error_message", "created_at", "items"): assert key in order @@ -1237,10 +1774,10 @@ def test_list_documents_date_range_filters_list_only(app, transfer_db, client, a 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"}, + group={"movement_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"}, + group={"movement_date": "2026-09-23"}, created_at=now - timedelta(days=1)) transfer_db.session.commit() @@ -1285,7 +1822,7 @@ def test_close_document_detaches_items_and_releases_group_lock( from app.models import TransferAuditEvent, TransferDocument, TransferInvoiceItem group = { - "source_code": "DBS-AWSBI", "external_org": "ORGA", "receipt_date": "2026-08-05", + "source_code": "DBS-AWSBI", "external_org": "ORGA", "movement_date": "2026-08-05", "from_warehouse": "DBS-TRANSIT", "to_warehouse": "HUB-CN01", } with app.app_context(): @@ -1424,3 +1961,297 @@ def test_document_run_no_projection_and_audit_with_real_run( event = TransferAuditEvent.query.filter_by(event_type="TRANSFER_DOCUMENT_CLOSED").one() assert event.aggregate_id == "D-RUN-1" assert event.run_no == "RUN-DOC-REAL-1" + + +# --------------------------------------------------------------------------- +# Task 5:证据压缩包按记录类型分目录;当天清单只列可用文件的大小与预签地址 +# --------------------------------------------------------------------------- + +EVIDENCE_SOURCE = "DSV360_AWSBI" +_INBOUND_ONLY_TYPE = "evidence_inbound_only" + + +def _ensure_inbound_only_type(): + """启用一个范围规则把记录类型收成只要 inbound 的调拨类型。 + + 核心逻辑:没有 record_kinds 列。equals inbound 的 record_kind 规则经 + record_kinds_of 只得到入站。已存在则复用。 + """ + from app.core.errors import ValidationError + from app.services.in_transit_transfer.transfer_type_config_service import ( + create_config, + get_by_code, + ) + + try: + return get_by_code(_INBOUND_ONLY_TYPE) + except ValidationError: + return create_config({ + "code": _INBOUND_ONLY_TYPE, + "names": {"zh-CN": "仅入站证据"}, + "enabled": True, + "scope_rules": [ + {"field": "record_kind", "match": "equals", "values": ["inbound"]}, + ], + }) + + +def _ensure_evidence_source(): + """保证 DSV360_AWSBI 来源存在(压缩包路径用这个编码)。""" + from tests.services.in_transit_transfer.factories import seed_inbound_reparse_source + + source, _profile = seed_inbound_reparse_source(EVIDENCE_SOURCE) + return source + + +def _seed_evidence_file( + source, + *, + kind: str, + filename: str, + storage_key: str, + sha: str, + file_size: int, + created_at: datetime, + deleted: bool = False, +): + """写入一条入站或出站归档。created_at 决定是否落在当天可用窗口。""" + from app.models import ( + FreightRpaInboundReportFile, + FreightRpaInboundUnitRun, + FreightRpaOutboundReportFile, + FreightRpaOutboundUnitRun, + ) + + if kind == "outbound": + unit_model, file_model = FreightRpaOutboundUnitRun, FreightRpaOutboundReportFile + else: + unit_model, file_model = FreightRpaInboundUnitRun, FreightRpaInboundReportFile + unit = unit_model( + source_id=source.id, + source_code=source.source_code, + connector_type=source.connector_type, + warehouse_id=source.fixed_warehouse_id, + callback_id=f"{kind}-{sha[:16]}", + status="success", + config_snapshot_json={}, + trigger_snapshot_json={}, + result_json={}, + ) + db.session.add(unit) + db.session.flush() + report = file_model( + unit_run_id=unit.id, + storage_provider="minio", + storage_bucket="test", + storage_key=storage_key, + original_filename=filename, + file_size=file_size, + sha256=sha, + created_at=created_at, + archive_deleted_at=created_at if deleted else None, + ) + db.session.add(report) + db.session.commit() + return report + + +def _patch_archive_bytes(monkeypatch, objects: dict[str, bytes]) -> None: + """用内存字节替换对象存储读取,避免下载测试连接 MinIO。""" + monkeypatch.setattr( + "app.services.file_assets.storage.file_asset_storage.get_bytes", + lambda storage_key: objects[storage_key], + ) + + +def _zip_entries(response) -> dict[str, bytes]: + """用 zipfile 读响应体,返回归档路径到原始字节。""" + import io + import zipfile + + with zipfile.ZipFile(io.BytesIO(response.data)) as archive: + return {name: archive.read(name) for name in archive.namelist()} + + +def test_evidence_zip_packs_inbound_only_when_scope_rule_equals_inbound( + app, client, admin_headers, monkeypatch, +): + """范围规则 record_kind equals inbound 时,压缩包只有入站最新文件。""" + from datetime import timedelta + + now = datetime.utcnow().replace(microsecond=0) + source = _ensure_evidence_source() + _ensure_inbound_only_type() + _seed_evidence_file( + source, kind="inbound", filename="OldInbound.xlsx", + storage_key="evidence/old-inbound", sha="31" * 32, file_size=10, + created_at=now - timedelta(minutes=10), + ) + _seed_evidence_file( + source, kind="inbound", filename="Inbound.xlsx", + storage_key="evidence/inbound", sha="11" * 32, file_size=12, + created_at=now, + ) + _seed_evidence_file( + source, kind="outbound", filename="Outbound.xlsx", + storage_key="evidence/outbound", sha="22" * 32, file_size=13, + created_at=now, + ) + _patch_archive_bytes(monkeypatch, { + "evidence/old-inbound": b"OLD-INBOUND", + "evidence/inbound": b"INBOUND-RAW", + "evidence/outbound": b"OUTBOUND-RAW", + }) + + response = client.post( + f"{API_PREFIX}/sources/inbound-files", + headers=admin_headers, + json={"source_codes": [EVIDENCE_SOURCE], "transfer_type": _INBOUND_ONLY_TYPE}, + ) + + assert response.status_code == 200 + entries = _zip_entries(response) + # 断言意图:目录是记录类型/来源/文件名,且只打最新一份入站,不打出站。 + assert entries == {f"inbound/{EVIDENCE_SOURCE}/Inbound.xlsx": b"INBOUND-RAW"} + assert not any(name.startswith("outbound/") for name in entries) + assert "evidence-files-1.zip" in response.headers.get("Content-Disposition", "") + with app.app_context(): + from app.models import TransferAuditEvent + + audit = TransferAuditEvent.query.filter_by( + event_type="TRANSFER_INBOUND_FILES_DOWNLOADED", + ).one() + assert audit.aggregate_id == EVIDENCE_SOURCE + + +def test_evidence_zip_packs_both_kinds_without_record_kind_rule( + app, client, admin_headers, monkeypatch, +): + """没有 record_kind 范围规则时,入站和出站就绪文件都打进包。""" + now = datetime.utcnow().replace(microsecond=0) + source = _ensure_evidence_source() + _seed_evidence_file( + source, kind="inbound", filename="Inbound.xlsx", + storage_key="evidence/both-inbound", sha="41" * 32, file_size=12, + created_at=now, + ) + _seed_evidence_file( + source, kind="outbound", filename="Outbound.xlsx", + storage_key="evidence/both-outbound", sha="42" * 32, file_size=13, + created_at=now, + ) + _patch_archive_bytes(monkeypatch, { + "evidence/both-inbound": b"INBOUND-RAW", + "evidence/both-outbound": b"OUTBOUND-RAW", + }) + + response = client.post( + f"{API_PREFIX}/sources/inbound-files", + headers=admin_headers, + json={"source_codes": [EVIDENCE_SOURCE], "transfer_type": "in_transit_to_hub"}, + ) + + assert response.status_code == 200 + entries = _zip_entries(response) + # 断言意图:默认类型只有单号前缀规则,两种就绪文件都按记录类型分目录。 + assert entries == { + f"inbound/{EVIDENCE_SOURCE}/Inbound.xlsx": b"INBOUND-RAW", + f"outbound/{EVIDENCE_SOURCE}/Outbound.xlsx": b"OUTBOUND-RAW", + } + assert "evidence-files-2.zip" in response.headers.get("Content-Disposition", "") + with app.app_context(): + from app.models import TransferAuditEvent + + audit = TransferAuditEvent.query.filter_by( + event_type="TRANSFER_INBOUND_FILES_DOWNLOADED", + ).one() + assert audit.event_type == "TRANSFER_INBOUND_FILES_DOWNLOADED" + + +def test_evidence_files_list_returns_today_size_and_presigned_url( + app, client, admin_headers, monkeypatch, +): + """当天清单返回全部可用入站文件的大小与预签地址,不解析行数。""" + from datetime import timedelta + + now = datetime.utcnow().replace(microsecond=0) + source = _ensure_evidence_source() + newer = _seed_evidence_file( + source, kind="inbound", filename="Inbound.xlsx", + storage_key="evidence/list-new", sha="51" * 32, file_size=111, + created_at=now, + ) + older = _seed_evidence_file( + source, kind="inbound", filename="Older.xlsx", + storage_key="evidence/list-old", sha="52" * 32, file_size=222, + created_at=now - timedelta(minutes=20), + ) + _seed_evidence_file( + source, kind="inbound", filename="Yesterday.xlsx", + storage_key="evidence/list-yesterday", sha="53" * 32, file_size=333, + created_at=now - timedelta(days=2), + ) + _seed_evidence_file( + source, kind="inbound", filename="Deleted.xlsx", + storage_key="evidence/list-deleted", sha="54" * 32, file_size=444, + created_at=now, deleted=True, + ) + signed = [] + + def _presign(storage_key, *, expires_seconds, download_name=None): + signed.append((storage_key, expires_seconds, download_name)) + if download_name: + return f"https://files.test/{storage_key}?filename={download_name}" + return f"https://files.test/{storage_key}" + + monkeypatch.setattr( + "app.services.file_assets.storage.file_asset_storage.presigned_get_url", + _presign, + ) + + response = client.get( + f"{API_PREFIX}/sources/{EVIDENCE_SOURCE}/evidence-files?record_kind=inbound", + headers=admin_headers, + ) + + assert response.status_code == 200 + rows = response.get_json()["data"] + # 断言意图:当天两份都在,隔日与已清理不在;字段是文件大小和预签地址,没有行数。 + assert [row["original_filename"] for row in rows] == ["Inbound.xlsx", "Older.xlsx"] + assert rows[0]["file_id"] == newer.id + assert rows[1]["file_id"] == older.id + assert rows[0]["file_size"] == 111 + assert rows[1]["file_size"] == 222 + assert rows[0]["sha256"] == "51" * 32 + assert rows[0]["created_at"] == now.isoformat() + assert rows[0]["presigned_url"] == "https://files.test/evidence/list-new" + assert rows[1]["presigned_url"] == "https://files.test/evidence/list-old" + from app.api.in_transit_transfer import evidence_download_filename + + # [断言意图] 保存名是库存源加东八区年月日和时分,不用对象键哈希。 + # 02:57 UTC 在上海是当天 10:57;16:30 UTC 已跨到上海次日 00:30。预览地址不带附件名。 + assert evidence_download_filename("CRANE", datetime(2026, 10, 22, 2, 57), "hash.xlsx") == "CRANE_20261022_1057.xlsx" + assert evidence_download_filename("CRANE", datetime(2026, 10, 21, 16, 30), "a.csv") == "CRANE_20261022_0030.csv" + newer_name = evidence_download_filename(EVIDENCE_SOURCE, now, "Inbound.xlsx") + older_name = evidence_download_filename(EVIDENCE_SOURCE, now - timedelta(minutes=20), "Older.xlsx") + assert rows[0]["download_url"] == f"https://files.test/evidence/list-new?filename={newer_name}" + assert rows[1]["download_url"] == f"https://files.test/evidence/list-old?filename={older_name}" + for row in rows: + assert set(row) == { + "file_id", "original_filename", "created_at", "sha256", "file_size", + "presigned_url", "download_url", + } + assert "rows" not in row and "row_count" not in row + assert signed == [ + ("evidence/list-new", 300, None), + ("evidence/list-new", 300, newer_name), + ("evidence/list-old", 300, None), + ("evidence/list-old", 300, older_name), + ] + with app.app_context(): + from app.models import TransferAuditEvent + + audit = TransferAuditEvent.query.filter_by( + event_type="TRANSFER_INBOUND_FILES_DOWNLOADED", + ).one() + assert audit.aggregate_id == EVIDENCE_SOURCE diff --git a/backend/tests/api/test_transfer_type_api.py b/backend/tests/api/test_transfer_type_api.py new file mode 100644 index 00000000..9deea9ab --- /dev/null +++ b/backend/tests/api/test_transfer_type_api.py @@ -0,0 +1,336 @@ +"""调拨类型 API 契约测试(admin CRUD + chat 最小暴露列表 + 四语言错误码)。 + +用途:锁定调拨类型配置两个 API 入口的外部契约——admin 列表/创建/更新 + (平台管理员、重复 code 与并发唯一键冲突统一 422、code 不可变 422、 + enabled/sort_order 参数形态门禁),chat GET /transfer-types(仅启用、 + 最小暴露、Agent 权限即可不要求平台管理员),以及四语言 errors.json + 与后端稳定错误码同 key 集。 +依赖:app/client 夹具、issue_local_access_token、transfer_type_config_service + (前置数据走服务层唯一写入入口)。 +逻辑:服务层校验契约由 test_transfer_type_config_service.py 覆盖,本文件只测 + API 壳(鉴权/状态码映射/序列化暴露面/i18n 文案登记)。 +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from sqlalchemy.exc import IntegrityError + +from app import db +from app.core.auth.jwt import issue_local_access_token +from app.models import Agent, User +from app.services.in_transit_transfer.transfer_type_config_service import ( + create_config as create_type_config, +) + +ADMIN_PREFIX = "/api/admin/in-transit-transfer/transfer-types" +CHAT_PREFIX = "/api/in-transit-transfer/transfer-types" + +# 四语言 errors.json 必须与后端稳定错误码保持同 key 集(前端文案映射契约)。 +EXPECTED_ERROR_KEYS = ( + "TRANSFER.TRANSFER_TYPE_REQUIRED", + "TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED", + "TRANSFER.TRANSFER_TYPE_DISABLED", + "TRANSFER.TRANSFER_TYPE_CODE_EXISTS", + "TRANSFER.TRANSFER_TYPE_CODE_IMMUTABLE", + "TRANSFER.SCOPE_RULE_INVALID", + "TRANSFER.WAREHOUSE_CONFIG_INVALID", + "TRANSFER.TRANSFORM_RULE_INVALID", +) + +# [FIXTURE] 合法创建载荷基线(与 test_transfer_type_config_service.VALID_PAYLOAD 同构)。 +VALID_PAYLOAD = { + "code": "in_transit_to_hub", + "names": {"zh-CN": "在途仓至HUB仓", "en": "In-transit to Hub"}, + "enabled": True, + "sort_order": 10, + "scope_rules": [ + {"field": "doc_no", "match": "prefix", "values": ["HOM", "HOX", "WTP"]}, + ], + "warehouse_config": { + "from": {"mode": "mapped"}, + "to": {"mode": "mapped"}, + }, + "transform_rules": [ + {"field": "lot_no", "op": "prefix_replace", "source": "wtp", "target": "HOW"}, + ], + "description": "一期默认类型", +} + + +def _headers(user: User) -> dict: + """为指定用户签发 Bearer JWT 请求头(须在 app context 内调用)。""" + token = issue_local_access_token(user) + return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} + + +def _seed_type(**overrides) -> None: + """按基线载荷落一个类型配置(API 测试前置数据,走服务层唯一写入入口)。""" + create_type_config({**VALID_PAYLOAD, **overrides}) + + +@pytest.fixture +def admin_headers(app): + """平台管理员 JWT 请求头(token 在 app context 内签发)。""" + 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() + return _headers(user) + + +@pytest.fixture +def warehouse_headers(app): + """持有 in_transit_transfer Agent 权限的仓库管理员 JWT 请求头(非平台管理员)。""" + with app.app_context(): + agent = Agent.query.filter_by(agent_code="in_transit_transfer").first() + if not agent: + agent = Agent(name="在途仓调拨", agent_code="in_transit_transfer", + type="api", is_active=True) + db.session.add(agent) + db.session.flush() + user = db.session.query(User).filter_by(username="warehouse").first() + if not user: + user = User(username="warehouse", email="warehouse@example.com", + role="user", status="active") + user.set_password("x") + db.session.add(user) + db.session.flush() + if agent not in user.agents: + user.agents.append(agent) + db.session.commit() + return _headers(user) + + +@pytest.fixture +def unauthorized_headers(app): + """已认证但无 Agent 权限的普通用户 JWT 请求头。""" + with app.app_context(): + user = db.session.query(User).filter_by(username="no_perm").first() + if not user: + user = User(username="no_perm", email="no_perm@example.com", role="user", status="active") + user.set_password("x") + db.session.add(user) + db.session.commit() + return _headers(user) + + +# --------------------------------------------------------------------------- +# admin CRUD(平台管理员) +# --------------------------------------------------------------------------- + + +def test_admin_create_returns_201_with_normalized_config(app, client, admin_headers): + """POST 创建 → 201 envelope;三块配置经服务层规范化后回读(transform 大写化)。""" + response = client.post(ADMIN_PREFIX, headers=admin_headers, json=VALID_PAYLOAD) + assert response.status_code == 201 + body = response.get_json() + assert body["success"] is True + assert body.get("request_id") + data = body["data"] + assert data["code"] == "in_transit_to_hub" + assert data["names"]["zh-CN"] == "在途仓至HUB仓" + assert data["enabled"] is True + assert data["sort_order"] == 10 + # [断言意图] scope_rules/transform_rules 是引擎规范化产物(source/target 统一大写), + # 前端编辑表单依赖该形态回显,形态漂移必须显式同步。 + assert data["scope_rules"] == [ + {"field": "doc_no", "match": "prefix", "values": ["HOM", "HOX", "WTP"]}, + ] + assert data["transform_rules"] == [ + {"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"}, + ] + assert data["warehouse_config"]["from"]["mode"] == "mapped" + assert data["description"] == "一期默认类型" + assert data["updated_at"].endswith("Z") + + +def test_admin_list_returns_configs_including_disabled(app, client, admin_headers): + """GET 列表 → 全量配置(含停用项),sort_order 升序;管理端可见三块配置。""" + _seed_type(sort_order=20) + _seed_type(code="hub_to_line", enabled=False, sort_order=10, description="停用类型") + response = client.get(ADMIN_PREFIX, headers=admin_headers) + assert response.status_code == 200 + body = response.get_json() + assert body["success"] is True + data = body["data"] + assert [item["code"] for item in data] == ["hub_to_line", "in_transit_to_hub"] + assert {item["enabled"] for item in data} == {True, False} + # [断言意图] 管理列表是全量视图(与 chat 最小暴露相对):三块配置均必须可见。 + for key in ("scope_rules", "warehouse_config", "transform_rules", "description"): + assert key in data[0] + + +def test_admin_update_partial_keeps_other_fields(app, client, admin_headers): + """PUT 部分更新:提供的字段生效,未提供的字段保持原值。""" + _seed_type() + response = client.put( + f"{ADMIN_PREFIX}/in_transit_to_hub", headers=admin_headers, + json={"enabled": False, "sort_order": 5}, + ) + assert response.status_code == 200 + data = response.get_json()["data"] + assert data["enabled"] is False + assert data["sort_order"] == 5 + assert data["description"] == "一期默认类型" + + +def test_admin_requires_platform_admin(app, client, unauthorized_headers): + """admin 端点:已认证但非平台管理员 → 403。""" + response = client.get(ADMIN_PREFIX, headers=unauthorized_headers) + assert response.status_code == 403 + assert response.get_json()["error"]["code"] == "AUTH.FORBIDDEN" + + +def test_admin_create_duplicate_code_maps_422(app, client, admin_headers): + """重复 code → 422 + TRANSFER.TRANSFER_TYPE_CODE_EXISTS(服务层预检路径)。""" + client.post(ADMIN_PREFIX, headers=admin_headers, json=VALID_PAYLOAD) + response = client.post(ADMIN_PREFIX, headers=admin_headers, json=VALID_PAYLOAD) + assert response.status_code == 422 + assert response.get_json()["error"]["code"] == "TRANSFER.TRANSFER_TYPE_CODE_EXISTS" + + +def test_admin_create_concurrent_integrity_error_maps_422( + app, client, admin_headers, monkeypatch, +): + """并发兜底:预检通过后唯一键仍冲突(IntegrityError)→ 422 而非 500。""" + + def _raise(payload, operator_id=None): + raise IntegrityError("INSERT INTO transfer_type_configs", {}, Exception("UNIQUE constraint failed")) + + monkeypatch.setattr("app.api.admin.transfer_type.service.create_config", _raise) + response = client.post(ADMIN_PREFIX, headers=admin_headers, json=VALID_PAYLOAD) + assert response.status_code == 422 + assert response.get_json()["error"]["code"] == "TRANSFER.TRANSFER_TYPE_CODE_EXISTS" + + +def test_admin_update_code_immutable_maps_422(app, client, admin_headers): + """改 code(transfer_runs.transfer_type 引用其改名即断链)→ 422 + CODE_IMMUTABLE。""" + _seed_type() + response = client.put( + f"{ADMIN_PREFIX}/in_transit_to_hub", headers=admin_headers, + json={"code": "renamed_type"}, + ) + assert response.status_code == 422 + assert response.get_json()["error"]["code"] == "TRANSFER.TRANSFER_TYPE_CODE_IMMUTABLE" + + +def test_admin_update_unknown_code_maps_404(app, client, admin_headers): + """更新不存在的 code → 404 + TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED。""" + response = client.put(f"{ADMIN_PREFIX}/no_such_type", headers=admin_headers, json={"enabled": True}) + assert response.status_code == 404 + assert response.get_json()["error"]["code"] == "TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED" + + +def test_admin_create_rejects_string_enabled(app, client, admin_headers): + """API 层类型门禁:字符串 "false" 不得直通服务层被 bool() 强转为真值。""" + response = client.post(ADMIN_PREFIX, headers=admin_headers, json={**VALID_PAYLOAD, "enabled": "false"}) + assert response.status_code == 400 + assert response.get_json()["error"]["code"] == "VALIDATION.INVALID_PARAM" + + +def test_admin_create_rejects_string_sort_order(app, client, admin_headers): + """API 层类型门禁:sort_order 只接受整数,数字字符串拒绝。""" + response = client.post(ADMIN_PREFIX, headers=admin_headers, json={**VALID_PAYLOAD, "sort_order": "10"}) + assert response.status_code == 400 + assert response.get_json()["error"]["code"] == "VALIDATION.INVALID_PARAM" + + +def test_admin_update_rejects_string_enabled(app, client, admin_headers): + """API 层类型门禁同样作用于更新路径。""" + _seed_type() + response = client.put( + f"{ADMIN_PREFIX}/in_transit_to_hub", headers=admin_headers, json={"enabled": "true"}, + ) + assert response.status_code == 400 + assert response.get_json()["error"]["code"] == "VALIDATION.INVALID_PARAM" + + +def test_admin_create_rejects_non_object_body(app, client, admin_headers): + """body 为非对象 JSON(如数组)→ 400 参数错误,而非 500。""" + response = client.post(ADMIN_PREFIX, headers=admin_headers, json=["in_transit_to_hub"]) + assert response.status_code == 400 + assert response.get_json()["success"] is False + + +# --------------------------------------------------------------------------- +# chat 列表(Agent 权限,最小暴露) +# --------------------------------------------------------------------------- + + +def test_chat_transfer_types_returns_enabled_only_with_minimal_fields( + app, client, warehouse_headers, +): + """chat 列表:仅启用项、sort_order 升序、最小暴露,并附推导出的 record_kinds。""" + _seed_type(sort_order=20) + _seed_type( + code="hub_to_line", + sort_order=10, + scope_rules=[{"field": "record_kind", "match": "equals", "values": ["inbound"]}], + ) + _seed_type(code="disabled_type", enabled=False, sort_order=1) + response = client.get(CHAT_PREFIX, headers=warehouse_headers) + assert response.status_code == 200 + body = response.get_json() + assert body["success"] is True + data = body["data"] + # [断言意图] 仅 enabled 限定 + sort_order 升序是前端类型选择器的顺序契约。 + assert [item["code"] for item in data] == ["hub_to_line", "in_transit_to_hub"] + for item in data: + # [断言意图] 最小暴露:在原四键上只增加 record_kinds。scope_rules / + # warehouse_config / description 仍不回传。record_kinds 由 + # record_kinds_of 现算:hub_to_line 只写 inbound,另一条没有 + # 记录类型规则所以入站和出站都要。 + assert set(item.keys()) == { + "code", "names", "sort_order", "transform_rules", "record_kinds", + } + assert data[0]["record_kinds"] == ["inbound"] + assert data[1]["record_kinds"] == ["inbound", "outbound"] + assert data[0]["transform_rules"] == [ + {"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"}, + ] + + +def test_chat_transfer_types_agent_permission_sufficient(app, client, warehouse_headers): + """chat 列表不要求平台管理员:持有 in_transit_transfer Agent 权限即可。""" + _seed_type() + response = client.get(CHAT_PREFIX, headers=warehouse_headers) + assert response.status_code == 200 + assert len(response.get_json()["data"]) == 1 + + +def test_chat_transfer_types_requires_authentication(client): + """未认证 → 401。""" + response = client.get(CHAT_PREFIX) + assert response.status_code == 401 + assert response.get_json()["success"] is False + + +def test_chat_transfer_types_forbidden_without_permission(client, unauthorized_headers): + """已认证但无 Agent 权限 → 403。""" + response = client.get(CHAT_PREFIX, headers=unauthorized_headers) + assert response.status_code == 403 + assert response.get_json()["error"]["code"] == "AUTH.FORBIDDEN" + + +# --------------------------------------------------------------------------- +# 四语言 errors.json 文案登记 +# --------------------------------------------------------------------------- + + +def test_error_codes_present_in_all_locales(): + """四语言 errors.json 与后端稳定错误码同 key 集且文案非空。""" + repo_root = Path(__file__).resolve().parents[3] + for locale in ("zh-CN", "zh-TW", "en", "th"): + path = repo_root / "frontend" / "src" / "locales" / locale / "errors.json" + assert path.exists(), f"missing errors.json: {locale}" + codes = json.loads(path.read_text(encoding="utf-8"))["codes"] + for key in EXPECTED_ERROR_KEYS: + assert key in codes, f"{locale} missing {key}" + assert isinstance(codes[key], str) and codes[key].strip(), f"{locale}:{key} has empty copy" diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 15bdb420..6dcb568a 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -90,19 +90,19 @@ def _shipping_notice_stable_auto_config(request, monkeypatch): tmp_path / "shipping_notice" / "freight_rpa" / "upload_triggers" ) if request.node.get_closest_marker("auto_rpa"): - app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True + app.config["SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED"] = True app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready", + "app.services.freight_rpa.common.worker_heartbeat.assert_inventory_rpa_worker_ready", lambda: None, ) monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat.assert_freight_upload_rpa_ready", + "app.services.freight_rpa.common.worker_heartbeat.assert_freight_upload_rpa_ready", lambda: None, ) return - app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = False + app.config["SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED"] = False app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False # 货代自动上传默认 fail-closed;单测与产品默认一致关闭。 app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = False @@ -111,10 +111,10 @@ def _shipping_notice_stable_auto_config(request, monkeypatch): app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = False app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True - from app.services.shipping_notice.rpa_worker_heartbeat import reset_rpa_worker_heartbeat_state_for_tests + from app.services.freight_rpa.common.worker_heartbeat import reset_rpa_worker_heartbeat_state_for_tests reset_rpa_worker_heartbeat_state_for_tests() - from app.services.shipping_notice.rpa_worker_heartbeat_alert import reset_rpa_worker_alert_state_for_tests + from app.services.freight_rpa.common.worker_heartbeat_alert import reset_rpa_worker_alert_state_for_tests reset_rpa_worker_alert_state_for_tests() @@ -123,9 +123,9 @@ def _shipping_notice_stable_auto_config(request, monkeypatch): def _shipping_test_default_destination(monkeypatch, request): """ 为未提供目的地线索的发货通知单测注入 Dublin,以唯一命中 DSV360_AWSDU。 - 标记 inventory_source_gate 的用例跳过,避免干扰库存源门禁专项测试。 + 标记 onhand_source_gate 的用例跳过,避免干扰库存源门禁专项测试。 """ - if request.node.get_closest_marker("inventory_source_gate"): + if request.node.get_closest_marker("onhand_source_gate"): return from app.services.shipping_notice import extract as extract_mod @@ -170,9 +170,9 @@ def seed_task_inventory_source( owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, getattr(task, 'order_task_id', None)) if owner is None: raise ValueError('test task must be linked to ShippingOrderTask') - from app.services.shipping_notice.inventory_candidate_freeze_service import freeze_candidates_for_task - from app.services.shipping_notice.inventory_source_rules import InventorySourceAdjudication - from app.services.shipping_notice.inventory_source_repository import ( + from app.services.shipping_notice.onhand_candidate_freeze_service import freeze_candidates_for_task + from app.services.shipping_notice.onhand_source_rules import InventorySourceAdjudication + from app.services.shipping_notice.onhand_source_repository import ( get_database_inventory_source, inventory_sources_runtime_version, ) @@ -391,7 +391,7 @@ def seed_rpa_inventory_trigger( run_no: str = "RUN-TEST-001", trigger_path: str | None = None, ) -> None: - """测试辅助:写入 inventory_rpa_triggered 事件,供单任务回调 run_no 校验。""" + """测试辅助:写入 onhand_rpa_triggered 事件,供单任务回调 run_no 校验。""" from app import db from app.services.shipping_notice.tool_common import log_task_event @@ -401,7 +401,7 @@ def seed_rpa_inventory_trigger( trigger = trigger_path or f"inventory_export_batch_{run_no}.json" log_task_event( task, - "inventory_rpa_triggered", + "onhand_rpa_triggered", {"trigger": trigger, "run_no": run_no, "attempt": 1, "manual_retry_round": False}, ) @@ -448,10 +448,10 @@ def inventory_csv_with_warehouse( def batch_rpa_item_identity(task: "ShippingNotice") -> dict[str, str]: """构造 batch 成功回调 item 须携带的 Source/Warehouse 身份字段。""" - from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes - source_code = next(iter(task_frozen_inventory_source_codes(task)), '') + source_code = next(iter(task_frozen_onhand_source_codes(task)), '') source = get_database_inventory_source(source_code) or {} return { "source_code": str(source_code or ""), @@ -461,7 +461,7 @@ def batch_rpa_item_identity(task: "ShippingNotice") -> dict[str, str]: def scheduled_rpa_batch_item(source_code: str, **overrides) -> dict[str, str]: """构造定时 batch 成功回调 item 的 Source/Warehouse 身份(与数据库配置一致)。""" - from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source + from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source source = get_database_inventory_source(source_code) if not source: @@ -475,10 +475,10 @@ def scheduled_rpa_batch_item(source_code: str, **overrides) -> dict[str, str]: def v2_inventory_batch_payload(payload: dict) -> dict: - """测试构造器:补齐冻结 shipping_inventory_rpa.v2 回调 envelope。""" + """测试构造器:补齐冻结 freight_rpa.onhand.v1 回调 envelope。""" body = dict(payload or {}) run_no = str(body.get('batch_run_no') or body.get('run_no') or '').strip() - body.setdefault('schema_version', 'shipping_inventory_rpa.v2') + body.setdefault('schema_version', 'freight_rpa.onhand.v1') body.setdefault('callback_id', f'test-callback:{run_no or "unknown"}') body.setdefault('batch_run_no', run_no) return body @@ -492,13 +492,13 @@ def rpa_callback_payload( status: str = "success", ) -> dict: """构造通过单源 RPA v2 身份/run_no 校验的最小成功 payload。""" - from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source - from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes + from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source + from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes - source_code = next(iter(task_frozen_inventory_source_codes(task)), '') + source_code = next(iter(task_frozen_onhand_source_codes(task)), '') source = get_database_inventory_source(source_code) or {} return { - "schema_version": "shipping_inventory_rpa.v2", + "schema_version": "freight_rpa.onhand.v1", "callback_id": f"test-callback:{run_no}", "task_id": task.task_no, "status": status, @@ -528,7 +528,7 @@ def pytest_configure(config): ) config.addinivalue_line( "markers", - "inventory_source_gate: 库存源门禁专项测试,跳过默认 Dublin 注入", + "onhand_source_gate: 库存源门禁专项测试,跳过默认 Dublin 注入", ) config.addinivalue_line( "markers", @@ -572,13 +572,17 @@ def app(): def _seed_test_inventory_configuration() -> None: - """为发货测试创建数据库库存源与发布路由规则,测试运行期不读取 YAML。""" + """为发货测试创建数据库库存源、在手报表配置与发布路由规则,测试运行期不读取 YAML。 + + s18 起:报表路径/查询条件/解析方案挂在 FreightRpaOnhandReportConfig 上, + 站点行只剩连接、模板绑定与启停。 + """ from app import db from app.models import ( - ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventorySource, - ShippingRpaProfile, + ShippingExcelTemplate, FreightRpaOnhandField, FreightRpaOnhandReportConfig, + FreightRpaParsingProfile, FreightRpaSource, FreightRpaProfile, ) - from app.services.shipping_notice.inventory_structure_fingerprint import ( + from app.services.shipping_notice.onhand_structure_fingerprint import ( FINGERPRINT_VERSION, compatibility_fingerprint, exact_fingerprint, @@ -586,24 +590,24 @@ def _seed_test_inventory_configuration() -> None: ) # 各测试显式创建所需用户字段;生产目录本身保持零预置。 - if not ShippingInventoryField.query.filter_by(field_code='part_number').first(): + if not FreightRpaOnhandField.query.filter_by(field_code='part_number').first(): db.session.add_all([ - ShippingInventoryField(field_code='part_number', display_name='内部料号', value_type='text', usage_type='match_identity', status='active', sort_order=10), - ShippingInventoryField(field_code='reservation_id', display_name='预约号', value_type='text', usage_type='match_identity', status='active', sort_order=20), - ShippingInventoryField(field_code='available_qty', display_name='可用库存数量', value_type='decimal', usage_type='inventory_quantity', status='active', sort_order=30), - ShippingInventoryField(field_code='warehouse_id', display_name='仓库标识', value_type='text', usage_type='warehouse_identity', status='active', sort_order=40), - ShippingInventoryField(field_code='aws_part_number', display_name='AWS 料号', value_type='text', usage_type='general', status='active', sort_order=100), - ShippingInventoryField(field_code='odm_id', display_name='ODM 编号', value_type='text', usage_type='general', status='active', sort_order=110), - ShippingInventoryField(field_code='warehouse_code', display_name='仓库编码', value_type='text', usage_type='general', status='active', sort_order=120), - ShippingInventoryField(field_code='lot_no', display_name='批次号', value_type='text', usage_type='general', status='active', sort_order=130), - ShippingInventoryField(field_code='location', display_name='库位', value_type='text', usage_type='general', status='active', sort_order=140), + FreightRpaOnhandField(field_code='part_number', display_name='内部料号', value_type='text', usage_type='match_identity', status='active', sort_order=10), + FreightRpaOnhandField(field_code='reservation_id', display_name='预约号', value_type='text', usage_type='match_identity', status='active', sort_order=20), + FreightRpaOnhandField(field_code='available_qty', display_name='可用库存数量', value_type='decimal', usage_type='inventory_quantity', status='active', sort_order=30), + FreightRpaOnhandField(field_code='warehouse_id', display_name='仓库标识', value_type='text', usage_type='warehouse_identity', status='active', sort_order=40), + FreightRpaOnhandField(field_code='aws_part_number', display_name='AWS 料号', value_type='text', usage_type='general', status='active', sort_order=100), + FreightRpaOnhandField(field_code='odm_id', display_name='ODM 编号', value_type='text', usage_type='general', status='active', sort_order=110), + FreightRpaOnhandField(field_code='warehouse_code', display_name='仓库编码', value_type='text', usage_type='general', status='active', sort_order=120), + FreightRpaOnhandField(field_code='lot_no', display_name='批次号', value_type='text', usage_type='general', status='active', sort_order=130), + FreightRpaOnhandField(field_code='location', display_name='库位', value_type='text', usage_type='general', status='active', sort_order=140), ]) db.session.flush() inventory_fields = { item.field_code: item - for item in ShippingInventoryField.query.filter( - ShippingInventoryField.field_code.in_([ + for item in FreightRpaOnhandField.query.filter( + FreightRpaOnhandField.field_code.in_([ 'part_number', 'reservation_id', 'available_qty', 'warehouse_id', ]) ).all() @@ -641,7 +645,7 @@ def _seed_test_inventory_configuration() -> None: checksum = hashlib.sha256( json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode() ).hexdigest() - parsing_profile = ShippingInventoryParsingProfile( + parsing_profile = FreightRpaParsingProfile( profile_code='TEST_RUNTIME', display_name='Test Runtime', version=1, status='published', file_format='xlsx', definition_json=definition, checksum=checksum, structure_definition_json=structure, @@ -658,14 +662,20 @@ def _seed_test_inventory_configuration() -> None: file_checksum='0' * 64, definition_json={}, definition_checksum='0' * 64, ) - profile = ShippingRpaProfile( + profile = FreightRpaProfile( profile_code='DBS_DUB_TEST', display_name='DBS Dublin', connector_type='dbs', login_url='https://test.invalid/dbs', login_config_json={'auth_mode': 'password'}, ) - source = ShippingInventorySource( + source = FreightRpaSource( source_code='DSV360_AWSDU', display_name='DBS Dublin AWSDU', connector_type='dbs', - rpa_profile=profile, parsing_profile=parsing_profile, excel_template=excel_template, + rpa_profile=profile, excel_template=excel_template, warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSDU', + enabled=True, + ) + # s18 起报表路径/查询条件/解析方案绑定归 FreightRpaOnhandReportConfig,站点行不再承载。 + report_config = FreightRpaOnhandReportConfig( + source=source, + parsing_profile=parsing_profile, report_path_json={ 'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand Inventory By Location 3lv', @@ -673,9 +683,8 @@ def _seed_test_inventory_configuration() -> None: query_parameters_json=[ {'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': True, 'select_all': False}, ], - enabled=True, ) - db.session.add_all([profile, parsing_profile, excel_template, source]) + db.session.add_all([profile, parsing_profile, excel_template, source, report_config]) db.session.commit() @@ -691,11 +700,13 @@ def dbs_ready_file() -> dict: rows 使用 movement 领域字段键(doc_no/material_code/quantity/movement_date), 与真实仓库 movement_file_repository 产出一致(B5 接线后 run_matching 按 parse_movement_rows 解析);sheet/row_no 为解析必带溯源字段。 + 【T−2 成熟封顶 2026-10-21】rows 异动日期取 2026-08-04(= 业务日 08-06 的 + T−2 恰好成熟边界);更晚日期(T−1/当天)已被圈档封顶排除,不得再作夹具日期。 """ return { "source_code": "DBS-AWSBI", "business_date": "2026-08-06", - "file_purpose": "receipt", + "file_purpose": "inbound", "file_no": "REC-20260806-001", "file_version": "v3", "checksum": "d" * 64, @@ -703,13 +714,13 @@ def dbs_ready_file() -> dict: "rows": [ {"sheet": "Receipt", "row_no": 10, "doc_no": "HOM-001", "lot_no": "LOT-10", "material_code": "MAT-001", "material_name": "连接器组件", "specification": "A 型 / 24PIN", - "movement_date": "2026-08-05", "quantity": "500", "unit": "个", "source_code": "DBS-AWSBI"}, + "movement_date": "2026-08-04", "quantity": "500", "unit": "个", "source_code": "DBS-AWSBI"}, {"sheet": "Receipt", "row_no": 11, "doc_no": "HOM-001", "lot_no": "LOT-10", "material_code": "MAT-001", "material_name": "连接器组件", "specification": "A 型 / 24PIN", - "movement_date": "2026-08-05", "quantity": "700", "unit": "个", "source_code": "DBS-AWSBI"}, + "movement_date": "2026-08-04", "quantity": "700", "unit": "个", "source_code": "DBS-AWSBI"}, {"sheet": "Receipt", "row_no": 20, "doc_no": "HOX-002", "lot_no": "LOT-20", "material_code": "MAT-002", "material_name": "控制器组件", "specification": "标准型 / 48V", - "movement_date": "2026-08-05", "quantity": "1200", "unit": "PCS", "source_code": "DBS-AWSBI"}, + "movement_date": "2026-08-04", "quantity": "1200", "unit": "PCS", "source_code": "DBS-AWSBI"}, ], } @@ -719,11 +730,12 @@ def crane_ready_file() -> dict: """当日 ready 收料全量文件(CRANE-SZ),独立来源。 rows 使用 movement 领域字段键,与真实仓库产出一致(B5 接线后)。 + 异动日期=T−2 成熟边界(见 dbs_ready_file 注释)。 """ return { "source_code": "CRANE-SZ", "business_date": "2026-08-06", - "file_purpose": "receipt", + "file_purpose": "inbound", "file_no": "REC-20260806-002", "file_version": "v4", "checksum": "c" * 64, @@ -731,21 +743,21 @@ def crane_ready_file() -> dict: "rows": [ {"sheet": "Inbound", "row_no": 5, "doc_no": "WTP-008", "lot_no": "LOT-8", "material_code": "MAT-200", "material_name": "传感器模组", "specification": "SZ-8 / IP67", - "movement_date": "2026-08-05", "quantity": "600", "unit": "PCS", "source_code": "CRANE-SZ"}, + "movement_date": "2026-08-04", "quantity": "600", "unit": "PCS", "source_code": "CRANE-SZ"}, ], } @pytest.fixture -def same_day_receipt_file() -> dict: - """含业务日期当天收料的文件;这些 Invoice 必须标记 not_matured。 +def same_day_inbound_file() -> dict: + """含业务日期当天异动数据的文件(T−2 成熟封顶 2026-10-21:当天未成熟不匹配)。 rows 使用 movement 领域字段键,与真实仓库产出一致(B5 接线后)。 """ return { "source_code": "DBS-AWSSG", "business_date": "2026-08-06", - "file_purpose": "receipt", + "file_purpose": "inbound", "file_no": "REC-20260806-003", "file_version": "v2", "checksum": "s" * 64, diff --git a/backend/tests/jobs/test_in_transit_transfer_jobs.py b/backend/tests/jobs/test_in_transit_transfer_jobs.py index 97fe0b4b..201ba4f1 100644 --- a/backend/tests/jobs/test_in_transit_transfer_jobs.py +++ b/backend/tests/jobs/test_in_transit_transfer_jobs.py @@ -19,6 +19,14 @@ from app.services.in_transit_transfer.matching_service import create_matching from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps, seed_rows_from_file +@pytest.fixture(autouse=True) +def _seed_transfer_type(app): + """类型配置化(Task 11/D8):Job 域用例预置默认启用类型(匹配创建必填)。""" + from tests.services.in_transit_transfer.factories import seed_transfer_type_config + + seed_transfer_type_config() + + @pytest.fixture def transfer_deps(app, monkeypatch, dbs_ready_file): """注入 Fake 依赖并预置库存;同时把执行文件对账投影替换为 ready(sha=夹具 checksum)。 @@ -32,8 +40,9 @@ def transfer_deps(app, monkeypatch, dbs_ready_file): seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps) - def _resolve(*, source_code: str) -> dict: + def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict: # 执行门禁②(文件版本对账)替身:来源恒 ready 且 sha 与夹具行版本戳同源。 + del record_kind return {"file_status": "ready", "has_ready_file": True, "file_no": "REC-TEST", "file_sha256": "d" * 64} monkeypatch.setattr( @@ -61,7 +70,7 @@ def test_matching_job_type_registered(): def test_matching_job_handler_runs_and_updates_matching(transfer_db, dbs_ready_file, transfer_deps): """handler 执行后匹配状态进入 ready_to_execute,明细落库。""" summary = create_matching( - source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps, + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps, transfer_type="in_transit_to_hub" ) handler = get_handler(JobType.TRANSFER_MATCH) handler(None, {"matching_id": summary.matching_id}) @@ -70,8 +79,8 @@ def test_matching_job_handler_runs_and_updates_matching(transfer_db, dbs_ready_f assert matching is not None assert matching.status == "ready_to_execute" assert matching.matching_hash.startswith("sha256:") - # 2026-09-25 行归属解耦:行由证据同步落地(matching_id=None),匹配卡不再 - # 持有行(matching.items 恒空)——明细断言改为按来源圈行。 + # 2026-10-14 items 出生翻转:行在匹配创建时从异动档圈行出生(matching_id + # 出生即绑定,D17),证据落地只写档不写行——明细断言按来源圈行验证落地等价。 rows = db.session.query(TransferInvoiceItem).filter_by(source_code="DBS-AWSBI").all() assert len(rows) == 2 assert all(row.status == "ready_to_execute" for row in rows) @@ -97,7 +106,7 @@ def test_run_job_handler_executes_run(transfer_db, dbs_ready_file, transfer_deps from app.services.in_transit_transfer.execution_service import prepare_execution create_matching( - source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps, + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps, transfer_type="in_transit_to_hub" ) from app.models import TransferInvoiceItem @@ -125,7 +134,7 @@ def test_run_job_handler_missing_run_id_raises(transfer_db): def test_item_job_handler_executes_single_item(transfer_db, dbs_ready_file, transfer_deps): """item handler 执行单个 Invoice 写入并置 success。""" create_matching( - source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps, + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps, transfer_type="in_transit_to_hub" ) from app.services.in_transit_transfer.execution_service import prepare_execution @@ -157,7 +166,7 @@ def test_run_job_handler_finishes_job_row(transfer_db, dbs_ready_file, transfer_ from app.services.in_transit_transfer.execution_service import prepare_execution create_matching( - source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps, + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps, transfer_type="in_transit_to_hub" ) ready_ids = [ item.id for item in TransferInvoiceItem.query.filter_by(status="ready_to_execute").all() diff --git a/backend/tests/jobs/test_schedule_queue.py b/backend/tests/jobs/test_schedule_queue.py index d6bb3594..204e81eb 100644 --- a/backend/tests/jobs/test_schedule_queue.py +++ b/backend/tests/jobs/test_schedule_queue.py @@ -23,14 +23,14 @@ from app.services.schedule.queue_service import ( def test_prepare_schedule_queue_recovers_transfer_waiting_source_jobs_every_cycle(app, monkeypatch): """关键断言:调拨来源等待回调 Job 的超时回收每轮领取都执行,不只在 worker 启动时扫一次。 - [STEP 1] 用计数桩替换 receipt_callback_bridge.recover_stale_waiting_source_jobs(queue_service + [STEP 1] 用计数桩替换 inbound_callback_bridge.recover_stale_waiting_source_jobs(queue_service 在函数体内延迟 import,桩生效)并复位 _worker_initialized,隔离模块级启动标记。 [STEP 2] 连续两轮调用真实 prepare_schedule_queue(空库下其余恢复均为 no-op)。 [STEP 3] 第二轮后计数必须为 2:若回收仍挂在启动一次性分支,第二次调用不会触发,计数停留 1。 """ - from app.services.in_transit_transfer import receipt_callback_bridge + from app.services.in_transit_transfer import inbound_callback_bridge from app.services.schedule import queue_service - from app.services.shipping_notice import rpa_worker_heartbeat_alert + from app.services.freight_rpa.common import worker_heartbeat_alert calls: list[int] = [] @@ -41,8 +41,8 @@ def test_prepare_schedule_queue_recovers_transfer_waiting_source_jobs_every_cycl def _fake_heartbeat(**_kwargs): return {"skipped": True, "reason": "test_stub"} - monkeypatch.setattr(receipt_callback_bridge, "recover_stale_waiting_source_jobs", _fake_recover) - monkeypatch.setattr(rpa_worker_heartbeat_alert, "maybe_alert_rpa_worker_status", _fake_heartbeat) + monkeypatch.setattr(inbound_callback_bridge, "recover_stale_waiting_source_jobs", _fake_recover) + monkeypatch.setattr(worker_heartbeat_alert, "maybe_alert_rpa_worker_status", _fake_heartbeat) monkeypatch.setattr(queue_service, "_worker_initialized", False) assert prepare_schedule_queue() == 0 diff --git a/backend/tests/jobs/test_store.py b/backend/tests/jobs/test_store.py index 3bad89f2..746e87db 100644 --- a/backend/tests/jobs/test_store.py +++ b/backend/tests/jobs/test_store.py @@ -68,7 +68,7 @@ def test_claim_next_shipping_claims_inventory_callback_process_job(app): with app.app_context(): job = Job( domain='shipping_notice', - job_type=JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS.value, + job_type=JobType.FREIGHT_RPA_ONHAND_CALLBACK_PROCESS.value, status='queued', payload_json={'callback_id': 'callback-test'}, ) @@ -79,7 +79,7 @@ def test_claim_next_shipping_claims_inventory_callback_process_job(app): assert claimed is not None assert claimed['id'] == job.id - assert claimed['job_type'] == JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS + assert claimed['job_type'] == JobType.FREIGHT_RPA_ONHAND_CALLBACK_PROCESS def test_claim_next_transfer_claims_run_job(app): diff --git a/backend/tests/performance/test_in_transit_transfer.py b/backend/tests/performance/test_in_transit_transfer.py index ec2d9f47..6b39c2f6 100644 --- a/backend/tests/performance/test_in_transit_transfer.py +++ b/backend/tests/performance/test_in_transit_transfer.py @@ -48,10 +48,17 @@ def test_bulk_matching_300_invoices(transfer_db): seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") started = time.perf_counter() - summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") elapsed = time.perf_counter() - started assert summary.counts.executable_count == 300 assert summary.counts.file_invoice_count == 300 restored = restore_matching(summary.matching_id) assert len(restored["items"]) == 300 print(f"\n[perf] bulk matching 300 invoices: {elapsed:.3f}s") + +@pytest.fixture(autouse=True) +def _seed_transfer_type(transfer_db): + """类型配置化(Task 11/D8):性能用例预置默认启用类型(匹配创建必填)。""" + from tests.services.in_transit_transfer.factories import seed_transfer_type_config + + seed_transfer_type_config() diff --git a/backend/tests/services/admin/test_shipping_inventory_service.py b/backend/tests/services/admin/test_shipping_onhand_service.py similarity index 66% rename from backend/tests/services/admin/test_shipping_inventory_service.py rename to backend/tests/services/admin/test_shipping_onhand_service.py index e9cc5dcb..907ff9de 100644 --- a/backend/tests/services/admin/test_shipping_inventory_service.py +++ b/backend/tests/services/admin/test_shipping_onhand_service.py @@ -2,7 +2,7 @@ tests/services/admin/test_shipping_inventory_service.py 用途:验证库存主数据管理服务的安全性和关键业务约束。 -依赖:Flask app/db、shipping_inventory_service、库存配置模型。 +依赖:Flask app/db、freight_rpa_source_admin_service、shipping_onhand_admin_service、库存配置模型。 逻辑:管理后台写配置前锁定凭据脱敏、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。 """ @@ -12,16 +12,16 @@ from cryptography.fernet import Fernet import pytest from app.core.errors import ConflictError, ValidationError -from app.services.admin import shipping_inventory_service -from app.services.shipping_notice import inventory_parsing_profile +from app.services.admin import freight_rpa_source_admin_service, shipping_onhand_admin_service +from app.services.freight_rpa import parsing_profile as onhand_parsing_profile from app.services.shipping_notice.order_schema import service as order_schema_service from app import db from app.models import ( ShippingExcelTemplate, - ShippingInventoryField, - ShippingInventorySource, - ShippingInventorySourceParsingBindingAudit, - ShippingInventoryStructureAnalysis, + FreightRpaOnhandField, + FreightRpaSource, + FreightRpaSourceParsingBindingAudit, + FreightRpaOnhandStructureAnalysis, ) @@ -35,7 +35,7 @@ def _profile_data(*, code: str = 'DBS_EU', connector_type: str = 'dbs') -> dict: def _sample_evidence() -> int: """创建最小表头证据,确保库存源服务测试不绕过解析方案样本门禁。""" - item = ShippingInventoryStructureAnalysis( + item = FreightRpaOnhandStructureAnalysis( source_kind='sample_upload', source_file_name='service-sample.xlsx', storage_path=None, file_checksum='b' * 64, file_format='xlsx', analysis_status='ready', structure_json={'candidates': [{ @@ -88,13 +88,13 @@ def _parsing_profile() -> dict: ) inventory_fields = { item.field_code: str(item.id) - for item in ShippingInventoryField.query.filter( - ShippingInventoryField.field_code.in_(['part_number', 'reservation_id', 'available_qty']), - ShippingInventoryField.status == 'active', + for item in FreightRpaOnhandField.query.filter( + FreightRpaOnhandField.field_code.in_(['part_number', 'reservation_id', 'available_qty']), + FreightRpaOnhandField.status == 'active', ).all() } assert set(inventory_fields) == {'part_number', 'reservation_id', 'available_qty'} - draft = inventory_parsing_profile.save_draft({ + draft = onhand_parsing_profile.save_draft({ 'profile_code': 'COMMON_DBS', 'display_name': 'Common DBS', 'file_format': 'xlsx', 'sample_analysis_id': _sample_evidence(), 'definition': { @@ -110,7 +110,7 @@ def _parsing_profile() -> dict: }], }, }, actor_id=None) - return inventory_parsing_profile.publish(draft['id'], actor_id=None) + return onhand_parsing_profile.publish(draft['id'], actor_id=None) def _excel_template_id() -> int: @@ -133,17 +133,21 @@ def _excel_template_id() -> int: def _source_data(profile_id: int, *, parsing_profile_id: int | None = None, code: str = 'DBS_DUB', connector_type: str = 'dbs') -> dict: return { 'source_code': code, 'display_name': code, 'connector_type': connector_type, - 'rpa_profile_id': profile_id, 'parsing_profile_id': parsing_profile_id or _parsing_profile()['id'], + 'rpa_profile_id': profile_id, 'excel_template_id': _excel_template_id(), 'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': 'DUB', 'snapshot_ttl_seconds': 3600, 'enabled': True, - 'report_path_json': { - 'program_group': 'Bison', 'program_label': 'AWSBI', - 'report_group': 'Inventory', 'report_name': 'On Hand Inventory By Location 3lv', + # s18 起报表路径/查询条件/解析方案绑定经内嵌 onhand_report_config 写配置行,站点载荷不再平铺。 + 'onhand_report_config': { + 'parsing_profile_id': parsing_profile_id or _parsing_profile()['id'], + 'report_path_json': { + 'program_group': 'Bison', 'program_label': 'AWSBI', + 'report_group': 'Inventory', 'report_name': 'On Hand Inventory By Location 3lv', + }, + 'query_parameters_json': [ + {'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False}, + ], }, - 'query_parameters_json': [ - {'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False}, - ], } @@ -160,7 +164,7 @@ def test_profile_credentials_are_not_returned(app): """Profile 保存后只返回配置标记,响应中不能含凭据明文或密文。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - payload = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) + payload = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None) assert payload['password_configured'] is True assert payload['username_masked'] == 'configured' assert 'password' not in payload @@ -174,7 +178,7 @@ def test_profile_rejects_page_operation_configuration(app): payload = _profile_data() payload['login_config_json'] = {'auth_mode': 'password', 'navigation': {'report_name': 'Wrong'}} with pytest.raises(ValidationError) as exc_info: - shipping_inventory_service.save_profile(payload, actor_id=None) + freight_rpa_source_admin_service.save_profile(payload, actor_id=None) assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_CONFIG_INVALID' @@ -182,10 +186,10 @@ def test_multiple_dbs_profiles_bind_independent_sources(app): """同一 DBS connector 可配置多个登录连接,每个 Source 稳定绑定自己的 Profile。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - first = shipping_inventory_service.save_profile(_profile_data(code='DBS_EU_A'), actor_id=None) - second = shipping_inventory_service.save_profile(_profile_data(code='DBS_EU_B'), actor_id=None) - first_source = shipping_inventory_service.save_source(_source_data(first['id'], code='DBS_DUB'), actor_id=None) - second_source = shipping_inventory_service.save_source(_source_data(second['id'], code='DBS_RTM'), actor_id=None) + first = freight_rpa_source_admin_service.save_profile(_profile_data(code='DBS_EU_A'), actor_id=None) + second = freight_rpa_source_admin_service.save_profile(_profile_data(code='DBS_EU_B'), actor_id=None) + first_source = freight_rpa_source_admin_service.save_source(_source_data(first['id'], code='DBS_DUB'), actor_id=None) + second_source = freight_rpa_source_admin_service.save_source(_source_data(second['id'], code='DBS_RTM'), actor_id=None) assert first_source['rpa_profile_id'] == first['id'] assert second_source['rpa_profile_id'] == second['id'] @@ -194,34 +198,36 @@ def test_source_rejects_profile_connector_mismatch(app): """库存源不能绑定不同 Driver 的 Profile。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - profile = shipping_inventory_service.save_profile(_profile_data(connector_type='crane'), actor_id=None) + profile = freight_rpa_source_admin_service.save_profile(_profile_data(connector_type='crane'), actor_id=None) with pytest.raises(ValidationError) as exc_info: - shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None) - assert exc_info.value.code == 'SHIPPING.INVENTORY_PROFILE_CONNECTOR_MISMATCH' + freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None) + assert exc_info.value.code == 'SHIPPING.ONHAND_PROFILE_CONNECTOR_MISMATCH' def test_disabled_source_can_be_saved_before_profile_and_template_binding(app): """禁用库存源允许分步配置;启用时必须补齐 published 解析 Profile 和模板。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - login = shipping_inventory_service.save_profile(_profile_data(code='DRAFT_SOURCE_LOGIN'), actor_id=None) + login = freight_rpa_source_admin_service.save_profile(_profile_data(code='DRAFT_SOURCE_LOGIN'), actor_id=None) payload = _source_data(login['id'], code='DRAFT_SOURCE') - payload.update({'enabled': False, 'parsing_profile_id': None, 'excel_template_id': None}) - draft = shipping_inventory_service.save_source(payload, actor_id=None) + payload.update({'enabled': False, 'excel_template_id': None}) + payload['onhand_report_config']['parsing_profile_id'] = None + draft = freight_rpa_source_admin_service.save_source(payload, actor_id=None) assert draft['enabled'] is False - assert draft['parsing_profile_id'] is None + assert draft['onhand_report_config']['parsing_profile_id'] is None assert draft['excel_template_id'] is None payload.update({'enabled': True}) with pytest.raises(ValidationError) as exc_info: - shipping_inventory_service.save_source(payload, actor_id=None, source_id=draft['id']) - assert exc_info.value.code == 'SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED' + freight_rpa_source_admin_service.save_source(payload, actor_id=None, source_id=draft['id']) + assert exc_info.value.code == 'SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED' + # 拒绝后回滚脏会话(等价于请求边界回滚):s18 服务在赋值后才触发启用门禁, + # 不回滚会让后续查询的 autoflush 把 enabled=True + 空模板撞 CHECK。 + db.session.rollback() - payload.update({ - 'parsing_profile_id': _parsing_profile()['id'], - 'excel_template_id': _excel_template_id(), - }) - enabled = shipping_inventory_service.save_source(payload, actor_id=None, source_id=draft['id']) + payload['onhand_report_config']['parsing_profile_id'] = _parsing_profile()['id'] + payload['excel_template_id'] = _excel_template_id() + enabled = freight_rpa_source_admin_service.save_source(payload, actor_id=None, source_id=draft['id']) assert enabled['enabled'] is True @@ -229,22 +235,23 @@ def test_activation_is_a_separate_gate_and_reports_unfinished_steps(app): """普通保存只能保留停用站点;独立启用动作必须返回尚未完成的硬门槛。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - login = shipping_inventory_service.save_profile(_profile_data(code='ACTIVATION_LOGIN'), actor_id=None) + login = freight_rpa_source_admin_service.save_profile(_profile_data(code='ACTIVATION_LOGIN'), actor_id=None) payload = _source_data(login['id'], code='ACTIVATION_SOURCE') - payload.update({'enabled': False, 'parsing_profile_id': None, 'excel_template_id': None}) - draft = shipping_inventory_service.save_source(payload, actor_id=None, allow_enable_transition=False) + payload.update({'enabled': False, 'excel_template_id': None}) + payload['onhand_report_config']['parsing_profile_id'] = None + draft = freight_rpa_source_admin_service.save_source(payload, actor_id=None, allow_enable_transition=False) assert draft['activation']['ready'] is False assert draft['activation']['missing_requirements'] == ['parsing_profile', 'excel_template'] payload['enabled'] = True - saved = shipping_inventory_service.save_source( + saved = freight_rpa_source_admin_service.save_source( payload, actor_id=None, source_id=draft['id'], allow_enable_transition=False, ) assert saved['enabled'] is False with pytest.raises(ConflictError) as exc_info: - shipping_inventory_service.activate_source(draft['id'], actor_id=None) - assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_ACTIVATION_BLOCKED' + freight_rpa_source_admin_service.activate_source(draft['id'], actor_id=None) + assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_ACTIVATION_BLOCKED' assert exc_info.value.details['missing_requirements'] == ['parsing_profile', 'excel_template'] @@ -252,18 +259,23 @@ def test_activation_status_exposes_only_hard_gate_checks(app): """启用门禁仅暴露连接/解析/发货模板硬门槛,不再包含测试导出或后续准备项。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - login = shipping_inventory_service.save_profile(_profile_data(code='CHECKS_LOGIN'), actor_id=None) + login = freight_rpa_source_admin_service.save_profile(_profile_data(code='CHECKS_LOGIN'), actor_id=None) payload = { 'source_code': 'CHECKS_SOURCE', 'display_name': 'Checks Source', 'connector_type': 'dbs', - 'rpa_profile_id': login['id'], 'parsing_profile_id': None, 'excel_template_id': None, + 'rpa_profile_id': login['id'], 'excel_template_id': None, 'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': 'DUB', 'snapshot_ttl_seconds': 3600, - 'report_path_json': { - 'program_group': 'Bison', 'program_label': 'AWSBI', - 'report_group': 'Inventory', 'report_name': 'On Hand', + # s18 起报表路径/查询条件/解析方案绑定经内嵌 onhand_report_config 写配置行。 + 'onhand_report_config': { + 'parsing_profile_id': None, + 'report_path_json': { + 'program_group': 'Bison', 'program_label': 'AWSBI', + 'report_group': 'Inventory', 'report_name': 'On Hand', + }, + 'query_parameters_json': [], }, - 'query_parameters_json': [], 'enabled': False, + 'enabled': False, } - draft = shipping_inventory_service.save_source(payload, actor_id=None, allow_enable_transition=False) + draft = freight_rpa_source_admin_service.save_source(payload, actor_id=None, allow_enable_transition=False) checks = {item['code']: item for item in draft['activation']['checks']} @@ -280,11 +292,11 @@ def test_enabled_source_rejects_disabled_rpa_profile(app): """启用库存源不得绑定停用连接,避免后台配置与运行时读取结果不一致。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - profile = shipping_inventory_service.save_profile( + profile = freight_rpa_source_admin_service.save_profile( {**_profile_data(code='DISABLED_LOGIN'), 'enabled': False}, actor_id=None, ) with pytest.raises(ValidationError) as exc_info: - shipping_inventory_service.save_source(_source_data(profile['id'], code='BLOCKED_SOURCE'), actor_id=None) + freight_rpa_source_admin_service.save_source(_source_data(profile['id'], code='BLOCKED_SOURCE'), actor_id=None) assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DISABLED' @@ -292,10 +304,11 @@ def test_dbs_source_persists_report_path_parameters_and_aliases(app): """数据库库存源必须承载 DBS 报表路径、查询参数与识别别名,不依赖 Profile 的页面配置。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) - source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None) - assert source['report_path_json']['report_name'] == 'On Hand Inventory By Location 3lv' - assert source['query_parameters_json'] == [ + profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None) + source = freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None) + # s18 起报表路径/查询条件挂在响应的 onhand_report_config 嵌套对象上。 + assert source['onhand_report_config']['report_path_json']['report_name'] == 'On Hand Inventory By Location 3lv' + assert source['onhand_report_config']['query_parameters_json'] == [ {'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False}, ] @@ -304,52 +317,54 @@ def test_source_rejects_driver_selector_in_business_parameters(app): """业务参数不得保存 selector 等 Driver 细节,避免后台配置与 RPA 模板耦合。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) + profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None) payload = _source_data(profile['id']) - payload['query_parameters_json'][0]['selector_env'] = 'FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR' + payload['onhand_report_config']['query_parameters_json'][0]['selector_env'] = 'FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR' with pytest.raises(ValidationError) as exc_info: - shipping_inventory_service.save_source(payload, actor_id=None) - assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID' + freight_rpa_source_admin_service.save_source(payload, actor_id=None) + assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_CONFIG_INVALID' def test_crane_source_rejects_dbs_report_path(app): """动态仓 Crane 库存源不得误填 DBS 四级报表路径。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - profile = shipping_inventory_service.save_profile(_profile_data(code='CRANE', connector_type='crane'), actor_id=None) + profile = freight_rpa_source_admin_service.save_profile(_profile_data(code='CRANE', connector_type='crane'), actor_id=None) payload = _source_data(profile['id'], code='CRANE', connector_type='crane') payload['warehouse_resolution_mode'] = 'inventory_match' payload['fixed_warehouse_id'] = None with pytest.raises(ValidationError) as exc_info: - shipping_inventory_service.save_source(payload, actor_id=None) - assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID' + freight_rpa_source_admin_service.save_source(payload, actor_id=None) + assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_CONFIG_INVALID' def test_direct_parsing_profile_binding_keeps_source_disabled_and_writes_audit(app): """停用站点可直接绑定已发布方案;绑定必须递增版本并留下不可变审计。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - login = shipping_inventory_service.save_profile(_profile_data(code='DIRECT_BIND_LOGIN'), actor_id=7) + login = freight_rpa_source_admin_service.save_profile(_profile_data(code='DIRECT_BIND_LOGIN'), actor_id=7) payload = _source_data(login['id'], code='DIRECT_BIND_SOURCE') - payload.update({'enabled': False, 'parsing_profile_id': None}) - source = shipping_inventory_service.save_source(payload, actor_id=7, allow_enable_transition=False) + payload.update({'enabled': False}) + payload['onhand_report_config']['parsing_profile_id'] = None + source = freight_rpa_source_admin_service.save_source(payload, actor_id=7, allow_enable_transition=False) profile = _parsing_profile() - bound = shipping_inventory_service.bind_source_parsing_profile( + bound = freight_rpa_source_admin_service.bind_source_parsing_profile( [source['id']], profile['id'], actor_id=7, operation='direct', ) # 关键断言:直接绑定只配置解析定义,绝不绕过独立启用门禁。 assert bound[0]['enabled'] is False - assert bound[0]['parsing_profile_id'] == profile['id'] + # s18 起解析绑定挂在响应的 onhand_report_config 嵌套对象上。 + assert bound[0]['onhand_report_config']['parsing_profile_id'] == profile['id'] assert bound[0]['config_version'] == source['config_version'] + 1 - audit = ShippingInventorySourceParsingBindingAudit.query.one() + audit = FreightRpaSourceParsingBindingAudit.query.one() assert audit.operation == 'direct' # 关键断言:审计保留系统动作说明,不要求管理员额外填写“绑定原因”。 assert audit.reason == '管理员直接绑定已发布解析方案' assert audit.before_snapshot_json['parsing_profile_id'] is None assert audit.after_snapshot_json['parsing_profile_id'] == profile['id'] - history = shipping_inventory_service.get_source_parsing_binding_audits(source['id']) + history = freight_rpa_source_admin_service.get_source_parsing_binding_audits(source['id']) assert history[0]['actor_id'] == 7 assert history[0]['source_config_version_after'] == bound[0]['config_version'] @@ -358,33 +373,36 @@ def test_bulk_parsing_profile_binding_allows_enabled_sites(app): """批量绑定允许包含已启用站点;全部预检通过后原子写入。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - login = shipping_inventory_service.save_profile(_profile_data(code='BULK_BIND_LOGIN'), actor_id=None) + login = freight_rpa_source_admin_service.save_profile(_profile_data(code='BULK_BIND_LOGIN'), actor_id=None) disabled_payload = _source_data(login['id'], code='BULK_BIND_DISABLED') - disabled_payload.update({'enabled': False, 'parsing_profile_id': None}) - disabled = shipping_inventory_service.save_source(disabled_payload, actor_id=None, allow_enable_transition=False) - enabled = shipping_inventory_service.save_source(_source_data(login['id'], code='BULK_BIND_ENABLED'), actor_id=None) + disabled_payload.update({'enabled': False}) + disabled_payload['onhand_report_config']['parsing_profile_id'] = None + disabled = freight_rpa_source_admin_service.save_source(disabled_payload, actor_id=None, allow_enable_transition=False) + enabled = freight_rpa_source_admin_service.save_source(_source_data(login['id'], code='BULK_BIND_ENABLED'), actor_id=None) profile = _parsing_profile() - bound = shipping_inventory_service.bind_source_parsing_profile( + bound = freight_rpa_source_admin_service.bind_source_parsing_profile( [disabled['id'], enabled['id']], profile['id'], actor_id=None, reason='批量迁移同类报表', operation='bulk', ) # 关键断言:已启用站点可直接换绑;两站同步写入且留下审计。 assert {row['id'] for row in bound} == {disabled['id'], enabled['id']} - assert all(row['parsing_profile_id'] == profile['id'] for row in bound) - assert db.session.get(ShippingInventorySource, enabled['id']).enabled is True - assert ShippingInventorySourceParsingBindingAudit.query.count() == 2 + # s18 起解析绑定挂在响应的 onhand_report_config 嵌套对象上。 + assert all(row['onhand_report_config']['parsing_profile_id'] == profile['id'] for row in bound) + assert db.session.get(FreightRpaSource, enabled['id']).enabled is True + assert FreightRpaSourceParsingBindingAudit.query.count() == 2 def test_direct_parsing_binding_rejects_template_fields_missing_from_profile(app): """直接绑定必须在提交前复核发货模板库存字段,防止问题延后到正式导出。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - login = shipping_inventory_service.save_profile(_profile_data(code='TEMPLATE_GATE_LOGIN'), actor_id=None) + login = freight_rpa_source_admin_service.save_profile(_profile_data(code='TEMPLATE_GATE_LOGIN'), actor_id=None) payload = _source_data(login['id'], code='TEMPLATE_GATE_SOURCE') - payload.update({'enabled': False, 'parsing_profile_id': None}) - source = shipping_inventory_service.save_source(payload, actor_id=None, allow_enable_transition=False) + payload.update({'enabled': False}) + payload['onhand_report_config']['parsing_profile_id'] = None + source = freight_rpa_source_admin_service.save_source(payload, actor_id=None, allow_enable_transition=False) template = db.session.get(ShippingExcelTemplate, source['excel_template_id']) template.definition_json = { 'filename_pattern': '{business_no}.xlsx', @@ -393,50 +411,51 @@ def test_direct_parsing_binding_rejects_template_fields_missing_from_profile(app db.session.commit() with pytest.raises(ValidationError) as exc_info: - shipping_inventory_service.bind_source_parsing_profile( + freight_rpa_source_admin_service.bind_source_parsing_profile( [source['id']], _parsing_profile()['id'], actor_id=None, reason='模板字段契约预检', operation='direct', ) # 关键断言:模板依赖缺失必须在绑定时拒绝,不能产生半成品站点绑定。 - assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_BINDING_TEMPLATE_INVALID' - assert db.session.get(ShippingInventorySource, source['id']).parsing_profile_id is None - assert ShippingInventorySourceParsingBindingAudit.query.count() == 0 + assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_BINDING_TEMPLATE_INVALID' + # s18 起解析绑定归 onhand_report_config 配置行;被拒后配置行必须保持未绑定。 + assert db.session.get(FreightRpaSource, source['id']).onhand_report_config.parsing_profile_id is None + assert FreightRpaSourceParsingBindingAudit.query.count() == 0 def test_published_rule_cannot_be_mutated_in_place(app): """发布规则必须依靠新版本演进,避免改写历史任务依据。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - profile = shipping_inventory_service.save_profile(_profile_data(code='IMMUTABLE_RULE_LOGIN'), actor_id=None) - source = shipping_inventory_service.save_source(_source_data(profile['id'], code='DBS_DUB'), actor_id=None) + profile = freight_rpa_source_admin_service.save_profile(_profile_data(code='IMMUTABLE_RULE_LOGIN'), actor_id=None) + source = freight_rpa_source_admin_service.save_source(_source_data(profile['id'], code='DBS_DUB'), actor_id=None) reservation_field_id = _published_route_field_id() - rule = shipping_inventory_service.save_rule({ + rule = shipping_onhand_admin_service.save_rule({ 'rule_code': 'RSV_PREFIX_1', 'rule_name': 'Reservation starts with 1', 'scope': 'line', 'priority': 100, 'match_mode': 'all', 'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': [source['source_code']]}, 'version': 1, 'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}], }, actor_id=None) - shipping_inventory_service.publish_rule(rule['id'], actor_id=None) + shipping_onhand_admin_service.publish_rule(rule['id'], actor_id=None) with pytest.raises(ConflictError) as exc_info: - shipping_inventory_service.save_rule({ + shipping_onhand_admin_service.save_rule({ 'rule_code': 'RSV_PREFIX_1', 'rule_name': 'Changed', 'scope': 'line', 'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['CRANE']}, 'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}], }, actor_id=None, rule_id=rule['id']) - assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_IMMUTABLE' + assert exc_info.value.code == 'SHIPPING.ONHAND_RULE_IMMUTABLE' def test_draft_rule_update_keeps_the_same_draft(app): """草稿更新应原地替换条件,不能偷偷新增同版本规则记录。""" with app.app_context(): reservation_field_id = _published_route_field_id() - rule = shipping_inventory_service.save_rule({ + rule = shipping_onhand_admin_service.save_rule({ 'rule_code': 'DRAFT_UPDATE', 'rule_name': 'Before', 'scope': 'line', 'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DBS_DUB']}, 'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'equals', 'expected_value_json': 'DUB'}], }, actor_id=None) - updated = shipping_inventory_service.save_rule({ + updated = shipping_onhand_admin_service.save_rule({ 'rule_code': 'DRAFT_UPDATE', 'rule_name': 'After', 'scope': 'line', 'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['CRANE']}, 'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'equals', 'expected_value_json': 'FRA'}], @@ -450,7 +469,7 @@ def test_rule_condition_value_type_follows_the_selected_operator(app): """列表、长度和空值操作符必须保存受控值类型,不能把配置错误拖到运行期。""" with app.app_context(): reservation_field_id = _published_route_field_id() - rule = shipping_inventory_service.save_rule({ + rule = shipping_onhand_admin_service.save_rule({ 'rule_code': 'RSV_IN', 'rule_name': 'Reservation list', 'scope': 'line', 'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DBS_DUB']}, 'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'in', 'expected_value_json': ['1001', '1002']}], @@ -458,106 +477,107 @@ def test_rule_condition_value_type_follows_the_selected_operator(app): assert rule['conditions'][0]['expected_value_json'] == ['1001', '1002'] with pytest.raises(ValidationError) as exc_info: - shipping_inventory_service.save_rule({ + shipping_onhand_admin_service.save_rule({ 'rule_code': 'RSV_BAD_IN', 'rule_name': 'Invalid list', 'scope': 'line', 'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DBS_DUB']}, 'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'in', 'expected_value_json': '1001'}], }, actor_id=None) - assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_CONDITION_INVALID' + assert exc_info.value.code == 'SHIPPING.ONHAND_RULE_CONDITION_INVALID' def test_lifecycle_allows_safe_delete_and_rejects_referenced_configuration(app): """未引用的误建配置可删除;一旦绑定库存源或发布,必须改为停用/归档。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - unused = shipping_inventory_service.save_profile(_profile_data(code='UNUSED'), actor_id=None) - shipping_inventory_service.delete_profile(unused['id']) - assert all(item['profile_code'] != 'UNUSED' for item in shipping_inventory_service.list_profiles()) + unused = freight_rpa_source_admin_service.save_profile(_profile_data(code='UNUSED'), actor_id=None) + freight_rpa_source_admin_service.delete_profile(unused['id']) + assert all(item['profile_code'] != 'UNUSED' for item in freight_rpa_source_admin_service.list_profiles()) - profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) - source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None) + profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None) + source = freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None) with pytest.raises(ConflictError) as exc_info: - shipping_inventory_service.delete_profile(profile['id']) + freight_rpa_source_admin_service.delete_profile(profile['id']) assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DELETE_BLOCKED' with pytest.raises(ConflictError) as exc_info: - shipping_inventory_service.save_profile({**_profile_data(), 'enabled': False}, actor_id=None, profile_id=profile['id']) + freight_rpa_source_admin_service.save_profile({**_profile_data(), 'enabled': False}, actor_id=None, profile_id=profile['id']) assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DISABLE_BLOCKED' reservation_field_id = _published_route_field_id() - rule = shipping_inventory_service.save_rule({ + rule = shipping_onhand_admin_service.save_rule({ 'rule_code': 'RETIRE_ME', 'rule_name': 'Retire me', 'scope': 'line', 'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': [source['source_code']]}, 'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}], }, actor_id=None) - shipping_inventory_service.publish_rule(rule['id'], actor_id=None) - retired = shipping_inventory_service.retire_rule(rule['id'], actor_id=None) + shipping_onhand_admin_service.publish_rule(rule['id'], actor_id=None) + retired = shipping_onhand_admin_service.retire_rule(rule['id'], actor_id=None) assert retired['status'] == 'retired' with pytest.raises(ConflictError) as exc_info: - shipping_inventory_service.delete_draft_rule(rule['id']) - assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_DELETE_BLOCKED' + shipping_onhand_admin_service.delete_draft_rule(rule['id']) + assert exc_info.value.code == 'SHIPPING.ONHAND_RULE_DELETE_BLOCKED' def test_publish_rule_rejects_missing_source_but_allows_disabled_source(app): """发布只校验 Source 存在;停用 Source 由实际 RPA 运行期门禁阻断。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - profile = shipping_inventory_service.save_profile(_profile_data(code='ROUTE_LOGIN'), actor_id=None) - source = shipping_inventory_service.save_source(_source_data(profile['id'], code='ROUTE_SOURCE'), actor_id=None) + profile = freight_rpa_source_admin_service.save_profile(_profile_data(code='ROUTE_LOGIN'), actor_id=None) + source = freight_rpa_source_admin_service.save_source(_source_data(profile['id'], code='ROUTE_SOURCE'), actor_id=None) disabled_payload = _source_data(profile['id'], code='DISABLED_ROUTE_SOURCE') - disabled_payload.update({'enabled': False, 'parsing_profile_id': None, 'excel_template_id': None}) - shipping_inventory_service.save_source(disabled_payload, actor_id=None) + disabled_payload.update({'enabled': False, 'excel_template_id': None}) + disabled_payload['onhand_report_config']['parsing_profile_id'] = None + freight_rpa_source_admin_service.save_source(disabled_payload, actor_id=None) reservation_field_id = _published_route_field_id() - missing_rule = shipping_inventory_service.save_rule({ + missing_rule = shipping_onhand_admin_service.save_rule({ 'rule_code': 'MISSING_SOURCE', 'rule_name': 'Missing source rule', 'scope': 'line', 'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['MISSING_SOURCE']}, 'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}], }, actor_id=None) with pytest.raises(ValidationError) as exc_info: - shipping_inventory_service.publish_rule(missing_rule['id'], actor_id=None) - assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_SOURCE_INVALID' + shipping_onhand_admin_service.publish_rule(missing_rule['id'], actor_id=None) + assert exc_info.value.code == 'SHIPPING.ONHAND_RULE_SOURCE_INVALID' - disabled_rule = shipping_inventory_service.save_rule({ + disabled_rule = shipping_onhand_admin_service.save_rule({ 'rule_code': 'DISABLED_SOURCE', 'rule_name': 'Disabled source rule', 'scope': 'line', 'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DISABLED_ROUTE_SOURCE']}, 'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '2'}], }, actor_id=None) - assert shipping_inventory_service.publish_rule(disabled_rule['id'], actor_id=None)['status'] == 'published' + assert shipping_onhand_admin_service.publish_rule(disabled_rule['id'], actor_id=None)['status'] == 'published' - valid_rule = shipping_inventory_service.save_rule({ + valid_rule = shipping_onhand_admin_service.save_rule({ 'rule_code': 'VALID_SOURCE', 'rule_name': 'Valid source rule', 'scope': 'line', 'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': [source['source_code']]}, 'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '9'}], }, actor_id=None) - assert shipping_inventory_service.publish_rule(valid_rule['id'], actor_id=None)['status'] == 'published' + assert shipping_onhand_admin_service.publish_rule(valid_rule['id'], actor_id=None)['status'] == 'published' def test_active_default_external_mapping_is_unique_per_source(app): """同一库存源同一货代仓库身份只能有一条启用的映射。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) - source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None) + profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None) + source = freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None) payload = { - 'inventory_source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP', + 'source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP', 'external_organization_code': None, 'external_site_code': 'EU01', 'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin', 'in_transit_warehouse_code': 'TZR2', 'enabled': True, } - shipping_inventory_service.save_external_mapping(payload, actor_id=None) + shipping_onhand_admin_service.save_external_mapping(payload, actor_id=None) with pytest.raises(ConflictError): - shipping_inventory_service.save_external_mapping(payload, actor_id=None) + shipping_onhand_admin_service.save_external_mapping(payload, actor_id=None) def test_external_mapping_allows_empty_freight_warehouse(app): """货代仓库改为可选:空值保存为 NULL(空库位默认映射行),供 inventory_match 源兜底匹配。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) - source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None) + profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None) + source = freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None) # [断言意图] 货代仓库为空不阻断保存;在途仓编码必填且大写归一后随 payload 返回。 - mapping = shipping_inventory_service.save_external_mapping({ - 'inventory_source_id': source['id'], 'freight_warehouse_id': None, 'external_system_code': 'TOPGP', + mapping = shipping_onhand_admin_service.save_external_mapping({ + 'source_id': source['id'], 'freight_warehouse_id': None, 'external_system_code': 'TOPGP', 'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin', 'in_transit_warehouse_code': 'tzr2', 'enabled': True, }, actor_id=None) @@ -569,12 +589,12 @@ def test_external_mapping_requires_in_transit_warehouse_code(app): """在途仓编码是在途调拨拨出库位来源——缺省必须在保存端拒绝(fail-closed 前置)。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) - source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None) + profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None) + source = freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None) # [断言意图] 缺在途仓编码的映射会让调拨拨出库位无来源,保存端必须 fail-closed。 with pytest.raises(ValidationError): - shipping_inventory_service.save_external_mapping({ - 'inventory_source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP', + shipping_onhand_admin_service.save_external_mapping({ + 'source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP', 'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin', 'enabled': True, }, actor_id=None) @@ -583,10 +603,10 @@ def test_external_mapping_normalizes_freight_warehouse_identity(app): """配置端小写货代仓应与收料文件仓库值(大写归一后)使用同一精确映射身份。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) - source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None) - mapping = shipping_inventory_service.save_external_mapping({ - 'inventory_source_id': source['id'], 'freight_warehouse_id': 'dub', + profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None) + source = freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None) + mapping = shipping_onhand_admin_service.save_external_mapping({ + 'source_id': source['id'], 'freight_warehouse_id': 'dub', 'external_system_code': 'TOPGP', 'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin', 'in_transit_warehouse_code': 'TZR2', 'enabled': True, }, actor_id=None) @@ -597,32 +617,32 @@ def test_upload_config_change_does_not_bump_rpa_profile_version(app): """连接级上传配置(upload_config_json)变更不递增 config_version。""" app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): - profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) + profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None) base_version = profile['config_version'] upload_cfg = { 'enabled': True, 'entry_url': 'https://s360.dbschenker.com/main/portal/frame/WMSUpload2', 'file_input_selector': 'input#file2', 'submit_mode': 'auto_after_file', 'submit_selector': None, 'result_mode': 'page_notice', 'result_selector': None, 'success_texts': [], 'timeout_seconds': 120, } - updated = shipping_inventory_service.save_profile( + updated = freight_rpa_source_admin_service.save_profile( {**_profile_data(), 'upload_config_json': upload_cfg}, actor_id=None, profile_id=profile['id'], ) assert updated['config_version'] == base_version assert updated['upload_config_json']['enabled'] is True # 仅修改运行期连接配置(login_url)仍应递增 config_version。 - bumped = shipping_inventory_service.save_profile( + bumped = freight_rpa_source_admin_service.save_profile( {**_profile_data(), 'login_url': 'https://example.invalid/login-v2'}, actor_id=None, profile_id=profile['id'], ) assert bumped['config_version'] == base_version + 1 # 非法上传配置(HTTP / 非法主机 / 脚本 selector)应拒绝。 with pytest.raises(ValidationError): - shipping_inventory_service.save_profile( + freight_rpa_source_admin_service.save_profile( {**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'http://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}}, actor_id=None, profile_id=profile['id'], ) with pytest.raises(ValidationError): - shipping_inventory_service.save_profile( + freight_rpa_source_admin_service.save_profile( {**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'https://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}}, actor_id=None, profile_id=profile['id'], ) diff --git a/backend/tests/services/freight_rpa/test_import_boundary.py b/backend/tests/services/freight_rpa/test_import_boundary.py new file mode 100644 index 00000000..f081a633 --- /dev/null +++ b/backend/tests/services/freight_rpa/test_import_boundary.py @@ -0,0 +1,40 @@ +"""freight_rpa 包 import 边界适应度测试。 + +用途:锁死阶段 B 验收标准——freight_rpa 不寄生业务编排。 +依赖:app/services/freight_rpa 包、ast。 +逻辑:遍历包内 .py 的 import(ast 解析),命中禁列即失败; + 白名单为空集(批次 B Task 6 起审计写入已下沉本包 + common/report_audit,包内不再引用任何 shipping_notice 业务模块; + 历史 file_assets 白名单条目随迁移一并删除——包内只引用 + app.services.file_assets,不属 shipping_notice 命名空间)。 +""" +from __future__ import annotations + +import ast +from pathlib import Path + +PKG = Path(__file__).resolve().parents[3] / "app" / "services" / "freight_rpa" + +# 空集:freight_rpa 禁止 import 任何 app.services.shipping_notice.* 模块 +# (审计写入走本包 common/report_audit;模型 import 走 app.models,不在此列)。 +ALLOWED_SHIPPING_NOTICE: set[str] = set() + + +def _imported_modules(path: Path) -> set[str]: + tree = ast.parse(path.read_text(encoding="utf-8")) + mods: set[str] = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + mods.update(a.name for a in node.names) + elif isinstance(node, ast.ImportFrom) and node.module: + mods.add(node.module) + return mods + +def test_freight_rpa_import_boundary(): + assert PKG.exists(), "freight_rpa 包不存在" + violations: list[str] = [] + for py in PKG.rglob("*.py"): + for mod in _imported_modules(py): + if mod.startswith("app.services.shipping_notice") and mod not in ALLOWED_SHIPPING_NOTICE: + violations.append(f"{py.name}: {mod}") + assert not violations, "freight_rpa 违规 import:\n" + "\n".join(violations) diff --git a/backend/tests/services/freight_rpa/test_outbound_trigger_contract.py b/backend/tests/services/freight_rpa/test_outbound_trigger_contract.py new file mode 100644 index 00000000..9f4c2630 --- /dev/null +++ b/backend/tests/services/freight_rpa/test_outbound_trigger_contract.py @@ -0,0 +1,16 @@ +""" +tests/services/freight_rpa/test_outbound_trigger_contract.py + +用途:出站 RPA trigger_io 与 Worker 心跳能力串的契约常量回归。 +依赖:freight_rpa.outbound.trigger_io、worker_heartbeat.OUTBOUND_EXPORT_CAPABILITY。 +逻辑:Task 7 接口清单的单一真相,防止 schema/action/能力名漂移。 +""" +from app.services.freight_rpa.outbound import trigger_io +from app.services.freight_rpa.common.worker_heartbeat import OUTBOUND_EXPORT_CAPABILITY + + +def test_outbound_trigger_constants(): + """出站 trigger schema/action 与 Worker outbound_export 能力须与设计 spec 一致。""" + assert trigger_io.SCHEMA == "freight_rpa.outbound.v1" + assert trigger_io.ACTION_OUTBOUND_EXPORT_BATCH == "outbound_export_batch" + assert OUTBOUND_EXPORT_CAPABILITY == "outbound_export" diff --git a/backend/tests/services/freight_rpa/test_report_fact_dispatch.py b/backend/tests/services/freight_rpa/test_report_fact_dispatch.py new file mode 100644 index 00000000..cf1f28b4 --- /dev/null +++ b/backend/tests/services/freight_rpa/test_report_fact_dispatch.py @@ -0,0 +1,196 @@ +"""tests/services/freight_rpa/test_report_fact_dispatch.py + +用途:锁定阶段 B Task 6——inbound 回调「先提交文件/终态,再投递事实」的顺序契约。 +依赖:pytest、tests/conftest 的 app 夹具(种子站点 DSV360_AWSDU)、 + app.core.errors.AppError、app.services.freight_rpa.reports.facts.ReportFact、 + freight_rpa.reports.dispatch.register_report_handler(Task 6 新增)、 + freight_rpa.inbound.report_archive.ingest_inbound_callback。 +逻辑:(1)处理函数抛异常时已 commit 的归档文件行仍在(不回滚)且异常原样外抛; + (2)同一 unit_run_id + sha256 重复回调不插第二行,事实仍重复投递 ok=True + (供处理函数重试);(3)kind 未注册处理函数时 404 + FREIGHT_RPA.SINK_NOT_REGISTERED,已提交文件行不受影响; + (4)empty 终态同样先 commit 再投递 ok=False 事实。 +""" + +from __future__ import annotations + +import hashlib + +import pytest + +from app.services.freight_rpa.reports.facts import ReportFact + +SEED_SOURCE_CODE = "DSV360_AWSDU" + +# 归档 IO 替身的注入字节:_fake_archive_io 夹具把它喂给 +# _read_inbound_callback_file,_success_payload 按需覆写。 +_FAKE_FILE_BYTES: dict[str, bytes] = {"data": b"abc"} + +# callback_id 唯一约束的测试序号(跨用例递增,避免 unique 冲突)。 +_CALLBACK_SEQ: dict[str, int] = {"n": 0} + + +@pytest.fixture +def db_session(app): + """复用 app 夹具已建立的应用上下文会话,供测试直接落库与查询。""" + from app import db + + return db.session + + +@pytest.fixture(autouse=True) +def _reset_report_handlers(): + """每用例隔离 dispatch 注册表(模块级全局字典),避免用例间处理函数串扰。 + + [断言意图] 缺处理器用例必须跑在"干净注册表"上——否则前序用例注册的 + inbound 处理函数会让 404 用例假绿。 + """ + from app.services.freight_rpa.reports import dispatch as dispatch_module + + saved = dict(dispatch_module._REPORT_HANDLERS) + dispatch_module._REPORT_HANDLERS.clear() + yield + dispatch_module._REPORT_HANDLERS.clear() + dispatch_module._REPORT_HANDLERS.update(saved) + + +@pytest.fixture(autouse=True) +def _fake_archive_io(monkeypatch): + """替身归档 IO:drop 根读取返回注入字节,MinIO 上传 no-op。 + + 核心逻辑:与旧回调测试同一 monkeypatch 姿态(patch report_archive 模块属性), + 使 ingest 的 success 分支可脱离真实文件系统与对象存储走完全程。 + """ + from app.services.freight_rpa.inbound import report_archive + + monkeypatch.setattr(report_archive, "_read_inbound_callback_file", lambda _path: _FAKE_FILE_BYTES["data"]) + monkeypatch.setattr( + "app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes", + lambda **_kwargs: None, + ) + + +def _next_callback_id(prefix: str) -> str: + """生成跨用例唯一的 callback_id(满足 unit run 唯一约束)。""" + _CALLBACK_SEQ["n"] += 1 + return f"{prefix}-{_CALLBACK_SEQ['n']}" + + +def _awaiting_unit(*, source_code: str = "DSV"): + """构造一个处于 awaiting_rpa 的 inbound 执行单元(挂种子站点满足外键)。 + + 核心逻辑:source_code 列允许测试值(如 "DSV"),source_id 外键挂种子站点 + DSV360_AWSDU——与 test_report_queries.py 的 _inbound_file 同构。 + """ + from app.models import FreightRpaInboundUnitRun, FreightRpaSource + + source = FreightRpaSource.query.filter_by(source_code=SEED_SOURCE_CODE).one() + return FreightRpaInboundUnitRun( + source_id=source.id, + source_code=source_code, + connector_type="dbs", + callback_id=_next_callback_id("report-fact-dispatch"), + status="awaiting_rpa", + config_snapshot_json={}, + ) + + +def _success_payload(unit, *, sha256_file: bytes = b"abc") -> dict: + """构造通过 schema 校验的 success 回调载荷;sha256_file 即被模拟读取的 xlsx 字节。""" + _FAKE_FILE_BYTES["data"] = sha256_file + return { + "schema_version": "freight_rpa.inbound.v1", + "callback_id": unit.callback_id, + "status": "success", + "file_path": f"receipt_{unit.id or 'x'}.xlsx", + "original_filename": "receipt.xlsx", + "sha256": hashlib.sha256(sha256_file).hexdigest(), + } + + +def test_handler_failure_keeps_committed_file(app, db_session, monkeypatch): + """处理函数失败绝不回滚已 commit 的归档文件行,异常原样外抛(不吞)。""" + from app.models import FreightRpaInboundReportFile + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback + from app.services.freight_rpa.reports.dispatch import register_report_handler + + unit = _awaiting_unit(source_code="DSV") + db_session.add(unit) + db_session.commit() + + def boom(fact: ReportFact) -> None: + raise RuntimeError("handler down") + + register_report_handler("inbound", boom) + with pytest.raises(RuntimeError, match="handler down"): + ingest_inbound_callback(_success_payload(unit, sha256_file=b"abc")) + # [断言意图] 异常外抛但文件行已提交:count==1 锁死「先 commit 再投递」顺序。 + assert FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1 + + +def test_second_delivery_does_not_insert_another_file(app, db_session): + """同一回调重放不插第二行文件,事实仍重复投递(同一 file_id、ok=True)。""" + from app.models import FreightRpaInboundReportFile + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback + from app.services.freight_rpa.reports.dispatch import register_report_handler + + seen: list[ReportFact] = [] + register_report_handler("inbound", seen.append) + unit = _awaiting_unit(source_code="DSV") + db_session.add(unit) + db_session.commit() + payload = _success_payload(unit, sha256_file=b"abc") + ingest_inbound_callback(payload) + ingest_inbound_callback(payload) + assert FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1 + # [断言意图] 幂等重放仍两次投递 ok=True 事实(同一 file_id),供处理函数重试。 + assert [fact.file_id for fact in seen] == [seen[0].file_id, seen[0].file_id] + assert all(fact.ok is True for fact in seen) + + +def test_missing_handler_raises_sink_not_registered(app, db_session): + """kind 未注册处理函数 → 404 FREIGHT_RPA.SINK_NOT_REGISTERED,文件行已提交。""" + from app.core.errors import AppError + from app.models import FreightRpaInboundReportFile + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback + + unit = _awaiting_unit(source_code="DSV") + db_session.add(unit) + db_session.commit() + with pytest.raises(AppError) as exc: + ingest_inbound_callback(_success_payload(unit, sha256_file=b"abc")) + assert exc.value.code == "FREIGHT_RPA.SINK_NOT_REGISTERED" + # [断言意图] 分发失败不回滚归档:文件行保留,Worker 重试整笔回调即可补投递。 + assert FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1 + + +def test_empty_callback_dispatches_failure_fact(app, db_session): + """empty 终态同样先 commit 再投递 ok=False 事实(error_code 随载荷落库值)。""" + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback + from app.services.freight_rpa.reports.dispatch import register_report_handler + + seen: list[ReportFact] = [] + register_report_handler("inbound", seen.append) + unit = _awaiting_unit(source_code="DSV") + db_session.add(unit) + db_session.commit() + result = ingest_inbound_callback( + { + "schema_version": "freight_rpa.inbound.v1", + "callback_id": unit.callback_id, + "status": "empty", + "error_code": "no_inbound_data", + "error_message": "no_inbound_data", + } + ) + assert result["status"] == "empty" + assert len(seen) == 1 + fact = seen[0] + # [断言意图] empty 是合法业务结果 → ok=False + error_code=no_inbound_data 的事实。 + assert fact.report_kind == "inbound" + assert fact.source_code == "DSV" + assert fact.ok is False + assert fact.file_id is None + assert fact.sha256 is None + assert fact.error_code == "no_inbound_data" + assert fact.error_message == "no_inbound_data" diff --git a/backend/tests/services/freight_rpa/test_report_queries.py b/backend/tests/services/freight_rpa/test_report_queries.py new file mode 100644 index 00000000..e337a274 --- /dev/null +++ b/backend/tests/services/freight_rpa/test_report_queries.py @@ -0,0 +1,282 @@ +"""tests/services/freight_rpa/test_report_queries.py + +用途:锁定阶段 B Task 3——freight_rpa.reports 只读查询模块的行为契约。 +依赖:pytest、app fixture(tests/conftest)、app.core.errors、 + app.services.freight_rpa.reports(待实现模块)。 +逻辑:覆盖(1)latest_usable_inbound_file 的可用门禁——未删除、当天 + (Asia/Shanghai 业务日)抓取、未过期、最新优先;(2)require_report_kind 的 + 白名单校验;(3)站点/在手/入站配置只读视图;(4)按 storage_key 读文件 + 字节 + 缺文件 NotFoundError;(5)解析失败三列的标记与清除(仅 flush + 不 commit)。(6)业务日窗口内外的定向拒收/放行。 + 时间口径:查询的 now 参数显式传 naive UTC;文件 created_at 也按 naive UTC + 存入,两者用同一业务日窗口锚点(now=2026-10-05 12:00 UTC → 上海业务日 + 10-05,UTC 窗口 [10-04 16:00, 10-05 16:00))。 +""" + +from __future__ import annotations + +from datetime import datetime, timedelta + +import pytest + +from app.core.errors import NotFoundError, ValidationError +from app.services.freight_rpa.reports import ( + clear_inbound_parse_failure, + get_inbound_config, + get_onhand_config, + get_site, + latest_usable_inbound_file, + mark_inbound_parse_failure, + read_inbound_file_bytes, + require_report_kind, +) + +SEED_SOURCE_CODE = "DSV360_AWSDU" + +# 业务日窗口锚点(naive UTC):2026-10-05 12:00 UTC = 上海 10-05 20:00, +# 对应业务日 2026-10-05 的 UTC 存储窗口 [10-04 16:00, 10-05 16:00)。 +FROZEN_NOW = datetime(2026, 10, 5, 12, 0, 0) + + +@pytest.fixture +def db_session(app): + """复用 app fixture 已建立的应用上下文会话,供测试直接落库与查询。""" + from app import db + + return db.session + + +def _inbound_file(*, source_code: str, sha256: str, created_at: datetime, **overrides): + """构造一条挂在指定 source_code 执行单元下的入站归档文件(含 unit run)。 + + 核心逻辑:外键要求文件必须挂在 FreightRpaInboundUnitRun 下,unit run 再挂 + 种子站点(DSV360_AWSDU);source_code 写进 unit run 列(非外键,允许 "DSV" + 等测试值),便于验证查询按 unit run 的 source_code 过滤。 + """ + from app import db + from app.models import FreightRpaInboundReportFile, FreightRpaInboundUnitRun, FreightRpaSource + + source = FreightRpaSource.query.filter_by(source_code=SEED_SOURCE_CODE).one() + unit = FreightRpaInboundUnitRun( + source_id=source.id, + source_code=source_code, + connector_type="dbs", + callback_id=f"test-callback:{source_code}:{sha256[:8]}", + status="success", + config_snapshot_json={}, + **overrides, + ) + db.session.add(unit) + db.session.flush() + report_file = FreightRpaInboundReportFile( + unit_run_id=unit.id, + storage_provider="minio", + storage_bucket="test", + storage_key=f"freight_rpa/inbound/{source_code}/{sha256[:12]}.xlsx", + original_filename=f"{sha256[:8]}.xlsx", + file_size=16, + sha256=sha256, + created_at=created_at, + ) + db.session.add(report_file) + return report_file + + +def test_latest_usable_inbound_file_returns_newest(app, db_session): + """同一业务日窗口内的两份可用文件 → 按 created_at 倒序取最新一份。 + + [断言意图] 两份文件的 created_at 均落在 FROZEN_NOW 的业务日 UTC 窗口 + ([10-04 16:00, 10-05 16:00))内,证明「最新优先」在当天门禁内生效, + 而不是因为当天新鲜度被丢掉才命中。 + """ + older = _inbound_file(source_code="DSV", sha256="a" * 64, created_at=datetime(2026, 10, 4, 18, 0, 0)) + newer = _inbound_file(source_code="DSV", sha256="b" * 64, created_at=datetime(2026, 10, 5, 2, 0, 0)) + db_session.add_all([older, newer]) + db_session.commit() + view = latest_usable_inbound_file("DSV", now=FROZEN_NOW) + assert view is not None + assert view.file_id == newer.id + assert view.sha256 == "b" * 64 + + +def test_latest_usable_inbound_file_rejects_out_of_business_day(app, db_session): + """「当天(Asia/Shanghai 业务日)抓取」是可用门禁的一部分:隔日文件不可用。 + + [断言意图] 同一份文件(expries 为空、未删除)在非当天业务日查 → None; + 把判定时刻推回文件被抓取的那个业务日 → 又可用;差异只能来自当天窗口, + 锁死修复轮补回的新鲜度条件。 + """ + report = _inbound_file(source_code="STL", sha256="0" * 64, created_at=datetime(2026, 10, 3, 10, 0, 0)) + db_session.commit() + + # FROZEN_NOW(业务日 10-05)下,10-03 抓取的文件是隔日旧文件 → 不可用。 + assert latest_usable_inbound_file("STL", now=FROZEN_NOW) is None + # 业务日 10-03 的窗口为 UTC [10-02 16:00, 10-03 16:00):10-03 10:00 UTC 在窗口内 → 可用。 + in_day_now = datetime(2026, 10, 3, 12, 0, 0) + view = latest_usable_inbound_file("STL", now=in_day_now) + assert view is not None + assert view.file_id == report.id + + +def test_latest_usable_inbound_file_skips_deleted_and_expired(app, db_session): + """已删除/已过期的文件不得被当作可用文件返回;同来源保留最新可用一份。""" + # [断言意图] 三份文件都在 FROZEN_NOW 的业务日窗口内,且已删除/已过期两份 + # 更新——若门禁失效,“最新优先”会先命中它们;断言只能命中唯一的可用文件。 + usable = _inbound_file(source_code="CRN", sha256="c" * 64, created_at=datetime(2026, 10, 4, 20, 0, 0)) + deleted = _inbound_file(source_code="CRN", sha256="d" * 64, created_at=datetime(2026, 10, 5, 1, 0, 0)) + deleted.archive_deleted_at = datetime(2026, 10, 5, 5, 0, 0) + expired = _inbound_file(source_code="CRN", sha256="e" * 64, created_at=datetime(2026, 10, 5, 2, 0, 0)) + # 保留期早于判定时刻(仍未被清理任务删除)→ 过期不可用。 + expired.archive_expires_at = FROZEN_NOW - timedelta(hours=1) + db_session.add_all([usable, deleted, expired]) + db_session.commit() + + view = latest_usable_inbound_file("CRN", now=FROZEN_NOW) + assert view is not None + assert view.sha256 == "c" * 64 + assert view.source_code == "CRN" + assert view.storage_key.endswith(f"{'c' * 12}.xlsx") + assert view.original_filename == f"{'c' * 8}.xlsx" + assert view.created_at == datetime(2026, 10, 4, 20, 0, 0) + + +def test_latest_usable_inbound_file_no_match_returns_none(app, db_session): + """来源无任何归档文件(或全部不可用)时返回 None,不抛异常。""" + assert latest_usable_inbound_file("NOPE") is None + + +def test_report_kind_rejects_shipment(): + with pytest.raises(ValidationError): + require_report_kind("shipment") + assert require_report_kind("outbound") == "outbound" + + +def test_get_site_returns_view_of_seeded_source(app): + """get_site 返回站点连接与模板绑定的只读视图;未知来源返回 None。""" + view = get_site(SEED_SOURCE_CODE) + assert view is not None + assert view.source_code == SEED_SOURCE_CODE + assert view.display_name == "DBS Dublin AWSDU" + assert view.connector_type == "dbs" + assert view.excel_template_id is not None + assert view.enabled is True + assert get_site("NOPE") is None + + +def test_get_onhand_config_returns_report_definition(app): + """get_onhand_config 返回 s18 起挂在配置行上的报表路径/查询条件/解析方案。""" + config = get_onhand_config(SEED_SOURCE_CODE) + assert config is not None + assert config.report_path_json.get("program_group") == "Bison" + assert config.query_parameters_json == [ + {"name": "Warehouse", "mode": "single", "values": ["AWSDU"], "required": True, "select_all": False}, + ] + assert config.parsing_profile_id is not None + # [断言意图] 未知来源与存在但未配置报表的来源都必须返回 None(fail-closed)。 + assert get_onhand_config("NOPE") is None + + +def test_get_inbound_config_returns_none_without_config_row(app): + """种子站点没有入站报表配置行 → get_inbound_config 返回 None。""" + from app import db + from app.models import FreightRpaInboundReportConfig, FreightRpaSource + + source = FreightRpaSource.query.filter_by(source_code=SEED_SOURCE_CODE).one() + assert get_inbound_config(SEED_SOURCE_CODE) is None + # [断言意图] 补一条配置行后即可读出三个字段(与在手配置视图同构)。 + db.session.add(FreightRpaInboundReportConfig( + source=source, + report_path_json={"program_group": "Bison", "report_name": "Receipt"}, + query_parameters_json=[{"name": "Date", "mode": "range"}], + parsing_profile_id=None, + )) + db.session.commit() + config = get_inbound_config(SEED_SOURCE_CODE) + assert config is not None + assert config.report_path_json["report_name"] == "Receipt" + assert config.query_parameters_json == [{"name": "Date", "mode": "range"}] + assert config.parsing_profile_id is None + + +def test_read_inbound_file_bytes_reads_by_storage_key(app, db_session, monkeypatch): + """read_inbound_file_bytes 按文件的 storage_key 调 file_asset_storage 读取。""" + from app.services.freight_rpa.reports import queries as queries_module + + report_file = _inbound_file(source_code="DSV", sha256="f" * 64, created_at=datetime(2026, 10, 6)) + db_session.commit() + + captured: dict[str, bytes] = {} + + def fake_get_bytes(storage_key): + captured["key"] = storage_key + return b"xlsx-bytes" + + monkeypatch.setattr(queries_module.file_asset_storage, "get_bytes", fake_get_bytes) + + assert read_inbound_file_bytes(report_file.id) == b"xlsx-bytes" + assert captured["key"] == report_file.storage_key + + +def test_read_inbound_file_bytes_missing_file_raises(app): + """文件 id 不存在 → NotFoundError(fail-closed,不吞 404)。""" + with pytest.raises(NotFoundError): + read_inbound_file_bytes(999999) + + +def test_mark_and_clear_inbound_parse_failure_roundtrip(app, db_session): + """mark 写入三列并 flush(不 commit 由调用方决定);clear 清空恢复。""" + from datetime import timedelta + + report_file = _inbound_file(source_code="DSV", sha256="9" * 64, created_at=datetime(2026, 10, 7)) + db_session.commit() + file_id = report_file.id + + mark_inbound_parse_failure( + file_id, + error_code="X" * 80, + error_message="m" * 2500, + ) + # [断言意图] 只 flush 不 commit——新开的同一事务查询立即可见,且列宽截断生效。 + from app import db + from app.models import FreightRpaInboundReportFile + + marked = db.session.get(FreightRpaInboundReportFile, file_id) + assert marked.parse_failed_at is not None + assert marked.parse_failed_at > datetime.utcnow() - timedelta(minutes=1) + assert marked.parse_error_code == "X" * 64 + assert marked.parse_error_message == "m" * 2000 + db_session.commit() + + clear_inbound_parse_failure(file_id) + cleared = db.session.get(FreightRpaInboundReportFile, file_id) + assert cleared.parse_failed_at is None + assert cleared.parse_error_code is None + assert cleared.parse_error_message is None + db_session.commit() + + +def test_mark_inbound_parse_failure_missing_file_raises(app): + """文件 id 不存在 → NotFoundError,与其他按 id 操作一致。""" + with pytest.raises(NotFoundError): + mark_inbound_parse_failure(999999, error_code="E", error_message="m") + + +def test_import_boundary_no_business_module_imports(): + """本模块(发货与调拨读报表唯一入口)不得 import shipping_notice / in_transit_transfer。""" + import ast + from pathlib import Path + + pkg = Path(__file__).resolve().parents[3] / "app" / "services" / "freight_rpa" / "reports" + assert pkg.exists() + for py in pkg.rglob("*.py"): + tree = ast.parse(py.read_text(encoding="utf-8")) + for node in ast.walk(tree): + if isinstance(node, ast.Import): + mods = [a.name for a in node.names] + elif isinstance(node, ast.ImportFrom) and node.module: + mods = [node.module] + else: + continue + for mod in mods: + assert not mod.startswith("app.services.shipping_notice"), f"{py.name}: {mod}" + assert not mod.startswith("app.services.in_transit_transfer"), f"{py.name}: {mod}" \ No newline at end of file diff --git a/backend/tests/services/freight_rpa/test_upload_trigger_contract.py b/backend/tests/services/freight_rpa/test_upload_trigger_contract.py new file mode 100644 index 00000000..cf6fc2f6 --- /dev/null +++ b/backend/tests/services/freight_rpa/test_upload_trigger_contract.py @@ -0,0 +1,59 @@ +""" +backend/tests/services/freight_rpa/test_upload_trigger_contract.py + +用途:锁死 upload trigger 写入契约——action 与心跳能力 freight_rpa_upload 对齐,schema 为 freight_rpa.upload.v1。 +依赖:app.services.freight_rpa.upload.trigger_io、Flask app fixture。 +逻辑:断言模块常量;write_upload_trigger 落盘后 JSON 的 action/schema_version 与常量一致。 +""" + +from __future__ import annotations + +import json +from pathlib import Path + +from app.services.freight_rpa.common.worker_heartbeat import FREIGHT_RPA_UPLOAD_CAPABILITY +from app.services.freight_rpa.upload import trigger_io + + +def test_upload_trigger_constants_align_with_heartbeat_capability(): + """upload action 必须与 Worker 心跳能力串 freight_rpa_upload 一致。""" + assert trigger_io.SCHEMA == "freight_rpa.upload.v1" + assert trigger_io.ACTION_FREIGHT_RPA_UPLOAD == "freight_rpa_upload" + assert trigger_io.ACTION_FREIGHT_RPA_UPLOAD == FREIGHT_RPA_UPLOAD_CAPABILITY + assert "outbound_upload" not in trigger_io.ACTION_FREIGHT_RPA_UPLOAD + assert "shipment_upload" not in trigger_io.ACTION_FREIGHT_RPA_UPLOAD + + +def test_write_upload_trigger_persists_freight_upload_action(app, tmp_path): + """落盘 trigger JSON 的 action/schema_version 须与模块常量一致。""" + export_file = tmp_path / "queue_src" / "SN-001.xlsx" + export_file.parent.mkdir(parents=True) + export_file.write_bytes(b"fake-xlsx") + + upload_queue = tmp_path / "upload_queue" + upload_trigger = tmp_path / "upload_triggers" + upload_queue.mkdir() + upload_trigger.mkdir() + + with app.app_context(): + app.config["FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(upload_queue) + app.config["FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(upload_trigger) + queue_path, trigger_path, callback_id = trigger_io.write_upload_trigger( + "TASK-UP-1", + str(export_file), + attempt_id=10, + artifact_id=20, + connector_type="dbs", + callback_id="upload-cb-1", + ) + + assert queue_path + assert trigger_path + assert callback_id == "upload-cb-1" + + payload = json.loads(Path(trigger_path).read_text(encoding="utf-8")) + # [断言意图] Worker 侧不校验 action 字面量,但双侧契约文档须与心跳能力 freight_rpa_upload 对齐。 + assert payload["action"] == trigger_io.ACTION_FREIGHT_RPA_UPLOAD + assert payload["schema_version"] == trigger_io.SCHEMA + assert payload["action"] == "freight_rpa_upload" + assert payload["schema_version"] == "freight_rpa.upload.v1" diff --git a/backend/tests/test_rpa_worker_heartbeat.py b/backend/tests/services/freight_rpa/test_worker_heartbeat.py similarity index 85% rename from backend/tests/test_rpa_worker_heartbeat.py rename to backend/tests/services/freight_rpa/test_worker_heartbeat.py index dba5026a..a7eed125 100644 --- a/backend/tests/test_rpa_worker_heartbeat.py +++ b/backend/tests/services/freight_rpa/test_worker_heartbeat.py @@ -1,8 +1,8 @@ """ -backend/tests/test_rpa_worker_heartbeat.py +backend/tests/services/freight_rpa/test_worker_heartbeat.py 用途:货代库存/上传 RPA Worker 心跳存储、共享目录校验、就绪检查与 API 契约单测。 -依赖:rpa_worker_heartbeat、shipping_notice_tools heartbeat 路由。 +依赖:freight_rpa.common.worker_heartbeat、shipping_notice_tools heartbeat 路由。 逻辑:覆盖跨平台 scope、哨兵、Redis 策略、环境匹配、货代上传就绪与 fail-fast 断言。 """ @@ -14,10 +14,10 @@ from typing import Any import pytest from app.core.errors import ServiceUnavailableError -from app.services.shipping_notice.rpa_worker_heartbeat import ( - FREIGHT_UPLOAD_CAPABILITY, - INVENTORY_EXPORT_CAPABILITY, - RECEIPT_EXPORT_CAPABILITY, +from app.services.freight_rpa.common.worker_heartbeat import ( + FREIGHT_RPA_UPLOAD_CAPABILITY, + ONHAND_EXPORT_CAPABILITY, + INBOUND_EXPORT_CAPABILITY, RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE, RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE, RPA_WORKER_OFFLINE_MESSAGE, @@ -53,7 +53,7 @@ def _heartbeat_payload( "worker_id": worker_id, "hostname": "WIN-RPA-HOST", "environment": environment or resolve_backend_rpa_environment(), - "capabilities": capabilities or [INVENTORY_EXPORT_CAPABILITY], + "capabilities": capabilities or [ONHAND_EXPORT_CAPABILITY], "status": "idle", "trigger_dir": trigger_dir, "drop_dir": str(trigger_dir).replace("triggers", "drop"), @@ -68,7 +68,7 @@ def _enable_prod_like_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-d trigger_dir.mkdir() _write_shared_sentinel(trigger_dir, scope_id=scope_id) app.config["ENV_NAME"] = "test" - app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir) app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False @@ -133,7 +133,7 @@ def test_missing_shared_sentinel_blocks_readiness_in_test_env(app, tmp_path): trigger_dir = tmp_path / "triggers" trigger_dir.mkdir() app.config["ENV_NAME"] = "test" - app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir) 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_ALLOW_MEMORY_FALLBACK"] = True @@ -155,11 +155,11 @@ def test_record_heartbeat_requires_redis_when_configured(app, tmp_path, monkeypa """生产策略要求 Redis 时,写入失败应抛存储不可用。""" trigger_dir = tmp_path / "triggers" trigger_dir.mkdir() - app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir) app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat._redis_store_worker", + "app.services.freight_rpa.common.worker_heartbeat._redis_store_worker", lambda _worker: False, ) @@ -172,20 +172,20 @@ def test_record_heartbeat_requires_redis_when_configured(app, tmp_path, monkeypa def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch): """fail-fast 应附带 reasons 详情供排程日志与运维定位。""" - from app.services.shipping_notice.rpa_worker_heartbeat import ( + from app.services.freight_rpa.common.worker_heartbeat import ( reset_rpa_worker_heartbeat_state_for_tests, ) # 隔离:强制无 Redis 分支(_redis_client 为模块级单例,config 置空不可靠,须 monkeypatch); # 并清空心跳存储,确保走 no_worker_heartbeat + 进程内存储原因码。 - from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module + from app.services.freight_rpa.common import worker_heartbeat as heartbeat_module monkeypatch.setattr(heartbeat_module, "_redis_client", lambda: None) reset_rpa_worker_heartbeat_state_for_tests() trigger_dir = tmp_path / "triggers" trigger_dir.mkdir() _write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data") app.config["ENV_NAME"] = "test" - app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir) 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_ALLOW_MEMORY_FALLBACK"] = True @@ -202,13 +202,13 @@ def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path assert (exc_info.value.details or {}).get("detail_message") -def test_assert_receipt_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch): +def test_assert_inbound_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch): """收料 fail-fast 应附带 reasons,且与库存同口径要求共享哨兵。""" from app.core.errors import ServiceUnavailableError - from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module - from app.services.shipping_notice.rpa_worker_heartbeat import ( + from app.services.freight_rpa.common import worker_heartbeat as heartbeat_module + from app.services.freight_rpa.common.worker_heartbeat import ( RPA_WORKER_OFFLINE_MESSAGE, - assert_receipt_rpa_worker_ready, + assert_inbound_rpa_worker_ready, reset_rpa_worker_heartbeat_state_for_tests, ) @@ -217,14 +217,14 @@ def test_assert_receipt_rpa_worker_ready_includes_reason_details(app, tmp_path, 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_SHARED_INBOUND_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() + assert_inbound_rpa_worker_ready() # [断言意图] 与库存同构的用户可见文案与 reasons;缺哨兵与无心跳同时暴露, # 对应部署侧必须由 ps1 注入 FREIGHT_RPA_SHARED_SCOPE_ID 写哨兵。 assert exc_info.value.message == RPA_WORKER_OFFLINE_MESSAGE @@ -249,7 +249,7 @@ def test_check_inventory_rpa_worker_ready_rejects_stale_heartbeat(app, tmp_path, ) ) monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat.time.time", + "app.services.freight_rpa.common.worker_heartbeat.time.time", lambda: base_now + 120, ) result = check_inventory_rpa_worker_ready() @@ -258,7 +258,7 @@ def test_check_inventory_rpa_worker_ready_rejects_stale_heartbeat(app, tmp_path, def test_rpa_heartbeat_api_records_worker(client, app, tmp_path): - """POST /rpa/heartbeat 应写入心跳并返回 ok。""" + """POST /api/freight-rpa/heartbeat 应写入心跳并返回 ok(旧 shipping-notice 路由已删)。""" trigger_dir = tmp_path / "triggers" trigger_dir.mkdir() app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "test-tool-key" @@ -266,7 +266,7 @@ def test_rpa_heartbeat_api_records_worker(client, app, tmp_path): payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve())) res = client.post( - "/api/shipping-notice/rpa/heartbeat", + "/api/freight-rpa/heartbeat", headers={"X-Integration-Key": "test-tool-key"}, json=payload, ) @@ -283,7 +283,7 @@ def test_rpa_heartbeat_api_rejects_missing_auth(client, app, tmp_path): app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "test-tool-key" payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve())) - res = client.post("/api/shipping-notice/rpa/heartbeat", json=payload) + res = client.post("/api/freight-rpa/heartbeat", json=payload) assert res.status_code == 401 @@ -295,7 +295,7 @@ def test_rpa_heartbeat_api_rejects_invalid_auth(client, app, tmp_path): payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve())) res = client.post( - "/api/shipping-notice/rpa/heartbeat", + "/api/freight-rpa/heartbeat", headers={"X-Integration-Key": "wrong-key"}, json=payload, ) @@ -306,9 +306,9 @@ def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp """排程触发时 worker 离线应立即 failed,不进入 awaiting_rpa_callback。""" from app import db from app.models import ScheduleRun, ScheduleTask, User - from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule - from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module - from app.services.shipping_notice.rpa_worker_heartbeat import ( + from app.services.schedule.freight_rpa_onhand_job import run_freight_rpa_onhand_schedule + from app.services.freight_rpa.common import worker_heartbeat as heartbeat_module + from app.services.freight_rpa.common.worker_heartbeat import ( reset_rpa_worker_heartbeat_state_for_tests, ) @@ -326,7 +326,7 @@ def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp schedule_no="SCH-HB-OFFLINE", name="货代库存每日导出", schedule_type="platform_job", - platform_api_path="shipping-inventory-rpa", + platform_api_path="freight-rpa-onhand", owner_user_id=user.id, cron_expr="0 3 * * *", enabled=True, @@ -337,7 +337,7 @@ def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp db.session.add(run) db.session.commit() - total, success, failed, skipped, _details, errors, logs = run_shipping_inventory_rpa_schedule(task, run) + total, success, failed, skipped, _details, errors, logs = run_freight_rpa_onhand_schedule(task, run) assert total >= 1 assert success == 0 assert failed >= 1 @@ -364,7 +364,7 @@ def test_redis_read_failure_reports_storage_unavailable_not_offline(app, tmp_pat raise ConnectionError("redis read failed") monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat._redis_client", + "app.services.freight_rpa.common.worker_heartbeat._redis_client", lambda: BrokenRedis(), ) @@ -400,7 +400,7 @@ def test_redis_store_and_list_ready_with_prod_policy(app, tmp_path, monkeypatch) return bucket.get(key) monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat._redis_client", + "app.services.freight_rpa.common.worker_heartbeat._redis_client", lambda: FakeRedis(), ) @@ -417,13 +417,13 @@ def test_redis_store_and_list_ready_with_prod_policy(app, tmp_path, monkeypatch) def test_shared_scope_id_derived_from_mount_path_when_env_missing(app, tmp_path): """未显式配置 scope 时,可从 /mnt/hxops-rpa-* 挂载路径推导。""" - from app.services.shipping_notice.rpa_worker_heartbeat import shared_scope_id + from app.services.freight_rpa.common.worker_heartbeat import shared_scope_id trigger_dir = tmp_path / "mnt" / "hxops-rpa-test-data" / "inventory_triggers" trigger_dir.mkdir(parents=True) _write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data") app.config.pop("FREIGHT_RPA_SHARED_SCOPE_ID", None) - app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir) with app.app_context(): assert shared_scope_id() == "hxops-rpa-test-data" @@ -457,24 +457,24 @@ def test_check_freight_upload_rpa_ready_requires_freight_upload_capability(app, _heartbeat_payload( trigger_dir=str(upload_trigger), shared_scope_id="hxops-rpa-test-data", - capabilities=[INVENTORY_EXPORT_CAPABILITY], + capabilities=[ONHAND_EXPORT_CAPABILITY], ) ) result = check_freight_upload_rpa_ready() - # 关键断言:缺少 freight_upload 能力必须阻断自动上传。 + # 关键断言:缺少 freight_rpa_upload 能力必须阻断自动上传。 assert result.ready is False - assert any("missing_freight_upload_capability" in reason for reason in result.reasons) + assert any("missing_freight_rpa_upload_capability" in reason for reason in result.reasons) def test_check_freight_upload_rpa_ready_when_worker_and_dirs_ok(app, tmp_path): - """Worker 声明 freight_upload 且目录/凭据齐全时应 ready。""" + """Worker 声明 freight_rpa_upload 且目录/凭据齐全时应 ready。""" upload_trigger = _enable_freight_upload_checks(app, tmp_path) with app.app_context(): record_rpa_worker_heartbeat( _heartbeat_payload( trigger_dir=str(upload_trigger), shared_scope_id="hxops-rpa-test-data", - capabilities=[INVENTORY_EXPORT_CAPABILITY, FREIGHT_UPLOAD_CAPABILITY], + capabilities=[ONHAND_EXPORT_CAPABILITY, FREIGHT_RPA_UPLOAD_CAPABILITY], ) ) result = check_freight_upload_rpa_ready() @@ -483,7 +483,7 @@ def test_check_freight_upload_rpa_ready_when_worker_and_dirs_ok(app, tmp_path): def test_assert_freight_upload_rpa_ready_includes_reasons(app, tmp_path): """上传 fail-fast 须带 reasons,供建单前/触发时展示阻断原因。""" - from app.services.shipping_notice.rpa_worker_heartbeat import ( + from app.services.freight_rpa.common.worker_heartbeat import ( reset_rpa_worker_heartbeat_state_for_tests, ) @@ -501,8 +501,8 @@ def test_assert_freight_upload_rpa_ready_includes_reasons(app, tmp_path): def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path): """收料 ready 与库存同口径:要求共享哨兵;仅有库存 Worker 不能冒充收料在线。""" - from app.services.shipping_notice.rpa_worker_heartbeat import ( - check_receipt_rpa_worker_ready, + from app.services.freight_rpa.common.worker_heartbeat import ( + check_inbound_rpa_worker_ready, reset_rpa_worker_heartbeat_state_for_tests, serialize_rpa_worker_status, ) @@ -513,8 +513,8 @@ def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path): 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_ONHAND_TRIGGER_DIR"] = str(inventory_trigger) + app.config["FREIGHT_RPA_SHARED_INBOUND_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 @@ -528,7 +528,7 @@ def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path): trigger_dir=str(inventory_trigger), shared_scope_id="hxops-rpa-test-data", )) - receipt_offline = check_receipt_rpa_worker_ready() + receipt_offline = check_inbound_rpa_worker_ready() assert receipt_offline.ready is False assert receipt_offline.workers == [] @@ -537,18 +537,18 @@ def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path): worker_id="HOST-receipt", trigger_dir=str(receipt_trigger), shared_scope_id="hxops-rpa-test-data", - capabilities=[RECEIPT_EXPORT_CAPABILITY], + capabilities=[INBOUND_EXPORT_CAPABILITY], )) - without_sentinel = check_receipt_rpa_worker_ready() + without_sentinel = check_inbound_rpa_worker_ready() assert without_sentinel.ready is False _write_shared_sentinel(receipt_trigger, scope_id="hxops-rpa-test-data") - receipt_ready = check_receipt_rpa_worker_ready() + receipt_ready = check_inbound_rpa_worker_ready() assert receipt_ready.ready is True assert [w["worker_id"] for w in receipt_ready.workers] == ["HOST-receipt"] - payload = serialize_rpa_worker_status(scope="receipt") - assert payload["scope"] == "receipt" + payload = serialize_rpa_worker_status(scope="inbound") + assert payload["scope"] == "inbound" assert payload["ready"] is True assert payload["trigger_dir"] == str(receipt_trigger) assert [w["worker_id"] for w in payload["workers"]] == ["HOST-receipt"] @@ -556,15 +556,15 @@ def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path): def test_receipt_worker_recognized_by_trigger_dir_without_receipt_suffix(app, tmp_path): """未注入 *-receipt 身份时,仍可用收料 trigger_dir 识别在线收料 Worker。""" - from app.services.shipping_notice.rpa_worker_heartbeat import ( - check_receipt_rpa_worker_ready, + from app.services.freight_rpa.common.worker_heartbeat import ( + check_inbound_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_INBOUND_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 @@ -577,8 +577,8 @@ def test_receipt_worker_recognized_by_trigger_dir_without_receipt_suffix(app, tm worker_id="Hugo-30820", trigger_dir=str(receipt_trigger), shared_scope_id="", - capabilities=[RECEIPT_EXPORT_CAPABILITY], + capabilities=[INBOUND_EXPORT_CAPABILITY], )) - result = check_receipt_rpa_worker_ready() + result = check_inbound_rpa_worker_ready() assert result.ready is True assert [w["worker_id"] for w in result.workers] == ["Hugo-30820"] diff --git a/backend/tests/test_rpa_worker_heartbeat_alert.py b/backend/tests/services/freight_rpa/test_worker_heartbeat_alert.py similarity index 88% rename from backend/tests/test_rpa_worker_heartbeat_alert.py rename to backend/tests/services/freight_rpa/test_worker_heartbeat_alert.py index 7d9fe64f..57743693 100644 --- a/backend/tests/test_rpa_worker_heartbeat_alert.py +++ b/backend/tests/services/freight_rpa/test_worker_heartbeat_alert.py @@ -1,8 +1,8 @@ """ -backend/tests/test_rpa_worker_heartbeat_alert.py +backend/tests/services/freight_rpa/test_worker_heartbeat_alert.py 用途:RPA Worker 心跳告警冷却、Redis/DB 不可用兜底与接收人回退单测。 -依赖:rpa_worker_heartbeat_alert、rpa_worker_heartbeat、models.AppSetting。 +依赖:freight_rpa.common.worker_heartbeat_alert、freight_rpa.common.worker_heartbeat、models.AppSetting。 逻辑:验证 DB 权威读取、Redis 陈旧/空 DB 清理、并发 claim、企微失败可重试、恢复与 admin 回退。 """ @@ -17,7 +17,7 @@ from sqlalchemy.exc import IntegrityError from app import db from app.models import AppSetting, User -from app.services.shipping_notice.rpa_worker_heartbeat_alert import ( +from app.services.freight_rpa.common.worker_heartbeat_alert import ( _DB_ALERT_STATE_KEY, _STATUS_SENDING, _claim_alert_send_lock, @@ -32,7 +32,7 @@ def _enable_alert_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-data" trigger_dir = tmp_path / "triggers" trigger_dir.mkdir() app.config["ENV_NAME"] = "test" - app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir) app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True @@ -62,7 +62,7 @@ def test_alert_state_memory_fallback_when_redis_save_fails(app, monkeypatch): raise ConnectionError("redis down") monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client", + "app.services.freight_rpa.common.worker_heartbeat_alert._redis_client", lambda: BrokenRedis(), ) @@ -89,15 +89,15 @@ def test_storage_unavailable_alert_respects_memory_cooldown(app, tmp_path, monke raise ConnectionError("redis write failed") monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat._redis_client", + "app.services.freight_rpa.common.worker_heartbeat._redis_client", lambda: BrokenRedis(), ) monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client", + "app.services.freight_rpa.common.worker_heartbeat_alert._redis_client", lambda: BrokenRedis(), ) monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat_alert._send_alert_to_recipients", + "app.services.freight_rpa.common.worker_heartbeat_alert._send_alert_to_recipients", lambda **kwargs: send_calls.append(kwargs["title"]) or True, ) @@ -129,11 +129,11 @@ def test_alert_fallback_admin_recipients(app, tmp_path, monkeypatch): return True monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat_alert._send_alert_to_recipients", + "app.services.freight_rpa.common.worker_heartbeat_alert._send_alert_to_recipients", _capture_send, ) monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready", + "app.services.freight_rpa.common.worker_heartbeat_alert.check_inventory_rpa_worker_ready", lambda: type( "Ready", (), @@ -147,7 +147,7 @@ def test_alert_fallback_admin_recipients(app, tmp_path, monkeypatch): ) with app.app_context(): - from app.services.shipping_notice.rpa_worker_heartbeat_alert import _alert_recipients + from app.services.freight_rpa.common.worker_heartbeat_alert import _alert_recipients recipients = _alert_recipients() assert len(recipients) == 1 @@ -170,7 +170,7 @@ def test_alert_state_persists_to_db_when_redis_unavailable(app, monkeypatch): raise ConnectionError("redis down") monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client", + "app.services.freight_rpa.common.worker_heartbeat_alert._redis_client", lambda: BrokenRedis(), ) @@ -191,7 +191,7 @@ def test_alert_logs_recipient_gap_when_no_wecom_users(app, tmp_path, monkeypatch app.config["FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready", + "app.services.freight_rpa.common.worker_heartbeat_alert.check_inventory_rpa_worker_ready", lambda: type( "Ready", (), @@ -225,7 +225,7 @@ def test_alert_prefers_configured_usernames_over_admin(app, tmp_path, monkeypatc ) db.session.commit() - from app.services.shipping_notice.rpa_worker_heartbeat_alert import _alert_recipients + from app.services.freight_rpa.common.worker_heartbeat_alert import _alert_recipients recipients = _alert_recipients() assert len(recipients) == 1 @@ -242,11 +242,11 @@ def test_alert_wecom_send_failure_allows_retry_before_cooldown(app, tmp_path, mo return send_attempts["count"] >= 2 monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat_alert._send_alert_to_recipients", + "app.services.freight_rpa.common.worker_heartbeat_alert._send_alert_to_recipients", _flaky_send, ) monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready", + "app.services.freight_rpa.common.worker_heartbeat_alert.check_inventory_rpa_worker_ready", lambda: type( "Ready", (), @@ -302,7 +302,7 @@ def test_concurrent_first_claim_integrity_error_does_not_claim(app, monkeypatch) raise IntegrityError("INSERT", {}, Exception("duplicate key")) monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat_alert._claim_alert_send_lock_db", + "app.services.freight_rpa.common.worker_heartbeat_alert._claim_alert_send_lock_db", _raise_integrity, ) @@ -342,11 +342,11 @@ def test_recovery_after_stale_sending_lock(app, tmp_path, monkeypatch): return True monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat_alert._send_alert_to_recipients", + "app.services.freight_rpa.common.worker_heartbeat_alert._send_alert_to_recipients", _capture_send, ) monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready", + "app.services.freight_rpa.common.worker_heartbeat_alert.check_inventory_rpa_worker_ready", lambda: type( "Ready", (), @@ -359,7 +359,7 @@ def test_recovery_after_stale_sending_lock(app, tmp_path, monkeypatch): )(), ) monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client", + "app.services.freight_rpa.common.worker_heartbeat_alert._redis_client", lambda: type("BrokenRedis", (), {"get": lambda *_a, **_k: None, "set": lambda *_a, **_k: None, "delete": lambda *_a, **_k: None})(), ) @@ -404,7 +404,7 @@ def test_load_alert_state_prefers_db_over_stale_redis(app, monkeypatch): redis_bucket.pop(key, None) monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client", + "app.services.freight_rpa.common.worker_heartbeat_alert._redis_client", lambda: FakeRedis(), ) @@ -448,7 +448,7 @@ def test_load_alert_state_overwrites_newer_stale_redis_from_db(app, monkeypatch) redis_bucket.pop(key, None) monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client", + "app.services.freight_rpa.common.worker_heartbeat_alert._redis_client", lambda: FakeRedis(), ) @@ -488,7 +488,7 @@ def test_load_alert_state_clears_stale_redis_when_db_has_no_row(app, monkeypatch redis_bucket.pop(key, None) monkeypatch.setattr( - "app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client", + "app.services.freight_rpa.common.worker_heartbeat_alert._redis_client", lambda: FakeRedis(), ) diff --git a/backend/tests/services/in_transit_transfer/conftest.py b/backend/tests/services/in_transit_transfer/conftest.py index 6741e069..715e556f 100644 --- a/backend/tests/services/in_transit_transfer/conftest.py +++ b/backend/tests/services/in_transit_transfer/conftest.py @@ -1,8 +1,8 @@ -"""在途调拨测试固定夹具:时钟、收料文件样例、外部替身与数据库隔离。 +"""在途调拨测试固定夹具:时钟、入站文件样例、外部替身与数据库隔离。 用途:为 tests/services/in_transit_transfer 提供与 TDD 文档一致的固定输入 (fixed_clock 默认 2026-08-06 09:00:00+08:00、dbs/crane ready 文件、 - same_day_receipt_file),并组装 FakeCapabilityClient/FakeRPA/FakeWeCom。 + same_day_inbound_file),并组装 FakeCapabilityClient/FakeRPA/FakeWeCom。 依赖:根 tests/conftest 的 app fixture(SQLite 内存库)、fakes 模块。 逻辑:纯单元用例(marker pure_unit 且未请求 app)不创建 Flask/DB; 请求 transfer_db 的用例复用 app fixture 的 create_all/drop_all 隔离。 @@ -35,19 +35,20 @@ def _stub_doc_sequence(monkeypatch): @pytest.fixture(autouse=True) -def _pin_maturity_lag_legacy(request): - """在途套件钉成熟滞后=1(T+1)。 +def _seed_default_transfer_type(request): + """默认启用类型配置种子(autouse,出生翻转后匹配创建必填且配置驱动)。 - 用途:存量夹具生态按 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 的无上下文回退。 + 用途:Task 11 切换后 run_matching/create_matching 必填 transfer_type 且类型 + 合法值=配置表 code;本 fixture 为请求 app 的用例预置一条与旧「类型 1 + 硬编码」语义对齐的启用配置(doc_no 前缀 HOM/HOX/WTP + WTP→HOW 转换 + + from/to 全 mapped),存量用例随语义平移后行为等价。专项用例可按 code + 覆盖/停用/补建其它类型。 """ if "app" in getattr(request, "fixturenames", []): - app = request.getfixturevalue("app") - app.config["IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS"] = 1 + request.getfixturevalue("app") + from tests.services.in_transit_transfer.factories import seed_transfer_type_config + + seed_transfer_type_config() @pytest.fixture @@ -78,9 +79,10 @@ def wecom_fake() -> FakeWeCom: def patch_source_file_status(monkeypatch): """执行文件对账门禁替身工厂:替换 execution_service 的来源文件状态投影。 - 用途:execute_items 门禁②按去重来源调 resolve_source_file_status(真实查询 - 收料文件表);单元测试注入替身避免触碰表数据。缺省全部来源投影为 - ready 且 sha=dbs 夹具 checksum("d"*64,与 dbs_ready_file 行版本戳同源)。 + 用途:execute_items 门禁②按 (来源, record_kind) 调 resolve_source_file_status + (真实查询收料/出站文件表);单元测试注入替身避免触碰表数据。缺省全部 + 来源投影为 ready 且 sha=dbs 夹具 checksum("d"*64,与 dbs_ready_file + 行版本戳同源)。record_kind 入参接受但不区分,存量用例仍按来源给 sha。 Args: mapping: source_code → sha 映射;值为 None 表示该来源无可用文件 @@ -91,7 +93,8 @@ def patch_source_file_status(monkeypatch): def _patch(mapping: dict[str, str | None] | None = None) -> None: table = mapping or {} - def _resolve(*, source_code: str) -> dict: + def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict: + del record_kind # 本替身按来源给 sha;出站分流用例自行覆盖本函数。 if source_code in table: sha = table[source_code] if sha is None: diff --git a/backend/tests/services/in_transit_transfer/factories.py b/backend/tests/services/in_transit_transfer/factories.py index 5727d25d..95399ec0 100644 --- a/backend/tests/services/in_transit_transfer/factories.py +++ b/backend/tests/services/in_transit_transfer/factories.py @@ -1,63 +1,362 @@ """在途调拨领域测试的对象工厂。 -用途:集中构造合法 Invoice / 文件行 / 预检 DTO,避免各测试重复内联样板。 -依赖:标准库(dataclasses / decimal)。 +用途:集中构造调拨类型配置种子与「清空并重新解析」(spec §6)用例种子 + (来源+入站解析规则+归档文件+档行),避免各测试重复内联样板。 +依赖:标准库(datetime)、openpyxl(内存 xlsx 构造)。 逻辑:工厂只生成业务合法的默认值;测试用 override 注入变体。 + 归档文件字节不落真存储:用例经 FakeArchiveStorage 注入并 monkeypatch + file_asset_storage.get_bytes。 """ from __future__ import annotations -from dataclasses import dataclass -from decimal import Decimal -from typing import Any +from datetime import datetime + +# --------------------------------------------------------------------------- +# 调拨类型配置种子(出生翻转后匹配创建必填且配置驱动,Task 11) +# --------------------------------------------------------------------------- + +# 默认种子类型:与旧类型 1 硬编码语义对齐(doc_no 前缀 HOM/HOX/WTP + WTP→HOW +# 批号转换 + from/to 全 mapped),保证存量用例随语义平移后行为等价。 +DEFAULT_TYPE_CODE = "in_transit_to_hub" +DEFAULT_SCOPE_RULES = [{"field": "doc_no", "match": "prefix", "values": ["HOM", "HOX", "WTP"]}] +DEFAULT_WAREHOUSE_CONFIG = { + "from": {"mode": "mapped", "warehouse_code": None, "external_org": None}, + "to": {"mode": "mapped", "warehouse_code": None, "external_org": None}, +} +DEFAULT_TRANSFORM_RULES = [{"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"}] -@dataclass(frozen=True) -class ReceiptRow: - """单行收料文件记录(含 Sheet/行号追溯证据)。""" - - sheet: str = "Receipt" - row_no: int = 1 - invoice_no: str = "HOM-001" - material_no: str = "MAT-001" - material_name: str = "连接器组件" - specification: str = "A 型 / 24PIN" - receipt_date: str = "2026-08-05" - receipt_quantity: str = "1200" - source_code: str = "DBS-AWSBI" - - def to_dict(self) -> dict[str, Any]: - """转 dict,供 parser/aggregator 输入。""" - return { - "sheet": self.sheet, - "row_no": self.row_no, - "invoice_no": self.invoice_no, - "material_no": self.material_no, - "material_name": self.material_name, - "specification": self.specification, - "receipt_date": self.receipt_date, - "receipt_quantity": self.receipt_quantity, - "source_code": self.source_code, - } - - -def make_invoice_item( +def seed_transfer_type_config( + code: str = DEFAULT_TYPE_CODE, *, - invoice_no: str = "HOM-001", - source_code: str = "DBS-AWSBI", - material_no: str = "MAT-001", - receipt_quantity: Decimal | str | int = "1200", - external_quantity: Decimal | str | int | None = "1200", - receipt_date: str = "2026-08-05", -) -> dict[str, Any]: - """构造一条预检明细项(默认严格匹配、可执行)。""" - return { - "invoice_no": invoice_no, - "source_code": source_code, - "material_no": material_no, - "material_name": "连接器组件", - "specification": "A 型 / 24PIN", - "receipt_date": receipt_date, - "receipt_quantity": Decimal(str(receipt_quantity)), - "external_quantity": None if external_quantity is None else Decimal(str(external_quantity)), - } + enabled: bool = True, + scope_rules: list[dict] | None = None, + warehouse_config: dict | None = None, + transform_rules: list[dict] | None = None, +): + """get-or-create 一条调拨类型配置(测试种子;直接 ORM 插入绕过服务校验)。 + + Args: + code: 类型编码。 + enabled: 启停(默认启用)。 + scope_rules / warehouse_config / transform_rules: 缺省与旧类型 1 硬编码 + 语义对齐(HOM/HOX/WTP 前缀 + mapped/mapped + WTP→HOW)。 + Returns: + TransferTypeConfig ORM 行。 + """ + from app import db + from app.models import TransferTypeConfig + + row = db.session.query(TransferTypeConfig).filter_by(code=code).first() + if row is not None: + return row + row = TransferTypeConfig( + code=code, + names_json={"zh-CN": f"类型 {code}"}, + enabled=enabled, + sort_order=0, + scope_rules_json=DEFAULT_SCOPE_RULES if scope_rules is None else scope_rules, + warehouse_config_json=DEFAULT_WAREHOUSE_CONFIG if warehouse_config is None else warehouse_config, + transform_rules_json=DEFAULT_TRANSFORM_RULES if transform_rules is None else transform_rules, + ) + db.session.add(row) + db.session.commit() + return row + + +# --------------------------------------------------------------------------- +# 清空并重新解析(spec §6,Task 7)用例种子 +# --------------------------------------------------------------------------- + +# 入站解析规则缺省 field_mapping(movement 定死领域字段 → 表头别名,CRANE 风格)。 +INBOUND_MOVEMENT_FIELD_MAPPING = { + "doc_no": "单据编号", + "line_no": "项次", + "in_out_flag": "进出库别", + "material_code": "料号", + "material_name": "品名", + "lot_no": "批号", + "quantity": "数量", + "movement_date": "异动日期", +} + +# 与 INBOUND_MOVEMENT_FIELD_MAPPING 对齐的 xlsx 表头行(build_movement_xlsx 缺省表头)。 +INBOUND_MOVEMENT_HEADERS = ["单据编号", "项次", "进出库别", "料号", "品名", "批号", "数量", "异动日期"] + + +def build_movement_xlsx(data_rows: list[list], *, sheet_name: str = "Receipt", + headers: list[str] | None = None) -> bytes: + """构造内存 xlsx 字节(表头 + 数据行),供归档假存储注入。 + + Args: + data_rows: 数据行(列序与 headers 一致;数量 int、日期 str)。 + sheet_name: 工作表标题(溯源 sheet 字段来源)。 + headers: 表头行;缺省 INBOUND_MOVEMENT_HEADERS。 + Returns: + xlsx 原始字节。 + """ + from io import BytesIO + + from openpyxl import Workbook + + wb = Workbook() + ws = wb.active + ws.title = sheet_name + ws.append(list(headers if headers is not None else INBOUND_MOVEMENT_HEADERS)) + for row in data_rows: + ws.append(list(row)) + buf = BytesIO() + wb.save(buf) + return buf.getvalue() + + +class FakeArchiveStorage: + """file_asset_storage 内存假件(storage_key → bytes),按 repo_fakes 风格最小实现。""" + + def __init__(self, objects: dict[str, bytes] | None = None) -> None: + self.objects: dict[str, bytes] = dict(objects or {}) + + def get_bytes(self, storage_key: str) -> bytes: + """读取注入对象;缺失键抛 KeyError(用例内即失败,不静默)。""" + return self.objects[storage_key] + + +def seed_inbound_reparse_source(source_code: str, *, profile_code: str | None = None, + version: int = 1, field_mapping: dict | None = None, + sheet_name: str = "Receipt", header_row_index: int = 1, + status: str = "published"): + """建「启用来源 + 已发布 inbound 解析规则 + 收料配置绑定」全套种子(幂等)。 + + 用途:清空并重新解析(spec §6)服务/端点用例的来源侧种子;来源自身 + 在手解析绑定(在手口径)按约束置最小占位配置行(s18 起归 + FreightRpaOnhandReportConfig),真实重建规则挂 + FreightRpaInboundReportConfig.parsing_profile_id(与运行期口径一致)。 + + Args: + source_code: 来源实例编码。 + profile_code: 入站解析规则 code(缺省 MV_)。 + version: 入站解析规则版本。 + field_mapping: 领域字段→表头别名;缺省 INBOUND_MOVEMENT_FIELD_MAPPING。 + sheet_name / header_row_index: definition_json 结构参数。 + status: 入站规则状态(缺省 published;用例可注入 draft 验证 abort)。 + Returns: + (FreightRpaSource, FreightRpaParsingProfile) 元组。 + """ + from app import db + from app.models import ( + ShippingExcelTemplate, + FreightRpaOnhandReportConfig, + FreightRpaParsingProfile, + FreightRpaSource, + FreightRpaProfile, + FreightRpaInboundReportConfig, + ) + + source = FreightRpaSource.query.filter_by(source_code=source_code).first() + if source is not None: + config = source.inbound_report_config + return source, (config.parsing_profile if config else None) + + resolved_code = profile_code or f"MV_{source_code}" + onhand = FreightRpaParsingProfile( + purpose="onhand", profile_code=f"ONHAND_{source_code}", display_name=source_code, + version=1, status="published", file_format="xlsx", + definition_json={}, structure_definition_json={}, + ) + profile = FreightRpaParsingProfile( + purpose="inbound", profile_code=resolved_code, display_name=resolved_code, + version=version, status=status, file_format="xlsx", + definition_json={ + "sheet_name": sheet_name, "header_row_index": header_row_index, + "field_mapping": dict( + INBOUND_MOVEMENT_FIELD_MAPPING if field_mapping is None else field_mapping), + }, + structure_definition_json={}, + ) + rpa = FreightRpaProfile( + profile_code=f"RPA_{source_code}", display_name=source_code, connector_type="dbs", + login_url="https://test.invalid/dbs", login_config_json={"auth_mode": "password"}, + ) + 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}/template.xlsx", original_filename="template.xlsx", + file_checksum="0" * 64, definition_json={}, definition_checksum="0" * 64, + ) + source = FreightRpaSource( + source_code=source_code, display_name=source_code, connector_type="dbs", + rpa_profile=rpa, excel_template=template, + warehouse_resolution_mode="fixed", fixed_warehouse_id="AWSDU", enabled=True, + ) + db.session.add_all([onhand, profile, rpa, template, source]) + db.session.flush() + # s18 起在手解析方案绑定归 FreightRpaOnhandReportConfig 配置行,站点行不再承载。 + db.session.add(FreightRpaOnhandReportConfig( + source_id=source.id, parsing_profile_id=onhand.id, + report_path_json={}, query_parameters_json=[], + )) + db.session.add(FreightRpaInboundReportConfig( + source_id=source.id, parsing_profile_id=profile.id)) + db.session.commit() + return source, profile + + +def seed_reparse_archive_file(source, *, sha: str, storage_key: str, created_at: datetime, + archive_expires_at: datetime | None = None, + archive_deleted_at: datetime | None = None, + callback_id: str | None = None): + """建一条收料执行单元 + 原样归档文件行(清空重建用例种子)。 + + 字节不落真存储:用例把 build_movement_xlsx 产物注入 FakeArchiveStorage + (键=storage_key)并 monkeypatch file_asset_storage.get_bytes。 + + Args: + source: seed_inbound_reparse_source 返回的来源行。 + sha: 归档文件 sha256(唯一约束 unit_run+sha,用例间取不同值)。 + storage_key: 对象存储键(与假存储注入键一致)。 + created_at: 归档时间(= repository 的 archived_at,排序依据)。 + archive_expires_at: 保留期截止;None=长期有效。 + archive_deleted_at: 清理时间;None=未清理。 + callback_id: 收料执行单元回调键(缺省按 sha 派生保证唯一)。 + Returns: + 已入库的 FreightRpaInboundReportFile。 + """ + from app import db + from app.models import FreightRpaInboundReportFile, FreightRpaInboundUnitRun + + unit = FreightRpaInboundUnitRun( + source_id=source.id, source_code=source.source_code, + connector_type=source.connector_type, + callback_id=callback_id or f"cb-{sha[:12]}", + status="success", config_snapshot_json={}, + ) + db.session.add(unit) + db.session.flush() + report = FreightRpaInboundReportFile( + unit_run_id=unit.id, storage_provider="minio", storage_bucket="test", + storage_key=storage_key, original_filename=f"{callback_id or 'cb'}.xlsx", + file_size=16, sha256=sha, created_at=created_at, + archive_expires_at=archive_expires_at, archive_deleted_at=archive_deleted_at, + ) + db.session.add(report) + db.session.commit() + return report + + +def seed_reparse_ledger_row(source_code: str, doc_no: str, *, line_no: str = "1", + in_out_flag: str = "I", lot_no: str = "LOT-1", + source_file_id: int | None = None, + sha: str = "9" * 64, quantity: str = "1", + material_code: str = "MAT-OLD", material_name: str = "旧映射名称", + movement_date: str = "2026-08-05", + transfer_executed: bool = False, + executed_doc_no: str | None = None, + updated_at: datetime | None = None, + record_kind: str = "inbound"): + """插一条旧映射库存异动档行(清空重建用例种子;业务值=旧映射形态)。 + + Args: + source_code / doc_no: 来源与单号(自然键主干)。 + line_no / in_out_flag / lot_no: 自然键可变成分(与解析行对齐便于断言覆写)。 + source_file_id: 溯源归档文件 id;None=证据缺失行形态。 + sha: 档行 file_sha256(缺省 9*64 表示旧文件指纹)。 + quantity / material_code / material_name / movement_date: 旧业务值。 + transfer_executed / executed_doc_no: 封存形态注入。 + updated_at: 显式更新时间(封存不动行断言用)。 + record_kind: inbound(默认)或 outbound。 + Returns: + 已入库的 TransferMovementLedger。 + """ + from app import db + from app.models import TransferMovementLedger + + row = TransferMovementLedger( + source_code=source_code, record_kind=record_kind, + doc_no=doc_no, line_no=line_no, line_seq="", in_out_flag=in_out_flag, + carton_id="", lot_no=lot_no, + material_code=material_code, material_name=material_name, + quantity=quantity, movement_date=movement_date, + source_file_id=source_file_id, file_version=None, file_sha256=sha, + transfer_executed=transfer_executed, executed_doc_no=executed_doc_no, + updated_at=updated_at or datetime(2026, 10, 1, 8, 0, 0), + ) + db.session.add(row) + db.session.commit() + return row + + +def seed_outbound_reparse_source(source_code: str, *, profile_code: str | None = None, + version: int = 1, status: str = "published"): + """建「启用来源 + 已发布 outbound 解析规则 + 出站配置绑定」种子(幂等)。 + + 用途:清空并重新解析出站流用例。若来源已存在则只补出站配置/规则。 + + Returns: + (FreightRpaSource, FreightRpaParsingProfile) 元组。 + """ + from app import db + from app.models import ( + FreightRpaOutboundReportConfig, + FreightRpaParsingProfile, + FreightRpaSource, + ) + + source, _inbound = seed_inbound_reparse_source(source_code) + existing = source.outbound_report_config + if existing is not None and existing.parsing_profile is not None: + return source, existing.parsing_profile + + resolved_code = profile_code or f"OUT_{source_code}" + profile = FreightRpaParsingProfile( + purpose="outbound", profile_code=resolved_code, display_name=resolved_code, + version=version, status=status, file_format="xlsx", + definition_json={ + "sheet_name": "Receipt", "header_row_index": 1, + "field_mapping": dict(INBOUND_MOVEMENT_FIELD_MAPPING), + }, + structure_definition_json={}, + ) + db.session.add(profile) + db.session.flush() + if existing is None: + db.session.add(FreightRpaOutboundReportConfig( + source_id=source.id, parsing_profile_id=profile.id, + report_path_json={"report_name": "Outbound"}, + query_parameters_json=[], + )) + else: + existing.parsing_profile_id = profile.id + db.session.commit() + return source, profile + + +def seed_reparse_outbound_archive_file(source, *, sha: str, storage_key: str, + created_at: datetime, + archive_expires_at: datetime | None = None, + callback_id: str | None = None): + """建一条出站执行单元 + 归档文件行(清空重建出站用例种子)。 + + Returns: + 已入库的 FreightRpaOutboundReportFile。 + """ + from app import db + from app.models import FreightRpaOutboundReportFile, FreightRpaOutboundUnitRun + + unit = FreightRpaOutboundUnitRun( + schedule_run_id=None, source_id=source.id, source_code=source.source_code, + connector_type=source.connector_type, warehouse_id="AWSDU", + callback_id=callback_id or f"out-cb-{sha[:12]}", + status="success", config_snapshot_json={}, + ) + db.session.add(unit) + db.session.flush() + report = FreightRpaOutboundReportFile( + unit_run_id=unit.id, storage_provider="minio", storage_bucket="test", + storage_key=storage_key, original_filename=f"{callback_id or 'out'}.xlsx", + file_size=16, sha256=sha, created_at=created_at, + archive_expires_at=archive_expires_at, + ) + db.session.add(report) + db.session.commit() + return report diff --git a/backend/tests/services/in_transit_transfer/fakes.py b/backend/tests/services/in_transit_transfer/fakes.py index 79ef6090..fc594649 100644 --- a/backend/tests/services/in_transit_transfer/fakes.py +++ b/backend/tests/services/in_transit_transfer/fakes.py @@ -285,7 +285,7 @@ class FakeRPA: }) if source_code in self.fail_on: return {"ok": False, "error_code": "RPA_TRIGGER_FAILED"} - return {"ok": True, "callback_id": f"receipt:{source_code}:{business_date}"} + return {"ok": True, "callback_id": f"inbound:{source_code}:{business_date}"} class FakeWeCom: diff --git a/backend/tests/services/in_transit_transfer/repo_fakes.py b/backend/tests/services/in_transit_transfer/repo_fakes.py index e0b80532..66a7e82a 100644 --- a/backend/tests/services/in_transit_transfer/repo_fakes.py +++ b/backend/tests/services/in_transit_transfer/repo_fakes.py @@ -1,7 +1,7 @@ """在途调拨测试的仓库/路由/依赖替身。 用途:为 file_preparation / matching_service / API / Job 测试提供可注入的 - ReceiptFileRepository、RouteResolver 与组装好的 TransferDeps; + InboundFileRepository、RouteResolver 与组装好的 TransferDeps; 并提供 seed_rows_from_file 迁移桥(2026-09-25 起匹配不解析文件, 行须经 evidence_sync 落地)。 依赖:app.services.in_transit_transfer(仅类型)、fakes。 @@ -13,15 +13,15 @@ from __future__ import annotations from datetime import datetime -from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile +from app.services.in_transit_transfer.file_preparation import ReadyInboundFile from app.services.in_transit_transfer.matching_service import RouteMapping, TransferDeps from tests.services.in_transit_transfer.fakes import FakeCapabilityClient, FakeRPA -class FakeReceiptFileRepository: +class FakeInboundFileRepository: """按 (source_code, business_date) 返回可注入 ready 文件。""" - def __init__(self, files: dict[tuple[str, str], ReadyReceiptFile] | None = None) -> None: + def __init__(self, files: dict[tuple[str, str], ReadyInboundFile] | None = None) -> None: self.files = files or {} self.lookups: list[tuple[str, str]] = [] # 一次性覆盖:下一次 latest_ready_file 对该来源返回此文件(用后即弃, @@ -34,7 +34,7 @@ class FakeReceiptFileRepository: Args: source_code: 来源实例编码(覆盖该来源的下一次查询)。 - rows: 文件原始行集(透传为 ReadyReceiptFile.rows)。 + rows: 文件原始行集(透传为 ReadyInboundFile.rows)。 checksum: 文件 sha256 版本戳。 file_version: 文件版本号(缺省 "override")。 """ @@ -42,12 +42,12 @@ class FakeReceiptFileRepository: "rows": tuple(rows), "checksum": checksum, "file_version": file_version, } - def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None: + def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyInboundFile | None: """记录查询并返回匹配文件;有一次性覆盖时优先返回并消费之。""" self.lookups.append((source_code, business_date)) override = self._next_files.pop(source_code, None) if override is not None: - return ReadyReceiptFile( + return ReadyInboundFile( source_code=source_code, business_date=business_date, file_no=f"REC-OVERRIDE-{source_code}", @@ -64,7 +64,7 @@ def seed_rows_from_file(source_code: str, deps: TransferDeps, business_date: str 【2026-09-25】匹配不再解析文件(行由 evidence_sync 落地);凡旧用例 「文件夹具直接进 run_matching/create_matching」的,须先经本助手把文件行 落成待查行(status='matching' + result_code='pending_stock_check'), - 再进入匹配管道(成熟过滤→查库存→落位)。须在 app/DB 上下文内调用。 + 再进入匹配管道(未来日期阻断→查库存→落位)。须在 app/DB 上下文内调用。 Args: source_code: 来源实例编码(须与 deps.file_repository 注入的文件一致)。 @@ -82,11 +82,11 @@ def seed_rows_from_file(source_code: str, deps: TransferDeps, business_date: str ) -def make_ready_repo(*files: dict) -> FakeReceiptFileRepository: - """由 fixture 文件 dict 构建仓库;rows 透传为 ReadyReceiptFile.rows。""" - repository = FakeReceiptFileRepository() +def make_ready_repo(*files: dict) -> FakeInboundFileRepository: + """由 fixture 文件 dict 构建仓库;rows 透传为 ReadyInboundFile.rows。""" + repository = FakeInboundFileRepository() for item in files: - repository.files[(item["source_code"], item["business_date"])] = ReadyReceiptFile( + repository.files[(item["source_code"], item["business_date"])] = ReadyInboundFile( source_code=item["source_code"], business_date=item["business_date"], file_no=item["file_no"], diff --git a/backend/tests/services/in_transit_transfer/test_auto_transfer.py b/backend/tests/services/in_transit_transfer/test_auto_transfer.py index a406a047..fff66cb0 100644 --- a/backend/tests/services/in_transit_transfer/test_auto_transfer.py +++ b/backend/tests/services/in_transit_transfer/test_auto_transfer.py @@ -20,7 +20,6 @@ def _summary(executable_count: int) -> 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", @@ -66,8 +65,8 @@ def test_executes_and_propagates_result_when_executable(monkeypatch): assert outcome.errors == [] -def test_passes_receipt_date_range_to_matching(monkeypatch): - """可选收料日期范围透传匹配层;缺省时为 None(=全部成熟积压)。""" +def test_passes_movement_date_range_to_matching(monkeypatch): + """可选异动日期范围透传匹配层;缺省时为 None(=全部积压)。""" captured = {} def _fake_create(**kwargs): @@ -78,15 +77,15 @@ def test_passes_receipt_date_range_to_matching(monkeypatch): at.run_auto_transfer( business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False, - receipt_date_from="2026-09-01", receipt_date_to="2026-09-05", + movement_date_from="2026-09-01", movement_date_to="2026-09-05", ) - # 断言:显式范围原样透传(成熟上限/起止合法性由匹配层 ValidationError 卡控)。 - assert captured["receipt_date_from"] == "2026-09-01" - assert captured["receipt_date_to"] == "2026-09-05" + # 断言:显式范围原样透传(起止合法性由匹配层 ValidationError 卡控)。 + assert captured["movement_date_from"] == "2026-09-01" + assert captured["movement_date_to"] == "2026-09-05" at.run_auto_transfer( business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False, ) # 断言:缺省(留空)不缩小匹配面,范围参数为 None。 - assert captured["receipt_date_from"] is None - assert captured["receipt_date_to"] is None + assert captured["movement_date_from"] is None + assert captured["movement_date_to"] is None diff --git a/backend/tests/services/in_transit_transfer/test_backlog_reparse_service.py b/backend/tests/services/in_transit_transfer/test_backlog_reparse_service.py new file mode 100644 index 00000000..6cc008e5 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_backlog_reparse_service.py @@ -0,0 +1,443 @@ +"""backlog_reparse_service:清空并重解析的守卫矩阵(spec §6,Task 7)。 + +用途:锁死「清空并重新解析」的安全不变量与五条守卫——①正常路径旧映射行被清、 + 按当前模板重落、计数/溯源正确、审计事件落库;②任一归档解析失败整体中止 + 一行不删(先解析后删除);③封存行(transfer_executed=true)与被有效 items + 占用行幸存;④证据缺失(归档已清理/过保留期/无溯源)的行保留并计入 + kept_unrebuildable;⑤预检形状(files/profile/clearable_rows/kept_rows)。 +依赖:factories(来源/归档/档行种子 + FakeArchiveStorage + build_movement_xlsx)、 + ledger_sync.movement_file_version、app fixture。 +逻辑:归档文件字节经假存储注入(monkeypatch file_asset_storage.get_bytes); + 归档文件 created_at 均早于 NOW 数日——若 repository 仍带运行期「当日抓取」 + 门禁则清单为空,本套件即红(锁定维护路径无当日门禁)。 +""" + +from __future__ import annotations + +from datetime import datetime + +import pytest + +from app import db +from app.core.errors import AppError +from app.models import ( + TransferAuditEvent, + TransferInvoiceItem, + TransferMatching, + TransferMovementLedger, +) +from app.services.in_transit_transfer import evidence_sync +from app.services.in_transit_transfer.ledger_sync import movement_file_version +from app.services.in_transit_transfer.backlog_reparse_service import ( + preview_pending_match_reparse, + reparse_pending_match, +) +from tests.services.in_transit_transfer import factories + +pytestmark = [pytest.mark.usefixtures("app")] + +SOURCE = "CRANE_NA" +NOW = datetime(2026, 10, 15, 10, 0, 0) +OLD_SHA = "9" * 64 +SHA_A = "a" * 64 +SHA_B = "b" * 64 +SHA_GONE = "e" * 64 # 已过保留期归档文件的 sha(证据缺失形态) +REPARSE_EVENT = "TRANSFER_PENDING_MATCH_REPARSED" + + +@pytest.fixture +def archive_storage(monkeypatch): + """归档假存储:注入 FakeArchiveStorage 并替换单例 get_bytes(所有引用方同源)。""" + fake = factories.FakeArchiveStorage() + monkeypatch.setattr( + "app.services.file_assets.storage.file_asset_storage.get_bytes", fake.get_bytes) + return fake + + +def _seed_world(*, profile_status: str = "published") -> tuple: + """标准场景种子:来源+已发布入站规则 + 两份可用归档(A 先 B 后)。 + + Returns: + (source, profile, file_a, file_b) 元组。 + """ + source, profile = factories.seed_inbound_reparse_source(SOURCE, status=profile_status) + file_a = factories.seed_reparse_archive_file( + source, sha=SHA_A, storage_key=f"archive/{SOURCE}/a.xlsx", + created_at=datetime(2026, 10, 10, 8, 0, 0)) + file_b = factories.seed_reparse_archive_file( + source, sha=SHA_B, storage_key=f"archive/{SOURCE}/b.xlsx", + created_at=datetime(2026, 10, 11, 8, 0, 0)) + return source, profile, file_a, file_b + + +def _count_ledger(source_code: str = SOURCE) -> int: + """该来源 inbound 档行总数(中止/幸存断言主对象)。""" + return TransferMovementLedger.query.filter_by( + source_code=source_code, record_kind="inbound").count() + + +def test_reparse_clears_and_relands(app, archive_storage): + # [断言意图] 正常路径:旧映射行全清(3)、按当前模板重落(3)、date_skipped + # 计入结果、审计事件 TRANSFER_PENDING_MATCH_REPARSED 落库且 payload 完整 + # (operator/source_code/files/profile/cleared/reinserted/date_skipped/kept)。 + source, profile, file_a, file_b = _seed_world() + archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([ + ["ASN-A1", "1", "I", "MAT-1", "连接器", "LOT-1", 500, "2026-08-05"], + ["ASN-A2", "1", "I", "MAT-2", "传感器", "LOT-2", 300, "2026-08-05"], + ]) + archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx([ + ["ASN-B1", "1", "I", "MAT-3", "模块", "LOT-3", 700, "2026-08-06"], + ]) + factories.seed_reparse_ledger_row(SOURCE, "ASN-A1", source_file_id=file_a.id, + sha=OLD_SHA, quantity="1") + factories.seed_reparse_ledger_row(SOURCE, "ASN-A2", source_file_id=file_a.id, + sha=OLD_SHA, quantity="2") + factories.seed_reparse_ledger_row(SOURCE, "ASN-B1", source_file_id=file_b.id, + sha=OLD_SHA, quantity="3") + assert _count_ledger() == 3 + + outcome = reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW) + + assert (outcome.cleared, outcome.reinserted) == (3, 3) # [断言意图] 清 3 落 3 + assert outcome.date_skipped == 0 and outcome.kept_unrebuildable == 0 + assert _count_ledger() == 3 # [断言意图] 无重复无丢失 + db.session.expire_all() + a1 = TransferMovementLedger.query.filter_by( + source_code=SOURCE, doc_no="ASN-A1").one() + # [断言意图] 新映射值生效:业务值来自当前归档重解析,溯源换新文件三元组 + # (真实 source_file_id / sha256: 版本戳),不再是旧映射值。 + assert a1.quantity == "500" and a1.material_code == "MAT-1" + assert a1.file_sha256 == SHA_A and a1.source_file_id == file_a.id + # [断言意图] 重建写入的版本戳走 movement_file_version,与运行期落档同一串。 + assert a1.file_version == movement_file_version(SHA_A) + assert a1.movement_date == "2026-08-05" + # [断言意图] 文件顺序:按归档时间升序逐文件重落(files 概要 A 在前)。 + assert [f["sha256"] for f in outcome.files] == [SHA_A, SHA_B] + assert [f["inserted"] for f in outcome.files] == [2, 1] + + event = TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).one() + assert event.aggregate_type == "transfer_source" + assert event.aggregate_id == SOURCE + payload = event.after_json + assert payload["operator"] == "admin" and payload["source_code"] == SOURCE + assert payload["record_kind"] == "inbound" + assert payload["cleared"] == 3 and payload["reinserted"] == 3 + assert payload["date_skipped"] == 0 and payload["kept"] == 0 + assert payload["profile_code"] == profile.profile_code + assert payload["profile_version"] == 1 + assert [f["sha256"] for f in payload["files"]] == [SHA_A, SHA_B] + + +def test_abort_on_parse_failure_deletes_nothing(app, archive_storage): + # [断言意图] 安全不变量:任一归档解析失败(坏表头→必填缺失)→ 整体中止 + # TRANSFER.REPARSE_PARSE_FAILED,一行未删、无审计事件(先解析后删除)。 + _source, _profile, file_a, file_b = _seed_world() + archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([ + ["ASN-A1", "1", "I", "MAT-1", "连接器", "LOT-1", 500, "2026-08-05"], + ]) + # 坏文件:料号可映射但缺单号列 → 行级 missing_invoice_no → 解析必失败。 + # 【不能用全垃圾表头】料号空行按 2026-10-21 规则静默跳过(不做管控不进 + # 异动表),表头全不匹配的文件会以 0 行成功收场,不再触发中止。 + archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx( + [["MAT-BAD"]], headers=["料号"]) + factories.seed_reparse_ledger_row(SOURCE, "ASN-A1", source_file_id=file_a.id, sha=OLD_SHA) + factories.seed_reparse_ledger_row(SOURCE, "ASN-A2", source_file_id=file_a.id, sha=OLD_SHA) + factories.seed_reparse_ledger_row(SOURCE, "ASN-B1", source_file_id=file_b.id, sha=OLD_SHA) + + with pytest.raises(AppError) as exc_info: + reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW) + + assert exc_info.value.code == "TRANSFER.REPARSE_PARSE_FAILED" + # [断言意图] 中止详情可精确定位失败文件:details 逐项断言(来源/文件身份/ + # 失败原因),不得用 or 短路式恒真断言掩盖缺键。 + details = exc_info.value.details + assert details["source_code"] == SOURCE + assert details["sha256"] == SHA_B # 失败文件=坏表头那份 + assert details["storage_key"] == f"archive/{SOURCE}/b.xlsx" + assert details["file_id"] == file_b.id + assert "missing_invoice_no" in details["reason"] # 行级失败原因透传 + assert _count_ledger() == 3 # [断言意图] 一行未删 + assert TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).count() == 0 + + +def test_sealed_and_occupied_rows_survive(app, archive_storage): + # [断言意图] 删除范围三重过滤:封存行(transfer_executed=true)不动不复活; + # 被有效 items 占用行不被删除(item 引用保持有效),重落按常规幂等语义 + # 走原行更新(新映射值生效、无第二行)。 + _source, _profile, file_a, _file_b = _seed_world() + archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([ + ["ASN-A1", "1", "I", "MAT-1", "连接器", "LOT-1", 500, "2026-08-05"], + ["ASN-A2", "1", "I", "MAT-2", "传感器", "LOT-2", 600, "2026-08-05"], + ]) + # 文件 B 可用但无数据行(仅表头):不参与断言,只为预解析通道完整。 + archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx([]) + sealed_at = datetime(2026, 10, 2, 8, 0, 0) + sealed = factories.seed_reparse_ledger_row( + SOURCE, "ASN-A1", source_file_id=file_a.id, sha=OLD_SHA, quantity="1", + transfer_executed=True, executed_doc_no="TRF-9", updated_at=sealed_at) + occupied = factories.seed_reparse_ledger_row( + SOURCE, "ASN-A2", line_no="1", in_out_flag="I", lot_no="LOT-2", + source_file_id=file_a.id, sha=OLD_SHA, quantity="2") + db.session.add(TransferInvoiceItem( + matching_id=None, ledger_record_id=occupied.id, source_code=SOURCE, + invoice_no="ASN-A2", material_no="MAT-OLD", from_warehouse="W1", + to_warehouse="W2", movement_quantity="2", status="matching", + result_code="pending_stock_check", + )) + db.session.commit() + + outcome = reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW) + + assert outcome.cleared == 0 # [断言意图] 无可删行 + assert outcome.reinserted == 0 # [断言意图] 封存跳过+占用原行更新 + assert _count_ledger() == 2 # [断言意图] 无新增行 + db.session.expire_all() + sealed_after = TransferMovementLedger.query.filter_by(id=sealed.id).one() + assert sealed_after.transfer_executed is True + assert sealed_after.executed_doc_no == "TRF-9" + assert sealed_after.quantity == "1" # [断言意图] 封存行零写入 + occupied_after = TransferMovementLedger.query.filter_by(id=occupied.id).one() + assert occupied_after.quantity == "600" # [断言意图] 占用行走更新分支换新映射 + assert occupied_after.file_sha256 == SHA_A + item = TransferInvoiceItem.query.filter_by(ledger_record_id=occupied.id).one() + assert item.result_code == "pending_stock_check" # [断言意图] item 引用仍然有效 + + +def test_unrebuildable_rows_kept_and_reported(app, archive_storage): + # [断言意图] 证据缺失行保留并计入 kept_unrebuildable:归档已过保留期 + # (repository 可用清单排除)或无溯源(source_file_id=NULL)的行原样留存。 + source, _profile, file_a, _file_b = _seed_world() + expired = factories.seed_reparse_archive_file( + source, sha=SHA_GONE, storage_key=f"archive/{SOURCE}/gone.xlsx", + created_at=datetime(2026, 10, 9, 8, 0, 0), + archive_expires_at=datetime(2026, 10, 14, 0, 0, 0)) # NOW 前已过保留期 + archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([ + ["ASN-A1", "1", "I", "MAT-1", "连接器", "LOT-1", 500, "2026-08-05"], + ]) + # 文件 B 可用但无数据行(仅表头):不参与断言,只为预解析通道完整。 + archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx([]) + factories.seed_reparse_ledger_row(SOURCE, "ASN-A1", source_file_id=file_a.id, sha=OLD_SHA) + factories.seed_reparse_ledger_row(SOURCE, "ASN-X", source_file_id=expired.id, + sha=SHA_GONE, quantity="9") + factories.seed_reparse_ledger_row(SOURCE, "ASN-Y", source_file_id=None, + sha=None, quantity="8") + + outcome = reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW) + + assert (outcome.cleared, outcome.reinserted) == (1, 1) # [断言意图] 仅可重建行被清/重落 + assert outcome.kept_unrebuildable == 2 # [断言意图] 证据缺失=2 行 + db.session.expire_all() + kept_x = TransferMovementLedger.query.filter_by(source_code=SOURCE, doc_no="ASN-X").one() + kept_y = TransferMovementLedger.query.filter_by(source_code=SOURCE, doc_no="ASN-Y").one() + assert kept_x.quantity == "9" and kept_x.file_sha256 == SHA_GONE # [断言意图] 原样留存 + assert kept_y.quantity == "8" and kept_y.file_sha256 is None + event = TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).one() + assert event.after_json["kept"] == 2 + + +def test_preview_shape(app, archive_storage): + # [断言意图] 预检形状:files(archived_at/sha256/预估行数,按归档时间升序)、 + # profile{code,version}、clearable_rows(可重建可清除)与 kept_rows(证据缺失 + # 保留)与执行口径 1:1;只读(不删行、不落审计、不重落)。 + source, profile, file_a, file_b = _seed_world() + factories.seed_reparse_ledger_row(SOURCE, "ASN-A1", source_file_id=file_a.id, sha=OLD_SHA) + factories.seed_reparse_ledger_row(SOURCE, "ASN-A2", source_file_id=file_a.id, + sha=OLD_SHA, transfer_executed=True, + executed_doc_no="TRF-8") + factories.seed_reparse_ledger_row(SOURCE, "ASN-Y", source_file_id=None, + sha=None, quantity="8") + + preview = preview_pending_match_reparse(source_code=SOURCE, now=NOW) + + assert set(preview.keys()) == { + "record_kind", "files", "profile", "clearable_rows", "kept_rows", + } + assert preview["record_kind"] == "inbound" + assert preview["profile"] == {"code": profile.profile_code, "version": 1} + assert [f["sha256"] for f in preview["files"]] == [SHA_A, SHA_B] # 归档时间升序 + assert preview["files"][0]["archived_at"] == datetime(2026, 10, 10, 8, 0, 0).isoformat() + # [断言意图] 预估行数口径=现有档行按 source_file_id 计数(含封存;docstring 声明), + # 不在预检里解析归档字节。 + assert preview["files"][0]["rows"] == 2 and preview["files"][1]["rows"] == 0 + assert preview["clearable_rows"] == 1 # [断言意图] 仅未封存未占用有据行 + assert preview["kept_rows"] == 1 # [断言意图] 证据缺失行计入保留 + assert _count_ledger() == 3 # [断言意图] 预检只读零副作用 + assert TransferAuditEvent.query.count() == 0 + + +def test_reparse_aborts_without_published_profile(app, archive_storage): + # [断言意图] 无已发布入站规则=无重建通道:即使存在档行也整体中止 + # (REPARSE_PARSE_FAILED),一行不删——防「删了装不回去」。 + factories.seed_inbound_reparse_source(SOURCE, status="draft") + factories.seed_reparse_ledger_row(SOURCE, "ASN-A1", source_file_id=None, sha=None) + + with pytest.raises(AppError) as exc_info: + reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW) + + assert exc_info.value.code == "TRANSFER.REPARSE_PARSE_FAILED" + assert _count_ledger() == 1 # [断言意图] 一行未删 + + +def test_cancelled_and_isolated_items_unlinked_before_delete(app, archive_storage): + # [断言意图] R9/方案 D(FK 悬挂修复):已取消匹配 items 与 blocked_file_removed + # 隔离 items 仍持有待删档行的 ledger_record_id(普通 FK 无 ondelete)——删除前 + # 必须同事务置空,否则 PG flush 撞 IntegrityError 且此后每次重建复发。 + # 范围严格限于待删集合:有效占用行不在删除集,其 items 引用保持不变。 + _source, _profile, file_a, file_b = _seed_world() + archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([ + ["ASN-A1", "1", "I", "MAT-1", "连接器", "LOT-1", 500, "2026-08-05"], + ["ASN-A2", "1", "I", "MAT-2", "传感器", "LOT-2", 600, "2026-08-05"], + ]) + archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx([ + ["ASN-B1", "1", "I", "MAT-3", "模块", "LOT-3", 700, "2026-08-06"], + ]) + row_a1 = factories.seed_reparse_ledger_row( + SOURCE, "ASN-A1", source_file_id=file_a.id, sha=OLD_SHA) + row_a2 = factories.seed_reparse_ledger_row( + SOURCE, "ASN-A2", lot_no="LOT-2", source_file_id=file_a.id, sha=OLD_SHA) + row_b1 = factories.seed_reparse_ledger_row( + SOURCE, "ASN-B1", lot_no="LOT-3", source_file_id=file_b.id, sha=OLD_SHA) + # ① 已取消匹配的 item → 引用待删行 row_a1。 + matching = TransferMatching( + matching_no="MTG-R9-1", business_date="2026-08-06", status="cancelled", + scope_json={}, file_snapshot_json={}, counts_json={}, matching_hash="sha256:r9", + ) + db.session.add(matching) + db.session.flush() + cancelled_item = TransferInvoiceItem( + matching_id=matching.id, ledger_record_id=row_a1.id, source_code=SOURCE, + invoice_no="ASN-A1", material_no="MAT-OLD", from_warehouse="W1", + to_warehouse="W2", movement_quantity="1", status="cancelled", + ) + # ② 失效隔离 item(blocked_file_removed 不构成占用)→ 引用待删行 row_a2。 + isolated_item = TransferInvoiceItem( + matching_id=None, ledger_record_id=row_a2.id, source_code=SOURCE, + invoice_no="ASN-A2", material_no="MAT-OLD", from_warehouse="W1", + to_warehouse="W2", movement_quantity="2", status="cancelled", + result_code="blocked_file_removed", + ) + # ③ 对照:有效占用 item(普通 pending 引用即占用)→ row_b1 不在删除集。 + occupied_item = TransferInvoiceItem( + matching_id=None, ledger_record_id=row_b1.id, source_code=SOURCE, + invoice_no="ASN-B1", material_no="MAT-OLD", from_warehouse="W1", + to_warehouse="W2", movement_quantity="3", status="matching", + result_code="pending_stock_check", + ) + db.session.add_all([cancelled_item, isolated_item, occupied_item]) + db.session.commit() + + outcome = reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW) + + # [断言意图] 删除成功(无 FK IntegrityError)且仅删未占用两行;解绑计数=2。 + assert (outcome.cleared, outcome.reinserted) == (2, 2) + assert outcome.unlinked_items == 2 + db.session.expire_all() + # [断言意图] 待删行的两枚废弃 items 引用被置空(溯源装饰让位于可重建性)。 + assert TransferInvoiceItem.query.filter_by(id=cancelled_item.id).one().ledger_record_id is None + assert TransferInvoiceItem.query.filter_by(id=isolated_item.id).one().ledger_record_id is None + # [断言意图] 占用行不在删除集:行原样幸存(原行更新换新映射),其 item 引用 + # 仍指向同一档行 id——有效匹配的圈定关系不受重建波及。 + row_b1_after = TransferMovementLedger.query.filter_by(id=row_b1.id).one() + assert row_b1_after.quantity == "700" and row_b1_after.file_sha256 == SHA_B + assert TransferInvoiceItem.query.filter_by(id=occupied_item.id).one().ledger_record_id == row_b1.id + event = TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).one() + assert event.after_json["unlinked_items"] == 2 + + +def test_reparse_writes_collapse_audit_for_multi_material_same_key(app, archive_storage): + # [断言意图] 终审遗留(坍缩审计接重建路径):重建与运行期同一坍缩守卫——同自然键 + # 六成分批内双料号(行级项次全空)重落时第二料号行仍被幂等吞掉(首见为准, + # 行为与运行期一致),但必须落 ledger_natural_key_collapse 审计事件——改模板 + # 后的清空重建恰是坍缩易发时刻,静默吞行必须显式可观测;重建概要审计携带 + # collapses 计数。 + _source, _profile, file_a, _file_b = _seed_world() + archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([ + ["ASN-C1", "1", "I", "MAT-X", "物料甲", "LOT-9", 500, "2026-08-05"], + ["ASN-C1", "1", "I", "MAT-Y", "物料乙", "LOT-9", 300, "2026-08-05"], + ]) + # 文件 B 可用但无数据行(仅表头):不参与断言,只为预解析通道完整。 + archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx([]) + factories.seed_reparse_ledger_row(SOURCE, "ASN-C1", lot_no="LOT-9", + source_file_id=file_a.id, sha=OLD_SHA) + + outcome = reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW) + + assert (outcome.cleared, outcome.reinserted) == (1, 1) # [断言意图] 旧行清 1、重落仅首见 1 行 + assert outcome.collapses == 1 # [断言意图] 坍缩键计数进结果 + db.session.expire_all() + rows = TransferMovementLedger.query.filter_by(source_code=SOURCE, doc_no="ASN-C1").all() + assert len(rows) == 1 and rows[0].material_code == "MAT-X" # [断言意图] 首见为准吞行不丢账 + # [断言意图] 坍缩审计事件落库且与运行期同构造:定位单号、failure 级、料号可追溯。 + event = TransferAuditEvent.query.filter_by( + event_type=evidence_sync.LEDGER_NATURAL_KEY_COLLAPSE_EVENT).one() + assert "ASN-C1" in event.aggregate_id + assert event.result == "failure" + assert event.after_json["material_codes"] == ["MAT-X", "MAT-Y"] + assert event.after_json["dropped_material_codes"] == ["MAT-Y"] + assert event.after_json["resolution"] == "first_seen_wins" + # [断言意图] 重建概要事件携带坍缩计数(运维一眼判断本次重建是否有数据质量降级)。 + reparse_event = TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).one() + assert reparse_event.after_json["collapses"] == 1 + + +def test_outbound_reparse_clears_and_relands_without_touching_inbound(app, archive_storage): + """出站流清空重建:只动 record_kind=outbound,入站档行幸存。""" + source, profile = factories.seed_outbound_reparse_source(SOURCE) + out_file = factories.seed_reparse_outbound_archive_file( + source, sha=SHA_A, storage_key=f"archive/{SOURCE}/out-a.xlsx", + created_at=datetime(2026, 10, 10, 8, 0, 0), + ) + archive_storage.objects[f"archive/{SOURCE}/out-a.xlsx"] = factories.build_movement_xlsx([ + ["HOX-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-08-05"], + ]) + # 入站旧行 + 出站旧行并存:出站重建不得误删入站。 + factories.seed_reparse_ledger_row( + SOURCE, "ASN-IN1", source_file_id=None, sha=OLD_SHA, record_kind="inbound", + ) + factories.seed_reparse_ledger_row( + SOURCE, "HOX-O1", source_file_id=out_file.id, sha=OLD_SHA, + quantity="1", record_kind="outbound", in_out_flag="O", + ) + assert TransferMovementLedger.query.filter_by( + source_code=SOURCE, record_kind="inbound").count() == 1 + assert TransferMovementLedger.query.filter_by( + source_code=SOURCE, record_kind="outbound").count() == 1 + + outcome = reparse_pending_match( + source_code=SOURCE, operator="admin", now=NOW, record_kind="outbound", + ) + + assert outcome.record_kind == "outbound" + assert (outcome.cleared, outcome.reinserted) == (1, 1) + db.session.expire_all() + # [断言意图] 入站行未动;出站行按新映射重落。 + assert TransferMovementLedger.query.filter_by( + source_code=SOURCE, record_kind="inbound", doc_no="ASN-IN1").count() == 1 + out_row = TransferMovementLedger.query.filter_by( + source_code=SOURCE, record_kind="outbound", doc_no="HOX-O1").one() + assert out_row.quantity == "120" and out_row.material_code == "MAT-O1" + assert out_row.source_file_id == out_file.id and out_row.file_sha256 == SHA_A + # [断言意图] 出站重建的版本戳同样走共享函数。 + assert out_row.file_version == movement_file_version(SHA_A) + event = TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).one() + assert event.after_json["record_kind"] == "outbound" + assert event.after_json["profile_code"] == profile.profile_code + + +def test_outbound_preview_uses_outbound_archives(app, archive_storage): + """出站预检只统计 outbound 归档与档行。""" + source, profile = factories.seed_outbound_reparse_source(SOURCE) + out_file = factories.seed_reparse_outbound_archive_file( + source, sha=SHA_A, storage_key=f"archive/{SOURCE}/out-preview.xlsx", + created_at=datetime(2026, 10, 10, 8, 0, 0), + ) + factories.seed_reparse_ledger_row( + SOURCE, "HOX-P1", source_file_id=out_file.id, sha=SHA_A, record_kind="outbound", + ) + preview = preview_pending_match_reparse( + source_code=SOURCE, now=NOW, record_kind="outbound", + ) + assert preview["record_kind"] == "outbound" + assert preview["profile"] == {"code": profile.profile_code, "version": 1} + assert preview["clearable_rows"] == 1 + assert len(preview["files"]) == 1 and preview["files"][0]["sha256"] == SHA_A 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 5ed8260a..adc240cc 100644 --- a/backend/tests/services/in_transit_transfer/test_backlog_service.py +++ b/backend/tests/services/in_transit_transfer/test_backlog_service.py @@ -28,7 +28,7 @@ def _blocked_matching(dbs_ready_file): erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # 1200 ≠ 1000 → blocked erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # executable seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub") return summary @@ -44,7 +44,7 @@ def test_aging_level_thresholds(): def test_list_backlog_includes_blocked_only(transfer_db, dbs_ready_file): - """待处理池收纳 blocked_recoverable,排除 success / not_matured。""" + """待处理池收纳 blocked_recoverable,排除 success(not_matured 已退役)。""" _blocked_matching(dbs_ready_file) items = list_backlog() invoice_set = {item.invoice_no for item in items} @@ -59,14 +59,14 @@ def test_backlog_order_stable_across_requery_touch(transfer_db, dbs_ready_file): updated_at 会让正在处理的行跳位(用户实测:恢复后被处理的行跳到列表末尾)。 业务稳定键下,触碰前后列表顺序完全一致。 """ - _blocked_matching(dbs_ready_file) # HOM-001(receipt 2026-08-05)与 HOX-002 不进池,构造两笔 blocked + _blocked_matching(dbs_ready_file) # HOM-001(inbound 2026-08-04)与 HOX-002 不进池,构造两笔 blocked item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first() # 手工造第二笔 blocked:不同收料日期、更晚创建 second = TransferInvoiceItem( matching_id=item.matching_id, source_code=item.source_code, invoice_no="HOM-002", material_no="MAT-003", material_name="垫片", - receipt_date="2026-08-01", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01", - receipt_quantity="10", status="blocked_recoverable", result_code="blocked_inventory_not_found", + movement_date="2026-08-01", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01", + movement_quantity="10", status="blocked_recoverable", result_code="blocked_inventory_not_found", ) db.session.add(second) db.session.commit() @@ -75,7 +75,7 @@ def test_backlog_order_stable_across_requery_touch(transfer_db, dbs_ready_file): db.session.commit() invoices = [dto.invoice_no for dto in list_backlog()] - # 排序只看业务键:HOM-002 收料日期(08-01) 早于 HOM-001(08-05),尽管它刚被触碰过 + # 排序只看业务键:HOM-002 收料日期(08-01) 早于 HOM-001(08-04),尽管它刚被触碰过 # (两行同来源,数据源键不改变先后)。 assert invoices == ["HOM-002", "HOM-001"] @@ -119,3 +119,28 @@ def test_list_backlog_exposes_result_code(transfer_db, dbs_ready_file): # 未打标的结果码为 None(普通阻断行不受影响)。 others = [entry for entry in items if entry.invoice_no != "HOM-001"] assert all(entry.result_code is None for entry in others) + + +def test_backlog_summary_includes_pending_match_count(transfer_db, dbs_ready_file): + """[断言意图·Task 12 D16] 汇总带「待匹配」桶计数(首页第 4 张数字卡): + 已落档且无有效 items 的收料记录计入,行桶(可恢复/已关闭)语义保持不变。""" + _blocked_matching(dbs_ready_file) + # 直接种子一条未匹配档记录(默认类型范围 HOM 前缀;无 items 引用)。 + from app.models import TransferMovementLedger + + db.session.add(TransferMovementLedger( + source_code="DBS-AWSBI", record_kind="inbound", + doc_no="HOM-901", line_no="1", line_seq="", in_out_flag="", + material_code="MAT-9", material_name="未匹配物料", specification="", + lot_no="LOT-9", quantity="55", unit="PCS", + warehouse_code="", storage_code="", movement_date="2026-08-04", + file_version="v1", file_sha256="a" * 64, + sheet_name="Receipt", row_no=9, + )) + db.session.commit() + + summary = backlog_summary() + + assert summary.pending_match_count == 1 # [断言意图] 待匹配桶计数独立于行桶 + assert summary.matchable_count == 1 # [断言意图] 范围内未匹配行同时计入可匹配 + assert summary.recoverable_count == 1 # [断言意图] 原行桶语义保持 diff --git a/backend/tests/services/in_transit_transfer/test_batch_actions.py b/backend/tests/services/in_transit_transfer/test_batch_actions.py index 065ad949..48342ec3 100644 --- a/backend/tests/services/in_transit_transfer/test_batch_actions.py +++ b/backend/tests/services/in_transit_transfer/test_batch_actions.py @@ -28,7 +28,7 @@ def _seed(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 seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub") blocked = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first() return deps, erp, blocked diff --git a/backend/tests/services/in_transit_transfer/test_cancellation.py b/backend/tests/services/in_transit_transfer/test_cancellation.py index 96ab76a3..20082137 100644 --- a/backend/tests/services/in_transit_transfer/test_cancellation.py +++ b/backend/tests/services/in_transit_transfer/test_cancellation.py @@ -24,7 +24,7 @@ def _ready_matching(dbs_ready_file): erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") deps, _, _ = make_transfer_deps(dbs_ready_file, capabilities=erp) seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub") items = ( db.session.query(TransferInvoiceItem) .filter_by(status="ready_to_execute") @@ -65,3 +65,53 @@ def test_cancel_marks_unstarted_items_only(transfer_db, dbs_ready_file, patch_so assert items["HOM-001"].status == "success" # 已成功单据保留 assert items["HOX-002"].status == "cancelled" # 未开始项取消 assert result["cancelled_count"] == 1 + + +def test_cancel_matching_retires_ready_rows_and_releases_ledger(transfer_db, dbs_ready_file): + """[Critical-2] 取消匹配:ready 行按 matching_id 退役(队列/执行门禁双拒), + 档记录释放后可被新匹配重圈——同批档记录不产生双份可执行行。""" + from app.models import TransferMatching + from app.services.in_transit_transfer.matching_service import list_executable_items + + deps, items = _ready_matching(dbs_ready_file) + ready_ids = [item.id for item in items] + assert len(ready_ids) == 2 + matching_a = TransferMatching.query.filter( + TransferMatching.id == items[0].matching_id).one() + + result = cancel_run(run_no=matching_a.run.run_no, reason="业务裁定不拨") + + # [断言意图] 出生行 run_id=None:取消必须按 matching_id 圈定才能退役 ready 行。 + rows = {row.id: row for row in db.session.query(TransferInvoiceItem).filter_by( + matching_id=matching_a.id).all()} + assert result["cancelled_count"] == 2 + assert all(rows[i].status == "cancelled" for i in ready_ids) + db.session.refresh(matching_a) + assert matching_a.status == "cancelled" + + # [断言意图] 队列不再出现 A 的行(可执行面清零)。 + payload = list_executable_items(deps=deps) + assert payload["counts"]["executable_count"] == 0 + + # [断言意图·防御双保险] 模拟绕过取消路径的残留 ready 行(匹配已取消): + # 队列不展示 + 执行门禁拒绝(EXECUTE_ITEMS_INVALID)。 + zombie = rows[ready_ids[0]] + zombie.status = "ready_to_execute" + zombie.result_code = None + db.session.commit() + payload = list_executable_items(deps=deps) + assert all(item.item_id != zombie.id for item in payload["items"]) + with pytest.raises(ValidationError) as gate: + execute_items(item_ids=[zombie.id], deps=deps) + assert gate.value.code == "TRANSFER.EXECUTE_ITEMS_INVALID" + + # [断言意图·D17 释放] 取消已释放档记录占用(A 的行→cancelled、匹配→cancelled): + # 匹配 B 出生翻转时重圈同批档记录、重建 2 行——新行绑定 matching B, + # ledger_record_id 与 A 的退役行同源,但行身份独立(一生一次绑定随取消重置)。 + second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + transfer_type="in_transit_to_hub") + matching_b = TransferMatching.query.filter_by(matching_no=second.matching_id).one() + born_b = db.session.query(TransferInvoiceItem).filter_by(matching_id=matching_b.id).all() + assert len(born_b) == 2 + assert {row.ledger_record_id for row in born_b} == { + row.ledger_record_id for row in rows.values()} diff --git a/backend/tests/services/in_transit_transfer/test_chat_actions.py b/backend/tests/services/in_transit_transfer/test_chat_actions.py index 7574fee4..9b77594c 100644 --- a/backend/tests/services/in_transit_transfer/test_chat_actions.py +++ b/backend/tests/services/in_transit_transfer/test_chat_actions.py @@ -78,6 +78,7 @@ def test_matching_action_streams_card(transfer_db, dbs_ready_file, monkeypatch): events = list(TransferMatchAction().stream(_ctx("in_transit_transfer", ACTION_TRANSFER_MATCH, { "source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06", + "transfer_type": "in_transit_to_hub", }))) assert len(events) == 1 event = events[0] @@ -103,7 +104,8 @@ def test_execute_action_streams_result_card(transfer_db, dbs_ready_file, monkeyp # 先跑匹配拿 matching_id matching_events = list(TransferMatchAction().stream(_ctx( "in_transit_transfer", ACTION_TRANSFER_MATCH, - {"source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06"}, + {"source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06", + "transfer_type": "in_transit_to_hub"}, ))) matching_id = matching_events[0].data["payload"]["summary"]["matching_id"] diff --git a/backend/tests/services/in_transit_transfer/test_contracts.py b/backend/tests/services/in_transit_transfer/test_contracts.py index b9a358a5..7d6f010c 100644 --- a/backend/tests/services/in_transit_transfer/test_contracts.py +++ b/backend/tests/services/in_transit_transfer/test_contracts.py @@ -29,7 +29,6 @@ pytestmark = pytest.mark.pure_unit EXPECTED_ERROR_CODES = { "TRANSFER_PERMISSION_DENIED", - "TRANSFER_RECEIPT_NOT_MATURED", "TRANSFER_FILE_NOT_READY", "TRANSFER_FILE_SCHEMA_INVALID", "TRANSFER_INVOICE_CONFLICT", @@ -67,13 +66,13 @@ def test_require_known_error_code_rejects_unknown(): def test_matching_counts_dto_fields(): - """匹配计数 DTO 包含文件内/未成熟/已匹配/可执行/阻断五类计数。""" + """匹配计数 DTO 包含文件内/已匹配/可执行/阻断等计数(not_matured 已退役)。""" counts = MatchingCountsDTO( - file_invoice_count=40, not_matured_count=8, matched_count=32, + file_invoice_count=40, matched_count=32, executable_count=27, blocked_count=5, ) assert counts.executable_count == 27 - assert counts.not_matured_count == 8 + assert counts.matched_count == 32 def test_matching_summary_dto_carries_estimate_and_hash(): @@ -82,9 +81,8 @@ def test_matching_summary_dto_carries_estimate_and_hash(): matching_id="MTG-20260806-001", status="ready_to_execute", business_date="2026-08-06", - eligible_receipt_date_to="2026-08-05", expires_at="2026-08-06T09:20:00+08:00", - counts=MatchingCountsDTO(40, 8, 32, 27, 5), + counts=MatchingCountsDTO(40, 32, 27, 5), estimated_transfer_quantity="18460", estimated_external_write_count=27, matching_hash="sha256:abc", diff --git a/backend/tests/services/in_transit_transfer/test_current_file_reparse.py b/backend/tests/services/in_transit_transfer/test_current_file_reparse.py new file mode 100644 index 00000000..703c5d47 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_current_file_reparse.py @@ -0,0 +1,277 @@ +"""current_file_reparse:当前归档重解析(不触发 RPA)守卫矩阵。 + +用途:锁定「当前最新可用入站/出站归档本地重解析落档」——成功落档、幂等跳过、 + 入站/出站 schema 失败标 parse_failed、无规则/无文件 fail-closed、 + 非 schema 异常与存储 AppError 回 ok=false 且不回标。 +依赖:factories、movement_file_version、app fixture、core.errors.ServiceUnavailableError; + 出站种子 DSV360_AWSDU,入站种子 seed_inbound_reparse_source。 +逻辑:归档字节经假存储注入;不新增 RPA 执行单元。 +""" + +from __future__ import annotations + +import logging +from datetime import datetime + +import pytest + +from app import db +from app.core.errors import AppError, ServiceUnavailableError +from app.models import ( + FreightRpaInboundReportFile, + FreightRpaOutboundReportConfig, + FreightRpaOutboundReportFile, + FreightRpaOutboundUnitRun, + FreightRpaParsingProfile, + TransferAuditEvent, + TransferMovementLedger, +) +from app.services.in_transit_transfer.current_file_reparse import reparse_current_file +from app.services.in_transit_transfer.ledger_sync import movement_file_version +from tests.services.in_transit_transfer import factories + +pytestmark = [pytest.mark.usefixtures("app")] + +SOURCE = "DSV360_AWSDU" +STORAGE_KEY = "shipping/outbound/evidence-sync.xlsx" + + +@pytest.fixture +def outbound_storage(monkeypatch): + """归档假存储:替换单例 get_bytes(所有引用方同源)。""" + fake = factories.FakeArchiveStorage() + monkeypatch.setattr( + "app.services.file_assets.storage.file_asset_storage.get_bytes", fake.get_bytes) + return fake + + +@pytest.fixture +def archive_storage(monkeypatch): + """归档假存储:注入 FakeArchiveStorage 并替换单例 get_bytes(所有引用方同源)。""" + fake = factories.FakeArchiveStorage() + monkeypatch.setattr( + "app.services.file_assets.storage.file_asset_storage.get_bytes", fake.get_bytes) + return fake + + +def _seed_outbound_world(*, profile_status: str = "published") -> FreightRpaOutboundReportFile: + """出站世界种子:出站配置(绑定解析规则)+ 执行单元 + 当天可用归档文件行。 + + Returns: + 已入库的 FreightRpaOutboundReportFile(字节由用例注入假存储)。 + """ + from app.models import FreightRpaSource + + source = FreightRpaSource.query.filter_by(source_code=SOURCE).one() + profile = FreightRpaParsingProfile( + purpose="outbound", profile_code=f"OUT_{SOURCE}", display_name=SOURCE, + version=1, status=profile_status, file_format="xlsx", + definition_json={ + "field_mapping": factories.INBOUND_MOVEMENT_FIELD_MAPPING, + "sheet_name": "Receipt", "header_row_index": 1, + }, + structure_definition_json={}, + ) + db.session.add(profile) + db.session.flush() + db.session.add(FreightRpaOutboundReportConfig( + source_id=source.id, + report_path_json={"report_name": "Outbound"}, + query_parameters_json=[], + parsing_profile_id=profile.id, + )) + unit = FreightRpaOutboundUnitRun( + schedule_run_id=None, source_id=source.id, source_code=SOURCE, + connector_type="dbs", warehouse_id="AWSDU", callback_id="outbound-sync-001", + status="success", config_snapshot_json={}, + ) + db.session.add(unit) + db.session.flush() + import hashlib + + digest = hashlib.sha256(b"outbound evidence workbook").hexdigest() + report = FreightRpaOutboundReportFile( + unit_run_id=unit.id, storage_provider="minio", storage_bucket="test", + storage_key=STORAGE_KEY, original_filename="outbound-sync.xlsx", + file_size=16, sha256=digest, + created_at=datetime.utcnow(), + ) + db.session.add(report) + db.session.commit() + return report + + +def test_reparse_outbound_inserts_ledger_without_new_rpa_run(outbound_storage): + # [断言意图] 已落地出站文件重解析后出现 outbound 档行,且不新增出站执行单元。 + report = _seed_outbound_world() + runs_before = FreightRpaOutboundUnitRun.query.filter_by(source_code=SOURCE).count() + outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([ + ["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"], + ]) + + result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow()) + + assert result.ok is True + assert result.file_id == report.id + assert result.inserted == 1 + assert result.file_status == "ready" + assert TransferMovementLedger.query.filter_by( + source_code=SOURCE, record_kind="outbound", doc_no="ASN-O1").count() == 1 + assert FreightRpaOutboundUnitRun.query.filter_by(source_code=SOURCE).count() == runs_before + assert TransferAuditEvent.query.filter_by(event_type="TRANSFER_EVIDENCE_SYNCED").count() == 1 + + +def test_reparse_same_outbound_file_skips_existing_row(outbound_storage): + # [断言意图] 同一份摘要再解析一次不插入第二行。 + _seed_outbound_world() + outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([ + ["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"], + ]) + reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow()) + + again = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow()) + + assert again.ok is True + assert again.inserted == 0 + assert again.skipped == 1 + assert TransferMovementLedger.query.filter_by( + source_code=SOURCE, record_kind="outbound").count() == 1 + + +def test_reparse_schema_failure_marks_file_and_lands_nothing(outbound_storage): + # [断言意图] 单号缺失是结构失败:零档行,文件变为 parse_failed,响应带原因。 + report = _seed_outbound_world() + outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx( + [["", 100, "O", "MAT-X", "成品", "LOT-X", 30, "2026-10-16"]]) + + result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow()) + + assert result.ok is False + assert result.file_status == "parse_failed" + assert result.inserted == 0 + assert "missing_invoice_no" in (result.error_message or "") + marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one() + assert marked.parse_failed_at is not None + assert TransferMovementLedger.query.filter_by( + source_code=SOURCE, record_kind="outbound").count() == 0 + + +def test_reparse_without_published_profile_does_not_mark_parse_failed(outbound_storage): + # [断言意图] 规则未发布不是文件错误,不写 parse_failed。 + report = _seed_outbound_world(profile_status="draft") + outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([ + ["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"], + ]) + + with pytest.raises(AppError) as exc_info: + reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow()) + + assert exc_info.value.code == "TRANSFER.CURRENT_REPARSE_NO_PROFILE" + marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one() + assert marked.parse_failed_at is None + + +def test_reparse_without_file_raises(): + # [断言意图] 没有可用归档时拒绝,而不是去触发 RPA。 + with pytest.raises(AppError) as exc_info: + reparse_current_file( + source_code="DSV360_AWSDU", record_kind="outbound", now=datetime.utcnow()) + + assert exc_info.value.code == "TRANSFER.CURRENT_REPARSE_NO_FILE" + assert exc_info.value.http_status == 422 + + +def test_reparse_non_schema_error_does_not_mark_parse_failed(outbound_storage, monkeypatch, caplog): + # [断言意图] 数据库一类异常回滚后不把文件标成解析失败,并把异常文本带回。 + report = _seed_outbound_world() + outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([ + ["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"], + ]) + + def _boom(**_kwargs): + raise RuntimeError("value too long for varchar(64)") + + monkeypatch.setattr( + "app.services.in_transit_transfer.current_file_reparse.sync_outbound_source_rows", + _boom, + ) + with caplog.at_level(logging.ERROR): + result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow()) + + assert result.ok is False + assert result.error_code == "TRANSFER.CURRENT_REPARSE_FAILED" + assert "varchar(64)" in (result.error_message or "") + marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one() + assert marked.parse_failed_at is None + assert TransferMovementLedger.query.filter_by( + source_code=SOURCE, record_kind="outbound").count() == 0 + assert any( + "TRANSFER_CURRENT_REPARSE_FAILED" in record.message and "kind=outbound" in record.message + for record in caplog.records + ) + + +def test_reparse_storage_unavailable_returns_ok_false(outbound_storage, monkeypatch): + # [断言意图] 存储读抛 ServiceUnavailableError 时走 ok=false,不把文件标成解析失败。 + report = _seed_outbound_world() + + def _unavailable(_storage_key: str) -> bytes: + raise ServiceUnavailableError("object storage unreachable") + + monkeypatch.setattr( + "app.services.file_assets.storage.file_asset_storage.get_bytes", + _unavailable, + ) + result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow()) + + assert result.ok is False + assert result.error_code == "TRANSFER.CURRENT_REPARSE_FAILED" + assert "object storage unreachable" in (result.error_message or "") + marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one() + assert marked.parse_failed_at is None + assert TransferMovementLedger.query.filter_by( + source_code=SOURCE, record_kind="outbound").count() == 0 + + +def test_reparse_inbound_inserts_ledger(archive_storage): + # [断言意图] 入站当前文件走 sync_source_rows,record_kind 为 inbound。 + source, _profile = factories.seed_inbound_reparse_source("CRANE_REPARSE_NOW") + storage_key = "archive/CRANE_REPARSE_NOW/current.xlsx" + report = factories.seed_reparse_archive_file( + source, sha="c" * 64, storage_key=storage_key, created_at=datetime.utcnow()) + archive_storage.objects[storage_key] = factories.build_movement_xlsx([ + ["ASN-I1", "1", "I", "MAT-I1", "连接器", "LOT-I1", 10, "2026-08-05"], + ]) + + result = reparse_current_file( + source_code="CRANE_REPARSE_NOW", record_kind="inbound", now=datetime.utcnow()) + + assert result.ok is True + assert result.file_id == report.id + assert result.inserted == 1 + row = TransferMovementLedger.query.filter_by( + source_code="CRANE_REPARSE_NOW", record_kind="inbound").one() + assert row.doc_no == "ASN-I1" + assert row.file_version == movement_file_version("c" * 64) + + +def test_reparse_inbound_schema_failure_marks_file_and_lands_nothing(archive_storage): + # [断言意图] 入站单号缺失是结构失败:零档行,入站文件变为 parse_failed。 + source, _profile = factories.seed_inbound_reparse_source("CRANE_REPARSE_SCHEMA") + storage_key = "archive/CRANE_REPARSE_SCHEMA/current.xlsx" + report = factories.seed_reparse_archive_file( + source, sha="d" * 64, storage_key=storage_key, created_at=datetime.utcnow()) + archive_storage.objects[storage_key] = factories.build_movement_xlsx( + [["", 100, "O", "MAT-X", "成品", "LOT-X", 30, "2026-10-16"]]) + + result = reparse_current_file( + source_code="CRANE_REPARSE_SCHEMA", record_kind="inbound", now=datetime.utcnow()) + + assert result.ok is False + assert result.file_status == "parse_failed" + assert result.inserted == 0 + assert "missing_invoice_no" in (result.error_message or "") + marked = FreightRpaInboundReportFile.query.filter_by(id=report.id).one() + assert marked.parse_failed_at is not None + assert TransferMovementLedger.query.filter_by( + source_code="CRANE_REPARSE_SCHEMA", record_kind="inbound").count() == 0 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 0aadb2a7..2f416653 100644 --- a/backend/tests/services/in_transit_transfer/test_date_policy.py +++ b/backend/tests/services/in_transit_transfer/test_date_policy.py @@ -1,9 +1,12 @@ -"""在途调拨日期成熟度策略测试(L0 纯单元)。 +"""在途调拨业务日期与日期解析测试(L0 纯单元)。 -用途:验证 T+lag 成熟规则(默认 T+2)、当天/T-1 not_matured、未来日期阻断与上海业务时区; - 以及 parse_date 对 ISO / 美式 MM/DD/YYYY 收料日期的归一化。 +用途:验证 parse_date 对 ISO / 美式 MM/DD/YYYY 异动日期的归一化与上海业务时区 + 换算(business_date_now / business_date_utc_window)。 依赖:app.services.in_transit_transfer.date_policy(纯函数)。 -逻辑:全部断言只依赖业务日期与收料日期,不接触 Flask/DB(pure_unit)。 +逻辑:全部断言只依赖入参日期,不接触 Flask/DB(pure_unit)。 + 【成熟度规则已退役 2026-10-16】原 T+lag 成熟策略用例随概念一并删除; + 日期边界现在由调用方入参给定(交互=用户范围,排程=T−N 偏移参数), + 引擎仅保留「截止 ≤ 业务日期」入参校验(matching_service 用例覆盖)。 """ from __future__ import annotations @@ -16,63 +19,11 @@ import pytest from app.services.in_transit_transfer.date_policy import ( business_date_now, business_date_utc_window, - eligible_receipt_date_to, - maturity_status, parse_date, ) pytestmark = pytest.mark.pure_unit -BUSINESS_T = date(2026, 8, 6) - - -def test_same_day_receipt_is_not_matured(): - """当天收料必须返回 not_matured;成熟门禁不查询 外部系统(调用次数由服务层保证为 0)。""" - assert maturity_status(date(2026, 8, 6), BUSINESS_T) == "not_matured" - - -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(): - """更早收料同样可预检。""" - assert maturity_status(date(2026, 8, 1), BUSINESS_T) == "eligible" - - -def test_future_receipt_is_blocked(): - """未来日期收料返回结构化阻断值。""" - assert maturity_status(date(2026, 8, 7), BUSINESS_T) == "future" - - -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) - def test_business_date_now_uses_shanghai_across_utc_midnight(): """UTC 17:00(北京时间次日 01:00)业务日期不得漂移回 UTC 日期。""" @@ -108,17 +59,11 @@ def test_business_date_utc_window_maps_shanghai_day_to_utc(): assert (end_next - start_next).total_seconds() == 24 * 3600 -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 零写入。 + [断言意图] 异动文件常见 '08/13/2026 13:08:00';仅认 ISO 会导致 + evidence_sync 整链 invalid_movement_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) diff --git a/backend/tests/services/in_transit_transfer/test_document_retry.py b/backend/tests/services/in_transit_transfer/test_document_retry.py index 8acbf7ea..e7fe0c4e 100644 --- a/backend/tests/services/in_transit_transfer/test_document_retry.py +++ b/backend/tests/services/in_transit_transfer/test_document_retry.py @@ -33,7 +33,7 @@ def _failed_document(dbs_ready_file, patch_source_file_status): for material, warehouse, lot in _INVOICE_TUPLES.values(): erp.seed_stock(material, warehouse, lot, "1200") seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub") patch_source_file_status() ready_ids = [ item.id for item in TransferInvoiceItem.query.filter_by(status="ready_to_execute").all() 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 60bee863..7ddb66bf 100644 --- a/backend/tests/services/in_transit_transfer/test_evidence_sync.py +++ b/backend/tests/services/in_transit_transfer/test_evidence_sync.py @@ -1,12 +1,18 @@ -"""证据同步三分类写入回归。 +"""证据同步落档回归(出生翻转:断言对象=库存异动档)。 -用途:锁死 evidence_sync 的核心语义——新行插入(待查态)、既有行按文件刷新、 - 值变重置库存侧、缺席行存续(只换戳不改状态)、终态行绝不触碰、全程零 ERP 调用; - 解析失败分层(2026-09-29):同步成功清除当前可用文件的解析失败标记, - 桥内 schema 类解析失败把失败事实独立 commit 落到当前可用文件上。 +用途:锁死 evidence_sync 的核心语义——解析行按明细粒度聚合成领域行落档 + (数量相加、首行溯源)、幂等(同文件重落完全不动行)、证据变原行更新 + (业务值换新 + 溯源五列换新)、缺席不删、封存行永不更新永不复活、 + 全程零 ERP 调用;解析失败分层(2026-09-29):同步成功清除当前可用文件的 + 解析失败标记,桥内 schema 类解析失败把失败事实独立 commit 落到当前可用 + 文件上;桥隔离(异常不向收料回调链路传播、成功自行 commit); + 档自然键坍缩守卫(终审 I3):同自然键批内料号不同的坍缩形态写 + ledger_natural_key_collapse 审计事件(静默丢行 → 显式可观测,行处理不变)。 依赖:repo_fakes(Fake 文件仓库注入文件行)、app fixture。 -逻辑:通过 Fake repository 的 latest_ready_file 提供文件;直接断言行级状态; - 解析失败标记用例另建真实 ORM 收料单元/归档文件(当天业务日窗口内 → 可用)。 +逻辑:通过 Fake repository 的 latest_ready_file 提供文件;断言对象从 items + 平移到档(TransferMovementLedger,「档断言等价于原 items 断言」—— + 数量=旧 items 汇总值、行数=旧 items 汇总行数);解析失败标记用例另建 + 真实 ORM 收料单元/归档文件(当天业务日窗口内 → 可用)。 """ from __future__ import annotations @@ -17,12 +23,9 @@ from datetime import datetime import pytest from app import db -from app.models import TransferInvoiceItem -from app.services.in_transit_transfer.evidence_sync import ( - SYNC_RESULT_PENDING, - align_scope_rows, - sync_source_rows, -) +from app.models import TransferAuditEvent, TransferInvoiceItem, TransferMovementLedger +from app.services.in_transit_transfer import evidence_sync +from app.services.in_transit_transfer.evidence_sync import sync_source_rows from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps pytestmark = [pytest.mark.usefixtures("app")] @@ -30,10 +33,20 @@ pytestmark = [pytest.mark.usefixtures("app")] NOW = datetime(2026, 9, 25, 10, 0, 0) -def _pending_count(source_code="DBS-AWSBI"): - """统计某来源处于待查态(pending_stock_check)的行数。""" - return TransferInvoiceItem.query.filter_by( - source_code=source_code, result_code=SYNC_RESULT_PENDING).count() +def _ledger_rows(source_code="DBS-AWSBI") -> list[TransferMovementLedger]: + """按自然键序取某来源全部档行(断言主对象)。""" + return ( + TransferMovementLedger.query + .filter_by(source_code=source_code, record_kind="inbound") + .order_by(TransferMovementLedger.doc_no.asc(), TransferMovementLedger.id.asc()) + .all() + ) + + +def _by_doc(doc_no: str, source_code="DBS-AWSBI") -> TransferMovementLedger: + """按单号取档行(fixture 内单号唯一)。""" + return TransferMovementLedger.query.filter_by( + source_code=source_code, doc_no=doc_no).one() def _seed_usable_report_file(*, source_code: str, sha: str, callback_id: str): @@ -44,24 +57,24 @@ def _seed_usable_report_file(*, source_code: str, sha: str, callback_id: str): sha: 归档文件 sha256(与 Fake 仓库 checksum 保持同值,模拟同一份文件)。 callback_id: 收料执行单元回调键(唯一约束,用例间取不同值)。 Returns: - 已入库的 ShippingReceiptReportFile。 + 已入库的 FreightRpaInboundReportFile。 """ from app import db from app.models import ( - ShippingInventorySource, - ShippingReceiptReportFile, - ShippingReceiptRpaUnitRun, + FreightRpaSource, + FreightRpaInboundReportFile, + FreightRpaInboundUnitRun, ) - source = ShippingInventorySource.query.filter_by(source_code="DSV360_AWSDU").one() - unit = ShippingReceiptRpaUnitRun( - inventory_source_id=source.id, source_code=source_code, + source = FreightRpaSource.query.filter_by(source_code="DSV360_AWSDU").one() + unit = FreightRpaInboundUnitRun( + source_id=source.id, source_code=source_code, connector_type="dbs", callback_id=callback_id, status="success", config_snapshot_json={}, ) db.session.add(unit) db.session.flush() - report = ShippingReceiptReportFile( + report = FreightRpaInboundReportFile( unit_run_id=unit.id, storage_provider="minio", storage_bucket="test", storage_key=f"shipping/receipt/{callback_id}.xlsx", original_filename=f"{callback_id}.xlsx", file_size=16, sha256=sha, @@ -71,198 +84,141 @@ def _seed_usable_report_file(*, source_code: str, sha: str, callback_id: str): return report -def test_sync_inserts_pending_rows_without_erp(app, dbs_ready_file): - # [断言意图] 首次同步:文件行全部落库为待查态;ERP 能力零调用。 +def test_sync_inserts_ledger_rows_without_erp(app, dbs_ready_file): + # [断言意图] 首次同步:解析行按明细粒度聚合落档(HOM-001 两行数量相加、 + # HOX-002 单行),档行携带 record_kind/溯源;明细表不再落地(停写 items); + # ERP 能力零调用。 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 outcome.absent_kept == 0 - assert _pending_count() == outcome.inserted # [断言意图] 插入行全部待查态 - row = TransferInvoiceItem.query.filter_by(source_code="DBS-AWSBI").first() - assert row.status == "matching" # [断言意图] 13 状态内的待查表达 - assert row.result_code == SYNC_RESULT_PENDING - assert row.matching_id is None # [断言意图] 落地行尚无匹配归属 - assert erp.query_calls == 0 # [断言意图] 零 ERP 调用 + assert outcome is not None and outcome.inserted == 2 # [断言意图] 两张单各一条档行 + rows = _ledger_rows() + assert len(rows) == 2 + assert all(row.record_kind == "inbound" for row in rows) + hom = _by_doc("HOM-001") + # [断言意图] 数量聚合等价于旧 items 汇总断言:500+700=1200(档是匹配圈定的 + # 数量真相源,与旧 items movement_quantity 等值)。 + assert hom.quantity == "1200" + assert hom.material_code == "MAT-001" and hom.lot_no == "LOT-10" + assert hom.movement_date == "2026-08-04" + assert hom.file_version == "v3" and hom.file_sha256 == "d" * 64 + assert hom.sheet_name == "Receipt" and hom.row_no == 10 # 组内首行溯源 + assert TransferInvoiceItem.query.count() == 0 # [断言意图] 停写 items + assert erp.query_calls == 0 # [断言意图] 零 ERP 调用 def test_sync_is_idempotent_when_sha_unchanged(app, dbs_ready_file): - # [断言意图] 同文件重复同步:整行跳过,不续新鲜度、不产生新行。 + # [断言意图] 同文件重复落档:全部跳过,档行完全不动(不续 updated_at、无新行)。 deps, _, _ = make_transfer_deps(dbs_ready_file) sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW) - before = TransferInvoiceItem.query.filter_by(source_code="DBS-AWSBI").all() - stamps = [r.updated_at for r in before] + before = _ledger_rows() + stamps = [(r.id, r.updated_at, r.quantity) for r in before] - sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW) + outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps, + business_date="2026-08-06", now=NOW) - after = TransferInvoiceItem.query.filter_by(source_code="DBS-AWSBI").all() - assert [r.id for r in after] == [r.id for r in before] # [断言意图] 不产生新行 - assert [r.updated_at for r in after] == stamps # [断言意图] sha 一致零写入 + assert outcome is not None and outcome.skipped == 2 # [断言意图] 幂等跳过计数 + assert outcome.inserted == 0 and outcome.updated == 0 + after = _ledger_rows() + assert [(r.id, r.updated_at, r.quantity) for r in after] == stamps # [断言意图] 零写入 -def test_sync_keeps_absent_rows_and_never_touches_terminal(app, dbs_ready_file): - # [断言意图] 新版文件缺席的行 → 存续:状态/结果码原样保留,只换版本戳; - # 终态行保持既定事实。(收料 RPA 非全量导出:缺席≠删除,2026-09-28 语义) +def test_sync_keeps_absent_rows(app, dbs_ready_file): + # [断言意图] 新版文件缺席的档行 → 保留不删(收料 RPA 非全量导出,缺席≠删除); + # 档无 TTL:缺席也不换戳(与旧 items 存续换戳的差异,档以 sha 幂等为准)。 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() + frozen = [(r.id, r.quantity, r.file_sha256) for r in _ledger_rows()] 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) + deps2.file_repository.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" # [断言意图] 终态行不复活 + assert outcome is not None and outcome.inserted == 0 + assert [(r.id, r.quantity, r.file_sha256) for r in _ledger_rows()] == frozen + # [断言意图] 缺席行的档记录原样留存(事实不随文件消失)。 -def test_sync_does_not_resurrect_terminal_rows_on_relanding(app, dbs_ready_file): - # [断言意图] 来源全终态后同文件重落地(同日 RPA 重试 / align 兜底重解析): - # 不重插新 pending 行、终态行原样保留——已执行调拨单不得复活回待办池。 +def test_sync_never_touches_sealed_rows_on_relanding(app, dbs_ready_file): + # [断言意图] 已执行封存行(transfer_executed=true):同文件重落地不更新、 + # 不复活(防二次调拨;命中即计 sealed_skipped)。 deps, _, _ = make_transfer_deps(dbs_ready_file) sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW) - rows = TransferInvoiceItem.query.filter_by(source_code="DBS-AWSBI").all() - assert len(rows) == 2 # [断言意图] 前置:文件聚合成两行 - for r in rows: - r.status = "success" # 全部推到终态(模拟已执行) - r.result_code = None # 执行终态清待查标记 + hom = _by_doc("HOM-001") + hom.transfer_executed = True + hom.executed_doc_no = "TRF-0001" db.session.flush() - frozen = {r.id: (r.status, r.result_code, r.updated_at) for r in rows} + frozen = (hom.quantity, hom.updated_at, hom.file_sha256) # 同一文件重落地:set_next_file 重注同 rows / 同 checksum(一次有效覆盖)。 deps.file_repository.set_next_file( source_code="DBS-AWSBI", rows=tuple(dbs_ready_file["rows"]), checksum="d" * 64) - later = datetime(2026, 9, 25, 11, 0, 0) # 后续新鲜度基准:任何写入都会暴露 + later = datetime(2026, 9, 25, 11, 0, 0) outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=later) assert outcome is not None - assert outcome.inserted == 0 # [断言意图] 终态 quad 不重插新行 - assert outcome.skipped == 2 # [断言意图] 全部计入跳过口径 - assert _pending_count() == 0 # [断言意图] 已执行单据不重回待办池 - after = TransferInvoiceItem.query.filter_by(source_code="DBS-AWSBI").all() - assert [r.id for r in after] == [r.id for r in rows] # [断言意图] 行集合不变 - assert {r.id: (r.status, r.result_code, r.updated_at) for r in after} == frozen - # [断言意图] 终态行零写入(含 updated_at 未被续新) + assert outcome.sealed_skipped == 1 # [断言意图] 封存行命中即计 + db.session.expire_all() + hom = _by_doc("HOM-001") + assert (hom.quantity, hom.updated_at, hom.file_sha256) == frozen # [断言意图] 零写入 + assert hom.transfer_executed is True and hom.executed_doc_no == "TRF-0001" -def test_sync_refreshes_display_fields_without_reset(app, dbs_ready_file): - # [断言意图] 纯名称/规格变更(sha 变、三证据字段未变)→ refreshed 且展示值已更新。 +def test_sync_updates_row_on_evidence_change(app, dbs_ready_file): + # [断言意图] 证据变化(数量)→ 原行更新:业务值换新 + 溯源五列整体换新, + # 不产生第二行(自然键幂等);未变行只跳过。 + deps, _, _ = make_transfer_deps(dbs_ready_file) + sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW) + + changed_rows = [ + {**row, "quantity": "1300"} if row["doc_no"] == "HOM-001" else row + for row in dbs_ready_file["rows"] + ] + deps.file_repository.set_next_file(source_code="DBS-AWSBI", rows=changed_rows, + checksum="f" * 64) + outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps, + business_date="2026-08-06", now=NOW) + + # [断言意图] 新文件版本(sha 变)下两行都走原行更新分支:HOM-001 业务值换新, + # HOX-002 业务值未变仅溯源换新(sha 变=证据换新版本,计数同归 updated)。 + assert outcome.updated == 2 and outcome.inserted == 0 + hom = _by_doc("HOM-001") + # [断言意图] 数量随新文件换新:夹具 HOM-001 两行的 quantity 均被替换为 1300, + # 聚合落档 2600(档=聚合镜像,聚合语义由 ledger 落地承接)。 + assert hom.quantity == "2600" + assert hom.file_sha256 == "f" * 64 # [断言意图] 溯源换新 + hox = _by_doc("HOX-002") + assert hox.quantity == "1200" and hox.file_sha256 == "f" * 64 # [断言意图] 值不变仅换溯源 + + +def test_sync_refreshes_display_fields_on_evidence_change(app, dbs_ready_file): + # [断言意图] 名称/规格属档镜像列:随原行更新分支整体换新(档=忠实镜像, + # 无「仅展示变更不重置」分支——那是 items 时代为保护库存评估的语义)。 deps, _, _ = make_transfer_deps(dbs_ready_file) sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW) - # 同证据(数量/批号/仓库/单号/料号/日期不变),只改 material_name/specification。 renamed_rows = [ - {**row, "material_name": "改名组件", "specification": "改规格 / NEW"} + {**row, "material_name": "改名组件", "specification": "改规格 / NEW", "quantity": "999"} for row in dbs_ready_file["rows"] ] deps.file_repository.set_next_file(source_code="DBS-AWSBI", rows=renamed_rows, checksum="f" * 64) outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW) - assert outcome.refreshed == 2 and outcome.reset_pending == 0 # [断言意图] 展示变更不重置待查 - row = TransferInvoiceItem.query.filter_by( - source_code="DBS-AWSBI", invoice_no="HOM-001").first() - assert row.material_name == "改名组件" # [断言意图] 展示值随新文件刷新 - assert row.specification == "改规格 / NEW" # [断言意图] 规格同步刷新 - assert row.status == "matching" # [断言意图] 状态不受展示变更影响 - assert row.result_code == SYNC_RESULT_PENDING - assert row.raw_lines_json[0]["file_sha256"] == "f" * 64 # [断言意图] 版本戳已换新 + assert outcome.updated == 2 + hom = _by_doc("HOM-001") + assert hom.material_name == "改名组件" # [断言意图] 展示值随新文件换新 + assert hom.specification == "改规格 / NEW" -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 # [断言意图] 删除解释清除 - - -def test_receipt_bridge_is_failure_isolated(app, monkeypatch, caplog): - # [断言意图] 同步崩溃只记日志:异常绝不向收料回调链路传播。 +def test_inbound_bridge_is_failure_isolated(app, monkeypatch, caplog): + # [断言意图] 落档崩溃只记日志:异常绝不向收料回调链路传播。 from app.services.in_transit_transfer import evidence_sync def _boom(**kwargs): @@ -277,8 +233,9 @@ def test_receipt_bridge_is_failure_isolated(app, monkeypatch, caplog): assert any("TRANSFER_EVIDENCE_SYNC" in r.message for r in caplog.records) -def test_receipt_bridge_commits_on_success(app, dbs_ready_file, monkeypatch): - # [断言意图] 成功路径自行 commit(B3 教训:不依赖调用方提交时机)。 +def test_inbound_bridge_commits_ledger_on_success(app, dbs_ready_file, monkeypatch): + # [断言意图] 成功路径自行 commit(B3 教训:不依赖调用方提交时机); + # 端到端一遍:桥 → 解析 → 聚合落档(档行持久化,items 停写)。 from app.services.in_transit_transfer import evidence_sync deps, _, _ = make_transfer_deps(dbs_ready_file) monkeypatch.setattr( @@ -288,29 +245,31 @@ def test_receipt_bridge_commits_on_success(app, dbs_ready_file, monkeypatch): source_code="DBS-AWSBI", business_date="2026-08-06", now=NOW) assert ok is True - assert _pending_count("DBS-AWSBI") > 0 # [断言意图] 已持久化(含 commit) + db.session.expire_all() + assert len(_ledger_rows()) == 2 # [断言意图] 档行已持久化(含 commit) + assert TransferInvoiceItem.query.count() == 0 # [断言意图] items 停写 -def test_receipt_bridge_skips_when_no_file(app): +def test_inbound_bridge_skips_when_no_file(app): # [断言意图] 来源无可用文件:静默返回 True(无事发生,非错误)。 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 类解析失败)→ 失败事实 +def test_inbound_bridge_schema_failure_marks_parse_failed(app, dbs_ready_file, monkeypatch): + # [断言意图] 桥内同步抛 MovementFileSchemaError(schema 类解析失败)→ 失败事实 # 独立 commit 落到当前可用文件(parse_failed 三列),来源投影转 parse_failed; # 同步数据已回滚(桥隔离保持)。 from app import db - from app.models import ShippingReceiptReportFile + from app.models import FreightRpaInboundReportFile from app.services.in_transit_transfer import evidence_sync from app.services.in_transit_transfer.source_file_status import resolve_source_file_status 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)。 + # 行缺单号(doc_no 置空)→ 解析必抛 MovementFileSchemaError(行级 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) @@ -321,9 +280,9 @@ def test_receipt_bridge_schema_failure_marks_parse_failed(app, dbs_ready_file, m source_code="DBS-AWSBI", business_date="2026-08-06", now=NOW) assert ok is False # [断言意图] 同步失败被吞(桥隔离) - assert _pending_count() == 0 # [断言意图] 坏行未落库(同步数据已回滚) + assert TransferMovementLedger.query.count() == 0 # [断言意图] 坏行未落档(同步数据已回滚) db.session.expire_all() # 标记经桥内独立 commit:失效缓存重读 - row = db.session.query(ShippingReceiptReportFile).filter_by(id=report.id).one() + row = db.session.query(FreightRpaInboundReportFile).filter_by(id=report.id).one() assert row.parse_failed_at is not None # [断言意图] 失败事实已落库 assert row.parse_error_code == "TRANSFER_FILE_SCHEMA_INVALID" assert row.parse_error_message @@ -335,13 +294,13 @@ 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, + record_inbound_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( + record_inbound_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" # [断言意图] 前置:确已标记 @@ -359,41 +318,144 @@ def test_sync_success_clears_parse_failed_mark(app, dbs_ready_file): 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) +def test_sync_writes_cross_flag_for_contradictory_in_out_flag(app): + # [断言意图] record_kind='inbound' 行出现出库语义 '-1':照常落档 + 计 + # cross_flagged(解析错位标记由 ledger_sync 落审计事件,档不拒收)。 + deps, _, _ = make_transfer_deps({ + "source_code": "DBS-AWSBI", + "business_date": "2026-08-06", + "file_purpose": "inbound", + "file_no": "REC-X", + "file_version": "v1", + "checksum": "x" * 64, + "status": "ready", + "rows": [ + {"sheet": "Receipt", "row_no": 1, "doc_no": "HOM-X1", "line_no": "1", + "in_out_flag": "-1", "lot_no": "LOT-X", "material_code": "MAT-X", + "movement_date": "2026-08-05", "quantity": "10", "source_code": "DBS-AWSBI"}, + ], + }) 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 # [断言意图] 换戳≠查过库存 + assert outcome is not None and outcome.cross_flagged == 1 + row = _by_doc("HOM-X1") + assert row.in_out_flag == "-1" # [断言意图] 原值落档不拒收 - # 收料数量变化 → 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) + +def test_sync_lands_external_doc_line_and_expands_natural_key(app): + # [断言意图] 外部单据身份(外部单号/外部项次=WMS Order #/行号)经落档链路 + # 写入档列并参与自然键:同单号同行不同外部单号 = 两行独立落档(2026-10-21 + # 档幂等主键管控扩维),外部身份列原值随行留存。 + deps, _, _ = make_transfer_deps({ + "source_code": "DBS-AWSBI", + "business_date": "2026-08-06", + "file_purpose": "inbound", + "file_no": "REC-EXT", + "file_version": "v1", + "checksum": "e" * 64, + "status": "ready", + "rows": [ + {"sheet": "Receipt", "row_no": 1, "doc_no": "HOM-E1", "line_no": "1", + "external_doc_no": "WMS-001", "external_line_no": "10", + "lot_no": "LOT-E", "material_code": "MAT-E", "material_name": "外部身份料号", + "movement_date": "2026-08-05", "quantity": "10", "source_code": "DBS-AWSBI"}, + {"sheet": "Receipt", "row_no": 2, "doc_no": "HOM-E1", "line_no": "1", + "external_doc_no": "WMS-002", "external_line_no": "10", + "lot_no": "LOT-E", "material_code": "MAT-E", "material_name": "外部身份料号", + "movement_date": "2026-08-05", "quantity": "20", "source_code": "DBS-AWSBI"}, + ], + }) 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 + assert outcome is not None and outcome.inserted == 2 # [断言意图] 不同外部单号各自成行 + rows = TransferMovementLedger.query.filter_by( + source_code="DBS-AWSBI", doc_no="HOM-E1").order_by(TransferMovementLedger.id).all() + assert [(r.external_doc_no, r.external_line_no) for r in rows] == [ + ("WMS-001", "10"), ("WMS-002", "10")] # [断言意图] 外部身份列原值落档 + + +def _collapsed_multi_material_file() -> dict: + """同单号双料号、行级 line_no/line_seq/in_out_flag 全空且 carton/lot 等值的坍缩形态文件。 + + 档自然键 (source_code, record_kind, doc_no, line_no, line_seq, in_out_flag, + carton_id, lot_no) 不含料号(tt14 起含箱号/批号,批内等值才同键):两行在批内 + 折叠为同一自然键,第二料号行会被幂等吞掉(首见为准)。 + """ + return { + "source_code": "DBS-AWSBI", + "business_date": "2026-08-06", + "file_purpose": "inbound", + "file_no": "REC-C1", + "file_version": "v1", + "checksum": "c1" + "0" * 62, + "status": "ready", + "rows": [ + {"sheet": "Receipt", "row_no": 1, "doc_no": "HOM-C1", "lot_no": "LOT-A", + "material_code": "MAT-A", "movement_date": "2026-08-05", "quantity": "10", + "source_code": "DBS-AWSBI"}, + {"sheet": "Receipt", "row_no": 2, "doc_no": "HOM-C1", "lot_no": "LOT-A", + "material_code": "MAT-B", "movement_date": "2026-08-05", "quantity": "20", + "source_code": "DBS-AWSBI"}, + ], + } + + +def test_sync_flags_natural_key_collapse_for_multi_material_without_line_fields(app): + # [断言意图] 终审 I3 坍缩守卫:同单号双料号且行级项次全空 → 第二料号行仍被 + # 自然键幂等吞掉(首见为准,数据行为维持现状),但必须留下 + # ledger_natural_key_collapse 审计事件——静默丢行变显式可观测。 + deps, _, _ = make_transfer_deps(_collapsed_multi_material_file()) + + outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps, + business_date="2026-08-06", now=NOW) + + rows = TransferMovementLedger.query.filter_by( + source_code="DBS-AWSBI", doc_no="HOM-C1").all() + assert len(rows) == 1 # [断言意图] 第二料号行被吞(首见为准) + assert rows[0].material_code == "MAT-A" and rows[0].line_no == "" + assert outcome is not None + assert outcome.inserted == 1 and outcome.skipped == 1 # [断言意图] 吞掉的行计 skipped + + event = TransferAuditEvent.query.filter_by( + event_type=evidence_sync.LEDGER_NATURAL_KEY_COLLAPSE_EVENT).one() + assert event.aggregate_type == "transfer_movement_ledger" + assert "HOM-C1" in event.aggregate_id # [断言意图] 事件定位到坍缩单号 + assert event.result == "failure" # [断言意图] 数据质量降级事件 + assert event.after_json["material_codes"] == ["MAT-A", "MAT-B"] # 首见序全量料号 + assert event.after_json["dropped_material_codes"] == ["MAT-B"] # 被吞料号可定位 + assert event.after_json["resolution"] == "first_seen_wins" + + +def test_collapse_event_not_reemitted_on_idempotent_relanding(app): + # [断言意图] 幂等重落不重复打事件(防只追加审计表被同文件重落刷爆,与 + # ledger_sync 交叉校验事件同款防刷口径);换文件版本(sha 变)才会再打。 + deps, _, _ = make_transfer_deps(_collapsed_multi_material_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=tuple(_collapsed_multi_material_file()["rows"]), + checksum="c1" + "0" * 62) + sync_source_rows(source_code="DBS-AWSBI", deps=deps, + business_date="2026-08-06", now=NOW) + + assert TransferAuditEvent.query.filter_by( + event_type=evidence_sync.LEDGER_NATURAL_KEY_COLLAPSE_EVENT).count() == 1 + + +def test_no_collapse_event_when_line_fields_present(app): + # [断言意图] 同单号双料号但项次列齐全(line_no 各异)→ 两个自然键两行落档, + # 不触发坍缩事件(真实 WMS 导出形态零误报)。 + file = _collapsed_multi_material_file() + file["rows"][0]["line_no"] = "1" + file["rows"][1]["line_no"] = "2" + deps, _, _ = make_transfer_deps(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 == 2 # [断言意图] 双料号各自成行 + assert TransferMovementLedger.query.filter_by( + source_code="DBS-AWSBI", doc_no="HOM-C1").count() == 2 + assert TransferAuditEvent.query.filter_by( + event_type=evidence_sync.LEDGER_NATURAL_KEY_COLLAPSE_EVENT).count() == 0 diff --git a/backend/tests/services/in_transit_transfer/test_excel_export.py b/backend/tests/services/in_transit_transfer/test_excel_export.py index 08db831a..675b27fc 100644 --- a/backend/tests/services/in_transit_transfer/test_excel_export.py +++ b/backend/tests/services/in_transit_transfer/test_excel_export.py @@ -29,7 +29,7 @@ def _executed_run(dbs_ready_file, patch_source_file_status): erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") erp.write_scenarios["HOM-001"] = "business_failed" seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub") items = ( db.session.query(TransferInvoiceItem) .filter_by(status="ready_to_execute") 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 2eeb85d3..ff51213b 100644 --- a/backend/tests/services/in_transit_transfer/test_execute_items.py +++ b/backend/tests/services/in_transit_transfer/test_execute_items.py @@ -47,7 +47,7 @@ def _ready_items(dbs_ready_file, *seeds) -> tuple: erp.seed_stock(*_INVOICE_TUPLES[invoice_no], quantity) deps, erp, _ = make_transfer_deps(dbs_ready_file, capabilities=erp) seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") items = ( TransferInvoiceItem.query.filter_by(status="ready_to_execute") .order_by(TransferInvoiceItem.id) @@ -76,7 +76,7 @@ def test_execute_items_writes_one_order_and_aggregates(transfer_db, dbs_ready_fi deps, erp, items = _ready_items( dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"), ) - matching = db.session.query(TransferMatching).filter_by(business_date="2026-08-06").first() + matching = db.session.query(TransferMatching).filter_by(business_date="2026-08-07").first() outcome = execute_items(item_ids=[item.id for item in items], deps=deps) # Run 终态与单据聚合:同组两 Invoice 合并一张 ERP 单(D1 五元组一组一单),无异常。 @@ -145,7 +145,7 @@ def _two_group_deps(dbs_ready_file, patch_source_file_status): erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") deps, erp, _ = make_transfer_deps(file, capabilities=erp) seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") items = ( TransferInvoiceItem.query.filter_by(status="ready_to_execute") .order_by(TransferInvoiceItem.id) @@ -289,7 +289,7 @@ def test_execute_matching_items_executes_selected_invoices(transfer_db, dbs_read deps, erp, _ = _ready_items( dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"), ) - matching = db.session.query(TransferMatching).filter_by(business_date="2026-08-06").first() + matching = db.session.query(TransferMatching).filter_by(business_date="2026-08-07").first() outcome = execute_matching_items( matching_id=matching.matching_no, deps=deps, invoice_nos=["HOM-001"], 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 96358086..89adf54c 100644 --- a/backend/tests/services/in_transit_transfer/test_execution_documents.py +++ b/backend/tests/services/in_transit_transfer/test_execution_documents.py @@ -10,7 +10,10 @@ 依赖:transfer_db、fakes、repo_fakes、matching_service、execution_service、jobs.queue。 逻辑:场景编号对应计划 Task 10 Step 1 场景①-⑪;SQLite 无 PG 序列,单号序列经 monkeypatch execution_service._sequence_loader 注入替身;文件对账门禁经 - patch_source_file_status 夹具注入 ready 投影。 + patch_source_file_status 夹具注入 ready 投影。出站档行用例把入站/出站 + 投影分成两个 sha,确认门禁与 file_current 读档上的 record_kind。 + 【T−2 成熟封顶 2026-10-21】匹配 business_date 用 2026-08-07(行日期 + 2026-08-04/08-05 均 ≤T−2 成熟可圈;文件/种子新鲜度仍用 2026-08-06)。 """ from __future__ import annotations @@ -32,6 +35,7 @@ from app.models import ( TransferDocument, TransferInvoiceItem, TransferMatching, + TransferMovementLedger, TransferRun, ) from app.services.in_transit_transfer.execution_service import ( @@ -41,7 +45,7 @@ from app.services.in_transit_transfer.execution_service import ( retrigger_document, ) from app.services.in_transit_transfer.serializers import serialize_order -from app.services.in_transit_transfer.matching_service import create_matching +from app.services.in_transit_transfer.matching_service import create_matching, restore_matching from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps, seed_rows_from_file READY_SHA = "d" * 64 @@ -63,7 +67,7 @@ def _file(rows: list[dict], *, checksum: str = READY_SHA) -> dict: """由行构造 DBS-AWSBI ready 收料文件 dict。""" return { "source_code": "DBS-AWSBI", "business_date": "2026-08-06", - "file_purpose": "receipt", "file_no": "REC-TEST", "file_version": "v9", + "file_purpose": "inbound", "file_no": "REC-TEST", "file_version": "v9", "checksum": checksum, "status": "ready", "rows": rows, } @@ -146,7 +150,7 @@ def _order_call(erp, doc: TransferDocument) -> dict: # 场景①:两单不同收料日期 → 两张单各一单号(D1 收料日期入组键) # --------------------------------------------------------------------------- -def test_two_receipt_dates_create_two_documents( +def test_two_movement_dates_create_two_documents( transfer_db, dbs_ready_file, patch_source_file_status, seq_loader, ): """不同收料日期的同来源行必须拆为两张单,各自终身独立单号/时间戳。""" @@ -154,7 +158,7 @@ def test_two_receipt_dates_create_two_documents( _row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"), _row("Receipt", 2, "HOM-B", "LOT-20", "MAT-002", "2026-08-04", "700"), ]) - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps) assert outcome.status == "queued" @@ -162,7 +166,7 @@ def test_two_receipt_dates_create_two_documents( docs = _docs_of(run) # 断言意图:收料日期入组键(D1)→ 两日期两单,且单初态 pending。 assert len(docs) == 2 - assert {doc.receipt_date for doc in docs} == {"2026-08-05", "2026-08-04"} + assert {doc.movement_date for doc in docs} == {"2026-08-05", "2026-08-04"} assert all(doc.status == "pending" for doc in docs) assert len({doc.doc_no for doc in docs}) == 2 assert len({doc.submit_timestamp for doc in docs}) == 2 @@ -185,7 +189,7 @@ def test_same_order_same_material_lot_across_invoices_aggregates_line( ]) # 严格数量匹配逐 Invoice 核对:库存须等于单 Invoice 数量(聚合发生在执行组建单时)。 erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "500.5") - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps) run = TransferRun.query.filter_by(run_no=outcome.run_no).first() doc = _doc_for(run) @@ -205,14 +209,14 @@ def test_same_order_same_material_lot_across_invoices_aggregates_line( # 场景③:制单日期=组收料日期(gls_cm06 必须等于 Excel 异动日期,D1) # --------------------------------------------------------------------------- -def test_order_doc_date_equals_group_receipt_date( +def test_order_doc_date_equals_group_movement_date( transfer_db, dbs_ready_file, patch_source_file_status, seq_loader, ): """单 doc_date 必须等于组收料日期;posting_date 为执行当天业务日。""" deps, erp = _setup(dbs_ready_file, patch_source_file_status, [ _row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"), ]) - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps) run = TransferRun.query.filter_by(run_no=outcome.run_no).first() doc = _doc_for(run) @@ -221,7 +225,7 @@ def test_order_doc_date_equals_group_receipt_date( call = _order_call(erp, doc) # 断言意图:制单日期=组收料日期(2026-08-05),过账日期=执行当天(run 业务日)。 assert call.doc_date == "2026-08-05" - assert doc.receipt_date == "2026-08-05" + assert doc.movement_date == "2026-08-05" assert call.posting_date == run.business_date @@ -237,7 +241,7 @@ def test_order_success_propagates_to_all_items( _row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"), _row("Receipt", 2, "HOM-B", "LOT-20", "MAT-002", "2026-08-05", "700"), ]) - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps) run = TransferRun.query.filter_by(run_no=outcome.run_no).first() doc = _doc_for(run) @@ -274,7 +278,7 @@ def test_order_failure_isolates_to_its_items( _row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"), _row("Receipt", 2, "HOM-B", "LOT-20", "MAT-002", "2026-08-04", "700"), ]) - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") items = _ready_items() outcome = prepare_execution(item_ids=[i.id for i in items], deps=deps) run = TransferRun.query.filter_by(run_no=outcome.run_no).first() @@ -310,7 +314,7 @@ def test_worker_reclaim_executing_stage_confirmed_runs_final_only( deps, erp = _setup(dbs_ready_file, patch_source_file_status, [ _row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"), ]) - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps) run = TransferRun.query.filter_by(run_no=outcome.run_no).first() doc = _doc_for(run) @@ -342,7 +346,7 @@ def test_failed_order_reused_with_new_row_full_rerun( deps, erp = _setup(dbs_ready_file, patch_source_file_status, [ _row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"), ]) - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") first = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps) run1 = TransferRun.query.filter_by(run_no=first.run_no).first() doc = _doc_for(run1) @@ -353,7 +357,10 @@ def test_failed_order_reused_with_new_row_full_rerun( assert doc.status == "business_failed" old_doc_no, old_ts = doc.doc_no, doc.submit_timestamp - # 新一轮匹配新增同组新行(新料号),原 blocked 行原地刷新回 ready。 + # 2026-10-14 出生翻转后:新一轮匹配从当前档版本出生新行(新料号 HOM-C; + # HOM-A 档记录仍被首匹配的 blocked 行有效占用,不再出生)。原单 + # blocked_recoverable 旧行由 D7① 复用分支重关联新 Run(executing)随全量 + # 重跑——并非原地刷回 ready。 erp.write_scenarios_by_doc.pop(doc.doc_no) deps2, erp2, _ = make_transfer_deps(_file([ _row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"), @@ -363,7 +370,7 @@ def test_failed_order_reused_with_new_row_full_rerun( erp2.seed_stock("MAT-003", "DBS-TRANSIT", "LOT-30", "300") patch_source_file_status() seed_rows_from_file("DBS-AWSBI", deps2, "2026-08-06") # 新行 HOM-C 落地;HOM-A 幂等跳过 - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps2) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps2, transfer_type="in_transit_to_hub") second = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps2) run2 = TransferRun.query.filter_by(run_no=second.run_no).first() @@ -399,7 +406,7 @@ def test_result_unknown_order_blocks_new_rows( deps, erp = _setup(dbs_ready_file, patch_source_file_status, [ _row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"), ]) - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") first = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps) run1 = TransferRun.query.filter_by(run_no=first.run_no).first() doc = _doc_for(run1) @@ -415,9 +422,9 @@ def test_result_unknown_order_blocks_new_rows( db.session.add(TransferInvoiceItem( matching_id=matching.id, source_code="DBS-AWSBI", invoice_no="HOM-NEW", material_no="MAT-009", material_name="新行", specification="", - receipt_date="2026-08-05", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01", - receipt_quantity="100", unit="PCS", status="ready_to_execute", - receipt_warehouse_code="DBS-TRANSIT", + movement_date="2026-08-05", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01", + movement_quantity="100", unit="PCS", status="ready_to_execute", + movement_warehouse_code="DBS-TRANSIT", raw_lines_json=[{"sheet": "Receipt", "row_no": 9, "file_version": "v9", "file_sha256": READY_SHA}], )) db.session.commit() @@ -458,7 +465,7 @@ def test_retrigger_document_full_chain( deps, erp = _setup(dbs_ready_file, patch_source_file_status, [ _row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"), ]) - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") first = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps) run = TransferRun.query.filter_by(run_no=first.run_no).first() doc = _doc_for(run) @@ -528,7 +535,7 @@ def test_partial_unique_index_race_falls_back_to_reuse( deps, erp = _setup(dbs_ready_file, patch_source_file_status, [ _row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"), ]) - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") items = _ready_items() original_insert = execution_service._insert_document @@ -540,7 +547,7 @@ def test_partial_unique_index_race_falls_back_to_reuse( if state["called"] == 1: winner = TransferDocument( source_code=doc.source_code, external_org=doc.external_org, - receipt_date=doc.receipt_date, from_warehouse=doc.from_warehouse, + movement_date=doc.movement_date, from_warehouse=doc.from_warehouse, to_warehouse=doc.to_warehouse, doc_no="HX-CN01-OR-26099999999", submit_timestamp="concurrent" + "0" * 38, status="pending", @@ -557,7 +564,7 @@ def test_partial_unique_index_race_falls_back_to_reuse( db.session.expire_all() docs = TransferDocument.query.filter_by( - source_code="DBS-AWSBI", receipt_date="2026-08-05", + source_code="DBS-AWSBI", movement_date="2026-08-05", ).all() # 断言意图:竞态后同组仅一张单(DB 部分唯一索引兜底 + 复用重试成立)。 assert len(docs) == 1 @@ -580,7 +587,7 @@ def test_prepare_enqueues_single_transfer_run_job( deps, erp = _setup(dbs_ready_file, patch_source_file_status, [ _row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"), ]) - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") ids = [i.id for i in _ready_items()] outcome = prepare_execution(item_ids=ids, deps=deps) @@ -605,30 +612,37 @@ def test_prepare_enqueues_single_transfer_run_job( # --------------------------------------------------------------------------- -# 补充:worker 二次门禁(Hash 失效 fail-closed,不触外部) +# 补充:文件版本对账门禁退役(2026-10-22)——版本变化不再拦截 worker 执行 # --------------------------------------------------------------------------- -def test_execute_run_rechecks_file_hash_fail_closed( +def test_worker_executes_despite_file_version_change( transfer_db, dbs_ready_file, patch_source_file_status, seq_loader, ): - """worker 二次门禁:文件版本对账失败 → fail-closed(单置 technical_failed、行阻断、零写入)。""" + """文件版本对账门禁退役:最新文件 sha 变化后 worker 仍逐单执行到底。 + + [断言意图] 入站抓取是部分导出——新文件不含旧行 ≠ 旧行失效,按最新文件 sha + 对账会错误卡死未处理行(557 行积压实测);门禁退役后版本滞后的行照常执行, + 证据漂移的防护由写前库存复查(ERP 账面严格相等)承担。 + """ deps, erp = _setup(dbs_ready_file, patch_source_file_status, [ _row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"), ]) - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps) run = TransferRun.query.filter_by(run_no=outcome.run_no).first() doc = _doc_for(run) - # 文件已更新未重新匹配:worker 复核必须拒绝执行。 + # 文件已更新(最新投影 sha=e,行/档仍持旧版本):旧门禁在此整 Run 落败。 patch_source_file_status({"DBS-AWSBI": "e" * 64}) execute_run(run_id=run.id, deps=deps) db.session.expire_all() doc = db.session.get(TransferDocument, doc.id) - assert doc.status == "technical_failed" + # [断言意图] 版本滞后不再拦截:单成功、行成功、ERP 照常写入(写前复查因 + # 账面 500==500 通过)。 + assert doc.status == "success" linked = TransferInvoiceItem.query.filter_by(document_id=doc.id).all() - assert all(item.status == "blocked_recoverable" for item in linked) - assert erp.write_calls() == [] + assert all(item.status == "success" for item in linked) + assert len(erp.write_calls()) == 1 db.session.expire_all() # --------------------------------------------------------------------------- @@ -643,7 +657,7 @@ def test_full_run_passes_stage_callback_and_marks_stage_confirmed( deps, erp = _setup(dbs_ready_file, patch_source_file_status, [ _row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"), ]) - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps) run = TransferRun.query.filter_by(run_no=outcome.run_no).first() doc = _doc_for(run) @@ -669,7 +683,7 @@ def test_retrigger_final_only_does_not_pass_stage_callback( deps, erp = _setup(dbs_ready_file, patch_source_file_status, [ _row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"), ]) - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") first = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps) run = TransferRun.query.filter_by(run_no=first.run_no).first() doc = _doc_for(run) @@ -699,11 +713,12 @@ def test_requeried_rows_reuse_order_without_new_rows( transfer_db, dbs_ready_file, patch_source_file_status, ): """失败单 → 行重查回 ready(run_id 留旧 Run)→ 纯旧行再次提交新 Run: - 归属补齐进新 Run(attempt_no 防双跳)、二次门禁覆盖该行、复用同单、投影非空。""" + 归属补齐进新 Run(attempt_no 防双跳)、复用同单、执行到底、投影非空 + (原「二次门禁覆盖该行」段随文件版本对账门禁退役 2026-10-22 删除)。""" deps, erp = _setup(dbs_ready_file, patch_source_file_status, [ _row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"), ]) - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") first = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps) run1 = TransferRun.query.filter_by(run_no=first.run_no).first() doc = _doc_for(run1) @@ -740,38 +755,17 @@ def test_requeried_rows_reuse_order_without_new_rows( assert reused.submit_timestamp == old_ts assert reused.run_id == run2.id - # [二次门禁覆盖该行] 文件 Hash 失效 → 行被阻断(证明门禁按新 Run 行集复核)。 - patch_source_file_status({"DBS-AWSBI": "e" * 64}) + # [执行完成] 文件版本对账门禁退役(2026-10-22):重查回 ready 的旧行不再被 + # 版本戳拦截,直接执行到底——单/行/Run 同成功族,投影非空。 execute_run(run_id=run2.id, deps=deps) db.session.expire_all() row = db.session.get(TransferInvoiceItem, row.id) reused = db.session.get(TransferDocument, doc.id) run2 = TransferRun.query.filter_by(run_no=run2.run_no).first() - assert row.status == "blocked_recoverable" - assert row.result_code == "file_changed" - # 断言意图:P2-1——executing 单遇门禁失败统一落 technical_failed(不留组锁悬挂), - # Run 终态与单一致(失败族)。 - assert reused.status == "technical_failed" - assert run2.status == "failed" - - # [修复后重跑] 行再次重查回 ready → 新 Run 复用同单全量重跑 → 投影非空。 - patch_source_file_status() - row.status = "ready_to_execute" - row.result_code = None - row.result_message = None - db.session.commit() - third = prepare_execution(item_ids=[row.id], deps=deps) - run3 = TransferRun.query.filter_by(run_no=third.run_no).first() - execute_run(run_id=run3.id, deps=deps) - db.session.expire_all() - run3 = TransferRun.query.filter_by(run_no=run3.run_no).first() - reused = db.session.get(TransferDocument, doc.id) - row = db.session.get(TransferInvoiceItem, row.id) - # 断言意图:终态与投影一致——单/行/Run 同成功族,_build_run_result 投影非空。 assert reused.status == "success" - assert run3.status == "success" + assert run2.status == "success" assert row.status == "success" - restored = get_run_projection(run3.run_no) + restored = get_run_projection(run2.run_no) assert len(restored["result"]["external_documents"]) == 1 assert restored["result"]["exceptions"] == [] db.session.expire_all() @@ -785,18 +779,23 @@ def get_run_projection(run_no: str) -> dict: # --------------------------------------------------------------------------- -# 评审修正 P2-1:executing 单遇二次门禁失败 → technical_failed(不留组锁悬挂) +# 评审修正 P2-1 历史段:executing 单遇门禁失败曾落 technical_failed—— +# 该门禁已随文件版本对账退役(2026-10-22),本用例改为锁定新行为 # --------------------------------------------------------------------------- -def test_recheck_failure_marks_executing_order_technical_failed( +def test_executing_stalled_order_executes_despite_file_version_change( transfer_db, dbs_ready_file, patch_source_file_status, seq_loader, ): - """上次 worker 中途搁浅的 executing 单,本次门禁复核失败 → 单 technical_failed - (可被 D18 关闭释放组锁),行阻断、Run failed、零外部写入。""" + """上次 worker 中途搁浅的 executing 单,文件版本变化后重跑仍正常执行到底。 + + [断言意图] 门禁退役(2026-10-22):executing 搁浅单不再因文件 Hash 复核失败 + 落 technical_failed——逐单执行照常走写前库存复查(账面 500==500 通过), + 单/行/Run 同成功族、ERP 恰一次写入。 + """ deps, erp = _setup(dbs_ready_file, patch_source_file_status, [ _row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"), ]) - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps) run = TransferRun.query.filter_by(run_no=outcome.run_no).first() doc = _doc_for(run) @@ -808,12 +807,11 @@ def test_recheck_failure_marks_executing_order_technical_failed( execute_run(run_id=run.id, deps=deps) db.session.expire_all() doc = db.session.get(TransferDocument, doc.id) - # 断言意图:P2-1——executing 单门禁失败同样落 technical_failed(而非停在 executing)。 - assert doc.status == "technical_failed" - assert doc.error_code == "file_changed" + # [断言意图] 版本变化不再拦截:搁浅单继续执行成功,行 success、ERP 恰一次写入。 + assert doc.status == "success" linked = TransferInvoiceItem.query.filter_by(document_id=doc.id).all() - assert all(item.status == "blocked_recoverable" for item in linked) - assert erp.write_calls() == [] + assert all(item.status == "success" for item in linked) + assert len(erp.write_calls()) == 1 db.session.expire_all() @@ -829,13 +827,13 @@ def test_serialize_run_orders_projects_multi_status_order_list( _row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500", unit="个"), _row("Receipt", 2, "HOX-B", "LOT-20", "MAT-002", "2026-08-04", "700", unit="PCS"), ]) - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps) run = TransferRun.query.filter_by(run_no=outcome.run_no).first() docs = _docs_of(run) assert len(docs) == 2 # 按单号注入写场景:收料日期 08-04 单失败、08-05 单成功(组建单按组键升序)。 - by_date = {doc.receipt_date: doc for doc in docs} + by_date = {doc.movement_date: doc for doc in docs} erp.write_scenarios_by_doc[by_date["2026-08-04"].doc_no] = "business_failed" execute_run(run_id=run.id, deps=deps) @@ -846,13 +844,13 @@ def test_serialize_run_orders_projects_multi_status_order_list( assert len(orders) == 2 # 断言意图:单序稳定(2026-09-29 投影排序=收料日期→数据源→库位,跨数据源 # 不再随建单序乱序;本例同数据源,收料日期升序)。 - assert [t["receipt_date"] for t in orders] == ["2026-08-04", "2026-08-05"] + assert [t["movement_date"] for t in orders] == ["2026-08-04", "2026-08-05"] failed, success = orders # 断言意图:计划 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", + "doc_no", "movement_date", "from_warehouse", "to_warehouse", "status", "erp_document_no", "error_message", "lines", } assert failed["status"] == "business_failed" @@ -882,15 +880,24 @@ def test_order_lines_group_by_external_lot_form(): Why: ERP 行粒度=外部批号身份;WMS 文件批号 WTP 形态对应 ERP 账面 HOW 形态 (2026-09-25 生产实证)。聚合前派生,行下传 lot_no 即外部形态。 """ + # [出生翻转] 批号派生按行所属匹配快照的转换规则(scope_json.transform_rules): + # 构造携带 WTP→HOW 规则的匹配对象并挂到两行(transient 赋值,不触库)。 + matching = TransferMatching( + matching_no="MTG-LOT", business_date="2026-08-07", status="success", + scope_json={"transform_rules": [ + {"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"}, + ]}, + counts_json={}, matching_hash="sha256:lot", + ) item_wtp = TransferInvoiceItem( invoice_no="HOX-900", material_no="MAT-900", lot_no="WTP26060612", from_warehouse="W1", to_warehouse="W2", - receipt_quantity="200", unit="PCS", + movement_quantity="200", unit="PCS", matching=matching, ) item_how = TransferInvoiceItem( invoice_no="HOX-901", material_no="MAT-900", lot_no="HOW26060612", from_warehouse="W1", to_warehouse="W2", - receipt_quantity="50", unit="PCS", + movement_quantity="50", unit="PCS", matching=matching, ) lines = _build_order_lines([item_wtp, item_how]) # [断言意图] WTP/HOW 两形态同属一个 ERP 批次 → 聚合为一行且数量相加, @@ -908,13 +915,21 @@ def test_serialize_order_reason_join_uses_external_lot_form(): _build_order_lines 聚合键必须经同一 external_lot_no 派生,否则 WTP 前缀行投影出空品名/空原因。 """ + matching = TransferMatching( + matching_no="MTG-LOT-2", business_date="2026-08-07", status="success", + scope_json={"transform_rules": [ + {"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"}, + ]}, + counts_json={}, matching_hash="sha256:lot", + ) item = TransferInvoiceItem( invoice_no="HOX-900", material_no="MAT-900", material_name="汇流排", lot_no="WTP26060612", from_warehouse="W1", to_warehouse="W2", - receipt_quantity="200", unit="PCS", result_message="strict quantity mismatch", + movement_quantity="200", unit="PCS", result_message="strict quantity mismatch", + matching=matching, ) doc = SimpleNamespace( - doc_no="DOC-1", receipt_date="2026-08-05", from_warehouse="W1", + doc_no="DOC-1", movement_date="2026-08-05", from_warehouse="W1", to_warehouse="W2", status="failed", erp_document_no=None, error_message=None, ) order = serialize_order(doc, [item]) @@ -922,3 +937,197 @@ def test_serialize_order_reason_join_uses_external_lot_form(): assert line["lot_no"] == "HOW26060612" assert line["material_name"] == "汇流排" assert line["reason"] == "strict quantity mismatch" + + +# --------------------------------------------------------------------------- +# Task 12 档级封存回写(规格 §9 防二次执行):票据成功 → 档 transfer_executed=true +# --------------------------------------------------------------------------- + +def test_order_success_seals_ledger_records( + transfer_db, dbs_ready_file, patch_source_file_status, seq_loader, +): + """执行成功落 ERP 单号时回写 items 关联的档记录:transfer_executed=true + executed_doc_no。""" + deps, erp = _setup(dbs_ready_file, patch_source_file_status, [ + _row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"), + _row("Receipt", 2, "HOM-B", "LOT-20", "MAT-002", "2026-08-05", "700"), + ]) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") + outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps) + run = TransferRun.query.filter_by(run_no=outcome.run_no).first() + doc = _doc_for(run) + record_ids = [ + item.ledger_record_id + for item in TransferInvoiceItem.query.filter_by(document_id=doc.id).all() + if item.ledger_record_id is not None + ] + assert record_ids # 出生翻转后行必挂档 + + execute_run(run_id=run.id, deps=deps) + db.session.expire_all() + erp_no = erp.write_calls()[0].document_no + from app.models import TransferMovementLedger + + sealed = {r.id: r for r in db.session.query(TransferMovementLedger).filter( + TransferMovementLedger.id.in_(record_ids)).all()} + # [断言意图] 档级封存回写:单内行关联的全部档记录封存位=true 且单号=ERP 单号 + # (防二次执行的档级兜底,规格 §9)。 + assert all(sealed[rid].transfer_executed is True for rid in record_ids) + assert {sealed[rid].executed_doc_no for rid in record_ids} == {erp_no} + db.session.expire_all() + + +def test_order_success_seal_is_idempotent_and_stays_sealed_on_duplicate( + transfer_db, dbs_ready_file, patch_source_file_status, seq_loader, +): + """封存回写幂等:重复回写/复用单以 duplicate_success 重跑后封存位恒 true 不报错。""" + deps, erp = _setup(dbs_ready_file, patch_source_file_status, [ + _row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"), + ]) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") + outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps) + run = TransferRun.query.filter_by(run_no=outcome.run_no).first() + doc = _doc_for(run) + execute_run(run_id=run.id, deps=deps) + db.session.expire_all() + doc = db.session.get(TransferDocument, doc.id) + assert doc.status == "success" + + # 幂等回写(同值覆盖不抛错、封存位不变)。 + from app.models import TransferMovementLedger + from app.services.in_transit_transfer.execution_service import _seal_ledger_records + + items = TransferInvoiceItem.query.filter_by(document_id=doc.id).all() + _seal_ledger_records(items, executed_doc_no=doc.erp_document_no) + db.session.commit() + db.session.expire_all() + sealed = db.session.query(TransferMovementLedger).filter( + TransferMovementLedger.id.in_([i.ledger_record_id for i in items if i.ledger_record_id])).all() + assert all(r.transfer_executed is True for r in sealed) + + # [断言意图] 复用单 duplicate_success 重跑:封存位恒 true(封存事实不可逆)。 + run2 = TransferRun.query.filter_by(run_no=outcome.run_no).first() + execute_run(run_id=run2.id, deps=deps) + db.session.expire_all() + sealed = db.session.query(TransferMovementLedger).filter( + TransferMovementLedger.id.in_([i.ledger_record_id for i in items if i.ledger_record_id])).all() + assert all(r.transfer_executed is True for r in sealed) + db.session.expire_all() + + +def test_order_failure_does_not_seal_ledger_records( + transfer_db, dbs_ready_file, patch_source_file_status, seq_loader, +): + """执行失败(business_failed)不封存:记录仍可被圈定/待匹配可见。""" + deps, erp = _setup(dbs_ready_file, patch_source_file_status, [ + _row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"), + ]) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") + items = _ready_items() + outcome = prepare_execution(item_ids=[i.id for i in items], deps=deps) + run = TransferRun.query.filter_by(run_no=outcome.run_no).first() + doc = _doc_for(run) + erp.write_scenarios_by_doc[doc.doc_no] = "business_failed" + + execute_run(run_id=run.id, deps=deps) + db.session.expire_all() + from app.models import TransferMovementLedger + + record_ids = [i.ledger_record_id for i in TransferInvoiceItem.query.filter_by( + document_id=doc.id).all() if i.ledger_record_id is not None] + sealed = db.session.query(TransferMovementLedger).filter( + TransferMovementLedger.id.in_(record_ids)).all() + # [断言意图] 未成事实不封存:失败单的档记录保持可圈定(重跑/重新匹配合法)。 + assert all(r.transfer_executed is False and r.executed_doc_no is None for r in sealed) + db.session.expire_all() + + +def test_file_version_change_no_longer_blocks_execution( + transfer_db, dbs_ready_file, patch_source_file_status, seq_loader, +): + """文件版本对账门禁退役(2026-10-22):档记录 sha 滞后最新文件不再拒绝执行 + (部分导出缺席≠失效);行级 file_current 徽标仍提示滞后,防护下沉写前库存复查。""" + deps, erp = _setup(dbs_ready_file, patch_source_file_status, [ + _row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"), + ]) + summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") + item = _ready_items()[0] + from app.models import TransferMovementLedger + + record = db.session.get(TransferMovementLedger, item.ledger_record_id) + + # 档记录滞后最新文件(记录 e,最新投影 f):旧门禁在此抛 TRANSFER.FILE_CHANGED。 + record.file_sha256 = "e" * 64 + db.session.commit() + patch_source_file_status({"DBS-AWSBI": "f" * 64}) + outcome = prepare_execution(item_ids=[item.id], deps=deps) + assert outcome.run_no # [断言意图] 版本滞后不再拒绝执行(不回退旧门禁) + + run = TransferRun.query.filter_by(run_no=outcome.run_no).first() + execute_run(run_id=run.id, deps=deps) + db.session.expire_all() + item = db.session.get(TransferInvoiceItem, item.id) + assert item.status == "success" # 写前复查(账面 500==500)通过后正常写 ERP + + # [断言意图] 行级「文件已更新」徽标仍提示滞后(提示不拦截,与门禁退役配套)。 + restored = restore_matching(summary.matching_id, deps=deps) + restored_item = next(i for i in restored["items"] if i.invoice_no == "HOM-A") + assert restored_item.file_current is False + + +def test_file_current_badge_uses_outbound_evidence_for_outbound_rows( + transfer_db, monkeypatch, seq_loader, +): + """出站档行的 file_current 徽标按出站文件 sha 计算,不拿入站投影比较。 + + 核心逻辑:同一来源入站投影 sha 与出站不同。出站档 file_sha256 等于出站投影 + → 徽标 file_current=True(执行门禁已退役 2026-10-22,本用例只锁徽标口径; + 若徽标误用入站投影,file_current 为假)。 + """ + del seq_loader # 夹具注入单号序列;本用例只确认门禁放行。 + out_sha = "o" * 64 + in_sha = "i" * 64 + + def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict: + """入站与出站返回不同 sha,用来区分门禁读了哪一条流。""" + del source_code + sha = out_sha if record_kind == "outbound" else in_sha + return { + "file_status": "ready", "has_ready_file": True, + "file_no": f"{record_kind}-file", "file_sha256": sha, + } + + monkeypatch.setattr( + "app.services.in_transit_transfer.matching_service.resolve_source_file_status", + _resolve, + ) + monkeypatch.setattr( + "app.services.in_transit_transfer.execution_service.resolve_source_file_status", + _resolve, + ) + deps, erp, _rpa = make_transfer_deps() + erp.seed_stock("MAT-OUT", "DBS-TRANSIT", "LOT-OUT", "100") + db.session.add(TransferMovementLedger( + source_code="DBS-AWSBI", record_kind="outbound", + doc_no="HOX-OUT", line_no="1", line_seq="", in_out_flag="", + material_code="MAT-OUT", material_name="出站物料", specification="", + lot_no="LOT-OUT", quantity="100", unit="PCS", + warehouse_code="", storage_code="", movement_date="2026-08-05", + source_file_id=None, file_version="v1", file_sha256=out_sha, + sheet_name="Shipment", row_no=1, updated_at=datetime.utcnow(), + transfer_executed=False, + )) + db.session.commit() + summary = create_matching( + source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, + transfer_type="in_transit_to_hub", + ) + restored = restore_matching(summary.matching_id, deps=deps) + row = next(item for item in restored["items"] if item.invoice_no == "HOX-OUT") + # [断言意图] 入站 sha 与档不同;file_current 仍为真,说明比的是出站证据文件。 + assert row.file_current is True + item = TransferInvoiceItem.query.filter_by(invoice_no="HOX-OUT").one() + assert item.ledger_record.record_kind == "outbound" + assert item.status == "ready_to_execute" + outcome = prepare_execution(item_ids=[item.id], deps=deps) + # [断言意图] 执行照常提交(门禁已退役,本行仅确认链路完好)。 + assert outcome.run_no diff --git a/backend/tests/services/in_transit_transfer/test_field_transforms.py b/backend/tests/services/in_transit_transfer/test_field_transforms.py new file mode 100644 index 00000000..e7834dab --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_field_transforms.py @@ -0,0 +1,51 @@ +"""字段转换引擎契约:前缀替换链式生效、字段白名单、原值不篡改(返回新值)。 + +用途:锁定 field_transforms 引擎对外契约——TRANSFORM_FIELDS/TRANSFORM_OPS 白名单 + 校验(错误码 TRANSFER.TRANSFORM_RULE_INVALID)、apply 按序链式派生与 + None/空串透传;Task 11(六边界点接线)与 Task 5/6(校验与 UI)消费本契约。 +依赖:app.core.errors.ValidationError、field_transforms 引擎。 +逻辑:纯函数测试(pure_unit),不创建 Flask/DB;仅断言内存派生行为, + 不触碰调拨类型模型与匹配快照(那些由各自任务的契约测试覆盖)。 +""" + +from __future__ import annotations + +import pytest +from app.core.errors import ValidationError +from app.services.in_transit_transfer.field_transforms import ( + apply_field_transforms, parse_transform_rules, +) + +pytestmark = pytest.mark.pure_unit + + +RULES = parse_transform_rules([ + {"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"}, +]) + + +def test_prefix_replace(): + """命中前缀派生新值;未命中前缀恒等返回原值。""" + assert apply_field_transforms("lot_no", "WTP26062302", RULES) == "HOW26062302" # WTP→HOW 替换 + assert apply_field_transforms("lot_no", "ABC123", RULES) == "ABC123" # 非 WTP 前缀不替换 + + +def test_none_and_empty_passthrough(): + """None 与空串原样透传,不做替换(防 NoneType.startswith 崩溃)。""" + assert apply_field_transforms("lot_no", None, RULES) is None + assert apply_field_transforms("lot_no", "", RULES) == "" + + +def test_chained_rules_apply_in_order(): + """多条规则按配置序链式生效:WTP→HOW 后再 HOW→HOWX。""" + rules = parse_transform_rules([ + {"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"}, + {"field": "lot_no", "op": "prefix_replace", "source": "HOW", "target": "HOWX"}, + ]) + assert apply_field_transforms("lot_no", "WTP1", rules) == "HOWX1" # 两条规则先后各命中一次 + + +def test_field_whitelist(): + """字段不在 TRANSFORM_FIELDS 白名单必须拒绝(校验在 parse 期,非 apply 期)。""" + with pytest.raises(ValidationError): + parse_transform_rules([{"field": "quantity", "op": "prefix_replace", "source": "A", "target": "B"}]) diff --git a/backend/tests/services/in_transit_transfer/test_file_preparation.py b/backend/tests/services/in_transit_transfer/test_file_preparation.py index a48becc4..b3f7cf35 100644 --- a/backend/tests/services/in_transit_transfer/test_file_preparation.py +++ b/backend/tests/services/in_transit_transfer/test_file_preparation.py @@ -12,16 +12,16 @@ import pytest from app.services.in_transit_transfer.file_preparation import ( FilePreparationResult, - ReadyReceiptFile, - ReceiptFileRepository, - ensure_receipt_file_ready, + ReadyInboundFile, + InboundFileRepository, + ensure_inbound_file_ready, ) from tests.services.in_transit_transfer.fakes import FakeRPA -from tests.services.in_transit_transfer.repo_fakes import FakeReceiptFileRepository +from tests.services.in_transit_transfer.repo_fakes import FakeInboundFileRepository -def _ready_file(source_code: str = "DBS-AWSBI", *, business_date: str = "2026-08-06") -> ReadyReceiptFile: - return ReadyReceiptFile( +def _ready_file(source_code: str = "DBS-AWSBI", *, business_date: str = "2026-08-06") -> ReadyInboundFile: + return ReadyInboundFile( source_code=source_code, business_date=business_date, file_no=f"REC-{source_code}-001", @@ -33,9 +33,9 @@ def _ready_file(source_code: str = "DBS-AWSBI", *, business_date: str = "2026-08 def test_ready_file_reused_without_rpa_trigger(): """当日 ready 文件存在 → 复用(stage=file_ready),不触发 RPA。""" - repository = FakeReceiptFileRepository({("DBS-AWSBI", "2026-08-06"): _ready_file()}) + repository = FakeInboundFileRepository({("DBS-AWSBI", "2026-08-06"): _ready_file()}) rpa = FakeRPA() - result = ensure_receipt_file_ready( + result = ensure_inbound_file_ready( source_code="DBS-AWSBI", business_date="2026-08-06", repository=repository, rpa_trigger=rpa, ) @@ -46,9 +46,9 @@ def test_ready_file_reused_without_rpa_trigger(): def test_missing_file_triggers_rpa_once(): """缺文件 → 触发 RPA 一次并进入 waiting_rpa_callback。""" - repository = FakeReceiptFileRepository() + repository = FakeInboundFileRepository() rpa = FakeRPA() - result = ensure_receipt_file_ready( + result = ensure_inbound_file_ready( source_code="DBS-AWSBI", business_date="2026-08-06", repository=repository, rpa_trigger=rpa, ) @@ -60,9 +60,9 @@ def test_missing_file_triggers_rpa_once(): def test_active_source_job_binds_existing_task_no_new_trigger(): """存在活动 Source Job → 绑定已有任务,不重复触发 RPA。""" - repository = FakeReceiptFileRepository() + repository = FakeInboundFileRepository() rpa = FakeRPA() - result = ensure_receipt_file_ready( + result = ensure_inbound_file_ready( source_code="DBS-AWSBI", business_date="2026-08-06", repository=repository, rpa_trigger=rpa, active_source_job_key="RUN-1/DBS-AWSBI", ) @@ -72,10 +72,10 @@ def test_active_source_job_binds_existing_task_no_new_trigger(): def test_concurrent_requests_share_one_trigger(): """并发请求携带同一活动键 → 全部绑定已有任务,不重复触发 RPA。""" - repository = FakeReceiptFileRepository() + repository = FakeInboundFileRepository() rpa = FakeRPA() for _ in range(3): - result = ensure_receipt_file_ready( + result = ensure_inbound_file_ready( source_code="DBS-AWSBI", business_date="2026-08-06", repository=repository, rpa_trigger=rpa, active_source_job_key="RUN-1/DBS-AWSBI", ) @@ -85,13 +85,13 @@ def test_concurrent_requests_share_one_trigger(): def test_without_active_key_each_call_triggers_once(): """无活动键时每次调用各触发一次;幂等由调用方 SourceJob 唯一键兜底。""" - repository = FakeReceiptFileRepository() + repository = FakeInboundFileRepository() rpa = FakeRPA() - ensure_receipt_file_ready( + ensure_inbound_file_ready( source_code="DBS-AWSBI", business_date="2026-08-06", repository=repository, rpa_trigger=rpa, ) - ensure_receipt_file_ready( + ensure_inbound_file_ready( source_code="DBS-AWSBI", business_date="2026-08-06", repository=repository, rpa_trigger=rpa, ) @@ -100,10 +100,10 @@ def test_without_active_key_each_call_triggers_once(): def test_rpa_trigger_failure_is_fail_closed(): """RPA 触发失败 → stage=failed 且带错误码,不误报 file_ready。""" - repository = FakeReceiptFileRepository() + repository = FakeInboundFileRepository() rpa = FakeRPA() rpa.fail_on.add("DBS-AWSBI") - result = ensure_receipt_file_ready( + result = ensure_inbound_file_ready( source_code="DBS-AWSBI", business_date="2026-08-06", repository=repository, rpa_trigger=rpa, ) @@ -113,14 +113,14 @@ def test_rpa_trigger_failure_is_fail_closed(): def test_dbs_and_crane_sources_isolated(): """DBS 失败不影响 Crane 的文件准备(来源隔离)。""" - repository = FakeReceiptFileRepository({("CRANE-SZ", "2026-08-06"): _ready_file("CRANE-SZ")}) + repository = FakeInboundFileRepository({("CRANE-SZ", "2026-08-06"): _ready_file("CRANE-SZ")}) rpa = FakeRPA() rpa.fail_on.add("DBS-AWSBI") - dbs_result = ensure_receipt_file_ready( + dbs_result = ensure_inbound_file_ready( source_code="DBS-AWSBI", business_date="2026-08-06", repository=repository, rpa_trigger=rpa, ) - crane_result = ensure_receipt_file_ready( + crane_result = ensure_inbound_file_ready( source_code="CRANE-SZ", business_date="2026-08-06", repository=repository, rpa_trigger=rpa, ) diff --git a/backend/tests/services/in_transit_transfer/test_receipt_callback_bridge.py b/backend/tests/services/in_transit_transfer/test_inbound_callback_bridge.py similarity index 89% rename from backend/tests/services/in_transit_transfer/test_receipt_callback_bridge.py rename to backend/tests/services/in_transit_transfer/test_inbound_callback_bridge.py index 7800cb60..77f8405b 100644 --- a/backend/tests/services/in_transit_transfer/test_receipt_callback_bridge.py +++ b/backend/tests/services/in_transit_transfer/test_inbound_callback_bridge.py @@ -12,8 +12,8 @@ from datetime import datetime, timedelta from app import db from app.models import TransferSourceJob, TransferRun -from app.services.in_transit_transfer.receipt_callback_bridge import ( - advance_source_job_from_receipt_callback, +from app.services.in_transit_transfer.inbound_callback_bridge import ( + advance_source_job_from_inbound_callback, ) @@ -31,7 +31,7 @@ def _make_waiting_job(run_no: str, source_code: str = "DSV360_AWSDU") -> Transfe def test_success_callback_advances_job_to_file_ready(app): """成功回调(含文件号/sha256)应把最新等待任务推进为 file_ready。""" job = _make_waiting_job("RUN-BRIDGE-1") - advanced = advance_source_job_from_receipt_callback( + advanced = advance_source_job_from_inbound_callback( source_code=job.source_code, file_no="42", file_sha256="abc", callback_ok=True, ) assert advanced is not None and advanced.status == "file_ready" @@ -41,7 +41,7 @@ def test_success_callback_advances_job_to_file_ready(app): def test_recover_stale_waiting_source_jobs(app): """超过收料回调超时的等待任务回收为 failed;新任务不动。""" - from app.services.in_transit_transfer.receipt_callback_bridge import recover_stale_waiting_source_jobs + from app.services.in_transit_transfer.inbound_callback_bridge import recover_stale_waiting_source_jobs stale = _make_waiting_job("RUN-BRIDGE-STALE-1", "DSV360_AWSDU") stale.updated_at = datetime.utcnow() - timedelta(seconds=3600) @@ -51,5 +51,5 @@ def test_recover_stale_waiting_source_jobs(app): db.session.expire_all() assert recovered == 1 assert db.session.get(TransferSourceJob, stale.id).status == "failed" - assert db.session.get(TransferSourceJob, stale.id).error_code == "RPA_RECEIPT_CALLBACK_TIMEOUT" + assert db.session.get(TransferSourceJob, stale.id).error_code == "RPA_INBOUND_CALLBACK_TIMEOUT" assert db.session.get(TransferSourceJob, fresh.id).status == "waiting_rpa_callback" diff --git a/backend/tests/services/in_transit_transfer/test_inbound_file_parser.py b/backend/tests/services/in_transit_transfer/test_inbound_file_parser.py new file mode 100644 index 00000000..b98497f3 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_inbound_file_parser.py @@ -0,0 +1,175 @@ +"""在途调拨异动文件字段/结构校验测试(L0 纯单元)。 + +用途:验证必填列缺失、空值、非法数量(0/负数/非数字)、非法日期与 + 来源身份不一致均整行阻断并抛出 MovementFileSchemaError。 +依赖:app.services.in_transit_transfer.file_parser(纯函数)。 +逻辑:解析不接触文件存储;所有错误带行号细节,供预检页展示原因。 + tt14 入站化后统一走 movement 契约行(parse_movement_rows 单一入口), + 本文件聚焦「原始行 → 调拨语义字段」投影后的校验行为(与 + test_movement_parser 的契约映射用例互补)。 +""" + +from __future__ import annotations + +from datetime import date +from decimal import Decimal + +import pytest + +from app.services.in_transit_transfer.file_parser import ( + MovementFileSchemaError, + ParsedMovementRow, + parse_movement_rows, +) + +pytestmark = pytest.mark.pure_unit + +VALID_ROW = { + "sheet": "Movement", + "row_no": 10, + "doc_no": "INV-001", + "material_code": "MAT-001", + "material_name": "连接器组件", + "specification": "A 型 / 24PIN", + "movement_date": "2026-08-05", + "quantity": "500", + "source_code": "DBS-AWSBI", +} + + +def _rows(**overrides) -> list[dict]: + """以 VALID_ROW 为基底覆盖字段构造测试行。""" + base = dict(VALID_ROW) + base.update(overrides) + return [base] + + +def test_valid_rows_parse(): + """合法行解析出全部字段(数量 Decimal、日期 date)。""" + parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows()) + assert len(parsed) == 1 + row = parsed[0] + assert isinstance(row, ParsedMovementRow) + assert row.invoice_no == "INV-001" + assert row.material_no == "MAT-001" + assert row.material_name == "连接器组件" + assert row.specification == "A 型 / 24PIN" + assert row.movement_date == date(2026, 8, 5) + assert row.movement_quantity == Decimal("500") + assert row.sheet == "Movement" + assert row.row_no == 10 + + +def test_missing_invoice_no_rejected(): + """单号(doc_no)缺失必须整行阻断(管控保留:配置错列由解析失败暴露)。""" + with pytest.raises(MovementFileSchemaError): + parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(doc_no="")) + + +def test_missing_material_no_row_skipped_not_blocked(): + """料号空行=非可用异动行:静默跳过——不管控、不进异动表(2026-10-21 实测反转)。 + + Why: CRANE/Lognet 出站报告携带说明行/占位行(料号为空),旧逻辑按 + missing_material_no 整文件阻断致出站解析失败;此类行不是可用异动事实, + 跳过语义与零数量行同家族(_is_unusable_movement_row)。 + """ + parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(material_code="")) + assert parsed == [] + + +def test_empty_material_rows_mixed_with_valid_rows_only_valid_parsed(): + """料号空行与合法行混排:只放行有料号的行,空料号行不阻断整文件。""" + rows = [ + dict(VALID_ROW, row_no=2, material_code=""), # 说明/占位行:跳过 + dict(VALID_ROW, row_no=3, material_code="MAT-002", doc_no="INV-002"), + ] + parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=rows) + assert [row.row_no for row in parsed] == [3] + + +def test_material_and_invoice_both_empty_row_skipped(): + """料号与单号双空行按料号空行处理:静默跳过而非 missing_invoice_no 阻断。""" + parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(doc_no="", material_code="")) + assert parsed == [] + + +def test_invalid_quantity_rejected(): + """非数字数量必须阻断。""" + with pytest.raises(MovementFileSchemaError): + parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(quantity="abc")) + + +def test_zero_quantity_stamped_row_skipped(): + """零数量异动行(日期已盖章、数量 0)为非可用异动事实:跳过不阻断(2026-10-08 CRANE WTP26082227 实测)。""" + parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(quantity="0")) + assert parsed == [] + + +def test_zero_quantity_rows_mixed_with_valid_rows_only_valid_parsed(): + """合法行与零数量行混排:只放行合法行,零数量行不阻断整文件。""" + rows = [ + dict(VALID_ROW, row_no=788, doc_no="WTP26082227", quantity="0", + movement_date="2026-10-01 14:37:43"), + dict(VALID_ROW, row_no=789, doc_no="INV-002", quantity="120"), + ] + parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=rows) + assert [row.row_no for row in parsed] == [789] + assert parsed[0].invoice_no == "INV-002" + + +def test_negative_quantity_rejected(): + """负数数量必须阻断。""" + with pytest.raises(MovementFileSchemaError): + parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(quantity="-5")) + + +def test_invalid_date_rejected(): + """非法日期必须阻断。""" + with pytest.raises(MovementFileSchemaError): + parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(movement_date="2026/13/99")) + + +def test_source_identity_mismatch_rejected(): + """行内来源与任务来源不一致(Callback 身份漂移)必须阻断。""" + with pytest.raises(MovementFileSchemaError): + parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(source_code="CRANE-SZ")) + + +def test_missing_sheet_or_row_no_rejected(): + """Sheet/原始行号缺失无法追溯,必须阻断。""" + with pytest.raises(MovementFileSchemaError): + parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(sheet="", row_no=0)) + + +def test_material_name_and_specification_optional(): + """品名/规格允许为空(后续由明细 DTO 展示空值)。""" + parsed = parse_movement_rows( + source_code="DBS-AWSBI", + rows=_rows(material_name="", specification=""), + ) + assert parsed[0].material_name == "" + assert parsed[0].specification == "" + + +def test_error_carries_row_details(): + """错误细节必须携带行号与原因,供页面定位。""" + with pytest.raises(MovementFileSchemaError) as excinfo: + parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(row_no=77, quantity="abc")) + details = excinfo.value.details + assert any(str(item.get("row_no")) == "77" for item in details.get("rows", [])) + + +def test_schema_error_message_carries_row_details(): + """诊断落库:schema 失败消息必须携带前几条行级明细(行号+原因),随 parse_error_message 落库自描述。""" + rows = [ + dict(VALID_ROW, row_no=5, doc_no=""), + dict(VALID_ROW, row_no=9, quantity="abc"), + ] + with pytest.raises(MovementFileSchemaError) as exc_info: + parse_movement_rows(source_code="DBS-AWSBI", rows=rows) + # [断言意图] 消息不再只是通用 "movement file schema invalid",须含行号与原因; + # 明细同时保留在 details.rows 供管理端展示。 + text = str(exc_info.value) or (exc_info.value.message or "") + assert "row 5" in text and "missing_invoice_no" in text + detail_rows = (exc_info.value.details or {}).get("rows") or [] + assert {"row_no": 5, "reason": "missing_invoice_no"} in detail_rows diff --git a/backend/tests/services/in_transit_transfer/test_inbound_report_handler.py b/backend/tests/services/in_transit_transfer/test_inbound_report_handler.py new file mode 100644 index 00000000..c0e4e9d1 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_inbound_report_handler.py @@ -0,0 +1,320 @@ +"""tests/services/in_transit_transfer/test_inbound_report_handler.py + +用途:阶段 B Task 7——inbound 报表事实处理函数(handle_inbound_report)的契约测试: + 未注册不推进、处理函数先失败后成功只推进一次且文件只留一行、无等待任务时回调成功、 + 同来源两单元分属两排程 run 时收口只打「本次回调收尾的单元」的 run(修复轮)。 +依赖:app(SQLite)fixture、freight_rpa.reports.dispatch(注册表)、 + freight_rpa.inbound.report_archive.ingest_inbound_callback(归档+投递入口)、 + in_transit_transfer.inbound_callback_bridge / TransferSourceJob(调拨侧事实)。 +逻辑:复刻 test_report_fact_dispatch 的注册表隔离与归档 IO 替身——组合根 + (create_app→register_inbound_sinks)启动即注册 handle_inbound_report, + 未注册用例必须先清空注册表,否则 404 断言假绿;success 归档走替身 IO + (drop 根读取返回注入字节、MinIO 上传 no-op),不依赖真实文件系统; + 收口定位用例构造两个 awaiting 排程 run(各挂一个同来源单元), + 对旧单元回调后断言只有旧 run 被收口、新 run 保持等待。 +""" + +from __future__ import annotations + +import hashlib + +import pytest + + +@pytest.fixture +def db_session(app): + """复用 app 夹具已建立的应用上下文会话,供测试直接落库与查询。""" + from app import db + + return db.session + + +@pytest.fixture(autouse=True) +def _reset_report_handlers(): + """每用例隔离 dispatch 注册表(模块级全局字典),避免用例间处理函数串扰。 + + [断言意图] 未注册用例必须跑在"干净注册表"上——组合根启动已注册 + handle_inbound_report,不清空会让 FREIGHT_RPA.SINK_NOT_REGISTERED 断言假绿。 + """ + from app.services.freight_rpa.reports import dispatch as dispatch_module + + saved = dict(dispatch_module._REPORT_HANDLERS) + dispatch_module._REPORT_HANDLERS.clear() + yield + dispatch_module._REPORT_HANDLERS.clear() + dispatch_module._REPORT_HANDLERS.update(saved) + + +@pytest.fixture(autouse=True) +def _fake_archive_io(monkeypatch): + """替身归档 IO:drop 根读取返回注入字节,MinIO 上传 no-op。 + + 核心逻辑:与 test_report_fact_dispatch 同一 monkeypatch 姿态(patch + report_archive 模块属性),使 success 归档分支脱离真实文件系统与对象存储。 + """ + from app.services.freight_rpa.inbound import report_archive + + monkeypatch.setattr(report_archive, "_read_inbound_callback_file", lambda _path: b"handler-bytes") + monkeypatch.setattr( + "app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes", + lambda **_kwargs: None, + ) + + +# callback_id 唯一约束的测试序号(跨用例递增,避免 unique 冲突)。 +_CALLBACK_SEQ: dict[str, int] = {"n": 0} + + +def _next_callback_id() -> str: + """生成跨用例唯一的 callback_id(unit run 唯一约束)。""" + _CALLBACK_SEQ["n"] += 1 + return f"inbound-handler-{_CALLBACK_SEQ['n']}" + + +def _waiting_job(source_code: str): + """构造一个未落库的 waiting_rpa_callback 来源任务(先建 TransferRun 满足外键)。 + + 核心逻辑:TransferRun 只 add+flush(拿 run_id);TransferSourceJob 由调用方 + add+commit——与用例体里的 db_session.add(job) 契约一致。 + """ + from app import db + from app.models import TransferRun, TransferSourceJob + + run = TransferRun( + run_no=f"RUN-HANDLER-{_next_callback_id()}", + business_date="2026-09-17", + status="preparing_files", + trigger_type="manual", + ) + db.session.add(run) + db.session.flush() + return TransferSourceJob(run_id=run.id, source_code=source_code, status="waiting_rpa_callback") + + +def _success_payload_for(source_code: str) -> dict: + """构造一个挂种子站点的 awaiting 单元及其 success 回调载荷(可通过 schema 校验)。 + + 核心逻辑:source_code 列允许测试值(如 "DSV",与调拨任务匹配),source_id + 外键挂 conftest 种子站点 DSV360_AWSDU;替身 IO 注入字节与 sha256 对齐。 + """ + from app import db + from app.models import FreightRpaInboundUnitRun, FreightRpaSource + + anchor = FreightRpaSource.query.filter_by(source_code="DSV360_AWSDU").one() + unit = FreightRpaInboundUnitRun( + source_id=anchor.id, + source_code=source_code, + connector_type="dbs", + callback_id=_next_callback_id(), + status="awaiting_rpa", + config_snapshot_json={}, + ) + db.session.add(unit) + db.session.commit() + data = b"handler-bytes" + return { + "schema_version": "freight_rpa.inbound.v1", + "callback_id": unit.callback_id, + "status": "success", + "file_path": f"receipt_{unit.id}.xlsx", + "original_filename": "receipt.xlsx", + "sha256": hashlib.sha256(data).hexdigest(), + } + + +def test_unregistered_transfer_handler_leaves_job_waiting(app, db_session): + """未注册处理函数:归档 404 后调拨任务必须原地保持 waiting_rpa_callback。""" + from app.core.errors import AppError + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback + + job = _waiting_job(source_code="DSV") + db_session.add(job) + db_session.commit() + # 不注册 handle_inbound_report + with pytest.raises(AppError) as exc: + ingest_inbound_callback(_success_payload_for("DSV")) + assert exc.value.code == "FREIGHT_RPA.SINK_NOT_REGISTERED" + db_session.refresh(job) + assert job.status == "waiting_rpa_callback" + + +def test_handler_fail_then_success_advances_once(app, db_session, monkeypatch): + """处理函数先失败后成功:文件只留一行,调拨任务只推进一次到 file_ready。""" + from app.models import FreightRpaInboundReportFile + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.freight_rpa.reports.facts import ReportFact + from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report + + job = _waiting_job(source_code="DSV") + db_session.add(job) + db_session.commit() + calls = {"n": 0} + + def flaky(fact: ReportFact) -> None: + calls["n"] += 1 + if calls["n"] == 1: + raise RuntimeError("once") + handle_inbound_report(fact) + + register_report_handler("inbound", flaky) + payload = _success_payload_for("DSV") + with pytest.raises(RuntimeError): + ingest_inbound_callback(payload) + ingest_inbound_callback(payload) + db_session.refresh(job) + assert job.status == "file_ready" + assert FreightRpaInboundReportFile.query.count() == 1 + + +def test_no_waiting_job_is_success(app, db_session): + """无等待中的调拨任务:处理函数照常成功返回,且不产生任何调拨来源任务行。""" + from app.models import TransferSourceJob + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report + + register_report_handler("inbound", handle_inbound_report) + ingest_inbound_callback(_success_payload_for("DSV")) + assert TransferSourceJob.query.filter_by(source_code="DSV").count() == 0 + + +def _awaiting_schedule_run(db_session, *, schedule_no: str, run_no: str, awaiting: bool = True): + """构造一个收料排程 task/run 对;awaiting=True 时挂 awaiting_inbound_rpa 等待态。""" + from app.models import ScheduleRun, ScheduleTask + + task = ScheduleTask( + schedule_no=schedule_no, name=f'Receipt {schedule_no}', schedule_type='platform_job', + platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *', + ) + db_session.add(task) + db_session.flush() + run = ScheduleRun( + run_no=run_no, schedule_task_id=task.id, status='running', total_count=1, + success_count=0, failed_count=0, skipped_count=0, + response_summary_json={'awaiting_inbound_rpa': awaiting}, + ) + db_session.add(run) + db_session.commit() + return run + + +def _unit_on_run(db_session, run, *, callback_id: str): + """在指定排程 run 下造一个挂种子站点的 awaiting 收料单元(source_code=DSV)。""" + from app.models import FreightRpaInboundUnitRun, FreightRpaSource + + anchor = FreightRpaSource.query.filter_by(source_code="DSV360_AWSDU").one() + unit = FreightRpaInboundUnitRun( + schedule_run_id=run.id, source_id=anchor.id, source_code="DSV", + connector_type="dbs", callback_id=callback_id, + status="awaiting_rpa", config_snapshot_json={}, + ) + db_session.add(unit) + db_session.commit() + return unit + + +def test_finalize_targets_unit_of_this_callback_not_newest_unit(app, db_session, monkeypatch): + """同来源两个单元分属两个排程 run:本回调收尾的单元(按文件反查)只收口它自己的 run。 + + [断言意图] 修复「按来源取最新单元」的错位:旧逻辑会把收口打到更新单元的 run, + 本回调刚完成的 run 永久滞留 awaiting_inbound_rpa。 + """ + from app.models import ScheduleRun + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report + + monkeypatch.setattr( + "app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file", + lambda _path: b"handler-bytes", + ) + monkeypatch.setattr( + "app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes", + lambda **_kwargs: None, + ) + register_report_handler("inbound", handle_inbound_report) + + run_old = _awaiting_schedule_run(db_session, schedule_no="SCH-ONHAND-OLD", run_no="RUN-ONHAND-OLD") + run_new = _awaiting_schedule_run(db_session, schedule_no="SCH-ONHAND-NEW", run_no="RUN-ONHAND-NEW") + unit_old = _unit_on_run(db_session, run_old, callback_id="inbound-handler-old") + _unit_on_run(db_session, run_new, callback_id="inbound-handler-new") + + ingest_inbound_callback({ + "schema_version": "freight_rpa.inbound.v1", + "callback_id": unit_old.callback_id, + "status": "success", + "file_path": "receipt_old.xlsx", + "original_filename": "receipt.xlsx", + "sha256": hashlib.sha256(b"handler-bytes").hexdigest(), + }) + + db_session.rollback() + db_session.expire_all() + # [断言意图] 本回调收尾的是旧单元:只有旧 run 被收口(全终态 → success)。 + refreshed_old = db_session.get(ScheduleRun, run_old.id) + assert refreshed_old.status == "success" + assert not (refreshed_old.response_summary_json or {}).get("awaiting_inbound_rpa") + # 新单元的 run 原样保持等待态——未被本次回调误收口。 + refreshed_new = db_session.get(ScheduleRun, run_new.id) + assert refreshed_new.status == "running" + assert (refreshed_new.response_summary_json or {}).get("awaiting_inbound_rpa") is True + + +def test_finalize_targets_failed_unit_of_this_callback_not_newest_unit(app, db_session, monkeypatch): + """同来源两单元、同失败错误文本、分属两 run:失败回调只收口本单元(unit_run_id)的 run。 + + [断言意图] 修复「按来源+终态+错误文本取最新单元」的错位:错误文本碰撞时旧回调 + 会收口新单元的 run,本回调刚失败的 run 永久滞留 awaiting_inbound_rpa。 + """ + from datetime import datetime + + from app.models import ScheduleRun, FreightRpaInboundUnitRun + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report + + monkeypatch.setattr( + "app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file", + lambda _path: b"handler-bytes", + ) + monkeypatch.setattr( + "app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes", + lambda **_kwargs: None, + ) + register_report_handler("inbound", handle_inbound_report) + + run_old = _awaiting_schedule_run(db_session, schedule_no="SCH-FAIL-OLD", run_no="RUN-FAIL-OLD") + run_new = _awaiting_schedule_run(db_session, schedule_no="SCH-FAIL-NEW", run_no="RUN-FAIL-NEW") + unit_old = _unit_on_run(db_session, run_old, callback_id="inbound-handler-fail-old") + unit_new = _unit_on_run(db_session, run_new, callback_id="inbound-handler-fail-new") + # [RED 场景] 新单元已先以同错误文本终态失败落库——旧逻辑按 (来源, 终态, 错误文本) + # 取最新单元会命中新单元,把收口打到新 run。 + unit_new.status = "failed" + unit_new.error_code = "RPA_TEST_FAIL" + unit_new.error_message = "boom" + unit_new.finished_at = datetime.utcnow() + db_session.commit() + + result = ingest_inbound_callback({ + "schema_version": "freight_rpa.inbound.v1", + "callback_id": unit_old.callback_id, + "status": "failed", + "error_code": "RPA_TEST_FAIL", + "error_message": "boom", + }) + assert result["status"] == "failed" + + db_session.rollback() + db_session.expire_all() + # [断言意图] 只有旧单元的 run 被收口(唯一单元终态失败 → failed、awaiting 清除)。 + refreshed_old = db_session.get(ScheduleRun, run_old.id) + assert refreshed_old.status == "failed" + assert not (refreshed_old.response_summary_json or {}).get("awaiting_inbound_rpa") + refreshed_saved_old = db_session.get(FreightRpaInboundUnitRun, unit_old.id) + assert refreshed_saved_old.status == "failed" + assert refreshed_saved_old.error_code == "RPA_TEST_FAIL" + # 新单元的 run 原样保持等待态——未被本次回调误收口(新单元自身终态由其回调收口)。 + refreshed_new = db_session.get(ScheduleRun, run_new.id) + assert refreshed_new.status == "running" + assert (refreshed_new.response_summary_json or {}).get("awaiting_inbound_rpa") is True diff --git a/backend/tests/services/in_transit_transfer/test_inbound_report_read_boundary.py b/backend/tests/services/in_transit_transfer/test_inbound_report_read_boundary.py new file mode 100644 index 00000000..fd16c84a --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_inbound_report_read_boundary.py @@ -0,0 +1,36 @@ +"""tests/services/in_transit_transfer/test_inbound_report_read_boundary.py + +用途:锁定阶段 B Task 4——in_transit_transfer 包不得引用 freight_rpa 报表模型 + (站点与报表文件/配置的读取一律改走 app.services.freight_rpa.reports + 只读入口,业务方只按 source_code / file_id 消费)。 +依赖:pathlib(纯文本扫描;无 app/DB fixture,秒级运行)。 +逻辑:对包内全部 .py 逐文件做 banned 字符串扫描(含注释/docstring——模型名 + 出现在任何位置都算引用面),命中即 fail 并按「文件名: 模型名」逐条列出, + 防止调拨域绕过只读入口直接 import 报表模型造成域间漂移。 +""" + +from __future__ import annotations + +from pathlib import Path + + +def test_in_transit_does_not_import_rpa_report_models(): + """in_transit_transfer 包内任何 .py 不得出现 freight_rpa 报表模型名。 + + banned 集合与计划 Task 4 冻结一致:入站归档文件、入站报表配置、库存站点、 + 在手报表配置四类模型自本任务起归 freight_rpa 域读写;调拨域(含注释与 + docstring)不得再引用其类名——命中即边界破坏,须收敛到 + freight_rpa.reports.queries 的只读函数。 + """ + root = Path(__file__).resolve().parents[3] / "app" / "services" / "in_transit_transfer" + banned = ("FreightRpaInboundReportFile", "FreightRpaInboundReportConfig", + "FreightRpaSource", "FreightRpaOnhandReportConfig") + hits = [] + for path in root.rglob("*.py"): + text = path.read_text(encoding="utf-8") + for name in banned: + if name in text: + hits.append(f"{path.name}: {name}") + # [断言意图] hits 必须为空:任一命中都意味着调拨域仍在直接引用 + # freight_rpa 报表模型(import、类型标注或文档残句),边界未闭合。 + assert hits == [] \ No newline at end of file diff --git a/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py b/backend/tests/services/in_transit_transfer/test_inbound_trigger_service.py similarity index 64% rename from backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py rename to backend/tests/services/in_transit_transfer/test_inbound_trigger_service.py index acff5854..99698cc6 100644 --- a/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py +++ b/backend/tests/services/in_transit_transfer/test_inbound_trigger_service.py @@ -1,10 +1,10 @@ """真实收料 RPA 触发服务测试。 -用途:验证 trigger_receipt_rpa / trigger_receipt_rpa_batch 按来源装配收料 trigger unit - 并调用写者;触发先落 ShippingReceiptRpaUnitRun(awaiting_rpa、真实 unit_run_id 进载荷); +用途:验证 trigger_inbound_rpa / trigger_inbound_rpa_batch 按来源装配收料 trigger unit + 并调用写者;触发先落 FreightRpaInboundUnitRun(awaiting_rpa、真实 unit_run_id 进载荷); 配置/来源/触发目录缺失时 fail-closed(ok=False 或单元标 failed)。 -依赖:app(SQLite)fixture、receipt_trigger_service.trigger_receipt_rpa(_batch)、 - 既有测试种子(ShippingRpaProfile/ShippingInventorySource)。 +依赖:app(SQLite)fixture、inbound_trigger_service.trigger_inbound_rpa(_batch)、 + 既有测试种子(FreightRpaProfile/FreightRpaSource)。 逻辑:来源停用或收料配置缺失不写 trigger,返回 ok=False; 批量触发多来源合并一个 batch trigger 文件(单源失败跳过不炸整批, parse_failed 先本地重解析不触发 RPA)。 @@ -14,20 +14,20 @@ from __future__ import annotations import pytest -from app.models import ShippingInventorySource, ShippingReceiptReportConfig -from app.services.in_transit_transfer.receipt_trigger_service import ( - trigger_receipt_rpa, - trigger_receipt_rpa_batch, +from app.models import FreightRpaSource, FreightRpaInboundReportConfig +from app.services.in_transit_transfer.inbound_trigger_service import ( + trigger_inbound_rpa, + trigger_inbound_rpa_batch, ) @pytest.fixture def receipt_source(): """复用种子来源并为其创建收料配置。""" - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first() assert source is not None - config = ShippingReceiptReportConfig( - inventory_source_id=source.id, + config = FreightRpaInboundReportConfig( + source_id=source.id, report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'}, query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False}], ) @@ -38,7 +38,7 @@ def receipt_source(): return source -def test_trigger_receipt_rpa_writes_batch_trigger(app, receipt_source): +def test_trigger_inbound_rpa_writes_batch_trigger(app, receipt_source): """来源有效 → 写入 trigger 并返回 callback_id / trigger_path。""" calls = {} @@ -48,9 +48,9 @@ def test_trigger_receipt_rpa_writes_batch_trigger(app, receipt_source): calls['payload'] = payload or {} return f'/tmp/trigger/{run_no}.json' - result = trigger_receipt_rpa( + result = trigger_inbound_rpa( source_code='DSV360_AWSDU', business_date='2026-08-06', - reason='transfer_retry_receipt', writer=fake_writer, + reason='transfer_retry_inbound', writer=fake_writer, ) assert result['ok'] is True assert result['callback_id'] @@ -62,31 +62,31 @@ def test_trigger_receipt_rpa_writes_batch_trigger(app, receipt_source): {'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' + assert calls['payload']['schema_version'] == 'freight_rpa.inbound.v1' -def test_trigger_receipt_rpa_disabled_source_fails_closed(app): +def test_trigger_inbound_rpa_disabled_source_fails_closed(app): """来源停用 → ok=False,不写 trigger。""" - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first() source.enabled = False from app import db db.session.commit() - result = trigger_receipt_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06') + result = trigger_inbound_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06') assert result['ok'] is False - assert result['error_code'] == 'RPA_RECEIPT_CONFIG_MISSING' + assert result['error_code'] == 'RPA_INBOUND_CONFIG_MISSING' -def test_trigger_receipt_rpa_missing_config_fails_closed(app): +def test_trigger_inbound_rpa_missing_config_fails_closed(app): """来源启用但无收料配置 → ok=False。""" - result = trigger_receipt_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06') + result = trigger_inbound_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06') assert result['ok'] is False -def test_trigger_receipt_rpa_creates_unit_run_before_writing_trigger(app, receipt_source): - """触发必须先落 ShippingReceiptRpaUnitRun(awaiting_rpa),否则回调按 callback_id 404。""" +def test_trigger_inbound_rpa_creates_unit_run_before_writing_trigger(app, receipt_source): + """触发必须先落 FreightRpaInboundUnitRun(awaiting_rpa),否则回调按 callback_id 404。""" from app import db - from app.models import ShippingReceiptRpaUnitRun + from app.models import FreightRpaInboundUnitRun captured: dict = {} @@ -96,28 +96,28 @@ def test_trigger_receipt_rpa_creates_unit_run_before_writing_trigger(app, receip captured["units"] = units return "trigger.json" - outcome = trigger_receipt_rpa( + outcome = trigger_inbound_rpa( source_code=receipt_source.source_code, business_date="2026-09-17", - reason="transfer_retry_receipt", writer=fake_writer, + reason="transfer_retry_inbound", writer=fake_writer, ) assert outcome["ok"] is True - unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=outcome["callback_id"]).one() + unit = FreightRpaInboundUnitRun.query.filter_by(callback_id=outcome["callback_id"]).one() assert unit.status == "awaiting_rpa" # [断言意图] 按需触发无排程 run,schedule_run_id 必须为 NULL—— # PostgreSQL 上 FK 禁止 0 占位(SQLite 测试库不强制 FK,需显式守住列可空契约)。 assert unit.schedule_run_id is None - assert ShippingReceiptRpaUnitRun.__table__.columns['schedule_run_id'].nullable is True + assert FreightRpaInboundUnitRun.__table__.columns['schedule_run_id'].nullable is True assert captured["units"][0]["unit_run_id"] == unit.id assert unit.trigger_snapshot_json["callback_id"] == unit.callback_id -def _bind_published_movement_profile(config: ShippingReceiptReportConfig) -> None: - """给收料配置绑定一条已发布 movement 规则(仅满足守卫校验,不参与解析)。""" +def _bind_published_inbound_profile(config: FreightRpaInboundReportConfig) -> None: + """给收料配置绑定一条已发布 inbound 规则(仅满足守卫校验,不参与解析)。""" from app import db - from app.models import ShippingInventoryParsingProfile + from app.models import FreightRpaParsingProfile - profile = ShippingInventoryParsingProfile( - purpose='movement', profile_code='MOVE_TRIGGER_STD', display_name='收料异动规则', + profile = FreightRpaParsingProfile( + purpose='inbound', profile_code='MOVE_TRIGGER_STD', display_name='入站解析规则', version=1, status='published', file_format='xlsx', definition_json={'sheet_name': None, 'header_row_index': 1, 'field_mapping': {'doc_no': '单据编号', 'material_code': '料号', @@ -135,77 +135,85 @@ def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_p from app.services.in_transit_transfer.deps import _DefaultRpaTrigger with app.app_context(): - config = ShippingReceiptReportConfig.query.filter_by( - inventory_source_id=receipt_source.id).one() - _bind_published_movement_profile(config) + config = FreightRpaInboundReportConfig.query.filter_by( + source_id=receipt_source.id).one() + _bind_published_inbound_profile(config) - monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path)) + monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR', str(tmp_path)) outcome = _DefaultRpaTrigger().trigger( source_code=receipt_source.source_code, business_date="2026-09-17", reason="matching_missing_ready_file", ) assert outcome["ok"] is True - # [断言意图] 真实落盘:Worker 轮询目录必须能看到待领取 trigger - assert list(tmp_path.glob("receipt_export_batch_*.json")), "trigger file not written" + # [断言意图] 真实落盘:Worker 轮询目录必须能看到 inbound_export_batch_*.json + # (批次 R 自 receipt_export_batch_* 改名,旧 glob 会把已写入的文件判成没写)。 + assert list(tmp_path.glob("inbound_export_batch_*.json")), "trigger file not written" -def test_default_trigger_fails_closed_when_movement_profile_missing(app, receipt_source, tmp_path, monkeypatch): - """收料配置存在但未绑已发布 movement 规则 → ok=False 且不写 trigger(防徒劳抓取)。""" +def test_default_trigger_fails_closed_when_inbound_profile_missing(app, receipt_source, tmp_path, monkeypatch): + """收料配置存在但未绑已发布 inbound 规则 → ok=False 且不写 trigger(防徒劳抓取)。""" from app.services.in_transit_transfer.deps import _DefaultRpaTrigger - monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path)) + monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR', str(tmp_path)) outcome = _DefaultRpaTrigger().trigger( source_code=receipt_source.source_code, business_date="2026-09-17", reason="matching_missing_ready_file", ) - # [断言意图] 未绑规则时抓回文件也无法解析复用,必须 fail-closed 且不落 trigger 文件。 + # [断言意图] 未绑规则时抓回文件也无法解析复用,必须 fail-closed 且不落 inbound trigger 文件。 assert outcome["ok"] is False - assert outcome["error_code"] == "RPA_RECEIPT_MOVEMENT_PROFILE_MISSING" - assert list(tmp_path.glob("receipt_export_batch_*.json")) == [] + assert outcome["error_code"] == "RPA_INBOUND_PROFILE_MISSING" + assert list(tmp_path.glob("inbound_export_batch_*.json")) == [] -def test_trigger_receipt_rpa_marks_unit_failed_when_trigger_unavailable(app, receipt_source): +def test_trigger_inbound_rpa_marks_unit_failed_when_trigger_unavailable(app, receipt_source): """trigger 目录不可用(writer 返回 None)时单元必须标 failed,不留永久 awaiting 幽灵。""" - from app.models import ShippingReceiptRpaUnitRun + from app.models import FreightRpaInboundUnitRun - outcome = trigger_receipt_rpa( + outcome = trigger_inbound_rpa( source_code=receipt_source.source_code, business_date="2026-09-17", - reason="transfer_retry_receipt", writer=lambda *a, **k: None, + reason="transfer_retry_inbound", writer=lambda *a, **k: None, ) assert outcome["ok"] is False - unit = ShippingReceiptRpaUnitRun.query.filter_by(source_code=receipt_source.source_code).order_by( - ShippingReceiptRpaUnitRun.id.desc()).first() + unit = FreightRpaInboundUnitRun.query.filter_by(source_code=receipt_source.source_code).order_by( + FreightRpaInboundUnitRun.id.desc()).first() assert unit.status == "failed" - assert unit.error_code == "RPA_RECEIPT_TRIGGER_UNAVAILABLE" + assert unit.error_code == "RPA_INBOUND_TRIGGER_UNAVAILABLE" # --------------------------------------------------------------------------- -# 批量触发(trigger_receipt_rpa_batch):多来源合并一个 batch trigger 文件, +# 批量触发(trigger_inbound_rpa_batch):多来源合并一个 batch trigger 文件, # Worker 单次浏览器会话串行处理(2026-10-09 批量重试效率修复)。 # --------------------------------------------------------------------------- @pytest.fixture def second_receipt_source(app): - """再造一个启用来源 + 收料配置(批量用例需要多来源);启用态必须绑定 - 解析规则/Excel 模板(ck_shipping_inventory_sources_enabled_bindings),复用种子源绑定。""" + """再造一个启用来源 + 收料配置(批量用例需要多来源);s18 起启用态要求 + Excel 模板绑定(ck_freight_rpa_sources_enabled_template),解析绑定复用种子源配置行。""" from app import db - from app.models import ShippingInventorySource, ShippingRpaProfile, ShippingReceiptReportConfig + from app.models import FreightRpaOnhandReportConfig, FreightRpaSource, FreightRpaProfile, FreightRpaInboundReportConfig - seed = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first() - profile = ShippingRpaProfile( + seed = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first() + profile = FreightRpaProfile( profile_code='DBS_SG_TEST', display_name='DBS SG', connector_type='dbs', login_url='https://test.invalid/dbs-sg', login_config_json={'auth_mode': 'password'}, ) - source = ShippingInventorySource( + source = FreightRpaSource( source_code='DSV360_AWSSG', display_name='DBS SG AWSSG', connector_type='dbs', rpa_profile=profile, - parsing_profile=seed.parsing_profile, excel_template=seed.excel_template, + excel_template=seed.excel_template, warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSSG', - report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'}, enabled=True, ) + # s18 起在手解析绑定/报表路径归配置行,复用种子源绑定形态。 + seed_config = seed.onhand_report_config + FreightRpaOnhandReportConfig( + source=source, + parsing_profile=seed_config.parsing_profile if seed_config is not None else None, + report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'}, + query_parameters_json=[], + ) db.session.add_all([profile, source]) db.session.flush() # 先取 source.id(新建对象 flush 前无主键) - config = ShippingReceiptReportConfig( - inventory_source_id=source.id, + config = FreightRpaInboundReportConfig( + source_id=source.id, report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'}, query_parameters_json=[], ) @@ -214,9 +222,9 @@ def second_receipt_source(app): return source -def test_trigger_receipt_rpa_batch_writes_one_trigger_for_all_units(app, receipt_source, second_receipt_source): +def test_trigger_inbound_rpa_batch_writes_one_trigger_for_all_units(app, receipt_source, second_receipt_source): """多来源 → 只写一次 trigger(一个文件 N units),各单元独立 callback_id/unit_run_id。""" - from app.models import ShippingReceiptRpaUnitRun + from app.models import FreightRpaInboundUnitRun calls: list = [] @@ -224,27 +232,27 @@ def test_trigger_receipt_rpa_batch_writes_one_trigger_for_all_units(app, receipt calls.append({'run_no': run_no, 'units': units, 'payload': payload or {}}) return f'/tmp/trigger/{run_no}.json' - outcome = trigger_receipt_rpa_batch( + outcome = trigger_inbound_rpa_batch( source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-09', - reason='transfer_retry_receipt', writer=fake_writer, + reason='transfer_retry_inbound', writer=fake_writer, ) # [断言意图] 合并单文件是本修复的核心:writer 恰好调用 1 次、units 装下全部来源。 assert len(calls) == 1 assert outcome['ok'] is True and outcome['triggered'] is True assert calls[0]['run_no'].startswith('TRIG-BATCH-') assert [u['source_code'] for u in calls[0]['units']] == ['DSV360_AWSDU', 'DSV360_AWSSG'] - assert calls[0]['payload']['schema_version'] == 'shipping_receipt_rpa.v1' + assert calls[0]['payload']['schema_version'] == 'freight_rpa.inbound.v1' # 每单元独立回调身份,且单元行先落库(回调按 callback_id 可达)。 callback_ids = {u['callback_id'] for u in calls[0]['units']} assert len(callback_ids) == 2 - rows = ShippingReceiptRpaUnitRun.query.filter(ShippingReceiptRpaUnitRun.source_code.in_( + rows = FreightRpaInboundUnitRun.query.filter(FreightRpaInboundUnitRun.source_code.in_( ['DSV360_AWSDU', 'DSV360_AWSSG'])).all() assert {row.status for row in rows} == {'awaiting_rpa'} assert all(row.schedule_run_id is None for row in rows) assert {row.id for row in rows} == {u['unit_run_id'] for u in calls[0]['units']} -def test_trigger_receipt_rpa_batch_skips_invalid_source(app, receipt_source): +def test_trigger_inbound_rpa_batch_skips_invalid_source(app, receipt_source): """单源配置缺失 → 跳过该源并逐源记录 error_code,其余来源照常进 batch trigger。""" captured: dict = {} @@ -252,7 +260,7 @@ def test_trigger_receipt_rpa_batch_skips_invalid_source(app, receipt_source): captured['units'] = units return f'/tmp/trigger/{run_no}.json' - outcome = trigger_receipt_rpa_batch( + outcome = trigger_inbound_rpa_batch( source_codes=['DSV360_AWSDU', 'DSV360_NOPE'], business_date='2026-10-09', writer=fake_writer, ) @@ -262,36 +270,36 @@ def test_trigger_receipt_rpa_batch_skips_invalid_source(app, receipt_source): by_code = {item['source_code']: item for item in outcome['results']} assert by_code['DSV360_AWSDU']['ok'] is True assert by_code['DSV360_NOPE']['ok'] is False - assert by_code['DSV360_NOPE']['error_code'] == 'RPA_RECEIPT_CONFIG_MISSING' + assert by_code['DSV360_NOPE']['error_code'] == 'RPA_INBOUND_CONFIG_MISSING' -def test_trigger_receipt_rpa_batch_all_invalid_no_trigger(app): - """全部来源无效 → 不写 trigger,ok=False + RPA_RECEIPT_NO_TRIGGERABLE_SOURCE。""" - outcome = trigger_receipt_rpa_batch( +def test_trigger_inbound_rpa_batch_all_invalid_no_trigger(app): + """全部来源无效 → 不写 trigger,ok=False + RPA_INBOUND_NO_TRIGGERABLE_SOURCE。""" + outcome = trigger_inbound_rpa_batch( source_codes=['DSV360_NOPE'], business_date='2026-10-09', writer=lambda *a, **k: (_ for _ in ()).throw(AssertionError('writer must not be called')), ) assert outcome['ok'] is False and outcome['triggered'] is False - assert outcome['error_code'] == 'RPA_RECEIPT_NO_TRIGGERABLE_SOURCE' + assert outcome['error_code'] == 'RPA_INBOUND_NO_TRIGGERABLE_SOURCE' -def test_trigger_receipt_rpa_batch_writer_unavailable_marks_all_failed(app, receipt_source, second_receipt_source): +def test_trigger_inbound_rpa_batch_writer_unavailable_marks_all_failed(app, receipt_source, second_receipt_source): """trigger 目录不可用 → 本批全部单元标 failed,不留永久 awaiting 幽灵。""" - from app.models import ShippingReceiptRpaUnitRun + from app.models import FreightRpaInboundUnitRun - outcome = trigger_receipt_rpa_batch( + outcome = trigger_inbound_rpa_batch( source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-09', writer=lambda *a, **k: None, ) assert outcome['ok'] is False and outcome['triggered'] is False - assert outcome['error_code'] == 'RPA_RECEIPT_TRIGGER_UNAVAILABLE' - rows = ShippingReceiptRpaUnitRun.query.filter(ShippingReceiptRpaUnitRun.source_code.in_( + assert outcome['error_code'] == 'RPA_INBOUND_TRIGGER_UNAVAILABLE' + rows = FreightRpaInboundUnitRun.query.filter(FreightRpaInboundUnitRun.source_code.in_( ['DSV360_AWSDU', 'DSV360_AWSSG'])).all() assert {row.status for row in rows} == {'failed'} - assert {row.error_code for row in rows} == {'RPA_RECEIPT_TRIGGER_UNAVAILABLE'} + assert {row.error_code for row in rows} == {'RPA_INBOUND_TRIGGER_UNAVAILABLE'} -def test_trigger_receipt_rpa_batch_parse_failed_reparses_without_rpa(app, receipt_source, monkeypatch): +def test_trigger_inbound_rpa_batch_parse_failed_reparses_without_rpa(app, receipt_source, monkeypatch): """parse_failed 来源先本地重解析(成功则不触发 RPA),与单来源端点分层语义一致。""" statuses = { 'DSV360_AWSDU': [ @@ -320,7 +328,7 @@ def test_trigger_receipt_rpa_batch_parse_failed_reparses_without_rpa(app, receip def fake_writer(run_no, units, payload=None): raise AssertionError('reparsed source must not be triggered via RPA') - outcome = trigger_receipt_rpa_batch( + outcome = trigger_inbound_rpa_batch( source_codes=['DSV360_AWSDU'], business_date='2026-10-09', writer=fake_writer, ) # [断言意图] 重解析恢复 ready → 无需写盘,整体 ok=True(请求已达成目的)。 diff --git a/backend/tests/services/in_transit_transfer/test_invoice_aggregator.py b/backend/tests/services/in_transit_transfer/test_invoice_aggregator.py index 90a8f66c..1138a64e 100644 --- a/backend/tests/services/in_transit_transfer/test_invoice_aggregator.py +++ b/backend/tests/services/in_transit_transfer/test_invoice_aggregator.py @@ -1,9 +1,10 @@ """在途调拨 Invoice 多行汇总与冲突测试(L0 纯单元)。 -用途:验证相同 Invoice 多行只汇总收料数量并永久保留原始行追溯; - 同一 Invoice 出现多料号/多收料日期时整单阻断(InvoiceConflictError)。 +用途:验证相同 Invoice 多行只汇总异动数量并永久保留原始行追溯; + 同一 Invoice 出现多料号/多异动日期时自然拆分(InvoiceConflictError 保留为防御)。 依赖:app.services.in_transit_transfer.invoice_aggregator + file_parser。 -逻辑:汇总键为 (source_code, invoice_no);冲突判定基于料号与收料日期。 +逻辑:汇总键为 (source_code, invoice_no);拆分维度为料号与异动日期。 + tt14 入站化后经 parse_movement_rows(movement 契约行)构造解析行。 """ from __future__ import annotations @@ -13,7 +14,7 @@ from decimal import Decimal import pytest -from app.services.in_transit_transfer.file_parser import parse_receipt_rows +from app.services.in_transit_transfer.file_parser import parse_movement_rows from app.services.in_transit_transfer.invoice_aggregator import ( AggregatedInvoice, aggregate_invoices, @@ -23,19 +24,19 @@ pytestmark = pytest.mark.pure_unit def _parsed(rows: list[dict]) -> list: - """将原始行解析为 ParsedReceiptRow。""" - return parse_receipt_rows(source_code="DBS-AWSBI", rows=rows) + """将原始 movement 契约行解析为 ParsedMovementRow。""" + return parse_movement_rows(source_code="DBS-AWSBI", rows=rows) -def _row(invoice_no: str, *, material_no: str = "MAT-001", material_name: str = "连接器组件", - specification: str = "A 型 / 24PIN", receipt_date: str = "2026-08-05", - quantity: str = "500", row_no: int = 10, sheet: str = "Receipt", +def _row(doc_no: str, *, material_code: str = "MAT-001", material_name: str = "连接器组件", + specification: str = "A 型 / 24PIN", movement_date: str = "2026-08-05", + quantity: str = "500", row_no: int = 10, sheet: str = "Movement", warehouse_code: str = "WMS-A") -> dict: return { - "sheet": sheet, "row_no": row_no, "invoice_no": invoice_no, - "material_no": material_no, "material_name": material_name, - "specification": specification, "receipt_date": receipt_date, - "receipt_quantity": quantity, "source_code": "DBS-AWSBI", + "sheet": sheet, "row_no": row_no, "doc_no": doc_no, + "material_code": material_code, "material_name": material_name, + "specification": specification, "movement_date": movement_date, + "quantity": quantity, "source_code": "DBS-AWSBI", "warehouse_code": warehouse_code, } @@ -50,11 +51,11 @@ def test_same_invoice_multiple_rows_sum_quantity(): assert len(invoices) == 1 invoice = invoices[0] assert invoice.invoice_no == "INV-001" - assert invoice.receipt_quantity == Decimal("1200") + assert invoice.movement_quantity == Decimal("1200") assert len(invoice.raw_lines) == 2 assert invoice.raw_lines[0].row_no == 10 assert invoice.raw_lines[1].row_no == 11 - assert all(line.sheet == "Receipt" for line in invoice.raw_lines) + assert all(line.sheet == "Movement" for line in invoice.raw_lines) def test_distinct_invoices_stay_separate_and_sorted(): @@ -70,41 +71,41 @@ def test_distinct_invoices_stay_separate_and_sorted(): def test_same_invoice_multiple_materials_split_into_separate_invoices(): """同一 Invoice(ASN)跨料号 → 按料号拆分为多张调拨发票,不再整单阻断。""" rows = [ - _row("ASN-001", material_no="MAT-001", row_no=1, quantity="100"), - _row("ASN-001", material_no="MAT-002", row_no=2, quantity="200"), + _row("ASN-001", material_code="MAT-001", row_no=1, quantity="100"), + _row("ASN-001", material_code="MAT-002", row_no=2, quantity="200"), ] invoices = aggregate_invoices(_parsed(rows)) # [断言意图] Invoice 语义 = 调拨拨出单据号;料号维度自然拆分,保留各自数量与原始行。 - assert [(i.material_no, i.receipt_quantity) for i in invoices] == [ + assert [(i.material_no, i.movement_quantity) for i in invoices] == [ ("MAT-001", Decimal("100")), ("MAT-002", Decimal("200")), ] assert all(i.invoice_no == "ASN-001" for i in invoices) def test_same_invoice_material_multiple_dates_split_by_date(): - """同 Invoice 同料号跨收料日期(部分交付)→ 按日期拆分,不再整单阻断。""" + """同 Invoice 同料号跨异动日期(部分交付)→ 按日期拆分,不再整单阻断。""" rows = [ - _row("ASN-001", receipt_date="2026-08-05", row_no=1, quantity="100"), - _row("ASN-001", receipt_date="2026-08-06", row_no=2, quantity="50"), + _row("ASN-001", movement_date="2026-08-05", row_no=1, quantity="100"), + _row("ASN-001", movement_date="2026-08-06", row_no=2, quantity="50"), ] invoices = aggregate_invoices(_parsed(rows)) - assert [str(i.receipt_date) for i in invoices] == ["2026-08-05", "2026-08-06"] - assert [i.receipt_quantity for i in invoices] == [Decimal("100"), Decimal("50")] + assert [str(i.movement_date) for i in invoices] == ["2026-08-05", "2026-08-06"] + assert [i.movement_quantity for i in invoices] == [Decimal("100"), Decimal("50")] def test_aggregated_invoice_keeps_material_identity(): - """汇总结果保留料号、品名、规格与收料日期。""" + """汇总结果保留料号、品名、规格与异动日期。""" rows = [ - _row("INV-001", material_no="MAT-001", material_name="连接器组件", - specification="A 型 / 24PIN", receipt_date="2026-08-05", row_no=1), - _row("INV-001", material_no="MAT-001", row_no=2), + _row("INV-001", material_code="MAT-001", material_name="连接器组件", + specification="A 型 / 24PIN", movement_date="2026-08-05", row_no=1), + _row("INV-001", material_code="MAT-001", row_no=2), ] invoices = aggregate_invoices(_parsed(rows)) invoice = invoices[0] assert invoice.material_no == "MAT-001" assert invoice.material_name == "连接器组件" assert invoice.specification == "A 型 / 24PIN" - assert invoice.receipt_date == date(2026, 8, 5) + assert invoice.movement_date == date(2026, 8, 5) def test_aggregated_invoice_keeps_first_row_warehouse_code(): diff --git a/backend/tests/services/in_transit_transfer/test_ledger_sync.py b/backend/tests/services/in_transit_transfer/test_ledger_sync.py new file mode 100644 index 00000000..04aa7466 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_ledger_sync.py @@ -0,0 +1,283 @@ +"""库存异动档落地(ledger_sync)幂等语义回归。 + +用途:锁定 ledger_sync.sync_ledger_rows 的规格 §5 五条幂等语义——首落插入、 + 同文件重落全跳过(完全不动行)、证据变原行更新+换溯源、缺席不删、 + 封存行(transfer_executed=True)永不更新永不复活;以及交叉校验矛盾 + (inbound 行出库语义 '-1')计 cross_flagged 并写 ledger_cross_check_failed + 审计事件且记录照常落档;shipment 预留合法值放行、同批自然键重复首见为准。 +依赖:app fixture(pytestmark)、models.TransferMovementLedger / TransferAuditEvent、 + ledger_sync.sync_ledger_rows / FileMeta / movement_file_version。 +逻辑:parsed_rows 以「movement 契约 field code → 值」的领域行 dict 直接构造 + (扩展字段值从 dict 取,非 ParsedMovementRow 属性——Task 11 接线同形态); + 直连 SQLite 内存库断言行级状态与审计事件,全程零外部调用。 +""" + +from __future__ import annotations + +from datetime import datetime + +import pytest + +from app import db +from app.models import TransferAuditEvent, TransferMovementLedger +from app.services.in_transit_transfer.ledger_sync import ( + FileMeta, + movement_file_version, + sync_ledger_rows, +) + +pytestmark = [pytest.mark.usefixtures("app")] + +SOURCE = "DBS-AWSBI" +NOW = datetime(2026, 10, 14, 10, 0, 0) +NOW2 = datetime(2026, 10, 14, 11, 0, 0) +SHA_V1 = "a" * 64 +SHA_V2 = "b" * 64 + + +def _row(**overrides) -> dict: + """构造一条标准领域行 dict(键=movement 契约 field code + 可选溯源键)。 + + Args: + **overrides: 按需覆盖的字段(doc_no/quantity/in_out_flag 等)。 + Returns: + 领域行 dict(既有 11 + 扩展 7 字段,另含 sheet_name/row_no 溯源键)。 + """ + row = { + "doc_no": "HOM-20261014-001", "line_no": "10", "in_out_flag": "1", + "material_code": "MAT-001", "material_name": "连接器", + "warehouse_code": "WTP", "storage_code": "A01", "lot_no": "WTP123", + "quantity": "12.5", "movement_date": "2026-10-14", "unit": "PCS", + "line_seq": "1", "specification": "C 型", "order_type": "ZRO1", + "odm_id": "ODM-1", "odm_name": "奥的斯", "carton_id": "CTN-1", + "pallet_id": "PLT-1", "sheet_name": "Sheet1", "row_no": 2, + } + row.update(overrides) + return row + + +def _meta(*, sha: str = SHA_V1, version: str = "v1", file_id: int = 101) -> FileMeta: + """构造来源文件证据三元组(source_file_id 用任意整数:测试库无 FK 强制)。""" + return FileMeta(source_file_id=file_id, file_version=version, file_sha256=sha) + + +def _sync(parsed_rows, *, record_kind: str = "inbound", meta: FileMeta | None = None, now=NOW): + """按默认来源发起一次落档(省略重复实参)。""" + return sync_ledger_rows( + source_code=SOURCE, record_kind=record_kind, + parsed_rows=parsed_rows, file_meta=meta or _meta(), now=now, + ) + + +def test_first_landing_inserts_rows_with_provenance(): + # [断言意图] 首落六分类归插入:业务镜像列(含扩展字段)与溯源五列随行写入。 + outcome = _sync([_row(), _row(doc_no="HOM-20261014-002", line_no="20")]) + assert (outcome.inserted, outcome.updated, outcome.skipped, + outcome.sealed_skipped, outcome.cross_flagged) == (2, 0, 0, 0, 0) + rows = TransferMovementLedger.query.order_by(TransferMovementLedger.doc_no).all() + assert len(rows) == 2 + first = rows[0] + assert (first.source_code, first.record_kind) == (SOURCE, "inbound") + assert first.quantity == "12.5" and first.lot_no == "WTP123" + # 扩展字段取自领域行 dict(movement 契约 code ↔ 档列 1:1 镜像)。 + assert first.specification == "C 型" and first.order_type == "ZRO1" + assert first.odm_name == "奥的斯" and first.carton_id == "CTN-1" and first.pallet_id == "PLT-1" + # 溯源:文件级三元组 + 行级 sheet/row_no + 显式 updated_at。 + assert first.source_file_id == 101 and first.file_version == "v1" + assert first.file_sha256 == SHA_V1 and first.sheet_name == "Sheet1" and first.row_no == 2 + assert first.updated_at == NOW + + +def test_same_file_relanding_all_skipped_without_touch(): + # [断言意图] 同文件重落全 skipped 且完全不动行:updated_at 不续、零审计事件。 + _sync([_row()]) + outcome = _sync([_row()], now=NOW2) + assert (outcome.inserted, outcome.updated, outcome.skipped) == (0, 0, 1) + row = TransferMovementLedger.query.one() + assert row.updated_at == NOW # 跳过=不动行(档无 TTL,无新鲜度可续) + assert TransferAuditEvent.query.count() == 0 # 幂等重落不写任何审计事件 + + +def test_evidence_change_updates_row_and_swaps_provenance(): + # [断言意图] 证据变(quantity)原行更新:业务值换新 + 溯源五列整体换新,不产生第二行。 + _sync([_row(quantity="12.5")]) + outcome = _sync( + [_row(quantity="30", sheet_name="Sheet2", row_no=7)], + meta=_meta(sha=SHA_V2, version="v2", file_id=102), now=NOW2, + ) + assert (outcome.updated, outcome.inserted, outcome.skipped) == (1, 0, 0) + assert TransferMovementLedger.query.count() == 1 # 原行更新,永不双行 + row = TransferMovementLedger.query.one() + assert row.quantity == "30" + assert row.file_version == "v2" and row.file_sha256 == SHA_V2 + assert row.source_file_id == 102 and row.sheet_name == "Sheet2" and row.row_no == 7 + assert row.updated_at == NOW2 + + +def test_absent_rows_kept_not_deleted(): + # [断言意图] 文件缺席的档行原样留存:收料 RPA 非全量导出,缺席≠删除。 + _sync([_row(), _row(doc_no="HOM-20261014-002", line_no="20")]) + outcome = _sync([_row()], now=NOW2) + assert outcome.skipped == 1 + assert TransferMovementLedger.query.count() == 2 # 缺席行不删 + absent = TransferMovementLedger.query.filter_by(doc_no="HOM-20261014-002").one() + assert absent.quantity == "12.5" and absent.updated_at == NOW # 原样留存 + + +def test_sealed_row_never_updated_nor_revived(): + # [断言意图] 封存行证据再变:不更新业务值、不换溯源、不动时间戳、不产生第二行。 + _sync([_row(quantity="12.5")]) + sealed = TransferMovementLedger.query.one() + sealed.transfer_executed = True + sealed.executed_doc_no = "TDO-0001" + db.session.commit() + # 封存提交触发行 UPDATE(onupdate 续戳),以封存落库后的时间戳为「零写入」基准。 + sealed_at = TransferMovementLedger.query.one().updated_at + outcome = _sync( + [_row(quantity="999", sheet_name="Sheet9", row_no=99)], + meta=_meta(sha=SHA_V2, version="v2", file_id=102), now=NOW2, + ) + assert (outcome.sealed_skipped, outcome.inserted, outcome.updated) == (1, 0, 0) + loaded = TransferMovementLedger.query.one() + assert loaded.quantity == "12.5" # 证据再变不更新 + assert loaded.file_sha256 == SHA_V1 and loaded.file_version == "v1" + assert loaded.source_file_id == 101 # 溯源不换新 + assert loaded.transfer_executed is True and loaded.executed_doc_no == "TDO-0001" + assert loaded.updated_at == sealed_at # 封存同步零写入 + assert TransferMovementLedger.query.count() == 1 # 永不复活(同键无第二行) + + +def test_inbound_outbound_flag_cross_flagged_but_landed(): + # [断言意图] inbound 行出库语义 '-1':计 cross_flagged、写审计事件,记录照常落档; + # 幂等重落同一矛盾文件不重复打事件(只追加审计表防刷爆)。 + outcome = _sync([_row(in_out_flag="-1"), _row(doc_no="HOM-20261014-002", line_no="20")]) + assert (outcome.cross_flagged, outcome.inserted) == (1, 2) + event = TransferAuditEvent.query.one() + assert event.event_type == "ledger_cross_check_failed" + assert event.aggregate_type == "transfer_movement_ledger" + assert "HOM-20261014-001" in event.aggregate_id + assert event.result == "failure" + assert event.after_json["in_out_flag"] == "-1" + bad = TransferMovementLedger.query.filter_by(doc_no="HOM-20261014-001").one() + assert bad.in_out_flag == "-1" # 矛盾记录照常落档 + outcome2 = _sync( + [_row(in_out_flag="-1"), _row(doc_no="HOM-20261014-002", line_no="20")], now=NOW2, + ) + assert (outcome2.cross_flagged, outcome2.skipped) == (0, 2) + assert TransferAuditEvent.query.count() == 1 # 无新增事件 + + +def test_shipment_kind_is_legal_and_not_cross_flagged(): + # [断言意图] record_kind='outbound'(出货侧,预留)为合法值:校验放行、无 inbound 侧矛盾判定。 + outcome = _sync([_row(in_out_flag="-1")], record_kind="outbound") + assert (outcome.inserted, outcome.cross_flagged) == (1, 0) + assert TransferMovementLedger.query.one().record_kind == "outbound" + + +def test_sealed_row_dominates_even_when_sha_unchanged(): + # [断言意图] 封存是最高优先事实:同 sha 重落命中封存行也计 sealed_skipped(非 skipped)。 + _sync([_row()]) + sealed = TransferMovementLedger.query.one() + sealed.transfer_executed = True + db.session.commit() + sealed_at = TransferMovementLedger.query.one().updated_at # 零写入基准(onupdate 后) + outcome = _sync([_row()], now=NOW2) + assert (outcome.sealed_skipped, outcome.skipped) == (1, 0) + assert TransferMovementLedger.query.one().updated_at == sealed_at # 依旧零写入 + + +def test_duplicate_natural_key_in_batch_first_wins(): + # [断言意图] 同批自然键重复:首见为准,后续幂等跳过(自然键唯一索引 DB 兜底防双行)。 + outcome = _sync([_row(quantity="12.5"), _row(quantity="88")]) + assert (outcome.inserted, outcome.skipped) == (1, 1) + assert TransferMovementLedger.query.count() == 1 + assert TransferMovementLedger.query.one().quantity == "12.5" + + +def test_carton_dimension_expands_natural_key(): + # [断言意图] 同单号同行不同箱号=两行独立落档(旧四成分键会塌缩为首见为准丢行)。 + outcome = _sync([ + _row(doc_no="DUB1", line_no="10", carton_id="C1", quantity="5"), + _row(doc_no="DUB1", line_no="10", carton_id="C2", quantity="7"), + ], record_kind="inbound") + assert (outcome.inserted, outcome.date_skipped) == (2, 0) + + +def test_lot_no_expands_natural_key(): + # [断言意图] 同单号同行不同批号=两行独立落档(tt14 键扩维防同批号塌缩丢行)。 + outcome = _sync([ + _row(doc_no="WTP1", line_no="1", lot_no="HOW001", quantity="1"), + _row(doc_no="WTP1", line_no="1", lot_no="HOW002", quantity="2"), + ], record_kind="inbound") + assert outcome.inserted == 2 + + +def test_external_doc_line_expands_natural_key(): + # [断言意图] 外部单据身份(外部单号/外部项次)入自然键:同单号同行但外部单号 + # 不同 = 两行独立落档(2026-10-21 档幂等主键管控扩维,防外部身份塌缩丢行)。 + outcome = _sync([ + _row(doc_no="WTP1", line_no="1", external_doc_no="WMS-001", quantity="1"), + _row(doc_no="WTP1", line_no="1", external_doc_no="WMS-002", quantity="2"), + ], record_kind="inbound") + assert outcome.inserted == 2 + assert outcome.skipped == 0 + + +def test_external_doc_line_same_identity_converges_to_one_row(): + # [断言意图] 主键管控收敛面:同外部单号+项次的重复落档收敛同一档行—— + # 证据变化走原行更新(不是插入第二行),与 tt14 箱号/批号扩维同语义。 + outcome = _sync([_row(doc_no="WTP1", line_no="1", external_doc_no="WMS-001", + external_line_no="5", quantity="1")]) + assert outcome.inserted == 1 + outcome2 = _sync([_row(doc_no="WTP1", line_no="1", external_doc_no="WMS-001", + external_line_no="5", quantity="3")], meta=_meta(sha=SHA_V2), now=NOW2) + assert (outcome2.inserted, outcome2.updated, outcome2.skipped) == (0, 1, 0) + row = TransferMovementLedger.query.one() + assert row.quantity == "3" + assert row.external_doc_no == "WMS-001" and row.external_line_no == "5" + + +def test_empty_movement_date_rows_skipped(): + # [断言意图] movement_date 空 = 未发生异动:不落档、不计入其他分类(date_skipped 单列)。 + outcome = _sync([ + _row(doc_no="EXP1", line_no="1", movement_date="", quantity="3"), + _row(doc_no="OK1", line_no="1", movement_date="2026-10-15", quantity="1"), + ], record_kind="inbound") + assert (outcome.inserted, outcome.date_skipped) == (1, 1) + + +def test_constants_inbound_outbound(): + # [断言意图] record_kind 常量契约:说辞清扫(Task 3)以这些常量名为准,不再散落字面量。 + from app.services.in_transit_transfer import ledger_sync + assert ledger_sync.RECORD_KIND_INBOUND == "inbound" + assert ledger_sync.RECORD_KIND_OUTBOUND == "outbound" + assert ledger_sync.INBOUND_CONTRADICTORY_FLAGS == frozenset({"-1"}) + + +def test_batch_external_doc_no_row_untouched_by_landing(): + # [断言意图] 评审 Important 回归(STEP 1 只圈批内 doc_no):同来源同种类的批外 + # 档行不被水化、不被触碰(updated_at/内容不变),outcome 计数只反映批内。 + db.session.add(TransferMovementLedger( + source_code=SOURCE, record_kind="inbound", + doc_no="HOM-20261013-999", line_no="1", line_seq="", in_out_flag="1", + quantity="7", file_sha256=SHA_V1, file_version="v0", source_file_id=201, + updated_at=NOW, + )) + db.session.commit() + external_at = TransferMovementLedger.query.filter_by( + doc_no="HOM-20261013-999").one().updated_at + outcome = _sync([_row()]) # 批内仅 HOM-20261014-001,批外 doc_no 不参与 + assert (outcome.inserted, outcome.skipped, outcome.sealed_skipped) == (1, 0, 0) + external = TransferMovementLedger.query.filter_by(doc_no="HOM-20261013-999").one() + assert external.quantity == "7" and external.file_sha256 == SHA_V1 # 内容不变 + assert external.updated_at == external_at # 零触碰 + assert TransferMovementLedger.query.count() == 2 # 缺席不删:批外行留存 + + +def test_movement_file_version_fits_varchar64_column(): + # [断言意图] 64 位摘要加 sha256: 前缀共 71 字符;档列 file_version 是 varchar(64), + # 戳必须是这一条已知截断值(2026-10-21 DSV 出站整批插入失败的摘要)。 + digest = "7bbca0adaef3d550e0db47955a9b59609313be3b1335c1b498381db3b7a11715" + stamp = movement_file_version(digest) + assert stamp == "sha256:7bbca0adaef3d550e0db47955a9b59609313be3b1335c1b498381db3b" + assert len(stamp) == 64 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 41c50733..6fb33c2a 100644 --- a/backend/tests/services/in_transit_transfer/test_matching_inplace.py +++ b/backend/tests/services/in_transit_transfer/test_matching_inplace.py @@ -1,220 +1,145 @@ -"""行原地刷新与文件版本戳测试(L1,SQLite 内存库)。 +"""匹配出生与行归属测试(出生翻转后语义,L1,SQLite 内存库)。 -用途:验证重复匹配对既有 InvoiceItem 行为"原地刷新"(不迁移 matching_id、显式续 - updated_at)、行携带证据同步落地的 file_sha256 版本戳,以及文件新版本缺席行 - 存续(只换戳不改状态)【2026-09-28 语义:缺席≠删除,归 evidence_sync】; - 最近匹配计数按匹配 scope 实时聚合(不再按行归属)。 +用途:锁定出生翻转(ADR 0001/D4/D17)后的行归属不变式——行由匹配创建时从档 + 圈定生成且「创建即绑定」matching_id;重复匹配因圈档互斥不累加行、不改写 + 他匹配归属;行携带档记录证据版本戳(file_sha256)供执行门禁②文件对账; + scope_item_query / invoice_in_scope 等旧 scope 圈行入口已退役(模块级 + 断言防回归)。 依赖:transfer_db、matching_service、evidence_sync(seed_rows_from_file 桥)、 - transfer_type、repo_fakes。 -逻辑:文件行先经 seed_rows_from_file(=evidence_sync.sync_source_rows)落成待查行, - 再经 create_matching 落位;用"改 checksum/裁剪 rows"的新文件再次 seed 模拟 - 文件新版本;版本戳缺失用手工清空 raw_lines_json 的 file_sha256 模拟存量数据。 + factories、repo_fakes。 +逻辑:文件行先经 seed_rows_from_file(=evidence_sync.sync_source_rows)落成档行, + 再经 create_matching 圈档建 items;旧「原地刷新/scope 实时视图」语义已由 + 「重查对档对账(test_requery_scope)」与「自有 items 视图(test_restore_scope)」 + 承接,本模块保留翻转后的归属/戳不变式与展示健壮性(§13.1)。 """ from __future__ import annotations +import pytest + from app import db from app.models import TransferInvoiceItem +from app.services.in_transit_transfer import matching_service from app.services.in_transit_transfer.matching_service import ( _item_evaluated_sha, create_matching, - scope_item_query, ) -from app.services.in_transit_transfer.transfer_type import invoice_in_scope +from tests.services.in_transit_transfer.factories import seed_transfer_type_config from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps, seed_rows_from_file - -def _file_without(dbs_ready_file: dict, doc_no: str, *, checksum: str) -> dict: - """构造"新版本文件":剔除指定单号后剩余行,并更换 checksum。""" - return { - **dbs_ready_file, - "checksum": checksum, - "rows": [row for row in dbs_ready_file["rows"] if row["doc_no"] != doc_no], - } +pytestmark = pytest.mark.usefixtures("transfer_db") -def test_rematching_refreshes_rows_in_place(transfer_db, dbs_ready_file): - """第二次匹配:同一物理行原地刷新(id 不变、matching_id 不变、值更新)。""" - 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 - seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - first = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) - row = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first() - old_id, old_matching_id, old_updated = row.id, row.matching_id, row.updated_at +def test_retired_scope_entries_are_gone(): + """scope_item_query / invoice_in_scope 已退役:模块级断言,残留引用即失败。 - second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + Why: 出生翻转后「这份匹配覆盖哪些行」= matching_id 归属(创建即绑定), + scope 实时圈行与类型前缀谓词的职责移交档圈定(scope_rules 引擎); + 二次引入会造成双重口径(D17 占用互斥失效)。 + """ + assert not hasattr(matching_service, "scope_item_query") + from app.services.in_transit_transfer import transfer_type - db.session.refresh(row) - # [断言意图] 行不换归属:重复匹配复用同一物理行,matching_id 保持首次创建值, - # 仅业务值与新鲜度(updated_at)被刷新——计数错乱与壳匹配的根源即"迁移行"。 - assert row.id == old_id - assert row.matching_id == old_matching_id - assert row.updated_at > old_updated - # 两份匹配记录都存在(评估留痕)。 - assert first.matching_id != second.matching_id + assert not hasattr(transfer_type, "invoice_in_scope") -def test_rows_carry_file_sha256_stamp(transfer_db, dbs_ready_file): - """行 raw_lines_json 携带本次评估所用文件的 file_sha256(新建行写入)。""" +def test_items_are_born_bound_to_matching(transfer_db, dbs_ready_file): + """创建即绑定:圈档出生行 matching_id/run_id/ledger_record_id 齐备,业务字段=档原值。""" 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") seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) - # [断言意图] 版本戳由证据同步落地时写入(与文件 checksum 同源):文件对账读取 - # item.raw_lines_json[0].file_sha256,缺失即无法判定行新鲜度。 + summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + transfer_type="in_transit_to_hub") + + from app.models import TransferMatching + + matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).one() + rows = TransferInvoiceItem.query.all() + # [断言意图] 出生即绑定:matching_id/run_id 指向本次、ledger_record_id 指向档。 + assert {row.invoice_no for row in rows} == {"HOM-001", "HOX-002"} + for row in rows: + assert row.matching_id == matching.id + # [断言意图] run_id 保持 None:执行 Run 关联归 orchestrator(圈未关联行)。 + assert row.run_id is None + assert row.ledger_record_id is not None + hom = next(row for row in rows if row.invoice_no == "HOM-001") + # [断言意图] 业务字段=档原值:数量=档聚合值(500+700),批号/仓库/日期同档。 + assert hom.movement_quantity == "1200" + assert hom.lot_no == "LOT-10" and hom.movement_date == "2026-08-04" + assert hom.movement_warehouse_code == "" # 夹具行无仓库列 → 档原值为空串 + + +def test_rematching_never_accumulates_or_steals_rows(transfer_db, dbs_ready_file): + """重复匹配:圈档互斥(D17)——第二匹配圈不到已占用记录,不累加行、不迁移归属。""" + from app.models import TransferMatching + + 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") + seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") + first = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + transfer_type="in_transit_to_hub") + first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one() + old_rows = {row.id: (row.matching_id, row.status) for row in TransferInvoiceItem.query.all()} + assert len(old_rows) == 2 + + second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + transfer_type="in_transit_to_hub") + + # [断言意图] 总行数不变(无 2×N 累加)、归属保持首建匹配;第二匹配为空壳 + # (其自有行集为空)——记录已被有效 items 占用,圈档互斥排除。 + assert TransferInvoiceItem.query.count() == 2 + for row in TransferInvoiceItem.query.all(): + assert (row.matching_id, row.status) == old_rows[row.id] + assert row.matching_id == first_matching.id + second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one() + assert TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).count() == 0 + assert TransferMatching.query.count() == 2 # 匹配记录照常逐次留痕 + + +def test_rows_carry_ledger_file_sha_stamp(transfer_db, dbs_ready_file): + """出生行 raw_lines_json 携带档记录证据版本戳(执行门禁②文件对账依据)。""" + 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") + seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + transfer_type="in_transit_to_hub") + + # [断言意图] 版本戳随出生行来自档记录(与文件 checksum 同源):文件对账读取 + # item.raw_lines_json[0].file_sha256,缺失即无法判定行新鲜度(fail-closed)。 for invoice_no in ("HOM-001", "HOX-002"): row = db.session.query(TransferInvoiceItem).filter_by(invoice_no=invoice_no).first() assert row.raw_lines_json, f"{invoice_no} 应有 raw_lines" assert row.raw_lines_json[0]["file_sha256"] == dbs_ready_file["checksum"] + assert row.raw_lines_json[0]["sheet"] == "Receipt" assert _item_evaluated_sha(row) == dbs_ready_file["checksum"] -def test_scope_item_query_follows_matching_scope(transfer_db, dbs_ready_file): - """scope_item_query 按 scope_json(来源+日期区间+类型前缀)圈行,不依赖行归属。""" - from app.models import TransferMatching +def test_display_robust_without_type_config(transfer_db, dbs_ready_file): + """展示健壮性(规格 §13.1):配置表无该类型 code 时 restore/序列化仍成功。 + + Why: Run/Matching 展示与审计不得依赖配置表存在性(类型值可能来自已停用/ + 已改名的配置,展示层读 scope_json 快照不查配置表)。 + """ + from app.models import TransferMatching, TransferTypeConfig + from app.services.in_transit_transfer.matching_service import restore_matching 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") seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - summary = create_matching( - source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, - receipt_date_from="2026-08-05", receipt_date_to="2026-08-05", - ) - matching = db.session.query(TransferMatching).filter_by(matching_no=summary.matching_id).first() - - rows = scope_item_query(matching).all() - - # [断言意图] 行的 matching_id 即使不指向本匹配,scope 命中的行也必须被圈入 - # (Task 2 restore 与最近匹配计数共用该口径)。 - assert {row.invoice_no for row in rows} == {"HOM-001", "HOX-002"} - - -def test_scope_query_sees_same_rows_for_overlapping_matchings(transfer_db, dbs_ready_file): - """重匹配不迁移行:两份匹配按各自 scope 实时圈行,命中同一批行(实时视图语义)。""" - from app.models import TransferMatching - - deps, erp, _ = make_transfer_deps(dbs_ready_file) - erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # blocked - erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # executable - seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - first = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) - second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) - - # [断言意图] 行不迁移后两份匹配的 scope 都命中同一批活跃行(总数 2、 - # 可执行 1、阻断 1)——匹配卡=范围实时视图,不再出现"旧匹配被掏空"。 - for matching_no in (first.matching_id, second.matching_id): - matching = db.session.query(TransferMatching).filter_by(matching_no=matching_no).one() - rows = scope_item_query(matching).all() - assert {row.invoice_no for row in rows} == {"HOM-001", "HOX-002"} - assert sum(1 for r in rows if r.status == "ready_to_execute") == 1 - assert sum(1 for r in rows if r.status == "blocked_recoverable") == 1 - - -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 - seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) - hom = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first() - hox = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOX-002").first() - assert hom.status == "ready_to_execute" - - # 新文件版本:内容只剩 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-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") - - db.session.refresh(hom) - db.session.refresh(hox) - # [断言意图] 同步后:缺席行状态原样保留(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_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") - seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) - hom = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first() - hox = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOX-002").first() - assert hom.status == "ready_to_execute" - # 模拟存量行:清空 raw_lines_json 的 file_sha256 版本戳。 - for row in (hom, hox): - row.raw_lines_json = [ - {key: value for key, value in line.items() if key != "file_sha256"} - for line in (row.raw_lines_json or []) - ] + summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + transfer_type="in_transit_to_hub") + # 模拟类型配置随后被清理(平台侧只停用不删除;此处取更强前提)。 + db.session.query(TransferTypeConfig).delete() db.session.commit() - 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") - seed_rows_from_file("DBS-AWSBI", deps2, "2026-08-06") - - db.session.refresh(hom) - db.session.refresh(hox) - # [断言意图] 身份判定不依赖版本戳:缺席行存续(状态保留),回填最新戳; - # 在文件行无证据变化 → 只换戳不重置待查。 - 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_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 - seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) - hom = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first() - assert hom.status == "blocked_recoverable" - assert hom.result_code == "blocked_quantity_mismatch" - - 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") - seed_rows_from_file("DBS-AWSBI", deps2, "2026-08-06") - - db.session.refresh(hom) - # [断言意图] 缺席不改写既有阻断解释;版本戳换到最新文件。 - assert hom.status == "blocked_recoverable" - assert hom.result_code == "blocked_quantity_mismatch" - assert _item_evaluated_sha(hom) == "e" * 64 - - -def test_invoice_in_scope_predicate(): - """invoice_in_scope:类型 1 按 HOM/HOX/WTP 前缀(大小写不敏感),占位类型恒 False。""" - assert invoice_in_scope("HOM-001", "in_transit_to_hub") is True - assert invoice_in_scope("hox-002", "in_transit_to_hub") is True - assert invoice_in_scope("WTP-008", None) is True # 缺省回落类型 1 - assert invoice_in_scope("INV-9", "in_transit_to_hub") is False - assert invoice_in_scope("", "in_transit_to_hub") is False - # [断言意图] 占位类型(规则未启用)必须返回 False:scope 查询不得圈入任何行。 - assert invoice_in_scope("HOM-001", "hub_repair_out") is False + restored = restore_matching(summary.matching_id) + # [断言意图] 展示链路零配置依赖:摘要/明细照常投影(scope_json 快照自足)。 + assert restored["summary"].matching_hash == summary.matching_hash + assert {item.invoice_no for item in restored["items"]} == {"HOM-001", "HOX-002"} + matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).one() + assert matching.scope_json["transfer_type"] == "in_transit_to_hub" 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 88d70c02..18cb78aa 100644 --- a/backend/tests/services/in_transit_transfer/test_matching_service.py +++ b/backend/tests/services/in_transit_transfer/test_matching_service.py @@ -1,14 +1,18 @@ """在途调拨匹配服务测试(L1,SQLite 内存库)。 -用途:验证 T+lag 成熟过滤(套件钉 lag=1)、严格数量匹配、来源隔离、 +用途:验证日期范围校验(截止≤业务日期)、严格数量匹配、来源隔离、 匹配快照 Hash 稳定、缺文件等待与进度恢复;专项用例锁生产默认 lag=2。 依赖:app fixture、transfer_db、fakes、repo_fakes、matching_service。 逻辑:全部经真实 ORM 落库(create_matching/restore_matching), - 外部依赖注入 Fake 替身。 + 外部依赖注入 Fake 替身。圈档记录类型用例直接插出站档行, + 经 create_matching 断言 doc_no。入站 no_data / 仅出站类型断言不触发入站 RPA。 + 确认匹配对 ready 出站归档幂等补落档后再圈行(空档窗口回归)。 """ from __future__ import annotations +from datetime import datetime + import pytest from app import db @@ -36,6 +40,21 @@ def _deps(*files: dict, erp: FakeCapabilityClient | None = None, rpa: FakeRPA | return make_transfer_deps(*files, capabilities=erp, rpa=rpa) +@pytest.fixture +def deps(app): + """圈档记录类型用例的匹配依赖(空文件仓库,DSV360_AWSBI 路由可解析)。 + + 核心逻辑:请求 app 以建表并触发默认类型种子;路由只为评估链不中断, + 断言不看仓库。 + Returns: + TransferDeps。 + """ + built, _erp, _rpa = make_transfer_deps( + routes={"DSV360_AWSBI": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")}, + ) + return built + + def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file): """两个来源全部严格匹配 → executable_count 正确,无阻断。""" deps, erp, _ = _deps(dbs_ready_file, crane_ready_file) @@ -49,11 +68,10 @@ def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file) seed_rows_from_file("CRANE-SZ", deps, "2026-08-06") result = run_matching( - source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps, + source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub" ) summary = result.summary assert summary.counts.executable_count == 3 - assert summary.counts.not_matured_count == 0 assert summary.counts.blocked_count == 0 assert summary.status == "ready_to_execute" assert summary.matching_hash.startswith("sha256:") @@ -65,13 +83,17 @@ def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file) assert items["HOM-001"].from_warehouse == "DBS-TRANSIT" assert items["HOM-001"].to_warehouse == "HUB-CN01" assert items["HOM-001"].from_quantity == items["HOM-001"].to_quantity == 1200 - assert len(items["HOM-001"].raw_lines) == 2 # 多行汇总保留原始行 + # [出生翻转] 行级溯源来自档记录(聚合在落档完成):raw_lines 单行、 + # 携带档记录 sheet/row_no(旧「多行汇总保留原始行」由档聚合承接)。 + assert len(items["HOM-001"].raw_lines) == 1 + assert items["HOM-001"].raw_lines[0].sheet == "Receipt" + assert items["HOM-001"].raw_lines[0].row_no == 10 def test_estimated_document_count_merges_same_group(dbs_ready_file): """[2026-10-12 单据数口径修正] 预计 ERP 单据数按执行建单五元组去重。 - 场景:同源同日两张 Invoice,五元组(org, source, receipt_date, from, to) + 场景:同源同日两张 Invoice,五元组(org, source, movement_date, from, to) 全同 → 执行期合并一张 ERP 单,预估数 = 1 而非可执行行数 2; 并断言 DTO external_org 随路由解析透出(前端勾选行预估的分组输入)。 """ @@ -80,26 +102,28 @@ def test_estimated_document_count_merges_same_group(dbs_ready_file): erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") result = run_matching( - source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub" ) assert result.summary.counts.executable_count == 2 - # HOM-001 与 HOX-002 同(HX-CN01, DBS-AWSBI, 2026-08-05, DBS-TRANSIT, HUB-CN01)。 + # HOM-001 与 HOX-002 同(HX-CN01, DBS-AWSBI, 2026-08-04, DBS-TRANSIT, HUB-CN01)。 assert result.summary.estimated_external_write_count == 1 items = {item.invoice_no: item for item in result.items} assert items["HOM-001"].external_org == "HX-CN01" assert items["HOX-002"].external_org == "HX-CN01" -def test_estimated_document_count_splits_by_receipt_date(): +def test_estimated_document_count_splits_by_movement_date(): """[2026-10-12 单据数口径修正] 同源同仓库但收料日期不同 → 五元组不同,预估 = 2。 - 锁定分组的日期维度:execution_service.prepare_execution 以 receipt_date 入键, + 锁定分组的日期维度:execution_service.prepare_execution 以 movement_date 入键, 跨日行不合并单(预估数与执行建单数一致,不给用户错误预期)。 + 【T−2 成熟封顶 2026-10-21】两行均取 ≤ T−2(08-03/08-04)成熟日期, + 隔天分组语义不变。 """ deps, erp, _ = _deps({ "source_code": "DBS-AWSBI", "business_date": "2026-08-06", - "file_purpose": "receipt", + "file_purpose": "inbound", "file_no": "REC-20260806-009", "file_version": "v9", "checksum": "e" * 64, @@ -107,32 +131,37 @@ def test_estimated_document_count_splits_by_receipt_date(): "rows": [ {"sheet": "Receipt", "row_no": 1, "doc_no": "HOM-A", "lot_no": "LOT-A", "material_code": "MAT-001", "material_name": "连接器组件", "specification": "A 型 / 24PIN", - "movement_date": "2026-08-04", "quantity": "600", "unit": "个", "source_code": "DBS-AWSBI"}, + "movement_date": "2026-08-03", "quantity": "600", "unit": "个", "source_code": "DBS-AWSBI"}, {"sheet": "Receipt", "row_no": 2, "doc_no": "HOM-B", "lot_no": "LOT-B", "material_code": "MAT-001", "material_name": "连接器组件", "specification": "A 型 / 24PIN", - "movement_date": "2026-08-05", "quantity": "600", "unit": "个", "source_code": "DBS-AWSBI"}, + "movement_date": "2026-08-04", "quantity": "600", "unit": "个", "source_code": "DBS-AWSBI"}, ], }) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-A", "600") erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-B", "600") seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") result = run_matching( - source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub" ) assert result.summary.counts.executable_count == 2 assert result.summary.estimated_external_write_count == 2 -def test_same_day_receipt_not_matured_no_erp_call(same_day_receipt_file): - """当天收料 → not_matured,外部系统 调用次数为 0。""" - deps, erp, _ = _deps(same_day_receipt_file) +def test_same_day_data_not_matched_before_maturity(same_day_inbound_file): + """【T−2 成熟封顶 2026-10-21】当天(T)异动未成熟:不进匹配、不发起外部查询。 + + [断言意图] 圈档封顶 movement_date ≤ T−2(T−2 之前数据全部成熟):当天行留在 + 档内待成熟,不出生 item、不查外部系统(=0);成熟(≤T−2)数据的正常匹配由 + happy path 用例锁定。此前「成熟规则已退役 2026-10-16」放开的当天进匹配语义 + 随 T−2 管控恢复一并收回。 + """ + deps, erp, _ = _deps(same_day_inbound_file) seed_rows_from_file("DBS-AWSSG", deps, "2026-08-06") result = run_matching( - source_codes=["DBS-AWSSG"], business_date="2026-08-06", deps=deps, + source_codes=["DBS-AWSSG"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub" ) - assert result.summary.counts.not_matured_count == 1 assert result.summary.counts.executable_count == 0 - assert result.summary.estimated_external_write_count == 0 + assert result.summary.counts.blocked_count == 0 assert_erp_calls(erp, 0) @@ -143,7 +172,7 @@ def test_quantity_mismatch_blocked_no_write(dbs_ready_file): erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") result = run_matching( - source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub" ) items = {item.invoice_no: item for item in result.items} assert items["HOM-001"].result == "blocked_quantity_mismatch" @@ -158,18 +187,18 @@ def test_erp_inventory_not_found_blocked(dbs_ready_file): erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") # INV-002 无库存 seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") result = run_matching( - source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub" ) items = {item.invoice_no: item for item in result.items} assert items["HOX-002"].result == "blocked_inventory_not_found" def _wtp_lot_file() -> dict: - """构造 WTP 前缀批号的单行收料文件(WMS 原形态落库口径)。""" + """构造 WTP 前缀批号的单行收料文件(WMS 原形态落库口径;异动日期=T−2 成熟边界)。""" return { "source_code": "DBS-AWSBI", "business_date": "2026-08-06", - "file_purpose": "receipt", + "file_purpose": "inbound", "file_no": "REC-20260806-900", "file_version": "v9", "checksum": "e" * 64, @@ -177,7 +206,7 @@ def _wtp_lot_file() -> dict: "rows": [ {"sheet": "Receipt", "row_no": 10, "doc_no": "HOX-900", "lot_no": "WTP26060612", "material_code": "MAT-900", "material_name": "汇流排", "specification": "48V", - "movement_date": "2026-08-05", "quantity": "200", "unit": "PCS", + "movement_date": "2026-08-04", "quantity": "200", "unit": "PCS", "source_code": "DBS-AWSBI"}, ], } @@ -193,7 +222,7 @@ def test_matching_queries_external_lot_form_for_wtp_lot(): deps, erp, _ = _deps(_wtp_lot_file()) erp.seed_stock("MAT-900", "DBS-TRANSIT", "HOW26060612", "200") # ERP 只有 HOW 形态账面 seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - result = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + result = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub") items = {item.invoice_no: item for item in result.items} # [断言意图] 查询目标已派生为 HOW 形态并命中账面 → 行可执行;若回归为原形态 # 直查,本用例将落 blocked_inventory_not_found(生产事故形状)。 @@ -208,7 +237,7 @@ def test_external_query_failure_degrades_to_blocked_item(dbs_ready_file): erp.query_scenario = "error" seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") result = run_matching( - source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub" ) # [断言意图] 外部系统 基础设施故障必须降级为逐单 blocked_external_query_failed: # 来源保持 file_ready,发票全部带原因出现在列表里,而不是来源消失、匹配全 0。 @@ -222,7 +251,7 @@ def test_missing_file_waits_without_erp(): """缺文件 → 来源阶段 waiting_rpa_callback,无 外部系统 调用。""" deps, erp, _ = _deps() result = run_matching( - source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub" ) assert result.sources[0].stage == "waiting_rpa_callback" assert result.summary.status == "file_pending" @@ -236,7 +265,7 @@ def test_source_isolation_dbs_failure_does_not_block_crane(crane_ready_file): erp.seed_stock("MAT-200", "CRANE-SZ-TRANSIT", "LOT-8", "600") seed_rows_from_file("CRANE-SZ", deps, "2026-08-06") result = run_matching( - source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps, + source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub" ) by_source = {stage.source_code: stage for stage in result.sources} assert by_source["DBS-AWSBI"].stage == "failed" @@ -251,8 +280,8 @@ def test_snapshot_hash_is_stable(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") - first = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) - second = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + first = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub") + second = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub") assert first.summary.matching_hash == second.summary.matching_hash @@ -264,7 +293,7 @@ def test_create_and_restore_matching(transfer_db, dbs_ready_file): seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") summary = create_matching( - source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub" ) assert summary.matching_id.startswith("MTG-") restored = restore_matching(summary.matching_id) @@ -276,41 +305,31 @@ def test_create_and_restore_matching(transfer_db, dbs_ready_file): # 落库数量与 DTO 一致(Decimal 文本持久化) assert str(restored_items["HOM-001"].to_quantity) == "1200" # [断言意图] 收料日期与批号必须随明细恢复——聊天卡片收料日期/拨出批号/拨入批号列的数据来源。 - assert restored_items["HOM-001"].receipt_date == "2026-08-05" + assert restored_items["HOM-001"].movement_date == "2026-08-04" assert restored_items["HOM-001"].lot_no == "LOT-10" assert restored_items["HOX-002"].lot_no == "LOT-20" -def test_parse_failure_persists_source_error_visible_on_restore(transfer_db, monkeypatch): - """解析失败 → 来源级 error 落库并经 restore 透出(匹配全 0 复发防线)。 - - [断言意图] CRANE 实况回归(2026-09-21):行缺 doc_no(别名覆盖症状)时 - 整文件 ReceiptFileSchemaError。解析上移 evidence_sync 后(2026-09-25), - 失败在 run_matching STEP 0 兜底对齐时暴露(文件状态投影报告可用文件才 - 会真正解析),失败事实必须持久化到 source_job,恢复后 error_code/ - error_message 仍可见,不得静默呈现为"无错误的全 0"。 - """ +def test_parse_failed_file_reports_source_failure_on_restore(transfer_db, monkeypatch): + """解析失败分层(翻转后):失败事实由落档桥落库(parse_failed 三列);匹配 + 不解析文件,但把 parse_failed 文件的来源如实标 failed 并经 restore 透出。""" deps, _erp, _rpa = make_transfer_deps( { "source_code": "DSV360_AWSDU", "business_date": "2026-09-17", "file_no": "F1", "file_version": "v1", "checksum": "sha:x", - "rows": [{ - # 行缺 doc_no(单号被同名列覆盖时的真实形态) - "sheet": "Movement", "row_no": 1, - "lot_no": "LOT-1", "material_code": "M1", - "quantity": 5, "movement_date": "2026-09-16", - }], + "rows": [], }, routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")}, ) - # STEP 0 对齐的文件状态投影(evidence_sync 命名空间)报告可用文件: - # 行集为空 → sha 不一致 → 触发 sync_source_rows 重解析 → 命中坏行抛错。 + # 文件状态投影报告 parse_failed(桥内 schema 类失败落库后的投影形态): + # 来源阶段转 failed、错误码随 SourceProgress 透出;档照常圈定(无档行=全 0)。 monkeypatch.setattr( - "app.services.in_transit_transfer.evidence_sync.resolve_source_file_status", - lambda *, source_code: {"file_status": "ready", "has_ready_file": True, + "app.services.in_transit_transfer.matching_service.resolve_source_file_status", + lambda *, source_code, record_kind="inbound": {"file_status": "parse_failed", "has_ready_file": False, "file_no": "F1", "file_sha256": "sha:x"}, ) - summary = create_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps) + summary = create_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps, + transfer_type="in_transit_to_hub") assert summary.status == "file_pending" assert summary.counts.file_invoice_count == 0 @@ -322,29 +341,27 @@ def test_parse_failure_persists_source_error_visible_on_restore(transfer_db, mon assert source.error_message -def test_repeated_matching_refreshes_instead_of_accumulating(transfer_db, dbs_ready_file): - """同一数据重复匹配 → 不新增行,既有行原地刷新且归属不变(累加缺陷回归防线)。""" +def test_repeated_matching_never_accumulates(transfer_db, dbs_ready_file): + """同一数据重复匹配 → 圈档互斥(D17):不累加行、不迁移归属(累加缺陷回归防线)。""" from app.models import TransferInvoiceItem, TransferMatching deps, erp, _ = _deps(dbs_ready_file) erp.query_scenario = "error" # 全部阻断:正是此前不断累加"可恢复异常"的场景 seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub") first_count = TransferInvoiceItem.query.count() assert first_count == 2 first_matching = TransferMatching.query.order_by(TransferMatching.id.asc()).first() - old_updated = {row.id: row.updated_at for row in TransferInvoiceItem.query.all()} + frozen = {row.id: row.matching_id for row in TransferInvoiceItem.query.all()} - # [断言意图] 第二次相同匹配必须复用既有行(不出现 2×116 式累加),且行归属 - # 不变、新鲜度被显式续期。2026-09-25 行归属解耦后语义升级为「无归属」: - # 行由证据同步落地(matching_id 恒为 None),匹配只在库存侧字段原地刷新, - # 不迁移、不累加、不改写归属。 - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + # [断言意图] 第二次相同匹配不得累加行(2×116 缺陷防线);出生翻转后行创建 + # 即绑定首匹配,圈档互斥使其圈不到已占用记录 → 归属/行集保持不变。 + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub") assert TransferInvoiceItem.query.count() == first_count assert TransferMatching.query.count() == 2 # 匹配记录照常逐次留痕 for row in TransferInvoiceItem.query.all(): - assert row.matching_id is None # 落地行无匹配归属(原 first_matching.id) - assert row.updated_at > old_updated[row.id] + assert frozen[row.id] == row.matching_id + assert row.matching_id == first_matching.id def test_same_lot_multiple_materials_persist_without_conflict(transfer_db): @@ -356,81 +373,100 @@ def test_same_lot_multiple_materials_persist_without_conflict(transfer_db): "rows": [ {"sheet": "Movement", "row_no": 1, "doc_no": "HOM-1", "lot_no": "ASN-1", "material_code": "M1", "material_name": "物料1", - "quantity": 5, "movement_date": "2026-09-16"}, + "quantity": 5, "movement_date": "2026-09-15"}, {"sheet": "Movement", "row_no": 2, "doc_no": "HOX-2", "lot_no": "ASN-1", "material_code": "M2", "material_name": "物料2", - "quantity": 7, "movement_date": "2026-09-16"}, + "quantity": 7, "movement_date": "2026-09-15"}, ], }, routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")}, ) erp_fake.query_scenario = "error" seed_rows_from_file("DSV360_AWSDU", deps, "2026-09-17") - summary = create_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps) + summary = create_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps, transfer_type="in_transit_to_hub") # [断言意图] 新唯一粒度 = (匹配,来源,单号,料号,日期):同批号多料号必须共存于同一匹配。 assert summary.counts.file_invoice_count == 2 -def test_receipt_date_range_filters_invoices(transfer_db, dbs_ready_file): - """收料日期范围作为匹配查询范围:范围外发票不进入明细。""" +def test_movement_date_range_filters_invoices(transfer_db, dbs_ready_file): + """收料日期范围作为匹配查询范围:范围外发票不进入明细(行日期=T−2 成熟边界)。""" 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") summary = create_matching( source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, - receipt_date_from="2026-08-05", receipt_date_to="2026-08-05", + movement_date_from="2026-08-04", movement_date_to="2026-08-04", transfer_type="in_transit_to_hub" ) assert summary.counts.file_invoice_count == 2 empty = create_matching( source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, - receipt_date_from="2026-08-01", receipt_date_to="2026-08-04", + movement_date_from="2026-08-01", movement_date_to="2026-08-03", transfer_type="in_transit_to_hub" ) assert empty.counts.file_invoice_count == 0 -def test_receipt_date_range_end_beyond_d1_rejected(transfer_db, dbs_ready_file): - """卡控:截止日期超出成熟规则(业务日期-lag,套件钉值 lag=1)必须拒绝。""" +def test_movement_date_range_end_beyond_matured_boundary_rejected(transfer_db, dbs_ready_file): + """卡控(T−2 成熟封顶 2026-10-21):截止晚于 T−2 可匹配截止日必须拒绝。 + + [断言意图] T−2 之前数据全部成熟(简化成熟边界,不回退退役决策)——范围 + 截止 ≤ T−2(2026-08-04)合法,T−1/当天/未来(>T−2)无成熟数据不可选; + 与前端选择器上限(transferDate.ts defaultMovementDate)同口径,越界统一 + TRANSFER.MOVEMENT_DATE_RANGE_INVALID。 + """ from app.core.errors import ValidationError deps, erp, _ = _deps(dbs_ready_file) + seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") with pytest.raises(ValidationError) as exc_info: create_matching( source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, - receipt_date_from="2026-08-04", receipt_date_to="2026-08-06", + movement_date_from="2026-08-04", movement_date_to="2026-08-05", transfer_type="in_transit_to_hub" ) - assert exc_info.value.code == "TRANSFER.RECEIPT_DATE_RANGE_INVALID" + assert exc_info.value.code == "TRANSFER.MOVEMENT_DATE_RANGE_INVALID" + + # [边界] 截止=T−2(2026-08-04)恰好合法:成熟行正常进匹配。 + bounded = create_matching( + source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + movement_date_from="2026-08-04", movement_date_to="2026-08-04", transfer_type="in_transit_to_hub" + ) + assert bounded.counts.file_invoice_count == 2 -def test_t_plus_2_default_boundary_yesterday_not_matured(app, dbs_ready_file): - """生产默认 lag=2 边界:昨天(T-1)收料 not_matured,改到 T-2 后可预检。 +def test_circle_excludes_immature_rows_beyond_t_minus_2(transfer_db): + """圈档 T−2 成熟封顶:T−1/当天行不进匹配(留在档内待成熟),≤T−2 正常圈定。 - [断言意图] 套件 conftest 把 lag 钉为 1(存量夹具语义);本用例显式恢复生产 - 默认 2,锁定真实默认口径不被钉值掩盖(海外时差:28 号最早处理 26 号)。 + [断言意图] 未传范围(积压模式)时 T−1(08-05)/当天(08-06)行也不被圈定 + ——成熟封顶是圈档固定条件,不依赖调用方传范围;两行在次日(业务日前移) + 自然跨过 T−2 后即可进圈。 """ - 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 # 覆盖套件钉值,锁生产默认 - + deps, _erp, _rpa = make_transfer_deps( + { + "source_code": "DSV360_AWSDU", "business_date": "2026-08-06", + "file_no": "F1", "file_version": "v1", "checksum": "sha:x", + "rows": [ + {"sheet": "Movement", "row_no": 1, "doc_no": "HOM-M", "lot_no": "LOT-M", + "material_code": "M1", "material_name": "物料1", + "quantity": 5, "movement_date": "2026-08-04"}, + {"sheet": "Movement", "row_no": 2, "doc_no": "HOM-Y", "lot_no": "LOT-Y", + "material_code": "M2", "material_name": "物料2", + "quantity": 6, "movement_date": "2026-08-05"}, + {"sheet": "Movement", "row_no": 3, "doc_no": "HOM-T", "lot_no": "LOT-T", + "material_code": "M3", "material_name": "物料3", + "quantity": 7, "movement_date": "2026-08-06"}, + ], + }, + routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")}, + ) + seed_rows_from_file("DSV360_AWSDU", deps, "2026-08-06") result = run_matching( - source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + source_codes=["DSV360_AWSDU"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub" ) - # [断言意图] 夹具行收料 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 + invoices = {item.invoice_no for item in result.items} + # [断言意图] 只有 ≤T−2(08-04)的行出生 item;T−1/当天行被圈档封顶排除。 + assert invoices == {"HOM-M"} + assert result.summary.counts.file_invoice_count == 1 def test_route_not_resolved_stays_row_level_not_source_failed(dbs_ready_file): @@ -450,7 +486,7 @@ def test_route_not_resolved_stays_row_level_not_source_failed(dbs_ready_file): ) 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, + source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub" ) by_source = {stage.source_code: stage for stage in result.sources} assert by_source["DBS-AWSBI"].stage == "file_ready" @@ -465,7 +501,7 @@ def test_route_not_resolved_stays_row_level_not_source_failed(dbs_ready_file): def test_run_matching_consumes_movement_field_rows(app): """run_matching 必须按 movement 领域字段(doc_no/quantity)解析真实仓库产出的行。""" # [断言意图] 真实仓库 rows 以 doc_no/material_code/quantity/movement_date 为键; - # 匹配应正确产出 executable 明细而非 ReceiptFileSchemaError + # 匹配应正确产出 executable 明细而非 MovementFileSchemaError # 注:sheet/row_no 为解析校验必带的溯源字段(与 parse_movement_rows 契约一致,同校验)。 deps, erp_fake, _rpa = make_transfer_deps( { @@ -474,14 +510,14 @@ def test_run_matching_consumes_movement_field_rows(app): "rows": [{ "sheet": "Movement", "row_no": 1, "doc_no": "WTP-1", "lot_no": "LOT-1", "material_code": "M1", "material_name": "物料1", - "quantity": 5, "movement_date": "2026-09-16", "unit": "PCS", + "quantity": 5, "movement_date": "2026-09-15", "unit": "PCS", }], }, routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")}, ) erp_fake.seed_stock("M1", "WH1", "LOT-1", 5) # 按 (料号, 拨出库位, 拨出批号) 维护账面库存 seed_rows_from_file("DSV360_AWSDU", deps, "2026-09-17") - result = run_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps) + result = run_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps, transfer_type="in_transit_to_hub") item = next(i for i in result.items if i.invoice_no == "WTP-1") assert item.result == "executable" @@ -491,7 +527,7 @@ def test_run_matching_consumes_movement_field_rows(app): def test_type1_filters_invoices_by_prefix(app): """类型 1(在途仓至HUB仓)只纳入 INVOICE 前缀 HOM/HOX/WTP 的单,范围外静默排除。""" # [断言意图] INV-9 不匹配任何前缀 → 不入明细、不产生 blocked 行; - # HOM/HOX/WTP 前缀单正常走完整匹配(成熟 + 外部系统 匹配)。 + # HOM/HOX/WTP 前缀单正常走完整匹配(日期圈定 + 外部系统 匹配)。 deps, erp_fake, _rpa = make_transfer_deps( { "source_code": "DSV360_AWSDU", "business_date": "2026-09-17", @@ -499,13 +535,13 @@ def test_type1_filters_invoices_by_prefix(app): "rows": [ {"sheet": "Movement", "row_no": 1, "doc_no": "HOM-100", "lot_no": "LOT-1", "material_code": "M1", "material_name": "物料1", - "quantity": 5, "movement_date": "2026-09-16", "unit": "PCS"}, + "quantity": 5, "movement_date": "2026-09-15", "unit": "PCS"}, {"sheet": "Movement", "row_no": 2, "doc_no": "INV-9", "lot_no": "LOT-2", "material_code": "M2", "material_name": "物料2", - "quantity": 6, "movement_date": "2026-09-16", "unit": "PCS"}, + "quantity": 6, "movement_date": "2026-09-15", "unit": "PCS"}, {"sheet": "Movement", "row_no": 3, "doc_no": "WTP-300", "lot_no": "LOT-3", "material_code": "M3", "material_name": "物料3", - "quantity": 7, "movement_date": "2026-09-16", "unit": "PCS"}, + "quantity": 7, "movement_date": "2026-09-15", "unit": "PCS"}, ], }, routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")}, @@ -513,7 +549,7 @@ def test_type1_filters_invoices_by_prefix(app): erp_fake.seed_stock("M1", "WH1", "LOT-1", 5) erp_fake.seed_stock("M3", "WH1", "LOT-3", 7) seed_rows_from_file("DSV360_AWSDU", deps, "2026-09-17") - result = run_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps) + result = run_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps, transfer_type="in_transit_to_hub") invoice_nos = {item.invoice_no for item in result.items} assert invoice_nos == {"HOM-100", "WTP-300"} assert all(item.result == "executable" for item in result.items) @@ -529,7 +565,7 @@ def test_create_matching_persists_transfer_type_on_run_and_scope(transfer_db): "rows": [{ "sheet": "Movement", "row_no": 1, "doc_no": "HOX-1", "lot_no": "LOT-1", "material_code": "M1", "material_name": "物料1", - "quantity": 5, "movement_date": "2026-09-16", + "quantity": 5, "movement_date": "2026-09-15", }], }, routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")}, @@ -546,37 +582,34 @@ def test_create_matching_persists_transfer_type_on_run_and_scope(transfer_db): matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).first() assert run is not None and run.transfer_type == "in_transit_to_hub" scope = matching.scope_json + # [断言意图] scope_json 新键快照(规格 §9.5):范围规则/审计说明/转换规则 + # 随匹配落库(快照自足,展示/重跑/审计不查配置表)。 assert scope["transfer_type"] == "in_transit_to_hub" - assert scope["transfer_type_scope"] == "invoice_prefix:hom+hox+wtp" + assert scope["source_codes"] == ["DSV360_AWSDU"] + assert scope["movement_date_from"] is None and scope["movement_date_to"] is None + assert scope["scope_rules"] == [ + {"field": "doc_no", "match": "prefix", "values": ["HOM", "HOX", "WTP"]}, + ] + assert scope["scope_note"] == "doc_no prefix HOM|HOX|WTP" + assert scope["transform_rules"] == [ + {"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"}, + ] + # [断言意图] hash 与 scope_json 快照内容一致(hash 纪律:从快照内容计算, + # 不引入环境变量/全局态;counts/items 瞬态口径不入 hash)。file_snapshot + # 同为匹配行持久化内容(file_snapshot_json),从行上复算。 + from app.services.in_transit_transfer.audit import canonical_hash + + expected = f"sha256:{canonical_hash({ + **scope, + 'business_date': matching.business_date, + 'file_snapshot': matching.file_snapshot_json, + })}" + assert matching.matching_hash == expected -def test_create_matching_defaults_transfer_type_when_omitted(transfer_db): - """缺省 transfer_type → 类型 1(存量调用方/排程行为不变但纳入前缀过滤)。""" - deps, erp_fake, _rpa = make_transfer_deps( - { - "source_code": "DSV360_AWSDU", "business_date": "2026-09-17", - "file_no": "F1", "file_version": "v1", "checksum": "sha:x", - "rows": [{ - "sheet": "Movement", "row_no": 1, "doc_no": "HOM-1", "lot_no": "LOT-1", - "material_code": "M1", "material_name": "物料1", - "quantity": 5, "movement_date": "2026-09-16", - }], - }, - routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")}, - ) - erp_fake.seed_stock("M1", "WH1", "LOT-1", 5) - seed_rows_from_file("DSV360_AWSDU", deps, "2026-09-17") - summary = create_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps) - from app.models import TransferMatching, TransferRun - - run = TransferRun.query.first() - matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).first() - assert run.transfer_type == "in_transit_to_hub" - assert matching.scope_json["transfer_type"] == "in_transit_to_hub" - - -def test_placeholder_transfer_types_fail_closed(): - """类型 2/3(占位)fail-closed:非法值/未支持类型均 ValidationError,不产生 Run。""" +def test_create_matching_requires_transfer_type(transfer_db): + """缺省 transfer_type → TRANSFER_TYPE_REQUIRED(D8 必填,不回落默认类型)。""" + from app.core.errors import ValidationError from app.models import TransferRun deps, _erp, _rpa = make_transfer_deps( @@ -586,18 +619,67 @@ def test_placeholder_transfer_types_fail_closed(): "rows": [], }, ) - with pytest.raises(ValidationError) as not_supported: + with pytest.raises(ValidationError) as required: + create_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps) + # [断言意图] 必填缺失独立成码(与 NOT_CONFIGURED 区分),且不产生 Run。 + assert required.value.code == "TRANSFER.TRANSFER_TYPE_REQUIRED" + assert TransferRun.query.count() == 0 + + +def test_unknown_transfer_types_fail_closed(): + """未配置类型 fail-closed:无此码(含配置表空)→ NOT_CONFIGURED,不产生 Run。 + + [语义平移] 旧「占位类型 NOT_SUPPORTED / 非法值 INVALID」随配置化退役: + 类型合法值=配置表 code,不存在/停用统一由类型门禁裁定(见 test_transfer_type)。 + """ + from app.models import TransferRun + + deps, _erp, _rpa = make_transfer_deps( + { + "source_code": "DSV360_AWSDU", "business_date": "2026-09-17", + "file_no": "F1", "file_version": "v1", "checksum": "sha:x", + "rows": [], + }, + ) + with pytest.raises(ValidationError) as not_configured: create_matching( source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps, transfer_type="hub_repair_out", ) - assert not_supported.value.code == "TRANSFER.TRANSFER_TYPE_NOT_SUPPORTED" + assert not_configured.value.code == "TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED" with pytest.raises(ValidationError) as invalid: create_matching( source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps, transfer_type="bogus_type", ) - assert invalid.value.code == "TRANSFER.TRANSFER_TYPE_INVALID" + assert invalid.value.code == "TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED" + assert TransferRun.query.count() == 0 + + +def test_create_matching_rejects_disabled_type(transfer_db, monkeypatch): + """停用类型 fail-closed(DISABLED):不产生 Run;排程/重跑走 require_enabled=False。""" + from app.models import TransferRun + + from app import db as _db + + from tests.services.in_transit_transfer.factories import seed_transfer_type_config + + row = seed_transfer_type_config() + row.enabled = False # autouse 种子已建启用行:显式停用(只有停用没有删除) + _db.session.commit() + deps, _erp, _rpa = make_transfer_deps( + { + "source_code": "DSV360_AWSDU", "business_date": "2026-09-17", + "file_no": "F1", "file_version": "v1", "checksum": "sha:x", + "rows": [], + }, + ) + with pytest.raises(ValidationError) as disabled: + create_matching( + source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps, + transfer_type="in_transit_to_hub", + ) + assert disabled.value.code == "TRANSFER.TRANSFER_TYPE_DISABLED" assert TransferRun.query.count() == 0 @@ -607,7 +689,7 @@ def test_evaluation_stamps_inventory_checked_at(dbs_ready_file): 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) + run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub") row = TransferInvoiceItem.query.filter_by( source_code="DBS-AWSBI", invoice_no="HOM-001").first() assert row.status == "ready_to_execute" @@ -627,19 +709,19 @@ def test_executable_list_stale_clock_is_inventory_checked_at(app, dbs_ready_file 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, + movement_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=[], + movement_quantity="1200", external_quantity="1200", lot_no="LOT-10", + movement_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, + movement_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=[], + movement_quantity="1200", external_quantity=None, lot_no="LOT-10", + movement_warehouse_code="W1", unit="PCS", raw_lines_json=[], )) db.session.commit() payload = list_executable_items() @@ -648,3 +730,425 @@ def test_executable_list_stale_clock_is_inventory_checked_at(app, dbs_ready_file assert items["HOX-OLD"].checked_at == old_ts.isoformat() assert items["HOX-NOCHK"].stale is False assert items["HOX-NOCHK"].checked_at is None + + +# ---- 匹配出生:圈档(范围/封存/仓库定义/占用互斥,Task 11 简报 Step 1-2) ---- + +def _seed_ledger_record(doc_no: str, *, material: str = "MAT-LED", quantity: str = "100", + movement_date: str = "2026-08-05", sealed: bool = False, + source_code: str = "DSV360_AWSDU", row_no: int = 1, + record_kind: str = "inbound", carton_id: str = "", + lot_no: str | None = None, file_sha256: str | None = None): + """直接 ORM 种子一条异动档记录(单元测试圈档口径;不依赖文件落地链路)。 + + Args: + record_kind: 档记录类型,缺省 inbound(存量圈档用例)。 + carton_id: 自然键成分(tt14);同 grain 不同 carton 可并存两条档。 + lot_no / file_sha256: 可选覆盖,便于构造 grain 分叉夹具。 + """ + from app.models import TransferMovementLedger + + record = TransferMovementLedger( + source_code=source_code, record_kind=record_kind, + doc_no=doc_no, line_no=str(row_no), line_seq="", in_out_flag="", + carton_id=carton_id, + material_code=material, material_name="档物料", specification="", + lot_no=lot_no if lot_no is not None else f"LOT-{doc_no}", + quantity=quantity, unit="PCS", + warehouse_code="", storage_code="", movement_date=movement_date, + source_file_id=None, file_version="v1", + file_sha256=file_sha256 or ("a" * 64), + sheet_name="Receipt", row_no=row_no, updated_at=datetime.utcnow(), + transfer_executed=sealed, + executed_doc_no="TRF-SEALED" if sealed else None, + ) + db.session.add(record) + db.session.flush() + return record + + +def _insert_ledger(*, source_code: str, record_kind: str, doc_no: str, movement_date: str): + """直接 ORM 落一条异动档(圈档记录类型用例;不走文件落地)。 + + 核心逻辑:复用 _seed_ledger_record 的列口径,只放开 record_kind / 来源 / 单号 / 日期。 + Returns: + TransferMovementLedger 行。 + """ + return _seed_ledger_record( + doc_no, movement_date=movement_date, source_code=source_code, record_kind=record_kind, + ) + + +def _prepare_record_kind_circle_types() -> None: + """启用 hub_to_hub(范围规则不含 record_kind),并给 in_transit_to_hub 写上只要 inbound。 + + 核心逻辑:hub_to_hub 用默认前缀规则(无记录类型 → 入站+出站)。 + in_transit_to_hub 在既有前缀规则上追加 record_kind equals inbound, + 否则同一出站行也会被圈入。 + """ + from app.models import TransferTypeConfig + from tests.services.in_transit_transfer.factories import seed_transfer_type_config + + seed_transfer_type_config() + seed_transfer_type_config("hub_to_hub") + row = db.session.query(TransferTypeConfig).filter_by(code="in_transit_to_hub").one() + rules = [dict(item) for item in (row.scope_rules_json or [])] + if not any(item.get("field") == "record_kind" for item in rules): + rules.append({"field": "record_kind", "match": "equals", "values": ["inbound"]}) + row.scope_rules_json = rules + db.session.commit() + + +def items_of(summary): + """读取本次匹配已圈明细,只暴露 doc_no(行 invoice_no = 档单号)。 + + Args: + summary: create_matching 返回的匹配摘要(matching_id 为匹配编号)。 + Returns: + 带 doc_no 属性的明细列表。 + """ + from types import SimpleNamespace + + from app.models import TransferMatching + + matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).one() + rows = TransferInvoiceItem.query.filter_by(matching_id=matching.id).all() + return [SimpleNamespace(doc_no=row.invoice_no) for row in rows] + + +def test_hub_to_hub_circles_outbound_ledger_rows(deps): + """没有记录类型规则的类型圈入出站档;范围规则写明只要 inbound 的类型不圈。""" + _prepare_record_kind_circle_types() + _insert_ledger(source_code="DSV360_AWSBI", record_kind="outbound", doc_no="HOX1", movement_date="2026-10-14") + inbound_only = create_matching( + source_codes=["DSV360_AWSBI"], + business_date="2026-10-16", + movement_date_from="2026-10-14", + movement_date_to="2026-10-14", + transfer_type="in_transit_to_hub", + deps=deps, + ) + # [断言意图] 先圈只要 inbound 的类型:行尚未被占用,HOX1 因记录类型被排除。 + assert "HOX1" not in {item.doc_no for item in items_of(inbound_only)} + circled = create_matching( + source_codes=["DSV360_AWSBI"], + business_date="2026-10-16", + movement_date_from="2026-10-14", + movement_date_to="2026-10-14", + transfer_type="hub_to_hub", + deps=deps, + ) + # [断言意图] 无 record_kind 规则的启用类型应圈入出站档 HOX1。 + assert "HOX1" in {item.doc_no for item in items_of(circled)} + + +def test_no_data_or_outbound_only_does_not_trigger_inbound_rpa(deps, monkeypatch): + """入站 no_data、或类型不要求入站时,create_matching 不触发入站 RPA。 + + 核心逻辑:投影替身按 record_kind 返回状态。先跑只要 inbound 且入站为 + no_data;再把 hub_to_hub 收成只要 outbound,入站投影改为 none(若入站仍被 + 当作必需,none 会走 ensure 并写入 matching_missing_ready_file)。 + """ + projection = {"inbound": "no_data", "outbound": "ready"} + + def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict: + """按当前 projection 返回该证据流的文件状态。""" + del source_code + state = projection.get(record_kind, "none") + if state == "ready": + return { + "file_status": "ready", "has_ready_file": True, + "file_no": f"{record_kind}-file", "file_sha256": "b" * 64, + } + if state == "no_data": + return { + "file_status": "no_data", "has_ready_file": False, + "file_no": None, "file_sha256": None, + } + return { + "file_status": "none", "has_ready_file": False, + "file_no": None, "file_sha256": None, + } + + monkeypatch.setattr( + "app.services.in_transit_transfer.matching_service.resolve_source_file_status", + _resolve, + ) + _prepare_record_kind_circle_types() + _insert_ledger( + source_code="DSV360_AWSBI", record_kind="inbound", + doc_no="HOM-ND", movement_date="2026-10-14", + ) + inbound_only = create_matching( + source_codes=["DSV360_AWSBI"], + business_date="2026-10-16", + movement_date_from="2026-10-14", + movement_date_to="2026-10-14", + transfer_type="in_transit_to_hub", + deps=deps, + ) + # [断言意图] 入站已确认 no_data:不得写 matching_missing_ready_file,档仍圈入。 + assert deps.rpa_trigger.triggered == [] + assert "HOM-ND" in {item.doc_no for item in items_of(inbound_only)} + + from app.models import TransferTypeConfig + + hub = db.session.query(TransferTypeConfig).filter_by(code="hub_to_hub").one() + rules = [dict(item) for item in (hub.scope_rules_json or [])] + rules.append({"field": "record_kind", "match": "equals", "values": ["outbound"]}) + hub.scope_rules_json = rules + db.session.commit() + projection["inbound"] = "none" + projection["outbound"] = "no_data" + deps.rpa_trigger.triggered.clear() + _insert_ledger( + source_code="DSV360_AWSBI", record_kind="outbound", + doc_no="HOX-OD", movement_date="2026-10-14", + ) + outbound_only = create_matching( + source_codes=["DSV360_AWSBI"], + business_date="2026-10-16", + movement_date_from="2026-10-14", + movement_date_to="2026-10-14", + transfer_type="hub_to_hub", + deps=deps, + ) + # [断言意图] 只要出站、入站缺文件(none)时仍不触发入站 RPA,出站档照常圈入。 + assert deps.rpa_trigger.triggered == [] + assert "HOX-OD" in {item.doc_no for item in items_of(outbound_only)} + + +def test_confirm_matching_syncs_ready_outbound_into_ledger_before_circle(deps, monkeypatch): + """确认匹配时:出站 ready 但档空 → 先幂等落档再圈行(补齐回调未落档窗口)。 + + [断言意图] 不再依赖「仅回调 success 才写档」;create_matching 对 ready 出站 + 流调用 sync_outbound_source_rows,圈出 HOX-MATCH-O1(前缀落在类型范围规则内)。 + """ + import hashlib + + from app.models import ( + FreightRpaOutboundReportConfig, + FreightRpaOutboundReportFile, + FreightRpaOutboundUnitRun, + FreightRpaParsingProfile, + FreightRpaSource, + TransferMovementLedger, + TransferTypeConfig, + ) + from tests.services.in_transit_transfer import factories + + source_code = "DSV360_AWSDU" + storage_key = "shipping/outbound/match-sync.xlsx" + now = datetime.utcnow() + fake_storage = factories.FakeArchiveStorage() + fake_storage.objects[storage_key] = factories.build_movement_xlsx([ + ["HOX-MATCH-O1", "1", "O", "MAT-LED", "成品", "LOT-O1", 80, "2026-10-14"], + ]) + monkeypatch.setattr( + "app.services.file_assets.storage.file_asset_storage.get_bytes", + fake_storage.get_bytes, + ) + # outbound_evidence_sync 直接 import 了 file_asset_storage 单例方法,需同补丁。 + monkeypatch.setattr( + "app.services.in_transit_transfer.outbound_evidence_sync.file_asset_storage.get_bytes", + fake_storage.get_bytes, + ) + + source = FreightRpaSource.query.filter_by(source_code=source_code).one() + profile = FreightRpaParsingProfile( + purpose="outbound", profile_code="OUT_MATCH_SYNC", display_name=source_code, + version=1, status="published", file_format="xlsx", + definition_json={ + "field_mapping": factories.INBOUND_MOVEMENT_FIELD_MAPPING, + "sheet_name": "Receipt", "header_row_index": 1, + }, + structure_definition_json={}, + ) + db.session.add(profile) + db.session.flush() + db.session.add(FreightRpaOutboundReportConfig( + source_id=source.id, + report_path_json={"report_name": "Outbound"}, + query_parameters_json=[], + parsing_profile_id=profile.id, + )) + unit = FreightRpaOutboundUnitRun( + schedule_run_id=None, source_id=source.id, source_code=source_code, + connector_type="dbs", warehouse_id="AWSDU", callback_id="match-sync-out-1", + status="success", config_snapshot_json={}, + ) + db.session.add(unit) + db.session.flush() + digest = hashlib.sha256(b"match sync outbound workbook").hexdigest() + db.session.add(FreightRpaOutboundReportFile( + unit_run_id=unit.id, storage_provider="minio", storage_bucket="test", + storage_key=storage_key, original_filename="match-sync.xlsx", + file_size=16, sha256=digest, created_at=now, + )) + _prepare_record_kind_circle_types() + hub = db.session.query(TransferTypeConfig).filter_by(code="hub_to_hub").one() + # 保留默认前缀规则,只追加「只要 outbound」,避免 ASN 类单号被前缀滤掉。 + rules = [dict(item) for item in (hub.scope_rules_json or [])] + rules = [item for item in rules if item.get("field") != "record_kind"] + rules.append({"field": "record_kind", "match": "equals", "values": ["outbound"]}) + hub.scope_rules_json = rules + db.session.commit() + + assert TransferMovementLedger.query.filter_by( + source_code=source_code, record_kind="outbound").count() == 0 + + summary = create_matching( + source_codes=[source_code], + business_date="2026-10-16", + movement_date_from="2026-10-14", + movement_date_to="2026-10-14", + transfer_type="hub_to_hub", + deps=deps, + ) + + # [断言意图] 匹配前落档:异动档出现 outbound 行,并被圈入本次匹配。 + assert TransferMovementLedger.query.filter_by( + source_code=source_code, record_kind="outbound", doc_no="HOX-MATCH-O1", + ).count() == 1 + assert "HOX-MATCH-O1" in {item.doc_no for item in items_of(summary)} + + +def test_matching_circles_ledger_records_within_scope(transfer_db): + """圈档口径:范围外单(前缀不匹配)与已封存记录不入 items;圈内记录出生绑定档。""" + from app.models import TransferMovementLedger + + deps, erp, _rpa = make_transfer_deps( + { + "source_code": "DSV360_AWSDU", "business_date": "2026-09-17", + "file_no": "F1", "file_version": "v1", "checksum": "sha:x", + "rows": [], + }, + routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")}, + ) + erp.seed_stock("MAT-LED", "WH1", "LOT-HOM-1", "100") + in_scope = _seed_ledger_record("HOM-1") + out_scope = _seed_ledger_record("EXT-9", row_no=2) # 前缀范围外 + sealed = _seed_ledger_record("HOM-2", sealed=True, row_no=3) # 已执行封存 + + result = run_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps, + transfer_type="in_transit_to_hub") + + # [断言意图] items 恰为「范围内未封存」记录:EXT-9 被范围规则排除、HOM-2 被 + # transfer_executed 封存位排除(防二次调拨)。 + invoice_nos = {item.invoice_no for item in result.items} + assert invoice_nos == {"HOM-1"} + assert result.summary.counts.executable_count == 1 + item_row = TransferInvoiceItem.query.filter_by(invoice_no="HOM-1").one() + assert item_row.ledger_record_id == in_scope.id + # 范围外/封存记录零占用(无行引用)。 + assert TransferMovementLedger.query.get(out_scope.id).id not in [ + row.ledger_record_id for row in TransferInvoiceItem.query.all() + ] + + +def test_matching_birth_dedupes_same_grain_ledger_forks(transfer_db): + """同 grain 多档(空 carton + 有 carton 重解析分叉)只出生一行,不撞唯一约束、不翻倍数量。""" + from app.models import TransferMatching + + deps, erp, _rpa = make_transfer_deps( + { + "source_code": "DSV360_AWSDU", "business_date": "2026-09-17", + "file_no": "F1", "file_version": "v1", "checksum": "sha:x", + "rows": [], + }, + routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")}, + ) + erp.seed_stock("D4-A08AR12000002", "WH1", "HOX26021903", "30") + older = _seed_ledger_record( + "HOX26021903", material="D4-A08AR12000002", quantity="30", + movement_date="2026-08-05", lot_no="HOX26021903", carton_id="", + row_no=1, file_sha256="b" * 64, + ) + newer = _seed_ledger_record( + "HOX26021903", material="D4-A08AR12000002", quantity="30", + movement_date="2026-08-05", lot_no="HOX26021903", carton_id="C260219121", + row_no=2, file_sha256="c" * 64, + ) + assert newer.id > older.id + + summary = create_matching( + source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps, + transfer_type="in_transit_to_hub", + ) + # [断言意图] grain 择优有 carton 的较新档;数量仍为 30(不把分叉双行相加)。 + # summary.matching_id 是 matching_no(MTG-…),行上 FK 是整数 matching.id。 + matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).one() + items = TransferInvoiceItem.query.filter_by(matching_id=matching.id).all() + assert len(items) == 1, (summary.counts, TransferInvoiceItem.query.count()) + assert items[0].ledger_record_id == newer.id + assert items[0].movement_quantity == "30" + assert items[0].invoice_no == "HOX26021903" + + # [断言意图] grain 占用互斥:二次匹配圈不到兄弟档,不累加行。 + create_matching( + source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps, + transfer_type="in_transit_to_hub", + ) + assert TransferInvoiceItem.query.filter_by(invoice_no="HOX26021903").count() == 1 + assert TransferMatching.query.count() == 2 + + +def test_matching_routes_fixed_warehouse_from_type_config(transfer_db): + """仓库定义(规格 §7):fixed 角色按类型配置覆盖映射档仓库(from 仍走映射档)。""" + from app import db as _db + + from tests.services.in_transit_transfer.factories import seed_transfer_type_config + + seed_transfer_type_config("hub_repair_out") + deps, erp, _rpa = make_transfer_deps( + { + "source_code": "DSV360_AWSDU", "business_date": "2026-09-17", + "file_no": "F1", "file_version": "v1", "checksum": "sha:x", + "rows": [], + }, + routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")}, + ) + erp.seed_stock("MAT-LED", "WH1", "LOT-HOM-1", "100") + _seed_ledger_record("HOM-1") + # to=fixed WH-REPAIR(覆盖映射档 WH2);from=mapped 透传 WH1。 + config_row = seed_transfer_type_config("hub_repair_out") + config_row.warehouse_config_json = { + "from": {"mode": "mapped", "warehouse_code": None, "external_org": None}, + "to": {"mode": "fixed", "warehouse_code": "WH-REPAIR", "external_org": None}, + } + _db.session.commit() + + result = run_matching(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps, + transfer_type="hub_repair_out") + + item = next(item for item in result.items if item.invoice_no == "HOM-1") + # [断言意图] from 走映射档(mapped 透传),to 按类型 fixed 定义覆盖—— + # 行 from/to 落列与建单分组逻辑不变,类型只改变解析取值来源。 + assert item.from_warehouse == "WH1" + assert item.to_warehouse == "WH-REPAIR" + + +def test_cancel_matching_releases_ledger_occupancy(transfer_db, dbs_ready_file): + """D17 释放出口:取消匹配后(items→cancelled + 匹配→cancelled),记录可被新匹配圈定。""" + from app.models import TransferInvoiceItem, TransferMatching + from app.services.in_transit_transfer.cancellation import cancel_run + + 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") + first = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + transfer_type="in_transit_to_hub") + assert TransferInvoiceItem.query.count() == 2 + + matching_a = TransferMatching.query.filter_by(matching_no=first.matching_id).one() + cancel_run(run_no=matching_a.run.run_no, reason="业务裁定不拨") + + second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + transfer_type="in_transit_to_hub") + # [断言意图] 取消释放占用:匹配 A 的 items→cancelled(不再构成有效占用)、 + # 匹配→cancelled(阻断行亦不占用),记录重新可被匹配 B 圈定(2 行重建)。 + second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one() + born = TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all() + assert len(born) == 2 + assert all(row.status == "ready_to_execute" for row in born) diff --git a/backend/tests/services/in_transit_transfer/test_metrics.py b/backend/tests/services/in_transit_transfer/test_metrics.py index f2318d25..33d9b308 100644 --- a/backend/tests/services/in_transit_transfer/test_metrics.py +++ b/backend/tests/services/in_transit_transfer/test_metrics.py @@ -24,7 +24,7 @@ def test_collect_metrics_counts_runs_and_items(transfer_db, dbs_ready_file, patc 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") - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub") item_ids = [ item.id for item in db.session.query(TransferInvoiceItem) .filter_by(status="ready_to_execute").all() @@ -42,7 +42,7 @@ def test_collect_metrics_backlog_and_notification_failure(transfer_db, dbs_ready erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # mismatch → blocked erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub") item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first() item.updated_at = item.updated_at # 保持默认年龄 db.session.commit() diff --git a/backend/tests/services/in_transit_transfer/test_migration_inbound_rename.py b/backend/tests/services/in_transit_transfer/test_migration_inbound_rename.py new file mode 100644 index 00000000..63a67f9d --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_migration_inbound_rename.py @@ -0,0 +1,177 @@ +"""tt14a5f6a7b8c9 入站化迁移契约测试。 + +用途:锁定 tt14 迁移与模型两侧契约——transfer_invoice_items/transfer_documents + receipt_* 列更名 movement_*(明细/单据方向中立,与异动档 movement_date + 对齐);transfer_movement_ledger.record_kind 值迁移 receipt→inbound / + shipment→outbound;自然键唯一约束重建为 8 成分(追加 carton_id/lot_no)。 +依赖:migrations/versions(it1a2b3c4d5e 建表 → it2c3d4e5f6a7 → tt0d1e2f3a4b → + tt11b2c3d4e5f → tt14)、app_ctx(根 conftest app fixture 上下文别名)。 +逻辑:revision 链断言 + 模型属性/约束成分断言 + SQLite 真实 upgrade/downgrade/ + upgrade 往返(test_migration_widen_transfer_run_type 同款模式)。 +""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +import pytest +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + +pytestmark = pytest.mark.pure_unit + +MIGRATIONS_DIR = Path(__file__).resolve().parents[3] / "migrations" / "versions" + + +@pytest.fixture +def app_ctx(app): + """根 conftest app fixture 的语义别名:app fixture 产出时已处于 app_context 内。""" + return app + + +def _load(revision_prefix: str): + for path in sorted(MIGRATIONS_DIR.glob(f"{revision_prefix}*.py")): + spec = importlib.util.spec_from_file_location(path.stem, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + raise AssertionError(f"migration {revision_prefix} not found") + + +def test_revision_chains_from_mh15_head(): + migration = _load("tt14a5f6a7b8c9") + assert migration.down_revision == "mh15f6a7b8c9" + + +def test_model_inbound_columns_and_ledger_key(app_ctx): + from app.models.in_transit_transfer import ( + TransferDocument, TransferInvoiceItem, TransferMovementLedger, + ) + + item_cols = {c.name for c in TransferInvoiceItem.__table__.columns} + assert {"movement_date", "movement_quantity", "movement_warehouse_code"} <= item_cols + assert not {"receipt_date", "receipt_quantity", "receipt_warehouse_code"} & item_cols + doc_cols = {c.name for c in TransferDocument.__table__.columns} + assert "movement_date" in doc_cols and "receipt_date" not in doc_cols + ledger_uq = next( + c for c in TransferMovementLedger.__table__.constraints + if getattr(c, "name", "") == "uq_transfer_movement_ledger_natural_key" + ) + assert [col.name for col in ledger_uq.columns] == [ + "source_code", "record_kind", "doc_no", "line_no", "line_seq", + "in_out_flag", "carton_id", "lot_no", "external_doc_no", "external_line_no", + ] + # R7 终审 + 2026-10-21 外部身份扩维:进键维度列必须 NOT NULL + default '' + #(nullable 成分的 NULL 不参与 PG/SQLite 唯一比对,会逃逸唯一约束)。 + ledger_cols = {c.name: c for c in TransferMovementLedger.__table__.columns} + for name in ("carton_id", "lot_no", "external_doc_no", "external_line_no"): + assert ledger_cols[name].nullable is False, f"{name} 进键即 NOT NULL" + assert ledger_cols[name].default.arg == '' + assert ledger_cols[name].server_default.arg == '' + + +def _ledger_natural_key(connection) -> list[str]: + """从 SQLite 反射 transfer_movement_ledger 自然键唯一约束的列序。""" + constraints = sa.inspect(connection).get_unique_constraints("transfer_movement_ledger") + for constraint in constraints: + if constraint.get("name") == "uq_transfer_movement_ledger_natural_key": + return list(constraint["column_names"]) + raise AssertionError("uq_transfer_movement_ledger_natural_key not found in SQLite schema") + + +def _item_column_names(connection) -> set[str]: + return {c["name"] for c in sa.inspect(connection).get_columns("transfer_invoice_items")} + + +def _doc_column_names(connection) -> set[str]: + return {c["name"] for c in sa.inspect(connection).get_columns("transfer_documents")} + + +def _ledger_dimension_column(connection, name: str) -> dict: + """从 SQLite 反射 transfer_movement_ledger 维度列(DDL 往返断言用)。""" + columns = {c["name"]: c for c in sa.inspect(connection).get_columns("transfer_movement_ledger")} + assert name in columns + return columns[name] + + +def test_sqlite_roundtrip_upgrade_downgrade_upgrade(): + """SQLite 真实往返:upgrade 更名+扩键 / downgrade 精确还原 / 再 upgrade。 + + [断言意图] 前置链(it1a2b3c4d5e 建表 + it2c3d4e5f6a7 加仓库列 + tt0d1e2f3a4b + 建单表 + tt11b2c3d4e5f 建档表)就位后,tt14 的 batch RENAME 不丢列、自然键 + 唯一约束随往返在 6/8 成分间精确翻转,证明 DDL 可回滚且与模型同构。 + """ + engine = sa.create_engine("sqlite:///:memory:") + with engine.begin() as connection: + context = MigrationContext.configure(connection) + operations = Operations(context) + + # batch copy-and-move 反射时按 FK autoload 目标表:内存库无 Flask 全量 + # 元数据,先建最小 users / shipping_receipt_report_files 桩表满足反射。 + sa.Table( + "users", sa.MetaData(), + sa.Column("id", sa.Integer(), primary_key=True), + ).create(connection) + sa.Table( + "shipping_receipt_report_files", sa.MetaData(), + sa.Column("id", sa.Integer(), primary_key=True), + ).create(connection) + # it2c3d4e5f6a7 同时给库存来源映射表加列(与调拨列无关):建最小桩表承接。 + sa.Table( + "shipping_inventory_external_mappings", sa.MetaData(), + sa.Column("id", sa.Integer(), primary_key=True), + ).create(connection) + + for revision in ("it1a2b3c4d5e", "it2c3d4e5f6a7", "tt0d1e2f3a4b", "tt11b2c3d4e5f"): + base = _load(revision) + base.op = operations + base.upgrade() + + # 前置基线:items/documents 仍是 receipt_* 列,档自然键为 6 成分。 + assert {"receipt_date", "receipt_quantity", "receipt_warehouse_code"} <= _item_column_names(connection) + assert "receipt_date" in _doc_column_names(connection) + assert _ledger_natural_key(connection) == [ + "source_code", "record_kind", "doc_no", "line_no", "line_seq", "in_out_flag", + ] + + migration = _load("tt14a5f6a7b8c9") + migration.op = operations + + migration.upgrade() + item_cols = _item_column_names(connection) + assert {"movement_date", "movement_quantity", "movement_warehouse_code"} <= item_cols + assert not {"receipt_date", "receipt_quantity", "receipt_warehouse_code"} & item_cols + assert "movement_date" in _doc_column_names(connection) + assert "receipt_date" not in _doc_column_names(connection) + # [断言意图] 自然键扩 8 成分(真实 WMS 行身份=单据+行+箱/批)。 + assert _ledger_natural_key(connection) == [ + "source_code", "record_kind", "doc_no", "line_no", "line_seq", + "in_out_flag", "carton_id", "lot_no", + ] + # [断言意图] 维度列 NOT NULL + default ''(R7:防 NULL 逃逸唯一比对)。 + for name in ("carton_id", "lot_no"): + column = _ledger_dimension_column(connection, name) + assert column["nullable"] is False + assert "''" in str(column.get("default") or "") + + migration.downgrade() + assert {"receipt_date", "receipt_quantity", "receipt_warehouse_code"} <= _item_column_names(connection) + assert "movement_date" not in _item_column_names(connection) + assert "receipt_date" in _doc_column_names(connection) + assert _ledger_natural_key(connection) == [ + "source_code", "record_kind", "doc_no", "line_no", "line_seq", "in_out_flag", + ] + # [断言意图] downgrade 对称还原:维度列回 nullable=True 且默认值移除。 + for name in ("carton_id", "lot_no"): + column = _ledger_dimension_column(connection, name) + assert column["nullable"] is True + assert "''" not in str(column.get("default") or "") + + migration.upgrade() + assert {"movement_date", "movement_quantity", "movement_warehouse_code"} <= _item_column_names(connection) + assert _ledger_natural_key(connection) == [ + "source_code", "record_kind", "doc_no", "line_no", "line_seq", + "in_out_flag", "carton_id", "lot_no", + ] diff --git a/backend/tests/services/in_transit_transfer/test_migration_widen_transfer_run_type.py b/backend/tests/services/in_transit_transfer/test_migration_widen_transfer_run_type.py new file mode 100644 index 00000000..2c70ad02 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_migration_widen_transfer_run_type.py @@ -0,0 +1,127 @@ +"""transfer_runs.transfer_type 列宽迁移契约测试(终审 I2 修复)。 + +用途:锁定 tt13d4e5f6a7b8 迁移与模型两侧契约——transfer_runs.transfer_type 列宽 + 64(与 transfer_type_configs.code 的 ≤64 上限对齐,消除「33~64 字符 code 建 + 匹配时 transfer_runs 写入超长 → DB 500」的长度错位);迁移链挂 tt12 之后; + SQLite 真实 upgrade/downgrade/upgrade 往返可执行。 +依赖:migrations/versions 迁移脚本(it1a2b3c4d5e 建表 / tt3d4e5f6a7b 加列 / + tt13d4e5f6a7b8 放宽)、app_ctx(根 conftest app fixture 上下文别名)、 + models/in_transit_transfer.TransferRun。 +逻辑:纯元数据断言(模型列宽/server_default/nullable)+ 迁移脚本字面量断言 + (revision 链)+ SQLite 内存库执行断言(upgrade→64 / downgrade→32 / + 再 upgrade→64,server_default 全程保持 'in_transit_to_hub')。 +""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +import pytest +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations + +from app.models.in_transit_transfer import TransferRun + +pytestmark = pytest.mark.pure_unit + +REVISION = "tt13d4e5f6a7b8" +DOWN_REVISION = "tt12c3d4e5f6a7" +MIGRATIONS_DIR = Path(__file__).resolve().parents[3] / "migrations" / "versions" + + +def _migration_path(revision: str) -> Path: + """按 revision 定位迁移文件(命名规则 _.py)。""" + for path in MIGRATIONS_DIR.glob("*.py"): + if path.name.startswith(f"{revision}_"): + return path + raise AssertionError(f"migration file for revision {revision} not found") + + +def _load_migration(revision: str): + """按 revision 加载迁移模块(test_migration_execution 同款,不加载 Flask 应用)。""" + path = _migration_path(revision) + spec = importlib.util.spec_from_file_location(f"migration_{revision}", 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.fixture +def app_ctx(app): + """根 conftest app fixture 的语义别名:app fixture 产出时已处于 app_context 内。""" + return app + + +def test_revision_chains_from_tt12_head(): + """迁移必须存在且挂在 tt12c3d4e5f6a7(实施时实际单 head)之后。""" + text = _migration_path(REVISION).read_text(encoding="utf-8") + assert f"revision = '{REVISION}'" in text + assert f"down_revision = '{DOWN_REVISION}'" in text + + +def test_model_transfer_type_column_widened_to_64(app_ctx): + """模型列宽必须为 64:与 transfer_type_configs.code ≤64 上限对齐(I2 错位根因)。""" + column = TransferRun.__table__.columns["transfer_type"] + assert column.type.length == 64 + assert column.nullable is False + # server_default 保持建列初值:类型配置为空时匹配 fail-closed,Run 默认仍归 + # 「在途仓至HUB仓」(上线 SOP 依赖该默认值,规格 §7)。 + assert column.server_default.arg == "in_transit_to_hub" + + +def _transfer_type_column(connection) -> dict: + """从 SQLite 反射 transfer_runs.transfer_type 列信息(DDL 往返断言用)。""" + columns = {c["name"]: c for c in sa.inspect(connection).get_columns("transfer_runs")} + assert "transfer_type" in columns + return columns["transfer_type"] + + +def test_upgrade_widen_downgrade_restore_roundtrip(app): + """SQLite 真实往返:upgrade 放宽 64 / downgrade 收回 32 / 再 upgrade 回 64。 + + [断言意图] 前置链(it1a2b3c4d5e 建表 + tt3d4e5f6a7b 加列 String(32))就位后, + tt13 的 copy-and-move 批改不丢列、不丢 server_default;列宽随迁移往返精确 + 翻转,证明 DDL 与模型同构且可回滚。 + """ + engine = sa.create_engine("sqlite:///:memory:") + with engine.begin() as connection: + context = MigrationContext.configure(connection) + operations = Operations(context) + + # SQLite batch copy-and-move 反射 transfer_runs 时会 autoload 其 FK 目标表 + # (users.id):内存库无 Flask 全量元数据,先建最小 users 表满足反射。 + sa.Table( + "users", sa.MetaData(), + sa.Column("id", sa.Integer(), primary_key=True), + ).create(connection) + + base = _load_migration("it1a2b3c4d5e") # 建调拨 7 表(无 transfer_type 列) + base.op = operations + base.upgrade() + # 前置加列 String(32):按 tt3d4e5f6a7b 的列字面量手工复刻——该迁移的 + # create_check_constraint 是 PG-only DDL(SQLite 不支持 ALTER 约束,真实 + # 链路该 CHECK 也已随 tt10 移除),与列宽无关,不在本往返范围。 + with operations.batch_alter_table("transfer_runs") as batch_op: + batch_op.add_column(sa.Column( + "transfer_type", sa.String(length=32), + nullable=False, server_default="in_transit_to_hub", + )) + + assert _transfer_type_column(connection)["type"].length == 32 # 前置:初始 32 + + migration = _load_migration(REVISION) + migration.op = operations + + migration.upgrade() + column = _transfer_type_column(connection) + assert column["type"].length == 64 # [断言意图] 放宽至 64 + assert "in_transit_to_hub" in str(column.get("default") or "") # 默认值不丢 + + migration.downgrade() + assert _transfer_type_column(connection)["type"].length == 32 # [断言意图] 收回 32 + + migration.upgrade() + assert _transfer_type_column(connection)["type"].length == 64 # [断言意图] 再放宽 64 diff --git a/backend/tests/services/in_transit_transfer/test_models.py b/backend/tests/services/in_transit_transfer/test_models.py index a6a7794c..d20a3392 100644 --- a/backend/tests/services/in_transit_transfer/test_models.py +++ b/backend/tests/services/in_transit_transfer/test_models.py @@ -73,10 +73,10 @@ def test_run_source_job_item_attempt_roundtrip(transfer_db): material_no="MAT-001", material_name="连接器组件", specification="A 型 / 24PIN", - receipt_date="2026-08-05", + movement_date="2026-08-05", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01", - receipt_quantity="1200", + movement_quantity="1200", external_quantity="1200", status="ready_to_execute", raw_lines_json=[{"sheet": "Receipt", "row_no": 10, "file_version": "v3"}], @@ -123,10 +123,10 @@ def test_invoice_item_unique_per_matching(transfer_db): source_code="DBS-AWSBI", invoice_no=invoice_no, material_no="MAT-001", - receipt_date="2026-08-05", + movement_date="2026-08-05", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01", - receipt_quantity="1200", + movement_quantity="1200", external_quantity="1200", status="ready_to_execute", raw_lines_json=[], @@ -162,9 +162,9 @@ def test_invoice_item_status_check_constraint(transfer_db): transfer_db.session.flush() transfer_db.session.add(TransferInvoiceItem( matching_id=matching.id, source_code="DBS-AWSBI", invoice_no="INV-999", - material_no="MAT-9", receipt_date="2026-08-05", + material_no="MAT-9", movement_date="2026-08-05", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01", - receipt_quantity="1", external_quantity="1", + movement_quantity="1", external_quantity="1", status="no_such_status", raw_lines_json=[], )) with pytest.raises(IntegrityError): diff --git a/backend/tests/services/in_transit_transfer/test_movement_contract.py b/backend/tests/services/in_transit_transfer/test_movement_contract.py index 00d43035..9fd5624e 100644 --- a/backend/tests/services/in_transit_transfer/test_movement_contract.py +++ b/backend/tests/services/in_transit_transfer/test_movement_contract.py @@ -1,10 +1,12 @@ """在途调拨通用异动表领域字段契约测试(L0 纯单元)。 -用途:锁定调拨定死的 11 个通用异动/移动字段契约(领域定死、不配置化, - D4 追加第 11 字段 unit),以及通用异动解析器 parse_movement_rows - 把字段映射到调拨 ParsedReceiptRow。 +用途:锁定调拨定死的通用异动/移动字段契约(领域定死、不配置化;D4 追加第 11 字段 + unit;2026-10-14 调拨类型配置化+库存异动档项目追加 7 个可选维度字段—— + line_seq/specification/order_type/odm_id/odm_name/carton_id/pallet_id), + 以及通用异动解析器 parse_movement_rows 把字段映射到调拨 ParsedMovementRow。 依赖:app.services.in_transit_transfer.movement_contract + file_parser(纯函数)。 -逻辑:字段契约是 immutable 常量;解析只认契约字段,供未来出货/入库 Excel 复用。 +逻辑:字段契约是 immutable 常量;解析只认契约字段,供未来出货/入库 Excel 复用; + 追加字段全部可选非身份,缺列容忍语义由既有 row.get 投影自动继承。 """ from __future__ import annotations @@ -14,11 +16,11 @@ from decimal import Decimal import pytest -from app.services.in_transit_transfer.file_parser import ParsedReceiptRow +from app.services.in_transit_transfer.file_parser import ParsedMovementRow, parse_movement_rows from app.services.in_transit_transfer.movement_contract import ( MOVEMENT_FIELDS, MovementField, - external_lot_no, + movement_field_codes, movement_match_key, movement_quantity_field, movement_identity_fields, @@ -26,14 +28,27 @@ from app.services.in_transit_transfer.movement_contract import ( pytestmark = pytest.mark.pure_unit +# 2026-10-14 扩展追加的可选维度字段(全部 required=False, is_identity=False, +# 按追加顺序排在既有 11 字段之后;Task 10 库存异动档按这些 code 取值)。 +EXTENSION_FIELD_CODES = ( + "line_seq", "specification", "order_type", "odm_id", "odm_name", "carton_id", "pallet_id", +) +# 2026-10-21 扩展追加的外部单据身份字段(外部单号/外部项次=WMS Order #/行号): +# required=False, is_identity=False(不进匹配身份);但作为异动档自然键成分承担 +# 档幂等主键管控(模型 uq_transfer_movement_ledger_natural_key 10 成分)。 +EXTERNAL_IDENTITY_FIELD_CODES = ("external_doc_no", "external_line_no") + def test_movement_fields_contract_is_frozen_and_complete(): - """领域字段契约定死:11 个字段(D4 追加第 11 字段 unit)、名称唯一、不可变。""" - assert len(MOVEMENT_FIELDS) == 11 + """领域字段契约定死:既有 11 字段 + 2026-10-14 扩展 7 可选字段 + 2026-10-21 + 外部单据身份 2 字段、名称唯一、不可变。""" + assert len(MOVEMENT_FIELDS) == 20 codes = {field.code for field in MOVEMENT_FIELDS} assert codes == { "doc_no", "line_no", "in_out_flag", "material_code", "material_name", "warehouse_code", "storage_code", "lot_no", "quantity", "movement_date", "unit", + *EXTENSION_FIELD_CODES, + *EXTERNAL_IDENTITY_FIELD_CODES, } @@ -48,6 +63,69 @@ def test_movement_field_metadata(): assert by_code["movement_date"].value_type == "date" +def test_movement_field_extension_codes_appended_optional_non_identity(): + """2026-10-14 扩展 7 字段:追加在既有 11 字段之后、全部可选非身份的文本字段。 + + Why: 库存异动档(Task 10)需按行留存项序/规格/订单类型/ODM/箱号/栈板号维度; + 追加式演进不得扰动既有 11 字段语义与顺序(unit 仍须在第 11 位)。 + """ + # [断言意图] 追加字段按 EXTENSION_FIELD_CODES 顺序紧随 unit——文件列顺序契约, + # 前端目录展示与既有测试(unit=第 11 字段)都依赖「只追加、不重排」。 + assert [field.code for field in MOVEMENT_FIELDS] == [ + "doc_no", "line_no", "in_out_flag", "material_code", "material_name", + "warehouse_code", "storage_code", "lot_no", "quantity", "movement_date", "unit", + *EXTENSION_FIELD_CODES, + *EXTERNAL_IDENTITY_FIELD_CODES, + ] + by_code = {field.code: field for field in MOVEMENT_FIELDS} + expected_labels = { + "line_seq": "项序", "specification": "规格", "order_type": "订单类型", + "odm_id": "ODM编号", "odm_name": "ODM名称", "carton_id": "箱号", "pallet_id": "栈板号", + } + for code in EXTENSION_FIELD_CODES: + field = by_code[code] + assert field.label == expected_labels[code], code + assert field.value_type == "text", code + # 扩展字段是展示/圈档维度:源文件缺列放行(解析容忍),不参与幂等/匹配键。 + assert field.required is False, code + assert field.is_identity is False, code + + +def test_external_identity_fields_appended_optional_non_matching_identity(): + """2026-10-21 外部单据身份 2 字段(外部单号/外部项次):追加尾部、可选、非匹配身份。 + + Why: CRANE/Lognet 出站报告携带 WMS 自己的单据+行身份,需要与调拨单号 + (doc_no)分开留存并作为异动档自然键成分(档幂等主键管控);匹配 grain + 仍=单号/料号/异动日期,不受外部身份扩维扰动(契约由 + test_identity_and_match_key_unchanged_by_extension 锁定)。 + """ + by_code = {field.code: field for field in MOVEMENT_FIELDS} + expected_labels = {"external_doc_no": "外部单号", "external_line_no": "外部项次"} + # [断言意图] 只追加不重排:外部身份字段排在既有全部字段之后(文件列顺序契约)。 + assert [field.code for field in MOVEMENT_FIELDS][-2:] == list(EXTERNAL_IDENTITY_FIELD_CODES) + for code in EXTERNAL_IDENTITY_FIELD_CODES: + field = by_code[code] + assert field.label == expected_labels[code], code + assert field.value_type == "text", code + # 解析放行空值(存量入站 Profile 未映射时不阻断);不进匹配身份集合。 + assert field.required is False, code + assert field.is_identity is False, code + + +def test_movement_field_codes_include_extension_codes(): + """movement_field_codes() 自动包含全部扩展字段码(管理端字段目录/映射白名单数据源)。""" + codes = movement_field_codes() + assert set(EXTENSION_FIELD_CODES) <= codes + assert codes == {field.code for field in MOVEMENT_FIELDS} + + +def test_identity_and_match_key_unchanged_by_extension(): + """扩展不得渗入匹配身份:幂等键 doc_no、身份集恰为 3 字段、数量字段 quantity。""" + assert movement_match_key() == "doc_no" + assert movement_identity_fields() == {"doc_no", "material_code", "movement_date"} + assert movement_quantity_field() == "quantity" + + def test_match_key_is_doc_no(): """调拨幂等/汇总键为 doc_no(单号)。""" assert movement_match_key() == "doc_no" @@ -64,24 +142,18 @@ def test_identity_fields_cover_match_predicates(): assert {"doc_no", "material_code", "movement_date"} <= ids -def test_external_lot_no_derives_how_from_wtp_prefix(): - """批号外部形态派生:WTP 前缀 → HOW,前缀识别大小写不敏感、余串逐字保留。 +def test_external_lot_no_retired_replaced_by_transform_rules(): + """external_lot_no 硬编码已退役(Task 11):批号外部形态改由类型配置转换规则驱动。 - Why: ERP 账面批号为 HOW 形态,WMS 文件批号为 WTP 形态——不经派生直查必查空 - (2026-09-25 生产实证 13 行假阴性)。前端 transferBatch.ts deriveBatchNo - 为展示侧镜像,两侧行为必须逐字节一致。 + Why: 原硬编码 WTP→HOW 迁移为 field_transforms 引擎 + 匹配快照规则(规格 §8); + 行为回归由 tests/services/in_transit_transfer/test_field_transforms.py 与 + test_matching_service.py 的转换规则接线用例承接,本模块不再持有该函数。 """ - assert external_lot_no("WTP26060612") == "HOW26060612" - assert external_lot_no("wtp26060612") == "HOW26060612" - assert external_lot_no("Wtp26-1") == "HOW26-1" - assert external_lot_no(" WTP26060612 ") == "HOW26060612" + import inspect + + from app.services.in_transit_transfer import movement_contract + + # [断言意图] 函数必须已删除:任何残留调用点会在 import 期/本断言暴露。 + assert not hasattr(movement_contract, "external_lot_no") -def test_external_lot_no_identity_for_non_wtp_and_empty(): - """非 WTP 前缀恒等(HOX/HOW/普通批号不受影响);空值/None 归空串。""" - assert external_lot_no("HOX26051805") == "HOX26051805" - assert external_lot_no("HOW26060612") == "HOW26060612" - assert external_lot_no("LOT-10") == "LOT-10" - assert external_lot_no("") == "" - assert external_lot_no(" ") == "" - assert external_lot_no(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 3340edd8..f1f6d82b 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 @@ -180,4 +180,4 @@ def test_extract_movement_rows_normalizes_ssrs_wrapped_headers(): 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 + assert parsed[0].movement_quantity == 24 diff --git a/backend/tests/services/in_transit_transfer/test_movement_parser.py b/backend/tests/services/in_transit_transfer/test_movement_parser.py index 49c2bce4..71b5a5f0 100644 --- a/backend/tests/services/in_transit_transfer/test_movement_parser.py +++ b/backend/tests/services/in_transit_transfer/test_movement_parser.py @@ -1,9 +1,9 @@ """通用异动表解析器测试(L0 纯单元)。 用途:验证 parse_movement_rows 把通用异动字段(doc_no/line_no/...)映射到 - 调拨 ParsedReceiptRow(invoice_no=doc_no, receipt_quantity=quantity, - receipt_date=movement_date),并保留既有校验(必填/非法值/来源一致)。 -依赖:app.services.in_transit_transfer.movement_parser(纯函数)。 + 调拨 ParsedMovementRow(invoice_no=doc_no, movement_quantity=quantity, + movement_date=movement_date),并保留既有校验(必填/非法值/来源一致)。 +依赖:app.services.in_transit_transfer.file_parser.parse_movement_rows(纯函数)。 逻辑:字段映射后进入既有 file_parser 校验链路,保证下游 invoice_aggregator 不变。 """ @@ -15,8 +15,8 @@ from decimal import Decimal import pytest from app.services.in_transit_transfer.file_parser import ( - ParsedReceiptRow, - ReceiptFileSchemaError, + ParsedMovementRow, + MovementFileSchemaError, parse_movement_rows, ) @@ -46,41 +46,41 @@ def _rows(**overrides) -> list[dict]: def test_valid_movement_row_maps_to_parsed_rows(): - """通用字段映射为调拨行:doc_no→invoice_no、quantity→receipt_quantity、movement_date→receipt_date。""" + """通用字段映射为调拨行:doc_no→invoice_no、quantity→movement_quantity、movement_date→movement_date(tt14 入站化后明细侧同名对齐)。""" parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows()) assert len(parsed) == 1 row = parsed[0] - assert isinstance(row, ParsedReceiptRow) + assert isinstance(row, ParsedMovementRow) assert row.invoice_no == "MOV-001" assert row.material_no == "MAT-001" assert row.material_name == "连接器组件" - assert row.receipt_date == date(2026, 8, 5) - assert row.receipt_quantity == Decimal("500") + assert row.movement_date == date(2026, 8, 5) + assert row.movement_quantity == Decimal("500") assert row.sheet == "Movement" assert row.row_no == 7 def test_missing_doc_no_rejected(): """单号缺失阻断。""" - with pytest.raises(ReceiptFileSchemaError): + with pytest.raises(MovementFileSchemaError): parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(doc_no="")) def test_invalid_quantity_rejected(): """非数字数量阻断。""" - with pytest.raises(ReceiptFileSchemaError): + with pytest.raises(MovementFileSchemaError): parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(quantity="abc")) def test_invalid_movement_date_rejected(): """非法异动日期阻断。""" - with pytest.raises(ReceiptFileSchemaError): + with pytest.raises(MovementFileSchemaError): parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(movement_date="2026/13/99")) def test_source_identity_mismatch_rejected(): """来源身份漂移阻断。""" - with pytest.raises(ReceiptFileSchemaError): + with pytest.raises(MovementFileSchemaError): parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(source_code="CRANE-SZ")) @@ -124,9 +124,9 @@ def test_receiving_in_progress_rows_are_skipped(): def test_unparseable_date_still_fails(): """日期有值但不可解析仍是数据损坏——跳过守卫不得吞掉真正的脏数据。""" corrupted = dict(VALID_MOVEMENT_ROW, row_no=5, doc_no="MOV-300", movement_date="not-a-date") - with pytest.raises(ReceiptFileSchemaError) as exc_info: + with pytest.raises(MovementFileSchemaError) as exc_info: parse_movement_rows(source_code="DBS-AWSBI", rows=[corrupted]) - assert any("invalid_receipt_date" in error.get("reason", "") + assert any("invalid_movement_date" in error.get("reason", "") for error in exc_info.value.details["rows"]) @@ -140,4 +140,4 @@ def test_datetime_cell_and_timed_string_dates_are_accepted(): movement_date="2026-09-08 00:00:00") parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=[datetime_cell, timed_string]) # [断言意图] WMS 报表真实日期形态不能被 ISO 纯日期校验误杀。 - assert [row.receipt_date for row in parsed] == [date(2026, 8, 26), date(2026, 9, 8)] + assert [row.movement_date for row in parsed] == [date(2026, 8, 26), date(2026, 9, 8)] diff --git a/backend/tests/services/in_transit_transfer/test_notification.py b/backend/tests/services/in_transit_transfer/test_notification.py index ca10c1d3..adb16eea 100644 --- a/backend/tests/services/in_transit_transfer/test_notification.py +++ b/backend/tests/services/in_transit_transfer/test_notification.py @@ -25,7 +25,7 @@ def _executed_run(dbs_ready_file, patch_source_file_status): 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") - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub") item_ids = [ item.id for item in db.session.query(TransferInvoiceItem) .filter_by(status="ready_to_execute").all() diff --git a/backend/tests/services/in_transit_transfer/test_orchestrator.py b/backend/tests/services/in_transit_transfer/test_orchestrator.py index 4f4b77e3..66ef5fe4 100644 --- a/backend/tests/services/in_transit_transfer/test_orchestrator.py +++ b/backend/tests/services/in_transit_transfer/test_orchestrator.py @@ -28,7 +28,7 @@ def _ready_items(dbs_ready_file): erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") deps, _, _ = make_transfer_deps(dbs_ready_file, capabilities=erp) seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub") items = ( TransferInvoiceItem.query.filter_by(status="ready_to_execute") .order_by(TransferInvoiceItem.id) diff --git a/backend/tests/services/in_transit_transfer/test_outbound_evidence_sync.py b/backend/tests/services/in_transit_transfer/test_outbound_evidence_sync.py new file mode 100644 index 00000000..dd14eb4c --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_outbound_evidence_sync.py @@ -0,0 +1,235 @@ +"""outbound_evidence_sync:出站证据同步(落档桥)守卫矩阵。 + +用途:锁定出站回调 success 后的解析落档链——①正常路径按 purpose=outbound 已发布 + 规则解析归档、record_kind='outbound' 幂等落档 + 审计事件;②schema 类解析 + 失败把 parse_failed 三列独立落到出站归档文件上(状态投影随之 parse_failed)、 + 一行不落;③无配置/规则未发布或 purpose 不符 → no-op(fail-closed,不落失败 + 标记——规则缺失不是文件错误);④handler 接线:success 事实触发同步。 +依赖:factories(build_movement_xlsx/INBOUND_MOVEMENT_FIELD_MAPPING + FakeArchiveStorage)、 + ledger_sync.movement_file_version、app fixture(全局种子含 DSV360_AWSDU 站点)。 +逻辑:归档字节经假存储注入(monkeypatch file_asset_storage.get_bytes);解析组装 + 与落档口径全部复用入站同一实现(parse_archive_to_ledger_rows / sync_ledger_rows), + 差异仅 record_kind 与规则门禁 purpose='outbound'。 +""" + +from __future__ import annotations + +from datetime import datetime + +import pytest + +from app import db +from app.models import ( + FreightRpaOutboundReportConfig, + FreightRpaOutboundReportFile, + FreightRpaOutboundUnitRun, + FreightRpaParsingProfile, + TransferAuditEvent, + TransferMovementLedger, +) +from app.services.in_transit_transfer.ledger_sync import movement_file_version +from app.services.in_transit_transfer.outbound_evidence_sync import ( + sync_and_commit_for_outbound_callback, +) +from app.services.in_transit_transfer.source_file_status import resolve_source_file_status +from tests.services.in_transit_transfer import factories + +pytestmark = [pytest.mark.usefixtures("app")] + +SOURCE = "DSV360_AWSDU" +# 真实时钟基准:handler/状态投影内部固定取 utcnow(),种子必须同窗口。 +NOW = datetime.utcnow() +STORAGE_KEY = "shipping/outbound/evidence-sync.xlsx" + + +@pytest.fixture +def outbound_storage(monkeypatch): + """归档假存储:替换单例 get_bytes(所有引用方同源)。""" + fake = factories.FakeArchiveStorage() + monkeypatch.setattr( + "app.services.file_assets.storage.file_asset_storage.get_bytes", fake.get_bytes) + return fake + + +def _seed_outbound_world(*, profile_status: str = "published", + profile_purpose: str = "outbound", + bind_profile: bool = True) -> FreightRpaOutboundReportFile: + """出站世界种子:出站配置(绑定解析规则)+ 执行单元 + 当天可用归档文件行。 + + Returns: + 已入库的 FreightRpaOutboundReportFile(字节由用例注入假存储)。 + """ + from app.models import FreightRpaSource + + source = FreightRpaSource.query.filter_by(source_code=SOURCE).one() + profile = None + if bind_profile: + profile = FreightRpaParsingProfile( + purpose=profile_purpose, profile_code=f"OUT_{SOURCE}", display_name=SOURCE, + version=1, status=profile_status, file_format="xlsx", + definition_json={ + "field_mapping": factories.INBOUND_MOVEMENT_FIELD_MAPPING, + "sheet_name": "Receipt", "header_row_index": 1, + }, + structure_definition_json={}, + ) + db.session.add(profile) + db.session.flush() + db.session.add(FreightRpaOutboundReportConfig( + source_id=source.id, + report_path_json={"report_name": "Outbound"}, + query_parameters_json=[], + parsing_profile_id=profile.id if profile is not None else None, + )) + unit = FreightRpaOutboundUnitRun( + schedule_run_id=None, source_id=source.id, source_code=SOURCE, + connector_type="dbs", warehouse_id="AWSDU", callback_id="outbound-sync-001", + status="success", config_snapshot_json={}, + ) + db.session.add(unit) + db.session.flush() + import hashlib + + digest = hashlib.sha256(b"outbound evidence workbook").hexdigest() + report = FreightRpaOutboundReportFile( + unit_run_id=unit.id, storage_provider="minio", storage_bucket="test", + storage_key=STORAGE_KEY, original_filename="outbound-sync.xlsx", + file_size=16, sha256=digest, + # 与 NOW 同刻:保证落在真实业务日新鲜度窗口内(handler/投影同窗口)。 + created_at=NOW, + ) + db.session.add(report) + db.session.commit() + return report + + +def _count_outbound_ledger(source_code: str = SOURCE) -> int: + """该来源 outbound 档行总数。""" + return TransferMovementLedger.query.filter_by( + source_code=source_code, record_kind="outbound").count() + + +def test_outbound_callback_syncs_ledger_rows(outbound_storage): + # [断言意图] 正常路径:success 回调桥把出站归档按 purpose=outbound 规则解析、 + # record_kind='outbound' 幂等落档;溯源(source_file_id/sha)与审计事件齐全。 + report = _seed_outbound_world() + outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([ + ["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"], + ]) + + ok = sync_and_commit_for_outbound_callback(source_code=SOURCE, now=NOW) + + assert ok is True # [断言意图] 落档成功 + assert _count_outbound_ledger() == 1 # [断言意图] 出站行落异动档 + db.session.expire_all() + row = TransferMovementLedger.query.filter_by( + source_code=SOURCE, record_kind="outbound").one() + assert row.doc_no == "ASN-O1" and row.material_code == "MAT-O1" + assert row.quantity == "120" and row.movement_date == "2026-10-16" + assert row.source_file_id == report.id and row.file_sha256 == report.sha256 + # [断言意图] 审计事件带 record_kind=outbound(与入站同 kind、payload 区分流)。 + event = TransferAuditEvent.query.filter_by(event_type="TRANSFER_EVIDENCE_SYNCED").one() + assert event.after_json["record_kind"] == "outbound" + assert event.after_json["inserted"] == 1 + + +def test_outbound_file_version_uses_shared_stamp(outbound_storage): + """出站落档的 file_version 必须是 movement_file_version,不能在本路径另拼。 + + Why: 2026-10-21 DSV AWSFRA01/AWSBICMH01 实测——本路径自行拼接 sha256: 前缀 + 且未按列宽截断,71 字符整批 INSERT 失败,文件仍显示就绪但档里零记录。 + """ + report = _seed_outbound_world() + outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([ + ["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"], + ]) + + ok = sync_and_commit_for_outbound_callback(source_code=SOURCE, now=NOW) + + assert ok is True # [断言意图] 落档成功(不再超长炸批) + db.session.expire_all() + row = TransferMovementLedger.query.filter_by( + source_code=SOURCE, record_kind="outbound").one() + # [断言意图] 落库版本戳等于共享函数对这份摘要的结果,且不超过列宽。 + assert row.file_version == movement_file_version(report.sha256) + assert len(row.file_version) <= 64 + + +def test_outbound_parse_failure_marks_file_and_lands_nothing(outbound_storage): + # [断言意图] 解析失败分层(出站补齐):schema 类失败 → parse_failed 三列独立 + # 落到出站归档文件、零档行;状态投影随之 parse_failed(文件仍可用、供诊断)。 + report = _seed_outbound_world() + # 有料号但单号为空 → missing_invoice_no → 解析必失败(料号空行 2026-10-21 + # 起静默跳过放行,schema 失败路径改由仍受管控的单号缺失触发)。 + outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx( + [["", 100, "O", "MAT-X", "成品", "LOT-X", 30, "2026-10-16"]]) + + ok = sync_and_commit_for_outbound_callback(source_code=SOURCE, now=NOW) + + assert ok is False # [断言意图] 落档失败如实返回 + assert _count_outbound_ledger() == 0 # [断言意图] 一行不落 + db.session.expire_all() + marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one() + assert marked.parse_failed_at is not None # [断言意图] 失败事实落到文件 + assert marked.parse_error_code == "TRANSFER_FILE_SCHEMA_INVALID" + status = resolve_source_file_status(source_code=SOURCE, record_kind="outbound") + assert status["file_status"] == "parse_failed" # [断言意图] 投影不再当 ready + assert status["file_sha256"] == report.sha256 + + +def test_outbound_without_published_outbound_profile_is_noop(outbound_storage): + # [断言意图] 规则门禁(fail-closed):无绑定规则 / 规则未发布 / purpose 不符 + # → 桥 no-op(True=无事可做),零档行且不落解析失败标记——规则缺失不是文件错误。 + for kwargs in ( + {"bind_profile": False}, # 未绑定规则 + {"profile_status": "draft"}, # 规则未发布 + {"profile_purpose": "inbound"}, # purpose 不符(误绑入站规则) + ): + report = _seed_outbound_world(**kwargs) + outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([ + ["ASN-O2", "1", "O", "MAT-O2", "成品", "LOT-O2", 30, "2026-10-16"], + ]) + + ok = sync_and_commit_for_outbound_callback(source_code=SOURCE, now=NOW) + + assert ok is True, kwargs # [断言意图] 无事可做≠失败 + assert _count_outbound_ledger() == 0, kwargs + db.session.expire_all() + assert FreightRpaOutboundReportFile.query.filter_by( + id=report.id).one().parse_failed_at is None, kwargs + # 清场(三门支共用全局种子,互不污染)。 + FreightRpaOutboundReportConfig.query.delete() + FreightRpaOutboundReportFile.query.delete() + FreightRpaOutboundUnitRun.query.delete() + if kwargs.get("bind_profile", True): + FreightRpaParsingProfile.query.filter( + FreightRpaParsingProfile.profile_code == f"OUT_{SOURCE}").delete() + db.session.commit() + + +def test_outbound_handler_success_fact_triggers_sync(outbound_storage): + # [断言意图] handler 接线:outbound success 事实(ok 且 file_id)在任务推进/ + # 提交之后触发证据同步(与入站 handle_inbound_report STEP 4 对称);失败事实 + # 不触发(无文件可解析,桥不得误读他源文件)。 + from app.services.freight_rpa.reports.facts import ReportFact + from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report + + report = _seed_outbound_world() + outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([ + ["ASN-O3", "1", "O", "MAT-O3", "成品", "LOT-O3", 55, "2026-10-16"], + ]) + + handle_outbound_report(ReportFact( + report_kind="outbound", source_code=SOURCE, file_id=report.id, + sha256=report.sha256, ok=True, error_code=None, error_message=None, + unit_run_id=report.unit_run_id, + )) + + assert _count_outbound_ledger() == 1 # [断言意图] 事实驱动落档 + # [断言意图] 失败事实(同一世界、新归档无字节解析路径不触发):行数不增。 + handle_outbound_report(ReportFact( + report_kind="outbound", source_code=SOURCE, file_id=None, + sha256=None, ok=False, error_code="RPA_OUTBOUND_CALLBACK_FAILED", + error_message="export failed", unit_run_id=report.unit_run_id, + )) + assert _count_outbound_ledger() == 1 diff --git a/backend/tests/services/in_transit_transfer/test_outbound_trigger_service.py b/backend/tests/services/in_transit_transfer/test_outbound_trigger_service.py new file mode 100644 index 00000000..a0e5d5c6 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_outbound_trigger_service.py @@ -0,0 +1,316 @@ +"""出站 RPA 触发服务与报表处理函数测试。 + +用途:验证 trigger_outbound_rpa / trigger_outbound_rpa_batch 按来源装配出站 + trigger unit 并调用写者;站点停用 / 出站配置缺失 / 登录连接缺失 fail-closed; + handle_outbound_report 把等待中的 TransferSourceJob 从 waiting_rpa_callback + 推进到 file_ready(无等待任务 no-op,可重入)。 +依赖:app(SQLite)fixture、outbound_trigger_service、outbound_report_handler、 + 既有测试种子(FreightRpaProfile/FreightRpaSource)。 +逻辑:对照 test_inbound_trigger_service;出站配置行挂 FreightRpaOutboundReportConfig; + 写者协议与入站一致(payload= 附加字段);handler 只改调拨等待行,不写新状态。 +""" + +from __future__ import annotations + +import pytest + +from app.models import FreightRpaSource, FreightRpaOutboundReportConfig +from app.services.in_transit_transfer.outbound_trigger_service import ( + trigger_outbound_rpa, + trigger_outbound_rpa_batch, +) + + +@pytest.fixture +def outbound_source(): + """复用种子来源并为其创建出站配置。""" + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first() + assert source is not None + config = FreightRpaOutboundReportConfig( + source_id=source.id, + report_path_json={'program_group': 'Bison', 'report_name': 'Outbound Details'}, + query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False}], + ) + from app import db + + db.session.add(config) + db.session.commit() + return source + + +def test_trigger_outbound_rpa_disabled_source_fails_closed(app): + """来源停用 → ok=False,不写 trigger。""" + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first() + source.enabled = False + from app import db + + db.session.commit() + result = trigger_outbound_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06') + assert result['ok'] is False + assert result['error_code'] == 'RPA_OUTBOUND_CONFIG_MISSING' + + +def test_trigger_outbound_rpa_missing_config_fails_closed(app): + """来源启用但无出站配置 → ok=False。""" + result = trigger_outbound_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06') + assert result['ok'] is False + assert result['error_code'] == 'RPA_OUTBOUND_CONFIG_MISSING' + + +def test_trigger_outbound_rpa_missing_login_fails_closed(app, outbound_source): + """出站配置存在但登录连接停用 → ok=False,不写 trigger。""" + from app import db + + outbound_source.rpa_profile.enabled = False + db.session.commit() + result = trigger_outbound_rpa( + source_code='DSV360_AWSDU', business_date='2026-08-06', + writer=lambda *a, **k: (_ for _ in ()).throw(AssertionError('writer must not be called')), + ) + assert result['ok'] is False + assert result['error_code'] == 'RPA_OUTBOUND_CONFIG_MISSING' + + +def test_trigger_outbound_rpa_writes_batch_trigger(app, outbound_source): + """来源有效 → 写入 trigger 并返回 callback_id / trigger_path。""" + calls = {} + + def fake_writer(run_no, units, payload=None): + calls['run_no'] = run_no + calls['units'] = units + calls['payload'] = payload or {} + return f'/tmp/trigger/{run_no}.json' + + result = trigger_outbound_rpa( + source_code='DSV360_AWSDU', business_date='2026-08-06', + reason='transfer_retry_outbound', writer=fake_writer, + ) + assert result['ok'] is True + assert result['callback_id'] + assert result['trigger_path'].endswith('.json') + assert calls['units'][0]['source_code'] == 'DSV360_AWSDU' + assert calls['units'][0]['warehouse_id'] is None + assert calls['units'][0]['query_parameters_json'] == [ + {'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False}, + ] + assert calls['units'][0]['credential_envelope'] + assert calls['payload']['schema_version'] == 'freight_rpa.outbound.v1' + + +def test_trigger_outbound_rpa_creates_unit_run_before_writing_trigger(app, outbound_source): + """触发必须先落 FreightRpaOutboundUnitRun(awaiting_rpa),否则回调按 callback_id 404。""" + from app.models import FreightRpaOutboundUnitRun + + captured: dict = {} + + def fake_writer(run_no, units, payload=None): + captured['units'] = units + return 'trigger.json' + + outcome = trigger_outbound_rpa( + source_code=outbound_source.source_code, business_date='2026-10-19', + reason='transfer_retry_outbound', writer=fake_writer, + ) + assert outcome['ok'] is True + unit = FreightRpaOutboundUnitRun.query.filter_by(callback_id=outcome['callback_id']).one() + assert unit.status == 'awaiting_rpa' + assert unit.schedule_run_id is None + assert FreightRpaOutboundUnitRun.__table__.columns['schedule_run_id'].nullable is True + assert captured['units'][0]['unit_run_id'] == unit.id + assert unit.trigger_snapshot_json['callback_id'] == unit.callback_id + + +def test_trigger_outbound_rpa_marks_unit_failed_when_trigger_unavailable(app, outbound_source): + """trigger 目录不可用(writer 返回 None)时单元必须标 failed,不留永久 awaiting 幽灵。""" + from app.models import FreightRpaOutboundUnitRun + + outcome = trigger_outbound_rpa( + source_code=outbound_source.source_code, business_date='2026-10-19', + reason='transfer_retry_outbound', writer=lambda *a, **k: None, + ) + assert outcome['ok'] is False + unit = FreightRpaOutboundUnitRun.query.filter_by(source_code=outbound_source.source_code).order_by( + FreightRpaOutboundUnitRun.id.desc()).first() + assert unit.status == 'failed' + assert unit.error_code == 'RPA_OUTBOUND_TRIGGER_UNAVAILABLE' + + +@pytest.fixture +def second_outbound_source(app): + """再造一个启用来源 + 出站配置(批量用例需要多来源)。""" + from app import db + from app.models import FreightRpaOnhandReportConfig, FreightRpaSource, FreightRpaProfile, FreightRpaOutboundReportConfig + + seed = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first() + profile = FreightRpaProfile( + profile_code='DBS_SG_OUT_TEST', display_name='DBS SG Out', connector_type='dbs', + login_url='https://test.invalid/dbs-sg', login_config_json={'auth_mode': 'password'}, + ) + source = FreightRpaSource( + source_code='DSV360_AWSSG', display_name='DBS SG AWSSG', connector_type='dbs', + rpa_profile=profile, + excel_template=seed.excel_template, + warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSSG', + enabled=True, + ) + seed_config = seed.onhand_report_config + FreightRpaOnhandReportConfig( + source=source, + parsing_profile=seed_config.parsing_profile if seed_config is not None else None, + report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'}, + query_parameters_json=[], + ) + db.session.add_all([profile, source]) + db.session.flush() + config = FreightRpaOutboundReportConfig( + source_id=source.id, + report_path_json={'program_group': 'Bison', 'report_name': 'Outbound Details'}, + query_parameters_json=[], + ) + db.session.add(config) + db.session.commit() + return source + + +def test_trigger_outbound_rpa_batch_writes_one_trigger_for_all_units(app, outbound_source, second_outbound_source): + """多来源 → 只写一次 trigger(一个文件 N units),各单元独立 callback_id/unit_run_id。""" + from app.models import FreightRpaOutboundUnitRun + + calls: list = [] + + def fake_writer(run_no, units, payload=None): + calls.append({'run_no': run_no, 'units': units, 'payload': payload or {}}) + return f'/tmp/trigger/{run_no}.json' + + outcome = trigger_outbound_rpa_batch( + source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-19', + reason='transfer_retry_outbound', writer=fake_writer, + ) + assert len(calls) == 1 + assert outcome['ok'] is True and outcome['triggered'] is True + assert calls[0]['run_no'].startswith('TRIG-BATCH-') + assert [u['source_code'] for u in calls[0]['units']] == ['DSV360_AWSDU', 'DSV360_AWSSG'] + assert calls[0]['payload']['schema_version'] == 'freight_rpa.outbound.v1' + callback_ids = {u['callback_id'] for u in calls[0]['units']} + assert len(callback_ids) == 2 + rows = FreightRpaOutboundUnitRun.query.filter(FreightRpaOutboundUnitRun.source_code.in_( + ['DSV360_AWSDU', 'DSV360_AWSSG'])).all() + assert {row.status for row in rows} == {'awaiting_rpa'} + assert all(row.schedule_run_id is None for row in rows) + assert {row.id for row in rows} == {u['unit_run_id'] for u in calls[0]['units']} + + +def test_trigger_outbound_rpa_batch_skips_invalid_source(app, outbound_source): + """单源配置缺失 → 跳过该源并逐源记录 error_code,其余来源照常进 batch trigger。""" + captured: dict = {} + + def fake_writer(run_no, units, payload=None): + captured['units'] = units + return f'/tmp/trigger/{run_no}.json' + + outcome = trigger_outbound_rpa_batch( + source_codes=['DSV360_AWSDU', 'DSV360_NOPE'], business_date='2026-10-19', + writer=fake_writer, + ) + assert outcome['ok'] is True and outcome['triggered'] is True + assert [u['source_code'] for u in captured['units']] == ['DSV360_AWSDU'] + by_code = {item['source_code']: item for item in outcome['results']} + assert by_code['DSV360_AWSDU']['ok'] is True + assert by_code['DSV360_NOPE']['ok'] is False + assert by_code['DSV360_NOPE']['error_code'] == 'RPA_OUTBOUND_CONFIG_MISSING' + + +def test_trigger_outbound_rpa_batch_all_invalid_no_trigger(app): + """全部来源无效 → 不写 trigger,ok=False + RPA_OUTBOUND_NO_TRIGGERABLE_SOURCE。""" + outcome = trigger_outbound_rpa_batch( + source_codes=['DSV360_NOPE'], business_date='2026-10-19', + writer=lambda *a, **k: (_ for _ in ()).throw(AssertionError('writer must not be called')), + ) + assert outcome['ok'] is False and outcome['triggered'] is False + assert outcome['error_code'] == 'RPA_OUTBOUND_NO_TRIGGERABLE_SOURCE' + + +def test_trigger_outbound_rpa_batch_writer_unavailable_marks_all_failed(app, outbound_source, second_outbound_source): + """trigger 目录不可用 → 本批全部单元标 failed,不留永久 awaiting 幽灵。""" + from app.models import FreightRpaOutboundUnitRun + + outcome = trigger_outbound_rpa_batch( + source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-19', + writer=lambda *a, **k: None, + ) + assert outcome['ok'] is False and outcome['triggered'] is False + assert outcome['error_code'] == 'RPA_OUTBOUND_TRIGGER_UNAVAILABLE' + rows = FreightRpaOutboundUnitRun.query.filter(FreightRpaOutboundUnitRun.source_code.in_( + ['DSV360_AWSDU', 'DSV360_AWSSG'])).all() + assert {row.status for row in rows} == {'failed'} + assert {row.error_code for row in rows} == {'RPA_OUTBOUND_TRIGGER_UNAVAILABLE'} + + +def _waiting_job(source_code: str): + """构造一个未落库的 waiting_rpa_callback 来源任务。""" + from app import db + from app.models import TransferRun, TransferSourceJob + + run = TransferRun( + run_no=f'RUN-OUT-{source_code}', + business_date='2026-10-19', + status='preparing_files', + trigger_type='manual', + ) + db.session.add(run) + db.session.flush() + return TransferSourceJob(run_id=run.id, source_code=source_code, status='waiting_rpa_callback') + + +def test_handle_outbound_report_advances_waiting_job_to_file_ready(app): + """ok 事实把等待中的 SourceJob 从 waiting_rpa_callback 推进到 file_ready。""" + from app import db + from app.services.freight_rpa.reports.facts import ReportFact + from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report + + job = _waiting_job('DSV') + db.session.add(job) + db.session.commit() + handle_outbound_report(ReportFact( + report_kind='outbound', source_code='DSV', file_id=42, sha256='abc', ok=True, + )) + db.session.refresh(job) + assert job.status == 'file_ready' + assert job.file_no == '42' + assert job.file_sha256 == 'abc' + + +def test_handle_outbound_report_noop_without_waiting_job(app): + """无等待中的调拨任务:处理函数 no-op,不产生任何调拨来源任务行。""" + from app.models import TransferSourceJob + from app.services.freight_rpa.reports.facts import ReportFact + from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report + + handle_outbound_report(ReportFact( + report_kind='outbound', source_code='DSV', file_id=42, sha256='abc', ok=True, + )) + assert TransferSourceJob.query.filter_by(source_code='DSV').count() == 0 + + +def test_handle_outbound_report_is_reentrant(app): + """第二次投递时该行已离开等待态,不再改(可重入)。""" + from app import db + from app.services.freight_rpa.reports.facts import ReportFact + from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report + + job = _waiting_job('DSV') + db.session.add(job) + db.session.commit() + fact = ReportFact(report_kind='outbound', source_code='DSV', file_id=42, sha256='abc', ok=True) + handle_outbound_report(fact) + db.session.refresh(job) + first_finished = job.finished_at + handle_outbound_report(ReportFact( + report_kind='outbound', source_code='DSV', file_id=99, sha256='zzz', ok=True, + )) + db.session.refresh(job) + assert job.status == 'file_ready' + assert job.file_no == '42' + assert job.file_sha256 == 'abc' + assert job.finished_at == first_finished + diff --git a/backend/tests/services/in_transit_transfer/test_quantity_match.py b/backend/tests/services/in_transit_transfer/test_quantity_match.py index f64cdb91..6f17ac90 100644 --- a/backend/tests/services/in_transit_transfer/test_quantity_match.py +++ b/backend/tests/services/in_transit_transfer/test_quantity_match.py @@ -16,7 +16,7 @@ from app.services.in_transit_transfer.quantity import ( QuantityValidationError, classify_quantity_match, strict_quantities_equal, - validate_receipt_quantity, + validate_inbound_quantity, ) pytestmark = pytest.mark.pure_unit @@ -27,12 +27,12 @@ def test_equal_quantities_are_executable(): assert classify_quantity_match(Decimal("1200"), Decimal("1200")) == "executable" -def test_erp_greater_than_receipt_is_blocked(): +def test_erp_greater_than_inbound_is_blocked(): """外部系统 库存大于收料数量 → 阻断(不允许部分调拨)。""" assert classify_quantity_match(Decimal("1200"), Decimal("1500")) == "blocked_quantity_mismatch" -def test_erp_less_than_receipt_is_blocked(): +def test_erp_less_than_inbound_is_blocked(): """外部系统 库存小于收料数量 → 阻断。""" assert classify_quantity_match(Decimal("1200"), Decimal("800")) == "blocked_quantity_mismatch" @@ -47,27 +47,27 @@ def test_decimal_scale_equality_is_exact(): assert strict_quantities_equal(Decimal("1.0"), Decimal("1.00")) -def test_zero_receipt_quantity_rejected(): +def test_zero_movement_quantity_rejected(): """收料数量为 0 非法。""" with pytest.raises(QuantityValidationError): - validate_receipt_quantity(Decimal("0")) + validate_inbound_quantity(Decimal("0")) -def test_negative_receipt_quantity_rejected(): +def test_negative_movement_quantity_rejected(): """收料数量为负数非法。""" with pytest.raises(QuantityValidationError): - validate_receipt_quantity(Decimal("-5")) + validate_inbound_quantity(Decimal("-5")) def test_non_numeric_quantity_rejected(): """非数字数量非法(解析层不得静默截断)。""" with pytest.raises(QuantityValidationError): - validate_receipt_quantity("abc") + validate_inbound_quantity("abc") def test_string_numeric_quantity_normalized(): """字符串数字归一化为 Decimal 后参与严格比较。""" - assert validate_receipt_quantity("1200") == Decimal("1200") + assert validate_inbound_quantity("1200") == Decimal("1200") assert strict_quantities_equal("1200", Decimal("1200")) diff --git a/backend/tests/services/in_transit_transfer/test_query_inventory_gateway.py b/backend/tests/services/in_transit_transfer/test_query_inventory_gateway.py index 47d62b50..547cd54c 100644 --- a/backend/tests/services/in_transit_transfer/test_query_inventory_gateway.py +++ b/backend/tests/services/in_transit_transfer/test_query_inventory_gateway.py @@ -48,7 +48,7 @@ def _cap_deps(file, gw): def test_query_inventory_routed_through_gateway(app, dbs_ready_file): - """成熟 Invoice 的库存查询经网关;严格数量匹配仍由领域控制。""" + """圈中行的库存查询经网关;严格数量匹配仍由领域控制。""" gw = FakeGateway(inventory={ ("MAT-001", "DBS-TRANSIT", "LOT-10"): "1200", ("MAT-002", "DBS-TRANSIT", "LOT-20"): "1200", @@ -57,7 +57,7 @@ def test_query_inventory_routed_through_gateway(app, dbs_ready_file): seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") result = run_matching( source_codes=["DBS-AWSBI"], business_date="2026-08-06", - deps=deps, run_no="RUN-T", + deps=deps, run_no="RUN-T", transfer_type="in_transit_to_hub" ) # 网关被调用,且携带 query_inventory 能力名与 (external_org, targets) 契约 assert any(capability == "in_transit_transfer.query_inventory" for capability, _, _ in gw.calls) @@ -70,17 +70,21 @@ def test_query_inventory_routed_through_gateway(app, dbs_ready_file): assert item.from_quantity == Decimal("1200") -def test_not_matured_not_queried(app, same_day_receipt_file): - """当天收料(not_matured)不查外部系统——网关零调用。""" +def test_same_day_data_not_queried_before_maturity(app, same_day_inbound_file): + """【T−2 成熟封顶 2026-10-21】当天(T)异动未成熟:不进圈档、不经网关查询。 + + [断言意图] 圈档封顶 movement_date ≤ T−2:当天行不出生 item,网关零调用—— + 日期在圈档入口即构成过滤(此前「成熟退役 2026-10-16」的免查语义随之收回)。 + """ gw = FakeGateway(inventory={}) - deps = _cap_deps(same_day_receipt_file, gw) + deps = _cap_deps(same_day_inbound_file, gw) seed_rows_from_file("DBS-AWSSG", deps, "2026-08-06") result = run_matching( source_codes=["DBS-AWSSG"], business_date="2026-08-06", - deps=deps, run_no="RUN-T", + deps=deps, run_no="RUN-T", transfer_type="in_transit_to_hub" ) assert gw.calls == [] - assert result.items[0].result == "not_matured" + assert result.items == () def test_no_binding_source_fails_but_not_others(app, dbs_ready_file, crane_ready_file): @@ -111,7 +115,7 @@ def test_no_binding_source_fails_but_not_others(app, dbs_ready_file, crane_ready seed_rows_from_file("CRANE-SZ", deps, "2026-08-06") result = run_matching( source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", - deps=deps, run_no="RUN-T", + deps=deps, run_no="RUN-T", transfer_type="in_transit_to_hub" ) # [断言意图] 外部系统基础设施故障降级为逐单 blocked_external_query_failed: # 来源保持 file_ready,发票带原因可见,其余来源(CRANE)不受影响。 diff --git a/backend/tests/services/in_transit_transfer/test_queue_ledger_view.py b/backend/tests/services/in_transit_transfer/test_queue_ledger_view.py new file mode 100644 index 00000000..3ab1fb6d --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_queue_ledger_view.py @@ -0,0 +1,332 @@ +"""首页队列「待匹配」桶与执行门禁改锚测试(Task 12,规格 §10,D16/D17)。 + +用途:锁定两块契约—— + ①「待匹配」桶口径:成熟未占用的出入站全量(不按类型范围过滤); + 可匹配=启用类型范围并集(matchable / matchable_count)。 + 未封存(transfer_executed=false)、无有效 items(D17 占用判定一致)、 + movement_date ≤ T−2;匹配圈定后离开、取消匹配释放后回归;无 item_id。 + ②file_current 门禁改锚(规格 §10):行当前性 = item → 档记录 file_sha256 == + 该来源最新可用文件 sha(档记录无变化即当前——档换版原行更新后行不再因 + 出生戳陈旧误判);行无档关联回退 raw_lines 出生戳(存量兼容)。 +依赖:app fixture、repo_fakes、factories、models、backlog_service、matching_service。 +逻辑:档记录直接 ORM 种子(与 test_requery_scope 同款);匹配走 create_matching + 真链路;来源文件状态投影经 monkeypatch 注入(不触碰收料文件表)。 +""" + +from __future__ import annotations + +from datetime import datetime + +import pytest + +from app import db +from app.models import TransferInvoiceItem, TransferMovementLedger, TransferRun, TransferTypeConfig +from app.services.in_transit_transfer.backlog_service import ( + backlog_summary, + list_pending_match_records, + list_pending_match_records_page, +) +from app.services.in_transit_transfer.matching_service import ( + _item_dto, + create_matching, +) +from tests.services.in_transit_transfer.factories import seed_transfer_type_config +from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps + +pytestmark = [pytest.mark.usefixtures("app")] + +NOW = datetime(2026, 10, 14, 12, 0, 0) + + +def _seed_ledger(doc_no: str, *, quantity: str = "100", lot_no: str = "LOT-1", + sha: str = "a" * 64, row_no: int = 1, source_code: str = "DBS-AWSBI", + record_kind: str = "inbound", movement_date: str | None = "2026-10-13", + transfer_executed: bool = False, executed_doc_no: str | None = None, + external_doc_no: str = "", external_line_no: str = "", + material_code: str = "MAT-1", material_name: str = "物料1"): + """种子一条档记录(缺省=默认类型范围内的收料记录,与 test_requery_scope 同款)。 + + external_doc_no 为空时,待匹配清单不会把该行并进其他外部单。 + """ + row = TransferMovementLedger( + source_code=source_code, record_kind=record_kind, + doc_no=doc_no, line_no=str(row_no), line_seq="", in_out_flag="", + material_code=material_code, material_name=material_name, specification="", + external_doc_no=external_doc_no, external_line_no=external_line_no, + lot_no=lot_no, quantity=quantity, unit="PCS", + warehouse_code="", storage_code="", movement_date=movement_date, + source_file_id=None, file_version="v1", file_sha256=sha, + sheet_name="Receipt", row_no=row_no, updated_at=NOW, + transfer_executed=transfer_executed, executed_doc_no=executed_doc_no, + ) + db.session.add(row) + db.session.flush() + return row + + +def _match_defaults(): + """构造默认 deps + 预置账面(create_matching 真链路;账面=行数量 → ready)。""" + deps, erp, _rpa = make_transfer_deps() + erp.seed_stock("MAT-1", "DBS-TRANSIT", "LOT-1", "100") + return deps + + +def _pending_doc_nos() -> set[str]: + """待匹配桶的单号集合(断言辅助)。""" + return {record.doc_no for record in list_pending_match_records()} + + +def _matchable_doc_nos() -> set[str]: + """待匹配桶里启用类型现在圈得住的单号。""" + return {record.doc_no for record in list_pending_match_records() if record.matchable} + + +# --------------------------------------------------------------------------- +# ①「待匹配」桶口径(D16) +# --------------------------------------------------------------------------- + +def test_pending_match_bucket_lists_unmatched_records(): + """已落档且无任何 items 的收料记录进「待匹配」桶,字段=档只读投影。""" + _seed_ledger("HOM-1", quantity="100") + _seed_ledger("HOM-2", quantity="200", row_no=2) + + records = list_pending_match_records() + + # [断言意图] 桶口径:范围内的未占用收料记录全部在桶(启用类型并集圈档)。 + assert _pending_doc_nos() == {"HOM-1", "HOM-2"} + first = records[0] + # [断言意图] 字段=档只读投影七键(前端只读清单列:单号/料号/名称/收料日期/来源/数量)。 + assert first.ledger_record_id > 0 + assert first.doc_no in {"HOM-1", "HOM-2"} + assert first.material_code == "MAT-1" + assert first.material_name == "物料1" + assert first.movement_date == "2026-10-13" + assert first.source_code == "DBS-AWSBI" + assert first.quantity == "100" + # [断言意图] 不可执行的结构保证:DTO 无 item_id(未做库存核对,不可勾选)。 + assert "item_id" not in type(first).__dataclass_fields__ + + +def test_pending_match_list_rolls_up_quantity_by_external_doc(): + """同一外部单号的多项次合成一行,数量相加;没有外部单号的档行仍逐行留下。""" + _seed_ledger("HOM-1", quantity="1.50", row_no=1, external_doc_no="5975091", external_line_no="0010") + _seed_ledger( + "HOM-1", quantity="2.50", row_no=2, external_doc_no=" 5975091 ", external_line_no="0020", lot_no="LOT-2", + ) + _seed_ledger( + "HOM-9", quantity="4", row_no=3, external_doc_no="5975091", external_line_no="0030", + lot_no="LOT-3", material_code="MAT-9", material_name="另一物料", movement_date="2026-10-12", + ) + _seed_ledger("HOM-2", quantity="7", row_no=4, external_doc_no="5976000", external_line_no="0010", lot_no="LOT-4") + _seed_ledger("HOM-3", quantity="4", row_no=5, lot_no="LOT-5") + _seed_ledger( + "HOM-4", quantity="8", row_no=6, external_doc_no="5975091", external_line_no="0010", + lot_no="LOT-6", source_code="OTHER-SRC", + ) + + records = list_pending_match_records() + rolled = next( + record for record in records + if record.external_doc_no == "5975091" and record.source_code == "DBS-AWSBI" + ) + + # [断言意图] 同一来源、同一记录类型、同一外部单号的项次合成一行,数量相加。 + assert rolled.quantity == "8" + # [断言意图] 内部单号、料号、异动日期在组内不一致时留空,避免显示成其中一笔。 + assert rolled.doc_no == "" + assert rolled.material_code is None + assert rolled.material_name is None + assert rolled.movement_date is None + assert "external_line_no" not in type(rolled).__dataclass_fields__ + assert next(record for record in records if record.external_doc_no == "5976000").quantity == "7" + blank = [record for record in records if not record.external_doc_no] + # [断言意图] 没有外部单号的档不并进别的单。 + assert len(blank) == 1 and blank[0].doc_no == "HOM-3" and blank[0].quantity == "4" + other = next(record for record in records if record.source_code == "OTHER-SRC") + # [断言意图] 不同来源的同一外部单号分开合计。 + assert other.external_doc_no == "5975091" and other.quantity == "8" and other.doc_no == "HOM-4" + assert len(records) == 4 + summary = backlog_summary() + # [断言意图] 首页待匹配、可匹配数字与清单合并后的行数一致,不再按档行计数。 + assert summary.pending_match_count == len(records) + assert summary.matchable_count == len(list_pending_match_records(segment="matchable")) + + page = list_pending_match_records_page(page=1, page_size=2) + # [断言意图] 分页总数是合并后的行数,当前页按合并结果切片。 + assert page.total == 4 and len(page.records) == 2 + + +def test_pending_match_bucket_summary_count(): + """backlog 汇总带 pending_match 计数(首页第 4 张数字卡数据源)。""" + _seed_ledger("HOM-1") + _seed_ledger("HOM-2", row_no=2) + + summary = backlog_summary() + + assert summary.pending_match_count == 2 + + +def test_pending_match_includes_mature_rows_outside_enabled_types(): + """待匹配收全部成熟未占用记录;可匹配只计启用类型范围并集。""" + _seed_ledger("HOM-1") + _seed_ledger("QQQ-1", row_no=2) + + pending = list_pending_match_records() + summary = backlog_summary() + + # [断言意图] 首页待匹配不再按类型范围收窄:范围外的成熟行仍在桶里。 + assert {record.doc_no for record in pending} == {"HOM-1", "QQQ-1"} + # [断言意图] 库存匹配卡的可匹配数只含启用类型罩得住的行。 + assert {record.doc_no for record in pending if record.matchable} == {"HOM-1"} + assert {record.doc_no for record in list_pending_match_records(segment="outside")} == {"QQQ-1"} + assert {record.doc_no for record in list_pending_match_records(segment="matchable")} == {"HOM-1"} + assert summary.pending_match_count == 2 + assert summary.matchable_count == 1 + + +def test_pending_match_bucket_leaves_once_matched(): + """匹配圈定 → 记录被 items 占用,离开待匹配桶(数字卡回落)。""" + _seed_ledger("HOM-1") + deps = _match_defaults() + + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-10-15", + deps=deps, transfer_type="in_transit_to_hub") + + # [断言意图] 记录被匹配 items 占用(D17)→ 离开待匹配桶。 + assert _pending_doc_nos() == set() + + +def test_pending_match_bucket_returns_after_matching_cancelled(): + """取消匹配释放占用(D17)→ 记录回归待匹配桶。""" + _seed_ledger("HOM-1") + deps = _match_defaults() + summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-10-15", + deps=deps, transfer_type="in_transit_to_hub") + assert _pending_doc_nos() == set() + + from app.models import TransferMatching + from app.services.in_transit_transfer.cancellation import cancel_run + + matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).first() + run = db.session.get(TransferRun, matching.run_id) + cancel_run(run_no=run.run_no, reason="test release") + + # [断言意图] 取消释放占用:记录重新可见于待匹配桶(抓到了没匹配的可见性不丢)。 + assert _pending_doc_nos() == {"HOM-1"} + + +def test_pending_match_bucket_excludes_sealed_and_out_of_scope(): + """恒排除已封存与空异动日期;范围外仍留在待匹配,但不算可匹配。""" + _seed_ledger("HOM-1") # 在桶且可匹配 + _seed_ledger("HOM-SEALED", row_no=2, transfer_executed=True, + executed_doc_no="ERP-1") # 已执行封存 + _seed_ledger("HOM-SHIP", row_no=3, record_kind="outbound") # 出站,默认类型未钉记录类型 + _seed_ledger("QQQ-1", row_no=4) # 范围外,仍在待匹配 + _seed_ledger("HOM-NODATE", row_no=5, movement_date=None) # 异动日期空值 + + # [断言意图] 待匹配收成熟未占用的出入站;可匹配才按启用类型范围并集收窄。 + assert _pending_doc_nos() == {"HOM-1", "HOM-SHIP", "QQQ-1"} + assert _matchable_doc_nos() == {"HOM-1", "HOM-SHIP"} + + +def test_pending_match_bucket_is_union_of_enabled_type_scopes(): + """可匹配=启用类型范围并集;停用类型不把已落档行移出待匹配。""" + _seed_ledger("HOM-1") # 默认类型(HOM/HOX/WTP 前缀) + _seed_ledger("ZZZ-1", row_no=2) # 第二类型范围 + _seed_ledger("QQQ-1", row_no=3) # 无类型覆盖 + seed_transfer_type_config("hub_repair_out", scope_rules=[ + {"field": "doc_no", "match": "prefix", "values": ["ZZZ"]}, + ]) + + assert _pending_doc_nos() == {"HOM-1", "ZZZ-1", "QQQ-1"} + assert _matchable_doc_nos() == {"HOM-1", "ZZZ-1"} + + # [断言意图] 停用类型即刻退出可匹配并集,待匹配全量保持不变。 + row = db.session.query(TransferTypeConfig).filter_by(code="hub_repair_out").one() + row.enabled = False + db.session.commit() + assert _pending_doc_nos() == {"HOM-1", "ZZZ-1", "QQQ-1"} + assert _matchable_doc_nos() == {"HOM-1"} + + # [断言意图] 无启用类型 → 可匹配为空;待匹配仍可见已落档行。 + for cfg in db.session.query(TransferTypeConfig).all(): + cfg.enabled = False + db.session.commit() + assert _matchable_doc_nos() == set() + assert _pending_doc_nos() == {"HOM-1", "ZZZ-1", "QQQ-1"} + # [断言意图] 可匹配段在没有启用类型时走空查询,而不是把全量当成可匹配。 + assert list_pending_match_records(segment="matchable") == [] + + +# --------------------------------------------------------------------------- +# ② file_current 门禁改锚(规格 §10) +# --------------------------------------------------------------------------- + +def _patch_latest_file(monkeypatch, sha_by_source: dict[str, str]): + """注入 matching_service 的来源文件状态投影(source_code → 最新可用文件 sha)。 + + record_kind 入参接受但不区分,存量断言仍按来源比对。 + """ + + def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict: + del record_kind + sha = sha_by_source.get(source_code) + return {"file_status": "ready" if sha else "none", "has_ready_file": bool(sha), + "file_no": "REC-TEST", "file_sha256": sha} + + monkeypatch.setattr( + "app.services.in_transit_transfer.matching_service.resolve_source_file_status", + _resolve, + ) + + +def _seed_ready_item_with_ledger(sha: str = "a" * 64): + """种子档记录 + 可执行 item(raw_lines 出生戳=sha,档记录 sha=sha)。""" + record = _seed_ledger("HOM-1", sha=sha) + item = TransferInvoiceItem( + matching_id=None, run_id=None, ledger_record_id=record.id, + source_code="DBS-AWSBI", invoice_no=record.doc_no, + material_no="MAT-1", material_name="物料1", specification="", + movement_date="2026-10-13", status="ready_to_execute", result_code=None, + from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01", + movement_quantity="100", external_quantity="100", + lot_no="LOT-1", movement_warehouse_code="", unit="PCS", + raw_lines_json=[{"sheet": "Receipt", "row_no": 1, + "file_version": "v1", "file_sha256": sha}], + inventory_checked_at=NOW, + ) + db.session.add(item) + db.session.flush() + return record, item + + +def test_file_current_anchors_to_ledger_record_version(monkeypatch): + """改锚后行当前性=档记录 file_sha256 == 最新可用文件 sha(出生戳不再参与)。""" + record, item = _seed_ready_item_with_ledger(sha="a" * 64) + + dto = _item_dto(item, {"file_sha256": "a" * 64}, NOW, 3600) + assert dto.file_current is True # [断言意图] 档记录持最新文件 sha → 当前 + + # [改锚行为变更] 档换版原行更新(file_sha256→b)而行出生戳仍是 a: + # 旧口径(出生戳 vs 最新)判 False;新口径档记录==最新 → 仍当前。 + record.file_sha256 = "b" * 64 + db.session.flush() + dto = _item_dto(item, {"file_sha256": "b" * 64}, NOW, 3600) + assert dto.file_current is True # [断言意图] 档记录无变化(仍在最新版)即当前 + + # 档记录滞后(最新文件 c,记录仍在 b)→ 行不再当前。 + dto = _item_dto(item, {"file_sha256": "c" * 64}, NOW, 3600) + assert dto.file_current is False # [断言意图] 记录落后最新文件 → stale/blocked 依据 + + +def test_file_current_falls_back_to_birth_stamp_without_ledger(monkeypatch): + """无档关联的隔离历史行回退 raw_lines 出生戳(存量兼容口径)。""" + _record, item = _seed_ready_item_with_ledger(sha="a" * 64) + item.ledger_record_id = None + db.session.flush() + + dto = _item_dto(item, {"file_sha256": "a" * 64}, NOW, 3600) + assert dto.file_current is True # [断言意图] 回退出生戳:出生版本==最新 → 当前 + + dto = _item_dto(item, {"file_sha256": "b" * 64}, NOW, 3600) + assert dto.file_current is False # [断言意图] 回退出生戳:版本落后 → 不当前 diff --git a/backend/tests/services/in_transit_transfer/test_receipt_file_parser.py b/backend/tests/services/in_transit_transfer/test_receipt_file_parser.py deleted file mode 100644 index bd32a88d..00000000 --- a/backend/tests/services/in_transit_transfer/test_receipt_file_parser.py +++ /dev/null @@ -1,151 +0,0 @@ -"""在途调拨收料文件字段/结构校验测试(L0 纯单元)。 - -用途:验证必填列缺失、空值、非法数量(0/负数/非数字)、非法日期与 - 来源身份不一致均整行阻断并抛出 ReceiptFileSchemaError。 -依赖:app.services.in_transit_transfer.file_parser(纯函数)。 -逻辑:解析不接触文件存储;所有错误带行号细节,供预检页展示原因。 -""" - -from __future__ import annotations - -from datetime import date -from decimal import Decimal - -import pytest - -from app.services.in_transit_transfer.file_parser import ( - ParsedReceiptRow, - ReceiptFileSchemaError, - parse_receipt_rows, -) - -pytestmark = pytest.mark.pure_unit - -VALID_ROW = { - "sheet": "Receipt", - "row_no": 10, - "invoice_no": "INV-001", - "material_no": "MAT-001", - "material_name": "连接器组件", - "specification": "A 型 / 24PIN", - "receipt_date": "2026-08-05", - "receipt_quantity": "500", - "source_code": "DBS-AWSBI", -} - - -def _rows(**overrides) -> list[dict]: - """以 VALID_ROW 为基底覆盖字段构造测试行。""" - base = dict(VALID_ROW) - base.update(overrides) - return [base] - - -def test_valid_rows_parse(): - """合法行解析出全部字段(数量 Decimal、日期 date)。""" - parsed = parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows()) - assert len(parsed) == 1 - row = parsed[0] - assert isinstance(row, ParsedReceiptRow) - assert row.invoice_no == "INV-001" - assert row.material_no == "MAT-001" - assert row.material_name == "连接器组件" - assert row.specification == "A 型 / 24PIN" - assert row.receipt_date == date(2026, 8, 5) - assert row.receipt_quantity == Decimal("500") - assert row.sheet == "Receipt" - assert row.row_no == 10 - - -def test_missing_invoice_no_rejected(): - """Invoice No 缺失必须整行阻断。""" - with pytest.raises(ReceiptFileSchemaError): - parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(invoice_no="")) - - -def test_missing_material_no_rejected(): - """料号缺失必须整行阻断。""" - with pytest.raises(ReceiptFileSchemaError): - parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(material_no="")) - - -def test_invalid_quantity_rejected(): - """非数字数量必须阻断。""" - with pytest.raises(ReceiptFileSchemaError): - parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="abc")) - - -def test_zero_quantity_stamped_row_skipped(): - """零数量收料行(日期已盖章、数量 0)为非可用收料事实:跳过不阻断(2026-10-08 CRANE WTP26082227 实测)。""" - parsed = parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="0")) - assert parsed == [] - - -def test_zero_quantity_rows_mixed_with_valid_rows_only_valid_parsed(): - """合法行与零数量行混排:只放行合法行,零数量行不阻断整文件。""" - rows = [ - dict(VALID_ROW, row_no=788, invoice_no="WTP26082227", receipt_quantity="0", - receipt_date="2026-10-01 14:37:43"), - dict(VALID_ROW, row_no=789, invoice_no="INV-002", receipt_quantity="120"), - ] - parsed = parse_receipt_rows(source_code="DBS-AWSBI", rows=rows) - assert [row.row_no for row in parsed] == [789] - assert parsed[0].invoice_no == "INV-002" - - -def test_negative_quantity_rejected(): - """负数数量必须阻断。""" - with pytest.raises(ReceiptFileSchemaError): - parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="-5")) - - -def test_invalid_date_rejected(): - """非法日期必须阻断。""" - with pytest.raises(ReceiptFileSchemaError): - parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_date="2026/13/99")) - - -def test_source_identity_mismatch_rejected(): - """行内来源与任务来源不一致(Callback 身份漂移)必须阻断。""" - with pytest.raises(ReceiptFileSchemaError): - parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(source_code="CRANE-SZ")) - - -def test_missing_sheet_or_row_no_rejected(): - """Sheet/原始行号缺失无法追溯,必须阻断。""" - with pytest.raises(ReceiptFileSchemaError): - parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(sheet="", row_no=0)) - - -def test_material_name_and_specification_optional(): - """品名/规格允许为空(后续由明细 DTO 展示空值)。""" - parsed = parse_receipt_rows( - source_code="DBS-AWSBI", - rows=_rows(material_name="", specification=""), - ) - assert parsed[0].material_name == "" - assert parsed[0].specification == "" - - -def test_error_carries_row_details(): - """错误细节必须携带行号与原因,供页面定位。""" - with pytest.raises(ReceiptFileSchemaError) as excinfo: - parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(row_no=77, receipt_quantity="abc")) - details = excinfo.value.details - assert any(str(item.get("row_no")) == "77" for item in details.get("rows", [])) - - -def test_schema_error_message_carries_row_details(): - """诊断落库:schema 失败消息必须携带前几条行级明细(行号+原因),随 parse_error_message 落库自描述。""" - rows = [ - dict(VALID_ROW, row_no=5, invoice_no=""), - dict(VALID_ROW, row_no=9, receipt_quantity="abc"), - ] - with pytest.raises(ReceiptFileSchemaError) as exc_info: - parse_receipt_rows(source_code="DBS-AWSBI", rows=rows) - # [断言意图] 消息不再只是通用 "receipt file schema invalid",须含行号与原因; - # 明细同时保留在 details.rows 供管理端展示。 - text = str(exc_info.value) or (exc_info.value.message or "") - assert "row 5" in text and "missing_invoice_no" in text - detail_rows = (exc_info.value.details or {}).get("rows") or [] - assert {"row_no": 5, "reason": "missing_invoice_no"} in detail_rows diff --git a/backend/tests/services/in_transit_transfer/test_recovery_service.py b/backend/tests/services/in_transit_transfer/test_recovery_service.py index 665c87fc..3667e4ad 100644 --- a/backend/tests/services/in_transit_transfer/test_recovery_service.py +++ b/backend/tests/services/in_transit_transfer/test_recovery_service.py @@ -23,7 +23,7 @@ def _mixed_matching(dbs_ready_file): erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # mismatch → blocked erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # executable seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub") return deps, erp, summary 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 index a8298828..55b35056 100644 --- a/backend/tests/services/in_transit_transfer/test_requery_batch_query.py +++ b/backend/tests/services/in_transit_transfer/test_requery_batch_query.py @@ -3,6 +3,8 @@ 用途:锁死重查外部访问形态——全部重查入口经 retry_service._recheck_items_batch 按组织分组批量 query_stock(与执行链写前复查同形态);禁止回退逐行单查 (N 行 N 次外部调用会打崩外部系统)。 + 【出生翻转 2026-10-14】行创建即绑定匹配,匹配号重查只触自有 items—— + 行种子显式挂匹配(旧「无归属行 + scope 圈行」语义已退役)。 依赖:app fixture、repo_fakes.make_transfer_deps、models。 逻辑:同组织多行 → 1 次 query_stock 且目标元组一次下传全部行;跨组织 → 每组织 各 1 次;单行路由解析失败只跳过该行(ok=False、行未被触碰、未建 Attempt), @@ -33,8 +35,8 @@ def _seed(scope_sources, matching_no): 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"}, + scope_json={"source_codes": scope_sources, "movement_date_from": None, + "movement_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", @@ -45,14 +47,16 @@ def _seed(scope_sources, matching_no): return matching -def _seed_row(source_code, invoice_no, lot_no): +def _seed_row(source_code, invoice_no, lot_no, matching=None): + """种子一条可重查行(出生翻转后行绑匹配:默认挂当前模块用例的匹配)。""" row = TransferInvoiceItem( - matching_id=None, source_code=source_code, invoice_no=invoice_no, + matching_id=matching.id if matching is not None else 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", + movement_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", + from_warehouse="W-FROM", to_warehouse="W-TO", movement_quantity="36", + external_quantity="30", lot_no=lot_no, movement_warehouse_code="W1", unit="PCS", raw_lines_json=[], ) db.session.add(row) @@ -64,8 +68,8 @@ 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") + row1 = _seed_row("DBS-AWSBI", "HOX-1", "LOT-1", matching=matching) + row2 = _seed_row("DBS-AWSSG", "HOX-2", "LOT-2", matching=matching) 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") @@ -87,8 +91,8 @@ def test_requery_same_org_hits_single_external_call(app): 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") + _seed_row("DBS-AWSBI", "HOX-3", "LOT-3", matching=matching) + _seed_row("DBS-AWSSG", "HOX-4", "LOT-4", matching=matching) 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"), @@ -107,8 +111,8 @@ 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") + good = _seed_row("DBS-AWSBI", "HOX-5", "LOT-5", matching=matching) + bad = _seed_row("GHOST-SRC", "HOX-6", "LOT-6", matching=matching) deps, erp, _ = make_transfer_deps() # GHOST-SRC 未配置路由 → RouteNotResolvedError erp.seed_stock("MAT-1", "DBS-TRANSIT", "LOT-5", "36") @@ -128,7 +132,7 @@ 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 = _seed_row("DBS-AWSBI", "HOX-STALE", "LOT-1", matching=matching) row.inventory_checked_at = datetime(2026, 9, 1, 8, 0, 0) db.session.commit() diff --git a/backend/tests/services/in_transit_transfer/test_requery_scope.py b/backend/tests/services/in_transit_transfer/test_requery_scope.py index f9c0cbf1..b82ad7c2 100644 --- a/backend/tests/services/in_transit_transfer/test_requery_scope.py +++ b/backend/tests/services/in_transit_transfer/test_requery_scope.py @@ -1,12 +1,13 @@ -"""重查圈行口径回归:视图(scope 圈行)能看到的行,重查必须够得着。 +"""重查对档对账回归(出生翻转后语义,规格 §9)。 -用途:锁死 2026-09-24 上午「点重查毫无反应」缺陷——requery_items 曾按 - matching_id 圈行,而行归属解耦后行停在首次创建的匹配上(不迁移), - 今天匹配卡(新 matching)重查恒命中 0 行。 -依赖:app fixture、repo_fakes.make_transfer_deps、models。 -逻辑:造两份同 scope 匹配;行归属旧匹配;经新匹配号重查必须命中该行; - file_removed 行即使可恢复状态也不可重查——匹配号圈行路径由 scope 谓词排除, - 按 id 直取与单行重查路径由 retry_item 的 result_code 兜底拒绝(单点闭环)。 +用途:锁定 requery_items 的对档 reconciliation——按匹配快照规则对档重圈: + 档新增记录 → 补建 item(绑同一匹配);档证据变 → 刷新 item 证据并重置 + 待查;档记录消失 → item 失效隔离(blocked_file_removed 语义); + D17 占用互斥:其他匹配的有效占用不补建(本匹配自有 items 不构成占用); + file_removed 失效行不可重查(按 id 直取与单行入口由 retry_item 兜底拒绝)。 +依赖:app fixture、repo_fakes.make_transfer_deps、factories、models。 +逻辑:直接 ORM 种子档记录 + 匹配(scope_json 带新键快照);断言行级状态与 + 占用互斥;scope_item_query 退役断言在 test_matching_inplace(模块级)。 """ from __future__ import annotations @@ -17,28 +18,63 @@ import pytest from app import db from app.core.errors import ValidationError -from app.models import TransferInvoiceItem, TransferMatching, TransferRun +from app.models import ( + TransferInvoiceItem, + TransferMatching, + TransferMovementLedger, + TransferRun, +) from app.services.in_transit_transfer.retry_service import ( requery_items, requery_items_by_ids, retry_item, ) +from tests.services.in_transit_transfer.factories import seed_transfer_type_config from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps pytestmark = [pytest.mark.usefixtures("app")] +NOW = datetime(2026, 10, 14, 12, 0, 0) -def _seed(scope_sources, business_date, matching_no): + +def _seed_ledger(doc_no: str, *, quantity: str = "100", lot_no: str = "LOT-1", + sha: str = "a" * 64, row_no: int = 1) -> TransferMovementLedger: + """种子一条入站档记录(DBS-AWSBI / inbound / 2026-10-13)。""" + row = TransferMovementLedger( + source_code="DBS-AWSBI", record_kind="inbound", + doc_no=doc_no, line_no=str(row_no), line_seq="", in_out_flag="", + material_code="MAT-1", material_name="物料1", specification="", + lot_no=lot_no, quantity=quantity, unit="PCS", + warehouse_code="", storage_code="", movement_date="2026-10-13", + source_file_id=None, file_version="v1", file_sha256=sha, + sheet_name="Receipt", row_no=row_no, updated_at=NOW, + ) + db.session.add(row) + db.session.flush() + return row + + +def _seed_matching(matching_no: str) -> TransferMatching: + """种子一份匹配(scope_json 携带出生翻转新键快照 + 自有 run)。""" + seed_transfer_type_config() run = TransferRun(run_no=f"RUN-{matching_no}", trigger_type="manual", - business_date=business_date, status="matching", - source_codes_json=scope_sources, counts_json={}, transfer_type="in_transit_to_hub") + business_date="2026-10-14", status="matching", + source_codes_json=["DBS-AWSBI"], 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=business_date, + matching_no=matching_no, run_id=run.id, business_date="2026-10-14", status="success", - scope_json={"source_codes": scope_sources, "receipt_date_from": None, - "receipt_date_to": None, "transfer_type": "in_transit_to_hub"}, + scope_json={ + "transfer_type": "in_transit_to_hub", + "source_codes": ["DBS-AWSBI"], + "movement_date_from": None, + "movement_date_to": None, + "scope_rules": [{"field": "doc_no", "match": "prefix", "values": ["HOM", "HOX", "WTP"]}], + "scope_note": "doc_no prefix HOM|HOX|WTP", + "transform_rules": [], + }, file_snapshot_json={}, mapping_version="v0", strategy_version="v0", counts_json={}, estimated_transfer_quantity="0", estimated_external_write_count=0, matching_hash="sha256:x", @@ -46,101 +82,228 @@ def _seed(scope_sources, business_date, matching_no): ) db.session.add(matching) db.session.flush() - return run, matching + return matching -def _seed_row(matching, invoice_no): +def _seed_own_item(matching: TransferMatching, ledger: TransferMovementLedger) -> TransferInvoiceItem: + """种子匹配自有 item(blocked 可重查态,业务字段=档原值)。""" row = TransferInvoiceItem( - matching_id=matching.id, source_code="CRANE-SZ", invoice_no=invoice_no, - material_no="MAT-1", material_name="n", specification="", - receipt_date="2026-09-20", status="blocked_recoverable", + matching_id=matching.id, run_id=matching.run_id, ledger_record_id=ledger.id, + source_code="DBS-AWSBI", invoice_no=ledger.doc_no, + material_no="MAT-1", material_name="物料1", specification="", + movement_date="2026-10-13", status="blocked_recoverable", result_code="blocked_quantity_mismatch", result_message="strict quantity mismatch", - from_warehouse="HTP-D43", to_warehouse="HTP-D49", receipt_quantity="36", - external_quantity="30", lot_no=invoice_no, receipt_warehouse_code="W1", - unit="PCS", raw_lines_json=[], + from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01", movement_quantity=ledger.quantity, + external_quantity="30", lot_no=ledger.lot_no, movement_warehouse_code="", + unit="PCS", raw_lines_json=[{"sheet": "Receipt", "row_no": ledger.row_no, + "file_version": "v1", "file_sha256": ledger.file_sha256}], ) db.session.add(row) db.session.flush() return row -def test_requery_hits_row_created_under_other_matching(app): - # [断言意图] 行归属匹配 A,经匹配 B(同 scope)发起重查必须命中——scope 口径。 - _, matching_a = _seed(["CRANE-SZ"], "2026-09-24", "MTG-A") - row = _seed_row(matching_a, "HOX-1") - _, matching_b = _seed(["CRANE-SZ"], "2026-09-24", "MTG-B") +def test_requery_births_item_for_new_ledger_record(app): + # [断言意图] 档新增记录 → 重查补建 item(绑同一匹配、待查态、数量=档原值)。 + matching = _seed_matching("MTG-A") + existing = _seed_ledger("HOM-1") + _seed_own_item(matching, existing) + new_record = _seed_ledger("HOM-2", quantity="50", row_no=2) deps, _, _ = make_transfer_deps() - outcome = requery_items(matching_no=matching_b.matching_no, deps=deps, - invoice_nos=["HOX-1"], actor_id="1") + requery_items(matching_no=matching.matching_no, deps=deps, actor_id="1") - assert outcome["total"] == 1 # [断言意图] scope 圈行命中旧匹配的行 - assert outcome["results"][0]["ok"] is True - assert outcome["results"][0]["item_id"] == row.id + born = TransferInvoiceItem.query.filter_by(invoice_no="HOM-2").one() + # [断言意图] 补建行创建即绑定本匹配:matching_id/run_id/ledger_record_id 齐备。 + assert born.matching_id == matching.id + assert born.run_id is None # 执行 Run 关联归 orchestrator + assert born.ledger_record_id == new_record.id + assert born.movement_quantity == "50" + assert born.status == "matching" and born.result_code == "pending_stock_check" # 待查态 -def test_requery_aligns_stale_source_first(app, monkeypatch): - # [断言意图] 行 sha 落后于最新文件时,重查第一步先对齐(兜底语义)。 - called = {} - from app.services.in_transit_transfer import evidence_sync +def test_requery_refreshes_item_when_ledger_evidence_changed(app): + # [断言意图] 档证据变(数量)→ item 证据刷新并重置待查(旧库存作废、 + # external_quantity/inventory_checked_at 置空);展示字段照常刷新。 + matching = _seed_matching("MTG-B") + record = _seed_ledger("HOM-1", quantity="100") + item = _seed_own_item(matching, record) + item.inventory_checked_at = datetime(2026, 10, 14, 10, 0, 0) + db.session.flush() - def _fake_align(**kwargs): - called["sources"] = kwargs.get("source_codes") - return {code: None for code in kwargs.get("source_codes") or []} - - monkeypatch.setattr(evidence_sync, "align_scope_rows", _fake_align) - monkeypatch.setattr( - "app.services.in_transit_transfer.retry_service.align_scope_rows", _fake_align) - _, matching = _seed(["CRANE"], "2026-09-25", "MTG-D") - deps, _, _ = make_transfer_deps() - - requery_items(matching_no=matching.matching_no, deps=deps, invoice_nos=None, actor_id="1") - - assert called.get("sources") == ["CRANE"] # [断言意图] 兜底对齐被前置调用 - - -def test_requery_skips_file_removed_rows(app): - # [断言意图] file_removed 行不允许重查翻回可执行(消失证据不可恢复)。 - _, matching_a = _seed(["CRANE-SZ"], "2026-09-24", "MTG-C") - removed = _seed_row(matching_a, "HOX-RM") - removed.result_code = "blocked_file_removed" - removed.result_message = "receipt row removed from latest file" + record.quantity = "180" # 档证据被新版本替换(原行更新) + record.material_name = "改名物料" + record.file_sha256 = "b" * 64 db.session.flush() deps, _, _ = make_transfer_deps() - outcome = requery_items(matching_no=matching_a.matching_no, deps=deps, - invoice_nos=["HOX-RM"], actor_id="1") + requery_items(matching_no=matching.matching_no, deps=deps, actor_id="1") + + db.session.refresh(item) + assert item.movement_quantity == "180" # [断言意图] 证据刷新 + assert item.material_name == "改名物料" # [断言意图] 展示字段随档换新 + assert item.status == "matching" and item.result_code == "pending_stock_check" # 重置待查 + assert item.external_quantity is None and item.inventory_checked_at is None # 旧库存作废 + + +def test_requery_respects_other_matching_occupancy(app): + # [断言意图] D17 圈档互斥:档记录被「其他匹配」的有效 item 占用时,本匹配 + # 重查不补建;本匹配自有 items 不构成占用(刷新路径不受互斥影响)。 + matching_a = _seed_matching("MTG-A2") + matching_b = _seed_matching("MTG-B2") + record = _seed_ledger("HOM-1") + _seed_own_item(matching_a, record) # 匹配 A 占用 + _seed_ledger("HOM-2", row_no=2) # 无主新记录 + deps, _, _ = make_transfer_deps() + + requery_items(matching_no=matching_b.matching_no, deps=deps, actor_id="1") + + # [断言意图] B 的重查只补建无主记录(HOM-2),不触碰 A 的占用记录(HOM-1 + # 在 B 下无行);自有占用路径由 refresh 用例覆盖。 + assert TransferInvoiceItem.query.filter_by(invoice_no="HOM-1").count() == 1 + born = TransferInvoiceItem.query.filter_by(invoice_no="HOM-2").one() + assert born.matching_id == matching_b.id + + +def test_requery_skips_file_removed_rows(app): + # [断言意图] 失效隔离行(blocked_file_removed)不允许重查翻回可执行 + # (消失证据不可恢复)。 + matching = _seed_matching("MTG-C") + record = _seed_ledger("HOM-1") + removed = _seed_own_item(matching, record) + removed.result_code = "blocked_file_removed" + removed.result_message = "inbound row removed from latest file" + db.session.flush() + deps, _, _ = make_transfer_deps() + + outcome = requery_items(matching_no=matching.matching_no, deps=deps, + invoice_nos=["HOM-1"], actor_id="1") assert outcome["total"] == 0 # [断言意图] 失效行被圈行排除 +def test_requery_aligns_ledger_not_files(app): + # [断言意图] 重查不再对文件兜底对齐(align_scope_rows 已退役): + # 重查入口按档对账,重试模块不再持有对齐入口(属性级断言防回归)。 + from app.services.in_transit_transfer import evidence_sync, retry_service + + assert not hasattr(evidence_sync, "align_scope_rows") + assert not hasattr(retry_service, "align_scope_rows") + + def test_retry_item_rejects_file_removed_row(app): - # [断言意图] 单行重查入口必须拒绝 file_removed 行(消失证据不可恢复, + # [断言意图] 单行重查入口必须拒绝失效隔离行(消失证据不可恢复, # 重查只会用外部系统旧库存把行翻回可执行)。 - _, matching = _seed(["CRANE-SZ"], "2026-09-25", "MTG-E") - row = _seed_row(matching, "HOX-RM2") + matching = _seed_matching("MTG-E") + record = _seed_ledger("HOM-1") + row = _seed_own_item(matching, record) row.result_code = "blocked_file_removed" - row.result_message = "receipt row removed from latest file" + row.result_message = "inbound row removed from latest file" db.session.flush() deps, _, _ = make_transfer_deps() with pytest.raises(ValidationError) as exc: retry_item(item_id=row.id, deps=deps, kind="external_recheck") - assert exc.value.code == "TRANSFER.RETRY_NOT_ALLOWED" # [断言意图] 消失行不可重查 + assert exc.value.code == "TRANSFER.RETRY_NOT_ALLOWED" # [断言意图] 隔离行不可重查 def test_requery_by_ids_rejects_file_removed_row(app): - # [断言意图] 待处理池按 id 直取的批量重查绕过了 scope 圈行谓词——其循环 + # [断言意图] 待处理池按 id 直取的批量重查绕过了对账口径——其循环 # 逐行调 retry_item,单行入口拒绝后此路径必须同步闭环(该行 ok=False)。 - _, matching = _seed(["CRANE-SZ"], "2026-09-25", "MTG-F") - row = _seed_row(matching, "HOX-RM3") + matching = _seed_matching("MTG-F") + record = _seed_ledger("HOM-1") + row = _seed_own_item(matching, record) row.result_code = "blocked_file_removed" - row.result_message = "receipt row removed from latest file" + row.result_message = "inbound row removed from latest file" db.session.flush() deps, _, _ = make_transfer_deps() outcome = requery_items_by_ids(item_ids=[row.id], deps=deps, actor_id="1") assert outcome["total"] == 1 - assert outcome["results"][0]["ok"] is False # [断言意图] 消失行经 by_ids 亦被拒绝 + assert outcome["results"][0]["ok"] is False # [断言意图] 隔离行经 by_ids 亦被拒绝 + + +def test_requery_never_touches_terminal_rows(app): + # [断言意图·Critical-1] 部分行已 SUCCESS 的匹配 + 档证据变化 + 重查: + # SUCCESS 行原样(status/result/updated_at/movement_quantity 均不变,防已执行 + # 行被重置复活 → 二次写 ERP);非终态行照常刷新重置。 + matching = _seed_matching("MTG-T1") + rec1 = _seed_ledger("HOM-1", quantity="100") + rec2 = _seed_ledger("HOM-2", quantity="200", row_no=2) + blocked = _seed_own_item(matching, rec1) # 非终态可重查行 + done = _seed_own_item(matching, rec2) + done.status = "success" + done.result_code = None + done.result_message = None + db.session.flush() + frozen = (done.status, done.result_code, done.result_message, + done.updated_at, done.movement_quantity, done.external_quantity) + + rec1.quantity = "150" # 档证据变化(两行同批) + rec2.quantity = "999" + db.session.flush() + deps, _, _ = make_transfer_deps() + + requery_items(matching_no=matching.matching_no, deps=deps, actor_id="1") + + db.session.expire_all() + done = db.session.get(TransferInvoiceItem, done.id) + blocked = db.session.get(TransferInvoiceItem, blocked.id) + # [断言意图] 终态行零写入:含 updated_at 在内全部字段保持原值。 + assert (done.status, done.result_code, done.result_message, + done.updated_at, done.movement_quantity, done.external_quantity) == frozen + assert done.status == "success" + # [断言意图] 非终态行正常对账:证据刷新 + 重置待查。 + assert blocked.movement_quantity == "150" + assert blocked.status == "matching" and blocked.result_code == "pending_stock_check" + assert blocked.external_quantity is None and blocked.inventory_checked_at is None + + +def test_requery_does_not_rebirth_record_bound_by_terminal_row(app): + # [断言意图·Critical-1 占用面] 档记录已被本匹配终态行绑定时,重查不得补建 + # 第二个 item(否则已执行记录以新待查行复活 → 二次写 ERP)。 + matching = _seed_matching("MTG-T2") + record = _seed_ledger("HOM-1") + done = _seed_own_item(matching, record) + done.status = "success" + done.result_code = None + db.session.flush() + deps, _, _ = make_transfer_deps() + + requery_items(matching_no=matching.matching_no, deps=deps, actor_id="1") + + # [断言意图] 该记录在匹配下恒只有一个绑定行,且仍是原终态行。 + rows = TransferInvoiceItem.query.filter_by(invoice_no="HOM-1").all() + assert len(rows) == 1 and rows[0].id == done.id + assert rows[0].status == "success" + + +def test_requery_tolerates_missing_type_config(app): + # [断言意图·Important-4] 配置表清空后重查:不抛 NOT_CONFIGURED(整次失败), + # 行级降级——既有自有行重查 ok=False(行级错误说明,口径同 _route_for_item), + # 补建行走行级阻断(blocked_route_not_resolved + 配置缺失说明),其余行不受影响。 + matching = _seed_matching("MTG-T3") + from app.models import TransferTypeConfig + + db.session.query(TransferTypeConfig).delete() + db.session.commit() + record = _seed_ledger("HOM-1") + own = _seed_own_item(matching, record) # 既有可重查行 + _seed_ledger("HOM-2", quantity="70", row_no=2) # 待补建的新档记录 + deps, _, _ = make_transfer_deps() + + outcome = requery_items(matching_no=matching.matching_no, deps=deps, actor_id="1") # 不抛 + + # [断言意图] 行级结果而非整体异常:既有行与补建行均 ok=False(行级路由前置 + # 失败,含配置缺失说明),不影响彼此、更不炸整次重查。 + assert outcome["total"] == 2 + by_item = {row["item_id"]: row for row in outcome["results"]} + assert by_item[own.id]["ok"] is False + # [断言意图] 补建行走行级阻断:可解释(配置缺失)、可重查(配置修复后恢复)。 + born = TransferInvoiceItem.query.filter_by(invoice_no="HOM-2").one() + assert born.matching_id == matching.id + assert born.status == "blocked_recoverable" + assert born.result_code == "blocked_route_not_resolved" + assert "transfer type config missing" in (born.result_message or "") 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 deleted file mode 100644 index 0cbf5c4b..00000000 --- a/backend/tests/services/in_transit_transfer/test_restore_file_removed_rows.py +++ /dev/null @@ -1,77 +0,0 @@ -"""存量误标行修复脚本回归(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_restore_scope.py b/backend/tests/services/in_transit_transfer/test_restore_scope.py index cb769008..4e0dfdd1 100644 --- a/backend/tests/services/in_transit_transfer/test_restore_scope.py +++ b/backend/tests/services/in_transit_transfer/test_restore_scope.py @@ -1,86 +1,112 @@ -"""匹配卡 scope 实时视图测试(restore 按 scope 查行 + 行装饰字段,L1)。 +"""匹配卡自有 items 视图测试(restore + 行装饰字段,L1)。 -用途:验证 restore_matching 不再读 matching.items 行归属,而按匹配 scope - (scope_item_query)实时圈定行集,并逐行装饰 item_id / checked_at / - stale / file_current;counts 为 scope 行实时聚合(不读 counts_json 快照)。 +用途:锁定出生翻转后的 restore_matching——匹配卡=自有 items 视图(创建即绑定, + matching_id 圈行;scope_item_query 实时圈行已退役),逐行装饰 item_id / + checked_at / stale / file_current;counts 为自有行实时聚合(不读 counts_json + 快照);展示不查配置表(规格 §13.1,快照自足)。 依赖:transfer_db、matching_service、repo_fakes。 -逻辑:经 create_matching 真实落库构造行状态;行归属(matching_id)保持首次 - 创建值(原地刷新语义),重复匹配的 restore 仍能看到同一批活跃行; - 收料文件状态投影按同款 monkeypatch 替身注入。 +逻辑:经 create_matching 真实落库构造行状态;收料文件状态投影按 monkeypatch + 替身注入;stale 时钟=inventory_checked_at(库存查得时刻,2026-09-29 换源)。 """ from __future__ import annotations from datetime import datetime, timedelta +import pytest + from app import db from app.models import TransferInvoiceItem from app.services.in_transit_transfer import matching_service from app.services.in_transit_transfer.matching_service import create_matching, restore_matching from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps, seed_rows_from_file +pytestmark = [pytest.mark.usefixtures("transfer_db")] + def _file_ready(monkeypatch, dbs_ready_file: dict) -> None: """让来源文件状态投影返回 ready(sha 与 fixture 文件一致,不触碰真实文件表)。""" monkeypatch.setattr( matching_service, "resolve_source_file_status", - lambda *, source_code: {"file_status": "ready", "has_ready_file": True, + lambda *, source_code, record_kind="inbound": {"file_status": "ready", "has_ready_file": True, "file_no": dbs_ready_file["file_no"], "file_sha256": dbs_ready_file["checksum"]}, ) -def test_restore_returns_scope_rows_not_owned_rows(transfer_db, dbs_ready_file, monkeypatch): - """restore 按范围返回实时行:行属于首份匹配,但第二份匹配的 restore 也能看到(实时状态)。""" +def test_restore_returns_own_items(transfer_db, dbs_ready_file, monkeypatch): + """restore 返回匹配自有行(创建即绑定):行装饰三要素齐备,counts 实时聚合。""" _file_ready(monkeypatch, dbs_ready_file) deps, erp, _ = make_transfer_deps(dbs_ready_file) erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) # 行经证据同步落地 - second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + transfer_type="in_transit_to_hub") - detail = restore_matching(second.matching_id, deps=deps) + detail = restore_matching(summary.matching_id, deps=deps) assert {i.invoice_no for i in detail["items"]} == {"HOM-001", "HOX-002"} row = next(i for i in detail["items"] if i.invoice_no == "HOX-002") - # [断言意图] 行装饰三要素:行 id 可追溯(item_id)、刚刷新不陈旧(stale)、 + # [断言意图] 行装饰三要素:行 id 可追溯(item_id)、刚取数不陈旧(stale)、 # 行评估版本戳仍是该来源当前可用文件(file_current)。 assert row.item_id > 0 and row.stale is False and row.file_current is True - # [断言意图] counts 为 scope 行实时聚合(不读 counts_json 快照): - # 2 行 = 1 可执行 + 1 阻断;summary 其余字段沿用匹配记录留痕。 + # [断言意图] counts 为自有行实时聚合(不读 counts_json 快照): + # 2 行 = 1 可执行 + 1 阻断。 counts = detail["summary"].counts assert counts.file_invoice_count == 2 assert counts.executable_count == 1 assert counts.blocked_count == 1 assert counts.matched_count == 2 - assert detail["summary"].matching_hash == second.matching_hash + assert detail["summary"].matching_hash == summary.matching_hash assert detail["summary"].expires_at +def test_second_matching_restores_empty_own_view(transfer_db, dbs_ready_file, monkeypatch): + """圈档互斥(D17)视图面:第二匹配无自有行,restore 呈现空明细而非他匹配的行。""" + _file_ready(monkeypatch, dbs_ready_file) + deps, erp, _ = make_transfer_deps(dbs_ready_file) + erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") + erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") + seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + transfer_type="in_transit_to_hub") + second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + transfer_type="in_transit_to_hub") + + detail = restore_matching(second.matching_id, deps=deps) + + # [断言意图] 出生翻转后行归属唯一:第二匹配未被圈定任何记录,restore 只见 + # 自有行(空)——跨匹配共享视图会掩盖「圈档互斥」事实。 + assert detail["items"] == [] + assert detail["summary"].counts.file_invoice_count == 0 + + def test_restore_marks_stale_beyond_ttl(transfer_db, dbs_ready_file, monkeypatch): - """行 updated_at 早于 TTL → stale=True(TTL 取 deps.strategy.confirm_ttl_seconds)。""" + """行库存取数时刻早于展示阈值 → stale=True(stale 时钟=inventory_checked_at)。""" _file_ready(monkeypatch, dbs_ready_file) 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") seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) - # 手工把 HOX-002 行的评估时间拨回 11 分钟前(TTL 默认 600 秒 = 10 分钟)。 - stale_at = datetime.utcnow() - timedelta(minutes=11) + summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + transfer_type="in_transit_to_hub") + # 手工把 HOX-002 行的库存查得时刻拨回阈值之外(stale 时钟=inventory_checked_at, + # 展示阈值=strategy.inventory_stale_ttl_seconds,TestingConfig 钉 24h)。 + stale_at = datetime.utcnow() - timedelta(hours=25) hox = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOX-002").first() - hox.updated_at = stale_at + hox.inventory_checked_at = stale_at db.session.commit() detail = restore_matching(summary.matching_id, deps=deps) row = next(i for i in detail["items"] if i.invoice_no == "HOX-002") fresh = next(i for i in detail["items"] if i.invoice_no == "HOM-001") - # [断言意图] 超过确认 TTL 未刷新的行必须标记 stale(提示用户重查后再执行), - # 未拨回的行保持新鲜;checked_at 携带行评估时间(updated_at isoformat)。 + # [断言意图] 超过展示阈值未取数的行必须标记 stale(提示用户重查后再执行), + # 未拨回的行保持新鲜;checked_at 携带库存查得时刻(inventory_checked_at isoformat)。 assert row.stale is True assert fresh.stale is False - assert row.checked_at == hox.updated_at.isoformat() + assert row.checked_at == stale_at.isoformat() assert row.file_current is True @@ -88,14 +114,15 @@ def test_restore_marks_file_current_false_without_ready_file(transfer_db, dbs_re """来源当前无可用文件 → 行 file_current=False(fail-safe,不得当作新鲜)。""" monkeypatch.setattr( matching_service, "resolve_source_file_status", - lambda *, source_code: {"file_status": "none", "has_ready_file": False, + lambda *, source_code, record_kind="inbound": {"file_status": "none", "has_ready_file": False, "file_no": None, "file_sha256": None}, ) 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") seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, + transfer_type="in_transit_to_hub") detail = restore_matching(summary.matching_id, deps=deps) diff --git a/backend/tests/services/in_transit_transfer/test_retry_and_manual_close.py b/backend/tests/services/in_transit_transfer/test_retry_and_manual_close.py index 6605d369..9b74c905 100644 --- a/backend/tests/services/in_transit_transfer/test_retry_and_manual_close.py +++ b/backend/tests/services/in_transit_transfer/test_retry_and_manual_close.py @@ -25,7 +25,7 @@ def _mismatch_matching(dbs_ready_file): erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") return deps, erp, summary @@ -197,35 +197,36 @@ def test_requery_items_invoice_filter_targets_only_given_rows(transfer_db, dbs_r assert _item_by_invoice("HOM-001").status == "blocked_recoverable" -def test_requery_reaches_rows_created_by_older_matching(transfer_db, dbs_ready_file): - """[回归防线 2026-09-24] 重查按 scope 圈行,行归属 matching_id 不参与。 +def test_requery_reaches_only_own_matching_rows(transfer_db, dbs_ready_file): + """[出生翻转语义] 重查只触达本匹配自有 items(创建即绑定,D17/规格 §9)。 - 行归属解耦后,重查只按 scope 圈行。2026-09-25 起行由证据同步落地, - matching_id 恒为 None(匹配完全不拥有行)——旧实现按 matching_id 圈行, - 会导致「卡片提示重查、重查命中 0 行」的死锁(生产实测 55 行全中)。本用例 - 锁定:第二次同 scope 匹配后,经新匹配号重查必须触达这批无归属行。 + [语义平移] 旧「scope 圈行跨匹配触达」随出生翻转退役:行由匹配创建时从档 + 圈定且创建即绑定,重查按 matching_id 圈自有行;其他匹配的占用行不越权 + (第二份同 scope 匹配为空壳——圈档互斥,见 test_matching_service)。 """ deps, erp, first = _mismatch_matching(dbs_ready_file) - row = _item_by_invoice("HOM-001") - # [断言意图] 落地行无匹配归属(matching_id=None):重查只能靠 scope 圈行。 - assert row.matching_id is None + from app.models import TransferMatching - # 第二次同 scope 匹配:行原地刷新、归属保持为空(匹配不拥有行)。 - second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) - assert second.matching_id != first.matching_id - db.session.expire_all() + first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one() row = _item_by_invoice("HOM-001") - second_matching_id = ( - db.session.query(TransferMatching).filter_by(matching_no=second.matching_id).one().id - ) - assert row.matching_id != second_matching_id + # [断言意图] 创建即绑定:行归属首匹配(旧「落地行 matching_id=None」已退役)。 + assert row.matching_id == first_matching.id + + # 第二次同 scope 匹配:圈档互斥 → 空壳(无自有行)。 + second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") + assert second.matching_id != first.matching_id + second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one() + assert row.matching_id != second_matching.id erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") # ERP 侧已修正库存 - result = requery_items(matching_no=second.matching_id, deps=deps) - # [断言意图] 新匹配号的重查必须触达 matching_id 指向旧匹配的行—— - # 视图(scope)能看到什么,重查就作用于什么(读与操作同一圈行谓词)。 - assert result["total"] == 2 - rows = {r["invoice_no"]: r for r in result["results"]} + result_second = requery_items(matching_no=second.matching_id, deps=deps) + # [断言意图] 第二匹配无自有行:重查命中 0(不越权触达他匹配占用行)。 + assert result_second["total"] == 0 + + result_first = requery_items(matching_no=first.matching_id, deps=deps) + # [断言意图] 首匹配自有行可重查:ERP 库存修正后 blocked 行翻回可执行。 + assert result_first["total"] == 2 + rows = {r["invoice_no"]: r for r in result_first["results"]} assert rows["HOM-001"]["ok"] is True assert rows["HOM-001"]["status"] == "ready_to_execute" @@ -270,7 +271,7 @@ def _wtp_lot_matching(transfer_db): file_dict = { "source_code": "DBS-AWSBI", "business_date": "2026-08-06", - "file_purpose": "receipt", + "file_purpose": "inbound", "file_no": "REC-20260806-900", "file_version": "v9", "checksum": "e" * 64, @@ -284,7 +285,7 @@ def _wtp_lot_matching(transfer_db): } deps, erp, _ = make_transfer_deps(file_dict) seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub") return deps, erp diff --git a/backend/tests/services/in_transit_transfer/test_route_resolver.py b/backend/tests/services/in_transit_transfer/test_route_resolver.py index 17790d50..b0d99fd0 100644 --- a/backend/tests/services/in_transit_transfer/test_route_resolver.py +++ b/backend/tests/services/in_transit_transfer/test_route_resolver.py @@ -4,7 +4,7 @@ 拨出库位 = 仓库映射的在途仓编码(必填),拨入仓库 = 映射的目标仓库代码; inventory_match 源优先按「收料文件仓库 == 货代仓库」精确匹配, 匹配不到回退「货代仓库为空」的默认映射行(空库位兜底)。 -依赖:app fixture 种子站点、ShippingInventoryExternalMapping、DefaultRouteResolver。 +依赖:app fixture 种子站点、FreightRpaOnhandExternalMapping、DefaultRouteResolver。 逻辑:fixed 源仅一条启用映射直接取用;任何映射行缺失或在途仓编码未维护 fail-closed。 """ @@ -13,18 +13,18 @@ from __future__ import annotations import pytest from app.extensions import db -from app.models import ShippingInventoryExternalMapping, ShippingInventorySource +from app.models import FreightRpaOnhandExternalMapping, FreightRpaSource from app.services.in_transit_transfer.deps import DefaultRouteResolver from app.services.in_transit_transfer.matching_service import RouteNotResolvedError def _seed_mapping( - source: ShippingInventorySource, *, freight_warehouse_id: str | None, + source: FreightRpaSource, *, freight_warehouse_id: str | None, in_transit_warehouse_code: str = 'TZT-01', -) -> ShippingInventoryExternalMapping: +) -> FreightRpaOnhandExternalMapping: """在既有种子来源上挂一条启用映射。""" - mapping = ShippingInventoryExternalMapping( - inventory_source_id=source.id, freight_warehouse_id=freight_warehouse_id, + mapping = FreightRpaOnhandExternalMapping( + source_id=source.id, freight_warehouse_id=freight_warehouse_id, external_system_code='TOPGP', external_organization_code='TGHX', external_warehouse_code='HUB-CN01', external_warehouse_name='HUB 仓', in_transit_warehouse_code=in_transit_warehouse_code, enabled=True, @@ -34,12 +34,13 @@ def _seed_mapping( return mapping -def _seed_inventory_match_source() -> ShippingInventorySource: +def _seed_inventory_match_source() -> FreightRpaSource: """以种子站点(fixed)的绑定配置为模板,新建 inventory_match 识别方式的来源。""" - template = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - source = ShippingInventorySource( + template = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + # s18 起站点行不再承载 parsing_profile_id;路由解析只读外部映射,无需在手配置行。 + source = FreightRpaSource( source_code='DSV360_CRANE', display_name='Crane 测试源', connector_type='crane', - rpa_profile_id=template.rpa_profile_id, parsing_profile_id=template.parsing_profile_id, + rpa_profile_id=template.rpa_profile_id, excel_template_id=template.excel_template_id, warehouse_resolution_mode='inventory_match', fixed_warehouse_id=None, enabled=True, ) @@ -51,7 +52,7 @@ def _seed_inventory_match_source() -> ShippingInventorySource: def test_fixed_source_uses_single_mapping_in_transit_code(app): """fixed 源仅一条启用映射:拨出库位取该行在途仓编码而非货代仓库/站点固定仓。""" with app.app_context(): - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() # 种子站点 fixed_warehouse_id='AWSDU';断言取映射在途仓 'TZT-01',证明拨出库位来自新字段。 _seed_mapping(source, freight_warehouse_id='TZR2') @@ -63,7 +64,7 @@ def test_fixed_source_uses_single_mapping_in_transit_code(app): assert route.external_org == 'TGHX' -def test_inventory_match_prefers_receipt_warehouse_exact_mapping(app): +def test_inventory_match_prefers_inbound_warehouse_exact_mapping(app): """inventory_match 源:收料仓库与某行货代仓库精确匹配 → 取该行在途仓编码。""" with app.app_context(): source = _seed_inventory_match_source() @@ -118,7 +119,7 @@ def test_inventory_match_fails_closed_without_any_match(app): def test_route_resolver_fails_closed_without_in_transit_code(app): """映射未维护在途仓编码(存量空串)→ 拨出库位无来源,fail-closed。""" with app.app_context(): - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() _seed_mapping(source, freight_warehouse_id=None, in_transit_warehouse_code='') with pytest.raises(RouteNotResolvedError): diff --git a/backend/tests/services/in_transit_transfer/test_rpa_sinks_ownership.py b/backend/tests/services/in_transit_transfer/test_rpa_sinks_ownership.py new file mode 100644 index 00000000..4097b053 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_rpa_sinks_ownership.py @@ -0,0 +1,51 @@ +""" +tests/services/in_transit_transfer/test_rpa_sinks_ownership.py + +用途:锁定入站/出站 sink 组合根归属——住在 in_transit_transfer,不在 shipping_notice; + inbound-batch-ready 直挂 freight_rpa 归档入口(无 shipping_notice Middle Man)。 +""" + +from __future__ import annotations + +import importlib + +import pytest + + +def test_shipping_notice_rpa_sinks_only_exposes_onhand_registration(): + """发货包只保留 onhand 注册入口,不再导出 inbound/outbound 注册。""" + sinks = importlib.import_module('app.services.shipping_notice.rpa_sinks') + assert hasattr(sinks, 'register_onhand_sinks') + assert not hasattr(sinks, 'register_inbound_sinks') + assert not hasattr(sinks, 'register_outbound_sinks') + + +def test_shipping_notice_inbound_report_storage_module_removed(): + """入站 Middle Man 模块已删除,生产与测试均直连 freight_rpa / 调拨处理函数。""" + with pytest.raises(ModuleNotFoundError): + importlib.import_module('app.services.shipping_notice.inbound_report_storage') + + +def test_register_inbound_sinks_binds_archive_and_transfer_handler(app): + """register_inbound_sinks 把归档入口与调拨 handler 接到 inbound kinds。""" + from app.services.freight_rpa.common import callback_sinks + from app.services.freight_rpa.reports import dispatch as dispatch_module + from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report + from app.services.in_transit_transfer.rpa_sinks import register_inbound_sinks + + dispatch_module._REPORT_HANDLERS.pop('inbound', None) + callback_sinks._SINKS.pop('inbound-batch-ready', None) + register_inbound_sinks() + assert dispatch_module._REPORT_HANDLERS.get('inbound') is handle_inbound_report + assert 'inbound-batch-ready' in callback_sinks._SINKS + + +def test_register_outbound_sinks_binds_outbound_handler(app): + """register_outbound_sinks 把 handle_outbound_report 接到 outbound kind。""" + from app.services.freight_rpa.reports import dispatch as dispatch_module + from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report + from app.services.in_transit_transfer.rpa_sinks import register_outbound_sinks + + dispatch_module._REPORT_HANDLERS.pop('outbound', None) + register_outbound_sinks() + assert dispatch_module._REPORT_HANDLERS.get('outbound') is handle_outbound_report diff --git a/backend/tests/services/in_transit_transfer/test_schedule_jobs.py b/backend/tests/services/in_transit_transfer/test_schedule_jobs.py index d8a30f8e..65018ff9 100644 --- a/backend/tests/services/in_transit_transfer/test_schedule_jobs.py +++ b/backend/tests/services/in_transit_transfer/test_schedule_jobs.py @@ -3,7 +3,7 @@ 用途:验证在途自动调拨 platform job 注册契约与 handler 调用形态; in-transit-receipt-file 已于 2026-09-28 下线(文件就绪保障内建于自动调拨, 见 job_registry 在途自动调拨描述),此处锁定其"不再注册"防回归。 -依赖:schedule.job_registry、receipt_trigger_service、in_transit_transfer_job。 +依赖:schedule.job_registry、inbound_trigger_service、in_transit_transfer_job。 逻辑:只验证注册契约与调用形态,真实排程触发由 scheduler 驱动。 """ @@ -46,12 +46,12 @@ def _make_receipt_source(db, source_code: str, *, enabled: bool): """创建可参与收料的最小库存源(rpa_profile_id 非空,须先建 Profile)。""" from app.models import ( ShippingExcelTemplate, - ShippingInventoryParsingProfile, - ShippingInventorySource, - ShippingRpaProfile, + FreightRpaParsingProfile, + FreightRpaSource, + FreightRpaProfile, ) - profile = ShippingRpaProfile( + profile = FreightRpaProfile( profile_code=f"RPA_{source_code}", display_name=source_code, connector_type="crane", login_url="https://test.invalid/login", login_config_json={"auth_mode": "password"}, ) @@ -62,7 +62,7 @@ def _make_receipt_source(db, source_code: str, *, enabled: bool): "rpa_profile_id": profile.id, "enabled": enabled, } if enabled: - parsing = ShippingInventoryParsingProfile( + parsing = FreightRpaParsingProfile( profile_code=f"PARSE_{source_code}", display_name=source_code, version=1, status="published", file_format="xlsx", definition_json={"field_mapping": {}, "match_keys": []}, @@ -79,31 +79,39 @@ def _make_receipt_source(db, source_code: str, *, enabled: bool): db.session.add_all([parsing, template]) db.session.flush() source_kwargs.update( - parsing_profile_id=parsing.id, excel_template_id=template.id, + excel_template_id=template.id, warehouse_resolution_mode="fixed", fixed_warehouse_id="WH1", ) else: source_kwargs.update(warehouse_resolution_mode="inventory_match", fixed_warehouse_id=None) - source = ShippingInventorySource(**source_kwargs) + source = FreightRpaSource(**source_kwargs) db.session.add(source) + if enabled: + # s18 起解析方案绑定/报表路径/查询条件归 FreightRpaOnhandReportConfig 配置行; + # 经关系级联随站点一并入库。 + from app.models import FreightRpaOnhandReportConfig + FreightRpaOnhandReportConfig( + source=source, parsing_profile=parsing, + report_path_json={}, query_parameters_json=[], + ) return source -def test_list_receipt_capable_source_codes_filters_by_enabled_and_config(app, transfer_db): +def test_list_inbound_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 + from app.models import FreightRpaInboundReportConfig + from app.services.in_transit_transfer.inbound_trigger_service import list_inbound_capable_source_codes enabled = _make_receipt_source(transfer_db, "CRANE_SGP", enabled=True) _make_receipt_source(transfer_db, "DBS_OFF", enabled=False) _make_receipt_source(transfer_db, "CRANE_NOCONF", enabled=True) transfer_db.session.flush() - transfer_db.session.add(ShippingReceiptReportConfig( - inventory_source_id=enabled.id, report_path_json={}, query_parameters_json=[], + transfer_db.session.add(FreightRpaInboundReportConfig( + source_id=enabled.id, report_path_json={}, query_parameters_json=[], )) transfer_db.session.commit() - result = list_receipt_capable_source_codes() + result = list_inbound_capable_source_codes() assert "CRANE_SGP" in result assert "DBS_OFF" not in result assert "CRANE_NOCONF" not in result @@ -116,7 +124,7 @@ def test_wanted_source_codes_falls_back_when_empty(monkeypatch): 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"]) + monkeypatch.setattr(job_mod, "list_inbound_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"]}) @@ -130,7 +138,7 @@ def test_handler_empty_data_day_stays_silent(monkeypatch): 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"]) + monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"]) captured = {} def _fake_auto_transfer(**kwargs): @@ -147,8 +155,8 @@ def test_handler_empty_data_day_stays_silent(monkeypatch): # 断言:领域通知接线已移除(不再透传 sender/recipients);空数据日置 C5 静默标记。 assert "sender" not in captured assert "recipients" not in captured - assert captured["receipt_date_from"] is None - assert captured["receipt_date_to"] is None + assert captured["movement_date_from"] is None + assert captured["movement_date_to"] is None assert captured["source_codes"] == ["CRANE_SGP"] assert captured["recover_history"] is True assert run.response_summary_json["domain_notification_managed"] is True @@ -164,7 +172,7 @@ def test_handler_converts_t_minus_offsets(monkeypatch): 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"]) + monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"]) monkeypatch.setattr(job_mod, "business_date_now", lambda: date(2026, 10, 12)) captured = {} @@ -181,8 +189,8 @@ def test_handler_converts_t_minus_offsets(monkeypatch): # 断言:T=2026-10-12,起4止2 换算为 T−4~T−2 的具体日期透传匹配层。 assert captured["business_date"] == "2026-10-12" - assert captured["receipt_date_from"] == "2026-10-08" - assert captured["receipt_date_to"] == "2026-10-10" + assert captured["movement_date_from"] == "2026-10-08" + assert captured["movement_date_to"] == "2026-10-10" def test_handler_rejects_invalid_offset_without_execution(monkeypatch): @@ -190,7 +198,7 @@ def test_handler_rejects_invalid_offset_without_execution(monkeypatch): 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"]) + monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"]) def _must_not_run(**kwargs): raise AssertionError("run_auto_transfer must not run with invalid offsets") @@ -205,7 +213,7 @@ def test_handler_rejects_invalid_offset_without_execution(monkeypatch): ) # 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名。 assert results == [] - assert any("收料日期起点" in e for e in errors) + assert any("异动日期起点" in e for e in errors) assert not (run.response_summary_json or {}).get("domain_notification_managed") task = ScheduleTask(job_params={"receipt_to_offset_days": 2.5}) @@ -213,7 +221,7 @@ def test_handler_rejects_invalid_offset_without_execution(monkeypatch): job_mod.run_in_transit_transfer_schedule(task, run) ) # 断言:小数偏移同样快速失败。 - assert any("收料日期终点" in e for e in errors) + assert any("异动日期终点" in e for e in errors) def test_handler_run_day_uses_framework_notification(monkeypatch): @@ -221,7 +229,7 @@ def test_handler_run_day_uses_framework_notification(monkeypatch): 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"]) + monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"]) def _fake_auto_transfer(**kwargs): return job_mod.AutoTransferOutcome(run_no="TR-1", run_status="success") @@ -245,7 +253,7 @@ def test_handler_hard_failure_keeps_framework_notification(monkeypatch): 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"]) + monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"]) def _fake_auto_transfer(**kwargs): return job_mod.AutoTransferOutcome(errors=["match pipeline boom"]) diff --git a/backend/tests/services/in_transit_transfer/test_scope_rules.py b/backend/tests/services/in_transit_transfer/test_scope_rules.py new file mode 100644 index 00000000..b91beafe --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_scope_rules.py @@ -0,0 +1,139 @@ +"""范围规则引擎契约:规则间 AND、规则内多值 OR、受控词表、SQL 编译与内存求值同口径。 + +用途:锁定 scope_rules 引擎对外契约——受控字段白名单校验、evaluate/apply 双形态 + 同口径(防谓词漂移)、record_kinds_of 证据流推导、审计说明文本格式; + Task 11(圈档/重查)与 Task 5(API 校验)及证据流 UI 后续任务消费本契约。 +依赖:app.core.errors.ValidationError、scope_rules 引擎、SQLAlchemy、 + models/in_transit_transfer.TransferMovementLedger(SQL 编译断言与真库 + 行集交叉验证均以真档表为对象,2026-10-14 Task 9 回补,探针模型退役)。 +逻辑:SQL 编译文本断言(pure_unit,不落库)+ 真库行集断言(请求 app/transfer_db + 夹具:真档表逐条比对内存谓词命中与 SQL 实际命中行集)。 +""" + +from __future__ import annotations + +import pytest +from sqlalchemy import select + +from app import db +from app.core.errors import ValidationError +from app.models.in_transit_transfer import TransferMovementLedger +from app.services.in_transit_transfer.scope_rules import ( + apply_scope_filters, evaluate_scope, parse_scope_rules, record_kinds_of, scope_rules_note, +) + +pytestmark = pytest.mark.pure_unit + + +RULES = parse_scope_rules([ + {"field": "doc_no", "match": "prefix", "values": ["HOM", "HOX"]}, + {"field": "source_code", "match": "in", "values": ["SRC-A"]}, +]) + + +def test_record_kinds_of_reads_existing_scope_rule(): + """没有记录类型规则时入站和出站都要;只写 outbound 时只要出站。""" + assert record_kinds_of(parse_scope_rules([ + {"field": "doc_no", "match": "prefix", "values": ["HOM"]}, + ])) == ("inbound", "outbound") + assert record_kinds_of(parse_scope_rules([ + {"field": "record_kind", "match": "equals", "values": ["outbound"]}, + ])) == ("outbound",) + assert record_kinds_of(parse_scope_rules([ + {"field": "record_kind", "match": "in", "values": ["outbound", "inbound"]}, + ])) == ("inbound", "outbound") + + +def test_rules_are_and_values_are_or(): + """两条规则须同时满足;同一规则内任一前缀命中即可。""" + assert evaluate_scope({"doc_no": "HOM-1", "source_code": "SRC-A"}, RULES) + assert evaluate_scope({"doc_no": "HOX-9", "source_code": "SRC-A"}, RULES) + assert not evaluate_scope({"doc_no": "HOM-1", "source_code": "SRC-B"}, RULES) # 规则间 AND:source 不中即淘汰 + assert not evaluate_scope({"doc_no": "INV-1", "source_code": "SRC-A"}, RULES) # doc_no 两前缀均不中即淘汰 + + +def test_match_modes(): + """equals 精确等值、contains 子串命中;未命中规则一票否决。 + + 注:简报原用例字段 material_name 不在受控白名单(规格 §6 词表),经控制器 + 确认字段须为前端下拉受控选择,改用白名单字段 material_code(contains 断言 + 语义不变)。 + """ + rules = parse_scope_rules([ + {"field": "odm_id", "match": "equals", "values": ["HoxinRMA"]}, + {"field": "material_code", "match": "contains", "values": ["轴承"]}, + ]) + assert evaluate_scope({"odm_id": "HoxinRMA", "material_code": "精密轴承"}, rules) + assert not evaluate_scope({"odm_id": "Other", "material_code": "精密轴承"}, rules) # equals 不中 + + +def test_unknown_field_rejected(): + """字段不在受控词表必须拒绝,且错误码固定为 TRANSFER.SCOPE_RULE_INVALID(Task 5 同步四语言 errors.json)。""" + with pytest.raises(ValidationError) as exc_info: + parse_scope_rules([{"field": "password", "match": "equals", "values": ["x"]}]) + assert exc_info.value.code == "TRANSFER.SCOPE_RULE_INVALID" # 稳定错误码契约 + + +def test_sql_compiler_literal_shape(): + """SQL 编译文本形状:prefix 编译为大写字面量 LIKE(双前缀 OR 展开)、in 编译为字面量 IN 列表。 + + 注:Task 2 期间以临时探针模型编译占位(真档表未落地);Task 9 起改以真实 + TransferMovementLedger 编译,断言不再依赖探针。原 `assert "IN" in sql` 偏弱 + (任意含 IN 的 SQL 均通过),收紧为断言字面量值列表本体。 + """ + assert scope_rules_note(RULES) == "doc_no prefix HOM|HOX AND source_code in SRC-A" + + query = apply_scope_filters(select(TransferMovementLedger.id), TransferMovementLedger, RULES) + sql = str(query.compile(compile_kwargs={"literal_binds": True})) + assert "LIKE 'HOM%'" in sql and "LIKE 'HOX%'" in sql # prefix 字面量保持大写 + assert "upper(transfer_movement_ledger.source_code) IN ('SRC-A')" in sql # in 匹配=字面量值列表 + + +def test_sql_hits_same_rows_as_memory_predicate(app, transfer_db): + """真档表行集交叉验证:SQL 实际命中行集与内存谓词逐条一致(Task 9 回补真库断言)。 + + 覆盖四类边界:双前缀 OR 命中、小写命中(UPPER 同口径)、AND 淘汰、空值淘汰 + (内存 _hit 空值 False ↔ SQL 空串/NULL 谓词排除,两侧必须同样不命中); + 另以 movement_date(可空业务字段,规格 §4.2「空值不进日期圈定」)单独验证 + NULL 边界——自然键成分 NOT NULL,NULL 只可能出现在可空业务字段。 + """ + # (doc_no, source_code):前 3 条命中、后 3 条淘汰。 + rows = [ + {"source_code": "SRC-A", "record_kind": "receipt", "doc_no": "HOM-1", "line_no": "1"}, # prefix 首值 + in + {"source_code": "SRC-A", "record_kind": "receipt", "doc_no": "HOX-9", "line_no": "2"}, # prefix 次值(规则内 OR) + {"source_code": "SRC-A", "record_kind": "receipt", "doc_no": "hom-2", "line_no": "3"}, # 小写:UPPER 后命中 + {"source_code": "SRC-B", "record_kind": "receipt", "doc_no": "HOM-3", "line_no": "4"}, # 规则间 AND:source 不中 + {"source_code": "SRC-A", "record_kind": "receipt", "doc_no": "INV-1", "line_no": "5"}, # 两前缀均不中 + {"source_code": "SRC-A", "record_kind": "receipt", "doc_no": "", "line_no": "6"}, # 空串:空值不进圈定 + # NULL 边界(movement_date 可空,规格 §4.2「空值不进日期圈定」;两行均满足 RULES, + # 用于下方 movement_date 专属规则的单列对照)。 + {"source_code": "SRC-A", "record_kind": "receipt", "doc_no": "HOM-NULL", "line_no": "99", "movement_date": None}, + {"source_code": "SRC-A", "record_kind": "receipt", "doc_no": "HOM-DATE", "line_no": "98", "movement_date": "2026-10-14"}, + ] + ledgers = [TransferMovementLedger(**row) for row in rows] + db.session.add_all(ledgers) + db.session.flush() + + query = apply_scope_filters(select(TransferMovementLedger.id), TransferMovementLedger, RULES) + sql_hits = {row.id for row in db.session.execute(query)} + # 行集级:SQL 命中行集恰为内存谓词判真的记录(含 2 条满足 RULES 的 NULL 边界行)。 + expected = { + ledger.id for ledger, row in zip(ledgers, rows) if evaluate_scope(row, RULES) + } + assert sql_hits == expected == { + ledgers[0].id, ledgers[1].id, ledgers[2].id, ledgers[6].id, ledgers[7].id, + } + # 逐条交叉验证:每条记录「内存求值结果 ↔ 是否在 SQL 命中行集」一致。 + for ledger, row in zip(ledgers, rows): + assert (ledger.id in sql_hits) is evaluate_scope(row, RULES) + + # NULL 日期边界:movement_date 规则只命中有值行,NULL 行两侧(内存/SQL)同样不命中。 + null_date_rules = parse_scope_rules([ + {"field": "movement_date", "match": "equals", "values": ["2026-10-14"]}, + ]) + date_query = apply_scope_filters( + select(TransferMovementLedger.id), TransferMovementLedger, null_date_rules, + ) + date_hits = {row.id for row in db.session.execute(date_query)} + assert date_hits == {ledgers[7].id} + assert ledgers[6].id not in date_hits 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 a42df15e..e922bbb2 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,12 +1,15 @@ -"""来源收料文件状态投影服务测试。 +"""来源证据文件状态投影服务测试。 -用途:验证 resolve_source_file_status 只读货代收料事实(UnitRun/ReportFile), - 按来源投影 ready/fetching/failed/expired/parse_failed/none,并验证解析失败 - 标记 record/clear 的往返语义。调拨不维护独立抓取状态表。 -依赖:app(SQLite)、ShippingInventorySource 种子、ScheduleTask/ScheduleRun/UnitRun/ReportFile。 -逻辑:有当天(业务日)抓取且未过期文件→ready(若标记解析失败→parse_failed); - 有进行中单元→fetching;最新单元失败终态→failed; - 保留期已到或隔日旧文件(未清理)→expired;否则→none。 +用途:验证 resolve_source_file_status / resolve_source_file_statuses 只读货代入站/出站事实(UnitRun/ReportFile), + 按来源与 record_kind 投影 ready/fetching/failed/expired/parse_failed/none/ + unconfigured,并验证入站解析失败标记 record/clear 的往返语义。 + 调拨不维护独立抓取状态表。 +依赖:app(SQLite)、FreightRpaSource 种子、ScheduleTask/ScheduleRun/UnitRun/ReportFile; + 出站用例用 monkeypatch 注入配置与可用文件视图,不连对象存储。 +逻辑:入站既有用例保持:当天业务日且未过期文件→ready(解析失败→parse_failed); + 进行中单元→fetching;最新单元失败终态→failed;空数据→no_data; + 保留期已到或隔日旧文件→expired;否则→none。 + 出站无配置→unconfigured;出站有可用文件视图→ready。 """ from __future__ import annotations @@ -25,9 +28,9 @@ SOURCE_CODE = 'DSV360_AWSDU' def receipt_unit_run(): """构造一条收料执行单元(含排程/来源上下文)。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun - source = ShippingInventorySource.query.filter_by(source_code=SOURCE_CODE).one() + source = FreightRpaSource.query.filter_by(source_code=SOURCE_CODE).one() task = ScheduleTask( schedule_no='SCH-SOURCE-STATUS', name='Source status test', schedule_type='platform_job', owner_user_id=1, cron_expr='0 8 * * *', job_params={}, @@ -37,8 +40,8 @@ def receipt_unit_run(): run = ScheduleRun(run_no='RUN-SOURCE-STATUS', schedule_task_id=task.id, status='awaiting_callback') db.session.add(run) db.session.flush() - unit = ShippingReceiptRpaUnitRun( - schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, + unit = FreightRpaInboundUnitRun( + schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-status-001', status='awaiting_rpa', config_snapshot_json={}, ) @@ -64,7 +67,7 @@ def test_running_unit_is_fetching(app, receipt_unit_run): def test_failed_latest_unit_is_failed(app, receipt_unit_run): """最新单元为失败终态且无文件 → failed。""" from app import db - from app.models import ShippingReceiptRpaUnitRun + from app.models import FreightRpaInboundUnitRun receipt_unit_run.status = 'failed' db.session.commit() @@ -75,11 +78,11 @@ def test_failed_latest_unit_is_failed(app, receipt_unit_run): def test_report_file_is_ready(app, receipt_unit_run): """有收料归档文件 → ready,且带 file_no/sha256。""" from app import db - from app.models import ShippingReceiptReportFile + from app.models import FreightRpaInboundReportFile receipt_unit_run.status = 'success' digest = hashlib.sha256(b'receipt workbook').hexdigest() - db.session.add(ShippingReceiptReportFile( + db.session.add(FreightRpaInboundReportFile( unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test', storage_key='shipping/receipt/test.xlsx', original_filename='receipt.xlsx', file_size=16, sha256=digest, @@ -96,10 +99,10 @@ def test_expired_report_is_expired(app, receipt_unit_run): """保留期已到但清理任务未删 → expired,不得误报 ready。""" # [断言意图] 过期判定只看 archive_expires_at,不依赖保留期清理任务是否已落位。 from app import db - from app.models import ShippingReceiptReportFile + from app.models import FreightRpaInboundReportFile receipt_unit_run.status = 'success' - db.session.add(ShippingReceiptReportFile( + db.session.add(FreightRpaInboundReportFile( unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test', storage_key='shipping/receipt/expired.xlsx', original_filename='expired.xlsx', file_size=16, sha256=hashlib.sha256(b'expired workbook').hexdigest(), @@ -115,17 +118,17 @@ def test_newer_valid_report_wins_over_expired(app, receipt_unit_run): """过期文件之后又抓到未过期文件 → 以最新未过期文件为准(ready)。""" # [断言意图] ready 查询过滤掉过期记录后仍按 created_at/id 倒序取最新一条。 from app import db - from app.models import ShippingReceiptReportFile + from app.models import FreightRpaInboundReportFile receipt_unit_run.status = 'success' digest = hashlib.sha256(b'fresh workbook').hexdigest() - db.session.add(ShippingReceiptReportFile( + db.session.add(FreightRpaInboundReportFile( unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test', storage_key='shipping/receipt/expired.xlsx', original_filename='expired.xlsx', file_size=16, sha256=hashlib.sha256(b'expired workbook').hexdigest(), archive_expires_at=datetime.utcnow() - timedelta(days=1), )) - db.session.add(ShippingReceiptReportFile( + db.session.add(FreightRpaInboundReportFile( unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test', storage_key='shipping/receipt/fresh.xlsx', original_filename='fresh.xlsx', file_size=16, sha256=digest, @@ -143,10 +146,10 @@ def test_stale_report_is_expired(app, receipt_unit_run): # [断言意图] 新鲜度按 Asia/Shanghai 业务日窗口判定(UTC 库存时间须换算): # 隔日抓取的文件对 D+1 预检是旧数据,投影 expired 引导重试重抓。 from app import db - from app.models import ShippingReceiptReportFile + from app.models import FreightRpaInboundReportFile receipt_unit_run.status = 'success' - db.session.add(ShippingReceiptReportFile( + db.session.add(FreightRpaInboundReportFile( unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test', storage_key='shipping/receipt/stale.xlsx', original_filename='stale.xlsx', file_size=16, sha256=hashlib.sha256(b'stale workbook').hexdigest(), @@ -161,11 +164,11 @@ def test_stale_report_is_expired(app, receipt_unit_run): def test_usable_file_with_parse_failed_at_projects_parse_failed(app, receipt_unit_run): """可用归档文件若已标记 parse_failed_at → file_status=parse_failed 且不可当 ready。""" from app import db - from app.models import ShippingReceiptReportFile + from app.models import FreightRpaInboundReportFile receipt_unit_run.status = 'success' digest = hashlib.sha256(b'bad workbook').hexdigest() - db.session.add(ShippingReceiptReportFile( + db.session.add(FreightRpaInboundReportFile( unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test', storage_key='shipping/receipt/bad.xlsx', original_filename='bad.xlsx', file_size=16, sha256=digest, @@ -183,28 +186,28 @@ def test_usable_file_with_parse_failed_at_projects_parse_failed(app, receipt_uni def test_record_and_clear_parse_failure_roundtrip(app, receipt_unit_run): """record 写入三列;clear 清空后投影回 ready。""" from app import db - from app.models import ShippingReceiptReportFile + from app.models import FreightRpaInboundReportFile from app.services.in_transit_transfer.source_file_status import ( - clear_receipt_parse_failure, - record_receipt_parse_failure, + clear_inbound_parse_failure, + record_inbound_parse_failure, resolve_source_file_status, ) receipt_unit_run.status = 'success' digest = hashlib.sha256(b'roundtrip').hexdigest() - report = ShippingReceiptReportFile( + report = FreightRpaInboundReportFile( unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test', storage_key='shipping/receipt/ok.xlsx', original_filename='ok.xlsx', file_size=16, sha256=digest, ) db.session.add(report) db.session.commit() - record_receipt_parse_failure( + record_inbound_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) + clear_inbound_parse_failure(report=report) db.session.commit() assert resolve_source_file_status(source_code=SOURCE_CODE)["file_status"] == "ready" @@ -218,3 +221,199 @@ def test_empty_unit_is_no_data(app, receipt_unit_run): status = resolve_source_file_status(source_code=SOURCE_CODE) assert status['file_status'] == 'no_data' assert status['has_ready_file'] is False + + +def test_stale_orphan_unit_sweeps_projection_to_failed(app): + """孤儿单元(按需触发无排程)超时回收后,投影 fetching 翻转为 failed。 + + 网页异常关闭事故回归(2026-10-16):按需触发的单元 schedule_run_id=NULL, + 回收扫描覆盖前投影永久 fetching、前端重试按钮(file_status !== 'fetching' + 门禁)永久锁死;回收后必须翻转 failed 解锁重新触发 RPA。 + """ + from app import db + from app.models import FreightRpaSource, FreightRpaInboundUnitRun + from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_orphan_inbound_units + + with app.app_context(): + app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60 + source = FreightRpaSource.query.filter_by(source_code=SOURCE_CODE).one() + db.session.add(FreightRpaInboundUnitRun( + schedule_run_id=None, source_id=source.id, source_code=source.source_code, + connector_type='dbs', callback_id='inbound-orphan-status', status='awaiting_rpa', + config_snapshot_json={}, created_at=datetime.utcnow() - timedelta(minutes=5), + )) + db.session.commit() + + assert resolve_source_file_status(source_code=SOURCE_CODE)['file_status'] == 'fetching' + # [断言意图] 回收扫描后投影必须翻转为 failed:这是前端重试门禁 + # (file_status !== 'fetching')解锁的依据,也是本测试与事故的直接回归点。 + assert recover_all_stale_orphan_inbound_units() == 1 + db.session.expire_all() + assert resolve_source_file_status(source_code=SOURCE_CODE)['file_status'] == 'failed' + + +def test_outbound_without_config_is_unconfigured(monkeypatch): + """没有出站报表配置时,出站流是未配置,入站投影函数签名仍可只传来源。""" + monkeypatch.setattr( + "app.services.in_transit_transfer.source_file_status.get_outbound_config", + lambda source_code: None, + ) + status = resolve_source_file_status(source_code="DSV360_AWSBI", record_kind="outbound") + assert status["file_status"] == "unconfigured" + assert status["has_ready_file"] is False + + +def test_outbound_usable_file_is_ready(monkeypatch): + """出站已配置且存在可用归档时投影 ready;文件视图按入站可用文件形状注入,不读对象存储。""" + from types import SimpleNamespace + + monkeypatch.setattr( + "app.services.in_transit_transfer.source_file_status.get_outbound_config", + lambda source_code: object(), + ) + monkeypatch.setattr( + "app.services.in_transit_transfer.source_file_status.latest_usable_outbound_file", + lambda source_code: SimpleNamespace( + file_id=7, + original_filename="outbound.xlsx", + sha256="ab" * 32, + parse_failed_at=None, + ), + ) + status = resolve_source_file_status(source_code="DSV360_AWSBI", record_kind="outbound") + # [断言意图] ready 必须读入站同形视图的文件名与摘要,而不是另查对象存储。 + assert status["file_status"] == "ready" + assert status["has_ready_file"] is True + assert status["file_no"] == "outbound.xlsx" + assert status["file_sha256"] == "ab" * 32 + + +def test_unknown_record_kind_is_rejected(): + """record_kind 只接受 inbound / outbound。""" + from app.core.errors import ValidationError + + with pytest.raises(ValidationError): + resolve_source_file_status(source_code="DSV360_AWSBI", record_kind="onhand") + + +def test_outbound_report_file_projects_ready(app): + """出站配置与当天可用归档都在库时,按出站文件表投影 ready,不读对象存储。""" + from app import db + from app.models import ( + FreightRpaOutboundReportConfig, + FreightRpaOutboundReportFile, + FreightRpaOutboundUnitRun, + FreightRpaSource, + ) + + source = FreightRpaSource.query.filter_by(source_code=SOURCE_CODE).one() + db.session.add(FreightRpaOutboundReportConfig( + source_id=source.id, + report_path_json={'report_name': 'Outbound'}, + query_parameters_json=[], + )) + unit = FreightRpaOutboundUnitRun( + schedule_run_id=None, source_id=source.id, source_code=source.source_code, + connector_type='dbs', warehouse_id='AWSDU', callback_id='outbound-status-ready', + status='success', config_snapshot_json={}, trigger_snapshot_json={}, + ) + db.session.add(unit) + db.session.flush() + digest = hashlib.sha256(b'outbound workbook').hexdigest() + db.session.add(FreightRpaOutboundReportFile( + unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', + storage_key='shipping/outbound/test.xlsx', original_filename='outbound-real.xlsx', + file_size=16, sha256=digest, + )) + db.session.commit() + status = resolve_source_file_status(source_code=SOURCE_CODE, record_kind='outbound') + # [断言意图] 出站 ready 走真实归档表与单元行,文件名/摘要来自行数据而非对象存储。 + assert status['file_status'] == 'ready' + assert status['has_ready_file'] is True + assert status['file_no'] == 'outbound-real.xlsx' + assert status['file_sha256'] == digest + + +def _clone_enabled_source(source_code: str): + """再造一个启用来源,复用种子站点的登录连接与模板,避免把查询次数测试绑在单来源上。""" + from app import db + from app.models import FreightRpaSource + + existing = FreightRpaSource.query.filter_by(source_code=SOURCE_CODE).one() + source = FreightRpaSource( + source_code=source_code, + display_name=source_code, + connector_type=existing.connector_type, + rpa_profile_id=existing.rpa_profile_id, + excel_template_id=existing.excel_template_id, + warehouse_resolution_mode=existing.warehouse_resolution_mode, + fixed_warehouse_id=existing.fixed_warehouse_id, + enabled=True, + ) + db.session.add(source) + db.session.commit() + return source + + +def test_batch_status_matches_per_source_and_prefers_running_unit(app, receipt_unit_run): + """列表批量投影与逐来源投影一致;较新的失败单元不能盖住仍在进行的单元。""" + from app import db + from app.models import FreightRpaInboundUnitRun, FreightRpaSource + from app.services.in_transit_transfer.source_file_status import resolve_source_file_statuses + + db.session.add(FreightRpaInboundUnitRun( + schedule_run_id=None, + source_id=receipt_unit_run.source_id, + source_code=SOURCE_CODE, + connector_type='dbs', + callback_id='inbound-newer-failed', + status='failed', + config_snapshot_json={}, + trigger_snapshot_json={}, + )) + extra = _clone_enabled_source('DSV360_BATCH_EXTRA') + db.session.commit() + + sources = FreightRpaSource.query.filter( + FreightRpaSource.source_code.in_([SOURCE_CODE, extra.source_code]), + ).all() + batched = resolve_source_file_statuses(sources) + # [断言意图] 进行中单元优先于更新的失败单元,批量结果必须与逐条投影相同。 + assert batched[SOURCE_CODE]['inbound']['file_status'] == 'fetching' + assert batched[SOURCE_CODE]['outbound']['file_status'] == 'unconfigured' + assert batched[extra.source_code]['inbound']['file_status'] == 'none' + for source in sources: + assert batched[source.source_code]['inbound'] == resolve_source_file_status( + source_code=source.source_code, record_kind='inbound', + ) + assert batched[source.source_code]['outbound'] == resolve_source_file_status( + source_code=source.source_code, record_kind='outbound', + ) + + +def test_batch_status_query_count_stays_flat_for_two_sources(app, receipt_unit_run): + """两个来源的列表投影查询次数保持常数,不能按来源乘开。""" + from sqlalchemy import event + + from app import db + from app.models import FreightRpaSource + from app.services.in_transit_transfer.source_file_status import resolve_source_file_statuses + + extra = _clone_enabled_source('DSV360_BATCH_COUNT') + sources = FreightRpaSource.query.filter( + FreightRpaSource.source_code.in_([SOURCE_CODE, extra.source_code]), + ).all() + assert len(sources) == 2 + + count = {'n': 0} + + def _count_query(*_args, **_kwargs): + count['n'] += 1 + + event.listen(db.engine, 'before_cursor_execute', _count_query) + try: + resolve_source_file_statuses(sources) + finally: + event.remove(db.engine, 'before_cursor_execute', _count_query) + # [断言意图] 逐来源投影约 7 次/来源;两个来源仍必须落在固定的几次批量查询里。 + assert count['n'] <= 8 diff --git a/backend/tests/services/in_transit_transfer/test_status_machine.py b/backend/tests/services/in_transit_transfer/test_status_machine.py index ebe480d6..bd81c3ea 100644 --- a/backend/tests/services/in_transit_transfer/test_status_machine.py +++ b/backend/tests/services/in_transit_transfer/test_status_machine.py @@ -26,7 +26,7 @@ pytestmark = pytest.mark.pure_unit PROMPT_STATUSES = { "file_pending", "file_ready", "matching", "ready_to_execute", "executing", - "success", "duplicate_success", "blocked_recoverable", "not_matured", + "success", "duplicate_success", "blocked_recoverable", "result_unknown", "manually_closed", "cancelled", "notification_failed", } @@ -102,11 +102,6 @@ def test_unknown_status_rejected(): assert_transition_allowed("no_such_status", TransferStatus.SUCCESS.value) -def test_not_matured_has_no_outgoing_edges(): - """not_matured 无出边:当天不得查询 外部系统、不得生成调拨单。""" - assert ITEM_TRANSITIONS[TransferStatus.NOT_MATURED.value] == frozenset() - - def test_run_transition_queued_to_executing_path(): """Run 生命周期:queued → preparing_files → matching → ready_to_execute → executing。""" assert_transition_allowed(TransferRunStatus.QUEUED.value, TransferRunStatus.PREPARING_FILES.value, transitions=RUN_TRANSITIONS) diff --git a/backend/tests/services/in_transit_transfer/test_transfer_movement_ledger_model.py b/backend/tests/services/in_transit_transfer/test_transfer_movement_ledger_model.py new file mode 100644 index 00000000..149ff254 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_transfer_movement_ledger_model.py @@ -0,0 +1,220 @@ +"""transfer_movement_ledger 模型契约测试(ADR 0001 库存异动档)。 + +用途:锁定库存异动档表(规格 §4.2)的模型契约——表名/自然键唯一约束/ + 可空成分 NOT NULL + default ''/transfer_executed 默认 false/ + source_file_id FK ON DELETE SET NULL(文件清理后档事实留存)。 +依赖:app_ctx(根 conftest app fixture 上下文别名)、transfer_db(SQLite 内存库)、 + models/in_transit_transfer、models/shipping_inbound_report。 +逻辑:纯元数据断言(不落库)+ 真库往返(默认值/唯一约束/FK SET NULL 行为)。 +""" + +from __future__ import annotations + +import pytest +from sqlalchemy import inspect, text +from sqlalchemy.exc import IntegrityError + +from app import db +from app.models import FreightRpaInboundReportFile +from app.models.in_transit_transfer import TransferMovementLedger + +# 自然键成分(幂等增量落地的去重键,规格 §4.2 + tt14 扩维 + 2026-10-21 外部身份 +# 扩维):10 成分全部 NOT NULL,可空语义成分(line_seq/in_out_flag/carton_id/ +# lot_no/external_doc_no/external_line_no)default ''(R7 终审:carton_id/lot_no +# NOT NULL + default '',防 PG NULL 逃逸唯一比对;外部身份两列同口径)。 +NATURAL_KEY_COLUMNS = ( + 'source_code', 'record_kind', 'doc_no', 'line_no', 'line_seq', 'in_out_flag', +) +NATURAL_KEY_DIMENSION_COLUMNS = ('carton_id', 'lot_no', 'external_doc_no', 'external_line_no') +NATURAL_KEY_CONSTRAINT = 'uq_transfer_movement_ledger_natural_key' + +# 规格 §4.2 全部业务/证据列(除自然键成分与回写布尔外一律 nullable)。 +NULLABLE_BUSINESS_COLUMNS = ( + 'material_code', 'material_name', 'specification', 'quantity', 'unit', + 'warehouse_code', 'storage_code', 'movement_date', + 'order_type', 'odm_id', 'odm_name', 'pallet_id', + 'doc_nature', 'movement_type', 'reason_code', 'source_ref_no', 'partner_code', 'remark', + 'source_file_id', 'file_version', 'file_sha256', 'sheet_name', 'row_no', + 'executed_doc_no', +) + + +@pytest.fixture +def app_ctx(app): + """根 conftest app fixture 的语义别名:app fixture 产出时已处于 app_context 内。""" + return app + + +def _column_map() -> dict: + return {c.name: c for c in TransferMovementLedger.__table__.columns} + + +def test_table_name_and_natural_key_constraint(app_ctx): + """表名固定;自然键十成分(tt14 扩维 carton_id/lot_no + 2026-10-21 外部单据身份)构成唯一约束。""" + assert TransferMovementLedger.__tablename__ == 'transfer_movement_ledger' + constraints = { + c.name: [col.name for col in c.columns] + for c in TransferMovementLedger.__table__.constraints + if c.name + } + assert constraints[NATURAL_KEY_CONSTRAINT] == list( + NATURAL_KEY_COLUMNS + NATURAL_KEY_DIMENSION_COLUMNS, + ) + + +def test_natural_key_columns_not_null_with_empty_default(app_ctx): + """自然键 10 成分全部 NOT NULL;可空语义成分 default ''(R7:carton_id/lot_no 同口径)。""" + cols = _column_map() + for name in NATURAL_KEY_COLUMNS + NATURAL_KEY_DIMENSION_COLUMNS: + assert cols[name].nullable is False, f"{name} 必须参与自然键即 NOT NULL" + # 与落档链路同口径:可空语义成分以空串入库(唯一约束可比,防 PG NULL 逃逸)。 + for name in ('line_seq', 'in_out_flag', 'carton_id', 'lot_no', + 'external_doc_no', 'external_line_no'): + assert cols[name].default.arg == '' + assert cols[name].server_default.arg == '' + + +def test_business_columns_nullable_and_types(app_ctx): + """业务/证据列一律 nullable(外部系统列宽松落地);数量 String(40)、日期 String(16)。""" + cols = _column_map() + for name in NULLABLE_BUSINESS_COLUMNS: + assert cols[name].nullable is True, f"{name} 为可空业务列" + assert cols['quantity'].type.length == 40 # 数量 Decimal 文本,与 items 同约定 + assert cols['movement_date'].type.length == 16 # 日期文本,与 items.movement_date 同约定 + assert cols['remark'].type.python_type is str # 预留列 remark 为 Text + + +def test_transfer_executed_defaults_false(app_ctx): + """平台回写封存位:NOT NULL 默认 false;executed_doc_no 可空。""" + cols = _column_map() + assert cols['transfer_executed'].nullable is False + assert cols['transfer_executed'].default.arg is False + assert cols['executed_doc_no'].nullable is True + + +def test_scope_indexes_declared(app_ctx): + """圈档/封存扫描两条索引:(source_code, record_kind, movement_date) 与 (record_kind, transfer_executed)。""" + indexes = { + ix.name: [col.name for col in ix.columns] + for ix in TransferMovementLedger.__table__.indexes + if ix.name + } + assert sorted(indexes['ix_transfer_movement_ledger_source_kind_date']) == sorted( + ['source_code', 'record_kind', 'movement_date'], + ) + assert sorted(indexes['ix_transfer_movement_ledger_kind_executed']) == sorted( + ['record_kind', 'transfer_executed'], + ) + + +def test_source_file_fk_on_delete_set_null(app_ctx): + """source_file_id FK 指向 freight_rpa_inbound_report_files 且 ON DELETE SET NULL(档事实留存)。""" + cols = _column_map() + fk = next( + fk for fk in TransferMovementLedger.__table__.foreign_keys + if fk.parent.name == 'source_file_id' + ) + assert fk.target_fullname == 'freight_rpa_inbound_report_files.id' + assert fk.ondelete == 'SET NULL' + assert cols['source_file_id'].nullable is True + + +def test_ledger_roundtrip_with_defaults(transfer_db): + """最小自然键落地:默认值生效(line_seq/in_out_flag 空串、transfer_executed false)。""" + ledger = TransferMovementLedger( + source_code='DBS-AWSBI', + record_kind='receipt', + doc_no='HOM-20261014-001', + line_no='10', + material_code='MAT-001', + quantity='12.5', + movement_date='2026-10-14', + source_file_id=None, + ) + db.session.add(ledger) + db.session.flush() + + loaded = db.session.get(TransferMovementLedger, ledger.id) + assert loaded.line_seq == '' + assert loaded.in_out_flag == '' + assert loaded.transfer_executed is False + assert loaded.executed_doc_no is None + assert loaded.created_at is not None and loaded.updated_at is not None + + +def test_duplicate_natural_key_rejected(transfer_db): + """自然键唯一约束 DB 兜底:同八成分二次落地必须失败。 + + carton_id/lot_no(R7)与 line_seq/in_out_flag 同口径:ORM default '' + DB + server_default '',未传维度列的行以空串入键即可触发约束。 + """ + def _make() -> TransferMovementLedger: + return TransferMovementLedger( + source_code='DBS-AWSBI', + record_kind='receipt', + doc_no='HOM-20261014-001', + line_no='10', + ) + + db.session.add(_make()) + db.session.flush() + db.session.add(_make()) + with pytest.raises(IntegrityError): + db.session.flush() + db.session.rollback() + + +def test_source_file_relationship_and_delete_sets_null(app, transfer_db): + """source_file relationship 可导航;来源文件删除后档记录留存且 source_file_id 置 NULL。""" + from app.models import FreightRpaInboundUnitRun + + unit_run = FreightRpaInboundUnitRun( + source_id=1, # SQLite 无 FK 强制(PRAGMA 未开),无需真实来源行 + source_code='DBS-AWSBI', + connector_type='rpa', + callback_id='CB-LEDGER-001', + ) + db.session.add(unit_run) + db.session.flush() + report_file = FreightRpaInboundReportFile( + unit_run_id=unit_run.id, + storage_provider='minio', + storage_bucket='receipts', + storage_key='receipts/hom-20261014.xlsx', + original_filename='hom-20261014.xlsx', + file_size=1024, + sha256='a' * 64, + ) + db.session.add(report_file) + db.session.flush() + ledger = TransferMovementLedger( + source_code='DBS-AWSBI', + record_kind='receipt', + doc_no='HOM-20261014-002', + line_no='1', + source_file_id=report_file.id, + file_version='v1', + file_sha256='a' * 64, + ) + db.session.add(ledger) + db.session.commit() + + loaded = db.session.get(TransferMovementLedger, ledger.id) + assert loaded.source_file.id == report_file.id # relationship 目标 FreightRpaInboundReportFile + + # ON DELETE SET NULL 行为:开启 SQLite FK 强制后原样删文件(文件资产保留策略)。 + # PRAGMA 是连接级开关且事务内为 no-op:必须走 AUTOCOMMIT 连接执行,归还连接池 + # 前关闭,否则 FK 强制残留会污染 app fixture 收尾的 drop_all(悬空 FK 拒解析)。 + file_id = report_file.id + ledger_id = ledger.id + with db.engine.connect().execution_options(isolation_level='AUTOCOMMIT') as conn: + conn.execute(text('PRAGMA foreign_keys=ON')) + conn.execute( + text('DELETE FROM freight_rpa_inbound_report_files WHERE id = :id'), + {'id': file_id}, + ) + conn.execute(text('PRAGMA foreign_keys=OFF')) + db.session.expire_all() + survivor = db.session.get(TransferMovementLedger, ledger_id) + assert survivor is not None # 档事实不随文件消失 + assert survivor.source_file_id is None # 链接仅溯源,删文件置 NULL diff --git a/backend/tests/services/in_transit_transfer/test_transfer_type.py b/backend/tests/services/in_transit_transfer/test_transfer_type.py index 735d79a7..6bd7534d 100644 --- a/backend/tests/services/in_transit_transfer/test_transfer_type.py +++ b/backend/tests/services/in_transit_transfer/test_transfer_type.py @@ -1,91 +1,93 @@ -"""在途调拨类型契约测试(L1 纯单元)。 +"""在途调拨类型门禁测试(配置化,L1)。 -用途:验证调拨类型规范化/支持性门禁/类型 1 INVOICE 前缀过滤与范围说明。 -依赖:transfer_type 模块、invoice_aggregator(构造汇总单)。 -逻辑:纯函数测试,不创建 Flask/DB。 +用途:验证 resolve_transfer_type 的三段 fail-closed 门禁——必填(None/空 → + REQUIRED)、存在性(空表/无此码 → NOT_CONFIGURED)、启停(停用 → + DISABLED;require_enabled=False 存量放行),以及正常配置解析返回 DTO。 +依赖:app fixture(配置表)、factories.seed_transfer_type_config。 +逻辑:类型合法值=transfer_type_configs.code(ADR 0002/D8:不做种子数据、 + 匹配创建必填、fail-closed)。 """ from __future__ import annotations -from datetime import date -from decimal import Decimal - import pytest from app.core.errors import ValidationError -from app.services.in_transit_transfer.invoice_aggregator import AggregatedInvoice from app.services.in_transit_transfer.transfer_type import ( - HUB_REPAIR_OUT_ODM_ID, - IN_TRANSIT_TO_HUB_INVOICE_PREFIXES, - TRANSFER_TYPE_NOT_SUPPORTED, - TransferType, - ensure_transfer_type_supported, - filter_invoices_for_type, - normalize_transfer_type, - transfer_type_scope_note, + TRANSFER_TYPE_DISABLED, + TRANSFER_TYPE_NOT_CONFIGURED, + TRANSFER_TYPE_REQUIRED, + resolve_transfer_type, ) +from tests.services.in_transit_transfer.factories import seed_transfer_type_config + +pytestmark = [pytest.mark.usefixtures("app")] -def _invoice(invoice_no: str) -> AggregatedInvoice: - """构造最小汇总单(过滤只看 invoice_no)。""" - return AggregatedInvoice( - source_code="DBS-AWSBI", invoice_no=invoice_no, material_no="MAT-001", - material_name="连接器组件", specification="A 型", - receipt_date=date(2026, 8, 5), receipt_quantity=Decimal("100"), - raw_lines=(), - ) +@pytest.fixture(autouse=True) +def _empty_transfer_type_configs(): + """类型门禁专项用例要求可控配置表:清空套件 autouse 种子后由用例自行播种。 + + Why: 域内 conftest 的 _seed_default_transfer_type 为全部 app 用例预置默认 + 类型;本模块锁定的是「空表/无此码/停用」的门禁形态,必须从空表出发。 + How to apply: 每用例开始前 delete 全部配置行(conftest autouse 先于本 + fixture 运行,播种被清除);需要配置的用例再调 seed_transfer_type_config。 + """ + from app import db + from app.models import TransferTypeConfig + + db.session.query(TransferTypeConfig).delete() + db.session.commit() + yield -def test_normalize_transfer_type_defaults_to_in_transit_to_hub(): - """缺省/空值/None 回落类型 1(存量调用方语义不变)。""" - assert normalize_transfer_type(None) == TransferType.IN_TRANSIT_TO_HUB - assert normalize_transfer_type("") == TransferType.IN_TRANSIT_TO_HUB - assert normalize_transfer_type("in_transit_to_hub") == TransferType.IN_TRANSIT_TO_HUB - assert normalize_transfer_type(TransferType.HUB_TO_HUB) == TransferType.HUB_TO_HUB +def test_resolve_returns_config_dto_when_configured(): + """配置存在 → 解析成功:DTO 携带范围规则/仓库定义/转换规则三块受控对象。""" + seed_transfer_type_config() + config = resolve_transfer_type("in_transit_to_hub") + # [断言意图] 门禁返回的是引擎解析后的配置对象(非原始 JSON): + # scope_rules/transform_rules 为规则元组,warehouse_config 可按角色解析。 + assert config.code == "in_transit_to_hub" + assert config.enabled is True + assert {rule.field for rule in config.scope_rules} == {"doc_no"} + assert {rule.field for rule in config.transform_rules} == {"lot_no"} + assert config.warehouse_config.from_role.mode == "mapped" + assert config.warehouse_config.to_role.mode == "mapped" -def test_normalize_transfer_type_rejects_unknown_value(): - """非法类型值 → ValidationError(TRANSFER.TRANSFER_TYPE_INVALID)。""" - with pytest.raises(ValidationError) as exc_info: - normalize_transfer_type("not_a_type") - assert exc_info.value.code == "TRANSFER.TRANSFER_TYPE_INVALID" - - -def test_ensure_supported_rejects_placeholder_types(): - """类型 2/3 一期占位:进入处理链路被 fail-closed 拒绝。""" - ensure_transfer_type_supported(TransferType.IN_TRANSIT_TO_HUB) - for placeholder in (TransferType.HUB_REPAIR_OUT, TransferType.HUB_TO_HUB): +def test_resolve_requires_transfer_type(): + """必填(D8):None/空/空白 → TRANSFER_TYPE_REQUIRED,不回落默认类型。""" + for bad in (None, "", " "): with pytest.raises(ValidationError) as exc_info: - ensure_transfer_type_supported(placeholder) - assert exc_info.value.code == TRANSFER_TYPE_NOT_SUPPORTED + resolve_transfer_type(bad) + # [断言意图] 缺失与「未配置」是两种失败:必填缺失必须独立成码。 + assert exc_info.value.code == TRANSFER_TYPE_REQUIRED -def test_filter_type1_keeps_invoice_prefixes_case_insensitive(): - """类型 1 只保留 INVOICE 前缀 HOM/HOX/WTP(大小写不敏感)。""" - invoices = [ - _invoice("HOM-20260801-01"), - _invoice("hox-20260801-02"), - _invoice("WTP-20260801-03"), - _invoice("INV-001"), - _invoice("RCP-9"), - _invoice("OTHER-1"), - ] - kept = filter_invoices_for_type(invoices, TransferType.IN_TRANSIT_TO_HUB) - assert [invoice.invoice_no for invoice in kept] == [ - "HOM-20260801-01", "hox-20260801-02", "WTP-20260801-03", - ] +def test_resolve_rejects_when_config_table_empty_or_missing(): + """配置表为空或无此码 → TRANSFER_TYPE_NOT_CONFIGURED(fail-closed,D8)。""" + # [断言意图] 空配置表:不抛「必填」也不静默放行——NOT_CONFIGURED 独立成码。 + with pytest.raises(ValidationError) as empty_table: + resolve_transfer_type("in_transit_to_hub") + assert empty_table.value.code == TRANSFER_TYPE_NOT_CONFIGURED + + seed_transfer_type_config() + # [断言意图] 表非空但编码不存在:同一码面(存在性失败)。 + with pytest.raises(ValidationError) as unknown_code: + resolve_transfer_type("no_such_type") + assert unknown_code.value.code == TRANSFER_TYPE_NOT_CONFIGURED -def test_filter_type1_empty_invoice_no_excluded(): - """空/空白 Invoice 号不匹配任何前缀 → 排除(防御性)。""" - kept = filter_invoices_for_type([_invoice("")], TransferType.IN_TRANSIT_TO_HUB) - assert kept == [] - assert set(IN_TRANSIT_TO_HUB_INVOICE_PREFIXES) == {"HOM", "HOX", "WTP"} - assert HUB_REPAIR_OUT_ODM_ID == "HoxinRMA" +def test_resolve_rejects_disabled_type_but_allows_existing_rerun(): + """停用类型:新匹配路径 DISABLED;require_enabled=False(存量重跑/重查)放行。""" + seed_transfer_type_config(enabled=False) + with pytest.raises(ValidationError) as exc_info: + resolve_transfer_type("in_transit_to_hub") + # [断言意图] 停用 ≠ 未配置:独立成码(前端可区分「请配置」与「已停用」)。 + assert exc_info.value.code == TRANSFER_TYPE_DISABLED - -def test_scope_note_records_type_rule(): - """范围说明写入 scope_json 的审计口径。""" - assert transfer_type_scope_note(TransferType.IN_TRANSIT_TO_HUB) == "invoice_prefix:hom+hox+wtp" - assert transfer_type_scope_note(TransferType.HUB_REPAIR_OUT) == "odm_id:HoxinRMA" - assert transfer_type_scope_note(TransferType.HUB_TO_HUB) == "pending_rule" + # [断言意图] 「停用后存量不受影响」(规格 §4.1):存量匹配的重跑/重查以 + # require_enabled=False 解析同一配置,成功返回 DTO。 + config = resolve_transfer_type("in_transit_to_hub", require_enabled=False) + assert config.code == "in_transit_to_hub" + assert config.enabled is False diff --git a/backend/tests/services/in_transit_transfer/test_transfer_type_config_model.py b/backend/tests/services/in_transit_transfer/test_transfer_type_config_model.py new file mode 100644 index 00000000..47582efa --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_transfer_type_config_model.py @@ -0,0 +1,35 @@ +"""transfer_type_configs 模型契约测试。 + +用途:锁定调拨类型配置表(ADR 0002)的模型契约——表名/列定义/唯一约束, + 以及 transfer_runs.transfer_type 枚举 CHECK 已随配置化移除。 +依赖:app_ctx 夹具(根 conftest app fixture 的上下文别名)、models/in_transit_transfer。 +逻辑:纯元数据断言(不落库);迁移接线由 alembic 校验与域模型测试兜底。 +""" + +from __future__ import annotations + +import pytest + +from app.models.in_transit_transfer import TransferTypeConfig + + +@pytest.fixture +def app_ctx(app): + """根 conftest app fixture 的语义别名:app fixture 产出时已处于 app_context 内。""" + return app + + +def test_table_and_unique_code(app_ctx): + """编码唯一且不可空;names_json/scope_rules_json 等为 JSON 列。""" + assert TransferTypeConfig.__tablename__ == 'transfer_type_configs' + cols = {c.name: c for c in TransferTypeConfig.__table__.columns} + assert cols['code'].nullable is False + assert cols['names_json'].type.python_type is dict + assert cols['enabled'].default.arg is False or cols['enabled'].default.arg is True + + +def test_transfer_runs_check_dropped(): + """transfer_runs.transfer_type 不再挂枚举 CHECK 约束(配置化取代)。""" + from app.models.in_transit_transfer import TransferRun + names = {c.name for c in TransferRun.__table__.constraints if hasattr(c, 'name') and c.name} + assert 'ck_transfer_runs_transfer_type' not in names diff --git a/backend/tests/services/in_transit_transfer/test_transfer_type_config_service.py b/backend/tests/services/in_transit_transfer/test_transfer_type_config_service.py new file mode 100644 index 00000000..c7e71165 --- /dev/null +++ b/backend/tests/services/in_transit_transfer/test_transfer_type_config_service.py @@ -0,0 +1,353 @@ +"""调拨类型配置服务契约:CRUD 校验门禁、读取侧 parse 拦截、仓库角色解析四场景。 + +用途:锁定 transfer_type_config_service 对外契约——code 格式/唯一/不可变、 + names zh-CN 必填、scope_rules 默认至少一条(显式确认可豁免)、 + warehouse_config 模式白名单与 fixed 必填仓库、get_enabled 只回启用且按 + sort_order 排序、resolve_warehouse mapped/fixed 混合解析 + (Task 5 API 与 Task 11 路由接入消费本契约)。 +依赖:transfer_db 夹具(根 conftest app fixture 的 db 别名,SQLite 内存库)、 + transfer_type_config_service、matching_service.RouteMapping、scope/transform 引擎。 +逻辑:CRUD 与读取侧拦截用例走真实 ORM 落库;resolve_warehouse 与 + _parse_warehouse_config 为纯函数用例不触 DB(模块级 pure_unit 标记: + 未请求 app 的用例跳过 Flask/DB 创建,请求 transfer_db 的用例仍走 app 夹具)。 +""" + +from __future__ import annotations + +import pytest + +from app.core.errors import ValidationError +from app.models.in_transit_transfer import TransferTypeConfig +from app.services.in_transit_transfer.field_transforms import TransformRule +from app.services.in_transit_transfer.matching_service import RouteMapping +from app.services.in_transit_transfer.scope_rules import ScopeRule +from app.services.in_transit_transfer.transfer_type_config_service import ( + WarehouseConfig, + WarehouseRole, + _parse_warehouse_config, + create_config, + get_by_code, + get_enabled, + list_configs, + resolve_warehouse, + update_config, +) + +pytestmark = pytest.mark.pure_unit + +@pytest.fixture(autouse=True) +def _drop_seeded_default_type(request): + """本模块以 in_transit_to_hub 为夹具码:清掉域 conftest autouse 种子防撞码。 + + Why: 域 conftest 为全部 app 用例预置启用类型 in_transit_to_hub;本模块 + create/update 用例以同一 code 构造 VALID_PAYLOAD,需从干净配置表出发。 + How to apply: 仅对请求 app 的用例清表(pure_unit 用例不触 Flask/DB)。 + """ + if "app" not in getattr(request, "fixturenames", []): + yield + return + from app import db + from app.models import TransferTypeConfig + + db.session.query(TransferTypeConfig).delete() + db.session.commit() + yield + +# [FIXTURE] 合法载荷基线:一期「在途仓至HUB仓」等价配置(双 mapped + WTP→HOW 转换)。 +VALID_PAYLOAD = { + "code": "in_transit_to_hub", + "names": {"zh-CN": "在途仓至HUB仓", "en": "In-transit to Hub"}, + "enabled": True, + "sort_order": 10, + "scope_rules": [ + {"field": "doc_no", "match": "prefix", "values": ["HOM", "HOX", "WTP"]}, + ], + "warehouse_config": { + "from": {"mode": "mapped", "warehouse_code": None, "external_org": None}, + "to": {"mode": "mapped", "warehouse_code": None, "external_org": None}, + }, + "transform_rules": [ + {"field": "lot_no", "op": "prefix_replace", "source": "wtp", "target": "HOW"}, + ], + "description": "一期默认类型", +} + +EXPECTED_SCOPE = (ScopeRule(field="doc_no", match="prefix", values=("HOM", "HOX", "WTP")),) + + +def _route() -> RouteMapping: + """映射档路由样例:法人 ORG-1000 / 拨出在途仓 WH-TRANSIT / 拨入 HUB 仓 WH-HUB。""" + return RouteMapping(external_org="ORG-1000", from_warehouse="WH-TRANSIT", to_warehouse="WH-HUB") + + +# --------------------------------------------------------------------------- +# create_config +# --------------------------------------------------------------------------- + + +def test_create_roundtrip(transfer_db): + """创建成功:字段逐一回读;scope/transform/warehouse 三块经 parse 规范化。""" + dto = create_config(VALID_PAYLOAD, operator_id=None) + assert dto.code == "in_transit_to_hub" + assert dto.names["zh-CN"] == "在途仓至HUB仓" # names 原样保留(zh-CN 必填已过门禁) + assert dto.enabled is True + assert dto.sort_order == 10 + assert dto.description == "一期默认类型" + assert dto.updated_at is not None # ORM flush 填充 updated_at + # [断言] 规则块为引擎受控 dataclass;transform source/target 统一大写。 + assert dto.scope_rules == EXPECTED_SCOPE + assert dto.transform_rules == ( + TransformRule(field="lot_no", op="prefix_replace", source="WTP", target="HOW"), + ) + assert dto.warehouse_config.from_role.mode == "mapped" + assert dto.warehouse_config.to_role.mode == "mapped" + + reloaded = get_by_code("in_transit_to_hub") + assert reloaded == dto # 读回与创建产物全等(DTO dataclass eq) + + +def test_create_duplicate_code(transfer_db): + """重复 code 被拒,错误码稳定为 TRANSFER.TRANSFER_TYPE_CODE_EXISTS。""" + create_config(VALID_PAYLOAD, operator_id=None) + with pytest.raises(ValidationError) as exc_info: + create_config(VALID_PAYLOAD, operator_id=None) + assert exc_info.value.code == "TRANSFER.TRANSFER_TYPE_CODE_EXISTS" # 稳定错误码契约 + + +def test_create_invalid_code_format(transfer_db): + """code 必须 ^[a-z][a-z0-9_]{1,63}$;非法形态走通用参数校验码。""" + for bad in ("Bad", "1abc", "-lead", "has space", "a", "x" * 65): + with pytest.raises(ValidationError) as exc_info: + create_config({**VALID_PAYLOAD, "code": bad}, operator_id=None) + # [断言] 参数形态类失败用既有通用码 VALIDATION.INVALID_PARAM(不在四语言新增清单内)。 + assert exc_info.value.code == "VALIDATION.INVALID_PARAM", f"code={bad!r} 应被拒" + # 边界内合法:a 开头 + 下划线数字,长度 2..64。 + create_config({**VALID_PAYLOAD, "code": "a" + "b" * 63}, operator_id=None) + + +def test_create_requires_zh_cn_name(transfer_db): + """names 必填且必须含非空 zh-CN;缺 key/纯外文/空白/None 均拒。""" + no_names = {k: v for k, v in VALID_PAYLOAD.items() if k != "names"} + with pytest.raises(ValidationError) as exc_info: + create_config(no_names, operator_id=None) + assert exc_info.value.code == "VALIDATION.INVALID_PARAM" # 缺 names 整体同拒 + with pytest.raises(ValidationError) as exc_info: + create_config({**VALID_PAYLOAD, "names": {"en": "English only"}}, operator_id=None) + assert exc_info.value.code == "VALIDATION.INVALID_PARAM" + with pytest.raises(ValidationError): + create_config({**VALID_PAYLOAD, "names": {"zh-CN": " "}}, operator_id=None) # 空白同拒 + with pytest.raises(ValidationError): + create_config({**VALID_PAYLOAD, "names": None}, operator_id=None) # 非 dict 同拒 + + +def test_create_empty_scope_rules_rejected_by_default(transfer_db): + """空 scope_rules 默认拒绝(防误圈全量,规格 §6)。""" + with pytest.raises(ValidationError) as exc_info: + create_config({**VALID_PAYLOAD, "scope_rules": []}, operator_id=None) + assert exc_info.value.code == "VALIDATION.INVALID_PARAM" + with pytest.raises(ValidationError): + create_config({**VALID_PAYLOAD, "scope_rules": None}, operator_id=None) + + +def test_create_empty_scope_rules_with_explicit_confirm(transfer_db): + """「空=不限」须管理页显式确认(payload 显式确认后放行,规格 §6)。""" + dto = create_config( + {**VALID_PAYLOAD, "scope_rules": [], "allow_empty_scope_rules": True}, operator_id=None, + ) + assert dto.scope_rules == () # 显式确认后空规则合法(= 不限) + + +def test_create_warehouse_fixed_requires_code(transfer_db): + """fixed 角色缺仓库编码在保存入口即拒(TRANSFER.WAREHOUSE_CONFIG_INVALID)。""" + payload = { + **VALID_PAYLOAD, + "warehouse_config": {"from": {"mode": "fixed"}}, # fixed 无 warehouse_code + } + with pytest.raises(ValidationError) as exc_info: + create_config(payload, operator_id=None) + assert exc_info.value.code == "TRANSFER.WAREHOUSE_CONFIG_INVALID" + + +# --------------------------------------------------------------------------- +# update_config +# --------------------------------------------------------------------------- + + +def test_update_code_immutable(transfer_db): + """payload 携带不同 code 即拒(TRANSFER.TRANSFER_TYPE_CODE_IMMUTABLE);同值放行。""" + create_config(VALID_PAYLOAD, operator_id=None) + with pytest.raises(ValidationError) as exc_info: + update_config("in_transit_to_hub", {"code": "renamed_type"}, operator_id=None) + assert exc_info.value.code == "TRANSFER.TRANSFER_TYPE_CODE_IMMUTABLE" + dto = update_config( + "in_transit_to_hub", {"code": "in_transit_to_hub", "sort_order": 99}, operator_id=None, + ) + assert dto.sort_order == 99 # 携带相同 code 不视为改名,其余字段正常更新 + + +def test_update_partial_keeps_unset_fields(transfer_db): + """部分更新:未传字段保持原值;更新路径同样过 parse 门禁。""" + create_config(VALID_PAYLOAD, operator_id=None) + dto = update_config("in_transit_to_hub", {"enabled": False, "description": "停用"}, operator_id=None) + assert dto.enabled is False + assert dto.description == "停用" + assert dto.scope_rules == EXPECTED_SCOPE # 未传 scope_rules 保持不变 + with pytest.raises(ValidationError) as exc_info: + update_config( + "in_transit_to_hub", {"warehouse_config": {"to": {"mode": "fixed"}}}, operator_id=None, + ) + assert exc_info.value.code == "TRANSFER.WAREHOUSE_CONFIG_INVALID" # 更新同样校验仓库定义 + + +def test_update_rejected_payload_leaves_row_untouched(transfer_db): + """部分更新载荷任一键非法:整单拒绝且 session 中行保持原值(无半截变更)。 + + 评审 Finding 2 回归:update 先全量校验后统一赋值—— + {"description": 新值, "transform_rules": 非法} 不得先改 description 再抛错。 + """ + create_config(VALID_PAYLOAD, operator_id=None) + with pytest.raises(ValidationError) as exc_info: + update_config( + "in_transit_to_hub", + { + "description": "半截变更探测", + "transform_rules": [{"field": "lot_no", "op": "nope", "source": "A", "target": "B"}], + }, + operator_id=None, + ) + assert exc_info.value.code == "TRANSFER.TRANSFORM_RULE_INVALID" # 非法键抛引擎错误码 + # [断言] 同一 session 内直读行:description 保持原值——校验失败不落半截变更。 + row = ( + transfer_db.session.query(TransferTypeConfig) + .filter(TransferTypeConfig.code == "in_transit_to_hub") + .one() + ) + assert row.description == "一期默认类型" + assert row.transform_rules_json == [ + {"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"} + ] # 合法键值同未被触碰(create 写入的引擎规范化原值:source/target 大写) + + +def test_update_not_configured(transfer_db): + """更新不存在的类型 → TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED。""" + with pytest.raises(ValidationError) as exc_info: + update_config("no_such_type", {"enabled": False}, operator_id=None) + assert exc_info.value.code == "TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED" + + +# --------------------------------------------------------------------------- +# 读取侧 +# --------------------------------------------------------------------------- + + +def test_get_enabled_only_enabled_sorted(transfer_db): + """get_enabled 只回 enabled 且按 sort_order 升序;list_configs 回全量同序。""" + create_config(VALID_PAYLOAD, operator_id=None) # sort_order=10, enabled + create_config({**VALID_PAYLOAD, "code": "hub_repair_out", "sort_order": 5}, operator_id=None) + create_config( + {**VALID_PAYLOAD, "code": "hub_to_hub", "sort_order": 1, "enabled": False}, operator_id=None, + ) + enabled = get_enabled() + assert [d.code for d in enabled] == ["hub_repair_out", "in_transit_to_hub"] # 停用不出现在 chat 列表 + all_configs = list_configs() + assert [d.code for d in all_configs] == ["hub_to_hub", "hub_repair_out", "in_transit_to_hub"] + + +def test_get_by_code_not_configured(transfer_db): + """不存在的 code → TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED(匹配链 fail-closed 同码)。""" + with pytest.raises(ValidationError) as exc_info: + get_by_code("no_such_type") + assert exc_info.value.code == "TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED" + + +def test_read_side_parse_intercepts_dirty_rows(transfer_db): + """库内脏数据在读取侧也被拦截:DTO 组装 scope/warehouse/transform 全走 parse。""" + # ORM 直插绕过服务校验,构造三类脏数据(模型 modeled default 使 JSON 列可省略)。 + transfer_db.session.add(TransferTypeConfig( + code="dirty_scope", names_json={"zh-CN": "脏范围"}, + scope_rules_json=[{"field": "password", "match": "equals", "values": ["x"]}], + )) + transfer_db.session.add(TransferTypeConfig( + code="dirty_warehouse", names_json={"zh-CN": "脏仓库"}, + warehouse_config_json={"from": {"mode": "bogus"}}, + )) + transfer_db.session.add(TransferTypeConfig( + code="dirty_transform", names_json={"zh-CN": "脏转换"}, + transform_rules_json=[{"field": "lot_no", "op": "nope", "source": "A", "target": "B"}], + )) + transfer_db.session.commit() + + with pytest.raises(ValidationError) as exc_info: + get_by_code("dirty_scope") + assert exc_info.value.code == "TRANSFER.SCOPE_RULE_INVALID" + with pytest.raises(ValidationError) as exc_info: + get_by_code("dirty_warehouse") + assert exc_info.value.code == "TRANSFER.WAREHOUSE_CONFIG_INVALID" + with pytest.raises(ValidationError) as exc_info: + get_by_code("dirty_transform") + assert exc_info.value.code == "TRANSFER.TRANSFORM_RULE_INVALID" + + +# --------------------------------------------------------------------------- +# resolve_warehouse / _parse_warehouse_config(纯函数,不触 DB) +# --------------------------------------------------------------------------- + + +def test_resolve_warehouse_mapped_passthrough(): + """双 mapped:仓库与法人全部透传映射档(存量 DefaultRouteResolver 行为)。""" + config = _parse_warehouse_config({}) # 缺省 warehouse_config = 双 mapped + assert resolve_warehouse(_route(), config, "from") == ("ORG-1000", "WH-TRANSIT") + assert resolve_warehouse(_route(), config, "to") == ("ORG-1000", "WH-HUB") + + +def test_resolve_warehouse_fixed_overrides_warehouse(): + """fixed 覆盖该角色仓库,external_org 为空沿用映射档法人。""" + config = WarehouseConfig( + from_role=WarehouseRole(mode="mapped"), + to_role=WarehouseRole(mode="fixed", warehouse_code="WH-REPAIR"), + ) + assert resolve_warehouse(_route(), config, "to") == ("ORG-1000", "WH-REPAIR") + assert resolve_warehouse(_route(), config, "from") == ("ORG-1000", "WH-TRANSIT") # mapped 角色不受影响 + + +def test_resolve_warehouse_fixed_with_org_overrides_external_org(): + """fixed + external_org 非空:法人一并覆盖(跨法人调拨场景)。""" + config = WarehouseConfig( + from_role=WarehouseRole(mode="mapped"), + to_role=WarehouseRole(mode="fixed", warehouse_code="WH-REPAIR", external_org="ORG-9000"), + ) + assert resolve_warehouse(_route(), config, "to") == ("ORG-9000", "WH-REPAIR") + + +def test_resolve_warehouse_fixed_missing_warehouse_code_raises(): + """fixed 缺 warehouse_code(绕过 parse 直构的非法配置)在解析侧也 fail-closed。""" + config = WarehouseConfig( + from_role=WarehouseRole(mode="mapped"), + to_role=WarehouseRole(mode="fixed", warehouse_code=None), + ) + with pytest.raises(ValidationError) as exc_info: + resolve_warehouse(_route(), config, "to") + assert exc_info.value.code == "TRANSFER.WAREHOUSE_CONFIG_INVALID" + + +def test_resolve_warehouse_unknown_role_raises(): + """role 仅接受 from/to;未知角色 fail-closed(防调用方静默拿错仓库)。""" + config = _parse_warehouse_config({}) + with pytest.raises(ValidationError) as exc_info: + resolve_warehouse(_route(), config, "middle") + assert exc_info.value.code == "TRANSFER.WAREHOUSE_CONFIG_INVALID" + + +def test_parse_warehouse_config_mode_whitelist_and_normalization(): + """mode 白名单(mapped/fixed);fixed 必填非空仓库编码;缺省角色回 mapped。""" + config = _parse_warehouse_config({ + "from": {"mode": "fixed", "warehouse_code": "WH-A"}, + "to": {"mode": "mapped"}, + }) + assert config.from_role == WarehouseRole(mode="fixed", warehouse_code="WH-A") + assert config.to_role == WarehouseRole(mode="mapped") + with pytest.raises(ValidationError) as exc_info: + _parse_warehouse_config({"to": {"mode": "static"}}) # 白名单外 mode + assert exc_info.value.code == "TRANSFER.WAREHOUSE_CONFIG_INVALID" + with pytest.raises(ValidationError): + _parse_warehouse_config({"to": {"mode": "fixed", "warehouse_code": " "}}) # 空白编码同拒 diff --git a/backend/tests/services/in_transit_transfer/test_unit_field.py b/backend/tests/services/in_transit_transfer/test_unit_field.py index 660bc86f..909291e9 100644 --- a/backend/tests/services/in_transit_transfer/test_unit_field.py +++ b/backend/tests/services/in_transit_transfer/test_unit_field.py @@ -43,8 +43,12 @@ def _file(*rows: dict) -> dict: } -def _row(row_no: int, doc_no: str, *, unit: str | None = None, movement_date: str = "2026-08-05") -> dict: - """构造单条 movement 行;unit=None 表示文件中该列缺失(而非空串)。""" +def _row(row_no: int, doc_no: str, *, unit: str | None = None, movement_date: str = "2026-08-04") -> dict: + """构造单条 movement 行;unit=None 表示文件中该列缺失(而非空串)。 + + movement_date 缺省取 2026-08-04(= 业务日 08-06 的 T−2 成熟边界;更晚日期 + 会被圈档 T−2 封顶排除)。 + """ row = { "sheet": "Movement", "row_no": row_no, "doc_no": doc_no, "lot_no": f"LOT-{row_no}", "material_code": f"MAT-{row_no}", @@ -59,8 +63,13 @@ def _row(row_no: int, doc_no: str, *, unit: str | None = None, movement_date: st # ---- ① 契约:MOVEMENT_FIELDS 恰含 unit 且为第 11 个 ------------------------ def test_movement_fields_contract_contains_unit_as_11th_field(): - """契约定死 11 个字段且第 11 个为 unit:可选文本字段(空值由匹配阶段行级阻断,不产生解析失败)。""" - assert len(MOVEMENT_FIELDS) == 11 + """契约定死且第 11 个为 unit:可选文本字段(空值由匹配阶段行级阻断,不产生解析失败)。 + + 2026-10-14 扩展在 unit 之后追加 7 个可选维度字段(Task 8)——只追加、不重排, + unit 的第 11 位契约不变;2026-10-21 再追加外部单据身份 2 字段(外部单号/ + 外部项次),总数 11+7+2=20。 + """ + assert len(MOVEMENT_FIELDS) == 20 unit = MOVEMENT_FIELDS[10] # [断言意图] unit 定死在第 11 位——movement 文件列顺序契约,解析/展示/ERP 写入共用。 assert unit.code == "unit" @@ -69,7 +78,7 @@ def test_movement_fields_contract_contains_unit_as_11th_field(): # unit 不是幂等/匹配身份,也不是必填(解析层放行空值,阻断留给匹配层)。 assert unit.is_identity is False assert unit.required is False - assert len({field.code for field in MOVEMENT_FIELDS}) == 11 + assert len({field.code for field in MOVEMENT_FIELDS}) == 20 # ---- ② 解析:带出 unit 原值(仅 trim,不换算/不清洗) ----------------------- @@ -91,7 +100,7 @@ def test_missing_unit_still_parses(): _row(1, "HOM-901"), _row(2, "HOM-902", unit=" "), ]) - # [断言意图] 缺列与纯空白等价归一为空串,解析不抛 ReceiptFileSchemaError。 + # [断言意图] 缺列与纯空白等价归一为空串,解析不抛 MovementFileSchemaError。 assert [row.unit for row in parsed] == ["", ""] assert [row.invoice_no for row in parsed] == ["HOM-901", "HOM-902"] @@ -107,7 +116,7 @@ def test_unit_taken_from_erp_stock_not_from_file(app): erp.seed_stock("MAT-1", "DBS-TRANSIT", "LOT-1", "100", unit="EA") erp.seed_stock("MAT-2", "DBS-TRANSIT", "LOT-2", "100", unit="PCS") seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - result = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + result = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub") items = {item.invoice_no: item for item in result.items} # [断言意图] 文件单位列(KG/缺失)对结果零影响:两行都 executable,行 unit # 等于 ERP 返回值(EA/PCS)——单据字段只看 ERP(2026-09-24 用户拍板)。 @@ -126,7 +135,7 @@ def test_erp_missing_unit_blocked_with_route_resolved(app): erp.seed_stock("MAT-1", "DBS-TRANSIT", "LOT-1", "100") erp.seed_stock("MAT-2", "DBS-TRANSIT", "LOT-2", "100", unit="") seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - result = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + result = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub") items = {item.invoice_no: item for item in result.items} # [断言意图] ERP 缺单位只阻断本行且原因指向 ERP 侧;行已完成路由解析—— # 拨出/拨入仓库照常落列(与旧「路由前拦截仓库留空」行为的本质区别), @@ -151,7 +160,7 @@ def test_missing_unit_difference_persisted_to_row_note(transfer_db): erp.seed_stock("MAT-1", "DBS-TRANSIT", "LOT-1", "100") erp.seed_stock("MAT-2", "DBS-TRANSIT", "LOT-2", "100", unit="") seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub") restored = restore_matching(summary.matching_id) items = {item.invoice_no: item for item in restored["items"]} # [断言意图] 差异注释随行落库:restore 视图能看到 blocked_missing_unit 与原因; @@ -176,23 +185,23 @@ def test_matching_hash_freezes_unit_value_out_of_snapshot(app): deps_pcs, erp_pcs, _rpa = make_transfer_deps(_file(_row(1, "HOM-901", unit="PCS"))) erp_pcs.seed_stock("MAT-1", "DBS-TRANSIT", "LOT-1", "100") seed_rows_from_file("DBS-AWSBI", deps_kg, "2026-08-06") # 行落地一次;unit 非证据字段不触发重置 - hash_kg = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps_kg).summary.matching_hash - hash_pcs = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps_pcs).summary.matching_hash + hash_kg = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps_kg, transfer_type="in_transit_to_hub").summary.matching_hash + hash_pcs = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps_pcs, transfer_type="in_transit_to_hub").summary.matching_hash # [断言意图] unit 是展示/写入字段而非匹配身份:换单位不得漂移匹配哈希(可审计复算)。 assert hash_kg == hash_pcs -def test_matching_hash_unchanged_when_unit_backfilled_on_not_matured_rows(app): - """未成熟行补 unit 前后 Hash 不变:既有成熟过滤先行,unit 追加校验不扰动历史行结果。""" +def test_matching_hash_unchanged_when_unit_backfilled(app): + """行补 unit 前后 Hash 不变:unit 是展示/写入列而非 Hash 入参(口径冻结)。""" deps_before, _erp_a, _rpa = make_transfer_deps(_file( - _row(1, "HOM-901", movement_date="2026-08-06"), + _row(1, "HOM-901", movement_date="2026-08-04"), )) deps_after, _erp_b, _rpa = make_transfer_deps(_file( - _row(1, "HOM-901", unit="KG", movement_date="2026-08-06"), + _row(1, "HOM-901", unit="KG", movement_date="2026-08-04"), )) - seed_rows_from_file("DBS-AWSBI", deps_before, "2026-08-06") # 行落地一次(当日收料 → 未成熟) - hash_before = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps_before).summary.matching_hash - hash_after = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps_after).summary.matching_hash + seed_rows_from_file("DBS-AWSBI", deps_before, "2026-08-06") # 行落地一次 + hash_before = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps_before, transfer_type="in_transit_to_hub").summary.matching_hash + hash_after = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps_after, transfer_type="in_transit_to_hub").summary.matching_hash # [断言意图] 口径冻结锁定:对同一行集补 unit 列,历史预检(匹配)哈希不变。 assert hash_before == hash_after @@ -218,10 +227,10 @@ def test_invoice_item_unit_column_roundtrip(transfer_db): source_code="DBS-AWSBI", invoice_no=invoice_no, material_no="MAT-001", - receipt_date="2026-08-05", + movement_date="2026-08-05", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01", - receipt_quantity="100", + movement_quantity="100", status="ready_to_execute", unit=unit, raw_lines_json=[], diff --git a/backend/tests/services/in_transit_transfer/test_worker_recovery.py b/backend/tests/services/in_transit_transfer/test_worker_recovery.py index e14c2351..1f90c45d 100644 --- a/backend/tests/services/in_transit_transfer/test_worker_recovery.py +++ b/backend/tests/services/in_transit_transfer/test_worker_recovery.py @@ -29,7 +29,7 @@ def _executing_matching(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") - summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub") for item in db.session.query(TransferInvoiceItem).all(): item.status = "executing" item.updated_at = datetime.utcnow() - timedelta(hours=2) # 租约已过期 @@ -70,7 +70,7 @@ def test_finalize_stale_runs_marks_terminal(transfer_db, 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") - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub") ready_items = ( TransferInvoiceItem.query.filter_by(status="ready_to_execute") .order_by(TransferInvoiceItem.id) diff --git a/backend/tests/services/in_transit_transfer/test_write_recheck.py b/backend/tests/services/in_transit_transfer/test_write_recheck.py index 4ceb3422..ee391480 100644 --- a/backend/tests/services/in_transit_transfer/test_write_recheck.py +++ b/backend/tests/services/in_transit_transfer/test_write_recheck.py @@ -35,7 +35,7 @@ def _ready_items(dbs_ready_file, *seeds) -> tuple: erp.seed_stock(*_INVOICE_TUPLES[invoice_no], quantity) deps, erp, _ = make_transfer_deps(dbs_ready_file, capabilities=erp) seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06") - create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) + create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub") items = ( TransferInvoiceItem.query.filter_by(status="ready_to_execute") .order_by(TransferInvoiceItem.id) diff --git a/backend/tests/services/shipping_notice/test_inventory_candidate_projection.py b/backend/tests/services/shipping_notice/test_onhand_candidate_projection.py similarity index 80% rename from backend/tests/services/shipping_notice/test_inventory_candidate_projection.py rename to backend/tests/services/shipping_notice/test_onhand_candidate_projection.py index f63675e6..aac31346 100644 --- a/backend/tests/services/shipping_notice/test_inventory_candidate_projection.py +++ b/backend/tests/services/shipping_notice/test_onhand_candidate_projection.py @@ -1,5 +1,5 @@ """ -tests/services/shipping_notice/test_inventory_candidate_projection.py +tests/services/shipping_notice/test_onhand_candidate_projection.py 用途:验证正式 Task 的 active CandidateSet 读取、缺失阻断与版本化候选事实投影。 依赖:Flask app fixture、ShippingNotice / CandidateSet / CandidateLine ORM、候选 projector。 @@ -10,19 +10,19 @@ from __future__ import annotations from app import db from app.models import ( - ShippingInventoryCandidateLine, - ShippingInventoryCandidateSet, - ShippingInventoryCandidateSource, + ShippingOnhandCandidateLine, + ShippingOnhandCandidateSet, + ShippingOnhandCandidateSource, ShippingOrderTask, ShippingOrderSnapshot, ShippingOrderSnapshotLine, - ShippingNoticeLineInventoryMatch, - ShippingInventoryFile, + ShippingNoticeLineOnhandMatch, + FreightRpaOnhandReportFile, ) -from app.services.shipping_notice.inventory_candidate_projection import ( +from app.services.shipping_notice.onhand_candidate_projection import ( project_inventory_candidate_facts, ) -from app.services.shipping_notice.stp_line_inventory_match import prepare_candidate_inventory_lines +from app.services.shipping_notice.stp_line_onhand_match import prepare_candidate_onhand_lines def _task(task_no: str) -> ShippingOrderTask: @@ -36,8 +36,8 @@ def _task(task_no: str) -> ShippingOrderTask: return task -def _candidate_set(task: ShippingOrderTask, version: int = 1) -> ShippingInventoryCandidateSet: - row = ShippingInventoryCandidateSet( +def _candidate_set(task: ShippingOrderTask, version: int = 1) -> ShippingOnhandCandidateSet: + row = ShippingOnhandCandidateSet( task_id=int(task.id), set_version=version, lifecycle_status='frozen', @@ -50,12 +50,12 @@ def _candidate_set(task: ShippingOrderTask, version: int = 1) -> ShippingInvento return row -def test_prepare_candidate_inventory_lines_blocks_without_active_set(app): +def test_prepare_candidate_onhand_lines_blocks_without_active_set(app): with app.app_context(): task = _task('SN-CAND-001') db.session.commit() - result = prepare_candidate_inventory_lines(task) + result = prepare_candidate_onhand_lines(task) assert result['status'] == 'blocked' assert result['error_code'] == 'inventory_candidates_missing' @@ -66,13 +66,13 @@ def test_project_inventory_candidate_facts_reads_current_structured_set(app): with app.app_context(): task = _task('SN-CAND-002') candidate_set = _candidate_set(task, version=2) - source = ShippingInventoryCandidateSource( + source = ShippingOnhandCandidateSource( candidate_set_id=int(candidate_set.id), source_code='DBS_DUB', candidate_order=1, candidate_origin='rule', ) - line = ShippingInventoryCandidateLine( + line = ShippingOnhandCandidateLine( candidate_set_id=int(candidate_set.id), line_no=1, source_line_no='00010', @@ -99,14 +99,14 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app): with app.app_context(): task = _task('SN-CAND-003') old_set = _candidate_set(task, version=1) - old_line = ShippingInventoryCandidateLine( + old_line = ShippingOnhandCandidateLine( candidate_set_id=int(old_set.id), line_no=1, source_codes_json=['DBS_OLD'], ) db.session.add(old_line) db.session.flush() - new_set = ShippingInventoryCandidateSet( + new_set = ShippingOnhandCandidateSet( task_id=int(task.id), set_version=2, lifecycle_status='frozen', @@ -116,7 +116,7 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app): db.session.flush() task.active_inventory_candidate_set_id = int(new_set.id) db.session.flush() - new_line = ShippingInventoryCandidateLine( + new_line = ShippingOnhandCandidateLine( candidate_set_id=int(new_set.id), line_no=1, source_codes_json=['DBS_NEW'], @@ -132,7 +132,7 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app): snapshot_line = ShippingOrderSnapshotLine(snapshot_id=int(snapshot.id), line_no=1, position=0) db.session.add(snapshot_line) db.session.flush() - db.session.add(ShippingNoticeLineInventoryMatch( + db.session.add(ShippingNoticeLineOnhandMatch( task_id=int(task.id), snapshot_line_id=int(snapshot_line.id), line_no=1, @@ -141,8 +141,8 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app): candidate_set_version=1, candidate_line_id=int(old_line.id), match_result='matched', - inventory_status='ready', - inventory_source_code='DBS_OLD', + onhand_status='ready', + source_code='DBS_OLD', is_current=True, allowed_source_codes_snapshot=['DBS_OLD'], detail_json={'disposition': 'ok'}, @@ -161,12 +161,12 @@ def test_project_inventory_candidate_facts_reads_file_evidence_from_snapshot(app with app.app_context(): task = _task('SN-CAND-EVIDENCE') candidate_set = _candidate_set(task) - db.session.add(ShippingInventoryCandidateLine( + db.session.add(ShippingOnhandCandidateLine( candidate_set_id=int(candidate_set.id), line_no=1, source_codes_json=['DBS_DUB'], )) db.session.flush() - inventory_file = ShippingInventoryFile( - inventory_file_no='INV-CAND-EVIDENCE', storage_path='memory://evidence.xlsx', + inventory_file = FreightRpaOnhandReportFile( + onhand_file_no='INV-CAND-EVIDENCE', storage_path='memory://evidence.xlsx', source_code='DBS_DUB', snapshot_status='ready', file_sha256='b' * 64, ) db.session.add(inventory_file) @@ -180,11 +180,11 @@ def test_project_inventory_candidate_facts_reads_file_evidence_from_snapshot(app snapshot_line = ShippingOrderSnapshotLine(snapshot_id=int(snapshot.id), line_no=1, position=0) db.session.add(snapshot_line) db.session.flush() - db.session.add(ShippingNoticeLineInventoryMatch( + db.session.add(ShippingNoticeLineOnhandMatch( task_id=int(task.id), snapshot_line_id=int(snapshot_line.id), line_no=1, candidate_set_id=int(candidate_set.id), - candidate_set_version=1, inventory_snapshot_id=int(inventory_file.id), match_result='matched', - inventory_status='ready', inventory_source_code='DBS_DUB', matched_file_no=inventory_file.inventory_file_no, + candidate_set_version=1, onhand_snapshot_id=int(inventory_file.id), match_result='matched', + onhand_status='ready', source_code='DBS_DUB', matched_file_no=inventory_file.onhand_file_no, matched_row_index=9, is_current=True, detail_json={}, )) db.session.commit() diff --git a/backend/tests/services/shipping_notice/test_onhand_report_handler.py b/backend/tests/services/shipping_notice/test_onhand_report_handler.py new file mode 100644 index 00000000..81c2e965 --- /dev/null +++ b/backend/tests/services/shipping_notice/test_onhand_report_handler.py @@ -0,0 +1,791 @@ +"""tests/services/shipping_notice/test_onhand_report_handler.py + +用途:阶段 B Task 7 修复轮——onhand 报表事实投递接线与处理函数契约测试: + 单回调/批量 worker 在文件行 commit 后投递事实(先 commit 再投递、处理函数 + 失败外抛且文件行保留)、success 事实 settle 等待中的候选准备并同步门禁 + (处理函数自行 commit、重放不重复候选行)、失败事实不发明候选行; + 修复轮 2 补批量契约:单文件处理函数失败不跳过其余文件投递与排程收口、 + Job 意外异常 requeue 可重试;修复轮 3 补:失败点回滚半途写(不被后续 + commit 持久化)、drop 文件清理先于错误外抛、Job 重试「只重投失败文件」 + 通道(callback_id 已消费拦不住重投、未完成绝不返回 ok)。 +依赖:app(SQLite)fixture、freight_rpa.reports.dispatch / facts、 + freight_rpa.onhand.report_store(候选 settle 所绑文件行的唯一插入入口)、 + onhand_rpa_workflow(回调入口 + 重试通道/专用异常)、onhand_recovery_service + (候选准备表)、jobs.handlers.freight_rpa_onhand_callback_process(Job 收口)。 +逻辑:直接处理函数用例以 monkeypatch 替身 gate 同步记录调用(不断言 Gate 全链); + e2e 投递用例复用 test_shipping_notice_inventory_rpa_workflow 的动态订单/ + 客户确认/库存源种子 harness,跑通 rpa_report_inventory / + process_rpa_report_inventory_batch 全程后在注册表注入记录器断言事实字段; + 批量失败用例以替身 finalize 记录收口调用(内部预存在 NameError 与本契约无关)。 +""" + +from __future__ import annotations + +import pytest + +from tests.conftest import inventory_xlsx_with_warehouse + + +@pytest.fixture +def db_session(app): + """复用 app 夹具已建立的应用上下文会话,供测试直接落库与查询。""" + from app import db + + return db.session + + +@pytest.fixture(autouse=True) +def _fake_gate_sync(monkeypatch): + """替身门禁同步:记录 (execution_id) 调用序列,不跑 Gate 全链(聚焦候选/提交契约)。""" + calls: list[int] = [] + + def _record(**kwargs): + calls.append(int(kwargs['execution'].id)) + + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', + _record, + ) + return calls + + +def _seed_waiting_preparation(db_session, *, task_no: str, execution_no: str): + """构造「任务 + 活动执行 + 等待中候选准备轮次(waiting SourceAttempt)」。 + + Returns: + (task, execution, preparation, source_row) 四元组。 + """ + from app.models import ( + ShippingOnhandPreparationAttempt, + ShippingOnhandPreparationSourceAttempt, + ShippingOrderTask, + ShippingProcessExecution, + ) + + task = ShippingOrderTask( + task_no=task_no, user_id=1, source_type='direct_pdf', status='ready', + ) + db_session.add(task) + db_session.flush() + execution = ShippingProcessExecution( + execution_no=execution_no, task_id=task.id, status='active', + ) + db_session.add(execution) + db_session.flush() + task.active_process_execution_id = execution.id + preparation = ShippingOnhandPreparationAttempt( + task_id=task.id, attempt_no=1, status='waiting_external', + ) + db_session.add(preparation) + db_session.flush() + source_row = ShippingOnhandPreparationSourceAttempt( + preparation_attempt_id=preparation.id, source_code='DSV360_AWSDU', status='waiting', + ) + db_session.add(source_row) + db_session.commit() + return task, execution, preparation, source_row + + +def _onhand_file_id(*, source_code: str = 'DSV360_AWSDU') -> int: + """经唯一插入入口 report_store 落一行 ready onhand 报表文件并 commit,返回 file_id。""" + from app import db + from app.services.freight_rpa.onhand.report_store import insert_onhand_report + from app.services.shipping_notice.onhand_file_store import generate_inventory_file_no + + file_id = insert_onhand_report( + onhand_file_no=generate_inventory_file_no(), + storage_path='handler://onhand-report-fact.xlsx', + source_code=source_code, + snapshot_status='ready', + file_sha256='a' * 64, + ) + db.session.commit() + return file_id + + +def test_onhand_fact_settles_waiting_candidates_and_syncs_gates(app, db_session, _fake_gate_sync): + """success 事实:settle 等待候选(ready + 绑文件)→ 聚合准备轮次 → 门禁同步 → 自行 commit。""" + from app.models import ShippingOnhandPreparationAttempt, ShippingOnhandPreparationSourceAttempt + from app.services.freight_rpa.reports.facts import ReportFact + from app.services.shipping_notice.onhand_report_handler import handle_onhand_report + + task, execution, preparation, source_row = _seed_waiting_preparation( + db_session, task_no='OT-ONHAND-FACT-SETTLE', execution_no='EX-ONHAND-FACT-SETTLE', + ) + file_id = _onhand_file_id() + + handle_onhand_report(ReportFact( + report_kind='onhand', source_code='DSV360_AWSDU', + file_id=file_id, sha256='a' * 64, ok=True, + )) + + # [断言意图] 处理函数必须自行 commit:rollback + expire_all 后 settle 仍可见。 + db_session.rollback() + db_session.expire_all() + refreshed_source = db_session.get(ShippingOnhandPreparationSourceAttempt, source_row.id) + assert refreshed_source.status == 'ready' + assert refreshed_source.onhand_file_id == file_id + refreshed_prep = db_session.get(ShippingOnhandPreparationAttempt, preparation.id) + assert refreshed_prep.status == 'succeeded' + assert refreshed_prep.completed_at is not None + # [断言意图] 门禁同步覆盖 settle 受影响的准备轮次任务(execution 绑定同任务)。 + assert _fake_gate_sync == [execution.id] + + # [重放] 同一事实重复投递:等待集已空——不重复 settle、不重复候选行(幂等)。 + handle_onhand_report(ReportFact( + report_kind='onhand', source_code='DSV360_AWSDU', + file_id=file_id, sha256='a' * 64, ok=True, + )) + db_session.rollback() + db_session.expire_all() + assert ShippingOnhandPreparationSourceAttempt.query.count() == 1 + assert db_session.get(ShippingOnhandPreparationSourceAttempt, source_row.id).onhand_file_id == file_id + assert db_session.get(ShippingOnhandPreparationAttempt, preparation.id).status == 'succeeded' + + +def test_onhand_failure_fact_invents_no_candidate_rows(app, db_session, _fake_gate_sync): + """失败/空事实:无文件可挂——不发明候选行(SourceAttempt 保持 waiting、不绑文件),仅重投影门禁。""" + from app.models import ShippingOnhandPreparationSourceAttempt + from app.services.freight_rpa.reports.facts import ReportFact + from app.services.shipping_notice.onhand_report_handler import handle_onhand_report + + task, execution, preparation, source_row = _seed_waiting_preparation( + db_session, task_no='OT-ONHAND-FACT-FAIL', execution_no='EX-ONHAND-FACT-FAIL', + ) + + handle_onhand_report(ReportFact( + report_kind='onhand', source_code='DSV360_AWSDU', + file_id=None, sha256=None, ok=False, + error_code='rpa_export_failed', error_message='boom', + )) + + db_session.rollback() + db_session.expire_all() + # [断言意图] 失败事实没有文件身份:不得发明/改写候选行——仍是唯一一行、 + # 状态保持 waiting、未绑定任何文件;门禁重投影(失败路径门禁更新归处理函数)。 + assert ShippingOnhandPreparationSourceAttempt.query.count() == 1 + refreshed = db_session.get(ShippingOnhandPreparationSourceAttempt, source_row.id) + assert refreshed.status == 'waiting' + assert refreshed.onhand_file_id is None + assert _fake_gate_sync == [execution.id] + + +def _seed_direct_rpa_task(db, *, task_no: str, run_no: str, sample) -> None: + """复用动态订单 harness:直建 OT + 动态订单 + 客户确认 + 库存源种子 + RPA 触发种子。""" + from app.models import ShippingOrderTask + from tests.conftest import seed_rpa_inventory_trigger, seed_task_inventory_source + from tests.test_shipping_notice_inventory_rpa_workflow import ( + _attach_dynamic_order, + _confirm_direct_rpa_task_customer, + ) + + task = ShippingOrderTask( + task_no=task_no, user_id=1, source_type='direct_pdf', status='ready', + ) + db.session.add(task) + db.session.flush() + _attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1) + _confirm_direct_rpa_task_customer(task) + seed_task_inventory_source(task, source_code='DSV360_AWSDU') + seed_rpa_inventory_trigger(task, run_no=run_no) + db.session.add(task) + db.session.commit() + + +def _stub_structure_validation(monkeypatch): + """替身结构校验:onhand_structure_drift 仍读已删站点列(Task 2 已记录的 deferred + minor,legacy 套件待 s18 改写)——与本修复无关;本测试聚焦 commit 后投递接线。 + + 返回与真实 validate_production_inventory_structure 同形状的确定性解析参数: + field_mapping 用 conftest 种子字段 ID 对齐样例 xlsx 列头 + (Warehouse ID / SKU / Reservation ID / Qty,表头行 1,默认 sheet)。 + """ + from app.models import FreightRpaOnhandField + + fields = { + row.field_code: row + for row in FreightRpaOnhandField.query.filter( + FreightRpaOnhandField.field_code.in_( + ['part_number', 'reservation_id', 'available_qty', 'warehouse_id'], + ) + ) + } + structure_check = { + 'field_mapping': { + str(fields['part_number'].id): 'SKU', + str(fields['reservation_id'].id): 'Reservation ID', + str(fields['available_qty'].id): 'Qty', + str(fields['warehouse_id'].id): 'Warehouse ID', + }, + 'header_row_index': 1, + 'sheet_name': 'Sheet', + 'level': 'exact', + 'difference': {}, + 'warnings': [], + } + monkeypatch.setattr( + 'app.services.shipping_notice.onhand_structure_drift.validate_production_inventory_structure', + lambda **_kwargs: structure_check, + ) + + +def test_single_callback_dispatches_onhand_fact_after_file_commit(app, tmp_path, monkeypatch): + """rpa_report_inventory:文件行 commit 后同请求投递 onhand 事实,字段与已提交行对齐。""" + from app import db + from app.models import FreightRpaOnhandReportFile + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.freight_rpa.reports.facts import ReportFact + from app.services.shipping_notice.onhand_rpa_workflow import rpa_report_inventory + from tests.conftest import rpa_callback_payload + + drop_dir = tmp_path / 'drop' + drop_dir.mkdir() + app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir) + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage') + sample = drop_dir / 'onhand-fact.xlsx' + sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue()) + + seen: list[ReportFact] = [] + register_report_handler('onhand', seen.append) + + with app.app_context(): + from app.models import ShippingOrderTask + + _stub_structure_validation(monkeypatch) + _seed_direct_rpa_task(db, task_no='OT-ONHAND-FACT-DISPATCH', run_no='RUN-ONHAND-FACT', sample=sample) + task = ShippingOrderTask.query.filter_by(task_no='OT-ONHAND-FACT-DISPATCH').one() + result = rpa_report_inventory(rpa_callback_payload(task, sample, run_no='RUN-ONHAND-FACT')) + + snap = FreightRpaOnhandReportFile.query.filter_by( + rpa_run_no='RUN-ONHAND-FACT', snapshot_status='ready', + ).first() + assert snap is not None + assert result.get('status') == 'ok' + # [断言意图] commit 后投递:恰好一条事实、字段与已提交文件行逐项对齐。 + assert len(seen) == 1 + fact = seen[0] + assert fact.report_kind == 'onhand' + assert fact.ok is True + assert fact.file_id == snap.id + assert fact.source_code == 'DSV360_AWSDU' + assert fact.sha256 == snap.file_sha256 + # 文件行已提交:rollback 后重查仍在(先 commit 再投递的顺序契约)。 + db.session.rollback() + db.session.expire_all() + assert db.session.get(FreightRpaOnhandReportFile, snap.id) is not None + + +def test_single_callback_handler_failure_propagates_and_keeps_file_row(app, tmp_path, monkeypatch): + """处理函数抛错:异常原样外抛(不折进 post_commit_warnings),已提交文件行保留。""" + from app import db + from app.models import FreightRpaOnhandReportFile, ShippingOrderTask + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.shipping_notice.onhand_rpa_workflow import rpa_report_inventory + from tests.conftest import rpa_callback_payload + + drop_dir = tmp_path / 'drop' + drop_dir.mkdir() + app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir) + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage') + sample = drop_dir / 'onhand-fact-fail.xlsx' + sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue()) + + def boom(_fact) -> None: + raise RuntimeError('onhand handler down') + + register_report_handler('onhand', boom) + + with app.app_context(): + _stub_structure_validation(monkeypatch) + _seed_direct_rpa_task(db, task_no='OT-ONHAND-FACT-RAISE', run_no='RUN-ONHAND-FACT-RAISE', sample=sample) + task = ShippingOrderTask.query.filter_by(task_no='OT-ONHAND-FACT-RAISE').one() + + # [断言意图] 异常必须外抛(供 Worker 重试整笔回调),绝不折进 warnings 后返回 ok。 + with pytest.raises(RuntimeError, match='onhand handler down'): + rpa_report_inventory(rpa_callback_payload(task, sample, run_no='RUN-ONHAND-FACT-RAISE')) + + snap = FreightRpaOnhandReportFile.query.filter_by( + rpa_run_no='RUN-ONHAND-FACT-RAISE', snapshot_status='ready', + ).first() + assert snap is not None + db.session.rollback() + db.session.expire_all() + # [断言意图] 处理函数失败不回滚已提交文件行。 + assert db.session.get(FreightRpaOnhandReportFile, snap.id) is not None + + +def test_batch_worker_dispatches_onhand_fact_after_commit(app, tmp_path, monkeypatch): + """process_rpa_report_inventory_batch:整批事务 commit 后逐文件投递 onhand 事实。""" + from app import db + from app.models import FreightRpaOnhandReportFile + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.freight_rpa.reports.facts import ReportFact + from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch + from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload + + drop_dir = tmp_path / 'drop' + drop_dir.mkdir() + app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir) + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage') + sample = drop_dir / 'onhand-fact-batch.xlsx' + sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue()) + + seen: list[ReportFact] = [] + register_report_handler('onhand', seen.append) + + with app.app_context(): + _stub_structure_validation(monkeypatch) + _seed_direct_rpa_task(db, task_no='OT-ONHAND-FACT-BATCH', run_no='RUN-ONHAND-FACT-BATCH', sample=sample) + task_no = 'OT-ONHAND-FACT-BATCH' + + result = process_rpa_report_inventory_batch(v2_inventory_batch_payload({ + 'run_no': 'RUN-ONHAND-FACT-BATCH', + 'trigger_type': 'on_demand', + 'results': [scheduled_rpa_batch_item( + 'DSV360_AWSDU', success=True, file_path=str(sample), task_no=task_no, + )], + })) + assert result.get('status') == 'ok' + assert result.get('data', {}).get('success_count') == 1 + + snap = FreightRpaOnhandReportFile.query.filter_by( + rpa_run_no='RUN-ONHAND-FACT-BATCH', snapshot_status='ready', + ).first() + assert snap is not None + # [断言意图] 整批 commit 后逐文件投递:恰一条 ok=True 事实,file_id 对齐已提交行。 + assert [fact.file_id for fact in seen] == [snap.id] + assert all(fact.report_kind == 'onhand' and fact.ok is True for fact in seen) + db.session.rollback() + db.session.expire_all() + assert db.session.get(FreightRpaOnhandReportFile, snap.id) is not None + + +def test_batch_handler_failure_does_not_skip_remaining_dispatch_or_finalize(app, tmp_path, monkeypatch): + """批量内单文件处理函数失败:其余已提交文件仍投递、排程收口仍执行、错误仍外抛、文件行保留。""" + from app import db + from app.models import ScheduleRun, ScheduleTask, FreightRpaOnhandReportFile + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.freight_rpa.reports.facts import ReportFact + from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch + from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload + + drop_dir = tmp_path / 'drop' + drop_dir.mkdir() + app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir) + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage') + sample_a = drop_dir / 'onhand-fact-batch-a.xlsx' + sample_a.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue()) + sample_b = drop_dir / 'onhand-fact-batch-b.xlsx' + sample_b.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue()) + + # [断言意图·观测点] 排程收口必须仍被调用(内部预存在 NameError 与本契约无关)。 + finalize_calls: list = [] + monkeypatch.setattr( + 'app.services.schedule.freight_rpa_onhand_finalize.finalize_shipping_inventory_schedule_run', + lambda schedule_run_id, **_kwargs: ( + finalize_calls.append(schedule_run_id) + or {'ok': True, 'schedule_finalize_status': 'finalized'} + ), + ) + # [断言意图·观测点] 首个文件处理函数失败,第二个必须照常收到事实。 + seen: list[ReportFact] = [] + calls = {'n': 0} + + def flaky(fact: ReportFact) -> None: + calls['n'] += 1 + seen.append(fact) + if calls['n'] == 1: + raise RuntimeError('onhand handler down mid-batch') + + register_report_handler('onhand', flaky) + + with app.app_context(): + _stub_structure_validation(monkeypatch) + task = ScheduleTask( + schedule_no='SCH-ONHAND-BATCH-FAIL', name='Onhand batch fail', schedule_type='platform_job', + platform_api_path='freight-rpa-onhand', owner_user_id=1, cron_expr='0 8 * * *', + ) + db.session.add(task) + db.session.flush() + run = ScheduleRun( + run_no='RUN-ONHAND-BATCH-FAIL', schedule_task_id=task.id, status='running', + total_count=2, success_count=0, failed_count=0, skipped_count=0, + response_summary_json={'awaiting_rpa': True}, + ) + db.session.add(run) + db.session.commit() + + # [断言意图] 处理函数异常必须外抛(调用方/Job 见到失败)——但不得因此跳过 + # 其余文件投递与排程收口(断言在 pytest.raises 之后进行)。 + with pytest.raises(RuntimeError, match='onhand handler down mid-batch'): + process_rpa_report_inventory_batch(v2_inventory_batch_payload({ + 'run_no': 'RUN-ONHAND-BATCH-FAIL', + 'schedule_run_id': run.id, + 'trigger_type': 'scheduled', + 'results': [ + scheduled_rpa_batch_item( + 'DSV360_AWSDU', success=True, file_path=str(sample_a), source_run_no='SR-BATCH-FAIL-A', + ), + scheduled_rpa_batch_item( + 'DSV360_AWSDU', success=True, file_path=str(sample_b), source_run_no='SR-BATCH-FAIL-B', + ), + ], + })) + + snaps = FreightRpaOnhandReportFile.query.filter( + FreightRpaOnhandReportFile.snapshot_status == 'ready', + FreightRpaOnhandReportFile.rpa_run_no.in_(('SR-BATCH-FAIL-A', 'SR-BATCH-FAIL-B')), + ).order_by(FreightRpaOnhandReportFile.id).all() + # [断言意图] 两个文件行都已落库并保留(commit 先于投递,失败不回滚)。 + assert [snap.rpa_run_no for snap in snaps] == ['SR-BATCH-FAIL-A', 'SR-BATCH-FAIL-B'] + # [断言意图] 两个文件的事实都投递了(首文件失败不跳过次文件投递)。 + assert [fact.file_id for fact in seen] == [snap.id for snap in snaps] + # [断言意图] 排程收口仍执行(不被处理函数失败跳过)。 + assert finalize_calls == [run.id] + db.session.rollback() + db.session.expire_all() + assert {db.session.get(FreightRpaOnhandReportFile, snap.id) is not None for snap in snaps} == {True} + + +def test_callback_process_job_requeues_on_unexpected_exception(app, monkeypatch): + """Job 意外异常(含批量 commit 后处理函数失败重抛)必须可重试 requeue,而非终态 failed。""" + from app import db + from app.jobs.context import JobContext + from app.jobs.handlers import freight_rpa_onhand_callback_process as handler + from app.models import Job + + with app.app_context(): + job = Job( + domain='shipping_notice', + job_type='freight_rpa_onhand_callback_process', + status='running', + attempts=1, + max_attempts=3, + business_ref='inventory-callback:retryable-check', + payload_json={'callback_id': 'retryable-check'}, + ) + db.session.add(job) + db.session.commit() + + def _boom(_payload): + raise RuntimeError('dispatch re-raise after commit') + + monkeypatch.setattr( + 'app.services.shipping_notice.onhand_rpa_workflow.process_rpa_report_inventory_batch', + _boom, + ) + + handler.run_shipping_inventory_callback_process( + JobContext(config={}, logger=None, extras={}), {'job_id': job.id}, + ) + db_session = db.session + db_session.expire_all() + # [断言意图] retryable=True → requeue(attempts 未耗尽时回到 queued 等待重试), + # 绝不落终态 failed——批量文件行已提交,重放按幂等契约补齐收口。 + refreshed = db_session.get(Job, job.id) + assert refreshed.status == 'queued' + + +def test_batch_handler_failure_rolls_back_partial_writes_and_next_file_dispatches(app, db_session, tmp_path, monkeypatch): + """批量内处理函数「先 bind 候选再抛错」:半途 flush 写必须回滚(不得被后续 commit 持久化),次文件照常投递。""" + from app import db + from app.models import FreightRpaOnhandReportFile, ShippingOnhandPreparationSourceAttempt + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.freight_rpa.reports.facts import ReportFact + from app.services.shipping_notice.onhand_report_handler import handle_onhand_report + from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch + from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload + + drop_dir = tmp_path / 'drop' + drop_dir.mkdir() + app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir) + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage') + sample_a = drop_dir / 'rollback-a.xlsx' + sample_a.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue()) + sample_b = drop_dir / 'rollback-b.xlsx' + sample_b.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue()) + + seen: list[ReportFact] = [] + calls = {'n': 0} + + def bind_then_raise_or_settle(fact: ReportFact) -> None: + calls['n'] += 1 + seen.append(fact) + if calls['n'] == 1: + # [RED 场景] 模拟「先 bind 候选再抛错」的处理函数:半途 flush(不 commit)。 + from app.models import ShippingOnhandPreparationSourceAttempt as _Row + + row = ( + _Row.query.filter_by(source_code='DSV360_AWSDU') + .order_by(_Row.id) + .first() + ) + row.status = 'ready' + row.onhand_file_id = int(fact.file_id) + db.session.flush() + raise RuntimeError('bind then raise mid-batch') + # 次文件走真实处理函数:内部 settle(等待集)→ 门禁同步 → 自行 commit。 + handle_onhand_report(fact) + + register_report_handler('onhand', bind_then_raise_or_settle) + + with app.app_context(): + _stub_structure_validation(monkeypatch) + _task, _execution, _preparation, source_row = _seed_waiting_preparation( + db_session, task_no='OT-ONHAND-ROLLBACK', execution_no='EX-ONHAND-ROLLBACK', + ) + + with pytest.raises(RuntimeError, match='bind then raise mid-batch'): + process_rpa_report_inventory_batch(v2_inventory_batch_payload({ + 'run_no': 'RUN-ONHAND-ROLLBACK', + 'trigger_type': 'on_demand', + 'results': [ + scheduled_rpa_batch_item( + 'DSV360_AWSDU', success=True, file_path=str(sample_a), source_run_no='SR-ROLLBACK-A', + ), + scheduled_rpa_batch_item( + 'DSV360_AWSDU', success=True, file_path=str(sample_b), source_run_no='SR-ROLLBACK-B', + ), + ], + })) + + snaps = FreightRpaOnhandReportFile.query.filter( + FreightRpaOnhandReportFile.snapshot_status == 'ready', + FreightRpaOnhandReportFile.rpa_run_no.in_(('SR-ROLLBACK-A', 'SR-ROLLBACK-B')), + ).order_by(FreightRpaOnhandReportFile.id).all() + # [断言意图] 次文件照常投递:两个已提交文件的事实都送达处理函数。 + assert [fact.file_id for fact in seen] == [snap.id for snap in snaps] + + db.session.rollback() + db.session.expire_all() + # [断言意图] 首文件半途 bind 已回滚——不得被次文件处理函数的 commit 持久化成 + # file-A 绑定;次文件真实 settle 落到 file B(等待集在回滚后原样可 settle)。 + refreshed = db.session.get(ShippingOnhandPreparationSourceAttempt, source_row.id) + assert refreshed.status == 'ready' + assert refreshed.onhand_file_id == snaps[1].id + + +def test_batch_handler_failure_still_flushes_drop_file_cleanup_before_raise(app, tmp_path, monkeypatch): + """处理函数抛错:drop 文件清理(消费标记+移动/入队)必须先于错误外抛完成。""" + from app import db + from app.models import FreightRpaOnhandReportFile + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch + from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload + + drop_dir = tmp_path / 'drop' + drop_dir.mkdir() + app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir) + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage') + sample = drop_dir / 'cleanup-before-raise.xlsx' + sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue()) + + def boom(_fact) -> None: + raise RuntimeError('onhand handler down cleanup') + + register_report_handler('onhand', boom) + + with app.app_context(): + _stub_structure_validation(monkeypatch) + _seed_direct_rpa_task(db, task_no='OT-ONHAND-CLEANUP', run_no='RUN-ONHAND-CLEANUP', sample=sample) + + with pytest.raises(RuntimeError, match='onhand handler down cleanup'): + process_rpa_report_inventory_batch(v2_inventory_batch_payload({ + 'run_no': 'RUN-ONHAND-CLEANUP', + 'trigger_type': 'on_demand', + 'results': [scheduled_rpa_batch_item( + 'DSV360_AWSDU', success=True, file_path=str(sample), task_no='OT-ONHAND-CLEANUP', + )], + })) + + snap = FreightRpaOnhandReportFile.query.filter_by( + rpa_run_no='RUN-ONHAND-CLEANUP', snapshot_status='ready', + ).first() + assert snap is not None + # [断言意图] 错误已外抛,但 drop 文件清理先行完成:消费标记/移动先于重抛, + # 文件离开 drop 根、落入 processed 归档(移动失败时则入持久化 cleanup 队列)。 + assert not sample.exists() + assert (drop_dir / 'processed' / sample.name).exists() + + +def test_batch_retry_channel_redispatches_file_despite_consumed_callback_id(app, tmp_path, monkeypatch): + """重试通道:task-linked 项 Attempt 已消费 callback_id(整批重放必被跳过)时,失败文件仍重投事实。""" + from datetime import datetime + + from app import db + from app.models import FreightRpaOnhandReportFile, ShippingOrderTask, FreightRpaOnhandTaskAttempt + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.freight_rpa.reports.facts import ReportFact + from app.services.shipping_notice.onhand_rpa_workflow import ( + OnhandReportDispatchAfterCommitError, + process_rpa_report_inventory_batch, + ) + from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload + + drop_dir = tmp_path / 'drop' + drop_dir.mkdir() + app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir) + app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage') + sample = drop_dir / 'retry-callback-id.xlsx' + sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue()) + + seen: list[ReportFact] = [] + calls = {'n': 0} + + def flaky(fact: ReportFact) -> None: + calls['n'] += 1 + seen.append(fact) + if calls['n'] == 1: + raise RuntimeError('onhand handler down first pass') + + register_report_handler('onhand', flaky) + + with app.app_context(): + _stub_structure_validation(monkeypatch) + _seed_direct_rpa_task(db, task_no='OT-ONHAND-RETRY', run_no='RUN-ONHAND-RETRY', sample=sample) + task = ShippingOrderTask.query.filter_by(task_no='OT-ONHAND-RETRY').one() + candidate_set_id = int(task.active_inventory_candidate_set_id or 1) + # [RED 场景] 结构化 per-source Attempt(v2 身份字段与回调 item 对齐): + # pass 1 的回调确认会把 attempt.callback_id 写入——整批重放随即被 replay 检查跳过。 + # source_run_no 用与批量 run_no 不同的 PSR 轮次号(与真实 Worker 形态一致: + # run_no=批量轮次、source_run_no=逐源轮次——run_no 消费标记按 source_run_no + # 匹配,不会误吞本 Attempt)。 + attempt = FreightRpaOnhandTaskAttempt( + task_no='OT-ONHAND-RETRY', + source_code='DSV360_AWSDU', + attempt_no=1, + source_run_no='PSR-ONHAND-RETRY-1', + status='queued', + triggered_at=datetime.utcnow(), + lease_token='test-lease-token', + execution_phase='trigger_written', + extra_json={ + 'trigger_mode': 'test', + 'candidate_set_id': candidate_set_id, + 'execution_id': 1, + 'gate_id': 1, + }, + ) + db.session.add(attempt) + db.session.commit() + + batch_payload = v2_inventory_batch_payload({ + 'run_no': 'RUN-ONHAND-RETRY', + 'trigger_type': 'on_demand', + 'results': [dict( + scheduled_rpa_batch_item( + 'DSV360_AWSDU', success=True, file_path=str(sample), task_no='OT-ONHAND-RETRY', + ), + callback_id='test-callback:RUN-ONHAND-RETRY', + source_run_no='PSR-ONHAND-RETRY-1', + attempt_no=1, + lease_token='test-lease-token', + candidate_set_id=candidate_set_id, + execution_id=1, + gate_id=1, + )], + }) + + # [STEP 1] 首轮:文件落地+回调确认(写 callback_id)+投递失败 → 专用异常携带清单外抛。 + with pytest.raises(OnhandReportDispatchAfterCommitError) as excinfo: + process_rpa_report_inventory_batch(batch_payload) + + snap = FreightRpaOnhandReportFile.query.filter_by( + rpa_run_no='PSR-ONHAND-RETRY-1', snapshot_status='ready', + ).first() + assert snap is not None + assert excinfo.value.failed_files == [{ + 'source_code': 'DSV360_AWSDU', + 'file_id': snap.id, + 'sha256': (snap.file_sha256 or None), + }] + # [断言意图·RED 场景] Attempt 已消费 callback_id——整批重放会被 replay 检查跳过。 + db.session.expire(attempt) + assert str(attempt.callback_id or '').strip() + armed_callback_id = str(attempt.callback_id) + + # [STEP 2] 整批重放(不带重试清单):item 被 replay 检查跳过——不落地、不投递, + # 证明整批重放无法补投(这正是「只重投失败文件」通道存在的原因)。 + replay_result = process_rpa_report_inventory_batch(dict(batch_payload)) + assert [fact.file_id for fact in seen] == [snap.id] + assert replay_result.get('data', {}).get('created') == [] + assert armed_callback_id == str( + FreightRpaOnhandTaskAttempt.query.filter_by( + task_no='OT-ONHAND-RETRY', source_code='DSV360_AWSDU', + ).order_by(FreightRpaOnhandTaskAttempt.id.desc()).first().callback_id or '', + ) + + # [STEP 3] 重试通道(Job 处理器写回的 retry_dispatch_files):只重投失败文件。 + retry_payload = {**batch_payload, 'retry_dispatch_files': excinfo.value.failed_files} + result = process_rpa_report_inventory_batch(retry_payload) + assert result.get('status') == 'ok' + assert result.get('data', {}).get('result_status') == 'retried' + # [断言意图] 同一 file_id 的事实再次送达处理函数(callback_id 已消费拦不住重投)。 + assert [fact.file_id for fact in seen] == [snap.id, snap.id] + + +def test_batch_retry_channel_reraises_while_handler_still_failing(app, monkeypatch): + """重试通道:处理函数仍未成功时必须继续携带清单重抛,绝不在未完成时返回 ok。""" + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.shipping_notice.onhand_rpa_workflow import ( + OnhandReportDispatchAfterCommitError, + process_rpa_report_inventory_batch, + ) + + def boom(_fact) -> None: + raise RuntimeError('onhand handler still down') + + register_report_handler('onhand', boom) + + with app.app_context(): + file_id = _onhand_file_id() + marker = {'source_code': 'DSV360_AWSDU', 'file_id': file_id, 'sha256': None} + + # [断言意图] 处理函数持续失败:重试通道继续抛专用异常(携带同一未成功清单, + # Job 据此继续 requeue 直至 attempts 耗尽落终态 failed)——绝不返回 ok。 + with pytest.raises(OnhandReportDispatchAfterCommitError) as excinfo: + process_rpa_report_inventory_batch({'retry_dispatch_files': [marker]}) + assert excinfo.value.failed_files == [marker] + + +def test_callback_process_job_records_failed_files_for_retry(app, monkeypatch): + """Job 收口:投递失败重抛的清单写回 payload(retry_dispatch_files)并 requeue 可重试。""" + from app import db + from app.jobs.context import JobContext + from app.jobs.handlers import freight_rpa_onhand_callback_process as handler + from app.models import Job + from app.services.shipping_notice.onhand_rpa_workflow import OnhandReportDispatchAfterCommitError + + marker = {'source_code': 'DSV360_AWSDU', 'file_id': 4242, 'sha256': 'a' * 64} + + with app.app_context(): + job = Job( + domain='shipping_notice', + job_type='freight_rpa_onhand_callback_process', + status='running', + attempts=1, + max_attempts=3, + business_ref='inventory-callback:dispatch-retry-check', + payload_json={'callback_id': 'dispatch-retry-check'}, + ) + db.session.add(job) + db.session.commit() + + def _raise_dispatch_error(_payload): + raise OnhandReportDispatchAfterCommitError( + 'onhand handler down after commit', failed_files=[dict(marker)], + ) + + monkeypatch.setattr( + 'app.services.shipping_notice.onhand_rpa_workflow.process_rpa_report_inventory_batch', + _raise_dispatch_error, + ) + + handler.run_shipping_inventory_callback_process( + JobContext(config={}, logger=None, extras={}), {'job_id': job.id}, + ) + db.session.expire_all() + # [断言意图] 清单写回 payload(重试只重投这些文件)+ requeue 可重试。 + refreshed = db.session.get(Job, job.id) + assert refreshed.status == 'queued' + assert refreshed.payload_json['retry_dispatch_files'] == [marker] diff --git a/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py b/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py index 6c92183f..ee6f2935 100644 --- a/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py +++ b/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py @@ -418,7 +418,7 @@ def test_pending_successor_gate_clears_a_resolved_field_conflict_from_current_ta facts = _project_case_formal_gate_facts({ 'current_gate': { - 'gate_code': 'inventory_source_routing', + 'gate_code': 'onhand_source_routing', 'status': 'pending', 'blocking_reason_code': None, 'next_action_code': None, @@ -430,7 +430,7 @@ def test_pending_successor_gate_clears_a_resolved_field_conflict_from_current_ta assert facts is not None current_gate, blocking_reason, user_status = facts - assert current_gate['gate_code'] == 'inventory_source_routing' + assert current_gate['gate_code'] == 'onhand_source_routing' assert blocking_reason['code'] is None assert user_status == 'running' diff --git a/backend/tests/services/shipping_notice/test_report_model_boundary.py b/backend/tests/services/shipping_notice/test_report_model_boundary.py new file mode 100644 index 00000000..b6763d5f --- /dev/null +++ b/backend/tests/services/shipping_notice/test_report_model_boundary.py @@ -0,0 +1,32 @@ +""" +tests/services/shipping_notice/test_report_model_boundary.py + +用途:阶段 B Task 5 边界门禁——禁止发货域(shipping_notice)源码直接构造 + 货代 RPA 报表模型行(FreightRpaOnhandReportFile / FreightRpaInboundReportFile / + FreightRpaInboundReportConfig 的构造调用)。插入必须经 + freight_rpa/onhand/report_store,读取/下载必须走 freight_rpa/reports 查询面。 +依赖:无运行时依赖(纯文件系统扫描);backend/app/services/shipping_notice 源码。 +逻辑:rglob 全部 *.py 逐文件搜禁词构造片段;命中即失败并列出文件与片段, + 保证违规时能一眼定位,而不是只报一个计数。 +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +pytestmark = pytest.mark.pure_unit + + +def test_shipping_notice_does_not_construct_rpa_report_rows(): + root = Path(__file__).resolve().parents[3] / "app" / "services" / "shipping_notice" + banned_snippets = ("FreightRpaOnhandReportFile(", "FreightRpaInboundReportFile(", "FreightRpaInboundReportConfig(") + hits = [] + for path in root.rglob("*.py"): + text = path.read_text(encoding="utf-8") + for snippet in banned_snippets: + if snippet in text: + hits.append(f"{path.name}: {snippet}") + # 关键断言:三类 RPA 报表行的构造调用必须全部消失(插入已收敛进 report_store)。 + assert hits == [] \ No newline at end of file diff --git a/backend/tests/test_admin_freight_rpa_onhand_config.py b/backend/tests/test_admin_freight_rpa_onhand_config.py new file mode 100644 index 00000000..d1e177cc --- /dev/null +++ b/backend/tests/test_admin_freight_rpa_onhand_config.py @@ -0,0 +1,204 @@ +""" +tests/test_admin_freight_rpa_onhand_config.py + +用途:锁定 s18 后库存站点启用门禁与在手报表配置行(FreightRpaOnhandReportConfig)的服务层行为。 +依赖:conftest 的 app fixture(建表并播种 TEST_RUNTIME 配置)、app.core.errors.ValidationError、 + freight_rpa_source_admin_service(assert_onhand_source_can_enable / save_onhand_report_config)、 + freight_rpa_report_config_service.save_inbound_report_config、 + FreightRpaOnhandReportConfig / FreightRpaSource 等模型。 +逻辑:验证启用中站点缺模板/缺配置行/缺解析绑定时 fail-closed;保存在手配置只写配置行、 + 不写站点已删除的三列,并递增配置行 config_version;在手与入站两侧解析方案 purpose 互斥。 +""" + +from __future__ import annotations + +import itertools + +import pytest + +from app.core.errors import ValidationError +from app.models import ( + FreightRpaOnhandReportConfig, FreightRpaSource, FreightRpaParsingProfile, FreightRpaProfile, +) +from app.services.admin.freight_rpa_report_config_service import save_inbound_report_config +from app.services.admin.freight_rpa_source_admin_service import ( + assert_onhand_source_can_enable, save_onhand_report_config, +) + +# 站点/连接编码自增,保证同一测试内多次构造不撞唯一约束。 +_SOURCE_SEQUENCE = itertools.count(1) + + +@pytest.fixture +def db_session(app): + """复用 app fixture 已建立的应用上下文会话,供测试直接落库与查询。""" + from app import db + + return db.session + + +def _source(*, enabled: bool, excel_template_id: int | None) -> FreightRpaSource: + """构造最小可落库的库存站点(fixed 仓库模式 + 专用连接 Profile),不自动 add 进会话。 + + Args: + enabled: 站点启用位;True 时调用方需自行保证模板/配置满足门禁或预期拒绝。 + excel_template_id: 发货模板外键;SQLite 测试库不强制外键,允许指向不存在的模板 id。 + + Returns: + FreightRpaSource: 未加入会话的站点对象,由调用方决定是否落库。 + """ + from app import db + + sequence = next(_SOURCE_SEQUENCE) + profile = FreightRpaProfile( + profile_code=f'TASK2_PROFILE_{sequence}', display_name=f'Task2 Profile {sequence}', + connector_type='dbs', login_url='https://test.invalid/dbs', + login_config_json={'auth_mode': 'password'}, + ) + db.session.add(profile) + db.session.flush() + return FreightRpaSource( + source_code=f'TASK2_SOURCE_{sequence}', display_name=f'Task2 Source {sequence}', + connector_type='dbs', rpa_profile_id=profile.id, excel_template_id=excel_template_id, + warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSDU', + enabled=enabled, + ) + + +def _published_onhand_profile_id() -> int: + """读取 conftest 播种的已发布在手解析方案(TEST_RUNTIME,purpose='onhand')。""" + profile = FreightRpaParsingProfile.query.filter_by( + profile_code='TEST_RUNTIME', status='published', + ).first() + assert profile is not None and profile.purpose == 'onhand' + return profile.id + + +def _published_inbound_profile_id(db_session) -> int: + """创建最小已发布入站解析方案,用于验证在手侧 fail-closed 拒绝跨 purpose 绑定。""" + profile = FreightRpaParsingProfile( + purpose='inbound', profile_code='TASK2_INBOUND', display_name='Task2 Inbound', + version=1, status='published', file_format='xlsx', definition_json={'field_mapping': {}}, + ) + db_session.add(profile) + db_session.commit() + return profile.id + + +def test_enabled_source_requires_onhand_profile_and_template(app, db_session): + """启用中站点缺发货模板必须被服务层拒绝。 + + [断言意图] 该状态同时违反 ck_freight_rpa_sources_enabled_template(enabled ⇒ 模板非空), + SQLite/PG 在 INSERT 时即拦截、无法落库,故按 save_source 提交前的调用形态验证未落库对象, + 与任务书原测试语义一致(服务层门禁先于数据库约束给出可解释错误码)。 + """ + source = _source(enabled=True, excel_template_id=None) + with pytest.raises(ValidationError) as exc: + assert_onhand_source_can_enable(source) + assert exc.value.code == "SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED" + + +def test_enabled_source_requires_onhand_report_config_row(app, db_session): + """启用中站点缺在手配置行时拒绝启用:配置行缺失是跨表状态,站点 CHECK 管不到。""" + source = _source(enabled=True, excel_template_id=9) + db_session.add(source) + db_session.commit() + with pytest.raises(ValidationError) as exc: + assert_onhand_source_can_enable(source) + assert exc.value.code == "SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED" + + +def test_enabled_source_requires_onhand_profile_binding(app, db_session): + """配置行存在但未绑解析方案时同样拒绝启用。""" + source = _source(enabled=True, excel_template_id=9) + db_session.add(source) + db_session.commit() + db_session.add(FreightRpaOnhandReportConfig(source=source)) + db_session.commit() + with pytest.raises(ValidationError) as exc: + assert_onhand_source_can_enable(source) + assert exc.value.code == "SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED" + + +def test_enabled_source_with_full_onhand_config_passes_gate(app, db_session): + """配置行 + 解析绑定 + 模板齐备的启用站点通过门禁(正向路径回归)。""" + source = _source(enabled=True, excel_template_id=9) + db_session.add(source) + db_session.commit() + db_session.add(FreightRpaOnhandReportConfig( + source=source, parsing_profile_id=_published_onhand_profile_id(), + )) + db_session.commit() + assert assert_onhand_source_can_enable(source) is None + + +def test_save_onhand_report_config_does_not_write_source_columns(app, db_session): + """保存在手配置只写配置行,不写站点已删除的 report_path_json 等三列。""" + source = _source(enabled=False, excel_template_id=9) + db_session.add(source) + db_session.commit() + save_onhand_report_config(source.id, { + "report_path_json": {"menu": "stock"}, + "query_parameters_json": [], + "parsing_profile_id": _published_onhand_profile_id(), + }, actor_id=1) + db_session.refresh(source) + assert not hasattr(source, "report_path_json") + config = FreightRpaOnhandReportConfig.query.filter_by(source_id=source.id).one() + assert config.report_path_json == {"menu": "stock"} + assert config.parsing_profile.purpose == "onhand" + + +def test_save_onhand_report_config_updates_row_and_bumps_config_version(app, db_session): + """已有配置行走更新并递增 config_version,行身份保持不变。""" + source = _source(enabled=False, excel_template_id=9) + db_session.add(source) + db_session.commit() + first = save_onhand_report_config(source.id, { + "report_path_json": {"menu": "stock"}, + "query_parameters_json": [], + "parsing_profile_id": _published_onhand_profile_id(), + }, actor_id=1) + second = save_onhand_report_config(source.id, { + "report_path_json": {"menu": "stock2"}, + "query_parameters_json": [], + "parsing_profile_id": _published_onhand_profile_id(), + }, actor_id=1) + assert second["id"] == first["id"] + row = FreightRpaOnhandReportConfig.query.filter_by(source_id=source.id).one() + assert row.report_path_json == {"menu": "stock2"} + # [断言意图] 首次插入默认 1,第二次保存必须递增为 2(任务书:有则更新并递增 config_version)。 + assert row.config_version == 2 + + +def test_save_onhand_report_config_rejects_non_onhand_parsing_profile(app, db_session): + """入站解析方案不得绑进在手配置;fail-closed 且不留下半写的配置行。""" + source = _source(enabled=False, excel_template_id=9) + db_session.add(source) + db_session.commit() + with pytest.raises(ValidationError) as exc: + save_onhand_report_config(source.id, { + "report_path_json": {}, + "query_parameters_json": [], + "parsing_profile_id": _published_inbound_profile_id(db_session), + }, actor_id=1) + assert exc.value.code == "SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED" + assert FreightRpaOnhandReportConfig.query.filter_by(source_id=source.id).count() == 0 + + +def test_save_inbound_report_config_keeps_inbound_only_binding(app, db_session): + """入站配置保存继续只接受 purpose='inbound' 的解析方案(在手/入站互斥回归)。""" + source = _source(enabled=False, excel_template_id=9) + db_session.add(source) + db_session.commit() + with pytest.raises(ValidationError) as exc: + save_inbound_report_config(source.id, { + # 先给合法 DBS 四段路径,确保失败点落在解析绑定校验(purpose 互斥)而非路径校验。 + "report_path_json": { + "program_group": "Bison", "program_label": "AWSBI", + "report_group": "Inbound", "report_name": "Receipt Detail", + }, + "query_parameters_json": [], + "parsing_profile_id": _published_onhand_profile_id(), + }, actor_id=1) + assert exc.value.code == "SHIPPING.INBOUND_PROFILE_INVALID" diff --git a/backend/tests/test_admin_freight_rpa_routes.py b/backend/tests/test_admin_freight_rpa_routes.py new file mode 100644 index 00000000..23226bec --- /dev/null +++ b/backend/tests/test_admin_freight_rpa_routes.py @@ -0,0 +1,87 @@ +""" +tests/test_admin_freight_rpa_routes.py + +用途:锁定货代 RPA 管理路由已迁到 /api/admin/freight-rpa/,旧 shipping-notice 管理路径 404。 +依赖:Flask 测试客户端、admin blueprint、User。 +逻辑:只断言路径注册与管理员可达;权限表存量字符串不在本测试更新。 +""" + +from __future__ import annotations + + +def _headers(username: str, role: str) -> dict[str, str]: + """构造遗留 Header 认证上下文,匹配现有管理 API 测试方式。""" + return {'X-Username': username, 'X-Role': role} + + +def _rules(app) -> set[str]: + """收集已注册的 URL 规则,用来断言旧路径没有双路由。""" + return {rule.rule for rule in app.url_map.iter_rules()} + + +def test_freight_rpa_admin_routes_moved_and_old_paths_404(app, client): + """新 sources 路径对管理员成功;旧 sources 与 inventory-fields 404;onhand/fields 已注册。""" + from app import db + from app.models import User + + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + db.session.add(User( + username='freight-rpa-admin', + email='freight-rpa-admin@example.com', + role='admin', + status='active', + )) + db.session.commit() + + headers = _headers('freight-rpa-admin', 'admin') + listed = client.get('/api/admin/freight-rpa/sources', headers=headers) + # [断言意图] 管理员读取新 sources 列表必须走统一成功 envelope。 + assert listed.status_code == 200 + body = listed.get_json() + assert body['success'] is True + assert isinstance(body['data'], list) + + # [断言意图] 旧库存源路径无兼容路由。 + assert client.get('/api/admin/shipping-notice/sources', headers=headers).status_code == 404 + # [断言意图] 旧字段目录路径无兼容路由。 + assert client.get('/api/admin/shipping-notice/inventory-fields', headers=headers).status_code == 404 + + rules = _rules(app) + # [断言意图] 字段目录已挂到 onhand/fields,且旧规则不在 url map。 + assert '/api/admin/freight-rpa/onhand/fields' in rules + assert '/api/admin/shipping-notice/inventory-fields' not in rules + assert '/api/admin/shipping-notice/sources' not in rules + # [断言意图] 任务表里的旧前缀都不能再注册(含其子路径)。 + retired_prefixes = ( + '/api/admin/shipping-notice/sources', + '/api/admin/shipping-notice/source-validation-batches', + '/api/admin/shipping-notice/snapshots', + '/api/admin/shipping-notice/export-records', + '/api/admin/shipping-notice/routing-rules', + '/api/admin/shipping-notice/routing-fields', + '/api/admin/shipping-notice/inventory-fields', + '/api/admin/shipping-notice/configuration-catalog', + '/api/admin/shipping-notice/parsing-profiles', + '/api/admin/shipping-notice/inventory-structure-analyses', + '/api/admin/shipping-notice/external-mappings', + ) + for rule in rules: + for prefix in retired_prefixes: + assert rule != prefix and not rule.startswith(prefix + '/'), rule + assert '/api/admin/freight-rpa/sources//inbound-report-config' in rules + assert '/api/admin/freight-rpa/onhand/validation-batches' in rules + + fields = client.get('/api/admin/freight-rpa/onhand/fields', headers=headers) + assert fields.status_code == 200 + assert fields.get_json()['success'] is True + + # [断言意图] 临时会话只改词根,仍留在 shipping-notice;Excel 模板不动;异动字段归 freight-rpa。 + assert '/api/admin/shipping-notice/temporary-onhand-sessions' in rules + assert '/api/admin/shipping-notice/temporary-inventory-sessions' not in rules + assert '/api/admin/shipping-notice/excel-templates' in rules + assert '/api/admin/freight-rpa/movement-fields' in rules + assert '/api/admin/shipping-notice/movement-fields' not in rules + # [断言意图] rpa-profiles 仍在 freight-rpa,不重复注册到 shipping-notice。 + assert '/api/admin/freight-rpa/rpa-profiles' in rules + assert '/api/admin/shipping-notice/rpa-profiles' not in rules diff --git a/backend/tests/test_admin_movement_fields.py b/backend/tests/test_admin_movement_fields.py index c909f548..685073c2 100644 --- a/backend/tests/test_admin_movement_fields.py +++ b/backend/tests/test_admin_movement_fields.py @@ -1,7 +1,7 @@ """ 标准异动字段目录接口测试。 -用途:验证 GET /api/admin/shipping-notice/movement-fields 下发只读领域契约。 +用途:验证 GET /api/admin/freight-rpa/movement-fields 下发只读领域契约。 依赖:Flask 管理 API、movement_contract 契约常量。 逻辑:字段目录是 immutable 常量的投影——码/类型/必填/身份标记与契约逐项一致, 不提供任何增删改入口,字段 label 由前端 i18n 渲染。 @@ -18,7 +18,8 @@ def _headers() -> dict[str, str]: def test_movement_fields_returns_fixed_catalog(app, client): - """标准异动字段目录:10 个定死字段、顺序稳定、必填/身份标记与契约一致。""" + """标准异动字段目录:18 个定死字段(11 核心 + 2026-10-14 扩展 7 可选维度)、 + 顺序稳定、必填/身份标记与契约一致。""" app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): from app.models import User @@ -26,13 +27,15 @@ def test_movement_fields_returns_fixed_catalog(app, client): db.session.add(User(username='movement-admin', email='movement-admin@example.com', role='admin', status='active')) db.session.commit() - response = client.get('/api/admin/shipping-notice/movement-fields', headers=_headers()) + response = client.get('/api/admin/freight-rpa/movement-fields', headers=_headers()) assert response.status_code == 200 data = parse_api_data(response.get_json()) # [断言意图] 字段码与顺序是前后端共同契约——后端 movement_contract 变更必须显式同步本断言。 assert [field['code'] for field in data] == [ 'doc_no', 'line_no', 'in_out_flag', 'material_code', 'material_name', 'warehouse_code', 'storage_code', 'lot_no', 'quantity', 'movement_date', + 'unit', + 'line_seq', 'specification', 'order_type', 'odm_id', 'odm_name', 'carton_id', 'pallet_id', ] required = {field['code'] for field in data if field['required']} assert required == {'doc_no', 'material_code', 'quantity', 'movement_date'} @@ -50,7 +53,7 @@ def test_movement_fields_rejects_non_admin(app, client): db.session.add(User(username='movement-user', email='movement-user@example.com', role='user', status='active')) db.session.commit() - response = client.get('/api/admin/shipping-notice/movement-fields', headers={ + response = client.get('/api/admin/freight-rpa/movement-fields', headers={ 'X-Username': 'movement-user', 'X-Role': 'user', 'Content-Type': 'application/json', }) assert response.status_code == 403 diff --git a/backend/tests/test_admin_shipping_customers.py b/backend/tests/test_admin_shipping_customers.py index df30caa8..1c030663 100644 --- a/backend/tests/test_admin_shipping_customers.py +++ b/backend/tests/test_admin_shipping_customers.py @@ -26,7 +26,7 @@ from app.models import ( ShippingOrderExtraction, ShippingOrderSnapshot, ShippingOrderSnapshotLine, - ShippingNoticeLineInventoryMatch, + ShippingNoticeLineOnhandMatch, ShippingNotice, User, ) @@ -148,12 +148,12 @@ def _notice_with_customer(*, task_no: str, customer_id: int, business_no: str | ) db.session.add(snapshot_line) db.session.flush() - db.session.add(ShippingNoticeLineInventoryMatch( + db.session.add(ShippingNoticeLineOnhandMatch( task_id=task.id, snapshot_line_id=snapshot_line.id, line_no=1, match_result='matched', - inventory_status='ready', + onhand_status='ready', is_current=True, )) notice = ShippingNotice(task_no=task_no, business_no=business_no, order_task_id=task.id) diff --git a/backend/tests/test_admin_shipping_inventory.py b/backend/tests/test_admin_shipping_inventory.py index a4f7ec36..95ce6ab2 100644 --- a/backend/tests/test_admin_shipping_inventory.py +++ b/backend/tests/test_admin_shipping_inventory.py @@ -1,9 +1,9 @@ """ tests/test_admin_shipping_inventory.py -用途:验证货代库存后台的只读快照/导出记录接口及管理员权限。 +用途:验证货代 RPA 管理端只读快照/导出记录、配置目录与站点保存接口。 依赖:Flask 测试客户端、库存文件和排程运行模型。 -逻辑:库存快照来自库存文件;没有库存文件的失败 RPA 运行也必须出现在导出记录中。 +逻辑:请求打到 /api/admin/freight-rpa/;快照来自在手文件,失败排程即使没有文件也出现在导出记录中。 """ from __future__ import annotations @@ -12,8 +12,8 @@ from datetime import datetime from pathlib import Path from app import db -from app.models import ScheduleRun, ScheduleTask, ShippingInventoryFile, User -from app.models import ShippingInventorySource, ShippingRpaProfile +from app.models import ScheduleRun, ScheduleTask, FreightRpaOnhandReportFile, User +from app.models import FreightRpaSource, FreightRpaProfile from app.services.shipping_notice.order_schema import service as order_schema_service from tests.conftest import parse_api_data, parse_api_error @@ -39,14 +39,14 @@ def test_inventory_snapshot_and_export_records_are_admin_only(app, client, tmp_p _create_users() snapshot_file = Path(tmp_path) / 'snapshot.xlsx' snapshot_file.write_bytes(b'admin-snapshot') - file_record = ShippingInventoryFile( - inventory_file_no='SIF-ADMIN-READY', storage_path=str(snapshot_file), source_code='DBS_DUB', + file_record = FreightRpaOnhandReportFile( + onhand_file_no='SIF-ADMIN-READY', storage_path=str(snapshot_file), source_code='DBS_DUB', warehouse_id='DUB', snapshot_status='ready', identity_status='verified', exported_at=datetime(2026, 7, 17, 10, 0, 0), rpa_run_no='RUN-READY-01', ) schedule_task = ScheduleTask( schedule_no='SCH-INVENTORY-FAILED', name='Inventory Export', schedule_type='platform_job', - owner_user_id=1, cron_expr='0 0 * * *', platform_api_path='shipping-inventory-rpa', + owner_user_id=1, cron_expr='0 0 * * *', platform_api_path='freight-rpa-onhand', ) db.session.add_all([file_record, schedule_task]) db.session.flush() @@ -57,23 +57,23 @@ def test_inventory_snapshot_and_export_records_are_admin_only(app, client, tmp_p )) db.session.commit() - for path in ('/api/admin/shipping-notice/snapshots', '/api/admin/shipping-notice/export-records'): + for path in ('/api/admin/freight-rpa/onhand/snapshots', '/api/admin/freight-rpa/onhand/export-records'): forbidden = client.get(path, headers=_headers('inventory-user', 'user')) assert forbidden.status_code == 403 assert parse_api_error(forbidden.get_json())['code'] == 'AUTH.FORBIDDEN' - snapshots = client.get('/api/admin/shipping-notice/snapshots', headers=_headers('inventory-admin', 'admin')) + snapshots = client.get('/api/admin/freight-rpa/onhand/snapshots', headers=_headers('inventory-admin', 'admin')) assert snapshots.status_code == 200 snapshot_rows = parse_api_data(snapshots.get_json()) assert snapshot_rows[0]['inventory_file_no'] == 'SIF-ADMIN-READY' assert 'storage_path' not in snapshot_rows[0] assert snapshot_rows[0]['download_available'] is True - downloaded = client.get('/api/admin/shipping-notice/snapshots/1/download', headers=_headers('inventory-admin', 'admin')) + downloaded = client.get('/api/admin/freight-rpa/onhand/snapshots/1/download', headers=_headers('inventory-admin', 'admin')) assert downloaded.status_code == 200 assert downloaded.data == b'admin-snapshot' - exports = client.get('/api/admin/shipping-notice/export-records', headers=_headers('inventory-admin', 'admin')) + exports = client.get('/api/admin/freight-rpa/onhand/export-records', headers=_headers('inventory-admin', 'admin')) assert exports.status_code == 200 export_rows = parse_api_data(exports.get_json()) failed_row = next(item for item in export_rows if item['rpa_run_no'] == 'RUN-FAILED-01') @@ -104,7 +104,7 @@ def test_inventory_configuration_catalog_is_admin_only_and_backend_controlled(ap }], 'expected_lock_version': draft['lock_version']}) order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version']) - path = '/api/admin/shipping-notice/configuration-catalog' + path = '/api/admin/freight-rpa/onhand/configuration-catalog' forbidden = client.get(path, headers=_headers('inventory-user', 'user')) assert forbidden.status_code == 403 @@ -128,8 +128,8 @@ def test_inventory_catalogs_remain_readable_before_order_schema_is_published(app order_schema_service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None) for path in ( - '/api/admin/shipping-notice/routing-fields', - '/api/admin/shipping-notice/configuration-catalog', + '/api/admin/freight-rpa/onhand/routing-fields', + '/api/admin/freight-rpa/onhand/configuration-catalog', ): response = client.get(path, headers=_headers('inventory-admin', 'admin')) assert response.status_code == 200 @@ -139,11 +139,11 @@ def test_inventory_catalogs_remain_readable_before_order_schema_is_published(app def test_inventory_source_api_saves_new_source_disabled_and_activation_reports_missing_steps(app, client): - """管理端普通保存不允许跳过测试直接启用,独立启用接口应返回业务缺失项。""" + """管理端普通保存不允许直接启用;独立启用接口只返回硬门槛缺失项,不含配置测试。""" app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): _create_users() - profile = ShippingRpaProfile( + profile = FreightRpaProfile( profile_code='API_ACTIVATION_LOGIN', display_name='API Activation', connector_type='dbs', login_url='https://example.invalid', login_config_json={'auth_mode': 'password'}, enabled=True, ) @@ -162,20 +162,22 @@ def test_inventory_source_api_saves_new_source_disabled_and_activation_reports_m }, 'query_parameters_json': [], } - created = client.post('/api/admin/shipping-notice/sources', json=payload, headers=_headers('inventory-admin', 'admin')) + created = client.post('/api/admin/freight-rpa/sources', json=payload, headers=_headers('inventory-admin', 'admin')) assert created.status_code == 201 source = parse_api_data(created.get_json()) assert source['enabled'] is False - assert source['activation']['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test'] + # 关键断言:配置测试已退出启用门禁,缺失项只剩解析方案与发货模板。 + assert source['activation']['missing_requirements'] == ['parsing_profile', 'excel_template'] + assert 'configuration_test' not in {item['code'] for item in source['activation']['checks']} activation = client.post( - f"/api/admin/shipping-notice/sources/{source['id']}/activate", + f"/api/admin/freight-rpa/sources/{source['id']}/activate", json={}, headers=_headers('inventory-admin', 'admin'), ) assert activation.status_code == 409 error = parse_api_error(activation.get_json()) - assert error['code'] == 'SHIPPING.INVENTORY_SOURCE_ACTIVATION_BLOCKED' - assert error['details']['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test'] + assert error['code'] == 'SHIPPING.ONHAND_SOURCE_ACTIVATION_BLOCKED' + assert error['details']['missing_requirements'] == ['parsing_profile', 'excel_template'] def test_latest_inventory_configuration_test_is_admin_only(app, client): @@ -183,25 +185,25 @@ def test_latest_inventory_configuration_test_is_admin_only(app, client): app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): _create_users() - profile = ShippingRpaProfile( + profile = FreightRpaProfile( profile_code='API_LATEST_TEST_LOGIN', display_name='Latest Test', connector_type='dbs', login_url='https://example.invalid', login_config_json={'auth_mode': 'password'}, enabled=True, ) db.session.add(profile) - source = ShippingInventorySource( + # s18 起站点行不再承载报表路径/查询条件;本用例只验证权限与空 envelope,无需配置行。 + source = FreightRpaSource( source_code='API_LATEST_TEST_SOURCE', display_name='Latest Test Source', connector_type='dbs', rpa_profile=profile, warehouse_resolution_mode='fixed', fixed_warehouse_id='DUB', - report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand'}, - query_parameters_json=[], enabled=False, + enabled=False, ) db.session.add(source) db.session.commit() source_id = source.id - forbidden = client.get(f'/api/admin/shipping-notice/sources/{source_id}/test-export/latest') + forbidden = client.get(f'/api/admin/freight-rpa/sources/{source_id}/test-export/latest') assert forbidden.status_code in {401, 403} response = client.get( - f'/api/admin/shipping-notice/sources/{source_id}/test-export/latest', + f'/api/admin/freight-rpa/sources/{source_id}/test-export/latest', headers=_headers('inventory-admin', 'admin'), ) assert response.status_code == 200 diff --git a/backend/tests/test_admin_shipping_receipt_config.py b/backend/tests/test_admin_shipping_receipt_config.py index c6bc90ad..bcb74e77 100644 --- a/backend/tests/test_admin_shipping_receipt_config.py +++ b/backend/tests/test_admin_shipping_receipt_config.py @@ -1,14 +1,16 @@ """ 收料报表配置管理接口测试。 -用途:验证站点内独立收料配置的权限、DBS/Crane 规则及不可影响库存配置的边界。 +用途:验证站点内独立入站报表配置的权限、DBS/Crane 规则及不可影响在手配置的边界。 依赖:Flask 管理 API、库存站点测试种子、货代统一审计事件。 -逻辑:配置保存只更新 shipping_receipt_report_configs,并留存前后快照审计。 +逻辑:请求打到 /api/admin/freight-rpa/sources//inbound-report-config;保存只更新入站配置并留存前后快照审计。 """ from __future__ import annotations -from app.models import ShippingAuditEvent, ShippingInventorySource, User +import pytest + +from app.models import ShippingAuditEvent, FreightRpaSource, User from tests.conftest import parse_api_data, parse_api_error @@ -47,21 +49,23 @@ def test_admin_saves_independent_dbs_receipt_config_and_audit(app, client): app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): _create_users() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() source_id = source.id + # s18 起在手报表路径/查询条件归 onhand_report_config 配置行,站点行不再承载。 + onhand_config = source.onhand_report_config inventory_before = { - 'path': dict(source.report_path_json), 'parameters': list(source.query_parameters_json), + 'path': dict(onhand_config.report_path_json), 'parameters': list(onhand_config.query_parameters_json), 'config_version': source.config_version, } forbidden = client.put( - f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config', json=_dbs_payload(), headers=_headers('receipt-user', 'user'), ) assert forbidden.status_code == 403 response = client.put( - f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config', json=_dbs_payload(), headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 200 @@ -72,13 +76,14 @@ def test_admin_saves_independent_dbs_receipt_config_and_audit(app, client): assert config['report_path_json']['report_group'] == 'Inbound' with app.app_context(): - source = ShippingInventorySource.query.get(source_id) - # 关键断言:收料配置不会借由站点抽屉保存改写库存 RPA 定义。 - assert source.report_path_json == inventory_before['path'] - assert source.query_parameters_json == inventory_before['parameters'] + source = FreightRpaSource.query.get(source_id) + # 关键断言:收料配置不会借由站点抽屉保存改写库存 RPA 定义(s18 起读配置行)。 + onhand_config = source.onhand_report_config + assert onhand_config.report_path_json == inventory_before['path'] + assert onhand_config.query_parameters_json == inventory_before['parameters'] assert source.config_version == inventory_before['config_version'] audit = ShippingAuditEvent.query.filter_by( - event_type='shipping_receipt_report_config_saved', aggregate_id=str(source_id), + event_type='shipping_inbound_report_config_saved', aggregate_id=str(source_id), ).one() assert audit.before_snapshot_json is None assert audit.after_snapshot_json['query_parameters_json'][0]['values'] == ['AWSDU', 'AWSDU-02'] @@ -89,17 +94,18 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): _create_users() - dbs = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + dbs = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() dbs_id = dbs.id from app import db crane_profile = dbs.rpa_profile.__class__( profile_code='CRANE_RECEIPT_CFG', display_name='Crane Receipt', connector_type='crane', login_url='https://crane.example.invalid', login_config_json={'auth_mode': 'password'}, ) - crane_source = ShippingInventorySource( + # s18 起站点行不再承载报表路径/查询条件;收料配置测试无需在手配置行。 + crane_source = FreightRpaSource( source_code='CRANE_RECEIPT_CFG', display_name='Crane Receipt', connector_type='crane', rpa_profile=crane_profile, warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE', - report_path_json={}, query_parameters_json=[], enabled=False, + enabled=False, ) db.session.add(crane_source) db.session.commit() @@ -108,26 +114,26 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c invalid_date = _dbs_payload() invalid_date['query_parameters_json'] = [{'name': 'Report Date', 'mode': 'single', 'values': ['2026-08-19'], 'required': False, 'select_all': False}] response = client.put( - f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{dbs_id}/inbound-report-config', json=invalid_date, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 400 - assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID' + assert parse_api_error(response.get_json())['code'] == 'SHIPPING.INBOUND_REPORT_CONFIG_INVALID' invalid_selector = _dbs_payload() invalid_selector['query_parameters_json'] = [{'name': 'Owner', 'mode': 'single', 'values': [], 'selector': '#owner'}] response = client.put( - f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{dbs_id}/inbound-report-config', json=invalid_selector, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 400 - assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID' + assert parse_api_error(response.get_json())['code'] == 'SHIPPING.INBOUND_REPORT_CONFIG_INVALID' # 关键断言:Warehouse 条件由管理员自行维护——缺失/空值允许保存,不再强制拦截。 missing_warehouse = _dbs_payload() missing_warehouse['query_parameters_json'] = [{'name': 'Owner', 'mode': 'single', 'values': ['AWS'], 'required': False, 'select_all': False}] response = client.put( - f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{dbs_id}/inbound-report-config', json=missing_warehouse, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 200 @@ -137,7 +143,7 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c empty_warehouse = _dbs_payload() empty_warehouse['query_parameters_json'] = [{'name': 'Warehouse', 'mode': 'multi_text', 'values': [], 'required': False, 'select_all': False}] response = client.put( - f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{dbs_id}/inbound-report-config', json=empty_warehouse, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 200 @@ -149,19 +155,19 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c 'query_parameters_json': [], } response = client.put( - f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{crane_id}/inbound-report-config', json=invalid_crane, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 400 - assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID' + assert parse_api_error(response.get_json())['code'] == 'SHIPPING.INBOUND_REPORT_CONFIG_INVALID' -def _create_movement_profile(profile_code: str, *, status: str, purpose: str): - """创建异动/库存解析 Profile 种子;定义仅用于绑定校验,不参与解析。""" +def _create_parsing_profile(profile_code: str, *, status: str, purpose: str): + """创建入站/在手解析 Profile 种子;定义仅用于绑定校验,不参与解析。""" from app import db - from app.models import ShippingInventoryParsingProfile + from app.models import FreightRpaParsingProfile - profile = ShippingInventoryParsingProfile( + profile = FreightRpaParsingProfile( purpose=purpose, profile_code=profile_code, display_name=f'{profile_code} 规则', version=1, status=status, file_format='xlsx', definition_json={'sheet_name': 'Movement', 'header_row_index': 1, @@ -174,19 +180,19 @@ def _create_movement_profile(profile_code: str, *, status: str, purpose: str): return profile -def test_receipt_config_binds_published_movement_profile(app, client): - """绑定已发布 movement 规则 → 保存成功,payload 携带 parsing_profile_id 与摘要,审计留痕。""" +def test_receipt_config_binds_published_inbound_profile(app, client): + """绑定已发布 inbound 规则 → 保存成功,payload 携带 parsing_profile_id 与摘要,审计留痕。""" app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): _create_users() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() source_id = source.id - profile = _create_movement_profile('CRANE_MOVE_STD', status='published', purpose='movement') + profile = _create_parsing_profile('CRANE_MOVE_STD', status='published', purpose='inbound') profile_id = profile.id payload = {**_dbs_payload(), 'parsing_profile_id': profile_id} response = client.put( - f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config', json=payload, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 200 @@ -198,31 +204,31 @@ def test_receipt_config_binds_published_movement_profile(app, client): from app.models import ShippingAuditEvent audit = ShippingAuditEvent.query.filter_by( - event_type='shipping_receipt_report_config_saved', aggregate_id=str(source_id), + event_type='shipping_inbound_report_config_saved', aggregate_id=str(source_id), ).order_by(ShippingAuditEvent.id.desc()).first() assert audit.metadata_json['parsing_profile_id'] == profile_id -def test_receipt_config_rejects_draft_or_non_movement_profile(app, client): - """draft/库存用途/不存在 的规则一律拒绝,防止误绑导致预检无法解析收料文件。""" +def test_receipt_config_rejects_draft_or_non_inbound_profile(app, client): + """draft/在手用途/不存在 的规则一律拒绝,防止误绑导致预检无法解析收料文件。""" app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): _create_users() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() source_id = source.id - draft = _create_movement_profile('MOVE_DRAFT', status='draft', purpose='movement') - inventory_profile = _create_movement_profile('INV_PUBLISHED', status='published', purpose='inventory') - cases = [draft.id, inventory_profile.id, 999999] + draft = _create_parsing_profile('MOVE_DRAFT', status='draft', purpose='inbound') + onhand_profile = _create_parsing_profile('INV_PUBLISHED', status='published', purpose='onhand') + cases = [draft.id, onhand_profile.id, 999999] for profile_id in cases: response = client.put( - f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config', json={**_dbs_payload(), 'parsing_profile_id': profile_id}, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 400, f'profile_id={profile_id}' - # 关键断言:非"已发布 movement"绑定必须走统一错误码,fail-closed。 - assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID' + # 关键断言:非"已发布 inbound"绑定必须走统一错误码,fail-closed。 + assert parse_api_error(response.get_json())['code'] == 'SHIPPING.INBOUND_PROFILE_INVALID' def test_receipt_config_empty_profile_id_unbinds(app, client): @@ -230,20 +236,20 @@ def test_receipt_config_empty_profile_id_unbinds(app, client): app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): _create_users() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() source_id = source.id - profile = _create_movement_profile('MOVE_UNBIND', status='published', purpose='movement') + profile = _create_parsing_profile('MOVE_UNBIND', status='published', purpose='inbound') profile_id = profile.id bound = client.put( - f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config', json={**_dbs_payload(), 'parsing_profile_id': profile_id}, headers=_headers('receipt-admin', 'admin'), ) assert bound.status_code == 200 unbound = client.put( - f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config', json={**_dbs_payload(), 'parsing_profile_id': None}, headers=_headers('receipt-admin', 'admin'), ) @@ -258,15 +264,16 @@ def test_crane_receipt_config_rejects_query_parameters(app, client): with app.app_context(): _create_users() from app import db - dbs = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + dbs = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() crane_profile = dbs.rpa_profile.__class__( profile_code='CRANE_RECEIPT_DEFAULT_CFG', display_name='Crane Receipt Defaults', connector_type='crane', login_url='https://crane.example.invalid', login_config_json={'auth_mode': 'password'}, ) - crane_source = ShippingInventorySource( + # s18 起站点行不再承载报表路径/查询条件;收料配置测试无需在手配置行。 + crane_source = FreightRpaSource( source_code='CRANE_RECEIPT_DEFAULT_CFG', display_name='Crane Receipt Defaults', connector_type='crane', rpa_profile=crane_profile, warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE', - report_path_json={}, query_parameters_json=[], enabled=False, + enabled=False, ) db.session.add(crane_source) db.session.commit() @@ -277,7 +284,7 @@ def test_crane_receipt_config_rejects_query_parameters(app, client): 'query_parameters_json': [], } response = client.put( - f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{crane_id}/inbound-report-config', json=default_query, headers=_headers('receipt-admin', 'admin'), ) assert response.status_code == 200 @@ -287,8 +294,41 @@ def test_crane_receipt_config_rejects_query_parameters(app, client): {'name': 'material', 'mode': 'single', 'values': ['PN-01'], 'required': False, 'select_all': False}, ]} rejected = client.put( - f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config', + f'/api/admin/freight-rpa/sources/{crane_id}/inbound-report-config', json=configured, headers=_headers('receipt-admin', 'admin'), ) assert rejected.status_code == 400 - assert parse_api_error(rejected.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID' + assert parse_api_error(rejected.get_json())['code'] == 'SHIPPING.INBOUND_REPORT_CONFIG_INVALID' + + +def test_retire_rejects_profile_bound_by_receipt_report_config(app): + """绑定收料报表配置的 published 解析 Profile 退役必须被拒(退役守卫补查)。 + + 背景:retire 此前只核查库存源(FreightRpaSource)绑定,遗漏了 + 收料报表配置(FreightRpaInboundReportConfig.parsing_profile_id)——入站文件 + 解析链会因规则退役静默失去规则。守卫补查后两者任一绑定都返回 + SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED。 + """ + from app import db + from app.models import FreightRpaInboundReportConfig + from app.services.freight_rpa import parsing_profile as onhand_parsing_profile + + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + _create_users() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + profile = _create_parsing_profile('MOVE_RETIRE_GUARD', status='published', purpose='inbound') + db.session.add(FreightRpaInboundReportConfig( + source_id=source.id, parsing_profile_id=profile.id, + report_path_json={}, query_parameters_json=[], + )) + db.session.commit() + profile_id = profile.id + + # 关键断言:仅绑定收料配置(无库存源绑定)也必须拒绝退役,沿用既有错误码。 + with pytest.raises(Exception) as exc_info: + onhand_parsing_profile.retire(profile_id) + assert getattr(exc_info.value, 'code', '') == 'SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED' + + # 关键断言:被拒后 Profile 状态保持 published,不得被半退役。 + assert FreightRpaInboundReportConfig.query.filter_by(parsing_profile_id=profile_id).count() == 1 diff --git a/backend/tests/test_chat_turn_runtime.py b/backend/tests/test_chat_turn_runtime.py index 48fc4e51..246a091e 100644 --- a/backend/tests/test_chat_turn_runtime.py +++ b/backend/tests/test_chat_turn_runtime.py @@ -197,7 +197,7 @@ def test_chat_turn_task_inventory_upload_uses_formal_inventory_handler(app, clie } monkeypatch.setattr( - 'app.services.shipping_notice.chat_action_extended_handlers.shipping_tools.upload_inventory_file', + 'app.services.shipping_notice.chat_action_extended_handlers.shipping_tools.upload_onhand_file', fake_upload_inventory, ) res = client.post( diff --git a/backend/tests/test_crane_navigation.py b/backend/tests/test_crane_navigation.py index 78138059..c212b76d 100644 --- a/backend/tests/test_crane_navigation.py +++ b/backend/tests/test_crane_navigation.py @@ -39,30 +39,48 @@ class _FakeLocator: class _FakePage: - def __init__(self, *, url: str = "https://wms-portal.craneww.com/#/") -> None: + def __init__( + self, + *, + url: str = "https://wms-portal.craneww.com/#/", + visible_tokens: tuple[str, ...] = ("on-hand-details-query", "On Hand Details", "Queries", "navbar"), + visible_role_names: tuple[str, ...] = ("On Hand Details", "Queries"), + ) -> None: self.url = url self.frames: list[_FakePage] = [] self.goto_calls: list[str] = [] + self.evaluate_calls: list[tuple[str, object]] = [] + self.reload_calls: list[int] = [] + self.locator_selectors: list[str] = [] + self._visible_tokens = visible_tokens + self._visible_role_names = visible_role_names def locator(self, selector: str) -> _FakeLocator: - if "on-hand-details-query" in selector or "On Hand Details" in selector: - return _FakeLocator(visible=True) - if "Queries" in selector or "navbar" in selector: - return _FakeLocator(visible=True) - return _FakeLocator(visible=False) + self.locator_selectors.append(selector) + visible = any(token in selector for token in self._visible_tokens) + return _FakeLocator(visible=visible) def get_by_role(self, role: str, name: str, exact: bool = False) -> _FakeLocator: - if role == "link" and name in {"On Hand Details", "Queries"}: - return _FakeLocator(visible=True) - return _FakeLocator(visible=False) + return _FakeLocator(visible=name in self._visible_role_names) def goto(self, url: str, wait_until: str = "", timeout: int = 0) -> None: self.goto_calls.append(url) self.url = url + def reload(self, wait_until: str = "", timeout: int = 0) -> None: + self.reload_calls.append(1) + + def evaluate(self, script: str, arg: object = None) -> None: + self.evaluate_calls.append((script, arg)) + if isinstance(arg, str): + self.url = f"https://wms-portal.craneww.com/#/{arg.lstrip('/')}" + + def wait_for_load_state(self, state: str = "", timeout: int = 0) -> None: + return None + def test_navigate_prefers_dashboard_tile(monkeypatch): - """应优先尝试首页 On Hand Details 卡片。""" + """应优先尝试首页目标报表卡片。""" module = _load_navigation() page = _FakePage() calls: list[str] = [] @@ -70,10 +88,10 @@ def test_navigate_prefers_dashboard_tile(monkeypatch): monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url: False) monkeypatch.setattr( module, - "_click_dashboard_on_hand_details", + "_click_dashboard_report_tile", lambda *args, **kwargs: calls.append("dashboard") or True, ) - monkeypatch.setattr(module, "_click_navbar_on_hand_details", lambda *args, **kwargs: calls.append("navbar") or True) + monkeypatch.setattr(module, "_click_navbar_report_item", lambda *args, **kwargs: calls.append("navbar") or True) monkeypatch.setattr(module, "_wait_for_report_navigation", lambda *args, **kwargs: True) mode = module.navigate_to_crane_report( @@ -95,8 +113,8 @@ def test_navigate_falls_back_to_navbar_when_dashboard_misses(monkeypatch): wait_calls = {"n": 0} monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url: False) - monkeypatch.setattr(module, "_click_dashboard_on_hand_details", lambda *args, **kwargs: True) - monkeypatch.setattr(module, "_click_navbar_on_hand_details", lambda *args, **kwargs: True) + monkeypatch.setattr(module, "_click_dashboard_report_tile", lambda *args, **kwargs: True) + monkeypatch.setattr(module, "_click_navbar_report_item", lambda *args, **kwargs: True) def _wait(page_arg, entry_url, *, browser_timeout_ms): wait_calls["n"] += 1 @@ -115,22 +133,59 @@ def test_navigate_falls_back_to_navbar_when_dashboard_misses(monkeypatch): assert wait_calls["n"] == 2 -def test_navigate_uses_direct_goto_as_last_resort(monkeypatch): - """卡片与菜单均失败时应 goto entry_url。""" +def test_direct_goto_last_resort_assigns_hash_in_place(monkeypatch): + """卡片与菜单均失败后:goto entry_url 未就绪时只允许就地赋 hash,禁止回根地址。""" module = _load_navigation() - page = _FakePage() - entry = "https://wms-portal.craneww.com/#/on-hand-details-query" + page = _FakePage(url="https://wms-portal.craneww.com/#/on-hand-details-query") + entry = "https://wms-portal.craneww.com/#/outbound-details-query" - monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url: False) - monkeypatch.setattr(module, "_click_dashboard_on_hand_details", lambda *args, **kwargs: True) - monkeypatch.setattr(module, "_click_navbar_on_hand_details", lambda *args, **kwargs: True) + monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url_arg: False) + monkeypatch.setattr(module, "_click_dashboard_report_tile", lambda *args, **kwargs: False) + monkeypatch.setattr(module, "_click_navbar_report_item", lambda *args, **kwargs: False) + + def _wait(page_arg, entry_url_arg, *, browser_timeout_ms): + # [断言意图] 就地赋 hash 之后表单才视为就绪;此前一律未就绪 + return len(page.evaluate_calls) > 0 + + monkeypatch.setattr(module, "_wait_for_report_navigation", _wait) + + mode = module.navigate_to_crane_report( + page, + entry, + env=lambda name, default="": default, + browser_timeout_ms=5_000, + ) + + assert mode == "direct_goto" + assert page.goto_calls == [entry] + assert page.reload_calls == [] + assert not any(call.rstrip("/") == "https://wms-portal.craneww.com" for call in page.goto_calls) + assert page.evaluate_calls and "outbound-details-query" in str(page.evaluate_calls[0][1]) + + +def test_navigation_never_lands_on_origin_when_form_never_ready(monkeypatch): + """表单始终未就绪也应抛 RuntimeError,且全程不得 goto 根地址或 reload(会强制登出)。""" + module = _load_navigation() + page = _FakePage(url="https://wms-portal.craneww.com/#/on-hand-details-query") + entry = "https://wms-portal.craneww.com/#/outbound-details-query" + + monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url_arg: False) + monkeypatch.setattr(module, "_click_dashboard_report_tile", lambda *args, **kwargs: False) + monkeypatch.setattr(module, "_click_navbar_report_item", lambda *args, **kwargs: False) monkeypatch.setattr(module, "_wait_for_report_navigation", lambda *args, **kwargs: False) with pytest.raises(RuntimeError, match="navigation failed"): - module.navigate_to_crane_report(page, entry, env=lambda n, d="": d, browser_timeout_ms=5_000) + module.navigate_to_crane_report( + page, + entry, + env=lambda name, default="": default, + browser_timeout_ms=5_000, + ) - assert page.goto_calls[0] == entry - assert any(call.rstrip("/") == "https://wms-portal.craneww.com" for call in page.goto_calls) + # [断言意图] 失败收场也只允许一次 goto(entry):根地址/reload 一旦发生即登出 + assert page.goto_calls == [entry] + assert page.reload_calls == [] + assert not any(call.rstrip("/") == "https://wms-portal.craneww.com" for call in page.goto_calls) def test_is_crane_on_report_route_reads_entry_hash(): @@ -157,3 +212,69 @@ def test_report_route_without_controls_is_not_ready(monkeypatch): entry = "https://wms-portal.craneww.com/#/on-hand-details-query" monkeypatch.setattr(module, "_has_report_form_controls", lambda page_arg: False) assert module.is_crane_report_form_ready(page, entry) is False + + +@pytest.mark.parametrize( + ("route", "label"), + ( + ("on-hand-details-query", "On Hand Details"), + ("inbound-details-query", "Inbound Details"), + ("outbound-details-query", "Outbound Details"), + ), +) +def test_navigate_targets_tile_by_entry_route(route, label, monkeypatch): + """首页卡片/菜单选择器必须由 entry 路由推导,禁止硬编码 On Hand Details。""" + module = _load_navigation() + # [构造] 门户对授权用户渲染目标报表卡片:当前路由/标签的选择器可见 + page = _FakePage( + url="https://wms-portal.craneww.com/#/", + visible_tokens=(route, label, "Queries"), + ) + entry = f"https://wms-portal.craneww.com/#/{route}" + + monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url_arg: False) + monkeypatch.setattr(module, "_wait_for_report_navigation", lambda *args, **kwargs: True) + + mode = module.navigate_to_crane_report( + page, + entry, + env=lambda name, default="": default, + browser_timeout_ms=5_000, + ) + + assert mode == "dashboard_tile" + joined = "\n".join(page.locator_selectors) + assert label in joined + # [断言意图] 出站/入站导航不得再查询 On Hand Details 选择器(2026-10-20 死循环根因之一); + # 路由推导由 test_direct_goto_last_resort(evaluate 参数)单独覆盖 + for other in {"On Hand Details", "Inbound Details", "Outbound Details"} - {label}: + assert other not in joined + + +def test_navbar_fallback_uses_entry_route_label(monkeypatch): + """首页卡片不可见时,经 Queries 菜单点击的路由项也须由 entry 推导。""" + module = _load_navigation() + # [构造] 卡片全部不可见(token 只含 navbar),仅 Queries 下拉项可见; + # 首页等待用短超时避免 shell 未就绪时白等 5s + page = _FakePage( + url="https://wms-portal.craneww.com/#/", + visible_tokens=("navbar",), + visible_role_names=("Queries",), + ) + entry = "https://wms-portal.craneww.com/#/outbound-details-query" + + monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url_arg: False) + monkeypatch.setattr(module, "_wait_for_report_navigation", lambda *args, **kwargs: True) + + mode = module.navigate_to_crane_report( + page, + entry, + env=lambda name, default="": default, + browser_timeout_ms=1_000, + ) + + assert mode == "navbar_menu" + joined = "\n".join(page.locator_selectors) + # [断言意图] 菜单回退路径同样按 entry 推导标签,禁止再查询 On Hand Details 选择器 + assert '.navbar-dropdown a.navbar-item:has-text("Outbound Details")' in joined + assert "On Hand Details" not in joined diff --git a/backend/tests/test_crane_report_export.py b/backend/tests/test_crane_report_export.py index 85e29f22..db453c57 100644 --- a/backend/tests/test_crane_report_export.py +++ b/backend/tests/test_crane_report_export.py @@ -599,6 +599,29 @@ def test_wait_and_click_scheduled_download_skips_fallback_on_click_failure(tmp_p assert fallback_called["value"] is False +def test_refresh_scheduled_reports_list_never_reloads_page(monkeypatch): + """列表 goto 刷新失败时就地重赋 hash;登录态下禁止 page.reload(Crane 门户刷新即登出)。""" + module = _load_export() + page = MagicMock() + page.url = "https://wms-portal.craneww.com/#/scheduled-reports" + page.goto.side_effect = RuntimeError("net::ERR_ABORTED") + + monkeypatch.setattr(module, "_is_crane_login_blocking", lambda *_a, **_k: False) + monkeypatch.setattr(module, "_scheduled_reports_table_visible", lambda *_a, **_k: True) + monkeypatch.setattr(module, "_wait_for_scheduled_reports_list_ready", lambda *_a, **_k: True) + + module._refresh_scheduled_reports_list( + page, + env=lambda name, default="": default, + browser_timeout_ms=5_000, + entry_url="https://wms-portal.craneww.com/#/outbound-details-query", + ) + + # [断言意图] goto 失败的兜底是就地 hash 重赋;reload 一次都不允许发生 + page.reload.assert_not_called() + assert page.evaluate.called + + def test_row_matches_scheduled_report_normalizes_name_form(monkeypatch): """行名 InboundDetails.xlsx 与期望名 Inbound Details 应规范化后相等(收料轮询 not found 根因)。""" module = _load_export() diff --git a/backend/tests/test_crane_session.py b/backend/tests/test_crane_session.py index 73c226a8..76e4c48e 100644 --- a/backend/tests/test_crane_session.py +++ b/backend/tests/test_crane_session.py @@ -144,7 +144,7 @@ def test_find_crane_sign_in_button_waits_for_enabled_state(monkeypatch): def test_ensure_crane_session_skips_login_when_session_active(monkeypatch): """batch 内 session 有效时不应重复 goto + login。""" - worker_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "inventory" / "inventory_rpa_worker.py" + worker_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "onhand" / "onhand_rpa_worker.py" spec = importlib.util.spec_from_file_location("freight_rpa_worker_crane_test", worker_path) assert spec and spec.loader worker = importlib.util.module_from_spec(spec) diff --git a/backend/tests/test_customer_resolution_rebind.py b/backend/tests/test_customer_resolution_rebind.py index d435bf3c..61732394 100644 --- a/backend/tests/test_customer_resolution_rebind.py +++ b/backend/tests/test_customer_resolution_rebind.py @@ -22,7 +22,7 @@ from app.models import ( ShippingCustomer, ShippingCustomerShadowResolution, ShippingExportArtifact, - ShippingInventoryParsingProfile, + FreightRpaParsingProfile, ShippingNotice, ShippingOrderCandidate, ShippingOrderExtraction, @@ -154,7 +154,7 @@ def _attach_ready_export_artifact(notice: ShippingNotice) -> None: from app.models import ShippingOrderSchemaVersion, ShippingOrderExtraction template = _template_row() - profile = ShippingInventoryParsingProfile( + profile = FreightRpaParsingProfile( profile_code='REBIND_PROFILE', display_name='Rebind profile', version=1, status='published', file_format='xlsx', definition_json={}, ) diff --git a/backend/tests/test_dsv_report_parameters.py b/backend/tests/test_dsv_report_parameters.py index 9f31bc09..4dd0ea77 100644 --- a/backend/tests/test_dsv_report_parameters.py +++ b/backend/tests/test_dsv_report_parameters.py @@ -217,6 +217,26 @@ def test_resolve_parameter_controls_receipt_detail_awsrtm_warehouse_multi_value( assert module.resolve_parameter_controls("Receipt Detail", "Warehouse")["control"] == "select" +def test_resolve_parameter_controls_shipment_order_detail_owner_and_warehouse(): + """出站 Shipment Order Detail 的 Owner/Warehouse 应按实机 DOM 使用 multi_value,而不是库存默认 select。""" + module = _load_module() + owner = module.resolve_parameter_controls("Shipment Order Detail", "Owner") + warehouse = module.resolve_parameter_controls("Shipment Order Detail", "Warehouse") + # 关键断言:2026-10-19 AWS/Bison/AWSBI 实机——Owner ctl15、Warehouse ctl31,均为 txtValue 下拉。 + assert owner == { + "control": "multi_value", + "text": "#ReportViewerMain_ctl08_ctl15_txtValue", + "toggle": "#ReportViewerMain_ctl08_ctl15_ctl01", + "dropdown": "#ReportViewerMain_ctl08_ctl15_divDropDown", + } + assert warehouse == { + "control": "multi_value", + "text": "#ReportViewerMain_ctl08_ctl31_txtValue", + "toggle": "#ReportViewerMain_ctl08_ctl31_ctl01", + "dropdown": "#ReportViewerMain_ctl08_ctl31_divDropDown", + } + + def test_resolve_parameter_controls_unknown_report_empty(): """未登记报表名应返回空配置,由调用方回退参数名默认值(保持旧行为)。""" module = _load_module() @@ -326,10 +346,12 @@ def test_fill_dsv_filter_if_needed_jda_report_uses_template_multi_value(): report_name="On Hand Inventory by Location", ) - assert payloads, "应进入多选框下拉填充路径而不是无痕失败" + # payloads 会混入结构性解析传入的 label 字符串("Warehouse"),只断言 dict 载荷。 + dict_payloads = [p for p in payloads if isinstance(p, dict)] + assert dict_payloads, "应进入多选框下拉填充路径而不是无痕失败" assert any( payload.get("dropdownSelector") == "#ReportViewerMain_ctl08_ctl17_divDropDown" - for payload in payloads + for payload in dict_payloads ), f"应命中 JDA ctl17 multi_value dropdown,实际 payloads={payloads!r}" @@ -431,10 +453,12 @@ def test_fill_dsv_filter_if_needed_receipt_awsrtm_uses_ctl29_multi_value(): program_label="AWSRTM", ) - assert payloads, "应进入 AWSRTM multi_value 填充路径" + # payloads 会混入结构性解析传入的 label 字符串,只断言 dict 载荷。 + dict_payloads = [p for p in payloads if isinstance(p, dict)] + assert dict_payloads, "应进入 AWSRTM multi_value 填充路径" assert any( payload.get("dropdownSelector") == "#ReportViewerMain_ctl08_ctl29_divDropDown" - for payload in payloads + for payload in dict_payloads ), f"应命中 ctl29 multi_value dropdown,实际 payloads={payloads!r}" @@ -471,14 +495,20 @@ class _RecordingPage: _STRUCTURAL_CONTROLS = { + "control": "multi_value", "text": "#ReportViewerMain_ctl08_ctl15_txtValue", "toggle": "#ReportViewerMain_ctl08_ctl15_ctl01", "dropdown": "#ReportViewerMain_ctl08_ctl15_divDropDown", } +_STRUCTURAL_SELECT = { + "control": "select", + "selector": "#ReportViewerMain_ctl08_ctl19_ddValue", +} + def test_structural_resolver_hit_returns_controls_and_trims_label(): - """命中 frame 返回三件套;label 先 trim 再传入页面脚本。""" + """命中 frame 返回 multi_value 三件套(含 control);label 先 trim 再传入页面脚本。""" module = _load_module() early = _RecordingFrame(result=None) hit = _RecordingFrame(result=dict(_STRUCTURAL_CONTROLS)) @@ -490,6 +520,22 @@ def test_structural_resolver_hit_returns_controls_and_trims_label(): assert hit.calls == ["Owner"] +def test_structural_resolver_select_via_label_for_returns_ddvalue(): + """Cincinnati CVG611 形态:label[for]=ctl19_ddValue 时返回 select,禁止再当 multi_value。 + + [断言意图] 2026-10-20 事故回归——Warehouse 是原生 select,不得落到 ctl17_txtValue + (已漂移为 Project ID)文本兜底。 + """ + module = _load_module() + hit = _RecordingFrame(result=dict(_STRUCTURAL_SELECT)) + page = _RecordingPage([hit]) + + got = module.resolve_parameter_controls_structural(page, "Warehouse") + + assert got == _STRUCTURAL_SELECT + assert hit.calls == ["Warehouse"] + + def test_structural_resolver_all_frames_miss_or_error_returns_none(): """全部 frame 未命中或探测异常(跨域/销毁帧):返回 None 交调用方回退。""" module = _load_module() @@ -596,6 +642,98 @@ def test_fill_multi_select_structural_preferred_registry_is_fallback(monkeypatch assert probed.calls == ["Warehouse"] +def test_fill_warehouse_uses_structural_select_not_stale_txtvalue(monkeypatch, capsys): + """Warehouse 结构性命中 select 时走 ddValue,禁止 JDA 模板 ctl17_txtValue 文本兜底。 + + [断言意图] 复现 2026-10-20 Cincinnati:模板仍写 multi_value@ctl17,但页面 Warehouse + 是 ctl19_ddValue;不得把 BYAWSCV611 写进漂移后的 Project ID。 + """ + module = _load_module() + page = _RecordingPage([_RecordingFrame(result=dict(_STRUCTURAL_SELECT))]) + selected: dict[str, str] = {} + + class _FakeText: + first = None + + def __init__(self) -> None: + self.first = self + + def is_visible(self, timeout: int | None = None) -> bool: + return False + + page.get_by_text = lambda text, exact=False: _FakeText() # type: ignore[attr-defined] + + def _fake_select(page_obj, label, value, selector, *, timeout_ms): + selected["selector"] = selector + selected["value"] = value + return True + + def _fake_multi(*_a, **_k): + raise AssertionError("select 形态不得走 multi_value") + + monkeypatch.setattr(module, "_fill_select_parameter", _fake_select) + monkeypatch.setattr(module, "_fill_multi_value_parameter", _fake_multi) + + ok = module.fill_dsv_filter_if_needed( + page, + "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", + "Warehouse", + "BYAWSCV611", + env=lambda name, default="": default, + browser_timeout_ms=lambda: 3_000, + report_name="On Hand Inventory By Location", + program_label="CVG611", + ) + + assert ok is True + assert selected == { + "selector": "#ReportViewerMain_ctl08_ctl19_ddValue", + "value": "BYAWSCV611", + } + captured = capsys.readouterr() + assert "ctl17_txtValue" not in captured.out + captured.err + + +def test_fill_warehouse_refuses_stale_txtvalue_when_structural_miss(monkeypatch, capsys): + """结构性未命中且模板 multi_value 失败时:Warehouse 拒绝 txtValue 文本兜底并返回 False。""" + module = _load_module() + page = _RecordingPage([_RecordingFrame(result=None)]) + + class _FakeText: + first = None + + def __init__(self) -> None: + self.first = self + + def is_visible(self, timeout: int | None = None) -> bool: + return False + + page.get_by_text = lambda text, exact=False: _FakeText() # type: ignore[attr-defined] + monkeypatch.setattr(module, "_fill_multi_value_parameter", lambda *_a, **_k: False) + monkeypatch.setattr(module, "_probe_report_parameter_controls", lambda *_a, **_k: {"controls": []}) + filled_via_script: list[str] = [] + monkeypatch.setattr( + module, + "_fill_input_via_script", + lambda root, selector, text: filled_via_script.append(selector) or True, + ) + + ok = module.fill_dsv_filter_if_needed( + page, + "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", + "Warehouse", + "BYAWSCV611", + env=lambda name, default="": default, + browser_timeout_ms=lambda: 3_000, + report_name="On Hand Inventory By Location", + ) + + assert ok is False + assert filled_via_script == [] + captured = capsys.readouterr() + assert "refusing stale txtValue fallback" in captured.err + + def test_multi_value_already_set_set_equality_not_substring(): """2026-10-08 Owner@AWSRTM 事故根因回归:SSRS 多选框默认全选,txtValue 恒为全量 CSV, 目标值必为该 CSV 的子串——必须用集合相等判定,子串包含会恒误判"已设置"并跳过下拉勾选。""" diff --git a/backend/tests/test_freight_receipt_rpa_access.py b/backend/tests/test_freight_receipt_rpa_access.py index 4afb155b..bc434c3e 100644 --- a/backend/tests/test_freight_receipt_rpa_access.py +++ b/backend/tests/test_freight_receipt_rpa_access.py @@ -1,4 +1,10 @@ -"""收料文件下载和人工补偿的权限/审计契约测试。""" +""" +backend/tests/test_freight_receipt_rpa_access.py + +用途:入站 RPA 管理员补偿 API 契约(失败单元列表/重试);工作台收料文件与 resend 已拆除。 +依赖:Flask test client、freight_rpa 入站模型与 schedule runs 路由。 +逻辑:仅覆盖 /api/admin/inbound-rpa-units 与 retry;审计 surface 为 admin_inbound_rpa_units。 +""" from __future__ import annotations @@ -7,179 +13,114 @@ def _headers(username: str, role: str) -> dict[str, str]: return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'} -def test_receipt_recipient_can_download_but_other_user_is_rejected(app, client, monkeypatch): - """排程接收人可下载原样文件;非接收人不可通过猜测 ID 越权。""" - from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User - - app.config['AUTH_JWT_REQUIRED'] = False - with app.app_context(): - recipient = User(username='receipt-download-user', email='receipt-download@example.com', role='user', status='active') - other = User(username='receipt-other-user', email='receipt-other@example.com', role='user', status='active') - db.session.add_all([recipient, other]); db.session.flush() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - task = ScheduleTask(schedule_no='SCH-RECEIPT-DL', name='Receipt download', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id]) - db.session.add(task); db.session.flush() - run = ScheduleRun(run_no='RUN-RECEIPT-DL', schedule_task_id=task.id, status='success') - db.session.add(run); db.session.flush() - unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-download', status='success', config_snapshot_json={}) - db.session.add(unit); db.session.flush() - report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/download.xlsx', original_filename='receipt.xlsx', file_size=4, sha256='b' * 64) - db.session.add(report_file); db.session.commit() - file_id = report_file.id - monkeypatch.setattr('app.services.shipping_notice.receipt_report_access.file_asset_storage.get_bytes', lambda _key: b'xlsx') - - allowed = client.get(f'/api/workspace/receipt-report-files/{file_id}/download', headers=_headers('receipt-download-user', 'user')) - denied = client.get(f'/api/workspace/receipt-report-files/{file_id}/download', headers=_headers('receipt-other-user', 'user')) - assert allowed.status_code == 200 - assert allowed.data == b'xlsx' - assert denied.status_code == 403 - - -def test_receipt_recipient_lists_only_own_archived_files(app, client): - """接收人文件列表仅返回本人排程归档,并且不得泄露对象存储定位。""" - from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User - - app.config['AUTH_JWT_REQUIRED'] = False - with app.app_context(): - recipient = User(username='receipt-list-user', email='receipt-list@example.com', role='user', status='active') - other = User(username='receipt-list-other', email='receipt-list-other@example.com', role='user', status='active') - db.session.add_all([recipient, other]); db.session.flush() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - own_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIST-OWN', name='Own receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id]) - other_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIST-OTHER', name='Other receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=other.id, cron_expr='0 8 * * *', notify_user_ids_json=[other.id]) - db.session.add_all([own_task, other_task]); db.session.flush() - own_run = ScheduleRun(run_no='RUN-RECEIPT-LIST-OWN', schedule_task_id=own_task.id, status='success') - other_run = ScheduleRun(run_no='RUN-RECEIPT-LIST-OTHER', schedule_task_id=other_task.id, status='success') - db.session.add_all([own_run, other_run]); db.session.flush() - own_unit = ShippingReceiptRpaUnitRun(schedule_run_id=own_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OWN', callback_id='receipt-list-own', status='success', config_snapshot_json={}) - other_unit = ShippingReceiptRpaUnitRun(schedule_run_id=other_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OTHER', callback_id='receipt-list-other', status='success', config_snapshot_json={}) - db.session.add_all([own_unit, other_unit]); db.session.flush() - own_file = ShippingReceiptReportFile(unit_run_id=own_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/list-own.xlsx', original_filename='own.xlsx', file_size=4, sha256='d' * 64) - db.session.add_all([own_file, ShippingReceiptReportFile(unit_run_id=other_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/list-other.xlsx', original_filename='other.xlsx', file_size=4, sha256='e' * 64)]) - db.session.commit() - own_file_id = own_file.id - - response = client.get('/api/workspace/receipt-report-files', headers=_headers('receipt-list-user', 'user')) - - assert response.status_code == 200 - items = response.get_json()['data']['items'] - # 关键断言:列表投影不能泄露非接收人的文件或对象存储定位。 - assert [item['id'] for item in items] == [own_file_id] - assert 'storage_key' not in items[0] - assert items[0]['download_url'].endswith(f'/receipt-report-files/{own_file_id}/download') - - -def test_receipt_file_list_filters_before_applying_limit(app): - """其他人的新文件再多,也不能挤掉接收人较早的可见归档。""" - from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User - from app.services.shipping_notice.receipt_report_access import list_receipt_report_files - - with app.app_context(): - recipient = User(username='receipt-limit-user', email='receipt-limit@example.com', role='user', status='active') - other = User(username='receipt-limit-other', email='receipt-limit-other@example.com', role='user', status='active') - db.session.add_all([recipient, other]); db.session.flush() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - own_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIMIT-OWN', name='Own receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id]) - other_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIMIT-OTHER', name='Other receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=other.id, cron_expr='0 8 * * *', notify_user_ids_json=[other.id]) - db.session.add_all([own_task, other_task]); db.session.flush() - own_run = ScheduleRun(run_no='RUN-RECEIPT-LIMIT-OWN', schedule_task_id=own_task.id, status='success') - other_run = ScheduleRun(run_no='RUN-RECEIPT-LIMIT-OTHER', schedule_task_id=other_task.id, status='success') - db.session.add_all([own_run, other_run]); db.session.flush() - own_unit = ShippingReceiptRpaUnitRun(schedule_run_id=own_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OWN', callback_id='receipt-limit-own', status='success', config_snapshot_json={}) - other_unit = ShippingReceiptRpaUnitRun(schedule_run_id=other_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OTHER', callback_id='receipt-limit-other', status='success', config_snapshot_json={}) - db.session.add_all([own_unit, other_unit]); db.session.flush() - own_file = ShippingReceiptReportFile(unit_run_id=own_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/limit-own.xlsx', original_filename='own.xlsx', file_size=4, sha256='f' * 64) - db.session.add(own_file); db.session.flush() - for index in range(3): - db.session.add(ShippingReceiptReportFile(unit_run_id=other_unit.id, storage_provider='minio', storage_bucket='test', storage_key=f'receipt/limit-other-{index}.xlsx', original_filename=f'other-{index}.xlsx', file_size=4, sha256=f'{index + 1}' * 64)) - db.session.commit() - - items = list_receipt_report_files(recipient, limit=1) - - # 关键断言:授权过滤发生在截断之前,避免被其他排程的归档饿死。 - assert [item['id'] for item in items] == [own_file.id] - - -def test_admin_can_resend_without_reexporting(app, client, monkeypatch): - """管理员重发只调用文件投递,不创建 RPA 单元或 trigger。""" - from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User - - app.config['AUTH_JWT_REQUIRED'] = False - with app.app_context(): - admin = User(username='receipt-resend-admin', email='receipt-resend-admin@example.com', role='admin', status='active') - db.session.add(admin); db.session.flush() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - task = ScheduleTask(schedule_no='SCH-RECEIPT-RESEND', name='Receipt resend', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=admin.id, cron_expr='0 8 * * *', notify_user_ids_json=[admin.id]) - db.session.add(task); db.session.flush() - run = ScheduleRun(run_no='RUN-RECEIPT-RESEND', schedule_task_id=task.id, status='success') - db.session.add(run); db.session.flush() - unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-resend', status='success', config_snapshot_json={}) - db.session.add(unit); db.session.flush() - report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/resend.xlsx', original_filename='receipt.xlsx', file_size=4, sha256='c' * 64) - db.session.add(report_file); db.session.commit() - file_id = report_file.id - calls = [] - monkeypatch.setattr('app.api.schedule.runs.deliver_receipt_file', lambda file_id, force=False: calls.append((file_id, force)) or {'success_count': 1, 'failed_count': 0}) - - response = client.post(f'/api/admin/receipt-report-files/{file_id}/resend', headers=_headers('receipt-resend-admin', 'admin')) - assert response.status_code == 200 - assert calls == [(file_id, True)] - - def test_admin_retry_creates_a_new_receipt_unit_linked_to_failed_unit(app, client, monkeypatch): """失败单元重试保留旧失败事实,创建新的 callback 单元和独立 trigger。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun, User + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun, User app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): admin = User(username='receipt-retry-admin', email='receipt-retry-admin@example.com', role='admin', status='active') db.session.add(admin); db.session.flush() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - task = ScheduleTask(schedule_no='SCH-RECEIPT-RETRY', name='Receipt retry', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=admin.id, cron_expr='0 8 * * *') + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + task = ScheduleTask(schedule_no='SCH-RECEIPT-RETRY', name='Receipt retry', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=admin.id, cron_expr='0 8 * * *') db.session.add(task); db.session.flush() run = ScheduleRun(run_no='RUN-RECEIPT-RETRY', schedule_task_id=task.id, status='failed') db.session.add(run); db.session.flush() - failed = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-failed', status='failed', config_snapshot_json={'report_path_json': {}, 'query_parameters_json': []}) + failed = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-failed', status='failed', config_snapshot_json={'report_path_json': {}, 'query_parameters_json': []}) db.session.add(failed); db.session.commit() failed_id = failed.id captured = [] - monkeypatch.setattr('app.api.schedule.runs.write_receipt_export_batch_trigger', lambda run_no, units, payload: captured.append((run_no, units, payload)) or 'retry-trigger.json') + monkeypatch.setattr('app.api.schedule.runs.write_inbound_export_batch_trigger', lambda run_no, units, payload: captured.append((run_no, units, payload)) or 'retry-trigger.json') - response = client.post(f'/api/admin/receipt-rpa-units/{failed_id}/retry', json={'reason': 'portal recovered'}, headers=_headers('receipt-retry-admin', 'admin')) + response = client.post(f'/api/admin/inbound-rpa-units/{failed_id}/retry', json={'reason': 'portal recovered'}, headers=_headers('receipt-retry-admin', 'admin')) assert response.status_code == 200 with app.app_context(): - retry = ShippingReceiptRpaUnitRun.query.filter_by(retry_of_id=failed_id).one() + retry = FreightRpaInboundUnitRun.query.filter_by(retry_of_id=failed_id).one() assert retry.status == 'awaiting_rpa' assert retry.callback_id != 'receipt-failed' + assert retry.callback_id.startswith('inbound:') assert captured and captured[0][1][0]['callback_id'] == retry.callback_id def test_admin_lists_failed_receipt_units_for_manual_compensation(app, client): """管理员可见失败单元用于人工补偿;该接口会记录管理员查看审计。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, ShippingInventorySource, ShippingReceiptRpaUnitRun, User + from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, FreightRpaSource, FreightRpaInboundUnitRun, User app.config['AUTH_JWT_REQUIRED'] = False with app.app_context(): admin = User(username='receipt-units-admin', email='receipt-units-admin@example.com', role='admin', status='active') db.session.add(admin); db.session.flush() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - task = ScheduleTask(schedule_no='SCH-RECEIPT-UNITS', name='Receipt units', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=admin.id, cron_expr='0 8 * * *') + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + task = ScheduleTask(schedule_no='SCH-RECEIPT-UNITS', name='Receipt units', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=admin.id, cron_expr='0 8 * * *') db.session.add(task); db.session.flush() run = ScheduleRun(run_no='RUN-RECEIPT-UNITS', schedule_task_id=task.id, status='failed') db.session.add(run); db.session.flush() - unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-admin-list', status='failed', error_code='RPA.RECEIPT_EXPORT_FAILED', config_snapshot_json={}) + unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-admin-list', status='failed', error_code='RPA.INBOUND_EXPORT_FAILED', config_snapshot_json={}) db.session.add(unit); db.session.commit() unit_id = unit.id - response = client.get('/api/admin/receipt-rpa-units?status=failed', headers=_headers('receipt-units-admin', 'admin')) + response = client.get('/api/admin/inbound-rpa-units?status=failed', headers=_headers('receipt-units-admin', 'admin')) assert response.status_code == 200 assert [item['id'] for item in response.get_json()['data']['items']] == [unit_id] with app.app_context(): - assert ShippingAuditEvent.query.filter_by(event_type='shipping_receipt_rpa_units_listed').count() == 1 + listed = ShippingAuditEvent.query.filter_by(event_type='shipping_inbound_rpa_units_listed').one() + assert listed.metadata_json.get('surface') == 'admin_inbound_rpa_units' + + +def test_admin_retry_inbound_unit_messages_use_inbound_not_receipt(app, client): + """入站 retry 面向用户的英文错误须用 Inbound,不得再写 Receipt。""" + from app import db + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun, User + from tests.conftest import parse_api_error + + app.config['AUTH_JWT_REQUIRED'] = False + with app.app_context(): + admin = User( + username='inbound-retry-msg-admin', + email='inbound-retry-msg-admin@example.com', + role='admin', + status='active', + ) + db.session.add(admin) + db.session.flush() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + task = ScheduleTask( + schedule_no='SCH-INBOUND-RETRY-MSG', + name='Inbound retry messages', + schedule_type='platform_job', + platform_api_path='freight-rpa-inbound', + owner_user_id=admin.id, + cron_expr='0 8 * * *', + ) + db.session.add(task) + db.session.flush() + run = ScheduleRun(run_no='RUN-INBOUND-RETRY-MSG', schedule_task_id=task.id, status='failed') + db.session.add(run) + db.session.flush() + success = FreightRpaInboundUnitRun( + schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, + connector_type='dbs', warehouse_id='A', callback_id='inbound-success-no-retry', + status='success', config_snapshot_json={}, + ) + db.session.add(success) + db.session.commit() + success_id = success.id + + missing = client.post( + '/api/admin/inbound-rpa-units/999999/retry', + json={'reason': 'should 404'}, + headers=_headers('inbound-retry-msg-admin', 'admin'), + ) + assert missing.status_code == 404 + assert parse_api_error(missing.get_json())['message'] == 'Inbound RPA unit not found' + + blocked = client.post( + f'/api/admin/inbound-rpa-units/{success_id}/retry', + json={'reason': 'should conflict'}, + headers=_headers('inbound-retry-msg-admin', 'admin'), + ) + assert blocked.status_code == 409 + assert parse_api_error(blocked.get_json())['message'] == 'Only failed inbound RPA units can be retried' diff --git a/backend/tests/test_freight_receipt_rpa_callback.py b/backend/tests/test_freight_receipt_rpa_callback.py index b237cdbe..5b9b7edf 100644 --- a/backend/tests/test_freight_receipt_rpa_callback.py +++ b/backend/tests/test_freight_receipt_rpa_callback.py @@ -7,49 +7,62 @@ import hashlib import pytest +def _register_inbound_report_handler(): + """注册生产用 inbound 事实处理函数(调拨侧 handle_inbound_report)。 + + 核心逻辑:归档入口终态 commit 后经 dispatch_report_fact 投递;测试在调用 + ingest_inbound_callback 前显式注册,避免依赖 create_app 全局状态顺序。 + """ + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report + + register_report_handler('inbound', handle_inbound_report) + return handle_inbound_report + + 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, + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun + from app.services.schedule.freight_rpa_inbound_finalize import ( + mark_inbound_unit_processing, + report_inbound_batch_progress, ) with app.app_context(): - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask( schedule_no='SCH-RECEIPT-LIVE', name='Receipt live progress', schedule_type='platform_job', - platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *', + platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *', ) db.session.add(task) db.session.flush() run = ScheduleRun( run_no='RUN-RECEIPT-LIVE', schedule_task_id=task.id, status='running', total_count=2, success_count=0, failed_count=0, skipped_count=0, - response_summary_json={'awaiting_receipt_rpa': True}, + response_summary_json={'awaiting_inbound_rpa': True}, ) db.session.add(run) db.session.flush() - unit = ShippingReceiptRpaUnitRun( - schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, + unit = FreightRpaInboundUnitRun( + schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-live-progress', status='awaiting_rpa', config_snapshot_json={}, ) db.session.add(unit) db.session.commit() - marked = mark_receipt_unit_processing({ - 'schema_version': 'shipping_receipt_rpa.v1', + marked = mark_inbound_unit_processing({ + 'schema_version': 'freight_rpa.inbound.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' + assert db.session.get(FreightRpaInboundUnitRun, unit.id).status == 'processing' - progressed = report_receipt_batch_progress({ - 'schema_version': 'shipping_receipt_rpa.v1', + progressed = report_inbound_batch_progress({ + 'schema_version': 'freight_rpa.inbound.v1', 'schedule_run_id': run.id, 'batch_run_no': run.run_no, 'success_count': 1, @@ -63,51 +76,133 @@ def test_receipt_unit_processing_and_batch_progress(app): assert refreshed.response_summary_json['progress']['success_count'] == 1 -def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch): - """success 回调在 finalize 前须回写 ScheduleRun 进度计数(对齐 empty/failed)。""" +def test_inbound_batch_ready_sink_finalizes_schedule_even_if_fact_handler_raises( + app, monkeypatch, +): + """文件归档单元终态后,事实/证据处理失败仍须收口排程(文件返回= RPA 结束)。 + + [断言意图] batch-ready sink 在 finally 中 finalize;不得依赖 handle_inbound_report 成功。 + """ from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun - from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun + from app.services.freight_rpa.reports.dispatch import register_report_handler + from app.services.in_transit_transfer.rpa_sinks import _inbound_batch_ready_sink with app.app_context(): - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask( - schedule_no='SCH-RECEIPT-PROG', name='Receipt progress', schedule_type='platform_job', - platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *', + schedule_no='SCH-INBOUND-FILE-FINAL', + name='Inbound file finalize', + schedule_type='platform_job', + platform_api_path='freight-rpa-inbound', + owner_user_id=1, + cron_expr='0 8 * * *', ) db.session.add(task) db.session.flush() run = ScheduleRun( - run_no='RUN-RECEIPT-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}, + run_no='RUN-INBOUND-FILE-FINAL', + schedule_task_id=task.id, + status='running', + total_count=1, + success_count=0, + failed_count=0, + skipped_count=0, + response_summary_json={'awaiting_inbound_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={}, + unit = FreightRpaInboundUnitRun( + schedule_run_id=run.id, + source_id=source.id, + source_code=source.source_code, + connector_type='dbs', + warehouse_id='AWSDU', + callback_id='inbound-file-final-cb', + 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', + 'app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file', lambda _path: b'receipt-bytes', ) monkeypatch.setattr( - 'app.services.shipping_notice.receipt_report_storage.file_asset_storage.upload_bytes', + 'app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes', lambda **_kwargs: None, ) + + def _boom(_fact): + raise RuntimeError('evidence sync exploded') + + register_report_handler('inbound', _boom) payload = { - 'schema_version': 'shipping_receipt_rpa.v1', + 'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'success', 'file_path': 'Z:/receipt.xlsx', 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest(), } - ingest_receipt_callback(payload) + + with pytest.raises(RuntimeError, match='evidence sync exploded'): + _inbound_batch_ready_sink(**payload) + + db.session.expire_all() + refreshed = db.session.get(ScheduleRun, run.id) + assert refreshed.status == 'success' + assert (refreshed.response_summary_json or {}).get('awaiting_inbound_rpa') is False + assert db.session.get(FreightRpaInboundUnitRun, unit.id).status == 'success' + + +def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch): + """success 回调在 finalize 前须回写 ScheduleRun 进度计数(对齐 empty/failed)。""" + from app import db + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback + + with app.app_context(): + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + task = ScheduleTask( + schedule_no='SCH-RECEIPT-PROG', name='Receipt progress', schedule_type='platform_job', + platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *', + ) + 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_inbound_rpa': True}, + ) + db.session.add(run) + db.session.flush() + unit = FreightRpaInboundUnitRun( + schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, + connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-progress', + status='awaiting_rpa', config_snapshot_json={}, + ) + db.session.add(unit) + db.session.commit() + monkeypatch.setattr( + 'app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file', + lambda _path: b'receipt-bytes', + ) + monkeypatch.setattr( + 'app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes', + lambda **_kwargs: None, + ) + _register_inbound_report_handler() + payload = { + 'schema_version': 'freight_rpa.inbound.v1', + 'callback_id': unit.callback_id, + 'status': 'success', + 'file_path': 'Z:/receipt.xlsx', + 'original_filename': 'receipt.xlsx', + 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest(), + } + ingest_inbound_callback(payload) db.session.expire_all() refreshed = db.session.get(ScheduleRun, run.id) # [断言意图] success 后进度至少抬升 success_count;终态可能已 finalize 清 awaiting。 @@ -117,49 +212,51 @@ def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch): def test_receipt_callback_archives_once_without_inventory_file(app, monkeypatch): """同一 callback 重放只归档一条收料文件,绝不创建库存快照。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventoryFile, ShippingInventorySource, ShippingReceiptRpaUnitRun - from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback + from app.models import ScheduleRun, ScheduleTask, FreightRpaOnhandReportFile, FreightRpaSource, FreightRpaInboundUnitRun + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback with app.app_context(): - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - task = ScheduleTask(schedule_no='SCH-RECEIPT-CB', name='Receipt callback', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *') + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + task = ScheduleTask(schedule_no='SCH-RECEIPT-CB', name='Receipt callback', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *') db.session.add(task); db.session.flush() run = ScheduleRun(run_no='RUN-RECEIPT-CB', schedule_task_id=task.id, status='running') db.session.add(run); db.session.flush() - unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-archive', status='awaiting_rpa', config_snapshot_json={}) + unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-archive', status='awaiting_rpa', config_snapshot_json={}) db.session.add(unit); db.session.commit() - monkeypatch.setattr('app.services.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()} - first = ingest_receipt_callback(payload) - second = ingest_receipt_callback(payload) + monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file', lambda _path: b'receipt-bytes') + monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes', lambda **_kwargs: None) + _register_inbound_report_handler() + payload = {'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'success', 'file_path': 'Z:/receipt.xlsx', 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest()} + first = ingest_inbound_callback(payload) + second = ingest_inbound_callback(payload) assert first['file_id'] == second['file_id'] - assert ShippingInventoryFile.query.count() == 0 + assert FreightRpaOnhandReportFile.query.count() == 0 def test_ingest_success_advances_transfer_waiting_job(app, monkeypatch): """收料回调 success 落归档后,必须推进调拨 waiting 来源任务(B3 接线)。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun, TransferSourceJob, TransferRun - from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun, TransferSourceJob, TransferRun + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback with app.app_context(): - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - task = ScheduleTask(schedule_no='SCH-RECEIPT-CB2', name='Receipt callback 2', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *') + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + task = ScheduleTask(schedule_no='SCH-RECEIPT-CB2', name='Receipt callback 2', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *') db.session.add(task); db.session.flush() run = ScheduleRun(run_no='RUN-RECEIPT-CB2', schedule_task_id=task.id, status='running') db.session.add(run); db.session.flush() - unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-bridge', status='awaiting_rpa', config_snapshot_json={}) + unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-bridge', status='awaiting_rpa', config_snapshot_json={}) db.session.add(unit) transfer_run = TransferRun(run_no='RUN-BRIDGE-E2E', business_date='2026-09-17', status='preparing_files', trigger_type='manual') db.session.add(transfer_run); db.session.flush() job = TransferSourceJob(run_id=transfer_run.id, source_code=source.source_code, status='waiting_rpa_callback') db.session.add(job); 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()} + monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file', lambda _path: b'receipt-bytes') + monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes', lambda **_kwargs: None) + _register_inbound_report_handler() + payload = {'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'success', 'file_path': 'Z:/receipt.xlsx', 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest()} - result = ingest_receipt_callback(payload) + result = ingest_inbound_callback(payload) # [断言意图] 桥接发生:收料归档后调拨任务状态推进 file_ready,file_no 为归档文件 id db.session.expire_all() advanced = db.session.get(TransferSourceJob, job.id) @@ -170,24 +267,25 @@ def test_ingest_success_advances_transfer_waiting_job(app, monkeypatch): def test_ingest_failed_advance_is_durable(app): """failed 回调推进调拨任务后必须已 commit——rollback 不得丢弃该推进(B3 持久性)。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun, TransferSourceJob, TransferRun - from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun, TransferSourceJob, TransferRun + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback with app.app_context(): - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - task = ScheduleTask(schedule_no='SCH-RECEIPT-CB3', name='Receipt callback 3', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *') + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + task = ScheduleTask(schedule_no='SCH-RECEIPT-CB3', name='Receipt callback 3', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *') db.session.add(task); db.session.flush() run = ScheduleRun(run_no='RUN-RECEIPT-CB3', schedule_task_id=task.id, status='running') db.session.add(run); db.session.flush() - unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-bridge-durable', status='awaiting_rpa', config_snapshot_json={}) + unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-bridge-durable', status='awaiting_rpa', config_snapshot_json={}) db.session.add(unit) transfer_run = TransferRun(run_no='RUN-BRIDGE-E2E-FAIL', business_date='2026-09-17', status='preparing_files', trigger_type='manual') db.session.add(transfer_run); db.session.flush() job = TransferSourceJob(run_id=transfer_run.id, source_code=source.source_code, status='waiting_rpa_callback') db.session.add(job); db.session.commit() - payload = {'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit.callback_id, 'status': 'failed', 'error_code': 'RPA_TEST_FAIL', 'error_message': 'boom'} + _register_inbound_report_handler() + payload = {'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'failed', 'error_code': 'RPA_TEST_FAIL', 'error_message': 'boom'} - result = ingest_receipt_callback(payload) + result = ingest_inbound_callback(payload) assert result['status'] == 'failed' # [断言意图] 推进必须已落库而非仅 flush:rollback 丢弃会话内未提交变更, # 只有真正 commit 过的推进才能在 expire_all 后被新查询读到。 @@ -201,36 +299,36 @@ def test_ingest_failed_advance_is_durable(app): def test_receipt_callback_rejects_file_outside_receipt_drop_root(app, tmp_path): """Callback cannot read arbitrary local xlsx files outside the receipt-only drop root.""" from app.core.errors import ValidationError - from app.services.shipping_notice.receipt_report_storage import _read_receipt_callback_file + from app.services.freight_rpa.inbound.report_archive import _read_inbound_callback_file with app.app_context(): allowed_root = tmp_path / 'receipt-drop' allowed_root.mkdir() - app.config['FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR'] = str(allowed_root) + app.config['FREIGHT_RPA_SHARED_INBOUND_DROP_DIR'] = str(allowed_root) outside = tmp_path / 'outside.xlsx' outside.write_bytes(b'not-a-real-xlsx') - with pytest.raises(ValidationError, match='receipt callback file'): - _read_receipt_callback_file(str(outside)) + with pytest.raises(ValidationError, match='inbound callback file'): + _read_inbound_callback_file(str(outside)) -def test_ingest_empty_persists_no_receipt_data(app): +def test_ingest_empty_persists_no_inbound_data(app): """ - empty 回调须落库 no_receipt_data(对齐库存 no_inventory_data)。 + empty 回调须落库 no_inbound_data(对齐库存 no_inventory_data)。 - [断言意图] 单元 status=empty 且 error_code/error_message 为 no_receipt_data,供管理端展示跳过原因。 + [断言意图] 单元 status=empty 且 error_code/error_message 为 no_inbound_data,供管理端展示跳过原因。 """ from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun - from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun + from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback with app.app_context(): - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask( schedule_no='SCH-RECEIPT-EMPTY', name='Receipt empty', schedule_type='platform_job', - platform_api_path='freight-receipt-rpa', + platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *', ) @@ -239,9 +337,9 @@ def test_ingest_empty_persists_no_receipt_data(app): run = ScheduleRun(run_no='RUN-RECEIPT-EMPTY', schedule_task_id=task.id, status='running') db.session.add(run) db.session.flush() - unit = ShippingReceiptRpaUnitRun( + unit = FreightRpaInboundUnitRun( schedule_run_id=run.id, - inventory_source_id=source.id, + source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', @@ -251,37 +349,40 @@ def test_ingest_empty_persists_no_receipt_data(app): ) db.session.add(unit) db.session.commit() + _register_inbound_report_handler() - result = ingest_receipt_callback({ - 'schema_version': 'shipping_receipt_rpa.v1', + result = ingest_inbound_callback({ + 'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'empty', - 'error_code': 'no_receipt_data', - 'error_message': 'no_receipt_data', + 'error_code': 'no_inbound_data', + 'error_message': 'no_inbound_data', }) assert result['status'] == 'empty' db.session.expire_all() - saved = db.session.get(ShippingReceiptRpaUnitRun, unit.id) + saved = db.session.get(FreightRpaInboundUnitRun, unit.id) assert saved is not None assert saved.status == 'empty' - assert saved.error_code == 'no_receipt_data' - assert saved.error_message == 'no_receipt_data' + assert saved.error_code == 'no_inbound_data' + assert saved.error_message == 'no_inbound_data' def test_receipt_progress_routes_are_registered(app): - """回归锁:receipt-unit-progress / receipt-batch-progress 必须注册在 Tool 蓝图上。 + """回归锁:inbound-unit-progress / inbound-batch-progress 必须注册在 freight-rpa 蓝图上。 2026-10-08 事故:重构分叉合并丢失两路由,Worker 上报全程 404、活动锚失效、 在飞批次被超时对账误杀——本用例保证路由缺失在任何部署前即红。 + (批次 R:路由自旧 shipping-notice rpa 回调前缀迁至 /api/freight-rpa/inbound-*, + 处理函数不变,本回归锁同步改指新 URL。) """ app.config['SHIPPING_NOTICE_TOOL_API_KEY'] = 'test-tool-key' client = app.test_client() headers = {'X-Integration-Key': 'test-tool-key'} for path, payload in ( - ('/api/shipping-notice/rpa/receipt-unit-progress', - {'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': 'no-such-callback'}), - ('/api/shipping-notice/rpa/receipt-batch-progress', - {'schema_version': 'shipping_receipt_rpa.v1', 'schedule_run_id': 999999999}), + ('/api/freight-rpa/inbound-unit-progress', + {'schema_version': 'freight_rpa.inbound.v1', 'callback_id': 'no-such-callback'}), + ('/api/freight-rpa/inbound-batch-progress', + {'schema_version': 'freight_rpa.inbound.v1', 'schedule_run_id': 999999999}), ): # [断言意图] 路由必须存在且鉴权通过(非 401/403/404);无匹配数据时服务层 # 返回 200 + updated=False(注册性探针,不依赖任何夹具数据)。 @@ -293,22 +394,22 @@ def test_receipt_progress_routes_are_registered(app): def test_read_receipt_callback_file_resolves_drop_root_filename(app, tmp_path): """跨机路径契约:Worker 只上报文件名(或历史 Windows 绝对路径),后端按自身 drop 根定位。""" from app.core.errors import ValidationError - from app.services.shipping_notice.receipt_report_storage import _read_receipt_callback_file + from app.services.freight_rpa.inbound.report_archive import _read_inbound_callback_file with app.app_context(): drop_root = tmp_path / 'receipt-drop' drop_root.mkdir() - app.config['FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR'] = str(drop_root) + app.config['FREIGHT_RPA_SHARED_INBOUND_DROP_DIR'] = str(drop_root) target = drop_root / 'receipt_RUN_X_SITE_NA_2026.xlsx' target.write_bytes(b'receipt-bytes') # [断言意图] 裸文件名(新 Worker 契约)与 Windows 本机绝对路径(历史载荷)都 # 必须解析到后端 drop 根内同一文件;根外文件依旧拒绝(任意本机文件读取护栏不变)。 - assert _read_receipt_callback_file('receipt_RUN_X_SITE_NA_2026.xlsx') == b'receipt-bytes' - assert _read_receipt_callback_file( + assert _read_inbound_callback_file('receipt_RUN_X_SITE_NA_2026.xlsx') == b'receipt-bytes' + assert _read_inbound_callback_file( r'C:\HxopsRpaTest\data\freight_rpa\receipt\drop\receipt_RUN_X_SITE_NA_2026.xlsx' ) == b'receipt-bytes' outside = tmp_path / 'outside.xlsx' outside.write_bytes(b'x') - with pytest.raises(ValidationError, match='receipt callback file'): - _read_receipt_callback_file(str(outside)) + with pytest.raises(ValidationError, match='inbound callback file'): + _read_inbound_callback_file(str(outside)) diff --git a/backend/tests/test_freight_receipt_rpa_notifications.py b/backend/tests/test_freight_receipt_rpa_notifications.py index db5b5f59..8e71712c 100644 --- a/backend/tests/test_freight_receipt_rpa_notifications.py +++ b/backend/tests/test_freight_receipt_rpa_notifications.py @@ -1,85 +1,29 @@ -"""收料文件企微投递和授权下载契约测试。""" +""" +backend/tests/test_freight_receipt_rpa_notifications.py + +用途:入站排程终态企微通知与 finalize 汇总 Excel 契约(统一排程出口)。 +依赖:freight_rpa_inbound_finalize、scheduler_service 企微门禁。 +逻辑:per-file deliver_inbound_file 已拆除;本文件不再覆盖单文件投递/resend。 +""" from __future__ import annotations -def test_receipt_file_delivery_is_idempotent_and_only_targets_schedule_recipients(app, monkeypatch): - """同一文件只向排程接收人发送一次,重放不会重复调用企微。""" - from app import db - from app.models import ( - ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, - ShippingReceiptRpaUnitRun, User, - ) - from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file - - with app.app_context(): - recipient = User(username='receipt-recipient', email='recipient@example.com', role='user', status='active', wecom_userid='receipt-user') - db.session.add(recipient); db.session.flush() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - task = ScheduleTask(schedule_no='SCH-RECEIPT-NOTIFY', name='Receipt notify', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id]) - db.session.add(task); db.session.flush() - run = ScheduleRun(run_no='RUN-RECEIPT-NOTIFY', schedule_task_id=task.id, status='running') - db.session.add(run); db.session.flush() - unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-notify-callback', status='success', config_snapshot_json={}) - db.session.add(unit); db.session.flush() - report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='a' * 64) - db.session.add(report_file); db.session.commit() - monkeypatch.setattr('app.services.shipping_notice.receipt_report_notification.file_asset_storage.get_bytes', lambda _key: b'receipt-data') - monkeypatch.setattr('app.services.shipping_notice.receipt_report_notification.upload_wecom_temp_media', lambda *_args: 'media-1') - calls: list[tuple] = [] - monkeypatch.setattr('app.services.shipping_notice.receipt_report_notification.send_wecom_file_message', lambda *args: calls.append(args) or {'errcode': 0}) - - assert deliver_receipt_file(report_file.id)['success_count'] == 1 - assert deliver_receipt_file(report_file.id)['success_count'] == 1 - assert len(calls) == 1 - - -def test_receipt_notification_failure_is_audited(app, monkeypatch): - """企微投递失败也必须保留接收人、时间、失败码和文件身份审计。""" - from app import db - from app.models import ( - ScheduleRun, ScheduleTask, ShippingAuditEvent, ShippingInventorySource, ShippingReceiptReportFile, - ShippingReceiptRpaUnitRun, User, - ) - from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file - - with app.app_context(): - recipient = User(username='receipt-unbound-recipient', email='receipt-unbound@example.com', role='user', status='active') - db.session.add(recipient); db.session.flush() - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - task = ScheduleTask(schedule_no='SCH-RECEIPT-NOTIFY-FAIL', name='Receipt notify fail', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id]) - db.session.add(task); db.session.flush() - run = ScheduleRun(run_no='RUN-RECEIPT-NOTIFY-FAIL', schedule_task_id=task.id, status='running') - db.session.add(run); db.session.flush() - unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-notify-fail', status='success', config_snapshot_json={}) - db.session.add(unit); db.session.flush() - report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt-fail.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='b' * 64) - db.session.add(report_file); db.session.commit() - - outcome = deliver_receipt_file(report_file.id) - - assert outcome['failed_count'] == 1 - audit = ShippingAuditEvent.query.filter_by(event_type='shipping_receipt_file_notification_attempted', aggregate_id=str(report_file.id)).one() - # 审计结果遵循统一枚举;业务投递状态仍保留为 failed。 - assert audit.result == 'failure' - assert audit.after_snapshot_json['error_code'] == 'WECOM_USER_UNBOUND' - - def _make_receipt_run_fixture(db, task_no: str, run_no: str, callback_id: str, *, awaiting: bool = True): """构造一个收料排程任务+run+成功单元+归档文件的最小通知夹具。""" from app.models import ( - ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, - ShippingReceiptRpaUnitRun, + ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile, + FreightRpaInboundUnitRun, ) - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - task = ScheduleTask(schedule_no=task_no, name=f'Receipt notify {task_no}', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *') + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + task = ScheduleTask(schedule_no=task_no, name=f'Receipt notify {task_no}', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *') db.session.add(task); db.session.flush() - run = ScheduleRun(run_no=run_no, schedule_task_id=task.id, status='running', response_summary_json={'awaiting_receipt_rpa': True} if awaiting else None) + run = ScheduleRun(run_no=run_no, schedule_task_id=task.id, status='running', response_summary_json={'awaiting_inbound_rpa': True} if awaiting else None) db.session.add(run); db.session.flush() - unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id=callback_id, status='success', config_snapshot_json={}) + unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id=callback_id, status='success', config_snapshot_json={}) db.session.add(unit); db.session.flush() - report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key=f'{callback_id}.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='c' * 64) + report_file = FreightRpaInboundReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key=f'{callback_id}.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='c' * 64) db.session.add(report_file) db.session.commit() return task, run, report_file @@ -115,10 +59,10 @@ def test_receipt_run_notification_is_one_shot_at_finalize(app, monkeypatch, tmp_ """收料 run 终态后经通用排程出口一次性发 textcard+收料 ZIP;重复归集不重发。""" from app import db from app.models import User - from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete + from app.services.schedule.freight_rpa_inbound_finalize import finalize_inbound_schedule_run_if_complete with app.app_context(): - app.config['FREIGHT_RPA_RECEIPT_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives') + app.config['FREIGHT_RPA_INBOUND_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') @@ -130,58 +74,58 @@ def test_receipt_run_notification_is_one_shot_at_finalize(app, monkeypatch, tmp_ app.config['WECOM_PUBLIC_BASE_URL'] = 'https://hxops.example.com' textcards, media_uploads, file_sends = _patch_unified_wecom(monkeypatch, enabled_events=True) - outcome = finalize_receipt_schedule_run_if_complete(run.id) + outcome = finalize_inbound_schedule_run_if_complete(run.id) # [断言意图] 一次性出口:单条 textcard + 结果 Excel + 单个收料 ZIP,与库存排程同通道同门禁。 assert outcome == {'finalized': True, 'status': 'success'} assert len(textcards) == 1 - assert '原始收料包:已随本通知发送' in textcards[0][1] + assert '原始入站包:已随本通知发送' in textcards[0][1] assert len(media_uploads) == 2 - assert media_uploads[0].startswith('收料RPA-') and media_uploads[0].endswith('-结果.xlsx') - assert media_uploads[1].startswith('收料RPA-') and media_uploads[1].endswith('-收料.zip') + assert media_uploads[0].startswith('入站RPA-') and media_uploads[0].endswith('-结果.xlsx') + assert media_uploads[1].startswith('入站RPA-') and media_uploads[1].endswith('-入站.zip') assert file_sends == ['media-1', 'media-2'] assert run.wecom_notified is True - assert run.response_summary_json.get('raw_receipt_zip_available') is True + assert run.response_summary_json.get('raw_inbound_zip_available') is True # [断言意图] awaiting 标志清零后再次归集必须短路,绝不二次打扰接收人。 - outcome_again = finalize_receipt_schedule_run_if_complete(run.id) - assert outcome_again == {'finalized': False, 'reason': 'not_awaiting_receipt_callback'} + outcome_again = finalize_inbound_schedule_run_if_complete(run.id) + assert outcome_again == {'finalized': False, 'reason': 'not_awaiting_inbound_callback'} assert len(textcards) == 1 and len(file_sends) == 2 def test_receipt_finalize_generates_summary_excel(app, tmp_path): - """收料 finalize 生成汇总 Excel:行结构对齐库存、状态归一、展示名 收料RPA-*-结果.xlsx。""" + """收料 finalize 生成汇总 Excel:行结构对齐库存、状态归一、展示名 入站RPA-*-结果.xlsx。""" from io import BytesIO from openpyxl import load_workbook from app import db from app.models import ( - ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, - ShippingReceiptRpaUnitRun, + ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportFile, + FreightRpaInboundUnitRun, ) - from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete + from app.services.schedule.freight_rpa_inbound_finalize import finalize_inbound_schedule_run_if_complete with app.app_context(): - app.config['FREIGHT_RPA_RECEIPT_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives-excel') - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - task = ScheduleTask(schedule_no='SCH-RECEIPT-EXCEL', name='Receipt excel', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *') + app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives-excel') + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + task = ScheduleTask(schedule_no='SCH-RECEIPT-EXCEL', name='Receipt excel', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *') db.session.add(task); db.session.flush() - run = ScheduleRun(run_no='RUN-RECEIPT-EXCEL', schedule_task_id=task.id, status='running', response_summary_json={'awaiting_receipt_rpa': True}) + run = ScheduleRun(run_no='RUN-RECEIPT-EXCEL', schedule_task_id=task.id, status='running', response_summary_json={'awaiting_inbound_rpa': True}) db.session.add(run); db.session.flush() - unit_ok = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='DSV360_AWSDU', connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-excel-ok', status='success', config_snapshot_json={}) - unit_empty = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='DSV360_AWSCV', connector_type='dbs', warehouse_id='AWSCV', callback_id='receipt-excel-empty', status='empty', config_snapshot_json={}) - unit_fail = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='CRANE_WH1', connector_type='crane', warehouse_id=None, callback_id='receipt-excel-fail', status='failed', error_code='RPA.RECEIPT_EXPORT_FAILED', error_message='download timeout', config_snapshot_json={}) + unit_ok = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code='DSV360_AWSDU', connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-excel-ok', status='success', config_snapshot_json={}) + unit_empty = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code='DSV360_AWSCV', connector_type='dbs', warehouse_id='AWSCV', callback_id='receipt-excel-empty', status='empty', config_snapshot_json={}) + unit_fail = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code='CRANE_WH1', connector_type='crane', warehouse_id=None, callback_id='receipt-excel-fail', status='failed', error_code='RPA.INBOUND_EXPORT_FAILED', error_message='download timeout', config_snapshot_json={}) db.session.add_all([unit_ok, unit_empty, unit_fail]); db.session.flush() - db.session.add(ShippingReceiptReportFile(unit_run_id=unit_ok.id, storage_provider='minio', storage_bucket='test', storage_key='receipt-excel-1.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='d' * 64)) + db.session.add(FreightRpaInboundReportFile(unit_run_id=unit_ok.id, storage_provider='minio', storage_bucket='test', storage_key='receipt-excel-1.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='d' * 64)) db.session.commit() - outcome = finalize_receipt_schedule_run_if_complete(run.id) + outcome = finalize_inbound_schedule_run_if_complete(run.id) # [断言意图] finalize 生成汇总 Excel,并携带与库存同名的 summary 契约键。 assert outcome == {'finalized': True, 'status': 'partial_failed'} assert run.excel_file_data - assert run.excel_file_name.startswith('收料RPA-') and run.excel_file_name.endswith('-结果.xlsx') + assert run.excel_file_name.startswith('入站RPA-') and run.excel_file_name.endswith('-结果.xlsx') assert run.response_summary_json['excel_export_status'] == 'ok' assert run.response_summary_json['excel_failed'] is False @@ -189,7 +133,7 @@ def test_receipt_finalize_generates_summary_excel(app, tmp_path): workbook = load_workbook(BytesIO(run.excel_file_data)) sheet = workbook.active header = [cell.value for cell in sheet[1]] - assert header[:2] == ['收料源', '仓库'] + assert header[:2] == ['入站源', '仓库'] rows = {row[0]: row for row in sheet.iter_rows(min_row=2, values_only=True)} assert rows['DSV360_AWSDU'][3] == 1 and rows['DSV360_AWSDU'][4] == 'success' assert rows['DSV360_AWSCV'][4] == 'skipped' diff --git a/backend/tests/test_freight_receipt_rpa_schedule.py b/backend/tests/test_freight_receipt_rpa_schedule.py index 26c51ca7..1701408d 100644 --- a/backend/tests/test_freight_receipt_rpa_schedule.py +++ b/backend/tests/test_freight_receipt_rpa_schedule.py @@ -8,26 +8,27 @@ from datetime import datetime, timedelta def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app, monkeypatch): """一源一单元:有/无 Warehouse 条件均产出 unit;多值 Warehouse 不拆分。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingRpaProfile - from app.services.schedule.freight_receipt_rpa_job import run_freight_receipt_rpa_schedule + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportConfig, FreightRpaProfile + from app.services.schedule.freight_rpa_inbound_job import run_freight_rpa_inbound_schedule with app.app_context(): - dbs = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - crane_profile = ShippingRpaProfile(profile_code='CRANE-RECEIPT', display_name='Crane', connector_type='crane', login_url='https://crane.invalid', login_config_json={'auth_mode': 'password'}) - crane = ShippingInventorySource( + dbs = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + crane_profile = FreightRpaProfile(profile_code='CRANE-RECEIPT', display_name='Crane', connector_type='crane', login_url='https://crane.invalid', login_config_json={'auth_mode': 'password'}) + # s18 起站点行不再承载解析绑定/报表路径/查询条件;入站排程只读 FreightRpaInboundReportConfig。 + crane = FreightRpaSource( source_code='CRANE-RECEIPT', display_name='Crane', connector_type='crane', rpa_profile=crane_profile, - parsing_profile=dbs.parsing_profile, excel_template=dbs.excel_template, - warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE', report_path_json={}, query_parameters_json=[], enabled=True, + excel_template=dbs.excel_template, + warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE', enabled=True, ) - empty_dbs = ShippingInventorySource( + empty_dbs = FreightRpaSource( source_code='DSV360_EMPTY_QP', display_name='Empty QP', connector_type='dbs', rpa_profile=dbs.rpa_profile, - parsing_profile=dbs.parsing_profile, excel_template=dbs.excel_template, - warehouse_resolution_mode='fixed', fixed_warehouse_id='EMPTY', report_path_json={}, query_parameters_json=[], enabled=True, + excel_template=dbs.excel_template, + warehouse_resolution_mode='fixed', fixed_warehouse_id='EMPTY', enabled=True, ) db.session.add_all([ crane, empty_dbs, - ShippingReceiptReportConfig( - inventory_source_id=dbs.id, + FreightRpaInboundReportConfig( + source_id=dbs.id, report_path_json={ 'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail', @@ -39,11 +40,11 @@ def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app, ]) db.session.flush() db.session.add_all([ - ShippingReceiptReportConfig( - inventory_source_id=crane.id, report_path_json={'report_name': 'Inbound Details'}, query_parameters_json=[], + FreightRpaInboundReportConfig( + source_id=crane.id, report_path_json={'report_name': 'Inbound Details'}, query_parameters_json=[], ), - ShippingReceiptReportConfig( - inventory_source_id=empty_dbs.id, + FreightRpaInboundReportConfig( + source_id=empty_dbs.id, report_path_json={ 'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail', @@ -53,7 +54,7 @@ def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app, ]) 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 * * *', + platform_api_path='freight-rpa-inbound', 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() @@ -62,16 +63,16 @@ def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app, captured = {} monkeypatch.setattr( - 'app.services.schedule.freight_receipt_rpa_job.write_receipt_export_batch_trigger', + 'app.services.schedule.freight_rpa_inbound_job.write_inbound_export_batch_trigger', lambda run_no, units, payload: captured.update(run_no=run_no, units=units, payload=payload) or 'receipt-trigger.json', ) - total, success, failed, skipped, details, errors, logs = run_freight_receipt_rpa_schedule(task, run) + total, success, failed, skipped, details, errors, logs = run_freight_rpa_inbound_schedule(task, run) # 关键断言:三源三单元;多值 Warehouse 不拆;空 query_parameters 仍产出。 assert (total, success, failed, skipped, errors) == (3, 0, 0, 0, []) 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 captured['payload']['schema_version'] == 'freight_rpa.inbound.v1' assert len(captured['units']) == 3 dbs_unit = next(item for item in captured['units'] if item['source_code'] == dbs.source_code) assert dbs_unit['rpa_profile_code'] == 'DBS_DUB_TEST' @@ -94,14 +95,14 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa """收料 Worker 离线时排程立即 failed,不写 trigger、不落 unit。""" from app import db from app.core.errors import ServiceUnavailableError - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptRpaUnitRun - from app.services.schedule.freight_receipt_rpa_job import run_freight_receipt_rpa_schedule - from app.services.shipping_notice.rpa_worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportConfig, FreightRpaInboundUnitRun + from app.services.schedule.freight_rpa_inbound_job import run_freight_rpa_inbound_schedule + from app.services.freight_rpa.common.worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE with app.app_context(): - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - db.session.add(ShippingReceiptReportConfig( - inventory_source_id=source.id, + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + db.session.add(FreightRpaInboundReportConfig( + source_id=source.id, report_path_json={ 'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail', @@ -110,7 +111,7 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa )) 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 * * *', + platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *', job_params={'source_codes': [source.source_code]}, ) db.session.add(task) @@ -121,30 +122,30 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa trigger_calls = [] monkeypatch.setattr( - 'app.services.schedule.freight_receipt_rpa_job.assert_receipt_rpa_worker_ready', + 'app.services.schedule.freight_rpa_inbound_job.assert_inbound_rpa_worker_ready', lambda: (_ for _ in ()).throw(ServiceUnavailableError( RPA_WORKER_OFFLINE_MESSAGE, code='RPA.WORKER_OFFLINE', - details={'reasons': ['no_worker_heartbeat'], 'detail_message': 'receipt worker offline'}, + details={'reasons': ['no_worker_heartbeat'], 'detail_message': 'inbound worker offline'}, )), ) monkeypatch.setattr( - 'app.services.schedule.freight_receipt_rpa_job.write_receipt_export_batch_trigger', + 'app.services.schedule.freight_rpa_inbound_job.write_inbound_export_batch_trigger', lambda *args, **kwargs: trigger_calls.append(args) or 'should-not-write.json', ) - total, success, failed, skipped, details, errors, logs = run_freight_receipt_rpa_schedule(task, run) + total, success, failed, skipped, details, errors, logs = run_freight_rpa_inbound_schedule(task, run) # [断言意图] fail-fast:计 failed、不入库 unit、不写 trigger、不进入 awaiting。 assert (total, success, failed, skipped) == (1, 0, 1, 0) assert details == [] - assert errors == ['receipt worker offline'] + assert errors == ['inbound worker offline'] assert trigger_calls == [] - assert ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).count() == 0 + assert FreightRpaInboundUnitRun.query.filter_by(schedule_run_id=run.id).count() == 0 failed_log = next(log for log in logs if isinstance(log, dict) and log.get('status') == 'failed') assert failed_log['detail'].get('reasons') == ['no_worker_heartbeat'] assert not any( - isinstance(log, dict) and log.get('status') == 'awaiting_receipt_rpa' + isinstance(log, dict) and log.get('status') == 'awaiting_inbound_rpa_callback' for log in logs ) @@ -152,19 +153,19 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa def test_receipt_schedule_options_only_return_enabled_configured_sources(app): """动态排程选项只暴露库存站点已启用且已配置收料的站点。""" from app import db - from app.models import ShippingInventorySource, ShippingReceiptReportConfig + from app.models import FreightRpaSource, FreightRpaInboundReportConfig from app.services.schedule.job_options import list_job_options with app.app_context(): - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - db.session.add(ShippingReceiptReportConfig( - inventory_source_id=source.id, + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + db.session.add(FreightRpaInboundReportConfig( + source_id=source.id, report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail'}, query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['A'], 'required': False, 'select_all': False}], )) db.session.commit() - options = list_job_options('shipping_receipt_sources') + options = list_job_options('freight_rpa_inbound_sources') assert any(item['value'] == source.source_code for item in options) @@ -172,91 +173,91 @@ def test_receipt_schedule_options_only_return_enabled_configured_sources(app): def test_stale_receipt_callback_run_is_failed_without_automatic_retry(app): """无回调超时只关闭本次 run/单元并写审计,绝不创建重试单元。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, ShippingInventorySource, ShippingReceiptRpaUnitRun - from app.services.schedule.freight_receipt_rpa_finalize import recover_stale_receipt_rpa_schedule_runs + from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, FreightRpaSource, FreightRpaInboundUnitRun + from app.services.schedule.freight_rpa_inbound_finalize import recover_stale_inbound_rpa_schedule_runs with app.app_context(): - app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60 - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - task = ScheduleTask(schedule_no='SCH-RECEIPT-TIMEOUT', name='Receipt timeout', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *') + app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60 + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + task = ScheduleTask(schedule_no='SCH-RECEIPT-TIMEOUT', name='Receipt timeout', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *') db.session.add(task); db.session.flush() - run = ScheduleRun(run_no='RUN-RECEIPT-TIMEOUT', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=2), response_summary_json={'awaiting_receipt_rpa': True}) + run = ScheduleRun(run_no='RUN-RECEIPT-TIMEOUT', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=2), response_summary_json={'awaiting_inbound_rpa': True}) db.session.add(run); db.session.flush() - unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-timeout', status='awaiting_rpa', config_snapshot_json={}) + unit = FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-timeout', status='awaiting_rpa', config_snapshot_json={}) db.session.add(unit); db.session.commit() - assert recover_stale_receipt_rpa_schedule_runs(task) == 1 + assert recover_stale_inbound_rpa_schedule_runs(task) == 1 db.session.refresh(run); db.session.refresh(unit) assert run.status == 'failed' assert unit.status == 'failed' - assert unit.error_code == 'RPA.RECEIPT_CALLBACK_TIMEOUT' - assert ShippingReceiptRpaUnitRun.query.filter_by(retry_of_id=unit.id).count() == 0 - assert ShippingAuditEvent.query.filter_by(event_type='shipping_receipt_rpa_callback_timeout', aggregate_id=str(unit.id)).count() == 1 + assert unit.error_code == 'RPA.INBOUND_CALLBACK_TIMEOUT' + assert FreightRpaInboundUnitRun.query.filter_by(retry_of_id=unit.id).count() == 0 + assert ShippingAuditEvent.query.filter_by(event_type='shipping_inbound_rpa_callback_timeout', aggregate_id=str(unit.id)).count() == 1 def test_receipt_trigger_is_published_atomically(app, tmp_path): """Worker 只能观察到完整 JSON;临时写入文件不会匹配其 *.json 扫描。""" - from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger + from app.services.freight_rpa.inbound.trigger_io import write_inbound_export_batch_trigger with app.app_context(): - app.config['FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR'] = str(tmp_path) - path = write_receipt_export_batch_trigger('RUN-ATOMIC', [{'callback_id': 'c1'}], {}) + app.config['FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR'] = str(tmp_path) + path = write_inbound_export_batch_trigger('RUN-ATOMIC', [{'callback_id': 'c1'}], {}) assert path - assert (tmp_path / 'receipt_export_batch_RUN-ATOMIC.json').exists() + assert (tmp_path / 'inbound_export_batch_RUN-ATOMIC.json').exists() assert not list(tmp_path.glob('.*.tmp')) def test_stale_receipt_full_scan_recovers_without_task_trigger_or_restart(app): """全量扫描(每轮 tick 路径)无需任务再次执行/进程重启即可收口超时收料 run。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun - from app.services.schedule.freight_receipt_rpa_finalize import recover_all_stale_receipt_rpa_schedule_runs + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun + from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_inbound_rpa_schedule_runs with app.app_context(): - app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60 - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - task = ScheduleTask(schedule_no='SCH-RECEIPT-ORPHAN', name='Receipt orphan', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *') + app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60 + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + task = ScheduleTask(schedule_no='SCH-RECEIPT-ORPHAN', name='Receipt orphan', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *') db.session.add(task); db.session.flush() - run = ScheduleRun(run_no='RUN-RECEIPT-ORPHAN', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=5), response_summary_json={'awaiting_receipt_rpa': True}) + run = ScheduleRun(run_no='RUN-RECEIPT-ORPHAN', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=5), response_summary_json={'awaiting_inbound_rpa': True}) db.session.add(run); db.session.flush() - db.session.add(ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-orphan', status='awaiting_rpa', config_snapshot_json={})) + db.session.add(FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-orphan', status='awaiting_rpa', config_snapshot_json={})) db.session.commit() # [断言意图] 全量扫描不依赖 task 入参、进程重启或同排程再次执行(点B 修复口径); # 超时窗(60s)过后扫描即收口为 failed 并写 recovered_reason。 - assert recover_all_stale_receipt_rpa_schedule_runs() == 1 + assert recover_all_stale_inbound_rpa_schedule_runs() == 1 db.session.refresh(run) assert run.status == 'failed' - assert run.response_summary_json.get('recovered_reason') == 'receipt_rpa_callback_timeout' + assert run.response_summary_json.get('recovered_reason') == 'inbound_rpa_callback_timeout' -def test_receipt_recovery_respects_fresh_activity_of_long_batch(app): +def test_inbound_recovery_respects_fresh_activity_of_long_batch(app): """长批次健康在跑不得被误杀:超时锚取最后单元活动而非 run 开始时间。""" from app import db - from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun - from app.services.schedule.freight_receipt_rpa_finalize import recover_all_stale_receipt_rpa_schedule_runs + from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun + from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_inbound_rpa_schedule_runs with app.app_context(): - app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60 - source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() - task = ScheduleTask(schedule_no='SCH-RECEIPT-LONG', name='Receipt long batch', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *') + app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60 + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + task = ScheduleTask(schedule_no='SCH-RECEIPT-LONG', name='Receipt long batch', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *') db.session.add(task); db.session.flush() - run = ScheduleRun(run_no='RUN-RECEIPT-LONG', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=30), response_summary_json={'awaiting_receipt_rpa': True}) + run = ScheduleRun(run_no='RUN-RECEIPT-LONG', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=30), response_summary_json={'awaiting_inbound_rpa': True}) db.session.add(run); db.session.flush() # 单元1:30 秒前终态(笔间活动新鲜);单元2:45 秒前进入 processing(在飞,started_at 为锚) - db.session.add(ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-long-done', status='success', config_snapshot_json={}, finished_at=datetime.utcnow() - timedelta(seconds=30))) - db.session.add(ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='B', callback_id='receipt-long-run', status='processing', config_snapshot_json={}, started_at=datetime.utcnow() - timedelta(seconds=45))) + db.session.add(FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-long-done', status='success', config_snapshot_json={}, finished_at=datetime.utcnow() - timedelta(seconds=30))) + db.session.add(FreightRpaInboundUnitRun(schedule_run_id=run.id, source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='B', callback_id='receipt-long-run', status='processing', config_snapshot_json={}, started_at=datetime.utcnow() - timedelta(seconds=45))) db.session.commit() # [断言意图] run.started_at(30min 前) 已远超 60s 窗,但最后活动仅 30~45s—— # 笔间静默口径下健康长批次必须不被回收(旧口径按 started_at 会误杀)。 - assert recover_all_stale_receipt_rpa_schedule_runs() == 0 + assert recover_all_stale_inbound_rpa_schedule_runs() == 0 db.session.refresh(run) assert run.status == 'running' -def test_receipt_recovery_is_wired_into_per_tick_maintenance_not_startup_only(): +def test_inbound_recovery_is_wired_into_per_tick_maintenance_not_startup_only(): """哨兵回归:收料超时对账必须挂在每轮领取维护区,不得回流启动一次性分支。""" import inspect @@ -265,6 +266,73 @@ def test_receipt_recovery_is_wired_into_per_tick_maintenance_not_startup_only(): source = inspect.getsource(queue_service) marker_init = source.index("_worker_initialized = True") # [断言意图] 调用点必须位于一次性分支竖旗之后(每轮维护区); - # 回流旧写法(receipt_recovered = ...)会让长驻进程永不回收(RUN20261001131705E5E5 根因)。 - assert source.index("receipt_stale = recover_all_stale_receipt_rpa_schedule_runs()") > marker_init - assert "receipt_recovered = recover_all_stale_receipt_rpa_schedule_runs()" not in source + # 回流旧写法(inbound_recovered = ...)会让长驻进程永不回收(RUN20261001131705E5E5 根因)。 + assert source.index("inbound_stale = recover_all_stale_inbound_rpa_schedule_runs()") > marker_init + assert "inbound_recovered = recover_all_stale_inbound_rpa_schedule_runs()" not in source + + +def test_stale_orphan_inbound_units_are_failed_by_full_scan(app): + """按需触发(无排程)的入站单元超时由全量扫描收口为失败,健康在跑单元不受影响。""" + from app import db + from app.models import ShippingAuditEvent, FreightRpaSource, FreightRpaInboundUnitRun + from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_orphan_inbound_units + + with app.app_context(): + app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60 + source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one() + # 单元1:排队 5 分钟从未被领取(created_at 为锚,queued 分支);单元2:领取后 + # 静默 5 分钟(started_at 为锚);单元3:30 秒前刚领取(健康在跑,不得误杀)。 + stale_queued = FreightRpaInboundUnitRun( + source_id=source.id, source_code=source.source_code, connector_type='dbs', + callback_id='inbound-orphan-queued', status='queued', config_snapshot_json={}, + created_at=datetime.utcnow() - timedelta(minutes=5), + ) + stale_processing = FreightRpaInboundUnitRun( + source_id=source.id, source_code=source.source_code, connector_type='dbs', + callback_id='inbound-orphan-processing', status='processing', config_snapshot_json={}, + created_at=datetime.utcnow() - timedelta(minutes=6), + started_at=datetime.utcnow() - timedelta(minutes=5), + ) + fresh_processing = FreightRpaInboundUnitRun( + source_id=source.id, source_code=source.source_code, connector_type='dbs', + callback_id='inbound-orphan-fresh', status='processing', config_snapshot_json={}, + created_at=datetime.utcnow() - timedelta(seconds=45), + started_at=datetime.utcnow() - timedelta(seconds=30), + ) + db.session.add_all([stale_queued, stale_processing, fresh_processing]) + db.session.commit() + + # [断言意图] 调拨工作台按需触发单元 schedule_run_id=NULL,不在 run 级扫描 + # (recover_all_stale_inbound_rpa_schedule_runs 按 run 遍历)范围内;网页异常 + # 关闭后回调永不到达,必须由本扫描终态化(2026-10-16 事故回归),健康单元原样; + # 与 run 级回收同口径:只标失败、写审计,绝不自动创建重试单元。 + assert recover_all_stale_orphan_inbound_units() == 2 + db.session.refresh(stale_queued) + db.session.refresh(stale_processing) + db.session.refresh(fresh_processing) + + assert stale_queued.status == 'failed' + assert stale_queued.error_code == 'RPA.INBOUND_CALLBACK_TIMEOUT' + assert stale_queued.finished_at is not None + assert stale_processing.status == 'failed' + assert fresh_processing.status == 'processing' + assert FreightRpaInboundUnitRun.query.filter_by(retry_of_id=stale_queued.id).count() == 0 + # [断言意图] 审计须含失败结果与 before/after 快照——与 run 级回收同语义由测试锁定。 + timeout_event = ShippingAuditEvent.query.filter_by( + event_type='shipping_inbound_rpa_callback_timeout', aggregate_id=str(stale_queued.id), + ).one() + assert timeout_event.result == 'failure' + assert (timeout_event.after_snapshot_json or {}).get('status') == 'failed' + + +def test_orphan_inbound_recovery_is_wired_into_per_tick_maintenance(): + """哨兵回归:孤儿单元回收必须挂在每轮领取维护区(与 run 级扫描同区同轮)。""" + import inspect + + from app.services.schedule import queue_service + + source = inspect.getsource(queue_service) + # [断言意图] 调用点必须与 run 级收料扫描同在每轮维护区且在其后; + # 缺席或回流启动一次性分支都会复现「长驻进程期间来源永久 fetching」事故。 + marker_run_scan = source.index("inbound_stale = recover_all_stale_inbound_rpa_schedule_runs()") + assert source.index("recover_all_stale_orphan_inbound_units()") > marker_run_scan diff --git a/backend/tests/test_freight_receipt_worker_contract.py b/backend/tests/test_freight_receipt_worker_contract.py index 117ce9c0..0b85e153 100644 --- a/backend/tests/test_freight_receipt_worker_contract.py +++ b/backend/tests/test_freight_receipt_worker_contract.py @@ -1,4 +1,4 @@ -"""独立收料 Worker 静态契约。""" +"""独立 inbound(原收料)Worker 静态契约。""" import importlib.util import sys @@ -6,22 +6,23 @@ from pathlib import Path def test_receipt_worker_isolated_from_inventory_worker_and_uses_receipt_contract(): - """收料 Worker 只消费 v1 receipt trigger、专用目录和独立 callback。""" - text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8') - assert 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR' in text - 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 + """inbound Worker 只消费 freight_rpa.inbound.v1 trigger、专用目录和独立 callback。""" + text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py').read_text(encoding='utf-8') + assert 'FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR' in text + assert 'FREIGHT_RPA_SHARED_INBOUND_DROP_DIR' in text + assert 'freight_rpa.inbound.v1' in text + assert "from rpa_callbacks import" in text + assert 'INBOUND_BATCH_READY' in text + assert 'INBOUND_BATCH_PROGRESS' in text + assert 'INBOUND_UNIT_PROGRESS' in text assert 'freight_rpa_worker' not in text - assert 'FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR' not in text + assert 'FREIGHT_RPA_SHARED_ONHAND_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' + Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_dbs_export.py' ).read_text(encoding='utf-8') # 关键断言:历史必填门禁已移除;仅在 warehouse_id 有值时追加(兼容旧 trigger)。 assert 'DBS receipt unit requires warehouse_id' not in text @@ -31,7 +32,7 @@ def test_receipt_dbs_export_does_not_require_warehouse_id(): 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' + Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_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 @@ -39,9 +40,9 @@ def test_receipt_dbs_export_maps_report_path_to_navigation(): 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') + root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' + worker = (root / 'inbound_rpa_worker.py').read_text(encoding='utf-8') + export = (root / 'inbound_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 @@ -51,12 +52,12 @@ def test_receipt_dbs_batch_reuses_inventory_session_prepare(): 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') + root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' + worker = (root / 'inbound_rpa_worker.py').read_text(encoding='utf-8') # 关键断言:命名函数与 source/run 字段存在;不再用 safe_callback 拼 receipt_ 文件名。 - assert 'def _receipt_download_name(' in worker + assert 'def _inbound_download_name(' in worker assert 'batch_run_no' in worker - assert "f'receipt_{safe_run}_{safe_source}_{safe_wh}_{stamp}{suffix}'" in worker + assert "f'inbound_{safe_run}_{safe_source}_{safe_wh}_{stamp}{suffix}'" in worker assert 'safe_callback' not in worker assert "receipt_{safe_callback}" not in worker @@ -64,7 +65,7 @@ def test_receipt_worker_download_name_uses_source_not_callback(): def test_receipt_crane_driver_forces_inbound_details_match_name(): """收料 Crane 必须将固定报表名传给轮询匹配,不能落回库存文件名默认值。""" root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' - receipt_driver = (root / 'receipt' / 'receipt_crane_export.py').read_text(encoding='utf-8') + receipt_driver = (root / 'inbound' / 'inbound_crane_export.py').read_text(encoding='utf-8') crane_driver = (root / 'connectors' / 'crane' / 'crane_report_export.py').read_text(encoding='utf-8') assert "'scheduled_report_name': 'Inbound Details'" in receipt_driver assert "source_value = str((source or {}).get('scheduled_report_name') or '').strip()" in crane_driver @@ -73,7 +74,7 @@ def test_receipt_crane_driver_forces_inbound_details_match_name(): 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' + Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_crane_export.py' ).read_text(encoding='utf-8') assert "'__download_dir': str(unit.get('__download_dir') or '')" in text @@ -81,7 +82,7 @@ def test_receipt_crane_export_passes_download_dir_for_fallback(): 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' + Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py' ).read_text(encoding='utf-8') assert 'download_artifact_fallback' in text assert 'def _persist_download_to_dest(' in text @@ -90,23 +91,23 @@ def test_receipt_worker_save_download_uses_directory_fallback(): def test_receipt_worker_validates_excel_and_reports_empty(): - """收料落盘后必须结构校验;无明细走 NoReceiptDataError → empty/no_receipt_data。""" + """收料落盘后必须结构校验;无明细走 NoReceiptDataError → empty/no_inbound_data。""" text = ( - Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py' + Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py' ).read_text(encoding='utf-8') empty_mod = ( Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' - / 'receipt' - / 'receipt_excel_empty.py' + / 'inbound' + / 'inbound_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 'def _validate_inbound_excel(' in text + assert 'from inbound_excel_empty import' in text + assert 'class NoInboundDataError' in empty_mod + assert 'no_inbound_data' in empty_mod + assert 'is_inbound_excel_header_row' in empty_mod + assert "'error_code': 'no_inbound_data'" in text assert "_post_callback({" in text and "'status': 'empty'" in text assert '_EXPORT_UNIT_MAX_ATTEMPTS = 2' in text assert 'retry with clean page' in text @@ -120,7 +121,7 @@ def test_receipt_ready_callback_outside_export_retry_like_inventory_progress(): _post_unit_ready / batch-progress 放在导出循环外,并禁止 ready 失败再导。 """ text = ( - Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py' + Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py' ).read_text(encoding='utf-8') assert 'def _post_unit_ready(' in text assert '重试只覆盖导出/落盘/校验' in text or 'ready 回调禁止进入本循环' in text @@ -133,18 +134,18 @@ def test_receipt_ready_callback_outside_export_retry_like_inventory_progress(): def test_receipt_heartbeat_capability_is_receipt_export(): - """收料 Worker 心跳能力必须声明 receipt_export,不得再写 inventory_export。""" + """inbound Worker 心跳能力必须声明 inbound_export,不得再写 onhand_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 + assert 'inbound_export' in text + assert 'is_inbound' 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' - module_path = root / 'receipt' / 'receipt_crane_export.py' + module_path = root / 'inbound' / 'inbound_crane_export.py' sys.path.insert(0, str(root)) spec = importlib.util.spec_from_file_location('freight_receipt_crane_export_test', module_path) assert spec and spec.loader @@ -161,7 +162,7 @@ def test_receipt_crane_driver_forces_inbound_details_entry_route(): def test_receipt_worker_uses_common_trigger_consumer(): """收料 Worker 必须复用公共 claim/归档原语,不再自建目录搬移实现。""" - text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8') + text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py').read_text(encoding='utf-8') assert 'claim_trigger' in text assert 'archive_trigger' in text assert "path.replace(claimed)" not in text # 领取逻辑收敛到公共模块 @@ -169,47 +170,64 @@ def test_receipt_worker_uses_common_trigger_consumer(): def test_receipt_worker_logs_full_lifecycle_and_banner(): """收料 Worker 必须启用文件日志、完整启动 banner,且成功/失败单元都留痕。""" - text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8') + text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py').read_text(encoding='utf-8') assert 'configure_file_logging' in text assert 'maybe_rotate_open_log' in text assert 'mock=' in text and 'api_base=' in text and 'auth_key=' in text # banner 对齐库存字段 - assert '[receipt-unit] success' in text # 成功单元留痕(此前成功路径零输出) - assert '[receipt-unit] failed' in text - assert '[receipt-trigger] claimed' in text and '[receipt-trigger] archived' in text + assert '[inbound-unit] success' in text # 成功单元留痕(此前成功路径零输出) + assert '[inbound-unit] failed' in text + assert '[inbound-trigger] claimed' in text and '[inbound-trigger] archived' in text def test_receipt_worker_reports_heartbeat_with_dedicated_identity(): """收料 Worker 必须接心跳(对齐库存),且 ps1 以独立 WORKER_ID 上报避免监控身份抖动。""" - text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8') + text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py').read_text(encoding='utf-8') assert 'start_heartbeat_loop' in text and 'maybe_send_heartbeat' in text - ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'start_receipt_worker.ps1').read_text(encoding='utf-8') - assert 'FREIGHT_RPA_WORKER_ID' in ps1 and '-receipt' in ps1 + ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'start_inbound_worker.ps1').read_text(encoding='utf-8') + assert 'FREIGHT_RPA_WORKER_ID' in ps1 and '-inbound' in ps1 def test_receipt_register_script_mirrors_inventory_with_distinct_identity(): """收料计划任务注册脚本与库存同构(AtLogOn+Interactive+headless),任务名独立可同机并存。""" root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' - receipt = (root / 'receipt' / 'register_receipt_worker_tasks.ps1').read_text(encoding='utf-8') - inventory = (root / 'inventory' / 'register_inventory_worker_tasks.ps1').read_text(encoding='utf-8') + receipt = (root / 'inbound' / 'register_inbound_worker_tasks.ps1').read_text(encoding='utf-8') + inventory = (root / 'onhand' / 'register_onhand_worker_tasks.ps1').read_text(encoding='utf-8') # [断言意图] 任务名赋值行必须指向 Receipt;docstring 允许提及库存任务名(并排设计说明),功能段不得引用 - assert '$TestTask = "HXOPS Receipt RPA Worker TEST"' in receipt - assert '$ProdTask = "HXOPS Receipt RPA Worker PROD"' in receipt - assert 'HXOPS Inventory RPA Worker TEST' in inventory and 'HXOPS Receipt RPA Worker' not in inventory + assert '$TestTask = "HXOPS Freight Inbound RPA Worker TEST"' in receipt + assert '$ProdTask = "HXOPS Freight Inbound RPA Worker PROD"' in receipt + assert 'HXOPS Freight Onhand RPA Worker TEST' in inventory and 'HXOPS Freight Inbound RPA Worker' not in inventory # [断言意图] 动作必须指向收料启动脚本,且不得把库存启动脚本带进收料注册 - assert 'start_receipt_worker.ps1' in receipt and 'start_inventory_worker.ps1' not in receipt + assert 'start_inbound_worker.ps1' in receipt and 'start_onhand_worker.ps1' not in receipt # [断言意图] 形状约束与库存同款:AtLogOn + Interactive + headless + 隐藏控制台 assert 'AtLogOn' in receipt and 'Interactive' in receipt and 'Headless' in receipt and 'WindowStyle Hidden' in receipt 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') + text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py').read_text(encoding='utf-8') # [断言意图] 默认开启复用;持久目录形如 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') + assert 'INBOUND_BATCH_PROGRESS' in text + assert 'INBOUND_UNIT_PROGRESS' in text + ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'start_inbound_worker.ps1').read_text(encoding='utf-8') assert '[switch]$NoSessionReuse' in ps1 assert "FREIGHT_RPA_WORKER_SESSION_REUSE = $sessionReuse" in ps1 + + +def test_receipt_worker_reports_remaining_units_on_batch_open_failure(): + """批级浏览器打开失败须给剩余单元补 failed 回调,禁止只归档 trigger。 + + [断言意图] 2026-10-20 事故:launch_persistent_context TargetClosed 后 trigger 进 + failed/ 但单元无终态回调 → awaiting_rpa/抓取中永挂。契约要求 + `_report_group_open_failure` + `reported_callback_ids` 剩余补发。 + """ + text = ( + Path(__file__).resolve().parents[2] + / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py' + ).read_text(encoding='utf-8') + assert 'def _report_group_open_failure(' in text + assert 'reported_callback_ids' in text + assert '_report_group_open_failure(remaining, exc)' in text + assert 'open/group failed' in text diff --git a/backend/tests/test_freight_rpa_admin_ownership_gate.py b/backend/tests/test_freight_rpa_admin_ownership_gate.py new file mode 100644 index 00000000..054f3673 --- /dev/null +++ b/backend/tests/test_freight_rpa_admin_ownership_gate.py @@ -0,0 +1,68 @@ +""" +tests/test_freight_rpa_admin_ownership_gate.py + +用途:锁定货代 RPA 管理归属——入站/出站配置、报表规则、来源站点/登录连接不再寄宿 shipping_onhand 命名空间。 +依赖:pathlib、importlib、pytest。 +""" + +from __future__ import annotations + +import importlib +from pathlib import Path + +BACKEND_ROOT = Path(__file__).resolve().parents[1] + + +def test_parsing_profile_lives_under_freight_rpa(): + """报表规则模块在 freight_rpa,shipping_notice 不再保留 onhand_parsing_profile 文件。""" + assert (BACKEND_ROOT / 'app/services/freight_rpa/parsing_profile.py').is_file() + assert not (BACKEND_ROOT / 'app/services/shipping_notice/onhand_parsing_profile.py').exists() + mod = importlib.import_module('app.services.freight_rpa.parsing_profile') + assert callable(mod.save_draft) + assert callable(mod.list_profiles) + + +def test_inbound_outbound_report_config_not_on_shipping_onhand_admin(): + """入站/出站配置 CRUD 在 freight_rpa_report_config_service,不在 onhand admin。""" + onhand = importlib.import_module('app.services.admin.shipping_onhand_admin_service') + report = importlib.import_module('app.services.admin.freight_rpa_report_config_service') + for name in ( + 'get_inbound_report_config', + 'save_inbound_report_config', + 'get_outbound_report_config', + 'save_outbound_report_config', + ): + assert not hasattr(onhand, name) + assert callable(getattr(report, name)) + + +def test_movement_fields_route_under_freight_rpa_not_shipping_notice(): + """异动字段目录挂在 /freight-rpa/,不在 /shipping-notice/。""" + freight = (BACKEND_ROOT / 'app/api/admin_freight_rpa.py').read_text(encoding='utf-8') + shipping = (BACKEND_ROOT / 'app/api/admin/shipping_notice_admin.py').read_text(encoding='utf-8') + assert "/freight-rpa/movement-fields" in freight + assert "/shipping-notice/movement-fields" not in shipping + +def test_source_profile_admin_not_on_shipping_onhand(): + """登录连接与来源站点 CRUD 在 freight_rpa_source_admin_service。""" + onhand = importlib.import_module('app.services.admin.shipping_onhand_admin_service') + source = importlib.import_module('app.services.admin.freight_rpa_source_admin_service') + for name in ( + 'list_profiles', + 'save_profile', + 'delete_profile', + 'list_sources', + 'save_source', + 'delete_source', + 'activate_source', + 'deactivate_source', + 'bind_source_parsing_profile', + 'assert_onhand_source_can_enable', + 'save_onhand_report_config', + ): + assert not hasattr(onhand, name), name + assert callable(getattr(source, name)), name + for name in ('list_snapshots', 'list_rules', 'list_external_mappings'): + assert callable(getattr(onhand, name)), name + assert not hasattr(source, name), name + diff --git a/backend/tests/test_freight_rpa_batch_s_grep_gate.py b/backend/tests/test_freight_rpa_batch_s_grep_gate.py new file mode 100644 index 00000000..aa93f81e --- /dev/null +++ b/backend/tests/test_freight_rpa_batch_s_grep_gate.py @@ -0,0 +1,292 @@ +""" +tests/test_freight_rpa_batch_s_grep_gate.py + +用途:批次 S 生产路径 grep 门禁。白名单外的旧表名、旧 admin inventory 路径、 + ShippingInventory 类名(含 camelCase 助手)、outbound_upload 必须为零。 +依赖:backend/app 与 frontend/src 源码(只读)。不读 docs/superpowers,不读历史迁移。 +逻辑:pytest 调用本文件扫描器。ALLOWED_TOKENS 只有两个 HTTP 工具名。 + 四个任务/行级类名已改为 Onhand,旧名整词现在失败。 + 缩写约束名因下划线前缀不是整词。履约 shipment、movement、中文「库存」不在禁词正则里。 +""" + +from __future__ import annotations + +import re +from pathlib import Path + +import pytest + +pytestmark = pytest.mark.pure_unit + +REPO = Path(__file__).resolve().parents[2] +SCAN_ROOTS = ( + REPO / "backend" / "app", + REPO / "frontend" / "src", +) +SKIP_PARTS = frozenset({ + "node_modules", + "__pycache__", + ".venv", + "dist", + "contract_payment", + "contract-payment", +}) +SOURCE_SUFFIXES = frozenset({".py", ".ts", ".vue", ".js", ".json", ".yml", ".yaml"}) + +# 词边界整词。函数名 list_shipping_inventory_sources、缩写约束 uq_shipping_inventory_* +# 前面还有下划线,不是独立表名,不会命中。 +PREFIX_TOKEN_RE = re.compile(r"\bshipping_(?:inventory|receipt)_[a-z0-9_]+\b") +# 29 表里不以 shipping_inventory_ / shipping_receipt_ 开头、但已改名的表。 +EXTRA_RETIRED_TABLES = ( + "shipping_rpa_profiles", + "shipping_task_inventory_rpa_attempts", + "shipping_task_inventory_links", + "shipping_temporary_inventory_sessions", + "shipping_notice_line_inventory_matches", + "shipping_notice_inventory_verifications", + "shipping_notice_inventory_verification_lines", +) +EXTRA_TABLE_RE = re.compile(r"\b(?:" + "|".join(EXTRA_RETIRED_TABLES) + r")\b") +# 无前导词边界:getShippingInventory* / listShippingInventory* / shippingInventory* 都要命中。 +CLASS_RE = re.compile(r"(?i)shippinginventory[a-z0-9_]*") +PATH_RE = re.compile(r"/api/admin/shipping-notice/inventory-") +UPLOAD_RE = re.compile(r"\boutbound_upload\b") +EXPLANATION_RE = re.compile(r"retired|legacy|废弃|退役|曾用|旧名|旧表|原表|原名|已改名") +RETIRED_CLASS_RE = re.compile( + r"\b(?:ShippingTaskInventoryLink|ShippingTaskInventoryRpaAttempt|" + r"ShippingTemporaryInventorySession|ShippingNoticeLineInventoryMatch)\b" +) + +# 只放行两个 HTTP 工具名。movement / shipment_* 不靠把模块名塞进这里。 +ALLOWED_TOKENS = frozenset({ + "ensure_inventory", + "upload_inventory_file", +}) + +ONHAND_CLASS_FILES = ( + REPO / "backend" / "app" / "models" / "shipping.py", + REPO / "backend" / "app" / "models" / "shipping_onhand_task_rpa_attempts.py", + REPO / "backend" / "app" / "models" / "shipping_temporary_onhand.py", + REPO / "backend" / "app" / "models" / "shipping_notice_line_onhand_match.py", +) + + +def _is_allowed(token: str) -> bool: + """两个 HTTP 工具名,以及 movement / shipment 履约词。""" + if token in ALLOWED_TOKENS: + return True + lowered = token.lower() + if lowered == "movement" or lowered.startswith("movement_") or "_movement" in lowered: + return True + if ( + lowered.startswith("shipment_") + or "_shipment_" in lowered + or lowered.endswith("_shipment") + or lowered == "generate_shipment_excel" + ): + return True + return False + + +def _is_explaining_comment(line: str) -> bool: + """整行是注释,并且在解释退役名,才从门禁里放过。""" + stripped = line.lstrip() + if not stripped.startswith(("#", "//", "*", "/*", " B[解析来源 日期 Invoice范围] - B --> C[按来源检查当日 receipt ready文件] + B --> C[按来源检查当日 inbound ready文件] C --> D{文件是否ready} D -->|是| H[文件校验与解析] D -->|正在抓取| E[绑定已有RPA任务] @@ -218,7 +224,7 @@ flowchart TD ### 6.1 文件准备进度阶段 1. 理解查询范围。 -2. 检查当前业务日期收料文件。 +2. 检查当前业务日期入站文件。 3. 复用文件、绑定抓取任务或触发 RPA。 4. 等待 RPA Callback。 5. 校验文件。 @@ -391,7 +397,7 @@ pending "precheck_id": "TPC-20260806-001", "status": "awaiting_confirmation", "business_date": "2026-08-06", - "eligible_receipt_date_to": "2026-08-05", + "eligible_inbound_date_to": "2026-08-05", "expires_at": "2026-08-06T09:20:00+08:00", "sources": [], "counts": { @@ -421,12 +427,12 @@ pending ## 10. 后台执行与并发 -建议一个收料抓取排程和一个自动调拨排程: +建议一个入站抓取排程和一个自动调拨排程: -- 08:00 收料文件抓取排程。 +- 08:00 入站文件抓取排程。 - 09:00 自动调拨排程。 -自动调拨排程不能假设 08:00 成功,仍调用统一 `ensure_receipt_file_ready()`。 +自动调拨排程不能假设 08:00 成功,仍调用统一 `ensure_inbound_file_ready()`。 默认并发: @@ -559,11 +565,11 @@ Excel Sheet: ```text 用户:查询今天有多少可以调拨 -AI:正在检查已选来源实例的收料文件;缺失来源会实时抓取。 +AI:正在检查已选来源实例的入站文件;缺失来源会实时抓取。 ┌─ 正在准备可调拨数据 ──────────────────────────────┐ -│ 可处理收料日期 截至 2026-08-05 │ -│ 当前阶段 准备收料Excel │ +│ 可处理异动日期 截至 2026-08-05 │ +│ 当前阶段 准备入站Excel │ │ │ │ DBS-AWSBI ✓ 复用今日08:00 ready文件 │ │ AWS-SG ◉ 未找到今日文件,RPA已领取,等待Callback│ @@ -580,7 +586,7 @@ AI:正在检查已选来源实例的收料文件;缺失来源会实时抓取 ```text ┌─ 今日调拨预检 ────────────────────────────────────┐ │ 文件内Invoice 40 │ -│ 当天收料未成熟 8 │ +│ 当天入站未成熟 8 │ │ 进入ERP预检 32 │ │ 可执行 27 │ │ 数量不一致 3 │ @@ -639,8 +645,8 @@ AI:正在检查已选来源实例的收料文件;缺失来源会实时抓取 ```text ┌─ INV-260806-019 ──────────────────────────────────┐ │ 来源实例 DBS-AWSBI 状态 数量不一致 │ -│ 文件 receipt-v20.xlsx Sheet Receipt │ -│ 原始行 128、129 收料 1,200 / ERP 1,000 │ +│ 文件 inbound-v20.xlsx Sheet Inbound │ +│ 原始行 128、129 入站 1,200 / ERP 1,000 │ │ │ │ 审计时间线 │ │ 09:01 文件解析完成 │ @@ -672,9 +678,9 @@ AI:正在检查已选来源实例的收料文件;缺失来源会实时抓取 ```text ┌─ HXOPS管理后台 ───────────────────────────────────────────────────┐ │ 调拨配置 │ -│ ● 数据来源 ┌─ 收料文件来源 ──────────────────────────────┐ │ -│ 调拨策略 │ DBS-AWSBI收料 AWS-SG收料 │ │ -│ 仓库与组织 │ 用途 receipt 用途 receipt │ │ +│ ● 数据来源 ┌─ 入站文件来源 ──────────────────────────────┐ │ +│ 调拨策略 │ DBS-AWSBI入站 AWS-SG入站 │ │ +│ 仓库与组织 │ 用途 inbound 用途 inbound │ │ │ 自动排程 │ RPA Profile HTTP Callback │ │ │ 通知设置 │ 解析方案 V3 解析方案 V3 │ │ │ │ 固定来源仓 固定来源仓 │ │ @@ -685,7 +691,7 @@ AI:正在检查已选来源实例的收料文件;缺失来源会实时抓取 └──────────────────────────────────────────────────────────────────┘ ``` -边界:发货库存与收料配置是不同来源实例;配置、锁和运行互不影响。页面不读取或回显ERP、RPA凭据。 +边界:发货库存与入站配置是不同来源实例;配置、锁和运行互不影响。页面不读取或回显ERP、RPA凭据。 ### 13.10 管理后台:调拨策略与仓库映射 @@ -701,8 +707,8 @@ AI:正在检查已选来源实例的收料文件;缺失来源会实时抓取 ┌─ 组织与仓库映射 ───────────────────────────────────────────────┐ │ 路由 ERP组织 来源实例 固定来源仓 目标HUB仓 │ -│ DBS-TRANSFER HX-CN01 DBS收料 DBS-TRANSIT 系统库存映射 │ -│ CRANE-TRANSFER HX-CN01 Crane收料 CRANE-TRANSIT 系统库存映射│ +│ DBS-TRANSFER HX-CN01 DBS入站 DBS-TRANSIT 系统库存映射 │ +│ CRANE-TRANSFER HX-CN01 Crane入站 CRANE-TRANSIT 系统库存映射│ └─────────────────────────────────────────────────────────────────┘ ``` @@ -710,7 +716,7 @@ AI:正在检查已选来源实例的收料文件;缺失来源会实时抓取 ```text ┌─ 自动排程 ──────────────────────────────────────────────────────┐ -│ 每日收料文件抓取 08:00 已启用来源实例并发2 [编辑][停用] │ +│ 每日入站文件抓取 08:00 已启用来源实例并发2 [编辑][停用] │ │ 每日自动调拨 09:00 查询并发2 / 写并发1 [编辑][停用] │ └─────────────────────────────────────────────────────────────────┘ ┌─ 通知设置 ──────────────────────────────────────────────────────┐ @@ -739,11 +745,11 @@ AI:正在检查已选来源实例的收料文件;缺失来源会实时抓取 | 路径 | 具体修改 | | --- | --- | -| `backend/app/models/shipping_inventory_config.py` | 为库存来源增加 `purpose`、任务所有者、通知人、收料解析用途和调拨启用字段;更新约束 | +| `backend/app/models/shipping_inventory_config.py` | 为库存来源增加 `purpose`、任务所有者、通知人、入站解析用途和调拨启用字段;更新约束 | | `backend/app/models/__init__.py` | 导出调拨领域模型 | -| `backend/app/api/admin/shipping_inventory.py` | 库存来源CRUD支持收料类型和调拨字段,返回配置版本 | -| `backend/app/services/shipping_notice/inventory_source_repository.py` | 运行时快照支持按purpose读取,避免发货与收料混用 | -| `frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue` | 复用现有页面增加收料来源字段,不新增管理页 | +| `backend/app/api/admin/shipping_inventory.py` | 库存来源CRUD支持入站类型和调拨字段,返回配置版本 | +| `backend/app/services/shipping_notice/inventory_source_repository.py` | 运行时快照支持按purpose读取,避免发货与入站混用 | +| `frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue` | 复用现有页面增加入站来源字段,不新增管理页 | | `frontend/src/features/admin/modules/shipping-inventory/shippingInventorySourceForm.ts` | 表单归一化、校验和脏状态比较 | | `frontend/src/features/admin/api/admin.api.ts` | 扩展来源DTO | | `docs/features/in-transit-transfer/in-transit-transfer-source-instance-mvp.html` | Chat 摘要发起、来源实例选择、文件冻结预检、异常 ERP 重查、组织→路由→Invoice 聚合确认与 Run/待处理跳转 | @@ -775,7 +781,7 @@ AI:正在检查已选来源实例的收料文件;缺失来源会实时抓取 | `backend/app/services/chat/action_types.py` | 增加调拨查询和预检Action类型 | | `backend/app/services/chat/action_schema.py` | 增加日期、来源、Invoice范围校验 | | `backend/app/services/chat/action_registry.py` | 加载调拨Handler | -| `backend/app/jobs/types.py` | 增加收料文件准备和调拨预检Job类型 | +| `backend/app/jobs/types.py` | 增加入站文件准备和调拨预检Job类型 | | `backend/app/jobs/store.py` | shipping/transfer队列可领取新Job | | `frontend/src/features/chat/types/chat.types.ts` | 增加结构化消息payload | | `frontend/src/features/chat/components/messages/ChatMessageBubble.vue` | 按message type挂载调拨卡片 | @@ -787,7 +793,7 @@ AI:正在检查已选来源实例的收料文件;缺失来源会实时抓取 | 路径 | 内容 | | --- | --- | -| `backend/app/services/in_transit_transfer/file_preparation.py` | `ensure_receipt_file_ready`和RPA绑定 | +| `backend/app/services/in_transit_transfer/file_preparation.py` | `ensure_inbound_file_ready`和RPA绑定 | | `backend/app/services/in_transit_transfer/file_parser.py` | 字段、结构、日期校验 | | `backend/app/services/in_transit_transfer/invoice_aggregator.py` | 多行汇总和原始行追溯 | | `backend/app/services/in_transit_transfer/erp_adapter.py` | SOAP查询/写入隔离;一期先由业务模块实现 | @@ -802,7 +808,7 @@ AI:正在检查已选来源实例的收料文件;缺失来源会实时抓取 | `frontend/src/features/chat/components/TransferInvoiceDetailDrawer.vue` | Invoice明细 | | 对应前后端测试 | 文件幂等、日期、解析、汇总、ERP查询、历史恢复 | -验收:缺文件时5秒内返回进度卡;并发请求只触发一次RPA;当天收料100%不查ERP;多行汇总准确率100%;任一来源实例失败不影响其他来源实例;历史会话可恢复进度;同一查询Run在历史侧栏中始终只有一条会话记录。 +验收:缺文件时5秒内返回进度卡;并发请求只触发一次RPA;当天入站100%不查ERP;多行汇总准确率100%;任一来源实例失败不影响其他来源实例;历史会话可恢复进度;同一查询Run在历史侧栏中始终只有一条会话记录。 ### Phase 2:确认和ERP调拨 @@ -846,7 +852,7 @@ AI:正在检查已选来源实例的收料文件;缺失来源会实时抓取 | 路径 | 具体修改 | | --- | --- | -| `backend/app/services/schedule/job_registry.py` | 注册收料抓取和自动调拨排程 | +| `backend/app/services/schedule/job_registry.py` | 注册入站抓取和自动调拨排程 | | `backend/app/services/schedule/job_params.py` | 来源、所有者、通知人、并发和恢复参数 | | `backend/app/services/schedule/schedule_contract.py` | 调拨排程契约 | | `backend/app/services/schedule/scheduler_service.py` | 调拨Run收尾和通知 | @@ -856,7 +862,7 @@ AI:正在检查已选来源实例的收料文件;缺失来源会实时抓取 | 路径 | 内容 | | --- | --- | -| ~~`backend/app/services/schedule/in_transit_receipt_file_job.py`~~ | 已下线(2026-09-28):文件就绪保障内建于在途自动调拨,独立排程类型删除 | +| ~~独立入站文件抓取排程 job~~ | 已下线(2026-09-28):文件就绪保障内建于在途自动调拨,独立排程类型删除(原 job 文件路径见 git 历史) | | `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 +924,7 @@ AI:正在检查已选来源实例的收料文件;缺失来源会实时抓取 | 风险 | 控制 | | --- | --- | -| 当天收料被误调拨 | T+2成熟硬门禁(可配),未成熟不查询ERP | +| 当天入站被误调拨 | T+2成熟硬门禁(可配),未成熟不查询ERP | | 历史失败被遗忘 | 自动待办池、每日复核、3/5/7天升级 | | 自动恢复误补偿 | 最新文件、ERP、幂等、映射全门禁和新Attempt | | 人工关闭滥用 | 原因必填、快照、永久审计 | @@ -940,7 +946,7 @@ AI:正在检查已选来源实例的收料文件;缺失来源会实时抓取 | 风险 | 控制 | | --- | --- | | ERP响应样例变化 | Phase 0冻结WSDL和样例 | -| 收料文件结构不稳定 | 样本测试、解析Profile版本、结构漂移阻断 | +| 入站文件结构不稳定 | 样本测试、解析Profile版本、结构漂移阻断 | | 审计在末期补做 | Phase 0先建审计,后续每节点强制接入 | | 前后端契约漂移 | DTO、契约测试、Mock数据并行开发 | | 范围膨胀到集成中心 | 明确一期不实现,ERP Adapter仅业务内隔离 | @@ -954,7 +960,7 @@ AI:正在检查已选来源实例的收料文件;缺失来源会实时抓取 1. 所有核心对话页面符合现有Chat UI,所有后台配置页面符合现有AdminLayout、库存来源和排程工作台风格。 2. 所有写操作有操作人、时间、内容、before/after快照和Hash。 3. 所有只读操作有条件、返回数、结果摘要Hash和关联上下文。 -4. 当天收料ERP查询和写入数量均为0。 +4. 当天入站ERP查询和写入数量均为0。 5. 未确认、过期确认、变化预检的ERP写入数量均为0。 6. `result_unknown`自动重试数量为0。 7. 历史可恢复项能自动进入新Attempt,旧Attempt不变。 diff --git a/docs/features/in-transit-transfer/mvp-requirements-and-prototype-review-pack.md b/docs/features/in-transit-transfer/mvp-requirements-and-prototype-review-pack.md index 81b7174f..fed2b6ba 100644 --- a/docs/features/in-transit-transfer/mvp-requirements-and-prototype-review-pack.md +++ b/docs/features/in-transit-transfer/mvp-requirements-and-prototype-review-pack.md @@ -16,7 +16,7 @@ 2. “DBS / Crane”等是否只作为来源平台,是否确认以**来源实例**作为选择、文件、排程、审计和失败隔离边界。 3. 是否确认手工调拨固定走“选择范围 → 预检 → 人工处理 ERP 异常(如需要)→ 重新查询 → 一次确认 → 后台写入”的闭环。 4. 是否确认调拨确认按“**ERP 组织 → 调拨路由 → Invoice**”三级聚合,默认不平铺大量路由或 Invoice。 -5. 是否确认数量不一致项可在当前预检页仅重新查询 ERP 库存,不重新抓 RPA、不替换冻结收料文件、不直接写 ERP。 +5. 是否确认数量不一致项可在当前预检页仅重新查询 ERP 库存,不重新抓 RPA、不替换冻结入站文件、不直接写 ERP。 6. 是否确认 `result_unknown` 必须只读隔离,禁止任何自动或手工的猜测性重试。 7. 是否确认 MVP 的边界:仓库管理人员为主;管理员配置、集成中心平台化不作为本次前台原型的交付范围。 @@ -39,7 +39,7 @@ ### 3.1 当前问题 -仓库管理人员需要依据货代收料 Excel 与 ERP 账面库存,判断 Invoice 是否可从在途仓调拨到对应 HUB 仓,并完成 ERP 建单、审核、过账。人工过程存在四类风险: +仓库管理人员需要依据货代收料报表 Excel 与 ERP 账面库存,判断 Invoice 是否可从在途仓调拨到对应 HUB 仓,并完成 ERP 建单、审核、过账。人工过程存在四类风险: - 多个来源平台持续拆分为多个实际来源实例,若按平台处理会漏选、误选或混淆来源仓。 - 预检与 ERP 写入之间 ERP 库存可能变化,数量不一致时需要先在 ERP 处理,再回来复查。 @@ -51,7 +51,7 @@ 在不建设独立集成中心的前提下,复用 HXOPS 既有 Chat、RPA、Worker、库存来源管理、企业微信与审计能力,完成: 1. 仓管可从 Chat 发起调拨意图,并清楚看到文件与预检进度。 -2. 系统按来源实例获取/消费收料文件、按 Invoice 汇总收料数量、严格匹配 ERP 账面库存。 +2. 系统按来源实例获取/消费入站文件、按 Invoice 汇总入站数量、严格匹配 ERP 账面库存。 3. 仅在用户一次明确确认后由后台 Worker 写 ERP;自动排程对满足门禁的项目可自动写入。 4. 所有动作、读取证据、下载、重查、确认、写入、关闭/恢复均留存可追溯审计。 @@ -59,7 +59,7 @@ - 管理员对来源、映射、策略、排程、通知的配置界面。 - 通用企业集成中心或让 Dify 直接持有 ERP 写权限。 -- 人工修改收料数量、仓库、ERP 组织或调拨数量。 +- 人工修改入站数量、仓库、ERP 组织或调拨数量。 - 部分数量调拨、单位换算、数量容差。 - 手工输入/搜索 Invoice 作为主工作方式。 - 多人占用锁、租约或“被谁占用”提示。 @@ -69,9 +69,9 @@ | 编号 | 规则 | 页面与系统行为 | | --- | --- | --- | | R1 | DBS、Crane 是来源平台;来源实例才是业务边界 | 页面按平台分组选择实例,例如 `DBS-AWSBI`;平台本身不能直接执行调拨 | -| R2 | 收料文件为累计全量 | 同一 Invoice 多行只汇总收料数量;保留原始 Sheet/行号证据 | -| R3 | 当天收料不可调拨 | 标记 `not_matured`,不查询 ERP、不写 ERP,也不可在当前预检中重查 | -| R4 | 数量必须严格相等 | 收料数量与 ERP 账面库存大于、小于或缺失均不可写入 | +| R2 | 入站文件(收料报表 RPA 产物)为累计全量 | 同一 Invoice 多行只汇总入站数量;保留原始 Sheet/行号证据 | +| R3 | 当天入站不可调拨 | 标记 `not_matured`,不查询 ERP、不写 ERP,也不可在当前预检中重查 | +| R4 | 数量必须严格相等 | 入站数量与 ERP 账面库存大于、小于或缺失均不可写入 | | R5 | 文件与策略必须冻结 | Run 创建后文件版本/checksum、解析映射、路由映射和策略不可替换;中途不允许重新抓 RPA | | R6 | 数量不一致允许复查 | 仓管可先在 ERP 人工处理,再在**当前预检页**仅重新查询异常 Invoice 的 ERP 库存;每次新增 Attempt | | R7 | 手工写 ERP 必须确认一次 | 用户必须先看到范围、数量、路由、单据数;点击确认后才投递 Worker | @@ -99,11 +99,11 @@ | 对话能力 | 典型用户表达/系统反馈 | MVP 行为 | | --- | --- | --- | -| 规则说明 | “为什么今天不能调拨?” | 解释当天收料、数量严格匹配、文件冻结、未知结果等规则 | +| 规则说明 | “为什么今天不能调拨?” | 解释当天入站、数量严格匹配、文件冻结、未知结果等规则 | | 状态查询 | “还有多少待处理?”、“最近自动调拨结果?” | 展示待处理数、未知数、最近 Run 摘要并提供跳转入口 | | 发起意图 | “查询昨天 DBS 的可调拨数据” | 识别为预检意图,提示进入来源实例选择页 | | 文件/预检进度 | “系统现在在做什么?” | 显示来源实例级文件准备、解析、ERP 查询、预检完成等阶段;不伪造总百分比 | -| 结果解释 | “INV-031 为什么不可调拨?” | 说明收料与 ERP 库存差异、最近 Attempt、下一步为 ERP 人工处理后复查 | +| 结果解释 | “INV-031 为什么不可调拨?” | 说明入站与 ERP 库存差异、最近 Attempt、下一步为 ERP 人工处理后复查 | | 异常引导 | “我已经在 ERP 处理好了” | 引导至当前预检页的“重新查询异常 ERP 库存”按钮 | | 安全解释 | “为什么不能重试结果未知?” | 明确 ERP 结果未确认,系统不得制造第二次写入 | @@ -167,7 +167,7 @@ Chat 首页 ### P2 来源实例选择:平台分组,实例为选择边界 ```text -┌────────────────────────── 选择收料来源实例 ──────────────────────────┐ +┌────────────────────────── 选择入站来源实例 ──────────────────────────┐ │ 搜索实例名称/编码 [全选已启用] [清空] 已选 2 个 │ │ │ │ ▼ DBS(3 个已启用) │ @@ -191,7 +191,7 @@ Chat 首页 │ Invoice 明细 [我已处理 ERP,重新查询异常库存]│ │ ☑ DBS-AWSBI | CN01 AWSBI-TRANSIT → HUB-SZ | INV-001 | 500/500 | 可执行│ │ □ DBS-AWSBI | CN01 AWSBI-TRANSIT → HUB-SZ | INV-031 | 300/280 | 不一致│ -│ □ DBS-AWSSG | 未进入路由 | INV-041 | 400/— | 当天收料│ +│ □ DBS-AWSSG | 未进入路由 | INV-041 | 400/— | 当天入站│ │ │ │ 已选 3 张 · 2 条路由 · 2,300 PCS · 预计 ERP 单据 3 张 [进入确认] │ └────────────────────────────────────────────────────────────────────────┘ @@ -244,9 +244,9 @@ Run 结果:成功 / 业务阻断 / 来源异常 / 通知状态 [固定异常 | --- | --- | --- | | S1 多来源发起 | Chat → 选择范围 → 展开 DBS/Crane → 选多个实例 → 预检 | 平台不等于来源;实例失败隔离;范围明确 | | S2 没有 Ready 文件 | 发起预检后观察来源级进度 | AI/页面必须解释 RPA/Callback 进度;不得无反馈等待 | -| S3 正常可调拨 | 预检中保留可执行项 → 进入确认 | 看到收料/ERP 等量、预计数量和路由;未确认前 ERP 写入为 0 | +| S3 正常可调拨 | 预检中保留可执行项 → 进入确认 | 看到入站/ERP 等量、预计数量和路由;未确认前 ERP 写入为 0 | | S4 数量不一致后人工处理 | 看到 `INV-031 300/280` → 去 ERP 人工处理(业务假设)→ 回预检点击重查 | 不抓 RPA、不换文件;新增 Attempt;匹配后自动入选但不自动写 ERP | -| S5 当天收料 | 查看 `not_matured` 项 | 不查 ERP、不提供重查、不允许选择 | +| S5 当天入站 | 查看 `not_matured` 项 | 不查 ERP、不提供重查、不允许选择 | | S6 多路由确认 | 进入确认 → 展开组织 → 展开一条路由 | 默认不平铺;可看清组织、来源仓、目标仓与 Invoice | | S7 写入和结果恢复 | 点击执行 → 离开/回到 Run 结果 | Worker 持续执行;结果固定、可查单号/Excel/审计 | | S8 可恢复异常 | 待处理 → 选异常 → 重查 ERP | 只读 ERP 查询;匹配后形成新的确认范围,不能直接写 ERP | @@ -275,7 +275,7 @@ stateDiagram-v2 file_pending --> prechecking prechecking --> ready_to_confirm: 数量严格匹配 prechecking --> blocked_recoverable: 数量不一致/明确技术失败 - prechecking --> not_matured: 当天收料 + prechecking --> not_matured: 当天入站 ready_to_confirm --> executing: 用户确认或自动排程 executing --> completed: ERP 成功/重复成功 executing --> blocked_recoverable: ERP 明确失败且原子回滚 @@ -302,7 +302,7 @@ stateDiagram-v2 | 操作节点 | 必须记录的业务证据 | | --- | --- | | 文件准备 | 来源实例、业务日期、文件版本、checksum、解析 Profile、Ready 时间 | -| 预检 | 收料汇总、ERP 库存、路由快照、`not_matured`/阻断原因、Attempt | +| 预检 | 入站汇总、ERP 库存、路由快照、`not_matured`/阻断原因、Attempt | | ERP 重查 | 原 Attempt、新 Attempt、查询时间、ERP 返回摘要、是否改变可执行性 | | 确认 | 操作者、选中 Invoice、数量、组织/路由、预检 Hash、有效期 | | ERP 写入 | 请求摘要、Operation ID、ERP 返回、调拨单号、重复单号或原子失败事实 | @@ -329,15 +329,15 @@ stateDiagram-v2 ### 本次首要关键风险 -**路由归属规则未冻结。** 目前可以确认“不同来源实例可能去不同 ERP 组织与 HUB 仓”,但若无法由不可变配置与 Invoice/收料数据唯一确定每个 Invoice 的实际路由,系统就无法安全计算 ERP 单据数或写入正确仓库。内部评审应确认:该风险阻塞 ERP 写入接入,但不阻塞来源选择、文件准备、只读预检、路由 DTO 与界面骨架开发。 +**路由归属规则未冻结。** 目前可以确认“不同来源实例可能去不同 ERP 组织与 HUB 仓”,但若无法由不可变配置与 Invoice/入站数据唯一确定每个 Invoice 的实际路由,系统就无法安全计算 ERP 单据数或写入正确仓库。内部评审应确认:该风险阻塞 ERP 写入接入,但不阻塞来源选择、文件准备、只读预检、路由 DTO 与界面骨架开发。 ## 14. MVP 验收口径(供评审确认) | 类别 | 可量化验收标准 | | --- | --- | | 来源范围 | 在 12+ 来源实例下,仓管可通过平台折叠和搜索选择实例;页面始终显示已选实例数 | -| 文件与成熟度 | 当天收料 ERP 查询次数为 0;Run 创建后文件版本/checksum 不可替换 | -| 数量校验 | 收料与 ERP 不严格相等时 ERP 写入次数为 0;同 Invoice 多行汇总准确 | +| 文件与成熟度 | 当天入站 ERP 查询次数为 0;Run 创建后文件版本/checksum 不可替换 | +| 数量校验 | 入站与 ERP 不严格相等时 ERP 写入次数为 0;同 Invoice 多行汇总准确 | | 复查 | 数量不一致复查仅请求 ERP 查询接口;不触发 RPA、不写 ERP;原 Attempt 永不覆盖 | | 确认 | 手工路径在无确认、确认过期、文件/映射/数量变化时 ERP 写入次数均为 0 | | 路由展示 | 每一可执行 Invoice 可追溯到组织、来源仓、目标仓;确认默认按组织聚合、按需展开路由/Invoice | diff --git a/docs/features/in-transit-transfer/mvp-source-instance-lean-ux-canvas.md b/docs/features/in-transit-transfer/mvp-source-instance-lean-ux-canvas.md index 317e67c2..45c98080 100644 --- a/docs/features/in-transit-transfer/mvp-source-instance-lean-ux-canvas.md +++ b/docs/features/in-transit-transfer/mvp-source-instance-lean-ux-canvas.md @@ -7,9 +7,9 @@ ## 0. 本轮边界与已知事实 - 平台(如 DBS、Crane)不是可执行对象;可执行、可排程、可冻结文件和可审计的最小边界是**来源实例**,例如 `DBS-AWSBI`、`DBS-AWSSG`、`CRANE-SZ`。 -- 收料文件是累计全量。手工发起时优先消费已就绪的最新有效文件;在尚未创建任务前可触发抓取,任务创建后文件版本、校验和、映射和策略均冻结。 -- 当天收料为 `not_matured`:不查询 ERP,不写 ERP。 -- 只有收料数量与 ERP 账面库存完全相等时才可调拨;手工调拨必须在写入前一次确认,自动排程的正常项可自动写入。 +- 入站文件(收料报表 RPA 产物)是累计全量。手工发起时优先消费已就绪的最新有效文件;在尚未创建任务前可触发抓取,任务创建后文件版本、校验和、映射和策略均冻结。 +- 当天入站为 `not_matured`:不查询 ERP,不写 ERP。 +- 只有入站数量与 ERP 账面库存完全相等时才可调拨;手工调拨必须在写入前一次确认,自动排程的正常项可自动写入。 - ERP 返回只有成功或失败;同 ERP 组织内 Invoice No 全局唯一。ERP 拒绝重复 Invoice 并返回原调拨单号;失败完全原子、不产生单据。 - `result_unknown` 只读隔离,不能重查、关闭、恢复或再次写入;系统不得推断 ERP 结果。 - 本 MVP 不引入多人并发锁或租约;所有实际动作仍需服务端状态校验、ERP 幂等约束及全量审计。 @@ -24,7 +24,7 @@ │ 来源实例。若把它们平铺在 Chat │ 复杂选择移入独立路由页。 │ 操作步骤和等待不确定性。 │ │ 首页,选择、预检、异常处理会随 │ - 按平台分组的来源实例选择页。│ - 可衡量:手工 Run 从发起至确认 │ │ 实例数量增长而失控,且用户无法 │ - 独立预检 / 确认 / Run 结果 │ 的完成率、异常可恢复项处理率。 │ -│ 理解每份收料文件、每次 ERP 调用 │ / 待处理页面。 │ - 可衡量:同一来源实例失败不影响 │ +│ 理解每份入站文件、每次 ERP 调用 │ / 待处理页面。 │ - 可衡量:同一来源实例失败不影响 │ │ 和异常处理分别对应什么业务边界。 │ - Chat 只负责意图、进度和摘要。│ 其他实例成功处理的比例。 │ ├──────────────────────────────────┤ ├──────────────────────────────────┤ │ 3. 目标用户 │ │ 4. 用户结果与收益 │ @@ -41,7 +41,7 @@ │ H1:若把来源实例选择移到独立页, │ 用户能否区分“平台”与“来源实例”,│ 以本原型与 5-8 位仓库管理人员 │ │ 仓管可在不拥挤 Chat 首页的前提下 │ 并完成“选择范围 → 预检 → 确认” │ 做任务走查: │ │ 完成多来源范围选择。 │ 而无需被 DBS/Crane 的历史概念 │ 1. 选 DBS-AWSBI 和 DBS-AWSSG; │ -│ │ 误导? │ 2. 识别当天收料不可调拨; │ +│ │ 误导? │ 2. 识别当天入站不可调拨; │ │ H2:若预检和确认采用独立主工作区,│ │ 3. 仅勾选可执行 Invoice 并确认; │ │ 用户能在 ERP 写入前正确说明范围、 │ 核心风险:用户把“平台”误当成 │ 4. 从待处理页批量重新查询 ERP; │ │ 预计单据数、数量与不可执行原因。 │ 单一可执行来源,导致漏选或误选, │ 5. 解释为何结果未知没有操作按钮。 │ @@ -91,7 +91,7 @@ flowchart LR 1. 在 Chat 首页不滚动、不搜索实例也能理解“范围尚未选择”与“待处理笔数”。 2. 选择页在 12+ 实例时仍可通过平台折叠、搜索和计数完成选择;不把 DBS 当成唯一来源。 -3. 预检页把 `可执行 / 数量不一致 / 当天收料` 显示为不同文字状态;当天收料不可勾选。 +3. 预检页把 `可执行 / 数量不一致 / 当天入站` 显示为不同文字状态;当天入站不可勾选。 4. 确认页始终显示已选 Invoice 数、预计调拨总数量、预计 ERP 单据数、ERP 组织和仓库。 5. 从 Run 结果和待处理返回浏览器历史时,保留对应业务页上下文;原型以 URL `page` 参数演示。 6. `result_unknown` 页面不存在任何造成第二次 ERP 写入或业务状态变更的入口。 diff --git a/docs/features/in-transit-transfer/prd.md b/docs/features/in-transit-transfer/prd.md index 2f18cddb..32da0d8f 100644 --- a/docs/features/in-transit-transfer/prd.md +++ b/docs/features/in-transit-transfer/prd.md @@ -29,7 +29,7 @@ ## 1. 执行摘要 -我们将在现有HXOPS中建设“在途仓自动调拨 Agent”,服务拥有Agent权限的仓库管理人员,解决当前需要人工获取DBS/Crane收料汇总、逐张核对ERP账面库存、人工创建审核过账调拨单,并容易遗漏历史失败Invoice的问题。用户可通过对话查询和预检,在看到范围、预计调拨总数量和预计ERP写入后确认一次执行;后台排程可每日自动处理新增及可恢复历史异常。Dify只负责意图理解,ERP写操作由HXOPS确定性业务服务和后台Worker执行,所有节点均保留操作人、时间、前后快照、Diff和Hash审计。 +我们将在现有HXOPS中建设“在途仓自动调拨 Agent”,服务拥有Agent权限的仓库管理人员,解决当前需要人工获取DBS/Crane收料报表汇总、逐张核对ERP账面库存、人工创建审核过账调拨单,并容易遗漏历史失败Invoice的问题。用户可通过对话查询和预检,在看到范围、预计调拨总数量和预计ERP写入后确认一次执行;后台排程可每日自动处理新增及可恢复历史异常。Dify只负责意图理解,ERP写操作由HXOPS确定性业务服务和后台Worker执行,所有节点均保留操作人、时间、前后快照、Diff和Hash审计。 一期优先实现安全、可恢复、可审计的最小闭环,不建设独立集成中心,不支持部分数量调拨,不允许Dify持有ERP写权限。 @@ -37,7 +37,7 @@ ### 2.1 谁遇到了问题 -主要是负责DBS、Crane在途仓到HUB仓调拨的仓库管理人员。他们需要根据货代收料数据与ERP账面库存,判断哪些Invoice可以调拨,并完成ERP新建、审核和过账。 +主要是负责DBS、Crane在途仓到HUB仓调拨的仓库管理人员。他们需要根据货代收料报表数据与ERP账面库存,判断哪些Invoice可以调拨,并完成ERP新建、审核和过账。 管理员和ERP管理员是次要参与者:前者维护来源、策略、排程和通知,后者提供ERP接口、测试组织、白名单和凭据。 @@ -45,9 +45,9 @@ 当前业务需要跨货代系统、Excel和ERP完成多个步骤: -1. 从DBS或Crane获取Invoice收料汇总。 +1. 从DBS或Crane获取Invoice收料报表汇总。 2. 按Invoice查询ERP账面库存。 -3. 判断收料数量是否完全匹配ERP库存。 +3. 判断入站数量是否完全匹配ERP库存。 4. 匹配时创建、审核、过账ERP调拨单。 5. 不匹配时整理异常Excel并通知仓库人员。 6. 次日继续处理之前失败或未完成的Invoice。 @@ -58,7 +58,7 @@ - 需要在多个系统间切换并人工核对数量。 - 无法快速判断当前处于文件抓取、ERP查询还是建单阶段。 -- 同一收料日期部分失败后,容易在后续工作日被遗忘。 +- 同一异动日期部分失败后,容易在后续工作日被遗忘。 - ERP超时、重复Invoice和结果未知场景容易被误判或重复操作。 - 出现问题时缺少统一的文件、原始行、库存、单号和操作时间线。 @@ -72,9 +72,9 @@ ### 2.5 现有证据 -- 已确认业务使用DBS、Crane的Invoice收料汇总,并按Invoice查询ERP库存。 -- 已确认同一收料日期可能只有部分Invoice调拨成功,需要防止失败项被遗忘。 -- 已确认当天收料不可能当天执行调拨。 +- 已确认业务使用DBS、Crane的Invoice收料报表汇总,并按Invoice查询ERP库存。 +- 已确认同一异动日期可能只有部分Invoice调拨成功,需要防止失败项被遗忘。 +- 已确认当天入站不可能当天执行调拨。 - 已确认ERP以Invoice No作为业务幂等键,并拒绝重复Invoice、返回原调拨单号。 - 已确认ERP一个接口原子完成新建、审核、过账,失败时不产生单据。 - 已确认后台自动执行需要企业微信汇总通知和异常Excel。 @@ -85,7 +85,7 @@ ### 3.1 主要角色:仓库管理人员 -- **职责:** 查询在途仓收料、核对库存、执行调拨、处理异常。 +- **职责:** 查询在途仓入站数据、核对库存、执行调拨、处理异常。 - **工作环境:** 日常使用HXOPS、货代系统、Excel和ERP。 - **目标:** 快速知道哪些Invoice可以安全调拨,并获得明确的执行结果。 - **痛点:** 系统切换多、人工比对容易出错、长任务无进度、失败项可能遗漏。 @@ -93,13 +93,13 @@ #### Jobs-to-be-Done -- **功能性任务:** 当收料数据可用时,准确完成所有可调拨Invoice,并识别不可执行项。 +- **功能性任务:** 当入站数据可用时,准确完成所有可调拨Invoice,并识别不可执行项。 - **情绪性任务:** 确认系统没有遗漏Invoice,也不会未经确认错误写入ERP。 - **协作性任务:** 向仓库同事提供统一、可解释、可下载的执行和异常结果。 ### 3.2 次要角色:调拨配置管理员 -- 维护收料来源、调拨策略、仓库映射、排程和通知。 +- 维护入站来源、调拨策略、仓库映射、排程和通知。 - 通过草稿、校验、发布流程让配置生效。 - 查看配置Diff、连接验证和配置审计。 - 不在页面查看ERP或RPA凭据明文。 @@ -148,13 +148,13 @@ 功能作为现有HXOPS Chat中的专用Agent提供。用户可以自然语言查询今天、指定日期、指定来源或指定Invoice的可调拨情况。 -系统先检查当前业务日期的最新Ready收料文件;缺失时实时触发来源获取,并在对话中显示来源级进度。文件完成后,系统按D+1规则过滤当天未成熟收料,汇总相同Invoice多行数量,查询ERP账面库存并生成预检结果。 +系统先检查当前业务日期的最新Ready入站文件;缺失时实时触发来源获取,并在对话中显示来源级进度。文件完成后,系统按D+1规则过滤当天未成熟入站,汇总相同Invoice多行数量,查询ERP账面库存并生成预检结果。 如果用户要求执行,系统展示可执行Invoice、预计调拨总数量和预计ERP写入数。用户点击一次“执行调拨”后,后台Worker写前重新查询ERP,并逐项调用ERP原子调拨接口。页面关闭或SSE断开不影响后台任务,用户重新进入会话可以恢复Run状态。 ### 5.2 后台自动方案 -- 08:00收料文件抓取排程。 +- 08:00入站文件抓取排程。 - 09:00自动调拨排程。 - 自动调拨仍调用统一文件准备服务,不假设08:00已成功。 - DBS、Crane在同一排程内来源级独立执行。 @@ -174,7 +174,7 @@ 复用现有库存来源和排程管理,增加: -- 收料用途的DBS/Crane来源实例。 +- 入站用途的DBS/Crane来源实例。 - 调拨策略。 - ERP组织、来源仓和目标HUB仓映射。 - 自动排程和通知配置。 @@ -187,7 +187,7 @@ → 检查当天Ready文件 → 缺失来源实时获取并展示进度 → 解析、校验、汇总Invoice -→ 过滤当天未成熟收料 +→ 过滤当天未成熟入站 → 查询ERP账面库存 → 数量匹配与预检 → 查询场景直接返回结果 @@ -211,7 +211,7 @@ | 指标 | 一期目标 | | --- | ---: | -| 当天收料产生ERP查询或写入 | 0 | +| 当天入站产生ERP查询或写入 | 0 | | 未确认、过期确认或预检变化产生ERP写入 | 0 | | 同ERP组织内重复建单 | 0 | | `result_unknown`自动重试 | 0 | @@ -285,8 +285,8 @@ **验收标准:** -- 当天收料标记`not_matured`,不查询ERP。 -- 相同Invoice多行只汇总收料数量。 +- 当天入站标记`not_matured`,不查询ERP。 +- 相同Invoice多行只汇总入站数量。 - 数量完全相等才可执行。 - 页面展示可调拨总数量和预计ERP单据数。 @@ -353,7 +353,7 @@ **验收标准:** -- DBS与Crane为独立收料来源实例。 +- DBS与Crane为独立入站来源实例。 - 配置通过草稿、校验、发布流程生效。 - 发布门禁不完整时禁止发布。 - 生产地址和凭据不以明文返回页面。 @@ -372,8 +372,8 @@ ### 7.3 关键边界与异常 -- 当天收料:仅显示未成熟,不作为错误。 -- ERP库存大于或小于收料数量:整Invoice阻断,不允许部分调拨。 +- 当天入站:仅显示未成熟,不作为错误。 +- ERP库存大于或小于入站数量:整Invoice阻断,不允许部分调拨。 - ERP业务失败:原子回滚,状态为明确失败。 - ERP超时无法确认结果:`result_unknown`,不自动重试。 - 重复Invoice且原单已审核过账:`duplicate_success`。 @@ -386,7 +386,7 @@ ### 8.1 包含 - 对话查询、文件进度、预检、确认、执行、结果和异常。 -- DBS RPA收料文件和Crane HTTP Callback收料文件。 +- 收料 RPA 抓取的 DBS 入站文件和 Crane HTTP Callback 入站文件。 - D+1成熟过滤和相同Invoice多行数量汇总。 - ERP账面库存查询和原子新建/审核/过账。 - Invoice幂等和重复成功识别。 @@ -471,7 +471,7 @@ ### 10.2 已冻结关键决策 -- 当天收料不得当天调拨。 +- 当天入站不得当天调拨。 - Invoice No全局唯一,同ERP组织内作为幂等键。 - ERP接口原子完成新建、审核、过账。 - 重复Invoice返回原调拨单号且可证明原单已审核过账。 diff --git a/docs/features/in-transit-transfer/roadmap.md b/docs/features/in-transit-transfer/roadmap.md index 9c9751b0..c452a0e2 100644 --- a/docs/features/in-transit-transfer/roadmap.md +++ b/docs/features/in-transit-transfer/roadmap.md @@ -25,7 +25,7 @@ 项目采用“先形成安全业务闭环,再完成自动化和治理,最后抽离通用集成能力”的路线: -1. **M0 契约就绪:** 冻结ERP、收料文件、领域状态、审计和测试契约,建立可并行开发的Fake与DTO。 +1. **M0 契约就绪:** 冻结ERP、入站文件、领域状态、审计和测试契约,建立可并行开发的Fake与DTO。 2. **M1 只读可用:** 用户可在现有HXOPS Chat中查询、看到文件获取进度,并得到可审计的调拨预检结果,全程不写ERP。 3. **M2 对话闭环:** 用户看到范围、预计调拨总数量和预计ERP写入后,点击一次“执行调拨”,由后台Worker安全完成ERP原子写入。 4. **M3 自动闭环:** 每日排程自动准备文件、处理新增和可恢复历史异常,并发送一次企业微信汇总通知及异常Excel。 @@ -74,9 +74,9 @@ M2不是一期最终完成,只是为了尽早验证真实业务价值的受控 - 现有Chat中的专用自动调拨Agent。 - 对话查询、文件准备进度、预检、选择、确认、执行、结果、异常和审计。 -- 已配置来源实例的 RPA / HTTP Callback 收料来源。 +- 已配置来源实例的 RPA / HTTP Callback 入站来源。 - 当前业务日期最新Ready累计全量文件。 -- D+1成熟规则、Invoice多行收料数量汇总、精确数量匹配。 +- D+1成熟规则、Invoice多行入站数量汇总、精确数量匹配。 - ERP账面库存查询及单接口原子新建、审核、过账。 - Invoice幂等、重复成功识别、结果未知隔离。 - 08:00文件获取、09:00自动调拨、历史失败恢复、3/5/7天老化机制。 @@ -105,7 +105,7 @@ M2不是一期最终完成,只是为了尽早验证真实业务价值的受控 | 阶段 | 业务成果 | 主要交付 | 退出门禁 | | --- | --- | --- | --- | | Phase 0 契约与测试底座 | 团队对业务真相和外部接口形成一致理解 | ERP/文件契约、状态机、DTO、审计模型、Fake、迁移草案 | 核心L0测试从Red到Green;ERP沙箱契约可执行 | -| Phase 1 文件与只读预检 | 仓储用户能查到“哪些可调拨、为什么” | 文件准备、D+1、汇总、ERP查询、Chat进度与预检 | 当天收料ERP调用0;缺文件5秒内反馈;来源互不阻断 | +| Phase 1 文件与只读预检 | 仓储用户能查到“哪些可调拨、为什么” | 文件准备、D+1、汇总、ERP查询、Chat进度与预检 | 当天入站ERP调用0;缺文件5秒内反馈;来源互不阻断 | | Phase 2 确认与ERP写入 | 对话发起的一次确认调拨闭环 | 确认Hash、写前复检、Worker、ERP原子写、结果卡 | 未确认/过期/变化写入0;重复建单0;单号可追溯 | | Phase 3 排程与异常闭环 | 系统每日自动处理且不会遗忘失败项 | 排程、待办池、新Attempt、老化、Excel、企微、配置发布 | 可恢复项100%重新预检;每个Run恰好1条通知 | | Phase 4 生产硬化与上线 | 满足生产安全、稳定和运维要求 | 性能、故障注入、安全、归档、指标、UAT、上线方案 | P0/P1为0;全量门禁通过;业务和ERP签字 | @@ -145,9 +145,9 @@ ERP WSDL/错误语义冻结 ### 4.2 产品与业务交付 - 业务术语表和状态定义完成评审。 -- 确认`receipt_date < business_date`才可进入ERP预检。 -- 确认相同Invoice多行只汇总收料数量,保留原始行。 -- 确认ERP数量必须与收料数量完全相等。 +- 确认`movement_date < business_date`才可进入ERP预检。 +- 确认相同Invoice多行只汇总入站数量,保留原始行。 +- 确认ERP数量必须与入站数量完全相等。 - 确认重复Invoice只有在ERP返回原单号并确认已审核过账时才为`duplicate_success`。 - 输出ERP超时/结果未知的人工核实SOP、责任人和处理时限。 @@ -155,22 +155,22 @@ ERP WSDL/错误语义冻结 | 类型 | 文件路径 | 修改内容 | | --- | --- | --- | -| 复用修改 | `backend/app/models/shipping_inventory_config.py` | 为库存来源增加收料用途、固定来源仓、调拨启用和版本化配置;发货与收料用途隔离 | +| 复用修改 | `backend/app/models/shipping_inventory_config.py` | 为库存来源增加入站用途、固定来源仓、调拨启用和版本化配置;发货与入站用途隔离 | | 复用修改 | `backend/app/models/__init__.py` | 导出调拨领域模型 | | 计划新增 | `backend/app/models/in_transit_transfer.py` | 定义Run、SourceJob、Precheck、InvoiceItem、Attempt、AuditEvent和Archive模型 | | 计划新增 | `backend/migrations/versions/_add_in_transit_transfer.py` | Alembic迁移、约束、唯一键和索引;必须验证upgrade/downgrade | | 计划新增 | `backend/app/services/in_transit_transfer/contracts.py` | 请求、响应、快照、进度和审计DTO | | 计划新增 | `backend/app/services/in_transit_transfer/status.py` | 合法状态、终态和转换门禁 | | 计划新增 | `backend/app/services/in_transit_transfer/audit.py` | before/after、Diff、Hash、actor和关联上下文 | -| 复用修改 | `backend/app/api/admin/shipping_inventory.py` | 来源CRUD支持收料用途和版本字段 | +| 复用修改 | `backend/app/api/admin/shipping_inventory.py` | 来源CRUD支持入站用途和版本字段 | | 复用修改 | `backend/app/services/admin/shipping_inventory_service.py` | 来源配置校验、激活门禁和敏感字段脱敏 | ### 4.4 前端工作包 | 类型 | 文件路径 | 修改内容 | | --- | --- | --- | -| 复用修改 | `frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue` | 复用库存来源页面,区分收料/发货用途 | -| 复用修改 | `frontend/src/features/admin/modules/shipping-inventory/shippingInventorySourceForm.ts` | 收料来源字段、校验、脏状态和版本冲突处理 | +| 复用修改 | `frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue` | 复用库存来源页面,区分入站/发货用途 | +| 复用修改 | `frontend/src/features/admin/modules/shipping-inventory/shippingInventorySourceForm.ts` | 入站来源字段、校验、脏状态和版本冲突处理 | | 复用修改 | `frontend/src/features/admin/api/admin.api.ts` | 扩展来源和配置版本DTO | | 计划新增 | 调拨稳定Fixture和Mock DTO | 供Chat卡片、管理页面和契约测试并行使用;实施时按现有Feature Module确定最终目录 | @@ -186,7 +186,7 @@ ERP WSDL/错误语义冻结 - [ ] ERP正式WSDL、查询字段、写入字段、超时、错误码和脱敏留存范围经ERP团队确认。 - [ ] Fake ERP覆盖成功、重复成功、原子业务失败、提交前超时和提交后结果未知。 -- [ ] 当天收料的ERP查询与写入调用均为0。 +- [ ] 当天入站的ERP查询与写入调用均为0。 - [ ] 非法状态转换拒绝率100%。 - [ ] 迁移upgrade/downgrade成功,模型与数据库约束一致。 - [ ] 审计before/after、Diff、Hash、actor、request_id、operation_id完整率100%。 @@ -203,7 +203,7 @@ ERP契约和结果未知SOP未关闭时,可以完成纯领域和前端Mock工 ### 5.1 阶段目标 -- 用户从现有HXOPS Chat发起查询或执行意图时,系统能准备当天最新有效收料文件。 +- 用户从现有HXOPS Chat发起查询或执行意图时,系统能准备当天最新有效入站文件。 - 当文件不存在时实时获取并持续显示进度,避免用户无反馈等待。 - 系统完成D+1过滤、Invoice汇总和ERP账面库存查询,返回结构化预检结果。 - 本阶段任何路径均不得调用ERP写接口。 @@ -226,7 +226,7 @@ ERP契约和结果未知SOP未关闭时,可以完成纯领域和前端Mock工 | 复用修改 | `backend/app/jobs/types.py`、`backend/app/jobs/store.py` | 增加文件准备和预检Job类型及领取能力 | | 计划新增 | `backend/app/services/in_transit_transfer/file_preparation.py` | 复用Ready文件、来源租约、缺失时触发RPA/Callback | | 计划新增 | `backend/app/services/in_transit_transfer/file_parser.py` | 文件Schema、日期、数量和必填列校验 | -| 计划新增 | `backend/app/services/in_transit_transfer/invoice_aggregator.py` | 同Invoice收料数量汇总和原始行追溯 | +| 计划新增 | `backend/app/services/in_transit_transfer/invoice_aggregator.py` | 同Invoice入站数量汇总和原始行追溯 | | 计划新增 | `backend/app/services/in_transit_transfer/erp_adapter.py` | 业务模块内隔离SOAP查询/写入边界;本阶段只启用查询 | | 计划新增 | `backend/app/services/in_transit_transfer/precheck_service.py` | D+1、ERP查询、数量匹配、快照和Hash | | 计划新增 | `backend/app/services/in_transit_transfer/chat_actions.py` | 调拨查询/预检Action处理 | @@ -252,7 +252,7 @@ ERP契约和结果未知SOP未关闭时,可以完成纯领域和前端Mock工 - 对话首次进度反馈不晚于5秒。 - 不显示无法解释的单一Spinner;必须显示当前来源、阶段和最近更新时间。 - 任一来源实例失败时其他来源实例继续。 -- 当天收料显示`not_matured`,不显示为ERP异常。 +- 当天入站显示`not_matured`,不显示为ERP异常。 - 查询和文件准备不会显示“执行成功”等写入语义。 - 刷新、切换会话或SSE断开后从Run投影恢复。 @@ -263,7 +263,7 @@ ERP契约和结果未知SOP未关闭时,可以完成纯领域和前端Mock工 - [ ] 缺文件后5秒内返回来源级进度。 - [ ] 任一来源实例故障不影响其他来源实例。 - [ ] 相同Invoice多行汇总准确率100%,原始行追溯完整率100%。 -- [ ] 当天收料ERP查询和写入均为0。 +- [ ] 当天入站ERP查询和写入均为0。 - [ ] 数量只有完全相等时为`executable`。 - [ ] 页面刷新和重新登录后的进行中Run恢复率100%。 - [ ] 同一查询Run在历史侧栏始终只有一条会话记录。 @@ -347,14 +347,14 @@ Phase 2完成后可以在ERP测试组织进行端到端试点。若申请小范 ### 7.1 阶段目标 -- 每日自动获取收料文件并自动处理可调拨Invoice。 +- 每日自动获取入站文件并自动处理可调拨Invoice。 - 自动发现此前失败但条件已恢复的Invoice,创建新Attempt,防止人工遗忘。 - 对不可自动决策项提供清晰证据、人工操作和老化升级。 - 完成来源、策略、映射、排程和通知的管理员配置发布闭环。 ### 7.2 自动运行规则 -- 默认08:00执行收料文件获取,09:00执行自动调拨。 +- 默认08:00执行入站文件获取,09:00执行自动调拨。 - 自动调拨始终调用统一文件准备服务,不假设08:00一定成功。 - 单个自动调拨排程可按来源实例并发处理;ERP写并发仍默认1。 - 当前来源失败不阻断其他来源。 @@ -378,11 +378,11 @@ Phase 2完成后可以在ERP测试组织进行端到端试点。若申请小范 | 类型 | 文件路径 | 修改内容 | | --- | --- | --- | -| 复用修改 | `backend/app/services/schedule/job_registry.py` | 注册收料文件和自动调拨任务类型 | +| 复用修改 | `backend/app/services/schedule/job_registry.py` | 注册入站文件和自动调拨任务类型 | | 复用修改 | `backend/app/services/schedule/job_params.py` | 来源、所有者、通知人、并发、恢复参数 | | 复用修改 | `backend/app/services/schedule/schedule_contract.py` | 调拨排程稳定契约 | | 复用修改 | `backend/app/services/schedule/scheduler_service.py` | 调拨Run收尾、通知状态和运行摘要 | -| ~~计划新增~~ 已下线(2026-09-28) | `backend/app/services/schedule/in_transit_receipt_file_job.py` | 文件准备职责内建于在途自动调拨排程 | +| ~~计划新增~~ 已下线(2026-09-28) | 独立入站文件抓取排程 job(原路径见 git 历史) | 文件准备职责内建于在途自动调拨排程 | | 计划新增 | `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 | @@ -400,7 +400,7 @@ Phase 2完成后可以在ERP测试组织进行端到端试点。若申请小范 | 计划新增 | `frontend/src/features/chat/components/messages/TransferExceptionCard.vue` | 异常证据和下一步操作 | | 计划新增 | `frontend/src/features/chat/components/TransferManualCloseDialog.vue` | 必填原因和影响范围确认 | | 计划新增 | `frontend/src/features/chat/components/TransferAuditDrawer.vue` | 业务审计时间线 | -| 复用修改 | `frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue` | 收料来源实例与发布状态 | +| 复用修改 | `frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue` | 入站来源实例与发布状态 | | 复用修改 | `frontend/src/features/admin/modules/schedules/SchedulesPage.vue` | 配置08:00/09:00任务和所有者/通知人 | | 计划新增 | `frontend/src/features/admin/modules/in-transit-transfer/` | 策略、映射、通知、校验、发布和配置审计;实施前复核现有admin模块拆分方式 | @@ -471,7 +471,7 @@ Phase 2完成后可以在ERP测试组织进行端到端试点。若申请小范 | 缺文件时首次进度反馈 | ≤5秒 | | Ready文件预检创建P95 | ≤800毫秒 | | Run投影读取P95 | ≤500毫秒 | -| 当天收料ERP查询/写入 | 0 | +| 当天入站ERP查询/写入 | 0 | | 未确认/过期/变化ERP写入 | 0 | | 同来源重复RPA触发 | 0 | | 同ERP组织重复建单 | 0 | @@ -484,7 +484,7 @@ Phase 2完成后可以在ERP测试组织进行端到端试点。若申请小范 - 来源实例 Ready复用和实时RPA获取。 - HTTP Callback正常、延迟、重复和来源不匹配。 -- 当天收料不进入ERP。 +- 当天入站不进入ERP。 - Invoice多行汇总后数量精确匹配。 - 用户取消部分可执行项并确认执行。 - 成功、重复成功、业务失败、技术失败和结果未知。 @@ -658,7 +658,7 @@ ERP SOAP / HTTP / 未来其他系统 | --- | --- | --- | --- | | Q1 | ERP正式WSDL、字段、错误码、超时和可留存脱敏字段是什么? | Phase 0退出前 | 禁止进入真实ERP写入开发 | | Q2 | ERP写超时后的人工核实SOP、责任人和完成时限是什么? | Phase 0退出前 | `result_unknown`无法安全运营 | -| Q3 | 各启用来源实例正式收料样例、Sheet、表头和结构漂移规则是否齐全? | Phase 1开始前 | 文件解析和汇总验收不可执行 | +| Q3 | 各启用来源实例正式入站样例、Sheet、表头和结构漂移规则是否齐全? | Phase 1开始前 | 文件解析和汇总验收不可执行 | | Q4 | 企业微信附件上限是否满足最大七Sheet Excel? | Phase 3开始前 | 需要切换为受控下载链接方案 | | Q5 | 自动调拨完成率正式目标和人工处理基线是多少? | Phase 4上线前 | 无法证明业务收益 | | Q6 | 所有Agent授权用户查看同权限Run的范围是否通过安全评审? | Phase 2上线前 | 可能产生跨用户数据暴露 | @@ -699,7 +699,7 @@ ERP SOAP / HTTP / 未来其他系统 - ERP错误写入数:0。 - 同ERP组织重复建单数:0。 -- 当天收料ERP查询/写入数:0。 +- 当天入站ERP查询/写入数:0。 - 未确认、过期或变化预检ERP写入数:0。 - `result_unknown`自动重试数:0。 - 历史可恢复失败下一排程重新预检率:100%。 diff --git a/docs/features/in-transit-transfer/technical.md b/docs/features/in-transit-transfer/technical.md index 51b38080..c69acafa 100644 --- a/docs/features/in-transit-transfer/technical.md +++ b/docs/features/in-transit-transfer/technical.md @@ -1,22 +1,22 @@ # 在途仓自动调拨 Agent — 运行维护手册 -> 状态:后端 Phase 0-4 已交付(领域/文件/匹配/执行/排程/恢复/通知/归档/指标),前端实施中。2026-09-23 术语重构:precheck(预检)→ match(匹配),表/列/API/状态值全量更名,未上线无兼容层。 +> 状态:后端 Phase 0-4 已交付(领域/文件/匹配/执行/排程/恢复/通知/归档/指标),前端实施中。2026-09-23 术语重构:precheck(预检)→ match(匹配),表/列/API/状态值全量更名,未上线无兼容层。2026-10-15 术语重构:单一入站单据假设改版为入站(inbound)/出站(outbound)统一、明细/单据列改用异动(`movement_*`)、解析类型 purpose 枚举改版(onhand/inbound/outbound),未上线无兼容层(见 §12)。 > 关联规格:[minimum-implementation-spec.md](./minimum-implementation-spec.md) · [TDD](./in-transit-transfer-tdd.md) · [PRD](./prd.md) · [路线图](./roadmap.md) ## 1. 架构概览 - **业务域**:`backend/app/services/in_transit_transfer/`(独立领域模块,不混入 shipping_notice 订单解析)。 -- **执行边界**:收料来源实例(如 DBS-AWSBI / DBS-AWSSG / CRANE-SZ);DBS/Crane 仅分组。 +- **执行边界**:出入站来源实例(如 DBS-AWSBI / DBS-AWSSG / CRANE-SZ);DBS/Crane 仅分组。 - **真相源**:`TransferRun` / `TransferMatching` / `TransferInvoiceItem` / `TransferAttempt`(表:`transfer_*`,迁移 `it1a2b3c4d5e`;术语重构迁移 `rn1a2b3c4d5e6`)。 - **外部系统访问唯一出口**:`capability_client.py`(`CapabilityClient.query_stock / create_transfer`,域能力恰读/写两个)。查询经集成连接器 CapabilityGateway 按 `in_transit_transfer.query_inventory` 能力批量调用(按 external_org 分组、targets = 料号+拨出库位+拨出批号 元组,`external_org` 取自仓库映射 `external_organization_code`)。写路径 `create_transfer` 为**单据级委派顺序引擎**(2026-09-24 ERP 建单写路径接线,管理端配置配方见 §10):入参为域单六键,绑定 `steps_json` 表达一对多有序接口配方(先写 ERP 中间表 → 触发 WS),网关顺序引擎按四条规则执行(①resume 跳过全部非末步 / ②非末步失败即中止 / ③末步映射+六态分类 / ④末步超时 result_unknown),六态结果映射回域;每步落 IntegrationCall 审计(同 operation_id 串联 + step_index 定位)。集成连接器 `database` 连接器类型(`db_kind` 四库:oracle / mysql / sqlserver / postgresql)支撑 SQL 直连接口(`:name` 绑定变量、bulk 行集、`identifiers` 白名单标识符替换);写可用性由绑定发布门禁承担(每步接口已发布 + 客户端启用,缺一 `BindingNotFoundError` fail-closed)——早期「外部契约冻结前写 fail-closed(`ExternalNotFrozenError`)」门禁已随接线移除。 -- **路由归属(拨出库位)**:拨出库位取仓库映射行的「在途仓编码」(`shipping_inventory_external_mappings.in_transit_warehouse_code`,保存端必填)。映射行按库存源 `warehouse_resolution_mode` 选择(`DefaultRouteResolver`):`inventory_match`(按库存行匹配)源优先按「库存源 + 收料文件仓库列(`warehouse_code`)== 货代仓库」精确匹配,匹配不到回退「库存源 + 货代仓库为空」的默认映射行(空库位兜底);`fixed`(指定仓库)源仅一条启用映射直接取用。收料文件仓库列原值随明细落库于 `transfer_invoice_items.receipt_warehouse_code`,执行/重试期以它重解析路由,路由变化 fail-closed 阻断(`TRANSFER.ROUTE_NOT_RESOLVED` / `matching_expired`)。运维注意:来源的 movement 解析方案须把收料文件「仓库」表头映射到领域字段 `warehouse_code`,未映射时该值为空、inventory_match 源将直接走空库位兜底。 -- **调拨业务类型(2026-09-22)**:`transfer_type.py` 定义三类——`in_transit_to_hub`(在途仓至HUB仓,一期唯一开放)、`hub_repair_out`(HUB仓维修出,占位)、`hub_to_hub`(HUB仓间调拨,占位)。类型决定匹配收料数据范围:类型 1 仅纳入 INVOICE 前缀 `HOM/HOX/WTP`(大小写不敏感)的单,范围外单与收料日期过滤同语义静默排除;类型 2 规则已冻结(ODM ID=`HoxinRMA`)待收料文件解析层支持 `odm_id` 字段后启用,类型 3 规则待业务定义;占位类型被调用时 fail-closed(`TRANSFER.TRANSFER_TYPE_NOT_SUPPORTED`)。类型随 Run 落库(`transfer_runs.transfer_type`,迁移 `tt3d4e5f6a7b`)并写入 `TransferMatching.scope_json`(含范围规则说明)参与匹配 Hash;前端来源选择卡顶部选择(类型 2/3 禁用展示「即将上线」),异步匹配 Job 从 scope_json 回读类型保证口径一致。 +- **路由归属(拨出库位)**:拨出库位取仓库映射行的「在途仓编码」(`shipping_inventory_external_mappings.in_transit_warehouse_code`,保存端必填)。映射行按库存源 `warehouse_resolution_mode` 选择(`DefaultRouteResolver`):`inventory_match`(按库存行匹配)源优先按「库存源 + 入站文件仓库列(`warehouse_code`)== 货代仓库」精确匹配,匹配不到回退「库存源 + 货代仓库为空」的默认映射行(空库位兜底);`fixed`(指定仓库)源仅一条启用映射直接取用。入站文件仓库列原值随明细落库于 `transfer_invoice_items.movement_warehouse_code`,执行/重试期以它重解析路由,路由变化 fail-closed 阻断(`TRANSFER.ROUTE_NOT_RESOLVED` / `matching_expired`)。运维注意:来源的 movement 解析方案须把入站文件「仓库」表头映射到领域字段 `warehouse_code`,未映射时该值为空、inventory_match 源将直接走空库位兜底。 +- **调拨业务类型(2026-10-14 配置化,取代 2026-09-22 代码枚举)**:调拨类型来自平台配置(表 `transfer_type_configs`,管理端「在途调拨类型」页维护),代码不再枚举类型——类型决定匹配数据范围(范围规则引擎)、仓库取值(仓库定义)与字段转换(如批号前缀替换)。`transfer_runs.transfer_type` CHECK 约束已放开,类型合法性由配置表校验;`transfer_type` 在匹配创建**必填**(缺省/未配置/停用 fail-closed)。配置为空时前端空态 + 匹配 fail-closed(「暂无可用调拨类型」是设计行为,见 §11)。类型、范围规则与转换规则随匹配快照进 `scope_json` 参与匹配 Hash。历史:原三类型枚举(`in_transit_to_hub` 唯一开放 / `hub_repair_out`、`hub_to_hub` 占位「即将上线」)已整体退役,无兼容层。完整模型与上线 SOP 见 §11。 - **异步**:`transfer` 队列(`worker_in_transit_transfer.py`)消费匹配/执行 Run/执行 Item 三类 Job。 -- **排程**:`in-transit-receipt-file`(08:00)与 `in-transit-transfer`(09:00)platform job(`schedule/job_registry.py`)。 +- **排程**:`in-transit-transfer`(建议 09:00 前)platform job(`schedule/job_registry.py`);当日入站文件缺失时该 job 自动触发收料 RPA 抓取(历史独立 `in-transit-receipt-file` job 已并入,注册表中不再单列)。 ## 2. 数据库 -- 迁移链:`it1a2b3c4d5e_add_in_transit_transfer.py`(down_revision=`hw6x7y8z9a0b`);后续 `it2c3d4e5f6a7_add_in_transit_warehouse_code.py` 为 `transfer_invoice_items` 追加 `receipt_warehouse_code`(收料仓库匹配键);`tt3d4e5f6a7b_add_transfer_runs_transfer_type.py` 为 `transfer_runs` 追加 `transfer_type`(调拨业务类型,带检查约束);`rn1a2b3c4d5e6_rename_transfer_precheck_to_match.py`(down_revision=`43a8179cdd88`)为术语重构迁移——表 `transfer_prechecks`→`transfer_matchings`、列 `precheck_no/precheck_hash/precheck_id`→`matching_no/matching_hash/matching_id`、状态值 `prechecking`→`matching`(13 状态中仅此一个更名)、约束/索引同步改名,未上线直改无兼容层。 +- 迁移链:`it1a2b3c4d5e_add_in_transit_transfer.py`(down_revision=`hw6x7y8z9a0b`);后续 `it2c3d4e5f6a7_add_in_transit_warehouse_code.py` 为 `transfer_invoice_items` 追加 `movement_warehouse_code`(入站仓库匹配键,2026-10-15 随明细列更名);`tt3d4e5f6a7b_add_transfer_runs_transfer_type.py` 为 `transfer_runs` 追加 `transfer_type`(调拨业务类型,带检查约束);`rn1a2b3c4d5e6_rename_transfer_precheck_to_match.py`(down_revision=`43a8179cdd88`)为术语重构迁移——表 `transfer_prechecks`→`transfer_matchings`、列 `precheck_no/precheck_hash/precheck_id`→`matching_no/matching_hash/matching_id`、状态值 `prechecking`→`matching`(13 状态中仅此一个更名)、约束/索引同步改名,未上线直改无兼容层;2026-10-15 改版迁移 `tt14a5f6a7b8c9_inbound_rename_and_ledger_key.py`(明细/单据列更名 `movement_*`、`record_kind` 值迁移 inbound/outbound、异动档自然键扩为 8 成分)与 `tt15b6a7b8c9d0_parsing_purpose_onhand_inbound_outbound.py`(解析规则 purpose CHECK 重建为 onhand/inbound/outbound + 值迁移);2026-10-21 迁移 `tt21c8d9e0f1a2_ledger_external_doc_line_natural_key.py`(异动档新增外部单号/外部项次两列并入自然键,约束 8→10 成分),均带 downgrade(见 §12)。 - 部署:`cd backend && flask db upgrade`(PostgreSQL)。回滚:`flask db downgrade <上一revision>`。 - 表:transfer_runs / transfer_source_jobs / transfer_matchings / transfer_invoice_items / transfer_attempts / transfer_audit_events / transfer_archives。 - 审计表只追加(ORM 门禁 + 前端禁止删除);大对象归档 MinIO(transfer_archives 记录 provider/bucket/key/sha256)。 @@ -27,12 +27,11 @@ | --- | --- | --- | | `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_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 目录(复用收料链路) | @@ -48,52 +47,55 @@ | 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,2026-09-29 与待处理池/匹配卡视图统一为同一口径;行含 item_id/checked_at/stale/file_current),勾选后 POST `/items/execute` 按行生成调拨单 | -| GET | `/matchings/{id}` | 按 scope 实时视图恢复匹配进度(行含 `item_id`/`checked_at`/`stale`/`file_current`/`external_org`(执行建单五元组首键,2026-10-12 起),counts 实时聚合) | -| 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(下载留审计) | +| POST | `/matchings` | 创建/复用一次调拨匹配(只读,不写 ERP;body `source_codes` 与 `transfer_type` **均必填**(2026-10-14 类型配置化:缺类型/未配置/停用 → 422 稳定错误码);可选 `business_date`/`movement_date_from`/`movement_date_to`(2026-10-15 更名,约束的是明细异动日期);响应含 matching_id/hash/计数/来源进度) | +| GET | `/items/executable` | 可调拨明细:全局 ready_to_execute 行队列(业务稳定排序=异动日期→数据源→Invoice→created_at,2026-09-29 与待处理池/匹配卡视图统一为同一口径;行含 item_id/checked_at/stale/file_current/transfer_type),勾选后 POST `/items/execute` 按行生成调拨单。2026-10-22 起表格展示出生匹配的调拨类型 | +| GET | `/matchings/{id}` | 恢复匹配进度与明细(2026-10-14 出生翻转后=**匹配自有出生行视图**:行由匹配创建时圈档生成且创建即绑定,counts 按自有行实时聚合;行含 `item_id`/`checked_at`/`stale`/`file_current`/`external_org`(执行建单五元组首键,2026-10-12 起)) | +| POST | `/matchings/{no}/items/requery` | 批量重查 ERP 库存——2026-10-14 起圈行口径=**对档对账**(匹配自有 items 与当前档按快照规则重圈对账:缺行补建/证据变刷新重置待查/档记录被替换→失效隔离);body 可选 `invoice_nos` 限定范围;库存查询按组织批量(2026-09-29:每组织一次 `query_stock`,N 行=N 组织内 1 次调用,行级评估/Attempt/审计保持单行粒度) | +| POST | `/sources/inbound-files` | 按选中来源打包下载各自最新归档入站文件 zip(下载留审计;2026-10-15 路由更名) | | GET | `/runs/{run_no}` | Run 结果(`orders` 调拨单清单=进度=结果,逐单八键/行六键含 reason;+ 按 ERP 单号聚合 external_documents + 未落单异常 exceptions) | | POST | `/runs/{run_no}/cancel` | 请求停止剩余任务(原因必填) | | POST | `/items/{id}/retry` | 人工重试(external_recheck,新 Attempt) | | 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`(按收料日期过滤,仅作用列表;2026-09-29 由 created_at 切换)/ `page`/`page_size`(默认 20 上限 100);分组计数恒全量(GROUP BY status 不受筛选影响),列表按 收料日期→数据源→拨出/拨入库位 升序分页(2026-09-29 与池子/结果卡统一),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`;单行隔离;2026-09-29 起库存查询按组织批量——每组织一次 `query_stock`,不再逐行单查外部系统) | +| POST | `/items/batch-requery` | 待处理异常「重查库存」(body `item_ids`;单行隔离;2026-09-29 起库存查询按组织批量——每组织一次 `query_stock`,不再逐行单查外部系统)。2026-10-22 起界面不再另放「恢复」按钮 | | 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}/inbound-files` | 入站来源文件 zip(下载留审计;2026-10-15 路由更名,zip 名 `inbound-files-*.zip`) | | GET | `/runs/{run_no}/external-inventory` | 匹配冻结 ERP 库存表 csv(下载留审计) | | GET | `/metrics` | 调拨运营指标(成功率/失败类型/待处理老化/通知失败) | -| 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) | -| POST | `/sources/retry-rpa-batch` | 批量来源收料重试(body `source_codes`;2026-10-09 起多来源合并写**一个** batch trigger 文件——Worker 单次浏览器会话按 profile 分组串行导出,替代逐来源 N 个 trigger/N 次开浏览器;逐来源分层与 fail-closed 语义同单来源端点,单源配置缺失跳过并记录不阻断整批,响应 `triggered`+逐源 `results`) | -| GET | `/backlog` | 待处理异常列表(可恢复/已关闭/结果未知 + 老化等级;查看留审计) | +| 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) | +| POST | `/sources/{source_code}/reparse` | 重解析当前最新可用归档(body `record_kind`,缺省 inbound;不接受 file_id;不触发 RPA)。成功 200,`ok/file_status/file_id/inserted/updated/skipped/sealed_skipped`。无文件 422 `TRANSFER.CURRENT_REPARSE_NO_FILE`。无已发布规则 422 `TRANSFER.CURRENT_REPARSE_NO_PROFILE`,不标 parse_failed。结构失败 200 `ok: false` 且文件为 `parse_failed`。其他异常 200 `ok: false`,不标 parse_failed。只重放当天最新一份,不删已有档行。 | +| POST | `/sources/retry-rpa-batch` | 批量来源入站重试(body `source_codes`;2026-10-09 起多来源合并写**一个** batch trigger 文件——Worker 单次浏览器会话按 profile 分组串行导出,替代逐来源 N 个 trigger/N 次开浏览器;逐来源分层与 fail-closed 语义同单来源端点,单源配置缺失跳过并记录不阻断整批,响应 `triggered`+逐源 `results`) | +| GET | `/backlog` | 待处理异常列表(可恢复/已关闭/结果未知 + 老化等级;查看留审计)。行含 transfer_type(出生匹配快照);2026-10-22 起表格展示调拨类型 | | GET | `/backlog/summary` | 待处理异常汇总(含 3/5/7 天老化分级) | +| GET | `/backlog/pending-match` | 待匹配桶清单(已落档但尚无有效 items 的出入站记录,§11.7;2026-10-22 起按来源、记录类型、外部单号合计 `quantity`,不再返回 `external_line_no`) | -> 已删除路由:`/prechecks`、`/prechecks/{id}` 等 precheck 路由全量下线,`/items/batch-resume` 随恢复处理改版删除,均无兼容层。 +> 已删除路由:`/prechecks`、`/prechecks/{id}` 等 precheck 路由全量下线,`/items/batch-resume` 随恢复处理改版删除,`/backlog/pending-match/reparse-preview` 与 `/backlog/pending-match/reparse` 于 2026-10-22 下线(会重放保留期内全部归档),均无兼容层。 权限:admin 或持有 `in_transit_transfer` Agent 权限;无权限 403。 -### 4.1 行归属与执行语义(2026-09-23 修订:行不迁移;术语 precheck→match 全量更名) +### 4.1 行归属与执行语义(2026-09-23 修订;**2026-10-14 行归属机制被 §11 出生翻转取代,本节保留作历史口径**) -- **主叙事**:库存匹配(动作,首页「库存匹配」卡发起)→ 可调拨清单(匹配结果的实时视图,勾选)→ 生成调拨单(按行执行);匹配不上的行进入待恢复异常(恢复处理=行级重查)。 -- **行不迁移(行归属与匹配解耦)**:`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`(库存查询时刻=「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-10-14 更新,取代下行「行不迁移」)**:`TransferInvoiceItem` 在**匹配创建时**从库存异动档按类型范围规则圈定生成(`matching_id`/`ledger_record_id` 出生即绑定),证据落地只写档不写行;本节下行「文件落地同步行 matching_id=NULL / 原地刷新 / scope 实时圈行」均为已退役的 2026-09-25 机制,权威口径见 §11。 +- **行不迁移(2026-09-25 机制,已退役留档)**:`TransferInvoiceItem.matching_id` 仅记录首次评估建行时的匹配(2026-09-25 起文件落地同步行 `matching_id` 为 NULL)。后续对同一 scope 的重复匹配/重查对既有行**原地刷新**(不迁移 `matching_id`),并刷新 `updated_at`;终态行不迁移、不复活。 +- **匹配 = 评估留痕**:匹配记录(表 `transfer_matchings`,单号 `matching_no` 前缀 `MTG-` 由 `_generate_no` 生成)固化 scope(来源 / 异动日期区间 / 调拨类型)、counts、入站文件快照与 `matching_hash` 作为**评估留痕**;hash 与 `expires_at` **不拦截执行**(仅展示)。【2026-10-14 更新】匹配卡与 `GET /matchings/{id}` 改为**自有出生行视图**(不再按 scope 重新圈行);行级装饰语义保留:`checked_at`(库存查询时刻=「inventory_checked_at」,2026-09-29 起仅匹配评估/重查/写前复查刷新)/ `stale`(新鲜度,时钟=inventory_checked_at,阈值 `IN_TRANSIT_TRANSFER_INVENTORY_STALE_TTL_SECONDS` 默认 24h)/ `file_current`(文件版本对账,改锚档记录版本戳,§11.8),counts 按自有行实时聚合。 - **执行 = 按行 + 执行门禁(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);2026-09-28 起收料文件按非全量导出对待(存续原则:缺席≠删除),缺席行只换版本戳保留状态,不再产生 `blocked_file_removed`;该结果码仅为历史残留数据的防御识别,真实删除走待处理池人工关闭;匹配卡主视图不渲染历史 `blocked_file_removed` 行(折叠提示计数+引导去待处理池「标记无需继续处理」,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`(不整批失败) | + | ④ 写前路由复查(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`;2026-10-14 起证据对齐兜底 `align_scope_rows` 已随出生翻转删除——对档对账兜底,见 §11.6)**原地刷新 + 续新鲜度**,不创建匹配、不迁移行,单行隔离(单行门禁/路由失败不影响其余行);结果同时报出已可执行、仍阻断、失败。ERP 事实修正后重查通过即回到可执行。按组重建范围匹配的 `POST /items/batch-resume` 与 `resume_service` 已删除,无兼容层。2026-10-22 起界面不再并列「恢复」。 ## 5. 部署 @@ -117,7 +119,7 @@ cd backend && flask db upgrade ### 6.1 批量库存查询对账结论(2026-09-23) - **现象**:对话侧库存答复为 0,与 ERP 账套内真实库存(30/40/36)不一致,触发批量查询对账排查。 -- **根因**:收料仓库映射行曾指向**错误的 ERP 组织账套 TGHX**;2026-09-23 00:52 修正为 TGHX1 后重查得到真实库存 30/40/36。关键证据来自 `integration_calls` 落库:call_id 12/13(TGHX 账套)仅返回 2 条 Record 且 `img10=0`;call_id 163(TGHX1 账套)返回 30/40/36——查询链路本身无丢数/改数,差异完全由账套路由错误造成。 +- **根因**:入站仓库映射行曾指向**错误的 ERP 组织账套 TGHX**;2026-09-23 00:52 修正为 TGHX1 后重查得到真实库存 30/40/36。关键证据来自 `integration_calls` 落库:call_id 12/13(TGHX 账套)仅返回 2 条 Record 且 `img10=0`;call_id 163(TGHX1 账套)返回 30/40/36——查询链路本身无丢数/改数,差异完全由账套路由错误造成。 - **WTP26060612**:在 TGHX1 亦真实查无,属真实业务答复,非缺陷。 - **顺带修复**:`integration_connector/mapping.py` 记录扇出(fan-out)在嵌套形态下丢行的潜在缺陷已修复(该嵌套形态尚未在生产数据中观测到,属防御性修复)。 - **待确认清单(移交 ERP/业务)**: @@ -130,43 +132,46 @@ cd backend && flask db upgrade - **列锚点**:`img_file`(库存资料明细档,数据库 hxjm)官方字典——键=img01 料件编号 / img02 仓库编号 / img04 批号,值=stock_quantity(img10 库存数量)+ stock_unit(img09 库存单位,**ERP 侧确认恒非空 → 能力出参必填**;2026-09-24 起为调拨行交易单位 unit 的**唯一来源**——单据字段只取 ERP,货代文件单位列禁用于门禁与写入:命中库存但 ERP 未给单位 → 行级 `blocked_missing_unit`,此时路由已解析、拨出/拨入仓库已落列);img03 库位刻意不进键(调拨按仓库+批号粒度,同键多库位行由 `StockQueryResult.lookup` 累加),img11/img12=No Use 永不取数。 - **命名原则**:能力契约用库存中性命名(`warehouse_code`/`stock_quantity`),调拨方向语义(拨出/拨入)归 movement 契约(`from_warehouse`/`to_warehouse`),翻译发生在仓库映射/绑定层。 - **同窗切换**:能力 Schema(`capabilities.py`)与绑定 `param_mapping_json`(`img02='{warehouse_code}'`)、接口定义 `response_mapping_json`(warehouse_code/stock_quantity/stock_unit 键)已一次性对齐;错窗会导致全部行 inventory_not_found。 -- **批号键为外部形态**:img04 发查询前经 `movement_contract.external_lot_no()` 派生(WTP→HOW,见 §6.4),行上落库保持 WMS 文件原形态。 +- **批号键为外部形态**:img04 发查询前按**类型配置的转换规则**派生(2026-10-14 起由 `field_transforms` 引擎按匹配快照规则执行,WTP→HOW 为「在途仓至HUB仓」的手工配置项,见 §11.4;原 `movement_contract.external_lot_no()` 硬编码已退役),行与档落库保持 WMS 文件原形态。 ### 6.3 三层管道与门禁(2026-09-25 定稿) -> 在途调拨从「点匹配时解析收料文件」改为「**文件落地即同步**」三层管道:证据轴(收料文件 → 待办行)与账面轴(待办行 → ERP 库存核对)分离,执行门禁随之定稿。本节为当前权威口径;与本文其他段落的历史表述冲突处以本节为准。 +> 在途调拨从「点匹配时解析入站文件」改为「**文件落地即同步**」三层管道:证据轴(入站文件 → 库存异动档)与账面轴(待办行 → ERP 库存核对)分离,执行门禁随之定稿。本节为当前权威口径;与本文其他段落的历史表述冲突处以本节为准。 -**证据轴(文件落地 → 待办行,主链路)** +**证据轴(文件落地 → 库存异动档;2026-10-14 起落档不落行,权威口径见 §11)** -- 收料 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 一致直通零解析开销**;来源级隔离(单来源解析失败只标该来源,不炸整批)。 +> 下述「插入/刷新/存续/封存」幂等语义平移到 `transfer_movement_ledger`(自然键幂等五分类,§11.3);文中「待查行/重置回待查」的 items 表述为 2026-09-25 机制留档——items 现改由匹配创建时从档圈定出生。 + +- 收料 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`(2026-10-14 已删除)**:匹配/重查的文件兜底重解析入口随出生翻转退役——匹配与重查改为**对档对账**(档是外部记录唯一镜像,落地同步失败/迟到由「待匹配」桶可见性兜底,人工重匹配即可;不再对文件静默重解析)。 **账面轴(待办行 → ERP 库存核对)** -- 匹配 = 证据对齐 → 成熟过滤/路由分组 → **按组织批量查库存**(`query_inventory` 能力)→ 严格数量比对落位;文件解析已上移证据轴,匹配不再解析收料文件。 -- **worker 写前库存复查 `_recheck_stock_for_document`**(TTL 门禁退役后的写前安全最后防线):`create_transfer` 前按组织批量重查一次账面,按「收料数量 == 账面」严格相等再裁——查无 → `blocked_inventory_not_found`(账面按 0 留痕)、数量不等 → `blocked_quantity_mismatch`,均携带最新账面数量原位落行并移出本单(fail-closed 不写 ERP;全行漂移 → 单 `business_failed/stock_drifted`)。**仅全量重跑路径执行**:final_only/result_unknown 续跑单不复查——单可能已在 ERP 建成、只触发末步,此时任何阻断都是假失败。复查自身查询失败不新造失败模式(行原样放行,交给写路径既有错误语义兜底)。 +- 匹配 = 证据对齐 → 未来日期阻断/路由分组 → **按组织批量查库存**(`query_inventory` 能力)→ 严格数量比对落位;文件解析已上移证据轴,匹配不再解析入站文件。【T−2 成熟封顶 2026-10-21】T−2 之前的数据全部成熟(简化成熟边界,不回退 2026-10-16 退役决策、无成熟行级状态):匹配圈档只圈 `movement_date ≤ T−2`(`date_policy.eligible_movement_date_to`),T−1/当天未成熟行留在档内待成熟后自然进圈;异动日期范围入参截止同样不得晚于 T−2(`TRANSFER.MOVEMENT_DATE_RANGE_INVALID`),与前端选择器上限(默认=上限=T−2)同口径。 +- **worker 写前库存复查 `_recheck_stock_for_document`**(TTL 门禁退役后的写前安全最后防线):`create_transfer` 前按组织批量重查一次账面,按「入站数量 == 账面」严格相等再裁——查无 → `blocked_inventory_not_found`(账面按 0 留痕)、数量不等 → `blocked_quantity_mismatch`,均携带最新账面数量原位落行并移出本单(fail-closed 不写 ERP;全行漂移 → 单 `business_failed/stock_drifted`)。**仅全量重跑路径执行**:final_only/result_unknown 续跑单不复查——单可能已在 ERP 建成、只触发末步,此时任何阻断都是假失败。复查自身查询失败不新造失败模式(行原样放行,交给写路径既有错误语义兜底)。 - **「库存数据已过期」为纯展示提示**:`IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS` 降为 stale 徽标判定阈值(默认 600s),超时行仅亮「库存数据已过期,请重查」徽标引导重查,不拦截任何动作。 **门禁终态(2026-09-25)** -- 执行 = **存在可执行**(API 前置校验,`TRANSFER.EXECUTE_ITEMS_INVALID`)+ **文件版本对账**(API 400 `TRANSFER.FILE_CHANGED` / worker 侧整 Run 落败 `file_changed`,双侧 fail-closed)+ **worker 写前库存复查**(仅全量重跑路径)+ 写前路由复查(漂移行 `matching_expired`,既有语义)。 -- **执行不自动对齐**:执行路径不触发 `align_scope_rows`——行版本戳 ≠ 最新文件 sha 时直接 fail-closed 拒绝,由人工重新匹配/重查刷新,不静默改写执行范围。 -- **`TRANSFER.ITEMS_STALE` 退役**:行级新鲜度 TTL 门禁(API/worker 双侧,`updated_at` 超阈值 → 整批/整 Run 拒绝)整体删除——匹配 10 分钟后必被拒是 2026-09-24 事故的死锁根因;TTL 降级为 stale 徽标展示阈值(见上),防错由文件版本对账 + 写前库存复查承担。 +- 执行 = **存在可执行**(API 前置校验,`TRANSFER.EXECUTE_ITEMS_INVALID`;含所属匹配未取消的防御性双保险)+ **worker 写前库存复查**(仅全量重跑路径)+ 写前路由复查(漂移行 `matching_expired`,既有语义)。 +- **【2026-10-22 退役】文件版本对账门禁**(原 API 400 `TRANSFER.FILE_CHANGED` / worker 侧整 Run 落败 `file_changed`):入站抓取是**部分导出**——新文件不含旧行 ≠ 旧行失效/已处理,按「行评估 sha vs 最新文件 sha」对账会把大量未处理行错误卡死(557 行积压实测)。证据漂移的防护下沉两层:①行级「文件已更新」徽标(`file_current=false`,仅提示不拦截,引导重查/重新匹配);②worker 写前库存复查——按实时 ERP 账面严格相等核对,数量/批号漂移的行在写前被**行级阻断**,不会错写 ERP(ERP 过账自身的可用量管控再兜一层)。 +- **执行不自动对齐**(口径不变):执行路径不触发兜底对齐(`align_scope_rows` 已删除)——证据漂移不再阻断执行,也不静默改写执行范围;漂移行由写前复查行级拦截,人工重查/重新匹配刷新。 +- **`TRANSFER.ITEMS_STALE` 退役**:行级新鲜度 TTL 门禁(API/worker 双侧,`updated_at` 超阈值 → 整批/整 Run 拒绝)整体删除——匹配 10 分钟后必被拒是 2026-09-24 事故的死锁根因;TTL 降级为 stale 徽标展示阈值(见上)。 **待查行契约** - 待查态在 13 状态冻结契约内表达:`status='matching'` + `result_code='pending_stock_check'`,禁用新状态值。 -- `transfer_invoice_items.matching_id` 放开非空(迁移 `tt1a2b3c4d5e6f`)——落地同步行尚无匹配归属(NULL 行不受 `uq_transfer_invoice_items_matching_grain` 唯一约束保护);同步行幂等去重由应用层按(source, invoice, material, receipt_date)四元组负责;匹配/重查动作仍不迁移行归属(§4.1 语义不变)。 +- `transfer_invoice_items.matching_id` 放开非空(迁移 `tt1a2b3c4d5e6f`)——落地同步行尚无匹配归属(NULL 行不受 `uq_transfer_invoice_items_matching_grain` 唯一约束保护);同步行幂等去重由应用层按(source, invoice, material, movement_date)四元组负责(2026-10-15 随明细列更名);匹配/重查动作仍不迁移行归属(§4.1 语义不变)。 **RPA 回调模块独立化建议(缓办另立项)** -- 收料 RPA 为多模块共享基础设施(调拨证据同步、发货通知等均消费其回调),回调归档逻辑目前内联于 shipping_notice 的 `receipt_report_storage`。建议后续独立成「收料回调」模块,以「文件落地事件 + 订阅」方式服务各业务模块,消除跨域惰性导入;现桥模式(异常隔离 + 自行 commit)已满足正确性,此项缓办、另立项处理。 +- 收料 RPA 为多模块共享基础设施(调拨证据同步、发货通知等均消费其回调),回调归档逻辑目前内联于 shipping_notice 的 `receipt_report_storage`。建议后续独立成「收料 RPA 回调」模块,以「文件落地事件 + 订阅」方式服务各业务模块,消除跨域惰性导入;现桥模式(异常隔离 + 自行 commit)已满足正确性,此项缓办、另立项处理。 -### 6.4 批号外部形态派生 WTP→HOW(2026-09-25 缺陷修复,未 commit) +### 6.4 批号外部形态派生 WTP→HOW(2026-09-25 缺陷修复;2026-10-14 起规则配置化) -- **规则**:WMS 文件批号(WTP 前缀)与 ERP 账面批号(HOW 前缀)存在确定性命名差。唯一实现 = `movement_contract.external_lot_no()`:WTP 前缀大小写不敏感替换为 HOW、余串逐字保留;非 WTP 恒等(HOX 批号两侧同形)。前端展示镜像 `transferBatch.ts deriveBatchNo`(拨出/拨入批号列),改动须双侧同步。 -- **转换边界(唯一转换点,代码已强制)**:匹配组查询 targets 与回查(`matching_service`)、重查(`retry_service`)、worker 写前复查(`execution_service._recheck_stock_for_document`,targets 与 lookup 同形)、单行聚合键与下传批号(`_build_order_lines`,聚合前派生——ERP 行粒度=外部批号身份,同 ERP 批次不得因 WMS 形态差异拆行)、单投影 join 键(`serializers.serialize_order`,与聚合键同形防品名/原因 lookup miss)。行上落库保持文件原形态(证据原则:raw_lines 对账/审计复算以文件为准);匹配 Hash 快照不含批号,派生不破坏 Hash 复算。 +- **规则**:WMS 文件批号(WTP 前缀)与 ERP 账面批号(HOW 前缀)存在确定性命名差。**2026-10-14 起唯一实现 = 类型配置的转换规则**(`field_transforms` 引擎 `prefix_replace`:前缀大小写不敏感替换、余串逐字保留;非配置前缀恒等),随匹配快照进 `scope_json`,在途匹配口径不被中途改配置扰动;`movement_contract.external_lot_no()` 硬编码已删除(movement_contract 仅留退役沿革注释)。WTP→HOW 现为「在途仓至HUB仓」类型的手工配置项(上线 SOP §11)。前端展示镜像 `transferBatch.ts deriveBatchNo`(拨出/拨入批号列)已同源规则驱动,改动须双侧同步。 +- **转换边界(唯一转换点,代码已强制)**:匹配库存查询 targets 与回查、重试/重查 targets、worker 写前复查(targets 与 lookup 同形)、票行聚合键与下传批号、单投影 join 键、前端展示镜像。行与档落库保持文件原形态(证据原则:raw_lines 对账/审计复算以文件为准);匹配 Hash 快照不含批号,派生不破坏 Hash 复算。 - **缺陷背景**:修复前查询/下传用 WMS 原形态直查 ERP → 全部 WTP 批号行假阴性 `blocked_inventory_not_found`(生产实证 13 行;HOW 形态复核实证 HOW26062302 实有 200 件、HOW26071505 实有 100 件)。§6.1 中「WTP26060612 真实查无」结论按 HOW 形态复核后维持(HOW26060612 确无账面),同批其余批号的旧结论以此为准重估。 - **回滚口径**:纯函数无配置/无迁移,回退 = 回滚代码版本。 @@ -188,14 +193,14 @@ cd backend && flask db upgrade - 前端:`cd frontend; npm run test:unit -- src/features/chat; npm run build` - 端到端场景清单(前端实施后落 Playwright/Vitest 契约):人工执行主路径、自动排程、异常恢复、刷新恢复、权限越权、ERP 沙箱真实单据(创建/审核/过账/作废)。 - 本期功能验收项(2026-09-24 ERP 建单写路径,配置见 §10): - - **五元组建单**:按五元组(external_org / source_code / 收料日期 / 拨出库位 / 拨入库位,全 .strip() 规范化)聚合明细建一张单,单号 `HX--OR-*`;同组失败单复用单号/时间戳全量重跑、result_unknown/executing 单阻断新行(group_ticket_unresolved)。 + - **五元组建单**:按五元组(external_org / source_code / 异动日期 / 拨出库位 / 拨入库位,全 .strip() 规范化)聚合明细建一张单,单号 `HX--OR-*`;同组失败单复用单号/时间戳全量重跑、result_unknown/executing 单阻断新行(group_ticket_unresolved)。 - **预计 ERP 单据数口径(2026-10-12 修正)**:匹配摘要 `estimated_external_write_count` = 可执行行按同款五元组去重后的组数(同组多行合并一张,原「=可执行行数」口径高估);匹配卡上该数(计数卡=全部可执行行、生成按钮旁=勾选可执行行,随勾选联动)由前端按行上 `external_org` 实时分组计算,历史快照中旧口径持久值不再上屏。 - **融合卡**:`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)。 - - **执行看板区块**(2026-09-29 由「已执行调拨单」改名):`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。 +- 上线门禁:P0/P1 缺陷 0;越权写 403 100%;当天入站 ERP 调用 0;审计 Hash 复算一致率 100%;Secret 明文暴露 0。 ## 10. ERP 建单连接器配置(2026-09-24 固化) @@ -342,3 +347,94 @@ cd backend && flask db upgrade ### 10.8 SOP 红线(D11,唯一双单路径) **`result_unknown` 单禁止人工关闭后重建**——人工关闭 + 重建是唯一双单路径。唯一正确动作 = **重新触发**(复用原单 doc_no/submit_timestamp 只触发末步:ERP 按同时间戳幂等处理 0 行并原样返回原单号)或 ERP 查单后人工标记。关闭出口(D18)仅对 business_failed/technical_failed 开放(关闭调拨单≠ERP 无单,关前须人工确认);result_unknown 行无关闭入口。 + +## 11. 调拨类型配置化与库存异动档(2026-10-14) + +> 定位:调拨类型从代码枚举改为**平台配置**(管理端「在途调拨类型」页维护,零代码新增调拨场景);建立**库存异动档** `transfer_movement_ledger` 作为外部系统入站/出站记录的唯一平台镜像;匹配明细(items)改为**匹配创建时从档圈定出生**。设计规格与决策记录:[设计规格(2026-10-14)](../../superpowers/specs/2026-10-14-transfer-type-config-and-movement-ledger-design.md) · [ADR 0001](../../adr/0001-movement-ledger-and-item-birth-flip.md) · [ADR 0002](../../adr/0002-transfer-type-configuration.md) · 术语见 [GLOSSARY.md](../../../GLOSSARY.md)。 + +### 11.1 类型配置模型(`transfer_type_configs`,迁移 `tt10a1b2c3d4e`) + +四块配置:**①基本信息**(`code` snake_case 创建后不可变;`names_json` 四语言名称 zh-CN 必填、缺失回落 zh-CN→en;`enabled` 只有停用没有删除;`sort_order`)**②范围规则** `scope_rules_json`(§11.2)**③仓库定义** `warehouse_config_json`(§11.3)**④字段转换规则** `transform_rules_json`(§11.4)。配套迁移 drop `transfer_runs.transfer_type` 的 CHECK 约束(类型合法性由配置表校验);不做种子数据(D8)。API:`GET/POST/PUT /api/admin/in-transit-transfer/transfer-types`(平台管理员;重复 code/改 code → 422 `*_CODE_EXISTS/*_CODE_IMMUTABLE`,更新目标不存在 404)与 `GET /api/in-transit-transfer/transfer-types`(Agent 权限,enabled 最小暴露 `{code, names, sort_order, transform_rules}`,chat 类型选择卡数据源)。配置为空时前端空态 + 匹配 fail-closed——「暂无可用调拨类型」即上线 SOP 漏了建类型。 + +### 11.2 范围规则引擎(`scope_rules.py`) + +- **规则模型**:`{field, match, values[]}`,`match ∈ {prefix, equals, contains, in}`;**规则间 AND、规则内多值 OR**;空规则=不限(管理页默认要求至少一条,显式确认才可豁免)。 +- **字段白名单(18 字段,封闭可扩展)**:`source_code, doc_no, warehouse_code, storage_code, lot_no, movement_date, record_kind, in_out_flag, order_type, odm_id, odm_name, carton_id, pallet_id, material_code, doc_nature, movement_type, reason_code, partner_code`。 +- **双形态求值(同一编译器,杜绝谓词漂移)**:内存谓词 `evaluate_scope`(测试/小数据)+ SQL 编译 `apply_scope_filters`(prefix→`UPPER(col) LIKE 'X%'`;equals→集合等值 upper.in_;contains/in 同理)。匹配创建圈档与重查对账共用。 +- **圈定固定条件**:`record_kind ∈ record_kinds_of(类型范围规则)`(无 `record_kind` 规则时入站与出站都圈;2026-10-15 起枚举值为 inbound/outbound)+ `source_code IN (所选来源)` + `movement_date BETWEEN 异动日期范围` + 未封存(`transfer_executed=false`)+ 未被有效 items 占用(D17,§11.6)。 +- **快照**:范围规则 + 转换规则 + 类型/来源/日期序列化进 `scope_json` 参与匹配 hash;hash 一律从快照内容计算。 + +### 11.3 仓库定义与路由(`warehouse_config_json`) + +- 拨出/拨入两角色各自 `mode=mapped`(沿用来源实例映射档 `DefaultRouteResolver`)/ `fixed`(类型固定 `warehouse_code`;`external_org` 非空时**覆盖映射档法人**,为空沿用映射档解析)。 +- 四场景配方:在途仓至HUB=双 mapped;维修出/调拨出=from mapped / to fixed;调拨入=from fixed / to mapped。管理页保存 fixed 时校验映射档存在同编码(**提示不硬拦**);运行期解析失败照旧 fail-closed(`ROUTE_NOT_RESOLVED`)。行上 from/to 落列与五元组建单分组逻辑不变——类型只改变解析器取值来源。 + +### 11.4 字段转换规则(`field_transforms.py`) + +- 一期 `field ∈ {lot_no}`、`op ∈ {prefix_replace}`(前缀大小写不敏感替换、余串逐字保留;如 WTP→HOW);多规则按序链式,类型未配置=恒等。**行与档始终保存原值**(证据原则)。 +- **六个生效边界**(取代已删除的 `movement_contract.external_lot_no()` 硬编码):①匹配库存查询 targets/回查 ②重试/重查 targets/回查 ③worker 写前库存复查 ④票行聚合键与下传批号 ⑤单投影 join 键/展示 ⑥前端 `transferBatch.ts deriveBatchNo` 展示镜像(规则随 `GET /transfer-types` 下发驱动)。匹配 hash 不含批号,规则变更不影响存量 hash。 + +### 11.5 库存异动档(`transfer_movement_ledger`,迁移 `tt11b2c3d4e5f`) + +- **自然键唯一索引**:`(source_code, record_kind, doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no, external_doc_no, external_line_no)`——2026-10-15 由 6 成分扩为 8 成分(追加箱号 `carton_id`、批号 `lot_no`;迁移 `tt14a5f6a7b8c9` 重建 `uq_transfer_movement_ledger_natural_key`),真实文件行身份「单据+行+箱/批」不再塌缩(三份实测文件扩键后塌缩归零,`ledger_natural_key_collapse` 审计退化为纯保险);2026-10-21 再扩为 **10 成分**(追加外部单号 `external_doc_no`、外部项次 `external_line_no`,对应 CRANE/Lognet 出站报告 WMS Order #/行号;迁移 `tt21c8d9e0f1a2` 重建约束)——外部单据身份作为档幂等主键管控,同一外部单号+项次的重复落档/证据更新收敛到同一档行;可空成分 NOT NULL + default ''(防 PG NULL 逃逸)。字段组:单据标识 / 外部单据身份 / 物料与数量 / 仓储与日期 / 业务属性(D13 新增 `order_type/odm_id/odm_name/carton_id/pallet_id` + 出站预留列 `doc_nature/movement_type/reason_code/source_ref_no/partner_code/remark`)/ 平台溯源(`source_file_id` FK ON DELETE SET NULL——文件清理后档记录必须留存)/ 平台回写。配套口径:movement 契约字段目录扩至 20 字段(追加 `external_doc_no/external_line_no`,解析 Profile 可映射、缺列放行空值入键);解析层料号空行静默跳过(不管控、不进异动表,2026-10-21 CRANE/Lognet 出站报告说明行实测)。 +- **落地幂等五语义**(`evidence_sync` 一次解析、写档不写明细):①自然键不存在→插入 ②同文件 sha 未变→幂等跳过 ③证据变化→原行更新业务镜像列+换溯源 ④文件缺席→保留不删(收料 RPA 非全量导出,缺席≠删除)⑤已执行封存行(`transfer_executed=true`)永不更新永不复活。 +- **record_kind 声明 + 交叉校验(D14)**:`record_kind` 由文件种类声明写入(权威),与数据列 `in_out_flag` 交叉校验,矛盾即解析错位——打审计事件 `ledger_cross_check_failed`,记录照常落档。 +- **`movement_date` 非空才落档(2026-10-15 起,D1)**:`ledger_sync` 行级前置过滤——异动日期为空的行计入 `date_skipped` 分类、不落档(无异动日期 = 未发生异动;入站未完成行、出站 Cancelled/Executing 行自动排除);圈档/待匹配桶的日期条件恒排除 NULL(纵深防御)。 +- **档级封存(防二次调拨)**:票据执行成功落 `executed_doc_no` 时回写关联档记录 `transfer_executed=true + executed_doc_no`;匹配圈档与首页队列恒排除已封存记录。 + +### 11.6 items 出生翻转与 D17 圈档互斥(迁移 `tt12c3d4e5f6a7`) + +- **出生翻转(ADR 0001)**:`transfer_invoice_items` 退化为纯匹配执行记录——匹配创建时从档按类型范围规则圈定生成(`matching_id`/`ledger_record_id` 出生即绑定,业务字段取档原值、路由解析落 from/to);证据落地只写档不写行;重查 `requery_items` 弃 items SQL 圈行(`scope_item_query` 退役),改**对档对账**(同一编译器、同一快照规则):档有行无→补建、档证据变→刷新证据并重置待查、档记录被新版本替换→items 失效隔离(`blocked_file_removed` 语义)。 +- **D17 圈档互斥**:一条档记录一生只生成一次 items 绑定——匹配创建圈档排除「已被有效 items 占用」的档记录(存在所属匹配未取消、行未被失效隔离的 item 引用即占用)。取消匹配(items→cancelled)释放占用,记录可被后续匹配重圈;人工关闭/成功终态不释放(前者=业务裁定不拨,后者=档级封存)。重查只对账本匹配自有 items,不受此规则影响。取消按 `matching_id` 圈定名下 ready 未建单行退役(出生行 `run_id=None`,按 run_id 圈行恒不命中)。 + +### 11.7 首页待办看板「待匹配」桶(D16) + +- 四队列卡数据源改为**档 + 最近执行状态联查**。新增「待匹配」桶:**已落档但尚无有效 items**(从未被匹配圈中)的外部记录在此可见——点击展开只读清单;**不可勾选执行**(未做库存核对)。【2026-10-21 首页拆数】待匹配计数与清单不再按调拨类型范围收窄:固定条件仍是未封存、异动日期非空、未被占用、movement_date ≤ T−2,出入站都收。启用类型范围并集改记为 `matchable_count`,显示在「匹配可调拨库存」卡上。清单上段是这段并集,带「去匹配」;下段是其余已落档,只读。选类型建匹配时仍只圈该类型罩得住的行。数字时机:文件落地→待匹配涨;点匹配→圈中记录离开;停用类型只减少可匹配数。【2026-10-22 清单收口】清单按来源 + 记录类型 + 外部单号合并,数量为该单各项次数量之和,不再返回、不再展示外部项次。没有外部单号的档行仍逐行展示。单号、料号、品名、异动日期只在组内一致时显示。首页「待匹配」计数等于整桶合并后的行数,「当前启用类型可匹配」等于清单上段「当前可匹配」的行数。【2026-10-22 首页 SQL 下推】以上口径全部不变,实现改 SQL 聚合:待匹配/可匹配计数=合并键 GROUP BY 计数(`_count_pending_match_groups`);清单分页=合并键计数 + row_number 组首行锚点 OFFSET/LIMIT,只召回本页组的档行再合并(分页单位仍是外部单);行桶汇总(三态计数/老化分级)单条查询取 (status, 最近 Attempt 时刻) 轻量元组。禁止再整段装载档行/池实体后内存切片(千行级池上 /summary 曾 33s)。 + +### 11.8 `file_current` 门禁改锚 + +- 文件版本对账锚点从 item 自身版本戳改为**其档记录的 `file_version`**:`item.ledger_record.file_sha256 == 来源最新可用文件 sha` 即当前;档记录无变化即当前(档幂等跳过不换戳,行不再需要落地侧续戳)。行新鲜度 stale 徽标(`inventory_checked_at` 时钟)机制不变。 + +### 11.9 上线 SOP(发布说明引用) + +> 前提(D15):目标环境**无存量调拨数据**(transfer_runs/matchings/items 均为空,业务方 2026-10-14 确认)。若发现与前提不符,**停止升级**并联系设计方补回填方案(items 四元组挂档 + 终态回写封存),不得带数据直切。 + +1. 部署含迁移的版本(`flask db upgrade`,单 head:`b7a2b2155155 → tt10a1b2c3d4e → tt11b2c3d4e5f → tt12c3d4e5f6a7`)。 +2. 管理端「在途调拨类型」创建「在途仓至HUB仓」:code=`in_transit_to_hub`,范围规则=`doc_no prefix [HOM, HOX, WTP]`,仓库定义=from/to 均 mapped,转换规则=`lot_no prefix_replace WTP→HOW`,启用。 +3. 验证:入站文件落地 → 首页「待匹配」计数上涨;chat 选类型建匹配 → 记录进入可调拨明细 → 抽一单核对 ERP 单号与批号转换。 +4. 出现「暂无可用调拨类型」即 SOP 第 2 步遗漏(fail-closed 是设计行为)。 + +**明确不做(YAGNI)**:出站解析/RPA、维修出/调拨出入执行链路、类型删除(只有停用)、按来源实例细分仓库、规则重叠硬拦截、转换规则反向(ERP→外部)。 + +## 12. 入站/出站统一改版:幂等修复、解析类型枚举与清空并重解析(2026-10-15) + +> 定位:模块原按单一入站单据假设设计,现改为**入站/出站统一**(record_kind=inbound/outbound),修复异动档幂等(自然键扩维 + 异动日期落档过滤),解析规则 purpose 枚举改版(onhand/inbound/outbound),新增待匹配桶「清空并重新解析」。设计规格(含旧名→新名全量对照表):[设计规格(2026-10-15)](../../superpowers/specs/2026-10-15-inbound-outbound-idempotency-rename-design.md)。D6 一次到位:不留旧路由/旧错误码/旧枚举值兼容层(未上线,无存量调用方)。 + +### 12.1 术语与命名改版(单一入站假设 → 入站/出站统一) + +旧命名引用只存在于设计规格对照表与 git 历史,本节按新口径记录改版结果: + +- **record_kind 值**:枚举值改版为 `inbound`(入站)/ `outbound`(出站)(迁移 tt14 值迁移;范围规则若以 record_kind 圈定须用新值)。 +- **明细/单据列(方向中立,用 movement)**:`transfer_invoice_items` 的异动日期/异动数量/异动仓库列(`movement_date/movement_quantity/movement_warehouse_code`)与 `transfer_documents.movement_date` 由原入站单据列 RENAME 而来;随行的匹配创建参数 `movement_date_from/to`、序列化键与 Excel 表头同步。表名 `transfer_invoice_items` 与字段 `invoice_no` 本轮不动(单独立项评估)。 +- **服务文件改名(3)**:入站文件门、入站回调桥、入站触发服务三个服务更名为 `inbound_file_gate/inbound_callback_bridge/inbound_trigger_service`;核心类/函数同步 `InboundFileRepository`、`ParsedMovementRow`、`parse_movement_rows`、常量 `RECORD_KIND_INBOUND/RECORD_KIND_OUTBOUND`。 +- **API 路由(2)**:来源入站文件打包下载(`POST /sources/inbound-files`)与 Run 入站文件下载(`GET /runs/{run_no}/inbound-files`)两条路由改为 `inbound-files`(§4 表已更新)。 +- **错误码**:入站未成熟、异动日期区间非法、RPA 入站回调/配置系列、`SHIPPING.INBOUND_FILE_NOT_FOUND` 等错误码统一 inbound 口径(四语言 errors.json 键名+值同步);审计事件入站文件下载同理。改版前后对照见设计规格 §4.1。 +- **交界保留(不改名)**:shipping_notice 收料报表域 `ShippingReceiptReport*` 全套、RPA 跨进程契约(`shipping_receipt_rpa.v1`、`FREIGHT_RPA_RECEIPT_*`、`FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR`)术语保留——**入站证据 = 收料报表 RPA 产物**;域内消费点(`deps.py`/`movement_file_repository.py`/`inbound_file_gate.py`/`source_file_status.py`)已加交界注释。 +- **排程 job_params 键保留**:`receipt_from/to_offset_days` 为持久化配置兼容的有意保留(内部变量已 movement_date_from/to),下轮清扫勿动。 + +### 12.2 解析类型 purpose 枚举(onhand/inbound/outbound) + +- `ShippingInventoryParsingProfile.purpose` CHECK 重建为 `('onhand','inbound','outbound')`(迁移 tt15,值迁移 inventory→onhand、movement→inbound,均带 downgrade);语义:onhand=库存文件、inbound=入站文件、outbound=出站文件(出站证据链路本期不存在,outbound 规则可配置但无数据来源,fail-closed 天然安全)。 +- 发布校验 `purpose != 'inbound'` 跳过订单 Schema 契约;收料配置绑定校验 `_validate_inbound_profile_binding` 只认 inbound(422 `SHIPPING.INBOUND_PROFILE_INVALID`);运行期取数门禁同口径。 +- **退役守卫补查(缺陷修复)**:`inventory_parsing_profile.retire` 原只查库存源绑定即放行退役——现补查 `ShippingReceiptReportConfig.parsing_profile_id`,任一绑定存在即 409 `SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED`(防入站解析链静默失去规则)。 + +### 12.3 待匹配桶「清空并重新解析」(D7,2026-10-22 下线) + +2026-10-22 起,待匹配界面和 `GET/POST /backlog/pending-match/reparse*` 已移除。该入口重放保留期内全部归档,一次执行可以把历史行整批灌进待匹配。重解析只保留来源卡 `POST /sources/{source_code}/reparse`:当天最新一份可用归档,不删行,同一文件再解析按 sha 跳过。下面保留原机制说明,供理解已经落进档的历史行;不要把接口挂回去。 + +动机:解析规则(模板)修改后,待匹配桶存量档行仍是旧映射产物;「清空重建」避开 sha 幂等原地更新与键漂移重复行两个硬障碍——桶数据 100% 可由 MinIO 归档文件重建,清空不是破坏性操作,是「从证据重建」。 + +- **API**:`GET /backlog/pending-match/reparse-preview?source_code=`(预检:可重建归档文件清单/份数、将用规则 code+version、将清除行数、证据缺失保留行数)+ `POST /backlog/pending-match/reparse`(执行,body `{source_code}`;鉴权沿用相邻 backlog 端点)。 +- **执行(单事务,service 提交)**:①取该来源可重建归档文件(未清理 + 未过保留期;显式绕过当日门禁的维护路径,与运行期 fail-closed 取数分开实现)②**先全量重解析入内存**——任一文件解析失败整体中止 422 `TRANSFER.REPARSE_PARSE_FAILED`、一行不删 ③删除「可重建、未封存(`transfer_executed=false`)、未被有效 items 占用」的 inbound 档行,证据缺失行保留并列报 ④按归档时间序调 `sync_ledger_rows` 重落(当前绑定模板、8 成分键、movement_date 过滤自动生效)⑤commit + 审计 `TRANSFER_PENDING_MATCH_REPARSED`(操作人/来源/文件清单/规则版本/前后计数)。 +- **解析复用**:从 `evidence_sync.sync_source_rows` 抽出「归档字节→档行」纯函数,运行期落档与重建路径共用单一解析口径,杜绝两套解析漂移;并发安全由删除+重落同事务(PG READ COMMITTED 原子切换)承担。 +- **前端**:待匹配清单按来源只读展示,2026-10-22 起按外部单号合计数量,不展示外部项次,也不再提供清空重解析。解析规则修改后的重放走来源卡「重新解析」(仅当天最新归档)。 diff --git a/docs/features/sample-admission-check/README.md b/docs/features/sample-admission-check/README.md new file mode 100644 index 00000000..580da687 --- /dev/null +++ b/docs/features/sample-admission-check/README.md @@ -0,0 +1,9 @@ +# 供应商送样承认检核 + +| 文档 | 读者 | 路径 | +| --- | --- | --- | +| **需求评审稿** | 品质、调用方(SRM)、研发、测试 | [需求评审.md](需求评审.md) | + +状态:2026-10-22 评审稿 v0.3,已按承认书样本修订,并合并三轮追问结论(第一期主场景 SRM 直连调用、品质工作台复核状态机、接口契约、验收基准)。待确认项见评审稿第 8 节(O1–O13)。未开发,不代表功能清单中的已有能力。 + +样本:17 份承认书存于仓库外 `D:\Workspace\Docs\和信精密\202610\供应商送样承认`(供应商资料不入 git)。期望结论全部为「合格」,阴性验收用例按评审稿 D39 准备。 diff --git a/docs/features/sample-admission-check/需求评审.md b/docs/features/sample-admission-check/需求评审.md new file mode 100644 index 00000000..9b86bc2e --- /dev/null +++ b/docs/features/sample-admission-check/需求评审.md @@ -0,0 +1,485 @@ +# 供应商送样承认检核 — 需求评审稿 + +| 项目 | 说明 | +|------|------| +| 文档版本 | v0.3 评审稿。合并 2026-10-22 追问三轮结论:第一期主场景定为 SRM 直连调用、品质在工作台复核(含确认状态机)、接口契约(业务单号透传、调用方类别交叉校验、工作簿与单文件双入口)、上传与保留限制、试运行开关、验收基准(17 份样本期望全为合格 + 阴性用例来源)。新增待确认 O11–O13 | +| 日期 | 2026-10-22 | +| 状态 | 供需求评审。已确认项可以据此拆验收;标为待确认的项没有当作已决定 | +| 读者 | 品质 / 供应商承认业务、调用方(SRM)、研发、测试 | +| 实现状态 | 未开发。本文不代表功能清单里的已有能力 | +| 样本位置 | 17 份承认书存于仓库外 `D:\Workspace\Docs\和信精密\202610\供应商送样承认`(供应商资料不入 git)。文中引用的样本(生久、沃顿、凯仕特等)均指该目录 | + +评审时请先看 [第 8 节 待确认清单](#8-待确认清单)。清单清空之前,不把对应条目写进验收。 + +--- + +## 1. 背景与目标 + +供应商在送样承认中提交一份相对固定、但页签名和附件形式会变的承认书(Excel 工作簿)。承认书按页签放入图纸、尺寸报告、第三方 RoHS、材质证明、信赖性测试、MSDS、UL 卡等资料。页签里可能是图片,也可能是嵌入文件。业务需要根据材料类别判断哪些页签必须有资料,并根据图纸 Notes 里的材质判断 RoHS、材质证明、MSDS 要有几份、分别覆盖哪一种材质。合格则返回合格信息;不合格则返回原因。读不准、对不上的情形单独返回,不写成供应商不合格。 + +业务目标流程(第一期主场景据此展开): + +1. ERP 发起 SRM 送样申请。 +2. 供应商在 SRM 送样单上传承认书附件。 +3. SRM 调用本能力异步检核,把结论回复到送样单。 +4. 品质人员在 HXOPS 工作台复核(重点处理待复核,可对任何结论改判)。 +5. 品质确认 OK 后进入承认流程。OA 触发本期不做,只留事件口子(见 O13)。 + +第一期主要流量来自 SRM 直连调用;工作台直传是补充入口,用于人工补检与非 SRM 场景。两个入口走同一套判定。 + +本期要同时满足两件事: + +1. 只上传文件就能检核,不依赖 SRM 登录态或 SRM 数据。 +2. 外部系统可以单独把文件交给本能力并取回结论。外部系统自己更新自己的状态。本能力不写 SRM。 + +已有检核页面本期不改。RoHS、MSDS 等单份资料在本期以新模块接入。 + +设计取文档处理里已经走通的分层,供两套部署方案共用: + +- 先把工作簿、PDF、图片解析成统一文档模型(页、文本块、表格、嵌入文件)。同类做法见 Docling(统一文档模型,约 6.9 万星)、MinerU(版面与 OCR)。 +- 再按资料类型抽取,抽取结果带原文位置。模型不直接给合格结论。 +- 必填页签、份数、栏位是否命中,由可配置规则判定。低置信和缺少证据的结果进入待复核。同类做法见 Unstructured 的「先切分、再按类型处理」,以及 Azure Document Intelligence、Google Document AI 的置信度进人审。 + +--- + +## 2. 已确认决定 + +| 编号 | 决定 | +|------|------| +| D1 | 调用方上传一个 xls 或 xlsx 承认书即可检核,不读 SRM。样本以这两种格式为主 | +| D2 | 标准资料类型按页签名归类,不按页签先后。同一类型可以有多张页签(如多张全尺寸报告),先归到同一种资料。全尺寸一张算不算齐、要不要对上模穴数,见 O8,未确认前不据此判合格或不合格。槽内有嵌入对象时检对象;没有对象、只有图片时检图片 | +| D3 | 材料类别只读「供应商送样承认记录表」上的类别勾选,不读名为「封面」的页签。业务规则是必须且只能勾一项。调用方传入的类别仅用于交叉校验(D44),不替代勾选 | +| D4 | 料号、版本、供应商、环保等级、研发签核、确认人不抽取、不回传、不参与合格判定 | +| D5 | 结论四态:合格、不合格、待复核、技术失败。待复核和技术失败都不是供应商不合格 | +| D6 | 本期新模块同时支持整本承认书,以及单独上传一种资料。单份资料覆盖:图纸、全尺寸报告、第三方 RoHS、材质证明/物性表、信赖性测试、MSDS、UL 卡 | +| D7 | 单份资料只跑该资料类型自己的检核项。按类别查必填页签、按材质数份数,只在整本承认书上做 | +| D8 | 必填矩阵做成配置。`✓` 必填,`---` 不要求,`/` 不适用(缺了不判不合格)。页签名与矩阵表头可以不一致,靠别名归类 | +| D9 | 附图矩阵作为第一版种子数据,上线后可改配置,不改代码 | +| D10 | 材质证明/物性表、MSDS 按归一后的材质名称覆盖,不按文件顺序。一种需要覆盖的材质至少要有一份报告点名它。RoHS 页签另见 D23,不按「一种材质一份文件」结案。一份报告能否同时覆盖多种材质,见 O3 | +| D11 | 金属、陶瓷同时免除 RoHS2.0 和卤素。豁免只命中已配置词表里的材质名。FE、铁、不锈钢、蓝锌等具体名称尚未确认,见 O10。未进词表的名称不得自动豁免。材质读不准时,这一条待复核 | +| D12 | 材质拆分的方向:先定位图纸备注(含「材质」「表面处理」),再由模型按固定结构列出材质,每一项带回原文片段;别名表把不同写法收成同一材质。同一材质的多个零件合并成一项。模型不判合格 | +| D13 | Notes 文本和页签里的文件都不保证顺序。对应关系不按第几条对第几个文件。插入对象旁边的材质文字只是线索;只有标签或文件名、没有读到正文里的检验结果,不算已通过 | +| D14 | 结果只返回给调用方。不写 SRM。运行记录留在本能力内,供追溯 | +| D15 | 外部系统以后通过 MCP 取结果,本期不把 MCP 列入验收。本期至少提供上传文件并取回结论的 HTTP 调用 | +| D16 | 配置放在新模块管理页:类别矩阵、页签别名、豁免材质、材质别名、每种资料的检核项。改配置只影响新运行;已完成运行保留当时的配置快照 | +| D17 | 结果带回读到的类别,调用方能看懂这份承认书按哪一类在检 | +| D18 | 部署做两套方案,见第 6 节。选哪套待确认 | +| D19 | 第一阶段调用节奏大概率是异步。是否最终采用异步,待确认 | +| D20 | 单元格里的模板提示(「××插入处」、图纸截屏说明)和「NA」不算资料已提供。全尺寸报告用实测行、模穴张数还是 Alert 来判,见 O8、O9,未确认前不写入验收 | +| D21 | 「封面」「目录」「其他」「和信和泰厂内测试报告」不进入类别必填矩阵。这些页签空着,不按矩阵判供应商不合格 | +| D22 | 判定使用管理页里的矩阵。承认书里复印的矩阵、目录里的 √ / NA,都不能放宽或加严必填项 | +| D23 | RoHS 页签同时放第三方 RoHS 报告和卤素报告,一个页签里可以有多份 PDF。两类可以在同一个 PDF 里,也可以分成多个文件。每份都要读出材质、报告种类和检验结果。文件名只是线索。非豁免材质要两类结果都明确通过 | +| D24 | 第一期主场景:供应商在 SRM 送样单上传承认书时由 SRM 调用本能力,结论回复送样单;品质人员在 HXOPS 工作台复核。完整目标流程:ERP 发起 SRM 送样申请 → 供应商上传附件 → AI 检核 → 结果回复 SRM → 品质工作台复核确认。工作台直传是补充入口 | +| D25 | 单份上传的资料类型由调用方(或工作台上传时)指定,取值限 D6 的 7 种;系统不从内容猜测类型 | +| D26 | 上传接口支持可选的「调用方业务单号」透传字段;本能力只存储并原样返回,不做理解 | +| D27 | 外部系统调用使用服务级独立凭据(方案 A 用现有 token 体系发专用凭据,方案 B 用独立 API Key),与个人账号无关,权限仅限本模块 | +| D28 | 本期不做主动通知(企微 / 站内信)。工作台以页面刷新、运行列表查询获知结果 | +| D29 | 品质复核状态机:仅「待复核」必须由品质在工作台确认后才有终态(确认合格 / 不合格 / 退回重报);AI 判定的合格、不合格直接生效;品质对任何结论有改判权,改判留痕。SRM 先取到 AI 四态;进入品质确认的运行,SRM 再次获取时拿到确认后的终态(含确认人、确认时间)。品质长期未确认时运行停在「待品质确认」,无自动超时升级,调用方视为未结案 | +| D30 | 管理页提供运行列表(时间、文件名、类别、结论、原因、配置快照号)与原件查看/下载。权限沿用现有体系,开放给品质相关角色(角色清单由业务给出) | +| D31 | 不做存量(历史)承认书回刷,只处理新送样 | +| D32 | 提供「试运行模式」配置开关:开启期间结论照常产出并标记试运行,不合格不对外生效,供业务抽查比对;试运行时长由业务定 | +| D33 | UL 卡本期只按页签有无资料判,不做材质级份数对应;是否需要按材质对应见 O11 | +| D34 | 本期不校验图纸是否「和信内部图」;是否需要校验见 O12。样本中每份承认书只有一张图纸页签(「图纸」或「图纸P4」,已核对 17 份);若出现多张,全部抽取 Notes 并按材质归一合并去重,作为兜底规则 | +| D35 | 判定按页签位置执行:必填槽空即不合格,不跨页签认领资料;原因中附带「在其他页签发现疑似该类资料」的提示(能识别时),供品质人工判断 | +| D36 | 中文、英文报告承诺支持抽取;其它语言尽力抽取,材质或结果读不出时进待复核 | +| D37 | 上传与解析限制:单文件上限 50MB;单份承认书嵌入对象数上限 30 个,超限不拒绝、超出部分进待复核并提示;加密 / 带密码文件返回技术失败(原因「文件受密码保护」);同一文件重复提交不判重,每次生成新运行号 | +| D38 | 时效无硬性 SLA,要求尽量短;设计目标单份承认书端到端 ≤10 分钟(不含排队),用于容量规划 | +| D39 | 验收基准:样本 17 份期望结论全部为「合格」(注意凯仕特 5 份 PDF 属最难解析用例,在验收集内)。阴性用例由业务提供历史退回件;不足部分授权测试从合格样本构造(删附件、清空必填页签、替换为不合格报告),构造方式记录在测试说明。不另设量化准确率指标,上线后人工抽查 | +| D40 | 原件与解析中间产物存 MinIO 私有桶;运行记录与原件默认保留 1 年(可配置),到期清理 | +| D41 | 管理页与工作台 UI 文案按 zh-CN / zh-TW / en / th 四语言交付;检核项配置中的原因文案由业务配置,本期仅中文,结论按原文返回 | +| D42 | SRM 联调前置项:本能力为 SRM 发放服务凭据(D27);网络出口 / 白名单由 SRM 方提供;凭据发放与网络连通验证列为上线前置项,责任人评审时指定 | +| D43 | 本期不做 OA 触发,核心是 AI 检核。「品质确认完成」作为事实记录并留事件口子,OA 接入的时机与单据需求见 O13 | +| D44 | 接口支持可选的「调用方类别」入参:传入时与承认书勾选比对,不一致则整单待复核并写明两边类别;未传入(工作台直传、非 SRM 调用)不做此检查 | +| D45 | 接口接收两种形态:单个工作簿(xls / xlsx),或单个文件加 D25 的资料类型指定。多文件调用返回明确的参数错误;散件(无工作簿)归组检核列为后续需求 | + +--- + +## 3. 范围 + +### 3.1 本期做 + +| 编号 | 能力 | +|------|------| +| R1 | 上传整本承认书(xls / xlsx),按承认记录表的类别和配置矩阵检必填页签 | +| R2 | 上传单份资料(指定资料类型),按该资料类型的配置项检核 | +| R3 | 图纸页的 Notes 从截图或嵌入文件抽取(有嵌入文件时用文件)。模板说明文字不算 Notes | +| R4 | 材质证明/物性表、MSDS 按非豁免材质做覆盖检查。RoHS 页签按每份 PDF 的检验结果,检查各材质的 RoHS2.0 和卤素是否通过 | +| R5 | 新模块管理页维护第 5 节的配置,并在每次运行冻结快照 | +| R6 | 返回四态结论。不合格返回逐条原因;原因能指到页签、文件和原文片段 | +| R7 | 工作台内上传,以及外部系统 HTTP 上传,走同一套判定 | +| R8 | 品质复核:工作台对待复核运行确认(合格 / 不合格 / 退回重报);对任何 AI 结论可改判并留痕;确认后调用方可再次获取终态(D29) | +| R9 | 运行列表页:时间、文件名、类别、结论、原因、配置快照号与原件查看/下载(D30) | +| R10 | 试运行模式开关:开启期间结论标记试运行、不合格不对外生效(D32) | +| R11 | 接口契约:业务单号透传(D26)、调用方类别交叉校验(D44)、服务级凭据(D27)、上传与解析限制(D37) | + +### 3.2 本期不做 + +- 读取或写回 SRM +- 修改已有检核页面、已有检核排程、已有检核对话 +- 抽取或回传料号、版本、供应商、环保等级、签核 +- 把 MCP 作为本期验收入口 +- OA 触发(只留「品质确认完成」事件口子,见 O13) +- 企微 / 站内信等主动结果通知 +- 存量(历史)承认书批量回刷 +- 散件(无工作簿)资料包归组检核 +- 图纸「和信内部图」校验(O12 未关闭) +- UL 卡材质级份数对应(O11 未关闭) +- 在待确认项(第 8 节)关闭之前,自动判定类别勾选异常、信赖性测试项目和样品个数、塑胶件模穴份数、全尺寸表中的 Alert +- 把「和信和泰厂内测试报告」的空缺判为供应商不合格 +- 用承认书里供应商改过的矩阵,或目录上的 NA,取消配置中的必填项 + +### 3.3 后续 + +- 外部系统改为调用 MCP。MCP 的入参和出参与本期 HTTP 的结论结构一致 +- 信赖性测试项目、样品个数等待确认关闭后,接到同一套规则上,不另做一条检核链路 +- OA 触发接入:消费「品质确认完成」事件(O13) +- 散件资料包归组检核 +- 主动通知(企微 / 站内信),如业务需要 + +--- + +## 4. 业务规则 + +### 4.1 承认书结构(据样本 17 份) + +样本是同一套模板的 xls / xlsx。页签不只有矩阵里的 7 列,常见 12 张,顺序不固定(有的文件把「图纸」放在承认记录表前面)。 + +| 页签 | 在检核中的角色 | +|------|------| +| 封面 | 样品承认书抬头。本期不抽取、不参与合格判定 | +| 目录 | 供应商自己勾的资料清单(√ 或 NA)。不作为合格依据 | +| 供应商送样承认记录表 | 读类别勾选。页内复印的矩阵不作为规则 | +| 图纸 | 矩阵中的「图纸」。说明文字要求截屏和信内部图;Notes 在截图或嵌入文件里 | +| 全尺寸报告 | 矩阵中的「尺寸报告」。主体是填写的实测表,可以按模穴复制多张 | +| 第三方 RoHS 报告 | 矩阵中的 RoHS。模板要求「插入 → 对象 → 显示为图标」 | +| 材质证明 物性表 | 矩阵中的材质证明/物性表。同样是插入对象 | +| 信赖性测试 | 矩阵中的信赖性测试。项目内容见 O4 | +| MSDS | 矩阵中的 MSDS | +| UL 卡 | 矩阵中的 UL 卡 | +| 其他 | 说明⑤:出货检验、外观等矩阵外的报告放这里。缺失不判不合格 | +| 和信和泰厂内测试报告 | 和信厂内页。缺失不判供应商不合格 | + +页签名还会带页码或序号,归类前先去掉这些尾巴再对别名。样本里出现过:`封面P1`、`图纸P4`、`MSDSP9`、`UL卡P10`、`全尺寸报告(9)`、`全尺寸报告 (11)`、`全尺寸报告1#`、`全尺寸报告2#`。 + +类别勾选在承认记录表,不在「封面」。选项仍是:小五金、钣金件、塑胶件、绝缘件/导热胶、包装材料、其他。17 份里实际勾中的是小五金或塑胶件。勾选符号不统一,见过 `þ`、`■`、`█`、`□√`、`R`,空选见过 `□`、`¨`。`þ`、`■`、`█` 在样本里表示选中。`□√` 和单独的 `R` 在符号表确认之前视为读不准,整单待复核,不猜测类别。 + +承认记录表底部的说明,作为种子规则的来源: + +1. 不同材质按矩阵提供相应资料。 +2. 信赖性项目除小五金、烤漆外,还有「表面处理(膜厚测试报告)」。项目和样品个数仍见 O4。 +3. 均质材料提供第三方 RoHS2.0 和卤素报告,金属、陶瓷除外。两类报告都在 RoHS 页签,可以合在一个 PDF,也可以分成两个文件。合格看两类是否都覆盖到该材质,不看文件个数。 +4. 塑胶件全尺寸按模穴号检测,多模穴时复制全尺寸页签。模穴份数是否自动判,见 O8。 +5. 报告用插入对象放进对应页签;出货检验、外观等放「其他」。 + +`111140603000-生久-第三次送样.xls` 把复印矩阵里小五金的信赖性改成了「无」。判定仍用管理页配置,不用这一格。 + +### 4.2 材料类别 + +只读取承认记录表上的类别勾选,用它选择矩阵的一行。名为「封面」的页签不读。目录里的 √ / NA 不改类别,也不取消必填。 + +业务约束:必须且只能勾一项。系统在「一项都没勾」或「勾了两项及以上」时给出哪一态,见 O1,评审前不定。 + +勾选读不准(符号不清、无法判断勾的是哪一项)时,整单待复核,不猜测类别。 + +调用方传入的类别(D44)只用于交叉校验:传入且与承认书勾选归一后不一致时,整单待复核,原因写明「调用方类别 X,承认书勾选 Y」。未传入(工作台直传、非 SRM 调用)不比对,也不因缺少该入参产生任何结论差异。 + +结果中的类别等于读到的那一项。读不准时类别为空,结论为待复核。 + +### 4.3 必填矩阵(种子) + +`✓` 必填。该类型下所有匹配页签都确定没有资料时,不合格。`---` 不要求。`/` 不适用,缺了不判不合格。 + +「没有资料」同时满足下面几条才成立: + +- 没有嵌入对象(xls / xlsx 里的 OLE 或打包文件) +- 没有图片(含截图) +- 单元格里只剩模板提示或 `NA` + +全尺寸报告不套用上面这三条直接结案。它有没有实测行、张数要不要等于模穴、表内 Alert 算不算不合格,都见 O8、O9。这两项关闭之前,全尺寸不自动判合格,也不自动判不合格。 + +下列文字是模板,出现了也不算已提供:`第三方RoHS报告插入处`、`材质证明/物性表插入处`、`信赖性测试报告插入处`、`MSDS插入处`、`UL卡插入处`、`其他相关报告插入处`、`说明:图纸需是和信内部图,图纸请截屏至以下区域内`。必填槽里写 `NA` 同样算未提供。不要求的槽写 `NA` 不产生不合格。 + +| 材料类别 | 图纸 | 尺寸报告 | 第三方 RoHS | 材质证明/物性表 | 信赖性测试 | MSDS | UL 卡 | +|------|------|------|------|------|------|------|------| +| 小五金 | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | --- | +| 钣金件 | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | --- | +| 塑胶件 | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| 包材(纸箱、PE袋、吸塑盒、泡棉等) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| 绝缘件、导热胶 | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | +| 漆粉、油墨 | / | / | ✓ | ✓ | ✓ | ✓ | --- | + +页签归类靠别名,不要求页签名与表头逐字相同。种子别名: + +| 标准资料类型 | 样本中出现过的页签名 | +|------|------| +| 尺寸报告 | 全尺寸报告、全尺寸报告1#、全尺寸报告(9)、全尺寸报告 (11) | +| 材质证明/物性表 | 材质证明 物性表、材质证明/物性表 | +| 第三方 RoHS | 第三方RoHS报告、第三方RoHS报告P6 | +| MSDS | MSDS、MSDSP9 | +| 承认记录表 | 供应商送样承认记录表、供应商送样承认记录表P3 | + +归类时去掉页码和序号尾巴后再对别名。多张页签可以归到同一标准类型。全尺寸归到「尺寸报告」之后,一张有数据算不算齐、要不要核对模穴个数,见 O8,未确认前不判合格或不合格。 + +一个页签归到两种标准类型,或归不进去又像是必填资料时,该槽待复核,不直接判缺资料。「封面」「目录」「其他」「和信和泰厂内测试报告」归为非矩阵页,不触发这条待复核。 + +必填槽判缺时按页签位置结案,不跨页签认领资料(D35)。同工作簿其它页签若能识别出疑似该类资料,原因中附「疑似」提示,供品质人工判断;识别不出就不提示。 + +矩阵有「漆粉、油墨」,封面勾选样本里没有这一项;SRM 页面的「厂商提供资料参考表」也只有 5 类,没有漆粉/油墨和「其他」。勾「其他」或写了漆粉/油墨时怎么选行,见 O2。 + +### 4.4 图纸 Notes 与材质清单 + +整本承认书从「图纸」页的备注抽取材质。该页单元格里的截屏说明不是备注。样本里的图纸主体是截图;若同一页还有嵌入文件,用文件,不用截图。 + +样本中每份承认书只有一张图纸页签(「图纸」或「图纸P4」)。若出现多张图纸页签,全部抽取 Notes,按材质归一合并去重后形成一份材质清单(D34)。 + +备注按条目抽取,不要求标题写成 Notes。`111040650800-凯仕特.xls` 的辅料图备注是: + +1. 材质:钉帽 FE、钉杆 FE +2. 表面处理:环保蓝锌 +3. 开孔直径、铆接板厚、抗拉力、抗剪力:这些不是材质,不进入覆盖清单 + +清单是集合。钉帽和钉杆都写着 FE,合并成一个材质项。表面处理单独成项,不并进本体材质。某一项是否豁免,只看它是否在已配置的豁免词表里。FE、环保蓝锌都还没有被确认写入词表,不能因为 FE 像铁、蓝锌像金属,就当成已经豁免。 + +每一项材质包含: + +- 归一前的原文片段(必须能在 Notes 里指回) +- 归一后的材质名 +- 是否命中豁免名单 +- 抽取是否有把握 + +对不上原文的项不进入「已确认材质」,该材质相关的份数检查待复核。 + +单份上传的 RoHS、材质证明、MSDS 没有承认书,不执行「几种材质几份报告」。单份只跑该类型配置的检核项。 + +### 4.5 报告与材质如何对应(建议方案,边界见 O3) + +Notes 和插入对象都是无序的。不按行号、不按对象插入顺序配对。 + +样本里的 RoHS、材质证明、MSDS 页,常在每个插入对象旁边写材质名,对象本身是图标,单元格读不到报告正文。例如 `121010038600-沃顿.xls` 写着「磨砂PC(8B35)」,`121020038300-沃顿-第二次送样.xls` 写着「泡棉YU356」,`121030025700-沃顿.xls` 同一页写着「阻燃硅胶」「色母」「3M 9448A双面胶」,三种页(RoHS、材质证明、MSDS)各有一份同名标签。这些文字是对象的标签,不是报告正文。 + +建议按下面的集合对应: + +1. 从图纸 Notes 得到材质集合 M。丢掉顺序。 +2. 豁免名单从 M 中划出免 RoHS2.0 和免卤素的材质。材质证明和 MSDS 是否同样豁免,见 O3。已确认的豁免对象是 RoHS 页签上的这两类报告。 +3. 该资料类型的每一个插入对象先取旁边的标签;再从对象内容里抽材质。两边都走别名表。标签和内容都有、且归一后不一致,该对象待复核。 +4. 只有标签、没有对象,不算一份报告。只有对象、没有标签,用对象内容里的材质。 +5. 一份报告覆盖一种材质,仅当标签或内容与 M 中某一项归一后一致。 +6. 材质证明和 MSDS:一种需要覆盖的材质,至少被一份报告点名,才算齐套。RoHS 页签不按这一条,按下一节。一份对象的正文或标签里出现多种材质时怎么计,见 O3;未确认前该对象待复核,不把它计成多份,也不把它计成合格覆盖。 + +### 4.5.1 RoHS 页签上的 RoHS 与卤素 + +第三方 RoHS 报告和卤素报告都放在 RoHS 页签,没有单独的卤素页签。一个页签里可以插入很多份 PDF。`111040650800-凯仕特.xls` 的 RoHS 页签在「第三方RoHS报告插入处」下面有 5 个 PDF: + +- `35KA2250839726101004E.pdf` +- `A2260379838101001 铁拉钉 英文.pdf` +- `A2250684500101001 锌无卤报告.pdf` +- `8AA2250839726101002E.pdf` +- `A2260181936101004R2 环保蛋白锌.pdf` + +这 5 份不是 5 种材质,也不能靠文件名结案。「锌无卤报告」「铁拉钉」「环保蛋白锌」只说明该去正文里核对什么。合格与否看每份 PDF 里各材质的检验结果。 + +两类报告的装法仍然都合法:同一个 PDF 里既有 RoHS2.0 又有卤素,或者拆成多份文件插在同一页签。 + +1. 每个 PDF 从正文抽出三件事:检验的材质、报告种类(RoHS2.0、卤素,或两类都有)、该材质在这一类上的检验结果原文。页签名和文件名都不能代替这三件事。 +2. 结果明确为符合、合格或未检出:这一材质的这一类算通过。结果明确为不符合、不合格或超标:不合格,原因写明材质、缺的或失败的是 RoHS 还是卤素,并带上结果原文。 +3. 一个 PDF 里两类结果都明确通过,并且对上了某一种材质,则这一种材质的两类都算通过。不因为只有一个文件判缺。 +4. 分成多份时,只要这些文件的结果能拼出同一种材质的两类都通过,就算齐。不因为分成多个文件判不合格。凯仕特这种 5 个文件,按结果归到材质上,不按 5 这个数字。 +5. 某种已确认的非豁免材质只有 RoHS2.0 通过、没有卤素通过,或只有卤素通过、没有 RoHS2.0 通过,不合格。 +6. 看不出文件检验的是哪一种材质、哪一类,或读不出检验结果,该文件待复核,不把它算成通过,也不直接判不合格。 +7. 只有命中豁免词表的材质才同时免除 RoHS2.0 和卤素。词表外的名称不自动豁免。表面处理是否随本体一起豁免,见 O10,未确认前不连带豁免,也不把未进词表的名称写成已豁免。 +8. 单份上传不执行「两类结果都要有」。单份只核对这个文件里读得出的检验结果。两类一起看,只在整本承认书的 RoHS 页签上做。 + +示例: + +- 图纸备注抽出两项:FE,以及表面处理环保蓝锌。钉帽和钉杆都是 FE,合成一项。这两项都还没有被确认放进豁免词表,本例不把 FE 当成已豁免。 +- RoHS 页签上的「锌无卤报告」只有在正文里能读到对应材质的卤素结果且结果通过时,才算卤素通过。文件名里有「无卤」不够。 +- 读不出某份 PDF 在检哪一种材质、哪一类、结果是什么,该文件待复核。 + +模型只负责从 Notes 和从每一份报告里列出材质并引用原文。份数够不够、有没有被覆盖,由规则计算。 + +下列边界没有确认,评审时需要业务和研发一起定(O3): + +- 一份报告正文里写了两种材质,算覆盖两种,还是只允许一种主材质,写了多种就待复核 +- 报告上的牌号、商品名在别名表里没有,与 Notes 的化学名对不上:待复核,还是直接不合格 +- 多出来的报告(对不上任何材质)是待复核,还是忽略 +- 材质证明、MSDS 是否沿用金属/陶瓷豁免。RoHS2.0 和卤素的豁免已确认,两类一起免 +- 图纸槽同时有文件和图片,且两边抽出的材质不一致时如何结案。已确认的优先级是:有文件则用文件 + +在 O3 关闭之前,材质对不上、一份对象多种材质、多余对象这些边界样本不进入自动合格或自动不合格,一律待复核。第 4.5.1 节的合订 PDF 与拆成两个文件是已确认规则,不放进这批待复核。 + +### 4.6 四态分别在什么时候出现 + +| 结论 | 何时使用 | 返回给调用方的内容 | +|------|------|------| +| 合格 | 必填槽都在,且已确认的份数、覆盖、配置检核项都满足 | 合格;读到的类别;已满足的必填资料类型 | +| 不合格 | 规则能确定被违反。例如必填槽确定为空;某种已确认的非豁免材质在 RoHS 页签上缺 RoHS2.0 或缺卤素 | 不合格;类别;逐条原因。每条原因包含资料类型、缺什么、原文或文件位置 | +| 待复核 | 类别读不准;Notes 或报告的材质拆不开;一份资料能对上多种材质又还没定规则;页签归类不确定;调用方类别与勾选不一致 | 待复核;不确定的是哪一条;已有的原文片段。不写成不合格 | +| 技术失败 | 文件打不开、损坏、加密、解析或模型调用失败 | 技术失败;失败环节。不表述为供应商资料不合格 | + +同一份承认书上,确定的规则违反优先于待复核:已经能确定缺必填槽时,结论为不合格,同时可以附带其它待复核项。全部确定项都通过、但仍有不确定项时,结论为待复核,不升为合格。 + +结论之后还有品质确认环节,见 4.8。 + +### 4.7 单份资料与整本承认书 + +| | 整本承认书 | 单份资料 | +|------|------|------| +| 输入 | 一个 xls 或 xlsx | 该资料类型的一个文件(pdf、图片或 Office),类型由调用方指定(D25) | +| 类别 | 读承认记录表勾选 | 不读类别,不套矩阵 | +| 必填页签 | 按矩阵 | 不做 | +| 材质份数 | 图纸 Notes 对 RoHS、材质证明、MSDS | 不做 | +| 检核项 | 每种资料类型的配置项 | 只跑这一类型的配置项 | +| 结果里的类别 | 读到的类别 | 空 | + +### 4.8 品质复核与运行状态 + +运行状态机: + +> 解析中 → 已出 AI 结论(合格 / 不合格 / 待复核 / 技术失败)→(仅待复核)待品质确认 → 终态 + +- 品质动作(D29):确认合格、确认不合格、退回重报;对任何已生效的 AI 结论可改判,改判记录改判人、时间与理由。 +- 对外取结果:AI 结论一出调用方即可取;运行进入品质确认后,再次获取拿到确认后的终态,含确认人与确认时间。 +- 待品质确认的运行没有自动超时;调用方视为未结案。 +- 待复核结论必须向品质说明原因:不确定的是哪一条、已有的原文片段(4.6 待复核行)。 +- 「品质确认完成」写入运行记录并作为事件留存,供后续 OA 接入(D43、O13)。 + +--- + +## 5. 配置 + +管理页维护下列对象。保存后只作用于新运行。运行记录写入当时的快照,事后改配置不改变旧结论。 + +| 配置 | 作用 | 种子 | +|------|------|------| +| 材料类别 | 封面勾选归到哪一行 | 第 4.3 节六类,另加封面的「其他」 | +| 必填矩阵 | 该类别下每个标准资料类型是必填、不要求还是不适用 | 第 4.3 节 | +| 页签别名 | 去掉页码、序号后再归到标准资料类型 | 第 4.3 节 | +| 勾选符号 | 哪些字符表示选中、哪些表示未选 | `þ` `■` `█` 为选中,`□` `¨` 为未选。`□√` 与单独的 `R` 在补进符号表之前按读不准处理 | +| 类别别名 | 勾选文字归到材料类别 | 「包装材料…」归到包材 | +| 材质别名 | 不同写法收成同一材质 | 上线前由业务给一版,可空表起步,空表时对不上的进待复核 | +| 豁免材质 | 这些材质不要求 RoHS2.0 和卤素 | 说明③里的「金属、陶瓷」是类别说法。FE、铁、不锈钢、蓝锌等具体名称尚未确认,见 O10 | +| 资料检核项 | 某一资料类型内部要核的栏位、比较方式和不合格原因文案 | 首批栏位清单见 O5。引擎本期就要能配置,不把栏位写死 | +| 试运行模式 | 开启期间结论照常产出并标记试运行,不合格不对外生效(D32) | 默认开启,业务抽查比对后关闭 | + +检核项至少支持:必填、与材质清单一致、包含指定文本、有效期晚于某日期(日期规则是否启用由配置决定)。比较失败且证据充分时不合格;证据不足待复核。 + +说明③已确认:RoHS 页签要覆盖第三方 RoHS2.0 和卤素;两类可以在同一个 PDF,也可以分成两个文件;金属、陶瓷两类都免除。报告里还要核哪些栏位(限值、实验室、签章、有效期等)属于 O5,不在本文写成固定清单。 + +--- + +## 6. 两套部署方案(待确认,见 O6) + +第一期主场景是 SRM 直连调用(D24),两套方案都必须支持外部系统直连、异步取结果与专用服务凭据(D27)。两套方案的判定规则、配置对象、四态结论、返回内容相同。不同的是进程放在哪里。评审选定之前,不按某一套写死接口路径。 + +### 6.1 方案 A — 当前项目内的新模块(Flask) + +- 新模块放在现有 HXOPS 中:Flask 接口、现有异步作业、PostgreSQL、MinIO、Redis、Vue 管理页。 +- SRM 和工作台用户都调用 HXOPS。 +- 登录与权限沿用现有体系,外部凭据用现有 token 体系发放(D27)。 +- 解析和视觉抽取与现有 Web 进程共用同一套发布和扩容方式。 + +适合:希望只维护一个系统、工作台与管理页复用现有登录和权限。 + +### 6.2 方案 B — 独立服务(FastAPI) + +- 新建独立服务,骨架与气泡图项目一致:FastAPI、独立 worker、共用 PostgreSQL / MinIO / Redis / LiteLLM / Casdoor。 +- 工作台只转发文件和取回结论,判定不写在 HXOPS 里。 +- SRM 直接调用该服务的 HTTP。以后的 MCP 也挂在这个服务上。 +- 解析任务按 worker 单独扩容。 + +适合:文件解析和视觉抽取需要单独扩容,外部流量不经过 HXOPS 主站。 + +### 6.3 调用节奏(待确认,见 O7) + +主场景是 SRM 在供应商上传后触发检核,供应商和品质分步查看结果,同步等待没有业务意义。建议第一阶段采用异步,两套方案相同: + +1. 提交文件后立即返回运行号。 +2. SRM 轮询,或在后续确认回调地址后接收回调(地址与轮询间隔由 SRM 方配置)。 +3. 终态才返回第 4.6 节的结论;品质确认后再次获取拿到确认后终态(D29)。 + +同步「一次请求里等到结论」不作为建议。图纸、多份 PDF 和视觉抽取的耗时不稳定。若仍要同步,需要在 O7 里同时给出超时和文件大小上限。 + +### 6.4 返回内容(两套方案相同) + +| 字段 | 说明 | +|------|------| +| 运行号 | 追溯用 | +| 结论 | 合格 / 不合格 / 待复核 / 技术失败 | +| 类别 | 整本承认书为读到的类别;单份资料为空;读不准为空 | +| 调用方业务单号 | 上传时传入则原样返回,否则为空(D26) | +| 品质确认 | 未确认时为空;品质确认后含终态结论、确认人、确认时间(D29) | +| 原因列表 | 不合格或待复核的逐条说明,含资料类型、原因码、页签或文件、原文片段 | +| 材质清单 | 整本承认书返回 Notes 抽出的材质、是否豁免、是否被对应类型的报告覆盖。单份资料不返回份数覆盖 | +| 配置快照号 | 指向这次运行使用的配置 | + +原因码在实现时再编号。评审只要求:同一类原因的文案稳定,调用方能区分「缺页签」「缺某种材质的 RoHS」「缺某种材质的卤素」「缺某种材质的材质证明或 MSDS」「调用方类别与勾选不一致」「待复核」「技术失败」。 + +--- + +## 7. 验收(只含已确认项) + +下列条目在第 8 节仍开放时也要能测。开放项对应的自动判定不启用,样本期望是「不自动合格、不自动不合格」,并在结论或原因里标明尚未启用的规则。 + +1. 只上传承认书、不提供任何 SRM 信息,能跑完并返回四态之一。 +2. 塑胶件勾选清楚时,按种子矩阵要求 UL 卡;小五金勾选清楚时,不因缺少 UL 卡判不合格。 +3. 漆粉、油墨若能选中该行,缺少图纸不判不合格(单元格为 `/`)。 +4. 页签名「全尺寸报告(9)」「全尺寸报告1#」「MSDSP9」能分别归到尺寸报告、尺寸报告、MSDS。归类之后是否合格,受 O8、O9 约束,本条不判断。 +5. 图纸、RoHS、材质证明、MSDS、UL、信赖性这些必填页,只有「××插入处」或 `NA`、没有嵌入对象也没有图片时,不合格,原因指到该页签。全尺寸不在本条内。 +6. 槽内有嵌入对象时,抽取使用该对象。对象旁的材质文字作为标签参与对应,不能代替对象。 +7. 图纸页的模板说明文字不进入材质清单。Notes 来自截图或嵌入文件,每一项都能指回原文;指不回的不参与「已确认材质」。 +8. 对应关系不使用 Notes 行序和对象顺序。旁注「磨砂PC(8B35)」经别名归到「磨砂 PC」后,才能覆盖 Notes 里的同一种材质。 +9. 已确认的非豁免材质,要在 RoHS 页签某份 PDF 的正文里读到 RoHS2.0 和卤素都明确通过。缺一类,或结果明确不合格,原因写明材质和是 RoHS 还是卤素。同一个 PDF 两类都通过,不因只有一个文件判缺。一个页签多份 PDF(如凯仕特 5 份)按检验结果归到材质,不按文件个数判。文件名含「无卤」但正文读不出该材质的卤素结果,不算通过。 +10. 只有材质名已经写在豁免词表里时,才不因缺少 RoHS2.0 或缺卤素判不合格。FE 不在已确认词表里,不能用本条把它豁免。钉帽 FE 与钉杆 FE 合并为一项,只表示它们是同一个材质名。 +11. 单份上传一份 MSDS(或 RoHS、材质证明、UL、图纸、尺寸报告、信赖性文件)并指定类型时,不要求承认书,也不按类别矩阵判缺页签。 +12. 修改配置后,新运行使用新配置;旧运行的结论仍按旧快照解释。承认书内把信赖性改成「无」或目录把信赖性标成 NA,不改变配置矩阵的必填结果。 +13. 返回体不含料号、版本、供应商、环保等级、签核。 +14. 本服务不连接 SRM 写状态。 +15. 技术失败的样本(损坏文件)返回技术失败,原因不是不合格。 +16. 「封面」「目录」「其他」「和信和泰厂内测试报告」空着,不按矩阵判不合格。 +17. 能打开样本中的 xls(不只是 xlsx)。 +18. 接口只接受单个工作簿,或「单个文件 + 资料类型指定」;多文件调用返回明确的参数错误,单文件不指定类型返回参数错误(D25、D45)。 +19. 上传带「调用方业务单号」时结果体原样返回;不带时该字段为空(D26)。 +20. 传入「调用方类别」且与承认书勾选不一致时,结论待复核并写明两边类别;未传入时不比对(D44)。 +21. 待复核运行经品质确认(合格 / 不合格 / 退回重报)后,调用方再次获取拿到确认后终态,含确认人与确认时间;对已生效结论改判有留痕(D29)。 +22. 试运行开关开启时,不合格结论被标记且不对外生效;关闭后恢复正常(D32)。 +23. 超过 50MB 的文件被拒绝;加密文件返回技术失败「文件受密码保护」;嵌入对象超过 30 个不拒绝、超出部分进待复核并提示(D37)。 +24. 运行列表页可查询全部运行(时间、文件名、类别、结论、原因、配置快照号)并查看原件(D30)。 +25. 样本 17 份全部判定「合格」作为验收基准,第 8 节相关待确认项的关闭口径须与该基准兼容;阴性用例(业务提供的历史退回件或按 D39 构造)按测试说明得出期望的不合格 / 待复核。 +26. 管理页与工作台 UI 支持四语言切换;业务配置的原因文案按中文原样返回(D41)。 + +--- + +## 8. 待确认清单 + +评审要逐条给出结论。建议列只是建议,不是已确认。 + +| 编号 | 议题 | 为什么要确认 | 建议 | 确认人 | +|------|------|------|------|------| +| O1 | 类别一项都没勾,或勾了两项及以上,结论是不合格还是待复核 | 业务规则已是「必须且只能一项」。系统看清楚时如何结案还没定。看不清已定为待复核 | 看清楚的 0 项:不合格,「类别未勾选」。看清楚的多项:不合格,「类别只能勾选一项」。看不清:待复核 | 业务用户 | +| O2 | 封面有「其他」,矩阵有「漆粉、油墨」,SRM 参考表两者都没有,三处对不齐 | SRM 页面的「厂商提供资料参考表」只有 5 类(小五金、钣金件、塑胶件、包材、绝缘件/导热胶),没有漆粉/油墨和「其他」;承认书封面勾选有「其他」;配置矩阵有「漆粉、油墨」。勾「其他」或写了漆粉/油墨时,没有确定的矩阵行 | 「其他」且无法归入已有类别:待复核。漆粉、油墨做成可勾选类别,或允许「其他」的填写文字经别名归入该行 | 业务用户 | +| O3 | 无序的 Notes 材质与无序的插入对象,边界如何算对上 | 方向已确认:不按顺序。对象旁的文字是标签(样本:磨砂PC(8B35)、泡棉YU356、阻燃硅胶、色母、3M 9448A双面胶)。标签与对象内容冲突、一份对象多种材质、多余对象,仍会改变合格/不合格 | 标签和内容不一致则该对象待复核。一份对象只覆盖一种主材质;出现多种材质则待复核。别名表没有的牌号待复核,不直接不合格。多出来且对不上任何材质的对象待复核。材质证明和 MSDS 先不套用金属/陶瓷豁免。文件与图片材质冲突时以文件为准,并另记一条待复核 | 业务用户 + 研发 | +| O4 | 信赖性测试检到哪一层 | 说明②列出小五金(盐雾、硬度、铆合强度)、烤漆(酒精摩擦、百格、铅笔硬度)、表面处理(膜厚),以及按单价决定的样品个数。承认书里没有单价 | 本期只按矩阵检查信赖性页签是否已提供资料。项目名称和样品个数不自动判。抽出的检测项只写入结果备查 | 业务用户 | +| O5 | 各资料类型第一批检核项清单 | 本期要求检核项可配置,但业务还没有给出 RoHS、材质证明、MSDS、UL、尺寸、图纸各自要核的栏位 | 评审会上按资料类型列出栏位、合格条件和不合格文案。在清单确认前,这些栏位不参与自动合格 | 业务用户 | +| O6 | 采用方案 A(Flask,放在当前项目)还是方案 B(FastAPI,独立服务) | 主场景已定为 SRM 直连调用 + 品质工作台复核(D24),两套都支持。方案 B 的额外收益是解析 worker 独立扩容、外部流量不经过 HXOPS 主站;方案 A 的收益是只维护一个系统、工作台与管理页复用现有登录和权限 | 按「解析算力是否需要独立扩容、运维是否接受两套部署」拍板;两套的外部行为与接口契约相同 | 研发 / 架构,SRM 调用方参加 | +| O7 | 第一阶段用异步还是同步 | 主场景是 SRM 在供应商上传后触发,供应商和品质分步查看结果,同步等待没有业务意义。尚未正式拍板 | 异步:立即返回运行号,轮询取结论。回调作为异步的可选项,地址与轮询间隔由 SRM 配置。若仍要同步,须同时给出超时与文件大小上限 | 研发 + SRM 调用方 | +| O8 | 塑胶件多张全尺寸报告要不要核对模穴个数 | 说明④要求按模穴号检测,并复制页签。样本里同一份承认书有 4 张或 8 张全尺寸页。与 D39 联动:17 份样本期望全部合格,其中含多张全尺寸页的样本,O8 的关闭口径必须保证这些样本能判合格 | 无。待业务用户确认前,不因全尺寸张数判合格或不合格 | 业务用户 | +| O9 | 全尺寸表中的 Accept / Alert 要不要判不合格 | 实测表有一列判定,样本里出现 Accept 和 Alert。与 D39 联动:含 Alert 的样本在验收基准里期望合格,O9 的关闭口径必须与业务意图一致(判合格,或明确某些 Alert 判不合格) | 无。待业务用户确认前,不因实测行或 Alert 判合格或不合格 | 业务用户 | +| O10 | 哪些材质名算金属、陶瓷,从而豁免 RoHS 和卤素 | 说明③只写了「除金属、陶瓷」。FE 被写成已豁免,是从「FE 像铁」推出来的,业务没有确认。与 D39 联动:凯仕特样本的 FE 若不入豁免词表,就必须在 5 份 PDF 中读出 FE 的 RoHS2.0 与卤素两类通过才能合格;词表评审须与验收基准联动 | 无。待业务给出词表前,不把 FE 或任何具体牌号自动豁免,也不因「像金属」跳过检查 | 业务用户 | +| O11 | UL 卡是否按材质份数对应 | UL 黄卡通常按材料牌号出具;塑胶件、包材、绝缘件的矩阵里 UL 卡必填。业务尚未给出按材质对应的规则 | 本期只查 UL 卡页签有无资料(D33);业务确认需要时,接入与材质证明/MSDS 同一套覆盖检查 | 业务用户 | +| O12 | 图纸是否需要校验为「和信内部图」 | 承认书说明要求「图纸需是和信内部图」,但目前没有可靠的自动判据(水印 / 图框识别) | 本期不校验,只要求图纸槽有资料且能抽 Notes(D34);业务确认需要时再定判据 | 业务用户 + 研发 | +| O13 | OA 触发的接入时机与单据需求 | 目标流程中品质确认 OK 后触发 OA;OA 单据模板、字段、会签链路未细化,本期不做(D43),只落「品质确认完成」事件口 | 先落事件;OA 单据需求细化后另起一期接入 | 业务用户 + 研发 | + +O4、O5、O8、O9、O10、O11、O12 未关闭时,第 7 节不包含「信赖性项目缺失即不合格」「某个 RoHS 栏位缺失即不合格」「模穴张数不对即不合格」「尺寸 Alert 即不合格」「FE 因属于金属而免 RoHS」「UL 卡按材质份数判合格」「图纸非内部图即不合格」。 + +--- + +## 9. 评审需要当场拍板的顺序 + +1. O6 部署方案、O7 调用节奏:主场景已定(D24、D42),这里决定部署单位与接口形态。 +2. O1、O2:决定类别异常样本的期望结论(SRM 参考表 5 类、封面「其他」、矩阵 6 类三处对齐)。 +3. O3:决定 RoHS / 材质证明 / MSDS 的合格样本怎么准备。 +4. O5:决定管理页第一批要配哪些检核项。 +5. O4:决定信赖性本期是否只检「有没有这份资料」。 +6. O8、O9:与 D39「17 份样本全合格」验收基准联动拍板。 +7. O10:给出豁免词表(与验收基准联动)。 +8. O11、O12、O13:UL 卡份数、内部图校验、OA 接入时机。 diff --git a/docs/features/shipping-notice/inventory_source_plan.md b/docs/features/shipping-notice/inventory_source_plan.md index 73e1d1fe..76334c41 100644 --- a/docs/features/shipping-notice/inventory_source_plan.md +++ b/docs/features/shipping-notice/inventory_source_plan.md @@ -35,7 +35,7 @@ query_parameters_json # 参数名、single/multi_text/multi_select、values、 业务管理员维护路径和参数值;订单到库存站点的选择统一在版本化路由规则中维护。RPA Driver 模板维护 `selector_env`、CSS selector、下载模式、控件等待策略等技术细节。上述技术字段和第二套路由别名不得写入库存源。DBS 参数必须支持单选、文本多值和列表多选。Crane 当前导出完整多仓库存文件,不维护 Crane Warehouse 清单。 -`backend/config/shipping_inventory_sources.yaml` 保留为**期初导入参考**,直到数据库导入、校验和试跑完成前不得删除;它不再是运行时读取源。导入时将旧 `dsv360` / `crane_footprint` 归一为 `dbs` / `crane`,映射报表路径、参数和别名,并丢弃 `site_id`。导入完成后,RPA 运行时只读取数据库。 +期初导入参考 `backend/config/freight_rpa_sources.yaml` 及配套导入脚本 `backend/scripts/import_freight_rpa_sources.py` 已于 2026-10-20 删除(数据库导入、校验和试跑早已完成):库存源唯一真相是数据库 `freight_rpa_sources`,新增/修改一律走管理端,运行时只读数据库。历史 YAML 内容可在 Git 历史中查阅(删除前提交 39fe3c05f 附近)。 ### 固定 Warehouse diff --git a/docs/features/shipping-notice/shipping-notice-auto-progress-mvp.md b/docs/features/shipping-notice/shipping-notice-auto-progress-mvp.md index 14575b21..b66b84f5 100644 --- a/docs/features/shipping-notice/shipping-notice-auto-progress-mvp.md +++ b/docs/features/shipping-notice/shipping-notice-auto-progress-mvp.md @@ -1,4 +1,4 @@ -# 发货通知自动推进 MVP 方案 +# 发货通知自动推进 MVP 方案 > 版本:MVP v1.0 > 日期:2026-08-07 @@ -263,7 +263,7 @@ Projection 至少包含: ```text SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true -SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true +SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 9151a045..939a3b48 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -1,4 +1,4 @@ -# 货代发货通知 — 完整手册 +# 货代发货通知 — 完整手册 > **唯一技术文档**:货代发货通知相关的部署、Dify 配置、OpenAPI、Agent 指令与运维说明 **仅维护本文件**(`docs/features/shipping-notice/technical.md`),请勿另建分散 md。\ > **业务操作说明**:[`business.md`](./business.md)(面向货代/跟单等业务人员,无程序与 Dify 内容)。\ @@ -46,7 +46,7 @@ **彻底清除(不留兼容层)**: - **写路径**:`set_task_step_progress` 入参 `step_key` 改名 `stage`,必须传 15 阶契约码(非法值 `ValueError` 立即失败);`current_step` 与 `current_step_progress` 载荷字段同步改存/改名 `stage`;`OT.stage` 写入带**只进不退守卫**(按 `shipping_processing_stage_index`,仅允许推进或平齐,禁止回退),进度上报永远无法再拉低阶段。 -- **29 个调用点**全部改传契约码:库存准备/映射/RPA → `inventory_fetching`;库存匹配/文件入库 → `inventory_matching`;Excel 生成 → `excel_generating`;货代上传 → `freight_uploading`;通知重提交/解析确认 → `order_creating` / `waiting_review`。 +- **29 个调用点**全部改传契约码:库存准备/映射/RPA → `onhand_fetching`;库存匹配/文件入库 → `onhand_matching`;Excel 生成 → `excel_generating`;货代上传 → `freight_uploading`;通知重提交/解析确认 → `order_creating` / `waiting_review`。 - **读路径别名全部删除**:`lifecycle_projection.LIFECYCLE_STAGE_BY_PROCESSING_STAGE` 与 `processing_projection_invariants._USER_STAGE_TO_CODE` 中的 4 个 stepN_* 别名条目移除,映射表只认契约码;`map_notice_to_processing_status_stage` 对 `current_step` 的子串/前缀启发式(`'upload' in step` / `startswith('step7')` 等)改为契约码精确匹配。 - **存量数据**:不落数据迁移——各环境确认无需要清洗的 stepN_* 存量,写路径切换后不再产生新遗留值。 - **前端**:`ShippingCurrentStepProgress.step_key` 字段改名 `stage`(无组件消费该字段,仅类型同步)。 @@ -66,7 +66,7 @@ - 桌面右栏 `ReviewCurrentProcessingCard` 是每个 Gate 唯一全局写入口;主区仅显示事实、行级局部操作或被右栏定位的裁决表单。`TaskTodoPanel` 在生命周期工作台仅作无界面动作执行宿主,禁止重复渲染 Gate 或主按钮。 - `stage_context` 不落库、不驱动状态、不授权动作,仅由正式任务详情与单票 `/ui-state` 按需返回;任务列表、聊天轻量投影不加载它,以避免 N+1 查询。 - **OT 阶段随 Gate 推进回写(2026-08-26)**:`_refresh_execution_pointers`(Gate 状态/指针刷新的唯一收口)在 Execution 已绑定任务时补调 `sync_order_task_stage_for_notice`,使 `shipping_order_tasks.stage/status` 与当前 Gate 事实一致(如 `manual_upload_handoff` → `freight_uploading/blocked`),避免右侧「当前任务」主卡/批次投影停留在旧技术阶段(如 `excel_generating`)。建单前执行(无 task_id)不触发。 -- **履约 Gate 编排分离(2026-09-06)**:`inventory_matching` Attempt 只做匹配 + `sync`;`complete(passed)` 后由 `_enqueue_auto_progress_after_gate_pass` 入队独立 `artifact_generation` Attempt,再由 `_handle_regenerate_excel` / `_task_payload` 调用 `generate_excel`。禁止 `try_auto_chain_after_match` 在匹配 Attempt 内嵌 generate/upload;`AUTO_GENERATE_EXCEL` / `AUTO_UPLOAD` 仅控制自动入队。详见 [process-gate-recovery-contract.md](./process-gate-recovery-contract.md) 与计划 `docs/superpowers/plans/2026-09-06-shipping-gate-orchestration-separation.md`。 +- **履约 Gate 编排分离(2026-09-06)**:`onhand_matching` Attempt 只做匹配 + `sync`;`complete(passed)` 后由 `_enqueue_auto_progress_after_gate_pass` 入队独立 `artifact_generation` Attempt,再由 `_handle_regenerate_excel` / `_task_payload` 调用 `generate_excel`。禁止 `try_auto_chain_after_match` 在匹配 Attempt 内嵌 generate/upload;`AUTO_GENERATE_EXCEL` / `AUTO_UPLOAD` 仅控制自动入队。详见 [process-gate-recovery-contract.md](./process-gate-recovery-contract.md) 与计划 `docs/superpowers/plans/2026-09-06-shipping-gate-orchestration-separation.md`。 ### Dify 配置边界(2026-08) @@ -699,7 +699,7 @@ Dify 故障不影响确定性解析和人工复核 - 管理端调用 `POST /api/admin/shipping-notice/source-validation-batches` 对多个停用且已绑定 published 解析方案的站点发起测试;`GET /.../{id}` 返回批次汇总和逐站点运行,`POST /.../{id}/retry-failed` 仅重试失败或已过期项。 - 管理端页面刷新时调用 `GET /api/admin/shipping-notice/source-validation-batches/latest-active` 恢复最近未结束的批次并继续轮询;已结束批次不自动弹出。批量面板固定高度,持续显示总体进度、处理中/成功/无库存/失败计数,并可按状态筛选逐站点结果。 - 服务端按 `rpa_profile_id + connector_type` 生成 trigger,同一组由 Worker 复用一次登录;Worker 按现有轮询串行消费 trigger,因此浏览器并发上限为 1,避免站点增加时无控制地并发登录。 -- 每个 source 透传 `validation_run_no`,Worker 通过 `/api/shipping-notice/rpa/inventory-configuration-test-batch-ready` 回传 `results[]`;成功、空库存、失败和配置变更均按运行号独立回写,绝不创建生产库存快照。 +- 每个 source 透传 `validation_run_no`,Worker 通过 `/api/freight-rpa/onhand-configuration-test-complete` 回传 `results[]`;成功、空库存、失败和配置变更均按运行号独立回写,绝不创建生产库存快照。 - **Dify 配置:无需修改。** Dify 不读取验证批次状态,不新增 Tool、节点或画布连线;该能力完全由 HXOPS 管理端、后端和 Windows RPA Worker 协作完成。 > **当前目标口径**:本文件描述的是 **shipping notice 新方案的目标技术稿**;后端实现统一采用 **Flask**,不使用 FastAPI,但也不回退到旧单 task 现状口径。 @@ -1737,13 +1737,13 @@ SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000 # RPA 目录 -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_SHARED_ONHAND_DROP_DIR=data/freight_rpa/onhand/drop +FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR=data/freight_rpa/onhand/triggers +FREIGHT_RPA_SHARED_INBOUND_DROP_DIR=data/freight_rpa/inbound/drop +FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR=data/freight_rpa/inbound/triggers +FREIGHT_RPA_INBOUND_ARCHIVE_DIR=data/freight_rpa/inbound/archives +FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=data/freight_rpa/upload/queue +FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/freight_rpa/upload/triggers ## 字段资产库与 Schema 契约(目标态) @@ -1828,29 +1828,29 @@ GET /api/admin/shipping-order-schema/published-contract - 解析 Profile 的 `field_mapping` 键、`match_keys[].inventory_field_id`、库存快照行 JSON 和发货模板 `source_kind=inventory_field` 的 `source_key` 均直接使用库存字段目录 ID。内部 `field_code` 只用于审计,不得参与解析、匹配、仓库识别或导出。 - 发布解析方案必须至少映射一个“库存匹配”字段,且必须且只能映射一个“库存数量”字段;动态仓库存站点还必须且只能映射一个“仓库识别”字段。一般业务字段数量不限,可供发货模板输出。 -- `ShippingInventoryParsingProfile` 独立于 RPA 登录 Profile 和 Inventory Source,使用 `draft -> published -> retired` 版本生命周期。 +- `ShippingOnhandParsingProfile` 独立于 RPA 登录 Profile 和 Onhand Source,使用 `draft -> published -> retired` 版本生命周期。 - Profile 定义保存 `file_format/sheet_name/header_row_index/field_mapping/match_keys`;`field_mapping` 为 `inventory_field_id -> source_header`,`match_keys` 为稳定订单 `order_field_id -> inventory_field_id`,均不保存显示名称或原始表头以外的技术字段。 - 管理端以结构化行编辑器维护标准库存字段、文件表头与订单行字段匹配键,所有可选项来自后端 `GET /api/admin/shipping-notice/configuration-catalog`,不要求管理员直接编辑 JSON。 -- 管理员新建库存文件解析方案时先上传 `.xls/.xlsx/.csv` 样本至 `POST /api/admin/shipping-notice/inventory-structure-analyses`。后端读取所有工作表、候选表头、真实栏位、推断类型、空值率与最多五行脱敏样例;管理端样本完整文件只在即时分析期间存在,分析完成后立即清理。`shipping_inventory_structure_analyses` 保留文件名、checksum、完整结构、统计、结构指纹和脱敏样例;`ShippingInventoryParsingProfile.sample_analysis_id` 绑定草稿和发布版本的样本证据。页面只允许从该证据选择工作表、表头和来源栏位,`POST /inventory-structure-analyses/{id}/create-profile-draft` 用确认后的结果创建草稿,不能以浏览器提交的虚构栏位替代分析结果。解析方案列表 DTO 返回最小化 `sample_evidence`;管理端再次打开草稿时从此恢复候选工作表、表头、来源栏位下拉和脱敏预览,不读取或回传原始文件。草稿替换样本前通过 `POST /parsing-profiles/{profile_id}/sample-replacement-preview/{analysis_id}` 以当前拟保存映射计算新增/缺少栏位、顺序变化、失效映射和格式差异;仅无失效映射且管理员在平台确认弹窗确认后,`create-profile-draft` 才接受 `confirm_sample_replacement=true` 切换证据。旧/新分析 ID、操作者和时间追加到 `sample_evidence_history_json`,已发布版本不可替换样本。Dify 画布不参与此证据绑定流程。 +- 管理员新建库存文件解析方案时先上传 `.xls/.xlsx/.csv` 样本至 `POST /api/admin/freight-rpa/onhand/structure-analyses`。后端读取所有工作表、候选表头、真实栏位、推断类型、空值率与最多五行脱敏样例;管理端样本完整文件只在即时分析期间存在,分析完成后立即清理。`freight_rpa_onhand_structure_analyses` 保留文件名、checksum、完整结构、统计、结构指纹和脱敏样例;`ShippingOnhandParsingProfile.sample_analysis_id` 绑定草稿和发布版本的样本证据。页面只允许从该证据选择工作表、表头和来源栏位,`POST /api/admin/freight-rpa/onhand/structure-analyses/{id}/create-profile-draft` 用确认后的结果创建草稿,不能以浏览器提交的虚构栏位替代分析结果。解析方案列表 DTO 返回最小化 `sample_evidence`;管理端再次打开草稿时从此恢复候选工作表、表头、来源栏位下拉和脱敏预览,不读取或回传原始文件。草稿替换样本前通过 `POST /parsing-profiles/{profile_id}/sample-replacement-preview/{analysis_id}` 以当前拟保存映射计算新增/缺少栏位、顺序变化、失效映射和格式差异;仅无失效映射且管理员在平台确认弹窗确认后,`create-profile-draft` 才接受 `confirm_sample_replacement=true` 切换证据。旧/新分析 ID、操作者和时间追加到 `sample_evidence_history_json`,已发布版本不可替换样本。Dify 画布不参与此证据绑定流程。 - 样本分析为文件结构生成精确指纹,解析方案保存同样的不可变结构定义;库存数据和文件名不参与判断。已发布方案的表头完全相同则返回 `exact`;方案实际使用的匹配/数量来源表头仍存在且仅有无关列变化时返回 `compatible` 并列出差异;所需栏位缺失、重复或冲突时不推荐复用。字段显示名称与真实表头标准化后完全相同时可确定性预填,其他陌生表头必须由管理员选择或 Dify 仅给候选。系统不得内置固定业务字段词典或自动创建字段。 -- 停用库存站点通过 `POST /api/admin/shipping-notice/sources/{id}/test-export` 写入 `configuration_test` trigger,Worker 完成后回调 `/api/shipping-notice/rpa/inventory-configuration-test-ready`。该文件只进入结构分析,不创建生产快照或任务链接;管理端轮询 `GET /sources/{id}/test-export/{run_no}` 并通过 `POST .../confirm-profile` 确认解析方案。Dify 不参与该流程。**身份契约**:`configuration_test` / `configuration_test_batch` 与 `scheduled` 同属按 run 计价模式,不携带订单 `task_no` / Attempt / Gate 等生产身份;Worker 不得对其做逐源 v2 身份 fail-closed(否则会误报 `trigger_identity_invalid` 并错误回调生产 `inventory-batch-ready`)。 -- **一期直接绑定**:停用站点可通过 `POST /api/admin/shipping-notice/sources/{id}/bind-parsing-profile` 直接绑定一个 `published` Profile;多站点使用 `POST /api/admin/shipping-notice/sources/bulk-bind-parsing-profile`。`reason` 是可选补充说明;未填写时,服务端自动记录直接或批量绑定动作。服务端先全量检查站点停用、方案已发布及当前 published 发货模板引用的全部库存字段均由方案提供,任一失败则整批不写入。成功后增加 `source.config_version`、写入 `shipping_inventory_source_parsing_binding_audits` 前后快照,但不触发 RPA、不产生快照、不启用站点。管理员可通过 `GET /sources/{id}/parsing-binding-audits` 追溯绑定。**Dify 手动配置说明**:一期不新增、修改或重新导入 Dify Tool/OpenAPI,不修改画布或 Prompt;上述管理 API 不供 Dify 调用。 -- **二期空库存验证**:Worker 将 `NoInventoryDataError` 作为 `status=empty` 回调,站点验证运行保存为 `completed_empty / empty_data_pending_validation`,而不是 `failed`。只有站点已绑定 `published` Profile 时,空结果才作为当前配置版本的连接/业务查询成功证据;否则仍失败,避免无解析定义时误放行。固定仓的空结果使 `configuration_test` 通过,`parsing_validation` 标为“待首次非空文件验证”但不阻断;动态仓仍阻断 `warehouse_identification`,因为空结果无法证明仓库识别和映射覆盖。定时 RPA 批量回调对 `skip_reason=no_inventory_data` 写入 `shipping_inventory_files.snapshot_status=empty`、`line_count=0` 的幂等审计快照;`find_latest_ready_snapshot`、任务链接与匹配链路只读取 `ready`,因此空快照绝不参与订单匹配或发货。**Dify 手动配置说明**:二期不新增、修改或重新导入 Dify Tool/OpenAPI,不修改画布或 Prompt;Dify 不读取站点验证或空快照状态。 +- 停用库存站点通过 `POST /api/admin/freight-rpa/sources/{id}/test-export` 写入 `configuration_test` trigger,Worker 完成后回调 `/api/freight-rpa/onhand-configuration-test-analyze`。该文件只进入结构分析,不创建生产快照或任务链接;管理端轮询 `GET /sources/{id}/test-export/{run_no}` 并通过 `POST .../confirm-profile` 确认解析方案。Dify 不参与该流程。**身份契约**:`configuration_test` / `configuration_test_batch` 与 `scheduled` 同属按 run 计价模式,不携带订单 `task_no` / Attempt / Gate 等生产身份;Worker 不得对其做逐源 v2 身份 fail-closed(否则会误报 `trigger_identity_invalid` 并错误回调生产 `onhand-batch-ready`)。 +- **一期直接绑定**:停用站点可通过 `POST /api/admin/freight-rpa/sources/{id}/bind-parsing-profile` 直接绑定一个 `published` Profile;多站点使用 `POST /api/admin/freight-rpa/sources/bulk-bind-parsing-profile`。`reason` 是可选补充说明;未填写时,服务端自动记录直接或批量绑定动作。服务端先全量检查站点停用、方案已发布及当前 published 发货模板引用的全部库存字段均由方案提供,任一失败则整批不写入。成功后增加 `source.config_version`、写入 `freight_rpa_onhand_source_parsing_binding_audits` 前后快照,但不触发 RPA、不产生快照、不启用站点。管理员可通过 `GET /sources/{id}/parsing-binding-audits` 追溯绑定。**Dify 手动配置说明**:一期不新增、修改或重新导入 Dify Tool/OpenAPI,不修改画布或 Prompt;上述管理 API 不供 Dify 调用。 +- **二期空库存验证**:Worker 将 `NoInventoryDataError` 作为 `status=empty` 回调,站点验证运行保存为 `completed_empty / empty_data_pending_validation`,而不是 `failed`。只有站点已绑定 `published` Profile 时,空结果才作为当前配置版本的连接/业务查询成功证据;否则仍失败,避免无解析定义时误放行。固定仓的空结果使 `configuration_test` 通过,`parsing_validation` 标为“待首次非空文件验证”但不阻断;动态仓仍阻断 `warehouse_identification`,因为空结果无法证明仓库识别和映射覆盖。定时 RPA 批量回调对 `skip_reason=no_inventory_data` 写入 `shipping_onhand_files.snapshot_status=empty`、`line_count=0` 的幂等审计快照;`find_latest_ready_snapshot`、任务链接与匹配链路只读取 `ready`,因此空快照绝不参与订单匹配或发货。**Dify 手动配置说明**:二期不新增、修改或重新导入 Dify Tool/OpenAPI,不修改画布或 Prompt;Dify 不读取站点验证或空快照状态。 - 库存站点详情的 `activation` 是 HXOPS 后端唯一的上线检查真相,返回 `ready` 与按配置顺序排列的 `checks[]`。每项包含稳定业务编号 `code`、`passed / pending / failed / stale` 状态、`blocking`、推荐 `action` 和非敏感 `evidence`;管理端只负责翻译与引导,不得根据表单值重算启用资格。`missing_requirements` 仅是由阻断 checks 派生的紧凑摘要。 - 管理端库存站点抽屉以“正式运行检查”状态轨道呈现 `checks[]`:已完成、待处理、失败/过期均同时提供图形与文本;每个阻断项至多提供一个推荐动作。测试导出留在站点抽屉,连接、解析、模板和仓库映射则跳转到对应维护区。若站点表单存在未保存修改,测试和启用操作必须禁用并提示先保存,禁止隐式保存或以旧配置发起测试。 - 配置测试、解析验证和仓库映射均绑定 `source.config_version` 与测试时的 `rpa_profile.config_version`。修改测试输入(库存站点配置、连接地址、登录方式或凭据)后,旧测试显示为 `stale` 且不能确认方案或启用;启用/停用仅改变运行状态,不使同一配置的已确认测试失效。尚未测试时,后续解析/仓库检查显示 `pending` 但不重复作为额外阻断项。动态仓 evidence 返回测试样例仓库;固定仓 evidence 返回当前固定仓与映射模式。任何 evidence 均不得包含 RPA 凭据、完整文件内容或内部路径。 - **Dify 手动配置说明**:本阶段无需新增、修改或重新导入 Dify Tool/OpenAPI,也无需修改画布或 Prompt。库存站点测试、结构检查、方案确认和启用均由管理端调用 HXOPS Admin API 完成;Dify 不读取或判断 `activation.checks`。 -- `GET /api/admin/shipping-notice/sources/{id}/test-export/latest` 只返回**当前站点配置和当前 RPA Profile 配置版本**对应的最近测试,无记录时返回 `null`。管理端打开站点抽屉时读取该接口恢复测试状态,只有 `awaiting_rpa / processing` 才轮询运行详情;关闭抽屉立即停止轮询。重复发起测试仅复用同一版本的运行任务,配置变更后的旧运行不会阻止新测试。 -- 批量测试创建时各站点先处于 `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 不读取此管理端状态接口。 +- `GET /api/admin/freight-rpa/sources/{id}/test-export/latest` 只返回**当前站点配置和当前 RPA Profile 配置版本**对应的最近测试,无记录时返回 `null`。管理端打开站点抽屉时读取该接口恢复测试状态,只有 `awaiting_rpa / processing` 才轮询运行详情;关闭抽屉立即停止轮询。重复发起测试仅复用同一版本的运行任务,配置变更后的旧运行不会阻止新测试。 +- 批量测试创建时各站点先处于 `awaiting_rpa / waiting_worker`。Windows Worker 实际领取某个站点前,会向 `POST /api/freight-rpa/onhand-configuration-test-start` 回调该站点的 `validation_run_no` 与受控阶段 `rpa_exporting`;后端仅允许将当前批次的非终态运行写为 `processing / rpa_exporting`。因此管理端可以区分“尚未被 Worker 领取”和“RPA 正在登录并导出”;最终成功、无库存或失败仍必须通过原有 `onhand-configuration-test-complete` 回调确认,进度回调不得覆盖终态。同一 Profile 仍只登录一次,但每个 DSV 站点使用新的页面并复用同一 browser context 的登录 Cookie,避免上一站报表 iframe、下载菜单或等待状态污染下一站。 +- 测试运行超过 `FREIGHT_RPA_ONHAND_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)。**收料 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 中复制完整映射。 +- **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__=inbound`(或报表名含 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 导出下载耗时。 +- 多个 Onhand Source 可绑定同一个 published Profile;同模板只维护一份。存在少量列差异时创建新 Profile 版本或新 Profile,不在 Source 中复制完整映射。 - 库存站点首次保存不要求绑定解析方案,且普通保存始终保持停用;后端仅允许通过独立启用接口进入正式运行。启用检查列出系统连接、库存文件解析方案、发货模板和测试导出与解析验证;确认后测试记录与站点当前配置版本绑定,后续编辑会使其失效。草稿、缺失或非法作用域字段仍阻断正式运行期自动解析。 -- 启用检查复用确认测试的结构记录,按当前方案实际映射的用途验证:至少一个匹配字段样例非空、唯一数量字段为数值;发货模板的全部库存字段必须由该方案提供。固定仓要求精确 `freight_warehouse_id` 映射或库存源默认映射;动态仓还要求唯一仓库识别字段且测试样例中每个仓库都有精确映射或默认映射。该检查只查询已维护的 `ShippingInventoryExternalMapping`,绝不自动创建映射。 -- 正式单票和批量 RPA 回调在创建/链接快照后、进入解析前调用 `inventory_structure_drift.validate_production_inventory_structure`。它以已绑定 published Profile 的格式、**指定工作表和表头行**、方案实际映射栏位作确定性比较,绝不采用分析器自动挑选的其他工作表:`exact` 放行;仅非关键栏位差异为 `compatible`,放行并写入 `schema_preview_json.structure_validation`;无候选方案或格式不一致抛出 `SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED`,回滚本次快照。放行后 `ingest_inventory_file` 显式接收 Profile 的 `field_mapping / sheet_name / header_row_index`,不得使用自动表头建议。 +- 启用检查复用确认测试的结构记录,按当前方案实际映射的用途验证:至少一个匹配字段样例非空、唯一数量字段为数值;发货模板的全部库存字段必须由该方案提供。固定仓要求精确 `freight_warehouse_id` 映射或库存源默认映射;动态仓还要求唯一仓库识别字段且测试样例中每个仓库都有精确映射或默认映射。该检查只查询已维护的 `ShippingOnhandExternalMapping`,绝不自动创建映射。 +- 正式单票和批量 RPA 回调在创建/链接快照后、进入解析前调用 `inventory_structure_drift.validate_production_inventory_structure`。它以已绑定 published Profile 的格式、**指定工作表和表头行**、方案实际映射栏位作确定性比较,绝不采用分析器自动挑选的其他工作表:`exact` 放行;仅非关键栏位差异为 `compatible`,放行并写入 `schema_preview_json.structure_validation`;无候选方案或格式不一致抛出 `SHIPPING.ONHAND_STRUCTURE_DRIFT_BLOCKED`,回滚本次快照。放行后 `ingest_inventory_file` 显式接收 Profile 的 `field_mapping / sheet_name / header_row_index`,不得使用自动表头建议。 - 正式库存快照因缓存行缺失而需要重读时,只能调用 `parse_inventory_snapshot_file`,并从快照所属已启用库存站点读取 published Profile;正式解析 API 已删除外部栏位映射、LLM 匹配说明和自动猜列表头参数。仅临时会话和管理员样本分析可产生候选建议,且其结果不能写入正式快照或库存站点绑定。 -- 管理端接口为 `POST /api/admin/shipping-notice/sources/{id}/activate` 与 `POST /api/admin/shipping-notice/sources/{id}/deactivate`。普通 `POST/PUT /sources` 只维护基础配置,不承担启停状态切换,避免在编辑报表参数时误使站点进入正式运行。 +- 管理端接口为 `POST /api/admin/freight-rpa/sources/{id}/activate` 与 `POST /api/admin/freight-rpa/sources/{id}/deactivate`。普通 `POST/PUT /sources` 只维护基础配置,不承担启停状态切换,避免在编辑报表参数时误使站点进入正式运行。 - 同编码新版本发布后不自动退役旧 published 版本;既有 Source 继续锁定原版本。管理员将全部 Source 显式迁移后,旧版本才允许退役。 - `parse_linked_inventory_file` 未显式传入映射时,从快照的 `source_code` 找到 Source 和绑定 Profile,使用发布定义确定性解析;LLM 不参与正常库存源文件判断与映射。 - 对话上传 `.xls/.xlsx/.csv` 且用户明确声明库存文件时,不会创建库存快照、不会自动确定库存源。后端先把它保存为当前用户和当前聊天会话隔离的“临时库存文件会话”,执行确定性结构初检;只有同时识别到料号和可用库存数量时,才作为库存候选交给后续受控映射建议流程。未知或不符合最低特征的文件明确拒绝,不能仅靠文件名或扩展名认定为库存文件。与之独立的任务级人工库存上传必须使用任务已确认库存站点绑定的 published 解析方案;结构一致后直接进入待匹配,结构漂移则完整回滚,不再产生任务级字段对齐确认。 @@ -1887,8 +1887,8 @@ GET /api/admin/shipping-order-schema/published-contract - 系统事实 `export_date` 按 `Asia/Shanghai` 获取实际导出日期,并由 `date_mmddyyyy` 格式化为 `MM/DD/YYYY`;它不依赖服务器所在时区。 - 发布时后端验证实际 Sheet、目标列冲突、字段有效性、格式化器和文件 checksum;发布后文件与定义不可变。管理端可点击“创建新版本”直接复制对象存储中的原 Excel 和映射定义创建草稿,不要求重新上传;只有 Excel 工作表、表头或版式发生变化时,才在草稿中替换模板文件。 - 模板原文件上传到平台私有 MinIO,数据库仅保存 provider/bucket/key 与 checksum;禁止本地模板静默 fallback。上传时验证真实 xlsx 和大小,事务失败补偿删除对象。 -- 生成时按 `task.inventory_source_code -> Inventory Source -> published Excel Template` 唯一确定模板,不再使用全局环境变量或空白工作簿 fallback。 -- Inventory Source 可先以 `enabled=false` 保存基础配置;启用前必须同时绑定 published 解析 Profile 与 published Excel Template。禁用 Source 的既有绑定同样必须先显式迁移,才能退役 Profile 或模板。 +- 生成时按 `task.inventory_source_code -> Onhand Source -> published Excel Template` 唯一确定模板,不再使用全局环境变量或空白工作簿 fallback。 +- Onhand Source 可先以 `enabled=false` 保存基础配置;启用前必须同时绑定 published 解析 Profile 与 published Excel Template。禁用 Source 的既有绑定同样必须先显式迁移,才能退役 Profile 或模板。 - 生成前使用解析 Profile `match_keys[]` 按稳定订单 `field_id -> inventory_field_id` 匹配库存行,订单和库存两侧均直接按字段 ID 取值;禁止按字段名称或数组顺序配对。零命中或模板所需库存字段冲突时阻断;模板引用库存字段必须存在于库存站点已绑定解析方案的 `field_mapping`。 - 每次生成新增 `ShippingExportArtifact`,锁定模板、订单 Schema/Extraction、库存解析 Profile、库存快照、输入 checksum、文件 checksum 和大小;新生成会 supersede 旧产物,下载只解析仍与 Task 当前导出引用一致的 ready Artifact。 - Dify 不选择模板、不传映射,仅在后端门禁允许时调用 `generate_shipment_excel`。 @@ -1922,7 +1922,7 @@ GET /api/admin/shipping-order-schema/published-contract # 自动推进 / 自动上传 # SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true -# SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true +# SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true # SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true # 是否在 match pass 后自动入队独立 artifact_generation Attempt(禁止在匹配 Attempt 内直跑 generate)。 # SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true @@ -1961,7 +1961,7 @@ GET /api/admin/shipping-order-schema/published-contract # SHIPPING_NOTICE_TASK_EXECUTION_MODE=worker # RPA 库存导出等待超时(秒,默认 900;DSV 实际链路建议至少 900) -# FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900 +# FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS=900 # 发货 worker 轮询间隔(秒) # SHIPPING_NOTICE_WORKER_POLL_SECONDS=2 @@ -1982,7 +1982,7 @@ GET /api/admin/shipping-order-schema/published-contract $env:HXOPS_API_BASE = "http://127.0.0.1:5052" $env:SHIPPING_NOTICE_TOOL_API_KEY = "your-tool-key" $env:FREIGHT_RPA_WORKER_MOCK = "true" -python scripts/freight_rpa/inventory/inventory_rpa_worker.py +python scripts/freight_rpa/onhand/onhand_rpa_worker.py ``` ### 1.5 库存导出 RPA 共享部署(Windows RPA + Ubuntu 后端) @@ -2012,18 +2012,18 @@ HXOPS 后端服务用户:hxops ```text 测试环境: -Windows RPA:C:\HxopsRpaTest\data\freight_rpa\inventory\triggers -Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers +Windows RPA:C:\HxopsRpaTest\data\freight_rpa\onhand\triggers +Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_rpa/onhand/triggers -Windows RPA:C:\HxopsRpaTest\data\freight_rpa\inventory\drop -Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_rpa/inventory/drop +Windows RPA:C:\HxopsRpaTest\data\freight_rpa\onhand\drop +Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_rpa/onhand/drop 正式环境: -Windows RPA:C:\HxopsRpaProd\data\freight_rpa\inventory\triggers -Ubuntu 后端:/mnt/hxops-rpa-prod-data/freight_rpa/inventory/triggers +Windows RPA:C:\HxopsRpaProd\data\freight_rpa\onhand\triggers +Ubuntu 后端:/mnt/hxops-rpa-prod-data/freight_rpa/onhand/triggers -Windows RPA:C:\HxopsRpaProd\data\freight_rpa\inventory\drop -Ubuntu 后端:/mnt/hxops-rpa-prod-data/freight_rpa/inventory/drop +Windows RPA:C:\HxopsRpaProd\data\freight_rpa\onhand\drop +Ubuntu 后端:/mnt/hxops-rpa-prod-data/freight_rpa/onhand/drop ``` Ubuntu 后端写 Linux 挂载路径,Windows RPA worker 读 Windows 本地路径;二者实际指向同一个 SMB 共享目录。测试与正式必须使用不同目录、不同共享、不同挂载点、不同 worker 任务名,避免测试任务误消费正式 trigger。 @@ -2038,36 +2038,36 @@ foreach ($root in @("C:\HxopsRpaTest", "C:\HxopsRpaProd")) { New-Item -ItemType Directory -Force "$root\scripts\freight_rpa" New-Item -ItemType Directory -Force "$root\backend\config" - New-Item -ItemType Directory -Force "$root\data\freight_rpa\inventory\triggers" - New-Item -ItemType Directory -Force "$root\data\freight_rpa\inventory\drop" - New-Item -ItemType Directory -Force "$root\data\freight_rpa\inventory\upload_triggers" - New-Item -ItemType Directory -Force "$root\data\freight_rpa\inventory\upload_queue" + New-Item -ItemType Directory -Force "$root\data\freight_rpa\onhand\triggers" + New-Item -ItemType Directory -Force "$root\data\freight_rpa\onhand\drop" + New-Item -ItemType Directory -Force "$root\data\freight_rpa\upload\triggers" + New-Item -ItemType Directory -Force "$root\data\freight_rpa\upload\queue" New-Item -ItemType Directory -Force "$root\data\freight_rpa\common\browser_profile" - New-Item -ItemType Directory -Force "$root\data\freight_rpa\inventory\logs" + New-Item -ItemType Directory -Force "$root\data\freight_rpa\onhand\logs" } ``` 从项目仓库复制以下文件到 Windows RPA 主机: ```text -scripts\freight_rpa\inventory\inventory_rpa_worker.py +scripts\freight_rpa\onhand\onhand_rpa_worker.py scripts\freight_rpa\connectors\dsv\dsv_report_parameters.py scripts\freight_rpa\connectors\dsv\dsv_login_smoke.py -scripts\freight_rpa\inventory\run_inventory_batch_trigger.py +scripts\freight_rpa\onhand\run_onhand_batch_trigger.py ``` 放置为: ```text -C:\HxopsRpaTest\scripts\freight_rpa\inventory\inventory_rpa_worker.py +C:\HxopsRpaTest\scripts\freight_rpa\onhand\onhand_rpa_worker.py C:\HxopsRpaTest\scripts\freight_rpa\connectors\dsv\dsv_report_parameters.py C:\HxopsRpaTest\scripts\freight_rpa\connectors\dsv\dsv_login_smoke.py -C:\HxopsRpaTest\scripts\freight_rpa\inventory\run_inventory_batch_trigger.py +C:\HxopsRpaTest\scripts\freight_rpa\onhand\run_onhand_batch_trigger.py -C:\HxopsRpaProd\scripts\freight_rpa\inventory\inventory_rpa_worker.py +C:\HxopsRpaProd\scripts\freight_rpa\onhand\onhand_rpa_worker.py C:\HxopsRpaProd\scripts\freight_rpa\connectors\dsv\dsv_report_parameters.py C:\HxopsRpaProd\scripts\freight_rpa\connectors\dsv\dsv_login_smoke.py -C:\HxopsRpaProd\scripts\freight_rpa\inventory\run_inventory_batch_trigger.py +C:\HxopsRpaProd\scripts\freight_rpa\onhand\run_onhand_batch_trigger.py ``` 不要复制 `.env*`、密码文件、`backend\data` 旧运行数据、浏览器 profile、旧 trigger / processed / failed 文件。 @@ -2140,12 +2140,12 @@ $env:FREIGHT_RPA_WORKER_HEADLESS = "false" # 不设 BROWSER_CHANNEL → Playwright Chromium;勿设 msedge。 $env:FREIGHT_RPA_WORKER_POLL_SECONDS = "3" -$env:FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR = "C:\HxopsRpaTest\data\freight_rpa\inventory\triggers" -$env:FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR = "C:\HxopsRpaTest\data\freight_rpa\inventory\drop" -$env:FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = "C:\HxopsRpaTest\data\freight_rpa\inventory\upload_triggers" -$env:FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = "C:\HxopsRpaTest\data\freight_rpa\inventory\upload_queue" +$env:FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR = "C:\HxopsRpaTest\data\freight_rpa\onhand\triggers" +$env:FREIGHT_RPA_SHARED_ONHAND_DROP_DIR = "C:\HxopsRpaTest\data\freight_rpa\onhand\drop" +$env:FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = "C:\HxopsRpaTest\data\freight_rpa\upload\triggers" +$env:FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = "C:\HxopsRpaTest\data\freight_rpa\upload\queue" $env:FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = "C:\HxopsRpaTest\data\freight_rpa\common\browser_profile" -$env:FREIGHT_RPA_WORKER_LOG_FILE = "C:\HxopsRpaTest\data\freight_rpa\inventory\logs\worker.log" +$env:FREIGHT_RPA_WORKER_LOG_FILE = "C:\HxopsRpaTest\data\freight_rpa\onhand\logs\worker.log" $env:FREIGHT_RPA_WORKER_LOG_MAX_BYTES = "10485760" $env:FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT = "5" $env:FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS = "7" @@ -2168,7 +2168,7 @@ $env:FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS = "20" #### 1.5.5a RPA Worker 心跳、共享 scope 与哨兵 -test/prod 触发库存 RPA 前,后端会检查 Worker 是否在线、环境是否匹配、共享目录是否有效。Windows Worker 需周期性 `POST /api/shipping-notice/rpa/heartbeat`,并在**库存 trigger 共享目录**(`FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR`,如 `...\data\freight_rpa\inventory\triggers`)写入哨兵文件 `.hxops_rpa_shared_mount`(默认文件名,可由 `FREIGHT_RPA_SHARED_SENTINEL_NAME` 覆盖)。 +test/prod 触发库存 RPA 前,后端会检查 Worker 是否在线、环境是否匹配、共享目录是否有效。Windows Worker 需周期性 `POST /api/freight-rpa/heartbeat`,并在**库存 trigger 共享目录**(`FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR`,如 `...\data\freight_rpa\onhand\triggers`)写入哨兵文件 `.hxops_rpa_shared_mount`(默认文件名,可由 `FREIGHT_RPA_SHARED_SENTINEL_NAME` 覆盖)。 | 侧 | 变量 | 测试示例 | 正式示例 | | --- | --- | --- | --- | @@ -2191,16 +2191,16 @@ test/prod 触发库存 RPA 前,后端会检查 Worker 是否在线、环境是 Worker 启动后验证哨兵(测试环境示例): ```powershell -Get-Content C:\HxopsRpaTest\data\freight_rpa\inventory\triggers\.hxops_rpa_shared_mount +Get-Content C:\HxopsRpaTest\data\freight_rpa\onhand\triggers\.hxops_rpa_shared_mount ``` 应包含 `scope_id=hxops-rpa-test-data`。Ubuntu 对应路径: ```bash -cat /mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers/.hxops_rpa_shared_mount +cat /mnt/hxops-rpa-test-data/freight_rpa/onhand/triggers/.hxops_rpa_shared_mount ``` -管理端 `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 会把收料工作台打爆)。 +管理端 `GET /api/admin/rpa-workers/status?scope=onhand|inbound` 可查看最后心跳;Worker 离线时触发库存 RPA 会立即失败(fail-fast),不再空等 900s。排程管理工作台的「RPA Worker 在线」徽标对该接口做 **10s 前台轮询**(库存 `freight-rpa-onhand` 与收料 `freight-rpa-inbound` 工作台;收料按 `*-inbound` 身份且与库存同口径要求共享哨兵;后台标签页暂停、请求未返回时跳过);执行记录列表按**历史查询**处理,仅切任务/点查询/重置时加载,不做定时自动刷新。「立即执行」等待期只轻量轮询任务 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` 时,调度器才会按冷却发送企微「心跳存储异常」告警(默认关闭)。 @@ -2216,10 +2216,10 @@ python scripts\freight_rpa\connectors\dsv\dsv_login_smoke.py SUCCESS — DSV session ready ``` -库存 RPA 必须由 HXOPS 管理端的 Inventory Source + RPA Profile 生成 trigger;如需人工联调,选取已生成的 trigger,执行: +库存 RPA 必须由 HXOPS 管理端的 Onhand Source + RPA Profile 生成 trigger;如需人工联调,选取已生成的 trigger,执行: ```powershell -python scripts\freight_rpa\inventory\run_inventory_batch_trigger.py +python scripts\freight_rpa\onhand\run_onhand_batch_trigger.py ``` 该入口不会读取 YAML 或本地账号密码,Profile 的密文凭据和页面操作均由平台生成的 trigger 提供。 @@ -2311,14 +2311,14 @@ ls -la /mnt/hxops-rpa-prod-data 用后端服务用户测试写入: ```bash -sudo -u hxops touch /mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers/ubuntu_write_test.txt -sudo -u hxops rm /mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers/ubuntu_write_test.txt +sudo -u hxops touch /mnt/hxops-rpa-test-data/freight_rpa/onhand/triggers/ubuntu_write_test.txt +sudo -u hxops rm /mnt/hxops-rpa-test-data/freight_rpa/onhand/triggers/ubuntu_write_test.txt -sudo -u hxops touch /mnt/hxops-rpa-prod-data/freight_rpa/inventory/triggers/ubuntu_write_test.txt -sudo -u hxops rm /mnt/hxops-rpa-prod-data/freight_rpa/inventory/triggers/ubuntu_write_test.txt +sudo -u hxops touch /mnt/hxops-rpa-prod-data/freight_rpa/onhand/triggers/ubuntu_write_test.txt +sudo -u hxops rm /mnt/hxops-rpa-prod-data/freight_rpa/onhand/triggers/ubuntu_write_test.txt ``` -测试文件应能分别在 Windows 的 `C:\HxopsRpaTest\data\freight_rpa\inventory\triggers` 与 `C:\HxopsRpaProd\data\freight_rpa\inventory\triggers` 中看到。 +测试文件应能分别在 Windows 的 `C:\HxopsRpaTest\data\freight_rpa\onhand\triggers` 与 `C:\HxopsRpaProd\data\freight_rpa\onhand\triggers` 中看到。 #### 1.5.8 Ubuntu 后端主机:开机自动挂载 @@ -2354,14 +2354,14 @@ Ubuntu 后端必须使用 Linux 挂载路径,不要写 Windows UNC 路径。 ```env 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 +SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true +SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED=true +FREIGHT_RPA_ONHAND_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 -FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/drop +FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/onhand/triggers +FREIGHT_RPA_SHARED_ONHAND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/onhand/drop FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue @@ -2433,7 +2433,7 @@ DSV/Crane 登录地址、账号和密码必须先在 HXOPS 管理端的 RPA Prof ```powershell powershell.exe -NoProfile -ExecutionPolicy Bypass -File ` - "C:\HxopsRpaTest\scripts\freight_rpa\inventory\start_inventory_worker.ps1" ` + "C:\HxopsRpaTest\scripts\freight_rpa\onhand\start_onhand_worker.ps1" ` -Environment test ` -ApiBase "http://:<端口>" ` -WorkerRoot "C:\HxopsRpaTest" ` @@ -2443,8 +2443,8 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File ` 若脚本来自网络或压缩包,先确认路径并按需解除文件阻止: ```powershell -Test-Path "C:\HxopsRpaTest\scripts\freight_rpa\inventory\start_inventory_worker.ps1" -Unblock-File "C:\HxopsRpaTest\scripts\freight_rpa\inventory\start_inventory_worker.ps1" +Test-Path "C:\HxopsRpaTest\scripts\freight_rpa\onhand\start_onhand_worker.ps1" +Unblock-File "C:\HxopsRpaTest\scripts\freight_rpa\onhand\start_onhand_worker.ps1" ``` `-ApiBase` 必须是 HXOPS 测试业务后端地址。`HXOPS_TOOLS_API_BASE`(例如 `:8890`)是 Tool API,不能填入 Worker 的 `-ApiBase`。如果使用 `http://192.168.100.192:5052`,必须先确认该地址确实是测试后端并可从 Windows Worker 访问: @@ -2459,7 +2459,7 @@ Invoke-WebRequest "http://192.168.100.192:5052/health" -UseBasicParsing 连通性确认后,也可以使用仓库原始命令: ```powershell -.\scripts\freight_rpa\inventory\start_inventory_worker.ps1 ` +.\scripts\freight_rpa\onhand\start_onhand_worker.ps1 ` -Environment test ` -ApiBase "http://测试后端:端口" ` -WorkerRoot "C:\HxopsRpaTest" ` @@ -2469,7 +2469,7 @@ Invoke-WebRequest "http://192.168.100.192:5052/health" -UseBasicParsing 手工启动 prod: ```powershell -C:\HxopsRpaProd\scripts\freight_rpa\inventory\start_inventory_worker.ps1 ` +C:\HxopsRpaProd\scripts\freight_rpa\onhand\start_onhand_worker.ps1 ` -Environment prod ` -ApiBase "http://正式后端:端口" ` -WorkerRoot "C:\HxopsRpaProd" ` @@ -2482,24 +2482,24 @@ C:\HxopsRpaProd\scripts\freight_rpa\inventory\start_inventory_worker.ps1 ` 1. Windows 手工打开 Edge,确认能访问 DSV/Crane。 2. Windows 执行 `python scripts\freight_rpa\connectors\dsv\dsv_login_smoke.py`。 3. 在管理端创建一个库存 RPA trigger,确认其包含 Source、Profile 和密文凭据。 -4. Ubuntu 执行 `sudo -u hxops touch /mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers/test_from_ubuntu.txt`,Windows 确认 `C:\HxopsRpaTest\data\freight_rpa\inventory\triggers` 能看到。 +4. Ubuntu 执行 `sudo -u hxops touch /mnt/hxops-rpa-test-data/freight_rpa/onhand/triggers/test_from_ubuntu.txt`,Windows 确认 `C:\HxopsRpaTest\data\freight_rpa\onhand\triggers` 能看到。 5. Windows 按当前方案执行 `start_rpa_worker.ps1`;不要直接运行 `freight_rpa_worker.py`。 -6. 确认哨兵:`Get-Content C:\HxopsRpaTest\data\freight_rpa\inventory\triggers\.hxops_rpa_shared_mount` 含正确 `scope_id`。 +6. 确认哨兵:`Get-Content C:\HxopsRpaTest\data\freight_rpa\onhand\triggers\.hxops_rpa_shared_mount` 含正确 `scope_id`。 7. HXOPS 管理端或 `GET /api/admin/rpa-workers/status` 显示 Worker 在线。 8. HXOPS 页面或排程触发库存 RPA 导出。 -9. Ubuntu 查看 trigger:`ls -lt /mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers`。 -10. Windows 查看 worker 输出;成功后 trigger 会进入 `C:\HxopsRpaTest\data\freight_rpa\inventory\triggers\processed`。 -11. Excel 会落到 `C:\HxopsRpaTest\data\freight_rpa\inventory\drop`,随后由后端回调流程入库为库存快照。 +9. Ubuntu 查看 trigger:`ls -lt /mnt/hxops-rpa-test-data/freight_rpa/onhand/triggers`。 +10. Windows 查看 worker 输出;成功后 trigger 会进入 `C:\HxopsRpaTest\data\freight_rpa\onhand\triggers\processed`。 +11. Excel 会落到 `C:\HxopsRpaTest\data\freight_rpa\onhand\drop`,随后由后端回调流程入库为库存快照。 12. HXOPS 任务应进入库存字段映射/库存匹配阶段;定时排程 run 应由 `awaiting_rpa_callback` 终态化为 `success` / `failed` / `partial_failed`。 #### 1.5.12 常见问题 -- Ubuntu `smbclient` 能访问,但后端写失败:用 `sudo -u hxops touch /mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers/test.txt` 测试后端服务用户权限,检查挂载参数中的 `uid/gid` 与 Windows 共享/NTFS 权限。 -- Windows worker 没反应:确认 worker 正在运行,测试环境 `FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR` 指向 `C:\HxopsRpaTest\data\freight_rpa\inventory\triggers`,正式环境指向 `C:\HxopsRpaProd\data\freight_rpa\inventory\triggers`,且后端真的把 JSON 写到了对应共享目录。 +- Ubuntu `smbclient` 能访问,但后端写失败:用 `sudo -u hxops touch /mnt/hxops-rpa-test-data/freight_rpa/onhand/triggers/test.txt` 测试后端服务用户权限,检查挂载参数中的 `uid/gid` 与 Windows 共享/NTFS 权限。 +- Windows worker 没反应:确认 worker 正在运行,测试环境 `FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR` 指向 `C:\HxopsRpaTest\data\freight_rpa\onhand\triggers`,正式环境指向 `C:\HxopsRpaProd\data\freight_rpa\onhand\triggers`,且后端真的把 JSON 写到了对应共享目录。 - worker 回调失败:确认 Windows 能访问 `HXOPS_API_BASE`,`SHIPPING_NOTICE_TOOL_API_KEY` 与后端一致,Ubuntu 防火墙允许 Windows 访问 HXOPS 端口。 - DSV/Crane 登录失败:先用 Windows Edge 手工登录,再跑 `dsv_login_smoke.py`;重点检查 MFA/验证码/SSO、企业代理、证书、账号密码。 - Ubuntu 重启后目录空了:执行 `sudo mount -a`,检查 `/etc/fstab`、网络是否已就绪、Windows 共享是否可访问。 -- 排程一直 running:检查对应环境的 `/mnt/hxops-rpa-*-data/freight_rpa/inventory/triggers/processed` 是否有对应 trigger、worker 日志是否回调 `/api/shipping-notice/rpa/inventory-batch-ready` 成功。 +- 排程一直 running:检查对应环境的 `/mnt/hxops-rpa-*-data/freight_rpa/onhand/triggers/processed` 是否有对应 trigger、worker 日志是否回调 `/api/freight-rpa/onhand-batch-ready` 成功。 #### 1.5.13 RPA 三环境部署与启停速查 @@ -2541,25 +2541,25 @@ $env:FREIGHT_RPA_WORKER_MOCK = "false" $env:FREIGHT_RPA_WORKER_HEADLESS = "false" # 不设 BROWSER_CHANNEL → Playwright Chromium;勿设 msedge。 $env:FREIGHT_RPA_WORKER_POLL_SECONDS = "3" -$env:FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR = Join-Path $rpaDataRoot "inventory\triggers" -$env:FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR = Join-Path $rpaDataRoot "inventory\drop" -$env:FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = Join-Path $rpaDataRoot "inventory\upload_triggers" -$env:FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = Join-Path $rpaDataRoot "inventory\upload_queue" +$env:FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR = Join-Path $rpaDataRoot "onhand\triggers" +$env:FREIGHT_RPA_SHARED_ONHAND_DROP_DIR = Join-Path $rpaDataRoot "onhand\drop" +$env:FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = Join-Path $rpaDataRoot "upload\triggers" +$env:FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = Join-Path $rpaDataRoot "upload\queue" $env:FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaDataRoot "common\browser_profile" -$env:FREIGHT_RPA_WORKER_LOG_FILE = Join-Path $rpaDataRoot "inventory\logs\worker.log" +$env:FREIGHT_RPA_WORKER_LOG_FILE = Join-Path $rpaDataRoot "onhand\logs\worker.log" -\.\scripts\freight_rpa\inventory\start_inventory_worker.ps1 -Environment test -ApiBase ":<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml" +.\scripts\freight_rpa\onhand\start_onhand_worker.ps1 -Environment test -ApiBase ":<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml" ``` 启动成功后,控制台会输出 `[freight_rpa_worker] started`,并持续轮询 trigger。另开一个 PowerShell 可检查日志和哨兵;本地未配置 shared scope 时不要求哨兵包含 test/prod scope: ```powershell -Get-Content "$rpaDataRoot\logs\worker.log" -Tail 100 -Wait -Get-ChildItem "$rpaDataRoot\inventory\triggers" -Get-ChildItem "$rpaDataRoot\inventory\drop" +Get-Content "$rpaDataRoot\onhand\logs\worker.log" -Tail 100 -Wait +Get-ChildItem "$rpaDataRoot\onhand\triggers" +Get-ChildItem "$rpaDataRoot\onhand\drop" ``` -在管理端发起一次测试导出,确认 trigger 被处理并且结果文件进入 `inventory_drop`。结束本地测试时,在运行 Worker 的窗口按 `Ctrl+C`;该方式只停止当前前台进程,不会修改用户级环境变量或创建自启动任务。 +在管理端发起一次测试导出,确认 trigger 被处理并且结果文件进入 `onhand drop`。结束本地测试时,在运行 Worker 的窗口按 `Ctrl+C`;该方式只停止当前前台进程,不会修改用户级环境变量或创建自启动任务。 ##### 1.5.13.2 Linux 测试服务器:部署、启动与停止 @@ -2575,16 +2575,16 @@ volumes: ```bash mountpoint -q /mnt/hxops-rpa-test-data -test -d /mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers +test -d /mnt/hxops-rpa-test-data/freight_rpa/onhand/triggers export COMPOSE_ENV_BASENAME=.env.test export COMPOSE_SHARED_ENV_BASENAME=.env.shared docker compose --env-file .env.test up -d hxops-backend hxops-kb-worker hxops-shipping-worker hxops-schedule-worker docker compose --env-file .env.test ps docker compose --env-file .env.test exec -T hxops-backend \ - sh -lc 'test -d /mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers && ls -ld /mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers' + sh -lc 'test -d /mnt/hxops-rpa-test-data/freight_rpa/onhand/triggers && ls -ld /mnt/hxops-rpa-test-data/freight_rpa/onhand/triggers' docker compose --env-file .env.test exec -T hxops-shipping-worker \ - sh -lc 'mountpoint -q /mnt/hxops-rpa-test-data && ls -ld /mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers' + sh -lc 'mountpoint -q /mnt/hxops-rpa-test-data && ls -ld /mnt/hxops-rpa-test-data/freight_rpa/onhand/triggers' ``` 随后在 Windows RPA 主机按 `1.5.5` 的 test 参数启动 Worker(`C:\HxopsRpaTest`、`FREIGHT_RPA_WORKER_ENVIRONMENT=test`、`FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data`)。确认 Windows 和 Linux 均能看到 `.hxops_rpa_shared_mount`,并在管理端的 RPA Worker 状态页确认 test Worker 在线后,再发起库存站点测试导出。 @@ -2613,16 +2613,16 @@ volumes: ```bash mountpoint -q /mnt/hxops-rpa-prod-data -test -d /mnt/hxops-rpa-prod-data/freight_rpa/inventory/triggers +test -d /mnt/hxops-rpa-prod-data/freight_rpa/onhand/triggers export COMPOSE_ENV_BASENAME=.env.prod export COMPOSE_SHARED_ENV_BASENAME=.env.shared docker compose --env-file .env.prod up -d hxops-backend hxops-kb-worker hxops-shipping-worker hxops-schedule-worker docker compose --env-file .env.prod ps docker compose --env-file .env.prod exec -T hxops-backend \ - sh -lc 'test -d /mnt/hxops-rpa-prod-data/freight_rpa/inventory/triggers && ls -ld /mnt/hxops-rpa-prod-data/freight_rpa/inventory/triggers' + sh -lc 'test -d /mnt/hxops-rpa-prod-data/freight_rpa/onhand/triggers && ls -ld /mnt/hxops-rpa-prod-data/freight_rpa/onhand/triggers' docker compose --env-file .env.prod exec -T hxops-shipping-worker \ - sh -lc 'mountpoint -q /mnt/hxops-rpa-prod-data && ls -ld /mnt/hxops-rpa-prod-data/freight_rpa/inventory/triggers' + sh -lc 'mountpoint -q /mnt/hxops-rpa-prod-data && ls -ld /mnt/hxops-rpa-prod-data/freight_rpa/onhand/triggers' ``` 再在 Windows RPA 主机启动正式 Worker:`C:\HxopsRpaProd`、`FREIGHT_RPA_WORKER_ENVIRONMENT=prod`、`FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data`。必须先验证哨兵内容、管理端 Worker 在线状态以及一笔受控正式导出,才允许启用正式排程。真实上传由配置驱动的 Playwright 流程执行:DSV 已确认从 Portal 首页 `My Applications > Upload Tool`(回退 `Apps > Upload Tool`)进入 `WMS Upload Tool > Upload`,由 `FREIGHT_RPA_WORKER_DSV_UPLOAD_ENTRY_URL` 指定受控 Portal 入口;`Browse` 的真实文件 input 是 `#file2`,选择文件后的真实提交控件为 `button.upload-button:has-text("Process File")`,DSV 默认使用这两个 selector。成功证据来自 `History`:同名文件行必须同时具有绿色 `em.fa.fa-circle.success-color.status-icon` 和非空 `Reference #`;该参考仅作为受信 RPA 成功回调的外部参考,不要求人工录入或上传回执。其他站点使用受控上传 URL;必须设置文件/提交/成功 selector,并保持 `FREIGHT_RPA_WORKER_UPLOAD_ENABLED=false`、`FREIGHT_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT=false`,直到测试环境完成非生产 dry-run 且确认成功标识语义。缺少配置、浏览器异常或未出现成功标识均回调失败,绝不把文件已选择视为上传成功。CRANE 上传页尚未确认,Worker 必须失败而不得复用 DSV 路径。由于尚未获得货代真实提交测试授权,生产仍须保持 `SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false`,以人工按业务单号确认已上传作为受控降级路径。 @@ -2744,7 +2744,7 @@ ui_state.actions -> 前端唯一可渲染的履约动作投影 needs_action ← pending_review / manual_upload_pending / failed / reparse_failed / Process Gate 阻断 / 待补信息 / 待客户确认 processing ← queued / layout_parsing / extracting / building_order / - inventory_matching / generating_excel / upload_rpa_* + onhand_matching / generating_excel / upload_rpa_* history ← completed / cancelled / 已查看历史失败 / 已被替代 ``` @@ -2787,11 +2787,11 @@ history ← completed / cancelled / 已查看历史失败 / 已被替代 5 candidate_creating 6 customer_resolving 7 duplicate_checking -8 inventory_source_resolving # 建单硬门禁:必须唯一可用 +8 onhand_source_resolving # 建单硬门禁:必须唯一可用 9 waiting_review 10 order_creating -11 inventory_fetching -12 inventory_matching +11 onhand_fetching +12 onhand_matching 13 excel_generating 14 freight_uploading 15 completed @@ -2958,11 +2958,11 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui - 上传成功 / 失败回执样例 - CRANE「Inbound Details」真实收料样本文件(用于建立异动解析规则的字段映射) -### 1.9 收料报表 RPA 共享部署(Windows RPA + Ubuntu 后端) +### 1.9 入站报表 RPA 共享部署(Windows RPA + Ubuntu 后端) -> 本节是收料报表 RPA(独立 Windows Worker)的部署手册,章节结构与 `1.5` 库存导出 RPA 对应。安全提示与 `1.5` 相同:示例中的 IP、账号、密码、API Key 均为占位符,请在各环境本地替换为实际值,**禁止将真实密码/密钥写入仓库或提交到 Git**。 -> 前置条件:已按 `1.5.2` 至 `1.5.10` 完成同一台 Windows RPA 主机、`hxops-rpa-test-data` / `hxops-rpa-prod-data` SMB 共享、Ubuntu 挂载与后端容器挂载。收料**不新建共享、不新建挂载**,只在既有共享下增加专用子目录、独立 Worker 与独立回调。 -> Worker 脚本层速查另见 [scripts/freight_rpa/README.md](../../../scripts/freight_rpa/README.md) 顶部「收料 RPA(独立 Worker)」;本节是部署权威来源。 +> 本节是**入站**(inbound,用户文案「入站」)报表 RPA 的部署手册,章节结构与 `1.5` 库存导出 RPA 对应。安全提示与 `1.5` 相同:示例中的 IP、账号、密码、API Key 均为占位符,请在各环境本地替换为实际值,**禁止将真实密码/密钥写入仓库或提交到 Git**。 +> 前置条件:已按 `1.5.2` 至 `1.5.10` 完成同一台 Windows RPA 主机、`hxops-rpa-test-data` / `hxops-rpa-prod-data` SMB 共享、Ubuntu 挂载与后端容器挂载。入站**不新建共享、不新建挂载**,只在既有共享下增加专用子目录、独立 Worker 与独立回调。工作台「收料文件」页已下线;接收人通过排程执行结果通知或 `inbound-raw-zip` 深链下载,**无** inbound notification_deliveries / 管理端「重发企微」。 +> Worker 脚本层速查另见 [scripts/freight_rpa/README.md](../../../scripts/freight_rpa/README.md) 顶部「入站 RPA(独立 Worker)」;本节是部署权威来源。 #### 1.9.1 与库存 RPA 的边界和目录规划 @@ -2976,25 +2976,25 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui | 项 | 库存 RPA | 收料 RPA | | --- | --- | --- | -| Worker | `scripts\freight_rpa\inventory\inventory_rpa_worker.py` | `scripts\freight_rpa\receipt\receipt_rpa_worker.py` | -| 启动脚本 | `inventory\start_inventory_worker.ps1` | `receipt\start_receipt_worker.ps1` | -| trigger 目录 | `data\freight_rpa\inventory\triggers` | `data\freight_rpa\receipt\triggers` | -| drop 目录 | `data\freight_rpa\inventory\drop` | `data\freight_rpa\receipt\drop` | -| 回调端点 | `/api/shipping-notice/rpa/inventory-batch-ready` | `/api/shipping-notice/rpa/receipt-batch-ready` | -| 心跳与哨兵 | 必需,触发前在线检查 fail-fast | 同库存口径:以 `<主机名>-receipt` 独立身份周期上报(ps1 注入 `FREIGHT_RPA_WORKER_ID`),`.hxops_rpa_shared_mount` 哨兵写入**收料** trigger 目录(ps1 注入 `FREIGHT_RPA_SHARED_SCOPE_ID`),触发前在线检查 fail-fast | +| Worker | `scripts\freight_rpa\onhand\onhand_rpa_worker.py` | `scripts\freight_rpa\inbound\inbound_rpa_worker.py` | +| 启动脚本 | `onhand\start_onhand_worker.ps1` | `inbound\start_inbound_worker.ps1` | +| trigger 目录 | `data\freight_rpa\onhand\triggers` | `data\freight_rpa\inbound\triggers` | +| drop 目录 | `data\freight_rpa\onhand\drop` | `data\freight_rpa\inbound\drop` | +| 回调端点 | `/api/freight-rpa/onhand-batch-ready` | `/api/freight-rpa/inbound-batch-ready` | +| 心跳与哨兵 | 必需,触发前在线检查 fail-fast | 同库存口径:以 `<主机名>-inbound` 独立身份周期上报(ps1 注入 `FREIGHT_RPA_WORKER_ID`),`.hxops_rpa_shared_mount` 哨兵写入**入站** trigger 目录(ps1 注入 `FREIGHT_RPA_SHARED_SCOPE_ID`),触发前在线检查 fail-fast | | 结果归属 | 库存快照/库存匹配 | MinIO 原样归档 + 企微投递,绝不进入库存链路 | 路径对应关系(测试环境;正式环境把 `Test` / `test-data` 换成 `Prod` / `prod-data`): ```text -Windows RPA:C:\HxopsRpaTest\data\freight_rpa\receipt\triggers -Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_rpa/receipt/triggers +Windows RPA:C:\HxopsRpaTest\data\freight_rpa\inbound\triggers +Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_rpa/inbound/triggers -Windows RPA:C:\HxopsRpaTest\data\freight_rpa\receipt\drop -Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_rpa/receipt/drop +Windows RPA:C:\HxopsRpaTest\data\freight_rpa\inbound\drop +Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_rpa/inbound/drop ``` -浏览器 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 同源双文件根因)。 +浏览器 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`)。每笔导出开始回调 `inbound-unit-progress`(`awaiting_rpa`→`processing`)。对齐库存:导出重试只覆盖落盘/校验;落盘成功后先轻量 `inbound-batch-progress` 抬升排程计数,再调 `inbound-batch-ready` 归档;ready 超时不得触发重新下载(2026-09-28 同源双文件根因)。 #### 1.9.2 Windows RPA 主机:部署收料 Worker @@ -3002,13 +3002,13 @@ Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_rpa/receipt/drop ```powershell foreach ($root in @("C:\HxopsRpaTest", "C:\HxopsRpaProd")) { - New-Item -ItemType Directory -Force "$root\data\freight_rpa\receipt\triggers" - New-Item -ItemType Directory -Force "$root\data\freight_rpa\receipt\drop" - New-Item -ItemType Directory -Force "$root\data\freight_rpa\receipt\logs" + New-Item -ItemType Directory -Force "$root\data\freight_rpa\inbound\triggers" + New-Item -ItemType Directory -Force "$root\data\freight_rpa\inbound\drop" + New-Item -ItemType Directory -Force "$root\data\freight_rpa\inbound\logs" } ``` -`receipt_rpa_worker.py` 启动时按「所在目录必须同时存在 `connectors/`、`common/`、`inventory/`、`receipt/` 子目录」定位 RPA 根目录,因此必须复制**整个** `scripts\freight_rpa`(首次部署 `1.5.2` 已覆盖;升级时同样整目录同步,保持 Worker、driver 与公共模块同一版本),不能只复制 `receipt\` 子目录。 +`inbound_rpa_worker.py` 启动时按「所在目录必须同时存在 `connectors/`、`common/`、`onhand/`、`inbound/` 子目录」定位 RPA 根目录,因此必须复制**整个** `scripts\freight_rpa`(首次部署 `1.5.2` 已覆盖;升级时同样整目录同步,保持 Worker、driver 与公共模块同一版本),不能只复制 `inbound\` 子目录。 依赖与 `1.5.4` 相同,另需 `cryptography`(解密 RPA Profile 加密凭据;库存 Worker 同样依赖,新增部署时两个 Worker 一起补齐): @@ -3022,24 +3022,24 @@ Secret 复用 `1.5.10` 创建的 `C:\HxopsRpaSecrets\test.xml` / `prod.xml`。 ```powershell powershell.exe -NoProfile -ExecutionPolicy Bypass -File ` - "C:\HxopsRpaTest\scripts\freight_rpa\receipt\start_receipt_worker.ps1" ` + "C:\HxopsRpaTest\scripts\freight_rpa\inbound\start_inbound_worker.ps1" ` -Environment test ` -ApiBase "http://:<端口>" ` -WorkerRoot "C:\HxopsRpaTest" ` -SecretFile "C:\HxopsRpaSecrets\test.xml" ``` -启动成功会输出 `[freight_receipt_rpa_worker] started` 独立行,后跟缩进字段块(` mock=...`、` api_base=...`、` trigger_dir=...`、` drop_dir=...`、` log=...` 等,完整字段以 `receipt_rpa_worker.py` 启动 banner 为准),随后轮询 `receipt_triggers` 下完整的 `.json` 触发文件。执行策略拦截、`Unblock-File`、UTF-8 BOM 要求均与 `1.5.10` 相同(`start_receipt_worker.ps1` 同样必须保持 UTF-8 BOM,从仓库原样复制)。 +启动成功会输出 `[freight_inbound_rpa_worker] started` 独立行,后跟缩进字段块(` mock=...`、` api_base=...`、` trigger_dir=...`、` drop_dir=...`、` log=...` 等,完整字段以 `inbound_rpa_worker.py` 启动 banner 为准),随后轮询 inbound `triggers` 下完整的 `.json` 触发文件。执行策略拦截、`Unblock-File`、UTF-8 BOM 要求均与 `1.5.10` 相同(`start_inbound_worker.ps1` 同样必须保持 UTF-8 BOM,从仓库原样复制)。 -启动脚本同时自动注入两个 Worker 运行变量:`FREIGHT_RPA_WORKER_LOG_FILE`(ps1 自动设为 `data\freight_rpa\receipt\logs\worker.log`,文件日志带时间戳并按大小轮转,无需手工配置)与 `FREIGHT_RPA_WORKER_ID=<主机名>-receipt`(独立心跳身份,监控端按此身份出独立收料卡片,不与库存 Worker 的 `<主机名>-inventory` 混淆;两个身份均由各自 ps1 注入 `FREIGHT_RPA_WORKER_ID`,重启不漂移)。收料 Worker 的文件日志、启动 banner、心跳上报与周期磁盘保留清理(含共享 Profile 的孤儿 `receipt_*`)能力均已与库存 Worker 对齐;两个 Worker 禁止共写同一日志文件,各自由启动脚本指向各自域目录(库存 `inventory\logs`、收料 `receipt\logs`)下的 `worker.log`。 +启动脚本同时自动注入两个 Worker 运行变量:`FREIGHT_RPA_WORKER_LOG_FILE`(ps1 自动设为 `data\freight_rpa\inbound\logs\worker.log`,文件日志带时间戳并按大小轮转,无需手工配置)与 `FREIGHT_RPA_WORKER_ID=<主机名>-inbound`(独立心跳身份,监控端按此身份出独立入站卡片,不与库存 Worker 的 `<主机名>-onhand` 混淆;两个身份均由各自 ps1 注入 `FREIGHT_RPA_WORKER_ID`,重启不漂移)。入站 Worker 的文件日志、启动 banner、心跳上报与周期磁盘保留清理(含共享 Profile 的孤儿 `inbound_*`)能力均已与库存 Worker 对齐;两个 Worker 禁止共写同一日志文件,各自由启动脚本指向各自域目录(库存 `onhand\logs`、入站 `inbound\logs`)下的 `worker.log`。 -后台常驻沿用 `1.5.10` 的「`AtLogOn + Interactive`、每环境独立任务」模式,注册脚本已交付:`scripts\freight_rpa\receipt\register_receipt_worker_tasks.ps1`(test/prod 双任务,任务名 `HXOPS Receipt RPA Worker TEST/PROD`,与库存注册脚本同构、相互独立)。收料 Worker 由启动脚本注入 `FREIGHT_RPA_WORKER_LOG_FILE`,文件日志写入 `data\freight_rpa\receipt\logs\worker.log`(tee 控制台、带时间戳、按大小轮转);计划任务仍可用 `cmd.exe` 包装对控制台输出做重定向留档: +后台常驻沿用 `1.5.10` 的「`AtLogOn + Interactive`、每环境独立任务」模式,注册脚本已交付:`scripts\freight_rpa\inbound\register_inbound_worker_tasks.ps1`(test/prod 双任务,任务名 `HXOPS Freight Inbound RPA Worker TEST/PROD`,与库存注册脚本同构、相互独立)。收料 Worker 由启动脚本注入 `FREIGHT_RPA_WORKER_LOG_FILE`,文件日志写入 `data\freight_rpa\inbound\logs\worker.log`(tee 控制台、带时间戳、按大小轮转);计划任务仍可用 `cmd.exe` 包装对控制台输出做重定向留档: ```powershell $TestApiBase = "http://:<端口>" $ReceiptAction = New-ScheduledTaskAction ` -Execute "cmd.exe" ` - -Argument "/c powershell.exe -NoProfile -ExecutionPolicy Bypass -File ""C:\HxopsRpaTest\scripts\freight_rpa\receipt\start_receipt_worker.ps1"" -Environment test -ApiBase ""$TestApiBase"" -WorkerRoot ""C:\HxopsRpaTest"" -SecretFile ""C:\HxopsRpaSecrets\test.xml"" >> ""C:\HxopsRpaTest\data\freight_rpa\receipt\logs\receipt_console_output.log"" 2>&1" ` + -Argument "/c powershell.exe -NoProfile -ExecutionPolicy Bypass -File ""C:\HxopsRpaTest\scripts\freight_rpa\inbound\start_inbound_worker.ps1"" -Environment test -ApiBase ""$TestApiBase"" -WorkerRoot ""C:\HxopsRpaTest"" -SecretFile ""C:\HxopsRpaSecrets\test.xml"" >> ""C:\HxopsRpaTest\data\freight_rpa\inbound\logs\receipt_console_output.log"" 2>&1" ` -WorkingDirectory "C:\HxopsRpaTest" # $Trigger / $Principal / $Settings 与 1.5.10 的库存任务完全一致: # AtLogOn + Interactive;RestartCount 10、RestartInterval 1 分钟、ExecutionTimeLimit 0、MultipleInstances IgnoreNew。 @@ -3053,59 +3053,59 @@ Register-ScheduledTask -TaskName "HXOPS Receipt RPA Worker TEST" -Action $Receip `.env.test` 在 `1.5.9` 基础上追加(正式环境把路径换成 `/mnt/hxops-rpa-prod-data/...`): ```env -# 收料 RPA 共享目录(与 Windows Worker 的 data\freight_rpa\receipt 属同一 SMB 共享的子路径) -FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/triggers -FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/drop +# 收料 RPA 共享目录(与 Windows Worker 的 data\freight_rpa\inbound 属同一 SMB 共享的子路径) +FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/triggers +FREIGHT_RPA_SHARED_INBOUND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/drop # 收料排程等待回调超时(秒);超时回收为 RPA.RECEIPT_CALLBACK_TIMEOUT,不自动重试 -FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS=900 +FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS=900 ``` -> ⚠️ **最容易漏的一步**:不配置这两个目录变量时,后端默认写容器本地 `backend/data/freight_rpa/receipt/*`,Windows 共享盘永远看不到 trigger,单元会一直等到超时回收。 +> ⚠️ **最容易漏的一步**:不配置这两个目录变量时,后端默认写容器本地 `backend/data/freight_rpa/inbound/*`,Windows 共享盘永远看不到 trigger,单元会一直等到超时回收。 容器 bind mount **无需新增**:收料目录位于既有 `/mnt/hxops-rpa-*data` 共享的子路径下,`hxops-backend`、`hxops-schedule-worker` 按 `1.5.9` 挂载后即已覆盖;修改 `.env` 后按惯例重建相关容器。 归档与通知依赖: - 收料文件在回调时**原样上传 MinIO**(`shipping/receipt-reports/{年}/{月}/{单元}/{sha256}.xlsx`),保留三年;MinIO 不可用时该单元回调失败,不落成功态。 -- 到期对象由平台排程任务 **货代收料归档到期清理**(`freight-receipt-rpa-retention`)删除,建议在排程管理配置每日一次;它只删除过期对象,不删除运行、文件事实与审计记录。 +- 到期对象由平台排程任务 **货代收料归档到期清理**(`freight-rpa-inbound-retention`)删除,建议在排程管理配置每日一次;它只删除过期对象,不删除运行、文件事实与审计记录。 - 企微通知与库存排程**同一出口同一门禁**(`scheduler_service._notify_schedule_run_wecom`,2026-09-21 统一;2026-09-28 起附件改为 ZIP):收料 run 全部单元终态归集后**一次性**发送 textcard 汇总(`schedule_completed` 事件)+ **汇总结果 Excel** `收料RPA-{yyyyMMdd}-{HHmm}-结果.xlsx`(2026-10-12 对齐库存补齐;列头 收料源/仓库/连接器/归档文件数/导出状态/跳过原因/错误原因,`empty→skipped`、`cancelled→failed` 与卡片计数同口径,导出失败降级 success→partial_failed 并记 `excel_export_status/excel_failed`)+ **一个**原始收料包 `收料RPA-{yyyyMMdd}-{HHmm}-收料.zip`(包内 `{序号}_{source_code}.xlsx` + `manifest.json`,磁盘键 `{run_no}.zip`);不再逐文件推送。Worker 落盘名为 `receipt_{batch_run_no}_{source_code}_{warehouse_or_NA}_{stamp}.xlsx`。接收人取排程任务的 `notify_user_ids` + `notify_enabled`,且必须已完成企微绑定;排障查 `schedule_runs.wecom_notified / wecom_notify_error`。管理员重发(`/receipt-report-files/{id}/resend`)保留为补偿通道,不触发 RPA,投递失败记 `WECOM_USER_UNBOUND`。 -排程创建:管理端「排程管理」新增平台任务 **货代收料 RPA**(`freight-receipt-rpa`),可选参数 `source_codes` 留空则执行全部已启用站点中已配置收料的站点,按需配置 Cron 与接收人。收料排程与库存排程相互独立(站点、Cron、接收人分别选择)。收料触发前执行**与库存同口径**的 Worker 在线 fail-fast 检查(`assert_receipt_rpa_worker_ready`:心跳 TTL + 收料 trigger 目录哨兵 + scope 匹配,2026-09-30 起对齐):Worker 离线、哨兵缺失(含漏配 `FREIGHT_RPA_SHARED_SCOPE_ID`)或 scope 不符时排程立即 failed(`RPA.WORKER_OFFLINE`),不再空等 `FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS`(默认 900 秒)超时回收。上线后仍应按 `1.9.4` 验收并保留 `data\freight_rpa\receipt\logs\worker.log` 巡检。 +排程创建:管理端「排程管理」新增平台任务 **货代入站 RPA**(`freight-rpa-inbound`),可选参数 `source_codes` 留空则执行全部已启用站点中已配置入站的站点,按需配置 Cron 与接收人。入站排程与库存排程相互独立(站点、Cron、接收人分别选择)。入站触发前执行**与库存同口径**的 Worker 在线 fail-fast 检查(`assert_inbound_rpa_worker_ready`:心跳 TTL + 入站 trigger 目录哨兵 + scope 匹配,2026-09-30 起对齐):Worker 离线、哨兵缺失(含漏配 `FREIGHT_RPA_SHARED_SCOPE_ID`)或 scope 不符时排程立即 failed(`RPA.WORKER_OFFLINE`),不再空等 `FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS`(默认 900 秒)超时回收。上线后仍应按 `1.9.4` 验收并保留 `data\freight_rpa\inbound\logs\worker.log` 巡检。 #### 1.9.4 端到端验证 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`; + - `ls /mnt/hxops-rpa-test-data/freight_rpa/inbound/triggers` 出现 `inbound_export_batch_{run_no}.json`; - Worker 领取后文件进入同目录 `processing/`,全部单元处理完进入 `processed/`(契约级失败进 `failed/`); - - `receipt_drop` 出现 `receipt_{callback_id}_{时间戳}.xlsx`; - - 回调 `/api/shipping-notice/rpa/receipt-batch-ready` 成功,单元 `success`,MinIO 出现归档对象; - - 接收人企微一次性收到 textcard 汇总与全部收料文件消息(与库存排程同一出口),工作台「收料文件」可查看并下载。 + - inbound drop 出现 `inbound_{run}_{source}_{wh}_{stamp}.xlsx`; + - 回调 `/api/freight-rpa/inbound-batch-ready` 成功,单元 `success`,MinIO 出现归档对象; + - 接收人企微一次性收到 textcard 汇总与原始入站包(与库存排程同一出口);排程管理执行记录可下载 `inbound-raw-zip`(企微深链 `raw_zip=1` 时突出下载入口)。 4. 失败路径:制造一个失败单元(如停用对应 RPA Profile),确认排程终态 `failed` / `partial_failed`、管理端失败单元可查、带原因重试生成新单元且以 `retry_of_id` 关联旧单元;通知重发不触发重新导出。 -5. 隔离确认:收料文件不出现在 `inventory_drop`,不产生任何 `ShippingInventoryFile` / 库存快照 / 库存匹配记录。 +5. 隔离确认:收料文件不出现在 `onhand drop`,不产生任何 `ShippingOnhandFile` / 库存快照 / 库存匹配记录。 #### 1.9.5 常见问题 -- trigger 长时间无人消费:收料 Worker 未启动;两端 `FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR` 不一致;或后端未配置变量、写到了容器本地默认路径(见 `1.9.3` 的告警)。 +- trigger 长时间无人消费:收料 Worker 未启动;两端 `FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR` 不一致;或后端未配置变量、写到了容器本地默认路径(见 `1.9.3` 的告警)。 - 回调 401/403:Worker `X-Integration-Key` 与该环境 `SHIPPING_NOTICE_TOOL_API_KEY` 不一致,或 `-ApiBase` 未按 `1.5.10` 的网关口径填写。 - 回调报 `SHIPPING.RECEIPT_CALLBACK_FILE_INVALID`:`file_path` 不在收料 drop 根内、非 `.xlsx`、空文件或超过 `FILE_ASSET_MAX_SIZE_MB`;多为收料/库存目录串用所致。 -- 单元长期 `awaiting_rpa`、排程停在 `awaiting_receipt_rpa_callback`:Worker 停止或崩溃;超过 `FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS` 由回收逻辑置 `RPA.RECEIPT_CALLBACK_TIMEOUT`,**不自动重试**,需管理员带原因重试或等下一轮 Cron。 +- 单元长期 `awaiting_rpa`、排程停在 `awaiting_receipt_rpa_callback`:Worker 停止或崩溃;超过 `FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS` 由回收逻辑置 `RPA.RECEIPT_CALLBACK_TIMEOUT`,**不自动重试**,需管理员带原因重试或等下一轮 Cron。 - DBS/Crane 登录或导出失败:先在 Windows 手工登录确认 MFA/SSO/代理;Crane 无论 Profile 首页保存为何,Worker 均强制进入 `#/inbound-details-query` 用页面默认条件执行;确认 Profile 已启用且 `FREIGHT_RPA_CREDENTIAL_KEY` 两端一致(否则无法解密凭据)。 -- `receipt_drop` 磁盘占用增长:收料 Worker 已启用周期磁盘保留清理(启动 + 周期各一轮,清收料 processed/failed/drop 与共享 Profile 的孤儿 `run_*`/`receipt_*`);如需更早释放仍可人工清理,建议保留最近几天便于排障。 -- 其余排障顺序与 `1.5.12` 一致:先看 Worker 控制台 / `data\freight_rpa\receipt\logs\worker.log`,再看两端目录与共享挂载,最后看后端日志与收料审计事件。 +- inbound drop 磁盘占用增长:入站 Worker 已启用周期磁盘保留清理(启动 + 周期各一轮,清入站 processed/failed/drop 与共享 Profile 的孤儿 `run_*`/`inbound_*`);如需更早释放仍可人工清理,建议保留最近几天便于排障。 +- 其余排障顺序与 `1.5.12` 一致:先看 Worker 控制台 / `data\freight_rpa\inbound\logs\worker.log`,再看两端目录与共享挂载,最后看后端日志与收料审计事件。 #### 1.9.6 收料 RPA 三环境速查 | 运行位置 | 后端目录/环境 | Worker 目录与环境 | 说明 | | --- | --- | --- | --- | -| Windows 本地联调 | 本地后端;默认 `backend/data/freight_rpa/receipt/*` | 当前项目 `scripts/freight_rpa/receipt/`;`dev` | 不连 test/prod、不用 test/prod Key;`-Mock` 可全链路演练 | -| Linux 测试服务器 | `/mnt/hxops-rpa-test-data/freight_rpa/receipt/*`;`.env.test` | `C:\HxopsRpaTest\data\freight_rpa\receipt`;`test` | 与库存测试共用同一 SMB 共享与挂载 | -| Linux 正式服务器 | `/mnt/hxops-rpa-prod-data/freight_rpa/receipt/*`;`.env.prod` | `C:\HxopsRpaProd\data\freight_rpa\receipt`;`prod` | 测试真实链路验收通过后再开启正式排程 | -| `FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR` | dev `data/freight_rpa/receipt/triggers`;test `/mnt/hxops-rpa-test-data/freight_rpa/receipt/triggers`;prod `/mnt/hxops-rpa-prod-data/freight_rpa/receipt/triggers` | 与后端同一物理目录(test `C:\HxopsRpaTest\data\freight_rpa\receipt\triggers`;prod `C:\HxopsRpaProd\data\freight_rpa\receipt\triggers`) | 本地联调两端默认一致,无需配置 | -| `FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR` | dev `data/freight_rpa/receipt/drop`;test `/mnt/hxops-rpa-test-data/freight_rpa/receipt/drop`;prod `/mnt/hxops-rpa-prod-data/freight_rpa/receipt/drop` | 与后端同一物理目录(test `C:\HxopsRpaTest\data\freight_rpa\receipt\drop`;prod `C:\HxopsRpaProd\data\freight_rpa\receipt\drop`) | 本地联调两端默认一致,无需配置 | +| Windows 本地联调 | 本地后端;默认 `backend/data/freight_rpa/inbound/*` | 当前项目 `scripts/freight_rpa/inbound/`;`dev` | 不连 test/prod、不用 test/prod Key;`-Mock` 可全链路演练 | +| Linux 测试服务器 | `/mnt/hxops-rpa-test-data/freight_rpa/inbound/*`;`.env.test` | `C:\HxopsRpaTest\data\freight_rpa\inbound`;`test` | 与库存测试共用同一 SMB 共享与挂载 | +| Linux 正式服务器 | `/mnt/hxops-rpa-prod-data/freight_rpa/inbound/*`;`.env.prod` | `C:\HxopsRpaProd\data\freight_rpa\inbound`;`prod` | 测试真实链路验收通过后再开启正式排程 | +| `FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR` | dev `data/freight_rpa/inbound/triggers`;test `/mnt/hxops-rpa-test-data/freight_rpa/inbound/triggers`;prod `/mnt/hxops-rpa-prod-data/freight_rpa/inbound/triggers` | 与后端同一物理目录(test `C:\HxopsRpaTest\data\freight_rpa\inbound\triggers`;prod `C:\HxopsRpaProd\data\freight_rpa\inbound\triggers`) | 本地联调两端默认一致,无需配置 | +| `FREIGHT_RPA_SHARED_INBOUND_DROP_DIR` | dev `data/freight_rpa/inbound/drop`;test `/mnt/hxops-rpa-test-data/freight_rpa/inbound/drop`;prod `/mnt/hxops-rpa-prod-data/freight_rpa/inbound/drop` | 与后端同一物理目录(test `C:\HxopsRpaTest\data\freight_rpa\inbound\drop`;prod `C:\HxopsRpaProd\data\freight_rpa\inbound\drop`) | 本地联调两端默认一致,无需配置 | -收料 trigger/drop 目录必须与 Windows 收料 Worker 上 `start_receipt_worker.ps1` 读取的同名变量指向**同一物理目录**;目录内子结构(processing/processed/failed)由统一契约管理,见 `scripts/freight_rpa/README.md`。 +收料 trigger/drop 目录必须与 Windows 收料 Worker 上 `start_inbound_worker.ps1` 读取的同名变量指向**同一物理目录**;目录内子结构(processing/processed/failed)由统一契约管理,见 `scripts/freight_rpa/README.md`。 Windows 本地联调(项目根目录 PowerShell;本地后端默认目录与 Worker 指向一致,无需配置目录变量): @@ -3116,13 +3116,94 @@ Windows 本地联调(项目根目录 PowerShell;本地后端默认目录与 $env:HXOPS_API_BASE = "http://127.0.0.1:5052" $env:SHIPPING_NOTICE_TOOL_API_KEY = "<与本地后端一致>" $env:FREIGHT_RPA_WORKER_MOCK = "true" -$receiptRoot = Join-Path (Get-Location).Path "backend\data\freight_rpa" -$env:FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $receiptRoot "receipt\triggers" -$env:FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $receiptRoot "receipt\drop" -python scripts/freight_rpa/receipt/receipt_rpa_worker.py +$inboundRoot = Join-Path (Get-Location).Path "backend\data\freight_rpa" +$env:FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR = Join-Path $inboundRoot "inbound\triggers" +$env:FREIGHT_RPA_SHARED_INBOUND_DROP_DIR = Join-Path $inboundRoot "inbound\drop" +python scripts/freight_rpa/inbound/inbound_rpa_worker.py ``` -真实本地导出(`MOCK=false`)还需受控注入 `FREIGHT_RPA_CREDENTIAL_KEY` 并设置 `FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR`;排程下发的真实 trigger 均含加密凭据,Mock 消费真实 trigger 时同样需要该密钥。也可改用启动脚本 `.\scripts\freight_rpa\receipt\start_receipt_worker.ps1 -Environment test -ApiBase "http://127.0.0.1:5052" ...`(需先按 `1.5.10` 生成本地 Secret 文件)。 +真实本地导出(`MOCK=false`)还需受控注入 `FREIGHT_RPA_CREDENTIAL_KEY` 并设置 `FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR`;排程下发的真实 trigger 均含加密凭据,Mock 消费真实 trigger 时同样需要该密钥。也可改用启动脚本 `.\scripts\freight_rpa\inbound\start_inbound_worker.ps1 -Environment test -ApiBase "http://127.0.0.1:5052" ...`(需先按 `1.5.10` 生成本地 Secret 文件)。 + +### 1.10 出站报表 RPA 共享部署(Windows RPA + Ubuntu 后端) + +> 本节是**出站**(outbound,在途调拨语境)报表 RPA 的部署手册,结构与 `1.9` 入站对称。术语见 `docs/features/freight-rpa/GLOSSARY.md`。**不承载**发货履约「出货」与 upload 域;**无** outbound notification_deliveries、**无**工作台出站文件页(运维走排程 + `outbound-raw-zip` 深链,与入站瘦身一致)。 + +#### 1.10.1 与库存/入站 RPA 的边界和目录规划 + +**与 `1.5` / `1.9` 复用**:同一 Windows RPA 主机、SMB 共享与 Ubuntu 挂载、DPAPI Secret、`FREIGHT_RPA_CREDENTIAL_KEY`、`-ApiBase` 网关口径、trigger 四态契约与 fail-fast(心跳 TTL + trigger 目录哨兵 + `FREIGHT_RPA_SHARED_SCOPE_ID`)。 + +**出站专用**: + +| 项 | 入站 RPA | 出站 RPA | +| --- | --- | --- | +| Worker | `inbound\inbound_rpa_worker.py` | `outbound\outbound_rpa_worker.py` | +| 启动脚本 | `inbound\start_inbound_worker.ps1` | `outbound\start_outbound_worker.ps1` | +| trigger / drop | `freight_rpa\inbound\{triggers,drop}` | `freight_rpa\outbound\{triggers,drop}` | +| 回调 | `/api/freight-rpa/inbound-batch-ready` 等 | `/api/freight-rpa/outbound-batch-ready` 等 | +| 心跳身份 | `<主机名>-inbound` | `<主机名>-outbound` | +| 事实分发 | `report_kind=inbound` | `report_kind=outbound` → `handle_outbound_report` | +| 排程 | `freight-rpa-inbound` | `freight-rpa-outbound`(归档清理 `freight-rpa-outbound-retention`) | + +路径示例(test;prod 换 `prod-data` / `HxopsRpaProd`): + +```text +Windows:C:\HxopsRpaTest\data\freight_rpa\outbound\triggers +Ubuntu:/mnt/hxops-rpa-test-data/freight_rpa/outbound/triggers + +Windows:C:\HxopsRpaTest\data\freight_rpa\outbound\drop +Ubuntu:/mnt/hxops-rpa-test-data/freight_rpa/outbound/drop +``` + +Crane 出站固定 **Outbound Details**;DBS 路径/查询与入站同构(日期不得出现在查询条件)。回调 `file_path` **只认 drop 根内文件名**(跨机 Windows 绝对路径须在后端取 `.name` 再拼 `FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR`)。 + +**Crane 导航整页刷新禁令(2026-10-20)**:Crane 门户登录态不随整页加载恢复(人工实测:登录后点浏览器刷新即掉登录),登录态下 `goto` 根地址 / `reload` 等于强制登出。`crane_navigation.navigate_to_crane_report` 的首页卡片/Queries 菜单目标由 `entry_url` 推导(On Hand / Inbound / Outbound Details 通用,禁止再硬编码 On Hand);direct goto 后先轮询表单就绪(SPA 换页有渲染间隙,瞬时判定会误判失败),兜底只允许就地 `window.location.hash` 赋值;`crane_report_export._refresh_scheduled_reports_list` 的 `reload` 兜底已替换为就地重赋 hash。出站死循环(登录→on-hand→整页刷新→登出反复)即由「导航硬编码 On Hand + goto 后瞬时判定失败即 goto 根地址」叠加触发。 + +#### 1.10.2 Windows:部署出站 Worker + +目录初始化(与入站并列,不共用 trigger/drop/logs): + +```powershell +foreach ($root in @("C:\HxopsRpaTest", "C:\HxopsRpaProd")) { + New-Item -ItemType Directory -Force "$root\data\freight_rpa\outbound\triggers" + New-Item -ItemType Directory -Force "$root\data\freight_rpa\outbound\drop" + New-Item -ItemType Directory -Force "$root\data\freight_rpa\outbound\logs" +} +``` + +须同步**整个** `scripts\freight_rpa`(含 `outbound/`、`inbound/`、`onhand/`、`connectors/`、`common/`)。启动示例: + +```powershell +powershell.exe -NoProfile -ExecutionPolicy Bypass -File ` + "C:\HxopsRpaTest\scripts\freight_rpa\outbound\start_outbound_worker.ps1" ` + -Environment test ` + -ApiBase "http://:<端口>" ` + -WorkerRoot "C:\HxopsRpaTest" ` + -SecretFile "C:\HxopsRpaSecrets\test.xml" +``` + +常驻任务脚本:`scripts\freight_rpa\outbound\register_outbound_worker_tasks.ps1`(与入站/库存任务并存)。日志默认 `data\freight_rpa\outbound\logs\worker.log`。 + +#### 1.10.3 Ubuntu 后端:环境变量与排程 + +`.env.test` / `.env.prod` 在入站变量旁追加(路径与 Windows 同一 SMB 子树): + +```env +FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/outbound/triggers +FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/outbound/drop +FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/outbound/archives +# 可选;默认 900,超时回收 RPA.OUTBOUND_CALLBACK_TIMEOUT,不自动重试 +FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS=900 +``` + +> ⚠️ 漏配 `FREIGHT_RPA_SHARED_OUTBOUND_*` 时后端会写容器本地 `data/freight_rpa/outbound/*`,Windows Worker 看不到 trigger。 + +排程:平台任务 **货代出站 RPA**(`freight-rpa-outbound`),参数 `source_codes` 可选;写 trigger 前 `assert_outbound_rpa_worker_ready` fail-fast。归档到期清理注册 **货代出站归档到期清理**(`freight-rpa-outbound-retention`)。在途调拨缺出站文件时可按需触发同一出站 RPA(与入站 trigger 对称,来源隔离)。 + +#### 1.10.4 端到端验证(摘要) + +1. 管理端「来源站点」配置**出站报表**与 published `purpose=outbound` 解析绑定;DBS/Crane 约束同 API(`SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID` / `SHIPPING.OUTBOUND_PROFILE_INVALID`)。 +2. `-Mock` 启动出站 Worker → 手工执行 `freight-rpa-outbound` → 确认 trigger 消费、回调、`report_kind=outbound` 事实、MinIO 归档、企微汇总与 `outbound-raw-zip` 下载。 +3. 失败单元:排程管理带原因重试(`SHIPPING.OUTBOUND_RETRY_REASON_REQUIRED`);回调文件/sha 类错误见四语言 `SHIPPING.OUTBOUND_CALLBACK_*` / `RPA.OUTBOUND_*`。 *** @@ -3247,7 +3328,7 @@ python scripts/freight_rpa/receipt/receipt_rpa_worker.py - **短缺放行后的单条自动履约(2026-08-26)**:单条 `release_inventory_shortage` 成功后仅入队既有 auto-fulfill Job;Worker 确认当前恰有一条开放且可履约的明细时,创建独立 `ShippingNotice` 并排程其 Excel。若有多条开放明细,系统不自动合并,用户仍须勾选后创建 wave;暂不提供批次放行。前端写入成功即关闭确认弹窗并重启处理投影轮询,后续只读刷新不阻塞操作。 - **短缺放行后任务级状态重算(2026-08-26)**:`release_inventory_shortage` 是对"库存满足性"Gate 的受控业务事实。放行回写后,任务级履约态必须按同一放行语义重算,否则会出现"Excel 已生成、任务却仍显示 `unfulfillable`/`shortage_review`/缺货"的矛盾。为此:① 放行决定与满足性/聚合重算共用 `_released_line_keys_for_task`(只认活动放行决定);② `_recompute_task_match_aggregate` 对已放行的缺口行视同满足(`line_status='released'`,不计入缺货),与 `match_completed` 语义对齐;③ 放行回写 `_sync_confirmed_task_fulfillment_gates` 与库存满足性复核 `recheck_inventory_sufficiency` 在确有匹配行事实时调用 `recompute_task_fulfillment_state`,同步 `match_status`/`line_results_json`/`shortage_json`/`review_status`/`pending_human_reason` 并应用对应迁移(`MATCHED_FULFILLABLE` / `MATCH_SHORTAGE`)。空事实任务不重算,避免被误标为缺货。 - **异常中断/恢复的旧状态残留统一清理(2026-08-26)**:除放行外,其余"中断恢复后未重算任务级状态"路径统一按"失效即清空派生状态、强制下轮重匹配"处理:① `inventory_loaded_response`(库存快照复用/重载)与 `inventory_mapping_workflow` 在载入新库存后清空 task 及其同库存文件关联任务的 `match_status`/`line_results_json`/`shortage_json`;② `recovery_invalidation_service.invalidate_inventory_downstream` 对 `retry_inventory_from_field_mapping`/`retry_inventory_from_matching` 同样清空匹配派生字段(仅库存文件级重试才清导出指针);③ `retry_task` 重试前清空旧匹配结果,强制 orchestr 重匹配而非带旧缺货跳过;④ `decision_workflow._request_formal_gate_action` 请求正式 Gate 前清除 review/pending/error 残留(原为 return 后不可达的死代码)。 -- **工作台详情/货代上传面板查询数优化(2026-08-26)**:单票详情(`/shipping-tasks/`)与货代上传面板首屏曾耗时约 12s,根因是 `build_task_ui_state` 的高单次成本被重复/循环放大。已修复:① detail 请求不再同一请求内重复投影 `build_task_ui_state`(`serialize_task_detail` 直接透传 `include_stage_context`,去掉被覆盖的内层调用);② 货代上传面板聚合对每个同 PO Notice 不再跑完整 `build_task_ui_state`,改用轻量 `project_notice_available_actions` 只返回已授权动作码;③ `serialize_process_execution` 在会话读缓存缺失时批量预取本 Execution 的 LatestAttempt(`latest_attempt_by_id`)与 `gates_by_execution_id`,消除 `serialize_process_gate` 逐 Gate 的 `query.get()` N+1;④ `project_inventory_candidate_facts` 批量预取当前匹配行引用的库存快照(`ShippingInventoryFile`),消除逐行 `sess.get()` N+1。 +- **工作台详情/货代上传面板查询数优化(2026-08-26)**:单票详情(`/shipping-tasks/`)与货代上传面板首屏曾耗时约 12s,根因是 `build_task_ui_state` 的高单次成本被重复/循环放大。已修复:① detail 请求不再同一请求内重复投影 `build_task_ui_state`(`serialize_task_detail` 直接透传 `include_stage_context`,去掉被覆盖的内层调用);② 货代上传面板聚合对每个同 PO Notice 不再跑完整 `build_task_ui_state`,改用轻量 `project_notice_available_actions` 只返回已授权动作码;③ `serialize_process_execution` 在会话读缓存缺失时批量预取本 Execution 的 LatestAttempt(`latest_attempt_by_id`)与 `gates_by_execution_id`,消除 `serialize_process_gate` 逐 Gate 的 `query.get()` N+1;④ `project_inventory_candidate_facts` 批量预取当前匹配行引用的库存快照(`ShippingOnhandFile`),消除逐行 `sess.get()` N+1。 - **Gate 恢复的统一页面同步(2026-08-26)**:所有正式 OT Gate 恢复在服务端受理后立即解除交互等待,后台刷新任务详情、Case 与处理投影,并重启五阶段轮询及会话级刷新;不得等待只读请求完成才恢复按钮,也不得依赖浏览器手动刷新显示 Worker 推进结果。 - **库存 RPA 超时恢复(2026-08-25)**:`inventory_rpa_timeout` / `inventory_rpa_exhausted` 的主动作是 `reload_inventory_result`,仅复用既有有效库存快照并重新挂接,不写 trigger、不新建 RPA Attempt;若未找到结果,保持原阻断并将“重新获取库存(RPA)”作为用户显式备用动作。 - **人工复核**:Case/Draft 版本冲突、确认建单幂等;确认后复用 `auto_progress`;布局重构完成(见 layout-plan §11)。 @@ -3424,7 +3505,7 @@ API 层 | `backend/tests/test_shipping_inventory_routing_engine.py` | 通用路由规则引擎单测 | | `backend/tests/test_shipping_notice_inventory_schedule.py` | 定时批量库存 RPA 排程 executor 单测 | | `backend/tests/test_shipping_notice_match_summary.py` | 匹配摘要相关测试 | -| `scripts/freight_rpa/inventory/inventory_rpa_worker.py` | 开发态 RPA worker(支持单条/批量 inventory_export) | +| `scripts/freight_rpa/onhand/onhand_rpa_worker.py` | 开发态 RPA worker(支持单条/批量 inventory_export) | --- @@ -3432,11 +3513,11 @@ API 层 ### 6.1 数据库主数据 -- `ShippingInventorySource` 是业务主键;`connector_type` 仅允许 `dbs` / `crane`。 +- `ShippingOnhandSource` 是业务主键;`connector_type` 仅允许 `dbs` / `crane`。 - `ShippingRpaProfile` 保存登录 URL、加密凭据和连接级登录配置;同一 connector 可配置多个 Profile。 -- `ShippingInventorySource` 保存 DBS 报表路径和查询参数;订单到库存站点的选择只由已发布路由规则决定,Source 不再维护第二套识别别名。Driver 选择器、下载方式和等待策略不得作为业务配置入库。 +- `ShippingOnhandSource` 保存 DBS 报表路径和查询参数;订单到库存站点的选择只由已发布路由规则决定,Source 不再维护第二套识别别名。Driver 选择器、下载方式和等待策略不得作为业务配置入库。 - 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。 +- 外部系统仓库映射保存在 `freight_rpa_onhand_external_mappings`:货代仓库(`freight_warehouse_id`)为可选维度——`inventory_match` 源按「收料文件仓库列 == 货代仓库」匹配映射行,空值即「空库位」默认映射行;在途仓编码(`in_transit_warehouse_code`)为在途调拨拨出库位来源(保存端必填)。发货链路仍按精确 `source + warehouse` 优先、随后回退 Source 默认映射查询;调拨链路(拨出库位)口径见 docs/features/in-transit-transfer/technical.md §1。 ### 6.2 库存站点启用与可选测试 @@ -3458,25 +3539,25 @@ API 层 - Trigger action:`inventory_export_batch`;按 `connector_type` 分组,DSV/Crane 各登录一次 - **每个 source 导出前**:DSV 首源 `_ensure_dsv_session` 完整登录一次;后续源复用当前 tab 登录态——同 navigation 用 `_return_to_dsv_report_parameters` 复用参数页(返回 True 则跳过菜单导航),导航不同**直接在当前页开 Reports 菜单导航(不再整页 goto 首页,省 ~12s 并避开 public/login 一闪)**;导航失败时 `_navigate_dsv_to_report_form` 内部整页回首页重置后重试一次。**批内不得每源新开页面/重复走 OAuth**(2026-08-26 修复:曾因"每源新开空白页 + 写死 index=0"导致每源重复 SSO 重定向 2-2.5 分钟且偶发 OAuth 空白页单源失败);仅当会话疑似失效(login/session/oauth 异常)时,新开干净页面重试一次完整登录。Crane 调用 `_reset_crane_export_entry` - **按需单票**:`write_inventory_export_trigger_for_task`;batch 开启时包装为单源 batch trigger(与定时共用 worker 路径) -- **单票 legacy 路径**:`_download_dsv360_inventory` / `_download_crane_inventory` 已委托 `_export_*_inventory_source`,与批量共用 `parameters` 填充 +- **单票路径**:`_download_dsv360_onhand` 与 `_export_crane_onhand_source` 与批量共用 `parameters` 填充;DSV 批量导出函数仍为 `_export_dsv_inventory_source` - **multi_select**:worker `_fill_dsv_multi_select` 支持多选控件(非仅取第一个值) - **报表控件模板**(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` +- Worker:`scripts/freight_rpa/onhand/onhand_rpa_worker.py` → `_handle_onhand_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` -- **回调响应语义**(2026-08):HTTP 回调只做信封校验、成功 Excel 从 RPA shared drop 复制到 HXOPS 受控 `rpa_callback_receipts//`、创建 `shipping_inventory_callback_process` Job 后立即返回 `status=ok` + 顶层/`data.result_status=accepted`。它**不得**在 HTTP 请求中做 Excel 结构校验、库存行解析、快照/任务关联或 Gate 自动推进;这些业务步骤只由 shipping worker 消费 Job 后执行。这样 Worker 的 30 秒 HTTP 等待只代表“平台已收件”,不再把实际导出成功误判为 callback timeout。Job 的最终 `callback_result.result_status` 才是 `success` / `partial_failed` / `failed`;排程场景(含 `schedule_run_id` 且 finalize 成功)由该异步结果终态化 `ScheduleRun`。worker 回调 payload 顶层含 `status`、`success`(legacy)、`has_success`、`success_count`、`skipped_count`、`failed_count`、`results[]`(每项含 `status`)。 +- 回调:`POST /api/freight-rpa/onhand-batch-ready` +- **回调响应语义**(2026-08):HTTP 回调只做信封校验、成功 Excel 从 RPA shared drop 复制到 HXOPS 受控 `rpa_callback_receipts//`、创建 `freight_rpa_onhand_callback_process` Job 后立即返回 `status=ok` + 顶层/`data.result_status=accepted`。它**不得**在 HTTP 请求中做 Excel 结构校验、库存行解析、快照/任务关联或 Gate 自动推进;这些业务步骤只由 shipping worker 消费 Job 后执行。这样 Worker 的 30 秒 HTTP 等待只代表“平台已收件”,不再把实际导出成功误判为 callback timeout。Job 的最终 `callback_result.result_status` 才是 `success` / `partial_failed` / `failed`;排程场景(含 `schedule_run_id` 且 finalize 成功)由该异步结果终态化 `ScheduleRun`。worker 回调 payload 顶层含 `status`、`success`(legacy)、`has_success`、`success_count`、`skipped_count`、`failed_count`、`results[]`(每项含 `status`)。 - **单票身份与失败收口**(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) +- 定时排程:`schedule_type=platform_job`,`platform_api_path=freight-rpa-onhand`,`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` 记账完全一致;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。 +- **收料 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_INBOUND_ARCHIVE_DIR`(默认 `freight_rpa/inbound/archives`);管理端 `GET /schedule-runs//receipt-raw-zip`。 +- **空快照状态约束**(2026-08-26):`create_empty_rpa_inventory_snapshot` 写入 `snapshot_status='empty'`(no_inventory_data 审计快照),依赖迁移 `hq0r1s2t3u4v` 把 `ck_shipping_onhand_files_snapshot_status` 检查约束从 `('ready','failed','expired')` 放宽为含 `'empty'`;未执行该迁移(或回退版本)时,批量回调插入空快照会触发 CheckViolation 导致整笔 Job 事务回滚、ScheduleRun 停在 awaiting 后被超时回收为 failed。 ### 6.5 审计字段 -- `shipping_inventory_files`:`warehouse_id`、`source_code`、`exported_at`、`expires_at`、`rpa_run_no`、`schedule_run_id`、`identity_status` -- `shipping_task_inventory_links`:`link_reason`、`matched_source_code`、`matched_warehouse_id`、`snapshot_age_seconds`、`audit_payload_json`、身份校验字段 +- `shipping_onhand_files`:`warehouse_id`、`source_code`、`exported_at`、`expires_at`、`rpa_run_no`、`schedule_run_id`、`identity_status` +- `shipping_task_onhand_links`:`link_reason`、`matched_source_code`、`matched_warehouse_id`、`snapshot_age_seconds`、`audit_payload_json`、身份校验字段 ### 6.6 订单解析阶段库存源判定(2026-07) @@ -3493,7 +3574,7 @@ API 层 - **人工确认已上传例外(2026-08-26)**:`upload_to_freight(mode=manual_confirm)` 不经过库存源稳定性校验——人工确认是"外部已上传、服务端登记",不触发 RPA、不依赖库存源;只有 `auto/retry_upload`(RPA 路径)在触发前校验库存源。 - **稳定性判定收窄(2026-08-26)**:`is_inventory_source_stable` 只校验任务实际命中 Source 的必要事实(状态 ∈ {resolved, candidates_frozen}、Source 存在且启用、connector_type 一致、fixed 仓一致;多候选冻结时各候选源存在且启用)。**不再**比对全局配置版本 hash 或路由指纹——无关库存源的改动、订单头字段漂移不再使已有任务失效;`inventory_source_config_changed` 同步只对"选中源自身不可用/驱动变化"返回 True。 6. **快照复用键**:`find_latest_ready_snapshot(source_code, warehouse_id)`;link 时做 identity check。 -7. **迁移**:`2b3c4d5e6f7a_add_shipping_inventory_configuration`、`3c4d5e6f7a8b_remove_shipping_inventory_site_id`、`4c5d6e7f8a9_add_dynamic_inventory_snapshot_idempotency`。 +7. **迁移**:`2b3c4d5e6f7a_add_shipping_inventory_configuration`、`3c4d5e6f7a8b_remove_shipping_inventory_site_id`、`4c5d6e7f8a9_add_dynamic_onhand_snapshot_idempotency`。 ### 6.7 字段分层、冻结策略与 Reservation 注册(目标态修订 2026-07-29) @@ -3740,21 +3821,21 @@ Case 状态:`unreviewed`、`draft`、`ready`、`confirming`、`confirmed`、`n - 嵌套标注采用固定语义层级:明细字段高于物理行容器,表头只展示列级字段,不显示内部表头行容器。物理行内部不吞掉字段点击,管理员通过物理行标签、边缘或已选中的缩放手柄操作父区域。 # 独立收料报表 RPA -收料不进入库存快照、匹配或 ERP 链路,也没有独立启停字段:是否运行统一由库存站点 `enabled` 与配置是否存在决定。站点的一对一 `ShippingReceiptReportConfig` 保存收料路径与受控查询条件;`ShippingReceiptRpaUnitRun` 保存每次冻结单元与重试关系(按需触发无排程时 `schedule_run_id` 为 NULL);`ShippingReceiptReportFile` 保存原样对象、SHA-256、到期和删除事实;`ShippingReceiptNotificationDelivery` 保存管理员重发通道的投递幂等事实(正常通知自 2026-09-21 起走通用排程出口,由 `schedule_runs.wecom_notified` 记账)。 +收料不进入库存快照、匹配或 ERP 链路,也没有独立启停字段:是否运行统一由库存站点 `enabled` 与配置是否存在决定。站点的一对一 `ShippingInboundReportConfig` 保存收料路径与受控查询条件;`ShippingInboundRpaUnitRun` 保存每次冻结单元与重试关系(按需触发无排程时 `schedule_run_id` 为 NULL);`ShippingInboundReportFile` 保存原样对象、SHA-256、到期和删除事实;`ShippingInboundNotificationDelivery` 保存管理员重发通道的投递幂等事实(正常通知自 2026-09-21 起走通用排程出口,由 `schedule_runs.wecom_notified` 记账)。 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`。 ### 可靠性、补偿与审计边界 - trigger 采用“同目录临时文件写完、`fsync` 后 `os.replace` 原子发布”方式;收料 Worker 只能 claim 完整的 `.json`,不得读取半写入 trigger。 -- `awaiting_receipt_rpa` 运行受 `FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS`(默认 `900`,可由部署配置覆盖)限制。超时回收将仍 pending/running 的单元标记为 `failed/RPA.RECEIPT_CALLBACK_TIMEOUT`,结束排程并写前后快照审计;**不自动重试、不自动重发**,后续 Cron 或管理员人工补偿可继续执行。 +- `awaiting_receipt_rpa` 运行受 `FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS`(默认 `900`,可由部署配置覆盖)限制。超时回收将仍 pending/running 的单元标记为 `failed/RPA.RECEIPT_CALLBACK_TIMEOUT`,结束排程并写前后快照审计;**不自动重试、不自动重发**,后续 Cron 或管理员人工补偿可继续执行。 - Worker 启动及常规扫描均回收超时运行,避免服务或 Worker 重启后运行永久占用排程状态。 - 空结果、Worker 失败、归档成功、对象删除失败、企微文件/汇总投递成功或失败、管理员查看失败单元、人工重试和重发均写追加式 `ShippingAuditEvent`。审计包含操作人/时间/对象、结果、脱敏原因或错误码、变更前后状态;不得写入密码、Cookie、令牌、对象存储定位或浏览器会话。 - 管理员失败单元查询仅返回运行诊断所需的站点、Warehouse、状态、错误码/脱敏错误和时间;接收人不拥有该查询、配置、重试或重发权限。 ### 管理、接收人与接口 -- 管理员在既有“货代管理 → 库存站点”抽屉维护独立收料卡;统一「保存更改」先调用库存 Source 保存接口、再调用 `PUT /api/admin/shipping-notice/sources/{source_id}/receipt-report-config`(仅当站点已有收料配置或本次展开并填写过收料卡时提交),两接口字段边界互不穿透,收料保存不改动库存路径、条件或版本。 +- 管理员在既有“货代管理 → 库存站点”抽屉维护独立收料卡;统一「保存更改」先调用库存 Source 保存接口、再调用 `PUT /api/admin/freight-rpa/sources/{source_id}/inbound-report-config`(仅当站点已有收料配置或本次展开并填写过收料卡时提交),两接口字段边界互不穿透,收料保存不改动库存路径、条件或版本。 - 接收人通过“工作台 → 收料文件”调用 `GET /api/workspace/receipt-report-files?limit=100` 查看本人排程归档;列表不返回 bucket、object key 或凭据。下载仍经 `GET /api/workspace/receipt-report-files/{file_id}/download` 再次鉴权并记录审计。 - 管理员的失败单元重试和通知重发接口分别为 `POST /api/admin/receipt-rpa-units/{unit_id}/retry`、`POST /api/admin/receipt-report-files/{file_id}/resend`;二者均只产生新的可审计事实,前者不覆盖旧单元,后者不重新导出。 @@ -3762,14 +3843,14 @@ DBS/Crane 收料排程与库存 RPA 同口径:**选中 N 个库存源 → N | 接口 | 权限 | 关键请求/响应约束 | 审计 | | --- | --- | --- | --- | -| `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/admin/freight-rpa/sources/{source_id}/inbound-report-config` | 管理员 | 返回独立收料路径与查询条件;不返回凭据 | 配置读取沿用管理端访问链路 | +| `PUT /api/admin/freight-rpa/sources/{source_id}/inbound-report-config` | 管理员 | body 仅 `report_path_json/query_parameters_json`;DBS 查询条件可选(空=页面默认,不作为单元门禁);日期/selector 拒绝;Crane 固定 `Inbound Details`,拒绝全部查询条件;Worker 无论 Profile 登录 URL 的原 hash,均强制进入 `#/inbound-details-query` 并使用页面默认条件执行 | `shipping_inbound_report_config_saved`,含前后快照 | +| `POST /api/freight-rpa/inbound-batch-ready` | 收料 Worker | 仅 `freight_rpa.inbound.v1`;`file_path` 必须在 inbound drop 根且为 `.xlsx`;校验大小、SHA-256 | 归档、通知、排程终态均保留事实 | +| `GET /api/workspace/receipt-report-files` | 管理员或排程接收人 | 当前用户授权过滤后再应用 `limit`;不泄露对象存储定位 | `freight_rpa_inbound_report_files_listed` | | `GET /api/workspace/receipt-report-files/{file_id}/download` | 管理员或对应接收人 | 原样下载;过期对象或无权限拒绝 | 成功/拒绝均记录下载审计 | -| `POST /api/admin/receipt-rpa-units/{unit_id}/retry` | 管理员 | 仅 `failed/cancelled`,必填 `reason` | `shipping_receipt_rpa_unit_retried` | -| `POST /api/admin/receipt-report-files/{file_id}/resend` | 管理员 | 仅重发归档文件企微消息,不触发 RPA | `shipping_receipt_report_notification_resent` | -| `GET /api/admin/receipt-rpa-units?status=failed` | 管理员 | 只查询失败单元,供人工补偿;不返回凭据、对象键或 trigger 内容 | `shipping_receipt_rpa_units_listed` | +| `POST /api/admin/receipt-rpa-units/{unit_id}/retry` | 管理员 | 仅 `failed/cancelled`,必填 `reason` | `shipping_inbound_rpa_unit_retried` | +| `POST /api/admin/receipt-report-files/{file_id}/resend` | 管理员 | 仅重发归档文件企微消息,不触发 RPA | `shipping_inbound_report_notification_resent` | +| `GET /api/admin/receipt-rpa-units?status=failed` | 管理员 | 只查询失败单元,供人工补偿;不返回凭据、对象键或 trigger 内容 | `shipping_inbound_rpa_units_listed` | # 2026-08-29 库存源自动探测与数据自证(一期) @@ -3816,7 +3897,7 @@ inventory_preparation Gate ## 既有能力与契约(不新增开关) -- 沿用 `SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED` 总开关与既有批次开关;无新增配置开关。 +- 沿用 `SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED` 总开关与既有批次开关;无新增配置开关。 - RPA Worker 无需修改(batch v2 契约已支持多源逐源身份)。 - 存量终态/已 `uploaded` 通知零影响;非终态停挡单首次进入工作台自动探测续跑(老单治愈)。 - 无强制数据迁移:行级覆写复用候选行 `override_by_id/override_reason`;歧义状态入匹配结果 JSON/行决定。 @@ -3838,8 +3919,8 @@ inventory_preparation Gate - 正式字段编辑走既有 `task_workflow.update_notice_fields` / `update_notice_line` / `add_notice_line` / `remove_notice_line`(不新增 Case 状态);写路径保留 `_assert_order_data_version` 乐观锁(409 语义不变)。 - **新增编辑窗守卫**:`_edit_window_busy_error`——订单任一通知有活动 Gate Attempt(库存 RPA / 匹配 queued|running)时返回 `SHIPPING.EDIT_WINDOW_SYSTEM_BUSY`(「系统处理中,请稍后再修改」);活动 Attempt 结束后恢复可编辑。 - **失效分类重跑**:沿用 Schema `task_edit_policy.change_effect` → `_apply_notice_edit_change_effects`: - - 头部路由字段 → `rerun_inventory_source_resolution`:清候选/匹配/导出、`clear_inventory_source_confirmation`、重裁库存源、OT 同步 `inventory_fetching`(快照复用,无新 RPA 当快照可用)。 - - 行字段(料号/数量/预约号)→ `rerun_inventory_matching`:仅清匹配并 OT 同步 `inventory_matching`。 + - 头部路由字段 → `rerun_inventory_source_resolution`:清候选/匹配/导出、`clear_inventory_source_confirmation`、重裁库存源、OT 同步 `onhand_fetching`(快照复用,无新 RPA 当快照可用)。 + - 行字段(料号/数量/预约号)→ `rerun_inventory_matching`:仅清匹配并 OT 同步 `onhand_matching`。 - 导出相关 → `regenerate_excel`;需重解析 → `require_revision`。 - 无路由引用 → `none`(仅保存 + `order_data_version` 递增 + 审计)。 - 被失效的匹配结果/缺口标记 superseded,界面显示「重新匹配中」;不产生新 Excel(Excel 尚未生成)。 @@ -3867,14 +3948,17 @@ inventory_preparation Gate ## 客户数据 ODM ID 范围与整单 ODM 裁决(2026-09) - 「客户主数据」页面与文案统一更名为「客户数据」;`ShippingCustomer` 新增可空 `odm_ids`(JSON 字符串清单),由客户数据页维护(每行一个,留空表示不限定)。 -- 生成发货 Excel 的整单 ODM 裁决(模板 Header 消费 `odm_id` 字段时生效,`export._adjudicate_notice_odm`): - 1. 客户 `odm_ids` 非空 → 先全局过滤库存命中行,仅保留范围内的 ODM;把原有命中全部排除时报「订单行命中的库存记录 ODM ID 不在客户数据维护的 ODM ID 范围内」。 - 2. 用户选择(`shipping_notice_line_inventory_matches.chosen_odm_id`,task 全部 `is_current` 行统一值)→ 过滤为所选 ODM;在当前库存中不存在时报「已选择的 ODM ID 在当前库存中不存在」。 - 3. 无范围、无选择且各行命中 ODM 交集唯一 → 自动收敛到唯一可行值;交集多个 → 维持折叠冲突阻断,由工作台下发候选。 +- 生成发货 Excel 的整单 ODM 裁决(模板 Header 消费 `odm_id` 字段时生效,`export._adjudicate_notice_odm`;2026-10-20 白名单降级): + 1. 各行命中 ODM 交集恰一个值(唯一可行解)→ **直接收敛到该值,跳过客户 `odm_ids` 白名单**——客户主数据与库存文件口径漂移不拦「Excel 里只有一个 ODM」的确定事实(回归 OT-20261017-184D440D)。 + 2. 交集多个且客户 `odm_ids` 非空 → 先全局过滤库存命中行,仅保留范围内的 ODM;把原有命中全部排除时报「订单行命中的库存记录 ODM ID 不在客户数据维护的 ODM ID 范围内」。 + 3. 用户选择(`shipping_notice_line_onhand_matches.chosen_odm_id`,task 全部 `is_current` 行统一值)→ 过滤为所选 ODM;在当前库存中不存在时报「已选择的 ODM ID 在当前库存中不存在」。 + 4. 多值、无范围、无选择 → 维持折叠冲突阻断,由工作台下发候选。 - 工作台「通知准备」面板为**行内 ODM 下拉**(任一行候选多于一个且未生成 Excel 时展示列):候选为该行经客户范围过滤后的命中值(保留原大小写);确认后 `POST /shipping-tasks//odm-choice`(body: `snapshot_line_id` + `odm_id`)落库并自动重试 `regenerate_excel_artifact`。 -- **同快照文件同步**:选择按 `inventory_snapshot_id` 圈同步——改任一行,同一快照文件的全部 `is_current` 匹配行写同一 `chosen_odm_id`(前后端同步:后端落库即同步,前端刷新后各行回显同一值);校验取同步范围内各行候选的交集,保证选择不会把其他行变成无匹配。 +- **同快照文件同步**:选择按 `onhand_snapshot_id` 圈同步——改任一行,同一快照文件的全部 `is_current` 匹配行写同一 `chosen_odm_id`(前后端同步:后端落库即同步,前端刷新后各行回显同一值);校验取同步范围内各行候选的交集,保证选择不会把其他行变成无匹配。 - 选择不落 Notice/OT:Notice 在生成失败事务中会回滚,行级匹配事实表才是导出读取库存源/文件的既有事实源;重匹配产生新匹配轮次后旧选择自然失效。Header 契约是整单一个值,若业务需要不同行走不同 ODM(跨快照文件),应拆分通知单。 -- 迁移:`aa11bb22cc33_customer_odm_scope`(`shipping_customers.odm_ids` + `shipping_notice_line_inventory_matches.chosen_odm_id`,均幂等守卫)。 +- 迁移:`aa11bb22cc33_customer_odm_scope`(`shipping_customers.odm_ids` + `shipping_notice_line_onhand_matches.chosen_odm_id`,均幂等守卫)。 +- **料号兜底自动放行的 ODM 唯一前置(2026-10-20)**:`order_review_fulfillment_decision_service.auto_release_part_fallback_shortages` 在「料号总量≥需求」之外,还要求预约+料号命中行(0 命中时回退料号命中行)的 ODM ID 唯一,否则保持人工路径——保证放行后导出可收敛;ODM 字段目录停用时不设前置。 +- **放行/满足性读取按 OT 回链(2026-10-20)**:匹配事实与复核 Case 的 `confirmed_task_id` 都按 OT 主键落库;Excel 生成链物化正式 Notice 后以 Notice 对象复评 `match_completed` / 放行 / 结案 / 库存准备失败读取时,统一经 `fulfillment_workflow._facts_order_task` 回链 OT,导出侧放行读取 join `owner.id`(回归 OT-20261017-364C7BF2:已自动放行的短缺单在 Notice 身份下被误判「尚未完成库存匹配」)。 ## 订单队列五态图标与 needs_attention(2026-09) @@ -3885,7 +3969,7 @@ inventory_preparation Gate ## 收料异动解析规则配置闭环(2026-09-21) -> 背景:调拨按需触发/预检复用链路依赖「收料配置绑定异动解析规则」,本节记录 2026-09-21 补齐的配置闭环与守卫语义。解析规则复用 `ShippingInventoryParsingProfile`(表名 inventory 为历史命名,用途以 `purpose` 为准)。 +> 背景:调拨按需触发/预检复用链路依赖「收料配置绑定异动解析规则」,本节记录 2026-09-21 补齐的配置闭环与守卫语义。解析规则复用 `ShippingParsingProfile`(表 `freight_rpa_parsing_profiles`,`purpose` 为 `onhand`/`inbound`/`outbound`)。 ### 标准异动字段目录(只读契约,共 10 项) @@ -3903,13 +3987,13 @@ inventory_preparation Gate | `movement_date` | 异动日期 | date | ✅ | ✅ | 成熟过滤 | - 唯一事实源:`movement_contract.MOVEMENT_FIELDS`;管理端经 `GET /api/admin/shipping-notice/movement-fields` 只读下发(code/value_type/required/is_identity),label 由前端 i18n(`admin.shippingInventory.movementFields.*`)渲染。禁止新增自定义字段。 -- 规则创建走既有「样本上传 → 结构分析 → 字段映射 → 发布」流程,新建弹窗新增「规则用途」(inventory/movement,创建后不可变);movement 弹窗渲染 10 行固定映射,隐藏库存字段目录与订单匹配键。`create_profile_draft` 透传 `purpose`。 +- 规则创建走既有「样本上传 → 结构分析 → 字段映射 → 发布」流程,新建弹窗新增「规则用途」(onhand/inbound/outbound,创建后不可变);inbound 弹窗渲染 10 行固定异动映射,隐藏库存字段目录与订单匹配键。`create_profile_draft` 透传 `purpose`。 ### 绑定闭环与守卫语义 -- `ShippingReceiptReportConfig.parsing_profile_id` 绑定已发布 movement 规则:保存接口校验(非 published 或用途非 movement → `SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID`),绑定进前后快照审计;抽屉「异动解析规则」下拉只列 published+movement 规则。 -- 预检触发守卫(`_DefaultRpaTrigger`):收料配置存在但未绑/规则未发布/用途不符 → `RPA_RECEIPT_MOVEMENT_PROFILE_MISSING`,不写 trigger(防徒劳抓取循环);无收料配置仍走既有 `RPA_RECEIPT_CONFIG_MISSING`。 -- 站点库存解析绑定(`ShippingInventorySource.parsing_profile_id`,站点表单与批量绑定弹窗)只列 `purpose==='inventory'` 的已发布规则,防止误绑异动规则。 +- `ShippingInboundReportConfig.parsing_profile_id` 绑定已发布 inbound 规则:保存接口校验(非 published 或 `purpose` 不是 inbound → `SHIPPING.INBOUND_PROFILE_INVALID`),绑定进前后快照审计;抽屉「异动解析规则」下拉只列 published 且 `purpose=inbound` 的规则。 +- 预检触发守卫(`_DefaultRpaTrigger`):收料配置存在但未绑/规则未发布/用途不符 → `RPA_INBOUND_PROFILE_MISSING`,不写 trigger(防徒劳抓取循环);无收料配置仍走既有 `RPA_INBOUND_CONFIG_MISSING`。 +- 站点库存解析绑定(`ShippingOnhandSource.parsing_profile_id`,站点表单与批量绑定弹窗)只列 `purpose==='onhand'` 的已发布规则,防止误绑 inbound/outbound 规则。 - `movement_file_repository.latest_ready_file` 复用条件不变:归档文件存在且绑定规则就绪;无排程按需触发的单元行 `schedule_run_id` 为 NULL(FK 禁止 0 占位)。 ## 通知准备阶段进度版本推进契约修复(2026-10-09) @@ -3945,7 +4029,7 @@ inventory_preparation Gate ### 存储:新列与回填策略 -- 新列 `shipping_notice_line_inventory_matches.part_available_qty`(`String(32)` 可空),迁移 `0a575f3afc32`(`backend/migrations/versions/0a575f3afc32_add_part_available_qty_to_shipping_.py`)。 +- 新列 `shipping_notice_line_onhand_matches.part_available_qty`(`String(32)` 可空),迁移 `0a575f3afc32`(`backend/migrations/versions/0a575f3afc32_add_part_available_qty_to_shipping_.py`)。 - 落库:`line_inventory_match_persistence` 在匹配落库(新建与更新路径)时随行事实字符串化写列。 - 存量行 NULL 不回填,重新匹配后回填。 diff --git a/docs/funclist.md b/docs/funclist.md index 3ee34542..8d289f8d 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -165,6 +165,7 @@ | Workflow 阶段 3 确认后自动进度 | 已实现 | 五门禁(批准模板/字段完整/证据/冲突重复/质量)失败仅 Review Case;确认返回 `shipping_notice_no`/`order_task_no` 并推进履约;复核页 `ReviewWorkflowProgressPanel` 读统一 OT 投影;建单后取消 Task `pending_void`+Excel 只读;移除工作台 upload-inventory/mark-manual-uploaded/retry-upload 写入口 | | Workflow 阶段 4 任务中心与审计闭环 | 已实现 | 任务中心进行中 2s/8s 自动刷新;时间线合并 Workflow Event;审计关联链/敏感读权限/哈希日检;删除复核监管台 | | EML 正文补充表合并(阶段 2) | 已实现 | 正文 HTML 表解析为带 DOM 单元格证据的 PO 级补充事实,不创建独立订单或执行 Unit;按 `PO + MPN`、受限 PO 降级补 Reservation/Allocation/库存来源提示,支持 `External reservation ID` 等冻结 Schema 显式别名;每个 Run 从原始 HTML 重建,避免旧的部分解析结果遮蔽新规则;PDF 数量保持权威,歧义统一进入人工复核 | +| 预约单号裸数字兜底(2026-10-14) | 已实现 | EML 正文数据表无表头、表头契约解析不出预约单号时,在补充合并末段只对正文 HTML 表格做「整格恰好 5/10 位纯数字」候选扫描(2026-10-15 收紧:自由文本/签名邮编/带前后字符的值一律不取,无表格不兜底);排除订单已提取字段值、补充行值、主题「PO/Invoice/Qty」标签数字与跨单已占用后,唯一候选以低置信度(0.5)写入并标记 `reservation_heuristic` 待人工确认,多候选复用字段冲突裁决面板,零候选维持缺失阻断;已有值(含非法格式原值)永不覆盖,仅限 EML 正文表格(PDF 仍走模板/Schema 契约);审计事件 `reservation_heuristic_applied`/`_ambiguous` 供误判率观察 | | PDF 模板 PO 拆分与严格拒识(阶段 3) | 已实现 | 已批准模板中每条明细均有唯一 PO 证据时,单 PDF 自动拆为多个独立订单;表级多 PO 未能归属明细、模板歧义、漂移和证据不足统一转人工复核,Route Decision 分别审计四类表计数 | | 订单模板版本中心(阶段 0-7) | 已实现 | 订单文档模板按 `profile_code` 聚合版本族;已落地独立版本详情、历史只读样本画布、服务端语义差异、审计记录页签、实际使用页签,以及阶段 7 的 blind test 隔离与发布治理;只读画布完整展示必需锚点及各受控标签区域的冻结识别值,必需锚点可对照配置值、识别值和匹配状态;标注取字、运行匹配与版本诊断统一按视觉行恢复字符阅读顺序;标注 Reservation ID 专区的模板跨页以 `Vendor Comments` 至首次 `Terms and Condition(s)` 作为语义边界读取预约单号,未标注模板保持原解析路径 | | **订单模板版面签名 Matcher** | 代码已落地(待真实样本灰度) | 版面签名存 ValidationRun;Profile 轻量引用;Matcher 三态证据 + Top-N 解析验证;表头签名直接消费既有 `header_layout.region`,签名生成与运行时统一视觉词组和坐标口径;跨模板发布门禁与发布检查页;重识别亲和性校验签名;表头身份原子按 Run 冻结 Schema 别名归一,同字段同义列名(如 Requested Arrival/Ship Date)不再触发表头硬互斥;`SHIPPING_NOTICE_PROFILE_LAYOUT_SIGNATURE_REQUIRED` 控制全量切换。说明:[order-profile-layout-signature.md](features/shipping-notice/order-profile-layout-signature.md) | @@ -200,16 +201,16 @@ | 人工复核与字段证据闭环(阶段 5) | 已实现 | 单头、订单行、冲突解决均要求乐观锁、原因和结构化 `document_cell`/`manual_input` 证据;跨订单或伪造证据在写值前拒绝,复核审计保存结构化证据且详情页展示页码、表格、单元格与原文 | | 原 PDF 双层重解析 | 已实现 | “重新识别此 PDF”仅为当前原始文件创建后继 Run;“重新解析本批次”逐 PDF 创建独立子 Run、局部成功替换,按完整 Run 谱系选择每个原文件的当前 Case;已确认/履约文件排除;不支持上传替代 PDF。 | | 多订单 Candidate 判重与自动建批 | 已实现 | Candidate 身份/内容双指纹;高置信 SKU+Qty 订单自动建 Task,低置信/冲突/修订保留待处理;部分消费 Intake 不丢剩余订单;缺 Reservation/Source Type/Hub Code 的 Task 停在自然对话补字段门禁 | -| 库存 RPA 源 YAML 配置 | 已实现 | `backend/config/shipping_inventory_sources.yaml`,新增 Warehouse 只改 YAML | +| 库存 RPA 源配置 | 已实现 | 源、报表路径与查询参数维护在数据库 `freight_rpa_sources`(管理端货代 RPA 页);期初 YAML 已于 2026-10-20 删除,运行时只读数据库 | | 订单解析阶段库存源判定 | 已实现 | `parse_notice` 内 adjudicate 写线索;低置信度先 `parse_review`,解析通过后再 `inventory_source_review`;稳定态 `resolved`/`user_confirmed` | | 文件解析阶段问题清单 | 已实现 | 步骤 2 工作台/`ui_state.summary.issues` 一次列出解析复核、RSV、库存源门禁与 parse warnings | | 发货通知关键字段真值校验 | 已实现 | LLM 出候选、后端裁决;支持多模板 Reservation 别名,拒绝 32 位 hex/UUID;仅按 TSV 列关系与唯一 SKU/APN/MPN 证据纠错;`parse_validation` 留痕,blocking issue 在解析确认和库存匹配前双重阻断 | | 内部料号库存匹配 | 已实现 | 主匹配键为 `(part_number, reservation_id)`;库存 `Supplier Sku` 对应内部料号,`AWS Sku` 仅作为可选 `aws_part_number`,AWS-only 库存表不能形成有效主匹配行 | | 库存快照身份校验 | 已实现 | link 时校验 `source_code`/`site_id`/`warehouse_id` 与任务一致 | | 库存快照 TTL 复用 | 已实现 | `inventory_snapshot_store`,按需任务优先复用未过期快照 | -| 库存 RPA 批量导出(DSV/Crane 一次登录) | 已实现 | `inventory_export_batch` trigger + worker + `/rpa/inventory-batch-ready`;回调以 `ShippingOrderTask` 为唯一任务模型,收件与业务处理分离,事务失败必须收口为失败;库存等待使用单一 Gate Attempt 与 30→60→120→240→300 秒退避 Job,不为每次轮询新增 Attempt。 | -| 库存每日定时导出排程 | 已实现 | `schedule_type=platform_job` + `platform_api_path=shipping-inventory-rpa`,cron 建议 `0 3 * * *` | -| 库存源至外部系统仓库映射 | 已实现 | 维护精确与默认(货代仓库为空)映射,货代仓库选填(inventory_match 源按收料仓库匹配的键);新增在途仓编码(必填)作为在途调拨拨出库位来源;仅后台维护,不开发 Tool API | +| 库存 RPA 批量导出(DSV/Crane 一次登录) | 已实现 | 文件名 `inventory_export_batch_{run_no}.json`(action `onhand_export_batch`)+ worker + `/api/freight-rpa/onhand-batch-ready`;回调以 `ShippingOrderTask` 为唯一任务模型,收件与业务处理分离,事务失败必须收口为失败;库存等待使用单一 Gate Attempt 与 30→60→120→240→300 秒退避 Job,不为每次轮询新增 Attempt。 | +| 库存每日定时导出排程 | 已实现 | `schedule_type=platform_job` + `platform_api_path=freight-rpa-onhand`,cron 建议 `0 3 * * *` | +| 库存源至外部系统仓库映射 | 已实现 | 维护精确与默认(货代仓库为空)映射,货代仓库选填(inventory_match 源按异动仓库列匹配的键);新增在途仓编码(必填)作为在途调拨拨出库位来源;仅后台维护,不开发 Tool API | | 建单防重复(第一阶段) | 已实现 | 批次 `create_idempotency_key`、任务 `source_content_hash`、同请求去重、幂等重放 | | 客户身份与业务编号规则 | 已文档化 | 内部 `SN-...` 与业务号分离;业务号固定为 `客户简码 + YYMMDD + 两位流水`,例如 `WYC26071501`,日期口径 `Asia/Shanghai` | | 客户受控合并 | 已实现 | 管理员预览历史保留与未来配置迁移后,输入源简码和原因归并至启用目标客户;历史业务/编号/审计不改写,识别证据和来源键迁移,源客户标记为 merged 并不可再用于新任务 | @@ -229,7 +230,7 @@ | 产品原型 | 已文档化 | 见 [docs/features/shipping-notice/shipping_notice_agent_prototype.md](features/shipping-notice/shipping_notice_agent_prototype.md) | | **多候选库存源自动批次探测(一期)** | 已实现 | `ensure_inventory` STP 多候选分支:缺文件不再隐式阻断为 `needs_human`,改为自动单批次 RPA 探测(仅缺失源,已有 ready 快照复用)并返回 `running`;逐源 Attempt/超时/重试保留。设计:[2026-08-29-shipping-inventory-source-selection-design.md](superpowers/specs/2026-08-29-shipping-inventory-source-selection-design.md) §2。 | | **库存匹配数据自证 + 行级歧义兜底(一期)** | 已实现 | 全部候选源快照按行打 `__source_code` 标签匹配,按行反写源/可用量/缺口;同一行命中多源 → 行 `multi_file_conflict` 阻断 + `candidate_hit_source_codes`(禁止静默选源)。设计 §2.3。 | -| **行级人工选源动作 select_line_inventory_source(一期)** | 已实现 | Gate 业务动作(属 `inventory_matching`):校验行冲突、源 ∈ 候选、源启用、通知未生成 Excel(否则 `SHIPPING.LINE_SOURCE_LOCKED`);写候选行覆写 + 仅该行重匹配 + 审计 `review_line_source_selected`。 | +| **行级人工选源动作 select_line_inventory_source(一期)** | 已实现 | Gate 业务动作(属 `onhand_matching`):校验行冲突、源 ∈ 候选、源启用、通知未生成 Excel(否则 `SHIPPING.LINE_SOURCE_LOCKED`);写候选行覆写 + 仅该行重匹配 + 审计 `review_line_source_selected`。 | | **通知准备行源下拉与锁定渲染(一期)** | 已实现 | `ui_state.preparation` 下发 `source_locked` / `lines[].source_ambiguous` / `source_candidates`;前端歧义行渲染库存源下拉 + 首选高亮 + 确认,`source_locked` 行只读徽标;阶段自动跳转一次性 toast + 清理 `reparse` 死守卫;四语言文案。 | | **波次库存源按自身行重路由(D8)** | 已实现 | `post_ot_fulfillment_wave_service` 创建波次通知不再继承首通知任务级源字段(`inventory_source_*`/`routing_fingerprint`/`snapshot_id`),仅继承订单级路由上下文(目的地/仓提示);新增 `inventory_candidate_freeze_service.freeze_wave_notice_routing` 按波次自身行评估路由并冻结候选集,随后走同一套自动探测/匹配/反写。测试:`test_shipping_wave_rerouting.py`。 | | **客户数据 ODM ID 范围与整单 ODM 裁决** | 已实现 | 客户数据(原客户主数据)维护可空 `odm_ids` 清单;生成 Excel 时按客户范围过滤库存命中行,范围后仍多值时工作台整单选择(写入行级匹配事实 `chosen_odm_id`)并自动重试;交集唯一自动收敛。 | @@ -247,7 +248,7 @@ | ------------------- | ------ | ----------------------------------------------------------------------------------------------------------- | | 平台任务注册表升级 | 已实现 | `job_registry.PlatformJobDefinition` 补 `category / params_schema / defaults`,注册表即任务契约中心 | | 任务定义接口 | 已实现 | `GET /api/admin/platform-tasks/definitions` 下发完整契约(含 params_schema) | -| 动态选项接口 | 已实现 | `GET /api/admin/platform-tasks/options?source=...`;已支持 `agent_apps`、`shipping_inventory_sources` | +| 动态选项接口 | 已实现 | `GET /api/admin/platform-tasks/options?source=...`;已支持 `agent_apps`、`freight_rpa_sources` | | job_params 统一校验 | 已实现 | `job_params.validate_task_params`:保存与执行前各校验一次;未声明字段拒绝,`_advanced` 例外透传 | | 结构化参数存储 | 已实现 | `schedule_tasks.job_params`(JSON),迁移 `d1e2f3a4b5c6`;FAQ/RPA handler 优先读取并回退旧字段 | | 前端通用参数表单 | 已实现 | `DynamicTaskParamsForm.vue` 按 schema 渲染 + 折叠高级 JSON,编辑弹窗移除任务级 v-if | @@ -738,7 +739,8 @@ | 功能项 | 状态 | 说明 | | ------------------------------ | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| 货代收料 RPA 后端与独立 Worker | 已实现(待测试环境联调) | 独立排程、原子 trigger、callback 超时回收、DBS Warehouse 拆分、Crane 强制 `#/inbound-details-query` 后按页面默认条件导出 Inbound Details、归档、企微、管理员失败单元补偿、接收人授权下载及完整审计已实现;写 trigger 前与库存同口径 fail-fast 就绪检查(心跳+哨兵+scope,部署侧由 `start_receipt_worker.ps1` 注入 `FREIGHT_RPA_SHARED_SCOPE_ID`);库存 Worker 和链路未改动。 | +| 货代入站 RPA 后端与独立 Worker | 已实现(待测试环境联调) | 独立排程 `freight-rpa-inbound`、原子 trigger、callback 超时回收、DBS Warehouse 拆分、Crane 强制 `#/inbound-details-query` 后按页面默认条件导出 Inbound Details、归档、企微、管理员失败单元补偿、排程 `inbound-raw-zip` 深链下载及完整审计;已删除 deliveries 表与「重发企微」、下线工作台收料文件页;写 trigger 前与库存同口径 fail-fast 就绪检查(心跳+哨兵+scope,部署侧由 `start_inbound_worker.ps1` 注入 `FREIGHT_RPA_SHARED_SCOPE_ID`)。 | +| 货代出站 RPA 后端与独立 Worker | 已实现(待测试环境联调) | 镜像入站:配置/unit/file 三表、排程 `freight-rpa-outbound` 与 `freight-rpa-outbound-retention`、trigger schema `freight_rpa.outbound.v1`、回调 `outbound-*`、MinIO 归档、`report_kind=outbound` → `handle_outbound_report` 在途按需触发;无 notification_deliveries、无工作台出站文件页;运维走排程管理与 `outbound-raw-zip`。 | | 功能项 | 状态 | 说明 | | ------------------------- | ------ | ------------------------------------------------------------------------------------------------------------- | @@ -812,18 +814,24 @@ | 功能项 | 状态 | 说明 | | --- | --- | --- | | 领域模型/状态机/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/来源隔离/字段校验/T+lag 成熟(默认 T+2)/Invoice 多行汇总+原始行追溯/匹配快照 Hash/进度恢复 | +| 入站文件准备与只读匹配(原"预检") | 后端已实现 | 入站文件落地即同步库存异动档(2026-10-14 出生翻转:RPA 回调桥 → evidence_sync 一次解析写档不写明细,自然键幂等五分类——插入/sha 幂等跳过/证据变原行更新/缺席存续/已执行封存);匹配=从档圈定建行 + 按组织批量查库存 + 严格数量比对;缺文件按来源触发收料 RPA/来源隔离/字段校验/T−2 成熟封顶(2026-10-21:T−2 之前数据全部成熟,圈档只圈 movement_date≤T−2,未成熟行留档待成熟;范围入参截止>T−2 拒绝)/Invoice 多行汇总+原始行追溯/匹配快照 Hash/进度恢复 | | 可调拨清单勾选与 ERP 原子调拨 | 后端已实现 | 可调拨明细队列勾选按行提交执行 Run/写前复查/Invoice 幂等/duplicate_success/result_unknown 隔离/单项失败不阻断/按票聚合结果(写路径已接线,见下行「ERP 建单写路径」) | -| 排程/恢复/异常/通知 | 后端已实现 | 08:00 收料文件与 09:00 自动调拨 platform job;任务参数=来源实例/历史可恢复异常复核/可选收料日期起止(T-N 偏移天数,执行日换算,测试/排障缩小匹配面;留空=全部成熟积压;非法偏移快速失败,越界由匹配层卡控成熟上限);待处理池 3/5/7 天老化;人工重试/关闭;七 Sheet 异常 Excel;执行结果通知统一走排程「启用通知」通用执行结果通知(空数据日静默,失败不改 ERP 结果;2026-10-12 移除任务级通知人参数) | -| 调拨业务类型 | 后端已实现(类型2/3占位) | 三类型:在途仓至HUB仓(一期开放,仅纳入 INVOICE 前缀 HOM/HOX/WTP 的票)/HUB仓维修出(占位,规则 ODM ID=HoxinRMA 待文件层支持 odm_id)/HUB仓间调拨(占位);类型随 Run 落库并入匹配 Hash,占位类型 fail-closed;前端来源选择卡选择(占位类型禁用) | +| 排程/恢复/异常/通知 | 后端已实现 | 08:00 入站文件与 09:00 自动调拨(现注册表单列 `in-transit-transfer` platform job,缺当日入站文件自动触发收料 RPA);任务参数=来源实例/历史可恢复异常复核/可选异动日期起止(T-N 偏移天数,执行日换算,测试/排障缩小匹配面;留空=全部成熟积压;非法偏移快速失败,偏移终点落在 T−1/当天或更晚由匹配层卡控截止≤T−2);待处理池 3/5/7 天老化;人工重试/关闭;七 Sheet 异常 Excel;执行结果通知统一走排程「启用通知」通用执行结果通知(空数据日静默,失败不改 ERP 结果;2026-10-12 移除任务级通知人参数) | +| 调拨类型配置化(2026-10-14) | 已实现 | 类型来自平台配置表 `transfer_type_configs`(ADR 0002,代码枚举/CHECK 约束/前端 union/「即将上线」占位全退役):管理端「在途调拨类型」页四块配置(基本信息/范围规则/仓库定义/字段转换),admin CRUD API + chat enabled 最小暴露 API;`transfer_type` 匹配创建必填(未配置/停用 fail-closed),配置为空前端空态;范围规则引擎(18 字段白名单、规则间 AND 值间 OR、内存谓词+SQL 编译双形态)、仓库定义(mapped/fixed+法人覆盖)、字段转换(批号前缀替换,六个系统边界生效,行/档保原值);规则随匹配快照进 scope_json;管理页见 `features/admin/modules/transfer-types/`,运维手册 technical.md §11 | +| 库存异动档与出生翻转(2026-10-14) | 已实现 | 新建 `transfer_movement_ledger`(ADR 0001,外部入站/出站记录唯一镜像):自然键幂等五语义(插入/sha 幂等跳过/证据变原行更新/缺席不删/已执行封存)、record_kind 声明+in_out_flag 交叉校验(矛盾打审计标记照常落档)、D13 业务字段+出站预留列、档级封存回写(执行成功 transfer_executed=true 防二次调拨);items 出生翻转=匹配创建时从档圈定建行(matching_id/ledger_record_id 出生即绑定),落地停写 items、重查对档对账、scope_item_query 退役;D17 圈档互斥(一条档记录一生一次绑定,取消释放/终态不释放);2026-10-21 外部单据身份扩维:自然键 8→10 成分(+外部单号/外部项次=WMS Order #/行号,迁移 tt21c8d9e0f1a2)作档幂等主键管控,movement 契约字段目录扩至 20 字段(解析 Profile 可映射),解析层料号空行静默跳过(不管控、不进异动表) | +| 入站/出站统一改版与幂等修复(2026-10-15) | 已实现 | record_kind 枚举值改版 inbound/outbound(迁移 tt14 值迁移);明细/单据列异动口径 `movement_*`(异动日期/数量/仓库列与匹配创建参数 `movement_date_from/to`、序列化键、Excel 表头随行更名,无兼容层);异动档自然键扩为 8 成分(+箱号/批号,三份真实 WMS 文件实测塌缩归零)+「异动日期非空才落档」过滤(`date_skipped`,未完成/已取消行不入档);解析规则 purpose 三枚举 onhand/inbound/outbound(迁移 tt15 值迁移);入站配置绑定校验 inbound 专用(`SHIPPING.INBOUND_PROFILE_INVALID`),出站绑定 `SHIPPING.OUTBOUND_PROFILE_INVALID`(2026-10-19 出站全栈);解析规则退役守卫补查入站/出站配置绑定;API 路由 `/sources/inbound-files`、`/runs/{run_no}/inbound-files` 与错误码/审计事件 inbound 化;出站 RPA 与调拨 sink 见 [superpowers/specs/2026-10-19-freight-rpa-outbound-and-rename-design.md](superpowers/specs/2026-10-19-freight-rpa-outbound-and-rename-design.md);2026-10-15 设计见 [superpowers/specs/2026-10-15-inbound-outbound-idempotency-rename-design.md](superpowers/specs/2026-10-15-inbound-outbound-idempotency-rename-design.md),运维手册 technical.md §12 | +| 待匹配桶清空并重新解析(2026-10-15) | 已下线(2026-10-22) | 原入口会重放该来源保留期内全部归档,一次执行可把历史行整批灌进待匹配。界面与 `GET/POST /backlog/pending-match/reparse*` 已移除。重解析只保留来源卡「重新解析」(当天最新一份,不删行)。 | +| 首页待匹配桶与 file_current 改锚(2026-10-14) | 已实现 | 待办看板新增「待匹配」桶(已落档但从未匹配的外部记录只读可见+去匹配引导,不可勾选执行),四队列卡数据源改档+最近执行状态联查;file_current 门禁改锚档记录 file_version(==来源最新可用文件 sha 即当前) | +| 首页待匹配与可匹配拆数(2026-10-21) | 已实现 | 「待匹配」改为成熟未占用的出入站全量,不再按调拨类型范围收窄。「匹配可调拨库存」卡显示启用类型现在圈得住的 `matchable_count`。清单上段可去匹配,下段范围外只读。建匹配仍按所选类型圈档。2026-10-22 清单按来源、记录类型、外部单号合计数量,不再展开外部项次;没有外部单号的档行仍逐行展示。首页待匹配、可匹配计数与清单行数同一口径。2026-10-22 首页 SQL 下推(性能):计数/清单分页/行桶汇总全改 SQL 聚合(合并键 GROUP BY 计数、组首行锚点分页、轻量元组老化),口径不变,禁止再整段装载内存切片。 | | 生产硬化 | 后端已实现 | MinIO 归档+Hash 复核;Worker 崩溃/陈旧执行恢复;运营指标;越权 403;下载访问审计;性能测试;运维手册 docs/features/in-transit-transfer/technical.md | -| 可调拨明细与待办看板首页 | 已实现 | 首页上区「库存匹配」动作卡 + 待办看板四队列:可调拨明细(GET /items/executable 全局可执行行,勾选按行生成调拨单)/待恢复异常/已人工关闭/结果未知;「最近匹配」(原"最近预检")已移除(行不迁移后匹配卡=范围实时视图,多份同 scope 匹配属重复窗口) | -| 待处理池批量操作与恢复处理 | 已实现 | 批量重查(恢复处理=行级重查原地刷新+续新鲜度,重查前证据对齐兜底)/批量关闭;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) | +| 可调拨明细与待办看板首页 | 已实现 | 首页上区「库存匹配」动作卡 + 待办看板五桶(2026-10-14 起数据源=档联查):待匹配(已落档未匹配,只读+去匹配引导,不可执行)/可调拨明细(GET /items/executable 全局可执行行,勾选按行生成调拨单)/待恢复异常/已人工关闭/结果未知;「最近匹配」(原"最近预检")已移除(匹配卡=范围实时视图,多份同 scope 匹配属重复窗口)。2026-10-22 可调拨明细与待处理异常表增加调拨类型列,名称取出生匹配快照 | +| 待处理池批量操作与恢复处理 | 已实现 | 待处理异常只保留「重查库存」与「关闭」(2026-10-22:恢复与重查是同一次 ERP 核对,不再并列两个按钮;结果同时报出已可执行、仍阻断、失败)。批量重查按明细 id 原地刷新;匹配卡重查仍对档对账。批量关闭;2026-10-22 跨页全选(Gmail 式):服务端分页下表头全选只覆盖当前页,未全选时透出「选择全部 N 行(按当前筛选)」经 `GET /backlog/item-ids` 拉全量 id 合并勾选集合,批量端点按 item_ids 列表复用;blocked_file_removed 仅历史残留防御(2026-09-28 起不再新产生,现为档记录被新版本替换的失效隔离语义);行归属=匹配出生即绑定(§「库存异动档与出生翻转」) | +| 按行执行与执行门禁 | 已实现 | execute(item_ids) **202 异步**:API 门禁(存在可执行 + 所属匹配未取消,fail-closed)通过即建 queued Run + 五元组分组建票 + 一次入队,worker 逐票执行(写前路由/库存复查——库存复查仅全量重跑路径,final_only 续跑不复查);Run 留痕不绑匹配;进度/结果无状态回读(GET /runs 轮询票清单);行级新鲜度 TTL 门禁与 ITEMS_STALE 错误码退役(2026-09-25),文件版本对账门禁退役(2026-10-22:入站部分导出缺席≠失效,按最新文件 sha 对账误卡未处理行;防错下沉 worker 写前库存复查 + 行级「文件已更新」提示徽标,见 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 既有;本期零新增环境变量) | -| 收料日期默认与输入期限制 | 已实现 | 来源选择卡收料日期默认 T+lag 成熟规则(默认业务日 T-2,可配 IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS);日期输入 max/min 即时限制 + 起止非法行内提示禁用确认(后端 RECEIPT_DATE_RANGE_INVALID 卡控保留双保险);「直接生成调拨单」改名「生成调拨单」 | +| 异动日期默认与输入期限制 | 已实现 | 来源选择卡异动日期默认与上限同为 T−2 可匹配截止日(T−2 成熟封顶 2026-10-21:T−2 之前数据全部成熟,T−2 之后不可选);面板 disabled-date 卡 T−2 之后日期 + 起止非法行内提示禁用确认(后端 MOVEMENT_DATE_RANGE_INVALID 截止≤T−2 双保险);「直接生成调拨单」改名「生成调拨单」 | | 来源重试合并触发与知情范围确认(2026-10-09) | 已实现 | 批量重试 RPA 合并写**单个** batch trigger(POST `/sources/retry-rpa-batch`,Worker 单次浏览器会话按 profile 分组串行导出,替代逐来源 N 个 trigger/N 次开浏览器;单源失败跳过不阻断整批,parse_failed 仍先本地重解析);来源选择卡混合选择(含非就绪项)确认前先披露范围(可匹配/暂不可匹配计数+按状态分组明细),显式确认后提交 ready-only,全就绪直达(知情部分确认,替代静默剔除;其余来源就绪后可重新匹配增量补入) | -| 前端 Chat 卡片/结果页与四语言 | 已实现 | `frontend/src/features/chat/` 卡片(文件进度/匹配/结果/待处理)与 admin 模块已按计划实施(结果=融合卡:202 提交后 4s 轮询票清单至严格终态) | +| 当前归档重新解析(2026-10-21) | 已实现 | 来源卡证据清单第一行「重新解析」调用 `POST /sources/{source_code}/reparse`,只重放该流入站或出站的最新可用归档并幂等落档,不触发 RPA,不删除档行。↻ 仍是重新抓取。待匹配清单不再提供清空重解析。 | +| 前端 Chat 卡片/结果页与四语言 | 已实现 | `frontend/src/features/chat/` 卡片(文件进度/匹配/结果/待处理)与 admin 模块已按计划实施(结果=融合卡:202 提交后 4s 轮询票清单至严格终态);2026-10-22 列表分页收口:可调拨清单(匹配明细卡)与融合卡票清单客户端分页 50/页(筛选变更回第 1 页、行数减少收拢当前页、勾选跨页保留),可调拨明细卡既有 50/页、待处理池/待匹配桶/已执行票清单为服务端分页(20/页),来源选择/首页队列卡为天然有界集合 | --- @@ -846,6 +854,7 @@ | 集成调用日志(wire 线级事实捕获 + 管理端查询,2026-09-27) | 已实现 | 传输层捕获线级事实(database=标识符替换后最终 SQL/绑定首行/行数;soap=endpoint/SOAPAction/渲染后 XML/原始响应;rest=method/URL/headers/body/原始响应;凭据 mask_secrets 脱敏、文本 20000 截断引擎统一收口)落 integration_calls.wire_json;通用业务锚点 business_ref 可选透传;管理端「集成连接器→调用日志」分页筛选(能力/接口/客户端/连接类型/状态/operation_id/trace_id/business_ref/参数关键字/时间起止)+ 步骤时间线详情(原始报文/归一化 JSON 双栏)+ 外部工具复现(curl / 绑定内联 SQL,写入类包事务警示);API GET /api/integration-connector/calls[/{id}](require_admin) | | 调拨 query_inventory 接线 | 后端已实现 | `services/in_transit_transfer/gateway_adapter.py` 把 ERP 访问收敛到 gateway(P1 用默认绑定,来源专属绑定待 P2/P3) | | 配置作业 UI / MCP / Dify 暴露 / RPA/SQL 传输 | 待实施 | 属 P2/P3(AI 只暴露 Capability;RPA 为独立异步 Transport) | -| 收料异动解析规则(标准字段目录 + 规则用途) | 后端+管理端已实现 | purpose='movement' 解析规则创建/发布;`GET /api/admin/shipping-notice/movement-fields` 只读目录(10 定死字段,禁自定义);movement 映射表单(前端 `admin/shipping-notice` 解析模块) | -| 收料配置绑定异动解析规则 | 后端+管理端已实现 | 收料配置保存/回显 `parsing_profile_id`(校验 published+movement,`SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID`);抽屉绑定选择器;审计快照含绑定 | -| 预检未绑异动规则守卫 | 后端已实现 | 收料配置存在但未绑已发布 movement 规则 → `RPA_RECEIPT_MOVEMENT_PROFILE_MISSING`,fail-closed 不触发徒劳抓取 | +| 入站解析规则(标准字段目录 + 解析类型) | 后端+管理端已实现 | purpose 三枚举 onhand/inbound/outbound(2026-10-15 由两值旧枚举改版,迁移 tt15 值迁移);purpose='inbound' 解析规则创建/发布;`GET /api/admin/shipping-notice/movement-fields` 只读目录(10 定死字段,禁自定义);movement 映射表单(前端 `admin/shipping-notice` 解析模块) | +| 入站报表配置绑定入站解析规则 | 后端+管理端已实现 | 入站配置保存/回显 `parsing_profile_id`(校验 published+purpose='inbound',`SHIPPING.INBOUND_PROFILE_INVALID`);抽屉绑定选择器;审计快照含绑定 | +| 出站报表配置绑定出站解析规则 | 后端+管理端已实现 | 出站配置保存/回显 `parsing_profile_id`(校验 published+purpose='outbound',`SHIPPING.OUTBOUND_PROFILE_INVALID`);与入站同构路径/查询/绑定 UI | +| 预检未绑入站规则守卫 | 后端已实现 | 入站配置存在但未绑已发布 inbound 规则 → `RPA_INBOUND_PROFILE_MISSING`,fail-closed 不触发徒劳抓取 | diff --git a/docs/refactor/frontend_architecture_refactor.md b/docs/refactor/frontend_architecture_refactor.md index f1eef0b7..4daa753a 100644 --- a/docs/refactor/frontend_architecture_refactor.md +++ b/docs/refactor/frontend_architecture_refactor.md @@ -30,7 +30,8 @@ | 组织方式 | Feature-Module | 按业务域(auth / workspace / chat / admin / kb)垂直拆分,域内自包含 api / composables / views | | 逻辑封装 | Composables | 副作用、表单、SSE、分页等放入 `use*`,View 只做编排 | | 跨页状态 | Pinia | 替代 localStorage + CustomEvent 为主的跨组件可变状态 | -| 未采用 | FSD、Element Plus | 目录层级更浅、迁移成本可控;继续 Tailwind + Design Tokens | +| 未采用 | FSD | 目录层级更浅、迁移成本可控;继续 Tailwind + Design Tokens | +| 受限采用 | Element Plus | 2026-10 起评审引入(admin 试点 + chat 在途调拨面板);仅用行为型组件(el-dialog/el-table/el-select 等),布局仍 Tailwind;组件显式 import + 页面级全量 CSS(含暗色 css-vars) | **固定技术栈(勿擅自替换):** @@ -184,7 +185,7 @@ flowchart TB 3. **单一 HTTP 客户端**:`@/shared/api/client`;SSE 对话走 `useChat`,不另造客户端。 4. **路由按域拆分**:新路由写入 `app/router/routes/.routes.ts`,守卫逻辑放 `guards.ts`。 5. **i18n 四语言同步**:新增 key 须同时写入 `zh-CN`、`zh-TW`、`en`、`th` 对应 JSON。 -6. **不引入未经评审的重型 UI 库**(Element Plus、Naive UI 等);复用 `shared/components` 与 Tailwind。 +6. **重型 UI 库仅限已评审的 Element Plus**(2026-10 评审引入,见 §1 选型表):新增使用场景须延续「行为型组件 + Tailwind 布局」模式并在评审说明给出理由;Naive UI 等其余库仍禁入;复用 `shared/components` 与 Tailwind。 7. **大页面必须薄壳化**:参考 chat / kb / schedules 模式(见 §5)。 ### 4.2 文件体量与拆分 diff --git a/docs/skills/add-i18n-keys-skill.md b/docs/skills/add-i18n-keys-skill.md index 58d256d0..1cb41146 100644 --- a/docs/skills/add-i18n-keys-skill.md +++ b/docs/skills/add-i18n-keys-skill.md @@ -141,8 +141,8 @@ JSON 中保留命名占位符,例如 `"共 {total} 条,当前第 {page} / {p ### 6.3 新增错误码 -**后端 code:** `SHIPPING.INVENTORY_SOURCE_INVALID` -**前端 key:** `errors.codes.SHIPPING_INVENTORY_SOURCE_INVALID` +**后端 code:** `SHIPPING.ONHAND_SOURCE_INVALID` +**前端 key:** `errors.codes.SHIPPING_ONHAND_SOURCE_INVALID` **文件:** `frontend/src/locales/{zh-CN,zh-TW,en,th}/errors.json` 的 `codes` 对象下各加一条。 --- diff --git a/docs/superpowers/plans/2026-10-14-transfer-type-config-and-movement-ledger.md b/docs/superpowers/plans/2026-10-14-transfer-type-config-and-movement-ledger.md new file mode 100644 index 00000000..0f9ce57b --- /dev/null +++ b/docs/superpowers/plans/2026-10-14-transfer-type-config-and-movement-ledger.md @@ -0,0 +1,809 @@ +# 在途调拨类型配置化 + 库存异动档 实施计划 + +> **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:** 调拨类型从代码枚举升级为管理页可配置(范围规则/仓库定义/字段转换),新建库存异动档(外部收料/出货记录镜像),匹配明细改为匹配时从档圈定创建。 + +**Architecture:** 三层改造——①配置域:`transfer_type_configs` 表 + 受控规则引擎(scope_rules/field_transforms 纯函数 + SQL 编译器)+ admin CRUD;②档域:`transfer_movement_ledger` 自然键幂等落地(evidence_sync 语义平移);③切换域(原子):匹配创建从档圈行建 items、落地停写 items、重查对档对账、队列/门禁改锚。 + +**Tech Stack:** Flask + SQLAlchemy 2.0 + Alembic + pytest;Vue 3 + TS + Pinia + vitest。 + +**Spec:** `docs/superpowers/specs/2026-10-14-transfer-type-config-and-movement-ledger-design.md`(本计划从规格论证;执行者两份都读) + +## Global Constraints + +- 🚫 **禁止自动 commit**:每个任务以 `git add <具体文件>` 收尾;提交由用户显式批准后统一进行。 +- 🌍 前端新增文案必须同时补 `zh-CN / zh-TW / en / th` 四语言;禁止硬编码中文。 +- ⚠️ JSON API 走 `{success, data|error, request_id}` envelope;后端失败 `raise AppError` 子类(`app/core/errors.py`);前端 HTTP 用 `requestJson`,失败 `useMessage()` 展示。 +- 🧬 模型变更必须配套 Alembic 迁移;每个迁移任务后 `flask db heads` 必须单 head。 +- 📡 所有 JSON POST 必须带 `Content-Type: application/json`(沿用 `transfer.api.ts` 的 `jsonHeaders` 模式)。 +- 📝 新建/调整文件遵守 AGENTS.md §5 注释三层结构(文件块注释 + 函数 docstring 含 Args/Returns/AI 触发时机)。 +- 后端测试门禁:`cd backend && python -m pytest tests/services/in_transit_transfer tests/api/test_in_transit_transfer_api.py -q` 全绿;前端门禁:`cd frontend && npx vitest run` 相关文件 + `npm run build` 绿。 +- 调拨域测试发票号夹具必须带真实前缀(HOM/HOX/WTP,见记忆教训);禁引入 `SHIPPING_RPA_*` 命名。 + +--- + +### Task 1: 类型配置表模型与迁移 + +**Files:** +- Modify: `backend/app/models/in_transit_transfer.py`(新增模型类;同时删除 `TRANSFER_RUN_TYPES` 元组及 `transfer_type` 列定义上的 CHECK 引用) +- Create: `backend/migrations/versions/tt10a1b2c3d4e_transfer_type_configs.py` +- Test: `backend/tests/services/in_transit_transfer/test_transfer_type_config_model.py` + +**Interfaces:** +- Produces: `TransferTypeConfig`(模型类,表 `transfer_type_configs`),供 Task 4 服务层与 Task 11 切换使用。 + +- [ ] **Step 1: 写失败测试(模型与约束存在性)** + +```python +"""transfer_type_configs 模型契约测试。""" + +from app.models.in_transit_transfer import TransferTypeConfig + + +def test_table_and_unique_code(app_ctx): + """编码唯一且不可空;names_json/scope_rules_json 等为 JSON 列。""" + assert TransferTypeConfig.__tablename__ == 'transfer_type_configs' + cols = {c.name: c for c in TransferTypeConfig.__table__.columns} + assert cols['code'].nullable is False + assert cols['names_json'].type.python_type is dict + assert cols['enabled'].default.arg is False or cols['enabled'].default.arg is True + + +def test_transfer_runs_check_dropped(): + """transfer_runs.transfer_type 不再挂枚举 CHECK 约束(配置化取代)。""" + from app.models.in_transit_transfer import TransferRun + names = {c.name for c in TransferRun.__table__.constraints if hasattr(c, 'name') and c.name} + assert 'ck_transfer_runs_transfer_type' not in names +``` + +- [ ] **Step 2: 跑测试确认失败** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_transfer_type_config_model.py -v` +Expected: FAIL(`TransferTypeConfig` 不存在) + +- [ ] **Step 3: 实现模型与迁移** + +模型(追加到 `backend/app/models/in_transit_transfer.py`,模块 docstring 同步更新): + +```python +class TransferTypeConfig(Base): + """调拨类型配置(ADR 0002):编码/四语言名称/启停/排序 + 范围规则/仓库定义/转换规则。 + + code 创建后不可变(transfer_runs.transfer_type 引用);只有停用没有删除; + 配置为空时匹配链路 fail-closed(TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED)。 + """ + + __tablename__ = 'transfer_type_configs' + __table_args__ = ( + UniqueConstraint('code', name='uq_transfer_type_configs_code'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + code: Mapped[str] = mapped_column(String(64), nullable=False) + names_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict) + enabled: Mapped[bool] = mapped_column(default=False, server_default=text('false'), nullable=False) + sort_order: Mapped[int] = mapped_column(Integer, default=0, server_default=text('0'), nullable=False) + scope_rules_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list) + warehouse_config_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict) + transform_rules_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list) + description: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) +``` + +同时:删除 `TRANSFER_RUN_TYPES` 元组与 `transfer_type` 列 `CheckConstraint` 中的引用(列本身保留)。迁移(`flask db migrate -m "add transfer_type_configs and drop transfer type check"` 后手改校验)须包含:建表 + `op.drop_constraint('ck_transfer_runs_transfer_type', 'transfer_runs', type_='check')`;downgrade 重建约束(用原四值元组)。 + +- [ ] **Step 4: 跑测试确认通过** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_transfer_type_config_model.py tests/models -v` +Expected: PASS + +- [ ] **Step 5: 校验迁移链单 head 并升级** + +Run: `cd backend && flask db heads && flask db upgrade` +Expected: 单 head;upgrade 成功 + +- [ ] **Step 6: Stage changes** + +```bash +git add backend/app/models/in_transit_transfer.py backend/migrations/versions/tt10a1b2c3d4e_transfer_type_configs.py backend/tests/services/in_transit_transfer/test_transfer_type_config_model.py +``` + +--- + +### Task 2: 范围规则引擎 scope_rules.py + +**Files:** +- Create: `backend/app/services/in_transit_transfer/scope_rules.py` +- Test: `backend/tests/services/in_transit_transfer/test_scope_rules.py` + +**Interfaces:** +- Consumes: `app.core.errors.ValidationError`。 +- Produces: `SCOPE_FIELDS: frozenset[str]`;`ScopeRule(field, match, values)` frozen dataclass;`parse_scope_rules(raw: list[dict]) -> tuple[ScopeRule, ...]`;`evaluate_scope(record: Mapping[str, str | None], rules) -> bool`;`apply_scope_filters(query: Select, model: type, rules) -> Select`;`scope_rules_note(rules) -> str`。Task 11(圈档/重查)、Task 5(API 校验)消费。 + +- [ ] **Step 1: 写失败测试(覆盖语义矩阵)** + +```python +"""范围规则引擎契约:规则间 AND、规则内多值 OR、受控词表、SQL 编译与内存求值同口径。""" + +import pytest +from sqlalchemy import select + +from app.core.errors import ValidationError +from app.services.in_transit_transfer.scope_rules import ( + apply_scope_filters, evaluate_scope, parse_scope_rules, scope_rules_note, +) + + +RULES = parse_scope_rules([ + {"field": "doc_no", "match": "prefix", "values": ["HOM", "HOX"]}, + {"field": "source_code", "match": "in", "values": ["SRC-A"]}, +]) + + +def test_rules_are_and_values_are_or(): + """两条规则须同时满足;同一规则内任一前缀命中即可。""" + assert evaluate_scope({"doc_no": "HOM-1", "source_code": "SRC-A"}, RULES) + assert evaluate_scope({"doc_no": "HOX-9", "source_code": "SRC-A"}, RULES) + assert not evaluate_scope({"doc_no": "HOM-1", "source_code": "SRC-B"}, RULES) + assert not evaluate_scope({"doc_no": "INV-1", "source_code": "SRC-A"}, RULES) + + +def test_match_modes(): + rules = parse_scope_rules([ + {"field": "odm_id", "match": "equals", "values": ["HoxinRMA"]}, + {"field": "material_name", "match": "contains", "values": ["轴承"]}, + ]) + assert evaluate_scope({"odm_id": "HoxinRMA", "material_name": "精密轴承"}, rules) + assert not evaluate_scope({"odm_id": "Other", "material_name": "精密轴承"}, rules) + + +def test_unknown_field_rejected(): + with pytest.raises(ValidationError): + parse_scope_rules([{"field": "password", "match": "equals", "values": ["x"]}]) + + +def test_sql_compiler_matches_memory_predicate(app_ctx): + """SQL 编译结果与内存谓词同口径:同一批记录两种求值结果一致。""" + from app.models.in_transit_transfer import TransferMovementLedger # Task 9 前以临时模型/内联表替代 + records = [ + {"doc_no": "HOM-1", "source_code": "SRC-A"}, + {"doc_no": "INV-1", "source_code": "SRC-A"}, + ] + assert all(evaluate_scope(r, RULES) for r in records if r["doc_no"] == "HOM-1") + assert scope_rules_note(RULES) == "doc_no prefix HOM|HOX AND source_code in SRC-A" +``` + +> 注:`test_sql_compiler_matches_memory_predicate` 在 Task 9(档模型)落地前,用 `apply_scope_filters(select(...), ledger_model, RULES)` 编译后以 `str(query)` 断言生成 SQL 含 `LIKE 'HOM%'`/`LIKE 'HOX%'`(大写)与 `IN`;Task 9 完成后回补真库断言。 + +- [ ] **Step 2: 跑测试确认失败** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_scope_rules.py -v` +Expected: FAIL(模块不存在) + +- [ ] **Step 3: 实现引擎** + +```python +"""services/in_transit_transfer/scope_rules.py + +用途:调拨类型范围规则引擎——受控字段白名单上的「字段+匹配方式+值列表」规则, + 规则间 AND、规则内多值 OR;内存谓词与 SQL 编译双形态共用同一解析结果, + 供匹配创建圈档、重查对账、管理页校验三处单一口径。 +依赖:app.core.errors.ValidationError;SQLAlchemy Select(编译形态)。 +逻辑:parse 校验词表/匹配方式/值非空 → ScopeRule 元组;evaluate 逐规则 AND、 + 逐值 OR(prefix/contains 大小写不敏感);apply_scope_filters 生成等价 SQL。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Mapping, Sequence + +from sqlalchemy import Select, and_, or_, func +from app.core.errors import ValidationError + +# 受控字段词表(封闭可扩展;新增字段须同步管理页下拉与 technical.md)。 +SCOPE_FIELDS: frozenset[str] = frozenset({ + "source_code", "doc_no", "warehouse_code", "storage_code", "lot_no", + "movement_date", "record_kind", "in_out_flag", "order_type", "odm_id", + "odm_name", "carton_id", "pallet_id", "material_code", "doc_nature", + "movement_type", "reason_code", "partner_code", +}) + +_MATCHES = ("prefix", "equals", "contains", "in") + + +@dataclass(frozen=True) +class ScopeRule: + """单条范围规则:field 字段 / match 匹配方式 / values 值列表(规则内 OR)。""" + + field: str + match: str + values: tuple[str, ...] + + +def parse_scope_rules(raw: list[dict] | None) -> tuple[ScopeRule, ...]: + """校验并解析范围规则 JSON(管理页保存与匹配快照共用)。 + + Args: + raw: [{"field", "match", "values"}];空列表/None 合法(=不限,由调用方决定是否放行)。 + Returns: + ScopeRule 元组。 + Raises: + ValidationError: 字段不在 SCOPE_FIELDS、match 非法、values 空/非字符串。 + """ + rules: list[ScopeRule] = [] + for item in raw or []: + field, match = str(item.get("field", "")), str(item.get("match", "")) + values = item.get("values") or [] + if field not in SCOPE_FIELDS: + raise ValidationError(f"unknown scope field: {field}", code="TRANSFER.SCOPE_RULE_INVALID", details={"field": field}) + if match not in _MATCHES or not values or not all(isinstance(v, str) and v.strip() for v in values): + raise ValidationError(f"invalid scope rule: {field}/{match}", code="TRANSFER.SCOPE_RULE_INVALID", details={"field": field, "match": match}) + rules.append(ScopeRule(field=field, match=match, values=tuple(v.strip() for v in values))) + return tuple(rules) + + +def _hit(value: str | None, rule: ScopeRule) -> bool: + text = str(value or "").strip().upper() + if not text: + return False + if rule.match == "prefix": + return text.startswith(tuple(v.upper() for v in rule.values)) + if rule.match == "equals": + return text in {v.upper() for v in rule.values} + if rule.match == "contains": + return any(v.upper() in text for v in rule.values) + return text in {v.upper() for v in rule.values} # in + + +def evaluate_scope(record: Mapping[str, Any], rules: Sequence[ScopeRule]) -> bool: + """内存求值:规则间 AND、规则内多值 OR(匹配/测试/小数据场景)。""" + return all(_hit(record.get(rule.field), rule) for rule in rules) + + +def apply_scope_filters(query: Select, model: type, rules: Sequence[ScopeRule]) -> Select: + """SQL 编译(与 evaluate_scope 同口径):圈档与重查对账共用,防谓词漂移。""" + clauses = [] + for rule in rules: + col = getattr(model, rule.field) + upper = func.upper(col) + if rule.match == "prefix": + clauses.append(or_(*(upper.like(f"{v.upper()}%") for v in rule.values))) + elif rule.match == "equals": + clauses.append(upper.in_([v.upper() for v in rule.values])) + elif rule.match == "contains": + clauses.append(or_(*(upper.contains(v.upper()) for v in rule.values))) + else: + clauses.append(upper.in_([v.upper() for v in rule.values])) + return query.filter(and_(*clauses)) if clauses else query + + +def scope_rules_note(rules: Sequence[ScopeRule]) -> str: + """范围规则审计说明(写 scope_json 旁路人读字段)。""" + parts = [] + for rule in rules: + parts.append(f"{rule.field} {rule.match} {'|'.join(rule.values)}") + return " AND ".join(parts) +``` + +- [ ] **Step 4: 跑测试确认通过** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_scope_rules.py -v` +Expected: PASS + +- [ ] **Step 5: Stage changes** + +```bash +git add backend/app/services/in_transit_transfer/scope_rules.py backend/tests/services/in_transit_transfer/test_scope_rules.py +``` + +--- + +### Task 3: 字段转换引擎 field_transforms.py + +**Files:** +- Create: `backend/app/services/in_transit_transfer/field_transforms.py` +- Test: `backend/tests/services/in_transit_transfer/test_field_transforms.py` + +**Interfaces:** +- Produces: `TRANSFORM_FIELDS = frozenset({"lot_no"})`;`TRANSFORM_OPS = frozenset({"prefix_replace"})`;`TransformRule(field, op, source, target)`;`parse_transform_rules(raw) -> tuple[TransformRule, ...]`;`apply_field_transforms(field: str, value: str | None, rules) -> str | None`;`transform_rules_note(rules) -> str`。Task 11(六边界点接线)、Task 5/6(校验与 UI)消费。 + +- [ ] **Step 1: 写失败测试** + +```python +"""字段转换引擎契约:前缀替换链式生效、字段白名单、原值不篡改(返回新值)。""" + +import pytest +from app.core.errors import ValidationError +from app.services.in_transit_transfer.field_transforms import ( + apply_field_transforms, parse_transform_rules, +) + +RULES = parse_transform_rules([ + {"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"}, +]) + + +def test_prefix_replace(): + assert apply_field_transforms("lot_no", "WTP26062302", RULES) == "HOW26062302" + assert apply_field_transforms("lot_no", "ABC123", RULES) == "ABC123" + + +def test_none_and_empty_passthrough(): + assert apply_field_transforms("lot_no", None, RULES) is None + assert apply_field_transforms("lot_no", "", RULES) == "" + + +def test_chained_rules_apply_in_order(): + rules = parse_transform_rules([ + {"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"}, + {"field": "lot_no", "op": "prefix_replace", "source": "HOW", "target": "HOWX"}, + ]) + assert apply_field_transforms("lot_no", "WTP1", rules) == "HOWX1" + + +def test_field_whitelist(): + with pytest.raises(ValidationError): + parse_transform_rules([{"field": "quantity", "op": "prefix_replace", "source": "A", "target": "B"}]) +``` + +- [ ] **Step 2: 跑测试确认失败** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_field_transforms.py -v` +Expected: FAIL + +- [ ] **Step 3: 实现引擎** + +```python +"""services/in_transit_transfer/field_transforms.py + +用途:调拨类型字段转换规则引擎——「外部系统值→ERP 值」的受控派生 + (一期仅 lot_no 前缀替换),只在系统边界生效;行与档保持文件原值。 +依赖:app.core.errors.ValidationError。 +逻辑:parse 校验白名单 → TransformRule 元组;apply 按序链式派生(未命中恒等)。 + 【AI 触发时机】任何把行上字段值发往外部系统或按派生值聚合/展示的场景 + (库存查询 targets、写前复查、建单单行、票行聚合键、前端批号展示), + 必须经本引擎按当前匹配快照的规则求值;禁止直接调用硬编码前缀转换。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Sequence + +from app.core.errors import ValidationError + +TRANSFORM_FIELDS: frozenset[str] = frozenset({"lot_no"}) +TRANSFORM_OPS: frozenset[str] = frozenset({"prefix_replace"}) + + +@dataclass(frozen=True) +class TransformRule: + """单条转换规则:field 字段 / op 转换方式 / source 原前缀 / target 新前缀。""" + + field: str + op: str + source: str + target: str + + +def parse_transform_rules(raw: list[dict] | None) -> tuple[TransformRule, ...]: + """校验并解析转换规则 JSON;空列表/None = 恒等(无转换)。""" + rules: list[TransformRule] = [] + for item in raw or []: + field, op = str(item.get("field", "")), str(item.get("op", "")) + source, target = str(item.get("source", "")), str(item.get("target", "")) + if field not in TRANSFORM_FIELDS or op not in TRANSFORM_OPS or not source or not target: + raise ValidationError( + f"invalid transform rule: {field}/{op}", code="TRANSFER.TRANSFORM_RULE_INVALID", + details={"field": field, "op": op}, + ) + rules.append(TransformRule(field=field, op=op, source=source.upper(), target=target.upper())) + return tuple(rules) + + +def apply_field_transforms(field: str, value: str | None, rules: Sequence[TransformRule]) -> str | None: + """按规则序链式派生;未命中规则恒等返回原值(None/空串透传)。""" + result = value + for rule in rules: + if rule.field != field or not result: + continue + if rule.op == "prefix_replace" and result.upper().startswith(rule.source): + result = rule.target + result[len(rule.source):] + return result + + +def transform_rules_note(rules: Sequence[TransformRule]) -> str: + """转换规则审计说明。""" + return " THEN ".join(f"{r.field} {r.op} {r.source}->{r.target}" for r in rules) +``` + +- [ ] **Step 4: 跑测试确认通过** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_field_transforms.py -v` +Expected: PASS + +- [ ] **Step 5: Stage changes** + +```bash +git add backend/app/services/in_transit_transfer/field_transforms.py backend/tests/services/in_transit_transfer/test_field_transforms.py +``` + +--- + +### Task 4: 类型配置服务 transfer_type_config_service.py + +**Files:** +- Create: `backend/app/services/in_transit_transfer/transfer_type_config_service.py` +- Test: `backend/tests/services/in_transit_transfer/test_transfer_type_config_service.py` + +**Interfaces:** +- Consumes: Task 1 模型、Task 2/3 引擎。 +- Produces: + - `WarehouseRole(mode: str, warehouse_code: str | None, external_org: str | None)`、`WarehouseConfig(from_role: WarehouseRole, to_role: WarehouseRole)`(`mode ∈ {"mapped","fixed"}`;fixed 时 warehouse_code 必填) + - `TransferTypeConfigDTO(code, names, enabled, sort_order, scope_rules, warehouse_config, transform_rules, description, updated_at)` + - `list_configs() -> list[DTO]` / `get_enabled() -> list[DTO]` / `get_by_code(code) -> DTO`(不存在 raise `TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED`) + - `create_config(payload: dict, operator_id) -> DTO`(code 重复 raise `TRANSFER.TRANSFER_TYPE_CODE_EXISTS`;code 必须 `^[a-z][a-z0-9_]{1,63}$`;names_json 必须含非空 `zh-CN`;默认要求 scope_rules 至少一条) + - `update_config(code, payload, operator_id) -> DTO`(payload 含 code 且不等时 raise `TRANSFER.TRANSFER_TYPE_CODE_IMMUTABLE`) + - `resolve_warehouse(route_mapped: RouteMapping, config: WarehouseConfig, role: str) -> tuple[str, str]`:返回 `(external_org, warehouse_code)`;`fixed` 覆盖仓库、`external_org` 非空覆盖法人,`mapped` 透传。Task 11 路由接入消费。 + +- [ ] **Step 1: 写失败测试**——覆盖:create 成功/重复 code/非法 code/缺 zh-CN/空 scope_rules 默认拒绝;update code 不可变;get_enabled 只回 enabled 且按 sort_order 排序;resolve_warehouse 四组合(mapped 透传 / fixed 覆盖仓库 / fixed+org 覆盖法人 / fixed 缺 warehouse_code 抛 `TRANSFER.WAREHOUSE_CONFIG_INVALID`)。 +- [ ] **Step 2: 跑测试确认失败**(模块不存在) +- [ ] **Step 3: 实现服务**——模块 docstring 声明用途(类型配置域服务,ADR 0002)与依赖;CRUD 用 `db.session`;parse 校验复用 Task 2/3 的 `parse_scope_rules`/`parse_transform_rules`;`warehouse_config` 解析器 `_parse_warehouse_config(raw: dict) -> WarehouseConfig`(mode 白名单、fixed 必填仓库编码,非法 raise `TRANSFER.WAREHOUSE_CONFIG_INVALID`);DTO 组装时 scope/transform/warehouse 全部走 parse(保证库内脏数据在读取侧也被拦截)。 +- [ ] **Step 4: 跑测试确认通过** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_transfer_type_config_service.py -v` +Expected: PASS + +- [ ] **Step 5: Stage changes** + +```bash +git add backend/app/services/in_transit_transfer/transfer_type_config_service.py backend/tests/services/in_transit_transfer/test_transfer_type_config_service.py +``` + +--- + +### Task 5: 类型 API(admin CRUD + chat 列表)与四语言错误码 + +**Files:** +- Create: `backend/app/api/admin/transfer_type.py` +- Modify: `backend/app/api/admin/__init__.py`(注册新资源,沿用 `shipping_inventory.py` 的注册模式) +- Modify: `backend/app/api/in_transit_transfer/__init__.py`(新增 `GET /transfer-types`;该 Blueprint 前缀 `/api/in-transit-transfer`,鉴权沿用文件内 `require_transfer_permission`) +- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/errors.json`(新增 6 个错误码文案) +- Test: `backend/tests/api/test_transfer_type_api.py` + +**Interfaces:** +- Consumes: Task 4 服务。 +- Produces: `GET/POST /api/admin/in-transit-transfer/transfer-types`、`PUT /api/admin/in-transit-transfer/transfer-types/`(平台管理员鉴权,沿用 admin 目录既有鉴权装饰器模式);`GET /api/in-transit-transfer/transfer-types`(Agent 权限,仅 enabled,按 sort_order,返回 `{code, names, sort_order, transform_rules}`)。 + +- [ ] **Step 1: 写失败测试**——admin 列表/创建/更新/未授权 403/code 不可变 422/重复 code 422;chat 列表仅 enabled 且不含 scope_rules/warehouse_config(最小暴露);错误码 key 与四语言 errors.json 完全一致(读 JSON 文件断言)。 +- [ ] **Step 2: 跑测试确认失败** +- [ ] **Step 3: 实现两个 API 文件**——envelope 走 `response_utils`;`TRANSFER_TYPE_*`/`SCOPE_RULE_INVALID`/`WAREHOUSE_CONFIG_INVALID`/`TRANSFORM_RULE_INVALID` 错误码常量统一放 `transfer_type.py` 或新 `errors` 常量区(避免散落);chat GET 不要求平台管理员。 +- [ ] **Step 4: 补四语言 errors.json**(zh-CN 文案示例:`TRANSFER_TYPE_NOT_CONFIGURED`: "暂无可用调拨类型,请先在管理端配置";其余语言同义翻译) +- [ ] **Step 5: 跑测试确认通过 + 全量域回归** + +Run: `cd backend && python -m pytest tests/api/test_transfer_type_api.py tests/api/test_in_transit_transfer_api.py -v` +Expected: PASS + +- [ ] **Step 6: Stage changes** + +```bash +git add backend/app/api/admin/transfer_type.py backend/app/api/admin/__init__.py backend/app/api/in_transit_transfer/__init__.py backend/tests/api/test_transfer_type_api.py frontend/src/locales/zh-CN/errors.json frontend/src/locales/zh-TW/errors.json frontend/src/locales/en/errors.json frontend/src/locales/th/errors.json +``` + +--- + +### Task 6: admin 前端模块页(transfer-types) + +**Files:** +- Create: `frontend/src/features/admin/modules/transfer-types/TransferTypesPage.vue`、同目录 `useTransferTypesAdmin.ts`、`transferTypes.api.ts` +- Modify: `frontend/src/features/admin/constants/modules.ts`(AdminModuleId 增 `transfer-types`)、`frontend/src/features/admin/index.ts`、`frontend/src/features/admin/components/AdminNav.vue`(iconMap)、`frontend/src/app/router/routes/admin.routes.ts` +- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/admin.json`(模块名与页面文案) +- Test: `frontend/src/features/admin/modules/transfer-types/__tests__/TransferTypesPage.spec.ts` + +**Interfaces:** +- Consumes: Task 5 admin API。 +- Produces: 管理页(列表 + 编辑抽屉四块:基本信息/范围规则行编辑器/仓库定义/转换规则行编辑器);字段下拉选项从 `SCOPE_FIELDS` 对应的 i18n 映射渲染。 +- **UI 规范(框线图,与规格 §12.1 一致):** + +``` +┌ 管理端 › 在途调拨类型 ──────────────────────[+ 新建类型] ┐ +│ 搜索编码/名称… [状态: 全部▾] │ +│ ┌ 编码 名称 规则数 状态 操作 ┐ │ +│ │ in_transit_to_hub 在途仓至HUB仓 1 [启用●] 编辑 │ │ +│ │ hub_repair_out HUB仓维修出 0 [停用○] 编辑 │ │ +│ └ 空态: 图标+「暂无调拨类型」+[新建类型]按钮 ─────────┘ │ +└────────────────────── 点击编辑 ↓ 右侧抽屉(≥480px)────────┐ +│ ① 基本信息: 编码*(创建后只读) / 名称* 四语言(zh-CN必填) │ +│ / 排序[10] / 状态(●)启用(○)停用 │ +│ ② 范围规则(规则间=且,规则内多值=或) │ +│ ┌ 字段▾ ┬ 匹配▾ ┬ 值(tag 多选) ┬ 🗑 ┐ │ +│ │ 收料单号 │ 前缀▾ │ [HOM✕][HOX✕][WTP✕] │ │ │ +│ │ 来源实例 │ 属于▾ │ [SRC-A✕][SRC-B✕] │ │ │ +│ └─────────┴────────┴───────────────────┴────┘ │ +│ [+添加规则] ⚠ 与启用类型「X」范围重叠——确认是否有意 │ +│ ③ 仓库定义: 拨出[映射档▾/固定▾] 拨入[映射档▾/固定▾] │ +│ 固定时: 编码[WH-REPAIR] + 法人覆盖[—](空=沿用映射档法人) │ +│ ✓/✕ 映射档存在性校验(黄色提示不拦截) │ +│ ④ 转换规则: [批号▾][前缀替换▾][WTP]→[HOW] [+添加转换] │ +│ [取消] [保存] │ +└──────────────────────────────────────────────────────────┘ +``` + +**交互与可用性规则(必须落实)**:①onBlur 校验,错误文案在字段正下方 + `aria-describedby` 关联,禁止只弹 toast/只标红;②提交失败顶部渲染可聚焦错误摘要(`role="alert"`),每条锚点跳到对应字段,行内错误保留;③保存按钮 loading→成功/失败反馈;④所有输入显式 label(禁 placeholder 当 label),tag 删除按钮点击区 ≥24px;⑤列表空态给「消息+行动」;⑥重叠提示/映射档未命中=黄色提示条**不拦截**保存(D10/D6)。 + +- [ ] **Step 1: 写失败组件测试**——渲染列表行;编辑抽屉:范围规则「添加规则」→ 选字段/匹配方式/输入值 → 保存 payload 断言(规则间 AND 结构);仓库定义 mode 切换(fixed 显示仓库编码输入);code 编辑态只读;四语言 admin.json 含模块键(断言四个 locale 文件)。 +- [ ] **Step 2: 跑测试确认失败**(`npx vitest run src/features/admin/modules/transfer-types`) +- [ ] **Step 3: 实现页面**——组件结构沿用 `shipping-inventory/ShippingInventoryPage.vue` 模式(列表页 + `use*Admin.ts` composable + api 文件);范围规则行编辑器:每行 `字段下拉 + 匹配方式下拉(prefix/equals/contains/in) + 多值输入(逗号或 tag)`;重叠提示:保存前对比其它启用类型的规则并集(调列表接口在客户端比对),有交集黄条提示不硬拦;四语言文案键前缀 `admin.transferTypes.*`。 +- [ ] **Step 4: 跑组件测试 + 注册完整性测试确认通过**(若仓库存在 admin 导航顺序 spec,一并更新) + +Run: `cd frontend && npx vitest run src/features/admin/modules/transfer-types && npm run build` +Expected: PASS / build 绿 + +- [ ] **Step 5: Stage changes** + +```bash +git add frontend/src/features/admin/modules/transfer-types frontend/src/features/admin/constants/modules.ts frontend/src/features/admin/index.ts frontend/src/features/admin/components/AdminNav.vue frontend/src/app/router/routes/admin.routes.ts 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: chat 前端类型选择接口化 + +**Files:** +- Modify: `frontend/src/features/chat/types/transfer.types.ts`(union 改 `string`,删除三值字面量) +- Modify: `frontend/src/features/chat/api/transfer.api.ts`(新增 `fetchTransferTypes()`) +- Modify: `frontend/src/features/chat/composables/useChatTransfer.ts`(types 拉取与状态;沿用 `loadSources` 的单飞模式) +- Modify: `frontend/src/features/chat/components/messages/TransferSourceSelectCard.vue`(选项改 props 注入;删除 `transferTypeOptions` 写死数组与「即将上线」逻辑;空数组渲染空态 `transferTypeEmpty`) +- Modify: `frontend/src/features/chat/components/messages/transferBatch.ts`(`deriveBatchNo(value, rules)` 规则驱动,默认规则=现行 WTP→HOW 以兼容未传场景) +- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json`(新增 `transferTypeEmpty`;`transferType.{code}` 动态名称不再走 i18n,静态三键可移除) +- Test: 更新 `TransferSourceSelectCard.spec.ts`、`useChatTransfer.spec.ts`、`transferCards.spec.ts` + +**Interfaces:** +- Consumes: Task 5 `GET /transfer-types`。 +- Produces: 类型按钮组=接口数据;选中类型 code 随 `confirm` 事件上抛(现有签名不变);`deriveBatchNo` 接受 `TransformRule[]` 形参(从所选类型的 `transform_rules` 传入)。 +- **UI 规范(框线图,与规格 §12.2 一致):** + +``` +┌ 选择收料来源实例 ──────────────────────────────────┐ +│ 匹配参数 │ +│ 调拨类型 [在途仓至HUB仓] [HUB仓维修出] [HUB仓间调拨]│ ←选项=接口下发(enabled), +│ 收料日期 [2026/10/12] ~ [2026/10/12] ⓘ │ 名称 names[locale]→zh-CN→en +│ …(来源实例列表/全选可见/只选可重试等全部不变) │ +│ [确认范围并匹配] │ +└────────────────────────────────────────────────────┘ +配置为空时: +│ 调拨类型 ⚠ 暂无可用调拨类型,请联系管理员在管理端配置│ +│ [确认范围并匹配](禁用+ │ +│ tooltip 说明原因) │ +``` + +变更点:删除写死三选项数组与「即将上线」徽标;按钮组数据=`GET /transfer-types`;空列表渲染空态文案(四语言 `transferTypeEmpty`)且确认按钮禁用。 + +- [ ] **Step 1: 更新失败测试**——mock 接口返回两类(其一 enabled)→ 断言只渲染 enabled;空返回 → 空态文案;「即将上线」断言删除;`deriveBatchNo("WTP1", [{field:"lot_no",op:"prefix_replace",source:"WTP",target:"HOW"}]) === "HOW1"`。 +- [ ] **Step 2: 跑测试确认失败** +- [ ] **Step 3: 实现改造**——`useChatTransfer` 增 `transferTypes` ref + `loadTransferTypes()`(与 `loadSources` 同样的模块级单飞防抖);`TransferMessageView.vue` 在 `kind==='source-select'` 挂载时并行拉取;名称显示 `names[locale] || names['zh-CN'] || names.en`。 +- [ ] **Step 4: 跑测试 + build** + +Run: `cd frontend && npx vitest run src/features/chat && npm run build` +Expected: PASS / build 绿 + +- [ ] **Step 5: Stage changes** + +```bash +git add frontend/src/features/chat/types/transfer.types.ts frontend/src/features/chat/api/transfer.api.ts frontend/src/features/chat/composables/useChatTransfer.ts frontend/src/features/chat/components/messages/TransferSourceSelectCard.vue frontend/src/features/chat/components/messages/transferBatch.ts frontend/src/features/chat/components/messages/TransferMessageView.vue 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 8: 解析契约扩展(movement 契约新字段) + +**Files:** +- Modify: `backend/app/services/in_transit_transfer/movement_contract.py`(MOVEMENT_FIELDS 追加可选字段) +- Modify: 解析 Profile 字段映射白名单处(`shipping_inventory_parsing_profiles` 的 movement purpose 映射项;跟随既有「字段⇄Excel表头」映射实现) +- Test: `backend/tests/services/in_transit_transfer/test_movement_contract.py`(追加) + +**Interfaces:** +- Produces: 契约新增可选字段 `line_seq`(项序)、`specification`(规格,若契约尚无)、`order_type`(订单类型)、`odm_id`、`odm_name`、`carton_id`(箱号)、`pallet_id`(栈板号)——全部 `required=False, is_identity=False`;`movement_field_codes()` 自动含新码。Task 10 档落地消费。 + +- [ ] **Step 1: 写失败测试**——`movement_field_codes()` 含全部新码;`parse_movement_rows` 对含新列的样本行能取值、缺列时字段值 None(不报错,保持既有缺列容忍语义)。 +- [ ] **Step 2: 跑测试确认失败** +- [ ] **Step 3: 实现契约扩展**——MOVEMENT_FIELDS 追加 `MovementField(..., required=False)`;不动既有 11 字段语义与 identity 集(`movement_match_key` 不变);Profile 管理端映射下拉自动继承(若映射白名单为硬编码清单则同步补)。 +- [ ] **Step 4: 跑契约与解析相关测试** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer -k "movement or contract or parse" -v` +Expected: PASS(既有用例不破) + +- [ ] **Step 5: Stage changes** + +```bash +git add backend/app/services/in_transit_transfer/movement_contract.py backend/tests/services/in_transit_transfer/test_movement_contract.py +``` + +--- + +### Task 9: 异动档模型与迁移 + +**Files:** +- Modify: `backend/app/models/in_transit_transfer.py`(新增 `TransferMovementLedger`) +- Create: `backend/migrations/versions/tt11b2c3d4e5f_transfer_movement_ledger.py` +- Test: `backend/tests/services/in_transit_transfer/test_transfer_movement_ledger_model.py` + +**Interfaces:** +- Produces: `TransferMovementLedger` 模型,列=规格 §4.2 全表;自然键唯一约束 `uq_transfer_movement_ledger_natural_key (source_code, record_kind, doc_no, line_no, line_seq, in_out_flag)`;索引 `(source_code, record_kind, movement_date)`、`(record_kind, transfer_executed)`;关系 `source_file` → `ShippingReceiptReportFile`。Task 10/11/12/13 消费。 + +- [ ] **Step 1: 写失败测试**——表名/自然键约束存在/`transfer_executed` 默认 false/可空成分 NOT NULL default ''(断言 `line_seq.nullable is False` 等)。 +- [ ] **Step 2: 跑测试确认失败** +- [ ] **Step 3: 实现模型+迁移**——列规格照抄规格 §4.2(数量 String(40)、日期 String(16),与 items 同约定;`movement_date` 可空);迁移建表+索引,`source_file_id` FK **ON DELETE SET NULL**(文件清理后档记录留存),单 head 校验后 upgrade。 +- [ ] **Step 4: 跑测试确认通过** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_transfer_movement_ledger_model.py -v && flask db heads` +Expected: PASS / 单 head + +- [ ] **Step 5: 回补 Task 2 的 SQL 编译真库断言**(`test_scope_rules.py` 中以真档表跑 `apply_scope_filters` 查询断言命中行集) +- [ ] **Step 6: Stage changes** + +```bash +git add backend/app/models/in_transit_transfer.py backend/migrations/versions/tt11b2c3d4e5f_transfer_movement_ledger.py backend/tests/services/in_transit_transfer/test_transfer_movement_ledger_model.py backend/tests/services/in_transit_transfer/test_scope_rules.py +``` + +--- + +### Task 10: 档落地 ledger_sync.py(不接线) + +**Files:** +- Create: `backend/app/services/in_transit_transfer/ledger_sync.py` +- Test: `backend/tests/services/in_transit_transfer/test_ledger_sync.py` + +**Interfaces:** +- Consumes: Task 8 契约行、Task 9 模型、`_latest_usable_report_file`(`matching_service.py` 既有)。 +- Produces: + - `LedgerSyncOutcome(inserted: int, updated: int, skipped: int, sealed_skipped: int, cross_flagged: int)` + - `sync_ledger_rows(*, source_code: str, record_kind: str, parsed_rows: list[dict], file_meta: FileMeta, now: datetime) -> LedgerSyncOutcome`——`FileMeta(source_file_id, file_version, file_sha256)`;自然键幂等(规格 §5 五条语义:插入/跳过/原行更新/缺席不删/封存不触碰);`record_kind` 与 `in_out_flag` 交叉校验矛盾时计 `cross_flagged` 并写审计事件(`build_transfer_audit_event`,event kind `ledger_cross_check_failed`)。Task 11 接线消费。 + +- [ ] **Step 1: 写失败测试**——首落插入;同文件重落全 skipped;证据变(改 quantity)原行更新且 `file_version` 换新;缺席记录保留;`transfer_executed=True` 的记录证据再变不更新(sealed_skipped 计数);record_kind='receipt' 行 `in_out_flag='-1'` → cross_flagged=1 且落档照常。 +- [ ] **Step 2: 跑测试确认失败** +- [ ] **Step 3: 实现 ledger_sync**——模块 docstring 声明「外部记录镜像落地;语义与 evidence_sync 三分类同源(ADR 0001)」;flush 不 commit(与 evidence_sync 同契约,提交归调用方);终态封存行跳过一切写。 +- [ ] **Step 4: 跑测试确认通过** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_ledger_sync.py -v` +Expected: PASS + +- [ ] **Step 5: Stage changes** + +```bash +git add backend/app/services/in_transit_transfer/ledger_sync.py backend/tests/services/in_transit_transfer/test_ledger_sync.py +``` + +--- + +### Task 11: 切换原子任务——档接线 + 匹配出生翻转 + 类型契约配置化 + +> ⚠️ 本任务是不可拆的原子切换(拆开任意一半都会让在产链路进入中间态)。执行前确认 Task 1-10 全部合入。**前提(D15):目标环境无存量调拨数据**——items/回填迁移类工作不存在,若上线前发现与前提不符,停止升级。 + +**Files:** +- Modify: `backend/app/services/in_transit_transfer/transfer_type.py`(整文件重写:枚举退役,改配置驱动) +- Modify: `backend/app/services/in_transit_transfer/evidence_sync.py`(落地写档、停写 items) +- Modify: `backend/app/services/in_transit_transfer/matching_service.py`(run_matching 圈档建 items;requery 对档对账;scope_item_query 退役;路由类型化;转换规则接线) +- Modify: `backend/app/services/in_transit_transfer/cancellation.py`(取消匹配时 items 转 cancelled 即释放档记录占用——D17 的释放出口,沿用既有取消语义) +- Modify: `backend/app/models/in_transit_transfer.py`(`TransferInvoiceItem` 增 `ledger_record_id`,含迁移 `tt12c3d4e5f6a7_item_ledger_record_fk.py`) +- Modify: `backend/app/services/in_transit_transfer/movement_contract.py`(`external_lot_no` 退役,改引擎派生;保留函数名做薄委托直至六调用点切净后删除) +- Modify: `backend/app/api/in_transit_transfer/__init__.py`(POST /matchings `transfer_type` 必填) +- Modify: `backend/app/jobs/handlers/in_transit_transfer_match.py`(异步 Job 回读快照不变,确认无枚举依赖) +- Test: 更新 `test_transfer_type.py` / `test_matching_service.py` / `test_requery_scope.py` / `test_in_transit_transfer_api.py` / evidence_sync 相关用例(断言对象平移到档) + +**Interfaces:** +- Consumes: Task 2/3 引擎、Task 4 服务(`get_by_code`/`resolve_warehouse`)、Task 10 `sync_ledger_rows`。 +- Produces: + - `transfer_type.py`:`resolve_transfer_type(code: str) -> TransferTypeConfigDTO`(必填;空/不存在→`TRANSFER_TYPE_NOT_CONFIGURED`;停用→`TRANSFER_TYPE_DISABLED`;旧 `normalize_transfer_type`/`ensure_transfer_type_supported`/`SUPPORTED_TRANSFER_TYPES` 删除);`invoice_in_scope`/`filter_invoices_for_type`/`transfer_type_scope_note` 删除(职责移交 scope_rules + 快照)。 + - `run_matching` STEP 0 新流程:`ledger_records = apply_scope_filters(Ledger 查询[record_kind='receipt', source IN, movement_date 范围, transfer_executed=false, 未被有效 items 占用(D17)], rules)` → 逐记录建 item(`matching_id`、`ledger_record_id`、业务字段=档原值、`receipt_quantity=record.quantity`、`raw_lines_json=[{sheet,row_no,file_version}]`)→ 路由 `resolve_warehouse` 落 from/to → 既有库存评估链不变。 + - `requery_items`:对档重圈(同一快照规则)→ 对账(新建/刷新/失效隔离)。 + - `scope_json` 快照键:`transfer_type, source_codes, receipt_date_from, receipt_date_to, scope_rules, scope_note, transform_rules`;hash 仍从 scope_json 内容计算(存量无新键→旧形状,复算兼容)。 + - 转换规则接线:`movement_contract.external_lot_no(lot_no)` 调用点改为 `apply_field_transforms("lot_no", lot_no, 快照规则)`(调用点:matching targets+lookup、retry targets+lookup、`_recheck_stock_for_document`、`_build_ticket_lines`、`serialize_ticket`);行落库保持原值。 + - evidence_sync:`sync_source_rows` 改为调 `sync_ledger_rows`(record_kind='receipt'),删除 items 三分类写入与 `filter_invoices_for_type` 调用(evidence_sync.py 原 L99-103);`sync_and_commit_for_callback` 桥隔离与 parse_failed 分层语义保留;`align_scope_rows` 删除(重查不再对文件对账,改对档对账)。 + +- [ ] **Step 1: 先写失败的切换契约测试** + 1. `test_transfer_type.py` 重写:配置存在→resolve 成功;空表→NOT_CONFIGURED;停用→DISABLED;必填(None→REQUIRED)。 + 2. `test_matching_service.py` 新增:种子档记录(含范围外单、已封存单)→ run_matching 后 items 恰为范围内未封存记录、`ledger_record_id` 正确、from/to 走仓库定义(fixed 覆盖断言)、scope_json 含新键、hash 与 scope_json 内容一致;**占用互斥(D17)**:匹配 A 已圈定的记录,匹配 B 圈档时排除;取消匹配 A 后 B 可重新圈定。 + 3. `test_requery_scope.py` 平移:档新增记录→重查补建 item;档证据变→item 刷新重置;`scope_item_query` 引用不存在(模块级 assert)。 + 4. evidence_sync 用例:断言对象从 items 改为档记录(插入/跳过/更新/封存语义沿用 Task 10 测试,桥接后端到端一遍)。 + 5. 展示健壮性(规格 §13.1):匹配/Run 的展示与审计序列化在配置表中无该类型 code 时仍成功(读 scope_json 快照,不查配置表)。 +- [ ] **Step 2: 跑确认失败**(`pytest tests/services/in_transit_transfer tests/api/test_in_transit_transfer_api.py -q`) +- [ ] **Step 3: 实施切换**——按 Interfaces 逐文件落实;`external_lot_no` 调用点逐个替换后删除函数与 `transferBatch.ts` 旧默认联动确认(前端 Task 7 已规则化);迁移 `tt12c3d4e5f6a7` 加列+索引。 +- [ ] **Step 4: 跑域全量回归** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer tests/api/test_in_transit_transfer_api.py -q` +Expected: 全绿(含存量兼容:hash 复算用例、file_removed 隔离用例) + +- [ ] **Step 5: Stage changes** + +```bash +git add backend/app/services/in_transit_transfer backend/app/api/in_transit_transfer backend/app/jobs/handlers/in_transit_transfer_match.py backend/migrations/versions/tt12c3d4e5f6a7_item_ledger_record_fk.py backend/tests/services/in_transit_transfer backend/tests/api/test_in_transit_transfer_api.py +``` + +--- + +### Task 12: 首页队列与执行门禁改锚 + +**UI 规范(框线图,与规格 §12.3 一致)**——待办看板加第 4 张卡,执行看板与其余卡片完全不变: + +``` +│ 待办看板 │ +│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ +│ │ 3 │ │ 0 │ │ 0 │ │ 0 │ │ +│ │ 待匹配 │ │ 可调拨明细│ │ 待恢复异常│ │ 已人工关闭│ │ +│ │ 已抓取尚未│ │ 勾选后按 │ │ 可重查库 │ │ 可查看原 │ │ +│ │ 匹配的外部│ │ 行生成调 │ │ 存或一键 │ │ 因并恢复 │ │ +│ │ 收料记录 │ │ 拨单 │ │ 恢复处理 │ │ 处理 │ │ +│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ +│ (新增卡·靛蓝) (绿·不变) (蓝·不变) (白·不变) │ +``` + +口径(D16/D17):启用类型范围并集内、`record_kind='receipt'`、未封存、无有效 items 的档记录计数;点击展开只读清单(单号/料号/收料日期/来源/数量)+「去匹配」引导按钮(=库存匹配入口);**不可勾选执行**。数字变化:文件落地→涨;被匹配圈定→离开;匹配后文件新增记录→再涨。 + +**Files:** +- Modify: `backend/app/services/in_transit_transfer/backlog_service.py`(队列数据源:档+items 联查,「待匹配」桶;圈定=启用类型范围并集,排除 `transfer_executed`) +- Modify: `backend/app/services/in_transit_transfer/execution_service.py`(票据成功落 `executed_doc_no` 时回写档 `transfer_executed`;`file_current` 门禁改档 `file_version` 对比) +- Modify: `backend/app/services/in_transit_transfer/retry_service.py`(targets 的转换规则来自行所属匹配快照——匹配创建时已固化在 scope_json,读快照求值) +- Modify: `frontend/src/features/chat/components/messages/TransferHomePanel.vue` 等(首页待办看板「待匹配」卡渲染与只读抽屉清单,不可勾选;四语言 chat.json 新增 `transferPendingMatch*` 键) +- Test: `test_backlog_service.py`、`test_execution_documents.py`、`test_retry_and_manual_close.py` 更新 + `test_queue_ledger_view.py` 新增 + +**Interfaces:** +- Consumes: Task 11 的档/快照。 +- Produces: 队列 DTO 增 `pending_match` 桶(`{ledger_record_id, doc_no, material_code, movement_date, source_code}`,无 item_id 不可执行);执行门禁 `file_current = item.ledger_record.file_version == 最新可用文件 sha`。 + +- [ ] **Step 1: 写失败测试**——档有记录无 items → 待匹配桶出现且不可执行;items ready → executable 桶;票据成功后档记录 `transfer_executed=True` 且从圈定中消失;档换版后 item 门禁转 stale/blocked。 +- [ ] **Step 2: 跑确认失败** +- [ ] **Step 3: 实现改造**(前后端) +- [ ] **Step 4: 域回归 + 前端 vitest/build** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer -q && cd ../frontend && npx vitest run src/features/chat && npm run build` +Expected: 全绿 + +- [ ] **Step 5: Stage changes** + +```bash +git add backend/app/services/in_transit_transfer backend/tests/services/in_transit_transfer frontend/src/features/chat frontend/src/locales +``` + +--- + +### Task 13: 提示词/catalog 同步 + 文档 + 全量收口 + +**Files:** +- Modify: `backend/app/services/agent_registry/handlers/in_transit_transfer.py`、`backend/app/services/agent_registry/data/catalog_manifest.yaml`(类型枚举叙述改「类型来自平台配置」;Dify 平台侧副本提示人工同步) +- Modify: `docs/features/in-transit-transfer/technical.md`(新增 §「调拨类型配置化与库存异动档」:表结构、规则引擎、切换语义、上线 SOP) +- Modify: `docs/funclist.md`(新增功能条目:调拨类型管理页、库存异动档、匹配明细翻转) +- Check: `docs/demand.md`(需求描述如含旧三类型枚举叙述则更新) +- Modify: `docs/skills/`、`GLOSSARY.md`(如术语有再修正) + +- [ ] **Step 1: grep 收口**——`grep -rn "hub_repair_out\|hub_to_hub\|IN_TRANSIT_TO_HUB\|transferTypeComingSoon\|scope_item_query\|external_lot_no" backend/app frontend/src docs | grep -v test`:仅允许存量数据兼容注释命中,代码引用必须为零。 +- [ ] **Step 2: 后端全量定向回归 + 前端全量 vitest + build** + +Run: `cd backend && python -m pytest tests/services/in_transit_transfer tests/api/test_in_transit_transfer_api.py -q && cd ../frontend && npx vitest run && npm run build` +Expected: 全绿 + +- [ ] **Step 3: Stage changes** + +```bash +git add backend/app/services/agent_registry docs/features/in-transit-transfer/technical.md docs/funclist.md docs/demand.md GLOSSARY.md +``` + +--- + +## 上线 SOP(发布说明引用) + +> 前提(D15):目标环境**无存量调拨数据**。若发现与前提不符,停止升级并联系设计方补回填方案。 + +1. 部署含迁移的版本(`flask db upgrade`,单 head)。 +2. 管理端「在途调拨类型」创建「在途仓至HUB仓」:code=`in_transit_to_hub`,范围规则=`doc_no prefix [HOM, HOX, WTP]`,仓库定义=from/to 均 mapped,转换规则=`lot_no prefix_replace WTP→HOW`,启用。 +3. 验证:收料文件落地 → 首页「待匹配」计数上涨;chat 选类型建匹配 → 记录进入可调拨明细 → 抽一单核对 ERP 单号与批号转换。 +4. 出现「暂无可用调拨类型」即 SOP 第 2 步遗漏(fail-closed 是设计行为)。 + +## 明确不做(YAGNI) + +- 出货解析/RPA、维修出/调拨出入执行链路、类型删除(只有停用)、按来源实例细分仓库、规则重叠硬拦截、转换规则反向(ERP→外部)。 diff --git a/docs/superpowers/plans/2026-10-15-inbound-outbound-idempotency-rename.md b/docs/superpowers/plans/2026-10-15-inbound-outbound-idempotency-rename.md new file mode 100644 index 00000000..94e60a3e --- /dev/null +++ b/docs/superpowers/plans/2026-10-15-inbound-outbound-idempotency-rename.md @@ -0,0 +1,730 @@ +# 入站/出站统一、幂等修复与解析类型枚举改版 实施计划 + +> **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:** 幂等修复(异动档自然键扩 8 成分 + movement_date 非空落档过滤)、解析规则 purpose 枚举改版(inventory/movement→onhand/inbound/outbound)、receipt→inbound 说辞三层清扫(一次到位无兼容层)。 + +**Architecture:** 两个 Alembic 迁移(tt14 列改名+record_kind 值+自然键重建、tt15 purpose 枚举)接续 tt13 单 head;后端结构波(ORM 属性/约束)与文案波(字符串/路由/错误码/注释)分两任务,各自编译绿;前端与 i18n 随后同口径更名;全程 movement 一词保留,shipping_notice 交界域只加注释不改名。 + +**Tech Stack:** Flask + SQLAlchemy 2.0 + Alembic(PG 语义、SQLite 往返测试)、Vue 3 + TS + Pinia + vitest、pytest。 + +**Spec:** `docs/superpowers/specs/2026-10-15-inbound-outbound-idempotency-rename-design.md`(对照表与决策 D1-D6 以 spec 为权威,本计划 argues from spec) + +## Global Constraints + +- **禁止自动 commit**:每个任务止于 `git add <显式路径>`;提交由用户显式批准后统一进行。 +- **i18n 四语言**:zh-CN / zh-TW / en / th 必须同步,缺一即审查不通过。 +- **术语边界**:只扫 receipt/shipment/收料/出货;**movement 一词保留**(`transfer_movement_ledger`、`MOVEMENT_FIELDS`、`movement_contract` 等不改)。shipping_notice 域文件、RPA 跨进程契约(`shipping_receipt_rpa.v1`/`receipt_export_batch`/trigger 文件名)、环境变量 `FREIGHT_RPA_RECEIPT_*` 一律不动(白名单 = spec §4.2/4.3)。 +- **迁移**:单 head;tt14/tt15 均须实现 downgrade;迁移语义按 PG,测试用 SQLite 往返(沿用 tt13 测试模式)。 +- **错误契约**:错误码更名必须同步四语言 `locales/*/errors.json`(键名与文案值)。 +- **注释纪律(AGENTS.md §5)**:改名处同步更新注释/docstring;模块头注释的「逻辑关系」描述同步。 +- **Windows 环境**:后端解释器 `backend/.venv/Scripts/python.exe`;pytest 从 `backend/` 运行;vitest/build 从 `frontend/` 运行。 +- **不新增第三方依赖。** + +--- + +### Task 1: tt14 迁移 + 数据层入站化(ORM 属性/约束/引用点) + +**Files:** +- Create: `backend/migrations/versions/tt14a5f6a7b8c9_inbound_rename_and_ledger_key.py` +- Modify: `backend/app/models/in_transit_transfer.py`(列属性、唯一约束成分、注释) +- Modify(引用点,编译器会暴露全量): `backend/app/services/in_transit_transfer/serializers.py`、`matching_service.py`、`execution_service.py`、`retry_service.py`、`excel_export.py`、`cancellation.py` 等 +- Test: `backend/tests/services/in_transit_transfer/test_migration_inbound_rename.py`(新建)、`test_transfer_movement_ledger_model.py`、`test_transfer_type_config_model.py` 等模型相关测试 + +**Interfaces:** +- Produces: ORM 属性 `TransferInvoiceItem.movement_date/movement_quantity/movement_warehouse_code`、`TransferDocument.movement_date`(**明细/单据是方向中立,用 movement_\*,不用 inbound_\***——spec §1 术语基线);tt14 迁移 revision `tt14a5f6a7b8c9`(down_revision=`tt13d4e5f6a7b8`)。本任务**只改 ORM 属性与 DB**,JSON 键/参数名等字符串说辞留给 Task 3。 +- 注意:序列化 JSON 的字典键(如 `"receipt_date"`)本任务**不改**(Task 3 统一改),因此 Task 1 后端到前端 API 形状不变。 + +- [ ] **Step 1: 写迁移契约测试(先失败)** + +```python +"""tt14a5f6a7b8c9 入站化迁移契约测试。 + +用途:锁定 tt14 迁移与模型两侧契约——transfer_invoice_items/transfer_documents + receipt_* 列更名 inbound_*;transfer_movement_ledger.record_kind 值迁移 + receipt→inbound / shipment→outbound;自然键唯一约束重建为 8 成分。 +依赖:migrations/versions(tt13 → tt14)、app_ctx。 +逻辑:revision 链断言 + 模型属性/约束成分断言 + SQLite 真实 upgrade/downgrade/upgrade 往返。 +""" +from __future__ import annotations + +import importlib.util +from pathlib import Path + +import pytest + +MIGRATIONS_DIR = Path(__file__).resolve().parents[3] / "migrations" / "versions" + + +def _load(revision_prefix: str): + for path in sorted(MIGRATIONS_DIR.glob(f"{revision_prefix}*.py")): + spec = importlib.util.spec_from_file_location(path.stem, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + raise AssertionError(f"migration {revision_prefix} not found") + + +def test_revision_chains_from_tt13_head(): + migration = _load("tt14a5f6a7b8c9") + assert migration.down_revision == "tt13d4e5f6a7b8" + + +def test_model_inbound_columns_and_ledger_key(app_ctx): + from app.models.in_transit_transfer import ( + TransferDocument, TransferInvoiceItem, TransferMovementLedger, + ) + + item_cols = {c.name for c in TransferInvoiceItem.__table__.columns} + assert {"movement_date", "movement_quantity", "movement_warehouse_code"} <= item_cols + assert not {"receipt_date", "receipt_quantity", "receipt_warehouse_code"} & item_cols + doc_cols = {c.name for c in TransferDocument.__table__.columns} + assert "movement_date" in doc_cols and "receipt_date" not in doc_cols + ledger_uq = next( + c for c in TransferMovementLedger.__table__.constraints + if getattr(c, "name", "") == "uq_transfer_movement_ledger_natural_key" + ) + assert [col.name for col in ledger_uq.columns] == [ + "source_code", "record_kind", "doc_no", "line_no", "line_seq", + "in_out_flag", "carton_id", "lot_no", + ] +``` + +- [ ] **Step 2: 运行测试确认失败** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_migration_inbound_rename.py -v` +Expected: FAIL(迁移文件不存在 / 模型仍是 receipt 列) + +- [ ] **Step 3: 写 tt14 迁移** + +```python +"""tt14 入站化:receipt_* 列更名 inbound_*、record_kind 值迁移、自然键扩 8 成分。 + +用途:落实 spec D1/D6——真实 WMS 文件行身份是「单据+行+箱/批」,自然键扩 + carton_id+lot_no;receipt 说辞一次性更名 inbound(无兼容层)。 +依赖:tt13d4e5f6a7b8。 +逻辑:batch_alter_table 完成 RENAME(PG/SQLite 双兼容);record_kind 值迁移为 + 数据 UPDATE(未上线为空操作,test 环境兜底);唯一约束按 8 成分重建。 + 列类型取自建表迁移(it1a2b3c4d5e/it2c3d4e5f6a7/tt0d1e2f3a4b)逐一核对。 +""" +revision = "tt14a5f6a7b8c9" +down_revision = "tt13d4e5f6a7b8" +branch_labels = None +depends_on = None + +import sqlalchemy as sa + + +def upgrade(): + with op.batch_alter_table("transfer_invoice_items") as batch: + batch.alter_column("receipt_date", new_column_name="movement_date", + existing_type=sa.String(length=16), existing_nullable=True) + batch.alter_column("receipt_quantity", new_column_name="movement_quantity", + existing_type=sa.String(length=40), existing_nullable=False) + batch.alter_column("receipt_warehouse_code", new_column_name="movement_warehouse_code", + existing_type=sa.String(length=64), existing_nullable=False) + with op.batch_alter_table("transfer_documents") as batch: + batch.alter_column("receipt_date", new_column_name="movement_date", + existing_type=sa.String(length=16), existing_nullable=False) + op.execute("UPDATE transfer_movement_ledger SET record_kind='inbound' WHERE record_kind='receipt'") + op.execute("UPDATE transfer_movement_ledger SET record_kind='outbound' WHERE record_kind='shipment'") + with op.batch_alter_table("transfer_movement_ledger") as batch: + batch.drop_constraint("uq_transfer_movement_ledger_natural_key", type_="unique") + batch.create_unique_constraint( + "uq_transfer_movement_ledger_natural_key", + ["source_code", "record_kind", "doc_no", "line_no", "line_seq", + "in_out_flag", "carton_id", "lot_no"], + ) + + +def downgrade(): + with op.batch_alter_table("transfer_movement_ledger") as batch: + batch.drop_constraint("uq_transfer_movement_ledger_natural_key", type_="unique") + batch.create_unique_constraint( + "uq_transfer_movement_ledger_natural_key", + ["source_code", "record_kind", "doc_no", "line_no", "line_seq", "in_out_flag"], + ) + op.execute("UPDATE transfer_movement_ledger SET record_kind='receipt' WHERE record_kind='inbound'") + op.execute("UPDATE transfer_movement_ledger SET record_kind='shipment' WHERE record_kind='outbound'") + with op.batch_alter_table("transfer_documents") as batch: + batch.alter_column("movement_date", new_column_name="receipt_date", + existing_type=sa.String(length=16), existing_nullable=False) + with op.batch_alter_table("transfer_invoice_items") as batch: + batch.alter_column("movement_date", new_column_name="receipt_date", + existing_type=sa.String(length=16), existing_nullable=True) + batch.alter_column("movement_quantity", new_column_name="receipt_quantity", + existing_type=sa.String(length=40), existing_nullable=False) + batch.alter_column("movement_warehouse_code", new_column_name="receipt_warehouse_code", + existing_type=sa.String(length=64), existing_nullable=False) +``` + +> 若 Alembic 当前版本 `batch.alter_column` 的 rename 形态为位置参数差异(如 +> `batch.alter_column(old_name, new_column_name=...)`),以仓库既有迁移写法为准 +> (可参考 `rc2b3c4d5e6f_drop_receipt_warehouse_list.py` 的列操作风格);列类型与 +> nullable 已按建表迁移核实,不再改动。 + +- [ ] **Step 4: 同步模型层** + +`backend/app/models/in_transit_transfer.py`: +- `TransferInvoiceItem`:`receipt_warehouse_code→movement_warehouse_code`(:266)、`receipt_date→movement_date`(:273)、`receipt_quantity→movement_quantity`(:277);唯一约束成分 `'receipt_date'→'movement_date'`(:231);类 docstring 相应行同步。 +- `TransferDocument`:`receipt_date→movement_date`(:355);`uq_transfer_documents_group_live` 成分(:342)同步。 +- `TransferMovementLedger`:唯一约束成分追加 `'carton_id', 'lot_no'`(:551-552);模块头注释(:16)与 :530 的自然键描述改为 8 成分。 +- 全文件其余 `receipt_date` 注释字样同步为 `movement_date`(grep 确认清零)。 + +- [ ] **Step 5: 修复编译面引用点** + +Run: `cd backend && grep -rn "\.receipt_date\|\.receipt_quantity\|\.receipt_warehouse_code" app/ --include="*.py"` +逐一更新为 `.movement_*`(预计命中 `serializers.py`、`matching_service.py`、`execution_service.py`、`retry_service.py`、`excel_export.py`)。**只改属性访问,不改字典字符串键。** + +- [ ] **Step 6: 跑受影响测试并全绿** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/ tests/api/test_in_transit_transfer_api.py -q` +Expected: 全部 PASS(fixture 造数据用模型属性会自动跟随;若有测试断言 ORM 属性名,改测试)。 + +- [ ] **Step 7: 暂存** + +```bash +git add backend/migrations/versions/tt14a5f6a7b8c9_inbound_rename_and_ledger_key.py backend/app/models/in_transit_transfer.py backend/app/services/in_transit_transfer backend/tests/services/in_transit_transfer/test_migration_inbound_rename.py backend/tests/services/in_transit_transfer/test_transfer_movement_ledger_model.py +``` +(以实际改动文件为准显式追加,禁止 `git add -A`) + +--- + +### Task 2: ledger_sync 幂等修复(8 成分键 + date_skipped + record_kind 常量) + +**Files:** +- Modify: `backend/app/services/in_transit_transfer/ledger_sync.py`(常量、Outcome、键构造、过滤) +- Modify: `backend/app/services/in_transit_transfer/evidence_sync.py`(import 与 record_kind 实参)、`matching_service.py`(:316 字面量) +- Test: `backend/tests/services/in_transit_transfer/test_ledger_sync.py`、`test_evidence_sync.py`(内容更新) + +**Interfaces:** +- Consumes: Task 1 的 8 成分唯一约束与 `TransferMovementLedger` 列。 +- Produces: `RECORD_KIND_INBOUND = "inbound"`、`RECORD_KIND_OUTBOUND = "outbound"`、`INBOUND_CONTRADICTORY_FLAGS`(Task 3 说辞清扫以这些常量名为准);`LedgerSyncOutcome.date_skipped: int = 0`(Task 8 冒烟核对)。 + +- [ ] **Step 1: 写失败测试** + +在 `test_ledger_sync.py` 追加(沿用文件内既有 fixture/造行手法,下面是核心断言): + +```python +def test_carton_dimension_expands_natural_key(make_row, sync_rows): + """同单号同行不同箱号=两行独立落档(旧键会塌缩为首见为准丢行)。""" + outcome = sync_rows([ + make_row(doc_no="DUB1", line_no="10", carton_id="C1", quantity="5"), + make_row(doc_no="DUB1", line_no="10", carton_id="C2", quantity="7"), + ], record_kind="inbound") + assert (outcome.inserted, outcome.date_skipped) == (2, 0) + + +def test_lot_no_expands_natural_key(make_row, sync_rows): + outcome = sync_rows([ + make_row(doc_no="WTP1", line_no="1", lot_no="HOW001", quantity="1"), + make_row(doc_no="WTP1", line_no="1", lot_no="HOW002", quantity="2"), + ], record_kind="inbound") + assert outcome.inserted == 2 + + +def test_empty_movement_date_rows_skipped(make_row, sync_rows): + """movement_date 空 = 未发生异动:不落档、不计入其他分类。""" + outcome = sync_rows([ + make_row(doc_no="EXP1", line_no="1", movement_date="", quantity="3"), + make_row(doc_no="OK1", line_no="1", movement_date="2026-10-15", quantity="1"), + ], record_kind="inbound") + assert (outcome.inserted, outcome.date_skipped) == (1, 1) + + +def test_constants_inbound_outbound(): + from app.services.in_transit_transfer import ledger_sync + assert ledger_sync.RECORD_KIND_INBOUND == "inbound" + assert ledger_sync.RECORD_KIND_OUTBOUND == "outbound" + assert ledger_sync.INBOUND_CONTRADICTORY_FLAGS == frozenset({"-1"}) +``` + +(`make_row`/`sync_rows` 为该文件既有测试助手名——以文件现状为准对齐;若助手签名不同,按现文件风格等价实现,断言语义不变。) + +- [ ] **Step 2: 运行确认失败** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_ledger_sync.py -v -k "carton or lot_no or movement_date or constants"` +Expected: FAIL(常量不存在/键塌缩/无 date_skipped) + +- [ ] **Step 3: 实现** + +`ledger_sync.py`: +1. 常量区(:44-46)替换: + +```python +# record_kind='inbound' 的矛盾进出标志:入站记录出现该值即解析错位(交叉校验矛盾)。 +INBOUND_CONTRADICTORY_FLAGS: frozenset[str] = frozenset({"-1"}) +# 记录种类字面量:inbound=入站(收料报表产物);outbound=出站(出货侧结构就位)。 +RECORD_KIND_INBOUND = "inbound" +RECORD_KIND_OUTBOUND = "outbound" +``` + +2. `LedgerSyncOutcome` 追加字段 `date_skipped: int = 0 # movement_date 空=未发生异动,不落档`;`counters` 初始化同步加 `"date_skipped": 0`;docstring 的五分类改六分类。 +3. `sync_ledger_rows` 开头(counters 初始化后、STEP 1 前)加过滤: + +```python + # [STEP 0] movement_date 非空才落档:空值=未发生异动(未收 ASN/未发货订单行), + # 落档即幽灵行(永不进匹配圈档)。解析层 file_parser 已滤一轮(收料语义), + # 此处是映射无关的第二道防线:Profile 无论把哪列配到 movement_date,空值都进不了档。 + parsed_rows = [raw for raw in parsed_rows if _key_text(raw.get("movement_date"))] + date_skipped = total_in - len(parsed_rows) # total_in=len(原始 parsed_rows),先行保存 +``` + +(实现时把原始长度先存 `total_in = len(parsed_rows)` 再过滤;`counters["date_skipped"] = total_in - len(parsed_rows)`。) +4. STEP 1 既有行索引键由四成分扩为六成分:`(doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no)`(全部经 `_key_text` 规整);行落库分支自然键取值同步加 `raw.get("carton_id")/raw.get("lot_no")`。 +5. `in_out_flag` 交叉校验处(:217)改用 `RECORD_KIND_INBOUND`/`INBOUND_CONTRADICTORY_FLAGS`;docstring 全部 receipt/shipment 说辞改 inbound/outbound(含 :55-58 的 record_kind 参数说明)。 + +`evidence_sync.py`:`RECORD_KIND_RECEIPT` import/使用(:51,230,242,285,321)→ `RECORD_KIND_INBOUND`。 +`matching_service.py`::316 `record_kind == "receipt"` → `== RECORD_KIND_INBOUND`(补 import)。 + +- [ ] **Step 4: 跑测试确认全绿** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_ledger_sync.py tests/services/in_transit_transfer/test_evidence_sync.py tests/services/in_transit_transfer/test_matching_service.py tests/services/in_transit_transfer/test_queue_ledger_view.py -q` +Expected: PASS(旧用例中 record_kind="shipment"/"receipt" 字面量改为 "inbound"/"outbound"——本任务只改值字符串,文件名 Task 3 改) + +- [ ] **Step 5: 暂存** + +```bash +git add backend/app/services/in_transit_transfer/ledger_sync.py 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_ledger_sync.py backend/tests/services/in_transit_transfer/test_evidence_sync.py +``` + +--- + +### Task 3: 后端说辞清扫(文件/类/函数/常量/路由/错误码/审计/注释) + +**Files:** +- Rename: `backend/app/services/in_transit_transfer/receipt_file_gate.py→inbound_file_gate.py`、`receipt_callback_bridge.py→inbound_callback_bridge.py`、`receipt_trigger_service.py→inbound_trigger_service.py` +- Rename(测试): `test_receipt_trigger_service.py→test_inbound_trigger_service.py` 等含 receipt 的测试文件 +- Modify: `backend/app/services/in_transit_transfer/` 全部、`backend/app/api/in_transit_transfer/__init__.py`、`backend/app/core/contracts.py`、`backend/tests/`(services/api/conftest)、`backend/app/services/admin/shipping_inventory_service.py`(仅退役守卫,见下) +- Test: 全量受影响 pytest + +**Interfaces:** +- Produces(Task 5 前端依赖的最终形状): 路由 `POST /sources/inbound-files`、`GET /runs//inbound-files`;匹配创建参数 `movement_date_from/movement_date_to`;序列化 JSON 键 `movement_date/movement_quantity/movement_warehouse_code`(明细方向中立,用 movement);错误码 `TRANSFER_INBOUND_NOT_MATURED`、`TRANSFER.MOVEMENT_DATE_RANGE_INVALID`、`RPA_INBOUND_PROFILE_MISSING`、`RPA_INBOUND_CALLBACK_FAILED/TIMEOUT`、`RPA_INBOUND_CONFIG_MISSING/UNAVAILABLE/NO_TRIGGERABLE_SOURCE`、`SHIPPING.INBOUND_FILE_NOT_FOUND`;审计事件 `TRANSFER_INBOUND_FILES_DOWNLOADED`;zip 名 `inbound-files-*.zip`。 +- 边界:`shipping_inventory_service.py` 的 `_validate_movement_profile_binding` 更名留给 Task 4(与 purpose 改版同文件同批);本任务**不碰** shipping_notice 域任何文件。 + +- [ ] **Step 1: 文件改名(git mv)** + +```bash +git mv backend/app/services/in_transit_transfer/receipt_file_gate.py backend/app/services/in_transit_transfer/inbound_file_gate.py +git mv backend/app/services/in_transit_transfer/receipt_callback_bridge.py backend/app/services/in_transit_transfer/inbound_callback_bridge.py +git mv backend/app/services/in_transit_transfer/receipt_trigger_service.py backend/app/services/in_transit_transfer/inbound_trigger_service.py +``` + +- [ ] **Step 2: 类/函数/常量改名(按 spec §4.1 对照表逐项)** + +| 旧 → 新(全部命中点含 import/调用/测试) | +| --- | +| `ReadyReceiptFile→ReadyInboundFile`;`ReceiptFileRepository→InboundFileRepository`;`ensure_receipt_file_ready→ensure_inbound_file_ready`(file_preparation.py,测试 repo_fakes.py 同步) | +| `ShippingReceiptFileRepository→ShippingInboundFileRepository`(movement_file_repository.py:40;deps.py:150 注入点) | +| `ParsedReceiptRow→ParsedMovementRow`;`ReceiptFileSchemaError→MovementFileSchemaError`;`parse_receipt_rows` 并入/更名 `parse_movement_rows`(file_parser.py:25,45,84,117;invoice_aggregator.py:53 类型标注) | +| `validate_receipt_quantity→validate_inbound_quantity`;`receipt_quantity` 形参→`inbound_quantity`(quantity.py:24,48) | +| `maturity_status(receipt_date=...)`→`inbound_date=`;`eligible_receipt_date_to→eligible_inbound_date_to`(date_policy.py:125,147) | +| `record_receipt_parse_failure/clear_receipt_parse_failure→record_inbound_parse_failure/clear_inbound_parse_failure`(source_file_status.py:112,143) | +| `advance_source_job_from_receipt_callback→advance_source_job_from_inbound_callback`(inbound_callback_bridge.py:22) | + +- [ ] **Step 3: 字符串说辞更名(spec §4.1 路由/参数/错误码/审计/zip 名对照表逐项)** + +- API:`:165 /sources/receipt-files→/sources/inbound-files`;`:612 /runs//receipt-files→/runs//inbound-files`;`:125-126 receipt_date_from/to→movement_date_from/to`(含 :98 docstring);`:229,:666 zip 名 receipt-files-→inbound-files-`。 +- 序列化字典键(R1 裁决):`"receipt_date"→"movement_date"`、`"receipt_quantity"→"movement_quantity"`、`"receipt_warehouse_code"→"movement_warehouse_code"`(serializers/matching_service/execution_service/retry payload,grep `"receipt_date"` 驱动;明细是方向中立,用 movement)。 +- 错误码定义点:`contracts.py:18`、`matching_service.py:255,259`(`TRANSFER.RECEIPT_DATE_RANGE_INVALID→TRANSFER.MOVEMENT_DATE_RANGE_INVALID`——约束的是明细异动日期)、`deps.py:180`、`inbound_callback_bridge.py:53,82`、`inbound_trigger_service.py:115,148,151,219,228,260,263`、`api/__init__.py:210`——按 Interfaces 块的新名逐一替换,同步更新 docstring。 +- 审计事件:`api/__init__.py:214,651 TRANSFER_RECEIPT_FILES_DOWNLOADED→TRANSFER_INBOUND_FILES_DOWNLOADED`。 +- `archive.py:111` object_type `receipt_file→inbound_file`。 +- **注释/docstring 约 170 行**:域内 `grep -rn "收料" backend/app/services/in_transit_transfer backend/app/api/in_transit_transfer` 逐文件改为「出入站/入站/异动」(语义按上下文:收料文件→入站文件、收料来源→出入站来源、明细的收料日期/收料数量→异动日期/异动数量)。`excel_export.py:85` Excel 表头「收料数量」→「异动数量」。 + +- [ ] **Step 4: 退役守卫补查(顺手修,spec §4.1)** + +`backend/app/services/shipping_notice/inventory_parsing_profile.py` 的 `retire`(:317-328)——守卫除 `ShippingInventorySource` 外补查 `ShippingReceiptReportConfig`: + +```python + bound_sources = ShippingInventorySource.query.filter_by(parsing_profile_id=profile.id).count() + bound_receipt_configs = ShippingReceiptReportConfig.query.filter_by(parsing_profile_id=profile.id).count() + if bound_sources or bound_receipt_configs: + raise AppError(... RETIRE_BLOCKED ...) # 沿用既有异常形态与错误码 +``` + +(import 从 `app.models.shipping_receipt_report` 引入;本任务不改 purpose 相关,只补守卫;对应测试在 `tests/test_admin_shipping_receipt_config.py` 追加:绑定了收料配置的 movement profile 退役被拒。) + +- [ ] **Step 5: 测试全量更名与内容更新** + +- 测试文件改名:`test_receipt_trigger_service.py→test_inbound_trigger_service.py`、`test_receipt_file_parser.py→test_inbound_file_parser.py`、`test_freight_receipt_rpa_callback.py` 等——`git mv` 保留历史;**注意** `tests/test_admin_shipping_receipt_config.py`、`tests/test_shipping_receipt_report_models.py`、`tests/test_shipping_receipt_rpa_archive.py` 属 shipping_notice 域测试**不改名**(只改其中因 API/错误码更名而失败的断言)。 +- `tests/conftest.py:698,726,748` fixture `"file_purpose": "receipt"→"inbound"`。 +- 全部测试内 `receipt-files` 路由、`receipt_date_from/to` 参数、错误码字面量、`RECORD_KIND_RECEIPT` 引用同步(grep 驱动)。 + +- [ ] **Step 6: 门禁 grep + 全量测试** + +```bash +cd backend && grep -rin "receipt" app/services/in_transit_transfer app/api/in_transit_transfer app/models/in_transit_transfer.py | grep -v "ShippingReceiptReport\|shipping_receipt_report\|receipt_export_batch\|FREIGHT_RPA_RECEIPT" ; echo "exit=$?" +``` +Expected: 无输出(白名单外清零)。`收料` 同样清零。 +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/ -q`(既有基线:API 16 例环境性失败允许,零新增) +Expected: 与基线一致或更好。 + +- [ ] **Step 7: 暂存(显式清单)** + +```bash +git add backend/app/services/in_transit_transfer backend/app/api/in_transit_transfer backend/app/core/contracts.py backend/app/services/shipping_notice/inventory_parsing_profile.py backend/tests +``` +(`backend/tests` 下 shipping_notice 域测试若有内容改动属 Step 5 允许范围;`git status` 复核无域外新文件混入) + +--- + +### Task 4: purpose 枚举改版(tt15 + 后端) + +**Files:** +- Create: `backend/migrations/versions/tt15b6a7b8c9d0_parsing_purpose_onhand_inbound_outbound.py` +- Modify: `backend/app/models/shipping_inventory_config.py`(:177-184 约束/default/docstring)、`backend/app/services/shipping_notice/inventory_parsing_profile.py`(:82,101,235-241,298)、`backend/app/services/admin/shipping_inventory_service.py`(:273-288 更名+枚举)、`backend/app/services/in_transit_transfer/deps.py`(:176-180)、`backend/app/services/in_transit_transfer/movement_file_repository.py`(:61-65) +- Test: `backend/tests/test_parsing_profile_purpose.py`、`tests/test_admin_shipping_receipt_config.py` + +**Interfaces:** +- Produces: purpose 合法值 `{'onhand','inbound','outbound'}`;`_validate_inbound_profile_binding`(Task 6 前端绑定下拉以 `inbound` 过滤);tt15 revision `tt15b6a7b8c9d0`(down_revision=`tt14a5f6a7b8c9`)。 + +- [ ] **Step 1: 写失败测试** + +`tests/test_parsing_profile_purpose.py` 追加/更新: + +```python +def test_purpose_enum_values(): + from app.models.shipping_inventory_config import ShippingInventoryParsingProfile + col = ShippingInventoryParsingProfile.__table__.columns["purpose"] + assert col.default.arg == "onhand" and col.server_default.arg == "onhand" + check = next(c for c in ShippingInventoryParsingProfile.__table__.constraints + if getattr(c, "name", "") == "ck_shipping_inventory_parsing_profiles_purpose") + sql = str(getattr(check, "sqltext", check)) + for value in ("onhand", "inbound", "outbound"): + assert value in sql + for legacy in ("'inventory'", "'movement'"): + assert legacy not in sql + + +def test_draft_accepts_outbound_and_rejects_legacy(app_ctx): + # save_draft purpose='outbound' 通过校验;purpose='movement' 报 SHIPPING.INVENTORY_PARSING_PROFILE_INVALID +``` + +(第二个测试按该文件既有 save_draft 造数手法等价实现。) + +- [ ] **Step 2: 确认失败** — Run pytest 该文件,FAIL。 + +- [ ] **Step 3: tt15 迁移** + +```python +revision = "tt15b6a7b8c9d0" +down_revision = "tt14a5f6a7b8c9" + +def upgrade(): + op.execute("ALTER TABLE shipping_inventory_parsing_profiles DROP CONSTRAINT ck_shipping_inventory_parsing_profiles_purpose") + op.execute("UPDATE shipping_inventory_parsing_profiles SET purpose='onhand' WHERE purpose='inventory'") + op.execute("UPDATE shipping_inventory_parsing_profiles SET purpose='inbound' WHERE purpose='movement'") + op.execute("ALTER TABLE shipping_inventory_parsing_profiles ADD CONSTRAINT ck_shipping_inventory_parsing_profiles_purpose CHECK (purpose IN ('onhand', 'inbound', 'outbound'))") + op.execute("ALTER TABLE shipping_inventory_parsing_profiles ALTER COLUMN purpose SET DEFAULT 'onhand'") + +def downgrade(): + # 逆向:outbound 行无 1:1 旧值,迁移到 'movement'(结构就位语义最接近) + op.execute("ALTER TABLE shipping_inventory_parsing_profiles ALTER COLUMN purpose SET DEFAULT 'inventory'") + op.execute("ALTER TABLE shipping_inventory_parsing_profiles DROP CONSTRAINT ck_shipping_inventory_parsing_profiles_purpose") + op.execute("UPDATE shipping_inventory_parsing_profiles SET purpose='inventory' WHERE purpose='onhand'") + op.execute("UPDATE shipping_inventory_parsing_profiles SET purpose='movement' WHERE purpose IN ('inbound', 'outbound')") + op.execute("ALTER TABLE shipping_inventory_parsing_profiles ADD CONSTRAINT ck_shipping_inventory_parsing_profiles_purpose CHECK (purpose IN ('inventory', 'movement'))") +``` + +> SQLite 往返测试:SQLite 不支持 ALTER COLUMN DEFAULT / 部分 DROP CONSTRAINT——沿用 tt13 测试的 SQLite 往返模式时,若往返失败,改为 `batch_alter_table`(batch 会重建表);以「往返可执行」为准,PG 端渲染等价。 + +- [ ] **Step 4: 模型与后端比较点** + +- 模型 `:177-184`:CheckConstraint SQL、`default='onhand'`、`server_default='onhand'`、docstring(inventory=onhand 库存文件;movement→inbound 入站收料文件;outbound 出站文件结构就位)。 +- `inventory_parsing_profile.py`:`:82` 默认 `purpose='onhand'`;`:101 if purpose == 'inbound':`;`:235` 默认回退 `'onhand'`;`:236-237` 白名单 `{'onhand','inbound','outbound'}`;`:238-241` 草稿用途不可变逻辑不变;`:298 if profile.purpose != 'inbound':`。 +- `shipping_inventory_service.py`:`_validate_movement_profile_binding→_validate_inbound_profile_binding`(:273),内部 `profile.purpose != 'inbound'`,错误码 `SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID→SHIPPING.INBOUND_PROFILE_INVALID`(:286-288);调用点 `api/admin/shipping_inventory.py:175-179` 同步。 +- `deps.py:176-180`:`purpose != 'inbound'`;错误码 `RPA_RECEIPT_MOVEMENT_PROFILE_MISSING` 已在 Task 3 更名为 `RPA_INBOUND_PROFILE_MISSING`,此处确认引用一致。 +- `movement_file_repository.py:61-65`:`purpose != 'inbound'`。 +- docstring/注释中 purpose 枚举说明全部同步(「收料异动规则」→「入站解析规则」)。 + +- [ ] **Step 5: 全绿 + 暂存** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_parsing_profile_purpose.py tests/test_admin_shipping_receipt_config.py tests/services/in_transit_transfer/ -q` → PASS。 +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/ -q`(零新增失败)。 +```bash +git add backend/migrations/versions/tt15b6a7b8c9d0_parsing_purpose_onhand_inbound_outbound.py backend/app/models/shipping_inventory_config.py backend/app/services/shipping_notice/inventory_parsing_profile.py backend/app/services/admin/shipping_inventory_service.py backend/app/api/admin/shipping_inventory.py backend/app/services/in_transit_transfer/deps.py backend/app/services/in_transit_transfer/movement_file_repository.py backend/tests/test_parsing_profile_purpose.py backend/tests/test_admin_shipping_receipt_config.py +``` + +--- + +### Task 5: 前端调拨侧更名 + i18n(chat.json/errors.json 四语言) + +**Files:** +- Modify: `frontend/src/features/chat/api/transfer.api.ts`、`composables/useChatTransfer.ts(+spec)`、`types/transfer.types.ts`、`components/messages/TransferSourceSelectCard.vue(+spec)`、`TransferHomePanel.vue(+spec)`、`TransferMessageView.vue(+spec)`、`TransferResultCard.vue`、`TransferMatchCard.vue`、`TransferBacklogSummaryCard.vue`、`TransferExecutableCard.vue`、`TransferExecutedOrders.vue`、`transferDate.ts`、`transferBatch.ts(+spec)`、`transferCards.spec.ts` +- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json`、`{四语言}/errors.json` + +**Interfaces:** +- Consumes: Task 3 的路由 `/sources/inbound-files`、`/runs//inbound-files`、参数 `movement_date_from/to`、JSON 键 `movement_date/movement_quantity/movement_warehouse_code`(明细 movement)、错误码 `TRANSFER_INBOUND_NOT_MATURED`(`TRANSFER.MOVEMENT_DATE_RANGE_INVALID` 无 errors.json 键)。 +- Produces: 组件 emit `download-inbound`、函数 `downloadTransferInboundFiles/downloadInboundFiles/eligibleInboundDateTo`、i18n 键 `chat.transfer.colMovementDate/downloadInboundFiles/movementDateHint/movementDateInvalid/movementDateLabel/movementDateTo/retryInbound`。 + +- [ ] **Step 1: 先写/改失败测试** + +`useChatTransfer.spec.ts`:下载函数断言 URL `/inbound-files`、参数名 `movement_date_from`;`TransferSourceSelectCard.spec.ts`:emit 事件 `download-inbound`、i18n 键 `chat.transfer.movementDateLabel` 渲染;`transferDate.spec`(如内嵌)`eligibleInboundDateTo`。以既有用例改名为准,断言值按上面 Interfaces。 + +- [ ] **Step 2: 确认失败** — Run: `cd frontend && npx vitest run src/features/chat --reporter=dot` → FAIL。 + +- [ ] **Step 3: 实现(对照表驱动)** + +- 函数/变量:`downloadTransferReceiptFiles→downloadTransferInboundFiles`、`downloadReceiptFiles→downloadInboundFiles`、`maxReceiptDate→maxInboundDate`、`eligibleReceiptDateTo→eligibleInboundDateTo`、`onDownloadReceipt→onDownloadInbound`、emit `download-receipt→download-inbound`。 +- API/类型:`transfer.api.ts:36-37,180-181,216` 路由与参数(`receipt_date_from/to→movement_date_from/to`);`transfer.types.ts` `receipt_date_from/to/eligible_receipt_date_to→movement_date_from/to / eligible_inbound_date_to`、明细字段 `receipt_date/receipt_quantity→movement_date/movement_quantity`(全部出现点 :61,78,178,223,228,338,grep 驱动)。 +- 组件模板/脚本内 `receiptDate*` i18n 键引用、zip 文件名(`TransferMessageView.vue:134` `receipt-files-→inbound-files-`);`TransferMatchCard.vue` 的 `receipt_date` 去重键/渲染 → `movement_date`。 +- i18n chat.json 四语言:键更名 `colReceiptDate→colMovementDate`(异动日期)、`downloadReceiptFiles→downloadInboundFiles`(下载收料来源文件→下载出入站来源文件)、`receiptDateHint→movementDateHint`、`receiptDateInvalid→movementDateInvalid`、`receiptDateLabel→movementDateLabel`、`receiptDateTo→movementDateTo`、`retryReceipt→retryInbound`;值文案 23 个「收料」按语义改「出入站/入站/异动」(zh-CN 例:`colSource`=出入站来源、`fileProgressTitle`=出入站文件准备、`notMaturedCount`=未成熟入站、`transferPendingMatchTitle`=待匹配出入站记录、`transferPendingMatchColDate`=入站日期、`sourceSelectTitle`=选择出入站来源实例、`reasonQuantityMismatch`=…与异动数量不一致…、`reasonFutureDate`=异动日期晚于业务日期、`colMovementDate`=异动日期)。zh-TW 用繁体、en `Receipt→Inbound`(日期类 `Movement Date`)、th 按语义改(รับเข้า/入站,日期 วันที่เคลื่อนไหว)。 +- errors.json 四语言:键 `TRANSFER_RECEIPT_NOT_MATURED→TRANSFER_INBOUND_NOT_MATURED`,值「收料」→「入站」(en Receipt→Inbound)。注:`TRANSFER.RECEIPT_DATE_RANGE_INVALID` 无 errors.json 键(走通用兜底文案),仅 Task 3 更名后端码字符串即可,前端无需动。 + +- [ ] **Step 4: 全绿** + +Run: `cd frontend && npx vitest run src/features/chat src/i18n.spec.ts --reporter=dot` → PASS;`grep -rn "receipt\|收料" src/features/chat src/locales/zh-CN/chat.json` 白名单外清零。 + +- [ ] **Step 5: 暂存** + +```bash +git add frontend/src/features/chat 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 frontend/src/locales/zh-CN/errors.json frontend/src/locales/zh-TW/errors.json frontend/src/locales/en/errors.json frontend/src/locales/th/errors.json +``` + +--- + +### Task 6: 前端库存解析 purpose 改版 + admin.json 文案 + +**Files:** +- Modify: `frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue`(purpose 19 处)、`movementParsingProfileForm.ts`(注释) +- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/admin.json`(parsingPurpose 及配套 hint/label、movementParsing.sampleFile 等「收料」文案) + +**Interfaces:** +- Consumes: Task 4 后端枚举 `onhand/inbound/outbound`、`SHIPPING.INBOUND_PROFILE_INVALID`。 +- Produces: 创建下拉三选项 value `onhand/inbound/outbound`;站点绑定过滤 `row.purpose !== 'inbound'`;收料配置绑定校验 `=== 'inbound'`。 + +- [ ] **Step 1: 更新既有 purpose 断言(grep 驱动)** + +```bash +cd frontend && grep -rn "'movement'\|\"movement\"\|'inventory'\|\"inventory\"" src/features/admin/modules/shipping-inventory --include="*.spec.ts" +``` +凡既有 spec 中断言 purpose 值的用例改为新枚举值;**若无任何既有断言,不新增同义反复测试**——本任务的测试门禁 = 既有 admin 模块 vitest 全绿 + `npm run build` 通过(选项值正确性由 Step 2 的 grep 清点与 Task 10 冒烟覆盖)。 + +- [ ] **Step 2: 实现(grep 清点驱动)** + +`:628` state 类型 `'onhand' as 'onhand' | 'inbound' | 'outbound'`;`:189,196-197,214,230` 创建下拉 options 三值(disabled 规则保留:同 code 同 purpose 已存在则禁用);`:155` 站点绑定 `row.purpose !== 'inbound'`;`:181` 收料绑定 `=== 'inbound'`;`:1135-1137` movement 载荷判断 `=== 'inbound'`;其余 19 处逐一 grep `purpose` 清点更新。`movementParsingProfileForm.ts:3` 注释同步。 +admin.json 四语言:`parsingPurpose`→`{"onhand":"库存","inbound":"入站","outbound":"出站"}`(en:On Hand/Inbound/Outbound;th:สต็อก/เข้า/ออก);`parsingPurposeHint`、`movementParsing.sampleFile`(收料样本文件→入站样本文件)等配套「收料」文案同步(只动 shippingInventory.parsingPurpose 相关与解析页可见文案,`receiptReportConfig*` 段**不动**——第二层边界)。 + +- [ ] **Step 3: 全绿 + 暂存** + +Run: `cd frontend && npx vitest run src/features/admin --reporter=dot && npm run build` → PASS。 +```bash +git add frontend/src/features/admin/modules/shipping-inventory 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: 待匹配桶「清空并重新解析」后端(service + 预检/执行端点) + +**Files:** +- Create: `backend/app/services/in_transit_transfer/backlog_reparse_service.py` +- Modify: `backend/app/services/in_transit_transfer/movement_file_repository.py`(新增 `list_reparseable_archived_files`)、`evidence_sync.py`(抽出归档解析纯函数)、`api/in_transit_transfer/__init__.py`(2 端点) +- Test: `backend/tests/services/in_transit_transfer/test_backlog_reparse_service.py`(新建)、`test_evidence_sync.py`(重构回归)、`tests/api/test_in_transit_transfer_api.py`(端点) + +**Interfaces:** +- Consumes: Task 1 的 8 成分档约束、Task 2 的 `RECORD_KIND_INBOUND`/`sync_ledger_rows`(含 date_skipped)、Task 3 的 inbound 命名与 `ShippingInboundFileRepository`、`_effective_occupancy_filter`(matching_service,占用排除口径)。 +- Produces: `preview_pending_match_reparse(source_code, now) -> dict`(files[{archived_at,sha256,rows}] / profile{code,version} / clearable_rows / kept_rows);`reparse_pending_match(source_code, operator, now) -> ReparseOutcome{cleared, reinserted, date_skipped, kept_unrebuildable, files}`;端点 `GET /backlog/pending-match/reparse-preview?source_code=`、`POST /backlog/pending-match/reparse`;审计事件 `TRANSFER_PENDING_MATCH_REPARSED`(Task 8 前端与 Task 10 冒烟依赖)。 + +- [ ] **Step 1: 写失败测试(核心行为先行)** + +```python +"""backlog_reparse_service:清空并重解析的守卫矩阵。""" +# 关键断言一:正常路径——旧映射行被清、按新映射重落、date_skipped/计数正确、审计事件落库 +def test_reparse_clears_and_relands(...): + # 造 2 份可用归档文件 + 3 条档行(file A 两行、file B 一行,均为旧映射值) + outcome = reparse_pending_match("CRANE_NA", operator="admin", now=...) + assert (outcome.cleared, outcome.reinserted) == (3, 3) + +# 关键断言二:解析失败整体中止——造 1 份坏文件(表头缺失),执行后行数不变 +def test_abort_on_parse_failure_deletes_nothing(...): + with pytest.raises(AppError) as ei: + reparse_pending_match(...) + assert ei.value.code == "TRANSFER.REPARSE_PARSE_FAILED" + assert count_ledger_rows("CRANE_NA") == 3 # 一行未删 + +# 关键断言三:封存行与被占用行幸存(transfer_executed=true / 存在有效 items 引用) +def test_sealed_and_occupied_rows_survive(...): ... + +# 关键断言四:证据缺失(归档文件已清理/过保留期)的行保留并计入 kept_unrebuildable +def test_unrebuildable_rows_kept_and_reported(...): ... + +# 关键断言五:预检形状——files/profile{code,version}/clearable_rows/kept_rows +def test_preview_shape(...): ... +``` + +(造数沿用 `tests/services/in_transit_transfer/` 既有 repo_fakes/factories;存储假件按 repo_fakes 现有风格扩展 `list_reparseable_archived_files`。) + +- [ ] **Step 2: 确认失败** — Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_backlog_reparse_service.py -v` → FAIL(模块不存在)。 + +- [ ] **Step 3: repository 维护查询** + +`movement_file_repository.py` 的 `ShippingInboundFileRepository` 新增(复用 `latest_ready_file`(:68-78)的 join 路径,**去掉当日门禁**): + +```python + def list_reparseable_archived_files(self, source_code: str, now: datetime) -> list[ArchiveRecord]: + """清空重建专用:该来源全部可重建归档(未清理+未过保留期),不设当日门禁。 + + 【AI 触发时机】仅待匹配「清空并重新解析」维护链路使用;运行期落档 + (evidence_sync)禁止改用本方法——当日 fail-closed 门禁是运行期语义, + 本方法是显式的历史重建通道(spec §6),两者不得混用。 + """ +``` + +(返回记录含 id/storage_key/sha256/file_version/archived_at;过滤 `archive_deleted_at IS NULL AND archive_expires_at >= now`,按归档时间升序。) + +- [ ] **Step 4: 抽取解析纯函数** + +从 `evidence_sync.sync_source_rows`(:252-332)抽出「归档字节→(档行列表, sheet/row_no 溯源)」模块级纯函数(如 `parse_archive_to_ledger_rows(data: bytes, profile) -> list[dict]`),`sync_source_rows` 改为调用之——**运行期与重建路径单一解析口径**。重构后 `test_evidence_sync.py` 必须全绿(不改断言)。 + +- [ ] **Step 5: service 编排** + +`backlog_reparse_service.py`: + +```python +def reparse_pending_match(*, source_code: str, operator: str, now: datetime) -> ReparseOutcome: + """清空并重新解析一个来源的待匹配桶(spec §6;单事务,本函数提交)。 + + 【AI 触发时机】仅管理/待匹配界面的「清空并重新解析」动作调用; + 禁止在运行期收料落地链路调用(运行期走 evidence_sync,当日语义)。 + + Raises: + AppError: TRANSFER.REPARSE_PARSE_FAILED——任一归档文件解析失败, + 整体中止且未删除任何行(先解析后删除是本函数的安全不变量)。 + """ + # [STEP 1] 可重建文件清单(维护路径,无当日门禁) + # [STEP 2] 全量预解析入内存;任一失败 → AppError(一行未删) + # [STEP 3] 删除可重建且未封存、未被有效 items 占用的 inbound 行 + # (占用排除复用 matching_service._effective_occupancy_filter 的 NOT EXISTS 口径) + # [STEP 4] 按归档时间序 sync_ledger_rows 重落(FileMeta 带 source_file_id/file_version/sha256) + # [STEP 5] commit + 审计事件 TRANSFER_PENDING_MATCH_REPARSED + # {operator, source_code, files, profile_code+version, cleared, reinserted, date_skipped, kept} +``` + +(`AppError`/错误码风格按域内惯例;新码 `TRANSFER.REPARSE_PARSE_FAILED` 走通用兜底文案,不新增四语言键——参照 `TRANSFER.RECEIPT_DATE_RANGE_INVALID` 先例。) + +- [ ] **Step 6: 两个端点** + +`api/in_transit_transfer/__init__.py`(鉴权与响应形态沿用相邻 backlog 端点 :907 模式): + +```python +@in_transit_transfer_bp.route("/backlog/pending-match/reparse-preview", methods=["GET"]) +def pending_match_reparse_preview_api(): ... # ?source_code= → preview dict + +@in_transit_transfer_bp.route("/backlog/pending-match/reparse", methods=["POST"]) +def pending_match_reparse_api(): ... # body {"source_code"} → ReparseOutcome + audit +``` + +- [ ] **Step 7: 全绿 + 暂存** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/ tests/api/test_in_transit_transfer_api.py -q` → PASS(API 既有环境性失败零新增)。 +```bash +git add backend/app/services/in_transit_transfer/backlog_reparse_service.py backend/app/services/in_transit_transfer/movement_file_repository.py backend/app/services/in_transit_transfer/evidence_sync.py backend/app/api/in_transit_transfer/__init__.py backend/tests/services/in_transit_transfer/test_backlog_reparse_service.py backend/tests/services/in_transit_transfer/test_evidence_sync.py backend/tests/api/test_in_transit_transfer_api.py +``` + +--- + +### Task 8: 待匹配面板「清空并重新解析」前端 + 四语言 + +**Files:** +- Modify: `frontend/src/features/chat/components/messages/TransferPendingMatchPanel.vue(+spec)`、`frontend/src/features/chat/api/transfer.api.ts`、`frontend/src/features/chat/composables/useChatTransfer.ts(+spec)` +- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json` + +**Interfaces:** +- Consumes: Task 7 的预检/执行端点与返回形状。 +- Produces: i18n 键 `chat.transfer.reparseButton/reparseTitle/reparseFiles/reparseProfile/reparseRows/reparseSuccess/reparseFailed`(Task 9/10 无依赖,仅四语言完整)。 + +- [ ] **Step 1: 失败测试** + +`TransferPendingMatchPanel.spec.ts`:来源行「清空重解析」按钮渲染;点击后调预检并弹确认(展示文件数/规则版本/清除行数);确认后调执行端点;`useChatTransfer.spec.ts`:`reparsePendingMatch(source)` 调 `POST /backlog/pending-match/reparse`、成功后刷新待匹配。 + +- [ ] **Step 2: 确认失败** — Run: `cd frontend && npx vitest run src/features/chat --reporter=dot` → FAIL。 + +- [ ] **Step 3: 实现** + +- `transfer.api.ts`:`fetchPendingMatchReparsePreview(sourceCode)` + `reparsePendingMatch(sourceCode)`。 +- `TransferPendingMatchPanel.vue`:行级「清空重解析」按钮(按来源聚合处/行级均可,确认弹窗必须展示预检数据);失败展示中止原因(解析失败未删任何数据);成功后 emit 刷新。 +- chat.json 四语言键值: + - zh-CN:`reparseButton`=清空重解析、`reparseTitle`=清空并重新解析、`reparseFiles`=归档文件 {count} 份、`reparseProfile`=使用规则 {code} v{version}、`reparseRows`=将清除 {clearable} 行;证据缺失保留 {kept} 行、`reparseSuccess`=已清除 {cleared} 行,重落 {reinserted} 行、`reparseFailed`=重解析中止,未删除任何数据:{reason} + - zh-TW 繁体、en(Clear & Reparse / Archived files {count} / Rule {code} v{version} / Will clear {clearable} rows; {kept} rows kept (missing evidence) / Cleared {cleared}, re-landed {reinserted} / Aborted, nothing deleted: {reason})、th 对应语义。 + +- [ ] **Step 4: 全绿 + 暂存** + +Run: `cd frontend && npx vitest run src/features/chat --reporter=dot` → PASS。 +```bash +git add frontend/src/features/chat 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 9: 文档与术语表清扫 + +**Files:** +- Modify: `docs/features/in-transit-transfer/GLOSSARY.md`、`docs/features/in-transit-transfer/technical.md`、`minimum-implementation-spec.md`、`in-transit-transfer-tdd.md`、`prd.md`、`roadmap.md`、`mvp-requirements*.md`、`lean-ux-canvas*.md`(按目录实际清单) +- Modify: `docs/funclist.md`、`docs/demand.md`、`docs/tec.md`(在途调拨相关条目) +- Modify: `docs/superpowers/specs/2026-10-15-inbound-outbound-idempotency-rename-design.md`(状态行改「已实施」) + +- [ ] **Step 1: GLOSSARY 术语更新** + +`收料登记 (Receipt Registration)→入站登记 (Inbound Registration)`、`出货登记 (Shipment Registration)→出站登记 (Outbound Registration)`、`收料来源实例 (Receipt Source Instance)→出入站来源实例 (Inbound Source Instance)`、`记录类型 (Record Kind)` 条目「收料/出货属性」→「入站/出站属性(inbound/outbound)」。补一条:`解析类型 (Parsing Purpose):onhand=库存文件,inbound=入站文件,outbound=出站文件`。 + +- [ ] **Step 2: 域内文档与跨域条目** + +`docs/features/in-transit-transfer/` 全套:收料→出入站/入站、receipt→inbound(路由/参数/错误码名同步 Task 3 结果)。`funclist.md :734,808-846`、`demand.md :37-40,899-903`、`tec.md :1523-1527` 相关条目同步——**shipping_notice 收料报表条目不改**。spec 头部状态改「已实施(YYYY-MM-DD)」。 + +- [ ] **Step 3: grep 门禁 + 暂存** + +```bash +grep -rn "收料\|receipt" docs/features/in-transit-transfer docs/funclist.md | grep -v "收料报表\|shipping_receipt\|收料 RPA" ; echo "exit=$?" +``` +Expected: 白名单外清零。 +```bash +git add docs/features/in-transit-transfer docs/funclist.md docs/demand.md docs/tec.md docs/superpowers/specs/2026-10-15-inbound-outbound-idempotency-rename-design.md +``` + +--- + +### Task 10: 终局门禁与开发库冒烟 + +**Files:** 无新改动(门禁任务;发现回归时修复归属前序任务) + +- [ ] **Step 1: 后端全量** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/ -q` +Expected: services 全绿;API 既有 16 例环境性失败零新增。 + +- [ ] **Step 2: 前端全量** + +Run: `cd frontend && npx vitest run --reporter=dot && npm run build` +Expected: 全绿(shipping-review 既有 1 例除外,若仍存在);build 通过。 + +- [ ] **Step 3: 迁移链与库** + +Run: `cd backend && ./.venv/Scripts/python.exe -c "from flask_migrate import Migrate; ..."` 或直接 `flask db heads`(app 上下文)确认单 head `tt15b6a7b8c9d0`;`flask db upgrade` 打到开发库;核对: +```sql +-- psql 或 flask shell +SELECT purpose, count(*) FROM shipping_inventory_parsing_profiles GROUP BY purpose; -- onhand=2, inbound=3 +SELECT record_kind, count(*) FROM transfer_movement_ledger GROUP BY record_kind; -- 无 'receipt' +``` + +- [ ] **Step 4: grep 终局断言** + +```bash +grep -rin "receipt" backend/app/services/in_transit_transfer backend/app/api/in_transit_transfer backend/app/models/in_transit_transfer.py frontend/src/features/chat | grep -v "ShippingReceiptReport\|shipping_receipt_report\|receipt_export_batch\|FREIGHT_RPA_RECEIPT\|收料报表" ; echo "exit=$?" +``` +Expected: 无输出。 + +- [ ] **Step 5: 冒烟清单(dev,手工)** + +1. 库存解析页:三条入站规则(现 draft)可编辑;purpose 下拉显示 库存/入站/出站;新建 outbound 草稿可保存。 +2. 调拨类型管理页:`in_transit_to_hub` 范围规则若含 `记录类型` 条件,值选项核对(inbound/outbound)。 +3. CRANE/DSV 样本文件解析回放:落档行数=完成行数(无 Expected 孪生行)、同箱不塌缩、`date_skipped` 计数与未完成行数一致。 +4. chat 调拨工作台:来源选择卡加载类型、匹配创建带 `movement_date_from/to`、下载 zip 名 `inbound-files-*`。 +5. 清空并重解析:改一条入站规则映射→待匹配面板预检(文件数/规则版本/行数)→执行→报告计数一致;故意改坏映射再执行→中止且数据未动。 + +- [ ] **Step 6: 暂存(如有回归修复,按归属任务清单显式追加)** + +--- + +## 明确不做(与 spec §8 一致) + +shipping_notice 域与 RPA 契约改名;出站抓取/落档/匹配链路;出站单位常量映射(ERP 回传为准,未来实施);解析规则「一键新版本/改绑引导」与待匹配「重新识别」(已搁置另立话题);ledger 扩列。 diff --git a/docs/superpowers/plans/2026-10-16-freight-rpa-decouple-and-rename-evaluation.md b/docs/superpowers/plans/2026-10-16-freight-rpa-decouple-and-rename-evaluation.md new file mode 100644 index 00000000..6dcb617e --- /dev/null +++ b/docs/superpowers/plans/2026-10-16-freight-rpa-decouple-and-rename-evaluation.md @@ -0,0 +1,200 @@ +# Freight RPA 独立模块化 + onhand/inbound/outbound 全域改名 — 可行性评估 + +日期:2026-10-16 | 状态:**评估完成,D1-D7 + Q10-Q12 已拍板(2026-10-16)**(决策记录见 §6,完整性清单见 §8) | 前置:`2026-10-15-inbound-outbound-idempotency-rename`(已实施未提交) | ADR:`docs/adr/0003-freight-rpa-module-boundary.md` + +## 0. 结论速览 + +1. **解耦:可行,且方向正确。** Worker 与后端之间早已是「文件契约 + HTTP 回调 + 心跳」的进程边界(Worker 零 backend import),in_transit_transfer 已成为第二个消费方——RPA 事实上已是跨域平台能力,继续寄生在 `services/shipping_notice/` 里只会让第三个、第四个业务域重复绑定。推荐**两阶段**:阶段 A 机械收编编排层/API/调度壳到 `services/freight_rpa/`(低风险);表所有权与事务边界重构单独立项(阶段 B)。 +2. **改名:可行,但必须分批。** inventory→onhand 是绝对重灾区(源码约 19,700 次 / 约 708 文件、24 张表、636 个 i18n 键、约 40 个前后端契约枚举值);receipt→inbound 约 4,100 次 / 203 文件(in_transit_transfer 域已完成)。**shipment→outbound 已否决(2026-10-17)**:货代履约「出货」与调拨 outbound 无关;contract_payment 的「发货款」shipment 仍须排除误伤。 +3. **解耦与改名互相纠缠,推荐合并批次:** 改名最危险的部分(Worker 回调 URL、trigger schema、env 变量、CIFS 物理目录)恰好集中在 RPA 域内——先解耦再改名等于把旧名字搬两次家。推荐「批次 R = 解耦 + RPA 域随迁新名」一次切换;shipping_notice 业务域改名(批次 S)随后独立进行。 + +## 1. 背景与本次范围 + +2026-10-15 的入站/出站改版(spec D5 三层清扫)明确把以下内容列为「第二层只注释、第三层单独立项」: + +- shipping_notice 域全部 `ShippingReceiptReport*`(模型/表/存储/通知/排程/工作台/路由/i18n); +- RPA 跨进程契约:`shipping_receipt_rpa.v1`、`receipt_export_batch`、trigger 文件名、`FREIGHT_RPA_RECEIPT_*`、`scripts/freight_rpa/receipt/` Worker。 + +**本次评估 = 该预留立项的展开**,并新增一项范围更大的诉求:inventory→onhand 全域改名(10-15 只改了解析 purpose 枚举值 inventory→onhand,未触及「inventory」一词本身)。 + +**衔接约束(硬前置)**:当前分支 `hugo-auto-transfer` 工作区有约 115 个暂存未提交文件(2026-10-15 交付:tt14/tt15 迁移、in_transit_transfer 域 inbound 化、前端与清空重解析)。本评估的任何实施批次必须**在该批提交落地之后**启动,避免并行会话同文件碰撞(此前已有多次教训)。 + +## 2. Freight RPA 现状地图(事实基线) + +RPA 能力分三层存在: + +| 层 | 位置 | 与业务的关系 | +| --- | --- | --- | +| Windows Worker | `scripts/freight_rpa/`(56 文件:inventory/、receipt/、common/、connectors/dsv、crane) | **已是独立进程**:轮询共享目录 trigger → Playwright 驱动 DSV/Crane → 回调 + 心跳;不 import 任何 backend 代码 | +| 后端编排层 | `services/shipping_notice/` 约 10 个 RPA 文件(rpa.py、receipt_rpa.py、rpa_attempts.py、per_source_rpa_service.py、rpa_worker_heartbeat(.alert).py、credential_crypto.py、inventory_rpa_workflow.py、inventory_rpa_callback_cleanup.py、inventory_configuration_test.py、receipt_report_storage.py)+ `services/schedule/` 6 个 job 壳 + 回调路由散在 4 处 blueprint | **寄生在业务包内**:按文件路径而非模块边界与业务共存 | +| 数据模型 | RPA 专属 5 张表(`shipping_rpa_profiles`、`shipping_task_inventory_rpa_attempts`、`shipping_receipt_report_configs/rpa_unit_runs/report_files`+`notification_deliveries`)+ 边界表(`ShippingInventorySource`、preparation attempts) | 专属表尚清晰;边界表同时服务业务路由/匹配 | + +触发链路两条:排程链(`schedule_tasks` → job_registry 三个 RPA job → 写 trigger → Worker 领取 → 回调 finalize)与按需业务链(workspace rpa-upload / `ensure_inventory_via_rpa` → 写 trigger → 同一回调面)。RPA 执行本身不走 jobs 表,纯目录契约驱动。 + +## 3. 解耦评估 + +### 3.1 耦合点分级 + +**干净接缝(可机械平移):** + +- trigger 写入层:`rpa.py`(仅依赖 flask config)、`receipt_rpa.py` 整文件; +- 心跳与告警:`rpa_worker_heartbeat(.alert).py`(redis + 两个目录函数); +- 凭据加解密:`credential_crypto.py`(FREIGHT_RPA_CREDENTIAL_KEY); +- attempt 计数:`rpa_attempts.py`、`per_source_rpa_service.py`(后者同事务操作业务模型,见下); +- 调度壳:`schedule/` 6 个 `*_rpa_*.py` job(依赖方向 schedule→RPA,无人反向依赖它们); +- 回调路由:`api/tools/shipping_notice.py` 的 `/rpa/*` 12 条端点(薄分发层)、`api/schedule/rpa_workers.py`; +- Worker 全部代码、全部 FREIGHT_RPA_* env、`data/freight_rpa/` 目录约定。 + +**深度纠缠(需要设计而非搬运):** + +1. **表所有权**:`ShippingReceiptReportFile/RpaUnitRun` 被 in_transit_transfer 当一等业务事实源(10 个文件查询/join,`matching_service._latest_usable_report_file` 等);`ShippingTaskInventoryRpaAttempt` 被 shipping_notice 13 个业务文件(process_gate、freeze、投影、恢复)消费;`ShippingInventorySource` 同时是 RPA 抓取配置与业务路由规则的事实源。 +2. **事务/状态机咬合**:回调不是消息边界而是业务事务边界——`inventory_rpa_workflow` 回调直接 finalize `ScheduleRun`、写 `ShippingProcessGate/Execution`、推进任务状态机(`PH_RPA_PENDING` 是状态机阶段);`receipt_report_storage._advance_transfer_source_job` 在 shipping_notice 文件内推进 in_transit 的 `TransferSourceJob`。 +3. **上传 RPA 与履约双向咬合**:`fulfillment_workflow` 写上传 trigger 携带 Excel artifact、upload_config 快照、凭据信封;`upload_rpa_pending` 是前端可见的状态投影。 +4. **两处小环**:`receipt_report_storage → in_transit`(回调桥)与 `in_transit/movement_file_repository → shipping_notice/inventory_snapshot`(excel 表头定位工具复用)。 + +**耦合度结论:编排层强寄生但协议层弱耦合 → 解耦可行性「中等偏可行」。** 机械部分约占工作量七成;剩余三成(表所有权 + 回调事务化)无法靠移动文件解开,须接口化设计。 + +### 3.2 推荐方案:两阶段 + +**阶段 A:模块归位(本次立项主体,机械为主)** + +- 新建 `backend/app/services/freight_rpa/` 包,收编上述「干净接缝」全部文件; +- 回调路由迁出业务 blueprint:新 blueprint `/api/freight-rpa/*`(onhand-ready、inbound-batch-ready、heartbeat 等),与 Worker 同步切换; +- admin 的 rpa-profiles 路由迁 `/api/admin/freight-rpa/rpa-profiles`; +- schedule job 改 import 新包; +- **表不动**(含 RPA 专属表):freight_rpa 包 import 现有 models,表所有权裁决留给阶段 B; +- 「一次到位无兼容层」全面适用(拍板 Q5/Q11):backend 内部 import 硬切不留 shim;Worker 回调 URL **同窗口切换、不做双路由**——后端+前端+DB 迁移+Windows Worker 在同一发布窗口完成,窗口纪律见 §6-Q11。 + +**阶段 B:数据与契约重构(单独立项,不在本次范围)** + +- 「文件就绪」事件化:RPA 只发布事件/落产物,业务域订阅,替代回调直写业务状态; +- 表所有权裁决:receipt report 表归 RPA 还是归消费方;`ShippingInventorySource` 拆分抓取配置与业务路由配置。 + +### 3.3 阶段 A 验收标准 + +- `services/freight_rpa/` 不 import `shipping_notice` 的任何 workflow/状态机模块(只 import models 与纯工具); +- shipping_notice / in_transit_transfer 通过稳定接口消费 RPA(trigger 写入函数 + 回调端点),业务包内不再有 RPA trigger/drop 目录知识; +- Worker 改动仅限回调 URL、env 名、目录路径与自身文件名。 + +## 4. 改名评估 + +### 4.1 量级(源码,排除 node_modules/venv/dist/运行日志) + +| 词 | 次数 | 文件数 | 后端 app | 后端测试 | 迁移 | 前端 | docs | scripts 根 | DB 表 | i18n 键(四语言合计) | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| inventory→onhand | ~19,700 | ~708 | 194 文件/6,630 | 197 文件/5,535 | 73 文件/1,010 | 150 文件/4,241 | 61 文件/1,568 | 26 文件/570 | **24 张** `shipping_inventory_*` | 159 键/语言 ≈ 636 | +| receipt→inbound | ~4,100 | ~203 | 52/832 | 46/1,190 | 18/124 | 33/358 | 28/1,184 | 21/413 | 4 张 `shipping_receipt_*` | 7 键/语言 | +| ~~shipment→outbound~~(履约) | — | — | **2026-10-17 否决**:履约 shipment 不改 outbound;调拨侧 outbound 已由 10-15/tt14 处理 | — | + +**无关业务排除项(误伤清单)**:`contract_payment` 模块的付款节点类型 `shipment`(「发货款」,与 prepayment 并列)——约占 shipment 总量 1/3,**必须排除**(backend/app/services/contract_payment/、frontend/src/features/contract-payment/、docs/features/contract-payment-plan/)。`shipping` 一词不在改名范围(模块名 shipping_notice、`shipping_*` 前缀保留,仅词根 inventory/receipt/shipment 替换——即 `shipping_inventory_files`→`shipping_onhand_files`)。`movement` 一词按 10-15 spec 拍板保留。 + +**无关业务核查结论**:inventory 与 receipt 在 backend/app 内未发现货代域之外的占用,全部命中属货代域。 + +### 4.2 改名与解耦的重叠区(为何批次 R 要合并) + +改名最高危的部分全部位于 RPA 域,且彼此耦合,必须一次切换: + +| 契约 | 现值 | 目标 | +| --- | --- | --- | +| Worker 目录 | `scripts/freight_rpa/inventory/`、`receipt/` | `onhand/`、`inbound/`(出站预留 `outbound/`) | +| env 变量 | `FREIGHT_RPA_SHARED_INVENTORY_TRIGGER/DROP_DIR`、`FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS`、`FREIGHT_RPA_RECEIPT_*`、`FREIGHT_RPA_INVENTORY/RECEIPT_ARCHIVE_DIR`、`FREIGHT_RPA_WORKER_SAMPLE_INVENTORY` | 同形 `*ONHAND*` / `*INBOUND*`(先例:2026-09-18 `SHIPPING_NOTICE_RPA_*`→`FREIGHT_RPA_*` 一刀切无兼容层);须同步四处 `.env.*`、`docs/convention/环境变量规则.md`、`.env.local` 的 6 个废弃变量顺手清理 | +| trigger schema | `shipping_inventory_rpa.v2`、`shipping_receipt_rpa.v1` | `freight_rpa.onhand.v1`、`freight_rpa.inbound.v1`(新包身份;切换窗口须清空在途 trigger 文件) | +| 回调 URL | `/api/shipping-notice/rpa/inventory-ready|inventory-batch-*|receipt-*|upload-complete|heartbeat` 等 12 条 | `/api/freight-rpa/onhand-*|inbound-*|...`(与 Worker 同窗口切换,无双路由) | +| CIFS 物理目录 | `/mnt/hxops-rpa-{test,prod}-data/freight_rpa/{inventory,receipt,common}` | `freight_rpa/{onhand,inbound,outbound,common}`——**生产数据目录迁移**,须与 Worker 计划任务(start_*/register_*.ps1)同窗口切换 | +| 上传 RPA env | `FREIGHT_RPA_UPLOAD_*`(不含目标词,不动) | 不动 | + +### 4.3 DB 与存量数据(隐藏大头) + +- **24 张 `shipping_inventory_*` 表**改名 = 24 次 `rename_table` + 索引/约束/外键名同步 + 8 个 models 文件改名(`shipping_inventory_config.py` 等)。历史 73 个迁移文件**不改写**(先例:历史 spec/plan/ADR 不改),rename 迁移追加在链尾即可,全新环境按序执行无碍。 +- **DB 存量枚举值**:`shipping_task_events` 的审计事件名(`rpa_report_inventory`、`inventory_rpa_*`)、`step_key`、attempt 行、任务 step_payload_json 里的动作/状态值(`upload_inventory_file`、`inventory_matching`、`wait_inventory` 等约 40 个)——推荐**数据迁移**(沿用 D6「无兼容层」哲学),上线 SOP 前备份;读时兼容映射会永久留债。 +- **归档产物不改**:MinIO 中历史 `inventory_*`/`receipt_*` 对象、ZIP 名按 storage_key 存取,不受代码改名影响。 +- **权限键**:`shipping_inventory` 权限模块键、`adminSubModule: 'inventory'`、路由 name `AdminShippingInventory`——需同步后端权限校验、前端 `modules.ts`/`admin.types.ts`,并核对权限数据表中是否有存量字符串值。 +- **前端契约同发**:前后端同仓同批提交(D6 先例),vitest + build 全绿为门禁;`npm run build` 通过是合并底线(AGENTS.md §4)。 + +### 4.4 i18n 与文档 + +- i18n:636 个 `inventory*` 键(chat 57 / admin 55 / workspace 47,×4 语言)+ 大量英文文案值含词(en/chat.json 199 次、en/admin.json 170 次);`receipt*` 7 键、`shipment*` 3 键。四语言缺一即审查不通过(红线)。 +- 文档:`docs/features/shipping-notice/technical.md`(inventory 236 次、receipt 77 次,全文核心词)、`scripts/freight_rpa/README.md`(inventory 194 次,部署手册总纲)、`docs/features/in-transit-transfer/GLOSSARY.md`、`funclist/demand/tec` 对应条目、`docs/convention/环境变量规则.md`。历史 `docs/superpowers/specs|plans` 按先例不改写(见 D6)。 + +## 5. 实施顺序建议 + +``` +[前置] 提交在途 115 文件(2026-10-15 交付) + ↓ +[批次 R] 解耦 + RPA 域随迁新名(§3.2 阶段 A + §4.2 契约表) + 约 35 后端文件 + Worker 56 文件 + env 四处 + CIFS 目录 SOP + Worker 切换窗口 + ↓ +[批次 S] shipping_notice 业务域 inventory→onhand(大爆炸,codemod 脚本化) + S1 表 24 张 rename 迁移 + services 122 文件 + tests 197 文件 + models 8 文件 + S2 API 路由 + 权限键 + 前端契约枚举 + 前端目录/文件 git mv + i18n 636 键(前后端同批) + S3 存量枚举值数据迁移 + 文档(technical.md 等) + ↓ +[批次 T] **已废除(2026-10-17)**:原「shipment→outbound」错误——货代履约出货 ≠ 调拨 outbound。 + 履约侧 `shipment_*` 保留;若未来另案做命名卫生,目标词也不得是 outbound。 + ↓ +[批次 D] 文档全域清扫收尾 + 终局 grep 门禁(合法 outbound=调拨;禁止再把履约 shipment 扫成待改 outbound) +``` + +理由:R 在 S 之前,避免「先给旧结构改名、再整体搬家」的双倍触碰;S 一次切换所有表与契约,避免两次表迁移;D 收口。原 T 因术语混用取消。 + +**发布拍板(Q5/Q9,2026-10-16;T 范围 2026-10-17 修订)**:批次 **R+S+D** 同一发布窗口上线(后端+前端+迁移+Windows Worker 同窗口),不做双路由;实施顺序 **R→S→D**,安全网纪律见 §6-Q11。 + +量级估计:批次 R 约 1~2 周(含 Worker 联调窗口);批次 S 机器替换 2~3 天 + 全量回归与冒烟;批次 D 约 1 天。 + +## 6. 决策记录(2026-10-16 已拍板) + +| # | 决策 | 结论 | +| --- | --- | --- | +| D1 | 解耦深度 | **阶段 A**:编排层归位,所有表不动;阶段 B(表所有权/事件化)单独立项 | +| D2 | RPA 域解耦+改名一次切换 | **是**(批次 R 合并),契约细目见 §4.2 | +| D3 | 表改名 | **29 张表在批次 S 一次 rename(Q13+Q15+Q16:统一 `freight_rpa_` 一级命名空间)**:共享 2 张→`freight_rpa_sources`/`freight_rpa_profiles`;onhand 子域 14 张→`freight_rpa_onhand_*`;inbound 子域 4× `shipping_receipt_*`→`freight_rpa_inbound_*`;10 张发货消费事实保留 shipping 前缀只改词根→`shipping_onhand_*`(与 env/包/蓝图/job key/admin 路由严格同构);**admin 配置域随批次 S 改**:路由统一 `/api/admin/freight-rpa/` 按子域分组、前端模块→freight-rpa、权限键→freight_rpa;细节见 spec | +| D4 | DB 存量枚举值/step_key/审计事件名 | **数据迁移**(无兼容层哲学),清点清单见 §8 | +| D5 | Worker 回调 URL 切换 | **同步发布、无双路由**(用户拍板,否决双路由建议):后端+Worker 同窗口切换 | +| D6 | 历史文档边界 | `docs/superpowers/`、ADR、归档文档**不改写**;权威文档(technical.md、freight_rpa/README、GLOSSARY、funclist/demand/tec、环境变量规则)**必改** | +| D7 | CIFS 生产目录迁移 | **排程静默窗口一次切换**(暂停排程→确认 Worker 空闲(心跳无在途 claim)→trigger+drop 双目录排空→迁目录→注册新 Worker 计划任务并**注销旧任务**(register ps1 已带 Unregister)→冒烟→恢复);切换脚本用 `/wizard` 生成、人工执行 | +| Q10 | 模块命名 | **`freight_rpa`**(否决泛化 `rpa`):对齐 `FREIGHT_RPA_*` env 红线;域中立件集中在 `freight_rpa/common/`,未来第二个 RPA 出现时上提平台层;blueprint `/api/freight-rpa/*` | +| Q11 | 单窗口安全网 | ① 全部新迁移带可执行 downgrade;② test 环境预演 upgrade→冒烟→downgrade→再 upgrade;③ 窗口纪律=暂停排程+禁止手动 RPA+备旧后端镜像与旧 Worker 包;④ 验收清单进 spec | +| Q12 | ADR | 已立 `docs/adr/0003-freight-rpa-module-boundary.md`;术语表 `docs/features/freight-rpa/GLOSSARY.md` | + +## 7. 下一步(流程路由) + +决策已闭环(**2026-10-17 追加:废除 T**)。正式 spec:`docs/superpowers/specs/2026-10-16-freight-rpa-decouple-and-rename-design.md`。后续:`/to-tickets`(epic:**R/S/D**,S 内 S1-S3;勿再开 shipment→outbound 票)→ 逐票 `/implement`;R 的 CIFS/Worker 切换见 cutover-runbook。 + +## 8. 完整性清单(Q3「需要考虑完整」/ Q4「需要考虑完整」的展开,spec 阶段逐项核实) + +### 8.1 批次 S 表/结构改名完整性 + +- **表**:28 张 `rename_table` + 全部索引/唯一约束/CHECK/外键**名称**同步(PG rename_table 不自动改索引与约束名)。 +- **列名清点**:`inventory_source_id`(5 处)、`inventory_snapshot_id`(4)、`inventory_file_id`(4)、`inventory_source_code`、`active_inventory_candidate_set_id` 等随表改名;`shipping_freight_cancellations.freight_receipt_no/receipt_asset_id` 是否随 inbound 改需逐一定语义。 +- **models**:8 个文件改名(`shipping_inventory_config.py`→`shipping_onhand_config.py` 等)+ 全部类名(`ShippingInventory*`→`ShippingOnhand*`、`ShippingReceipt*`→`ShippingInbound*`)。 +- **配置文件**:`backend/config/shipping_inventory_sources.yaml`(文件名+内容键)。 +- **job 注册**:`job_registry.py` 的 job key(`shipping-inventory-rpa`/`freight-receipt-rpa*`,**存于 `schedule_tasks.job_key` 存量行**,改名须带数据 UPDATE)与 `options_source` 注册键(`shipping_inventory_sources`/`shipping_receipt_sources`);前端 `schedule-job-key.utils.ts` 同步。 +- **脚本**:`backend/scripts/import_shipping_inventory_sources.py`。 +- **权限键(Q14 最终拍板:随批次 S 改;Q13b 层级修订)**:后端权限校验与前端 `modules.ts`/`admin.types.ts`/`admin.routes.ts` 的 `shipping_inventory`→`freight_rpa`(name `AdminFreightRpa`),并**迁移权限数据表中存量字符串值**(否则管理员丢页面,迁移动进批次 S 数据迁移波)。 +- **admin 路由与前端模块(Q13b:货代管理 = onhand/inbound/outbound 三子域)**:统一 `/api/admin/freight-rpa/` 命名空间——共享 `sources`/`rpa-profiles`,onhand 子域 `onhand/{fields,structure-analyses,validation-batches,snapshots,export-records}`,inbound 挂站点 `sources//inbound-report-config`,outbound 预留;`features/admin/modules/shipping-inventory/`→`freight-rpa/`(FreightRpaPage);admin.json `shippingInventory.*` 键名段四语言随改。 +- **文件产物模板**:出货 Excel 名 `shipment_{task_no}_{ts}.xlsx` **保留 shipment 词根**(履约出货 ≠ outbound);zip/导出模板清点时不得改成 outbound_*。 +- **不改**:MinIO/storage_key、历史归档对象名、历史迁移文件、`docs/superpowers/` 归档。 +- **错误码族(2026-10-16 评审补充,最大漏项)**:`errors.json` 四语言含 **73+ 个含 INVENTORY 的键**(`SHIPPING_INVENTORY_*`、`SHIPPING.*INVENTORY*`、`TRANSFER_ERP_INVENTORY_NOT_FOUND`)——键名、值文案(含「库存」字样)、后端 `contracts.py` 定义与 AppError 抛点同批改;`TRANSFER_*` 已由 10-15 处理的部分除外。 +- **docker-compose 透传(评审补充)**:`docker-compose.yml` 仅 1 行显式透传 `FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR`(L324),批次 R 随 env 改名同步;其余 FREIGHT_RPA_* 经 env_file 自动流入,无需逐条改。 +- **已核实无风险项(评审确认,spec 不再怀疑)**:nginx 无 shipping-notice/freight 路径规则(仅前端静态 + 通用 `/api` 代理,回调 URL 改名不触及网关);DB 自定义触发器/函数仅挂 `shipping_audit_events`(不含目标词,28 张改名表无触发器/视图依赖——spec 阶段对 28 表做一次依赖对象全量 sweep 收尾);Worker 回调鉴权为 `Authorization: Bearer` / `X-Integration-Key`(`_require_tool_auth`),与改名无关、凭据免轮换。 + +### 8.2 批次 S 存量枚举值清点(数据迁移对象) + +- `shipping_task_events`:审计事件名(`rpa_report_inventory`、`inventory_rpa_*`)与 step_key。 +- `step_payload_json`/ui_state JSON:动作与阶段值(`upload_inventory_file`、`retry_inventory_preparation`、`inventory_matching`、`inventory_fetching`、`wait_inventory` 等约 40 个,前后端契约同批)。 +- jobs 表**在途 payload**:发布窗口前排空/等待 shipping 队列;jobs 共享枚举成员 `SHIPPING_INVENTORY_CALLBACK_PROCESS`(`jobs/types.py`,值存于 jobs 表 `job_type` 列)在批次 S 改名时须连带 UPDATE 存量行(2026-10-16 波及面核查补充)。 +- 心跳/状态 scope 契约值:`scope=inventory|receipt`(默认 inventory)、能力串 `inventory_export/receipt_export`、worker_id 后缀 `-receipt`——批次 R 已并入(api/schedule/rpa_workers.py + 前端 schedule.api.ts + worker rpa_heartbeat.py,均属 RPA/admin 域内)。 +- attempt 表:列名+行内枚举值。 +- `schedule_tasks.job_key`(若按本清单改名)。 +- 已完成 ✓:`record_kind`(tt14)、解析 purpose(tt15)。 +- **执行方式(评审补充)**:枚举值 UPDATE 须**分批执行**(`shipping_task_events` 行数大,避免长锁);批次 S 迁移执行前**全库备份**(Q4 拍板含备份义务)。 + +### 8.3 门禁 + +grep 门禁(白名单外 `inventory/receipt/shipment` 清零,排除 contract_payment 与历史文档)+ 后端 pytest 463 基线 + 前端 vitest/build + i18n 四语言键集护栏 + test 环境迁移预演(§6-Q11)。 + +### 8.4 实施与协作优化(2026-10-16 评审补充) + +- **分支策略**:先提交在途 10-15 交付(~115 文件),随后从 `dev` 切单一 feature 分支承载 R/S/T/D 四批(单窗口发布对应单分支,符合 AGENTS.md §7)。 +- **Worker 回调 path 收拢**:Worker 侧回调 URL 已集中经 `_post_callback`/`rpa_heartbeat.py` 发出,批次 R 把全部 path 常量收拢到 `common/` 单点,切换与回滚各只改一处。 +- **批次 S 替换脚本化**:自写 codemod(不引第三方依赖),白名单排除 `contract_payment`、历史文档、MinIO 键;三道闸 = ruff/编译绿 → pytest/vitest → grep 门禁;git diff 抽查高频歧义词(如 `inventory` 出现在字符串文案中的大小写变体)。 diff --git a/docs/superpowers/plans/2026-10-16-freight-rpa-decouple-batch-r.md b/docs/superpowers/plans/2026-10-16-freight-rpa-decouple-batch-r.md new file mode 100644 index 00000000..2126b703 --- /dev/null +++ b/docs/superpowers/plans/2026-10-16-freight-rpa-decouple-batch-r.md @@ -0,0 +1,580 @@ +# Freight RPA 解耦批次 R 实施计划(模块归位 + RPA 域随迁新名) + +> **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. +> +> **2026-10-17 勘误(就地纠偏,不另开文档):** outbound **仅**在途调拨出站;货代履约「出货」≠ outbound。本批交付的 `freight_rpa/outbound/` 骨架合法。upload trigger action 误用 `outbound_upload`,须改为与心跳一致的 **`freight_upload`**(后端+Worker 同窗口硬切)。后续批次见 evaluation/design:**T(shipment→outbound)已废除**;发布序 **R→S→D**。 + +**Goal:** 把 freight RPA 后端编排层从 shipping_notice 收编为独立 `freight_rpa` 包,并把 RPA 跨进程契约(env/trigger schema/回调 URL/Worker 目录/排程 job key)一次切换为 onhand/inbound 命名;数据库表零变更。 + +**Architecture:** 四层形态——Worker(进程外)↔ 文件契约+回调+心跳 ↔ `freight_rpa` 包(trigger/attempt/心跳/凭据/归档)↔ 业务 sink 注册(shipping_notice/in_transit 在组合根注册回调业务处理器)↔ 业务域(快照落盘/状态机)。回调业务持久化经 `callback_sinks` 注册表注入,保证 freight_rpa 零业务 workflow import。 + +**Tech Stack:** Flask + SQLAlchemy 2.0 + Alembic(单 head tt16 接续 tt15)、Vue3+TS(仅 API URL 字符串微调)、pytest/vitest、Playwright Worker(Python 脚本侧)。 + +**Spec:** `docs/superpowers/specs/2026-10-16-freight-rpa-decouple-and-rename-design.md`(本计划 argues from spec;决策与完整性清单以评估文档 `2026-10-16-freight-rpa-decouple-and-rename-evaluation.md` §6/§8 为权威) + +## Global Constraints + +- **禁止自动 commit**:每任务止于 `git add <显式路径>`;提交由用户显式批准(Task 1 的前置交付提交亦须用户批准)。 +- **import 边界**:`freight_rpa` 包禁止 import `app.services.shipping_notice.*`,白名单仅 `shipping_notice.audit_service`、`shipping_notice.file_assets`(Task 2 适应度测试锁死)。 +- **契约精确值**:trigger schema `freight_rpa.onhand.v1` / `freight_rpa.inbound.v1`;回调前缀 `/api/freight-rpa/`;env `FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR`、`FREIGHT_RPA_SHARED_ONHAND_DROP_DIR`、`FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS`、`FREIGHT_RPA_ONHAND_ARCHIVE_DIR`、`FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR`、`FREIGHT_RPA_SHARED_INBOUND_DROP_DIR`、`FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS`、`FREIGHT_RPA_INBOUND_ARCHIVE_DIR`、`FREIGHT_RPA_WORKER_SAMPLE_ONHAND`;job key `freight-rpa-onhand` / `freight-rpa-inbound` / `freight-rpa-inbound-retention`(2026-10-16 拍板:与包/蓝图/env 层级同构,freight-rpa 在前)。 +- **表零变更**:批次 R 不改任何表结构;`schedule_tasks.platform_api_path`(承载归一化 job key)存量值经 tt16 数据迁移(单 head;down_revision 以迁移图实测为准——tt15 后已被 tt16a7b8c9d0e1f2 接续,tt16c7 链于其上;带 downgrade)。 +- **迁移测试模式**:SQLite upgrade→downgrade→upgrade 往返(沿用 tt13/tt14 先例);PG 语义。 +- **i18n**:本批仅动 job 相关少量键,四语言(zh-CN/zh-TW/en/th)缺一不通过。 +- **中文文案基线**:onhand=库存、inbound=入站(job 描述里的「收料」改「入站」)。 +- **Windows 环境**:后端解释器 `backend/.venv/Scripts/python.exe`;pytest 从 `backend/` 运行;vitest/build 从 `frontend/` 运行。 +- **不新增第三方依赖**;`SHIPPING_NOTICE_*` 命名空间的 4 个 inventory 业务 env(AUTO_RPA_INVENTORY_ENABLED 等)**属批次 S**,本批不动。 +- **注释纪律(AGENTS.md §5)**:搬移/改名处同步 docstring 与模块头「逻辑关系」。 + +## 计划切分说明 + +本计划只覆盖批次 R。批次 S(表 rename+shipping_notice 域改名+存量数据迁移)、D(文档收口)在 R 落地后另出计划;**原批次 T「shipment→outbound」已废除(2026-10-17)**。发布窗口为 **R+S+D** 同窗口(ADR 0003,术语边界以 GLOSSARY 为准)。 + +--- + +### Task 1: 前置落地——在途交付提交与分支 + +**Files:** 无新改动(纯 git 操作,提交须用户批准) + +- [ ] **Step 1: 受影响面回归确认基线(用户指示:不跑全局)** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/ -q -k "shipping or rpa or receipt or transfer or schedule or heartbeat or credential or inbound or freight"` +Expected: 记录通过/失败数作为批次基线(零新增为后续门槛)。 +Run: `cd frontend && npx vitest run && npm run build` +Expected: build 通过;vitest 既有失败基线=10(useShippingOrderReview 1、ShippingAuditEventDetailDrawer 3、XfaSplitRulePanel 6,Element Plus 迁移带入,非本工程引入)。 + +- [ ] **Step 2: 用户批准后提交在途交付** + +向用户展示 `git status` 清单(~115 文件:tt14/tt15、in_transit inbound 化、前端、清空重解析),**经用户显式批准**后按逻辑分组提交(`feat(in-transit-transfer): ...` 等 Conventional Commits)。 + +- [ ] **Step 3: 从 dev 切功能分支** + +```bash +git fetch origin dev && git checkout -b feature/freight-rpa-decouple origin/dev +``` +(若 dev 不含刚提交的交付,改为从含交付的分支点切出;以用户确认为准。) + +--- + +### Task 2: freight_rpa 包骨架 + import 边界适应度测试(接缝 5) + +**Files:** +- Create: `backend/app/services/freight_rpa/__init__.py`、`backend/app/services/freight_rpa/common/__init__.py`、`backend/app/services/freight_rpa/onhand/__init__.py`、`backend/app/services/freight_rpa/inbound/__init__.py`、`backend/app/services/freight_rpa/upload/__init__.py`(空 `__init__`,各含一行模块用途 docstring) +- Test: `backend/tests/services/freight_rpa/test_import_boundary.py`(新建目录) + +**Interfaces:** +- Produces: 包骨架 `app.services.freight_rpa.{common,onhand,inbound,upload}`;适应度测试 `test_freight_rpa_import_boundary`(后续所有搬移任务违法 import 即红)。 + +- [ ] **Step 1: 写适应度测试** + +```python +"""freight_rpa 包 import 边界适应度测试。 + +用途:锁死阶段 A 验收标准——freight_rpa 不寄生业务编排。 +依赖:app/services/freight_rpa 包、ast。 +逻辑:遍历包内 .py 的 import(ast 解析),命中禁列即失败; + 白名单是 RPA 归档/凭据所需的两块业务工具(阶段 B 收敛为零)。 +""" +from __future__ import annotations + +import ast +from pathlib import Path + +PKG = Path(__file__).resolve().parents[3] / "app" / "services" / "freight_rpa" + +ALLOWED_SHIPPING_NOTICE = { + "app.services.shipping_notice.audit_service", + "app.services.shipping_notice.file_assets", +} + + +def _imported_modules(path: Path) -> set[str]: + tree = ast.parse(path.read_text(encoding="utf-8")) + mods: set[str] = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + mods.update(a.name for a in node.names) + elif isinstance(node, ast.ImportFrom) and node.module: + mods.add(node.module) + return mods + + +def test_freight_rpa_import_boundary(): + assert PKG.exists(), "freight_rpa 包不存在" + violations: list[str] = [] + for py in PKG.rglob("*.py"): + for mod in _imported_modules(py): + if mod.startswith("app.services.shipping_notice") and mod not in ALLOWED_SHIPPING_NOTICE: + violations.append(f"{py.name}: {mod}") + assert not violations, "freight_rpa 违规 import:\n" + "\n".join(violations) +``` + +- [ ] **Step 2: 运行测试** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/services/freight_rpa/test_import_boundary.py -v` +Expected: PASS(包为空骨架)。后续任务搬入文件后此测试必须始终 PASS。 + +- [ ] **Step 3: 建包骨架并暂存** + +创建 5 个 `__init__.py`(各一行 docstring:common=域中立件;onhand=在手库存 RPA;inbound=入站 RPA;upload=货代上传 RPA)。 +```bash +git add backend/app/services/freight_rpa backend/tests/services/freight_rpa/test_import_boundary.py +``` + +--- + +### Task 3: env 命名切换(settings + .env 四处 + compose) + +**Files:** +- Modify: `backend/app/core/config/settings.py`(L379-476 区段 onhand/inbound 相关 8 键 + L478 MOCK 不变;`_rpa_data_path` L78-96 注释同步) +- Modify: `.env.dev`(L136-149)、`.env.test`(L120-181)、`.env.prod`(L121-159)、`.env.local`(L52-57 删除 6 个废弃 SHIPPING_NOTICE_RPA_* 变量) +- Modify: `docker-compose.yml:324`(唯一显式透传行) +- Modify: `docs/convention/环境变量规则.md`、`docs/convention/env_loading_priority.md`(涉及处) + +**Interfaces:** +- Produces: settings 新属性名(同 Global Constraints 契约值);旧属性名全仓清零。读点改名列:`FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR`(30 处)、`_INVENTORY_TRIGGER_DIR`(23)、`FREIGHT_RPA_INVENTORY_ARCHIVE_DIR`(14)、`FREIGHT_RPA_RECEIPT_ARCHIVE_DIR`(14)、`_RECEIPT_TRIGGER_DIR`(11)、`FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS`(11)、`FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS`(8)、`_RECEIPT_DROP_DIR`(6)、`FREIGHT_RPA_WORKER_SAMPLE_INVENTORY`(1)、`FREIGHT_RPA_INVENTORY_TRIGGER_DIR`(1,历史残留直接删除)。 + +- [ ] **Step 1: 全仓清点旧 env 读点** + +```bash +cd backend && grep -rn "FREIGHT_RPA_\(SHARED_\)\?\(INVENTORY\|RECEIPT\)" app/ scripts/ --include="*.py" | wc -l +``` +Expected: ≈119 处(30+23+14+14+11+11+8+6+1+1),记录文件清单供 Step 3 使用。 + +- [ ] **Step 2: settings.py 属性改名 + .env 文件切换** + +settings.py:8 个属性按 Global Constraints 精确新名重命名(只改名,默认值与语义不动;`FREIGHT_RPA_INVENTORY_TRIGGER_DIR` 残留键删除)。 +`.env.dev/.env.test/.env.prod`:变量名与**目录值**同步(`freight_rpa/inventory→freight_rpa/onhand`、`freight_rpa/receipt→freight_rpa/inbound`;prod/test 的 `/mnt/hxops-rpa-*-data` 前缀不变)。遵守 §8.1:只整行移动+改名,注释同步。`.env.local`:删除 6 个 `SHIPPING_NOTICE_RPA_*` 行及注释。 +`docker-compose.yml:324`:`FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR`→`FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR`(含 `${...:-}` 默认值占位)。 + +- [ ] **Step 3: 全仓读点替换 + 编译绿** + +```bash +cd backend && grep -rl "FREIGHT_RPA_SHARED_INVENTORY\|FREIGHT_RPA_INVENTORY\|FREIGHT_RPA_SHARED_RECEIPT\|FREIGHT_RPA_RECEIPT" app/ --include="*.py" | xargs sed -i "s/FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR/FREIGHT_RPA_SHARED_ONHAND_DROP_DIR/g; s/FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR/FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR/g; s/FREIGHT_RPA_INVENTORY_ARCHIVE_DIR/FREIGHT_RPA_ONHAND_ARCHIVE_DIR/g; s/FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS/FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS/g; s/FREIGHT_RPA_WORKER_SAMPLE_INVENTORY/FREIGHT_RPA_WORKER_SAMPLE_ONHAND/g; s/FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR/FREIGHT_RPA_SHARED_INBOUND_DROP_DIR/g; s/FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR/FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR/g; s/FREIGHT_RPA_RECEIPT_ARCHIVE_DIR/FREIGHT_RPA_INBOUND_ARCHIVE_DIR/g; s/FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS/FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS/g" +``` +(sed 后逐文件复核 diff——`scripts/freight_rpa/` Worker 侧读点留 Task 12 一并切换,本步只改 `app/`。) + +- [ ] **Step 4: 门禁 + 测试** + +```bash +grep -rn "FREIGHT_RPA_\(SHARED_\)\?\(INVENTORY\|RECEIPT\)" backend/app backend/config docker-compose.yml .env.dev .env.test .env.prod .env.shared; echo "exit=$?" +``` +Expected: 无输出(`.env.local` 废弃段已删)。`SHIPPING_NOTICE_*INVENTORY*` 4 键不在此门禁(批次 S)。 +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/ -q -x`(config 相关失败即改断言里的 env 名)。 + +- [ ] **Step 5: 文档同步 + 暂存** + +`docs/convention/环境变量规则.md` 的 RPA 命名空间小节:示例与分域说明 inventory→onhand、receipt→inbound(2026-10-16 批次 R 修订注记)。 +```bash +git add backend/app/core/config/settings.py .env.dev .env.test .env.prod .env.local docker-compose.yml docs/convention/环境变量规则.md backend/app +``` + +--- + +### Task 4: onhand 侧平移(trigger/attempts/per_source) + +**Files:** +- Create: `backend/app/services/freight_rpa/onhand/trigger_io.py`(源自 `shipping_notice/rpa.py` 的目录函数+库存导出 trigger 部分) +- Rename: `shipping_notice/rpa_attempts.py`→`freight_rpa/onhand/attempts.py`;`shipping_notice/per_source_rpa_service.py`→`freight_rpa/onhand/per_source_service.py` +- Modify: `shipping_notice/rpa.py` 拆剩 upload 部分(Task 6 处理;本任务先保留原文件并在 docstring 标注拆分中);`shipping_notice/rpa_worker_heartbeat.py`(尚未平移,旧 `shipping_notice.rpa` 引用改指 `freight_rpa.onhand.trigger_io`);全仓调用点(grep 驱动) +- Test: 对应测试文件 git mv + import/名称更新 + +**Interfaces:** +- Produces(后续任务依赖的精确名): `freight_rpa.onhand.trigger_io.write_onhand_export_trigger(...)`、`.write_onhand_export_batch_trigger(...)`、`.onhand_trigger_dir()`、`.onhand_drop_dir()`;`freight_rpa.onhand.attempts`(函数名同法替换词根 inventory→onhand);`freight_rpa.onhand.per_source_service`(类/函数名 inventory→onhand)。旧名 `write_inventory_export_trigger` 族**不留 shim**。 + +- [ ] **Step 1: 词根对照与拆分** + +`rpa.py` 中库存导出相关(目录函数、`write_inventory_export_trigger`、`write_inventory_export_batch_trigger`、批量载荷原子写)剪切到 `onhand/trigger_io.py`,标识符按对照替换:`inventory`→`onhand`(函数名/变量名/注释);schema 串 `shipping_inventory_rpa.v2`→`freight_rpa.onhand.v1`;`onhand_trigger_dir()/onhand_drop_dir()` 改读 Task 3 新 env。 +`rpa_attempts.py`→`attempts.py`、`per_source_rpa_service.py`→`per_source_service.py`:`git mv` 后文件内 inventory 词根标识符同规则替换(models import 不变:`ShippingTaskInventoryRpaAttempt` 等表名批次 S 才改)。 + +- [ ] **Step 2: 调用点更新(grep 驱动)** + +```bash +cd backend && grep -rn "shipping_notice.rpa\b\|shipping_notice import rpa\|rpa_attempts\|per_source_rpa_service\|write_inventory_export\|inventory_trigger_dir\|inventory_drop_dir" app/ tests/ --include="*.py" | grep -v "scripts/" +``` +命中点按 Interfaces 新名改写(重点:`inventory_rpa_workflow.py`、`fulfillment_workflow.py`、`inventory_workflow.py`、`api/tools/shipping_notice.py`、`schedule/shipping_inventory_rpa_job.py`;`rpa_worker_heartbeat.py` 此刻仍在 shipping_notice,其 `shipping_notice.rpa` 引用改为 `freight_rpa.onhand.trigger_io`)。schema 串断言的测试同步改 `freight_rpa.onhand.v1`。 + +- [ ] **Step 3: 测试绿** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/ -q -k "rpa"` → 既有 RPA 用例全绿(失败项=漏改 import/名称,按报错逐一修)。 +Run: 适应度测试 → PASS(`attempts.py`/`per_source_service.py` 只 import models,不违例)。 + +- [ ] **Step 4: 暂存** + +```bash +git add backend/app/services/freight_rpa backend/app/services/shipping_notice backend/tests +``` + +--- + +### Task 5: inbound 侧平移(receipt_rpa 整体 + 调拨调用点) + +**Files:** +- Rename: `backend/app/services/shipping_notice/receipt_rpa.py`→`backend/app/services/freight_rpa/inbound/trigger_io.py` +- Modify: `backend/app/services/in_transit_transfer/inbound_trigger_service.py:22`(import 与 L121/191 调用)、`shipping_notice/rpa_worker_heartbeat.py`(旧 `shipping_notice.receipt_rpa` 引用改指 `freight_rpa.inbound.trigger_io`) +- Test: `test_freight_receipt_worker_contract.py` 等 schema 断言更新 + +**Interfaces:** +- Produces: `freight_rpa.inbound.trigger_io.write_inbound_export_batch_trigger(...)`、`.inbound_trigger_dir()`、`.inbound_drop_dir()`;trigger schema `shipping_receipt_rpa.v1`→`freight_rpa.inbound.v1`;action `receipt_export_batch`→`inbound_export_batch`(trigger JSON 内 action 值,Worker Task 12 同步)。 + +- [ ] **Step 1: git mv + 词根替换** + +```bash +git mv backend/app/services/shipping_notice/receipt_rpa.py backend/app/services/freight_rpa/inbound/trigger_io.py +``` +文件内 `receipt` 词根标识符→`inbound`(`write_receipt_export_batch_trigger`→`write_inbound_export_batch_trigger`、`receipt_trigger_dir`→`inbound_trigger_dir`…);schema 串与 action 值按 Interfaces 替换;目录函数改读新 env;`rpa_worker_heartbeat.py` 的 receipt_rpa 引用同步改新路径。 + +- [ ] **Step 2: 调用点更新** + +`inbound_trigger_service.py:22`:`from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger` → `from app.services.freight_rpa.inbound.trigger_io import write_inbound_export_batch_trigger`(:121/:191 调用点同改;域内错误码 `RPA_INBOUND_*` 不变)。全仓 grep `receipt_rpa\|write_receipt_export_batch_trigger\|shipping_receipt_rpa.v1\|receipt_export_batch` 清零(scripts/ 留 Task 12)。 + +- [ ] **Step 3: 测试绿 + 暂存** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/ -q -k "receipt or inbound or trigger"` → PASS(worker contract 测试 schema 断言改 `freight_rpa.inbound.v1`)。 +```bash +git add backend/app/services/freight_rpa backend/app/services/shipping_notice backend/app/services/in_transit_transfer backend/tests +``` + +--- + +### Task 6: upload 侧平移(rpa.py 残部) + +**Files:** +- Create: `backend/app/services/freight_rpa/upload/trigger_io.py`(源自 `shipping_notice/rpa.py` 上传部分) +- Delete: `backend/app/services/shipping_notice/rpa.py`(拆空后删除) +- Modify: `backend/app/services/shipping_notice/fulfillment_workflow.py:68-69,428,535`、`api/workspace/shipping_notice.py` 触发点 + +**Interfaces:** +- Produces: `freight_rpa.upload.trigger_io.write_upload_trigger(...)`、`.upload_queue_dir()`、`.upload_trigger_dir()`(upload 词根不变,仅模块路径变);env `FREIGHT_RPA_UPLOAD_*` 不变。 + +- [ ] **Step 1: 拆移 + 删原文件** + +`rpa.py` 上传相关(`write_upload_trigger`、upload 队列/trigger 目录函数、凭据信封组装)平移至 `upload/trigger_io.py`;共享目录工具若被 onhand/inbound 复用则下沉 `freight_rpa/common/dirs.py` 并让两侧引用。`git rm backend/app/services/shipping_notice/rpa.py`。 + +- [ ] **Step 2: 调用点更新** + +grep `shipping_notice.rpa import\|shipping_notice\.rpa\.` 清零(`fulfillment_workflow` 的 `assert_freight_upload_rpa_ready` 等业务逻辑不动,仅 import 改 `freight_rpa.upload.trigger_io`)。 + +- [ ] **Step 3: 测试绿 + 暂存** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/ -q -k "upload or fulfillment"` → PASS;适应度测试 PASS。 +```bash +git add backend/app/services/freight_rpa backend/app/services/shipping_notice backend/tests +``` + +--- + +### Task 7: common 平移(凭据/心跳/告警,依赖 Task 4/5 新路径) + +**Files:** +- Rename: `backend/app/services/shipping_notice/credential_crypto.py`→`backend/app/services/freight_rpa/common/credential_crypto.py`;`rpa_worker_heartbeat.py`→`.../common/worker_heartbeat.py`;`rpa_worker_heartbeat_alert.py`→`.../common/worker_heartbeat_alert.py` +- Modify: 全仓 import 点(grep 驱动);`backend/app/services/schedule/queue_service.py`(tick 调用点改 import) +- Test: 移动既有对应测试文件(grep `credential_crypto\|rpa_worker_heartbeat` 于 `backend/tests/` 定位),仅改 import 路径与模块名 + +**Interfaces:** +- Produces: `freight_rpa.common.credential_crypto`、`freight_rpa.common.worker_heartbeat`、`freight_rpa.common.worker_heartbeat_alert`(函数签名不变,仅模块路径变;heartbeat 内对 onhand/inbound trigger_io 的引用已在 Task 4/5 指向新路径)。 + +- [ ] **Step 1: git mv 三文件 + 测试文件** + +```bash +git mv backend/app/services/shipping_notice/credential_crypto.py backend/app/services/freight_rpa/common/credential_crypto.py +git mv backend/app/services/shipping_notice/rpa_worker_heartbeat.py backend/app/services/freight_rpa/common/worker_heartbeat.py +git mv backend/app/services/shipping_notice/rpa_worker_heartbeat_alert.py backend/app/services/freight_rpa/common/worker_heartbeat_alert.py +``` +测试文件同法 `git mv`(保留历史)。 + +- [ ] **Step 2: 全仓 import 更新** + +```bash +cd backend && grep -rln "shipping_notice.credential_crypto\|shipping_notice.rpa_worker_heartbeat" app/ tests/ --include="*.py" +``` +逐文件改为 `freight_rpa.common.credential_crypto` / `freight_rpa.common.worker_heartbeat` / `freight_rpa.common.worker_heartbeat_alert`。`worker_heartbeat.py` 头注释「依赖 shipping_notice.rpa」改为「依赖 freight_rpa.onhand.trigger_io / freight_rpa.inbound.trigger_io」。 + +- [ ] **Step 3: 受影响测试绿 + 适应度测试绿** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/ -q -k "heartbeat or credential"` → PASS +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/services/freight_rpa/test_import_boundary.py -v` → PASS + +- [ ] **Step 4: 暂存** + +```bash +git add backend/app/services/freight_rpa backend/app/services/shipping_notice backend/app/services/schedule backend/tests +``` + +--- + +### Task 8: 回调 sink 注册表 + /api/freight-rpa 蓝图 + +**Files:** +- Create: `backend/app/services/freight_rpa/common/callback_sinks.py`、`backend/app/core/tool_auth.py`(自 `api/tools/shipping_notice.py:37-42` 抽出 `_require_tool_auth`)、`backend/app/api/freight_rpa.py` +- Modify: `backend/app/api/__init__.py`(注册新蓝图)、`backend/app/api/tools/shipping_notice.py`(删除 L302-416 的 `/rpa/*` 路由,改 import tool_auth) +- Test: `backend/tests/api/test_freight_rpa_api.py`(新建) + +**Interfaces:** +- Produces: `freight_rpa.common.callback_sinks.register_sink(kind: str, handler: Callable) -> None`、`dispatch_sink(kind: str, **payload) -> Any`(未注册 kind 抛 `AppError("FREIGHT_RPA.SINK_NOT_REGISTERED", 404)`);蓝图 12 条路由(Global Constraints 前缀):`/heartbeat`、`/onhand-ready`、`/onhand-batch-ready`、`/onhand-batch-claimed`、`/onhand-batch-progress`、`/inbound-batch-ready`、`/inbound-unit-progress`、`/inbound-batch-progress`、`/onhand-configuration-test-start|analyze|complete`、`/onhand-repair`、`/upload-complete`。 + +- [ ] **Step 1: 写失败测试(heartbeat + 404 门禁 + sink 分发)** + +```python +"""freight_rpa 回调 API 契约测试。""" +# 关键断言一:heartbeat 走新路由且鉴权必备 +def test_heartbeat_requires_auth(client): + assert client.post("/api/freight-rpa/heartbeat", json={}).status_code == 401 + +# 关键断言二:旧路由已死(无兼容层,脏回调显式 404) +def test_legacy_rpa_routes_removed(client): + assert client.post("/api/shipping-notice/rpa/heartbeat", json={}).status_code == 404 + +# 关键断言三:未注册 sink 显式失败 +def test_onhand_ready_without_sink_fails(client, auth_headers): + resp = client.post("/api/freight-rpa/onhand-ready", json={}, headers=auth_headers) + assert resp.status_code == 404 and resp.get_json()["error"]["code"] == "FREIGHT_RPA.SINK_NOT_REGISTERED" +``` +(`client`/`auth_headers` 沿用 `tests/conftest.py` 既有 tool-auth fixture 手法;`auth_headers` 用测试 integration key 生成 Bearer。) + +- [ ] **Step 2: 运行确认失败** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/api/test_freight_rpa_api.py -v` → FAIL(路由不存在)。 + +- [ ] **Step 3: 实现 registry + 蓝图** + +`callback_sinks.py`: +```python +"""RPA 回调业务 sink 注册表。 + +用途:freight_rpa 收到 Worker 回调后,把业务持久化委托给业务域注册的处理器, + 从而 freight_rpa 零业务 workflow import(spec §3 import 边界)。 +约束:kind 命名 = 回调路由名去前缀(如 "onhand-ready");handler 由组合根注册。 +""" +_SINKS: dict[str, Callable[..., Any]] = {} + +def register_sink(kind: str, handler: Callable[..., Any]) -> None: + _SINKS[kind] = handler + +def dispatch_sink(kind: str, **payload: Any) -> Any: + handler = _SINKS.get(kind) + if handler is None: + raise AppError("FREIGHT_RPA.SINK_NOT_REGISTERED", 404) + return handler(**payload) +``` +`api/freight_rpa.py`:12 条路由,鉴权统一 `tool_auth.require_tool_auth()`;`/heartbeat` 直调 `freight_rpa.common.worker_heartbeat`;其余端点解析载荷后 `dispatch_sink(kind, **payload)`(Task 9/10 注册真实 sink 前返回 404 语义)。`api/__init__.py` 注册蓝图。 + +- [ ] **Step 4: admin rpa-profiles 路由迁移(批次 R 唯一前端改动,Q8 边界)** + +`api/admin/shipping_inventory.py` 的 rpa-profiles CRUD(L113-136)迁至新文件 `backend/app/api/admin_freight_rpa.py`,URL `/shipping-notice/rpa-profiles`→`/freight-rpa/rpa-profiles`(admin_bp `/api/admin` 前缀不变);`/sources/*` 与 `receipt-report-config` 路由留原地(批次 S)。前端 `features/admin/api/admin.api.ts` 三处 URL(L190/329/333)同步改 `/api/admin/freight-rpa/rpa-profiles`。 +Run: `cd frontend && npx vitest run src/features/admin --reporter=dot` → PASS。 + +- [ ] **Step 5: 测试绿 + 暂存** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/api/test_freight_rpa_api.py tests/ -q -k "rpa or tool"` → PASS(旧 tools rpa 测试删除或改指新路由)。 +```bash +git add backend/app/services/freight_rpa backend/app/core/tool_auth.py backend/app/api backend/tests/api/test_freight_rpa_api.py frontend/src/features/admin/api/admin.api.ts +``` + +--- + +### Task 9: inventory_rpa_workflow 拆分(协议壳入包,业务落盘留域) + +**Files:** +- Create: `backend/app/services/freight_rpa/onhand/workflow_protocol.py`(回调协议:claim/progress/超时判定/attempt 记账) +- Rename: `shipping_notice/inventory_configuration_test.py`→`freight_rpa/onhand/configuration_test.py`;`shipping_notice/inventory_rpa_callback_cleanup.py`→`freight_rpa/onhand/callback_cleanup.py` +- Create: `backend/app/services/shipping_notice/rpa_sinks.py`(业务 sink:快照落盘、ScheduleRun finalize、ProcessGate 推进、审计投影) +- Modify: `backend/app/services/shipping_notice/inventory_rpa_workflow.py`(拆后仅剩业务落盘与编排入口 `ensure_inventory_via_rpa` 调用链) +- Modify: `backend/app/__init__.py`(组合根注册 sinks——create_app 内 import 并调用注册) +- Test: 既有 inventory rpa workflow 测试改造为「HTTP 缝」(接缝 1)+ sink 单测 + +**Interfaces:** +- Consumes: Task 8 `register_sink/dispatch_sink`。 +- Produces: sink kind 注册清单(组合根调用):`register_sink("onhand-ready", shipping_notice_rpa_sink)`、`register_sink("onhand-batch-ready", ...)`、`register_sink("onhand-batch-claimed", ...)`、`register_sink("onhand-batch-progress", ...)`、`register_sink("onhand-configuration-test-start|analyze|complete", ...)`、`register_sink("onhand-repair", ...)`;`workflow_protocol.claim_onhand_batch(...)`、`.record_onhand_progress(...)`(协议态:attempt 行、callback_id、幂等键)。 + +- [ ] **Step 1: 以回调载荷分类拆线** + +grep `inventory_rpa_workflow` 的公开函数与 `/rpa/` 旧端点处理器(`rpa_report_inventory`(L1683)、`rpa_report_inventory_batch`(L2103) 等),按「是否写 ShippingInventoryFile/快照/ProcessGate/ScheduleRun 业务终态」二分:**写业务的留 shipping_notice**,**attempt/协议/幂等/进度态的入 `workflow_protocol.py`**。拆分不变量:`ShippingTaskInventoryRpaAttempt` 行写入归 protocol(freight_rpa),业务快照与门禁推进归 sink(shipping_notice)——同事务边界由 sink handler 内部保持(与拆分前行为等价)。 +同批整体平移:`inventory_configuration_test.py`→`onhand/configuration_test.py`、`inventory_rpa_callback_cleanup.py`→`onhand/callback_cleanup.py`(词根 inventory→onhand 标识符替换 + 全仓 import 更新;两文件均为 RPA 协议侧,无业务落盘)。 + +- [ ] **Step 2: 组合根注册 + 旧端点分发改新路由** + +`app/__init__.py` create_app:`from app.services.shipping_notice.rpa_sinks import register_onhand_sinks; register_onhand_sinks()`。Task 8 蓝图各端点经 `dispatch_sink` 落到真实处理器。旧 `api/tools/shipping_notice.py` 的对应分发逻辑已在该蓝图删除(Task 8),此处确认无残留引用。 + +- [ ] **Step 3: 测试改造 + 全绿** + +既有 `test_shipping_notice_inventory_rpa_workflow.py`(481 处 inventory 命中,**文件名不改**——批次 S):URL 全部改 `/api/freight-rpa/*`,schema/错误断言改新值;新增 sink 未注册→404 用例已在 Task 8 覆盖。 +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/ -q -k "inventory_rpa or freight_rpa"` → PASS;适应度测试 PASS(`rpa_sinks.py` 在 shipping_notice 侧,不违例)。 + +- [ ] **Step 4: 暂存** + +```bash +git add backend/app/services/freight_rpa backend/app/services/shipping_notice backend/app/__init__.py backend/tests +``` + +--- + +### Task 10: receipt 链拆分(归档入包,业务桥留域) + +**Files:** +- Create: `backend/app/services/freight_rpa/inbound/report_archive.py`(源自 `receipt_report_storage.py`:原样归档、三年保留、resend、通知投递) +- Create: `backend/app/services/shipping_notice/rpa_sinks.py`(追加 inbound sink:终态落库后推进 in_transit `TransferSourceJob`——内部调 `in_transit_transfer.inbound_callback_bridge`,调用方向与拆分前一致) +- Modify: `backend/app/services/schedule/freight_receipt_rpa_finalize.py`(引用 `report_archive` 新路径)、`schedule/shipping_receipt_rpa_archive.py`、`schedule/freight_receipt_rpa_retention_job.py`、`api/schedule/runs.py`(resend/raw-zip 处理器引用) + +**Interfaces:** +- Consumes: Task 8 registry;白名单模块 `shipping_notice.audit_service`、`shipping_notice.file_assets`(归档与审计直接 import,适应度测试放行)。 +- Produces: `freight_rpa.inbound.report_archive.ingest_inbound_callback(...)`(原 `ingest_receipt_callback` 的归档部分);sink kind `"inbound-batch-ready"`/`"inbound-unit-progress"`/`"inbound-batch-progress"` 注册;三年保留与 resend 行为不变。 + +- [ ] **Step 1: 拆分与注册** + +`receipt_report_storage.py` 中归档/保留/通知函数平移 `report_archive.py`(函数名 receipt 词根→inbound;模型 `ShippingReceiptReport*` 引用不变——批次 S 才改表);`_advance_transfer_source_job` 业务桥留在 shipping_notice sink 内。组合根追加 `register_inbound_sinks()`。`freight_receipt_rpa_finalize` 等 schedule 文件的 import 改新路径(Task 11 会整体平移这些文件,此处先改引用保证绿)。 + +- [ ] **Step 2: 测试绿** + +既有 `test_freight_receipt_rpa_callback.py`(103 处 receipt 命中,文件名不改):URL 改 `/api/freight-rpa/inbound-*`、断言行为不变(归档三年、TransferSourceJob 推进、resend)。 +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/ -q -k "receipt"` → PASS。 + +- [ ] **Step 3: 暂存** + +```bash +git add backend/app/services/freight_rpa backend/app/services/shipping_notice backend/app/services/schedule backend/app/__init__.py backend/tests +``` + +--- + +### Task 11: schedule 调度壳平移 + job key 改名(tt16) + +**Files:** +- Rename: `backend/app/services/schedule/{shipping_inventory_rpa_job,shipping_inventory_rpa_finalize,shipping_inventory_rpa_archive}.py`→`backend/app/services/schedule/freight_onhand_rpa_{job,finalize,archive}.py`;`{freight_receipt_rpa_job,freight_receipt_rpa_finalize,freight_receipt_rpa_retention_job,shipping_receipt_rpa_archive}.py`→`freight_inbound_rpa_{job,finalize,retention,archive}.py` +- Create: `backend/migrations/versions/tt16c7d8e9f0a1b2_rename_freight_rpa_job_keys.py` +- Modify: `backend/app/services/schedule/job_registry.py`(L374/400/413 三个注册项 key/label/description;handler import)、`schedule/queue_service.py`(finalize/heartbeat 引用)、`backend/workers/worker_scheduler.py`、`backend/app/api/schedule/rpa_workers.py`(scope 取值 `inventory|receipt`→`onhand|inbound`,默认值 L28 同步) +- Modify: `frontend/src/features/admin/modules/schedules/utils/schedule-job-key.utils.ts`、`types/schedule-admin.types.ts`、`composables/schedule-admin/*`(job key 字面量)、`frontend/src/features/admin/api/schedule.api.ts`(L184/198 scope 类型与默认值)、`ScheduleWorkbenchPanel.vue`(心跳徽标 scope 实参) +- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/admin.json`(`platformJobShippingInventory` 等 label_key 键值:en 文案 Onhand/Inbound;中文「库存/入站」基线) +- Test: `backend/tests/services/in_transit_transfer/` 同级新建 `backend/tests/test_migration_tt16_job_keys.py`;schedule 相关既有测试 import 更新 + +**Interfaces:** +- Produces: job key `shipping-inventory-rpa`→`freight-rpa-onhand`、`freight-receipt-rpa`→`freight-rpa-inbound`、`freight-receipt-rpa-retention`→`freight-rpa-inbound-retention`;tt16 revision `tt16c7d8e9f0a1b2`(down_revision=`tt15b6a7b8c9d0`);`options_source` 键(`shipping_inventory_sources`/`shipping_receipt_sources`)**本批不动**(绑定业务表名,批次 S)。 + +- [ ] **Step 1: 写迁移契约测试(先失败)** + +```python +"""tt16 排程 job key 入站化迁移契约测试。""" +def test_revision_chains_from_tt15(): + migration = _load("tt16c7d8e9f0a1b2") # _load 沿用 tt14 测试手法 + assert migration.down_revision == "tt15b6a7b8c9d0" + +def test_job_key_upgrade_downgrade(app_ctx): + # 造 shipping-inventory-rpa 行 → upgrade → 断言 freight-onhand-rpa → downgrade → 还原 +``` + +- [ ] **Step 2: 运行确认失败** → `pytest tests/test_migration_tt16_job_keys.py -v` → FAIL。 + +- [ ] **Step 3: 写 tt16** + +```python +"""tt16:RPA 排程任务 key 更名(批次 R,随代码同窗口发布)。 + +依赖:tt15b6a7b8c9d0。逻辑:schedule_tasks.job_key 三键 UPDATE; + downgrade 反向映射;无表结构变更。 +""" +revision = "tt16c7d8e9f0a1b2" +down_revision = "tt15b6a7b8c9d0" + +_MAPPING = { + "shipping-inventory-rpa": "freight-rpa-onhand", + "freight-receipt-rpa": "freight-rpa-inbound", + "freight-receipt-rpa-retention": "freight-rpa-inbound-retention", +} + +def upgrade(): + for old, new in _MAPPING.items(): + op.execute(f"UPDATE schedule_tasks SET platform_api_path='{new}' WHERE platform_api_path='{old}'") + +def downgrade(): + for old, new in _MAPPING.items(): + op.execute(f"UPDATE schedule_tasks SET platform_api_path='{old}' WHERE platform_api_path='{new}'") +``` + +- [ ] **Step 4: 注册表与文件改名** + +`job_registry.py` 三项:key 按对照表、label 不变(中文基线 onhand=库存)、label_key 不变(四语言 en 值文案改 Onhand/Inbound)、description「收料」→「入站」、handler import 改新模块名。8 个 schedule 文件 `git mv` + 文件内 self-import 更新 + `queue_service.py`/`worker_scheduler.py` 引用更新。前端 job-key 字面量与 admin.json 四语言值(en:Onhand/Inbound;zh 库存/入站;th 对应)。 + +- [ ] **Step 5: 测试绿 + 暂存** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_migration_tt16_job_keys.py tests/ -q -k "schedule or migration"` → PASS +Run: `cd frontend && npx vitest run src/features/admin --reporter=dot && npm run build` → PASS +```bash +git add backend/app/services/schedule backend/migrations/versions/tt16c7d8e9f0a1b2_rename_freight_rpa_job_keys.py backend/tests/test_migration_tt16_job_keys.py backend/workers frontend/src/features/admin frontend/src/locales +``` + +--- + +### Task 12: Worker 侧切换(目录/schema/URL/计划任务) + +**Files:** +- Rename: `scripts/freight_rpa/inventory/`→`scripts/freight_rpa/onhand/`(4 文件,`inventory_rpa_worker.py`→`onhand_rpa_worker.py`);`scripts/freight_rpa/receipt/`→`scripts/freight_rpa/inbound/`(6 文件,`receipt_rpa_worker.py`→`inbound_rpa_worker.py`、`receipt_dbs_export.py`→`inbound_dbs_export.py`、`receipt_crane_export.py`→`inbound_crane_export.py`、`receipt_excel_empty.py`→`inbound_excel_empty.py`) +- Modify: `scripts/freight_rpa/common/rpa_heartbeat.py`(URL L182)、`common/trigger_consumer.py`(schema 校验串)、两个 worker 内回调 path(L1297/1426/1456 等)收拢为 `common/rpa_callbacks.py` 常量、`connectors/dsv/dsv_report_export.py`(58 处 receipt 词根→inbound)、`README.md`、2 个 `register_*.ps1`(任务名与脚本路径)、`start_*.ps1` +- Modify: `backend/tests/test_freight_rpa_worker.py`、`backend/tests/test_freight_receipt_worker_contract.py` 等(import 路径与断言) +- Create: `docs/features/freight-rpa/cutover-runbook.md`(切换 runbook,生产窗口用) + +**Interfaces:** +- Produces: Worker 回调 URL 常量(`/api/freight-rpa/...` 12 条);schema 校验 `freight_rpa.onhand.v1`/`freight_rpa.inbound.v1`;action `inbound_export_batch`;env 读名与 Task 3 一致;计划任务新名 `HXOPS Freight Onhand RPA Worker`/`HXOPS Freight Inbound RPA Worker`(旧名须在窗口注销)。 + +- [ ] **Step 1: 目录改名 + 词根替换** + +```bash +git mv scripts/freight_rpa/inventory scripts/freight_rpa/onhand +git mv scripts/freight_rpa/receipt scripts/freight_rpa/inbound +git mv scripts/freight_rpa/onhand/inventory_rpa_worker.py scripts/freight_rpa/onhand/onhand_rpa_worker.py +git mv scripts/freight_rpa/inbound/receipt_rpa_worker.py scripts/freight_rpa/inbound/inbound_rpa_worker.py +git mv scripts/freight_rpa/inbound/receipt_dbs_export.py scripts/freight_rpa/inbound/inbound_dbs_export.py +git mv scripts/freight_rpa/inbound/receipt_crane_export.py scripts/freight_rpa/inbound/inbound_crane_export.py +git mv scripts/freight_rpa/inbound/receipt_excel_empty.py scripts/freight_rpa/inbound/inbound_excel_empty.py +``` +全目录 grep `inventory`→`onhand`、`receipt`→`inbound`(标识符/注释/schema/env 读名/trigger 文件名前缀 `receipt_export_batch_*`→`inbound_export_batch_*`),`upload` 词根不动;回调 URL 硬编码点收拢到新建 `common/rpa_callbacks.py`(12 条 path 常量 + `post_callback(kind, payload)` 复用既有 `_post_callback` 逻辑)。 + +- [ ] **Step 2: 后端 worker 测试同步** + +`backend/tests/test_freight_rpa_worker.py` 等 import 改新路径;schema/URL/trigger 文件名断言改新值。 + +- [ ] **Step 3: 双侧契约一致性门禁** + +```bash +grep -rn "freight_rpa.onhand.v1" backend/app scripts/freight_rpa --include="*.py" | wc -l +grep -rn "shipping_inventory_rpa.v2\|shipping_receipt_rpa.v1" backend/app scripts/freight_rpa --include="*.py"; echo "exit=$?" +``` +Expected: 新 schema 双侧命中;旧 schema 清零。后端写入的 trigger 字段名与 `trigger_consumer.py` 校验字段逐一比对(四态契约 claim/processing/processed/failed 不变)。心跳契约同步点核对:能力串 `inventory_export/receipt_export`→`onhand_export/inbound_export`(`freight_upload` 不变)、worker_id 后缀判定 `-receipt`→`-inbound`(Windows 端 `FREIGHT_RPA_WORKER_ID` 配置值若以 `-receipt` 结尾须随窗口改配,写进 runbook)、目录存在性检查路径清单(`inventory`,`receipt`→`onhand`,`inbound`)。 + +- [ ] **Step 4: ps1 与 README** + +`register_onhand_worker_tasks.ps1`/`register_inbound_worker_tasks.ps1`:`-TaskName` 默认值改新名、脚本路径改新目录、保留 Unregister 清理段(runbook 引用);`start_*.ps1` 路径同步;`README.md` 目录布局/契约/env 全部新词(inventory 194 处清零)。 + +- [ ] **Step 5: runbook 落盘 + 暂存** + +`cutover-runbook.md`(发布窗口执行序,人机协作):① 管理端暂停 `freight-rpa-onhand`/`freight-rpa-inbound`/retention 三任务 → ② 心跳确认 Worker 空闲(无 processing 在途)→ ③ trigger/drop 目录排空归档 → ④ CIFS `freight_rpa/inventory→onhand`、`receipt→inbound` 目录改名(新增 `outbound/`)→ ⑤ 部署后端+前端 → `flask db upgrade`(tt16)→ ⑥ Windows 计划任务:注册新名任务、Unregister 旧名,`FREIGHT_RPA_WORKER_ID` 后缀 `-receipt`→`-inbound`(如适用)→ ⑦ 单源冒烟(一次 onhand 导出+一次 inbound 导出+一次上传,心跳徽标核对 onhand/inbound 两 scope)→ ⑧ 恢复排程。回滚段:整体回退=旧镜像+`flask db downgrade tt15b6a7b8c9d0`+旧 Worker 包+目录名还原。 +```bash +git add scripts/freight_rpa backend/tests docs/features/freight-rpa/cutover-runbook.md +``` + +--- + +### Task 13: 批次 R 终局门禁 + +**Files:** 无新改动(门禁任务;回归修复归属前序任务) + +- [ ] **Step 1: 受影响面后端 + 适应度(用户指示:不跑全局)** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/ -q -k "shipping or rpa or receipt or transfer or schedule or heartbeat or credential or inbound or freight"` +Expected: 与 Task 1 基线一致零新增失败;`tests/services/freight_rpa/test_import_boundary.py` PASS。 + +- [ ] **Step 2: 前端全量** + +Run: `cd frontend && npx vitest run --reporter=dot && npm run build` → PASS。 + +- [ ] **Step 3: grep 终局断言** + +```bash +grep -rn "shipping_notice.rpa\b\|shipping_notice.receipt_rpa\|shipping_notice.credential_crypto\|shipping_notice.rpa_worker_heartbeat\|shipping_notice.rpa_attempts\|per_source_rpa_service\|receipt_report_storage" backend/app --include="*.py"; echo "exit=$?" +grep -rn "shipping_inventory_rpa.v2\|shipping_receipt_rpa.v1\|/api/shipping-notice/rpa/" backend/app scripts/freight_rpa --include="*.py" | grep -v docs; echo "exit=$?" +``` +Expected: 两条均无输出。 + +- [ ] **Step 4: 冒烟(dev,手工)** + +① 排程页手动触发 freight-onhand-rpa(MOCK 模式 `FREIGHT_RPA_WORKER_MOCK=true`)→ trigger 文件 schema `freight_rpa.onhand.v1`、回落 awaiting_rpa_callback、回调后 ScheduleRun 终态+attempt 行;② inbound 同法;③ 工作台 retry_rpa 与 rpa-upload 走通;④ Worker 心跳页离线告警不误报。 + +- [ ] **Step 5: 暂存(如有回归修复)** diff --git a/docs/superpowers/plans/2026-10-17-freight-rpa-decouple-batch-d.md b/docs/superpowers/plans/2026-10-17-freight-rpa-decouple-batch-d.md new file mode 100644 index 00000000..fa21bd57 --- /dev/null +++ b/docs/superpowers/plans/2026-10-17-freight-rpa-decouple-batch-d.md @@ -0,0 +1,34 @@ +# Freight RPA 解耦批次 D 实施计划(权威文档收口) + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development. + +**Goal:** 把权威文档中的 inventory/receipt 旧词收口为 onhand/inbound;确认 outbound 仅调拨;upload=freight_upload;不做 shipment→outbound。 + +**Spec:** `docs/superpowers/specs/2026-10-16-freight-rpa-decouple-and-rename-design.md` +**D6:** `docs/superpowers/` 历史 plans/specs/ADR 归档**不改写**;权威文档必改。 + +## Global Constraints + +- 不提交(本轮用户已下令整段不提交) +- 不改 `docs/superpowers/plans|specs` 历史快照(本批新写的 batch-d 计划除外) +- 不改 ADR 编号历史正文中的决策快照句,除非 ADR 0003 已在批次 R 勘误范围内需保持一致 +- shipment 履约 / contract_payment / freight_upload / 调拨 outbound 边界以 GLOSSARY 为准 + +## Task 1: 权威文档术语收口 + +**Files (must update if they still say inventory/receipt as code terms):** + +- `docs/features/shipping-notice/technical.md`(inventory/receipt 代码词 → onhand/inbound;保留履约 shipment) +- `docs/features/freight-rpa/GLOSSARY.md`(核对,已纠偏则只补漏) +- `docs/features/freight-rpa/cutover-runbook.md`(核对 freight_upload) +- `scripts/freight_rpa/README.md` +- `docs/funclist.md` / `docs/demand.md` / `docs/tec.md` 中相关条目 +- `docs/convention/环境变量规则.md` 中 FREIGHT_RPA_* 命名段 +- `docs/adr/0003-freight-rpa-module-boundary.md`(若与现行 R→S→D 不一致则就地勘误) + +Steps: + +1. Grep 上述权威路径中的 `inventory`/`receipt`/`outbound_upload`/`shipment→outbound` 作为代码术语的命中。 +2. 按 GLOSSARY 替换;中文「库存」可保留为 onhand 文案。 +3. 自检:`docs/superpowers/` 除本批新计划外不改。 +4. Stage only the doc files you change. Do not commit. diff --git a/docs/superpowers/plans/2026-10-17-freight-rpa-decouple-batch-s.md b/docs/superpowers/plans/2026-10-17-freight-rpa-decouple-batch-s.md new file mode 100644 index 00000000..656d9b31 --- /dev/null +++ b/docs/superpowers/plans/2026-10-17-freight-rpa-decouple-batch-s.md @@ -0,0 +1,201 @@ +# Freight RPA 解耦批次 S 实施计划(表 rename + shipping_notice 域 inventory→onhand) + +> **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:** 在批次 R 已切换 RPA 契约(onhand/inbound/`freight_upload`)的前提下,把 shipping_notice 业务域代码/表/前端/i18n/权限/存量枚举从 `inventory`/`receipt` 词根迁到 `onhand`/`inbound`,数据库 **29 张表一次 rename**,无兼容层。 + +**Architecture:** 表命名与 env/包/蓝图同构——共享 `freight_rpa_sources`/`freight_rpa_profiles`;配置域 `freight_rpa_onhand_*` / `freight_rpa_inbound_*`;发货消费事实保留 `shipping_*` 前缀只改词根→`shipping_onhand_*`。admin 入口统一 `/api/admin/freight-rpa/`。 + +**Tech Stack:** Flask + SQLAlchemy 2.0 + Alembic(接批次 R 后 head)、Vue3+TS+i18n 四语言、pytest/vitest;自写 codemod(不引第三方)。 + +**Spec:** `docs/superpowers/specs/2026-10-16-freight-rpa-decouple-and-rename-design.md` +**清单权威:** `docs/superpowers/plans/2026-10-16-freight-rpa-decouple-and-rename-evaluation.md` §5/§8 +**术语:** `docs/features/freight-rpa/GLOSSARY.md` + +## Global Constraints + +- **禁止自动 commit**:每任务止于 `git add`;提交须用户显式批准。 +- **批次 T 已废除**:禁止把履约 `shipment_*` / 出货 Excel 改成 `outbound_*`;outbound **仅**调拨出站。 +- **upload 独立**:action=`freight_upload`(已与心跳对齐);禁止 `outbound_upload` / `freight_rpa_upload`。 +- **白名单勿伤**:`contract_payment` 的 `shipment`(发货款);`movement` 一词;MinIO/storage_key;历史 `docs/superpowers/` 与旧迁移文件不改写。 +- **无双路由/无兼容层**:旧 admin 路径与旧枚举字符串发布后直接失效;权限键存量必须 UPDATE。 +- **迁移**:全部带可执行 downgrade;枚举 UPDATE 分批防长锁;发布前全库备份义务。 +- **中文文案**:onhand=库存、inbound=入站、outbound=出站(仅调拨)、履约称「出货」。 +- **注释纪律**:改签名/协作关系同步文件头与函数 docstring(AGENTS.md §5)。 +- **Windows**:`backend/.venv/Scripts/python.exe`;pytest 从 `backend/`;vitest/build 从 `frontend/`。 +- **不新增第三方依赖**。 + +## 29 表映射(S1 权威表) + +### 共享 → `freight_rpa_*` +| 旧 | 新 | +| --- | --- | +| `shipping_inventory_sources` | `freight_rpa_sources` | +| `shipping_rpa_profiles` | `freight_rpa_profiles` | + +### 配置域 → `freight_rpa_onhand_*` +| 旧 | 新 | +| --- | --- | +| `shipping_inventory_fields` | `freight_rpa_onhand_fields` | +| `shipping_inventory_source_parsing_binding_audits` | `freight_rpa_onhand_source_parsing_binding_audits` | +| `shipping_inventory_parsing_profiles` | `freight_rpa_onhand_parsing_profiles` | +| `shipping_inventory_structure_analyses` | `freight_rpa_onhand_structure_analyses` | +| `shipping_inventory_configuration_test_runs` | `freight_rpa_onhand_configuration_test_runs` | +| `shipping_inventory_validation_batches` | `freight_rpa_onhand_validation_batches` | +| `shipping_inventory_routing_rules` | `freight_rpa_onhand_routing_rules` | +| `shipping_inventory_routing_rule_conditions` | `freight_rpa_onhand_routing_rule_conditions` | +| `shipping_inventory_routing_rule_versions` | `freight_rpa_onhand_routing_rule_versions` | +| `shipping_inventory_external_mappings` | `freight_rpa_onhand_external_mappings` | +| `shipping_inventory_mappings` | `freight_rpa_onhand_mappings` | +| `shipping_task_inventory_rpa_attempts` | `freight_rpa_onhand_task_rpa_attempts` | + +### inbound → `freight_rpa_inbound_*` +| 旧 | 新 | +| --- | --- | +| `shipping_receipt_report_configs` | `freight_rpa_inbound_report_configs` | +| `shipping_receipt_rpa_unit_runs` | `freight_rpa_inbound_rpa_unit_runs` | +| `shipping_receipt_report_files` | `freight_rpa_inbound_report_files` | +| `shipping_receipt_notification_deliveries` | `freight_rpa_inbound_notification_deliveries` | + +### 发货消费事实 → `shipping_onhand_*`(保留 shipping 前缀) +| 旧 | 新 | +| --- | --- | +| `shipping_inventory_files` | `shipping_onhand_files` | +| `shipping_inventory_candidate_sets` | `shipping_onhand_candidate_sets` | +| `shipping_inventory_candidate_sources` | `shipping_onhand_candidate_sources` | +| `shipping_inventory_candidate_lines` | `shipping_onhand_candidate_lines` | +| `shipping_inventory_preparation_attempts` | `shipping_onhand_preparation_attempts` | +| `shipping_inventory_preparation_source_attempts` | `shipping_onhand_preparation_source_attempts` | +| `shipping_task_inventory_links` | `shipping_task_onhand_links` | +| `shipping_temporary_inventory_sessions` | `shipping_temporary_onhand_sessions` | +| `shipping_notice_line_inventory_matches` | `shipping_notice_line_onhand_matches` | +| `shipping_notice_inventory_verifications` | `shipping_notice_onhand_verifications` | +| `shipping_notice_inventory_verification_lines` | `shipping_notice_onhand_verification_lines` | + +列名族(随迁):`inventory_source_id`→`source_id` 等(以 evaluation §8.1 为准,迁移内列清单锁死)。`in_transit_transfer` 对 `shipping_receipt_report_files` 的 FK 必须跟随 inbound rename。 + +--- + +### Task 1: 迁移骨架 + 29 表 rename 往返测试(红) + +**Files:** +- Create: `backend/migrations/versions/_freight_rpa_batch_s_rename_tables.py`(down_revision = 当前 head) +- Create: `backend/tests/migrations/test_freight_rpa_batch_s_rename_contract.py`(或沿用既有 migration contract 目录惯例) + +- [ ] **Step 1: 写失败测试** — SQLite upgrade 后断言 29 新表名存在、旧表名不存在;downgrade 后反向;再 upgrade。 +- [ ] **Step 2: 跑测确认失败** +```bash +cd backend && ./.venv/Scripts/python.exe -m pytest tests/migrations/test_freight_rpa_batch_s_rename_contract.py -q +``` +- [ ] **Step 3: 实现 rename_table + 索引/约束/FK 名 sweep + downgrade** +- [ ] **Step 4: 跑测通过** +- [ ] **Step 5: 暂存不提交** + +--- + +### Task 2: models 类名/文件名/__tablename__ 对齐 + +**Files:** +- Modify/Rename: `backend/app/models/shipping_inventory_*.py`、`shipping_receipt_report.py`、`shipping_task_inventory_rpa_attempts.py`、`shipping_temporary_inventory.py`、`shipping_notice_line_inventory_match.py`、相关 `shipping.py`/`shipping_fulfillment.py` 段落、`models/__init__.py` +- Modify: `backend/app/models/in_transit_transfer.py`(FK 字符串) + +- [ ] **Step 1: 更新测试或编译探针**(import 旧类名应失败) +- [ ] **Step 2: 跑测确认红** +- [ ] **Step 3: git mv + 类名/表名/关系字符串替换;同步文件头注释** +- [ ] **Step 4: 相关 model 测试绿** +- [ ] **Step 5: 暂存不提交** + +--- + +### Task 3: 后端 services/api 机械改名(inventory→onhand,receipt→inbound) + +**Files:** `backend/app/services/shipping_notice/**`、`backend/app/services/admin/shipping_inventory_service.py`、`backend/app/api/**` 中引用旧模型/路径的模块;**不含**把 `shipment_*` 改 outbound。 + +- [ ] **Step 1: 写/更新聚焦测试**(至少一条 admin sources 列表、一条 candidate 流) +- [ ] **Step 2: 红** +- [ ] **Step 3: codemod + 手工修歧义**(白名单排除 contract_payment、shipment 履约、freight_upload) +- [ ] **Step 4: `pytest -k "onhand or inbound or freight_rpa or shipping_notice"` 相关子集绿** +- [ ] **Step 5: 暂存不提交** + +--- + +### Task 4: admin 路由迁 `/api/admin/freight-rpa/` + 权限键 + +**Files:** +- Modify/Rename: `backend/app/api/admin/shipping_inventory.py` → freight-rpa 树 +- Modify: `backend/app/api/admin/__init__.py`、`admin_freight_rpa.py` 合并边界 +- Modify: 权限常量与校验;迁移脚本(或本批 migration 第二段)UPDATE 权限表存量字符串 `shipping_inventory`→`freight_rpa` + +- [ ] **Step 1: 契约测试** — 新路径 200;旧 `/api/admin/shipping-notice/...` inventory 管理路径 404 +- [ ] **Step 2: 红** +- [ ] **Step 3: 实现路由树**(共享 sources/rpa-profiles;onhand/*;sources//inbound-report-config;temporary sessions 留 shipping-notice 只改词根) +- [ ] **Step 4: 测绿** +- [ ] **Step 5: 暂存不提交** + +--- + +### Task 5: 前端模块 git mv + API/路由/权限 + i18n 四语言 + +**Files:** +- `frontend/src/features/admin/modules/shipping-inventory/` → `freight-rpa/` +- `admin.routes.ts`、`modules.ts`、`admin.types.ts`、`admin.api.ts` +- `locales/{zh-CN,zh-TW,en,th}/admin.json`、`errors.json`(及 chat/workspace 中 inventory 键) + +- [ ] **Step 1: 写/更新 vitest**(模块 id、路由名 `AdminFreightRpa`) +- [ ] **Step 2: 红** +- [ ] **Step 3: git mv + URL/键替换;四语言同步** +- [ ] **Step 4: `npm run test -- --run` 相关 + `npm run build`** +- [ ] **Step 5: 暂存不提交** + +--- + +### Task 6: 存量枚举/审计/job_type 数据迁移 + +**Files:** 新 Alembic data migration(可与 Task 1 同文件分段或独立 revision) + +对象(evaluation §8.2):`shipping_task_events` 事件名/step_key;`step_payload_json`/ui_state ~40 契约值;`jobs.job_type`(如 `SHIPPING_INVENTORY_CALLBACK_PROCESS`);attempt 行内枚举;权限存量(若未在 Task 4 完成)。 + +- [ ] **Step 1: 迁移契约测试**(种子旧值 → upgrade → 断言新值 → downgrade) +- [ ] **Step 2: 红** +- [ ] **Step 3: 分批 UPDATE + downgrade** +- [ ] **Step 4: 测绿** +- [ ] **Step 5: 暂存不提交** + +--- + +### Task 7: 配置/脚本/job 注册键 + 错误码族 + +**Files:** +- `backend/config/shipping_inventory_sources.yaml`(改名+键) +- `backend/scripts/import_shipping_inventory_sources.py` +- `job_registry.py` options_source;jobs handler 模块名 +- `errors.json`×4 + 后端错误码定义/抛点(`SHIPPING_INVENTORY_*` 族) + +- [ ] **Step 1: 护栏测试**(四语言 errors 键 parity) +- [ ] **Step 2–4: 红→改→绿** +- [ ] **Step 5: 暂存不提交** + +--- + +### Task 8: grep 门禁 + 子集回归收口 + +- [ ] **Step 1: 增加/更新门禁脚本或测试** — 白名单外 `inventory`/`receipt` 在约定路径清零;**禁止**把 `shipment` 履约扫成待改;合法 `outbound` 仅调拨语境 +- [ ] **Step 2: 跑门禁(预期先红再修漏网)** +- [ ] **Step 3: 后端关键 pytest 基线 + 前端 build** +- [ ] **Step 4: 自审 DO-NOT-TOUCH 列表无误伤** +- [ ] **Step 5: 暂存不提交** + +--- + +## 计划外(下一批) + +- **批次 D**:权威文档全域清扫(`shipping-notice/technical.md`、funclist/demand/tec、环境变量规则、freight_rpa README);历史 superpowers 不改写。 +- **批次 T**:已废除,不实施。 + +## 验收 + +- 29 表 rename 往返绿;旧 admin inventory 路径 404;新 freight-rpa 管理路径可用 +- 权限键迁移后管理员不丢页 +- i18n 四语言键集一致;errors 族同步 +- grep 门禁白名单外清零;shipment 履约与 contract_payment 未误伤 +- upload action 仍为 `freight_upload` diff --git a/docs/superpowers/plans/2026-10-17-freight-rpa-upload-action-fix.md b/docs/superpowers/plans/2026-10-17-freight-rpa-upload-action-fix.md new file mode 100644 index 00000000..683b1a2c --- /dev/null +++ b/docs/superpowers/plans/2026-10-17-freight-rpa-upload-action-fix.md @@ -0,0 +1,78 @@ +# Freight RPA upload action 纠偏 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:** 把批次 R 误写的 upload trigger action `outbound_upload` 改回与心跳能力一致的 `freight_upload`,消除「出站 outbound」与「履约上传 upload」混名。 + +**Architecture:** upload 是与 onhand/inbound/outbound **同级独立域**。trigger schema 保持 `freight_rpa.upload.v1`;action 与心跳能力串 `FREIGHT_UPLOAD_CAPABILITY = "freight_upload"` 对齐。不做 `freight_rpa_upload`(见下方裁决)。 + +**Tech Stack:** Python / Flask;Worker 侧 `onhand_rpa_worker._handle_upload_trigger` 当前不校验 action 字面量,但仍须双侧契约文档一致。 + +**Ruling(2026-10-17):** 否决把 `freight_upload` 改成 `freight_rpa_upload`。理由:心跳能力、lifecycle stage、gate `freight_upload_rpa` 已广泛使用 `freight_upload`;`freight_rpa_*` 是包/表/env 命名空间,action 用短动词与 `onhand_export`/`inbound_export` 同形。改成 `freight_rpa_upload` 会制造第三套词根且波及 shipping_notice 生命周期契约,超出本纠偏。 + +**Spec 权威:** `docs/superpowers/specs/2026-10-16-freight-rpa-decouple-and-rename-design.md`(upload action 对齐 freight_upload)+ `docs/features/freight-rpa/GLOSSARY.md` Upload 条。 + +--- + +## File map + +| File | Responsibility | +| --- | --- | +| `backend/app/services/freight_rpa/upload/trigger_io.py` | 常量 + 写入 action | +| `backend/tests/services/freight_rpa/**`(若已有 upload 契约测)或新建最小单测 | 断言 action/schema | +| `docs/features/freight-rpa/GLOSSARY.md` / cutover-runbook / batch-R 勘误 | 已就地写明;本计划只确认代码落地 | + +--- + +### Task 1: upload action → `freight_upload` + +**Files:** +- Modify: `backend/app/services/freight_rpa/upload/trigger_io.py` +- Modify or create: focused test under `backend/tests/services/freight_rpa/`(优先改既有;无则新建 `test_upload_trigger_contract.py`) + +- [ ] **Step 1: 写失败测试** + +断言 `ACTION_*`(或写入 trigger 后读出的 `action`)等于 `"freight_upload"`,`schema_version` 等于 `"freight_rpa.upload.v1"`。禁止再出现 `outbound_upload` / `shipment_upload`。 + +- [ ] **Step 2: 跑测确认失败** + +```bash +cd backend && python -m pytest tests/services/freight_rpa/ -k upload -q +``` + +Expected: 失败(当前常量仍是 outbound_upload)或新增测未发现常量。 + +- [ ] **Step 3: 改常量与注释** + +- 将 `ACTION_OUTBOUND_UPLOAD = "outbound_upload"` 改为 `ACTION_FREIGHT_UPLOAD = "freight_upload"` +- 更新所有引用 +- 文件头 docstring:说明 action 对齐心跳 `freight_upload`;upload 独立域,禁止 outbound_* / shipment_* 作为 upload action +- 禁止引入 `freight_rpa_upload` + +- [ ] **Step 4: 跑测通过** + +```bash +cd backend && python -m pytest tests/services/freight_rpa/ -k upload -q +``` + +另跑: + +```bash +rg -n "outbound_upload|ACTION_OUTBOUND_UPLOAD" backend/app scripts/freight_rpa +``` + +Expected: 代码命中清零(文档勘误「勿用 outbound_upload」可保留)。 + +- [ ] **Step 5: 暂存,不提交** + +`git add` 相关文件;**不要 commit**(等用户批准)。 + +--- + +## Global Constraints + +- 不改 lifecycle / gate / i18n 里的 `freight_upload` 业务词(它们本来就对) +- 不改 `shipment_*` 履约出货命名 +- 不改 `freight_rpa/outbound/` 调拨出站骨架 +- 不做双路由/兼容层 +- 三层注释规范(文件头 + 函数)随改同步 diff --git a/docs/superpowers/plans/2026-10-18-freight-rpa-phase-b.md b/docs/superpowers/plans/2026-10-18-freight-rpa-phase-b.md new file mode 100644 index 00000000..8f0f5794 --- /dev/null +++ b/docs/superpowers/plans/2026-10-18-freight-rpa-phase-b.md @@ -0,0 +1,716 @@ +# Freight RPA 阶段 B 实施计划(报表归属与回调事实) + +> **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:** 在当前 Flask 进程内,让 `freight_rpa` 拥有登录连接、库存站点、在手/入站报表配置和两类报表文件;发货通知与在途调拨只按 `source_code` 读取,并只更新自己的任务。 + +**Architecture:** 批次 S 的未执行迁移已经把解析方案表落到 `freight_rpa_parsing_profiles`,本计划不再写第二条改名。新迁移 `s18` 挂在 `s17c` 之后:新建 `freight_rpa_onhand_report_configs` 并搬走站点上的三列,再把 `shipping_onhand_files` 改名为 `freight_rpa_onhand_report_files`(列不动)。回调在 RPA 事务提交文件之后,用 `ReportFact` 调用已注册处理函数;处理函数失败不回滚文件。不引入队列,不拆第二个服务。 + +**Tech Stack:** Flask、SQLAlchemy 2.0、Alembic、Vue 3 + TypeScript、pytest。Python 用 `backend/.venv/Scripts/python.exe`,命令在 `backend/` 下执行。 + +**Spec:** `docs/superpowers/specs/2026-10-18-freight-rpa-phase-b-design.md` + +## Global Constraints + +- 不把 `freight_rpa` 拆成第二个可部署服务,不引入消息队列。 +- 不新做出站抓取。出站配置和出站文件表等出站立项再加,命名与在手、入站相同。 +- 不把履约出货改名为 outbound,不改 `freight_upload`。 +- 不改合同付款的 `shipment`(发货款),不改 `movement`,不改历史 MinIO 对象键(含 `shipping/receipt-reports/`)。 +- 不改写已有的阶段 A 计划与 spec。 +- 不改这些仍只服务在手的表:`freight_rpa_onhand_fields`、外部仓库映射、发货路由规则、配置测试。不改它们的表名和归属。 +- 不把在手文件表里的解析行、字段映射、快照状态拆到另一张表。入站文件表只存原文件,两张表的列保持不同。 +- `report_kind` 取值 `onhand`、`inbound`、`outbound`,与解析方案 `purpose` 相同。本阶段实际送达的是 `onhand` 和 `inbound`。 +- 批次 S、D 已在工作区且未提交。本计划的代码继续改在这份工作区上。禁止 `git add -A`。禁止 `git commit`(提交须用户显式批准)。每任务只 `git add` 该任务列出的路径。 +- 解析方案最终表名已经写在未执行的 `s17b` 里。禁止再添加 `freight_rpa_onhand_parsing_profiles` 这个名字。 +- 站点启用规则:已有在手报表配置且其中 `parsing_profile_id` 非空,并且站点 `excel_template_id` 非空。PostgreSQL 的 CHECK 不能跨表,所以模板仍留在站点行的 CHECK 上,解析方案改由保存站点的服务拒绝。 +- 注释:改签名或协作关系时同步文件头和函数 docstring(AGENTS.md §5)。 +- 新增 `error.code` 时补齐 `locales/*/errors.json` 四语言。本计划复用已有码,不新造码,除非某步写明。 + +## 文件地图 + +| 路径 | 职责 | +| --- | --- | +| `backend/migrations/versions/s18d1e2f3a4b5_freight_rpa_phase_b_report_ownership.py` | 新建在手配置表、搬三列、改在手文件表名、downgrade | +| `backend/app/models/shipping_onhand_config.py` | 站点去掉三列;新增 `ShippingOnhandReportConfig` | +| `backend/app/models/shipping.py` | `ShippingOnhandFile.__tablename__` 改为 `freight_rpa_onhand_report_files` | +| `backend/app/services/freight_rpa/reports/facts.py` | `ReportFact` 与取值校验 | +| `backend/app/services/freight_rpa/reports/queries.py` | 按 `source_code` / `file_id` 的只读查询,以及入站解析结果标记 | +| `backend/app/services/freight_rpa/reports/dispatch.py` | 提交后调用处理函数;未注册则 `FREIGHT_RPA.SINK_NOT_REGISTERED` | +| `backend/app/services/freight_rpa/common/report_audit.py` | 写既有 `ShippingAuditEvent`,替代对 `shipping_notice.audit_service` 的 import | +| `backend/app/services/freight_rpa/onhand/report_store.py` | 在手报表行的插入与更新(含解析列) | +| `backend/app/services/in_transit_transfer/inbound_report_handler.py` | inbound 事实只推进 `TransferSourceJob` | +| `backend/app/services/shipping_notice/onhand_report_handler.py` | onhand 事实只更新发货门禁、候选和任务关联 | +| `docs/adr/0004-freight-rpa-report-ownership.md` | 阶段 B 归属决策 | +| `docs/features/freight-rpa/GLOSSARY.md` | 站点归属改为 RPA | + +--- + +### Task 1: 迁移在手配置表与在手文件表名 + +**Files:** +- Create: `backend/migrations/versions/s18d1e2f3a4b5_freight_rpa_phase_b_report_ownership.py` +- Modify: `backend/app/models/shipping_onhand_config.py` +- Modify: `backend/app/models/shipping.py`(`ShippingOnhandFile.__tablename__` 与指向 `shipping_onhand_files` 的 `ForeignKey`) +- Modify: `backend/app/models/__init__.py`(导出 `ShippingOnhandReportConfig`) +- Modify: 下列文件里的 `ForeignKey('shipping_onhand_files.id')` 改为 `ForeignKey('freight_rpa_onhand_report_files.id')`:`shipping_onhand_mapping.py`、`shipping_excel_template.py`、`shipping_onhand_preparation.py`、`shipping_notice_line_onhand_match.py` +- Test: `backend/tests/test_migration_s18_phase_b_report_ownership.py` + +**Interfaces:** +- Consumes: 批次 S 之后库上已有 `freight_rpa_sources.report_path_json`、`query_parameters_json`、`parsing_profile_id`,以及表 `shipping_onhand_files`。`s17b` 的解析方案目标名已是 `freight_rpa_parsing_profiles`。 +- Produces: 表 `freight_rpa_onhand_report_configs`(列:`id`、`source_id` 唯一、`parsing_profile_id` 可空、`report_path_json` JSON 非空、`query_parameters_json` JSON 非空、`config_version` int 默认 1、`created_by`、`updated_by`、`created_at`、`updated_at`)。站点行不再有那三列。`ck_freight_rpa_sources_enabled_bindings` 换成 `ck_freight_rpa_sources_enabled_template`,表达式 `enabled = false OR excel_template_id IS NOT NULL`。模型类 `ShippingOnhandReportConfig`,关系 `ShippingOnhandSource.onhand_report_config`(`uselist=False`)。`ShippingOnhandFile.__tablename__ == 'freight_rpa_onhand_report_files'`,列与改名前相同。 + +- [ ] **Step 1: 写失败测试** + +`backend/tests/test_migration_s18_phase_b_report_ownership.py` 沿用 `tests/test_migration_s17_batch_s_rename.py` 的 `_load` + SQLite `Operations` 手法。测试不从迁移模块读取期望表名。 + +```python +def test_s18_revision_follows_s17c(): + migration = _load("s18d1e2f3a4b5_freight_rpa_phase_b_report_ownership.py") + assert migration.revision == "s18d1e2f3a4b5" + assert migration.down_revision == "s17c2d3e4f5a6" + + +def test_s17b_parsing_profile_target_is_final_name(): + s17b = _load("s17b1c2d3e4f5a_freight_rpa_batch_s_rename_tables.py") + assert ("shipping_inventory_parsing_profiles", "freight_rpa_parsing_profiles") in s17b._TABLE_RENAMES + assert "freight_rpa_onhand_parsing_profiles" not in str(s17b._TABLE_RENAMES) + + +def test_s18_upgrade_moves_onhand_config_and_renames_files_then_downgrade_restores(op): + # op fixture:内存 SQLite,先跑 s17b.upgrade 再跑 s17c.upgrade(或桩出 s17c 之后的两张表)。 + # 桩站点一行:source_code='DSV',report_path_json={'menu':'onhand'}, + # query_parameters_json=[{'name':'wh'}],parsing_profile_id=1,excel_template_id=9。 + # 桩 shipping_onhand_files 一行:id=7,onhand_lines_json=[{'sku':'A'}],snapshot_status='ready'。 + migration = _load("s18d1e2f3a4b5_freight_rpa_phase_b_report_ownership.py") + migration.upgrade() + config_cols = _column_names(op, "freight_rpa_onhand_report_configs") + assert {"source_id", "report_path_json", "query_parameters_json", "parsing_profile_id"} <= set(config_cols) + source_cols = _column_names(op, "freight_rpa_sources") + assert "report_path_json" not in source_cols + assert "parsing_profile_id" not in source_cols + assert "source_code" in source_cols + file_cols = _column_names(op, "freight_rpa_onhand_report_files") + assert "onhand_lines_json" in file_cols + assert "snapshot_status" in file_cols + row = op.get_bind().exec_driver_sql( + "SELECT report_path_json, parsing_profile_id FROM freight_rpa_onhand_report_configs" + ).one() + assert row.parsing_profile_id == 1 + migration.downgrade() + assert "report_path_json" in _column_names(op, "freight_rpa_sources") + assert "onhand_lines_json" in _column_names(op, "shipping_onhand_files") + assert "freight_rpa_onhand_parsing_profiles" not in _table_names(op) +``` + +- [ ] **Step 2: 跑测试确认失败** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/test_migration_s18_phase_b_report_ownership.py -q` + +Expected: FAIL,迁移文件不存在。 + +- [ ] **Step 3: 写迁移与模型** + +`revision = "s18d1e2f3a4b5"`,`down_revision = "s17c2d3e4f5a6"`。 + +upgrade 顺序: + +1. `op.create_table('freight_rpa_onhand_report_configs', ...)`,`UniqueConstraint('source_id', name='uq_freight_rpa_onhand_report_configs_source')`,`source_id` 外键 `freight_rpa_sources.id` `ondelete='CASCADE'`,`parsing_profile_id` 外键 `freight_rpa_parsing_profiles.id`。 +2. `INSERT INTO freight_rpa_onhand_report_configs (source_id, report_path_json, query_parameters_json, parsing_profile_id, config_version, created_at, updated_at) SELECT id, report_path_json, query_parameters_json, parsing_profile_id, config_version, created_at, updated_at FROM freight_rpa_sources`。 +3. `op.drop_constraint('ck_freight_rpa_sources_enabled_bindings', 'freight_rpa_sources', type_='check')`。若库上的历史约束名仍是改名前的名字,用反射按「定义里同时含 `parsing_profile_id` 与 `excel_template_id`」找到那一条再删。 +4. 删掉站点上的 `report_path_json`、`query_parameters_json`、`parsing_profile_id`。 +5. `op.create_check_constraint('ck_freight_rpa_sources_enabled_template', 'freight_rpa_sources', 'enabled = false OR excel_template_id IS NOT NULL')`。 +6. `op.rename_table('shipping_onhand_files', 'freight_rpa_onhand_report_files')`。然后复用 `s17b` 里「对象名包含旧表名则替换」的扫描,旧串 `shipping_onhand_files`,新串 `freight_rpa_onhand_report_files`。新名超过 63 字符时沿用 `s17b` 的截断函数。列名不改。 + +downgrade 相反:文件表改回 `shipping_onhand_files`,把三列加回 `freight_rpa_sources`,从配置表 `UPDATE` 回去,丢掉配置表,恢复 `ck_freight_rpa_sources_enabled_bindings` 原文 `enabled = false OR (parsing_profile_id IS NOT NULL AND excel_template_id IS NOT NULL)`。 + +模型:`ShippingOnhandSource` 删除三列与 `parsing_profile` 关系;启用 CHECK 改为模板那条。新增 `ShippingOnhandReportConfig`,字段与上表一致,`inventory_source` 关系命名与入站配置的 `ShippingInboundReportConfig` 相同风格。`ShippingParsingProfile.sources` 改为指向配置行。`ShippingOnhandFile.__tablename__ = 'freight_rpa_onhand_report_files'`。文件头写明:在手文件表归 RPA,列仍含解析行与快照状态。 + +- [ ] **Step 4: 跑测试确认通过** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/test_migration_s18_phase_b_report_ownership.py tests/test_migration_s17_batch_s_rename.py -q` + +Expected: PASS。 + +- [ ] **Step 5: 只暂存本任务路径** + +```powershell +git add backend/migrations/versions/s18d1e2f3a4b5_freight_rpa_phase_b_report_ownership.py backend/tests/test_migration_s18_phase_b_report_ownership.py backend/app/models/shipping_onhand_config.py backend/app/models/shipping.py backend/app/models/__init__.py backend/app/models/shipping_onhand_mapping.py backend/app/models/shipping_excel_template.py backend/app/models/shipping_onhand_preparation.py backend/app/models/shipping_notice_line_onhand_match.py +``` + +--- + +### Task 2: 站点启用与管理端改读写在手配置 + +**Files:** +- Modify: `backend/app/services/admin/shipping_onhand_admin_service.py` +- Modify: `frontend/src/features/admin/modules/freight-rpa/FreightRpaPage.vue`(库存报表配置卡片的绑定字段) +- Test: `backend/tests/test_admin_freight_rpa_onhand_config.py` + +**Interfaces:** +- Consumes: `ShippingOnhandReportConfig`,站点行上的 `excel_template_id`、`enabled`。 +- Produces: `assert_onhand_source_can_enable(source: ShippingOnhandSource) -> None`。`enabled` 为真且缺少配置、或配置的 `parsing_profile_id` 为空、或 `excel_template_id` 为空时抛 `ValidationError(code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')`。站点 DTO 不再带 `report_path_json` / `query_parameters_json` / `parsing_profile_id`;改为 `onhand_report_config: { id, report_path_json, query_parameters_json, parsing_profile_id } | null`。保存在手配置的函数 `save_onhand_report_config(source_id: int, data: dict, actor_id: int | None) -> dict`,没有配置行时插入,有则更新,并递增该行的 `config_version`。 + +- [ ] **Step 1: 写失败测试** + +```python +def test_enabled_source_requires_onhand_profile_and_template(app, db_session): + source = _source(enabled=True, excel_template_id=None) + db_session.add(source) + db_session.commit() + with pytest.raises(ValidationError) as exc: + assert_onhand_source_can_enable(source) + assert exc.value.code == "SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED" + + +def test_save_onhand_report_config_does_not_write_source_columns(app, db_session): + source = _source(enabled=False, excel_template_id=9) + db_session.add(source) + db_session.commit() + save_onhand_report_config(source.id, { + "report_path_json": {"menu": "stock"}, + "query_parameters_json": [], + "parsing_profile_id": _published_onhand_profile_id(), + }, actor_id=1) + db_session.refresh(source) + assert not hasattr(source, "report_path_json") + config = ShippingOnhandReportConfig.query.filter_by(source_id=source.id).one() + assert config.report_path_json == {"menu": "stock"} + assert config.parsing_profile.purpose == "onhand" +``` + +`parsing_profile.purpose` 不是 `onhand` 时,`save_onhand_report_config` 抛 `ValidationError(code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')`。入站配置的保存函数保持只接受 `purpose='inbound'`。 + +- [ ] **Step 2: 跑测试确认失败** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/test_admin_freight_rpa_onhand_config.py -q` + +Expected: FAIL,`assert_onhand_source_can_enable` 未定义。 + +- [ ] **Step 3: 改服务与页面** + +`shipping_onhand_admin_service.py` 里现在写 `source.report_path_json`、`source.query_parameters_json`、`source.parsing_profile_id` 的分支改写配置行。解析方案绑定审计仍写 `freight_rpa_onhand_source_parsing_binding_audits`,`parsing_profile_id` 取自配置行。`FreightRpaPage.vue` 的库存报表配置卡片改绑 `onhand_report_config` 的三个字段;收料卡片继续绑入站配置。站点头部仍编辑 `source_code`、`display_name`、`connector_type`、`rpa_profile_id`、`excel_template_id`、仓库模式。不新增文案。 + +触发抓取读路径的同一任务内改完,否则管理端能存、排程仍读已删除的列: + +- `backend/app/services/shipping_notice/onhand_trigger_batch.py`:`report_path_json` / `query_parameters_json` / `parsing_profile_id` 从 `source.onhand_report_config` 取。配置缺失则沿用现有「站点未就绪」错误,不新造码。 +- `backend/app/services/freight_rpa/onhand/trigger_io.py` 若直接读这三列,同样改读配置。 + +- [ ] **Step 4: 跑测试确认通过** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/test_admin_freight_rpa_onhand_config.py tests/test_admin_freight_rpa_routes.py -q` + +Expected: PASS。 + +- [ ] **Step 5: 只暂存本任务路径** + +```powershell +git add backend/app/services/admin/shipping_onhand_admin_service.py backend/app/services/shipping_notice/onhand_trigger_batch.py backend/app/services/freight_rpa/onhand/trigger_io.py frontend/src/features/admin/modules/freight-rpa/FreightRpaPage.vue backend/tests/test_admin_freight_rpa_onhand_config.py +``` + +--- + +### Task 3: 报表只读查询 + +**Files:** +- Create: `backend/app/services/freight_rpa/reports/__init__.py` +- Create: `backend/app/services/freight_rpa/reports/facts.py` +- Create: `backend/app/services/freight_rpa/reports/queries.py` +- Test: `backend/tests/services/freight_rpa/test_report_queries.py` + +**Interfaces:** +- Consumes: `ShippingOnhandSource`、`ShippingOnhandReportConfig`、`ShippingInboundReportConfig`、`ShippingInboundReportFile`、`ShippingOnhandFile`、`usable_inbound_file_condition()`(现位于 `in_transit_transfer/inbound_file_gate.py`,本任务把可用条件的过滤表达式复制进 `queries.py`,门禁模块下一步改为调用这里,避免 `freight_rpa` import `in_transit_transfer`)。 +- Produces: + +```python +@dataclass(frozen=True) +class ReportFact: + report_kind: str + source_code: str + file_id: int | None + sha256: str | None + ok: bool + error_code: str | None = None + error_message: str | None = None + +def require_report_kind(value: str) -> str: + """只接受 onhand、inbound、outbound。其他值抛 ValidationError(code='SHIPPING.RECEIPT_CALLBACK_INVALID')。""" + +@dataclass(frozen=True) +class SiteView: + source_code: str + display_name: str + connector_type: str + excel_template_id: int | None + enabled: bool + +@dataclass(frozen=True) +class OnhandConfigView: + report_path_json: dict + query_parameters_json: list + parsing_profile_id: int | None + +@dataclass(frozen=True) +class InboundConfigView: + report_path_json: dict + query_parameters_json: list + parsing_profile_id: int | None + +@dataclass(frozen=True) +class InboundFileView: + file_id: int + source_code: str + sha256: str + storage_key: str + original_filename: str + created_at: datetime + +def get_site(source_code: str) -> SiteView | None: ... +def get_onhand_config(source_code: str) -> OnhandConfigView | None: ... +def get_inbound_config(source_code: str) -> InboundConfigView | None: ... +def latest_usable_inbound_file(source_code: str) -> InboundFileView | None: ... +def read_inbound_file_bytes(file_id: int) -> bytes: ... +def mark_inbound_parse_failure(file_id: int, *, error_code: str, error_message: str) -> None: ... +def clear_inbound_parse_failure(file_id: int) -> None: ... +``` + +`latest_usable_inbound_file` 的过滤与今天 `matching_service._latest_usable_report_file` 相同:经 unit run 的 `source_code`,未删除、未过期、按 `created_at`/`id` 倒序第一条。`read_inbound_file_bytes` 用现有 `file_asset_storage` 按 `storage_key` 读取。找不到文件抛 `NotFoundError`。 + +- [ ] **Step 1: 写失败测试** + +```python +def test_latest_usable_inbound_file_returns_newest(app, db_session): + older = _inbound_file(source_code="DSV", sha256="a" * 64, created_at=datetime(2026, 10, 1)) + newer = _inbound_file(source_code="DSV", sha256="b" * 64, created_at=datetime(2026, 10, 2)) + db_session.add_all([older, newer]) + db_session.commit() + view = latest_usable_inbound_file("DSV") + assert view is not None + assert view.file_id == newer.id + assert view.sha256 == "b" * 64 + + +def test_report_kind_rejects_shipment(): + with pytest.raises(ValidationError): + require_report_kind("shipment") + assert require_report_kind("outbound") == "outbound" +``` + +- [ ] **Step 2: 跑测试确认失败** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/freight_rpa/test_report_queries.py -q` + +Expected: FAIL,模块不存在。 + +- [ ] **Step 3: 实现查询模块** + +文件头写明:本模块是发货与调拨读报表的唯一入口;不 import `shipping_notice` 或 `in_transit_transfer`。`mark_inbound_parse_failure` 只更新 `parse_failed_at`、`parse_error_code`、`parse_error_message` 后 `flush`,不 `commit`(调用方处于自己的事务)。 + +- [ ] **Step 4: 跑测试确认通过** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/freight_rpa/test_report_queries.py -q` + +Expected: PASS。 + +- [ ] **Step 5: 只暂存本任务路径** + +```powershell +git add backend/app/services/freight_rpa/reports backend/tests/services/freight_rpa/test_report_queries.py +``` + +--- + +### Task 4: 在途调拨改为只读函数 + +**Files:** +- Modify: `backend/app/services/in_transit_transfer/matching_service.py` +- Modify: `backend/app/services/in_transit_transfer/movement_file_repository.py` +- Modify: `backend/app/services/in_transit_transfer/source_file_status.py` +- Modify: `backend/app/services/in_transit_transfer/inbound_file_gate.py` +- Modify: `backend/app/services/in_transit_transfer/inbound_trigger_service.py` +- Modify: `backend/app/services/in_transit_transfer/backlog_reparse_service.py` +- Modify: `backend/app/services/in_transit_transfer/deps.py` +- Modify: `backend/app/services/in_transit_transfer/evidence_sync.py`(它经 `_latest_usable_report_file` 取文件) +- Test: `backend/tests/services/in_transit_transfer/test_inbound_report_read_boundary.py` + +**Interfaces:** +- Consumes: Task 3 的 `latest_usable_inbound_file`、`read_inbound_file_bytes`、`get_inbound_config`、`get_site`、`mark_inbound_parse_failure`、`clear_inbound_parse_failure`。 +- Produces: 上述文件不再出现 `from app.models import ShippingInboundReportFile` 或 `ShippingInboundReportConfig` 或 `ShippingOnhandSource`。`matching_service._latest_usable_report_file` 删除,调用处改为 `latest_usable_inbound_file`。解析失败标记改为 `mark_inbound_parse_failure(file_id=...)`。 + +- [ ] **Step 1: 写失败测试** + +```python +def test_in_transit_does_not_import_rpa_report_models(): + root = Path(__file__).resolve().parents[3] / "app" / "services" / "in_transit_transfer" + banned = ("ShippingInboundReportFile", "ShippingInboundReportConfig", "ShippingOnhandSource", "ShippingOnhandReportConfig") + hits = [] + for path in root.rglob("*.py"): + text = path.read_text(encoding="utf-8") + for name in banned: + if name in text: + hits.append(f"{path.name}: {name}") + assert hits == [] +``` + +- [ ] **Step 2: 跑测试确认失败** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_inbound_report_read_boundary.py -q` + +Expected: FAIL,列出 `matching_service.py` 等文件。 + +- [ ] **Step 3: 替换查询** + +`matching_service` 里原 `_latest_usable_report_file` 的调用改为: + +```python +from app.services.freight_rpa.reports.queries import latest_usable_inbound_file, read_inbound_file_bytes + +view = latest_usable_inbound_file(source_code) +if view is None: + return None +payload = read_inbound_file_bytes(view.file_id) +``` + +后续只用 `view.file_id`、`view.sha256`、`view.created_at`。`source_file_status.py` 的写标记改为 `mark_inbound_parse_failure` / `clear_inbound_parse_failure`。`inbound_trigger_service.py` 读站点与入站配置改为 `get_site` / `get_inbound_config`。`inbound_file_gate.py` 若只剩过滤表达式,改为从 `queries.py` 引用,自身不再 import 模型。 + +- [ ] **Step 4: 跑测试确认通过** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_inbound_report_read_boundary.py tests/services/in_transit_transfer -q` + +Expected: PASS。既有匹配测试仍绿。 + +- [ ] **Step 5: 只暂存本任务路径** + +```powershell +git add backend/app/services/in_transit_transfer backend/tests/services/in_transit_transfer/test_inbound_report_read_boundary.py +``` + +--- + +### Task 5: 发货通知改为只读函数,在手文件写入收进 RPA + +**Files:** +- Create: `backend/app/services/freight_rpa/onhand/report_store.py` +- Modify: `backend/app/services/shipping_notice/onhand_snapshot_store.py`(`create_inventory_snapshot_from_rpa`、`create_empty_rpa_inventory_snapshot`、`get_or_create_rpa_inventory_snapshot` 改为调用 report_store,不再自己 `ShippingOnhandFile(...)`) +- Modify: `backend/app/services/shipping_notice/onhand_file_store.py`(`save_task_inventory_upload` 的插入改为调用 report_store) +- Modify: 仍直接构造或查询 `ShippingOnhandFile` / `ShippingInboundReportConfig` 的发货模块:`onhand_rpa_workflow.py`、`onhand_source_repository.py`、`inbound_report_access.py`、`query_service.py` +- Test: `backend/tests/services/shipping_notice/test_report_model_boundary.py` + +**Interfaces:** +- Consumes: Task 3 的查询函数。`ShippingOnhandFile` 列集合不变。 +- Produces: + +```python +def insert_onhand_report(**columns: Any) -> int: + """插入 freight_rpa_onhand_report_files 一行并 flush。返回 file_id。不创建任务关联,不 commit。""" + +def update_onhand_report(file_id: int, **columns: Any) -> None: + """按 file_id 更新该行的给定列并 flush。不 commit。""" +``` + +发货侧可以继续更新 `shipping_task_onhand_links`、候选集、行匹配、核验。禁止再 `db.session.add(ShippingOnhandFile(...))`。 + +- [ ] **Step 1: 写失败测试** + +```python +def test_shipping_notice_does_not_construct_rpa_report_rows(): + root = Path(__file__).resolve().parents[3] / "app" / "services" / "shipping_notice" + banned_snippets = ("ShippingOnhandFile(", "ShippingInboundReportFile(", "ShippingInboundReportConfig(") + hits = [] + for path in root.rglob("*.py"): + text = path.read_text(encoding="utf-8") + for snippet in banned_snippets: + if snippet in text: + hits.append(f"{path.name}: {snippet}") + assert hits == [] +``` + +- [ ] **Step 2: 跑测试确认失败** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/shipping_notice/test_report_model_boundary.py -q` + +Expected: FAIL,命中 `onhand_file_store.py` 与 `onhand_snapshot_store.py`。 + +- [ ] **Step 3: 挪走插入** + +`report_store.insert_onhand_report` 接收今天 `ShippingOnhandFile(...)` 已有的列关键字(`storage_path`、`file_sha256`、`onhand_lines_json`、`field_mapping_json`、`snapshot_status`、`warehouse_id`、`source_code`、`rpa_run_no` 等),不增列。`onhand_snapshot_store.create_inventory_snapshot_from_rpa` 在得到 `file_id` 之后仍调用现有的 `link_snapshot_to_task`,关联表留在发货域。查询改用 `get_onhand_config` / `get_site`。`inbound_report_access.py` 的下载改 `read_inbound_file_bytes`。 + +- [ ] **Step 4: 跑测试确认通过** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/shipping_notice/test_report_model_boundary.py tests/test_freight_rpa_batch_s_grep_gate.py -q` + +Expected: PASS。 + +- [ ] **Step 5: 只暂存本任务路径** + +```powershell +git add backend/app/services/freight_rpa/onhand/report_store.py backend/app/services/shipping_notice/onhand_snapshot_store.py backend/app/services/shipping_notice/onhand_file_store.py backend/app/services/shipping_notice/onhand_rpa_workflow.py backend/app/services/shipping_notice/onhand_source_repository.py backend/app/services/shipping_notice/inbound_report_access.py backend/app/services/shipping_notice/query_service.py backend/tests/services/shipping_notice/test_report_model_boundary.py +``` + +--- + +### Task 6: 回调先提交文件,再投递事实 + +**Files:** +- Create: `backend/app/services/freight_rpa/reports/dispatch.py` +- Create: `backend/app/services/freight_rpa/common/report_audit.py` +- Modify: `backend/app/services/freight_rpa/inbound/report_archive.py` +- Modify: `backend/app/services/freight_rpa/common/callback_sinks.py`(文件头说明文件就绪走 `dispatch_report_fact`,进度类 kind 仍走 `dispatch_sink`) +- Modify: `backend/tests/services/freight_rpa/test_import_boundary.py` +- Test: `backend/tests/services/freight_rpa/test_report_fact_dispatch.py` + +**Interfaces:** +- Consumes: `ReportFact`、`register_sink` 的未注册错误码 `FREIGHT_RPA.SINK_NOT_REGISTERED`(http 404)。 +- Produces: + +```python +Handler = Callable[[ReportFact], None] + +def register_report_handler(report_kind: str, handler: Handler) -> None: ... + +def dispatch_report_fact(fact: ReportFact) -> None: + """kind 无处理函数时抛 AppError(code='FREIGHT_RPA.SINK_NOT_REGISTERED', http_status=404)。 + 本函数不 commit、不 rollback。""" +``` + +`ingest_inbound_callback` 去掉 `on_terminal` 参数。每个终态分支在 `db.session.commit()` 之后构造 `ReportFact(report_kind='inbound', source_code=unit.source_code, file_id=..., sha256=..., ok=..., error_code=..., error_message=...)` 并调用 `dispatch_report_fact`。同一 `unit_run_id + sha256` 已有文件时不插入第二行,仍投递 `ok=True` 的事实(供处理函数重试)。处理函数抛出的异常原样向外抛,不包一层日志后吞掉。 + +`append_shipping_audit_event(...)` 的调用改为 `report_audit.append_rpa_report_event(...)`,关键字与现函数相同,内部写入同一个 `ShippingAuditEvent` 模型(允许 import 模型,禁止 import `app.services.shipping_notice.audit_service`)。事件名字符串保持 `shipping_inbound_rpa_callback_received` 与 `shipping_inbound_report_archived`,避免审计查询断档。 + +`test_import_boundary.py` 的 `ALLOWED_SHIPPING_NOTICE` 改为空集。`file_assets` 那条白名单一并删除(包内已经不引用它)。 + +- [ ] **Step 1: 写失败测试** + +```python +def test_handler_failure_keeps_committed_file(app, db_session, monkeypatch): + unit = _awaiting_unit(source_code="DSV") + db_session.add(unit) + db_session.commit() + + def boom(fact: ReportFact) -> None: + raise RuntimeError("handler down") + + register_report_handler("inbound", boom) + with pytest.raises(RuntimeError, match="handler down"): + ingest_inbound_callback(_success_payload(unit, sha256_file=b"abc")) + assert ShippingInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1 + + +def test_second_delivery_does_not_insert_another_file(app, db_session): + seen: list[ReportFact] = [] + register_report_handler("inbound", seen.append) + unit = _awaiting_unit(source_code="DSV") + db_session.add(unit) + db_session.commit() + payload = _success_payload(unit, sha256_file=b"abc") + ingest_inbound_callback(payload) + ingest_inbound_callback(payload) + assert ShippingInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1 + assert [fact.file_id for fact in seen] == [seen[0].file_id, seen[0].file_id] + + +def test_missing_handler_raises_sink_not_registered(app, db_session): + unit = _awaiting_unit(source_code="DSV") + db_session.add(unit) + db_session.commit() + with pytest.raises(AppError) as exc: + ingest_inbound_callback(_success_payload(unit, sha256_file=b"abc")) + assert exc.value.code == "FREIGHT_RPA.SINK_NOT_REGISTERED" + assert ShippingInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1 +``` + +- [ ] **Step 2: 跑测试确认失败** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/freight_rpa/test_report_fact_dispatch.py -q` + +Expected: FAIL,`ingest_inbound_callback` 仍要求 `on_terminal`。 + +- [ ] **Step 3: 改归档与审计** + +非法载荷、单元不存在、配置缺失维持现有 4xx(`SHIPPING.RECEIPT_CALLBACK_INVALID`、`SHIPPING.RECEIPT_UNIT_NOT_FOUND`),在 `commit` 之前抛出,不调用 `dispatch_report_fact`。落 MinIO 或插行失败时事务回滚,同样不投递。`freight_upload` 的 trigger 与回调文件不改。 + +- [ ] **Step 4: 跑测试确认通过** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/freight_rpa/test_report_fact_dispatch.py tests/services/freight_rpa/test_import_boundary.py tests/test_freight_receipt_rpa_callback.py -q` + +Expected: PASS。旧回调测试里若仍向 `ingest_inbound_callback` 传 `on_terminal=`,改成注册 `register_report_handler`。 + +- [ ] **Step 5: 只暂存本任务路径** + +```powershell +git add backend/app/services/freight_rpa/reports/dispatch.py backend/app/services/freight_rpa/common/report_audit.py backend/app/services/freight_rpa/inbound/report_archive.py backend/app/services/freight_rpa/common/callback_sinks.py backend/tests/services/freight_rpa/test_report_fact_dispatch.py backend/tests/services/freight_rpa/test_import_boundary.py backend/tests/test_freight_receipt_rpa_callback.py +``` + +--- + +### Task 7: 业务处理函数只改自己的任务 + +**Files:** +- Create: `backend/app/services/in_transit_transfer/inbound_report_handler.py` +- Create: `backend/app/services/shipping_notice/onhand_report_handler.py` +- Modify: `backend/app/services/shipping_notice/rpa_sinks.py` +- Modify: `backend/app/services/shipping_notice/inbound_report_storage.py`(去掉吞掉异常的 `_advance_transfer_source_job`;终态推进改由调拨处理函数承担) +- Modify: `backend/app/__init__.py`(`register_onhand_sinks` / `register_inbound_sinks` 里增加 `register_report_handler`) +- Modify: `backend/app/services/in_transit_transfer/inbound_callback_bridge.py`(`advance_source_job_from_inbound_callback` 保持只更新 `status='waiting_rpa_callback'` 的行) +- Test: `backend/tests/services/in_transit_transfer/test_inbound_report_handler.py` + +**Interfaces:** +- Consumes: `ReportFact`、`advance_source_job_from_inbound_callback`、`register_report_handler`。 +- Produces: + +```python +def handle_inbound_report(fact: ReportFact) -> None: + """report_kind 必须是 inbound。ok 且 file_id 有值时把等待中的 TransferSourceJob 推进到 file_ready; + ok 为假时推进到 failed。没有 waiting_rpa_callback 行则 return。第二次调用时该行已离开等待态,不再改。""" + +def handle_onhand_report(fact: ReportFact) -> None: + """report_kind 必须是 onhand。用 fact.file_id 更新发货门禁与候选。不写 TransferSourceJob。 + 不插入 freight_rpa_onhand_report_files。""" +``` + +`register_inbound_sinks` 调用 `register_report_handler('inbound', handle_inbound_report)`。`register_onhand_sinks` 调用 `register_report_handler('onhand', handle_onhand_report)`。进度类 sink(`inbound-unit-progress`、`onhand-batch-claimed` 等)仍走 `register_sink`,不改 envelope。 + +在手回调 `rpa_report_inventory` / `rpa_report_inventory_batch`:先 `insert_onhand_report` 或 `update_onhand_report`,`db.session.commit()`,再 `dispatch_report_fact(ReportFact(report_kind='onhand', ...))`。处理函数抛错时文件行还在。 + +证据同步 `sync_and_commit_for_callback` 改由 `handle_inbound_report` 在推进 `file_ready` 之后调用。它抛错时文件已提交,异常继续向外抛,供 Worker 重试。排程终态 `finalize_receipt_schedule_run_if_complete` 仍由该处理函数在调拨推进之后调用;函数本身在 `schedule` 包,`freight_rpa` 不 import 它。 + +- [ ] **Step 1: 写失败测试** + +```python +def test_unregistered_transfer_handler_leaves_job_waiting(app, db_session): + job = _waiting_job(source_code="DSV") + db_session.add(job) + db_session.commit() + # 不注册 handle_inbound_report + with pytest.raises(AppError) as exc: + ingest_inbound_callback(_success_payload_for("DSV")) + assert exc.value.code == "FREIGHT_RPA.SINK_NOT_REGISTERED" + db_session.refresh(job) + assert job.status == "waiting_rpa_callback" + + +def test_handler_fail_then_success_advances_once(app, db_session, monkeypatch): + job = _waiting_job(source_code="DSV") + db_session.add(job) + db_session.commit() + calls = {"n": 0} + + def flaky(fact: ReportFact) -> None: + calls["n"] += 1 + if calls["n"] == 1: + raise RuntimeError("once") + handle_inbound_report(fact) + + register_report_handler("inbound", flaky) + payload = _success_payload_for("DSV") + with pytest.raises(RuntimeError): + ingest_inbound_callback(payload) + ingest_inbound_callback(payload) + db_session.refresh(job) + assert job.status == "file_ready" + assert ShippingInboundReportFile.query.count() == 1 + + +def test_no_waiting_job_is_success(app, db_session): + register_report_handler("inbound", handle_inbound_report) + ingest_inbound_callback(_success_payload_for("DSV")) + assert TransferSourceJob.query.filter_by(source_code="DSV").count() == 0 +``` + +- [ ] **Step 2: 跑测试确认失败** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_inbound_report_handler.py -q` + +Expected: FAIL,`handle_inbound_report` 未定义。 + +- [ ] **Step 3: 接上两个处理函数** + +`handle_inbound_report` 在 `fact.ok and fact.file_id` 时调用: + +```python +advance_source_job_from_inbound_callback( + source_code=fact.source_code, + file_no=str(fact.file_id), + file_sha256=fact.sha256, + callback_ok=True, +) +``` + +否则 `callback_ok=False`,带上 `fact.error_code` 与 `fact.error_message`。返回 `None` 时直接结束。不要在这里捕获异常。`inbound_report_storage._advance_transfer_source_job` 的 `except Exception: logger.warning` 删除,避免再次把失败吞掉。 + +- [ ] **Step 4: 跑测试确认通过** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_inbound_report_handler.py tests/test_freight_receipt_rpa_callback.py tests/services/freight_rpa/test_import_boundary.py -q` + +Expected: PASS。 + +- [ ] **Step 5: 只暂存本任务路径** + +```powershell +git add backend/app/services/in_transit_transfer/inbound_report_handler.py backend/app/services/shipping_notice/onhand_report_handler.py backend/app/services/shipping_notice/rpa_sinks.py backend/app/services/shipping_notice/inbound_report_storage.py backend/app/__init__.py backend/app/services/in_transit_transfer/inbound_callback_bridge.py backend/tests/services/in_transit_transfer/test_inbound_report_handler.py +``` + +--- + +### Task 8: ADR、术语与切换说明 + +**Files:** +- Create: `docs/adr/0004-freight-rpa-report-ownership.md` +- Modify: `docs/features/freight-rpa/GLOSSARY.md`(站点一条) +- Modify: `docs/features/freight-rpa/cutover-runbook.md` 第 5 节的升级目标 revision +- Modify: `docs/superpowers/specs/2026-10-18-freight-rpa-phase-b-design.md` 状态行改为「已有实施计划」,并加上本计划路径。不改其他段落。 + +**Interfaces:** +- Consumes: 本计划 Task 1–7 的表名与 `ReportFact` 字段。 +- Produces: ADR 记录「同一进程、提交后调用处理函数、无队列」。GLOSSARY 站点句改为归属 `freight_rpa`。Runbook 的 `flask db current` 目标改为 `s18d1e2f3a4b5`,并写明它包含 `s17b`、`s17c`。 + +- [ ] **Step 1: 写 ADR** + +标题:Freight RPA 报表归 RPA,业务方只消费报表事实。 + +正文按 `docs/adr/0002-transfer-type-configuration.md` 的篇幅,写清三句: + +1. 登录连接、站点、在手配置、入站配置、解析方案、在手文件、入站文件由 `freight_rpa` 写入。 +2. 文件在 RPA 事务提交之后,同一次 HTTP 请求调用 `handle_onhand_report` / `handle_inbound_report`。失败返回 5xx,文件保留,Worker 重试。 +3. 不另建服务、不引入消息队列。出站抓取不在本决策内;`report_kind=outbound` 只占位。 + +- [ ] **Step 2: 改 GLOSSARY 与 runbook** + +`GLOSSARY.md` 第 51–52 行改为: + +```markdown +**站点(Source)**: +一个货代抓取目标(如 DSV AWS、Crane NA),持有登录连接与报表配置。表 `freight_rpa_sources` 归属 freight_rpa。发货通知与在途调拨只保存 source_code。 +``` + +`cutover-runbook.md` 第 5 节把 `flask db current` 的期望从 `tt16c7d8e9f0a1b2` 改为 `s18d1e2f3a4b5`。同节加一句:该 revision 依次包含批次 R 的任务键、批次 S 的表改名与枚举、阶段 B 的在手配置表和在手文件表名。冒烟三条链路的文字不改:在手导出、入站导出、履约上传。 + +- [ ] **Step 3: 核对用词** + +在 `docs/adr/0004-freight-rpa-report-ownership.md` 与 `docs/features/freight-rpa/GLOSSARY.md` 中搜索 `归属 shipping_notice`,结果应为空。搜索 `freight_upload`,runbook 的履约上传冒烟仍在。 + +- [ ] **Step 4: 只暂存本任务路径** + +```powershell +git add docs/adr/0004-freight-rpa-report-ownership.md docs/features/freight-rpa/GLOSSARY.md docs/features/freight-rpa/cutover-runbook.md docs/superpowers/specs/2026-10-18-freight-rpa-phase-b-design.md +``` + +--- + +## 自检 + +| 设计条款 | 任务 | +| --- | --- | +| 在手配置表,三列搬离站点 | Task 1、Task 2 | +| 解析方案表名在 s17b,库上不出现 `freight_rpa_onhand_parsing_profiles` | Task 1 测试 | +| 在手文件只改表名 | Task 1 | +| 启用规则换检查位置 | Task 2 | +| 只读函数:站点、配置、最新入站文件、按 file_id 读内容 | Task 3、Task 4、Task 5 | +| 调拨与发货不再为查询 import 报表模型 | Task 4、Task 5 的门禁测试 | +| 回调事实含 outbound 取值;本阶段投递 onhand 与 inbound | Task 3、Task 6、Task 7 | +| 未注册处理函数、重复回调、失败后再成功 | Task 6、Task 7 | +| 文件提交不依赖处理函数 | Task 6 | +| `freight_rpa` 不 import 发货工作流与 `audit_service` | Task 6 边界测试 | +| 不改 `freight_upload`、不做出站抓取、不拆服务 | Global Constraints;Task 6 写明不改 upload 文件 | +| ADR 0004 与 GLOSSARY | Task 8 | + +不在本计划里的项:排程函数名 `run_freight_receipt_rpa_*`、表名 `freight_rpa_inbound_rpa_unit_runs` 与 `freight_rpa_onhand_task_rpa_attempts` 的中间 `rpa`、Worker 日志行 `[freight_inbound_rpa_worker]`。设计文档没有要求改它们。 diff --git a/docs/superpowers/plans/2026-10-19-freight-rpa-class-prefix.md b/docs/superpowers/plans/2026-10-19-freight-rpa-class-prefix.md new file mode 100644 index 00000000..13a8ae85 --- /dev/null +++ b/docs/superpowers/plans/2026-10-19-freight-rpa-class-prefix.md @@ -0,0 +1,448 @@ +# 货代 RPA 类名前缀与上传动作 Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** 把表名已是 `freight_rpa_*` 的 ORM 类改成 `FreightRpa` 前缀,并把 Worker 上传动作与心跳能力改成 `freight_rpa_upload`。 + +**Architecture:** 两块互不依赖。任务 1 只改三个动作/能力字面量、原因码和两份现行文档,schema 仍是 `freight_rpa.upload.v1`。任务 2 用显式类名表做整词替换并移动模型文件,再只改站点关系属性 `inventory_source` 与 `receipt_report_config`。不留旧名别名,不写迁移。 + +**Tech Stack:** Flask、SQLAlchemy 2.0、pytest。Python 用 `backend/.venv/Scripts/python.exe`。pytest 的工作目录是 `backend/`。 + +**Spec:** `docs/superpowers/specs/2026-10-19-freight-rpa-class-prefix-design.md` + +## Global Constraints + +- 类名以 `FreightRpa` 开头。`ShippingInboundRpaUnitRun` 改为 `FreightRpaInboundUnitRun`,`ShippingTaskOnhandRpaAttempt` 改为 `FreightRpaOnhandTaskAttempt`,`ShippingOnhandSource` 改为 `FreightRpaSource`。 +- 心跳能力与 trigger `action` 改为 `freight_rpa_upload`。`trigger_io.SCHEMA` 保持 `freight_rpa.upload.v1`。 +- 不保留旧类名、旧模块路径、旧动作名的别名。后端与 Windows Worker 同一次发布。 +- 不改任何表名、索引名、约束名、外键名。不新增 Alembic 迁移。`backend/migrations/` 不参与替换。 +- 不改发货阶段 `freight_upload`、`freight_uploading`,不改门禁码 `freight_upload_rpa`,不改动作码 `retry_freight_upload_rpa`、`poll_freight_upload_rpa`、`trigger_freight_upload_rpa`,不改四语言文案。 +- 函数名 `check_freight_upload_rpa_ready` 与 `assert_freight_upload_rpa_ready` 保留。 +- 不改 `ShippingUploadAttempt` 与表 `shipping_notice_upload_attempts`。 +- 不改这些发货类:`ShippingNotice`、`ShippingTaskOnhandLink`、`ShippingOnhandCandidateSet`、`ShippingOnhandCandidateSource`、`ShippingOnhandCandidateLine`、`ShippingOnhandPreparationAttempt`、`ShippingOnhandPreparationSourceAttempt`、`ShippingNoticeLineOnhandMatch`、`ShippingOnhandVerification`、`ShippingOnhandVerificationLine`、`ShippingFreightCancellation`、`ShippingExcelTemplate`。关系属性 `inventory_file` 保留。 +- 不把履约出货改名为 outbound,不改 `shipment_*`。 +- 不改环境变量 `FREIGHT_RPA_UPLOAD_*`,不改上传回调路径,不改 MinIO 键。 +- 不改写 `docs/superpowers/plans/` 与 `docs/superpowers/specs/` 里已有计划正文。本规格的状态行除外,见任务 2 最后一步。 +- 本计划覆盖 2026-10-17 对 `freight_rpa_upload` 的否决,也覆盖阶段 B「不改 `freight_upload`」里对动作名和心跳能力的那一句。阶段名和门禁码仍不改。 +- 工作区里已有未提交的批次 S/D 与阶段 B。禁止 `git add -A`,禁止 `git commit`。每任务只暂存该任务列出的路径。 +- 改签名或文件协作关系时同步文件头 docstring(AGENTS.md §5)。 + +## 文件地图 + +| 文件 | 职责 | +| --- | --- | +| `backend/app/services/freight_rpa/upload/trigger_io.py` | trigger 的 `action` 常量 | +| `backend/app/services/freight_rpa/common/worker_heartbeat.py` | 心跳能力常量、缺失原因码、管理端状态键 | +| `scripts/freight_rpa/common/rpa_heartbeat.py` | Windows Worker 上报的能力字符串 | +| `docs/features/freight-rpa/GLOSSARY.md` | Upload 条的现行动作名 | +| `docs/features/freight-rpa/cutover-runbook.md` | 发布窗口里的动作名,以及发布前清空 upload 目录 | +| `backend/app/models/freight_rpa_config.py` | 站点、登录连接、解析方案及在手配置类。由 `shipping_onhand_config.py` 改名 | +| `backend/app/models/freight_rpa_inbound_report.py` | 入站配置、执行单元、文件、通知。由 `shipping_inbound_report.py` 改名 | +| `backend/app/models/freight_rpa_onhand_mapping.py` | 在手字段映射。由 `shipping_onhand_mapping.py` 改名 | +| `backend/app/models/freight_rpa_onhand_task_attempts.py` | 在手任务抓取尝试。由 `shipping_onhand_task_rpa_attempts.py` 改名 | +| `backend/app/models/freight_rpa_onhand_report_file.py` | 在手报表文件。从 `shipping.py` 拆出 | +| `backend/app/models/__init__.py` | 导出新类名,不留旧类名 | +| `backend/tests/test_freight_rpa_class_names.py` | 锁表名、新类名、关系属性名 | + +--- + +### Task 1: 上传动作与心跳能力 + +**Files:** +- Modify: `backend/app/services/freight_rpa/upload/trigger_io.py` +- Modify: `backend/app/services/freight_rpa/common/worker_heartbeat.py` +- Modify: `scripts/freight_rpa/common/rpa_heartbeat.py` +- Modify: `backend/tests/services/freight_rpa/test_upload_trigger_contract.py` +- Modify: `backend/tests/services/freight_rpa/test_worker_heartbeat.py` +- Modify: `backend/tests/test_freight_rpa_heartbeat.py` +- Modify: `docs/features/freight-rpa/GLOSSARY.md` +- Modify: `docs/features/freight-rpa/cutover-runbook.md` +- Test: `backend/tests/services/freight_rpa/test_upload_trigger_contract.py` + +**Interfaces:** +- Consumes: 现有 `write_upload_trigger(...)`、`check_freight_upload_rpa_ready()`、`build_heartbeat_payload(...)`。函数名不改。 +- Produces: `ACTION_FREIGHT_RPA_UPLOAD = "freight_rpa_upload"`;`FREIGHT_RPA_UPLOAD_CAPABILITY = "freight_rpa_upload"`;两者相等。缺失原因码 `missing_freight_rpa_upload_capability`。`SCHEMA` 仍为 `freight_rpa.upload.v1`。 + +- [ ] **Step 1: 把契约测试改成新动作名** + +在 `backend/tests/services/freight_rpa/test_upload_trigger_contract.py` 把导入和断言换成: + +```python +from app.services.freight_rpa.common.worker_heartbeat import FREIGHT_RPA_UPLOAD_CAPABILITY +from app.services.freight_rpa.upload import trigger_io + + +def test_upload_trigger_constants_align_with_heartbeat_capability(): + """upload action 必须与 Worker 心跳能力串 freight_rpa_upload 一致。""" + assert trigger_io.SCHEMA == "freight_rpa.upload.v1" + assert trigger_io.ACTION_FREIGHT_RPA_UPLOAD == "freight_rpa_upload" + assert trigger_io.ACTION_FREIGHT_RPA_UPLOAD == FREIGHT_RPA_UPLOAD_CAPABILITY + assert "outbound_upload" not in trigger_io.ACTION_FREIGHT_RPA_UPLOAD + assert "shipment_upload" not in trigger_io.ACTION_FREIGHT_RPA_UPLOAD +``` + +同一文件里 `test_write_upload_trigger_persists_freight_upload_action` 的两处动作断言改为: + +```python + assert payload["action"] == trigger_io.ACTION_FREIGHT_RPA_UPLOAD + assert payload["schema_version"] == trigger_io.SCHEMA + assert payload["action"] == "freight_rpa_upload" + assert payload["schema_version"] == "freight_rpa.upload.v1" +``` + +在 `backend/tests/services/freight_rpa/test_worker_heartbeat.py` 把 `FREIGHT_UPLOAD_CAPABILITY` 的导入改成 `FREIGHT_RPA_UPLOAD_CAPABILITY`。`test_check_freight_upload_rpa_ready_requires_freight_upload_capability` 的断言改为: + +```python + assert result.ready is False + assert any("missing_freight_rpa_upload_capability" in reason for reason in result.reasons) +``` + +`test_check_freight_upload_rpa_ready_when_worker_and_dirs_ok` 里心跳能力列表改为: + +```python + capabilities=[ONHAND_EXPORT_CAPABILITY, FREIGHT_RPA_UPLOAD_CAPABILITY], +``` + +在 `backend/tests/test_freight_rpa_heartbeat.py` 的 `test_build_heartbeat_payload_inbound_worker_declares_inbound_export` 后面增加: + +```python +def test_build_heartbeat_payload_adds_freight_rpa_upload_when_upload_enabled(monkeypatch): + """开启上传时心跳能力是 freight_rpa_upload,不再上报 freight_upload。""" + module = _load_freight_rpa_heartbeat_module() + monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "true") + payload = module.build_heartbeat_payload( + trigger_dir=r"C:\HxopsRpaTest\data\onhand_triggers", + drop_dir=r"C:\HxopsRpaTest\data\onhand_drop", + ) + assert payload["capabilities"] == ["onhand_export", "freight_rpa_upload"] +``` + +- [ ] **Step 2: 跑测试,确认失败** + +工作目录 `backend/`: + +```powershell +..\.venv\Scripts\python.exe -m pytest tests/services/freight_rpa/test_upload_trigger_contract.py tests/services/freight_rpa/test_worker_heartbeat.py::test_check_freight_upload_rpa_ready_requires_freight_upload_capability tests/test_freight_rpa_heartbeat.py::test_build_heartbeat_payload_adds_freight_rpa_upload_when_upload_enabled -q --tb=line +``` + +Expected: FAIL。导入失败或断言仍是 `freight_upload`。 + +- [ ] **Step 3: 改三个字面量** + +`trigger_io.py`: + +```python +SCHEMA = "freight_rpa.upload.v1" +ACTION_FREIGHT_RPA_UPLOAD = "freight_rpa_upload" +``` + +`write_upload_trigger` 写入的 `"action"` 改为 `ACTION_FREIGHT_RPA_UPLOAD`。文件头里描述动作的那一句改为:action 对齐心跳能力 `freight_rpa_upload`(`FREIGHT_RPA_UPLOAD_CAPABILITY`)。删除对常量名 `ACTION_FREIGHT_UPLOAD`、`FREIGHT_UPLOAD_CAPABILITY` 的引用。 + +`worker_heartbeat.py`: + +```python +FREIGHT_RPA_UPLOAD_CAPABILITY = "freight_rpa_upload" +``` + +删除 `FREIGHT_UPLOAD_CAPABILITY`。所有引用改到新常量,包括 `check_freight_upload_rpa_ready` 与 `assert_freight_upload_rpa_ready` 内部。这两个函数名保留。 + +`_REASON_USER_HINTS` 的键改为 `missing_freight_rpa_upload_capability`,提示文案改为 `Worker 未声明 freight_rpa_upload 能力`。`_missing_capability_reason` 继续用 `f"missing_{required_capability}_capability"`,不要再手写旧码。 + +`serialize_rpa_worker_status` 返回字典里的键 `"freight_upload"` 改为 `"freight_rpa_upload"`。这是该文件里剩下的动作字面量;仓库里没有前端读取这个键。 + +文件头注释里「freight_upload 不变」改为「上传能力为 freight_rpa_upload」。 + +`scripts/freight_rpa/common/rpa_heartbeat.py` 的 `build_heartbeat_payload`:开启上传时 `capabilities.append("freight_rpa_upload")`。函数 docstring 同步写成 `freight_rpa_upload`。 + +- [ ] **Step 4: 改现行文档** + +`docs/features/freight-rpa/GLOSSARY.md` Upload 条:心跳能力与上传 action 写成 `freight_rpa_upload`。schema 仍写 `freight_rpa.upload.v1`。保留「禁止 outbound_*」这句话。 + +`docs/features/freight-rpa/cutover-runbook.md` 里动作和心跳现在写成 `freight_upload` 或「`freight_upload` 不变」的地方,改成 `freight_rpa_upload`。在「一次上传」那一步之前加一句:发布前清空 upload 的 triggers 与 queue;已落盘且 `action` 为 `freight_upload` 的 trigger 不改写、不双读。 + +不要改 `docs/superpowers/plans/2026-10-17-freight-rpa-upload-action-fix.md`。 + +- [ ] **Step 5: 跑测试并检索旧字面量** + +工作目录 `backend/`: + +```powershell +..\.venv\Scripts\python.exe -m pytest tests/services/freight_rpa/test_upload_trigger_contract.py tests/services/freight_rpa/test_worker_heartbeat.py tests/test_freight_rpa_heartbeat.py -q --tb=short +``` + +Expected: PASS。 + +在仓库根目录检索。下面三条的结果必须为空: + +```powershell +rg -n "ACTION_FREIGHT_UPLOAD|FREIGHT_UPLOAD_CAPABILITY" backend/app/services/freight_rpa/upload/trigger_io.py backend/app/services/freight_rpa/common/worker_heartbeat.py scripts/freight_rpa/common/rpa_heartbeat.py +rg -n "\"freight_upload\"" backend/app/services/freight_rpa/upload/trigger_io.py backend/app/services/freight_rpa/common/worker_heartbeat.py scripts/freight_rpa/common/rpa_heartbeat.py +rg -n "missing_freight_upload_capability" backend/app/services/freight_rpa/common/worker_heartbeat.py backend/tests/services/freight_rpa/test_worker_heartbeat.py +``` + +`check_freight_upload_rpa_ready` 仍在 `worker_heartbeat.py`。发货阶段文件里的 `freight_upload` 不动。 + +- [ ] **Step 6: 只暂存本任务路径** + +```powershell +git add -- backend/app/services/freight_rpa/upload/trigger_io.py backend/app/services/freight_rpa/common/worker_heartbeat.py scripts/freight_rpa/common/rpa_heartbeat.py backend/tests/services/freight_rpa/test_upload_trigger_contract.py backend/tests/services/freight_rpa/test_worker_heartbeat.py backend/tests/test_freight_rpa_heartbeat.py docs/features/freight-rpa/GLOSSARY.md docs/features/freight-rpa/cutover-runbook.md +``` + +--- + +### Task 2: ORM 类名与模型文件 + +**Files:** +- Create: `backend/app/models/freight_rpa_config.py` +- Create: `backend/app/models/freight_rpa_inbound_report.py` +- Create: `backend/app/models/freight_rpa_onhand_mapping.py` +- Create: `backend/app/models/freight_rpa_onhand_task_attempts.py` +- Create: `backend/app/models/freight_rpa_onhand_report_file.py` +- Create: `backend/tests/test_freight_rpa_class_names.py` +- Modify: `backend/app/models/shipping.py` +- Modify: `backend/app/models/__init__.py` +- Delete: `backend/app/models/shipping_onhand_config.py` +- Delete: `backend/app/models/shipping_inbound_report.py` +- Delete: `backend/app/models/shipping_onhand_mapping.py` +- Delete: `backend/app/models/shipping_onhand_task_rpa_attempts.py` +- Test: `backend/tests/test_freight_rpa_class_names.py` + +引用这些类的 `backend/app`、`backend/tests`、`backend/scripts` 由下面的脚本改名。`backend/migrations/` 与 `docs/superpowers/` 不跑脚本。 + +**Interfaces:** +- Consumes: 任务 1 不需要。表名保持规格第 3 节那一列。 +- Produces: `from app.models import FreightRpaSource, FreightRpaOnhandReportFile, FreightRpaInboundReportFile, FreightRpaInboundUnitRun, FreightRpaParsingProfile, FreightRpaProfile`。`FreightRpaSource.inbound_report_config`。`FreightRpaOnhandReportConfig.source`、`FreightRpaOnhandExternalMapping.source`、`FreightRpaInboundReportConfig.source`、`FreightRpaInboundUnitRun.source`。`app.models` 上不再有 `ShippingOnhandSource`、`ShippingOnhandFile`、`ShippingInboundReportFile`、`ShippingParsingProfile`。 + +- [ ] **Step 1: 写会失败的类名测试** + +创建 `backend/tests/test_freight_rpa_class_names.py`: + +```python +""" +backend/tests/test_freight_rpa_class_names.py + +用途:锁住货代 RPA 模型的类名、表名和站点关系属性名。 +依赖:app.models 里拆出的 freight_rpa_* 模型模块。 +逻辑:被 pytest 直接导入;不连数据库。 +""" + +from __future__ import annotations + +import app.models as models +from app.models.freight_rpa_config import ( + FreightRpaOnhandExternalMapping, + FreightRpaOnhandReportConfig, + FreightRpaSource, +) +from app.models.freight_rpa_inbound_report import ( + FreightRpaInboundReportConfig, + FreightRpaInboundReportFile, + FreightRpaInboundUnitRun, +) +from app.models.freight_rpa_onhand_report_file import FreightRpaOnhandReportFile +from app.models.freight_rpa_onhand_task_attempts import FreightRpaOnhandTaskAttempt + + +def test_freight_rpa_classes_keep_existing_table_names(): + """类名换成 FreightRpa 后,表名仍是规格里的 freight_rpa_*。""" + assert FreightRpaSource.__tablename__ == "freight_rpa_sources" + assert FreightRpaOnhandReportFile.__tablename__ == "freight_rpa_onhand_report_files" + assert FreightRpaInboundReportFile.__tablename__ == "freight_rpa_inbound_report_files" + assert FreightRpaInboundUnitRun.__tablename__ == "freight_rpa_inbound_rpa_unit_runs" + + +def test_site_relationships_drop_inventory_and_receipt_names(): + """站点关系改叫 source / inbound_report_config,索引名不在这个测试里改。""" + assert "source" in FreightRpaOnhandReportConfig.__mapper__.relationships + assert "inventory_source" not in FreightRpaOnhandReportConfig.__mapper__.relationships + assert "source" in FreightRpaInboundReportConfig.__mapper__.relationships + assert "source" in FreightRpaInboundUnitRun.__mapper__.relationships + assert "inbound_report_config" in FreightRpaSource.__mapper__.relationships + assert "receipt_report_config" not in FreightRpaSource.__mapper__.relationships + assert "source" in FreightRpaOnhandExternalMapping.__mapper__.relationships + assert FreightRpaOnhandTaskAttempt.__tablename__ == "freight_rpa_onhand_task_rpa_attempts" + + +def test_old_shipping_class_names_are_not_exported(): + """旧类名不留别名。发货任务关联类仍叫 ShippingTaskOnhandLink。""" + assert not hasattr(models, "ShippingOnhandSource") + assert not hasattr(models, "ShippingOnhandFile") + assert not hasattr(models, "ShippingInboundReportFile") + assert not hasattr(models, "ShippingParsingProfile") + assert hasattr(models, "FreightRpaSource") + assert hasattr(models, "FreightRpaOnhandReportFile") + assert hasattr(models, "ShippingTaskOnhandLink") + assert hasattr(models, "ShippingUploadAttempt") +``` + +- [ ] **Step 2: 跑测试,确认失败** + +工作目录 `backend/`: + +```powershell +..\.venv\Scripts\python.exe -m pytest tests/test_freight_rpa_class_names.py -q --tb=line +``` + +Expected: FAIL,模块 `app.models.freight_rpa_config` 不存在。 + +- [ ] **Step 3: 移动文件并按显式表替换类名** + +在仓库根目录把下面整段存成临时文件 `rename_freight_rpa_classes.py` 并执行。跑完删除它,不要 `git add` 它。脚本先 `git mv`,再替换模块路径,再只替换类名整词,长名字在前。不要把 `ShippingOnhand` 当成前缀去替换。 + +```python +import re +import subprocess +from pathlib import Path + +ROOT = Path.cwd() +MOVES = [ + ("backend/app/models/shipping_onhand_config.py", "backend/app/models/freight_rpa_config.py"), + ("backend/app/models/shipping_inbound_report.py", "backend/app/models/freight_rpa_inbound_report.py"), + ("backend/app/models/shipping_onhand_mapping.py", "backend/app/models/freight_rpa_onhand_mapping.py"), + ("backend/app/models/shipping_onhand_task_rpa_attempts.py", "backend/app/models/freight_rpa_onhand_task_attempts.py"), +] +MODULE_PATHS = [ + ("app.models.shipping_onhand_task_rpa_attempts", "app.models.freight_rpa_onhand_task_attempts"), + ("app.models.shipping_onhand_config", "app.models.freight_rpa_config"), + ("app.models.shipping_inbound_report", "app.models.freight_rpa_inbound_report"), + ("app.models.shipping_onhand_mapping", "app.models.freight_rpa_onhand_mapping"), + ("models.shipping_onhand_task_rpa_attempts", "models.freight_rpa_onhand_task_attempts"), + ("models.shipping_onhand_config", "models.freight_rpa_config"), + ("models.shipping_inbound_report", "models.freight_rpa_inbound_report"), + ("models.shipping_onhand_mapping", "models.freight_rpa_onhand_mapping"), +] +RENAMES = [ + ("ShippingOnhandSourceParsingBindingAudit", "FreightRpaSourceParsingBindingAudit"), + ("ShippingOnhandRoutingRuleCondition", "FreightRpaOnhandRoutingRuleCondition"), + ("ShippingOnhandRoutingRuleVersion", "FreightRpaOnhandRoutingRuleVersion"), + ("ShippingOnhandConfigurationTestRun", "FreightRpaOnhandConfigurationTestRun"), + ("ShippingInboundNotificationDelivery", "FreightRpaInboundNotificationDelivery"), + ("ShippingOnhandStructureAnalysis", "FreightRpaOnhandStructureAnalysis"), + ("ShippingOnhandExternalMapping", "FreightRpaOnhandExternalMapping"), + ("ShippingOnhandValidationBatch", "FreightRpaOnhandValidationBatch"), + ("ShippingInboundReportConfig", "FreightRpaInboundReportConfig"), + ("ShippingOnhandReportConfig", "FreightRpaOnhandReportConfig"), + ("ShippingInboundReportFile", "FreightRpaInboundReportFile"), + ("ShippingTaskOnhandRpaAttempt", "FreightRpaOnhandTaskAttempt"), + ("ShippingOnhandRoutingRule", "FreightRpaOnhandRoutingRule"), + ("ShippingInboundRpaUnitRun", "FreightRpaInboundUnitRun"), + ("ShippingParsingProfile", "FreightRpaParsingProfile"), + ("ShippingOnhandMapping", "FreightRpaOnhandMapping"), + ("ShippingOnhandSource", "FreightRpaSource"), + ("ShippingOnhandField", "FreightRpaOnhandField"), + ("ShippingOnhandFile", "FreightRpaOnhandReportFile"), + ("ShippingRpaProfile", "FreightRpaProfile"), +] +SKIP_PARTS = {"migrations", "superpowers", ".superpowers"} +ROOTS = [ + ROOT / "backend" / "app", + ROOT / "backend" / "tests", + ROOT / "backend" / "scripts", + ROOT / "scripts" / "freight_rpa", +] + +for src, dst in MOVES: + subprocess.run(["git", "mv", src, dst], check=True, cwd=ROOT) + +for base in ROOTS: + for path in base.rglob("*"): + if not path.is_file() or path.suffix not in {".py", ".md"}: + continue + if any(part in SKIP_PARTS for part in path.parts): + continue + text = path.read_text(encoding="utf-8") + updated = text + for old, new in MODULE_PATHS: + updated = updated.replace(old, new) + for old, new in RENAMES: + updated = re.sub(rf"\b{old}\b", new, updated) + if updated != text: + path.write_text(updated, encoding="utf-8") +``` + +然后把 `FreightRpaOnhandReportFile` 的整个类(含它上方的类 docstring,不含 `ShippingTaskOnhandLink`)从 `backend/app/models/shipping.py` 剪到新文件 `backend/app/models/freight_rpa_onhand_report_file.py`。新文件自己 import `Base` 以及这个类用到的 SQLAlchemy 符号。`shipping.py` 若还引用该类,改为从新模块导入,或只在类型注解里用字符串 `"FreightRpaOnhandReportFile"`。`ShippingTaskOnhandLink.inventory_file` 的目标类字符串改为 `"FreightRpaOnhandReportFile"`,属性名 `inventory_file` 不变。 + +把新文件头写成: + +```python +""" +backend/app/models/freight_rpa_onhand_report_file.py + +用途:货代 RPA 抓回的在手报表文件。 +依赖:models.base.Base、shipping.py 里的 ShippingTaskOnhandLink。 +逻辑:表名 freight_rpa_onhand_report_files 不变;发货任务通过 ShippingTaskOnhandLink 引用本行。 +""" +``` + +另外四个模型文件的文件头第一行改成新路径,类名改成新类名。`__tablename__`、`Index(...)`、`UniqueConstraint(...)`、`CheckConstraint(...)` 的字符串一个字都不改。 + +`backend/app/models/__init__.py` 的 import 路径改到新模块,`__all__` 只导出新类名。文件头「在手/入站模型只导出 ShippingOnhand* 与 ShippingInbound*」改为「在手/入站模型导出 FreightRpa*」。 + +- [ ] **Step 4: 只改两个关系属性** + +不要全局把 `inventory_source` 换成 `source`。投影字典的键 `'inventory_source'`、门禁码、`inventory_source_code` 都要留下。 + +只做这三类替换,范围是 `backend/app`、`backend/tests`、`backend/scripts`: + +1. 模型字段行 `inventory_source:` 改为 `source:`。出现位置是 `FreightRpaOnhandReportConfig`、`FreightRpaOnhandExternalMapping`、`FreightRpaInboundReportConfig`、`FreightRpaInboundUnitRun`。 +2. 模型文件里的 `back_populates='inventory_source'` 改为 `back_populates='source'`。 +3. 关键字实参 `inventory_source=` 改为 `source=`。点号访问 `.inventory_source` 改为 `.source`。已知位置包括 `shipping_onhand_admin_service.py` 构造 `FreightRpaOnhandReportConfig`、`onhand_configuration_test.py`、`import_freight_rpa_sources.py`、`freight_rpa_inbound_job.py` 的 `unit.inventory_source`、`api/schedule/runs.py` 的 `retry.inventory_source`。 + +`receipt_report_config` 用整词替换成 `inbound_report_config`,同一范围。这个整词不会打中 `get_receipt_report_config`,因为中间有下划线。不要改 `backend/migrations` 里的旧表名 `shipping_receipt_report_configs`。 + +改完后这两条结果必须为空: + +```powershell +rg -n "\.inventory_source\b|inventory_source=" backend/app backend/tests backend/scripts +rg -n "\breceipt_report_config\b" backend/app backend/tests backend/scripts +``` + +`rg -n "inventory_source" backend/app/services/shipping_notice/line_onhand_match_projection.py` 仍应能看到字典键 `'inventory_source'`。那是发货投影,本任务不改。 + +- [ ] **Step 5: 跑类名测试并检索旧类名** + +工作目录 `backend/`: + +```powershell +..\.venv\Scripts\python.exe -m pytest tests/test_freight_rpa_class_names.py -q --tb=short +``` + +Expected: PASS。 + +仓库根目录,下面每一条结果必须为空。把规格第 3 节的旧类名逐个放进同一条正则: + +```powershell +rg -n "\bShippingOnhandSource\b|\bShippingOnhandFile\b|\bShippingInboundReportFile\b|\bShippingInboundRpaUnitRun\b|\bShippingTaskOnhandRpaAttempt\b|\bShippingParsingProfile\b|\bShippingRpaProfile\b|\bShippingOnhandReportConfig\b|\bShippingOnhandMapping\b|\bShippingInboundReportConfig\b|\bShippingInboundNotificationDelivery\b|\bShippingOnhandField\b|\bShippingOnhandExternalMapping\b|\bShippingOnhandStructureAnalysis\b|\bShippingOnhandConfigurationTestRun\b|\bShippingOnhandValidationBatch\b|\bShippingOnhandRoutingRule\b|\bShippingOnhandRoutingRuleCondition\b|\bShippingOnhandRoutingRuleVersion\b|\bShippingOnhandSourceParsingBindingAudit\b" backend/app scripts/freight_rpa +``` + +`backend/migrations` 里的旧类名允许留下。 + +旧模块路径也必须为空: + +```powershell +rg -n "models\.shipping_onhand_config|models\.shipping_inbound_report|models\.shipping_onhand_mapping|models\.shipping_onhand_task_rpa_attempts|shipping import FreightRpaOnhandReportFile" backend/app backend/tests backend/scripts +``` + +若 `from app.models.shipping import FreightRpaOnhandReportFile` 仍在,改成 `from app.models.freight_rpa_onhand_report_file import FreightRpaOnhandReportFile`,或改成 `from app.models import FreightRpaOnhandReportFile`。 + +再跑一条导入检查,确认模型包能加载: + +```powershell +..\.venv\Scripts\python.exe -c "import app.models as m; assert m.FreightRpaInboundReportFile.__tablename__=='freight_rpa_inbound_report_files'" +``` + +工作目录仍是 `backend/`。 + +- [ ] **Step 6: 改规格状态行** + +`docs/superpowers/specs/2026-10-19-freight-rpa-class-prefix-design.md` 第一段状态从 `待评审` 改为 `已有实施计划`,并写上本计划路径 `docs/superpowers/plans/2026-10-19-freight-rpa-class-prefix.md`。规格正文的类名对照表不要改。 + +- [ ] **Step 7: 只暂存本任务碰到的路径** + +先删掉临时脚本 `rename_freight_rpa_classes.py`。然后暂存新模型文件、测试、`shipping.py`、`models/__init__.py`,以及 `git status --short` 里确因本任务改了类名或关系属性的 `backend/app`、`backend/tests`、`backend/scripts` 文件。不要暂存 `backend/migrations`。不要 `git add -A`。规格状态行一并暂存: + +```powershell +git add -- docs/superpowers/specs/2026-10-19-freight-rpa-class-prefix-design.md backend/tests/test_freight_rpa_class_names.py backend/app/models/freight_rpa_config.py backend/app/models/freight_rpa_inbound_report.py backend/app/models/freight_rpa_onhand_mapping.py backend/app/models/freight_rpa_onhand_task_attempts.py backend/app/models/freight_rpa_onhand_report_file.py backend/app/models/shipping.py backend/app/models/__init__.py +``` + +其余被类名替换碰到的文件,按 `git diff --name-only` 逐个 `git add -- `。 diff --git a/docs/superpowers/plans/2026-10-19-freight-rpa-outbound-and-rename.md b/docs/superpowers/plans/2026-10-19-freight-rpa-outbound-and-rename.md new file mode 100644 index 00000000..01619192 --- /dev/null +++ b/docs/superpowers/plans/2026-10-19-freight-rpa-outbound-and-rename.md @@ -0,0 +1,737 @@ +# 货代 RPA:报表规则改名 + 出站全栈 + 入站运维瘦身 Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** 管理端改名为「报表规则 / 来源站点 / 入站报表」,交付与入站同构的出站 RPA 全栈,并拆除入站 deliveries 与工作台收料文件页。 + +**Architecture:** 做法 A——按入站包逐文件克隆出站(models / trigger_io / report_archive / schedule job / Worker / 调拨 trigger / sink),不先做泛化层。改名与入站瘦身穿插在前序任务,降低出站联调噪声。`purpose=outbound` 校验改走 `MOVEMENT_FIELDS`。通知只走排程 `notify_user_ids`。 + +**Tech Stack:** Flask、SQLAlchemy 2.0、Alembic、Vue 3、pytest、Playwright Worker(Python)。后端测试工作目录 `backend/`;Windows 上 Python 用 `backend/.venv/Scripts/python.exe`(若无则用已激活的 venv)。 + +**Spec:** `docs/superpowers/specs/2026-10-19-freight-rpa-outbound-and-rename-design.md` + +## Global Constraints + +- 入口文案:`库存解析` → **报表规则**;`库存站点` → **来源站点**;`收料报表配置` → **入站报表配置**。父级「库存管理」、库存字段目录不改。 +- 出站类名一律 `FreightRpaOutbound*`;假定 class-prefix 已合入(`FreightRpaSource` 等)。禁止引入 `Shipping*Outbound*`。 +- 出站新建三表:`freight_rpa_outbound_report_configs` / `freight_rpa_outbound_rpa_unit_runs` / `freight_rpa_outbound_report_files`。**禁止**建 `*_notification_deliveries`。 +- 删除 `freight_rpa_inbound_notification_deliveries` 及 resend / 工作台收料页 / `inbound_report_access`。 +- `receipt-raw-zip` → `inbound-raw-zip`(路径与深链参数),无兼容别名。 +- 出站配置非启用硬门槛;触发时站点停用/缺配置 fail-closed。 +- `purpose=outbound` 与 inbound 同异动契约;旧 onhand 形态 outbound 草稿不自动迁移。 +- RPA 层不强制 `in_out_flag`;方向过滤留在调拨域。 +- 不改履约出货 / upload;不新建工作台出站文件页。 +- 四语言 i18n 同步;错误码新增须写 `locales/*/errors.json`。 +- 改函数签名或模块协作时同步文件头与函数注释(AGENTS.md §5)。 +- 禁止 `git add -A` / `git commit`;每任务只 stage 该任务列出的路径。工作区可能已有未提交的其它批次,勿混入。 +- **跨机路径(硬约束)**:出站回调 `file_path` 只按「outbound drop 根内文件名」解析。后端必须 `replace('\\','/')` 后取 `.name`,再拼 `FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR`,`relative_to(root)` 防穿越。禁止把 Windows 绝对路径当 Linux 路径打开。对照入站 `_read_inbound_callback_file` 与在手 `resolve_shared_inventory_drop_file`。Worker 侧优先只上报文件名。必须有带 `C:\\...\\foo.xlsx` 的回归测。 + +## 文件地图 + +| 文件 / 目录 | 职责 | +| --- | --- | +| `frontend/src/locales/{zh-CN,zh-TW,en,th}/admin.json` 等 | 报表规则 / 来源站点 / 入站·出站报表文案 | +| `frontend/src/features/admin/modules/freight-rpa/*` | 来源站点三块配置、报表规则 purpose=outbound UI | +| `frontend/src/features/workspace/**`(收料页相关) | 删除 | +| `backend/app/models/freight_rpa_outbound_report.py` | 出站三模型(新建) | +| `backend/app/models/freight_rpa_inbound_report.py` | 去掉 NotificationDelivery | +| `backend/migrations/versions/*_freight_rpa_outbound_and_inbound_slim.py` | 出站建表 + drop deliveries | +| `backend/app/services/shipping_notice/onhand_parsing_profile.py` | outbound → 异动校验 | +| `backend/app/services/admin/shipping_onhand_admin_service.py` | `get_/save_inbound_*` + `get_/save_outbound_*` | +| `backend/app/services/freight_rpa/outbound/*` | trigger_io、report_archive | +| `backend/app/services/schedule/freight_rpa_outbound_*.py` | job / finalize / archive / retention | +| `backend/app/api/freight_rpa.py` | outbound 回调路由 | +| `backend/app/api/schedule/runs.py` | inbound-raw-zip、outbound-raw-zip、outbound units | +| `backend/app/services/in_transit_transfer/outbound_trigger_service.py` | 按需触发 | +| `backend/app/services/in_transit_transfer/outbound_report_handler.py` | sink handler | +| `backend/app/services/shipping_notice/rpa_sinks.py` | `register_outbound_sinks` | +| `scripts/freight_rpa/outbound/*` | Worker / ps1 / 驱动 | +| `docs/features/freight-rpa/GLOSSARY.md` 等 | 术语与运维文档 | + +--- + +### Task 1: 管理端改名(报表规则 / 来源站点 / 入站报表) + +**Files:** +- Modify: `frontend/src/locales/zh-CN/admin.json` +- Modify: `frontend/src/locales/zh-TW/admin.json` +- Modify: `frontend/src/locales/en/admin.json` +- Modify: `frontend/src/locales/th/admin.json` +- Modify: `frontend/src/features/admin/shippingConfigNavigation.spec.ts`(若断言旧文案) +- Modify: `frontend/src/features/admin/modules/freight-rpa/FreightRpaPage.vue`(仅当硬编码「收料」时) +- Modify: `frontend/src/features/admin/modules/freight-rpa/receiptReportConfigForm.ts` → 重命名文件为 `inboundReportConfigForm.ts`,并改导出函数名 +- Modify: 所有 import 上述 form 的文件(`FreightRpaPage.vue`、`*.spec.ts`) +- Test: `frontend/src/features/admin/modules/freight-rpa/receiptReportConfigForm.spec.ts` → `inboundReportConfigForm.spec.ts` + +**Interfaces:** +- Consumes: 现有 i18n 键 `admin.freightRpa.parsingProfiles`、`sources`、`receiptReportConfig*` +- Produces: 用户可见字符串变更;键名可将 `receiptReportConfig` 改为 `inboundReportConfig`(四语言同步改键,调用处同步);`buildInboundReportConfigPayload` 替代 `buildReceiptReportConfigPayload` + +- [ ] **Step 1: 写失败的导航/文案断言(若已有 spec 则改期望)** + +在 `shippingConfigNavigation.spec.ts` 或新建窄测中断言 labelKey 对应文案解析后为「报表规则」「来源站点」(用 i18n 或直接断言 key 不变、另测 locale 文件内容)。 + +最小 locale 断言脚本(Node,在 `frontend/`): + +```js +const zh = require('./src/locales/zh-CN/admin.json'); +if (zh.freightRpa.parsingProfiles !== '报表规则') throw new Error('parsingProfiles'); +if (zh.freightRpa.sources !== '来源站点') throw new Error('sources'); +if ((zh.freightRpa.inboundReportConfig || zh.freightRpa.receiptReportConfig) !== '入站报表配置') { + throw new Error('inboundReportConfig'); +} +``` + +先跑应失败(当前为库存解析/库存站点/收料报表配置)。 + +- [ ] **Step 2: 改四语言文案与键** + +zh-CN 最低改动示例: + +```json +"parsingProfiles": "报表规则", +"parsingProfilesHelp": "维护可辨识的文件解析规则:库存面向字段目录与订单匹配,入站/出站面向标准异动字段(只读契约)。", +"sources": "来源站点", +"inventorySites": "来源站点", +"inboundReportConfig": "入站报表配置", +"inboundReportConfigHint": "与库存配置同构:报表路径 + 查询条件。查询条件可选,空则使用页面默认;排程按站点一对一导出。入站无独立开关,随站点统一启停。", +"outboundReportConfig": "出站报表配置", +"outboundReportConfigHint": "与入站配置同构:报表路径 + 查询条件;出站无独立开关,随站点统一启停。" +``` + +删除或停止使用 `receiptReportConfig*` 键。zh-TW / en / th 同步语义(en: Report Rules / Source Sites / Inbound Report Config / Outbound Report Config)。 + +同步 `parsingPurposeHint` 等仍写「仅入站」的句子,改为「入站/出站」。 + +- [ ] **Step 3: 重命名前端 form 模块** + +`buildReceiptReportConfigPayload` → `buildInboundReportConfigPayload`;文件改名;`FreightRpaPage.vue` 中 `receiptConfig` 展示文案键改为 `inboundReportConfig*`(状态变量可暂留,Task 6/11 再统一)。 + +- [ ] **Step 4: 跑前端相关测试** + +Run: `cd frontend && npx vitest run src/features/admin/modules/freight-rpa/inboundReportConfigForm.spec.ts src/features/admin/shippingConfigNavigation.spec.ts` +Expected: PASS + +- [ ] **Step 5: Stage** + +```bash +git add frontend/src/locales/zh-CN/admin.json frontend/src/locales/zh-TW/admin.json frontend/src/locales/en/admin.json frontend/src/locales/th/admin.json frontend/src/features/admin/modules/freight-rpa/inboundReportConfigForm.ts frontend/src/features/admin/modules/freight-rpa/inboundReportConfigForm.spec.ts frontend/src/features/admin/modules/freight-rpa/FreightRpaPage.vue frontend/src/features/admin/shippingConfigNavigation.spec.ts +``` + +(含删除旧 `receiptReportConfigForm*` 的 staged deletion。) + +--- + +### Task 2: 拆除入站 deliveries + 工作台收料页 + +**Files:** +- Modify: `backend/app/models/freight_rpa_inbound_report.py`(删 `FreightRpaInboundNotificationDelivery` 与 relationship) +- Modify: `backend/app/models/__init__.py` +- Modify: `backend/app/services/freight_rpa/inbound/report_archive.py`(删 `deliver_inbound_file`、`_recipient_ids` 及 WeCom 投递 import) +- Modify: `backend/app/api/schedule/runs.py`(删 resend 路由) +- Delete: `backend/app/services/shipping_notice/inbound_report_access.py` +- Modify: `backend/app/api/workspace/shipping_notice.py`(删 list/download inbound-report-files 两路由) +- Delete: `frontend/src/features/workspace/pages/InboundReportFilesPage.vue` 及其 `.spec.ts` +- Delete: `frontend/src/features/workspace/api/inbound-report.api.ts` 及其 `.spec.ts`(若仅服务该页) +- Modify: `frontend/src/app/router/routes/workspace.routes.ts` +- Modify: `frontend/src/features/workspace/components/WorkspaceSidebar.vue` +- Modify: `frontend/src/features/workspace/constants/routes.ts` +- Modify: `frontend/src/features/workspace/composables/useWorkspaceNavigation.ts` +- Modify: 四语言 `workspace` locale(去掉 `inboundReports` / nav 项) +- Delete or rewrite: `backend/tests/test_freight_receipt_rpa_notifications.py`、`test_freight_receipt_rpa_access.py`(去掉 deliveries/resend/workspace 断言) +- Create: `backend/migrations/versions/_drop_inbound_notification_deliveries.py`(可与 Task 4 合并为一迁移;若拆分则本任务只 drop) +- Test: 新建 `backend/tests/test_freight_rpa_inbound_slim_gate.py` + +**Interfaces:** +- Consumes: 无 +- Produces: 无 `FreightRpaInboundNotificationDelivery`;无 resend API;无 workspace 收料路由 + +- [ ] **Step 1: 写 grep gate 失败用例** + +```python +# backend/tests/test_freight_rpa_inbound_slim_gate.py +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] + + +def test_no_inbound_notification_delivery_symbol(): + hits = [] + for path in (ROOT / "app").rglob("*.py"): + text = path.read_text(encoding="utf-8") + if "InboundNotificationDelivery" in text or "deliver_inbound_file" in text: + hits.append(str(path)) + assert hits == [] + + +def test_no_workspace_inbound_report_routes(): + text = (ROOT / "app/api/workspace/shipping_notice.py").read_text(encoding="utf-8") + assert "inbound-report-files" not in text +``` + +Run: `pytest tests/test_freight_rpa_inbound_slim_gate.py -v` +Expected: FAIL + +- [ ] **Step 2: 删模型、服务、API、前端页与测试中的引用** + +按 Files 列表删除/改写。`report_archive.py` 文件头 docstring 去掉投递职责。迁移 `op.drop_table('freight_rpa_inbound_notification_deliveries')`(downgrade 可重建最小表结构或 `pass` 并在注释标明不可逆——推荐完整 rebuild 以便本地 downgrade)。 + +- [ ] **Step 3: 再跑 gate + 受影响测试** + +Run: `pytest tests/test_freight_rpa_inbound_slim_gate.py tests/test_freight_receipt_rpa_notifications.py tests/test_freight_receipt_rpa_access.py -v` +Expected: gate PASS;旧测文件已删或改写后 PASS + +- [ ] **Step 4: Stage 本任务路径** + +```bash +git add backend/app/models/freight_rpa_inbound_report.py backend/app/models/__init__.py backend/app/services/freight_rpa/inbound/report_archive.py backend/app/api/schedule/runs.py backend/app/api/workspace/shipping_notice.py backend/migrations/versions/ backend/tests/test_freight_rpa_inbound_slim_gate.py frontend/src/app/router/routes/workspace.routes.ts frontend/src/features/workspace/ +``` + +--- + +### Task 3: `receipt-raw-zip` → `inbound-raw-zip` + +**Files:** +- Modify: `backend/app/api/schedule/runs.py`(路由与函数名) +- Modify: `backend/app/services/schedule/freight_rpa_inbound_archive.py`(`receipt_raw_zip_*` → `inbound_raw_zip_*` 函数名) +- Modify: `backend/app/services/schedule/scheduler_service.py`(深链 `download=inbound_raw_zip`) +- Modify: `backend/app/services/schedule/query_service.py`(summary 字段 `inbound_raw_zip_available`) +- Modify: `frontend/src/features/admin/api/schedule.api.ts` +- Modify: `frontend/src/features/admin/modules/schedules/**`(文案与 query 参数) +- Modify: 四语言 `admin.json` 中 downloadReceipt* → downloadInbound* +- Test: 既有 receipt zip 相关测改断言 + +**Interfaces:** +- Consumes: `resolve_receipt_raw_zip_download`(旧) +- Produces: `resolve_inbound_raw_zip_download(run) -> tuple[Path, str]`;路由 `GET /api/admin/schedule-runs//inbound-raw-zip`;深链 `download=inbound_raw_zip` + +- [ ] **Step 1: 改后端路由与函数名,更新调用方** + +路由: + +```python +@schedule_admin_bp.route('/schedule-runs//inbound-raw-zip', methods=['GET']) +@require_admin +def get_schedule_run_inbound_raw_zip(run_id: int): + """下载入站 RPA 排程 run 的原始入站 Excel 打包(ZIP + manifest)。""" + ... +``` + +禁止保留 `receipt-raw-zip` 路由。 + +- [ ] **Step 2: 改前端 API 与深链** + +```ts +export const scheduleRunInboundRawZipUrl = (runId: number) => + `/api/admin/schedule-runs/${runId}/inbound-raw-zip`; +``` + +`useScheduleAdminDeepLink`:`downloadKind === 'inbound_raw_zip'`。 + +- [ ] **Step 3: 跑相关测试** + +Run: `pytest tests/ -k "inbound_raw_zip or receipt_raw_zip" -v` +Expected: 无 receipt_raw_zip 残留失败;新名 PASS + +- [ ] **Step 4: Stage** + +```bash +git add backend/app/api/schedule/runs.py backend/app/services/schedule/freight_rpa_inbound_archive.py backend/app/services/schedule/scheduler_service.py backend/app/services/schedule/query_service.py frontend/src/features/admin/api/schedule.api.ts frontend/src/features/admin/modules/schedules frontend/src/locales +``` + +--- + +### Task 4: 出站模型 + Alembic 迁移 + +**Files:** +- Create: `backend/app/models/freight_rpa_outbound_report.py` +- Modify: `backend/app/models/freight_rpa_config.py`(`FreightRpaSource.outbound_report_config` relationship) +- Modify: `backend/app/models/__init__.py` +- Create/Modify: Alembic revision(建三表;若 Task 2 未 drop deliveries 则本迁移一并 drop) +- Test: `backend/tests/test_freight_rpa_outbound_models.py` + +**Interfaces:** +- Consumes: `FreightRpaSource`、`FreightRpaParsingProfile` +- Produces: `FreightRpaOutboundReportConfig` / `UnitRun` / `ReportFile`;表名见 Global Constraints + +- [ ] **Step 1: 写模型存在性测试** + +```python +from app.models import FreightRpaOutboundReportConfig, FreightRpaOutboundUnitRun, FreightRpaOutboundReportFile + +def test_outbound_model_tablenames(): + assert FreightRpaOutboundReportConfig.__tablename__ == "freight_rpa_outbound_report_configs" + assert FreightRpaOutboundUnitRun.__tablename__ == "freight_rpa_outbound_rpa_unit_runs" + assert FreightRpaOutboundReportFile.__tablename__ == "freight_rpa_outbound_report_files" +``` + +Expected FAIL(未建类) + +- [ ] **Step 2: 复制入站模型文件并改名** + +以 `freight_rpa_inbound_report.py` 为模板新建 outbound 文件: + +- 类/表/约束名全面 `Inbound`→`Outbound`、`inbound`→`outbound` +- **不要**复制 NotificationDelivery +- 文件头 docstring 写清出站职责;注释去掉「收料」 +- `FreightRpaSource`:`outbound_report_config = relationship(..., uselist=False, back_populates='source')` + +- [ ] **Step 3: 生成并手审迁移** + +Run: `flask db migrate -m "freight_rpa outbound tables and drop inbound notification deliveries"` +手审:仅目标三表 create + deliveries drop;无无关 drop。 + +Run: `flask db upgrade` +Expected: OK + +- [ ] **Step 4: 跑模型测** + +Run: `pytest tests/test_freight_rpa_outbound_models.py -v` +Expected: PASS + +- [ ] **Step 5: Stage** + +```bash +git add backend/app/models/freight_rpa_outbound_report.py backend/app/models/freight_rpa_config.py backend/app/models/__init__.py backend/migrations/versions/ backend/tests/test_freight_rpa_outbound_models.py +``` + +--- + +### Task 5: `purpose=outbound` 改走异动校验 + +**Files:** +- Modify: `backend/app/services/shipping_notice/onhand_parsing_profile.py` +- Modify: `backend/tests/test_parsing_profile_purpose.py` +- Modify: `frontend/src/features/admin/modules/freight-rpa/FreightRpaPage.vue`(`parsing.purpose === 'inbound'` 判断扩展为 inbound|outbound 共用异动 UI) +- Modify: `frontend/src/features/admin/modules/freight-rpa/movementParsingProfileForm.ts`(若有 purpose 分支) + +**Interfaces:** +- Consumes: `_validate_definition(..., purpose=)` +- Produces: `purpose in {'inbound','outbound'}` 均走 `_required_movement_field_ids`,`match_keys=[]` + +- [ ] **Step 1: 改测试期望** + +```python +def test_outbound_definition_uses_movement_fields(): + definition = _validate_definition(_inbound_definition(), purpose='outbound') + assert definition['match_keys'] == [] + assert definition['field_mapping']['doc_no'] == '单据编号' + + +def test_outbound_onhand_shaped_definition_rejected(): + """库存目录形态(含 match_keys)在 outbound 下应失败。""" + # 使用现有 onhand 合法定义夹具;expect ValidationError + ... +``` + +文件头注释:删除「onhand/outbound 维持库存字段目录」。 + +Run: `pytest tests/test_parsing_profile_purpose.py::test_outbound_definition_uses_movement_fields -v` +Expected: FAIL + +- [ ] **Step 2: 改校验分支** + +```python + if purpose in {'inbound', 'outbound'}: + _required_movement_field_ids(raw) + return { + 'sheet_name': str(raw.get('sheet_name') or '').strip() or None, + 'header_row_index': header_row_index, + 'field_mapping': {str(key).strip(): str(value).strip() for key, value in field_mapping.items()}, + 'match_keys': [], + } +``` + +同步所有 `purpose == 'inbound'` 的文档字符串与 `purpose != 'inbound'` 的前端条件 → `purpose === 'onhand'` 才走库存目录 UI。 + +站点绑定过滤: + +- 库存报表:`purpose === 'onhand'`(不要再用 `!== 'inbound'`,以免 outbound 混入) +- 入站:`purpose === 'inbound'` +- 出站:`purpose === 'outbound'` + +- [ ] **Step 3: 跑测试** + +Run: `pytest tests/test_parsing_profile_purpose.py -v` +Expected: PASS + +- [ ] **Step 4: Stage** + +```bash +git add backend/app/services/shipping_notice/onhand_parsing_profile.py backend/tests/test_parsing_profile_purpose.py frontend/src/features/admin/modules/freight-rpa/FreightRpaPage.vue frontend/src/features/admin/modules/freight-rpa/movementParsingProfileForm.ts +``` + +--- + +### Task 6: 出站报表配置 Admin API + receipt→inbound 服务符号 + +**Files:** +- Modify: `backend/app/services/admin/shipping_onhand_admin_service.py` +- Modify: `backend/app/api/admin_freight_rpa.py` +- Modify: `frontend/src/features/admin/api/admin.api.ts` +- Create: `frontend/src/features/admin/modules/freight-rpa/outboundReportConfigForm.ts`(镜像 inbound form) +- Test: `backend/tests/test_freight_rpa_outbound_report_config_api.py` + +**Interfaces:** +- Consumes: `FreightRpaOutboundReportConfig` +- Produces: + - `get_inbound_report_config(source_id) -> dict | None`(由 `get_receipt_report_config` 改名) + - `save_inbound_report_config(source_id, data, *, actor_id) -> dict` + - `get_outbound_report_config(source_id) -> dict | None` + - `save_outbound_report_config(source_id, data, *, actor_id) -> dict` + - 路由 `GET/PUT /api/admin/freight-rpa/sources//outbound-report-config` + - 载荷键:`parsing_profile_id`、`report_path_json`、`query_parameters_json`(与入站相同) + +- [ ] **Step 1: API 契约测试(失败)** + +```python +def test_put_outbound_report_config_requires_outbound_profile(client, admin_headers, source_id, onhand_profile_id): + resp = client.put( + f"/api/admin/freight-rpa/sources/{source_id}/outbound-report-config", + json={"parsing_profile_id": onhand_profile_id, "report_path_json": {}, "query_parameters_json": []}, + headers=admin_headers, + ) + assert resp.status_code in (400, 422) +``` + +- [ ] **Step 2: 实现服务与路由** + +校验:`parsing_profile.purpose == 'outbound' and status == 'published'`(或允许草稿绑定策略与入站现行一致——**逐行对照** `_validate_receipt_report_config` 后改名为 `_validate_inbound_report_config`,再复制为 `_validate_outbound_report_config` 只改 purpose)。 + +重命名所有 `receipt_report_config` 服务函数与事件名中的 receipt→inbound(审计 `event_type` 若已有历史,新事件用 `shipping_outbound_report_config_saved` / `freight_rpa_inbound_report_config_saved`,不强制改历史事件字符串除非测试锁死)。 + +- [ ] **Step 3: 前端 API** + +```ts +export const getOutboundReportConfig = (sourceId: number) => + requestJson(`/api/admin/freight-rpa/sources/${sourceId}/outbound-report-config`); +export const saveOutboundReportConfig = (sourceId: number, body: unknown) => + requestJson(`/api/admin/freight-rpa/sources/${sourceId}/outbound-report-config`, { method: 'PUT', body }); +``` + +- [ ] **Step 4: 跑测** + +Run: `pytest tests/test_freight_rpa_outbound_report_config_api.py -v` +Expected: PASS + +- [ ] **Step 5: Stage 列出文件** + +--- + +### Task 7: 出站 trigger_io + Worker 心跳能力 + +**Files:** +- Create: `backend/app/services/freight_rpa/outbound/__init__.py` +- Create: `backend/app/services/freight_rpa/outbound/trigger_io.py` +- Modify: `backend/app/services/freight_rpa/common/worker_heartbeat.py`(`OUTBOUND_EXPORT_CAPABILITY`、`assert_outbound_rpa_worker_ready`) +- Modify: `scripts/freight_rpa/common/rpa_callbacks.py`(outbound 回调路径常量) +- Test: `backend/tests/services/freight_rpa/test_outbound_trigger_contract.py` + +**Interfaces:** +- Produces: + - `SCHEMA = "freight_rpa.outbound.v1"` + - `ACTION_OUTBOUND_EXPORT_BATCH = "outbound_export_batch"` + - `write_outbound_export_batch_trigger(run_no, units, meta) -> str | None` + - `outbound_trigger_dir()` / `outbound_drop_dir()` 读 `FREIGHT_RPA_SHARED_OUTBOUND_*` + - `OUTBOUND_EXPORT_CAPABILITY = "outbound_export"` + +- [ ] **Step 1: 契约测试** + +```python +from app.services.freight_rpa.outbound import trigger_io +from app.services.freight_rpa.common.worker_heartbeat import OUTBOUND_EXPORT_CAPABILITY + +def test_outbound_trigger_constants(): + assert trigger_io.SCHEMA == "freight_rpa.outbound.v1" + assert trigger_io.ACTION_OUTBOUND_EXPORT_BATCH == "outbound_export_batch" + assert OUTBOUND_EXPORT_CAPABILITY == "outbound_export" +``` + +- [ ] **Step 2: 实现**(逐函数对照 `inbound/trigger_io.py` 与 `assert_receipt_rpa_worker_ready`,符号全部 outbound 化;**禁止**复用 inbound 目录配置键) + +- [ ] **Step 3: 跑测并 stage** + +--- + +### Task 8: 出站排程 job / finalize / archive / retention + 注册 + +**Files:** +- Create: `backend/app/services/schedule/freight_rpa_outbound_job.py` +- Create: `backend/app/services/schedule/freight_rpa_outbound_finalize.py` +- Create: `backend/app/services/schedule/freight_rpa_outbound_archive.py` +- Create: `backend/app/services/schedule/freight_rpa_outbound_retention.py` +- Modify: `backend/app/services/schedule/job_registry.py` +- Modify: `backend/app/services/schedule/__init__.py`(若需注册 excel headers) +- Test: `backend/tests/test_freight_rpa_outbound_job.py` + +**Interfaces:** +- Consumes: `write_outbound_export_batch_trigger`、`assert_outbound_rpa_worker_ready` +- Produces: + - `OUTBOUND_RPA_JOB_KEY = "freight-rpa-outbound"` + - `OUTBOUND_RETENTION_JOB_KEY = "freight-rpa-outbound-retention"` + - `AWAITING_OUTBOUND_RPA_CALLBACK_STATUS = "awaiting_outbound_rpa_callback"` + - 错误码使用 `RPA.OUTBOUND_*`(如 `RPA.OUTBOUND_TRIGGER_UNAVAILABLE`、`RPA.OUTBOUND_CALLBACK_TIMEOUT`),四语言 errors 本任务或 Task 13 补齐 + - 单元表写入 `FreightRpaOutboundUnitRun` + +- [ ] **Step 1: 对照入站 job 写「空 source 列表 fail-closed / worker 离线 failed」测试** + +- [ ] **Step 2: 复制入站四文件并全文替换符号**(`receipt`→`outbound` 语义处改为 outbound;状态串不要沿用 `awaiting_receipt_*`) + +- [ ] **Step 3: `job_registry` 注册两个 platform job** + +- [ ] **Step 4: 跑测并 stage** + +--- + +### Task 9: 出站回调 API + report_archive ingest + +**Files:** +- Create: `backend/app/services/freight_rpa/outbound/report_archive.py` +- Modify: `backend/app/api/freight_rpa.py` +- Modify: `scripts/freight_rpa/common/rpa_callbacks.py`(若 Task 7 未完) +- Test: `backend/tests/test_freight_rpa_outbound_callback.py` +- Optional Create: `backend/app/services/freight_rpa/common/drop_path.py`(若抽取共用「drop 根 + 文件名」解析,供 outbound 使用;抽取时入站可后续再迁,本任务不强制改 inbound) + +**Interfaces:** +- Produces: `ingest_outbound_callback(payload) -> None`;`_read_outbound_callback_file(file_path: str) -> bytes`;路由: + - `POST /api/freight-rpa/outbound-batch-ready` + - `POST /api/freight-rpa/outbound-unit-progress` + - `POST /api/freight-rpa/outbound-batch-progress` +- 归档成功后 `dispatch_report_fact(report_kind='outbound', ...)`(handler 可在 Task 10 注册前用测内临时 register) +- 路径解析语义与入站 `_read_inbound_callback_file` 一致(见 Global Constraints) + +- [ ] **Step 1: 先写跨机路径回归测(必须红)** + +```python +def test_read_outbound_callback_file_accepts_windows_absolute_path(tmp_path, app): + """Worker 上报 C:\\...\\drop\\foo.xlsx 时,Linux 侧只按文件名拼本机 drop 根。""" + drop = tmp_path / "outbound_drop" + drop.mkdir() + target = drop / "foo.xlsx" + target.write_bytes(b"PK\x03\x04fake") + with app.app_context(): + app.config["FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR"] = str(drop) + from app.services.freight_rpa.outbound.report_archive import _read_outbound_callback_file + data = _read_outbound_callback_file(r"C:\HxopsRpaTest\data\freight_rpa\outbound\drop\foo.xlsx") + assert data.startswith(b"PK") + + +def test_read_outbound_callback_file_rejects_traversal(tmp_path, app): + drop = tmp_path / "outbound_drop" + drop.mkdir() + with app.app_context(): + app.config["FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR"] = str(drop) + from app.services.freight_rpa.outbound.report_archive import _read_outbound_callback_file + from app.core.errors import ValidationError + with pytest.raises(ValidationError): + _read_outbound_callback_file(r"..\..\etc\passwd") +``` + +另测:`file_path="foo.xlsx"`(仅文件名)同样成功。 +Run: `pytest tests/test_freight_rpa_outbound_callback.py -k windows_absolute -v` +Expected: FAIL(函数未实现) + +- [ ] **Step 2: 回调 schema 校验失败测试**(错误 schema → 4xx) + +- [ ] **Step 3: 实现 `_read_outbound_callback_file` + archive** + +最小实现(对照入站,**禁止** `Path(file_path).read_bytes()` 直接读回调串): + +```python +def _read_outbound_callback_file(file_path: str) -> bytes: + configured_root = str(outbound_drop_dir() or "").strip() + if not configured_root: + raise ValidationError("outbound callback file root is unavailable", code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID") + root = Path(configured_root).resolve() + name = Path(str(file_path).replace("\\", "/")).name + path = (root / name).resolve() + try: + path.relative_to(root) + except ValueError as exc: + raise ValidationError( + "outbound callback file is outside outbound drop root", + code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID", + ) from exc + if path.suffix.lower() != ".xlsx" or not path.is_file(): + raise ValidationError( + "outbound callback file must be an existing xlsx", + code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID", + ) + ... + return path.read_bytes() +``` + +**不要**移植已删除的 `deliver_inbound_file`。 + +- [ ] **Step 4: 接线路由与鉴权(与入站回调同 ToolApiKey 机制)** + +- [ ] **Step 5: 跑测并 stage**(含 Step 1 路径测必须绿) + +--- + +### Task 10: 调拨 outbound_trigger_service + handler/sink + +**Files:** +- Create: `backend/app/services/in_transit_transfer/outbound_trigger_service.py` +- Create: `backend/app/services/in_transit_transfer/outbound_report_handler.py` +- Modify: `backend/app/services/shipping_notice/rpa_sinks.py`(`register_outbound_sinks`) +- Modify: `backend/app/__init__.py` 或组合根调用处(与 `register_inbound_sinks` 并列) +- Modify: `backend/app/services/freight_rpa/reports/queries.py`(`get_outbound_config` / `list_outbound_configured_source_codes`,对照 inbound) +- Test: `backend/tests/services/in_transit_transfer/test_outbound_trigger_service.py` + +**Interfaces:** +- Produces: + - `trigger_outbound_rpa(...)` / `trigger_outbound_rpa_batch(...)` + - `handle_outbound_report(fact) -> None`(对称 `handle_inbound_report`:推进等待中的出站相关 SourceJob;无等待任务则 no-op;可重入) + - `register_outbound_sinks()` → `register_report_handler('outbound', handle_outbound_report)` + +- [ ] **Step 1: 缺配置 fail-closed 测试** + +- [ ] **Step 2: 实现 trigger + handler**(对照 inbound 文件;调拨状态机字段名以现有 outbound `record_kind` / SourceJob 为准,禁止猜新状态——若入站 handler 推 `waiting_rpa_callback`→`file_ready`,出站同一套等待态字段) + +- [ ] **Step 3: 组合根注册** + +- [ ] **Step 4: 跑测并 stage** + +--- + +### Task 11: 管理端来源站点出站配置卡 + 排程运维 UI + +**Files:** +- Modify: `frontend/src/features/admin/modules/freight-rpa/FreightRpaPage.vue` +- Create: `frontend/src/features/admin/modules/freight-rpa/outboundReportConfigForm.ts`(若 Task 6 未建) +- Modify: `frontend/src/features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminRuns.ts` +- Modify: `backend/app/api/schedule/runs.py`(`outbound-rpa-units` list/retry、`outbound-raw-zip`) +- Modify: 四语言 admin schedule 文案 +- Test: vitest 组件/ composable 窄测;后端 units API 测 + +**Interfaces:** +- Produces: 来源站点第三折叠「出站报表配置」;排程 scope `outbound`;`rpaWorkerStatusScope: 'onhand'|'inbound'|'outbound'` + +- [ ] **Step 1: Vue —— 在入站配置块后复制一块出站**,绑定 `outboundConfig`,保存调 `saveOutboundReportConfig`;解析下拉 `purpose === 'outbound'` + +- [ ] **Step 2: 排程 —— 对齐 inbound 的 worker 徽标与 raw-zip 下载按钮** + +- [ ] **Step 3: 后端 units/retry/raw-zip 对照 inbound 路由实现** + +- [ ] **Step 4: `cd frontend && npm run build`** Expected: PASS + +- [ ] **Step 5: Stage** + +--- + +### Task 12: Windows Outbound Worker 脚本 + +**Files:** +- Create: `scripts/freight_rpa/outbound/outbound_rpa_worker.py` +- Create: `scripts/freight_rpa/outbound/start_outbound_worker.ps1` +- Create: `scripts/freight_rpa/outbound/register_outbound_worker_tasks.ps1` +- Create: `scripts/freight_rpa/outbound/outbound_dbs_export.py` +- Create: `scripts/freight_rpa/outbound/outbound_crane_export.py` +- Modify: `scripts/freight_rpa/README.md` +- Modify: `scripts/freight_rpa/common/rpa_callbacks.py`(确认 outbound 端点) +- Test: 后端侧可用「trigger 文件名/schema」合同测;Worker 无 pytest 时用脚本静态断言(读常量) + +**Interfaces:** +- Consumes: `freight_rpa.outbound.v1` / `outbound_export_batch` +- Produces: 轮询 `FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR`;回调 outbound-*-progress/ready;心跳 `outbound_export`;Worker ID `*-outbound` + +- [ ] **Step 1: 复制 inbound Worker 目录结构并替换常量/路径/回调** + +- [ ] **Step 2: 回调 `file_path` 只报文件名** + +在 outbound Worker 组装 batch-ready / unit 成功载荷时,`file_path`(及若有的等价字段)必须是 `Path(local_drop_file).name`,**禁止**把 `C:\\...\\drop\\xxx.xlsx` 整串作为契约主值(与入站现行「后端可容忍绝对路径、Worker 应只报文件名」一致)。在 worker 内加注释指向规格 §4.2 跨机路径契约。 + +- [ ] **Step 3: DBS 使用配置 `report_path`;Crane 固定出站页**(页面选择器字符串实现时按货代实名填写,注释标明来源截图/环境;禁止误用 Inbound Details) + +- [ ] **Step 4: ps1 注入 `FREIGHT_RPA_WORKER_ID=-outbound`、outbound logs 目录** + +- [ ] **Step 5: Stage `scripts/freight_rpa/outbound/` 与 README** + +--- + +### Task 13: 错误码四语言 + 文档 + ADR + 规格状态 + +**Files:** +- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/errors.json` +- Modify: `docs/features/freight-rpa/GLOSSARY.md` +- Modify: `docs/features/shipping-notice/technical.md`(改名 + 出站部署节,对称 §1.9) +- Modify: `docs/funclist.md` +- Modify: `docs/adr/0004-freight-rpa-report-ownership.md` +- Modify: `docs/superpowers/specs/2026-10-19-freight-rpa-outbound-and-rename-design.md`(状态 → 已有实施计划) +- Modify: 环境变量权威文档(若缺 OUTBOUND 项则补齐说明,不改真实密钥) + +**Interfaces:** 无代码接口 + +- [ ] **Step 1: 为 Task 8/9 引入的每个新 `code=` 补四语言** + +- [ ] **Step 2: Glossary —— Outbound 改为已交付抓取;注明无 deliveries、无工作台收料页;Inbound 用户文案「入站」** + +- [ ] **Step 3: ADR 0004 Consequences 增加「本阶段注册 outbound handler」** + +- [ ] **Step 4: 规格头状态改为「已有实施计划」并链到本 plan 路径** + +- [ ] **Step 5: Stage 文档与 errors.json** + +--- + +### Task 14: 总闸门(grep + 构建) + +**Files:** +- Create/Modify: `backend/tests/test_freight_rpa_outbound_rename_gate.py` + +**Interfaces:** 无 + +- [ ] **Step 1: 写入总闸门测试** + +```python +def test_no_receipt_raw_zip_route(): + text = Path("app/api/schedule/runs.py").read_text(encoding="utf-8") + assert "receipt-raw-zip" not in text + assert "inbound-raw-zip" in text + +def test_outbound_purpose_not_catalog_in_validate_docstring(): + text = Path("app/services/shipping_notice/onhand_parsing_profile.py").read_text(encoding="utf-8") + assert "purpose in {'inbound', 'outbound'}" in text or 'purpose in {"inbound", "outbound"}' in text + +def test_no_outbound_notification_deliveries_table_reference(): + ... +``` + +- [ ] **Step 2: 跑闸门 + 出站相关测 + frontend build** + +Run: + +```bash +cd backend && pytest tests/test_freight_rpa_outbound_rename_gate.py tests/test_freight_rpa_inbound_slim_gate.py tests/test_parsing_profile_purpose.py tests/test_freight_rpa_outbound_models.py -v +cd ../frontend && npm run build +``` + +Expected: 全部 PASS + +- [ ] **Step 3: Stage 闸门测试** + +--- + +## Spec coverage(自检) + +| 规格项 | 任务 | +| --- | --- | +| 报表规则 / 来源站点 / 入站报表文案 | T1 | +| 出站报表配置 UI | T11(API T6) | +| outbound 异动解析 | T5 | +| 出站三表 + 迁移 | T4 | +| 无 outbound deliveries;删入站 deliveries | T2、T4 | +| 下线工作台收料页 | T2 | +| inbound-raw-zip | T3 | +| trigger/心跳/回调/排程/retention | T7–T9、T8 | +| 按需 trigger + sink | T10 | +| Worker 脚本 | T12 | +| 错误码 / 文档 / ADR | T13 | +| 单发布总闸门 | T14 | +| 启用非硬门槛 | T6 校验不接入 activation checks(显式不改 `_source_activation_checks`) | +| Crane 固定出站页 | T12 | +| class-prefix 前置 | Global Constraints | +| 跨机路径:Windows `file_path` → Linux drop 文件名映射 | T9(测+读)、T12(Worker 只报文件名)、Global Constraints | + +无 TBD。入站历史错误码 `RPA.RECEIPT_*` **本计划不强制改名**(避免无收益大爆炸);用户可见「收料」文案必须清掉。 diff --git a/docs/superpowers/plans/2026-10-19-transfer-evidence-stream-ui.md b/docs/superpowers/plans/2026-10-19-transfer-evidence-stream-ui.md new file mode 100644 index 00000000..fc8c9fe3 --- /dev/null +++ b/docs/superpowers/plans/2026-10-19-transfer-evidence-stream-ui.md @@ -0,0 +1,463 @@ +# 调拨证据流状态、重试与下载 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:** 来源选择卡按调拨类型声明的记录类型,分行内括号显示入站/出站状态,并用一个批量按钮和一个下载按钮按流重试、按目录打包。 + +**Architecture:** 一条调拨类型要哪些证据流,从它已有的范围规则里推导:字段为 `record_kind` 的规则值。没有这种规则时结果是 `("inbound", "outbound")`。状态投影、批量重试、下载打包和匹配圈档都读这个推导结果。不新增表字段,不改调拨类型表单。`resolve_source_file_status` 增加 `record_kind`,默认 `inbound`,这只是单流查询的参数缺省,不是类型没写规则时的业务默认。来源 API 在保留入站扁平字段的同时增加 `streams`。前端只按 `streams` 画括号。 + +**Tech Stack:** Flask、SQLAlchemy 2.0、Alembic、Vue 3、Vitest、pytest。后端测试在 `backend/`,Python 用 `backend/.venv/Scripts/python.exe`。 + +**Spec:** `docs/superpowers/specs/2026-10-19-transfer-evidence-stream-ui-design.md` + +## Global Constraints + +- 状态粒度是来源实例 × 记录类型。不拆来源行,不做「部分就绪」。 +- 不新增调拨类型字段,不改调拨类型表单。入站还是出站,读该类型已有的范围规则:字段为 `record_kind`(表单下拉里的「记录类型」)的那几条,值里的 `inbound` / `outbound`。 +- 一条类型没有「记录类型」规则时,入站和出站都要。规则里只写了其中一种,就只要那一种。来源卡、批量重试、下载、圈档都读这一结果,不看类型编码。 +- 来源行只显示当前调拨类型声明的证据流。缺报表配置时状态为「未配置」。 +- 行形态:`DSV360_AWSBI_BYAWSCMH01 [入站 √就绪 ↻] [出站 ⟳抓取中]`。重试是括号内的 `↻`,可读名称「重试入站」或「重试出站」。抓取中不显示 `↻`。行上不出现「重试」「文件」。 +- 点状态字展开该流当天清单:文件名、抓取时间、sha256、文件大小、预览、下载。不解析 Excel,不新增行数字段。 +- 选择条仍是三个按钮。下载文案为「下载证据文件」。压缩包名 `evidence-files-.zip`,路径 `inbound//` 与 `outbound//`,只打包当前类型所需且已就绪的文件。 +- 批量重试仍是一个按钮。按当前调拨类型的 `record_kinds`,只重试尚未就绪、且不是抓取中、且已配置的流。行上的 `↻` 可对已就绪的流强制重试。 +- 确认匹配:该来源每一条所需流为 `ready` 或 `no_data` 才可提交。混合选择沿用披露条,并写明记录类型。 +- 圈档固定条件里的 `record_kind='inbound'` 改为 `record_kinds_of(该类型的范围规则)`。没有类型对象的调用方显式只圈入站。 +- 不拆两个下载按钮,不拆两个批量按钮,不为出站复制来源实例行,不改 Worker、排程和回调契约。 +- 新增用户可见文案同时写入 `zh-CN` / `zh-TW` / `en` / `th`。 +- 每个任务结束于 `git add`。不要在计划步骤里 `git commit`。 + +## File Structure + +- `backend/app/services/in_transit_transfer/scope_rules.py`:从已有范围规则推导 `record_kinds_of`。不改表,不写迁移。 +- `backend/app/services/in_transit_transfer/source_file_status.py`:按 `record_kind` 投影,缺配置为 `unconfigured`。 +- `backend/app/api/in_transit_transfer/__init__.py`:`/sources` 增加 `streams`;重试与批量重试接受记录类型;下载改目录;新增证据清单。 +- `backend/app/services/in_transit_transfer/matching_service.py`:`create_matching` 把 `record_kinds_of(类型.scope_rules)` 传入圈档底座。底座默认仍是入站。 +- `frontend/src/features/chat/types/transfer.types.ts`、`api/transfer.api.ts`、`components/messages/TransferSourceSelectCard.vue`:括号行、清单、一个下载按钮、一个批量按钮。 +- `frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json`:来源卡新文案。调拨类型页不改。 + +## 界面框线 + +调拨类型页不改。要出站时,仍用现有范围规则,字段选「记录类型」,值写 `outbound` 或同时写 `inbound` 与 `outbound`。 + +```text ++--------------------------------------------------+ +| 范围规则 | +| 字段 [记录类型 v] 匹配 [等于 v] 值 [outbound] | ++--------------------------------------------------+ +``` + +Task 7 只改来源选择卡。当前类型的范围规则里,「记录类型」只写了 inbound: + +```text ++----------------------------------------------------------+ +| 选择出入站来源实例 | +| 调拨类型 (在途仓至HUB仓) HUB仓维修出 HUB仓维修入 | +| 异动日期 [2026-10-14] ~ [2026-10-14] | +| 已选 10 个来源实例,其中 10 个可重试 | +| [批量重试 RPA] [下载证据文件] [清空选择] | +| CRANE | +| [x] DSV360_AWSBI_BYAWSCMH01 [入站 √就绪 ↻] | +| [确认范围并匹配] | ++----------------------------------------------------------+ +``` + +同一张卡。当前类型没有「记录类型」规则,或规则值里 inbound 和 outbound 都有。点「入站 √就绪」后,清单开在该行下面。抓取中的括号里没有 ↻。 + +```text ++----------------------------------------------------------+ +| 调拨类型 (没有记录类型规则,或两种值都有) | +| [x] DSV360_AWSBI_BYAWSCMH01 | +| [入站 √就绪 ↻] [出站 ⟳抓取中] | +| +----------------------------------------------+ | +| | Inbound_20261014.xlsx | | +| | 2026-10-14 09:12 · 128 KB · a1b2c3d4… | | +| | [预览] [下载] | | +| +----------------------------------------------+ | +| [x] DSV360_AWSBI_BYAWSPRD01 | +| [入站 —无数据 ↻] [出站 —未配置] | ++----------------------------------------------------------+ +``` + +「未配置」的括号里没有 ↻。文件大小来自归档的 `file_size`,框线里的 `128 KB` 只是示意。 + +--- + +### Task 1: 从已有范围规则推导证据流 + +**Files:** +- Modify: `backend/app/services/in_transit_transfer/scope_rules.py` +- Test: `backend/tests/services/in_transit_transfer/test_scope_rules.py`(没有则新建) + +**Interfaces:** +- Consumes: `parse_scope_rules` 得到的 `ScopeRule`。字段名已在 `SCOPE_FIELDS` 里,就是 `record_kind`。 +- Produces: `record_kinds_of(rules: tuple[ScopeRule, ...]) -> tuple[str, ...]`。只认值 `inbound` 与 `outbound`,按这个顺序去重。没有任何 `field == "record_kind"` 的规则时返回 `("inbound", "outbound")`。多条这种规则取值的交集;交集为空时返回 `()`。 + +- [ ] **Step 1: Write the failing test** + +```python +def test_record_kinds_of_reads_existing_scope_rule(): + """没有记录类型规则时入站和出站都要;只写 outbound 时只要出站。""" + assert record_kinds_of(parse_scope_rules([ + {"field": "doc_no", "match": "prefix", "values": ["HOM"]}, + ])) == ("inbound", "outbound") + assert record_kinds_of(parse_scope_rules([ + {"field": "record_kind", "match": "equals", "values": ["outbound"]}, + ])) == ("outbound",) + assert record_kinds_of(parse_scope_rules([ + {"field": "record_kind", "match": "in", "values": ["outbound", "inbound"]}, + ])) == ("inbound", "outbound") +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_scope_rules.py::test_record_kinds_of_reads_existing_scope_rule -v` + +Expected: FAIL,`record_kinds_of` 未定义。 + +- [ ] **Step 3: Write minimal implementation** + +在 `scope_rules.py` 实现 `record_kinds_of`。不要加模型列,不要写迁移,不要改调拨类型表单。启用类型 API 若把推导结果放进响应,字段名用 `record_kinds`,值只能来自这个函数。 + +- [ ] **Step 4: Run test to verify it passes** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_scope_rules.py -v` + +Expected: PASS + +- [ ] **Step 5: Stage changes** + +```bash +git add backend/app/services/in_transit_transfer/scope_rules.py backend/tests/services/in_transit_transfer/test_scope_rules.py +``` + +--- + +### Task 2: 按记录类型投影文件状态 + +**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:** +- Consumes: `queries.get_inbound_config` / `get_outbound_config`,`latest_usable_inbound_file`,出站文件与 `FreightRpaOutboundUnitRun` 的同口径查询。 +- Produces: `resolve_source_file_status(*, source_code: str, record_kind: str = "inbound") -> dict`。`record_kind="inbound"` 时返回值与今天相同。`record_kind="outbound"` 且 `get_outbound_config` 为 `None` 时返回 `{"file_status": "unconfigured", "has_ready_file": False, "file_no": None, "file_sha256": None}`。 + +- [ ] **Step 1: Write the failing test** + +```python +def test_outbound_without_config_is_unconfigured(monkeypatch): + """没有出站报表配置时,出站流是未配置,入站投影函数签名仍可只传来源。""" + monkeypatch.setattr( + "app.services.in_transit_transfer.source_file_status.get_outbound_config", + lambda source_code: None, + ) + status = resolve_source_file_status(source_code="DSV360_AWSBI", record_kind="outbound") + assert status["file_status"] == "unconfigured" + assert status["has_ready_file"] is False +``` + +再写一条:出站存在可用文件时 `file_status == "ready"`。查询函数按入站 `latest_usable_inbound_file` 的返回形状做 monkeypatch,不连真实 MinIO。 + +- [ ] **Step 2: Run test to verify it fails** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_source_file_status.py::test_outbound_without_config_is_unconfigured -v` + +Expected: FAIL,`record_kind` 意外参数或没有 `unconfigured`。 + +- [ ] **Step 3: Write minimal implementation** + +`record_kind` 不是 `inbound`/`outbound` 时抛 `ValidationError`。入站分支保持现有顺序:可用文件 → 解析失败 → 进行中单元 → 失败 → `no_data` → 过期 → `none`。出站先查配置,没有则 `unconfigured`;有配置则用出站文件表和 `FreightRpaOutboundUnitRun` 走同一顺序。默认参数 `record_kind="inbound"`,不改 `execution_service` 等现有调用。 + +- [ ] **Step 4: Run test to verify it passes** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_source_file_status.py tests/services/in_transit_transfer/test_evidence_sync.py -v` + +Expected: PASS。既有入站用例仍绿。 + +- [ ] **Step 5: Stage changes** + +```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: 来源列表返回 streams + +**Files:** +- Modify: `backend/app/api/in_transit_transfer/__init__.py`(`transfer_sources_api`) +- Test: `backend/tests/api/test_in_transit_transfer_api.py` + +**Interfaces:** +- Consumes: `resolve_source_file_status(*, source_code, record_kind)`。 +- Produces: 每个来源除现有 `file_status` / `has_ready_file`(等于入站流,供尚未改完的前端)外,增加 + +```python +"streams": [ + {"record_kind": "inbound", "file_status": "ready", "has_ready_file": True, "file_no": "...", "file_sha256": "..."}, + {"record_kind": "outbound", "file_status": "unconfigured", "has_ready_file": False, "file_no": None, "file_sha256": None}, +] +``` + +两条都返回,前端按类型过滤。 + +- [ ] **Step 1: Write the failing test** + +在来源列表用例中断言响应里 `DSV` 来源的 `streams` 长度为 2,且 `streams[0]["record_kind"] == "inbound"`,`file_status` 仍等于入站那条的 `file_status`。用现有测试夹具里的来源码,不要新造平台。 + +- [ ] **Step 2: Run test to verify it fails** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/api/test_in_transit_transfer_api.py -k sources -v` + +Expected: FAIL,响应没有 `streams`。 + +- [ ] **Step 3: Write minimal implementation** + +`transfer_sources_api` 对每个来源调用两次投影,组装 `streams`。扁平字段继续取 `record_kind="inbound"` 的结果。 + +- [ ] **Step 4: Run test to verify it passes** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/api/test_in_transit_transfer_api.py -k sources -v` + +Expected: PASS + +- [ ] **Step 5: Stage changes** + +```bash +git add backend/app/api/in_transit_transfer/__init__.py backend/tests/api/test_in_transit_transfer_api.py +``` + +--- + +### Task 4: 重试按证据流,批量按调拨类型 + +**Files:** +- Modify: `backend/app/api/in_transit_transfer/__init__.py`(`retry_source_rpa_api`、`retry_sources_rpa_batch_api`) +- Modify: `backend/app/services/in_transit_transfer/inbound_trigger_service.py` 与 `outbound_trigger_service.py`(只在 API 层选择调用哪个,不合并两个 trigger 实现) +- Test: `backend/tests/api/test_in_transit_transfer_api.py` + +**Interfaces:** +- Consumes: `trigger_inbound_rpa`、`trigger_outbound_rpa`、`trigger_*_rpa_batch`、`get_by_code(transfer_type).record_kinds`。 +- Produces: `POST /sources//retry-rpa` 请求体 `{"record_kind": "outbound"}`,缺省 `inbound`。`POST /sources/retry-rpa-batch` 请求体 `{"source_codes": [...], "transfer_type": "hub_to_hub"}`。批量结果每项增加 `record_kind`。已 `ready`、`fetching`、`unconfigured` 的流不写入 trigger。`no_data` / `failed` / `expired` / `none` / `parse_failed` 会进入对应流的重试。 + +- [ ] **Step 1: Write the failing test** + +```python +def test_batch_retry_skips_ready_inbound_and_triggers_outbound(client, monkeypatch): + """HUB 仓间调拨:入站已就绪不重抓,出站未就绪才触发。""" + def fail_inbound(**kwargs): + raise AssertionError("inbound batch") + + called = {} + + def record_outbound(**kwargs): + called["codes"] = kwargs["source_codes"] + return {"ok": True, "triggered": True} + + def status(*, source_code, record_kind="inbound"): + if record_kind == "outbound": + return {"file_status": "none", "has_ready_file": False, "file_no": None, "file_sha256": None} + return {"file_status": "ready", "has_ready_file": True, "file_no": "a.xlsx", "file_sha256": "abc"} + + monkeypatch.setattr(api_module, "trigger_inbound_rpa_batch", fail_inbound) + monkeypatch.setattr(api_module, "trigger_outbound_rpa_batch", record_outbound) + monkeypatch.setattr(api_module, "resolve_source_file_status", status) + response = client.post("/api/in-transit-transfer/sources/retry-rpa-batch", json={ + "source_codes": ["DSV360_AWSBI"], + "transfer_type": "hub_to_hub", + }) + assert response.status_code == 202 + assert called["codes"] == ["DSV360_AWSBI"] +``` + +`api_module` 指 `app.api.in_transit_transfer`。蓝图前缀是 `/api/in-transit-transfer`。夹具若没有启用的 `hub_to_hub`,本测试用 `create_config` 建一个,`record_kinds` 为 `["inbound", "outbound"]`。 + +- [ ] **Step 2: Run test to verify it fails** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/api/test_in_transit_transfer_api.py::test_batch_retry_skips_ready_inbound_and_triggers_outbound -v` + +Expected: FAIL,请求体没有 `transfer_type` 或仍只调用入站 batch。 + +- [ ] **Step 3: Write minimal implementation** + +单源端点读取 `record_kind`,出站走 `trigger_outbound_rpa`,`parse_failed` 仍只对入站做本地重解析;出站 `parse_failed` 重新触发出站 RPA。批量端点读取类型的 `record_kinds`,按流分组后最多写一个入站 batch 和一个出站 batch。`unconfigured` 记入结果 `ok: false`,`error_code` 用现有配置缺失码,不新增错误码。 + +- [ ] **Step 4: Run test to verify it passes** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/api/test_in_transit_transfer_api.py -k retry -v` + +Expected: PASS + +- [ ] **Step 5: Stage changes** + +```bash +git add backend/app/api/in_transit_transfer/__init__.py backend/tests/api/test_in_transit_transfer_api.py +``` + +--- + +### Task 5: 证据压缩包与当天清单 + +**Files:** +- Modify: `backend/app/api/in_transit_transfer/__init__.py`(`download_source_inbound_files_api`,并新增清单路由) +- Test: `backend/tests/api/test_in_transit_transfer_api.py` + +**Interfaces:** +- Consumes: 可用入站/出站归档文件、`file_asset_storage.get_bytes`、`file_asset_storage.presigned_get_url`。 +- Produces: + - `POST /sources/inbound-files` 请求体增加 `transfer_type`。压缩包内路径为 `inbound//` 或 `outbound//`。下载名 `evidence-files-.zip`。审计事件类型仍是 `TRANSFER_INBOUND_FILES_DOWNLOADED`。 + - `GET /sources//evidence-files?record_kind=inbound` 返回 `[{file_id, original_filename, created_at, sha256, file_size, presigned_url}]`,只含当天可用文件。签发 URL 时写同一审计事件,`aggregate_id` 为 `source_code`。 + +- [ ] **Step 1: Write the failing test** + +用 `zipfile.ZipFile` 读响应体。类型的范围规则把记录类型收成只要 inbound 时,名单包含 `inbound/DSV360_AWSBI/Inbound.xlsx`,且不包含 `outbound/`。没有记录类型规则时,两种就绪文件都打进包。清单用例断言 JSON 含 `file_size` 与 `presigned_url`,不含解析出的行数。 + +- [ ] **Step 2: Run test to verify it fails** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/api/test_in_transit_transfer_api.py -k "evidence or inbound_files" -v` + +Expected: FAIL,路径仍是 `-` 或清单路由 404。 + +- [ ] **Step 3: Write minimal implementation** + +下载循环按类型的 `record_kinds` 各取该来源最新可用文件,`archive.writestr(f"{kind}/{code}/{safe_name}", data)`。两种都没有文件时仍 `NotFoundError(..., code="SHIPPING.INBOUND_FILE_NOT_FOUND")`。清单查询复用下载用的可用文件条件,但返回当天全部可用文件而不只最新一份。`presigned_get_url(..., expires_seconds=300)`。 + +- [ ] **Step 4: Run test to verify it passes** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/api/test_in_transit_transfer_api.py -k "evidence or inbound_files" -v` + +Expected: PASS + +- [ ] **Step 5: Stage changes** + +```bash +git add backend/app/api/in_transit_transfer/__init__.py backend/tests/api/test_in_transit_transfer_api.py +``` + +--- + +### Task 6: 圈档跟随调拨类型的记录类型 + +**Files:** +- Modify: `backend/app/services/in_transit_transfer/matching_service.py`(`_circle_ledger_base_query` 与 `create_matching` 附近的调用) +- Test: `backend/tests/services/in_transit_transfer/test_matching_service.py` + +**Interfaces:** +- Consumes: `record_kinds_of(config.scope_rules)`。 +- Produces: `_circle_ledger_base_query(*, record_kinds: tuple[str, ...], exclude_occupied_by_matching_id: int | None = None)`。`record_kinds` 必传,避免再用入站当隐式默认。`_circle_ledger_records` 增加同名参数并传给底座。`create_matching` 与 `circle_ledger_records_scope_union` 传入 `record_kinds_of(...)`。没有类型对象的调用点显式传入 `("inbound",)`。 + +- [ ] **Step 1: Write the failing test** + +```python +def test_hub_to_hub_circles_outbound_ledger_rows(deps): + """没有记录类型规则的类型圈入出站档;范围规则写明只要 inbound 的类型不圈。""" + _insert_ledger(source_code="DSV360_AWSBI", record_kind="outbound", doc_no="HOX1", movement_date="2026-10-14") + circled = create_matching( + source_codes=["DSV360_AWSBI"], + business_date="2026-10-14", + movement_date_from="2026-10-14", + movement_date_to="2026-10-14", + transfer_type="hub_to_hub", + deps=deps, + ) + assert "HOX1" in {item.doc_no for item in items_of(circled)} + inbound_only = create_matching( + source_codes=["DSV360_AWSBI"], + business_date="2026-10-14", + movement_date_from="2026-10-14", + movement_date_to="2026-10-14", + transfer_type="in_transit_to_hub", + deps=deps, + ) + assert "HOX1" not in {item.doc_no for item in items_of(inbound_only)} +``` + +`_insert_ledger` 与 `items_of` 按本文件已有的落档、读明细写法就地写,断言只看 `doc_no`。`hub_to_hub` 的范围规则不写记录类型。`in_transit_to_hub` 的范围规则必须有一条 `record_kind` 等于 `inbound`,否则会把 `HOX1` 也圈进来。 + +- [ ] **Step 2: Run test to verify it fails** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_matching_service.py::test_hub_to_hub_circles_outbound_ledger_rows -v` + +Expected: FAIL,出站行被 `record_kind='inbound'` 滤掉。 + +- [ ] **Step 3: Write minimal implementation** + +底座过滤改为 `TransferMovementLedger.record_kind.in_(record_kinds)`。`_circle_ledger_records` 把 `record_kinds` 传给底座。`create_matching` 传入 `record_kinds_of(当前类型.scope_rules)`。`circle_ledger_records_scope_union` 对每个 `config` 传入 `record_kinds_of(config.scope_rules)`。没有类型对象的调用点不改参数。 + +- [ ] **Step 4: Run test to verify it passes** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_matching_service.py -v` + +Expected: PASS + +- [ ] **Step 5: Stage changes** + +```bash +git add backend/app/services/in_transit_transfer/matching_service.py backend/tests/services/in_transit_transfer/test_matching_service.py +``` + +--- + +### Task 7: 来源选择卡与调拨类型表单 + +**Files:** +- Modify: `frontend/src/features/chat/types/transfer.types.ts` +- Modify: `frontend/src/features/chat/api/transfer.api.ts` +- Modify: `frontend/src/features/chat/components/messages/TransferSourceSelectCard.vue` +- Modify: `frontend/src/features/chat/components/messages/TransferSourceSelectCard.spec.ts` +- Modify: `frontend/src/locales/zh-CN/chat.json`、`zh-TW/chat.json`、`en/chat.json`、`th/chat.json` + +**Interfaces:** +- Consumes: `streams[]`、`record_kinds`、`POST retry-rpa` 的 `record_kind`、`POST retry-rpa-batch` 的 `transfer_type`、`GET evidence-files`、`POST inbound-files` 的 `transfer_type`。 +- Produces: 卡片只渲染当前类型 `record_kinds` 里的括号。状态字按钮的 `aria-expanded` 控制行下清单。`↻` 的 `aria-label` 为 i18n「重试入站」或「重试出站」。`file_status === 'fetching'` 时不渲染 `↻`。 + +- [ ] **Step 1: Write the failing test** + +在 `TransferSourceSelectCard.spec.ts` 增加来源: + +```typescript +const hubSource = { + source_code: 'DSV360_AWSBI_BYAWSCMH01', + display_name: 'CMH01', + platform: 'crane', + enabled: true, + has_ready_file: true, + file_status: 'ready' as const, + streams: [ + { record_kind: 'inbound' as const, file_status: 'ready' as const, has_ready_file: true }, + { record_kind: 'outbound' as const, file_status: 'fetching' as const, has_ready_file: false }, + ], +}; +``` + +断言类型为 `hub_to_hub`(两种记录类型)时,文本含 `[入站 √就绪]` 与 `[出站 ⟳抓取中]`,出站括号内没有重试按钮,入站括号内的按钮 `aria-label` 为「重试入站」。类型为 `in_transit_to_hub` 时不出现「出站」。组件内不出现按钮文案「文件」。下载按钮文案为「下载证据文件」。 + +- [ ] **Step 2: Run test to verify it fails** + +Run: `npm run test -- src/features/chat/components/messages/TransferSourceSelectCard.spec.ts` + +工作目录:`frontend/`。 + +Expected: FAIL,仍渲染单个「文件已就绪」和「下载入站文件」。 + +- [ ] **Step 3: Write minimal implementation** + +`TransferSourceOption.streams` 为 `{ record_kind: 'inbound' | 'outbound'; file_status: ...; has_ready_file: boolean }[]`。状态字映射:`ready` → `√就绪`,`fetching` → `⟳抓取中`,`failed` → `×失败`,`no_data` → `—无数据`,`expired` → `!已过期`,`parse_failed` → `!解析失败`,`none` → `—无文件`,`unconfigured` → `—未配置`。前缀用 i18n「入站」「出站」。括号用文本,不用额外色块区分记录类型;就绪/失败仍可用现有绿/红字色,文字始终在。 + +点状态字调用 `listEvidenceFiles(sourceCode, recordKind)`,清单插在该行下方,按钮只有「预览」「下载」,都打开 `presigned_url`。批量重试提交 `{ source_codes, transfer_type }`。单行 `↻` 提交 `{ record_kind }`。确认门禁改为:所选类型的每条流都是 `ready` 或 `no_data`。披露条把未就绪流写成「来源编码 入站 抓取中」。 + +`downloadFiles` 的 zh-CN 改为「下载证据文件」,zh-TW「下載證據文件」,en「Download evidence files」,th「ดาวน์โหลดไฟล์หลักฐาน」。新增键走 `chat.transfer.streamInbound`、`streamOutbound`、`retryInbound`、`retryOutbound`、`previewEvidence`、`downloadEvidence`,四语言一起补。不改 `TransferTypesPage.vue`。来源卡用启用类型接口带回的 `record_kinds`(由 `record_kinds_of` 算出)决定画几条括号。 + +卡片上的来源编码、状态括号保持现在的 `text-xs` 密度,不把重试按钮放大到 44px。 + +- [ ] **Step 4: Run test to verify it passes** + +Run: `npm run test -- src/features/chat/components/messages/TransferSourceSelectCard.spec.ts` + +Expected: PASS + +- [ ] **Step 5: Stage changes** + +```bash +git add frontend/src/features/chat/types/transfer.types.ts frontend/src/features/chat/api/transfer.api.ts frontend/src/features/chat/components/messages/TransferSourceSelectCard.vue frontend/src/features/chat/components/messages/TransferSourceSelectCard.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 +``` diff --git a/docs/superpowers/plans/2026-10-21-transfer-current-file-reparse.md b/docs/superpowers/plans/2026-10-21-transfer-current-file-reparse.md new file mode 100644 index 00000000..6597788b --- /dev/null +++ b/docs/superpowers/plans/2026-10-21-transfer-current-file-reparse.md @@ -0,0 +1,571 @@ +# 当前归档重新解析 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:** 新服务 `reparse_current_file` 自己找出站或入站的最新可用归档,然后调用已经存在的 `sync_outbound_source_rows` / `sync_source_rows`(它们只 flush)。结构错误沿用现有 `mark_*_parse_failure`。HTTP 层只做鉴权、参数和 envelope。前端按钮只画在清单第一行,请求体不带 `file_id`。 + +**Tech Stack:** Flask、SQLAlchemy 2.0、Vue 3、Vitest、pytest。后端测试在 `backend/`,Python 用 `backend/.venv/Scripts/python.exe`。前端测试在 `frontend/`,用 `npx vitest run`。 + +**Spec:** `docs/superpowers/specs/2026-10-21-transfer-current-file-reparse-design.md` + +## Global Constraints + +- 入站和出站各自有「重新解析」。当天该流已有可用归档时可以点,状态是就绪或解析失败都可以。 +- 只解析该流当前最新一份可用归档(`created_at`、`id` 倒序第一条,与 `latest_usable_*_file` 相同),并幂等写入异动档。不写 RPA trigger。 +- 请求不接受 `file_id`。服务端自己取最新一份,避免清单过期时重放历史文件。 +- 同一份文件再解析一次:摘要未变则跳过已有档行,不另插一行。 +- 没有可用归档:422 `TRANSFER.CURRENT_REPARSE_NO_FILE`。 +- 有归档但没有已发布的对应 purpose 规则:422 `TRANSFER.CURRENT_REPARSE_NO_PROFILE`。不把文件标成解析失败。规则缺失不是文件错误。 +- 结构校验失败(`MovementFileSchemaError`):回滚档行,把 `parse_failed` 写到当前文件,HTTP 200,`ok: false`,`file_status: parse_failed`,带 `error_message`。 +- 其他异常(数据库截断、连接失败):回滚,不标解析失败,HTTP 200,`ok: false`,`error_message` 为异常文本。文件状态保持原投影。 +- 成功:HTTP 200,`ok: true`,返回 `inserted` / `updated` / `skipped` / `sealed_skipped` 和解析后的 `file_status`。审计沿用落档函数已有的 `TRANSFER_EVIDENCE_SYNCED`,不另造事件。 +- `file_version` 只经 `movement_file_version`。本入口不自己拼版本戳。 +- 展开清单后只有第一行显示「重新解析」。↻ 与 `POST /sources/{source_code}/retry-rpa` 不变。 +- 不调用 `POST /backlog/pending-match/reparse`,不删除已有档行。 +- 新增用户可见文案同时写入 `zh-CN` / `zh-TW` / `en` / `th`。新增 `error.code` 同步写入四份 `locales/*/errors.json`。 +- 每个任务结束于 `git add`。不要在计划步骤里 `git commit`。 + +## File Structure + +- `backend/app/services/in_transit_transfer/current_file_reparse.py`:取当前归档、调用既有落档函数、提交或回滚、返回计数。不触发 RPA,不拼 `file_version`。 +- `backend/app/api/in_transit_transfer/__init__.py`:新增 `POST /sources//reparse`。不改 `retry-rpa`。 +- `backend/tests/services/in_transit_transfer/test_current_file_reparse.py`:服务行为。 +- `backend/tests/api/test_in_transit_transfer_api.py`:无文件 422、无权限 403。 +- `frontend/src/features/chat/api/transfer.api.ts` 与 `types/transfer.types.ts`:请求与响应类型。 +- `frontend/src/features/chat/components/messages/TransferSourceSelectCard.vue`:第一行按钮。 +- `frontend/src/features/chat/components/messages/TransferMessageView.vue`:成功后 `loadSources`。 +- `frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json` 与 `errors.json`:按钮文案和两个错误码。 +- `docs/features/in-transit-transfer/technical.md`、`docs/funclist.md`:登记入口。 + +--- + +### Task 1: 当前文件重解析服务 + +**Files:** +- Create: `backend/app/services/in_transit_transfer/current_file_reparse.py` +- Create: `backend/tests/services/in_transit_transfer/test_current_file_reparse.py` +- Test: `backend/tests/services/in_transit_transfer/test_current_file_reparse.py` + +**Interfaces:** +- Consumes: `sync_outbound_source_rows(*, source_code: str, now: datetime) -> SyncOutcome | None`;`sync_source_rows(*, source_code: str, deps, business_date: str, now: datetime) -> SyncOutcome | None`;`latest_usable_outbound_file` / `latest_usable_inbound_file`;`mark_outbound_parse_failure` / `mark_inbound_parse_failure`;`resolve_source_file_status(*, source_code: str, record_kind: str) -> dict`;`MovementFileSchemaError`。 +- Produces: `reparse_current_file(*, source_code: str, record_kind: str, now: datetime) -> CurrentReparseResult`。`CurrentReparseResult` 字段:`source_code: str`、`record_kind: str`、`ok: bool`、`file_status: str`、`file_id: int | None`、`inserted: int`、`updated: int`、`skipped: int`、`sealed_skipped: int`、`error_code: str | None`、`error_message: str | None`。 + +- [ ] **Step 1: Write the failing test** + +新建 `backend/tests/services/in_transit_transfer/test_current_file_reparse.py`。文件头写明用途是锁定「当前归档重解析、不触发 RPA」。导入 `pytest`、`datetime`、`AppError`、`TransferAuditEvent`、`TransferMovementLedger`、`FreightRpaOutboundReportFile`、`FreightRpaOutboundUnitRun`、`reparse_current_file`、`movement_file_version`、`factories`。把 `test_outbound_evidence_sync.py` 里的 `outbound_storage` fixture 和 `_seed_outbound_world` 抄进来,来源仍用全局种子 `DSV360_AWSDU`,`created_at` 用 `datetime.utcnow()`,否则当天可用门禁会把文件看成过期。`pytestmark = [pytest.mark.usefixtures("app")]`。 + +```python +def test_reparse_outbound_inserts_ledger_without_new_rpa_run(outbound_storage): + # [断言意图] 已落地出站文件重解析后出现 outbound 档行,且不新增出站执行单元。 + report = _seed_outbound_world() + runs_before = FreightRpaOutboundUnitRun.query.filter_by(source_code=SOURCE).count() + outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([ + ["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"], + ]) + + result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow()) + + assert result.ok is True + assert result.file_id == report.id + assert result.inserted == 1 + assert result.file_status == "ready" + assert TransferMovementLedger.query.filter_by( + source_code=SOURCE, record_kind="outbound", doc_no="ASN-O1").count() == 1 + assert FreightRpaOutboundUnitRun.query.filter_by(source_code=SOURCE).count() == runs_before + assert TransferAuditEvent.query.filter_by(event_type="TRANSFER_EVIDENCE_SYNCED").count() == 1 + + +def test_reparse_same_outbound_file_skips_existing_row(outbound_storage): + # [断言意图] 同一份摘要再解析一次不插入第二行。 + _seed_outbound_world() + outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([ + ["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"], + ]) + reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow()) + + again = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow()) + + assert again.ok is True + assert again.inserted == 0 + assert again.skipped == 1 + assert TransferMovementLedger.query.filter_by( + source_code=SOURCE, record_kind="outbound").count() == 1 + + +def test_reparse_schema_failure_marks_file_and_lands_nothing(outbound_storage): + # [断言意图] 单号缺失是结构失败:零档行,文件变为 parse_failed,响应带原因。 + report = _seed_outbound_world() + outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx( + [["", 100, "O", "MAT-X", "成品", "LOT-X", 30, "2026-10-16"]]) + + result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow()) + + assert result.ok is False + assert result.file_status == "parse_failed" + assert result.inserted == 0 + assert "missing_invoice_no" in (result.error_message or "") + marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one() + assert marked.parse_failed_at is not None + assert TransferMovementLedger.query.filter_by( + source_code=SOURCE, record_kind="outbound").count() == 0 + + +def test_reparse_without_published_profile_does_not_mark_parse_failed(outbound_storage): + # [断言意图] 规则未发布不是文件错误,不写 parse_failed。 + report = _seed_outbound_world(profile_status="draft") + outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([ + ["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"], + ]) + + with pytest.raises(AppError) as exc_info: + reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow()) + + assert exc_info.value.code == "TRANSFER.CURRENT_REPARSE_NO_PROFILE" + marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one() + assert marked.parse_failed_at is None + + +def test_reparse_without_file_raises(): + # [断言意图] 没有可用归档时拒绝,而不是去触发 RPA。 + with pytest.raises(AppError) as exc_info: + reparse_current_file( + source_code="DSV360_AWSDU", record_kind="outbound", now=datetime.utcnow()) + + assert exc_info.value.code == "TRANSFER.CURRENT_REPARSE_NO_FILE" + assert exc_info.value.http_status == 422 + + +def test_reparse_non_schema_error_does_not_mark_parse_failed(outbound_storage, monkeypatch): + # [断言意图] 数据库一类异常回滚后不把文件标成解析失败,并把异常文本带回。 + report = _seed_outbound_world() + outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([ + ["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"], + ]) + + def _boom(**_kwargs): + raise RuntimeError("value too long for varchar(64)") + + monkeypatch.setattr( + "app.services.in_transit_transfer.current_file_reparse.sync_outbound_source_rows", + _boom, + ) + result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow()) + + assert result.ok is False + assert result.error_code == "TRANSFER.CURRENT_REPARSE_FAILED" + assert "varchar(64)" in (result.error_message or "") + marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one() + assert marked.parse_failed_at is None + assert TransferMovementLedger.query.filter_by( + source_code=SOURCE, record_kind="outbound").count() == 0 +``` + +`_seed_outbound_world` 增加可选参数 `profile_status: str = "published"`,传给 `FreightRpaParsingProfile.status`。入站成功路径用下面这个测试,归档时间同样取 `datetime.utcnow()`: + +```python +def test_reparse_inbound_inserts_ledger(archive_storage): + # [断言意图] 入站当前文件走 sync_source_rows,record_kind 为 inbound。 + source, _profile = factories.seed_inbound_reparse_source("CRANE_REPARSE_NOW") + storage_key = "archive/CRANE_REPARSE_NOW/current.xlsx" + report = factories.seed_reparse_archive_file( + source, sha="c" * 64, storage_key=storage_key, created_at=datetime.utcnow()) + archive_storage.objects[storage_key] = factories.build_movement_xlsx([ + ["ASN-I1", "1", "I", "MAT-I1", "连接器", "LOT-I1", 10, "2026-08-05"], + ]) + + result = reparse_current_file( + source_code="CRANE_REPARSE_NOW", record_kind="inbound", now=datetime.utcnow()) + + assert result.ok is True + assert result.file_id == report.id + assert result.inserted == 1 + row = TransferMovementLedger.query.filter_by( + source_code="CRANE_REPARSE_NOW", record_kind="inbound").one() + assert row.doc_no == "ASN-I1" + assert row.file_version == movement_file_version("c" * 64) +``` + +`archive_storage` fixture 与 `test_backlog_reparse_service.py` 相同:替换 `file_asset_storage.get_bytes`。 + +- [ ] **Step 2: Run test to verify it fails** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_current_file_reparse.py -q` + +Expected: FAIL,`reparse_current_file` 无法导入。 + +- [ ] **Step 3: Write minimal implementation** + +新建 `backend/app/services/in_transit_transfer/current_file_reparse.py`。文件头写明:用途是对当前可用归档做一次本地重解析;依赖 `evidence_sync.sync_source_rows`、`outbound_evidence_sync.sync_outbound_source_rows`、`source_file_status`、`freight_rpa.reports.queries` 的 mark/latest 函数;逻辑是先确认文件和已发布规则,再落档并提交,失败按规格回滚。 + +```python +@dataclass(frozen=True) +class CurrentReparseResult: + """一次当前归档重解析的返回。""" + + source_code: str + record_kind: str + ok: bool + file_status: str + file_id: int | None + inserted: int = 0 + updated: int = 0 + skipped: int = 0 + sealed_skipped: int = 0 + error_code: str | None = None + error_message: str | None = None + + +def reparse_current_file(*, source_code: str, record_kind: str, now: datetime) -> CurrentReparseResult: + """重解析该来源当前最新可用归档并提交。 + + 核心逻辑:先取 latest usable 文件。没有文件抛 CURRENT_REPARSE_NO_FILE。 + 有文件则调用既有 sync_*_source_rows。返回 None 表示没有已发布规则,抛 + CURRENT_REPARSE_NO_PROFILE,不写 parse_failed。结构错误回滚后 mark_*_parse_failure + 并单独提交。其他异常只回滚,不标解析失败。成功路径由 sync 函数里的 + movement_file_version 写版本戳,本函数不拼 sha256: 前缀。 + + Args: + source_code: 来源实例编码。 + record_kind: inbound 或 outbound。 + now: 落档与新鲜度判定时刻。 + Returns: + CurrentReparseResult。结构错误和其他落档异常时 ok 为 False。 + Raises: + ValidationError: record_kind 不是 inbound 或 outbound。 + AppError: TRANSFER.CURRENT_REPARSE_NO_FILE 或 TRANSFER.CURRENT_REPARSE_NO_PROFILE,HTTP 422。 + """ +``` + +函数体按这个顺序写: + +1. `kind = record_kind.strip()`。不在 `{"inbound", "outbound"}` 时 `raise ValidationError("record_kind must be inbound or outbound")`。 +2. 出站用 `latest_usable_outbound_file(source_code, now=now)`,入站用 `latest_usable_inbound_file(source_code, now=now)`。结果是 `None` 时抛 `AppError(code="TRANSFER.CURRENT_REPARSE_NO_FILE", message="no usable archive file", http_status=422, details={"source_code": source_code, "record_kind": kind})`。 +3. `try` 里调用落档。出站:`sync_outbound_source_rows(source_code=source_code, now=now)`。入站:`sync_source_rows(source_code=source_code, deps=get_transfer_dependencies(), business_date=business_date_now(), now=now)`。 +4. 返回值是 `None`:抛 `AppError(code="TRANSFER.CURRENT_REPARSE_NO_PROFILE", message="no published parsing profile", http_status=422, details={"source_code": source_code, "record_kind": kind})`。此时还没有 commit。 +5. `db.session.commit()`。再用 `resolve_source_file_status(source_code=source_code, record_kind=kind)` 填 `file_status`。返回 `ok=True` 和 outcome 的四个计数、`file_id=file_view.file_id`。 +6. `except MovementFileSchemaError as exc`:`db.session.rollback()`,然后 `mark_outbound_parse_failure` 或 `mark_inbound_parse_failure`。`error_message` 取 `getattr(exc, "message", "") or str(exc)` 后截到 2000 字符(`AppError` 的 `str()` 可能是空串,行级原因在 `message` 里,例如 `missing_invoice_no`)。`error_code=exc.code`。`db.session.commit()` 只提交失败标记。再投影状态,返回 `ok=False`、同样的 `error_code` / `error_message`、计数全 0。 +7. `except AppError`:原样抛出(第 4 步的无规则错误不能被下面的通用分支吃掉)。 +8. `except Exception as exc`:`db.session.rollback()`,不调用 mark。投影状态后返回 `ok=False`、`error_code="TRANSFER.CURRENT_REPARSE_FAILED"`、`error_message=str(exc)[:500]`、计数全 0。 + +`sync_outbound_source_rows` 和 `sync_source_rows` 必须是本模块的顶层 import。非结构异常测试打桩的是 `app.services.in_transit_transfer.current_file_reparse.sync_outbound_source_rows`。不要 import `trigger_inbound_rpa` 或 `trigger_outbound_rpa`。 + +- [ ] **Step 4: Run test to verify it passes** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/services/in_transit_transfer/test_current_file_reparse.py -q` + +Expected: PASS。 + +- [ ] **Step 5: Stage changes** + +```bash +git add backend/app/services/in_transit_transfer/current_file_reparse.py backend/tests/services/in_transit_transfer/test_current_file_reparse.py +``` + +--- + +### Task 2: HTTP 入口 + +**Files:** +- Modify: `backend/app/api/in_transit_transfer/__init__.py`(放在 `retry_source_rpa_api` 前面) +- Modify: `backend/tests/api/test_in_transit_transfer_api.py` +- Test: `backend/tests/api/test_in_transit_transfer_api.py` + +**Interfaces:** +- Consumes: `reparse_current_file(*, source_code: str, record_kind: str, now: datetime) -> CurrentReparseResult` +- Produces: `POST /api/in-transit-transfer/sources//reparse`。body `{"record_kind": "inbound"|"outbound"}`,缺省 `inbound`。成功 envelope 的 `data` 是 `CurrentReparseResult` 的字段。无文件、无规则由服务抛出的 `AppError` 变成 422。 + +- [ ] **Step 1: Write the failing test** + +在 `test_in_transit_transfer_api.py` 增加: + +```python +def test_reparse_current_without_file_returns_422(client, admin_headers): + # [断言意图] 没有出站归档时重解析是 422,不是 202 抓取中。 + response = client.post( + f"{API_PREFIX}/sources/DSV360_AWSDU/reparse", + headers=admin_headers, + json={"record_kind": "outbound"}, + ) + assert response.status_code == 422 + assert response.get_json()["error"]["code"] == "TRANSFER.CURRENT_REPARSE_NO_FILE" + + +def test_reparse_current_forbidden(client, unauthorized_headers): + # [断言意图] 无调拨权限不能重解析。 + response = client.post( + f"{API_PREFIX}/sources/DSV360_AWSDU/reparse", + headers=unauthorized_headers, + json={"record_kind": "inbound"}, + ) + assert response.status_code == 403 +``` + +使用该文件已有的 `admin_headers` 和 `unauthorized_headers`。 + +- [ ] **Step 2: Run test to verify it fails** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/api/test_in_transit_transfer_api.py::test_reparse_current_without_file_returns_422 tests/api/test_in_transit_transfer_api.py::test_reparse_current_forbidden -q` + +Expected: FAIL,路由 404。 + +- [ ] **Step 3: Write minimal implementation** + +在 `retry_source_rpa_api` 之前增加路由。不要修改 `retry_source_rpa_api` 的函数体。 + +```python +@in_transit_transfer_bp.route("/sources//reparse", methods=["POST"]) +@require_transfer_permission +def reparse_current_file_api(source_code: str): + """重解析该来源当前最新可用归档,不触发 RPA。 + + body 只读 record_kind,缺省 inbound。不接受 file_id。 + """ + from app.services.in_transit_transfer.current_file_reparse import reparse_current_file + + payload = request.get_json(silent=True) or {} + if not isinstance(payload, dict): + raise ValidationError("request body must be a JSON object") + record_kind = str(payload.get("record_kind") or "inbound").strip() or "inbound" + result = reparse_current_file( + source_code=str(source_code).strip(), + record_kind=record_kind, + now=datetime.utcnow(), + ) + return _ok({ + "source_code": result.source_code, + "record_kind": result.record_kind, + "ok": result.ok, + "file_status": result.file_status, + "file_id": result.file_id, + "inserted": result.inserted, + "updated": result.updated, + "skipped": result.skipped, + "sealed_skipped": result.sealed_skipped, + "error_code": result.error_code, + "error_message": result.error_message, + }) +``` + +更新该 API 模块文件头的路由说明,加上这条 POST。`datetime` 若文件顶部未导入,沿用文件里已有的导入方式(`retry_source_rpa_api` 已使用 `datetime.utcnow()`,不要重复导入)。 + +- [ ] **Step 4: Run test to verify it passes** + +Run: `backend/.venv/Scripts/python.exe -m pytest tests/api/test_in_transit_transfer_api.py::test_reparse_current_without_file_returns_422 tests/api/test_in_transit_transfer_api.py::test_reparse_current_forbidden tests/services/in_transit_transfer/test_current_file_reparse.py -q` + +Expected: PASS。 + +- [ ] **Step 5: Stage changes** + +```bash +git add backend/app/api/in_transit_transfer/__init__.py backend/tests/api/test_in_transit_transfer_api.py +``` + +--- + +### Task 3: 来源卡按钮与四语文案 + +**Files:** +- Modify: `frontend/src/features/chat/types/transfer.types.ts` +- Modify: `frontend/src/features/chat/api/transfer.api.ts` +- Modify: `frontend/src/features/chat/api/transfer.api.spec.ts` +- Modify: `frontend/src/features/chat/components/messages/TransferSourceSelectCard.vue` +- Modify: `frontend/src/features/chat/components/messages/TransferSourceSelectCard.spec.ts` +- Modify: `frontend/src/features/chat/components/messages/TransferMessageView.vue` +- Modify: `frontend/src/locales/zh-CN/chat.json` +- Modify: `frontend/src/locales/zh-TW/chat.json` +- Modify: `frontend/src/locales/en/chat.json` +- Modify: `frontend/src/locales/th/chat.json` +- Modify: `frontend/src/locales/zh-CN/errors.json` +- Modify: `frontend/src/locales/zh-TW/errors.json` +- Modify: `frontend/src/locales/en/errors.json` +- Modify: `frontend/src/locales/th/errors.json` +- Test: `frontend/src/features/chat/components/messages/TransferSourceSelectCard.spec.ts`、`frontend/src/features/chat/api/transfer.api.spec.ts` + +**Interfaces:** +- Consumes: `POST /api/in-transit-transfer/sources/{sourceCode}/reparse` +- Produces: `reparseCurrentFile(sourceCode: string, recordKind: TransferRecordKind): Promise`。`TransferCurrentReparseResult` 字段与 Task 2 的 `data` 相同。 + +- [ ] **Step 1: Write the failing test** + +在 `transfer.api.spec.ts` 旁路现有 `retryTransferSourceRpa` 用例增加: + +```typescript +it('当前文件重解析 POST reparse,body 只有 record_kind', () => { + reparseCurrentFile('DSV360_AWSDU', 'outbound'); + const calls = vi.mocked(requestJson).mock.calls; + expect(calls[0][0]).toBe('/api/in-transit-transfer/sources/DSV360_AWSDU/reparse'); + expect(JSON.parse(String((calls[0][1] as RequestInit).body))).toEqual({ record_kind: 'outbound' }); +}); +``` + +按该文件已有的 `requestJson` mock 写法调整 `calls` 的取法。断言 body 里没有 `file_id`。 + +在 `TransferSourceSelectCard.spec.ts` 顶部、组件 import 之前增加 mock: + +```typescript +const transferApiMocks = vi.hoisted(() => ({ + listEvidenceFiles: vi.fn(), + reparseCurrentFile: vi.fn(), +})); +vi.mock('../../api/transfer.api', () => transferApiMocks); +``` + +新增用例: + +```typescript +it('只在清单第一行显示重新解析,点击不发出 retry', async () => { + transferApiMocks.listEvidenceFiles.mockResolvedValue([ + { file_id: 25, original_filename: 'current.xlsx', created_at: '2026-10-21T10:00:00', sha256: 'abc', file_size: 10, presigned_url: 'https://files.example/current' }, + { file_id: 9, original_filename: 'older.xlsx', created_at: '2026-10-20T10:00:00', sha256: 'def', file_size: 10, presigned_url: 'https://files.example/older' }, + ]); + transferApiMocks.reparseCurrentFile.mockResolvedValue({ + source_code: 'DBS-AWSBI', record_kind: 'inbound', ok: true, file_status: 'ready', + file_id: 25, inserted: 2, updated: 0, skipped: 0, sealed_skipped: 0, + error_code: null, error_message: null, + }); + const wrapper = mount(TransferSourceSelectCard, { + props: { sources: readySources, transferTypes: defaultTransferTypes }, + global: { plugins: [i18n] }, + }); + await wrapper.find('[data-testid="transfer-source-status-DBS-AWSBI"]').trigger('click'); + await flushPromises(); + const buttons = wrapper.findAll('[data-testid="transfer-evidence-reparse-DBS-AWSBI-inbound"]'); + expect(buttons).toHaveLength(1); + await buttons[0].trigger('click'); + expect(transferApiMocks.reparseCurrentFile).toHaveBeenCalledWith('DBS-AWSBI', 'inbound'); + expect(wrapper.emitted('retry')).toBeUndefined(); + expect(wrapper.emitted('reparsed')).toBeTruthy(); +}); +``` + +`flushPromises` 用 `import { flushPromises } from '@vue/test-utils'`。若现有 mount 助手已经包了 props,沿用那个助手,不要另写一套来源数据。 + +- [ ] **Step 2: Run test to verify it fails** + +Run: `npx vitest run src/features/chat/api/transfer.api.spec.ts src/features/chat/components/messages/TransferSourceSelectCard.spec.ts` + +工作目录:`frontend/`。 + +Expected: FAIL,`reparseCurrentFile` 不存在,按钮找不到。 + +- [ ] **Step 3: Write minimal implementation** + +`transfer.types.ts` 在 `TransferEvidenceFile` 后增加: + +```typescript +export interface TransferCurrentReparseResult { + source_code: string; + record_kind: TransferRecordKind; + ok: boolean; + file_status: TransferSourceFileStatus['file_status']; + file_id: number | null; + inserted: number; + updated: number; + skipped: number; + sealed_skipped: number; + error_code: string | null; + error_message: string | null; +} +``` + +`transfer.api.ts` 在 `listEvidenceFiles` 后增加 `reparseCurrentFile`。JSDoc 写明:只重放当前最新归档;body 只有 `record_kind`;不触发 RPA。 + +```typescript +export const reparseCurrentFile = ( + sourceCode: string, + recordKind: TransferRecordKind, +) => + requestJson( + `${BASE}/sources/${encodeURIComponent(sourceCode)}/reparse`, + { + method: 'POST', + headers: jsonHeaders(), + body: JSON.stringify({ record_kind: recordKind }), + }, + ); +``` + +`TransferSourceSelectCard.vue`: + +- import 改为 `listEvidenceFiles, reparseCurrentFile`。 +- `defineEmits` 增加 `reparsed: []`。 +- 增加 `reparsingKey = ref(null)`。 +- 清单 `v-for` 改成 `(file, index) in evidenceFilesOf(...)`。 +- 仅当 `index === 0` 时,在预览链接前放按钮: + +```vue + +``` + +`reparseEvidence` 的 JSDoc 写明:调用 `reparseCurrentFile`,不 emit `retry`。成功且 `ok` 时 `success` 提示新增/更新数,并重新 `listEvidenceFiles` 写回 `evidenceByKey`,然后 `emit('reparsed')`。`ok === false` 时 `notifyError` 显示 `error_message`,同样刷新清单和 `emit('reparsed')`,让解析失败状态回到芯片上。抛错时只 `notifyError`。 + +`TransferMessageView.vue` 的来源卡增加 `@reparsed="transfer.loadSources()"`。不要改 `onSourceRetry`。 + +四份 `chat.json` 的 `chat.transfer` 里,紧挨 `previewEvidence` 增加: + +| key | zh-CN | zh-TW | en | th | +| --- | --- | --- | --- | --- | +| `reparseCurrentFile` | 重新解析 | 重新解析 | Reparse | แยกวิเคราะห์ซ้ำ | +| `reparseCurrentFileDone` | 已重新解析:新增 {inserted},更新 {updated} | 已重新解析:新增 {inserted},更新 {updated} | Reparsed: {inserted} inserted, {updated} updated | แยกวิเคราะห์ซ้ำแล้ว: เพิ่ม {inserted} อัปเดต {updated} | + +四份 `errors.json` 的 `TRANSFER.*` 段增加: + +| key | zh-CN | zh-TW | en | th | +| --- | --- | --- | --- | --- | +| `TRANSFER.CURRENT_REPARSE_NO_FILE` | 当前没有可重新解析的归档文件。 | 目前沒有可重新解析的歸檔檔案。 | No archived file is available to reparse. | ไม่มีไฟล์ที่เก็บถาวรให้แยกวิเคราะห์ซ้ำ | +| `TRANSFER.CURRENT_REPARSE_NO_PROFILE` | 当前证据流没有已发布的解析规则。 | 目前證據流沒有已發布的解析規則。 | This evidence stream has no published parsing profile. | สตรีมหลักฐานนี้ไม่มีโปรไฟล์การแยกวิเคราะห์ที่เผยแพร่แล้ว | + +更新 `TransferSourceSelectCard.vue` 文件头依赖,写上 `reparseCurrentFile`。函数 `reparseEvidence` 上方按项目 JSDoc 写用途、参数、返回值。 + +- [ ] **Step 4: Run test to verify it passes** + +Run: `npx vitest run src/features/chat/api/transfer.api.spec.ts src/features/chat/components/messages/TransferSourceSelectCard.spec.ts` + +工作目录:`frontend/`。 + +Expected: PASS。既有来源卡用例仍然通过。若 mock 替换了整个 `transfer.api` 导致其他用例缺导出,只补那些用例实际会调用的导出,不要改断言去迁就 mock。 + +- [ ] **Step 5: Stage changes** + +```bash +git add frontend/src/features/chat/types/transfer.types.ts frontend/src/features/chat/api/transfer.api.ts frontend/src/features/chat/api/transfer.api.spec.ts frontend/src/features/chat/components/messages/TransferSourceSelectCard.vue frontend/src/features/chat/components/messages/TransferSourceSelectCard.spec.ts frontend/src/features/chat/components/messages/TransferMessageView.vue 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 frontend/src/locales/zh-CN/errors.json frontend/src/locales/zh-TW/errors.json frontend/src/locales/en/errors.json frontend/src/locales/th/errors.json +``` + +--- + +### Task 4: 文档 + +**Files:** +- Modify: `docs/features/in-transit-transfer/technical.md`(来源 API 表,约第 70 行 `retry-rpa` 那一行之后) +- Modify: `docs/funclist.md`(「来源重试合并触发与知情范围确认」那一行之后) + +**Interfaces:** +- Consumes: Task 2 的路由和两个错误码。 +- Produces: 文档与代码一致。无新代码。 + +- [ ] **Step 1: Update the API table** + +在 `technical.md` 的来源路由表,`POST /sources/{source_code}/retry-rpa` 下一行增加: + +`POST /sources/{source_code}/reparse`:重解析当前最新可用归档(body `record_kind`,缺省 inbound;不接受 file_id;不触发 RPA)。成功 200,`ok/file_status/file_id/inserted/updated/skipped/sealed_skipped`。无文件 422 `TRANSFER.CURRENT_REPARSE_NO_FILE`。无已发布规则 422 `TRANSFER.CURRENT_REPARSE_NO_PROFILE`,不标 parse_failed。结构失败 200 `ok: false` 且文件为 `parse_failed`。其他异常 200 `ok: false`,不标 parse_failed。与待匹配 `POST /backlog/pending-match/reparse` 不是同一条链路。 + +- [ ] **Step 2: Update the feature list** + +在 `funclist.md` 来源重试行后增加一行: + +「当前归档重新解析(2026-10-21)」已实现。来源卡证据清单第一行「重新解析」调用 `POST /sources/{source_code}/reparse`,只重放该流入站或出站的最新可用归档并幂等落档,不触发 RPA,不删除档行。↻ 仍是重新抓取。待匹配「清空并重新解析」仍是整桶重建。 + +- [ ] **Step 3: Stage changes** + +```bash +git add docs/features/in-transit-transfer/technical.md docs/funclist.md docs/superpowers/specs/2026-10-21-transfer-current-file-reparse-design.md docs/superpowers/plans/2026-10-21-transfer-current-file-reparse.md +``` diff --git a/docs/superpowers/specs/2026-10-14-transfer-type-config-and-movement-ledger-design.md b/docs/superpowers/specs/2026-10-14-transfer-type-config-and-movement-ledger-design.md new file mode 100644 index 00000000..15a8876f --- /dev/null +++ b/docs/superpowers/specs/2026-10-14-transfer-type-config-and-movement-ledger-design.md @@ -0,0 +1,310 @@ +# 在途调拨类型配置化 + 库存异动档 设计规格 + +> 日期:2026-10-14 · 状态:已与业务方逐轮确认(grilling 五轮 + 逐题拍板) +> 关联:[ADR 0001](../../adr/0001-movement-ledger-and-item-birth-flip.md) · [ADR 0002](../../adr/0002-transfer-type-configuration.md) · [GLOSSARY.md](../../../GLOSSARY.md) + +## 1. 背景与问题 + +「在途自动调拨」当前的调拨类型硬编码四处(后端 `transfer_type.py` 枚举、`transfer_runs.transfer_type` CHECK 约束、前端 union+选项数组、四语言 i18n),每类型的数据范围规则(收料单号前缀 HOM/HOX/WTP、ODM ID=HoxinRMA)是后端代码常量。业务上即将出现更多调拨场景(HUB仓维修出、HUB仓间调拨出/入),每个场景的数据圈定口径不同,不可能每加一个场景就发一次版。 + +同时,平台缺少一份「外部系统库存记录镜像」:`transfer_invoice_items` 一张表既当外部记录落地层(文件落地即写、按类型 1 前缀过滤)又当匹配执行工作集,导致①范围外的外部记录根本不落平台、②出货记录无处可落、③两个职责互相牵制。 + +## 2. 目标 / 非目标 + +**目标** +1. 调拨类型完全可配置:运营在 admin 管理页自助创建/启停类型,零代码零发版。 +2. 每类型可自定义数据范围:基于库存异动档字段的受控规则(UI 维护,不暴露 JSON)。 +3. 建立库存异动档:外部系统收料/出货记录的平台镜像(参照 ERP `inaj_t` 形态),本期收料全量落档,出货侧结构与模型就位。 +4. 匹配明细(items)改为匹配时从异动档圈定创建,一次匹配永久写入。 +5. 类型支持仓库定义(拨出/拨入 × 映射档/固定值)与字段转换规则(一期:批号前缀替换)。 + +**非目标** +- 出货 RPA / 出货登记解析(后续项目;本期只保证档结构与类型模型无需回头改造)。 +- HUB仓维修出、HUB仓间调拨的实际启用(待出货数据可用,届时管理页建类型即可)。 +- 同一类型按不同来源实例细分仓库映射(一期固定值/映射档二选一即可)。 +- 出货侧的匹配/执行链路实现。 +- 类型配置的变更历史审计(匹配快照已保证「当时口径」可追溯;配置变更流水后补)。 +- 档数据保留/清理策略(一期记录量级小,不清理;远期随归档策略一并设计)。 +- 类型配置并发编辑冲突检测(低频管理操作,采用后写覆盖 last-write-wins)。 + +## 3. 已定决策(业务方逐题确认) + +| # | 决策 | +| --- | --- | +| D1 | 类型配置存专用配置表 + admin 管理页(否决 app_settings KV) | +| D2 | 范围规则=受控「字段+匹配方式+值列表」,规则间 AND、规则内多值 OR;UI 规则行编辑器,不暴露 JSON | +| D3 | 异动档独立新建表(参照 inaj_t),**否决**升级 items 为档;档字段白名单见 §5 | +| D4 | items 改为匹配创建时从档圈定生成,永久绑定匹配;不做落地即写 | +| D5 | 档落地沿用现有增量幂等语义:自然键去重、证据变原行更新、缺席不删、已执行封存 | +| D6 | 仓库定义:拨出/拨入两角色 × `mapped`(取映射档)/ `fixed`(固定值+可选法人覆盖);固定仓库编码保存时校验提示不硬拦 | +| D7 | 转换规则一期=批号前缀替换(WTP→HOW 作为「在途仓至HUB仓」的手工配置),只在系统边界生效,行与档保原值;规则快照进匹配 | +| D8 | 不做种子数据:上线后管理页手工建类型;配置为空时前端空态 + 匹配 fail-closed;`transfer_type` 匹配创建必填 | +| D9 | 收料来源实例是范围规则字段之一 | +| D10 | 范围重叠暂不硬拦(配置责任),档级封存防二次执行 | +| D11 | 出货侧本期只做「结构就位」(record_kind、预留列),解析与执行链路留给出货项目 | +| D12 | 一步到位(本期完成翻转+迁移),内部按阶段交付 | +| D13 | 新增档字段:order_type / odm_id / odm_name / carton_id / pallet_id(进解析 Profile 可映射字段) | +| D14 | record_kind 由文件种类声明写入,与 in_out_flag 交叉校验,不一致打异常标记 | +| D15 | **无存量数据**(2026-10-14 业务方确认):transfer_runs/matchings/items 均为空,迁移在空数据环境执行,不建回填脚本 | +| D16 | 首页待办看板新增「待匹配」桶:翻转后已落档但从未匹配的外部记录在此可见(只读 + 引导去匹配),不可勾选执行 | +| D17 | 圈档互斥:一条档记录一生只生成一次 items 绑定;已被有效 items 占用的记录不再被新匹配圈定,取消匹配释放占用(数据唯一性的匹配侧保证) | + +## 4. 领域模型 + +### 4.1 调拨类型配置表 `transfer_type_configs`(新建) + +| 列 | 类型 | 说明 | +| --- | --- | --- | +| id | PK | | +| code | String(64) UNIQUE | 类型编码(snake_case),创建后**不可变**;`transfer_runs.transfer_type` 引用此值 | +| names_json | JSON | 四语言名称 `{"zh-CN": "...", "zh-TW": "...", "en": "...", "th": "..."}`;zh-CN 必填,缺失回落 zh-CN→en | +| enabled | bool | 停用后新匹配不可选,存量不受影响;**只有停用没有删除** | +| sort_order | Integer | 前端排序 | +| scope_rules_json | JSON | 范围规则列表,见 §6 | +| warehouse_config_json | JSON | 仓库定义,见 §7 | +| transform_rules_json | JSON | 字段转换规则列表,见 §8 | +| description | Text | 管理页备注 | +| created_by / updated_by / created_at / updated_at | | 审计 | + +配套迁移:**drop** `transfer_runs` 的 `ck_transfer_runs_transfer_type` CHECK 约束(类型合法性改由配置表校验);存量行不动。 + +### 4.2 库存异动档 `transfer_movement_ledger`(新建) + +自然键唯一索引:`(source_code, record_kind, doc_no, line_no, line_seq, in_out_flag)`(可空成分一律 NOT NULL + default '')。 + +| 组 | 列 | +| --- | --- | +| A 单据标识 | `doc_no`(64) / `line_no`(32) / `line_seq`(32, default '') / `in_out_flag`(8, default '') | +| B 物料与数量 | `material_code`(64) / `material_name`(200) / `specification`(200) / `lot_no`(64) / `quantity` String(40) / `unit`(32) | +| C 仓储与日期 | `warehouse_code`(64) / `storage_code`(64) / `movement_date` String(16) | +| D 业务属性 | `order_type`(64)⭐ / `odm_id`(64)⭐ / `odm_name`(128)⭐ / `carton_id`(64)⭐ / `pallet_id`(64)⭐ / `doc_nature`(64)🔖 / `movement_type`(64)🔖 / `reason_code`(32)🔖 / `source_ref_no`(64)🔖 / `partner_code`(64)🔖 / `remark` Text🔖 | +| E 平台溯源 | `source_code`(64) / `record_kind`(16) / `source_file_id` FK `shipping_receipt_report_files` / `file_version`(64) / `file_sha256`(64) / `sheet_name`(128) / `row_no` Integer / `created_at` / `updated_at` | +| F 平台回写 | `transfer_executed` bool default false / `executed_doc_no`(64) nullable | + +⭐=本期新增强业务字段(进解析 Profile 可映射);🔖=预留列(nullable,出货报告确认后直接映射,免后续迁移)。 + +**FK 与空值语义**:`source_file_id` 外键 `ON DELETE SET NULL`——来源文件被清理(文件资产保留策略)后档记录必须留存(事实不随文件消失,链接仅溯源)。`movement_date` 可空:空值记录照常落档,但不进收料日期圈定(日期条件恒排除 NULL)。 + +**刻意双字段**:`record_kind`(文件种类声明,权威)与 `in_out_flag`(数据列原值,校验用)——两者矛盾即解析错位,落档时打异常标记(审计事件),记录照常落档。 + +**不进档**:`from_warehouse`/`to_warehouse`/`external_org`(ERP 解析值,属路由与匹配明细侧);`external_quantity`/`inventory_checked_at`(ERP 评估结果,属 items);换算率/VMI/成本等 inaj 内部管理字段;企业编号/营运据点(来源实例配置承载)。 + +### 4.3 匹配明细 `transfer_invoice_items`(改造) + +- 新增 `ledger_record_id` FK → `transfer_movement_ledger.id`(nullable,索引;隔离的历史行允许 NULL)。 +- `matching_id` 语义回归「创建即绑定」:新行恒非空(模型层不强制 NOT NULL,存量兼容,服务层保证)。 +- **落地不再写 items**;行来源=匹配创建时从档圈定(§9)。 +- 行上批号等字段保持档记录原值;`external_lot_no` 类转换只在系统边界按类型规则派生(§8)。 + +## 5. 档落地链路(增量幂等) + +解析入口不变(收料 RPA 回调桥 `sync_and_commit_for_callback` → 落地主链路),`evidence_sync` 改造为「一次解析、写档」: + +1. 按自然键查档:不存在 → **插入**(`record_kind`、`source_file_id`、`file_version`、`file_sha256`、`sheet_name`、`row_no` 随行写入)。 +2. 存在且来源文件 sha 未变 → **跳过**(幂等)。 +3. 存在且证据变化 → **原行更新**证据字段 + 换 `file_version`/`file_sha256`/`source_file_id`/`sheet_name`/`row_no`/`updated_at`。 +4. 文件缺席的档记录 → **保留不删**(收料 RPA 非全量导出,缺席≠删除)。 +5. `transfer_executed=true` 的记录**永不更新、永不复活**(封存事实;反证:同文件重落地不产生第二行,自然键唯一索引兜底)。 +6. `record_kind` 与 `in_out_flag` 矛盾 → 审计事件标记,记录照常落档。 + +解析失败分层语义(2026-09-29 引入的 parse_failed 三列/桥隔离/仅 schema 类失败落库)原样保留。 + +## 6. 范围规则引擎 + +**规则模型**:`ScopeRule = {field, match, values[]}`;`match ∈ {prefix, equals, contains, in}`。一个类型的范围 = 规则列表:**规则间 AND,规则内多值 OR**。空规则列表 = 不限(全量在档记录中圈定)——是否允许「空=不限」由管理页显式确认(默认要求至少一条规则,防误圈全量)。 + +**字段词表(受控白名单,封闭可扩展)**:`source_code, doc_no, warehouse_code, storage_code, lot_no, movement_date, record_kind, in_out_flag, order_type, odm_id, odm_name, carton_id, pallet_id, material_code, doc_nature, movement_type, reason_code, partner_code`。 + +**求值**: +- 内存谓词 `evaluate_scope(record: Mapping, rules) -> bool`(单元测试/小数据场景)。 +- SQL 编译 `apply_scope_filters(query, model, rules) -> query`:prefix→`UPPER(col) LIKE 'X%'`;equals→`=`;contains→`LIKE '%X%'`;in→`IN`。匹配创建圈档与重查对账共用同一编译器(单一口径,杜绝谓词漂移)。 +- 匹配创建时附加固定条件:`record_kind='receipt'`(一期)、`source_code IN (所选来源)`、`movement_date BETWEEN 收料日期范围`、`transfer_executed = false`、**未被有效 items 占用**(D17,见 §9)。 + +**快照**:范围规则 JSON 序列化进 `TransferMatching.scope_json`(新键 `scope_rules`,保留旧键 `transfer_type_scope` 仅存量读取),参与匹配 hash。 + +## 7. 仓库定义与路由 + +类型配置 `warehouse_config_json`: + +```json +{ + "from": {"mode": "mapped", "warehouse_code": null, "external_org": null}, + "to": {"mode": "fixed", "warehouse_code": "WH-REPAIR", "external_org": null} +} +``` + +- `mode=mapped`:沿用 `DefaultRouteResolver`(来源实例映射档:`in_transit_warehouse_code`/`external_warehouse_code`/`external_organization_code`)。 +- `mode=fixed`:该角色取类型固定 `warehouse_code`;`external_org` 非空时覆盖映射档法人,为空沿用映射档解析。 +- 四场景:在途仓至HUB=from mapped / to mapped;维修出=from mapped / to fixed;调拨出=from mapped / to fixed;调拨入=from fixed / to mapped。 +- 管理页保存 fixed 时校验映射档存在同编码 `external_warehouse_code`(**提示不硬拦**);运行期解析失败照旧 fail-closed(`ROUTE_NOT_RESOLVED`)。 +- 行上 `from_warehouse`/`to_warehouse` 落列与建单分组 `(external_org, source_code, receipt_date, from, to)` 逻辑不变——类型只改变解析器的取值来源。 + +## 8. 字段转换规则 + +`TransformRule = {field, op, source, target}`;一期 `field ∈ {lot_no}`、`op ∈ {prefix_replace}`(`lot_no` 前缀 `source`→`target`,如 WTP→HOW)。多规则按序链式生效;类型未配置=恒等。 + +- **生效边界**(替换现 `movement_contract.external_lot_no()` 硬编码的 6 个调用点):匹配库存查询 targets、重试/重查 targets、写前库存复查、票行聚合键、票投影展示、前端 `transferBatch.ts deriveBatchNo` 展示镜像(规则随类型接口下发驱动)。 +- 行与档**始终保存原值**(证据原则不变)。 +- 转换规则随匹配快照进 `scope_json`(新键 `transform_rules`),在途匹配口径不被中途改配置扰动。 +- 匹配 hash 不含批号(已验证事实),规则变更不影响存量 hash。 + +## 9. 匹配出生与重查对账 + +**匹配创建 `run_matching`**: +1. 校验类型:必填、存在、enabled(空配置表→`TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED` fail-closed)。 +2. **从档圈定**:`apply_scope_filters(范围规则) + 固定条件(§6)` 选中档记录。 +3. 按选中记录**创建 items**:`matching_id` 绑定本次、`ledger_record_id` 外键、业务字段取档原值、路由解析(§7)落 from/to、`receipt_quantity=quantity`。 +4. 库存查询/评估/落位逻辑不变(继续以 items 为工作单元)。 +5. `scope_json` 快照:范围规则 + 转换规则 + 类型 + 来源 + 日期;hash 从快照内容计算(存量无新键→旧形状,兼容陷阱消除)。 + +**圈档互斥(D17,防同记录重复圈定)**:一条档记录一生只生成一次 items 绑定。匹配创建圈档时排除「已被有效 items 占用」的档记录——存在任一 item(所属匹配未取消、行未被失效隔离)引用即视为占用。取消匹配时其 items 转入 cancelled(`cancellation.py` 既有语义),占用即释放,记录重新可被后续匹配圈定;人工关闭/成功终态不释放(前者=业务裁定不拨,恢复走既有恢复处理;后者=档级封存)。重查只对账本匹配自己的 items,不受此规则影响。 + +**重查 `requery_items`**:弃 `scope_item_query`(items SQL 圈行退役),改为**对档重圈**(同一编译器、同一快照规则)→ 与该匹配已有 items 对账:档有行无→新建 items(绑同一匹配);档证据变→刷新 items 证据并重置待查;档记录被新版本替换→items 失效隔离(沿用 `blocked_file_removed` 语义与退出主视图的交互)。 + +**防二次执行(档级封存)**:票据执行成功落 `executed_doc_no` 时,回写其 items 关联的档记录 `transfer_executed=true` + `executed_doc_no`;匹配创建圈档与首页队列恒排除已封存记录。行级终态状态机与 `duplicate_success` 语义不变。 + +## 10. 首页可调拨明细(队列)与执行门禁 + +- 四队列卡数据源改为**档 + 最近执行状态联查**:以启用类型范围并集圈档,左联 items 取最近评估状态;新增「待匹配」桶(档有记录、尚无有效 items),**不可勾选执行**;ready/blocked 桶语义保持。 +- `GET /items/executable` 仍返回可执行 items(行恒属某匹配,跨匹配勾选执行允许——`execute_items` 按行 ID 工作不变)。 +- `file_current` 门禁改锚:item → 档记录 `file_version` == 该来源最新可用文件 sha;档记录无变化即当前。行新鲜度 TTL(`updated_at` 显式续期)机制不变。 + +## 11. API 设计 + +| 方法与路径 | 权限 | 说明 | +| --- | --- | --- | +| `GET /api/in-transit-transfer/transfer-types` | in_transit_transfer Agent 权限 | enabled 列表(code/names_json/sort_order/transform_rules),前端类型选择与转换展示驱动 | +| `GET /api/admin/in-transit-transfer/transfer-types` | 平台管理员 | 全量列表(含停用) | +| `POST /api/admin/in-transit-transfer/transfer-types` | 平台管理员 | 创建(code 不可重复、不可变) | +| `PUT /api/admin/in-transit-transfer/transfer-types/` | 平台管理员 | 更新(code 不可改;names/scope/warehouse/transform/enabled/sort 可改) | +| `POST /api/in-transit-transfer/matchings` | Agent 权限 | body.transfer_type 改**必填**;空配置/停用类型→422 | + +错误码(同步四语言 `errors.json`):`TRANSFER.TRANSFER_TYPE_REQUIRED` / `TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED` / `TRANSFER.TRANSFER_TYPE_DISABLED` / `TRANSFER.TRANSFER_TYPE_CODE_EXISTS`(创建重复编码) / `TRANSFER.TRANSFER_TYPE_CODE_IMMUTABLE`(修改编码) / `TRANSFER.SCOPE_RULE_INVALID` / `TRANSFER.WAREHOUSE_CONFIG_INVALID` / `TRANSFER.TRANSFORM_RULE_INVALID`。JSON envelope `{success, data|error, request_id}` 与 `AppError` 契约不变。 + +## 12. 管理页设计(admin 新模块 `transfer-types`) + +- 位置:`frontend/src/features/admin/modules/transfer-types/TransferTypesPage.vue`;路由挂 `admin.routes.ts`;`AdminModuleId`/`constants/modules.ts`/`AdminNav` iconMap 同步;**四语言**(`locales/*/admin.json`)。 +- 列表:编码/名称/启停/排序/更新时间 + 启停开关。 +- 编辑抽屉四块:①基本信息(编码创建后只读、四语言名称、排序)②范围规则行编辑器(字段下拉=白名单、匹配方式下拉、多值 tags;重叠提示:与其它启用类型的规则并集有交集时黄条提示不硬拦)③仓库定义(from/to 两行的 mode 切换 + fixed 时仓库编码输入 + 映射档存在性校验提示)④转换规则行编辑器(字段下拉[一期仅批号]、op 下拉[prefix_replace]、source/target 输入)。 +- 前端 HTTP 走 `requestJson`,失败 `useMessage()` 展示 `BusinessError`。 + +### 12.1 管理页框线图(ui-ux-pro-max) + +``` +┌──────────────────────────────────────────────────────────────────────┐ +│ 管理端 › 在途调拨类型 [+ 新建类型] │ +├──────────────────────────────────────────────────────────────────────┤ +│ 搜索编码/名称… [状态: 全部 ▾] │ +│ ┌────────────────────────────────────────────────────────────────┐ │ +│ │ 编码 名称 规则数 状态 更新时间 操作 │ │ +│ │ in_transit_to_hub 在途仓至HUB仓 1 [启用●] 10-14 编辑 │ │ +│ │ hub_repair_out HUB仓维修出 0 [停用○] 10-14 编辑 │ │ +│ └────────────────────────────────────────────────────────────────┘ │ +│ 空态:图标 + 「暂无调拨类型,点击右上角新建」 + [新建类型] 按钮 │ +└──────────────────────────────────────────────────────────────────────┘ + │ 点击「编辑 / 新建」→ 右侧抽屉(≥480px) + ▼ +┌─ 编辑调拨类型 ───────────────────────────────────[×]─┐ +│ ① 基本信息 │ +│ 类型编码* [in_transit_to_hub ](创建后只读) │ +│ 名称* zh-CN[在途仓至HUB仓] zh-TW[在途倉至HUB倉] │ +│ en[In-Transit to HUB] th[…] │ +│ 排序 [10] 状态 (●)启用 (○)停用 │ +│ ② 范围规则 (规则之间=且,规则内多值=或) │ +│ ┌────────────┬──────────┬────────────────────┬───┐ │ +│ │ 字段 ▾ │ 匹配 ▾ │ 值(多值 tag) │ │ │ +│ │ 收料单号 │ 前缀 ▾ │ [HOM ✕][HOX ✕][WTP✕]│ 🗑│ │ +│ │ 来源实例 │ 属于 ▾ │ [SRC-A ✕][SRC-B ✕] │ 🗑│ │ +│ └────────────┴──────────┴────────────────────┴───┘ │ +│ [+ 添加规则] │ +│ ⚠ 与启用类型「X」的范围存在重叠——请确认是有意配置 │ +│ ③ 仓库定义 拨出仓库 拨入仓库 │ +│ 来源 [映射档 ▾] [映射档 ▾] [固定 ▾] │ +│ 编码 [—] [—] [WH-REPAIR ] │ +│ 法人 [—] [—] [—] │ +│ ✓ WH-REPAIR 在仓库映射档中存在(绿色)/ ✕ 未找到(黄)│ +│ ④ 字段转换规则 │ +│ [字段: 批号 ▾] [前缀替换 ▾] [WTP] → [HOW] 🗑 │ +│ [+ 添加转换] │ +│ [取消] [保存] │ +└──────────────────────────────────────────────────────┘ +``` + +**交互与可用性规则**(来源:ui-ux-pro-max UX 准则检索): + +- 行内校验:onBlur 校验;错误文案显示在**对应字段正下方**并以 `aria-describedby` 关联,禁止只弹 toast/只标红边。 +- 提交失败:顶部渲染可聚焦的错误摘要(`role="alert"`),每条链接跳到对应字段;行内错误保留。 +- 保存按钮:loading → 成功/失败状态反馈,禁止点击后无响应。 +- 所有输入必须有显式 label(禁止 placeholder 充当 label);tag 删除按钮点击区 ≥24px。 +- 列表空态给「消息 + 行动」(新建按钮),不留白屏。 +- 规则重叠、映射档未命中固定仓库:黄色提示条**不拦截**保存(配置责任在管理员,D10/D6)。 + +### 12.2 chat 类型选择卡(改造)框线图 + +``` +┌ 选择收料来源实例 ──────────────────────────────────┐ +│ 匹配参数 │ +│ 调拨类型 [在途仓至HUB仓] [HUB仓维修出] [HUB仓间调拨]│ ←选项=接口下发(enabled), +│ 收料日期 [2026/10/12] ~ [2026/10/12] ⓘ │ 名称 names[locale]→zh-CN→en +│ …(来源实例列表/全选可见/只选可重试等全部不变) │ +│ [确认范围并匹配] │ +└────────────────────────────────────────────────────┘ +配置为空时(D8 fail-closed 的前端形态): +│ 调拨类型 ⚠ 暂无可用调拨类型,请联系管理员在管理端配置│ ← 空态文案 + 行动指引 +│ [确认范围并匹配](禁用)│ +``` + +变更点:删除写死三选项数组与「即将上线」徽标逻辑;按钮组数据= `GET /transfer-types`;空列表渲染空态且确认按钮禁用(tooltip 说明原因)。 + +### 12.3 首页待办看板(改造)框线图——「待匹配」桶 + +``` +│ 库存匹配 │ +│ [+ 匹配可调拨库存 选择来源实例后,系统默认以昨天…] │ +│ 待办看板 │ +│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ +│ │ 3 │ │ 0 │ │ 0 │ │ 0 │ │ +│ │ 待匹配 │ │ 可调拨明细│ │ 待恢复异常│ │ 已人工关闭│ │ +│ │ 已抓取尚未│ │ 勾选后按 │ │ 可重查库 │ │ 可查看原 │ │ +│ │ 匹配的外部│ │ 行生成调 │ │ 存或一键 │ │ 因并恢复 │ │ +│ │ 收料记录 │ │ 拨单 │ │ 恢复处理 │ │ 处理 │ │ +│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ +│ (新增卡·靛蓝) (绿·不变) (蓝·不变) (白·不变) │ +│ 执行看板(成功/失败/执行中/结果未知)——不变 │ +``` + +**「待匹配」桶逻辑(D16,回答"计划中为什么多了它")**:翻转后外部记录**落档不落 items**,items 只在匹配时创建——因此「RPA 已抓到、但还没点过匹配」的记录在旧首页上**没有任何位置可见**(旧行为里它们以 items 形态躺在可调拨明细)。待匹配桶补上这个可见性: + +- **口径**:档记录 ∈ 启用类型范围并集、`record_kind='receipt'`、未封存、**无有效 items**(从未被任何匹配圈中)。 +- **数字变化时机**:收料文件落地 → 数字涨;点了匹配 → 圈中的记录离开待匹配、进入可调拨明细等后续状态;匹配之后文件又新增记录 → 数字再涨。 +- **点击行为**:展开只读清单(单号/料号/收料日期/来源/数量),顶部「去匹配」按钮=库存匹配入口;**不可勾选执行**(未做库存核对)。 +- 若业务上不需要此可见性,可直接砍掉该卡(砍掉后唯一损失是「抓到了没匹配」不主动可见);**推荐保留**。 + +## 13. 兼容与迁移 + +**前提(D15):无存量数据**——业务方 2026-10-14 确认 `transfer_runs` / `transfer_matchings` / `transfer_invoice_items` 在目标环境均为空,全部迁移在空数据环境执行,**不建存量回填脚本**。 + +1. **历史展示健壮性**:Run/Matching 展示与审计不依赖配置表存在性(类型值可能来自已停用/已改名的配置,展示层读快照不查配置)。 +2. **hash 纪律**:hash 一律从 `scope_json` 快照内容计算;无存量快照即无兼容包袱,但「从快照内容计算、不引入环境变量」的实现纪律保留(2026-09-22 陷阱的根因防御)。 +3. **例外预案**:若上线前发现目标环境实际已有数据(与本节前提不符),**停止升级**并补做回填方案(items 四元组挂档 + 终态回写封存),不得带数据直切。 +4. **evidence_sync 三分类测试**:现有用例语义平移到档(断言对象改为档记录)。 +5. **提示词/catalog**:`agent_registry` 中如枚举调拨类型的文案改为「类型来自平台配置」;Dify 平台侧如有副本需人工同步。 + +## 14. 出货侧就位(本期交付的「零回头」承诺) + +- 档:`record_kind='shipment'` 即可落出货记录;D 组字段 + 🔖预留列覆盖出货报告预期字段。 +- 类型:维修出/调拨出/调拨入在管理页建类型即可(仓库定义、范围规则、转换规则全覆盖其需求)。 +- 后续项目只需:出货抓取 RPA → 出货解析 Profile(purpose 扩展)→ 对应类型执行链路(从档圈 `record_kind='shipment'` 复用同一套引擎)。 + +## 15. 测试策略 + +- 后端域套件(`backend/tests/services/in_transit_transfer/`)为门禁:现有用例随语义平移改造(evidence_sync 断言对象、matching 圈行来源、queue 数据源);新增 scope_rules / field_transforms / transfer_type_config / ledger 落地 / 匹配出生 / 重查对账 / 档级封存 / 待匹配桶用例;API 测试(admin CRUD + chat types + matchings 必填)。 +- 前端 vitest:`TransferSourceSelectCard`(接口选项/空态/无「即将上线」)、`useChatTransfer`(types 拉取)、`transferBatch`(规则驱动 deriveBatchNo)、admin 页面组件测试;`npm run build` 必须绿。 + +## 16. 分阶段交付(每阶段测试绿、可独立验收) + +1. **P0 引擎与配置域**:scope_rules / field_transforms 纯函数引擎(TDD)、配置表模型+迁移(含 drop CHECK)、transfer_type.py 配置化改造、类型服务与 API、四语言错误码。 +2. **P1 管理页与前端接入**:admin 模块页四块编辑器、chat 类型选择接口化、转换规则驱动展示、移除「即将上线」。 +3. **P2 异动档**:档模型+迁移、解析契约扩展(D13 字段)、档落地链路(增量幂等+交叉校验)。 +4. **P3 出生翻转**:匹配创建从档圈行建 items、重查对档对账、落地停写 items(与上一任务原子)、scope_json 快照与 hash、旧 `scope_item_query` 退役。 +5. **P4 队列与门禁收口**:首页队列档联查+待匹配桶(D16)、file_current 改锚、档级封存回写、提示词/catalog 同步、文档(technical.md/funclist)与全量回归。 diff --git a/docs/superpowers/specs/2026-10-15-inbound-outbound-idempotency-rename-design.md b/docs/superpowers/specs/2026-10-15-inbound-outbound-idempotency-rename-design.md new file mode 100644 index 00000000..2ecf2915 --- /dev/null +++ b/docs/superpowers/specs/2026-10-15-inbound-outbound-idempotency-rename-design.md @@ -0,0 +1,167 @@ +# 库存异动接入改版:入站/出站统一、幂等修复与解析类型枚举改版 — 设计文档 + +日期:2026-10-15 | 状态:已实施(2026-10-15) | 前置:调拨类型配置化+库存异动档(2026-10-14,已提交 52c71ee46) + +## 0. 背景与实测证据 + +调拨模块原按「收料(receipt)单假设」设计。用三份真实 WMS 文件实测暴露四类问题: + +| 文件 | 行数 | 现行自然键去重后 | 最坏塌缩 | 扩键后(含箱号/批号) | +| --- | --- | --- | --- | --- | +| CRANE NA 入站 | 4213 | 3454 | 1 键 43 行 | 完全唯一 | +| DSV AWSSG 入站 | 16326 | 16236 | 1 键 4 行 | 完成行下唯一 | +| Outbound 出站 | 7492(完成 6131) | 897 | **1 键 428 行** | 完全唯一 | + +问题定性:①自然键(单号+行+项序+进出标志)粒度不足,真实文件行身份是「单据+行+箱/批」,落档首见为准会静默丢行;②入站文件含生命周期孪生行(DSV 同键 Expected/Closed 各一条);③未完成行(收料日期空)落成永不进匹配的幽灵档;④出站文件无单位列。另外模块将承接出站(outbound)文件,receipt 说辞全面失准。 + +## 1. 已拍板决策(2026-10-15,用户逐项确认) + +- **D1 幂等修复**:自然键扩为 8 成分 `(source_code, record_kind, doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no)` + 「movement_date 非空才落档」过滤。 +- **D2 出站 doc_no**:用 External Order #——属于解析 Profile 映射配置,不动代码。实测 `(External Order #, Line #, Carton ID)` 在出站完成行上完全唯一(6131/6131)。 +- **D3 quantity 口径**:入站 Qty Received / 出站 Quantity 等均为映射配置,不动代码。 +- **D4 单位**:以匹配时 ERP 回传为单位,文件单位列仅为入站参考。本期无代码(出站仅落档结构就位,无匹配链路;入站单位列照常映射)。未来出站匹配实施时按此契约设计。 +- **D5 说辞清扫**:三层方案(§4),第一层全改、第二层交界只注释、第三层默认不做;实施前按本 spec §4 清单再复核一遍。 +- **D6 兼容策略**:一次到位,不留旧路由/旧错误码兼容层(未上线,无存量调用方)。 +- **D7 清空并重解析(2026-10-15 追加拍板)**:解析规则修改后,待匹配面板按来源提供「清空并重新解析」(清空可重建行→当前模板重解析归档文件→常规幂等重落),本轮随批实施,设计见 §6。 + +术语基线:**receipt→inbound(入站)、shipment→outbound(出站)、收料→出入站/入站**;**movement(异动)一词不在清扫范围**——`transfer_movement_ledger`、`MOVEMENT_FIELDS`、`movement_contract` 等命名语义准确,全部保留。**方向中立的明细/单据侧用 movement**:`transfer_invoice_items`/`transfer_documents` 的 `receipt_*` 列更名 `movement_*`(items 不再只装收料产物,出站调拨同样会产生明细,inbound_* 会再次失准)——随行的序列化键、匹配创建参数 `receipt_date_from/to→movement_date_from/to`、Excel 表头同步;表名 `transfer_invoice_items` 与字段 `invoice_no` 本轮不动(单独立项评估)。 + +前置说明:上一话题(已发布解析规则「一键新版本+改绑引导+退役守卫修复」与待匹配重新识别)已搁置(shelved),本轮不做;退役守卫不查收料配置绑定的缺陷修复并入 §4.1 第一层(错误码更名同文件顺手修)。 + +## 2. 幂等修复设计 + +### 2.1 自然键扩维 + +- 迁移(tt14):`uq_transfer_movement_ledger_natural_key` 重建为 8 列成分。carton_id/lot_no 本就是档列(2026-10-14 追加的可选维度字段),无新增列;可空成分已 NOT NULL default ''(防 PG NULL 逃逸),沿用。 +- `ledger_sync.sync_ledger_rows` 批内既有行索引键同步扩为 8 元组;同批同键首见为准逻辑不变。 +- 坍缩审计(`ledger_natural_key_collapse`)保留,扩键后三份实测文件塌缩归零,该守卫退化为纯保险。 +- 档内既有数据:未上线(dev 库仅测试数据),无值迁移需求;`record_kind` 值迁移见 §4.1。 + +### 2.2 movement_date 非空才落档 + +- `ledger_sync` 新增行级前置过滤:`movement_date` 为空 → 计入新分类 `date_skipped`(LedgerSyncOutcome 加字段),不落档、不进任何分支。 +- 与解析层既有过滤(`file_parser._is_unusable_receipt_row`:未收 ASN/零数量行跳过)的关系:解析层是第一道(按旧收料语义),档层是第二道防线(映射无关——即使 Profile 把任何列配到 movement_date,空值行都进不了档)。两层口径一致:**无异动日期 = 未发生异动**。 +- 效果:DSV Expected 孪生行(收料日期空)自动排除,完成行唯一;出站 Cancelled/Executing 行(Actual Ship Date 空)自动排除。 +- 待匹配桶/圈档固定条件的 `movement_date` 非空条件保留(纵深防御)。 + +### 2.3 不变的语义 + +文件 sha 幂等跳过、缺席不删、封存(transfer_executed)永不触碰、D17 圈档互斥、cross_flagged 交叉校验(`in_out_flag='-1'` 计数)全部不变。 + +## 3. 解析规则 purpose 枚举改版:inventory/movement → onhand/inbound/outbound + +- 迁移(tt15):CHECK 约束重建为 `purpose IN ('onhand','inbound','outbound')`;数据迁移 `inventory→onhand`、`movement→inbound`(dev 库 2+3 行);列 server_default 改 `'onhand'`。 +- 模型:`ShippingInventoryParsingProfile` default/server_default/约束声明/docstring 同步。 +- 后端比较点(4 处):`inventory_parsing_profile.py` 白名单 `{'onhand','inbound','outbound'}` 与 `_validate_definition` 默认值;发布校验 `purpose != 'inbound'` 跳过订单 Schema 契约;`shipping_inventory_service._validate_movement_profile_binding`(更名 `_validate_inbound_profile_binding`,错误码 `SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID`→`SHIPPING.INBOUND_PROFILE_INVALID`);运行期门禁 `deps.py`/`movement_file_repository.py` 的 `purpose != 'inbound'`。 +- 前端(~19 处):创建下拉三选项(value onhand/inbound/outbound)、站点绑定下拉过滤(`!== 'inbound'`)、收料配置绑定校验(`=== 'inbound'`)、state 类型。 +- i18n 四语言:`shippingInventory.parsingPurpose` → `{onhand:"库存", inbound:"入站", outbound:"出站"}`(en: On Hand / Inbound / Outbound),配套 hint/label 键同步。 +- **outbound 运行期说明**:出站文件抓取→归档→落档链路本期不存在(出货侧仅结构就位)。outbound 规则可配置、可绑定收料配置以外的场景尚未定义;在出站证据链路落地前,outbound 规则无数据来源、待匹配恒空——fail-closed 天然安全。绑定校验侧收料配置仍限定 inbound 规则。 + +## 4. receipt→inbound 说辞清扫三层清单 + +### 4.1 第一层:in_transit_transfer 域内全改(一次到位,无兼容层) + +**文件改名(3)**:`receipt_file_gate.py→inbound_file_gate.py`、`receipt_callback_bridge.py→inbound_callback_bridge.py`、`receipt_trigger_service.py→inbound_trigger_service.py`(含对应测试文件名)。 + +**类/函数/常量改名(对照表)**: + +| 旧 | 新 | +| --- | --- | +| `ReadyReceiptFile` / `ReceiptFileRepository` / `ensure_receipt_file_ready` | `ReadyInboundFile` / `InboundFileRepository` / `ensure_inbound_file_ready` | +| `ShippingReceiptFileRepository`(movement_file_repository.py 内) | `ShippingInboundFileRepository` | +| `ParsedReceiptRow` / `ReceiptFileSchemaError` / `parse_receipt_rows` | `ParsedMovementRow` / `MovementFileSchemaError` / 并入既有 `parse_movement_rows` | +| `validate_receipt_quantity` 及 `receipt_quantity` 形参 | `validate_inbound_quantity` / `inbound_quantity` | +| `maturity_status(receipt_date)` / `eligible_receipt_date_to` | 形参/函数名 `inbound_date` / `eligible_inbound_date_to` | +| `record_receipt_parse_failure` / `clear_receipt_parse_failure` | `record_inbound_parse_failure` / `clear_inbound_parse_failure` | +| `advance_source_job_from_receipt_callback` | `advance_source_job_from_inbound_callback` | +| `RECORD_KIND_RECEIPT = "receipt"` | `RECORD_KIND_INBOUND = "inbound"`;新增 `RECORD_KIND_OUTBOUND = "outbound"` | +| `RECEIPT_CONTRADICTORY_FLAGS` | `INBOUND_CONTRADICTORY_FLAGS` | + +**DB 列改名(迁移 tt14 内,RENAME COLUMN,约束/索引名均不含 receipt 无需重建)**: +`transfer_invoice_items.receipt_date→movement_date`、`receipt_quantity→movement_quantity`、`receipt_warehouse_code→movement_warehouse_code`;`transfer_documents.receipt_date→movement_date`(明细/单据方向中立,用 movement_*,见 §1 术语基线)。 +**record_kind 值迁移(tt14)**:`UPDATE transfer_movement_ledger SET record_kind='inbound' WHERE record_kind='receipt'`;`'shipment'→'outbound'`(未上线为空操作,test 环境兜底)。调拨类型范围规则若以 `record_kind equals 'receipt'` 配置需同步改值——未上线无存量配置,上线 SOP 冒烟项核对管理页配置。 + +**API 路由(2 条 + 请求参数)**:`POST /sources/receipt-files→/sources/inbound-files`;`GET /runs//receipt-files→/runs//inbound-files`;匹配创建入参 `receipt_date_from/receipt_date_to→movement_date_from/to`(约束的是明细 movement_date)。前端 `transfer.api.ts`/`useChatTransfer`/`transfer.types.ts` 同批同步(D6 无兼容层)。 + +**错误码(四语言 errors.json 键名+值)**:`TRANSFER_RECEIPT_NOT_MATURED→TRANSFER_INBOUND_NOT_MATURED`、`TRANSFER.RECEIPT_DATE_RANGE_INVALID→TRANSFER.MOVEMENT_DATE_RANGE_INVALID`、`RPA_RECEIPT_MOVEMENT_PROFILE_MISSING→RPA_INBOUND_PROFILE_MISSING`、`RPA_RECEIPT_CALLBACK_FAILED/TIMEOUT→RPA_INBOUND_CALLBACK_FAILED/TIMEOUT`、`RPA_RECEIPT_CONFIG_MISSING/UNAVAILABLE/NO_TRIGGERABLE_SOURCE→RPA_INBOUND_CONFIG_MISSING/UNAVAILABLE/NO_TRIGGERABLE_SOURCE`、`SHIPPING.RECEIPT_FILE_NOT_FOUND→SHIPPING.INBOUND_FILE_NOT_FOUND`。 + +**审计事件**:`TRANSFER_RECEIPT_FILES_DOWNLOADED→TRANSFER_INBOUND_FILES_DOWNLOADED`(未上线无历史断档)。 + +**注释/文档**:域内约 170 行「收料」→「出入站/入站」;`docs/features/in-transit-transfer/` 全套文档、`funclist/demand/tec` 对应条目;`docs/features/in-transit-transfer/GLOSSARY.md` 术语——收料登记→入站登记(Inbound Registration)、出货登记→出站登记(Outbound Registration)、收料来源实例→出入站来源实例(Inbound Source Instance)、记录类型「收料/出货」→「入站/出站(inbound/outbound)」。历史 spec/plan/ADR 不改写。 + +**前端**:`downloadTransferReceiptFiles→downloadTransferInboundFiles`、`downloadReceiptFiles→downloadInboundFiles`、`eligibleReceiptDateTo→eligibleInboundDateTo`、emit `download-receipt→download-inbound`、zip 名 `receipt-files-*.zip→inbound-files-*.zip`;**明细字段键** `receipt_date→movement_date`、`receipt_quantity→movement_quantity`、参数 `receipt_date_from/to→movement_date_from/to`;chat.json 四语言:`colReceiptDate→colMovementDate`(异动日期)、`receiptDateHint/Invalid/Label/To→movementDate*`(异动日期…)、`downloadReceiptFiles→downloadInboundFiles`、`retryReceipt→retryInbound`;值文案 23 个「收料」→「出入站/入站/异动」(按语义:待匹配收料记录→待匹配出入站记录、收料来源→出入站来源、收料日期→异动日期、未成熟收料→未成熟入站);admin.json `transferTypes.scopeFieldLabels.source_code`=出入站来源实例、`doc_no`=出入站单号。 + +**顺手修(同文件)**:退役守卫补查 `ShippingReceiptReportConfig` 绑定(`retire` 只查库存站点的缺陷)。 + +**测试**:后端约 30 个测试文件全量改写(含 conftest fixture `file_purpose:"receipt"→"inbound"`)。 + +### 4.2 第二层:交界处不改名,仅注释标注 + +- shipping_notice 域全部 `ShippingReceiptReport*`(模型/表/MinIO 存储/通知/排程 job/workspace 收料工作台/路由 `receipt-reports`/admin 收料配置 i18n)。 +- RPA 跨进程契约:`shipping_receipt_rpa.v1`、action `receipt_export_batch`、trigger 文件名 `receipt_export_batch_*.json`、`FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS`、`scripts/freight_rpa/receipt/` Worker。 +- 域内消费点(更名后为 `deps.py`/`movement_file_repository.py`/`inbound_file_gate.py`/`source_file_status.py`)加注释:「入站证据 = 收料报表 RPA 产物(shipping_notice 域,术语保留)」。 + +### 4.3 第三层:默认不做 + +环境变量 `FREIGHT_RPA_RECEIPT_*` 其余键、admin.json 收料配置段文案(`receiptReportConfig*` 等 25 键)、workspace 收料工作台页面文案。如后续要做,单独立项。 + +## 5. 出站/入站字段映射备忘(供解析 Profile 配置参考,零代码) + +| 档字段 | CRANE 入站 | DSV 入站 | Outbound 出站 | +| --- | --- | --- | --- | +| doc_no | External ASN # | External ASN # | **External Order #**(D2,唯一性已验证) | +| line_no / line_seq | External Line # / 空 | 同左 | External Line # / 空 | +| material_code / material_name | AWS SKU / SKU Description | 同左 | 同左 | +| warehouse_code | Warehouse | Warehouse | Warehouse | +| quantity | Qty Received | Qty Received | Quantity | +| movement_date | Date Received(空=过滤) | 同左 | Actual Ship Date(空=过滤) | +| unit | UOM | UOM | 无列(D4:单位以 ERP 回传为准,未来出站匹配时实施) | +| lot_no | 空 | 空 | Batch | +| order_type / carton_id / pallet_id / odm_id / odm_name | Order Type / ✓ / ✓ / 空 / 空 | Type / ✓ / ✓ / 空 / 空 | Order Type / ✓ / ✓ / ODM ID / ODM Name | +| 日期格式 | ISO(`parse_date` 已支持) | 美式 MM/DD/YYYY(`parse_date` 已支持) | ISO | + +未安放列(Waybill、ASN Status、Check-In Time、PO Number 等)不新增档列——原文件在 MinIO 可回溯,行上有 sheet/row_no 溯源;ASN Status 完成语义由 movement_date 过滤吸收。 + +## 6. 待匹配桶「清空并重新解析」(D7,2026-10-15 追加) + +动机:解析规则(模板)修改后,待匹配桶里的存量档行仍是旧映射产物。此前讨论的「受控更新式重识别」有两个硬障碍——sha 幂等使原地更新需特殊写入路径、键漂移会产生新旧重复行;「清空重建」两者皆避:清空后走**常规** `sync_ledger_rows` 插入,且桶数据 100% 可由 MinIO 归档文件重建(原件保留约 3 年,行上有 sheet/row_no 溯源)——清空不是破坏性操作,是「从证据重建」。 + +**入口**:待匹配面板按来源提供「清空并重新解析」;确认弹窗展示预检结果(归档文件清单与份数、将使用的解析规则 code+version、将清除行数、证据缺失保留行数)。 + +**执行(单事务,service 提交)**: +1. 取该来源**可重建**归档文件(未清理 `archive_deleted_at` 空 + 未过保留期;显式绕过当日门禁的维护路径,与运行期 fail-closed 取数分开实现并注释); +2. **先全量重解析入内存**——任一文件解析失败整体中止、一行不删(AppError 报告文件与原因); +3. 删除该来源「可重建、未封存、未被有效 items 占用」的 inbound 档行(`transfer_executed=false` + 占用排除复用 `_effective_occupancy_filter` 口径 + `source_file_id IN 可用文件`);证据缺失的行保留并在报告列出; +4. 按归档时间序调 `sync_ledger_rows` 重落(当前绑定模板、8 成分键、movement_date 过滤自动生效); +5. commit + 审计事件 `TRANSFER_PENDING_MATCH_REPARSED`(操作人/来源/文件清单/规则版本/前后计数)。 + +**API**:`GET /backlog/pending-match/reparse-preview?source_code=`(预检)+ `POST /backlog/pending-match/reparse`(执行,body `{source_code}`);鉴权沿用相邻 backlog 端点模式。 + +**并发**:删除+重落同事务,匹配圈档读到删前或重落后的完整状态(PG READ COMMITTED 原子切换);管理端低频操作可接受。 + +**解析复用**:从 `evidence_sync.sync_source_rows` 抽出「归档字节→档行」纯函数,运行期落档与重建路径共用单一解析口径,杜绝两套解析漂移。 + +## 7. 兼容与上线 SOP + +- 未上线无存量调用方(D6):前端与后端路由/参数/错误码同仓同批提交,无灰度。 +- 迁移顺序:`flask db upgrade`(tt14 列改名+record_kind 值、tt15 purpose 枚举)随代码发布一次执行;迁移均带 downGRADE(rename 反向 + CHECK 还原)。 +- dev 库验证:5 条解析 profile(2 onhand + 3 inbound)purpose 自动迁移;调拨类型管理页、库存解析页全功能冒烟;CRANE/DSV 样本文件回放落档验证塌缩归零;改一条入站规则映射→待匹配面板预检→清空并重解析→报告行数对得上。 + +## 8. 测试策略 + +- 迁移 round-trip(PG):tt14/tt15 upgrade+downgrade。 +- ledger_sync:8 成分键去重、date_skipped 分类、carton/lot 进键后同文件重落语义、封存/占用守卫回归。 +- 更名全量:后端 pytest 全绿(既有 463 基线 + 新增)、前端 vitest/build 绿、i18n 四语言键集护栏(movementFieldLabels.spec 同款思路覆盖新键名)。 +- 审计/待匹配桶:record_kind=inbound 后桶口径与圈档回归。 +- 清空并重解析(§6):预检形状、解析失败中止不删、封存/占用行幸存、证据缺失行保留、重落后新映射值生效、审计事件字段。 + +## 9. 明确不做(本轮) + +- shipping_notice 收料报表域与 RPA 契约改名(§4.2/4.3)。 +- 出站文件抓取/归档/落档链路(出货侧结构就位即止)、出站匹配执行、出站单位常量映射。 +- 已发布解析规则的「一键新版本/改绑引导/退役前置」UX 简化(已搁置,另立话题);受控更新式重识别(被 §6 清空重建方案替代,不做)。 +- ledger 未安放列扩容、ext_json 原始行存储。 + +## 10. 影响面统计 + +第一层约 90~100 文件(后端 app ~26、后端测试 ~30、前端源码 ~25、i18n 8、文档 ~8);purpose 改版约 18 文件(与第一层大面积重叠,合并实施);迁移 2 个(tt14/tt15,接续 tt13 单 head);清空并重解析(§6)约 10 文件(后端 service/repository 抽取/2 端点/测试、前端面板与预检弹窗/四语言)。 diff --git a/docs/superpowers/specs/2026-10-16-freight-rpa-decouple-and-rename-design.md b/docs/superpowers/specs/2026-10-16-freight-rpa-decouple-and-rename-design.md new file mode 100644 index 00000000..4b905a19 --- /dev/null +++ b/docs/superpowers/specs/2026-10-16-freight-rpa-decouple-and-rename-design.md @@ -0,0 +1,107 @@ +# Freight RPA 独立模块化与 onhand/inbound/outbound 全域改名 — 设计文档 + +日期:2026-10-16 | 状态:**已修订(2026-10-17 术语纠偏)** | 决策依据:`docs/superpowers/plans/2026-10-16-freight-rpa-decouple-and-rename-evaluation.md`(§6 决策记录 + §8 完整性清单)+ `docs/adr/0003-freight-rpa-module-boundary.md` | 术语:`docs/features/freight-rpa/GLOSSARY.md` | 前置:`2026-10-15-inbound-outbound-idempotency-rename`(已实施)| **2026-10-17 纠偏**:outbound **仅**在途调拨出站;货代履约「出货」(shipment) **禁止**改名为 outbound;废除批次 T「shipment→outbound」;upload action 应对齐 `freight_upload`(批次 R 误落的 `outbound_upload` 须改回) + +## 0. 问题陈述(Problem Statement) + +Freight RPA(货代 RPA)的后端编排层寄生在 shipping_notice 业务包内:Worker 早已通过「共享目录 trigger + HTTP 回调 + 心跳」独立运行,且在途调拨已成为第二个消费方,但新业务想接入 RPA 就必须 import 发货通知的业务模块,回调路由也挂在业务 blueprint 下——模块边界持续腐蚀。同时,2026-10-15 改版已把 onhand/inbound/outbound 确立为术语基线,但只覆盖了调拨域与解析 purpose 枚举值:shipping_notice 域(~1.97 万处 inventory、~4100 处 receipt)、RPA 跨进程契约、28 张数据库表与全部权威文档仍用旧词,同一套事实两套叫法,持续误导开发者与 AI 助手。 + +## 1. 解决方案(Solution) + +把 RPA 编排层/调度壳/回调路由收编为独立模块 `freight_rpa`(回调 blueprint `/api/freight-rpa/*`),数据库表全部留在原地;术语改名按批次 **R→S→D** 实施(**原批次 T「shipment→outbound」已废除**):R=RPA 域随解耦一次切换、S=shipping_notice 域含表 rename 与存量数据迁移、D=文档收口。同一发布窗口上线:后端+前端+迁移+Windows Worker 同窗口切换,不做双路由、不留兼容层。**outbound** 仅服务在途调拨出站(目录/解析预留,抓取链路留待未来);**货代履约出货**留在 shipping_notice(`shipment_*`),与 outbound 无关。 + +## 2. 用户故事(User Stories) + +1. 作为平台开发者,我希望 RPA 编排层独立于 shipping_notice 业务包,以便新增 RPA 消费方时不必理解发货通知业务。 +2. 作为平台开发者,我希望 freight_rpa 包的 import 边界被自动化测试守卫(禁止 import 业务 workflow/状态机),以便未来改动不会重新引入反向依赖。 +3. 作为货代运营,我希望库存/入站在代码、契约、目录中统一为 onhand/inbound,出站(outbound)仅用于在途调拨语境,以便与调拨域一致;发货履约「出货」不并入 outbound。 +4. 作为货代运营,我希望收料工作台、文件下载等既有功能仅更名不变行为,以便操作习惯零变化。 +5. 作为 RPA 管理员,我希望 RPA Profile/站点配置的管理入口迁移到 `/api/admin/freight-rpa/*`,以便配置归属清晰。 +6. 作为 RPA 管理员,我希望 Worker 心跳与离线企微告警行为不变,以便监控不中断。 +7. 作为 RPA 管理员,我希望排程任务以新 key(`freight-onhand-rpa`/`freight-inbound-rpa`/`freight-inbound-rpa-retention`)存在且存量排程配置自动迁移,以便无需手工重建。 +8. 作为系统运维,我希望获得 `/wizard` 生成的切换 runbook(暂停排程→确认 Worker 空闲→排空 trigger/drop→迁目录→注册新计划任务并注销旧任务→部署→迁移→冒烟→恢复),以便单窗口内按序执行不漏步。 +9. 作为系统运维,我希望本轮全部新迁移带可执行 downgrade,以便发布失败时 DB 可整体回滚。 +10. 作为系统运维,我希望发布前在 test 环境完整预演 upgrade→冒烟→downgrade→再 upgrade,以便发布日不遇到迁移意外。 +11. 作为系统运维,我希望切换窗口内旧回调端点直接 404(而非静默兼容),以便任何脏回调立即暴露而不是被吞掉。 +12. 作为系统运维,我希望发布窗口有明确回滚单元(旧后端镜像 + 旧 Worker 包 + 迁移 downgrade + 全库备份),以便最坏情况整体回退。 +13. 作为在途调拨集成方,我希望通过稳定接口(trigger 写入 + 回调桥)消费 RPA 产物,以便 RPA 归位不改变调拨行为。 +14. 作为审计查看者,我希望存量审计事件名/step_key 被数据迁移为新术语,以便历史追溯在新词下连续可读。 +15. 作为审计查看者,我希望审计中心的展示映射与筛选项随新事件名更新,以便界面不出现旧词。 +16. 作为前端用户,我希望 i18n 四语言(zh-CN/zh-TW/en/th)文案全部使用新术语,以便四语言一致性不破坏。 +17. 作为前端用户,我希望管理页(库存/入站数据域配置页)与用户端的路由、模块名、权限键全部使用新术语且存量权限数据随迁移,以便权限分配与新结构一致(Q14 最终拍板:随批次 S 改)。 +18. 作为未来开发者(含 AI 助手),我希望权威文档(shipping-notice technical、freight_rpa README、GLOSSARY、funclist/demand/tec、环境变量规则)全部使用新术语,以便按文档写出的代码就是对的。 +19. 作为未来开发者,我希望历史 spec/plan/ADR 不被改写,以便保留当时的决策快照。 +20. 作为货代运营,我希望 outbound 仅作**在途调拨出站**结构预留(解析 purpose 枚举、目录分层),以便未来调拨出站抓取接入时零术语迁移;不与发货履约出货混名。 +21. 作为系统,我希望 trigger schema 升级为 `freight_rpa.onhand.v1`/`freight_rpa.inbound.v1` 且切换时在途文件排空,以便新旧契约不混挂。 +22. 作为合同付款用户,我希望「发货款」付款节点(shipment)完全不受影响,以便无关业务零风险。 +23. 作为平台开发者,我希望错误码族(errors.json 四语言 73+ 个含 INVENTORY 键 + 后端定义与抛点)同批更名,以便错误契约与术语一致。 +24. 作为 RPA 管理员,我希望 CIFS 目录迁移后文件的存取路径按新目录解析而历史 MinIO 对象 key 不变,以便三年归档可追溯。 + +## 3. 实施决策(Implementation Decisions) + +**模块边界与命名(批次 R)** + +- 新包 `freight_rpa`:收编 trigger 写入、心跳与告警、凭据加解密、attempt 计数、站点测试导出编排、回调清理队列;域中立件集中 `freight_rpa/common/` 子层。**表全部不动**,包只 import models 与纯工具。 +- import 边界白名单:freight_rpa 不得 import shipping_notice 的 workflow/状态机模块;`per_source_rpa_service` 同事务写业务模型(ProcessGate/Execution)属于「允许 import models」范畴,其编排入口由业务域调用。 +- 业务→RPA 只经两个稳定面:trigger 写入函数与 `/api/freight-rpa/*` 回调端点(鉴权沿用 Bearer/X-Integration-Key,凭据不轮换)。 +- admin 的 rpa-profiles 管理路由迁 `/api/admin/freight-rpa/*`;批次 R 对前端只改必要的 API URL 字符串,页面/组件/i18n 改名全部留批次 S。 +- Worker 侧回调 path 常量收拢到 `common/` 单点。 + +**跨进程契约(批次 R,一次切换)** + +- trigger schema:`shipping_inventory_rpa.v2`→`freight_rpa.onhand.v1`、`shipping_receipt_rpa.v1`→`freight_rpa.inbound.v1`。 +- 回调 URL:`/api/shipping-notice/rpa/*` 12 条 → `/api/freight-rpa/{onhand,inbound,...}`;Worker 同窗口切换,无双路由。 +- env:`FREIGHT_RPA_SHARED_INVENTORY_*`→`*_ONHAND_*`、`FREIGHT_RPA_RECEIPT_*`→`*_INBOUND_*` 等同形替换;同步四处 `.env.*`、compose 唯一显式透传行、环境变量规则文档;`.env.local` 6 个废弃 SHIPPING_NOTICE_RPA_* 变量顺手删除。 +- CIFS:`freight_rpa/{inventory,receipt}`→`{onhand,inbound}`(新增 `outbound/` 预留),排程静默窗口一次迁移。 +- 排程 job key:`shipping-inventory-rpa`→`freight-onhand-rpa`、`freight-receipt-rpa`→`freight-inbound-rpa`、`freight-receipt-rpa-retention`→`freight-inbound-rpa-retention`,`schedule_tasks.job_key` 存量行 UPDATE,前端 job-key 工具同步。 +- 上传 RPA(无目标词)命名不动;Worker 目录改名后,upload 段仍在 onhand Worker 内一并迁移,不拆独立 Worker。 + +**数据层(批次 S)** + +- **29 张表一次 rename(Q13+Q15+Q16:统一 `freight_rpa_` 一级命名空间,子域第二段)**——共享 2 张:`shipping_inventory_sources`→`freight_rpa_sources`(站点三子域共用)、`shipping_rpa_profiles`→`freight_rpa_profiles`;onhand 子域 14 张:字段/映射/文件/解析/结构分析/配置测试/验证批次/路由 4 件套/绑定审计与 `shipping_task_inventory_rpa_attempts`→`freight_rpa_onhand_*`;inbound 子域 4 张:`shipping_receipt_*`→`freight_rpa_inbound_*`;发货消费事实 10 张保留 shipping 前缀只改词根:候选集 3、准备 2、任务关联 1(`shipping_task_onhand_links`)、临时会话 1、行匹配 1、核验 2→`shipping_onhand_*`。命名与 env/包/蓝图/job key/admin 路由严格同构(`/api/admin/freight-rpa/onhand/fields` ↔ `freight_rpa_onhand_fields`)。索引/约束/外键名、models 类名、相关列名(`inventory_source_id` 族→`source_id`)随迁;迁移用 rename_table + 依赖对象 sweep 收尾。 +- 存量枚举值数据迁移(无兼容层):审计事件名、step_key、step_payload_json/ui_state 动作值(约 40 个前后端契约值)、attempt 行;UPDATE 分批防长锁;迁移前全库备份;全部带可执行 downgrade。 +- 完整清单(含配置 yaml、options_source 注册键、导入脚本、权限键与存量权限数据、文件名模板、已核实无风险项)以评估文档 §8 为权威,spec 不重复罗列。 + +**术语面(批次 S/D;原 T 已废除)** + +- shipping_notice 域代码、前端目录/文件/组件/路由名、i18n(inventory/receipt 键,四语言)、错误码族、权威文档:inventory→onhand、receipt→inbound;**不做** shipment→outbound。履约侧 `shipment_*`(出货 Excel 等)保留在 shipping_notice;合同付款 `shipment`(发货款)永远排除。`movement` 一词保留(10-15 已拍板)。中文文案基线:onhand=库存、inbound=入站、outbound=出站(**仅调拨**);货代履约称「出货」。 +- upload action:应对齐心跳能力 `freight_upload`(批次 R 误用 `outbound_upload` 须在后续提交改回)。 +- 历史归档快照不整篇改写;**本文件与 evaluation / GLOSSARY / 批次 R 计划**作为现行权威已就地纠偏。 +- **admin 配置域随批次 S 改(Q14 + Q13b:货代管理 = onhand/inbound/outbound 三子域)**:outbound 子域预留指**调拨出站配置/抓取**,不是发货履约。路由统一 `/api/admin/freight-rpa/`——共享 `sources`/`rpa-profiles`,onhand `onhand/{...}`,inbound 挂站点 `sources//inbound-report-config`,outbound 同级预留(本期无路由)。temporary-inventory-sessions 归发货业务侧,留 `/shipping-notice/` 只改词根。前端模块→`freight-rpa/`、权限键→`freight_rpa`,存量权限数据随迁移 UPDATE。 + +**发布协议(单窗口)** + +- 批次 **R+S+D** 同一发布窗口(T 已取消独立改名批);窗口纪律:暂停三个 RPA 排程 + 禁止手动 RPA 触发 + 确认 Worker 空闲 + trigger/drop 排空 + 备好回滚单元;全部迁移带 downgrade 且 test 环境预演 upgrade→冒烟→downgrade→upgrade。 +- 分支:从含在途交付的基线切 feature 分支承载 R→S→D。 + +## 4. 测试决策(Testing Decisions) + +好测试只断言外部可见行为(HTTP 响应与副作用、文件契约形状、迁移后的库状态),不断言内部调用关系;迁移测试以「往返可执行 + 终态契约」为行为,grep 门禁与 i18n 键集护栏是 lint 性门禁而非单测。 + +五条接缝(已与用户确认): + +| # | 接缝 | 断言内容 | 先例 | +| --- | --- | --- | --- | +| 1 | HTTP 回调缝(最高) | test client 模拟 Worker 调 `/api/freight-rpa/*`:鉴权→载荷→ScheduleRun 终态/attempt 行/快照/TransferSourceJob 推进;旧端点 404 | receipt rpa callback、inventory rpa workflow 既有测试 | +| 2 | 跨进程文件契约缝 | trigger JSON 形状(schema 串、目录、文件名、四态契约)双侧契约测试 | freight receipt worker contract 测试 | +| 3 | 迁移往返缝 | SQLite upgrade→downgrade→upgrade + 28 表表名/列名/约束 + 枚举值 UPDATE + job_key UPDATE | tt14 迁移契约测试 | +| 4 | 改名完备性缝 | grep 白名单门禁 + i18n 四语言键集护栏 + errors.json 键 parity | movementFieldLabels.spec 思路 | +| 5 | import 边界适应度缝(新增,仅一条) | 扫描 freight_rpa 包 import,workflow/状态机模块出现即失败 | 无 | + +范围:批次 R 重点在缝 1/2/5;批次 S 重点在缝 3/4 + 后端 463 基线 + 前端 vitest/build;两批都跑全量回归(既有环境性失败零新增)。 + +## 5. 范围外(Out of Scope) + +- 阶段 B:表所有权裁决、「文件就绪」事件化、回调事务边界重构、`ShippingInventorySource` 拆分(另立项另立 ADR)。 +- 调拨出站抓取/归档/落档/匹配链路(outbound 仅结构就位);出站单位常量映射。 +- 发货履约 `generate_shipment_excel` / `shipment_qty` / `shipment_*.xlsx` **禁止**改名为 outbound_*(原批次 T 已废除)。 +- contract_payment 的 shipment(发货款)节点;`movement` 一词;`shipping` 模块名与前缀。 +- MinIO 历史 storage_key、历史迁移文件、`docs/superpowers/` 与 ADR 归档、运行日志。 +- 10-15 spec §9 遗留未做项(一键新版本/改绑引导等)继续搁置。 + +## 6. 补充说明(Further Notes) + +- 实施顺序 **R→S→D**(原 T 已废除),同一发布窗口上线(ADR 0003);批次间的内部阻塞边在 to-tickets 阶段声明。 +- 影响面量化(~700 文件/2 万次、41 条路由、636 i18n 键、73+ 错误码键)见评估文档 §4/§8,本 spec 不重复。 +- 术语冲突裁决权:本 spec + GLOSSARY 为准;与旧文档冲突处按 D6「历史不改写、权威必改」处理。 +- 验收总门禁:grep 白名单外清零(白名单 = contract_payment、历史文档)+ 后端 463 基线 + 前端 vitest/build + 四语言键集护栏 + test 预演通过 + 生产窗口冒烟清单全绿。 diff --git a/docs/superpowers/specs/2026-10-18-freight-rpa-phase-b-design.md b/docs/superpowers/specs/2026-10-18-freight-rpa-phase-b-design.md new file mode 100644 index 00000000..c58d7475 --- /dev/null +++ b/docs/superpowers/specs/2026-10-18-freight-rpa-phase-b-design.md @@ -0,0 +1,143 @@ +# Freight RPA 阶段 B — 报表归属与业务解耦设计 + +日期:2026-10-18 | 状态:**已有实施计划**(`docs/superpowers/plans/2026-10-18-freight-rpa-phase-b.md`)| 前置:`docs/superpowers/specs/2026-10-16-freight-rpa-decouple-and-rename-design.md`(阶段 A,批次 R/S/D)| 术语:`docs/features/freight-rpa/GLOSSARY.md` | 决策记录将另立 `docs/adr/0004-freight-rpa-report-ownership.md` + +## 0. 问题 + +阶段 A 把编排、回调路由和 Worker 契约收进 `freight_rpa`。Windows Worker 是独立进程。后端仍是同一个 Flask 进程、同一套数据库。 + +还没解开的是写入权。回调转给发货通知之后,发货通知既落报表文件,又推进自己的门禁,并调用 `advance_source_job_from_inbound_callback` 修改在途调拨的 `TransferSourceJob`。在途调拨直接查询入站报表表。站点、报表配置、报表文件都是 RPA 的数据,发货代码仍在读写它们。 + +表名也还不对齐。管理端上,一个库存站点下面并列着「库存报表配置」和「收料报表配置」。收料配置已是独立表;在手报表的路径、查询条件和解析方案仍在站点行上。解析方案目录用 `purpose` 区分 onhand、inbound、outbound。未提交的批次 S 迁移目标名已改为 `freight_rpa_parsing_profiles`。入站原文件在 `freight_rpa_inbound_report_files`,在手文件仍叫 `shipping_onhand_files`。 + +## 1. 目标与非目标 + +**目标:** 在当前后端进程内,RPA 拥有登录连接、库存站点、报表配置和报表文件。发货通知和在途调拨只选用 `source_code`,只更新自己的任务。 + +报表记录是货代系统导出、由 Worker 抓回的文件: + +| 词 | 含义 | +| --- | --- | +| onhand | 在手库存报表 | +| inbound | 入站报表(界面称收料报表) | +| outbound | 出站报表 | + +履约出货是发货通知自己的出货 Excel 和上传,代码继续用 `shipment_*` 与 `freight_upload`。它不是 outbound。本阶段不改这条链路。 + +**非目标:** + +- 不把 `freight_rpa` 拆成第二个可部署服务,不引入消息队列。 +- 不新做出站抓取。出站配置和出站文件表等出站立项再加,命名与在手、入站相同。 +- 不把履约出货改名为 outbound,不改 `freight_upload`。 +- 不改合同付款的 `shipment`(发货款),不改 `movement`,不改历史 MinIO 对象键。 +- 不改写已有的阶段 A 计划与 spec。 +- 不改这些仍只服务在手的表:`freight_rpa_onhand_fields`(在手字段目录;入站解析用固定领域字段)、外部仓库映射、发货路由规则、配置测试。不改它们的表名和归属。 +- 不把在手文件表里的解析行、字段映射、快照状态拆到另一张表。入站文件表只存原文件,两张表的列保持不同。 + +## 2. 目标结构 + +一个库存站点先存在。在手报表配置和入站报表配置都挂在这个站点上,各最多一行。登录连接是站点引用的另一张表。 + +| 目标表 | 现在的表 | 内容 | +| --- | --- | --- | +| `freight_rpa_profiles` | 同名(旧 `shipping_rpa_profiles`) | 登录连接:地址、账号、密码。界面「连接配置」 | +| `freight_rpa_sources` | 同名(旧 `shipping_inventory_sources`) | 库存站点。留下 `source_code`、`display_name`、`connector_type`、`rpa_profile_id`、`excel_template_id`、`warehouse_resolution_mode`、`fixed_warehouse_id`、`enabled`、`snapshot_ttl_seconds`、`config_version`。不再放报表路径、查询条件和解析方案 | +| `freight_rpa_onhand_report_configs` | 无。三列现在在站点行上 | 在手报表配置:路径、查询条件、解析方案。一个站点一行 | +| `freight_rpa_inbound_report_configs` | 同名(旧 `shipping_receipt_report_configs`) | 入站报表配置。一个站点一行。本阶段不改结构 | +| `freight_rpa_parsing_profiles` | `shipping_inventory_parsing_profiles` | 解析方案目录。`purpose` 区分 onhand / inbound / outbound。批次 S 未执行的迁移直接改到这个表名。模型类为 `ShippingParsingProfile` | +| `freight_rpa_onhand_report_files` | `shipping_onhand_files` | 在手报表文件。只改表名,列保留 | +| `freight_rpa_inbound_report_files` | 同名 | 入站报表原文件。本阶段不改结构 | + +发货通知的候选集、行匹配、核验,以及在途调拨的 `TransferSourceJob`,仍由各自的领域写入。 + +站点要启用,必须已有在手报表配置且其中有解析方案,并且站点上已选发货模板。这是现有约束换了检查位置,不是新规则。 + +## 3. 谁写入 + +RPA 写入并更新:登录连接、站点、在手配置、入站配置、解析方案、在手报表文件、入站报表文件及其单元和投递记录。 + +发货通知和在途调拨不插入、不更新这些表。它们需要数据时调用 RPA 的只读函数: + +- 按 `source_code` 读取站点,以及在手或入站配置里抓取要用的字段 +- 按 `source_code` 取最新一份可用入站报表(文件号、哈希、创建时间、下载标识) +- 按 `file_id` 读取报表内容或受控下载信息 + +触发抓取仍由业务方调用 `freight_rpa` 的 trigger 写入函数。RPA 不调用业务包来决定要不要抓。 + +## 4. 回调 + +Worker 回调仍进入 `/api/freight-rpa/*`。RPA 在自己的事务里校验载荷、按对应报表配置落文件、写抓取尝试,然后提交。提交成功后,在同一次请求里调用使用方注册的处理函数。事实为: + +- `report_kind`:`onhand`、`inbound`、`outbound`。与解析方案的 `purpose` 同一套取值。本阶段实际送达的是 `onhand` 和 `inbound`;`outbound` 留给出站抓取,事实形状不再另改 +- `source_code`、`file_id`、`sha256` +- `ok`,失败时还有 `error_code`、`error_message` + +RPA 不 import 发货工作流,不写 `TransferSourceJob`、发货门禁或排程终态。 + +- 发货通知用 onhand 事实更新自己的快照、候选和门禁。 +- 在途调拨用 inbound 事实把仍处于 `waiting_rpa_callback` 的 `TransferSourceJob` 推进到 `file_ready` 或 `failed`。没有等待中的任务时不改行。 + +处理函数必须能重复执行。同一 `file_id` 再次送达时不重复插入报表,也不重复推进已经离开等待态的任务。处理函数抛错时,回调对 Worker 返回错误,已提交的文件不回滚,Worker 按现有机制重试。 + +`register_sink` 仍是注册点。注册的函数只更新使用方自己的状态。报表归档审计记在 RPA 自己的审计事件上,`freight_rpa` 不再 import `shipping_notice.audit_service`。 + +```text +Worker 回调 + → freight_rpa 校验、落报表、提交 + → 同请求调用处理函数(报表事实) + → 发货通知更新自己的快照/门禁 + → 在途调拨更新自己的 TransferSourceJob + → 处理函数失败:HTTP 错误,文件保留,Worker 重试 +``` + +在途调拨匹配: + +```text +matching_service + → freight_rpa 只读查询(source_code) → 最新可用 inbound 报表 + → 按 file_id 读取内容 +``` + +## 5. 错误处理 + +| 情况 | 行为 | +| --- | --- | +| 载荷非法、站点不存在、对应报表配置不存在 | 不落文件,回调 4xx,不调用处理函数 | +| 落文件失败 | 事务回滚,回调 5xx,Worker 重试 | +| 文件已提交,处理函数失败 | 文件保留,回调 5xx,Worker 重试 | +| 没有等待中的调拨任务 | 调拨处理函数成功返回,不改行 | +| 未注册处理函数 | `FREIGHT_RPA.SINK_NOT_REGISTERED`,不静默丢弃 | + +## 6. 迁移 + +一次迁移完成三件事,并带可执行 downgrade: + +1. 新建 `freight_rpa_onhand_report_configs`,把站点行上的 `report_path_json`、`query_parameters_json`、`parsing_profile_id` 拷入后从站点行删除。`source_code` 不变。 +2. 解析方案目录的最终表名是 `freight_rpa_parsing_profiles`。批次 S 尚未提交、也尚未在任何环境执行 upgrade,因此改的是批次 S 那次迁移的目标名,而不是在它之后再写一条改名迁移。行和 `purpose` 不改。 +3. `shipping_onhand_files` 改名为 `freight_rpa_onhand_report_files`。列不改。 + +downgrade 按相反顺序把表名和三列搬回。 + +## 7. 测试 + +1. 未注册调拨处理函数时,报表行已存在,`TransferSourceJob` 仍停在 `waiting_rpa_callback`。 +2. 同一回调投递两次,报表不重复,调拨任务不重复推进。 +3. 处理函数第一次失败、第二次成功:报表仍是一行,任务最终为 `file_ready`。 +4. 在途调拨通过只读函数取到文件。`in_transit_transfer` 与 `shipping_notice` 不再 import 这些报表和配置模型做查询。 +5. upgrade 后三列在 `freight_rpa_onhand_report_configs`,解析方案表名为 `freight_rpa_parsing_profiles`,在手文件表名为 `freight_rpa_onhand_report_files` 且列还在。downgrade 后在手配置三列回到站点行,在手文件表名回到 `shipping_onhand_files`,解析方案表名回到 `shipping_inventory_parsing_profiles`。库上不会出现 `freight_rpa_onhand_parsing_profiles`。 +6. 缺少在手解析方案或发货模板时,站点不能启用。 +7. `freight_rpa` 不 import `shipping_notice` 或 `in_transit_transfer` 的工作流、状态机和任务推进函数。 + +## 8. 验收 + +- 在手配置与入站配置都是站点下的一对一表,登录连接、站点、解析方案目录、两类报表文件的表名与第 2 节一致,归属 RPA。 +- 发货通知和在途调拨只通过 `source_code` 和只读函数使用它们,并只写自己的任务。 +- 回调落文件不依赖处理函数成功。 +- 履约出货与 `freight_upload` 的行为不变。 +- 迁移可 downgrade。ADR 0004 记录上述归属。GLOSSARY 中的站点不再写「归属 shipping_notice」。 + +## 9. 实施顺序 + +批次 S、D 的现有改动先不提交。解析方案目录的最终表名改在这批未执行的迁移里,随批次 S 第一次 upgrade 生效。批次 T 已废除,不涉及这张表。 + +在手配置新表、在手文件改名、回调拆开仍属阶段 B,设计评审通过后再写实施计划,顺序为:这两项迁移 → 只读查询与 import 边界 → 回调事实与幂等处理函数 → ADR 0004 与 GLOSSARY。阶段 B 的代码改在当前未提交的批次 S/D 工作区上继续,不另起一份已包含错误表名的提交。 diff --git a/docs/superpowers/specs/2026-10-19-freight-rpa-class-prefix-design.md b/docs/superpowers/specs/2026-10-19-freight-rpa-class-prefix-design.md new file mode 100644 index 00000000..0fd3582f --- /dev/null +++ b/docs/superpowers/specs/2026-10-19-freight-rpa-class-prefix-design.md @@ -0,0 +1,107 @@ +# 货代 RPA 类名前缀与上传动作改名 + +日期:2026-10-19 | 状态:**已有实施计划** | 实施计划:docs/superpowers/plans/2026-10-19-freight-rpa-class-prefix.md | 做法:A(类名与 Worker 动作分开改,发货流程用词不动) + +本规格覆盖两处旧约束,只覆盖写明的那一层: + +- 2026-10-17《upload action 纠偏》否决 `freight_rpa_upload`。本规格改回这个动作名,只用于 Worker 心跳能力和 trigger 的 `action`。 +- 阶段 B 规格「不改 `freight_upload`」对上述动作名与心跳能力不再有效。发货阶段名、门禁码、界面文案仍遵守那一句。 + +## 1. 问题 + +表名已经是 `freight_rpa_*`,Python 类仍以 `Shipping` 开头。入站报表、在手报表和站点不属于发货通知。`ShippingInboundReportFile` 这类名字会让调用方以为行归发货通知。 + +上传已经由 `app.services.freight_rpa.upload` 执行。trigger 的 `action` 和心跳能力仍是 `freight_upload`。这个短名和发货单阶段 `freight_upload` 撞车。 + +## 2. 目标与非目标 + +**目标:** + +- `__tablename__` 以 `freight_rpa_` 开头的模型类,类名以 `FreightRpa` 开头。 +- 类名里不再出现连续的 `RpaRpa`。`ShippingInboundRpaUnitRun` 改为 `FreightRpaInboundUnitRun`,`ShippingTaskOnhandRpaAttempt` 改为 `FreightRpaOnhandTaskAttempt`。 +- 站点类改为 `FreightRpaSource`。表 `freight_rpa_sources` 同时服务在手和入站。 +- Worker 心跳能力与 trigger `action` 改为 `freight_rpa_upload`。schema 保持 `freight_rpa.upload.v1`。 +- 不保留旧类名、旧模块路径、旧动作名的别名。后端与 Windows Worker 同一次发布。 + +**非目标:** + +- 不改任何表名、索引名、约束名、外键名。包括仍带重复 `rpa` 的 `freight_rpa_inbound_rpa_unit_runs` 与 `freight_rpa_onhand_task_rpa_attempts`。因此本规格不新增 Alembic 迁移。 +- 不改发货阶段 `freight_upload`、`freight_uploading`,不改门禁码 `freight_upload_rpa`,不改动作码 `retry_freight_upload_rpa`、`poll_freight_upload_rpa`、`trigger_freight_upload_rpa`,不改四语言文案。 +- 不改 `ShippingUploadAttempt` 与表 `shipping_notice_upload_attempts`。 +- 不改发货自己的类:`ShippingNotice`、`ShippingTaskOnhandLink`、候选集、准备轮次、行匹配、在手核销、`ShippingFreightCancellation`、`ShippingExcelTemplate`。 +- 不把履约出货改名为 outbound,不改 `shipment_*`。 +- 不改环境变量 `FREIGHT_RPA_UPLOAD_*`,不改上传回调路径,不改 MinIO 键。 +- 不改写已有的阶段 A、阶段 B、2026-10-17 计划正文。 + +## 3. 类与文件 + +下表每一行都改类名,并改全部 import、类型注解、`relationship` 字符串和 `models/__init__.py` 导出。不留 `Shipping*` 别名。 + +| 现类名 | 新类名 | 表名(不变) | 现文件 → 新文件 | +| --- | --- | --- | --- | +| `ShippingOnhandField` | `FreightRpaOnhandField` | `freight_rpa_onhand_fields` | `shipping_onhand_config.py` → `freight_rpa_config.py` | +| `ShippingRpaProfile` | `FreightRpaProfile` | `freight_rpa_profiles` | 同上 | +| `ShippingOnhandSource` | `FreightRpaSource` | `freight_rpa_sources` | 同上 | +| `ShippingOnhandReportConfig` | `FreightRpaOnhandReportConfig` | `freight_rpa_onhand_report_configs` | 同上 | +| `ShippingOnhandSourceParsingBindingAudit` | `FreightRpaSourceParsingBindingAudit` | `freight_rpa_onhand_source_parsing_binding_audits` | 同上 | +| `ShippingParsingProfile` | `FreightRpaParsingProfile` | `freight_rpa_parsing_profiles` | 同上 | +| `ShippingOnhandStructureAnalysis` | `FreightRpaOnhandStructureAnalysis` | `freight_rpa_onhand_structure_analyses` | 同上 | +| `ShippingOnhandConfigurationTestRun` | `FreightRpaOnhandConfigurationTestRun` | `freight_rpa_onhand_configuration_test_runs` | 同上 | +| `ShippingOnhandValidationBatch` | `FreightRpaOnhandValidationBatch` | `freight_rpa_onhand_validation_batches` | 同上 | +| `ShippingOnhandRoutingRule` | `FreightRpaOnhandRoutingRule` | `freight_rpa_onhand_routing_rules` | 同上 | +| `ShippingOnhandRoutingRuleCondition` | `FreightRpaOnhandRoutingRuleCondition` | `freight_rpa_onhand_routing_rule_conditions` | 同上 | +| `ShippingOnhandRoutingRuleVersion` | `FreightRpaOnhandRoutingRuleVersion` | `freight_rpa_onhand_routing_rule_versions` | 同上 | +| `ShippingOnhandExternalMapping` | `FreightRpaOnhandExternalMapping` | `freight_rpa_onhand_external_mappings` | 同上 | +| `ShippingInboundReportConfig` | `FreightRpaInboundReportConfig` | `freight_rpa_inbound_report_configs` | `shipping_inbound_report.py` → `freight_rpa_inbound_report.py` | +| `ShippingInboundRpaUnitRun` | `FreightRpaInboundUnitRun` | `freight_rpa_inbound_rpa_unit_runs` | 同上 | +| `ShippingInboundReportFile` | `FreightRpaInboundReportFile` | `freight_rpa_inbound_report_files` | 同上 | +| `ShippingInboundNotificationDelivery` | `FreightRpaInboundNotificationDelivery` | `freight_rpa_inbound_notification_deliveries` | 同上 | +| `ShippingOnhandMapping` | `FreightRpaOnhandMapping` | `freight_rpa_onhand_mappings` | `shipping_onhand_mapping.py` → `freight_rpa_onhand_mapping.py` | +| `ShippingTaskOnhandRpaAttempt` | `FreightRpaOnhandTaskAttempt` | `freight_rpa_onhand_task_rpa_attempts` | `shipping_onhand_task_rpa_attempts.py` → `freight_rpa_onhand_task_attempts.py` | +| `ShippingOnhandFile` | `FreightRpaOnhandReportFile` | `freight_rpa_onhand_report_files` | 从 `shipping.py` 拆到 `freight_rpa_onhand_report_file.py` | + +`shipping.py` 改完后只保留发货通知、任务事件、清除审计、任务与在手文件关联,以及订单接入相关类。 + +这些类上仍指向站点、且名字还是 inventory / receipt 的关系属性一并改名。索引名不动。 + +| 现属性 | 新属性 | 所在类(用新类名) | +| --- | --- | --- | +| `inventory_source` | `source` | `FreightRpaOnhandReportConfig`、`FreightRpaOnhandExternalMapping`、`FreightRpaInboundReportConfig`、`FreightRpaInboundUnitRun` | +| `receipt_report_config` | `inbound_report_config` | `FreightRpaSource` | + +`onhand_report_config`、`external_mappings`、`rpa_profile`、`parsing_profile` 保持原属性名。 + +## 4. 上传动作 + +只改下面三个字面量,从 `freight_upload` 改为 `freight_rpa_upload`: + +- `app.services.freight_rpa.common.worker_heartbeat.FREIGHT_UPLOAD_CAPABILITY`。常量改名为 `FREIGHT_RPA_UPLOAD_CAPABILITY`。 +- `app.services.freight_rpa.upload.trigger_io.ACTION_FREIGHT_UPLOAD`。常量改名为 `ACTION_FREIGHT_RPA_UPLOAD`。写入 trigger 的 `action` 使用该常量。 +- `scripts/freight_rpa/common/rpa_heartbeat.py` 在开启上传时追加的能力字符串。 + +`trigger_io.SCHEMA` 保持 `freight_rpa.upload.v1`。 + +就绪检查函数名保持 `check_freight_upload_rpa_ready` 与 `assert_freight_upload_rpa_ready`。它们检查的是发货门禁能否放行,函数名继续带门禁码;函数内部改读 `FREIGHT_RPA_UPLOAD_CAPABILITY`。 + +已落在共享目录、`action` 仍为 `freight_upload` 的 trigger 不改写、不双读。发布前清空 upload 的 triggers 与 queue。发布后 Worker 只声明并处理 `freight_rpa_upload`。 + +## 5. 错误处理 + +旧类名 import 直接失败,不提供兼容导出。 + +旧动作名不映射到新动作名。心跳里没有 `freight_rpa_upload` 时,现有就绪检查仍按缺少上传能力阻断自动上传,原因码改为 `missing_freight_rpa_upload_capability`。不保留 `missing_freight_upload_capability`。 + +## 6. 文档 + +实现时改这些现行文档,不改历史计划正文: + +- `docs/features/freight-rpa/GLOSSARY.md` 的 Upload 条:action 与心跳能力写 `freight_rpa_upload`。 +- `docs/features/freight-rpa/cutover-runbook.md` 里把「`freight_upload` 不变」改成新动作名,并写上发布前清空 upload triggers/queue。 + +## 7. 测试 + +- `tests/services/freight_rpa/test_upload_trigger_contract.py`:`action`、心跳能力等于 `freight_rpa_upload`,schema 仍为 `freight_rpa.upload.v1`,且两者相等。 +- 心跳就绪测试:缺少 `freight_rpa_upload` 时原因含 `missing_freight_rpa_upload_capability`。 +- 在 `backend/app` 与 `scripts/freight_rpa` 中检索旧类名,结果为空。 +- 在 `trigger_io.py`、`app/services/freight_rpa/common/worker_heartbeat.py`、`scripts/freight_rpa/common/rpa_heartbeat.py` 中,动作与能力字面量 `"freight_upload"`、旧常量名 `FREIGHT_UPLOAD_CAPABILITY` 与 `ACTION_FREIGHT_UPLOAD` 结果为空。函数名 `check_freight_upload_rpa_ready`、`assert_freight_upload_rpa_ready` 保留。发货阶段与门禁文件里的 `freight_upload` 允许留下。 +- 不新增迁移测试。 diff --git a/docs/superpowers/specs/2026-10-19-freight-rpa-outbound-and-rename-design.md b/docs/superpowers/specs/2026-10-19-freight-rpa-outbound-and-rename-design.md new file mode 100644 index 00000000..b0d0eb65 --- /dev/null +++ b/docs/superpowers/specs/2026-10-19-freight-rpa-outbound-and-rename-design.md @@ -0,0 +1,183 @@ +# 货代 RPA:报表规则 / 来源站点改名 + 出站全栈 + 入站运维瘦身 + +日期:2026-10-19 | 状态:**已有实施计划**(`docs/superpowers/plans/2026-10-19-freight-rpa-outbound-and-rename.md`)| 前置:`docs/superpowers/specs/2026-10-18-freight-rpa-phase-b-design.md`、`docs/superpowers/specs/2026-10-19-freight-rpa-class-prefix-design.md`(假定 `FreightRpa*` 已落地或同发布先合入)| 术语:`docs/features/freight-rpa/GLOSSARY.md` | ADR:延续 `docs/adr/0004-freight-rpa-report-ownership.md`(本规格注册 outbound handler) + +## 0. 问题 + +管理端货代域仍用「库存解析」「库存站点」「收料报表」等旧称,与已落地的 onhand / inbound 代码语义不一致。解析用途里虽有 `purpose=outbound`,但 UI/校验仍按库存字段目录占位;出站抓取(配置表、Worker、排程、回调、事实分发)未实施,仅有共享目录与 env 占位。 + +入站侧另有两处过度设计:`freight_rpa_inbound_notification_deliveries` 仅服务工作台「重发企微」幂等账,日常通知已由排程任务的通知人清单 + `_notify_schedule_run_wecom` 覆盖;工作台「收料文件」页与排程管理的 run 查询 / raw-zip 下载重叠。 + +## 1. 目标与非目标 + +**目标** + +1. 用户可见改名(四语言):`库存解析` → **报表规则**;`库存站点` → **来源站点**;`收料报表配置` → **入站报表配置**。父级菜单「库存管理」、页内「库存字段目录」不改。 +2. 来源站点详情新增 **出站报表配置**,与入站配置同构(路径 / 查询条件 / 解析绑定)。 +3. `purpose=outbound` 解析改为与 inbound 相同的 **标准异动字段**(`MOVEMENT_FIELDS`)契约;纠正现有 onhand 形态占位。 +4. 出站全栈镜像入站(做法 A:逐文件克隆,不先做泛化重构):配置 / unit / file 三表、trigger schema、独立 Worker、排程 + retention、回调、排程运维(unit 列表/重试/raw-zip)、在途调拨按需触发、`report_kind=outbound` handler + sinks。 +5. 管理端代码命名:`receipt*` → `inbound*`(对外已是 `inbound-report-config` 的路径保持;`receipt-raw-zip` → `inbound-raw-zip`,无兼容别名)。 +6. 入站瘦身:删除 deliveries 表与「重发企微」;下线工作台收料文件页;运维统一到排程管理。通知人须为可进入排程管理的管理员。 + +**非目标** + +- 不改父级「库存管理」、不改「库存字段目录」信息架构。 +- 不把履约「出货」/`shipment_*`/`freight_upload`/upload 域改名为 outbound。 +- 不把入站/出站配置纳入来源站点启用硬门槛(与入站现状一致:可选配置,触发时 fail-closed)。 +- 不做 outbound 旧解析草稿的自动字段迁移。 +- 不重做 class-prefix;出站类一律 `FreightRpaOutbound*`。 +- 不在本规格改在途调拨匹配算法,只接线 outbound 报表事实。 +- 不新建工作台「出站文件」页。 +- 出站不建 `notification_deliveries`;入站该表删除后亦不重建。 + +## 2. 已拍板决策 + +| 编号 | 决策 | +| --- | --- | +| D1 | 出站解析对齐入站异动契约(`MOVEMENT_FIELDS`) | +| D2 | 注册 `report_kind=outbound` handler + 调拨 sink(对称入站) | +| D3 | 改名含用户可见文案 + 管理端 `receipt*` 符号清理;回调路径无兼容层 | +| D4 | 单发布:改名 + 出站全栈 + 入站瘦身同交付 | +| D5 | 出站配置非启用硬门槛 | +| D6 | 出站触发 = 排程 `freight-rpa-outbound`(+ retention)+ 调拨 `outbound_trigger_service` | +| D7 | DBS 路径/查询可配;Crane 固定出站报表页(实名实现时对接,规格约束:固定页、不按 Warehouse 拆分) | +| D8 | 旧 onhand 形态 outbound 草稿:发布失败,人工重建 | +| D9 | 通知只走排程通知人清单;无逐文件企微投递账 | +| D10 | 父级「库存管理」不改 | +| D11 | 假定 `FreightRpa*` class-prefix 已落地或同发先合入 | +| D12 | RPA 层不强制 `in_out_flag`;方向过滤留在调拨域 | +| D13 | 库存字段目录保留,仅服务 onhand | +| D14 | 入口文案最终为 **报表规则**(非「文档规则」) | +| D15 | 删除入站 deliveries + resend API + 工作台收料页;运维归排程 | + +**实现路径:做法 A**(入站模板逐文件克隆)。否决:先抽象 MovementReport 泛化层(B);复用入站 Worker 目录承载出站(C)。 + +## 3. 数据模型与解析契约 + +### 3.1 解析 Profile + +| purpose | 字段契约 | 管理端 | +| --- | --- | --- | +| `onhand` | 库存字段目录 + `match_keys` | 不变 | +| `inbound` | `MOVEMENT_FIELDS` | 不变 | +| `outbound` | 与 inbound 相同 | 纠正:异动映射 UI/校验 | + +创建后 purpose 不可改。保存/发布 outbound 必须通过与 inbound 同源的异动必填映射校验。 + +### 3.2 出站新建表(三张) + +| 类 | 表 | +| --- | --- | +| `FreightRpaOutboundReportConfig` | `freight_rpa_outbound_report_configs` | +| `FreightRpaOutboundUnitRun` | `freight_rpa_outbound_rpa_unit_runs` | +| `FreightRpaOutboundReportFile` | `freight_rpa_outbound_report_files` | + +配置字段与入站同构:`source_id`(1:1)、`parsing_profile_id`(仅 published 且 `purpose=outbound`)、`report_path_json`、`query_parameters_json`、`config_version`。无独立启停:是否运行 = 来源站点 `enabled` ∧ 配置存在且可解析。 + +`FreightRpaSource` 增加 `outbound_report_config` 关系(并列 `onhand_report_config` / `inbound_report_config`)。 + +### 3.3 报表事实分发 + +在阶段 B 白名单上注册 `handle_outbound_report` 与 `register_outbound_sinks`。在途调拨消费出站事实;方向过滤不在 RPA 层新增规则。 + +### 3.4 入站拆除 + +Alembic:`DROP` `freight_rpa_inbound_notification_deliveries`。删除模型 `FreightRpaInboundNotificationDelivery`、`deliver_inbound_file`、`POST /api/admin/inbound-report-files//resend`,以及仅服务于该账本的测试。 + +工作台下线:`/workspace/inbound-reports` 路由、侧栏入口、`InboundReportFilesPage`、workspace `inbound-report-files` list/download API,以及仅被该页使用的 `shipping_notice.inbound_report_access` 模块(当前无其它调用方)。失败 unit 重试保留在**排程管理 / admin inbound-rpa-units**;原始包下载保留在排程 `inbound-raw-zip`。 + +## 4. API / 管理端 / 触发 / Worker + +### 4.1 管理端 API + +| 能力 | 说明 | +| --- | --- | +| `GET/PUT .../sources//inbound-report-config` | 已有;服务层/前端符号 `receipt*` → `inbound*` | +| `GET/PUT .../sources//outbound-report-config` | 新增,镜像入站 | +| parsing-profiles | `purpose=outbound` 走异动校验 | +| `receipt-raw-zip` → `inbound-raw-zip` | 无别名;企微深链参数同发 | + +### 4.2 Worker 回调与契约 + +新增(镜像入站): + +- `/api/freight-rpa/outbound-batch-ready` +- `/api/freight-rpa/outbound-unit-progress` +- `/api/freight-rpa/outbound-batch-progress` + +Trigger:schema `freight_rpa.outbound.v1`,action `outbound_export_batch`,文件名 `outbound_export_batch_{run_no}.json`。 +心跳能力:`outbound_export`;Worker ID:`*-outbound`。 +目录(env 多已占位):`FREIGHT_RPA_SHARED_OUTBOUND_{TRIGGER,DROP}_DIR`、`FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR`、`FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS`。 + +**跨机路径契约(硬约束,复现 onhand/inbound 历史事故禁止项)** + +Windows Worker 与 Linux 后端通过同一 SMB 共享看到不同绝对路径根(如 `C:\HxopsRpaTest\data\freight_rpa\outbound\drop\...` vs `/mnt/hxops-rpa-*-data/freight_rpa/outbound/drop/...`)。历史上曾因回调 `file_path` 携带 Windows 分隔符/`\` 绝对路径,在 Linux 侧按原样打开导致成功抓取后全程 400(入站于 2026-10-08 按「只认文件名」修复)。 + +出站必须遵守: + +1. Worker 回调 `file_path` **优先只报 drop 根内的文件名**(单一路径段,无目录)。 +2. 后端读取时:**禁止**把 Worker 绝对路径当 Linux 路径直接 `open`;一律 `Path(str(file_path).replace('\\', '/')).name` 取末段,再拼到本机 `FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR` 根下,并用 `resolve().relative_to(root)` 防穿越。 +3. 实现时对照入站 `_read_inbound_callback_file`(`freight_rpa/inbound/report_archive.py`)与在手 `resolve_shared_inventory_drop_file`(`onhand/workflow_protocol.py`);出站可抽共用 helper,但**不得**弱化「只认文件名」语义。 +4. 必须有回归测试:载荷带 `C:\\...\\outbound\\drop\\foo.xlsx` 与仅 `foo.xlsx` 均能读到 Linux drop 内同名文件;带 `..\\` 的路径被拒绝。 + +### 4.3 排程与运维 + +- 平台任务:`freight-rpa-outbound`、`freight-rpa-outbound-retention` +- Admin:`outbound-rpa-units`(list/retry)、`GET .../schedule-runs//outbound-raw-zip` +- 入站排程文案「收料」→「入站」;finalize 仍用排程通知人清单发企微(可附 raw-zip,与现网库存/入站一致) + +### 4.4 按需触发 + +新增 `outbound_trigger_service`(镜像 `inbound_trigger_service`):一源一单元;站点停用 / 出站配置缺失 / 登录连接缺失 → fail-closed。 + +### 4.5 脚本 + +`scripts/freight_rpa/outbound/`:`outbound_rpa_worker.py`、`start_outbound_worker.ps1`、`register_outbound_worker_tasks.ps1`、DBS/Crane export 驱动。Windows 任务名与入站同构独立(如 `HXOPS Freight Outbound RPA Worker TEST/PROD`)。后端与 Worker **同发**。 + +### 4.6 管理端 UI + +- `FreightRpaPage`:侧栏/标题改为报表规则、来源站点;来源站点详情三块折叠——库存报表|入站报表|出站报表。 +- 报表规则:outbound 与 inbound 共用异动映射交互。 +- 排程工作台:outbound job key、Worker 轮询 scope=`outbound`。 + +## 5. 错误处理 / 测试 / 文档 / 发布 + +### 5.1 错误 + +新增出站错误码(镜像入站超时/Worker 离线等),四语言 `locales/*/errors.json` 同步。统一 envelope / `AppError` / `requestJson` / `useMessage`。 + +### 5.2 测试最低集 + +- outbound 异动校验;旧 onhand 形态 outbound 发布失败 +- 出站配置 GET/PUT、1:1、绑定约束 +- 排程/按需 trigger 契约;回调 → 归档 → dispatch(fake sink) +- grep gate:无 deliveries / resend / 工作台收料页引用 +- i18n/导航:报表规则、来源站点、入站报表 +- Worker env 目录契约 + +### 5.3 文档(同 PR) + +- `GLOSSARY.md`:出站改为已交付抓取;注明无 deliveries、无工作台收料页 +- `docs/features/shipping-notice/technical.md`:改名 + 出站部署对称入站 §1.9 +- `docs/funclist.md`:补出站 RPA 与改名 +- 环境变量权威文档确认 `FREIGHT_RPA_*OUTBOUND*` +- ADR 0004 Consequences:本阶段注册 outbound handler + +### 5.4 发布 + +- class-prefix 先合入或同发 +- 迁移:新建出站三表 + drop inbound deliveries +- 共享目录创建 `freight_rpa/outbound/{triggers,drop,logs,archives}` +- 先 Worker 心跳就绪再挂排程;不提交密钥 + +## 6. 成功标准 + +- 管理端可见文案符合 §1;来源站点可独立维护入站/出站报表配置。 +- 出站排程与按需触发可跑通:trigger → Worker → 回调 → 文件归档 → outbound 事实分发。 +- 排程管理可查 outbound run、下载 outbound-raw-zip、重试失败 unit;企微走排程通知人。 +- 工作台无收料文件入口;无 deliveries 表与 resend 企微 API。 +- `frontend` 相关改动 `npm run build` 通过;关键后端测试与 grep gate 通过。 + +## 7. 后续实施 + +实施计划:`docs/superpowers/plans/2026-10-19-freight-rpa-outbound-and-rename.md`。按任务执行;提交须用户显式授权。 diff --git a/docs/superpowers/specs/2026-10-19-transfer-evidence-stream-ui-design.md b/docs/superpowers/specs/2026-10-19-transfer-evidence-stream-ui-design.md new file mode 100644 index 00000000..4892824b --- /dev/null +++ b/docs/superpowers/specs/2026-10-19-transfer-evidence-stream-ui-design.md @@ -0,0 +1,29 @@ +# 调拨来源选择:按证据流显示状态、重试与下载 + +日期:2026-10-19 + +对话已确认的界面与范围。实施计划:`docs/superpowers/plans/2026-10-19-transfer-evidence-stream-ui.md`。 + +## 目的 + +操作员在来源选择卡上能看出每个来源实例的入站、出站是否各自就绪,并只重试当前调拨类型还缺的那条证据流。下载仍是一个按钮,压缩包内按记录类型分目录。 + +## 已定决策 + +- 状态粒度是来源实例 × 记录类型。不拆来源行,不做「部分就绪」。 +- 不新增调拨类型字段,不改调拨类型表单。入站还是出站,读该类型已有的范围规则:字段为 `record_kind`(表单下拉里的「记录类型」)的那几条,值里的 `inbound` / `outbound`。 +- 一条类型没有「记录类型」规则时,入站和出站都要。规则里只写了其中一种,就只要那一种。来源卡、批量重试、下载、圈档都读这一结果,不看类型编码。 +- 来源行只显示当前调拨类型声明的证据流。缺报表配置时状态为「未配置」。 +- 行形态:`DSV360_AWSBI_BYAWSCMH01 [入站 √就绪 ↻] [出站 ⟳抓取中]`。重试是括号内的 `↻`,可读名称「重试入站」或「重试出站」。抓取中不显示 `↻`。行上不出现「重试」「文件」。 +- 点状态字展开该流当天清单:文件名、抓取时间、sha256、文件大小、预览、下载。不解析 Excel,不新增行数字段。 +- 选择条仍是三个按钮。下载文案为「下载证据文件」。压缩包名 `evidence-files-.zip`,路径 `inbound//` 与 `outbound//`,只打包当前类型所需且已就绪的文件。 +- 批量重试仍是一个按钮。按当前调拨类型的 `record_kinds`,只重试尚未就绪、且不是抓取中、且已配置的流。行上的 `↻` 可对已就绪的流强制重试。 +- 确认匹配:该来源每一条所需流为 `ready` 或 `no_data` 才可提交。混合选择沿用披露条,并写明记录类型。 +- 圈档固定条件里的 `record_kind='inbound'` 改为 `record_kinds_of(该类型的范围规则)`。没有类型对象的调用方显式只圈入站。 + +## 不做 + +- 不拆两个下载按钮,不拆两个批量按钮。 +- 不为出站复制来源实例行。 +- 不把整张卡改成大触控尺寸。 +- 不改货代 RPA Worker、排程和回调契约。 diff --git a/docs/superpowers/specs/2026-10-21-transfer-current-file-reparse-design.md b/docs/superpowers/specs/2026-10-21-transfer-current-file-reparse-design.md new file mode 100644 index 00000000..9bd3f43e --- /dev/null +++ b/docs/superpowers/specs/2026-10-21-transfer-current-file-reparse-design.md @@ -0,0 +1,32 @@ +# 当前归档重新解析 + +日期:2026-10-21 + +来源选择卡在文件已经落地之后,需要一条不触发 RPA 的重新解析入口。出站回调落档失败(例如 `file_version` 超长)会被桥接吞掉,文件状态仍是就绪,异动档没有行。只在 `parse_failed` 上重试,覆盖不到这种情况。↻ 继续表示重新抓取。 + +## 行为 + +- 入站和出站各自有「重新解析」。当天该流已有可用归档时可以点,状态是就绪或解析失败都可以。 +- 只解析该流当前最新一份可用归档(`created_at`、`id` 倒序第一条,与 `latest_usable_*_file` 相同),并幂等写入异动档。不写 RPA trigger。 +- 请求不接受 `file_id`。服务端自己取最新一份,避免清单过期时重放历史文件。 +- 同一份文件再解析一次:摘要未变则跳过已有档行,不另插一行。 +- 没有可用归档:422 `TRANSFER.CURRENT_REPARSE_NO_FILE`。 +- 有归档但没有已发布的对应 purpose 规则:422 `TRANSFER.CURRENT_REPARSE_NO_PROFILE`。不把文件标成解析失败。规则缺失不是文件错误。 +- 结构校验失败(`MovementFileSchemaError`):回滚档行,把 `parse_failed` 写到当前文件,HTTP 200,`ok: false`,`file_status: parse_failed`,带 `error_message`。 +- 其他异常(数据库截断、连接失败):回滚,不标解析失败,HTTP 200,`ok: false`,`error_message` 为异常文本。文件状态保持原投影。 +- 成功:HTTP 200,`ok: true`,返回 `inserted` / `updated` / `skipped` / `sealed_skipped` 和解析后的 `file_status`。审计沿用落档函数已有的 `TRANSFER_EVIDENCE_SYNCED`,不另造事件。 +- `file_version` 只经 `movement_file_version`。本入口不自己拼版本戳。 + +## 界面 + +展开来源卡某条证据流的当天清单后,只有第一行(当前文件)在预览、下载旁边显示「重新解析」。更旧的归档只有预览和下载。 + +点下去调用 `POST /api/in-transit-transfer/sources/{source_code}/reparse`,body 只有 `{ "record_kind": "inbound" | "outbound" }`。成功或 `ok: false` 后刷新来源状态和这一条清单。↻ 与 `POST /sources/{source_code}/retry-rpa` 的行为不变。 + +待匹配「清空并重新解析」(`POST /backlog/pending-match/reparse`)仍是改规则后的整桶重建,本入口不调用它,也不删除已有档行。 + +## 不做 + +- 不改 ↻、批量重试、Worker、回调契约。 +- 不给历史归档逐份重放。 +- 不在部署或进程启动时自动补解析已经落地的文件。 diff --git a/docs/tec.md b/docs/tec.md index 4d19004d..303c1684 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -247,12 +247,12 @@ PDF 证据锚定优先使用现有 `pypdfium2` 逐字文本坐标定位,并由 - 当前预置核心清单为 13 个 Header 加 12 个 Line(共 25 个):Header 为 `po_number`、`customer_code`、`customer_name`、`bill_to_customer`、`bill_to_address`、`ship_to_customer`、`ship_to_address`、`destination`、`currency`、`incoterm`、`required_date`、`order_date`、`payment_term`;Line 为 `line_no`、`part_number`、`customer_part_number`、`aws_part_number`、`reservation_id`、`qty`、`uom`、`unit_price`、`amount`、`warehouse`、`inventory_source_hint`、`remark`。历史“26 个”计数中的 `bill_to_customer_code` 已按业务决定替换为 `bill_to_address`;`position` 仅为行排序键,二者均不新增为核心字段。料号和预约单为字符串,数量/金额为 `Decimal/Numeric`,不得使用浮点数;管理员可按业务增加扩展字段。 - `ShippingOrderSnapshot` / `ShippingOrderSnapshotLine` 同步保存预置核心的强类型列、正式 `customer_id`、客户简码和规则版本,并以稳定 `field_id` JSON 冻结所有已发布扩展字段;库存、导出、RPA 是否消费扩展字段由已发布业务配置决定。库存、导出、RPA 与其测试不得读取 `ShippingOrderFieldValue` 作为业务真相;`ShippingOrderReviewEvent` 保存人工纠错的原值、新值、证据、原因、人员和时间。 -- `ShippingReservation` 是预约单全局注册表,唯一键为 `reservation_id`,保存当前有效快照行和状态;`ShippingInventoryVerification` / Line 保存每轮库存快照和逐预约单结论;`ShippingNotice` 是同一 PO 可多次创建的独立发货通知边界,冻结选中行、唯一 `business_no` 和状态;`ShippingExportArtifactLine` 建立预约单到 Excel 的唯一有效归属。 +- `ShippingReservation` 是预约单全局注册表,唯一键为 `reservation_id`,保存当前有效快照行和状态;`ShippingOnhandVerification` / Line 保存每轮库存快照和逐预约单结论;`ShippingNotice` 是同一 PO 可多次创建的独立发货通知边界,冻结选中行、唯一 `business_no` 和状态;`ShippingExportArtifactLine` 建立预约单到 Excel 的唯一有效归属。 - `ShippingUploadAttempt` 以 `(artifact_id, attempt_no)`、`idempotency_key` 与 `callback_id` 约束一次上传事实,记录模式、起止时间、错误、操作人和外部上传参考。人工上传只确认 Notice 已处理,不上传或依赖回执、截图或 PDF。成功回调原子锁定本 Artifact 所有预约单为 `uploaded`;失败保持预约单占用,明确货代拒绝后才允许授权作废并释放。每个 Notice 仅允许一个 Artifact;后续库存波次必须创建新的 Notice。 - 状态机为 `pending -> available -> artifact_reserved -> uploaded`,`pending|available|artifact_reserved -> external_change_required`;Artifact 作废仅在外部明确拒绝且授权后释放对应预约单。`SHIP_AVAILABLE_ROLLING` 仅在至少一个 `available` 时进入 `READY_TO_EXPORT`,生成操作以行锁/唯一约束一次性领取所有当前可用行。 - Excel 命名规则由已发布模板的 `filename_pattern` 定义;未定义时读取环境变量 `SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN`。两者均由后端编译、校验并在 Artifact 保存规则来源、版本、最终文件名和独立流水。客户端请求不得携带命名模式或文件名;流水即使 Artifact 作废亦不得复用。 - LLM Observation 必须有真实 `evidence_ref`,并以 `evidence_verified=false` 落库;任意关键字段存在该类 Observation 时,冻结门禁返回 `SHIPPING.ORDER_LLM_REVIEW_REQUIRED`。Dify 故障只能转人工复核,不能使确定性模板路径降级为猜测。 -- JSON API 按统一 envelope 返回。关键错误码至少包括 `SHIPPING.ORDER_SNAPSHOT_FROZEN`、`SHIPPING.ORDER_LLM_REVIEW_REQUIRED`、`SHIPPING.RESERVATION_CONFLICT`、`SHIPPING.INVENTORY_STALE`、`SHIPPING.EXPORT_NOT_READY`、`SHIPPING.UPLOAD_EVIDENCE_REQUIRED`;权限矩阵禁止 Dify/普通用户调用冻结、制单、上传回调和作废接口。 +- JSON API 按统一 envelope 返回。关键错误码至少包括 `SHIPPING.ORDER_SNAPSHOT_FROZEN`、`SHIPPING.ORDER_LLM_REVIEW_REQUIRED`、`SHIPPING.RESERVATION_CONFLICT`、`SHIPPING.ONHAND_STALE`、`SHIPPING.EXPORT_NOT_READY`、`SHIPPING.UPLOAD_EVIDENCE_REQUIRED`;权限矩阵禁止 Dify/普通用户调用冻结、制单、上传回调和作废接口。 - **引用与快照**:规则保存发布时的 `context_field_id`,发布/运行快照同时冻结字段代码、显示名、Schema 字段配置、规则集版本、定义和命中证据。运行期**以 `field_code`(语义键)优先绑定**当前 Schema 字段,快照 `context_field_id`(UUID) 仅作同字段快速命中兜底;Schema 升级造成字段 UUID 漂移时仍能按稳定 `field_code` 承接旧快照,实际命中字段 ID 仍写入证据链。字段退役、删除或 Schema 发布移除被启用规则引用字段时服务端阻断。 - **裁决边界**:客户主体和送货站点独立候选;编码确定性匹配优先;多命中、冲突、未命中均进入人工复核。业务弱证据(地址、联系人、名称)默认不得单独自动确认;公共邮箱域名永久禁止。 - **Dify**:不新增 Tool 或修改画布。Dify 继续按已发布动态 Schema 契约提交 Header Observation;HXOPS 完成证据校验、字段裁决、规则匹配、质量门禁和最终确认。 @@ -337,9 +337,9 @@ PDF 证据锚定优先使用现有 `pypdfium2` 逐字文本坐标定位,并由 - 客户识别可采用外部编码、标准名称、已审核别名或其他已发布证据;Bill-to/Ship-to 不是客户业务角色。Candidate 只展示 Resolution 候选,正式客户绑定和业务编号仍通过既有质量门禁。 - 单票与多票发货需求统一落入 `ShippingBatch`;单票使用 `file_count=1` 的批次容器。 -- 库存 Excel 上传后保存为 `shipping_inventory_files` 批次库存快照,并通过 `shipping_task_inventory_links` 关联到本批任务。 +- 库存 Excel 上传后保存为 `shipping_onhand_files` 批次库存快照,并通过 `shipping_task_onhand_links` 关联到本批任务。 - 字段映射与完整库存解析在库存快照层完成一次;每票仍使用自己的发货需求行独立执行库存匹配、Excel 生成与上传。 -- `ShippingTask.inventory_lines_json` 仅作为任务侧投影缓存,批次库存真相源为 `shipping_inventory_files.inventory_lines_json`。 +- 批次库存真相源为 `shipping_onhand_files.onhand_lines_json`。 - **订单真相分层**:`shipping_order_extractions`、`shipping_order_lines`、`ShippingOrderFieldDecision/Value` 是可追溯的解析事实;`ShippingOrderSnapshot/Line` 是冻结后的履约业务事实。`ShippingTask.current_order_extraction_id` 追溯解析版本,`order_snapshot_id` 锁定履约版本。`shipping_task_lines`、`ShippingTask.lines_json` 和兼容固定单头列不得作为业务真相;冻结前的 Candidate 编辑及 Snapshot 冻结均使用乐观锁。 - **库存源与库存文件分层**:`source_code` 是业务库存主键;通用、版本化的路由规则先产生 Source 候选,正常任务再按 Source 匹配最新 `ready`、未过期库存文件,禁止因文件缺失自动触发 RPA。RPA Profile 仅保存登录 URL、加密凭据和连接级登录配置;每个 Source 保存 DBS 的报表路径和查询参数,不允许在业务配置中保存 selector、下载策略或第二套路由别名。排程按 Profile 分组优化登录但每个结果独立归档到 Source。`connector_type` 只允许 `dbs` / `crane`,不再使用 `site_id`。固定 Source 使用配置 Warehouse;Crane 等动态 Source 按 `reservation_id + part_number` 从库存行解析 Warehouse。详见 [inventory_source_plan.md](features/shipping-notice/inventory_source_plan.md)。 - **建单防重复(第一阶段)**:`ShippingBatch.create_idempotency_key` + `(user_id, create_idempotency_key)` 唯一约束提供并发保护;`ShippingTask.source_content_hash` 记录源文件 SHA-256;Chat Turn 与 Workspace API 共用 `batch_from_notices` 幂等逻辑;与货代上传 `ShippingTask.idempotency_key` 语义分离。 @@ -1438,15 +1438,15 @@ Dify - 聚合问答由目录 Agent 自己的 Dify Chatflow 实现。 - HXOPS 当前只负责配置、权限、会话与上下文注入,不直接编排多个子 Agent 的回答。 -- **版本化 Excel 模板与 Artifact**:`shipping_excel_templates` 保存私有 MinIO `bucket/key`、模板文件校验和及字段映射发布版本,`shipping_inventory_sources.excel_template_id` 决定新任务使用的模板;`shipping_export_artifacts` 保存每次生成文件及所锁定的 Schema、Extraction、库存解析 Profile、库存快照、输入/文件 checksum。导出运行时从 MinIO读取模板,不读取全局模板环境变量,也不回退空白工作簿。 +- **版本化 Excel 模板与 Artifact**:`shipping_excel_templates` 保存私有 MinIO `bucket/key`、模板文件校验和及字段映射发布版本,`freight_rpa_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/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,不能读取二进制、路径、样例值、全量行或直接宣布库存可用于匹配。已确认会话可由管理员沉淀为解析方案草稿,但不能自动发布或绑定库存站点。 +- **库存样本结构分析**:`freight_rpa_onhand_structure_analyses` 保存受控库存样本的文件名、checksum、工作表/候选表头、来源栏位、类型/空值统计、结构指纹和最多五行脱敏样例,不保存完整样本文件或正式库存明细。管理端样本与配置测试文件只在即时分析期间落盘,分析完成即清理;仅对话临时库存会话可在其短期确认窗口保留受控原件。`ShippingOnhandParsingProfile.sample_analysis_id` 锁定草稿/发布版本的样本证据;创建、保存和发布均要求工作表、表头和来源栏位来自该分析记录。 +- **对话临时库存文件**:用户在货代对话上传 `.xls` / `.xlsx` / `.csv` 表格后,系统先保留附件,只有用户明确声明其为库存文件才创建 `FileAsset -> shipping_temporary_onhand_sessions` 短生命周期会话;绝不依据后缀猜测库存或订单。会话同时绑定 `user_id + conversation_id + asset_id`,以 `source_kind=temporary_conversation` 保存结构审计。后端只向 Dify 返回不含样例库存值的结构预览与规则建议;不创建 `shipping_onhand_files`、不写任务库存关联、不绑定库存站点。跨聊天回合时,HXOPS 从数据库恢复当前会话最新、未过期且仍待确认的临时会话号,但不会自动路由或确认;Dify 只有识别到用户明确确认本次临时使用时,才可调用确认 Tool。所有 Tool 输出先按 `text` JSON 标准化,不能依赖 Dify 隐式会话记忆或假定的 Tool 顶层字段。Dify 仅可调用创建、读取、提交候选映射和经用户明确确认后的临时使用 Tool,不能读取二进制、路径、样例值、全量行或直接宣布库存可用于匹配。已确认会话可由管理员沉淀为解析方案草稿,但不能自动发布或绑定库存站点。 - **方案复用**:结构分析与解析方案分别保存精确结构指纹和兼容指纹,均不包含库存业务数据或文件名。精确指纹覆盖格式、工作表、表头行、标准化列名及顺序;兼容判断验证既有方案实际使用的库存匹配与数量来源表头仍存在,并输出新增/缺少/顺序变化。后端不使用固定字段词典把“内部料号”猜成 `Supplier Sku`;仅当用户字段显示名称与真实表头标准化后完全相同时给出确定性预填,其他情况由管理员选择或 Dify 提供候选。管理员确认复用只写分析审计,不更新库存站点绑定。 -- **库存站点测试导出**:`shipping_inventory_configuration_test_runs` 保存专用 `configuration_test` RPA run、来源配置版本、分析记录和确认结果。测试回调走 `/api/shipping-notice/rpa/inventory-configuration-test-ready`,只创建 `source_kind=configuration_test` 的结构分析,不创建 `shipping_inventory_files`。确认方案时要求站点仍停用且配置版本未变化,成功后绑定解析方案并使测试记录追随新的配置版本;后续编辑站点自动使旧测试失效。 -- **批量库存站点验证**:`shipping_inventory_validation_batches` 聚合一次管理员批量验证,`shipping_inventory_configuration_test_runs.validation_batch_id` 仍保存逐站点事实。服务端仅将相同 `rpa_profile_id + connector_type` 分为一个 Worker trigger;Worker 按既有单 Worker 串行消费,因此并发上限为 1,避免无边界浏览器并发。每个 source 透传 `validation_run_no`,通过 `/api/shipping-notice/rpa/inventory-configuration-test-batch-ready` 独立回写成功、空库存或失败;批次只汇总进度,失败不回滚其他站点。Dify 不读取批次状态、不新增 Tool 或画布配置。 -- **正式库存结构漂移**:`inventory_structure_drift` 在 RPA 单票与批量回调正式解析前分析实际文件;只允许已绑定 published Profile 成为 `exact` 或 `compatible` 候选。兼容变化只限非关键栏位,差异写入快照 `schema_preview_json.structure_validation`;关键结构变化返回 `SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED` 并回滚本次快照与任务链接。解析参数固定来自 Profile,运行期不再根据文件表头调用规则猜测。 +- **库存站点测试导出**:`freight_rpa_onhand_configuration_test_runs` 保存专用 `configuration_test` RPA run、来源配置版本、分析记录和确认结果。测试回调走 `/api/freight-rpa/onhand-configuration-test-analyze`,只创建 `source_kind=configuration_test` 的结构分析,不创建 `shipping_onhand_files`。确认方案时要求站点仍停用且配置版本未变化,成功后绑定解析方案并使测试记录追随新的配置版本;后续编辑站点自动使旧测试失效。 +- **批量库存站点验证**:`freight_rpa_onhand_validation_batches` 聚合一次管理员批量验证,`freight_rpa_onhand_configuration_test_runs.validation_batch_id` 仍保存逐站点事实。服务端仅将相同 `rpa_profile_id + connector_type` 分为一个 Worker trigger;Worker 按既有单 Worker 串行消费,因此并发上限为 1,避免无边界浏览器并发。每个 source 透传 `validation_run_no`,通过 `/api/freight-rpa/onhand-configuration-test-complete` 独立回写成功、空库存或失败;批次只汇总进度,失败不回滚其他站点。Dify 不读取批次状态、不新增 Tool 或画布配置。 +- **正式库存结构漂移**:`inventory_structure_drift` 在 RPA 单票与批量回调正式解析前分析实际文件;只允许已绑定 published Profile 成为 `exact` 或 `compatible` 候选。兼容变化只限非关键栏位,差异写入快照 `schema_preview_json.structure_validation`;关键结构变化返回 `SHIPPING.ONHAND_STRUCTURE_DRIFT_BLOCKED` 并回滚本次快照与任务链接。解析参数固定来自 Profile,运行期不再根据文件表头调用规则猜测。 - **管理端契约**:Profile 和 Excel 模板使用后端 `configuration-catalog` 返回的订单字段、库存标准字段、系统事实、row mode 和 formatter 结构化编辑,不以自由 JSON 作为日常维护入口;禁用 Source 可分步保存,启用时服务层与数据库双重校验绑定完整性。 - **发货任务分页与批次下载**:`GET /api/workspace/shipping-tasks` 接收 `page`、`page_size` 和可选状态筛选,由数据库返回 `{ items, page, page_size, total }`;工作台默认每页 10 条,筛选、刷新或切页不保留跨页选择。`POST /api/workspace/shipping-exports/archive` 只接收 `batch_no` 或 `task_nos[]`,后端重新做用户归属校验并选择仍与 Task 当前导出路径一致的最新 ready Artifact;ZIP 使用可溢写临时文件,含 `manifest.json`,同名追加任务号,单次最多 100 票。 - **发货任务处置与 Dify 边界**:`ShippingTask` 以独立生命周期和回收站字段管理 delete/void/archive,后台 worker、RPA 回调和履约入口统一读取生命周期熔断。Dify 不新增 Tool、不修改画布、不参与批量处置;工作台调用 HXOPS `/api/workspace/shipping-tasks/batch-*` API。外部货代作废能力接入前,上传中/已上传任务只允许归档。 @@ -1522,14 +1522,16 @@ RecoveryPlan → Gate Attempt → Job → Worker/RPA → 幂等回调 → `run_t # 货代收料 RPA 独立架构(2026-08) -`freight-receipt-rpa` 写入 `shipping_receipt_rpa.v1` trigger,仅由 `freight_receipt_rpa_worker.py` 消费。它使用专属 `FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR` 和 `...RECEIPT_DROP_DIR`,不得与库存 Worker 共享目录或 callback。trigger 先写同目录临时文件、`fsync` 后以 `os.replace` 原子发布,避免 Worker 读取半截 JSON。Worker 在单次排程内按 `connector_type + rpa_profile_id + login_url` 分组并登录一次,串行导出;密文凭据仅在冻结 trigger 内传递并在 Worker 短暂解密。callback 仅允许读取 receipt drop 根内的 `.xlsx`,校验 SHA-256/大小后归档 MinIO。收料表与 `shipping_inventory_files` 无关联。 +`freight-rpa-inbound` 写入 `freight_rpa.inbound.v1` trigger,仅由 `inbound_rpa_worker.py` 消费。它使用专属 `FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR` 和 `...INBOUND_DROP_DIR`,不得与库存 Worker 共享目录或 callback。trigger 先写同目录临时文件、`fsync` 后以 `os.replace` 原子发布,避免 Worker 读取半截 JSON。Worker 在单次排程内按 `connector_type + rpa_profile_id + login_url` 分组并登录一次,串行导出;密文凭据仅在冻结 trigger 内传递并在 Worker 短暂解密。callback 仅允许读取 inbound drop 根内的 `.xlsx`,校验 SHA-256/大小后归档 MinIO。收料表与 `shipping_onhand_files` 无关联。 -下载接口为 `GET /api/workspace/receipt-report-files/{file_id}/download`(管理员或排程接收人);`GET /api/workspace/receipt-report-files` 仅列出当前用户有权读取的脱敏归档元数据,并在授权过滤后施加 limit。管理员可通过 `GET /api/admin/receipt-rpa-units?status=failed` 定位失败单元,并以 `POST /api/admin/receipt-rpa-units/{unit_id}/retry`(必填原因)或 `POST /api/admin/receipt-report-files/{file_id}/resend` 补偿。运行等待 callback 超时会被 Worker 启动和周期扫描收口为失败,绝不自动重试;管理员补偿创建新单元,保留旧单元。管理员在既有库存站点抽屉通过独立 `GET/PUT /api/admin/shipping-notice/sources/{source_id}/receipt-report-config` 维护收料配置,不能改写库存 Source 字段:DBS 维护路径/条件/Warehouse,Crane 固定 `Inbound Details`,拒绝 Warehouse 和查询条件;Worker 无论 Profile 登录 URL 的原 hash 均强制进入 `#/inbound-details-query` 并直接使用页面默认条件。所有入口写含前后状态快照的 `ShippingAuditEvent`;三年期满仅删除对象、保留文件事实与审计。 +下载接口为 `GET /api/workspace/receipt-report-files/{file_id}/download`(管理员或排程接收人);`GET /api/workspace/receipt-report-files` 仅列出当前用户有权读取的脱敏归档元数据,并在授权过滤后施加 limit。管理员可通过 `GET /api/admin/receipt-rpa-units?status=failed` 定位失败单元,并以 `POST /api/admin/receipt-rpa-units/{unit_id}/retry`(必填原因)或 `POST /api/admin/receipt-report-files/{file_id}/resend` 补偿。运行等待 callback 超时会被 Worker 启动和周期扫描收口为失败,绝不自动重试;管理员补偿创建新单元,保留旧单元。管理员在既有库存站点抽屉通过独立 `GET/PUT /api/admin/freight-rpa/sources/{source_id}/inbound-report-config` 维护收料配置,不能改写库存 Source 字段:DBS 维护路径/条件/Warehouse,Crane 固定 `Inbound Details`,拒绝 Warehouse 和查询条件;Worker 无论 Profile 登录 URL 的原 hash 均强制进入 `#/inbound-details-query` 并直接使用页面默认条件。所有入口写含前后状态快照的 `ShippingAuditEvent`;三年期满仅删除对象、保留文件事实与审计。 # 在途仓自动调拨独立架构(2026-08) 调拨业务域独立于 shipping_notice 订单解析:ackend/app/services/in_transit_transfer/ 承载状态机/DTO/审计/文件准备/预检/执行/恢复/通知/归档/指标,erp_adapter.py 为 ERP 唯一访问出口(SOAP 在 WSDL 冻结前 fail-closed,凭据仅来自环境/Secret)。数据落 ransfer_* 七表(迁移 it1a2b3c4d5e);异步走 ransfer 队列(workers/worker_in_transit_transfer.py);08:00/09:00 platform job 注册于 schedule。前端卡片在 rontend/src/features/chat/(TransferMessageView 自驱动),四语言文案齐备。运维手册见 [features/in-transit-transfer/technical.md](features/in-transit-transfer/technical.md)。 +**2026-10-15 补充(入站/出站统一改版)**:调拨域术语全面改版为入站(inbound)/出站(outbound)统一口径——`record_kind` 枚举值 inbound/outbound、明细/单据列异动口径(`movement_*`:异动日期/异动数量/异动仓库)、API 路由与错误码/审计事件同步更名(未上线无兼容层,迁移 tt14);异动档 `transfer_movement_ledger` 自然键扩为 8 成分(单据+行+进出标志+箱号/批号)并新增「异动日期非空才落档」过滤(`date_skipped`)。解析规则模型 `ShippingOnhandParsingProfile.purpose` CHECK 重建为三枚举 `onhand/inbound/outbound`(迁移 tt15 值迁移:两值旧枚举→新枚举),收料配置绑定校验只认 inbound(`SHIPPING.INBOUND_PROFILE_INVALID`),解析规则退役守卫补查收料配置绑定(防入站解析链静默失去规则);outbound 规则结构就位、出站证据链路未建,运行期天然 fail-closed。待匹配桶「清空并重新解析」接口已于 2026-10-22 下线。与 shipping_notice 收料报表域的交界保留原术语——入站证据=收料报表 RPA 产物。详见 features/in-transit-transfer/technical.md §12 与 [superpowers/specs/2026-10-15-inbound-outbound-idempotency-rename-design.md](superpowers/specs/2026-10-15-inbound-outbound-idempotency-rename-design.md)。 + # 跨文档主题同步与前端设计系统补全(2026-10-09) - **主题跨文档同步**:`shared/composables/useTheme.ts` 的 `initTheme()` 新增 `storage` 事件监听(`cleanupTheme` 对应解绑)。背景:应用管理 iframe 应用(如订单交期回复 `/apps/order-delivery-reply`)是独立文档,主题类挂在各自 `` 上,父壳切换亮暗后 iframe 收不到任何通知,停留在加载时的主题。`storage` 事件只在「其他同源文档」修改 localStorage 时触发,监听 `hxops_theme_preference` 变化后同步偏好并 `applyTheme()`,父壳切换主题的所有同源 iframe 实时跟随;iframe 首次加载仍按 localStorage + `matchMedia` 初始化,行为不变。 diff --git a/frontend/src/App.vue b/frontend/src/App.vue index 6925bdcb..06fe7a1e 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -7,7 +7,12 @@ * 书签/刷新冷启动遇到 401 时只回登录页;本页已确认会话后中途失效才弹窗。 */ import { useI18n } from 'vue-i18n'; -import { watch, onMounted, onBeforeUnmount } from 'vue'; +import { computed, watch, onMounted, onBeforeUnmount } from 'vue'; +import { ElConfigProvider } from 'element-plus'; +import zhCn from 'element-plus/es/locale/lang/zh-cn'; +import zhTw from 'element-plus/es/locale/lang/zh-tw'; +import en from 'element-plus/es/locale/lang/en'; +import th from 'element-plus/es/locale/lang/th'; import { useTheme } from '@/shared/composables/useTheme'; import LevelMessageDialog from '@/shared/components/LevelMessageDialog.vue'; import { useGlobalMessageDialog } from '@/shared/composables/useGlobalMessageDialog'; @@ -18,6 +23,23 @@ import { useLinkedNavStore } from '@/features/sso/stores/linked-nav.store'; const router = useRouter(); const { locale, t } = useI18n(); + +/** + * Element Plus 组件内置文案(下拉占位/日期面板/分页等)跟随应用语言: + * EP 有独立 locale 体系,默认英文,必须在根部经 el-config-provider 注入当前语言包。 + */ +const elementPlusLocale = computed(() => { + switch (locale.value) { + case 'zh-TW': + return zhTw; + case 'en': + return en; + case 'th': + return th; + default: + return zhCn; + } +}); const { themePreference, initTheme, setThemePreference } = useTheme(); const { messageDialogVisible, @@ -136,12 +158,14 @@ onBeforeUnmount(() => { diff --git a/frontend/src/app/router/routes/admin.routes.ts b/frontend/src/app/router/routes/admin.routes.ts index 4a776725..bde99665 100644 --- a/frontend/src/app/router/routes/admin.routes.ts +++ b/frontend/src/app/router/routes/admin.routes.ts @@ -46,8 +46,8 @@ const LinkedServicesPage = () => const ReportsPage = () => import("@/features/admin/modules/reports/ReportsPage.vue"); -const ShippingInventoryPage = () => - import("@/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue"); +const FreightRpaPage = () => + import("@/features/admin/modules/freight-rpa/FreightRpaPage.vue"); const ShippingFieldAssetsPage = () => import("@/features/admin/modules/shipping-field-assets/ShippingFieldAssetsPage.vue"); const ShippingOrderSchemaPage = () => @@ -82,6 +82,9 @@ const TrainingConfigPage = () => const IntegrationConnectorPage = () => import("@/features/admin/modules/integration-connector/IntegrationConnectorPage.vue"); +const TransferTypesPage = () => + import("@/features/admin/modules/transfer-types/TransferTypesPage.vue"); + export const adminRoutes: RouteRecordRaw[] = [ { path: "/admin", @@ -171,82 +174,82 @@ export const adminRoutes: RouteRecordRaw[] = [ { path: "shipping-notice", - name: "AdminShippingInventory", - component: ShippingInventoryPage, - meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'inventory', title: "货代管理" }, + name: "AdminFreightRpa", + component: FreightRpaPage, + meta: { requiresAdmin: true, adminModule: "freight_rpa", adminSubModule: 'inventory', title: "货代管理" }, }, { path: "shipping-field-assets", name: "AdminShippingFieldAssets", component: ShippingFieldAssetsPage, - meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'field_assets', title: "字段资产库" }, + meta: { requiresAdmin: true, adminModule: "freight_rpa", adminSubModule: 'field_assets', title: "字段资产库" }, }, { path: "shipping-order-schema", name: "AdminShippingOrderSchema", component: ShippingOrderSchemaPage, - meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'order_schema', title: "订单 Schema" }, + meta: { requiresAdmin: true, adminModule: "freight_rpa", adminSubModule: 'order_schema', title: "订单 Schema" }, }, { path: "shipping-identity-rules", name: "AdminShippingIdentityRules", component: ShippingIdentityRulesPage, - meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'identity_rules', title: "客户识别规则" }, + meta: { requiresAdmin: true, adminModule: "freight_rpa", adminSubModule: 'identity_rules', title: "客户识别规则" }, }, { path: "shipping-order-extraction-runs", name: "AdminShippingOrderExtractionRuns", component: ShippingOrderExtractionRunsPage, - meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'order_extraction_runs', title: "识别任务" }, + meta: { requiresAdmin: true, adminModule: "freight_rpa", adminSubModule: 'order_extraction_runs', title: "识别任务" }, }, { path: "shipping-audit", name: "AdminShippingAudit", component: ShippingAuditCenterPage, - meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'shipping_audit', title: "运行与审计" }, + meta: { requiresAdmin: true, adminModule: "freight_rpa", adminSubModule: 'shipping_audit', title: "运行与审计" }, }, { path: "shipping-process-gates", name: "AdminShippingProcessGates", component: ShippingProcessGateDiagnosticsPage, - meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'process_gates', title: "门禁诊断" }, + meta: { requiresAdmin: true, adminModule: "freight_rpa", adminSubModule: 'process_gates', title: "门禁诊断" }, }, { path: "shipping-order-document-profiles", name: "AdminShippingOrderDocumentProfiles", component: ShippingOrderDocumentProfilesPage, - meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'order_document_profiles', title: "订单文档模板" }, + meta: { requiresAdmin: true, adminModule: "freight_rpa", adminSubModule: 'order_document_profiles', title: "订单文档模板" }, }, // 阶段 0 先固定 URL 身份;对应专属页面将在各自实施阶段替换,当前不切换旧工作台流量。 { path: "shipping-order-document-profiles/new", name: "AdminShippingOrderDocumentProfileCreate", component: OrderProfileCreateWizardPage, - meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'order_document_profiles', title: "创建订单文档模板" }, + meta: { requiresAdmin: true, adminModule: "freight_rpa", adminSubModule: 'order_document_profiles', title: "创建订单文档模板" }, }, { path: "shipping-order-document-profiles/:profileCode/drafts/:profileId/edit", name: "AdminShippingOrderDocumentProfileEdit", component: OrderProfileEditorRoutePage, - meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'order_document_profiles', title: "编辑订单文档模板" }, + meta: { requiresAdmin: true, adminModule: "freight_rpa", adminSubModule: 'order_document_profiles', title: "编辑订单文档模板" }, }, { path: "shipping-order-document-profiles/:profileCode/drafts/:profileId/validate", name: "AdminShippingOrderDocumentProfileValidate", component: OrderProfileValidationPage, - meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'order_document_profiles', title: "验证订单文档模板" }, + meta: { requiresAdmin: true, adminModule: "freight_rpa", adminSubModule: 'order_document_profiles', title: "验证订单文档模板" }, }, { path: "shipping-order-document-profiles/:profileCode/drafts/:profileId/blind-test", name: "AdminShippingOrderDocumentProfileBlindTest", component: OrderProfileBlindTestPage, - meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'order_document_profiles', title: "订单文档模板盲测" }, + meta: { requiresAdmin: true, adminModule: "freight_rpa", adminSubModule: 'order_document_profiles', title: "订单文档模板盲测" }, }, { path: "shipping-order-document-profiles/:profileCode/drafts/:profileId/publish-check", name: "AdminShippingOrderDocumentProfilePublishCheck", component: OrderProfilePublishCheckPage, - meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'order_document_profiles', title: "订单文档模板发布检查" }, + meta: { requiresAdmin: true, adminModule: "freight_rpa", adminSubModule: 'order_document_profiles', title: "订单文档模板发布检查" }, }, { path: "shipping-order-document-profiles/:profileCode/versions/:version", @@ -254,7 +257,7 @@ export const adminRoutes: RouteRecordRaw[] = [ component: OrderProfileVersionDetailPage, meta: { requiresAdmin: true, - adminModule: "shipping_inventory", + adminModule: "freight_rpa", adminSubModule: 'order_document_profiles', title: "模板版本详情", }, @@ -341,6 +344,16 @@ export const adminRoutes: RouteRecordRaw[] = [ title: "admin.nav.integrationConnector", }, }, + { + path: "transfer-types", + name: "AdminTransferTypes", + component: TransferTypesPage, + meta: { + requiresAdmin: true, + adminModule: "transfer_types", + title: "admin.nav.transferTypes", + }, + }, { path: "reports/:table?", name: "AdminReports", diff --git a/frontend/src/app/router/routes/workspace.routes.ts b/frontend/src/app/router/routes/workspace.routes.ts index 83b6cb05..37724b78 100644 --- a/frontend/src/app/router/routes/workspace.routes.ts +++ b/frontend/src/app/router/routes/workspace.routes.ts @@ -62,12 +62,6 @@ export const workspaceRoutes: RouteRecordRaw[] = [ component: () => import('@/features/workspace/pages/ScheduleRunsPage.vue'), meta: { title: 'workspace.nav.scheduleRuns' }, }, - { - path: 'receipt-reports', - name: 'workspace-receipt-reports', - component: () => import('@/features/workspace/pages/ReceiptReportFilesPage.vue'), - meta: { title: 'workspace.nav.receiptReports' }, - }, { path: 'shipping-notice', redirect: '/workspace/shipping-notice/my-tasks', diff --git a/frontend/src/config.ts b/frontend/src/config.ts index 2ad8a82c..4a6a82b4 100644 --- a/frontend/src/config.ts +++ b/frontend/src/config.ts @@ -70,10 +70,11 @@ export const config = { schedules: true, // 定时任务 wecom: true, // 企业微信 linked_services: true, // 关联服务(侧栏跳转入口) - shipping_inventory: true, // 货代配置 + freight_rpa: true, // 货代配置 procurement_contract: true, // 采购合同审查(模板库 + 历史) training_config: true, integration_connector: true, // 集成连接器配置 + transfer_types: true, // 在途调拨类型配置(ADR 0002) } } }; diff --git a/frontend/src/features/admin/api/admin.api.ts b/frontend/src/features/admin/api/admin.api.ts index 1a0a5d3c..a77fd18d 100644 --- a/frontend/src/features/admin/api/admin.api.ts +++ b/frontend/src/features/admin/api/admin.api.ts @@ -41,7 +41,7 @@ const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getA -export type ShippingInventoryReadinessCheck = { +export type ShippingOnhandReadinessCheck = { code: string; status: 'passed' | 'pending' | 'failed' | 'stale' | 'empty'; blocking: boolean; @@ -49,15 +49,15 @@ export type ShippingInventoryReadinessCheck = { evidence: Record; }; -export type ShippingInventoryReadiness = { +export type ShippingOnhandReadiness = { ready: boolean; - checks: ShippingInventoryReadinessCheck[]; + checks: ShippingOnhandReadinessCheck[]; missing_requirements: string[]; }; -export type ShippingInventoryConfigurationTest = { +export type ShippingOnhandConfigurationTest = { run_no: string; - inventory_source_id: number; + source_id: number; source_config_version: number; rpa_profile_config_version: number; status: 'awaiting_rpa' | 'processing' | 'completed' | 'completed_empty' | 'failed'; @@ -76,7 +76,7 @@ export type ShippingInventoryConfigurationTest = { }; }; -export type ShippingInventoryValidationBatch = { +export type ShippingOnhandValidationBatch = { id: number; batch_no: string; status: 'queued' | 'running' | 'completed' | 'partial_failed' | 'failed'; @@ -85,7 +85,7 @@ export type ShippingInventoryValidationBatch = { empty_count: number; failed_count: number; stale_count: number; - runs: ShippingInventoryConfigurationTest[]; + runs: ShippingOnhandConfigurationTest[]; }; export type ShippingOrderExtractionDiagnosticAutoFreezePolicy = { @@ -171,8 +171,8 @@ export const getShippingOrderExtractionHealth = (windowHours = 24) => { }; /** 下载管理员可访问的库存快照,并保留服务端指定的原始文件名。 */ -export const downloadShippingInventorySnapshot = async (snapshotId: number, fallbackName: string): Promise => { - const response = await fetch(`/api/admin/shipping-notice/snapshots/${snapshotId}/download`, { headers: getAuthHeaders() }); +export const downloadShippingOnhandSnapshot = async (snapshotId: number, fallbackName: string): Promise => { + const response = await fetch(`/api/admin/freight-rpa/onhand/snapshots/${snapshotId}/download`, { headers: getAuthHeaders() }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const blob = await response.blob(); const disposition = response.headers.get('Content-Disposition') || ''; @@ -186,18 +186,18 @@ export const downloadShippingInventorySnapshot = async (snapshotId: number, fall }; /** 货代库存配置统一接口;敏感凭据仅能写入,服务端不会回显。 */ -export const getShippingInventoryConfig = async () => Promise.all([ - requestJson('/api/admin/shipping-notice/rpa-profiles', auth()), - requestJson('/api/admin/shipping-notice/sources', auth()), - requestJson('/api/admin/shipping-notice/routing-rules', auth()), - requestJson('/api/admin/shipping-notice/external-mappings', auth()), - requestJson('/api/admin/shipping-notice/snapshots', auth()), - requestJson('/api/admin/shipping-notice/export-records', auth()), - requestJson('/api/admin/shipping-notice/parsing-profiles', auth()), +export const getShippingOnhandConfig = async () => Promise.all([ + requestJson('/api/admin/freight-rpa/rpa-profiles', auth()), + requestJson('/api/admin/freight-rpa/sources', auth()), + requestJson('/api/admin/freight-rpa/onhand/routing-rules', auth()), + requestJson('/api/admin/freight-rpa/onhand/external-mappings', auth()), + requestJson('/api/admin/freight-rpa/onhand/snapshots', auth()), + requestJson('/api/admin/freight-rpa/onhand/export-records', auth()), + requestJson('/api/admin/freight-rpa/onhand/parsing-profiles', auth()), requestJson('/api/admin/shipping-notice/excel-templates', auth()), ]); -export type ShippingInventoryField = { +export type ShippingOnhandField = { id: number; display_name: string; description: string; @@ -208,20 +208,20 @@ export type ShippingInventoryField = { }; /** 管理可供不同库存文件解析方案复用的统一库存业务字段。 */ -export const getShippingInventoryFields = () => requestJson( - '/api/admin/shipping-notice/inventory-fields?include_retired=true', auth(), +export const getShippingOnhandFields = () => requestJson( + '/api/admin/freight-rpa/onhand/fields?include_retired=true', auth(), ); -export const createShippingInventoryField = (payload: Omit) => requestJson( - '/api/admin/shipping-notice/inventory-fields', { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() }, +export const createShippingOnhandField = (payload: Omit) => requestJson( + '/api/admin/freight-rpa/onhand/fields', { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() }, ); -export const updateShippingInventoryField = (id: number, payload: Omit) => requestJson( - `/api/admin/shipping-notice/inventory-fields/${id}`, { method: 'PUT', body: JSON.stringify(payload), ...jsonAuth() }, +export const updateShippingOnhandField = (id: number, payload: Omit) => requestJson( + `/api/admin/freight-rpa/onhand/fields/${id}`, { method: 'PUT', body: JSON.stringify(payload), ...jsonAuth() }, ); -export const retireShippingInventoryField = (id: number) => requestJson( - `/api/admin/shipping-notice/inventory-fields/${id}/retire`, { method: 'POST', ...jsonAuth() }, +export const retireShippingOnhandField = (id: number) => requestJson( + `/api/admin/freight-rpa/onhand/fields/${id}/retire`, { method: 'POST', ...jsonAuth() }, ); -export const deleteShippingInventoryField = (id: number) => requestJson( - `/api/admin/shipping-notice/inventory-fields/${id}`, { method: 'DELETE', ...auth() }, +export const deleteShippingOnhandField = (id: number) => requestJson( + `/api/admin/freight-rpa/onhand/fields/${id}`, { method: 'DELETE', ...auth() }, ); /** 上传或更新版本化发货 Excel 模板;文件仅在创建草稿时提交。 */ @@ -251,15 +251,15 @@ export const deleteShippingExcelTemplate = (id: number) => requestJson( ); /** 读取库存路由可选的已发布订单字段。 */ -export const getShippingInventoryRoutingFields = () => requestJson<{ +export const getShippingOnhandRoutingFields = () => requestJson<{ order_fields: Array<{ field_id: string; field_code: string; display_name: string; description?: string; scope: 'header' | 'line' }>; order_schema_published: boolean; -}>('/api/admin/shipping-notice/routing-fields', auth()); +}>('/api/admin/freight-rpa/onhand/routing-fields', auth()); -export type ShippingInventoryConfigurationCatalog = { +export type ShippingOnhandConfigurationCatalog = { order_fields: Array<{ field_id: string; field_code: string; display_name: string; description?: string; scope: 'header' | 'line' }>; order_schema_published: boolean; - inventory_fields: ShippingInventoryField[]; + inventory_fields: ShippingOnhandField[]; template_system_facts: string[]; template_source_kinds: Array<'order_field' | 'inventory_field' | 'system_fact' | 'constant'>; template_row_modes: Array<'header' | 'line'>; @@ -267,167 +267,175 @@ export type ShippingInventoryConfigurationCatalog = { }; /** 读取 Profile 与模板结构化编辑器使用的后端权威白名单。 */ -export const getShippingInventoryConfigurationCatalog = () => - requestJson( - '/api/admin/shipping-notice/configuration-catalog', auth(), +export const getShippingOnhandConfigurationCatalog = () => + requestJson( + '/api/admin/freight-rpa/onhand/configuration-catalog', auth(), ); /** 保存和发布可复用库存解析 Profile。 */ -export const saveShippingInventoryParsingProfile = (payload: Record, id?: number) => requestJson( - `/api/admin/shipping-notice/parsing-profiles${id ? `/${id}` : ''}`, +export const saveShippingOnhandParsingProfile = (payload: Record, id?: number) => requestJson( + `/api/admin/freight-rpa/onhand/parsing-profiles${id ? `/${id}` : ''}`, { method: id ? 'PUT' : 'POST', body: JSON.stringify(payload), ...jsonAuth() }, ); -export const publishShippingInventoryParsingProfile = (id: number) => requestJson( - `/api/admin/shipping-notice/parsing-profiles/${id}/publish`, { method: 'POST', ...jsonAuth() }, +export const publishShippingOnhandParsingProfile = (id: number) => requestJson( + `/api/admin/freight-rpa/onhand/parsing-profiles/${id}/publish`, { method: 'POST', ...jsonAuth() }, ); -export const retireShippingInventoryParsingProfile = (id: number) => requestJson( - `/api/admin/shipping-notice/parsing-profiles/${id}/retire`, { method: 'POST', ...jsonAuth() }, +export const retireShippingOnhandParsingProfile = (id: number) => requestJson( + `/api/admin/freight-rpa/onhand/parsing-profiles/${id}/retire`, { method: 'POST', ...jsonAuth() }, ); -export const deleteShippingInventoryParsingProfile = (id: number) => requestJson( - `/api/admin/shipping-notice/parsing-profiles/${id}`, { method: 'DELETE', ...auth() }, +export const deleteShippingOnhandParsingProfile = (id: number) => requestJson( + `/api/admin/freight-rpa/onhand/parsing-profiles/${id}`, { method: 'DELETE', ...auth() }, ); /** 上传库存样本,由后端分析工作表、表头、栏位样例和字段建议。 */ -export const createShippingInventoryStructureAnalysis = (file: File) => { +export const createShippingOnhandStructureAnalysis = (file: File) => { const form = new FormData(); form.set('file', file); - return requestJson('/api/admin/shipping-notice/inventory-structure-analyses', { + return requestJson('/api/admin/freight-rpa/onhand/structure-analyses', { method: 'POST', body: form, ...auth(), }); }; -/** 读取标准异动字段目录(只读领域契约,供收料异动解析规则映射表单)。 */ +/** 读取标准异动字段目录(只读领域契约,供入站/出站报表规则映射表单)。 */ export const fetchMovementFields = () => requestJson>( - '/api/admin/shipping-notice/movement-fields', auth(), + '/api/admin/freight-rpa/movement-fields', auth(), ); /** 用已分析的真实栏位创建库存文件解析方案草稿。 */ -export const createShippingInventoryParsingDraftFromAnalysis = (id: number, payload: Record) => requestJson( - `/api/admin/shipping-notice/inventory-structure-analyses/${id}/create-profile-draft`, +export const createShippingOnhandParsingDraftFromAnalysis = (id: number, payload: Record) => requestJson( + `/api/admin/freight-rpa/onhand/structure-analyses/${id}/create-profile-draft`, { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() }, ); /** 样本替换先读取后端结构差异;管理员确认前不会改动草稿的审计证据。 */ -export const previewShippingInventorySampleReplacement = (profileId: number, analysisId: number, payload: Record = {}) => requestJson( - `/api/admin/shipping-notice/parsing-profiles/${profileId}/sample-replacement-preview/${analysisId}`, +export const previewShippingOnhandSampleReplacement = (profileId: number, analysisId: number, payload: Record = {}) => requestJson( + `/api/admin/freight-rpa/onhand/parsing-profiles/${profileId}/sample-replacement-preview/${analysisId}`, { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() }, ); /** 确认复用后端推荐的已发布解析方案;库存站点绑定仍由后续测试流程确认。 */ -export const adoptShippingInventoryParsingProfile = (analysisId: number, profileId: number) => requestJson( - `/api/admin/shipping-notice/inventory-structure-analyses/${analysisId}/adopt-profile`, +export const adoptShippingOnhandParsingProfile = (analysisId: number, profileId: number) => requestJson( + `/api/admin/freight-rpa/onhand/structure-analyses/${analysisId}/adopt-profile`, { method: 'POST', body: JSON.stringify({ profile_id: profileId }), ...jsonAuth() }, ); -/** 列出已确认、可由管理员沉淀为库存文件解析方案草稿的对话临时库存会话。 */ -export const listShippingTemporaryInventorySessions = () => requestJson( - '/api/admin/shipping-notice/temporary-inventory-sessions', auth(), +/** 列出已确认、可由管理员沉淀为库存文件解析方案草稿的对话临时库存会话。路径留在 /api/admin/shipping-notice/temporary-onhand-sessions。 */ +export const listShippingTemporaryOnhandSessions = () => requestJson( + '/api/admin/shipping-notice/temporary-onhand-sessions', auth(), ); -/** 使用临时会话锁定的结构和映射创建草稿;前端提交的字段映射不会被接受。 */ +/** 使用临时会话锁定的结构和映射创建草稿;前端提交的字段映射不会被接受。路径为 /api/admin/shipping-notice/temporary-onhand-sessions//create-profile-draft。 */ export const createShippingParsingDraftFromTemporarySession = (sessionNo: string, payload: Record) => requestJson( - `/api/admin/shipping-notice/temporary-inventory-sessions/${encodeURIComponent(sessionNo)}/create-profile-draft`, + `/api/admin/shipping-notice/temporary-onhand-sessions/${encodeURIComponent(sessionNo)}/create-profile-draft`, { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() }, ); /** 保存 RPA Profile;password 未传或为空时由服务端保留旧密文。 */ export const saveShippingRpaProfile = (payload: Record, id?: number) => requestJson( - `/api/admin/shipping-notice/rpa-profiles${id ? `/${id}` : ''}`, + `/api/admin/freight-rpa/rpa-profiles${id ? `/${id}` : ''}`, { method: id ? 'PUT' : 'POST', body: JSON.stringify(payload), ...jsonAuth() }, ); export const deleteShippingRpaProfile = (id: number) => requestJson( - `/api/admin/shipping-notice/rpa-profiles/${id}`, { method: 'DELETE', ...auth() }, + `/api/admin/freight-rpa/rpa-profiles/${id}`, { method: 'DELETE', ...auth() }, ); /** 保存 Inventory Source,服务端校验其 Driver 与 Profile 一致。 */ -export const saveShippingInventorySource = (payload: Record, id?: number) => requestJson( - `/api/admin/shipping-notice/sources${id ? `/${id}` : ''}`, +export const saveShippingOnhandSource = (payload: Record, id?: number) => requestJson( + `/api/admin/freight-rpa/sources${id ? `/${id}` : ''}`, { method: id ? 'PUT' : 'POST', body: JSON.stringify(payload), ...jsonAuth() }, ); -/** 读取/保存站点独立收料配置;严禁通过库存站点保存接口夹带这些字段。 */ -export const getShippingReceiptReportConfig = (sourceId: number) => requestJson | null>( - `/api/admin/shipping-notice/sources/${sourceId}/receipt-report-config`, auth(), +/** 读取/保存站点独立入站报表配置(/freight-rpa/sources//inbound-report-config);严禁通过库存站点保存接口夹带这些字段。 */ +export const getInboundReportConfig = (sourceId: number) => requestJson | null>( + `/api/admin/freight-rpa/sources/${sourceId}/inbound-report-config`, auth(), ); -export const saveShippingReceiptReportConfig = (sourceId: number, payload: Record) => requestJson>( - `/api/admin/shipping-notice/sources/${sourceId}/receipt-report-config`, +export const saveInboundReportConfig = (sourceId: number, payload: Record) => requestJson>( + `/api/admin/freight-rpa/sources/${sourceId}/inbound-report-config`, + { method: 'PUT', body: JSON.stringify(payload), ...jsonAuth() }, +); +/** 读取/保存站点独立出站报表配置;载荷键与入站相同,严禁夹带来源站点字段。 */ +export const getOutboundReportConfig = (sourceId: number) => requestJson | null>( + `/api/admin/freight-rpa/sources/${sourceId}/outbound-report-config`, auth(), +); +export const saveOutboundReportConfig = (sourceId: number, payload: Record) => requestJson>( + `/api/admin/freight-rpa/sources/${sourceId}/outbound-report-config`, { method: 'PUT', body: JSON.stringify(payload), ...jsonAuth() }, ); /** 直接绑定停用库存站点到已发布解析方案;服务端自动写入操作审计。 */ -export const bindShippingInventorySourceParsingProfile = (id: number, payload: { parsing_profile_id: number }) => requestJson( - `/api/admin/shipping-notice/sources/${id}/bind-parsing-profile`, { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() }, +export const bindShippingOnhandSourceParsingProfile = (id: number, payload: { parsing_profile_id: number }) => requestJson( + `/api/admin/freight-rpa/sources/${id}/bind-parsing-profile`, { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() }, ); /** 原子批量绑定已发布解析方案;任一站点不合格时整批拒绝,避免部分更新。 */ -export const bulkBindShippingInventorySourceParsingProfile = (payload: { source_ids: number[]; parsing_profile_id: number }) => requestJson( - '/api/admin/shipping-notice/sources/bulk-bind-parsing-profile', { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() }, +export const bulkBindShippingOnhandSourceParsingProfile = (payload: { source_ids: number[]; parsing_profile_id: number }) => requestJson( + '/api/admin/freight-rpa/sources/bulk-bind-parsing-profile', { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() }, ); /** 读取站点解析方案绑定的可追溯审计记录。 */ -export const getShippingInventorySourceParsingBindingAudits = (id: number) => requestJson( - `/api/admin/shipping-notice/sources/${id}/parsing-binding-audits`, auth(), +export const getShippingOnhandSourceParsingBindingAudits = (id: number) => requestJson( + `/api/admin/freight-rpa/sources/${id}/parsing-binding-audits`, auth(), ); -export const deleteShippingInventorySource = (id: number) => requestJson( - `/api/admin/shipping-notice/sources/${id}`, { method: 'DELETE', ...auth() }, +export const deleteShippingOnhandSource = (id: number) => requestJson( + `/api/admin/freight-rpa/sources/${id}`, { method: 'DELETE', ...auth() }, ); /** 仅在站点完成测试和必需绑定后启用正式库存运行。 */ -export const activateShippingInventorySource = (id: number) => requestJson( - `/api/admin/shipping-notice/sources/${id}/activate`, { method: 'POST', ...jsonAuth() }, +export const activateShippingOnhandSource = (id: number) => requestJson( + `/api/admin/freight-rpa/sources/${id}/activate`, { method: 'POST', ...jsonAuth() }, ); /** 停用库存站点但保留其既有配置和审计记录。 */ -export const deactivateShippingInventorySource = (id: number) => requestJson( - `/api/admin/shipping-notice/sources/${id}/deactivate`, { method: 'POST', ...jsonAuth() }, +export const deactivateShippingOnhandSource = (id: number) => requestJson( + `/api/admin/freight-rpa/sources/${id}/deactivate`, { method: 'POST', ...jsonAuth() }, ); /** 对停用库存站点发起异步 RPA 测试导出,测试文件不会进入生产库存池。 */ -export const startShippingInventoryConfigurationTest = (id: number) => requestJson( - `/api/admin/shipping-notice/sources/${id}/test-export`, { method: 'POST', ...jsonAuth() }, +export const startShippingOnhandConfigurationTest = (id: number) => requestJson( + `/api/admin/freight-rpa/sources/${id}/test-export`, { method: 'POST', ...jsonAuth() }, ); /** 查询库存站点测试导出与结构识别的后端真实状态。 */ -export const getShippingInventoryConfigurationTest = (id: number, runNo: string) => requestJson( - `/api/admin/shipping-notice/sources/${id}/test-export/${encodeURIComponent(runNo)}`, auth(), +export const getShippingOnhandConfigurationTest = (id: number, runNo: string) => requestJson( + `/api/admin/freight-rpa/sources/${id}/test-export/${encodeURIComponent(runNo)}`, auth(), ); /** 读取当前站点配置对应的最近测试,使刷新页面或重开抽屉时可恢复服务端真实状态。 */ -export const getLatestShippingInventoryConfigurationTest = (id: number) => requestJson( - `/api/admin/shipping-notice/sources/${id}/test-export/latest`, auth(), +export const getLatestShippingOnhandConfigurationTest = (id: number) => requestJson( + `/api/admin/freight-rpa/sources/${id}/test-export/latest`, auth(), ); /** 管理员确认测试结果使用的已发布解析方案,才更新停用库存站点绑定。 */ -export const confirmShippingInventoryConfigurationTestProfile = (id: number, runNo: string, profileId: number) => requestJson( - `/api/admin/shipping-notice/sources/${id}/test-export/${encodeURIComponent(runNo)}/confirm-profile`, +export const confirmShippingOnhandConfigurationTestProfile = (id: number, runNo: string, profileId: number) => requestJson( + `/api/admin/freight-rpa/sources/${id}/test-export/${encodeURIComponent(runNo)}/confirm-profile`, { method: 'POST', body: JSON.stringify({ profile_id: profileId }), ...jsonAuth() }, ); /** 对已绑定发布解析方案的多个停用站点发起受控批量测试。 */ -export const startShippingInventoryValidationBatch = (sourceIds: number[]) => requestJson( - '/api/admin/shipping-notice/source-validation-batches', { method: 'POST', body: JSON.stringify({ source_ids: sourceIds }), ...jsonAuth() }, +export const startShippingOnhandValidationBatch = (sourceIds: number[]) => requestJson( + '/api/admin/freight-rpa/onhand/validation-batches', { method: 'POST', body: JSON.stringify({ source_ids: sourceIds }), ...jsonAuth() }, ); /** 读取批量测试进度和逐站点独立结果。 */ -export const getShippingInventoryValidationBatch = (batchId: number) => requestJson( - `/api/admin/shipping-notice/source-validation-batches/${batchId}`, auth(), +export const getShippingOnhandValidationBatch = (batchId: number) => requestJson( + `/api/admin/freight-rpa/onhand/validation-batches/${batchId}`, auth(), ); /** 恢复最近尚未结束的批量测试,供刷新页面后继续展示进度。 */ -export const getLatestActiveShippingInventoryValidationBatch = () => requestJson( - '/api/admin/shipping-notice/source-validation-batches/latest-active', auth(), +export const getLatestActiveShippingOnhandValidationBatch = () => requestJson( + '/api/admin/freight-rpa/onhand/validation-batches/latest-active', auth(), ); /** 仅重试批次内失败或已过期的站点。 */ -export const retryFailedShippingInventoryValidationBatch = (batchId: number) => requestJson( - `/api/admin/shipping-notice/source-validation-batches/${batchId}/retry-failed`, { method: 'POST', ...jsonAuth() }, +export const retryFailedShippingOnhandValidationBatch = (batchId: number) => requestJson( + `/api/admin/freight-rpa/onhand/validation-batches/${batchId}/retry-failed`, { method: 'POST', ...jsonAuth() }, ); /** 保存路由规则草稿;规则发布需调用独立接口以生成审计快照。 */ -export const saveShippingInventoryRule = (payload: Record, id?: number) => requestJson( - `/api/admin/shipping-notice/routing-rules${id ? `/${id}` : ''}`, +export const saveShippingOnhandRule = (payload: Record, id?: number) => requestJson( + `/api/admin/freight-rpa/onhand/routing-rules${id ? `/${id}` : ''}`, { method: id ? 'PUT' : 'POST', body: JSON.stringify(payload), ...jsonAuth() }, ); /** 发布草稿规则,服务端会保存不可变定义快照。 */ -export const publishShippingInventoryRule = (id: number) => requestJson( - `/api/admin/shipping-notice/routing-rules/${id}/publish`, +export const publishShippingOnhandRule = (id: number) => requestJson( + `/api/admin/freight-rpa/onhand/routing-rules/${id}/publish`, { method: 'POST', ...jsonAuth() }, ); -export const retireShippingInventoryRule = (id: number) => requestJson( - `/api/admin/shipping-notice/routing-rules/${id}/retire`, { method: 'POST', ...jsonAuth() }, +export const retireShippingOnhandRule = (id: number) => requestJson( + `/api/admin/freight-rpa/onhand/routing-rules/${id}/retire`, { method: 'POST', ...jsonAuth() }, ); -export const deleteShippingInventoryRule = (id: number) => requestJson( - `/api/admin/shipping-notice/routing-rules/${id}`, { method: 'DELETE', ...auth() }, +export const deleteShippingOnhandRule = (id: number) => requestJson( + `/api/admin/freight-rpa/onhand/routing-rules/${id}`, { method: 'DELETE', ...auth() }, ); /** 保存精确或 Source 默认外部系统映射。 */ -export const saveShippingInventoryExternalMapping = (payload: Record, id?: number) => requestJson( - `/api/admin/shipping-notice/external-mappings${id ? `/${id}` : ''}`, +export const saveShippingOnhandExternalMapping = (payload: Record, id?: number) => requestJson( + `/api/admin/freight-rpa/onhand/external-mappings${id ? `/${id}` : ''}`, { method: id ? 'PUT' : 'POST', body: JSON.stringify(payload), ...jsonAuth() }, ); -export const deleteShippingInventoryExternalMapping = (id: number) => requestJson( - `/api/admin/shipping-notice/external-mappings/${id}`, { method: 'DELETE', ...auth() }, +export const deleteShippingOnhandExternalMapping = (id: number) => requestJson( + `/api/admin/freight-rpa/onhand/external-mappings/${id}`, { method: 'DELETE', ...auth() }, ); export const listAdminTrainingConfigs = () => requestJson('/api/admin/training-configs', auth()); diff --git a/frontend/src/features/admin/api/schedule.api.ts b/frontend/src/features/admin/api/schedule.api.ts index 80acf421..71e7a96d 100644 --- a/frontend/src/features/admin/api/schedule.api.ts +++ b/frontend/src/features/admin/api/schedule.api.ts @@ -1,6 +1,6 @@ /** * features/admin/api/schedule.api.ts - * 管理后台定时任务 HTTP API:任务 CRUD、配置、测试执行、运行记录。 + * 管理后台定时任务 HTTP API:任务 CRUD、配置、测试执行、运行记录、库存/入站/出站 raw-zip。 */ import { getAuthHeaders } from '@/shared/utils/auth'; import { requestJson } from '@/shared/api/client'; @@ -159,8 +159,11 @@ export const adminRunExcelUrl = (runId: number) => `/api/admin/schedule-runs/${r export const adminRunInventoryRawZipUrl = (runId: number) => `/api/admin/schedule-runs/${runId}/inventory-raw-zip`; -export const adminRunReceiptRawZipUrl = (runId: number) => - `/api/admin/schedule-runs/${runId}/receipt-raw-zip`; +export const adminRunInboundRawZipUrl = (runId: number) => + `/api/admin/schedule-runs/${runId}/inbound-raw-zip`; + +export const adminRunOutboundRawZipUrl = (runId: number) => + `/api/admin/schedule-runs/${runId}/outbound-raw-zip`; export interface RpaWorkerHeartbeatWorker { worker_id?: string; @@ -181,7 +184,7 @@ export interface RpaWorkerHeartbeatWorker { } export interface RpaWorkerHeartbeatSummary { - scope?: 'inventory' | 'receipt' | string; + scope?: 'onhand' | 'inbound' | 'outbound' | string; ready: boolean; message: string; detail_message?: string; @@ -195,7 +198,7 @@ export interface RpaWorkerHeartbeatSummary { workers: RpaWorkerHeartbeatWorker[]; } -export const getAdminRpaWorkersStatus = (scope: 'inventory' | 'receipt' = 'inventory') => +export const getAdminRpaWorkersStatus = (scope: 'onhand' | 'inbound' | 'outbound' = 'onhand') => getJson(`/api/admin/rpa-workers/status?scope=${encodeURIComponent(scope)}`); export type { DifyExecutionSnapshot, ScheduleRun, ScheduleTask, StepLog, TestScheduleRunResult, TestScheduleSqlResult }; diff --git a/frontend/src/features/admin/components/AdminNav.vue b/frontend/src/features/admin/components/AdminNav.vue index 3fc21cd1..0f8e2f07 100644 --- a/frontend/src/features/admin/components/AdminNav.vue +++ b/frontend/src/features/admin/components/AdminNav.vue @@ -11,7 +11,7 @@ import { useRoute, useRouter } from 'vue-router'; import { LayoutDashboard, UserCog, Building, Bot, FileText, Settings2, Megaphone, MessageCircleQuestion, Link2, Users, BarChart2, AppWindow, - ScrollText, ExternalLink, PackageSearch, GraduationCap, Cable, + ScrollText, ExternalLink, PackageSearch, GraduationCap, Cable, ArrowLeftRight, } from 'lucide-vue-next'; import type { Component } from 'vue'; import { config } from '@/config'; @@ -44,16 +44,18 @@ const iconMap: Record = { procurement_contract: ScrollText, training_config: GraduationCap, integration_connector: Cable, + transfer_types: ArrowLeftRight, reports: BarChart2, - shipping_inventory: PackageSearch, + freight_rpa: PackageSearch, }; const visibleModules = computed(() => ADMIN_MODULE_METAS.filter((item) => config.admin.modules[item.configKey] !== false), ); +// 调拨类型(transfer_types)已移入货代管理子菜单(路由规则之下),不再作为顶级入口渲染 const standardModules = computed(() => - visibleModules.value.filter((item) => item.id !== 'wecom' && item.id !== 'shipping_inventory'), + visibleModules.value.filter((item) => item.id !== 'wecom' && item.id !== 'freight_rpa' && item.id !== 'transfer_types'), ); const isModuleActive = (moduleId: AdminModuleId): boolean => @@ -61,11 +63,19 @@ const isModuleActive = (moduleId: AdminModuleId): boolean => const isReportsActive = computed(() => route.meta.adminModule === 'reports'); const isWecomActive = computed(() => route.meta.adminModule === 'wecom'); -const isShippingActive = computed(() => route.meta.adminModule === 'shipping_inventory'); +// 货代管理激活态涵盖调拨类型:进入该子页时父菜单高亮并自动展开 +const isShippingActive = computed(() => ( + route.meta.adminModule === 'freight_rpa' || route.meta.adminModule === 'transfer_types' +)); const shippingGroups = computed(() => [...new Set(SHIPPING_CONFIG_SUB_MODULE_METAS.map((item) => item.groupKey))]); const shippingExpanded = ref>({}); +// 子菜单项可见性:调拨类型沿用自身的模块 config 开关,其余跟随货代管理父开关 +const visibleShippingSubMetas = computed(() => + SHIPPING_CONFIG_SUB_MODULE_METAS.filter((item) => item.id !== 'transfer_types' || config.admin.modules.transfer_types !== false), +); + const isShippingSubActive = (sub: (typeof SHIPPING_CONFIG_SUB_MODULE_METAS)[number]): boolean => { if (route.name !== sub.routeName) return false; if (!sub.query) return true; @@ -200,7 +210,7 @@ watch( -
+