Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d3204f1db8 | ||
|
|
bce589eb96 | ||
|
|
e15b7b1ac2 | ||
|
|
663f401873 | ||
|
|
5a269f940d | ||
|
|
4c2a7e2a23 | ||
|
|
911afa0f73 | ||
|
|
39fe3c05f2 | ||
|
|
ffc0d4a430 | ||
|
|
bf3154033b | ||
|
|
8102a1fe44 | ||
|
|
43dceaf027 | ||
|
|
fc42bb14c9 | ||
|
|
e4100815a0 | ||
|
|
3a19f9c27d | ||
|
|
52c71ee46a | ||
|
|
28d6085d07 | ||
|
|
4225ed4d0b | ||
|
|
89b32bcdb5 | ||
|
|
9eb3749888 | ||
|
|
f67fa6f09f | ||
|
|
5746b1d220 | ||
|
|
01ae63901a | ||
|
|
06c77d40c7 | ||
|
|
9f132564d6 | ||
|
|
92ed140739 |
No files matched your search
@@ -1,2 +0,0 @@
|
|||||||
DEBUG_SERVER_URL=http://127.0.0.1:7778/event
|
|
||||||
DEBUG_SESSION_ID=login-401
|
|
||||||
@@ -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}
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
# =============================================================================
|
# =============================================================================
|
||||||
# Development — docker compose / deploy_compose.sh dev
|
# Development — docker compose / deploy_compose.sh dev
|
||||||
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
||||||
# - .env.dev / .env.test / .env.prod for deployment environments
|
# - .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
|
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
|
||||||
# 复核工作台字段级 AI 建议;仅开发环境启用,建议仍须证据校验与人工裁决
|
# 复核工作台字段级 AI 建议;仅开发环境启用,建议仍须证据校验与人工裁决
|
||||||
SHIPPING_NOTICE_LLM_REVIEW_ENABLED=true
|
SHIPPING_NOTICE_LLM_REVIEW_ENABLED=true
|
||||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true
|
||||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED=true
|
||||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
||||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_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_NATIVE_PAGE_REUSE_ENABLED=true
|
||||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
|
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
|
||||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
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_MAX_ATTEMPTS=3
|
||||||
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||||
# RPA 目录(相对 backend/ 根目录,统一 freight_rpa/{inventory,receipt,common} 三层布局)
|
# RPA 目录(相对 backend/ 根;freight_rpa/{onhand,inbound,outbound,upload,common},2026-10-16 批次 R)
|
||||||
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=data/freight_rpa/inventory/drop
|
FREIGHT_RPA_SHARED_ONHAND_DROP_DIR=data/freight_rpa/onhand/drop
|
||||||
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory/triggers
|
FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR=data/freight_rpa/onhand/triggers
|
||||||
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=data/freight_rpa/receipt/drop
|
FREIGHT_RPA_SHARED_INBOUND_DROP_DIR=data/freight_rpa/inbound/drop
|
||||||
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=data/freight_rpa/receipt/triggers
|
FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR=data/freight_rpa/inbound/triggers
|
||||||
FREIGHT_RPA_RECEIPT_ARCHIVE_DIR=data/freight_rpa/receipt/archives
|
FREIGHT_RPA_INBOUND_ARCHIVE_DIR=data/freight_rpa/inbound/archives
|
||||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=data/freight_rpa/inventory/upload_queue
|
FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR=data/freight_rpa/outbound/drop
|
||||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/freight_rpa/inventory/upload_triggers
|
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
|
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR=data/freight_rpa/common/browser_profile
|
||||||
# AWS 库存列映射(可选 JSON 字符串)
|
# AWS 库存列映射(可选 JSON 字符串)
|
||||||
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
|
# 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
|
FREIGHT_RPA_WORKER_MOCK=false
|
||||||
# 本机无 Redis 时允许进程内存记录心跳;有 Redis 时优先写 Redis
|
# 本机无 Redis 时允许进程内存记录心跳;有 Redis 时优先写 Redis
|
||||||
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false
|
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false
|
||||||
FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK=true
|
FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK=true
|
||||||
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
|
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
|
||||||
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
|
# FREIGHT_RPA_WORKER_SAMPLE_ONHAND=
|
||||||
# --- 10. 运维、告警与维护工具 ---
|
# --- 10. 运维、告警与维护工具 ---
|
||||||
# 设备维保助手后端工具调用密钥
|
# 设备维保助手后端工具调用密钥
|
||||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# =============================================================================
|
# =============================================================================
|
||||||
# Production — docker compose env_file + deploy_compose.sh prod
|
# Production — docker compose env_file + deploy_compose.sh prod
|
||||||
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
||||||
# - .env.dev / .env.test / .env.prod for deployment environments
|
# - .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
|
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
|
||||||
|
|
||||||
# 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享)
|
# 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享)
|
||||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true
|
||||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED=true
|
||||||
# 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥)
|
# 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||||
SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh
|
SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh
|
||||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||||
@@ -142,21 +142,24 @@ SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=false
|
|||||||
FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
|
FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
|
||||||
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致)
|
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致)
|
||||||
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
|
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
|
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
||||||
# 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微
|
# 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微
|
||||||
FREIGHT_RPA_WORKER_ALERT_USERNAMES=
|
FREIGHT_RPA_WORKER_ALERT_USERNAMES=
|
||||||
FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
|
FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
|
||||||
FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
|
FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
|
||||||
FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
|
FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
|
||||||
# RPA 目录(正式环境:Ubuntu 挂载 Windows RPA 正式共享,统一 freight_rpa/{inventory,receipt,common} 三层布局)
|
# RPA 目录(正式:Ubuntu 挂载 Windows 共享;freight_rpa/{onhand,inbound,outbound,upload,common})
|
||||||
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/drop
|
FREIGHT_RPA_SHARED_ONHAND_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/onhand/drop
|
||||||
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/triggers
|
FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/onhand/triggers
|
||||||
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/drop
|
FREIGHT_RPA_SHARED_INBOUND_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inbound/drop
|
||||||
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/triggers
|
FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inbound/triggers
|
||||||
FREIGHT_RPA_RECEIPT_ARCHIVE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/archives
|
FREIGHT_RPA_INBOUND_ARCHIVE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inbound/archives
|
||||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_queue
|
FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/outbound/drop
|
||||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_triggers
|
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 访问)
|
# 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod
|
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod
|
||||||
# 订单交期回复 Agent(2026-10-10 上线边界):只同步订单日期 ≥ 起始日的订单行,早于边界的历史行随 erp_missing 语义自动移出工作台;留空/删除 = 全量同步(dev/test 不配置)
|
# 订单交期回复 Agent(2026-10-10 上线边界):只同步订单日期 ≥ 起始日的订单行,早于边界的历史行随 erp_missing 语义自动移出工作台;留空/删除 = 全量同步(dev/test 不配置)
|
||||||
|
|||||||
@@ -238,7 +238,6 @@ IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS=86400
|
|||||||
IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS=3
|
IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS=3
|
||||||
IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS=5
|
IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS=5
|
||||||
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS=7
|
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS=7
|
||||||
IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS=2
|
|
||||||
# 归档 bucket(MinIO;凭据复用 MINIO_*)
|
# 归档 bucket(MinIO;凭据复用 MINIO_*)
|
||||||
IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET=hxops-transfer
|
IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET=hxops-transfer
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# =============================================================================
|
# =============================================================================
|
||||||
# Test — docker compose / deploy_compose.sh test
|
# Test — docker compose / deploy_compose.sh test
|
||||||
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
||||||
# - .env.dev / .env.test / .env.prod for deployment environments
|
# - .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_PROGRESS_UI_V3_ENABLED=true
|
||||||
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
||||||
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
|
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
|
||||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true
|
||||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED=true
|
||||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
||||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_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
|
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
|
||||||
# 两域超时须覆盖最坏批次总时长(10 站串行 + 单站失败重试可达 30 分钟+),
|
# 两域超时须覆盖最坏批次总时长(10 站串行 + 单站失败重试可达 30 分钟+),
|
||||||
# 否则每轮对账会把仍在飞的健康批次误回收(2026-10-08 RUN20261008003113B726 实测教训)
|
# 否则每轮对账会把仍在飞的健康批次误回收(2026-10-08 RUN20261008003113B726 实测教训)
|
||||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=3600
|
FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS=3600
|
||||||
FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS=3600
|
FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS=3600
|
||||||
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
|
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||||
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||||
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
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
|
FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
|
||||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||||
FREIGHT_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns=
|
FREIGHT_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns=
|
||||||
# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享,统一 freight_rpa/{inventory,receipt,common} 三层布局)
|
# RPA 目录(测试:Ubuntu 挂载 Windows 共享;freight_rpa/{onhand,inbound,outbound,upload,common})
|
||||||
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/drop
|
FREIGHT_RPA_SHARED_ONHAND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/onhand/drop
|
||||||
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers
|
FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/onhand/triggers
|
||||||
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/drop
|
FREIGHT_RPA_SHARED_INBOUND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/drop
|
||||||
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/triggers
|
FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/triggers
|
||||||
FREIGHT_RPA_RECEIPT_ARCHIVE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/archives
|
FREIGHT_RPA_INBOUND_ARCHIVE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/archives
|
||||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_queue
|
FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/outbound/drop
|
||||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_triggers
|
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 字符串)
|
# AWS 库存列映射(可选 JSON 字符串)
|
||||||
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
|
# 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_MOCK=true
|
||||||
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
|
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
|
||||||
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
|
# FREIGHT_RPA_WORKER_SAMPLE_ONHAND=
|
||||||
# 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
# 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
|
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
|
||||||
# --- 10. 运维、告警与维护工具 ---
|
# --- 10. 运维、告警与维护工具 ---
|
||||||
|
|||||||
@@ -164,7 +164,7 @@ docker compose logs -f hxops-backend
|
|||||||
- **文件内章节顺序**:① 环境与应用标识 → ② 应用运行与进程 → ③ 公共地址与网络入口 → ④ 安全、认证与身份源 → ⑤ 数据库与基础设施 → ⑥ AI 平台、模型与内部工具 → ⑦ 企业系统集成 → ⑧ 知识库与文件处理 → ⑨ 业务模块 → ⑩ 运维、告警与维护工具;文件没有某类变量时直接省略该章节。
|
- **文件内章节顺序**:① 环境与应用标识 → ② 应用运行与进程 → ③ 公共地址与网络入口 → ④ 安全、认证与身份源 → ⑤ 数据库与基础设施 → ⑥ AI 平台、模型与内部工具 → ⑦ 企业系统集成 → ⑧ 知识库与文件处理 → ⑨ 业务模块 → ⑩ 运维、告警与维护工具;文件没有某类变量时直接省略该章节。
|
||||||
- **章节内组织**:先按业务域及子域聚合(如 Casdoor、MinIO、WeCom、HR、PLM、SRM、FAQ、Shipping Notice、Fixed Asset),不得把同一域拆散后做全局字母排序;同一域内按“开关/模式 → 地址 → 标识 → 凭据 → 路径 → 业务参数 → 超时/重试/并发 → 兼容/Mock”排列,同级变量再按字母排序。
|
- **章节内组织**:先按业务域及子域聚合(如 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`)置于该数据源首位。
|
- **数据库连接固定顺序**:`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` 使用相同章节骨架;同名变量保持相同相对位置,便于审查差异;新增变量时同步检查所有适用环境文件和上述权威文档。
|
- **跨环境一致性**:`.env.dev`、`.env.test`、`.env.prod` 使用相同章节骨架;同名变量保持相同相对位置,便于审查差异;新增变量时同步检查所有适用环境文件和上述权威文档。
|
||||||
- **调整红线**:重排环境变量时只能移动“注释 + 完整赋值行”,禁止修改变量名或值,禁止删除变量、注释或示例;真实密码、密钥、Token、Webhook 与生产连接信息必须由系统环境变量、Jenkins/CI 或 Secret 管理机制注入。
|
- **调整红线**:重排环境变量时只能移动“注释 + 完整赋值行”,禁止修改变量名或值,禁止删除变量、注释或示例;真实密码、密钥、Token、Webhook 与生产连接信息必须由系统环境变量、Jenkins/CI 或 Secret 管理机制注入。
|
||||||
|
|
||||||
@@ -205,7 +205,7 @@ docker compose logs -f hxops-backend
|
|||||||
| 环境变量 | [docs/convention/env_loading_priority.md](docs/convention/env_loading_priority.md) · [docs/convention/环境变量规则.md](docs/convention/环境变量规则.md) |
|
| 环境变量 | [docs/convention/env_loading_priority.md](docs/convention/env_loading_priority.md) · [docs/convention/环境变量规则.md](docs/convention/环境变量规则.md) |
|
||||||
| 知识库部署 | [docs/knowledge_base_runtime_deploy.md](docs/knowledge_base_runtime_deploy.md) |
|
| 知识库部署 | [docs/knowledge_base_runtime_deploy.md](docs/knowledge_base_runtime_deploy.md) |
|
||||||
| Excel/CSV 切块与 Dify 分段 | [docs/kb-excel-dify-chunking.md](docs/kb-excel-dify-chunking.md) |
|
| Excel/CSV 切块与 Dify 分段 | [docs/kb-excel-dify-chunking.md](docs/kb-excel-dify-chunking.md) |
|
||||||
| FAQ 缓存 / 热点发现运维 | [docs/faq_cache_ops_manual.md](docs/faq_cache_ops_manual.md) |
|
| FAQ 缓存 / 热点发现运维 | [docs/features/faq/faq_cache_ops_manual.md](docs/features/faq/faq_cache_ops_manual.md) |
|
||||||
| 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.md) |
|
| 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.md) |
|
||||||
| 前端架构规范 | [docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md) |
|
| 前端架构规范 | [docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md) |
|
||||||
| 前端 Element Plus | [docs/ui/ELEMENT_MIGRATION.md](docs/ui/ELEMENT_MIGRATION.md) |
|
| 前端 Element Plus | [docs/ui/ELEMENT_MIGRATION.md](docs/ui/ELEMENT_MIGRATION.md) |
|
||||||
|
|||||||
+15
-1
@@ -79,6 +79,20 @@ def create_app(config_name='default'):
|
|||||||
|
|
||||||
_transfer_capabilities.register_transfer_capabilities()
|
_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 冷启动到首个请求之间仍用镜像默认值。
|
# 启动时强制加载一次,避免 worker 冷启动到首个请求之间仍用镜像默认值。
|
||||||
with app.app_context():
|
with app.app_context():
|
||||||
_apply_persisted_settings(app, force=True)
|
_apply_persisted_settings(app, force=True)
|
||||||
@@ -149,7 +163,7 @@ def create_app(config_name='default'):
|
|||||||
# 负责(dev Wave 4),Web 进程不再兜底扫描。
|
# 负责(dev Wave 4),Web 进程不再兜底扫描。
|
||||||
# AUTO_UPLOAD 显式开启时启动级校验货代上传 RPA(仅告警,不阻断启动)。
|
# AUTO_UPLOAD 显式开启时启动级校验货代上传 RPA(仅告警,不阻断启动)。
|
||||||
try:
|
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,
|
||||||
)
|
)
|
||||||
log_auto_upload_readiness_at_startup(app)
|
log_auto_upload_readiness_at_startup(app)
|
||||||
|
|||||||
@@ -47,6 +47,7 @@ def register_blueprints(app: Flask) -> None:
|
|||||||
procurement_contract_bp,
|
procurement_contract_bp,
|
||||||
shipping_notice_bp,
|
shipping_notice_bp,
|
||||||
)
|
)
|
||||||
|
from app.api.freight_rpa import freight_rpa_bp
|
||||||
from app.api.files import files_bp
|
from app.api.files import files_bp
|
||||||
from app.api.contract_payment import contract_payment_bp
|
from app.api.contract_payment import contract_payment_bp
|
||||||
from app.api.equipment_acceptance import equipment_acceptance_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(internal_jobs_bp, url_prefix='/api/internal/jobs')
|
||||||
app.register_blueprint(maintenance_bp, url_prefix='/api/maintenance')
|
app.register_blueprint(maintenance_bp, url_prefix='/api/maintenance')
|
||||||
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
|
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(file_check_bp, url_prefix='/api/file-check')
|
||||||
app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context')
|
app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context')
|
||||||
app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance')
|
app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance')
|
||||||
|
|||||||
@@ -23,7 +23,8 @@ import app.api.admin.shipping_order_extraction # noqa: F401
|
|||||||
import app.api.admin.announcements # noqa: F401
|
import app.api.admin.announcements # noqa: F401
|
||||||
import app.api.admin.shipping_customers # noqa: F401
|
import app.api.admin.shipping_customers # noqa: F401
|
||||||
import app.api.admin.shipping_identity_rules # 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_order_schema # noqa: F401
|
||||||
import app.api.admin.shipping_field_assets # noqa: F401
|
import app.api.admin.shipping_field_assets # noqa: F401
|
||||||
import app.api.admin.shipping_order_document_profiles # 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.linked_services # noqa: F401
|
||||||
import app.api.admin.procurement_contract # noqa: F401
|
import app.api.admin.procurement_contract # noqa: F401
|
||||||
import app.api.admin.training_configs # noqa: F401
|
import app.api.admin.training_configs # noqa: F401
|
||||||
|
import app.api.admin.transfer_type # noqa: F401
|
||||||
|
|
||||||
__all__ = ['admin_bp']
|
__all__ = ['admin_bp']
|
||||||
@@ -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/<int:template_id>', 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/<int:template_id>/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/<int:template_id>/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/<int:template_id>/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/<int:template_id>/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/<int:template_id>/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/<int:template_id>', 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/<int:profile_id>', 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/<int:profile_id>', 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/<int:source_id>', 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/<int:source_id>/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/<int:source_id>/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/<int:source_id>/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/<int:source_id>/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/<int:source_id>/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/<int:source_id>/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/<int:source_id>', 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/<int:source_id>/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/<int:batch_id>', 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/<int:batch_id>/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/<int:source_id>/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/<int:source_id>/test-export/<string:run_no>', 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/<int:source_id>/test-export/<string:run_no>/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/<int:snapshot_id>/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/<int:field_id>', 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/<int:field_id>/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/<int:field_id>', 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/<int:profile_id>', 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/<int:profile_id>/sample-replacement-preview/<int:analysis_id>', 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/<int:profile_id>/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/<int:profile_id>/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/<int:profile_id>', 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/<int:analysis_id>', 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/<int:analysis_id>/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/<int:analysis_id>/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/<string:session_no>/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/<int:rule_id>', 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/<int:rule_id>/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/<int:rule_id>/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/<int:rule_id>', 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/<int:mapping_id>', 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/<int:mapping_id>', methods=['DELETE'])
|
|
||||||
@require_admin
|
|
||||||
def delete_shipping_inventory_external_mapping(mapping_id: int):
|
|
||||||
"""删除错误的外部系统仓库映射。"""
|
|
||||||
shipping_inventory_service.delete_external_mapping(mapping_id)
|
|
||||||
return '', 204
|
|
||||||
@@ -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/<int:template_id>', 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/<int:template_id>/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/<int:template_id>/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/<int:template_id>/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/<int:template_id>/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/<int:template_id>/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/<int:template_id>', 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/<string:session_no>/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)
|
||||||
@@ -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/<string:code>', 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))
|
||||||
@@ -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/<int:profile_id>', 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/<int:profile_id>', 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/<int:source_id>', 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/<int:source_id>/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/<int:source_id>/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/<int:source_id>/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/<int:source_id>/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/<int:source_id>/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/<int:source_id>/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/<int:source_id>/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/<int:source_id>/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/<int:source_id>', 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/<int:source_id>/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/<int:batch_id>', 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/<int:batch_id>/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/<int:source_id>/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/<int:source_id>/test-export/<string:run_no>', 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/<int:source_id>/test-export/<string:run_no>/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/<int:snapshot_id>/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/<int:field_id>', 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/<int:field_id>/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/<int:field_id>', 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/<int:profile_id>', 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/<int:profile_id>/sample-replacement-preview/<int:analysis_id>', 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/<int:profile_id>/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/<int:profile_id>/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/<int:profile_id>', 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/<int:analysis_id>', 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/<int:analysis_id>/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/<int:analysis_id>/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/<int:rule_id>', 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/<int:rule_id>/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/<int:rule_id>/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/<int:rule_id>', 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/<int:mapping_id>', 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/<int:mapping_id>', methods=['DELETE'])
|
||||||
|
@require_admin
|
||||||
|
def delete_shipping_inventory_external_mapping(mapping_id: int):
|
||||||
|
"""删除错误的外部系统仓库映射。"""
|
||||||
|
shipping_onhand_admin_service.delete_external_mapping(mapping_id)
|
||||||
|
return '', 204
|
||||||
@@ -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()))
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -2,7 +2,8 @@
|
|||||||
backend/app/api/internal/jobs.py
|
backend/app/api/internal/jobs.py
|
||||||
|
|
||||||
用途:平台内置 Job 内部 API(POST /api/internal/jobs/<job_key>)。
|
用途:平台内置 Job 内部 API(POST /api/internal/jobs/<job_key>)。
|
||||||
依赖: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 → 返回统一结构。
|
逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
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.job_registry import get_platform_job, run_platform_job
|
||||||
from app.services.schedule.schedule_contract import normalize_job_key
|
from app.services.schedule.schedule_contract import normalize_job_key
|
||||||
from app.services.schedule.scheduler_service import _generate_run_no
|
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,
|
apply_deferred_schedule_run_state,
|
||||||
recover_stale_awaiting_rpa_schedule_runs,
|
recover_stale_awaiting_rpa_schedule_runs,
|
||||||
should_defer_schedule_run_finalization,
|
should_defer_schedule_run_finalization,
|
||||||
)
|
)
|
||||||
from app.services.schedule.freight_receipt_rpa_finalize import (
|
from app.services.schedule.freight_rpa_inbound_finalize import (
|
||||||
apply_deferred_receipt_schedule_run_state,
|
apply_deferred_inbound_schedule_run_state,
|
||||||
recover_stale_receipt_rpa_schedule_runs,
|
recover_stale_inbound_rpa_schedule_runs,
|
||||||
should_defer_receipt_schedule_run,
|
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__)
|
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)
|
task, run = _resolve_schedule_task_and_run(key, data)
|
||||||
recover_stale_awaiting_rpa_schedule_runs(task)
|
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:
|
try:
|
||||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = run_platform_job(
|
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = run_platform_job(
|
||||||
key, task, run, data,
|
key, task, run, data,
|
||||||
@@ -189,8 +196,8 @@ def run_internal_job(name: str):
|
|||||||
'awaiting_rpa_callback': True,
|
'awaiting_rpa_callback': True,
|
||||||
})
|
})
|
||||||
|
|
||||||
if should_defer_receipt_schedule_run(task, step_logs):
|
if should_defer_inbound_schedule_run(task, step_logs):
|
||||||
apply_deferred_receipt_schedule_run_state(
|
apply_deferred_inbound_schedule_run_state(
|
||||||
run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs,
|
run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs,
|
||||||
)
|
)
|
||||||
return jsonify({
|
return jsonify({
|
||||||
@@ -199,7 +206,20 @@ def run_internal_job(name: str):
|
|||||||
'failed_count': failed_count, 'skipped_count': skipped_count,
|
'failed_count': failed_count, 'skipped_count': skipped_count,
|
||||||
},
|
},
|
||||||
'details': details, 'errors': errors, 'step_logs': step_logs,
|
'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(
|
_finalize_run(
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ def update_schedule_task_config(task_id: int):
|
|||||||
|
|
||||||
config_data = data.get('config', data)
|
config_data = data.get('config', data)
|
||||||
if isinstance(config_data, dict) and 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):
|
if task.schedule_type != SCHEDULE_TYPE_DATA_PIPELINE and not platform_job_allows_config(task.platform_api_path):
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
f"platform_job '{task.platform_api_path}' does not accept ScheduleTaskConfig"
|
f"platform_job '{task.platform_api_path}' does not accept ScheduleTaskConfig"
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/api/schedule/rpa_workers.py
|
backend/app/api/schedule/rpa_workers.py
|
||||||
|
|
||||||
用途:管理端查询货代库存/收料 RPA Worker 在线状态与就绪摘要。
|
用途:管理端查询货代库存/入站/出站 RPA Worker 在线状态与就绪摘要。
|
||||||
依赖:schedule.blueprint、rpa_worker_heartbeat.serialize_rpa_worker_status。
|
依赖:schedule.blueprint、freight_rpa.common.worker_heartbeat.serialize_rpa_worker_status。
|
||||||
逻辑:ScheduleWorkbenchPanel 在库存或收料 RPA 排程工作台展示对应 worker 心跳状态。
|
逻辑:ScheduleWorkbenchPanel 在库存、入站或出站 RPA 排程工作台展示对应 worker 心跳状态。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -13,7 +13,7 @@ from flask import request
|
|||||||
from app.api.schedule.blueprint import schedule_admin_bp
|
from app.api.schedule.blueprint import schedule_admin_bp
|
||||||
from app.core.decorators import require_admin
|
from app.core.decorators import require_admin
|
||||||
from app.core.response import ok
|
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'])
|
@schedule_admin_bp.route('/rpa-workers/status', methods=['GET'])
|
||||||
@@ -23,7 +23,7 @@ def get_rpa_workers_status():
|
|||||||
返回 RPA Worker 心跳摘要(在线/离线、最后心跳时间、就绪原因)。
|
返回 RPA Worker 心跳摘要(在线/离线、最后心跳时间、就绪原因)。
|
||||||
|
|
||||||
Query:
|
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))
|
return ok(serialize_rpa_worker_status(scope=scope))
|
||||||
@@ -2,8 +2,10 @@
|
|||||||
backend/app/api/schedule/runs.py
|
backend/app/api/schedule/runs.py
|
||||||
|
|
||||||
用途:排程运行触发与运行记录查询 API。
|
用途:排程运行触发与运行记录查询 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 承担实际运行。
|
逻辑:手动执行仅创建 queued run/job;独立 schedule worker 承担实际运行。
|
||||||
|
入站/出站 raw-zip 下载与失败单元 list/retry 对照同构。
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
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.auth.jwt import get_current_user
|
||||||
from app.core.decorators import require_admin
|
from app.core.decorators import require_admin
|
||||||
from app.core.errors import ConflictError, NotFoundError
|
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.query_service import get_run, list_runs, serialize_run
|
||||||
from app.services.schedule.queue_service import enqueue_manual_schedule_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.freight_rpa_onhand_archive import resolve_inventory_raw_zip_download
|
||||||
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
|
||||||
from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file
|
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.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/<int:task_id>/run', methods=['POST'])
|
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
|
||||||
@@ -44,7 +47,11 @@ def run_schedule(task_id: int):
|
|||||||
triggered_by_user_id=getattr(user, 'id', None),
|
triggered_by_user_id=getattr(user, 'id', None),
|
||||||
)
|
)
|
||||||
if not created:
|
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)
|
fresh = db.session.get(ScheduleRun, run.id)
|
||||||
return jsonify(serialize_run(fresh))
|
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/<int:run_id>/receipt-raw-zip', methods=['GET'])
|
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/inbound-raw-zip', methods=['GET'])
|
||||||
@require_admin
|
@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)
|
run = get_run(run_id)
|
||||||
if not run:
|
if not run:
|
||||||
raise NotFoundError('Not found')
|
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(
|
return send_file(
|
||||||
zip_path,
|
zip_path,
|
||||||
as_attachment=True,
|
as_attachment=True,
|
||||||
@@ -144,31 +151,10 @@ def get_schedule_run_receipt_raw_zip(run_id: int):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@schedule_admin_bp.route('/receipt-report-files/<int:file_id>/resend', methods=['POST'])
|
@schedule_admin_bp.route('/inbound-rpa-units', methods=['GET'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def resend_receipt_report_file(file_id: int):
|
def list_inbound_rpa_units():
|
||||||
"""管理员重发已归档的收料文件;禁止借重发重新触发 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():
|
|
||||||
"""管理员查看收料单元运行事实,供失败单元填写原因后人工重试。"""
|
|
||||||
status = str(request.args.get('status') or '').strip().lower()
|
status = str(request.args.get('status') or '').strip().lower()
|
||||||
if status and status not in {'queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled'}:
|
if status and status not in {'queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled'}:
|
||||||
from app.core.errors import ValidationError
|
from app.core.errors import ValidationError
|
||||||
@@ -178,19 +164,19 @@ def list_receipt_rpa_units():
|
|||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
from app.core.errors import ValidationError
|
from app.core.errors import ValidationError
|
||||||
raise ValidationError('limit is invalid')
|
raise ValidationError('limit is invalid')
|
||||||
query = ShippingReceiptRpaUnitRun.query.order_by(
|
query = FreightRpaInboundUnitRun.query.order_by(
|
||||||
ShippingReceiptRpaUnitRun.created_at.desc(), ShippingReceiptRpaUnitRun.id.desc(),
|
FreightRpaInboundUnitRun.created_at.desc(), FreightRpaInboundUnitRun.id.desc(),
|
||||||
)
|
)
|
||||||
if status:
|
if status:
|
||||||
query = query.filter(ShippingReceiptRpaUnitRun.status == status)
|
query = query.filter(FreightRpaInboundUnitRun.status == status)
|
||||||
units = query.limit(limit).all()
|
units = query.limit(limit).all()
|
||||||
user = get_current_user()
|
user = get_current_user()
|
||||||
append_shipping_audit_event(
|
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),
|
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',
|
owner_user_id=getattr(user, 'id', None), result='success',
|
||||||
after={'visible_count': len(units), 'status': status or None, 'limit': limit},
|
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()
|
db.session.commit()
|
||||||
return jsonify({'success': True, 'data': {'items': [{
|
return jsonify({'success': True, 'data': {'items': [{
|
||||||
@@ -207,34 +193,34 @@ def list_receipt_rpa_units():
|
|||||||
} for unit in units]}})
|
} for unit in units]}})
|
||||||
|
|
||||||
|
|
||||||
@schedule_admin_bp.route('/receipt-rpa-units/<int:unit_id>/retry', methods=['POST'])
|
@schedule_admin_bp.route('/inbound-rpa-units/<int:unit_id>/retry', methods=['POST'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def retry_receipt_rpa_unit(unit_id: int):
|
def retry_inbound_rpa_unit(unit_id: int):
|
||||||
"""管理员为失败收料单元创建独立重试事实;旧单元永不覆盖。"""
|
"""管理员为失败入站单元创建独立重试事实;旧单元永不覆盖。"""
|
||||||
failed = db.session.get(ShippingReceiptRpaUnitRun, unit_id)
|
failed = db.session.get(FreightRpaInboundUnitRun, unit_id)
|
||||||
if failed is None:
|
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'}:
|
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 {}
|
data = request.get_json(silent=True) or {}
|
||||||
reason = str(data.get('reason') or '').strip()
|
reason = str(data.get('reason') or '').strip()
|
||||||
if not reason:
|
if not reason:
|
||||||
from app.core.errors import ValidationError
|
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()
|
user = get_current_user()
|
||||||
retry = ShippingReceiptRpaUnitRun(
|
retry = FreightRpaInboundUnitRun(
|
||||||
schedule_run_id=failed.schedule_run_id, inventory_source_id=failed.inventory_source_id,
|
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,
|
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 {}),
|
config_snapshot_json=dict(failed.config_snapshot_json or {}),
|
||||||
)
|
)
|
||||||
db.session.add(retry)
|
db.session.add(retry)
|
||||||
db.session.flush()
|
db.session.flush()
|
||||||
source = retry.inventory_source
|
source = retry.source
|
||||||
profile = source.rpa_profile if source is not None else None
|
profile = source.rpa_profile if source is not None else None
|
||||||
if source is None or profile is None or not profile.enabled:
|
if source is None or profile is None or not profile.enabled:
|
||||||
db.session.rollback()
|
db.session.rollback()
|
||||||
raise ConflictError('Receipt RPA profile is unavailable')
|
raise ConflictError('Inbound RPA profile is unavailable')
|
||||||
snapshot = dict(retry.config_snapshot_json or {})
|
snapshot = dict(retry.config_snapshot_json or {})
|
||||||
trigger_unit = {
|
trigger_unit = {
|
||||||
'unit_run_id': retry.id, 'callback_id': retry.callback_id, 'source_code': retry.source_code,
|
'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
|
retry.trigger_snapshot_json = trigger_unit
|
||||||
run = retry.schedule_run
|
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],
|
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:
|
if not trigger_path:
|
||||||
db.session.rollback()
|
db.session.rollback()
|
||||||
raise ConflictError('Receipt RPA trigger directory is unavailable')
|
raise ConflictError('Inbound RPA trigger directory is unavailable')
|
||||||
run.status = 'running'
|
run.status = 'running'
|
||||||
run.finished_at = None
|
run.finished_at = None
|
||||||
summary = dict(run.response_summary_json or {})
|
summary = dict(run.response_summary_json or {})
|
||||||
summary['awaiting_receipt_rpa'] = True
|
summary['awaiting_inbound_rpa'] = True
|
||||||
run.response_summary_json = summary
|
run.response_summary_json = summary
|
||||||
append_shipping_audit_event(
|
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/<int:run_id>/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/<int:unit_id>/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),
|
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,
|
owner_user_id=getattr(user, 'id', None), unit_id=retry.id, result='success', reason=reason,
|
||||||
before={'status': failed.status, 'error_code': failed.error_code},
|
before={'status': failed.status, 'error_code': failed.error_code},
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/api/tools/shipping_notice.py
|
backend/app/api/tools/shipping_notice.py
|
||||||
|
|
||||||
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。
|
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent 与导出下载入口调用。
|
||||||
依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url。
|
依赖: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;
|
逻辑:register_blueprints 从 api.tools 挂载;Tool 成功响应仍用 status: ok/failed 业务 envelope;
|
||||||
HTTP 级参数/资源错误统一 raise AppError;`_payload()` 剥离 body 中的操作人伪造字段;
|
HTTP 级参数/资源错误统一 raise AppError;`_payload()` 剥离 body 中的操作人伪造字段;
|
||||||
|
RPA 回调已整体迁出至 api/freight_rpa.py(/api/freight-rpa/*,无双路由);
|
||||||
历史批次 Tool 已删除,订单抽取统一走 order-extraction-submissions。
|
历史批次 Tool 已删除,订单抽取统一走 order-extraction-submissions。
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -15,10 +16,8 @@ from app import db
|
|||||||
from app.core.errors import (
|
from app.core.errors import (
|
||||||
AppError,
|
AppError,
|
||||||
NotFoundError,
|
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 import tools as shipping_tools
|
||||||
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
|
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
|
||||||
from app.services.shipping_notice.query_service import (
|
from app.services.shipping_notice.query_service import (
|
||||||
@@ -28,40 +27,10 @@ from app.services.shipping_notice.query_service import (
|
|||||||
serialize_task_summary,
|
serialize_task_summary,
|
||||||
task_export_error_message,
|
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
|
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||||
|
|
||||||
shipping_notice_bp = Blueprint("shipping_notice", __name__)
|
shipping_notice_bp = Blueprint("shipping_notice", __name__)
|
||||||
|
|
||||||
|
|
||||||
def _require_tool_auth() -> None:
|
|
||||||
"""
|
|
||||||
校验货代 Tool API 鉴权 Header。
|
|
||||||
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;当 Dify、RPA 或外部系统请求本蓝图时由 before_request 自动触发。
|
|
||||||
|
|
||||||
核心逻辑:只接受 `Authorization: Bearer <token>` 或 `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:
|
def _tool_error_code(exc: AppError) -> str:
|
||||||
"""统一归一化 Tool API 的错误码,保持与文件检核 Tool 返回风格一致。"""
|
"""统一归一化 Tool API 的错误码,保持与文件检核 Tool 返回风格一致。"""
|
||||||
message = str(exc.message or '').strip()
|
message = str(exc.message or '').strip()
|
||||||
@@ -84,12 +53,13 @@ def _handle_tool_app_error(exc: AppError):
|
|||||||
@shipping_notice_bp.before_request
|
@shipping_notice_bp.before_request
|
||||||
def _verify_tool_access():
|
def _verify_tool_access():
|
||||||
"""
|
"""
|
||||||
对货代 Tool / RPA / 导出接口做统一 Header 鉴权。
|
对货代 Tool / 导出接口做统一 Header 鉴权。
|
||||||
核心逻辑:仅放行 OpenAPI 导入文档,其他请求都必须携带有效 Tool Key。
|
核心逻辑:仅放行 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'):
|
if request.path.endswith('/openapi.json') or request.path.endswith('/openapi.dify.yaml'):
|
||||||
return None
|
return None
|
||||||
_require_tool_auth()
|
require_tool_auth()
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def _tool_api_base_url() -> str:
|
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(),
|
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
|
||||||
trigger='legacy_tool_ensure_inventory',
|
trigger='legacy_tool_ensure_inventory',
|
||||||
operator_id=payload.get('operator_id'),
|
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'])
|
@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(),
|
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
|
||||||
trigger='legacy_tool_match_inventory',
|
trigger='legacy_tool_match_inventory',
|
||||||
operator_id=payload.get('operator_id'),
|
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'])
|
@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)
|
_require_read_capability(payload, scope='get_shipping_status', task_no=task_no or None)
|
||||||
return jsonify(shipping_tools.get_task_status(payload))
|
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/<task_no>/repair-inventory-attachment', methods=['POST'])
|
@shipping_notice_bp.route('/tasks/<task_no>/repair-inventory-attachment', methods=['POST'])
|
||||||
def repair_task_inventory_attachment(task_no: str):
|
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)
|
payload.setdefault("task_id", task_no)
|
||||||
return jsonify(shipping_tools.repair_task_inventory_attachment(payload))
|
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/<task_no>/export', methods=['GET'])
|
@shipping_notice_bp.route('/tasks/<task_no>/export', methods=['GET'])
|
||||||
def download_task_export(task_no: str):
|
def download_task_export(task_no: str):
|
||||||
"""下载任务已生成的出货 Excel。"""
|
"""下载任务已生成的出货 Excel。"""
|
||||||
|
|||||||
@@ -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
|
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_process_gate # noqa: F401
|
||||||
import app.api.workspace.shipping_inventory_candidates # noqa: F401
|
import app.api.workspace.shipping_onhand_candidates # noqa: F401
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
'workspace_announcements_bp',
|
'workspace_announcements_bp',
|
||||||
|
|||||||
@@ -87,34 +87,6 @@ def _ok(payload: Any, *, status: int = 200):
|
|||||||
return ok(payload, request_id=getattr(g, 'request_id', None), status=status)
|
return ok(payload, request_id=getattr(g, 'request_id', None), status=status)
|
||||||
|
|
||||||
|
|
||||||
@workspace_shipping_notice_bp.route('/receipt-report-files/<int:file_id>/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:
|
def _assert_fulfillment_task_ownership(task: ShippingNotice, user_id: int) -> None:
|
||||||
"""
|
"""
|
||||||
履约写接口:若请求携带期望 OT/Case/Run,校验与正式 Notice 归属一致。
|
履约写接口:若请求携带期望 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)
|
task = get_task_for_user(task_no, user.id)
|
||||||
if not task:
|
if not task:
|
||||||
raise NotFoundError('Not found')
|
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)
|
resolved = resolve_task_inventory_download(task)
|
||||||
if resolved is None:
|
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
|
path, download_name = resolved
|
||||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||||
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')
|
raise NotFoundError('Not found')
|
||||||
from pathlib import Path
|
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()
|
requested_file_no = str(inventory_file_no or '').strip()
|
||||||
inventory_file = (
|
inventory_file = (
|
||||||
ShippingInventoryFile.query
|
FreightRpaOnhandReportFile.query
|
||||||
.join(
|
.join(
|
||||||
ShippingNoticeLineInventoryMatch,
|
ShippingNoticeLineOnhandMatch,
|
||||||
ShippingNoticeLineInventoryMatch.inventory_snapshot_id == ShippingInventoryFile.id,
|
ShippingNoticeLineOnhandMatch.onhand_snapshot_id == FreightRpaOnhandReportFile.id,
|
||||||
)
|
)
|
||||||
.filter(
|
.filter(
|
||||||
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
|
ShippingNoticeLineOnhandMatch.task_id == int(task.id),
|
||||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
ShippingNoticeLineOnhandMatch.is_current.is_(True),
|
||||||
ShippingNoticeLineInventoryMatch.matched_file_no == requested_file_no,
|
ShippingNoticeLineOnhandMatch.matched_file_no == requested_file_no,
|
||||||
ShippingInventoryFile.inventory_file_no == requested_file_no,
|
FreightRpaOnhandReportFile.onhand_file_no == requested_file_no,
|
||||||
)
|
)
|
||||||
.first()
|
.first()
|
||||||
)
|
)
|
||||||
storage_path = str(getattr(inventory_file, 'storage_path', '') or '').strip()
|
storage_path = str(getattr(inventory_file, 'storage_path', '') or '').strip()
|
||||||
path = Path(storage_path).resolve() if storage_path else None
|
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():
|
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')
|
raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_ONHAND_FILE_NOT_FOUND')
|
||||||
download_name = str(
|
from app.services.shipping_notice.onhand_file_store import build_inventory_download_name
|
||||||
inventory_file.source_file_name or f'{inventory_file.inventory_file_no}{path.suffix or ".xlsx"}',
|
download_name = build_inventory_download_name(
|
||||||
).strip()
|
inventory_file, source_file_name=inventory_file.source_file_name, path=path,
|
||||||
|
)
|
||||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||||
record_access_audit(
|
record_access_audit(
|
||||||
action='download_task_line_inventory_file',
|
action='download_task_line_inventory_file',
|
||||||
|
|||||||
+3
-3
@@ -1,8 +1,8 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/api/workspace/shipping_inventory_candidates.py
|
backend/app/api/workspace/shipping_onhand_candidates.py
|
||||||
|
|
||||||
用途:正式 Task 库存候选只读详情 API。
|
用途:正式 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,
|
逻辑:路由层仅做鉴权与查询参数校验;当前版本缺失返回 200 + current_set=null + blocking_reason,
|
||||||
不把可恢复业务阻断误报成 404。
|
不把可恢复业务阻断误报成 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.api.workspace.shipping_notice import _ok, _require_user, workspace_shipping_notice_bp
|
||||||
from app.core.errors import ValidationError
|
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,
|
project_inventory_candidate_detail,
|
||||||
)
|
)
|
||||||
from app.services.shipping_notice.query_service import get_task_for_user
|
from app.services.shipping_notice.query_service import get_task_for_user
|
||||||
@@ -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_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_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_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(
|
SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float(
|
||||||
os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '420')
|
os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '420')
|
||||||
)
|
)
|
||||||
@@ -373,14 +370,18 @@ class Config:
|
|||||||
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY = float(
|
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY = float(
|
||||||
os.getenv('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY') or '0.98'
|
os.getenv('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY') or '0.98'
|
||||||
)
|
)
|
||||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
|
SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED = (
|
||||||
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
|
os.getenv('SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED', 'true').lower() == 'true'
|
||||||
)
|
)
|
||||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS = int(
|
FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS = int(
|
||||||
os.getenv('FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS') or '900'
|
os.getenv('FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS') or '900'
|
||||||
)
|
)
|
||||||
FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS = int(
|
FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS = int(
|
||||||
os.getenv('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS') or '900'
|
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(
|
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int(
|
||||||
os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90'
|
os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90'
|
||||||
@@ -442,38 +443,51 @@ class Config:
|
|||||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS = int(
|
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS = int(
|
||||||
os.getenv('SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS') or '24'
|
os.getenv('SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS') or '24'
|
||||||
)
|
)
|
||||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED = (
|
SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED = (
|
||||||
os.getenv('SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED', 'true').lower() == 'true'
|
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')
|
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
|
||||||
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
|
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
|
||||||
# RPA 运行期数据目录统一为 `freight_rpa/{inventory,receipt,common}` 三层布局(与 env/ps1 三侧一致)。
|
# RPA 运行期数据目录分域(2026-10-16 批次 R):
|
||||||
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR = _rpa_data_path(
|
# onhand/ inbound/ outbound/ — 抓取域,叶目录同构 triggers|drop|logs|archives
|
||||||
'FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR', 'freight_rpa', 'inventory', 'drop'
|
# 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_ONHAND_TRIGGER_DIR = _rpa_data_path(
|
||||||
'FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR', 'freight_rpa', 'inventory', 'triggers'
|
'FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR', 'freight_rpa', 'onhand', 'triggers'
|
||||||
)
|
)
|
||||||
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR = _rpa_data_path(
|
FREIGHT_RPA_SHARED_INBOUND_DROP_DIR = _rpa_data_path(
|
||||||
'FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR', 'freight_rpa', 'receipt', 'drop'
|
'FREIGHT_RPA_SHARED_INBOUND_DROP_DIR', 'freight_rpa', 'inbound', 'drop'
|
||||||
)
|
)
|
||||||
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR = _rpa_data_path(
|
FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR = _rpa_data_path(
|
||||||
'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', 'freight_rpa', 'receipt', 'triggers'
|
'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 = _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 = _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 = _rpa_data_path(
|
||||||
'FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR', 'freight_rpa', 'common', 'browser_profile'
|
'FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR', 'freight_rpa', 'common', 'browser_profile'
|
||||||
)
|
)
|
||||||
FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = _rpa_data_path(
|
FREIGHT_RPA_ONHAND_ARCHIVE_DIR = _rpa_data_path(
|
||||||
'FREIGHT_RPA_INVENTORY_ARCHIVE_DIR', 'freight_rpa', 'inventory', 'archives'
|
'FREIGHT_RPA_ONHAND_ARCHIVE_DIR', 'freight_rpa', 'onhand', 'archives'
|
||||||
)
|
)
|
||||||
FREIGHT_RPA_RECEIPT_ARCHIVE_DIR = _rpa_data_path(
|
FREIGHT_RPA_INBOUND_ARCHIVE_DIR = _rpa_data_path(
|
||||||
'FREIGHT_RPA_RECEIPT_ARCHIVE_DIR', 'freight_rpa', 'receipt', 'archives'
|
'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')
|
FREIGHT_RPA_WORKER_MOCK = os.getenv('FREIGHT_RPA_WORKER_MOCK', 'false')
|
||||||
|
|
||||||
|
|||||||
@@ -28,11 +28,14 @@ class ValidationError(AppError):
|
|||||||
*,
|
*,
|
||||||
code: str = "VALIDATION.INVALID_PARAM",
|
code: str = "VALIDATION.INVALID_PARAM",
|
||||||
details: dict[str, Any] | None = None,
|
details: dict[str, Any] | None = None,
|
||||||
|
http_status: int = 400,
|
||||||
):
|
):
|
||||||
super().__init__(
|
super().__init__(
|
||||||
code=code,
|
code=code,
|
||||||
message=message,
|
message=message,
|
||||||
http_status=400,
|
# 默认 400(参数形态类校验);业务契约指定状态码时显式传入
|
||||||
|
# (如调拨类型门禁 REQUIRED/NOT_CONFIGURED/DISABLED = 422,规格 §11)。
|
||||||
|
http_status=http_status,
|
||||||
details=details or {},
|
details=details or {},
|
||||||
retryable=False,
|
retryable=False,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -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 <token>` 或 `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')
|
||||||
@@ -16,7 +16,7 @@ from app.jobs.handlers import ( # noqa: F401
|
|||||||
procurement_contract_review,
|
procurement_contract_review,
|
||||||
schedule_run,
|
schedule_run,
|
||||||
shipping_document_layout,
|
shipping_document_layout,
|
||||||
shipping_inventory_callback_process,
|
freight_rpa_onhand_callback_process,
|
||||||
shipping_notice_parse,
|
shipping_notice_parse,
|
||||||
shipping_notice_run,
|
shipping_notice_run,
|
||||||
shipping_order_extraction,
|
shipping_order_extraction,
|
||||||
|
|||||||
+31
-7
@@ -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 处理阻塞。
|
用途:异步处理已收件的库存 RPA batch 回调,避免 Worker HTTP 回调被 Excel 处理阻塞。
|
||||||
依赖:Job 队列、inventory_rpa_workflow 的正式批量处理函数。
|
依赖:Job 队列、onhand_rpa_workflow 的正式批量处理函数。
|
||||||
逻辑:HTTP 回调只写本 Job;shipping worker 领取后执行结构校验、库存解析、任务关联与后续推进。
|
逻辑:HTTP 回调只写本 Job;shipping worker 领取后执行结构校验、库存解析、任务关联与后续推进。
|
||||||
|
业务失败(transport/result_status=failed)收口为不可重试;意外异常(含批量 commit 后
|
||||||
|
onhand 事实处理函数失败的重抛)收口为可重试(Task 7 修复轮 2——文件行已提交不回滚,
|
||||||
|
重放按幂等契约补齐候选/门禁收口);修复轮 3:投递失败重抛携带的未成功文件清单写回
|
||||||
|
payload(retry_dispatch_files),重试经批量入口的「只重投失败文件」通道补齐。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -16,7 +20,7 @@ from app.jobs.types import JobType
|
|||||||
from app.models import Job
|
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:
|
def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> None:
|
||||||
"""处理一个已收件的库存 RPA 回调。
|
"""处理一个已收件的库存 RPA 回调。
|
||||||
|
|
||||||
@@ -31,7 +35,7 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N
|
|||||||
|
|
||||||
owned_attempt = int(job.attempts or 0)
|
owned_attempt = int(job.attempts or 0)
|
||||||
try:
|
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 = process_rpa_report_inventory_batch(dict(job.payload_json or {}))
|
||||||
result_data = result.get('data') if isinstance(result, dict) else None
|
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'}:
|
if transport_status == 'failed' or result_status in {'failed', 'partial_failed'}:
|
||||||
failed_items = result_data.get('failed') if isinstance(result_data, dict) else []
|
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
|
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(
|
settle_failed_inventory_callback(
|
||||||
dict(job.payload_json or {}),
|
dict(job.payload_json or {}),
|
||||||
@@ -64,12 +68,32 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N
|
|||||||
message='库存 RPA 回调已异步处理',
|
message='库存 RPA 回调已异步处理',
|
||||||
owned_attempt=owned_attempt,
|
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()
|
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(
|
fail_job(
|
||||||
job.id,
|
job.id,
|
||||||
error=str(exc),
|
error=str(exc),
|
||||||
result={'status': 'processing_failed', 'error': str(exc)[:1000]},
|
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,
|
owned_attempt=owned_attempt,
|
||||||
)
|
)
|
||||||
@@ -5,6 +5,13 @@
|
|||||||
逻辑:领取后按 payload.matching_id 加载匹配,运行 run_matching 并回写
|
逻辑:领取后按 payload.matching_id 加载匹配,运行 run_matching 并回写
|
||||||
状态/计数/Hash;匹配不存在时 fail-closed 抛 RuntimeError。业务收尾后
|
状态/计数/Hash;匹配不存在时 fail-closed 抛 RuntimeError。业务收尾后
|
||||||
handler 自行 finish_job(runner 仅兜底异常路径,正常完成不代收口)。
|
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
|
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
|
owned_attempt = int(job_row.attempts) if job_row is not None else None
|
||||||
|
|
||||||
deps = transfer_deps.get_transfer_dependencies()
|
deps = transfer_deps.get_transfer_dependencies()
|
||||||
|
# [快照自足] 类型/范围/转换规则全部回读 scope_json(无枚举依赖、不查现行
|
||||||
|
# 配置规则);warehouse 路由的 fixed 定义随类型配置现行值(未入快照契约)。
|
||||||
scope = matching.scope_json if isinstance(matching.scope_json, dict) else {}
|
scope = matching.scope_json if isinstance(matching.scope_json, dict) else {}
|
||||||
source_codes = list(scope.get("source_codes") or [])
|
source_codes = list(scope.get("source_codes") or [])
|
||||||
result = run_matching(
|
result = run_matching(
|
||||||
@@ -43,14 +52,18 @@ def run_in_transit_transfer_match(_ctx, payload: dict) -> None:
|
|||||||
business_date=matching.business_date,
|
business_date=matching.business_date,
|
||||||
deps=deps,
|
deps=deps,
|
||||||
run_no=matching.run.run_no if matching.run else "RUN-PENDING",
|
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,
|
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
|
summary = result.summary
|
||||||
matching.status = summary.status
|
matching.status = summary.status
|
||||||
matching.counts_json = {
|
matching.counts_json = {
|
||||||
"file_invoice_count": summary.counts.file_invoice_count,
|
"file_invoice_count": summary.counts.file_invoice_count,
|
||||||
"not_matured_count": summary.counts.not_matured_count,
|
|
||||||
"matched_count": summary.counts.matched_count,
|
"matched_count": summary.counts.matched_count,
|
||||||
"executable_count": summary.counts.executable_count,
|
"executable_count": summary.counts.executable_count,
|
||||||
"blocked_count": summary.counts.blocked_count,
|
"blocked_count": summary.counts.blocked_count,
|
||||||
|
|||||||
@@ -3,7 +3,9 @@ backend/app/jobs/types.py
|
|||||||
|
|
||||||
用途:Job 类型与状态枚举;KbJob.job_type 与 handler JobType 的双向映射。
|
用途:Job 类型与状态枚举;KbJob.job_type 与 handler JobType 的双向映射。
|
||||||
逻辑:handlers 与 queue 通过 JobType 注册;store 持久化仍走 KbJob 表(Wave 2 双轨);
|
逻辑: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
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -20,8 +22,9 @@ class JobType(StrEnum):
|
|||||||
SHIPPING_ORDER_EXTRACTION = 'shipping_order_extraction'
|
SHIPPING_ORDER_EXTRACTION = 'shipping_order_extraction'
|
||||||
SHIPPING_DOCUMENT_LAYOUT = 'shipping_document_layout'
|
SHIPPING_DOCUMENT_LAYOUT = 'shipping_document_layout'
|
||||||
SHIPPING_PROCESS_GATE = 'shipping_process_gate'
|
SHIPPING_PROCESS_GATE = 'shipping_process_gate'
|
||||||
# RPA 回调 HTTP 只收件;Excel 校验、解析、任务关联由 shipping worker 异步完成。
|
# 在手 RPA 回调 HTTP 只收件;Excel 校验、解析、任务关联由 shipping worker 异步完成。
|
||||||
SHIPPING_INVENTORY_CALLBACK_PROCESS = 'shipping_inventory_callback_process'
|
# 持久化 jobs.job_type 为 freight_rpa_onhand_callback_process。
|
||||||
|
FREIGHT_RPA_ONHAND_CALLBACK_PROCESS = 'freight_rpa_onhand_callback_process'
|
||||||
# 统一 PDF 自动标记:按实际证据能力执行坐标重建或 XFA 多源视觉融合。
|
# 统一 PDF 自动标记:按实际证据能力执行坐标重建或 XFA 多源视觉融合。
|
||||||
SHIPPING_PDF_AUTOMARK = 'shipping_pdf_automark'
|
SHIPPING_PDF_AUTOMARK = 'shipping_pdf_automark'
|
||||||
# 资格达标后的 STP 自动建单入队(先 queued,再由 worker 执行 confirm)
|
# 资格达标后的 STP 自动建单入队(先 queued,再由 worker 执行 confirm)
|
||||||
@@ -76,7 +79,7 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
|
|||||||
'shipping': frozenset({
|
'shipping': frozenset({
|
||||||
'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction',
|
'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction',
|
||||||
'shipping_document_layout', 'shipping_process_gate', 'shipping_pdf_automark',
|
'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_stp_auto_create', 'shipping_line_auto_fulfill',
|
||||||
'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress',
|
'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress',
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -2,8 +2,9 @@
|
|||||||
backend/app/models/__init__.py
|
backend/app/models/__init__.py
|
||||||
|
|
||||||
用途:按业务域拆分的 ORM 模型包入口;聚合导出以保持 `from app.models import User` 兼容。
|
用途:按业务域拆分的 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 注册全部表元数据;业务代码继续从此处导入模型类。
|
逻辑:Alembic / Flask-Migrate 通过本模块 import 注册全部表元数据;业务代码继续从此处导入模型类。
|
||||||
|
在手/入站/出站模型导出 FreightRpa*。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest
|
from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest
|
||||||
@@ -31,15 +32,15 @@ from app.models.contract_payment import (
|
|||||||
ContractPaymentVendorRequest,
|
ContractPaymentVendorRequest,
|
||||||
)
|
)
|
||||||
from app.models.shipping import (
|
from app.models.shipping import (
|
||||||
ShippingInventoryFile,
|
|
||||||
ShippingNotice,
|
ShippingNotice,
|
||||||
ShippingOrderCandidate,
|
ShippingOrderCandidate,
|
||||||
ShippingOrderDocument,
|
ShippingOrderDocument,
|
||||||
ShippingOrderIntake,
|
ShippingOrderIntake,
|
||||||
ShippingTaskEvent,
|
ShippingTaskEvent,
|
||||||
ShippingTaskPurgeAudit,
|
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_submission import ShippingOrderSubmission
|
||||||
from app.models.shipping_order_task import ShippingOrderTask
|
from app.models.shipping_order_task import ShippingOrderTask
|
||||||
from app.models.shipping_order_candidate_evidence import ShippingOrderCandidateEvidence
|
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_excel_template import ShippingExcelTemplate, ShippingExportArtifact
|
||||||
from app.models.shipping_fulfillment import (
|
from app.models.shipping_fulfillment import (
|
||||||
ShippingExportArtifactLine,
|
ShippingExportArtifactLine,
|
||||||
ShippingInventoryVerification,
|
ShippingOnhandVerification,
|
||||||
ShippingInventoryVerificationLine,
|
ShippingOnhandVerificationLine,
|
||||||
ShippingReservation,
|
ShippingReservation,
|
||||||
ShippingUploadAttempt,
|
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_line_decision import ShippingOrderReviewLineDecision
|
||||||
from app.models.shipping_order_review_wave_line import ShippingOrderReviewWaveLine
|
from app.models.shipping_order_review_wave_line import ShippingOrderReviewWaveLine
|
||||||
from app.models.shipping_order_review_wave_idempotency import ShippingOrderReviewWaveIdempotency
|
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_review_suggestion import ShippingOrderReviewSuggestion
|
||||||
from app.models.shipping_order_extraction_run import (
|
from app.models.shipping_order_extraction_run import (
|
||||||
ShippingOrderExtractionDiagnosticAudit,
|
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_eml_preview_snapshot import ShippingEmlPreviewSnapshot
|
||||||
from app.models.shipping_xfa_structure_analysis import ShippingXfaStructureAnalysis
|
from app.models.shipping_xfa_structure_analysis import ShippingXfaStructureAnalysis
|
||||||
from app.models.shipping_xfa_audit_snapshot import ShippingXfaAuditSnapshot
|
from app.models.shipping_xfa_audit_snapshot import ShippingXfaAuditSnapshot
|
||||||
from app.models.shipping_inventory_config import (
|
from app.models.freight_rpa_config import (
|
||||||
ShippingInventoryField,
|
FreightRpaOnhandField,
|
||||||
ShippingInventoryExternalMapping,
|
FreightRpaOnhandExternalMapping,
|
||||||
ShippingInventoryConfigurationTestRun,
|
FreightRpaOnhandConfigurationTestRun,
|
||||||
ShippingInventoryValidationBatch,
|
FreightRpaOnhandValidationBatch,
|
||||||
ShippingInventorySourceParsingBindingAudit,
|
FreightRpaSourceParsingBindingAudit,
|
||||||
ShippingInventoryParsingProfile,
|
FreightRpaParsingProfile,
|
||||||
ShippingInventoryRoutingRule,
|
FreightRpaOnhandRoutingRule,
|
||||||
ShippingInventoryRoutingRuleCondition,
|
FreightRpaOnhandRoutingRuleCondition,
|
||||||
ShippingInventoryRoutingRuleVersion,
|
FreightRpaOnhandRoutingRuleVersion,
|
||||||
ShippingInventorySource,
|
FreightRpaSource,
|
||||||
ShippingInventoryStructureAnalysis,
|
FreightRpaOnhandReportConfig,
|
||||||
ShippingRpaProfile,
|
FreightRpaOnhandStructureAnalysis,
|
||||||
|
FreightRpaProfile,
|
||||||
)
|
)
|
||||||
from app.models.shipping_receipt_report import (
|
from app.models.freight_rpa_inbound_report import (
|
||||||
ShippingReceiptNotificationDelivery,
|
FreightRpaInboundReportConfig,
|
||||||
ShippingReceiptReportConfig,
|
FreightRpaInboundReportFile,
|
||||||
ShippingReceiptReportFile,
|
FreightRpaInboundUnitRun,
|
||||||
ShippingReceiptRpaUnitRun,
|
|
||||||
)
|
)
|
||||||
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 (
|
from app.models.shipping_customer import (
|
||||||
ShippingBusinessSequence,
|
ShippingBusinessSequence,
|
||||||
ShippingCustomer,
|
ShippingCustomer,
|
||||||
@@ -180,18 +186,18 @@ from app.models.shipping_identity_rule import (
|
|||||||
ShippingIdentityRuleAuditEvent,
|
ShippingIdentityRuleAuditEvent,
|
||||||
ShippingIdentityRuleSet,
|
ShippingIdentityRuleSet,
|
||||||
)
|
)
|
||||||
from app.models.shipping_inventory_candidates import (
|
from app.models.shipping_onhand_candidates import (
|
||||||
ShippingInventoryCandidateLine,
|
ShippingOnhandCandidateLine,
|
||||||
ShippingInventoryCandidateSet,
|
ShippingOnhandCandidateSet,
|
||||||
ShippingInventoryCandidateSource,
|
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_process_recovery_plan import ShippingProcessRecoveryPlan
|
||||||
from app.models.shipping_inventory_preparation import (
|
from app.models.shipping_onhand_preparation import (
|
||||||
ShippingInventoryPreparationAttempt,
|
ShippingOnhandPreparationAttempt,
|
||||||
ShippingInventoryPreparationSourceAttempt,
|
ShippingOnhandPreparationSourceAttempt,
|
||||||
)
|
)
|
||||||
from app.models.shipping_inventory_mapping import ShippingInventoryMapping
|
from app.models.freight_rpa_onhand_mapping import FreightRpaOnhandMapping
|
||||||
from app.models.training import (
|
from app.models.training import (
|
||||||
LeanTrainingCompletion,
|
LeanTrainingCompletion,
|
||||||
LeanTrainingReminder,
|
LeanTrainingReminder,
|
||||||
@@ -208,8 +214,10 @@ from app.models.in_transit_transfer import (
|
|||||||
TransferDocument,
|
TransferDocument,
|
||||||
TransferInvoiceItem,
|
TransferInvoiceItem,
|
||||||
TransferMatching,
|
TransferMatching,
|
||||||
|
TransferMovementLedger,
|
||||||
TransferRun,
|
TransferRun,
|
||||||
TransferSourceJob,
|
TransferSourceJob,
|
||||||
|
TransferTypeConfig,
|
||||||
)
|
)
|
||||||
from app.models.integration_connector import (
|
from app.models.integration_connector import (
|
||||||
IntegrationBinding,
|
IntegrationBinding,
|
||||||
@@ -317,7 +325,7 @@ __all__ = [
|
|||||||
'ShippingOrderReviewLineDecision',
|
'ShippingOrderReviewLineDecision',
|
||||||
'ShippingOrderReviewWaveLine',
|
'ShippingOrderReviewWaveLine',
|
||||||
'ShippingOrderReviewWaveIdempotency',
|
'ShippingOrderReviewWaveIdempotency',
|
||||||
'ShippingNoticeLineInventoryMatch',
|
'ShippingNoticeLineOnhandMatch',
|
||||||
'ShippingOrderReviewSuggestion',
|
'ShippingOrderReviewSuggestion',
|
||||||
'ShippingOrderProcessingRun',
|
'ShippingOrderProcessingRun',
|
||||||
'ShippingOrderProcessingRunIntake',
|
'ShippingOrderProcessingRunIntake',
|
||||||
@@ -366,30 +374,33 @@ __all__ = [
|
|||||||
'ShippingIdentityRuleAuditEvent',
|
'ShippingIdentityRuleAuditEvent',
|
||||||
'ShippingTaskEvent',
|
'ShippingTaskEvent',
|
||||||
'ShippingTaskPurgeAudit',
|
'ShippingTaskPurgeAudit',
|
||||||
'ShippingInventoryFile',
|
'FreightRpaOnhandReportFile',
|
||||||
'ShippingTaskInventoryLink',
|
'ShippingTaskOnhandLink',
|
||||||
'ShippingRpaProfile',
|
'FreightRpaProfile',
|
||||||
'ShippingInventorySource',
|
'FreightRpaSource',
|
||||||
'ShippingReceiptReportConfig',
|
'FreightRpaOnhandReportConfig',
|
||||||
'ShippingReceiptRpaUnitRun',
|
'FreightRpaInboundReportConfig',
|
||||||
'ShippingReceiptReportFile',
|
'FreightRpaInboundUnitRun',
|
||||||
'ShippingReceiptNotificationDelivery',
|
'FreightRpaInboundReportFile',
|
||||||
'ShippingInventoryField',
|
'FreightRpaOutboundReportConfig',
|
||||||
'ShippingInventoryStructureAnalysis',
|
'FreightRpaOutboundUnitRun',
|
||||||
'ShippingInventoryRoutingRule',
|
'FreightRpaOutboundReportFile',
|
||||||
'ShippingInventoryRoutingRuleCondition',
|
'FreightRpaOnhandField',
|
||||||
'ShippingInventoryRoutingRuleVersion',
|
'FreightRpaOnhandStructureAnalysis',
|
||||||
'ShippingInventoryExternalMapping',
|
'FreightRpaOnhandRoutingRule',
|
||||||
'ShippingInventoryConfigurationTestRun',
|
'FreightRpaOnhandRoutingRuleCondition',
|
||||||
'ShippingInventoryValidationBatch',
|
'FreightRpaOnhandRoutingRuleVersion',
|
||||||
'ShippingInventorySourceParsingBindingAudit',
|
'FreightRpaOnhandExternalMapping',
|
||||||
'ShippingInventoryParsingProfile',
|
'FreightRpaOnhandConfigurationTestRun',
|
||||||
'ShippingTemporaryInventorySession',
|
'FreightRpaOnhandValidationBatch',
|
||||||
|
'FreightRpaSourceParsingBindingAudit',
|
||||||
|
'FreightRpaParsingProfile',
|
||||||
|
'ShippingTemporaryOnhandSession',
|
||||||
'ShippingExcelTemplate',
|
'ShippingExcelTemplate',
|
||||||
'ShippingExportArtifact',
|
'ShippingExportArtifact',
|
||||||
'ShippingReservation',
|
'ShippingReservation',
|
||||||
'ShippingInventoryVerification',
|
'ShippingOnhandVerification',
|
||||||
'ShippingInventoryVerificationLine',
|
'ShippingOnhandVerificationLine',
|
||||||
'ShippingExportArtifactLine',
|
'ShippingExportArtifactLine',
|
||||||
'ShippingUploadAttempt',
|
'ShippingUploadAttempt',
|
||||||
'ShippingProcessExecution',
|
'ShippingProcessExecution',
|
||||||
@@ -424,10 +435,10 @@ __all__ = [
|
|||||||
'MaintenanceDevice',
|
'MaintenanceDevice',
|
||||||
'MaintenanceRecord',
|
'MaintenanceRecord',
|
||||||
'MaintenanceAuditLog',
|
'MaintenanceAuditLog',
|
||||||
'ShippingInventoryCandidateSet',
|
'ShippingOnhandCandidateSet',
|
||||||
'ShippingInventoryCandidateSource',
|
'ShippingOnhandCandidateSource',
|
||||||
'ShippingInventoryCandidateLine',
|
'ShippingOnhandCandidateLine',
|
||||||
'ShippingTaskInventoryRpaAttempt',
|
'FreightRpaOnhandTaskAttempt',
|
||||||
'VoucherCheckProfile',
|
'VoucherCheckProfile',
|
||||||
'VoucherCheckRun',
|
'VoucherCheckRun',
|
||||||
'VoucherCheckSubject',
|
'VoucherCheckSubject',
|
||||||
@@ -456,6 +467,8 @@ __all__ = [
|
|||||||
'TransferAttempt',
|
'TransferAttempt',
|
||||||
'TransferAuditEvent',
|
'TransferAuditEvent',
|
||||||
'TransferArchive',
|
'TransferArchive',
|
||||||
|
'TransferTypeConfig',
|
||||||
|
'TransferMovementLedger',
|
||||||
'IntegrationCredentialReference',
|
'IntegrationCredentialReference',
|
||||||
'IntegrationClientInstance',
|
'IntegrationClientInstance',
|
||||||
'IntegrationInterfaceDefinition',
|
'IntegrationInterfaceDefinition',
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ class QuickQuestion(Base):
|
|||||||
常用问题表
|
常用问题表
|
||||||
用途:存储全局/用户常用问题;全局条目(user_id 为空)可配置标准答案并启用 FAQ 缓存命中。
|
用途:存储全局/用户常用问题;全局条目(user_id 为空)可配置标准答案并启用 FAQ 缓存命中。
|
||||||
is_enabled 控制工作台首页快捷入口;cache_enabled 控制聊天是否跳过 Dify 直答,二者独立。
|
is_enabled 控制工作台首页快捷入口;cache_enabled 控制聊天是否跳过 Dify 直答,二者独立。
|
||||||
|
fuzzy_enabled / fuzzy_threshold 控制精确未命中后的模糊兜底直答(逐条目独立,阈值钳制在 0.5~1.0)。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__tablename__ = 'quick_questions'
|
__tablename__ = 'quick_questions'
|
||||||
@@ -48,6 +49,8 @@ class QuickQuestion(Base):
|
|||||||
aliases: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
aliases: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||||
cache_enabled: Mapped[bool] = mapped_column(default=False)
|
cache_enabled: Mapped[bool] = mapped_column(default=False)
|
||||||
is_enabled: Mapped[bool] = mapped_column(default=True)
|
is_enabled: Mapped[bool] = mapped_column(default=True)
|
||||||
|
fuzzy_enabled: Mapped[bool] = mapped_column(default=False)
|
||||||
|
fuzzy_threshold: Mapped[float] = mapped_column(default=0.80)
|
||||||
hit_count: Mapped[int] = mapped_column(default=0)
|
hit_count: Mapped[int] = mapped_column(default=0)
|
||||||
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||||
source_kb_document_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
source_kb_document_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||||
|
|||||||
+142
-92
@@ -1,9 +1,11 @@
|
|||||||
"""
|
"""
|
||||||
models/shipping_inventory_config.py
|
backend/app/models/freight_rpa_config.py
|
||||||
|
|
||||||
用途:定义货代库存源、RPA Profile、通用路由规则及外部系统仓库映射主数据。
|
用途:定义货代库存源、RPA Profile、在手/入站/出站报表配置、通用路由规则及外部系统仓库映射主数据。
|
||||||
依赖:models.base.Base、SQLAlchemy ORM;凭据密文由 shipping_notice.credential_crypto 读写。
|
依赖:models.base.Base、SQLAlchemy ORM;凭据密文由 freight_rpa.common.credential_crypto 读写。
|
||||||
逻辑:库存运行链路以 ShippingInventorySource.source_code 为业务主键;RPA Profile 仅提供登录连接配置,
|
逻辑:库存运行链路以 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
|
from app.models.base import Base
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryField(Base):
|
class FreightRpaOnhandField(Base):
|
||||||
"""用户维护的库存业务字段目录;程序仅依据字段 ID 和业务用途运行。"""
|
"""用户维护的库存业务字段目录;程序仅依据字段 ID 和业务用途运行。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_fields'
|
__tablename__ = 'freight_rpa_onhand_fields'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint('field_code', name='uq_shipping_inventory_fields_code'),
|
UniqueConstraint('field_code', name='uq_freight_rpa_onhand_fields_code'),
|
||||||
UniqueConstraint('display_name', name='uq_shipping_inventory_fields_display_name'),
|
UniqueConstraint('display_name', name='uq_freight_rpa_onhand_fields_display_name'),
|
||||||
CheckConstraint("status IN ('active', 'retired')", name='ck_shipping_inventory_fields_status'),
|
CheckConstraint("status IN ('active', 'retired')", name='ck_freight_rpa_onhand_fields_status'),
|
||||||
CheckConstraint("value_type IN ('text', 'integer', 'decimal', 'date')", name='ck_shipping_inventory_fields_value_type'),
|
CheckConstraint("value_type IN ('text', 'integer', 'decimal', 'date')", name='ck_freight_rpa_onhand_fields_value_type'),
|
||||||
CheckConstraint(
|
CheckConstraint(
|
||||||
"usage_type IN ('match_identity', 'inventory_quantity', 'warehouse_identity', 'general')",
|
"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)
|
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__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint('profile_code', name='uq_shipping_rpa_profiles_profile_code'),
|
UniqueConstraint('profile_code', name='uq_freight_rpa_profiles_profile_code'),
|
||||||
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_shipping_rpa_profiles_connector_type'),
|
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_freight_rpa_profiles_connector_type'),
|
||||||
)
|
)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
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)
|
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)
|
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。"""
|
"""库存业务来源;固定仓或库存行动态解析 Warehouse。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_sources'
|
__tablename__ = 'freight_rpa_sources'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint('source_code', name='uq_shipping_inventory_sources_source_code'),
|
UniqueConstraint('source_code', name='uq_freight_rpa_sources_source_code'),
|
||||||
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_shipping_inventory_sources_connector_type'),
|
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_freight_rpa_sources_connector_type'),
|
||||||
CheckConstraint(
|
CheckConstraint(
|
||||||
"(warehouse_resolution_mode = 'fixed' AND fixed_warehouse_id IS NOT NULL) "
|
"(warehouse_resolution_mode = 'fixed' AND fixed_warehouse_id IS NOT NULL) "
|
||||||
"OR (warehouse_resolution_mode = 'inventory_match' AND fixed_warehouse_id IS 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(
|
CheckConstraint(
|
||||||
"enabled = false OR (parsing_profile_id IS NOT NULL AND excel_template_id IS NOT NULL)",
|
"enabled = false OR excel_template_id IS NOT NULL",
|
||||||
name='ck_shipping_inventory_sources_enabled_bindings',
|
name='ck_freight_rpa_sources_enabled_template',
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -106,14 +108,12 @@ class ShippingInventorySource(Base):
|
|||||||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
connector_type: Mapped[str] = mapped_column(String(32), 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)
|
rpa_profile_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_profiles.id'), nullable=False, index=True)
|
||||||
parsing_profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True)
|
|
||||||
excel_template_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=True, index=True)
|
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)
|
warehouse_resolution_mode: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||||
fixed_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
fixed_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
# 业务报表定义属于 Source;Driver 的 selector、等待与下载实现不进入数据库配置。
|
# 业务报表定义自 s18 起搬到 FreightRpaOnhandReportConfig(路径、查询条件、解析方案绑定);
|
||||||
report_path_json: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict, server_default=text("'{}'"), nullable=False)
|
# CHECK 不能跨表,模板绑定仍留在站点行的启用约束上,解析方案存在性由保存站点的服务校验。
|
||||||
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, default=list, server_default=text("'[]'"), nullable=False)
|
|
||||||
snapshot_ttl_seconds: Mapped[int] = mapped_column(Integer, default=86400, server_default=text('86400'), nullable=False)
|
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)
|
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)
|
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)
|
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)
|
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
rpa_profile: Mapped[ShippingRpaProfile] = relationship(back_populates='sources')
|
rpa_profile: Mapped[FreightRpaProfile] = relationship(back_populates='sources')
|
||||||
parsing_profile: Mapped[Optional['ShippingInventoryParsingProfile']] = relationship(back_populates='sources')
|
|
||||||
excel_template: Mapped[Optional['ShippingExcelTemplate']] = relationship(back_populates='sources')
|
excel_template: Mapped[Optional['ShippingExcelTemplate']] = relationship(back_populates='sources')
|
||||||
external_mappings: Mapped[list['ShippingInventoryExternalMapping']] = relationship(
|
onhand_report_config: Mapped[Optional['FreightRpaOnhandReportConfig']] = relationship(
|
||||||
back_populates='inventory_source', cascade='all, delete-orphan'
|
back_populates='source', uselist=False, cascade='all, delete-orphan',
|
||||||
)
|
)
|
||||||
receipt_report_config: Mapped[Optional['ShippingReceiptReportConfig']] = relationship(
|
external_mappings: Mapped[list['FreightRpaOnhandExternalMapping']] = relationship(
|
||||||
back_populates='inventory_source', uselist=False, cascade='all, delete-orphan',
|
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__ = (
|
__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)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False)
|
# 站点删除时配置行级联删除(与迁移端 fk_freight_rpa_onhand_report_configs_source 的 ondelete 一致)。
|
||||||
previous_parsing_profile_id: Mapped[Optional[int]] = mapped_column(
|
source_id: Mapped[int] = mapped_column(
|
||||||
ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True,
|
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)
|
operation: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||||
reason: Mapped[str] = mapped_column(String(500), nullable=False)
|
reason: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||||
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
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)
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryParsingProfile(Base):
|
class FreightRpaParsingProfile(Base):
|
||||||
"""可跨源复用的通用文件解析规则(库存/异动按 purpose 区分)。
|
"""可跨源复用的通用文件解析规则(在手/入站/出站按 purpose 区分)。
|
||||||
|
|
||||||
注意:表名中的 inventory 是历史命名——本表实为"通用文件解析规则表",
|
表 freight_rpa_parsing_profiles 按 purpose 服务在手/入站/出站。
|
||||||
用途以 purpose 字段为准,勿按表名推断只服务库存。
|
purpose='onhand':在手库存文件,端点用 FreightRpaOnhandField 库存字段目录;
|
||||||
purpose='inventory':端点用 ShippingInventoryField 库存字段目录(既有语义);
|
purpose='inbound':入站文件,端点用定死领域字段
|
||||||
purpose='movement':端点用定死领域字段(MOVEMENT_FIELDS,doc_no/line_no/.../movement_date),
|
(MOVEMENT_FIELDS,doc_no/line_no/.../movement_date),
|
||||||
供收料/异动文件映射,不依赖库存字段目录。校验逻辑按 purpose 分支。
|
不依赖库存字段目录。校验逻辑按 purpose 分支。
|
||||||
绑定入口:库存站点 ShippingInventorySource.parsing_profile_id /
|
绑定入口:在手配置 FreightRpaOnhandReportConfig.parsing_profile_id /
|
||||||
收料配置 ShippingReceiptReportConfig.parsing_profile_id(后者必须 purpose='movement')。
|
入站配置 FreightRpaInboundReportConfig.parsing_profile_id(后者必须 purpose='inbound');
|
||||||
|
purpose='outbound':出站文件,结构就位(白名单放行,暂无运行时消费方)。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_parsing_profiles'
|
__tablename__ = 'freight_rpa_parsing_profiles'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint('profile_code', 'version', name='uq_inventory_parsing_profiles_code_version'),
|
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_exact_fp', 'exact_structure_fingerprint'),
|
||||||
Index('ix_inv_parse_profile_compat_fp', 'compatibility_fingerprint'),
|
Index('ix_inv_parse_profile_compat_fp', 'compatibility_fingerprint'),
|
||||||
CheckConstraint(
|
CheckConstraint(
|
||||||
"purpose IN ('inventory', 'movement')",
|
"purpose IN ('onhand', 'inbound', 'outbound')",
|
||||||
name='ck_shipping_inventory_parsing_profiles_purpose',
|
name='ck_freight_rpa_parsing_profiles_purpose',
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
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)
|
profile_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
display_name: Mapped[str] = mapped_column(String(128), 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'))
|
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)
|
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.
|
# Draft and published definitions keep their analysed sample evidence without retaining the full uploaded workbook.
|
||||||
sample_analysis_id: Mapped[Optional[int]] = mapped_column(
|
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.
|
# Preserve every confirmed evidence switch so a draft remains explainable after samples change.
|
||||||
sample_evidence_history_json: Mapped[list[dict[str, Any]]] = mapped_column(
|
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)
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
|
||||||
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='parsing_profile')
|
# s18 起站点行不再绑定解析方案;在手配置行(FreightRpaOnhandReportConfig)是 onhand 侧的唯一挂点。
|
||||||
sample_analysis: Mapped[Optional['ShippingInventoryStructureAnalysis']] = relationship(
|
sources: Mapped[list['FreightRpaOnhandReportConfig']] = relationship(back_populates='parsing_profile')
|
||||||
|
sample_analysis: Mapped[Optional['FreightRpaOnhandStructureAnalysis']] = relationship(
|
||||||
foreign_keys=[sample_analysis_id],
|
foreign_keys=[sample_analysis_id],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryStructureAnalysis(Base):
|
class FreightRpaOnhandStructureAnalysis(Base):
|
||||||
"""库存文件结构分析记录;保存脱敏结构证据,不承载正式库存快照。"""
|
"""库存文件结构分析记录;保存脱敏结构证据,不承载正式库存快照。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_structure_analyses'
|
__tablename__ = 'freight_rpa_onhand_structure_analyses'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
Index('ix_inv_structure_analysis_file_hash', 'file_checksum'),
|
Index('ix_inv_structure_analysis_file_hash', 'file_checksum'),
|
||||||
Index('ix_inv_structure_analysis_created', 'created_at'),
|
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)
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryConfigurationTestRun(Base):
|
class FreightRpaOnhandConfigurationTestRun(Base):
|
||||||
"""库存站点配置测试的异步 RPA 运行;锁定站点和连接配置版本且不进入生产库存池。"""
|
"""库存站点配置测试的异步 RPA 运行;锁定站点和连接配置版本且不进入生产库存池。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_configuration_test_runs'
|
__tablename__ = 'freight_rpa_onhand_configuration_test_runs'
|
||||||
__table_args__ = (UniqueConstraint('run_no', name='uq_inventory_configuration_test_runs_run_no'),)
|
__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)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
validation_batch_id: Mapped[Optional[int]] = mapped_column(
|
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)
|
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)
|
source_config_version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
rpa_profile_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')
|
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')
|
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)
|
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), 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)
|
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryValidationBatch(Base):
|
class FreightRpaOnhandValidationBatch(Base):
|
||||||
"""库存站点批量验证的聚合运行;逐站点结果仍由 ConfigurationTestRun 保存。"""
|
"""库存站点批量验证的聚合运行;逐站点结果仍由 ConfigurationTestRun 保存。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_validation_batches'
|
__tablename__ = 'freight_rpa_onhand_validation_batches'
|
||||||
__table_args__ = (UniqueConstraint('batch_no', name='uq_inventory_validation_batches_batch_no'),)
|
__table_args__ = (UniqueConstraint('batch_no', name='uq_inventory_validation_batches_batch_no'),)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
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'))
|
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)
|
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||||
retry_of_batch_id: Mapped[Optional[int]] = mapped_column(
|
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)
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryRoutingRule(Base):
|
class FreightRpaOnhandRoutingRule(Base):
|
||||||
"""可版本化的库存源路由决策表;仅产出受控 Source 候选。"""
|
"""可版本化的库存源路由决策表;仅产出受控 Source 候选。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_routing_rules'
|
__tablename__ = 'freight_rpa_onhand_routing_rules'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint('rule_code', 'version', name='uq_shipping_inventory_routing_rules_code_version'),
|
UniqueConstraint('rule_code', 'version', name='uq_freight_rpa_onhand_routing_rules_code_version'),
|
||||||
CheckConstraint("scope IN ('task', 'line')", name='ck_shipping_inventory_routing_rules_scope'),
|
CheckConstraint("scope IN ('task', 'line')", name='ck_freight_rpa_onhand_routing_rules_scope'),
|
||||||
CheckConstraint("match_mode IN ('all', 'any')", name='ck_shipping_inventory_routing_rules_match_mode'),
|
CheckConstraint("match_mode IN ('all', 'any')", name='ck_freight_rpa_onhand_routing_rules_match_mode'),
|
||||||
CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_inventory_routing_rules_status'),
|
CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_freight_rpa_onhand_routing_rules_status'),
|
||||||
)
|
)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
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)
|
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)
|
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
conditions: Mapped[list['ShippingInventoryRoutingRuleCondition']] = relationship(
|
conditions: Mapped[list['FreightRpaOnhandRoutingRuleCondition']] = relationship(
|
||||||
back_populates='rule', cascade='all, delete-orphan', order_by='ShippingInventoryRoutingRuleCondition.sequence'
|
back_populates='rule', cascade='all, delete-orphan', order_by='FreightRpaOnhandRoutingRuleCondition.sequence'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryRoutingRuleCondition(Base):
|
class FreightRpaOnhandRoutingRuleCondition(Base):
|
||||||
"""库存源路由条件;仅引用已发布订单 Schema 的稳定 field_id。"""
|
"""库存源路由条件;仅引用已发布订单 Schema 的稳定 field_id。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_routing_rule_conditions'
|
__tablename__ = 'freight_rpa_onhand_routing_rule_conditions'
|
||||||
__table_args__ = (
|
__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(
|
CheckConstraint(
|
||||||
"source_kind = 'order_field' AND order_field_id IS NOT NULL",
|
"source_kind = 'order_field' AND order_field_id IS NOT NULL",
|
||||||
name='ck_inventory_routing_condition_source',
|
name='ck_inventory_routing_condition_source',
|
||||||
@@ -336,7 +386,7 @@ class ShippingInventoryRoutingRuleCondition(Base):
|
|||||||
)
|
)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
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)
|
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')
|
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)
|
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)
|
expected_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
|
||||||
sequence: Mapped[int] = mapped_column(Integer, nullable=False)
|
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'
|
__tablename__ = 'freight_rpa_onhand_routing_rule_versions'
|
||||||
__table_args__ = (UniqueConstraint('rule_id', 'version', name='uq_shipping_inventory_routing_rule_versions_rule_version'),)
|
__table_args__ = (UniqueConstraint('rule_id', 'version', name='uq_freight_rpa_onhand_routing_rule_versions_rule_version'),)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
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)
|
version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, 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_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||||
published_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
published_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryExternalMapping(Base):
|
class FreightRpaOnhandExternalMapping(Base):
|
||||||
"""库存源到外部系统仓库的映射。
|
"""库存源到外部系统仓库的映射。
|
||||||
|
|
||||||
freight_warehouse_id(货代仓库)为可选维度:inventory_match 源用它匹配收料文件
|
freight_warehouse_id(货代仓库)为可选维度:inventory_match 源用它匹配收料文件
|
||||||
@@ -371,18 +421,18 @@ class ShippingInventoryExternalMapping(Base):
|
|||||||
(in_transit_transfer DefaultRouteResolver),保存端必填,库内空串仅为存量行兼容。
|
(in_transit_transfer DefaultRouteResolver),保存端必填,库内空串仅为存量行兼容。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_external_mappings'
|
__tablename__ = 'freight_rpa_onhand_external_mappings'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
Index(
|
Index(
|
||||||
'uq_shipping_inv_ext_map_src_default_enabled',
|
'uq_shipping_inv_ext_map_src_default_enabled',
|
||||||
'inventory_source_id',
|
'source_id',
|
||||||
unique=True,
|
unique=True,
|
||||||
postgresql_where=text('freight_warehouse_id IS NULL AND enabled = true'),
|
postgresql_where=text('freight_warehouse_id IS NULL AND enabled = true'),
|
||||||
sqlite_where=text('freight_warehouse_id IS NULL AND enabled = 1'),
|
sqlite_where=text('freight_warehouse_id IS NULL AND enabled = 1'),
|
||||||
),
|
),
|
||||||
Index(
|
Index(
|
||||||
'uq_shipping_inv_ext_map_src_wh_enabled',
|
'uq_shipping_inv_ext_map_src_wh_enabled',
|
||||||
'inventory_source_id',
|
'source_id',
|
||||||
'freight_warehouse_id',
|
'freight_warehouse_id',
|
||||||
unique=True,
|
unique=True,
|
||||||
postgresql_where=text('freight_warehouse_id IS NOT NULL AND enabled = 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)
|
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)
|
freight_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
external_system_code: Mapped[str] = mapped_column(String(32), nullable=False)
|
external_system_code: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||||
external_organization_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
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)
|
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)
|
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')
|
||||||
@@ -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')
|
||||||
+9
-9
@@ -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 精确引用。
|
逻辑:每次确认/重跑创建新版本,匹配 Attempt 通过 mapping_id 精确引用。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -17,24 +17,24 @@ from sqlalchemy.orm import Mapped, mapped_column
|
|||||||
from app.models.base import Base
|
from app.models.base import Base
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryMapping(Base):
|
class FreightRpaOnhandMapping(Base):
|
||||||
"""库存文件的不可变字段映射版本。"""
|
"""库存文件的不可变字段映射版本。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_mappings'
|
__tablename__ = 'freight_rpa_onhand_mappings'
|
||||||
__table_args__ = (
|
__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'),
|
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)
|
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)
|
version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active')
|
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)
|
mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||||
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
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)
|
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||||
operation_id: Mapped[Optional[str]] = mapped_column(String(128), 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)
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
@@ -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',
|
||||||
|
)
|
||||||
+4
-4
@@ -1,5 +1,5 @@
|
|||||||
"""
|
"""
|
||||||
models/shipping_task_inventory_rpa_attempts.py
|
backend/app/models/freight_rpa_onhand_task_attempts.py
|
||||||
|
|
||||||
用途:逐库存源的 RPA 导出 Attempt 结构化记录(决策 D1/D2 三元组幂等)。
|
用途:逐库存源的 RPA 导出 Attempt 结构化记录(决策 D1/D2 三元组幂等)。
|
||||||
依赖:Base、ShippingNotice(task_no FK 可选直连 id 先保留 task_no 字符串关联)、users。
|
依赖: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 记录。"""
|
"""逐 (task_no, source_code) 的库存 RPA 导出 Attempt 记录。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_task_inventory_rpa_attempts'
|
__tablename__ = 'freight_rpa_onhand_task_rpa_attempts'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
# 三元组唯一:同一运行号同一源只允许一条记录
|
# 三元组唯一:同一运行号同一源只允许一条记录
|
||||||
UniqueConstraint('task_no', 'source_code', 'source_run_no', name='uq_shipping_task_inv_rpa_triplet'),
|
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)
|
trigger_file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
|
||||||
callback_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_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
@@ -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')
|
||||||
@@ -1,13 +1,22 @@
|
|||||||
"""models/in_transit_transfer.py
|
"""models/in_transit_transfer.py
|
||||||
|
|
||||||
用途:在途仓自动调拨一期核心领域模型:Run、SourceJob、Matching、InvoiceItem、
|
用途:在途仓自动调拨一期核心领域模型:Run、SourceJob、Matching、InvoiceItem、
|
||||||
Document(ERP 调拨单)、Attempt、AuditEvent 与 Archive。
|
Document(ERP 调拨单)、Attempt、AuditEvent 与 Archive;另含调拨类型
|
||||||
依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁)。
|
配置表 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)唯一防止重复建单;
|
逻辑:Run 是异步真相源;InvoiceItem 按(matching_id, invoice_no)唯一防止重复建单;
|
||||||
Document(单)实现「五元组一组一单」,同组未完结单唯一由部分唯一索引在
|
Document(单)实现「五元组一组一单」,同组未完结单唯一由部分唯一索引在
|
||||||
DB 层强制(D15 防双单兜底);单:Attempt=1:N,外键在 Attempt 侧(D14);
|
DB 层强制(D15 防双单兜底);单:Attempt=1:N,外键在 Attempt 侧(D14);
|
||||||
Attempt 保留每次恢复/重查/执行事实,旧 Attempt 永不覆盖;
|
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
|
from __future__ import annotations
|
||||||
@@ -34,20 +43,16 @@ from app.core.errors import ValidationError
|
|||||||
from app.models.base import Base
|
from app.models.base import Base
|
||||||
|
|
||||||
# 与 services/in_transit_transfer/status.py 保持一致的冻结枚举(数据库级兜底)。
|
# 与 services/in_transit_transfer/status.py 保持一致的冻结枚举(数据库级兜底)。
|
||||||
|
# 【not_matured 已退役 2026-10-16】成熟概念删除,存量行经 tt16 重映射 cancelled。
|
||||||
TRANSFER_ITEM_STATUSES = (
|
TRANSFER_ITEM_STATUSES = (
|
||||||
'file_pending', 'file_ready', 'matching', 'ready_to_execute', 'executing',
|
'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',
|
'result_unknown', 'manually_closed', 'cancelled', 'notification_failed',
|
||||||
)
|
)
|
||||||
TRANSFER_RUN_STATUSES = (
|
TRANSFER_RUN_STATUSES = (
|
||||||
'queued', 'preparing_files', 'matching', 'ready_to_execute', 'executing',
|
'queued', 'preparing_files', 'matching', 'ready_to_execute', 'executing',
|
||||||
'success', 'partial_failed', 'failed', 'cancelled',
|
'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 = (
|
TRANSFER_SOURCE_JOB_STATUSES = (
|
||||||
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
|
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
|
||||||
'matching', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
|
'matching', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
|
||||||
@@ -98,10 +103,6 @@ class TransferRun(Base):
|
|||||||
"trigger_type IN ('manual', 'schedule')",
|
"trigger_type IN ('manual', 'schedule')",
|
||||||
name='ck_transfer_runs_trigger_type',
|
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_status_created', 'status', 'created_at'),
|
||||||
Index('ix_transfer_runs_business_date', 'business_date'),
|
Index('ix_transfer_runs_business_date', 'business_date'),
|
||||||
)
|
)
|
||||||
@@ -109,9 +110,11 @@ class TransferRun(Base):
|
|||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
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')
|
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(
|
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)
|
business_date: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
||||||
@@ -215,15 +218,18 @@ class TransferMatching(Base):
|
|||||||
|
|
||||||
|
|
||||||
class TransferInvoiceItem(Base):
|
class TransferInvoiceItem(Base):
|
||||||
"""匹配明细项;同一匹配内 (来源,Invoice,料号,收料日期) 唯一,保留原始行追溯。
|
"""匹配明细项;同一匹配内 (来源,Invoice,料号,异动日期) 唯一,保留原始行追溯。
|
||||||
|
|
||||||
Invoice 锚定批号(2026-09-21 业务口径):同一批号跨料号/跨日期拆分为多行。
|
Invoice 锚定批号(2026-09-21 业务口径):同一批号跨料号/跨日期拆分为多行。
|
||||||
|
【2026-10-14 出生翻转(ADR 0001/D4)】行不再由文件落地写入,而是匹配创建时
|
||||||
|
从库存异动档圈定生成:ledger_record_id 指向档记录(业务字段=档原值),
|
||||||
|
matching_id 创建即绑定(D17:一条档记录一生只生成一次 items 绑定)。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__tablename__ = 'transfer_invoice_items'
|
__tablename__ = 'transfer_invoice_items'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint(
|
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',
|
name='uq_transfer_invoice_items_matching_grain',
|
||||||
),
|
),
|
||||||
CheckConstraint(
|
CheckConstraint(
|
||||||
@@ -236,32 +242,40 @@ class TransferInvoiceItem(Base):
|
|||||||
# 单据级执行(T10)高频「按单查行」:document_id 单列索引(控制器裁决,
|
# 单据级执行(T10)高频「按单查行」:document_id 单列索引(控制器裁决,
|
||||||
# 并入 tt0d1e2f3a4b 避免额外迁移节点)。
|
# 并入 tt0d1e2f3a4b 避免额外迁移节点)。
|
||||||
Index('ix_transfer_invoice_items_document_id', 'document_id'),
|
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)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
# 行归属解耦后 matching_id 仅留痕(首次创建值);落地证据同步行尚无匹配归属
|
# 【2026-10-14 出生翻转】matching_id 回归「创建即绑定」:行由匹配创建时从档
|
||||||
# (2026-09-25),放开非空。uq_transfer_invoice_items_matching_grain 含本列,
|
# 圈定生成(落地不再写 items,见 evidence_sync/ADR 0001),新行恒非空
|
||||||
# NULL 行不受该唯一约束保护——同步的幂等去重由 evidence_sync 应用层按
|
# (模型层不强制 NOT NULL,存量兼容,服务层保证);D17 圈档互斥的占用判定
|
||||||
# (source, invoice, material, receipt_date) 四元组负责(见 evidence_sync)。
|
# 以本列 + 所属匹配状态为准(取消匹配即释放占用)。
|
||||||
matching_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_matchings.id'), nullable=True, index=True)
|
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)
|
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)
|
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
invoice_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
invoice_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
# 批号(External ASN 等)原值;「拨入批号」展示由 WTP→HOW 转换派生,不落库。
|
# 批号(External ASN 等)原值;「拨入批号」展示由 WTP→HOW 转换派生,不落库。
|
||||||
lot_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
lot_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(拨出库位解析审计)。
|
# 入站文件「仓库」列原值:inventory_match 源映射行匹配键(拨出库位解析审计)。
|
||||||
receipt_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
movement_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
||||||
# 交易单位原值(movement 契约第 11 字段 unit,计划 D4):解析原样保留(仅 trim,
|
# 交易单位原值(movement 契约第 11 字段 unit,计划 D4):解析原样保留(仅 trim,
|
||||||
# 不换算);空值行在匹配阶段落 blocked_missing_unit。unit 不参与匹配 Hash(口径冻结)。
|
# 不换算);空值行在匹配阶段落 blocked_missing_unit。unit 不参与匹配 Hash(口径冻结)。
|
||||||
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, default='', server_default='')
|
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, default='', server_default='')
|
||||||
material_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
material_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
material_name: Mapped[str] = mapped_column(String(200), nullable=False, default='')
|
material_name: Mapped[str] = mapped_column(String(200), nullable=False, default='')
|
||||||
specification: 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)
|
from_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
|
to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
# 数量以 Decimal 文本保存,杜绝浮点误差;比较在服务层完成。
|
# 数量以 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: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||||
# [库存查得时刻] 当前 external_quantity 的 ERP 取数时间戳(stale 徽标判定时钟,
|
# [库存查得时刻] 当前 external_quantity 的 ERP 取数时间戳(stale 徽标判定时钟,
|
||||||
# 2026-09-29 起与行新鲜度 updated_at 分离:证据同步换戳/存续不续期本字段,
|
# 2026-09-29 起与行新鲜度 updated_at 分离:证据同步换戳/存续不续期本字段,
|
||||||
@@ -289,6 +303,12 @@ class TransferInvoiceItem(Base):
|
|||||||
# (document_id 置 NULL)回到 ready_to_execute,可被重新勾选组建新单。
|
# (document_id 置 NULL)回到 ready_to_execute,可被重新勾选组建新单。
|
||||||
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_documents.id'), nullable=True)
|
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_documents.id'), nullable=True)
|
||||||
document: Mapped[Optional['TransferDocument']] = relationship(back_populates='items')
|
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):
|
class TransferDocument(Base):
|
||||||
@@ -320,7 +340,7 @@ class TransferDocument(Base):
|
|||||||
# 建表同语义(部分唯一,非全组唯一)。
|
# 建表同语义(部分唯一,非全组唯一)。
|
||||||
Index(
|
Index(
|
||||||
'uq_transfer_documents_group_live',
|
'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,
|
unique=True,
|
||||||
postgresql_where=text(UNRESOLVED_DOC_STATUS_WHERE),
|
postgresql_where=text(UNRESOLVED_DOC_STATUS_WHERE),
|
||||||
sqlite_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)
|
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True)
|
||||||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
external_org: 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)
|
from_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
|
to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
# 提交标识(D3 终身复用):同组复用单时保持首建值不变;唯一性由
|
# 提交标识(D3 终身复用):同组复用单时保持首建值不变;唯一性由
|
||||||
@@ -476,6 +496,146 @@ class TransferArchive(Base):
|
|||||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
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')
|
@event.listens_for(TransferAuditEvent, 'before_update')
|
||||||
def _reject_transfer_audit_update(_mapper, _connection, _target) -> None:
|
def _reject_transfer_audit_update(_mapper, _connection, _target) -> None:
|
||||||
"""拒绝 ORM 更新,确保审计事件不可改写。"""
|
"""拒绝 ORM 更新,确保审计事件不可改写。"""
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
backend/app/models/job.py
|
backend/app/models/job.py
|
||||||
|
|
||||||
用途:通用后台任务模型,承载跨业务域的异步任务执行状态。
|
用途:通用后台任务模型,承载跨业务域的异步任务执行状态。
|
||||||
依赖:models.base.Base。
|
依赖:models.base.Base;候选集外键指向 shipping_onhand_candidate_sets。
|
||||||
逻辑:由 app.jobs.queue 写入和领取,由 worker 分发到具体业务 handler;业务模型保存业务状态,本表保存执行状态、锁、重试与结果。
|
逻辑:由 app.jobs.queue 写入和领取,由 worker 分发到具体业务 handler;业务模型保存业务状态,本表保存执行状态、锁、重试与结果。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -149,7 +149,7 @@ class Job(Base):
|
|||||||
ForeignKey('shipping_process_gates.id'), nullable=True, index=True,
|
ForeignKey('shipping_process_gates.id'), nullable=True, index=True,
|
||||||
)
|
)
|
||||||
candidate_set_id: Mapped[Optional[int]] = mapped_column(
|
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)
|
fencing_token: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||||
|
|||||||
+12
-105
@@ -1,7 +1,7 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/models/shipping.py
|
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。
|
依赖:models.base.Base;规范订单行见 shipping_task_line;建单前 OT 见 shipping_order_task。
|
||||||
逻辑:co8e9f0a1b2c 已物理 DROP shipping_batches 及全表 batch_id / consumed_batch_id 列;
|
逻辑:co8e9f0a1b2c 已物理 DROP shipping_batches 及全表 batch_id / consumed_batch_id 列;
|
||||||
Intake 消费绑定仅保留 consumed_task_id / consumed_at;upload_batch_id 为上传边界批次(非 shipping_batches);
|
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)
|
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryFile(Base):
|
class ShippingTaskOnhandLink(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):
|
|
||||||
"""发货任务与库存快照的关联记录,一期每个任务只保留一条 active link。"""
|
"""发货任务与库存快照的关联记录,一期每个任务只保留一条 active link。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_task_inventory_links'
|
__tablename__ = 'shipping_task_onhand_links'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
Index('ix_shipping_task_inventory_links_task_active', 'task_id', 'is_active'),
|
Index('ix_shipping_task_onhand_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_file_active', 'onhand_file_id', 'is_active'),
|
||||||
Index(
|
Index(
|
||||||
'ix_shipping_task_inventory_links_task_source',
|
'ix_shipping_task_onhand_links_task_source',
|
||||||
'task_id',
|
'task_id',
|
||||||
'matched_source_code',
|
'matched_source_code',
|
||||||
),
|
),
|
||||||
@@ -273,7 +180,7 @@ class ShippingTaskInventoryLink(Base):
|
|||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), index=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')
|
link_role: Mapped[str] = mapped_column(String(32), default='member')
|
||||||
access_mode: Mapped[str] = mapped_column(String(32), default='readonly')
|
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)
|
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_check_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||||
identity_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
identity_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
snapshot_age_seconds: Mapped[Optional[int]] = mapped_column(Integer, 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)
|
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_inventory_preparation_source_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_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)
|
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)
|
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)
|
linked_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||||
|
|
||||||
task: Mapped['ShippingOrderTask'] = relationship('ShippingOrderTask', foreign_keys=[task_id])
|
task: Mapped['ShippingOrderTask'] = relationship('ShippingOrderTask', foreign_keys=[task_id])
|
||||||
inventory_file: Mapped['ShippingInventoryFile'] = relationship(
|
inventory_file: Mapped['FreightRpaOnhandReportFile'] = relationship(
|
||||||
'ShippingInventoryFile',
|
'FreightRpaOnhandReportFile',
|
||||||
back_populates='links',
|
back_populates='links',
|
||||||
foreign_keys=[inventory_file_id],
|
foreign_keys=[onhand_file_id],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
models/shipping_excel_template.py
|
models/shipping_excel_template.py
|
||||||
|
|
||||||
用途:定义版本化发货 Excel 模板及不可变 Notice 导出产物。
|
用途:定义版本化发货 Excel 模板及不可变 Notice 导出产物。
|
||||||
依赖:models.base.Base、库存源、订单 Schema、ShippingNotice 与库存快照模型。
|
依赖:models.base.Base、FreightRpaSource、订单 Schema、ShippingNotice、freight_rpa_parsing_profiles 与 freight_rpa_onhand_report_files。
|
||||||
逻辑:库存源只绑定已发布模板版本;每次生成均新增 Artifact 并锁定输入版本与校验和;
|
逻辑:库存源只绑定已发布模板版本;每次生成均新增 Artifact 并锁定输入版本与校验和;
|
||||||
co8e9f0a1b2c 已删除 export artifact 的 batch_id 列;Artifact 直接属于一张 Notice。
|
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)
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
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):
|
class ShippingExportArtifact(Base):
|
||||||
@@ -62,8 +62,8 @@ class ShippingExportArtifact(Base):
|
|||||||
template_id: Mapped[int] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=False)
|
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_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)
|
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_parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_parsing_profiles.id'), nullable=False)
|
||||||
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True)
|
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)
|
input_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
file_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
file_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||||
file_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
file_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
backend/app/models/shipping_fulfillment.py
|
backend/app/models/shipping_fulfillment.py
|
||||||
|
|
||||||
用途:保存预约单全局注册、每轮库存核验和 Excel 对预约单的不可重叠归属。
|
用途:保存预约单全局注册、每轮库存核验和 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 行均追加保存。
|
逻辑: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)
|
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__ = (
|
__table_args__ = (
|
||||||
CheckConstraint(
|
CheckConstraint(
|
||||||
"status IN ('completed', 'expired', 'superseded')",
|
"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)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False)
|
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)
|
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)
|
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)
|
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')
|
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)
|
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)
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
lines: Mapped[list['ShippingInventoryVerificationLine']] = relationship(
|
lines: Mapped[list['ShippingOnhandVerificationLine']] = relationship(
|
||||||
back_populates='verification', cascade='all, delete-orphan', order_by='ShippingInventoryVerificationLine.id',
|
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__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint(
|
UniqueConstraint(
|
||||||
'verification_id', 'reservation_id',
|
'verification_id', 'reservation_id',
|
||||||
name='uq_shipping_notice_inventory_verification_lines_reservation',
|
name='uq_shipping_notice_onhand_verification_lines_reservation',
|
||||||
),
|
),
|
||||||
CheckConstraint(
|
CheckConstraint(
|
||||||
"status IN ('available', 'shortage', 'invalid')",
|
"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)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
verification_id: Mapped[int] = mapped_column(
|
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)
|
reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False)
|
||||||
required_qty: Mapped[Decimal] = mapped_column(Numeric(24, 8), 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)
|
status: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||||
detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
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):
|
class ShippingExportArtifactLine(Base):
|
||||||
@@ -120,7 +120,7 @@ class ShippingExportArtifactLine(Base):
|
|||||||
)
|
)
|
||||||
reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False)
|
reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False)
|
||||||
verification_line_id: Mapped[int] = mapped_column(
|
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)
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
backend/app/models/shipping_notice_line.py
|
backend/app/models/shipping_notice_line.py
|
||||||
|
|
||||||
用途:正式发货通知行(shipping_notice_lines),对齐蓝图建单后命名空间。
|
用途:正式发货通知行(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 扩展。
|
逻辑:冻结 Snapshot 时双写;履约仍以 Snapshot 为权威,本表供 Notice 域查询与 1:N 扩展。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -47,7 +47,7 @@ class ShippingNoticeLine(Base):
|
|||||||
# 正式履约事实按通知行固化;Notice 单头不得承载仓库或库存快照。
|
# 正式履约事实按通知行固化;Notice 单头不得承载仓库或库存快照。
|
||||||
inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||||
inventory_file_id: Mapped[Optional[int]] = mapped_column(
|
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)
|
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)
|
field_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||||
|
|||||||
+17
-17
@@ -1,9 +1,9 @@
|
|||||||
"""
|
"""
|
||||||
models/shipping_notice_line_inventory_match.py
|
models/shipping_notice_line_onhand_match.py
|
||||||
|
|
||||||
用途:正式 OT(ShippingNotice)行级库存匹配事实持久化——可用数量/短缺/match_result 的真相源。
|
用途:正式 OT(ShippingNotice)行级库存匹配事实持久化——可用数量/短缺/match_result 的真相源。
|
||||||
依赖:shipping_notices、shipping_inventory_files、shipping_order_review_cases(可选关联)。
|
依赖:shipping_notices、freight_rpa_onhand_report_files、shipping_order_review_cases(可选关联)。
|
||||||
逻辑:由 inventory_matching 完成后写入;同一 OT+行+快照唯一;新快照新增行不覆盖历史;
|
逻辑:由 onhand_matching 完成后写入;同一 OT+行+快照唯一;新快照新增行不覆盖历史;
|
||||||
is_current 标记投影用的当前事实;禁止用 Job payload / line_projections 充当正式真相。
|
is_current 标记投影用的当前事实;禁止用 Job payload / line_projections 充当正式真相。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -30,15 +30,15 @@ from sqlalchemy.orm import Mapped, mapped_column
|
|||||||
from app.models.base import Base
|
from app.models.base import Base
|
||||||
|
|
||||||
|
|
||||||
class ShippingNoticeLineInventoryMatch(Base):
|
class ShippingNoticeLineOnhandMatch(Base):
|
||||||
"""一条 OT 明细在某库存快照下的匹配事实(不可原地覆盖历史快照结果)。"""
|
"""一条 OT 明细在某库存快照下的匹配事实(不可原地覆盖历史快照结果)。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_notice_line_inventory_matches'
|
__tablename__ = 'shipping_notice_line_onhand_matches'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint(
|
UniqueConstraint(
|
||||||
'task_id',
|
'task_id',
|
||||||
'snapshot_line_id',
|
'snapshot_line_id',
|
||||||
'inventory_snapshot_id',
|
'onhand_snapshot_id',
|
||||||
name='uq_shipping_notice_line_inv_match_task_line_snap',
|
name='uq_shipping_notice_line_inv_match_task_line_snap',
|
||||||
),
|
),
|
||||||
# 同一 OT 行同一时刻仅一条当前事实(PostgreSQL partial unique)。
|
# 同一 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_task', 'task_id'),
|
||||||
Index('ix_shipping_notice_line_inv_match_case', 'review_case_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(
|
CheckConstraint(
|
||||||
"match_result IN ("
|
"match_result IN ("
|
||||||
"'matched', 'not_found', 'result_missing', 'preparing', "
|
"'matched', 'not_found', 'result_missing', 'preparing', "
|
||||||
@@ -60,7 +60,7 @@ class ShippingNoticeLineInventoryMatch(Base):
|
|||||||
name='ck_shipping_notice_line_inv_match_result',
|
name='ck_shipping_notice_line_inv_match_result',
|
||||||
),
|
),
|
||||||
CheckConstraint(
|
CheckConstraint(
|
||||||
"inventory_status IN ("
|
"onhand_status IN ("
|
||||||
"'ready', 'preparing', 'mapping_failed', 'source_conflict', "
|
"'ready', 'preparing', 'mapping_failed', 'source_conflict', "
|
||||||
"'unavailable', 'invalid_key', 'invalid'"
|
"'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_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
|
||||||
line_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
line_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||||
candidate_set_id: Mapped[Optional[int]] = mapped_column(
|
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,
|
nullable=True,
|
||||||
index=True,
|
index=True,
|
||||||
)
|
)
|
||||||
candidate_set_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
candidate_set_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||||
candidate_line_id: Mapped[Optional[int]] = mapped_column(
|
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,
|
nullable=True,
|
||||||
index=True,
|
index=True,
|
||||||
)
|
)
|
||||||
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(
|
onhand_snapshot_id: Mapped[Optional[int]] = mapped_column(
|
||||||
ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'),
|
ForeignKey('freight_rpa_onhand_report_files.id', ondelete='SET NULL'),
|
||||||
nullable=True,
|
nullable=True,
|
||||||
)
|
)
|
||||||
match_result: Mapped[str] = mapped_column(String(32), nullable=False)
|
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)
|
required_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||||
available_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)
|
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)
|
part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||||
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||||
matching_rule_version: Mapped[Optional[str]] = mapped_column(String(64), 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')
|
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)
|
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)
|
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_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)
|
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)
|
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)
|
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)
|
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_inventory_verifications.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)
|
||||||
+19
-19
@@ -1,12 +1,12 @@
|
|||||||
"""
|
"""
|
||||||
models/shipping_inventory_candidates.py
|
models/shipping_onhand_candidates.py
|
||||||
|
|
||||||
用途:库存候选冻结的结构化持久化——决策 C1 的正式业务真相。
|
用途:库存候选冻结的结构化持久化——决策 C1 的正式业务真相。
|
||||||
InventoryCandidateSet(候选集合)→ Source(任务级候选源)→ Line(行级候选源),
|
ShippingOnhandCandidateSet(候选集合)→ Source(任务级候选源)→ Line(行级候选源),
|
||||||
同时 ShippingOrderSnapshot.source_manifest_json['inventory_candidate_freeze'] 保存
|
同时 ShippingOrderSnapshot.source_manifest_json['inventory_candidate_freeze'] 保存
|
||||||
同一时刻的完整不可变副本,用于审计与回滚。
|
同一时刻的完整不可变副本,用于审计与回滚。
|
||||||
依赖:Base、ShippingOrderTask、ShippingProcessExecution、ShippingOrderReviewCase、users、
|
依赖:Base、ShippingOrderTask、ShippingProcessExecution、ShippingOrderReviewCase、users、
|
||||||
ShippingInventoryRoutingRule(可选外键,路由规则版本)。
|
FreightRpaOnhandRoutingRule(可选外键,路由规则版本)。
|
||||||
逻辑:建单前复核阶段(review_case 绑定)或建单后正式推进阶段(task 绑定)都可冻结;
|
逻辑:建单前复核阶段(review_case 绑定)或建单后正式推进阶段(task 绑定)都可冻结;
|
||||||
input_fingerprint 相同的重复 freeze 直接返回旧 set_id(幂等);
|
input_fingerprint 相同的重复 freeze 直接返回旧 set_id(幂等);
|
||||||
source_codes_json 为有序列表(路由优先级信息不能丢),禁止用 SET 类型。
|
source_codes_json 为有序列表(路由优先级信息不能丢),禁止用 SET 类型。
|
||||||
@@ -39,7 +39,7 @@ def _utc_now() -> datetime:
|
|||||||
return datetime.utcnow()
|
return datetime.utcnow()
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryCandidateSet(Base):
|
class ShippingOnhandCandidateSet(Base):
|
||||||
"""
|
"""
|
||||||
库存候选集合(冻结真相根)。
|
库存候选集合(冻结真相根)。
|
||||||
|
|
||||||
@@ -48,7 +48,7 @@ class ShippingInventoryCandidateSet(Base):
|
|||||||
二者至少一个非空(CheckConstraint 强制)。
|
二者至少一个非空(CheckConstraint 强制)。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_candidate_sets'
|
__tablename__ = 'shipping_onhand_candidate_sets'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
CheckConstraint(
|
CheckConstraint(
|
||||||
'task_id IS NOT NULL OR review_case_id IS NOT NULL',
|
'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_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
superseded_by_set_id: Mapped[Optional[int]] = mapped_column(
|
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_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
invalidated_reason: Mapped[Optional[str]] = mapped_column(Text, 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)
|
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
|
|
||||||
sources: Mapped[list['ShippingInventoryCandidateSource']] = relationship(
|
sources: Mapped[list['ShippingOnhandCandidateSource']] = relationship(
|
||||||
back_populates='candidate_set',
|
back_populates='candidate_set',
|
||||||
cascade='all, delete-orphan',
|
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',
|
back_populates='candidate_set',
|
||||||
cascade='all, delete-orphan',
|
cascade='all, delete-orphan',
|
||||||
order_by='ShippingInventoryCandidateLine.line_no',
|
order_by='ShippingOnhandCandidateLine.line_no',
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryCandidateSource(Base):
|
class ShippingOnhandCandidateSource(Base):
|
||||||
"""
|
"""
|
||||||
任务级候选库存源(Set 的子级)。
|
任务级候选库存源(Set 的子级)。
|
||||||
|
|
||||||
@@ -132,7 +132,7 @@ class ShippingInventoryCandidateSource(Base):
|
|||||||
candidate_origin ∈ {rule, manual_override},区分是规则算出来还是人工强制指定。
|
candidate_origin ∈ {rule, manual_override},区分是规则算出来还是人工强制指定。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_candidate_sources'
|
__tablename__ = 'shipping_onhand_candidate_sources'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint(
|
UniqueConstraint(
|
||||||
'candidate_set_id', 'source_code',
|
'candidate_set_id', 'source_code',
|
||||||
@@ -151,13 +151,13 @@ class ShippingInventoryCandidateSource(Base):
|
|||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
candidate_set_id: Mapped[int] = mapped_column(
|
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)
|
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
candidate_order: Mapped[int] = mapped_column(Integer, nullable=False)
|
candidate_order: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
candidate_origin: Mapped[str] = mapped_column(String(32), nullable=False, default='rule')
|
candidate_origin: Mapped[str] = mapped_column(String(32), nullable=False, default='rule')
|
||||||
routing_rule_id: Mapped[Optional[int]] = mapped_column(
|
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)
|
routing_rule_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||||
source_config_version: Mapped[Optional[str]] = mapped_column(String(64), 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,
|
DateTime, default=_utc_now, onupdate=_utc_now, nullable=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
candidate_set: Mapped['ShippingInventoryCandidateSet'] = relationship(
|
candidate_set: Mapped['ShippingOnhandCandidateSet'] = relationship(
|
||||||
back_populates='sources',
|
back_populates='sources',
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryCandidateLine(Base):
|
class ShippingOnhandCandidateLine(Base):
|
||||||
"""
|
"""
|
||||||
行级候选库存源(Set 的子级,按稳定 line_no 对齐订单行)。
|
行级候选库存源(Set 的子级,按稳定 line_no 对齐订单行)。
|
||||||
|
|
||||||
@@ -185,7 +185,7 @@ class ShippingInventoryCandidateLine(Base):
|
|||||||
part_number + reservation_id,不能只依赖 Snapshot JSON 做高频查询。
|
part_number + reservation_id,不能只依赖 Snapshot JSON 做高频查询。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_candidate_lines'
|
__tablename__ = 'shipping_onhand_candidate_lines'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint(
|
UniqueConstraint(
|
||||||
'candidate_set_id', 'line_no',
|
'candidate_set_id', 'line_no',
|
||||||
@@ -199,7 +199,7 @@ class ShippingInventoryCandidateLine(Base):
|
|||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
candidate_set_id: Mapped[int] = mapped_column(
|
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)
|
line_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
source_line_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
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,
|
DateTime, default=_utc_now, onupdate=_utc_now, nullable=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
candidate_set: Mapped['ShippingInventoryCandidateSet'] = relationship(
|
candidate_set: Mapped['ShippingOnhandCandidateSet'] = relationship(
|
||||||
back_populates='lines',
|
back_populates='lines',
|
||||||
)
|
)
|
||||||
+13
-13
@@ -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,支持有效源复用和问题源单独重拉。
|
逻辑:PreparationAttempt 聚合多个 SourceAttempt,支持有效源复用和问题源单独重拉。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -17,10 +17,10 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship
|
|||||||
from app.models.base import Base
|
from app.models.base import Base
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryPreparationAttempt(Base):
|
class ShippingOnhandPreparationAttempt(Base):
|
||||||
"""一次任务级库存准备恢复轮次。"""
|
"""一次任务级库存准备恢复轮次。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_preparation_attempts'
|
__tablename__ = 'shipping_onhand_preparation_attempts'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint('task_id', 'attempt_no', name='uq_shipping_inventory_preparation_task_attempt'),
|
UniqueConstraint('task_id', 'attempt_no', name='uq_shipping_inventory_preparation_task_attempt'),
|
||||||
CheckConstraint(
|
CheckConstraint(
|
||||||
@@ -38,7 +38,7 @@ class ShippingInventoryPreparationAttempt(Base):
|
|||||||
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
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)
|
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)
|
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)
|
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)
|
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)
|
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
completed_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__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint('preparation_attempt_id', 'source_code', name='uq_shipping_inventory_preparation_source_attempt'),
|
UniqueConstraint('preparation_attempt_id', 'source_code', name='uq_shipping_inventory_preparation_source_attempt'),
|
||||||
CheckConstraint(
|
CheckConstraint(
|
||||||
@@ -63,17 +63,17 @@ class ShippingInventoryPreparationSourceAttempt(Base):
|
|||||||
)
|
)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
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)
|
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
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')
|
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)
|
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)
|
rpa_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_task_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)
|
onhand_file_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_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)
|
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)
|
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
operation_id: Mapped[Optional[str]] = mapped_column(String(128), 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)
|
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)
|
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')
|
||||||
@@ -32,8 +32,8 @@ class ShippingOrderReviewLineDecision(Base):
|
|||||||
),
|
),
|
||||||
CheckConstraint(
|
CheckConstraint(
|
||||||
"decision_code IN ("
|
"decision_code IN ("
|
||||||
"'wait_inventory', 'use_new_inventory_file', 'change_inventory_source', "
|
"'wait_onhand', 'use_new_inventory_file', 'change_inventory_source', "
|
||||||
"'fulfill_complete_line_now', 'close_unfulfillable', 'reopen', 'release_inventory_shortage'"
|
"'fulfill_complete_line_now', 'close_unfulfillable', 'reopen', 'release_onhand_shortage'"
|
||||||
")",
|
")",
|
||||||
name='ck_shipping_review_line_decisions_code',
|
name='ck_shipping_review_line_decisions_code',
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
backend/app/models/shipping_order_task.py
|
backend/app/models/shipping_order_task.py
|
||||||
|
|
||||||
用途:正式发货通知创建前的 OT(shipping_order_tasks)聚合根,对齐多 EML/PDF 蓝图。
|
用途:正式发货通知创建前的 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 反向关联,本表不保存通知单指针。
|
逻辑:由 Extraction Run 的 user_task_no 双写/回填;正式 ShippingNotice 通过 order_task_id 反向关联,本表不保存通知单指针。
|
||||||
页面链路以 task_no(OT-…)为根身份;1 OT 可对应 0..N Notice。
|
页面链路以 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,
|
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(
|
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)
|
step_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||||
active_process_execution_id: Mapped[Optional[int]] = mapped_column(
|
active_process_execution_id: Mapped[Optional[int]] = mapped_column(
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
models/shipping_process_gate.py
|
models/shipping_process_gate.py
|
||||||
|
|
||||||
用途:门禁级中断恢复的持久化模型——Execution / Gate / Attempt。
|
用途:门禁级中断恢复的持久化模型——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 不可变执行尝试并承载租约。
|
逻辑:Execution 为业务恢复真相;Gate 保存当前门禁状态;Attempt 不可变执行尝试并承载租约。
|
||||||
由领域服务独占写入;Job 仅调度。
|
由领域服务独占写入;Job 仅调度。
|
||||||
co8e9f0a1b2c:已移除对 shipping_notice_workflow_* 的硬外键(无历史兼容)。
|
co8e9f0a1b2c:已移除对 shipping_notice_workflow_* 的硬外键(无历史兼容)。
|
||||||
@@ -78,7 +78,7 @@ class ShippingProcessExecution(Base):
|
|||||||
)
|
)
|
||||||
# 绑定候选版本,防止旧 callback/job 写入新候选链。
|
# 绑定候选版本,防止旧 callback/job 写入新候选链。
|
||||||
candidate_set_id: Mapped[Optional[int]] = mapped_column(
|
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(
|
execution_revision: Mapped[int] = mapped_column(
|
||||||
Integer, nullable=False, default=1, server_default='1',
|
Integer, nullable=False, default=1, server_default='1',
|
||||||
|
|||||||
@@ -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')
|
|
||||||
+6
-6
@@ -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 与工作台均先创建本会话,再由后端对受控文件资产进行结构初检;
|
逻辑:Dify Tool 与工作台均先创建本会话,再由后端对受控文件资产进行结构初检;
|
||||||
co8e9f0a1b2c 已删除 batch_id;会话仅可关联 task_id;
|
co8e9f0a1b2c 已删除 batch_id;会话仅可关联 task_id;
|
||||||
本表不代表库存站点配置,也不代表生产库存快照。
|
本表不代表库存站点配置,也不代表生产库存快照。
|
||||||
@@ -19,12 +19,12 @@ from sqlalchemy.orm import Mapped, mapped_column
|
|||||||
from app.models.base import Base
|
from app.models.base import Base
|
||||||
|
|
||||||
|
|
||||||
class ShippingTemporaryInventorySession(Base):
|
class ShippingTemporaryOnhandSession(Base):
|
||||||
"""对话上传库存候选文件的短生命周期会话;禁止直接成为生产库存来源。"""
|
"""对话上传库存候选文件的短生命周期会话;禁止直接成为生产库存来源。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_temporary_inventory_sessions'
|
__tablename__ = 'shipping_temporary_onhand_sessions'
|
||||||
__table_args__ = (
|
__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_user_created', 'user_id', 'created_at'),
|
||||||
Index('ix_shipping_temp_inventory_conversation_created', 'conversation_id', 'created_at'),
|
Index('ix_shipping_temp_inventory_conversation_created', 'conversation_id', 'created_at'),
|
||||||
Index('ix_shipping_temp_inventory_asset', 'asset_id'),
|
Index('ix_shipping_temp_inventory_asset', 'asset_id'),
|
||||||
@@ -37,7 +37,7 @@ class ShippingTemporaryInventorySession(Base):
|
|||||||
conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
|
conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
|
||||||
asset_id: Mapped[int] = mapped_column(ForeignKey('file_assets.id'), nullable=False, index=True)
|
asset_id: Mapped[int] = mapped_column(ForeignKey('file_assets.id'), nullable=False, index=True)
|
||||||
analysis_id: Mapped[Optional[int]] = mapped_column(
|
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)
|
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')
|
declared_intent: Mapped[str] = mapped_column(String(32), nullable=False, default='inventory_candidate')
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
backend/app/services/admin/faq_service.py
|
backend/app/services/admin/faq_service.py
|
||||||
|
|
||||||
用途:全局常用问题(QuickQuestion)与热点 FAQ 候选管理。
|
用途:全局常用问题(QuickQuestion)与热点 FAQ 候选管理。
|
||||||
依赖:models、faq_kb_invalidation、hot_faq_* services。
|
依赖:models、faq_kb_invalidation、hot_faq_* services、faq_text_utils(模糊阈值钳制)。
|
||||||
逻辑:由 api/admin/quick_questions.py、faq_candidates.py 调用。
|
逻辑:由 api/admin/quick_questions.py、faq_candidates.py 调用。
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -13,6 +13,7 @@ from typing import Any
|
|||||||
from app import db
|
from app import db
|
||||||
from app.core.errors import NotFoundError, ValidationError
|
from app.core.errors import NotFoundError, ValidationError
|
||||||
from app.models import Agent, KbDocument, QuickQuestion
|
from app.models import Agent, KbDocument, QuickQuestion
|
||||||
|
from app.services.faq_text_utils import clamp_fuzzy_threshold
|
||||||
|
|
||||||
|
|
||||||
def parse_aliases(raw_aliases) -> list[str]:
|
def parse_aliases(raw_aliases) -> list[str]:
|
||||||
@@ -61,6 +62,8 @@ def serialize_quick_question(
|
|||||||
'aliases': q.aliases if isinstance(q.aliases, list) else [],
|
'aliases': q.aliases if isinstance(q.aliases, list) else [],
|
||||||
'cache_enabled': bool(q.cache_enabled),
|
'cache_enabled': bool(q.cache_enabled),
|
||||||
'is_enabled': bool(q.is_enabled),
|
'is_enabled': bool(q.is_enabled),
|
||||||
|
'fuzzy_enabled': bool(getattr(q, 'fuzzy_enabled', False)),
|
||||||
|
'fuzzy_threshold': clamp_fuzzy_threshold(getattr(q, 'fuzzy_threshold', None)),
|
||||||
'hit_count': q.hit_count or 0,
|
'hit_count': q.hit_count or 0,
|
||||||
'agent_id': q.agent_id,
|
'agent_id': q.agent_id,
|
||||||
'agent_name': agent_name,
|
'agent_name': agent_name,
|
||||||
@@ -93,6 +96,12 @@ def apply_quick_question_payload(qq: QuickQuestion, data: dict, *, require_answe
|
|||||||
qq.cache_enabled = bool(data['cache_enabled'])
|
qq.cache_enabled = bool(data['cache_enabled'])
|
||||||
if 'is_enabled' in data:
|
if 'is_enabled' in data:
|
||||||
qq.is_enabled = bool(data['is_enabled'])
|
qq.is_enabled = bool(data['is_enabled'])
|
||||||
|
if 'fuzzy_enabled' in data:
|
||||||
|
qq.fuzzy_enabled = bool(data['fuzzy_enabled'])
|
||||||
|
if 'fuzzy_threshold' in data:
|
||||||
|
qq.fuzzy_threshold = clamp_fuzzy_threshold(data['fuzzy_threshold'])
|
||||||
|
else:
|
||||||
|
qq.fuzzy_threshold = clamp_fuzzy_threshold(qq.fuzzy_threshold)
|
||||||
if 'expires_at' in data:
|
if 'expires_at' in data:
|
||||||
qq.expires_at = parse_expires_at(data['expires_at'])
|
qq.expires_at = parse_expires_at(data['expires_at'])
|
||||||
if 'retriever_resources' in data and isinstance(data.get('retriever_resources'), list):
|
if 'retriever_resources' in data and isinstance(data.get('retriever_resources'), list):
|
||||||
@@ -106,6 +115,8 @@ def apply_quick_question_payload(qq: QuickQuestion, data: dict, *, require_answe
|
|||||||
|
|
||||||
if qq.cache_enabled and not str(qq.answer or '').strip():
|
if qq.cache_enabled and not str(qq.answer or '').strip():
|
||||||
raise ValidationError('启用 FAQ 缓存时必须填写标准答案')
|
raise ValidationError('启用 FAQ 缓存时必须填写标准答案')
|
||||||
|
if qq.fuzzy_enabled and not qq.cache_enabled:
|
||||||
|
raise ValidationError('启用模糊匹配前需先启用 FAQ 缓存')
|
||||||
if require_answer and (not qq.title or not qq.question or not qq.agent_id):
|
if require_answer and (not qq.title or not qq.question or not qq.agent_id):
|
||||||
raise ValidationError('Missing required fields')
|
raise ValidationError('Missing required fields')
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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)
|
||||||
|
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -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)
|
||||||
@@ -162,6 +162,8 @@ agent_types:
|
|||||||
handler_config_schema: {}
|
handler_config_schema: {}
|
||||||
in_transit_transfer:
|
in_transit_transfer:
|
||||||
label: 在途仓自动调拨
|
label: 在途仓自动调拨
|
||||||
|
# 调拨类型来自平台配置(管理端「在途调拨类型」维护,GET /transfer-types 下发),
|
||||||
|
# 本清单与提示词不硬编码类型列表;Dify 平台侧如有副本需人工同步。
|
||||||
conversation_mode_default: task_chat
|
conversation_mode_default: task_chat
|
||||||
runtime_provider_default: hybrid
|
runtime_provider_default: hybrid
|
||||||
models:
|
models:
|
||||||
|
|||||||
@@ -6,6 +6,9 @@
|
|||||||
输出结构化 message.completed 卡片,并经 Run API 恢复;本 Handler 负责 hybrid
|
输出结构化 message.completed 卡片,并经 Run API 恢复;本 Handler 负责 hybrid
|
||||||
运行时的上下文钩子与领域 UI State 扩展位(transfer_ui_state),暂不注入
|
运行时的上下文钩子与领域 UI State 扩展位(transfer_ui_state),暂不注入
|
||||||
Dify Chatflow 生命周期。
|
Dify Chatflow 生命周期。
|
||||||
|
【调拨类型语义 2026-10-14】调拨类型来自平台配置(管理端「在途调拨类型」
|
||||||
|
维护,`GET /api/in-transit-transfer/transfer-types` 下发);提示词与本
|
||||||
|
Handler 一律不硬编码类型列表,Dify 平台侧如有副本需人工同步。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|||||||
@@ -77,12 +77,13 @@ def try_fast_route(
|
|||||||
_log_fast_route('faq_cache', agent_code=agent_code, agent_id=agent_id, session_id=session_id)
|
_log_fast_route('faq_cache', agent_code=agent_code, agent_id=agent_id, session_id=session_id)
|
||||||
return FastRouteResult(
|
return FastRouteResult(
|
||||||
generator=FaqCacheService.stream_chat(
|
generator=FaqCacheService.stream_chat(
|
||||||
faq_hit,
|
faq_hit.entry,
|
||||||
query,
|
query,
|
||||||
user,
|
user,
|
||||||
agent,
|
agent,
|
||||||
external_conversation_id,
|
external_conversation_id,
|
||||||
session_id=session_id,
|
session_id=session_id,
|
||||||
|
match=faq_hit,
|
||||||
),
|
),
|
||||||
route_name='faq_cache',
|
route_name='faq_cache',
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -2,11 +2,14 @@
|
|||||||
backend/app/services/faq_cache.py
|
backend/app/services/faq_cache.py
|
||||||
|
|
||||||
用途:全局常用问题 FAQ 缓存匹配与 SSE 直答,避免重复调用 Dify。
|
用途:全局常用问题 FAQ 缓存匹配与 SSE 直答,避免重复调用 Dify。
|
||||||
依赖:models.QuickQuestion、ChatLog、SQLAlchemy db。
|
依赖:models.QuickQuestion、ChatLog、SQLAlchemy db、faq_text_utils(归一化与模糊评分)。
|
||||||
逻辑:chat.py 在调用 DifyService 前委托本模块 try_match(只看 cache_enabled,不看首页展示 is_enabled);命中则 stream_chat 返回预置答案。
|
逻辑:chat router 在调用 DifyService 前委托本模块 try_match(只看 cache_enabled,不看首页展示 is_enabled)。
|
||||||
|
匹配分两阶段:[STEP 1] 归一化精确命中(所有启用缓存的条目);[STEP 2] 模糊兜底
|
||||||
|
(仅 fuzzy_enabled 条目,得分达该条目阈值才命中),命中后 stream_chat 返回预置答案。
|
||||||
"""
|
"""
|
||||||
import json
|
import json
|
||||||
import time
|
import time
|
||||||
|
from dataclasses import dataclass
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Any, Optional
|
from typing import Any, Optional
|
||||||
|
|
||||||
@@ -14,7 +17,26 @@ from flask import current_app
|
|||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
from app.models import ChatLog, QuickQuestion
|
from app.models import ChatLog, QuickQuestion
|
||||||
from app.services.faq_text_utils import normalize_faq_query
|
from app.services.faq_text_utils import (
|
||||||
|
FUZZY_MIN_LENGTH,
|
||||||
|
clamp_fuzzy_threshold,
|
||||||
|
fuzzy_match_score,
|
||||||
|
normalize_faq_query,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 命中类型(写入 ChatLog payload 与 SSE metadata,供审计与排障)
|
||||||
|
MATCH_TYPE_EXACT = 'exact'
|
||||||
|
MATCH_TYPE_FUZZY = 'fuzzy'
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class FaqCacheMatch:
|
||||||
|
"""FAQ 缓存命中结果:条目本体 + 命中方式审计信息。"""
|
||||||
|
|
||||||
|
entry: QuickQuestion
|
||||||
|
match_type: str # 'exact' 归一化全等;'fuzzy' 模糊兜底
|
||||||
|
match_score: Optional[float] = None
|
||||||
|
matched_text: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
class FaqCacheService:
|
class FaqCacheService:
|
||||||
@@ -43,33 +65,48 @@ class FaqCacheService:
|
|||||||
return expires_at <= datetime.utcnow()
|
return expires_at <= datetime.utcnow()
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _candidate_texts(entry: QuickQuestion) -> list[str]:
|
def _candidate_pairs(entry: QuickQuestion) -> list[tuple[str, str]]:
|
||||||
"""
|
"""
|
||||||
收集条目可用于匹配的标准化文本集合。
|
收集条目可用于匹配的 (原文, 归一化文本) 对。
|
||||||
|
核心逻辑:候选来源为 question、title 与 aliases;原文用于审计展示,归一化文本用于比对。
|
||||||
@param entry - QuickQuestion 实例
|
@param entry - QuickQuestion 实例
|
||||||
@returns 归一化后的候选文本列表
|
@returns (原文, 归一化文本) 列表
|
||||||
"""
|
"""
|
||||||
texts: list[str] = []
|
pairs: list[tuple[str, str]] = []
|
||||||
for raw in (entry.question, entry.title):
|
for raw in (entry.question, entry.title):
|
||||||
normalized = FaqCacheService._normalize_text(raw)
|
normalized = FaqCacheService._normalize_text(raw)
|
||||||
if normalized:
|
if normalized:
|
||||||
texts.append(normalized)
|
pairs.append((str(raw), normalized))
|
||||||
aliases = entry.aliases if isinstance(entry.aliases, list) else []
|
aliases = entry.aliases if isinstance(entry.aliases, list) else []
|
||||||
for alias in aliases:
|
for alias in aliases:
|
||||||
normalized = FaqCacheService._normalize_text(str(alias))
|
normalized = FaqCacheService._normalize_text(str(alias))
|
||||||
if normalized:
|
if normalized:
|
||||||
texts.append(normalized)
|
pairs.append((str(alias), normalized))
|
||||||
return texts
|
return pairs
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def try_match(query: str, agent_id: int) -> Optional[QuickQuestion]:
|
def _candidate_texts(entry: QuickQuestion) -> list[str]:
|
||||||
"""
|
"""
|
||||||
尝试为指定 Agent 命中全局 FAQ 缓存条目。
|
收集条目可用于匹配的标准化文本集合。
|
||||||
核心逻辑:加载 cache_enabled 的全局条目,对 question/title/aliases 做归一化精确匹配。
|
核心逻辑:委托 _candidate_pairs 取归一化列;热点聚合(hot_faq_aggregator)依赖本方法做去重比对。
|
||||||
|
@param entry - QuickQuestion 实例
|
||||||
|
@returns 归一化后的候选文本列表
|
||||||
|
"""
|
||||||
|
return [normalized for _, normalized in FaqCacheService._candidate_pairs(entry)]
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def try_match(query: str, agent_id: int) -> Optional[FaqCacheMatch]:
|
||||||
|
"""
|
||||||
|
尝试为指定 Agent 命中全局 FAQ 缓存条目(两阶段)。
|
||||||
|
核心逻辑:
|
||||||
|
[STEP 1] 精确阶段——所有 cache_enabled 条目的 question/title/aliases 归一化后与输入全等比对;
|
||||||
|
[STEP 2] 模糊兜底——精确未命中且输入长度达 FUZZY_MIN_LENGTH 时,仅对 fuzzy_enabled 条目
|
||||||
|
计算 fuzzy_match_score,最高分达到该条目阈值(钳制在 0.5~1.0)才命中;
|
||||||
|
同分时先出现的条目(sort_order 靠前)胜出。
|
||||||
is_enabled 只控制工作台首页是否展示快捷入口,不影响本方法是否直答。
|
is_enabled 只控制工作台首页是否展示快捷入口,不影响本方法是否直答。
|
||||||
@param query - 用户提问
|
@param query - 用户提问
|
||||||
@param agent_id - 当前 Agent 主键
|
@param agent_id - 当前 Agent 主键
|
||||||
@returns 命中的 QuickQuestion;未命中返回 None
|
@returns FaqCacheMatch;未命中返回 None
|
||||||
"""
|
"""
|
||||||
normalized_query = FaqCacheService._normalize_text(query)
|
normalized_query = FaqCacheService._normalize_text(query)
|
||||||
if not normalized_query or not agent_id:
|
if not normalized_query or not agent_id:
|
||||||
@@ -89,12 +126,50 @@ class FaqCacheService:
|
|||||||
.all()
|
.all()
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# [STEP 1] 精确命中:归一化后全等,任何启用缓存的条目参与
|
||||||
for entry in entries:
|
for entry in entries:
|
||||||
if FaqCacheService._is_expired(entry):
|
if FaqCacheService._is_expired(entry):
|
||||||
continue
|
continue
|
||||||
if normalized_query in FaqCacheService._candidate_texts(entry):
|
for raw, normalized in FaqCacheService._candidate_pairs(entry):
|
||||||
return entry
|
if normalized_query == normalized:
|
||||||
return None
|
return FaqCacheMatch(
|
||||||
|
entry=entry, match_type=MATCH_TYPE_EXACT, match_score=1.0, matched_text=raw
|
||||||
|
)
|
||||||
|
|
||||||
|
# [STEP 2] 模糊兜底:仅参与模糊开关打开的条目,取最高分;短问句不参与
|
||||||
|
if len(normalized_query) < FUZZY_MIN_LENGTH:
|
||||||
|
return None
|
||||||
|
best: Optional[FaqCacheMatch] = None
|
||||||
|
for entry in entries:
|
||||||
|
if not entry.fuzzy_enabled:
|
||||||
|
continue
|
||||||
|
if FaqCacheService._is_expired(entry):
|
||||||
|
continue
|
||||||
|
threshold = clamp_fuzzy_threshold(entry.fuzzy_threshold)
|
||||||
|
for raw, normalized in FaqCacheService._candidate_pairs(entry):
|
||||||
|
if len(normalized) < FUZZY_MIN_LENGTH:
|
||||||
|
continue
|
||||||
|
score = fuzzy_match_score(normalized_query, normalized)
|
||||||
|
if score >= threshold and (best is None or score > (best.match_score or 0.0)):
|
||||||
|
best = FaqCacheMatch(
|
||||||
|
entry=entry, match_type=MATCH_TYPE_FUZZY, match_score=score, matched_text=raw
|
||||||
|
)
|
||||||
|
return best
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _match_audit_fields(match: Optional[FaqCacheMatch]) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
构造命中方式的审计字段,写入 ChatLog payload 与 SSE metadata。
|
||||||
|
@param match - try_match 的命中结果;可为 None(历史调用方未传)
|
||||||
|
@returns 含 match_type / match_score / matched_text 的字典
|
||||||
|
"""
|
||||||
|
if match is None:
|
||||||
|
return {}
|
||||||
|
return {
|
||||||
|
'match_type': match.match_type,
|
||||||
|
'match_score': round(match.match_score, 4) if match.match_score is not None else None,
|
||||||
|
'matched_text': match.matched_text,
|
||||||
|
}
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _increment_hit_count(entry_id: int) -> None:
|
def _increment_hit_count(entry_id: int) -> None:
|
||||||
@@ -124,28 +199,38 @@ class FaqCacheService:
|
|||||||
agent,
|
agent,
|
||||||
conversation_id: str | None = None,
|
conversation_id: str | None = None,
|
||||||
session_id: str | None = None,
|
session_id: str | None = None,
|
||||||
|
match: Optional[FaqCacheMatch] = None,
|
||||||
):
|
):
|
||||||
"""
|
"""
|
||||||
以 SSE 形式返回 FAQ 预置答案,并写入 ChatLog。
|
以 SSE 形式返回 FAQ 预置答案,并写入 ChatLog。
|
||||||
核心逻辑:产出 message + message_end 事件,标记 payload.source=faq_cache。
|
核心逻辑:产出 message + message_end 事件,标记 payload.source=faq_cache;
|
||||||
|
match 非空时附带 match_type / match_score / matched_text 供审计与排障。
|
||||||
@param entry - 命中的 QuickQuestion
|
@param entry - 命中的 QuickQuestion
|
||||||
@param query - 用户原始提问
|
@param query - 用户原始提问
|
||||||
@param user - 当前用户代理对象(需含 id)
|
@param user - 当前用户代理对象(需含 id)
|
||||||
@param agent - 当前 Agent 代理对象(需含 id)
|
@param agent - 当前 Agent 代理对象(需含 id)
|
||||||
@param conversation_id - Dify/外部会话 ID
|
@param conversation_id - Dify/外部会话 ID
|
||||||
@param session_id - 本地会话 ID
|
@param session_id - 本地会话 ID
|
||||||
|
@param match - try_match 的命中结果;历史调用方可不传
|
||||||
@yields SSE 格式字符串
|
@yields SSE 格式字符串
|
||||||
"""
|
"""
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
final_conversation_id = conversation_id or f"faq_{int(time.time())}"
|
final_conversation_id = conversation_id or f"faq_{int(time.time())}"
|
||||||
answer = str(entry.answer or "").strip()
|
answer = str(entry.answer or "").strip()
|
||||||
retriever_resources = entry.retriever_resources if isinstance(entry.retriever_resources, list) else []
|
retriever_resources = entry.retriever_resources if isinstance(entry.retriever_resources, list) else []
|
||||||
|
audit_fields = FaqCacheService._match_audit_fields(match)
|
||||||
|
|
||||||
yield f"data: {json.dumps({'event': 'message', 'answer': answer}, ensure_ascii=False)}\n\n"
|
yield f"data: {json.dumps({'event': 'message', 'answer': answer}, ensure_ascii=False)}\n\n"
|
||||||
|
|
||||||
latency = int((time.time() - start_time) * 1000)
|
latency = int((time.time() - start_time) * 1000)
|
||||||
chat_log_id = None
|
chat_log_id = None
|
||||||
try:
|
try:
|
||||||
|
payload: dict[str, Any] = {
|
||||||
|
'source': 'faq_cache',
|
||||||
|
'faq_id': entry.id,
|
||||||
|
'faq_title': entry.title,
|
||||||
|
}
|
||||||
|
payload.update(audit_fields)
|
||||||
chat_log = ChatLog(
|
chat_log = ChatLog(
|
||||||
user_id=user.id,
|
user_id=user.id,
|
||||||
agent_id=agent.id,
|
agent_id=agent.id,
|
||||||
@@ -156,11 +241,7 @@ class FaqCacheService:
|
|||||||
tokens_used=0,
|
tokens_used=0,
|
||||||
latency=latency,
|
latency=latency,
|
||||||
retriever_resources=retriever_resources,
|
retriever_resources=retriever_resources,
|
||||||
payload={
|
payload=payload,
|
||||||
"source": "faq_cache",
|
|
||||||
"faq_id": entry.id,
|
|
||||||
"faq_title": entry.title,
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
db.session.add(chat_log)
|
db.session.add(chat_log)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
@@ -173,15 +254,16 @@ class FaqCacheService:
|
|||||||
FaqCacheService._increment_hit_count(entry.id)
|
FaqCacheService._increment_hit_count(entry.id)
|
||||||
|
|
||||||
end_data: dict[str, Any] = {
|
end_data: dict[str, Any] = {
|
||||||
"event": "message_end",
|
'event': 'message_end',
|
||||||
"answer": answer,
|
'answer': answer,
|
||||||
"replace_answer": True,
|
'replace_answer': True,
|
||||||
"chat_log_id": chat_log_id,
|
'chat_log_id': chat_log_id,
|
||||||
"conversation_id": final_conversation_id,
|
'conversation_id': final_conversation_id,
|
||||||
"metadata": {
|
'metadata': {
|
||||||
"retriever_resources": retriever_resources,
|
'retriever_resources': retriever_resources,
|
||||||
"source": "faq_cache",
|
'source': 'faq_cache',
|
||||||
"faq_id": entry.id,
|
'faq_id': entry.id,
|
||||||
|
**audit_fields,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
if retriever_resources:
|
if retriever_resources:
|
||||||
|
|||||||
@@ -1,11 +1,19 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/services/faq_text_utils.py
|
backend/app/services/faq_text_utils.py
|
||||||
|
|
||||||
用途:FAQ / 热点问句归一化等纯文本工具,供 faq_cache 与 hot_faq_aggregator 共用。
|
用途:FAQ / 热点问句归一化、模糊相似度评分等纯文本工具,供 faq_cache 与 hot_faq_aggregator 共用。
|
||||||
依赖:无外部业务模块。
|
依赖:difflib(Python 标准库,无第三方依赖)。
|
||||||
逻辑:保证离线聚合与在线命中使用同一 normalize 规则。
|
逻辑:保证离线聚合与在线命中使用同一 normalize 规则;模糊评分供 FAQ 兜底直答使用。
|
||||||
"""
|
"""
|
||||||
import re
|
import re
|
||||||
|
from difflib import SequenceMatcher
|
||||||
|
|
||||||
|
# 模糊兜底参与的最低归一化长度:过短问句(如「帮助」)误命中代价高,只走精确匹配。
|
||||||
|
FUZZY_MIN_LENGTH = 4
|
||||||
|
# 模糊阈值的安全钳制区间与默认值:下限防止管理员设得过低导致大面积误直答。
|
||||||
|
FUZZY_THRESHOLD_MIN = 0.5
|
||||||
|
FUZZY_THRESHOLD_MAX = 1.0
|
||||||
|
FUZZY_THRESHOLD_DEFAULT = 0.8
|
||||||
|
|
||||||
|
|
||||||
def normalize_faq_query(text: str) -> str:
|
def normalize_faq_query(text: str) -> str:
|
||||||
@@ -16,5 +24,38 @@ def normalize_faq_query(text: str) -> str:
|
|||||||
@returns 归一化后的字符串;空输入返回空串
|
@returns 归一化后的字符串;空输入返回空串
|
||||||
"""
|
"""
|
||||||
value = str(text or "").strip().lower()
|
value = str(text or "").strip().lower()
|
||||||
value = re.sub(r"[\s\u3000,。!?、;:""''()()\[\]【】\-—·,.!?;:'\"]+", "", value)
|
value = re.sub(r"[\s\u3000,。!?、;:“”‘’()()\[\]【】\-—·,.!?;:'\"]+", "", value)
|
||||||
return value
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def clamp_fuzzy_threshold(value) -> float:
|
||||||
|
"""
|
||||||
|
将模糊匹配阈值钳制到安全区间 [0.5, 1.0]。
|
||||||
|
核心逻辑:空值/非法值回退默认 0.8,越界值收敛到边界,保证在线匹配不会因配置异常失真。
|
||||||
|
@param value - 数据库或请求体中的阈值原始值
|
||||||
|
@returns 钳制后的浮点阈值
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
threshold = float(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return FUZZY_THRESHOLD_DEFAULT
|
||||||
|
return min(FUZZY_THRESHOLD_MAX, max(FUZZY_THRESHOLD_MIN, threshold))
|
||||||
|
|
||||||
|
|
||||||
|
def fuzzy_match_score(query: str, candidate: str) -> float:
|
||||||
|
"""
|
||||||
|
计算两段归一化问句的模糊相似度得分(0~1),供 FAQ 模糊兜底匹配使用。
|
||||||
|
核心逻辑:取编辑距离类相似度(SequenceMatcher.ratio)与包含覆盖率的最大值——
|
||||||
|
前者容忍换字/错字(能→可以),后者容忍加前后缀(我还能问什么 vs 还能问什么);
|
||||||
|
真问题偶含候选短语时(如「怎么用你查MES服务器」vs「怎么用你」)覆盖率很低,不会误命中。
|
||||||
|
@param query - 归一化后的用户问句
|
||||||
|
@param candidate - 归一化后的候选问句(标题/标准问句/同义问法)
|
||||||
|
@returns 0~1 之间的相似度得分
|
||||||
|
"""
|
||||||
|
if not query or not candidate:
|
||||||
|
return 0.0
|
||||||
|
score = SequenceMatcher(None, query, candidate).ratio()
|
||||||
|
if query in candidate or candidate in query:
|
||||||
|
coverage = min(len(query), len(candidate)) / max(len(query), len(candidate))
|
||||||
|
score = max(score, coverage)
|
||||||
|
return score
|
||||||
@@ -3,7 +3,8 @@ backend/app/services/file_assets/storage.py
|
|||||||
|
|
||||||
用途:私有 MinIO 业务文件存储适配层(与 agent-guides 公开 bucket 隔离)。
|
用途:私有 MinIO 业务文件存储适配层(与 agent-guides 公开 bucket 隔离)。
|
||||||
依赖:minio、app.core.config.settings、app.core.errors.ServiceUnavailableError。
|
依赖: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
|
from __future__ import annotations
|
||||||
@@ -119,13 +120,39 @@ class FileAssetStorage:
|
|||||||
except S3Error:
|
except S3Error:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def presigned_get_url(self, storage_key: str, *, expires_seconds: int) -> str:
|
def presigned_get_url(
|
||||||
"""生成短期受控下载 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()
|
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(
|
return self.client.presigned_get_object(
|
||||||
self.bucket_name,
|
self.bucket_name,
|
||||||
storage_key,
|
storage_key,
|
||||||
expires=timedelta(seconds=max(int(expires_seconds or 60), 60)),
|
expires=timedelta(seconds=max(int(expires_seconds or 60), 60)),
|
||||||
|
response_headers=response_headers,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
"""货代 RPA 模块根:承载 freight_rpa 域代码(common/onhand/inbound/upload)。"""
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""common:域中立件(跨 RPA Worker 共用、不依赖具体业务域)。"""
|
||||||
@@ -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)
|
||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
"""
|
"""
|
||||||
services/shipping_notice/credential_crypto.py
|
services/freight_rpa/common/credential_crypto.py
|
||||||
|
|
||||||
用途:加密和解密库存 RPA Profile 的登录凭据(委托通用 core 模块,仅固定本域密钥键与错误码)。
|
用途:加密和解密库存 RPA Profile 的登录凭据(委托通用 core 模块,仅固定本域密钥键与错误码)。
|
||||||
依赖:app.core.credential_crypto(Fernet 加解密);调用方仅保存密文,不将凭据写入日志或 API 响应。
|
依赖:app.core.credential_crypto(Fernet 加解密);调用方仅保存密文,不将凭据写入日志或 API 响应。
|
||||||
@@ -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
|
||||||
@@ -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")
|
||||||
+161
-67
@@ -1,11 +1,14 @@
|
|||||||
"""
|
"""
|
||||||
services/shipping_notice/rpa_worker_heartbeat.py
|
services/freight_rpa/common/worker_heartbeat.py
|
||||||
|
|
||||||
用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传/收料就绪检查与状态查询。
|
用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传/入站/出站就绪检查与状态查询。
|
||||||
依赖:Flask current_app、redis_client、shipping_notice.rpa(库存与上传目录、mock 模式)、
|
依赖:Flask current_app、redis_client、同包 rpa_runtime(mock 模式)、
|
||||||
shipping_notice.receipt_rpa(收料 trigger 目录)。
|
freight_rpa.onhand.trigger_io(onhand trigger 目录)、
|
||||||
逻辑:freight_rpa_worker 调 POST /rpa/heartbeat;写 inventory/upload/receipt trigger 前强制就绪检查;
|
freight_rpa.upload.trigger_io(上传目录)、
|
||||||
管理端 /rpa-workers/status?scope=inventory|receipt 展示对应 Worker 心跳徽标。
|
freight_rpa.inbound.trigger_io(inbound trigger 目录)、
|
||||||
|
freight_rpa.outbound.trigger_io(outbound trigger 目录)。
|
||||||
|
逻辑:Windows Worker 调 POST /api/freight-rpa/heartbeat;写 onhand/upload/inbound/outbound trigger 前强制就绪检查;
|
||||||
|
管理端 /rpa-workers/status?scope=onhand|inbound|outbound 展示对应 Worker 心跳徽标。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
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.config.settings import _normalize_env_name
|
||||||
from app.core.errors import ServiceUnavailableError
|
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__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
RPA_WORKER_OFFLINE_MESSAGE = "RPA Worker 未在线,请启动 Windows RPA 服务后重试"
|
RPA_WORKER_OFFLINE_MESSAGE = "RPA Worker 未在线,请启动 Windows RPA 服务后重试"
|
||||||
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE = "RPA Worker 心跳存储不可用,请检查 Redis 连接"
|
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE = "RPA Worker 心跳存储不可用,请检查 Redis 连接"
|
||||||
RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE = "货代上传 RPA 未就绪,请检查 Worker、凭据与共享目录后重试"
|
RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE = "货代上传 RPA 未就绪,请检查 Worker、凭据与共享目录后重试"
|
||||||
INVENTORY_EXPORT_CAPABILITY = "inventory_export"
|
# [PROMPT_UPDATE] 2026-10-16 freight_rpa 解耦批次 R:能力串随 Worker 侧(Task 12)切换——
|
||||||
FREIGHT_UPLOAD_CAPABILITY = "freight_upload"
|
# inventory_export→onhand_export、receipt_export→inbound_export;上传能力为 freight_rpa_upload;
|
||||||
RECEIPT_EXPORT_CAPABILITY = "receipt_export"
|
# worker_id 后缀判定 -receipt→-inbound(ps1 注入值随发布窗口改配,见 cutover runbook)。
|
||||||
# 收料 Worker 由 start_receipt_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-receipt。
|
ONHAND_EXPORT_CAPABILITY = "onhand_export"
|
||||||
RECEIPT_WORKER_ID_SUFFIX = "-receipt"
|
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_INDEX_KEY = "shipping:rpa:heartbeat:index"
|
||||||
_REDIS_WORKER_KEY_PREFIX = "shipping:rpa:heartbeat:worker:"
|
_REDIS_WORKER_KEY_PREFIX = "shipping:rpa:heartbeat:worker:"
|
||||||
_MEMORY_STORE: dict[str, dict[str, Any]] = {}
|
_MEMORY_STORE: dict[str, dict[str, Any]] = {}
|
||||||
@@ -51,8 +61,10 @@ _REASON_USER_HINTS: dict[str, str] = {
|
|||||||
"shared_scope_mismatch": "共享目录 scope 与后端配置不一致",
|
"shared_scope_mismatch": "共享目录 scope 与后端配置不一致",
|
||||||
"trigger_dir_not_writable": "trigger 目录不可写",
|
"trigger_dir_not_writable": "trigger 目录不可写",
|
||||||
"environment_mismatch": "Worker 环境与后端环境不一致",
|
"environment_mismatch": "Worker 环境与后端环境不一致",
|
||||||
"missing_inventory_export_capability": "Worker 未声明 inventory_export 能力",
|
"missing_onhand_export_capability": "Worker 未声明 onhand_export 能力",
|
||||||
"missing_freight_upload_capability": "Worker 未声明 freight_upload 能力",
|
"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",
|
"credential_key_missing": "未配置 FREIGHT_RPA_CREDENTIAL_KEY",
|
||||||
"upload_queue_dir_not_configured": "未配置货代上传队列目录",
|
"upload_queue_dir_not_configured": "未配置货代上传队列目录",
|
||||||
"upload_queue_dir_not_accessible": "货代上传队列目录不可访问",
|
"upload_queue_dir_not_accessible": "货代上传队列目录不可访问",
|
||||||
@@ -139,7 +151,7 @@ def shared_scope_id() -> str:
|
|||||||
explicit = _config_str("FREIGHT_RPA_SHARED_SCOPE_ID", "")
|
explicit = _config_str("FREIGHT_RPA_SHARED_SCOPE_ID", "")
|
||||||
if explicit:
|
if explicit:
|
||||||
return explicit
|
return explicit
|
||||||
trigger_dir = inventory_trigger_dir()
|
trigger_dir = onhand_trigger_dir()
|
||||||
if not trigger_dir:
|
if not trigger_dir:
|
||||||
return ""
|
return ""
|
||||||
for part in Path(trigger_dir).parts:
|
for part in Path(trigger_dir).parts:
|
||||||
@@ -362,7 +374,7 @@ def _verify_shared_trigger_mount(
|
|||||||
trigger_dir: Path | None, *, require_sentinel: bool = True,
|
trigger_dir: Path | None, *, require_sentinel: bool = True,
|
||||||
) -> tuple[bool, list[str]]:
|
) -> tuple[bool, list[str]]:
|
||||||
"""
|
"""
|
||||||
校验 trigger 目录可写;默认要求共享哨兵(库存与收料同口径)。
|
校验 trigger 目录可写;默认要求共享哨兵(库存与入站同口径)。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
trigger_dir: 共享 trigger 目录。
|
trigger_dir: 共享 trigger 目录。
|
||||||
@@ -400,18 +412,39 @@ def _verify_shared_trigger_mount(
|
|||||||
return not reasons, reasons
|
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、
|
优先认 <主机名>-inbound(ps1 注入);兼容未注入 FREIGHT_RPA_WORKER_ID、
|
||||||
回退为 <主机名>-<pid> 的进程——用心跳 trigger_dir 与收料目录对齐判定。
|
回退为 <主机名>-<pid> 的进程——用心跳 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
|
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、
|
||||||
|
回退为 <主机名>-<pid> 的进程——用心跳 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()
|
actual = str(worker.get("trigger_dir") or "").strip()
|
||||||
if expected is None or not actual:
|
if expected is None or not actual:
|
||||||
return False
|
return False
|
||||||
@@ -437,7 +470,7 @@ def _worker_is_eligible(
|
|||||||
backend_env: str,
|
backend_env: str,
|
||||||
ttl_seconds: int,
|
ttl_seconds: int,
|
||||||
now: float,
|
now: float,
|
||||||
required_capability: str = INVENTORY_EXPORT_CAPABILITY,
|
required_capability: str = ONHAND_EXPORT_CAPABILITY,
|
||||||
) -> tuple[bool, list[str]]:
|
) -> tuple[bool, list[str]]:
|
||||||
"""
|
"""
|
||||||
判断单 Worker 是否满足心跳新鲜度、能力声明与环境/scope 隔离。
|
判断单 Worker 是否满足心跳新鲜度、能力声明与环境/scope 隔离。
|
||||||
@@ -447,7 +480,7 @@ def _worker_is_eligible(
|
|||||||
backend_env: 后端归一环境(dev/test/prod)。
|
backend_env: 后端归一环境(dev/test/prod)。
|
||||||
ttl_seconds: 心跳 TTL。
|
ttl_seconds: 心跳 TTL。
|
||||||
now: 当前 epoch 秒。
|
now: 当前 epoch 秒。
|
||||||
required_capability: 必选能力(inventory_export / freight_upload)。
|
required_capability: 必选能力(onhand_export / inbound_export / outbound_export / freight_rpa_upload)。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
(是否合格, 不合格原因列表)。
|
(是否合格, 不合格原因列表)。
|
||||||
@@ -461,10 +494,7 @@ def _worker_is_eligible(
|
|||||||
|
|
||||||
capabilities = _parse_capabilities(worker.get("capabilities"))
|
capabilities = _parse_capabilities(worker.get("capabilities"))
|
||||||
if required_capability and required_capability not in capabilities:
|
if required_capability and required_capability not in capabilities:
|
||||||
if required_capability == FREIGHT_UPLOAD_CAPABILITY:
|
reasons.append(_missing_capability_reason(required_capability))
|
||||||
reasons.append("missing_freight_upload_capability")
|
|
||||||
else:
|
|
||||||
reasons.append("missing_inventory_export_capability")
|
|
||||||
|
|
||||||
worker_env = str(worker.get("environment") or "").strip().lower()
|
worker_env = str(worker.get("environment") or "").strip().lower()
|
||||||
if worker_env and worker_env != backend_env:
|
if worker_env and worker_env != backend_env:
|
||||||
@@ -477,6 +507,11 @@ def _worker_is_eligible(
|
|||||||
return not reasons, reasons
|
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:
|
def _summarize_reasons(reasons: list[str]) -> str:
|
||||||
hints: list[str] = []
|
hints: list[str] = []
|
||||||
for reason in reasons:
|
for reason in reasons:
|
||||||
@@ -512,8 +547,8 @@ def _check_rpa_worker_ready_for_capability(
|
|||||||
trigger_dir: 待校验的共享 trigger 目录。
|
trigger_dir: 待校验的共享 trigger 目录。
|
||||||
required_capability: 必选 Worker 能力;空字符串表示不校验能力。
|
required_capability: 必选 Worker 能力;空字符串表示不校验能力。
|
||||||
extra_reasons: 调用方预检附加原因(凭据/队列等)。
|
extra_reasons: 调用方预检附加原因(凭据/队列等)。
|
||||||
worker_predicate: 可选过滤(如仅收料 Worker);不匹配的心跳不进入列表。
|
worker_predicate: 可选过滤(如仅入站 Worker);不匹配的心跳不进入列表。
|
||||||
require_sentinel: 是否要求共享哨兵(库存/收料同口径均 True)。
|
require_sentinel: 是否要求共享哨兵(库存/入站同口径均 True)。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
RpaWorkerReadiness。
|
RpaWorkerReadiness。
|
||||||
@@ -601,7 +636,7 @@ def _check_rpa_worker_ready_for_capability(
|
|||||||
message, detail_message = "ready", "ready"
|
message, detail_message = "ready", "ready"
|
||||||
else:
|
else:
|
||||||
failure = RpaWorkerReadiness(ready=False, message="", reasons=sorted(set(reasons)))
|
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)
|
detail = _summarize_reasons(failure.reasons)
|
||||||
message = RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE
|
message = RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE
|
||||||
detail_message = f"{message}({detail})" if detail else message
|
detail_message = f"{message}({detail})" if detail else message
|
||||||
@@ -623,41 +658,41 @@ def check_inventory_rpa_worker_ready() -> RpaWorkerReadiness:
|
|||||||
核心逻辑:Redis 可用、共享哨兵有效、最近心跳在 TTL 内、环境/scope 匹配。
|
核心逻辑:Redis 可用、共享哨兵有效、最近心跳在 TTL 内、环境/scope 匹配。
|
||||||
"""
|
"""
|
||||||
return _check_rpa_worker_ready_for_capability(
|
return _check_rpa_worker_ready_for_capability(
|
||||||
trigger_dir=inventory_trigger_dir(),
|
trigger_dir=onhand_trigger_dir(),
|
||||||
required_capability=INVENTORY_EXPORT_CAPABILITY,
|
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 对齐);要求
|
核心逻辑:仅看 inbound Worker 心跳(*-inbound 或 trigger_dir 对齐);要求
|
||||||
receipt_export 能力;校验收料 trigger 目录可写;与库存同口径要求共享哨兵。
|
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(
|
return _check_rpa_worker_ready_for_capability(
|
||||||
trigger_dir=receipt_trigger_dir(),
|
trigger_dir=inbound_trigger_dir(),
|
||||||
required_capability=RECEIPT_EXPORT_CAPABILITY,
|
required_capability=INBOUND_EXPORT_CAPABILITY,
|
||||||
worker_predicate=is_receipt_rpa_worker,
|
worker_predicate=is_inbound_rpa_worker,
|
||||||
require_sentinel=True,
|
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,
|
核心逻辑:镜像 assert_inventory_rpa_worker_ready;离线则抛 ServiceUnavailableError,
|
||||||
排程不得进入 awaiting_receipt_rpa。
|
排程不得进入 awaiting_inbound_rpa。
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
ServiceUnavailableError: worker 未就绪、共享目录无效或心跳存储不可用。
|
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:
|
if result.ready:
|
||||||
return
|
return
|
||||||
code = 'RPA.WORKER_OFFLINE'
|
code = 'RPA.WORKER_OFFLINE'
|
||||||
@@ -677,7 +712,61 @@ def assert_receipt_rpa_worker_ready() -> None:
|
|||||||
'detail_message': result.detail_message,
|
'detail_message': result.detail_message,
|
||||||
'checked_at': result.checked_at,
|
'checked_at': result.checked_at,
|
||||||
'shared_scope_id': shared_scope_id(),
|
'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:
|
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] = []
|
reasons: list[str] = []
|
||||||
credential_key = _config_str("FREIGHT_RPA_CREDENTIAL_KEY", "")
|
credential_key = _config_str("FREIGHT_RPA_CREDENTIAL_KEY", "")
|
||||||
@@ -722,16 +811,16 @@ def check_freight_upload_rpa_ready() -> RpaWorkerReadiness:
|
|||||||
检查货代上传 RPA 是否可安全自动触发。
|
检查货代上传 RPA 是否可安全自动触发。
|
||||||
|
|
||||||
核心逻辑:凭据/队列/回调基址预检 + 上传 trigger 共享挂载 + Worker 心跳与
|
核心逻辑:凭据/队列/回调基址预检 + 上传 trigger 共享挂载 + Worker 心跳与
|
||||||
freight_upload 能力 + 环境/scope 隔离。Mock 模式跳过心跳。
|
freight_rpa_upload 能力 + 环境/scope 隔离。Mock 模式跳过心跳。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
RpaWorkerReadiness(含 reasons 供建单前/启动日志展示)。
|
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(
|
return _check_rpa_worker_ready_for_capability(
|
||||||
trigger_dir=upload_trigger_dir(),
|
trigger_dir=upload_trigger_dir(),
|
||||||
required_capability=FREIGHT_UPLOAD_CAPABILITY,
|
required_capability=FREIGHT_RPA_UPLOAD_CAPABILITY,
|
||||||
extra_reasons=_freight_upload_config_reasons(),
|
extra_reasons=_freight_upload_config_reasons(),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -757,7 +846,7 @@ def assert_freight_upload_rpa_ready() -> None:
|
|||||||
result.reasons,
|
result.reasons,
|
||||||
result.detail_message,
|
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(
|
raise ServiceUnavailableError(
|
||||||
result.message,
|
result.message,
|
||||||
@@ -768,7 +857,7 @@ def assert_freight_upload_rpa_ready() -> None:
|
|||||||
"checked_at": result.checked_at,
|
"checked_at": result.checked_at,
|
||||||
"shared_scope_id": shared_scope_id(),
|
"shared_scope_id": shared_scope_id(),
|
||||||
"trigger_dir": str(upload_trigger_dir() or ""),
|
"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,
|
"detail_message": result.detail_message,
|
||||||
"checked_at": result.checked_at,
|
"checked_at": result.checked_at,
|
||||||
"shared_scope_id": shared_scope_id(),
|
"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:
|
Args:
|
||||||
scope: inventory(默认)或 receipt。
|
scope: onhand(默认,库存 RPA 工作台)、inbound(入站)或 outbound(出站);
|
||||||
|
取值为后端内部与前端查询参数约定,与 Worker 上报能力标识无关。
|
||||||
"""
|
"""
|
||||||
from app.services.shipping_notice.rpa import upload_trigger_dir
|
from app.services.freight_rpa.upload.trigger_io import upload_trigger_dir
|
||||||
from app.services.shipping_notice.receipt_rpa import receipt_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()
|
normalized = str(scope or "onhand").strip().lower()
|
||||||
if normalized == "receipt":
|
if normalized == "inbound":
|
||||||
readiness = check_receipt_rpa_worker_ready()
|
readiness = check_inbound_rpa_worker_ready()
|
||||||
trigger_path = str(receipt_trigger_dir() or "")
|
trigger_path = str(inbound_trigger_dir() or "")
|
||||||
|
elif normalized == "outbound":
|
||||||
|
readiness = check_outbound_rpa_worker_ready()
|
||||||
|
trigger_path = str(outbound_trigger_dir() or "")
|
||||||
else:
|
else:
|
||||||
readiness = check_inventory_rpa_worker_ready()
|
readiness = check_inventory_rpa_worker_ready()
|
||||||
trigger_path = str(inventory_trigger_dir() or "")
|
trigger_path = str(onhand_trigger_dir() or "")
|
||||||
normalized = "inventory"
|
normalized = "onhand"
|
||||||
|
|
||||||
freight_readiness = check_freight_upload_rpa_ready()
|
freight_readiness = check_freight_upload_rpa_ready()
|
||||||
ttl_seconds = _heartbeat_ttl_seconds()
|
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 ""),
|
"upload_trigger_dir": str(upload_trigger_dir() or ""),
|
||||||
"reasons": readiness.reasons,
|
"reasons": readiness.reasons,
|
||||||
"workers": workers,
|
"workers": workers,
|
||||||
"freight_upload": {
|
"freight_rpa_upload": {
|
||||||
"ready": freight_readiness.ready,
|
"ready": freight_readiness.ready,
|
||||||
"message": freight_readiness.message,
|
"message": freight_readiness.message,
|
||||||
"detail_message": freight_readiness.detail_message,
|
"detail_message": freight_readiness.detail_message,
|
||||||
+3
-3
@@ -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 离线/恢复主动告警(企微 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 仅作缓存同步。
|
逻辑:由 schedule worker 每轮循环调用;默认 ALERT_ENABLED=false 不发送;DB 为告警状态权威源,Redis 仅作缓存同步。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -21,7 +21,7 @@ from sqlalchemy.exc import IntegrityError
|
|||||||
from app import db
|
from app import db
|
||||||
from app.models import AppSetting, User
|
from app.models import AppSetting, User
|
||||||
from app.services.permission_roles.service import list_platform_admin_users
|
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_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
|
||||||
RPA_WORKER_OFFLINE_MESSAGE,
|
RPA_WORKER_OFFLINE_MESSAGE,
|
||||||
_heartbeat_check_required,
|
_heartbeat_check_required,
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""inbound:入站 RPA。"""
|
||||||
@@ -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'}]
|
||||||
@@ -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 轮询 <root>/*.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)
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""onhand:在手库存 RPA。"""
|
||||||
+14
-12
@@ -1,9 +1,11 @@
|
|||||||
"""
|
"""
|
||||||
services/shipping_notice/rpa_attempts.py
|
services/freight_rpa/onhand/attempts.py
|
||||||
|
|
||||||
用途:统计任务的 RPA 库存导出与货代上传重试次数,并返回统一上限。
|
用途:统计任务的 onhand(库存)RPA 导出与货代上传重试次数,并返回统一上限。
|
||||||
依赖:ShippingNotice、ShippingTaskEvent 模型与事件查询逻辑。
|
依赖:ShippingNotice、ShippingTaskEvent 模型与事件查询逻辑(仅 models,无业务编排 import)。
|
||||||
逻辑:由 inventory_rpa_workflow、fulfillment_workflow 等模块调用本文件,决定是否还能继续触发 RPA 重试。
|
逻辑:由 shipping_notice 的 onhand_rpa_workflow、fulfillment_workflow 等模块调用本文件,
|
||||||
|
决定是否还能继续触发 RPA 重试;事件类型字符串(onhand_rpa_* 等)是落库数据值,
|
||||||
|
随 models 命名一并留待批次 S 处理,本模块只改包归属与标识符词根。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -15,15 +17,15 @@ from app.models import ShippingNotice, ShippingTaskEvent
|
|||||||
|
|
||||||
DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS = 3
|
DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS = 3
|
||||||
|
|
||||||
_INVENTORY_SUCCESS_EVENTS = {
|
_ONHAND_SUCCESS_EVENTS = {
|
||||||
"inventory_uploaded",
|
"inventory_uploaded",
|
||||||
"inventory_parsed",
|
"inventory_parsed",
|
||||||
"inventory_rpa_drop_ingested",
|
"onhand_rpa_drop_ingested",
|
||||||
"inventory_rpa_ready",
|
"onhand_rpa_ready",
|
||||||
"inventory_template_mapping_used",
|
"inventory_template_mapping_used",
|
||||||
}
|
}
|
||||||
|
|
||||||
_INVENTORY_ATTEMPT_RESET_EVENTS = _INVENTORY_SUCCESS_EVENTS | {
|
_ONHAND_ATTEMPT_RESET_EVENTS = _ONHAND_SUCCESS_EVENTS | {
|
||||||
"decision_retry_rpa",
|
"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 库存导出触发/失败次数。"""
|
"""统计自上次库存成功事件以来的 RPA 库存导出触发/失败次数。"""
|
||||||
if not task or task.id is None:
|
if not task or task.id is None:
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
last_reset = (
|
last_reset = (
|
||||||
ShippingTaskEvent.query.filter_by(task_id=task.id)
|
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())
|
.order_by(ShippingTaskEvent.id.desc())
|
||||||
.first()
|
.first()
|
||||||
)
|
)
|
||||||
since: datetime | None = last_reset.created_at if last_reset else None
|
since: datetime | None = last_reset.created_at if last_reset else None
|
||||||
|
|
||||||
triggered = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
|
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(
|
failed = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
|
||||||
ShippingTaskEvent.event_type == "inventory_rpa_failed"
|
ShippingTaskEvent.event_type == "onhand_rpa_failed"
|
||||||
)
|
)
|
||||||
if since:
|
if since:
|
||||||
triggered = triggered.filter(ShippingTaskEvent.created_at >= since)
|
triggered = triggered.filter(ShippingTaskEvent.created_at >= since)
|
||||||
+11
-9
@@ -1,9 +1,11 @@
|
|||||||
"""
|
"""
|
||||||
services/shipping_notice/inventory_rpa_callback_cleanup.py
|
services/freight_rpa/onhand/callback_cleanup.py
|
||||||
|
|
||||||
用途:RPA callback drop 区文件归档失败后的持久化重试队列、隔离与消费标记。
|
用途:RPA callback drop 区文件归档失败后的持久化重试队列、隔离与消费标记
|
||||||
依赖:rpa.inventory_drop_dir / inventory_processed_dir、json、uuid、Flask current_app。
|
(Task 9 自 shipping_notice.onhand_rpa_callback_cleanup 整体平移,纯协议文件 IO、零业务落盘)。
|
||||||
逻辑:commit 后尝试归档;失败则移入 .hxops_quarantine 并入队;scheduler/worker 启动时定期消费队列。
|
依赖: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
|
from __future__ import annotations
|
||||||
@@ -18,7 +20,7 @@ from typing import Any
|
|||||||
|
|
||||||
from flask import current_app
|
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"
|
_CALLBACK_CONSUMED_SUFFIX = ".hxops_consumed"
|
||||||
_CLEANUP_QUEUE_DIRNAME = ".cleanup_queue"
|
_CLEANUP_QUEUE_DIRNAME = ".cleanup_queue"
|
||||||
@@ -30,7 +32,7 @@ _LOGGER = logging.getLogger(__name__)
|
|||||||
|
|
||||||
def callback_cleanup_queue_dir() -> Path | None:
|
def callback_cleanup_queue_dir() -> Path | None:
|
||||||
"""drop 目录下 callback 归档重试队列路径。"""
|
"""drop 目录下 callback 归档重试队列路径。"""
|
||||||
drop = inventory_drop_dir()
|
drop = onhand_drop_dir()
|
||||||
if not drop:
|
if not drop:
|
||||||
return None
|
return None
|
||||||
return drop / _CLEANUP_QUEUE_DIRNAME
|
return drop / _CLEANUP_QUEUE_DIRNAME
|
||||||
@@ -38,7 +40,7 @@ def callback_cleanup_queue_dir() -> Path | None:
|
|||||||
|
|
||||||
def callback_cleanup_failed_dir() -> Path | None:
|
def callback_cleanup_failed_dir() -> Path | None:
|
||||||
"""超过最大重试次数的 cleanup job 隔离目录。"""
|
"""超过最大重试次数的 cleanup job 隔离目录。"""
|
||||||
drop = inventory_drop_dir()
|
drop = onhand_drop_dir()
|
||||||
if not drop:
|
if not drop:
|
||||||
return None
|
return None
|
||||||
return drop / _CLEANUP_FAILED_DIRNAME
|
return drop / _CLEANUP_FAILED_DIRNAME
|
||||||
@@ -49,7 +51,7 @@ def callback_quarantine_dir() -> Path | None:
|
|||||||
Worker 不应扫描的 callback 隔离目录(drop 根目录外的子目录)。
|
Worker 不应扫描的 callback 隔离目录(drop 根目录外的子目录)。
|
||||||
归档失败时 HXOPS 将文件原子移入此处,避免重复上报。
|
归档失败时 HXOPS 将文件原子移入此处,避免重复上报。
|
||||||
"""
|
"""
|
||||||
drop = inventory_drop_dir()
|
drop = onhand_drop_dir()
|
||||||
if not drop:
|
if not drop:
|
||||||
return None
|
return None
|
||||||
return drop / _QUARANTINE_DIRNAME
|
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()
|
callback_raw = str(payload.get("callback_path") or "").strip()
|
||||||
processed_raw = str(payload.get("processed_dir") or "").strip()
|
processed_raw = str(payload.get("processed_dir") or "").strip()
|
||||||
callback_path = Path(callback_raw) if callback_raw else None
|
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:
|
if callback_path is None or processed_dir is None:
|
||||||
try:
|
try:
|
||||||
job_path.unlink()
|
job_path.unlink()
|
||||||
@@ -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()
|
||||||
@@ -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)
|
||||||
@@ -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
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""outbound:出站 RPA。"""
|
||||||
@@ -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}
|
||||||
@@ -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 轮询 <root>/*.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)
|
||||||
+90
-73
@@ -1,9 +1,16 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/services/shipping_notice/inventory_parsing_profile.py
|
services/freight_rpa/parsing_profile.py
|
||||||
|
|
||||||
用途:管理可跨库存源复用的版本化库存解析 Profile,并为运行期提供确定性解析定义。
|
用途:管理货代「报表规则」(FreightRpaParsingProfile)的草稿/发布与运行期定义读取。
|
||||||
依赖:ShippingInventoryParsingProfile、ShippingInventorySource、ShippingOrderField、inventory_mapping。
|
purpose=onhand 走库存字段目录 + match_keys;purpose=inbound/outbound 走调拨
|
||||||
逻辑:管理员保存草稿并发布不可变版本;库存源仅绑定 published Profile,解析链直接使用定义中的列映射与订单字段匹配键。
|
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
|
from __future__ import annotations
|
||||||
@@ -18,47 +25,49 @@ from sqlalchemy import func
|
|||||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||||
from app.extensions import db
|
from app.extensions import db
|
||||||
from app.models import (
|
from app.models import (
|
||||||
ShippingInventoryField,
|
FreightRpaOnhandField,
|
||||||
ShippingInventoryParsingProfile,
|
FreightRpaOnhandReportConfig,
|
||||||
ShippingInventorySource,
|
FreightRpaParsingProfile,
|
||||||
ShippingInventoryStructureAnalysis,
|
FreightRpaOnhandStructureAnalysis,
|
||||||
ShippingOrderField,
|
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 并确认均为可用于新方案的启用库存业务字段。"""
|
"""解析字段目录 ID 并确认均为可用于新方案的启用库存业务字段。"""
|
||||||
field_ids: list[int] = []
|
field_ids: list[int] = []
|
||||||
for raw_id in field_mapping:
|
for raw_id in field_mapping:
|
||||||
try:
|
try:
|
||||||
field_id = int(raw_id)
|
field_id = int(raw_id)
|
||||||
except (TypeError, ValueError) as exc:
|
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:
|
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)
|
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'}
|
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)):
|
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
|
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'}
|
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'}
|
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:
|
if not match_ids or len(quantity_ids) != 1:
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
'Parsing profile requires at least one match field and exactly one inventory quantity field',
|
'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
|
return match_ids | quantity_ids
|
||||||
|
|
||||||
|
|
||||||
# 异动(movement)用途的定死字段端点与必需字段集(领域定死,不依赖库存字段目录)。
|
# 入站(inbound)用途的定死字段端点与必需字段集(领域定死,不依赖库存字段目录)。
|
||||||
def _required_movement_field_ids(definition: dict[str, Any]) -> set[str]:
|
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
|
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
|
||||||
|
|
||||||
movement_codes = {field.code for field in 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:
|
if unknown:
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
f'Movement parsing profile references unknown field: {sorted(unknown)}',
|
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}
|
missing = {code for code in ('doc_no', 'material_code', 'quantity', 'movement_date') if code not in mapped_codes}
|
||||||
if missing:
|
if missing:
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
f'Movement parsing profile requires doc_no/material_code/quantity/movement_date: {sorted(missing)}',
|
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
|
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 到来源表头的映射及订单明细匹配键,禁止自由脚本。
|
"""校验字段目录 ID 到来源表头的映射及订单明细匹配键,禁止自由脚本。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
raw: 解析定义对象。
|
raw: 解析定义对象。
|
||||||
purpose: 'inventory'(沿用库存字段目录与 match_keys)或
|
purpose: 'onhand'(库存字段目录 + match_keys)或
|
||||||
'movement'(端点用定死 MOVEMENT_FIELDS,无 match_keys)。
|
'inbound'/'outbound'(端点用定死 MOVEMENT_FIELDS,无 match_keys)。
|
||||||
"""
|
"""
|
||||||
if not isinstance(raw, dict):
|
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')
|
field_mapping = raw.get('field_mapping')
|
||||||
if not isinstance(field_mapping, dict) or not 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()):
|
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')
|
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):
|
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)
|
_required_movement_field_ids(raw)
|
||||||
return {
|
return {
|
||||||
'sheet_name': str(raw.get('sheet_name') or '').strip() or None,
|
'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)
|
_required_catalog_field_ids(catalog_fields)
|
||||||
match_keys = raw.get('match_keys')
|
match_keys = raw.get('match_keys')
|
||||||
if not isinstance(match_keys, list) or not 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]] = []
|
normalized_keys: list[dict[str, str]] = []
|
||||||
seen_order_fields: set[str] = set()
|
seen_order_fields: set[str] = set()
|
||||||
seen_inventory_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'
|
field is None or field.status != 'active' or field.scope != 'line'
|
||||||
or inventory is None or inventory.usage_type != 'match_identity'
|
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:
|
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_order_fields.add(field.id)
|
||||||
seen_inventory_fields.add(inventory_field)
|
seen_inventory_fields.add(inventory_field)
|
||||||
normalized_keys.append({'order_field_id': field.id, 'inventory_field_id': 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],
|
definition: dict[str, Any],
|
||||||
*,
|
*,
|
||||||
file_format: str,
|
file_format: str,
|
||||||
) -> ShippingInventoryStructureAnalysis:
|
) -> FreightRpaOnhandStructureAnalysis:
|
||||||
"""校验草稿仅能使用已持久化样本证据中的工作表、表头和来源栏位。"""
|
"""校验草稿仅能使用已持久化样本证据中的工作表、表头和来源栏位。"""
|
||||||
try:
|
try:
|
||||||
analysis_id = int(sample_analysis_id)
|
analysis_id = int(sample_analysis_id)
|
||||||
except (TypeError, ValueError) as exc:
|
except (TypeError, ValueError) as exc:
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
'Parsing profile requires sample analysis evidence',
|
'Parsing profile requires sample analysis evidence',
|
||||||
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED',
|
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_REQUIRED',
|
||||||
) from exc
|
) 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:
|
if analysis is None or analysis.analysis_status != 'ready' or analysis.file_format != file_format:
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
'Parsing profile sample analysis evidence is unavailable',
|
'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 {}
|
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
|
||||||
candidates = structure.get('candidates') if isinstance(structure.get('candidates'), list) 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):
|
if not isinstance(selected, dict):
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
'Parsing profile worksheet or header row is not present in sample evidence',
|
'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()}
|
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()):
|
if any(str(header or '').strip() not in headers for header in (definition.get('field_mapping') or {}).values()):
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
'Parsing profile mapping is not present in sample evidence',
|
'Parsing profile mapping is not present in sample evidence',
|
||||||
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID',
|
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID',
|
||||||
)
|
)
|
||||||
duplicates = {
|
duplicates = {
|
||||||
str(column.get('header') or '').strip()
|
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()):
|
if any(str(header).strip() in duplicates for header in (definition.get('field_mapping') or {}).values()):
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
'Parsing profile mapping uses duplicate sample headers',
|
'Parsing profile mapping uses duplicate sample headers',
|
||||||
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID',
|
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID',
|
||||||
)
|
)
|
||||||
return analysis
|
return analysis
|
||||||
|
|
||||||
|
|
||||||
def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]:
|
def payload(profile: FreightRpaParsingProfile) -> dict[str, Any]:
|
||||||
"""序列化解析 Profile 管理 DTO。"""
|
"""序列化解析 Profile 管理 DTO。"""
|
||||||
sample_analysis = profile.sample_analysis
|
sample_analysis = profile.sample_analysis
|
||||||
return {
|
return {
|
||||||
@@ -211,49 +220,49 @@ def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]:
|
|||||||
|
|
||||||
def list_profiles() -> list[dict[str, Any]]:
|
def list_profiles() -> list[dict[str, Any]]:
|
||||||
"""列出全部解析 Profile 版本。"""
|
"""列出全部解析 Profile 版本。"""
|
||||||
return [payload(item) for item in ShippingInventoryParsingProfile.query.order_by(
|
return [payload(item) for item in FreightRpaParsingProfile.query.order_by(
|
||||||
ShippingInventoryParsingProfile.profile_code, ShippingInventoryParsingProfile.version.desc(),
|
FreightRpaParsingProfile.profile_code, FreightRpaParsingProfile.version.desc(),
|
||||||
).all()]
|
).all()]
|
||||||
|
|
||||||
|
|
||||||
def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
|
def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
|
||||||
"""创建或更新解析 Profile 草稿;必须绑定样本证据,published 版本不可原地修改。"""
|
"""创建或更新解析 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:
|
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':
|
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()
|
code = str(data.get('profile_code') or '').strip().upper()
|
||||||
if not code:
|
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:
|
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:
|
if profile is None:
|
||||||
next_version = int(db.session.query(func.max(ShippingInventoryParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1
|
next_version = int(db.session.query(func.max(FreightRpaParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1
|
||||||
profile = ShippingInventoryParsingProfile(profile_code=code, version=next_version, created_by=actor_id)
|
profile = FreightRpaParsingProfile(profile_code=code, version=next_version, created_by=actor_id)
|
||||||
db.session.add(profile)
|
db.session.add(profile)
|
||||||
purpose = str(data.get('purpose') or profile.purpose or 'inventory').strip().lower()
|
purpose = str(data.get('purpose') or profile.purpose or 'onhand').strip().lower()
|
||||||
if purpose not in {'inventory', 'movement'}:
|
if purpose not in {'onhand', 'inbound', 'outbound'}:
|
||||||
raise ValidationError('purpose is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
raise ValidationError('purpose is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||||
if profile_id and purpose != profile.purpose:
|
if profile_id and purpose != profile.purpose:
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
'Draft parsing profile purpose is immutable',
|
'Draft parsing profile purpose is immutable',
|
||||||
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
|
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
|
||||||
)
|
)
|
||||||
profile.purpose = purpose
|
profile.purpose = purpose
|
||||||
profile.display_name = str(data.get('display_name') or code).strip()
|
profile.display_name = str(data.get('display_name') or code).strip()
|
||||||
requested_file_format = str(data.get('file_format') or 'xlsx').lower()
|
requested_file_format = str(data.get('file_format') or 'xlsx').lower()
|
||||||
if requested_file_format not in {'xls', 'xlsx', 'csv'}:
|
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:
|
if profile_id and requested_file_format != profile.file_format:
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
'Draft parsing profile file format is immutable',
|
'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
|
profile.file_format = requested_file_format
|
||||||
definition = _validate_definition(data.get('definition'), purpose=purpose)
|
definition = _validate_definition(data.get('definition'), purpose=purpose)
|
||||||
if profile.file_format == 'csv' and definition.get('sheet_name'):
|
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(
|
sample_analysis = _require_sample_evidence(
|
||||||
data.get('sample_analysis_id', profile.sample_analysis_id), definition, file_format=profile.file_format,
|
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')):
|
if not bool(data.get('confirm_sample_replacement')):
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
'Replacing inventory sample evidence requires confirmation',
|
'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 = list(profile.sample_evidence_history_json or [])
|
||||||
history.append({
|
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]:
|
def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||||
"""发布解析 Profile;既有 published 版本继续供已绑定库存源稳定使用。"""
|
"""发布解析 Profile;既有 published 版本继续供已绑定库存源稳定使用。"""
|
||||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
|
profile = db.session.get(FreightRpaParsingProfile, profile_id)
|
||||||
if profile is None:
|
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':
|
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(
|
_require_sample_evidence(
|
||||||
profile.sample_analysis_id, profile.definition_json or {}, file_format=profile.file_format,
|
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
|
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||||
|
|
||||||
# movement 用途无订单匹配键(端点为定死异动字段),跳过订单 Schema 契约校验;inventory 维持原约束。
|
# inbound/outbound 无订单匹配键(端点为定死异动字段),跳过订单 Schema 契约校验;onhand 维持原约束。
|
||||||
referenced_field_ids = {
|
referenced_field_ids = {
|
||||||
str(item.get('order_field_id') or '')
|
str(item.get('order_field_id') or '')
|
||||||
for item in (profile.definition_json or {}).get('match_keys', [])
|
for item in (profile.definition_json or {}).get('match_keys', [])
|
||||||
if isinstance(item, dict)
|
if isinstance(item, dict)
|
||||||
}
|
}
|
||||||
if profile.purpose != 'movement':
|
if profile.purpose == 'onhand':
|
||||||
published_field_ids = {
|
published_field_ids = {
|
||||||
str(item.get('field_id') or '')
|
str(item.get('field_id') or '')
|
||||||
for item in order_schema_service.get_published_contract().get('fields', [])
|
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:
|
if not referenced_field_ids or not referenced_field_ids <= published_field_ids:
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
'Parsing profile match keys must reference the current published order schema',
|
'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()
|
encoded = json.dumps(profile.definition_json, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
|
||||||
profile.checksum = hashlib.sha256(encoded).hexdigest()
|
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]:
|
def retire(profile_id: int) -> dict[str, Any]:
|
||||||
"""退役无库存源引用的 published Profile,避免使现有 Source 静默失效。"""
|
"""退役无库存源/入站/出站报表配置引用的 published Profile,避免使现有绑定静默失效。"""
|
||||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
|
profile = db.session.get(FreightRpaParsingProfile, profile_id)
|
||||||
if profile is None:
|
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':
|
if profile.status != 'published':
|
||||||
raise ConflictError('Only published parsing profile can be retired', code='SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_INVALID')
|
raise ConflictError('Only published parsing profile can be retired', code='SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_INVALID')
|
||||||
if ShippingInventorySource.query.filter_by(parsing_profile_id=profile.id).count():
|
# s18 起库存站点绑定归 FreightRpaOnhandReportConfig 配置行,站点行不再承载该外键。
|
||||||
raise ConflictError('Rebind inventory sources before retiring profile', code='SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_BLOCKED')
|
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'
|
profile.status = 'retired'
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return payload(profile)
|
return payload(profile)
|
||||||
@@ -330,18 +345,20 @@ def retire(profile_id: int) -> dict[str, Any]:
|
|||||||
|
|
||||||
def delete_draft(profile_id: int) -> None:
|
def delete_draft(profile_id: int) -> None:
|
||||||
"""删除从未发布的解析 Profile 草稿。"""
|
"""删除从未发布的解析 Profile 草稿。"""
|
||||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
|
profile = db.session.get(FreightRpaParsingProfile, profile_id)
|
||||||
if profile is None:
|
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':
|
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.delete(profile)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
|
|
||||||
def require_source_profile(source: Any) -> ShippingInventoryParsingProfile:
|
def require_source_profile(source: Any) -> FreightRpaParsingProfile:
|
||||||
"""读取库存源绑定的 published 解析 Profile;缺失或非发布状态时阻断自动解析。"""
|
"""读取库存源绑定的 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':
|
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
|
return profile
|
||||||
@@ -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',
|
||||||
|
]
|
||||||
@@ -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)
|
||||||
@@ -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
|
||||||
@@ -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()
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""upload:货代上传 RPA。"""
|
||||||
@@ -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
|
||||||
@@ -108,7 +108,7 @@ def archive_snapshot(
|
|||||||
"""归档一份对象并持久化索引 + 审计。
|
"""归档一份对象并持久化索引 + 审计。
|
||||||
|
|
||||||
Args:
|
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)。
|
object_id: 业务对象编号(matching_no / run_no)。
|
||||||
data: 待归档字节。
|
data: 待归档字节。
|
||||||
original_filename: 原始文件名。
|
original_filename: 原始文件名。
|
||||||
|
|||||||
@@ -32,8 +32,9 @@ class AutoTransferOutcome:
|
|||||||
def run_auto_transfer(*, business_date: str, deps: TransferDeps,
|
def run_auto_transfer(*, business_date: str, deps: TransferDeps,
|
||||||
source_codes: list[str] | None = None,
|
source_codes: list[str] | None = None,
|
||||||
recover_history: bool = True,
|
recover_history: bool = True,
|
||||||
receipt_date_from: str | None = None,
|
movement_date_from: str | None = None,
|
||||||
receipt_date_to: str | None = None,
|
movement_date_to: str | None = None,
|
||||||
|
transfer_type: str | None = None,
|
||||||
sender: WeComSender | None = None,
|
sender: WeComSender | None = None,
|
||||||
recipients: list[str] | None = None) -> AutoTransferOutcome:
|
recipients: list[str] | None = None) -> AutoTransferOutcome:
|
||||||
"""执行一次自动调拨排程。
|
"""执行一次自动调拨排程。
|
||||||
@@ -46,8 +47,10 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps,
|
|||||||
deps: 注入依赖。
|
deps: 注入依赖。
|
||||||
source_codes: 来源实例列表(缺省全部启用来源)。
|
source_codes: 来源实例列表(缺省全部启用来源)。
|
||||||
recover_history: 是否执行历史恢复。
|
recover_history: 是否执行历史恢复。
|
||||||
receipt_date_from / receipt_date_to: 可选收料日期范围(测试/排障缩小
|
movement_date_from / movement_date_to: 可选异动日期范围(测试/排障缩小
|
||||||
匹配面;留空=全部成熟积压;非法范围由匹配层抛 ValidationError)。
|
匹配面;留空=全部积压;非法范围由匹配层抛 ValidationError)。
|
||||||
|
transfer_type: 调拨类型编码(D8 匹配创建必填——排程任务参数承载;
|
||||||
|
缺省 None 时匹配层 fail-closed 抛 TRANSFER_TYPE_REQUIRED)。
|
||||||
sender / recipients: 企微通知(None 则跳过通知;run_no 为空时不发送)。
|
sender / recipients: 企微通知(None 则跳过通知;run_no 为空时不发送)。
|
||||||
Returns:
|
Returns:
|
||||||
AutoTransferOutcome;空数据日时 run_no/run_status 均为 None 且 errors 为空。
|
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 [],
|
source_codes=source_codes or [],
|
||||||
business_date=business_date,
|
business_date=business_date,
|
||||||
deps=deps,
|
deps=deps,
|
||||||
receipt_date_from=receipt_date_from,
|
movement_date_from=movement_date_from,
|
||||||
receipt_date_to=receipt_date_to,
|
movement_date_to=movement_date_to,
|
||||||
|
transfer_type=transfer_type,
|
||||||
)
|
)
|
||||||
# [STEP 2] 空数据日跳过执行:匹配后无可执行行(含恢复后仍为 0)时不建票、
|
# [STEP 2] 空数据日跳过执行:匹配后无可执行行(含恢复后仍为 0)时不建票、
|
||||||
# 不写 ERP、不通知(产品决策 C5);该日仅留痕 Run/Matching,不视作失败。
|
# 不写 ERP、不通知(产品决策 C5);该日仅留痕 Run/Matching,不视作失败。
|
||||||
|
|||||||
@@ -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),
|
||||||
|
)
|
||||||
@@ -1,22 +1,43 @@
|
|||||||
"""在途调拨历史待处理池与老化分级。
|
"""services/in_transit_transfer/backlog_service.py
|
||||||
|
|
||||||
|
在途调拨历史待处理池与老化分级 + 首页「待匹配」桶(D16)。
|
||||||
|
|
||||||
用途:聚合未成功且未人工关闭的可恢复异常、已关闭与结果未知项,
|
用途:聚合未成功且未人工关闭的可恢复异常、已关闭与结果未知项,
|
||||||
按 3/5/7 天阈值输出老化等级,防止历史失败被遗忘。
|
按 3/5/7 天阈值输出老化等级,防止历史失败被遗忘;
|
||||||
依赖:models、status。
|
并提供首页待办看板「待匹配」桶(已落档尚未匹配的外部出入站记录,
|
||||||
|
规格 §10/D16:只读清单 + 计数,不可勾选执行)。
|
||||||
|
依赖:models、status、matching_service(待匹配全量圈档 + 启用类型范围并集)。
|
||||||
逻辑:可恢复=blocked_recoverable;result_unknown 单独高风险展示且只读;
|
逻辑:可恢复=blocked_recoverable;result_unknown 单独高风险展示且只读;
|
||||||
manually_closed / success / duplicate_success 永久排除。
|
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 __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import datetime
|
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 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
|
from app.services.in_transit_transfer.status import TransferStatus
|
||||||
|
|
||||||
AGING_NORMAL = "normal"
|
AGING_NORMAL = "normal"
|
||||||
@@ -28,6 +49,32 @@ AGING_CLOSED = "closed"
|
|||||||
|
|
||||||
_BACKLOG_RECOVERABLE = TransferStatus.BLOCKED_RECOVERABLE.value
|
_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)
|
@dataclass(frozen=True)
|
||||||
class BacklogItemDTO:
|
class BacklogItemDTO:
|
||||||
@@ -42,20 +89,47 @@ class BacklogItemDTO:
|
|||||||
age_days: int
|
age_days: int
|
||||||
aging_level: str
|
aging_level: str
|
||||||
last_attempt_at: Optional[str] = None
|
last_attempt_at: Optional[str] = None
|
||||||
receipt_date: Optional[str] = None
|
movement_date: Optional[str] = None
|
||||||
material_name: Optional[str] = None
|
material_name: Optional[str] = None
|
||||||
from_warehouse: Optional[str] = None
|
from_warehouse: Optional[str] = None
|
||||||
to_warehouse: Optional[str] = None
|
to_warehouse: Optional[str] = None
|
||||||
lot_no: Optional[str] = None
|
lot_no: Optional[str] = None
|
||||||
receipt_quantity: Optional[str] = None
|
movement_quantity: Optional[str] = None
|
||||||
external_quantity: Optional[str] = None
|
external_quantity: Optional[str] = None
|
||||||
# 最近一次结果码(如 blocked_file_removed);供前端区分「文件已移除」徽标
|
# 最近一次结果码(如 blocked_file_removed);供前端区分「文件已移除」徽标
|
||||||
result_code: Optional[str] = None
|
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
|
@dataclass
|
||||||
class BacklogSummaryDTO:
|
class BacklogSummaryDTO:
|
||||||
"""待处理池汇总(含老化分级计数)。"""
|
"""待处理池汇总(含老化分级计数 + 待匹配桶计数)。"""
|
||||||
|
|
||||||
recoverable_count: int = 0
|
recoverable_count: int = 0
|
||||||
closed_count: int = 0
|
closed_count: int = 0
|
||||||
@@ -63,6 +137,36 @@ class BacklogSummaryDTO:
|
|||||||
warn_3d: int = 0
|
warn_3d: int = 0
|
||||||
escalate_5d: int = 0
|
escalate_5d: int = 0
|
||||||
critical_7d: 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:
|
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}
|
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 → 创建时间(全链路统一业务稳定键,
|
keyword 与前端池内筛选同字段集(Invoice/料号/品名/来源,2026-10-16 随
|
||||||
与可调拨明细/匹配卡视图同口径,2026-09-29 统一;与重查/恢复等操作无关)。
|
服务端分页下推),大小写不敏感子串匹配(ilike)。
|
||||||
不用 updated_at 排序——它是行级新鲜度时间戳,重查/恢复会刷新它,
|
|
||||||
以此排序会让正在处理的行在列表中跳位。
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
now: 判定时刻(默认当前时间)。
|
statuses: 池内状态白名单(result_filter 切片或三态并集)。
|
||||||
source_code: 可选来源过滤。
|
source_code: 可选来源过滤。
|
||||||
|
keyword: 可选关键字(子串大小写不敏感)。
|
||||||
Returns:
|
Returns:
|
||||||
BacklogItemDTO 列表。
|
未排序的 SQLAlchemy Query(排序由调用方统一拼 _BACKLOG_ORDER_BY)。
|
||||||
"""
|
"""
|
||||||
current = now or datetime.utcnow()
|
query = TransferInvoiceItem.query.filter(TransferInvoiceItem.status.in_(statuses))
|
||||||
query = TransferInvoiceItem.query.filter(
|
|
||||||
TransferInvoiceItem.status.in_([
|
|
||||||
_BACKLOG_RECOVERABLE,
|
|
||||||
TransferStatus.RESULT_UNKNOWN.value,
|
|
||||||
TransferStatus.MANUALLY_CLOSED.value,
|
|
||||||
]),
|
|
||||||
)
|
|
||||||
if source_code:
|
if source_code:
|
||||||
query = query.filter_by(source_code=source_code)
|
query = query.filter_by(source_code=source_code)
|
||||||
pool_rows = query.order_by(
|
if keyword:
|
||||||
TransferInvoiceItem.receipt_date.asc().nulls_last(),
|
like = f"%{keyword}%"
|
||||||
TransferInvoiceItem.source_code.asc(),
|
query = query.filter(or_(
|
||||||
TransferInvoiceItem.invoice_no.asc(),
|
TransferInvoiceItem.invoice_no.ilike(like),
|
||||||
TransferInvoiceItem.created_at.asc(),
|
TransferInvoiceItem.material_no.ilike(like),
|
||||||
TransferInvoiceItem.id.asc(),
|
TransferInvoiceItem.material_name.ilike(like),
|
||||||
).all()
|
TransferInvoiceItem.source_code.ilike(like),
|
||||||
latest_map = _latest_attempt_times([row.id for row in pool_rows])
|
))
|
||||||
|
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] = []
|
output: list[BacklogItemDTO] = []
|
||||||
for item in pool_rows:
|
for item in rows:
|
||||||
latest = latest_map.get(item.id)
|
latest = latest_map.get(item.id)
|
||||||
base = latest if latest is not None else item.updated_at
|
base = latest if latest is not None else item.updated_at
|
||||||
age = max(0, int((current - base).total_seconds() // 86400))
|
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,
|
age_days=age,
|
||||||
aging_level=level,
|
aging_level=level,
|
||||||
last_attempt_at=latest.isoformat() if latest is not None else None,
|
last_attempt_at=latest.isoformat() if latest is not None else None,
|
||||||
receipt_date=item.receipt_date,
|
movement_date=item.movement_date,
|
||||||
material_name=item.material_name,
|
material_name=item.material_name,
|
||||||
from_warehouse=item.from_warehouse,
|
from_warehouse=item.from_warehouse,
|
||||||
to_warehouse=item.to_warehouse,
|
to_warehouse=item.to_warehouse,
|
||||||
lot_no=item.lot_no,
|
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,
|
external_quantity=str(item.external_quantity) if item.external_quantity is not None else None,
|
||||||
result_code=item.result_code,
|
result_code=item.result_code,
|
||||||
|
transfer_type=transfer_type_code_of(item),
|
||||||
))
|
))
|
||||||
return output
|
return output
|
||||||
|
|
||||||
|
|
||||||
def backlog_summary(*, now: datetime | None = None) -> BacklogSummaryDTO:
|
def list_backlog(*, now: datetime | None = None, source_code: str | None = None) -> list[BacklogItemDTO]:
|
||||||
"""计算待处理池汇总计数与老化分级。"""
|
"""列出待处理池项(可恢复 + 已关闭 + 结果未知)——全量(兼容口径,未分页)。
|
||||||
items = list_backlog(now=now)
|
|
||||||
summary = BacklogSummaryDTO()
|
排序:异动日期 → 数据源 → Invoice → 创建时间(全链路统一业务稳定键,
|
||||||
for item in items:
|
与可调拨明细/匹配卡视图同口径,2026-09-29 统一;与重查/恢复等操作无关)。
|
||||||
if item.status == TransferStatus.MANUALLY_CLOSED.value:
|
不用 updated_at 排序——它是行级新鲜度时间戳,重查/恢复会刷新它,
|
||||||
summary.closed_count += 1
|
以此排序会让正在处理的行在列表中跳位。
|
||||||
elif item.status == TransferStatus.RESULT_UNKNOWN.value:
|
分页场景请用 list_backlog_page(2026-10-16),本函数保留供无参兼容调用。
|
||||||
summary.unknown_count += 1
|
|
||||||
|
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:
|
else:
|
||||||
summary.recoverable_count += 1
|
bucket.append(record)
|
||||||
if item.aging_level == AGING_WARN_3D:
|
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
|
summary.warn_3d += 1
|
||||||
elif item.aging_level == AGING_ESCALATE_5D:
|
elif level == AGING_ESCALATE_5D:
|
||||||
summary.escalate_5d += 1
|
summary.escalate_5d += 1
|
||||||
elif item.aging_level == AGING_CRITICAL_7D:
|
elif level == AGING_CRITICAL_7D:
|
||||||
summary.critical_7d += 1
|
summary.critical_7d += 1
|
||||||
|
# [待匹配桶计数] 与行桶相互独立,并与清单外部单号合并后的行数一致。
|
||||||
|
summary.pending_match_count, summary.matchable_count = _pending_match_counts()
|
||||||
return summary
|
return summary
|
||||||
@@ -3,7 +3,13 @@
|
|||||||
用途:取消尚未开始的 Invoice(cancelled),已成功单据保留、不撤销;
|
用途:取消尚未开始的 Invoice(cancelled),已成功单据保留、不撤销;
|
||||||
原因必填;取消前后状态进入审计。
|
原因必填;取消前后状态进入审计。
|
||||||
依赖:models、status、core.errors。
|
依赖: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
|
from __future__ import annotations
|
||||||
@@ -12,7 +18,7 @@ from datetime import datetime
|
|||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
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
|
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()
|
).count()
|
||||||
if active == 0:
|
if active == 0:
|
||||||
run.status = status_machine.TransferRunStatus.CANCELLED.value
|
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()
|
run.completed_at = run.completed_at or datetime.utcnow()
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return {"run_no": run.run_no, "cancelled_count": cancelled}
|
return {"run_no": run.run_no, "cancelled_count": cancelled}
|
||||||
@@ -14,8 +14,9 @@ from decimal import Decimal
|
|||||||
from typing import Iterable
|
from typing import Iterable
|
||||||
|
|
||||||
# ---- 一期冻结错误码(TDD §7.3)-------------------------------------------
|
# ---- 一期冻结错误码(TDD §7.3)-------------------------------------------
|
||||||
|
# 【TRANSFER_INBOUND_NOT_MATURED 已退役 2026-10-16】成熟概念删除(未上线期不设
|
||||||
|
# 兼容层);前端四语言 errors.json 同键一并移除。
|
||||||
TRANSFER_PERMISSION_DENIED = "TRANSFER_PERMISSION_DENIED"
|
TRANSFER_PERMISSION_DENIED = "TRANSFER_PERMISSION_DENIED"
|
||||||
TRANSFER_RECEIPT_NOT_MATURED = "TRANSFER_RECEIPT_NOT_MATURED"
|
|
||||||
TRANSFER_FILE_NOT_READY = "TRANSFER_FILE_NOT_READY"
|
TRANSFER_FILE_NOT_READY = "TRANSFER_FILE_NOT_READY"
|
||||||
TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID"
|
TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID"
|
||||||
TRANSFER_INVOICE_CONFLICT = "TRANSFER_INVOICE_CONFLICT"
|
TRANSFER_INVOICE_CONFLICT = "TRANSFER_INVOICE_CONFLICT"
|
||||||
@@ -32,7 +33,6 @@ TRANSFER_NOTIFICATION_FAILED = "TRANSFER_NOTIFICATION_FAILED"
|
|||||||
|
|
||||||
KNOWN_TRANSFER_ERROR_CODES: frozenset[str] = frozenset({
|
KNOWN_TRANSFER_ERROR_CODES: frozenset[str] = frozenset({
|
||||||
TRANSFER_PERMISSION_DENIED,
|
TRANSFER_PERMISSION_DENIED,
|
||||||
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,
|
||||||
@@ -67,7 +67,6 @@ class MatchingCountsDTO:
|
|||||||
"""匹配计数。"""
|
"""匹配计数。"""
|
||||||
|
|
||||||
file_invoice_count: int = 0
|
file_invoice_count: int = 0
|
||||||
not_matured_count: int = 0
|
|
||||||
matched_count: int = 0
|
matched_count: int = 0
|
||||||
executable_count: int = 0
|
executable_count: int = 0
|
||||||
blocked_count: int = 0
|
blocked_count: int = 0
|
||||||
@@ -101,13 +100,13 @@ class MatchingItemDTO:
|
|||||||
to_warehouse: str
|
to_warehouse: str
|
||||||
to_quantity: Decimal
|
to_quantity: Decimal
|
||||||
result: str
|
result: str
|
||||||
receipt_date: str | None = None
|
movement_date: str | None = None
|
||||||
reason: str = ""
|
reason: str = ""
|
||||||
external_document_no: str | None = None
|
external_document_no: str | None = None
|
||||||
raw_lines: tuple[RawLineRefDTO, ...] = field(default_factory=tuple)
|
raw_lines: tuple[RawLineRefDTO, ...] = field(default_factory=tuple)
|
||||||
lot_no: str = ""
|
lot_no: str = ""
|
||||||
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(明细审计与执行期重解析输入)。
|
# 入站文件「仓库」列原值:inventory_match 源映射行匹配键(明细审计与执行期重解析输入)。
|
||||||
receipt_warehouse_code: str = ""
|
movement_warehouse_code: str = ""
|
||||||
# 交易单位原值(movement 契约第 11 字段 unit,计划 D4):展示与 ERP 写入行输入,
|
# 交易单位原值(movement 契约第 11 字段 unit,计划 D4):展示与 ERP 写入行输入,
|
||||||
# 不参与匹配身份与 Hash 快照;空值行在匹配阶段落 blocked_missing_unit。
|
# 不参与匹配身份与 Hash 快照;空值行在匹配阶段落 blocked_missing_unit。
|
||||||
unit: str = ""
|
unit: str = ""
|
||||||
@@ -122,6 +121,9 @@ class MatchingItemDTO:
|
|||||||
# (execution_service.prepare_execution 同款 .strip() 口径)。匹配评估路径填齐,
|
# (execution_service.prepare_execution 同款 .strip() 口径)。匹配评估路径填齐,
|
||||||
# 供「预计 ERP 单据数」按五元组去重与前端勾选行预估;restore 视图路径缺省 ""。
|
# 供「预计 ERP 单据数」按五元组去重与前端勾选行预估;restore 视图路径缺省 ""。
|
||||||
external_org: str = ""
|
external_org: str = ""
|
||||||
|
# 出生匹配快照上的调拨类型 code。可调拨明细跨类型混排时用来展示类别;
|
||||||
|
# 无匹配或快照未写类型时为空串。
|
||||||
|
transfer_type: str = ""
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@@ -129,14 +131,13 @@ class MatchingSummaryDTO:
|
|||||||
"""匹配摘要(含预计调拨数量、预计 ERP 单据数与匹配 Hash)。
|
"""匹配摘要(含预计调拨数量、预计 ERP 单据数与匹配 Hash)。
|
||||||
|
|
||||||
estimated_external_write_count(2026-10-12 口径修正):可执行行按执行建单
|
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 单。
|
去重后的单据数,非可执行行数——同组多行在执行期合并一张 ERP 单。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
matching_id: str
|
matching_id: str
|
||||||
status: str
|
status: str
|
||||||
business_date: str
|
business_date: str
|
||||||
eligible_receipt_date_to: str
|
|
||||||
expires_at: str
|
expires_at: str
|
||||||
counts: MatchingCountsDTO
|
counts: MatchingCountsDTO
|
||||||
estimated_transfer_quantity: str
|
estimated_transfer_quantity: str
|
||||||
|
|||||||
@@ -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,
|
||||||
|
)
|
||||||
@@ -1,11 +1,15 @@
|
|||||||
"""在途调拨业务日期与成熟度策略。
|
"""在途调拨业务日期与日期解析。
|
||||||
|
|
||||||
用途:固定业务时区 Asia/Shanghai,实现 T+lag 成熟规则(默认 T+2:收料日期 ≤ T-2
|
用途:固定业务时区 Asia/Shanghai,统一 parse_date 归一化异动日期(ISO + DSV SSRS
|
||||||
可匹配,T-1/当天 not_matured,未来日期阻断);统一 parse_date 归一化收料日期
|
美式 MM/DD/YYYY[ HH:MM:SS]);提供业务日换算、UTC 存储窗口换算与可匹配
|
||||||
(ISO + DSV SSRS 美式 MM/DD/YYYY[ HH:MM:SS])。
|
截止日(T−2)换算。
|
||||||
依赖:标准库 zoneinfo / datetime;可选 Flask current_app(读成熟滞后配置)。
|
依赖:标准库 zoneinfo / datetime。
|
||||||
逻辑:所有日期判定集中在本模块,供 matching_service / file_parser / evidence_sync
|
逻辑:所有日期判定集中在本模块,供 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
|
from __future__ import annotations
|
||||||
@@ -15,14 +19,9 @@ from zoneinfo import ZoneInfo
|
|||||||
|
|
||||||
SHANGHAI_TZ = ZoneInfo("Asia/Shanghai")
|
SHANGHAI_TZ = ZoneInfo("Asia/Shanghai")
|
||||||
|
|
||||||
# 成熟度结果
|
# 可匹配截止滞后天数:T−2 之前数据全部成熟(与前端 transferDate.ts
|
||||||
MATURITY_ELIGIBLE = "eligible"
|
# DEFAULT_LOOKBACK_DAYS 同口径,两侧须同步调整)。
|
||||||
MATURITY_NOT_MATURED = "not_matured"
|
MOVEMENT_DATE_MAX_LAG_DAYS = 2
|
||||||
MATURITY_FUTURE = "future"
|
|
||||||
|
|
||||||
# 成熟滞后天数默认值(T+2:收料日期 ≤ T-2 才可匹配;与海外的时差余量)。
|
|
||||||
# 可经环境变量 IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS 覆盖(settings 装载)。
|
|
||||||
DEFAULT_MATURITY_LAG_DAYS = 2
|
|
||||||
|
|
||||||
# DSV SSRS Date Received 常见美式格式(月/日/年,可选时分秒);%m/%d 亦接受单位数。
|
# DSV SSRS Date Received 常见美式格式(月/日/年,可选时分秒);%m/%d 亦接受单位数。
|
||||||
_US_DATE_FORMATS = (
|
_US_DATE_FORMATS = (
|
||||||
@@ -35,7 +34,7 @@ _US_DATE_FORMATS = (
|
|||||||
def parse_date(value: date | datetime | str) -> date:
|
def parse_date(value: date | datetime | str) -> date:
|
||||||
"""将 date/datetime 或日期字符串归一化为 date。
|
"""将 date/datetime 或日期字符串归一化为 date。
|
||||||
|
|
||||||
核心逻辑:先认 ISO(含带时间),再认美式 MM/DD/YYYY[ HH:MM[:SS]](DSV 收料);
|
核心逻辑:先认 ISO(含带时间),再认美式 MM/DD/YYYY[ HH:MM[:SS]](DSV 入站文件);
|
||||||
均失败则 ValueError(fail-closed)。
|
均失败则 ValueError(fail-closed)。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
@@ -59,7 +58,7 @@ def parse_date(value: date | datetime | str) -> date:
|
|||||||
return datetime.fromisoformat(text).date()
|
return datetime.fromisoformat(text).date()
|
||||||
except ValueError:
|
except ValueError:
|
||||||
pass
|
pass
|
||||||
# [STEP] DSV SSRS 收料 Date Received:美式月/日/年(可带时分秒)。
|
# [STEP] DSV SSRS 入站 Date Received:美式月/日/年(可带时分秒)。
|
||||||
for fmt in _US_DATE_FORMATS:
|
for fmt in _US_DATE_FORMATS:
|
||||||
try:
|
try:
|
||||||
return datetime.strptime(text, fmt).date()
|
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()
|
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]:
|
def business_date_utc_window(now: datetime | None = None) -> tuple[datetime, datetime]:
|
||||||
"""返回当前业务日期(Asia/Shanghai)在 UTC 存储时间轴上的 [起, 止) 窗口。
|
"""返回当前业务日期(Asia/Shanghai)在 UTC 存储时间轴上的 [起, 止) 窗口。
|
||||||
|
|
||||||
@@ -105,53 +120,3 @@ def business_date_utc_window(now: datetime | None = None) -> tuple[datetime, dat
|
|||||||
.replace(tzinfo=None)
|
.replace(tzinfo=None)
|
||||||
)
|
)
|
||||||
return start_utc, start_utc + timedelta(hours=24)
|
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)
|
|
||||||
Loaded 100 of 803 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user