Merge branch 'dev' into snow

# Conflicts:
#	backend/app/api/chat.py
#	backend/app/services/admin/permission_service.py
#	frontend/src/features/user/views/UserProfilePage.vue
This commit is contained in:
HTEWJ\26070045 committed 2026-09-23 14:34:20 +08:00
commit 5faf86b184
691 files changed
+55948 -17728

No files matched your search

+20 -16
View File
@@ -10,6 +10,8 @@ FLASK_ENV=development
# --- 2. 应用运行与进程 ---
TASK_EXECUTION_MODE=sync
# 集成连接器凭据密文的 Fernet 主密钥(凭据引用 db 模式落库用);仅由环境注入,轮换需同步重录凭据。
INTEGRATION_CREDENTIAL_KEY=d8MCilouDvf6ubi-EWM2kZpiYCpH4kU7BSfOtBI0194=
# Gunicorn配置
GUNICORN_WORKERS=10
@@ -135,27 +137,29 @@ SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_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_RPA_INVENTORY_TIMEOUT_SECONDS=900
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
# RPA 目录(相对 backend/ 根目录)
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
# RPA 目录(相对 backend/ 根目录,统一 freight_rpa/{inventory,receipt,common} 三层布局)
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=data/freight_rpa/inventory/drop
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory/triggers
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=data/freight_rpa/receipt/drop
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=data/freight_rpa/receipt/triggers
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=data/freight_rpa/inventory/upload_queue
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/freight_rpa/inventory/upload_triggers
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR=data/freight_rpa/common/browser_profile
# AWS 库存列映射(可选 JSON 字符串)
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
# 本地 RPA(scripts/rpa/freight_rpa_worker.py)
SHIPPING_NOTICE_RPA_WORKER_MOCK=false
# 本地 RPA(scripts/freight_rpa/inventory/inventory_rpa_worker.py)
FREIGHT_RPA_WORKER_MOCK=false
# 本机无 Redis 时允许进程内存记录心跳;有 Redis 时优先写 Redis
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK=true
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false
FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK=true
# 企微心跳告警总开关(默认关闭;需要时改为 true)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false
# SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3
# SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY=
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
# --- 10. 运维、告警与维护工具 ---
# 设备维保助手后端工具调用密钥
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
+24 -13
View File
@@ -10,6 +10,8 @@ FLASK_ENV=production
# --- 2. 应用运行与进程 ---
TASK_EXECUTION_MODE=rq
# 集成连接器凭据密文的 Fernet 主密钥(凭据引用 db 模式落库用);仅由环境注入,轮换需同步重录凭据。
INTEGRATION_CREDENTIAL_KEY=YJGD6nLfYUrbzhAlzBJ4xXvyoHw0dIOxDfRIA3xOXWA=
# Gunicorn配置
GUNICORN_WORKERS=20
@@ -70,7 +72,7 @@ GUNICORN_WORKERS=20
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
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
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
# --- 5. 数据库与基础设施 ---
@@ -107,6 +109,9 @@ WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
# SHIPPING_NOTICE_XFA_PROFILE_CHECKSUM_ALLOWLIST=
# SHIPPING_NOTICE_XFA_SCENARIO_ALLOWLIST=shipping_notice_order
# 自动推进(auto_progress)
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
# 进度细化灰度(阶段 5;生产默认开启,回滚时按需关闭,禁止删除审计事实)
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
@@ -134,21 +139,27 @@ SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=false
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=false
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=false
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
# RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。
# 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。
FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致)
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
# 企微心跳告警总开关(默认关闭;需要时改为 true)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
# 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/inventory_drop
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/inventory_triggers
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/upload_queue
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/upload_triggers
FREIGHT_RPA_WORKER_ALERT_USERNAMES=
FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
# RPA 目录(正式环境:Ubuntu 挂载 Windows RPA 正式共享,统一 freight_rpa/{inventory,receipt,common} 三层布局)
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/drop
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/triggers
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/drop
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/triggers
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_queue
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_triggers
# 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod
+25 -16
View File
@@ -150,7 +150,7 @@ WECOM_TRUSTED_DOMAIN=
WECOM_PUBLIC_BASE_URL=
WECOM_NOTIFY_ENABLED=true
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
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_FEEDBACK_NOTIFY_ENABLED=true
WECOM_FEEDBACK_NOTIFY_BASE_URL=http://ai.well-trust.com:8881
# 企业微信群机器人 webhook,按环境写入 .env.<env> 或部署平台变量;不要提交真实 URL。
@@ -187,6 +187,26 @@ CONTRACT_PAYMENT_ERP_USERNAME=hxjm
CONTRACT_PAYMENT_ERP_PASSWORD=hxjm
ERP_TIMEOUT_SECONDS=30
TEXT2SQL_SCHEMA_PATH=
# 立账凭证销货放行单:E10 OpenAPI + ecology10(与 E9 OA_SQLSERVER_DATABASE=ecology 隔离)
# 开关/超时三环境一致;基址、corpId、应用密钥、SQL 主机与账号由 .env.local / .env.<env> / Jenkins 注入
OA_E10_SQLSERVER_DATABASE=ecology10
OA_E10_SQLSERVER_PORT=1433
OA_E10_SQLSERVER_ENCRYPT=no
OA_E10_SQLSERVER_TRUST_CERT=yes
OA_E10_SQLSERVER_TIMEOUT=10
OA_E10_TIMEOUT_SECONDS=30
OA_E10_TOKEN_REFRESH_SKEW_SECONDS=300
OA_E10_OPENAPI_BASE_URL=http://192.168.100.184:10600/papi/openapi
OA_E10_CORPID=8c47e679b2e3a415b0381089af1a2e58
OA_E10_APP_KEY=7a9c97b6a3f5525f1150985b006f96b8
OA_E10_APP_SECRET=474922f5e071f972c46f357aa8a41eda
# 需要换成OA
OA_E10_USERID=1251671276931039236
OA_E10_SQLSERVER_HOST=192.168.100.186
OA_E10_SQLSERVER_USERNAME=AI_Knowledge_Base_OA
OA_E10_SQLSERVER_PASSWORD=hoo-thai@123_AI_OA
# 驱动可留空,留空会按本机已装驱动自动选:ODBC Driver 18 for SQL Server → 17 → SQL Server
OA_E10_SQLSERVER_DRIVER=
# --- 8. 知识库与文件处理 ---
# Knowledge base runtime
@@ -209,21 +229,13 @@ EDKB_WORD_FILE_TIMEOUT_SEC=420
# --- 9. 业务模块 ---
# 在途仓自动调拨 Agent(来源并发 / ERP 查询并发 / ERP 写并发恒 1 / 确认有效期 10 分钟 / 老化阈值)
# 在途仓自动调拨 Agent(来源并发 / 确认有效期 10 分钟 / 老化阈值);
# 外部系统端点与凭据由集成连接器客户端实例管理,不在环境变量中配置。
IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY=3
IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY=3
IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY=3
IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS=60
IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS=60
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS=600
IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS=3
IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS=5
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS=7
# ERP SOAP 地址与凭据仅由环境/Secret 注入(WSDL 冻结前留空 = fail-closed,禁止写入本文件)
# IN_TRANSIT_TRANSFER_ERP_ENDPOINT=
# IN_TRANSIT_TRANSFER_ERP_USERNAME=
# IN_TRANSIT_TRANSFER_ERP_PASSWORD=
IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG=
# 归档 bucket(MinIO;凭据复用 MINIO_*)
IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET=hxops-transfer
@@ -268,9 +280,6 @@ SHIPPING_PROCESS_GATE_TAKEOVER_SECONDS=120
SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES=3
SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS=30
SHIPPING_PROCESS_GATE_EXTERNAL_WAIT_TIMEOUT_SECONDS=1800
# RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。
# 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
# 订单解析主链灰度(默认关闭高风险路径;主链不依赖 Dify)。
# L7 验收完成前禁止开启通用解析与通用自动冻结。
# 通用确定性解析:仅 no_special_profile_feature / 无漂移 no_match 可进入。
@@ -300,9 +309,9 @@ SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
# 货代上传 RPA:默认关闭;具备 Worker/凭据/共享目录与隔离校验后再在环境文件显式设 true。
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
# Freight RPA defaults to real browser automation. Set to true only for local mock/debug runs.
SHIPPING_NOTICE_RPA_WORKER_MOCK=false
FREIGHT_RPA_WORKER_MOCK=false
# 企微心跳告警总开关(默认关闭;需要时在环境文件改为 true)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
# 固资履历共享盘
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
+25 -21
View File
@@ -10,6 +10,8 @@ FLASK_ENV=test
# --- 2. 应用运行与进程 ---
TASK_EXECUTION_MODE=rq
# 集成连接器凭据密文的 Fernet 主密钥(凭据引用 db 模式落库用);仅由环境注入,轮换需同步重录凭据。
INTEGRATION_CREDENTIAL_KEY=S6LTZXSdli532953J5G90rWxs35plKEph8ds6rh8AKQ=
# Gunicorn配置
GUNICORN_WORKERS=6
@@ -70,7 +72,7 @@ GUNICORN_WORKERS=6
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
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
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
HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
@@ -152,33 +154,35 @@ SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐)
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
# 企微心跳告警总开关(默认关闭;需要时改为 true)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
# 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微
# 两者皆无则告警只写日志、不会发企微
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
FREIGHT_RPA_WORKER_ALERT_USERNAMES=
FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
# 企微发送中短锁秒数(发送失败过期后可重试,默认 120)
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns=
# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享)
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers
FREIGHT_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns=
# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享,统一 freight_rpa/{inventory,receipt,common} 三层布局)
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/drop
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/drop
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/triggers
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_queue
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_triggers
# AWS 库存列映射(可选 JSON 字符串)
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
# 本地 Mock RPA(scripts/rpa/inventory/inventory_rpa_worker.py,可选)
# SHIPPING_NOTICE_RPA_WORKER_MOCK=true
# SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3
# SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY=
# 本地 Mock RPA(scripts/freight_rpa/inventory/inventory_rpa_worker.py,可选)
# FREIGHT_RPA_WORKER_MOCK=true
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
# 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
+2
View File
@@ -63,6 +63,7 @@ frontend/package-lock.json
*.swp
*.swo
.cursorrules
.zcode
# Runtime files
.run/
@@ -93,6 +94,7 @@ backend/data/kb/
.pytest_cache/
backend/data/fixed_assets/
docs/FixedAssets_*.xlsx
backend/data/freight_rpa/
backend/data/shipping_notice/
backend/data/logs/
backend/data/logs/*.log
+1 -1
View File
@@ -163,7 +163,7 @@ docker compose logs -f hxops-backend
- **文件内章节顺序**:① 环境与应用标识 → ② 应用运行与进程 → ③ 公共地址与网络入口 → ④ 安全、认证与身份源 → ⑤ 数据库与基础设施 → ⑥ AI 平台、模型与内部工具 → ⑦ 企业系统集成 → ⑧ 知识库与文件处理 → ⑨ 业务模块 → ⑩ 运维、告警与维护工具;文件没有某类变量时直接省略该章节。
- **章节内组织**:先按业务域及子域聚合(如 Casdoor、MinIO、WeCom、HR、PLM、SRM、FAQ、Shipping Notice、Fixed Asset),不得把同一域拆散后做全局字母排序;同一域内按“开关/模式 → 地址 → 标识 → 凭据 → 路径 → 业务参数 → 超时/重试/并发 → 兼容/Mock”排列,同级变量再按字母排序。
- **数据库连接固定顺序**:`HOST → PORT → DATABASE/SID → USERNAME → PASSWORD → DRIVER → ENCRYPT/TRUST_CERT → TIMEOUT`;完整连接串(如 `DATABASE_URL`、`*_DSN`)置于该数据源首位。
- **RPA 命名空间(强制)**:货代发货通知 RPA 统一使用 `SHIPPING_NOTICE_RPA_*`。后端业务参数使用 `SHIPPING_NOTICE_RPA_<配置项>`,后端与 Windows Worker 的共享目录/标识使用 `SHIPPING_NOTICE_RPA_SHARED_*`,Windows Worker 自身运行参数使用 `SHIPPING_NOTICE_RPA_WORKER_*`,平台凭据主密钥使用 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY`。禁止新增 `FREIGHT_RPA_*`、`SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`;历史名称只能存在于兼容映射和迁移说明中。
- **RPA 命名空间(强制,2026-09-18 修订)**:货代 RPA(库存/收料/上传及后续新增 Worker)统一使用 `FREIGHT_RPA_*`。后端业务参数使用 `FREIGHT_RPA_<配置项>`,后端与 Windows Worker 的共享目录/标识使用 `FREIGHT_RPA_SHARED_*`,Windows Worker 自身运行参数使用 `FREIGHT_RPA_WORKER_*`,平台凭据主密钥使用 `FREIGHT_RPA_CREDENTIAL_KEY`。禁止新增 `SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`。历史名称 `SHIPPING_NOTICE_RPA_*` 于 2026-09-18 未上线期一刀切废弃,**不设兼容层**;RPA 运行期数据统一存放于独立 `freight_rpa/` 根下,按 `inventory/`、`receipt/`、`common/` 分域(common 仅放跨 Worker 共享物,如 browser_profile)。
- **跨环境一致性**:`.env.dev`、`.env.test`、`.env.prod` 使用相同章节骨架;同名变量保持相同相对位置,便于审查差异;新增变量时同步检查所有适用环境文件和上述权威文档。
- **调整红线**:重排环境变量时只能移动“注释 + 完整赋值行”,禁止修改变量名或值,禁止删除变量、注释或示例;真实密码、密钥、Token、Webhook 与生产连接信息必须由系统环境变量、Jenkins/CI 或 Secret 管理机制注入。
+12 -1
View File
@@ -72,6 +72,13 @@ def create_app(config_name='default'):
register_blueprints(app)
# 能力声明是代码级契约:组合根在每次 create_app 时显式注册各域能力(幂等),
# 保证管理端「能力清单」冷启动即可见,且测试 reset 注册表后建新 app 也能恢复。
# 注意用 from-import:`import app.services...` 会把局部名 app 遮蔽成包模块。
from app.services.in_transit_transfer import capabilities as _transfer_capabilities
_transfer_capabilities.register_transfer_capabilities()
# Eagerly load persisted runtime settings so the very first request after
# a worker boot already sees the admin-saved configuration (otherwise the
# window between worker boot and the first ``before_request`` would still
@@ -103,12 +110,16 @@ def create_app(config_name='default'):
try:
from app.services.voucher_check.schedule_seed import (
ensure_default_voucher_check_schedule,
ensure_default_voucher_oa_sales_release_schedule,
ensure_default_voucher_po_print_schedule,
register_voucher_check_schedule_hooks,
)
register_voucher_check_schedule_hooks()
ensure_default_voucher_check_schedule()
ensure_default_voucher_po_print_schedule()
ensure_default_voucher_oa_sales_release_schedule()
except Exception as exc: # pragma: no cover - 表未就绪时容忍
logger.warning('Failed to ensure accounting-voucher-check schedule: %s', exc)
logger.warning('Failed to ensure accounting-voucher-check / po-print / oa-sales-release schedules: %s', exc)
try:
from app.services.contract_payment.schedule_seed import ensure_default_contract_payment_schedules
ensure_default_contract_payment_schedules()
@@ -428,6 +428,21 @@ def get_shipping_inventory_configuration_catalog():
})
@admin_bp.route('/shipping-notice/movement-fields', methods=['GET'])
@require_admin
def list_movement_fields():
"""标准异动字段目录(只读领域契约,供收料异动解析规则映射表单;禁止增删)。"""
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
return _ok([
{
'code': field.code, 'value_type': str(field.value_type),
'required': bool(field.required), 'is_identity': bool(field.is_identity),
}
for field in MOVEMENT_FIELDS
])
@admin_bp.route('/shipping-notice/parsing-profiles', methods=['GET'])
@require_admin
def list_shipping_inventory_parsing_profiles():
+1 -1
View File
@@ -15,7 +15,7 @@ from app.core.auth.jwt import get_current_user
from app.core.errors import UnauthorizedError
from app.models import Agent, User, AgentGuide
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
from app.services.minio_service import minio_service
from app.services.integrations.minio import minio_service
# 定义 Blueprint,将在应用工厂中注册为 /api/agents
agents_bp = Blueprint('agents', __name__)
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -36,7 +36,7 @@ def get_chat_query_preview(chat_log_id: int):
if not sql:
raise ValidationError('query preview sql is missing')
from app.services.text2sql import Text2SQLService
from app.services.integrations.text2sql import Text2SQLService
total_count = payload.get('total_count')
try:
total_count = int(total_count) if total_count is not None else None
+1 -1
View File
@@ -87,7 +87,7 @@ def chat_completions():
role=getattr(user, 'role', None),
)
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
external_conversation_id = None
if conversation_id:
+1 -1
View File
@@ -35,7 +35,7 @@ def _should_reset_provider_conversation_for_asset_query(query: str, agent_proxy)
- 仅当用户本轮问题可脱离上一轮上下文独立完成时触发;
- 这样可以保留本地同一历史会话,又避免把上一轮超大结果继续带给上游模型,导致 context length 爆掉。
"""
from app.services.text2sql import Text2SQLService
from app.services.integrations.text2sql import Text2SQLService
return Text2SQLService._should_reset_provider_conversation(query, agent_proxy)
+2 -2
View File
@@ -25,7 +25,7 @@ def get_oa_employees():
page = 1
page_size = 20
try:
from app.services.oa_sqlserver import OASQLServerService
from app.services.integrations.oa.sqlserver import OASQLServerService
result = OASQLServerService.search_employees(keyword, page, page_size)
return jsonify(result)
except Exception as e:
@@ -39,7 +39,7 @@ def resolve_oa_names():
sub_ids = request.args.get('subcompany_ids', '').strip()
result = {}
try:
from app.services.oa_sqlserver import OASQLServerService
from app.services.integrations.oa.sqlserver import OASQLServerService
if dept_ids:
for did in dept_ids.split(','):
did = did.strip()
+11 -3
View File
@@ -2,8 +2,8 @@
api/chat/sessions.py
用途:处理聊天会话、历史消息与本地结构化消息路由。
依赖:chat.shared、chat.core、ChatSession、ChatLog。
逻辑:校验当前用户和 Agent 后读写会话及日志,保持历史数据兼容查询。
依赖:chat.shared、chat.core、ChatSession、ChatLog、_normalize_user_attachments。
逻辑:校验当前用户和 Agent 后读写会话及日志;用户附件快照写库前规范化,超限显式失败不落半截。
"""
from __future__ import annotations
@@ -246,7 +246,8 @@ def save_local_message():
保存前端本地生成的聊天记录(如表单、确认弹窗、合同审查结果卡等)。
核心逻辑:user 角色用 content/query 落库;纯文本 assistant 忽略 query 防重复气泡;
结构化 typed 消息(leave-form / procurement-contract-review 等)保留 query,供历史回放与会话标题。
结构化 typed 消息(leave-form / procurement-contract-review 等)保留 query,供历史回放与会话标题;
user 角色 payload 含 user_attachments 时写库前调用 _normalize_user_attachments,超限抛 ValidationError。
"""
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
@@ -286,6 +287,13 @@ def save_local_message():
if user_query and _looks_like_review_auto_title(session.title or ''):
session.title = _session_title_from_text(user_query)
# [STEP] 用户附件快照写前规范化;超限由 _normalize_user_attachments 显式失败,禁止落半截
if role == 'user' and isinstance(payload, dict) and 'user_attachments' in payload:
payload = {
**payload,
'user_attachments': _normalize_user_attachments(payload.get('user_attachments')),
}
# 如果 payload 里面包含 formId,且该 formId 已经被保存过,可以直接更新该记录
# 这样能保证前端表单状态(例如已确认)被持久化
local_id = payload.get('formId') if payload and isinstance(payload, dict) else None
+19 -6
View File
@@ -24,9 +24,9 @@ from flask import Blueprint, request, Response, stream_with_context, jsonify, g,
from sqlalchemy import func, desc, or_, exists, and_
from openpyxl import load_workbook
from app.services.agent_runtime_context.dify_inputs import build_chat_dify_inputs
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
from app.core.config.settings import Config
from app.services.integration_api import IntegrationApiService
from app.services.integrations.integration_api import IntegrationApiService
from app.core.decorators import require_agent_permission
from app.models import Agent, ChatLog, ChatSession, Feedback
from app import db
@@ -43,7 +43,7 @@ from app.core.errors import (
SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice'
# 用户消息附件白名单(迁移自 legacy app/api/chat.py;供 ChatLog payload 与历史接口复用)。
CHAT_USER_ATTACHMENT_LIMIT = 20
CHAT_USER_ATTACHMENT_LIMIT = 200
CHAT_USER_ATTACHMENT_MAX_SIZE = 10 * 1024 * 1024 * 1024
CHAT_USER_ATTACHMENT_TYPES = {'image', 'document', 'audio', 'video', 'custom'}
CHAT_USER_ATTACHMENT_SOURCES = {'local', 'remote', 'shipping_notice'}
@@ -53,18 +53,31 @@ def _normalize_user_attachments(value) -> list[dict]:
"""
校验并清洗用户消息附件快照,供 ChatLog payload 与历史接口复用。
核心逻辑:仅接受展示白名单字段;剥离路径、控制字符与未知枚举,不接收 URL、上传 ID 或资产编号。
核心逻辑:仅接受展示白名单字段;剥离路径、控制字符与未知枚举;
列表长度超过 CHAT_USER_ATTACHMENT_LIMIT 时显式失败,禁止静默截断。
Args:
value: 前端 user_attachments 原始值;必须为列表,最多处理 20 项。
value: 前端 user_attachments 原始值;必须为列表。
Returns:
可安全写入 JSON 的附件快照列表;非法项目被忽略。
Raises:
ValidationError: 列表长度超过上限(code=CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED)。
"""
if not isinstance(value, list):
return []
if len(value) > CHAT_USER_ATTACHMENT_LIMIT:
raise ValidationError(
f'User attachments exceed limit ({CHAT_USER_ATTACHMENT_LIMIT})',
code='CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED',
details={
'limit': CHAT_USER_ATTACHMENT_LIMIT,
'count': len(value),
},
)
normalized: list[dict] = []
for item in value[:CHAT_USER_ATTACHMENT_LIMIT]:
for item in value:
if not isinstance(item, dict):
continue
raw_name = str(item.get('name') or '')
+1 -1
View File
@@ -27,7 +27,7 @@ def upload_chat_file():
if not upload:
raise ValidationError('file is required')
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
from app.core.config.settings import Config
params = DifyService.get_app_parameters(agent, force_refresh=True)
+83 -29
View File
@@ -2,10 +2,10 @@
backend/app/api/contract_payment.py
用途:采购合同付款预警 Agent 的合同台账、付款计划、待发送摘要、台账汇总卡和同步 API。
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、contract_payment 服务和通用 Job 队列。
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、Agent 授权、contract_payment 服务和通用 Job 队列。
逻辑:页面查询合同、节点、本周待发送摘要与四张汇总卡;同步和预警操作入队,避免请求线程执行外部系统和企微调用。
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍。
鉴权:查询接口要求 `contract_payment.access`(admin 默认开,可显式授予普通用户);
鉴权:查询接口要求平台 admin 或持有 `agent_code=contract_payment` 的 Agent 授权;
同步/扫描/周汇总发送仅 `role=admin`。
"""
@@ -21,6 +21,7 @@ from app.core.response import ok
from app.jobs.queue import enqueue
from app.jobs.types import JobType
from app.models import (
Agent,
ContractPaymentAlert,
ContractPaymentAlertBatch,
ContractPaymentAttachment,
@@ -41,6 +42,8 @@ from app.services.file_assets.service import read_asset_bytes
contract_payment_bp = Blueprint("contract_payment", __name__)
CONTRACT_PAYMENT_AGENT_CODE = "contract_payment"
def _attachment_parse_priority(attachment: ContractPaymentAttachment) -> tuple[int, int]:
"""
@@ -74,35 +77,45 @@ def _require_user():
return user
def _user_has_contract_payment_agent(user) -> bool:
"""
判断用户是否持有启用中的合同付款预警 Agent。
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions;admin 不走此判断。
"""
agent = Agent.query.filter_by(agent_code=CONTRACT_PAYMENT_AGENT_CODE, is_active=True).first()
return bool(agent is not None and agent in user.agents)
def _require_contract_payment_access():
"""
确保当前用户已登录且具备合同付款预警访问权限。
核心逻辑:登录校验之后读取 `contract_payment.access`;admin 角色默认具备,
其他角色需在用户管理中显式授予。无权限时返回业务 403,而不是静默空数据。
核心逻辑:平台 admin 放行;普通用户必须被授予启用中的 `agent_code=contract_payment` Agent。
无权限时返回业务 403,而不是静默空数据。
Args:
无。当前请求身份由 JWT 上下文提供。
Returns:
已认证且具备合同付款预警访问权限的用户。
已认证且具备合同付款预警 Agent 授权(或 admin)的用户。
Raises:
UnauthorizedError: 请求没有有效登录身份。
ForbiddenError: 已登录但没有 `contract_payment.access`。
ForbiddenError: 已登录但没有合同付款预警 Agent 授权。
"""
user = _require_user()
if not user.can_access_contract_payment():
raise ForbiddenError(
'Contract payment access required',
code='CONTRACT_PAYMENT.FORBIDDEN',
)
return user
if getattr(user, "role", None) == "admin" or _user_has_contract_payment_agent(user):
return user
raise ForbiddenError(
'Contract payment agent permission required',
code='CONTRACT_PAYMENT.FORBIDDEN',
)
def _require_contract_payment_admin():
"""
确保当前用户既有合同付款预警访问权,又是平台管理员。
核心逻辑:普通授权用户可查台账;同步 OA、强制覆盖、批量重解析、扫描预警和发送周汇总
核心逻辑:持有 Agent 的普通用户可查台账;同步 OA、强制覆盖、批量重解析、扫描预警和发送周汇总
会改写外部系统或触发企微,因此仅 `role=admin` 可调用。
Args:
@@ -195,19 +208,48 @@ def _serialize_contract(row: ContractPaymentContract) -> dict:
}
@contract_payment_bp.route("/contracts", methods=["GET"])
def list_contracts():
def _review_only_requested() -> bool:
"""
查询合同台账。
判断当前请求是否只要待确认合同。
核心逻辑:支持合同编号、流程编号、采购单号、供应商名称、解析状态和汇总卡口径(focus)筛选,并按 offset 分页返回台账。
Args:
无。筛选条件从 query string 读取。
无。读取 query string 的 review_only。
Returns:
标准成功 envelope,data 包含 total、page、page_size、pages 和 items。
值为 1 / true / yes 时为 True。
"""
return str(request.args.get("review_only") or "").strip().lower() in {"1", "true", "yes"}
def _scoped_contract_query(*, review_only: bool, parse_status: str = ""):
"""
按台账 / 待确认口径收窄合同查询。
核心逻辑:review_only 优先于 parse_status;二者都空时默认只看已解析台账。
Args:
review_only: 为 True 时只返回 needs_review。
parse_status: 精确解析状态;review_only 为 False 且为空时默认 parsed。
Returns:
已套上解析状态条件的合同查询。
"""
_require_contract_payment_access()
query = db.session.query(ContractPaymentContract)
if review_only:
return query.filter_by(parse_status="needs_review")
if parse_status:
return query.filter_by(parse_status=parse_status)
# 自动付款预警台账仅展示关键解析事实完整的合同;待确认合同由独立导航集中处理。
return query.filter_by(parse_status="parsed")
def _apply_contract_text_filters(query):
"""
叠关键词过滤。
核心逻辑:keyword 对合同号、流程号、采购单号、供应商、申请人做模糊 OR。
Args:
query: 已按解析状态收窄的合同查询。
Returns:
叠加文本过滤后的查询。
"""
keyword = str(request.args.get("keyword") or "").strip()
if keyword:
like = f"%{keyword}%"
@@ -216,16 +258,28 @@ def list_contracts():
| ContractPaymentContract.workflow_no.ilike(like)
| ContractPaymentContract.purchase_order_no.ilike(like)
| ContractPaymentContract.supplier_name.ilike(like)
| ContractPaymentContract.applicant_name.ilike(like)
)
return query
@contract_payment_bp.route("/contracts", methods=["GET"])
def list_contracts():
"""
查询合同台账。
核心逻辑:支持合同编号、流程编号、采购单号、供应商、申请人、解析状态和汇总卡口径(focus)筛选,并按 offset 分页返回台账。
Args:
无。筛选条件从 query string 读取。
Returns:
标准成功 envelope,data 包含 total、page、page_size、pages 和 items。
"""
_require_contract_payment_access()
review_only = _review_only_requested()
parse_status = str(request.args.get("parse_status") or "").strip()
review_only = str(request.args.get("review_only") or "").strip().lower() in {"1", "true", "yes"}
if review_only:
query = query.filter_by(parse_status="needs_review")
elif parse_status:
query = query.filter_by(parse_status=parse_status)
else:
# 自动付款预警台账仅展示关键解析事实完整的合同;待确认合同由独立导航集中处理。
query = query.filter_by(parse_status="parsed")
query = _apply_contract_text_filters(
_scoped_contract_query(review_only=review_only, parse_status=parse_status)
)
focus = str(request.args.get("focus") or "").strip()
if focus:
if review_only:
@@ -262,7 +316,7 @@ def get_ledger_summary():
Args:
无。
Returns:
标准成功 envelope,含 due、overdue、needs_completion、due_this_month。
标准成功 envelope,含 due、overdue、active、due_this_month。
"""
_require_contract_payment_access()
return ok(ledger_focus_counts(session=db.session), request_id=getattr(g, "request_id", None))
+10 -21
View File
@@ -3,7 +3,7 @@ backend/app/api/file_check_tools.py
用途:文件检核 / 立账凭证检核 Chatflow 显式 HTTP Tool API(启动检核复用本蓝图)。
依赖:workspace_file_check、file_check_tools、schedule.scheduler_service。
逻辑:发起检核时可透传顶层 mode/invoice_no(或嵌套 run_options)写入 ScheduleRun.api_request_json。
逻辑:发起检核时可透传顶层 mode/invoice_no(或嵌套 run_options)写入 ScheduleRun.api_request_json;实际执行入队 FILE_CHECK_RUN,由 schedule worker 执行。
"""
from __future__ import annotations
@@ -17,6 +17,7 @@ from sqlalchemy import text
from app import db
from app.api.workspace_file_check import serialize_file_judgement
from app.jobs import JobType, enqueue
from app.core.errors import (
AppError,
ConflictError,
@@ -31,7 +32,7 @@ from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE, resolve_hx
from app.services.schedule import _build_srm_conn_str
from app.services.schedule.query_service import get_run, serialize_run
from app.services.schedule.srm_service import _fetch_records
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
from app.services.schedule.scheduler_service import _generate_run_no
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
try:
@@ -543,28 +544,16 @@ def run_file_check():
db.session.commit()
_record_run_bind(run, data)
db.session.commit()
app = current_app._get_current_object()
run_id = run.id
task_id = task.id
def _background():
with app.app_context():
t = db.session.get(ScheduleTask, task_id)
r = db.session.get(ScheduleRun, run_id)
if not t or not r:
return
try:
run_task_now(t, trigger_type="dify_chatflow", triggered_by_user_id=None, run=r)
except Exception as exc:
current_app.logger.error("[file-check-tool] run_id=%s failed: %s", run_id, exc, exc_info=True)
r = db.session.get(ScheduleRun, run_id)
if r and r.status == "running":
r.status = "failed"
r.error_message = str(exc)
r.finished_at = datetime.utcnow()
db.session.commit()
threading.Thread(target=_background, daemon=True, name=f"file-check-run-{run_id}").start()
enqueue(
JobType.FILE_CHECK_RUN,
{"task_id": task_id, "schedule_run_id": run_id},
domain="file_check",
business_ref=str(run_id),
message="等待执行文件检核",
)
db.session.refresh(run)
lock_ms = int((time.perf_counter() - lock_started) * 1000)
total_ms = int((time.perf_counter() - perf_started) * 1000)
+104 -16
View File
@@ -28,7 +28,7 @@ from app.services.in_transit_transfer.execution_service import (
)
from app.services.in_transit_transfer.manual_close_service import manual_close_item
from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck
from app.services.in_transit_transfer.retry_service import retry_item
from app.services.in_transit_transfer.retry_service import requery_items as retry_service_requery_items, retry_item
from app.services.in_transit_transfer.serializers import (
serialize_item,
serialize_source,
@@ -72,9 +72,11 @@ def _ok(payload: Any, *, status: int = 200):
@in_transit_transfer_bp.route("/prechecks", methods=["POST"])
@require_transfer_permission
def create_precheck_api():
"""创建或复用一次调拨预检(只读,不写 ERP)。
"""创建或复用一次调拨预检(只读,不写 外部系统)。
请求体:{"source_codes": [...], "business_date": "YYYY-MM-DD"(可选)}。
请求体:{"source_codes": [...], "business_date": "YYYY-MM-DD"(可选),
"receipt_date_from"/"receipt_date_to"(可选),
"transfer_type": "in_transit_to_hub"(可选,缺省在途仓至HUB仓)}。
响应:201 envelope,data 为预检摘要(precheck_id/hash/计数/来源进度)。
"""
body = request.get_json(silent=True) or {}
@@ -89,6 +91,9 @@ def create_precheck_api():
source_codes=[str(item).strip() for item in source_codes],
business_date=business_date,
deps=deps,
receipt_date_from=str(body.get("receipt_date_from")) if body.get("receipt_date_from") else None,
receipt_date_to=str(body.get("receipt_date_to")) if body.get("receipt_date_to") else None,
transfer_type=str(body.get("transfer_type")) if body.get("transfer_type") else None,
)
return _ok(serialize_summary(summary), status=201)
@@ -111,7 +116,7 @@ def execute_precheck_api(precheck_id: str):
"""确认预检选择范围并直接生成执行 Run(决策 4/5:无独立确认页)。
请求体:{"invoice_nos": [...]}(可选;缺省执行全部可执行项)。
响应:201 envelope,data 为 run_no / run 状态 / ERP 单号聚合结果。
响应:201 envelope,data 为 run_no / run 状态 / 外部系统 单号聚合结果。
"""
body = request.get_json(silent=True) or {}
invoice_nos = body.get("invoice_nos") if isinstance(body, dict) else None
@@ -130,6 +135,88 @@ def execute_precheck_api(precheck_id: str):
}, status=201)
@in_transit_transfer_bp.route("/prechecks/<precheck_no>/items/requery", methods=["POST"])
@require_transfer_permission
def requery_items_api(precheck_no: str):
"""批量重查 外部系统 库存(可恢复阻断行);body 可选 invoice_nos 限定范围。"""
user = _require_user()
body = request.get_json(silent=True) or {}
invoice_nos = body.get("invoice_nos") if isinstance(body.get("invoice_nos"), list) else None
deps = transfer_deps.get_transfer_dependencies()
return _ok(retry_service_requery_items(
precheck_no=precheck_no, deps=deps, invoice_nos=invoice_nos,
actor_id=str(user.id) if user.id else None,
))
@in_transit_transfer_bp.route("/sources/receipt-files", methods=["POST"])
@require_transfer_permission
def download_source_receipt_files_api():
"""按选中来源打包下载各自最新归档收料文件(zip);记录访问审计。"""
import io
import zipfile
from pathlib import Path as _Path
from app import db
from app.models import ShippingReceiptReportFile
from app.services.file_assets.storage import file_asset_storage
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition
body = request.get_json(silent=True) or {}
source_codes = body.get("source_codes")
if not isinstance(source_codes, list) or not [c for c in source_codes if str(c or "").strip()]:
raise ValidationError("source_codes is required")
buffer = io.BytesIO()
included: list[str] = []
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
for code in source_codes:
code = str(code or "").strip()
if not code:
continue
report = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=code),
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)与徽标/预检取文件同口径,
# 单一事实来源见 receipt_file_gate。
usable_receipt_file_condition(),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.first()
)
if report is None:
continue
data = file_asset_storage.get_bytes(report.storage_key)
safe_name = _Path(report.original_filename or f"{report.id}.xlsx").name
archive.writestr(f"{code}-{safe_name}", data)
included.append(code)
if not included:
raise NotFoundError("no archived receipt files", code="SHIPPING.RECEIPT_FILE_NOT_FOUND")
user = _require_user()
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_RECEIPT_FILES_DOWNLOADED",
aggregate_type="in_transit_source",
aggregate_id=",".join(included),
actor_type="user",
actor_id=str(user.id) if user.id else None,
actor_display=str(getattr(user, "name", "") or ""),
request_id=getattr(g, "request_id", None),
result="success",
))
db.session.commit()
buffer.seek(0)
return send_file(
buffer,
mimetype="application/zip",
as_attachment=True,
download_name=f"receipt-files-{len(included)}-source{'s' if len(included) > 1 else ''}.zip",
)
@in_transit_transfer_bp.route("/runs/<run_no>", methods=["GET"])
@require_transfer_permission
def get_run_api(run_no: str):
@@ -149,14 +236,14 @@ def cancel_run_api(run_no: str):
@in_transit_transfer_bp.route("/items/<int:item_id>/retry", methods=["POST"])
@require_transfer_permission
def retry_item_api(item_id: int):
"""人工重试异常项(基于冻结文件仅重新查询 ERP,创建新 Attempt)。
"""人工重试异常项(基于冻结文件仅重新查询 外部系统,创建新 Attempt)。
请求体:{"kind": "erp_recheck"}(可选,默认 erp_recheck)。
请求体:{"kind": "external_recheck"}(可选,默认 external_recheck)。
"""
body = request.get_json(silent=True) or {}
kind = body.get("kind") if isinstance(body, dict) else None
deps = transfer_deps.get_transfer_dependencies()
return _ok(retry_item(item_id=item_id, deps=deps, kind=kind or "erp_recheck"))
return _ok(retry_item(item_id=item_id, deps=deps, kind=kind or "external_recheck"))
@in_transit_transfer_bp.route("/items/<int:item_id>/manual-close", methods=["POST"])
@@ -257,10 +344,10 @@ def receipt_files_api(run_no: str):
)
@in_transit_transfer_bp.route("/runs/<run_no>/erp-inventory", methods=["GET"])
@in_transit_transfer_bp.route("/runs/<run_no>/external-inventory", methods=["GET"])
@require_transfer_permission
def erp_inventory_api(run_no: str):
"""下载本次预检冻结的 ERP 库存表(csv);记录访问审计。"""
"""下载本次预检冻结的 外部系统 库存表(csv);记录访问审计。"""
import io
from app import db
@@ -270,19 +357,19 @@ def erp_inventory_api(run_no: str):
run = TransferRun.query.filter_by(run_no=str(run_no).strip()).first()
if run is None:
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
lines = ["invoice_no,source_code,material_no,from_warehouse,to_warehouse,receipt_quantity,erp_quantity,result,erp_document_no"]
lines = ["invoice_no,source_code,material_no,from_warehouse,to_warehouse,receipt_quantity,external_quantity,result,external_document_no"]
for item in TransferInvoiceItem.query.filter_by(run_id=run.id).order_by(TransferInvoiceItem.invoice_no).all():
lines.append(",".join([
str(item.invoice_no), str(item.source_code), str(item.material_no),
str(item.from_warehouse), str(item.to_warehouse),
str(item.receipt_quantity), str(item.erp_quantity or ""),
str(item.result_code or item.status), str(item.erp_document_no or ""),
str(item.receipt_quantity), str(item.external_quantity or ""),
str(item.result_code or item.status), str(item.external_document_no or ""),
]))
data = ("\n".join(lines) + "\n").encode("utf-8")
user = _require_user()
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_ERP_INVENTORY_DOWNLOADED",
event_type="TRANSFER_EXTERNAL_INVENTORY_DOWNLOADED",
aggregate_type="transfer_run",
aggregate_id=run_no,
run_no=run_no,
@@ -297,7 +384,7 @@ def erp_inventory_api(run_no: str):
io.BytesIO(data),
mimetype="text/csv",
as_attachment=True,
download_name=f"erp-inventory-{run_no}.csv",
download_name=f"external-inventory-{run_no}.csv",
)
@@ -315,8 +402,9 @@ def transfer_metrics_api():
def transfer_sources_api():
"""来源实例列表(决策 3:平台 DBS/Crane 仅分组,实例为执行边界)。
每来源附收料文件状态(ready/fetching/failed/none + has_ready_file),
供前端门禁(无 ready 文件时禁止确认预检)与状态标识。只读复用已启用库存来源。
每来源附收料文件状态(ready/fetching/failed/expired/none + has_ready_file),
供前端门禁(无 ready 文件时禁止确认预检)与状态标识;保留期已到或非当天
(业务日)抓取且未清理均投影 expired。只读复用已启用库存来源。
"""
from app.models import ShippingInventorySource
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
+1 -1
View File
@@ -22,7 +22,7 @@ from app.core.errors import (
ValidationError,
raise_for_status,
)
from app.services.integration_api import IntegrationApiService
from app.services.integrations.integration_api import IntegrationApiService
integration_bp = Blueprint('integration', __name__)
+369 -67
View File
@@ -1,21 +1,30 @@
"""api/integration_connector.py
用途:Integration Connector Admin API——配置实体 CRUD、能力清单、能力调用端点与连接测试。
依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway。
依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway、credential_crypto。
逻辑:全部 require_admin;能力调用只接受 {params, context, operation_id, idempotency_key},
拒绝 interface_id(禁止覆盖 Binding);配置写操作做字段白名单校验,非法即 400。
接口定义的连接器类型由所属客户端实例服务端推导(单一事实源);接口定义与绑定的
状态只经 /publish /unpublish /retire /reopen 动作端点按 CONFIG_STATUS_TRANSITIONS
转移(绑定发布附加就绪门禁:接口须已发布且客户端启用);绑定创建/更新做客户端
与接口成对校验(接口定义必须属于所选客户端实例,错配即 400)。
凭据引用状态为两态开关:PUT 仅允许 active/retired(rotating 不可进入,存量可置回
active 恢复);接口定义 enabled 冻结忽略传值(可用性只由 status 表达)。
凭据引用 db 模式在服务端加密用户名/密码落库,接口响应永不回显明文/密文。
注意:url_prefix 在 api/__init__.py 注册为 /api/integration-connector(区别于既有
/api/integration Dify 文件代理)。
"""
from __future__ import annotations
import json
import uuid
from flask import Blueprint, request
from app.core.credential_crypto import CredentialCryptoErrorCodes, decrypt_secret, encrypt_secret
from app.core.decorators import require_admin
from app.core.errors import NotFoundError, ValidationError
from app.core.errors import AppError, NotFoundError, ValidationError
from app.core.response import ok
from app.models import (
IntegrationBinding,
@@ -23,14 +32,36 @@ from app.models import (
IntegrationCredentialReference,
IntegrationInterfaceDefinition,
)
from app.services.integration_connector.capability import ensure_capabilities_loaded, list_capabilities
from app.services.integration_connector.capability import list_capabilities
from app.services.integration_connector.credential_types import (
build_secret_dict,
get_credential_type,
list_credential_types,
visible_fields,
)
from app.services.integration_connector.gateway import get_capability_gateway
from app.services.integration_connector.transports.base import IntegrationCallResult
from app.services.integration_connector.security import CREDENTIAL_KEY_CONFIG_NAME, _DB_SECRET_CODES
from app.services.integration_connector.transports.base import IntegrationCallResult, merge_client_config
integration_connector_bp = Blueprint('integration_connector', __name__)
VALID_CONNECTOR_TYPES = ('rest', 'soap')
VALID_STATUSES = ('draft', 'published', 'retired')
VALID_SECRET_PROVIDERS = ('db', 'env')
# 凭据两态化(UI 可达状态):resolve_credential 只解析 active(fail-closed),「轮换中」
# 现语义等于断供且真实版本化轮换未实现(属 P2),故 PUT 只允许在 active/retired 间切换,
# rotating 不再可进入;存量 rotating 数据保留只读展示,经 PUT 置 active 即恢复。
VALID_CREDENTIAL_UI_STATUSES = ('active', 'retired')
# 配置实体生命周期转移表(接口定义与绑定共用):动作 → (源状态, 目标状态)。状态不再
# 由 PUT 直接改写,只能经动作端点按此表转移(draft→published 发布;published→draft 撤回;
# published→retired 退役;retired→draft 恢复为草稿,作为无版本化阶段的保险阀)。
CONFIG_STATUS_TRANSITIONS = {
'publish': ('draft', 'published'),
'unpublish': ('published', 'draft'),
'retire': ('published', 'retired'),
'reopen': ('retired', 'draft'),
}
def _require(value, field: str) -> None:
@@ -39,6 +70,70 @@ def _require(value, field: str) -> None:
raise ValidationError(f'{field} is required', details={'field': field})
def _require_client(code: str) -> IntegrationClientInstance:
"""按编码取客户端实例;不存在即 400(接口定义的连接器类型以其为单一事实源)。"""
client = IntegrationClientInstance.query.filter_by(code=code).first()
if client is None:
raise ValidationError(
'client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND',
details={'client_instance_code': code},
)
return client
def _apply_status_transition(entity, action: str, *, kind: str) -> None:
"""按转移表校验并落库状态;非法动作或源状态不符即 400。"""
transition = CONFIG_STATUS_TRANSITIONS.get(action)
if transition is None:
raise ValidationError(
'unknown lifecycle action', details={'allowed': sorted(CONFIG_STATUS_TRANSITIONS)})
src, dst = transition
if entity.status != src:
raise ValidationError(
f'{kind} status is {entity.status}, cannot {action}',
code='INTEGRATION.ILLEGAL_STATUS_TRANSITION',
details={'action': action, 'from': entity.status, 'to': dst},
)
entity.status = dst
def _require_interface(code: str) -> IntegrationInterfaceDefinition:
"""按编码取接口定义;不存在即 400(绑定成对校验以其所属客户端为准,而非依赖外键报 500)。"""
iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first()
if iface is None:
raise ValidationError(
'interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND',
details={'interface_definition_code': code},
)
return iface
def _validate_binding_pair(client_code, interface_code) -> tuple[IntegrationClientInstance, IntegrationInterfaceDefinition]:
"""绑定成对校验:接口定义必须属于所选客户端实例(接口归属即客户端归属)。
错配组合会产生「拿 A 客户端的地址/凭据发 B 接口报文」的调用,创建/更新时直接
400(fail-fast),不留给调用期 fail-closed。
"""
client = _require_client(str(client_code).strip())
iface = _require_interface(str(interface_code).strip())
if iface.client_instance_code != client.code:
raise ValidationError(
'interface definition does not belong to the selected client instance',
code='INTEGRATION.BINDING_PAIR_MISMATCH',
details={
'client_instance_code': client.code,
'interface_definition_code': iface.code,
'interface_client_instance_code': iface.client_instance_code,
},
)
return client, iface
def _interface_transition(iface, action: str) -> None:
"""按转移表校验并落库接口定义状态;非法动作或源状态不符即 400。"""
_apply_status_transition(iface, action, kind='interface')
def _serialize_client(client) -> dict:
return {
'id': client.id, 'code': client.code, 'name': client.name,
@@ -64,7 +159,7 @@ def _serialize_binding(binding) -> dict:
return {
'id': binding.id, 'capability': binding.capability,
'context_selector_json': binding.context_selector_json or {},
'context_source_code': binding.context_source_code,
'param_mapping_json': binding.param_mapping_json or {},
'client_instance_code': binding.client_instance_code,
'interface_definition_code': binding.interface_definition_code,
'mapping_version': binding.mapping_version, 'priority': binding.priority,
@@ -73,15 +168,59 @@ def _serialize_binding(binding) -> dict:
}
def _decrypted_secret(cred) -> dict:
"""db 模式下解密凭据字典;密文缺失或主密钥异常时返回空 dict(fail-closed 不炸列表)。"""
if cred.secret_provider != 'db' or not cred.secret_ciphertext:
return {}
try:
raw = decrypt_secret(
cred.secret_ciphertext,
key_config_name=CREDENTIAL_KEY_CONFIG_NAME,
codes=_DB_SECRET_CODES,
)
parsed = json.loads(raw)
return parsed if isinstance(parsed, dict) else {}
except AppError:
return {}
def _serialize_credential(cred) -> dict:
secret_dict = _decrypted_secret(cred)
return {
'id': cred.id, 'code': cred.code, 'secret_ref': cred.secret_ref,
'secret_provider': cred.secret_provider, 'credential_type': cred.credential_type,
# 非密字段按类型定义回显(如 username);密文字段与密文本身永不回显。
'secret_fields': visible_fields(cred.credential_type, secret_dict),
'has_secret': bool(cred.secret_ciphertext),
'version': cred.version, 'status': cred.status,
'updated_at': cred.updated_at.isoformat() if cred.updated_at else None,
'last_verified_at': cred.last_verified_at.isoformat() if cred.last_verified_at else None,
}
def _apply_db_secret(cred, body) -> None:
"""db 模式:按凭据类型定义组装字段并加密落库;只改部分字段可沿用解密出的旧值。
类型必须在凭据类型注册表内(fail-closed);合并旧值后必填字段仍缺失即拒绝。
"""
ctype = str(body.get('credential_type') or cred.credential_type or 'password').strip()
if get_credential_type(ctype) is None:
raise ValidationError('unknown credential_type', details={'credential_type': ctype})
cred.credential_type = ctype
current = _decrypted_secret(cred) if cred.secret_ciphertext else {}
values: dict = dict(current)
for key in (field['key'] for field in get_credential_type(ctype)['fields']):
incoming = body.get(key)
if incoming is not None and str(incoming) != '':
values[key] = str(incoming)
merged = build_secret_dict(ctype, values)
cred.secret_ciphertext = encrypt_secret(
json.dumps(merged, ensure_ascii=False),
key_config_name=CREDENTIAL_KEY_CONFIG_NAME,
codes=_DB_SECRET_CODES,
)
def _result_to_dict(result: IntegrationCallResult) -> dict:
return {
'status': result.status,
@@ -98,7 +237,6 @@ def _result_to_dict(result: IntegrationCallResult) -> dict:
@integration_connector_bp.route('/capabilities', methods=['GET'])
@require_admin
def list_capabilities_endpoint():
ensure_capabilities_loaded()
data = [{
'name': spec.name, 'write': spec.write, 'idempotency': spec.idempotency,
'input_schema': spec.input_schema, 'output_schema': spec.output_schema,
@@ -231,15 +369,15 @@ def create_interface_definition():
code = str(body.get('code') or '').strip()
_require(code, 'code')
_require(body.get('client_instance_code'), 'client_instance_code')
connector_type = str(body.get('connector_type') or '')
if connector_type not in VALID_CONNECTOR_TYPES:
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
# 连接器类型以所选客户端实例为单一事实源(服务端推导落库,忽略请求体传值,
# 杜绝接口与客户端类型不一致);客户端不存在即 400,而非依赖外键报 500。
client = _require_client(str(body['client_instance_code']).strip())
status = str(body.get('status') or 'draft')
if status not in VALID_STATUSES:
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
iface = IntegrationInterfaceDefinition(
code=code, name=str(body.get('name') or code).strip(),
client_instance_code=body['client_instance_code'], connector_type=connector_type,
client_instance_code=client.code, connector_type=client.connector_type,
http_method=(str(body.get('http_method') or '').strip().upper() or None),
request_path=(str(body.get('request_path') or '').strip() or None),
request_spec_json=body.get('request_spec_json') or {},
@@ -247,7 +385,9 @@ def create_interface_definition():
response_mapping_json=body.get('response_mapping_json') or {},
output_schema_json=body.get('output_schema_json') or {},
version=int(body.get('version') or 1), status=status,
enabled=bool(body.get('enabled', True)),
# enabled 冻结:与 status 重复表达可用性且运行时不消费(假开关),请求体传值忽略;
# 可用性只由 status 生命周期表达,列待 P2 版本化迁移时清理。
enabled=True,
)
from app import db
db.session.add(iface)
@@ -258,7 +398,11 @@ def create_interface_definition():
@integration_connector_bp.route('/interface-definitions/<code>', methods=['PUT'])
@require_admin
def update_interface_definition(code):
"""更新接口定义(code 不变;可改模板/入参/回传/出参 Schema、状态、启停)。"""
"""更新接口定义(code 不变;可改模板/入参/回传/出参 Schema 与所属客户端)。
状态不在此改写(须经 /publish /unpublish /retire /reopen 动作端点按转移表流转);
连接器类型由所属客户端实例服务端推导,请求体传值被忽略。
"""
iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first()
if iface is None:
raise NotFoundError('interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND')
@@ -268,12 +412,9 @@ def update_interface_definition(code):
iface.name = str(body['name']).strip()
if body.get('client_instance_code') is not None:
_require(body.get('client_instance_code'), 'client_instance_code')
iface.client_instance_code = body['client_instance_code']
if body.get('connector_type') is not None:
connector_type = str(body['connector_type'])
if connector_type not in VALID_CONNECTOR_TYPES:
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
iface.connector_type = connector_type
client = _require_client(str(body['client_instance_code']).strip())
iface.client_instance_code = client.code
iface.connector_type = client.connector_type
if 'http_method' in body:
iface.http_method = str(body.get('http_method') or '').strip().upper() or None
if 'request_path' in body:
@@ -283,18 +424,52 @@ def update_interface_definition(code):
setattr(iface, json_field, body.get(json_field) or {})
if body.get('version') is not None:
iface.version = int(body.get('version') or 1)
if body.get('status') is not None:
status = str(body['status'])
if status not in VALID_STATUSES:
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
iface.status = status
if 'enabled' in body:
iface.enabled = bool(body.get('enabled', True))
from app import db
db.session.commit()
return ok(_serialize_interface(iface))
# ---- 接口定义生命周期(状态只经动作端点按转移表流转) ----
def _do_interface_lifecycle(code: str, action: str):
"""动作端点共用体:取接口 → 按转移表转移 → 落库并回显。"""
iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first()
if iface is None:
raise NotFoundError('interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND')
_interface_transition(iface, action)
from app import db
db.session.commit()
return ok(_serialize_interface(iface))
@integration_connector_bp.route('/interface-definitions/<code>/publish', methods=['POST'])
@require_admin
def publish_interface_definition(code):
"""发布接口定义(draft → published):发布后才会被绑定解析选中。"""
return _do_interface_lifecycle(code, 'publish')
@integration_connector_bp.route('/interface-definitions/<code>/unpublish', methods=['POST'])
@require_admin
def unpublish_interface_definition(code):
"""撤回发布(published → draft):临时下线,修正后可重新发布。"""
return _do_interface_lifecycle(code, 'unpublish')
@integration_connector_bp.route('/interface-definitions/<code>/retire', methods=['POST'])
@require_admin
def retire_interface_definition(code):
"""退役(published → retired):该接口引用的所有绑定同时失效。"""
return _do_interface_lifecycle(code, 'retire')
@integration_connector_bp.route('/interface-definitions/<code>/reopen', methods=['POST'])
@require_admin
def reopen_interface_definition(code):
"""恢复为草稿(retired → draft):版本化发布上线前的保险阀,重新走发布流程。"""
return _do_interface_lifecycle(code, 'reopen')
# ---- Binding ----
@integration_connector_bp.route('/bindings', methods=['GET'])
@@ -307,23 +482,22 @@ def list_bindings():
@integration_connector_bp.route('/bindings', methods=['POST'])
@require_admin
def create_binding():
"""创建绑定:成对校验客户端与接口后落库;新建固定落 draft,发布走 /publish 动作端点。"""
body = request.get_json(silent=True) or {}
_require(body.get('capability'), 'capability')
_require(body.get('client_instance_code'), 'client_instance_code')
_require(body.get('interface_definition_code'), 'interface_definition_code')
status = str(body.get('status') or 'draft')
if status not in VALID_STATUSES:
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
client, iface = _validate_binding_pair(body['client_instance_code'], body['interface_definition_code'])
binding = IntegrationBinding(
capability=body['capability'],
context_selector_json=body.get('context_selector_json') or {},
context_source_code=(str(body.get('context_source_code') or '').strip() or None),
client_instance_code=body['client_instance_code'],
interface_definition_code=body['interface_definition_code'],
param_mapping_json=body.get('param_mapping_json') or {},
client_instance_code=client.code,
interface_definition_code=iface.code,
mapping_version=int(body.get('mapping_version') or 1),
priority=int(body.get('priority') or 0),
environment=str(body.get('environment') or 'prod').strip(),
status=status,
status='draft',
)
from app import db
db.session.add(binding)
@@ -334,7 +508,11 @@ def create_binding():
@integration_connector_bp.route('/bindings/<int:binding_id>', methods=['PUT'])
@require_admin
def update_binding(binding_id):
"""更新绑定(capability 不变;可改 context 选择器、客户端/接口、映射版本、优先级、环境、生效区间、状态)。"""
"""更新绑定(capability 不变;可改 context 选择器、客户端/接口、映射版本、优先级、环境、生效区间)。
状态不在此改写(须经 /publish /unpublish /retire /reopen 动作端点按转移表流转);
客户端与接口成对校验:以变更后的最终组合为准,接口定义不属于该客户端即 400。
"""
from app import db
binding = db.session.get(IntegrationBinding, binding_id)
if binding is None:
@@ -345,14 +523,23 @@ def update_binding(binding_id):
binding.capability = body['capability']
if 'context_selector_json' in body:
binding.context_selector_json = body.get('context_selector_json') or {}
if 'context_source_code' in body:
binding.context_source_code = str(body.get('context_source_code') or '').strip() or None
if body.get('client_instance_code') is not None:
_require(body.get('client_instance_code'), 'client_instance_code')
binding.client_instance_code = body['client_instance_code']
if body.get('interface_definition_code') is not None:
_require(body.get('interface_definition_code'), 'interface_definition_code')
binding.interface_definition_code = body['interface_definition_code']
if 'param_mapping_json' in body:
binding.param_mapping_json = body.get('param_mapping_json') or {}
new_client_code = body.get('client_instance_code')
new_iface_code = body.get('interface_definition_code')
if new_client_code is not None:
_require(new_client_code, 'client_instance_code')
if new_iface_code is not None:
_require(new_iface_code, 'interface_definition_code')
if new_client_code is not None or new_iface_code is not None:
_validate_binding_pair(
new_client_code if new_client_code is not None else binding.client_instance_code,
new_iface_code if new_iface_code is not None else binding.interface_definition_code,
)
if new_client_code is not None:
binding.client_instance_code = str(new_client_code).strip()
if new_iface_code is not None:
binding.interface_definition_code = str(new_iface_code).strip()
if body.get('mapping_version') is not None:
binding.mapping_version = int(body.get('mapping_version') or 1)
if body.get('priority') is not None:
@@ -363,16 +550,69 @@ def update_binding(binding_id):
binding.effective_from = body['effective_from'] or None
if body.get('effective_to') is not None:
binding.effective_to = body['effective_to'] or None
if body.get('status') is not None:
status = str(body['status'])
if status not in VALID_STATUSES:
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
binding.status = status
from app import db
db.session.commit()
return ok(_serialize_binding(binding))
# ---- 绑定生命周期(状态只经动作端点按转移表流转) ----
def _do_binding_lifecycle(binding_id: int, action: str):
"""动作端点共用体:取绑定 → 按转移表转移 → 落库并回显。
发布(publish)附加就绪门禁:引用的接口定义须已发布、客户端实例须启用,
否则 400——避免出现列表「已发布」但调用期永远 fail-closed 的死绑定
(与 binding.resolve_binding 的调用期门禁同一语义)。
"""
from app import db
binding = db.session.get(IntegrationBinding, binding_id)
if binding is None:
raise NotFoundError('binding not found', code='INTEGRATION.BINDING_NOT_FOUND')
if action == 'publish':
client = IntegrationClientInstance.query.filter_by(code=binding.client_instance_code).first()
iface = IntegrationInterfaceDefinition.query.filter_by(code=binding.interface_definition_code).first()
if client is None or iface is None or iface.status != 'published' or not client.enabled:
raise ValidationError(
'binding target not ready: interface must be published and client instance enabled',
code='INTEGRATION.BINDING_TARGET_NOT_READY',
details={
'client_instance_code': binding.client_instance_code,
'interface_definition_code': binding.interface_definition_code,
},
)
_apply_status_transition(binding, action, kind='binding')
db.session.commit()
return ok(_serialize_binding(binding))
@integration_connector_bp.route('/bindings/<int:binding_id>/publish', methods=['POST'])
@require_admin
def publish_binding(binding_id):
"""发布绑定(draft → published):发布后才会被绑定解析选中。"""
return _do_binding_lifecycle(binding_id, 'publish')
@integration_connector_bp.route('/bindings/<int:binding_id>/unpublish', methods=['POST'])
@require_admin
def unpublish_binding(binding_id):
"""撤回发布(published → draft):临时下线,修正后可重新发布。"""
return _do_binding_lifecycle(binding_id, 'unpublish')
@integration_connector_bp.route('/bindings/<int:binding_id>/retire', methods=['POST'])
@require_admin
def retire_binding(binding_id):
"""退役(published → retired):绑定退出自动调用。"""
return _do_binding_lifecycle(binding_id, 'retire')
@integration_connector_bp.route('/bindings/<int:binding_id>/reopen', methods=['POST'])
@require_admin
def reopen_binding(binding_id):
"""恢复为草稿(retired → draft):重新走发布流程。"""
return _do_binding_lifecycle(binding_id, 'reopen')
# ---- 凭据引用 ----
@integration_connector_bp.route('/credential-references', methods=['GET'])
@@ -385,41 +625,87 @@ def list_credential_references():
@integration_connector_bp.route('/credential-references', methods=['POST'])
@require_admin
def create_credential_reference():
"""创建凭据引用:db 模式(默认)按凭据类型加密字段落库;env 模式只存配置键名。"""
body = request.get_json(silent=True) or {}
_require(body.get('code'), 'code')
_require(body.get('secret_ref'), 'secret_ref')
from app import db
# 缺省保持 env(兼容既有直连 API 调用);管理端 db 模式显式传 secret_provider='db'。
provider = str(body.get('secret_provider') or 'env').strip()
if provider not in VALID_SECRET_PROVIDERS:
raise ValidationError('invalid secret_provider', details={'allowed': list(VALID_SECRET_PROVIDERS)})
code = str(body['code']).strip()
if IntegrationCredentialReference.query.filter_by(code=code).first():
raise ValidationError('credential reference code already exists', code='RESOURCE.CONFLICT')
status = str(body.get('status') or 'active')
if status not in ('active', 'rotating', 'retired'):
raise ValidationError('invalid credential status', details={'allowed': ['active', 'rotating', 'retired']})
cred = IntegrationCredentialReference(
code=str(body['code']).strip(),
secret_ref=str(body['secret_ref']).strip(),
secret_provider=str(body.get('secret_provider') or 'env').strip(),
code=code,
secret_ref=str(body.get('secret_ref') or '').strip(),
secret_provider=provider,
credential_type=str(body.get('credential_type') or 'password').strip(),
version=int(body.get('version') or 1),
status=str(body.get('status') or 'active'),
status=status,
)
if provider == 'db':
_apply_db_secret(cred, body)
cred.secret_ref = f'db:{code}'
else:
_require(cred.secret_ref, 'secret_ref')
from app import db
db.session.add(cred)
db.session.commit()
# 永不回显真实凭据值;只回元数据。
# 永不回显真实凭据值;只回元数据与非密字段。
return ok(_serialize_credential(cred), status=201)
@integration_connector_bp.route('/credential-references/types', methods=['GET'])
@require_admin
def list_credential_type_specs():
"""凭据类型注册表清单(类型 + 字段定义),供管理端动态渲染表单与占位符提示。"""
return ok(list_credential_types())
@integration_connector_bp.route('/credential-references/<code>', methods=['PUT'])
@require_admin
def update_credential_reference(code):
"""更新凭据引用(code 不变;可改 secret_ref/provider/type/status)。只存引用,永不回显明文。"""
"""更新凭据引用(code 不变);db 模式可只改部分字段(其余沿用旧值),永不回显明文。"""
cred = IntegrationCredentialReference.query.filter_by(code=code).first()
if cred is None:
raise NotFoundError('credential reference not found', code='INTEGRATION.CREDENTIAL_NOT_FOUND')
body = request.get_json(silent=True) or {}
if body.get('secret_ref') is not None:
_require(body.get('secret_ref'), 'secret_ref')
cred.secret_ref = str(body['secret_ref']).strip()
if body.get('secret_provider') is not None:
cred.secret_provider = str(body['secret_provider']).strip()
if body.get('credential_type') is not None:
cred.credential_type = str(body['credential_type']).strip()
provider = str(body['secret_provider']).strip()
if provider not in VALID_SECRET_PROVIDERS:
raise ValidationError('invalid secret_provider', details={'allowed': list(VALID_SECRET_PROVIDERS)})
cred.secret_provider = provider
if provider == 'env':
# 切回 env 模式时清掉遗留密文,避免失效凭据残留库中。
cred.secret_ciphertext = None
field_keys = tuple(
field['key'] for field in (get_credential_type(
str(body.get('credential_type') or cred.credential_type or 'password')) or {'fields': []}
)['fields']
)
has_secret_input = any(body.get(key) is not None for key in field_keys)
if cred.secret_provider == 'db':
if has_secret_input or body.get('credential_type') is not None or not cred.secret_ciphertext:
_apply_db_secret(cred, body)
cred.secret_ref = f'db:{cred.code}'
else:
if body.get('secret_ref') is not None:
_require(body.get('secret_ref'), 'secret_ref')
cred.secret_ref = str(body['secret_ref']).strip()
if has_secret_input:
raise ValidationError('credential fields only apply to db credentials')
if body.get('status') is not None:
cred.status = str(body['status']).strip()
# 状态改写冻结为两态开关:仅允许 active/retired(管理端行内开关即走此通道);
# rotating 不可进入——其现语义等于断供(resolve_credential 只解析 active),
# 真实版本化轮换属 P2;存量 rotating 数据经置 active 即恢复。
status = str(body['status']).strip()
if status not in VALID_CREDENTIAL_UI_STATUSES:
raise ValidationError(
'invalid credential status', details={'allowed': list(VALID_CREDENTIAL_UI_STATUSES)})
cred.status = status
from app import db
db.session.commit()
return ok(_serialize_credential(cred))
@@ -430,6 +716,11 @@ def update_credential_reference(code):
@integration_connector_bp.route('/client-instances/<code>/test', methods=['POST'])
@require_admin
def test_connection(code):
"""连接测试探针:只证明网络/服务可达(设计文档:连接测试不做业务调用)。
配置兼容层与 binding.resolve_binding 同源:endpoint/timeout_seconds 独立列
拼回 config_json 后再交给 transport,否则存独立列的地址会被误判为未冻结。
"""
client = IntegrationClientInstance.query.filter_by(code=code).first()
if client is None:
raise NotFoundError('client instance not found')
@@ -439,9 +730,20 @@ def test_connection(code):
raise ValidationError(
'no transport available for client', code='INTEGRATION.TRANSPORT_NOT_FROZEN',
)
raw = transport.call(
client={'config_json': client.config_json or {}, 'credential': {}},
interface={'request_spec_json': {}},
request={},
)
return ok({'ok': True, 'status': raw.get('status') or 'success', 'result': raw})
client_payload = {
'config_json': merge_client_config({
'config_json': client.config_json or {},
'endpoint': client.endpoint,
'timeout_seconds': client.timeout_seconds,
}),
'credential': {},
}
probe = getattr(transport, 'probe', None)
if probe is not None:
raw = probe(client=client_payload)
ok_flag = bool(raw.get('ok'))
else:
# 测试替身等未实现 probe 的传输:回退 call(空 interface 规格)。
raw = transport.call(client=client_payload, interface={'request_spec_json': {}}, request={})
ok_flag = raw.get('status') not in ('business_failed', 'technical_failed', 'timeout', 'result_unknown')
return ok({'ok': ok_flag, 'status': 'success' if ok_flag else 'failed', 'result': raw})
-10
View File
@@ -1,10 +0,0 @@
"""
backend/app/api/knowledge_base.py
用途:知识库 API 兼容 shim(Wave 3 迁包过渡期)。
依赖:app.api.kb。
逻辑:旧 import 路径仍可用;新代码请用 app.api.kb。
"""
from app.api.kb import knowledge_base_bp
__all__ = ['knowledge_base_bp']
-10
View File
@@ -1,10 +0,0 @@
"""
backend/app/api/schedule_admin.py
用途:排程 API 兼容 shim(Wave 3 迁包过渡期)。
依赖:app.api.schedule。
逻辑:旧 import 路径仍可用;新代码请用 app.api.schedule。
"""
from app.api.schedule import schedule_admin_bp
__all__ = ['schedule_admin_bp']
+14
View File
@@ -27,6 +27,7 @@ from app.services.training_config_service import get_published_config, list_trai
from app.services.lean_training_service import (
LEAN_TRAINING_TYPE,
create_or_update_weekly_task,
export_dashboard_excel,
get_current_weekly_task,
get_weekly_task_for_admin,
list_dashboard,
@@ -275,3 +276,16 @@ def get_admin_lean_training_dashboard():
_require_lean_training_manager()
raw_task_id = request.args.get("task_id", type=int)
return ok(list_dashboard(raw_task_id))
@training_admin_bp.route("/lean-training/dashboard/export", methods=["GET"])
def export_admin_lean_training_dashboard():
_require_lean_training_manager()
raw_task_id = request.args.get("task_id", type=int)
file_data, file_name = export_dashboard_excel(raw_task_id)
return send_file(
BytesIO(file_data),
as_attachment=True,
download_name=file_name,
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
+1 -1
View File
@@ -14,7 +14,7 @@ from flask import current_app, jsonify, request
from app import db
from app.core.errors import AppError, ValidationError
from app.services.wecom_notify import send_wecom_event_message
from app.services.integrations.wecom.notify import send_wecom_event_message
from . import auth as _compat
from .auth import auth_bp
+2 -2
View File
@@ -14,8 +14,8 @@ from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaul
from app.services.feedback_notify import send_feedback_group_notification
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
from app.services.agent_registry.serialization import serialize_registry_fields
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
from app.services.integrations.wecom.notify import mark_wecom_message_opened, send_wecom_event_message
from app.services.integrations.wecom.crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
from app.core.auth.jwt import get_current_user as _auth_current_user, issue_local_access_token
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
from sqlalchemy import and_, or_, inspect, insert
+1 -1
View File
@@ -14,7 +14,7 @@ from flask import current_app, jsonify, request
from app import db
from app.core.errors import AppError, ConflictError, ForbiddenError, UnauthorizedError, ValidationError
from app.services.wecom_crypto import decrypt_wecom_aes, extract_encrypt_field
from app.services.integrations.wecom.crypto import decrypt_wecom_aes, extract_encrypt_field
from . import auth as _compat
from .auth import auth_bp
+3 -3
View File
@@ -13,7 +13,7 @@ from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaul
from app.services.feedback_notify import send_feedback_group_notification
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
from app.services.agent_registry.serialization import serialize_registry_fields
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
from app.services.integrations.wecom.notify import mark_wecom_message_opened, send_wecom_event_message
import re
import ast
from app.core.errors import (
@@ -108,7 +108,7 @@ def submit_leave_workflow():
if not form_data.get(key):
raise ValidationError(f'{label}不能为空。')
try:
from app.services.oa_leave_workflow import OALeaveWorkflowService, OALeaveWorkflowError
from app.services.integrations.oa.leave_workflow import OALeaveWorkflowService, OALeaveWorkflowError
result = OALeaveWorkflowService.submit_leave_request(form_data, user)
except OALeaveWorkflowError as exc:
current_app.logger.warning('[oa-leave] submit failed user_id=%s employee_id=%s err=%s', getattr(user, 'id', None), form_data.get('employeeId'), exc)
@@ -358,7 +358,7 @@ def get_agent_details(id):
dify_parameters = None
if resolve_runtime_provider(agent) in {'dify', 'hybrid'} and getattr(agent, 'dify_api_key', None):
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
try:
params = DifyService.get_app_parameters(agent)
+120 -4
View File
@@ -154,6 +154,21 @@ def _require_formal_notice(task: Any) -> ShippingNotice:
return task
def _require_editable_task(task: Any) -> Any:
"""订单编辑写接口的实体守卫:正式 Notice 或建单前 OT 均可。
核心逻辑:订单字段/行的编辑权限由服务层状态制闸门裁决
(Excel ready 硬冻结 + 活动 Attempt 忙碌锁 + Schema 反向锁),
与实体类型无关——通知准备阶段(Notice 未建)编辑履约字段是受支持场景。
"""
if not isinstance(task, (ShippingNotice, ShippingOrderTask)):
raise ValidationError(
'Formal shipping notice is required for this operation',
code='SHIPPING.FORMAL_NOTICE_REQUIRED',
)
return task
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
def workspace_shipping_tasks():
"""分页列出当前用户可见的发货任务,可按处理状态过滤。"""
@@ -199,6 +214,7 @@ def workspace_shipping_my_todos():
todo_category=str(request.args.get('todo_category') or '').strip() or None,
customer=str(request.args.get('customer') or '').strip() or None,
task_no=str(request.args.get('task_no') or '').strip() or None,
terminal_kind=str(request.args.get('terminal_kind') or '').strip() or None,
))
@@ -212,6 +228,67 @@ def workspace_shipping_my_todos_count():
return _ok(count_my_todos(user.id, is_admin=is_admin))
def _done_lines_report_params() -> dict[str, Any]:
"""解析明细报表共用筛选参数(客户/料号/发货通知日期范围),供查询与导出复用。"""
return {
'customer': str(request.args.get('customer') or '').strip() or None,
'part_number': str(request.args.get('part_number') or '').strip() or None,
'notice_date_from': str(request.args.get('notice_date_from') or '').strip() or None,
'notice_date_to': str(request.args.get('notice_date_to') or '').strip() or None,
}
@workspace_shipping_notice_bp.route('/shipping-tasks/my-todos/done-lines', methods=['GET'])
def workspace_shipping_done_lines():
"""
分页列出已完成(已核验上传成功)通知的平铺明细行,供「通知完成」子视图报表。
核心逻辑:明细行跨 Notice 混排、不按 OT 聚合;支持 客户 / 料号 /
发货通知日期范围 筛选;行结构为标准 12 字段 + 溯源编号(task_no/business_no)。
"""
user = _require_user()
from app.services.shipping_notice.done_line_report import list_done_notice_lines
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
try:
page = int(request.args.get('page') or 1)
page_size = int(request.args.get('page_size') or 20)
except (TypeError, ValueError) as exc:
raise ValidationError('page and page_size must be integers') from exc
return _ok(list_done_notice_lines(
user.id,
is_admin=is_admin,
page=page,
page_size=page_size,
**_done_lines_report_params(),
))
@workspace_shipping_notice_bp.route('/shipping-tasks/my-todos/done-lines/export', methods=['GET'])
def workspace_shipping_done_lines_export():
"""
导出当前筛选下的已完成通知明细 Excel。
核心逻辑:固定 12 列标准格式(客户/客户编号/订单日期/订单项次/料号/数量/
约定出货日期/客户PO/已用数量/open qty/订单单号/单价),OT 编号不落列;
已用数量 / open qty 无数据源留空。
"""
user = _require_user()
from app.services.shipping_notice.done_line_report import build_done_lines_xlsx
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
stream, filename = build_done_lines_xlsx(
user.id,
is_admin=is_admin,
**_done_lines_report_params(),
)
response = send_file(
stream, as_attachment=True, download_name=filename, mimetype=EXPORT_MIME_TYPE,
)
response.call_on_close(stream.close)
return response
def _batch_task_nos(data: dict) -> list[str]:
"""校验批量任务号,统一限制 100 条并去重,避免前端循环绕过服务端门禁。"""
raw_task_nos = data.get('task_nos')
@@ -481,6 +558,45 @@ def workspace_shipping_task_detail(task_no: str):
))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/odm-options', methods=['GET'])
def workspace_shipping_task_odm_options(task_no: str):
"""返回整单 ODM ID 候选与当前选择(工作台整单裁决路径,只读)。"""
user = _require_user()
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
from app.services.shipping_notice.notice_odm_choice_service import notice_odm_options
from app.services.shipping_notice.query_service import get_task_visible_to_user
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
if not task:
raise NotFoundError('Not found')
return _ok(notice_odm_options(task))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/odm-choice', methods=['POST'])
def workspace_set_shipping_task_odm_choice(task_no: str):
"""保存整单 ODM ID 用户选择;重复提交覆盖旧选择,成功后前端可重试生成 Excel。"""
user = _require_user()
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
from app.services.shipping_notice.notice_odm_choice_service import set_notice_odm_choice
from app.services.shipping_notice.query_service import get_task_visible_to_user
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
if not task:
raise NotFoundError('Not found')
data = request.get_json(silent=True) or {}
try:
snapshot_line_id = int(data.get('snapshot_line_id') or 0)
except (TypeError, ValueError):
snapshot_line_id = 0
result = set_notice_odm_choice(
task,
snapshot_line_id=snapshot_line_id,
odm_id=str(data.get('odm_id') or ''),
)
db.session.commit()
return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/audit-timeline', methods=['GET'])
def workspace_list_shipping_task_audit_timeline(task_no: str):
"""业务用户 Task 审计时间线(统一 ShippingAuditEvent,无敏感快照)。"""
@@ -559,7 +675,7 @@ def workspace_update_shipping_notice_fields(task_no: str):
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
task = _require_formal_notice(task)
task = _require_editable_task(task)
data = request.get_json(silent=True) or {}
fields = data.get('fields')
if not isinstance(fields, dict) or not fields:
@@ -606,7 +722,7 @@ def workspace_update_shipping_notice_line(task_no: str):
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
task = _require_formal_notice(task)
task = _require_editable_task(task)
data = request.get_json(silent=True) or {}
try:
line_index = int(data.get('line_index'))
@@ -695,7 +811,7 @@ def workspace_add_shipping_notice_line(task_no: str):
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
task = _require_formal_notice(task)
task = _require_editable_task(task)
data = request.get_json(silent=True) or {}
line = data.get('line')
if not isinstance(line, dict) or not line:
@@ -721,7 +837,7 @@ def workspace_remove_shipping_notice_line(task_no: str):
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
task = _require_formal_notice(task)
task = _require_editable_task(task)
data = request.get_json(silent=True) or {}
try:
line_index = int(data.get('line_index'))
+115 -13
View File
@@ -1,9 +1,10 @@
"""
backend/app/api/workspace/voucher_check.py
用途:工作台立账凭证检核查询与强制重检 API(任务列表 / 批次明细 / 企微发送记录)。
依赖:auth.jwt、response_utils envelope、voucher_check.query_service。
逻辑:对话与检核任务页共用;GET notifications 为企微发送记录;POST runs 仅 admin,以 force_all 入队周批排程。
用途:立账凭证检核查询、强制重检与通知配置 API(任务列表 / 最近一次检核 / 批次明细 / 企微发送记录 / 按类型接收人)。
依赖:auth.jwt、response_utils envelope、Agent 授权、voucher_check.query_service、notify_config_service。
逻辑:Chat Agent 与旧工作台查询共用;GET runs/latest 不跟筛选;GET notifications 为企微发送记录;
查询要求平台 admin 或持有 `agent_code=voucher_check` 的 Agent 授权;POST runs 与通知配置仅 admin。
"""
from __future__ import annotations
@@ -13,23 +14,88 @@ from flask import Blueprint, request
from app.core.auth.jwt import get_current_user
from app.core.errors import ForbiddenError, UnauthorizedError, ValidationError
from app.core.response import ok
from app.services.voucher_check import query_service
from app.models import Agent
from app.services.voucher_check import notify_config_service, query_service
workspace_voucher_check_bp = Blueprint("workspace_voucher_check", __name__)
VOUCHER_CHECK_AGENT_CODE = "voucher_check"
def _require_user():
"""
返回当前登录用户。
Returns:
已认证用户。
Raises:
UnauthorizedError: 请求没有有效登录身份。
"""
user = get_current_user()
if not user:
raise UnauthorizedError()
return user
def _require_admin():
"""工作台强制重检仅管理员可触发,鉴权方式与本蓝图 GET 一致。"""
def _user_has_voucher_check_agent(user) -> bool:
"""
判断用户是否持有启用中的立账凭证检核 Agent。
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions;admin 不走此判断。
Args:
user: 已认证用户。
Returns:
已绑定启用中的 voucher_check Agent 时为 True。
"""
agent = Agent.query.filter_by(agent_code=VOUCHER_CHECK_AGENT_CODE, is_active=True).first()
return bool(agent is not None and agent in user.agents)
def _require_voucher_check_access():
"""
确保当前用户已登录且具备立账凭证检核访问权限。
核心逻辑:平台 admin 放行;普通用户必须被授予启用中的 `agent_code=voucher_check` Agent。
无权限时返回业务 403,而不是静默空数据。
Returns:
已认证且具备立账凭证 Agent 授权(或 admin)的用户。
Raises:
UnauthorizedError: 请求没有有效登录身份。
ForbiddenError: 已登录但没有立账凭证 Agent 授权。
"""
user = _require_user()
if getattr(user, "role", None) == "admin" or _user_has_voucher_check_agent(user):
return user
raise ForbiddenError(
"Voucher check agent permission required",
code="VOUCHER_CHECK.FORBIDDEN",
)
def _require_admin():
"""
确保当前用户既有立账凭证访问权,又是平台管理员。
核心逻辑:持有 Agent 的普通用户可查检核任务与发送记录;强制重检与通知配置仅 `role=admin`。
Returns:
已认证的管理员用户。
Raises:
UnauthorizedError: 请求没有有效登录身份。
ForbiddenError: 无立账凭证访问权,或已授权但不是管理员。
"""
user = _require_voucher_check_access()
if getattr(user, "role", None) != "admin":
raise ForbiddenError("Admin privilege required")
raise ForbiddenError(
"Admin privilege required for voucher check jobs",
code="VOUCHER_CHECK.ADMIN_REQUIRED",
)
return user
@@ -37,9 +103,9 @@ def _require_admin():
def workspace_voucher_runs():
"""
分页查看检核任务列表。
核心逻辑:委托 query_service.list_runs,按资料所属期间/业务方/状态筛选。
核心逻辑:委托 query_service.list_runs;period 为 YYYY 或 YYYY-MM,可再按业务方/状态筛选。
"""
_require_user()
_require_voucher_check_access()
data = query_service.list_runs(
period=request.args.get("period"),
profile_code=request.args.get("profile_code"),
@@ -69,13 +135,23 @@ def workspace_voucher_force_run():
return ok(data)
@workspace_voucher_check_bp.route("/accounting-voucher-check/runs/latest", methods=["GET"])
def workspace_voucher_latest_run():
"""
读取最近一次立账凭证检核批次(含排队/执行中)。
核心逻辑:委托 query_service.get_latest_run;不跟列表 period/status;无批次时 data 为 null。
"""
_require_voucher_check_access()
return ok(query_service.get_latest_run())
@workspace_voucher_check_bp.route("/accounting-voucher-check/runs/<int:run_id>/items", methods=["GET"])
def workspace_voucher_run_items(run_id: int):
"""
分页查看批次明细。
核心逻辑:委托 query_service.list_run_items,可按 result 过滤,并返回 by_file_type。
"""
_require_user()
_require_voucher_check_access()
data = query_service.list_run_items(
run_id=run_id,
result=request.args.get("result"),
@@ -88,10 +164,10 @@ def workspace_voucher_run_items(run_id: int):
@workspace_voucher_check_bp.route("/accounting-voucher-check/notifications", methods=["GET"])
def workspace_voucher_notifications():
"""
分页查看企微缺件汇总发送记录。
核心逻辑:委托 query_service.list_notifications,可按期间和发送状态筛选。
分页查看企微缺件通知发送记录。
核心逻辑:委托 query_service.list_notifications;period 为 YYYY 或 YYYY-MM,可再按发送状态筛选。
"""
_require_user()
_require_voucher_check_access()
data = query_service.list_notifications(
period=request.args.get("period"),
send_status=request.args.get("send_status"),
@@ -99,3 +175,29 @@ def workspace_voucher_notifications():
page_size=request.args.get("page_size", default=50, type=int) or 50,
)
return ok(data)
@workspace_voucher_check_bp.route("/accounting-voucher-check/notify-config", methods=["GET"])
def workspace_voucher_notify_config_get():
"""
读取按文件类型的企微接收人配置。
核心逻辑:仅 admin;规则来自销售 Profile,接收人来自独立配置表。
"""
_require_admin()
return ok(notify_config_service.get_notify_config(profile_code=request.args.get("profile_code")))
@workspace_voucher_check_bp.route("/accounting-voucher-check/notify-config", methods=["PUT"])
def workspace_voucher_notify_config_put():
"""
保存按文件类型的企微接收人。
核心逻辑:仅 admin;未知规则码丢弃;未绑企微的人可保存但发送时跳过。
"""
user = _require_admin()
payload = request.get_json(silent=True) or {}
data = notify_config_service.save_notify_config(
profile_code=payload.get("profile_code") or request.args.get("profile_code"),
recipients=payload.get("recipients"),
updated_by=getattr(user, "id", None),
)
return ok(data)
-10
View File
@@ -1,10 +0,0 @@
"""
backend/app/api/workspace_schedule.py
用途:工作台排程 API 兼容 shim(Wave 1 迁包)。
依赖:app.api.workspace.schedule。
逻辑:旧 import 路径仍可用;新代码请用 app.api.workspace。
"""
from app.api.workspace.schedule import workspace_schedule_bp
__all__ = ['workspace_schedule_bp']
@@ -1,10 +0,0 @@
"""
backend/app/api/workspace_shipping_notice.py
用途:工作台发货通知 API 兼容 shim(Wave 1 迁包)。
依赖:app.api.workspace.shipping_notice。
逻辑:旧 import 路径继续 re-export `workspace_shipping_notice_bp`;真实实现统一维护在 workspace 子包中,避免双份路由漂移。
"""
from app.api.workspace.shipping_notice import workspace_shipping_notice_bp
__all__ = ['workspace_shipping_notice_bp']
+90 -133
View File
@@ -8,7 +8,6 @@ backend/app/core/config/settings.py
旧路径 app.config 为兼容 shim。
"""
import os
import warnings
from pathlib import Path
from dotenv import dotenv_values
@@ -16,18 +15,6 @@ from dotenv import dotenv_values
_BACKEND_DIR = Path(__file__).resolve().parents[3]
_ROOT_DIR = _BACKEND_DIR.parent
_WARNED_LEGACY_RPA_ENV: set[str] = set()
_RPA_LEGACY_TO_CANONICAL = {
'SHIPPING_RPA_CREDENTIAL_KEY': 'SHIPPING_NOTICE_RPA_CREDENTIAL_KEY',
'FREIGHT_INVENTORY_DROP_DIR': 'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR',
'FREIGHT_RPA_INVENTORY_TRIGGER_DIR': 'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR',
'FREIGHT_UPLOAD_QUEUE_DIR': 'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR',
'FREIGHT_RPA_UPLOAD_TRIGGER_DIR': 'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR',
'FREIGHT_RPA_BROWSER_PROFILE_DIR': 'SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR',
'FREIGHT_RPA_INVENTORY_ARCHIVE_DIR': 'SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR',
'FREIGHT_RPA_MOCK': 'SHIPPING_NOTICE_RPA_WORKER_MOCK',
}
def _normalize_env_name(raw: str | None) -> str:
@@ -90,47 +77,15 @@ def _backend_path(env_key: str, *parts: str) -> str:
return resolve_backend_relative_path(os.getenv(env_key), default)
def _rpa_env(canonical_name: str, default: str | None = None) -> str | None:
def _rpa_data_path(env_key: str, *parts: str) -> str:
"""
读取 Shipping Notice RPA 配置,并在迁移期兼容历史环境变量名。
解析 RPA 数据目录环境变量,未配置时回落到 `backend/data` 默认路径。
核心逻辑:优先读取 `SHIPPING_NOTICE_RPA_*`;仅在新变量缺失时读取映射的
历史变量,并按进程对每个旧名称最多发出一次弃用警告。
核心逻辑:直接读取规范环境变量名(FREIGHT_RPA_*);历史
SHIPPING_NOTICE_RPA_* 前缀已于 2026-09-18 废弃,不提供别名兼容。
Args:
canonical_name: 统一后的规范环境变量名。
default: 新旧变量均未设置时返回的默认值。
Returns:
str | None: 环境变量值或默认值。
"""
value = os.getenv(canonical_name)
if value is not None:
return value
legacy_name = next(
(legacy for legacy, canonical in _RPA_LEGACY_TO_CANONICAL.items() if canonical == canonical_name),
None,
)
if legacy_name:
value = os.getenv(legacy_name)
if value is not None:
if legacy_name not in _WARNED_LEGACY_RPA_ENV:
warnings.warn(
f'{legacy_name} is deprecated; use {canonical_name}',
DeprecationWarning,
stacklevel=2,
)
_WARNED_LEGACY_RPA_ENV.add(legacy_name)
return value
return default
def _rpa_data_path(canonical_name: str, *parts: str) -> str:
"""
解析 RPA 数据目录,并兼容历史环境变量名称。
Args:
canonical_name: 统一后的 RPA 目录环境变量名。
env_key: 规范 RPA 目录环境变量名。
*parts: 未配置时相对 `backend/data` 的默认路径片段。
Returns:
@@ -139,7 +94,7 @@ def _rpa_data_path(canonical_name: str, *parts: str) -> str:
from app.path_utils import resolve_backend_relative_path
default = _BACKEND_DIR.joinpath('data', *parts)
return resolve_backend_relative_path(_rpa_env(canonical_name), default)
return resolve_backend_relative_path(os.getenv(env_key), default)
class Config:
@@ -300,6 +255,8 @@ class Config:
INTEGRATION_API_MODE = os.getenv('INTEGRATION_API_MODE', 'local').strip().lower()
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
# 集成连接器凭据密文的 Fernet 主密钥;只允许由环境变量提供,禁止持久化到数据库。
INTEGRATION_CREDENTIAL_KEY = os.getenv('INTEGRATION_CREDENTIAL_KEY')
# HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 服务端调用;无尾斜杠,常为内网 IP)
HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOLS_API_BASE')
@@ -310,9 +267,7 @@ class Config:
# 货代发货通知 Agent Tool API
SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY')
# RPA Profile 凭据字段的 Fernet 主密钥;只允许由环境变量提供,禁止持久化到数据库。
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY = _rpa_env('SHIPPING_NOTICE_RPA_CREDENTIAL_KEY')
# 兼容仍从 Flask config 读取旧属性的扩展;新代码禁止继续使用该属性。
SHIPPING_RPA_CREDENTIAL_KEY = SHIPPING_NOTICE_RPA_CREDENTIAL_KEY
FREIGHT_RPA_CREDENTIAL_KEY = os.getenv('FREIGHT_RPA_CREDENTIAL_KEY')
# 文件检核 Chatflow Tool API
FILE_CHECK_TOOL_API_KEY = os.getenv('FILE_CHECK_TOOL_API_KEY')
@@ -329,27 +284,14 @@ class Config:
SHIPPING_NOTICE_TASK_EXECUTION_MODE = os.getenv('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker').strip().lower()
SHIPPING_NOTICE_WORKER_POLL_SECONDS = float(os.getenv('SHIPPING_NOTICE_WORKER_POLL_SECONDS', '2'))
SHIPPING_NOTICE_WORKER_CONCURRENCY = int(os.getenv('SHIPPING_NOTICE_WORKER_CONCURRENCY', '2'))
# 在途仓自动调拨(独立业务模块)参数;ERP 凭据仅由环境/Secret 注入,未配置时 fail-closed。
# 在途仓自动调拨(独立业务模块)参数;外部系统端点/凭据由集成连接器客户端实例管理。
IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY', '2'))
IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY', '2'))
IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY = int(os.getenv('IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY', '1'))
IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS = int(
os.getenv('IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS', '60') or '60'
)
IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS = int(
os.getenv('IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS', '60') or '60'
)
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS = int(
os.getenv('IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS', '600') or '600'
)
IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS', '3') or '3')
IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS', '5') or '5')
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS', '7') or '7')
# ERP SOAP:WSDL/endpoint 冻结前保持空(SoapErpTransport fail-closed)。
IN_TRANSIT_TRANSFER_ERP_ENDPOINT = os.getenv('IN_TRANSIT_TRANSFER_ERP_ENDPOINT', '').strip()
IN_TRANSIT_TRANSFER_ERP_USERNAME = os.getenv('IN_TRANSIT_TRANSFER_ERP_USERNAME', '').strip()
IN_TRANSIT_TRANSFER_ERP_PASSWORD = os.getenv('IN_TRANSIT_TRANSFER_ERP_PASSWORD', '').strip()
IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG = os.getenv('IN_TRANSIT_TRANSFER_ERP_DEFAULT_ORG', '').strip()
IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET = os.getenv('IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET', 'hxops-transfer').strip()
SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float(
os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '420')
@@ -425,46 +367,46 @@ class Config:
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '900'
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS = int(
os.getenv('FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS') or '900'
)
SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS') or '900'
FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS = int(
os.getenv('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS') or '900'
)
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90'
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int(
os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90'
)
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED', 'true').lower() == 'true'
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED = (
os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS', '').strip().lower()
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = (
os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS', '').strip().lower()
in {'1', 'true', 'yes', 'on'}
if os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS')
if os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS')
else _normalize_env_name(os.getenv('ENV_NAME')) in {'test', 'prod'}
)
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK', 'false').lower() == 'true'
FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = (
os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK', 'false').lower() == 'true'
)
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID = os.getenv('SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID', '').strip()
SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME = (
os.getenv('SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME', '.hxops_rpa_shared_mount').strip()
FREIGHT_RPA_SHARED_SCOPE_ID = os.getenv('FREIGHT_RPA_SHARED_SCOPE_ID', '').strip()
FREIGHT_RPA_SHARED_SENTINEL_NAME = (
os.getenv('FREIGHT_RPA_SHARED_SENTINEL_NAME', '.hxops_rpa_shared_mount').strip()
or '.hxops_rpa_shared_mount'
)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED', 'false').lower() == 'true'
FREIGHT_RPA_WORKER_ALERT_ENABLED = (
os.getenv('FREIGHT_RPA_WORKER_ALERT_ENABLED', 'false').lower() == 'true'
)
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS') or '1800'
FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS = int(
os.getenv('FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS') or '1800'
)
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES = os.getenv(
'SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES', ''
FREIGHT_RPA_WORKER_ALERT_USERNAMES = os.getenv(
'FREIGHT_RPA_WORKER_ALERT_USERNAMES', ''
).strip()
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN', 'true').lower() == 'true'
FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN = (
os.getenv('FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN', 'true').lower() == 'true'
)
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS') or '120'
FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS = int(
os.getenv('FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS') or '120'
)
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM = os.getenv('SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM', 'false').lower() == 'true'
SHIPPING_NOTICE_AUTO_MATCH_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_MATCH_ENABLED', 'true').lower() == 'true'
@@ -481,9 +423,9 @@ class Config:
)
# Hxops 工作台 / 聊天按钮兜底串联(Dify 主路径走 auto_progress;画布 HTTP 不传 auto_chain_fallback)
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK = os.getenv('SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK', 'true').lower() == 'true'
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS') or '3')
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS') or '30'
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS') or '3')
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS = int(
os.getenv('FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS') or '30'
)
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS = int(
os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000'
@@ -496,39 +438,32 @@ class Config:
)
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR', 'shipping_notice', 'freight_rpa', 'inventory_drop'
# RPA 运行期数据目录统一为 `freight_rpa/{inventory,receipt,common}` 三层布局(与 env/ps1 三侧一致)。
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR', 'freight_rpa', 'inventory', 'drop'
)
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR', 'shipping_notice', 'freight_rpa', 'inventory_triggers'
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR', 'freight_rpa', 'inventory', 'triggers'
)
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR', 'shipping_notice', 'freight_receipt_rpa', 'receipt_drop'
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR', 'freight_rpa', 'receipt', 'drop'
)
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR', 'shipping_notice', 'freight_receipt_rpa', 'receipt_triggers'
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', 'freight_rpa', 'receipt', 'triggers'
)
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR', 'shipping_notice', 'freight_rpa', 'upload_queue'
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR', 'freight_rpa', 'inventory', 'upload_queue'
)
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR', 'shipping_notice', 'freight_rpa', 'upload_triggers'
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR', 'freight_rpa', 'inventory', 'upload_triggers'
)
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR', 'shipping_notice', 'freight_rpa', 'browser_profile'
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = _rpa_data_path(
'FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR', 'freight_rpa', 'common', 'browser_profile'
)
SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR', 'shipping_notice', 'freight_rpa', 'inventory_archives'
FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = _rpa_data_path(
'FREIGHT_RPA_INVENTORY_ARCHIVE_DIR', 'freight_rpa', 'inventory', 'archives'
)
SHIPPING_NOTICE_RPA_WORKER_MOCK = _rpa_env('SHIPPING_NOTICE_RPA_WORKER_MOCK', 'false')
# 旧 Flask config 属性仅用于过渡期测试和外部扩展兼容。
FREIGHT_INVENTORY_DROP_DIR = SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR
FREIGHT_RPA_INVENTORY_TRIGGER_DIR = SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR
FREIGHT_UPLOAD_QUEUE_DIR = SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR
FREIGHT_RPA_UPLOAD_TRIGGER_DIR = SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR
FREIGHT_RPA_BROWSER_PROFILE_DIR = SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR
FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR
FREIGHT_RPA_MOCK = SHIPPING_NOTICE_RPA_WORKER_MOCK
FREIGHT_RPA_WORKER_MOCK = os.getenv('FREIGHT_RPA_WORKER_MOCK', 'false')
# WeCom (企业微信) 登录配置
WECOM_ENABLED = os.getenv('WECOM_ENABLED', 'false').lower() == 'true'
@@ -552,11 +487,13 @@ class Config:
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
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')
# 精益培训企微提醒卡片跳转的员工培训聊天页 agent id(前端路由 /chat/<id>,默认 27=员工培训)。
# 注意:默认值必须指向 content_profile=training 的培训 agent;历史默认 16 实为「通用入口」,
# 会导致卡片落地非培训 agent、前端精益页签深链不消费([FIX] 2026-09-11)。
WECOM_LEAN_TRAINING_JUMP_AGENT_ID = int(os.getenv('WECOM_LEAN_TRAINING_JUMP_AGENT_ID', '27'))
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,training_lean_video_push,training_overseas_thailand_guidelines')
# 精益培训企微提醒卡片跳转的员工培训聊天页 agent id(前端路由 /chat/<id>)。
# 缺省 0 = 不显式指定,由后端按 handler_config.content_profile='training' 动态解析各环境的培训 Agent
# (测试/正式环境 Agent ID 不同,动态解析保证卡片均可定位「员工培训-精益管理」);
# 仅当某环境需要固定指向特定 Agent 时才配置此项。历史默认 27 曾在部分环境错指「通用入口」导致深链失效
# ([FIX] 2026-09-18 改为动态解析,27 仅保留为解析失败时的兼容兜底)。
WECOM_LEAN_TRAINING_JUMP_AGENT_ID = int(os.getenv('WECOM_LEAN_TRAINING_JUMP_AGENT_ID', '0'))
WECOM_FEEDBACK_NOTIFY_ENABLED = os.getenv('WECOM_FEEDBACK_NOTIFY_ENABLED', 'true').lower() == 'true'
WECOM_FEEDBACK_NOTIFY_BASE_URL = os.getenv('WECOM_FEEDBACK_NOTIFY_BASE_URL')
WECOM_FEEDBACK_BOT_WEBHOOK = os.getenv('WECOM_FEEDBACK_BOT_WEBHOOK')
@@ -677,6 +614,24 @@ class Config:
VOUCHER_CHECK_DMS_LIBRARY_ID = os.getenv('VOUCHER_CHECK_DMS_LIBRARY_ID', '').strip()
VOUCHER_CHECK_DMS_ROOT_FOLDER_ID = os.getenv('VOUCHER_CHECK_DMS_ROOT_FOLDER_ID', '').strip()
# 立账凭证销货放行单:E10 OpenAPI + ecology10(密码仅 env;DATABASE 禁止回退 E9 ecology)
OA_E10_OPENAPI_BASE_URL = os.getenv('OA_E10_OPENAPI_BASE_URL', '').strip().rstrip('/')
OA_E10_CORPID = os.getenv('OA_E10_CORPID', '').strip()
OA_E10_APP_KEY = os.getenv('OA_E10_APP_KEY', '').strip()
OA_E10_APP_SECRET = os.getenv('OA_E10_APP_SECRET', '')
OA_E10_USERID = os.getenv('OA_E10_USERID', '').strip()
OA_E10_TIMEOUT_SECONDS = int(os.getenv('OA_E10_TIMEOUT_SECONDS', '30') or '30')
OA_E10_TOKEN_REFRESH_SKEW_SECONDS = int(os.getenv('OA_E10_TOKEN_REFRESH_SKEW_SECONDS', '300') or '300')
OA_E10_SQLSERVER_HOST = os.getenv('OA_E10_SQLSERVER_HOST', '').strip()
OA_E10_SQLSERVER_PORT = os.getenv('OA_E10_SQLSERVER_PORT', '').strip()
OA_E10_SQLSERVER_DATABASE = os.getenv('OA_E10_SQLSERVER_DATABASE', 'ecology10').strip() or 'ecology10'
OA_E10_SQLSERVER_USERNAME = os.getenv('OA_E10_SQLSERVER_USERNAME', '').strip()
OA_E10_SQLSERVER_PASSWORD = os.getenv('OA_E10_SQLSERVER_PASSWORD', '')
OA_E10_SQLSERVER_DRIVER = os.getenv('OA_E10_SQLSERVER_DRIVER', '').strip()
OA_E10_SQLSERVER_ENCRYPT = os.getenv('OA_E10_SQLSERVER_ENCRYPT', '').strip()
OA_E10_SQLSERVER_TRUST_CERT = os.getenv('OA_E10_SQLSERVER_TRUST_CERT', '').strip()
OA_E10_SQLSERVER_TIMEOUT = os.getenv('OA_E10_SQLSERVER_TIMEOUT', '').strip()
# MinIO 配置
MINIO_ENDPOINT = os.getenv('MINIO_ENDPOINT', '127.0.0.1:9000')
MINIO_ACCESS_KEY = os.getenv('MINIO_ACCESS_KEY', 'minioadmin')
@@ -693,7 +648,9 @@ class Config:
SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', '300')
)
# 订单抽取发送后选择计划预算:首轮只挑最相关附件,后续批次按固定预算待扩展。
# 订单抽取发送后选择计划预算:合格附件全量入选批次 1,有多少单解析多少单;
# 唯一生效的选择预算是 MAX_TOTAL_BYTES(超限转 Review)。数量类字段仅作快照
# 审计记录,不再截断;总量由 EML 层(每封 20)与单次上传 intake 数兜底。
SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_ATTACHMENTS = int(
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_INITIAL_ATTACHMENTS', '2')
)
@@ -704,7 +661,7 @@ class Config:
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_EXPANSION_BATCH_SIZE', '2')
)
SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_ATTACHMENTS = int(
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_ATTACHMENTS', '6')
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_TOTAL_ATTACHMENTS', '20')
)
SHIPPING_NOTICE_PARSER_VERSION = os.getenv('SHIPPING_NOTICE_PARSER_VERSION', 'v6')
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED = os.getenv(
@@ -787,8 +744,8 @@ class DevelopmentConfig(Config):
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
ORDER_DOCUMENT_PROFILE_PREVIEW_ALLOW_MEMORY_FALLBACK = True
# 本机常无 Redis:不强制 Redis,允许进程内存兜底心跳(单进程 run.py 可用)
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
# XFA 拆分确认 JTI:仅单进程 development 允许内存消费;test/prod 多 Worker 必须 Redis
XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI = True
@@ -808,8 +765,8 @@ class TestingConfig(Config):
FIXED_ASSETS_SYNC_ENABLED = False
FIXED_ASSETS_EXPORT_TO_DOCS = False
ENV_NAME = 'dev'
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
# pytest 单进程:允许内存 JTI;生产语义由 ProductionConfig 关闭
XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI = True
+64
View File
@@ -0,0 +1,64 @@
"""app/core/credential_crypto.py
用途:通用 Fernet 凭据加解密(主密钥只来自 Flask config 的环境注入键,绝不落库明文)。
依赖:cryptography.fernet、Flask current_app、app.core.errors。
逻辑:调用方通过 CredentialCryptoErrorCodes 提供各自的业务错误码;主密钥缺失/无效时
fail-closed 拒绝加密,避免产生不可恢复密文。shipping_notice(RPA Profile)与
integration_connector(凭据引用)共用本模块,仅密钥键名与错误码不同。
"""
from __future__ import annotations
from dataclasses import dataclass
from cryptography.fernet import Fernet, InvalidToken
from flask import current_app
from app.core.errors import ServiceUnavailableError, ValidationError
@dataclass(frozen=True)
class CredentialCryptoErrorCodes:
"""加解密失败的错误码集合(按调用方业务域自定义)。"""
key_missing: str
key_invalid: str
secret_empty: str
secret_missing: str
secret_invalid: str
def _fernet(key_config_name: str, codes: CredentialCryptoErrorCodes) -> Fernet:
"""从 Flask config 读取主密钥并构造加密器;缺失/无效即 fail-closed。"""
key = str(current_app.config.get(key_config_name) or '').strip()
if not key:
raise ServiceUnavailableError(
f'{key_config_name} is not configured',
code=codes.key_missing,
)
try:
return Fernet(key.encode('ascii'))
except (ValueError, UnicodeEncodeError) as exc:
raise ServiceUnavailableError(
f'{key_config_name} is invalid',
code=codes.key_invalid,
) from exc
def encrypt_secret(value: str, *, key_config_name: str, codes: CredentialCryptoErrorCodes) -> str:
"""加密单个凭据字段以便持久化;调用方不得记录明文。"""
plaintext = str(value or '')
if not plaintext:
raise ValidationError('credential must not be empty', code=codes.secret_empty)
return _fernet(key_config_name, codes).encrypt(plaintext.encode('utf-8')).decode('ascii')
def decrypt_secret(ciphertext: str, *, key_config_name: str, codes: CredentialCryptoErrorCodes) -> str:
"""在受控运行时解密密文;仅供当次调用内存使用,禁止落日志/响应。"""
value = str(ciphertext or '').strip()
if not value:
raise ValidationError('credential ciphertext is missing', code=codes.secret_missing)
try:
return _fernet(key_config_name, codes).decrypt(value.encode('ascii')).decode('utf-8')
except (InvalidToken, UnicodeDecodeError) as exc:
raise ValidationError('credential ciphertext is invalid', code=codes.secret_invalid) from exc
+51
View File
@@ -0,0 +1,51 @@
"""
backend/app/core/http_context.py
用途:把 Flask request 读取收口在 core,避免 services 直接依赖 flask.request。
依赖:flask.has_request_context / request(仅本模块)。
逻辑:API 与 service 需要 Host、Header、客户端 IP 时调用本模块;无请求上下文时返回空值。
"""
from __future__ import annotations
def has_http_request() -> bool:
"""
当前是否处于 HTTP 请求上下文。
返回:
有请求上下文时 True,Worker / CLI 时 False。
"""
from flask import has_request_context
return bool(has_request_context())
def header(name: str, default: str = "") -> str:
"""
读取请求头;无请求上下文时返回 default。
参数:
name: Header 名。
default: 缺省值。
"""
if not has_http_request():
return default
from flask import request
return str(request.headers.get(name) or default)
def host_url() -> str:
"""返回当前请求 host_url(无尾斜杠);无请求时返回空字符串。"""
if not has_http_request():
return ""
from flask import request
return str(request.host_url or "").rstrip("/")
def remote_addr() -> str:
"""返回 request.remote_addr;无请求时返回空字符串。"""
if not has_http_request():
return ""
from flask import request
return str(request.remote_addr or "").strip()
+31 -4
View File
@@ -2,17 +2,44 @@
backend/app/jobs/handlers/file_check_run.py
用途:文件检核异步执行 handler。
逻辑:Wave 4 替代 api/file_check_tools 内 threading.Thread。
依赖:schedule.scheduler_service.run_task_now、jobs.queue.finish_job。
逻辑:schedule worker 领取 FILE_CHECK_RUN 后,按 payload 中的 task_id / schedule_run_id 执行已创建的 ScheduleRun。
"""
from __future__ import annotations
from app import db
from app.jobs.context import JobContext
from app.jobs.queue import finish_job
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule.scheduler_service import run_task_now
@register_handler(JobType.FILE_CHECK_RUN)
def run_file_check(ctx: JobContext, payload: dict) -> None:
"""执行异步文件检核。"""
ctx.logger.info('file_check_run handler skeleton invoked payload=%s', payload)
raise NotImplementedError('file_check_run handler pending Wave 4')
"""
执行已入队的文件检核 ScheduleRun。
核心逻辑:读取 task/run → 调用 run_task_now(与原 API 后台线程同一入口)→ finish_job。
参数:
ctx: Worker 上下文。
payload: 必须包含 task_id 与 schedule_run_id;可选 job_id。
异常:
RuntimeError: payload 缺失或任务/运行记录不存在。
"""
task_id = int(payload.get("task_id") or 0)
run_id = int(payload.get("schedule_run_id") or 0)
job_id = int(payload.get("job_id") or 0)
if not task_id or not run_id:
raise RuntimeError("task_id and schedule_run_id are required")
task = db.session.get(ScheduleTask, task_id)
run = db.session.get(ScheduleRun, run_id)
if not task or not run:
raise RuntimeError(f"file-check task/run not found task_id={task_id} run_id={run_id}")
ctx.logger.info("file_check_run start job_id=%s task_id=%s run_id=%s", job_id, task_id, run_id)
run_task_now(task, trigger_type="dify_chatflow", triggered_by_user_id=None, run=run)
if job_id:
finish_job(job_id, result={"task_id": task_id, "schedule_run_id": run_id}, message="文件检核执行完成")
@@ -31,14 +31,15 @@ def run_in_transit_transfer_precheck(_ctx, payload: dict) -> None:
raise RuntimeError(f"missing_transfer_precheck: {precheck_no}")
deps = transfer_deps.get_transfer_dependencies()
source_codes = list(precheck.scope_json.get("source_codes") or []) if isinstance(
precheck.scope_json, dict
) else []
scope = precheck.scope_json if isinstance(precheck.scope_json, dict) else {}
source_codes = list(scope.get("source_codes") or [])
result = run_precheck(
source_codes=source_codes,
business_date=precheck.business_date,
deps=deps,
run_no=precheck.run.run_no if precheck.run else "RUN-PENDING",
# 类型范围随预检落库回读:异步重跑与创建时口径一致(缺省回落类型1)。
transfer_type=str(scope.get("transfer_type")) if scope.get("transfer_type") else None,
)
summary = result.summary
precheck.status = summary.status
@@ -50,6 +51,6 @@ def run_in_transit_transfer_precheck(_ctx, payload: dict) -> None:
"blocked_count": summary.counts.blocked_count,
}
precheck.estimated_transfer_quantity = summary.estimated_transfer_quantity
precheck.estimated_erp_write_count = summary.estimated_erp_write_count
precheck.estimated_external_write_count = summary.estimated_external_write_count
precheck.precheck_hash = summary.precheck_hash
db.session.commit()
@@ -4,10 +4,15 @@ backend/app/jobs/handlers/shipping_order_extraction.py
用途:消费订单抽取 Run,使用固定模板/通用确定性解析并持久化可复核结果。
依赖:Job queue、冻结 Run/Plan、确定性路由和解析、统一审计服务、版面排程、
ensure_workflow_items_for_run(物化后兜底建 Item)、order_extraction_merge、
order_supplement_merge(仅 eml)、order_extraction_ready_document_ids(Unit 级放行)。
order_supplement_merge(仅 eml)、order_extraction_ready_document_ids(Unit 级放行)、
order_extraction_has_extractable_ready_work(收口自交接判断)。
逻辑:物化附件与排版面 Job 均在主 try 内执行;有 ready PDF 即按 Unit 抽取并下游推进,
兄弟文件 layout pending 时 Job 以 partial_units_done 回到 waiting_layout;
收口时用 DB 实况判断:有 extractable ready work 则 layout_ready_continue 自交接;
仅 layouts_pending 且无 ready work 时以 partial_units_done 回到 waiting_layout;
运行时预算耗尽且仍有 pending Unit 时入队续抽,禁止终态 partially_completed;
两处续抽须同事务先 finish(commit=False) 再 enqueue(唯一索引含 running,
否则会撞 uq_jobs_shipping_order_extraction_active_ref);continue_from_running
仅对 queued 去重,避免复用已结束 Job;
每个 Unit 按 STP route_decision 直通或落 provisional;needs_review 剥离验收标记;
不调用 Dify 主链。阶段 2:direct_pdf 跳过 email_supplements 与 ORDER_EMAIL_ADJUDICATION_*;
合并默认 keep_primary_documents_separate(多 PDF 各成 Candidate)。
@@ -46,6 +51,7 @@ from app.services.shipping_notice.order_extraction_run_service import (
begin_input_freeze,
complete_input_freeze,
mark_order_extraction_persistence_started,
order_extraction_has_extractable_ready_work,
order_extraction_layout_prerequisite_issues,
order_extraction_layouts_pending,
order_extraction_ready_document_ids,
@@ -662,6 +668,74 @@ def _process_unit_with_retries(*, run, unit, job, owned_attempt: int) -> list[di
return None
def _handoff_continue_order_extraction(
*,
job: Job,
run: ShippingOrderProcessingRun,
owned_attempt: int,
result: dict[str, Any],
message: str,
enqueue_message: str,
phase: str,
) -> bool:
"""
同事务自交接:当前 running Job → success,再 INSERT 续抽 queued Job。
核心逻辑:finish_job(commit=False) 释放
uq_jobs_shipping_order_extraction_active_ref 槽位后,再
_enqueue_ready_order_extraction_job(continue_from_running=True);
写入 continue_job_id / Run.current_job_id 后一次 commit。
禁止先 enqueue 再 finish(running 仍占唯一索引会 UniqueViolation)。
Args:
job: 当前 running 的抽取 Job。
run: 对应 ProcessingRun。
owned_attempt: Worker 领取代次,传给 finish_job 围栏。
result: 写入旧 Job.result_json 的业务结果(本函数会补 continue_job_id)。
message: 旧 Job 收口说明。
enqueue_message: 新 Job 初始 message。
phase: 交接后 Run.phase(queued / waiting_layout)。
Returns:
True 表示已成功收口并入队;False 表示 finish 未生效(代次失效),调用方应停止。
"""
# [STEP 1] 先释放 active 唯一槽,勿在 running 时 INSERT 后继
if not finish_job(
job.id,
result=result,
message=message,
owned_attempt=owned_attempt,
commit=False,
):
return False
# [STEP 2] 同事务入队续抽;仅对 queued 去重,避免复用已 success 的本 Job
continue_job_id = _enqueue_ready_order_extraction_job(
run,
message=enqueue_message,
continue_from_running=True,
)
result['continue_job_id'] = int(continue_job_id)
run.current_job_id = int(continue_job_id)
run.phase = phase
finished = db.session.get(Job, int(job.id))
if finished is not None:
finished.result_json = dict(result)
db.session.commit()
return True
def _is_transient_lock_error(exc: BaseException) -> bool:
"""
判断异常是否为瞬时锁冲突(PostgreSQL 死锁 40P01 / 锁等待超时 55P03)。
【AI 触发时机】:订单抽取 Job 异常收口时决定是否标记可重试。此类错误重试即可恢复,
按终态失败收口会触发 run failed 并要求人工重新识别(2026-09-22 生产事故两次)。
SQLAlchemy 将 DBAPI 错误包装为 exc.orig;非 DBAPI 异常(无 pgcode)一律返回 False。
"""
orig = getattr(exc, 'orig', None)
return getattr(orig, 'pgcode', None) in {'40P01', '55P03'}
@register_handler(JobType.SHIPPING_ORDER_EXTRACTION)
def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
"""
@@ -855,15 +929,16 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
persisted_orders.extend(unit_orders_by_id[int(unit.id)])
wave_orders.extend(unit_orders_by_id[int(unit.id)])
# 重试路径:已 candidate_ready 的 Unit 仍须独立触发下游(幂等)。
try:
progress_ready_extraction_unit(
run=run, unit=unit, orders=unit_orders_by_id[int(unit.id)],
)
except Exception:
from flask import current_app
current_app.logger.exception(
'retry unit progress failed run=%s unit=%s', run.run_no, unit.id,
)
# [交接不变量] defer_stp_enqueue:开工快照仍有待排版附件(本 Job 必交接)时
# 推迟 STP 入队到 run 收口,确保 STP 只由最后一个抽取 Job 提交;否则本 Job
# 提交的 STP Job 会与续抽 Job 并发执行,双方以相反顺序抢 run/intake 行锁
# 形成结构性死锁(2026-09-22 SNER-20260922-6466EB53 生产事故)。
# 推送失败必须冒泡(与下方新单元推送同一规则):此处是这些 Unit 候选与
# 复核 Case 的唯一物化触发点,吞掉等于静默丢单。
progress_ready_extraction_unit(
run=run, unit=unit, orders=unit_orders_by_id[int(unit.id)],
defer_stp_enqueue=bool(pending_layout_ids),
)
continue
if unit.status == 'review_required':
continue
@@ -1133,9 +1208,11 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
apply_worker_cancellation_checkpoint(run=run)
db.session.commit()
continue
# [交接不变量] 同 replay 路径:本 Job 仍会交接时推迟 STP 入队到 run 收口。
try:
unit_persist = progress_ready_extraction_unit(
run=run, unit=unit, orders=merged_unit_orders,
defer_stp_enqueue=bool(pending_layout_ids),
)
record_unit_progress(
run=run,
@@ -1158,8 +1235,30 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
job_id=job.id,
)
raise
# [STEP] 仍有兄弟文件版式未完成:已抽 Unit 保留,Job 成功收口并回到 waiting_layout,禁止 Run 终态。
if layout_blocked_in_wave or order_extraction_layouts_pending(run):
# [STEP] 收口前用 DB 实况判断版面就绪:有可抽 ready work 则自交接续抽,
# 覆盖「Job 中途 layout 变 ready」与「开工快照过期跳过」;勿仅信 layout_blocked_in_wave。
has_ready_work = order_extraction_has_extractable_ready_work(run)
layouts_pending = order_extraction_layouts_pending(run)
if has_ready_work:
_handoff_continue_order_extraction(
job=job,
run=run,
owned_attempt=owned_attempt,
result={
'run_no': run.run_no,
'waiting_layout': bool(layouts_pending),
'waiting_continue': True,
'handoff_status': 'layout_ready_continue',
'merged_unit_count': len(pending_merge_unit_ids),
'ready_document_ids': sorted(ready_document_ids),
},
message='附件版面已就绪,已排队继续识别剩余附件',
enqueue_message='附件版面已就绪,继续识别剩余附件',
phase='waiting_layout' if layouts_pending else 'queued',
)
return
if layouts_pending:
# 仅仍有 layout pending、无可抽 ready work:回到 waiting_layout,靠 layout 完成回调唤醒。
run.phase = 'waiting_layout'
db.session.commit()
finish_job(
@@ -1196,14 +1295,10 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
job_id=job.id,
commit=False,
)
continue_job_id = _enqueue_ready_order_extraction_job(
run, message='运行时预算已用尽,继续识别剩余附件',
)
run.current_job_id = continue_job_id
run.phase = 'waiting_layout'
db.session.commit()
finish_job(
job.id,
_handoff_continue_order_extraction(
job=job,
run=run,
owned_attempt=owned_attempt,
result={
'run_no': run.run_no,
'budget_stopped': True,
@@ -1213,10 +1308,10 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
'pending_unit_count': sum(
1 for unit in units if str(unit.status or '') == 'pending'
),
'continue_job_id': int(continue_job_id),
},
message='运行时预算已用尽,已排队继续识别剩余附件',
owned_attempt=owned_attempt,
enqueue_message='运行时预算已用尽,继续识别剩余附件',
phase='waiting_layout',
)
return
orders = persisted_orders + merged_orders
@@ -1337,6 +1432,14 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
finish_job(job.id, result=summary, message='订单抽取完成', owned_attempt=owned_attempt)
except Exception as exc:
db.session.rollback()
# [STEP] 瞬时锁错(PostgreSQL 死锁 40P01 / 锁超时 55P03)不收口 run/unit 失败:
# 失败标记会写 run=failed,重试 Job 将被"run status is not executable"门弹掉。
# 直接可重试入队,由队列在 attempts 耗尽前自动重排;冲突窗口为秒级,重试即过
# (2026-09-22 SNER-20260922-6466EB53 / 879785D1 生产事故)。attempts 耗尽后
# 走下方常规失败收口,fail-closed 语义不变。
if _is_transient_lock_error(exc):
fail_job(job.id, error=str(exc), retryable=True, owned_attempt=owned_attempt)
return
run = ShippingOrderProcessingRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first()
retryable = False
if run is not None and run.status in {'queued', 'processing', 'failed'}:
@@ -2,17 +2,38 @@
backend/app/jobs/handlers/wecom_directory_sync.py
用途:企微通讯录同步 handler。
逻辑:Wave 4 包装 wecom_directory_sync 服务。
依赖:wecom_directory_sync.sync_wecom_userids_from_directory、jobs.queue.finish_job。
逻辑:schedule worker 领取后按 payload.apply / department_id 执行通讯录回填。
"""
from __future__ import annotations
from app.jobs.context import JobContext
from app.jobs.queue import finish_job
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.services.integrations.wecom.directory_sync import sync_wecom_userids_from_directory
@register_handler(JobType.WECOM_DIRECTORY_SYNC)
def run_wecom_directory_sync(ctx: JobContext, payload: dict) -> None:
"""同步企微通讯录到本地用户/部门。"""
ctx.logger.info('wecom_directory_sync handler skeleton invoked payload=%s', payload)
raise NotImplementedError('wecom_directory_sync handler pending Wave 4')
"""
从企微通讯录同步 users.wecom_userid。
核心逻辑:委托 sync_wecom_userids_from_directory;conflicts 时抛错由 Job 层标记失败。
参数:
ctx: Worker 上下文。
payload: apply(bool)、department_id(可选 int)、job_id(可选)。
"""
apply = bool(payload.get("apply"))
raw_dept = payload.get("department_id")
department_id = int(raw_dept) if raw_dept not in (None, "") else None
job_id = int(payload.get("job_id") or 0)
ctx.logger.info(
"wecom_directory_sync start job_id=%s apply=%s department_id=%s",
job_id,
apply,
department_id,
)
summary = sync_wecom_userids_from_directory(apply=apply, department_id=department_id)
if job_id:
finish_job(job_id, result=summary, message="企微通讯录同步完成")
+15 -1
View File
@@ -6,6 +6,7 @@ backend/app/jobs/queue.py
shipping_notice Intake 仅在预解析 Job 被 queued 同伴取代时同事务重指 parse_job_id。
逻辑:业务服务调用 enqueue 写入 jobs;旧 KB 清洗入口委托 legacy KbJob 队列;worker 调用 claim/finish/fail 完成执行闭环;
recover 使用 FOR UPDATE SKIP LOCKED + 条件 UPDATE;finish/fail 以 status/attempts 条件 UPDATE;
finish_job(commit=False) 可供与续抽 enqueue 同事务提交;
enqueue 仅在 SAVEPOINT 内 add+flush,唯一冲突回落已有 Job;
running→queued 若撞 shipping_notice_parse queued 唯一索引则标 cancelled;
替代 Job 须 FOR UPDATE;仅 queued 或已真正持有 Intake lease 的 running 可 supersede。
@@ -791,10 +792,22 @@ def finish_job(
result: dict[str, Any] | None = None,
message: str | None = None,
owned_attempt: int | None = None,
commit: bool = True,
) -> bool:
"""
条件收口为 success:仅当 Job 仍为 running(且可选 attempts 匹配)时生效。
核心逻辑:status/attempts 条件 UPDATE;commit=False 时不提交,供调用方与
续抽 enqueue 等同事务提交(避免 shipping_order_extraction 唯一索引仍被
本 Job running 占用时无法 INSERT 后继)。
Args:
job: Job 实例或主键。
result: 写入 result_json 的业务结果。
message: 收口说明。
owned_attempt: 非空时要求 Job.attempts 匹配,防止代次错收口。
commit: False 时仅执行 UPDATE,由调用方统一 commit。
Returns:
是否实际更新到一行(False 表示代次失效或已非 running,调用方应视为 no-op)。
"""
@@ -819,7 +832,8 @@ def finish_job(
)
)
rowcount = int(db.session.execute(stmt).rowcount or 0)
db.session.commit()
if commit:
db.session.commit()
cached = db.session.get(Job, job_id)
if cached is not None:
db.session.expire(cached)
+7
View File
@@ -149,6 +149,13 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
)
if job:
return _normalize_generic_job(job)
# file-check / 企微通讯录同步与排程共用 schedule worker,但 domain 不同
job = claim_next_job(
domain=None,
job_types=[JobType.FILE_CHECK_RUN, JobType.WECOM_DIRECTORY_SYNC],
)
if job:
return _normalize_generic_job(job)
return None
+1 -1
View File
@@ -81,7 +81,7 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress',
}),
'contract': frozenset({'procurement_contract_review', 'contract_payment_sync', 'contract_payment_alert', 'contract_payment_alert_weekly'}),
'schedule': frozenset({'schedule_run'}),
'schedule': frozenset({'schedule_run', 'file_check_run', 'wecom_directory_sync'}),
'transfer': frozenset({
'in_transit_transfer_precheck', 'in_transit_transfer_run', 'in_transit_transfer_item',
}),
+2
View File
@@ -221,6 +221,7 @@ from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgen
from app.models.voucher_check import (
VoucherCheckFileResult,
VoucherCheckNotification,
VoucherCheckNotifyConfig,
VoucherCheckProfile,
VoucherCheckRun,
VoucherCheckSubject,
@@ -413,6 +414,7 @@ __all__ = [
'VoucherCheckSubject',
'VoucherCheckFileResult',
'VoucherCheckNotification',
'VoucherCheckNotifyConfig',
'ContractPaymentContract',
'ContractPaymentAttachment',
'ContractPaymentNode',
+30 -7
View File
@@ -41,6 +41,11 @@ TRANSFER_RUN_STATUSES = (
'queued', 'preparing_files', 'prechecking', 'ready_to_execute', 'executing',
'success', 'partial_failed', 'failed', 'cancelled',
)
# 与 services/in_transit_transfer/transfer_type.py TransferType 保持一致的冻结枚举
# (数据库级兜底);一期仅 in_transit_to_hub 进入处理链路,其余为占位值。
TRANSFER_RUN_TYPES = (
'in_transit_to_hub', 'hub_repair_out', 'hub_to_hub',
)
TRANSFER_SOURCE_JOB_STATUSES = (
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
@@ -49,7 +54,7 @@ TRANSFER_PRECHECK_STATUSES = (
'file_pending', 'file_ready', 'prechecking', 'ready_to_execute', 'executing',
'success', 'failed', 'cancelled', 'expired',
)
TRANSFER_ATTEMPT_KINDS = ('precheck', 'rpa', 'erp_query', 'erp_write')
TRANSFER_ATTEMPT_KINDS = ('precheck', 'rpa', 'external_query', 'external_write')
TRANSFER_ATTEMPT_STATUSES = (
'queued', 'running', 'waiting_external', 'success', 'failed',
'result_unknown', 'superseded',
@@ -75,6 +80,10 @@ class TransferRun(Base):
"trigger_type IN ('manual', 'schedule')",
name='ck_transfer_runs_trigger_type',
),
CheckConstraint(
f"transfer_type IN ({', '.join(repr(t) for t in TRANSFER_RUN_TYPES)})",
name='ck_transfer_runs_transfer_type',
),
Index('ix_transfer_runs_status_created', 'status', 'created_at'),
Index('ix_transfer_runs_business_date', 'business_date'),
)
@@ -82,6 +91,10 @@ class TransferRun(Base):
id: Mapped[int] = mapped_column(primary_key=True)
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
trigger_type: Mapped[str] = mapped_column(String(16), nullable=False, default='manual', server_default='manual')
# 调拨业务类型(在途仓至HUB仓/HUB仓维修出/HUB仓间调拨);决定预检收料数据范围。
transfer_type: Mapped[str] = mapped_column(
String(32), nullable=False, default='in_transit_to_hub', server_default='in_transit_to_hub',
)
business_date: Mapped[str] = mapped_column(String(16), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
source_codes_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
@@ -167,7 +180,7 @@ class TransferPrecheck(Base):
strategy_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
counts_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
estimated_transfer_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
estimated_erp_write_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
estimated_external_write_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
precheck_hash: Mapped[str] = mapped_column(String(128), nullable=False)
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
@@ -184,18 +197,24 @@ class TransferPrecheck(Base):
class TransferInvoiceItem(Base):
"""预检明细项;同一预检内 Invoice 唯一,保留原始行追溯。"""
"""预检明细项;同一预检内 (来源,Invoice,料号,收料日期) 唯一,保留原始行追溯。
Invoice 锚定批号(2026-09-21 业务口径):同一批号跨料号/跨日期拆分为多行。
"""
__tablename__ = 'transfer_invoice_items'
__table_args__ = (
UniqueConstraint('precheck_id', 'invoice_no', name='uq_transfer_invoice_items_precheck_invoice'),
UniqueConstraint(
'precheck_id', 'source_code', 'invoice_no', 'material_no', 'receipt_date',
name='uq_transfer_invoice_items_precheck_grain',
),
CheckConstraint(
f"status IN ({', '.join(repr(s) for s in TRANSFER_ITEM_STATUSES)})",
name='ck_transfer_invoice_items_status',
),
Index('ix_transfer_invoice_items_source_invoice_status', 'source_code', 'invoice_no', 'status'),
Index('ix_transfer_invoice_items_run_id', 'run_id'),
Index('ix_transfer_invoice_items_erp_document_no', 'erp_document_no'),
Index('ix_transfer_invoice_items_external_document_no', 'external_document_no'),
)
id: Mapped[int] = mapped_column(primary_key=True)
@@ -203,6 +222,10 @@ class TransferInvoiceItem(Base):
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True)
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
invoice_no: Mapped[str] = mapped_column(String(64), nullable=False)
# 批号(External ASN 等)原值;「拨入批号」展示由 WTP→HOW 转换派生,不落库。
lot_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(拨出库位解析审计)。
receipt_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
material_no: Mapped[str] = mapped_column(String(64), nullable=False)
material_name: Mapped[str] = mapped_column(String(200), nullable=False, default='')
specification: Mapped[str] = mapped_column(String(200), nullable=False, default='')
@@ -211,11 +234,11 @@ class TransferInvoiceItem(Base):
to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
# 数量以 Decimal 文本保存,杜绝浮点误差;比较在服务层完成。
receipt_quantity: Mapped[str] = mapped_column(String(40), nullable=False)
erp_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
external_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False)
result_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
result_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
erp_document_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
external_document_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# 原始文件行追溯:Sheet + 行号 + 文件版本(决策 11)。
raw_lines_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
+10 -3
View File
@@ -22,6 +22,7 @@ from sqlalchemy import (
Integer,
JSON,
String,
Text,
UniqueConstraint,
text,
)
@@ -41,7 +42,7 @@ CONTEXT_SELECTOR_JSON = JSON().with_variant(JSONB(), 'postgresql')
class IntegrationCredentialReference(Base):
"""凭据引用:只存 secret_ref 键 + 元数据,真实凭据由 Secret 服务注入,绝不落库明文。"""
"""凭据引用:真实凭据加密落库(db 模式)或引用环境注入键(env 模式),绝不落库明文。"""
__tablename__ = 'integration_credential_references'
__table_args__ = (
@@ -55,6 +56,9 @@ class IntegrationCredentialReference(Base):
id: Mapped[int] = mapped_column(primary_key=True)
code: Mapped[str] = mapped_column(String(64), nullable=False)
secret_ref: Mapped[str] = mapped_column(String(128), nullable=False)
# db 模式:凭据 JSON(如 {"username","password"})的 Fernet 密文;主密钥由
# INTEGRATION_CREDENTIAL_KEY 环境注入。env 模式为空。绝不回显、绝不写日志。
secret_ciphertext: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
secret_provider: Mapped[str] = mapped_column(String(32), nullable=False, default='env', server_default='env')
credential_type: Mapped[str] = mapped_column(String(32), nullable=False, default='password', server_default='password')
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
@@ -159,9 +163,12 @@ class IntegrationBinding(Base):
id: Mapped[int] = mapped_column(primary_key=True)
capability: Mapped[str] = mapped_column(String(128), nullable=False)
# 路由条件(来源/组织/租户等键值对;空对象 = 默认绑定):须为调用 context 的子集才命中。
context_selector_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict)
# 最常用的 context 匹配键独立列(JSON 保留作兜底)。
context_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# 域参数 → 接口参数的声明式映射(map_response 规范:{接口参数: {expr/template/transform/args}});
# 空对象 = 域参数同名直通。结构属绑定(capability↔接口的翻译契约),不属接口定义。
# 与 context_selector_json 同用 JSONB variant(PostgreSQL)保持表内 JSON 列类型一致。
param_mapping_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict)
client_instance_code: Mapped[str] = mapped_column(
ForeignKey('integration_client_instances.code'), nullable=False,
)
+4 -1
View File
@@ -37,7 +37,8 @@ class ShippingCustomer(Base):
id: Mapped[int] = mapped_column(primary_key=True)
standard_name: Mapped[str] = mapped_column(String(200), nullable=False, index=True)
short_code: Mapped[str] = mapped_column(String(6), nullable=False, unique=True)
# 业务规则:客户简码允许重复(不同标准客户可共用同一简码,仅用作编号前缀),禁止再加唯一约束。
short_code: Mapped[str] = mapped_column(String(6), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active')
merged_into_customer_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_customers.id'),
@@ -45,6 +46,8 @@ class ShippingCustomer(Base):
index=True,
)
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
# 客户可用的 ODM ID 清单;为空表示不限定。生成发货 Excel 时用于收敛库存命中行。
odm_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
@@ -160,9 +160,13 @@ class ShippingInventorySourceParsingBindingAudit(Base):
class ShippingInventoryParsingProfile(Base):
"""可跨源复用的通用文件解析规则(库存/异动按 purpose 区分)。
注意:表名中的 inventory 是历史命名——本表实为"通用文件解析规则表",
用途以 purpose 字段为准,勿按表名推断只服务库存。
purpose='inventory':端点用 ShippingInventoryField 库存字段目录(既有语义);
purpose='movement':端点用定死领域字段(MOVEMENT_FIELDS,doc_no/line_no/.../movement_date),
供收料/异动文件映射,不依赖库存字段目录。校验逻辑按 purpose 分支。
绑定入口:库存站点 ShippingInventorySource.parsing_profile_id /
收料配置 ShippingReceiptReportConfig.parsing_profile_id(后者必须 purpose='movement')。
"""
__tablename__ = 'shipping_inventory_parsing_profiles'
@@ -358,7 +362,14 @@ class ShippingInventoryRoutingRuleVersion(Base):
class ShippingInventoryExternalMapping(Base):
"""货代库存身份到外部系统仓库的单向映射;不承载调拨规则。"""
"""库存源到外部系统仓库的映射。
freight_warehouse_id(货代仓库)为可选维度:inventory_match 源用它匹配收料文件
「仓库」列(空值即「空库位」默认映射行,下方两个部分唯一索引保证同源最多
一条启用的精确/默认映射);fixed 源仅一条启用映射直接取用。
in_transit_warehouse_code(在途仓编码)是在途调拨拨出库位的来源
(in_transit_transfer DefaultRouteResolver),保存端必填,库内空串仅为存量行兼容。
"""
__tablename__ = 'shipping_inventory_external_mappings'
__table_args__ = (
@@ -387,6 +398,8 @@ class ShippingInventoryExternalMapping(Base):
external_site_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
external_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False)
external_warehouse_name: Mapped[str] = mapped_column(String(128), nullable=False)
# 在途仓编码:在途调拨拨出库位来源(DefaultRouteResolver);保存端必填。
in_transit_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, server_default='', default='')
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
@@ -126,6 +126,8 @@ class ShippingNoticeLineInventoryMatch(Base):
onupdate=datetime.utcnow,
nullable=False,
)
# 整单 ODM ID 用户选择;写在当前匹配事实行上,随重匹配轮次自然失效。
chosen_odm_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# T6: 行级实际源证据(决策 E1 硬约束)——用于幂等保护与跨源匹配审计。
matched_file_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
matched_row_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
@@ -29,7 +29,7 @@ class ShippingReceiptReportConfig(Base):
inventory_source_id: Mapped[int] = mapped_column(
ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True,
)
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
# 收料不设独立启停:是否运行统一由库存站点 enabled 与本配置是否存在决定。
# 收料文件解析规则(purpose='movement');定死领域字段端点。空则无法解析收料文件。
parsing_profile_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True,
@@ -40,10 +40,7 @@ class ShippingReceiptReportConfig(Base):
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(
JSON, default=list, server_default=text("'[]'"), nullable=False,
)
# DBS 可包含多个 Warehouse;Crane 固定 Inbound Details,保留空数组。
warehouse_ids_json: Mapped[list[str]] = mapped_column(
JSON, default=list, server_default=text("'[]'"), nullable=False,
)
# 与库存同构:Warehouse 是查询条件之一(支持多值),逐仓拆分在排程/触发时由该条件运行时派生,不单独持久化仓库清单。
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
@@ -55,7 +52,10 @@ class ShippingReceiptReportConfig(Base):
class ShippingReceiptRpaUnitRun(Base):
"""一次收料排程内的站点或站点-Warehouse 不可重复执行单元。"""
"""一次收料执行的站点或站点-Warehouse 不可重复执行单元。
schedule_run_id 指向排程 run;调拨按需触发(重试/预检补抓)无排程,保持 NULL。
"""
__tablename__ = 'shipping_receipt_rpa_unit_runs'
__table_args__ = (
@@ -69,7 +69,7 @@ class ShippingReceiptRpaUnitRun(Base):
)
id: Mapped[int] = mapped_column(primary_key=True)
schedule_run_id: Mapped[int] = mapped_column(ForeignKey('schedule_runs.id'), nullable=False, index=True)
schedule_run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_runs.id'), nullable=True, index=True)
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True)
retry_of_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_receipt_rpa_unit_runs.id'), nullable=True, index=True,
@@ -88,7 +88,7 @@ class ShippingReceiptRpaUnitRun(Base):
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
schedule_run: Mapped['ScheduleRun'] = relationship(foreign_keys=[schedule_run_id])
schedule_run: Mapped[Optional['ScheduleRun']] = relationship(foreign_keys=[schedule_run_id])
inventory_source: Mapped['ShippingInventorySource'] = relationship()
retry_of: Mapped[Optional['ShippingReceiptRpaUnitRun']] = relationship(remote_side=[id])
files: Mapped[list['ShippingReceiptReportFile']] = relationship(
+2 -8
View File
@@ -96,8 +96,6 @@ class User(Base):
'shipping_notice.xfa_split_rule_edit': self.role == 'admin',
'shipping_notice.xfa_split_rule_preview': self.role == 'admin',
'shipping_notice.xfa_split_rule_publish': self.role == 'admin',
# 合同付款预警工作台:admin 默认开;不新建角色,可给采购同事单独授予
'contract_payment.access': self.role == 'admin',
}
def get_feature_permissions(self) -> dict[str, bool]:
@@ -105,7 +103,7 @@ class User(Base):
返回当前用户的有效功能权限。
用途:统一为前端展示、登录态注入与后端业务校验提供同一份权限结果。
核心逻辑:先按角色生成默认权限,再用用户显式配置覆盖,避免把培训、合同付款等业务权限硬编码在多个模块。
核心逻辑:先按角色生成默认权限,再用用户显式配置覆盖,避免把培训等业务权限硬编码在多个模块。
输出约束:仅返回布尔型权限键,缺失项自动回退到角色默认值。
"""
defaults = self._role_default_feature_permissions()
@@ -123,7 +121,7 @@ class User(Base):
保存用户显式配置的功能权限覆盖项。
用途:给管理后台用户编辑表单落库权限配置。
核心逻辑:只持久化与角色默认值不同的权限,既保留“admin/hr 角色默认可见”的现有语义,也支持前端手动关闭或给普通用户单独授予。
核心逻辑:只持久化与角色默认值不同的权限,既保留“admin/hr 角色默认可见”的现有语义,也支持前端手动关闭或给普通用户单独授予。合同付款预警改走 Agent 授权,不再占用功能权限键。
参数约束:permissions 必须为 dict 或 None;未知键会被忽略。
"""
defaults = self._role_default_feature_permissions()
@@ -145,10 +143,6 @@ class User(Base):
"""判断当前用户是否可使用培训 HR 管理面板与接口。"""
return self.has_feature_permission('training_hr_manage')
def can_access_contract_payment(self) -> bool:
"""判断当前用户是否可查看合同付款预警工作台并触发同步/扫描。"""
return self.has_feature_permission('contract_payment.access')
def set_password(self, password: str) -> None:
"""设置密码哈希。"""
self.password_hash = generate_password_hash(password)
+27 -4
View File
@@ -1,9 +1,9 @@
"""
backend/app/models/voucher_check.py
用途:立账凭证检核 ORM(Profile / 批次 / 主体 / 单文件结果 / 企微通知)。
用途:立账凭证检核 ORM(Profile / 批次 / 主体 / 单文件结果 / 企微通知 / 按类型接收人)。
依赖:models.base.Base、schedule_runs。
逻辑:引擎写入 profiles/runs/subjects/file_results/notifications;工作台与查询服务只读这些表。
逻辑:引擎写入 profiles/runs/subjects/file_results/notifications;通知配置表供管理员维护文件类型接收人。
"""
from __future__ import annotations
@@ -17,6 +17,7 @@ from sqlalchemy import (
DateTime,
ForeignKey,
Index,
Integer,
JSON,
String,
Text,
@@ -158,13 +159,35 @@ class VoucherCheckFileResult(Base):
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class VoucherCheckNotifyConfig(Base):
"""按业务方保存文件类型 → 接收人;换人不改 Profile 版本。"""
__tablename__ = "voucher_check_notify_configs"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
profile_code: Mapped[str] = mapped_column(String(32), nullable=False, unique=True)
recipients_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
updated_by: Mapped[Optional[int]] = mapped_column(
Integer,
ForeignKey("users.id", ondelete="SET NULL"),
nullable=True,
)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime,
default=datetime.utcnow,
onupdate=datetime.utcnow,
nullable=False,
)
class VoucherCheckNotification(Base):
"""一个检核批次对应一条企微汇总通知审计。"""
"""一个检核批次对应一条企微缺件通知审计(可含多人分信摘要)。"""
__tablename__ = "voucher_check_notifications"
__table_args__ = (Index("ix_voucher_check_notifications_status", "send_status"),)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
run_id: Mapped[int] = mapped_column(
BigInteger,
ForeignKey("voucher_check_runs.id", ondelete="CASCADE"),
+1 -1
View File
@@ -27,7 +27,7 @@ from app.services.admin.training_exam_pdf_service import parse_training_question
from app.services.agent_registry.admin_payload import apply_agent_payload, validate_agent_payload
from app.services.agent_registry.catalog_loader import get_dify_required_providers
from app.services.agent_registry.serialization import serialize_agent_for_admin
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
def serialize_agent(agent: Agent) -> dict:
+1 -1
View File
@@ -14,7 +14,7 @@ from werkzeug.datastructures import FileStorage
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
from app.models import AgentGuide
from app.services.minio_service import minio_service
from app.services.integrations.minio import minio_service
GUIDE_USAGE_GENERAL = 'general'
@@ -1,8 +1,8 @@
"""
backend/app/services/admin/permission_service.py
用途:用户 Agent 权限批量/单用户更新,以及权限申请审批业务逻辑。
依赖:models、wecom_notify.send_wecom_event_message。
用途:用户 Agent 权限批量/单用户更新业务逻辑。
依赖:models、integrations.wecom.notify.send_wecom_event_message。
逻辑:由 api/admin/permissions.py 调用;users 路由 /users/<id>/permissions 亦委托本模块。
"""
from __future__ import annotations
@@ -12,7 +12,7 @@ from typing import Any
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import Agent, User
from app.services.wecom_notify import send_wecom_event_message
from app.services.integrations.wecom.notify import send_wecom_event_message
_BATCH_ACTION_LABELS = {'add': '新增', 'remove': '移除', 'set': '重置为'}
@@ -95,67 +95,3 @@ def update_user_permissions(user_id: int, data: dict[str, Any]) -> dict:
user.agents = agents
db.session.commit()
return {'status': 'ok'}
def list_permission_requests() -> list[dict]:
"""返回全部权限申请(按 created_at 降序)。"""
reqs = (
db.session.query(PermissionRequest)
.order_by(PermissionRequest.created_at.desc())
.all()
)
return [serialize_permission_request(r) for r in reqs]
def approve_permission_request(request_id: int) -> dict:
"""
批准权限申请:更新状态并将 Agent 加入用户权限。
Raises:
NotFoundError: 申请不存在。
"""
req = db.session.get(PermissionRequest, request_id)
if not req:
raise NotFoundError('Not found')
user = db.session.get(User, req.user_id)
agent = db.session.get(Agent, req.agent_id)
req.status = 'approved'
req.reviewed_at = datetime.utcnow()
if user and agent and (agent not in user.agents):
user.agents.append(agent)
if user and user.wecom_userid:
send_wecom_event_message(
event_type='permission_request_approved',
user=user,
title='权限申请已通过',
content=f'你申请的应用权限已通过:{(agent.name if agent else req.agent_id)}',
jump_path='/workspace',
)
db.session.commit()
return {'status': 'ok'}
def reject_permission_request(request_id: int) -> dict:
"""
拒绝权限申请并通知用户(若已绑定企微)。
Raises:
NotFoundError: 申请不存在。
"""
req = db.session.get(PermissionRequest, request_id)
if not req:
raise NotFoundError('Not found')
req.status = 'rejected'
req.reviewed_at = datetime.utcnow()
user = db.session.get(User, req.user_id)
agent = db.session.get(Agent, req.agent_id)
if user and user.wecom_userid:
send_wecom_event_message(
event_type='permission_request_rejected',
user=user,
title='权限申请未通过',
content=f'你申请的应用权限未通过:{(agent.name if agent else req.agent_id)}',
jump_path='/workspace',
)
db.session.commit()
return {'status': 'ok'}
@@ -153,13 +153,7 @@ def _customer_row_validation(raw: dict[str, Any], *, default_source_system: str)
if status not in {'active', 'inactive'}:
errors.append({'code': 'SHIPPING.CUSTOMER_STATUS_INVALID', 'field': 'status'})
existing_ref = _existing_customer_by_ref(source_system, legacy_key) if legacy_key and source_system else None
code_owner = db.session.query(ShippingCustomer).filter_by(short_code=short_code).first() if short_code else None
if code_owner and (not existing_ref or code_owner.id != existing_ref.id):
warnings.append({
'code': 'SHIPPING.CUSTOMER_IMPORT_SHORT_CODE_CONFLICT',
'customer_id': code_owner.id,
'short_code': short_code,
})
# 客户简码允许重复(业务规则),导入预检不再因简码撞码产生 warning。
normalized_name = normalize_customer_name(name)
similar = [
item for item in db.session.query(ShippingCustomer).all()
@@ -37,6 +37,47 @@ from app.services.shipping_notice.customer_normalization import (
CUSTOMER_STATUSES = frozenset({'active', 'inactive', 'merged'})
IDENTIFIER_STATUSES = frozenset({'pending', 'approved', 'disabled'})
_ODM_ID_MAX_ITEMS = 100
_ODM_ID_MAX_LENGTH = 64
def _normalize_odm_ids(value: Any) -> list[str] | None:
"""
规范化客户 ODM ID 清单:逐项 trim、去空、去重(保持原顺序)。
Args:
value: 前端提交的清单(字符串列表);None 表示未提交,空列表表示清空。
Returns:
规范化后的清单;None 仅当输入为 None。
Raises:
ValidationError: 条目超长或清单超量。
"""
if value is None:
return None
if not isinstance(value, list):
raise ValidationError(
'ODM ID list must be an array of strings',
code='SHIPPING.CUSTOMER_ODM_IDS_INVALID',
)
normalized: list[str] = []
for item in value:
text = str(item or '').strip()
if not text:
continue
if len(text) > _ODM_ID_MAX_LENGTH:
raise ValidationError(
'ODM ID is too long',
code='SHIPPING.CUSTOMER_ODM_IDS_INVALID',
details={'odm_id': text},
)
if text not in normalized:
normalized.append(text)
if len(normalized) > _ODM_ID_MAX_ITEMS:
raise ValidationError(
'Too many ODM IDs',
code='SHIPPING.CUSTOMER_ODM_IDS_INVALID',
)
return normalized
def _record_lifecycle_event(
@@ -142,6 +183,7 @@ def serialize_customer(
'status': record.status,
'merged_into_customer_id': record.merged_into_customer_id,
'remark': record.remark,
'odm_ids': list(record.odm_ids or []) if record.odm_ids is not None else None,
'created_by_id': record.created_by_id,
'updated_by_id': record.updated_by_id,
'created_at': record.created_at.isoformat() if record.created_at else None,
@@ -278,23 +320,12 @@ def get_customer(customer_id: int) -> dict[str, Any]:
return serialize_customer(record, include_identifiers=True)
def _assert_short_code_available(short_code: str, *, exclude_customer_id: int | None = None) -> None:
"""校验客户简码全局唯一。"""
query = db.session.query(ShippingCustomer.id).filter(ShippingCustomer.short_code == short_code)
if exclude_customer_id is not None:
query = query.filter(ShippingCustomer.id != exclude_customer_id)
if query.first():
raise ConflictError(
'Customer short code already exists',
code='SHIPPING.CUSTOMER_SHORT_CODE_EXISTS',
details={'short_code': short_code},
)
def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""
创建标准客户。
客户简码允许重复(业务规则),仅做格式归一化,不做唯一性校验。
Args:
data: standard_name、short_code、status、remark。
actor_id: 当前管理员 ID。
@@ -309,7 +340,6 @@ def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
details={'field': 'standard_name'},
)
short_code = normalize_short_code(data.get('short_code'))
_assert_short_code_available(short_code)
status = clean_text(data.get('status') or 'active').lower()
if status not in CUSTOMER_STATUSES - {'merged'}:
raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID')
@@ -318,6 +348,7 @@ def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
short_code=short_code,
status=status,
remark=clean_text(data.get('remark')) or None,
odm_ids=_normalize_odm_ids(data.get('odm_ids')) if 'odm_ids' in data else None,
created_by_id=actor_id,
updated_by_id=actor_id,
)
@@ -385,11 +416,13 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N
'short_code': record.short_code,
'status': record.status,
'remark': record.remark,
'odm_ids': list(record.odm_ids or []) if record.odm_ids is not None else None,
}
next_name = before['standard_name']
next_short_code = before['short_code']
next_status = before['status']
next_remark = before['remark']
next_odm_ids = before['odm_ids']
if 'standard_name' in data:
name = clean_text(data.get('standard_name'))
if not name:
@@ -397,18 +430,20 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N
next_name = name
if 'short_code' in data:
next_short_code = normalize_short_code(data.get('short_code'))
_assert_short_code_available(next_short_code, exclude_customer_id=customer_id)
if 'status' in data:
next_status = clean_text(data.get('status')).lower()
if next_status not in CUSTOMER_STATUSES - {'merged'}:
raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID')
if 'remark' in data:
next_remark = clean_text(data.get('remark')) or None
if 'odm_ids' in data:
next_odm_ids = _normalize_odm_ids(data.get('odm_ids'))
after = {
'standard_name': next_name,
'short_code': next_short_code,
'status': next_status,
'remark': next_remark,
'odm_ids': next_odm_ids,
}
changes = {key: {'before': before[key], 'after': after[key]} for key in before if before[key] != after[key]}
if changes:
@@ -418,6 +453,7 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N
record.short_code = next_short_code
record.status = next_status
record.remark = next_remark
record.odm_ids = next_odm_ids
record.updated_by_id = actor_id
_record_lifecycle_event(
record,
@@ -67,19 +67,6 @@ def _json_object(data: dict[str, Any], field: str) -> dict[str, Any]:
return dict(value)
def _json_string_list(data: dict[str, Any], field: str) -> list[str]:
"""读取非空、去重的字符串列表,供 Source 别名等业务配置使用。"""
value = data.get(field, [])
if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
raise ValidationError(f'{field} must be a string list', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
result: list[str] = []
for item in value:
normalized = item.strip()
if normalized and normalized not in result:
result.append(normalized)
return result
def _validate_profile_login_config(data: dict[str, Any]) -> dict[str, str]:
"""校验连接级登录配置,不接收页面选择器或报表操作字段。"""
value = data.get('login_config_json', {})
@@ -268,20 +255,47 @@ def _source_payload(source: ShippingInventorySource) -> dict[str, Any]:
def _receipt_report_config_payload(config: ShippingReceiptReportConfig) -> dict[str, Any]:
"""序列化独立收料配置,禁止把库存路径或凭据透传至管理端。"""
profile = config.parsing_profile
return {
'id': config.id, 'inventory_source_id': config.inventory_source_id, 'enabled': bool(config.enabled),
'id': config.id, 'inventory_source_id': config.inventory_source_id,
'report_path_json': config.report_path_json or {},
'query_parameters_json': config.query_parameters_json or [],
'warehouse_ids_json': config.warehouse_ids_json or [], 'config_version': config.config_version,
# 异动解析绑定:供抽屉回显当前规则;摘要只取展示字段,不透传定义。
'parsing_profile_id': config.parsing_profile_id,
'parsing_profile': ({
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
'version': profile.version, 'status': profile.status,
} if profile else None),
'config_version': config.config_version,
'created_at': _iso(config.created_at), 'updated_at': _iso(config.updated_at),
}
def _validate_movement_profile_binding(profile_id: Any) -> int | None:
"""校验收料配置绑定的异动解析规则:必须已发布且 purpose='movement';空值表示解绑。
Args:
profile_id: 请求中的 parsing_profile_id;None/空串表示解绑。
Returns:
规整后的规则 id 或 None。
Raises:
ValidationError: 规则不存在/未发布/用途不是 movement(fail-closed,防误绑库存规则)。
"""
if profile_id is None or str(profile_id).strip() == '':
return None
profile = db.session.get(ShippingInventoryParsingProfile, int(profile_id))
if profile is None or profile.status != 'published' or profile.purpose != 'movement':
raise ValidationError(
'Receipt movement parsing profile must be published with purpose movement',
code='SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID',
)
return profile.id
def _validate_receipt_report_config(
source: ShippingInventorySource, data: dict[str, Any],
) -> tuple[bool, dict[str, str], list[dict[str, Any]], list[str]]:
"""规范收料配置,确保日期保持空值、DBS/Crane 路径与仓库拆分规则不混用。"""
enabled = _bool(data, 'enabled', True)
) -> tuple[dict[str, str], list[dict[str, Any]]]:
"""规范收料配置,与库存同构:路径+查询条件;日期禁填,DBS 以 Warehouse 条件为逐仓拆分维度。"""
try:
parameters = _validate_query_parameters(data)
except ValidationError as exc:
@@ -289,19 +303,22 @@ def _validate_receipt_report_config(
# 报表日期不筛选,避免管理端误传日期使跨日排程导出产生漏数。
if any('date' in str(item.get('name') or '').strip().lower() for item in parameters):
raise ValidationError('Receipt report date filtering is not supported', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
raw_warehouses = _json_string_list(data, 'warehouse_ids_json')
raw_path = _json_object(data, 'report_path_json')
if source.connector_type == 'dbs':
try:
path = _validate_report_path('dbs', raw_path)
except ValidationError as exc:
raise ValidationError(str(exc), code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') from exc
if enabled and not raw_warehouses:
raise ValidationError('DBS receipt report requires warehouse_ids_json', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
return enabled, path, parameters, raw_warehouses
# Warehouse 条件即逐仓拆分维度(不单独持久化仓库清单):必须恰一条且至少一个有效值。
warehouse_conditions = [item for item in parameters if str(item.get('name') or '').strip().lower() == 'warehouse']
warehouse_values = [str(value or '').strip() for value in (warehouse_conditions[0].get('values') or [])] if warehouse_conditions else []
if len(warehouse_conditions) != 1 or not any(warehouse_values):
raise ValidationError(
'DBS receipt report requires exactly one Warehouse query condition with values',
code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID',
)
return path, parameters
if source.connector_type == 'crane':
if raw_warehouses:
raise ValidationError('Crane receipt report does not support Warehouse split', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Inbound Details'):
raise ValidationError('Crane receipt report is fixed to Inbound Details', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
if parameters:
@@ -309,7 +326,7 @@ def _validate_receipt_report_config(
'Crane receipt report does not support query parameters',
code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID',
)
return enabled, {'report_name': 'Inbound Details'}, [], []
return {'report_name': 'Inbound Details'}, []
raise ValidationError('Unsupported receipt connector type', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
@@ -327,7 +344,7 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
source = db.session.get(ShippingInventorySource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
enabled, path, parameters, warehouses = _validate_receipt_report_config(source, data)
path, parameters = _validate_receipt_report_config(source, data)
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).one_or_none()
before = _receipt_report_config_payload(config) if config else None
is_new = config is None
@@ -337,10 +354,9 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
db.session.add(config)
else:
config.config_version += 1
config.enabled = enabled
config.report_path_json = path
config.query_parameters_json = parameters
config.warehouse_ids_json = warehouses
config.parsing_profile_id = _validate_movement_profile_binding(data.get('parsing_profile_id'))
config.updated_by = actor_id
db.session.flush()
after = _receipt_report_config_payload(config)
@@ -348,7 +364,8 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
event_type='shipping_receipt_report_config_saved', aggregate_type='shipping_receipt_report_config',
aggregate_id=str(source.id), actor_type='admin', actor_id=actor_id, action='create' if is_new else 'update',
result='success', before=before, after=after,
metadata={'inventory_source_id': source.id, 'connector_type': source.connector_type},
metadata={'inventory_source_id': source.id, 'connector_type': source.connector_type,
'parsing_profile_id': config.parsing_profile_id},
)
db.session.commit()
return after
@@ -1160,6 +1177,7 @@ def _external_payload(mapping: ShippingInventoryExternalMapping) -> dict[str, An
'freight_warehouse_id': mapping.freight_warehouse_id, 'external_system_code': mapping.external_system_code,
'external_organization_code': mapping.external_organization_code, 'external_site_code': mapping.external_site_code,
'external_warehouse_code': mapping.external_warehouse_code, 'external_warehouse_name': mapping.external_warehouse_name,
'in_transit_warehouse_code': mapping.in_transit_warehouse_code,
'enabled': bool(mapping.enabled), 'version': mapping.version,
}
@@ -1191,8 +1209,11 @@ def save_external_mapping(data: dict[str, Any], *, actor_id: int | None, mapping
raise ValidationError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
record = record or ShippingInventoryExternalMapping(inventory_source_id=source_id, external_system_code='', external_warehouse_code='', external_warehouse_name='')
record.inventory_source_id = source_id
# Freight warehouse is a business identity token; normalize it to match runtime inventory rows.
record.freight_warehouse_id = (_text(data, 'freight_warehouse_id') or '').upper() or None
# 货代仓库改为可选维度:inventory_match 源按「收料文件仓库 == 货代仓库」匹配映射行,
# 空值即「空库位」默认映射行;归一化为大写以与收料仓库值精确比对。
record.freight_warehouse_id = str(_text(data, 'freight_warehouse_id') or '').upper() or None
# 在途仓编码是在途调拨拨出库位来源(DefaultRouteResolver),保存端必填并大写归一。
record.in_transit_warehouse_code = str(_text(data, 'in_transit_warehouse_code', required=True)).upper()
record.external_system_code = str(_text(data, 'external_system_code', required=True)).upper()
record.external_organization_code = _text(data, 'external_organization_code')
record.external_site_code = _text(data, 'external_site_code')
@@ -20,7 +20,7 @@ from app.core.errors import NotFoundError, ValidationError
from app.models import AgentGuide, KbDocumentVersion
from app.services.admin.guide_service import GUIDE_USAGE_TRAINING_EXAM_PDF
from app.services.kb.storage import resolve_storage_path
from app.services.minio_service import minio_service
from app.services.integrations.minio import minio_service
from edkb_system.contracts import Block, Context
from edkb_system.skills import loader_pdf, ocr
@@ -21,7 +21,7 @@ from app.core.config.env_persistence import persist_env_settings
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
from app.models import Agent, LoginAudit, User, WecomNotifyAudit
from app.services.auth import wecom_auth_service
from app.services.oa_wecom_sync import sync_wecom_userids_from_oa
from app.services.integrations.oa.wecom_sync import sync_wecom_userids_from_oa
def serialize_debug_match_user(user: User) -> dict:
@@ -12,5 +12,7 @@ from __future__ import annotations
RUNTIME_HANDLER_BINDINGS: dict[str, str] = {
'shipping_notice': 'shipping_notice',
'file_check': 'file_check',
'contract_payment': 'contract_payment',
'voucher_check': 'voucher_check',
'in_transit_transfer': 'in_transit_transfer',
}
@@ -129,6 +129,37 @@ agent_types:
file_upload: true
human_confirm: false
handler_config_schema: {}
contract_payment:
label: 合同付款预警
conversation_mode_default: task_chat
runtime_provider_default: builtin
models:
- ContractPaymentContract
- ContractPaymentAlert
- ContractPaymentAlertBatch
required_fields: []
default_capabilities:
streaming: false
file_upload: false
task_progress: false
forced_capabilities:
file_upload: false
handler_config_schema: {}
voucher_check:
label: 立账凭证
conversation_mode_default: task_chat
runtime_provider_default: builtin
models:
- VoucherCheckRun
- VoucherCheckNotification
required_fields: []
default_capabilities:
streaming: false
file_upload: false
task_progress: false
forced_capabilities:
file_upload: false
handler_config_schema: {}
in_transit_transfer:
label: 在途仓自动调拨
conversation_mode_default: task_chat
@@ -2,7 +2,7 @@
backend/app/services/agent_registry/handlers/bootstrap.py
用途:应用启动时加载 HANDLER_REGISTRY。
依赖:handlers.shipping_notice 等领域 handler 模块。
依赖:handlers.shipping_notice、handlers.contract_payment、handlers.voucher_check 等领域 handler 模块。
逻辑:create_app 在 load_context_adapters 之后调用 load_handlers()。
"""
@@ -29,12 +29,16 @@ def load_handlers() -> None:
import importlib
import app.services.agent_registry.handlers.contract_payment as contract_payment_mod
import app.services.agent_registry.handlers.file_check as file_check_mod
import app.services.agent_registry.handlers.in_transit_transfer as in_transit_transfer_mod
import app.services.agent_registry.handlers.shipping_notice as shipping_mod
import app.services.agent_registry.handlers.voucher_check as voucher_check_mod
importlib.reload(file_check_mod)
importlib.reload(shipping_mod)
importlib.reload(contract_payment_mod)
importlib.reload(voucher_check_mod)
importlib.reload(in_transit_transfer_mod)
logger.info('Agent handlers loaded: %s', sorted(HANDLER_REGISTRY.keys()))
@@ -0,0 +1,31 @@
"""
backend/app/services/agent_registry/handlers/contract_payment.py
用途:合同付款预警 builtin Handler。第一期不走对话 completions,只满足 Catalog 对 builtin 必须声明 runtime_handler 的校验。
依赖:agent_registry.handlers.base / registry。
逻辑:Chat 主区渲染台账 Tab,不调用 Dify;prepare_stream 原样返回上下文,供后续 hybrid 接入预留。
"""
from __future__ import annotations
from typing import Any
from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext
from app.services.agent_registry.handlers.registry import register_handler
@register_handler('contract_payment')
class ContractPaymentHandler(AgentHandler):
"""
合同付款预警业务 Handler。
核心逻辑:第一期隐藏输入框,不进入聊天流;保留钩子以便第二期改 hybrid 后注入合同摘要。
"""
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
"""聊天流开始前原样返回上下文;第一期前端不会发起 completions。"""
return ctx
def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None:
"""第一期无领域 UI State;台账由独立 HTTP API 加载。"""
return None
@@ -0,0 +1,31 @@
"""
backend/app/services/agent_registry/handlers/voucher_check.py
用途:立账凭证检核 builtin Handler。第一期不走对话 completions,只满足 Catalog 对 builtin 必须声明 runtime_handler 的校验。
依赖:agent_registry.handlers.base / registry。
逻辑:Chat 主区渲染检核任务 / 企微发送记录 Tab,不调用 Dify;prepare_stream 原样返回上下文,供后续 hybrid 接入预留。
"""
from __future__ import annotations
from typing import Any
from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext
from app.services.agent_registry.handlers.registry import register_handler
@register_handler('voucher_check')
class VoucherCheckHandler(AgentHandler):
"""
立账凭证检核业务 Handler。
核心逻辑:第一期隐藏输入框,不进入聊天流;保留钩子以便第二期改 hybrid 后注入批次摘要。
"""
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
"""聊天流开始前原样返回上下文;第一期前端不会发起 completions。"""
return ctx
def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None:
"""第一期无领域 UI State;检核列表由独立 HTTP API 加载。"""
return None
@@ -15,7 +15,7 @@ from app.services.chat.executors.base import (
ChatStreamContext,
build_dify_inputs_for_context,
)
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
class DifyChatExecutor(ChatExecutor):
@@ -16,13 +16,13 @@ from app.services.chat.intent_route_registry import (
def _match(ctx: ChatIntentRouteContext) -> bool:
from app.services.plm_oracle import PLMOracleService
from app.services.integrations.plm.oracle import PLMOracleService
return PLMOracleService.supports(ctx.query, ctx.agent)
def _stream(ctx: ChatIntentRouteContext):
from app.services.plm_oracle import PLMOracleService
from app.services.integrations.plm.oracle import PLMOracleService
return PLMOracleService.stream_chat(
ctx.query,
@@ -27,7 +27,7 @@ def _match(ctx: ChatIntentRouteContext) -> bool:
def _stream(ctx: ChatIntentRouteContext):
from app.services.text2sql import Text2SQLService
from app.services.integrations.text2sql import Text2SQLService
return Text2SQLService.stream_chat(
ctx.query,
@@ -16,7 +16,7 @@ from typing import Any
from flask import current_app
from app.services.oa_sqlserver import OASQLServerService
from app.services.integrations.oa.sqlserver import OASQLServerService
# [STEP] 仅允许字母数字下划线作为 SQL 标识符,表名/字段来自配置,禁止拼接任意字符串。
_SAFE_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
@@ -29,7 +29,7 @@ from app.models import (
ContractPaymentNode,
User,
)
from app.services.wecom_notify import (
from app.services.integrations.wecom.notify import (
send_wecom_event_message,
send_wecom_file_message,
upload_wecom_temp_media,
@@ -53,7 +53,7 @@ def fetch_paid_records(purchase_order_nos: Iterable[str]) -> dict[str, list[ErpP
return {}
try:
import oracledb
from app.services.text2sql import Text2SQLService
from app.services.integrations.text2sql import Text2SQLService
except ImportError:
current_app.logger.warning("合同付款预警:Oracle 驱动不可用,按未付款处理")
return {}
@@ -1,9 +1,9 @@
"""
backend/app/services/contract_payment/ledger_focus.py
用途:合同台账汇总卡口径——即将到期、逾期未付、待补充、本月应付,均按合同计数。
用途:合同台账汇总卡口径——即将到期、逾期未付、进行中、本月应付,均按合同计数。
依赖:ContractPaymentContract、ContractPaymentNode、业务时区 Asia/Shanghai。
逻辑:由 list/summary API 调用;分类规则与台账行状态标签对齐,本月应付可与前两项重叠。
逻辑:由 list/summary API 调用;即将到期/逾期/进行中互斥,本月应付可与这三项重叠。行级「待补充」不进汇总卡。
"""
from __future__ import annotations
@@ -20,12 +20,12 @@ from app.models import ContractPaymentContract, ContractPaymentNode
LEDGER_FOCUS_DUE = "due"
LEDGER_FOCUS_OVERDUE = "overdue"
LEDGER_FOCUS_NEEDS_COMPLETION = "needs_completion"
LEDGER_FOCUS_ACTIVE = "active"
LEDGER_FOCUS_DUE_THIS_MONTH = "due_this_month"
LEDGER_FOCUS_VALUES = {
LEDGER_FOCUS_DUE,
LEDGER_FOCUS_OVERDUE,
LEDGER_FOCUS_NEEDS_COMPLETION,
LEDGER_FOCUS_ACTIVE,
LEDGER_FOCUS_DUE_THIS_MONTH,
}
_NEAR_DUE_DAYS = 7
@@ -68,7 +68,7 @@ def classify_ledger_status(
"""
按合同聚合出台账状态,与列表「状态」列一致。
核心逻辑:非激活或待确认 → 待补充;无进行中节点则按是否已付分为已完成/待补充;
核心逻辑:非激活或待确认 → 待补充(仅行状态,不进汇总卡);无进行中节点则按是否已付分为已完成/待补充;
进行中节点若已过到期日 → 逾期,若在今天起 7 天内 → 即将到期,否则进行中。
Args:
contract_status: 合同主状态。
@@ -80,16 +80,16 @@ def classify_ledger_status(
"""
node_list = list(nodes)
if str(contract_status or "").strip() != "active" or str(parse_status or "").strip() == "needs_review":
return LEDGER_FOCUS_NEEDS_COMPLETION
return "needs_completion"
if not node_list:
return LEDGER_FOCUS_NEEDS_COMPLETION
return "needs_completion"
active = [node for node in node_list if str(node.get("status") or "").strip().lower() == "active"]
if not active:
has_paid = any(
str(node.get("status") or "").strip().lower() == "paid" or bool(node.get("paid_at"))
for node in node_list
)
return "completed" if has_paid else LEDGER_FOCUS_NEEDS_COMPLETION
return "completed" if has_paid else "needs_completion"
refs = [
ref
for node in active
@@ -99,7 +99,7 @@ def classify_ledger_status(
return LEDGER_FOCUS_OVERDUE
if any(0 <= (ref - today).days <= _NEAR_DUE_DAYS for ref in refs):
return LEDGER_FOCUS_DUE
return "active"
return LEDGER_FOCUS_ACTIVE
def has_unpaid_due_this_month(nodes: Iterable[dict[str, Any]], today: date) -> bool:
@@ -138,7 +138,7 @@ def collect_ledger_focus(*, session: Session, today: date | None = None) -> dict
"""
扫描全部已解析台账合同,按汇总卡口径收集合同 ID。
核心逻辑:不应用页面 keyword;待确认合同不进入台账汇总。本月应付可与即将到期/逾期重叠。
核心逻辑:不应用页面 keyword;待确认合同不进入台账汇总。进行中为未到期且未逾期的未付合同;本月应付可与即将到期、逾期或进行中重叠。
Args:
session: 当前请求的 SQLAlchemy 会话。
today: 可选业务日。
@@ -154,7 +154,7 @@ def collect_ledger_focus(*, session: Session, today: date | None = None) -> dict
buckets: dict[str, set[int]] = {
LEDGER_FOCUS_DUE: set(),
LEDGER_FOCUS_OVERDUE: set(),
LEDGER_FOCUS_NEEDS_COMPLETION: set(),
LEDGER_FOCUS_ACTIVE: set(),
LEDGER_FOCUS_DUE_THIS_MONTH: set(),
}
if not contracts:
@@ -180,8 +180,8 @@ def collect_ledger_focus(*, session: Session, today: date | None = None) -> dict
buckets[LEDGER_FOCUS_DUE].add(row.id)
elif status == LEDGER_FOCUS_OVERDUE:
buckets[LEDGER_FOCUS_OVERDUE].add(row.id)
elif status == LEDGER_FOCUS_NEEDS_COMPLETION:
buckets[LEDGER_FOCUS_NEEDS_COMPLETION].add(row.id)
elif status == LEDGER_FOCUS_ACTIVE:
buckets[LEDGER_FOCUS_ACTIVE].add(row.id)
if has_unpaid_due_this_month(nodes, as_of):
buckets[LEDGER_FOCUS_DUE_THIS_MONTH].add(row.id)
return buckets
@@ -195,7 +195,7 @@ def ledger_focus_counts(*, session: Session, today: date | None = None) -> dict[
session: 当前请求的 SQLAlchemy 会话。
today: 可选业务日。
Returns:
due / overdue / needs_completion / due_this_month 的计数。
due / overdue / active / due_this_month 的计数。
"""
buckets = collect_ledger_focus(session=session, today=today)
return {key: len(ids) for key, ids in buckets.items()}
@@ -16,7 +16,7 @@ from typing import Any
from flask import current_app
from app.services.oa_sqlserver import OASQLServerService
from app.services.integrations.oa.sqlserver import OASQLServerService
# [STEP] 仅允许字母数字下划线作为 SQL 标识符,表名/字段来自配置,禁止拼接任意字符串。
_SAFE_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -14,8 +14,8 @@ from flask import current_app
from app import db
from app.models import KbDifySyncRecord, QuickQuestion
from app.services.dify import DifyService
from app.services.integration_api import IntegrationApiService
from app.services.integrations.dify import DifyService
from app.services.integrations.integration_api import IntegrationApiService
STALE_REASON_KB_UPDATED = 'kb_document_updated'
STALE_REASON_KB_DELETED = 'kb_document_deleted'
+1 -1
View File
@@ -12,7 +12,7 @@ from typing import Any
import requests
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
VALID_FILE_CHECK_RESULTS = {"合格", "不合格", "人工判定"}
@@ -284,7 +284,7 @@ ORDER BY faj.faj02
def _fetch_snapshot_rows(cls, timeout_seconds: int) -> list[dict[str, str]]:
"""从 ERP Oracle 拉取固定资产全量快照。"""
import oracledb
from app.services.text2sql import Text2SQLService
from app.services.integrations.text2sql import Text2SQLService
username, password, dsn = cls._oracle_credentials()
Text2SQLService._init_oracle_client(oracledb)
@@ -729,7 +729,7 @@ INSERT INTO fixed_assets (
user_context: dict[str, Any] | None = None,
) -> tuple[str, list[str], dict[str, Any]]:
"""根据用户问句生成本地快照过滤条件。"""
from app.services.text2sql import Text2SQLService
from app.services.integrations.text2sql import Text2SQLService
clauses: list[str] = []
params: list[str] = []
+13 -11
View File
@@ -2,12 +2,14 @@
backend/app/services/hxops_tool_api.py
用途:解析 HXOPS 两类对外基地址——Dify Tool API(服务端)与用户浏览器访问(下载链等)。
依赖:Flask current_app / request。
依赖:Flask current_app、core.http_context。
逻辑:Dify/RPA 调 Tool API 走 resolve_HXOPS_TOOLS_API_BASE;用户可见下载链走 resolve_hxops_user_facing_base_url。
"""
from __future__ import annotations
from flask import current_app, has_request_context, request
from flask import current_app
from app.core.http_context import has_http_request, host_url
def _resolve_config(config: dict | None = None) -> dict:
@@ -25,11 +27,11 @@ def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: st
核心逻辑:仅读 HXOPS_TOOLS_API_BASE(常为内网 IP),与浏览器下载链、PUBLIC_BASE_URL 分离。
Args:
参数:
config: 可选配置字典;缺省时读 current_app.config。
request_host: 可选请求 host_url;缺省且在请求上下文中时取 request.host_url。
request_host: 可选请求 host_url;缺省且在请求上下文中时取 host_url()。
Returns:
返回:
无尾斜杠的根地址,如 http://192.168.100.192:8890。
"""
cfg = _resolve_config(config)
@@ -39,8 +41,8 @@ def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: st
return configured
host = request_host
if host is None and has_request_context():
host = request.host_url.rstrip("/")
if host is None and has_http_request():
host = host_url()
return host or ""
@@ -50,10 +52,10 @@ def resolve_hxops_user_facing_base_url(*, config: dict | None = None) -> str:
核心逻辑:仅读 HXOPS_PUBLIC_BASE_URL / WECOM_PUBLIC_BASE_URL,不复用 Tool API 内网地址或通知地址。
Args:
参数:
config: 可选配置字典;缺省时读 current_app.config。
Returns:
返回:
无尾斜杠的根地址,如 https://ai.example.com。
"""
cfg = _resolve_config(config)
@@ -63,7 +65,7 @@ def resolve_hxops_user_facing_base_url(*, config: dict | None = None) -> str:
if configured:
return configured
if has_request_context():
return request.host_url.rstrip("/")
if has_http_request():
return host_url()
return resolve_HXOPS_TOOLS_API_BASE(config=cfg)
@@ -4,5 +4,5 @@
依赖:同包 date_policy / status / quantity / strategy / contracts / audit;
Phase 1 起扩展 file_preparation / precheck_service 等。
逻辑:本包只承载调拨领域规则与确定性门禁,不混入 shipping_notice 订单解析;
对外部系统(RPA/ERP/企微)的访问通过本包隔离的 adapter 与 job/worker 完成。
对外部系统(RPA/外部系统/企微)的访问通过本包隔离的 adapter 与 job/worker 完成。
"""
@@ -108,7 +108,7 @@ def archive_snapshot(
"""归档一份对象并持久化索引 + 审计。
Args:
object_type: 对象类型(erp_inventory_snapshot / exception_excel / receipt_file)。
object_type: 对象类型(external_inventory_snapshot / exception_excel / receipt_file)。
object_id: 业务对象编号(precheck_no / run_no)。
data: 待归档字节。
original_filename: 原始文件名。
@@ -3,7 +3,7 @@
用途:组合"每日恢复 → 自动预检 → 自动执行 → 企微汇总通知",
供 in-transit-transfer platform job 调用。
依赖:recovery_service、precheck_service、execution_service、notification。
逻辑:各阶段独立 try/except,任一阶段失败不阻断后续;通知失败不改 ERP 结果。
逻辑:各阶段独立 try/except,任一阶段失败不阻断后续;通知失败不改 外部系统 结果。
"""
from __future__ import annotations
@@ -45,7 +45,7 @@ def cancel_run(*, run_no: str, reason: str, actor_id: int | None = None, request
cancelled = 0
for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all():
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value and not item.erp_document_no:
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value and not item.external_document_no:
item.status = status_machine.TransferStatus.CANCELLED.value
item.result_code = "cancelled"
item.result_message = reason_value
@@ -0,0 +1,103 @@
"""services/in_transit_transfer/capabilities.py
用途:在途调拨域的能力声明——本域经集成连接器暴露的能力契约(入参/出参 Schema、
幂等语义、读写标志),代码注册、禁止管理端动态定义。
依赖:integration_connector.capability(机制层:CapabilitySpec/注册表)。
逻辑:本模块属于领域包而非连接器框架——框架只提供注册/校验机制,域契约随域代码
版本化;应用组合根(app/__init__.py)在每次 create_app 时调用
register_transfer_capabilities()(幂等),保证管理端「能力清单」冷启动即可见,
测试 reset 注册表后也能重建。
"""
from __future__ import annotations
from app.services.integration_connector.capability import (
CapabilitySpec,
list_capabilities,
register_capability,
)
# 在途调拨能力输入/输出 Schema(JSON Schema 最小子集,供入参/出参校验)。
# 查询契约:按组织批量查库存,目标为 (料号, 拨出库位, 拨出批号) 元组列表;
# external_org 取自仓库映射(external_organization_code),由绑定参数映射翻译为接口的 organization。
_QUERY_INPUT_SCHEMA: dict = {
"type": "object",
"required": ["external_org", "targets"],
"properties": {
"external_org": {"type": "string"},
"targets": {"type": "array", "items": {
"type": "object",
"required": ["material_no", "from_warehouse", "lot_no"],
"properties": {
"material_no": {"type": "string"},
"from_warehouse": {"type": "string"},
"lot_no": {"type": "string"},
},
}},
},
}
_QUERY_OUTPUT_SCHEMA: dict = {
"type": "object",
"required": ["rows"],
"properties": {
"rows": {"type": "array", "items": {
"type": "object",
"required": ["material_no", "from_warehouse", "lot_no", "quantity"],
"properties": {
"material_no": {"type": "string"},
"from_warehouse": {"type": "string"},
"lot_no": {"type": "string"},
"quantity": {"type": "number"},
},
}},
},
}
_WRITE_OUTPUT_SCHEMA: dict = {
"type": "object",
"required": ["status"],
"properties": {
"status": {
"type": "string",
"enum": ["success", "business_failed", "technical_failed", "timeout", "result_unknown"],
},
"document_no": {"type": ["string", "null"]},
"verified_posted": {"type": ["boolean", "null"]},
},
}
def register_transfer_capabilities() -> None:
"""注册在途调拨域的三个能力(幂等:已注册的同名跳过)。
幂等是硬要求:组合根每次 create_app 都会调用;测试 reset 注册表后(模块缓存导致
import 副作用不再执行)也依赖本函数重建,故不能依赖「只注册一次」。
"""
registered = {spec.name for spec in list_capabilities()}
for spec in (
CapabilitySpec(
name="in_transit_transfer.query_inventory",
input_schema=_QUERY_INPUT_SCHEMA,
output_schema=_QUERY_OUTPUT_SCHEMA,
idempotency="none",
write=False,
),
CapabilitySpec(
name="in_transit_transfer.create_transfer",
input_schema=_QUERY_INPUT_SCHEMA,
output_schema=_WRITE_OUTPUT_SCHEMA,
idempotency="invoice",
write=True,
),
CapabilitySpec(
name="in_transit_transfer.verify_duplicate",
input_schema=_QUERY_INPUT_SCHEMA,
output_schema=_WRITE_OUTPUT_SCHEMA,
idempotency="invoice",
write=False,
),
):
if spec.name not in registered:
register_capability(spec)
register_transfer_capabilities()
@@ -0,0 +1,283 @@
"""services/in_transit_transfer/capability_client.py
用途:在途调拨域的外部访问统一客户端——查询经 CapabilityGateway 按能力批量调用;
写路径在外部契约冻结前 fail-closed(Phase 2 接线点);域异常与写结果分类集中于此。
依赖:integration_connector.gateway / errors、app.core.errors。
逻辑:查询按 (料号, 拨出库位, 拨出批号) 元组批量进行,组织键 external_org 取自
仓库映射(external_organization_code);查询超时→ExternalQueryTimeoutError,
网关失败→AppError;写 transport 未注入时 create_transfer/verify_duplicate
抛 ExternalNotFrozenError,注入后超时分类为 technical_failed / result_unknown。
"""
from __future__ import annotations
from dataclasses import dataclass
from decimal import Decimal
from typing import Any
from app.core.errors import AppError
QUERY_INVENTORY_CAPABILITY = "in_transit_transfer.query_inventory"
EXTERNAL_NOT_FROZEN_CODE = "TRANSFER.EXTERNAL_NOT_FROZEN"
EXTERNAL_QUERY_TIMEOUT_CODE = "TRANSFER.EXTERNAL_QUERY_TIMEOUT"
EXTERNAL_RESULT_UNKNOWN_CODE = "TRANSFER_RESULT_UNKNOWN"
class ExternalNotFrozenError(AppError):
"""外部系统契约(WSDL/endpoint)尚未冻结,禁止调用(fail-closed)。"""
def __init__(self, message: str = "external system contract not frozen"):
super().__init__(code=EXTERNAL_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False)
class ExternalQueryTimeoutError(AppError):
"""外部系统查询超时(只读路径,允许上层重试)。"""
def __init__(self, message: str = "external query timeout"):
super().__init__(code=EXTERNAL_QUERY_TIMEOUT_CODE, message=message, http_status=503, retryable=True)
class ExternalResultUnknownError(AppError):
"""外部系统写结果无法确认(Phase 2 使用);禁止自动重试。"""
def __init__(self, message: str = "external result unknown", *, operation_id: str | None = None):
details = {"operation_id": operation_id} if operation_id else {}
super().__init__(code=EXTERNAL_RESULT_UNKNOWN_CODE, message=message, http_status=503, retryable=False, details=details)
class ExternalWriteTimeoutError(TimeoutError):
"""外部系统写超时;committed 表达是否可证明已落单。"""
def __init__(
self,
message: str,
*,
committed: bool | None,
document_no: str | None = None,
operation_id: str | None = None,
) -> None:
super().__init__(message)
self.committed = committed
self.document_no = document_no
self.operation_id = operation_id
@dataclass(frozen=True)
class TransferWriteResult:
"""外部系统原子建单/审核/过账结果分类。"""
status: str # success | duplicate_success | duplicate_unverified | business_failed | technical_failed | result_unknown
document_no: str | None = None
verified_posted: bool | None = None
error_code: str | None = None
error_message: str | None = None
@dataclass(frozen=True)
class StockTarget:
"""库存查询目标元组:料号 + 拨出库位 + 拨出批号。"""
material_no: str
from_warehouse: str
lot_no: str
@dataclass(frozen=True)
class StockRow:
"""外部系统返回的一行账面库存。"""
material_no: str
from_warehouse: str
lot_no: str
quantity: Decimal
@dataclass(frozen=True)
class StockQueryResult:
"""一次批量库存查询的结果;按元组精确匹配取数。"""
rows: tuple[StockRow, ...]
def lookup(self, *, material_no: str, from_warehouse: str, lot_no: str) -> Decimal | None:
"""按三元组取库存数量;同键多行累加;未命中返回 None。"""
total: Decimal | None = None
for row in self.rows:
if (row.material_no, row.from_warehouse, row.lot_no) == (material_no, from_warehouse, lot_no):
total = row.quantity if total is None else total + row.quantity
return total
class CapabilityClient:
"""域内外部访问统一客户端:查询经 CapabilityGateway,写路径 fail-closed。
Args:
gateway: 可注入替身(测试);缺省 get_capability_gateway()。
write_transport: 写路径传输替身(Phase 2 前恒 None → 写调用抛
ExternalNotFrozenError;测试注入后走经典写分类:可证明未落单→
technical_failed,否则 result_unknown)。
"""
def __init__(self, gateway: Any | None = None, write_transport: Any | None = None) -> None:
self._gateway_override = gateway
self._write_transport = write_transport
def _gateway(self) -> Any:
if self._gateway_override is not None:
return self._gateway_override
from app.services.integration_connector.gateway import get_capability_gateway
return get_capability_gateway()
def query_stock(
self,
*,
operation_id: str,
external_org: str,
targets: list[StockTarget],
) -> StockQueryResult:
"""按组织批量查询库存(一次调用覆盖全部目标元组)。
Raises:
ExternalQueryTimeoutError: 查询超时(可重试)。
AppError: 网关失败(绑定缺失/调用失败,fail-closed)。
"""
if not targets:
return StockQueryResult(rows=())
result = self._gateway().call(
capability=QUERY_INVENTORY_CAPABILITY,
context={},
params={
"external_org": external_org,
"targets": [
{
"material_no": target.material_no,
"from_warehouse": target.from_warehouse,
"lot_no": target.lot_no,
}
for target in targets
],
},
operation_id=operation_id,
)
if result.status == "timeout":
raise ExternalQueryTimeoutError()
if result.status != "success":
raise AppError(
code=result.error_code or "INTEGRATION.CALL_FAILED",
message=result.error_message or "query_inventory failed",
http_status=503,
retryable=False,
)
rows = [
StockRow(
material_no=str(row.get("material_no") or ""),
from_warehouse=str(row.get("from_warehouse") or ""),
lot_no=str(row.get("lot_no") or ""),
quantity=Decimal(str(row.get("quantity") or "0")),
)
for row in ((result.data or {}).get("rows") or [])
]
return StockQueryResult(rows=tuple(rows))
def create_transfer(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
external_org: str,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> TransferWriteResult:
"""外部系统原子建单/审核/过账并按结果分类。
Returns:
TransferWriteResult:success / duplicate_success / duplicate_unverified /
business_failed / technical_failed / result_unknown。
Raises:
ExternalNotFrozenError: 写契约未冻结(write_transport 未注入)。
"""
if self._write_transport is None:
raise ExternalNotFrozenError("external create_transfer contract not frozen (endpoint missing)")
try:
response = self._write_transport.create_transfer(
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
invoice_no=invoice_no, external_org=external_org,
from_warehouse=from_warehouse, to_warehouse=to_warehouse, quantity=quantity,
)
except ExternalWriteTimeoutError as exc:
if exc.committed is False:
# 可证明未落单 → 明确技术失败(不产生单据)。
return TransferWriteResult(status="technical_failed", error_code="EXTERNAL_TIMEOUT_BEFORE_COMMIT")
return TransferWriteResult(
status="result_unknown", error_code="EXTERNAL_TIMEOUT_AFTER_COMMIT",
document_no=exc.document_no,
)
except TimeoutError:
# 无法区分是否落单 → result_unknown,禁止自动重试。
return TransferWriteResult(status="result_unknown", error_code="EXTERNAL_TIMEOUT_UNKNOWN")
return _classify_write_response(response)
def verify_duplicate(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
external_org: str,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> TransferWriteResult:
"""核实重复 Invoice 原单是否已审核过账(幂等确认)。
Returns:
duplicate_success(已过账,含原单号)或 duplicate_unverified。
"""
if self._write_transport is None:
raise ExternalNotFrozenError("external verify_duplicate contract not frozen (endpoint missing)")
try:
response = self._write_transport.verify_duplicate(
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
invoice_no=invoice_no, external_org=external_org,
from_warehouse=from_warehouse, to_warehouse=to_warehouse, quantity=quantity,
)
except (TimeoutError, ExternalWriteTimeoutError):
return TransferWriteResult(status="result_unknown", error_code="EXTERNAL_TIMEOUT_UNKNOWN")
response = response if isinstance(response, dict) else {}
status = str(response.get("status") or "")
document_no = response.get("document_no")
posted = bool(response.get("verified_posted"))
if status == "duplicate_success" and posted:
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
return TransferWriteResult(
status="duplicate_unverified", document_no=document_no, verified_posted=posted,
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
)
def _classify_write_response(response: dict[str, Any]) -> TransferWriteResult:
"""按外部系统写响应原文分类业务结果。"""
status = str(response.get("status") or "")
document_no = response.get("document_no")
if status == "success":
return TransferWriteResult(status="success", document_no=document_no)
if status == "duplicate_success":
posted = bool(response.get("verified_posted"))
if posted:
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
return TransferWriteResult(
status="duplicate_unverified", document_no=document_no, verified_posted=False,
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
)
if status == "business_failed":
return TransferWriteResult(
status="business_failed",
error_code=str(response.get("code") or "EXTERNAL_BUSINESS_REJECT"),
error_message=str(response.get("message") or ""),
)
return TransferWriteResult(status="technical_failed", error_code="EXTERNAL_UNKNOWN_RESPONSE")
@@ -42,16 +42,18 @@ class TransferPrecheckAction:
"""执行只读预检并输出 transfer-precheck 卡片。
【AI 触发时机】:用户表达"查询今天可调拨 / 预检"等意图后由候选 Action 触发;
只读,不写 ERP。
只读,不写 外部系统。
"""
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
source_codes = [str(item).strip() for item in (payload.get("source_codes") or [])]
business_date = str(payload.get("business_date") or business_date_now())
transfer_type = str(payload.get("transfer_type")) if payload.get("transfer_type") else None
deps = transfer_deps.get_transfer_dependencies()
summary = create_precheck(
source_codes=source_codes,
business_date=business_date,
deps=deps,
transfer_type=transfer_type,
)
detail = restore_precheck(summary.precheck_id)
yield _message(
@@ -71,7 +73,7 @@ class TransferExecuteAction:
"""执行勾选范围并输出 transfer-result 卡片。
【AI 触发时机】:用户在预检卡点击"直接生成调拨单"后触发;
后台确定性服务完成写前复查与 ERP 原子写入。
后台确定性服务完成写前复查与 外部系统 原子写入。
"""
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
precheck_id = str(payload.get("precheck_id") or "").strip()
@@ -1,7 +1,7 @@
"""在途调拨并发参数与单写者约束。
用途:冻结来源并发(2)、ERP 查询并发(2)与 ERP 写并发(1)默认值;
ERP 写并发恒为 1,同预检只允许一个执行 Run(由 orchestrator 门禁兜底)。
用途:冻结来源并发(2)、外部系统 查询并发(2)与 外部系统 写并发(1)默认值;
外部系统 写并发恒为 1,同预检只允许一个执行 Run(由 orchestrator 门禁兜底)。
依赖:无(纯常量)。
逻辑:写并发 1 与"同 Invoice 执行数=1"为一期硬约束,禁止运行时提升。
"""
@@ -10,8 +10,8 @@ from __future__ import annotations
# 一期冻结并发参数(与规格 §10 一致)。
SOURCE_CONCURRENCY = 3
ERP_QUERY_CONCURRENCY = 3
ERP_WRITE_CONCURRENCY = 3
外部系统_QUERY_CONCURRENCY = 3
外部系统_WRITE_CONCURRENCY = 3
def assert_single_writer(run_count: int) -> None:
@@ -22,4 +22,4 @@ def assert_single_writer(run_count: int) -> None:
Raises:
AssertionError: run_count > 1(一期硬约束)。
"""
assert run_count <= 1, "ERP write concurrency must stay 1 for the same precheck"
assert run_count <= 1, "External write concurrency must stay 1 for the same precheck"
@@ -1,10 +1,10 @@
"""在途调拨 DTO 与稳定错误码契约。
用途:冻结前后端契约(预检摘要、明细项、ERP 单据聚合结果)与一期错误码,
用途:冻结前后端契约(预检摘要、明细项、外部系统 单据聚合结果)与一期错误码,
保证前端只依赖稳定 DTO、不感知 SOAP/WSDL/文件路径。
依赖:标准库 dataclasses / decimal。
逻辑:DTO 全部 frozen;aggregate_erp_documents 按 ERP 单号聚合最终结果页
(决策 20:ERP 单号、拨出仓、拨入仓、物料数、调拨总数量、过账状态)。
逻辑:DTO 全部 frozen;aggregate_external_documents 按 外部系统 单号聚合最终结果页
(决策 20:外部系统 单号、拨出仓、拨入仓、物料数、调拨总数量、过账状态)。
"""
from __future__ import annotations
@@ -20,7 +20,7 @@ TRANSFER_FILE_NOT_READY = "TRANSFER_FILE_NOT_READY"
TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID"
TRANSFER_INVOICE_CONFLICT = "TRANSFER_INVOICE_CONFLICT"
TRANSFER_QUANTITY_MISMATCH = "TRANSFER_QUANTITY_MISMATCH"
TRANSFER_ERP_INVENTORY_NOT_FOUND = "TRANSFER_ERP_INVENTORY_NOT_FOUND"
TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND = "TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND"
TRANSFER_PRECHECK_EXPIRED = "TRANSFER_PRECHECK_EXPIRED"
TRANSFER_CONFIRMATION_REQUIRED = "TRANSFER_CONFIRMATION_REQUIRED"
TRANSFER_DUPLICATE_NOT_VERIFIED = "TRANSFER_DUPLICATE_NOT_VERIFIED"
@@ -37,7 +37,7 @@ KNOWN_TRANSFER_ERROR_CODES: frozenset[str] = frozenset({
TRANSFER_FILE_SCHEMA_INVALID,
TRANSFER_INVOICE_CONFLICT,
TRANSFER_QUANTITY_MISMATCH,
TRANSFER_ERP_INVENTORY_NOT_FOUND,
TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND,
TRANSFER_PRECHECK_EXPIRED,
TRANSFER_CONFIRMATION_REQUIRED,
TRANSFER_DUPLICATE_NOT_VERIFIED,
@@ -84,7 +84,7 @@ class RawLineRefDTO:
@dataclass(frozen=True)
class PrecheckInvoiceItemDTO:
"""预检明细项(决策 6:收料来源/料号/品名/规格/Invoice/拨出仓/拨出数量/拨入仓/拨入数量/预检结果)。"""
"""预检明细项(决策 6 十列 + 2026-09-21 增批号:拨出批号/拨入批号由 lot_no 转换派生,lot_no 存原值)。"""
source_code: str
material_no: str
@@ -98,13 +98,16 @@ class PrecheckInvoiceItemDTO:
result: str
receipt_date: str | None = None
reason: str = ""
erp_document_no: str | None = None
external_document_no: str | None = None
raw_lines: tuple[RawLineRefDTO, ...] = field(default_factory=tuple)
lot_no: str = ""
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(明细审计与执行期重解析输入)。
receipt_warehouse_code: str = ""
@dataclass(frozen=True)
class PrecheckSummaryDTO:
"""预检摘要(含预计调拨数量、预计 ERP 写入数与预检 Hash)。"""
"""预检摘要(含预计调拨数量、预计 外部系统 写入数与预检 Hash)。"""
precheck_id: str
status: str
@@ -113,14 +116,14 @@ class PrecheckSummaryDTO:
expires_at: str
counts: PrecheckCountsDTO
estimated_transfer_quantity: str
estimated_erp_write_count: int
estimated_external_write_count: int
precheck_hash: str
# ---- 结果页 DTO(决策 20)--------------------------------------------------
@dataclass(frozen=True)
class ErpDocumentLineDTO:
"""ERP 单据内物料明细。"""
class ExternalDocumentLineDTO:
"""外部系统 单据内物料明细。"""
material_no: str
material_name: str
@@ -130,8 +133,8 @@ class ErpDocumentLineDTO:
@dataclass(frozen=True)
class ErpDocumentDTO:
"""按 ERP 单号聚合的结果项。"""
class ExternalDocumentDTO:
"""按 外部系统 单号聚合的结果项。"""
document_no: str
from_warehouse: str
@@ -139,12 +142,12 @@ class ErpDocumentDTO:
material_count: int
total_quantity: Decimal
posting_status: str
lines: tuple[ErpDocumentLineDTO, ...] = field(default_factory=tuple)
lines: tuple[ExternalDocumentLineDTO, ...] = field(default_factory=tuple)
@dataclass(frozen=True)
class TransferExceptionDTO:
"""未生成 ERP 单据的异常项(单独展示)。"""
"""未生成 外部系统 单据的异常项(单独展示)。"""
source_code: str
invoice_no: str
@@ -155,31 +158,31 @@ class TransferExceptionDTO:
@dataclass(frozen=True)
class RunResultDTO:
"""Run 最终结果投影:ERP 单据聚合 + 未生成单据异常。"""
"""Run 最终结果投影:外部系统 单据聚合 + 未生成单据异常。"""
run_no: str
status: str
erp_documents: tuple[ErpDocumentDTO, ...] = field(default_factory=tuple)
external_documents: tuple[ExternalDocumentDTO, ...] = field(default_factory=tuple)
exceptions: tuple[TransferExceptionDTO, ...] = field(default_factory=tuple)
def aggregate_erp_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tuple[ErpDocumentDTO, ...]:
"""按 ERP 单号聚合成功项,产出结果页文档视图。
def aggregate_external_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tuple[ExternalDocumentDTO, ...]:
"""按 外部系统 单号聚合成功项,产出结果页文档视图。
Args:
items: 预检明细项(含 erp_document_no 与 result)。
items: 预检明细项(含 external_document_no 与 result)。
Returns:
按单号聚合的 ErpDocumentDTO 元组(行按 Invoice 排序)。
按单号聚合的 ExternalDocumentDTO 元组(行按 Invoice 排序)。
"""
grouped: dict[str, list[PrecheckInvoiceItemDTO]] = {}
for item in items:
if item.erp_document_no and item.result in {"success", "duplicate_success"}:
grouped.setdefault(item.erp_document_no, []).append(item)
documents: list[ErpDocumentDTO] = []
if item.external_document_no and item.result in {"success", "duplicate_success"}:
grouped.setdefault(item.external_document_no, []).append(item)
documents: list[ExternalDocumentDTO] = []
for document_no in sorted(grouped):
rows = sorted(grouped[document_no], key=lambda row: row.invoice_no)
lines = tuple(
ErpDocumentLineDTO(
ExternalDocumentLineDTO(
material_no=row.material_no,
material_name=row.material_name,
specification=row.specification,
@@ -188,7 +191,7 @@ def aggregate_erp_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tuple[Er
)
for row in rows
)
documents.append(ErpDocumentDTO(
documents.append(ExternalDocumentDTO(
document_no=document_no,
from_warehouse=rows[0].from_warehouse,
to_warehouse=rows[0].to_warehouse,
@@ -20,19 +20,30 @@ MATURITY_NOT_MATURED = "not_matured"
MATURITY_FUTURE = "future"
def parse_date(value: date | str) -> date:
"""将 date 或 'YYYY-MM-DD' 字符串归一化为 date。
def parse_date(value: date | datetime | str) -> date:
"""将 date/datetime 或日期字符串归一化为 date。
Args:
value: date 对象或 ISO 日期字符串。
value: date/datetime 对象,或日期字符串(允许携带时间部分,如
Excel 日期单元格经字符串化的 '2026-08-26 17:38:38')。
Returns:
归一化后的 date。
Raises:
ValueError: 字符串不是合法 ISO 日期。
ValueError: 字符串不是可识别的日期/日期时间。
"""
if isinstance(value, datetime):
return value.date()
if isinstance(value, date):
return value
return date.fromisoformat(str(value).strip())
text = str(value).strip()
try:
return date.fromisoformat(text)
except ValueError:
pass
try:
return datetime.fromisoformat(text).date()
except ValueError as exc:
raise ValueError(f"Invalid date value: {value!r}") from exc
def business_date_now(moment: datetime | None = None) -> date:
@@ -51,6 +62,29 @@ def business_date_now(moment: datetime | None = None) -> date:
return moment.astimezone(SHANGHAI_TZ).date()
def business_date_utc_window(now: datetime | None = None) -> tuple[datetime, datetime]:
"""返回当前业务日期(Asia/Shanghai)在 UTC 存储时间轴上的 [起, 止) 窗口。
用途:判定"文件是否当天抓取"等新鲜度场景。数据库统一存 naive UTC 时间,
直接取 .date() 与业务日期比较会漂移 8 小时,必须先换算窗口再比较。
Args:
now: 可选时刻;naive 按 UTC 兼容处理(与 business_date_now 口径一致)。
Returns:
(窗口起, 窗口止);两者均为 naive UTC datetime,止为开区间(时长 24h)。
"""
if now is None:
now = datetime.now(SHANGHAI_TZ)
if now.tzinfo is None:
now = now.replace(tzinfo=ZoneInfo("UTC"))
sh_now = now.astimezone(SHANGHAI_TZ)
start_utc = (
datetime(sh_now.year, sh_now.month, sh_now.day, tzinfo=SHANGHAI_TZ)
.astimezone(ZoneInfo("UTC"))
.replace(tzinfo=None)
)
return start_utc, start_utc + timedelta(hours=24)
def maturity_status(receipt_date: date | str, business_date: date | str) -> str:
"""按 D+1 规则判定收料日期成熟度。
@@ -1,19 +1,20 @@
"""在途调拨依赖装配(Dependencies)。
用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。
依赖:file_preparation / erp_adapter / precheck_service / models。
逻辑:默认实现 fail-closed —— 收料文件行读取(Q3 样例未冻结)与路由归属
(Q1 规则未冻结)在真实契约冻结前拒绝执行;ERP SOAP 在 WSDL 冻结前拒绝。
依赖:movement_file_repository / capability_client / precheck_service / models。
逻辑:默认实现直接接线真实链路 —— 收料文件行读取走 movement_file_repository
(复用货代收料归档 + movement 解析规则,无文件/无规则时返回 None 由
预检走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver
fail-closed 拒绝;外部访问统一走 CapabilityClient(绑定缺失时 fail-closed)。
"""
from __future__ import annotations
from typing import Any
from app.core.errors import AppError
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile, ReceiptFileRepository
from app.services.in_transit_transfer.gateway_adapter import CapabilityErpAdapter
from app.services.in_transit_transfer.capability_client import CapabilityClient
from app.services.in_transit_transfer.movement_file_repository import ShippingReceiptFileRepository
from app.services.in_transit_transfer.precheck_service import (
RouteMapping,
RouteNotResolvedError,
@@ -21,59 +22,68 @@ from app.services.in_transit_transfer.precheck_service import (
TransferDeps,
)
RECEIPT_ROWS_NOT_FROZEN_CODE = "TRANSFER.RECEIPT_ROWS_NOT_FROZEN"
class ReceiptRowsNotFrozenError(AppError):
"""收料文件行读取契约未冻结(Q3:正式样例/Sheet/表头缺失)。"""
def __init__(self, message: str = "receipt file row contract not frozen"):
super().__init__(code=RECEIPT_ROWS_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False)
class ShippingReceiptFileRepository:
"""默认收料 ready 文件仓库(只读复用 shipping 收料归档)。
行读取依赖收料文件正式样例契约(Q3);未冻结前 fail-closed。
"""
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
"""返回最新 ready 文件;行内容契约未冻结时抛 ReceiptRowsNotFrozenError。"""
raise ReceiptRowsNotFrozenError(
"receipt file rows unfrozen: sample/sheet contract required (Q3)"
)
class DefaultRouteResolver:
"""默认路由解析:来源固定仓 + 外部系统仓库映射。
"""默认路由解析:仓库映射的在途仓编码 + 外部系统仓库。
路由归属规则(来源实例 → ERP 组织/在途仓/映射仓)冻结前 fail-closed。
拨出库位 = 映射行的在途仓编码(in_transit_warehouse_code);拨入仓库 = 映射的
目标仓库代码;组织 = 映射的外部组织编码。映射行按库存源识别方式选择:
inventory_match 源优先「收料文件仓库列 == 货代仓库」精确匹配,匹配不到回退
货代仓库为空的默认映射行(空库位兜底);fixed 源仅一条启用映射直接取用。
不借用站点固定仓库(那是货代发货/库存导出链路的字段)。
"""
def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping:
"""按来源配置与外部映射解析路由;无法归属时抛 RouteNotResolvedError。"""
def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
"""按来源识别方式选择映射行并解析路由;无法归属时抛 RouteNotResolvedError。
Args:
source_code: 来源实例编码(须启用)。
invoice_no: Invoice 单号(当前不参与匹配,保留协议兼容)。
warehouse_code: 收料文件「仓库」列原值(inventory_match 源的映射匹配键)。
Returns:
RouteMapping(external_org / from_warehouse=在途仓编码 / to_warehouse)。
Raises:
RouteNotResolvedError: 来源不存在、无可用映射行或在途仓编码未维护。
"""
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
raise RouteNotResolvedError(source_code=source_code)
mapping = ShippingInventoryExternalMapping.query.filter_by(
mappings = ShippingInventoryExternalMapping.query.filter_by(
inventory_source_id=source.id, enabled=True,
).first()
if mapping is None or not mapping.external_organization_code:
).all()
selected = None
if getattr(source, 'warehouse_resolution_mode', '') == 'inventory_match':
# [匹配] 收料仓库大写归一后与货代仓库精确比对;空库位走默认映射行兜底。
# 部分唯一索引保证同源「精确/默认」各最多一条启用映射,选择结果确定。
key = str(warehouse_code or '').strip().upper()
if key:
selected = next(
(m for m in mappings if str(m.freight_warehouse_id or '').strip().upper() == key), None,
)
if selected is None:
selected = next((m for m in mappings if not str(m.freight_warehouse_id or '').strip()), None)
else:
selected = mappings[0] if mappings else None
if selected is None or not selected.external_organization_code:
raise RouteNotResolvedError(source_code=source_code)
from_warehouse = str(selected.in_transit_warehouse_code or '').strip()
if not from_warehouse:
# 拨出库位无来源(映射未维护在途仓编码)——fail-closed,不猜测。
raise RouteNotResolvedError(source_code=source_code)
return RouteMapping(
erp_org=mapping.external_organization_code,
from_warehouse=source.fixed_warehouse_id or "",
to_warehouse=mapping.external_warehouse_code,
external_org=selected.external_organization_code,
from_warehouse=from_warehouse,
to_warehouse=selected.external_warehouse_code,
)
def _build_erp_adapter() -> CapabilityErpAdapter:
"""装配调拨 ERP 访问:默认走 CapabilityGateway(query_inventory 首消费者)。
def _build_capability_client() -> CapabilityClient:
"""装配调拨外部访问客户端:查询走 CapabilityGateway(绑定缺失时 fail-closed)。
P1 连接器框架:外部系统差异由配置(ClientInstance/InterfaceDefinition/Binding/映射)
承担;缺绑定/契约未冻结时 fail-closed。create_transfer/verify_duplicate 待执行阶段接线。
承担;create_transfer/verify_duplicate 在 WSDL 冻结前 fail-closed(Phase 2 接线)。
"""
return CapabilityErpAdapter()
return CapabilityClient()
_override: TransferDeps | None = None
@@ -86,33 +96,45 @@ def set_transfer_dependencies(deps: TransferDeps | None) -> None:
def get_transfer_dependencies() -> TransferDeps:
"""返回装配好的 TransferDeps(测试覆盖优先,默认 fail-closed)。"""
"""返回装配好的 TransferDeps(测试覆盖优先;默认接线真实文件仓库/触发服务/外部系统 网关)。"""
if _override is not None:
return _override
return TransferDeps(
file_repository=ShippingReceiptFileRepository(),
rpa_trigger=_DefaultRpaTrigger(),
route_resolver=DefaultRouteResolver(),
erp=_build_erp_adapter(),
capabilities=_build_capability_client(),
)
class _DefaultRpaTrigger:
"""默认收料 RPA 触发器:复用既有收料 RPA trigger 目录。
"""默认收料 RPA 触发器:委托真实触发服务(trigger_receipt_rpa)。
依赖来源配置(ShippingInventorySource + 收料报表配置);来源未启用或
trigger 目录未配置时返回失败(fail-closed),不伪造等待。
真实链路 = 落单元行 + 原子写 trigger 文件;来源/收料配置缺失或 trigger
目录未配置时由触发服务返回 fail-closed(ok=False),本类只透传结果。
另在本类前置守卫:收料配置存在但未绑定已发布 movement 解析规则时
直接返回 RPA_RECEIPT_MOVEMENT_PROFILE_MISSING,不触发徒劳抓取。
"""
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
from flask import current_app
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa
# [守卫] 收料配置存在但未绑定已发布 movement 解析规则时,触发 RPA 必然徒劳:
# 抓回的文件无法被 latest_ready_file 复用,预检会反复重抓。fail-closed 返回明确错误码。
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
trigger_dir = str(
current_app.config.get("SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR") or ""
).strip()
if not trigger_dir:
return {"ok": False, "error_code": "RPA_TRIGGER_DIR_NOT_CONFIGURED"}
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
return {"ok": False, "error_code": "SOURCE_NOT_ENABLED"}
return {"ok": True, "callback_id": f"receipt:{source_code}:{business_date}"}
if source is not None:
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
if config is not None:
profile = config.parsing_profile
if profile is None or profile.status != 'published' or profile.purpose != 'movement':
return {'ok': False, 'error_code': 'RPA_RECEIPT_MOVEMENT_PROFILE_MISSING'}
outcome = trigger_receipt_rpa(source_code=source_code, business_date=business_date, reason=reason)
return {
"ok": bool(outcome.get("ok")),
"callback_id": outcome.get("callback_id"),
"error_code": outcome.get("error_code"),
"error_message": outcome.get("error_message"),
}
@@ -1,295 +0,0 @@
"""在途调拨 ERP 访问统一边界(Adapter)。
用途:隔离全部 ERP 请求;业务服务只允许经本模块访问 ERP。
Phase 1 启用只读 query_inventory;Phase 2 增加 create_transfer /
verify_duplicate / 结果分类。
依赖:typing.Protocol 传输层(测试注入 FakeERP;生产为 SOAP 传输)。
逻辑:请求统一携带 operation_id / run_no / attempt_no / invoice_no /
erp_org / 拨出仓 / 拨入仓 / 数量;查询超时分类为可重试;
SOAP 传输在 WSDL/endpoint 冻结前 fail-closed(ErpNotFrozenError)。
"""
from __future__ import annotations
from dataclasses import dataclass
from decimal import Decimal
from typing import Any, Protocol
from app.core.errors import AppError
ERP_NOT_FROZEN_CODE = "TRANSFER.ERP_NOT_FROZEN"
ERP_QUERY_TIMEOUT_CODE = "TRANSFER.ERP_QUERY_TIMEOUT"
ERP_RESULT_UNKNOWN_CODE = "TRANSFER_RESULT_UNKNOWN"
@dataclass(frozen=True)
class InventoryQuery:
"""ERP 账面库存查询结果。"""
found: bool
quantity: Decimal | None = None
document_no: str | None = None
class ErpNotFrozenError(AppError):
"""ERP WSDL/endpoint 尚未冻结,禁止调用(fail-closed)。"""
def __init__(self, message: str = "ERP contract not frozen"):
super().__init__(code=ERP_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False)
class ErpQueryTimeoutError(AppError):
"""ERP 查询超时(只读路径,允许上层重试)。"""
def __init__(self, message: str = "ERP query timeout"):
super().__init__(code=ERP_QUERY_TIMEOUT_CODE, message=message, http_status=503, retryable=True)
class ErpResultUnknownError(AppError):
"""ERP 写结果无法确认(Phase 2 使用);禁止自动重试。"""
def __init__(self, message: str = "ERP result unknown", *, operation_id: str | None = None):
details = {"operation_id": operation_id} if operation_id else {}
super().__init__(code=ERP_RESULT_UNKNOWN_CODE, message=message, http_status=503, retryable=False, details=details)
class ErpWriteTimeoutError(TimeoutError):
"""ERP 写超时;committed 表达是否可证明已落单。"""
def __init__(
self,
message: str,
*,
committed: bool | None,
document_no: str | None = None,
operation_id: str | None = None,
) -> None:
super().__init__(message)
self.committed = committed
self.document_no = document_no
self.operation_id = operation_id
@dataclass(frozen=True)
class TransferWriteResult:
"""ERP 原子建单/审核/过账结果分类。"""
status: str # success | duplicate_success | duplicate_unverified | business_failed | technical_failed | result_unknown
document_no: str | None = None
verified_posted: bool | None = None
error_code: str | None = None
error_message: str | None = None
class ErpTransport(Protocol):
"""ERP 传输层协议(SOAP 或测试替身)。"""
def query_inventory(self, **kwargs: Any) -> dict[str, Any]:
"""按 Invoice 查询账面库存。"""
def create_transfer(self, **kwargs: Any) -> dict[str, Any]:
"""原子建单/审核/过账(Phase 2)。"""
def verify_duplicate(self, **kwargs: Any) -> dict[str, Any]:
"""核实重复 Invoice 原单是否已审核过账。"""
class SoapErpTransport:
"""真实 SOAP 传输;凭据只来自配置/环境,不写入请求体回显。
Args:
config: 来自 Flask config 或环境变量(endpoint/username/password 等)。
"""
def __init__(self, config: dict[str, Any] | None = None) -> None:
self._config = config or {}
def _require_frozen(self, operation: str) -> None:
"""WSDL/endpoint 未冻结前任何调用直接拒绝。"""
if not str(self._config.get("endpoint") or "").strip():
raise ErpNotFrozenError(f"ERP {operation} contract not frozen (endpoint missing)")
def query_inventory(self, **kwargs: Any) -> dict[str, Any]:
"""SOAP 查询账面库存(实现待 WSDL 冻结后落地)。"""
self._require_frozen("query_inventory")
raise NotImplementedError("SOAP query_inventory implementation pending frozen WSDL")
def create_transfer(self, **kwargs: Any) -> dict[str, Any]:
"""SOAP 原子建单/审核/过账(实现待 WSDL 冻结后落地)。"""
self._require_frozen("create_transfer")
raise NotImplementedError("SOAP create_transfer implementation pending frozen WSDL")
def verify_duplicate(self, **kwargs: Any) -> dict[str, Any]:
"""SOAP 核实重复 Invoice 原单状态(实现待 WSDL 冻结后落地)。"""
self._require_frozen("verify_duplicate")
raise NotImplementedError("SOAP verify_duplicate implementation pending frozen WSDL")
class ErpAdapter:
"""ERP 唯一访问入口;组装统一请求并分类结果。"""
def __init__(self, transport: ErpTransport, *, default_org: str = "") -> None:
self._transport = transport
self._default_org = default_org
def query_inventory(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
erp_org: str | None = None,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> InventoryQuery:
"""查询 ERP 账面库存并分类结果。
Args:
operation_id / run_no / attempt_no / invoice_no / erp_org /
from_warehouse / to_warehouse / quantity: 请求强制追踪字段。
Returns:
InventoryQuery。
Raises:
ErpQueryTimeoutError: 查询超时(可重试)。
ErpNotFrozenError: ERP 契约未冻结。
"""
request = {
"operation_id": operation_id,
"run_no": run_no,
"attempt_no": attempt_no,
"invoice_no": invoice_no,
"erp_org": erp_org or self._default_org,
"from_warehouse": from_warehouse,
"to_warehouse": to_warehouse,
"quantity": quantity,
}
try:
response = self._transport.query_inventory(**request)
except ErpNotFrozenError:
raise
except TimeoutError as exc:
raise ErpQueryTimeoutError() from exc
response = response if isinstance(response, dict) else {}
if response.get("found"):
return InventoryQuery(found=True, quantity=Decimal(str(response.get("quantity") or "0")))
return InventoryQuery(found=False)
def _build_request(self, *, operation_id, run_no, attempt_no, invoice_no, erp_org,
from_warehouse, to_warehouse, quantity) -> dict[str, Any]:
"""组装携带全部强制追踪字段的 ERP 请求。"""
return {
"operation_id": operation_id,
"run_no": run_no,
"attempt_no": attempt_no,
"invoice_no": invoice_no,
"erp_org": erp_org or self._default_org,
"from_warehouse": from_warehouse,
"to_warehouse": to_warehouse,
"quantity": quantity,
}
def create_transfer(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
erp_org: str | None = None,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> TransferWriteResult:
"""ERP 原子建单/审核/过账并按结果分类。
Returns:
TransferWriteResult:success / duplicate_success / duplicate_unverified /
business_failed / technical_failed / result_unknown。
Raises:
ErpNotFrozenError: ERP 契约未冻结。
"""
request = self._build_request(
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
invoice_no=invoice_no, erp_org=erp_org, from_warehouse=from_warehouse,
to_warehouse=to_warehouse, quantity=quantity,
)
try:
response = self._transport.create_transfer(**request)
except ErpNotFrozenError:
raise
except ErpWriteTimeoutError as exc:
if exc.committed is False:
# 可证明未落单 → 明确技术失败(不产生单据)。
return TransferWriteResult(status="technical_failed", error_code="ERP_TIMEOUT_BEFORE_COMMIT")
return TransferWriteResult(
status="result_unknown", error_code="ERP_TIMEOUT_AFTER_COMMIT",
document_no=exc.document_no,
)
except TimeoutError:
# 无法区分是否落单 → result_unknown,禁止自动重试。
return TransferWriteResult(status="result_unknown", error_code="ERP_TIMEOUT_UNKNOWN")
return _classify_write_response(response)
def verify_duplicate(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
erp_org: str | None = None,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> TransferWriteResult:
"""核实重复 Invoice 原单是否已审核过账(幂等确认)。
Returns:
duplicate_success(已过账,含原单号)或 duplicate_unverified。
"""
request = self._build_request(
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
invoice_no=invoice_no, erp_org=erp_org, from_warehouse=from_warehouse,
to_warehouse=to_warehouse, quantity=quantity,
)
try:
response = self._transport.verify_duplicate(**request)
except ErpNotFrozenError:
raise
except (TimeoutError, ErpWriteTimeoutError):
return TransferWriteResult(status="result_unknown", error_code="ERP_TIMEOUT_UNKNOWN")
response = response if isinstance(response, dict) else {}
status = str(response.get("status") or "")
document_no = response.get("document_no")
posted = bool(response.get("verified_posted"))
if status == "duplicate_success" and posted:
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
return TransferWriteResult(
status="duplicate_unverified", document_no=document_no, verified_posted=posted,
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
)
def _classify_write_response(response: dict[str, Any]) -> TransferWriteResult:
"""按 ERP 写响应原文分类业务结果。"""
status = str(response.get("status") or "")
document_no = response.get("document_no")
if status == "success":
return TransferWriteResult(status="success", document_no=document_no)
if status == "duplicate_success":
posted = bool(response.get("verified_posted"))
if posted:
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
return TransferWriteResult(
status="duplicate_unverified", document_no=document_no, verified_posted=False,
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
)
if status == "business_failed":
return TransferWriteResult(
status="business_failed",
error_code=str(response.get("code") or "ERP_BUSINESS_REJECT"),
error_message=str(response.get("message") or ""),
)
return TransferWriteResult(status="technical_failed", error_code="ERP_UNKNOWN_RESPONSE")
@@ -1,7 +1,7 @@
"""在途调拨七 Sheet 异常 Excel 导出。
用途:按规格生成七 Sheet 异常 Excel(执行汇总/数量不一致/ERP无库存/
ERP技术失败/ERP结果未知/通知失败/原始文件追溯),供企微附件与下载。
用途:按规格生成七 Sheet 异常 Excel(执行汇总/数量不一致/外部系统无库存/
外部系统技术失败/外部系统结果未知/通知失败/原始文件追溯),供企微附件与下载。
依赖:openpyxl、models、execution_service。
逻辑:Sheet 内容按状态归类;原始文件追溯保留 Sheet/行号/文件版本;
Secret 明文永不写入单元格(仅输出业务字段)。
@@ -21,9 +21,9 @@ from app.core.errors import NotFoundError
EXCEL_SHEET_NAMES = [
"执行汇总",
"数量不一致",
"ERP无库存",
"ERP技术失败",
"ERP结果未知",
"外部系统无库存",
"外部系统技术失败",
"外部系统结果未知",
"通知失败",
"原始文件追溯",
]
@@ -53,8 +53,8 @@ def build_exceptions_workbook(run_no: str) -> bytes:
_sheet_summary(workbook, run, items)
_sheet_blocked(workbook, items, "数量不一致", {"blocked_quantity_mismatch", "precheck_expired"})
_sheet_blocked(workbook, items, "ERP无库存", {"blocked_inventory_not_found"})
_sheet_blocked(workbook, items, "ERP技术失败", {"business_failed", "technical_failed", "item_execution_error"})
_sheet_blocked(workbook, items, "外部系统无库存", {"blocked_inventory_not_found"})
_sheet_blocked(workbook, items, "外部系统技术失败", {"business_failed", "technical_failed", "item_execution_error"})
_sheet_unknown(workbook, items)
_sheet_notification(workbook, run)
_sheet_raw_trace(workbook, items)
@@ -71,30 +71,30 @@ def _sheet_summary(workbook: Workbook, run: TransferRun, items: list[TransferInv
sheet.append(["Run 状态", run.status])
sheet.append(["通知状态", run.notification_status])
sheet.append([])
sheet.append(["Invoice", "来源", "料号", "预检结果", "ERP 单号"])
sheet.append(["Invoice", "来源", "料号", "预检结果", "外部系统 单号"])
for item in items:
sheet.append([
item.invoice_no, item.source_code, item.material_no,
item.result_code or item.status, item.erp_document_no or "",
item.result_code or item.status, item.external_document_no or "",
])
def _sheet_blocked(workbook: Workbook, items: list[TransferInvoiceItem], sheet_name: str, codes: set[str]) -> None:
"""按阻断原因归类 Sheet。"""
sheet = workbook.create_sheet(sheet_name)
sheet.append(["Invoice", "来源", "料号", "收料数量", "ERP 数量", "原因"])
sheet.append(["Invoice", "来源", "料号", "收料数量", "外部系统 数量", "原因"])
for item in items:
if (item.result_code or "") in codes or item.status in codes:
sheet.append([
item.invoice_no, item.source_code, item.material_no,
item.receipt_quantity, item.erp_quantity or "",
item.receipt_quantity, item.external_quantity or "",
item.result_message or item.result_code or item.status,
])
def _sheet_unknown(workbook: Workbook, items: list[TransferInvoiceItem]) -> None:
"""ERP 结果未知 Sheet(只读提示,含 Operation 关联)。"""
sheet = workbook.create_sheet("ERP结果未知")
"""外部系统 结果未知 Sheet(只读提示,含 Operation 关联)。"""
sheet = workbook.create_sheet("外部系统结果未知")
sheet.append(["Invoice", "来源", "料号", "说明"])
sheet.append(["仅展示事实,禁止重试/关闭;请按人工核实 SOP 处理", "", "", ""])
for item in items:
@@ -1,9 +1,9 @@
"""在途调拨执行服务(确认门禁 + 写前复查 + ERP 原子写入 + 结果投影)。
"""在途调拨执行服务(确认门禁 + 写前复查 + 外部系统 原子写入 + 结果投影)。
用途:执行一次预检:校验确认范围与预检快照(fail-closed)→ 创建执行 Run →
逐项写前复查 ERP 库存 → 原子建单/审核/过账 → 按 ERP 单号投影最终结果。
依赖:orchestrator、erp_adapter、quantity、contracts、audit、status、models。
逻辑:未确认/过期/快照变化/选择含不可执行项 → ERP 写调用为 0;
逐项写前复查 外部系统 库存 → 原子建单/审核/过账 → 按 外部系统 单号投影最终结果。
依赖:orchestrator、capability_client、quantity、contracts、audit、status、models。
逻辑:未确认/过期/快照变化/选择含不可执行项 → 外部系统 写调用为 0;
每个 Invoice 独立写入,单项失败/结果未知不阻断其他项;
result_unknown 为终态,禁止自动重试;每次写入创建新 Attempt。
"""
@@ -24,11 +24,11 @@ from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.contracts import (
TRANSFER_CONFIRMATION_REQUIRED,
TRANSFER_PRECHECK_EXPIRED,
ErpDocumentDTO,
ExternalDocumentDTO,
PrecheckInvoiceItemDTO,
RunResultDTO,
TransferExceptionDTO,
aggregate_erp_documents,
aggregate_external_documents,
)
from app.services.in_transit_transfer.orchestrator import create_execution_run, finalize_run
from app.services.in_transit_transfer.precheck_service import (
@@ -36,6 +36,7 @@ from app.services.in_transit_transfer.precheck_service import (
RouteNotResolvedError,
TransferDeps,
)
from app.services.in_transit_transfer.capability_client import StockTarget
from app.services.in_transit_transfer.quantity import classify_quantity_match
PRECHECK_EXPIRED_RESULT = "precheck_expired"
@@ -72,7 +73,7 @@ def recompute_precheck_hash(precheck: TransferPrecheck) -> str:
"from_warehouse": item.from_warehouse,
"to_warehouse": item.to_warehouse,
"receipt_quantity": item.receipt_quantity,
"erp_quantity": item.erp_quantity,
"external_quantity": item.external_quantity,
"result": _item_result_of(item),
}
for item in sorted(precheck.items, key=lambda row: row.id)
@@ -88,6 +89,11 @@ def recompute_precheck_hash(precheck: TransferPrecheck) -> str:
},
"items": items,
}
# [调拨类型] 创建时快照含 transfer_type(2026-09-22 起 scope_json 恒写入);
# 存量预检 scope_json 无该字段时保持旧快照形状,避免复算 Hash 不一致误判过期。
scope_transfer_type = str(precheck.scope_json.get("transfer_type") or "").strip()
if scope_transfer_type:
snapshot["transfer_type"] = scope_transfer_type
return f"sha256:{canonical_hash(snapshot)}"
@@ -115,7 +121,7 @@ def execute_precheck(
Returns:
ExecuteOutcome(run_no / run 状态 / 单据聚合结果)。
Raises:
NotFoundError / ValidationError / AppError: 门禁失败(ERP 写入为 0)。
NotFoundError / ValidationError / AppError: 门禁失败(外部系统 写入为 0)。
ConflictError: 重复执行。
"""
precheck = db.session.query(TransferPrecheck).filter_by(
@@ -185,42 +191,48 @@ def execute_precheck(
def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, request_id: str | None) -> None:
"""写前复查 + ERP 原子写入单个 Invoice(创建新 Attempt)。"""
route = deps.route_resolver.resolve(source_code=item.source_code, invoice_no=item.invoice_no)
"""写前复查 + 外部系统 原子写入单个 Invoice(创建新 Attempt)。"""
route = deps.route_resolver.resolve(
source_code=item.source_code, invoice_no=item.invoice_no,
warehouse_code=item.receipt_warehouse_code or "",
)
if route.from_warehouse != item.from_warehouse or route.to_warehouse != item.to_warehouse:
_mark_recheck_blocked(item, "precheck_expired", "route mapping changed since precheck")
return
receipt_qty = Decimal(item.receipt_quantity)
operation_id = f"op-{uuid.uuid4().hex[:12]}"
# [STEP 1] 写前复查:重新查询 ERP 库存并严格匹配冻结收料数量。
# [STEP 1] 写前复查:重新查询外部系统库存并严格匹配冻结收料数量。
try:
query = deps.erp.query_inventory(
operation_id=operation_id, run_no=run_no, attempt_no=item.attempt_no,
invoice_no=item.invoice_no, erp_org=route.erp_org,
from_warehouse=route.from_warehouse, to_warehouse=route.to_warehouse,
quantity=receipt_qty,
stock = deps.capabilities.query_stock(
operation_id=operation_id, external_org=route.external_org,
targets=[StockTarget(
material_no=item.material_no, from_warehouse=item.from_warehouse, lot_no=item.lot_no or "",
)],
)
stock_qty = stock.lookup(
material_no=item.material_no, from_warehouse=item.from_warehouse, lot_no=item.lot_no or "",
)
except RouteNotResolvedError:
raise
if not query.found or classify_quantity_match(receipt_qty, query.quantity) != RESULT_EXECUTABLE:
_mark_recheck_blocked(item, "precheck_expired", "erp inventory changed since precheck")
if stock_qty is None or classify_quantity_match(receipt_qty, stock_qty) != RESULT_EXECUTABLE:
_mark_recheck_blocked(item, "precheck_expired", "external inventory changed since precheck")
return
# [STEP 2] 记录写 Attempt 并调用 ERP 原子建单/审核/过账。
# [STEP 2] 记录写 Attempt 并调用外部系统原子建单/审核/过账。
attempt = TransferAttempt(
item_id=item.id, attempt_no=item.attempt_no, kind="erp_write",
item_id=item.id, attempt_no=item.attempt_no, kind="external_write",
status="running", operation_id=operation_id,
request_snapshot_json={
"run_no": run_no, "invoice_no": item.invoice_no, "erp_org": route.erp_org,
"run_no": run_no, "invoice_no": item.invoice_no, "external_org": route.external_org,
"from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse,
"quantity": str(receipt_qty),
},
)
db.session.add(attempt)
db.session.flush()
result = deps.erp.create_transfer(
result = deps.capabilities.create_transfer(
operation_id=operation_id, run_no=run_no, attempt_no=item.attempt_no,
invoice_no=item.invoice_no, erp_org=route.erp_org,
invoice_no=item.invoice_no, external_org=route.external_org,
from_warehouse=route.from_warehouse, to_warehouse=route.to_warehouse,
quantity=receipt_qty,
)
@@ -230,7 +242,7 @@ def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, r
def _mark_recheck_blocked(item: TransferInvoiceItem, result: str, message: str) -> None:
"""写前复查失败:fail-closed,不写 ERP。"""
"""写前复查失败:fail-closed,不写 外部系统。"""
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = result
item.result_message = message
@@ -238,7 +250,7 @@ def _mark_recheck_blocked(item: TransferInvoiceItem, result: str, message: str)
def _apply_write_result(item: TransferInvoiceItem, attempt: TransferAttempt, result) -> None:
"""按 ERP 写结果分类落位 item 与 attempt(result_unknown 为终态)。"""
"""按 外部系统 写结果分类落位 item 与 attempt(result_unknown 为终态)。"""
attempt.response_summary_json = {
"status": result.status,
"document_no": result.document_no,
@@ -247,12 +259,12 @@ def _apply_write_result(item: TransferInvoiceItem, attempt: TransferAttempt, res
}
if result.status == "success":
item.status = status_machine.TransferStatus.SUCCESS.value
item.erp_document_no = result.document_no
item.external_document_no = result.document_no
item.result_code = None
attempt.status = "success"
elif result.status == "duplicate_success":
item.status = status_machine.TransferStatus.DUPLICATE_SUCCESS.value
item.erp_document_no = result.document_no
item.external_document_no = result.document_no
item.result_code = None
attempt.status = "success"
elif result.status == "result_unknown":
@@ -270,7 +282,7 @@ def _apply_write_result(item: TransferInvoiceItem, attempt: TransferAttempt, res
def _audit_item_write(item, run_no, request_id, operation_id, before_status) -> None:
"""为每次 ERP 写入追加审计事件(脱敏快照 + Hash)。"""
"""为每次 外部系统 写入追加审计事件(脱敏快照 + Hash)。"""
event = build_transfer_audit_event(
event_type="TRANSFER_ITEM_EXECUTED",
aggregate_type="transfer_item",
@@ -284,7 +296,7 @@ def _audit_item_write(item, run_no, request_id, operation_id, before_status) ->
operation_id=operation_id,
result="success" if item.status in {"success", "duplicate_success"} else "failure",
before={"status": before_status},
after={"status": item.status, "erp_document_no": item.erp_document_no},
after={"status": item.status, "external_document_no": item.external_document_no},
)
db.session.add(event)
@@ -312,7 +324,7 @@ def execute_item(*, item_id: int, deps: TransferDeps, request_id: str | None = N
def get_run(run_no: str) -> dict[str, Any]:
"""按 run_no 恢复 Run 最终结果(ERP 单号聚合 + 未生成单据异常)。"""
"""按 run_no 恢复 Run 最终结果(外部系统 单号聚合 + 未生成单据异常)。"""
run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first()
if run is None:
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
@@ -337,12 +349,13 @@ def _build_run_result(run: TransferRun) -> RunResultDTO:
invoice_no=item.invoice_no,
receipt_date=item.receipt_date,
from_warehouse=item.from_warehouse,
from_quantity=Decimal(item.erp_quantity) if item.erp_quantity else None,
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
to_warehouse=item.to_warehouse,
to_quantity=Decimal(item.receipt_quantity),
result=result,
reason=item.result_message or "",
erp_document_no=item.erp_document_no,
external_document_no=item.external_document_no,
receipt_warehouse_code=item.receipt_warehouse_code or "",
))
if result not in {"success", "duplicate_success"}:
exceptions.append(TransferExceptionDTO(
@@ -350,12 +363,12 @@ def _build_run_result(run: TransferRun) -> RunResultDTO:
invoice_no=item.invoice_no,
material_no=item.material_no,
reason=result,
facts=f"收料 {item.receipt_quantity}" + (f" / ERP {item.erp_quantity}" if item.erp_quantity else ""),
facts=f"收料 {item.receipt_quantity}" + (f" / 外部系统 {item.external_quantity}" if item.external_quantity else ""),
))
return RunResultDTO(
run_no=run.run_no,
status=run.status,
erp_documents=aggregate_erp_documents(item_dtos),
external_documents=aggregate_external_documents(item_dtos),
exceptions=tuple(exceptions),
)
@@ -365,7 +378,7 @@ def serialize_run_result(result: RunResultDTO) -> dict[str, Any]:
return {
"run_no": result.run_no,
"status": result.status,
"erp_documents": [
"external_documents": [
{
"document_no": document.document_no,
"from_warehouse": document.from_warehouse,
@@ -384,7 +397,7 @@ def serialize_run_result(result: RunResultDTO) -> dict[str, Any]:
for line in document.lines
],
}
for document in result.erp_documents
for document in result.external_documents
],
"exceptions": [
{
@@ -9,7 +9,7 @@
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from datetime import date, datetime
from decimal import Decimal
from typing import Any, Iterable, Mapping
@@ -34,6 +34,9 @@ class ParsedReceiptRow:
specification: str
receipt_date: date
receipt_quantity: Decimal
lot_no: str = ""
# 收料文件「仓库」列原值(movement 契约 warehouse_code):inventory_match 源映射行匹配键。
warehouse_code: str = ""
class ReceiptFileSchemaError(AppError):
@@ -53,6 +56,18 @@ def _fail(rows: list[dict[str, Any]], *, row_no: Any, reason: str) -> None:
rows.append({"row_no": row_no, "reason": reason})
def _is_unreceived_row(date_value: Any) -> bool:
"""判断是否为"无收料事实的在途行":无异动日期即跳过。
WMS 异动报告会携带两类无日期行,均不是可用的收料事实:
① 未收料在途 ASN(Date Received 空、Qty Received 0);
② 收料执行中(ASN Status=Executing,Qty Received 已计数但收料日期未盖章)。
收料日期是匹配身份与成熟过滤的必要字段,缺失即无法参与预检;
跳过后由下次排程抓取补齐(ASN 完成时盖章日期),不得整文件阻断。
"""
return not (isinstance(date_value, (date, datetime)) or str(date_value or "").strip())
def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]:
"""把通用异动/移动字段(doc_no/line_no/in_out_flag/material_code/...)映射为调拨解析行。
@@ -60,8 +75,9 @@ def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]])
doc_no → invoice_no(幂等/汇总键)
quantity → receipt_quantity(严格数量匹配)
movement_date → receipt_date(成熟过滤)
其余字段(material_code→material_no、material_name、warehouse_code、storage_code、
lot_no)透传/展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。
其余字段(material_code→material_no、material_name、doc_no)透传/展示保留;
warehouse_code 透传至 ParsedReceiptRow.warehouse_code(inventory_match 源路由匹配键);
storage_code 仍仅展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。
Args:
source_code: 任务来源实例(行内来源身份一致性校验)。
@@ -120,7 +136,7 @@ def _parse_rows(
projection: 调拨语义字段(invoice_no/material_no/receipt_quantity/receipt_date)
到原始行字段名的映射(如 {invoice_no: doc_no})。
Returns:
已校验的 ParsedReceiptRow 列表。
已校验的 ParsedReceiptRow 列表("无异动日期"的在途/执行中行已跳过)。
Raises:
ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
"""
@@ -137,7 +153,7 @@ def _parse_rows(
invoice_no = str(row.get(invoice_key) or "").strip()
material_no = str(row.get(material_key) or "").strip()
sheet = str(row.get("sheet") or "").strip()
receipt_date_raw = str(row.get(date_key) or "").strip()
receipt_date_value = row.get(date_key)
quantity_raw = row.get(quantity_key)
if not sheet or not row_no:
@@ -153,10 +169,12 @@ def _parse_rows(
if row_source and row_source.upper() != str(source_code).upper():
_fail(errors, row_no=row_no, reason=f"source_identity_mismatch: {row_source}")
continue
if _is_unreceived_row(receipt_date_value):
continue
try:
receipt_date = parse_date(receipt_date_raw)
receipt_date = parse_date(receipt_date_value)
except ValueError:
_fail(errors, row_no=row_no, reason=f"invalid_receipt_date: {receipt_date_raw!r}")
_fail(errors, row_no=row_no, reason=f"invalid_receipt_date: {receipt_date_value!r}")
continue
try:
quantity = validate_receipt_quantity(quantity_raw)
@@ -173,6 +191,8 @@ def _parse_rows(
specification=str(row.get("specification") or "").strip(),
receipt_date=receipt_date,
receipt_quantity=quantity,
lot_no=str(row.get("lot_no") or "").strip(),
warehouse_code=str(row.get("warehouse_code") or "").strip(),
))
if errors:
raise ReceiptFileSchemaError(rows=errors)
@@ -1,80 +0,0 @@
"""services/in_transit_transfer/gateway_adapter.py
用途:把调拨的 ERP 访问收敛为通过 Integration Connector CapabilityGateway 调用
(query_inventory 是首个配置绑定消费者)。
依赖:integration_connector.gateway / capability、erp_adapter.InventoryQuery/ErpQueryTimeoutError。
逻辑:领域只调 query_inventory 能力;外部系统差异全在连接器层。create_transfer /
verify_duplicate 留待调拨执行阶段(Phase 2)接线。
"""
from __future__ import annotations
from decimal import Decimal
from typing import Any
from app.core.errors import AppError
from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError, InventoryQuery
QUERY_INVENTORY_CAPABILITY = "in_transit_transfer.query_inventory"
class CapabilityErpAdapter:
"""把调拨 query_inventory 收敛为通过 CapabilityGateway 调用。
Args:
gateway: 可选 Gateway;缺省用 get_capability_gateway()(可注入替身测试)。
"""
def __init__(self, gateway: Any | None = None) -> None:
self._gateway = gateway
def _gateway_or_default(self):
if self._gateway is not None:
return self._gateway
from app.services.integration_connector.gateway import get_capability_gateway
return get_capability_gateway()
def query_inventory(
self,
*,
operation_id: str,
run_no: str,
attempt_no: int,
invoice_no: str,
erp_org: str,
from_warehouse: str,
to_warehouse: str,
quantity: Decimal,
) -> InventoryQuery:
"""查询外部系统库存(经连接器框架)。
Args/Raises:
与 erp_adapter.ErpAdapter.query_inventory 一致;超时→ErpQueryTimeoutError;
写失败→AppError(预检把它归为来源失败)。P1 用默认绑定(context={});
来源专属绑定待 P2/P3。
"""
result = self._gateway_or_default().call(
capability=QUERY_INVENTORY_CAPABILITY,
context={},
params={
"invoice_no": invoice_no,
"from_warehouse": from_warehouse,
"to_warehouse": to_warehouse,
"quantity": quantity,
},
operation_id=operation_id,
)
if result.status == "timeout":
raise ErpQueryTimeoutError()
if result.status != "success":
raise AppError(
code=result.error_code or "INTEGRATION.CALL_FAILED",
message=result.error_message or "query_inventory failed",
http_status=503,
retryable=False,
)
data = result.data or {}
found = bool(data.get("found"))
qty = data.get("quantity")
return InventoryQuery(found=found, quantity=Decimal(str(qty)) if qty is not None else None)
@@ -1,9 +1,9 @@
"""在途调拨 Invoice 多行汇总与冲突阻断。
"""在途调拨 Invoice 多行汇总。
用途:相同 Invoice 多行只汇总收料数量,并永久保留原始 Sheet/行号/文件版本;
同一 Invoice 出现多料号或多收料日期时整单阻断(InvoiceConflictError)。
用途:相同 Invoice+料号+收料日期 的多行只汇总收料数量,并永久保留原始
Sheet/行号/文件版本;同 Invoice 跨料号或跨日期自然拆分为多张发票。
依赖:app.core.errors.AppError、contracts.RawLineRefDTO。
逻辑:汇总键 (source_code, invoice_no);冲突判定基于料号与收料日期。
逻辑:汇总键 (source_code, invoice_no, material_no, receipt_date)。
"""
from __future__ import annotations
@@ -30,6 +30,9 @@ class AggregatedInvoice:
receipt_date: date
receipt_quantity: Decimal
raw_lines: tuple[RawLineRefDTO, ...]
lot_no: str = ""
# 组内首行收料仓库值(movement 契约 warehouse_code):inventory_match 源路由匹配键。
warehouse_code: str = ""
class InvoiceConflictError(AppError):
@@ -45,34 +48,25 @@ class InvoiceConflictError(AppError):
def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str = "v1") -> list[AggregatedInvoice]:
"""按 Invoice 汇总收料数量并保留原始行证据。
"""按 Invoice+料号+收料日期 汇总收料数量并保留原始行证据。
汇总键 (source_code, invoice_no, material_no, receipt_date):Invoice 语义为
调拨拨出单据号(如 WMS 的 External ASN #);同单号跨料号或跨收料日期时
自然拆分为多张发票(部分交付场景),不做整单阻断。
Args:
rows: 已校验的解析行。
file_version: 当前文件版本(写入原始行追溯)。
Returns:
汇总后的 Invoice 列表(按 Invoice 排序)。
Raises:
InvoiceConflictError: 同一 Invoice 多料号或多收料日期。
汇总后的 Invoice 列表(按汇总键排序)。
"""
grouped: dict[tuple[str, str], list[ParsedReceiptRow]] = {}
grouped: dict[tuple[str, str, str, date], list[ParsedReceiptRow]] = {}
for row in rows:
grouped.setdefault((row.source_code, row.invoice_no), []).append(row)
grouped.setdefault(
(row.source_code, row.invoice_no, row.material_no, row.receipt_date), [],
).append(row)
invoices: list[AggregatedInvoice] = []
for (source_code, invoice_no), group in sorted(grouped.items()):
material_nos = {row.material_no for row in group}
dates = {row.receipt_date for row in group}
if len(material_nos) > 1:
raise InvoiceConflictError(
invoice_no=invoice_no,
conflict=f"multiple_material_no: {sorted(material_nos)}",
)
if len(dates) > 1:
raise InvoiceConflictError(
invoice_no=invoice_no,
conflict=f"multiple_receipt_date: {sorted(str(item) for item in dates)}",
)
for (source_code, invoice_no, material_no, receipt_date), group in sorted(grouped.items()):
first = group[0]
raw_lines = tuple(
RawLineRefDTO(sheet=row.sheet, row_no=row.row_no, file_version=file_version)
@@ -81,11 +75,13 @@ def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str =
invoices.append(AggregatedInvoice(
source_code=source_code,
invoice_no=invoice_no,
material_no=first.material_no,
material_no=material_no,
material_name=first.material_name,
specification=first.specification,
receipt_date=first.receipt_date,
receipt_date=receipt_date,
receipt_quantity=sum((row.receipt_quantity for row in group), Decimal("0")),
raw_lines=raw_lines,
lot_no=first.lot_no,
warehouse_code=first.warehouse_code,
))
return invoices
@@ -41,6 +41,8 @@ class MovementField:
# 定死的 10 个通用异动字段(领域契约,不配置化)。
# [PROMPT_UPDATE] 2026-09-21:Invoice 保持锚定单号(doc_no,WMS 收料单号);
# 批号(lot_no)为展示维度——预检列「拨出/拨入批号」由 lot_no 经 WTP→HOW 转换派生。
MOVEMENT_FIELDS: tuple[MovementField, ...] = (
MovementField("doc_no", "单号", MovementFieldValueType.TEXT, is_identity=True, required=True),
MovementField("line_no", "项次", MovementFieldValueType.TEXT),
@@ -4,9 +4,11 @@
用该来源收料配置绑定的 movement 解析规则(purpose='movement',端点=定死
领域字段 MOVEMENT_FIELDS)的 field_mapping 把列映射为领域行,产出 ReadyReceiptFile。
依赖:ShippingReceiptReportFile / ShippingReceiptReportConfig / file_asset_storage、
movement_contract、openpyxl。
逻辑:按来源取最新未过期(未清理)收料文件;无绑定 movement profile 或文件缺失时
返回 None(fail-closed),绝不伪造 ready 文件。行完整校验由下游 file_parser 完成。
movement_contract、receipt_file_gate(可用性门禁)、openpyxl。
逻辑:按来源取最新【当天(业务日)抓取】且未过期(未清理)的收料文件;无绑定规则、
文件缺失或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域
字段 + 溯源字段(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整
校验由下游 file_parser 完成。
"""
from __future__ import annotations
@@ -16,6 +18,7 @@ from typing import Any, Mapping
from app.services.file_assets.storage import file_asset_storage
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile
from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition
class ShippingReceiptFileRepository:
@@ -25,20 +28,21 @@ class ShippingReceiptFileRepository:
self._storage = file_asset_storage
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
"""返回该来源最新未过期收料文件;无绑定规则或文件缺失时返回 None。
"""返回该来源最新且当天(业务日)抓取的未过期收料文件;否则返回 None。
Args:
source_code: 来源实例编码。
business_date: 业务日期(用于展示/匹配成熟度,不强制匹配文件日期)。
Returns:
ReadyReceiptFile(rows 为领域字段名 dict)或 None。
ReadyReceiptFile(rows 为领域字段 + 溯源 sheet/row_no 的 dict)或 None。
新鲜度/保留期/缺失均 fail-closed 返回 None(fail 消息由上游触发重抓)。
"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptReportFile
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
return None
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id, enabled=True).first()
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
if config is None or config.parsing_profile_id is None:
return None
profile = config.parsing_profile
@@ -50,7 +54,8 @@ class ShippingReceiptFileRepository:
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
ShippingReceiptReportFile.archive_deleted_at.is_(None),
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)单一事实来源见 receipt_file_gate。
usable_receipt_file_condition(),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.first()
@@ -85,7 +90,8 @@ def _extract_movement_rows(
"""从 xlsx 字节按 movement field_mapping 提取领域行 dict。
field_mapping: {定死领域字段 code: Excel 表头别名}(端点必须是 MOVEMENT_FIELDS 的 code)。
输出以领域字段 code 为 key 的行,供 file_parser.parse_movement_rows 校验。
输出以领域字段 code 为 key 的行,并附带溯源字段(sheet=实际使用的工作表标题、
row_no=数据行在工作表中的真实 1-based 行号),供 file_parser.parse_movement_rows 校验。
"""
from openpyxl import load_workbook
from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index
@@ -111,15 +117,32 @@ def _extract_movement_rows(
headers = [str(c or '').strip() for c in raw_rows[header_idx]]
data_rows = [list(r) for r in raw_rows[header_idx + 1:] if r]
header_to_code = {str(alias).strip(): str(code).strip() for code, alias in field_mapping.items()}
return [_map_header_row(headers, row, header_to_code) for row in data_rows]
header_to_code: dict[str, list[str]] = {}
for code, alias in field_mapping.items():
# 一个表头别名可被多个领域字段共用(如 CRANE 单号/批号同源 ASN 列);
# 反查必须是 一别名→多字段,不得互相覆盖。
header_to_code.setdefault(str(alias).strip(), []).append(str(code).strip())
# 溯源字段:sheet 取实际使用的工作表标题;row_no 为数据行在工作表中的真实
# 1-based 行号(表头在第 header_idx+1 行,第 offset 个数据行 = header_idx+2+offset),
# 使下游 RawLineRef 证据引用指向真实电子表格行,并满足 parse_movement_rows 行校验。
sheet_title = str(ws.title or '').strip()
return [
{"sheet": sheet_title, "row_no": header_idx + 2 + offset,
**_map_header_row(headers, row, header_to_code)}
for offset, row in enumerate(data_rows)
]
def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str, str]) -> dict[str, Any]:
"""把一行原始单元格按表头别名映射为定死领域字段 dict。"""
def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str, list[str]]) -> dict[str, Any]:
"""把一行原始单元格按表头别名映射为定死领域字段 dict。
header_to_code 为 一别名→多字段 列表:共用同一表头别名的字段
(如 doc_no 与 lot_no 同源一列)各自都写入该单元格值,互不覆盖。
"""
output: dict[str, Any] = {}
for index, header in enumerate(headers):
code = header_to_code.get(header)
if code and index < len(row):
output[code] = row[index]
codes = header_to_code.get(header)
if codes and index < len(row):
for code in codes:
output[code] = row[index]
return output
@@ -1,9 +1,9 @@
"""在途调拨企业微信汇总通知。
用途:每个非空 Run 恰好一条汇总通知;空数据不通知;通知失败记录
notification_failed 且不改变 ERP 业务结果(run.status 保持)。
notification_failed 且不改变 外部系统 业务结果(run.status 保持)。
依赖:models、audit、typing.Protocol。
逻辑:通知状态独立于 ERP 状态;已成功投递幂等(每个 Run 一条)。
逻辑:通知状态独立于 外部系统 状态;已成功投递幂等(每个 Run 一条)。
"""
from __future__ import annotations
@@ -65,7 +65,7 @@ def notify_run_summary(*, run_no: str, sender: WeComSender, recipients: list[str
if failed:
run.notification_error_code = str(outcome.get("error_code") or "WECOM_SEND_FAILED")
run.notification_error_message = str(outcome.get("error_message") or "")
# 关键:通知失败绝不修改 run.status(ERP 业务结果保持)。
# 关键:通知失败绝不修改 run.status(外部系统 业务结果保持)。
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_NOTIFICATION",
aggregate_type="transfer_run",
@@ -1,10 +1,10 @@
"""在途调拨预检服务。
用途:编排"文件准备 → 解析 → Invoice 汇总 → D+1 成熟过滤 → ERP 库存查询 →
用途:编排"文件准备 → 解析 → Invoice 汇总 → D+1 成熟过滤 → 外部系统 库存查询 →
严格数量匹配 → 预检快照与 Hash",并支持预检进度恢复(restore)。
依赖:file_preparation / file_parser / invoice_aggregator / erp_adapter /
依赖:file_preparation / file_parser / invoice_aggregator / capability_client /
date_policy / quantity / contracts / audit / models。
逻辑:来源实例独立处理,任一来源失败不阻断其他来源;当天收料不查询 ERP;
逻辑:来源实例独立处理,任一来源失败不阻断其他来源;当天收料不查询 外部系统;
预检 Hash 由冻结快照复算;create_precheck 落库 Run + Precheck + Items。
"""
@@ -29,14 +29,17 @@ from app.services.in_transit_transfer.contracts import (
)
from app.services.in_transit_transfer.date_policy import (
MATURITY_ELIGIBLE,
eligible_receipt_date_to,
MATURITY_FUTURE,
MATURITY_NOT_MATURED,
maturity_status,
parse_date,
)
from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError
from app.services.in_transit_transfer.capability_client import ExternalQueryTimeoutError, StockTarget
from app.services.in_transit_transfer.file_parser import (
ParsedReceiptRow,
ReceiptFileSchemaError,
parse_movement_rows,
parse_receipt_rows,
)
from app.services.in_transit_transfer.file_preparation import (
@@ -46,7 +49,6 @@ from app.services.in_transit_transfer.file_preparation import (
ensure_receipt_file_ready,
)
from app.services.in_transit_transfer.invoice_aggregator import (
InvoiceConflictError,
aggregate_invoices,
)
from app.services.in_transit_transfer.quantity import classify_quantity_match
@@ -54,6 +56,13 @@ from app.services.in_transit_transfer.strategy import (
TransferStrategyPolicy,
default_strategy,
)
from app.services.in_transit_transfer.transfer_type import (
TransferType,
ensure_transfer_type_supported,
filter_invoices_for_type,
normalize_transfer_type,
transfer_type_scope_note,
)
ROUTE_NOT_RESOLVED_CODE = "TRANSFER.ROUTE_NOT_RESOLVED"
@@ -63,14 +72,15 @@ RESULT_NOT_MATURED = "not_matured"
RESULT_QUANTITY_MISMATCH = "blocked_quantity_mismatch"
RESULT_INVENTORY_NOT_FOUND = "blocked_inventory_not_found"
RESULT_FUTURE_DATE = "blocked_future_date"
RESULT_ERP_QUERY_TIMEOUT = "erp_query_timeout"
RESULT_EXTERNAL_QUERY_FAILED = "blocked_external_query_failed"
RESULT_EXTERNAL_QUERY_TIMEOUT = "external_query_timeout"
@dataclass(frozen=True)
class RouteMapping:
"""来源路由:ERP 组织 / 拨出仓(ERP 在途仓)/ 拨入仓(ERP 映射仓)。"""
"""来源路由:外部组织(external_org,取自仓库映射)/ 拨出仓(外部在途仓)/ 拨入仓(映射仓)。"""
erp_org: str
external_org: str
from_warehouse: str
to_warehouse: str
@@ -90,8 +100,8 @@ class RouteNotResolvedError(AppError):
class RouteResolver(Protocol):
"""来源路由解析协议(路由归属规则冻结前由 Fake/门禁兜底)。"""
def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping:
"""返回 Invoice 的路由;无法归属时抛 RouteNotResolvedError。"""
def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
"""返回 Invoice 的路由(warehouse_code 为收料文件仓库列,inventory_match 源匹配键);无法归属时抛 RouteNotResolvedError。"""
@dataclass(frozen=True)
@@ -123,7 +133,7 @@ class TransferDeps:
file_repository: ReceiptFileRepository
rpa_trigger: RpaTrigger
route_resolver: RouteResolver
erp: Any
capabilities: Any
strategy: TransferStrategyPolicy = field(default_factory=default_strategy)
@@ -143,22 +153,40 @@ def run_precheck(
deps: TransferDeps,
active_source_job_key: str | None = None,
run_no: str = "RUN-PENDING",
receipt_date_from: str | None = None,
receipt_date_to: str | None = None,
transfer_type: TransferType | str | None = None,
) -> PrecheckRunResult:
"""执行一次只读预检(不写 ERP)。
"""执行一次只读预检(不写 外部系统)。
Args:
source_codes: 来源实例列表(DBS/Crane 仅分组,实例为执行边界)。
business_date: 业务日期 T(YYYY-MM-DD)。
deps: 注入的文件仓库 / RPA / 路由 / ERP 依赖。
deps: 注入的文件仓库 / RPA / 路由 / 外部系统 依赖。
active_source_job_key: 活动 Source Job 键(缺文件时绑定已有任务)。
run_no: Run 编号(创建 Run 前可为占位)。
receipt_date_from / receipt_date_to: 可选收料日期查询范围。
transfer_type: 调拨业务类型(缺省在途仓至HUB仓);类型决定收料数据范围。
Returns:
PrecheckRunResult(摘要 + 明细 + 来源进度)。
Raises:
ValidationError: source_codes 为空。
ValidationError: source_codes 为空、日期范围非法或调拨类型非法/未支持。
"""
if not source_codes:
raise ValidationError("source_codes is required")
resolved_transfer_type = normalize_transfer_type(transfer_type)
ensure_transfer_type_supported(resolved_transfer_type)
# [日期范围] 可选收料日期过滤;卡控:截止不得超出 D+1 规则(业务日期-1),起始不得晚于截止。
range_from = parse_date(receipt_date_from) if receipt_date_from else None
range_to = parse_date(receipt_date_to) if receipt_date_to else None
if range_from and range_to and range_from > range_to:
raise ValidationError(
"receipt date range is invalid", code="TRANSFER.RECEIPT_DATE_RANGE_INVALID",
)
if range_to and range_to > eligible_receipt_date_to(business_date):
raise ValidationError(
"receipt date range end exceeds D+1 maturity limit", code="TRANSFER.RECEIPT_DATE_RANGE_INVALID",
)
validate_strategy = deps.strategy
sources: list[SourceProgressDTO] = []
@@ -188,8 +216,17 @@ def run_precheck(
"file_version": ready_file.file_version,
"checksum": ready_file.checksum,
}
parsed = parse_receipt_rows(source_code=source_code, rows=ready_file.rows)
# 真实仓库(movement_file_repository)产出 movement 领域字段行
# (doc_no/material_code/quantity/movement_date),按异动解析规则映射校验。
parsed = parse_movement_rows(source_code=source_code, rows=ready_file.rows)
invoices = aggregate_invoices(parsed, file_version=ready_file.file_version)
if range_from is not None:
invoices = [invoice for invoice in invoices if invoice.receipt_date >= range_from]
if range_to is not None:
invoices = [invoice for invoice in invoices if invoice.receipt_date <= range_to]
# [调拨类型] 类型决定收料数据范围(如类型1仅保留 INVOICE 前缀 HOM/HOX/WTP),
# 范围外票与日期范围过滤同语义:静默排除、不入明细、不阻断来源。
invoices = filter_invoices_for_type(invoices, resolved_transfer_type)
source_items = _precheck_invoices(
invoices=invoices,
source_code=source_code,
@@ -206,7 +243,7 @@ def run_precheck(
file_version=ready_file.file_version,
checksum=ready_file.checksum,
))
except (ReceiptFileSchemaError, InvoiceConflictError) as exc:
except ReceiptFileSchemaError as exc:
sources.append(SourceProgressDTO(
source_code=source_code, stage="failed",
error_code=exc.code, error_message=exc.message,
@@ -238,6 +275,7 @@ def run_precheck(
snapshot = {
"scope": sorted(set(source_codes)),
"business_date": business_date,
"transfer_type": resolved_transfer_type.value,
"file_snapshot": file_snapshot,
"counts": {
"file_invoice_count": counts.file_invoice_count,
@@ -253,7 +291,7 @@ def run_precheck(
"from_warehouse": item.from_warehouse,
"to_warehouse": item.to_warehouse,
"receipt_quantity": str(item.to_quantity),
"erp_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
"external_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
"result": item.result,
}
for item in items
@@ -271,7 +309,7 @@ def run_precheck(
expires_at="",
counts=counts,
estimated_transfer_quantity=str(estimated_quantity),
estimated_erp_write_count=counts.executable_count,
estimated_external_write_count=counts.executable_count,
precheck_hash=precheck_hash,
)
return PrecheckRunResult(summary=summary, items=tuple(items), sources=sources_tuple)
@@ -286,8 +324,12 @@ def _precheck_invoices(
deps: TransferDeps,
run_no: str,
) -> list[PrecheckInvoiceItemDTO]:
"""对单个来源的汇总 Invoice 逐项预检(成熟过滤 → 路由 → ERP → 匹配)。"""
"""对单个来源的汇总 Invoice 预检(成熟过滤 → 路由 → 按组织分组批量查 外部系统 → 匹配)。"""
output: list[PrecheckInvoiceItemDTO] = []
# [STEP 1] 成熟过滤与路由解析(不查询):未成熟/未来日期直接落位,
# 成熟项按 external_org(仓库映射的外部组织)分组,每组合并为一次批量查询。
matured: list[tuple[Any, RouteMapping, tuple[RawLineRefDTO, ...], str]] = []
for invoice in invoices:
maturity = maturity_status(invoice.receipt_date, business_date)
raw = tuple(
@@ -299,10 +341,11 @@ def _precheck_invoices(
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
from_warehouse="", from_quantity=None,
to_warehouse="", to_quantity=invoice.receipt_quantity,
result=RESULT_NOT_MATURED, reason="receipt not matured until next business day",
receipt_warehouse_code=invoice.warehouse_code or "",
raw_lines=raw,
))
continue
@@ -310,61 +353,98 @@ def _precheck_invoices(
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
from_warehouse="", from_quantity=None,
to_warehouse="", to_quantity=invoice.receipt_quantity,
result=RESULT_FUTURE_DATE, reason="future receipt date",
receipt_warehouse_code=invoice.warehouse_code or "",
raw_lines=raw,
))
continue
route = deps.route_resolver.resolve(source_code=source_code, invoice_no=invoice.invoice_no)
route = deps.route_resolver.resolve(
source_code=source_code, invoice_no=invoice.invoice_no,
warehouse_code=invoice.warehouse_code or "",
)
matured.append((invoice, route, raw, receipt_date_iso))
groups: dict[str, list[tuple[Any, RouteMapping, tuple[RawLineRefDTO, ...], str]]] = {}
for entry in matured:
groups.setdefault(entry[1].external_org, []).append(entry)
# [STEP 2] 每个组织一次批量查询(targets = 料号+拨出库位+拨出批号 元组列表),
# 组内逐票按三元组精确匹配库存数量;组级故障降级到组内全部票,不炸整来源。
for external_org, entries in groups.items():
targets = [
StockTarget(material_no=invoice.material_no, from_warehouse=route.from_warehouse, lot_no=invoice.lot_no)
for invoice, route, _, _ in entries
]
operation_id = f"op-{uuid.uuid4().hex[:12]}"
try:
query = deps.erp.query_inventory(
operation_id=operation_id,
run_no=run_no,
attempt_no=1,
invoice_no=invoice.invoice_no,
erp_org=route.erp_org,
from_warehouse=route.from_warehouse,
to_warehouse=route.to_warehouse,
quantity=invoice.receipt_quantity,
stock = deps.capabilities.query_stock(
operation_id=operation_id, external_org=external_org, targets=targets,
)
except ErpQueryTimeoutError:
except ExternalQueryTimeoutError:
for invoice, route, raw, receipt_date_iso in entries:
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
from_quantity=None, to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
result=RESULT_EXTERNAL_QUERY_TIMEOUT, reason="external query timeout",
receipt_warehouse_code=invoice.warehouse_code or "",
raw_lines=raw,
))
continue
except Exception as exc: # noqa: BLE001 —— 网关/绑定层故障降级为整组阻断,不炸整来源
# [语义] 绑定缺失、连接失败等基础设施故障是环境问题而非业务阻断:
# 组内逐票给 blocked_external_query_failed + 原因,预检列表保持可见可解释。
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
for invoice, route, raw, receipt_date_iso in entries:
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
from_quantity=None, to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
result=RESULT_EXTERNAL_QUERY_FAILED, reason=f"external query failed: {detail}",
receipt_warehouse_code=invoice.warehouse_code or "",
raw_lines=raw,
))
continue
for invoice, route, raw, receipt_date_iso in entries:
stock_qty = stock.lookup(
material_no=invoice.material_no, from_warehouse=route.from_warehouse, lot_no=invoice.lot_no,
)
if stock_qty is None:
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
# 查无库存记录也是外部系统的真实答复:库存数按 0 展示(而非"-"),
# 避免用户误以为查询失败;分类仍为 blocked_inventory_not_found。
from_quantity=Decimal("0"), to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
result=RESULT_INVENTORY_NOT_FOUND, reason="external inventory not found",
receipt_warehouse_code=invoice.warehouse_code or "",
raw_lines=raw,
))
continue
match = classify_quantity_match(invoice.receipt_quantity, stock_qty)
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
from_quantity=None, to_warehouse=route.to_warehouse,
from_quantity=stock_qty, to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
result=RESULT_ERP_QUERY_TIMEOUT, reason="erp query timeout",
result=match, reason="" if match == RESULT_EXECUTABLE else "strict quantity mismatch",
receipt_warehouse_code=invoice.warehouse_code or "",
raw_lines=raw,
))
continue
if not query.found:
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
from_quantity=None, to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
result=RESULT_INVENTORY_NOT_FOUND, reason="erp inventory not found",
raw_lines=raw,
))
continue
match = classify_quantity_match(invoice.receipt_quantity, query.quantity)
output.append(PrecheckInvoiceItemDTO(
source_code=source_code, material_no=invoice.material_no,
material_name=invoice.material_name, specification=invoice.specification,
invoice_no=invoice.invoice_no, receipt_date=receipt_date_iso,
from_warehouse=route.from_warehouse,
from_quantity=query.quantity, to_warehouse=route.to_warehouse,
to_quantity=invoice.receipt_quantity,
result=match, reason="" if match == RESULT_EXECUTABLE else "strict quantity mismatch",
raw_lines=raw,
))
return output
@@ -374,7 +454,7 @@ def _item_status(result: str) -> str:
RESULT_EXECUTABLE: status_machine.TransferStatus.READY_TO_EXECUTE.value,
RESULT_NOT_MATURED: status_machine.TransferStatus.NOT_MATURED.value,
RESULT_FUTURE_DATE: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
RESULT_ERP_QUERY_TIMEOUT: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
RESULT_EXTERNAL_QUERY_TIMEOUT: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
RESULT_QUANTITY_MISMATCH: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
RESULT_INVENTORY_NOT_FOUND: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
}
@@ -393,20 +473,29 @@ def create_precheck(
business_date: str,
deps: TransferDeps,
active_source_job_key: str | None = None,
receipt_date_from: str | None = None,
receipt_date_to: str | None = None,
transfer_type: TransferType | str | None = None,
) -> PrecheckSummaryDTO:
"""运行预检并落库 TransferRun + TransferPrecheck + InvoiceItems。
Args:
source_codes / business_date / deps: 同 run_precheck。
receipt_date_from / receipt_date_to / transfer_type: 同 run_precheck。
Returns:
预检摘要(precheck_id 已回填)。
"""
resolved_transfer_type = normalize_transfer_type(transfer_type)
ensure_transfer_type_supported(resolved_transfer_type)
run_no = _generate_no("RUN", business_date)
result = run_precheck(
source_codes=source_codes,
business_date=business_date,
deps=deps,
active_source_job_key=active_source_job_key,
receipt_date_from=receipt_date_from,
receipt_date_to=receipt_date_to,
transfer_type=resolved_transfer_type,
run_no=run_no,
)
now = datetime.utcnow()
@@ -417,6 +506,7 @@ def create_precheck(
status="prechecking",
source_codes_json=list(source_codes),
counts_json=asdict(result.summary.counts),
transfer_type=resolved_transfer_type.value,
)
db.session.add(run)
db.session.flush()
@@ -434,6 +524,8 @@ def create_precheck(
run_id=run.id,
source_code=job_source.source_code,
status=job_source.stage if job_source.stage in _valid_job_statuses else 'pending',
error_code=job_source.error_code,
error_message=job_source.error_message,
)
precheck_no = _generate_no("TPC", business_date)
@@ -442,7 +534,13 @@ def create_precheck(
run_id=run.id,
business_date=business_date,
status=result.summary.status,
scope_json={"source_codes": list(source_codes)},
scope_json={
"source_codes": list(source_codes),
"receipt_date_from": receipt_date_from,
"receipt_date_to": receipt_date_to,
"transfer_type": resolved_transfer_type.value,
"transfer_type_scope": transfer_type_scope_note(resolved_transfer_type),
},
file_snapshot_json={
stage.source_code: {
"file_no": stage.file_no,
@@ -456,34 +554,65 @@ def create_precheck(
strategy_version="v0",
counts_json=asdict(result.summary.counts),
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
estimated_erp_write_count=result.summary.estimated_erp_write_count,
estimated_external_write_count=result.summary.estimated_external_write_count,
precheck_hash=result.summary.precheck_hash,
expires_at=now + timedelta(seconds=deps.strategy.confirm_ttl_seconds),
)
db.session.add(precheck)
db.session.flush()
# [幂等] 相同 (来源,单号,料号,收料日期) 的重复预检不得累加异常行:
# 非终态行原地刷新并挂到最新预检;终态行(已执行/人工关闭等)保持既定事实不复活。
_terminal_item_statuses = {
status_machine.TransferStatus.SUCCESS.value,
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
status_machine.TransferStatus.MANUALLY_CLOSED.value,
status_machine.TransferStatus.CANCELLED.value,
status_machine.TransferStatus.EXECUTING.value,
}
for item in result.items:
fields = {
"precheck_id": precheck.id,
"status": _item_status(item.result),
"result_code": item.result if item.result != RESULT_EXECUTABLE else None,
"result_message": item.reason or None,
"from_warehouse": item.from_warehouse or "",
"to_warehouse": item.to_warehouse or "",
"receipt_quantity": str(item.to_quantity),
"external_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
"lot_no": item.lot_no or "",
"receipt_warehouse_code": item.receipt_warehouse_code or "",
"raw_lines_json": [
{"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version}
for line in item.raw_lines
],
}
# 禁 autoflush:避免本批 pending 插入在查询时提前落库(应随循环末统一 commit)。
with db.session.no_autoflush:
existing = (
TransferInvoiceItem.query.filter_by(
source_code=item.source_code,
invoice_no=item.invoice_no,
material_no=item.material_no,
receipt_date=item.receipt_date,
)
.order_by(TransferInvoiceItem.id.desc())
.first()
)
if existing is not None:
if existing.status not in _terminal_item_statuses:
for attr, value in fields.items():
setattr(existing, attr, value)
continue
# 预检阶段不绑定执行 Run(run_id 在执行 Run 创建时由 orchestrator 关联)。
db.session.add(TransferInvoiceItem(
precheck_id=precheck.id,
# 预检阶段不绑定执行 Run(run_id 在执行 Run 创建时由 orchestrator 关联)。
source_code=item.source_code,
invoice_no=item.invoice_no,
material_no=item.material_no,
material_name=item.material_name,
specification=item.specification,
receipt_date=item.receipt_date,
from_warehouse=item.from_warehouse or "",
to_warehouse=item.to_warehouse or "",
receipt_quantity=str(item.to_quantity),
erp_quantity=str(item.from_quantity) if item.from_quantity is not None else None,
status=_item_status(item.result),
result_code=item.result if item.result != RESULT_EXECUTABLE else None,
result_message=item.reason or None,
raw_lines_json=[
{"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version}
for line in item.raw_lines
],
**fields,
))
db.session.commit()
@@ -495,7 +624,7 @@ def create_precheck(
expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "",
counts=result.summary.counts,
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
estimated_erp_write_count=result.summary.estimated_erp_write_count,
estimated_external_write_count=result.summary.estimated_external_write_count,
precheck_hash=result.summary.precheck_hash,
)
return summary
@@ -531,7 +660,7 @@ def restore_precheck(precheck_id: str) -> dict[str, Any]:
expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "",
counts=counts,
estimated_transfer_quantity=precheck.estimated_transfer_quantity or "0",
estimated_erp_write_count=int(precheck.estimated_erp_write_count or 0),
estimated_external_write_count=int(precheck.estimated_external_write_count or 0),
precheck_hash=precheck.precheck_hash,
)
items = []
@@ -542,13 +671,19 @@ def restore_precheck(precheck_id: str) -> dict[str, Any]:
material_name=item.material_name,
specification=item.specification,
invoice_no=item.invoice_no,
receipt_date=item.receipt_date,
lot_no=item.lot_no or "",
receipt_warehouse_code=item.receipt_warehouse_code or "",
from_warehouse=item.from_warehouse,
from_quantity=Decimal(item.erp_quantity) if item.erp_quantity else None,
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
to_warehouse=item.to_warehouse,
to_quantity=Decimal(item.receipt_quantity),
result=item.result_code or (
RESULT_EXECUTABLE if item.status == "ready_to_execute" else item.status
),
# 失败原因落库于 result_message(预检/重查降级均写);restore 不回读则
# 前端刷新后原因恒为空,呈现「安静阻断」无法排查。
reason=item.result_message or "",
raw_lines=tuple(
RawLineRefDTO(
sheet=line.get("sheet", ""),
@@ -565,6 +700,8 @@ def restore_precheck(precheck_id: str) -> dict[str, Any]:
file_no=job.file_no,
file_version=None,
checksum=job.file_sha256,
error_code=job.error_code,
error_message=job.error_message,
)
for job in (precheck.run.source_jobs if precheck.run else [])
] or [
@@ -1,6 +1,6 @@
"""在途调拨严格数量门禁。
用途:实现"收料数量 == ERP 账面库存 才可执行"的精确匹配规则,
用途:实现"收料数量 == 外部系统 账面库存 才可执行"的精确匹配规则,
禁止部分调拨、数量容差与隐式截断。
依赖:标准库 decimal。
逻辑:所有比较基于 Decimal 精确语义;非法数量(0/负数/非数字)在解析层拒绝。
@@ -45,17 +45,17 @@ def strict_quantities_equal(left: Any, right: Any) -> bool:
return Decimal(str(left)) == Decimal(str(right))
def classify_quantity_match(receipt_quantity: Any, erp_quantity: Any | None) -> str:
def classify_quantity_match(receipt_quantity: Any, external_quantity: Any | None) -> str:
"""按严格相等规则分类数量匹配结果。
Args:
receipt_quantity: 收料数量。
erp_quantity: ERP 账面库存;None 表示无库存。
external_quantity: 外部系统 账面库存;None 表示无库存。
Returns:
'executable' | 'blocked_quantity_mismatch' | 'blocked_inventory_not_found'。
"""
if erp_quantity is None:
if external_quantity is None:
return MATCH_INVENTORY_NOT_FOUND
if strict_quantities_equal(receipt_quantity, erp_quantity):
if strict_quantities_equal(receipt_quantity, external_quantity):
return MATCH_EXECUTABLE
return MATCH_QUANTITY_MISMATCH
Loaded 100 of 691 files, more files were not shown because too many files have changed in this diff. Show more