Compare commits
44
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f38e940e3c | ||
|
|
7e7bcbd388 | ||
|
|
28b4a428ef | ||
|
|
e181d4e9ec | ||
|
|
8c97d5ed21 | ||
|
|
e38e5a63fe | ||
|
|
d95c4dc086 | ||
|
|
a8d721e793 | ||
|
|
91a4bcbb8b | ||
|
|
02af2c9599 | ||
|
|
86fc8a2c06 | ||
|
|
34c3bfb254 | ||
|
|
386f93108c | ||
|
|
4e97553f42 | ||
|
|
91a4bd538d | ||
|
|
ffbcb93b2e | ||
|
|
e8d9dba8a3 | ||
|
|
239d373503 | ||
|
|
d57ecc62f9 | ||
|
|
c5b7cc662b | ||
|
|
abde3de71d | ||
|
|
f4edec6e07 | ||
|
|
fe5191b38a | ||
|
|
444a7482e3 | ||
|
|
83e0bad22f | ||
|
|
20122ce6d3 | ||
|
|
a3078a4415 | ||
|
|
9adb3ec077 | ||
|
|
64afe94924 | ||
|
|
ebd27ccfa7 | ||
|
|
ce4b69eb7c | ||
|
|
3bfd881c4f | ||
|
|
5b7e0d5f87 | ||
|
|
aed076046a | ||
|
|
d004a141f2 | ||
|
|
6ad93e829c | ||
|
|
425ed43649 | ||
|
|
5ede1cbcc4 | ||
|
|
22b05c91a2 | ||
|
|
d2e7eb678a | ||
|
|
f723732eb5 | ||
|
|
594d9c22b5 | ||
|
|
d635a2920c | ||
|
|
863e009b59 |
No files matched your search
@@ -102,7 +102,6 @@ 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_AUDIT_RETENTION_DAYS=1095
|
|
||||||
# 复核工作台字段级 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_INVENTORY_ENABLED=true
|
||||||
@@ -110,7 +109,6 @@ SHIPPING_NOTICE_INVENTORY_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
|
||||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
|
|
||||||
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
||||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||||
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||||
@@ -135,7 +133,6 @@ SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
|
|||||||
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true
|
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_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
|
|
||||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||||
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
|
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||||
@@ -157,10 +154,13 @@ 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
|
||||||
# 企微心跳告警总开关(默认关闭;需要时改为 true)
|
|
||||||
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
|
|
||||||
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
|
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
|
||||||
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
|
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
|
||||||
# --- 10. 运维、告警与维护工具 ---
|
# --- 10. 运维、告警与维护工具 ---
|
||||||
# 设备维保助手后端工具调用密钥
|
# 设备维保助手后端工具调用密钥
|
||||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||||
|
|
||||||
|
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||||
|
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||||
|
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
|
||||||
|
WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||||
@@ -25,6 +25,7 @@ HXOPS_PUBLIC_BASE_URL=https://ai.well-trust.com
|
|||||||
AUTH_LOGIN_MODE=casdoor
|
AUTH_LOGIN_MODE=casdoor
|
||||||
# 如果需要用户密码登录,修改该值为password
|
# 如果需要用户密码登录,修改该值为password
|
||||||
# AUTH_LOGIN_MODE=password
|
# AUTH_LOGIN_MODE=password
|
||||||
|
|
||||||
# 是否启用 JWT 认证
|
# 是否启用 JWT 认证
|
||||||
AUTH_JWT_REQUIRED=true
|
AUTH_JWT_REQUIRED=true
|
||||||
AUTH_JWT_ISSUER=https://auth.well-trust.com
|
AUTH_JWT_ISSUER=https://auth.well-trust.com
|
||||||
@@ -72,7 +73,6 @@ GUNICORN_WORKERS=20
|
|||||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||||
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||||
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
|
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
|
||||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines
|
|
||||||
WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com
|
WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||||
|
|
||||||
# --- 5. 数据库与基础设施 ---
|
# --- 5. 数据库与基础设施 ---
|
||||||
@@ -116,7 +116,6 @@ 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_AUDIT_RETENTION_DAYS=1095
|
|
||||||
|
|
||||||
# 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享)
|
# 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享)
|
||||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||||
@@ -138,7 +137,6 @@ SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
|
|||||||
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=false
|
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=false
|
||||||
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=false
|
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=false
|
||||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=false
|
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=false
|
||||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
|
|
||||||
# RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。
|
# RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。
|
||||||
# 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。
|
# 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。
|
||||||
FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
|
FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
|
||||||
@@ -146,8 +144,6 @@ FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
|
|||||||
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_INVENTORY_TIMEOUT_SECONDS=900
|
||||||
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
||||||
# 企微心跳告警总开关(默认关闭;需要时改为 true)
|
|
||||||
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
|
|
||||||
# 运维必填其一:填写已绑企微的用户名,或确保至少一名 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
|
||||||
@@ -162,10 +158,9 @@ FREIGHT_RPA_RECEIPT_ARCHIVE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/arc
|
|||||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_queue
|
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_queue
|
||||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_triggers
|
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_triggers
|
||||||
# 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
# 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
|
||||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod
|
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod
|
||||||
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
# 订单交期回复 Agent(2026-10-10 上线边界):只同步订单日期 ≥ 起始日的订单行,早于边界的历史行随 erp_missing 语义自动移出工作台;留空/删除 = 全量同步(dev/test 不配置)
|
||||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
ORDER_DELIVERY_SYNC_DATE_FROM=2026-10-10
|
||||||
# --- 10. 运维、告警与维护工具 ---
|
# --- 10. 运维、告警与维护工具 ---
|
||||||
# 设备维保助手后端工具调用密钥
|
# 设备维保助手后端工具调用密钥
|
||||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||||
+1
-1
@@ -150,7 +150,7 @@ WECOM_TRUSTED_DOMAIN=
|
|||||||
WECOM_PUBLIC_BASE_URL=
|
WECOM_PUBLIC_BASE_URL=
|
||||||
WECOM_NOTIFY_ENABLED=true
|
WECOM_NOTIFY_ENABLED=true
|
||||||
WECOM_NOTIFY_BASE_URL=
|
WECOM_NOTIFY_BASE_URL=
|
||||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,order_delivery_reply_notify,training_overseas_thailand_guidelines
|
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,equipment_acceptance_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,order_delivery_reply_notify,training_overseas_thailand_guidelines
|
||||||
WECOM_FEEDBACK_NOTIFY_ENABLED=true
|
WECOM_FEEDBACK_NOTIFY_ENABLED=true
|
||||||
WECOM_FEEDBACK_NOTIFY_BASE_URL=http://ai.well-trust.com:8881
|
WECOM_FEEDBACK_NOTIFY_BASE_URL=http://ai.well-trust.com:8881
|
||||||
# 企业微信群机器人 webhook,按环境写入 .env.<env> 或部署平台变量;不要提交真实 URL。
|
# 企业微信群机器人 webhook,按环境写入 .env.<env> 或部署平台变量;不要提交真实 URL。
|
||||||
|
|||||||
@@ -24,8 +24,6 @@ HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
|
|||||||
# 如果需要用户密码登录,修改该值为password
|
# 如果需要用户密码登录,修改该值为password
|
||||||
#AUTH_LOGIN_MODE=casdoor
|
#AUTH_LOGIN_MODE=casdoor
|
||||||
AUTH_LOGIN_MODE=casdoor
|
AUTH_LOGIN_MODE=casdoor
|
||||||
# 是否启用 JWT 认证
|
|
||||||
AUTH_JWT_REQUIRED=true
|
|
||||||
|
|
||||||
# 必须与 CASDOOR_BASE_URL discovery 返回的 issuer 完全一致,不能填写 HXOPS 地址。
|
# 必须与 CASDOOR_BASE_URL discovery 返回的 issuer 完全一致,不能填写 HXOPS 地址。
|
||||||
AUTH_JWT_ISSUER=https://autht.well-trust.com
|
AUTH_JWT_ISSUER=https://autht.well-trust.com
|
||||||
@@ -72,7 +70,6 @@ GUNICORN_WORKERS=6
|
|||||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||||
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||||
WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
|
WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
|
||||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines
|
|
||||||
WECOM_PUBLIC_BASE_URL=https://ait.well-trust.com
|
WECOM_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||||
HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
|
HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||||
|
|
||||||
@@ -120,13 +117,11 @@ 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_AUDIT_RETENTION_DAYS=1095
|
|
||||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
SHIPPING_NOTICE_INVENTORY_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
|
||||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
|
|
||||||
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
||||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||||
# 货代专用 Tool API Key(RPA 回调优先读取;真实值请在服务器本地配置,禁止提交真实密钥)
|
# 货代专用 Tool API Key(RPA 回调优先读取;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||||
@@ -151,16 +146,16 @@ SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
|
|||||||
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true
|
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_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
|
|
||||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||||
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐)
|
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐)
|
||||||
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
|
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
|
||||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
# 两域超时须覆盖最坏批次总时长(10 站串行 + 单站失败重试可达 30 分钟+),
|
||||||
|
# 否则每轮对账会把仍在飞的健康批次误回收(2026-10-08 RUN20261008003113B726 实测教训)
|
||||||
|
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=3600
|
||||||
|
FREIGHT_RPA_RECEIPT_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
|
||||||
# 企微心跳告警总开关(默认关闭;需要时改为 true)
|
|
||||||
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
|
|
||||||
# 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微
|
# 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微
|
||||||
# 两者皆无则告警只写日志、不会发企微
|
# 两者皆无则告警只写日志、不会发企微
|
||||||
FREIGHT_RPA_WORKER_ALERT_USERNAMES=
|
FREIGHT_RPA_WORKER_ALERT_USERNAMES=
|
||||||
@@ -185,10 +180,7 @@ FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inven
|
|||||||
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
|
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
|
||||||
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
|
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
|
||||||
# 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
# 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
|
||||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
|
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
|
||||||
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
|
||||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
|
||||||
# --- 10. 运维、告警与维护工具 ---
|
# --- 10. 运维、告警与维护工具 ---
|
||||||
# 设备维保助手后端工具调用密钥
|
# 设备维保助手后端工具调用密钥
|
||||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||||
@@ -122,6 +122,11 @@ def create_app(config_name='default'):
|
|||||||
ensure_default_contract_payment_schedules()
|
ensure_default_contract_payment_schedules()
|
||||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||||
logger.warning('Failed to ensure contract-payment schedules: %s', exc)
|
logger.warning('Failed to ensure contract-payment schedules: %s', exc)
|
||||||
|
try:
|
||||||
|
from app.services.equipment_acceptance.schedule_seed import ensure_default_equipment_acceptance_schedules
|
||||||
|
ensure_default_equipment_acceptance_schedules()
|
||||||
|
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||||
|
logger.warning('Failed to ensure equipment-acceptance schedules: %s', exc)
|
||||||
try:
|
try:
|
||||||
from app.services.order_delivery_reply.schedule_seed import ensure_default_order_delivery_schedules
|
from app.services.order_delivery_reply.schedule_seed import ensure_default_order_delivery_schedules
|
||||||
ensure_default_order_delivery_schedules()
|
ensure_default_order_delivery_schedules()
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ def register_blueprints(app: Flask) -> None:
|
|||||||
)
|
)
|
||||||
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.order_delivery_reply import order_delivery_reply_bp
|
from app.api.order_delivery_reply import order_delivery_reply_bp
|
||||||
from app.api.in_transit_transfer import in_transit_transfer_bp
|
from app.api.in_transit_transfer import in_transit_transfer_bp
|
||||||
from app.api.integration_connector import integration_connector_bp
|
from app.api.integration_connector import integration_connector_bp
|
||||||
@@ -81,6 +82,7 @@ def register_blueprints(app: Flask) -> None:
|
|||||||
app.register_blueprint(files_bp, url_prefix='/api/files')
|
app.register_blueprint(files_bp, url_prefix='/api/files')
|
||||||
app.register_blueprint(procurement_contract_bp, url_prefix='/api/procurement-contract')
|
app.register_blueprint(procurement_contract_bp, url_prefix='/api/procurement-contract')
|
||||||
app.register_blueprint(contract_payment_bp, url_prefix='/api/contract-payment')
|
app.register_blueprint(contract_payment_bp, url_prefix='/api/contract-payment')
|
||||||
|
app.register_blueprint(equipment_acceptance_bp, url_prefix='/api/equipment-acceptance')
|
||||||
app.register_blueprint(order_delivery_reply_bp, url_prefix='/api/order-delivery-reply')
|
app.register_blueprint(order_delivery_reply_bp, url_prefix='/api/order-delivery-reply')
|
||||||
app.register_blueprint(in_transit_transfer_bp, url_prefix='/api/in-transit-transfer')
|
app.register_blueprint(in_transit_transfer_bp, url_prefix='/api/in-transit-transfer')
|
||||||
app.register_blueprint(integration_connector_bp, url_prefix='/api/integration-connector')
|
app.register_blueprint(integration_connector_bp, url_prefix='/api/integration-connector')
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/equipment_acceptance/__init__.py
|
||||||
|
|
||||||
|
用途:设备验收预警的 Chat 作业面接口。
|
||||||
|
依赖:JWT 当前用户、Agent 授权、sync_service、统一成功响应。
|
||||||
|
逻辑:持有 equipment_acceptance Agent 的用户可看停留列表、发送记录和配置;同步、扫描、发送和保存配置仅平台管理员。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from flask import Blueprint, g, request
|
||||||
|
|
||||||
|
from app.core.auth.jwt import get_current_user
|
||||||
|
from app.core.errors import ForbiddenError, UnauthorizedError
|
||||||
|
from app.core.response import ok
|
||||||
|
from app.models import Agent
|
||||||
|
from app.services.equipment_acceptance.config_service import (
|
||||||
|
get_acceptance_config,
|
||||||
|
save_acceptance_config,
|
||||||
|
)
|
||||||
|
from app.services.equipment_acceptance.alert_service import generate_alerts, send_pending_alerts
|
||||||
|
from app.services.equipment_acceptance.send_record_service import list_send_records
|
||||||
|
from app.services.equipment_acceptance.sync_service import (
|
||||||
|
get_acceptance_order,
|
||||||
|
list_acceptance_orders,
|
||||||
|
sync_acceptance_snapshots,
|
||||||
|
)
|
||||||
|
|
||||||
|
equipment_acceptance_bp = Blueprint("equipment_acceptance", __name__)
|
||||||
|
EQUIPMENT_ACCEPTANCE_AGENT_CODE = "equipment_acceptance"
|
||||||
|
|
||||||
|
|
||||||
|
def _require_user():
|
||||||
|
"""
|
||||||
|
读取当前登录用户。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
已认证用户。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
UnauthorizedError: 没有有效登录身份。
|
||||||
|
"""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
raise UnauthorizedError()
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _user_has_equipment_acceptance_agent(user) -> bool:
|
||||||
|
"""
|
||||||
|
判断用户是否持有启用中的设备验收预警 Agent。
|
||||||
|
|
||||||
|
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions。
|
||||||
|
"""
|
||||||
|
agent = Agent.query.filter_by(agent_code=EQUIPMENT_ACCEPTANCE_AGENT_CODE, is_active=True).first()
|
||||||
|
return bool(agent is not None and agent in user.agents)
|
||||||
|
|
||||||
|
|
||||||
|
def _require_equipment_acceptance_access():
|
||||||
|
"""
|
||||||
|
确保当前用户可以打开设备验收预警作业面。
|
||||||
|
|
||||||
|
核心逻辑:平台管理员放行;普通用户必须被授予启用中的 equipment_acceptance Agent。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
已认证且有权查看的用户。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
UnauthorizedError: 没有有效登录身份。
|
||||||
|
ForbiddenError: 已登录但没有该 Agent。
|
||||||
|
"""
|
||||||
|
user = _require_user()
|
||||||
|
if user.is_platform_admin() or _user_has_equipment_acceptance_agent(user):
|
||||||
|
return user
|
||||||
|
raise ForbiddenError(
|
||||||
|
"Equipment acceptance agent permission required",
|
||||||
|
code="EQUIPMENT_ACCEPTANCE.FORBIDDEN",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _require_equipment_acceptance_admin():
|
||||||
|
"""
|
||||||
|
确保当前用户可以触发 E10 同步。
|
||||||
|
|
||||||
|
核心逻辑:先确认能看作业面,再要求平台管理员。同步会读取外部库并改写本地快照。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
已认证的管理员。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ForbiddenError: 不是平台管理员。
|
||||||
|
"""
|
||||||
|
user = _require_equipment_acceptance_access()
|
||||||
|
if not user.is_platform_admin():
|
||||||
|
raise ForbiddenError(
|
||||||
|
"Admin privilege required for equipment acceptance sync",
|
||||||
|
code="EQUIPMENT_ACCEPTANCE.ADMIN_REQUIRED",
|
||||||
|
)
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
@equipment_acceptance_bp.route("/sync", methods=["POST"])
|
||||||
|
def sync_equipment_acceptance():
|
||||||
|
"""从 E10 拉取验收单并写入本地快照。仅平台管理员。"""
|
||||||
|
_require_equipment_acceptance_admin()
|
||||||
|
return ok(sync_acceptance_snapshots(), request_id=getattr(g, "request_id", None))
|
||||||
|
|
||||||
|
|
||||||
|
@equipment_acceptance_bp.route("/orders", methods=["GET"])
|
||||||
|
def list_equipment_acceptance_orders():
|
||||||
|
"""分页查看已同步的验收单。focus 按原型分组过滤,summary 始终统计全部单据。"""
|
||||||
|
_require_equipment_acceptance_access()
|
||||||
|
page = _int_arg("page", 1)
|
||||||
|
page_size = _int_arg("page_size", 20)
|
||||||
|
payload = list_acceptance_orders(
|
||||||
|
monitor_status=request.args.get("monitor_status"),
|
||||||
|
focus=request.args.get("focus"),
|
||||||
|
page=page,
|
||||||
|
page_size=page_size,
|
||||||
|
)
|
||||||
|
return ok(payload, request_id=getattr(g, "request_id", None))
|
||||||
|
|
||||||
|
|
||||||
|
@equipment_acceptance_bp.route("/config", methods=["GET"])
|
||||||
|
def get_equipment_acceptance_config():
|
||||||
|
"""读取四档天数和三个固定岗位。候选人名单只给平台管理员。"""
|
||||||
|
user = _require_equipment_acceptance_access()
|
||||||
|
payload = get_acceptance_config(include_candidates=user.is_platform_admin())
|
||||||
|
return ok(payload, request_id=getattr(g, "request_id", None))
|
||||||
|
|
||||||
|
|
||||||
|
@equipment_acceptance_bp.route("/config", methods=["PUT"])
|
||||||
|
def save_equipment_acceptance_config():
|
||||||
|
"""保存四档天数和三个固定岗位。仅平台管理员。发送时刻不在本接口。"""
|
||||||
|
user = _require_equipment_acceptance_access()
|
||||||
|
if not user.is_platform_admin():
|
||||||
|
raise ForbiddenError(
|
||||||
|
"Admin privilege required for equipment acceptance settings",
|
||||||
|
code="EQUIPMENT_ACCEPTANCE.SETTINGS_ADMIN_REQUIRED",
|
||||||
|
)
|
||||||
|
payload = request.get_json(silent=True) or {}
|
||||||
|
saved = save_acceptance_config(payload, updated_by=user.id)
|
||||||
|
return ok(saved, request_id=getattr(g, "request_id", None))
|
||||||
|
|
||||||
|
|
||||||
|
@equipment_acceptance_bp.route("/alerts/scan", methods=["POST"])
|
||||||
|
def scan_equipment_acceptance_alerts():
|
||||||
|
"""管理员立即同步 E10 并生成待发送记录。不发企业微信。"""
|
||||||
|
_require_equipment_acceptance_admin()
|
||||||
|
return ok(generate_alerts(), request_id=getattr(g, "request_id", None))
|
||||||
|
|
||||||
|
|
||||||
|
@equipment_acceptance_bp.route("/alerts/send", methods=["POST"])
|
||||||
|
def send_equipment_acceptance_alerts():
|
||||||
|
"""管理员立即把待发送记录按收件人发到企业微信。"""
|
||||||
|
_require_equipment_acceptance_admin()
|
||||||
|
return ok(send_pending_alerts(), request_id=getattr(g, "request_id", None))
|
||||||
|
|
||||||
|
|
||||||
|
@equipment_acceptance_bp.route("/sends", methods=["GET"])
|
||||||
|
def list_equipment_acceptance_sends():
|
||||||
|
"""分页查看发送记录。扫描写入后这里才有行。"""
|
||||||
|
_require_equipment_acceptance_access()
|
||||||
|
payload = list_send_records(page=_int_arg("page", 1), page_size=_int_arg("page_size", 20))
|
||||||
|
return ok(payload, request_id=getattr(g, "request_id", None))
|
||||||
|
|
||||||
|
|
||||||
|
@equipment_acceptance_bp.route("/orders/<int:order_id>", methods=["GET"])
|
||||||
|
def get_equipment_acceptance_order(order_id: int):
|
||||||
|
"""查看一张验收单的节点和操作人原值。"""
|
||||||
|
_require_equipment_acceptance_access()
|
||||||
|
return ok(get_acceptance_order(order_id), request_id=getattr(g, "request_id", None))
|
||||||
|
|
||||||
|
|
||||||
|
def _int_arg(name: str, default: int) -> int:
|
||||||
|
"""读取正整数查询参数,非法时用默认值。"""
|
||||||
|
raw = request.args.get(name)
|
||||||
|
if raw is None or str(raw).strip() == "":
|
||||||
|
return default
|
||||||
|
try:
|
||||||
|
return int(raw)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return default
|
||||||
@@ -793,6 +793,32 @@ def retry_source_rpa_api(source_code: str):
|
|||||||
}, status=202)
|
}, status=202)
|
||||||
|
|
||||||
|
|
||||||
|
@in_transit_transfer_bp.route("/sources/retry-rpa-batch", methods=["POST"])
|
||||||
|
@require_transfer_permission
|
||||||
|
def retry_sources_rpa_batch_api():
|
||||||
|
"""批量重试多来源收料 RPA:全部有效来源合并写**一个** batch trigger(一文件 N units)。
|
||||||
|
|
||||||
|
【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个来源编码时调用;
|
||||||
|
逐来源调用单来源端点会产生 N 个 trigger 文件,Worker 每文件开/关一次浏览器;
|
||||||
|
合并单文件后 Worker 单次登录串行导出全部来源(与收料排程路径同效率)。
|
||||||
|
|
||||||
|
请求体:{"source_codes": ["DSV360_AWSBI", ...]}。逐来源解析失败分层与
|
||||||
|
fail-closed 语义同单来源端点;单源配置缺失跳过并记录,不阻断其余来源。
|
||||||
|
"""
|
||||||
|
payload = request.get_json(silent=True) or {}
|
||||||
|
source_codes = [str(code).strip() for code in (payload.get("source_codes") or []) if str(code).strip()]
|
||||||
|
if not source_codes:
|
||||||
|
raise ValidationError("source_codes is required")
|
||||||
|
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa_batch
|
||||||
|
|
||||||
|
outcome = trigger_receipt_rpa_batch(
|
||||||
|
source_codes=source_codes,
|
||||||
|
business_date=str(business_date_now()),
|
||||||
|
reason="transfer_retry_receipt",
|
||||||
|
)
|
||||||
|
return _ok(outcome)
|
||||||
|
|
||||||
|
|
||||||
@in_transit_transfer_bp.route("/backlog", methods=["GET"])
|
@in_transit_transfer_bp.route("/backlog", methods=["GET"])
|
||||||
@require_transfer_permission
|
@require_transfer_permission
|
||||||
def backlog_api():
|
def backlog_api():
|
||||||
|
|||||||
@@ -16,7 +16,11 @@ backend/app/api/order_delivery_reply.py
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from flask import Blueprint, g, request
|
from datetime import datetime
|
||||||
|
from io import BytesIO
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from flask import Blueprint, g, request, send_file
|
||||||
|
|
||||||
from app.core.auth.jwt import get_current_user
|
from app.core.auth.jwt import get_current_user
|
||||||
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError
|
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError
|
||||||
@@ -28,6 +32,8 @@ from app.services.order_delivery_reply.sync_service import OrderDeliverySyncServ
|
|||||||
|
|
||||||
order_delivery_reply_bp = Blueprint("order_delivery_reply", __name__)
|
order_delivery_reply_bp = Blueprint("order_delivery_reply", __name__)
|
||||||
|
|
||||||
|
XLSX_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||||
|
|
||||||
|
|
||||||
def _utc_to_shanghai(value) -> str | None:
|
def _utc_to_shanghai(value) -> str | None:
|
||||||
"""
|
"""
|
||||||
@@ -121,6 +127,28 @@ def list_lines():
|
|||||||
return ok(data, request_id=getattr(g, "request_id", None))
|
return ok(data, request_id=getattr(g, "request_id", None))
|
||||||
|
|
||||||
|
|
||||||
|
@order_delivery_reply_bp.get("/lines/export")
|
||||||
|
def export_lines():
|
||||||
|
"""
|
||||||
|
导出当前筛选下的全部订单行 Excel(不分页)。
|
||||||
|
|
||||||
|
用途与触发时机:工作台工具栏「导出 Excel」按钮;查询参数与列表一致
|
||||||
|
(keyword/order_date/status),导出全部命中行(服务层 EXPORT_MAX_ROWS 兜底)。
|
||||||
|
|
||||||
|
参数与输出约束:要求 order_delivery_reply.access 及以上;返回 xlsx 文件流(attachment,
|
||||||
|
文件名带北京时间日期)。
|
||||||
|
"""
|
||||||
|
_require_access()
|
||||||
|
content = query_service.export_lines(request.args.to_dict(flat=True))
|
||||||
|
filename = f"订单交期回复_{datetime.now(ZoneInfo('Asia/Shanghai')):%Y%m%d}.xlsx"
|
||||||
|
return send_file(
|
||||||
|
BytesIO(content),
|
||||||
|
as_attachment=True,
|
||||||
|
download_name=filename,
|
||||||
|
mimetype=XLSX_MIME_TYPE,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@order_delivery_reply_bp.get("/lines/<order_no>/<int:line_no>")
|
@order_delivery_reply_bp.get("/lines/<order_no>/<int:line_no>")
|
||||||
def get_line(order_no: str, line_no: int):
|
def get_line(order_no: str, line_no: int):
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -334,6 +334,26 @@ def rpa_receipt_batch_ready():
|
|||||||
return jsonify({'success': True, 'data': ingest_receipt_callback(_payload())})
|
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'])
|
@shipping_notice_bp.route('/rpa/inventory-batch-claimed', methods=['POST'])
|
||||||
def rpa_inventory_batch_claimed():
|
def rpa_inventory_batch_claimed():
|
||||||
"""v2 Worker 领取回调:仅记录 Attempt 执行阶段。"""
|
"""v2 Worker 领取回调:仅记录 Attempt 执行阶段。"""
|
||||||
|
|||||||
@@ -499,7 +499,7 @@ class Config:
|
|||||||
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
|
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
|
||||||
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
||||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,order_delivery_reply_notify,training_lean_video_push,training_overseas_thailand_guidelines')
|
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning,equipment_acceptance_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,order_delivery_reply_notify,training_lean_video_push,training_overseas_thailand_guidelines')
|
||||||
# 精益培训企微提醒卡片跳转的员工培训聊天页 agent id(前端路由 /chat/<id>)。
|
# 精益培训企微提醒卡片跳转的员工培训聊天页 agent id(前端路由 /chat/<id>)。
|
||||||
# 缺省 0 = 不显式指定,由后端按 handler_config.content_profile='training' 动态解析各环境的培训 Agent
|
# 缺省 0 = 不显式指定,由后端按 handler_config.content_profile='training' 动态解析各环境的培训 Agent
|
||||||
# (测试/正式环境 Agent ID 不同,动态解析保证卡片均可定位「员工培训-精益管理」);
|
# (测试/正式环境 Agent ID 不同,动态解析保证卡片均可定位「员工培训-精益管理」);
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
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)、app.extensions.db(经 base.Base)。
|
依赖:models/* 子模块(含 voucher_check、equipment_acceptance)、app.extensions.db(经 base.Base)。
|
||||||
逻辑:Alembic / Flask-Migrate 通过本模块 import 注册全部表元数据;业务代码继续从此处导入模型类。
|
逻辑:Alembic / Flask-Migrate 通过本模块 import 注册全部表元数据;业务代码继续从此处导入模型类。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -238,6 +238,13 @@ from app.models.contract_payment import (
|
|||||||
ContractPaymentSyncState,
|
ContractPaymentSyncState,
|
||||||
ContractPaymentVendorRequest,
|
ContractPaymentVendorRequest,
|
||||||
)
|
)
|
||||||
|
from app.models.equipment_acceptance import (
|
||||||
|
EquipmentAcceptanceNode,
|
||||||
|
EquipmentAcceptanceOperator,
|
||||||
|
EquipmentAcceptanceOrder,
|
||||||
|
EquipmentAcceptanceSendRecord,
|
||||||
|
EquipmentAcceptanceSetting,
|
||||||
|
)
|
||||||
from app.models.order_delivery_reply import (
|
from app.models.order_delivery_reply import (
|
||||||
OrderDeliveryAuditEvent,
|
OrderDeliveryAuditEvent,
|
||||||
OrderDeliveryBatch,
|
OrderDeliveryBatch,
|
||||||
@@ -434,6 +441,11 @@ __all__ = [
|
|||||||
'ContractPaymentAlert',
|
'ContractPaymentAlert',
|
||||||
'ContractPaymentAlertBatch',
|
'ContractPaymentAlertBatch',
|
||||||
'ContractPaymentSyncState',
|
'ContractPaymentSyncState',
|
||||||
|
'EquipmentAcceptanceOrder',
|
||||||
|
'EquipmentAcceptanceNode',
|
||||||
|
'EquipmentAcceptanceOperator',
|
||||||
|
'EquipmentAcceptanceSetting',
|
||||||
|
'EquipmentAcceptanceSendRecord',
|
||||||
'TransferRun',
|
'TransferRun',
|
||||||
'TransferSourceJob',
|
'TransferSourceJob',
|
||||||
'TransferMatching',
|
'TransferMatching',
|
||||||
|
|||||||
@@ -0,0 +1,156 @@
|
|||||||
|
"""
|
||||||
|
backend/app/models/equipment_acceptance.py
|
||||||
|
|
||||||
|
用途:设备验收预警的本地同步快照和可改配置。
|
||||||
|
依赖:models.base.Base、users。
|
||||||
|
逻辑:同步服务按流程实例 request_id upsert 主表,并整批替换当前节点和操作人子表。
|
||||||
|
配置表只存四档天数和三个固定岗位的系统用户。发送时刻不在这张表。
|
||||||
|
发送记录按验收单和档位留一行。已发送和已取消的姓名不回写;待发送每次扫描重算。
|
||||||
|
不保存流程编号、第二合同编号、验收日期和 isremark。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from sqlalchemy import JSON, BigInteger, Boolean, DateTime, ForeignKey, Index, String, Text, UniqueConstraint
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from app.models.base import Base
|
||||||
|
|
||||||
|
|
||||||
|
class EquipmentAcceptanceOrder(Base):
|
||||||
|
"""一张验收单的最近一次同步结果。流程实例 request_id 唯一。"""
|
||||||
|
|
||||||
|
__tablename__ = "equipment_acceptance_orders"
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("request_id", name="uq_equipment_acceptance_orders_request_id"),
|
||||||
|
Index("ix_equipment_acceptance_orders_status", "monitor_status"),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
acceptance_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||||
|
purchase_order_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||||
|
contract_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||||
|
timer_started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
dwell_days: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||||
|
can_accept: Mapped[Optional[int]] = mapped_column(
|
||||||
|
nullable=True,
|
||||||
|
comment="是否可以正常验收。0 否,1 是。空表示未标明。由 OA sfkyzcys 翻转,OA 为 0 是、1 否。",
|
||||||
|
)
|
||||||
|
cannot_accept_note: Mapped[Optional[str]] = mapped_column(
|
||||||
|
Text,
|
||||||
|
nullable=True,
|
||||||
|
comment="无法验收说明正文,来自 OA ft_gdzcysdv2.ycsm。只留痕,不单独触发停表。",
|
||||||
|
)
|
||||||
|
is_returned: Mapped[Optional[int]] = mapped_column(
|
||||||
|
nullable=True,
|
||||||
|
comment="是否退回。0 否,1 是。由 OA sfzfth 翻转,OA 为 0 是、1 否;OA 空值收成 0。",
|
||||||
|
)
|
||||||
|
flow_status_raw: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||||
|
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
request_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||||
|
request_match_count: Mapped[int] = mapped_column(nullable=False, default=0)
|
||||||
|
owner_oa_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
|
||||||
|
owner_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||||
|
owner_job_num: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
equip_oa_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
|
||||||
|
equip_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||||
|
equip_job_num: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
applicant_oa_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
|
||||||
|
applicant_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||||
|
applicant_job_num: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
monitor_status: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||||
|
present_in_source: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
|
||||||
|
synced_at: Mapped[datetime] = mapped_column(DateTime, 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
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class EquipmentAcceptanceNode(Base):
|
||||||
|
"""同步时看到的当前节点。一条流程可以有多行。"""
|
||||||
|
|
||||||
|
__tablename__ = "equipment_acceptance_nodes"
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("order_id", "node_id", name="uq_equipment_acceptance_nodes_order_node"),
|
||||||
|
Index("ix_equipment_acceptance_nodes_order", "order_id"),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
order_id: Mapped[int] = mapped_column(
|
||||||
|
ForeignKey("equipment_acceptance_orders.id", ondelete="CASCADE"), nullable=False
|
||||||
|
)
|
||||||
|
node_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||||
|
node_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||||
|
node_type: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||||
|
|
||||||
|
|
||||||
|
class EquipmentAcceptanceOperator(Base):
|
||||||
|
"""当前节点上的操作人。同一节点同一人只留一行。不保存 isremark。"""
|
||||||
|
|
||||||
|
__tablename__ = "equipment_acceptance_operators"
|
||||||
|
__table_args__ = (
|
||||||
|
Index("ix_equipment_acceptance_operators_order", "order_id"),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
order_id: Mapped[int] = mapped_column(
|
||||||
|
ForeignKey("equipment_acceptance_orders.id", ondelete="CASCADE"), nullable=False
|
||||||
|
)
|
||||||
|
node_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||||
|
user_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||||
|
handler_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||||
|
handler_job_num: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
|
||||||
|
|
||||||
|
class EquipmentAcceptanceSetting(Base):
|
||||||
|
"""预警配置。全表只使用 id=1 这一行。岗位存系统用户主键,姓名不入库。"""
|
||||||
|
|
||||||
|
__tablename__ = "equipment_acceptance_settings"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
day_1: Mapped[int] = mapped_column(nullable=False, default=30)
|
||||||
|
day_2: Mapped[int] = mapped_column(nullable=False, default=37)
|
||||||
|
day_3: Mapped[int] = mapped_column(nullable=False, default=44)
|
||||||
|
day_4: Mapped[int] = mapped_column(nullable=False, default=51)
|
||||||
|
buyer_manager_user_id: Mapped[Optional[int]] = mapped_column(
|
||||||
|
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
|
||||||
|
)
|
||||||
|
coo_user_id: Mapped[Optional[int]] = mapped_column(
|
||||||
|
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
|
||||||
|
)
|
||||||
|
executive_user_id: Mapped[Optional[int]] = mapped_column(
|
||||||
|
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
|
||||||
|
)
|
||||||
|
updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
updated_by: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||||
|
|
||||||
|
|
||||||
|
class EquipmentAcceptanceSendRecord(Base):
|
||||||
|
"""一张验收单某一档的发送记录。同一张单同一档只留一行。已发送后不改收件人。"""
|
||||||
|
|
||||||
|
__tablename__ = "equipment_acceptance_send_records"
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("order_id", "tier", name="uq_equipment_acceptance_send_records_order_tier"),
|
||||||
|
Index("ix_equipment_acceptance_send_records_created", "created_at"),
|
||||||
|
Index("ix_equipment_acceptance_send_records_status", "status"),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
order_id: Mapped[Optional[int]] = mapped_column(
|
||||||
|
ForeignKey("equipment_acceptance_orders.id", ondelete="SET NULL"), nullable=True
|
||||||
|
)
|
||||||
|
acceptance_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||||
|
purchase_order_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||||
|
tier: Mapped[int] = mapped_column(nullable=False)
|
||||||
|
threshold_days: Mapped[int] = mapped_column(nullable=False)
|
||||||
|
to_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
|
cc_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
|
recipients_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||||
|
status: Mapped[str] = mapped_column(String(32), nullable=False, default="pending")
|
||||||
|
sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
|
||||||
@@ -30,8 +30,9 @@ class ShippingDocumentProfileAutoFreezeQualification(Base):
|
|||||||
"status IN ('manual_confirmation', 'auto_freeze_approved', 'auto_freeze_suspended')",
|
"status IN ('manual_confirmation', 'auto_freeze_approved', 'auto_freeze_suspended')",
|
||||||
name='ck_shipping_document_profile_auto_freeze_qualification_status',
|
name='ck_shipping_document_profile_auto_freeze_qualification_status',
|
||||||
),
|
),
|
||||||
|
# 索引名沿用迁移 0aa34b5c6d7e 的短名;PostgreSQL 标识符上限 63 字符,超长名会导致建库失败。
|
||||||
Index(
|
Index(
|
||||||
'ix_shipping_document_profile_auto_freeze_qualification_profile_status',
|
'ix_ship_doc_prof_auto_freeze_profile_status',
|
||||||
'profile_id', 'status',
|
'profile_id', 'status',
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -104,6 +104,9 @@ class ShippingNoticeLineInventoryMatch(Base):
|
|||||||
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)
|
||||||
|
# 料号维度总可用量(忽略预约号、行允许源内汇总);预约号不匹配行的放行兜底依据。
|
||||||
|
# 历史行与无快照行为 NULL,前端显示占位符;重新匹配后回填。
|
||||||
|
part_available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||||
reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||||
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)
|
||||||
|
|||||||
@@ -204,9 +204,10 @@ class ShippingOrderDocumentProfileSuggestionDecision(Base):
|
|||||||
|
|
||||||
__tablename__ = 'shipping_order_document_profile_suggestion_decisions'
|
__tablename__ = 'shipping_order_document_profile_suggestion_decisions'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
CheckConstraint("decision IN ('accepted', 'accepted_adjusted', 'rejected')", name='ck_shipping_order_document_profile_suggestion_decisions_decision'),
|
# 约束/索引名沿用迁移的短名;PostgreSQL 标识符上限 63 字符,超长名会导致建库失败。
|
||||||
UniqueConstraint('profile_id', 'suggestion_id', name='uq_shipping_order_document_profile_suggestion_decisions_suggestion'),
|
CheckConstraint("decision IN ('accepted', 'accepted_adjusted', 'rejected')", name='ck_order_profile_suggestion_decision'),
|
||||||
Index('ix_shipping_order_document_profile_suggestion_decisions_profile_revision', 'profile_id', 'revision_no'),
|
UniqueConstraint('profile_id', 'suggestion_id', name='uq_order_profile_suggestion'),
|
||||||
|
Index('ix_order_profile_suggestion_revision', 'profile_id', 'revision_no'),
|
||||||
)
|
)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
@@ -238,8 +239,8 @@ class ShippingOrderDocumentProfileValidationRun(Base):
|
|||||||
name='ck_shipping_order_document_profile_validation_runs_type',
|
name='ck_shipping_order_document_profile_validation_runs_type',
|
||||||
),
|
),
|
||||||
CheckConstraint("status IN ('pending', 'running', 'passed', 'failed')", name='ck_shipping_order_document_profile_validation_runs_status'),
|
CheckConstraint("status IN ('pending', 'running', 'passed', 'failed')", name='ck_shipping_order_document_profile_validation_runs_status'),
|
||||||
Index('ix_shipping_order_document_profile_validation_runs_profile_created', 'profile_id', 'created_at'),
|
Index('ix_order_profile_validation_created', 'profile_id', 'created_at'),
|
||||||
Index('ix_shipping_order_document_profile_validation_runs_checksum', 'profile_id', 'definition_checksum'),
|
Index('ix_order_profile_validation_checksum', 'profile_id', 'definition_checksum'),
|
||||||
)
|
)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
@@ -268,10 +269,10 @@ class ShippingOrderDocumentProfilePublishCheckReport(Base):
|
|||||||
|
|
||||||
__tablename__ = 'shipping_order_document_profile_publish_check_reports'
|
__tablename__ = 'shipping_order_document_profile_publish_check_reports'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
CheckConstraint("status IN ('valid', 'invalidated', 'consumed')", name='ck_shipping_order_document_profile_publish_check_reports_status'),
|
CheckConstraint("status IN ('valid', 'invalidated', 'consumed')", name='ck_sodppcr_status'),
|
||||||
UniqueConstraint('profile_id', 'operation_id', name='uq_shipping_order_document_profile_publish_check_reports_operation'),
|
UniqueConstraint('profile_id', 'operation_id', name='uq_sodppcr_profile_operation'),
|
||||||
Index('ix_shipping_order_document_profile_publish_check_reports_profile_created', 'profile_id', 'created_at'),
|
Index('ix_sodppcr_profile_created', 'profile_id', 'created_at'),
|
||||||
Index('ix_shipping_order_document_profile_publish_check_reports_report_no', 'report_no', unique=True),
|
Index('ix_sodppcr_report_no', 'report_no', unique=True),
|
||||||
)
|
)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
|||||||
@@ -97,7 +97,12 @@ def raise_auth_error(source, *, context: str, status_code: int = 401) -> None:
|
|||||||
)
|
)
|
||||||
if 'invalid or expired casdoor state' in lowered_raw:
|
if 'invalid or expired casdoor state' in lowered_raw:
|
||||||
raise ValidationError('Invalid or expired Casdoor state')
|
raise ValidationError('Invalid or expired Casdoor state')
|
||||||
current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s', context, data)
|
# [STEP 2] 未识别错误必须保留原始异常堆栈,否则本地换票后的崩溃会被吞成一行 payload={}。
|
||||||
|
current_app.logger.warning(
|
||||||
|
'[casdoor] unmapped auth error context=%s payload=%s source=%r',
|
||||||
|
context, data, source,
|
||||||
|
exc_info=source if isinstance(source, BaseException) else None,
|
||||||
|
)
|
||||||
raise AppError(
|
raise AppError(
|
||||||
code='CASDOOR_AUTH_FAILED',
|
code='CASDOOR_AUTH_FAILED',
|
||||||
message='Authentication failed, please try again',
|
message='Authentication failed, please try again',
|
||||||
|
|||||||
@@ -141,7 +141,21 @@ def emit_run_failed(
|
|||||||
conversation_id: str,
|
conversation_id: str,
|
||||||
message: str,
|
message: str,
|
||||||
code: str | None = None,
|
code: str | None = None,
|
||||||
|
user_facing: bool = False,
|
||||||
) -> str:
|
) -> str:
|
||||||
|
"""
|
||||||
|
发出本轮失败事件,并附带兼容用的 error 帧。
|
||||||
|
|
||||||
|
核心逻辑:user_facing 为 True 时两帧都带标记,前端原样展示 message。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
message: 失败说明。user_facing 为 True 时必须已是给用户看的句子。
|
||||||
|
code: 业务错误码,可选。
|
||||||
|
user_facing: 为 True 时前端不再把 message 收成通用失败提示。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
连续两段 SSE 帧:run.failed 与 error。
|
||||||
|
"""
|
||||||
error_payload: dict[str, Any] = {
|
error_payload: dict[str, Any] = {
|
||||||
"event": "run.failed",
|
"event": "run.failed",
|
||||||
"run_id": run_id,
|
"run_id": run_id,
|
||||||
@@ -150,10 +164,18 @@ def emit_run_failed(
|
|||||||
"message": message,
|
"message": message,
|
||||||
"session_status": "error",
|
"session_status": "error",
|
||||||
}
|
}
|
||||||
|
legacy_payload: dict[str, Any] = {
|
||||||
|
"event": "error",
|
||||||
|
"message": message,
|
||||||
|
"conversation_id": conversation_id,
|
||||||
|
"session_status": "error",
|
||||||
|
}
|
||||||
if code:
|
if code:
|
||||||
error_payload["code"] = code
|
error_payload["code"] = code
|
||||||
legacy = sse_frame({"event": "error", "message": message, "conversation_id": conversation_id, "session_status": "error"})
|
if user_facing:
|
||||||
return sse_frame(error_payload) + legacy
|
error_payload["user_facing"] = True
|
||||||
|
legacy_payload["user_facing"] = True
|
||||||
|
return sse_frame(error_payload) + sse_frame(legacy_payload)
|
||||||
|
|
||||||
|
|
||||||
def emit_turn_event(event: TurnEvent, *, conversation_id: str) -> str:
|
def emit_turn_event(event: TurnEvent, *, conversation_id: str) -> str:
|
||||||
|
|||||||
@@ -194,6 +194,7 @@ class ChatTurnRuntime:
|
|||||||
conversation_id=session.session_id,
|
conversation_id=session.session_id,
|
||||||
message=exc.message,
|
message=exc.message,
|
||||||
code=str(getattr(exc, "code", "") or "") or None,
|
code=str(getattr(exc, "code", "") or "") or None,
|
||||||
|
user_facing=True,
|
||||||
)
|
)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
current_app.logger.exception("[chat-turn] unexpected failure request_id=%s turn_id=%s", req_id, turn_id)
|
current_app.logger.exception("[chat-turn] unexpected failure request_id=%s turn_id=%s", req_id, turn_id)
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ backend/app/services/contract_payment/parse_service.py
|
|||||||
依赖:标准库正则与日期处理;原文抽取由调用方传入,避免绑定某一种文件解析器。
|
依赖:标准库正则与日期处理;原文抽取由调用方传入,避免绑定某一种文件解析器。
|
||||||
逻辑:先识别固定字段和付款比例,再校验金额/比例/日期;无法确定的事实进入 needs_review,不猜测。
|
逻辑:先识别固定字段和付款比例,再校验金额/比例/日期;无法确定的事实进入 needs_review,不猜测。
|
||||||
合同金额以正文抽出的正数为准;OA 的 0 与空值都不是有效总额。同一付款阶段的相同比例重复抽取不报重复。
|
合同金额以正文抽出的正数为准;OA 的 0 与空值都不是有效总额。同一付款阶段的相同比例重复抽取不报重复。
|
||||||
|
增值税税率和「收到定金后 N 天」不计入付款比例。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -24,7 +25,12 @@ from app.services.procurement_contract.analyze import extract_text_from_bytes
|
|||||||
|
|
||||||
_DATE_RE = re.compile(r"(20\d{2})[\s_]*[年./-][\s_]*(\d{1,2})[\s_]*[月./-][\s_]*(\d{1,2})[\s_]*日?")
|
_DATE_RE = re.compile(r"(20\d{2})[\s_]*[年./-][\s_]*(\d{1,2})[\s_]*[月./-][\s_]*(\d{1,2})[\s_]*日?")
|
||||||
_MONEY_RE = re.compile(r"(?:设备总价款\s*[((]?含税[))]?|人民币合同金额|合同金额|合同总价|含税总价)[::\s¥¥]*([\d,]+(?:\.\d+)?)", re.I)
|
_MONEY_RE = re.compile(r"(?:设备总价款\s*[((]?含税[))]?|人民币合同金额|合同金额|合同总价|含税总价)[::\s¥¥]*([\d,]+(?:\.\d+)?)", re.I)
|
||||||
_PERCENT_RE = re.compile(r"(预付款|定金|出货款|货款|验收款|质保款|保款|尾款)[^。;;\n]{0,140}?(\d+(?:\.\d+)?)\s*%", re.S)
|
_STAGE_LABEL_RE = re.compile(r"预付款|定金|出货款|货款|验收款|质保款|保款|尾款")
|
||||||
|
_PERCENT_VALUE_RE = re.compile(r"(\d+(?:\.\d+)?)\s*%")
|
||||||
|
_DEPOSIT_SCHEDULE_RE = re.compile(r"定金\s*后\s*\d+\s*(?:个)?(?:工作日|天|日)")
|
||||||
|
_SENTENCE_BREAK_RE = re.compile(r"[。;;\n]")
|
||||||
|
_TAX_PREFIX_RE = re.compile(r"(?:增值税|税率)\s*$")
|
||||||
|
_TAX_SUFFIX_RE = re.compile(r"\s*(?:的\s*)?增值税")
|
||||||
_DELIVERY_RE = re.compile(r"(?:交货期限|约定到货日期|交付期限|交货期)[::\s]*[^。;;\n]{0,60}?(20\d{2}[^\n。;;]*)")
|
_DELIVERY_RE = re.compile(r"(?:交货期限|约定到货日期|交付期限|交货期)[::\s]*[^。;;\n]{0,60}?(20\d{2}[^\n。;;]*)")
|
||||||
_WARRANTY_RE = re.compile(r"(?:质保期|保修期|保固期|质保款[^。;;\n]{0,100}?)(?:满后|为|:|:)?\s*(\d+)\s*(年|个月|月|天)")
|
_WARRANTY_RE = re.compile(r"(?:质保期|保修期|保固期|质保款[^。;;\n]{0,100}?)(?:满后|为|:|:)?\s*(\d+)\s*(年|个月|月|天)")
|
||||||
_WARRANTY_PAYMENT_RE = re.compile(
|
_WARRANTY_PAYMENT_RE = re.compile(
|
||||||
@@ -146,12 +152,82 @@ def unique_parse_issues(issues: list[Any] | None) -> list[str]:
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _is_tax_percentage(body: str, number_start: int, percent_end: int) -> bool:
|
||||||
|
"""
|
||||||
|
判断百分号是增值税或税率,而不是付款比例。
|
||||||
|
|
||||||
|
核心逻辑:数字前紧挨「增值税」或「税率」,或百分号后紧挨「增值税」,都视为税率。
|
||||||
|
「含13%增值税」靠百分号后面的「增值税」识别;单独的「含30%」仍可当作付款比例。
|
||||||
|
Args:
|
||||||
|
body: 合同正文。
|
||||||
|
number_start: 百分数数字在正文中的起始下标。
|
||||||
|
percent_end: 百分号结束下标,不含其后的文字。
|
||||||
|
Returns:
|
||||||
|
该百分号是税率时返回 True。
|
||||||
|
"""
|
||||||
|
before = body[max(0, number_start - 16):number_start]
|
||||||
|
after = body[percent_end:percent_end + 16]
|
||||||
|
return _TAX_PREFIX_RE.search(before) is not None or _TAX_SUFFIX_RE.match(after) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def _first_payment_percentage(body: str, label_end: int) -> re.Match[str] | None:
|
||||||
|
"""
|
||||||
|
在阶段词后的同一句、140 字内取第一个非税率百分号。
|
||||||
|
|
||||||
|
核心逻辑:税率百分号跳过并继续看,避免「含13%增值税」挡住同一句里的「总价款的30%」。
|
||||||
|
遇到句号、分号或换行即停止,窗口长度与原先一致。
|
||||||
|
Args:
|
||||||
|
body: 合同正文。
|
||||||
|
label_end: 阶段词结束下标。
|
||||||
|
Returns:
|
||||||
|
付款比例的正则匹配;窗口内没有可用百分号时返回 None。
|
||||||
|
"""
|
||||||
|
window_end = label_end + 140
|
||||||
|
sentence = _SENTENCE_BREAK_RE.search(body, label_end)
|
||||||
|
if sentence and sentence.start() < window_end:
|
||||||
|
window_end = sentence.start()
|
||||||
|
cursor = label_end
|
||||||
|
while cursor < window_end:
|
||||||
|
value_match = _PERCENT_VALUE_RE.search(body, cursor, window_end)
|
||||||
|
if value_match is None:
|
||||||
|
return None
|
||||||
|
if _is_tax_percentage(body, value_match.start(1), value_match.end()):
|
||||||
|
cursor = value_match.end()
|
||||||
|
continue
|
||||||
|
return value_match
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _matched_payment_percentages(body: str) -> list[tuple[str, str]]:
|
||||||
|
"""
|
||||||
|
抽出每个付款阶段词对应的第一个付款比例。
|
||||||
|
|
||||||
|
核心逻辑:「收到定金后 N 天」是完成日期,不作为预付款锚点。
|
||||||
|
其余阶段词沿用原窗口,但丢掉增值税、税率百分号。
|
||||||
|
Args:
|
||||||
|
body: 已抽取的合同正文。
|
||||||
|
Returns:
|
||||||
|
(阶段词, 百分数字符串) 列表,按出现顺序。未命中付款比例的阶段词不出现。
|
||||||
|
"""
|
||||||
|
matched: list[tuple[str, str]] = []
|
||||||
|
for label_match in _STAGE_LABEL_RE.finditer(body):
|
||||||
|
label = label_match.group(0)
|
||||||
|
if label == "定金" and _DEPOSIT_SCHEDULE_RE.match(body, label_match.start()):
|
||||||
|
continue
|
||||||
|
value_match = _first_payment_percentage(body, label_match.end())
|
||||||
|
if value_match is None:
|
||||||
|
continue
|
||||||
|
matched.append((label, value_match.group(1)))
|
||||||
|
return matched
|
||||||
|
|
||||||
|
|
||||||
def _extract_payment_percentages(body: str) -> tuple[dict[str, Decimal], list[str]]:
|
def _extract_payment_percentages(body: str) -> tuple[dict[str, Decimal], list[str]]:
|
||||||
"""
|
"""
|
||||||
提取四阶段付款比例,并校验阶段完整性及比例合计。
|
提取四阶段付款比例,并校验阶段完整性及比例合计。
|
||||||
|
|
||||||
核心逻辑:同一语义阶段只允许一个比例。正文里同一比例被抽到多次(表格/页眉重复)
|
核心逻辑:同一语义阶段只允许一个比例。正文里同一比例被抽到多次(表格/页眉重复)
|
||||||
视为同一事实,不报重复;只有同一阶段出现不同比例才阻断。四阶段须完整且合计 100%。
|
视为同一事实,不报重复;只有同一阶段出现不同比例才阻断。四阶段须完整且合计 100%。
|
||||||
|
增值税税率和「收到定金后 N 天」不计入付款比例。
|
||||||
Args:
|
Args:
|
||||||
body: 已抽取的合同正文。
|
body: 已抽取的合同正文。
|
||||||
Returns:
|
Returns:
|
||||||
@@ -159,8 +235,8 @@ def _extract_payment_percentages(body: str) -> tuple[dict[str, Decimal], list[st
|
|||||||
"""
|
"""
|
||||||
found: dict[str, list[Decimal]] = {node_type: [] for node_type in _PAYMENT_NODE_TYPES}
|
found: dict[str, list[Decimal]] = {node_type: [] for node_type in _PAYMENT_NODE_TYPES}
|
||||||
issues: list[str] = []
|
issues: list[str] = []
|
||||||
for match in _PERCENT_RE.finditer(body):
|
matched = _matched_payment_percentages(body)
|
||||||
label, raw = match.groups()
|
for label, raw in matched:
|
||||||
node_type = _PAYMENT_LABEL_TO_NODE_TYPE[label]
|
node_type = _PAYMENT_LABEL_TO_NODE_TYPE[label]
|
||||||
percentage = _parse_decimal(raw)
|
percentage = _parse_decimal(raw)
|
||||||
if percentage is None:
|
if percentage is None:
|
||||||
@@ -181,7 +257,6 @@ def _extract_payment_percentages(body: str) -> tuple[dict[str, Decimal], list[st
|
|||||||
if missing:
|
if missing:
|
||||||
issues.append(f"付款阶段比例无法识别:{'、'.join(_PAYMENT_NODE_LABELS[item] for item in missing)}")
|
issues.append(f"付款阶段比例无法识别:{'、'.join(_PAYMENT_NODE_LABELS[item] for item in missing)}")
|
||||||
try:
|
try:
|
||||||
matched = [(m.group(1), m.group(2)) for m in _PERCENT_RE.finditer(body)]
|
|
||||||
snippet = ""
|
snippet = ""
|
||||||
for label in ("质保款", "验收款", "尾款"):
|
for label in ("质保款", "验收款", "尾款"):
|
||||||
idx = body.find(label)
|
idx = body.find(label)
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
"""
|
||||||
|
backend/app/services/equipment_acceptance/__init__.py
|
||||||
|
|
||||||
|
用途:设备验收预警同步包。
|
||||||
|
依赖:snapshot_rules、source_group、query_sql、sync_service。
|
||||||
|
逻辑:本包只做 OA 只读同步和本地快照,不发送企业微信。
|
||||||
|
"""
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
"""
|
||||||
|
backend/app/services/equipment_acceptance/alert_plan.py
|
||||||
|
|
||||||
|
用途:判断验收单跨了哪几档,并把主送、抄送收成一条待发送。
|
||||||
|
依赖:无。不读数据库,不访问 OA,不发企业微信。
|
||||||
|
逻辑:扫描服务先解析出人员,再调用本模块去重和定状态。超过天数才进档,等于阈值不算。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
def due_tiers(dwell_days: int | None, thresholds: tuple[int, int, int, int]) -> list[int]:
|
||||||
|
"""
|
||||||
|
按累计天数给出已经跨过的档位。
|
||||||
|
|
||||||
|
核心逻辑:需求是「超过 N 天」。停留刚好等于阈值时还不发。四档各自独立,一次可以跨多档。
|
||||||
|
Args:
|
||||||
|
dwell_days: 签核自然日。没有计时起点时为空。
|
||||||
|
thresholds: 四个天数,对应第 1 到第 4 档。
|
||||||
|
Returns:
|
||||||
|
档位号 1 到 4 的列表。没有跨档时为空。
|
||||||
|
"""
|
||||||
|
if dwell_days is None:
|
||||||
|
return []
|
||||||
|
return [index + 1 for index, day in enumerate(thresholds) if dwell_days > day]
|
||||||
|
|
||||||
|
|
||||||
|
def make_person(
|
||||||
|
*,
|
||||||
|
slot: str,
|
||||||
|
label: str,
|
||||||
|
name: str | None = None,
|
||||||
|
user_id: int | None = None,
|
||||||
|
wecom_userid: str | None = None,
|
||||||
|
oa_employee_id: int | None = None,
|
||||||
|
error: str | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
收成一名收件人。
|
||||||
|
|
||||||
|
核心逻辑:解析失败时留下 error,不改成别的人。
|
||||||
|
Args:
|
||||||
|
slot: to 主送,cc 抄送。
|
||||||
|
label: 角色名称,例如当前处理人、直接主管。
|
||||||
|
name: 展示姓名。
|
||||||
|
user_id: 系统用户主键。对不上时为空。
|
||||||
|
wecom_userid: 已绑定的企业微信 userid。
|
||||||
|
oa_employee_id: E10 employee.ID。
|
||||||
|
error: 解析失败原因。成功时为空。
|
||||||
|
Returns:
|
||||||
|
写入 recipients_json 的字典。
|
||||||
|
"""
|
||||||
|
return {
|
||||||
|
"slot": slot,
|
||||||
|
"label": label,
|
||||||
|
"name": name,
|
||||||
|
"user_id": user_id,
|
||||||
|
"wecom_userid": wecom_userid or None,
|
||||||
|
"oa_employee_id": oa_employee_id,
|
||||||
|
"error": error,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_account(
|
||||||
|
*,
|
||||||
|
slot: str,
|
||||||
|
label: str,
|
||||||
|
name: str | None,
|
||||||
|
job_num: str | None,
|
||||||
|
user: Any,
|
||||||
|
missing_job_error: str,
|
||||||
|
oa_employee_id: int | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
用工号对上系统用户,并要求已绑定企业微信。
|
||||||
|
|
||||||
|
核心逻辑:没有工号、对不上用户、没绑企微都记失败,不换成别人。
|
||||||
|
Args:
|
||||||
|
slot: to 或 cc。
|
||||||
|
label: 角色名称。
|
||||||
|
name: OA 或快照上的姓名。
|
||||||
|
job_num: employee.JOB_NUM,对应 users.employee_id。
|
||||||
|
user: 已按工号找到的用户。需要 id、wecom_userid,姓名优先 real_name。
|
||||||
|
missing_job_error: 没有工号时的失败原因。
|
||||||
|
oa_employee_id: E10 人员 ID。
|
||||||
|
Returns:
|
||||||
|
一名收件人。
|
||||||
|
"""
|
||||||
|
if not str(job_num or "").strip():
|
||||||
|
return make_person(
|
||||||
|
slot=slot,
|
||||||
|
label=label,
|
||||||
|
name=name,
|
||||||
|
oa_employee_id=oa_employee_id,
|
||||||
|
error=missing_job_error,
|
||||||
|
)
|
||||||
|
if user is None:
|
||||||
|
return make_person(
|
||||||
|
slot=slot,
|
||||||
|
label=label,
|
||||||
|
name=name,
|
||||||
|
oa_employee_id=oa_employee_id,
|
||||||
|
error="未对上系统用户",
|
||||||
|
)
|
||||||
|
display = _user_name(user) or name
|
||||||
|
wecom = str(getattr(user, "wecom_userid", None) or "").strip()
|
||||||
|
if not wecom:
|
||||||
|
return make_person(
|
||||||
|
slot=slot,
|
||||||
|
label=label,
|
||||||
|
name=display,
|
||||||
|
user_id=getattr(user, "id", None),
|
||||||
|
oa_employee_id=oa_employee_id,
|
||||||
|
error="未绑定企业微信",
|
||||||
|
)
|
||||||
|
return make_person(
|
||||||
|
slot=slot,
|
||||||
|
label=label,
|
||||||
|
name=display,
|
||||||
|
user_id=getattr(user, "id", None),
|
||||||
|
wecom_userid=wecom,
|
||||||
|
oa_employee_id=oa_employee_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_configured_user(*, slot: str, label: str, user: Any, missing_error: str) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
把预警配置里的固定岗位收成收件人。
|
||||||
|
|
||||||
|
核心逻辑:没选人或没绑企微都记失败。不使用代码里的姓名兜底。
|
||||||
|
Args:
|
||||||
|
slot: to 或 cc。
|
||||||
|
label: 采购经副理、COO 或总经理。
|
||||||
|
user: 配置指向的系统用户。空表示未选。
|
||||||
|
missing_error: 未选人时的失败原因。
|
||||||
|
Returns:
|
||||||
|
一名收件人。
|
||||||
|
"""
|
||||||
|
if user is None:
|
||||||
|
return make_person(slot=slot, label=label, error=missing_error)
|
||||||
|
return resolve_account(
|
||||||
|
slot=slot,
|
||||||
|
label=label,
|
||||||
|
name=_user_name(user),
|
||||||
|
job_num="configured",
|
||||||
|
user=user,
|
||||||
|
missing_job_error=missing_error,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def assemble_tier(
|
||||||
|
*,
|
||||||
|
tier: int,
|
||||||
|
threshold_days: int,
|
||||||
|
to_people: list[dict[str, Any]],
|
||||||
|
cc_people: list[dict[str, Any]],
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
把一档的主送和抄送收成一条发送记录草稿。
|
||||||
|
|
||||||
|
核心逻辑:同一人同时出现在主送和抄送时只留主送。至少有一名可发的人则为待发送,否则整档失败。
|
||||||
|
失败原因留在记录上,不把名额转给别人。
|
||||||
|
Args:
|
||||||
|
tier: 1 到 4。
|
||||||
|
threshold_days: 这一档的天数。
|
||||||
|
to_people: 主送。
|
||||||
|
cc_people: 抄送。
|
||||||
|
Returns:
|
||||||
|
tier、threshold_days、to_text、cc_text、recipients、status、error_message。
|
||||||
|
"""
|
||||||
|
primary = _dedupe(to_people)
|
||||||
|
copied = _drop_already_primary(_dedupe(cc_people), primary)
|
||||||
|
recipients = primary + copied
|
||||||
|
errors = [item["error"] for item in recipients if item.get("error")]
|
||||||
|
ready = any(item.get("wecom_userid") and not item.get("error") for item in recipients)
|
||||||
|
return {
|
||||||
|
"tier": tier,
|
||||||
|
"threshold_days": threshold_days,
|
||||||
|
"to_text": _names(primary) or None,
|
||||||
|
"cc_text": _names(copied) or None,
|
||||||
|
"recipients": recipients,
|
||||||
|
"status": "pending" if ready else "failed",
|
||||||
|
"error_message": ";".join(errors) or None,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _dedupe(people: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||||
|
"""同一系统用户或同一 OA 人员只留第一次。解析失败的行各自保留。"""
|
||||||
|
seen: set[tuple[Any, ...]] = set()
|
||||||
|
kept: list[dict[str, Any]] = []
|
||||||
|
for person in people:
|
||||||
|
if person.get("user_id"):
|
||||||
|
key: tuple[Any, ...] = ("user", person["user_id"])
|
||||||
|
elif person.get("oa_employee_id") and not person.get("error"):
|
||||||
|
key = ("oa", person["oa_employee_id"])
|
||||||
|
else:
|
||||||
|
key = ("error", person.get("label"), person.get("name"), person.get("error"))
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
kept.append(person)
|
||||||
|
return kept
|
||||||
|
|
||||||
|
|
||||||
|
def _drop_already_primary(copied: list[dict[str, Any]], primary: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||||
|
"""抄送里已经是主送的人不再重复。"""
|
||||||
|
keys = {_identity(person) for person in primary}
|
||||||
|
return [person for person in copied if _identity(person) not in keys]
|
||||||
|
|
||||||
|
|
||||||
|
def _identity(person: dict[str, Any]) -> tuple[Any, ...]:
|
||||||
|
"""用系统用户或 OA 人员识别同一个人。失败行用原因区分。"""
|
||||||
|
if person.get("user_id"):
|
||||||
|
return ("user", person["user_id"])
|
||||||
|
if person.get("oa_employee_id") and not person.get("error"):
|
||||||
|
return ("oa", person["oa_employee_id"])
|
||||||
|
return ("error", person.get("label"), person.get("name"), person.get("error"))
|
||||||
|
|
||||||
|
|
||||||
|
def _names(people: list[dict[str, Any]]) -> str:
|
||||||
|
"""只拼接解析成功的姓名。"""
|
||||||
|
return "、".join(str(person["name"]) for person in people if person.get("name") and not person.get("error"))
|
||||||
|
|
||||||
|
|
||||||
|
def _user_name(user: Any) -> str | None:
|
||||||
|
"""系统用户展示名:真实姓名优先,其次用户名。"""
|
||||||
|
real_name = str(getattr(user, "real_name", None) or "").strip()
|
||||||
|
if real_name:
|
||||||
|
return real_name
|
||||||
|
username = str(getattr(user, "username", None) or "").strip()
|
||||||
|
return username or None
|
||||||
@@ -0,0 +1,481 @@
|
|||||||
|
"""
|
||||||
|
backend/app/services/equipment_acceptance/alert_service.py
|
||||||
|
|
||||||
|
用途:每日扫描生成设备验收待发送记录,并在周五按收件人发送企业微信。
|
||||||
|
依赖:同步服务、OA 人员目录、alert_plan、发送记录模型、企微通知。
|
||||||
|
逻辑:扫描先同步 E10,再按停留天数跨档。停表取消未发送记录。已发送的不重发、不改收件人。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.extensions import db
|
||||||
|
from app.models.equipment_acceptance import (
|
||||||
|
EquipmentAcceptanceOperator,
|
||||||
|
EquipmentAcceptanceOrder,
|
||||||
|
EquipmentAcceptanceSendRecord,
|
||||||
|
EquipmentAcceptanceSetting,
|
||||||
|
)
|
||||||
|
from app.models.user import User
|
||||||
|
from app.services.equipment_acceptance.alert_plan import (
|
||||||
|
assemble_tier,
|
||||||
|
due_tiers,
|
||||||
|
make_person,
|
||||||
|
resolve_account,
|
||||||
|
resolve_configured_user,
|
||||||
|
)
|
||||||
|
from app.services.equipment_acceptance.config_service import reminder_days
|
||||||
|
from app.services.equipment_acceptance.snapshot_rules import WATCHING
|
||||||
|
|
||||||
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
_SETTING_ID = 1
|
||||||
|
_EVENT = "equipment_acceptance_warning"
|
||||||
|
_UNSENT = ("pending", "failed")
|
||||||
|
|
||||||
|
|
||||||
|
def generate_alerts() -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
同步 E10 后生成或更新待发送记录。
|
||||||
|
|
||||||
|
核心逻辑:先拉最新节点和停表状态,再按当前处理人解析收件人。本函数不发企业微信。
|
||||||
|
Returns:
|
||||||
|
sync 摘要,以及 created、updated、cancelled 条数。
|
||||||
|
"""
|
||||||
|
from app.services.equipment_acceptance.sync_service import sync_acceptance_snapshots
|
||||||
|
|
||||||
|
sync_result = sync_acceptance_snapshots()
|
||||||
|
summary = refresh_pending_alerts()
|
||||||
|
# 同步提交时已经取消的未发送,刷新阶段不会再数到,这里加回去。
|
||||||
|
summary["cancelled"] += int(sync_result.get("cancelled") or 0)
|
||||||
|
summary["sync"] = sync_result
|
||||||
|
return summary
|
||||||
|
|
||||||
|
|
||||||
|
def refresh_pending_alerts(
|
||||||
|
*,
|
||||||
|
directory: tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]] | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
按本地快照刷新待发送记录。
|
||||||
|
|
||||||
|
核心逻辑:计时中的单据跨过哪一档就保留哪一档。已发送和已取消不改。
|
||||||
|
未计时或已停表的单据,把还没发出的记录改成已取消。
|
||||||
|
Args:
|
||||||
|
directory: 测试注入的人员目录和经副理。空则查询 E10。
|
||||||
|
Returns:
|
||||||
|
created、updated、cancelled。
|
||||||
|
"""
|
||||||
|
orders = db.session.query(EquipmentAcceptanceOrder).all()
|
||||||
|
operators = _operators_by_order([order.id for order in orders])
|
||||||
|
people, deputies = directory if directory is not None else _load_directory(orders, operators)
|
||||||
|
users_by_job = _users_by_job(_job_numbers(orders, operators, people, deputies))
|
||||||
|
roles = _configured_users()
|
||||||
|
thresholds = reminder_days()
|
||||||
|
existing = {
|
||||||
|
(row.order_id, row.tier): row
|
||||||
|
for row in db.session.query(EquipmentAcceptanceSendRecord).all()
|
||||||
|
if row.order_id is not None
|
||||||
|
}
|
||||||
|
created = 0
|
||||||
|
updated = 0
|
||||||
|
cancelled = 0
|
||||||
|
for order in orders:
|
||||||
|
if order.monitor_status != WATCHING:
|
||||||
|
cancelled += cancel_unsent(order.id)
|
||||||
|
continue
|
||||||
|
for draft in _drafts(order, operators.get(order.id, []), people, deputies, users_by_job, roles, thresholds):
|
||||||
|
current = existing.get((order.id, draft["tier"]))
|
||||||
|
if current is not None and current.status in ("sent", "cancelled"):
|
||||||
|
continue
|
||||||
|
if current is None:
|
||||||
|
current = EquipmentAcceptanceSendRecord(
|
||||||
|
order_id=order.id,
|
||||||
|
tier=draft["tier"],
|
||||||
|
threshold_days=draft["threshold_days"],
|
||||||
|
status=draft["status"],
|
||||||
|
created_at=datetime.utcnow(),
|
||||||
|
)
|
||||||
|
db.session.add(current)
|
||||||
|
existing[(order.id, draft["tier"])] = current
|
||||||
|
created += 1
|
||||||
|
else:
|
||||||
|
updated += 1
|
||||||
|
_apply_draft(current, order, draft)
|
||||||
|
db.session.commit()
|
||||||
|
return {"created": created, "updated": updated, "cancelled": cancelled}
|
||||||
|
|
||||||
|
|
||||||
|
def cancel_unsent(order_id: int) -> int:
|
||||||
|
"""
|
||||||
|
取消一张验收单上还没发出的预警。
|
||||||
|
|
||||||
|
核心逻辑:待发送和解析失败都还没出企业微信,停表后改成已取消。已发送的保留。
|
||||||
|
Args:
|
||||||
|
order_id: 本地验收单主键。
|
||||||
|
Returns:
|
||||||
|
改成已取消的行数。
|
||||||
|
"""
|
||||||
|
rows = (
|
||||||
|
db.session.query(EquipmentAcceptanceSendRecord)
|
||||||
|
.filter(
|
||||||
|
EquipmentAcceptanceSendRecord.order_id == order_id,
|
||||||
|
EquipmentAcceptanceSendRecord.status.in_(_UNSENT),
|
||||||
|
EquipmentAcceptanceSendRecord.sent_at.is_(None),
|
||||||
|
)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
for row in rows:
|
||||||
|
row.status = "cancelled"
|
||||||
|
return len(rows)
|
||||||
|
|
||||||
|
|
||||||
|
def send_pending_alerts() -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
把待发送记录按收件人合并成一条企业微信。
|
||||||
|
|
||||||
|
核心逻辑:同一个人本轮只收一条。解析失败的人不改发给别人。已取消和已发送不参与。
|
||||||
|
Returns:
|
||||||
|
成功人数、失败人数,以及对应的记录条数。
|
||||||
|
"""
|
||||||
|
from app.models import Agent
|
||||||
|
from app.services.integrations.wecom.notify import send_wecom_event_message
|
||||||
|
|
||||||
|
rows = (
|
||||||
|
db.session.query(EquipmentAcceptanceSendRecord)
|
||||||
|
.filter(EquipmentAcceptanceSendRecord.status == "pending")
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
orders = {
|
||||||
|
order.id: order
|
||||||
|
for order in db.session.query(EquipmentAcceptanceOrder)
|
||||||
|
.filter(EquipmentAcceptanceOrder.id.in_([row.order_id for row in rows if row.order_id]))
|
||||||
|
.all()
|
||||||
|
} if rows else {}
|
||||||
|
users = _users_by_id(_recipient_user_ids(rows))
|
||||||
|
buckets: dict[str, list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]]] = {}
|
||||||
|
for row in rows:
|
||||||
|
for person in list(row.recipients_json or []):
|
||||||
|
wecom_id = str(person.get("wecom_userid") or "").strip()
|
||||||
|
if person.get("error") or not wecom_id:
|
||||||
|
continue
|
||||||
|
buckets.setdefault(wecom_id, []).append((row, person))
|
||||||
|
agent = db.session.query(Agent).filter_by(agent_code="equipment_acceptance", is_active=True).first()
|
||||||
|
jump_path = f"/chat/{agent.id}" if agent is not None else "/workspace"
|
||||||
|
jump_params = {"view": "sends"} if agent is not None else None
|
||||||
|
sent_ids: set[str] = set()
|
||||||
|
failed_ids: set[str] = set()
|
||||||
|
for wecom_id, entries in buckets.items():
|
||||||
|
user = _audit_user(entries, users)
|
||||||
|
try:
|
||||||
|
result = send_wecom_event_message(
|
||||||
|
event_type=_EVENT,
|
||||||
|
user=user,
|
||||||
|
title="设备验收停留提醒",
|
||||||
|
content=_message(entries, orders),
|
||||||
|
jump_path=jump_path,
|
||||||
|
jump_params=jump_params,
|
||||||
|
wecom_userid=wecom_id,
|
||||||
|
)
|
||||||
|
ok = bool(result.get("ok"))
|
||||||
|
except Exception:
|
||||||
|
_LOGGER.warning("equipment acceptance wecom send failed")
|
||||||
|
ok = False
|
||||||
|
(sent_ids if ok else failed_ids).add(wecom_id)
|
||||||
|
records_sent = 0
|
||||||
|
records_failed = 0
|
||||||
|
now = datetime.utcnow()
|
||||||
|
for row in rows:
|
||||||
|
ready = {
|
||||||
|
str(person.get("wecom_userid") or "").strip()
|
||||||
|
for person in list(row.recipients_json or [])
|
||||||
|
if person.get("wecom_userid") and not person.get("error")
|
||||||
|
}
|
||||||
|
ready.discard("")
|
||||||
|
if not ready:
|
||||||
|
continue
|
||||||
|
if ready & failed_ids:
|
||||||
|
row.status = "failed"
|
||||||
|
row.error_message = _join_error(row.error_message, "企业微信发送失败")
|
||||||
|
records_failed += 1
|
||||||
|
elif ready <= sent_ids:
|
||||||
|
row.status = "sent"
|
||||||
|
row.sent_at = now
|
||||||
|
records_sent += 1
|
||||||
|
db.session.commit()
|
||||||
|
return {
|
||||||
|
"sent": len(sent_ids),
|
||||||
|
"failed": len(failed_ids),
|
||||||
|
"records_sent": records_sent,
|
||||||
|
"records_failed": records_failed,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _drafts(
|
||||||
|
order: EquipmentAcceptanceOrder,
|
||||||
|
operators: list[EquipmentAcceptanceOperator],
|
||||||
|
people: dict[int, dict[str, Any]],
|
||||||
|
deputies: dict[str, list[dict[str, Any]]],
|
||||||
|
users_by_job: dict[str, User],
|
||||||
|
roles: dict[str, User | None],
|
||||||
|
thresholds: tuple[int, int, int, int],
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
"""按当前处理人展开四档里已经跨过的档。"""
|
||||||
|
due = due_tiers(order.dwell_days, thresholds)
|
||||||
|
if not due:
|
||||||
|
return []
|
||||||
|
handlers: list[dict[str, Any]] = []
|
||||||
|
supervisors: list[dict[str, Any]] = []
|
||||||
|
deputy_people: list[dict[str, Any]] = []
|
||||||
|
if not operators:
|
||||||
|
handlers.append(make_person(slot="to", label="当前处理人", error="没有当前处理人"))
|
||||||
|
deputy_people.append(make_person(slot="to", label="经副理", error="没有当前处理人,查不到经副理"))
|
||||||
|
for operator in operators:
|
||||||
|
fact = people.get(operator.user_id) or {}
|
||||||
|
name = fact.get("name") or operator.handler_name
|
||||||
|
job_num = fact.get("job_num") or operator.handler_job_num
|
||||||
|
shown = name or "处理人"
|
||||||
|
handlers.append(resolve_account(
|
||||||
|
slot="to",
|
||||||
|
label="当前处理人",
|
||||||
|
name=name,
|
||||||
|
job_num=job_num,
|
||||||
|
user=users_by_job.get(str(job_num or "")),
|
||||||
|
missing_job_error=f"{shown}没有工号",
|
||||||
|
oa_employee_id=operator.user_id,
|
||||||
|
))
|
||||||
|
superior_id = fact.get("superior_id")
|
||||||
|
if superior_id is None:
|
||||||
|
supervisors.append(make_person(slot="cc", label="直接主管", name=name, error=f"{shown}没有直接主管"))
|
||||||
|
else:
|
||||||
|
supervisors.append(resolve_account(
|
||||||
|
slot="cc",
|
||||||
|
label="直接主管",
|
||||||
|
name=fact.get("superior_name"),
|
||||||
|
job_num=fact.get("superior_job_num"),
|
||||||
|
user=users_by_job.get(str(fact.get("superior_job_num") or "")),
|
||||||
|
missing_job_error=f"{shown}的直接主管没有工号",
|
||||||
|
oa_employee_id=superior_id,
|
||||||
|
))
|
||||||
|
found = deputies.get(str(fact.get("department_id") or ""), [])
|
||||||
|
if not found:
|
||||||
|
deputy_people.append(make_person(slot="to", label="经副理", name=name, error=f"{shown}没有经副理"))
|
||||||
|
else:
|
||||||
|
for item in found:
|
||||||
|
deputy_people.append(resolve_account(
|
||||||
|
slot="to",
|
||||||
|
label="经副理",
|
||||||
|
name=item.get("name"),
|
||||||
|
job_num=item.get("job_num"),
|
||||||
|
user=users_by_job.get(str(item.get("job_num") or "")),
|
||||||
|
missing_job_error=f"{shown}的经副理没有工号",
|
||||||
|
oa_employee_id=item.get("oa_id"),
|
||||||
|
))
|
||||||
|
applicant_fact = people.get(order.applicant_oa_id) if order.applicant_oa_id else None
|
||||||
|
applicant = resolve_account(
|
||||||
|
slot="cc",
|
||||||
|
label="采购担当",
|
||||||
|
name=(applicant_fact or {}).get("name") or order.applicant_name,
|
||||||
|
job_num=(applicant_fact or {}).get("job_num") or order.applicant_job_num,
|
||||||
|
user=users_by_job.get(str(((applicant_fact or {}).get("job_num") or order.applicant_job_num) or "")),
|
||||||
|
missing_job_error="没有申请人工号",
|
||||||
|
oa_employee_id=order.applicant_oa_id,
|
||||||
|
)
|
||||||
|
drafts: list[dict[str, Any]] = []
|
||||||
|
if 1 in due:
|
||||||
|
drafts.append(assemble_tier(
|
||||||
|
tier=1,
|
||||||
|
threshold_days=thresholds[0],
|
||||||
|
to_people=handlers,
|
||||||
|
cc_people=[*supervisors, applicant],
|
||||||
|
))
|
||||||
|
if 2 in due:
|
||||||
|
drafts.append(assemble_tier(
|
||||||
|
tier=2,
|
||||||
|
threshold_days=thresholds[1],
|
||||||
|
to_people=deputy_people,
|
||||||
|
cc_people=[
|
||||||
|
resolve_configured_user(slot="cc", label="COO", user=roles.get("coo"), missing_error="未配置COO"),
|
||||||
|
resolve_configured_user(slot="cc", label="采购经副理", user=roles.get("buyer"), missing_error="未配置采购经副理"),
|
||||||
|
],
|
||||||
|
))
|
||||||
|
if 3 in due:
|
||||||
|
drafts.append(assemble_tier(
|
||||||
|
tier=3,
|
||||||
|
threshold_days=thresholds[2],
|
||||||
|
to_people=[resolve_configured_user(slot="to", label="COO", user=roles.get("coo"), missing_error="未配置COO")],
|
||||||
|
cc_people=[resolve_configured_user(slot="cc", label="采购经副理", user=roles.get("buyer"), missing_error="未配置采购经副理")],
|
||||||
|
))
|
||||||
|
if 4 in due:
|
||||||
|
drafts.append(assemble_tier(
|
||||||
|
tier=4,
|
||||||
|
threshold_days=thresholds[3],
|
||||||
|
to_people=[resolve_configured_user(slot="to", label="总经理", user=roles.get("executive"), missing_error="未配置总经理")],
|
||||||
|
cc_people=[
|
||||||
|
resolve_configured_user(slot="cc", label="COO", user=roles.get("coo"), missing_error="未配置COO"),
|
||||||
|
resolve_configured_user(slot="cc", label="采购经副理", user=roles.get("buyer"), missing_error="未配置采购经副理"),
|
||||||
|
],
|
||||||
|
))
|
||||||
|
return drafts
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_draft(row: EquipmentAcceptanceSendRecord, order: EquipmentAcceptanceOrder, draft: dict[str, Any]) -> None:
|
||||||
|
"""把草稿写进未发送的记录。不改创建时间,也不填发送时间。"""
|
||||||
|
row.acceptance_no = order.acceptance_no
|
||||||
|
row.purchase_order_no = order.purchase_order_no
|
||||||
|
row.threshold_days = draft["threshold_days"]
|
||||||
|
row.to_text = draft["to_text"]
|
||||||
|
row.cc_text = draft["cc_text"]
|
||||||
|
row.recipients_json = draft["recipients"]
|
||||||
|
row.status = draft["status"]
|
||||||
|
row.error_message = draft["error_message"]
|
||||||
|
|
||||||
|
|
||||||
|
def _load_directory(
|
||||||
|
orders: list[EquipmentAcceptanceOrder],
|
||||||
|
operators: dict[int, list[EquipmentAcceptanceOperator]],
|
||||||
|
) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]]:
|
||||||
|
"""向 E10 要当前处理人和申请人的主管、部门、经副理。"""
|
||||||
|
from app.services.equipment_acceptance.oa_repository import fetch_alert_directory
|
||||||
|
|
||||||
|
ids: set[int] = set()
|
||||||
|
for group in operators.values():
|
||||||
|
for operator in group:
|
||||||
|
if operator.user_id:
|
||||||
|
ids.add(operator.user_id)
|
||||||
|
for order in orders:
|
||||||
|
if order.monitor_status == WATCHING and order.applicant_oa_id:
|
||||||
|
ids.add(order.applicant_oa_id)
|
||||||
|
return fetch_alert_directory(sorted(ids))
|
||||||
|
|
||||||
|
|
||||||
|
def _job_numbers(
|
||||||
|
orders: list[EquipmentAcceptanceOrder],
|
||||||
|
operators: dict[int, list[EquipmentAcceptanceOperator]],
|
||||||
|
people: dict[int, dict[str, Any]],
|
||||||
|
deputies: dict[str, list[dict[str, Any]]],
|
||||||
|
) -> set[str]:
|
||||||
|
"""收集要对系统用户的工号。"""
|
||||||
|
found: set[str] = set()
|
||||||
|
for order in orders:
|
||||||
|
if order.applicant_job_num:
|
||||||
|
found.add(order.applicant_job_num)
|
||||||
|
for group in operators.values():
|
||||||
|
for operator in group:
|
||||||
|
if operator.handler_job_num:
|
||||||
|
found.add(operator.handler_job_num)
|
||||||
|
for fact in people.values():
|
||||||
|
if fact.get("job_num"):
|
||||||
|
found.add(str(fact["job_num"]))
|
||||||
|
if fact.get("superior_job_num"):
|
||||||
|
found.add(str(fact["superior_job_num"]))
|
||||||
|
for group in deputies.values():
|
||||||
|
for item in group:
|
||||||
|
if item.get("job_num"):
|
||||||
|
found.add(str(item["job_num"]))
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _users_by_job(job_nums: set[str]) -> dict[str, User]:
|
||||||
|
"""用工号索引系统用户。"""
|
||||||
|
if not job_nums:
|
||||||
|
return {}
|
||||||
|
rows = db.session.query(User).filter(User.employee_id.in_(job_nums)).all()
|
||||||
|
return {str(row.employee_id): row for row in rows if row.employee_id}
|
||||||
|
|
||||||
|
|
||||||
|
def _configured_users() -> dict[str, User | None]:
|
||||||
|
"""读取三个固定岗位。没选时对应值是空。"""
|
||||||
|
setting = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
|
||||||
|
ids = []
|
||||||
|
if setting is not None:
|
||||||
|
ids = [item for item in (setting.buyer_manager_user_id, setting.coo_user_id, setting.executive_user_id) if item]
|
||||||
|
found = _users_by_id(ids)
|
||||||
|
if setting is None:
|
||||||
|
return {"buyer": None, "coo": None, "executive": None}
|
||||||
|
return {
|
||||||
|
"buyer": found.get(setting.buyer_manager_user_id or 0),
|
||||||
|
"coo": found.get(setting.coo_user_id or 0),
|
||||||
|
"executive": found.get(setting.executive_user_id or 0),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _users_by_id(user_ids: list[int]) -> dict[int, User]:
|
||||||
|
"""按主键取出系统用户。"""
|
||||||
|
if not user_ids:
|
||||||
|
return {}
|
||||||
|
rows = db.session.query(User).filter(User.id.in_(user_ids)).all()
|
||||||
|
return {row.id: row for row in rows}
|
||||||
|
|
||||||
|
|
||||||
|
def _operators_by_order(order_ids: list[int]) -> dict[int, list[EquipmentAcceptanceOperator]]:
|
||||||
|
"""取出这些验收单的当前处理人。"""
|
||||||
|
if not order_ids:
|
||||||
|
return {}
|
||||||
|
grouped: dict[int, list[EquipmentAcceptanceOperator]] = {}
|
||||||
|
rows = (
|
||||||
|
db.session.query(EquipmentAcceptanceOperator)
|
||||||
|
.filter(EquipmentAcceptanceOperator.order_id.in_(order_ids))
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
for row in rows:
|
||||||
|
grouped.setdefault(row.order_id, []).append(row)
|
||||||
|
return grouped
|
||||||
|
|
||||||
|
|
||||||
|
def _recipient_user_ids(rows: list[EquipmentAcceptanceSendRecord]) -> list[int]:
|
||||||
|
"""从待发送收件人里取出系统用户主键。"""
|
||||||
|
found: list[int] = []
|
||||||
|
for row in rows:
|
||||||
|
for person in list(row.recipients_json or []):
|
||||||
|
if person.get("user_id"):
|
||||||
|
found.append(int(person["user_id"]))
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _audit_user(
|
||||||
|
entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]],
|
||||||
|
users: dict[int, User],
|
||||||
|
) -> User | None:
|
||||||
|
"""取这名收件人在系统里的账号,供企微审计。没有账号时仍按企微 userid 发送。"""
|
||||||
|
for _row, person in entries:
|
||||||
|
user_id = person.get("user_id")
|
||||||
|
if user_id and int(user_id) in users:
|
||||||
|
return users[int(user_id)]
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _message(
|
||||||
|
entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]],
|
||||||
|
orders: dict[int, EquipmentAcceptanceOrder],
|
||||||
|
) -> str:
|
||||||
|
"""拼一名收件人本轮要看的验收单。过长时截断。"""
|
||||||
|
lines: list[str] = []
|
||||||
|
seen: set[int] = set()
|
||||||
|
for row, person in entries:
|
||||||
|
if row.id in seen:
|
||||||
|
continue
|
||||||
|
seen.add(row.id)
|
||||||
|
order = orders.get(row.order_id or 0)
|
||||||
|
days = "—" if order is None or order.dwell_days is None else str(order.dwell_days)
|
||||||
|
role = "主送" if person.get("slot") == "to" else "抄送"
|
||||||
|
lines.append(
|
||||||
|
f"{role} {row.acceptance_no or '—'},采购单 {row.purchase_order_no or '—'},"
|
||||||
|
f"停留 {days} 天,超过 {row.threshold_days} 天"
|
||||||
|
)
|
||||||
|
text = "\n".join(lines[:12])
|
||||||
|
if len(lines) > 12:
|
||||||
|
text = f"{text}\n另有 {len(lines) - 12} 条"
|
||||||
|
return text[:500]
|
||||||
|
|
||||||
|
|
||||||
|
def _join_error(current: str | None, extra: str) -> str:
|
||||||
|
"""把新的失败原因接在原有原因后面。相同句子不重复。"""
|
||||||
|
parts = [part for part in (current, extra) if part]
|
||||||
|
unique: list[str] = []
|
||||||
|
for part in parts:
|
||||||
|
if part not in unique:
|
||||||
|
unique.append(part)
|
||||||
|
return ";".join(unique)
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
"""
|
||||||
|
backend/app/services/equipment_acceptance/config_service.py
|
||||||
|
|
||||||
|
用途:读写设备验收预警配置:四档天数和三个固定岗位。
|
||||||
|
依赖:extensions.db、EquipmentAcceptanceSetting、User、统一错误。
|
||||||
|
逻辑:配置页和停留列表调用。岗位只存系统用户主键。发送时刻不在这里,由排程 Cron 决定。
|
||||||
|
没有配置行时按冻结默认值 30/37/44/51 返回,不把姓名写进代码。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.core.errors import ValidationError
|
||||||
|
from app.core.response import utc_iso
|
||||||
|
from app.extensions import db
|
||||||
|
from app.models.equipment_acceptance import EquipmentAcceptanceSetting
|
||||||
|
from app.models.user import User
|
||||||
|
from app.services.equipment_acceptance.snapshot_rules import FIRST_REMINDER_DAY
|
||||||
|
|
||||||
|
DEFAULT_REMINDER_DAYS = (FIRST_REMINDER_DAY, 37, 44, 51)
|
||||||
|
_SETTING_ID = 1
|
||||||
|
_ROLE_FIELDS = (
|
||||||
|
"buyer_manager_user_id",
|
||||||
|
"coo_user_id",
|
||||||
|
"executive_user_id",
|
||||||
|
)
|
||||||
|
_MAX_DAY = 3650
|
||||||
|
|
||||||
|
|
||||||
|
def reminder_days() -> tuple[int, int, int, int]:
|
||||||
|
"""
|
||||||
|
读取四档天数。
|
||||||
|
|
||||||
|
核心逻辑:没有配置行时用冻结默认值。扫描用这四个数判断有没有跨档。
|
||||||
|
Returns:
|
||||||
|
四个逐档增大的正整数。
|
||||||
|
"""
|
||||||
|
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
|
||||||
|
if row is None:
|
||||||
|
return DEFAULT_REMINDER_DAYS
|
||||||
|
return (int(row.day_1), int(row.day_2), int(row.day_3), int(row.day_4))
|
||||||
|
|
||||||
|
|
||||||
|
def first_reminder_day() -> int:
|
||||||
|
"""
|
||||||
|
读取第 1 档天数,供停留列表判断已逾期。
|
||||||
|
|
||||||
|
核心逻辑:没有配置行时用冻结默认值,避免列表在未保存配置前失去阈值。
|
||||||
|
Returns:
|
||||||
|
正整数天数。
|
||||||
|
"""
|
||||||
|
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
|
||||||
|
if row is None:
|
||||||
|
return DEFAULT_REMINDER_DAYS[0]
|
||||||
|
return int(row.day_1)
|
||||||
|
|
||||||
|
|
||||||
|
def get_acceptance_config(*, include_candidates: bool) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
组装配置页数据。
|
||||||
|
|
||||||
|
核心逻辑:天数和已选用户谁都能看。候选人名单只给平台管理员,避免把全员目录交给普通用户。
|
||||||
|
Args:
|
||||||
|
include_candidates: 为 True 时附带在职用户,供选人弹窗使用。
|
||||||
|
Returns:
|
||||||
|
days、三个岗位用户主键、已选用户、候选人和更新时间。
|
||||||
|
"""
|
||||||
|
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
|
||||||
|
selected_ids = _selected_ids(row)
|
||||||
|
return {
|
||||||
|
"days": list(_days_of(row)),
|
||||||
|
"buyer_manager_user_id": None if row is None else row.buyer_manager_user_id,
|
||||||
|
"coo_user_id": None if row is None else row.coo_user_id,
|
||||||
|
"executive_user_id": None if row is None else row.executive_user_id,
|
||||||
|
"selected_users": _briefs(selected_ids),
|
||||||
|
"users": _candidate_users() if include_candidates else [],
|
||||||
|
"updated_at": None if row is None else utc_iso(row.updated_at),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def save_acceptance_config(payload: dict[str, Any], *, updated_by: int) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
保存四档天数和三个岗位用户。
|
||||||
|
|
||||||
|
核心逻辑:天数必须逐档增大。岗位为空表示未选;有值时必须是已存在的系统用户。
|
||||||
|
保存后只影响以后的预警,这里不改历史发送记录。
|
||||||
|
Args:
|
||||||
|
payload: days 为四个整数;三个岗位字段为用户主键或空。
|
||||||
|
updated_by: 操作人的系统用户主键。
|
||||||
|
Returns:
|
||||||
|
与读取接口相同的配置,并带候选人。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValidationError: 天数不合法,或岗位用户不存在。
|
||||||
|
"""
|
||||||
|
days = validate_reminder_days(payload.get("days"))
|
||||||
|
role_ids = {field: _require_user_id(payload.get(field), field) for field in _ROLE_FIELDS}
|
||||||
|
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
|
||||||
|
if row is None:
|
||||||
|
row = EquipmentAcceptanceSetting(id=_SETTING_ID)
|
||||||
|
db.session.add(row)
|
||||||
|
row.day_1, row.day_2, row.day_3, row.day_4 = days
|
||||||
|
row.buyer_manager_user_id = role_ids["buyer_manager_user_id"]
|
||||||
|
row.coo_user_id = role_ids["coo_user_id"]
|
||||||
|
row.executive_user_id = role_ids["executive_user_id"]
|
||||||
|
row.updated_at = datetime.utcnow()
|
||||||
|
row.updated_by = updated_by
|
||||||
|
db.session.commit()
|
||||||
|
return get_acceptance_config(include_candidates=True)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_reminder_days(raw: Any) -> tuple[int, int, int, int]:
|
||||||
|
"""
|
||||||
|
校验四档天数。
|
||||||
|
|
||||||
|
核心逻辑:必须是四个逐档增大的正整数。布尔值在 Python 里也是 int,这里明确拒绝。
|
||||||
|
Args:
|
||||||
|
raw: 接口里的 days。
|
||||||
|
Returns:
|
||||||
|
四个天数。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValidationError: 不是四个逐档增大的天数。
|
||||||
|
"""
|
||||||
|
if not isinstance(raw, list) or len(raw) != 4:
|
||||||
|
_reject_days()
|
||||||
|
parsed: list[int] = []
|
||||||
|
for value in raw:
|
||||||
|
if isinstance(value, bool) or not isinstance(value, int) or value < 1 or value > _MAX_DAY:
|
||||||
|
_reject_days()
|
||||||
|
parsed.append(value)
|
||||||
|
if not (parsed[0] < parsed[1] < parsed[2] < parsed[3]):
|
||||||
|
_reject_days()
|
||||||
|
return parsed[0], parsed[1], parsed[2], parsed[3]
|
||||||
|
|
||||||
|
|
||||||
|
def _reject_days() -> None:
|
||||||
|
"""四档天数不合法时用同一错误码拒绝。"""
|
||||||
|
raise ValidationError(
|
||||||
|
"设备验收预警的四档天数须逐档增大",
|
||||||
|
code="EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID",
|
||||||
|
details={"field": "days"},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _require_user_id(raw: Any, field: str) -> int | None:
|
||||||
|
"""空岗位允许保存。有值时必须指向 users 表里的一行。"""
|
||||||
|
if raw is None or raw == "":
|
||||||
|
return None
|
||||||
|
if isinstance(raw, bool) or not isinstance(raw, int) or raw <= 0:
|
||||||
|
raise ValidationError(
|
||||||
|
"设备验收预警岗位必须选择系统用户",
|
||||||
|
code="EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID",
|
||||||
|
details={"field": field},
|
||||||
|
)
|
||||||
|
if db.session.get(User, raw) is None:
|
||||||
|
raise ValidationError(
|
||||||
|
"设备验收预警岗位必须选择系统用户",
|
||||||
|
code="EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID",
|
||||||
|
details={"field": field},
|
||||||
|
)
|
||||||
|
return raw
|
||||||
|
|
||||||
|
|
||||||
|
def _days_of(row: EquipmentAcceptanceSetting | None) -> tuple[int, int, int, int]:
|
||||||
|
"""没有配置行时返回冻结默认值。"""
|
||||||
|
if row is None:
|
||||||
|
return DEFAULT_REMINDER_DAYS
|
||||||
|
return (int(row.day_1), int(row.day_2), int(row.day_3), int(row.day_4))
|
||||||
|
|
||||||
|
|
||||||
|
def _selected_ids(row: EquipmentAcceptanceSetting | None) -> list[int]:
|
||||||
|
"""收集三个岗位里已经选中的用户主键,供姓名回显。"""
|
||||||
|
if row is None:
|
||||||
|
return []
|
||||||
|
return [user_id for user_id in (row.buyer_manager_user_id, row.coo_user_id, row.executive_user_id) if user_id]
|
||||||
|
|
||||||
|
|
||||||
|
def _candidate_users() -> list[dict[str, Any]]:
|
||||||
|
"""在职用户,带部门和企微绑定标记,供选人弹窗分组。"""
|
||||||
|
rows = db.session.query(User).filter(User.status == "active").order_by(User.username).all()
|
||||||
|
return [_user_brief(user) for user in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def _briefs(user_ids: list[int]) -> list[dict[str, Any]]:
|
||||||
|
"""按主键取出已选用户。停用用户也返回,避免页面上只剩一个数字。"""
|
||||||
|
if not user_ids:
|
||||||
|
return []
|
||||||
|
rows = db.session.query(User).filter(User.id.in_(user_ids)).all()
|
||||||
|
return [_user_brief(user) for user in rows]
|
||||||
|
|
||||||
|
|
||||||
|
def _user_brief(user: User) -> dict[str, Any]:
|
||||||
|
"""选人组件要的展示字段。姓名只从用户资料来,不另存一份。"""
|
||||||
|
return {
|
||||||
|
"id": user.id,
|
||||||
|
"username": user.username,
|
||||||
|
"real_name": user.real_name,
|
||||||
|
"employee_id": user.employee_id,
|
||||||
|
"department": user.department,
|
||||||
|
"wecom_bound": bool(user.wecom_userid),
|
||||||
|
}
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
"""
|
||||||
|
backend/app/services/equipment_acceptance/oa_repository.py
|
||||||
|
|
||||||
|
用途:只读拉取 E10 验收单、当前节点、操作人,以及直接主管和经副理。
|
||||||
|
依赖:pyodbc、settings、query_sql。不调用 E8 的 OA_SQLSERVER_* 连接。
|
||||||
|
逻辑:先探测实例上的库名,再执行联表查询。经副理矩阵固定在 eteams。查询失败不把连接串写入日志。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||||
|
from app.services.equipment_acceptance.query_sql import _qualified, build_acceptance_sql, resolve_catalogs
|
||||||
|
from app.services.equipment_acceptance.snapshot_rules import as_int
|
||||||
|
from app.services.equipment_acceptance.settings import (
|
||||||
|
EquipmentAcceptanceSqlSettings,
|
||||||
|
load_equipment_acceptance_sql_settings,
|
||||||
|
)
|
||||||
|
|
||||||
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
# 苏州和信「HXJM-审批矩阵」。取值配置是该矩阵下 config_name 为「经副理」的 id。
|
||||||
|
_MATRIX_TENANT = "temkc46eme"
|
||||||
|
_MATRIX_ID = 1115770797884751874
|
||||||
|
_DEPUTY_CONFIG_ID = 1115771897387991041
|
||||||
|
_MATRIX_CATALOG = "eteams"
|
||||||
|
_PREFERRED_DRIVERS = (
|
||||||
|
"ODBC Driver 18 for SQL Server",
|
||||||
|
"ODBC Driver 17 for SQL Server",
|
||||||
|
"SQL Server",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_acceptance_rows() -> list[dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
从 E10 拉验收单联表结果。
|
||||||
|
|
||||||
|
核心逻辑:连接 ecology10 所在实例,按实际库名组装 SQL。不查询 isremark。
|
||||||
|
Returns:
|
||||||
|
字段名为小写别名的字典行。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValidationError: 连接配置不完整,或库名非法。
|
||||||
|
ServiceUnavailableError: 驱动、连接或查询失败。
|
||||||
|
"""
|
||||||
|
settings = load_equipment_acceptance_sql_settings()
|
||||||
|
connection = _open_connection(settings)
|
||||||
|
try:
|
||||||
|
cursor = connection.cursor()
|
||||||
|
cursor.execute("SELECT name FROM sys.databases")
|
||||||
|
names = {str(row[0]) for row in cursor.fetchall() if row and row[0]}
|
||||||
|
try:
|
||||||
|
catalogs = resolve_catalogs(
|
||||||
|
names,
|
||||||
|
form=settings.form_catalog or None,
|
||||||
|
employee=settings.employee_catalog or None,
|
||||||
|
request=settings.request_catalog or None,
|
||||||
|
node=settings.node_catalog or None,
|
||||||
|
)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ValidationError(
|
||||||
|
"设备验收同步找不到要查询的数据库",
|
||||||
|
code="EQUIPMENT_ACCEPTANCE.CONFIG_INVALID",
|
||||||
|
details={"reason": str(exc)},
|
||||||
|
) from exc
|
||||||
|
_LOGGER.info(
|
||||||
|
"equipment acceptance catalogs form=%s employee=%s request=%s node=%s",
|
||||||
|
catalogs.form,
|
||||||
|
catalogs.employee,
|
||||||
|
catalogs.request,
|
||||||
|
catalogs.node,
|
||||||
|
)
|
||||||
|
cursor.execute(build_acceptance_sql(catalogs))
|
||||||
|
columns = [str(col[0]).lower() for col in cursor.description]
|
||||||
|
return [
|
||||||
|
{columns[index]: raw[index] for index in range(len(columns))}
|
||||||
|
for raw in cursor.fetchall()
|
||||||
|
]
|
||||||
|
except (ValidationError, ServiceUnavailableError):
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
_LOGGER.warning("equipment acceptance sql failed error=%s", type(exc).__name__)
|
||||||
|
raise ServiceUnavailableError(
|
||||||
|
"查询 E10 设备验收数据失败",
|
||||||
|
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
|
||||||
|
) from exc
|
||||||
|
finally:
|
||||||
|
connection.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _open_connection(settings: EquipmentAcceptanceSqlSettings):
|
||||||
|
"""
|
||||||
|
打开 E10 只读连接。初始库固定为 ecology10,跨库表名在 SQL 里写全。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ServiceUnavailableError: 没有 pyodbc、没有 ODBC 驱动或连接失败。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
import pyodbc
|
||||||
|
except ImportError as exc:
|
||||||
|
raise ServiceUnavailableError(
|
||||||
|
"未安装 pyodbc,无法连接 E10 SQL Server",
|
||||||
|
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
|
||||||
|
) from exc
|
||||||
|
driver = _pick_driver(pyodbc, settings.driver)
|
||||||
|
database = settings.form_catalog or "ecology10"
|
||||||
|
conn_str = (
|
||||||
|
f"DRIVER={{{driver}}};"
|
||||||
|
f"SERVER={settings.host},{settings.port};"
|
||||||
|
f"DATABASE={database};"
|
||||||
|
f"UID={settings.username};"
|
||||||
|
f"PWD={settings.password};"
|
||||||
|
)
|
||||||
|
if driver != "SQL Server":
|
||||||
|
conn_str += f"Encrypt={settings.encrypt};TrustServerCertificate={settings.trust_cert};"
|
||||||
|
try:
|
||||||
|
return pyodbc.connect(conn_str, timeout=settings.timeout)
|
||||||
|
except Exception as exc:
|
||||||
|
_LOGGER.warning("equipment acceptance connect failed error=%s", type(exc).__name__)
|
||||||
|
raise ServiceUnavailableError(
|
||||||
|
"连接 E10 SQL Server 失败",
|
||||||
|
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_alert_directory(employee_ids: list[int]) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]]:
|
||||||
|
"""
|
||||||
|
读取处理人的直接主管,并按部门查出经副理。
|
||||||
|
|
||||||
|
核心逻辑:主管在 employee.SUPERIOR。经副理不在这一列,按部门 ID 走 eteams 矩阵条件表。
|
||||||
|
人员 ID 必须是整数。没有人员时不连库。
|
||||||
|
Args:
|
||||||
|
employee_ids: 当前处理人和申请人的 employee.ID。
|
||||||
|
Returns:
|
||||||
|
(人员字典, 部门 ID 到经副理列表)。人员字典的键是 employee.ID。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValidationError: 库名不合法。
|
||||||
|
ServiceUnavailableError: 连接或查询失败。
|
||||||
|
"""
|
||||||
|
ids = sorted({int(item) for item in employee_ids})
|
||||||
|
if not ids:
|
||||||
|
return {}, {}
|
||||||
|
settings = load_equipment_acceptance_sql_settings()
|
||||||
|
connection = _open_connection(settings)
|
||||||
|
try:
|
||||||
|
cursor = connection.cursor()
|
||||||
|
cursor.execute("SELECT name FROM sys.databases")
|
||||||
|
names = {str(row[0]) for row in cursor.fetchall() if row and row[0]}
|
||||||
|
catalogs = resolve_catalogs(
|
||||||
|
names,
|
||||||
|
form=settings.form_catalog or None,
|
||||||
|
employee=settings.employee_catalog or None,
|
||||||
|
request=settings.request_catalog or None,
|
||||||
|
node=settings.node_catalog or None,
|
||||||
|
)
|
||||||
|
employee = _qualified(catalogs.employee, "employee")
|
||||||
|
people = _load_people(cursor, employee, ids)
|
||||||
|
departments = sorted({item["department_id"] for item in people.values() if item.get("department_id")})
|
||||||
|
deputies = _load_deputies(cursor, employee, departments)
|
||||||
|
return people, deputies
|
||||||
|
except (ValidationError, ServiceUnavailableError):
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
_LOGGER.warning("equipment acceptance directory sql failed error=%s", type(exc).__name__)
|
||||||
|
raise ServiceUnavailableError(
|
||||||
|
"查询 E10 直接主管和经副理失败",
|
||||||
|
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
|
||||||
|
) from exc
|
||||||
|
finally:
|
||||||
|
connection.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _load_people(cursor: Any, employee: str, employee_ids: list[int]) -> dict[int, dict[str, Any]]:
|
||||||
|
"""按人员 ID 取出姓名、工号、直接主管和部门。"""
|
||||||
|
found: dict[int, dict[str, Any]] = {}
|
||||||
|
for chunk in _chunks(employee_ids):
|
||||||
|
marks = ",".join("?" for _ in chunk)
|
||||||
|
cursor.execute(
|
||||||
|
f"""
|
||||||
|
SELECT e.ID, e.USERNAME, e.JOB_NUM, e.SUPERIOR, e.DEPARTMENT,
|
||||||
|
sup.USERNAME, sup.JOB_NUM
|
||||||
|
FROM {employee} AS e
|
||||||
|
LEFT JOIN {employee} AS sup ON sup.ID = e.SUPERIOR
|
||||||
|
WHERE e.ID IN ({marks})
|
||||||
|
""",
|
||||||
|
chunk,
|
||||||
|
)
|
||||||
|
for raw in cursor.fetchall():
|
||||||
|
oa_id = as_int(raw[0])
|
||||||
|
if oa_id is None:
|
||||||
|
continue
|
||||||
|
department = _clean(raw[4])
|
||||||
|
found[oa_id] = {
|
||||||
|
"oa_id": oa_id,
|
||||||
|
"name": _clean(raw[1]),
|
||||||
|
"job_num": _clean(raw[2]),
|
||||||
|
"superior_id": as_int(raw[3]),
|
||||||
|
"department_id": department,
|
||||||
|
"superior_name": _clean(raw[5]),
|
||||||
|
"superior_job_num": _clean(raw[6]),
|
||||||
|
}
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _load_deputies(cursor: Any, employee: str, department_ids: list[str]) -> dict[str, list[dict[str, Any]]]:
|
||||||
|
"""按部门 ID 字符串查出经副理。部门不在矩阵里时不产生人员。"""
|
||||||
|
found: dict[str, list[dict[str, Any]]] = {}
|
||||||
|
if not department_ids:
|
||||||
|
return found
|
||||||
|
matrix_condition = _qualified(_MATRIX_CATALOG, "hrm_matrix_condition_data")
|
||||||
|
matrix_value = _qualified(_MATRIX_CATALOG, "hrm_matrix_value_data")
|
||||||
|
for chunk in _chunks(department_ids):
|
||||||
|
marks = ",".join("?" for _ in chunk)
|
||||||
|
params: list[Any] = [_DEPUTY_CONFIG_ID, _MATRIX_TENANT, _MATRIX_ID, *_chunk_params(chunk)]
|
||||||
|
cursor.execute(
|
||||||
|
f"""
|
||||||
|
SELECT c.relate_id, v.relate_id, emp.USERNAME, emp.JOB_NUM
|
||||||
|
FROM {matrix_condition} AS c
|
||||||
|
INNER JOIN {matrix_value} AS v
|
||||||
|
ON v.matrix_data_id = c.matrix_data_id
|
||||||
|
AND v.tenant_key = c.tenant_key
|
||||||
|
AND v.matrix_id = c.matrix_id
|
||||||
|
AND v.delete_type = 0
|
||||||
|
AND v.matrix_value_config_id = ?
|
||||||
|
LEFT JOIN {employee} AS emp ON emp.ID = v.relate_id
|
||||||
|
WHERE c.tenant_key = ?
|
||||||
|
AND c.matrix_id = ?
|
||||||
|
AND c.delete_type = 0
|
||||||
|
AND c.relate_id IN ({marks})
|
||||||
|
""",
|
||||||
|
params,
|
||||||
|
)
|
||||||
|
for raw in cursor.fetchall():
|
||||||
|
department_id = _clean(raw[0])
|
||||||
|
person_id = as_int(raw[1])
|
||||||
|
if not department_id or person_id is None:
|
||||||
|
continue
|
||||||
|
found.setdefault(department_id, []).append({
|
||||||
|
"oa_id": person_id,
|
||||||
|
"name": _clean(raw[2]),
|
||||||
|
"job_num": _clean(raw[3]),
|
||||||
|
})
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _chunk_params(chunk: list[Any]) -> list[Any]:
|
||||||
|
"""部门 ID 按原字符串传给条件表。"""
|
||||||
|
return list(chunk)
|
||||||
|
|
||||||
|
|
||||||
|
def _chunks(values: list[Any], size: int = 400) -> list[list[Any]]:
|
||||||
|
"""把 IN 列表拆开,避免一条 SQL 的参数过多。"""
|
||||||
|
return [values[index:index + size] for index in range(0, len(values), size)]
|
||||||
|
|
||||||
|
|
||||||
|
def _clean(value: Any) -> str | None:
|
||||||
|
"""去掉空白。数字部门 ID 也收成字符串,供矩阵条件表比较。"""
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
text = str(value).strip()
|
||||||
|
return text or None
|
||||||
|
|
||||||
|
|
||||||
|
def _pick_driver(pyodbc: Any, configured: str) -> str:
|
||||||
|
"""选用已配置且本机存在的 ODBC 驱动,否则按 18、17、SQL Server 的顺序挑。"""
|
||||||
|
available = list(pyodbc.drivers())
|
||||||
|
if configured and configured in available:
|
||||||
|
return configured
|
||||||
|
for name in _PREFERRED_DRIVERS:
|
||||||
|
if name in available:
|
||||||
|
return name
|
||||||
|
if not available:
|
||||||
|
raise ServiceUnavailableError(
|
||||||
|
"未找到 SQL Server ODBC 驱动",
|
||||||
|
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
|
||||||
|
)
|
||||||
|
return available[-1]
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
"""
|
||||||
|
backend/app/services/equipment_acceptance/query_sql.py
|
||||||
|
|
||||||
|
用途:决定 E10 各表所在库,并组装只读联表 SQL。
|
||||||
|
依赖:无 Flask。库名只允许字母、数字和下划线。
|
||||||
|
逻辑:同步仓库调用。验收单用 FORM_DATA_ID 经 wfc_form_data 挂到流程实例。
|
||||||
|
不读流程编号、第二合同编号、验收日期、optgroupid、batch_number、operate_log_id、isremark。无法验收说明读取 ycsm。字典库看不到时,流程表回退到 ecology10。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
||||||
|
_FORM_CATALOG = "ecology10"
|
||||||
|
_EMPLOYEE_CATALOG = "eteams"
|
||||||
|
_REQUEST_CATALOG = "weaver_wfc"
|
||||||
|
_NODE_CATALOG = "weaver_wfp"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class AcceptanceCatalogs:
|
||||||
|
"""一次同步使用的四个库名。"""
|
||||||
|
|
||||||
|
form: str
|
||||||
|
employee: str
|
||||||
|
request: str
|
||||||
|
node: str
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_catalogs(
|
||||||
|
database_names: set[str],
|
||||||
|
*,
|
||||||
|
form: str | None = None,
|
||||||
|
employee: str | None = None,
|
||||||
|
request: str | None = None,
|
||||||
|
node: str | None = None,
|
||||||
|
) -> AcceptanceCatalogs:
|
||||||
|
"""
|
||||||
|
按数据字典和实例上实际存在的库选择库名。
|
||||||
|
|
||||||
|
核心逻辑:显式传入的库名优先。否则流程库优先 weaver_wfc、节点库优先 weaver_wfp,
|
||||||
|
实例里没有这两个库时用 ecology10。人员库只认 eteams,不猜测到别的库。
|
||||||
|
Args:
|
||||||
|
database_names: sys.databases 里的库名。
|
||||||
|
form: 验收单库覆盖值。
|
||||||
|
employee: 人员库覆盖值。
|
||||||
|
request: 流程库覆盖值。
|
||||||
|
node: 节点定义库覆盖值。
|
||||||
|
Returns:
|
||||||
|
AcceptanceCatalogs。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: 库名非法,或人员库、回退后的流程库仍然不存在。
|
||||||
|
"""
|
||||||
|
present = {name.lower(): name for name in database_names if name}
|
||||||
|
return AcceptanceCatalogs(
|
||||||
|
form=_pick(form, _FORM_CATALOG, present, allow_fallback=_FORM_CATALOG),
|
||||||
|
employee=_pick(employee, _EMPLOYEE_CATALOG, present, allow_fallback=None),
|
||||||
|
request=_pick(request, _REQUEST_CATALOG, present, allow_fallback=_FORM_CATALOG),
|
||||||
|
node=_pick(node, _NODE_CATALOG, present, allow_fallback=_FORM_CATALOG),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def build_acceptance_sql(catalogs: AcceptanceCatalogs) -> str:
|
||||||
|
"""
|
||||||
|
组装验收单、人员、流程实例、当前节点、节点定义、操作人的只读 SQL。
|
||||||
|
|
||||||
|
核心逻辑:用 FORM_DATA_ID 对齐 wfc_form_data.dataid,再按 requestid 挂到流程实例。
|
||||||
|
不查询流程编号、第二合同编号、验收日期和 isremark。当前节点和操作人按 requestid + nodeid 对齐,
|
||||||
|
delete_type 只取 0。当前处理人就是这些 userid。
|
||||||
|
Args:
|
||||||
|
catalogs: 已解析的库名。
|
||||||
|
Returns:
|
||||||
|
一条 SELECT。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: 库名不是合法标识符。
|
||||||
|
"""
|
||||||
|
form = _qualified(catalogs.form, "ft_gdzcysdv2")
|
||||||
|
employee = _qualified(catalogs.employee, "employee")
|
||||||
|
form_data = _qualified(catalogs.request, "wfc_form_data")
|
||||||
|
request = _qualified(catalogs.request, "wfc_requestbase")
|
||||||
|
current = _qualified(catalogs.request, "wfc_currentnode")
|
||||||
|
node = _qualified(catalogs.node, "wfp_node")
|
||||||
|
operate = _qualified(catalogs.request, "wfc_operate")
|
||||||
|
return f"""
|
||||||
|
SELECT
|
||||||
|
f.ysddh,
|
||||||
|
f.cgdh,
|
||||||
|
f.htbh,
|
||||||
|
f.sbsyrjssj,
|
||||||
|
f.sfzfth,
|
||||||
|
f.sfkyzcys,
|
||||||
|
f.ycsm,
|
||||||
|
f.sybmdd,
|
||||||
|
owner.USERNAME AS owner_name,
|
||||||
|
owner.JOB_NUM AS owner_job_num,
|
||||||
|
f.sbglry,
|
||||||
|
equip.USERNAME AS equip_name,
|
||||||
|
equip.JOB_NUM AS equip_job_num,
|
||||||
|
f.sqr,
|
||||||
|
applicant.USERNAME AS applicant_name,
|
||||||
|
applicant.JOB_NUM AS applicant_job_num,
|
||||||
|
r.requestid,
|
||||||
|
r.flowstatus,
|
||||||
|
r.finishdatetime,
|
||||||
|
c.nodeid,
|
||||||
|
n.nodename,
|
||||||
|
n.nodetype,
|
||||||
|
op.userid,
|
||||||
|
handler.USERNAME AS handler_name,
|
||||||
|
handler.JOB_NUM AS handler_job_num
|
||||||
|
FROM {form} AS f
|
||||||
|
LEFT JOIN {employee} AS owner ON owner.ID = f.sybmdd
|
||||||
|
LEFT JOIN {employee} AS equip ON equip.ID = f.sbglry
|
||||||
|
LEFT JOIN {employee} AS applicant ON applicant.ID = f.sqr
|
||||||
|
LEFT JOIN {form_data} AS d
|
||||||
|
ON d.dataid = f.FORM_DATA_ID
|
||||||
|
AND d.delete_type = 0
|
||||||
|
LEFT JOIN {request} AS r
|
||||||
|
ON r.requestid = d.requestid
|
||||||
|
AND r.delete_type = 0
|
||||||
|
LEFT JOIN {current} AS c
|
||||||
|
ON c.requestid = r.requestid
|
||||||
|
AND c.delete_type = 0
|
||||||
|
LEFT JOIN {node} AS n
|
||||||
|
ON n.id = c.nodeid
|
||||||
|
AND n.delete_type = 0
|
||||||
|
LEFT JOIN {operate} AS op
|
||||||
|
ON op.requestid = c.requestid
|
||||||
|
AND op.nodeid = c.nodeid
|
||||||
|
AND op.delete_type = 0
|
||||||
|
LEFT JOIN {employee} AS handler ON handler.ID = op.userid
|
||||||
|
WHERE ISNULL(f.delete_type, 0) = 0
|
||||||
|
AND r.requestid IS NOT NULL
|
||||||
|
""".strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _pick(
|
||||||
|
override: str | None,
|
||||||
|
preferred: str,
|
||||||
|
present: dict[str, str],
|
||||||
|
*,
|
||||||
|
allow_fallback: str | None,
|
||||||
|
) -> str:
|
||||||
|
"""选择一个实际可用的库名。覆盖值不要求已经出现在探测结果里。"""
|
||||||
|
if override and override.strip():
|
||||||
|
return _ident(override.strip())
|
||||||
|
if preferred.lower() in present:
|
||||||
|
return _ident(present[preferred.lower()])
|
||||||
|
if allow_fallback and allow_fallback.lower() in present:
|
||||||
|
return _ident(present[allow_fallback.lower()])
|
||||||
|
raise ValueError(f"缺少数据库 {preferred}")
|
||||||
|
|
||||||
|
|
||||||
|
def _qualified(catalog: str, table: str) -> str:
|
||||||
|
"""返回 [库].[dbo].[表]。"""
|
||||||
|
return f"[{_ident(catalog)}].[dbo].[{_ident(table)}]"
|
||||||
|
|
||||||
|
|
||||||
|
def _ident(name: str) -> str:
|
||||||
|
"""拒绝不是普通标识符的库名或表名。"""
|
||||||
|
if not _IDENT.match(name):
|
||||||
|
raise ValueError(f"非法 SQL 标识符: {name}")
|
||||||
|
return name
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
"""
|
||||||
|
backend/app/services/equipment_acceptance/schedule_seed.py
|
||||||
|
|
||||||
|
用途:设备验收预警的默认排程:每日扫描和周五 18:00 发送。
|
||||||
|
依赖:ScheduleTask、permission_roles.service.first_schedule_owner_user、timezone_util。
|
||||||
|
逻辑:应用启动时幂等创建。已有同编号或同任务键时不覆盖管理员改过的 Cron。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.models import ScheduleTask
|
||||||
|
from app.services.permission_roles.service import first_schedule_owner_user
|
||||||
|
from app.services.schedule.timezone_util import compute_next_run_at
|
||||||
|
|
||||||
|
|
||||||
|
_DEFAULTS = (
|
||||||
|
("SCH-EQUIPMENT-ACCEPTANCE-SCAN", "equipment-acceptance-alert-scan", "设备验收预警扫描(日批)", "0 6 * * *"),
|
||||||
|
("SCH-EQUIPMENT-ACCEPTANCE-WEEKLY", "equipment-acceptance-alert-weekly", "设备验收预警发送(周五 18:00)", "0 18 * * 5"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_default_equipment_acceptance_schedules(*, commit: bool = True):
|
||||||
|
"""
|
||||||
|
幂等创建设备验收每日扫描和周五发送两个排程。
|
||||||
|
|
||||||
|
核心逻辑:发送时刻不在预警配置表。默认与合同付款一样,周五 18:00,时区 Asia/Shanghai。
|
||||||
|
Args:
|
||||||
|
commit: 为 False 时只 flush,交给外层事务提交。
|
||||||
|
Returns:
|
||||||
|
新建的排程。没有可当负责人的用户时返回空列表。
|
||||||
|
"""
|
||||||
|
owner = first_schedule_owner_user()
|
||||||
|
if owner is None:
|
||||||
|
return []
|
||||||
|
created = []
|
||||||
|
for schedule_no, platform_path, name, cron in _DEFAULTS:
|
||||||
|
existing = (
|
||||||
|
db.session.query(ScheduleTask)
|
||||||
|
.filter((ScheduleTask.schedule_no == schedule_no) | (ScheduleTask.platform_api_path == platform_path))
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if existing:
|
||||||
|
continue
|
||||||
|
now = datetime.utcnow()
|
||||||
|
task = ScheduleTask(
|
||||||
|
schedule_no=schedule_no,
|
||||||
|
name=name,
|
||||||
|
schedule_type="platform_job",
|
||||||
|
owner_user_id=owner.id,
|
||||||
|
cron_expr=cron,
|
||||||
|
schedule_timezone="Asia/Shanghai",
|
||||||
|
wait_seconds=0,
|
||||||
|
platform_api_path=platform_path,
|
||||||
|
job_params={},
|
||||||
|
kb_sync_enabled=False,
|
||||||
|
notify_user_ids_json=[],
|
||||||
|
notify_enabled=False,
|
||||||
|
enabled=True,
|
||||||
|
next_run_at=compute_next_run_at(cron, timezone_name="Asia/Shanghai") or now,
|
||||||
|
created_by=owner.id,
|
||||||
|
updated_by=owner.id,
|
||||||
|
created_at=now,
|
||||||
|
updated_at=now,
|
||||||
|
)
|
||||||
|
db.session.add(task)
|
||||||
|
created.append(task)
|
||||||
|
if commit and created:
|
||||||
|
db.session.commit()
|
||||||
|
elif not commit:
|
||||||
|
db.session.flush()
|
||||||
|
return created
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
"""
|
||||||
|
backend/app/services/equipment_acceptance/send_record_service.py
|
||||||
|
|
||||||
|
用途:分页读取设备验收预警的发送记录。
|
||||||
|
依赖:extensions.db、EquipmentAcceptanceSendRecord、utc_iso。
|
||||||
|
逻辑:由 GET /api/equipment-acceptance/sends 调用。待发送由扫描写入,本模块只读取。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.core.response import utc_iso
|
||||||
|
from app.extensions import db
|
||||||
|
from app.models.equipment_acceptance import EquipmentAcceptanceSendRecord
|
||||||
|
|
||||||
|
|
||||||
|
def list_send_records(*, page: int, page_size: int) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
按创建时间倒序分页列出发送记录。
|
||||||
|
|
||||||
|
核心逻辑:只读已落库的记录。扫描还没跑过时列表为空。
|
||||||
|
Args:
|
||||||
|
page: 从 1 开始。
|
||||||
|
page_size: 每页条数,上限 100。
|
||||||
|
Returns:
|
||||||
|
items、total、page、page_size。
|
||||||
|
"""
|
||||||
|
page = max(1, page)
|
||||||
|
page_size = min(100, max(1, page_size))
|
||||||
|
query = db.session.query(EquipmentAcceptanceSendRecord)
|
||||||
|
total = query.count()
|
||||||
|
rows = (
|
||||||
|
query.order_by(EquipmentAcceptanceSendRecord.created_at.desc(), EquipmentAcceptanceSendRecord.id.desc())
|
||||||
|
.offset((page - 1) * page_size)
|
||||||
|
.limit(page_size)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"items": [send_record_payload(row) for row in rows],
|
||||||
|
"total": total,
|
||||||
|
"page": page,
|
||||||
|
"page_size": page_size,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def send_record_payload(row: EquipmentAcceptanceSendRecord) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
把一条发送记录收成接口数据。
|
||||||
|
|
||||||
|
核心逻辑:单号和主送、抄送用写入时的快照,不回读当前岗位。
|
||||||
|
Args:
|
||||||
|
row: 本地发送记录。
|
||||||
|
Returns:
|
||||||
|
页签表格用的字段。
|
||||||
|
"""
|
||||||
|
return {
|
||||||
|
"id": row.id,
|
||||||
|
"order_id": row.order_id,
|
||||||
|
"acceptance_no": row.acceptance_no,
|
||||||
|
"purchase_order_no": row.purchase_order_no,
|
||||||
|
"tier": row.tier,
|
||||||
|
"threshold_days": row.threshold_days,
|
||||||
|
"to_text": row.to_text,
|
||||||
|
"cc_text": row.cc_text,
|
||||||
|
"recipients": list(row.recipients_json or []),
|
||||||
|
"status": row.status,
|
||||||
|
"sent_at": utc_iso(row.sent_at),
|
||||||
|
"error_message": row.error_message,
|
||||||
|
"created_at": utc_iso(row.created_at),
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
"""
|
||||||
|
backend/app/services/equipment_acceptance/settings.py
|
||||||
|
|
||||||
|
用途:读取设备验收同步要用的 E10 SQL Server 连接。
|
||||||
|
依赖:Flask current_app、环境变量 OA_E10_SQLSERVER_HOST / USERNAME / PASSWORD。
|
||||||
|
逻辑:主机、账号、密码不回退到 E8 的 OA_SQLSERVER_*。库名由查询时再探测。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from flask import current_app, has_app_context
|
||||||
|
|
||||||
|
from app.core.errors import ValidationError
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class EquipmentAcceptanceSqlSettings:
|
||||||
|
"""E10 只读连接。repr 不包含密码。"""
|
||||||
|
|
||||||
|
host: str
|
||||||
|
port: str
|
||||||
|
username: str
|
||||||
|
password: str
|
||||||
|
driver: str
|
||||||
|
encrypt: str
|
||||||
|
trust_cert: str
|
||||||
|
timeout: int
|
||||||
|
form_catalog: str
|
||||||
|
employee_catalog: str
|
||||||
|
request_catalog: str
|
||||||
|
node_catalog: str
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
return (
|
||||||
|
"EquipmentAcceptanceSqlSettings("
|
||||||
|
f"host={self.host!r}, port={self.port!r}, username={self.username!r}, "
|
||||||
|
f"form_catalog={self.form_catalog!r}, employee_catalog={self.employee_catalog!r}, "
|
||||||
|
f"request_catalog={self.request_catalog!r}, node_catalog={self.node_catalog!r})"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def load_equipment_acceptance_sql_settings() -> EquipmentAcceptanceSqlSettings:
|
||||||
|
"""
|
||||||
|
读取同步连接配置。
|
||||||
|
|
||||||
|
核心逻辑:三个必填变量只认 OA_E10_SQLSERVER_*。库名覆盖可空,空则交给实例探测。
|
||||||
|
Returns:
|
||||||
|
EquipmentAcceptanceSqlSettings。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValidationError: 主机、账号或密码缺失。
|
||||||
|
"""
|
||||||
|
host = _cfg("OA_E10_SQLSERVER_HOST")
|
||||||
|
username = _cfg("OA_E10_SQLSERVER_USERNAME")
|
||||||
|
password = _cfg_raw("OA_E10_SQLSERVER_PASSWORD")
|
||||||
|
missing = [
|
||||||
|
key
|
||||||
|
for key, value in (
|
||||||
|
("OA_E10_SQLSERVER_HOST", host),
|
||||||
|
("OA_E10_SQLSERVER_USERNAME", username),
|
||||||
|
("OA_E10_SQLSERVER_PASSWORD", password),
|
||||||
|
)
|
||||||
|
if not str(value or "").strip()
|
||||||
|
]
|
||||||
|
if missing:
|
||||||
|
raise ValidationError(
|
||||||
|
"设备验收同步的 E10 数据库配置不完整",
|
||||||
|
code="EQUIPMENT_ACCEPTANCE.CONFIG_INVALID",
|
||||||
|
details={"missing": missing},
|
||||||
|
)
|
||||||
|
return EquipmentAcceptanceSqlSettings(
|
||||||
|
host=host,
|
||||||
|
port=_cfg("OA_E10_SQLSERVER_PORT") or "1433",
|
||||||
|
username=username,
|
||||||
|
password=password,
|
||||||
|
driver=_cfg("OA_E10_SQLSERVER_DRIVER"),
|
||||||
|
encrypt=(_cfg("OA_E10_SQLSERVER_ENCRYPT") or "no").lower(),
|
||||||
|
trust_cert=(_cfg("OA_E10_SQLSERVER_TRUST_CERT") or "yes").lower(),
|
||||||
|
timeout=_as_int(_cfg("OA_E10_SQLSERVER_TIMEOUT") or "60", 60),
|
||||||
|
form_catalog=_cfg("EQUIPMENT_ACCEPTANCE_FORM_CATALOG"),
|
||||||
|
employee_catalog=_cfg("EQUIPMENT_ACCEPTANCE_EMPLOYEE_CATALOG"),
|
||||||
|
request_catalog=_cfg("EQUIPMENT_ACCEPTANCE_REQUEST_CATALOG"),
|
||||||
|
node_catalog=_cfg("EQUIPMENT_ACCEPTANCE_NODE_CATALOG"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _cfg(key: str) -> str:
|
||||||
|
"""优先 Flask config,再读环境变量,并去掉首尾空白。"""
|
||||||
|
if has_app_context():
|
||||||
|
value = current_app.config.get(key)
|
||||||
|
if value is not None and str(value).strip():
|
||||||
|
return str(value).strip()
|
||||||
|
return str(os.getenv(key) or "").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _cfg_raw(key: str) -> str:
|
||||||
|
"""读取密码,保留中间空格。"""
|
||||||
|
if has_app_context():
|
||||||
|
value = current_app.config.get(key)
|
||||||
|
if value is not None and str(value) != "":
|
||||||
|
return str(value)
|
||||||
|
env = os.getenv(key)
|
||||||
|
if env is not None and env != "":
|
||||||
|
return env
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _as_int(raw: str, default: int) -> int:
|
||||||
|
"""超时秒数,非法时用默认值。"""
|
||||||
|
try:
|
||||||
|
return max(1, int(str(raw).strip() or default))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return default
|
||||||
@@ -0,0 +1,243 @@
|
|||||||
|
"""
|
||||||
|
backend/app/services/equipment_acceptance/snapshot_rules.py
|
||||||
|
|
||||||
|
用途:把 OA 原值收成同步快照上的监控状态和签核天数。
|
||||||
|
依赖:无。不读数据库,也不使用 isremark。
|
||||||
|
逻辑:同步服务对每一张验收单调用本模块。OA 的 0=是、1=否先翻成标准 0=否、1=是。
|
||||||
|
flowstatus 为 7、8、99、-99 时记为已撤销,不再提醒。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import date, datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
NOT_STARTED = "not_started"
|
||||||
|
WATCHING = "watching"
|
||||||
|
STOPPED_CANNOT_ACCEPT = "stopped_cannot_accept"
|
||||||
|
STOPPED_RETURNED = "stopped_returned"
|
||||||
|
STOPPED_ARCHIVED = "stopped_archived"
|
||||||
|
STOPPED_FORCE_FINISHED = "stopped_force_finished"
|
||||||
|
STOPPED_VOIDED = "stopped_voided"
|
||||||
|
STOPPED_REVOKED = "stopped_revoked"
|
||||||
|
EXCLUDED = "excluded"
|
||||||
|
|
||||||
|
MONITOR_STATUSES = (
|
||||||
|
NOT_STARTED,
|
||||||
|
WATCHING,
|
||||||
|
STOPPED_CANNOT_ACCEPT,
|
||||||
|
STOPPED_RETURNED,
|
||||||
|
STOPPED_ARCHIVED,
|
||||||
|
STOPPED_FORCE_FINISHED,
|
||||||
|
STOPPED_VOIDED,
|
||||||
|
STOPPED_REVOKED,
|
||||||
|
EXCLUDED,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 需求冻结的第 1 档是超过 30 天。列表上的「已逾期」按这一档判断,还没有发送记录。
|
||||||
|
FIRST_REMINDER_DAY = 30
|
||||||
|
_FLOW_APPROVING = 1
|
||||||
|
_FLOW_ARCHIVED = 3
|
||||||
|
_FLOW_FORCE_FINISHED = 4
|
||||||
|
_FLOW_VOIDED = 5
|
||||||
|
# 7、8、99 已确认按撤销停表。字典截断值是 -99,一并按撤销处理。
|
||||||
|
_REVOKED_FLOW = {7, 8, 99, -99}
|
||||||
|
_TERMINAL_FLOW = {_FLOW_ARCHIVED, _FLOW_FORCE_FINISHED, _FLOW_VOIDED, *_REVOKED_FLOW}
|
||||||
|
|
||||||
|
|
||||||
|
def as_int(value: Any) -> int | None:
|
||||||
|
"""
|
||||||
|
把 OA 数字收成 int。空值保持空。
|
||||||
|
|
||||||
|
核心逻辑:布尔值不是业务枚举;0 是有效取值,不能当成空。
|
||||||
|
Args:
|
||||||
|
value: 查询结果里的数字、数字字符串或空。
|
||||||
|
Returns:
|
||||||
|
整数或 None。
|
||||||
|
"""
|
||||||
|
if value is None or isinstance(value, bool):
|
||||||
|
return None
|
||||||
|
if isinstance(value, int):
|
||||||
|
return value
|
||||||
|
if isinstance(value, float):
|
||||||
|
if value != value:
|
||||||
|
return None
|
||||||
|
return int(value)
|
||||||
|
text = str(value).strip()
|
||||||
|
if not text:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return int(text)
|
||||||
|
except ValueError:
|
||||||
|
try:
|
||||||
|
number = float(text)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
return int(number)
|
||||||
|
|
||||||
|
|
||||||
|
def as_date(value: Any) -> date | None:
|
||||||
|
"""
|
||||||
|
把 OA 日期收成 date。
|
||||||
|
|
||||||
|
核心逻辑:datetime 取日期部分;常见字符串只认日期前 10 位。
|
||||||
|
Args:
|
||||||
|
value: datetime、date 或字符串。
|
||||||
|
Returns:
|
||||||
|
date 或 None。
|
||||||
|
"""
|
||||||
|
if value is None or isinstance(value, bool):
|
||||||
|
return None
|
||||||
|
if isinstance(value, datetime):
|
||||||
|
return value.date()
|
||||||
|
if isinstance(value, date):
|
||||||
|
return value
|
||||||
|
text = str(value).strip()
|
||||||
|
if len(text) < 10:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return date.fromisoformat(text[:10])
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def as_datetime(value: Any) -> datetime | None:
|
||||||
|
"""
|
||||||
|
把 OA 时间收成去掉时区的 datetime,供本地快照保存。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
value: datetime 或可解析字符串。
|
||||||
|
Returns:
|
||||||
|
naive datetime 或 None。
|
||||||
|
"""
|
||||||
|
if value is None or isinstance(value, bool):
|
||||||
|
return None
|
||||||
|
if isinstance(value, datetime):
|
||||||
|
return value.replace(tzinfo=None)
|
||||||
|
if isinstance(value, date):
|
||||||
|
return datetime(value.year, value.month, value.day)
|
||||||
|
text = str(value).strip().replace("T", " ")
|
||||||
|
if not text:
|
||||||
|
return None
|
||||||
|
for fmt in ("%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d"):
|
||||||
|
try:
|
||||||
|
return datetime.strptime(text[:26], fmt)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
parsed = as_date(text)
|
||||||
|
if parsed is None:
|
||||||
|
return None
|
||||||
|
return datetime(parsed.year, parsed.month, parsed.day)
|
||||||
|
|
||||||
|
|
||||||
|
def can_accept_from_oa(value: int | None) -> int | None:
|
||||||
|
"""
|
||||||
|
把 OA「是否可以正常验收」翻成标准布尔。
|
||||||
|
|
||||||
|
核心逻辑:OA sfkyzcys 是 0=是、1=否。本地 can_accept 用 0=否、1=是。
|
||||||
|
空值表示未标明,保持空,不收成否。0、1 以外的值原样留下,交给状态判断排除。
|
||||||
|
Args:
|
||||||
|
value: sfkyzcys 的整数。0 可以,1 不可以。
|
||||||
|
Returns:
|
||||||
|
1 表示可以验收,0 表示不可以,空保持空。
|
||||||
|
"""
|
||||||
|
# [STEP] OA 0=是、1=否,与本地 0=否、1=是对调。空不是「否」。
|
||||||
|
if value == 0:
|
||||||
|
return 1
|
||||||
|
if value == 1:
|
||||||
|
return 0
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def is_returned_from_oa(value: int | None) -> int | None:
|
||||||
|
"""
|
||||||
|
把 OA「是否退回」翻成标准布尔。
|
||||||
|
|
||||||
|
核心逻辑:OA sfzfth 是 0=是(退回),1=否(正常)。本地 is_returned 用 0=否、1=是。
|
||||||
|
空和 1 都已确认是未退回,所以空收成 0。0、1、空以外的值原样留下。
|
||||||
|
Args:
|
||||||
|
value: sfzfth 的整数。0 退回,1 和空为正常。
|
||||||
|
Returns:
|
||||||
|
1 表示已退回,0 表示未退回。
|
||||||
|
"""
|
||||||
|
# [STEP] OA 0=是、1=否,翻成 0=否、1=是。空按已确认口径当作未退回。
|
||||||
|
if value == 0:
|
||||||
|
return 1
|
||||||
|
if value in (1, None):
|
||||||
|
return 0
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def classify_monitor_status(
|
||||||
|
*,
|
||||||
|
can_accept: int | None,
|
||||||
|
is_returned: int | None,
|
||||||
|
flow_status: int | None,
|
||||||
|
timer_started: bool,
|
||||||
|
) -> str:
|
||||||
|
"""
|
||||||
|
按已确认规则给出监控状态。入参已是标准 0=否、1=是。
|
||||||
|
|
||||||
|
核心逻辑:退回、无法验收、作废、归档、强制结束、撤销优先于未开始。
|
||||||
|
审批中、可以验收、未退回、已有计时起点才是计时中。
|
||||||
|
flowstatus 为 7、8、99、-99 时记为已撤销,有没有计时起点都不再提醒。
|
||||||
|
Args:
|
||||||
|
can_accept: 本地是否可以正常验收。0 否,1 是,空为未标明。
|
||||||
|
is_returned: 本地是否退回。0 否,1 是。
|
||||||
|
flow_status: wfc_requestbase.flowstatus。
|
||||||
|
timer_started: sbsyrjssj 是否有值。
|
||||||
|
Returns:
|
||||||
|
MONITOR_STATUSES 中的一个代码。
|
||||||
|
"""
|
||||||
|
# [STEP 1] 表单上的停表原因优先于流程是否已经结束
|
||||||
|
if is_returned == 1:
|
||||||
|
return STOPPED_RETURNED
|
||||||
|
if can_accept == 0:
|
||||||
|
return STOPPED_CANNOT_ACCEPT
|
||||||
|
if flow_status == _FLOW_VOIDED:
|
||||||
|
return STOPPED_VOIDED
|
||||||
|
if flow_status == _FLOW_ARCHIVED:
|
||||||
|
return STOPPED_ARCHIVED
|
||||||
|
if flow_status == _FLOW_FORCE_FINISHED:
|
||||||
|
return STOPPED_FORCE_FINISHED
|
||||||
|
if flow_status in _REVOKED_FLOW:
|
||||||
|
return STOPPED_REVOKED
|
||||||
|
if not timer_started:
|
||||||
|
return NOT_STARTED
|
||||||
|
# [STEP 2] 只有审批中、可以验收、未退回时继续计时
|
||||||
|
if can_accept == 1 and flow_status == _FLOW_APPROVING and is_returned == 0:
|
||||||
|
return WATCHING
|
||||||
|
return EXCLUDED
|
||||||
|
|
||||||
|
|
||||||
|
def dwell_days(
|
||||||
|
*,
|
||||||
|
timer_started_at: datetime | date | None,
|
||||||
|
flow_status: int | None,
|
||||||
|
finished_at: datetime | date | None,
|
||||||
|
as_of: date,
|
||||||
|
) -> int | None:
|
||||||
|
"""
|
||||||
|
计算同步日看到的签核自然日。
|
||||||
|
|
||||||
|
核心逻辑:起点为空则没有天数。归档、强制结束、作废、撤销且有结束时间时,
|
||||||
|
截止到结束日,避免停表后每次同步继续加天。退回和无法验收没有结束时间,截止到同步日。
|
||||||
|
Args:
|
||||||
|
timer_started_at: sbsyrjssj。
|
||||||
|
flow_status: 流程状态原值。
|
||||||
|
finished_at: finishdatetime。
|
||||||
|
as_of: 同步当日,使用 Asia/Shanghai 的日期。
|
||||||
|
Returns:
|
||||||
|
非负天数;没有起点时为 None。
|
||||||
|
"""
|
||||||
|
start = as_date(timer_started_at)
|
||||||
|
if start is None:
|
||||||
|
return None
|
||||||
|
end = as_of
|
||||||
|
if flow_status in _TERMINAL_FLOW:
|
||||||
|
finished = as_date(finished_at)
|
||||||
|
if finished is not None:
|
||||||
|
end = finished if finished < as_of else as_of
|
||||||
|
if end < start:
|
||||||
|
return 0
|
||||||
|
return (end - start).days
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
"""
|
||||||
|
backend/app/services/equipment_acceptance/source_group.py
|
||||||
|
|
||||||
|
用途:把验收单联表的扁平行收成一张单一条草稿。
|
||||||
|
依赖:snapshot_rules。
|
||||||
|
逻辑:同步服务先分组再落库。是否可以验收、是否退回在这里从 OA 的 0=是、1=否
|
||||||
|
翻成标准 0=否、1=是。无法验收说明取 ycsm,不参与停表。操作人按节点和人员去重,不读 isremark。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.services.equipment_acceptance.snapshot_rules import (
|
||||||
|
as_datetime,
|
||||||
|
as_int,
|
||||||
|
can_accept_from_oa,
|
||||||
|
is_returned_from_oa,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class OperatorDraft:
|
||||||
|
"""当前节点上的一名操作人。不带操作状态。"""
|
||||||
|
|
||||||
|
node_id: int
|
||||||
|
user_id: int
|
||||||
|
handler_name: str | None
|
||||||
|
handler_job_num: str | None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class NodeDraft:
|
||||||
|
"""一条当前节点。"""
|
||||||
|
|
||||||
|
node_id: int
|
||||||
|
node_name: str | None
|
||||||
|
node_type: int | None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class AcceptanceDraft:
|
||||||
|
"""一张验收单在一次同步中的快照草稿。不包含流程编号、第二合同编号和验收日期。"""
|
||||||
|
|
||||||
|
request_id: int
|
||||||
|
acceptance_no: str | None
|
||||||
|
purchase_order_no: str | None
|
||||||
|
contract_no: str | None
|
||||||
|
timer_started_at: datetime | None
|
||||||
|
can_accept: int | None
|
||||||
|
cannot_accept_note: str | None
|
||||||
|
is_returned: int | None
|
||||||
|
flow_status_raw: int | None
|
||||||
|
finished_at: datetime | None
|
||||||
|
request_match_count: int
|
||||||
|
owner_oa_id: int | None
|
||||||
|
owner_name: str | None
|
||||||
|
owner_job_num: str | None
|
||||||
|
equip_oa_id: int | None
|
||||||
|
equip_name: str | None
|
||||||
|
equip_job_num: str | None
|
||||||
|
applicant_oa_id: int | None
|
||||||
|
applicant_name: str | None
|
||||||
|
applicant_job_num: str | None
|
||||||
|
nodes: list[NodeDraft] = field(default_factory=list)
|
||||||
|
operators: list[OperatorDraft] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
def group_acceptance_rows(rows: list[dict[str, Any]]) -> tuple[list[AcceptanceDraft], int]:
|
||||||
|
"""
|
||||||
|
按流程实例 requestid 合并联表结果。
|
||||||
|
|
||||||
|
核心逻辑:没有 requestid 的行跳过。同一请求上的节点和操作人收成一张单。
|
||||||
|
不读取流程编号、第二合同编号和验收日期。
|
||||||
|
Args:
|
||||||
|
rows: 查询别名组成的字典行。
|
||||||
|
Returns:
|
||||||
|
(草稿列表, 因缺少 requestid 而跳过的行数)。
|
||||||
|
"""
|
||||||
|
skipped = 0
|
||||||
|
buckets: dict[int, list[dict[str, Any]]] = {}
|
||||||
|
for row in rows:
|
||||||
|
request_id = as_int(row.get("requestid"))
|
||||||
|
if request_id is None:
|
||||||
|
skipped += 1
|
||||||
|
continue
|
||||||
|
buckets.setdefault(request_id, []).append(row)
|
||||||
|
return [_draft_from_rows(request_id, items) for request_id, items in buckets.items()], skipped
|
||||||
|
|
||||||
|
|
||||||
|
def _draft_from_rows(request_id: int, items: list[dict[str, Any]]) -> AcceptanceDraft:
|
||||||
|
"""同一流程实例的多行收成一条草稿。"""
|
||||||
|
header = items[0]
|
||||||
|
return AcceptanceDraft(
|
||||||
|
request_id=request_id,
|
||||||
|
acceptance_no=_text(header.get("ysddh")),
|
||||||
|
purchase_order_no=_text(header.get("cgdh")),
|
||||||
|
contract_no=_text(header.get("htbh")),
|
||||||
|
timer_started_at=as_datetime(header.get("sbsyrjssj")),
|
||||||
|
can_accept=can_accept_from_oa(as_int(header.get("sfkyzcys"))),
|
||||||
|
cannot_accept_note=_text(header.get("ycsm")),
|
||||||
|
is_returned=is_returned_from_oa(as_int(header.get("sfzfth"))),
|
||||||
|
flow_status_raw=as_int(header.get("flowstatus")),
|
||||||
|
finished_at=as_datetime(header.get("finishdatetime")),
|
||||||
|
request_match_count=1,
|
||||||
|
nodes=_nodes(items),
|
||||||
|
operators=_operators(items),
|
||||||
|
owner_oa_id=as_int(header.get("sybmdd")),
|
||||||
|
owner_name=_text(header.get("owner_name")),
|
||||||
|
owner_job_num=_text(header.get("owner_job_num")),
|
||||||
|
equip_oa_id=as_int(header.get("sbglry")),
|
||||||
|
equip_name=_text(header.get("equip_name")),
|
||||||
|
equip_job_num=_text(header.get("equip_job_num")),
|
||||||
|
applicant_oa_id=as_int(header.get("sqr")),
|
||||||
|
applicant_name=_text(header.get("applicant_name")),
|
||||||
|
applicant_job_num=_text(header.get("applicant_job_num")),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _nodes(rows: list[dict[str, Any]]) -> list[NodeDraft]:
|
||||||
|
"""按节点 ID 去重,保留节点名称。"""
|
||||||
|
found: dict[int, NodeDraft] = {}
|
||||||
|
for row in rows:
|
||||||
|
node_id = as_int(row.get("nodeid"))
|
||||||
|
if node_id is None or node_id in found:
|
||||||
|
continue
|
||||||
|
found[node_id] = NodeDraft(
|
||||||
|
node_id=node_id,
|
||||||
|
node_name=_text(row.get("nodename")),
|
||||||
|
node_type=as_int(row.get("nodetype")),
|
||||||
|
)
|
||||||
|
return list(found.values())
|
||||||
|
|
||||||
|
|
||||||
|
def _operators(rows: list[dict[str, Any]]) -> list[OperatorDraft]:
|
||||||
|
"""按节点和人员去重。不读 isremark,同一人只留一行。"""
|
||||||
|
found: dict[tuple[int, int], OperatorDraft] = {}
|
||||||
|
for row in rows:
|
||||||
|
node_id = as_int(row.get("nodeid"))
|
||||||
|
user_id = as_int(row.get("userid"))
|
||||||
|
if node_id is None or user_id is None:
|
||||||
|
continue
|
||||||
|
key = (node_id, user_id)
|
||||||
|
if key in found:
|
||||||
|
continue
|
||||||
|
found[key] = OperatorDraft(
|
||||||
|
node_id=node_id,
|
||||||
|
user_id=user_id,
|
||||||
|
handler_name=_text(row.get("handler_name")),
|
||||||
|
handler_job_num=_text(row.get("handler_job_num")),
|
||||||
|
)
|
||||||
|
return list(found.values())
|
||||||
|
|
||||||
|
|
||||||
|
def _text(value: Any) -> str | None:
|
||||||
|
"""去空白;空串视为没有值。"""
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
text = str(value).strip()
|
||||||
|
return text or None
|
||||||
@@ -0,0 +1,412 @@
|
|||||||
|
"""
|
||||||
|
backend/app/services/equipment_acceptance/sync_service.py
|
||||||
|
|
||||||
|
用途:把 E10 验收单快照写入本地表,并提供管理员查询。
|
||||||
|
依赖:extensions.db、equipment_acceptance 模型、snapshot_rules、source_group、oa_repository。
|
||||||
|
逻辑:手动同步 upsert 主表并替换子表。列表按原型分组过滤,并附带全部单据的汇总。
|
||||||
|
停表时取消该单未发送的预警。操作人不保存 isremark。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections import Counter
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from app.core.errors import NotFoundError, ValidationError
|
||||||
|
from app.core.response import utc_iso
|
||||||
|
from app.extensions import db
|
||||||
|
from app.models.equipment_acceptance import (
|
||||||
|
EquipmentAcceptanceNode,
|
||||||
|
EquipmentAcceptanceOperator,
|
||||||
|
EquipmentAcceptanceOrder,
|
||||||
|
)
|
||||||
|
from app.services.equipment_acceptance.config_service import first_reminder_day
|
||||||
|
from app.services.equipment_acceptance.snapshot_rules import (
|
||||||
|
MONITOR_STATUSES,
|
||||||
|
classify_monitor_status,
|
||||||
|
dwell_days,
|
||||||
|
)
|
||||||
|
from app.services.equipment_acceptance.source_group import AcceptanceDraft, group_acceptance_rows
|
||||||
|
|
||||||
|
_SHANGHAI = ZoneInfo("Asia/Shanghai")
|
||||||
|
_LEDGER_FOCUSES = ("watching", "overdue", "stopped", "not_started")
|
||||||
|
_STOPPED_STATUSES = (
|
||||||
|
"stopped_returned",
|
||||||
|
"stopped_cannot_accept",
|
||||||
|
"stopped_archived",
|
||||||
|
"stopped_force_finished",
|
||||||
|
"stopped_voided",
|
||||||
|
"stopped_revoked",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def sync_acceptance_snapshots(rows: list[dict[str, Any]] | None = None) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
同步验收单快照。
|
||||||
|
|
||||||
|
核心逻辑:未传入行时自己读 E10。按流程实例 request_id 更新主表,子表整批替换。
|
||||||
|
本次查询里消失的单据保留上次内容,只把 present_in_source 标成否。
|
||||||
|
Args:
|
||||||
|
rows: 测试或调用方已经取好的联表行。None 时访问 E10。
|
||||||
|
Returns:
|
||||||
|
本次写入条数、跳过条数、停表取消的未发送条数,以及各监控状态计数。
|
||||||
|
"""
|
||||||
|
if rows is None:
|
||||||
|
from app.services.equipment_acceptance.oa_repository import fetch_acceptance_rows
|
||||||
|
|
||||||
|
rows = fetch_acceptance_rows()
|
||||||
|
drafts, skipped = group_acceptance_rows(rows)
|
||||||
|
as_of = datetime.now(_SHANGHAI).date()
|
||||||
|
counts: Counter[str] = Counter()
|
||||||
|
request_ids: list[int] = []
|
||||||
|
cancelled = 0
|
||||||
|
for draft in drafts:
|
||||||
|
order, cancelled_now = _upsert_order(draft, as_of=as_of)
|
||||||
|
request_ids.append(order.request_id)
|
||||||
|
counts[order.monitor_status] += 1
|
||||||
|
cancelled += cancelled_now
|
||||||
|
absent = _mark_absent(request_ids)
|
||||||
|
db.session.commit()
|
||||||
|
return {
|
||||||
|
"upserted": len(drafts),
|
||||||
|
"skipped_without_request_id": skipped,
|
||||||
|
"absent": absent,
|
||||||
|
"cancelled": cancelled,
|
||||||
|
"by_status": dict(counts),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def list_acceptance_orders(
|
||||||
|
*,
|
||||||
|
monitor_status: str | None,
|
||||||
|
focus: str | None,
|
||||||
|
page: int,
|
||||||
|
page_size: int,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
分页列出本地快照。
|
||||||
|
|
||||||
|
核心逻辑:focus 按原型的全部、进行中、已逾期、不再提醒、未开始过滤。
|
||||||
|
已逾期是计时中且签核天数超过第 1 档。汇总数字始终看全部单据。
|
||||||
|
Args:
|
||||||
|
monitor_status: 可选的单个监控状态代码。与 focus 同时传时以 focus 为准。
|
||||||
|
focus: watching、overdue、stopped、not_started 或空。
|
||||||
|
page: 从 1 开始。
|
||||||
|
page_size: 每页条数,上限 100。
|
||||||
|
Returns:
|
||||||
|
items、total、page、page_size、summary。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValidationError: focus 或监控状态不是已定义值。
|
||||||
|
"""
|
||||||
|
status = _clean_status(monitor_status)
|
||||||
|
ledger_focus = _clean_focus(focus)
|
||||||
|
reminder_day = first_reminder_day()
|
||||||
|
page = max(1, page)
|
||||||
|
page_size = min(100, max(1, page_size))
|
||||||
|
query = db.session.query(EquipmentAcceptanceOrder)
|
||||||
|
if ledger_focus:
|
||||||
|
query = _apply_focus(query, ledger_focus, reminder_day)
|
||||||
|
elif status:
|
||||||
|
query = query.filter(EquipmentAcceptanceOrder.monitor_status == status)
|
||||||
|
total = query.count()
|
||||||
|
orders = (
|
||||||
|
query.order_by(EquipmentAcceptanceOrder.synced_at.desc(), EquipmentAcceptanceOrder.id.desc())
|
||||||
|
.offset((page - 1) * page_size)
|
||||||
|
.limit(page_size)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
order_ids = [order.id for order in orders]
|
||||||
|
nodes = _nodes_by_order(order_ids)
|
||||||
|
operators = _operators_by_order(order_ids)
|
||||||
|
pages = (total + page_size - 1) // page_size if total else 1
|
||||||
|
return {
|
||||||
|
"items": [
|
||||||
|
_order_payload(order, nodes.get(order.id, []), operators.get(order.id, []), reminder_day)
|
||||||
|
for order in orders
|
||||||
|
],
|
||||||
|
"total": total,
|
||||||
|
"page": page,
|
||||||
|
"page_size": page_size,
|
||||||
|
"pages": pages,
|
||||||
|
"summary": _ledger_summary(reminder_day),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def get_acceptance_order(order_id: int) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
读取一张验收单快照,含当前节点和操作人原值。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
order_id: 本地主键。
|
||||||
|
Returns:
|
||||||
|
快照详情。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
NotFoundError: 记录不存在。
|
||||||
|
"""
|
||||||
|
order = db.session.get(EquipmentAcceptanceOrder, order_id)
|
||||||
|
if order is None:
|
||||||
|
raise NotFoundError("设备验收同步记录不存在", code="EQUIPMENT_ACCEPTANCE.NOT_FOUND")
|
||||||
|
return _order_payload(
|
||||||
|
order,
|
||||||
|
_nodes_by_order([order.id]).get(order.id, []),
|
||||||
|
_operators_by_order([order.id]).get(order.id, []),
|
||||||
|
first_reminder_day(),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _upsert_order(draft: AcceptanceDraft, *, as_of) -> tuple[EquipmentAcceptanceOrder, int]:
|
||||||
|
"""
|
||||||
|
按流程实例 request_id 更新主表,并替换该单的节点和操作人。
|
||||||
|
|
||||||
|
核心逻辑:不再计时的单据顺手取消未发送预警。已发送的记录不动。
|
||||||
|
Returns:
|
||||||
|
更新后的验收单,以及本次改成已取消的发送记录条数。
|
||||||
|
"""
|
||||||
|
order = (
|
||||||
|
db.session.query(EquipmentAcceptanceOrder)
|
||||||
|
.filter(EquipmentAcceptanceOrder.request_id == draft.request_id)
|
||||||
|
.one_or_none()
|
||||||
|
)
|
||||||
|
now = datetime.utcnow()
|
||||||
|
if order is None:
|
||||||
|
order = EquipmentAcceptanceOrder(
|
||||||
|
request_id=draft.request_id,
|
||||||
|
monitor_status="excluded",
|
||||||
|
synced_at=now,
|
||||||
|
created_at=now,
|
||||||
|
updated_at=now,
|
||||||
|
)
|
||||||
|
db.session.add(order)
|
||||||
|
db.session.flush()
|
||||||
|
order.acceptance_no = draft.acceptance_no
|
||||||
|
order.purchase_order_no = draft.purchase_order_no
|
||||||
|
order.contract_no = draft.contract_no
|
||||||
|
order.timer_started_at = draft.timer_started_at
|
||||||
|
order.can_accept = draft.can_accept
|
||||||
|
order.cannot_accept_note = draft.cannot_accept_note
|
||||||
|
order.is_returned = draft.is_returned
|
||||||
|
order.flow_status_raw = draft.flow_status_raw
|
||||||
|
order.finished_at = draft.finished_at
|
||||||
|
order.request_id = draft.request_id
|
||||||
|
order.request_match_count = draft.request_match_count
|
||||||
|
order.owner_oa_id = draft.owner_oa_id
|
||||||
|
order.owner_name = draft.owner_name
|
||||||
|
order.owner_job_num = draft.owner_job_num
|
||||||
|
order.equip_oa_id = draft.equip_oa_id
|
||||||
|
order.equip_name = draft.equip_name
|
||||||
|
order.equip_job_num = draft.equip_job_num
|
||||||
|
order.applicant_oa_id = draft.applicant_oa_id
|
||||||
|
order.applicant_name = draft.applicant_name
|
||||||
|
order.applicant_job_num = draft.applicant_job_num
|
||||||
|
order.monitor_status = classify_monitor_status(
|
||||||
|
can_accept=draft.can_accept,
|
||||||
|
is_returned=draft.is_returned,
|
||||||
|
flow_status=draft.flow_status_raw,
|
||||||
|
timer_started=draft.timer_started_at is not None,
|
||||||
|
)
|
||||||
|
order.dwell_days = dwell_days(
|
||||||
|
timer_started_at=draft.timer_started_at,
|
||||||
|
flow_status=draft.flow_status_raw,
|
||||||
|
finished_at=draft.finished_at,
|
||||||
|
as_of=as_of,
|
||||||
|
)
|
||||||
|
order.present_in_source = True
|
||||||
|
order.synced_at = now
|
||||||
|
order.updated_at = now
|
||||||
|
cancelled = 0
|
||||||
|
if order.monitor_status != "watching":
|
||||||
|
from app.services.equipment_acceptance.alert_service import cancel_unsent
|
||||||
|
|
||||||
|
cancelled = cancel_unsent(order.id)
|
||||||
|
# [STEP] 先从会话里删掉旧子行,再插入本次节点和操作人,避免批量 delete 后旧对象被重新写回
|
||||||
|
for node in db.session.query(EquipmentAcceptanceNode).filter(EquipmentAcceptanceNode.order_id == order.id).all():
|
||||||
|
db.session.delete(node)
|
||||||
|
for operator in (
|
||||||
|
db.session.query(EquipmentAcceptanceOperator)
|
||||||
|
.filter(EquipmentAcceptanceOperator.order_id == order.id)
|
||||||
|
.all()
|
||||||
|
):
|
||||||
|
db.session.delete(operator)
|
||||||
|
db.session.flush()
|
||||||
|
for node in draft.nodes:
|
||||||
|
db.session.add(
|
||||||
|
EquipmentAcceptanceNode(
|
||||||
|
order_id=order.id,
|
||||||
|
node_id=node.node_id,
|
||||||
|
node_name=node.node_name,
|
||||||
|
node_type=node.node_type,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
for operator in draft.operators:
|
||||||
|
db.session.add(
|
||||||
|
EquipmentAcceptanceOperator(
|
||||||
|
order_id=order.id,
|
||||||
|
node_id=operator.node_id,
|
||||||
|
user_id=operator.user_id,
|
||||||
|
handler_name=operator.handler_name,
|
||||||
|
handler_job_num=operator.handler_job_num,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return order, cancelled
|
||||||
|
|
||||||
|
|
||||||
|
def _mark_absent(request_ids: list[int]) -> int:
|
||||||
|
"""把这次没拉到的单据标成源里不存在。"""
|
||||||
|
query = db.session.query(EquipmentAcceptanceOrder).filter(EquipmentAcceptanceOrder.present_in_source.is_(True))
|
||||||
|
if request_ids:
|
||||||
|
query = query.filter(EquipmentAcceptanceOrder.request_id.notin_(request_ids))
|
||||||
|
return query.update({EquipmentAcceptanceOrder.present_in_source: False}, synchronize_session=False)
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_focus(focus: str | None) -> str | None:
|
||||||
|
"""空白视为全部。未知分组拒绝,避免把原型筛选项写错后悄悄查出空表。"""
|
||||||
|
value = str(focus or "").strip()
|
||||||
|
if not value or value == "all":
|
||||||
|
return None
|
||||||
|
if value not in _LEDGER_FOCUSES:
|
||||||
|
raise ValidationError(
|
||||||
|
"未知的设备验收列表分组",
|
||||||
|
code="EQUIPMENT_ACCEPTANCE.CONFIG_INVALID",
|
||||||
|
details={"focus": value},
|
||||||
|
)
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_focus(query, focus: str, reminder_day: int):
|
||||||
|
"""按停留列表分组过滤。已逾期只含计时中且超过当前第 1 档的单据。"""
|
||||||
|
if focus == "watching":
|
||||||
|
return query.filter(EquipmentAcceptanceOrder.monitor_status == "watching")
|
||||||
|
if focus == "not_started":
|
||||||
|
return query.filter(EquipmentAcceptanceOrder.monitor_status == "not_started")
|
||||||
|
if focus == "stopped":
|
||||||
|
return query.filter(EquipmentAcceptanceOrder.monitor_status.in_(_STOPPED_STATUSES))
|
||||||
|
return query.filter(
|
||||||
|
EquipmentAcceptanceOrder.monitor_status == "watching",
|
||||||
|
EquipmentAcceptanceOrder.dwell_days > reminder_day,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _ledger_summary(reminder_day: int) -> dict[str, int]:
|
||||||
|
"""统计全部单据的进行中、已逾期、不再提醒、未开始,不受当前筛选影响。"""
|
||||||
|
base = db.session.query(EquipmentAcceptanceOrder)
|
||||||
|
return {
|
||||||
|
"watching": base.filter(EquipmentAcceptanceOrder.monitor_status == "watching").count(),
|
||||||
|
"overdue": base.filter(
|
||||||
|
EquipmentAcceptanceOrder.monitor_status == "watching",
|
||||||
|
EquipmentAcceptanceOrder.dwell_days > reminder_day,
|
||||||
|
).count(),
|
||||||
|
"stopped": base.filter(EquipmentAcceptanceOrder.monitor_status.in_(_STOPPED_STATUSES)).count(),
|
||||||
|
"not_started": base.filter(EquipmentAcceptanceOrder.monitor_status == "not_started").count(),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_status(monitor_status: str | None) -> str | None:
|
||||||
|
"""空白过滤视为不筛选。未知状态拒绝,避免把撤回等未定义值写进查询。"""
|
||||||
|
status = str(monitor_status or "").strip()
|
||||||
|
if not status:
|
||||||
|
return None
|
||||||
|
if status not in MONITOR_STATUSES:
|
||||||
|
raise ValidationError(
|
||||||
|
"未知的设备验收监控状态",
|
||||||
|
code="EQUIPMENT_ACCEPTANCE.CONFIG_INVALID",
|
||||||
|
details={"monitor_status": status},
|
||||||
|
)
|
||||||
|
return status
|
||||||
|
|
||||||
|
|
||||||
|
def _nodes_by_order(order_ids: list[int]) -> dict[int, list[EquipmentAcceptanceNode]]:
|
||||||
|
"""一次取出当前页的节点,避免逐单查询。"""
|
||||||
|
if not order_ids:
|
||||||
|
return {}
|
||||||
|
grouped: dict[int, list[EquipmentAcceptanceNode]] = {}
|
||||||
|
rows = (
|
||||||
|
db.session.query(EquipmentAcceptanceNode)
|
||||||
|
.filter(EquipmentAcceptanceNode.order_id.in_(order_ids))
|
||||||
|
.order_by(EquipmentAcceptanceNode.id.asc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
for row in rows:
|
||||||
|
grouped.setdefault(row.order_id, []).append(row)
|
||||||
|
return grouped
|
||||||
|
|
||||||
|
|
||||||
|
def _operators_by_order(order_ids: list[int]) -> dict[int, list[EquipmentAcceptanceOperator]]:
|
||||||
|
"""一次取出当前页的操作人,避免逐单查询。"""
|
||||||
|
if not order_ids:
|
||||||
|
return {}
|
||||||
|
grouped: dict[int, list[EquipmentAcceptanceOperator]] = {}
|
||||||
|
rows = (
|
||||||
|
db.session.query(EquipmentAcceptanceOperator)
|
||||||
|
.filter(EquipmentAcceptanceOperator.order_id.in_(order_ids))
|
||||||
|
.order_by(EquipmentAcceptanceOperator.id.asc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
for row in rows:
|
||||||
|
grouped.setdefault(row.order_id, []).append(row)
|
||||||
|
return grouped
|
||||||
|
|
||||||
|
|
||||||
|
def _order_payload(
|
||||||
|
order: EquipmentAcceptanceOrder,
|
||||||
|
nodes: list[EquipmentAcceptanceNode],
|
||||||
|
operators: list[EquipmentAcceptanceOperator],
|
||||||
|
reminder_day: int,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""把快照收成 API 数据。人员主键用字符串,避免长整型在前端丢精度。overdue 只标记计时中且超过第 1 档的单据。"""
|
||||||
|
payload: dict[str, Any] = {
|
||||||
|
"id": order.id,
|
||||||
|
"acceptance_no": order.acceptance_no,
|
||||||
|
"purchase_order_no": order.purchase_order_no,
|
||||||
|
"contract_no": order.contract_no,
|
||||||
|
"timer_started_at": utc_iso(order.timer_started_at),
|
||||||
|
"dwell_days": order.dwell_days,
|
||||||
|
"can_accept": order.can_accept,
|
||||||
|
"cannot_accept_note": order.cannot_accept_note,
|
||||||
|
"is_returned": order.is_returned,
|
||||||
|
"flow_status_raw": order.flow_status_raw,
|
||||||
|
"finished_at": utc_iso(order.finished_at),
|
||||||
|
"request_id": _id_text(order.request_id),
|
||||||
|
"request_match_count": order.request_match_count,
|
||||||
|
"owner_oa_id": _id_text(order.owner_oa_id),
|
||||||
|
"owner_name": order.owner_name,
|
||||||
|
"owner_job_num": order.owner_job_num,
|
||||||
|
"equip_oa_id": _id_text(order.equip_oa_id),
|
||||||
|
"equip_name": order.equip_name,
|
||||||
|
"equip_job_num": order.equip_job_num,
|
||||||
|
"applicant_oa_id": _id_text(order.applicant_oa_id),
|
||||||
|
"applicant_name": order.applicant_name,
|
||||||
|
"applicant_job_num": order.applicant_job_num,
|
||||||
|
"monitor_status": order.monitor_status,
|
||||||
|
"overdue": order.monitor_status == "watching" and (order.dwell_days or 0) > reminder_day,
|
||||||
|
"present_in_source": order.present_in_source,
|
||||||
|
"synced_at": utc_iso(order.synced_at),
|
||||||
|
"nodes": [
|
||||||
|
{
|
||||||
|
"node_id": _id_text(node.node_id),
|
||||||
|
"node_name": node.node_name,
|
||||||
|
"node_type": node.node_type,
|
||||||
|
}
|
||||||
|
for node in nodes
|
||||||
|
],
|
||||||
|
"operators": [
|
||||||
|
{
|
||||||
|
"node_id": _id_text(item.node_id),
|
||||||
|
"user_id": _id_text(item.user_id),
|
||||||
|
"handler_name": item.handler_name,
|
||||||
|
"handler_job_num": item.handler_job_num,
|
||||||
|
}
|
||||||
|
for item in operators
|
||||||
|
],
|
||||||
|
}
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def _id_text(value: int | None) -> str | None:
|
||||||
|
"""OA 长整型主键序列化成字符串。"""
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
return str(value)
|
||||||
@@ -32,6 +32,8 @@ 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,
|
||||||
|
receipt_date_to: str | None = None,
|
||||||
sender: WeComSender | None = None,
|
sender: WeComSender | None = None,
|
||||||
recipients: list[str] | None = None) -> AutoTransferOutcome:
|
recipients: list[str] | None = None) -> AutoTransferOutcome:
|
||||||
"""执行一次自动调拨排程。
|
"""执行一次自动调拨排程。
|
||||||
@@ -44,6 +46,8 @@ 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: 可选收料日期范围(测试/排障缩小
|
||||||
|
匹配面;留空=全部成熟积压;非法范围由匹配层抛 ValidationError)。
|
||||||
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 为空。
|
||||||
@@ -59,6 +63,8 @@ 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,
|
||||||
|
receipt_date_to=receipt_date_to,
|
||||||
)
|
)
|
||||||
# [STEP 2] 空数据日跳过执行:匹配后无可执行行(含恢复后仍为 0)时不建票、
|
# [STEP 2] 空数据日跳过执行:匹配后无可执行行(含恢复后仍为 0)时不建票、
|
||||||
# 不写 ERP、不通知(产品决策 C5);该日仅留痕 Run/Matching,不视作失败。
|
# 不写 ERP、不通知(产品决策 C5);该日仅留痕 Run/Matching,不视作失败。
|
||||||
|
|||||||
@@ -112,17 +112,26 @@ class MatchingItemDTO:
|
|||||||
# 不参与匹配身份与 Hash 快照;空值行在匹配阶段落 blocked_missing_unit。
|
# 不参与匹配身份与 Hash 快照;空值行在匹配阶段落 blocked_missing_unit。
|
||||||
unit: str = ""
|
unit: str = ""
|
||||||
# 行装饰字段(restore 按 scope 实时视图时填齐;run_matching 快照路径保持缺省):
|
# 行装饰字段(restore 按 scope 实时视图时填齐;run_matching 快照路径保持缺省):
|
||||||
# item_id=行主键(批量操作/待处理池回链);checked_at=行评估时间(updated_at);
|
# item_id=行主键(批量操作/待处理池回链);checked_at=行库存查得时刻(见 _item_dto);
|
||||||
# stale=评估时间距今超过确认 TTL;file_current=行评估版本戳仍是该来源当前可用文件。
|
# stale=距库存取数超过展示阈值;file_current=行评估版本戳仍是该来源当前可用文件。
|
||||||
item_id: int = 0
|
item_id: int = 0
|
||||||
checked_at: str | None = None
|
checked_at: str | None = None
|
||||||
stale: bool = False
|
stale: bool = False
|
||||||
file_current: bool = False
|
file_current: bool = False
|
||||||
|
# [2026-10-12 单据数口径修正] 执行建单五元组首键:路由解析所得外部组织
|
||||||
|
# (execution_service.prepare_execution 同款 .strip() 口径)。匹配评估路径填齐,
|
||||||
|
# 供「预计 ERP 单据数」按五元组去重与前端勾选行预估;restore 视图路径缺省 ""。
|
||||||
|
external_org: str = ""
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class MatchingSummaryDTO:
|
class MatchingSummaryDTO:
|
||||||
"""匹配摘要(含预计调拨数量、预计 外部系统 写入数与匹配 Hash)。"""
|
"""匹配摘要(含预计调拨数量、预计 ERP 单据数与匹配 Hash)。
|
||||||
|
|
||||||
|
estimated_external_write_count(2026-10-12 口径修正):可执行行按执行建单
|
||||||
|
五元组 (external_org, source_code, receipt_date, from_warehouse, to_warehouse)
|
||||||
|
去重后的单据数,非可执行行数——同组多行在执行期合并一张 ERP 单。
|
||||||
|
"""
|
||||||
|
|
||||||
matching_id: str
|
matching_id: str
|
||||||
status: str
|
status: str
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
from decimal import Decimal
|
from decimal import Decimal, InvalidOperation
|
||||||
from typing import Any, Iterable, Mapping
|
from typing import Any, Iterable, Mapping
|
||||||
|
|
||||||
from app.core.errors import AppError
|
from app.core.errors import AppError
|
||||||
@@ -59,16 +59,26 @@ def _fail(rows: list[dict[str, Any]], *, row_no: Any, reason: str) -> None:
|
|||||||
rows.append({"row_no": row_no, "reason": reason})
|
rows.append({"row_no": row_no, "reason": reason})
|
||||||
|
|
||||||
|
|
||||||
def _is_unreceived_row(date_value: Any) -> bool:
|
def _is_unusable_receipt_row(date_value: Any, quantity_raw: Any) -> bool:
|
||||||
"""判断是否为"无收料事实的在途行":无异动日期即跳过。
|
"""判断是否为"非可用收料事实"的行:跳过,不参与匹配,也不阻断整文件。
|
||||||
|
|
||||||
WMS 异动报告会携带两类无日期行,均不是可用的收料事实:
|
WMS 异动报告会携带三类非可用收料行,均不是可用的收料事实:
|
||||||
① 未收料在途 ASN(Date Received 空、Qty Received 0);
|
① 未收料在途 ASN(Date Received 空、Qty Received 0);
|
||||||
② 收料执行中(ASN Status=Executing,Qty Received 已计数但收料日期未盖章)。
|
② 收料执行中(ASN Status=Executing,Qty Received 已计数但收料日期未盖章);
|
||||||
收料日期是匹配身份与成熟过滤的必要字段,缺失即无法参与匹配;
|
③ 零数量收料行(Date Received 已盖章但 Qty Received = 0;2026-10-08 CRANE
|
||||||
跳过后由下次排程抓取补齐(ASN 完成时盖章日期),不得整文件阻断。
|
WTP26082227 实测——扫码收货数量记在他行/收货取消的占位行)。
|
||||||
|
收料日期与正数量是行级匹配身份与成熟过滤的必要字段;此类行跳过后由下次排程
|
||||||
|
抓取补齐(WMS 补数量/盖章后自然带出),不得整文件阻断。
|
||||||
"""
|
"""
|
||||||
return not (isinstance(date_value, (date, datetime)) or str(date_value or "").strip())
|
if not (isinstance(date_value, (date, datetime)) or str(date_value or "").strip()):
|
||||||
|
return True
|
||||||
|
try:
|
||||||
|
# 只跳过恰好为 0 的零收料行;负数属数据损坏,交由 validate_receipt_quantity 阻断。
|
||||||
|
return Decimal(str(quantity_raw)) == 0
|
||||||
|
except (InvalidOperation, ValueError, TypeError):
|
||||||
|
# 数量缺失/空:日期已盖章但无数量,同为零收料家族;非数字垃圾交由
|
||||||
|
# validate_receipt_quantity 按非法数量阻断,不在此吞掉。
|
||||||
|
return not str(quantity_raw or "").strip()
|
||||||
|
|
||||||
|
|
||||||
def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]:
|
def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]:
|
||||||
@@ -174,7 +184,7 @@ def _parse_rows(
|
|||||||
if row_source and row_source.upper() != str(source_code).upper():
|
if row_source and row_source.upper() != str(source_code).upper():
|
||||||
_fail(errors, row_no=row_no, reason=f"source_identity_mismatch: {row_source}")
|
_fail(errors, row_no=row_no, reason=f"source_identity_mismatch: {row_source}")
|
||||||
continue
|
continue
|
||||||
if _is_unreceived_row(receipt_date_value):
|
if _is_unusable_receipt_row(receipt_date_value, quantity_raw):
|
||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
receipt_date = parse_date(receipt_date_value)
|
receipt_date = parse_date(receipt_date_value)
|
||||||
@@ -202,5 +212,8 @@ def _parse_rows(
|
|||||||
unit=str(row.get("unit") or "").strip(),
|
unit=str(row.get("unit") or "").strip(),
|
||||||
))
|
))
|
||||||
if errors:
|
if errors:
|
||||||
raise ReceiptFileSchemaError(rows=errors)
|
# 诊断落库:消息携带前 3 条行级明细(行号+原因),随 parse_error_message
|
||||||
|
# 落库自描述(2026-10-08 CRANE 零数量行事故:此前只有通用消息、无法定位)。
|
||||||
|
summary = '; '.join(f"row {r.get('row_no')}: {r.get('reason')}" for r in errors[:3])
|
||||||
|
raise ReceiptFileSchemaError(f"receipt file schema invalid: {summary}", rows=errors)
|
||||||
return parsed
|
return parsed
|
||||||
@@ -389,6 +389,23 @@ def run_matching(
|
|||||||
estimated_quantity = sum(
|
estimated_quantity = sum(
|
||||||
(item.to_quantity for item in items if item.result == RESULT_EXECUTABLE), Decimal("0")
|
(item.to_quantity for item in items if item.result == RESULT_EXECUTABLE), Decimal("0")
|
||||||
)
|
)
|
||||||
|
# [2026-10-12 单据数口径修正] 预计 ERP 单据数 ≠ 可执行行数:执行建单按五元组
|
||||||
|
# (external_org, source_code, receipt_date, from_warehouse, to_warehouse) 分组,
|
||||||
|
# 同组多行合并一张 ERP 单(execution_service.prepare_execution 同键同 .strip()
|
||||||
|
# 规范化)。本值 = 可执行行按同款五元组去重后的组数;行上 external_org 由
|
||||||
|
# 匹配评估随路由解析填齐(_matching_rows 评估分支)。原「= executable_count」
|
||||||
|
# 口径在多行同组时高估单据数,误导用户。
|
||||||
|
estimated_document_keys = {
|
||||||
|
(
|
||||||
|
item.external_org,
|
||||||
|
str(item.source_code or "").strip(),
|
||||||
|
str(item.receipt_date or "").strip(),
|
||||||
|
str(item.from_warehouse or "").strip(),
|
||||||
|
str(item.to_warehouse or "").strip(),
|
||||||
|
)
|
||||||
|
for item in items
|
||||||
|
if item.result == RESULT_EXECUTABLE
|
||||||
|
}
|
||||||
snapshot = {
|
snapshot = {
|
||||||
"scope": sorted(set(source_codes)),
|
"scope": sorted(set(source_codes)),
|
||||||
"business_date": business_date,
|
"business_date": business_date,
|
||||||
@@ -433,7 +450,7 @@ def run_matching(
|
|||||||
expires_at="",
|
expires_at="",
|
||||||
counts=counts,
|
counts=counts,
|
||||||
estimated_transfer_quantity=str(estimated_quantity),
|
estimated_transfer_quantity=str(estimated_quantity),
|
||||||
estimated_external_write_count=counts.executable_count,
|
estimated_external_write_count=len(estimated_document_keys),
|
||||||
matching_hash=matching_hash,
|
matching_hash=matching_hash,
|
||||||
)
|
)
|
||||||
return MatchingRunResult(summary=summary, items=tuple(items), sources=sources_tuple)
|
return MatchingRunResult(summary=summary, items=tuple(items), sources=sources_tuple)
|
||||||
@@ -621,8 +638,11 @@ def _matching_rows(
|
|||||||
row.result_code = match
|
row.result_code = match
|
||||||
row.result_message = "strict quantity mismatch"
|
row.result_message = "strict quantity mismatch"
|
||||||
row.updated_at = now
|
row.updated_at = now
|
||||||
|
# 本行已完成路由解析:external_org 随行透出(执行建单五元组首键,
|
||||||
|
# 2026-10-12 单据数口径修正——预计单据数按五元组去重依赖本字段)。
|
||||||
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
|
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
|
||||||
int(deps.strategy.inventory_stale_ttl_seconds)))
|
int(deps.strategy.inventory_stale_ttl_seconds),
|
||||||
|
external_org=str(route.external_org or "").strip()))
|
||||||
return output, pending_count
|
return output, pending_count
|
||||||
|
|
||||||
|
|
||||||
@@ -944,6 +964,7 @@ def _item_dto(
|
|||||||
latest: dict,
|
latest: dict,
|
||||||
moment: datetime,
|
moment: datetime,
|
||||||
inventory_stale_ttl_seconds: int,
|
inventory_stale_ttl_seconds: int,
|
||||||
|
external_org: str = "",
|
||||||
) -> MatchingItemDTO:
|
) -> MatchingItemDTO:
|
||||||
"""把 InvoiceItem 装饰为前端行 DTO(restore 视图与可调拨明细队列共用)。
|
"""把 InvoiceItem 装饰为前端行 DTO(restore 视图与可调拨明细队列共用)。
|
||||||
|
|
||||||
@@ -953,8 +974,10 @@ def _item_dto(
|
|||||||
moment: 新鲜度判定基准时间。
|
moment: 新鲜度判定基准时间。
|
||||||
inventory_stale_ttl_seconds: stale 展示阈值(strategy.inventory_stale_ttl_seconds;
|
inventory_stale_ttl_seconds: stale 展示阈值(strategy.inventory_stale_ttl_seconds;
|
||||||
仅驱动 stale 徽标提示,不阻断执行——2026-09-25 TTL 门禁退役)。
|
仅驱动 stale 徽标提示,不阻断执行——2026-09-25 TTL 门禁退役)。
|
||||||
|
external_org: 路由解析所得外部组织(执行建单五元组首键,2026-10-12 单据数
|
||||||
|
口径修正);仅匹配评估路径可填,restore 视图路径缺省 ""。
|
||||||
Returns:
|
Returns:
|
||||||
MatchingItemDTO(含 item_id / checked_at / stale / file_current)。
|
MatchingItemDTO(含 item_id / checked_at / stale / file_current / external_org)。
|
||||||
"""
|
"""
|
||||||
evaluated_sha = _item_evaluated_sha(item)
|
evaluated_sha = _item_evaluated_sha(item)
|
||||||
inventory_checked_at = item.inventory_checked_at
|
inventory_checked_at = item.inventory_checked_at
|
||||||
@@ -1002,6 +1025,7 @@ def _item_dto(
|
|||||||
stale=bool(inventory_checked_at)
|
stale=bool(inventory_checked_at)
|
||||||
and (moment - inventory_checked_at).total_seconds() > inventory_stale_ttl_seconds,
|
and (moment - inventory_checked_at).total_seconds() > inventory_stale_ttl_seconds,
|
||||||
file_current=bool(evaluated_sha) and evaluated_sha == latest.get("file_sha256"),
|
file_current=bool(evaluated_sha) and evaluated_sha == latest.get("file_sha256"),
|
||||||
|
external_org=external_org,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"""在途调拨真实收料 RPA 触发服务。
|
"""在途调拨真实收料 RPA 触发服务。
|
||||||
|
|
||||||
用途:为单个来源触发一次收料/异动 RPA 抓取(复用货代收料 trigger 链路),不创建排程。
|
用途:为单个或多个来源触发收料/异动 RPA 抓取(复用货代收料 trigger 链路),不创建排程。
|
||||||
按来源取 ShippingInventorySource + ShippingReceiptReportConfig + rpa_profile,
|
按来源取 ShippingInventorySource + ShippingReceiptReportConfig + rpa_profile,
|
||||||
先落 ShippingReceiptRpaUnitRun(awaiting_rpa,回调按 callback_id 查库可达),
|
先落 ShippingReceiptRpaUnitRun(awaiting_rpa,回调按 callback_id 查库可达),
|
||||||
再装配收料 trigger unit 并调用 write_receipt_export_batch_trigger 原子写 trigger。
|
再装配收料 trigger unit 并调用 write_receipt_export_batch_trigger 原子写 trigger。
|
||||||
@@ -8,11 +8,14 @@
|
|||||||
逻辑:list_receipt_capable_source_codes 供排程 source_codes 留空时的缺省范围;
|
逻辑:list_receipt_capable_source_codes 供排程 source_codes 留空时的缺省范围;
|
||||||
一源一单元,query_parameters 原样下发;来源停用/收料配置缺失/rpa_profile 缺失时
|
一源一单元,query_parameters 原样下发;来源停用/收料配置缺失/rpa_profile 缺失时
|
||||||
fail-closed;写 trigger 失败把单元行标 failed 并 commit。
|
fail-closed;写 trigger 失败把单元行标 failed 并 commit。
|
||||||
|
trigger_receipt_rpa_batch(2026-10-09)把多来源合并为一个 batch trigger 文件:
|
||||||
|
Worker 对单文件按 profile 分组共享一次浏览器会话,避免逐来源开/关浏览器。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import uuid
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
from typing import Any, Callable
|
from typing import Any, Callable
|
||||||
|
|
||||||
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
|
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
|
||||||
@@ -151,3 +154,117 @@ def trigger_receipt_rpa(
|
|||||||
unit.trigger_snapshot_json = unit_payload
|
unit.trigger_snapshot_json = unit_payload
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return {"ok": True, "callback_id": unit_payload['callback_id'], "trigger_path": path}
|
return {"ok": True, "callback_id": unit_payload['callback_id'], "trigger_path": path}
|
||||||
|
|
||||||
|
|
||||||
|
def trigger_receipt_rpa_batch(
|
||||||
|
*,
|
||||||
|
source_codes: list[str],
|
||||||
|
business_date: str,
|
||||||
|
reason: str = 'transfer_retry_receipt',
|
||||||
|
writer: RouteTriggerWriter | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""批量触发多来源收料 RPA:全部有效来源合并写**一个** batch trigger 文件。
|
||||||
|
|
||||||
|
【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个来源编码时调用;
|
||||||
|
行级单来源重试仍走 trigger_receipt_rpa(一源一文件语义不变)。
|
||||||
|
|
||||||
|
核心逻辑:逐来源装配 unit(来源级隔离——配置缺失/停用跳过并记录,不炸整批;
|
||||||
|
parse_failed 先本地重解析,恢复 ready 则不触发 RPA),有效 units 先各落一行
|
||||||
|
ShippingReceiptRpaUnitRun 再一次性 write_receipt_export_batch_trigger 原子落盘。
|
||||||
|
Worker 对单文件按 profile 分组共享一次浏览器会话串行导出,避免逐来源开/关浏览器。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
source_codes: 来源实例编码列表(去重保序;空串自动剔除)。
|
||||||
|
business_date: 业务日期。
|
||||||
|
reason: 触发原因(写入 trigger payload)。
|
||||||
|
writer: 触发写者;缺省复用 write_receipt_export_batch_trigger。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
{"ok": True/False, "triggered": bool, "results": [...], "trigger_path"?/「error_code」?}。
|
||||||
|
ok=本次请求产生了主效果(写盘成功,或无需写盘且全部来源经本地重解析恢复);
|
||||||
|
triggered=是否写了 batch trigger;results 逐来源携带真实结果
|
||||||
|
(触发:{source_code, ok: true};重解析:{..., reparsed: true, file_status};
|
||||||
|
跳过:{source_code, ok: false, error_code, error_message})。
|
||||||
|
"""
|
||||||
|
from app import db
|
||||||
|
from app.models import ShippingReceiptRpaUnitRun
|
||||||
|
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
|
||||||
|
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||||
|
|
||||||
|
codes = list(dict.fromkeys(str(code).strip() for code in source_codes if str(code).strip()))
|
||||||
|
results: list[dict[str, Any]] = []
|
||||||
|
units: list[ShippingReceiptRpaUnitRun] = []
|
||||||
|
unit_payloads: list[dict[str, Any]] = []
|
||||||
|
|
||||||
|
# [STEP 1] 解析失败分层(对齐单来源端点)+ 逐来源装配 unit;单源失败跳过不阻断整批。
|
||||||
|
for code in codes:
|
||||||
|
status = resolve_source_file_status(source_code=code)
|
||||||
|
if status.get('file_status') == 'parse_failed' and status.get('file_sha256'):
|
||||||
|
sync_and_commit_for_callback(
|
||||||
|
source_code=code, business_date=business_date, now=datetime.utcnow(),
|
||||||
|
)
|
||||||
|
status = resolve_source_file_status(source_code=code)
|
||||||
|
results.append({
|
||||||
|
'source_code': code,
|
||||||
|
'ok': status.get('file_status') == 'ready',
|
||||||
|
'reparsed': True,
|
||||||
|
'file_status': status.get('file_status'),
|
||||||
|
})
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
unit_payloads.append(_build_trigger_unit(source_code=code, business_date=business_date, reason=reason))
|
||||||
|
except RuntimeError as exc:
|
||||||
|
results.append({
|
||||||
|
'source_code': code, 'ok': False,
|
||||||
|
'error_code': 'RPA_RECEIPT_CONFIG_MISSING', 'error_message': str(exc),
|
||||||
|
})
|
||||||
|
|
||||||
|
if not unit_payloads:
|
||||||
|
# 无可触发来源:全部经重解析恢复 → 请求已达成目的;否则如实报无可用来源。
|
||||||
|
reparse_recovered = any(item.get('reparsed') and item.get('ok') for item in results)
|
||||||
|
db.session.commit()
|
||||||
|
if reparse_recovered:
|
||||||
|
return {"ok": True, "triggered": False, "results": results}
|
||||||
|
return {"ok": False, "triggered": False, "error_code": "RPA_RECEIPT_NO_TRIGGERABLE_SOURCE", "results": results}
|
||||||
|
|
||||||
|
# [STEP 2] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库(与单来源同模式)。
|
||||||
|
for payload in unit_payloads:
|
||||||
|
unit = ShippingReceiptRpaUnitRun(
|
||||||
|
inventory_source_id=payload['inventory_source_id'],
|
||||||
|
source_code=payload['source_code'],
|
||||||
|
connector_type=payload['connector_type'],
|
||||||
|
warehouse_id=payload.get('warehouse_id'),
|
||||||
|
callback_id=payload['callback_id'],
|
||||||
|
status='awaiting_rpa',
|
||||||
|
config_snapshot_json=dict(payload['config_snapshot']),
|
||||||
|
)
|
||||||
|
db.session.add(unit)
|
||||||
|
units.append(unit)
|
||||||
|
db.session.flush()
|
||||||
|
for unit, payload in zip(units, unit_payloads):
|
||||||
|
payload['unit_run_id'] = unit.id
|
||||||
|
|
||||||
|
# [STEP 3] 一个 batch trigger 原子落盘;目录不可用则本批单元全部标 failed(不留永久 awaiting)。
|
||||||
|
run_no = f"TRIG-BATCH-{uuid.uuid4().hex[:8].upper()}"
|
||||||
|
writer_fn = writer or write_receipt_export_batch_trigger
|
||||||
|
path = writer_fn(run_no, unit_payloads, payload={
|
||||||
|
'schema_version': 'shipping_receipt_rpa.v1',
|
||||||
|
'action': 'receipt_export_batch',
|
||||||
|
'business_date': business_date,
|
||||||
|
'reason': reason,
|
||||||
|
'source_codes': [payload['source_code'] for payload in unit_payloads],
|
||||||
|
})
|
||||||
|
if not path:
|
||||||
|
for unit in units:
|
||||||
|
unit.status = 'failed'
|
||||||
|
unit.error_code = 'RPA_RECEIPT_TRIGGER_UNAVAILABLE'
|
||||||
|
unit.error_message = 'receipt trigger directory unavailable'
|
||||||
|
db.session.commit()
|
||||||
|
return {"ok": False, "triggered": False, "error_code": "RPA_RECEIPT_TRIGGER_UNAVAILABLE", "results": results}
|
||||||
|
|
||||||
|
# [STEP 4] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。
|
||||||
|
for unit, payload in zip(units, unit_payloads):
|
||||||
|
unit.trigger_snapshot_json = payload
|
||||||
|
results.append({'source_code': unit.source_code, 'ok': True})
|
||||||
|
db.session.commit()
|
||||||
|
return {"ok": True, "triggered": True, "trigger_path": path, "results": results}
|
||||||
@@ -81,6 +81,9 @@ def serialize_item(item) -> dict[str, Any]:
|
|||||||
"to_quantity": str(item.to_quantity),
|
"to_quantity": str(item.to_quantity),
|
||||||
# 交易单位原值透传(movement 契约第 11 字段 unit,T7 交接:序列化缺口补齐)。
|
# 交易单位原值透传(movement 契约第 11 字段 unit,T7 交接:序列化缺口补齐)。
|
||||||
"unit": item.unit,
|
"unit": item.unit,
|
||||||
|
# [2026-10-12 单据数口径修正] 执行建单五元组首键透传:前端按勾选行
|
||||||
|
# 预估 ERP 单据数与后端同口径分组(匹配评估路径填齐,历史回放缺省 "")。
|
||||||
|
"external_org": item.external_org,
|
||||||
"result": item.result,
|
"result": item.result,
|
||||||
"reason": item.reason,
|
"reason": item.reason,
|
||||||
"raw_lines": [
|
"raw_lines": [
|
||||||
|
|||||||
@@ -26,7 +26,10 @@ from app.services.in_transit_transfer.receipt_file_gate import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing')
|
RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing')
|
||||||
FAILED_UNIT_STATUSES = ('failed', 'empty', 'cancelled')
|
FAILED_UNIT_STATUSES = ('failed', 'cancelled')
|
||||||
|
# 空数据(no_receipt_data):抓取成功但当日无收料记录,属业务结果而非故障,
|
||||||
|
# 独立投影 no_data 供前端如实展示(2026-10-08:曾误并入 failed 致无法分辨真失败)。
|
||||||
|
NO_DATA_UNIT_STATUSES = ('empty',)
|
||||||
|
|
||||||
|
|
||||||
def resolve_source_file_status(*, source_code: str) -> dict:
|
def resolve_source_file_status(*, source_code: str) -> dict:
|
||||||
@@ -37,7 +40,7 @@ def resolve_source_file_status(*, source_code: str) -> dict:
|
|||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
{"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...},
|
{"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...},
|
||||||
file_status ∈ {'ready', 'parse_failed', 'fetching', 'failed', 'expired', 'none'};
|
file_status ∈ {'ready', 'parse_failed', 'fetching', 'failed', 'no_data', 'expired', 'none'};
|
||||||
parse_failed 表示文件仍可用但解析失败:has_ready_file=False,
|
parse_failed 表示文件仍可用但解析失败:has_ready_file=False,
|
||||||
仍带 file_no/file_sha256 便于诊断与前端提示。
|
仍带 file_no/file_sha256 便于诊断与前端提示。
|
||||||
"""
|
"""
|
||||||
@@ -84,6 +87,9 @@ def resolve_source_file_status(*, source_code: str) -> dict:
|
|||||||
.order_by(ShippingReceiptRpaUnitRun.id.desc())
|
.order_by(ShippingReceiptRpaUnitRun.id.desc())
|
||||||
.first()
|
.first()
|
||||||
)
|
)
|
||||||
|
if latest_unit is not None and latest_unit.status in NO_DATA_UNIT_STATUSES:
|
||||||
|
# 空数据:抓取成功但当日无收料记录——如实投影 no_data,不得与抓取失败混淆。
|
||||||
|
return {'file_status': 'no_data', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||||
if latest_unit is not None and latest_unit.status in FAILED_UNIT_STATUSES:
|
if latest_unit is not None and latest_unit.status in FAILED_UNIT_STATUSES:
|
||||||
return {'file_status': 'failed', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
return {'file_status': 'failed', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||||
|
|
||||||
|
|||||||
@@ -103,6 +103,9 @@ class DifyService:
|
|||||||
def _friendly_workflow_failure_message(raw_error: str, agent_name: str | None = None) -> str:
|
def _friendly_workflow_failure_message(raw_error: str, agent_name: str | None = None) -> str:
|
||||||
"""
|
"""
|
||||||
将 Dify/Tool 技术错误转成用户可读提示。
|
将 Dify/Tool 技术错误转成用户可读提示。
|
||||||
|
|
||||||
|
核心逻辑:优先识别知识库重排授权和知识检索失败,再按工具、上下文长度等归类。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
raw_error: Dify 返回的原始错误文本。
|
raw_error: Dify 返回的原始错误文本。
|
||||||
agent_name: 当前触发错误的 Agent 名称,用于返回更贴合页面上下文的提示文案。
|
agent_name: 当前触发错误的 Agent 名称,用于返回更贴合页面上下文的提示文案。
|
||||||
@@ -112,6 +115,19 @@ class DifyService:
|
|||||||
text = str(raw_error or "")
|
text = str(raw_error or "")
|
||||||
lower = text.lower()
|
lower = text.lower()
|
||||||
resolved_agent_name = str(agent_name or "").strip() or "当前智能体"
|
resolved_agent_name = str(agent_name or "").strip() or "当前智能体"
|
||||||
|
if "rerank" in lower and ("403" in lower or "forbidden" in lower):
|
||||||
|
return (
|
||||||
|
f"{resolved_agent_name}的知识检索重排服务授权失败。"
|
||||||
|
"请联系管理员在 Dify 中更新 Rerank 模型供应商的 API Key 后重新发布应用。"
|
||||||
|
)
|
||||||
|
if any(token in lower for token in (
|
||||||
|
"knowledge-retrieval",
|
||||||
|
"knowledge retrieval",
|
||||||
|
"dataset not found",
|
||||||
|
"embedding model",
|
||||||
|
"知识库",
|
||||||
|
)):
|
||||||
|
return f"{resolved_agent_name}的知识库检索失败,请稍后重试;如持续失败请联系管理员检查知识库与模型配置。"
|
||||||
if "keyword is required" in lower or re.search(r"\bstatus code 400\b", lower):
|
if "keyword is required" in lower or re.search(r"\bstatus code 400\b", lower):
|
||||||
return "没有识别到要查询的设备编号或设备名称,请补充完整设备信息后再试。"
|
return "没有识别到要查询的设备编号或设备名称,请补充完整设备信息后再试。"
|
||||||
if re.search(r"\b(401|403)\b", lower) or "unauthorized" in lower or "invalid_auth" in lower:
|
if re.search(r"\b(401|403)\b", lower) or "unauthorized" in lower or "invalid_auth" in lower:
|
||||||
@@ -124,6 +140,52 @@ class DifyService:
|
|||||||
return "当前会话上下文过长,模型无法继续回答。请新建对话后重新查询。"
|
return "当前会话上下文过长,模型无法继续回答。请新建对话后重新查询。"
|
||||||
return f"{resolved_agent_name}暂时无法完成查询,请稍后重试。"
|
return f"{resolved_agent_name}暂时无法完成查询,请稍后重试。"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _present_stream_error_message(raw_message: str, status_code: int | None, agent_name: str | None = None) -> str:
|
||||||
|
"""
|
||||||
|
把 Dify 流内 error 事件转成可直接展示的提示。
|
||||||
|
|
||||||
|
核心逻辑:重排授权、鉴权、地址和网关状态走上游 HTTP 文案;其余走工作流失败文案。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
raw_message: Dify error 事件的 message。
|
||||||
|
status_code: 事件里的 HTTP 状态;没有时传 0。
|
||||||
|
agent_name: 当前智能体名称。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
面向用户的中文提示。
|
||||||
|
"""
|
||||||
|
text = str(raw_message or "")
|
||||||
|
lower = text.lower()
|
||||||
|
try:
|
||||||
|
code = int(status_code or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
code = 0
|
||||||
|
if "rerank" in lower or code in (401, 403, 404, 429, 502, 503, 504):
|
||||||
|
return DifyService._friendly_upstream_error_message(code, text, agent_name)
|
||||||
|
return DifyService._friendly_workflow_failure_message(text, agent_name)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _friendly_stream_request_failure_message(exc: Exception, agent_name: str | None = None) -> str:
|
||||||
|
"""
|
||||||
|
将连接 Dify 时的网络异常转成用户可读提示。
|
||||||
|
|
||||||
|
核心逻辑:超时和连接失败分开说明;其余 RequestException 使用当前智能体名称的通用失败句。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
exc: requests 抛出的连接、超时或协议异常。
|
||||||
|
agent_name: 当前智能体名称。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
面向用户的中文提示,不包含异常原文。
|
||||||
|
"""
|
||||||
|
resolved_agent_name = str(agent_name or "").strip() or "当前智能体"
|
||||||
|
if isinstance(exc, (requests.exceptions.ReadTimeout, requests.exceptions.ConnectTimeout)):
|
||||||
|
return f"{resolved_agent_name}等待 AI 服务响应超时,请稍后重试。"
|
||||||
|
if isinstance(exc, requests.exceptions.ConnectionError):
|
||||||
|
return f"暂时无法连接{resolved_agent_name}的 AI 服务,请稍后重试。"
|
||||||
|
return f"{resolved_agent_name}暂时无法完成查询,请稍后重试。"
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _friendly_upstream_error_message(status_code: int, raw_body: str, agent_name: str | None = None) -> str:
|
def _friendly_upstream_error_message(status_code: int, raw_body: str, agent_name: str | None = None) -> str:
|
||||||
"""将 Dify HTTP 错误转换为可执行的用户提示。
|
"""将 Dify HTTP 错误转换为可执行的用户提示。
|
||||||
@@ -1106,7 +1168,7 @@ class DifyService:
|
|||||||
},
|
},
|
||||||
'error',
|
'error',
|
||||||
)
|
)
|
||||||
yield f"data: {json.dumps({'event': 'error', 'message': message}, ensure_ascii=False)}\n\n"
|
yield f"data: {json.dumps({'event': 'error', 'message': message, 'user_facing': True}, ensure_ascii=False)}\n\n"
|
||||||
return
|
return
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
yield f"data: {json.dumps({'event': 'upstream_connected', 'message': 'Dify 已连接'}, ensure_ascii=False)}\n\n"
|
yield f"data: {json.dumps({'event': 'upstream_connected', 'message': 'Dify 已连接'}, ensure_ascii=False)}\n\n"
|
||||||
@@ -1140,7 +1202,29 @@ class DifyService:
|
|||||||
data.get('conversation_id') or normalized_conversation_id,
|
data.get('conversation_id') or normalized_conversation_id,
|
||||||
)
|
)
|
||||||
|
|
||||||
if event == 'node_finished':
|
if event == 'error':
|
||||||
|
status_raw = data.get('status')
|
||||||
|
try:
|
||||||
|
status_code = int(status_raw)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
status_code = 0
|
||||||
|
raw_message = str(data.get('message') or '')
|
||||||
|
# [STEP] 流内 error 先转成用户提示再转发,避免前端只能看到笼统的请求失败。
|
||||||
|
data['message'] = DifyService._present_stream_error_message(
|
||||||
|
raw_message,
|
||||||
|
status_code,
|
||||||
|
getattr(agent, 'name', None),
|
||||||
|
)
|
||||||
|
data['user_facing'] = True
|
||||||
|
if current_app:
|
||||||
|
current_app.logger.warning(
|
||||||
|
"[chat-stream] dify error event request_id=%s agent_id=%s status=%s raw_error=%s",
|
||||||
|
request_id,
|
||||||
|
getattr(agent, 'id', None),
|
||||||
|
status_code,
|
||||||
|
raw_message,
|
||||||
|
)
|
||||||
|
elif event == 'node_finished':
|
||||||
# [STEP] Chatflow 知识检索结果在 node_finished.outputs.result,不在 message_end
|
# [STEP] Chatflow 知识检索结果在 node_finished.outputs.result,不在 message_end
|
||||||
DifyService._collect_knowledge_retrieval_from_node(retriever_resources, data)
|
DifyService._collect_knowledge_retrieval_from_node(retriever_resources, data)
|
||||||
|
|
||||||
@@ -1180,6 +1264,7 @@ class DifyService:
|
|||||||
)
|
)
|
||||||
data['message'] = friendly_error
|
data['message'] = friendly_error
|
||||||
data['error'] = friendly_error
|
data['error'] = friendly_error
|
||||||
|
data['user_facing'] = True
|
||||||
if isinstance(data.get('data'), dict):
|
if isinstance(data.get('data'), dict):
|
||||||
data['data']['message'] = friendly_error
|
data['data']['message'] = friendly_error
|
||||||
data['data']['error'] = friendly_error
|
data['data']['error'] = friendly_error
|
||||||
@@ -1226,13 +1311,17 @@ class DifyService:
|
|||||||
if not is_timeout and attempt < max_retries:
|
if not is_timeout and attempt < max_retries:
|
||||||
time.sleep(attempt * 2)
|
time.sleep(attempt * 2)
|
||||||
continue
|
continue
|
||||||
message = DifyService._friendly_stream_request_failure_message(e)
|
message = DifyService._friendly_stream_request_failure_message(
|
||||||
|
e,
|
||||||
|
getattr(agent, 'name', None),
|
||||||
|
)
|
||||||
# [STEP 4] 错误事件与持久化对象必须是同一个 dict,确保 chat_log_id 能继续传给 relay/领域 Handler。
|
# [STEP 4] 错误事件与持久化对象必须是同一个 dict,确保 chat_log_id 能继续传给 relay/领域 Handler。
|
||||||
error_event = {
|
error_event = {
|
||||||
'event': 'error',
|
'event': 'error',
|
||||||
'conversation_id': normalized_conversation_id,
|
'conversation_id': normalized_conversation_id,
|
||||||
'answer': message,
|
'answer': message,
|
||||||
'message': message,
|
'message': message,
|
||||||
|
'user_facing': True,
|
||||||
'metadata': {},
|
'metadata': {},
|
||||||
}
|
}
|
||||||
persist_stream_chat(error_event, 'error')
|
persist_stream_chat(error_event, 'error')
|
||||||
|
|||||||
@@ -5,8 +5,10 @@ backend/app/services/lean_training_push_service.py
|
|||||||
同时承担"每周自动滚动创建当周任务"与"推送成功后立即提醒已延期人员"两项周任务规则。
|
同时承担"每周自动滚动创建当周任务"与"推送成功后立即提醒已延期人员"两项周任务规则。
|
||||||
依赖:LeanTrainingWeeklyTask/LeanTrainingVideoPushLog/LeanTrainingReminder/User、lean_training_service(受训对象/当周边界)、lean_training_reminder_service(企微发送模板/延期提醒)、wecom_notify。
|
依赖:LeanTrainingWeeklyTask/LeanTrainingVideoPushLog/LeanTrainingReminder/User、lean_training_service(受训对象/当周边界)、lean_training_reminder_service(企微发送模板/延期提醒)、wecom_notify。
|
||||||
逻辑:以 task.pushed_video_count 为游标,每次从游标向后取 weekly_count 个"未被任何任务推送过"的视频(跨任务
|
逻辑:以 task.pushed_video_count 为游标,每次从游标向后取 weekly_count 个"未被任何任务推送过"的视频(跨任务
|
||||||
按已推送前缀并集去重,推过的视频绝不重复推);员工端展示已推送前缀;
|
按已推送前缀并集去重,推过的视频绝不重复推);员工端展示与考核口径为本任务首次推送的视频
|
||||||
企微 event_key 按"批次区间"幂等防止重复打扰;每轮执行写入 lean_training_video_push_logs 便于管理端查看失败明细;
|
(上一期已推送视频不重复展示、不要求重学,见 lean_training_service._own_pushed_video_ids);
|
||||||
|
企微 event_key 按"批次区间"幂等防止重复打扰(推送后的延期提醒与排程扫描共用"每人每天最多一条"去重,
|
||||||
|
由 lean_training_reminder_service 统一生成事件键);每轮执行写入 lean_training_video_push_logs 便于管理端查看失败明细;
|
||||||
排程入口每周一 09:00 先自动滚动创建当周任务(复制最近一期配置并自动追加配置新增视频,无需人工维护;
|
排程入口每周一 09:00 先自动滚动创建当周任务(复制最近一期配置并自动追加配置新增视频,无需人工维护;
|
||||||
视频库全部推完且无新增视频时暂停滚动、不创建内容重复的新一期),再对各任务推进一批推送。
|
视频库全部推完且无新增视频时暂停滚动、不创建内容重复的新一期),再对各任务推进一批推送。
|
||||||
"""
|
"""
|
||||||
@@ -234,10 +236,10 @@ def push_lean_training_videos(
|
|||||||
)
|
)
|
||||||
db.session.add(log)
|
db.session.add(log)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
# [STEP 4] 消息推送规则:本批推送成功后立马对任务中"已延期"(过截止未提交)的受训人员发送企微提醒
|
# [STEP 4] 消息推送规则:本批推送成功后立马对任务中"已延期"(过截止未提交)的受训人员发送企微提醒;
|
||||||
|
# 延期提醒与排程扫描共用"每人每天最多一条"判定(event_key 由提醒服务按北京日期统一生成)
|
||||||
notify_overdue_users_after_push(
|
notify_overdue_users_after_push(
|
||||||
task,
|
task,
|
||||||
event_key=f"overdue-after-push-{start_index}-{start_index + len(batch)}",
|
|
||||||
current=current,
|
current=current,
|
||||||
)
|
)
|
||||||
return serialize_push_log(log)
|
return serialize_push_log(log)
|
||||||
|
|||||||
@@ -4,12 +4,15 @@ backend/app/services/lean_training_reminder_service.py
|
|||||||
用途:执行精益管理周度培训的企微提醒生成与发送。
|
用途:执行精益管理周度培训的企微提醒生成与发送。
|
||||||
依赖:精益培训任务/完成/提醒模型、User、wecom_notify。
|
依赖:精益培训任务/完成/提醒模型、User、wecom_notify。
|
||||||
逻辑:排程按周日截止、周一/周三/周五催学规则写入幂等提醒,再由统一企微服务发送并落审计。
|
逻辑:排程按周日截止、周一/周三/周五催学规则写入幂等提醒,再由统一企微服务发送并落审计。
|
||||||
|
催办文案携带期次标签(第N期+周次区间)供员工区分期次;多期过期任务对同一员工合并为
|
||||||
|
一条汇总提醒,且所有自动催办(排程扫描/推送后延期)共用"每人每天最多一条"判定,
|
||||||
|
历史期任务过截止超过 OVERDUE_REMINDER_STOP_AFTER_DAYS 天后停止催办。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import datetime, timezone
|
from datetime import date, datetime, time, timedelta, timezone
|
||||||
|
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
from sqlalchemy.exc import IntegrityError
|
from sqlalchemy.exc import IntegrityError
|
||||||
@@ -19,9 +22,75 @@ from app.models import LeanTrainingCompletion, LeanTrainingReminder, LeanTrainin
|
|||||||
from app.services.lean_training_service import (
|
from app.services.lean_training_service import (
|
||||||
resolve_lean_training_jump_agent_id,
|
resolve_lean_training_jump_agent_id,
|
||||||
target_user_ids_for_task,
|
target_user_ids_for_task,
|
||||||
|
week_index_for_task,
|
||||||
)
|
)
|
||||||
from app.services.integrations.wecom.notify import send_wecom_event_message
|
from app.services.integrations.wecom.notify import send_wecom_event_message
|
||||||
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, utc_now_naive
|
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, to_utc_naive, utc_now_naive
|
||||||
|
|
||||||
|
# 历史期任务停止催办的宽限天数:过截止超过该天数后不再发送任何逾期/延期提醒。
|
||||||
|
# 任务仍保持 published 供管理端查询与统计,仅静默催办(2026-09-30 用户反馈旧期任务永久催办造成重复打扰)。
|
||||||
|
OVERDUE_REMINDER_STOP_AFTER_DAYS = 100
|
||||||
|
# 周中催学发送日(周一/周三/周五,Asia/Shanghai),与排程契约一致。
|
||||||
|
OVERDUE_REMINDER_WEEKDAYS = {0, 2, 4}
|
||||||
|
|
||||||
|
|
||||||
|
def _period_labels(task: LeanTrainingWeeklyTask) -> tuple[str, str]:
|
||||||
|
"""
|
||||||
|
返回周任务的期次标签二元组,供催办文案区分期次。
|
||||||
|
|
||||||
|
用途:多期任务并存扫描时,各期提醒文案完全相同,员工完成当期后仍会收到历史期催办,
|
||||||
|
无法分辨提醒归属哪一期而误以为系统误推(2026-09-30 正式环境用户反馈)。
|
||||||
|
期号与学员端"第N期"口径一致(week_key 全局升序,最早为第 1 期)。
|
||||||
|
Returns:
|
||||||
|
(短标签「第N期」用于标题后缀, 完整标签「第N期(MM-DD至MM-DD)」用于内容前缀);
|
||||||
|
week_key 脏数据解析失败时返回 ("", ""),调用方回退历史文案,提醒不因标签失败而中断。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
week_start = date.fromisoformat(task.week_key)
|
||||||
|
except ValueError:
|
||||||
|
return "", ""
|
||||||
|
week_end = week_start + timedelta(days=6)
|
||||||
|
index = week_index_for_task(task)
|
||||||
|
return f"第{index}期", f"第{index}期({week_start.strftime('%m-%d')}至{week_end.strftime('%m-%d')})"
|
||||||
|
|
||||||
|
|
||||||
|
def _overdue_event_key(now: datetime) -> str | None:
|
||||||
|
"""
|
||||||
|
返回催办轮次唯一键(overdue-<北京日期>),仅周一/周三/周五返回键,其余日期返回 None。
|
||||||
|
|
||||||
|
排程扫描与推送后延期提醒共用同一键空间:同一员工同一自然天的全部自动催办只允许一条,
|
||||||
|
LeanTrainingReminder 唯一约束 + 发送前"当天已催办"前置查询双重拦截重复推送
|
||||||
|
(2026-09-30 用户反馈同一员工同一天收到多条相同催办)。
|
||||||
|
"""
|
||||||
|
local_now = now.replace(tzinfo=timezone.utc).astimezone(resolve_schedule_tzinfo("Asia/Shanghai"))
|
||||||
|
if local_now.weekday() not in OVERDUE_REMINDER_WEEKDAYS:
|
||||||
|
return None
|
||||||
|
return f"overdue-{local_now.date().isoformat()}"
|
||||||
|
|
||||||
|
|
||||||
|
def _is_overdue_active(task: LeanTrainingWeeklyTask, now: datetime) -> bool:
|
||||||
|
"""判断任务处于"可催办"窗口:已过截止、且过截止未超过宽限期(超期历史期停止催办)。"""
|
||||||
|
return task.due_at < now <= task.due_at + timedelta(days=OVERDUE_REMINDER_STOP_AFTER_DAYS)
|
||||||
|
|
||||||
|
|
||||||
|
def _has_overdue_reminder_today(user_id: int, now: datetime) -> bool:
|
||||||
|
"""
|
||||||
|
判断员工北京时间当天是否已收到过任意精益自动催办(逾期/延期),实现"每人每天最多一条"。
|
||||||
|
|
||||||
|
用途:多期过期任务并存、排程扫描与批次推送两条催办路径同天先后执行时,
|
||||||
|
后执行的一方据此跳过,避免同一员工同一天收到多条相同催办。
|
||||||
|
"""
|
||||||
|
local_tz = resolve_schedule_tzinfo("Asia/Shanghai")
|
||||||
|
local_now = now.replace(tzinfo=timezone.utc).astimezone(local_tz)
|
||||||
|
day_floor_utc = to_utc_naive(datetime.combine(local_now.date(), time(0, 0, 0), tzinfo=local_tz))
|
||||||
|
existing = db.session.execute(
|
||||||
|
select(LeanTrainingReminder.id).where(
|
||||||
|
LeanTrainingReminder.recipient_user_id == user_id,
|
||||||
|
LeanTrainingReminder.event_key.like("overdue-%"),
|
||||||
|
LeanTrainingReminder.created_at >= day_floor_utc,
|
||||||
|
).limit(1)
|
||||||
|
).scalar_one_or_none()
|
||||||
|
return existing is not None
|
||||||
|
|
||||||
|
|
||||||
def _send_reminder(
|
def _send_reminder(
|
||||||
@@ -126,6 +195,9 @@ def send_targeted_reminders(task_id: int, user_ids: list[int], *, now: datetime
|
|||||||
if forbidden_ids:
|
if forbidden_ids:
|
||||||
raise ValueError("Some reminder recipients are outside the task target")
|
raise ValueError("Some reminder recipients are outside the task target")
|
||||||
totals = {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
|
totals = {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
|
||||||
|
short_label, full_label = _period_labels(task)
|
||||||
|
title_suffix = f"({short_label})" if short_label else ""
|
||||||
|
content_prefix = full_label if full_label else "本周"
|
||||||
for recipient in recipients:
|
for recipient in recipients:
|
||||||
if recipient.id in completed_user_ids:
|
if recipient.id in completed_user_ids:
|
||||||
totals["skipped"] += 1
|
totals["skipped"] += 1
|
||||||
@@ -135,8 +207,8 @@ def send_targeted_reminders(task_id: int, user_ids: list[int], *, now: datetime
|
|||||||
recipient=recipient,
|
recipient=recipient,
|
||||||
event_key=f"targeted-{uuid.uuid4().hex}",
|
event_key=f"targeted-{uuid.uuid4().hex}",
|
||||||
event_type="training_lean_targeted_reminder",
|
event_type="training_lean_targeted_reminder",
|
||||||
title="精益管理培训定向提醒",
|
title=f"精益管理培训定向提醒{title_suffix}",
|
||||||
content="您尚未完成本周精益管理培训,请观看指定视频并提交不少于50字的学习感悟。",
|
content=f"您尚未完成{content_prefix}精益管理培训,请观看指定视频并提交不少于50字的学习感悟。",
|
||||||
current=current,
|
current=current,
|
||||||
)
|
)
|
||||||
totals["created"] += result != "skipped"
|
totals["created"] += result != "skipped"
|
||||||
@@ -148,25 +220,27 @@ def send_targeted_reminders(task_id: int, user_ids: list[int], *, now: datetime
|
|||||||
def notify_overdue_users_after_push(
|
def notify_overdue_users_after_push(
|
||||||
task: LeanTrainingWeeklyTask,
|
task: LeanTrainingWeeklyTask,
|
||||||
*,
|
*,
|
||||||
event_key: str,
|
|
||||||
current: datetime | None = None,
|
current: datetime | None = None,
|
||||||
) -> dict[str, int]:
|
) -> dict[str, int]:
|
||||||
"""
|
"""
|
||||||
视频批次推送成功后,立即对该任务中"已延期"(已过截止时间且未提交感悟)的受训人员发送企微提醒。
|
视频批次推送成功后,立即对该任务中"已延期"(已过截止时间且未提交感悟)的受训人员发送企微提醒。
|
||||||
|
|
||||||
对应周任务消息推送规则:每次推送周任务成功后立马推送延期提醒(与批次 event_key 绑定幂等,同批重推不重复打扰)。
|
对应周任务消息推送规则:每次推送周任务成功后立马推送延期提醒。
|
||||||
|
去重规则(2026-09-30 用户反馈消息太多):与排程扫描共用 overdue-<北京日期> 事件键与
|
||||||
|
"每人每天最多一条自动催办"前置判定——员工当天已收到过任意精益催办(含排程扫描、
|
||||||
|
其它批次延期提醒)时本路径静默跳过,确保同一员工同一自然天只收到一条催办。
|
||||||
|
已过截止超过 OVERDUE_REMINDER_STOP_AFTER_DAYS 天的历史期任务不再发送(历史期补推不再催办旧账)。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
task: 刚完成视频推送的周任务(必须已发布)。
|
task: 刚完成视频推送的周任务(必须已发布)。
|
||||||
event_key: 幂等键,建议携带批次区间(如 overdue-after-push-0-2),与推送批次一一对应。
|
|
||||||
current: 覆盖当前时间(UTC naive,测试用)。
|
current: 覆盖当前时间(UTC naive,测试用)。
|
||||||
Returns:
|
Returns:
|
||||||
{"created", "sent", "skipped", "failed"} 汇总统计。
|
{"created", "sent", "skipped", "failed"} 汇总统计。
|
||||||
"""
|
"""
|
||||||
now = current or utc_now_naive()
|
now = current or utc_now_naive()
|
||||||
totals = {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
|
totals = {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
|
||||||
# 未过截止时间不存在"已延期"人员,直接返回,避免无意义扫描
|
# 未过截止时间不存在"已延期"人员;超宽限期的历史期任务同样跳过,避免对旧账无限催办
|
||||||
if now <= task.due_at:
|
if not _is_overdue_active(task, now):
|
||||||
return totals
|
return totals
|
||||||
completed_user_ids = set(
|
completed_user_ids = set(
|
||||||
db.session.execute(
|
db.session.execute(
|
||||||
@@ -178,14 +252,21 @@ def notify_overdue_users_after_push(
|
|||||||
)
|
)
|
||||||
overdue_ids = target_user_ids_for_task(task) - completed_user_ids
|
overdue_ids = target_user_ids_for_task(task) - completed_user_ids
|
||||||
users = db.session.execute(select(User).where(User.id.in_(overdue_ids), User.status == "active")).scalars().all() if overdue_ids else []
|
users = db.session.execute(select(User).where(User.id.in_(overdue_ids), User.status == "active")).scalars().all() if overdue_ids else []
|
||||||
|
event_key = _overdue_event_key(now)
|
||||||
|
short_label, full_label = _period_labels(task)
|
||||||
|
title_suffix = f"({short_label})" if short_label else ""
|
||||||
|
content_prefix = full_label if full_label else "本周"
|
||||||
for user in users:
|
for user in users:
|
||||||
|
if _has_overdue_reminder_today(user.id, now):
|
||||||
|
totals["skipped"] += 1
|
||||||
|
continue
|
||||||
result = _send_reminder(
|
result = _send_reminder(
|
||||||
task=task,
|
task=task,
|
||||||
recipient=user,
|
recipient=user,
|
||||||
event_key=event_key,
|
event_key=event_key or f"overdue-after-push-{uuid.uuid4().hex}",
|
||||||
event_type="training_lean_overdue",
|
event_type="training_lean_overdue",
|
||||||
title="精益管理培训延期提醒",
|
title=f"精益管理培训延期提醒{title_suffix}",
|
||||||
content="您本周精益管理培训已延期,尚未完成视频观看与学习感悟提交,请尽快完成。",
|
content=f"您{content_prefix}精益管理培训已延期,尚未完成视频观看与学习感悟提交,请尽快完成。",
|
||||||
current=now,
|
current=now,
|
||||||
)
|
)
|
||||||
totals["created"] += result != "skipped"
|
totals["created"] += result != "skipped"
|
||||||
@@ -194,45 +275,65 @@ def notify_overdue_users_after_push(
|
|||||||
return totals
|
return totals
|
||||||
|
|
||||||
|
|
||||||
def _event_key(task: LeanTrainingWeeklyTask, now: datetime) -> str | None:
|
|
||||||
"""按周日截止后的周一、周三、周五计算本轮逾期提醒唯一键。"""
|
|
||||||
if now <= task.due_at:
|
|
||||||
return None
|
|
||||||
local_now = now.replace(tzinfo=timezone.utc).astimezone(resolve_schedule_tzinfo("Asia/Shanghai"))
|
|
||||||
weekday = local_now.weekday()
|
|
||||||
if weekday not in {0, 2, 4}:
|
|
||||||
return None
|
|
||||||
return f"overdue-{local_now.date().isoformat()}"
|
|
||||||
|
|
||||||
|
|
||||||
def run_lean_training_reminders(*, now: datetime | None = None) -> dict[str, int]:
|
def run_lean_training_reminders(*, now: datetime | None = None) -> dict[str, int]:
|
||||||
"""扫描未完成人员并发送本轮提醒,重复运行由唯一约束确保不重复推送。"""
|
"""扫描全部已发布任务,按"每人每天一条"发送合并逾期提醒,重复运行由当天去重与唯一约束兜底。
|
||||||
|
|
||||||
|
合并规则(2026-09-30 用户反馈多期并存时每人收到多条相同催办):周一/周三/周五扫描时,
|
||||||
|
同一员工名下全部可催办期次(已过截止且未超宽限期、本人未完成)合并为一条提醒——单期文案
|
||||||
|
携带该期次标签,多期汇总各期标签并注明期数;卡片跳转定位到其最近一期未完成任务。
|
||||||
|
提醒文案携带期次标签(第N期+周次区间)供员工区分期次,避免完成当期后仍收到历史期
|
||||||
|
相同提醒而被误认为系统误推。
|
||||||
|
"""
|
||||||
current = now or utc_now_naive()
|
current = now or utc_now_naive()
|
||||||
|
event_key = _overdue_event_key(current)
|
||||||
|
if not event_key:
|
||||||
|
return {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
|
||||||
tasks = db.session.execute(select(LeanTrainingWeeklyTask).where(LeanTrainingWeeklyTask.status == "published")).scalars().all()
|
tasks = db.session.execute(select(LeanTrainingWeeklyTask).where(LeanTrainingWeeklyTask.status == "published")).scalars().all()
|
||||||
created = sent = skipped = failed = 0
|
# [STEP 1] 汇总各员工全部可催办期次:已过截止、未超宽限期、本人属于受训对象且未完成
|
||||||
|
pending: dict[int, list[LeanTrainingWeeklyTask]] = {}
|
||||||
for task in tasks:
|
for task in tasks:
|
||||||
event_key = _event_key(task, current)
|
if not _is_overdue_active(task, current):
|
||||||
if not event_key:
|
|
||||||
continue
|
continue
|
||||||
completed_user_ids = set(db.session.execute(select(LeanTrainingCompletion.user_id).where(LeanTrainingCompletion.weekly_task_id == task.id, LeanTrainingCompletion.status == "completed")).scalars())
|
completed_user_ids = set(db.session.execute(select(LeanTrainingCompletion.user_id).where(LeanTrainingCompletion.weekly_task_id == task.id, LeanTrainingCompletion.status == "completed")).scalars())
|
||||||
target_user_ids = target_user_ids_for_task(task)
|
for user_id in sorted(target_user_ids_for_task(task) - completed_user_ids):
|
||||||
users = db.session.execute(select(User).where(User.id.in_(target_user_ids - completed_user_ids))).scalars().all() if target_user_ids else []
|
pending.setdefault(user_id, []).append(task)
|
||||||
for user in users:
|
if not pending:
|
||||||
result = _send_reminder(
|
return {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
|
||||||
task=task,
|
# [STEP 2] 每人仅发一条:按周次倒序取最近一期未完成任务作卡片跳转主任务,多期时汇总各期标签
|
||||||
recipient=user,
|
users = db.session.execute(select(User).where(User.id.in_(list(pending)))).scalars().all()
|
||||||
event_key=event_key,
|
created = sent = skipped = failed = 0
|
||||||
event_type="training_lean_overdue",
|
for user in users:
|
||||||
title="精益管理培训逾期提醒",
|
if _has_overdue_reminder_today(user.id, current):
|
||||||
content="本周精益管理培训尚未完成,请观看指定视频并提交不少于50字的学习感悟。",
|
skipped += 1
|
||||||
current=current,
|
continue
|
||||||
)
|
user_tasks = sorted(pending[user.id], key=lambda item: item.week_key, reverse=True)
|
||||||
created += result != "skipped"
|
primary = user_tasks[0]
|
||||||
if result == "sent":
|
period_labels = [_period_labels(item) for item in reversed(user_tasks)]
|
||||||
sent += 1
|
if len(user_tasks) == 1:
|
||||||
elif result == "failed":
|
short_label, full_label = period_labels[0]
|
||||||
failed += 1
|
title_suffix = f"({short_label})" if short_label else ""
|
||||||
else:
|
content_prefix = full_label if full_label else "本周"
|
||||||
skipped += 1
|
title = f"精益管理培训逾期提醒{title_suffix}"
|
||||||
|
content = f"{content_prefix}精益管理培训尚未完成,请观看指定视频并提交不少于50字的学习感悟。"
|
||||||
|
else:
|
||||||
|
joined_labels = "、".join(full for _, full in period_labels if full)
|
||||||
|
title = f"精益管理培训逾期提醒(共{len(user_tasks)}期未完成)"
|
||||||
|
content = f"您共有{len(user_tasks)}期精益管理培训尚未完成:{joined_labels},请观看指定视频并提交不少于50字的学习感悟。"
|
||||||
|
result = _send_reminder(
|
||||||
|
task=primary,
|
||||||
|
recipient=user,
|
||||||
|
event_key=event_key,
|
||||||
|
event_type="training_lean_overdue",
|
||||||
|
title=title,
|
||||||
|
content=content,
|
||||||
|
current=current,
|
||||||
|
)
|
||||||
|
created += result != "skipped"
|
||||||
|
if result == "sent":
|
||||||
|
sent += 1
|
||||||
|
elif result == "failed":
|
||||||
|
failed += 1
|
||||||
|
else:
|
||||||
|
skipped += 1
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return {"created": created, "sent": sent, "skipped": skipped, "failed": failed}
|
return {"created": created, "sent": sent, "skipped": skipped, "failed": failed}
|
||||||
@@ -3,8 +3,9 @@ backend/app/services/lean_training_service.py
|
|||||||
|
|
||||||
用途:精益管理培训的周任务、员工提交、看板和提醒规则服务。
|
用途:精益管理培训的周任务、员工提交、看板和提醒规则服务。
|
||||||
依赖:TrainingConfig/Resource、精益培训模型、User、统一 ValidationError。
|
依赖:TrainingConfig/Resource、精益培训模型、User、统一 ValidationError。
|
||||||
逻辑:管理端冻结每周视频列表、每周推送数量与受训对象;员工仅对已推送批次提交观看事实与学习感悟;
|
逻辑:管理端冻结每周视频列表、每周推送数量与受训对象;学员端"本期视频"口径为本任务首次推送的
|
||||||
服务端按 50 字门槛判定完成,管理看板只读取已授权范围。
|
视频(已推送前缀扣除其它更早期任务已推送部分,推过的视频不重复展示、不要求重学);
|
||||||
|
员工仅对本期视频提交观看事实与学习感悟,服务端按 50 字门槛判定完成,管理看板只读取已授权范围。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -267,15 +268,21 @@ def is_task_targeted_to_user(task: LeanTrainingWeeklyTask, user: User) -> bool:
|
|||||||
return user.status == "active" and (user.id in set(task.target_user_ids or []) or user.role in set(task.target_roles or []))
|
return user.status == "active" and (user.id in set(task.target_user_ids or []) or user.role in set(task.target_roles or []))
|
||||||
|
|
||||||
|
|
||||||
def serialize_weekly_task(task: LeanTrainingWeeklyTask, *, learner_view: bool = False) -> dict[str, Any]:
|
def serialize_weekly_task(task: LeanTrainingWeeklyTask, *, learner_view: bool = False, own_pushed_ids: list[int] | None = None) -> dict[str, Any]:
|
||||||
"""序列化精益周任务;员工端视图仅含已推送视频前缀(游标内),管理端返回全量选择列表。
|
"""
|
||||||
|
序列化精益周任务;管理端返回全量选择列表,学员端视图仅含本任务首次推送的视频(本期视频)。
|
||||||
|
|
||||||
videos 每项附带 file_url(MinIO 公开地址),供学员端视频缩略图与点击播放使用。
|
videos 每项附带 file_url(MinIO 公开地址),供学员端视频缩略图与点击播放使用。
|
||||||
附带 week_index(第 N 期)与 week_end(周日),供前后端拼装"第N周 MM-DD至MM-DD"周次标签。
|
附带 week_index(第 N 期)与 week_end(周日),供前后端拼装"第N周 MM-DD至MM-DD"周次标签。
|
||||||
|
Args:
|
||||||
|
own_pushed_ids: 调用方已批量算好的本任务首推视频列表(如列表页一次归一遍历);
|
||||||
|
缺省时内部单任务计算,避免调用方重复查询。
|
||||||
"""
|
"""
|
||||||
visible_ids = list(task.video_resource_ids or [])
|
visible_ids = list(task.video_resource_ids or [])
|
||||||
if learner_view:
|
if learner_view:
|
||||||
visible_ids = visible_ids[: task.pushed_video_count]
|
# [RULE] 学员端"本期视频"不含其它更早期任务已推送的视频:自动滚动复制上一期冻结列表时,
|
||||||
|
# 上一期已推送视频不再重复展示、也不要求重学(推过的视频不能重复再推)
|
||||||
|
visible_ids = own_pushed_ids if own_pushed_ids is not None else _own_pushed_video_ids(task)
|
||||||
resources = db.session.execute(
|
resources = db.session.execute(
|
||||||
select(TrainingConfigResource).where(TrainingConfigResource.id.in_(visible_ids))
|
select(TrainingConfigResource).where(TrainingConfigResource.id.in_(visible_ids))
|
||||||
).scalars().all()
|
).scalars().all()
|
||||||
@@ -327,6 +334,46 @@ def _already_pushed_resource_ids(*, exclude_task_id: int | None = None) -> set[i
|
|||||||
return pushed
|
return pushed
|
||||||
|
|
||||||
|
|
||||||
|
def _first_pushed_video_ids_map() -> dict[int, list[int]]:
|
||||||
|
"""
|
||||||
|
一次性计算全部已发布周任务的"本任务首次推送视频"归属映射。
|
||||||
|
|
||||||
|
用途:修复自动滚动把上一期冻结列表原样复制进新一期后,学员端按累积前缀(video_resource_ids[:pushed_video_count])
|
||||||
|
展示与考核,导致上一期已推送视频在第2期重复出现、并要求员工重看重写感悟的问题
|
||||||
|
(对应"前面任务中推送过的视频不能重复再推"规则,2026-09-29 方案 A)。
|
||||||
|
核心逻辑:按周次升序(同期唯一)遍历已发布任务,维护"此前已被推送过"的全局集合;
|
||||||
|
各任务已推送前缀中首次出现的视频归属本任务,与更早期任务重复的视频不属于本任务(本期无需重学)。
|
||||||
|
Returns:
|
||||||
|
{task_id: 本任务首次推送的视频资源 ID 顺序列表(保持冻结列表内的相对顺序)}。
|
||||||
|
"""
|
||||||
|
tasks = db.session.execute(
|
||||||
|
select(LeanTrainingWeeklyTask)
|
||||||
|
.where(LeanTrainingWeeklyTask.status == "published")
|
||||||
|
.order_by(LeanTrainingWeeklyTask.week_key, LeanTrainingWeeklyTask.id)
|
||||||
|
).scalars().all()
|
||||||
|
seen: set[int] = set()
|
||||||
|
ownership: dict[int, list[int]] = {}
|
||||||
|
for task in tasks:
|
||||||
|
prefix_ids = [int(resource_id) for resource_id in list(task.video_resource_ids or [])[: task.pushed_video_count]]
|
||||||
|
ownership[task.id] = [resource_id for resource_id in prefix_ids if resource_id not in seen]
|
||||||
|
seen.update(prefix_ids)
|
||||||
|
return ownership
|
||||||
|
|
||||||
|
|
||||||
|
def _own_pushed_video_ids(task: LeanTrainingWeeklyTask) -> list[int]:
|
||||||
|
"""
|
||||||
|
返回指定任务的"本期视频":已推送前缀中本任务首次推送(此前其它任务未推送过)的部分。
|
||||||
|
|
||||||
|
用途:学员端展示、观看/完成校验、管理看板视频列统一按此口径取"本周期实际布置的视频",
|
||||||
|
保证自动滚动复制上一期列表后,上一期已推送视频不再重复出现在新一期。
|
||||||
|
Args:
|
||||||
|
task: 精益周任务。
|
||||||
|
Returns:
|
||||||
|
本任务首次推送的视频资源 ID 顺序列表。
|
||||||
|
"""
|
||||||
|
return _first_pushed_video_ids_map().get(task.id, [])
|
||||||
|
|
||||||
|
|
||||||
def _inherited_pushed_video_count(video_ids: list[int]) -> int:
|
def _inherited_pushed_video_count(video_ids: list[int]) -> int:
|
||||||
"""
|
"""
|
||||||
计算手动新建周任务应继承的推送游标:新视频列表的"最长已推送前缀"长度。
|
计算手动新建周任务应继承的推送游标:新视频列表的"最长已推送前缀"长度。
|
||||||
@@ -436,7 +483,7 @@ def list_my_weekly_tasks(user: User) -> list[dict[str, Any]]:
|
|||||||
"""
|
"""
|
||||||
返回当前员工被指派的全部已发布精益周任务(按周期倒序,最新在最上),供员工端时间树展示。
|
返回当前员工被指派的全部已发布精益周任务(按周期倒序,最新在最上),供员工端时间树展示。
|
||||||
|
|
||||||
每项为学员视角序列化(仅已推送视频前缀),并附加:
|
每项为学员视角序列化(仅本任务首次推送的视频),并附加:
|
||||||
- task_status: completed=已完成感悟提交(completed_at 非空);overdue=未完成且已过截止时间;in_progress=未完成且未到截止;
|
- task_status: completed=已完成感悟提交(completed_at 非空);overdue=未完成且已过截止时间;in_progress=未完成且未到截止;
|
||||||
- completion: 观看草稿(仅记录了视频观看、感悟未提交)或完成记录的总结/观看时间/完成时间摘要,两者均无时为 None。
|
- completion: 观看草稿(仅记录了视频观看、感悟未提交)或完成记录的总结/观看时间/完成时间摘要,两者均无时为 None。
|
||||||
"""
|
"""
|
||||||
@@ -446,6 +493,8 @@ def list_my_weekly_tasks(user: User) -> list[dict[str, Any]]:
|
|||||||
targeted = [item for item in tasks if is_task_targeted_to_user(item, user)]
|
targeted = [item for item in tasks if is_task_targeted_to_user(item, user)]
|
||||||
if not targeted:
|
if not targeted:
|
||||||
return []
|
return []
|
||||||
|
# [STEP] 一次遍历算出各任务首推视频归属,列表页逐任务序列化复用,避免 N 个任务各查一遍全表
|
||||||
|
own_pushed_map = _first_pushed_video_ids_map()
|
||||||
completions = {
|
completions = {
|
||||||
item.weekly_task_id: item
|
item.weekly_task_id: item
|
||||||
for item in db.session.execute(
|
for item in db.session.execute(
|
||||||
@@ -459,7 +508,7 @@ def list_my_weekly_tasks(user: User) -> list[dict[str, Any]]:
|
|||||||
items: list[dict[str, Any]] = []
|
items: list[dict[str, Any]] = []
|
||||||
for task in targeted:
|
for task in targeted:
|
||||||
completion = completions.get(task.id)
|
completion = completions.get(task.id)
|
||||||
item = serialize_weekly_task(task, learner_view=True)
|
item = serialize_weekly_task(task, learner_view=True, own_pushed_ids=own_pushed_map.get(task.id, []))
|
||||||
# 只有感悟提交完成(completed_at 非空)才算"已完成";仅有观看草稿时仍按截止时间判定进行中/已延期
|
# 只有感悟提交完成(completed_at 非空)才算"已完成";仅有观看草稿时仍按截止时间判定进行中/已延期
|
||||||
item["task_status"] = "completed" if completion and completion.completed_at else ("overdue" if now > task.due_at else "in_progress")
|
item["task_status"] = "completed" if completion and completion.completed_at else ("overdue" if now > task.due_at else "in_progress")
|
||||||
item["completion"] = {
|
item["completion"] = {
|
||||||
@@ -478,19 +527,19 @@ def mark_video_watched(user: User, data: dict[str, Any]) -> dict[str, Any]:
|
|||||||
|
|
||||||
Args:
|
Args:
|
||||||
user: 当前登录员工。
|
user: 当前登录员工。
|
||||||
data: 需包含 weekly_task_id 与 resource_id;resource_id 必须属于该任务已推送的前缀视频。
|
data: 需包含 weekly_task_id 与 resource_id;resource_id 必须属于本任务首次推送(本期要求学习)的视频。
|
||||||
Returns:
|
Returns:
|
||||||
{"watched_at": {resource_id: 观看时间iso字符串}},该任务当前的全部观看记录。
|
{"watched_at": {resource_id: 观看时间iso字符串}},该任务当前的全部观看记录。
|
||||||
Raises:
|
Raises:
|
||||||
NotFoundError: 任务不存在、未发布、未指派给该员工或视频不在已推送范围。
|
NotFoundError: 任务不存在、未发布、未指派给该员工或视频不属于本期学习范围。
|
||||||
"""
|
"""
|
||||||
task_id = int(data.get("weekly_task_id") or 0)
|
task_id = int(data.get("weekly_task_id") or 0)
|
||||||
resource_id = int(data.get("resource_id") or 0)
|
resource_id = int(data.get("resource_id") or 0)
|
||||||
task = db.session.get(LeanTrainingWeeklyTask, task_id)
|
task = db.session.get(LeanTrainingWeeklyTask, task_id)
|
||||||
if not task or task.status != "published" or not is_task_targeted_to_user(task, user):
|
if not task or task.status != "published" or not is_task_targeted_to_user(task, user):
|
||||||
raise NotFoundError("Lean training weekly task not found")
|
raise NotFoundError("Lean training weekly task not found")
|
||||||
# 员工只能记录已推送前缀视频的观看,防止越权观看未发布视频
|
# 员工只能记录本期视频的观看:其它更早期任务已推送的视频不属于本周期学习范围,防止越权观看未布置内容
|
||||||
if resource_id not in list(task.video_resource_ids or [])[: task.pushed_video_count]:
|
if resource_id not in _own_pushed_video_ids(task):
|
||||||
raise NotFoundError("Video resource not in pushed scope")
|
raise NotFoundError("Video resource not in pushed scope")
|
||||||
completion = db.session.execute(
|
completion = db.session.execute(
|
||||||
select(LeanTrainingCompletion).where(LeanTrainingCompletion.weekly_task_id == task.id, LeanTrainingCompletion.user_id == user.id)
|
select(LeanTrainingCompletion).where(LeanTrainingCompletion.weekly_task_id == task.id, LeanTrainingCompletion.user_id == user.id)
|
||||||
@@ -514,8 +563,9 @@ def save_completion(user: User, data: dict[str, Any]) -> dict[str, Any]:
|
|||||||
raise NotFoundError("Lean training weekly task not found")
|
raise NotFoundError("Lean training weekly task not found")
|
||||||
if not is_task_targeted_to_user(task, user):
|
if not is_task_targeted_to_user(task, user):
|
||||||
raise NotFoundError("Lean training weekly task not found")
|
raise NotFoundError("Lean training weekly task not found")
|
||||||
# 员工只能观看已推送的前缀视频,完成校验同样基于已推送范围而非全量选择列表
|
# 员工只能观看本期视频,完成校验同样只考核本任务首次推送的视频:
|
||||||
required_ids = list(task.video_resource_ids or [])[: task.pushed_video_count]
|
# 自动滚动复制的上一期已推送视频不要求重学,防止重复学习(推过的视频不能重复再推)
|
||||||
|
required_ids = _own_pushed_video_ids(task)
|
||||||
# 观看记录以服务端持久化为准(mark_video_watched 已逐个保存),客户端仅作回显兜底,防止伪造观看
|
# 观看记录以服务端持久化为准(mark_video_watched 已逐个保存),客户端仅作回显兜底,防止伪造观看
|
||||||
# 兜底值入库前归一为 UTC:客户端可能提交北京时间(+08:00)或 UTC(Z)格式,存储一律 UTC
|
# 兜底值入库前归一为 UTC:客户端可能提交北京时间(+08:00)或 UTC(Z)格式,存储一律 UTC
|
||||||
watched = {str(key): parse_client_iso_to_utc_text(value) for key, value in (data.get("watched_at") or {}).items()}
|
watched = {str(key): parse_client_iso_to_utc_text(value) for key, value in (data.get("watched_at") or {}).items()}
|
||||||
@@ -539,28 +589,29 @@ def save_completion(user: User, data: dict[str, Any]) -> dict[str, Any]:
|
|||||||
return serialize_completion(completion, task, user)
|
return serialize_completion(completion, task, user)
|
||||||
|
|
||||||
|
|
||||||
def _task_video_rows(task: LeanTrainingWeeklyTask, completion: LeanTrainingCompletion | None) -> list[dict[str, Any]]:
|
def _task_video_rows(task: LeanTrainingWeeklyTask, completion: LeanTrainingCompletion | None, own_video_ids: list[int] | None = None) -> list[dict[str, Any]]:
|
||||||
"""
|
"""
|
||||||
生成看板行的视频明细:仅展示本周期内已推送、要求员工学习的视频(推送游标前缀),与学员端可见范围一致。
|
生成看板行的视频明细:仅展示本周期内布置、要求员工学习的视频(本任务首次推送部分),与学员端可见范围一致。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
task: 当前周任务,视频顺序按管理端冻结时的选择顺序展示(截断到推送游标)。
|
task: 当前周任务,视频顺序按冻结列表内的相对顺序展示。
|
||||||
completion: 该员工的完成记录;从未观看(无完成记录)时传 None,仅返回视频名称清单(观看时间为 None)。
|
completion: 该员工的完成记录;从未观看(无完成记录)时传 None,仅返回视频名称清单(观看时间为 None)。
|
||||||
|
own_video_ids: 调用方已批量算好的本任务首推视频列表(看板逐行透传,避免每行重算);缺省时内部单任务计算。
|
||||||
Returns:
|
Returns:
|
||||||
[{"name": 视频名, "watched_at": 观看时间iso或None}];尚未推送任何视频(游标为 0)时返回空列表,前端展示 "--"。
|
[{"name": 视频名, "watched_at": 观看时间iso或None}];本任务无首推视频(游标为 0 或前缀全为历史视频)时返回空列表,前端展示 "--"。
|
||||||
"""
|
"""
|
||||||
titles = {resource.id: resource.title or (resource.agent_guide.file_name if resource.agent_guide else "") for resource in task.config.resources}
|
titles = {resource.id: resource.title or (resource.agent_guide.file_name if resource.agent_guide else "") for resource in task.config.resources}
|
||||||
watched = dict(completion.watched_at_json or {}) if completion else {}
|
watched = dict(completion.watched_at_json or {}) if completion else {}
|
||||||
# [RULE] 看板视频列只展示已推送前缀(video_resource_ids[:pushed_video_count]):未推送视频不属于本周期学习范围,避免名单出现从未布置过的视频
|
# [RULE] 看板视频列只展示本期布置的视频(本任务首推部分):上一期已推送的视频不属于本周期学习范围,避免要求重学
|
||||||
visible_ids = task.video_resource_ids[: task.pushed_video_count]
|
visible_ids = own_video_ids if own_video_ids is not None else _own_pushed_video_ids(task)
|
||||||
return [
|
return [
|
||||||
{"name": titles.get(resource_id, ""), "watched_at": format_beijing_iso(watched.get(str(resource_id)))}
|
{"name": titles.get(resource_id, ""), "watched_at": format_beijing_iso(watched.get(str(resource_id)))}
|
||||||
for resource_id in visible_ids
|
for resource_id in visible_ids
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
def serialize_completion(completion: LeanTrainingCompletion, task: LeanTrainingWeeklyTask, user: User) -> dict[str, Any]:
|
def serialize_completion(completion: LeanTrainingCompletion, task: LeanTrainingWeeklyTask, user: User, own_video_ids: list[int] | None = None) -> dict[str, Any]:
|
||||||
"""组合看板所需人员、视频观看、总结和完成状态字段。"""
|
"""组合看板所需人员、视频观看、总结和完成状态字段;own_video_ids 供看板批量透传本期视频口径。"""
|
||||||
# 状态三态归一:已提交感悟为 completed;未完成时按截止时间区分进行中/已延期,管理端状态列直接展示中文
|
# 状态三态归一:已提交感悟为 completed;未完成时按截止时间区分进行中/已延期,管理端状态列直接展示中文
|
||||||
if completion.status == "completed":
|
if completion.status == "completed":
|
||||||
status = "completed"
|
status = "completed"
|
||||||
@@ -572,7 +623,7 @@ def serialize_completion(completion: LeanTrainingCompletion, task: LeanTrainingW
|
|||||||
"employee_id": user.employee_id,
|
"employee_id": user.employee_id,
|
||||||
"name": user.real_name or user.username,
|
"name": user.real_name or user.username,
|
||||||
"department": user.department,
|
"department": user.department,
|
||||||
"videos": _task_video_rows(task, completion),
|
"videos": _task_video_rows(task, completion, own_video_ids=own_video_ids),
|
||||||
"summary_text": completion.summary_text,
|
"summary_text": completion.summary_text,
|
||||||
"status": status,
|
"status": status,
|
||||||
"completed_at": format_beijing_iso(completion.completed_at),
|
"completed_at": format_beijing_iso(completion.completed_at),
|
||||||
@@ -595,12 +646,14 @@ def list_dashboard(task_id: int | None) -> dict[str, Any]:
|
|||||||
target_user_ids = target_user_ids_for_task(task)
|
target_user_ids = target_user_ids_for_task(task)
|
||||||
users = db.session.execute(select(User).where(User.id.in_(target_user_ids)).order_by(User.department, User.employee_id)).scalars().all() if target_user_ids else []
|
users = db.session.execute(select(User).where(User.id.in_(target_user_ids)).order_by(User.department, User.employee_id)).scalars().all() if target_user_ids else []
|
||||||
completions = {item.user_id: item for item in db.session.execute(select(LeanTrainingCompletion).where(LeanTrainingCompletion.weekly_task_id == task.id)).scalars().all()}
|
completions = {item.user_id: item for item in db.session.execute(select(LeanTrainingCompletion).where(LeanTrainingCompletion.weekly_task_id == task.id)).scalars().all()}
|
||||||
|
# [STEP] 本期视频口径一次算好逐行透传:看板按人逐行输出,避免每行重算首推归属
|
||||||
|
own_video_ids = _own_pushed_video_ids(task)
|
||||||
completed: list[dict[str, Any]] = []
|
completed: list[dict[str, Any]] = []
|
||||||
incomplete: list[dict[str, Any]] = []
|
incomplete: list[dict[str, Any]] = []
|
||||||
for user in users:
|
for user in users:
|
||||||
item = completions.get(user.id)
|
item = completions.get(user.id)
|
||||||
# 无完成记录的指派对象同样三态归一:截止前进行中、截止后已延期;视频列全员一致(仅已推送前缀),仅观看时间为空
|
# 无完成记录的指派对象同样三态归一:截止前进行中、截止后已延期;视频列全员一致(仅本期布置视频),仅观看时间为空
|
||||||
row = serialize_completion(item, task, user) if item else {"user_id": user.id, "employee_id": user.employee_id, "name": user.real_name or user.username, "department": user.department, "videos": _task_video_rows(task, None), "summary_text": None, "status": "overdue" if utc_now_naive() > task.due_at else "in_progress", "completed_at": None}
|
row = serialize_completion(item, task, user, own_video_ids=own_video_ids) if item else {"user_id": user.id, "employee_id": user.employee_id, "name": user.real_name or user.username, "department": user.department, "videos": _task_video_rows(task, None, own_video_ids=own_video_ids), "summary_text": None, "status": "overdue" if utc_now_naive() > task.due_at else "in_progress", "completed_at": None}
|
||||||
(completed if row["status"] == "completed" else incomplete).append(row)
|
(completed if row["status"] == "completed" else incomplete).append(row)
|
||||||
return {"task": serialize_weekly_task(task), "completed": completed, "incomplete": incomplete, "periods": periods}
|
return {"task": serialize_weekly_task(task), "completed": completed, "incomplete": incomplete, "periods": periods}
|
||||||
|
|
||||||
|
|||||||
@@ -12,8 +12,10 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
|
from io import BytesIO
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
from openpyxl import Workbook
|
||||||
from sqlalchemy import Select, func, or_, select
|
from sqlalchemy import Select, func, or_, select
|
||||||
|
|
||||||
from app.extensions import db
|
from app.extensions import db
|
||||||
@@ -30,6 +32,18 @@ STATUS_FILTER_VALUES = {"replied", "not_fully_replied"}
|
|||||||
DEFAULT_PAGE_SIZE = 50
|
DEFAULT_PAGE_SIZE = 50
|
||||||
MAX_PAGE_SIZE = 200
|
MAX_PAGE_SIZE = 200
|
||||||
|
|
||||||
|
# 导出兜底上限:防止极端筛选全量导出失控(当前数据量 ~1k 行,远低于该值)。
|
||||||
|
EXPORT_MAX_ROWS = 10000
|
||||||
|
|
||||||
|
# 导出表头(与工作台列顺序一致,交期回复批次合并为单列)。
|
||||||
|
EXPORT_HEADERS = [
|
||||||
|
"客户编号", "客户简称", "订单日期", "订单单号", "项次", "产品编号", "品名",
|
||||||
|
"客户产品编号", "数量", "约定交货日", "交期回复状态", "交期回复批次",
|
||||||
|
"业务员", "部门", "客户订单", "规格", "单位", "通知时间",
|
||||||
|
]
|
||||||
|
|
||||||
|
STATUS_EXPORT_LABELS = {"not_replied": "未回复", "partial_replied": "部分回复", "replied": "已回复"}
|
||||||
|
|
||||||
|
|
||||||
def _utc_to_shanghai(value) -> str | None:
|
def _utc_to_shanghai(value) -> str | None:
|
||||||
"""naive-UTC 时间转北京时间展示串;仅用于序列化,详情见 api 层同名 helper 注释。"""
|
"""naive-UTC 时间转北京时间展示串;仅用于序列化,详情见 api 层同名 helper 注释。"""
|
||||||
@@ -278,6 +292,82 @@ def list_lines(params: dict[str, Any]) -> dict[str, Any]:
|
|||||||
return {"items": items, "page": page, "page_size": page_size, "total": total or 0}
|
return {"items": items, "page": page, "page_size": page_size, "total": total or 0}
|
||||||
|
|
||||||
|
|
||||||
|
def export_lines(params: dict[str, Any]) -> bytes:
|
||||||
|
"""
|
||||||
|
导出当前筛选下的全部订单行(xlsx 字节流)。
|
||||||
|
|
||||||
|
用途与触发时机:GET /api/order-delivery-reply/lines/export;工作台「导出 Excel」按钮。
|
||||||
|
|
||||||
|
核心逻辑:[STEP 1] 与 list_lines 同一筛选与默认排序,不分页(EXPORT_MAX_ROWS 兜底防失控);
|
||||||
|
[STEP 2] 批量预取批次与锁定状态后序列化;
|
||||||
|
[STEP 3] openpyxl 生成单工作表(中文表头同工作台列顺序,批次合并为「交期·数量」分号串,
|
||||||
|
行状态转中文)。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
params: keyword / order_date / status(与列表筛选一致)。
|
||||||
|
Returns:
|
||||||
|
xlsx 文件字节流。
|
||||||
|
"""
|
||||||
|
stmt = _apply_filters(_base_query(), params).order_by(
|
||||||
|
OrderDeliveryErpLine.order_date.asc(),
|
||||||
|
OrderDeliveryErpLine.customer_no.asc(),
|
||||||
|
OrderDeliveryErpLine.order_no.asc(),
|
||||||
|
OrderDeliveryErpLine.line_no.asc(),
|
||||||
|
OrderDeliveryErpLine.part_no.asc(),
|
||||||
|
).limit(EXPORT_MAX_ROWS)
|
||||||
|
|
||||||
|
lines = list(db.session.scalars(stmt).all())
|
||||||
|
line_ids = [line.id for line in lines]
|
||||||
|
|
||||||
|
batches_by_line: dict[int, list[OrderDeliveryBatch]] = {}
|
||||||
|
states_by_line: dict[int, OrderDeliveryLineState] = {}
|
||||||
|
if line_ids:
|
||||||
|
for batch in db.session.scalars(
|
||||||
|
select(OrderDeliveryBatch)
|
||||||
|
.where(OrderDeliveryBatch.line_id.in_(line_ids))
|
||||||
|
.order_by(OrderDeliveryBatch.line_id, OrderDeliveryBatch.seq)
|
||||||
|
).all():
|
||||||
|
batches_by_line.setdefault(batch.line_id, []).append(batch)
|
||||||
|
for state in db.session.scalars(
|
||||||
|
select(OrderDeliveryLineState).where(OrderDeliveryLineState.line_id.in_(line_ids))
|
||||||
|
).all():
|
||||||
|
states_by_line[state.line_id] = state
|
||||||
|
|
||||||
|
workbook = Workbook()
|
||||||
|
sheet = workbook.active
|
||||||
|
sheet.title = "订单交期回复"
|
||||||
|
sheet.append(EXPORT_HEADERS)
|
||||||
|
for line in lines:
|
||||||
|
item = _serialize_line(line, batches_by_line.get(line.id, []), states_by_line.get(line.id))
|
||||||
|
batch_text = ";".join(
|
||||||
|
f"{batch['planned_date']}·{batch['qty']}" for batch in item["batches"] if batch["planned_date"]
|
||||||
|
)
|
||||||
|
sheet.append([
|
||||||
|
item["customer_no"] or "",
|
||||||
|
item["customer_short_name"] or "",
|
||||||
|
item["order_date"] or "",
|
||||||
|
item["order_no"] or "",
|
||||||
|
item["line_no"],
|
||||||
|
item["part_no"] or "",
|
||||||
|
item["part_name"] or "",
|
||||||
|
item["customer_part_no"] or "",
|
||||||
|
item["qty"] or "",
|
||||||
|
item["agreed_date"] or "",
|
||||||
|
STATUS_EXPORT_LABELS.get(item["status"], item["status"]),
|
||||||
|
batch_text,
|
||||||
|
item["salesperson_name"] or item["salesperson_code"] or "",
|
||||||
|
item["dept_name"] or item["dept_code"] or "",
|
||||||
|
item["customer_po"] or "",
|
||||||
|
item["spec"] or "",
|
||||||
|
item["unit"] or "",
|
||||||
|
item["notified_at"] or "",
|
||||||
|
])
|
||||||
|
|
||||||
|
buffer = BytesIO()
|
||||||
|
workbook.save(buffer)
|
||||||
|
return buffer.getvalue()
|
||||||
|
|
||||||
|
|
||||||
def get_line(order_no: str, line_no: int) -> dict[str, Any] | None:
|
def get_line(order_no: str, line_no: int) -> dict[str, Any] | None:
|
||||||
"""
|
"""
|
||||||
单行详情:快照 + 批次 + 锁定状态 + 该行审计事件。
|
单行详情:快照 + 批次 + 锁定状态 + 该行审计事件。
|
||||||
|
|||||||
@@ -11,6 +11,11 @@ backend/app/services/order_delivery_reply/sql.py
|
|||||||
# 基础 SELECT:不带分页/排序,同步服务按 oea01 keyset 分页时在外层包装。
|
# 基础 SELECT:不带分页/排序,同步服务按 oea01 keyset 分页时在外层包装。
|
||||||
# 关联:oea01=oeb01;oeb04=ima01 且 oeb06=ima02;oea03=occ01;oea14=gen01;oea15=gem01。
|
# 关联:oea01=oeb01;oeb04=ima01 且 oeb06=ima02;oea03=occ01;oea14=gen01;oea15=gem01。
|
||||||
# 别名与 docs/features/order-delivery-reply/technical-design.md §3.5 标准 SELECT 逐列一致。
|
# 别名与 docs/features/order-delivery-reply/technical-design.md §3.5 标准 SELECT 逐列一致。
|
||||||
|
# 可选起始日下界(2026-10-09 增补):正式环境经 ORDER_DELIVERY_SYNC_DATE_FROM 注入边界值
|
||||||
|
# (绑定为 date,oea02 为 Oracle DATE 列),只同步订单日期 ≥ 边界的订单行;
|
||||||
|
# 未配置边界时服务层不拼接此子句,SQL 本体保持全量口径不变。仅只读 SELECT 约束同上。
|
||||||
|
ORDER_DELIVERY_DATE_FROM_CLAUSE = "AND a.oea02 >= :order_date_from"
|
||||||
|
|
||||||
ORDER_DELIVERY_SQL = """
|
ORDER_DELIVERY_SQL = """
|
||||||
SELECT
|
SELECT
|
||||||
a.oea01 AS order_no,
|
a.oea01 AS order_no,
|
||||||
|
|||||||
@@ -7,6 +7,9 @@ backend/app/services/order_delivery_reply/sync_service.py
|
|||||||
逻辑:按 oea01 keyset 分页拉取合格订单行 → 对 (order_no, line_no) 做 upsert 且只更新 ERP 列白名单
|
逻辑:按 oea01 keyset 分页拉取合格订单行 → 对 (order_no, line_no) 做 upsert 且只更新 ERP 列白名单
|
||||||
(绝不覆盖批次/锁定)→ 本轮未命中的本地行置 erp_missing=true(不删除)→ 写 sync_runs。
|
(绝不覆盖批次/锁定)→ 本轮未命中的本地行置 erp_missing=true(不删除)→ 写 sync_runs。
|
||||||
全程模块级锁保证同时只有一个同步;失败保留上次快照并记录错误。
|
全程模块级锁保证同时只有一个同步;失败保留上次快照并记录错误。
|
||||||
|
可选起始日下界(2026-10-09):ORDER_DELIVERY_SYNC_DATE_FROM(YYYY-MM-DD,仅正式环境配置)——
|
||||||
|
只同步订单日期 ≥ 边界的订单行(早于边界的历史行随 erp_missing 语义自动移出工作台);
|
||||||
|
未配置 = 全量同步(dev/test 现状);配置非法格式 fail-closed 拒绝同步。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -14,7 +17,7 @@ from __future__ import annotations
|
|||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import threading
|
import threading
|
||||||
from datetime import datetime
|
from datetime import date, datetime
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from sqlalchemy import select, update
|
from sqlalchemy import select, update
|
||||||
@@ -25,10 +28,35 @@ from app.models.order_delivery_reply import (
|
|||||||
OrderDeliveryErpLine,
|
OrderDeliveryErpLine,
|
||||||
OrderDeliverySyncRun,
|
OrderDeliverySyncRun,
|
||||||
)
|
)
|
||||||
from app.services.order_delivery_reply.sql import ORDER_DELIVERY_SQL
|
from app.services.order_delivery_reply.sql import ORDER_DELIVERY_DATE_FROM_CLAUSE, ORDER_DELIVERY_SQL
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_sync_date_from() -> date | None:
|
||||||
|
"""
|
||||||
|
解析同步起始日下界(环境变量 ORDER_DELIVERY_SYNC_DATE_FROM,YYYY-MM-DD,可选)。
|
||||||
|
|
||||||
|
用途与触发时机:run_sync 每轮同步开始时调用;正式环境配置上线日起只同步
|
||||||
|
订单日期 ≥ 边界的订单行,dev/test 不配置保持全量(需求 2026-10-09)。
|
||||||
|
|
||||||
|
约束:配置了但格式非法时 fail-closed 抛 ValueError 拒绝本轮同步——
|
||||||
|
绝不允许静默回退全量把历史数据抓进正式库。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
边界日期(含当日);未配置返回 None。
|
||||||
|
"""
|
||||||
|
raw = (os.getenv("ORDER_DELIVERY_SYNC_DATE_FROM") or "").strip()
|
||||||
|
if not raw:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return datetime.strptime(raw, "%Y-%m-%d").date()
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ValueError(
|
||||||
|
f"ORDER_DELIVERY_SYNC_DATE_FROM 格式错误(应为 YYYY-MM-DD):{raw!r};"
|
||||||
|
"已拒绝执行同步以防止误抓边界外的历史数据"
|
||||||
|
) from exc
|
||||||
|
|
||||||
# 同步 upsert 只允许更新这些 ERP 快照列;触碰批次/锁定列会覆盖业务回复,禁止扩充业务列进来。
|
# 同步 upsert 只允许更新这些 ERP 快照列;触碰批次/锁定列会覆盖业务回复,禁止扩充业务列进来。
|
||||||
ERP_LINE_COLUMNS = (
|
ERP_LINE_COLUMNS = (
|
||||||
"order_date",
|
"order_date",
|
||||||
@@ -147,27 +175,40 @@ class OrderDeliverySyncService:
|
|||||||
return oracledb.connect(user=user, password=password, dsn=dsn)
|
return oracledb.connect(user=user, password=password, dsn=dsn)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _fetch_page(cls, cursor, last_order_no: str | None) -> list[dict[str, Any]]:
|
def _fetch_page(
|
||||||
|
cls,
|
||||||
|
cursor,
|
||||||
|
last_order_no: str | None,
|
||||||
|
date_from: date | None = None,
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
"""
|
"""
|
||||||
按 oea01 keyset 分页拉取一页订单行。
|
按 oea01 keyset 分页拉取一页订单行。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
cursor: oracledb 游标。
|
cursor: oracledb 游标。
|
||||||
last_order_no: 上一页最后一条订单单号;None 表示从头发起。
|
last_order_no: 上一页最后一条订单单号;None 表示从头发起。
|
||||||
|
date_from: 起始日下界(含);None 表示不过滤。条件拼在内层视图
|
||||||
|
(ROWNUM 之前)——若加在外层会先截断再过滤造成每页缺行漏单。
|
||||||
Returns:
|
Returns:
|
||||||
本页行字典列表(列为 sql.ORDER_DELIVERY_SQL 的别名)。
|
本页行字典列表(列为 sql.ORDER_DELIVERY_SQL 的别名)。
|
||||||
"""
|
"""
|
||||||
# Oracle 空串即 NULL:首页不能带 `order_no > ''`(与 NULL 比较恒 UNKNOWN 会滤掉全部行),
|
# Oracle 空串即 NULL:首页不能带 `order_no > ''`(与 NULL 比较恒 UNKNOWN 会滤掉全部行),
|
||||||
# 因此首页与续页使用两个 SQL 变体。
|
# 因此首页与续页使用两个 SQL 变体。
|
||||||
|
binds: dict[str, Any] = {}
|
||||||
|
date_clause = ""
|
||||||
|
if date_from is not None:
|
||||||
|
date_clause = f" {ORDER_DELIVERY_DATE_FROM_CLAUSE}"
|
||||||
|
binds["order_date_from"] = date_from
|
||||||
if last_order_no:
|
if last_order_no:
|
||||||
page_sql = (
|
page_sql = (
|
||||||
f"SELECT * FROM ({ORDER_DELIVERY_SQL} ORDER BY a.oea01) "
|
f"SELECT * FROM ({ORDER_DELIVERY_SQL}{date_clause} ORDER BY a.oea01) "
|
||||||
f"WHERE order_no > :last_order_no AND ROWNUM <= {_FETCH_SIZE}"
|
f"WHERE order_no > :last_order_no AND ROWNUM <= {_FETCH_SIZE}"
|
||||||
)
|
)
|
||||||
cursor.execute(page_sql, last_order_no=last_order_no)
|
binds["last_order_no"] = last_order_no
|
||||||
|
cursor.execute(page_sql, binds)
|
||||||
else:
|
else:
|
||||||
page_sql = f"SELECT * FROM ({ORDER_DELIVERY_SQL} ORDER BY a.oea01) WHERE ROWNUM <= {_FETCH_SIZE}"
|
page_sql = f"SELECT * FROM ({ORDER_DELIVERY_SQL}{date_clause} ORDER BY a.oea01) WHERE ROWNUM <= {_FETCH_SIZE}"
|
||||||
cursor.execute(page_sql)
|
cursor.execute(page_sql, binds)
|
||||||
columns = [col[0].lower() for col in cursor.description]
|
columns = [col[0].lower() for col in cursor.description]
|
||||||
return [dict(zip(columns, row)) for row in cursor.fetchall()]
|
return [dict(zip(columns, row)) for row in cursor.fetchall()]
|
||||||
|
|
||||||
@@ -230,6 +271,16 @@ class OrderDeliverySyncService:
|
|||||||
Returns:
|
Returns:
|
||||||
{"run_id", "status", "line_count"};并发冲突返回 status='skipped'。
|
{"run_id", "status", "line_count"};并发冲突返回 status='skipped'。
|
||||||
"""
|
"""
|
||||||
|
# 起始日边界先于抢锁解析:配置非法直接抛错(不写 sync_runs),防止误抓边界外历史数据
|
||||||
|
date_from = _resolve_sync_date_from()
|
||||||
|
if date_from:
|
||||||
|
logger.info(
|
||||||
|
"order-delivery-reply sync date-from boundary: %s (inclusive, order_date >= boundary)",
|
||||||
|
date_from.isoformat(),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
logger.info("order-delivery-reply sync date-from boundary: not configured (full sync)")
|
||||||
|
|
||||||
if not _sync_lock.acquire(blocking=False):
|
if not _sync_lock.acquire(blocking=False):
|
||||||
return {"run_id": None, "status": "skipped", "line_count": 0}
|
return {"run_id": None, "status": "skipped", "line_count": 0}
|
||||||
|
|
||||||
@@ -244,7 +295,7 @@ class OrderDeliverySyncService:
|
|||||||
with conn.cursor() as cursor:
|
with conn.cursor() as cursor:
|
||||||
last_order_no: str | None = None
|
last_order_no: str | None = None
|
||||||
while True:
|
while True:
|
||||||
page = cls._fetch_page(cursor, last_order_no)
|
page = cls._fetch_page(cursor, last_order_no, date_from)
|
||||||
if not page:
|
if not page:
|
||||||
break
|
break
|
||||||
hit_keys |= cls._upsert_page(page, synced_at)
|
hit_keys |= cls._upsert_page(page, synced_at)
|
||||||
|
|||||||
@@ -344,8 +344,10 @@ def _register_headers_from_config() -> None:
|
|||||||
if cfg.alias_order and cfg.header_labels:
|
if cfg.alias_order and cfg.header_labels:
|
||||||
register_schedule_header(name, cfg.alias_order, cfg.header_labels)
|
register_schedule_header(name, cfg.alias_order, cfg.header_labels)
|
||||||
from app.services.schedule.shipping_inventory_rpa_finalize import register_inventory_rpa_excel_headers
|
from app.services.schedule.shipping_inventory_rpa_finalize import register_inventory_rpa_excel_headers
|
||||||
|
from app.services.schedule.freight_receipt_rpa_finalize import register_receipt_rpa_excel_headers
|
||||||
|
|
||||||
register_inventory_rpa_excel_headers()
|
register_inventory_rpa_excel_headers()
|
||||||
|
register_receipt_rpa_excel_headers()
|
||||||
|
|
||||||
|
|
||||||
def reload_config() -> dict[str, Any]:
|
def reload_config() -> dict[str, Any]:
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
"""
|
||||||
|
backend/app/services/schedule/equipment_acceptance_job.py
|
||||||
|
|
||||||
|
用途:把设备验收预警扫描和周五发送接到平台排程。
|
||||||
|
依赖:equipment_acceptance.alert_service、ScheduleTask、ScheduleRun。
|
||||||
|
逻辑:日批先同步再写待发送。周五任务只发送,不再同步。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
|
|
||||||
|
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
|
||||||
|
|
||||||
|
|
||||||
|
def run_equipment_acceptance_alert_scan_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||||
|
"""
|
||||||
|
执行设备验收每日扫描。
|
||||||
|
|
||||||
|
核心逻辑:同步 E10 后生成待发送,不发企业微信。
|
||||||
|
Args:
|
||||||
|
task: 当前排程。
|
||||||
|
run: 本次执行记录。
|
||||||
|
Returns:
|
||||||
|
排程审计七元组。成功数是新增加更新,跳过数是停表取消的条数。
|
||||||
|
"""
|
||||||
|
from app.services.equipment_acceptance.alert_service import generate_alerts
|
||||||
|
|
||||||
|
summary = generate_alerts()
|
||||||
|
created = int(summary.get("created") or 0)
|
||||||
|
updated = int(summary.get("updated") or 0)
|
||||||
|
cancelled = int(summary.get("cancelled") or 0)
|
||||||
|
handled = created + updated
|
||||||
|
return handled + cancelled, handled, 0, cancelled, [summary], [], [
|
||||||
|
{"step": "equipment_acceptance_alert_scan", "status": "success", "detail": summary}
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def run_equipment_acceptance_alert_weekly_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||||
|
"""
|
||||||
|
执行周五设备验收企业微信汇总。
|
||||||
|
|
||||||
|
核心逻辑:按收件人各发一条。失败人数记入排程的失败计数。
|
||||||
|
Args:
|
||||||
|
task: 当前排程。
|
||||||
|
run: 本次执行记录。
|
||||||
|
Returns:
|
||||||
|
排程审计七元组。
|
||||||
|
"""
|
||||||
|
from app.services.equipment_acceptance.alert_service import send_pending_alerts
|
||||||
|
|
||||||
|
summary = send_pending_alerts()
|
||||||
|
sent = int(summary.get("sent") or 0)
|
||||||
|
failed = int(summary.get("failed") or 0)
|
||||||
|
status = "success" if not failed else "partial"
|
||||||
|
return sent + failed, sent, failed, 0, [summary], [], [
|
||||||
|
{"step": "equipment_acceptance_alert_weekly", "status": status, "detail": summary}
|
||||||
|
]
|
||||||
@@ -9,16 +9,83 @@ backend/app/services/schedule/freight_receipt_rpa_finalize.py
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
from flask import current_app
|
from flask import current_app
|
||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
from app.models import ScheduleRun, ScheduleTask
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
from app.models import ShippingReceiptRpaUnitRun
|
from app.models import ShippingReceiptRpaUnitRun
|
||||||
from app.services.schedule import normalize_platform_api_path
|
from app.services.schedule import normalize_platform_api_path, register_schedule_header, resolve_schedule_header
|
||||||
|
from app.services.schedule.excel_service import export_schedule_result_excel
|
||||||
from app.services.schedule.freight_receipt_rpa_job import AWAITING_RECEIPT_RPA_CALLBACK_STATUS, RECEIPT_RPA_JOB_KEY
|
from app.services.schedule.freight_receipt_rpa_job import AWAITING_RECEIPT_RPA_CALLBACK_STATUS, RECEIPT_RPA_JOB_KEY
|
||||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||||
|
|
||||||
|
_RECEIPT_RPA_HEADER_ORDER = [
|
||||||
|
"source_code",
|
||||||
|
"warehouse_id",
|
||||||
|
"connector_type",
|
||||||
|
"receipt_file_count",
|
||||||
|
"export_status",
|
||||||
|
"skip_reason",
|
||||||
|
"error_message",
|
||||||
|
]
|
||||||
|
_RECEIPT_RPA_HEADER_LABELS = {
|
||||||
|
"source_code": "收料源",
|
||||||
|
"warehouse_id": "仓库",
|
||||||
|
"connector_type": "连接器",
|
||||||
|
"receipt_file_count": "归档文件数",
|
||||||
|
"export_status": "导出状态",
|
||||||
|
"skip_reason": "跳过原因",
|
||||||
|
"error_message": "错误原因",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def register_receipt_rpa_excel_headers() -> None:
|
||||||
|
"""
|
||||||
|
注册货代收料 RPA 排程 Excel 列头(幂等)。
|
||||||
|
核心逻辑:由 schedule.__init__._register_headers_from_config 在 reload 后调用,避免被 clear 冲掉。
|
||||||
|
"""
|
||||||
|
register_schedule_header(
|
||||||
|
RECEIPT_RPA_JOB_KEY,
|
||||||
|
_RECEIPT_RPA_HEADER_ORDER,
|
||||||
|
_RECEIPT_RPA_HEADER_LABELS,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _build_receipt_finalize_details(units: list[ShippingReceiptRpaUnitRun]) -> list[dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
收料单元 → 排程 Excel 明细行(对齐库存 finalize 的行结构)。
|
||||||
|
|
||||||
|
核心逻辑:empty 归一为 skipped、cancelled 归一为 failed,与卡片 计数口径一致;
|
||||||
|
归档文件数便于与原始收料包内 {序号}_{source_code}.xlsx 条目对账。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
units: 该 run 的全部收料单元(已全部终态)。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
list[dict]: 按 unit.id 升序的明细行。
|
||||||
|
"""
|
||||||
|
rows: list[dict[str, Any]] = []
|
||||||
|
for unit in sorted(units, key=lambda item: item.id):
|
||||||
|
status = unit.status
|
||||||
|
if status == 'empty':
|
||||||
|
export_status = 'skipped'
|
||||||
|
elif status == 'cancelled':
|
||||||
|
export_status = 'failed'
|
||||||
|
else:
|
||||||
|
export_status = status
|
||||||
|
rows.append({
|
||||||
|
'source_code': unit.source_code,
|
||||||
|
'warehouse_id': unit.warehouse_id or '',
|
||||||
|
'connector_type': unit.connector_type or '',
|
||||||
|
'receipt_file_count': len(unit.files or []),
|
||||||
|
'export_status': export_status,
|
||||||
|
'skip_reason': str(unit.error_code or '') if export_status == 'skipped' else '',
|
||||||
|
'error_message': str(unit.error_message or '')[:500] if export_status == 'failed' else '',
|
||||||
|
})
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
def should_defer_receipt_schedule_run(task: ScheduleTask, step_logs: list | None) -> bool:
|
def should_defer_receipt_schedule_run(task: ScheduleTask, step_logs: list | None) -> bool:
|
||||||
"""仅当独立收料 job 成功写入 trigger 后延后终态,避免影响库存 job 判断。"""
|
"""仅当独立收料 job 成功写入 trigger 后延后终态,避免影响库存 job 判断。"""
|
||||||
@@ -176,6 +243,9 @@ def mark_receipt_unit_processing(payload: dict) -> dict:
|
|||||||
if unit.status == 'processing':
|
if unit.status == 'processing':
|
||||||
return {'updated': True, 'status': 'processing', 'idempotent': True}
|
return {'updated': True, 'status': 'processing', 'idempotent': True}
|
||||||
unit.status = 'processing'
|
unit.status = 'processing'
|
||||||
|
# started_at 是收料超时对账的活动锚(_receipt_last_activity):在飞单元必须有
|
||||||
|
# 开始时间,否则长静默批次无法区分"在跑"与"worker 已死"。
|
||||||
|
unit.started_at = datetime.utcnow()
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
if unit.schedule_run_id:
|
if unit.schedule_run_id:
|
||||||
refresh_receipt_schedule_run_progress(unit.schedule_run_id)
|
refresh_receipt_schedule_run_progress(unit.schedule_run_id)
|
||||||
@@ -210,6 +280,44 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
|
|||||||
run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed'
|
run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed'
|
||||||
run.error_message = '; '.join(filter(None, (unit.error_message for unit in units if unit.status == 'failed')))[:2000] or None
|
run.error_message = '; '.join(filter(None, (unit.error_message for unit in units if unit.status == 'failed')))[:2000] or None
|
||||||
|
|
||||||
|
# [STEP] 对齐库存 finalize:终态前生成收料汇总 Excel,企微在 textcard+ZIP 之外多发一条 [文件] 消息。
|
||||||
|
register_receipt_rpa_excel_headers()
|
||||||
|
header_order, header_labels = resolve_schedule_header(RECEIPT_RPA_JOB_KEY)
|
||||||
|
excel_export_ok = True
|
||||||
|
excel_data, excel_name, excel_size = None, None, 0
|
||||||
|
try:
|
||||||
|
excel_data, _excel_name, excel_size = export_schedule_result_excel(
|
||||||
|
run_no=run.run_no,
|
||||||
|
summary={
|
||||||
|
'status': run.status,
|
||||||
|
'total_count': len(units),
|
||||||
|
'success_count': success_count,
|
||||||
|
'skipped_count': skipped_count,
|
||||||
|
'failed_count': failed_count,
|
||||||
|
'duration_ms': run.duration_ms,
|
||||||
|
},
|
||||||
|
details=_build_receipt_finalize_details(units),
|
||||||
|
header_order=header_order,
|
||||||
|
header_labels=header_labels,
|
||||||
|
)
|
||||||
|
except Exception as excel_exc:
|
||||||
|
excel_export_ok = False
|
||||||
|
current_app.logger.error(
|
||||||
|
'[schedule-run] receipt RPA excel export failed for run %s: %s', run.run_no, excel_exc,
|
||||||
|
)
|
||||||
|
# 对齐库存:全成功批次的 Excel 失败要降级,不得让收件人误以为一切正常。
|
||||||
|
if run.status == 'success':
|
||||||
|
run.status = 'partial_failed'
|
||||||
|
run.error_message = '; '.join(filter(None, [run.error_message, f'Excel导出失败: {excel_exc}']))[:2000]
|
||||||
|
else:
|
||||||
|
# 企微/下载展示名:收料RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。
|
||||||
|
from app.services.schedule.shipping_receipt_rpa_archive import receipt_rpa_result_excel_name
|
||||||
|
|
||||||
|
excel_name = receipt_rpa_result_excel_name(run)
|
||||||
|
run.excel_file_data = excel_data
|
||||||
|
run.excel_file_name = excel_name if excel_data else None
|
||||||
|
run.excel_file_size = excel_size or 0
|
||||||
|
|
||||||
# [STEP] 对齐库存:终态前预生成原始收料 ZIP,企微只发一个包。
|
# [STEP] 对齐库存:终态前预生成原始收料 ZIP,企微只发一个包。
|
||||||
archive_summary = {
|
archive_summary = {
|
||||||
'raw_receipt_zip_available': False,
|
'raw_receipt_zip_available': False,
|
||||||
@@ -234,6 +342,8 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
|
|||||||
'success_count': success_count,
|
'success_count': success_count,
|
||||||
'empty_count': skipped_count,
|
'empty_count': skipped_count,
|
||||||
'failed_count': failed_count,
|
'failed_count': failed_count,
|
||||||
|
'excel_export_status': 'ok' if excel_export_ok else 'failed',
|
||||||
|
'excel_failed': not excel_export_ok,
|
||||||
**archive_summary,
|
**archive_summary,
|
||||||
}
|
}
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
@@ -267,19 +377,40 @@ def is_freight_receipt_rpa_task(task: ScheduleTask | None) -> bool:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _receipt_last_activity(run: ScheduleRun, units: list[ShippingReceiptRpaUnitRun]) -> datetime:
|
||||||
|
"""收料 run 的最后活动锚:run 开始时间与全部单元 started/finished 时间的最大值。
|
||||||
|
|
||||||
|
语义为「笔间静默」:worker 每开始/完成一笔都会推进锚点,锚点静默超过
|
||||||
|
FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS 才判定 worker 不再活动。刻意不含单元
|
||||||
|
created_at——批量 trigger 中排队单元的创建时间不代表活动,否则整批永不超时。
|
||||||
|
极端长单笔(单站点导出超过 timeout)会被判超时,需按最慢单笔调大该配置。
|
||||||
|
"""
|
||||||
|
stamps = [run.started_at] if run.started_at else []
|
||||||
|
for unit in units:
|
||||||
|
if unit.started_at:
|
||||||
|
stamps.append(unit.started_at)
|
||||||
|
if unit.finished_at:
|
||||||
|
stamps.append(unit.finished_at)
|
||||||
|
return max(stamps)
|
||||||
|
|
||||||
|
|
||||||
def _recover_stale_receipt_run(run: ScheduleRun, *, cutoff: datetime, timeout_seconds: int) -> bool:
|
def _recover_stale_receipt_run(run: ScheduleRun, *, cutoff: datetime, timeout_seconds: int) -> bool:
|
||||||
"""将无回调的独立收料运行收口为失败,保留其单元与触发审计事实。"""
|
"""将无回调的独立收料运行收口为失败,保留其单元与触发审计事实。
|
||||||
|
|
||||||
|
截止判据为最后活动锚(_receipt_last_activity)而非 run.started_at——
|
||||||
|
串行长批次(>timeout)只要仍有笔间活动就不得被误杀。
|
||||||
|
"""
|
||||||
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
|
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
|
||||||
if not summary.get('awaiting_receipt_rpa') or run.status != 'running' or not run.started_at or run.started_at > cutoff:
|
if not summary.get('awaiting_receipt_rpa') or run.status != 'running' or not run.started_at:
|
||||||
return False
|
return False
|
||||||
task = run.task or db.session.get(ScheduleTask, run.schedule_task_id)
|
task = run.task or db.session.get(ScheduleTask, run.schedule_task_id)
|
||||||
if not is_freight_receipt_rpa_task(task):
|
if not is_freight_receipt_rpa_task(task):
|
||||||
return False
|
return False
|
||||||
|
units = ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).all()
|
||||||
|
if _receipt_last_activity(run, units) > cutoff:
|
||||||
|
return False
|
||||||
now = datetime.utcnow()
|
now = datetime.utcnow()
|
||||||
pending = ShippingReceiptRpaUnitRun.query.filter(
|
pending = [unit for unit in units if unit.status in {'queued', 'awaiting_rpa', 'processing'}]
|
||||||
ShippingReceiptRpaUnitRun.schedule_run_id == run.id,
|
|
||||||
ShippingReceiptRpaUnitRun.status.in_({'queued', 'awaiting_rpa', 'processing'}),
|
|
||||||
).all()
|
|
||||||
for unit in pending:
|
for unit in pending:
|
||||||
before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}
|
before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}
|
||||||
unit.status = 'failed'
|
unit.status = 'failed'
|
||||||
|
|||||||
@@ -1,24 +1,27 @@
|
|||||||
"""自动调拨排程。
|
"""自动调拨排程。
|
||||||
|
|
||||||
用途:自动处理当日新成熟可调拨项与历史可恢复异常,并发送一次企微汇总通知。
|
用途:自动处理当日新成熟可调拨项与历史可恢复异常;执行结果通知统一走
|
||||||
依赖:auto_transfer、transfer deps、wecom_sender、job_registry.ScheduleExecuteResult、
|
排程「启用通知」通用企微通知,本任务不自建领域通知。
|
||||||
receipt_trigger_service.list_receipt_capable_source_codes(缺省来源口径)。
|
依赖:auto_transfer、transfer deps、job_registry.ScheduleExecuteResult、
|
||||||
|
receipt_trigger_service.list_receipt_capable_source_codes(缺省来源口径)、
|
||||||
|
date_policy(业务日与日期解析)。
|
||||||
逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发收料 RPA),
|
逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发收料 RPA),
|
||||||
不依赖其他排程成功;来源留空兜底为全部启用收料来源;有通知人时构造
|
不依赖其他排程成功;来源留空兜底为全部启用收料来源;可选收料日期范围
|
||||||
sender,仅在有 run_no 或空数据日(无 errors)后置 domain_notification_managed
|
以「T−N 偏移天数」配置,执行时按当日业务日换算为具体日期透传匹配层;
|
||||||
抑制框架卡;硬失败不置标记以便框架兜底。
|
空数据日(无 run_no 且无 errors)置 domain_notification_managed 保持
|
||||||
|
静默(C5),有 Run 或硬失败交由框架完成卡按排程「启用通知」发送。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import timedelta
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from app.models import ScheduleRun, ScheduleTask
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
from app.services.in_transit_transfer import deps as transfer_deps
|
from app.services.in_transit_transfer import deps as transfer_deps
|
||||||
from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome, run_auto_transfer
|
from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome, run_auto_transfer
|
||||||
from app.services.in_transit_transfer.date_policy import business_date_now
|
from app.services.in_transit_transfer.date_policy import business_date_now, parse_date
|
||||||
from app.services.in_transit_transfer.receipt_trigger_service import list_receipt_capable_source_codes
|
from app.services.in_transit_transfer.receipt_trigger_service import list_receipt_capable_source_codes
|
||||||
from app.services.in_transit_transfer.wecom_sender import WecomSummarySender
|
|
||||||
from app.services.schedule.job_registry import ScheduleExecuteResult
|
from app.services.schedule.job_registry import ScheduleExecuteResult
|
||||||
|
|
||||||
|
|
||||||
@@ -45,41 +48,77 @@ def _wanted_source_codes(task: ScheduleTask) -> list[str]:
|
|||||||
return codes
|
return codes
|
||||||
|
|
||||||
|
|
||||||
def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
def _offset_to_date(business_date: str, offset_days: Any, label: str, errors: list[str]) -> str | None:
|
||||||
"""自动调拨:恢复 + 匹配(严格相等)+ 执行 + 企微汇总通知。
|
"""把「T−N 偏移天数」参数换算为执行日口径的具体收料日期(T−N)。
|
||||||
|
|
||||||
核心逻辑:有通知人时构造 WecomSummarySender 传入 run_auto_transfer;
|
|
||||||
仅在返回后按结果决定是否置 domain_notification_managed——有 run_no
|
|
||||||
(成功/部分失败领域卡路径)或无 errors(空数据日 C5)时抑制框架卡;
|
|
||||||
硬失败(无 run_no 且有 errors)不置标记,允许框架完成卡兜底。
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
task: 排程任务(job_params: source_codes/recover_history/notify_user_ids)。
|
business_date: 业务日期 T(YYYY-MM-DD)。
|
||||||
run: 排程执行批次(领域自管通知时写入 response_summary_json 标记)。
|
offset_days: 偏移天数(须为非负整数;None/空视为未配置)。
|
||||||
|
label: 参数中文名(写错误信息用)。
|
||||||
|
errors: 错误累积列表(非法配置写入后返回 None,由调用方快速失败)。
|
||||||
|
Returns:
|
||||||
|
'YYYY-MM-DD';未配置或非法时为 None(非法同时落错误)。
|
||||||
|
"""
|
||||||
|
if offset_days is None or offset_days == "":
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
days = int(offset_days)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
errors.append(f"{label}须为非负整数(当前值 {offset_days!r})")
|
||||||
|
return None
|
||||||
|
if days < 0 or float(offset_days) != days:
|
||||||
|
errors.append(f"{label}须为非负整数(当前值 {offset_days!r})")
|
||||||
|
return None
|
||||||
|
return (parse_date(business_date) - timedelta(days=days)).isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||||
|
"""自动调拨:恢复 + 匹配(严格相等)+ 执行;通知统一走排程「启用通知」。
|
||||||
|
|
||||||
|
核心逻辑:不自建领域汇总通知(任务级通知人参数已移除,收件人取排程表单
|
||||||
|
底部「启用通知」配置);仅在空数据日(无 run_no 且无 errors)置
|
||||||
|
domain_notification_managed 抑制框架完成卡(C5 空数据日静默);
|
||||||
|
有 run_no(成功/部分失败)或硬失败时框架卡照常发送/兜底。
|
||||||
|
可选收料日期范围以「T−N 偏移天数」配置(receipt_from/to_offset_days),
|
||||||
|
执行时按当日业务日换算为具体日期透传匹配层,供测试/排障缩小本轮处理面;
|
||||||
|
偏移非法(负数/小数/非数字)快速失败不执行;范围越界由匹配层
|
||||||
|
ValidationError 落 errors 走硬失败路径。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
task: 排程任务(job_params: source_codes/recover_history/
|
||||||
|
receipt_from_offset_days/receipt_to_offset_days)。
|
||||||
|
run: 排程执行批次(空数据日写入 response_summary_json 标记)。
|
||||||
Returns:
|
Returns:
|
||||||
ScheduleExecuteResult 七元组;空数据日 total=0 且不记 error(C5)。
|
ScheduleExecuteResult 七元组;空数据日 total=0 且不记 error(C5)。
|
||||||
"""
|
"""
|
||||||
params = _task_params(task)
|
params = _task_params(task)
|
||||||
source_codes = _wanted_source_codes(task)
|
source_codes = _wanted_source_codes(task)
|
||||||
recover_history = bool(params.get("recover_history", True))
|
recover_history = bool(params.get("recover_history", True))
|
||||||
recipients = [str(item).strip() for item in (params.get("notify_user_ids") or []) if str(item).strip()]
|
business_date = str(business_date_now())
|
||||||
|
|
||||||
# 有通知人时构造 sender 传入领域层;是否抑制框架卡见下方按 outcome 判定。
|
# [STEP] T−N 偏移换算:非法配置快速失败(不执行、交框架失败通知),
|
||||||
sender = WecomSummarySender() if recipients else None
|
# 防止坏参数被静默忽略后退化成全量积压处理。
|
||||||
|
param_errors: list[str] = []
|
||||||
|
receipt_date_from = _offset_to_date(
|
||||||
|
business_date, params.get("receipt_from_offset_days"), "收料日期起点", param_errors)
|
||||||
|
receipt_date_to = _offset_to_date(
|
||||||
|
business_date, params.get("receipt_to_offset_days"), "收料日期终点", param_errors)
|
||||||
|
if param_errors:
|
||||||
|
return (0, 0, 0, 0, [], [f"sources={len(source_codes)}"], param_errors)
|
||||||
|
|
||||||
deps = transfer_deps.get_transfer_dependencies()
|
deps = transfer_deps.get_transfer_dependencies()
|
||||||
outcome = run_auto_transfer(
|
outcome = run_auto_transfer(
|
||||||
business_date=str(business_date_now()),
|
business_date=business_date,
|
||||||
deps=deps,
|
deps=deps,
|
||||||
source_codes=source_codes,
|
source_codes=source_codes,
|
||||||
recover_history=recover_history,
|
recover_history=recover_history,
|
||||||
sender=sender,
|
receipt_date_from=receipt_date_from,
|
||||||
recipients=recipients,
|
receipt_date_to=receipt_date_to,
|
||||||
)
|
)
|
||||||
|
|
||||||
# [STEP] 领域自管通知门禁:仅在领域卡已发出(有 run_no)或空数据日
|
# [STEP] 空数据日静默门禁:无 run 且无错误(匹配后无可执行行,C5)时置
|
||||||
# (无 errors,C5 静默)时置标记;硬失败让框架完成卡兜底。
|
# 标记抑制框架完成卡;有 run 或硬失败时框架卡照常通知/兜底。
|
||||||
if recipients and (outcome.run_no or not outcome.errors):
|
if not outcome.run_no and not outcome.errors:
|
||||||
run.response_summary_json = {
|
run.response_summary_json = {
|
||||||
**(run.response_summary_json or {}),
|
**(run.response_summary_json or {}),
|
||||||
"domain_notification_managed": True,
|
"domain_notification_managed": True,
|
||||||
@@ -94,7 +133,6 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
|
|||||||
results.append({
|
results.append({
|
||||||
"run_no": outcome.run_no,
|
"run_no": outcome.run_no,
|
||||||
"status": outcome.run_status,
|
"status": outcome.run_status,
|
||||||
"notification_status": outcome.notification_status,
|
|
||||||
})
|
})
|
||||||
elif not outcome.errors:
|
elif not outcome.errors:
|
||||||
# 空数据日:匹配后无可执行行,执行与通知按 C5 跳过,不记失败。
|
# 空数据日:匹配后无可执行行,执行与通知按 C5 跳过,不记失败。
|
||||||
|
|||||||
@@ -156,6 +156,10 @@ def _register_builtin_platform_jobs() -> None:
|
|||||||
run_contract_payment_sync_schedule,
|
run_contract_payment_sync_schedule,
|
||||||
run_contract_payment_weekly_alert_schedule,
|
run_contract_payment_weekly_alert_schedule,
|
||||||
)
|
)
|
||||||
|
from app.services.schedule.equipment_acceptance_job import (
|
||||||
|
run_equipment_acceptance_alert_scan_schedule,
|
||||||
|
run_equipment_acceptance_alert_weekly_schedule,
|
||||||
|
)
|
||||||
from app.services.schedule.lean_training_job import run_lean_training_reminder_schedule, run_lean_training_video_push_schedule
|
from app.services.schedule.lean_training_job import run_lean_training_reminder_schedule, run_lean_training_video_push_schedule
|
||||||
|
|
||||||
register_platform_job(PlatformJobDefinition(
|
register_platform_job(PlatformJobDefinition(
|
||||||
@@ -268,6 +272,20 @@ def _register_builtin_platform_jobs() -> None:
|
|||||||
key="contract-payment-alert-weekly", label="合同付款预警周汇总", handler=run_contract_payment_weekly_alert_schedule,
|
key="contract-payment-alert-weekly", label="合同付款预警周汇总", handler=run_contract_payment_weekly_alert_schedule,
|
||||||
description="每周五 18:00 按收件人发送一条付款预警汇总及 Excel 明细。", category="contract_payment",
|
description="每周五 18:00 按收件人发送一条付款预警汇总及 Excel 明细。", category="contract_payment",
|
||||||
))
|
))
|
||||||
|
register_platform_job(PlatformJobDefinition(
|
||||||
|
key="equipment-acceptance-alert-scan",
|
||||||
|
label="设备验收预警扫描",
|
||||||
|
handler=run_equipment_acceptance_alert_scan_schedule,
|
||||||
|
description="每日同步 E10 验收单,并按停留天数生成待发送记录。",
|
||||||
|
category="equipment_acceptance",
|
||||||
|
))
|
||||||
|
register_platform_job(PlatformJobDefinition(
|
||||||
|
key="equipment-acceptance-alert-weekly",
|
||||||
|
label="设备验收预警发送",
|
||||||
|
handler=run_equipment_acceptance_alert_weekly_schedule,
|
||||||
|
description="每周五 18:00 按收件人发送一条设备验收停留提醒。",
|
||||||
|
category="equipment_acceptance",
|
||||||
|
))
|
||||||
|
|
||||||
register_platform_job(PlatformJobDefinition(
|
register_platform_job(PlatformJobDefinition(
|
||||||
key="contract-payment-sync",
|
key="contract-payment-sync",
|
||||||
@@ -566,10 +584,8 @@ def _register_builtin_platform_jobs() -> None:
|
|||||||
label="在途自动调拨",
|
label="在途自动调拨",
|
||||||
handler=run_in_transit_transfer_schedule,
|
handler=run_in_transit_transfer_schedule,
|
||||||
description=(
|
description=(
|
||||||
"自动处理可调拨项与历史可恢复异常:调拨前确保各来源当日收料文件就绪"
|
"自动匹配可调拨项并生成 ERP 调拨单,含历史可恢复异常复核;"
|
||||||
"(就绪复用,缺失自动触发收料 RPA),数量严格相等匹配后自动生成 ERP 调拨单;"
|
"缺收料文件时自动触发收料 RPA。执行时间建议配置在期望调拨时点之前。"
|
||||||
"每非空 Run 发送一条企微汇总通知,通知失败不改变 ERP 结果。"
|
|
||||||
"执行时间由排程配置决定,建议配置在业务期望的调拨时点之前。"
|
|
||||||
),
|
),
|
||||||
category="platform",
|
category="platform",
|
||||||
params_schema=(
|
params_schema=(
|
||||||
@@ -591,16 +607,23 @@ def _register_builtin_platform_jobs() -> None:
|
|||||||
"default": True,
|
"default": True,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"key": "notify_user_ids",
|
"key": "receipt_from_offset_days",
|
||||||
"type": "multi_select",
|
"type": "number",
|
||||||
"label": "通知人",
|
"label": "收料日期起(T-N)",
|
||||||
"label_key": "admin.schedule.form.transferNotifyUsers",
|
"label_key": "admin.schedule.form.transferReceiptDateFrom",
|
||||||
"required": False,
|
"required": False,
|
||||||
"default": [],
|
"help": "填天数 N,按执行日换算收料日期下限 T−N;例:4=从 T−4 起。留空=全部成熟积压(默认 ≤ T-2)。",
|
||||||
"options_source": "users",
|
},
|
||||||
|
{
|
||||||
|
"key": "receipt_to_offset_days",
|
||||||
|
"type": "number",
|
||||||
|
"label": "收料日期止(T-N)",
|
||||||
|
"label_key": "admin.schedule.form.transferReceiptDateTo",
|
||||||
|
"required": False,
|
||||||
|
"help": "填天数 N,按执行日换算收料日期上限 T−N;例:起4止2=只处理 T−4~T−2。不得晚于成熟上限(默认 T-2)。",
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
defaults={"source_codes": [], "recover_history": True, "notify_user_ids": []},
|
defaults={"source_codes": [], "recover_history": True},
|
||||||
))
|
))
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -357,9 +357,6 @@ def prepare_schedule_queue() -> int:
|
|||||||
recovered = recover_all_stale_awaiting_rpa_schedule_runs()
|
recovered = recover_all_stale_awaiting_rpa_schedule_runs()
|
||||||
if recovered:
|
if recovered:
|
||||||
current_app.logger.info("[schedule-worker] recovered %d stale awaiting RPA runs", recovered)
|
current_app.logger.info("[schedule-worker] recovered %d stale awaiting RPA runs", recovered)
|
||||||
receipt_recovered = recover_all_stale_receipt_rpa_schedule_runs()
|
|
||||||
if receipt_recovered:
|
|
||||||
current_app.logger.info("[schedule-worker] recovered %d stale receipt RPA runs", receipt_recovered)
|
|
||||||
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
|
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
|
||||||
recover_pending_rpa_callback_cleanup_jobs,
|
recover_pending_rpa_callback_cleanup_jobs,
|
||||||
)
|
)
|
||||||
@@ -379,6 +376,13 @@ def prepare_schedule_queue() -> int:
|
|||||||
if transfer_stale:
|
if transfer_stale:
|
||||||
current_app.logger.info("[schedule-worker] recovered %d stale transfer waiting source jobs", transfer_stale)
|
current_app.logger.info("[schedule-worker] recovered %d stale transfer waiting source jobs", transfer_stale)
|
||||||
|
|
||||||
|
# 收料 run 超时对账同为每轮领取维护(2026-10-07 从启动一次性分支迁出):
|
||||||
|
# 此前长驻进程期间超时 run 永不终态(RUN20261001131705E5E5 卡执行中的根因)。
|
||||||
|
# 回收判据为最后活动锚(笔间静默),健康长批次不被误杀,见 freight_receipt_rpa_finalize。
|
||||||
|
receipt_stale = recover_all_stale_receipt_rpa_schedule_runs()
|
||||||
|
if receipt_stale:
|
||||||
|
current_app.logger.info("[schedule-worker] recovered %d stale receipt RPA runs", receipt_stale)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from app.services.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status
|
from app.services.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status
|
||||||
|
|
||||||
|
|||||||
@@ -110,6 +110,11 @@ def receipt_raw_zip_download_name(run: ScheduleRun) -> str:
|
|||||||
return f'{receipt_rpa_attachment_stem(run)}-收料.zip'
|
return f'{receipt_rpa_attachment_stem(run)}-收料.zip'
|
||||||
|
|
||||||
|
|
||||||
|
def receipt_rpa_result_excel_name(run: ScheduleRun) -> str:
|
||||||
|
"""收料 RPA 结果 Excel 的企微/下载展示名(对齐库存 inventory_rpa_result_excel_name)。"""
|
||||||
|
return f'{receipt_rpa_attachment_stem(run)}-结果.xlsx'
|
||||||
|
|
||||||
|
|
||||||
def _receipt_raw_zip_archive_path(run_no: str) -> Path:
|
def _receipt_raw_zip_archive_path(run_no: str) -> Path:
|
||||||
"""磁盘归档路径:<archive_dir>/<run_no>.zip。"""
|
"""磁盘归档路径:<archive_dir>/<run_no>.zip。"""
|
||||||
return Path(get_receipt_archive_dir()) / f'{run_no}.zip'
|
return Path(get_receipt_archive_dir()) / f'{run_no}.zip'
|
||||||
|
|||||||
@@ -1277,6 +1277,14 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str,
|
|||||||
)
|
)
|
||||||
# 行级匹配只持久化当前 LineMatch;OT 不再保存库存匹配聚合列或行结果缓存。
|
# 行级匹配只持久化当前 LineMatch;OT 不再保存库存匹配聚合列或行结果缓存。
|
||||||
_merge_line_inventory_resolutions(task, match_payload, snapshot_line_id=int(snapshot.lines[orig_idx].id) if snapshot is not None and orig_idx < len(snapshot.lines) else None)
|
_merge_line_inventory_resolutions(task, match_payload, snapshot_line_id=int(snapshot.lines[orig_idx].id) if snapshot is not None and orig_idx < len(snapshot.lines) else None)
|
||||||
|
# [BE-料号兜底自动放行] 行事实落库后、聚合重算【前】执行(与 match_inventory 同款钩子):
|
||||||
|
# 料号总量满足需求的缺口行由系统自动放行,使下方聚合重算把放行行计入满足、
|
||||||
|
# 行级重匹配可直接落 MATCHED_FULFILLABLE;重入安全性说明见 match_inventory 钩子注释。
|
||||||
|
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||||
|
auto_release_part_fallback_shortages,
|
||||||
|
)
|
||||||
|
|
||||||
|
auto_release_part_fallback_shortages(task)
|
||||||
|
|
||||||
line_results = list(match_payload.get('line_results') or [])
|
line_results = list(match_payload.get('line_results') or [])
|
||||||
from app.services.shipping_notice.reservation_service import record_inventory_verification
|
from app.services.shipping_notice.reservation_service import record_inventory_verification
|
||||||
@@ -1778,6 +1786,17 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
|||||||
inventory_snapshot_id=active_inventory_file_for_task(task).id if active_inventory_file_for_task(task) else None,
|
inventory_snapshot_id=active_inventory_file_for_task(task).id if active_inventory_file_for_task(task) else None,
|
||||||
matching_rule_version='stp_line_v2',
|
matching_rule_version='stp_line_v2',
|
||||||
)
|
)
|
||||||
|
# [BE-料号兜底自动放行] 行事实落库后、聚合与 match_completed 判定【前】执行:
|
||||||
|
# 料号总量满足需求的缺口行由系统自动放行(满足即放行,非仅可放行),使随后的
|
||||||
|
# 聚合重算与满足性判定把放行行计入满足、任务可直接落 MATCHED_FULFILLABLE。
|
||||||
|
# 重入安全:匹配跑在 AutoProgress Gate 执行器事务内时,submit_auto_progress 按
|
||||||
|
# 「任务唯一活动 Job + 活动 Attempt 复用」幂等,不会重复入队或自触发;auto fulfill
|
||||||
|
# Job 重复入队由协调器 eligible+幂等键吸收(与既有匹配路径的多入队行为一致)。
|
||||||
|
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||||
|
auto_release_part_fallback_shortages,
|
||||||
|
)
|
||||||
|
|
||||||
|
auto_release_part_fallback_shortages(task)
|
||||||
# 详情投影只读 task JSON;必须基于已落库的 current 行事实重算整单,
|
# 详情投影只读 task JSON;必须基于已落库的 current 行事实重算整单,
|
||||||
# 否则匹配失败后订单明细仍显示“待确认”,且局部结果可能覆盖既有缺口。
|
# 否则匹配失败后订单明细仍显示“待确认”,且局部结果可能覆盖既有缺口。
|
||||||
match_status, shortages = _recompute_task_match_aggregate(task)
|
match_status, shortages = _recompute_task_match_aggregate(task)
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ services/shipping_notice/line_inventory_match_persistence.py
|
|||||||
依赖:ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、normalize 投影语义。
|
依赖:ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、normalize 投影语义。
|
||||||
逻辑:由 fulfillment_workflow.match_inventory 调用;按冻结订单行 snapshot_line_id 落库;
|
逻辑:由 fulfillment_workflow.match_inventory 调用;按冻结订单行 snapshot_line_id 落库;
|
||||||
新快照新增行并切换 is_current;不覆盖历史快照事实。
|
新快照新增行并切换 is_current;不覆盖历史快照事实。
|
||||||
|
匹配器下发的料号兜底总量 part_available_qty(Task 1)随行事实字符串化落列,
|
||||||
|
供后续投影层与自动放行服务读取。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -277,6 +279,12 @@ def persist_line_inventory_match_facts(
|
|||||||
required_qty=str(required) if required is not None else None,
|
required_qty=str(required) if required is not None else None,
|
||||||
available_qty=str(available) if available is not None else None,
|
available_qty=str(available) if available is not None else None,
|
||||||
shortage_qty=str(shortage) if shortage is not None else None,
|
shortage_qty=str(shortage) if shortage is not None else None,
|
||||||
|
# 料号兜底总量(Task 1 匹配器下发):字符串化落列;无键/None → NULL,
|
||||||
|
# BE-5 / not_found 分支不篡改,直接取匹配器原值。
|
||||||
|
part_available_qty=(
|
||||||
|
str(result['part_available_qty'])
|
||||||
|
if result.get('part_available_qty') is not None else None
|
||||||
|
),
|
||||||
reservation_id=rsv,
|
reservation_id=rsv,
|
||||||
part_number=pn,
|
part_number=pn,
|
||||||
unit=unit_value,
|
unit=unit_value,
|
||||||
@@ -342,6 +350,11 @@ def persist_line_inventory_match_facts(
|
|||||||
existing.required_qty = str(required) if required is not None else None
|
existing.required_qty = str(required) if required is not None else None
|
||||||
existing.available_qty = str(available) if available is not None else None
|
existing.available_qty = str(available) if available is not None else None
|
||||||
existing.shortage_qty = str(shortage) if shortage is not None else None
|
existing.shortage_qty = str(shortage) if shortage is not None else None
|
||||||
|
# 更新分支同样以最新匹配结果刷新兜底总量;键缺失 → NULL,不残留旧值。
|
||||||
|
existing.part_available_qty = (
|
||||||
|
str(result['part_available_qty'])
|
||||||
|
if result.get('part_available_qty') is not None else None
|
||||||
|
)
|
||||||
existing.reservation_id = rsv
|
existing.reservation_id = rsv
|
||||||
existing.part_number = pn
|
existing.part_number = pn
|
||||||
existing.unit = unit_value
|
existing.unit = unit_value
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ services/shipping_notice/line_inventory_match_projection.py
|
|||||||
依赖:ShippingNoticeLineInventoryMatch、ShippingTaskInventoryRpaAttempt、Config 自动履约开关。
|
依赖:ShippingNoticeLineInventoryMatch、ShippingTaskInventoryRpaAttempt、Config 自动履约开关。
|
||||||
逻辑:由 order_review_fulfillment_decision_service / ui_state._build_stage_context 调用;
|
逻辑:由 order_review_fulfillment_decision_service / ui_state._build_stage_context 调用;
|
||||||
ready+not_found→available=0;result_missing 不得转 0;
|
ready+not_found→available=0;result_missing 不得转 0;
|
||||||
|
part_available_qty(料号兜底总量)仅 inventory_status==ready 时透出,否则 None,
|
||||||
|
不派生「可兜底放行」布尔(自动放行判定在 Task 7 服务内基于行事实现算);
|
||||||
inventory_allowed_actions / line_allowed_actions 分域下发(禁止前端自推按钮);
|
inventory_allowed_actions / line_allowed_actions 分域下发(禁止前端自推按钮);
|
||||||
line_allowed_actions 仅 close_unfulfillable,不再下发 view_fulfillment_detail;
|
line_allowed_actions 仅 close_unfulfillable,不再下发 view_fulfillment_detail;
|
||||||
load_current_match_facts_by_task / inventory_rpa_is_running 在同一 HTTP 请求内 memo,
|
load_current_match_facts_by_task / inventory_rpa_is_running 在同一 HTTP 请求内 memo,
|
||||||
@@ -562,6 +564,7 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any
|
|||||||
'required_qty': row.required_qty,
|
'required_qty': row.required_qty,
|
||||||
'available_qty': row.available_qty,
|
'available_qty': row.available_qty,
|
||||||
'shortage_qty': row.shortage_qty,
|
'shortage_qty': row.shortage_qty,
|
||||||
|
'part_available_qty': getattr(row, 'part_available_qty', None),
|
||||||
'reservation_id': row.reservation_id,
|
'reservation_id': row.reservation_id,
|
||||||
'part_number': row.part_number,
|
'part_number': row.part_number,
|
||||||
'unit': row.unit,
|
'unit': row.unit,
|
||||||
@@ -661,6 +664,7 @@ def project_line_inventory_view(
|
|||||||
'inventory_status': None,
|
'inventory_status': None,
|
||||||
'match_result': None,
|
'match_result': None,
|
||||||
'available_qty': None,
|
'available_qty': None,
|
||||||
|
'part_available_qty': None,
|
||||||
'shortage_qty': None,
|
'shortage_qty': None,
|
||||||
'is_shortage': False,
|
'is_shortage': False,
|
||||||
'display_available': 'pending',
|
'display_available': 'pending',
|
||||||
@@ -699,6 +703,12 @@ def project_line_inventory_view(
|
|||||||
required_qty=required_qty if required_qty is not None else fact.get('required_qty'),
|
required_qty=required_qty if required_qty is not None else fact.get('required_qty'),
|
||||||
available_qty=fact.get('available_qty'),
|
available_qty=fact.get('available_qty'),
|
||||||
)
|
)
|
||||||
|
# [STEP] 料号兜底口径:仅库存就绪时透出料号总可用量(与 available_qty 同门控);
|
||||||
|
# 「是否可兜底放行」的判定由自动放行服务基于行事实现算,投影层不下发派生布尔。
|
||||||
|
part_total = _parse_qty(fact.get('part_available_qty'))
|
||||||
|
part_available_value = (
|
||||||
|
str(part_total) if inventory_status == STATUS_READY and part_total is not None else None
|
||||||
|
)
|
||||||
user_status = project_user_line_status(
|
user_status = project_user_line_status(
|
||||||
inventory_status=inventory_status,
|
inventory_status=inventory_status,
|
||||||
match_result=match_result,
|
match_result=match_result,
|
||||||
@@ -770,6 +780,7 @@ def project_line_inventory_view(
|
|||||||
'inventory_status': inventory_status,
|
'inventory_status': inventory_status,
|
||||||
'match_result': match_result,
|
'match_result': match_result,
|
||||||
'available_qty': qty['available_qty'],
|
'available_qty': qty['available_qty'],
|
||||||
|
'part_available_qty': part_available_value,
|
||||||
'shortage_qty': qty['shortage_qty'],
|
'shortage_qty': qty['shortage_qty'],
|
||||||
'is_shortage': bool(qty['is_shortage']),
|
'is_shortage': bool(qty['is_shortage']),
|
||||||
'display_available': qty['display_available'],
|
'display_available': qty['display_available'],
|
||||||
|
|||||||
+408
-90
@@ -30,6 +30,9 @@ from app.models import (
|
|||||||
ShippingOrderTask,
|
ShippingOrderTask,
|
||||||
ShippingTaskInventoryRpaAttempt,
|
ShippingTaskInventoryRpaAttempt,
|
||||||
)
|
)
|
||||||
|
from app.services.shipping_notice.line_inventory_match_persistence import (
|
||||||
|
resolve_review_case_for_task,
|
||||||
|
)
|
||||||
from app.services.shipping_notice.workflow_ledger_service import (
|
from app.services.shipping_notice.workflow_ledger_service import (
|
||||||
assert_case_is_current_workflow_version,
|
assert_case_is_current_workflow_version,
|
||||||
)
|
)
|
||||||
@@ -317,8 +320,14 @@ def _shortage_release_required_fields(
|
|||||||
line_index: int | None,
|
line_index: int | None,
|
||||||
inventory_snapshot_id: int | None,
|
inventory_snapshot_id: int | None,
|
||||||
inventory_source_code: str | None,
|
inventory_source_code: str | None,
|
||||||
) -> list[dict[str, str]]:
|
) -> tuple[list[dict[str, Any]], str]:
|
||||||
"""按该行快照、库存源解析方案和发货模板计算短缺放行补录字段。"""
|
"""按该行快照、库存源解析方案和发货模板计算短缺放行补录字段。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(fields, evidence_scope) 元组:fields 为模板库存字段投影(快照唯一值只读,
|
||||||
|
其余 requires_manual);evidence_scope ∈ {'inventory_snapshot', 'part_fallback'},
|
||||||
|
'part_fallback' 表示预约键在库存快照 0 行命中、已按料号键重筛带出(审计口径)。
|
||||||
|
"""
|
||||||
if line_index is None:
|
if line_index is None:
|
||||||
raise ConflictError(
|
raise ConflictError(
|
||||||
'Current line inventory evidence is unavailable',
|
'Current line inventory evidence is unavailable',
|
||||||
@@ -371,7 +380,8 @@ def _shortage_release_required_fields(
|
|||||||
and str(item.get('source_key') or '').strip().isdigit()
|
and str(item.get('source_key') or '').strip().isdigit()
|
||||||
}
|
}
|
||||||
labels = {str(row.id): str(row.display_name or '').strip() for row in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all()} if field_ids else {}
|
labels = {str(row.id): str(row.display_name or '').strip() for row in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all()} if field_ids else {}
|
||||||
return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels)
|
# 无快照即无库存证据:全部模板库存字段人工补录,证据范围维持快照口径。
|
||||||
|
return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels), 'inventory_snapshot'
|
||||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||||
match_keys = definition.get('match_keys') if isinstance(definition.get('match_keys'), list) else []
|
match_keys = definition.get('match_keys') if isinstance(definition.get('match_keys'), list) else []
|
||||||
expected = [
|
expected = [
|
||||||
@@ -395,6 +405,24 @@ def _shortage_release_required_fields(
|
|||||||
dict(row) for row in inventory_lines
|
dict(row) for row in inventory_lines
|
||||||
if all(_match_text(row.get(inventory_field)) == value for inventory_field, value in expected)
|
if all(_match_text(row.get(inventory_field)) == value for inventory_field, value in expected)
|
||||||
]
|
]
|
||||||
|
evidence_scope = 'inventory_snapshot'
|
||||||
|
if not candidates:
|
||||||
|
# [STEP] 料号兜底(2026-10 需求):预约键在库存快照 0 行命中时,按料号键重筛证据行,
|
||||||
|
# 能唯一取值的字段不再要求人工手填。仅识别 field_code='part_number' 的匹配键;
|
||||||
|
# 匹配方案不含料号键则维持空候选(全人工补录,fail-closed)。
|
||||||
|
part_field_ids = {
|
||||||
|
int(field_id) for field_id, _value in expected
|
||||||
|
if str(field_id).strip().isdigit()
|
||||||
|
and str(getattr(db.session.get(ShippingInventoryField, int(field_id)), 'field_code', '') or '') == 'part_number'
|
||||||
|
}
|
||||||
|
if part_field_ids:
|
||||||
|
candidates = [
|
||||||
|
dict(row) for row in inventory_lines
|
||||||
|
if all(_match_text(row.get(str(field_id))) == value
|
||||||
|
for field_id, value in expected if int(field_id) in part_field_ids)
|
||||||
|
]
|
||||||
|
if candidates:
|
||||||
|
evidence_scope = 'part_fallback'
|
||||||
field_ids = {
|
field_ids = {
|
||||||
int(str(item.get('source_key') or '').strip())
|
int(str(item.get('source_key') or '').strip())
|
||||||
for item in mappings
|
for item in mappings
|
||||||
@@ -411,7 +439,7 @@ def _shortage_release_required_fields(
|
|||||||
mappings=mappings,
|
mappings=mappings,
|
||||||
candidates=candidates,
|
candidates=candidates,
|
||||||
field_labels=labels,
|
field_labels=labels,
|
||||||
)
|
), evidence_scope
|
||||||
|
|
||||||
|
|
||||||
def _manual_required_release_fields(fields: list[dict[str, Any]]) -> list[dict[str, str]]:
|
def _manual_required_release_fields(fields: list[dict[str, Any]]) -> list[dict[str, str]]:
|
||||||
@@ -429,7 +457,7 @@ def _manual_required_release_fields(fields: list[dict[str, Any]]) -> list[dict[s
|
|||||||
def _sync_confirmed_task_fulfillment_gates(
|
def _sync_confirmed_task_fulfillment_gates(
|
||||||
*,
|
*,
|
||||||
case: ShippingOrderReviewCase,
|
case: ShippingOrderReviewCase,
|
||||||
actor_id: int,
|
actor_id: int | None,
|
||||||
trigger: str = 'inventory_shortage_released',
|
trigger: str = 'inventory_shortage_released',
|
||||||
) -> None:
|
) -> None:
|
||||||
"""
|
"""
|
||||||
@@ -924,7 +952,8 @@ def project_review_case_line_decisions(
|
|||||||
release_line_index, release_snapshot_id, release_source_code = _release_fact_identity(fact)
|
release_line_index, release_snapshot_id, release_source_code = _release_fact_identity(fact)
|
||||||
if release_line_index is None:
|
if release_line_index is None:
|
||||||
release_line_index = draft_line.get('_line_index')
|
release_line_index = draft_line.get('_line_index')
|
||||||
release_template_fields = _shortage_release_required_fields(
|
# scope 仅在 decide 落库时写入审计快照;投影契约本期不新增字段。
|
||||||
|
release_template_fields, _evidence_scope = _shortage_release_required_fields(
|
||||||
task=task,
|
task=task,
|
||||||
line_index=release_line_index,
|
line_index=release_line_index,
|
||||||
inventory_snapshot_id=release_snapshot_id,
|
inventory_snapshot_id=release_snapshot_id,
|
||||||
@@ -1076,6 +1105,185 @@ def build_inventory_issue_fallback(
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_shortage_line_release(
|
||||||
|
task: ShippingNotice,
|
||||||
|
line_index: int,
|
||||||
|
release_field_values: dict[str, Any],
|
||||||
|
*,
|
||||||
|
evidence_scope: str | None = None,
|
||||||
|
actor_type: str = 'user',
|
||||||
|
actor_id: int | None = None,
|
||||||
|
auto_release: bool = False,
|
||||||
|
case: ShippingOrderReviewCase | None = None,
|
||||||
|
reason: str | None = None,
|
||||||
|
) -> ShippingOrderReviewLineDecision:
|
||||||
|
"""
|
||||||
|
人工 decide 与缺口自动放行共用的短缺放行执行体:解析证据字段、校验补录、
|
||||||
|
版本化落库、同步正式 OT 门禁并写审计。
|
||||||
|
|
||||||
|
核心逻辑:从 decide_review_line_fulfillment 放行分支原样提取(行为不变)。
|
||||||
|
证据字段按行事实快照解析(预约键命中 → inventory_snapshot;预约键 0 行命中
|
||||||
|
按料号键重筛 → part_fallback);落库快照 release_field_values 为「自动带出 +
|
||||||
|
人工补录」全量字段值字典(导出覆盖唯一来源);落库后立即重算任务履约态并
|
||||||
|
同步门禁/自动履约入队,与人工放行完全一致。终态/已决定行必须由调用方先跳过,
|
||||||
|
本执行体不重复校验放行资格。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
task: 正式 OT 聚合根(含 order_snapshot_id;自动放行来自匹配钩子,
|
||||||
|
人工 decide 来自 case.confirmed_task_id)。
|
||||||
|
line_index: 目标行号(0-based,与行匹配事实 line_index 同口径)。
|
||||||
|
release_field_values: 人工补录值(decide)或自动带出全量值(自动放行);
|
||||||
|
校验后与模板字段合并为全量值字典落库。
|
||||||
|
evidence_scope: 调用方已解析的证据范围;None 时按行事实重新解析
|
||||||
|
(人工 decide 路径,由本执行体统一解析避免双重查询语义分叉)。
|
||||||
|
actor_type: 决定来源('user' 人工 / 'system' 自动放行),写入 decision_source。
|
||||||
|
actor_id: 操作人(人工为操作用户;自动为触发匹配的用户,可为 None)。
|
||||||
|
auto_release: True 时在决定与审计快照标记 auto_release(系统自动放行溯源)。
|
||||||
|
case: 可选;人工 decide 已加载的可写 Case。缺省时按 confirmed_task_id 反查。
|
||||||
|
reason: 可选人工放行原因;自动放行为 None。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
新建的 ShippingOrderReviewLineDecision(已 flush、含主键)。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ConflictError: Case/草稿行缺失、证据不可解析或人工必填字段缺失。
|
||||||
|
"""
|
||||||
|
release_case = case if case is not None else resolve_review_case_for_task(task)
|
||||||
|
if release_case is None or getattr(release_case, 'id', None) is None:
|
||||||
|
raise ConflictError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
|
||||||
|
draft_line_by_index = {
|
||||||
|
int(row.get('_line_index')): (key, row)
|
||||||
|
for key, row in _draft_line_map(release_case).items()
|
||||||
|
if row.get('_line_index') is not None
|
||||||
|
}
|
||||||
|
pair = draft_line_by_index.get(int(line_index))
|
||||||
|
if pair is None:
|
||||||
|
raise ConflictError('Review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND')
|
||||||
|
key, draft_line = pair
|
||||||
|
|
||||||
|
from app.models import ShippingNoticeLineInventoryMatch
|
||||||
|
|
||||||
|
fact = (
|
||||||
|
ShippingNoticeLineInventoryMatch.query
|
||||||
|
.filter_by(task_id=int(task.id), line_index=int(line_index), is_current=True)
|
||||||
|
.first()
|
||||||
|
if getattr(task, 'id', None) is not None else None
|
||||||
|
)
|
||||||
|
release_line_index = getattr(fact, 'line_index', None) if fact is not None else int(line_index)
|
||||||
|
release_template_fields, resolved_scope = _shortage_release_required_fields(
|
||||||
|
task=task,
|
||||||
|
line_index=release_line_index,
|
||||||
|
inventory_snapshot_id=getattr(fact, 'inventory_snapshot_id', None) if fact is not None else None,
|
||||||
|
inventory_source_code=getattr(fact, 'inventory_source_code', None) if fact is not None else None,
|
||||||
|
)
|
||||||
|
release_evidence_scope = str(evidence_scope or resolved_scope or 'inventory_snapshot')
|
||||||
|
release_required_fields = _manual_required_release_fields(release_template_fields)
|
||||||
|
release_values = _validate_inventory_shortage_release_fields(
|
||||||
|
required_fields=release_required_fields,
|
||||||
|
supplied_values=release_field_values or {},
|
||||||
|
)
|
||||||
|
# [STEP] 落库为「自动带出 + 人工补录」全量模板字段值字典:人工提交值覆盖自动带出值
|
||||||
|
# (校验白名单仅用于必填校验,不再裁剪落库字典)。export.release_overrides_by_source_line
|
||||||
|
# 只读本字典——若仍落仅人工项,料号兜底/预约命中自动带出的字段在 Excel 证据列将为空。
|
||||||
|
manual_field_ids = {str(field.get('field_id') or '') for field in release_required_fields}
|
||||||
|
release_values = {
|
||||||
|
str(field.get('field_id') or ''): (
|
||||||
|
release_values[str(field.get('field_id') or '')]
|
||||||
|
if str(field.get('field_id') or '') in manual_field_ids
|
||||||
|
else (None if field.get('value') is None else str(field.get('value')))
|
||||||
|
)
|
||||||
|
for field in release_template_fields
|
||||||
|
}
|
||||||
|
|
||||||
|
projections = _line_projection_map(release_case)
|
||||||
|
proj = projections.get(key) or {}
|
||||||
|
from app.services.shipping_notice.order_review_workbench_projection import (
|
||||||
|
schema_fields_from_case,
|
||||||
|
)
|
||||||
|
|
||||||
|
schema_fields = schema_fields_from_case(release_case)
|
||||||
|
req_qty = _parse_qty(_line_required_qty(draft_line, proj, schema_fields=schema_fields))
|
||||||
|
avail_qty = _parse_qty(proj.get('available_qty'))
|
||||||
|
|
||||||
|
current = _active_decision(release_case, key)
|
||||||
|
# [STEP 1] 停用旧活动决定(放行资格与终态校验由调用方完成)。
|
||||||
|
if current is not None:
|
||||||
|
current.is_active = False
|
||||||
|
current.updated_at = datetime.utcnow()
|
||||||
|
|
||||||
|
status = _STATUS_BY_DECISION[DECISION_RELEASE_SHORTAGE]
|
||||||
|
row = ShippingOrderReviewLineDecision(
|
||||||
|
review_case_id=int(release_case.id),
|
||||||
|
draft_line_id=key,
|
||||||
|
line_index=draft_line.get('_line_index'),
|
||||||
|
decision_version=_next_version(release_case, key),
|
||||||
|
decision_code=DECISION_RELEASE_SHORTAGE,
|
||||||
|
decision_source=actor_type,
|
||||||
|
line_status=status,
|
||||||
|
is_active=True,
|
||||||
|
reason=str(reason or '').strip()[:2000] or None,
|
||||||
|
required_qty=str(req_qty) if req_qty is not None else None,
|
||||||
|
available_qty=str(avail_qty) if avail_qty is not None else (
|
||||||
|
str(proj.get('available_qty') or '').strip() or None
|
||||||
|
),
|
||||||
|
reservation_id=_line_reservation_id(draft_line, proj),
|
||||||
|
part_number=_line_part_number(
|
||||||
|
draft_line,
|
||||||
|
proj,
|
||||||
|
schema_fields=schema_fields,
|
||||||
|
),
|
||||||
|
actor_user_id=int(actor_id) if actor_id is not None else None,
|
||||||
|
snapshot_json={
|
||||||
|
'decision_code': DECISION_RELEASE_SHORTAGE,
|
||||||
|
'decision_source': actor_type,
|
||||||
|
'required_qty': str(req_qty) if req_qty is not None else None,
|
||||||
|
'available_qty': str(avail_qty) if avail_qty is not None else None,
|
||||||
|
'draft_line_id': key,
|
||||||
|
'release_field_values': release_values,
|
||||||
|
'release_required_fields': release_required_fields,
|
||||||
|
# 审计口径:放行证据来自预约匹配快照(inventory_snapshot)还是料号兜底重筛(part_fallback)。
|
||||||
|
'release_evidence_scope': release_evidence_scope,
|
||||||
|
**({'auto_release': True} if auto_release else {}),
|
||||||
|
},
|
||||||
|
created_at=datetime.utcnow(),
|
||||||
|
updated_at=datetime.utcnow(),
|
||||||
|
)
|
||||||
|
db.session.add(row)
|
||||||
|
# [STEP 2] 审计 after 投影依赖数据库分配的主键,必须先 flush。
|
||||||
|
db.session.flush()
|
||||||
|
# [BE-结案-豁免] 放行是库存充分性 Gate 的受控事实:决定落库后立即重算并触发编排。
|
||||||
|
_sync_confirmed_task_fulfillment_gates(
|
||||||
|
case=release_case,
|
||||||
|
actor_id=actor_id,
|
||||||
|
trigger='inventory_shortage_released',
|
||||||
|
)
|
||||||
|
|
||||||
|
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||||
|
|
||||||
|
record_fulfillment_audit(
|
||||||
|
event_type='review_line_fulfillment_decided',
|
||||||
|
aggregate_type='order_review_case',
|
||||||
|
aggregate_id=str(release_case.case_no),
|
||||||
|
action=DECISION_RELEASE_SHORTAGE,
|
||||||
|
actor_type=actor_type,
|
||||||
|
actor_id=int(actor_id) if actor_id is not None else None,
|
||||||
|
review_case_no=str(release_case.case_no),
|
||||||
|
run_no=str(release_case.run.run_no) if release_case.run is not None else None,
|
||||||
|
metadata={
|
||||||
|
'draft_line_id': key,
|
||||||
|
'decision_code': DECISION_RELEASE_SHORTAGE,
|
||||||
|
'decision_version': int(row.decision_version),
|
||||||
|
'line_status': status,
|
||||||
|
'release_field_count': len(release_values),
|
||||||
|
**({'auto_release': True} if auto_release else {}),
|
||||||
|
},
|
||||||
|
before=_serialize_decision(current) if current is not None else None,
|
||||||
|
after=_serialize_decision(row),
|
||||||
|
source='order_review_fulfillment_decision',
|
||||||
|
)
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
def decide_review_line_fulfillment(
|
def decide_review_line_fulfillment(
|
||||||
*,
|
*,
|
||||||
user_id: int,
|
user_id: int,
|
||||||
@@ -1100,7 +1308,9 @@ def decide_review_line_fulfillment(
|
|||||||
draft_line_id: 草稿行键。
|
draft_line_id: 草稿行键。
|
||||||
decision_code: 决定码。
|
decision_code: 决定码。
|
||||||
reason: 关闭/重开必填原因;短缺放行可选(人工放行事实由审计链记录)。
|
reason: 关闭/重开必填原因;短缺放行可选(人工放行事实由审计链记录)。
|
||||||
release_field_values: 短缺放行时模板行级库存字段的人工补录值。
|
release_field_values: 短缺放行时模板行级库存字段的人工补录值;落库快照
|
||||||
|
release_field_values 为「自动带出 + 人工补录」全量字段值字典(导出覆盖唯一来源),
|
||||||
|
release_evidence_scope 记录证据范围(inventory_snapshot / part_fallback)。
|
||||||
expected_draft_version: 可选草稿乐观锁。
|
expected_draft_version: 可选草稿乐观锁。
|
||||||
actor_is_admin: 是否管理员(重开授权)。
|
actor_is_admin: 是否管理员(重开授权)。
|
||||||
|
|
||||||
@@ -1200,93 +1410,94 @@ def decide_review_line_fulfillment(
|
|||||||
details={'draft_line_id': key},
|
details={'draft_line_id': key},
|
||||||
)
|
)
|
||||||
release_line_index = getattr(fact, 'line_index', None) if fact is not None else draft_line.get('_line_index')
|
release_line_index = getattr(fact, 'line_index', None) if fact is not None else draft_line.get('_line_index')
|
||||||
release_template_fields = _shortage_release_required_fields(
|
# [STEP] 短缺放行统一走共享执行体:证据字段解析、全量字段落库、停用旧决定、
|
||||||
task=task,
|
# 门禁同步与审计均在 _apply_shortage_line_release 内完成(人工与系统自动放行
|
||||||
line_index=release_line_index,
|
# 同一条链路,行为不变)。无 task 时上方放行资格校验已拒绝(无事实且无 RPA
|
||||||
inventory_snapshot_id=getattr(fact, 'inventory_snapshot_id', None) if fact is not None else None,
|
# 终态失败豁免),不会到达此处。
|
||||||
inventory_source_code=getattr(fact, 'inventory_source_code', None) if fact is not None else None,
|
row = _apply_shortage_line_release(
|
||||||
) if task is not None else []
|
task,
|
||||||
release_required_fields = _manual_required_release_fields(release_template_fields)
|
release_line_index,
|
||||||
release_values = _validate_inventory_shortage_release_fields(
|
release_field_values or {},
|
||||||
required_fields=release_required_fields,
|
actor_type='user',
|
||||||
supplied_values=release_field_values or {},
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
release_required_fields = []
|
|
||||||
release_values = {}
|
|
||||||
|
|
||||||
# [STEP 1] 停用旧活动决定
|
|
||||||
if current is not None:
|
|
||||||
current.is_active = False
|
|
||||||
current.updated_at = datetime.utcnow()
|
|
||||||
|
|
||||||
status = _STATUS_BY_DECISION.get(code, 'pending_decision')
|
|
||||||
row = ShippingOrderReviewLineDecision(
|
|
||||||
review_case_id=int(case.id),
|
|
||||||
draft_line_id=key,
|
|
||||||
line_index=draft_line.get('_line_index'),
|
|
||||||
decision_version=_next_version(case, key),
|
|
||||||
decision_code=code,
|
|
||||||
decision_source='user',
|
|
||||||
line_status=status,
|
|
||||||
is_active=True,
|
|
||||||
reason=str(reason or '').strip()[:2000] or None,
|
|
||||||
required_qty=str(req_qty) if req_qty is not None else None,
|
|
||||||
available_qty=str(avail_qty) if avail_qty is not None else (
|
|
||||||
str(proj.get('available_qty') or '').strip() or None
|
|
||||||
),
|
|
||||||
reservation_id=_line_reservation_id(draft_line, proj),
|
|
||||||
part_number=_line_part_number(
|
|
||||||
draft_line,
|
|
||||||
proj,
|
|
||||||
schema_fields=schema_fields,
|
|
||||||
),
|
|
||||||
actor_user_id=int(user_id),
|
|
||||||
snapshot_json={
|
|
||||||
'decision_code': code,
|
|
||||||
'decision_source': 'user',
|
|
||||||
'required_qty': str(req_qty) if req_qty is not None else None,
|
|
||||||
'available_qty': str(avail_qty) if avail_qty is not None else None,
|
|
||||||
'draft_line_id': key,
|
|
||||||
'release_field_values': release_values,
|
|
||||||
'release_required_fields': release_required_fields,
|
|
||||||
},
|
|
||||||
created_at=datetime.utcnow(),
|
|
||||||
updated_at=datetime.utcnow(),
|
|
||||||
)
|
|
||||||
db.session.add(row)
|
|
||||||
# [STEP 2] 审计 after 投影依赖数据库分配的主键,必须先 flush。
|
|
||||||
db.session.flush()
|
|
||||||
if code in {DECISION_RELEASE_SHORTAGE, DECISION_CLOSE}:
|
|
||||||
# [BE-结案-豁免] 结案与放行同为库存充分性 Gate 的受控事实:决定落库后立即重算并触发编排。
|
|
||||||
_sync_confirmed_task_fulfillment_gates(
|
|
||||||
case=case,
|
|
||||||
actor_id=int(user_id),
|
actor_id=int(user_id),
|
||||||
trigger='inventory_shortage_released' if code == DECISION_RELEASE_SHORTAGE else 'line_fulfillment_closed',
|
case=case,
|
||||||
|
reason=reason,
|
||||||
)
|
)
|
||||||
|
status = _STATUS_BY_DECISION[DECISION_RELEASE_SHORTAGE]
|
||||||
|
else:
|
||||||
|
# [STEP 1] 停用旧活动决定
|
||||||
|
if current is not None:
|
||||||
|
current.is_active = False
|
||||||
|
current.updated_at = datetime.utcnow()
|
||||||
|
|
||||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
status = _STATUS_BY_DECISION.get(code, 'pending_decision')
|
||||||
|
row = ShippingOrderReviewLineDecision(
|
||||||
|
review_case_id=int(case.id),
|
||||||
|
draft_line_id=key,
|
||||||
|
line_index=draft_line.get('_line_index'),
|
||||||
|
decision_version=_next_version(case, key),
|
||||||
|
decision_code=code,
|
||||||
|
decision_source='user',
|
||||||
|
line_status=status,
|
||||||
|
is_active=True,
|
||||||
|
reason=str(reason or '').strip()[:2000] or None,
|
||||||
|
required_qty=str(req_qty) if req_qty is not None else None,
|
||||||
|
available_qty=str(avail_qty) if avail_qty is not None else (
|
||||||
|
str(proj.get('available_qty') or '').strip() or None
|
||||||
|
),
|
||||||
|
reservation_id=_line_reservation_id(draft_line, proj),
|
||||||
|
part_number=_line_part_number(
|
||||||
|
draft_line,
|
||||||
|
proj,
|
||||||
|
schema_fields=schema_fields,
|
||||||
|
),
|
||||||
|
actor_user_id=int(user_id),
|
||||||
|
snapshot_json={
|
||||||
|
'decision_code': code,
|
||||||
|
'decision_source': 'user',
|
||||||
|
'required_qty': str(req_qty) if req_qty is not None else None,
|
||||||
|
'available_qty': str(avail_qty) if avail_qty is not None else None,
|
||||||
|
'draft_line_id': key,
|
||||||
|
'release_field_values': {},
|
||||||
|
'release_required_fields': [],
|
||||||
|
'release_evidence_scope': None,
|
||||||
|
},
|
||||||
|
created_at=datetime.utcnow(),
|
||||||
|
updated_at=datetime.utcnow(),
|
||||||
|
)
|
||||||
|
db.session.add(row)
|
||||||
|
# [STEP 2] 审计 after 投影依赖数据库分配的主键,必须先 flush。
|
||||||
|
db.session.flush()
|
||||||
|
if code == DECISION_CLOSE:
|
||||||
|
# [BE-结案-豁免] 结案是库存充分性 Gate 的受控事实:决定落库后立即重算并触发编排。
|
||||||
|
_sync_confirmed_task_fulfillment_gates(
|
||||||
|
case=case,
|
||||||
|
actor_id=int(user_id),
|
||||||
|
trigger='line_fulfillment_closed',
|
||||||
|
)
|
||||||
|
|
||||||
record_fulfillment_audit(
|
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||||
event_type='review_line_fulfillment_reopened' if code == DECISION_REOPEN else 'review_line_fulfillment_decided',
|
|
||||||
aggregate_type='order_review_case',
|
record_fulfillment_audit(
|
||||||
aggregate_id=str(case.case_no),
|
event_type='review_line_fulfillment_reopened' if code == DECISION_REOPEN else 'review_line_fulfillment_decided',
|
||||||
action=code,
|
aggregate_type='order_review_case',
|
||||||
actor_type='user',
|
aggregate_id=str(case.case_no),
|
||||||
actor_id=int(user_id),
|
action=code,
|
||||||
review_case_no=str(case.case_no),
|
actor_type='user',
|
||||||
run_no=str(case.run.run_no) if case.run is not None else None,
|
actor_id=int(user_id),
|
||||||
metadata={
|
review_case_no=str(case.case_no),
|
||||||
'draft_line_id': key,
|
run_no=str(case.run.run_no) if case.run is not None else None,
|
||||||
'decision_code': code,
|
metadata={
|
||||||
'decision_version': int(row.decision_version),
|
'draft_line_id': key,
|
||||||
'line_status': status,
|
'decision_code': code,
|
||||||
'release_field_count': len(release_values),
|
'decision_version': int(row.decision_version),
|
||||||
},
|
'line_status': status,
|
||||||
before=_serialize_decision(current) if current is not None else None,
|
'release_field_count': 0,
|
||||||
after=_serialize_decision(row),
|
},
|
||||||
source='order_review_fulfillment_decision',
|
before=_serialize_decision(current) if current is not None else None,
|
||||||
)
|
after=_serialize_decision(row),
|
||||||
|
source='order_review_fulfillment_decision',
|
||||||
|
)
|
||||||
|
|
||||||
from app.services.shipping_notice.order_review_resume_service import (
|
from app.services.shipping_notice.order_review_resume_service import (
|
||||||
attach_resume_outcome,
|
attach_resume_outcome,
|
||||||
@@ -1311,6 +1522,113 @@ def decide_review_line_fulfillment(
|
|||||||
return attach_resume_outcome(payload, resume)
|
return attach_resume_outcome(payload, resume)
|
||||||
|
|
||||||
|
|
||||||
|
def _active_decision_line_indexes(task: ShippingNotice) -> set[int]:
|
||||||
|
"""读取当前任务全部活动行决定的 line_index(含 release/close/fulfill 等一切决定)。
|
||||||
|
|
||||||
|
核心逻辑:自动放行只处理「无任何活动决定」的行——已放行、已结案、已入波次或
|
||||||
|
已有其他人工决定的行一律跳过,保证幂等且绝不自动撤销既有决定(与
|
||||||
|
``_released_snapshot_line_ids_for_task`` 同款 Case 反查口径)。
|
||||||
|
"""
|
||||||
|
from app.models import ShippingOrderReviewCase
|
||||||
|
|
||||||
|
if getattr(task, 'id', None) is None:
|
||||||
|
return set()
|
||||||
|
rows = (
|
||||||
|
ShippingOrderReviewLineDecision.query
|
||||||
|
.join(
|
||||||
|
ShippingOrderReviewCase,
|
||||||
|
ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id,
|
||||||
|
)
|
||||||
|
.filter(
|
||||||
|
ShippingOrderReviewCase.confirmed_task_id == int(task.id),
|
||||||
|
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||||
|
ShippingOrderReviewLineDecision.line_index.isnot(None),
|
||||||
|
)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
return {int(row.line_index) for row in rows}
|
||||||
|
|
||||||
|
|
||||||
|
def auto_release_part_fallback_shortages(
|
||||||
|
task: ShippingNotice,
|
||||||
|
*,
|
||||||
|
actor_id: int | None = None,
|
||||||
|
) -> list[int]:
|
||||||
|
"""
|
||||||
|
匹配落库后按料号兜底自动放行缺口行(用户确认语义:满足即自动放行,非仅可放行)。
|
||||||
|
|
||||||
|
核心逻辑:仅处理「ready + 缺口 + 料号总量≥需求 + 无活动决定 + 证据字段全部可
|
||||||
|
自动取值」的行;任一条件不满足(含证据解析 ConflictError)一律跳过并保持人工
|
||||||
|
路径,fail-closed 不变。复用 _apply_shortage_line_release,审计/门禁同步/自动
|
||||||
|
履约入队与人工放行完全一致;幂等由「无活动决定的行才处理」保证,不自动撤销
|
||||||
|
既有放行。注意:行匹配事实以 snapshot_line_id 为键,行号取自 fact['line_index']。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
task: 正式任务聚合根(OT 或正式 Notice,须含 id 与 order_snapshot_id)。
|
||||||
|
actor_id: 触发匹配的用户(审计归属);自动决定本身 actor_type='system'。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
自动放行的 line_index 列表(按行号升序)。
|
||||||
|
"""
|
||||||
|
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||||
|
load_current_match_facts_by_task,
|
||||||
|
)
|
||||||
|
|
||||||
|
task_id = getattr(task, 'id', None)
|
||||||
|
if task_id is None:
|
||||||
|
return []
|
||||||
|
facts = load_current_match_facts_by_task(int(task_id))
|
||||||
|
if not facts:
|
||||||
|
return []
|
||||||
|
decided_indexes = _active_decision_line_indexes(task)
|
||||||
|
ordered_facts = sorted(
|
||||||
|
(fact for fact in facts.values() if fact.get('line_index') is not None),
|
||||||
|
key=lambda fact: int(fact['line_index']),
|
||||||
|
)
|
||||||
|
released: list[int] = []
|
||||||
|
for fact in ordered_facts:
|
||||||
|
line_index = int(fact['line_index'])
|
||||||
|
try:
|
||||||
|
if line_index in decided_indexes:
|
||||||
|
continue
|
||||||
|
if not _is_shortage_match_fact(fact):
|
||||||
|
continue
|
||||||
|
required = _parse_qty(fact.get('required_qty'))
|
||||||
|
part_total = _parse_qty(fact.get('part_available_qty'))
|
||||||
|
if required is None or part_total is None or part_total < required:
|
||||||
|
# 料号兜底量缺失或不足 → 维持人工待处置(不得任取部分数量放行)。
|
||||||
|
continue
|
||||||
|
fields, evidence_scope = _shortage_release_required_fields(
|
||||||
|
task=task,
|
||||||
|
line_index=line_index,
|
||||||
|
inventory_snapshot_id=fact.get('inventory_snapshot_id'),
|
||||||
|
inventory_source_code=fact.get('inventory_source_code'),
|
||||||
|
)
|
||||||
|
if any(bool(field.get('requires_manual')) for field in fields):
|
||||||
|
# 证据字段无法唯一取值(requires_manual 残留)→ 降级人工放行,补录要求保留。
|
||||||
|
continue
|
||||||
|
auto_values = {
|
||||||
|
str(field.get('field_id') or ''): (
|
||||||
|
None if field.get('value') is None else str(field.get('value'))
|
||||||
|
)
|
||||||
|
for field in fields
|
||||||
|
}
|
||||||
|
_apply_shortage_line_release(
|
||||||
|
task,
|
||||||
|
line_index,
|
||||||
|
auto_values,
|
||||||
|
evidence_scope=evidence_scope,
|
||||||
|
actor_type='system',
|
||||||
|
actor_id=actor_id,
|
||||||
|
auto_release=True,
|
||||||
|
)
|
||||||
|
released.append(line_index)
|
||||||
|
except ConflictError:
|
||||||
|
# 证据不可解析(无源/模板未发布/无快照/草稿行缺失)→ 维持人工路径,不中断其余行。
|
||||||
|
continue
|
||||||
|
return released
|
||||||
|
|
||||||
|
|
||||||
def close_remaining_fulfillment(
|
def close_remaining_fulfillment(
|
||||||
*,
|
*,
|
||||||
user_id: int,
|
user_id: int,
|
||||||
|
|||||||
@@ -478,17 +478,22 @@ def inventory_preparation_primary_action(
|
|||||||
"""裁决库存准备 Gate 面向业务用户的主动作。
|
"""裁决库存准备 Gate 面向业务用户的主动作。
|
||||||
|
|
||||||
单源合并(用户拍板):库存失败只保留 2 个按钮 ——
|
单源合并(用户拍板):库存失败只保留 2 个按钮 ——
|
||||||
``retry_inventory_preparation``(直接重跑 RPA)与 ``retry_inventory_matching``
|
``retry_inventory_preparation``(显式重跑 RPA)与 ``retry_inventory_matching``
|
||||||
(优先复用已有快照并重匹配;无快照时 match_inventory 内部经 ensure_inventory 回退 RPA)。
|
(复用已抓取库存与字段映射并重匹配,不重抓,见 execute_stage_capability_rematch)。
|
||||||
已下线的 ``reload_inventory_result``(只重读)不再独立成主动作,其「复用快照」行为已并入
|
已下线的 ``reload_inventory_result``(只重读)不再独立成主动作,其「复用快照」行为已并入
|
||||||
``retry_inventory_matching``。
|
``retry_inventory_matching``。
|
||||||
|
边界(STP 多候选,ensure_inventory auto 模式):缺快照停人工待处理、不隐式触发 RPA。
|
||||||
|
因此获取库存未成功(无行级匹配结果)时,``retry_inventory_matching`` 由阶段能力禁用
|
||||||
|
(disabled_reason=no_match_result,见 ui_state._stage_capabilities_for_task),
|
||||||
|
重抓必须走显式的 ``retry_inventory_preparation``;本函数只裁决按钮位次,不禁用按钮。
|
||||||
"""
|
"""
|
||||||
normalized_status = str(status or '').strip().lower()
|
normalized_status = str(status or '').strip().lower()
|
||||||
normalized_reason = str(blocking_reason_code or '').strip().lower()
|
normalized_reason = str(blocking_reason_code or '').strip().lower()
|
||||||
if normalized_status == 'waiting_external':
|
if normalized_status == 'waiting_external':
|
||||||
return 'poll_inventory_preparation'
|
return 'poll_inventory_preparation'
|
||||||
if normalized_reason in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'}:
|
if normalized_reason in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'}:
|
||||||
# [MERGE] 超时/耗尽:优先复用已有快照重匹配,无则回退 RPA(retry_inventory_matching 自含)。
|
# [MERGE] 超时/耗尽:优先复用已有快照重匹配;无匹配结果时该按钮由阶段能力
|
||||||
|
# 禁用(no_match_result),显式重抓走侧路 retry_inventory_preparation。
|
||||||
return 'retry_inventory_matching'
|
return 'retry_inventory_matching'
|
||||||
if normalized_status in {'blocked_manual', 'blocked_retryable'}:
|
if normalized_status in {'blocked_manual', 'blocked_retryable'}:
|
||||||
return 'retry_inventory_preparation'
|
return 'retry_inventory_preparation'
|
||||||
|
|||||||
@@ -352,6 +352,13 @@ def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None:
|
|||||||
continue
|
continue
|
||||||
current = gate
|
current = gate
|
||||||
break
|
break
|
||||||
|
facts_before = (
|
||||||
|
execution.last_passed_gate_code,
|
||||||
|
execution.current_gate_code,
|
||||||
|
execution.primary_next_action_code,
|
||||||
|
execution.responsible_party,
|
||||||
|
execution.status,
|
||||||
|
)
|
||||||
execution.last_passed_gate_code = last_passed
|
execution.last_passed_gate_code = last_passed
|
||||||
if current is None:
|
if current is None:
|
||||||
execution.current_gate_code = None
|
execution.current_gate_code = None
|
||||||
@@ -359,7 +366,16 @@ def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None:
|
|||||||
execution.responsible_party = None
|
execution.responsible_party = None
|
||||||
if execution.status not in {'cancelled', 'failed'}:
|
if execution.status not in {'cancelled', 'failed'}:
|
||||||
execution.status = 'completed'
|
execution.status = 'completed'
|
||||||
_sync_order_task_stage_after_gate_refresh(execution)
|
_sync_order_task_stage_after_gate_refresh(
|
||||||
|
execution,
|
||||||
|
facts_changed=facts_before != (
|
||||||
|
execution.last_passed_gate_code,
|
||||||
|
execution.current_gate_code,
|
||||||
|
execution.primary_next_action_code,
|
||||||
|
execution.responsible_party,
|
||||||
|
execution.status,
|
||||||
|
),
|
||||||
|
)
|
||||||
return
|
return
|
||||||
execution.current_gate_code = current.gate_code
|
execution.current_gate_code = current.gate_code
|
||||||
execution.primary_next_action_code = current.next_action_code
|
execution.primary_next_action_code = current.next_action_code
|
||||||
@@ -376,10 +392,23 @@ def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None:
|
|||||||
# [OT SYNC] Gate 指针刷新后回写挂接 OT 的 stage/status,避免主卡/批次只读
|
# [OT SYNC] Gate 指针刷新后回写挂接 OT 的 stage/status,避免主卡/批次只读
|
||||||
# 投影停留在技术阶段(如 excel_generating),与当前 Gate 事实分叉。
|
# 投影停留在技术阶段(如 excel_generating),与当前 Gate 事实分叉。
|
||||||
# 仅已绑定任务时同步;建单前执行(无 task_id)自然跳过。延迟导入避免循环依赖。
|
# 仅已绑定任务时同步;建单前执行(无 task_id)自然跳过。延迟导入避免循环依赖。
|
||||||
_sync_order_task_stage_after_gate_refresh(execution)
|
_sync_order_task_stage_after_gate_refresh(
|
||||||
|
execution,
|
||||||
|
facts_changed=facts_before != (
|
||||||
|
execution.last_passed_gate_code,
|
||||||
|
execution.current_gate_code,
|
||||||
|
execution.primary_next_action_code,
|
||||||
|
execution.responsible_party,
|
||||||
|
execution.status,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _sync_order_task_stage_after_gate_refresh(execution: ShippingProcessExecution) -> None:
|
def _sync_order_task_stage_after_gate_refresh(
|
||||||
|
execution: ShippingProcessExecution,
|
||||||
|
*,
|
||||||
|
facts_changed: bool = False,
|
||||||
|
) -> None:
|
||||||
"""Gate 指针刷新后回写挂接 OT 的 stage/status(completed 与阻断两个出口共用)。"""
|
"""Gate 指针刷新后回写挂接 OT 的 stage/status(completed 与阻断两个出口共用)。"""
|
||||||
if getattr(execution, 'task_id', None) is None:
|
if getattr(execution, 'task_id', None) is None:
|
||||||
return
|
return
|
||||||
@@ -397,10 +426,38 @@ def _sync_order_task_stage_after_gate_refresh(execution: ShippingProcessExecutio
|
|||||||
if task is not None else None
|
if task is not None else None
|
||||||
)
|
)
|
||||||
if notice is not None:
|
if notice is not None:
|
||||||
|
version_before = int(getattr(task, 'progress_version', 0) or 0)
|
||||||
sync_order_task_stage_for_notice(notice, order_task=task)
|
sync_order_task_stage_for_notice(notice, order_task=task)
|
||||||
|
# 库存缺口/文件就绪等 Gate 事实变化但映射后 stage/status 未变时,仍须推进
|
||||||
|
# progress_version:工作台以该版本变化触发 [REFRESH_ON_CHANGE] 重拉任务详情,
|
||||||
|
# 版本冻结会让行级可用数量/缺口停留在上一次快照。
|
||||||
|
if (
|
||||||
|
facts_changed
|
||||||
|
and task is not None
|
||||||
|
and int(getattr(task, 'progress_version', 0) or 0) == version_before
|
||||||
|
):
|
||||||
|
_bump_order_task_progress_version(task)
|
||||||
elif task is not None:
|
elif task is not None:
|
||||||
# Notice 生成前只维护 OT 自身阶段;不能调用 Notice 专属映射。
|
# Notice 生成前只维护 OT 自身阶段;不能调用 Notice 专属映射。
|
||||||
task.stage = task.stage or 'notification_preparation'
|
task.stage = task.stage or 'notification_preparation'
|
||||||
|
# 无 Notice 绑定(通知准备/库存匹配常态)时上方 Notice 映射不存在,Gate 每次真实
|
||||||
|
# 推进都必须经中央写入口递增 progress_version,否则统一投影版本冻结,
|
||||||
|
# 前端轮询只更新右卡门禁、任务详情表格永不刷新。
|
||||||
|
if facts_changed:
|
||||||
|
_bump_order_task_progress_version(task)
|
||||||
|
|
||||||
|
|
||||||
|
def _bump_order_task_progress_version(task: ShippingOrderTask) -> None:
|
||||||
|
"""Gate 事实已变化但 stage/status 无值可变时,经中央写入口强制递增进度版本。"""
|
||||||
|
from app.services.shipping_notice.order_task_service import sync_order_task_processing_state
|
||||||
|
|
||||||
|
sync_order_task_processing_state(
|
||||||
|
task,
|
||||||
|
bump_progress=True,
|
||||||
|
force_progress_bump=True,
|
||||||
|
reason_code='gate_facts_advanced',
|
||||||
|
source='process_gate_service',
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def ensure_execution_for_workflow_version(
|
def ensure_execution_for_workflow_version(
|
||||||
|
|||||||
@@ -812,6 +812,11 @@ def apply_user_projection_fields(
|
|||||||
return 'waiting_human'
|
return 'waiting_human'
|
||||||
if unverified_upload_terminal:
|
if unverified_upload_terminal:
|
||||||
return 'waiting_human'
|
return 'waiting_human'
|
||||||
|
if gate_status in {'queued', 'running', 'waiting_external'}:
|
||||||
|
# Gate/Execution 在途 = 系统处理中:Notice 生成前 OT.status 会停留在建单前
|
||||||
|
# 的 waiting_review,不得据此把 RPA 自动推进误报成待人工——前端把
|
||||||
|
# waiting_human 视为终态并停止投影轮询,回调完成将永远无法被感知。
|
||||||
|
return 'running'
|
||||||
# 1) 终态短路:old_status completed/cancelled/failed
|
# 1) 终态短路:old_status completed/cancelled/failed
|
||||||
if old_status == 'completed':
|
if old_status == 'completed':
|
||||||
return 'completed'
|
return 'completed'
|
||||||
|
|||||||
@@ -29,12 +29,20 @@ from app.services.shipping_notice.audit_service import append_shipping_audit_eve
|
|||||||
|
|
||||||
|
|
||||||
def _read_receipt_callback_file(file_path: str) -> bytes:
|
def _read_receipt_callback_file(file_path: str) -> bytes:
|
||||||
"""只读取收料专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。"""
|
"""只读取收料专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。
|
||||||
|
|
||||||
|
路径契约为「drop 根内文件名」:Worker(Windows RPA 主机)与后端(Linux 容器)分属
|
||||||
|
两机,各自看到的根路径不同(C:\\HxopsRpaTest\\... vs /mnt/hxops-rpa-*-data/...),
|
||||||
|
Worker 只上报文件名,后端用自身挂载的 drop 根拼接定位;携带本机绝对路径的历史
|
||||||
|
载荷亦按末段文件名解析(2026-10-08 修复跨机成功回调全程 400 的事故)。
|
||||||
|
"""
|
||||||
configured_root = str(current_app.config.get('FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR') or '').strip()
|
configured_root = str(current_app.config.get('FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR') or '').strip()
|
||||||
if not configured_root:
|
if not configured_root:
|
||||||
raise ValidationError('receipt callback file root is unavailable', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID')
|
raise ValidationError('receipt callback file root is unavailable', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID')
|
||||||
root = Path(configured_root).resolve()
|
root = Path(configured_root).resolve()
|
||||||
path = Path(file_path).resolve()
|
# 容忍历史载荷携带 Windows 绝对路径:先归一分隔符再取末段文件名(防遍历,单一分段)。
|
||||||
|
name = Path(str(file_path).replace('\\', '/')).name
|
||||||
|
path = (root / name).resolve()
|
||||||
try:
|
try:
|
||||||
path.relative_to(root)
|
path.relative_to(root)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
|
|||||||
@@ -513,7 +513,7 @@ def _check_rpa_worker_ready_for_capability(
|
|||||||
required_capability: 必选 Worker 能力;空字符串表示不校验能力。
|
required_capability: 必选 Worker 能力;空字符串表示不校验能力。
|
||||||
extra_reasons: 调用方预检附加原因(凭据/队列等)。
|
extra_reasons: 调用方预检附加原因(凭据/队列等)。
|
||||||
worker_predicate: 可选过滤(如仅收料 Worker);不匹配的心跳不进入列表。
|
worker_predicate: 可选过滤(如仅收料 Worker);不匹配的心跳不进入列表。
|
||||||
require_sentinel: 是否要求共享哨兵(收料为 False)。
|
require_sentinel: 是否要求共享哨兵(库存/收料同口径均 True)。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
RpaWorkerReadiness。
|
RpaWorkerReadiness。
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ services/shipping_notice/stp_line_inventory_match.py
|
|||||||
__source_code(源已在选源/载入 Excel 时确定);多文件命中为冲突;唯一命中且数量充足则冻结
|
__source_code(源已在选源/载入 Excel 时确定);多文件命中为冲突;唯一命中且数量充足则冻结
|
||||||
resolved 源与行证据;多源可履约行暂停 Excel(step_payload 标记);人工指定源后
|
resolved 源与行证据;多源可履约行暂停 Excel(step_payload 标记);人工指定源后
|
||||||
forced_match_source_code 过滤库存行再匹配;结果写入 step_payload / line_results_json。
|
forced_match_source_code 过滤库存行再匹配;结果写入 step_payload / line_results_json。
|
||||||
|
行结果另含料号兜底总量 part_available_qty(允许源内、忽略预约号与单位的二次汇总)。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -77,6 +78,37 @@ def _inventory_row_qty(row: dict[str, Any]) -> Decimal:
|
|||||||
return Decimal('0')
|
return Decimal('0')
|
||||||
|
|
||||||
|
|
||||||
|
def _part_total_available_qty(
|
||||||
|
buckets: dict[tuple[str, str, str, str], dict[str, Any]],
|
||||||
|
*,
|
||||||
|
part: str,
|
||||||
|
allowed_source_codes: list[str],
|
||||||
|
has_candidate_scope: bool,
|
||||||
|
) -> Decimal | None:
|
||||||
|
"""
|
||||||
|
按料号(忽略预约号、不限单位)在该行允许源范围内汇总库存总可用量(料号兜底口径)。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
buckets: (reservation, part, unit, source) 聚合桶;unit 维度不参与过滤。
|
||||||
|
part: 归一化料号;空串返回 None。
|
||||||
|
allowed_source_codes: 该行冻结的候选源;仅 has_candidate_scope 时约束。
|
||||||
|
has_candidate_scope: 行是否携带候选源范围事实。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
料号总可用量(Decimal);缺料号返回 None。跨源不合并(multi_file_conflict 语义)。
|
||||||
|
"""
|
||||||
|
if not part:
|
||||||
|
return None
|
||||||
|
total = Decimal('0')
|
||||||
|
for key, bucket in buckets.items():
|
||||||
|
if key[1] != part:
|
||||||
|
continue
|
||||||
|
if has_candidate_scope and bucket['source_code'] and bucket['source_code'] not in allowed_source_codes:
|
||||||
|
continue
|
||||||
|
total += bucket['available_qty']
|
||||||
|
return total
|
||||||
|
|
||||||
|
|
||||||
def snapshot_header_reservation_id(snapshot: ShippingOrderSnapshot | None) -> str | None:
|
def snapshot_header_reservation_id(snapshot: ShippingOrderSnapshot | None) -> str | None:
|
||||||
"""
|
"""
|
||||||
从冻结 Snapshot 读取 Header 级 reservation_id。
|
从冻结 Snapshot 读取 Header 级 reservation_id。
|
||||||
@@ -275,6 +307,9 @@ def match_order_lines_across_candidates(
|
|||||||
|
|
||||||
核心逻辑:匹配键是 Reservation + Part(单位可选);库存源在选源/载入 Excel 时已确定,
|
核心逻辑:匹配键是 Reservation + Part(单位可选);库存源在选源/载入 Excel 时已确定,
|
||||||
库存行缺 ``__source_code`` 仍参与聚合。仅当行上显式带源码时,才用候选源范围过滤/判冲突。
|
库存行缺 ``__source_code`` 仍参与聚合。仅当行上显式带源码时,才用候选源范围过滤/判冲突。
|
||||||
|
料号兜底:仅 not_found(预约不匹配)/ok/shortage 行额外下发
|
||||||
|
``part_available_qty``(行允许源内、忽略预约号、不限单位的料号总可用量);
|
||||||
|
缺料号、invalid(超出候选范围)、multi_file_conflict、缺预约行不写该键,由下游按缺失→None 处理。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
order_lines: 含 part_number / reservation_id / quantity(或 qty)/ uom 的订单行。
|
order_lines: 含 part_number / reservation_id / quantity(或 qty)/ uom 的订单行。
|
||||||
@@ -348,6 +383,13 @@ def match_order_lines_across_candidates(
|
|||||||
else True
|
else True
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
|
# [STEP] 料号兜底总量:行允许源内、忽略预约号、不限单位,供预约不匹配/缺口行自动放行判断。
|
||||||
|
part_total = _part_total_available_qty(
|
||||||
|
buckets,
|
||||||
|
part=part,
|
||||||
|
allowed_source_codes=allowed_source_codes,
|
||||||
|
has_candidate_scope=has_candidate_scope,
|
||||||
|
)
|
||||||
|
|
||||||
if not effective or not part:
|
if not effective or not part:
|
||||||
disposition = 'not_found'
|
disposition = 'not_found'
|
||||||
@@ -408,6 +450,7 @@ def match_order_lines_across_candidates(
|
|||||||
'required_qty': float(required),
|
'required_qty': float(required),
|
||||||
'available_qty': 0.0,
|
'available_qty': 0.0,
|
||||||
'shortage_qty': float(required),
|
'shortage_qty': float(required),
|
||||||
|
'part_available_qty': float(part_total) if part_total is not None else None,
|
||||||
'line_status': 'shortage',
|
'line_status': 'shortage',
|
||||||
'disposition': disposition,
|
'disposition': disposition,
|
||||||
'resolved_inventory_source_code': None,
|
'resolved_inventory_source_code': None,
|
||||||
@@ -431,6 +474,7 @@ def match_order_lines_across_candidates(
|
|||||||
'required_qty': float(required),
|
'required_qty': float(required),
|
||||||
'available_qty': float(available),
|
'available_qty': float(available),
|
||||||
'shortage_qty': 0.0,
|
'shortage_qty': 0.0,
|
||||||
|
'part_available_qty': float(part_total) if part_total is not None else None,
|
||||||
'line_status': 'ok',
|
'line_status': 'ok',
|
||||||
'disposition': disposition,
|
'disposition': disposition,
|
||||||
'resolved_inventory_source_code': resolved_source,
|
'resolved_inventory_source_code': resolved_source,
|
||||||
@@ -453,6 +497,7 @@ def match_order_lines_across_candidates(
|
|||||||
'required_qty': float(required),
|
'required_qty': float(required),
|
||||||
'available_qty': float(available),
|
'available_qty': float(available),
|
||||||
'shortage_qty': float(max(required - available, Decimal('0'))),
|
'shortage_qty': float(max(required - available, Decimal('0'))),
|
||||||
|
'part_available_qty': float(part_total) if part_total is not None else None,
|
||||||
'line_status': 'partial' if available > 0 else 'shortage',
|
'line_status': 'partial' if available > 0 else 'shortage',
|
||||||
'disposition': disposition,
|
'disposition': disposition,
|
||||||
'resolved_inventory_source_code': resolved_source,
|
'resolved_inventory_source_code': resolved_source,
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ services/shipping_notice/ui_state.py
|
|||||||
+ 当前 Match 投影诚实反映最近一轮(Notice 经 order_task_id→OT),
|
+ 当前 Match 投影诚实反映最近一轮(Notice 经 order_task_id→OT),
|
||||||
行级拆 selected_source_code(CandidateSet 取数目标)与 source_code(Match 正式源);
|
行级拆 selected_source_code(CandidateSet 取数目标)与 source_code(Match 正式源);
|
||||||
短缺行复用放行模板字段;匹配成功无短缺下发 can_fulfill_complete_line;
|
短缺行复用放行模板字段;匹配成功无短缺下发 can_fulfill_complete_line;
|
||||||
|
prep 行直透投影 part_available_qty(料号兜底总量,仅库存就绪时非空)供前端「可用数量」列;
|
||||||
下发 source_options 与 capabilities(阶段能力,供右卡点击 stageCapabilityBypass);
|
下发 source_options 与 capabilities(阶段能力,供右卡点击 stageCapabilityBypass);
|
||||||
用户动作统一由 Gate 授权;build_task_ui_state 同请求内复用一次 Gate 摘要;
|
用户动作统一由 Gate 授权;build_task_ui_state 同请求内复用一次 Gate 摘要;
|
||||||
project_notice_available_actions 供货代上传聚合行内菜单轻量消费。
|
project_notice_available_actions 供货代上传聚合行内菜单轻量消费。
|
||||||
@@ -950,7 +951,8 @@ def _build_stage_context(
|
|||||||
release_line_index, release_snapshot_id, release_source_code = _release_fact_identity(fact)
|
release_line_index, release_snapshot_id, release_source_code = _release_fact_identity(fact)
|
||||||
if release_line_index is None and getattr(snapshot_line, 'position', None) is not None:
|
if release_line_index is None and getattr(snapshot_line, 'position', None) is not None:
|
||||||
release_line_index = int(snapshot_line.position)
|
release_line_index = int(snapshot_line.position)
|
||||||
release_template_fields = _shortage_release_required_fields(
|
# scope 仅在 decide 落库时写入审计快照;prep 行投影契约本期不新增字段。
|
||||||
|
release_template_fields, _evidence_scope = _shortage_release_required_fields(
|
||||||
task=order_task,
|
task=order_task,
|
||||||
line_index=release_line_index,
|
line_index=release_line_index,
|
||||||
inventory_snapshot_id=release_snapshot_id,
|
inventory_snapshot_id=release_snapshot_id,
|
||||||
@@ -976,6 +978,7 @@ def _build_stage_context(
|
|||||||
'required_qty': required_qty,
|
'required_qty': required_qty,
|
||||||
'available_qty': inv_view.get('available_qty'),
|
'available_qty': inv_view.get('available_qty'),
|
||||||
'shortage_qty': inv_view.get('shortage_qty'),
|
'shortage_qty': inv_view.get('shortage_qty'),
|
||||||
|
'part_available_qty': inv_view.get('part_available_qty'),
|
||||||
'source_code': source_code,
|
'source_code': source_code,
|
||||||
'selected_source_code': selected_source_code,
|
'selected_source_code': selected_source_code,
|
||||||
'status': inv_view.get('user_line_status'),
|
'status': inv_view.get('user_line_status'),
|
||||||
|
|||||||
@@ -4,11 +4,13 @@ backend/app/services/voucher_check/notification.py
|
|||||||
用途:立账凭证检核缺件通知、以及检核 / PO 生成排程的技术失败告警。
|
用途:立账凭证检核缺件通知、以及检核 / PO 生成排程的技术失败告警。
|
||||||
依赖:wecom_notify、notify_config_service、ScheduleTask.notify_user_ids_json、engine_persistence。
|
依赖:wecom_notify、notify_config_service、ScheduleTask.notify_user_ids_json、engine_persistence。
|
||||||
逻辑:缺件按文件类型接收人拆成每人一封,正文只含该人负责且本批缺失的类型;
|
逻辑:缺件按文件类型接收人拆成每人一封,正文只含该人负责且本批缺失的类型;
|
||||||
|
卡片标题为「销售开票附件缺件」,不写业务方代号和批次号;
|
||||||
排程「启用通知」为总开关;技术失败仍走排程通知人;domain_notification_managed 避免通用排程重复通知。
|
排程「启用通知」为总开关;技术失败仍走排程通知人;domain_notification_managed 避免通用排程重复通知。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Any
|
from typing import Any
|
||||||
@@ -23,6 +25,46 @@ from app.services.voucher_check.engine_persistence import persist_notification
|
|||||||
_TZ = ZoneInfo("Asia/Shanghai")
|
_TZ = ZoneInfo("Asia/Shanghai")
|
||||||
|
|
||||||
|
|
||||||
|
def _friendly_period_label(period_month: str) -> str:
|
||||||
|
"""
|
||||||
|
把 YYYY-MM 收成企微卡片上的中文年月。
|
||||||
|
核心逻辑:收件人看「2026年8月」,不看 2026-08;解析失败时保留原文。
|
||||||
|
"""
|
||||||
|
text = str(period_month or "").strip()
|
||||||
|
match = re.fullmatch(r"(\d{4})-(\d{2})", text)
|
||||||
|
if not match:
|
||||||
|
return text or "-"
|
||||||
|
return f"{int(match.group(1))}年{int(match.group(2))}月"
|
||||||
|
|
||||||
|
|
||||||
|
def _missing_type_line(item: dict[str, Any]) -> str:
|
||||||
|
"""一条缺件类型:名称、缺件份数、涉及发票张数。"""
|
||||||
|
name = str(item.get("name") or item.get("code") or "")
|
||||||
|
files = int(item.get("missing_file_count") or 0)
|
||||||
|
invoices = int(item.get("missing_invoice_count") or 0)
|
||||||
|
return f"{name}:缺 {files} 份,涉及 {invoices} 张发票"
|
||||||
|
|
||||||
|
|
||||||
|
def _missing_textcard(period_month: str, items: list[dict[str, Any]]) -> tuple[str, str]:
|
||||||
|
"""
|
||||||
|
组装销售开票附件缺件 textcard。
|
||||||
|
核心逻辑:用纯文本而不是 div 着色。企微 description 约 512 字节,
|
||||||
|
颜色标签会挤掉后面的缺件类型。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(title, description)
|
||||||
|
"""
|
||||||
|
body = "\n".join(
|
||||||
|
[
|
||||||
|
_friendly_period_label(period_month),
|
||||||
|
"销售开票附件已检核,你负责的类型还有缺件:",
|
||||||
|
*[_missing_type_line(item) for item in items],
|
||||||
|
"请尽快补齐。完整清单见详情里的 Excel。",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
return "销售开票附件缺件", body
|
||||||
|
|
||||||
|
|
||||||
def _users_by_ids(user_ids: list[int]) -> list[User]:
|
def _users_by_ids(user_ids: list[int]) -> list[User]:
|
||||||
"""按 id 取出已绑定企微的用户,保持传入顺序。"""
|
"""按 id 取出已绑定企微的用户,保持传入顺序。"""
|
||||||
if not user_ids:
|
if not user_ids:
|
||||||
@@ -84,7 +126,7 @@ def send_batch_missing_summary(
|
|||||||
) -> str:
|
) -> str:
|
||||||
"""
|
"""
|
||||||
按文件类型接收人发送缺件 textcard。
|
按文件类型接收人发送缺件 textcard。
|
||||||
核心逻辑:每人一封,只列出该人负责且本批缺失的类型;无缺件或无人可发则写审计不发空消息。
|
核心逻辑:每人一封,只列出该人负责且本批缺失的类型;标题写明销售开票附件,不写业务方代号和批次号。无缺件或无人可发则写审计不发空消息。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
send_status:sent / skipped_no_missing / skipped_no_recipients / skipped_disabled / failed
|
send_status:sent / skipped_no_missing / skipped_no_recipients / skipped_disabled / failed
|
||||||
@@ -177,19 +219,7 @@ def send_batch_missing_summary(
|
|||||||
sent_ids: list[int] = []
|
sent_ids: list[int] = []
|
||||||
for user in users:
|
for user in users:
|
||||||
items = plan["user_rules"].get(int(user.id)) or []
|
items = plan["user_rules"].get(int(user.id)) or []
|
||||||
type_lines = [
|
title, description = _missing_textcard(period_month, items)
|
||||||
f"{item['name']} {item['missing_file_count']} 份 / {item['missing_invoice_count']} 张 invoice"
|
|
||||||
for item in items
|
|
||||||
]
|
|
||||||
title = f"立账凭证缺件: {task.name}"
|
|
||||||
description = (
|
|
||||||
f"业务方 {profile_code}\n"
|
|
||||||
f"资料所属期间 {period_month}\n"
|
|
||||||
f"批次 {schedule_run.run_no}\n"
|
|
||||||
f"你负责的缺件:\n"
|
|
||||||
+ "\n".join(type_lines)
|
|
||||||
+ "\n明细以工作台 Excel 为准。"
|
|
||||||
)
|
|
||||||
trace_id = uuid.uuid4().hex
|
trace_id = uuid.uuid4().hex
|
||||||
jump_url = _build_jump_url(
|
jump_url = _build_jump_url(
|
||||||
"/workspace/accounting-voucher-check",
|
"/workspace/accounting-voucher-check",
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
"""add part_available_qty to shipping_notice_line_inventory_matches
|
||||||
|
|
||||||
|
Revision ID: 0a575f3afc32
|
||||||
|
Revises: 9e5045511198
|
||||||
|
Create Date: 2026-10-09 14:46:05.242283
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '0a575f3afc32'
|
||||||
|
down_revision = '9e5045511198'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
# 本迁移由 autogenerate 生成后人工裁剪:本地 dev 库与模型存在大量与本任务无关的
|
||||||
|
# 结构漂移,仅保留目标表新列(料号维度总可用量),其余漂移由后续专项迁移处理。
|
||||||
|
op.add_column('shipping_notice_line_inventory_matches', sa.Column('part_available_qty', sa.String(32), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
op.drop_column('shipping_notice_line_inventory_matches', 'part_available_qty')
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
"""
|
||||||
|
migrations/versions/b7a2b2155155_merge_migration_heads.py
|
||||||
|
|
||||||
|
用途:合并两条并行 Alembic head,恢复单 head 迁移图。
|
||||||
|
依赖:0a575f3afc32(shipping part_available_qty)、ea8c0a1b2c3d(设备验收快照)。
|
||||||
|
逻辑:两分支均 Revises 9e5045511198;本文件仅作图合并,upgrade/downgrade 为空操作。
|
||||||
|
|
||||||
|
Revision ID: b7a2b2155155
|
||||||
|
Revises: 0a575f3afc32, ea8c0a1b2c3d
|
||||||
|
Create Date: 2026-10-12 21:36:06.898157
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = "b7a2b2155155"
|
||||||
|
down_revision = ("0a575f3afc32", "ea8c0a1b2c3d")
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
"""空合并:两 head 无冲突 schema,仅统一 revision 图。"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
"""空合并:降级时 Alembic 回到两个并行 head。"""
|
||||||
|
pass
|
||||||
@@ -0,0 +1,247 @@
|
|||||||
|
"""设备验收预警同步快照与 Chat Agent。
|
||||||
|
|
||||||
|
Revision ID: ea8c0a1b2c3d
|
||||||
|
Revises: 9e5045511198
|
||||||
|
Create Date: 2026-10-08 15:30:00.000000
|
||||||
|
|
||||||
|
用途:一次建好设备验收快照、预警配置、发送记录,并注册 Chat Agent。
|
||||||
|
依赖:users、agents 表已存在。不改合同付款表。
|
||||||
|
逻辑:主表按流程实例 request_id 唯一;节点和操作人随主表级联删除。
|
||||||
|
发送记录按验收单和档位唯一,收件人明细 recipients_json 建表时一并创建。
|
||||||
|
无法验收说明 cannot_accept_note 来自 ycsm。配置表只插入 id=1,天数 30/37/44/51,岗位先空着。
|
||||||
|
发送时刻不在配置表。Agent 按 agent_code 复用已有实例;没有则插入。降级不删除 Agent。
|
||||||
|
不保存流程编号、第二合同编号、验收日期和 isremark。
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from sqlalchemy import text
|
||||||
|
|
||||||
|
|
||||||
|
revision = "ea8c0a1b2c3d"
|
||||||
|
down_revision = "9e5045511198"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
"""建快照、节点、操作人、发送记录和配置,并注册设备验收 Agent。"""
|
||||||
|
op.create_table(
|
||||||
|
"equipment_acceptance_orders",
|
||||||
|
sa.Column("id", sa.Integer(), primary_key=True),
|
||||||
|
sa.Column("acceptance_no", sa.String(length=128), nullable=True),
|
||||||
|
sa.Column("purchase_order_no", sa.String(length=128), nullable=True),
|
||||||
|
sa.Column("contract_no", sa.String(length=128), nullable=True),
|
||||||
|
sa.Column("timer_started_at", sa.DateTime(), nullable=True),
|
||||||
|
sa.Column("dwell_days", sa.Integer(), nullable=True),
|
||||||
|
sa.Column(
|
||||||
|
"can_accept",
|
||||||
|
sa.Integer(),
|
||||||
|
nullable=True,
|
||||||
|
comment="是否可以正常验收。0 否,1 是。空表示未标明。由 OA sfkyzcys 翻转,OA 为 0 是、1 否。",
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"is_returned",
|
||||||
|
sa.Integer(),
|
||||||
|
nullable=True,
|
||||||
|
comment="是否退回。0 否,1 是。由 OA sfzfth 翻转,OA 为 0 是、1 否;OA 空值收成 0。",
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"cannot_accept_note",
|
||||||
|
sa.Text(),
|
||||||
|
nullable=True,
|
||||||
|
comment="无法验收说明正文,来自 OA ft_gdzcysdv2.ycsm。只留痕,不单独触发停表。",
|
||||||
|
),
|
||||||
|
sa.Column("flow_status_raw", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("finished_at", sa.DateTime(), nullable=True),
|
||||||
|
sa.Column("request_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("request_match_count", sa.Integer(), nullable=False, server_default="0"),
|
||||||
|
sa.Column("owner_oa_id", sa.BigInteger(), nullable=True),
|
||||||
|
sa.Column("owner_name", sa.String(length=200), nullable=True),
|
||||||
|
sa.Column("owner_job_num", sa.String(length=64), nullable=True),
|
||||||
|
sa.Column("equip_oa_id", sa.BigInteger(), nullable=True),
|
||||||
|
sa.Column("equip_name", sa.String(length=200), nullable=True),
|
||||||
|
sa.Column("equip_job_num", sa.String(length=64), nullable=True),
|
||||||
|
sa.Column("applicant_oa_id", sa.BigInteger(), nullable=True),
|
||||||
|
sa.Column("applicant_name", sa.String(length=200), nullable=True),
|
||||||
|
sa.Column("applicant_job_num", sa.String(length=64), nullable=True),
|
||||||
|
sa.Column("monitor_status", sa.String(length=40), nullable=False),
|
||||||
|
sa.Column("present_in_source", sa.Boolean(), nullable=False, server_default=sa.true()),
|
||||||
|
sa.Column("synced_at", sa.DateTime(), nullable=False),
|
||||||
|
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||||
|
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||||
|
sa.UniqueConstraint("request_id", name="uq_equipment_acceptance_orders_request_id"),
|
||||||
|
)
|
||||||
|
op.create_index(
|
||||||
|
"ix_equipment_acceptance_orders_status",
|
||||||
|
"equipment_acceptance_orders",
|
||||||
|
["monitor_status"],
|
||||||
|
)
|
||||||
|
op.create_table(
|
||||||
|
"equipment_acceptance_nodes",
|
||||||
|
sa.Column("id", sa.Integer(), primary_key=True),
|
||||||
|
sa.Column("order_id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("node_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("node_name", sa.String(length=200), nullable=True),
|
||||||
|
sa.Column("node_type", sa.Integer(), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(["order_id"], ["equipment_acceptance_orders.id"], ondelete="CASCADE"),
|
||||||
|
sa.UniqueConstraint("order_id", "node_id", name="uq_equipment_acceptance_nodes_order_node"),
|
||||||
|
)
|
||||||
|
op.create_index("ix_equipment_acceptance_nodes_order", "equipment_acceptance_nodes", ["order_id"])
|
||||||
|
op.create_table(
|
||||||
|
"equipment_acceptance_operators",
|
||||||
|
sa.Column("id", sa.Integer(), primary_key=True),
|
||||||
|
sa.Column("order_id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("node_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("user_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("handler_name", sa.String(length=200), nullable=True),
|
||||||
|
sa.Column("handler_job_num", sa.String(length=64), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(["order_id"], ["equipment_acceptance_orders.id"], ondelete="CASCADE"),
|
||||||
|
)
|
||||||
|
op.create_index(
|
||||||
|
"ix_equipment_acceptance_operators_order",
|
||||||
|
"equipment_acceptance_operators",
|
||||||
|
["order_id"],
|
||||||
|
)
|
||||||
|
op.create_table(
|
||||||
|
"equipment_acceptance_send_records",
|
||||||
|
sa.Column("id", sa.Integer(), primary_key=True),
|
||||||
|
sa.Column("order_id", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("acceptance_no", sa.String(length=128), nullable=True),
|
||||||
|
sa.Column("purchase_order_no", sa.String(length=128), nullable=True),
|
||||||
|
sa.Column("tier", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("threshold_days", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("to_text", sa.Text(), nullable=True),
|
||||||
|
sa.Column("cc_text", sa.Text(), nullable=True),
|
||||||
|
sa.Column("recipients_json", sa.JSON(), nullable=True),
|
||||||
|
sa.Column("status", sa.String(length=32), nullable=False, server_default="pending"),
|
||||||
|
sa.Column("sent_at", sa.DateTime(), nullable=True),
|
||||||
|
sa.Column("error_message", sa.Text(), nullable=True),
|
||||||
|
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["order_id"],
|
||||||
|
["equipment_acceptance_orders.id"],
|
||||||
|
ondelete="SET NULL",
|
||||||
|
),
|
||||||
|
sa.UniqueConstraint(
|
||||||
|
"order_id",
|
||||||
|
"tier",
|
||||||
|
name="uq_equipment_acceptance_send_records_order_tier",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
op.create_index(
|
||||||
|
"ix_equipment_acceptance_send_records_created",
|
||||||
|
"equipment_acceptance_send_records",
|
||||||
|
["created_at"],
|
||||||
|
)
|
||||||
|
op.create_index(
|
||||||
|
"ix_equipment_acceptance_send_records_status",
|
||||||
|
"equipment_acceptance_send_records",
|
||||||
|
["status"],
|
||||||
|
)
|
||||||
|
op.create_table(
|
||||||
|
"equipment_acceptance_settings",
|
||||||
|
sa.Column("id", sa.Integer(), primary_key=True),
|
||||||
|
sa.Column("day_1", sa.Integer(), nullable=False, server_default="30"),
|
||||||
|
sa.Column("day_2", sa.Integer(), nullable=False, server_default="37"),
|
||||||
|
sa.Column("day_3", sa.Integer(), nullable=False, server_default="44"),
|
||||||
|
sa.Column("day_4", sa.Integer(), nullable=False, server_default="51"),
|
||||||
|
sa.Column("buyer_manager_user_id", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("coo_user_id", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("executive_user_id", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("updated_at", sa.DateTime(), nullable=True),
|
||||||
|
sa.Column("updated_by", sa.Integer(), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(["buyer_manager_user_id"], ["users.id"], ondelete="SET NULL"),
|
||||||
|
sa.ForeignKeyConstraint(["coo_user_id"], ["users.id"], ondelete="SET NULL"),
|
||||||
|
sa.ForeignKeyConstraint(["executive_user_id"], ["users.id"], ondelete="SET NULL"),
|
||||||
|
)
|
||||||
|
op.execute(
|
||||||
|
"INSERT INTO equipment_acceptance_settings (id, day_1, day_2, day_3, day_4) "
|
||||||
|
"VALUES (1, 30, 37, 44, 51)"
|
||||||
|
)
|
||||||
|
_seed_equipment_acceptance_agent()
|
||||||
|
|
||||||
|
|
||||||
|
def _resync_agents_id_sequence() -> None:
|
||||||
|
"""把 agents 主键序列对齐现有最大 id,避免 nextval 撞上已占用主键。"""
|
||||||
|
bind = op.get_bind()
|
||||||
|
if bind.dialect.name != "postgresql":
|
||||||
|
return
|
||||||
|
op.execute(
|
||||||
|
"""
|
||||||
|
SELECT setval(
|
||||||
|
pg_get_serial_sequence('public.agents', 'id'),
|
||||||
|
COALESCE((SELECT MAX(id) FROM public.agents), 1),
|
||||||
|
true
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _seed_equipment_acceptance_agent() -> None:
|
||||||
|
"""插入或复用设备验收预警 Agent。已有同编码实例时只更新入口配置。"""
|
||||||
|
conn = op.get_bind()
|
||||||
|
agent_id = conn.execute(
|
||||||
|
text(
|
||||||
|
"SELECT id FROM agents WHERE agent_code = :code "
|
||||||
|
"ORDER BY id ASC LIMIT 1"
|
||||||
|
),
|
||||||
|
{"code": "equipment_acceptance"},
|
||||||
|
).scalar()
|
||||||
|
if agent_id is not None:
|
||||||
|
conn.execute(
|
||||||
|
text(
|
||||||
|
"""
|
||||||
|
UPDATE agents
|
||||||
|
SET is_active = true,
|
||||||
|
name = :name,
|
||||||
|
description = :description,
|
||||||
|
runtime_provider = 'builtin',
|
||||||
|
conversation_mode = 'task_chat',
|
||||||
|
dify_app_type = 'chatflow',
|
||||||
|
updated_at = CURRENT_TIMESTAMP
|
||||||
|
WHERE id = :agent_id
|
||||||
|
"""
|
||||||
|
),
|
||||||
|
{
|
||||||
|
"agent_id": agent_id,
|
||||||
|
"name": "设备验收预警",
|
||||||
|
"description": "查看资产验收单停留天数,并从 E10 同步当前节点与操作人。",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
_resync_agents_id_sequence()
|
||||||
|
conn.execute(
|
||||||
|
text(
|
||||||
|
"""
|
||||||
|
INSERT INTO agents (
|
||||||
|
name, description, type, is_active, is_aggregate,
|
||||||
|
agent_code, runtime_provider, conversation_mode, dify_app_type,
|
||||||
|
suggested_questions_style, sort_order, created_at, updated_at
|
||||||
|
) VALUES (
|
||||||
|
:name, :description, 'api', true, false,
|
||||||
|
:code, 'builtin', 'task_chat', 'chatflow',
|
||||||
|
'plain', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
),
|
||||||
|
{
|
||||||
|
"name": "设备验收预警",
|
||||||
|
"description": "查看资产验收单停留天数,并从 E10 同步当前节点与操作人。",
|
||||||
|
"code": "equipment_acceptance",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
"""删除验收快照、配置和发送记录。不删除已创建的 Agent,以免误伤运营配置。"""
|
||||||
|
op.drop_index("ix_equipment_acceptance_send_records_status", table_name="equipment_acceptance_send_records")
|
||||||
|
op.drop_index("ix_equipment_acceptance_send_records_created", table_name="equipment_acceptance_send_records")
|
||||||
|
op.drop_table("equipment_acceptance_send_records")
|
||||||
|
op.drop_table("equipment_acceptance_settings")
|
||||||
|
op.drop_index("ix_equipment_acceptance_operators_order", table_name="equipment_acceptance_operators")
|
||||||
|
op.drop_table("equipment_acceptance_operators")
|
||||||
|
op.drop_index("ix_equipment_acceptance_nodes_order", table_name="equipment_acceptance_nodes")
|
||||||
|
op.drop_table("equipment_acceptance_nodes")
|
||||||
|
op.drop_index("ix_equipment_acceptance_orders_status", table_name="equipment_acceptance_orders")
|
||||||
|
op.drop_table("equipment_acceptance_orders")
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
|
|
||||||
flask
|
flask
|
||||||
flask-sqlalchemy
|
flask-sqlalchemy
|
||||||
|
# 2.1 起 postgresql:// 默认改用 psycopg(v3);本仓库只安装 psycopg2-binary。
|
||||||
|
sqlalchemy>=2.0.16,<2.1
|
||||||
flask-migrate
|
flask-migrate
|
||||||
flask-cors
|
flask-cors
|
||||||
psycopg2-binary
|
psycopg2-binary
|
||||||
|
|||||||
@@ -122,7 +122,8 @@ def test_create_matching_returns_envelope_with_matching_id(app, client, admin_he
|
|||||||
data = body["data"]
|
data = body["data"]
|
||||||
assert data["matching_id"].startswith("MTG-")
|
assert data["matching_id"].startswith("MTG-")
|
||||||
assert data["matching_hash"].startswith("sha256:")
|
assert data["matching_hash"].startswith("sha256:")
|
||||||
assert data["estimated_external_write_count"] == 2
|
# [2026-10-12 单据数口径修正] HOM-001/HOX-002 同五元组合并 1 张(原口径=行数 2)。
|
||||||
|
assert data["estimated_external_write_count"] == 1
|
||||||
assert body.get("request_id")
|
assert body.get("request_id")
|
||||||
|
|
||||||
|
|
||||||
@@ -625,6 +626,41 @@ def test_retry_rpa_parse_failed_still_failed_reports_not_ok(app, client, admin_h
|
|||||||
assert called["rpa"] == 0
|
assert called["rpa"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_retry_rpa_batch_requires_source_codes(app, client, admin_headers):
|
||||||
|
"""空 source_codes → 400(批量端点参数卡控)。"""
|
||||||
|
response = client.post(
|
||||||
|
f"{API_PREFIX}/sources/retry-rpa-batch", headers=admin_headers, json={"source_codes": []},
|
||||||
|
)
|
||||||
|
assert response.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
def test_retry_rpa_batch_delegates_to_batch_trigger_service(app, client, admin_headers, monkeypatch):
|
||||||
|
"""批量端点把 source_codes 原样交给 trigger_receipt_rpa_batch 并回传结果 envelope。"""
|
||||||
|
captured: dict = {}
|
||||||
|
|
||||||
|
def fake_batch(*, source_codes, business_date, reason):
|
||||||
|
captured.update(source_codes=source_codes, business_date=business_date, reason=reason)
|
||||||
|
return {
|
||||||
|
"ok": True, "triggered": True, "trigger_path": "/tmp/trigger.json",
|
||||||
|
"results": [{"source_code": code, "ok": True} for code in source_codes],
|
||||||
|
}
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
"app.services.in_transit_transfer.receipt_trigger_service.trigger_receipt_rpa_batch", fake_batch,
|
||||||
|
)
|
||||||
|
response = client.post(
|
||||||
|
f"{API_PREFIX}/sources/retry-rpa-batch", headers=admin_headers,
|
||||||
|
json={"source_codes": ["DSV360_AWSDU", "DSV360_AWSSG"]},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
body = response.get_json()["data"]
|
||||||
|
# [断言意图] 端点只做参数卡控与转发:来源列表原样下传、reason 固定业务语义。
|
||||||
|
assert captured["source_codes"] == ["DSV360_AWSDU", "DSV360_AWSSG"]
|
||||||
|
assert captured["reason"] == "transfer_retry_receipt"
|
||||||
|
assert body["ok"] is True and body["triggered"] is True
|
||||||
|
assert [item["source_code"] for item in body["results"]] == ["DSV360_AWSDU", "DSV360_AWSSG"]
|
||||||
|
|
||||||
|
|
||||||
def test_metrics_endpoint(app, transfer_db, client, admin_headers, transfer_deps):
|
def test_metrics_endpoint(app, transfer_db, client, admin_headers, transfer_deps):
|
||||||
"""运营指标端点:返回 Run/明细/待处理/通知失败结构。"""
|
"""运营指标端点:返回 Run/明细/待处理/通知失败结构。"""
|
||||||
response = client.get(f"{API_PREFIX}/metrics", headers=admin_headers)
|
response = client.get(f"{API_PREFIX}/metrics", headers=admin_headers)
|
||||||
|
|||||||
@@ -64,3 +64,29 @@ def test_executes_and_propagates_result_when_executable(monkeypatch):
|
|||||||
assert outcome.run_no == "RUN-20260928-XYZ789"
|
assert outcome.run_no == "RUN-20260928-XYZ789"
|
||||||
assert outcome.run_status == "success"
|
assert outcome.run_status == "success"
|
||||||
assert outcome.errors == []
|
assert outcome.errors == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_passes_receipt_date_range_to_matching(monkeypatch):
|
||||||
|
"""可选收料日期范围透传匹配层;缺省时为 None(=全部成熟积压)。"""
|
||||||
|
captured = {}
|
||||||
|
|
||||||
|
def _fake_create(**kwargs):
|
||||||
|
captured.update(kwargs)
|
||||||
|
return _summary(0)
|
||||||
|
|
||||||
|
monkeypatch.setattr(at, "create_matching", _fake_create)
|
||||||
|
|
||||||
|
at.run_auto_transfer(
|
||||||
|
business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False,
|
||||||
|
receipt_date_from="2026-09-01", receipt_date_to="2026-09-05",
|
||||||
|
)
|
||||||
|
# 断言:显式范围原样透传(成熟上限/起止合法性由匹配层 ValidationError 卡控)。
|
||||||
|
assert captured["receipt_date_from"] == "2026-09-01"
|
||||||
|
assert captured["receipt_date_to"] == "2026-09-05"
|
||||||
|
|
||||||
|
at.run_auto_transfer(
|
||||||
|
business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False,
|
||||||
|
)
|
||||||
|
# 断言:缺省(留空)不缩小匹配面,范围参数为 None。
|
||||||
|
assert captured["receipt_date_from"] is None
|
||||||
|
assert captured["receipt_date_to"] is None
|
||||||
@@ -85,7 +85,8 @@ def test_matching_action_streams_card(transfer_db, dbs_ready_file, monkeypatch):
|
|||||||
assert event.data["message_type"] == "transfer-match"
|
assert event.data["message_type"] == "transfer-match"
|
||||||
payload = event.data["payload"]
|
payload = event.data["payload"]
|
||||||
assert payload["kind"] == "match"
|
assert payload["kind"] == "match"
|
||||||
assert payload["summary"]["estimated_external_write_count"] == 2
|
# [2026-10-12 单据数口径修正] HOM-001/HOX-002 同五元组合并 1 张(原口径=行数 2)。
|
||||||
|
assert payload["summary"]["estimated_external_write_count"] == 1
|
||||||
assert {item["invoice_no"] for item in payload["items"]} == {"HOM-001", "HOX-002"}
|
assert {item["invoice_no"] for item in payload["items"]} == {"HOM-001", "HOX-002"}
|
||||||
assert payload["sources"][0]["source_code"] == "DBS-AWSBI"
|
assert payload["sources"][0]["source_code"] == "DBS-AWSBI"
|
||||||
|
|
||||||
|
|||||||
@@ -57,7 +57,9 @@ def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file)
|
|||||||
assert summary.counts.blocked_count == 0
|
assert summary.counts.blocked_count == 0
|
||||||
assert summary.status == "ready_to_execute"
|
assert summary.status == "ready_to_execute"
|
||||||
assert summary.matching_hash.startswith("sha256:")
|
assert summary.matching_hash.startswith("sha256:")
|
||||||
assert summary.estimated_external_write_count == 3
|
# [2026-10-12 单据数口径修正] 3 行可执行按执行建单五元组去重:DBS 两行
|
||||||
|
# 同(org,source,date,from,to)合并 1 张 + CRANE 1 行 1 张 = 2(原口径=行数 3)。
|
||||||
|
assert summary.estimated_external_write_count == 2
|
||||||
# 明细 DTO 决策 6/7:拨出/拨入仓库与数量对
|
# 明细 DTO 决策 6/7:拨出/拨入仓库与数量对
|
||||||
items = {item.invoice_no: item for item in result.items}
|
items = {item.invoice_no: item for item in result.items}
|
||||||
assert items["HOM-001"].from_warehouse == "DBS-TRANSIT"
|
assert items["HOM-001"].from_warehouse == "DBS-TRANSIT"
|
||||||
@@ -66,6 +68,61 @@ def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file)
|
|||||||
assert len(items["HOM-001"].raw_lines) == 2 # 多行汇总保留原始行
|
assert len(items["HOM-001"].raw_lines) == 2 # 多行汇总保留原始行
|
||||||
|
|
||||||
|
|
||||||
|
def test_estimated_document_count_merges_same_group(dbs_ready_file):
|
||||||
|
"""[2026-10-12 单据数口径修正] 预计 ERP 单据数按执行建单五元组去重。
|
||||||
|
|
||||||
|
场景:同源同日两张 Invoice,五元组(org, source, receipt_date, from, to)
|
||||||
|
全同 → 执行期合并一张 ERP 单,预估数 = 1 而非可执行行数 2;
|
||||||
|
并断言 DTO external_org 随路由解析透出(前端勾选行预估的分组输入)。
|
||||||
|
"""
|
||||||
|
deps, erp, _ = _deps(dbs_ready_file)
|
||||||
|
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||||
|
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||||
|
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||||
|
result = run_matching(
|
||||||
|
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||||
|
)
|
||||||
|
assert result.summary.counts.executable_count == 2
|
||||||
|
# HOM-001 与 HOX-002 同(HX-CN01, DBS-AWSBI, 2026-08-05, DBS-TRANSIT, HUB-CN01)。
|
||||||
|
assert result.summary.estimated_external_write_count == 1
|
||||||
|
items = {item.invoice_no: item for item in result.items}
|
||||||
|
assert items["HOM-001"].external_org == "HX-CN01"
|
||||||
|
assert items["HOX-002"].external_org == "HX-CN01"
|
||||||
|
|
||||||
|
|
||||||
|
def test_estimated_document_count_splits_by_receipt_date():
|
||||||
|
"""[2026-10-12 单据数口径修正] 同源同仓库但收料日期不同 → 五元组不同,预估 = 2。
|
||||||
|
|
||||||
|
锁定分组的日期维度:execution_service.prepare_execution 以 receipt_date 入键,
|
||||||
|
跨日行不合并单(预估数与执行建单数一致,不给用户错误预期)。
|
||||||
|
"""
|
||||||
|
deps, erp, _ = _deps({
|
||||||
|
"source_code": "DBS-AWSBI",
|
||||||
|
"business_date": "2026-08-06",
|
||||||
|
"file_purpose": "receipt",
|
||||||
|
"file_no": "REC-20260806-009",
|
||||||
|
"file_version": "v9",
|
||||||
|
"checksum": "e" * 64,
|
||||||
|
"status": "ready",
|
||||||
|
"rows": [
|
||||||
|
{"sheet": "Receipt", "row_no": 1, "doc_no": "HOM-A", "lot_no": "LOT-A",
|
||||||
|
"material_code": "MAT-001", "material_name": "连接器组件", "specification": "A 型 / 24PIN",
|
||||||
|
"movement_date": "2026-08-04", "quantity": "600", "unit": "个", "source_code": "DBS-AWSBI"},
|
||||||
|
{"sheet": "Receipt", "row_no": 2, "doc_no": "HOM-B", "lot_no": "LOT-B",
|
||||||
|
"material_code": "MAT-001", "material_name": "连接器组件", "specification": "A 型 / 24PIN",
|
||||||
|
"movement_date": "2026-08-05", "quantity": "600", "unit": "个", "source_code": "DBS-AWSBI"},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-A", "600")
|
||||||
|
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-B", "600")
|
||||||
|
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||||
|
result = run_matching(
|
||||||
|
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||||
|
)
|
||||||
|
assert result.summary.counts.executable_count == 2
|
||||||
|
assert result.summary.estimated_external_write_count == 2
|
||||||
|
|
||||||
|
|
||||||
def test_same_day_receipt_not_matured_no_erp_call(same_day_receipt_file):
|
def test_same_day_receipt_not_matured_no_erp_call(same_day_receipt_file):
|
||||||
"""当天收料 → not_matured,外部系统 调用次数为 0。"""
|
"""当天收料 → not_matured,外部系统 调用次数为 0。"""
|
||||||
deps, erp, _ = _deps(same_day_receipt_file)
|
deps, erp, _ = _deps(same_day_receipt_file)
|
||||||
|
|||||||
@@ -75,10 +75,22 @@ def test_invalid_quantity_rejected():
|
|||||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="abc"))
|
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="abc"))
|
||||||
|
|
||||||
|
|
||||||
def test_zero_quantity_rejected():
|
def test_zero_quantity_stamped_row_skipped():
|
||||||
"""0 数量必须阻断。"""
|
"""零数量收料行(日期已盖章、数量 0)为非可用收料事实:跳过不阻断(2026-10-08 CRANE WTP26082227 实测)。"""
|
||||||
with pytest.raises(ReceiptFileSchemaError):
|
parsed = parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="0"))
|
||||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="0"))
|
assert parsed == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_zero_quantity_rows_mixed_with_valid_rows_only_valid_parsed():
|
||||||
|
"""合法行与零数量行混排:只放行合法行,零数量行不阻断整文件。"""
|
||||||
|
rows = [
|
||||||
|
dict(VALID_ROW, row_no=788, invoice_no="WTP26082227", receipt_quantity="0",
|
||||||
|
receipt_date="2026-10-01 14:37:43"),
|
||||||
|
dict(VALID_ROW, row_no=789, invoice_no="INV-002", receipt_quantity="120"),
|
||||||
|
]
|
||||||
|
parsed = parse_receipt_rows(source_code="DBS-AWSBI", rows=rows)
|
||||||
|
assert [row.row_no for row in parsed] == [789]
|
||||||
|
assert parsed[0].invoice_no == "INV-002"
|
||||||
|
|
||||||
|
|
||||||
def test_negative_quantity_rejected():
|
def test_negative_quantity_rejected():
|
||||||
@@ -121,3 +133,19 @@ def test_error_carries_row_details():
|
|||||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(row_no=77, receipt_quantity="abc"))
|
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(row_no=77, receipt_quantity="abc"))
|
||||||
details = excinfo.value.details
|
details = excinfo.value.details
|
||||||
assert any(str(item.get("row_no")) == "77" for item in details.get("rows", []))
|
assert any(str(item.get("row_no")) == "77" for item in details.get("rows", []))
|
||||||
|
|
||||||
|
|
||||||
|
def test_schema_error_message_carries_row_details():
|
||||||
|
"""诊断落库:schema 失败消息必须携带前几条行级明细(行号+原因),随 parse_error_message 落库自描述。"""
|
||||||
|
rows = [
|
||||||
|
dict(VALID_ROW, row_no=5, invoice_no=""),
|
||||||
|
dict(VALID_ROW, row_no=9, receipt_quantity="abc"),
|
||||||
|
]
|
||||||
|
with pytest.raises(ReceiptFileSchemaError) as exc_info:
|
||||||
|
parse_receipt_rows(source_code="DBS-AWSBI", rows=rows)
|
||||||
|
# [断言意图] 消息不再只是通用 "receipt file schema invalid",须含行号与原因;
|
||||||
|
# 明细同时保留在 details.rows 供管理端展示。
|
||||||
|
text = str(exc_info.value) or (exc_info.value.message or "")
|
||||||
|
assert "row 5" in text and "missing_invoice_no" in text
|
||||||
|
detail_rows = (exc_info.value.details or {}).get("rows") or []
|
||||||
|
assert {"row_no": 5, "reason": "missing_invoice_no"} in detail_rows
|
||||||
@@ -1,11 +1,13 @@
|
|||||||
"""真实收料 RPA 触发服务测试。
|
"""真实收料 RPA 触发服务测试。
|
||||||
|
|
||||||
用途:验证 trigger_receipt_rpa 按来源装配收料 trigger unit 并调用写者;
|
用途:验证 trigger_receipt_rpa / trigger_receipt_rpa_batch 按来源装配收料 trigger unit
|
||||||
触发先落 ShippingReceiptRpaUnitRun(awaiting_rpa、真实 unit_run_id 进载荷);
|
并调用写者;触发先落 ShippingReceiptRpaUnitRun(awaiting_rpa、真实 unit_run_id 进载荷);
|
||||||
配置/来源/触发目录缺失时 fail-closed(ok=False 或单元标 failed)。
|
配置/来源/触发目录缺失时 fail-closed(ok=False 或单元标 failed)。
|
||||||
依赖:app(SQLite)fixture、receipt_trigger_service.trigger_receipt_rpa、
|
依赖:app(SQLite)fixture、receipt_trigger_service.trigger_receipt_rpa(_batch)、
|
||||||
既有测试种子(ShippingRpaProfile/ShippingInventorySource)。
|
既有测试种子(ShippingRpaProfile/ShippingInventorySource)。
|
||||||
逻辑:来源停用或收料配置缺失不写 trigger,返回 ok=False。
|
逻辑:来源停用或收料配置缺失不写 trigger,返回 ok=False;
|
||||||
|
批量触发多来源合并一个 batch trigger 文件(单源失败跳过不炸整批,
|
||||||
|
parse_failed 先本地重解析不触发 RPA)。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -13,7 +15,10 @@ from __future__ import annotations
|
|||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||||
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa
|
from app.services.in_transit_transfer.receipt_trigger_service import (
|
||||||
|
trigger_receipt_rpa,
|
||||||
|
trigger_receipt_rpa_batch,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
@@ -170,3 +175,157 @@ def test_trigger_receipt_rpa_marks_unit_failed_when_trigger_unavailable(app, rec
|
|||||||
ShippingReceiptRpaUnitRun.id.desc()).first()
|
ShippingReceiptRpaUnitRun.id.desc()).first()
|
||||||
assert unit.status == "failed"
|
assert unit.status == "failed"
|
||||||
assert unit.error_code == "RPA_RECEIPT_TRIGGER_UNAVAILABLE"
|
assert unit.error_code == "RPA_RECEIPT_TRIGGER_UNAVAILABLE"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 批量触发(trigger_receipt_rpa_batch):多来源合并一个 batch trigger 文件,
|
||||||
|
# Worker 单次浏览器会话串行处理(2026-10-09 批量重试效率修复)。
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def second_receipt_source(app):
|
||||||
|
"""再造一个启用来源 + 收料配置(批量用例需要多来源);启用态必须绑定
|
||||||
|
解析规则/Excel 模板(ck_shipping_inventory_sources_enabled_bindings),复用种子源绑定。"""
|
||||||
|
from app import db
|
||||||
|
from app.models import ShippingInventorySource, ShippingRpaProfile, ShippingReceiptReportConfig
|
||||||
|
|
||||||
|
seed = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first()
|
||||||
|
profile = ShippingRpaProfile(
|
||||||
|
profile_code='DBS_SG_TEST', display_name='DBS SG', connector_type='dbs',
|
||||||
|
login_url='https://test.invalid/dbs-sg', login_config_json={'auth_mode': 'password'},
|
||||||
|
)
|
||||||
|
source = ShippingInventorySource(
|
||||||
|
source_code='DSV360_AWSSG', display_name='DBS SG AWSSG', connector_type='dbs',
|
||||||
|
rpa_profile=profile,
|
||||||
|
parsing_profile=seed.parsing_profile, excel_template=seed.excel_template,
|
||||||
|
warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSSG',
|
||||||
|
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
|
||||||
|
enabled=True,
|
||||||
|
)
|
||||||
|
db.session.add_all([profile, source])
|
||||||
|
db.session.flush() # 先取 source.id(新建对象 flush 前无主键)
|
||||||
|
config = ShippingReceiptReportConfig(
|
||||||
|
inventory_source_id=source.id,
|
||||||
|
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
|
||||||
|
query_parameters_json=[],
|
||||||
|
)
|
||||||
|
db.session.add(config)
|
||||||
|
db.session.commit()
|
||||||
|
return source
|
||||||
|
|
||||||
|
|
||||||
|
def test_trigger_receipt_rpa_batch_writes_one_trigger_for_all_units(app, receipt_source, second_receipt_source):
|
||||||
|
"""多来源 → 只写一次 trigger(一个文件 N units),各单元独立 callback_id/unit_run_id。"""
|
||||||
|
from app.models import ShippingReceiptRpaUnitRun
|
||||||
|
|
||||||
|
calls: list = []
|
||||||
|
|
||||||
|
def fake_writer(run_no, units, payload=None):
|
||||||
|
calls.append({'run_no': run_no, 'units': units, 'payload': payload or {}})
|
||||||
|
return f'/tmp/trigger/{run_no}.json'
|
||||||
|
|
||||||
|
outcome = trigger_receipt_rpa_batch(
|
||||||
|
source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-09',
|
||||||
|
reason='transfer_retry_receipt', writer=fake_writer,
|
||||||
|
)
|
||||||
|
# [断言意图] 合并单文件是本修复的核心:writer 恰好调用 1 次、units 装下全部来源。
|
||||||
|
assert len(calls) == 1
|
||||||
|
assert outcome['ok'] is True and outcome['triggered'] is True
|
||||||
|
assert calls[0]['run_no'].startswith('TRIG-BATCH-')
|
||||||
|
assert [u['source_code'] for u in calls[0]['units']] == ['DSV360_AWSDU', 'DSV360_AWSSG']
|
||||||
|
assert calls[0]['payload']['schema_version'] == 'shipping_receipt_rpa.v1'
|
||||||
|
# 每单元独立回调身份,且单元行先落库(回调按 callback_id 可达)。
|
||||||
|
callback_ids = {u['callback_id'] for u in calls[0]['units']}
|
||||||
|
assert len(callback_ids) == 2
|
||||||
|
rows = ShippingReceiptRpaUnitRun.query.filter(ShippingReceiptRpaUnitRun.source_code.in_(
|
||||||
|
['DSV360_AWSDU', 'DSV360_AWSSG'])).all()
|
||||||
|
assert {row.status for row in rows} == {'awaiting_rpa'}
|
||||||
|
assert all(row.schedule_run_id is None for row in rows)
|
||||||
|
assert {row.id for row in rows} == {u['unit_run_id'] for u in calls[0]['units']}
|
||||||
|
|
||||||
|
|
||||||
|
def test_trigger_receipt_rpa_batch_skips_invalid_source(app, receipt_source):
|
||||||
|
"""单源配置缺失 → 跳过该源并逐源记录 error_code,其余来源照常进 batch trigger。"""
|
||||||
|
captured: dict = {}
|
||||||
|
|
||||||
|
def fake_writer(run_no, units, payload=None):
|
||||||
|
captured['units'] = units
|
||||||
|
return f'/tmp/trigger/{run_no}.json'
|
||||||
|
|
||||||
|
outcome = trigger_receipt_rpa_batch(
|
||||||
|
source_codes=['DSV360_AWSDU', 'DSV360_NOPE'], business_date='2026-10-09',
|
||||||
|
writer=fake_writer,
|
||||||
|
)
|
||||||
|
# [断言意图] 来源级隔离:坏源不炸整批,trigger 只含有效源;结果逐源如实分层。
|
||||||
|
assert outcome['ok'] is True and outcome['triggered'] is True
|
||||||
|
assert [u['source_code'] for u in captured['units']] == ['DSV360_AWSDU']
|
||||||
|
by_code = {item['source_code']: item for item in outcome['results']}
|
||||||
|
assert by_code['DSV360_AWSDU']['ok'] is True
|
||||||
|
assert by_code['DSV360_NOPE']['ok'] is False
|
||||||
|
assert by_code['DSV360_NOPE']['error_code'] == 'RPA_RECEIPT_CONFIG_MISSING'
|
||||||
|
|
||||||
|
|
||||||
|
def test_trigger_receipt_rpa_batch_all_invalid_no_trigger(app):
|
||||||
|
"""全部来源无效 → 不写 trigger,ok=False + RPA_RECEIPT_NO_TRIGGERABLE_SOURCE。"""
|
||||||
|
outcome = trigger_receipt_rpa_batch(
|
||||||
|
source_codes=['DSV360_NOPE'], business_date='2026-10-09',
|
||||||
|
writer=lambda *a, **k: (_ for _ in ()).throw(AssertionError('writer must not be called')),
|
||||||
|
)
|
||||||
|
assert outcome['ok'] is False and outcome['triggered'] is False
|
||||||
|
assert outcome['error_code'] == 'RPA_RECEIPT_NO_TRIGGERABLE_SOURCE'
|
||||||
|
|
||||||
|
|
||||||
|
def test_trigger_receipt_rpa_batch_writer_unavailable_marks_all_failed(app, receipt_source, second_receipt_source):
|
||||||
|
"""trigger 目录不可用 → 本批全部单元标 failed,不留永久 awaiting 幽灵。"""
|
||||||
|
from app.models import ShippingReceiptRpaUnitRun
|
||||||
|
|
||||||
|
outcome = trigger_receipt_rpa_batch(
|
||||||
|
source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-09',
|
||||||
|
writer=lambda *a, **k: None,
|
||||||
|
)
|
||||||
|
assert outcome['ok'] is False and outcome['triggered'] is False
|
||||||
|
assert outcome['error_code'] == 'RPA_RECEIPT_TRIGGER_UNAVAILABLE'
|
||||||
|
rows = ShippingReceiptRpaUnitRun.query.filter(ShippingReceiptRpaUnitRun.source_code.in_(
|
||||||
|
['DSV360_AWSDU', 'DSV360_AWSSG'])).all()
|
||||||
|
assert {row.status for row in rows} == {'failed'}
|
||||||
|
assert {row.error_code for row in rows} == {'RPA_RECEIPT_TRIGGER_UNAVAILABLE'}
|
||||||
|
|
||||||
|
|
||||||
|
def test_trigger_receipt_rpa_batch_parse_failed_reparses_without_rpa(app, receipt_source, monkeypatch):
|
||||||
|
"""parse_failed 来源先本地重解析(成功则不触发 RPA),与单来源端点分层语义一致。"""
|
||||||
|
statuses = {
|
||||||
|
'DSV360_AWSDU': [
|
||||||
|
{'file_status': 'parse_failed', 'file_sha256': 'abc'},
|
||||||
|
{'file_status': 'ready', 'file_sha256': 'abc'},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
def fake_resolve(*, source_code):
|
||||||
|
# [断言意图] 解析失败分层:首次投影 parse_failed 触发本地重解析,
|
||||||
|
# sync 后再查投影回 ready——该来源不得进入 batch trigger。
|
||||||
|
queue = statuses.get(source_code)
|
||||||
|
if queue and len(queue) > 1:
|
||||||
|
return queue.pop(0)
|
||||||
|
return queue[0] if queue else {'file_status': 'none'}
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
'app.services.in_transit_transfer.source_file_status.resolve_source_file_status', fake_resolve,
|
||||||
|
)
|
||||||
|
synced: list = []
|
||||||
|
monkeypatch.setattr(
|
||||||
|
'app.services.in_transit_transfer.evidence_sync.sync_and_commit_for_callback',
|
||||||
|
lambda *, source_code, business_date, now: synced.append(source_code) or True,
|
||||||
|
)
|
||||||
|
|
||||||
|
def fake_writer(run_no, units, payload=None):
|
||||||
|
raise AssertionError('reparsed source must not be triggered via RPA')
|
||||||
|
|
||||||
|
outcome = trigger_receipt_rpa_batch(
|
||||||
|
source_codes=['DSV360_AWSDU'], business_date='2026-10-09', writer=fake_writer,
|
||||||
|
)
|
||||||
|
# [断言意图] 重解析恢复 ready → 无需写盘,整体 ok=True(请求已达成目的)。
|
||||||
|
assert synced == ['DSV360_AWSDU']
|
||||||
|
assert outcome['ok'] is True and outcome['triggered'] is False
|
||||||
|
assert outcome['results'] == [{
|
||||||
|
'source_code': 'DSV360_AWSDU', 'ok': True, 'reparsed': True, 'file_status': 'ready',
|
||||||
|
}]
|
||||||
@@ -29,7 +29,9 @@ def test_transfer_job_registered_with_schedule_defaults():
|
|||||||
assert job is not None
|
assert job is not None
|
||||||
assert job.enabled
|
assert job.enabled
|
||||||
keys = {field.get("key") for field in job.params_schema}
|
keys = {field.get("key") for field in job.params_schema}
|
||||||
assert {"source_codes", "recover_history"} <= keys
|
assert {"source_codes", "recover_history", "receipt_from_offset_days", "receipt_to_offset_days"} <= keys
|
||||||
|
# 断言:任务级通知人已移除——通知统一走排程「启用通知」,防止参数回归。
|
||||||
|
assert "notify_user_ids" not in keys
|
||||||
assert not re.search(r"\d{2}:\d{2}", job.description), "描述禁止硬编码执行时刻"
|
assert not re.search(r"\d{2}:\d{2}", job.description), "描述禁止硬编码执行时刻"
|
||||||
|
|
||||||
|
|
||||||
@@ -123,17 +125,8 @@ def test_wanted_source_codes_falls_back_when_empty(monkeypatch):
|
|||||||
assert _wanted_source_codes(string_param) == ["DBS_HUB"]
|
assert _wanted_source_codes(string_param) == ["DBS_HUB"]
|
||||||
|
|
||||||
|
|
||||||
class _FakeSender:
|
def test_handler_empty_data_day_stays_silent(monkeypatch):
|
||||||
"""记录实例化的发送器替身(断言 handler 接线,不发真实消息)。"""
|
"""空数据日(无 run_no 且无 errors):不传领域通知参数,置静默标记抑制框架完成卡(C5)。"""
|
||||||
|
|
||||||
instantiated = 0
|
|
||||||
|
|
||||||
def __init__(self):
|
|
||||||
type(self).instantiated += 1
|
|
||||||
|
|
||||||
|
|
||||||
def test_handler_wires_sender_and_domain_notification(monkeypatch):
|
|
||||||
"""配了通知人:构造 sender、置领域自管标记、recipients 透传。"""
|
|
||||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||||
from app.models import ScheduleRun, ScheduleTask
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
|
|
||||||
@@ -147,28 +140,32 @@ def test_handler_wires_sender_and_domain_notification(monkeypatch):
|
|||||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||||
|
|
||||||
class _FakeSenderInner:
|
task = ScheduleTask(job_params={"source_codes": [], "recover_history": True})
|
||||||
pass
|
|
||||||
|
|
||||||
monkeypatch.setattr(job_mod, "WecomSummarySender", _FakeSenderInner)
|
|
||||||
|
|
||||||
task = ScheduleTask(job_params={"source_codes": [], "recover_history": True, "notify_user_ids": ["7"]})
|
|
||||||
run = ScheduleRun(run_no="RUNR-1", status="running")
|
run = ScheduleRun(run_no="RUNR-1", status="running")
|
||||||
total, success, failed, skipped, results, warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
|
total, success, failed, skipped, results, warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
|
||||||
|
|
||||||
|
# 断言:领域通知接线已移除(不再透传 sender/recipients);空数据日置 C5 静默标记。
|
||||||
|
assert "sender" not in captured
|
||||||
|
assert "recipients" not in captured
|
||||||
|
assert captured["receipt_date_from"] is None
|
||||||
|
assert captured["receipt_date_to"] is None
|
||||||
assert captured["source_codes"] == ["CRANE_SGP"]
|
assert captured["source_codes"] == ["CRANE_SGP"]
|
||||||
assert captured["recipients"] == ["7"]
|
assert captured["recover_history"] is True
|
||||||
assert isinstance(captured["sender"], _FakeSenderInner)
|
|
||||||
assert run.response_summary_json["domain_notification_managed"] is True
|
assert run.response_summary_json["domain_notification_managed"] is True
|
||||||
assert (total, success, failed, skipped) == (0, 0, 0, 0)
|
assert (total, success, failed, skipped) == (0, 0, 0, 0)
|
||||||
|
assert results == []
|
||||||
|
assert any("no executable items" in w for w in warnings)
|
||||||
|
|
||||||
|
|
||||||
def test_handler_without_recipients_skips_domain_notification(monkeypatch):
|
def test_handler_converts_t_minus_offsets(monkeypatch):
|
||||||
"""未配通知人:sender=None、不置标记、落回框架通用通知(由框架按任务配置发送)。"""
|
"""T−N 偏移天数按执行日业务日换算为具体收料日期透传;留空为 None。"""
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||||
from app.models import ScheduleRun, ScheduleTask
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
|
|
||||||
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
|
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||||
|
monkeypatch.setattr(job_mod, "business_date_now", lambda: date(2026, 10, 12))
|
||||||
captured = {}
|
captured = {}
|
||||||
|
|
||||||
def _fake_auto_transfer(**kwargs):
|
def _fake_auto_transfer(**kwargs):
|
||||||
@@ -178,43 +175,91 @@ def test_handler_without_recipients_skips_domain_notification(monkeypatch):
|
|||||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||||
|
|
||||||
|
task = ScheduleTask(job_params={"receipt_from_offset_days": 4, "receipt_to_offset_days": 2})
|
||||||
|
run = ScheduleRun(run_no="RUNR-4", status="running")
|
||||||
|
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||||
|
|
||||||
|
# 断言:T=2026-10-12,起4止2 换算为 T−4~T−2 的具体日期透传匹配层。
|
||||||
|
assert captured["business_date"] == "2026-10-12"
|
||||||
|
assert captured["receipt_date_from"] == "2026-10-08"
|
||||||
|
assert captured["receipt_date_to"] == "2026-10-10"
|
||||||
|
|
||||||
|
|
||||||
|
def test_handler_rejects_invalid_offset_without_execution(monkeypatch):
|
||||||
|
"""偏移非法(负数/非整数):快速失败不执行,错误走框架失败通知。"""
|
||||||
|
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||||
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
|
|
||||||
|
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||||
|
|
||||||
|
def _must_not_run(**kwargs):
|
||||||
|
raise AssertionError("run_auto_transfer must not run with invalid offsets")
|
||||||
|
|
||||||
|
monkeypatch.setattr(job_mod, "run_auto_transfer", _must_not_run)
|
||||||
|
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||||
|
|
||||||
|
run = ScheduleRun(run_no="RUNR-5", status="running")
|
||||||
|
task = ScheduleTask(job_params={"receipt_from_offset_days": -1})
|
||||||
|
_total, _success, _failed, _skipped, results, _warnings, errors = (
|
||||||
|
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||||
|
)
|
||||||
|
# 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名。
|
||||||
|
assert results == []
|
||||||
|
assert any("收料日期起点" in e for e in errors)
|
||||||
|
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||||
|
|
||||||
|
task = ScheduleTask(job_params={"receipt_to_offset_days": 2.5})
|
||||||
|
_total, _success, _failed, _skipped, _results, _warnings, errors = (
|
||||||
|
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||||
|
)
|
||||||
|
# 断言:小数偏移同样快速失败。
|
||||||
|
assert any("收料日期终点" in e for e in errors)
|
||||||
|
|
||||||
|
|
||||||
|
def test_handler_run_day_uses_framework_notification(monkeypatch):
|
||||||
|
"""有 Run(成功):不置静默标记,框架完成卡按排程「启用通知」照常发送。"""
|
||||||
|
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||||
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
|
|
||||||
|
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||||
|
|
||||||
|
def _fake_auto_transfer(**kwargs):
|
||||||
|
return job_mod.AutoTransferOutcome(run_no="TR-1", run_status="success")
|
||||||
|
|
||||||
|
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||||
|
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||||
|
|
||||||
task = ScheduleTask(job_params={})
|
task = ScheduleTask(job_params={})
|
||||||
run = ScheduleRun(run_no="RUNR-2", status="running")
|
run = ScheduleRun(run_no="RUNR-2", status="running")
|
||||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
total, success, failed, skipped, results, _warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
|
||||||
|
|
||||||
assert captured["sender"] is None
|
# 断言:有 run 不抑制框架通知;run_no 落入 results 供完成卡/留痕展示。
|
||||||
assert captured["recipients"] == []
|
|
||||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||||
|
assert results and results[0]["run_no"] == "TR-1"
|
||||||
|
assert (total, success, failed, skipped) == (1, 1, 0, 0)
|
||||||
|
assert errors == []
|
||||||
|
|
||||||
|
|
||||||
def test_handler_hard_failure_keeps_framework_notification(monkeypatch):
|
def test_handler_hard_failure_keeps_framework_notification(monkeypatch):
|
||||||
"""硬失败(有通知人、无 run_no、有 errors):仍构造并传入 sender,但不置自管标记。"""
|
"""硬失败(无 run_no、有 errors):不置静默标记,框架完成卡兜底告警。"""
|
||||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||||
from app.models import ScheduleRun, ScheduleTask
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
|
|
||||||
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
|
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||||
captured = {}
|
|
||||||
|
|
||||||
def _fake_auto_transfer(**kwargs):
|
def _fake_auto_transfer(**kwargs):
|
||||||
captured.update(kwargs)
|
|
||||||
return job_mod.AutoTransferOutcome(errors=["match pipeline boom"])
|
return job_mod.AutoTransferOutcome(errors=["match pipeline boom"])
|
||||||
|
|
||||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||||
|
|
||||||
class _FakeSenderInner:
|
task = ScheduleTask(job_params={})
|
||||||
pass
|
|
||||||
|
|
||||||
monkeypatch.setattr(job_mod, "WecomSummarySender", _FakeSenderInner)
|
|
||||||
|
|
||||||
task = ScheduleTask(job_params={"notify_user_ids": ["7"]})
|
|
||||||
run = ScheduleRun(run_no="RUNR-3", status="running")
|
run = ScheduleRun(run_no="RUNR-3", status="running")
|
||||||
_total, _success, _failed, _skipped, _results, _warnings, errors = (
|
_total, _success, _failed, _skipped, results, _warnings, errors = (
|
||||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||||
)
|
)
|
||||||
|
|
||||||
# 断言:sender 已构造并透传;硬失败不抑制框架完成卡。
|
# 断言:硬失败不抑制框架完成卡(兜底告警),errors 原样上抛、无 results。
|
||||||
assert isinstance(captured["sender"], _FakeSenderInner)
|
|
||||||
assert captured["recipients"] == ["7"]
|
|
||||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||||
|
assert results == []
|
||||||
assert errors == ["match pipeline boom"]
|
assert errors == ["match pipeline boom"]
|
||||||
@@ -207,3 +207,14 @@ def test_record_and_clear_parse_failure_roundtrip(app, receipt_unit_run):
|
|||||||
clear_receipt_parse_failure(report=report)
|
clear_receipt_parse_failure(report=report)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
assert resolve_source_file_status(source_code=SOURCE_CODE)["file_status"] == "ready"
|
assert resolve_source_file_status(source_code=SOURCE_CODE)["file_status"] == "ready"
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_unit_is_no_data(app, receipt_unit_run):
|
||||||
|
"""空数据单元(抓取成功、当日无收料记录)→ no_data,不得与抓取失败混淆。"""
|
||||||
|
from app import db
|
||||||
|
|
||||||
|
receipt_unit_run.status = 'empty'
|
||||||
|
db.session.commit()
|
||||||
|
status = resolve_source_file_status(source_code=SOURCE_CODE)
|
||||||
|
assert status['file_status'] == 'no_data'
|
||||||
|
assert status['has_ready_file'] is False
|
||||||
@@ -3,7 +3,7 @@ backend/tests/test_contract_payment_parse.py
|
|||||||
|
|
||||||
用途:验证合同付款预警解析器、三轮预警升级、ERP 金额匹配、周汇总摘要及企微 Excel 收件人列。
|
用途:验证合同付款预警解析器、三轮预警升级、ERP 金额匹配、周汇总摘要及企微 Excel 收件人列。
|
||||||
依赖:contract_payment.parse_service、alert_service、erp_payment_service、supervisor_oa_service(三轮测试 mock)、openpyxl。
|
依赖:contract_payment.parse_service、alert_service、erp_payment_service、supervisor_oa_service(三轮测试 mock)、openpyxl。
|
||||||
逻辑:覆盖确定性解析边界、pending 计数与下一次周五 18:00;三轮升级 mock OA 矩阵,不调用外部 OA、文档库或企业微信;Excel 用例只断言「收件人」列为真实姓名;失败原因用例只断言轨迹归类;OA 金额为 0 时断言正文正数回写台账;合同原文被清理后断言按附件 ID 重新下载;OA「公司」决定 ERP 账套,同一采购单号不能跨账套记成已付。
|
逻辑:覆盖确定性解析边界、pending 计数与下一次周五 18:00;三轮升级 mock OA 矩阵,不调用外部 OA、文档库或企业微信;Excel 用例只断言「收件人」列为真实姓名;失败原因用例只断言轨迹归类;OA 金额为 0 时断言正文正数回写台账;合同原文被清理后断言按附件 ID 重新下载;OA「公司」决定 ERP 账套,同一采购单号不能跨账套记成已付;增值税税率和「收到定金后 N 天」不计入付款比例。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
@@ -443,6 +443,38 @@ def test_conflicting_shipment_percentages_report_duplicate_once():
|
|||||||
assert not any(node["node_type"] == "shipment" for node in result["nodes"])
|
assert not any(node["node_type"] == "shipment" for node in result["nodes"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_vat_rate_beside_deposit_schedule_is_not_prepayment_percentage():
|
||||||
|
"""关键断言:完成日期「收到定金后135天」后的含13%增值税不算预付款,结算条款的定金30%仍保留。"""
|
||||||
|
result = parse_contract_text(
|
||||||
|
"设备定作合同 收到定金后 135天 合计(人民币大写)壹佰伍拾伍万元整(含13%增值税) "
|
||||||
|
"四、结算方式及期限:甲方支付乙方定金:¥465,000.00元(总价款的30%),"
|
||||||
|
"甲方支付乙方发货款:¥930,000.00元(总价款的60%),"
|
||||||
|
"验收款(总价款的10%)¥155,000.00元。"
|
||||||
|
"设备总价款(含税):1550000.00元"
|
||||||
|
)
|
||||||
|
|
||||||
|
percentages = {node["node_type"]: node["percentage"] for node in result["nodes"]}
|
||||||
|
assert percentages["prepayment"] == "30"
|
||||||
|
assert percentages["shipment"] == "60"
|
||||||
|
assert percentages["acceptance"] == "10"
|
||||||
|
assert "warranty" not in percentages
|
||||||
|
assert "预付款付款比例重复,需人工确认" not in result["issues"]
|
||||||
|
assert "付款阶段比例无法识别:质保款" in result["issues"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_tax_rate_in_same_clause_does_not_hide_payment_percentage():
|
||||||
|
"""关键断言:同一句里先写含13%增值税、再写总价款30%时,预付款取30%,不取税率。"""
|
||||||
|
result = parse_contract_text(
|
||||||
|
"采购协议 合同号:HT-2026-006;合同总价:100,000元;"
|
||||||
|
"定金(含13%增值税)为总价款的30%;出货款40%;验收款20%;质保款10%;交货期:2026年09月01日。"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result["status"] == "parsed"
|
||||||
|
prepayment = next(item for item in result["nodes"] if item["node_type"] == "prepayment")
|
||||||
|
assert prepayment["percentage"] == "30"
|
||||||
|
assert "预付款付款比例重复,需人工确认" not in result["issues"]
|
||||||
|
|
||||||
|
|
||||||
def test_dms_resolve_year_folder_uses_configured_root(app, monkeypatch):
|
def test_dms_resolve_year_folder_uses_configured_root(app, monkeypatch):
|
||||||
"""关键断言:DMS 先用根 FolderID 查年份目录,并返回目录记录 ID。"""
|
"""关键断言:DMS 先用根 FolderID 查年份目录,并返回目录记录 ID。"""
|
||||||
app.config.update(
|
app.config.update(
|
||||||
|
|||||||
@@ -78,6 +78,38 @@ def test_friendly_workflow_failure_message_rewrites_tool_error_with_current_agen
|
|||||||
assert message == '员工培训查询工具调用失败,请稍后重试;如持续失败请联系管理员。'
|
assert message == '员工培训查询工具调用失败,请稍后重试;如持续失败请联系管理员。'
|
||||||
|
|
||||||
|
|
||||||
|
def test_friendly_workflow_failure_message_identifies_knowledge_retrieval_failure():
|
||||||
|
"""知识检索节点失败应说明是知识库,而不是笼统的查询失败。"""
|
||||||
|
message = DifyService._friendly_workflow_failure_message(
|
||||||
|
'Node knowledge-retrieval run failed: dataset not found',
|
||||||
|
agent_name='研发培训',
|
||||||
|
)
|
||||||
|
assert message == '研发培训的知识库检索失败,请稍后重试;如持续失败请联系管理员检查知识库与模型配置。'
|
||||||
|
|
||||||
|
|
||||||
|
def test_friendly_stream_request_failure_message_distinguishes_timeout():
|
||||||
|
"""连接 Dify 读超时应提示等待超时,且不带异常原文。"""
|
||||||
|
import requests
|
||||||
|
|
||||||
|
message = DifyService._friendly_stream_request_failure_message(
|
||||||
|
requests.exceptions.ReadTimeout('read timed out'),
|
||||||
|
agent_name='研发培训',
|
||||||
|
)
|
||||||
|
assert message == '研发培训等待 AI 服务响应超时,请稍后重试。'
|
||||||
|
assert 'read timed out' not in message
|
||||||
|
|
||||||
|
|
||||||
|
def test_present_stream_error_message_keeps_rerank_authorization_copy():
|
||||||
|
"""流内 error 事件里的重排 403 应沿用授权失败文案。"""
|
||||||
|
message = DifyService._present_stream_error_message(
|
||||||
|
'PluginInvokeError: 403 Forbidden for url https://api.example/v1/rerank',
|
||||||
|
400,
|
||||||
|
'研发培训',
|
||||||
|
)
|
||||||
|
assert '知识检索重排服务授权失败' in message
|
||||||
|
assert 'https://api.example' not in message
|
||||||
|
|
||||||
|
|
||||||
def test_friendly_upstream_error_message_identifies_rerank_authorization_failure():
|
def test_friendly_upstream_error_message_identifies_rerank_authorization_failure():
|
||||||
"""断言:Dify 重排插件 403 应提示修复模型授权,而非误导为网络超时。"""
|
"""断言:Dify 重排插件 403 应提示修复模型授权,而非误导为网络超时。"""
|
||||||
message = DifyService._friendly_upstream_error_message(
|
message = DifyService._friendly_upstream_error_message(
|
||||||
|
|||||||
@@ -448,3 +448,167 @@ def test_fill_multi_value_js_uses_entry_text_not_bare_text():
|
|||||||
# 禁止在 checkbox 循环里出现未绑定的 `text`(旧脚本 ReferenceError)。
|
# 禁止在 checkbox 循环里出现未绑定的 `text`(旧脚本 ReferenceError)。
|
||||||
assert "desiredValues.includes(text" not in source
|
assert "desiredValues.includes(text" not in source
|
||||||
assert "normalize(text)" not in source or "entryText" in source
|
assert "normalize(text)" not in source or "entryText" in source
|
||||||
|
|
||||||
|
|
||||||
|
class _RecordingFrame:
|
||||||
|
"""脚本化 frame:evaluate 返回预置结果或抛预置异常,并记录收到的 label。"""
|
||||||
|
|
||||||
|
def __init__(self, result=None, error: Exception | None = None):
|
||||||
|
self._result = result
|
||||||
|
self._error = error
|
||||||
|
self.calls: list[str] = []
|
||||||
|
|
||||||
|
def evaluate(self, script: str, label: str):
|
||||||
|
self.calls.append(label)
|
||||||
|
if self._error is not None:
|
||||||
|
raise self._error
|
||||||
|
return self._result
|
||||||
|
|
||||||
|
|
||||||
|
class _RecordingPage:
|
||||||
|
def __init__(self, frames):
|
||||||
|
self.frames = frames
|
||||||
|
|
||||||
|
|
||||||
|
_STRUCTURAL_CONTROLS = {
|
||||||
|
"text": "#ReportViewerMain_ctl08_ctl15_txtValue",
|
||||||
|
"toggle": "#ReportViewerMain_ctl08_ctl15_ctl01",
|
||||||
|
"dropdown": "#ReportViewerMain_ctl08_ctl15_divDropDown",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_structural_resolver_hit_returns_controls_and_trims_label():
|
||||||
|
"""命中 frame 返回三件套;label 先 trim 再传入页面脚本。"""
|
||||||
|
module = _load_module()
|
||||||
|
early = _RecordingFrame(result=None)
|
||||||
|
hit = _RecordingFrame(result=dict(_STRUCTURAL_CONTROLS))
|
||||||
|
page = _RecordingPage([early, hit])
|
||||||
|
|
||||||
|
got = module.resolve_parameter_controls_structural(page, " Owner ")
|
||||||
|
|
||||||
|
assert got == _STRUCTURAL_CONTROLS
|
||||||
|
assert hit.calls == ["Owner"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_structural_resolver_all_frames_miss_or_error_returns_none():
|
||||||
|
"""全部 frame 未命中或探测异常(跨域/销毁帧):返回 None 交调用方回退。"""
|
||||||
|
module = _load_module()
|
||||||
|
page = _RecordingPage([
|
||||||
|
_RecordingFrame(result=None),
|
||||||
|
_RecordingFrame(error=RuntimeError("execution context destroyed")),
|
||||||
|
_RecordingFrame(result=None),
|
||||||
|
])
|
||||||
|
assert module.resolve_parameter_controls_structural(page, "Owner") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_structural_resolver_empty_label_short_circuits():
|
||||||
|
"""空标签短路:不打扰任何 frame。"""
|
||||||
|
module = _load_module()
|
||||||
|
frame = _RecordingFrame(result=dict(_STRUCTURAL_CONTROLS))
|
||||||
|
page = _RecordingPage([frame])
|
||||||
|
assert module.resolve_parameter_controls_structural(page, " ") is None
|
||||||
|
assert frame.calls == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_structural_resolver_none_page_returns_none():
|
||||||
|
"""无页面上下文(纯函数调用):直接返回 None。"""
|
||||||
|
module = _load_module()
|
||||||
|
assert module.resolve_parameter_controls_structural(None, "Owner") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_fill_multi_select_template_miss_falls_back_to_structural(monkeypatch):
|
||||||
|
"""接线:报表模板未命中 Owner 时,落到结构性解析并把三件套传入 multi_value 填充。
|
||||||
|
|
||||||
|
[断言意图] 2026-10-08 事故回归:Owner@Receipt Detail@AWSRTM 未登记 ctl15 模板时,
|
||||||
|
不得静默失败弃填(导致全货主巨报表渲染超时),必须结构性解析后正常填充。
|
||||||
|
"""
|
||||||
|
module = _load_module()
|
||||||
|
captured: dict[str, object] = {}
|
||||||
|
|
||||||
|
def _fake_fill(page, label, values, *, timeout_ms, config_override, select_all):
|
||||||
|
captured.update(config_override)
|
||||||
|
return True
|
||||||
|
|
||||||
|
monkeypatch.setattr(module, "resolve_parameter_controls", lambda *a, **k: {})
|
||||||
|
probe = _RecordingFrame(result=dict(_STRUCTURAL_CONTROLS))
|
||||||
|
page = _RecordingPage([probe])
|
||||||
|
monkeypatch.setattr(module, "_fill_multi_value_parameter", _fake_fill)
|
||||||
|
|
||||||
|
ok = module.fill_dsv_multi_select_parameter(
|
||||||
|
page, "Owner", ["CRTM-0000000100"], select_all=False,
|
||||||
|
browser_timeout_ms=lambda: 3_000,
|
||||||
|
report_name="Receipt Detail", program_label="AWSRTM",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert ok is True
|
||||||
|
assert captured == {"control": "multi_value", **_STRUCTURAL_CONTROLS}
|
||||||
|
assert probe.calls == ["Owner"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_fill_multi_select_structural_preferred_registry_is_fallback(monkeypatch):
|
||||||
|
"""优先级:结构性解析优先(ctl 编号随渲染漂移,注册表 ctl 条目只作回退)。
|
||||||
|
|
||||||
|
[断言意图] 结构性命中时使用结构性三件套、注册表回退不被消费;
|
||||||
|
结构性未命中时才回退注册表控件。
|
||||||
|
"""
|
||||||
|
module = _load_module()
|
||||||
|
registry_controls = {
|
||||||
|
"text": "#ReportViewerMain_ctl08_ctl29_txtValue",
|
||||||
|
"toggle": "#ReportViewerMain_ctl08_ctl29_ctl01",
|
||||||
|
"dropdown": "#ReportViewerMain_ctl08_ctl29_divDropDown",
|
||||||
|
}
|
||||||
|
resolve_calls: list[tuple] = []
|
||||||
|
monkeypatch.setattr(
|
||||||
|
module, "resolve_parameter_controls",
|
||||||
|
lambda *a, **k: (resolve_calls.append(a), dict(registry_controls))[1],
|
||||||
|
)
|
||||||
|
probe = _RecordingFrame(result=dict(_STRUCTURAL_CONTROLS))
|
||||||
|
page = _RecordingPage([probe])
|
||||||
|
captured: dict[str, object] = {}
|
||||||
|
|
||||||
|
def _fake_fill(page, label, values, *, timeout_ms, config_override, select_all):
|
||||||
|
captured.update(config_override)
|
||||||
|
return True
|
||||||
|
|
||||||
|
monkeypatch.setattr(module, "_fill_multi_value_parameter", _fake_fill)
|
||||||
|
|
||||||
|
ok = module.fill_dsv_multi_select_parameter(
|
||||||
|
page, "Warehouse", ["RTM"], select_all=False,
|
||||||
|
browser_timeout_ms=lambda: 3_000,
|
||||||
|
report_name="Receipt Detail", program_label="AWSRTM",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert ok is True
|
||||||
|
assert captured.get("text") == _STRUCTURAL_CONTROLS["text"] # 结构性解析优先生效
|
||||||
|
assert resolve_calls == [] # 结构性命中:注册表回退未被消费
|
||||||
|
|
||||||
|
# 结构性未命中 → 回退注册表控件
|
||||||
|
probed = _RecordingFrame(result=None)
|
||||||
|
page = _RecordingPage([probed])
|
||||||
|
captured.clear()
|
||||||
|
ok = module.fill_dsv_multi_select_parameter(
|
||||||
|
page, "Warehouse", ["RTM"], select_all=False,
|
||||||
|
browser_timeout_ms=lambda: 3_000,
|
||||||
|
report_name="Receipt Detail", program_label="AWSRTM",
|
||||||
|
)
|
||||||
|
assert ok is True
|
||||||
|
assert captured.get("text") == registry_controls["text"] # 回退到注册表
|
||||||
|
assert probed.calls == ["Warehouse"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_multi_value_already_set_set_equality_not_substring():
|
||||||
|
"""2026-10-08 Owner@AWSRTM 事故根因回归:SSRS 多选框默认全选,txtValue 恒为全量 CSV,
|
||||||
|
目标值必为该 CSV 的子串——必须用集合相等判定,子串包含会恒误判"已设置"并跳过下拉勾选。"""
|
||||||
|
module = _load_module()
|
||||||
|
all_owners_csv = ",".join(f"CRTM-0000000{n:03d}" for n in range(5, 449))
|
||||||
|
|
||||||
|
# [断言意图] 目标值是全选 CSV 的"子串"但非"全集"——不得判已设置(旧 bug 行为)。
|
||||||
|
assert module._multi_value_already_set(all_owners_csv, ["CRTM-0000000100"]) is False
|
||||||
|
# 完全相等的选中集合才允许跳过。
|
||||||
|
assert module._multi_value_already_set("CRTM-0000000100", ["CRTM-0000000100"]) is True
|
||||||
|
assert module._multi_value_already_set("CRTM-0000000100, CRTM-0000000101",
|
||||||
|
["CRTM-0000000101", "CRTM-0000000100"]) is True
|
||||||
|
# 边界:空当前值/空目标不判已设置;大小写与空白不敏感。
|
||||||
|
assert module._multi_value_already_set("", ["CRTM-0000000100"]) is False
|
||||||
|
assert module._multi_value_already_set(all_owners_csv, []) is False
|
||||||
|
assert module._multi_value_already_set(" crtm-0000000100 ", ["CRTM-0000000100"]) is True
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
"""
|
||||||
|
backend/tests/test_equipment_acceptance_alert_plan.py
|
||||||
|
|
||||||
|
用途:设备验收四档跨档和收件人组装的纯函数测试。
|
||||||
|
依赖:alert_plan。不连接数据库,不访问 OA,不发企业微信。
|
||||||
|
逻辑:超过阈值才进档。解析失败留在原角色上,不改发给别人。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.pure_unit
|
||||||
|
|
||||||
|
from app.services.equipment_acceptance.alert_plan import (
|
||||||
|
assemble_tier,
|
||||||
|
due_tiers,
|
||||||
|
make_person,
|
||||||
|
resolve_account,
|
||||||
|
resolve_configured_user,
|
||||||
|
)
|
||||||
|
|
||||||
|
_DAYS = (30, 37, 44, 51)
|
||||||
|
|
||||||
|
|
||||||
|
def test_due_tiers_use_strictly_greater_than_threshold():
|
||||||
|
"""刚好等于 30 天还不发。超过 51 天才四档都到。"""
|
||||||
|
assert due_tiers(None, _DAYS) == []
|
||||||
|
assert due_tiers(30, _DAYS) == []
|
||||||
|
assert due_tiers(31, _DAYS) == [1]
|
||||||
|
assert due_tiers(51, _DAYS) == [1, 2, 3]
|
||||||
|
assert due_tiers(52, _DAYS) == [1, 2, 3, 4]
|
||||||
|
|
||||||
|
|
||||||
|
def test_tier_one_keeps_missing_supervisor_as_failure():
|
||||||
|
"""直接主管缺失时整档仍可发给处理人和采购担当,不把申请人改成主送。"""
|
||||||
|
handler = resolve_account(
|
||||||
|
slot="to",
|
||||||
|
label="当前处理人",
|
||||||
|
name="吴敏",
|
||||||
|
job_num="10086",
|
||||||
|
user=SimpleNamespace(id=7, wecom_userid="wx-handler", real_name="吴敏"),
|
||||||
|
missing_job_error="吴敏没有工号",
|
||||||
|
oa_employee_id=11,
|
||||||
|
)
|
||||||
|
supervisor = make_person(slot="cc", label="直接主管", name="吴敏", error="吴敏没有直接主管")
|
||||||
|
applicant = resolve_account(
|
||||||
|
slot="cc",
|
||||||
|
label="采购担当",
|
||||||
|
name="赵琴",
|
||||||
|
job_num="20001",
|
||||||
|
user=SimpleNamespace(id=8, wecom_userid="wx-buyer", real_name="赵琴"),
|
||||||
|
missing_job_error="没有申请人工号",
|
||||||
|
)
|
||||||
|
draft = assemble_tier(tier=1, threshold_days=30, to_people=[handler], cc_people=[supervisor, applicant])
|
||||||
|
assert draft["status"] == "pending"
|
||||||
|
assert draft["to_text"] == "吴敏"
|
||||||
|
assert draft["cc_text"] == "赵琴"
|
||||||
|
assert "吴敏没有直接主管" in draft["error_message"]
|
||||||
|
assert all(item["label"] != "采购担当" or item["slot"] == "cc" for item in draft["recipients"])
|
||||||
|
|
||||||
|
|
||||||
|
def test_duplicate_person_stays_only_on_the_primary_list():
|
||||||
|
"""同一个人既是主送又是抄送时只留主送。"""
|
||||||
|
person = resolve_account(
|
||||||
|
slot="to",
|
||||||
|
label="当前处理人",
|
||||||
|
name="吴敏",
|
||||||
|
job_num="10086",
|
||||||
|
user=SimpleNamespace(id=7, wecom_userid="wx-handler", real_name="吴敏"),
|
||||||
|
missing_job_error="吴敏没有工号",
|
||||||
|
)
|
||||||
|
copied = dict(person)
|
||||||
|
copied["slot"] = "cc"
|
||||||
|
copied["label"] = "直接主管"
|
||||||
|
draft = assemble_tier(tier=1, threshold_days=30, to_people=[person], cc_people=[copied])
|
||||||
|
assert draft["to_text"] == "吴敏"
|
||||||
|
assert draft["cc_text"] is None
|
||||||
|
assert len(draft["recipients"]) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_unbound_wecom_and_missing_role_stay_failed():
|
||||||
|
"""没绑企微、没选 COO 都记失败,不写死姓名。"""
|
||||||
|
unbound = resolve_account(
|
||||||
|
slot="to",
|
||||||
|
label="当前处理人",
|
||||||
|
name="吴敏",
|
||||||
|
job_num="10086",
|
||||||
|
user=SimpleNamespace(id=7, wecom_userid="", real_name="吴敏"),
|
||||||
|
missing_job_error="吴敏没有工号",
|
||||||
|
)
|
||||||
|
assert unbound["error"] == "未绑定企业微信"
|
||||||
|
missing = resolve_configured_user(slot="to", label="COO", user=None, missing_error="未配置COO")
|
||||||
|
draft = assemble_tier(tier=3, threshold_days=44, to_people=[missing], cc_people=[unbound])
|
||||||
|
assert draft["status"] == "failed"
|
||||||
|
assert draft["to_text"] is None
|
||||||
|
assert "未配置COO" in draft["error_message"]
|
||||||
|
assert "未绑定企业微信" in draft["error_message"]
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
"""
|
||||||
|
tests/test_equipment_acceptance_config.py
|
||||||
|
|
||||||
|
用途:锁定设备验收预警四档天数的保存前校验。
|
||||||
|
依赖:config_service.validate_reminder_days、ValidationError。
|
||||||
|
逻辑:不连数据库。默认 30/37/44/51 通过;相等、倒序、非整数和空岗位以外的天数形状被拒绝。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.core.errors import ValidationError
|
||||||
|
from app.services.equipment_acceptance.config_service import validate_reminder_days
|
||||||
|
|
||||||
|
|
||||||
|
def test_default_reminder_days_pass():
|
||||||
|
"""冻结默认值可以保存。"""
|
||||||
|
assert validate_reminder_days([30, 37, 44, 51]) == (30, 37, 44, 51)
|
||||||
|
|
||||||
|
|
||||||
|
def test_days_must_increase():
|
||||||
|
"""后一档不大于前一档时拒绝,避免两档在同一天触发。"""
|
||||||
|
with pytest.raises(ValidationError) as caught:
|
||||||
|
validate_reminder_days([30, 30, 44, 51])
|
||||||
|
assert caught.value.code == "EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID"
|
||||||
|
|
||||||
|
|
||||||
|
def test_days_reject_bool_and_wrong_length():
|
||||||
|
"""布尔值在 Python 里也是 int,不能当成 1 天;档数必须是四档。"""
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
validate_reminder_days([True, 37, 44, 51])
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
validate_reminder_days([30, 37, 44])
|
||||||
@@ -0,0 +1,257 @@
|
|||||||
|
"""
|
||||||
|
backend/tests/test_equipment_acceptance_snapshot.py
|
||||||
|
|
||||||
|
用途:设备验收同步的状态、分组和 SQL 组装单测。
|
||||||
|
依赖:snapshot_rules、source_group、query_sql。不连接 OA,也不启动 Flask。
|
||||||
|
逻辑:停表规则、按 requestid 分组、SQL 不查 isremark,发送记录快照字段原样返回。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import date, datetime
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.pure_unit
|
||||||
|
|
||||||
|
from app.services.equipment_acceptance.query_sql import build_acceptance_sql, resolve_catalogs
|
||||||
|
from app.services.equipment_acceptance.snapshot_rules import (
|
||||||
|
EXCLUDED,
|
||||||
|
NOT_STARTED,
|
||||||
|
STOPPED_ARCHIVED,
|
||||||
|
STOPPED_CANNOT_ACCEPT,
|
||||||
|
STOPPED_FORCE_FINISHED,
|
||||||
|
STOPPED_RETURNED,
|
||||||
|
STOPPED_REVOKED,
|
||||||
|
STOPPED_VOIDED,
|
||||||
|
WATCHING,
|
||||||
|
can_accept_from_oa,
|
||||||
|
classify_monitor_status,
|
||||||
|
dwell_days,
|
||||||
|
is_returned_from_oa,
|
||||||
|
)
|
||||||
|
from app.services.equipment_acceptance.source_group import group_acceptance_rows
|
||||||
|
|
||||||
|
|
||||||
|
def test_oa_yes_no_is_flipped_before_storage():
|
||||||
|
"""OA 0 是、1 否。验收空值保持空;退回空值收成否。其他值不猜测。"""
|
||||||
|
assert can_accept_from_oa(0) == 1
|
||||||
|
assert can_accept_from_oa(1) == 0
|
||||||
|
assert can_accept_from_oa(None) is None
|
||||||
|
assert can_accept_from_oa(2) == 2
|
||||||
|
assert is_returned_from_oa(0) == 1
|
||||||
|
assert is_returned_from_oa(1) == 0
|
||||||
|
assert is_returned_from_oa(None) == 0
|
||||||
|
assert is_returned_from_oa(2) == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_returned_yes_stops_even_while_approving():
|
||||||
|
"""is_returned=1 是退回,审批中也停表。"""
|
||||||
|
status = classify_monitor_status(
|
||||||
|
can_accept=1, is_returned=1, flow_status=1, timer_started=True
|
||||||
|
)
|
||||||
|
assert status == STOPPED_RETURNED
|
||||||
|
|
||||||
|
|
||||||
|
def test_cannot_accept_stops_and_null_can_accept_is_not_watching():
|
||||||
|
"""can_accept=0 是不可以,停表;空值不是可以验收。"""
|
||||||
|
stopped = classify_monitor_status(
|
||||||
|
can_accept=0, is_returned=0, flow_status=1, timer_started=True
|
||||||
|
)
|
||||||
|
excluded = classify_monitor_status(
|
||||||
|
can_accept=None, is_returned=0, flow_status=1, timer_started=True
|
||||||
|
)
|
||||||
|
assert stopped == STOPPED_CANNOT_ACCEPT
|
||||||
|
assert excluded == EXCLUDED
|
||||||
|
|
||||||
|
|
||||||
|
def test_not_returned_and_can_accept_watches():
|
||||||
|
"""未退回且可以验收、审批中、已有计时起点时继续计时。"""
|
||||||
|
status = classify_monitor_status(
|
||||||
|
can_accept=1, is_returned=0, flow_status=1, timer_started=True
|
||||||
|
)
|
||||||
|
assert status == WATCHING
|
||||||
|
|
||||||
|
|
||||||
|
def test_terminal_flow_status_stops():
|
||||||
|
"""3/4/5 分别停表。7、8、99、-99 都是撤销,没有计时起点也不再提醒。"""
|
||||||
|
assert classify_monitor_status(can_accept=1, is_returned=0, flow_status=3, timer_started=True) == STOPPED_ARCHIVED
|
||||||
|
assert classify_monitor_status(can_accept=1, is_returned=0, flow_status=4, timer_started=True) == STOPPED_FORCE_FINISHED
|
||||||
|
assert classify_monitor_status(can_accept=1, is_returned=0, flow_status=5, timer_started=True) == STOPPED_VOIDED
|
||||||
|
for flow_status in (7, 8, 99, -99):
|
||||||
|
assert classify_monitor_status(
|
||||||
|
can_accept=1, is_returned=0, flow_status=flow_status, timer_started=True
|
||||||
|
) == STOPPED_REVOKED
|
||||||
|
assert classify_monitor_status(
|
||||||
|
can_accept=1, is_returned=0, flow_status=flow_status, timer_started=False
|
||||||
|
) == STOPPED_REVOKED
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_timer_is_not_started_when_no_stop_reason():
|
||||||
|
"""没有计时起点且没有停表原因时是未开始。"""
|
||||||
|
status = classify_monitor_status(
|
||||||
|
can_accept=1, is_returned=0, flow_status=1, timer_started=False
|
||||||
|
)
|
||||||
|
assert status == NOT_STARTED
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_returned_is_excluded():
|
||||||
|
"""0、1 以外的退回值既不判退回也不当未退回。"""
|
||||||
|
status = classify_monitor_status(
|
||||||
|
can_accept=1, is_returned=2, flow_status=1, timer_started=True
|
||||||
|
)
|
||||||
|
assert status == EXCLUDED
|
||||||
|
|
||||||
|
|
||||||
|
def test_dwell_days_freeze_on_archive_date():
|
||||||
|
"""归档后的天数截止到归档日,不随同步日继续增加。"""
|
||||||
|
days = dwell_days(
|
||||||
|
timer_started_at=datetime(2026, 9, 1, 8, 0, 0),
|
||||||
|
flow_status=3,
|
||||||
|
finished_at=datetime(2026, 9, 11, 18, 0, 0),
|
||||||
|
as_of=date(2026, 10, 8),
|
||||||
|
)
|
||||||
|
assert days == 10
|
||||||
|
|
||||||
|
|
||||||
|
def test_dwell_days_use_sync_date_while_watching():
|
||||||
|
"""计时中按同步日减起点的自然日。"""
|
||||||
|
days = dwell_days(
|
||||||
|
timer_started_at=date(2026, 10, 1),
|
||||||
|
flow_status=1,
|
||||||
|
finished_at=None,
|
||||||
|
as_of=date(2026, 10, 8),
|
||||||
|
)
|
||||||
|
assert days == 7
|
||||||
|
|
||||||
|
|
||||||
|
def test_group_splits_requests_and_dedupes_operators():
|
||||||
|
"""不同 requestid 各成一张单。同一节点同一人只留一行,即使源行带了不同的 isremark。没有 requestid 的行跳过。"""
|
||||||
|
drafts, skipped = group_acceptance_rows(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"ysddh": "YS-1",
|
||||||
|
"cgdh": "CG-1",
|
||||||
|
"htbh": "HT-1",
|
||||||
|
"sbsyrjssj": "2026-10-01 09:00:00",
|
||||||
|
"sfkyzcys": 0,
|
||||||
|
"ycsm": " 到货规格与请购不符 ",
|
||||||
|
"sfzfth": None,
|
||||||
|
"requestid": 10,
|
||||||
|
"flowstatus": 3,
|
||||||
|
"nodeid": 1,
|
||||||
|
"nodename": "旧节点",
|
||||||
|
"userid": 7,
|
||||||
|
"isremark": 2,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ysddh": "YS-2",
|
||||||
|
"requestid": 20,
|
||||||
|
"flowstatus": 1,
|
||||||
|
"nodeid": 2,
|
||||||
|
"nodename": "使用部门担当",
|
||||||
|
"userid": 8,
|
||||||
|
"isremark": 0,
|
||||||
|
"handler_name": "吴敏",
|
||||||
|
"handler_job_num": "10086",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"requestid": 20,
|
||||||
|
"flowstatus": 1,
|
||||||
|
"nodeid": 2,
|
||||||
|
"nodename": "使用部门担当",
|
||||||
|
"userid": 9,
|
||||||
|
"isremark": 2,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"requestid": 20,
|
||||||
|
"flowstatus": 1,
|
||||||
|
"nodeid": 2,
|
||||||
|
"nodename": "使用部门担当",
|
||||||
|
"userid": 8,
|
||||||
|
"isremark": 9,
|
||||||
|
"handler_name": "吴敏",
|
||||||
|
"handler_job_num": "10086",
|
||||||
|
},
|
||||||
|
{"ysddh": "NO-REQUEST"},
|
||||||
|
]
|
||||||
|
)
|
||||||
|
assert skipped == 1
|
||||||
|
by_request = {draft.request_id: draft for draft in drafts}
|
||||||
|
assert set(by_request) == {10, 20}
|
||||||
|
assert by_request[10].acceptance_no == "YS-1"
|
||||||
|
assert by_request[10].contract_no == "HT-1"
|
||||||
|
assert by_request[10].can_accept == 1
|
||||||
|
assert by_request[10].cannot_accept_note == "到货规格与请购不符"
|
||||||
|
assert by_request[10].is_returned == 0
|
||||||
|
assert by_request[10].flow_status_raw == 3
|
||||||
|
current = by_request[20]
|
||||||
|
assert current.request_match_count == 1
|
||||||
|
assert current.flow_status_raw == 1
|
||||||
|
assert [node.node_name for node in current.nodes] == ["使用部门担当"]
|
||||||
|
assert sorted(item.user_id for item in current.operators) == [8, 9]
|
||||||
|
assert not hasattr(current.operators[0], "isremark")
|
||||||
|
|
||||||
|
|
||||||
|
def test_sql_uses_dictionary_catalogs_and_does_not_select_isremark():
|
||||||
|
"""实例同时有字典库时用 weaver_wfc / weaver_wfp,SQL 不查询 isremark。"""
|
||||||
|
catalogs = resolve_catalogs({"ecology10", "eteams", "weaver_wfc", "weaver_wfp"})
|
||||||
|
sql = build_acceptance_sql(catalogs)
|
||||||
|
assert catalogs.request == "weaver_wfc"
|
||||||
|
assert catalogs.node == "weaver_wfp"
|
||||||
|
assert "[weaver_wfc].[dbo].[wfc_operate]" in sql
|
||||||
|
assert "[weaver_wfp].[dbo].[wfp_node]" in sql
|
||||||
|
assert "isremark" not in sql.lower()
|
||||||
|
assert "ycsm" in sql
|
||||||
|
assert "workflow_requestbase" not in sql
|
||||||
|
assert "[weaver_wfc].[dbo].[wfc_form_data]" in sql
|
||||||
|
assert "d.dataid = f.FORM_DATA_ID" in sql
|
||||||
|
assert "lcbh" not in sql
|
||||||
|
assert "htbh1" not in sql
|
||||||
|
assert "ysrq" not in sql
|
||||||
|
assert "requestmark" not in sql
|
||||||
|
assert "operateround" not in sql.lower()
|
||||||
|
assert "optgroupid" not in sql.lower()
|
||||||
|
assert "batch_number" not in sql.lower()
|
||||||
|
assert "operate_log_id" not in sql.lower()
|
||||||
|
|
||||||
|
|
||||||
|
def test_sql_falls_back_when_dictionary_catalog_is_absent():
|
||||||
|
"""看不到 weaver_wfc 时,流程表改用 ecology10。人员库缺失则失败。"""
|
||||||
|
catalogs = resolve_catalogs({"ecology10", "eteams"})
|
||||||
|
assert catalogs.request == "ecology10"
|
||||||
|
assert catalogs.node == "ecology10"
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
resolve_catalogs({"ecology10"})
|
||||||
|
|
||||||
|
|
||||||
|
def test_sql_rejects_unsafe_catalog_override():
|
||||||
|
"""库名覆盖值不能带分号或空格。"""
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
resolve_catalogs({"ecology10", "eteams"}, request="weaver_wfc;drop")
|
||||||
|
|
||||||
|
|
||||||
|
def test_send_record_payload_keeps_written_names():
|
||||||
|
"""发送记录接口用写入时的单号和主送抄送,不回读当前岗位。"""
|
||||||
|
from app.models.equipment_acceptance import EquipmentAcceptanceSendRecord
|
||||||
|
from app.services.equipment_acceptance.send_record_service import send_record_payload
|
||||||
|
|
||||||
|
row = EquipmentAcceptanceSendRecord(
|
||||||
|
id=3,
|
||||||
|
order_id=9,
|
||||||
|
acceptance_no="YS-1",
|
||||||
|
purchase_order_no="CG-1",
|
||||||
|
tier=2,
|
||||||
|
threshold_days=37,
|
||||||
|
to_text="经副理甲",
|
||||||
|
cc_text="COO、采购经副理",
|
||||||
|
status="sent",
|
||||||
|
sent_at=datetime(2026, 10, 9, 10, 0, 0),
|
||||||
|
error_message=None,
|
||||||
|
created_at=datetime(2026, 10, 9, 9, 0, 0),
|
||||||
|
)
|
||||||
|
payload = send_record_payload(row)
|
||||||
|
assert payload["acceptance_no"] == "YS-1"
|
||||||
|
assert payload["to_text"] == "经副理甲"
|
||||||
|
assert payload["cc_text"] == "COO、采购经副理"
|
||||||
|
assert payload["threshold_days"] == 37
|
||||||
|
assert payload["status"] == "sent"
|
||||||
|
assert payload["sent_at"]
|
||||||
@@ -266,3 +266,49 @@ def test_ingest_empty_persists_no_receipt_data(app):
|
|||||||
assert saved.status == 'empty'
|
assert saved.status == 'empty'
|
||||||
assert saved.error_code == 'no_receipt_data'
|
assert saved.error_code == 'no_receipt_data'
|
||||||
assert saved.error_message == 'no_receipt_data'
|
assert saved.error_message == 'no_receipt_data'
|
||||||
|
|
||||||
|
|
||||||
|
def test_receipt_progress_routes_are_registered(app):
|
||||||
|
"""回归锁:receipt-unit-progress / receipt-batch-progress 必须注册在 Tool 蓝图上。
|
||||||
|
|
||||||
|
2026-10-08 事故:重构分叉合并丢失两路由,Worker 上报全程 404、活动锚失效、
|
||||||
|
在飞批次被超时对账误杀——本用例保证路由缺失在任何部署前即红。
|
||||||
|
"""
|
||||||
|
app.config['SHIPPING_NOTICE_TOOL_API_KEY'] = 'test-tool-key'
|
||||||
|
client = app.test_client()
|
||||||
|
headers = {'X-Integration-Key': 'test-tool-key'}
|
||||||
|
for path, payload in (
|
||||||
|
('/api/shipping-notice/rpa/receipt-unit-progress',
|
||||||
|
{'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': 'no-such-callback'}),
|
||||||
|
('/api/shipping-notice/rpa/receipt-batch-progress',
|
||||||
|
{'schema_version': 'shipping_receipt_rpa.v1', 'schedule_run_id': 999999999}),
|
||||||
|
):
|
||||||
|
# [断言意图] 路由必须存在且鉴权通过(非 401/403/404);无匹配数据时服务层
|
||||||
|
# 返回 200 + updated=False(注册性探针,不依赖任何夹具数据)。
|
||||||
|
resp = client.post(path, json=payload, headers=headers)
|
||||||
|
assert resp.status_code == 200, (path, resp.status_code, resp.get_json())
|
||||||
|
assert resp.get_json()['data']['updated'] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_receipt_callback_file_resolves_drop_root_filename(app, tmp_path):
|
||||||
|
"""跨机路径契约:Worker 只上报文件名(或历史 Windows 绝对路径),后端按自身 drop 根定位。"""
|
||||||
|
from app.core.errors import ValidationError
|
||||||
|
from app.services.shipping_notice.receipt_report_storage import _read_receipt_callback_file
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
drop_root = tmp_path / 'receipt-drop'
|
||||||
|
drop_root.mkdir()
|
||||||
|
app.config['FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR'] = str(drop_root)
|
||||||
|
target = drop_root / 'receipt_RUN_X_SITE_NA_2026.xlsx'
|
||||||
|
target.write_bytes(b'receipt-bytes')
|
||||||
|
|
||||||
|
# [断言意图] 裸文件名(新 Worker 契约)与 Windows 本机绝对路径(历史载荷)都
|
||||||
|
# 必须解析到后端 drop 根内同一文件;根外文件依旧拒绝(任意本机文件读取护栏不变)。
|
||||||
|
assert _read_receipt_callback_file('receipt_RUN_X_SITE_NA_2026.xlsx') == b'receipt-bytes'
|
||||||
|
assert _read_receipt_callback_file(
|
||||||
|
r'C:\HxopsRpaTest\data\freight_rpa\receipt\drop\receipt_RUN_X_SITE_NA_2026.xlsx'
|
||||||
|
) == b'receipt-bytes'
|
||||||
|
outside = tmp_path / 'outside.xlsx'
|
||||||
|
outside.write_bytes(b'x')
|
||||||
|
with pytest.raises(ValidationError, match='receipt callback file'):
|
||||||
|
_read_receipt_callback_file(str(outside))
|
||||||
@@ -132,20 +132,68 @@ def test_receipt_run_notification_is_one_shot_at_finalize(app, monkeypatch, tmp_
|
|||||||
|
|
||||||
outcome = finalize_receipt_schedule_run_if_complete(run.id)
|
outcome = finalize_receipt_schedule_run_if_complete(run.id)
|
||||||
|
|
||||||
# [断言意图] 一次性出口:单条 textcard + 单个收料 ZIP,与库存排程同通道同门禁。
|
# [断言意图] 一次性出口:单条 textcard + 结果 Excel + 单个收料 ZIP,与库存排程同通道同门禁。
|
||||||
assert outcome == {'finalized': True, 'status': 'success'}
|
assert outcome == {'finalized': True, 'status': 'success'}
|
||||||
assert len(textcards) == 1
|
assert len(textcards) == 1
|
||||||
assert '原始收料包:已随本通知发送' in textcards[0][1]
|
assert '原始收料包:已随本通知发送' in textcards[0][1]
|
||||||
assert len(media_uploads) == 1
|
assert len(media_uploads) == 2
|
||||||
assert media_uploads[0].startswith('收料RPA-') and media_uploads[0].endswith('-收料.zip')
|
assert media_uploads[0].startswith('收料RPA-') and media_uploads[0].endswith('-结果.xlsx')
|
||||||
assert file_sends == ['media-1']
|
assert media_uploads[1].startswith('收料RPA-') and media_uploads[1].endswith('-收料.zip')
|
||||||
|
assert file_sends == ['media-1', 'media-2']
|
||||||
assert run.wecom_notified is True
|
assert run.wecom_notified is True
|
||||||
assert run.response_summary_json.get('raw_receipt_zip_available') is True
|
assert run.response_summary_json.get('raw_receipt_zip_available') is True
|
||||||
|
|
||||||
# [断言意图] awaiting 标志清零后再次归集必须短路,绝不二次打扰接收人。
|
# [断言意图] awaiting 标志清零后再次归集必须短路,绝不二次打扰接收人。
|
||||||
outcome_again = finalize_receipt_schedule_run_if_complete(run.id)
|
outcome_again = finalize_receipt_schedule_run_if_complete(run.id)
|
||||||
assert outcome_again == {'finalized': False, 'reason': 'not_awaiting_receipt_callback'}
|
assert outcome_again == {'finalized': False, 'reason': 'not_awaiting_receipt_callback'}
|
||||||
assert len(textcards) == 1 and len(file_sends) == 1
|
assert len(textcards) == 1 and len(file_sends) == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_receipt_finalize_generates_summary_excel(app, tmp_path):
|
||||||
|
"""收料 finalize 生成汇总 Excel:行结构对齐库存、状态归一、展示名 收料RPA-*-结果.xlsx。"""
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
from openpyxl import load_workbook
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.models import (
|
||||||
|
ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile,
|
||||||
|
ShippingReceiptRpaUnitRun,
|
||||||
|
)
|
||||||
|
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
app.config['FREIGHT_RPA_RECEIPT_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives-excel')
|
||||||
|
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||||
|
task = ScheduleTask(schedule_no='SCH-RECEIPT-EXCEL', name='Receipt excel', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||||
|
db.session.add(task); db.session.flush()
|
||||||
|
run = ScheduleRun(run_no='RUN-RECEIPT-EXCEL', schedule_task_id=task.id, status='running', response_summary_json={'awaiting_receipt_rpa': True})
|
||||||
|
db.session.add(run); db.session.flush()
|
||||||
|
unit_ok = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='DSV360_AWSDU', connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-excel-ok', status='success', config_snapshot_json={})
|
||||||
|
unit_empty = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='DSV360_AWSCV', connector_type='dbs', warehouse_id='AWSCV', callback_id='receipt-excel-empty', status='empty', config_snapshot_json={})
|
||||||
|
unit_fail = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='CRANE_WH1', connector_type='crane', warehouse_id=None, callback_id='receipt-excel-fail', status='failed', error_code='RPA.RECEIPT_EXPORT_FAILED', error_message='download timeout', config_snapshot_json={})
|
||||||
|
db.session.add_all([unit_ok, unit_empty, unit_fail]); db.session.flush()
|
||||||
|
db.session.add(ShippingReceiptReportFile(unit_run_id=unit_ok.id, storage_provider='minio', storage_bucket='test', storage_key='receipt-excel-1.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='d' * 64))
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
outcome = finalize_receipt_schedule_run_if_complete(run.id)
|
||||||
|
|
||||||
|
# [断言意图] finalize 生成汇总 Excel,并携带与库存同名的 summary 契约键。
|
||||||
|
assert outcome == {'finalized': True, 'status': 'partial_failed'}
|
||||||
|
assert run.excel_file_data
|
||||||
|
assert run.excel_file_name.startswith('收料RPA-') and run.excel_file_name.endswith('-结果.xlsx')
|
||||||
|
assert run.response_summary_json['excel_export_status'] == 'ok'
|
||||||
|
assert run.response_summary_json['excel_failed'] is False
|
||||||
|
|
||||||
|
# [断言意图] 行结构对齐库存:中文表头 + empty→skipped / failed 保持 failed,与卡片计数口径一致。
|
||||||
|
workbook = load_workbook(BytesIO(run.excel_file_data))
|
||||||
|
sheet = workbook.active
|
||||||
|
header = [cell.value for cell in sheet[1]]
|
||||||
|
assert header[:2] == ['收料源', '仓库']
|
||||||
|
rows = {row[0]: row for row in sheet.iter_rows(min_row=2, values_only=True)}
|
||||||
|
assert rows['DSV360_AWSDU'][3] == 1 and rows['DSV360_AWSDU'][4] == 'success'
|
||||||
|
assert rows['DSV360_AWSCV'][4] == 'skipped'
|
||||||
|
assert rows['CRANE_WH1'][4] == 'failed' and rows['CRANE_WH1'][6] == 'download timeout'
|
||||||
|
|
||||||
|
|
||||||
def test_receipt_run_notification_follows_inventory_gates(app, monkeypatch):
|
def test_receipt_run_notification_follows_inventory_gates(app, monkeypatch):
|
||||||
|
|||||||
@@ -205,3 +205,66 @@ def test_receipt_trigger_is_published_atomically(app, tmp_path):
|
|||||||
assert path
|
assert path
|
||||||
assert (tmp_path / 'receipt_export_batch_RUN-ATOMIC.json').exists()
|
assert (tmp_path / 'receipt_export_batch_RUN-ATOMIC.json').exists()
|
||||||
assert not list(tmp_path.glob('.*.tmp'))
|
assert not list(tmp_path.glob('.*.tmp'))
|
||||||
|
|
||||||
|
|
||||||
|
def test_stale_receipt_full_scan_recovers_without_task_trigger_or_restart(app):
|
||||||
|
"""全量扫描(每轮 tick 路径)无需任务再次执行/进程重启即可收口超时收料 run。"""
|
||||||
|
from app import db
|
||||||
|
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||||
|
from app.services.schedule.freight_receipt_rpa_finalize import recover_all_stale_receipt_rpa_schedule_runs
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
|
||||||
|
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||||
|
task = ScheduleTask(schedule_no='SCH-RECEIPT-ORPHAN', name='Receipt orphan', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||||
|
db.session.add(task); db.session.flush()
|
||||||
|
run = ScheduleRun(run_no='RUN-RECEIPT-ORPHAN', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=5), response_summary_json={'awaiting_receipt_rpa': True})
|
||||||
|
db.session.add(run); db.session.flush()
|
||||||
|
db.session.add(ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-orphan', status='awaiting_rpa', config_snapshot_json={}))
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
# [断言意图] 全量扫描不依赖 task 入参、进程重启或同排程再次执行(点B 修复口径);
|
||||||
|
# 超时窗(60s)过后扫描即收口为 failed 并写 recovered_reason。
|
||||||
|
assert recover_all_stale_receipt_rpa_schedule_runs() == 1
|
||||||
|
db.session.refresh(run)
|
||||||
|
assert run.status == 'failed'
|
||||||
|
assert run.response_summary_json.get('recovered_reason') == 'receipt_rpa_callback_timeout'
|
||||||
|
|
||||||
|
|
||||||
|
def test_receipt_recovery_respects_fresh_activity_of_long_batch(app):
|
||||||
|
"""长批次健康在跑不得被误杀:超时锚取最后单元活动而非 run 开始时间。"""
|
||||||
|
from app import db
|
||||||
|
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||||
|
from app.services.schedule.freight_receipt_rpa_finalize import recover_all_stale_receipt_rpa_schedule_runs
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
|
||||||
|
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||||
|
task = ScheduleTask(schedule_no='SCH-RECEIPT-LONG', name='Receipt long batch', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||||
|
db.session.add(task); db.session.flush()
|
||||||
|
run = ScheduleRun(run_no='RUN-RECEIPT-LONG', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=30), response_summary_json={'awaiting_receipt_rpa': True})
|
||||||
|
db.session.add(run); db.session.flush()
|
||||||
|
# 单元1:30 秒前终态(笔间活动新鲜);单元2:45 秒前进入 processing(在飞,started_at 为锚)
|
||||||
|
db.session.add(ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-long-done', status='success', config_snapshot_json={}, finished_at=datetime.utcnow() - timedelta(seconds=30)))
|
||||||
|
db.session.add(ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='B', callback_id='receipt-long-run', status='processing', config_snapshot_json={}, started_at=datetime.utcnow() - timedelta(seconds=45)))
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
# [断言意图] run.started_at(30min 前) 已远超 60s 窗,但最后活动仅 30~45s——
|
||||||
|
# 笔间静默口径下健康长批次必须不被回收(旧口径按 started_at 会误杀)。
|
||||||
|
assert recover_all_stale_receipt_rpa_schedule_runs() == 0
|
||||||
|
db.session.refresh(run)
|
||||||
|
assert run.status == 'running'
|
||||||
|
|
||||||
|
|
||||||
|
def test_receipt_recovery_is_wired_into_per_tick_maintenance_not_startup_only():
|
||||||
|
"""哨兵回归:收料超时对账必须挂在每轮领取维护区,不得回流启动一次性分支。"""
|
||||||
|
import inspect
|
||||||
|
|
||||||
|
from app.services.schedule import queue_service
|
||||||
|
|
||||||
|
source = inspect.getsource(queue_service)
|
||||||
|
marker_init = source.index("_worker_initialized = True")
|
||||||
|
# [断言意图] 调用点必须位于一次性分支竖旗之后(每轮维护区);
|
||||||
|
# 回流旧写法(receipt_recovered = ...)会让长驻进程永不回收(RUN20261001131705E5E5 根因)。
|
||||||
|
assert source.index("receipt_stale = recover_all_stale_receipt_rpa_schedule_runs()") > marker_init
|
||||||
|
assert "receipt_recovered = recover_all_stale_receipt_rpa_schedule_runs()" not in source
|
||||||
@@ -1909,8 +1909,10 @@ def test_maybe_switch_dsv_locale_to_zh_cn_clicks_english_to_simplified(monkeypat
|
|||||||
|
|
||||||
class _FakeFrame:
|
class _FakeFrame:
|
||||||
def locator(self, selector: str) -> _FakeLocator:
|
def locator(self, selector: str) -> _FakeLocator:
|
||||||
|
# 2026-09-20 页面改版后 #lanNavSel 既是标签读取点也是下拉开关(先于旧 #kc_locale 点击),
|
||||||
|
# 因此点击它须置 opened,模拟“点开语言菜单”。
|
||||||
if selector == "#lanNavSel":
|
if selector == "#lanNavSel":
|
||||||
return _FakeLocator("label")
|
return _FakeLocator("toggle")
|
||||||
if selector == "#kc_locale":
|
if selector == "#kc_locale":
|
||||||
return _FakeLocator("toggle")
|
return _FakeLocator("toggle")
|
||||||
if "中文简体" in selector:
|
if "中文简体" in selector:
|
||||||
@@ -2123,6 +2125,292 @@ def test_wait_for_dsv_login_method_page_skips_human_check_when_not_detected(monk
|
|||||||
assert human_check_calls["value"] == 0
|
assert human_check_calls["value"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_is_dsv_password_upgrade_redirect_accepts_auth_dsv_com_resume():
|
||||||
|
"""auth.dsv.com 的 resume/authorization.ping 也必须识别为密码升级提示地址。
|
||||||
|
|
||||||
|
[2026-10-12 回归] PingFederate resume 链迁移至 auth.dsv.com 后,旧的单域硬编码
|
||||||
|
返回 False,导致升级提示检测不到、登录卡死在“使用密码升级登录!”页不点「也许以后」。
|
||||||
|
"""
|
||||||
|
_load_freight_rpa_worker()
|
||||||
|
import dsv_auth
|
||||||
|
|
||||||
|
class _FakePage:
|
||||||
|
url = "https://auth.dsv.com/as/TKVXR7dFI7/resume/as/authorization.ping"
|
||||||
|
|
||||||
|
assert dsv_auth._is_dsv_password_upgrade_redirect(_FakePage()) is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_is_dsv_oauth_handshake_and_ping_urls_accept_auth_dsv_com():
|
||||||
|
"""OAuth 握手 / authorization.ping 判定须覆盖 auth.dsv.com 双认证域。"""
|
||||||
|
_load_freight_rpa_worker()
|
||||||
|
import dsv_auth
|
||||||
|
|
||||||
|
assert dsv_auth.is_dsv_oauth_handshake_url(
|
||||||
|
"https://auth.dsv.com/as/mock/as/authorization.oauth2"
|
||||||
|
) is True
|
||||||
|
assert dsv_auth.is_dsv_auth_ping_url(
|
||||||
|
"https://auth.dsv.com/as/mock/resume/as/authorization.ping"
|
||||||
|
) is True
|
||||||
|
assert dsv_auth.is_dsv_oauth_handshake_url("https://s360.dbschenker.com/main") is False
|
||||||
|
assert dsv_auth.is_dsv_auth_ping_url("https://s360.dbschenker.com/main") is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_looks_like_dsv_identifier_chooser_matches_strong_markers_only():
|
||||||
|
"""「选择登录方法」标题命中且无密码框 → 已记住标识页;用户名页不得误判。"""
|
||||||
|
worker = _load_freight_rpa_worker()
|
||||||
|
|
||||||
|
class _FakeLocator:
|
||||||
|
def __init__(self, body: str) -> None:
|
||||||
|
self.body = body
|
||||||
|
self.first = self
|
||||||
|
|
||||||
|
def inner_text(self, *args, **kwargs) -> str:
|
||||||
|
return self.body
|
||||||
|
|
||||||
|
def is_visible(self, *args, **kwargs) -> bool:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def count(self) -> int:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
class _FakeFrame:
|
||||||
|
def __init__(self, body: str) -> None:
|
||||||
|
self.body = body
|
||||||
|
|
||||||
|
def locator(self, selector: str) -> _FakeLocator:
|
||||||
|
return _FakeLocator(self.body)
|
||||||
|
|
||||||
|
class _FakePage:
|
||||||
|
def __init__(self, body: str) -> None:
|
||||||
|
self.frames = [_FakeFrame(body)]
|
||||||
|
|
||||||
|
chooser_body = (
|
||||||
|
"欢迎\nhtcus@hoo-thai.com\n选择登录方法\n通行密钥\n使用此设备登录。\n"
|
||||||
|
"移动应用程序 (iPhone 11)\n密码\n输入您的密码并登录。\n取消"
|
||||||
|
)
|
||||||
|
assert worker._looks_like_dsv_identifier_chooser(_FakePage(chooser_body)) is True
|
||||||
|
|
||||||
|
username_body = "电子邮件或SIMS ID或手机号\n继续\n忘记密码"
|
||||||
|
assert worker._looks_like_dsv_identifier_chooser(_FakePage(username_body)) is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_has_dsv_password_upgrade_prompt_on_auth_dsv_com_upgrade_page():
|
||||||
|
"""升级提示检测在 auth.dsv.com resume 页必须生效,否则不点「也许以后」直接卡死。"""
|
||||||
|
worker = _load_freight_rpa_worker()
|
||||||
|
|
||||||
|
upgrade_body = "使用密码升级登录!\n从密码和电子邮件中解脱出来。\n也许以后\n立即启用"
|
||||||
|
|
||||||
|
class _FakeLocator:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.first = self
|
||||||
|
|
||||||
|
def is_visible(self, *args, **kwargs) -> bool:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def inner_text(self, *args, **kwargs) -> str:
|
||||||
|
return upgrade_body
|
||||||
|
|
||||||
|
class _FakeFrame:
|
||||||
|
def locator(self, selector: str) -> _FakeLocator:
|
||||||
|
return _FakeLocator()
|
||||||
|
|
||||||
|
class _FakePage:
|
||||||
|
frames = [_FakeFrame()]
|
||||||
|
url = "https://auth.dsv.com/as/TKVXR7dFI7/resume/as/authorization.ping"
|
||||||
|
|
||||||
|
def locator(self, selector: str) -> _FakeLocator:
|
||||||
|
return _FakeLocator()
|
||||||
|
|
||||||
|
assert worker._has_dsv_password_upgrade_prompt(_FakePage()) is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_maybe_auto_login_dsv_chooser_first_skips_username_and_completes(monkeypatch):
|
||||||
|
"""已记住标识:方法选择页预检命中 → 跳过用户名等待/继续点击,直进密码阶段完成登录。
|
||||||
|
|
||||||
|
[2026-10-12 回归] 首版实现 chooser 分支漏初始化 user_filled,命中即抛
|
||||||
|
UnboundLocalError 导致整源失败;且选择页判定在用户名等待超时后才做,每源白等约 2 分钟。
|
||||||
|
"""
|
||||||
|
worker = _load_freight_rpa_worker()
|
||||||
|
g = worker._maybe_auto_login_dsv.__globals__
|
||||||
|
state = {
|
||||||
|
"continue_clicked": False,
|
||||||
|
"purge_called": False,
|
||||||
|
"password_method_clicked": False,
|
||||||
|
"submitted": False,
|
||||||
|
"home_ready": False,
|
||||||
|
"find_password_calls": 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
class _FakeLocator:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.first = self
|
||||||
|
|
||||||
|
def is_visible(self, *args, **kwargs) -> bool:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def fill(self, *args, **kwargs) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
password_locator = _FakeLocator()
|
||||||
|
|
||||||
|
def fake_find_password(page, timeout_ms: int = 250):
|
||||||
|
state["find_password_calls"] += 1
|
||||||
|
return password_locator if state["find_password_calls"] >= 2 else None
|
||||||
|
|
||||||
|
class _FakePage:
|
||||||
|
url = "https://auth.dsv.com/as/mock/resume/as/authorization.ping"
|
||||||
|
frames: list = []
|
||||||
|
|
||||||
|
def locator(self, selector: str) -> _FakeLocator:
|
||||||
|
return _FakeLocator()
|
||||||
|
|
||||||
|
def wait_for_load_state(self, *args, **kwargs) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
monkeypatch.setitem(
|
||||||
|
g, "_env",
|
||||||
|
lambda name, default=None: {"FREIGHT_RPA_WORKER_DSV_USERNAME": "mock-user",
|
||||||
|
"FREIGHT_RPA_WORKER_DSV_PASSWORD": "mock-pass"}.get(name, default),
|
||||||
|
)
|
||||||
|
monkeypatch.setitem(g, "_has_existing_dsv_portal_session", lambda page: False)
|
||||||
|
monkeypatch.setitem(g, "_wait_for_visible_selector", lambda *args, **kwargs: None)
|
||||||
|
monkeypatch.setitem(g, "_wait_for_dsv_auth_page_ready", lambda page, **kwargs: True)
|
||||||
|
monkeypatch.setitem(g, "_maybe_switch_dsv_locale_to_zh_cn", lambda page: False)
|
||||||
|
monkeypatch.setitem(g, "_looks_like_dsv_identifier_chooser", lambda page: True)
|
||||||
|
monkeypatch.setitem(g, "_click_dsv_continue", lambda page, locator: state.__setitem__("continue_clicked", True))
|
||||||
|
monkeypatch.setitem(
|
||||||
|
g, "_retry_dsv_login_with_purged_cookies", lambda page, username: state.__setitem__("purge_called", True)
|
||||||
|
)
|
||||||
|
monkeypatch.setitem(g, "_is_dsv_password_upgrade_redirect", lambda page: False)
|
||||||
|
monkeypatch.setitem(g, "_has_dsv_password_upgrade_prompt", lambda page, **kwargs: False)
|
||||||
|
monkeypatch.setitem(g, "_dismiss_dsv_password_upgrade_prompt", lambda page: None)
|
||||||
|
monkeypatch.setitem(g, "_dismiss_dsv_password_upgrade_prompt_after_login_redirect", lambda page: None)
|
||||||
|
monkeypatch.setitem(g, "_find_dsv_password_locator", fake_find_password)
|
||||||
|
monkeypatch.setitem(g, "_fill_dsv_password_page_fields", lambda page, username, password: False)
|
||||||
|
monkeypatch.setitem(g, "_has_dsv_human_check_prompt", lambda page: False)
|
||||||
|
monkeypatch.setitem(g, "_wait_for_dsv_login_method_page", lambda page, timeout_ms=None: True)
|
||||||
|
monkeypatch.setitem(
|
||||||
|
g, "_click_dsv_password_method",
|
||||||
|
lambda page: (state.__setitem__("password_method_clicked", True) or True),
|
||||||
|
)
|
||||||
|
monkeypatch.setitem(
|
||||||
|
g, "_submit_dsv_password_form",
|
||||||
|
lambda page: (state.__setitem__("submitted", True) or True),
|
||||||
|
)
|
||||||
|
monkeypatch.setitem(g, "_debug_dsv_stage", lambda page, *args, **kwargs: None)
|
||||||
|
monkeypatch.setitem(
|
||||||
|
g, "_wait_for_dsv_home_ready_after_login",
|
||||||
|
lambda page, **kwargs: state.__setitem__("home_ready", True),
|
||||||
|
)
|
||||||
|
monkeypatch.setitem(g, "_report_dsv_chain_stage", lambda *args, **kwargs: None)
|
||||||
|
monkeypatch.setitem(g, "_report_debug_event", lambda *args, **kwargs: None)
|
||||||
|
monkeypatch.setitem(g, "_collect_dsv_reports_probe", lambda page: {})
|
||||||
|
monkeypatch.setattr(g["time"], "sleep", lambda seconds: None)
|
||||||
|
ticks = {"value": 0.0}
|
||||||
|
|
||||||
|
def fake_monotonic() -> float:
|
||||||
|
ticks["value"] += 0.25
|
||||||
|
return ticks["value"]
|
||||||
|
|
||||||
|
monkeypatch.setattr(g["time"], "monotonic", fake_monotonic)
|
||||||
|
|
||||||
|
worker._maybe_auto_login_dsv(_FakePage())
|
||||||
|
|
||||||
|
assert state["continue_clicked"] is False, "chooser-first 不得点击继续按钮"
|
||||||
|
assert state["purge_called"] is False, "chooser-first 不得触发 Cookie 清空兜底"
|
||||||
|
assert state["password_method_clicked"] is True
|
||||||
|
assert state["submitted"] is True
|
||||||
|
assert state["home_ready"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_maybe_auto_login_dsv_generic_fill_reaches_continue_without_unbound(monkeypatch):
|
||||||
|
"""无用户名选择器时走通用填装:username_locator=None 传给继续点击,不得抛 UnboundLocalError。"""
|
||||||
|
worker = _load_freight_rpa_worker()
|
||||||
|
g = worker._maybe_auto_login_dsv.__globals__
|
||||||
|
state = {
|
||||||
|
"continue_args": None,
|
||||||
|
"submitted": False,
|
||||||
|
"home_ready": False,
|
||||||
|
"find_password_calls": 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
class _FakeLocator:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.first = self
|
||||||
|
|
||||||
|
def is_visible(self, *args, **kwargs) -> bool:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def fill(self, *args, **kwargs) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
password_locator = _FakeLocator()
|
||||||
|
|
||||||
|
def fake_find_password(page, timeout_ms: int = 250):
|
||||||
|
state["find_password_calls"] += 1
|
||||||
|
return password_locator
|
||||||
|
|
||||||
|
class _FakePage:
|
||||||
|
url = "https://auth.dbschenker.com/as/mock/resume/as/authorization.ping"
|
||||||
|
frames: list = []
|
||||||
|
|
||||||
|
def locator(self, selector: str) -> _FakeLocator:
|
||||||
|
return _FakeLocator()
|
||||||
|
|
||||||
|
def wait_for_load_state(self, *args, **kwargs) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
monkeypatch.setitem(
|
||||||
|
g, "_env",
|
||||||
|
lambda name, default=None: {"FREIGHT_RPA_WORKER_DSV_USERNAME": "mock-user",
|
||||||
|
"FREIGHT_RPA_WORKER_DSV_PASSWORD": "mock-pass"}.get(name, default),
|
||||||
|
)
|
||||||
|
monkeypatch.setitem(g, "_has_existing_dsv_portal_session", lambda page: False)
|
||||||
|
monkeypatch.setitem(g, "_wait_for_visible_selector", lambda *args, **kwargs: None)
|
||||||
|
monkeypatch.setitem(g, "_wait_for_dsv_auth_page_ready", lambda page, **kwargs: True)
|
||||||
|
monkeypatch.setitem(g, "_maybe_switch_dsv_locale_to_zh_cn", lambda page: False)
|
||||||
|
monkeypatch.setitem(g, "_looks_like_dsv_identifier_chooser", lambda page: False)
|
||||||
|
monkeypatch.setitem(g, "_fill_first_visible_text_input", lambda page, username: True)
|
||||||
|
|
||||||
|
def fake_click_continue(page, locator):
|
||||||
|
state["continue_args"] = locator
|
||||||
|
return True
|
||||||
|
|
||||||
|
monkeypatch.setitem(g, "_click_dsv_continue", fake_click_continue)
|
||||||
|
monkeypatch.setitem(g, "_is_dsv_password_upgrade_redirect", lambda page: False)
|
||||||
|
monkeypatch.setitem(g, "_has_dsv_password_upgrade_prompt", lambda page, **kwargs: False)
|
||||||
|
monkeypatch.setitem(g, "_dismiss_dsv_password_upgrade_prompt", lambda page: None)
|
||||||
|
monkeypatch.setitem(g, "_dismiss_dsv_password_upgrade_prompt_after_login_redirect", lambda page: None)
|
||||||
|
monkeypatch.setitem(g, "_find_dsv_password_locator", fake_find_password)
|
||||||
|
monkeypatch.setitem(g, "_has_dsv_human_check_prompt", lambda page: False)
|
||||||
|
monkeypatch.setitem(
|
||||||
|
g, "_submit_dsv_password_form",
|
||||||
|
lambda page: (state.__setitem__("submitted", True) or True),
|
||||||
|
)
|
||||||
|
monkeypatch.setitem(g, "_debug_dsv_stage", lambda page, *args, **kwargs: None)
|
||||||
|
monkeypatch.setitem(
|
||||||
|
g, "_wait_for_dsv_home_ready_after_login",
|
||||||
|
lambda page, **kwargs: state.__setitem__("home_ready", True),
|
||||||
|
)
|
||||||
|
monkeypatch.setitem(g, "_report_dsv_chain_stage", lambda *args, **kwargs: None)
|
||||||
|
monkeypatch.setitem(g, "_report_debug_event", lambda *args, **kwargs: None)
|
||||||
|
monkeypatch.setitem(g, "_collect_dsv_reports_probe", lambda page: {})
|
||||||
|
monkeypatch.setattr(g["time"], "sleep", lambda seconds: None)
|
||||||
|
ticks = {"value": 0.0}
|
||||||
|
|
||||||
|
def fake_monotonic() -> float:
|
||||||
|
ticks["value"] += 0.25
|
||||||
|
return ticks["value"]
|
||||||
|
|
||||||
|
monkeypatch.setattr(g["time"], "monotonic", fake_monotonic)
|
||||||
|
|
||||||
|
worker._maybe_auto_login_dsv(_FakePage())
|
||||||
|
|
||||||
|
assert state["continue_args"] is None, "通用填装路径 username_locator 应显式为 None"
|
||||||
|
assert state["submitted"] is True
|
||||||
|
assert state["home_ready"] is True
|
||||||
|
|
||||||
|
|
||||||
def test_find_dsv_password_locator_returns_visible_locator():
|
def test_find_dsv_password_locator_returns_visible_locator():
|
||||||
"""密码方式切换轮询应走轻量密码框探测,而不是长时间通用等待。"""
|
"""密码方式切换轮询应走轻量密码框探测,而不是长时间通用等待。"""
|
||||||
worker = _load_freight_rpa_worker()
|
worker = _load_freight_rpa_worker()
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ _RPA_MODULE_PATHS = {
|
|||||||
"dsv_auth": "connectors/dsv/dsv_auth.py",
|
"dsv_auth": "connectors/dsv/dsv_auth.py",
|
||||||
"dsv_session": "connectors/dsv/dsv_session.py",
|
"dsv_session": "connectors/dsv/dsv_session.py",
|
||||||
"dsv_debug": "connectors/dsv/dsv_debug.py",
|
"dsv_debug": "connectors/dsv/dsv_debug.py",
|
||||||
|
"dsv_report_parameters": "connectors/dsv/dsv_report_parameters.py",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -449,6 +450,7 @@ def test_dsv_navigation_emits_elapsed_stage_logs(monkeypatch):
|
|||||||
monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock())
|
monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock())
|
||||||
monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock())
|
monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock())
|
||||||
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
|
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
|
||||||
|
monkeypatch.setattr(worker, "_assert_dsv_report_viewer_identity", MagicMock())
|
||||||
|
|
||||||
worker._navigate_dsv_to_report_form(
|
worker._navigate_dsv_to_report_form(
|
||||||
page,
|
page,
|
||||||
@@ -581,6 +583,7 @@ def test_navigate_dsv_to_report_form_retries_once_with_home_reset(monkeypatch):
|
|||||||
monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock())
|
monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock())
|
||||||
monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock())
|
monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock())
|
||||||
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
|
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
|
||||||
|
monkeypatch.setattr(worker, "_assert_dsv_report_viewer_identity", MagicMock())
|
||||||
reset = MagicMock()
|
reset = MagicMock()
|
||||||
monkeypatch.setattr(worker, "_reset_dsv_export_entry", reset)
|
monkeypatch.setattr(worker, "_reset_dsv_export_entry", reset)
|
||||||
monkeypatch.setattr(worker, "_report_dsv_chain_stage", MagicMock())
|
monkeypatch.setattr(worker, "_report_dsv_chain_stage", MagicMock())
|
||||||
@@ -608,6 +611,7 @@ def test_navigate_dsv_to_report_form_raises_when_retry_fails(monkeypatch):
|
|||||||
monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock())
|
monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock())
|
||||||
monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock())
|
monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock())
|
||||||
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
|
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
|
||||||
|
monkeypatch.setattr(worker, "_assert_dsv_report_viewer_identity", MagicMock())
|
||||||
reset = MagicMock()
|
reset = MagicMock()
|
||||||
monkeypatch.setattr(worker, "_reset_dsv_export_entry", reset)
|
monkeypatch.setattr(worker, "_reset_dsv_export_entry", reset)
|
||||||
chain = MagicMock()
|
chain = MagicMock()
|
||||||
@@ -630,6 +634,177 @@ def test_navigate_dsv_to_report_form_raises_when_retry_fails(monkeypatch):
|
|||||||
assert any(call.args[:2] == ("report_navigation", "error") for call in chain.call_args_list)
|
assert any(call.args[:2] == ("report_navigation", "error") for call in chain.call_args_list)
|
||||||
|
|
||||||
|
|
||||||
|
def _fake_dsv_page_with_frames(*frames):
|
||||||
|
page = MagicMock()
|
||||||
|
page.frames = list(frames)
|
||||||
|
return page
|
||||||
|
|
||||||
|
|
||||||
|
def _fake_dsv_frame(url: str, body: str):
|
||||||
|
frame = MagicMock()
|
||||||
|
frame.url = url
|
||||||
|
frame.locator.return_value.inner_text.return_value = body
|
||||||
|
return frame
|
||||||
|
|
||||||
|
|
||||||
|
def test_assert_dsv_report_viewer_identity_passes_for_expected_program():
|
||||||
|
"""SSRS viewer 标题含 program_label 时应判定打开了目标报表,直接放行。"""
|
||||||
|
worker = _load_dsv_report_export()
|
||||||
|
viewer = _fake_dsv_frame(
|
||||||
|
"https://s360.dbschenker.com/S360Reports/SSRS/f26275b5?token=x&isLegacy=true",
|
||||||
|
"On Hand Inventory By Location AWS > Moerdijk > AWSRTM favorite_border",
|
||||||
|
)
|
||||||
|
page = _fake_dsv_page_with_frames(viewer)
|
||||||
|
|
||||||
|
worker._assert_dsv_report_viewer_identity(
|
||||||
|
page,
|
||||||
|
{"navigation": {"program_label": "AWSRTM", "report_name": "On Hand Inventory by Location"}},
|
||||||
|
timeout_ms=1000,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_assert_dsv_report_viewer_identity_raises_on_wrong_program():
|
||||||
|
"""viewer 载入 Bison 3lv(AWS > Bison > AWSBI)时应报身份不匹配。
|
||||||
|
|
||||||
|
2026-10-09 AWSRTM 事故回归:portal 顶层 Recent Reports 文本同样含 AWSRTM,
|
||||||
|
门禁只认 /s360reports/ssrs/ viewer frame,顶层的 AWSRTM 字样不得误判为匹配。
|
||||||
|
"""
|
||||||
|
worker = _load_dsv_report_export()
|
||||||
|
portal = _fake_dsv_frame(
|
||||||
|
"https://s360.dbschenker.com/main/portal/frame/reports/x",
|
||||||
|
"RECENT REPORTS On Hand Inventory By Location (Moerdijk > AWSRTM)",
|
||||||
|
)
|
||||||
|
viewer = _fake_dsv_frame(
|
||||||
|
"https://s360.dbschenker.com/S360Reports/SSRS/d40ada0a?token=x&isLegacy=true",
|
||||||
|
"On Hand Inventory By Location 3lv AWS > Bison > AWSBI favorite_border",
|
||||||
|
)
|
||||||
|
page = _fake_dsv_page_with_frames(portal, viewer)
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
with pytest.raises(RuntimeError, match="identity mismatch"):
|
||||||
|
worker._assert_dsv_report_viewer_identity(
|
||||||
|
page,
|
||||||
|
{"navigation": {"program_label": "AWSRTM", "report_name": "On Hand Inventory by Location"}},
|
||||||
|
timeout_ms=1000,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_assert_dsv_report_viewer_identity_skips_without_program_label():
|
||||||
|
"""配置缺 program_label 时应跳过身份校验(保持旧行为,不因无身份信息而失败)。"""
|
||||||
|
worker = _load_dsv_report_export()
|
||||||
|
page = _fake_dsv_page_with_frames()
|
||||||
|
|
||||||
|
worker._assert_dsv_report_viewer_identity(page, {"navigation": {"report_name": "X"}}, timeout_ms=1000)
|
||||||
|
|
||||||
|
|
||||||
|
def test_navigate_dsv_to_report_form_resets_home_when_viewer_identity_mismatch(monkeypatch):
|
||||||
|
"""viewer 载错报表(身份不匹配)时应整页 reset 后重导一次(2026-10-09 AWSRTM 串报修复)。"""
|
||||||
|
worker = _load_dsv_report_export()
|
||||||
|
page = MagicMock()
|
||||||
|
monkeypatch.setattr(worker, "_env", lambda key, default=None: "")
|
||||||
|
monkeypatch.setattr(worker, "_click_dsv_reports_menu", MagicMock())
|
||||||
|
monkeypatch.setattr(worker, "_wait_for_dsv_reports_open", MagicMock())
|
||||||
|
monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock())
|
||||||
|
monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock())
|
||||||
|
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
|
||||||
|
identity = MagicMock(side_effect=[RuntimeError("identity mismatch"), None])
|
||||||
|
monkeypatch.setattr(worker, "_assert_dsv_report_viewer_identity", identity)
|
||||||
|
reset = MagicMock()
|
||||||
|
monkeypatch.setattr(worker, "_reset_dsv_export_entry", reset)
|
||||||
|
monkeypatch.setattr(worker, "_report_dsv_chain_stage", MagicMock())
|
||||||
|
|
||||||
|
source = {
|
||||||
|
"entry_url": "https://s360.dbschenker.com/main/portal",
|
||||||
|
"navigation": {
|
||||||
|
"program_group": "Moerdijk",
|
||||||
|
"program_label": "AWSRTM",
|
||||||
|
"report_group": "Inventory",
|
||||||
|
"report_name": "On Hand Inventory by Location",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
assert worker._navigate_dsv_to_report_form(page, source) == "On Hand Inventory by Location"
|
||||||
|
assert identity.call_count == 2
|
||||||
|
reset.assert_called_once_with(page, "https://s360.dbschenker.com/main/portal")
|
||||||
|
|
||||||
|
|
||||||
|
def test_fill_dsv_filter_returns_false_when_all_paths_fail(monkeypatch):
|
||||||
|
"""配置了值但 multi_value/select/脚本/fill 全部失败时应返回 False(FILL-FAIL-FAST 契约)。"""
|
||||||
|
params = _load_rpa_module("dsv_report_parameters")
|
||||||
|
monkeypatch.setattr(params, "_fill_multi_value_parameter", MagicMock(return_value=False))
|
||||||
|
monkeypatch.setattr(params, "_fill_select_parameter", MagicMock(return_value=False))
|
||||||
|
monkeypatch.setattr(params, "_iter_dsv_report_roots", lambda page: [])
|
||||||
|
monkeypatch.setattr(params, "_find_locator", lambda page, selector: (None, None))
|
||||||
|
monkeypatch.setattr(params, "_probe_report_parameter_controls", lambda page: {})
|
||||||
|
|
||||||
|
result = params.fill_dsv_filter_if_needed(
|
||||||
|
MagicMock(),
|
||||||
|
"FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||||
|
"Warehouse",
|
||||||
|
"RTM",
|
||||||
|
env=lambda key, default=None: "",
|
||||||
|
browser_timeout_ms=lambda: 1000,
|
||||||
|
report_name="On Hand Inventory by Location",
|
||||||
|
)
|
||||||
|
assert result is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_fill_dsv_filter_returns_true_on_success_and_legitimate_skip(monkeypatch):
|
||||||
|
"""填充成功或合法跳过(值为空)应返回 True,不得被包装层误判为失败。"""
|
||||||
|
params = _load_rpa_module("dsv_report_parameters")
|
||||||
|
# JDA 模板下 Warehouse 是 multi_value 控件:mock 主路径成功即可验证 True 契约。
|
||||||
|
monkeypatch.setattr(params, "_fill_multi_value_parameter", MagicMock(return_value=True))
|
||||||
|
monkeypatch.setattr(params, "_fill_select_parameter", MagicMock(return_value=False))
|
||||||
|
monkeypatch.setattr(params, "_iter_dsv_report_roots", lambda page: [])
|
||||||
|
monkeypatch.setattr(params, "_find_locator", lambda page, selector: (None, None))
|
||||||
|
|
||||||
|
filled = params.fill_dsv_filter_if_needed(
|
||||||
|
MagicMock(),
|
||||||
|
"FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||||
|
"Warehouse",
|
||||||
|
"RTM",
|
||||||
|
env=lambda key, default=None: "",
|
||||||
|
browser_timeout_ms=lambda: 1000,
|
||||||
|
report_name="On Hand Inventory by Location",
|
||||||
|
)
|
||||||
|
skipped = params.fill_dsv_filter_if_needed(
|
||||||
|
MagicMock(),
|
||||||
|
"FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||||
|
"Warehouse",
|
||||||
|
None,
|
||||||
|
env=lambda key, default=None: "",
|
||||||
|
browser_timeout_ms=lambda: 1000,
|
||||||
|
report_name="On Hand Inventory by Location",
|
||||||
|
)
|
||||||
|
assert filled is True
|
||||||
|
assert skipped is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_fill_dsv_filter_wrapper_raises_on_fill_failure(monkeypatch):
|
||||||
|
"""包装层在 fill 返回 False 时必须抛错中止本源(2026-10-09 静默吞掉曾连环误报)。"""
|
||||||
|
worker = _load_dsv_report_export()
|
||||||
|
fake_module = MagicMock()
|
||||||
|
fake_module.fill_dsv_filter_if_needed.return_value = False
|
||||||
|
monkeypatch.setattr(worker.importlib.util, "spec_from_file_location", lambda *a, **k: MagicMock())
|
||||||
|
monkeypatch.setattr(worker.importlib.util, "module_from_spec", lambda *a, **k: fake_module)
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
with pytest.raises(RuntimeError, match="fill failed"):
|
||||||
|
worker._fill_dsv_filter_if_needed(MagicMock(), "ENV", "Warehouse", "RTM")
|
||||||
|
|
||||||
|
|
||||||
|
def test_fill_dsv_filter_wrapper_silent_on_fill_success(monkeypatch):
|
||||||
|
"""fill 返回 True(已填充/合法跳过)时包装层不得抛错。"""
|
||||||
|
worker = _load_dsv_report_export()
|
||||||
|
fake_module = MagicMock()
|
||||||
|
fake_module.fill_dsv_filter_if_needed.return_value = True
|
||||||
|
monkeypatch.setattr(worker.importlib.util, "spec_from_file_location", lambda *a, **k: MagicMock())
|
||||||
|
monkeypatch.setattr(worker.importlib.util, "module_from_spec", lambda *a, **k: fake_module)
|
||||||
|
|
||||||
|
worker._fill_dsv_filter_if_needed(MagicMock(), "ENV", "Warehouse", "RTM")
|
||||||
|
|
||||||
|
|
||||||
def test_reset_dsv_export_entry_skips_login_when_session_active(monkeypatch):
|
def test_reset_dsv_export_entry_skips_login_when_session_active(monkeypatch):
|
||||||
"""同 entry_url 且 session 有效时 reset 不应再触发 auto_login,但应 goto portal 首页。"""
|
"""同 entry_url 且 session 有效时 reset 不应再触发 auto_login,但应 goto portal 首页。"""
|
||||||
worker = _load_dsv_report_export()
|
worker = _load_dsv_report_export()
|
||||||
@@ -696,6 +871,7 @@ def test_navigate_dsv_to_report_form_clicks_program_group_before_program_label(m
|
|||||||
lambda page_arg, text, *, next_text="": group_calls.append((text, next_text)),
|
lambda page_arg, text, *, next_text="": group_calls.append((text, next_text)),
|
||||||
)
|
)
|
||||||
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
|
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
|
||||||
|
monkeypatch.setattr(worker, "_assert_dsv_report_viewer_identity", MagicMock())
|
||||||
|
|
||||||
source = {
|
source = {
|
||||||
"navigation": {
|
"navigation": {
|
||||||
|
|||||||
@@ -0,0 +1,555 @@
|
|||||||
|
"""
|
||||||
|
backend/tests/test_lean_training_push.py
|
||||||
|
|
||||||
|
用途:覆盖精益管理培训"推过的视频绝不重复推"的跨任务推送契约与企微提醒催办规则。
|
||||||
|
依赖:pytest、Flask test client、LeanTrainingWeeklyTask/TrainingConfig/AgentGuide 模型、lean_training_* 服务。
|
||||||
|
逻辑:验证 HR 手动新建下一期周任务必须继承上一期推送游标(不从 0 重推首批),
|
||||||
|
且推送分批时跳过其它任务已推送的视频,自动从上一任务断点继续向后推进直至全部推完;
|
||||||
|
逾期/延期提醒文案携带期次标签(第N期+周次区间)供员工区分期次,多期过期任务对同一员工
|
||||||
|
合并为一条汇总提醒且每人每天最多一条自动催办(排程扫描/推送后延期双路径当天去重),
|
||||||
|
历史期任务过截止超过 100 天宽限期后停止催办。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from flask import current_app
|
||||||
|
from sqlalchemy import select
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.api import training as training_api
|
||||||
|
from app.core.errors import NotFoundError
|
||||||
|
from app.models import Agent, AgentGuide, LeanTrainingWeeklyTask, TrainingConfig, TrainingConfigResource, User
|
||||||
|
from app.services import lean_training_push_service, lean_training_reminder_service, lean_training_service
|
||||||
|
|
||||||
|
|
||||||
|
def _create_hr_user(*, username: str) -> User:
|
||||||
|
"""创建具备培训管理权限的用户,兼作受训对象(role=user)。"""
|
||||||
|
user = User(
|
||||||
|
username=username,
|
||||||
|
email=f"{username}@example.com",
|
||||||
|
role="user",
|
||||||
|
status="active",
|
||||||
|
real_name=f"{username}-实名",
|
||||||
|
employee_id=f"{username.upper()}-EMP",
|
||||||
|
department="生产一部",
|
||||||
|
)
|
||||||
|
user.set_feature_permissions({"training_hr_manage": True})
|
||||||
|
user.set_password("password123")
|
||||||
|
db.session.add(user)
|
||||||
|
db.session.commit()
|
||||||
|
db.session.refresh(user)
|
||||||
|
db.session.expunge(user)
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _create_lean_video_config(*, video_count: int) -> tuple[int, list[int]]:
|
||||||
|
"""
|
||||||
|
创建已发布精益培训配置并挂 video_count 个视频资源。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(config_id, desc_resource_ids):desc_resource_ids 为按上传时间倒序的自动填充顺序(新视频在前)。
|
||||||
|
"""
|
||||||
|
agent = Agent(name="lean_video_agent", type="api")
|
||||||
|
db.session.add(agent)
|
||||||
|
db.session.flush()
|
||||||
|
config = TrainingConfig(training_type="lean_management", name="精益管理培训", version="v1", status="published")
|
||||||
|
db.session.add(config)
|
||||||
|
db.session.flush()
|
||||||
|
asc_ids: list[int] = []
|
||||||
|
base = datetime.utcnow() - timedelta(days=30)
|
||||||
|
for index in range(video_count):
|
||||||
|
guide = AgentGuide(
|
||||||
|
agent_id=agent.id,
|
||||||
|
file_name=f"lean-video-{index}.mp4",
|
||||||
|
file_type="video",
|
||||||
|
file_path=f"lean/video-{index}.mp4",
|
||||||
|
created_at=base + timedelta(days=index),
|
||||||
|
)
|
||||||
|
db.session.add(guide)
|
||||||
|
db.session.flush()
|
||||||
|
resource = TrainingConfigResource(
|
||||||
|
config_id=config.id,
|
||||||
|
resource_type="agent_guide",
|
||||||
|
training_level="company",
|
||||||
|
agent_guide_id=guide.id,
|
||||||
|
title=f"精益视频{index + 1}",
|
||||||
|
created_at=base + timedelta(days=index),
|
||||||
|
)
|
||||||
|
db.session.add(resource)
|
||||||
|
db.session.flush()
|
||||||
|
asc_ids.append(resource.id)
|
||||||
|
db.session.commit()
|
||||||
|
return config.id, list(reversed(asc_ids))
|
||||||
|
|
||||||
|
|
||||||
|
def _create_last_week_task(*, config_id: int, video_resource_ids: list[int], pushed_video_count: int) -> None:
|
||||||
|
"""直接落库一期"上一周"已发布任务,冻结视频列表并写入指定推送游标。"""
|
||||||
|
week_start, due_at = lean_training_service._current_week_bounds()
|
||||||
|
db.session.add(LeanTrainingWeeklyTask(
|
||||||
|
config_id=config_id,
|
||||||
|
week_key=(week_start - timedelta(days=7)).isoformat(),
|
||||||
|
due_at=due_at - timedelta(days=7),
|
||||||
|
video_resource_ids=video_resource_ids,
|
||||||
|
weekly_count=1,
|
||||||
|
pushed_video_count=pushed_video_count,
|
||||||
|
target_roles=["user"],
|
||||||
|
target_user_ids=[],
|
||||||
|
status="published",
|
||||||
|
))
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def _create_published_task(
|
||||||
|
*,
|
||||||
|
config_id: int,
|
||||||
|
video_resource_ids: list[int],
|
||||||
|
week_key: str,
|
||||||
|
due_utc: datetime,
|
||||||
|
target_user_ids: list[int],
|
||||||
|
) -> LeanTrainingWeeklyTask:
|
||||||
|
"""
|
||||||
|
落库一期指定周次的已发布任务(提醒文案/停止催办测试用),冻结列表并整体置为已推送。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
week_key: 该周周一的 ISO 日期文本(固定日期保证期号与 weekday 断言确定)。
|
||||||
|
due_utc: 截止时间(UTC naive,如北京周日 23:59:59 对应 UTC 15:59:59)。
|
||||||
|
target_user_ids: 显式受训对象(不经角色匹配,避免误圈其它测试用户)。
|
||||||
|
"""
|
||||||
|
task = LeanTrainingWeeklyTask(
|
||||||
|
config_id=config_id,
|
||||||
|
week_key=week_key,
|
||||||
|
due_at=due_utc,
|
||||||
|
video_resource_ids=video_resource_ids,
|
||||||
|
weekly_count=1,
|
||||||
|
pushed_video_count=len(video_resource_ids),
|
||||||
|
target_roles=[],
|
||||||
|
target_user_ids=target_user_ids,
|
||||||
|
status="published",
|
||||||
|
)
|
||||||
|
db.session.add(task)
|
||||||
|
db.session.commit()
|
||||||
|
return task
|
||||||
|
|
||||||
|
|
||||||
|
def _auth_headers(user: User) -> dict[str, str]:
|
||||||
|
"""生成管理端接口测试鉴权头,显式携带 user_id 以稳定命中 legacy 用户解析。"""
|
||||||
|
return {"X-User-Id": str(user.id), "X-Username": user.username, "Content-Type": "application/json"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_manual_new_week_task_inherits_cursor_and_skips_auto_push(client, app, monkeypatch):
|
||||||
|
"""关键断言:上一期视频全部推送后,手动新建下一期必须继承游标——不自动重推首批、不重复发企微。"""
|
||||||
|
push_messages: list[dict] = []
|
||||||
|
initial_messages: list[dict] = []
|
||||||
|
monkeypatch.setattr(
|
||||||
|
lean_training_push_service,
|
||||||
|
"_send_reminder",
|
||||||
|
lambda **kwargs: push_messages.append(kwargs) or "sent",
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
lean_training_reminder_service,
|
||||||
|
"_send_reminder",
|
||||||
|
lambda **kwargs: initial_messages.append(kwargs) or "sent",
|
||||||
|
)
|
||||||
|
with app.app_context():
|
||||||
|
hr = _create_hr_user(username="lean_hr_inherit")
|
||||||
|
config_id, desc_ids = _create_lean_video_config(video_count=2)
|
||||||
|
# [STEP] 上一期已按自动填充顺序把 2 个视频全部推完(游标=2)
|
||||||
|
_create_last_week_task(config_id=config_id, video_resource_ids=list(desc_ids), pushed_video_count=2)
|
||||||
|
week_start, _ = lean_training_service._current_week_bounds()
|
||||||
|
|
||||||
|
response = client.post("/api/admin/lean-training/weekly-tasks", headers=_auth_headers(hr), json={
|
||||||
|
"week_key": week_start.isoformat(),
|
||||||
|
"video_resource_ids": [],
|
||||||
|
"target_roles": ["user"],
|
||||||
|
"target_user_ids": [],
|
||||||
|
"weekly_count": 1,
|
||||||
|
})
|
||||||
|
|
||||||
|
assert response.status_code == 201
|
||||||
|
body = response.get_json()
|
||||||
|
# [ASSERT] 新任务游标必须继承上一期的全部推送进度,而非从 0 开始
|
||||||
|
assert body["data"]["pushed_video_count"] == 2
|
||||||
|
# [ASSERT] 游标非 0 时不触发发布首批推送,员工不会收到重复的"精益管理培训视频推送"企微通知
|
||||||
|
assert push_messages == []
|
||||||
|
assert len(initial_messages) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_new_week_task_continues_from_last_cursor_and_never_repushes(client, app, monkeypatch):
|
||||||
|
"""关键断言:存在未推送视频时从断点只推新视频;剩余全是已推送视频时游标直接推到末尾且不再发企微。"""
|
||||||
|
push_messages: list[dict] = []
|
||||||
|
monkeypatch.setattr(
|
||||||
|
lean_training_push_service,
|
||||||
|
"_send_reminder",
|
||||||
|
lambda **kwargs: push_messages.append(kwargs) or "sent",
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(lean_training_reminder_service, "_send_reminder", lambda **kwargs: "sent")
|
||||||
|
with app.app_context():
|
||||||
|
hr = _create_hr_user(username="lean_hr_continue")
|
||||||
|
config_id, desc_ids = _create_lean_video_config(video_count=3)
|
||||||
|
# [STEP] 资源按上传倒序为 desc_ids=[r3, r2, r1];上一期冻结 [r2, r1] 并已全部推完
|
||||||
|
r3, r2, r1 = desc_ids
|
||||||
|
_create_last_week_task(config_id=config_id, video_resource_ids=[r2, r1], pushed_video_count=2)
|
||||||
|
week_start, _ = lean_training_service._current_week_bounds()
|
||||||
|
|
||||||
|
create_response = client.post("/api/admin/lean-training/weekly-tasks", headers=_auth_headers(hr), json={
|
||||||
|
"week_key": week_start.isoformat(),
|
||||||
|
"video_resource_ids": [],
|
||||||
|
"target_roles": ["user"],
|
||||||
|
"target_user_ids": [],
|
||||||
|
"weekly_count": 1,
|
||||||
|
})
|
||||||
|
|
||||||
|
assert create_response.status_code == 201
|
||||||
|
task = create_response.get_json()["data"]
|
||||||
|
assert task["video_resource_ids"] == [r3, r2, r1]
|
||||||
|
# [ASSERT] 新列表首个视频未被推送过 → 继承游标 0 并自动推首批,但批次只含"新视频 r3",绝不重推 r1/r2
|
||||||
|
assert task["pushed_video_count"] == 1
|
||||||
|
assert len(push_messages) == 1
|
||||||
|
assert push_messages[0]["event_key"] == "video-push-0-1"
|
||||||
|
|
||||||
|
# [STEP] HR 手动推送下一批:待推区间 [r2, r1] 全部已被上一期推送过 → 视为推完,不发企微
|
||||||
|
push_response = client.post(f"/api/admin/lean-training/weekly-tasks/{task['id']}/push", headers=_auth_headers(hr))
|
||||||
|
|
||||||
|
assert push_response.status_code == 200
|
||||||
|
push_result = push_response.get_json()
|
||||||
|
assert push_result["data"]["status"] == "completed"
|
||||||
|
assert push_result["data"]["pushed_count"] == 0
|
||||||
|
# [ASSERT] 游标越过重复视频推进到列表末尾,企微通知始终只有首批新视频那一轮
|
||||||
|
refreshed = client.get(f"/api/admin/lean-training/weekly-tasks/{task['id']}", headers=_auth_headers(hr))
|
||||||
|
assert refreshed.get_json()["data"]["pushed_video_count"] == 3
|
||||||
|
assert len(push_messages) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_auto_roll_appends_new_videos_and_continues_push_from_cursor(app, monkeypatch):
|
||||||
|
"""关键断言:每周自动滚动继承游标并自动追加配置新增视频,推送只从断点继续推新视频、绝不重推旧视频。"""
|
||||||
|
push_messages: list[dict] = []
|
||||||
|
monkeypatch.setattr(
|
||||||
|
lean_training_push_service,
|
||||||
|
"_send_reminder",
|
||||||
|
lambda **kwargs: push_messages.append(kwargs) or "sent",
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(lean_training_reminder_service, "_send_reminder", lambda **kwargs: "sent")
|
||||||
|
with app.app_context():
|
||||||
|
_create_hr_user(username="lean_hr_roll")
|
||||||
|
config_id, desc_ids = _create_lean_video_config(video_count=4)
|
||||||
|
# [STEP] 等价"手动勾选补齐并推完"后的状态:上一期冻结 4 个视频、游标 4/4;配置随后新上传第 5 个视频
|
||||||
|
_create_last_week_task(config_id=config_id, video_resource_ids=list(desc_ids), pushed_video_count=4)
|
||||||
|
agent = db.session.execute(select(Agent).where(Agent.name == "lean_video_agent")).scalars().first()
|
||||||
|
new_guide = AgentGuide(
|
||||||
|
agent_id=agent.id,
|
||||||
|
file_name="lean-video-new.mp4",
|
||||||
|
file_type="video",
|
||||||
|
file_path="lean/video-new.mp4",
|
||||||
|
created_at=datetime.utcnow(),
|
||||||
|
)
|
||||||
|
db.session.add(new_guide)
|
||||||
|
db.session.flush()
|
||||||
|
new_resource = TrainingConfigResource(
|
||||||
|
config_id=config_id,
|
||||||
|
resource_type="agent_guide",
|
||||||
|
training_level="company",
|
||||||
|
agent_guide_id=new_guide.id,
|
||||||
|
title="精益视频新增",
|
||||||
|
created_at=datetime.utcnow(),
|
||||||
|
)
|
||||||
|
db.session.add(new_resource)
|
||||||
|
db.session.commit()
|
||||||
|
new_resource_id = new_resource.id
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
rolled = lean_training_push_service.ensure_current_week_task()
|
||||||
|
|
||||||
|
assert rolled is not None
|
||||||
|
rolled_ids = list(rolled.video_resource_ids)
|
||||||
|
# [ASSERT] 已推送前缀原样保留在列表头部,新视频自动追加到末尾,游标继承不受追加影响
|
||||||
|
assert rolled_ids == [*desc_ids, new_resource_id]
|
||||||
|
assert rolled.pushed_video_count == 4
|
||||||
|
rolled_id = rolled.id
|
||||||
|
|
||||||
|
push_result = lean_training_push_service.push_lean_training_videos(rolled.id, trigger="schedule")
|
||||||
|
|
||||||
|
# [ASSERT] 首次推送只含新视频(断点续推),旧视频一个都不重推
|
||||||
|
assert push_result["status"] == "sent"
|
||||||
|
assert push_result["pushed_resource_ids"] == [new_resource_id]
|
||||||
|
assert len(push_messages) == 1
|
||||||
|
assert push_messages[0]["event_key"] == "video-push-4-5"
|
||||||
|
refreshed = db.session.get(LeanTrainingWeeklyTask, rolled_id)
|
||||||
|
assert refreshed.pushed_video_count == 5
|
||||||
|
|
||||||
|
# [STEP] 再次推送:待推区间为空 → 推完即停,不再发企微
|
||||||
|
second_result = lean_training_push_service.push_lean_training_videos(rolled.id, trigger="manual")
|
||||||
|
|
||||||
|
assert second_result["status"] == "completed"
|
||||||
|
assert len(push_messages) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_lean_reminders_jump_to_training_agent_dynamically(app, monkeypatch):
|
||||||
|
"""关键断言:精益企微卡片必须动态解析各环境的「员工培训」Agent(content_profile=training),不得依赖固定 ID 27。"""
|
||||||
|
sent: list[dict] = []
|
||||||
|
monkeypatch.setattr(
|
||||||
|
lean_training_reminder_service,
|
||||||
|
"send_wecom_event_message",
|
||||||
|
lambda **kwargs: sent.append(kwargs) or {"ok": True, "trace_id": "lean-jump-trace"},
|
||||||
|
)
|
||||||
|
with app.app_context():
|
||||||
|
hr = _create_hr_user(username="lean_hr_jump")
|
||||||
|
config_id, desc_ids = _create_lean_video_config(video_count=1)
|
||||||
|
training_agent = Agent(name="员工培训", type="api", handler_config={"content_profile": "training"})
|
||||||
|
db.session.add(training_agent)
|
||||||
|
db.session.flush()
|
||||||
|
week_start, due_at = lean_training_service._current_week_bounds()
|
||||||
|
task = LeanTrainingWeeklyTask(
|
||||||
|
config_id=config_id,
|
||||||
|
week_key=week_start.isoformat(),
|
||||||
|
due_at=due_at,
|
||||||
|
video_resource_ids=list(desc_ids),
|
||||||
|
weekly_count=1,
|
||||||
|
pushed_video_count=0,
|
||||||
|
target_roles=[],
|
||||||
|
target_user_ids=[hr.id],
|
||||||
|
status="published",
|
||||||
|
)
|
||||||
|
db.session.add(task)
|
||||||
|
db.session.commit()
|
||||||
|
task_id, training_agent_id = task.id, training_agent.id
|
||||||
|
|
||||||
|
totals = lean_training_reminder_service.send_initial_target_notifications(task_id)
|
||||||
|
|
||||||
|
assert totals["sent"] == 1
|
||||||
|
assert len(sent) == 1
|
||||||
|
# [ASSERT] 跳转路径动态指向本环境培训 Agent(即使 ID≠27 也正确),并携带精益页签深链参数
|
||||||
|
assert sent[0]["jump_path"] == f"/chat/{training_agent_id}"
|
||||||
|
assert sent[0]["jump_params"]["training_type"] == "lean_management"
|
||||||
|
assert sent[0]["jump_params"]["weekly_task_id"] == task_id
|
||||||
|
|
||||||
|
|
||||||
|
def test_lean_jump_agent_id_config_override_and_legacy_fallback(app, monkeypatch):
|
||||||
|
"""关键断言:显式配置优先于动态解析;无配置且无培训 Agent 时回退历史默认 27 保持兼容。"""
|
||||||
|
with app.app_context():
|
||||||
|
# [ASSERT] 显式配置覆盖动态解析(运维固定指向特定 Agent 的逃生通道)
|
||||||
|
monkeypatch.setitem(current_app.config, "WECOM_LEAN_TRAINING_JUMP_AGENT_ID", 999)
|
||||||
|
assert lean_training_service.resolve_lean_training_jump_agent_id() == 999
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
monkeypatch.setitem(current_app.config, "WECOM_LEAN_TRAINING_JUMP_AGENT_ID", 0)
|
||||||
|
# [ASSERT] 系统内不存在培训 Agent 时回退历史默认 27
|
||||||
|
assert lean_training_service.resolve_lean_training_jump_agent_id() == 27
|
||||||
|
|
||||||
|
|
||||||
|
def test_auto_roll_pauses_when_all_videos_pushed_and_no_new_videos(app):
|
||||||
|
"""关键断言:视频库全部推完且配置无新增视频时,自动滚动不再创建内容重复的新一期任务(暂停)。"""
|
||||||
|
with app.app_context():
|
||||||
|
_create_hr_user(username="lean_hr_pause")
|
||||||
|
config_id, desc_ids = _create_lean_video_config(video_count=2)
|
||||||
|
# [STEP] 等价"每周推 2 个、库内共 2 个视频":上一期已把全部视频推完(游标 2/2)
|
||||||
|
_create_last_week_task(config_id=config_id, video_resource_ids=list(desc_ids), pushed_video_count=2)
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
rolled = lean_training_push_service.ensure_current_week_task()
|
||||||
|
|
||||||
|
# [ASSERT] 无新视频可推时滚动暂停(返回 None),不创建重复内容的新一期任务
|
||||||
|
assert rolled is None
|
||||||
|
with app.app_context():
|
||||||
|
remaining = db.session.execute(select(LeanTrainingWeeklyTask)).scalars().all()
|
||||||
|
assert len(remaining) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_format_beijing_iso_converts_utc_storage_to_beijing_display():
|
||||||
|
"""关键断言:序列化输出的观看/完成/截止时间必须为北京时间(+08:00)——UTC naive 10:47 对应北京 18:47,
|
||||||
|
此前 UTC 直出导致页面显示比实际早 8 小时(18:47 完成显示 10:47)。"""
|
||||||
|
# [ASSERT] UTC naive(数据库存储口径)→ 北京时间 +08:00
|
||||||
|
assert lean_training_service.format_beijing_iso(datetime(2026, 9, 22, 10, 47, 33)) == "2026-09-22T18:47:33+08:00"
|
||||||
|
# [ASSERT] UTC 带 Z 文本(老数据/客户端口径)→ 北京时间
|
||||||
|
assert lean_training_service.format_beijing_iso("2026-09-22T10:47:33+00:00") == "2026-09-22T18:47:33+08:00"
|
||||||
|
# [ASSERT] 已是北京时间的文本保持墙钟不变(幂等,前端回显值二次进入不重复偏移)
|
||||||
|
assert lean_training_service.format_beijing_iso("2026-09-22T18:47:33+08:00") == "2026-09-22T18:47:33+08:00"
|
||||||
|
# [ASSERT] 空值返回 None,非法文本原样返回(历史脏数据不阻塞展示)
|
||||||
|
assert lean_training_service.format_beijing_iso(None) is None
|
||||||
|
assert lean_training_service.format_beijing_iso("") is None
|
||||||
|
assert lean_training_service.format_beijing_iso("not-a-time") == "not-a-time"
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_client_iso_to_utc_text_normalizes_client_echo_to_utc_storage():
|
||||||
|
"""关键断言:save_completion 兜底入库的客户端回显时间必须归一为 UTC naive 文本,
|
||||||
|
保证 watched_at_json"存储一律 UTC"约定不被北京时间回显值破坏。"""
|
||||||
|
# [ASSERT] 北京时间(+08:00)→ UTC naive
|
||||||
|
assert lean_training_service.parse_client_iso_to_utc_text("2026-09-22T18:47:33+08:00") == "2026-09-22T10:47:33"
|
||||||
|
# [ASSERT] UTC 带 Z(老版客户端 toISOString 口径)→ 去时区 UTC
|
||||||
|
assert lean_training_service.parse_client_iso_to_utc_text("2026-09-22T10:47:33Z") == "2026-09-22T10:47:33"
|
||||||
|
# [ASSERT] naive 按北京时间墙钟解释 → UTC
|
||||||
|
assert lean_training_service.parse_client_iso_to_utc_text("2026-09-22T18:47:33") == "2026-09-22T10:47:33"
|
||||||
|
# [ASSERT] 非法文本原样返回,不阻塞感悟提交
|
||||||
|
assert lean_training_service.parse_client_iso_to_utc_text("garbage") == "garbage"
|
||||||
|
|
||||||
|
|
||||||
|
def test_learner_period_videos_only_own_first_pushed(app):
|
||||||
|
"""关键断言:自动滚动复制上一期冻结列表后(第2期前缀含上一期已推视频的脏数据),
|
||||||
|
学员端/看板/完成校验的"本期视频"只含本任务首次推送的部分——上一期已推送视频不再重复展示、不要求重学;
|
||||||
|
第1期自身展示不受影响;管理端任务详情仍返回全量冻结列表。"""
|
||||||
|
with app.app_context():
|
||||||
|
learner = _create_hr_user(username="lean_learner_own")
|
||||||
|
config_id, desc_ids = _create_lean_video_config(video_count=4)
|
||||||
|
# [STEP] 复刻生产事故数据:资源按上传倒序 desc_ids=[r4, r3, r2, r1];
|
||||||
|
# 第1期冻结 [r2, r1] 已推完,自动滚动第2期 = [r2, r1, r4, r3]、继承游标 2 后推完新视频 → 游标 4
|
||||||
|
r4, r3, r2, r1 = desc_ids
|
||||||
|
_create_last_week_task(config_id=config_id, video_resource_ids=[r2, r1], pushed_video_count=2)
|
||||||
|
week_start, due_at = lean_training_service._current_week_bounds()
|
||||||
|
current_task = LeanTrainingWeeklyTask(
|
||||||
|
config_id=config_id,
|
||||||
|
week_key=week_start.isoformat(),
|
||||||
|
due_at=due_at,
|
||||||
|
video_resource_ids=[r2, r1, r4, r3],
|
||||||
|
weekly_count=2,
|
||||||
|
pushed_video_count=4,
|
||||||
|
target_roles=["user"],
|
||||||
|
target_user_ids=[],
|
||||||
|
status="published",
|
||||||
|
)
|
||||||
|
db.session.add(current_task)
|
||||||
|
db.session.commit()
|
||||||
|
current_task_id = current_task.id
|
||||||
|
|
||||||
|
# [ASSERT] 第1期不受影响:本任务首推的 [r2, r1] 全量展示
|
||||||
|
mine = {item["week_key"]: item for item in lean_training_service.list_my_weekly_tasks(learner)}
|
||||||
|
assert mine[(week_start - timedelta(days=7)).isoformat()]["video_resource_ids"] == [r2, r1]
|
||||||
|
# [ASSERT] 第2期学员端只展示本任务首次推送的 [r4, r3],上一期已推的 r2/r1 不再出现(推过的视频不能重复再推)
|
||||||
|
assert mine[week_start.isoformat()]["video_resource_ids"] == [r4, r3]
|
||||||
|
assert [video["id"] for video in mine[week_start.isoformat()]["videos"]] == [r4, r3]
|
||||||
|
|
||||||
|
# [ASSERT] 管理看板任务详情仍是全量冻结列表,但人员行视频列只列本期布置的 [r4, r3]
|
||||||
|
dashboard = lean_training_service.list_dashboard(current_task_id)
|
||||||
|
assert dashboard["task"]["video_resource_ids"] == [r2, r1, r4, r3]
|
||||||
|
assert dashboard["incomplete"][0]["videos"] == [
|
||||||
|
{"name": "精益视频4", "watched_at": None},
|
||||||
|
{"name": "精益视频3", "watched_at": None},
|
||||||
|
]
|
||||||
|
|
||||||
|
# [ASSERT] 其它任务首推的视频(r2)不在本期学习范围,观看记录被拒绝
|
||||||
|
with pytest.raises(NotFoundError):
|
||||||
|
lean_training_service.mark_video_watched(learner, {"weekly_task_id": current_task_id, "resource_id": r2})
|
||||||
|
|
||||||
|
# [ASSERT] 完成校验只考核本任务首推视频:仅观看 r4/r3 并提交达标感悟即完成,不要求重看上一期的 r1/r2
|
||||||
|
result = lean_training_service.save_completion(learner, {
|
||||||
|
"weekly_task_id": current_task_id,
|
||||||
|
"watched_at": {str(r4): "2026-09-28T10:00:00", str(r3): "2026-09-28T11:00:00"},
|
||||||
|
"summary_text": "通过本期两个新视频的学习,我认识到持续改善要从小处着手,先改变思维再改变行动,后续会在日常工作中主动发现问题并逐步优化,让改善真正落地。",
|
||||||
|
})
|
||||||
|
assert result["status"] == "completed"
|
||||||
|
assert [video["name"] for video in result["videos"]] == ["精益视频4", "精益视频3"]
|
||||||
|
assert all(video["watched_at"] for video in result["videos"])
|
||||||
|
|
||||||
|
# [ASSERT] 看板行同步反映本期口径与完成状态
|
||||||
|
refreshed = lean_training_service.list_dashboard(current_task_id)
|
||||||
|
assert [row["videos"] for row in refreshed["completed"]] != []
|
||||||
|
assert refreshed["completed"][0]["status"] == "completed"
|
||||||
|
|
||||||
|
|
||||||
|
def test_lean_overdue_reminder_texts_carry_period_labels(app, monkeypatch):
|
||||||
|
"""关键断言:多期任务并存扫描时,逾期提醒标题/内容必须携带期次标签(第N期+周次区间),
|
||||||
|
员工可分辨催办归属哪一期,避免"完成当期后仍收到历史期相同提醒"被误认为系统误推
|
||||||
|
(2026-09-30 正式环境用户反馈);未过截止的当期任务不产生逾期提醒。"""
|
||||||
|
sent: list[dict] = []
|
||||||
|
monkeypatch.setattr(
|
||||||
|
lean_training_reminder_service,
|
||||||
|
"send_wecom_event_message",
|
||||||
|
lambda **kwargs: sent.append(kwargs) or {"ok": True, "trace_id": "period-trace"},
|
||||||
|
)
|
||||||
|
with app.app_context():
|
||||||
|
hr = _create_hr_user(username="lean_hr_period")
|
||||||
|
config_id, desc_ids = _create_lean_video_config(video_count=1)
|
||||||
|
# [STEP] 第1期(9-21周)已过截止,第2期(9-28当期)未过截止;扫描时刻=2026-09-30(周三)北京 09:00(UTC 01:00)
|
||||||
|
_create_published_task(
|
||||||
|
config_id=config_id, video_resource_ids=list(desc_ids),
|
||||||
|
week_key="2026-09-21", due_utc=datetime(2026, 9, 27, 15, 59, 59), target_user_ids=[hr.id])
|
||||||
|
_create_published_task(
|
||||||
|
config_id=config_id, video_resource_ids=list(desc_ids),
|
||||||
|
week_key="2026-09-28", due_utc=datetime(2026, 10, 4, 15, 59, 59), target_user_ids=[hr.id])
|
||||||
|
|
||||||
|
result = lean_training_reminder_service.run_lean_training_reminders(now=datetime(2026, 9, 30, 1, 0, 0))
|
||||||
|
|
||||||
|
# [ASSERT] 仅已过截止的第1期触发一轮提醒,且标题带期次、内容以完整周次区间开头
|
||||||
|
assert result["sent"] == 1
|
||||||
|
assert sent[0]["title"] == "精益管理培训逾期提醒(第1期)"
|
||||||
|
assert sent[0]["content"].startswith("第1期(09-21至09-27)")
|
||||||
|
# [ASSERT] 未过截止的第2期不发送任何逾期提醒
|
||||||
|
assert all("第2期" not in message["title"] for message in sent)
|
||||||
|
|
||||||
|
|
||||||
|
def test_lean_overdue_reminders_stop_after_grace_days(app, monkeypatch):
|
||||||
|
"""关键断言:已过截止超过 100 天宽限期的历史期任务停止催办——排程扫描与推送后延期提醒
|
||||||
|
两条路径均静默,任务保持 published 供管理端查询,但不再对旧账无限期发送企微。"""
|
||||||
|
sent: list[dict] = []
|
||||||
|
monkeypatch.setattr(
|
||||||
|
lean_training_reminder_service,
|
||||||
|
"send_wecom_event_message",
|
||||||
|
lambda **kwargs: sent.append(kwargs) or {"ok": True, "trace_id": "stop-trace"},
|
||||||
|
)
|
||||||
|
with app.app_context():
|
||||||
|
hr = _create_hr_user(username="lean_hr_stop")
|
||||||
|
config_id, desc_ids = _create_lean_video_config(video_count=1)
|
||||||
|
# [STEP] 截止 2026-05-31(北京),早于扫描时刻 2026-09-30 已 122 天,超出 100 天宽限期
|
||||||
|
stale_task = _create_published_task(
|
||||||
|
config_id=config_id, video_resource_ids=list(desc_ids),
|
||||||
|
week_key="2026-05-25", due_utc=datetime(2026, 5, 31, 15, 59, 59), target_user_ids=[hr.id])
|
||||||
|
stale_task_id = stale_task.id
|
||||||
|
|
||||||
|
scan_result = lean_training_reminder_service.run_lean_training_reminders(now=datetime(2026, 9, 30, 1, 0, 0))
|
||||||
|
|
||||||
|
# [ASSERT] 排程扫描对超宽限期任务静默(event_key 直接不生成)
|
||||||
|
assert scan_result["sent"] == 0
|
||||||
|
|
||||||
|
# [ASSERT] HR 对历史期手动补推视频触发的"推送后延期提醒"同样受宽限期约束
|
||||||
|
overdue_result = lean_training_reminder_service.notify_overdue_users_after_push(
|
||||||
|
db.session.get(LeanTrainingWeeklyTask, stale_task_id),
|
||||||
|
current=datetime(2026, 9, 30, 1, 0, 0),
|
||||||
|
)
|
||||||
|
assert overdue_result["sent"] == 0
|
||||||
|
assert sent == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_lean_overdue_reminder_merges_periods_per_user_per_day(app, monkeypatch):
|
||||||
|
"""关键断言:多期过期任务并存时,同一员工同一天只收到一条精益催办——
|
||||||
|
排程扫描把多期未完成合并为一条汇总提醒(文案列明各期次);
|
||||||
|
同天再触发推送后延期提醒或重复扫描均静默跳过(2026-09-30 用户反馈一人一天收到多条相同催办)。"""
|
||||||
|
sent: list[dict] = []
|
||||||
|
monkeypatch.setattr(
|
||||||
|
lean_training_reminder_service,
|
||||||
|
"send_wecom_event_message",
|
||||||
|
lambda **kwargs: sent.append(kwargs) or {"ok": True, "trace_id": "merge-trace"},
|
||||||
|
)
|
||||||
|
with app.app_context():
|
||||||
|
hr = _create_hr_user(username="lean_hr_merge")
|
||||||
|
config_id, desc_ids = _create_lean_video_config(video_count=1)
|
||||||
|
# [STEP] 两期均已过截止(9-14 期、9-21 期)且该员工都未完成;扫描时刻=2026-09-30(周三)北京 09:00
|
||||||
|
week1_task = _create_published_task(
|
||||||
|
config_id=config_id, video_resource_ids=list(desc_ids),
|
||||||
|
week_key="2026-09-14", due_utc=datetime(2026, 9, 20, 15, 59, 59), target_user_ids=[hr.id])
|
||||||
|
week2_task = _create_published_task(
|
||||||
|
config_id=config_id, video_resource_ids=list(desc_ids),
|
||||||
|
week_key="2026-09-21", due_utc=datetime(2026, 9, 27, 15, 59, 59), target_user_ids=[hr.id])
|
||||||
|
|
||||||
|
result = lean_training_reminder_service.run_lean_training_reminders(now=datetime(2026, 9, 30, 1, 0, 0))
|
||||||
|
|
||||||
|
# [ASSERT] 两期合并为一条汇总提醒:标题注明期数,内容列明各期周次区间,卡片跳转最近一期
|
||||||
|
assert result["sent"] == 1
|
||||||
|
assert len(sent) == 1
|
||||||
|
assert sent[0]["title"] == "精益管理培训逾期提醒(共2期未完成)"
|
||||||
|
assert "第1期(09-14至09-20)" in sent[0]["content"]
|
||||||
|
assert "第2期(09-21至09-27)" in sent[0]["content"]
|
||||||
|
assert sent[0]["jump_params"]["weekly_task_id"] == week2_task.id
|
||||||
|
|
||||||
|
# [ASSERT] 同天批次推送触发的延期提醒被"当天已催办"判定拦截,不再发送
|
||||||
|
pushed_overdue = lean_training_reminder_service.notify_overdue_users_after_push(
|
||||||
|
db.session.get(LeanTrainingWeeklyTask, week1_task.id),
|
||||||
|
current=datetime(2026, 9, 30, 3, 0, 0),
|
||||||
|
)
|
||||||
|
assert pushed_overdue["sent"] == 0
|
||||||
|
assert pushed_overdue["skipped"] == 1
|
||||||
|
|
||||||
|
# [ASSERT] 同天重复运行排程扫描同样静默(幂等,不产生第二条)
|
||||||
|
rerun = lean_training_reminder_service.run_lean_training_reminders(now=datetime(2026, 9, 30, 5, 0, 0))
|
||||||
|
assert rerun["sent"] == 0
|
||||||
|
assert len(sent) == 1
|
||||||
@@ -1,15 +1,17 @@
|
|||||||
"""
|
"""
|
||||||
tests/test_line_inventory_match_persistence.py
|
tests/test_line_inventory_match_persistence.py
|
||||||
|
|
||||||
用途:锁定 disposition → match_result 映射与 not_found/invalid_key 语义。
|
用途:锁定 disposition → match_result 映射、not_found/invalid_key 语义,
|
||||||
依赖:pytest、line_inventory_match_persistence。
|
及行级匹配事实落库契约(含料号兜底总量 part_available_qty)。
|
||||||
逻辑:纯单元;不写库。
|
依赖:pytest、line_inventory_match_persistence、app 夹具(persist 用例)。
|
||||||
|
逻辑:映射用例纯单元;persist 用例写库(内存测试库),不触外部集成。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from app.services.shipping_notice.line_inventory_match_persistence import (
|
from app.services.shipping_notice.line_inventory_match_persistence import (
|
||||||
map_disposition_to_match_codes,
|
map_disposition_to_match_codes,
|
||||||
|
persist_line_inventory_match_facts,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -54,3 +56,134 @@ def test_ok_and_shortage_are_matched_ready():
|
|||||||
assert map_disposition_to_match_codes(
|
assert map_disposition_to_match_codes(
|
||||||
disposition='shortage', part_number='A', reservation_id='B',
|
disposition='shortage', part_number='A', reservation_id='B',
|
||||||
) == ('matched', 'ready')
|
) == ('matched', 'ready')
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# persist_line_inventory_match_facts 落库契约(依赖 app 夹具,写内存测试库)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _make_snapshot_task(task_no: str):
|
||||||
|
"""
|
||||||
|
构造含两行冻结快照的 OT 任务,供 persist 落库测试复用。
|
||||||
|
|
||||||
|
核心逻辑:持久化按 order_snapshot_id → ShippingOrderSnapshot.lines 的 line_no
|
||||||
|
解析 snapshot_line_id;第 1 行料号/预约号齐全,第 2 行缺料号
|
||||||
|
(对齐匹配器「缺料号行不下发 part_available_qty 键」的真实产出,见
|
||||||
|
test_shipping_stp_phase4_line_inventory_match.py 的兜底总量用例)。
|
||||||
|
"""
|
||||||
|
from app import db
|
||||||
|
from app.models import ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask
|
||||||
|
|
||||||
|
task = ShippingOrderTask(task_no=task_no, source_type='direct_pdf', user_id=1)
|
||||||
|
db.session.add(task)
|
||||||
|
db.session.flush()
|
||||||
|
snapshot = ShippingOrderSnapshot(
|
||||||
|
task_id=task.id,
|
||||||
|
extraction_id=1,
|
||||||
|
schema_version_id=1,
|
||||||
|
order_data_version=1,
|
||||||
|
rule_versions_json={},
|
||||||
|
source_manifest_json={},
|
||||||
|
header_values_json={},
|
||||||
|
)
|
||||||
|
db.session.add(snapshot)
|
||||||
|
db.session.flush()
|
||||||
|
lines = [
|
||||||
|
{'line_no': 1, 'part_number': 'PN-1', 'reservation_id': '3000092917', 'qty': 8},
|
||||||
|
{'line_no': 2, 'part_number': None, 'reservation_id': '3000092918', 'qty': 1},
|
||||||
|
]
|
||||||
|
for position, line in enumerate(lines):
|
||||||
|
db.session.add(
|
||||||
|
ShippingOrderSnapshotLine(
|
||||||
|
snapshot_id=snapshot.id,
|
||||||
|
position=position,
|
||||||
|
line_no=line['line_no'],
|
||||||
|
part_number=line['part_number'],
|
||||||
|
reservation_id=line['reservation_id'],
|
||||||
|
qty=line['qty'],
|
||||||
|
field_values_json={},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
task.order_snapshot_id = snapshot.id
|
||||||
|
db.session.flush()
|
||||||
|
return task
|
||||||
|
|
||||||
|
|
||||||
|
def _not_found_result(*, part_available_qty, line_index: int = 0) -> dict:
|
||||||
|
"""
|
||||||
|
构造 not_found 行结果桩。
|
||||||
|
|
||||||
|
核心逻辑:part_available_qty 传 None 时**不下发该键**(而非显式 None),
|
||||||
|
对齐匹配器对 conflict/缺料号行「无键即无兜底」的契约;持久化必须按
|
||||||
|
无键 → NULL 处理。
|
||||||
|
"""
|
||||||
|
result = {
|
||||||
|
'line_index': line_index,
|
||||||
|
'disposition': 'not_found',
|
||||||
|
'part_number': 'PN-1',
|
||||||
|
'reservation_id': '3000092917',
|
||||||
|
'required_qty': 8.0,
|
||||||
|
'available_qty': 0.0,
|
||||||
|
}
|
||||||
|
if part_available_qty is not None:
|
||||||
|
result['part_available_qty'] = part_available_qty
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def test_persist_writes_part_available_qty_for_not_found_line(app):
|
||||||
|
"""预约不匹配行的料号兜底总量必须随匹配事实落库。"""
|
||||||
|
with app.app_context():
|
||||||
|
task = _make_snapshot_task('OT-PART-AVAILABLE-NEW')
|
||||||
|
match_payload = {
|
||||||
|
'line_results': [
|
||||||
|
_not_found_result(part_available_qty=8.0),
|
||||||
|
_not_found_result(part_available_qty=None, line_index=1),
|
||||||
|
],
|
||||||
|
'resolutions': [],
|
||||||
|
}
|
||||||
|
rows = persist_line_inventory_match_facts(
|
||||||
|
task=task,
|
||||||
|
match_payload=match_payload,
|
||||||
|
inventory_snapshot_id=None,
|
||||||
|
)
|
||||||
|
# 断言意图:兜底总量字符串化落列
|
||||||
|
assert str(rows[0].part_available_qty) == '8.0'
|
||||||
|
# 断言意图:无键/None 时必须落 NULL 而非 'None'
|
||||||
|
assert rows[1].part_available_qty is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_persist_updates_part_available_qty_on_existing_row(app):
|
||||||
|
"""同快照幂等更新时,料号兜底总量必须以最新匹配结果为准。"""
|
||||||
|
with app.app_context():
|
||||||
|
task = _make_snapshot_task('OT-PART-AVAILABLE-UPDATE')
|
||||||
|
persist_line_inventory_match_facts(
|
||||||
|
task=task,
|
||||||
|
match_payload={
|
||||||
|
'line_results': [_not_found_result(part_available_qty=8.0)],
|
||||||
|
'resolutions': [],
|
||||||
|
},
|
||||||
|
inventory_snapshot_id=None,
|
||||||
|
)
|
||||||
|
rows = persist_line_inventory_match_facts(
|
||||||
|
task=task,
|
||||||
|
match_payload={
|
||||||
|
'line_results': [_not_found_result(part_available_qty=13.0)],
|
||||||
|
'resolutions': [],
|
||||||
|
},
|
||||||
|
inventory_snapshot_id=None,
|
||||||
|
)
|
||||||
|
# 断言意图:更新分支同样把新兜底总量字符串化落列
|
||||||
|
assert str(rows[0].part_available_qty) == '13.0'
|
||||||
|
# 断言意图:更新时键缺失 → 回写 NULL,不得残留旧值或 'None'
|
||||||
|
rows = persist_line_inventory_match_facts(
|
||||||
|
task=task,
|
||||||
|
match_payload={
|
||||||
|
'line_results': [_not_found_result(part_available_qty=None)],
|
||||||
|
'resolutions': [],
|
||||||
|
},
|
||||||
|
inventory_snapshot_id=None,
|
||||||
|
)
|
||||||
|
assert rows[0].part_available_qty is None
|
||||||
|
# 断言意图:同快照幂等更新,始终只有一条 current 事实
|
||||||
|
assert len(rows) == 1
|
||||||
@@ -10,6 +10,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||||
ACTION_CLOSE,
|
ACTION_CLOSE,
|
||||||
|
ACTION_RELEASE_SHORTAGE,
|
||||||
ACTION_RETRY_MATCHING,
|
ACTION_RETRY_MATCHING,
|
||||||
ACTION_RETRY_PREPARATION,
|
ACTION_RETRY_PREPARATION,
|
||||||
normalize_match_quantities,
|
normalize_match_quantities,
|
||||||
@@ -116,7 +117,9 @@ def test_shortage_actions_preparation_and_close_only():
|
|||||||
user_line_status='shortage',
|
user_line_status='shortage',
|
||||||
)
|
)
|
||||||
assert inv == [ACTION_RETRY_PREPARATION]
|
assert inv == [ACTION_RETRY_PREPARATION]
|
||||||
assert line == [ACTION_CLOSE]
|
# 断言意图(既有用例修复):对齐已上线契约(eed1068ae)——短缺行除关闭外
|
||||||
|
# 同时下发 release_inventory_shortage(填写原因放行),本用例原断言已过期。
|
||||||
|
assert line == [ACTION_CLOSE, ACTION_RELEASE_SHORTAGE]
|
||||||
|
|
||||||
|
|
||||||
def test_wave_created_hides_line_actions():
|
def test_wave_created_hides_line_actions():
|
||||||
@@ -204,3 +207,28 @@ def test_user_status_maps_closed_and_system_ready():
|
|||||||
stored_line_status='ready_to_fulfill',
|
stored_line_status='ready_to_fulfill',
|
||||||
decision_source='system',
|
decision_source='system',
|
||||||
) == 'auto_fulfilling'
|
) == 'auto_fulfilling'
|
||||||
|
|
||||||
|
|
||||||
|
def test_view_exposes_part_available_qty_gated_by_ready():
|
||||||
|
"""料号兜底总量必须随投影透出,且非 ready 一律 None(与 available_qty 同门控)。"""
|
||||||
|
base = {
|
||||||
|
'match_result': 'not_found', 'inventory_status': 'ready',
|
||||||
|
'required_qty': '8', 'available_qty': None,
|
||||||
|
'inventory_snapshot_id': 1, 'matched_at': None,
|
||||||
|
'inventory_source_code': 'DSV', 'detail_json': {},
|
||||||
|
}
|
||||||
|
view = project_line_inventory_view(
|
||||||
|
has_formal_ot=True, fact={**base, 'part_available_qty': '9'},
|
||||||
|
required_qty='8', stored_line_status=None, decision_source=None,
|
||||||
|
can_fulfill_complete_line=False,
|
||||||
|
)
|
||||||
|
# 断言意图:not_found 行 available 规范为 0,兜底量原样透出(前端新列数据源)。
|
||||||
|
assert view['available_qty'] == '0'
|
||||||
|
assert view['part_available_qty'] == '9'
|
||||||
|
pending = project_line_inventory_view(
|
||||||
|
has_formal_ot=True, fact={**base, 'inventory_status': 'preparing', 'part_available_qty': '9'},
|
||||||
|
required_qty='8', stored_line_status=None, decision_source=None,
|
||||||
|
can_fulfill_complete_line=False,
|
||||||
|
)
|
||||||
|
# 断言意图:非 ready 一律 pending,兜底量同样不下发,避免半就绪状态误导。
|
||||||
|
assert pending['part_available_qty'] is None
|
||||||
@@ -203,7 +203,7 @@ def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path
|
|||||||
|
|
||||||
|
|
||||||
def test_assert_receipt_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch):
|
def test_assert_receipt_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch):
|
||||||
"""收料 fail-fast 应附带 reasons,且不要求共享哨兵。"""
|
"""收料 fail-fast 应附带 reasons,且与库存同口径要求共享哨兵。"""
|
||||||
from app.core.errors import ServiceUnavailableError
|
from app.core.errors import ServiceUnavailableError
|
||||||
from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module
|
from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module
|
||||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||||
@@ -225,11 +225,12 @@ def test_assert_receipt_rpa_worker_ready_includes_reason_details(app, tmp_path,
|
|||||||
with app.app_context():
|
with app.app_context():
|
||||||
with pytest.raises(ServiceUnavailableError) as exc_info:
|
with pytest.raises(ServiceUnavailableError) as exc_info:
|
||||||
assert_receipt_rpa_worker_ready()
|
assert_receipt_rpa_worker_ready()
|
||||||
# [断言意图] 与库存同构的用户可见文案与 reasons;收料不因缺哨兵失败。
|
# [断言意图] 与库存同构的用户可见文案与 reasons;缺哨兵与无心跳同时暴露,
|
||||||
|
# 对应部署侧必须由 ps1 注入 FREIGHT_RPA_SHARED_SCOPE_ID 写哨兵。
|
||||||
assert exc_info.value.message == RPA_WORKER_OFFLINE_MESSAGE
|
assert exc_info.value.message == RPA_WORKER_OFFLINE_MESSAGE
|
||||||
reasons = (exc_info.value.details or {}).get('reasons', [])
|
reasons = (exc_info.value.details or {}).get('reasons', [])
|
||||||
assert 'no_worker_heartbeat' in reasons
|
assert 'no_worker_heartbeat' in reasons
|
||||||
assert 'shared_sentinel_missing' not in reasons
|
assert 'shared_sentinel_missing' in reasons
|
||||||
|
|
||||||
|
|
||||||
def test_check_inventory_rpa_worker_ready_rejects_stale_heartbeat(app, tmp_path, monkeypatch):
|
def test_check_inventory_rpa_worker_ready_rejects_stale_heartbeat(app, tmp_path, monkeypatch):
|
||||||
|
|||||||
@@ -891,6 +891,31 @@ def test_stage_context_keeps_frozen_order_lines_when_inventory_match_is_not_read
|
|||||||
assert preparation["has_match_result"] is False
|
assert preparation["has_match_result"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_preparation_lines_carry_part_available_qty(app) -> None:
|
||||||
|
"""prep 行必须下发料号兜底总量,供前端新增「可用数量」列。"""
|
||||||
|
with app.app_context():
|
||||||
|
task, line = _frozen_task_with_line(
|
||||||
|
task_no="OT-UI-PART-AVAILABLE",
|
||||||
|
reservation_id="RSV-PART-AVAIL",
|
||||||
|
part_number="PN-PART-AVAIL",
|
||||||
|
qty="8",
|
||||||
|
)
|
||||||
|
# 行 Match 事实:required '8'、part_available_qty='9'(允许源内、忽略预约号与单位的料号总可用量)。
|
||||||
|
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||||
|
task_id=task.id, snapshot_line_id=line.id, line_no=1, line_index=0,
|
||||||
|
match_result="matched", inventory_status="ready", required_qty="8",
|
||||||
|
available_qty="9", matched_qty="9", shortage_qty="0", part_available_qty="9",
|
||||||
|
reservation_id="RSV-PART-AVAIL", part_number="PN-PART-AVAIL",
|
||||||
|
inventory_source_code="DBS_DUB", is_current=True,
|
||||||
|
))
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
state = build_task_ui_state(task, include_stage_context=True)
|
||||||
|
prep_line = state["stage_context"]["preparation"]["lines"][0]
|
||||||
|
# 断言意图:ui_state 单源直透投影值,前端不做二次推导;不下发任何派生布尔标志。
|
||||||
|
assert prep_line["part_available_qty"] == "9"
|
||||||
|
|
||||||
|
|
||||||
def test_resolve_task_inventory_download_requires_current_task_link(app, tmp_path) -> None:
|
def test_resolve_task_inventory_download_requires_current_task_link(app, tmp_path) -> None:
|
||||||
"""库存文件下载只能读取当前任务 active link 指向的托管文件,禁止按库存源或订单猜测文件。"""
|
"""库存文件下载只能读取当前任务 active link 指向的托管文件,禁止按库存源或订单猜测文件。"""
|
||||||
from app.models import ShippingInventoryFile, ShippingTaskInventoryLink
|
from app.models import ShippingInventoryFile, ShippingTaskInventoryLink
|
||||||
|
|||||||
@@ -459,6 +459,56 @@ def test_refresh_pointers_keeps_invalidated_when_downstream_still_passed(gate_ex
|
|||||||
assert gate_execution.status == 'blocked'
|
assert gate_execution.status == 'blocked'
|
||||||
|
|
||||||
|
|
||||||
|
def test_refresh_pointers_bumps_task_progress_version_without_notice(gate_execution):
|
||||||
|
"""无 Notice 绑定时 Gate 指针事实变化必须递增 OT progress_version。
|
||||||
|
|
||||||
|
复现:通知准备/库存匹配阶段 Notice 尚未生成,历史实现只回填 stage、不推进版本;
|
||||||
|
统一投影 progress_version 冻结导致工作台 [REFRESH_ON_CHANGE] 永不重拉任务详情,
|
||||||
|
RPA 重取成功后行级可用数量/缺口停留在旧快照(界面显示「库存文件未准备」)。
|
||||||
|
"""
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from app.services.shipping_notice import process_gate_service
|
||||||
|
|
||||||
|
task = db.session.get(ShippingOrderTask, int(gate_execution.task_id))
|
||||||
|
version_before = int(task.progress_version or 1)
|
||||||
|
|
||||||
|
now = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
|
for gate in ShippingProcessGate.query.filter_by(execution_id=int(gate_execution.id)).all():
|
||||||
|
if gate.gate_code in {
|
||||||
|
'document_materialization', 'layout_parsing', 'document_profile_routing',
|
||||||
|
'order_field_extraction', 'field_completeness', 'reservation_validation',
|
||||||
|
'customer_resolution', 'duplicate_detection', 'field_conflict_resolution',
|
||||||
|
'task_creation', 'order_freeze_readiness', 'inventory_source_routing',
|
||||||
|
'inventory_preparation', 'inventory_field_mapping', 'inventory_matching',
|
||||||
|
}:
|
||||||
|
gate.status = 'passed'
|
||||||
|
gate.passed_at = now
|
||||||
|
elif gate.gate_code == 'inventory_sufficiency':
|
||||||
|
gate.status = 'blocked_manual'
|
||||||
|
gate.blocking_reason_code = 'inventory_shortage_review_required'
|
||||||
|
gate.next_action_code = 'open_shortage_review'
|
||||||
|
elif gate.gate_code == 'excel_readiness':
|
||||||
|
gate.status = 'blocked_manual'
|
||||||
|
gate.blocking_reason_code = 'excel_not_ready'
|
||||||
|
# 其余保持 pending
|
||||||
|
db.session.flush()
|
||||||
|
|
||||||
|
process_gate_service._refresh_execution_pointers(gate_execution)
|
||||||
|
db.session.flush()
|
||||||
|
|
||||||
|
# 关键断言:缺口落定属于真实事实变化,无 Notice 也必须经中央写入口推进版本。
|
||||||
|
assert gate_execution.current_gate_code == 'inventory_sufficiency'
|
||||||
|
assert gate_execution.status == 'blocked'
|
||||||
|
assert int(task.progress_version or 1) == version_before + 1
|
||||||
|
|
||||||
|
process_gate_service._refresh_execution_pointers(gate_execution)
|
||||||
|
db.session.flush()
|
||||||
|
|
||||||
|
# 关键断言:事实未变的重复刷新不得递增版本,避免轮询期被放大成详情刷新风暴。
|
||||||
|
assert int(task.progress_version or 1) == version_before + 1
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -519,6 +519,29 @@ def test_waiting_human_without_reconcile_action_has_no_false_primary_action():
|
|||||||
assert payload['primary_action'] is None
|
assert payload['primary_action'] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_in_flight_gate_projects_running_not_waiting_human():
|
||||||
|
"""RPA 在途(Gate waiting_external)必须投影 running,不得误报待人工。
|
||||||
|
|
||||||
|
Notice 生成前 OT.status 停留在建单前的 waiting_review;若在途期被投影成
|
||||||
|
waiting_human,前端会把任务当终态停止投影轮询,RPA 回调完成将永远无法被
|
||||||
|
感知(库存匹配表格冻结在「库存文件未准备」)。与门禁契约
|
||||||
|
GATE_STATUS_TO_USER_STATUS['waiting_external']=='running' 对齐。
|
||||||
|
"""
|
||||||
|
payload = apply_user_projection_fields({
|
||||||
|
'status': 'waiting_review',
|
||||||
|
'stage': 'inventory_preparation',
|
||||||
|
'source_type': 'order_task',
|
||||||
|
'current_gate': {
|
||||||
|
'gate_code': 'inventory_preparation',
|
||||||
|
'status': 'waiting_external',
|
||||||
|
},
|
||||||
|
'available_actions': [],
|
||||||
|
})
|
||||||
|
|
||||||
|
# 关键断言:Gate 在途 = 系统处理中;待人工只属于 blocked_manual 等人工阻断。
|
||||||
|
assert payload['user_status'] == 'running'
|
||||||
|
|
||||||
|
|
||||||
def test_apply_user_projection_fields_fail_closes_inconsistent_projection():
|
def test_apply_user_projection_fields_fail_closes_inconsistent_projection():
|
||||||
"""事实读取异常即使发生在用户态计算后,也必须清空动作并进入诊断态。"""
|
"""事实读取异常即使发生在用户态计算后,也必须清空动作并进入诊断态。"""
|
||||||
payload = apply_user_projection_fields({
|
payload = apply_user_projection_fields({
|
||||||
|
|||||||
@@ -4,7 +4,9 @@ tests/test_shipping_review_line_fulfillment_decision.py
|
|||||||
用途:行级履约决定的库存安全、reopen 约束与审计参数契约测试。
|
用途:行级履约决定的库存安全、reopen 约束与审计参数契约测试。
|
||||||
依赖:pytest、order_review_fulfillment_decision_service。
|
依赖:pytest、order_review_fulfillment_decision_service。
|
||||||
逻辑:覆盖库存不足禁止先行、task_created 禁止 reopen、管理员重开边界、
|
逻辑:覆盖库存不足禁止先行、task_created 禁止 reopen、管理员重开边界、
|
||||||
数量解析与评估助手;不依赖完整建单 Fixture。
|
数量解析与评估助手;以及缺口放行证据字段按「预约号+料号」筛快照、
|
||||||
|
预约键 0 行命中时按料号键兜底重筛(evidence_scope=part_fallback)与
|
||||||
|
放行全量字段值落库契约;不依赖完整建单 Fixture。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -28,6 +30,7 @@ from app.services.shipping_notice.order_review_fulfillment_decision_service impo
|
|||||||
_release_template_system_fields,
|
_release_template_system_fields,
|
||||||
_release_fact_identity,
|
_release_fact_identity,
|
||||||
_resolve_shortage_release_inventory_source,
|
_resolve_shortage_release_inventory_source,
|
||||||
|
_shortage_release_required_fields,
|
||||||
_sync_confirmed_task_fulfillment_gates,
|
_sync_confirmed_task_fulfillment_gates,
|
||||||
_is_shortage_match_fact,
|
_is_shortage_match_fact,
|
||||||
_has_terminal_inventory_rpa_failure,
|
_has_terminal_inventory_rpa_failure,
|
||||||
@@ -616,3 +619,610 @@ def test_project_empty_case_without_draft(app):
|
|||||||
result = project_review_case_line_decisions(case)
|
result = project_review_case_line_decisions(case)
|
||||||
assert result['lines'] == []
|
assert result['lines'] == []
|
||||||
assert result['has_open_lines'] is False
|
assert result['has_open_lines'] is False
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# [Task 6] 缺口料号兜底:放行证据字段按「预约号+料号」筛库存快照;预约键 0 行命中
|
||||||
|
# 时按料号键重筛带出(evidence_scope=part_fallback,审计可见),并落全量模板字段值。
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _seed_part_fallback_release_fixture(
|
||||||
|
app,
|
||||||
|
*,
|
||||||
|
inventory_rows: list[dict[str, str]] | None = None,
|
||||||
|
order_reservation_id: str = 'R-ORDER',
|
||||||
|
order_part_number: str = 'ODM-001',
|
||||||
|
required_qty: str = '10',
|
||||||
|
part_available_qty: str | None = None,
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
构造放行字段判定夹具:「预约号+料号」匹配方案 + 行级库存快照 + 模板消费 ODM 字段。
|
||||||
|
|
||||||
|
核心逻辑:复用 conftest 种子源 DSV360_AWSDU(profile.match_keys=part_number +
|
||||||
|
reservation_id,订单键 test-order-part-number / test-order-reservation-id),
|
||||||
|
订单行预约号默认 'R-ORDER';库存快照行预约号默认 'R-INV'(≠订单)以制造
|
||||||
|
预约键 0 行命中、料号键可命中的兜底场景。同时落一条真实行匹配事实
|
||||||
|
(not_found 且指向本快照),供 decide 放行分支走真实模型查询。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
inventory_rows: 库存快照行(语义键 part / reservation / odm);
|
||||||
|
None 时默认单行且 odm 值唯一('ODM-VAL')。
|
||||||
|
required_qty: 行需求量(默认 '10' 保持 Task 6 口径)。
|
||||||
|
part_available_qty: 匹配器下发的料号兜底总量;None 时不落列
|
||||||
|
(自动放行服务视为不可判定并跳过,Task 7 使用)。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(task, inventory_file, odm_field)。
|
||||||
|
"""
|
||||||
|
from app import db
|
||||||
|
from app.models import (
|
||||||
|
ShippingExcelTemplate,
|
||||||
|
ShippingInventoryField,
|
||||||
|
ShippingInventoryFile,
|
||||||
|
ShippingInventorySource,
|
||||||
|
ShippingNoticeLineInventoryMatch,
|
||||||
|
ShippingOrderSchema,
|
||||||
|
ShippingOrderSchemaVersion,
|
||||||
|
ShippingOrderSnapshot,
|
||||||
|
ShippingOrderSnapshotLine,
|
||||||
|
ShippingOrderTask,
|
||||||
|
User,
|
||||||
|
)
|
||||||
|
|
||||||
|
part_field = ShippingInventoryField.query.filter_by(field_code='part_number').one()
|
||||||
|
reservation_field = ShippingInventoryField.query.filter_by(field_code='reservation_id').one()
|
||||||
|
odm_field = ShippingInventoryField.query.filter_by(field_code='odm_id').one()
|
||||||
|
|
||||||
|
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||||
|
template = db.session.get(ShippingExcelTemplate, int(source.excel_template_id))
|
||||||
|
assert template is not None
|
||||||
|
# 发货模板只消费 ODM 字段:该字段在快照行上的唯一值即放行自动带出的证据值。
|
||||||
|
template.definition_json = {
|
||||||
|
'mappings': [
|
||||||
|
{'row_mode': 'line', 'source_kind': 'inventory_field', 'source_key': str(odm_field.id)},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
user = User(username='part-fallback', email='part-fallback@example.com')
|
||||||
|
db.session.add(user)
|
||||||
|
db.session.flush()
|
||||||
|
schema = ShippingOrderSchema(schema_code='PART_FALLBACK', display_name='Part Fallback')
|
||||||
|
db.session.add(schema)
|
||||||
|
db.session.flush()
|
||||||
|
schema_version = ShippingOrderSchemaVersion(
|
||||||
|
schema_id=schema.id,
|
||||||
|
version=1,
|
||||||
|
status='published',
|
||||||
|
definition_json={'fields': []},
|
||||||
|
)
|
||||||
|
db.session.add(schema_version)
|
||||||
|
db.session.flush()
|
||||||
|
|
||||||
|
task = ShippingOrderTask(
|
||||||
|
task_no='OT-PART-FALLBACK',
|
||||||
|
user_id=user.id,
|
||||||
|
stage='inventory_matching',
|
||||||
|
)
|
||||||
|
db.session.add(task)
|
||||||
|
db.session.flush()
|
||||||
|
snapshot = ShippingOrderSnapshot(
|
||||||
|
task_id=task.id,
|
||||||
|
extraction_id=1,
|
||||||
|
schema_version_id=schema_version.id,
|
||||||
|
order_data_version=1,
|
||||||
|
header_values_json={},
|
||||||
|
)
|
||||||
|
db.session.add(snapshot)
|
||||||
|
db.session.flush()
|
||||||
|
task.order_snapshot_id = snapshot.id
|
||||||
|
# 订单行 match-key 值必须写入 field_values_json(键 = match_keys.order_field_id)。
|
||||||
|
snapshot_line = ShippingOrderSnapshotLine(
|
||||||
|
snapshot_id=snapshot.id,
|
||||||
|
position=0,
|
||||||
|
line_no=1,
|
||||||
|
reservation_id=order_reservation_id,
|
||||||
|
part_number=order_part_number,
|
||||||
|
qty=required_qty,
|
||||||
|
field_values_json={
|
||||||
|
'test-order-part-number': order_part_number,
|
||||||
|
'test-order-reservation-id': order_reservation_id,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
db.session.add(snapshot_line)
|
||||||
|
db.session.flush()
|
||||||
|
|
||||||
|
rows = [
|
||||||
|
{
|
||||||
|
str(part_field.id): str(row.get('part') or ''),
|
||||||
|
str(reservation_field.id): str(row.get('reservation') or ''),
|
||||||
|
str(odm_field.id): str(row.get('odm') or ''),
|
||||||
|
}
|
||||||
|
for row in (inventory_rows if inventory_rows is not None else [
|
||||||
|
{'part': order_part_number, 'reservation': 'R-INV', 'odm': 'ODM-VAL'},
|
||||||
|
])
|
||||||
|
]
|
||||||
|
inventory_file = ShippingInventoryFile(
|
||||||
|
inventory_file_no='SIF-PART-FALLBACK',
|
||||||
|
storage_path='test/part-fallback.xlsx',
|
||||||
|
source_file_name='part-fallback.xlsx',
|
||||||
|
source_code='DSV360_AWSDU',
|
||||||
|
snapshot_status='ready',
|
||||||
|
inventory_lines_json=rows,
|
||||||
|
line_count=len(rows),
|
||||||
|
)
|
||||||
|
db.session.add(inventory_file)
|
||||||
|
db.session.flush()
|
||||||
|
|
||||||
|
# 放行资格走真实模型查询:行匹配事实 = not_found(库存不足),指向本快照与本库存源。
|
||||||
|
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||||
|
task_id=task.id,
|
||||||
|
snapshot_line_id=snapshot_line.id,
|
||||||
|
line_no=1,
|
||||||
|
line_index=0,
|
||||||
|
match_result='not_found',
|
||||||
|
inventory_status='ready',
|
||||||
|
required_qty=required_qty,
|
||||||
|
available_qty='0',
|
||||||
|
matched_qty='0',
|
||||||
|
shortage_qty=required_qty,
|
||||||
|
part_available_qty=part_available_qty,
|
||||||
|
reservation_id=order_reservation_id,
|
||||||
|
part_number=order_part_number,
|
||||||
|
inventory_source_code='DSV360_AWSDU',
|
||||||
|
inventory_snapshot_id=inventory_file.id,
|
||||||
|
is_current=True,
|
||||||
|
))
|
||||||
|
db.session.commit()
|
||||||
|
return task, inventory_file, odm_field
|
||||||
|
|
||||||
|
|
||||||
|
def _decide_release_with_captured_snapshot(app, monkeypatch, *, task):
|
||||||
|
"""
|
||||||
|
经 decide_review_line_fulfillment 公开路径提交放行(预约不匹配场景),捕获落库快照。
|
||||||
|
|
||||||
|
核心逻辑:Case/草稿/决定行为进程内替身;放行分支真实执行(真实行匹配事实 +
|
||||||
|
真实 _shortage_release_required_fields + 真实校验),Gate 重算、审计写库与
|
||||||
|
resume/投影替身化,隔离外部副作用。提交 release_field_values={},
|
||||||
|
用于证明自动带出值无须人工输入即可落库。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
captured:决定行构造 kwargs(含 snapshot_json 全量内容)。
|
||||||
|
"""
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
from app.services.shipping_notice import order_review_fulfillment_decision_service as svc
|
||||||
|
|
||||||
|
draft = SimpleNamespace(
|
||||||
|
draft_version=1,
|
||||||
|
lines_json=[{
|
||||||
|
'draft_line_id': 'L1',
|
||||||
|
'qty': '10',
|
||||||
|
'reservation_id': 'R-ORDER',
|
||||||
|
'part_number': 'ODM-001',
|
||||||
|
}],
|
||||||
|
validation_result_json={'line_projections': [{'draft_line_id': 'L1', 'available_qty': '0'}]},
|
||||||
|
)
|
||||||
|
case = SimpleNamespace(
|
||||||
|
id=1,
|
||||||
|
case_no='CASE-PART-FALLBACK',
|
||||||
|
status='ready',
|
||||||
|
current_draft=draft,
|
||||||
|
run=SimpleNamespace(run_no='RUN-1'),
|
||||||
|
confirmed_task_id=int(task.id),
|
||||||
|
)
|
||||||
|
row = SimpleNamespace(
|
||||||
|
id=None,
|
||||||
|
draft_line_id='L1',
|
||||||
|
line_index=0,
|
||||||
|
decision_version=1,
|
||||||
|
decision_code=DECISION_RELEASE_SHORTAGE,
|
||||||
|
decision_source='user',
|
||||||
|
line_status='released_shortage',
|
||||||
|
is_active=True,
|
||||||
|
reason=None,
|
||||||
|
required_qty='10',
|
||||||
|
available_qty='0',
|
||||||
|
reservation_id='R-ORDER',
|
||||||
|
part_number='ODM-001',
|
||||||
|
task_id=None,
|
||||||
|
wave_no=None,
|
||||||
|
actor_user_id=1,
|
||||||
|
snapshot_json={},
|
||||||
|
created_at=None,
|
||||||
|
updated_at=None,
|
||||||
|
)
|
||||||
|
captured = {}
|
||||||
|
|
||||||
|
monkeypatch.setattr(svc, '_load_writable_case', lambda **kwargs: case)
|
||||||
|
monkeypatch.setattr(svc, '_active_decision', lambda *args, **kwargs: None)
|
||||||
|
monkeypatch.setattr(svc, '_next_version', lambda *args, **kwargs: 1)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
svc,
|
||||||
|
'ShippingOrderReviewLineDecision',
|
||||||
|
lambda **kwargs: (captured.update(kwargs), row)[1],
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(svc.db.session, 'add', lambda value: None)
|
||||||
|
monkeypatch.setattr(svc.db.session, 'flush', lambda: setattr(row, 'id', 42))
|
||||||
|
# [STEP] 放行后 Gate 同步会重算任务履约态;测试中替身化重算与审计/resume/投影副作用。
|
||||||
|
monkeypatch.setattr(
|
||||||
|
'app.services.shipping_notice.fulfillment_workflow.recompute_task_fulfillment_state',
|
||||||
|
lambda task: None,
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit',
|
||||||
|
lambda **kwargs: None,
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
'app.services.shipping_notice.order_review_resume_service.resume_after_review_change',
|
||||||
|
lambda **kwargs: {},
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
'app.services.shipping_notice.order_review_resume_service.attach_resume_outcome',
|
||||||
|
lambda payload, resume: payload,
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(svc, '_get_soft_loader', lambda: (lambda **kwargs: case))
|
||||||
|
monkeypatch.setattr(svc, 'project_review_case_line_decisions', lambda value: {})
|
||||||
|
monkeypatch.setattr(
|
||||||
|
'app.services.shipping_notice.order_review_projection.serialize_review_case',
|
||||||
|
lambda value: {},
|
||||||
|
)
|
||||||
|
|
||||||
|
result = svc.decide_review_line_fulfillment(
|
||||||
|
user_id=1,
|
||||||
|
case_no=case.case_no,
|
||||||
|
draft_line_id='L1',
|
||||||
|
decision_code=DECISION_RELEASE_SHORTAGE,
|
||||||
|
reason='库存缺口按料号兜底放行',
|
||||||
|
expected_draft_version=1,
|
||||||
|
release_field_values={},
|
||||||
|
)
|
||||||
|
# 断言意图:决定行已分配主键并完成落库流程(flush 替身回填)。
|
||||||
|
assert result['decision']['id'] == 42
|
||||||
|
return captured
|
||||||
|
|
||||||
|
|
||||||
|
def test_shortage_release_fields_fall_back_to_part_key_when_reservation_misses(app):
|
||||||
|
"""预约号在库存中不存在但料号存在时,补录字段必须按料号键带出快照值。"""
|
||||||
|
with app.app_context():
|
||||||
|
task, inventory_file, odm_field = _seed_part_fallback_release_fixture(app)
|
||||||
|
|
||||||
|
fields, scope = _shortage_release_required_fields(
|
||||||
|
task=task,
|
||||||
|
line_index=0,
|
||||||
|
inventory_snapshot_id=inventory_file.id,
|
||||||
|
inventory_source_code='DSV360_AWSDU',
|
||||||
|
)
|
||||||
|
|
||||||
|
# 断言意图:预约键筛空 → 料号键重筛命中 → 字段自动带值(不再 requires_manual),
|
||||||
|
# 且证据范围显式标记为 part_fallback(审计可见)。
|
||||||
|
assert scope == 'part_fallback'
|
||||||
|
assert fields == [{
|
||||||
|
'field_id': str(odm_field.id),
|
||||||
|
'display_name': 'ODM 编号',
|
||||||
|
'value': 'ODM-VAL',
|
||||||
|
'value_source': 'inventory_snapshot',
|
||||||
|
'requires_manual': False,
|
||||||
|
}]
|
||||||
|
|
||||||
|
|
||||||
|
def test_shortage_release_part_fallback_still_manual_when_values_ambiguous(app):
|
||||||
|
"""料号命中多行且字段值不一致时,该字段必须维持人工必填(fail-closed)。"""
|
||||||
|
with app.app_context():
|
||||||
|
task, inventory_file, odm_field = _seed_part_fallback_release_fixture(
|
||||||
|
app,
|
||||||
|
inventory_rows=[
|
||||||
|
{'part': 'ODM-001', 'reservation': 'R-INV-A', 'odm': 'ODM-V1'},
|
||||||
|
{'part': 'ODM-001', 'reservation': 'R-INV-B', 'odm': 'ODM-V2'},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
fields, scope = _shortage_release_required_fields(
|
||||||
|
task=task,
|
||||||
|
line_index=0,
|
||||||
|
inventory_snapshot_id=inventory_file.id,
|
||||||
|
inventory_source_code='DSV360_AWSDU',
|
||||||
|
)
|
||||||
|
|
||||||
|
# 断言意图:scope 仍标记 part_fallback(确按料号重筛),但分歧字段禁止任取值,
|
||||||
|
# 必须回退为人工必填、值为空。
|
||||||
|
assert scope == 'part_fallback'
|
||||||
|
assert fields == [{
|
||||||
|
'field_id': str(odm_field.id),
|
||||||
|
'display_name': 'ODM 编号',
|
||||||
|
'value': None,
|
||||||
|
'value_source': 'manual_required',
|
||||||
|
'requires_manual': True,
|
||||||
|
}]
|
||||||
|
|
||||||
|
|
||||||
|
def test_shortage_release_reservation_hit_keeps_inventory_snapshot_scope(app):
|
||||||
|
"""预约号+料号同时命中时不得误标兜底,证据范围必须保持 inventory_snapshot。"""
|
||||||
|
with app.app_context():
|
||||||
|
task, inventory_file, odm_field = _seed_part_fallback_release_fixture(
|
||||||
|
app,
|
||||||
|
inventory_rows=[
|
||||||
|
{'part': 'ODM-001', 'reservation': 'R-ORDER', 'odm': 'ODM-VAL'},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
fields, scope = _shortage_release_required_fields(
|
||||||
|
task=task,
|
||||||
|
line_index=0,
|
||||||
|
inventory_snapshot_id=inventory_file.id,
|
||||||
|
inventory_source_code='DSV360_AWSDU',
|
||||||
|
)
|
||||||
|
|
||||||
|
# 断言意图:预约命中场景 scope 恒为 inventory_snapshot,字段照常自动带值。
|
||||||
|
assert scope == 'inventory_snapshot'
|
||||||
|
assert fields == [{
|
||||||
|
'field_id': str(odm_field.id),
|
||||||
|
'display_name': 'ODM 编号',
|
||||||
|
'value': 'ODM-VAL',
|
||||||
|
'value_source': 'inventory_snapshot',
|
||||||
|
'requires_manual': False,
|
||||||
|
}]
|
||||||
|
|
||||||
|
|
||||||
|
def test_shortage_release_decision_records_part_fallback_scope(app, monkeypatch):
|
||||||
|
"""放行决定的审计快照必须记录证据来源范围(release_evidence_scope)。"""
|
||||||
|
with app.app_context():
|
||||||
|
task, inventory_file, odm_field = _seed_part_fallback_release_fixture(app)
|
||||||
|
captured = _decide_release_with_captured_snapshot(app, monkeypatch, task=task)
|
||||||
|
|
||||||
|
# 断言意图:审计可回答「放行证据来自预约匹配还是料号兜底」——scope 落在
|
||||||
|
# 决定审计快照 snapshot_json['release_evidence_scope'](导出/审计同源读取)。
|
||||||
|
assert captured['snapshot_json']['release_evidence_scope'] == 'part_fallback'
|
||||||
|
|
||||||
|
|
||||||
|
def test_shortage_release_persists_full_template_field_values(app, monkeypatch):
|
||||||
|
"""落库的 release_field_values 必须包含自动带出字段(导出覆盖的唯一来源)。"""
|
||||||
|
with app.app_context():
|
||||||
|
task, inventory_file, odm_field = _seed_part_fallback_release_fixture(app)
|
||||||
|
captured = _decide_release_with_captured_snapshot(app, monkeypatch, task=task)
|
||||||
|
|
||||||
|
# 断言意图:自动带出值必须落库——export.release_overrides_by_source_line 只读
|
||||||
|
# snapshot_json['release_field_values'],不落库导出 Excel 证据列将为空;
|
||||||
|
# 全部字段自动带出时人工必填清单为空、人工提交为空 dict 仍可放行。
|
||||||
|
assert captured['snapshot_json']['release_field_values'] == {str(odm_field.id): 'ODM-VAL'}
|
||||||
|
assert captured['snapshot_json']['release_required_fields'] == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_shortage_release_part_fallback_still_requires_manual_fill_on_decide(app, monkeypatch):
|
||||||
|
"""料号兜底分歧字段未人工补录时,公开 decide 路径仍必须 409(fail-closed 不回退)。"""
|
||||||
|
with app.app_context():
|
||||||
|
task, inventory_file, odm_field = _seed_part_fallback_release_fixture(
|
||||||
|
app,
|
||||||
|
inventory_rows=[
|
||||||
|
{'part': 'ODM-001', 'reservation': 'R-INV-A', 'odm': 'ODM-V1'},
|
||||||
|
{'part': 'ODM-001', 'reservation': 'R-INV-B', 'odm': 'ODM-V2'},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
with pytest.raises(ConflictError) as exc:
|
||||||
|
_decide_release_with_captured_snapshot(app, monkeypatch, task=task)
|
||||||
|
|
||||||
|
# 断言意图:兜底只解决「能唯一取值」的补录;分歧字段缺失人工补录仍按原契约拒绝。
|
||||||
|
assert exc.value.code == 'SHIPPING.REVIEW_LINE_RELEASE_FIELDS_REQUIRED'
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# [Task 7] 料号兜底自动放行:料号总量满足需求时,匹配完成后缺口行由系统自动放行
|
||||||
|
# (decision_source='system'、snapshot.auto_release=True、scope=part_fallback);
|
||||||
|
# 量不足 / 证据分歧 / 已有活动决定一律跳过并维持人工路径(fail-closed)。
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _seed_auto_release_fixture(
|
||||||
|
app,
|
||||||
|
*,
|
||||||
|
required_qty: str = '8',
|
||||||
|
part_available_qty: str = '9',
|
||||||
|
inventory_rows: list[dict[str, str]] | None = None,
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
构造自动放行端到端夹具:真实 OT/快照行/行事实(part_available_qty)/复核 Case+草稿。
|
||||||
|
|
||||||
|
核心逻辑:复用 Task 6 seed(预约号改用 10 位纯数字域契约值;订单预约号与库存行
|
||||||
|
预约号不同 → 预约键 0 行命中、料号键命中),再落一条真实 Review Case 与草稿
|
||||||
|
(与既有投影测试同构:run/unit/document 用悬挂占位 ID),使自动放行可走真实的
|
||||||
|
Case 反查、草稿行定位、决定落库与门禁满足性查询。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(task, case, odm_field)。
|
||||||
|
"""
|
||||||
|
from app import db
|
||||||
|
from app.models import ShippingOrderReviewCase, ShippingOrderReviewDraft, ShippingOrderSnapshot
|
||||||
|
|
||||||
|
task, _inventory_file, odm_field = _seed_part_fallback_release_fixture(
|
||||||
|
app,
|
||||||
|
inventory_rows=inventory_rows,
|
||||||
|
order_reservation_id='3000112934',
|
||||||
|
required_qty=required_qty,
|
||||||
|
part_available_qty=part_available_qty,
|
||||||
|
)
|
||||||
|
snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
|
||||||
|
case = ShippingOrderReviewCase(
|
||||||
|
case_no='CASE-AUTO-RELEASE', run_id=921, unit_id=922, document_id=923,
|
||||||
|
owner_user_id=int(task.user_id), status='confirmed', confirmed_task_id=task.id,
|
||||||
|
)
|
||||||
|
db.session.add(case)
|
||||||
|
db.session.flush()
|
||||||
|
db.session.add(ShippingOrderReviewDraft(
|
||||||
|
case_id=case.id, draft_version=1, schema_version_id=int(snapshot.schema_version_id),
|
||||||
|
header_values_json={},
|
||||||
|
lines_json=[{
|
||||||
|
'draft_line_id': 'line-1',
|
||||||
|
'qty': required_qty,
|
||||||
|
'reservation_id': '3000112934',
|
||||||
|
'part_number': 'ODM-001',
|
||||||
|
}],
|
||||||
|
validation_result_json={'line_projections': [
|
||||||
|
{'draft_line_id': 'line-1', 'available_qty': '0'},
|
||||||
|
]},
|
||||||
|
))
|
||||||
|
db.session.flush()
|
||||||
|
case.current_draft_id = case.drafts[0].id if case.drafts else None
|
||||||
|
db.session.flush()
|
||||||
|
db.session.commit()
|
||||||
|
return task, case, odm_field
|
||||||
|
|
||||||
|
|
||||||
|
def _patch_auto_release_side_effects(monkeypatch, *, stub_recompute: bool = True) -> list[dict]:
|
||||||
|
"""
|
||||||
|
替身化自动放行的编排副作用(与 Task 6 decide 测试同口径)。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stub_recompute: True 时替身化任务履约态重算;False 保留真实重算
|
||||||
|
(供门禁满足性测试走完整「放行→重算→sufficiency 放行」链路)。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
auto_fulfill_jobs:enqueue_post_ot_auto_fulfill_job 捕获列表。
|
||||||
|
"""
|
||||||
|
if stub_recompute:
|
||||||
|
monkeypatch.setattr(
|
||||||
|
'app.services.shipping_notice.fulfillment_workflow.recompute_task_fulfillment_state',
|
||||||
|
lambda task: None,
|
||||||
|
)
|
||||||
|
monkeypatch.setattr(
|
||||||
|
'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit',
|
||||||
|
lambda **kwargs: None,
|
||||||
|
)
|
||||||
|
auto_fulfill_jobs: list[dict] = []
|
||||||
|
monkeypatch.setattr(
|
||||||
|
'app.services.shipping_notice.line_auto_fulfill_coordinator.enqueue_post_ot_auto_fulfill_job',
|
||||||
|
lambda **kwargs: auto_fulfill_jobs.append(kwargs),
|
||||||
|
)
|
||||||
|
return auto_fulfill_jobs
|
||||||
|
|
||||||
|
|
||||||
|
def _active_auto_release_decisions(case):
|
||||||
|
"""读取该 Case 活动的 release_inventory_shortage 决定(真实模型查询)。"""
|
||||||
|
from app.models import ShippingOrderReviewLineDecision
|
||||||
|
|
||||||
|
return (
|
||||||
|
ShippingOrderReviewLineDecision.query
|
||||||
|
.filter_by(
|
||||||
|
review_case_id=int(case.id),
|
||||||
|
decision_code=DECISION_RELEASE_SHORTAGE,
|
||||||
|
is_active=True,
|
||||||
|
)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_auto_release_runs_after_match_when_part_total_satisfies(app, monkeypatch):
|
||||||
|
"""料号兜底量满足且证据全自动取值时,匹配完成后必须系统自动放行。"""
|
||||||
|
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||||
|
auto_release_part_fallback_shortages,
|
||||||
|
)
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
# 构造:订单行需求 8、预约不匹配(not_found)、同料号允许源内总量 9、
|
||||||
|
# 模板字段(ODM)可由料号命中的快照行唯一取值。
|
||||||
|
task, case, odm_field = _seed_auto_release_fixture(app)
|
||||||
|
_patch_auto_release_side_effects(monkeypatch)
|
||||||
|
|
||||||
|
released = auto_release_part_fallback_shortages(task)
|
||||||
|
|
||||||
|
# 断言意图:无需任何人工动作,缺口行已被系统放行且标记来源。
|
||||||
|
assert released == [0]
|
||||||
|
decisions = _active_auto_release_decisions(case)
|
||||||
|
assert len(decisions) == 1
|
||||||
|
decision = decisions[0]
|
||||||
|
assert decision.decision_source == 'system'
|
||||||
|
assert decision.snapshot_json['auto_release'] is True
|
||||||
|
assert decision.snapshot_json['release_evidence_scope'] == 'part_fallback'
|
||||||
|
# 自动带出值必须落库(导出覆盖唯一来源),与人工 decide 放行同契约。
|
||||||
|
assert decision.snapshot_json['release_field_values'] == {str(odm_field.id): 'ODM-VAL'}
|
||||||
|
assert decision.snapshot_json['release_required_fields'] == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_auto_release_skips_when_part_total_below_required(app, monkeypatch):
|
||||||
|
"""料号兜底量不足时不得自动放行,行保持人工待处置。"""
|
||||||
|
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||||
|
auto_release_part_fallback_shortages,
|
||||||
|
)
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
# 同上构造,但料号总量改为 3(< 8)。
|
||||||
|
task, case, _odm_field = _seed_auto_release_fixture(app, part_available_qty='3')
|
||||||
|
_patch_auto_release_side_effects(monkeypatch)
|
||||||
|
|
||||||
|
released = auto_release_part_fallback_shortages(task)
|
||||||
|
|
||||||
|
# 断言意图:不足行维持 shortage 等人工;聚合仍为 shortage。
|
||||||
|
assert released == []
|
||||||
|
assert _active_auto_release_decisions(case) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_auto_release_skips_when_evidence_field_ambiguous(app, monkeypatch):
|
||||||
|
"""证据字段无法唯一取值(requires_manual 残留)时不得自动放行。"""
|
||||||
|
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||||
|
auto_release_part_fallback_shortages,
|
||||||
|
)
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
# 同上构造,但两条同料号快照行在模板字段(ODM)上取值不同。
|
||||||
|
task, case, _odm_field = _seed_auto_release_fixture(
|
||||||
|
app,
|
||||||
|
inventory_rows=[
|
||||||
|
{'part': 'ODM-001', 'reservation': '3000420001', 'odm': 'ODM-V1'},
|
||||||
|
{'part': 'ODM-001', 'reservation': '3000420002', 'odm': 'ODM-V2'},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
_patch_auto_release_side_effects(monkeypatch)
|
||||||
|
|
||||||
|
released = auto_release_part_fallback_shortages(task)
|
||||||
|
|
||||||
|
# 断言意图:降级为人工放行(补录要求保留),不产生自动决定。
|
||||||
|
assert released == []
|
||||||
|
assert _active_auto_release_decisions(case) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_auto_release_does_not_duplicate_existing_decision(app, monkeypatch):
|
||||||
|
"""已有人工放行/结案决定(或已放行)的行不得重复自动放行。"""
|
||||||
|
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||||
|
auto_release_part_fallback_shortages,
|
||||||
|
)
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
task, case, _odm_field = _seed_auto_release_fixture(app)
|
||||||
|
_patch_auto_release_side_effects(monkeypatch)
|
||||||
|
|
||||||
|
first = auto_release_part_fallback_shortages(task)
|
||||||
|
second = auto_release_part_fallback_shortages(task)
|
||||||
|
|
||||||
|
# 断言意图:幂等——不新建第二个活动决定,原决定保持不变。
|
||||||
|
assert first == [0]
|
||||||
|
assert second == []
|
||||||
|
assert len(_active_auto_release_decisions(case)) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_auto_release_counted_in_sufficiency_and_gate_releases(app, monkeypatch):
|
||||||
|
"""自动放行后聚合满足、sufficiency 门禁放行(复用既有 released 语义)。"""
|
||||||
|
from app.services.shipping_notice.fulfillment_workflow import (
|
||||||
|
_recompute_task_match_aggregate,
|
||||||
|
match_completed,
|
||||||
|
)
|
||||||
|
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||||
|
auto_release_part_fallback_shortages,
|
||||||
|
)
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
task, _case, _odm_field = _seed_auto_release_fixture(app)
|
||||||
|
# 保留真实 recompute:完整走「放行落库 → 任务履约态重算 → 满足性门禁」链路。
|
||||||
|
_patch_auto_release_side_effects(monkeypatch, stub_recompute=False)
|
||||||
|
|
||||||
|
# 放行前:缺口行未放行 → 整单不满足。
|
||||||
|
assert match_completed(task) is False
|
||||||
|
|
||||||
|
released = auto_release_part_fallback_shortages(task)
|
||||||
|
|
||||||
|
# 断言意图:自动放行走同一聚合/门禁链路——match_completed 通过,
|
||||||
|
# inventory_sufficiency 不再因该行 blocked_manual。
|
||||||
|
assert released == [0]
|
||||||
|
assert match_completed(task) is True
|
||||||
|
status, shortages = _recompute_task_match_aggregate(task)
|
||||||
|
assert status == 'fulfillable'
|
||||||
|
assert shortages == []
|
||||||
|
line_results = task.step_payload_json['current_match_projection']['line_results']
|
||||||
|
assert line_results[0]['line_status'] == 'released'
|
||||||
@@ -236,3 +236,55 @@ def test_recompute_fulfillment_state_keeps_shortage_when_not_released(app, monke
|
|||||||
assert task.review_status == 'shortage_review'
|
assert task.review_status == 'shortage_review'
|
||||||
assert task.pending_human_reason == 'shortage'
|
assert task.pending_human_reason == 'shortage'
|
||||||
assert task.step_payload_json['current_match_projection']['line_results'][0]['line_status'] == 'shortage'
|
assert task.step_payload_json['current_match_projection']['line_results'][0]['line_status'] == 'shortage'
|
||||||
|
|
||||||
|
|
||||||
|
def test_system_auto_release_decision_counts_as_released(app):
|
||||||
|
"""系统自动放行(decision_source='system')的活动决定必须被满足性门禁按放行读取。
|
||||||
|
|
||||||
|
核心逻辑:料号兜底自动放行(Task 7)落库的 release_inventory_shortage 决定
|
||||||
|
decision_source='system';``_released_snapshot_line_ids_for_task`` 的真实查询
|
||||||
|
(不经测试 seam)必须同等识别,match_completed / 聚合重算才能把放行行计入满足。
|
||||||
|
"""
|
||||||
|
from app.models import ShippingOrderReviewCase, ShippingOrderReviewDraft, ShippingOrderReviewLineDecision
|
||||||
|
from app.services.shipping_notice.fulfillment_workflow import _recompute_task_match_aggregate
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
task = _task_with_current_matches(
|
||||||
|
task_no='SN-AUTO-RELEASE-GATE',
|
||||||
|
rows=[{'match_result': 'not_found', 'shortage_qty': '1'}],
|
||||||
|
)
|
||||||
|
# 放行前:缺口行未放行 → 整单不满足。
|
||||||
|
assert match_completed(task) is False
|
||||||
|
case = ShippingOrderReviewCase(
|
||||||
|
case_no='SNRC-AUTO-RELEASE-GATE', run_id=931, unit_id=932, document_id=933,
|
||||||
|
owner_user_id=task.user_id, status='confirmed', confirmed_task_id=task.id,
|
||||||
|
)
|
||||||
|
db.session.add(case)
|
||||||
|
db.session.flush()
|
||||||
|
db.session.add(ShippingOrderReviewDraft(
|
||||||
|
case_id=case.id, draft_version=1, schema_version_id=1,
|
||||||
|
header_values_json={},
|
||||||
|
lines_json=[{'draft_line_id': 'line-1', 'qty': '1', 'reservation_id': '3000112934'}],
|
||||||
|
))
|
||||||
|
db.session.flush()
|
||||||
|
case.current_draft_id = case.drafts[0].id if case.drafts else None
|
||||||
|
db.session.flush()
|
||||||
|
db.session.add(ShippingOrderReviewLineDecision(
|
||||||
|
review_case_id=int(case.id),
|
||||||
|
draft_line_id='line-1',
|
||||||
|
line_index=0,
|
||||||
|
decision_version=1,
|
||||||
|
decision_code='release_inventory_shortage',
|
||||||
|
decision_source='system',
|
||||||
|
line_status='released_shortage',
|
||||||
|
is_active=True,
|
||||||
|
snapshot_json={'auto_release': True, 'release_evidence_scope': 'part_fallback'},
|
||||||
|
))
|
||||||
|
db.session.flush()
|
||||||
|
|
||||||
|
# 系统自动放行决定落库后走真实放行查询(不打 seam 补丁)必须满足。
|
||||||
|
assert match_completed(task) is True
|
||||||
|
status, shortages = _recompute_task_match_aggregate(task)
|
||||||
|
assert status == 'fulfillable'
|
||||||
|
assert shortages == []
|
||||||
|
assert task.step_payload_json['current_match_projection']['line_results'][0]['line_status'] == 'released'
|
||||||
@@ -215,6 +215,92 @@ def test_allowed_system_facts_use_notice_line_no_not_export_sequence():
|
|||||||
assert 'export_sequence' not in ALLOWED_SYSTEM_FACTS
|
assert 'export_sequence' not in ALLOWED_SYSTEM_FACTS
|
||||||
|
|
||||||
|
|
||||||
|
def test_part_fallback_total_aggregates_across_reservations_within_allowed_source():
|
||||||
|
"""预约号不匹配但同料号在其它预约号下总量足够时,必须下发料号总可用量。"""
|
||||||
|
# Reservation 契约只接受 5/10 位纯数字(validated_reservation_id),
|
||||||
|
# 故用互不相同的数字预约号表达「订单预约号 vs 其它预约号」。
|
||||||
|
order_lines = [{'line_no': 1, 'part_number': 'P-1', 'reservation_id': '3000092917', 'quantity': 8}]
|
||||||
|
inventory_lines = [
|
||||||
|
{'reservation_id': '3000092920', 'part_number': 'P-1', 'qty': 0, '__source_code': 'DSV'},
|
||||||
|
{'reservation_id': '3000092918', 'part_number': 'P-1', 'qty': 5, '__source_code': 'DSV'},
|
||||||
|
{'reservation_id': '3000092919', 'part_number': 'P-1', 'qty': 3, '__source_code': 'DSV'},
|
||||||
|
]
|
||||||
|
payload = match_order_lines_across_candidates(
|
||||||
|
order_lines=order_lines,
|
||||||
|
inventory_lines=inventory_lines,
|
||||||
|
header_reservation_id=None,
|
||||||
|
)
|
||||||
|
result = payload['line_results'][0]
|
||||||
|
# 断言意图:订单预约号无库存桶 → not_found;料号兜底总量 0+5+3=8 必须随行结果下发。
|
||||||
|
assert result['disposition'] == 'not_found'
|
||||||
|
assert result['available_qty'] == 0.0
|
||||||
|
assert result['part_available_qty'] == 8.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_part_fallback_total_respects_allowed_source_and_ignores_unit():
|
||||||
|
"""料号兜底汇总受候选源范围约束,但不限定单位(用户确认口径 2026-10-09)。"""
|
||||||
|
order_lines = [{
|
||||||
|
'line_no': 1, 'part_number': 'P-1', 'reservation_id': '3000092917', 'quantity': 8,
|
||||||
|
'allowed_source_codes': ['DSV'], 'candidate_line_id': 1,
|
||||||
|
}]
|
||||||
|
inventory_lines = [
|
||||||
|
{'reservation_id': '3000092918', 'part_number': 'P-1', 'qty': 6, '__source_code': 'DSV'},
|
||||||
|
{'reservation_id': '3000092919', 'part_number': 'P-1', 'qty': 10, '__source_code': 'OTHER'},
|
||||||
|
{'reservation_id': '3000092920', 'part_number': 'P-1', 'qty': 99, '__source_code': 'DSV', 'uom': 'BOX'},
|
||||||
|
]
|
||||||
|
payload = match_order_lines_across_candidates(
|
||||||
|
order_lines=order_lines, inventory_lines=inventory_lines,
|
||||||
|
)
|
||||||
|
result = payload['line_results'][0]
|
||||||
|
# 断言意图:范围外源(OTHER)不得计入;异单位(BOX)行**必须计入**(不限单位),总量 6+99=105。
|
||||||
|
assert result['disposition'] == 'not_found'
|
||||||
|
assert result['part_available_qty'] == 105.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_part_fallback_total_absent_for_conflict_and_missing_part():
|
||||||
|
"""multi_file_conflict / 缺料号 / invalid(超出候选范围)行不下发料号总量,避免误导用户。"""
|
||||||
|
order_lines = [
|
||||||
|
{'line_no': 1, 'part_number': 'P-1', 'reservation_id': '3000092917', 'quantity': 1,
|
||||||
|
'allowed_source_codes': ['A', 'B'], 'candidate_line_id': 1},
|
||||||
|
{'line_no': 2, 'reservation_id': '3000092918', 'quantity': 1,
|
||||||
|
'allowed_source_codes': ['A'], 'candidate_line_id': 2},
|
||||||
|
{'line_no': 3, 'part_number': 'P-2', 'reservation_id': '1380000000', 'quantity': 1,
|
||||||
|
'allowed_source_codes': ['A'], 'candidate_line_id': 3},
|
||||||
|
]
|
||||||
|
inventory_lines = [
|
||||||
|
{'reservation_id': '3000092917', 'part_number': 'P-1', 'qty': 5, '__source_code': 'A'},
|
||||||
|
{'reservation_id': '3000092917', 'part_number': 'P-1', 'qty': 5, '__source_code': 'B'},
|
||||||
|
{'reservation_id': '1380000000', 'part_number': 'P-2', 'qty': 5, '__source_code': 'B'},
|
||||||
|
]
|
||||||
|
payload = match_order_lines_across_candidates(
|
||||||
|
order_lines=order_lines, inventory_lines=inventory_lines,
|
||||||
|
)
|
||||||
|
# 断言意图:冲突行与缺料号行均无 part_available_qty 键(持久化/投影按缺失→None)。
|
||||||
|
assert 'part_available_qty' not in payload['line_results'][0]
|
||||||
|
assert 'part_available_qty' not in payload['line_results'][1]
|
||||||
|
# 断言意图:命中仅存在于候选范围外源(invalid)的行同样不写键,不得误导放行判断。
|
||||||
|
assert payload['line_results'][2]['disposition'] == 'invalid'
|
||||||
|
assert 'part_available_qty' not in payload['line_results'][2]
|
||||||
|
|
||||||
|
|
||||||
|
def test_part_fallback_total_on_shortage_line_sums_other_reservations():
|
||||||
|
"""预约命中但不足(shortage)时,料号总量同样跨预约号合计下发。"""
|
||||||
|
order_lines = [{'line_no': 1, 'part_number': 'P-1', 'reservation_id': '3000092917', 'quantity': 8}]
|
||||||
|
inventory_lines = [
|
||||||
|
{'reservation_id': '3000092917', 'part_number': 'P-1', 'qty': 2, '__source_code': 'DSV'},
|
||||||
|
{'reservation_id': '3000092918', 'part_number': 'P-1', 'qty': 7, '__source_code': 'DSV'},
|
||||||
|
]
|
||||||
|
payload = match_order_lines_across_candidates(
|
||||||
|
order_lines=order_lines, inventory_lines=inventory_lines,
|
||||||
|
)
|
||||||
|
result = payload['line_results'][0]
|
||||||
|
# 断言意图:缺口判定不变(available=2/shortage=6);兜底总量=2+7=9。
|
||||||
|
assert result['disposition'] == 'shortage'
|
||||||
|
assert result['available_qty'] == 2.0
|
||||||
|
assert result['shortage_qty'] == 6.0
|
||||||
|
assert result['part_available_qty'] == 9.0
|
||||||
|
|
||||||
|
|
||||||
def test_permanent_audit_events_have_no_retention_expiry(app):
|
def test_permanent_audit_events_have_no_retention_expiry(app):
|
||||||
"""货代统一审计账本新写入事件永久保留(retention_expires_at 为空)。"""
|
"""货代统一审计账本新写入事件永久保留(retention_expires_at 为空)。"""
|
||||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||||
|
|||||||
@@ -291,10 +291,18 @@ def test_send_batch_splits_one_card_per_user(app, monkeypatch):
|
|||||||
|
|
||||||
wecom_ids = {item[0] for item in sent}
|
wecom_ids = {item[0] for item in sent}
|
||||||
assert wecom_ids == {"wx-po-recv", "wx-bl-recv"}
|
assert wecom_ids == {"wx-po-recv", "wx-bl-recv"}
|
||||||
po_body = next(item[2] for item in sent if item[0] == "wx-po-recv")
|
po_title, po_body = next((item[1], item[2]) for item in sent if item[0] == "wx-po-recv")
|
||||||
bl_body = next(item[2] for item in sent if item[0] == "wx-bl-recv")
|
bl_body = next(item[2] for item in sent if item[0] == "wx-bl-recv")
|
||||||
|
# 关键断言:卡片面向销售开票附件,不暴露业务方代号和批次号。
|
||||||
|
assert po_title == "销售开票附件缺件"
|
||||||
|
assert "2026年8月" in po_body
|
||||||
|
assert "缺 2 份,涉及 1 张发票" in po_body
|
||||||
|
assert "业务方" not in po_body
|
||||||
|
assert "sales" not in po_body
|
||||||
|
assert "RUN-VC-NOTIFY-SPLIT" not in po_body
|
||||||
assert "PO订单" in po_body
|
assert "PO订单" in po_body
|
||||||
assert "提单" not in po_body
|
# 关键断言:「张发票」是计量用语,类型是否出现要看「发票:缺」。
|
||||||
assert "发票" not in po_body
|
assert "提单:缺" not in po_body
|
||||||
|
assert "发票:缺" not in po_body
|
||||||
assert "提单" in bl_body
|
assert "提单" in bl_body
|
||||||
assert "PO订单" not in bl_body
|
assert "PO订单:缺" not in bl_body
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# 调试记录:访问不可用
|
||||||
|
|
||||||
|
- 状态:OPEN
|
||||||
|
- 会话:access-unavailable
|
||||||
|
- 日期:2026-09-09
|
||||||
|
|
||||||
|
## 症状
|
||||||
|
|
||||||
|
用户反馈“无法访问”,尚未明确是前端页面、后端接口、登录链路还是企微消息访问失败。
|
||||||
|
|
||||||
|
## 假设
|
||||||
|
|
||||||
|
1. 前端开发服务器未启动或端口 8881 不可达。
|
||||||
|
2. 后端 Flask 服务未启动或端口 5052 不可达。
|
||||||
|
3. 前端代理、环境地址或跨域配置指向了错误的后端地址。
|
||||||
|
4. 服务启动后因数据库或外部集成初始化异常退出。
|
||||||
|
5. 浏览器会话、认证或路由守卫导致访问被拒绝。
|
||||||
|
|
||||||
|
## 证据与下一步
|
||||||
|
|
||||||
|
待确认访问目标、访问地址、浏览器报错或网络响应后,再收集运行时证据。
|
||||||
Loaded 100 of 204 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user