Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c48329d4e | ||
|
|
a10ecc8073 | ||
|
|
79050d02ba | ||
|
|
f5611d6783 | ||
|
|
70c7f03a5a | ||
|
|
440afe097f | ||
|
|
dfd48e08e7 | ||
|
|
00c52fdaae | ||
|
|
0331029ead | ||
|
|
b032bb6729 | ||
|
|
5d0a79f5fb | ||
|
|
3bb9938c05 | ||
|
|
fa5d316b25 | ||
|
|
95e7db0831 | ||
|
|
724cd74043 | ||
|
|
d3204f1db8 | ||
|
|
bce589eb96 | ||
|
|
31434f8424 | ||
|
|
e15b7b1ac2 | ||
|
|
663f401873 | ||
|
|
627da80e65 | ||
|
|
5a269f940d | ||
|
|
b69c725992 | ||
|
|
331a983476 | ||
|
|
4c2a7e2a23 | ||
|
|
11cfedcc62 | ||
|
|
55e56e4dc9 | ||
|
|
a5d7085c08 | ||
|
|
cdc8610ec1 | ||
|
|
911afa0f73 | ||
|
|
39fe3c05f2 | ||
|
|
ffc0d4a430 | ||
|
|
bf3154033b | ||
|
|
8102a1fe44 | ||
|
|
9236f2949c | ||
|
|
47ff0107bd | ||
|
|
050987692a | ||
|
|
6c47d0639c | ||
|
|
19d6b234ea | ||
|
|
43dceaf027 | ||
|
|
fc42bb14c9 | ||
|
|
e4100815a0 | ||
|
|
3a19f9c27d | ||
|
|
52c71ee46a | ||
|
|
28d6085d07 | ||
|
|
68c944607c | ||
|
|
22bee49346 | ||
|
|
4225ed4d0b | ||
|
|
d75f2e7d86 | ||
|
|
c27379d933 | ||
|
|
89b32bcdb5 | ||
|
|
b8fe089b3d | ||
|
|
f7734c8ccb | ||
|
|
9eb3749888 | ||
|
|
3e8b12b954 | ||
|
|
dde2093e06 | ||
|
|
f67fa6f09f | ||
|
|
6502f73cb5 | ||
|
|
e78f750db0 | ||
|
|
5746b1d220 | ||
|
|
1a2753d3b5 | ||
|
|
1efb165fd5 | ||
|
|
01ae63901a | ||
|
|
2250ac98e6 | ||
|
|
47ee68ed25 | ||
|
|
06c77d40c7 | ||
|
|
5f9df244c0 | ||
|
|
97059b336b | ||
|
|
9f132564d6 | ||
|
|
3b53a2219c | ||
|
|
a92df4c38d | ||
|
|
5f6fbcd76f | ||
|
|
d7d4819a42 | ||
|
|
92ed140739 | ||
|
|
041bb73b9a | ||
|
|
5187b6105b | ||
|
|
570d1c605c | ||
|
|
af2658e244 | ||
|
|
6ac2effac3 | ||
|
|
c305d0544b | ||
|
|
5879871ade | ||
|
|
b8cc0cbe77 | ||
|
|
4a726fe8b2 | ||
|
|
f38e940e3c | ||
|
|
ea94fb28db | ||
|
|
7e7bcbd388 | ||
|
|
28b4a428ef | ||
|
|
e181d4e9ec | ||
|
|
8c97d5ed21 | ||
|
|
e38e5a63fe | ||
|
|
d95c4dc086 | ||
|
|
a8d721e793 | ||
|
|
8cd8012632 | ||
|
|
91a4bcbb8b | ||
|
|
02af2c9599 | ||
|
|
86fc8a2c06 | ||
|
|
34c3bfb254 | ||
|
|
386f93108c | ||
|
|
4e97553f42 | ||
|
|
91a4bd538d | ||
|
|
ffbcb93b2e | ||
|
|
e8d9dba8a3 | ||
|
|
239d373503 | ||
|
|
d57ecc62f9 | ||
|
|
c5b7cc662b | ||
|
|
abde3de71d | ||
|
|
f4edec6e07 | ||
|
|
fe5191b38a | ||
|
|
444a7482e3 | ||
|
|
83e0bad22f | ||
|
|
20122ce6d3 | ||
|
|
a3078a4415 | ||
|
|
9adb3ec077 | ||
|
|
64afe94924 | ||
|
|
ebd27ccfa7 | ||
|
|
ce4b69eb7c | ||
|
|
3bfd881c4f | ||
|
|
5b7e0d5f87 | ||
|
|
aed076046a | ||
|
|
d004a141f2 | ||
|
|
6ad93e829c | ||
|
|
425ed43649 | ||
|
|
5ede1cbcc4 | ||
|
|
22b05c91a2 | ||
|
|
d2e7eb678a | ||
|
|
f723732eb5 | ||
|
|
f0ac888d60 | ||
|
|
594d9c22b5 | ||
|
|
d635a2920c | ||
|
|
6cf71679b7 | ||
|
|
abf3d48927 | ||
|
|
821bd0a62c | ||
|
|
e87dca85a3 | ||
|
|
42d8b70250 | ||
|
|
a1828f75e6 | ||
|
|
2065b73610 | ||
|
|
863e009b59 | ||
|
|
14e5af0c9c | ||
|
|
d4cb8c5def | ||
|
|
5faf86b184 | ||
|
|
298fadf1c8 | ||
|
|
36868f875c | ||
|
|
bb7e0977b8 | ||
|
|
7fb36b301c | ||
|
|
616034a4cd | ||
|
|
3de24fd373 | ||
|
|
49f6a0f222 | ||
|
|
a24bd94d43 | ||
|
|
de9db2ea77 | ||
|
|
590a21515a | ||
|
|
ed4a47ffba | ||
|
|
09603b334b | ||
|
|
ca9c174f29 | ||
|
|
cc41f8fe25 | ||
|
|
4445ff68d4 | ||
|
|
07e83132c0 | ||
|
|
55c6467d83 |
No files matched your search
@@ -1,70 +0,0 @@
|
||||
---
|
||||
description: 文件层与函数层注释强制规范(撰写与调整代码时均适用)
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# 代码注释(强制)
|
||||
|
||||
撰写或**修改**代码时,必须补齐或更新两层注释。完整说明见 `AGENTS.md` §5。
|
||||
|
||||
## 文件层(文件顶部)
|
||||
|
||||
块注释须包含:**用途**、**主要 import/依赖**、**与上下游文件的逻辑关系**。
|
||||
|
||||
```typescript
|
||||
/**
|
||||
* features/kb/composables/useKbWorkspace.ts
|
||||
* 用途:知识库作业面编排入口,组合 state / computed / data 等子模块。
|
||||
* 依赖:kb-workspace/* composables、kb.api、kb-display.utils。
|
||||
* 逻辑:KbWorkspaceView 调用本 composable;本文件再分发至 useKbWorkspaceData 等子模块。
|
||||
*/
|
||||
```
|
||||
|
||||
```python
|
||||
"""
|
||||
services/kb_sync.py
|
||||
|
||||
用途:知识库文档与 Dify 之间的同步编排。
|
||||
依赖:dify_service、models.KbDocument、minio_service。
|
||||
逻辑:由 api/knowledge_base 路由调用;内部委托 chunking 与 job 状态机。
|
||||
"""
|
||||
```
|
||||
|
||||
## 函数层(每个函数定义上方)
|
||||
|
||||
须说明:**用途**、**核心逻辑与实现方式**、**参数**与**返回值**(及异常)。
|
||||
|
||||
```typescript
|
||||
/**
|
||||
* 加载当前分组下的文档列表,并在静默刷新时合并 stable 项避免闪烁。
|
||||
* 核心逻辑:调用 getKbGroupFilesSafe,按 mergeStableItems 策略合并新旧列表。
|
||||
* @param options.silent - 为 true 时不切换 loading,用于轮询刷新
|
||||
* @returns 是否成功拉取到数据
|
||||
*/
|
||||
async function loadDocuments(options?: LoadListOptions): Promise<boolean> { ... }
|
||||
```
|
||||
|
||||
```python
|
||||
def sync_document_to_dify(document_id: int, *, force: bool = False) -> SyncResult:
|
||||
"""
|
||||
将指定文档切片同步至 Dify 知识库。
|
||||
|
||||
核心逻辑:读 MinIO 原文 → 切块 → 调 Dify API upsert;失败写入 KbJob 供重试。
|
||||
|
||||
Args:
|
||||
document_id: 本地 KbDocument 主键。
|
||||
force: 为 True 时忽略已完成状态强制重同步。
|
||||
|
||||
Returns:
|
||||
SyncResult: 含 dify_document_id 与分段数。
|
||||
|
||||
Raises:
|
||||
KbNotFoundError: 文档不存在或无权限。
|
||||
"""
|
||||
```
|
||||
|
||||
## 修改既有文件时
|
||||
|
||||
- 改函数逻辑/签名 → 同步改该函数注释。
|
||||
- 改 import 或模块协作关系 → 同步改文件头注释。
|
||||
- Vue SFC:`<script setup>` 内每个函数同样要求函数层注释。
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
description: 未启用。管理端改用 Element Plus 的写法。启用前不要自动套用。
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# 管理端 Element Plus(未启用)
|
||||
|
||||
本规则现在不自动生效:`alwaysApply` 为 false,且没有 `globs`。打开管理端文件时不会套用。
|
||||
|
||||
启用:在本文件顶部 frontmatter 加上下面的 `globs` 后保存。不要改 `alwaysApply`。
|
||||
|
||||
```yaml
|
||||
globs: frontend/src/features/admin/**/*.vue,frontend/src/features/kb/components/KbAdminPanel.vue,frontend/src/features/kb/components/KbGroupDrawer.vue
|
||||
```
|
||||
|
||||
启用之后,改这些 Vue 时遵守 `docs/ui/ELEMENT_MIGRATION.md` §4:
|
||||
|
||||
- 按钮、输入、下拉、表格、弹窗、分页用 Element Plus,不要新写 `<button>`、`<input>`、`<select>`、`<textarea>`。
|
||||
- 不要新写 `btn-primary`、`btn-secondary`、`btn-ghost`、`btn-danger`、`input-field`、`select-field`。
|
||||
- 图标用 `@element-plus/icons-vue`,不要新加 `lucide-vue-next`。
|
||||
- 字号和颜色用 `element-trial.css` 里的 Element 变量,不要在单元格上写 `text-sm`、`text-xs`、`text-muted`。
|
||||
@@ -1,2 +0,0 @@
|
||||
DEBUG_SERVER_URL=http://127.0.0.1:7778/event
|
||||
DEBUG_SESSION_ID=login-401
|
||||
@@ -1,2 +0,0 @@
|
||||
{"sessionId": "app-open-error", "runId": "pre-fix", "hypothesisId": "A", "location": "src/main.ts:8", "msg": "[DEBUG] Frontend bootstrap started", "data": {"href": "http://192.168.100.192:8910/config"}, "ts": 1788828493927}
|
||||
{"sessionId": "app-open-error", "runId": "pre-fix", "hypothesisId": "C", "location": "src/main.ts:16", "msg": "[DEBUG] Vue app mounted", "data": {"appChildren": 1}, "ts": 1788828493938}
|
||||
@@ -1,4 +1,4 @@
|
||||
# =============================================================================
|
||||
# =============================================================================
|
||||
# Development — docker compose / deploy_compose.sh dev
|
||||
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
||||
# - .env.dev / .env.test / .env.prod for deployment environments
|
||||
@@ -102,15 +102,13 @@ SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
|
||||
# 复核工作台字段级 AI 建议;仅开发环境启用,建议仍须证据校验与人工裁决
|
||||
SHIPPING_NOTICE_LLM_REVIEW_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true
|
||||
SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
|
||||
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||
@@ -135,31 +133,37 @@ SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true
|
||||
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS=900
|
||||
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||
# RPA 目录(相对 backend/ 根目录,统一 freight_rpa/{inventory,receipt,common} 三层布局)
|
||||
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=data/freight_rpa/inventory/drop
|
||||
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory/triggers
|
||||
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=data/freight_rpa/receipt/drop
|
||||
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=data/freight_rpa/receipt/triggers
|
||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=data/freight_rpa/inventory/upload_queue
|
||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/freight_rpa/inventory/upload_triggers
|
||||
# RPA 目录(相对 backend/ 根;freight_rpa/{onhand,inbound,outbound,upload,common},2026-10-16 批次 R)
|
||||
FREIGHT_RPA_SHARED_ONHAND_DROP_DIR=data/freight_rpa/onhand/drop
|
||||
FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR=data/freight_rpa/onhand/triggers
|
||||
FREIGHT_RPA_SHARED_INBOUND_DROP_DIR=data/freight_rpa/inbound/drop
|
||||
FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR=data/freight_rpa/inbound/triggers
|
||||
FREIGHT_RPA_INBOUND_ARCHIVE_DIR=data/freight_rpa/inbound/archives
|
||||
FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR=data/freight_rpa/outbound/drop
|
||||
FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR=data/freight_rpa/outbound/triggers
|
||||
FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR=data/freight_rpa/outbound/archives
|
||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=data/freight_rpa/upload/queue
|
||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/freight_rpa/upload/triggers
|
||||
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR=data/freight_rpa/common/browser_profile
|
||||
# AWS 库存列映射(可选 JSON 字符串)
|
||||
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
|
||||
# 本地 RPA(scripts/freight_rpa/inventory/inventory_rpa_worker.py)
|
||||
# 本地 RPA(scripts/freight_rpa/onhand/onhand_rpa_worker.py)
|
||||
FREIGHT_RPA_WORKER_MOCK=false
|
||||
# 本机无 Redis 时允许进程内存记录心跳;有 Redis 时优先写 Redis
|
||||
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false
|
||||
FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK=true
|
||||
# 企微心跳告警总开关(默认关闭;需要时改为 true)
|
||||
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
|
||||
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
|
||||
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
|
||||
# FREIGHT_RPA_WORKER_SAMPLE_ONHAND=
|
||||
# --- 10. 运维、告警与维护工具 ---
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
|
||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
|
||||
WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||
@@ -1,4 +1,4 @@
|
||||
# =============================================================================
|
||||
# =============================================================================
|
||||
# Production — docker compose env_file + deploy_compose.sh prod
|
||||
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
||||
# - .env.dev / .env.test / .env.prod for deployment environments
|
||||
@@ -25,6 +25,7 @@ HXOPS_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||
AUTH_LOGIN_MODE=casdoor
|
||||
# 如果需要用户密码登录,修改该值为password
|
||||
# AUTH_LOGIN_MODE=password
|
||||
|
||||
# 是否启用 JWT 认证
|
||||
AUTH_JWT_REQUIRED=true
|
||||
AUTH_JWT_ISSUER=https://auth.well-trust.com
|
||||
@@ -72,7 +73,6 @@ GUNICORN_WORKERS=20
|
||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
|
||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines
|
||||
WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||
|
||||
# --- 5. 数据库与基础设施 ---
|
||||
@@ -116,11 +116,10 @@ SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
|
||||
|
||||
# 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享)
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true
|
||||
SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED=true
|
||||
# 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
@@ -138,33 +137,33 @@ SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
|
||||
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 必须一致)
|
||||
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
|
||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS=900
|
||||
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
||||
# 企微心跳告警总开关(默认关闭;需要时改为 true)
|
||||
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
|
||||
# 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微
|
||||
FREIGHT_RPA_WORKER_ALERT_USERNAMES=
|
||||
FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
|
||||
FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
|
||||
FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
|
||||
# RPA 目录(正式环境:Ubuntu 挂载 Windows RPA 正式共享,统一 freight_rpa/{inventory,receipt,common} 三层布局)
|
||||
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/drop
|
||||
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/triggers
|
||||
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/drop
|
||||
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/triggers
|
||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_queue
|
||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_triggers
|
||||
# RPA 目录(正式:Ubuntu 挂载 Windows 共享;freight_rpa/{onhand,inbound,outbound,upload,common})
|
||||
FREIGHT_RPA_SHARED_ONHAND_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/onhand/drop
|
||||
FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/onhand/triggers
|
||||
FREIGHT_RPA_SHARED_INBOUND_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inbound/drop
|
||||
FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inbound/triggers
|
||||
FREIGHT_RPA_INBOUND_ARCHIVE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inbound/archives
|
||||
FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/outbound/drop
|
||||
FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/outbound/triggers
|
||||
FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/outbound/archives
|
||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/upload/queue
|
||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/upload/triggers
|
||||
# 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
||||
# 订单交期回复 Agent(2026-10-10 上线边界):只同步订单日期 ≥ 起始日的订单行,早于边界的历史行随 erp_missing 语义自动移出工作台;留空/删除 = 全量同步(dev/test 不配置)
|
||||
ORDER_DELIVERY_SYNC_DATE_FROM=2026-10-10
|
||||
# --- 10. 运维、告警与维护工具 ---
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
+1
-1
@@ -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,training_overseas_thailand_guidelines
|
||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,equipment_acceptance_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,order_delivery_reply_notify,training_overseas_thailand_guidelines
|
||||
WECOM_FEEDBACK_NOTIFY_ENABLED=true
|
||||
WECOM_FEEDBACK_NOTIFY_BASE_URL=http://ai.well-trust.com:8881
|
||||
# 企业微信群机器人 webhook,按环境写入 .env.<env> 或部署平台变量;不要提交真实 URL。
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# =============================================================================
|
||||
# =============================================================================
|
||||
# Test — docker compose / deploy_compose.sh test
|
||||
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
||||
# - .env.dev / .env.test / .env.prod for deployment environments
|
||||
@@ -24,8 +24,6 @@ HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||
# 如果需要用户密码登录,修改该值为password
|
||||
#AUTH_LOGIN_MODE=casdoor
|
||||
AUTH_LOGIN_MODE=casdoor
|
||||
# 是否启用 JWT 认证
|
||||
AUTH_JWT_REQUIRED=true
|
||||
|
||||
# 必须与 CASDOOR_BASE_URL discovery 返回的 issuer 完全一致,不能填写 HXOPS 地址。
|
||||
AUTH_JWT_ISSUER=https://autht.well-trust.com
|
||||
@@ -72,7 +70,6 @@ GUNICORN_WORKERS=6
|
||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||
WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
|
||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines
|
||||
WECOM_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||
HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||
|
||||
@@ -120,13 +117,11 @@ SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true
|
||||
SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
|
||||
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||
# 货代专用 Tool API Key(RPA 回调优先读取;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||
@@ -151,16 +146,16 @@ SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true
|
||||
SHIPPING_NOTICE_LAYOUT_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
|
||||
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐)
|
||||
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
|
||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
# 两域超时须覆盖最坏批次总时长(10 站串行 + 单站失败重试可达 30 分钟+),
|
||||
# 否则每轮对账会把仍在飞的健康批次误回收(2026-10-08 RUN20261008003113B726 实测教训)
|
||||
FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS=3600
|
||||
FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS=3600
|
||||
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
||||
# 企微心跳告警总开关(默认关闭;需要时改为 true)
|
||||
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
|
||||
# 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微
|
||||
# 两者皆无则告警只写日志、不会发企微
|
||||
FREIGHT_RPA_WORKER_ALERT_USERNAMES=
|
||||
@@ -170,24 +165,25 @@ FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
|
||||
FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||
FREIGHT_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns=
|
||||
# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享,统一 freight_rpa/{inventory,receipt,common} 三层布局)
|
||||
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/drop
|
||||
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers
|
||||
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/drop
|
||||
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/triggers
|
||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_queue
|
||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_triggers
|
||||
# RPA 目录(测试:Ubuntu 挂载 Windows 共享;freight_rpa/{onhand,inbound,outbound,upload,common})
|
||||
FREIGHT_RPA_SHARED_ONHAND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/onhand/drop
|
||||
FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/onhand/triggers
|
||||
FREIGHT_RPA_SHARED_INBOUND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/drop
|
||||
FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/triggers
|
||||
FREIGHT_RPA_INBOUND_ARCHIVE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/archives
|
||||
FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/outbound/drop
|
||||
FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/outbound/triggers
|
||||
FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/outbound/archives
|
||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/upload/queue
|
||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/upload/triggers
|
||||
# AWS 库存列映射(可选 JSON 字符串)
|
||||
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
|
||||
# 本地 Mock RPA(scripts/freight_rpa/inventory/inventory_rpa_worker.py,可选)
|
||||
# 本地 Mock RPA(scripts/freight_rpa/onhand/onhand_rpa_worker.py,可选)
|
||||
# FREIGHT_RPA_WORKER_MOCK=true
|
||||
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
|
||||
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
|
||||
# FREIGHT_RPA_WORKER_SAMPLE_ONHAND=
|
||||
# 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
||||
# --- 10. 运维、告警与维护工具 ---
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
@@ -0,0 +1,23 @@
|
||||
## 改动说明
|
||||
|
||||
<!-- 这次改了什么、为什么改。 -->
|
||||
|
||||
## 管理端界面
|
||||
|
||||
这次改动如果碰到管理控制台、知识库配置,或已经换成 Element Plus 的页面,按 `docs/ui/ELEMENT_MIGRATION.md` §6 核对。没改界面就删掉下面的清单。
|
||||
|
||||
- [ ] 只在该页入口引入 Element 样式和 `element-trial.css`,并用 `ElConfigProvider` 包住。
|
||||
- [ ] 列表骨架符合规范 §3,左右 32px 对齐,只有一层卡片。
|
||||
- [ ] 按钮符合规范 §4.1,没有 `size="small"` 和默认按钮混在一行。
|
||||
- [ ] 表格状态是 `ElTag`,单元格没有 `text-xs` / `text-sm` / `text-muted`。
|
||||
- [ ] 筛选框没有被拉成整行,空选项不是「请选择」。
|
||||
- [ ] 弹窗宽度只有 480px 或 680px,短表单不是整屏抽屉。
|
||||
- [ ] 加载遮罩只等列表请求,数据出来后遮罩消失。
|
||||
- [ ] 删除确认与本页其他确认框是同一种。
|
||||
- [ ] 四种语言下按钮、表头、空状态、分页都能读通。
|
||||
- [ ] `html.dark` 下边框、表头、弹窗底色跟着变量变。
|
||||
- [ ] `frontend` 下 `npx vue-tsc -b --pretty false` 通过。
|
||||
|
||||
## 测试
|
||||
|
||||
<!-- 怎么验证。 -->
|
||||
@@ -59,6 +59,9 @@ frontend/package-lock.json
|
||||
!.vscode/extensions.json
|
||||
.trae/*
|
||||
.cursor/*
|
||||
!.cursor/rules/
|
||||
!.cursor/rules/*.mdc
|
||||
.cursor/rules/* copy.mdc
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
@@ -150,6 +150,7 @@ docker compose logs -f hxops-backend
|
||||
- 🧬 **修改数据库表结构必须配套迁移**:任何对 `models.py` / 数据表结构的新增、删除、字段或约束变更,都必须生成并提交对应的 Alembic 迁移脚本(`flask db migrate -m "..."` → `flask db upgrade`),禁止只改模型不出迁移。
|
||||
- 🌐 **环境变量分层**:`.env.shared` + `.env.<env>`(dev/test/prod),不要在代码里写死环境值。规则见 **[docs/convention/env_loading_priority.md](docs/convention/env_loading_priority.md)** 与 **[docs/convention/环境变量规则.md](docs/convention/环境变量规则.md)**。
|
||||
- 🌍 **i18n 四语言**:前端新增文案必须同时补齐 `zh-CN / zh-TW / en / th`,禁止硬编码中文。Agent 流程见项目 Skill `add-i18n-keys` 与 [docs/skills/add-i18n-keys-skill.md](docs/skills/add-i18n-keys-skill.md)。
|
||||
- 🎨 **前端界面统一 Element Plus**:`frontend/src` 的页面、弹窗、筛选、表格、按钮和输入使用 Element Plus,写法以 [docs/ui/ELEMENT_MIGRATION.md](docs/ui/ELEMENT_MIGRATION.md) 为准。新改的界面禁止再加 `btn-*`、`input-field`、`select-field`,以及手写 `<button>` / `<input>` / `<select>` / `<textarea>`。尚未替换的旧页面保持原样,轮到该页再整页替换,同一页不要混用两套控件。管理端列表骨架用 `AdminListPage`,页签用 `AdminListTabs`。
|
||||
- 📡 **SSE 流式约束**:对话链路依赖 Gevent 异步 worker + Nginx `proxy_buffering off`;对话接口(`chat.py`)使用原生 Fetch/SSE 而非 Axios,改动需保持流式不被破坏。
|
||||
- 🔌 **外部集成依赖**:Oracle Instant Client 19.30 / `pyodbc` / `zeep`(OA、PLM、HR)等本地未必可运行,涉及这些 service 时谨慎并说明。
|
||||
- ➕ **新增依赖需克制**:不擅自引入未经评审的第三方依赖;如需新增,在提交说明中给出理由。
|
||||
@@ -163,7 +164,7 @@ docker compose logs -f hxops-backend
|
||||
- **文件内章节顺序**:① 环境与应用标识 → ② 应用运行与进程 → ③ 公共地址与网络入口 → ④ 安全、认证与身份源 → ⑤ 数据库与基础设施 → ⑥ AI 平台、模型与内部工具 → ⑦ 企业系统集成 → ⑧ 知识库与文件处理 → ⑨ 业务模块 → ⑩ 运维、告警与维护工具;文件没有某类变量时直接省略该章节。
|
||||
- **章节内组织**:先按业务域及子域聚合(如 Casdoor、MinIO、WeCom、HR、PLM、SRM、FAQ、Shipping Notice、Fixed Asset),不得把同一域拆散后做全局字母排序;同一域内按“开关/模式 → 地址 → 标识 → 凭据 → 路径 → 业务参数 → 超时/重试/并发 → 兼容/Mock”排列,同级变量再按字母排序。
|
||||
- **数据库连接固定顺序**:`HOST → PORT → DATABASE/SID → USERNAME → PASSWORD → DRIVER → ENCRYPT/TRUST_CERT → TIMEOUT`;完整连接串(如 `DATABASE_URL`、`*_DSN`)置于该数据源首位。
|
||||
- **RPA 命名空间(强制,2026-09-18 修订)**:货代 RPA(库存/收料/上传及后续新增 Worker)统一使用 `FREIGHT_RPA_*`。后端业务参数使用 `FREIGHT_RPA_<配置项>`,后端与 Windows Worker 的共享目录/标识使用 `FREIGHT_RPA_SHARED_*`,Windows Worker 自身运行参数使用 `FREIGHT_RPA_WORKER_*`,平台凭据主密钥使用 `FREIGHT_RPA_CREDENTIAL_KEY`。禁止新增 `SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`。历史名称 `SHIPPING_NOTICE_RPA_*` 于 2026-09-18 未上线期一刀切废弃,**不设兼容层**;RPA 运行期数据统一存放于独立 `freight_rpa/` 根下,按 `inventory/`、`receipt/`、`common/` 分域(common 仅放跨 Worker 共享物,如 browser_profile)。
|
||||
- **RPA 命名空间(强制,2026-09-18 修订)**:货代 RPA(库存/收料/上传及后续新增 Worker)统一使用 `FREIGHT_RPA_*`。后端业务参数使用 `FREIGHT_RPA_<配置项>`,后端与 Windows Worker 的共享目录/标识使用 `FREIGHT_RPA_SHARED_*`,Windows Worker 自身运行参数使用 `FREIGHT_RPA_WORKER_*`,平台凭据主密钥使用 `FREIGHT_RPA_CREDENTIAL_KEY`。禁止新增 `SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`。历史名称 `SHIPPING_NOTICE_RPA_*` 于 2026-09-18 未上线期一刀切废弃,**不设兼容层**;RPA 运行期数据统一存放于独立 `freight_rpa/` 根下,按 `onhand/`、`inbound/`、`outbound/`(抓取域,叶目录同构 triggers/drop/logs/archives)、`upload/`(上传域,triggers/queue)、`common/`(跨 Worker 共享物,如 browser_profile)分域(2026-10-16 批次 R:原 inventory/receipt 已随迁)。
|
||||
- **跨环境一致性**:`.env.dev`、`.env.test`、`.env.prod` 使用相同章节骨架;同名变量保持相同相对位置,便于审查差异;新增变量时同步检查所有适用环境文件和上述权威文档。
|
||||
- **调整红线**:重排环境变量时只能移动“注释 + 完整赋值行”,禁止修改变量名或值,禁止删除变量、注释或示例;真实密码、密钥、Token、Webhook 与生产连接信息必须由系统环境变量、Jenkins/CI 或 Secret 管理机制注入。
|
||||
|
||||
@@ -204,9 +205,10 @@ docker compose logs -f hxops-backend
|
||||
| 环境变量 | [docs/convention/env_loading_priority.md](docs/convention/env_loading_priority.md) · [docs/convention/环境变量规则.md](docs/convention/环境变量规则.md) |
|
||||
| 知识库部署 | [docs/knowledge_base_runtime_deploy.md](docs/knowledge_base_runtime_deploy.md) |
|
||||
| Excel/CSV 切块与 Dify 分段 | [docs/kb-excel-dify-chunking.md](docs/kb-excel-dify-chunking.md) |
|
||||
| FAQ 缓存 / 热点发现运维 | [docs/faq_cache_ops_manual.md](docs/faq_cache_ops_manual.md) |
|
||||
| FAQ 缓存 / 热点发现运维 | [docs/features/faq/faq_cache_ops_manual.md](docs/features/faq/faq_cache_ops_manual.md) |
|
||||
| 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.md) |
|
||||
| 前端架构规范 | [docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md) |
|
||||
| 前端 Element Plus | [docs/ui/ELEMENT_MIGRATION.md](docs/ui/ELEMENT_MIGRATION.md) |
|
||||
| 错误处理规范 | [docs/convention/error_handling.md](docs/convention/error_handling.md) |
|
||||
| Cursor Skills 索引 | [docs/skills/README.md](docs/skills/README.md) |
|
||||
| 前端四语言 i18n Skill | [docs/skills/add-i18n-keys-skill.md](docs/skills/add-i18n-keys-skill.md) |
|
||||
|
||||
Vendored
+23
@@ -353,6 +353,29 @@ pipeline {
|
||||
}
|
||||
}
|
||||
|
||||
stage('Frontend Lint') {
|
||||
when {
|
||||
expression { env.FRONTEND_CHANGED == 'true' }
|
||||
}
|
||||
steps {
|
||||
echo '[Frontend Lint] FRONTEND_CHANGED=true,执行 npm run lint(Element 规则当前为 off)'
|
||||
sh '''
|
||||
set -eu
|
||||
test -f "${WORKSPACE}/scripts/ci_frontend_lint.sh"
|
||||
test -f "${WORKSPACE}/frontend/package.json"
|
||||
# 不用 -v 挂载工作区:Jenkins 在容器里时,宿主机 Docker 看不到 /var/jenkins_home。
|
||||
# 把前端源码和脚本打进容器再检查。node_modules 由容器内 npm ci 安装。
|
||||
tar -C "${WORKSPACE}" \
|
||||
--exclude=frontend/node_modules \
|
||||
--exclude=frontend/dist \
|
||||
-cf - \
|
||||
frontend scripts/ci_frontend_lint.sh \
|
||||
| docker run --rm -i node:22-alpine \
|
||||
sh -c 'mkdir -p /repo && tar -xf - -C /repo && sh /repo/scripts/ci_frontend_lint.sh'
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
// stage('Frontend Build (CI)') {
|
||||
// when {
|
||||
// expression { env.FRONTEND_CHANGED == 'true' }
|
||||
|
||||
+42
-14
@@ -42,17 +42,17 @@ def _is_database_table_ready(table_name: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _apply_persisted_settings(app: Flask) -> None:
|
||||
"""Pull the latest runtime-editable settings into ``app.config``.
|
||||
def _apply_persisted_settings(app: Flask, *, force: bool = False) -> None:
|
||||
"""
|
||||
将运行时可编辑配置同步进 ``app.config``。
|
||||
|
||||
Reads from the database first, then ``backend/.env``. Tolerates the
|
||||
common case where the table does not yet exist (fresh deploy before
|
||||
``flask db upgrade`` runs).
|
||||
核心逻辑:委托 apply_env_settings(进程内 TTL,默认 30s);force 时强制读库。
|
||||
表尚未创建(迁移前)时静默跳过。
|
||||
"""
|
||||
from app.core.config.env_persistence import apply_env_settings
|
||||
|
||||
try:
|
||||
applied = apply_env_settings()
|
||||
applied = apply_env_settings(force=force)
|
||||
except Exception as exc: # pragma: no cover - defensive
|
||||
logger.warning('Failed to refresh persisted settings: %s', exc)
|
||||
return
|
||||
@@ -79,12 +79,23 @@ def create_app(config_name='default'):
|
||||
|
||||
_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
|
||||
# serve the defaults baked into config.py / the image).
|
||||
# onhand/inbound/outbound RPA 回调 sink 注册(幂等):按消费域分组合根——
|
||||
# onhand → shipping_notice.rpa_sinks;inbound/outbound → in_transit_transfer.rpa_sinks。
|
||||
# 进度类经 callback_sinks.dispatch_sink;文件事实经 reports.dispatch;
|
||||
# 未注册 kind 显式 404(FREIGHT_RPA.SINK_NOT_REGISTERED)。
|
||||
from app.services.in_transit_transfer.rpa_sinks import (
|
||||
register_inbound_sinks,
|
||||
register_outbound_sinks,
|
||||
)
|
||||
from app.services.shipping_notice.rpa_sinks import register_onhand_sinks
|
||||
|
||||
register_onhand_sinks()
|
||||
register_inbound_sinks()
|
||||
register_outbound_sinks()
|
||||
|
||||
# 启动时强制加载一次,避免 worker 冷启动到首个请求之间仍用镜像默认值。
|
||||
with app.app_context():
|
||||
_apply_persisted_settings(app)
|
||||
_apply_persisted_settings(app, force=True)
|
||||
from app.services.agent_runtime_context.bootstrap import load_context_adapters
|
||||
load_context_adapters()
|
||||
from app.services.agent_registry.handlers.bootstrap import load_handlers
|
||||
@@ -125,6 +136,21 @@ def create_app(config_name='default'):
|
||||
ensure_default_contract_payment_schedules()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure contract-payment schedules: %s', exc)
|
||||
try:
|
||||
from app.services.equipment_acceptance.schedule_seed import ensure_default_equipment_acceptance_schedules
|
||||
ensure_default_equipment_acceptance_schedules()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure equipment-acceptance schedules: %s', exc)
|
||||
try:
|
||||
from app.services.order_delivery_reply.schedule_seed import ensure_default_order_delivery_schedules
|
||||
ensure_default_order_delivery_schedules()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure order-delivery-reply schedule: %s', exc)
|
||||
try:
|
||||
from app.services.order_delivery_reply.app_seed import ensure_builtin_order_delivery_agent
|
||||
ensure_builtin_order_delivery_agent()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure order-delivery-reply agent: %s', exc)
|
||||
try:
|
||||
from app.services.lean_training_schedule_seed import ensure_default_lean_training_schedule
|
||||
ensure_default_lean_training_schedule()
|
||||
@@ -132,11 +158,12 @@ def create_app(config_name='default'):
|
||||
logger.warning('Failed to ensure lean-training schedule: %s', exc)
|
||||
else:
|
||||
logger.info('Skip startup schedule seeding: schedule_tasks table is not ready')
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
FixedAssetsSnapshotService.start_worker(app)
|
||||
# 固资快照同步已迁至独立进程 workers/worker_fixed_assets.py,Web 不再起线程;
|
||||
# 排程执行同样由独立 worker 进程(workers/worker_scheduler.py,生产 hxops-schedule-worker 容器)
|
||||
# 负责(dev Wave 4),Web 进程不再兜底扫描。
|
||||
# AUTO_UPLOAD 显式开启时启动级校验货代上传 RPA(仅告警,不阻断启动)。
|
||||
try:
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
log_auto_upload_readiness_at_startup,
|
||||
)
|
||||
log_auto_upload_readiness_at_startup(app)
|
||||
@@ -145,6 +172,7 @@ def create_app(config_name='default'):
|
||||
|
||||
@app.before_request
|
||||
def _sync_persisted_settings():
|
||||
# TTL 内复用进程缓存,不每请求打 app_settings;跨 worker 最多延迟一个 TTL。
|
||||
_apply_persisted_settings(app)
|
||||
incoming_request_id = (request.headers.get('X-Request-Id') or '').strip()
|
||||
g.request_id = incoming_request_id or f"req_{uuid.uuid4().hex[:16]}"
|
||||
|
||||
@@ -17,21 +17,20 @@ def register_blueprints(app: Flask) -> None:
|
||||
Args:
|
||||
app: Flask 应用实例。
|
||||
"""
|
||||
# [STEP 1] 单体模块(Wave 3 前保持不变)
|
||||
# [STEP 1] 域包入口(Blueprint 多在包 __init__ 或子模块)
|
||||
from app.api.chat import chat_bp
|
||||
from app.api.admin import admin_bp
|
||||
from app.api.agents import agents_bp
|
||||
from app.api.user import auth_bp, user_bp
|
||||
from app.api.integration import integration_bp
|
||||
from app.api.internal_jobs import internal_jobs_bp
|
||||
from app.api.internal import internal_jobs_bp
|
||||
from app.api.maintenance import maintenance_bp
|
||||
from app.api.speech import speech_bp
|
||||
from app.api.sso import sso_bp, sso_well_known_bp
|
||||
from app.api.linked_services import linked_services_bp
|
||||
from app.api.training import training_admin_bp, training_user_bp
|
||||
from app.api.agent_runtime_context_tools import agent_runtime_context_bp
|
||||
|
||||
# [STEP 2] 已分包骨架(Wave 3:kb、schedule 等)
|
||||
# [STEP 2] 其余域包与 Tool API
|
||||
from app.api.kb import knowledge_base_bp
|
||||
from app.api.schedule import schedule_admin_bp
|
||||
from app.api.workspace import (
|
||||
@@ -41,10 +40,18 @@ def register_blueprints(app: Flask) -> None:
|
||||
workspace_shipping_notice_bp,
|
||||
workspace_voucher_check_bp,
|
||||
)
|
||||
from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp
|
||||
from app.api.tools import (
|
||||
agent_runtime_context_bp,
|
||||
file_check_bp,
|
||||
maintenance_tool_bp,
|
||||
procurement_contract_bp,
|
||||
shipping_notice_bp,
|
||||
)
|
||||
from app.api.freight_rpa import freight_rpa_bp
|
||||
from app.api.files import files_bp
|
||||
from app.api.procurement_contract_tools import procurement_contract_bp
|
||||
from app.api.contract_payment import contract_payment_bp
|
||||
from app.api.equipment_acceptance import equipment_acceptance_bp
|
||||
from app.api.order_delivery_reply import order_delivery_reply_bp
|
||||
from app.api.in_transit_transfer import in_transit_transfer_bp
|
||||
from app.api.integration_connector import integration_connector_bp
|
||||
|
||||
@@ -65,6 +72,7 @@ def register_blueprints(app: Flask) -> None:
|
||||
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
|
||||
app.register_blueprint(maintenance_bp, url_prefix='/api/maintenance')
|
||||
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
|
||||
app.register_blueprint(freight_rpa_bp, url_prefix='/api/freight-rpa')
|
||||
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
|
||||
app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context')
|
||||
app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance')
|
||||
@@ -76,5 +84,7 @@ def register_blueprints(app: Flask) -> None:
|
||||
app.register_blueprint(files_bp, url_prefix='/api/files')
|
||||
app.register_blueprint(procurement_contract_bp, url_prefix='/api/procurement-contract')
|
||||
app.register_blueprint(contract_payment_bp, url_prefix='/api/contract-payment')
|
||||
app.register_blueprint(equipment_acceptance_bp, url_prefix='/api/equipment-acceptance')
|
||||
app.register_blueprint(order_delivery_reply_bp, url_prefix='/api/order-delivery-reply')
|
||||
app.register_blueprint(in_transit_transfer_bp, url_prefix='/api/in-transit-transfer')
|
||||
app.register_blueprint(integration_connector_bp, url_prefix='/api/integration-connector')
|
||||
@@ -16,13 +16,15 @@ import app.api.admin.faq_candidates # noqa: F401
|
||||
import app.api.admin.reports # noqa: F401
|
||||
import app.api.admin.database # noqa: F401
|
||||
import app.api.admin.permissions # noqa: F401
|
||||
import app.api.admin.permission_roles # noqa: F401
|
||||
import app.api.admin.users # noqa: F401
|
||||
import app.api.admin.wecom # noqa: F401
|
||||
import app.api.admin.shipping_order_extraction # noqa: F401
|
||||
import app.api.admin.announcements # noqa: F401
|
||||
import app.api.admin.shipping_customers # noqa: F401
|
||||
import app.api.admin.shipping_identity_rules # noqa: F401
|
||||
import app.api.admin.shipping_inventory # noqa: F401
|
||||
import app.api.admin.shipping_notice_admin # noqa: F401
|
||||
import app.api.admin_freight_rpa # noqa: F401
|
||||
import app.api.admin.shipping_order_schema # noqa: F401
|
||||
import app.api.admin.shipping_field_assets # noqa: F401
|
||||
import app.api.admin.shipping_order_document_profiles # noqa: F401
|
||||
@@ -31,5 +33,6 @@ import app.api.admin.shipping_process_gate # noqa: F401
|
||||
import app.api.admin.linked_services # noqa: F401
|
||||
import app.api.admin.procurement_contract # noqa: F401
|
||||
import app.api.admin.training_configs # noqa: F401
|
||||
import app.api.admin.transfer_type # noqa: F401
|
||||
|
||||
__all__ = ['admin_bp']
|
||||
@@ -22,21 +22,11 @@ def dashboard_summary():
|
||||
return jsonify(dashboard_service.compute_dashboard_summary())
|
||||
|
||||
|
||||
@admin_bp.route('/dashboard/badges', methods=['GET'])
|
||||
@require_admin
|
||||
def dashboard_badges():
|
||||
"""
|
||||
管理后台侧栏待办角标(供 AdminLayout 轻量轮询/缓存刷新)。
|
||||
GET /api/admin/dashboard/badges
|
||||
"""
|
||||
return jsonify(dashboard_service.compute_dashboard_badges())
|
||||
|
||||
|
||||
@admin_bp.route('/dashboard', methods=['GET'])
|
||||
@require_admin
|
||||
def dashboard_stats():
|
||||
"""
|
||||
仪表盘统计(遗留接口;新代码请用 /dashboard/summary 与 /dashboard/badges)。
|
||||
仪表盘统计(遗留接口;新代码请用 /dashboard/summary)。
|
||||
GET /api/admin/dashboard
|
||||
"""
|
||||
return jsonify(dashboard_service.compute_legacy_dashboard_stats())
|
||||
@@ -28,6 +28,13 @@ def create_department():
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@admin_bp.route('/departments/<int:id>/members', methods=['GET'])
|
||||
@require_admin
|
||||
def list_department_members(id: int):
|
||||
"""返回部门员工数量与名单。"""
|
||||
return jsonify(department_service.list_department_members(id))
|
||||
|
||||
|
||||
@admin_bp.route('/departments/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_department(id: int):
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"""
|
||||
api/admin/permission_roles.py
|
||||
|
||||
用途:管理端权限组列表、编辑、成员预览与确认调整。
|
||||
依赖:admin.blueprint、permission_roles.service。
|
||||
逻辑:/permission-roles* 路由;成员调整必须先 preview 再 apply。
|
||||
"""
|
||||
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.permission_roles import service as role_service
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_permission_roles():
|
||||
"""列出全部权限组。"""
|
||||
return jsonify(role_service.list_roles())
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/catalog', methods=['GET'])
|
||||
@require_admin
|
||||
def permission_role_catalog():
|
||||
"""角色编辑可选应用与应用内能力。"""
|
||||
return jsonify(role_service.grantable_catalog())
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/picker-users', methods=['GET'])
|
||||
@require_admin
|
||||
def permission_role_picker_users():
|
||||
"""选人弹窗候选人(排除管理员)。"""
|
||||
return jsonify(role_service.list_picker_people())
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles', methods=['POST'])
|
||||
@require_admin
|
||||
def create_permission_role():
|
||||
"""新建权限组。"""
|
||||
data = request.get_json() or {}
|
||||
payload = role_service.create_role(data)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/<code>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_permission_role(code: str):
|
||||
"""权限组详情。"""
|
||||
return jsonify(role_service.get_role_detail(code))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/<code>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_permission_role(code: str):
|
||||
"""保存权限包并同步该组用户授权。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(role_service.update_role(code, data))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/<code>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_permission_role(code: str):
|
||||
"""删除空的非内置权限组。"""
|
||||
return jsonify(role_service.delete_role(code))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/<code>/members/preview', methods=['POST'])
|
||||
@require_admin
|
||||
def preview_permission_role_members(code: str):
|
||||
"""确认前预览将改入/移出的人及来源角色。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(role_service.preview_role_members(code, data.get('selected_ids')))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/<code>/members', methods=['POST'])
|
||||
@require_admin
|
||||
def apply_permission_role_members(code: str):
|
||||
"""确认后写回成员。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(role_service.apply_role_members(code, data.get('selected_ids')))
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/api/admin/permissions.py
|
||||
|
||||
用途:管理后台权限批量更新与权限申请审批 API(薄路由层)。
|
||||
用途:管理后台应用权限批量更新 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/permission_service。
|
||||
逻辑:/permissions/*、/permission-requests/*、/users/<id>/permissions 路由。
|
||||
逻辑:/permissions/*、/users/<id>/permissions 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
@@ -28,22 +28,3 @@ def update_user_permissions(id: int):
|
||||
return jsonify(permission_service.update_user_permissions(id, data))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-requests', methods=['GET'])
|
||||
@require_admin
|
||||
def list_permission_requests():
|
||||
"""列出全部权限申请。"""
|
||||
return jsonify(permission_service.list_permission_requests())
|
||||
|
||||
|
||||
@admin_bp.route('/permission-requests/<int:id>/approve', methods=['POST'])
|
||||
@require_admin
|
||||
def approve_request(id: int):
|
||||
"""批准权限申请。"""
|
||||
return jsonify(permission_service.approve_permission_request(id))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-requests/<int:id>/reject', methods=['POST'])
|
||||
@require_admin
|
||||
def reject_request(id: int):
|
||||
"""拒绝权限申请。"""
|
||||
return jsonify(permission_service.reject_permission_request(id))
|
||||
@@ -19,7 +19,7 @@ def _query_params() -> dict[str, str]:
|
||||
@admin_bp.route('/reports/usage', methods=['GET'])
|
||||
@require_admin
|
||||
def usage_report():
|
||||
"""聊天使用分析报表(支持时间范围 range=7d|30d|90d|180d|365d)。"""
|
||||
"""聊天使用分析报表(统计范围:start_date/end_date 自定义日期优先,否则 range=7d|30d|90d|180d|365d)。"""
|
||||
try:
|
||||
user_page = int(request.args.get('user_page', 1))
|
||||
except (TypeError, ValueError):
|
||||
@@ -34,6 +34,8 @@ def usage_report():
|
||||
user_page=user_page,
|
||||
user_page_size=user_page_size,
|
||||
range_key=range_key,
|
||||
start_date=request.args.get('start_date'),
|
||||
end_date=request.args.get('end_date'),
|
||||
)
|
||||
)
|
||||
|
||||
@@ -43,7 +45,7 @@ def usage_report():
|
||||
def applications_report():
|
||||
"""
|
||||
应用运营报表:按应用聚合使用 / 权限 / 评分。
|
||||
Query: range, status, usage, q, sort, order, page, page_size。
|
||||
Query: start_date, end_date(自定义日期优先), range, status, usage, q, sort, order, page, page_size。
|
||||
"""
|
||||
try:
|
||||
page = int(request.args.get('page', 1))
|
||||
@@ -56,6 +58,8 @@ def applications_report():
|
||||
return jsonify(
|
||||
report_service.build_application_report(
|
||||
range_key=request.args.get('range'),
|
||||
start_date=request.args.get('start_date'),
|
||||
end_date=request.args.get('end_date'),
|
||||
status=request.args.get('status'),
|
||||
usage=request.args.get('usage'),
|
||||
q=request.args.get('q'),
|
||||
@@ -67,6 +71,22 @@ def applications_report():
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/reports/overview', methods=['GET'])
|
||||
@require_admin
|
||||
def ops_overview_report():
|
||||
"""
|
||||
运营总览报表:对话量 / 活跃用户 / 活跃应用 / 趋势环比 / Top 与低使用应用 / 未处理反馈。
|
||||
Query: start_date, end_date(自定义日期优先),否则 range(7d/30d/90d/180d/365d)。
|
||||
"""
|
||||
return jsonify(
|
||||
report_service.build_ops_overview_report(
|
||||
range_key=request.args.get('range'),
|
||||
start_date=request.args.get('start_date'),
|
||||
end_date=request.args.get('end_date'),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/reports/feedback', methods=['GET'])
|
||||
@require_admin
|
||||
def feedback_report():
|
||||
@@ -86,3 +106,31 @@ def list_general_feedbacks_report():
|
||||
def count_general_feedbacks_report():
|
||||
"""通用反馈计数。"""
|
||||
return jsonify(report_service.count_general_feedbacks_report(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/reports/chat-log-tops', methods=['GET'])
|
||||
@require_admin
|
||||
def chat_log_tops():
|
||||
"""聊天日志 Top 提问/回答内容(直接按 ChatLog 明细统计,复用 FAQ 问句归一化)。"""
|
||||
return jsonify(report_service.build_chat_log_top_content(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/reports/feedback-summary', methods=['GET'])
|
||||
@require_admin
|
||||
def feedback_summary():
|
||||
"""用户反馈概览:待处理 / 本月已关闭 / 最多反馈应用(三张概览卡)。"""
|
||||
return jsonify(report_service.build_feedback_summary(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/reports/issue-analysis', methods=['GET'])
|
||||
@require_admin
|
||||
def issue_analysis():
|
||||
"""问题分析:高频问题簇 KPI + 优先处理问题(复用聊天日志风险规则)。"""
|
||||
return jsonify(report_service.build_issue_analysis_report(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/reports/general-feedbacks/<int:feedback_id>/close', methods=['POST'])
|
||||
@require_admin
|
||||
def close_general_feedback(feedback_id: int):
|
||||
"""将一条意见反馈标记为已关闭(status='closed')。"""
|
||||
return jsonify(report_service.mark_general_feedback_closed(feedback_id))
|
||||
@@ -1,617 +0,0 @@
|
||||
"""
|
||||
api/admin/shipping_inventory.py
|
||||
|
||||
用途:提供库存源、RPA Profile、路由规则及外部系统映射的管理 API。
|
||||
依赖:admin blueprint、require_admin、shipping_inventory_service。
|
||||
逻辑:路由只处理鉴权和 JSON 参数,业务校验、凭据加密及事务由服务层完成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from flask import g, request, send_file
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import ConflictError
|
||||
from app.core.response import ok
|
||||
from app.services.admin import shipping_inventory_service
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from app.services.shipping_notice import inventory_parsing_profile
|
||||
from app.services.shipping_notice import excel_template
|
||||
from app.services.shipping_notice import inventory_field_catalog
|
||||
from app.services.shipping_notice import inventory_structure_analysis
|
||||
|
||||
|
||||
def _actor_id() -> int | None:
|
||||
"""取得 require_admin 已写入请求上下文的管理员 ID。"""
|
||||
return getattr(getattr(g, 'current_user', None), 'id', None)
|
||||
|
||||
|
||||
def _ok(data, *, status: int = 200):
|
||||
"""按平台统一 envelope 返回管理 API 成功结果。"""
|
||||
return ok(data, request_id=getattr(g, 'request_id', None), status=status)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_excel_templates():
|
||||
"""列出版本化发货 Excel 模板。"""
|
||||
return _ok(excel_template.list_templates())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_excel_template():
|
||||
"""上传 xlsx 并创建模板草稿版本。"""
|
||||
try:
|
||||
definition = json.loads(request.form.get('definition') or '{}')
|
||||
except json.JSONDecodeError as exc:
|
||||
from app.core.errors import ValidationError
|
||||
raise ValidationError('definition must be valid JSON', code='SHIPPING.EXCEL_TEMPLATE_INVALID') from exc
|
||||
data = {
|
||||
'template_code': request.form.get('template_code'),
|
||||
'display_name': request.form.get('display_name'),
|
||||
'definition': definition,
|
||||
}
|
||||
return _ok(excel_template.create_draft(request.files.get('file'), data, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_excel_template(template_id: int):
|
||||
"""更新 Excel 模板草稿定义。"""
|
||||
return _ok(excel_template.update_draft(template_id, request.get_json(silent=True) or {}))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/layout', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_excel_template_layout(template_id: int):
|
||||
"""读取已保存模板的工作表和栏位,编辑时无需重新上传 Excel。"""
|
||||
return _ok(excel_template.get_layout(template_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/new-version', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_excel_template_version(template_id: int):
|
||||
"""复制现有模板文件和映射定义,创建新的草稿版本。"""
|
||||
return _ok(excel_template.create_draft_from_existing(template_id, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/clone', methods=['POST'])
|
||||
@require_admin
|
||||
def clone_shipping_excel_template(template_id: int):
|
||||
"""复制已有模板为使用新编码的独立 v1 草稿。"""
|
||||
return _ok(excel_template.clone_as_new_template(
|
||||
template_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/publish', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_shipping_excel_template(template_id: int):
|
||||
"""校验工作簿和字段映射后发布模板。"""
|
||||
return _ok(excel_template.publish(template_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/retire', methods=['POST'])
|
||||
@require_admin
|
||||
def retire_shipping_excel_template(template_id: int):
|
||||
"""退役没有启用库存源引用的模板。"""
|
||||
return _ok(excel_template.retire(template_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_excel_template(template_id: int):
|
||||
"""删除从未发布且未使用的模板草稿。"""
|
||||
excel_template.delete_draft(template_id)
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/rpa-profiles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_rpa_profiles():
|
||||
"""列出脱敏后的 RPA Profile 配置。"""
|
||||
return _ok(shipping_inventory_service.list_profiles())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/rpa-profiles', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_rpa_profile():
|
||||
"""创建 RPA Profile;明文凭据仅在本次请求内用于加密。"""
|
||||
return _ok(shipping_inventory_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/rpa-profiles/<int:profile_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_rpa_profile(profile_id: int):
|
||||
"""更新 RPA Profile;未提交密码字段时保留既有密文。"""
|
||||
return _ok(shipping_inventory_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/rpa-profiles/<int:profile_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_rpa_profile(profile_id: int):
|
||||
"""删除没有库存源引用的错误连接配置。"""
|
||||
shipping_inventory_service.delete_profile(profile_id)
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_sources():
|
||||
"""列出库存业务来源。"""
|
||||
return _ok(shipping_inventory_service.list_sources())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_inventory_source():
|
||||
"""保存停用的库存站点基础配置;正式启用由独立接口控制。"""
|
||||
return _ok(shipping_inventory_service.save_source(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(), allow_enable_transition=False,
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_inventory_source(source_id: int):
|
||||
"""更新库存站点业务配置;不能借由普通保存绕过启用门禁。"""
|
||||
return _ok(shipping_inventory_service.save_source(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(), source_id=source_id,
|
||||
allow_enable_transition=False,
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/receipt-report-config', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_receipt_report_config(source_id: int):
|
||||
"""读取站点独立收料报表配置;库存配置和收料配置永不混写。"""
|
||||
return _ok(shipping_inventory_service.get_receipt_report_config(source_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/receipt-report-config', methods=['PUT'])
|
||||
@require_admin
|
||||
def save_shipping_receipt_report_config(source_id: int):
|
||||
"""保存独立收料报表配置,并由服务记录可追溯的前后快照审计。"""
|
||||
return _ok(shipping_inventory_service.save_receipt_report_config(
|
||||
source_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/bind-parsing-profile', methods=['POST'])
|
||||
@require_admin
|
||||
def bind_shipping_inventory_source_parsing_profile(source_id: int):
|
||||
"""直接为停用库存站点绑定已发布解析方案;审计说明由系统自动记录。"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
rows = shipping_inventory_service.bind_source_parsing_profile(
|
||||
[source_id], payload.get('parsing_profile_id'), actor_id=_actor_id(),
|
||||
reason=str(payload.get('reason') or ''), operation='direct',
|
||||
)
|
||||
return _ok(rows[0])
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/bulk-bind-parsing-profile', methods=['POST'])
|
||||
@require_admin
|
||||
def bulk_bind_shipping_inventory_source_parsing_profile():
|
||||
"""原子批量绑定已发布解析方案;任一站点预检失败则整批不写入。"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
source_ids = payload.get('source_ids')
|
||||
if not isinstance(source_ids, list):
|
||||
source_ids = []
|
||||
return _ok(shipping_inventory_service.bind_source_parsing_profile(
|
||||
source_ids, payload.get('parsing_profile_id'), actor_id=_actor_id(),
|
||||
reason=str(payload.get('reason') or ''), operation='bulk',
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/parsing-binding-audits', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_source_parsing_binding_audits(source_id: int):
|
||||
"""返回库存站点的解析方案绑定审计,不包含任何 RPA 凭据。"""
|
||||
return _ok(shipping_inventory_service.get_source_parsing_binding_audits(source_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/activate', methods=['POST'])
|
||||
@require_admin
|
||||
def activate_shipping_inventory_source(source_id: int):
|
||||
"""仅在库存站点完成测试与必需绑定后启用正式运行。"""
|
||||
return _ok(shipping_inventory_service.activate_source(source_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/deactivate', methods=['POST'])
|
||||
@require_admin
|
||||
def deactivate_shipping_inventory_source(source_id: int):
|
||||
"""停用库存站点而不删除已有配置和运行审计。"""
|
||||
return _ok(shipping_inventory_service.deactivate_source(source_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_inventory_source(source_id: int):
|
||||
"""删除无运行/路由引用的错误库存源。"""
|
||||
shipping_inventory_service.delete_source(source_id)
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export', methods=['POST'])
|
||||
@require_admin
|
||||
def start_shipping_inventory_configuration_test(source_id: int):
|
||||
"""为停用库存站点发起异步测试导出,不产生生产库存快照。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return _ok(inventory_configuration_test.start_test_export(source_id, actor_id=_actor_id()), status=202)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/source-validation-batches', methods=['POST'])
|
||||
@require_admin
|
||||
def start_shipping_inventory_validation_batch():
|
||||
"""为多个停用且已绑定发布解析方案的站点发起批量测试验证。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
payload = request.get_json(silent=True) or {}
|
||||
return _ok(inventory_configuration_test.start_batch_test_export(
|
||||
payload.get('source_ids') or [], actor_id=_actor_id(),
|
||||
), status=202)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/source-validation-batches/latest-active', methods=['GET'])
|
||||
@require_admin
|
||||
def get_latest_active_shipping_inventory_validation_batch():
|
||||
"""恢复最近未结束的批量验证,避免页面刷新后丢失进度。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return _ok(inventory_configuration_test.get_latest_active_validation_batch())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/source-validation-batches/<int:batch_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_inventory_validation_batch(batch_id: int):
|
||||
"""读取批量验证汇总进度及每个站点的独立测试结果。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return _ok(inventory_configuration_test.get_validation_batch(batch_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/source-validation-batches/<int:batch_id>/retry-failed', methods=['POST'])
|
||||
@require_admin
|
||||
def retry_failed_shipping_inventory_validation_batch(batch_id: int):
|
||||
"""只重试批次中失败或配置已过期的站点,不重复导出成功项。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return _ok(inventory_configuration_test.retry_failed_validation_batch(batch_id, actor_id=_actor_id()), status=202)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export/latest', methods=['GET'])
|
||||
@require_admin
|
||||
def get_latest_shipping_inventory_configuration_test(source_id: int):
|
||||
"""读取当前库存站点配置对应的最近测试,使管理端可恢复异步执行状态。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return _ok(inventory_configuration_test.get_latest_test_run(source_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export/<string:run_no>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_inventory_configuration_test(source_id: int, run_no: str):
|
||||
"""读取库存站点测试导出的异步执行状态与结构识别结果。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return _ok(inventory_configuration_test.get_test_run(source_id, run_no))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export/<string:run_no>/confirm-profile', methods=['POST'])
|
||||
@require_admin
|
||||
def confirm_shipping_inventory_configuration_test_profile(source_id: int, run_no: str):
|
||||
"""确认测试结果采用的解析方案,并更新仍停用的库存站点绑定。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
payload = request.get_json(silent=True) or {}
|
||||
return _ok(inventory_configuration_test.confirm_test_profile(
|
||||
source_id, run_no, int(payload.get('profile_id') or 0), actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/snapshots', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_snapshots():
|
||||
"""列出库存快照的管理端只读记录。"""
|
||||
return _ok(shipping_inventory_service.list_snapshots())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/snapshots/<int:snapshot_id>/download', methods=['GET'])
|
||||
@require_admin
|
||||
def download_shipping_inventory_snapshot(snapshot_id: int):
|
||||
"""下载管理员选定的已托管库存快照,不向前端暴露服务器存储路径。"""
|
||||
path, filename = shipping_inventory_service.get_snapshot_download(snapshot_id)
|
||||
return send_file(path, as_attachment=True, download_name=filename)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/export-records', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_export_records():
|
||||
"""列出 RPA 导出结果;失败后应修复配置并重新创建运行。"""
|
||||
return _ok(shipping_inventory_service.list_export_records())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/routing-rules', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_rules():
|
||||
"""列出库存源路由规则及条件。"""
|
||||
return _ok(shipping_inventory_service.list_rules())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/routing-fields', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_routing_fields():
|
||||
"""返回路由规则可引用的已发布订单字段;路由不再读取固定系统投影。"""
|
||||
try:
|
||||
contract = order_schema_service.get_published_contract()
|
||||
order_fields = contract['fields']
|
||||
published = True
|
||||
except ConflictError as exc:
|
||||
if not isinstance(exc, ConflictError) or exc.code != 'SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED':
|
||||
raise
|
||||
order_fields = []
|
||||
published = False
|
||||
return _ok({
|
||||
'order_fields': order_fields,
|
||||
'order_schema_published': published,
|
||||
})
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/inventory-fields', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_fields():
|
||||
"""列出库存统一业务字段;管理工作区可查看已停用字段。"""
|
||||
return _ok(inventory_field_catalog.list_fields(include_retired=request.args.get('include_retired') == 'true'))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/inventory-fields', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_inventory_field():
|
||||
"""创建可由 DBS、Crane 等多个库存解析方案复用的扩展业务字段。"""
|
||||
return _ok(inventory_field_catalog.create_field(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/inventory-fields/<int:field_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_inventory_field(field_id: int):
|
||||
"""更新库存业务字段的名称、说明、格式和展示顺序。"""
|
||||
return _ok(inventory_field_catalog.update_field(field_id, request.get_json(silent=True) or {}, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/inventory-fields/<int:field_id>/retire', methods=['POST'])
|
||||
@require_admin
|
||||
def retire_shipping_inventory_field(field_id: int):
|
||||
"""停用无引用的扩展库存字段,核心字段始终由服务层保护。"""
|
||||
return _ok(inventory_field_catalog.retire_field(field_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/inventory-fields/<int:field_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_inventory_field(field_id: int):
|
||||
"""删除未被配置引用的扩展库存字段。"""
|
||||
inventory_field_catalog.delete_field(field_id)
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/configuration-catalog', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_inventory_configuration_catalog():
|
||||
"""返回 Profile、模板和路由编辑器共用的后端受控字段目录。"""
|
||||
from app.services.shipping_notice.excel_template import (
|
||||
ALLOWED_FORMATTERS,
|
||||
ALLOWED_ROW_MODES,
|
||||
ALLOWED_SOURCE_KINDS,
|
||||
ALLOWED_SYSTEM_FACTS,
|
||||
)
|
||||
try:
|
||||
contract = order_schema_service.get_published_contract()
|
||||
order_fields = contract['fields']
|
||||
published = True
|
||||
except ConflictError as exc:
|
||||
if not isinstance(exc, ConflictError) or exc.code != 'SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED':
|
||||
raise
|
||||
order_fields = []
|
||||
published = False
|
||||
return _ok({
|
||||
'order_fields': order_fields,
|
||||
'order_schema_published': published,
|
||||
'inventory_fields': inventory_field_catalog.list_fields(),
|
||||
'template_system_facts': sorted(ALLOWED_SYSTEM_FACTS),
|
||||
'template_source_kinds': sorted(ALLOWED_SOURCE_KINDS),
|
||||
'template_row_modes': sorted(ALLOWED_ROW_MODES),
|
||||
'template_formatters': sorted(ALLOWED_FORMATTERS),
|
||||
})
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/movement-fields', methods=['GET'])
|
||||
@require_admin
|
||||
def list_movement_fields():
|
||||
"""标准异动字段目录(只读领域契约,供收料异动解析规则映射表单;禁止增删)。"""
|
||||
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
|
||||
|
||||
return _ok([
|
||||
{
|
||||
'code': field.code, 'value_type': str(field.value_type),
|
||||
'required': bool(field.required), 'is_identity': bool(field.is_identity),
|
||||
}
|
||||
for field in MOVEMENT_FIELDS
|
||||
])
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/parsing-profiles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_parsing_profiles():
|
||||
"""列出可复用库存解析 Profile 版本。"""
|
||||
return _ok(inventory_parsing_profile.list_profiles())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/parsing-profiles', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_inventory_parsing_profile():
|
||||
"""创建库存解析 Profile 草稿。"""
|
||||
return _ok(inventory_parsing_profile.save_draft(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_inventory_parsing_profile(profile_id: int):
|
||||
"""更新库存解析 Profile 草稿。"""
|
||||
return _ok(inventory_parsing_profile.save_draft(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id,
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>/sample-replacement-preview/<int:analysis_id>', methods=['POST'])
|
||||
@require_admin
|
||||
def preview_shipping_inventory_sample_replacement(profile_id: int, analysis_id: int):
|
||||
"""比较库存映射草稿当前样本与候选样本,替换前必须由管理员确认差异。"""
|
||||
return _ok(inventory_structure_analysis.preview_profile_sample_replacement(
|
||||
profile_id, analysis_id, request.get_json(silent=True) or {},
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>/publish', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_shipping_inventory_parsing_profile(profile_id: int):
|
||||
"""发布库存解析 Profile。"""
|
||||
return _ok(inventory_parsing_profile.publish(profile_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>/retire', methods=['POST'])
|
||||
@require_admin
|
||||
def retire_shipping_inventory_parsing_profile(profile_id: int):
|
||||
"""退役无库存源引用的已发布解析 Profile。"""
|
||||
return _ok(inventory_parsing_profile.retire(profile_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_inventory_parsing_profile(profile_id: int):
|
||||
"""删除从未发布的解析 Profile 草稿。"""
|
||||
inventory_parsing_profile.delete_draft(profile_id)
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/inventory-structure-analyses', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_inventory_structure_analysis():
|
||||
"""上传库存样本并返回后端分析出的工作表、表头、栏位和建议。"""
|
||||
return _ok(inventory_structure_analysis.create_sample_upload(
|
||||
request.files.get('file'), actor_id=_actor_id(),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/inventory-structure-analyses/<int:analysis_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_inventory_structure_analysis(analysis_id: int):
|
||||
"""读取库存样本结构分析结果,供管理端继续配置解析方案。"""
|
||||
return _ok(inventory_structure_analysis.get_analysis(analysis_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/inventory-structure-analyses/<int:analysis_id>/create-profile-draft', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_inventory_parsing_draft_from_analysis(analysis_id: int):
|
||||
"""使用确认后的真实表头和匹配键创建库存文件解析方案草稿。"""
|
||||
return _ok(inventory_structure_analysis.create_profile_draft(
|
||||
analysis_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/inventory-structure-analyses/<int:analysis_id>/adopt-profile', methods=['POST'])
|
||||
@require_admin
|
||||
def adopt_shipping_inventory_parsing_profile(analysis_id: int):
|
||||
"""确认复用推荐的已发布库存文件解析方案,不修改库存站点绑定。"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
return _ok(inventory_structure_analysis.adopt_published_profile(
|
||||
analysis_id, int(payload.get('profile_id') or 0),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/temporary-inventory-sessions', methods=['GET'])
|
||||
@require_admin
|
||||
def list_confirmed_shipping_temporary_inventory_sessions():
|
||||
"""列出已通过质量校验、可供管理员沉淀为解析方案草稿的对话临时库存会话。"""
|
||||
from app.services.shipping_notice import inventory_temporary_session
|
||||
|
||||
return _ok(inventory_temporary_session.list_confirmed_temporary_inventory_sessions())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/temporary-inventory-sessions/<string:session_no>/create-profile-draft', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_parsing_draft_from_temporary_inventory_session(session_no: str):
|
||||
"""管理员将已确认临时会话锁定映射复制为解析方案草稿;发布仍走既有门禁。"""
|
||||
from app.services.shipping_notice import inventory_temporary_session
|
||||
|
||||
return _ok(inventory_temporary_session.create_parsing_profile_draft_from_temporary_session(
|
||||
session_no, request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/routing-rules', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_inventory_rule():
|
||||
"""创建草稿路由规则。"""
|
||||
return _ok(shipping_inventory_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/routing-rules/<int:rule_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_inventory_rule(rule_id: int):
|
||||
"""更新草稿规则;已发布规则由服务层拒绝原地修改。"""
|
||||
return _ok(shipping_inventory_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id(), rule_id=rule_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/routing-rules/<int:rule_id>/publish', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_shipping_inventory_rule(rule_id: int):
|
||||
"""发布草稿规则并写入不可变定义快照。"""
|
||||
return _ok(shipping_inventory_service.publish_rule(rule_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/routing-rules/<int:rule_id>/retire', methods=['POST'])
|
||||
@require_admin
|
||||
def retire_shipping_inventory_rule(rule_id: int):
|
||||
"""归档已发布规则,保留其审计版本但停止新路由使用。"""
|
||||
return _ok(shipping_inventory_service.retire_rule(rule_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/routing-rules/<int:rule_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_inventory_rule(rule_id: int):
|
||||
"""删除从未发布的草稿规则。"""
|
||||
shipping_inventory_service.delete_draft_rule(rule_id)
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/external-mappings', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_external_mappings():
|
||||
"""列出库存源到外部系统仓库映射。"""
|
||||
return _ok(shipping_inventory_service.list_external_mappings())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/external-mappings', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_inventory_external_mapping():
|
||||
"""创建精确或 Source 默认外部系统映射。"""
|
||||
return _ok(shipping_inventory_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/external-mappings/<int:mapping_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_inventory_external_mapping(mapping_id: int):
|
||||
"""更新外部系统映射,不参与任何调拨动作。"""
|
||||
return _ok(shipping_inventory_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id(), mapping_id=mapping_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/external-mappings/<int:mapping_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_inventory_external_mapping(mapping_id: int):
|
||||
"""删除错误的外部系统仓库映射。"""
|
||||
shipping_inventory_service.delete_external_mapping(mapping_id)
|
||||
return '', 204
|
||||
@@ -0,0 +1,126 @@
|
||||
"""
|
||||
api/admin/shipping_notice_admin.py
|
||||
|
||||
用途:发货通知仍留在本蓝图的管理面——Excel 模板、临时在手会话。
|
||||
依赖:admin blueprint、require_admin、excel_template、临时会话服务。
|
||||
逻辑:货代 RPA 管理路由(含 movement-fields / 报表规则)已迁至
|
||||
api/admin_freight_rpa.py 的 /api/admin/freight-rpa/;本文件不再注册那些路径。
|
||||
临时会话只改路径段 temporary-onhand-sessions,仍挂在 /shipping-notice/。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from flask import g, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.response import ok
|
||||
from app.services.shipping_notice import excel_template
|
||||
|
||||
|
||||
def _actor_id() -> int | None:
|
||||
"""取得 require_admin 已写入请求上下文的管理员 ID。"""
|
||||
return getattr(getattr(g, 'current_user', None), 'id', None)
|
||||
|
||||
|
||||
def _ok(data, *, status: int = 200):
|
||||
"""按平台统一 envelope 返回管理 API 成功结果。"""
|
||||
return ok(data, request_id=getattr(g, 'request_id', None), status=status)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_excel_templates():
|
||||
"""列出版本化发货 Excel 模板。"""
|
||||
return _ok(excel_template.list_templates())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_excel_template():
|
||||
"""上传 xlsx 并创建模板草稿版本。"""
|
||||
try:
|
||||
definition = json.loads(request.form.get('definition') or '{}')
|
||||
except json.JSONDecodeError as exc:
|
||||
from app.core.errors import ValidationError
|
||||
raise ValidationError('definition must be valid JSON', code='SHIPPING.EXCEL_TEMPLATE_INVALID') from exc
|
||||
data = {
|
||||
'template_code': request.form.get('template_code'),
|
||||
'display_name': request.form.get('display_name'),
|
||||
'definition': definition,
|
||||
}
|
||||
return _ok(excel_template.create_draft(request.files.get('file'), data, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_excel_template(template_id: int):
|
||||
"""更新 Excel 模板草稿定义。"""
|
||||
return _ok(excel_template.update_draft(template_id, request.get_json(silent=True) or {}))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/layout', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_excel_template_layout(template_id: int):
|
||||
"""读取已保存模板的工作表和栏位,编辑时无需重新上传 Excel。"""
|
||||
return _ok(excel_template.get_layout(template_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/new-version', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_excel_template_version(template_id: int):
|
||||
"""复制现有模板文件和映射定义,创建新的草稿版本。"""
|
||||
return _ok(excel_template.create_draft_from_existing(template_id, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/clone', methods=['POST'])
|
||||
@require_admin
|
||||
def clone_shipping_excel_template(template_id: int):
|
||||
"""复制已有模板为使用新编码的独立 v1 草稿。"""
|
||||
return _ok(excel_template.clone_as_new_template(
|
||||
template_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/publish', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_shipping_excel_template(template_id: int):
|
||||
"""校验工作簿和字段映射后发布模板。"""
|
||||
return _ok(excel_template.publish(template_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/retire', methods=['POST'])
|
||||
@require_admin
|
||||
def retire_shipping_excel_template(template_id: int):
|
||||
"""退役没有启用库存源引用的模板。"""
|
||||
return _ok(excel_template.retire(template_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_excel_template(template_id: int):
|
||||
"""删除从未发布且未使用的模板草稿。"""
|
||||
excel_template.delete_draft(template_id)
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/temporary-onhand-sessions', methods=['GET'])
|
||||
@require_admin
|
||||
def list_confirmed_shipping_temporary_inventory_sessions():
|
||||
"""列出已通过质量校验、可供管理员沉淀为解析方案草稿的对话临时库存会话。"""
|
||||
from app.services.shipping_notice import onhand_temporary_session
|
||||
|
||||
return _ok(onhand_temporary_session.list_confirmed_temporary_inventory_sessions())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/temporary-onhand-sessions/<string:session_no>/create-profile-draft', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_parsing_draft_from_temporary_inventory_session(session_no: str):
|
||||
"""管理员将已确认临时会话锁定映射复制为解析方案草稿;发布仍走既有门禁。"""
|
||||
from app.services.shipping_notice import onhand_temporary_session
|
||||
|
||||
return _ok(onhand_temporary_session.create_parsing_profile_draft_from_temporary_session(
|
||||
session_no, request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
), status=201)
|
||||
@@ -0,0 +1,157 @@
|
||||
"""
|
||||
api/admin/transfer_type.py
|
||||
|
||||
用途:调拨类型配置的管理 API(列表/创建/更新,ADR 0002 类型配置化)。
|
||||
依赖:admin blueprint、require_admin、transfer_type_config_service(Task 4)。
|
||||
逻辑:路由只做鉴权、参数形态门禁与错误码→HTTP 状态映射;业务校验、配置
|
||||
规范化与事务全在服务层。重复 code(服务层预检)与并发唯一键冲突
|
||||
(IntegrityError 兜底)统一映射 422 TRANSFER.TRANSFER_TYPE_CODE_EXISTS;
|
||||
code 不可变 422;更新目标不存在 404。本模块是稳定错误码 → 前端四语言
|
||||
errors.json 文案的 API 侧登记点(TRANSFER_TYPE_*/SCOPE/WAREHOUSE/TRANSFORM)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import g, request
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import AppError, ValidationError
|
||||
from app.core.response import ok, utc_iso
|
||||
from app.services.in_transit_transfer import transfer_type_config_service as service
|
||||
|
||||
# 稳定错误码统一转出(服务层常量 + 引擎码 + 匹配链码),避免 API 层散落字符串。
|
||||
ERR_NOT_CONFIGURED = service.TRANSFER_TYPE_NOT_CONFIGURED
|
||||
ERR_CODE_EXISTS = service.TRANSFER_TYPE_CODE_EXISTS
|
||||
ERR_CODE_IMMUTABLE = service.TRANSFER_TYPE_CODE_IMMUTABLE
|
||||
ERR_WAREHOUSE_INVALID = service.WAREHOUSE_CONFIG_INVALID
|
||||
ERR_SCOPE_INVALID = "TRANSFER.SCOPE_RULE_INVALID"
|
||||
ERR_TRANSFORM_INVALID = "TRANSFER.TRANSFORM_RULE_INVALID"
|
||||
|
||||
# 服务层业务码 → HTTP 状态映射:编码冲突/不可变是语义冲突(422)、更新目标
|
||||
# 不存在(404);不在表内的码(含 VALIDATION.INVALID_PARAM 与三块配置引擎码)
|
||||
# 保持 ValidationError 默认 400。
|
||||
_HTTP_STATUS_BY_CODE = {
|
||||
ERR_CODE_EXISTS: 422,
|
||||
ERR_CODE_IMMUTABLE: 422,
|
||||
ERR_NOT_CONFIGURED: 404,
|
||||
}
|
||||
|
||||
|
||||
def _actor_id() -> int | None:
|
||||
"""取得 require_admin 已写入请求上下文的管理员 ID。"""
|
||||
return getattr(getattr(g, 'current_user', None), 'id', None)
|
||||
|
||||
|
||||
def _ok(data, *, status: int = 200):
|
||||
"""按平台统一 envelope 返回管理 API 成功结果。"""
|
||||
return ok(data, request_id=getattr(g, 'request_id', None), status=status)
|
||||
|
||||
|
||||
def _reraise_with_status(exc: ValidationError) -> None:
|
||||
"""按稳定错误码改写 HTTP 状态后重抛;表外码原样透传(保持 400)。"""
|
||||
status = _HTTP_STATUS_BY_CODE.get(exc.code)
|
||||
if status is None:
|
||||
raise exc
|
||||
raise AppError(
|
||||
code=exc.code, message=exc.message, http_status=status, details=exc.details,
|
||||
) from exc
|
||||
|
||||
|
||||
def _request_payload() -> dict:
|
||||
"""读取 JSON body 并保证是 dict(非对象形态统一 400,防下游 AttributeError)。"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
if not isinstance(payload, dict):
|
||||
raise ValidationError("request body must be a JSON object")
|
||||
return payload
|
||||
|
||||
|
||||
def _enforce_field_types(payload: dict) -> None:
|
||||
"""API 层参数形态门禁:enabled 只接受布尔/整数、sort_order 只接受整数。
|
||||
|
||||
防御字符串形态(如 "false")绕过 API 直达服务层被 bool() 强转为真值;
|
||||
业务校验(code 格式、names、三块配置)仍归服务层,此处只挡类型。
|
||||
"""
|
||||
if "enabled" in payload and not isinstance(payload["enabled"], (bool, int)):
|
||||
raise ValidationError(
|
||||
"enabled must be boolean or integer", details={"enabled": payload["enabled"]},
|
||||
)
|
||||
sort_order = payload.get("sort_order")
|
||||
if "sort_order" in payload and (not isinstance(sort_order, int) or isinstance(sort_order, bool)):
|
||||
raise ValidationError("sort_order must be integer", details={"sort_order": sort_order})
|
||||
|
||||
|
||||
def _warehouse_role_json(role) -> dict:
|
||||
"""WarehouseRole → 管理端 JSON 项(与入库规范化形态读写对称)。"""
|
||||
return {
|
||||
"mode": role.mode,
|
||||
"warehouse_code": role.warehouse_code,
|
||||
"external_org": role.external_org,
|
||||
}
|
||||
|
||||
|
||||
def _serialize_config(dto) -> dict:
|
||||
"""TransferTypeConfigDTO → 管理 API 全量视图(三块配置全暴露,仅管理端可见)。"""
|
||||
return {
|
||||
"code": dto.code,
|
||||
"names": dict(dto.names),
|
||||
"enabled": dto.enabled,
|
||||
"sort_order": dto.sort_order,
|
||||
"scope_rules": [
|
||||
{"field": rule.field, "match": rule.match, "values": list(rule.values)}
|
||||
for rule in dto.scope_rules
|
||||
],
|
||||
"warehouse_config": {
|
||||
"from": _warehouse_role_json(dto.warehouse_config.from_role),
|
||||
"to": _warehouse_role_json(dto.warehouse_config.to_role),
|
||||
},
|
||||
"transform_rules": [
|
||||
{"field": rule.field, "op": rule.op, "source": rule.source, "target": rule.target}
|
||||
for rule in dto.transform_rules
|
||||
],
|
||||
"description": dto.description,
|
||||
"updated_at": utc_iso(dto.updated_at),
|
||||
}
|
||||
|
||||
|
||||
@admin_bp.route('/in-transit-transfer/transfer-types', methods=['GET'])
|
||||
@require_admin
|
||||
def list_transfer_types():
|
||||
"""全量类型配置(含停用),sort_order 升序——管理页列表。"""
|
||||
return _ok([_serialize_config(dto) for dto in service.list_configs()])
|
||||
|
||||
|
||||
@admin_bp.route('/in-transit-transfer/transfer-types', methods=['POST'])
|
||||
@require_admin
|
||||
def create_transfer_type():
|
||||
"""创建类型配置;重复 code(预检或并发唯一键)统一 422。"""
|
||||
payload = _request_payload()
|
||||
_enforce_field_types(payload)
|
||||
try:
|
||||
dto = service.create_config(payload, operator_id=_actor_id())
|
||||
except ValidationError as exc:
|
||||
_reraise_with_status(exc)
|
||||
except IntegrityError as exc:
|
||||
# [防御] 服务层唯一性预检在事务之前,并发窗口漏出的唯一键冲突兜底映射
|
||||
# 422,避免 500 漏给管理页(控制器裁定①)。
|
||||
raise AppError(
|
||||
code=ERR_CODE_EXISTS,
|
||||
message="transfer type code already exists",
|
||||
http_status=422,
|
||||
details={},
|
||||
) from exc
|
||||
return _ok(_serialize_config(dto), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/in-transit-transfer/transfer-types/<string:code>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_transfer_type(code: str):
|
||||
"""更新类型配置(部分更新;改 code → 422,目标不存在 → 404)。"""
|
||||
payload = _request_payload()
|
||||
_enforce_field_types(payload)
|
||||
try:
|
||||
dto = service.update_config(code, payload, operator_id=_actor_id())
|
||||
except ValidationError as exc:
|
||||
_reraise_with_status(exc)
|
||||
return _ok(_serialize_config(dto))
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
"""
|
||||
backend/app/api/admin/users.py
|
||||
|
||||
用途:管理后台用户 CRUD API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/user_service、core.auth.jwt。
|
||||
逻辑:/users* 路由。
|
||||
鐢ㄩ€旓細绠$悊鍚庡彴鐢ㄦ埛 CRUD API锛堣杽璺敱灞傦級銆?
|
||||
渚濊禆锛歛dmin.blueprint銆乻ervices/admin/user_service銆乧ore.auth.jwt銆?
|
||||
閫昏緫锛?users* 璺敱銆?
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
@@ -20,7 +20,7 @@ def _query_params() -> dict[str, str]:
|
||||
@admin_bp.route('/users', methods=['GET'])
|
||||
@require_admin
|
||||
def list_users():
|
||||
"""列出管理端用户(支持分页与筛选)。"""
|
||||
"""Admin user operation."""
|
||||
result = user_service.list_users(_query_params())
|
||||
return jsonify(result)
|
||||
|
||||
@@ -28,7 +28,7 @@ def list_users():
|
||||
@admin_bp.route('/users', methods=['POST'])
|
||||
@require_admin
|
||||
def create_user():
|
||||
"""创建用户并同步 Casdoor。"""
|
||||
"""Admin user operation."""
|
||||
data = request.get_json() or {}
|
||||
payload = user_service.create_user(data)
|
||||
return jsonify(payload), 201
|
||||
@@ -37,22 +37,30 @@ def create_user():
|
||||
@admin_bp.route('/users/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_user(id: int):
|
||||
"""更新用户资料;有 password 时同步 Casdoor 改密。"""
|
||||
"""Admin user operation."""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(user_service.update_user(id, data))
|
||||
|
||||
|
||||
@admin_bp.route('/users/batch', methods=['PUT'])
|
||||
@require_admin
|
||||
def batch_update_users():
|
||||
"""批量更新用户部门 / 角色 / 状态。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(user_service.batch_update_users(data.get('user_ids', []), data.get('data') or {}))
|
||||
|
||||
|
||||
@admin_bp.route('/users/cleanup-rejected', methods=['POST'])
|
||||
@require_admin
|
||||
def cleanup_rejected_users():
|
||||
"""批量删除 status=rejected 的用户。"""
|
||||
"""Admin user operation."""
|
||||
return jsonify(user_service.cleanup_rejected_users())
|
||||
|
||||
|
||||
@admin_bp.route('/users/batch-delete', methods=['POST'])
|
||||
@require_admin
|
||||
def batch_delete_users():
|
||||
"""批量删除用户(排除当前登录管理员)。"""
|
||||
"""Admin user operation."""
|
||||
data = request.get_json() or {}
|
||||
current_user = _get_auth_user()
|
||||
current_user_id = current_user.id if current_user else None
|
||||
@@ -62,21 +70,7 @@ def batch_delete_users():
|
||||
@admin_bp.route('/users/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_user(id: int):
|
||||
"""删除单个用户。"""
|
||||
"""Admin user operation."""
|
||||
current_user = _get_auth_user()
|
||||
current_user_id = current_user.id if current_user else None
|
||||
return jsonify(user_service.delete_user(id, current_user_id=current_user_id))
|
||||
|
||||
|
||||
@admin_bp.route('/users/<int:id>/approve', methods=['POST'])
|
||||
@require_admin
|
||||
def approve_user(id: int):
|
||||
"""审批通过用户。"""
|
||||
return jsonify(user_service.approve_user(id))
|
||||
|
||||
|
||||
@admin_bp.route('/users/<int:id>/reject', methods=['POST'])
|
||||
@require_admin
|
||||
def reject_user(id: int):
|
||||
"""拒绝用户注册。"""
|
||||
return jsonify(user_service.reject_user(id))
|
||||
@@ -0,0 +1,543 @@
|
||||
"""
|
||||
api/admin_freight_rpa.py
|
||||
|
||||
用途:货代 RPA 管理 API,挂在 /api/admin/freight-rpa/(站点 sources、onhand 配置、
|
||||
入站/出站报表配置、报表规则、异动字段目录、RPA Profile)。
|
||||
依赖:admin blueprint、require_admin、freight_rpa_source_admin_service、
|
||||
shipping_onhand_admin_service、freight_rpa_report_config_service、
|
||||
freight_rpa.parsing_profile、
|
||||
onhand 字段/结构分析服务、in_transit_transfer.movement_contract。
|
||||
逻辑:路由只做鉴权与 JSON 参数;业务校验与事务留在服务层。
|
||||
不保留 /shipping-notice/ 双路由。Excel 模板与 temporary-onhand-sessions
|
||||
仍在 admin/shipping_notice_admin.py。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import g, request, send_file
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import ConflictError
|
||||
from app.core.response import ok
|
||||
from app.services.admin import (
|
||||
freight_rpa_report_config_service,
|
||||
freight_rpa_source_admin_service,
|
||||
shipping_onhand_admin_service,
|
||||
)
|
||||
from app.services.freight_rpa import parsing_profile as onhand_parsing_profile
|
||||
from app.services.shipping_notice import onhand_field_catalog, onhand_structure_analysis
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
|
||||
|
||||
def _actor_id() -> int | None:
|
||||
"""取得 require_admin 已写入请求上下文的管理员 ID。"""
|
||||
return getattr(getattr(g, 'current_user', None), 'id', None)
|
||||
|
||||
|
||||
def _ok(data, *, status: int = 200):
|
||||
"""按平台统一 envelope 返回管理 API 成功结果。"""
|
||||
return ok(data, request_id=getattr(g, 'request_id', None), status=status)
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/rpa-profiles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_rpa_profiles():
|
||||
"""列出 RPA Profile;响应含用户名明文,不含密码与密文。"""
|
||||
return _ok(freight_rpa_source_admin_service.list_profiles())
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/rpa-profiles', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_rpa_profile():
|
||||
"""创建 RPA Profile;明文凭据仅在本次请求内用于加密。"""
|
||||
return _ok(freight_rpa_source_admin_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/rpa-profiles/<int:profile_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_rpa_profile(profile_id: int):
|
||||
"""更新 RPA Profile;用户名与已存明文相同、或密码留空时不重写对应密文。"""
|
||||
return _ok(freight_rpa_source_admin_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/rpa-profiles/<int:profile_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_rpa_profile(profile_id: int):
|
||||
"""删除没有库存源引用的错误连接配置。"""
|
||||
freight_rpa_source_admin_service.delete_profile(profile_id)
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/sources', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_sources():
|
||||
"""列出库存业务来源。"""
|
||||
return _ok(freight_rpa_source_admin_service.list_sources())
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/sources', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_inventory_source():
|
||||
"""保存停用的库存站点基础配置;正式启用由独立接口控制。"""
|
||||
return _ok(freight_rpa_source_admin_service.save_source(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(), allow_enable_transition=False,
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/sources/<int:source_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_inventory_source(source_id: int):
|
||||
"""更新库存站点业务配置;不能借由普通保存绕过启用门禁。"""
|
||||
return _ok(freight_rpa_source_admin_service.save_source(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(), source_id=source_id,
|
||||
allow_enable_transition=False,
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/sources/<int:source_id>/inbound-report-config', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_inbound_report_config(source_id: int):
|
||||
"""读取站点独立入站报表配置;库存配置和入站配置永不混写。"""
|
||||
return _ok(freight_rpa_report_config_service.get_inbound_report_config(source_id))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/sources/<int:source_id>/inbound-report-config', methods=['PUT'])
|
||||
@require_admin
|
||||
def save_shipping_inbound_report_config(source_id: int):
|
||||
"""保存独立入站报表配置,并由服务记录可追溯的前后快照审计。"""
|
||||
return _ok(freight_rpa_report_config_service.save_inbound_report_config(
|
||||
source_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/sources/<int:source_id>/outbound-report-config', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_outbound_report_config(source_id: int):
|
||||
"""读取站点独立出站报表配置;库存/入站/出站配置永不混写。"""
|
||||
return _ok(freight_rpa_report_config_service.get_outbound_report_config(source_id))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/sources/<int:source_id>/outbound-report-config', methods=['PUT'])
|
||||
@require_admin
|
||||
def save_shipping_outbound_report_config(source_id: int):
|
||||
"""保存独立出站报表配置,并由服务记录可追溯的前后快照审计。"""
|
||||
return _ok(freight_rpa_report_config_service.save_outbound_report_config(
|
||||
source_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/movement-fields', methods=['GET'])
|
||||
@require_admin
|
||||
def list_freight_rpa_movement_fields():
|
||||
"""标准异动字段目录(只读领域契约,供入站/出站报表规则映射表单)。"""
|
||||
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
|
||||
|
||||
return _ok([
|
||||
{
|
||||
'code': field.code, 'value_type': str(field.value_type),
|
||||
'required': bool(field.required), 'is_identity': bool(field.is_identity),
|
||||
}
|
||||
for field in MOVEMENT_FIELDS
|
||||
])
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/sources/<int:source_id>/bind-parsing-profile', methods=['POST'])
|
||||
@require_admin
|
||||
def bind_shipping_inventory_source_parsing_profile(source_id: int):
|
||||
"""直接为停用库存站点绑定已发布解析方案;审计说明由系统自动记录。"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
rows = freight_rpa_source_admin_service.bind_source_parsing_profile(
|
||||
[source_id], payload.get('parsing_profile_id'), actor_id=_actor_id(),
|
||||
reason=str(payload.get('reason') or ''), operation='direct',
|
||||
)
|
||||
return _ok(rows[0])
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/sources/bulk-bind-parsing-profile', methods=['POST'])
|
||||
@require_admin
|
||||
def bulk_bind_shipping_inventory_source_parsing_profile():
|
||||
"""原子批量绑定已发布解析方案;任一站点预检失败则整批不写入。"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
source_ids = payload.get('source_ids')
|
||||
if not isinstance(source_ids, list):
|
||||
source_ids = []
|
||||
return _ok(freight_rpa_source_admin_service.bind_source_parsing_profile(
|
||||
source_ids, payload.get('parsing_profile_id'), actor_id=_actor_id(),
|
||||
reason=str(payload.get('reason') or ''), operation='bulk',
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/sources/<int:source_id>/parsing-binding-audits', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_source_parsing_binding_audits(source_id: int):
|
||||
"""返回库存站点的解析方案绑定审计,不包含任何 RPA 凭据。"""
|
||||
return _ok(freight_rpa_source_admin_service.get_source_parsing_binding_audits(source_id))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/sources/<int:source_id>/activate', methods=['POST'])
|
||||
@require_admin
|
||||
def activate_shipping_inventory_source(source_id: int):
|
||||
"""仅在库存站点完成测试与必需绑定后启用正式运行。"""
|
||||
return _ok(freight_rpa_source_admin_service.activate_source(source_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/sources/<int:source_id>/deactivate', methods=['POST'])
|
||||
@require_admin
|
||||
def deactivate_shipping_inventory_source(source_id: int):
|
||||
"""停用库存站点而不删除已有配置和运行审计。"""
|
||||
return _ok(freight_rpa_source_admin_service.deactivate_source(source_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/sources/<int:source_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_inventory_source(source_id: int):
|
||||
"""删除无运行/路由引用的错误库存源。"""
|
||||
freight_rpa_source_admin_service.delete_source(source_id)
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/sources/<int:source_id>/test-export', methods=['POST'])
|
||||
@require_admin
|
||||
def start_shipping_inventory_configuration_test(source_id: int):
|
||||
"""为停用库存站点发起异步测试导出,不产生生产库存快照。"""
|
||||
from app.services.shipping_notice import onhand_configuration_test
|
||||
|
||||
return _ok(onhand_configuration_test.start_test_export(source_id, actor_id=_actor_id()), status=202)
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/validation-batches', methods=['POST'])
|
||||
@require_admin
|
||||
def start_shipping_inventory_validation_batch():
|
||||
"""为多个停用且已绑定发布解析方案的站点发起批量测试验证。"""
|
||||
from app.services.shipping_notice import onhand_configuration_test
|
||||
|
||||
payload = request.get_json(silent=True) or {}
|
||||
return _ok(onhand_configuration_test.start_batch_test_export(
|
||||
payload.get('source_ids') or [], actor_id=_actor_id(),
|
||||
), status=202)
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/validation-batches/latest-active', methods=['GET'])
|
||||
@require_admin
|
||||
def get_latest_active_shipping_inventory_validation_batch():
|
||||
"""恢复最近未结束的批量验证,避免页面刷新后丢失进度。"""
|
||||
from app.services.shipping_notice import onhand_configuration_test
|
||||
|
||||
return _ok(onhand_configuration_test.get_latest_active_validation_batch())
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/validation-batches/<int:batch_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_inventory_validation_batch(batch_id: int):
|
||||
"""读取批量验证汇总进度及每个站点的独立测试结果。"""
|
||||
from app.services.shipping_notice import onhand_configuration_test
|
||||
|
||||
return _ok(onhand_configuration_test.get_validation_batch(batch_id))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/validation-batches/<int:batch_id>/retry-failed', methods=['POST'])
|
||||
@require_admin
|
||||
def retry_failed_shipping_inventory_validation_batch(batch_id: int):
|
||||
"""只重试批次中失败或配置已过期的站点,不重复导出成功项。"""
|
||||
from app.services.shipping_notice import onhand_configuration_test
|
||||
|
||||
return _ok(onhand_configuration_test.retry_failed_validation_batch(batch_id, actor_id=_actor_id()), status=202)
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/sources/<int:source_id>/test-export/latest', methods=['GET'])
|
||||
@require_admin
|
||||
def get_latest_shipping_inventory_configuration_test(source_id: int):
|
||||
"""读取当前库存站点配置对应的最近测试,使管理端可恢复异步执行状态。"""
|
||||
from app.services.shipping_notice import onhand_configuration_test
|
||||
|
||||
return _ok(onhand_configuration_test.get_latest_test_run(source_id))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/sources/<int:source_id>/test-export/<string:run_no>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_inventory_configuration_test(source_id: int, run_no: str):
|
||||
"""读取库存站点测试导出的异步执行状态与结构识别结果。"""
|
||||
from app.services.shipping_notice import onhand_configuration_test
|
||||
|
||||
return _ok(onhand_configuration_test.get_test_run(source_id, run_no))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/sources/<int:source_id>/test-export/<string:run_no>/confirm-profile', methods=['POST'])
|
||||
@require_admin
|
||||
def confirm_shipping_inventory_configuration_test_profile(source_id: int, run_no: str):
|
||||
"""确认测试结果采用的解析方案,并更新仍停用的库存站点绑定。"""
|
||||
from app.services.shipping_notice import onhand_configuration_test
|
||||
|
||||
payload = request.get_json(silent=True) or {}
|
||||
return _ok(onhand_configuration_test.confirm_test_profile(
|
||||
source_id, run_no, int(payload.get('profile_id') or 0), actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/snapshots', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_snapshots():
|
||||
"""列出库存快照的管理端只读记录。"""
|
||||
return _ok(shipping_onhand_admin_service.list_snapshots())
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/snapshots/<int:snapshot_id>/download', methods=['GET'])
|
||||
@require_admin
|
||||
def download_shipping_inventory_snapshot(snapshot_id: int):
|
||||
"""下载管理员选定的已托管库存快照,不向前端暴露服务器存储路径。"""
|
||||
path, filename = shipping_onhand_admin_service.get_snapshot_download(snapshot_id)
|
||||
return send_file(path, as_attachment=True, download_name=filename)
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/export-records', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_export_records():
|
||||
"""列出 RPA 导出结果;失败后应修复配置并重新创建运行。"""
|
||||
return _ok(shipping_onhand_admin_service.list_export_records())
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/routing-rules', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_rules():
|
||||
"""列出库存源路由规则及条件。"""
|
||||
return _ok(shipping_onhand_admin_service.list_rules())
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/routing-fields', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_routing_fields():
|
||||
"""返回路由规则可引用的已发布订单字段;路由不再读取固定系统投影。"""
|
||||
try:
|
||||
contract = order_schema_service.get_published_contract()
|
||||
order_fields = contract['fields']
|
||||
published = True
|
||||
except ConflictError as exc:
|
||||
if not isinstance(exc, ConflictError) or exc.code != 'SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED':
|
||||
raise
|
||||
order_fields = []
|
||||
published = False
|
||||
return _ok({
|
||||
'order_fields': order_fields,
|
||||
'order_schema_published': published,
|
||||
})
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/fields', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_fields():
|
||||
"""列出库存统一业务字段;管理工作区可查看已停用字段。"""
|
||||
return _ok(onhand_field_catalog.list_fields(include_retired=request.args.get('include_retired') == 'true'))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/fields', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_inventory_field():
|
||||
"""创建可由 DBS、Crane 等多个库存解析方案复用的扩展业务字段。"""
|
||||
return _ok(onhand_field_catalog.create_field(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/fields/<int:field_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_inventory_field(field_id: int):
|
||||
"""更新库存业务字段的名称、说明、格式和展示顺序。"""
|
||||
return _ok(onhand_field_catalog.update_field(field_id, request.get_json(silent=True) or {}, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/fields/<int:field_id>/retire', methods=['POST'])
|
||||
@require_admin
|
||||
def retire_shipping_inventory_field(field_id: int):
|
||||
"""停用无引用的扩展库存字段,核心字段始终由服务层保护。"""
|
||||
return _ok(onhand_field_catalog.retire_field(field_id))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/fields/<int:field_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_inventory_field(field_id: int):
|
||||
"""删除未被配置引用的扩展库存字段。"""
|
||||
onhand_field_catalog.delete_field(field_id)
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/configuration-catalog', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_inventory_configuration_catalog():
|
||||
"""返回 Profile、模板和路由编辑器共用的后端受控字段目录。"""
|
||||
from app.services.shipping_notice.excel_template import (
|
||||
ALLOWED_FORMATTERS,
|
||||
ALLOWED_ROW_MODES,
|
||||
ALLOWED_SOURCE_KINDS,
|
||||
ALLOWED_SYSTEM_FACTS,
|
||||
)
|
||||
try:
|
||||
contract = order_schema_service.get_published_contract()
|
||||
order_fields = contract['fields']
|
||||
published = True
|
||||
except ConflictError as exc:
|
||||
if not isinstance(exc, ConflictError) or exc.code != 'SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED':
|
||||
raise
|
||||
order_fields = []
|
||||
published = False
|
||||
return _ok({
|
||||
'order_fields': order_fields,
|
||||
'order_schema_published': published,
|
||||
'inventory_fields': onhand_field_catalog.list_fields(),
|
||||
'template_system_facts': sorted(ALLOWED_SYSTEM_FACTS),
|
||||
'template_source_kinds': sorted(ALLOWED_SOURCE_KINDS),
|
||||
'template_row_modes': sorted(ALLOWED_ROW_MODES),
|
||||
'template_formatters': sorted(ALLOWED_FORMATTERS),
|
||||
})
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/parsing-profiles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_parsing_profiles():
|
||||
"""列出可复用库存解析 Profile 版本。"""
|
||||
return _ok(onhand_parsing_profile.list_profiles())
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/parsing-profiles', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_inventory_parsing_profile():
|
||||
"""创建库存解析 Profile 草稿。"""
|
||||
return _ok(onhand_parsing_profile.save_draft(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/parsing-profiles/<int:profile_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_inventory_parsing_profile(profile_id: int):
|
||||
"""更新库存解析 Profile 草稿。"""
|
||||
return _ok(onhand_parsing_profile.save_draft(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id,
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/parsing-profiles/<int:profile_id>/sample-replacement-preview/<int:analysis_id>', methods=['POST'])
|
||||
@require_admin
|
||||
def preview_shipping_inventory_sample_replacement(profile_id: int, analysis_id: int):
|
||||
"""比较库存映射草稿当前样本与候选样本,替换前必须由管理员确认差异。"""
|
||||
return _ok(onhand_structure_analysis.preview_profile_sample_replacement(
|
||||
profile_id, analysis_id, request.get_json(silent=True) or {},
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/parsing-profiles/<int:profile_id>/publish', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_shipping_inventory_parsing_profile(profile_id: int):
|
||||
"""发布库存解析 Profile。"""
|
||||
return _ok(onhand_parsing_profile.publish(profile_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/parsing-profiles/<int:profile_id>/retire', methods=['POST'])
|
||||
@require_admin
|
||||
def retire_shipping_inventory_parsing_profile(profile_id: int):
|
||||
"""退役无库存源引用的已发布解析 Profile。"""
|
||||
return _ok(onhand_parsing_profile.retire(profile_id))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/parsing-profiles/<int:profile_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_inventory_parsing_profile(profile_id: int):
|
||||
"""删除从未发布的解析 Profile 草稿。"""
|
||||
onhand_parsing_profile.delete_draft(profile_id)
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/structure-analyses', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_inventory_structure_analysis():
|
||||
"""上传库存样本并返回后端分析出的工作表、表头、栏位和建议。"""
|
||||
return _ok(onhand_structure_analysis.create_sample_upload(
|
||||
request.files.get('file'), actor_id=_actor_id(),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/structure-analyses/<int:analysis_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_inventory_structure_analysis(analysis_id: int):
|
||||
"""读取库存样本结构分析结果,供管理端继续配置解析方案。"""
|
||||
return _ok(onhand_structure_analysis.get_analysis(analysis_id))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/structure-analyses/<int:analysis_id>/create-profile-draft', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_inventory_parsing_draft_from_analysis(analysis_id: int):
|
||||
"""使用确认后的真实表头和匹配键创建库存文件解析方案草稿。"""
|
||||
return _ok(onhand_structure_analysis.create_profile_draft(
|
||||
analysis_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/structure-analyses/<int:analysis_id>/adopt-profile', methods=['POST'])
|
||||
@require_admin
|
||||
def adopt_shipping_inventory_parsing_profile(analysis_id: int):
|
||||
"""确认复用推荐的已发布库存文件解析方案,不修改库存站点绑定。"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
return _ok(onhand_structure_analysis.adopt_published_profile(
|
||||
analysis_id, int(payload.get('profile_id') or 0),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/routing-rules', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_inventory_rule():
|
||||
"""创建草稿路由规则。"""
|
||||
return _ok(shipping_onhand_admin_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/routing-rules/<int:rule_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_inventory_rule(rule_id: int):
|
||||
"""更新草稿规则;已发布规则由服务层拒绝原地修改。"""
|
||||
return _ok(shipping_onhand_admin_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id(), rule_id=rule_id))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/routing-rules/<int:rule_id>/publish', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_shipping_inventory_rule(rule_id: int):
|
||||
"""发布草稿规则并写入不可变定义快照。"""
|
||||
return _ok(shipping_onhand_admin_service.publish_rule(rule_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/routing-rules/<int:rule_id>/retire', methods=['POST'])
|
||||
@require_admin
|
||||
def retire_shipping_inventory_rule(rule_id: int):
|
||||
"""归档已发布规则,保留其审计版本但停止新路由使用。"""
|
||||
return _ok(shipping_onhand_admin_service.retire_rule(rule_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/routing-rules/<int:rule_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_inventory_rule(rule_id: int):
|
||||
"""删除从未发布的草稿规则。"""
|
||||
shipping_onhand_admin_service.delete_draft_rule(rule_id)
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/external-mappings', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_external_mappings():
|
||||
"""列出库存源到外部系统仓库映射。"""
|
||||
return _ok(shipping_onhand_admin_service.list_external_mappings())
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/external-mappings', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_inventory_external_mapping():
|
||||
"""创建精确或 Source 默认外部系统映射。"""
|
||||
return _ok(shipping_onhand_admin_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/external-mappings/<int:mapping_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_inventory_external_mapping(mapping_id: int):
|
||||
"""更新外部系统映射,不参与任何调拨动作。"""
|
||||
return _ok(shipping_onhand_admin_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id(), mapping_id=mapping_id))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/onhand/external-mappings/<int:mapping_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_inventory_external_mapping(mapping_id: int):
|
||||
"""删除错误的外部系统仓库映射。"""
|
||||
shipping_onhand_admin_service.delete_external_mapping(mapping_id)
|
||||
return '', 204
|
||||
@@ -1,107 +1,10 @@
|
||||
"""
|
||||
backend/app/api/agent_runtime_context_tools.py
|
||||
|
||||
用途:暴露 agent_runtime_context 只读 Tool API,供 Dify Chatflow 解析 HXOPS 上下文。
|
||||
依赖:app.core.errors、agent_runtime_context.parser/openapi_spec、shipping_notice.tool_api_url。
|
||||
逻辑:OpenAPI 文档接口放行;parse 工具复用 Authorization Bearer / X-Integration-Key 鉴权,不推进业务状态。
|
||||
用途:兼容旧 import 路径的薄 shim(真实现已迁至 api/tools/agent_runtime_context.py)。
|
||||
依赖:app.api.tools.agent_runtime_context。
|
||||
逻辑:保留 Blueprint;新代码请从 app.api.tools 导入。
|
||||
"""
|
||||
from app.api.tools.agent_runtime_context import agent_runtime_context_bp # noqa: F401
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request
|
||||
|
||||
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError
|
||||
from app.services.agent_runtime_context.openapi_spec import build_agent_runtime_context_openapi_spec
|
||||
from app.services.agent_runtime_context.parser import parse_agent_runtime_context
|
||||
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||
|
||||
agent_runtime_context_bp = Blueprint("agent_runtime_context_tools", __name__)
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验 agent_runtime_context Tool API 鉴权 Header。
|
||||
|
||||
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;Dify 请求 parse 工具时由 before_request 自动触发。
|
||||
|
||||
核心逻辑:只接受 Authorization Bearer 或 X-Integration-Key,复用 INTEGRATION_API_KEY 作为平台工具密钥。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 未配置 INTEGRATION_API_KEY。
|
||||
UnauthorizedError: 缺少或传入错误鉴权。
|
||||
"""
|
||||
configured = str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError("INTEGRATION_API_KEY is not configured", code="missing_auth")
|
||||
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||
if configured in {token, integration_key}:
|
||||
return
|
||||
if not token and not integration_key:
|
||||
raise UnauthorizedError("missing_auth")
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
"""
|
||||
归一化 Tool API 错误码。
|
||||
|
||||
核心逻辑:保持与 shipping/file-check Tool API 的 ok:false 响应风格一致,便于 Dify 侧统一处理。
|
||||
|
||||
Args:
|
||||
exc: 业务异常。
|
||||
|
||||
Returns:
|
||||
Tool 侧错误码。
|
||||
"""
|
||||
message = str(exc.message or "").strip()
|
||||
if message in {"missing_auth", "invalid_auth"}:
|
||||
return message
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
return "missing_auth"
|
||||
return exc.code
|
||||
|
||||
|
||||
@agent_runtime_context_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
"""把业务异常统一转成 Tool 侧约定的 JSON 结构。"""
|
||||
return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status
|
||||
|
||||
|
||||
@agent_runtime_context_bp.before_request
|
||||
def _verify_tool_access():
|
||||
"""
|
||||
对上下文解析 Tool 做统一 Header 鉴权。
|
||||
|
||||
核心逻辑:OpenAPI 导入文档无需鉴权;parse 工具必须携带平台 Tool Key。
|
||||
"""
|
||||
if request.path.endswith("/openapi.json"):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
@agent_runtime_context_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def openapi_spec():
|
||||
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
|
||||
return jsonify(build_agent_runtime_context_openapi_spec(resolve_tool_api_base_url()))
|
||||
|
||||
|
||||
@agent_runtime_context_bp.route("/tools/parse", methods=["POST"])
|
||||
def parse_context_tool():
|
||||
"""
|
||||
解析 agent_runtime_context 的白名单字段。
|
||||
|
||||
【AI 触发时机】:Dify 需要读取 HXOPS session/task/batch/run_purpose/state_hint 等上下文字段时调用;
|
||||
不用于推进业务状态。
|
||||
"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
return jsonify(
|
||||
parse_agent_runtime_context(
|
||||
payload.get("agent_runtime_context"),
|
||||
payload.get("paths"),
|
||||
)
|
||||
)
|
||||
__all__ = ['agent_runtime_context_bp']
|
||||
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
backend/app/api/agents.py
|
||||
backend/app/api/agents/__init__.py
|
||||
|
||||
用途:普通用户可见的 Agent 列表与 AgentGuide 静态资源。
|
||||
依赖:app.core.auth.jwt、models、minio_service、agent_registry.serialization。
|
||||
@@ -37,7 +37,7 @@ def _serialize_agent_row(agent: Agent, *, visible_agent_ids: set[int] | None = N
|
||||
|
||||
def _list_active_agents_for_user(user: User) -> list[Agent]:
|
||||
"""返回用户可见的完整 Agent ORM 行(含 Registry 结构化列)。"""
|
||||
if user.role == 'admin':
|
||||
if user.is_platform_admin():
|
||||
return (
|
||||
db.session.query(Agent)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
@@ -2,7 +2,7 @@
|
||||
api/chat/__init__.py
|
||||
|
||||
用途:聊天域 Blueprint 的统一入口。
|
||||
依赖:chat 各职责路由模块、app.api.chat_turns。
|
||||
依赖:chat 各职责路由模块、chat.turns。
|
||||
逻辑:创建唯一的 chat_bp,导入子模块完成路由注册,并挂载 Chat Turn 流式接口。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
@@ -21,7 +21,7 @@ from .shared import ( # noqa: E402, F401
|
||||
_merge_user_attachments_from_terminal_event,
|
||||
_normalize_user_attachments,
|
||||
)
|
||||
from app.api.chat_turns import register_chat_turn_routes # noqa: E402
|
||||
from .turns import register_chat_turn_routes # noqa: E402
|
||||
|
||||
register_chat_turn_routes(chat_bp)
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ def chat_completions():
|
||||
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
|
||||
conversation_id = data.get('conversation_id')
|
||||
shipping_task_id = str(data.get('task_id') or '').strip()
|
||||
shipping_batch_no = str(data.get('batch_no') or '').strip()
|
||||
kb_type = data.get('kb_type', '企业知识库')
|
||||
files = data.get('files')
|
||||
request_id = uuid.uuid4().hex[:12]
|
||||
@@ -174,6 +175,7 @@ def chat_completions():
|
||||
normalized_files=normalized_files,
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
),
|
||||
shipping_task_id=shipping_task_id,
|
||||
kb_type=kb_type,
|
||||
@@ -214,6 +216,7 @@ def chat_completions():
|
||||
user_role=user_proxy.role,
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -10,19 +10,21 @@ from __future__ import annotations
|
||||
from .shared import * # noqa: F403
|
||||
|
||||
|
||||
def _build_chat_adapter_hints(*, shipping_task_id: str | None = None) -> dict | None:
|
||||
def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_batch_no: str | None = None) -> dict | None:
|
||||
"""
|
||||
构建聊天入口分发给领域 adapter 的提示字典。
|
||||
|
||||
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task 提示,
|
||||
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示,
|
||||
统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。
|
||||
"""
|
||||
task_id = str(shipping_task_id or '').strip()
|
||||
if not task_id:
|
||||
batch_no = str(shipping_batch_no or '').strip()
|
||||
if not task_id and not batch_no:
|
||||
return None
|
||||
return {
|
||||
'shipping_notice': {
|
||||
'task_id': task_id or None,
|
||||
'batch_no': batch_no or None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/api/chat_turns.py
|
||||
backend/app/api/chat/turns.py
|
||||
|
||||
用途:Chat Turn 流式 API 路由(POST /api/chat/turns/stream)。
|
||||
依赖:app.core.decorators、ChatTurnRuntime、chat_bp。
|
||||
逻辑:支持 JSON 与 multipart(附件上传 + Turn);由 chat.py 注册到同一 Blueprint。
|
||||
逻辑:支持 JSON 与 multipart(附件上传 + Turn);由 chat 包注册到同一 Blueprint。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
backend/app/api/contract_payment.py
|
||||
backend/app/api/contract_payment/__init__.py
|
||||
|
||||
用途:采购合同付款预警 Agent 的合同台账、付款计划、待发送摘要、台账汇总卡和同步 API。
|
||||
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、Agent 授权、contract_payment 服务和通用 Job 队列。
|
||||
@@ -7,8 +7,8 @@ backend/app/api/contract_payment.py
|
||||
下载和单合同重解析走 read_contract_attachment_bytes:原文还在则直接读,被临时清理删掉则按附件 ID 从 OA/DMS 重新下载。
|
||||
待确认合同的人工复核走 apply_manual_review:比例合计 100% 后改为已解析并进入台账。未付的预付款、出货款可手动标为已付。
|
||||
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍;同时返回 OA 公司及对应 ERP 账套。
|
||||
鉴权:查询接口要求平台 admin 或持有 `agent_code=contract_payment` 的 Agent 授权;
|
||||
同步/扫描/周汇总发送仅 `role=admin`。
|
||||
鉴权:查询接口要求平台管理员(is_platform_admin)或持有 `agent_code=contract_payment` 的 Agent 授权;
|
||||
同步/扫描/周汇总发送仅平台管理员。权限组启用后,普通用户通过角色包获得该 Agent,不再按人授权。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -111,7 +111,7 @@ def _require_contract_payment_access():
|
||||
ForbiddenError: 已登录但没有合同付款预警 Agent 授权。
|
||||
"""
|
||||
user = _require_user()
|
||||
if getattr(user, "role", None) == "admin" or _user_has_contract_payment_agent(user):
|
||||
if user.is_platform_admin() or _user_has_contract_payment_agent(user):
|
||||
return user
|
||||
raise ForbiddenError(
|
||||
'Contract payment agent permission required',
|
||||
@@ -124,7 +124,7 @@ def _require_contract_payment_admin():
|
||||
确保当前用户既有合同付款预警访问权,又是平台管理员。
|
||||
|
||||
核心逻辑:持有 Agent 的普通用户可查台账;同步 OA、强制覆盖、批量重解析、扫描预警和发送周汇总
|
||||
会改写外部系统或触发企微,因此仅 `role=admin` 可调用。
|
||||
会改写外部系统或触发企微,因此仅平台管理员可调用。
|
||||
|
||||
Args:
|
||||
无。当前请求身份由 JWT 上下文提供。
|
||||
@@ -135,7 +135,7 @@ def _require_contract_payment_admin():
|
||||
ForbiddenError: 无合同付款访问权,或已授权但不是管理员。
|
||||
"""
|
||||
user = _require_contract_payment_access()
|
||||
if getattr(user, "role", None) != "admin":
|
||||
if not user.is_platform_admin():
|
||||
raise ForbiddenError(
|
||||
'Admin privilege required for contract payment jobs',
|
||||
code='CONTRACT_PAYMENT.ADMIN_REQUIRED',
|
||||
@@ -0,0 +1,205 @@
|
||||
"""
|
||||
backend/app/api/equipment_acceptance/__init__.py
|
||||
|
||||
用途:设备验收预警的 Chat 作业面接口。
|
||||
依赖:JWT 当前用户、Agent 授权、sync_service、统一成功响应。
|
||||
逻辑:持有 equipment_acceptance Agent 的用户可看停留列表、发送记录、已归档 Excel 和配置;同步、扫描、发送和保存配置仅平台管理员。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
from flask import Blueprint, g, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, UnauthorizedError
|
||||
from app.core.response import ok
|
||||
from app.models import Agent
|
||||
from app.services.equipment_acceptance.config_service import (
|
||||
get_acceptance_config,
|
||||
save_acceptance_config,
|
||||
)
|
||||
from app.services.equipment_acceptance.alert_service import generate_alerts, send_pending_alerts
|
||||
from app.services.equipment_acceptance.send_record_service import get_send_file, list_send_files, list_send_records
|
||||
from app.services.equipment_acceptance.sync_service import (
|
||||
get_acceptance_order,
|
||||
list_acceptance_orders,
|
||||
sync_acceptance_snapshots,
|
||||
)
|
||||
|
||||
equipment_acceptance_bp = Blueprint("equipment_acceptance", __name__)
|
||||
EQUIPMENT_ACCEPTANCE_AGENT_CODE = "equipment_acceptance"
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""
|
||||
读取当前登录用户。
|
||||
|
||||
Returns:
|
||||
已认证用户。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 没有有效登录身份。
|
||||
"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _user_has_equipment_acceptance_agent(user) -> bool:
|
||||
"""
|
||||
判断用户是否持有启用中的设备验收预警 Agent。
|
||||
|
||||
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions。
|
||||
"""
|
||||
agent = Agent.query.filter_by(agent_code=EQUIPMENT_ACCEPTANCE_AGENT_CODE, is_active=True).first()
|
||||
return bool(agent is not None and agent in user.agents)
|
||||
|
||||
|
||||
def _require_equipment_acceptance_access():
|
||||
"""
|
||||
确保当前用户可以打开设备验收预警作业面。
|
||||
|
||||
核心逻辑:平台管理员放行;普通用户必须被授予启用中的 equipment_acceptance Agent。
|
||||
|
||||
Returns:
|
||||
已认证且有权查看的用户。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 没有有效登录身份。
|
||||
ForbiddenError: 已登录但没有该 Agent。
|
||||
"""
|
||||
user = _require_user()
|
||||
if user.is_platform_admin() or _user_has_equipment_acceptance_agent(user):
|
||||
return user
|
||||
raise ForbiddenError(
|
||||
"Equipment acceptance agent permission required",
|
||||
code="EQUIPMENT_ACCEPTANCE.FORBIDDEN",
|
||||
)
|
||||
|
||||
|
||||
def _require_equipment_acceptance_admin():
|
||||
"""
|
||||
确保当前用户可以触发 E10 同步。
|
||||
|
||||
核心逻辑:先确认能看作业面,再要求平台管理员。同步会读取外部库并改写本地快照。
|
||||
|
||||
Returns:
|
||||
已认证的管理员。
|
||||
|
||||
Raises:
|
||||
ForbiddenError: 不是平台管理员。
|
||||
"""
|
||||
user = _require_equipment_acceptance_access()
|
||||
if not user.is_platform_admin():
|
||||
raise ForbiddenError(
|
||||
"Admin privilege required for equipment acceptance sync",
|
||||
code="EQUIPMENT_ACCEPTANCE.ADMIN_REQUIRED",
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/sync", methods=["POST"])
|
||||
def sync_equipment_acceptance():
|
||||
"""从 E10 拉取验收单并写入本地快照。仅平台管理员。"""
|
||||
_require_equipment_acceptance_admin()
|
||||
return ok(sync_acceptance_snapshots(), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/orders", methods=["GET"])
|
||||
def list_equipment_acceptance_orders():
|
||||
"""分页查看已同步的验收单。focus 按原型分组过滤,summary 始终统计全部单据。"""
|
||||
_require_equipment_acceptance_access()
|
||||
page = _int_arg("page", 1)
|
||||
page_size = _int_arg("page_size", 20)
|
||||
payload = list_acceptance_orders(
|
||||
monitor_status=request.args.get("monitor_status"),
|
||||
focus=request.args.get("focus"),
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/config", methods=["GET"])
|
||||
def get_equipment_acceptance_config():
|
||||
"""读取四档天数和三个固定岗位。候选人名单只给平台管理员。"""
|
||||
user = _require_equipment_acceptance_access()
|
||||
payload = get_acceptance_config(include_candidates=user.is_platform_admin())
|
||||
return ok(payload, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/config", methods=["PUT"])
|
||||
def save_equipment_acceptance_config():
|
||||
"""保存四档天数和三个固定岗位。仅平台管理员。发送时刻不在本接口。"""
|
||||
user = _require_equipment_acceptance_access()
|
||||
if not user.is_platform_admin():
|
||||
raise ForbiddenError(
|
||||
"Admin privilege required for equipment acceptance settings",
|
||||
code="EQUIPMENT_ACCEPTANCE.SETTINGS_ADMIN_REQUIRED",
|
||||
)
|
||||
payload = request.get_json(silent=True) or {}
|
||||
saved = save_acceptance_config(payload, updated_by=user.id)
|
||||
return ok(saved, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/alerts/scan", methods=["POST"])
|
||||
def scan_equipment_acceptance_alerts():
|
||||
"""管理员立即同步 E10 并生成待发送记录。不发企业微信。"""
|
||||
_require_equipment_acceptance_admin()
|
||||
return ok(generate_alerts(), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/alerts/send", methods=["POST"])
|
||||
def send_equipment_acceptance_alerts():
|
||||
"""管理员立即把待发送记录按收件人发到企业微信。"""
|
||||
_require_equipment_acceptance_admin()
|
||||
return ok(send_pending_alerts(), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/send-files", methods=["GET"])
|
||||
def list_equipment_acceptance_send_files():
|
||||
"""列出最近按收件人归档的 Excel。不含文件字节。"""
|
||||
_require_equipment_acceptance_access()
|
||||
return ok({"items": list_send_files()}, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/send-files/<int:file_id>/excel", methods=["GET"])
|
||||
def download_equipment_acceptance_send_file(file_id: int):
|
||||
"""下载一份当时发给收件人的设备验收预警 Excel。"""
|
||||
_require_equipment_acceptance_access()
|
||||
row = get_send_file(file_id)
|
||||
return send_file(
|
||||
BytesIO(row.excel_file_data),
|
||||
as_attachment=True,
|
||||
download_name=row.excel_file_name or f"equipment-acceptance-alert-{file_id}.xlsx",
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/sends", methods=["GET"])
|
||||
def list_equipment_acceptance_sends():
|
||||
"""分页查看发送记录。扫描写入后这里才有行。"""
|
||||
_require_equipment_acceptance_access()
|
||||
payload = list_send_records(page=_int_arg("page", 1), page_size=_int_arg("page_size", 20))
|
||||
return ok(payload, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/orders/<int:order_id>", methods=["GET"])
|
||||
def get_equipment_acceptance_order(order_id: int):
|
||||
"""查看一张验收单的节点和操作人原值。"""
|
||||
_require_equipment_acceptance_access()
|
||||
return ok(get_acceptance_order(order_id), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
def _int_arg(name: str, default: int) -> int:
|
||||
"""读取正整数查询参数,非法时用默认值。"""
|
||||
raw = request.args.get(name)
|
||||
if raw is None or str(raw).strip() == "":
|
||||
return default
|
||||
try:
|
||||
return int(raw)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
@@ -1,657 +1,28 @@
|
||||
"""
|
||||
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;实际执行入队 FILE_CHECK_RUN,由 schedule worker 执行。
|
||||
用途:兼容旧 import 路径的薄 shim(真实现已迁至 api/tools/file_check.py)。
|
||||
依赖:app.api.tools.file_check。
|
||||
逻辑:保留 Blueprint 与测试 monkeypatch 常用符号;新代码请从 app.api.tools 导入。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from io import BytesIO
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
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,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
from app.api.tools.file_check import ( # noqa: F401
|
||||
_RUN_START_LOCK,
|
||||
_build_excel_download_url,
|
||||
_precheck_no_data,
|
||||
enqueue,
|
||||
file_check_bp,
|
||||
get_schedule_sql_config_by_task_id,
|
||||
_build_srm_conn_str,
|
||||
_fetch_records,
|
||||
)
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.file_check_tools.openapi_spec import build_file_check_openapi_spec
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE, resolve_hxops_user_facing_base_url
|
||||
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
|
||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
|
||||
|
||||
try:
|
||||
import pyodbc # type: ignore
|
||||
except Exception: # pragma: no cover
|
||||
pyodbc = None
|
||||
|
||||
|
||||
file_check_bp = Blueprint("file_check_tools", __name__)
|
||||
|
||||
_EXCEL_TOKEN_SCOPES = {"file_check_excel", "file_schedule_excel"}
|
||||
_RUN_START_LOCK = threading.Lock()
|
||||
_TASK_LOCK_KEY_BASE = 8700000000
|
||||
|
||||
|
||||
def _download_token_secret() -> str:
|
||||
"""
|
||||
Excel 下载 JWT 签名密钥。
|
||||
|
||||
核心逻辑:与 Dify Tool API Key 分离,仅用 SECRET_KEY,避免 API Key 未配置时浏览器下载失败。
|
||||
"""
|
||||
return str(current_app.config.get("SECRET_KEY") or "default-secret").strip()
|
||||
|
||||
|
||||
def _decode_download_token(token: str | None) -> dict | None:
|
||||
normalized = str(token or "").strip()
|
||||
if not normalized:
|
||||
return None
|
||||
try:
|
||||
import jwt
|
||||
|
||||
payload = jwt.decode(normalized, _download_token_secret(), algorithms=["HS256"])
|
||||
return payload if isinstance(payload, dict) else None
|
||||
except Exception as exc:
|
||||
current_app.logger.warning("[file-check-tool] download token validation failed: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验 Tool API 访问权限。
|
||||
|
||||
核心逻辑:Excel 下载仅校验 query token(浏览器场景);其余端点走共用 integration_tool_auth。
|
||||
"""
|
||||
# [STEP 1] 浏览器 Excel 下载:JWT token 独立于 Tool API Key
|
||||
if request.path.endswith("/excel"):
|
||||
query_token = str(request.args.get("token") or "").strip()
|
||||
if query_token:
|
||||
if _decode_download_token(query_token):
|
||||
return
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
# [STEP 2] Dify / RPA 服务端调用(与立账凭证检核等 Tool 共用密钥)
|
||||
from app.services.integration_tool_auth import require_integration_tool_auth
|
||||
|
||||
require_integration_tool_auth()
|
||||
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
message = str(exc.message or "").strip()
|
||||
if message in {
|
||||
"missing_auth",
|
||||
"invalid_auth",
|
||||
"task_not_found",
|
||||
"run_not_found",
|
||||
"excel_not_ready",
|
||||
"kb_sync_failed",
|
||||
"query_required",
|
||||
"kb_not_configured",
|
||||
"kb_group_not_found",
|
||||
"kb_dataset_not_bound",
|
||||
"dify_retrieve_failed",
|
||||
}:
|
||||
return message
|
||||
if exc.code == "data_source_unavailable":
|
||||
return "data_source_unavailable"
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
return "missing_auth"
|
||||
if exc.code == "RESOURCE.NOT_FOUND":
|
||||
return message or "run_not_found"
|
||||
if exc.code == "VALIDATION.INVALID_PARAM":
|
||||
return message or "invalid_request"
|
||||
if exc.code == "RESOURCE.CONFLICT":
|
||||
return message or "conflict"
|
||||
return exc.code
|
||||
|
||||
|
||||
@file_check_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
status = exc.http_status
|
||||
return jsonify({
|
||||
"ok": False,
|
||||
"error_code": _tool_error_code(exc),
|
||||
"message": exc.message,
|
||||
}), status
|
||||
|
||||
|
||||
def _public_base_url() -> str:
|
||||
"""用户可见下载链基地址;与 Dify 调 Tool API 的内网基地址分离。"""
|
||||
return resolve_hxops_user_facing_base_url()
|
||||
|
||||
|
||||
def _acquire_task_start_lock(task_id: int) -> None:
|
||||
"""按 schedule_task_id 串行化同任务启动检核(PostgreSQL advisory lock)。"""
|
||||
bind = db.session.get_bind()
|
||||
if bind.dialect.name != "postgresql":
|
||||
return
|
||||
lock_key = _TASK_LOCK_KEY_BASE + int(task_id)
|
||||
db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": lock_key})
|
||||
|
||||
|
||||
def _build_excel_download_url(run: ScheduleRun) -> str:
|
||||
import jwt
|
||||
|
||||
payload = {
|
||||
"scope": "file_check_excel",
|
||||
"run_id": run.id,
|
||||
"exp": int(time.time()) + 600,
|
||||
}
|
||||
token = jwt.encode(payload, _download_token_secret(), algorithm="HS256")
|
||||
return f"{_public_base_url()}/api/file-check/tools/runs/{run.id}/excel?token={token}"
|
||||
|
||||
|
||||
@file_check_bp.before_request
|
||||
def _verify_tool_access():
|
||||
if request.path.endswith("/openapi.json"):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
def _serialize_tool_run(run: ScheduleRun) -> dict:
|
||||
payload = serialize_run(run)
|
||||
return {
|
||||
"run_id": payload["id"],
|
||||
"run_no": payload["run_no"],
|
||||
"task_id": payload["schedule_task_id"],
|
||||
"task_name": payload.get("schedule_name"),
|
||||
"status": payload["status"],
|
||||
"total_count": payload["total_count"],
|
||||
"success_count": payload["success_count"],
|
||||
"failed_count": payload["failed_count"],
|
||||
"skipped_count": payload["skipped_count"],
|
||||
"judgement": serialize_file_judgement(payload),
|
||||
"started_at": payload.get("started_at"),
|
||||
"finished_at": payload.get("finished_at"),
|
||||
"duration_ms": payload.get("duration_ms"),
|
||||
"error_message": payload.get("error_message"),
|
||||
"excel": {
|
||||
"file_name": payload.get("excel_file_name"),
|
||||
"file_size": payload.get("excel_file_size"),
|
||||
"download_url": _build_excel_download_url(run) if payload.get("excel_file_name") else None,
|
||||
},
|
||||
"knowledge_base": {
|
||||
"enabled": bool(getattr(run.task, "kb_sync_enabled", False)) if run.task else bool(payload.get("kb_group_id")),
|
||||
"sync_status": payload.get("kb_sync_status"),
|
||||
"group_id": payload.get("kb_group_id"),
|
||||
"document_id": payload.get("kb_document_id"),
|
||||
"document_version_id": payload.get("kb_document_version_id"),
|
||||
"sync_job_id": payload.get("kb_sync_job_id"),
|
||||
"error_message": payload.get("kb_sync_error"),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _resolve_check_task(data: dict | None = None, *, task_id: int | None = None) -> ScheduleTask:
|
||||
data = data or {}
|
||||
raw_task_id = task_id if task_id is not None else data.get("task_id")
|
||||
if raw_task_id in (None, "", 0, "0") and not str(data.get("task_no") or "").strip():
|
||||
raise ValidationError("task_id_required")
|
||||
try:
|
||||
normalized_task_id = int(raw_task_id) if raw_task_id not in (None, "", 0, "0") else None
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError("task_id_invalid")
|
||||
task = db.session.get(ScheduleTask, normalized_task_id) if normalized_task_id is not None else None
|
||||
if not task:
|
||||
task_no = str(data.get("task_no") or "").strip()
|
||||
if task_no:
|
||||
task = ScheduleTask.query.filter_by(schedule_no=task_no).first()
|
||||
if not task:
|
||||
raise NotFoundError("task_not_found")
|
||||
return task
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/tasks", methods=["GET"])
|
||||
def list_file_check_tasks():
|
||||
"""
|
||||
查询指定检核任务摘要;须传 task_id(Agent 绑定的 schedule_task_id),不再返回全量任务列表。
|
||||
"""
|
||||
raw_task_id = request.args.get("task_id", type=int)
|
||||
if raw_task_id is None:
|
||||
raise ValidationError("task_id_required")
|
||||
task = _resolve_check_task(task_id=raw_task_id)
|
||||
latest = (
|
||||
ScheduleRun.query.filter_by(schedule_task_id=task.id)
|
||||
.order_by(ScheduleRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
tasks = [{
|
||||
"task_id": task.id,
|
||||
"task_no": task.schedule_no,
|
||||
"name": task.name,
|
||||
"enabled": bool(task.enabled),
|
||||
"last_status": latest.status if latest else None,
|
||||
"last_run_at": task.last_run_at.isoformat() if task.last_run_at else None,
|
||||
"next_run_at": task.next_run_at.isoformat() if task.next_run_at else None,
|
||||
}]
|
||||
return jsonify({"ok": True, "tasks": tasks})
|
||||
|
||||
|
||||
def _normalize_bind_payload(data: dict | None) -> dict:
|
||||
"""规范化启动检核 Body;兼容 Chatflow 漏传 hxops_session_id。"""
|
||||
payload = dict(data or {})
|
||||
session_id = str(payload.get("hxops_session_id") or "").strip()
|
||||
if session_id:
|
||||
return payload
|
||||
conversation_id = str(payload.get("conversation_id") or "").strip()
|
||||
if not conversation_id:
|
||||
return payload
|
||||
from app.models import ChatSession
|
||||
|
||||
session = ChatSession.query.filter_by(session_id=conversation_id).first()
|
||||
if session:
|
||||
payload["hxops_session_id"] = conversation_id
|
||||
return payload
|
||||
|
||||
|
||||
def _prepare_bind_payload(data: dict | None) -> dict:
|
||||
from app.services.file_check_tools.chat_turn_registry import infer_bind_context_for_run_request
|
||||
|
||||
payload = _normalize_bind_payload(data)
|
||||
inferred = infer_bind_context_for_run_request(payload)
|
||||
if inferred:
|
||||
payload = {**payload, **inferred}
|
||||
return payload
|
||||
|
||||
|
||||
def _record_run_bind(run: ScheduleRun, data: dict) -> None:
|
||||
from app.services.file_check_tools.chat_log_run_binding import merge_chat_log_bind_context
|
||||
from app.services.file_check_tools.chat_tool_run_binding import (
|
||||
_has_ambiguous_pending_turns,
|
||||
bind_schedule_run,
|
||||
)
|
||||
from app.services.file_check_tools.chat_turn_registry import attach_run_to_turn
|
||||
|
||||
turn_id = str(data.get("hxops_turn_id") or "").strip()
|
||||
session_id = str(data.get("hxops_session_id") or "").strip() or None
|
||||
user_message = str(data.get("user_message") or "").strip() or None
|
||||
bound = bind_schedule_run(
|
||||
schedule_run_id=int(run.id),
|
||||
turn_id=turn_id or None,
|
||||
session_id=session_id,
|
||||
user_message=user_message,
|
||||
schedule_task_id=int(run.schedule_task_id) if run.schedule_task_id else None,
|
||||
bind_source='tool_start',
|
||||
)
|
||||
ambiguous = _has_ambiguous_pending_turns(
|
||||
session_id=session_id,
|
||||
user_message=user_message,
|
||||
schedule_task_id=int(run.schedule_task_id) if run.schedule_task_id else None,
|
||||
)
|
||||
if bound or (not ambiguous and (turn_id or session_id)):
|
||||
merge_chat_log_bind_context(run, data)
|
||||
if bound and turn_id:
|
||||
attach_run_to_turn(turn_id, int(run.id))
|
||||
|
||||
|
||||
def _bind_queried_run_to_turn(run: ScheduleRun, data: dict) -> None:
|
||||
"""
|
||||
将已有检核批次关联到本轮查询对话,不改写批次原始执行上下文。
|
||||
|
||||
查询最近批次时触发;仅更新 chat_tool_runs 与内存 turn registry,
|
||||
使 message_end 可以把既有 ScheduleRun.id 写入当前 ChatLog.run_id。
|
||||
"""
|
||||
from app.services.file_check_tools.chat_tool_run_binding import bind_schedule_run
|
||||
from app.services.file_check_tools.chat_turn_registry import attach_run_to_turn
|
||||
|
||||
turn_id = str(data.get("hxops_turn_id") or "").strip()
|
||||
session_id = str(data.get("conversation_id") or "").strip() or None
|
||||
user_message = str(data.get("user_message") or "").strip() or None
|
||||
if not turn_id:
|
||||
return
|
||||
|
||||
bound = bind_schedule_run(
|
||||
schedule_run_id=int(run.id),
|
||||
turn_id=turn_id,
|
||||
session_id=session_id,
|
||||
user_message=user_message,
|
||||
schedule_task_id=int(run.schedule_task_id),
|
||||
bind_source="tool_query_latest",
|
||||
)
|
||||
if bound:
|
||||
attach_run_to_turn(turn_id, int(run.id))
|
||||
|
||||
|
||||
def _build_no_data_response(task: ScheduleTask, run: ScheduleRun) -> dict:
|
||||
"""
|
||||
组装无待检资料的 Tool 响应,并返回本轮已完成的空批次。
|
||||
|
||||
【AI 触发时机】:用户要求立即执行文件检核,但预检未发现待检资料时调用。
|
||||
核心逻辑:保留 no_data_to_check 供 Chatflow 回复无资料提示,同时携带已绑定的 Run,
|
||||
使前端能在该轮消息下展示总数 0、进度 100% 的完成进度卡。
|
||||
|
||||
Args:
|
||||
task: 当前检核任务。
|
||||
run: 已持久化并绑定当前对话的成功空批次。
|
||||
|
||||
Returns:
|
||||
dict: 包含 no_data_to_check、任务信息和 Run 摘要的 HTTP 200 响应体。
|
||||
"""
|
||||
return {
|
||||
"ok": False,
|
||||
"error_code": "no_data_to_check",
|
||||
"message": "目前没有资料需要检核",
|
||||
"run": _serialize_tool_run(run),
|
||||
"task": {
|
||||
"task_id": task.id,
|
||||
"task_name": task.name,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _raise_data_source_unavailable(task: ScheduleTask, exc: Exception) -> None:
|
||||
"""
|
||||
将检核预检阶段的数据源连接/配置错误转为 Tool API 503。
|
||||
|
||||
核心逻辑:ODBC/SQL Server 不可用时返回 data_source_unavailable,避免 Dify 收到 500 后显示 maximum retries。
|
||||
"""
|
||||
current_app.logger.warning(
|
||||
"[file-check-tool] precheck data source unavailable task_id=%s error=%s",
|
||||
task.id,
|
||||
exc,
|
||||
exc_info=True,
|
||||
)
|
||||
raise ServiceUnavailableError(
|
||||
"检核数据源不可用,请检查排程 SQL 配置、SRM_SQLSERVER_* 环境变量及本机 ODBC 驱动",
|
||||
code="data_source_unavailable",
|
||||
) from exc
|
||||
|
||||
|
||||
def _precheck_no_data(task: ScheduleTask) -> dict | None:
|
||||
"""
|
||||
启动前预检当前任务是否存在待检资料。
|
||||
|
||||
核心逻辑:仅在数据库型检核任务上做轻量预检;若结果为空,则返回 no_data_to_check 标识,
|
||||
由启动入口创建并绑定完成态的 0 笔 Run。数据源连接失败时抛 503 data_source_unavailable。
|
||||
"""
|
||||
if str(getattr(task, "data_source_type", "") or "database").lower() != "database":
|
||||
return None
|
||||
|
||||
cfg = get_schedule_sql_config_by_task_id(task.id)
|
||||
if not cfg or not str(cfg.fetch_sql or "").strip():
|
||||
return None
|
||||
|
||||
try:
|
||||
if cfg.data_source and not cfg.data_source.is_empty():
|
||||
conn_str = cfg.data_source.build_connection_string()
|
||||
else:
|
||||
conn_str = _build_srm_conn_str()
|
||||
rows = _fetch_records(conn_str, cfg.fetch_sql)
|
||||
except RuntimeError as exc:
|
||||
_raise_data_source_unavailable(task, exc)
|
||||
except Exception as exc:
|
||||
if pyodbc is not None and isinstance(exc, pyodbc.Error):
|
||||
_raise_data_source_unavailable(task, exc)
|
||||
raise
|
||||
|
||||
if rows:
|
||||
return None
|
||||
return {
|
||||
"ok": False,
|
||||
"error_code": "no_data_to_check",
|
||||
"message": "目前没有资料需要检核",
|
||||
}
|
||||
|
||||
|
||||
def _create_no_data_run(task: ScheduleTask, data: dict) -> ScheduleRun:
|
||||
"""
|
||||
为预检为空的立即执行请求创建并绑定已完成的 0 笔检核批次。
|
||||
|
||||
【AI 触发时机】:run_file_check 收到 no_data_to_check 预检结果时调用。
|
||||
核心逻辑:不启动后台 worker,仅写入 success Run 与对话绑定;完成态空批次由工作区进度接口
|
||||
序列化为 100%,让用户明确知道本次检核已经结束且没有待处理资料。
|
||||
|
||||
Args:
|
||||
task: 已解析的文件检核任务。
|
||||
data: Tool 请求及对话绑定上下文。
|
||||
|
||||
Returns:
|
||||
ScheduleRun: 已提交且已绑定当前对话的成功空批次。
|
||||
"""
|
||||
finished_at = datetime.utcnow()
|
||||
run = ScheduleRun(
|
||||
run_no=_generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
trigger_type="dify_chatflow",
|
||||
started_at=finished_at,
|
||||
finished_at=finished_at,
|
||||
duration_ms=0,
|
||||
status="success",
|
||||
total_count=0,
|
||||
success_count=0,
|
||||
failed_count=0,
|
||||
skipped_count=0,
|
||||
api_request_json={
|
||||
"trigger_source": data.get("trigger_source") or "dify_chatflow",
|
||||
"conversation_id": data.get("conversation_id"),
|
||||
},
|
||||
response_summary_json={"errors": [], "no_data": True},
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
_record_run_bind(run, data)
|
||||
db.session.commit()
|
||||
return run
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/tasks/run", methods=["POST"])
|
||||
def run_file_check():
|
||||
"""
|
||||
立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。
|
||||
|
||||
核心逻辑:解析 task → 防并发锁 → 可选透传 mode/invoice_no(或 run_options)到
|
||||
ScheduleRun.api_request_json → 异步启动平台 Job。Dify 推荐填顶层 mode/invoice_no。
|
||||
|
||||
Body 关键字段(立账凭证检核):
|
||||
mode: incremental | force_all | single
|
||||
invoice_no: mode=single 时发票号
|
||||
run_options: 可选嵌套对象,与顶层字段合并(顶层优先)
|
||||
"""
|
||||
perf_started = time.perf_counter()
|
||||
data = _prepare_bind_payload(request.get_json(silent=True) or {})
|
||||
task = _resolve_check_task(data)
|
||||
resolve_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
|
||||
lock_started = time.perf_counter()
|
||||
with _RUN_START_LOCK:
|
||||
_acquire_task_start_lock(task.id)
|
||||
existing = (
|
||||
ScheduleRun.query.filter_by(schedule_task_id=task.id, status="running")
|
||||
.order_by(ScheduleRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
if existing:
|
||||
_record_run_bind(existing, data)
|
||||
db.session.commit()
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
current_app.logger.info(
|
||||
"[file-check-tool-perf] run_file_check outcome=check_running resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
existing.id,
|
||||
)
|
||||
return jsonify({
|
||||
"ok": False,
|
||||
"error_code": "check_running",
|
||||
"message": "该检核任务正在执行中,请稍后查询结果",
|
||||
"run": _serialize_tool_run(existing),
|
||||
})
|
||||
|
||||
no_data_response = _precheck_no_data(task)
|
||||
if no_data_response:
|
||||
run = _create_no_data_run(task, data)
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
current_app.logger.info(
|
||||
"[file-check-tool-perf] run_file_check outcome=no_data resolve_ms=%s lock_ms=%s total_ms=%s task_id=%s run_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
task.id,
|
||||
run.id,
|
||||
)
|
||||
return jsonify(_build_no_data_response(task, run))
|
||||
|
||||
# [STEP] 解析运行选项:优先顶层 mode/invoice_no(Dify Tool 表单对嵌套 object 常不展示),
|
||||
# 再与 run_options 对象合并;立账凭证检核读取,普通文件检核忽略。
|
||||
raw_options = data.get("run_options") if isinstance(data.get("run_options"), dict) else {}
|
||||
run_options = {}
|
||||
mode = str(data.get("mode") or raw_options.get("mode") or "").strip().lower()
|
||||
if mode in {"incremental", "force_all", "single"}:
|
||||
run_options["mode"] = mode
|
||||
invoice_no = data.get("invoice_no")
|
||||
if invoice_no is None or not str(invoice_no).strip():
|
||||
invoice_no = raw_options.get("invoice_no")
|
||||
if invoice_no is not None and str(invoice_no).strip():
|
||||
run_options["invoice_no"] = str(invoice_no).strip()
|
||||
|
||||
api_request_json = {
|
||||
"trigger_source": data.get("trigger_source") or "dify_chatflow",
|
||||
"conversation_id": data.get("conversation_id"),
|
||||
}
|
||||
if run_options:
|
||||
api_request_json["run_options"] = run_options
|
||||
|
||||
run = ScheduleRun(
|
||||
run_no=_generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
trigger_type="dify_chatflow",
|
||||
started_at=datetime.utcnow(),
|
||||
status="running",
|
||||
api_request_json=api_request_json,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
_record_run_bind(run, data)
|
||||
db.session.commit()
|
||||
run_id = run.id
|
||||
task_id = task.id
|
||||
|
||||
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)
|
||||
current_app.logger.info(
|
||||
"[file-check-tool-perf] run_file_check outcome=started resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
run_id,
|
||||
)
|
||||
return jsonify({"ok": True, "message": "检核已启动", "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/runs/<int:run_id>", methods=["GET"])
|
||||
def get_file_check_run(run_id: int):
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/runs", methods=["GET"])
|
||||
def list_file_check_runs():
|
||||
raw_task_id = request.args.get("task_id", type=int)
|
||||
raw_limit = request.args.get("limit", default=20, type=int)
|
||||
limit = max(1, min(int(raw_limit or 20), 100))
|
||||
if raw_task_id is not None:
|
||||
task = _resolve_check_task(task_id=raw_task_id)
|
||||
query = ScheduleRun.query.filter_by(schedule_task_id=task.id)
|
||||
else:
|
||||
query = ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
|
||||
rows = query.order_by(ScheduleRun.created_at.desc()).limit(limit).all()
|
||||
runs = [_serialize_tool_run(row) for row in rows]
|
||||
return jsonify({"ok": True, "runs": runs, "count": len(runs)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/runs/<int:run_id>/excel", methods=["GET"])
|
||||
def download_file_check_run_excel(run_id: int):
|
||||
token_payload = _decode_download_token(request.args.get("token"))
|
||||
if token_payload:
|
||||
if token_payload.get("scope") not in _EXCEL_TOKEN_SCOPES or int(token_payload.get("run_id") or 0) != run_id:
|
||||
raise UnauthorizedError("Unauthorized")
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
if not run.excel_file_data:
|
||||
raise ConflictError("excel_not_ready")
|
||||
filename = run.excel_file_name or f"{run.run_no}.xlsx"
|
||||
return send_file(
|
||||
BytesIO(run.excel_file_data),
|
||||
as_attachment=True,
|
||||
download_name=filename,
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/tasks/<int:task_id>/latest-run", methods=["GET"])
|
||||
def get_latest_file_check_run(task_id: int):
|
||||
"""查询任务最近批次;可绑定本轮对话以展示该批次进度。"""
|
||||
task = _resolve_check_task(task_id=task_id)
|
||||
run = ScheduleRun.query.filter_by(schedule_task_id=task.id).order_by(ScheduleRun.id.desc()).first()
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
_bind_queried_run_to_turn(run, {
|
||||
"hxops_turn_id": request.args.get("hxops_turn_id"),
|
||||
"conversation_id": request.args.get("conversation_id"),
|
||||
"user_message": request.args.get("user_message"),
|
||||
})
|
||||
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/history/search", methods=["POST"])
|
||||
def search_file_check_history():
|
||||
"""
|
||||
检索已入库的历史检核报告片段;按 task_id 解析 ScheduleTask → KbGroup → Dify Dataset。
|
||||
|
||||
核心逻辑:Chatflow history_report_query 分支调用;task_id 来自 HXOPS 注入的 Start 变量。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
raw_task_id = data.get("task_id")
|
||||
try:
|
||||
task_id = int(raw_task_id)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError("task_id_invalid")
|
||||
if task_id <= 0:
|
||||
raise ValidationError("task_id_invalid")
|
||||
|
||||
from app.services.file_check_tools.history_search_service import search_file_check_history as run_history_search
|
||||
|
||||
result = run_history_search(
|
||||
task_id=task_id,
|
||||
query=str(data.get("query") or ""),
|
||||
top_k=data.get("top_k"),
|
||||
score_threshold=data.get("score_threshold"),
|
||||
)
|
||||
return jsonify({"ok": True, **result})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def file_check_openapi_spec():
|
||||
return jsonify(build_file_check_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
|
||||
__all__ = [
|
||||
'file_check_bp',
|
||||
'enqueue',
|
||||
'_precheck_no_data',
|
||||
'_build_excel_download_url',
|
||||
'_RUN_START_LOCK',
|
||||
'get_schedule_sql_config_by_task_id',
|
||||
'_build_srm_conn_str',
|
||||
'_fetch_records',
|
||||
]
|
||||
@@ -0,0 +1,261 @@
|
||||
"""
|
||||
backend/app/api/freight_rpa.py
|
||||
|
||||
用途:货代 RPA 回调蓝图(/api/freight-rpa/*)——Windows Worker 向后端上报心跳、
|
||||
库存(onhand)/入站(inbound)/出站(outbound)导出结果与货代上传结果的唯一回调入口。
|
||||
批次 R 解耦后取代旧 shipping-notice rpa 回调前缀(无双路由、无兼容层)。
|
||||
依赖:app.core.tool_auth(集成密钥鉴权)、freight_rpa.common.callback_sinks(sink 分发)、
|
||||
freight_rpa.common.worker_heartbeat(心跳)、shipping_tools。
|
||||
逻辑:before_request 统一 Bearer / X-Integration-Key 鉴权(与 Tool 蓝图同一把 key)。
|
||||
分发策略按「处理函数当前住在哪个包」决定:
|
||||
- /heartbeat 直连 freight_rpa.common.worker_heartbeat;
|
||||
- /upload-complete 直连现有业务处理器(shipping_notice.tools);
|
||||
- onhand-* / inbound-* / outbound-* 全部经 callback_sinks.dispatch_sink 分发,
|
||||
真实业务 sink 由组合根注册(onhand→shipping_notice.rpa_sinks;
|
||||
inbound/outbound→in_transit_transfer.rpa_sinks);
|
||||
未注册的 kind 显式 404(FREIGHT_RPA.SINK_NOT_REGISTERED)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.core.tool_auth import require_tool_auth
|
||||
from app.services.freight_rpa.common.callback_sinks import dispatch_sink
|
||||
from app.services.freight_rpa.common.worker_heartbeat import record_rpa_worker_heartbeat
|
||||
|
||||
freight_rpa_bp = Blueprint('freight_rpa', __name__)
|
||||
|
||||
|
||||
def _payload() -> dict:
|
||||
"""
|
||||
读取回调 JSON 请求体,并剥离不可信的操作人身份字段。
|
||||
|
||||
核心逻辑:与 shipping_notice Tool 蓝图同口径——集成密钥调用方不得通过 body
|
||||
伪造 `_trusted_user_id` / `operator_id` / `actor_id`。
|
||||
"""
|
||||
raw = request.get_json(silent=True) or {}
|
||||
if not isinstance(raw, dict):
|
||||
return {}
|
||||
payload = dict(raw)
|
||||
for key in ('_trusted_user_id', 'operator_id', 'actor_id'):
|
||||
payload.pop(key, None)
|
||||
return payload
|
||||
|
||||
|
||||
@freight_rpa_bp.before_request
|
||||
def _verify_worker_access():
|
||||
"""RPA Worker 回调统一 Header 鉴权;与 Tool API 共用同一集成密钥配置。"""
|
||||
require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/heartbeat', methods=['POST'])
|
||||
def heartbeat():
|
||||
"""
|
||||
RPA Worker 心跳上报。
|
||||
【AI 触发时机】:非 Agent 入口;Windows Worker(库存/入站)由独立守护线程周期调用。
|
||||
|
||||
核心逻辑:校验 payload 后写入 Redis/内存;后端在写各类 trigger 前以此做在线就绪检查。
|
||||
"""
|
||||
payload = _payload()
|
||||
try:
|
||||
worker = record_rpa_worker_heartbeat(payload)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc))
|
||||
# 心跳存储不可用(ServiceUnavailableError)原样上抛,由全局 AppError handler 出标准错误 envelope。
|
||||
# 到期的 Crane 定时回查跟着心跳落成 trigger;写失败不让心跳本身失败。
|
||||
try:
|
||||
from app.services.freight_rpa.upload.crane_recheck import materialize_due_crane_rechecks
|
||||
materialize_due_crane_rechecks()
|
||||
except Exception:
|
||||
current_app.logger.exception('crane recheck materialize failed')
|
||||
return jsonify({'status': 'ok', 'message': 'heartbeat recorded', 'data': worker})
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/onhand-ready', methods=['POST'])
|
||||
def onhand_ready():
|
||||
"""
|
||||
onhand 单任务导出回调(旧 inventory-ready 端点随批次 R 迁入本蓝图)。
|
||||
【AI 触发时机】:非 Agent 入口;库存 Worker 完成单任务导出后调用。
|
||||
|
||||
核心逻辑:dispatch_sink('onhand-ready') 分发到组合根注册的业务 sink
|
||||
(onhand_rpa_workflow.rpa_report_inventory:快照落盘 + 任务状态回写),
|
||||
envelope = 裸业务 tool_response dict(与旧 /rpa/inventory-ready 逐字一致)。
|
||||
"""
|
||||
return jsonify(dispatch_sink('onhand-ready', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/onhand-batch-ready', methods=['POST'])
|
||||
def onhand_batch_ready():
|
||||
"""
|
||||
onhand 批量导出终态回调(旧 /rpa/inventory-batch-ready)。
|
||||
【AI 触发时机】:非 Agent 入口;库存 Worker 按排程批次完成全部站点导出后调用。
|
||||
|
||||
核心逻辑:dispatch_sink('onhand-batch-ready') 分发;按 Warehouse 写入库存快照并
|
||||
finalize 排程 run(rpa_report_inventory_batch),envelope = 裸业务 dict。
|
||||
"""
|
||||
return jsonify(dispatch_sink('onhand-batch-ready', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/onhand-batch-claimed', methods=['POST'])
|
||||
def onhand_batch_claimed():
|
||||
"""
|
||||
onhand 批量领取回调(旧 /rpa/inventory-batch-claimed)。
|
||||
【AI 触发时机】:非 Agent 入口;v2 Worker 领取批次 trigger 后立即调用。
|
||||
|
||||
核心逻辑:dispatch_sink('onhand-batch-claimed') 分发;仅记录 Attempt 执行阶段
|
||||
(per_source_rpa_service.claim_inventory_batch),envelope = {'success':True,'data':...}。
|
||||
"""
|
||||
return jsonify(dispatch_sink('onhand-batch-claimed', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/onhand-batch-progress', methods=['POST'])
|
||||
def onhand_batch_progress():
|
||||
"""
|
||||
onhand 批量导出进度回调(旧 /rpa/inventory-batch-progress)。
|
||||
【AI 触发时机】:非 Agent 入口;Worker 每完成一个站点导出后调用(非终态,以 batch-ready 为准)。
|
||||
|
||||
核心逻辑:dispatch_sink('onhand-batch-progress') 分发;实时回写排程 run 计数
|
||||
(onhand_rpa_workflow.report_inventory_batch_progress),envelope = 裸业务 dict。
|
||||
"""
|
||||
return jsonify(dispatch_sink('onhand-batch-progress', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/onhand-configuration-test-start', methods=['POST'])
|
||||
def onhand_configuration_test_start():
|
||||
"""
|
||||
onhand 配置测试开始回调(旧 /rpa/inventory-configuration-test-batch-progress)。
|
||||
【AI 触发时机】:非 Agent 入口;Worker 领取批量验证中的单个站点后立即调用。
|
||||
|
||||
核心逻辑:dispatch_sink('onhand-configuration-test-start') 分发;把该站点测试运行写为
|
||||
processing / rpa_exporting,envelope = {'status':'ok','data':...}(旧 batch-progress 同款)。
|
||||
"""
|
||||
return jsonify(dispatch_sink('onhand-configuration-test-start', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/onhand-configuration-test-analyze', methods=['POST'])
|
||||
def onhand_configuration_test_analyze():
|
||||
"""
|
||||
onhand 配置测试结构分析回调(旧 /rpa/inventory-configuration-test-ready)。
|
||||
【AI 触发时机】:非 Agent 入口;Worker 完成单站点配置测试导出后调用。
|
||||
|
||||
核心逻辑:dispatch_sink('onhand-configuration-test-analyze') 分发;仅分析文件结构,
|
||||
不创建生产库存快照或任务关联,envelope = {'status':'ok','data':...}(旧 ready 同款)。
|
||||
"""
|
||||
return jsonify(dispatch_sink('onhand-configuration-test-analyze', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/onhand-configuration-test-complete', methods=['POST'])
|
||||
def onhand_configuration_test_complete():
|
||||
"""
|
||||
onhand 配置测试批次终态回调(旧 /rpa/inventory-configuration-test-batch-ready)。
|
||||
【AI 触发时机】:非 Agent 入口;Worker 完成批量配置测试后按 validation_run_no 回传 results。
|
||||
|
||||
核心逻辑:dispatch_sink('onhand-configuration-test-complete') 分发;独立回写每个库存站点
|
||||
的测试结果,envelope = {'status':'ok','data':...}(旧 batch-ready 同款)。
|
||||
"""
|
||||
return jsonify(dispatch_sink('onhand-configuration-test-complete', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/onhand-repair', methods=['POST'])
|
||||
def onhand_repair():
|
||||
"""
|
||||
onhand 受控库存回调修复(旧 /rpa/inventory-repair)。
|
||||
【AI 触发时机】:非 Agent 入口;人工/运维补偿链路调用,复用正式 v2 ingest 流程。
|
||||
|
||||
核心逻辑:dispatch_sink('onhand-repair') 分发;repair 语义由 kind 承载——sink 等价于
|
||||
旧实现 `payload['repair'] = True` 后走 batch-ready ingest,envelope = 裸业务 dict。
|
||||
"""
|
||||
return jsonify(dispatch_sink('onhand-repair', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/inbound-batch-ready', methods=['POST'])
|
||||
def inbound_batch_ready():
|
||||
"""
|
||||
inbound(收料)批量导出终态回调(旧 /rpa/receipt-batch-ready)。
|
||||
【AI 触发时机】:非 Agent 入口;入站 Worker 完成报表导出并落 drop 目录后调用。
|
||||
|
||||
核心逻辑:dispatch_sink('inbound-batch-ready') 分发到组合根
|
||||
(in_transit_transfer.rpa_sinks)注册的业务 sink——直挂
|
||||
freight_rpa.inbound.report_archive.ingest_inbound_callback 原样归档,终态 commit
|
||||
后经 ReportFact → handle_inbound_report 推进调拨并归集排程;绝不进入库存匹配链路;
|
||||
envelope = {'success': True, 'data': ...}(旧端点逐字一致)。
|
||||
"""
|
||||
return jsonify(dispatch_sink('inbound-batch-ready', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/inbound-unit-progress', methods=['POST'])
|
||||
def inbound_unit_progress():
|
||||
"""
|
||||
inbound 单元领取/导出中回调(旧 /rpa/receipt-unit-progress)。
|
||||
【AI 触发时机】:非 Agent 入口;入站 Worker 领取单元后调用(awaiting_rpa → processing)。
|
||||
|
||||
核心逻辑:dispatch_sink('inbound-unit-progress') 分发到 mark_inbound_unit_processing
|
||||
(Task 11 已随排程壳平移改名,现住 schedule.freight_rpa_inbound_finalize);本路由同时是收料
|
||||
超时对账的活动锚数据源(mark 落单元 started_at)。曾因重构分叉合并丢失(2026-10-08),
|
||||
Worker 上报全程 404,勿再从任何路由文件删除。
|
||||
"""
|
||||
return jsonify(dispatch_sink('inbound-unit-progress', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/inbound-batch-progress', methods=['POST'])
|
||||
def inbound_batch_progress():
|
||||
"""
|
||||
inbound 批量导出累计进度回调(旧 /rpa/receipt-batch-progress)。
|
||||
【AI 触发时机】:非 Agent 入口;入站 Worker 每完成一笔导出后调用(非终态)。
|
||||
|
||||
核心逻辑:dispatch_sink('inbound-batch-progress') 分发到 report_inbound_batch_progress
|
||||
(Task 11 已随排程壳平移改名,现住 schedule.freight_rpa_inbound_finalize),回写排程 run 计数
|
||||
(对齐 onhand-batch-progress 语义)。
|
||||
"""
|
||||
return jsonify(dispatch_sink('inbound-batch-progress', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/outbound-batch-ready', methods=['POST'])
|
||||
def outbound_batch_ready():
|
||||
"""
|
||||
outbound(出站)批量导出终态回调。
|
||||
【AI 触发时机】:非 Agent 入口;出站 Worker 完成报表导出并落 drop 目录后调用。
|
||||
|
||||
核心逻辑:dispatch_sink('outbound-batch-ready') 分发到组合根或测内注册的 sink
|
||||
(ingest_outbound_callback:原样归档,终态 commit 后 dispatch_report_fact
|
||||
report_kind='outbound');鉴权与入站同 ToolApiKey。
|
||||
"""
|
||||
return jsonify(dispatch_sink('outbound-batch-ready', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/outbound-unit-progress', methods=['POST'])
|
||||
def outbound_unit_progress():
|
||||
"""
|
||||
outbound 单元领取/导出中回调。
|
||||
【AI 触发时机】:非 Agent 入口;出站 Worker 领取单元后调用(awaiting_rpa → processing)。
|
||||
|
||||
核心逻辑:dispatch_sink('outbound-unit-progress') 分发;鉴权与入站同 ToolApiKey。
|
||||
"""
|
||||
return jsonify(dispatch_sink('outbound-unit-progress', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/outbound-batch-progress', methods=['POST'])
|
||||
def outbound_batch_progress():
|
||||
"""
|
||||
outbound 批量导出累计进度回调。
|
||||
【AI 触发时机】:非 Agent 入口;出站 Worker 每完成一笔导出后调用(非终态)。
|
||||
|
||||
核心逻辑:dispatch_sink('outbound-batch-progress') 分发;鉴权与入站同 ToolApiKey。
|
||||
"""
|
||||
return jsonify(dispatch_sink('outbound-batch-progress', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/upload-complete', methods=['POST'])
|
||||
def upload_complete():
|
||||
"""
|
||||
货代上传结果回调(旧 /rpa/upload-complete,URL 词根不变)。
|
||||
【AI 触发时机】:非 Agent 入口;Worker 完成出货 Excel 上传(成功或失败)后调用。
|
||||
|
||||
核心逻辑:直连 shipping_notice.tools.rpa_report_upload 回写任务状态。
|
||||
"""
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
return jsonify(shipping_tools.rpa_report_upload(_payload()))
|
||||
@@ -1,820 +0,0 @@
|
||||
"""backend/app/api/in_transit_transfer.py
|
||||
|
||||
用途:在途仓自动调拨用户态 API(仓库管理人员)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、app.core.response、matching_service、deps。
|
||||
逻辑:薄路由层鉴权与参数校验;成功响应统一 envelope(ok + request_id);
|
||||
匹配创建(POST /matchings)与进度恢复(GET /matchings/{id});执行为 D8
|
||||
异步契约(POST /items/execute → 202 queued + run_no,单在提交时组建);
|
||||
result_unknown 单人工重新触发(POST /runs/{run_no}/documents/{doc_no}/
|
||||
retrigger → 202,D11 唯一出口);首页「已执行」区块:已执行单分页查询
|
||||
(GET /documents,只读)与人工关闭失败单(POST /documents/{doc_no}/close,
|
||||
D18 废单不废行)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from functools import wraps
|
||||
from typing import Any
|
||||
|
||||
from flask import Blueprint, g, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.models import Agent
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
from app.services.in_transit_transfer.cancellation import cancel_run
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now
|
||||
from app.services.in_transit_transfer.excel_export import _MIME, build_exceptions_workbook
|
||||
from app.services.in_transit_transfer.execution_service import (
|
||||
get_run,
|
||||
prepare_execution,
|
||||
retrigger_document,
|
||||
)
|
||||
from app.services.in_transit_transfer.manual_close_service import manual_close_item, manual_close_items
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
create_matching,
|
||||
list_executable_items,
|
||||
restore_matching,
|
||||
)
|
||||
from app.services.in_transit_transfer.retry_service import (
|
||||
requery_items as retry_service_requery_items,
|
||||
requery_items_by_ids,
|
||||
retry_item,
|
||||
)
|
||||
from app.services.in_transit_transfer.serializers import (
|
||||
DOCUMENT_STATUS_GROUPS,
|
||||
serialize_executed_order,
|
||||
serialize_item,
|
||||
serialize_source,
|
||||
serialize_summary,
|
||||
)
|
||||
|
||||
in_transit_transfer_bp = Blueprint("in_transit_transfer", __name__)
|
||||
|
||||
TRANSFER_AGENT_CODE = "in_transit_transfer"
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""校验当前登录用户;未认证抛 UnauthorizedError。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError("Unauthorized")
|
||||
return user
|
||||
|
||||
|
||||
def require_transfer_permission(f):
|
||||
"""装饰器:admin 放行,或持有 in_transit_transfer Agent 权限的用户放行。"""
|
||||
|
||||
@wraps(f)
|
||||
def decorated(*args, **kwargs):
|
||||
user = _require_user()
|
||||
if user.role == "admin":
|
||||
return f(*args, **kwargs)
|
||||
agent = Agent.query.filter_by(agent_code=TRANSFER_AGENT_CODE, is_active=True).first()
|
||||
if agent is None or agent not in user.agents:
|
||||
raise ForbiddenError("Transfer agent permission required")
|
||||
return f(*args, **kwargs)
|
||||
|
||||
return decorated
|
||||
|
||||
|
||||
def _ok(payload: Any, *, status: int = 200):
|
||||
"""统一成功 envelope(带 request_id)。"""
|
||||
return ok(payload, request_id=getattr(g, "request_id", None), status=status)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/matchings", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def create_matching_api():
|
||||
"""创建或复用一次调拨匹配(只读,不写 外部系统)。
|
||||
|
||||
请求体:{"source_codes": [...], "business_date": "YYYY-MM-DD"(可选),
|
||||
"receipt_date_from"/"receipt_date_to"(可选),
|
||||
"transfer_type": "in_transit_to_hub"(可选,缺省在途仓至HUB仓)}。
|
||||
响应:201 envelope,data 为匹配摘要(matching_id/hash/计数/来源进度)。
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError("request body must be a JSON object")
|
||||
source_codes = body.get("source_codes")
|
||||
if not isinstance(source_codes, list) or not source_codes:
|
||||
raise ValidationError("source_codes is required")
|
||||
business_date = str(body.get("business_date") or business_date_now())
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
summary = create_matching(
|
||||
source_codes=[str(item).strip() for item in source_codes],
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
receipt_date_from=str(body.get("receipt_date_from")) if body.get("receipt_date_from") else None,
|
||||
receipt_date_to=str(body.get("receipt_date_to")) if body.get("receipt_date_to") else None,
|
||||
transfer_type=str(body.get("transfer_type")) if body.get("transfer_type") else None,
|
||||
)
|
||||
return _ok(serialize_summary(summary), status=201)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/items/executable", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def executable_items_api():
|
||||
"""可调拨明细(全局可执行行队列):勾选后 POST /items/execute 按行生成调拨单。"""
|
||||
return _ok(list_executable_items())
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/matchings/<matching_id>", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def get_matching_api(matching_id: str):
|
||||
"""恢复匹配进度与明细(页面刷新/会话恢复;明细按 scope 实时圈行并装饰行级状态)。"""
|
||||
restored = restore_matching(matching_id, deps=transfer_deps.get_transfer_dependencies())
|
||||
return _ok({
|
||||
"summary": serialize_summary(restored["summary"]),
|
||||
"items": [serialize_item(item) for item in restored["items"]],
|
||||
"sources": [serialize_source(source) for source in restored["sources"]],
|
||||
})
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/matchings/<matching_no>/items/requery", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def requery_items_api(matching_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(
|
||||
matching_no=matching_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):
|
||||
"""恢复 Run 结果(页面刷新/会话恢复)。
|
||||
|
||||
返回体:result(单号聚合 + exceptions 既有口径)+ orders 调拨单清单
|
||||
(D9 融合卡数据源:调拨单清单=进度=结果,轮询即恢复最新单态)。
|
||||
"""
|
||||
return _ok(get_run(run_no))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>/cancel", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def cancel_run_api(run_no: str):
|
||||
"""请求停止剩余任务(原因必填,已成功单据保留)。"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
reason = body.get("reason") if isinstance(body, dict) else None
|
||||
return _ok(cancel_run(run_no=run_no, reason=reason))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/items/<int:item_id>/retry", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def retry_item_api(item_id: int):
|
||||
"""人工重试异常项(基于冻结文件仅重新查询 外部系统,创建新 Attempt)。
|
||||
|
||||
请求体:{"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 "external_recheck"))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/items/<int:item_id>/manual-close", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def manual_close_item_api(item_id: int):
|
||||
"""人工关闭异常项(原因必填,永久排除)。"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
reason = body.get("reason") if isinstance(body, dict) else None
|
||||
return _ok(manual_close_item(item_id=item_id, reason=reason))
|
||||
|
||||
|
||||
def _require_item_ids(body: Any) -> list[int]:
|
||||
"""解析并校验批量操作的 item_ids(非空整数列表)。"""
|
||||
raw = body.get("item_ids") if isinstance(body, dict) else None
|
||||
if not isinstance(raw, list) or not raw:
|
||||
raise ValidationError("item_ids is required", code="TRANSFER.BATCH_ITEMS_REQUIRED")
|
||||
try:
|
||||
return [int(x) for x in raw]
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError("item_ids must be integers", code="TRANSFER.BATCH_ITEMS_REQUIRED") from exc
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/items/execute", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def execute_items_api():
|
||||
"""按行提交执行(D8 异步:202 排队,单在提交时已组建,worker 逐单执行)。
|
||||
|
||||
请求体:{"item_ids": [int]}(匹配卡/待执行池勾选的真实明细行 id)。
|
||||
响应:202 envelope,data 为 {"run_no", "status": "queued"}(纯库内毫秒级:
|
||||
两道门禁(存在可执行 + 文件版本对账;TTL 新鲜度门禁 2026-09-25 退役)+
|
||||
建 queued Run + 五元组分组建单 + 一次入队);
|
||||
门禁失败 400,error.details 携带对应 id 列表
|
||||
(invalid_item_ids / changed_item_ids)。
|
||||
进度与结果经 GET /runs/{run_no} 轮询恢复(融合卡数据源)。
|
||||
"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
item_ids = _require_item_ids(body)
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
outcome = prepare_execution(
|
||||
item_ids=item_ids,
|
||||
deps=deps,
|
||||
actor_id=user.id,
|
||||
request_id=getattr(g, "request_id", None),
|
||||
)
|
||||
return _ok({
|
||||
"run_no": outcome.run_no,
|
||||
"status": outcome.status,
|
||||
}, status=202)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>/documents/<doc_no>/retrigger", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def retrigger_document_api(run_no: str, doc_no: str):
|
||||
"""人工重新触发 result_unknown 单(D11 唯一出口,禁止关闭重建)。
|
||||
|
||||
语义:复用本单 doc_no/submit_timestamp,只触发末步(D7②,幂等安全);
|
||||
成功后单/行推进成功族并亮出原单号。人工动作,非自动重试。
|
||||
响应:202 envelope,data 为 {"run_no", "doc_no", "status": "queued"};
|
||||
非 result_unknown 单 → 400(TRANSFER.RETRIGGER_NOT_ALLOWED)。
|
||||
"""
|
||||
user = _require_user()
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
outcome = retrigger_document(
|
||||
run_no=run_no,
|
||||
doc_no=doc_no,
|
||||
deps=deps,
|
||||
actor_id=str(user.id) if user.id else None,
|
||||
request_id=getattr(g, "request_id", None),
|
||||
)
|
||||
return _ok(outcome, status=202)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/documents", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def list_documents_api():
|
||||
"""已执行单分页查询(首页「已执行」区块数据源;只读,不写审计)。
|
||||
|
||||
Query:
|
||||
status_group ∈ {success, failed, executing, result_unknown}(可选,缺省全部;
|
||||
非法 400);date_from/date_to=YYYY-MM-DD(可选,仅作用 orders 列表);
|
||||
page(默认 1);page_size(默认 20,上限 100)。
|
||||
口径:分组计数恒全量(GROUP BY status 对全部单统计,不受筛选影响——
|
||||
失败/结果未知/执行中=未完结即待办,全量才不漏;成功=累计产出);
|
||||
列表 created_at 倒序分页,cancelled 不展示(无产生路径)。
|
||||
响应:{groups, total, page, page_size, orders:[serialize_executed_order 投影]}。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import TransferDocument, TransferInvoiceItem
|
||||
from sqlalchemy import func
|
||||
|
||||
def _parse_date(name: str):
|
||||
"""解析 YYYY-MM-DD 查询参数;空缺省返回 None,非法格式 400。"""
|
||||
raw = (request.args.get(name) or "").strip()
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
return datetime.strptime(raw, "%Y-%m-%d").date()
|
||||
except ValueError as exc:
|
||||
raise ValidationError(f"{name} must be YYYY-MM-DD") from exc
|
||||
|
||||
def _parse_int(name: str, default: int, *, minimum: int, maximum: int | None = None) -> int:
|
||||
"""解析整数查询参数(缺省回默认值;下限钳制必填,上限可选)。"""
|
||||
raw = (request.args.get(name) or "").strip()
|
||||
if not raw:
|
||||
return default
|
||||
try:
|
||||
value = int(raw)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(f"{name} must be an integer") from exc
|
||||
value = max(minimum, value)
|
||||
if maximum is not None:
|
||||
value = min(maximum, value)
|
||||
return value
|
||||
|
||||
# [STEP 1] 参数校验:status_group 白名单外 400(fail-closed)。
|
||||
status_group = (request.args.get("status_group") or "").strip()
|
||||
if status_group and status_group not in DOCUMENT_STATUS_GROUPS:
|
||||
raise ValidationError(
|
||||
f"status_group must be one of {sorted(DOCUMENT_STATUS_GROUPS)}",
|
||||
)
|
||||
date_from = _parse_date("date_from")
|
||||
date_to = _parse_date("date_to")
|
||||
page = _parse_int("page", 1, minimum=1)
|
||||
page_size = _parse_int("page_size", 20, minimum=1, maximum=100)
|
||||
|
||||
# [STEP 2] 分组计数恒全量:GROUP BY status 对全部单统计,不受任何筛选影响。
|
||||
counts = dict(
|
||||
db.session.query(TransferDocument.status, func.count())
|
||||
.group_by(TransferDocument.status)
|
||||
.all()
|
||||
)
|
||||
groups = {
|
||||
group: sum(counts.get(status, 0) for status in statuses)
|
||||
for group, statuses in DOCUMENT_STATUS_GROUPS.items()
|
||||
}
|
||||
|
||||
# [STEP 3] 列表查询:status_group / created_at 时间窗仅作用列表;
|
||||
# cancelled 恒不展示;created_at 倒序稳定分页(id 兜底同刻排序)。
|
||||
query = TransferDocument.query.filter(TransferDocument.status != "cancelled")
|
||||
if status_group:
|
||||
query = query.filter(TransferDocument.status.in_(DOCUMENT_STATUS_GROUPS[status_group]))
|
||||
if date_from:
|
||||
query = query.filter(TransferDocument.created_at >= datetime(date_from.year, date_from.month, date_from.day))
|
||||
if date_to:
|
||||
window_end = datetime(date_to.year, date_to.month, date_to.day) + timedelta(days=1)
|
||||
query = query.filter(TransferDocument.created_at < window_end)
|
||||
total = query.count()
|
||||
docs = (
|
||||
query.order_by(TransferDocument.created_at.desc(), TransferDocument.id.desc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
|
||||
# [STEP 4] items 批量查回(防 N+1),按 document_id 分组后逐单投影。
|
||||
doc_ids = [doc.id for doc in docs]
|
||||
items_by_doc: dict[int, list] = {}
|
||||
if doc_ids:
|
||||
rows = (
|
||||
TransferInvoiceItem.query.filter(TransferInvoiceItem.document_id.in_(doc_ids))
|
||||
.order_by(TransferInvoiceItem.id.asc())
|
||||
.all()
|
||||
)
|
||||
for row in rows:
|
||||
items_by_doc.setdefault(row.document_id, []).append(row)
|
||||
|
||||
return _ok({
|
||||
"groups": groups,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"orders": [serialize_executed_order(doc, items_by_doc.get(doc.id, [])) for doc in docs],
|
||||
})
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/documents/<doc_no>/close", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def close_document_api(doc_no: str):
|
||||
"""人工关闭失败单(D18:语义=A 废单不废行;首页已执行区块/融合卡共用)。
|
||||
|
||||
门禁:仅 business_failed/technical_failed 可关;result_unknown → 400
|
||||
(D11:结果未知单唯一出口=重新触发,禁止「关闭后重建」双单路径);
|
||||
pending/executing → 400(在飞);原因必填;单不存在 404。
|
||||
行为:doc.status='cancelled' + closed_reason=reason;单内 items 全部脱离
|
||||
(document_id=NULL、status→ready_to_execute、清 result_code/result_message
|
||||
——原路由漂移行由执行期既有守卫重新把关);审计事件(actor/reason/
|
||||
前后状态/行数)。
|
||||
效果:cancelled 不在部分唯一索引未完结集 → 组锁释放,同组可另开新单。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import TransferDocument, TransferInvoiceItem
|
||||
from app.services.in_transit_transfer import status as status_machine
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.contracts import TRANSFER_MANUAL_CLOSE_REASON_REQUIRED
|
||||
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
reason = str(body.get("reason") or "").strip() if isinstance(body, dict) else ""
|
||||
# [STEP 1] 原因必填(复用人工关闭既有错误码,查重不新增)。
|
||||
if not reason:
|
||||
raise ValidationError(
|
||||
"document close reason is required",
|
||||
code=TRANSFER_MANUAL_CLOSE_REASON_REQUIRED,
|
||||
)
|
||||
doc = TransferDocument.query.filter_by(doc_no=str(doc_no).strip()).first()
|
||||
if doc is None:
|
||||
raise NotFoundError("transfer document not found", code="TRANSFER.DOCUMENT_NOT_FOUND")
|
||||
|
||||
# [STEP 2] 状态门禁:result_unknown 走 retrigger(D11);在飞/已完结单拒绝。
|
||||
if doc.status == "result_unknown":
|
||||
raise ValidationError(
|
||||
"result_unknown order cannot be closed; use retrigger instead (D11)",
|
||||
code="TRANSFER.DOCUMENT_CLOSE_NOT_ALLOWED",
|
||||
)
|
||||
if doc.status not in DOCUMENT_STATUS_GROUPS["failed"]:
|
||||
raise ValidationError(
|
||||
f"order status {doc.status} is not closeable (in-flight or settled)",
|
||||
code="TRANSFER.DOCUMENT_CLOSE_NOT_ALLOWED",
|
||||
)
|
||||
|
||||
# [STEP 3] D18 行脱离:单内 items 全部脱离单(document_id=NULL)回
|
||||
# ready_to_execute(可重新勾选组建新单),行级结果清空。
|
||||
before_status = doc.status
|
||||
items = TransferInvoiceItem.query.filter_by(document_id=doc.id).all()
|
||||
ready_status = status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
for item in items:
|
||||
item.document_id = None
|
||||
item.status = ready_status
|
||||
item.result_code = None
|
||||
item.result_message = None
|
||||
|
||||
# [STEP 4] 单 cancelled + closed_reason 可视留档;组锁随之释放。
|
||||
doc.status = "cancelled"
|
||||
doc.closed_reason = reason
|
||||
|
||||
# [STEP 5] 审计事件(actor/reason/前后状态/行数)后提交。
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_DOCUMENT_CLOSED",
|
||||
aggregate_type="transfer_document",
|
||||
aggregate_id=doc.doc_no,
|
||||
run_no=doc.run.run_no if doc.run_id and doc.run else None,
|
||||
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",
|
||||
before={"status": before_status},
|
||||
after={"status": doc.status, "reason": reason, "item_count": len(items)},
|
||||
))
|
||||
db.session.commit()
|
||||
return _ok({"doc_no": doc.doc_no, "status": doc.status, "released_items": len(items)})
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/documents/<doc_no>/retry", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def retry_document_api(doc_no: str):
|
||||
"""调拨单级重试(失败单一键恢复主路径)。
|
||||
|
||||
门禁:仅 business_failed/technical_failed 可重试;result_unknown → 400
|
||||
(D11 唯一出口=重新触发);pending/executing 在飞拒绝;单不存在 404。
|
||||
行为:单内 blocked 行逐行重查(复用 retry_item,单行隔离)→ 全部 ready 则
|
||||
自动建新 Run 重跑(prepare_execution,D7①分支②复用原单号);任一行仍
|
||||
阻断则不重跑(单是原子单位),阻断明细随响应返回由恢复池兜底。
|
||||
"""
|
||||
from app.services.in_transit_transfer.retry_service import retry_document
|
||||
|
||||
user = _require_user()
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
return _ok(retry_document(
|
||||
doc_no=doc_no, deps=deps,
|
||||
actor_id=user.id if user and user.id else None,
|
||||
request_id=getattr(g, "request_id", None),
|
||||
))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/items/batch-requery", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def batch_requery_items_api():
|
||||
"""批量重查外部系统库存(待处理池多选「重查」;单行隔离)。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
item_ids = _require_item_ids(body)
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
return _ok(requery_items_by_ids(
|
||||
item_ids=item_ids, deps=deps,
|
||||
actor_id=str(user.id) if user.id else None,
|
||||
request_id=getattr(g, "request_id", None),
|
||||
))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/items/batch-manual-close", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def batch_manual_close_items_api():
|
||||
"""批量人工关闭异常项(原因必填,整批共用;单行隔离)。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
item_ids = _require_item_ids(body)
|
||||
return _ok(manual_close_items(
|
||||
item_ids=item_ids, reason=str(body.get("reason") or ""),
|
||||
actor_id=str(user.id) if user.id else None,
|
||||
request_id=getattr(g, "request_id", None),
|
||||
))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>/exceptions.xlsx", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def exceptions_excel_api(run_no: str):
|
||||
"""下载本次 Run 的七 Sheet 异常 Excel(下载行为记录访问审计)。"""
|
||||
import io
|
||||
|
||||
from app import db
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
|
||||
data = build_exceptions_workbook(run_no)
|
||||
user = _require_user()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_EXCEL_DOWNLOADED",
|
||||
aggregate_type="transfer_run",
|
||||
aggregate_id=run_no,
|
||||
run_no=run_no,
|
||||
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()
|
||||
return send_file(
|
||||
io.BytesIO(data),
|
||||
mimetype=_MIME,
|
||||
as_attachment=True,
|
||||
download_name=f"transfer-exceptions-{run_no}.xlsx",
|
||||
)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>/receipt-files", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def receipt_files_api(run_no: str):
|
||||
"""下载本次收料来源文件(清单 + 原始行追溯,zip);记录访问审计。"""
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
|
||||
from app import db
|
||||
from app.models import TransferInvoiceItem, TransferRun
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
|
||||
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")
|
||||
matching = run.matchings[0] if run.matchings else None
|
||||
file_snapshot = matching.file_snapshot_json if matching and isinstance(matching.file_snapshot_json, dict) else {}
|
||||
|
||||
buffer = io.BytesIO()
|
||||
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
|
||||
for source_code in run.source_codes_json:
|
||||
manifest = {
|
||||
"source_code": source_code,
|
||||
"business_date": run.business_date,
|
||||
**dict(file_snapshot.get(source_code) or {}),
|
||||
}
|
||||
archive.writestr(f"{source_code}-receipt-info.json", json.dumps(manifest, ensure_ascii=False, indent=2))
|
||||
rows = []
|
||||
for item in TransferInvoiceItem.query.filter_by(run_id=run.id).all():
|
||||
for line in (item.raw_lines_json or []):
|
||||
rows.append({
|
||||
"invoice_no": item.invoice_no, "source_code": item.source_code,
|
||||
"sheet": line.get("sheet", ""), "row_no": line.get("row_no", ""),
|
||||
"file_version": line.get("file_version", ""),
|
||||
})
|
||||
archive.writestr("raw-line-trace.json", json.dumps(rows, ensure_ascii=False, indent=2))
|
||||
|
||||
user = _require_user()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_RECEIPT_FILES_DOWNLOADED",
|
||||
aggregate_type="transfer_run",
|
||||
aggregate_id=run_no,
|
||||
run_no=run_no,
|
||||
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()
|
||||
return send_file(
|
||||
io.BytesIO(buffer.getvalue()),
|
||||
mimetype="application/zip",
|
||||
as_attachment=True,
|
||||
download_name=f"receipt-files-{run_no}.zip",
|
||||
)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>/external-inventory", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def erp_inventory_api(run_no: str):
|
||||
"""下载本次匹配冻结的 外部系统 库存表(csv);记录访问审计。"""
|
||||
import io
|
||||
|
||||
from app import db
|
||||
from app.models import TransferInvoiceItem, TransferRun
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
|
||||
run = TransferRun.query.filter_by(run_no=str(run_no).strip()).first()
|
||||
if run is None:
|
||||
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
|
||||
lines = ["invoice_no,source_code,material_no,from_warehouse,to_warehouse,receipt_quantity,external_quantity,result,external_document_no"]
|
||||
for item in TransferInvoiceItem.query.filter_by(run_id=run.id).order_by(TransferInvoiceItem.invoice_no).all():
|
||||
lines.append(",".join([
|
||||
str(item.invoice_no), str(item.source_code), str(item.material_no),
|
||||
str(item.from_warehouse), str(item.to_warehouse),
|
||||
str(item.receipt_quantity), str(item.external_quantity or ""),
|
||||
str(item.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_EXTERNAL_INVENTORY_DOWNLOADED",
|
||||
aggregate_type="transfer_run",
|
||||
aggregate_id=run_no,
|
||||
run_no=run_no,
|
||||
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()
|
||||
return send_file(
|
||||
io.BytesIO(data),
|
||||
mimetype="text/csv",
|
||||
as_attachment=True,
|
||||
download_name=f"external-inventory-{run_no}.csv",
|
||||
)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/metrics", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def transfer_metrics_api():
|
||||
"""调拨运营指标(成功率/失败类型/待处理老化/通知失败),供运营看板。"""
|
||||
from app.services.in_transit_transfer.metrics import collect_metrics
|
||||
|
||||
return _ok(collect_metrics())
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/sources", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def transfer_sources_api():
|
||||
"""来源实例列表(决策 3:平台 DBS/Crane 仅分组,实例为执行边界)。
|
||||
|
||||
每来源附收料文件状态(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
|
||||
|
||||
rows = ShippingInventorySource.query.filter_by(enabled=True).order_by(
|
||||
ShippingInventorySource.connector_type, ShippingInventorySource.source_code,
|
||||
).all()
|
||||
return _ok([
|
||||
{
|
||||
"source_code": source.source_code,
|
||||
"display_name": source.display_name,
|
||||
"platform": source.connector_type,
|
||||
"enabled": bool(source.enabled),
|
||||
**resolve_source_file_status(source_code=source.source_code),
|
||||
}
|
||||
for source in rows
|
||||
])
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/sources/<source_code>/retry-rpa", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def retry_source_rpa_api(source_code: str):
|
||||
"""对指定来源重新触发一次收料 RPA 抓取(复用货代收料 trigger 链路)。
|
||||
|
||||
响应:{"source_code", "file_status", "ok"};配置缺失时 fail-closed(ok=False)。
|
||||
"""
|
||||
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now
|
||||
|
||||
source_code = str(source_code).strip()
|
||||
outcome = trigger_receipt_rpa(
|
||||
source_code=source_code,
|
||||
business_date=str(business_date_now()),
|
||||
reason="transfer_retry_receipt",
|
||||
)
|
||||
status = resolve_source_file_status(source_code=source_code)
|
||||
if not outcome.get("ok"):
|
||||
return _ok({
|
||||
"source_code": source_code,
|
||||
"ok": False,
|
||||
"file_status": status["file_status"],
|
||||
"error_code": outcome.get("error_code"),
|
||||
})
|
||||
return _ok({
|
||||
"source_code": source_code,
|
||||
"ok": True,
|
||||
"file_status": "fetching",
|
||||
"callback_id": outcome.get("callback_id"),
|
||||
}, status=202)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/backlog", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def backlog_api():
|
||||
"""待处理异常列表(可恢复/已关闭/结果未知 + 老化等级);查看记录访问审计。"""
|
||||
from app import db
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.backlog_service import list_backlog
|
||||
|
||||
items = list_backlog()
|
||||
user = _require_user()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type='TRANSFER_BACKLOG_VIEWED',
|
||||
aggregate_type='transfer_backlog',
|
||||
aggregate_id='backlog',
|
||||
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',
|
||||
after={'item_count': len(items)},
|
||||
))
|
||||
db.session.commit()
|
||||
return _ok([_serialize_backlog_item(item) for item in items])
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/backlog/summary", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def backlog_summary_api():
|
||||
"""待处理异常汇总(含 3/5/7 天老化分级)。"""
|
||||
from app.services.in_transit_transfer.backlog_service import backlog_summary
|
||||
|
||||
summary = backlog_summary()
|
||||
return _ok({
|
||||
'recoverable': summary.recoverable_count,
|
||||
'closed': summary.closed_count,
|
||||
'unknown': summary.unknown_count,
|
||||
'aging': {
|
||||
'warn_3d': summary.warn_3d,
|
||||
'escalate_5d': summary.escalate_5d,
|
||||
'critical_7d': summary.critical_7d,
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
def _serialize_backlog_item(item) -> dict[str, Any]:
|
||||
"""待处理池项序列化(明细字段与匹配窗口列一致)。"""
|
||||
return {
|
||||
'item_id': item.item_id,
|
||||
'source_code': item.source_code,
|
||||
'invoice_no': item.invoice_no,
|
||||
'material_no': item.material_no,
|
||||
'status': item.status,
|
||||
'reason': item.reason,
|
||||
'age_days': item.age_days,
|
||||
'aging_level': item.aging_level,
|
||||
'last_attempt_at': item.last_attempt_at,
|
||||
'receipt_date': item.receipt_date,
|
||||
'material_name': item.material_name,
|
||||
'from_warehouse': item.from_warehouse,
|
||||
'to_warehouse': item.to_warehouse,
|
||||
'lot_no': item.lot_no,
|
||||
'receipt_quantity': item.receipt_quantity,
|
||||
'external_quantity': item.external_quantity,
|
||||
'result_code': item.result_code,
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
backend/app/api/integration.py
|
||||
backend/app/api/integration/__init__.py
|
||||
|
||||
用途:知识库外部集成查询/下载接口(供 Dify Tool 与聊天源文件预览解析)。
|
||||
依赖:Flask Blueprint、SQLAlchemy、IntegrationApiService、Kb* 模型。
|
||||
+3
-1
@@ -1,4 +1,6 @@
|
||||
"""api/integration_connector.py
|
||||
"""
|
||||
backend/app/api/integration_connector/__init__.py
|
||||
|
||||
|
||||
用途:Integration Connector Admin API——配置实体 CRUD、能力清单、能力调用端点、
|
||||
连接测试与集成调用日志查询(列表 + 详情 + 同 operation 步骤时间线)。
|
||||
@@ -1,7 +1,9 @@
|
||||
"""
|
||||
backend/app/api/internal/__init__.py
|
||||
|
||||
用途:内部 job 回调/健康检查 Blueprint。
|
||||
用途:内部 Job 回调 / 健康检查 Blueprint 包。
|
||||
依赖:internal.jobs。
|
||||
逻辑:register_blueprints 从本包导入 internal_jobs_bp,挂载 /api/internal/jobs。
|
||||
"""
|
||||
from app.api.internal.jobs import internal_jobs_bp # noqa: F401
|
||||
|
||||
|
||||
@@ -1,8 +1,243 @@
|
||||
"""
|
||||
backend/app/api/internal/jobs.py
|
||||
|
||||
用途:内部 jobs API(Wave 1 自 internal_jobs.py 迁入)。
|
||||
用途:平台内置 Job 内部 API(POST /api/internal/jobs/<job_key>)。
|
||||
依赖:job_registry、schedule_contract、scheduler_service、
|
||||
freight_rpa_onhand_finalize / inbound_finalize / outbound_finalize(awaiting 延后终态)。
|
||||
逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。
|
||||
"""
|
||||
from app.api.internal_jobs import internal_jobs_bp # noqa: F401
|
||||
from __future__ import annotations
|
||||
|
||||
__all__ = ['internal_jobs_bp']
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||
from app.services.schedule.job_registry import get_platform_job, run_platform_job
|
||||
from app.services.schedule.schedule_contract import normalize_job_key
|
||||
from app.services.schedule.scheduler_service import _generate_run_no
|
||||
from app.services.schedule.freight_rpa_onhand_finalize import (
|
||||
apply_deferred_schedule_run_state,
|
||||
recover_stale_awaiting_rpa_schedule_runs,
|
||||
should_defer_schedule_run_finalization,
|
||||
)
|
||||
from app.services.schedule.freight_rpa_inbound_finalize import (
|
||||
apply_deferred_inbound_schedule_run_state,
|
||||
recover_stale_inbound_rpa_schedule_runs,
|
||||
should_defer_inbound_schedule_run,
|
||||
)
|
||||
from app.services.schedule.freight_rpa_outbound_finalize import (
|
||||
apply_deferred_outbound_schedule_run_state,
|
||||
recover_stale_outbound_rpa_schedule_runs,
|
||||
should_defer_outbound_schedule_run,
|
||||
)
|
||||
|
||||
internal_jobs_bp = Blueprint('internal_jobs', __name__)
|
||||
|
||||
|
||||
def _assert_task_matches_job_key(task: ScheduleTask, job_key: str) -> None:
|
||||
"""
|
||||
校验 task 与 URL job key 一致,防止 schedule_task_id 指向错误 handler。
|
||||
Raises:
|
||||
ValidationError: 非 platform_job 或 platform_api_path 不匹配
|
||||
"""
|
||||
if task.schedule_type != 'platform_job':
|
||||
raise ValidationError(f"schedule_task_id {task.id} is not a platform_job task")
|
||||
task_key = normalize_job_key(task.platform_api_path)
|
||||
if task_key != job_key:
|
||||
raise ValidationError(
|
||||
f"schedule_task_id {task.id} platform_api_path '{task.platform_api_path}' "
|
||||
f"does not match job key '{job_key}'"
|
||||
)
|
||||
|
||||
|
||||
def _resolve_schedule_task_and_run(job_key: str, data: dict) -> tuple[ScheduleTask, ScheduleRun]:
|
||||
"""
|
||||
解析或创建 ScheduleTask / ScheduleRun。
|
||||
核心逻辑:优先 schedule_task_id(须匹配 job key);否则按 platform_api_path 匹配 job key。
|
||||
run_no 查询限定 schedule_task_id,避免跨任务写入。
|
||||
"""
|
||||
schedule_task_id = data.get('schedule_task_id')
|
||||
task = db.session.get(ScheduleTask, int(schedule_task_id)) if schedule_task_id else None
|
||||
if task:
|
||||
_assert_task_matches_job_key(task, job_key)
|
||||
else:
|
||||
task = (
|
||||
ScheduleTask.query.filter(
|
||||
ScheduleTask.platform_api_path == job_key,
|
||||
ScheduleTask.schedule_type == 'platform_job',
|
||||
)
|
||||
.order_by(ScheduleTask.id.desc())
|
||||
.first()
|
||||
)
|
||||
if not task:
|
||||
raise NotFoundError(f"No schedule task found for platform job '{job_key}'")
|
||||
|
||||
run_no = str(data.get('run_no') or '').strip()
|
||||
run = None
|
||||
if run_no:
|
||||
run = ScheduleRun.query.filter_by(run_no=run_no, schedule_task_id=task.id).first()
|
||||
if not run:
|
||||
foreign = ScheduleRun.query.filter_by(run_no=run_no).first()
|
||||
if foreign and foreign.schedule_task_id != task.id:
|
||||
raise ValidationError(
|
||||
f"run_no '{run_no}' belongs to schedule_task_id {foreign.schedule_task_id}, "
|
||||
f"not {task.id}"
|
||||
)
|
||||
if not run:
|
||||
run = ScheduleRun(
|
||||
run_no=run_no or _generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
trigger_type='api',
|
||||
started_at=datetime.utcnow(),
|
||||
status='running',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
if not run.dify_execution_snapshot:
|
||||
capture_dify_execution_snapshot(run, task)
|
||||
db.session.commit()
|
||||
return task, run
|
||||
|
||||
|
||||
def _finalize_run(
|
||||
run: ScheduleRun,
|
||||
*,
|
||||
total_count: int,
|
||||
success_count: int,
|
||||
failed_count: int,
|
||||
skipped_count: int,
|
||||
step_logs: list | None,
|
||||
) -> None:
|
||||
"""写入 run 汇总字段并 commit。"""
|
||||
run.status = (
|
||||
'success' if failed_count == 0
|
||||
else 'failed' if success_count == 0
|
||||
else 'partial_failed'
|
||||
)
|
||||
run.total_count = total_count
|
||||
run.success_count = success_count
|
||||
run.failed_count = failed_count
|
||||
run.skipped_count = skipped_count
|
||||
run.finished_at = datetime.utcnow()
|
||||
if run.started_at and run.finished_at:
|
||||
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000)
|
||||
run.step_logs = step_logs if step_logs else None
|
||||
db.session.commit()
|
||||
|
||||
|
||||
@internal_jobs_bp.route('/<name>', methods=['POST'])
|
||||
def run_internal_job(name: str):
|
||||
"""
|
||||
执行已注册平台 Job。
|
||||
核心逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。
|
||||
"""
|
||||
key = normalize_job_key(name)
|
||||
data = request.get_json(silent=True) or {}
|
||||
|
||||
if not get_platform_job(key):
|
||||
raise NotFoundError(f"Unknown platform job: {name}")
|
||||
|
||||
task, run = _resolve_schedule_task_and_run(key, data)
|
||||
recover_stale_awaiting_rpa_schedule_runs(task)
|
||||
recover_stale_inbound_rpa_schedule_runs(task)
|
||||
recover_stale_outbound_rpa_schedule_runs(task)
|
||||
try:
|
||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = run_platform_job(
|
||||
key, task, run, data,
|
||||
)
|
||||
except Exception as exc:
|
||||
run.status = 'failed'
|
||||
run.error_message = str(exc)
|
||||
run.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
raise AppError(
|
||||
code='SYSTEM.HTTP_ERROR',
|
||||
message=str(exc),
|
||||
http_status=500,
|
||||
details={
|
||||
'traceback': traceback.format_exc(),
|
||||
'summary': {
|
||||
'total_count': 0,
|
||||
'success_count': 0,
|
||||
'failed_count': 0,
|
||||
'skipped_count': 0,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
if should_defer_schedule_run_finalization(task, step_logs):
|
||||
apply_deferred_schedule_run_state(
|
||||
run,
|
||||
task,
|
||||
total_count=total_count,
|
||||
success_count=success_count,
|
||||
failed_count=failed_count,
|
||||
skipped_count=skipped_count,
|
||||
details=details,
|
||||
errors=errors,
|
||||
step_logs=step_logs,
|
||||
)
|
||||
return jsonify({
|
||||
'summary': {
|
||||
'total_count': total_count,
|
||||
'success_count': success_count,
|
||||
'failed_count': failed_count,
|
||||
'skipped_count': skipped_count,
|
||||
},
|
||||
'details': details,
|
||||
'errors': errors,
|
||||
'step_logs': step_logs,
|
||||
'awaiting_rpa_callback': True,
|
||||
})
|
||||
|
||||
if should_defer_inbound_schedule_run(task, step_logs):
|
||||
apply_deferred_inbound_schedule_run_state(
|
||||
run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs,
|
||||
)
|
||||
return jsonify({
|
||||
'summary': {
|
||||
'total_count': total_count, 'success_count': success_count,
|
||||
'failed_count': failed_count, 'skipped_count': skipped_count,
|
||||
},
|
||||
'details': details, 'errors': errors, 'step_logs': step_logs,
|
||||
'awaiting_inbound_rpa_callback': True,
|
||||
})
|
||||
|
||||
if should_defer_outbound_schedule_run(task, step_logs):
|
||||
apply_deferred_outbound_schedule_run_state(
|
||||
run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs,
|
||||
)
|
||||
return jsonify({
|
||||
'summary': {
|
||||
'total_count': total_count, 'success_count': success_count,
|
||||
'failed_count': failed_count, 'skipped_count': skipped_count,
|
||||
},
|
||||
'details': details, 'errors': errors, 'step_logs': step_logs,
|
||||
'awaiting_outbound_rpa_callback': True,
|
||||
})
|
||||
|
||||
_finalize_run(
|
||||
run,
|
||||
total_count=total_count,
|
||||
success_count=success_count,
|
||||
failed_count=failed_count,
|
||||
skipped_count=skipped_count,
|
||||
step_logs=step_logs,
|
||||
)
|
||||
return jsonify({
|
||||
'summary': {
|
||||
'total_count': total_count,
|
||||
'success_count': success_count,
|
||||
'failed_count': failed_count,
|
||||
'skipped_count': skipped_count,
|
||||
},
|
||||
'details': details,
|
||||
'errors': errors,
|
||||
'step_logs': step_logs,
|
||||
})
|
||||
@@ -1,223 +0,0 @@
|
||||
"""
|
||||
backend/app/api/internal_jobs.py
|
||||
|
||||
用途:平台内置 Job 内部 API(POST /api/internal/jobs/<job_key>)。
|
||||
依赖:job_registry、schedule_contract、scheduler_service。
|
||||
逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||
from app.services.schedule.job_registry import get_platform_job, run_platform_job
|
||||
from app.services.schedule.schedule_contract import normalize_job_key
|
||||
from app.services.schedule.scheduler_service import _generate_run_no
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import (
|
||||
apply_deferred_schedule_run_state,
|
||||
recover_stale_awaiting_rpa_schedule_runs,
|
||||
should_defer_schedule_run_finalization,
|
||||
)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import (
|
||||
apply_deferred_receipt_schedule_run_state,
|
||||
recover_stale_receipt_rpa_schedule_runs,
|
||||
should_defer_receipt_schedule_run,
|
||||
)
|
||||
|
||||
internal_jobs_bp = Blueprint('internal_jobs', __name__)
|
||||
|
||||
|
||||
def _assert_task_matches_job_key(task: ScheduleTask, job_key: str) -> None:
|
||||
"""
|
||||
校验 task 与 URL job key 一致,防止 schedule_task_id 指向错误 handler。
|
||||
Raises:
|
||||
ValidationError: 非 platform_job 或 platform_api_path 不匹配
|
||||
"""
|
||||
if task.schedule_type != 'platform_job':
|
||||
raise ValidationError(f"schedule_task_id {task.id} is not a platform_job task")
|
||||
task_key = normalize_job_key(task.platform_api_path)
|
||||
if task_key != job_key:
|
||||
raise ValidationError(
|
||||
f"schedule_task_id {task.id} platform_api_path '{task.platform_api_path}' "
|
||||
f"does not match job key '{job_key}'"
|
||||
)
|
||||
|
||||
|
||||
def _resolve_schedule_task_and_run(job_key: str, data: dict) -> tuple[ScheduleTask, ScheduleRun]:
|
||||
"""
|
||||
解析或创建 ScheduleTask / ScheduleRun。
|
||||
核心逻辑:优先 schedule_task_id(须匹配 job key);否则按 platform_api_path 匹配 job key。
|
||||
run_no 查询限定 schedule_task_id,避免跨任务写入。
|
||||
"""
|
||||
schedule_task_id = data.get('schedule_task_id')
|
||||
task = db.session.get(ScheduleTask, int(schedule_task_id)) if schedule_task_id else None
|
||||
if task:
|
||||
_assert_task_matches_job_key(task, job_key)
|
||||
else:
|
||||
task = (
|
||||
ScheduleTask.query.filter(
|
||||
ScheduleTask.platform_api_path == job_key,
|
||||
ScheduleTask.schedule_type == 'platform_job',
|
||||
)
|
||||
.order_by(ScheduleTask.id.desc())
|
||||
.first()
|
||||
)
|
||||
if not task:
|
||||
raise NotFoundError(f"No schedule task found for platform job '{job_key}'")
|
||||
|
||||
run_no = str(data.get('run_no') or '').strip()
|
||||
run = None
|
||||
if run_no:
|
||||
run = ScheduleRun.query.filter_by(run_no=run_no, schedule_task_id=task.id).first()
|
||||
if not run:
|
||||
foreign = ScheduleRun.query.filter_by(run_no=run_no).first()
|
||||
if foreign and foreign.schedule_task_id != task.id:
|
||||
raise ValidationError(
|
||||
f"run_no '{run_no}' belongs to schedule_task_id {foreign.schedule_task_id}, "
|
||||
f"not {task.id}"
|
||||
)
|
||||
if not run:
|
||||
run = ScheduleRun(
|
||||
run_no=run_no or _generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
trigger_type='api',
|
||||
started_at=datetime.utcnow(),
|
||||
status='running',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
if not run.dify_execution_snapshot:
|
||||
capture_dify_execution_snapshot(run, task)
|
||||
db.session.commit()
|
||||
return task, run
|
||||
|
||||
|
||||
def _finalize_run(
|
||||
run: ScheduleRun,
|
||||
*,
|
||||
total_count: int,
|
||||
success_count: int,
|
||||
failed_count: int,
|
||||
skipped_count: int,
|
||||
step_logs: list | None,
|
||||
) -> None:
|
||||
"""写入 run 汇总字段并 commit。"""
|
||||
run.status = (
|
||||
'success' if failed_count == 0
|
||||
else 'failed' if success_count == 0
|
||||
else 'partial_failed'
|
||||
)
|
||||
run.total_count = total_count
|
||||
run.success_count = success_count
|
||||
run.failed_count = failed_count
|
||||
run.skipped_count = skipped_count
|
||||
run.finished_at = datetime.utcnow()
|
||||
if run.started_at and run.finished_at:
|
||||
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000)
|
||||
run.step_logs = step_logs if step_logs else None
|
||||
db.session.commit()
|
||||
|
||||
|
||||
@internal_jobs_bp.route('/<name>', methods=['POST'])
|
||||
def run_internal_job(name: str):
|
||||
"""
|
||||
执行已注册平台 Job。
|
||||
核心逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。
|
||||
"""
|
||||
key = normalize_job_key(name)
|
||||
data = request.get_json(silent=True) or {}
|
||||
|
||||
if not get_platform_job(key):
|
||||
raise NotFoundError(f"Unknown platform job: {name}")
|
||||
|
||||
task, run = _resolve_schedule_task_and_run(key, data)
|
||||
recover_stale_awaiting_rpa_schedule_runs(task)
|
||||
recover_stale_receipt_rpa_schedule_runs(task)
|
||||
try:
|
||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = run_platform_job(
|
||||
key, task, run, data,
|
||||
)
|
||||
except Exception as exc:
|
||||
run.status = 'failed'
|
||||
run.error_message = str(exc)
|
||||
run.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
raise AppError(
|
||||
code='SYSTEM.HTTP_ERROR',
|
||||
message=str(exc),
|
||||
http_status=500,
|
||||
details={
|
||||
'traceback': traceback.format_exc(),
|
||||
'summary': {
|
||||
'total_count': 0,
|
||||
'success_count': 0,
|
||||
'failed_count': 0,
|
||||
'skipped_count': 0,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
if should_defer_schedule_run_finalization(task, step_logs):
|
||||
apply_deferred_schedule_run_state(
|
||||
run,
|
||||
task,
|
||||
total_count=total_count,
|
||||
success_count=success_count,
|
||||
failed_count=failed_count,
|
||||
skipped_count=skipped_count,
|
||||
details=details,
|
||||
errors=errors,
|
||||
step_logs=step_logs,
|
||||
)
|
||||
return jsonify({
|
||||
'summary': {
|
||||
'total_count': total_count,
|
||||
'success_count': success_count,
|
||||
'failed_count': failed_count,
|
||||
'skipped_count': skipped_count,
|
||||
},
|
||||
'details': details,
|
||||
'errors': errors,
|
||||
'step_logs': step_logs,
|
||||
'awaiting_rpa_callback': True,
|
||||
})
|
||||
|
||||
if should_defer_receipt_schedule_run(task, step_logs):
|
||||
apply_deferred_receipt_schedule_run_state(
|
||||
run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs,
|
||||
)
|
||||
return jsonify({
|
||||
'summary': {
|
||||
'total_count': total_count, 'success_count': success_count,
|
||||
'failed_count': failed_count, 'skipped_count': skipped_count,
|
||||
},
|
||||
'details': details, 'errors': errors, 'step_logs': step_logs,
|
||||
'awaiting_receipt_rpa_callback': True,
|
||||
})
|
||||
|
||||
_finalize_run(
|
||||
run,
|
||||
total_count=total_count,
|
||||
success_count=success_count,
|
||||
failed_count=failed_count,
|
||||
skipped_count=skipped_count,
|
||||
step_logs=step_logs,
|
||||
)
|
||||
return jsonify({
|
||||
'summary': {
|
||||
'total_count': total_count,
|
||||
'success_count': success_count,
|
||||
'failed_count': failed_count,
|
||||
'skipped_count': skipped_count,
|
||||
},
|
||||
'details': details,
|
||||
'errors': errors,
|
||||
'step_logs': step_logs,
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
backend/app/api/linked_services.py
|
||||
backend/app/api/linked_services/__init__.py
|
||||
|
||||
用途:已登录用户读取启用中的关联服务,供 Chat/工作台侧栏入口展示。
|
||||
依赖:JWT current-user、linked_service_service。
|
||||
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
backend/app/api/maintenance.py
|
||||
backend/app/api/maintenance/__init__.py
|
||||
|
||||
用途:设备维保助手 HTTP API,当前提供设备台账配置与 Excel 导入能力。
|
||||
依赖:JWT 当前用户、maintenance_ledger_service、Flask Blueprint/send_file。
|
||||
@@ -55,9 +55,9 @@ def _require_ledger_admin():
|
||||
ForbiddenError: 当前角色不允许写入台账或维修记录。
|
||||
"""
|
||||
user = _require_user()
|
||||
if getattr(user, 'role', None) not in {'admin', 'maintenance_manager'}:
|
||||
raise ForbiddenError('Maintenance manager privilege required')
|
||||
return user
|
||||
if user.has_feature_permission('maintenance.ledger_write'):
|
||||
return user
|
||||
raise ForbiddenError('Maintenance manager privilege required')
|
||||
|
||||
|
||||
def _record_list_filters_from_request() -> dict[str, Any]:
|
||||
@@ -1,149 +1,10 @@
|
||||
"""
|
||||
backend/app/api/maintenance_tools.py
|
||||
|
||||
用途:设备维保助手 Dify Tool API,只开放只读查询工具。
|
||||
依赖:maintenance_chat_service、maintenance_record_service、OpenAPI 构建、Tool API 基地址解析。
|
||||
逻辑:Dify 复杂问法调用本蓝图查询设备台账/维修记录;明确查询仍由 chat.py 本地直答,写操作仍走 HXOPS 管理面板。
|
||||
用途:兼容旧 import 路径的薄 shim(真实现已迁至 api/tools/maintenance.py)。
|
||||
依赖:app.api.tools.maintenance。
|
||||
逻辑:保留 Blueprint;新代码请从 app.api.tools 导入。
|
||||
"""
|
||||
from app.api.tools.maintenance import maintenance_tool_bp # noqa: F401
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError, ValidationError
|
||||
from app.models import MaintenanceRecord
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
|
||||
from app.services.maintenance_chat_service import build_device_query_result
|
||||
from app.services.maintenance_record_service import serialize_record
|
||||
from app.services.maintenance_tools.openapi_spec import build_maintenance_openapi_spec
|
||||
|
||||
maintenance_tool_bp = Blueprint("maintenance_tools", __name__)
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验设备维保 Tool API 鉴权。
|
||||
AI 触发时机:Dify Tool 调用本蓝图时由 before_request 自动执行,不是给 LLM 直接调用的业务工具。
|
||||
"""
|
||||
configured = str(
|
||||
current_app.config.get("MAINTENANCE_TOOL_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
or ""
|
||||
).strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError(
|
||||
"MAINTENANCE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured",
|
||||
code="missing_auth",
|
||||
)
|
||||
|
||||
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||
if configured in {token, integration_key}:
|
||||
return
|
||||
if not token and not integration_key:
|
||||
raise UnauthorizedError("missing_auth")
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
"""把 AppError 归一成 Dify Tool 侧可读错误码。"""
|
||||
message = str(exc.message or "").strip()
|
||||
if message in {"missing_auth", "invalid_auth"}:
|
||||
return message
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
return "missing_auth"
|
||||
if exc.code == "VALIDATION.INVALID_PARAM":
|
||||
return message or "invalid_request"
|
||||
return exc.code
|
||||
|
||||
|
||||
@maintenance_tool_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
"""Tool API 统一错误响应。"""
|
||||
return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status
|
||||
|
||||
|
||||
@maintenance_tool_bp.before_request
|
||||
def _verify_tool_access():
|
||||
"""除 OpenAPI 文档外,所有 Tool 调用必须携带有效服务级 token。"""
|
||||
if request.path.endswith("/openapi.json") or request.path.endswith("/openapi.dify.yaml"):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
def _payload() -> dict:
|
||||
"""读取 JSON 请求体。"""
|
||||
return request.get_json(silent=True) or {}
|
||||
|
||||
|
||||
def _clean_text(value) -> str:
|
||||
return str(value or "").strip()
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def openapi_spec():
|
||||
"""返回 Dify 导入用的 OpenAPI JSON。"""
|
||||
return jsonify(build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/openapi.dify.yaml", methods=["GET"])
|
||||
def openapi_dify_yaml():
|
||||
"""返回 Dify 导入用的 OpenAPI YAML。"""
|
||||
import yaml
|
||||
|
||||
body = yaml.safe_dump(
|
||||
build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()),
|
||||
allow_unicode=True,
|
||||
sort_keys=False,
|
||||
)
|
||||
return current_app.response_class(body, mimetype="text/yaml; charset=utf-8")
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/query_device", methods=["POST"])
|
||||
def query_device():
|
||||
"""按设备编号或名称查询设备台账,并可带出最近维修记录。"""
|
||||
data = _payload()
|
||||
keyword = _clean_text(data.get("keyword"))
|
||||
if not keyword:
|
||||
raise ValidationError("keyword is required")
|
||||
include_records = bool(data.get("include_records", True))
|
||||
record_limit = max(0, min(20, int(data.get("record_limit") or 5)))
|
||||
result = build_device_query_result(keyword, include_records=include_records, record_limit=record_limit)
|
||||
return jsonify({"ok": True, **result})
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/query_records", methods=["POST"])
|
||||
def query_records():
|
||||
"""按设备编号/名称和状态查询维修记录。"""
|
||||
data = _payload()
|
||||
keyword = _clean_text(data.get("keyword"))
|
||||
if not keyword:
|
||||
raise ValidationError("keyword is required")
|
||||
status = _clean_text(data.get("status"))
|
||||
limit = max(1, min(50, int(data.get("limit") or 10)))
|
||||
|
||||
query = db.session.query(MaintenanceRecord)
|
||||
like = f"%{keyword}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
MaintenanceRecord.device_code.ilike(like),
|
||||
MaintenanceRecord.device_name.ilike(like),
|
||||
)
|
||||
)
|
||||
if status:
|
||||
query = query.filter(MaintenanceRecord.repair_status == status)
|
||||
rows = query.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc()).limit(limit).all()
|
||||
return jsonify({
|
||||
"ok": True,
|
||||
"matched": bool(rows),
|
||||
"keyword": keyword,
|
||||
"items": [serialize_record(item) for item in rows],
|
||||
"totalReturned": len(rows),
|
||||
})
|
||||
|
||||
__all__ = ['maintenance_tool_bp']
|
||||
@@ -0,0 +1,320 @@
|
||||
"""
|
||||
backend/app/api/order_delivery_reply.py
|
||||
|
||||
用途:订单交期回复工作台 API——列表筛选分页、单行详情、最近同步时间、保存交期批次、单行通知、
|
||||
联合回复保存与批量通知、手动全量同步。
|
||||
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError/NotFoundError/ValidationError、
|
||||
services/order_delivery_reply(query_service 查询、reply_service 保存批次、
|
||||
notify_service 通知锁定、sync_service 同步状态)。
|
||||
逻辑:读取只打本地快照,不触碰 ERP;保存批次只写批次与 save 审计,不通知不锁定;
|
||||
通知与锁定在 notify_service 中同事务完成(企微成功才锁定)。
|
||||
权限要求 access 或 manage(manage 隐含 access),键常量与技术文档 §7.2 一致;写接口要求 manage。
|
||||
鉴权:GET 系列要求 `order_delivery_reply.access` 或 `order_delivery_reply.manage`;
|
||||
保存批次 / 单行通知 / 联合回复 / 批量通知 / 手动同步要求 `order_delivery_reply.manage`;
|
||||
部门批量发放仅 admin 角色。两键 admin 默认开(User._role_default_feature_permissions)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from io import BytesIO
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from flask import Blueprint, g, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.extensions import db
|
||||
from app.models import User
|
||||
from app.services.order_delivery_reply import notify_service, query_service, reply_service
|
||||
from app.services.order_delivery_reply.sync_service import OrderDeliverySyncService
|
||||
|
||||
order_delivery_reply_bp = Blueprint("order_delivery_reply", __name__)
|
||||
|
||||
XLSX_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
|
||||
|
||||
def _utc_to_shanghai(value) -> str | None:
|
||||
"""
|
||||
把后端 naive-UTC 时间转为北京时间的展示字符串(YYYY-MM-DD HH:MM:SS)。
|
||||
|
||||
用途:sync_runs / notified_at 等以 utcnow 落库,直接 isoformat 会把 UTC 当本地时间误导用户。
|
||||
约束:仅用于展示序列化,不改变库内存储;无法解析时原样返回。
|
||||
"""
|
||||
from datetime import timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
local = value.replace(tzinfo=timezone.utc).astimezone(ZoneInfo("Asia/Shanghai"))
|
||||
return local.strftime("%Y-%m-%d %H:%M:%S")
|
||||
except (AttributeError, ValueError):
|
||||
return value.isoformat() if hasattr(value, "isoformat") else str(value)
|
||||
|
||||
# 功能权限键(与 docs/features/order-delivery-reply/technical-design.md §7.2 对齐)。
|
||||
PERMISSION_MANAGE = "order_delivery_reply.manage"
|
||||
PERMISSION_ACCESS = "order_delivery_reply.access"
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""返回当前登录用户;未认证抛 UnauthorizedError。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _has_order_delivery_permission(user, key: str) -> bool:
|
||||
"""
|
||||
判定功能权限:统一走 User.has_feature_permission(角色默认 + 显式勾选合并)。
|
||||
|
||||
核心逻辑:admin 角色两键默认开(User._role_default_feature_permissions);
|
||||
普通用户按用户管理表单勾选;每次请求只看勾选,不拿部门当门禁(技术文档 §7.2)。
|
||||
"""
|
||||
return user.has_feature_permission(key)
|
||||
|
||||
|
||||
def _require_access():
|
||||
"""
|
||||
确保当前用户可访问订单交期回复(查看)。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 未登录。
|
||||
ForbiddenError: 已登录但既无 manage 也无 access(manage 命中视为有 access)。
|
||||
"""
|
||||
user = _require_user()
|
||||
if not (_has_order_delivery_permission(user, PERMISSION_MANAGE) or _has_order_delivery_permission(user, PERMISSION_ACCESS)):
|
||||
raise ForbiddenError(
|
||||
"Order delivery reply access required",
|
||||
code="ORDER_DELIVERY_REPLY.FORBIDDEN",
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
def _require_manage():
|
||||
"""
|
||||
确保当前用户可写订单交期回复(保存批次 / 通知 / 手动同步)。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 未登录。
|
||||
ForbiddenError: 已登录但无 manage(仅有 access 的业务用户只读)。
|
||||
"""
|
||||
user = _require_user()
|
||||
if not _has_order_delivery_permission(user, PERMISSION_MANAGE):
|
||||
raise ForbiddenError(
|
||||
"Order delivery reply manage permission required",
|
||||
code="ORDER_DELIVERY_REPLY.MANAGE_FORBIDDEN",
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
@order_delivery_reply_bp.get("/lines")
|
||||
def list_lines():
|
||||
"""
|
||||
订单行列表(筛选 + 分页)。
|
||||
|
||||
用途与触发时机:工作台首屏与筛选刷新;全选仅作用于本页返回的 items。
|
||||
|
||||
参数与输出约束:查询参数 keyword/order_date/status/page/page_size——keyword 为合并搜索
|
||||
(订单单号/客户订单/客户编号/客户简称/公司全名/产品编号/品名/客户产品编号
|
||||
命中任一即返回);status ∈ 空(全部) | replied(已回复) | not_fully_replied(未完全回复);
|
||||
返回统一 envelope,data.items 为行序列化(含批次、状态、未交数量)。
|
||||
"""
|
||||
_require_access()
|
||||
data = query_service.list_lines(request.args.to_dict(flat=True))
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@order_delivery_reply_bp.get("/lines/export")
|
||||
def export_lines():
|
||||
"""
|
||||
导出当前筛选下的全部订单行 Excel(不分页)。
|
||||
|
||||
用途与触发时机:工作台工具栏「导出 Excel」按钮;查询参数与列表一致
|
||||
(keyword/order_date/status),导出全部命中行(服务层 EXPORT_MAX_ROWS 兜底)。
|
||||
|
||||
参数与输出约束:要求 order_delivery_reply.access 及以上;返回 xlsx 文件流(attachment,
|
||||
文件名带北京时间日期)。
|
||||
"""
|
||||
_require_access()
|
||||
content = query_service.export_lines(request.args.to_dict(flat=True))
|
||||
filename = f"订单交期回复_{datetime.now(ZoneInfo('Asia/Shanghai')):%Y%m%d}.xlsx"
|
||||
return send_file(
|
||||
BytesIO(content),
|
||||
as_attachment=True,
|
||||
download_name=filename,
|
||||
mimetype=XLSX_MIME_TYPE,
|
||||
)
|
||||
|
||||
|
||||
@order_delivery_reply_bp.get("/lines/<order_no>/<int:line_no>")
|
||||
def get_line(order_no: str, line_no: int):
|
||||
"""
|
||||
单行详情:快照 + 批次 + 状态 + 审计事件。
|
||||
|
||||
参数与输出约束:order_no/line_no 为行唯一键;不存在或已标 erp_missing(已不在同步范围)
|
||||
的行一律按不存在处理返回 404,不在工作台展示。
|
||||
"""
|
||||
_require_access()
|
||||
payload = query_service.get_line(order_no, line_no)
|
||||
if payload is None:
|
||||
raise NotFoundError(
|
||||
"Order delivery line not found",
|
||||
code="ORDER_DELIVERY_REPLY.LINE_NOT_FOUND",
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@order_delivery_reply_bp.put("/lines/<order_no>/<int:line_no>/batches")
|
||||
def save_line_batches(order_no: str, line_no: int):
|
||||
"""
|
||||
保存单行交期批次(未锁定行整表替换)。
|
||||
|
||||
用途与触发时机:单行弹窗「回复交期/修改回复」提交;联合回复保存逐行复用同一服务入口。
|
||||
|
||||
参数与输出约束:body {"batches": [{planned_date, qty, remark?}]};交期必填 YYYY-MM-DD、
|
||||
数量 > 0、备注 ≤ 200、批次 1..20 条且交期不重复;各批次合计必须等于订单数量,
|
||||
不等返回 422 BATCH_QTY_TOTAL_MISMATCH(2026-09-23 由「超额仅提醒」修订)。
|
||||
已锁定行返回 409 LINE_LOCKED;erp_missing 行按 404。
|
||||
"""
|
||||
user = _require_manage()
|
||||
payload = request.get_json(silent=True) or {}
|
||||
data = reply_service.save_batches(order_no, line_no, payload.get("batches"), user.id)
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@order_delivery_reply_bp.post("/lines/<order_no>/<int:line_no>/notify")
|
||||
def notify_line(order_no: str, line_no: int):
|
||||
"""
|
||||
单行发送通知业务部门(企微),成功后行级锁定。
|
||||
|
||||
用途与触发时机:生管在行内点「发送通知业务部门」(该行已有批次且未锁定时可用)。
|
||||
|
||||
参数与输出约束:无 body;无批次 422(请先回复交期)、已锁定 409、业务员对不上
|
||||
User.employee_id 或企微发送失败 503(该行不锁定);成功返回
|
||||
locked=true 与交期回复人员(生管工号+姓名)、通知时间、trace_id。
|
||||
"""
|
||||
user = _require_manage()
|
||||
data = notify_service.notify_line(order_no, line_no, user)
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@order_delivery_reply_bp.post("/batch-reply")
|
||||
def batch_reply():
|
||||
"""
|
||||
联合回复交期:对勾选多行逐行保存批次(只保存,不通知、不锁定)。
|
||||
|
||||
用途与触发时机:勾选多行 →「+ 联合回复交期」→ 按行填批次 → 保存回复(R-REPLY-02)。
|
||||
|
||||
参数与输出约束:body {"items": [{order_no, line_no, batches: [{planned_date, qty, remark?}]}]},
|
||||
单次 ≤ 200 行;每行各批次合计必须等于订单数量(不等该行失败,2026-09-23 修订);
|
||||
单行失败不回滚其它行,响应按行给 ok/error;
|
||||
全部行保存成功 success 才为 true 语义由 data.succeeded/failed 表达。
|
||||
"""
|
||||
user = _require_manage()
|
||||
payload = request.get_json(silent=True) or {}
|
||||
data = reply_service.batch_reply(payload.get("items"), user.id)
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@order_delivery_reply_bp.post("/notify-batch")
|
||||
def notify_batch():
|
||||
"""
|
||||
批量通知:对勾选中「已有批次且未锁定」的行逐行发送企微通知并锁定。
|
||||
|
||||
用途与触发时机:勾选多行 → 工具栏「批量通知」(R-NOTIFY-02);与联合回复是两个独立操作。
|
||||
|
||||
参数与输出约束:body {"lines": [{order_no, line_no}]},单次 ≤ 200 行;
|
||||
无批次或已锁定的勾选行 skipped(带 reason)不计成败;
|
||||
单行失败不回滚其它行;返回 succeeded/failed/skipped 与逐行结果。
|
||||
"""
|
||||
user = _require_manage()
|
||||
payload = request.get_json(silent=True) or {}
|
||||
data = notify_service.notify_batch(payload.get("lines"), user)
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@order_delivery_reply_bp.get("/sync/latest")
|
||||
def latest_sync():
|
||||
"""
|
||||
最近一次同步运行记录,供页面展示同步时间与结果。
|
||||
|
||||
参数与输出约束:无参数;从未同步过时 data 为 null(前端展示「尚未同步」),
|
||||
失败时返回 failed 状态与错误摘要,前端明示同步失败并保留上次快照口径。
|
||||
"""
|
||||
_require_access()
|
||||
run = OrderDeliverySyncService.latest_run()
|
||||
if run is None:
|
||||
return ok(None, request_id=getattr(g, "request_id", None))
|
||||
return ok(
|
||||
{
|
||||
"id": run.id,
|
||||
"trigger": run.trigger,
|
||||
"status": run.status,
|
||||
"started_at": _utc_to_shanghai(run.started_at),
|
||||
"finished_at": _utc_to_shanghai(run.finished_at),
|
||||
"line_count": run.line_count,
|
||||
"error_message": run.error_message,
|
||||
},
|
||||
request_id=getattr(g, "request_id", None),
|
||||
)
|
||||
|
||||
|
||||
@order_delivery_reply_bp.post("/sync")
|
||||
def run_sync():
|
||||
"""
|
||||
手动触发一次 ERP 全量同步(范围与 07:00 排程完全一致)。
|
||||
|
||||
用途与触发时机:生管在工作台点「手动刷新」(需求 §15);同步互斥——排程正在跑时
|
||||
返回 skipped,不并发执行。
|
||||
|
||||
参数与输出约束:无 body;同步在本请求内同步执行(一期口径,行量在万级内可控),
|
||||
返回 {run_id, status: success|skipped, line_count};失败原样抛 AppError
|
||||
(上次快照保留,页面明示失败原因)。
|
||||
"""
|
||||
_require_manage()
|
||||
data = OrderDeliverySyncService.run_sync(trigger="manual")
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@order_delivery_reply_bp.post("/admin/permissions/grant-by-department")
|
||||
def grant_permissions_by_department():
|
||||
"""
|
||||
按部门批量发放订单交期回复功能权限(可选能力,仅 admin)。
|
||||
|
||||
用途与触发时机:用户量大时管理员选部门一次性把勾选写到当时该部门成员账号上(需求 §3)。
|
||||
|
||||
参数与输出约束:body {"department": "<部门名>", "permission": "manage" | "access"};
|
||||
这是一次性发放——调岗后权限不随部门字段变化自动增减,需再勾或再跑一次;
|
||||
只做授予(置 true),不撤销;返回 {"department", "permission", "granted"}。
|
||||
部门无成员时 granted=0,不视为错误。
|
||||
"""
|
||||
user = _require_user()
|
||||
if getattr(user, "role", None) != "admin":
|
||||
raise ForbiddenError(
|
||||
"Admin privilege required for department permission grant",
|
||||
code="ORDER_DELIVERY_REPLY.ADMIN_REQUIRED",
|
||||
)
|
||||
payload = request.get_json(silent=True) or {}
|
||||
department = str(payload.get("department") or "").strip()
|
||||
permission = str(payload.get("permission") or "").strip()
|
||||
if not department:
|
||||
raise ValidationError("department 必填", code="ORDER_DELIVERY_REPLY.GRANT_DEPARTMENT_REQUIRED")
|
||||
if permission not in (PERMISSION_MANAGE, PERMISSION_ACCESS):
|
||||
raise ValidationError("permission 须为 manage 或 access", code="ORDER_DELIVERY_REPLY.GRANT_PERMISSION_INVALID")
|
||||
|
||||
members = User.query.filter(User.department == department).all()
|
||||
granted = 0
|
||||
for member in members:
|
||||
# [STEP] 经 set_feature_permissions 归一化:只持久化与角色默认不同的覆盖项。
|
||||
raw = dict(member.feature_permissions) if isinstance(member.feature_permissions, dict) else {}
|
||||
raw[permission] = True
|
||||
member.set_feature_permissions(raw)
|
||||
granted += 1
|
||||
db.session.commit()
|
||||
return ok(
|
||||
{"department": department, "permission": permission, "granted": granted},
|
||||
request_id=getattr(g, "request_id", None),
|
||||
)
|
||||
@@ -1,111 +1,10 @@
|
||||
"""
|
||||
backend/app/api/procurement_contract_tools.py
|
||||
|
||||
Purpose: Chat/tool-facing procurement contract review APIs.
|
||||
Dependencies: procurement_contract services, JWT current user, unified response envelope.
|
||||
Flow: Authenticated users upload comparison files, start reviews, query own history, and download own reports.
|
||||
用途:兼容旧 import 路径的薄 shim(真实现已迁至 api/tools/procurement_contract.py)。
|
||||
依赖:app.api.tools.procurement_contract。
|
||||
逻辑:保留 Blueprint;新代码请从 app.api.tools 导入。
|
||||
"""
|
||||
from app.api.tools.procurement_contract import procurement_contract_bp # noqa: F401
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
|
||||
from flask import Blueprint, g, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.procurement_contract import review_service, template_service
|
||||
|
||||
procurement_contract_bp = Blueprint("procurement_contract", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""Return current authenticated user."""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _optional_int(value, field: str) -> int | None:
|
||||
"""Parse optional int payload fields with a ValidationError on bad input."""
|
||||
if value in (None, ""):
|
||||
return None
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(f"{field} must be integer") from exc
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/templates", methods=["GET"])
|
||||
def list_enabled_templates():
|
||||
"""List enabled templates for chat dropdown."""
|
||||
_require_user()
|
||||
return ok(template_service.list_enabled_for_chat(), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews", methods=["POST"])
|
||||
def start_contract_review():
|
||||
"""Start a review; compare mode requires a user-uploaded original contract baseline."""
|
||||
user = _require_user()
|
||||
data = request.get_json() or {}
|
||||
contract_asset_no = (data.get("contract_asset_no") or "").strip()
|
||||
if not contract_asset_no:
|
||||
raise ValidationError("contract_asset_no is required")
|
||||
result = review_service.start_review(
|
||||
user_id=user.id,
|
||||
review_mode=str(data.get("review_mode") or "compare"),
|
||||
contract_asset_no=contract_asset_no,
|
||||
original_contract_asset_no=(data.get("original_contract_asset_no") or None),
|
||||
contract_type=(data.get("contract_type") or None),
|
||||
supplier_name=(data.get("supplier_name") or None),
|
||||
agent_id=_optional_int(data.get("agent_id"), "agent_id"),
|
||||
chat_log_id=_optional_int(data.get("chat_log_id"), "chat_log_id"),
|
||||
)
|
||||
return ok(result, request_id=getattr(g, "request_id", None), status=202)
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews/<review_no>", methods=["GET"])
|
||||
def get_contract_review(review_no: str):
|
||||
"""Get a current user's review by review number."""
|
||||
user = _require_user()
|
||||
return ok(review_service.get_review_for_owner(review_no=review_no, user_id=user.id), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews/<review_no>/report", methods=["GET"])
|
||||
def download_my_contract_review_report(review_no: str):
|
||||
"""Download current user's review report as txt or docx."""
|
||||
user = _require_user()
|
||||
review_service.get_review_for_owner(review_no=review_no, user_id=user.id)
|
||||
if (request.args.get("format") or "").lower() == "docx":
|
||||
name, data, mimetype = review_service.read_review_report_docx_bytes(review_no=review_no)
|
||||
else:
|
||||
name, data = review_service.read_review_report_bytes(review_no=review_no)
|
||||
mimetype = "text/plain; charset=utf-8"
|
||||
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=name)
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews/<review_no>/annotated-contract", methods=["GET"])
|
||||
def download_my_annotated_contract(review_no: str):
|
||||
"""Download current user's original PDF with anchored risk highlights."""
|
||||
user = _require_user()
|
||||
review_service.get_review_for_owner(review_no=review_no, user_id=user.id)
|
||||
name, data, mimetype = review_service.read_review_annotated_contract_bytes(review_no=review_no)
|
||||
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=name)
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews", methods=["GET"])
|
||||
def list_my_contract_reviews():
|
||||
"""List current user's recent procurement contract reviews."""
|
||||
user = _require_user()
|
||||
data = review_service.list_reviews(
|
||||
user_id=user.id,
|
||||
review_mode=request.args.get("review_mode") or None,
|
||||
status=request.args.get("status") or None,
|
||||
keyword=request.args.get("keyword") or None,
|
||||
risk_level=request.args.get("risk_level") or None,
|
||||
limit=_optional_int(request.args.get("limit"), "limit") or 20,
|
||||
offset=_optional_int(request.args.get("offset"), "offset") or 0,
|
||||
)
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
__all__ = ['procurement_contract_bp']
|
||||
@@ -67,7 +67,7 @@ def update_schedule_task_config(task_id: int):
|
||||
|
||||
config_data = data.get('config', data)
|
||||
if isinstance(config_data, dict) and config_data:
|
||||
# platform_job 仅白名单且 enabled 的任务(如 shipping-inventory-rpa)允许写 ScheduleTaskConfig
|
||||
# platform_job 仅白名单且 enabled 的任务(如 freight-rpa-onhand)允许写 ScheduleTaskConfig
|
||||
if task.schedule_type != SCHEDULE_TYPE_DATA_PIPELINE and not platform_job_allows_config(task.platform_api_path):
|
||||
raise ValidationError(
|
||||
f"platform_job '{task.platform_api_path}' does not accept ScheduleTaskConfig"
|
||||
|
||||
@@ -1,24 +1,29 @@
|
||||
"""
|
||||
backend/app/api/schedule/rpa_workers.py
|
||||
|
||||
用途:管理端查询货代库存 RPA Worker 在线状态与就绪摘要。
|
||||
依赖:schedule.blueprint、rpa_worker_heartbeat.serialize_rpa_worker_status。
|
||||
逻辑:ScheduleWorkbenchPanel 在库存 RPA 排程工作台展示 worker 心跳状态。
|
||||
用途:管理端查询货代库存/入站/出站 RPA Worker 在线状态与就绪摘要。
|
||||
依赖:schedule.blueprint、freight_rpa.common.worker_heartbeat.serialize_rpa_worker_status。
|
||||
逻辑:ScheduleWorkbenchPanel 在库存、入站或出站 RPA 排程工作台展示对应 worker 心跳状态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import request
|
||||
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.response import ok
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import serialize_rpa_worker_status
|
||||
from app.services.freight_rpa.common.worker_heartbeat import serialize_rpa_worker_status
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/rpa-workers/status', methods=['GET'])
|
||||
@require_admin
|
||||
def get_rpa_workers_status():
|
||||
"""
|
||||
返回库存 RPA Worker 心跳摘要(在线/离线、最后心跳时间、就绪原因)。
|
||||
核心逻辑:读取 Redis/内存心跳并与当前环境、trigger 目录比对。
|
||||
返回 RPA Worker 心跳摘要(在线/离线、最后心跳时间、就绪原因)。
|
||||
|
||||
Query:
|
||||
scope: onhand(默认)、inbound 或 outbound。
|
||||
"""
|
||||
return ok(serialize_rpa_worker_status())
|
||||
scope = str(request.args.get('scope') or 'onhand').strip().lower() or 'onhand'
|
||||
return ok(serialize_rpa_worker_status(scope=scope))
|
||||
@@ -2,8 +2,10 @@
|
||||
backend/app/api/schedule/runs.py
|
||||
|
||||
用途:排程运行触发与运行记录查询 API。
|
||||
依赖:schedule.blueprint、services/schedule/query_service、queue_service。
|
||||
依赖:schedule.blueprint、services/schedule/query_service、queue_service、
|
||||
freight_rpa inbound/outbound archive 与 trigger_io。
|
||||
逻辑:手动执行仅创建 queued run/job;独立 schedule worker 承担实际运行。
|
||||
入站/出站 raw-zip 下载与失败单元 list/retry 对照同构。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -18,13 +20,15 @@ from app.api.schedule.blueprint import schedule_admin_bp
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import ConflictError, NotFoundError
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
|
||||
from app.models import ScheduleRun, ScheduleTask, FreightRpaInboundUnitRun, FreightRpaOutboundUnitRun
|
||||
from app.services.schedule.query_service import get_run, list_runs, serialize_run
|
||||
from app.services.schedule.queue_service import enqueue_manual_schedule_run
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download
|
||||
from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file
|
||||
from app.services.schedule.freight_rpa_onhand_archive import resolve_inventory_raw_zip_download
|
||||
from app.services.schedule.freight_rpa_inbound_archive import resolve_inbound_raw_zip_download
|
||||
from app.services.schedule.freight_rpa_outbound_archive import resolve_outbound_raw_zip_download
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
|
||||
from app.services.freight_rpa.inbound.trigger_io import SCHEMA, write_inbound_export_batch_trigger
|
||||
from app.services.freight_rpa.outbound.trigger_io import SCHEMA as OUTBOUND_SCHEMA, write_outbound_export_batch_trigger
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
|
||||
@@ -43,7 +47,11 @@ def run_schedule(task_id: int):
|
||||
triggered_by_user_id=getattr(user, 'id', None),
|
||||
)
|
||||
if not created:
|
||||
raise ConflictError('该排程正在等待或执行中,请等待完成后再试', details={'run_id': run.id})
|
||||
raise ConflictError(
|
||||
'该排程正在等待或执行中,请等待完成后再试',
|
||||
code='SCHEDULE.RUN_ALREADY_ACTIVE',
|
||||
details={'run_id': run.id},
|
||||
)
|
||||
fresh = db.session.get(ScheduleRun, run.id)
|
||||
return jsonify(serialize_run(fresh))
|
||||
|
||||
@@ -123,31 +131,30 @@ def get_schedule_run_inventory_raw_zip(run_id: int):
|
||||
)
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/receipt-report-files/<int:file_id>/resend', methods=['POST'])
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/inbound-raw-zip', methods=['GET'])
|
||||
@require_admin
|
||||
def resend_receipt_report_file(file_id: int):
|
||||
"""管理员重发已归档的收料文件;禁止借重发重新触发 RPA 导出。"""
|
||||
report_file = db.session.get(ShippingReceiptReportFile, file_id)
|
||||
if report_file is None or report_file.archive_deleted_at is not None:
|
||||
raise NotFoundError('Receipt report file not found')
|
||||
user = get_current_user()
|
||||
outcome = deliver_receipt_file(report_file.id, force=True)
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_report_notification_resent', aggregate_type='shipping_receipt_file',
|
||||
aggregate_id=str(report_file.id), actor_type='admin', actor_id=getattr(user, 'id', None),
|
||||
owner_user_id=getattr(user, 'id', None), unit_id=report_file.unit_run_id, result='success',
|
||||
after={'status': 'resent', 'owner_user_id': getattr(user, 'id', None)},
|
||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
metadata={'success_count': int(outcome.get('success_count', 0)), 'failed_count': int(outcome.get('failed_count', 0))},
|
||||
def get_schedule_run_inbound_raw_zip(run_id: int):
|
||||
"""
|
||||
下载入站 RPA 排程 run 的原始入站 Excel 打包(ZIP + manifest)。
|
||||
|
||||
核心逻辑:对齐 inventory-raw-zip;展示名为 入站RPA-{日期}-{时刻}-入站.zip。
|
||||
"""
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
zip_path, file_name = resolve_inbound_raw_zip_download(run)
|
||||
return send_file(
|
||||
zip_path,
|
||||
as_attachment=True,
|
||||
download_name=file_name,
|
||||
mimetype='application/zip',
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify({'success': True, 'data': outcome})
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/receipt-rpa-units', methods=['GET'])
|
||||
@schedule_admin_bp.route('/inbound-rpa-units', methods=['GET'])
|
||||
@require_admin
|
||||
def list_receipt_rpa_units():
|
||||
"""管理员查看收料单元运行事实,供失败单元填写原因后人工重试。"""
|
||||
def list_inbound_rpa_units():
|
||||
"""管理员查看入站单元运行事实,供失败单元填写原因后人工重试。"""
|
||||
status = str(request.args.get('status') or '').strip().lower()
|
||||
if status and status not in {'queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled'}:
|
||||
from app.core.errors import ValidationError
|
||||
@@ -157,19 +164,19 @@ def list_receipt_rpa_units():
|
||||
except (TypeError, ValueError):
|
||||
from app.core.errors import ValidationError
|
||||
raise ValidationError('limit is invalid')
|
||||
query = ShippingReceiptRpaUnitRun.query.order_by(
|
||||
ShippingReceiptRpaUnitRun.created_at.desc(), ShippingReceiptRpaUnitRun.id.desc(),
|
||||
query = FreightRpaInboundUnitRun.query.order_by(
|
||||
FreightRpaInboundUnitRun.created_at.desc(), FreightRpaInboundUnitRun.id.desc(),
|
||||
)
|
||||
if status:
|
||||
query = query.filter(ShippingReceiptRpaUnitRun.status == status)
|
||||
query = query.filter(FreightRpaInboundUnitRun.status == status)
|
||||
units = query.limit(limit).all()
|
||||
user = get_current_user()
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_rpa_units_listed', aggregate_type='shipping_receipt_unit_collection',
|
||||
event_type='shipping_inbound_rpa_units_listed', aggregate_type='shipping_inbound_unit_collection',
|
||||
aggregate_id=str(getattr(user, 'id', 'admin')), actor_type='admin', actor_id=getattr(user, 'id', None),
|
||||
owner_user_id=getattr(user, 'id', None), result='success',
|
||||
after={'visible_count': len(units), 'status': status or None, 'limit': limit},
|
||||
metadata={'surface': 'workspace_receipt_report_files'},
|
||||
metadata={'surface': 'admin_inbound_rpa_units'},
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify({'success': True, 'data': {'items': [{
|
||||
@@ -186,34 +193,34 @@ def list_receipt_rpa_units():
|
||||
} for unit in units]}})
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/receipt-rpa-units/<int:unit_id>/retry', methods=['POST'])
|
||||
@schedule_admin_bp.route('/inbound-rpa-units/<int:unit_id>/retry', methods=['POST'])
|
||||
@require_admin
|
||||
def retry_receipt_rpa_unit(unit_id: int):
|
||||
"""管理员为失败收料单元创建独立重试事实;旧单元永不覆盖。"""
|
||||
failed = db.session.get(ShippingReceiptRpaUnitRun, unit_id)
|
||||
def retry_inbound_rpa_unit(unit_id: int):
|
||||
"""管理员为失败入站单元创建独立重试事实;旧单元永不覆盖。"""
|
||||
failed = db.session.get(FreightRpaInboundUnitRun, unit_id)
|
||||
if failed is None:
|
||||
raise NotFoundError('Receipt RPA unit not found')
|
||||
raise NotFoundError('Inbound RPA unit not found')
|
||||
if failed.status not in {'failed', 'cancelled'}:
|
||||
raise ConflictError('Only failed receipt RPA units can be retried')
|
||||
raise ConflictError('Only failed inbound RPA units can be retried')
|
||||
data = request.get_json(silent=True) or {}
|
||||
reason = str(data.get('reason') or '').strip()
|
||||
if not reason:
|
||||
from app.core.errors import ValidationError
|
||||
raise ValidationError('reason is required', code='SHIPPING.RECEIPT_RETRY_REASON_REQUIRED')
|
||||
raise ValidationError('reason is required', code='SHIPPING.INBOUND_RETRY_REASON_REQUIRED')
|
||||
user = get_current_user()
|
||||
retry = ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=failed.schedule_run_id, inventory_source_id=failed.inventory_source_id,
|
||||
retry = FreightRpaInboundUnitRun(
|
||||
schedule_run_id=failed.schedule_run_id, source_id=failed.source_id,
|
||||
retry_of_id=failed.id, source_code=failed.source_code, connector_type=failed.connector_type,
|
||||
warehouse_id=failed.warehouse_id, callback_id=f'receipt:{uuid.uuid4().hex}', status='awaiting_rpa',
|
||||
warehouse_id=failed.warehouse_id, callback_id=f'inbound:{uuid.uuid4().hex}', status='awaiting_rpa',
|
||||
config_snapshot_json=dict(failed.config_snapshot_json or {}),
|
||||
)
|
||||
db.session.add(retry)
|
||||
db.session.flush()
|
||||
source = retry.inventory_source
|
||||
source = retry.source
|
||||
profile = source.rpa_profile if source is not None else None
|
||||
if source is None or profile is None or not profile.enabled:
|
||||
db.session.rollback()
|
||||
raise ConflictError('Receipt RPA profile is unavailable')
|
||||
raise ConflictError('Inbound RPA profile is unavailable')
|
||||
snapshot = dict(retry.config_snapshot_json or {})
|
||||
trigger_unit = {
|
||||
'unit_run_id': retry.id, 'callback_id': retry.callback_id, 'source_code': retry.source_code,
|
||||
@@ -226,20 +233,153 @@ def retry_receipt_rpa_unit(unit_id: int):
|
||||
}
|
||||
retry.trigger_snapshot_json = trigger_unit
|
||||
run = retry.schedule_run
|
||||
trigger_path = write_receipt_export_batch_trigger(
|
||||
trigger_path = write_inbound_export_batch_trigger(
|
||||
f'{run.run_no}-retry-{retry.id}', [trigger_unit],
|
||||
{'schedule_run_id': run.id, 'schedule_task_id': run.schedule_task_id, 'schema_version': 'shipping_receipt_rpa.v1', 'retry_of_unit_id': failed.id},
|
||||
{'schedule_run_id': run.id, 'schedule_task_id': run.schedule_task_id, 'schema_version': SCHEMA, 'retry_of_unit_id': failed.id},
|
||||
)
|
||||
if not trigger_path:
|
||||
db.session.rollback()
|
||||
raise ConflictError('Receipt RPA trigger directory is unavailable')
|
||||
raise ConflictError('Inbound RPA trigger directory is unavailable')
|
||||
run.status = 'running'
|
||||
run.finished_at = None
|
||||
summary = dict(run.response_summary_json or {})
|
||||
summary['awaiting_receipt_rpa'] = True
|
||||
summary['awaiting_inbound_rpa'] = True
|
||||
run.response_summary_json = summary
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_rpa_unit_retried', aggregate_type='shipping_receipt_unit',
|
||||
event_type='shipping_inbound_rpa_unit_retried', aggregate_type='shipping_inbound_unit',
|
||||
aggregate_id=str(retry.id), actor_type='admin', actor_id=getattr(user, 'id', None),
|
||||
owner_user_id=getattr(user, 'id', None), unit_id=retry.id, result='success', reason=reason,
|
||||
before={'status': failed.status, 'error_code': failed.error_code},
|
||||
after={'status': retry.status, 'source_run_no': retry.callback_id, 'owner_user_id': getattr(user, 'id', None)},
|
||||
metadata={'retry_of_id': failed.id},
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify({'success': True, 'data': {'unit_id': retry.id, 'retry_of_id': failed.id, 'callback_id': retry.callback_id, 'trigger_path': trigger_path}})
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/outbound-raw-zip', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_run_outbound_raw_zip(run_id: int):
|
||||
"""
|
||||
下载出站 RPA 排程 run 的原始出站 Excel 打包(ZIP + manifest)。
|
||||
|
||||
核心逻辑:对齐 inbound-raw-zip;展示名为 出站RPA-{日期}-{时刻}-出站.zip。
|
||||
"""
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
zip_path, file_name = resolve_outbound_raw_zip_download(run)
|
||||
return send_file(
|
||||
zip_path,
|
||||
as_attachment=True,
|
||||
download_name=file_name,
|
||||
mimetype='application/zip',
|
||||
)
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/outbound-rpa-units', methods=['GET'])
|
||||
@require_admin
|
||||
def list_outbound_rpa_units():
|
||||
"""管理员查出站单元运行事实,供失败单元填写原因后人工重试。"""
|
||||
status = str(request.args.get('status') or '').strip().lower()
|
||||
if status and status not in {'queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled'}:
|
||||
from app.core.errors import ValidationError
|
||||
raise ValidationError('status is invalid')
|
||||
try:
|
||||
limit = max(1, min(int(request.args.get('limit') or 100), 200))
|
||||
except (TypeError, ValueError):
|
||||
from app.core.errors import ValidationError
|
||||
raise ValidationError('limit is invalid')
|
||||
query = FreightRpaOutboundUnitRun.query.order_by(
|
||||
FreightRpaOutboundUnitRun.created_at.desc(), FreightRpaOutboundUnitRun.id.desc(),
|
||||
)
|
||||
if status:
|
||||
query = query.filter(FreightRpaOutboundUnitRun.status == status)
|
||||
units = query.limit(limit).all()
|
||||
user = get_current_user()
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_outbound_rpa_units_listed', aggregate_type='shipping_outbound_unit_collection',
|
||||
aggregate_id=str(getattr(user, 'id', 'admin')), actor_type='admin', actor_id=getattr(user, 'id', None),
|
||||
owner_user_id=getattr(user, 'id', None), result='success',
|
||||
after={'visible_count': len(units), 'status': status or None, 'limit': limit},
|
||||
metadata={'surface': 'admin_outbound_rpa_units'},
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify({'success': True, 'data': {'items': [{
|
||||
'id': unit.id,
|
||||
'source_code': unit.source_code,
|
||||
'warehouse_id': unit.warehouse_id,
|
||||
'status': unit.status,
|
||||
'error_code': unit.error_code,
|
||||
'error_message': unit.error_message,
|
||||
'retry_of_id': unit.retry_of_id,
|
||||
'schedule_run_id': unit.schedule_run_id,
|
||||
'created_at': unit.created_at.isoformat() if unit.created_at else None,
|
||||
'finished_at': unit.finished_at.isoformat() if unit.finished_at else None,
|
||||
} for unit in units]}})
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/outbound-rpa-units/<int:unit_id>/retry', methods=['POST'])
|
||||
@require_admin
|
||||
def retry_outbound_rpa_unit(unit_id: int):
|
||||
"""管理员为失败出站单元创建独立重试事实;旧单元永不覆盖。调拨按需单元无排程 run 时仍可重试。"""
|
||||
failed = db.session.get(FreightRpaOutboundUnitRun, unit_id)
|
||||
if failed is None:
|
||||
raise NotFoundError('Outbound RPA unit not found')
|
||||
if failed.status not in {'failed', 'cancelled'}:
|
||||
raise ConflictError('Only failed outbound RPA units can be retried')
|
||||
data = request.get_json(silent=True) or {}
|
||||
reason = str(data.get('reason') or '').strip()
|
||||
if not reason:
|
||||
from app.core.errors import ValidationError
|
||||
raise ValidationError('reason is required', code='SHIPPING.OUTBOUND_RETRY_REASON_REQUIRED')
|
||||
user = get_current_user()
|
||||
retry = FreightRpaOutboundUnitRun(
|
||||
schedule_run_id=failed.schedule_run_id, source_id=failed.source_id,
|
||||
retry_of_id=failed.id, source_code=failed.source_code, connector_type=failed.connector_type,
|
||||
warehouse_id=failed.warehouse_id, callback_id=f'outbound:{uuid.uuid4().hex}', status='awaiting_rpa',
|
||||
config_snapshot_json=dict(failed.config_snapshot_json or {}),
|
||||
)
|
||||
db.session.add(retry)
|
||||
db.session.flush()
|
||||
source = retry.source
|
||||
profile = source.rpa_profile if source is not None else None
|
||||
if source is None or profile is None or not profile.enabled:
|
||||
db.session.rollback()
|
||||
raise ConflictError('Outbound RPA profile is unavailable')
|
||||
snapshot = dict(retry.config_snapshot_json or {})
|
||||
trigger_unit = {
|
||||
'unit_run_id': retry.id, 'callback_id': retry.callback_id, 'source_code': retry.source_code,
|
||||
'connector_type': retry.connector_type, 'warehouse_id': retry.warehouse_id,
|
||||
'rpa_profile_id': profile.id, 'rpa_profile_code': profile.profile_code, 'login_url': profile.login_url,
|
||||
'login_config': dict(profile.login_config_json or {}),
|
||||
'credential_envelope': {'username_ciphertext': profile.username_ciphertext, 'password_ciphertext': profile.password_ciphertext},
|
||||
'report_path_json': dict(snapshot.get('report_path_json') or {}),
|
||||
'query_parameters_json': list(snapshot.get('query_parameters_json') or []), 'config_snapshot': snapshot,
|
||||
}
|
||||
retry.trigger_snapshot_json = trigger_unit
|
||||
run = retry.schedule_run
|
||||
run_no = run.run_no if run is not None else f'outbound-retry-{retry.id}'
|
||||
trigger_meta = {
|
||||
'schema_version': OUTBOUND_SCHEMA, 'retry_of_unit_id': failed.id,
|
||||
}
|
||||
if run is not None:
|
||||
trigger_meta['schedule_run_id'] = run.id
|
||||
trigger_meta['schedule_task_id'] = run.schedule_task_id
|
||||
trigger_path = write_outbound_export_batch_trigger(
|
||||
f'{run_no}-retry-{retry.id}', [trigger_unit], trigger_meta,
|
||||
)
|
||||
if not trigger_path:
|
||||
db.session.rollback()
|
||||
raise ConflictError('Outbound RPA trigger directory is unavailable')
|
||||
if run is not None:
|
||||
run.status = 'running'
|
||||
run.finished_at = None
|
||||
summary = dict(run.response_summary_json or {})
|
||||
summary['awaiting_outbound_rpa'] = True
|
||||
run.response_summary_json = summary
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_outbound_rpa_unit_retried', aggregate_type='shipping_outbound_unit',
|
||||
aggregate_id=str(retry.id), actor_type='admin', actor_id=getattr(user, 'id', None),
|
||||
owner_user_id=getattr(user, 'id', None), unit_id=retry.id, result='success', reason=reason,
|
||||
before={'status': failed.status, 'error_code': failed.error_code},
|
||||
|
||||
@@ -1,409 +1,13 @@
|
||||
"""
|
||||
api/shipping_notice_tools.py
|
||||
backend/app/api/shipping_notice_tools.py
|
||||
|
||||
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。
|
||||
依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url、
|
||||
tool_api_url。
|
||||
逻辑:Tool 成功响应仍用 status: ok/failed 业务 envelope;HTTP 级参数/资源错误统一 raise AppError;
|
||||
`_payload()` 剥离 body 中的操作人伪造字段,禁止集成密钥冒充用户写审计;
|
||||
历史批次 Tool 已删除,订单抽取统一走 order-extraction-submissions。
|
||||
用途:兼容旧 import 路径的薄 shim(真实现已迁至 api/tools/shipping_notice.py)。
|
||||
依赖:app.api.tools.shipping_notice。
|
||||
逻辑:保留 Blueprint 与 `_payload` 等测试符号;新代码请从 app.api.tools 导入。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
from app.api.tools.shipping_notice import ( # noqa: F401
|
||||
_payload,
|
||||
shipping_notice_bp,
|
||||
)
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
|
||||
from app.services.shipping_notice.query_service import (
|
||||
EXPORT_MIME_TYPE,
|
||||
get_task_by_ref,
|
||||
resolve_task_export_download,
|
||||
serialize_task_summary,
|
||||
task_export_error_message,
|
||||
)
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import record_rpa_worker_heartbeat
|
||||
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||
|
||||
shipping_notice_bp = Blueprint("shipping_notice", __name__)
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验货代 Tool API 鉴权 Header。
|
||||
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;当 Dify、RPA 或外部系统请求本蓝图时由 before_request 自动触发。
|
||||
|
||||
核心逻辑:只接受 `Authorization: Bearer <token>` 或 `X-Integration-Key`。
|
||||
货代专用 `SHIPPING_NOTICE_TOOL_API_KEY` 优先,未配置时回退 `INTEGRATION_API_KEY`;
|
||||
未配置任何可用 key 时报服务不可用,缺失或错误时报未授权。
|
||||
"""
|
||||
configured = str(
|
||||
current_app.config.get('SHIPPING_NOTICE_TOOL_API_KEY')
|
||||
or current_app.config.get('INTEGRATION_API_KEY')
|
||||
or ''
|
||||
).strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError(
|
||||
'SHIPPING_NOTICE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured',
|
||||
code='missing_auth',
|
||||
)
|
||||
bearer = str(request.headers.get('Authorization') or '').strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith('bearer ') else ''
|
||||
integration_key = str(request.headers.get('X-Integration-Key') or '').strip()
|
||||
if configured in {token, integration_key}:
|
||||
return
|
||||
if not token and (not integration_key):
|
||||
raise UnauthorizedError('missing_auth')
|
||||
raise UnauthorizedError('invalid_auth')
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
"""统一归一化 Tool API 的错误码,保持与文件检核 Tool 返回风格一致。"""
|
||||
message = str(exc.message or '').strip()
|
||||
if message in {'missing_auth', 'invalid_auth'}:
|
||||
return message
|
||||
if exc.code == 'AUTH.UNAUTHORIZED':
|
||||
return 'invalid_auth'
|
||||
if exc.code == 'SYSTEM.SERVICE_UNAVAILABLE' and 'not configured' in message.lower():
|
||||
return 'missing_auth'
|
||||
return exc.code
|
||||
|
||||
@shipping_notice_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
"""把业务异常统一转成 Tool 侧约定的 JSON 结构。"""
|
||||
body: dict[str, object] = {'ok': False, 'error_code': _tool_error_code(exc), 'message': exc.message}
|
||||
if exc.details:
|
||||
body['details'] = exc.details
|
||||
return jsonify(body), exc.http_status
|
||||
|
||||
@shipping_notice_bp.before_request
|
||||
def _verify_tool_access():
|
||||
"""
|
||||
对货代 Tool / RPA / 导出接口做统一 Header 鉴权。
|
||||
核心逻辑:仅放行 OpenAPI 导入文档,其他请求都必须携带有效 Tool Key。
|
||||
"""
|
||||
if request.path.endswith('/openapi.json') or request.path.endswith('/openapi.dify.yaml'):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
def _tool_api_base_url() -> str:
|
||||
"""Base URL for OpenAPI servers — hxops backend, NOT Dify (8882)."""
|
||||
return resolve_tool_api_base_url()
|
||||
|
||||
def _dify_openapi_spec() -> dict:
|
||||
return build_dify_openapi_spec(_tool_api_base_url())
|
||||
|
||||
def _payload() -> dict:
|
||||
"""
|
||||
读取 Tool API JSON 请求体,并剥离不可信的操作人身份字段。
|
||||
|
||||
核心逻辑:集成密钥调用方不得通过 body 伪造 `_trusted_user_id` /
|
||||
`operator_id` / `actor_id`;真实用户身份仅允许工作台/会话层鉴权后注入。
|
||||
"""
|
||||
raw = request.get_json(silent=True) or {}
|
||||
if not isinstance(raw, dict):
|
||||
return {}
|
||||
payload = dict(raw)
|
||||
for key in ('_trusted_user_id', 'operator_id', 'actor_id'):
|
||||
payload.pop(key, None)
|
||||
return payload
|
||||
|
||||
|
||||
def _require_read_capability(payload: dict, *, scope: str, task_no: str | None = None) -> None:
|
||||
"""Chatflow 只读查询必须携带短效会话能力令牌,不能仅依赖全局集成密钥。"""
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.chat_tool_capability import require_chat_capability
|
||||
claims = require_chat_capability(token=payload.get('shipping_chat_capability_token'), scope=scope, task_no=task_no)
|
||||
db.session.add(ShippingAuditEvent(
|
||||
event_type='chatflow_tool_read', aggregate_type='chat_session', aggregate_id=str(claims['sid']),
|
||||
task_no=task_no, actor_type='chatflow', actor_id=str(claims['uid']),
|
||||
request_id=str(request.headers.get('X-Request-ID') or '')[:64] or None,
|
||||
metadata_json={'tool': scope, 'token_nonce': str(claims['nonce'])[:16], 'success': True},
|
||||
))
|
||||
|
||||
@shipping_notice_bp.route('/tools/openapi.json', methods=['GET'])
|
||||
def openapi_spec():
|
||||
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
|
||||
return jsonify(_dify_openapi_spec())
|
||||
|
||||
@shipping_notice_bp.route('/tools/openapi.dify.yaml', methods=['GET'])
|
||||
def openapi_dify_yaml():
|
||||
"""返回 Dify 导入用的 OpenAPI YAML 文档。"""
|
||||
import yaml
|
||||
body = yaml.safe_dump(_dify_openapi_spec(), allow_unicode=True, sort_keys=False)
|
||||
return current_app.response_class(body, mimetype='text/yaml; charset=utf-8')
|
||||
|
||||
@shipping_notice_bp.route('/tools/create_task', methods=['POST'])
|
||||
def tool_create_task():
|
||||
"""
|
||||
创建单个发货任务。
|
||||
【AI 触发时机】:仅供 Hxops 内部建单链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.create_task(_payload()))
|
||||
|
||||
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/create_temporary_inventory_session', methods=['POST'])
|
||||
def tool_create_temporary_inventory_session():
|
||||
"""
|
||||
创建对话上传库存候选会话。
|
||||
【AI 触发时机】:用户明确说明 .xls、.xlsx 或 .csv 附件是库存文件时,在临时库存固定分支调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.create_temporary_inventory_session(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/get_temporary_inventory_session', methods=['POST'])
|
||||
def tool_get_temporary_inventory_session():
|
||||
"""
|
||||
读取临时库存候选的脱敏分析结果。
|
||||
【AI 触发时机】:创建临时会话后,需要决定采用已有方案还是请求映射建议时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.get_temporary_inventory_session(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/submit_temporary_inventory_mapping_suggestion', methods=['POST'])
|
||||
def tool_submit_temporary_inventory_mapping_suggestion():
|
||||
"""
|
||||
保存临时库存字段映射建议。
|
||||
【AI 触发时机】:仅在临时库存 LLM 节点返回真实表头到库存字段目录的候选后调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.submit_temporary_inventory_mapping_suggestion(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/confirm_temporary_inventory_use', methods=['POST'])
|
||||
def tool_confirm_temporary_inventory_use():
|
||||
"""
|
||||
确认本次对话临时库存文件的使用。
|
||||
【AI 触发时机】:仅在用户明确确认当前文件和方案后调用,禁止模型自行确认。
|
||||
"""
|
||||
return jsonify(shipping_tools.confirm_temporary_inventory_use(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/update_notice_fields', methods=['POST'])
|
||||
def tool_update_notice_fields():
|
||||
"""
|
||||
修改发货通知单头字段。
|
||||
【AI 触发时机】:当用户明确要求更正客户、PO、收货地或交期等单头信息时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.update_notice_fields(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/update_notice_line', methods=['POST'])
|
||||
def tool_update_notice_line():
|
||||
"""
|
||||
修改指定订单行。
|
||||
【AI 触发时机】:当用户指出某一行的 SKU、数量、Reservation ID 或交期有误时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.update_notice_line(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/add_notice_line', methods=['POST'])
|
||||
def tool_add_notice_line():
|
||||
"""
|
||||
新增订单行。
|
||||
【AI 触发时机】:当用户说明漏了一行订单、需要补录发货通知明细时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.add_notice_line(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/remove_notice_line', methods=['POST'])
|
||||
def tool_remove_notice_line():
|
||||
"""
|
||||
删除订单行。
|
||||
【AI 触发时机】:当用户确认某一行是误解析、重复行或不应出货的行时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.remove_notice_line(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/ensure_inventory', methods=['POST'])
|
||||
def tool_ensure_inventory():
|
||||
"""
|
||||
保证任务已取得库存数据。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
payload = _payload()
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
return jsonify(run_task_auto_progress(
|
||||
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
|
||||
trigger='legacy_tool_ensure_inventory',
|
||||
operator_id=payload.get('operator_id'),
|
||||
resume_gate_code='inventory_preparation',
|
||||
))
|
||||
|
||||
@shipping_notice_bp.route('/tools/auto_progress', methods=['POST'])
|
||||
def tool_auto_progress():
|
||||
"""
|
||||
自动推进任务。
|
||||
【AI 触发时机】:仅供后端 orchestrator / worker 调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.auto_progress(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/match_inventory', methods=['POST'])
|
||||
def tool_match_inventory():
|
||||
"""
|
||||
执行库存匹配。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
payload = _payload()
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
return jsonify(run_task_auto_progress(
|
||||
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
|
||||
trigger='legacy_tool_match_inventory',
|
||||
operator_id=payload.get('operator_id'),
|
||||
resume_gate_code='inventory_matching',
|
||||
))
|
||||
|
||||
@shipping_notice_bp.route('/tools/confirm_customer', methods=['POST'])
|
||||
def tool_confirm_customer():
|
||||
"""
|
||||
确认任务所属标准客户(仅提交 customer_id)。
|
||||
【AI 触发时机】:用户在客户人工确认检查点选择正式客户后调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.confirm_customer(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/generate_shipment_excel', methods=['POST'])
|
||||
def tool_generate_shipment_excel():
|
||||
"""
|
||||
生成出货 Excel。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
payload = _payload()
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
return jsonify(run_task_auto_progress(
|
||||
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
|
||||
trigger='legacy_tool_generate_excel',
|
||||
operator_id=payload.get('operator_id'),
|
||||
resume_gate_code='artifact_generation',
|
||||
))
|
||||
|
||||
@shipping_notice_bp.route('/tools/upload_to_freight', methods=['POST'])
|
||||
def tool_upload_to_freight():
|
||||
"""
|
||||
上传到货代系统或确认人工上传完成。
|
||||
【AI 触发时机】:仅供后端主调度、内部恢复链路或人工上传收口调用;不是 Dify 画布正式入口。
|
||||
Agent 应优先引导用户走工作台 mark-manual-uploaded,勿在自动链中调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.upload_to_freight(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/get_task_status', methods=['POST'])
|
||||
def tool_get_task_status():
|
||||
"""
|
||||
查询任务状态。
|
||||
【AI 触发时机】:当 Agent 只拿到任务号/会话号,需要先确认当前卡点后再决定下一步时调用。
|
||||
"""
|
||||
payload = _payload()
|
||||
task_no = str(payload.get('task_id') or payload.get('task_no') or '').strip().upper()
|
||||
_require_read_capability(payload, scope='get_shipping_status', task_no=task_no or None)
|
||||
return jsonify(shipping_tools.get_task_status(payload))
|
||||
|
||||
@shipping_notice_bp.route('/rpa/heartbeat', methods=['POST'])
|
||||
def rpa_worker_heartbeat():
|
||||
"""
|
||||
RPA Worker 心跳上报。
|
||||
核心逻辑:校验 payload 后写入 Redis/内存;供触发库存 RPA 前就绪检查使用。
|
||||
"""
|
||||
payload = _payload()
|
||||
try:
|
||||
worker = record_rpa_worker_heartbeat(payload)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc))
|
||||
except ServiceUnavailableError:
|
||||
raise
|
||||
return jsonify({'status': 'ok', 'message': 'heartbeat recorded', 'data': worker})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-ready', methods=['POST'])
|
||||
def rpa_inventory_ready():
|
||||
"""RPA 回调入口:上报库存导出结果并回写任务状态。"""
|
||||
return jsonify(shipping_tools.rpa_report_inventory(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-batch-ready', methods=['POST'])
|
||||
def rpa_inventory_batch_ready():
|
||||
"""RPA 批量库存导出回调:按 Warehouse 写入库存快照。"""
|
||||
return jsonify(shipping_tools.rpa_report_inventory_batch(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/receipt-batch-ready', methods=['POST'])
|
||||
def rpa_receipt_batch_ready():
|
||||
"""收料 RPA 回调:独立归档文件,绝不进入库存回调或库存匹配链路。"""
|
||||
from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback
|
||||
|
||||
return jsonify({'success': True, 'data': ingest_receipt_callback(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-batch-claimed', methods=['POST'])
|
||||
def rpa_inventory_batch_claimed():
|
||||
"""v2 Worker 领取回调:仅记录 Attempt 执行阶段。"""
|
||||
from app.services.shipping_notice.per_source_rpa_service import claim_inventory_batch
|
||||
return jsonify({'success': True, 'data': claim_inventory_batch(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-batch-progress', methods=['POST'])
|
||||
def rpa_inventory_batch_progress():
|
||||
"""RPA 批量库存导出进度回调:实时回写排程 run 计数(非终态,最终以 batch-ready 为准)。"""
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import report_inventory_batch_progress
|
||||
return jsonify(report_inventory_batch_progress(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-configuration-test-ready', methods=['POST'])
|
||||
def rpa_inventory_configuration_test_ready():
|
||||
"""RPA 配置测试回调:仅分析文件结构,不创建生产库存快照或任务关联。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_test_export(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-configuration-test-batch-ready', methods=['POST'])
|
||||
def rpa_inventory_configuration_test_batch_ready():
|
||||
"""RPA 批量配置测试回调:按 validation_run_no 独立回写每个库存站点。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_batch_test_exports(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-configuration-test-batch-progress', methods=['POST'])
|
||||
def rpa_inventory_configuration_test_batch_progress():
|
||||
"""RPA 批量配置测试进度:Worker 领取单个站点后立即回写执行阶段。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_batch_test_progress(_payload())})
|
||||
|
||||
@shipping_notice_bp.route('/tasks/<task_no>/repair-inventory-attachment', methods=['POST'])
|
||||
def repair_task_inventory_attachment(task_no: str):
|
||||
"""
|
||||
从任务库存快照幂等重建正式附件(不重新消费 RPA callback)。
|
||||
核心逻辑:供晋升失败或 marker 异常后的人工/后台补偿。
|
||||
"""
|
||||
payload = _payload()
|
||||
payload.setdefault("task_no", task_no)
|
||||
payload.setdefault("task_id", task_no)
|
||||
return jsonify(shipping_tools.repair_task_inventory_attachment(payload))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-repair', methods=['POST'])
|
||||
def rpa_inventory_repair():
|
||||
"""受控库存回调修复:复用正式 v2 ingest 链路。"""
|
||||
payload = _payload()
|
||||
payload['repair'] = True
|
||||
return jsonify(shipping_tools.rpa_report_inventory_batch(payload))
|
||||
|
||||
@shipping_notice_bp.route('/rpa/upload-complete', methods=['POST'])
|
||||
def rpa_upload_complete():
|
||||
"""RPA 回调入口:上报货代上传结果并回写任务状态。"""
|
||||
return jsonify(shipping_tools.rpa_report_upload(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tasks/<task_no>/export', methods=['GET'])
|
||||
def download_task_export(task_no: str):
|
||||
"""下载任务已生成的出货 Excel。"""
|
||||
task = get_task_by_ref(task_no)
|
||||
err_msg = task_export_error_message(task)
|
||||
if err_msg:
|
||||
raise NotFoundError(err_msg)
|
||||
resolved = resolve_task_export_download(task)
|
||||
assert resolved is not None
|
||||
path, download_name = resolved
|
||||
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
|
||||
__all__ = ['shipping_notice_bp', '_payload']
|
||||
@@ -1,6 +1,11 @@
|
||||
"""
|
||||
Speech transcription API — forwards audio to SiliconFlow ASR.
|
||||
backend/app/api/speech/__init__.py
|
||||
|
||||
用途:语音转写 API,将音频转发至 SiliconFlow ASR。
|
||||
依赖:app.core.auth.jwt、SpeechAsrService。
|
||||
逻辑:register_blueprints 挂载 /api/speech;需登录后上传 audio/file。
|
||||
"""
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
backend/app/api/sso.py
|
||||
backend/app/api/sso/__init__.py
|
||||
|
||||
Purpose: Expose peer-service discovery, short-lived assertion issuance, and public JWKS APIs.
|
||||
Dependencies: JWT current-user resolver, SSO services, and Flask Blueprint.
|
||||
@@ -1,11 +1,20 @@
|
||||
"""
|
||||
backend/app/api/tools/__init__.py
|
||||
|
||||
用途:Dify HTTP Tool API Blueprint 聚合。
|
||||
逻辑:re-export shipping_notice、file_check、maintenance tools。
|
||||
用途:Dify / Chatflow HTTP Tool API Blueprint 聚合。
|
||||
依赖:tools 子模块(file_check、shipping_notice、maintenance、agent_runtime_context、procurement_contract)。
|
||||
逻辑:register_blueprints 只从本包导入 Tool Blueprint;真实现已收口到本目录,根路径 *_tools.py 仅为兼容 shim。
|
||||
"""
|
||||
from app.api.tools.shipping_notice import shipping_notice_bp # noqa: F401
|
||||
from app.api.tools.agent_runtime_context import agent_runtime_context_bp # noqa: F401
|
||||
from app.api.tools.file_check import file_check_bp # noqa: F401
|
||||
from app.api.tools.maintenance import maintenance_tool_bp # noqa: F401
|
||||
from app.api.tools.procurement_contract import procurement_contract_bp # noqa: F401
|
||||
from app.api.tools.shipping_notice import shipping_notice_bp # noqa: F401
|
||||
|
||||
__all__ = ['shipping_notice_bp', 'file_check_bp', 'maintenance_tool_bp']
|
||||
__all__ = [
|
||||
'agent_runtime_context_bp',
|
||||
'file_check_bp',
|
||||
'maintenance_tool_bp',
|
||||
'procurement_contract_bp',
|
||||
'shipping_notice_bp',
|
||||
]
|
||||
@@ -0,0 +1,108 @@
|
||||
"""
|
||||
backend/app/api/tools/agent_runtime_context.py
|
||||
|
||||
用途:暴露 agent_runtime_context 只读 Tool API,供 Dify Chatflow 解析 HXOPS 上下文。
|
||||
依赖:app.core.errors、agent_runtime_context.parser/openapi_spec、shipping_notice.tool_api_url。
|
||||
逻辑:register_blueprints 从 api.tools 挂载;OpenAPI 文档接口放行;parse 工具复用
|
||||
Authorization Bearer / X-Integration-Key 鉴权,不推进业务状态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request
|
||||
|
||||
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError
|
||||
from app.services.agent_runtime_context.openapi_spec import build_agent_runtime_context_openapi_spec
|
||||
from app.services.agent_runtime_context.parser import parse_agent_runtime_context
|
||||
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||
|
||||
agent_runtime_context_bp = Blueprint("agent_runtime_context_tools", __name__)
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验 agent_runtime_context Tool API 鉴权 Header。
|
||||
|
||||
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;Dify 请求 parse 工具时由 before_request 自动触发。
|
||||
|
||||
核心逻辑:只接受 Authorization Bearer 或 X-Integration-Key,复用 INTEGRATION_API_KEY 作为平台工具密钥。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 未配置 INTEGRATION_API_KEY。
|
||||
UnauthorizedError: 缺少或传入错误鉴权。
|
||||
"""
|
||||
configured = str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError("INTEGRATION_API_KEY is not configured", code="missing_auth")
|
||||
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||
if configured in {token, integration_key}:
|
||||
return
|
||||
if not token and not integration_key:
|
||||
raise UnauthorizedError("missing_auth")
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
"""
|
||||
归一化 Tool API 错误码。
|
||||
|
||||
核心逻辑:保持与 shipping/file-check Tool API 的 ok:false 响应风格一致,便于 Dify 侧统一处理。
|
||||
|
||||
Args:
|
||||
exc: 业务异常。
|
||||
|
||||
Returns:
|
||||
Tool 侧错误码。
|
||||
"""
|
||||
message = str(exc.message or "").strip()
|
||||
if message in {"missing_auth", "invalid_auth"}:
|
||||
return message
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
return "missing_auth"
|
||||
return exc.code
|
||||
|
||||
|
||||
@agent_runtime_context_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
"""把业务异常统一转成 Tool 侧约定的 JSON 结构。"""
|
||||
return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status
|
||||
|
||||
|
||||
@agent_runtime_context_bp.before_request
|
||||
def _verify_tool_access():
|
||||
"""
|
||||
对上下文解析 Tool 做统一 Header 鉴权。
|
||||
|
||||
核心逻辑:OpenAPI 导入文档无需鉴权;parse 工具必须携带平台 Tool Key。
|
||||
"""
|
||||
if request.path.endswith("/openapi.json"):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
@agent_runtime_context_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def openapi_spec():
|
||||
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
|
||||
return jsonify(build_agent_runtime_context_openapi_spec(resolve_tool_api_base_url()))
|
||||
|
||||
|
||||
@agent_runtime_context_bp.route("/tools/parse", methods=["POST"])
|
||||
def parse_context_tool():
|
||||
"""
|
||||
解析 agent_runtime_context 的白名单字段。
|
||||
|
||||
【AI 触发时机】:Dify 需要读取 HXOPS session/task/batch/run_purpose/state_hint 等上下文字段时调用;
|
||||
不用于推进业务状态。
|
||||
"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
return jsonify(
|
||||
parse_agent_runtime_context(
|
||||
payload.get("agent_runtime_context"),
|
||||
payload.get("paths"),
|
||||
)
|
||||
)
|
||||
@@ -1,8 +1,657 @@
|
||||
"""
|
||||
backend/app/api/tools/file_check.py
|
||||
|
||||
用途:文件检核 Tool API Blueprint(Wave 1 自 file_check_tools.py 迁入)。
|
||||
用途:文件检核 / 立账凭证检核 Chatflow 显式 HTTP Tool API(启动检核复用本蓝图)。
|
||||
依赖:workspace.file_check、services.file_check_tools、schedule.scheduler_service、jobs.enqueue。
|
||||
逻辑:register_blueprints 从 api.tools 挂载;发起检核时可透传顶层 mode/invoice_no(或嵌套 run_options)写入 ScheduleRun.api_request_json;实际执行入队 FILE_CHECK_RUN,由 schedule worker 执行。
|
||||
"""
|
||||
from app.api.file_check_tools import file_check_bp # noqa: F401
|
||||
from __future__ import annotations
|
||||
|
||||
__all__ = ['file_check_bp']
|
||||
import threading
|
||||
import time
|
||||
from io import BytesIO
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
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,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
)
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.file_check_tools.openapi_spec import build_file_check_openapi_spec
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE, resolve_hxops_user_facing_base_url
|
||||
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
|
||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
|
||||
|
||||
try:
|
||||
import pyodbc # type: ignore
|
||||
except Exception: # pragma: no cover
|
||||
pyodbc = None
|
||||
|
||||
|
||||
file_check_bp = Blueprint("file_check_tools", __name__)
|
||||
|
||||
_EXCEL_TOKEN_SCOPES = {"file_check_excel", "file_schedule_excel"}
|
||||
_RUN_START_LOCK = threading.Lock()
|
||||
_TASK_LOCK_KEY_BASE = 8700000000
|
||||
|
||||
|
||||
def _download_token_secret() -> str:
|
||||
"""
|
||||
Excel 下载 JWT 签名密钥。
|
||||
|
||||
核心逻辑:与 Dify Tool API Key 分离,仅用 SECRET_KEY,避免 API Key 未配置时浏览器下载失败。
|
||||
"""
|
||||
return str(current_app.config.get("SECRET_KEY") or "default-secret").strip()
|
||||
|
||||
|
||||
def _decode_download_token(token: str | None) -> dict | None:
|
||||
normalized = str(token or "").strip()
|
||||
if not normalized:
|
||||
return None
|
||||
try:
|
||||
import jwt
|
||||
|
||||
payload = jwt.decode(normalized, _download_token_secret(), algorithms=["HS256"])
|
||||
return payload if isinstance(payload, dict) else None
|
||||
except Exception as exc:
|
||||
current_app.logger.warning("[file-check-tool] download token validation failed: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验 Tool API 访问权限。
|
||||
|
||||
核心逻辑:Excel 下载仅校验 query token(浏览器场景);其余端点走共用 integration_tool_auth。
|
||||
"""
|
||||
# [STEP 1] 浏览器 Excel 下载:JWT token 独立于 Tool API Key
|
||||
if request.path.endswith("/excel"):
|
||||
query_token = str(request.args.get("token") or "").strip()
|
||||
if query_token:
|
||||
if _decode_download_token(query_token):
|
||||
return
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
# [STEP 2] Dify / RPA 服务端调用(与立账凭证检核等 Tool 共用密钥)
|
||||
from app.services.integration_tool_auth import require_integration_tool_auth
|
||||
|
||||
require_integration_tool_auth()
|
||||
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
message = str(exc.message or "").strip()
|
||||
if message in {
|
||||
"missing_auth",
|
||||
"invalid_auth",
|
||||
"task_not_found",
|
||||
"run_not_found",
|
||||
"excel_not_ready",
|
||||
"kb_sync_failed",
|
||||
"query_required",
|
||||
"kb_not_configured",
|
||||
"kb_group_not_found",
|
||||
"kb_dataset_not_bound",
|
||||
"dify_retrieve_failed",
|
||||
}:
|
||||
return message
|
||||
if exc.code == "data_source_unavailable":
|
||||
return "data_source_unavailable"
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
return "missing_auth"
|
||||
if exc.code == "RESOURCE.NOT_FOUND":
|
||||
return message or "run_not_found"
|
||||
if exc.code == "VALIDATION.INVALID_PARAM":
|
||||
return message or "invalid_request"
|
||||
if exc.code == "RESOURCE.CONFLICT":
|
||||
return message or "conflict"
|
||||
return exc.code
|
||||
|
||||
|
||||
@file_check_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
status = exc.http_status
|
||||
return jsonify({
|
||||
"ok": False,
|
||||
"error_code": _tool_error_code(exc),
|
||||
"message": exc.message,
|
||||
}), status
|
||||
|
||||
|
||||
def _public_base_url() -> str:
|
||||
"""用户可见下载链基地址;与 Dify 调 Tool API 的内网基地址分离。"""
|
||||
return resolve_hxops_user_facing_base_url()
|
||||
|
||||
|
||||
def _acquire_task_start_lock(task_id: int) -> None:
|
||||
"""按 schedule_task_id 串行化同任务启动检核(PostgreSQL advisory lock)。"""
|
||||
bind = db.session.get_bind()
|
||||
if bind.dialect.name != "postgresql":
|
||||
return
|
||||
lock_key = _TASK_LOCK_KEY_BASE + int(task_id)
|
||||
db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": lock_key})
|
||||
|
||||
|
||||
def _build_excel_download_url(run: ScheduleRun) -> str:
|
||||
import jwt
|
||||
|
||||
payload = {
|
||||
"scope": "file_check_excel",
|
||||
"run_id": run.id,
|
||||
"exp": int(time.time()) + 600,
|
||||
}
|
||||
token = jwt.encode(payload, _download_token_secret(), algorithm="HS256")
|
||||
return f"{_public_base_url()}/api/file-check/tools/runs/{run.id}/excel?token={token}"
|
||||
|
||||
|
||||
@file_check_bp.before_request
|
||||
def _verify_tool_access():
|
||||
if request.path.endswith("/openapi.json"):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
def _serialize_tool_run(run: ScheduleRun) -> dict:
|
||||
payload = serialize_run(run)
|
||||
return {
|
||||
"run_id": payload["id"],
|
||||
"run_no": payload["run_no"],
|
||||
"task_id": payload["schedule_task_id"],
|
||||
"task_name": payload.get("schedule_name"),
|
||||
"status": payload["status"],
|
||||
"total_count": payload["total_count"],
|
||||
"success_count": payload["success_count"],
|
||||
"failed_count": payload["failed_count"],
|
||||
"skipped_count": payload["skipped_count"],
|
||||
"judgement": serialize_file_judgement(payload),
|
||||
"started_at": payload.get("started_at"),
|
||||
"finished_at": payload.get("finished_at"),
|
||||
"duration_ms": payload.get("duration_ms"),
|
||||
"error_message": payload.get("error_message"),
|
||||
"excel": {
|
||||
"file_name": payload.get("excel_file_name"),
|
||||
"file_size": payload.get("excel_file_size"),
|
||||
"download_url": _build_excel_download_url(run) if payload.get("excel_file_name") else None,
|
||||
},
|
||||
"knowledge_base": {
|
||||
"enabled": bool(getattr(run.task, "kb_sync_enabled", False)) if run.task else bool(payload.get("kb_group_id")),
|
||||
"sync_status": payload.get("kb_sync_status"),
|
||||
"group_id": payload.get("kb_group_id"),
|
||||
"document_id": payload.get("kb_document_id"),
|
||||
"document_version_id": payload.get("kb_document_version_id"),
|
||||
"sync_job_id": payload.get("kb_sync_job_id"),
|
||||
"error_message": payload.get("kb_sync_error"),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _resolve_check_task(data: dict | None = None, *, task_id: int | None = None) -> ScheduleTask:
|
||||
data = data or {}
|
||||
raw_task_id = task_id if task_id is not None else data.get("task_id")
|
||||
if raw_task_id in (None, "", 0, "0") and not str(data.get("task_no") or "").strip():
|
||||
raise ValidationError("task_id_required")
|
||||
try:
|
||||
normalized_task_id = int(raw_task_id) if raw_task_id not in (None, "", 0, "0") else None
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError("task_id_invalid")
|
||||
task = db.session.get(ScheduleTask, normalized_task_id) if normalized_task_id is not None else None
|
||||
if not task:
|
||||
task_no = str(data.get("task_no") or "").strip()
|
||||
if task_no:
|
||||
task = ScheduleTask.query.filter_by(schedule_no=task_no).first()
|
||||
if not task:
|
||||
raise NotFoundError("task_not_found")
|
||||
return task
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/tasks", methods=["GET"])
|
||||
def list_file_check_tasks():
|
||||
"""
|
||||
查询指定检核任务摘要;须传 task_id(Agent 绑定的 schedule_task_id),不再返回全量任务列表。
|
||||
"""
|
||||
raw_task_id = request.args.get("task_id", type=int)
|
||||
if raw_task_id is None:
|
||||
raise ValidationError("task_id_required")
|
||||
task = _resolve_check_task(task_id=raw_task_id)
|
||||
latest = (
|
||||
ScheduleRun.query.filter_by(schedule_task_id=task.id)
|
||||
.order_by(ScheduleRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
tasks = [{
|
||||
"task_id": task.id,
|
||||
"task_no": task.schedule_no,
|
||||
"name": task.name,
|
||||
"enabled": bool(task.enabled),
|
||||
"last_status": latest.status if latest else None,
|
||||
"last_run_at": task.last_run_at.isoformat() if task.last_run_at else None,
|
||||
"next_run_at": task.next_run_at.isoformat() if task.next_run_at else None,
|
||||
}]
|
||||
return jsonify({"ok": True, "tasks": tasks})
|
||||
|
||||
|
||||
def _normalize_bind_payload(data: dict | None) -> dict:
|
||||
"""规范化启动检核 Body;兼容 Chatflow 漏传 hxops_session_id。"""
|
||||
payload = dict(data or {})
|
||||
session_id = str(payload.get("hxops_session_id") or "").strip()
|
||||
if session_id:
|
||||
return payload
|
||||
conversation_id = str(payload.get("conversation_id") or "").strip()
|
||||
if not conversation_id:
|
||||
return payload
|
||||
from app.models import ChatSession
|
||||
|
||||
session = ChatSession.query.filter_by(session_id=conversation_id).first()
|
||||
if session:
|
||||
payload["hxops_session_id"] = conversation_id
|
||||
return payload
|
||||
|
||||
|
||||
def _prepare_bind_payload(data: dict | None) -> dict:
|
||||
from app.services.file_check_tools.chat_turn_registry import infer_bind_context_for_run_request
|
||||
|
||||
payload = _normalize_bind_payload(data)
|
||||
inferred = infer_bind_context_for_run_request(payload)
|
||||
if inferred:
|
||||
payload = {**payload, **inferred}
|
||||
return payload
|
||||
|
||||
|
||||
def _record_run_bind(run: ScheduleRun, data: dict) -> None:
|
||||
from app.services.file_check_tools.chat_log_run_binding import merge_chat_log_bind_context
|
||||
from app.services.file_check_tools.chat_tool_run_binding import (
|
||||
_has_ambiguous_pending_turns,
|
||||
bind_schedule_run,
|
||||
)
|
||||
from app.services.file_check_tools.chat_turn_registry import attach_run_to_turn
|
||||
|
||||
turn_id = str(data.get("hxops_turn_id") or "").strip()
|
||||
session_id = str(data.get("hxops_session_id") or "").strip() or None
|
||||
user_message = str(data.get("user_message") or "").strip() or None
|
||||
bound = bind_schedule_run(
|
||||
schedule_run_id=int(run.id),
|
||||
turn_id=turn_id or None,
|
||||
session_id=session_id,
|
||||
user_message=user_message,
|
||||
schedule_task_id=int(run.schedule_task_id) if run.schedule_task_id else None,
|
||||
bind_source='tool_start',
|
||||
)
|
||||
ambiguous = _has_ambiguous_pending_turns(
|
||||
session_id=session_id,
|
||||
user_message=user_message,
|
||||
schedule_task_id=int(run.schedule_task_id) if run.schedule_task_id else None,
|
||||
)
|
||||
if bound or (not ambiguous and (turn_id or session_id)):
|
||||
merge_chat_log_bind_context(run, data)
|
||||
if bound and turn_id:
|
||||
attach_run_to_turn(turn_id, int(run.id))
|
||||
|
||||
|
||||
def _bind_queried_run_to_turn(run: ScheduleRun, data: dict) -> None:
|
||||
"""
|
||||
将已有检核批次关联到本轮查询对话,不改写批次原始执行上下文。
|
||||
|
||||
查询最近批次时触发;仅更新 chat_tool_runs 与内存 turn registry,
|
||||
使 message_end 可以把既有 ScheduleRun.id 写入当前 ChatLog.run_id。
|
||||
"""
|
||||
from app.services.file_check_tools.chat_tool_run_binding import bind_schedule_run
|
||||
from app.services.file_check_tools.chat_turn_registry import attach_run_to_turn
|
||||
|
||||
turn_id = str(data.get("hxops_turn_id") or "").strip()
|
||||
session_id = str(data.get("conversation_id") or "").strip() or None
|
||||
user_message = str(data.get("user_message") or "").strip() or None
|
||||
if not turn_id:
|
||||
return
|
||||
|
||||
bound = bind_schedule_run(
|
||||
schedule_run_id=int(run.id),
|
||||
turn_id=turn_id,
|
||||
session_id=session_id,
|
||||
user_message=user_message,
|
||||
schedule_task_id=int(run.schedule_task_id),
|
||||
bind_source="tool_query_latest",
|
||||
)
|
||||
if bound:
|
||||
attach_run_to_turn(turn_id, int(run.id))
|
||||
|
||||
|
||||
def _build_no_data_response(task: ScheduleTask, run: ScheduleRun) -> dict:
|
||||
"""
|
||||
组装无待检资料的 Tool 响应,并返回本轮已完成的空批次。
|
||||
|
||||
【AI 触发时机】:用户要求立即执行文件检核,但预检未发现待检资料时调用。
|
||||
核心逻辑:保留 no_data_to_check 供 Chatflow 回复无资料提示,同时携带已绑定的 Run,
|
||||
使前端能在该轮消息下展示总数 0、进度 100% 的完成进度卡。
|
||||
|
||||
Args:
|
||||
task: 当前检核任务。
|
||||
run: 已持久化并绑定当前对话的成功空批次。
|
||||
|
||||
Returns:
|
||||
dict: 包含 no_data_to_check、任务信息和 Run 摘要的 HTTP 200 响应体。
|
||||
"""
|
||||
return {
|
||||
"ok": False,
|
||||
"error_code": "no_data_to_check",
|
||||
"message": "目前没有资料需要检核",
|
||||
"run": _serialize_tool_run(run),
|
||||
"task": {
|
||||
"task_id": task.id,
|
||||
"task_name": task.name,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _raise_data_source_unavailable(task: ScheduleTask, exc: Exception) -> None:
|
||||
"""
|
||||
将检核预检阶段的数据源连接/配置错误转为 Tool API 503。
|
||||
|
||||
核心逻辑:ODBC/SQL Server 不可用时返回 data_source_unavailable,避免 Dify 收到 500 后显示 maximum retries。
|
||||
"""
|
||||
current_app.logger.warning(
|
||||
"[file-check-tool] precheck data source unavailable task_id=%s error=%s",
|
||||
task.id,
|
||||
exc,
|
||||
exc_info=True,
|
||||
)
|
||||
raise ServiceUnavailableError(
|
||||
"检核数据源不可用,请检查排程 SQL 配置、SRM_SQLSERVER_* 环境变量及本机 ODBC 驱动",
|
||||
code="data_source_unavailable",
|
||||
) from exc
|
||||
|
||||
|
||||
def _precheck_no_data(task: ScheduleTask) -> dict | None:
|
||||
"""
|
||||
启动前预检当前任务是否存在待检资料。
|
||||
|
||||
核心逻辑:仅在数据库型检核任务上做轻量预检;若结果为空,则返回 no_data_to_check 标识,
|
||||
由启动入口创建并绑定完成态的 0 笔 Run。数据源连接失败时抛 503 data_source_unavailable。
|
||||
"""
|
||||
if str(getattr(task, "data_source_type", "") or "database").lower() != "database":
|
||||
return None
|
||||
|
||||
cfg = get_schedule_sql_config_by_task_id(task.id)
|
||||
if not cfg or not str(cfg.fetch_sql or "").strip():
|
||||
return None
|
||||
|
||||
try:
|
||||
if cfg.data_source and not cfg.data_source.is_empty():
|
||||
conn_str = cfg.data_source.build_connection_string()
|
||||
else:
|
||||
conn_str = _build_srm_conn_str()
|
||||
rows = _fetch_records(conn_str, cfg.fetch_sql)
|
||||
except RuntimeError as exc:
|
||||
_raise_data_source_unavailable(task, exc)
|
||||
except Exception as exc:
|
||||
if pyodbc is not None and isinstance(exc, pyodbc.Error):
|
||||
_raise_data_source_unavailable(task, exc)
|
||||
raise
|
||||
|
||||
if rows:
|
||||
return None
|
||||
return {
|
||||
"ok": False,
|
||||
"error_code": "no_data_to_check",
|
||||
"message": "目前没有资料需要检核",
|
||||
}
|
||||
|
||||
|
||||
def _create_no_data_run(task: ScheduleTask, data: dict) -> ScheduleRun:
|
||||
"""
|
||||
为预检为空的立即执行请求创建并绑定已完成的 0 笔检核批次。
|
||||
|
||||
【AI 触发时机】:run_file_check 收到 no_data_to_check 预检结果时调用。
|
||||
核心逻辑:不启动后台 worker,仅写入 success Run 与对话绑定;完成态空批次由工作区进度接口
|
||||
序列化为 100%,让用户明确知道本次检核已经结束且没有待处理资料。
|
||||
|
||||
Args:
|
||||
task: 已解析的文件检核任务。
|
||||
data: Tool 请求及对话绑定上下文。
|
||||
|
||||
Returns:
|
||||
ScheduleRun: 已提交且已绑定当前对话的成功空批次。
|
||||
"""
|
||||
finished_at = datetime.utcnow()
|
||||
run = ScheduleRun(
|
||||
run_no=_generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
trigger_type="dify_chatflow",
|
||||
started_at=finished_at,
|
||||
finished_at=finished_at,
|
||||
duration_ms=0,
|
||||
status="success",
|
||||
total_count=0,
|
||||
success_count=0,
|
||||
failed_count=0,
|
||||
skipped_count=0,
|
||||
api_request_json={
|
||||
"trigger_source": data.get("trigger_source") or "dify_chatflow",
|
||||
"conversation_id": data.get("conversation_id"),
|
||||
},
|
||||
response_summary_json={"errors": [], "no_data": True},
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
_record_run_bind(run, data)
|
||||
db.session.commit()
|
||||
return run
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/tasks/run", methods=["POST"])
|
||||
def run_file_check():
|
||||
"""
|
||||
立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。
|
||||
|
||||
核心逻辑:解析 task → 防并发锁 → 可选透传 mode/invoice_no(或 run_options)到
|
||||
ScheduleRun.api_request_json → 异步启动平台 Job。Dify 推荐填顶层 mode/invoice_no。
|
||||
|
||||
Body 关键字段(立账凭证检核):
|
||||
mode: incremental | force_all | single
|
||||
invoice_no: mode=single 时发票号
|
||||
run_options: 可选嵌套对象,与顶层字段合并(顶层优先)
|
||||
"""
|
||||
perf_started = time.perf_counter()
|
||||
data = _prepare_bind_payload(request.get_json(silent=True) or {})
|
||||
task = _resolve_check_task(data)
|
||||
resolve_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
|
||||
lock_started = time.perf_counter()
|
||||
with _RUN_START_LOCK:
|
||||
_acquire_task_start_lock(task.id)
|
||||
existing = (
|
||||
ScheduleRun.query.filter_by(schedule_task_id=task.id, status="running")
|
||||
.order_by(ScheduleRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
if existing:
|
||||
_record_run_bind(existing, data)
|
||||
db.session.commit()
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
current_app.logger.info(
|
||||
"[file-check-tool-perf] run_file_check outcome=check_running resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
existing.id,
|
||||
)
|
||||
return jsonify({
|
||||
"ok": False,
|
||||
"error_code": "check_running",
|
||||
"message": "该检核任务正在执行中,请稍后查询结果",
|
||||
"run": _serialize_tool_run(existing),
|
||||
})
|
||||
|
||||
no_data_response = _precheck_no_data(task)
|
||||
if no_data_response:
|
||||
run = _create_no_data_run(task, data)
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
current_app.logger.info(
|
||||
"[file-check-tool-perf] run_file_check outcome=no_data resolve_ms=%s lock_ms=%s total_ms=%s task_id=%s run_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
task.id,
|
||||
run.id,
|
||||
)
|
||||
return jsonify(_build_no_data_response(task, run))
|
||||
|
||||
# [STEP] 解析运行选项:优先顶层 mode/invoice_no(Dify Tool 表单对嵌套 object 常不展示),
|
||||
# 再与 run_options 对象合并;立账凭证检核读取,普通文件检核忽略。
|
||||
raw_options = data.get("run_options") if isinstance(data.get("run_options"), dict) else {}
|
||||
run_options = {}
|
||||
mode = str(data.get("mode") or raw_options.get("mode") or "").strip().lower()
|
||||
if mode in {"incremental", "force_all", "single"}:
|
||||
run_options["mode"] = mode
|
||||
invoice_no = data.get("invoice_no")
|
||||
if invoice_no is None or not str(invoice_no).strip():
|
||||
invoice_no = raw_options.get("invoice_no")
|
||||
if invoice_no is not None and str(invoice_no).strip():
|
||||
run_options["invoice_no"] = str(invoice_no).strip()
|
||||
|
||||
api_request_json = {
|
||||
"trigger_source": data.get("trigger_source") or "dify_chatflow",
|
||||
"conversation_id": data.get("conversation_id"),
|
||||
}
|
||||
if run_options:
|
||||
api_request_json["run_options"] = run_options
|
||||
|
||||
run = ScheduleRun(
|
||||
run_no=_generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
trigger_type="dify_chatflow",
|
||||
started_at=datetime.utcnow(),
|
||||
status="running",
|
||||
api_request_json=api_request_json,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
_record_run_bind(run, data)
|
||||
db.session.commit()
|
||||
run_id = run.id
|
||||
task_id = task.id
|
||||
|
||||
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)
|
||||
current_app.logger.info(
|
||||
"[file-check-tool-perf] run_file_check outcome=started resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
run_id,
|
||||
)
|
||||
return jsonify({"ok": True, "message": "检核已启动", "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/runs/<int:run_id>", methods=["GET"])
|
||||
def get_file_check_run(run_id: int):
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/runs", methods=["GET"])
|
||||
def list_file_check_runs():
|
||||
raw_task_id = request.args.get("task_id", type=int)
|
||||
raw_limit = request.args.get("limit", default=20, type=int)
|
||||
limit = max(1, min(int(raw_limit or 20), 100))
|
||||
if raw_task_id is not None:
|
||||
task = _resolve_check_task(task_id=raw_task_id)
|
||||
query = ScheduleRun.query.filter_by(schedule_task_id=task.id)
|
||||
else:
|
||||
query = ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
|
||||
rows = query.order_by(ScheduleRun.created_at.desc()).limit(limit).all()
|
||||
runs = [_serialize_tool_run(row) for row in rows]
|
||||
return jsonify({"ok": True, "runs": runs, "count": len(runs)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/runs/<int:run_id>/excel", methods=["GET"])
|
||||
def download_file_check_run_excel(run_id: int):
|
||||
token_payload = _decode_download_token(request.args.get("token"))
|
||||
if token_payload:
|
||||
if token_payload.get("scope") not in _EXCEL_TOKEN_SCOPES or int(token_payload.get("run_id") or 0) != run_id:
|
||||
raise UnauthorizedError("Unauthorized")
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
if not run.excel_file_data:
|
||||
raise ConflictError("excel_not_ready")
|
||||
filename = run.excel_file_name or f"{run.run_no}.xlsx"
|
||||
return send_file(
|
||||
BytesIO(run.excel_file_data),
|
||||
as_attachment=True,
|
||||
download_name=filename,
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/tasks/<int:task_id>/latest-run", methods=["GET"])
|
||||
def get_latest_file_check_run(task_id: int):
|
||||
"""查询任务最近批次;可绑定本轮对话以展示该批次进度。"""
|
||||
task = _resolve_check_task(task_id=task_id)
|
||||
run = ScheduleRun.query.filter_by(schedule_task_id=task.id).order_by(ScheduleRun.id.desc()).first()
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
_bind_queried_run_to_turn(run, {
|
||||
"hxops_turn_id": request.args.get("hxops_turn_id"),
|
||||
"conversation_id": request.args.get("conversation_id"),
|
||||
"user_message": request.args.get("user_message"),
|
||||
})
|
||||
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/history/search", methods=["POST"])
|
||||
def search_file_check_history():
|
||||
"""
|
||||
检索已入库的历史检核报告片段;按 task_id 解析 ScheduleTask → KbGroup → Dify Dataset。
|
||||
|
||||
核心逻辑:Chatflow history_report_query 分支调用;task_id 来自 HXOPS 注入的 Start 变量。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
raw_task_id = data.get("task_id")
|
||||
try:
|
||||
task_id = int(raw_task_id)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError("task_id_invalid")
|
||||
if task_id <= 0:
|
||||
raise ValidationError("task_id_invalid")
|
||||
|
||||
from app.services.file_check_tools.history_search_service import search_file_check_history as run_history_search
|
||||
|
||||
result = run_history_search(
|
||||
task_id=task_id,
|
||||
query=str(data.get("query") or ""),
|
||||
top_k=data.get("top_k"),
|
||||
score_threshold=data.get("score_threshold"),
|
||||
)
|
||||
return jsonify({"ok": True, **result})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def file_check_openapi_spec():
|
||||
return jsonify(build_file_check_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
|
||||
@@ -1,9 +1,150 @@
|
||||
"""
|
||||
backend/app/api/tools/maintenance.py
|
||||
|
||||
用途:设备维保 Tool API Blueprint re-export。
|
||||
依赖:app.api.maintenance_tools。
|
||||
逻辑:保持 api.tools 分包统一入口,register_blueprints 只从 app.api.tools 导入各 Tool Blueprint。
|
||||
用途:设备维保助手 Dify Tool API,只开放只读查询工具。
|
||||
依赖:maintenance_chat_service、maintenance_record_service、OpenAPI 构建、Tool API 基地址解析。
|
||||
逻辑:register_blueprints 从 api.tools 挂载;Dify 复杂问法调用本蓝图查询设备台账/维修记录;
|
||||
明确查询仍由 chat 本地直答,写操作仍走 HXOPS 管理面板。
|
||||
"""
|
||||
|
||||
from app.api.maintenance_tools import maintenance_tool_bp # noqa: F401
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError, ValidationError
|
||||
from app.models import MaintenanceRecord
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
|
||||
from app.services.maintenance_chat_service import build_device_query_result
|
||||
from app.services.maintenance_record_service import serialize_record
|
||||
from app.services.maintenance_tools.openapi_spec import build_maintenance_openapi_spec
|
||||
|
||||
maintenance_tool_bp = Blueprint("maintenance_tools", __name__)
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验设备维保 Tool API 鉴权。
|
||||
AI 触发时机:Dify Tool 调用本蓝图时由 before_request 自动执行,不是给 LLM 直接调用的业务工具。
|
||||
"""
|
||||
configured = str(
|
||||
current_app.config.get("MAINTENANCE_TOOL_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
or ""
|
||||
).strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError(
|
||||
"MAINTENANCE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured",
|
||||
code="missing_auth",
|
||||
)
|
||||
|
||||
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||
if configured in {token, integration_key}:
|
||||
return
|
||||
if not token and not integration_key:
|
||||
raise UnauthorizedError("missing_auth")
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
"""把 AppError 归一成 Dify Tool 侧可读错误码。"""
|
||||
message = str(exc.message or "").strip()
|
||||
if message in {"missing_auth", "invalid_auth"}:
|
||||
return message
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
return "missing_auth"
|
||||
if exc.code == "VALIDATION.INVALID_PARAM":
|
||||
return message or "invalid_request"
|
||||
return exc.code
|
||||
|
||||
|
||||
@maintenance_tool_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
"""Tool API 统一错误响应。"""
|
||||
return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status
|
||||
|
||||
|
||||
@maintenance_tool_bp.before_request
|
||||
def _verify_tool_access():
|
||||
"""除 OpenAPI 文档外,所有 Tool 调用必须携带有效服务级 token。"""
|
||||
if request.path.endswith("/openapi.json") or request.path.endswith("/openapi.dify.yaml"):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
def _payload() -> dict:
|
||||
"""读取 JSON 请求体。"""
|
||||
return request.get_json(silent=True) or {}
|
||||
|
||||
|
||||
def _clean_text(value) -> str:
|
||||
return str(value or "").strip()
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def openapi_spec():
|
||||
"""返回 Dify 导入用的 OpenAPI JSON。"""
|
||||
return jsonify(build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/openapi.dify.yaml", methods=["GET"])
|
||||
def openapi_dify_yaml():
|
||||
"""返回 Dify 导入用的 OpenAPI YAML。"""
|
||||
import yaml
|
||||
|
||||
body = yaml.safe_dump(
|
||||
build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()),
|
||||
allow_unicode=True,
|
||||
sort_keys=False,
|
||||
)
|
||||
return current_app.response_class(body, mimetype="text/yaml; charset=utf-8")
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/query_device", methods=["POST"])
|
||||
def query_device():
|
||||
"""按设备编号或名称查询设备台账,并可带出最近维修记录。"""
|
||||
data = _payload()
|
||||
keyword = _clean_text(data.get("keyword"))
|
||||
if not keyword:
|
||||
raise ValidationError("keyword is required")
|
||||
include_records = bool(data.get("include_records", True))
|
||||
record_limit = max(0, min(20, int(data.get("record_limit") or 5)))
|
||||
result = build_device_query_result(keyword, include_records=include_records, record_limit=record_limit)
|
||||
return jsonify({"ok": True, **result})
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/query_records", methods=["POST"])
|
||||
def query_records():
|
||||
"""按设备编号/名称和状态查询维修记录。"""
|
||||
data = _payload()
|
||||
keyword = _clean_text(data.get("keyword"))
|
||||
if not keyword:
|
||||
raise ValidationError("keyword is required")
|
||||
status = _clean_text(data.get("status"))
|
||||
limit = max(1, min(50, int(data.get("limit") or 10)))
|
||||
|
||||
query = db.session.query(MaintenanceRecord)
|
||||
like = f"%{keyword}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
MaintenanceRecord.device_code.ilike(like),
|
||||
MaintenanceRecord.device_name.ilike(like),
|
||||
)
|
||||
)
|
||||
if status:
|
||||
query = query.filter(MaintenanceRecord.repair_status == status)
|
||||
rows = query.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc()).limit(limit).all()
|
||||
return jsonify({
|
||||
"ok": True,
|
||||
"matched": bool(rows),
|
||||
"keyword": keyword,
|
||||
"items": [serialize_record(item) for item in rows],
|
||||
"totalReturned": len(rows),
|
||||
})
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
"""
|
||||
backend/app/api/tools/procurement_contract.py
|
||||
|
||||
用途:采购合同审核面向 Chat/Tool 的 HTTP API。
|
||||
依赖:procurement_contract services、JWT 当前用户、统一 response envelope。
|
||||
逻辑:register_blueprints 从 api.tools 挂载;已登录用户可上传对照文件、发起审核、查本人历史并下载本人报告。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
|
||||
from flask import Blueprint, g, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.procurement_contract import review_service, template_service
|
||||
|
||||
procurement_contract_bp = Blueprint("procurement_contract", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""Return current authenticated user."""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _optional_int(value, field: str) -> int | None:
|
||||
"""Parse optional int payload fields with a ValidationError on bad input."""
|
||||
if value in (None, ""):
|
||||
return None
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(f"{field} must be integer") from exc
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/templates", methods=["GET"])
|
||||
def list_enabled_templates():
|
||||
"""List enabled templates for chat dropdown."""
|
||||
_require_user()
|
||||
return ok(template_service.list_enabled_for_chat(), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews", methods=["POST"])
|
||||
def start_contract_review():
|
||||
"""Start a review; compare mode requires a user-uploaded original contract baseline."""
|
||||
user = _require_user()
|
||||
data = request.get_json() or {}
|
||||
contract_asset_no = (data.get("contract_asset_no") or "").strip()
|
||||
if not contract_asset_no:
|
||||
raise ValidationError("contract_asset_no is required")
|
||||
result = review_service.start_review(
|
||||
user_id=user.id,
|
||||
review_mode=str(data.get("review_mode") or "compare"),
|
||||
contract_asset_no=contract_asset_no,
|
||||
original_contract_asset_no=(data.get("original_contract_asset_no") or None),
|
||||
contract_type=(data.get("contract_type") or None),
|
||||
supplier_name=(data.get("supplier_name") or None),
|
||||
agent_id=_optional_int(data.get("agent_id"), "agent_id"),
|
||||
chat_log_id=_optional_int(data.get("chat_log_id"), "chat_log_id"),
|
||||
)
|
||||
return ok(result, request_id=getattr(g, "request_id", None), status=202)
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews/<review_no>", methods=["GET"])
|
||||
def get_contract_review(review_no: str):
|
||||
"""Get a current user's review by review number."""
|
||||
user = _require_user()
|
||||
return ok(review_service.get_review_for_owner(review_no=review_no, user_id=user.id), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews/<review_no>/report", methods=["GET"])
|
||||
def download_my_contract_review_report(review_no: str):
|
||||
"""Download current user's review report as txt or docx."""
|
||||
user = _require_user()
|
||||
review_service.get_review_for_owner(review_no=review_no, user_id=user.id)
|
||||
if (request.args.get("format") or "").lower() == "docx":
|
||||
name, data, mimetype = review_service.read_review_report_docx_bytes(review_no=review_no)
|
||||
else:
|
||||
name, data = review_service.read_review_report_bytes(review_no=review_no)
|
||||
mimetype = "text/plain; charset=utf-8"
|
||||
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=name)
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews/<review_no>/annotated-contract", methods=["GET"])
|
||||
def download_my_annotated_contract(review_no: str):
|
||||
"""Download current user's original PDF with anchored risk highlights."""
|
||||
user = _require_user()
|
||||
review_service.get_review_for_owner(review_no=review_no, user_id=user.id)
|
||||
name, data, mimetype = review_service.read_review_annotated_contract_bytes(review_no=review_no)
|
||||
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=name)
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews", methods=["GET"])
|
||||
def list_my_contract_reviews():
|
||||
"""List current user's recent procurement contract reviews."""
|
||||
user = _require_user()
|
||||
data = review_service.list_reviews(
|
||||
user_id=user.id,
|
||||
review_mode=request.args.get("review_mode") or None,
|
||||
status=request.args.get("status") or None,
|
||||
keyword=request.args.get("keyword") or None,
|
||||
risk_level=request.args.get("risk_level") or None,
|
||||
limit=_optional_int(request.args.get("limit"), "limit") or 20,
|
||||
offset=_optional_int(request.args.get("offset"), "offset") or 0,
|
||||
)
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
@@ -1,8 +1,293 @@
|
||||
"""
|
||||
backend/app/api/tools/shipping_notice.py
|
||||
|
||||
用途:出货通知 Tool API Blueprint(Wave 1 自 shipping_notice_tools.py 迁入)。
|
||||
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent 与导出下载入口调用。
|
||||
依赖:app.core.errors、app.core.tool_auth、shipping_notice.tools、query_service、openapi_spec、tool_api_url。
|
||||
逻辑:register_blueprints 从 api.tools 挂载;Tool 成功响应仍用 status: ok/failed 业务 envelope;
|
||||
HTTP 级参数/资源错误统一 raise AppError;`_payload()` 剥离 body 中的操作人伪造字段;
|
||||
RPA 回调已整体迁出至 api/freight_rpa.py(/api/freight-rpa/*,无双路由);
|
||||
历史批次 Tool 已删除,订单抽取统一走 order-extraction-submissions。
|
||||
"""
|
||||
from app.api.shipping_notice_tools import shipping_notice_bp # noqa: F401
|
||||
from __future__ import annotations
|
||||
|
||||
__all__ = ['shipping_notice_bp']
|
||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
NotFoundError,
|
||||
)
|
||||
from app.core.tool_auth import require_tool_auth
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
|
||||
from app.services.shipping_notice.query_service import (
|
||||
EXPORT_MIME_TYPE,
|
||||
get_task_by_ref,
|
||||
resolve_task_export_download,
|
||||
serialize_task_summary,
|
||||
task_export_error_message,
|
||||
)
|
||||
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||
|
||||
shipping_notice_bp = Blueprint("shipping_notice", __name__)
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
"""统一归一化 Tool API 的错误码,保持与文件检核 Tool 返回风格一致。"""
|
||||
message = str(exc.message or '').strip()
|
||||
if message in {'missing_auth', 'invalid_auth'}:
|
||||
return message
|
||||
if exc.code == 'AUTH.UNAUTHORIZED':
|
||||
return 'invalid_auth'
|
||||
if exc.code == 'SYSTEM.SERVICE_UNAVAILABLE' and 'not configured' in message.lower():
|
||||
return 'missing_auth'
|
||||
return exc.code
|
||||
|
||||
@shipping_notice_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
"""把业务异常统一转成 Tool 侧约定的 JSON 结构。"""
|
||||
body: dict[str, object] = {'ok': False, 'error_code': _tool_error_code(exc), 'message': exc.message}
|
||||
if exc.details:
|
||||
body['details'] = exc.details
|
||||
return jsonify(body), exc.http_status
|
||||
|
||||
@shipping_notice_bp.before_request
|
||||
def _verify_tool_access():
|
||||
"""
|
||||
对货代 Tool / 导出接口做统一 Header 鉴权。
|
||||
核心逻辑:仅放行 OpenAPI 导入文档,其他请求都必须携带有效 Tool Key
|
||||
(鉴权实现见 app.core.tool_auth.require_tool_auth,与 freight-rpa 回调蓝图共用)。
|
||||
"""
|
||||
if request.path.endswith('/openapi.json') or request.path.endswith('/openapi.dify.yaml'):
|
||||
return None
|
||||
require_tool_auth()
|
||||
return None
|
||||
|
||||
def _tool_api_base_url() -> str:
|
||||
"""Base URL for OpenAPI servers — hxops backend, NOT Dify (8882)."""
|
||||
return resolve_tool_api_base_url()
|
||||
|
||||
def _dify_openapi_spec() -> dict:
|
||||
return build_dify_openapi_spec(_tool_api_base_url())
|
||||
|
||||
def _payload() -> dict:
|
||||
"""
|
||||
读取 Tool API JSON 请求体,并剥离不可信的操作人身份字段。
|
||||
|
||||
核心逻辑:集成密钥调用方不得通过 body 伪造 `_trusted_user_id` /
|
||||
`operator_id` / `actor_id`;真实用户身份仅允许工作台/会话层鉴权后注入。
|
||||
"""
|
||||
raw = request.get_json(silent=True) or {}
|
||||
if not isinstance(raw, dict):
|
||||
return {}
|
||||
payload = dict(raw)
|
||||
for key in ('_trusted_user_id', 'operator_id', 'actor_id'):
|
||||
payload.pop(key, None)
|
||||
return payload
|
||||
|
||||
|
||||
def _require_read_capability(payload: dict, *, scope: str, task_no: str | None = None) -> None:
|
||||
"""Chatflow 只读查询必须携带短效会话能力令牌,不能仅依赖全局集成密钥。"""
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.chat_tool_capability import require_chat_capability
|
||||
claims = require_chat_capability(token=payload.get('shipping_chat_capability_token'), scope=scope, task_no=task_no)
|
||||
db.session.add(ShippingAuditEvent(
|
||||
event_type='chatflow_tool_read', aggregate_type='chat_session', aggregate_id=str(claims['sid']),
|
||||
task_no=task_no, actor_type='chatflow', actor_id=str(claims['uid']),
|
||||
request_id=str(request.headers.get('X-Request-ID') or '')[:64] or None,
|
||||
metadata_json={'tool': scope, 'token_nonce': str(claims['nonce'])[:16], 'success': True},
|
||||
))
|
||||
|
||||
@shipping_notice_bp.route('/tools/openapi.json', methods=['GET'])
|
||||
def openapi_spec():
|
||||
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
|
||||
return jsonify(_dify_openapi_spec())
|
||||
|
||||
@shipping_notice_bp.route('/tools/openapi.dify.yaml', methods=['GET'])
|
||||
def openapi_dify_yaml():
|
||||
"""返回 Dify 导入用的 OpenAPI YAML 文档。"""
|
||||
import yaml
|
||||
body = yaml.safe_dump(_dify_openapi_spec(), allow_unicode=True, sort_keys=False)
|
||||
return current_app.response_class(body, mimetype='text/yaml; charset=utf-8')
|
||||
|
||||
@shipping_notice_bp.route('/tools/create_task', methods=['POST'])
|
||||
def tool_create_task():
|
||||
"""
|
||||
创建单个发货任务。
|
||||
【AI 触发时机】:仅供 Hxops 内部建单链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.create_task(_payload()))
|
||||
|
||||
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/create_temporary_inventory_session', methods=['POST'])
|
||||
def tool_create_temporary_inventory_session():
|
||||
"""
|
||||
创建对话上传库存候选会话。
|
||||
【AI 触发时机】:用户明确说明 .xls、.xlsx 或 .csv 附件是库存文件时,在临时库存固定分支调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.create_temporary_inventory_session(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/get_temporary_inventory_session', methods=['POST'])
|
||||
def tool_get_temporary_inventory_session():
|
||||
"""
|
||||
读取临时库存候选的脱敏分析结果。
|
||||
【AI 触发时机】:创建临时会话后,需要决定采用已有方案还是请求映射建议时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.get_temporary_inventory_session(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/submit_temporary_inventory_mapping_suggestion', methods=['POST'])
|
||||
def tool_submit_temporary_inventory_mapping_suggestion():
|
||||
"""
|
||||
保存临时库存字段映射建议。
|
||||
【AI 触发时机】:仅在临时库存 LLM 节点返回真实表头到库存字段目录的候选后调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.submit_temporary_inventory_mapping_suggestion(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/confirm_temporary_inventory_use', methods=['POST'])
|
||||
def tool_confirm_temporary_inventory_use():
|
||||
"""
|
||||
确认本次对话临时库存文件的使用。
|
||||
【AI 触发时机】:仅在用户明确确认当前文件和方案后调用,禁止模型自行确认。
|
||||
"""
|
||||
return jsonify(shipping_tools.confirm_temporary_inventory_use(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/update_notice_fields', methods=['POST'])
|
||||
def tool_update_notice_fields():
|
||||
"""
|
||||
修改发货通知单头字段。
|
||||
【AI 触发时机】:当用户明确要求更正客户、PO、收货地或交期等单头信息时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.update_notice_fields(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/update_notice_line', methods=['POST'])
|
||||
def tool_update_notice_line():
|
||||
"""
|
||||
修改指定订单行。
|
||||
【AI 触发时机】:当用户指出某一行的 SKU、数量、Reservation ID 或交期有误时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.update_notice_line(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/add_notice_line', methods=['POST'])
|
||||
def tool_add_notice_line():
|
||||
"""
|
||||
新增订单行。
|
||||
【AI 触发时机】:当用户说明漏了一行订单、需要补录发货通知明细时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.add_notice_line(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/remove_notice_line', methods=['POST'])
|
||||
def tool_remove_notice_line():
|
||||
"""
|
||||
删除订单行。
|
||||
【AI 触发时机】:当用户确认某一行是误解析、重复行或不应出货的行时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.remove_notice_line(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/ensure_inventory', methods=['POST'])
|
||||
def tool_ensure_inventory():
|
||||
"""
|
||||
保证任务已取得库存数据。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
payload = _payload()
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
return jsonify(run_task_auto_progress(
|
||||
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
|
||||
trigger='legacy_tool_ensure_inventory',
|
||||
operator_id=payload.get('operator_id'),
|
||||
resume_gate_code='onhand_preparation',
|
||||
))
|
||||
|
||||
@shipping_notice_bp.route('/tools/auto_progress', methods=['POST'])
|
||||
def tool_auto_progress():
|
||||
"""
|
||||
自动推进任务。
|
||||
【AI 触发时机】:仅供后端 orchestrator / worker 调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.auto_progress(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/match_inventory', methods=['POST'])
|
||||
def tool_match_inventory():
|
||||
"""
|
||||
执行库存匹配。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
payload = _payload()
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
return jsonify(run_task_auto_progress(
|
||||
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
|
||||
trigger='legacy_tool_match_inventory',
|
||||
operator_id=payload.get('operator_id'),
|
||||
resume_gate_code='onhand_matching',
|
||||
))
|
||||
|
||||
@shipping_notice_bp.route('/tools/confirm_customer', methods=['POST'])
|
||||
def tool_confirm_customer():
|
||||
"""
|
||||
确认任务所属标准客户(仅提交 customer_id)。
|
||||
【AI 触发时机】:用户在客户人工确认检查点选择正式客户后调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.confirm_customer(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/generate_shipment_excel', methods=['POST'])
|
||||
def tool_generate_shipment_excel():
|
||||
"""
|
||||
生成出货 Excel。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
payload = _payload()
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
return jsonify(run_task_auto_progress(
|
||||
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
|
||||
trigger='legacy_tool_generate_excel',
|
||||
operator_id=payload.get('operator_id'),
|
||||
resume_gate_code='artifact_generation',
|
||||
))
|
||||
|
||||
@shipping_notice_bp.route('/tools/upload_to_freight', methods=['POST'])
|
||||
def tool_upload_to_freight():
|
||||
"""
|
||||
上传到货代系统或确认人工上传完成。
|
||||
【AI 触发时机】:仅供后端主调度、内部恢复链路或人工上传收口调用;不是 Dify 画布正式入口。
|
||||
Agent 应优先引导用户走工作台 mark-manual-uploaded,勿在自动链中调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.upload_to_freight(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/get_task_status', methods=['POST'])
|
||||
def tool_get_task_status():
|
||||
"""
|
||||
查询任务状态。
|
||||
【AI 触发时机】:当 Agent 只拿到任务号/会话号,需要先确认当前卡点后再决定下一步时调用。
|
||||
"""
|
||||
payload = _payload()
|
||||
task_no = str(payload.get('task_id') or payload.get('task_no') or '').strip().upper()
|
||||
_require_read_capability(payload, scope='get_shipping_status', task_no=task_no or None)
|
||||
return jsonify(shipping_tools.get_task_status(payload))
|
||||
|
||||
@shipping_notice_bp.route('/tasks/<task_no>/repair-inventory-attachment', methods=['POST'])
|
||||
def repair_task_inventory_attachment(task_no: str):
|
||||
"""
|
||||
从任务库存快照幂等重建正式附件(不重新消费 RPA callback)。
|
||||
核心逻辑:供晋升失败或 marker 异常后的人工/后台补偿。
|
||||
"""
|
||||
payload = _payload()
|
||||
payload.setdefault("task_no", task_no)
|
||||
payload.setdefault("task_id", task_no)
|
||||
return jsonify(shipping_tools.repair_task_inventory_attachment(payload))
|
||||
|
||||
@shipping_notice_bp.route('/tasks/<task_no>/export', methods=['GET'])
|
||||
def download_task_export(task_no: str):
|
||||
"""下载任务已生成的出货 Excel。"""
|
||||
task = get_task_by_ref(task_no)
|
||||
err_msg = task_export_error_message(task)
|
||||
if err_msg:
|
||||
raise NotFoundError(err_msg)
|
||||
resolved = resolve_task_export_download(task)
|
||||
assert resolved is not None
|
||||
path, download_name = resolved
|
||||
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
|
||||
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
backend/app/api/training.py
|
||||
backend/app/api/training/__init__.py
|
||||
|
||||
用途:提供新人培训用户侧进度接口与管理端统计导出接口。
|
||||
依赖:JWT 当前用户解析、training_service、Flask Blueprint/send_file。
|
||||
@@ -435,7 +435,7 @@ def _build_login_payload(user: User, source: str='password', bind_status: str=No
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'default_agent_id': user.default_agent_id,
|
||||
'feature_permissions': user.get_feature_permissions(),
|
||||
**user.client_auth_fields(),
|
||||
'source': source,
|
||||
'access_token': issue_local_access_token(user),
|
||||
'token_type': 'Bearer',
|
||||
|
||||
@@ -185,7 +185,7 @@ def home():
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
|
||||
def _load_home_payload():
|
||||
if user.role == 'admin':
|
||||
if user.is_platform_admin():
|
||||
agent_rows = Agent.query.filter(Agent.is_active.is_(True)).all()
|
||||
else:
|
||||
agent_rows = [agent for agent in user.agents if agent.is_active]
|
||||
@@ -213,7 +213,7 @@ def home():
|
||||
'runtime_provider': registry.get('runtime_provider'),
|
||||
'conversation_mode': registry.get('conversation_mode'),
|
||||
})
|
||||
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
|
||||
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'language': user.language, 'theme_preference': user.theme_preference or 'system', **user.client_auth_fields()}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
|
||||
try:
|
||||
return _run_db_with_retry(_load_home_payload, label='user.home')
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
@@ -297,7 +297,7 @@ def user_profile():
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
if request.method == 'GET':
|
||||
return jsonify({'id': user.id, 'username': user.username, 'real_name': user.real_name, 'email': user.email, 'phone_number': user.phone_number, 'employee_id': user.employee_id, 'department': user.department, 'role': user.role, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'})
|
||||
return jsonify({'id': user.id, 'username': user.username, 'real_name': user.real_name, 'email': user.email, 'phone_number': user.phone_number, 'employee_id': user.employee_id, 'department': user.department, 'role': user.role, 'language': user.language, 'theme_preference': user.theme_preference or 'system', **user.client_auth_fields()})
|
||||
data = request.get_json() or {}
|
||||
|
||||
def _update_profile():
|
||||
@@ -348,7 +348,7 @@ def get_agent_details(id):
|
||||
agent = db.session.get(Agent, id)
|
||||
if not agent:
|
||||
raise NotFoundError('Not found')
|
||||
if user.role != 'admin':
|
||||
if not user.is_platform_admin():
|
||||
has_permission = agent in user.agents
|
||||
if not has_permission:
|
||||
raise ForbiddenError('Access denied')
|
||||
|
||||
@@ -12,7 +12,7 @@ from app.api.workspace.shipping_notice import workspace_shipping_notice_bp
|
||||
from app.api.workspace.voucher_check import workspace_voucher_check_bp
|
||||
|
||||
import app.api.workspace.shipping_process_gate # noqa: F401
|
||||
import app.api.workspace.shipping_inventory_candidates # noqa: F401
|
||||
import app.api.workspace.shipping_onhand_candidates # noqa: F401
|
||||
|
||||
__all__ = [
|
||||
'workspace_announcements_bp',
|
||||
|
||||
@@ -20,7 +20,7 @@ from flask import Blueprint, Response, current_app, g, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.core.errors import AppError, ConflictError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice, ShippingOrderTask
|
||||
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
|
||||
@@ -87,34 +87,6 @@ def _ok(payload: Any, *, status: int = 200):
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None), status=status)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/receipt-report-files/<int:file_id>/download', methods=['GET'])
|
||||
def workspace_download_receipt_report_file(file_id: int):
|
||||
"""下载当前接收人或管理员有权读取的原样收料报表。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.receipt_report_access import resolve_receipt_report_download
|
||||
|
||||
stream, filename, content_type = resolve_receipt_report_download(file_id, user)
|
||||
response = send_file(
|
||||
stream, as_attachment=True, download_name=filename,
|
||||
mimetype=content_type or 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
)
|
||||
response.call_on_close(stream.close)
|
||||
return response
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/receipt-report-files', methods=['GET'])
|
||||
def workspace_list_receipt_report_files():
|
||||
"""列出当前接收人或管理员可下载的收料归档文件,不返回对象存储定位。"""
|
||||
user = _require_user()
|
||||
try:
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('limit must be an integer') from exc
|
||||
from app.services.shipping_notice.receipt_report_access import list_receipt_report_files
|
||||
|
||||
return _ok({'items': list_receipt_report_files(user, limit=limit)})
|
||||
|
||||
|
||||
def _assert_fulfillment_task_ownership(task: ShippingNotice, user_id: int) -> None:
|
||||
"""
|
||||
履约写接口:若请求携带期望 OT/Case/Run,校验与正式 Notice 归属一致。
|
||||
@@ -186,6 +158,7 @@ def workspace_shipping_tasks():
|
||||
lifecycle_status=lifecycle_status,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
is_admin=bool(user.is_platform_admin()),
|
||||
))
|
||||
|
||||
|
||||
@@ -199,7 +172,7 @@ def workspace_shipping_my_todos():
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.query_service import list_my_todos
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
try:
|
||||
page = int(request.args.get('page') or 1)
|
||||
page_size = int(request.args.get('page_size') or 20)
|
||||
@@ -224,7 +197,7 @@ def workspace_shipping_my_todos_count():
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.query_service import count_my_todos
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
return _ok(count_my_todos(user.id, is_admin=is_admin))
|
||||
|
||||
|
||||
@@ -249,7 +222,7 @@ def workspace_shipping_done_lines():
|
||||
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'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
try:
|
||||
page = int(request.args.get('page') or 1)
|
||||
page_size = int(request.args.get('page_size') or 20)
|
||||
@@ -276,7 +249,7 @@ def workspace_shipping_done_lines_export():
|
||||
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'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
stream, filename = build_done_lines_xlsx(
|
||||
user.id,
|
||||
is_admin=is_admin,
|
||||
@@ -302,7 +275,7 @@ def _batch_task_nos(data: dict) -> list[str]:
|
||||
|
||||
def _can_dispose_task(user, task) -> bool:
|
||||
"""管理员可跨用户处置;普通用户仅可处置自己名下或未归属任务。"""
|
||||
return str(getattr(user, 'role', '')).lower() == 'admin' or task.user_id in {None, user.id}
|
||||
return bool(user.is_platform_admin()) or task.user_id in {None, user.id}
|
||||
|
||||
|
||||
def _batch_dispose(action: str):
|
||||
@@ -345,7 +318,7 @@ def _batch_dispose(action: str):
|
||||
def workspace_batch_purge_shipping_tasks():
|
||||
"""仅管理员可永久清除回收站中的纯误建任务;每条均在行锁下重查全部引用。"""
|
||||
user = _require_user()
|
||||
if str(getattr(user, 'role', '')).lower() != 'admin':
|
||||
if not user.is_platform_admin():
|
||||
from app.core.errors import ForbiddenError
|
||||
|
||||
raise ForbiddenError('Admin privilege required')
|
||||
@@ -394,14 +367,38 @@ def workspace_batch_restore_shipping_tasks():
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-exports/archive', methods=['POST'])
|
||||
def workspace_shipping_export_archive():
|
||||
"""按显式任务号下载当前用户可访问的 ready 发货 Excel ZIP。"""
|
||||
"""按显式任务号下载当前用户可下载(创建者或管理员)的 ready 发货 Excel ZIP。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
task_nos = data.get('task_nos')
|
||||
if task_nos is not None and not isinstance(task_nos, list):
|
||||
raise ValidationError('task_nos must be a list', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
|
||||
from app.services.shipping_notice.export_archive import build_export_archive
|
||||
stream, filename, _manifest = build_export_archive(user_id=user.id, task_nos=task_nos or [])
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
|
||||
stream, filename, manifest = build_export_archive(
|
||||
user_id=user.id,
|
||||
task_nos=task_nos or [],
|
||||
is_admin=bool(user.is_platform_admin()),
|
||||
)
|
||||
# 与 business_no 批量导出同一审计口径:按票落 record_access_audit(自行提交)。
|
||||
for entry in manifest.get('entries') or []:
|
||||
aggregate_no = str(entry.get('business_no') or '').strip()
|
||||
task_no = str(entry.get('task_no') or '').strip()
|
||||
if not aggregate_no and not task_no:
|
||||
continue
|
||||
record_access_audit(
|
||||
action='download_task_excel',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=task_no or aggregate_no,
|
||||
actor_id=user.id,
|
||||
task_no=task_no or None,
|
||||
reason_code='excel_downloaded',
|
||||
metadata={
|
||||
'export': 'batch_zip',
|
||||
'batch_status': str(entry.get('status') or ''),
|
||||
},
|
||||
)
|
||||
response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip')
|
||||
response.call_on_close(stream.close)
|
||||
return response
|
||||
@@ -455,7 +452,11 @@ def workspace_confirm_shipping_customer(task_no: str):
|
||||
details={'field': 'customer_id'},
|
||||
) from exc
|
||||
updated = confirm_task_customer(task, customer_id=customer_id, actor_id=user.id)
|
||||
return _ok(serialize_task_detail(updated))
|
||||
return _ok(serialize_task_detail(
|
||||
updated,
|
||||
viewer_user_id=user.id,
|
||||
is_admin=bool(user.is_platform_admin()),
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
|
||||
@@ -499,7 +500,7 @@ def workspace_create_shipping_task_from_notice():
|
||||
db.session.commit()
|
||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
|
||||
orchestrator_started = start_task_orchestrator(task_id)
|
||||
return _ok({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
|
||||
return _ok({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task, viewer_user_id=user.id) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/replace-notice', methods=['POST'])
|
||||
def workspace_replace_shipping_task_notice(task_no: str):
|
||||
@@ -542,7 +543,7 @@ def workspace_shipping_task_detail(task_no: str):
|
||||
position / user_mode / actions / steps,减少前端二次推导与竞态刷新。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
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:
|
||||
@@ -562,7 +563,7 @@ def workspace_shipping_task_detail(task_no: str):
|
||||
def workspace_shipping_task_odm_options(task_no: str):
|
||||
"""返回整单 ODM ID 候选与当前选择(工作台整单裁决路径,只读)。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_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
|
||||
|
||||
@@ -576,7 +577,7 @@ def workspace_shipping_task_odm_options(task_no: str):
|
||||
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'
|
||||
is_admin = bool(user.is_platform_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
|
||||
|
||||
@@ -601,7 +602,7 @@ def workspace_set_shipping_task_odm_choice(task_no: str):
|
||||
def workspace_list_shipping_task_audit_timeline(task_no: str):
|
||||
"""业务用户 Task 审计时间线(统一 ShippingAuditEvent,无敏感快照)。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.audit_query_service import list_task_audit_timeline
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||||
@@ -633,7 +634,7 @@ def workspace_list_shipping_task_audit_timeline(task_no: str):
|
||||
def workspace_shipping_task_freight_notice_groups(task_no: str):
|
||||
"""读取当前 PO 下按 business_no 聚合的货代上传 Notice;仅供订单工作台展示。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_task_visible_to_user,
|
||||
list_freight_notice_groups_for_task,
|
||||
@@ -657,7 +658,12 @@ def workspace_shipping_task_ui_state(task_no: str):
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok(build_task_ui_state(task, include_stage_context=True))
|
||||
return _ok(build_task_ui_state(
|
||||
task,
|
||||
include_stage_context=True,
|
||||
viewer_user_id=user.id,
|
||||
viewer_is_admin=bool(user.is_platform_admin()),
|
||||
))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET'])
|
||||
def workspace_shipping_task_chat_actions(task_no: str):
|
||||
@@ -1032,6 +1038,38 @@ def _load_business_notice_for_user(*, business_no: str, user_id: int) -> Shippin
|
||||
return task
|
||||
|
||||
|
||||
def _load_business_notice_readable_for_user(
|
||||
*,
|
||||
business_no: str,
|
||||
user_id: int,
|
||||
is_admin: bool,
|
||||
) -> ShippingNotice:
|
||||
"""
|
||||
按精确发货通知单号加载当前用户可下载的 Notice(创建者或管理员)。
|
||||
|
||||
核心逻辑:下载是只读动作,授权走 can_download_task_export 统一谓词口径
|
||||
(可下载=可见),不经过写路径的履约归属断言;管理员可下载其可见的正式
|
||||
Notice,且每次下载均由端点写入 record_access_audit。
|
||||
|
||||
Args:
|
||||
business_no: 对外发货通知单号。
|
||||
user_id: 当前服务端会话用户主键。
|
||||
is_admin: 是否平台管理员。
|
||||
|
||||
Returns:
|
||||
可下载的 ShippingNotice。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 编号不存在、非正式 Notice 或用户不可见。
|
||||
"""
|
||||
normalized = str(business_no or '').strip().upper()
|
||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||||
task = get_task_visible_to_user(normalized, user_id, is_admin=is_admin)
|
||||
if not isinstance(task, ShippingNotice) or str(task.business_no or '').strip().upper() != normalized:
|
||||
raise NotFoundError('Shipping notice not found')
|
||||
return task
|
||||
|
||||
|
||||
def _start_notice_rpa_upload(*, business_no: str, user_id: int, artifact_id: int | None = None) -> dict[str, Any]:
|
||||
"""按 business_no 发起单张通知的货代 RPA 上传或重试。"""
|
||||
task = _load_business_notice_for_user(business_no=business_no, user_id=user_id)
|
||||
@@ -1064,6 +1102,47 @@ def workspace_confirm_shipping_notice_uploaded(business_no: str):
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/refresh-crane-upload', methods=['POST'])
|
||||
def workspace_refresh_crane_upload_status(business_no: str):
|
||||
"""手动刷新一张仍在分配中的 Crane 发货单。
|
||||
|
||||
核心逻辑:校验当前用户可见的通知单,读取最近一次上传尝试,写入一条只查状态的 trigger。
|
||||
不改 10 分钟定时回查的到期时间,也不重新上传 Excel。
|
||||
|
||||
Args:
|
||||
business_no: 对外发货通知单号,同时是 Crane 的 Pull Request #。
|
||||
|
||||
Returns:
|
||||
JSON: business_no 与 trigger_queued。
|
||||
|
||||
Raises:
|
||||
ValidationError: 没有可刷新的上传尝试或来源连接。
|
||||
ConflictError: 当前不是分配中,或上一次手动刷新还在排队。
|
||||
"""
|
||||
user = _require_user()
|
||||
task = _load_business_notice_for_user(business_no=business_no, user_id=int(user.id))
|
||||
from app.services.freight_rpa.upload.crane_recheck import request_manual_crane_refresh
|
||||
from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source
|
||||
from app.services.shipping_notice.onhand_source_repository import get_rpa_trigger_inventory_source
|
||||
from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt
|
||||
|
||||
attempt = latest_upload_attempt(task)
|
||||
from app.models import ShippingExportArtifact
|
||||
artifact = db.session.get(ShippingExportArtifact, attempt.artifact_id) if attempt is not None else None
|
||||
snapshot = task_rpa_inventory_source(task) or {}
|
||||
upload_source = get_rpa_trigger_inventory_source(str(snapshot.get('source_code') or '')) if snapshot.get('source_code') else None
|
||||
if attempt is None or artifact is None or not isinstance(upload_source, dict):
|
||||
raise ValidationError('Crane upload status cannot be refreshed', code='SHIPPING.UPLOAD_CRANE_ALLOCATING')
|
||||
trigger_path = request_manual_crane_refresh(
|
||||
attempt,
|
||||
upload_source,
|
||||
task_no=str(task.task_no),
|
||||
export_file_path=str(artifact.file_path or ''),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok({'business_no': str(task.business_no), 'trigger_queued': bool(trigger_path)})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/rpa-upload', methods=['POST'])
|
||||
def workspace_start_shipping_notice_rpa_upload(business_no: str):
|
||||
"""按发货通知单号发起 RPA 上传;RPA 成功事实仍由受信回调裁决。"""
|
||||
@@ -1138,9 +1217,13 @@ def workspace_batch_start_shipping_notice_rpa_upload():
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/export', methods=['GET'])
|
||||
def workspace_shipping_notice_export(business_no: str):
|
||||
"""按发货通知单号下载该通知唯一的正式 Excel,并保留下载审计。"""
|
||||
"""按发货通知单号下载该通知唯一的正式 Excel(创建者或管理员),并保留下载审计。"""
|
||||
user = _require_user()
|
||||
task = _load_business_notice_for_user(business_no=business_no, user_id=int(user.id))
|
||||
task = _load_business_notice_readable_for_user(
|
||||
business_no=business_no,
|
||||
user_id=int(user.id),
|
||||
is_admin=bool(user.is_platform_admin()),
|
||||
)
|
||||
err_msg = task_export_error_message(task)
|
||||
if err_msg:
|
||||
raise NotFoundError(err_msg)
|
||||
@@ -1162,7 +1245,7 @@ def workspace_shipping_notice_export(business_no: str):
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notices/batch/export', methods=['POST'])
|
||||
def workspace_shipping_notice_export_archive():
|
||||
"""按多个 business_no 下载各自唯一 Excel 的 ZIP;任一越权或缺文件均整体拒绝。"""
|
||||
"""按多个 business_no 下载各自唯一 Excel 的 ZIP(创建者或管理员);任一越权或缺文件均整体拒绝。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
raw_values = data.get('business_nos')
|
||||
@@ -1174,8 +1257,32 @@ def workspace_shipping_notice_export_archive():
|
||||
if not business_nos or len(business_nos) > 100:
|
||||
raise ValidationError('business_nos must contain 1 to 100 business numbers')
|
||||
from app.services.shipping_notice.export_archive import build_export_archive
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
|
||||
stream, filename, _manifest = build_export_archive(user_id=int(user.id), business_nos=business_nos)
|
||||
stream, filename, manifest = build_export_archive(
|
||||
user_id=int(user.id),
|
||||
business_nos=business_nos,
|
||||
is_admin=bool(user.is_platform_admin()),
|
||||
)
|
||||
# 批量导出与单票下载同一审计口径:按票落 record_access_audit(自行提交),
|
||||
# manifest.business_no 是 aggregate 事实源;missing/checksum 票据也留痕。
|
||||
for entry in manifest.get('entries') or []:
|
||||
aggregate_no = str(entry.get('business_no') or '').strip()
|
||||
task_no = str(entry.get('task_no') or '').strip()
|
||||
if not aggregate_no and not task_no:
|
||||
continue
|
||||
record_access_audit(
|
||||
action='download_notice_excel',
|
||||
aggregate_type='shipping_notice',
|
||||
aggregate_id=aggregate_no or task_no,
|
||||
actor_id=user.id,
|
||||
task_no=task_no or None,
|
||||
reason_code='excel_downloaded',
|
||||
metadata={
|
||||
'export': 'batch_zip',
|
||||
'batch_status': str(entry.get('status') or ''),
|
||||
},
|
||||
)
|
||||
response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip')
|
||||
response.call_on_close(stream.close)
|
||||
return response
|
||||
@@ -1183,9 +1290,10 @@ def workspace_shipping_notice_export_archive():
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
|
||||
def workspace_shipping_task_export(task_no: str):
|
||||
"""下载当前用户可访问任务的出货 Excel;写入统一访问审计。"""
|
||||
"""下载当前用户可下载任务的出货 Excel(创建者或管理员);写入统一访问审计。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
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=bool(user.is_platform_admin()))
|
||||
task = _require_formal_notice(task)
|
||||
err_msg = task_export_error_message(task)
|
||||
if err_msg:
|
||||
@@ -1213,11 +1321,11 @@ def workspace_shipping_task_inventory_file(task_no: str):
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_task_inventory_download
|
||||
from app.services.shipping_notice.onhand_file_store import resolve_task_inventory_download
|
||||
|
||||
resolved = resolve_task_inventory_download(task)
|
||||
if resolved is None:
|
||||
raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND')
|
||||
raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_ONHAND_FILE_NOT_FOUND')
|
||||
path, download_name = resolved
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
record_access_audit(
|
||||
@@ -1243,30 +1351,31 @@ def workspace_shipping_task_line_inventory_file(task_no: str, inventory_file_no:
|
||||
raise NotFoundError('Not found')
|
||||
from pathlib import Path
|
||||
|
||||
from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch
|
||||
from app.models import FreightRpaOnhandReportFile, ShippingNoticeLineOnhandMatch
|
||||
|
||||
requested_file_no = str(inventory_file_no or '').strip()
|
||||
inventory_file = (
|
||||
ShippingInventoryFile.query
|
||||
FreightRpaOnhandReportFile.query
|
||||
.join(
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingNoticeLineInventoryMatch.inventory_snapshot_id == ShippingInventoryFile.id,
|
||||
ShippingNoticeLineOnhandMatch,
|
||||
ShippingNoticeLineOnhandMatch.onhand_snapshot_id == FreightRpaOnhandReportFile.id,
|
||||
)
|
||||
.filter(
|
||||
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
|
||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||||
ShippingNoticeLineInventoryMatch.matched_file_no == requested_file_no,
|
||||
ShippingInventoryFile.inventory_file_no == requested_file_no,
|
||||
ShippingNoticeLineOnhandMatch.task_id == int(task.id),
|
||||
ShippingNoticeLineOnhandMatch.is_current.is_(True),
|
||||
ShippingNoticeLineOnhandMatch.matched_file_no == requested_file_no,
|
||||
FreightRpaOnhandReportFile.onhand_file_no == requested_file_no,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
storage_path = str(getattr(inventory_file, 'storage_path', '') or '').strip()
|
||||
path = Path(storage_path).resolve() if storage_path else None
|
||||
if inventory_file is None or not storage_path or storage_path.startswith('failed://') or not path.is_file():
|
||||
raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND')
|
||||
download_name = str(
|
||||
inventory_file.source_file_name or f'{inventory_file.inventory_file_no}{path.suffix or ".xlsx"}',
|
||||
).strip()
|
||||
raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_ONHAND_FILE_NOT_FOUND')
|
||||
from app.services.shipping_notice.onhand_file_store import build_inventory_download_name
|
||||
download_name = build_inventory_download_name(
|
||||
inventory_file, source_file_name=inventory_file.source_file_name, path=path,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
record_access_audit(
|
||||
action='download_task_line_inventory_file',
|
||||
@@ -1604,7 +1713,7 @@ def workspace_get_shipping_order_review_run(run_no: str):
|
||||
JSON 响应契约或业务数据。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_run
|
||||
from app.services.shipping_notice.order_review_service import get_review_run_visible_to_user
|
||||
@@ -1639,7 +1748,7 @@ def workspace_get_shipping_order_review_queue(run_no: str):
|
||||
JSON 响应契约或业务数据。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_queue
|
||||
from app.services.shipping_notice.order_review_service import get_review_queue_visible_to_user
|
||||
@@ -1676,7 +1785,7 @@ def workspace_get_shipping_order_review_case(case_no: str):
|
||||
JSON 响应契约或业务数据。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_case_snapshot import (
|
||||
build_order_review_case_snapshot,
|
||||
@@ -1724,7 +1833,7 @@ def workspace_retry_shipping_order_stp_auto_create(case_no: str):
|
||||
要求前端切换到 reconcile-and-progress;通过后再委托 retry_stp_auto_create_for_case。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import (
|
||||
retry_stp_auto_create_for_case,
|
||||
@@ -1762,7 +1871,7 @@ def workspace_reconcile_shipping_order_case_and_progress(case_no: str):
|
||||
source_content_hash: string(可选,请求快照用于参数一致性)
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
payload = request.get_json(silent=True) if request.is_json else None
|
||||
if not isinstance(payload, dict):
|
||||
payload = {}
|
||||
@@ -1821,7 +1930,7 @@ def workspace_audit_shipping_order_review_version_history(case_no: str):
|
||||
核心逻辑:先做 Case 可见性校验,再写入 access + 工作台语义事件,禁止仅改本地 UI 状态而不留痕。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit, record_fulfillment_audit
|
||||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||||
|
||||
@@ -1867,7 +1976,7 @@ def workspace_audit_shipping_order_review_eligibility_details(case_no: str):
|
||||
核心逻辑:先做 Case 可见性校验,再写入 access + 工作台语义事件。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit, record_fulfillment_audit
|
||||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||||
|
||||
@@ -2103,6 +2212,88 @@ def workspace_confirm_shipping_order_review_customer(case_no: str):
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/customer/rebind',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_rebind_shipping_order_review_customer(case_no: str):
|
||||
"""
|
||||
确认客户改绑:直接修改已确认的客户识别结果并刷新订单快照客户。
|
||||
|
||||
Body: customer_id, expected_order_data_version, reason?
|
||||
仅当订单编辑窗 header 可编辑(任一通知无 Export Artifact 且无活动 Gate Attempt,
|
||||
即发货通知/Excel 未产生)时允许;版本乐观锁与状态守卫在服务层 fail-closed。
|
||||
"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
customer_id = int(data.get('customer_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'Customer id is required',
|
||||
code='SHIPPING.CUSTOMER_REBIND_CUSTOMER_REQUIRED',
|
||||
details={'field': 'customer_id'},
|
||||
) from exc
|
||||
try:
|
||||
expected_order_data_version = int(data.get('expected_order_data_version'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'Expected order data version is required',
|
||||
code='SHIPPING.CUSTOMER_REBIND_VERSION_REQUIRED',
|
||||
details={'field': 'expected_order_data_version'},
|
||||
) from exc
|
||||
|
||||
from app.services.shipping_notice.customer_resolution_service import rebind_confirmed_customer
|
||||
from app.services.shipping_notice.order_review_customer_service import (
|
||||
project_review_case_customer_resolution,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_draft_service import soft_load_review_case_for_audit
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_case
|
||||
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
|
||||
|
||||
case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or ''))
|
||||
if case is None:
|
||||
raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
|
||||
formal = resolve_formal_ot(case)
|
||||
if not formal.get('has_formal_ot') or formal.get('task') is None:
|
||||
raise ConflictError(
|
||||
'A formal order task is required before rebinding customer',
|
||||
code='SHIPPING.FORMAL_OT_REQUIRED',
|
||||
details={'task_missing': bool(formal.get('task_missing'))},
|
||||
)
|
||||
|
||||
result = rebind_confirmed_customer(
|
||||
task=formal['task'],
|
||||
new_customer_id=customer_id,
|
||||
actor_id=int(user.id),
|
||||
expected_order_data_version=expected_order_data_version,
|
||||
reason=str(data.get('reason') or '').strip() or None,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
resolution = result['resolution']
|
||||
rebind_record = next(
|
||||
(
|
||||
item.get('rebind') for item in (resolution.evidence_json or [])
|
||||
if isinstance(item, dict) and item.get('rebind')
|
||||
),
|
||||
None,
|
||||
) or {}
|
||||
refreshed_case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or ''))
|
||||
return _ok({
|
||||
'case': serialize_review_case(refreshed_case) if refreshed_case is not None else None,
|
||||
'customer_resolution': (
|
||||
project_review_case_customer_resolution(refreshed_case)
|
||||
if refreshed_case is not None else None
|
||||
),
|
||||
'rebind': {
|
||||
'previous_customer_id': rebind_record.get('previous_customer_id'),
|
||||
'customer_id': int(resolution.confirmed_customer_id),
|
||||
'snapshot_id': int(result['snapshot'].id),
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/reservation/revalidate',
|
||||
methods=['POST'],
|
||||
@@ -2135,7 +2326,7 @@ def workspace_revalidate_shipping_order_review_reservation(case_no: str):
|
||||
def workspace_list_shipping_order_review_audit_timeline(case_no: str):
|
||||
"""业务用户 Case 审计时间线(无敏感快照)。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.audit_query_service import list_review_case_audit_timeline
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||||
@@ -2176,7 +2367,7 @@ def workspace_decide_shipping_order_review_line_fulfillment(case_no: str):
|
||||
decide_review_line_fulfillment,
|
||||
)
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
result = decide_review_line_fulfillment(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
@@ -2277,7 +2468,7 @@ def workspace_close_shipping_order_review_fulfillment(case_no: str):
|
||||
close_remaining_fulfillment,
|
||||
)
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
result = close_remaining_fulfillment(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
@@ -2690,7 +2881,7 @@ def workspace_attempt_shipping_order_review_field_locate(case_no: str):
|
||||
def workspace_list_shipping_order_review_llm_suggestions(case_no: str):
|
||||
"""列出 Case 下 Dify 最小证据建议记录。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.order_review_llm_service import list_case_suggestions
|
||||
|
||||
return _ok(list_case_suggestions(user_id=user.id, case_no=case_no, is_admin=is_admin))
|
||||
@@ -2700,7 +2891,7 @@ def workspace_list_shipping_order_review_llm_suggestions(case_no: str):
|
||||
def workspace_request_shipping_order_review_llm_suggestion(case_no: str):
|
||||
"""为指定字段请求 Dify 最小证据建议;Provider 不可用时不阻断人工复核。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.order_review_llm_service import request_field_suggestion
|
||||
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='request_llm_suggestion')
|
||||
@@ -2725,7 +2916,7 @@ def workspace_request_shipping_order_review_llm_suggestion(case_no: str):
|
||||
def workspace_adjudicate_shipping_order_review_llm_suggestion(case_no: str, suggestion_no: str):
|
||||
"""人工裁决 LLM 建议:accept / modify / reject。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.order_review_llm_service import decide_suggestion
|
||||
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='adjudicate_llm_suggestion')
|
||||
|
||||
+3
-3
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
backend/app/api/workspace/shipping_inventory_candidates.py
|
||||
backend/app/api/workspace/shipping_onhand_candidates.py
|
||||
|
||||
用途:正式 Task 库存候选只读详情 API。
|
||||
依赖:workspace_shipping_notice_bp、query_service.get_task_for_user、inventory_candidate_projection。
|
||||
依赖:workspace_shipping_notice_bp、query_service.get_task_for_user、onhand_candidate_projection。
|
||||
逻辑:路由层仅做鉴权与查询参数校验;当前版本缺失返回 200 + current_set=null + blocking_reason,
|
||||
不把可恢复业务阻断误报成 404。
|
||||
"""
|
||||
@@ -13,7 +13,7 @@ from flask import request
|
||||
|
||||
from app.api.workspace.shipping_notice import _ok, _require_user, workspace_shipping_notice_bp
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.inventory_candidate_projection import (
|
||||
from app.services.shipping_notice.onhand_candidate_projection import (
|
||||
project_inventory_candidate_detail,
|
||||
)
|
||||
from app.services.shipping_notice.query_service import get_task_for_user
|
||||
@@ -135,7 +135,7 @@ def workspace_post_process_gate_action(execution_no: str, gate_code: str):
|
||||
action_code=parsed['action_code'],
|
||||
expected_gate_version=parsed['expected_gate_version'],
|
||||
idempotency_key=parsed['idempotency_key'],
|
||||
actor_type='admin' if str(user.role or '').lower() == 'admin' else 'user',
|
||||
actor_type='admin' if user.is_platform_admin() else 'user',
|
||||
actor_id=int(user.id),
|
||||
payload=parsed['payload'],
|
||||
)
|
||||
|
||||
@@ -4,7 +4,7 @@ backend/app/api/workspace/voucher_check.py
|
||||
用途:立账凭证检核查询、强制重检与通知配置 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。
|
||||
查询要求 is_platform_admin 或持有 `agent_code=voucher_check` 的 Agent 授权;POST runs 与通知配置仅平台管理员。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -42,7 +42,7 @@ def _user_has_voucher_check_agent(user) -> bool:
|
||||
"""
|
||||
判断用户是否持有启用中的立账凭证检核 Agent。
|
||||
|
||||
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions;admin 不走此判断。
|
||||
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions;平台管理员不走此判断。
|
||||
|
||||
Args:
|
||||
user: 已认证用户。
|
||||
@@ -58,18 +58,18 @@ def _require_voucher_check_access():
|
||||
"""
|
||||
确保当前用户已登录且具备立账凭证检核访问权限。
|
||||
|
||||
核心逻辑:平台 admin 放行;普通用户必须被授予启用中的 `agent_code=voucher_check` Agent。
|
||||
核心逻辑:is_platform_admin 放行;普通用户必须被授予启用中的 `agent_code=voucher_check` Agent。
|
||||
无权限时返回业务 403,而不是静默空数据。
|
||||
|
||||
Returns:
|
||||
已认证且具备立账凭证 Agent 授权(或 admin)的用户。
|
||||
已认证且具备立账凭证 Agent 授权(或平台管理员)的用户。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 请求没有有效登录身份。
|
||||
ForbiddenError: 已登录但没有立账凭证 Agent 授权。
|
||||
"""
|
||||
user = _require_user()
|
||||
if getattr(user, "role", None) == "admin" or _user_has_voucher_check_agent(user):
|
||||
if user.is_platform_admin() or _user_has_voucher_check_agent(user):
|
||||
return user
|
||||
raise ForbiddenError(
|
||||
"Voucher check agent permission required",
|
||||
@@ -81,7 +81,7 @@ def _require_admin():
|
||||
"""
|
||||
确保当前用户既有立账凭证访问权,又是平台管理员。
|
||||
|
||||
核心逻辑:持有 Agent 的普通用户可查检核任务与发送记录;强制重检与通知配置仅 `role=admin`。
|
||||
核心逻辑:持有 Agent 的普通用户可查检核任务与发送记录;强制重检与通知配置仅 is_platform_admin。
|
||||
|
||||
Returns:
|
||||
已认证的管理员用户。
|
||||
@@ -91,7 +91,7 @@ def _require_admin():
|
||||
ForbiddenError: 无立账凭证访问权,或已授权但不是管理员。
|
||||
"""
|
||||
user = _require_voucher_check_access()
|
||||
if getattr(user, "role", None) != "admin":
|
||||
if not user.is_platform_admin():
|
||||
raise ForbiddenError(
|
||||
"Admin privilege required for voucher check jobs",
|
||||
code="VOUCHER_CHECK.ADMIN_REQUIRED",
|
||||
@@ -181,7 +181,7 @@ def workspace_voucher_notifications():
|
||||
def workspace_voucher_notify_config_get():
|
||||
"""
|
||||
读取按文件类型的企微接收人配置。
|
||||
核心逻辑:仅 admin;规则来自销售 Profile,接收人来自独立配置表。
|
||||
核心逻辑:仅 is_platform_admin;规则来自销售 Profile,接收人来自独立配置表。
|
||||
"""
|
||||
_require_admin()
|
||||
return ok(notify_config_service.get_notify_config(profile_code=request.args.get("profile_code")))
|
||||
@@ -191,7 +191,7 @@ def workspace_voucher_notify_config_get():
|
||||
def workspace_voucher_notify_config_put():
|
||||
"""
|
||||
保存按文件类型的企微接收人。
|
||||
核心逻辑:仅 admin;未知规则码丢弃;未绑企微的人可保存但发送时跳过。
|
||||
核心逻辑:仅 is_platform_admin;未知规则码丢弃;未绑企微的人可保存但发送时跳过。
|
||||
"""
|
||||
user = _require_admin()
|
||||
payload = request.get_json(silent=True) or {}
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
"""
|
||||
backend/app/api/workspace_file_check.py
|
||||
|
||||
用途:工作台文件检核 API 兼容 shim(Wave 1 迁包)。
|
||||
依赖:app.api.workspace.file_check。
|
||||
逻辑:旧 import 路径仍可用;新代码请用 app.api.workspace。
|
||||
"""
|
||||
from app.api.workspace.file_check import (
|
||||
serialize_current_step,
|
||||
serialize_file_judgement,
|
||||
workspace_file_check_bp,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'serialize_current_step',
|
||||
'serialize_file_judgement',
|
||||
'workspace_file_check_bp',
|
||||
]
|
||||
@@ -2,8 +2,9 @@
|
||||
backend/app/core/config/env_persistence.py
|
||||
|
||||
用途:运行时配置 DB 持久化与 env 镜像(WeCom 等 admin 设置)。
|
||||
依赖:app.extensions.db、app.models.AppSetting。
|
||||
逻辑:before_request 调用 apply_env_settings;persist_env_settings 供 admin 写入。
|
||||
依赖:app.extensions.db、app.models.AppSetting、threading/time(进程内 TTL 缓存)。
|
||||
逻辑:admin 经 persist_env_settings 写入;HTTP before_request 调用 apply_env_settings
|
||||
按 APP_SETTINGS_REFRESH_SECONDS 做进程内 TTL,避免每个请求全表扫描;写入时刷新缓存。
|
||||
|
||||
Storage strategy:
|
||||
1. Database (app_settings) - canonical
|
||||
@@ -15,6 +16,8 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
@@ -39,6 +42,12 @@ WECOM_BOOL_KEYS = {
|
||||
'WECOM_FEEDBACK_NOTIFY_ENABLED',
|
||||
}
|
||||
|
||||
_DEFAULT_REFRESH_SECONDS = 30.0
|
||||
_cache_lock = threading.Lock()
|
||||
_cache_prefixes: tuple[str, ...] | None = None
|
||||
_cache_applied: dict[str, object] = {}
|
||||
_cache_loaded_at: float = 0.0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
@@ -87,6 +96,27 @@ def _matches_prefixes(key: str, prefixes: Iterable[str]) -> bool:
|
||||
return any(key.startswith(prefix) for prefix in prefixes)
|
||||
|
||||
|
||||
def _refresh_ttl_seconds() -> float:
|
||||
"""
|
||||
读取进程内配置热更新 TTL(秒)。
|
||||
|
||||
核心逻辑:优先 Flask app.config;否则环境变量;非法值回退默认 30。
|
||||
设为 0 表示每次强制重载(兼容旧行为,便于排障)。
|
||||
"""
|
||||
raw: object = os.getenv('APP_SETTINGS_REFRESH_SECONDS', str(_DEFAULT_REFRESH_SECONDS))
|
||||
try:
|
||||
from flask import current_app, has_app_context
|
||||
|
||||
if has_app_context():
|
||||
raw = current_app.config.get('APP_SETTINGS_REFRESH_SECONDS', raw)
|
||||
except Exception: # pragma: no cover - 无 Flask 上下文时忽略
|
||||
pass
|
||||
try:
|
||||
return max(0.0, float(raw if raw not in (None, '') else _DEFAULT_REFRESH_SECONDS))
|
||||
except (TypeError, ValueError):
|
||||
return _DEFAULT_REFRESH_SECONDS
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Database read/write (primary store)
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -127,7 +157,14 @@ def _persist_to_db(values: dict[str, str]) -> bool:
|
||||
|
||||
|
||||
def _load_from_db(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
"""
|
||||
从 app_settings 读取匹配前缀的配置行。
|
||||
|
||||
核心逻辑:用 LIKE 前缀过滤,避免每次 before_request 拉全表后再 Python 过滤。
|
||||
"""
|
||||
try:
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import AppSetting
|
||||
except Exception as exc: # pragma: no cover
|
||||
@@ -135,7 +172,11 @@ def _load_from_db(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
return {}
|
||||
|
||||
try:
|
||||
rows = db.session.query(AppSetting).all()
|
||||
if not prefixes:
|
||||
rows = db.session.query(AppSetting).all()
|
||||
else:
|
||||
clauses = [AppSetting.key.like(f'{prefix}%') for prefix in prefixes]
|
||||
rows = db.session.query(AppSetting).filter(or_(*clauses)).all()
|
||||
except Exception as exc:
|
||||
# Most common case: the migration has not been applied yet on a
|
||||
# freshly-built container. Degrade gracefully to .env-only mode.
|
||||
@@ -197,15 +238,36 @@ def _load_from_env_file(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def persist_env_settings(values: dict[str, object]) -> dict[str, str]:
|
||||
"""Persist settings to the canonical store and mirror to ``os.environ``.
|
||||
def invalidate_env_settings_cache() -> None:
|
||||
"""
|
||||
清空进程内配置缓存,使下次 apply_env_settings 强制读库。
|
||||
|
||||
Order:
|
||||
1. Mirror to ``os.environ`` so the current process picks them up
|
||||
immediately.
|
||||
2. Persist to the database (canonical, survives container rebuilds).
|
||||
3. In dev only, best-effort write to ``.env.local`` so local restarts
|
||||
without DB access keep working.
|
||||
用途:测试或运维需要立刻看到外部写入的 app_settings 时调用。
|
||||
"""
|
||||
global _cache_loaded_at, _cache_applied, _cache_prefixes
|
||||
with _cache_lock:
|
||||
_cache_loaded_at = 0.0
|
||||
_cache_applied = {}
|
||||
_cache_prefixes = None
|
||||
|
||||
|
||||
def _store_cache(prefixes: tuple[str, ...], applied: dict[str, object]) -> None:
|
||||
"""写入进程内 TTL 缓存(调用方须已持有 _cache_lock)。"""
|
||||
global _cache_loaded_at, _cache_applied, _cache_prefixes
|
||||
_cache_prefixes = prefixes
|
||||
_cache_applied = dict(applied)
|
||||
_cache_loaded_at = time.monotonic()
|
||||
|
||||
|
||||
def persist_env_settings(values: dict[str, object]) -> dict[str, str]:
|
||||
"""
|
||||
将设置写入权威存储,并镜像到 ``os.environ`` 与进程内缓存。
|
||||
|
||||
顺序:
|
||||
1. 镜像到 ``os.environ``,当前进程立即可见;
|
||||
2. 写入数据库(权威源,容器重建后仍在);
|
||||
3. 仅在 dev 尽力写 ``.env.local``;
|
||||
4. 合并进 TTL 缓存并刷新时间戳,避免本进程还要等 TTL 才看到新值。
|
||||
"""
|
||||
if not values:
|
||||
return {}
|
||||
@@ -226,24 +288,61 @@ def persist_env_settings(values: dict[str, object]) -> dict[str, str]:
|
||||
list(persisted.keys()),
|
||||
)
|
||||
|
||||
# [STEP] 写入后失效缓存:下一请求全量重载,避免「只合并写入键」导致 TTL 内缺键。
|
||||
# 当前进程通常已在 admin service 里同步写过 current_app.config。
|
||||
invalidate_env_settings_cache()
|
||||
|
||||
return persisted
|
||||
|
||||
|
||||
def apply_env_settings(prefixes: tuple[str, ...] = ('WECOM_',)) -> dict[str, object]:
|
||||
"""Load settings from the canonical store and apply to ``os.environ``.
|
||||
|
||||
DB values take priority over env-file values; both are merged so
|
||||
keys that only live in env files (e.g. fresh deploy before any admin
|
||||
edit) are still honored.
|
||||
def apply_env_settings(
|
||||
prefixes: tuple[str, ...] = ('WECOM_',),
|
||||
*,
|
||||
force: bool = False,
|
||||
) -> dict[str, object]:
|
||||
"""
|
||||
从权威存储加载设置并应用到 ``os.environ``。
|
||||
|
||||
核心逻辑:DB 优先于 env 文件;进程内按 TTL 复用上次完整加载结果,减轻 before_request 查库压力。
|
||||
force=True 或 TTL=0 时始终重载。
|
||||
|
||||
Args:
|
||||
prefixes: 仅加载匹配此前缀的配置键,默认 WECOM_。
|
||||
force: 为 True 时忽略 TTL 强制读库。
|
||||
|
||||
Returns:
|
||||
解析后的配置字典(bool 键已转为 bool)。
|
||||
"""
|
||||
ttl = _refresh_ttl_seconds()
|
||||
now = time.monotonic()
|
||||
with _cache_lock:
|
||||
if (
|
||||
not force
|
||||
and ttl > 0
|
||||
and _cache_prefixes == prefixes
|
||||
and _cache_applied
|
||||
and (now - _cache_loaded_at) < ttl
|
||||
):
|
||||
applied = dict(_cache_applied)
|
||||
else:
|
||||
applied = None
|
||||
|
||||
if applied is not None:
|
||||
for key, parsed in applied.items():
|
||||
os.environ[key] = _to_env_string(parsed)
|
||||
return applied
|
||||
|
||||
# [STEP] 锁外读库/读文件,缩短临界区
|
||||
file_values = _load_from_env_file(prefixes)
|
||||
db_values = _load_from_db(prefixes)
|
||||
|
||||
merged: dict[str, str] = {**file_values, **db_values}
|
||||
|
||||
applied: dict[str, object] = {}
|
||||
applied = {}
|
||||
for key, raw_value in merged.items():
|
||||
parsed = _parse_env_value(key, raw_value)
|
||||
os.environ[key] = _to_env_string(parsed)
|
||||
applied[key] = parsed
|
||||
return applied
|
||||
|
||||
with _cache_lock:
|
||||
_store_cache(prefixes, applied)
|
||||
return dict(applied)
|
||||
@@ -101,6 +101,8 @@ class Config:
|
||||
ENV_NAME = ACTIVE_ENV_NAME
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
SECRET_KEY = os.getenv('SECRET_KEY')
|
||||
# 运行时可编辑配置(app_settings)进程内热更新间隔(秒);0=每请求强制读库
|
||||
APP_SETTINGS_REFRESH_SECONDS = float(os.getenv('APP_SETTINGS_REFRESH_SECONDS', '30') or '30')
|
||||
# 配置最大上传文件大小(200MB)
|
||||
MAX_CONTENT_LENGTH = 200 * 1024 * 1024
|
||||
KB_STORAGE_ROOT = _data_path('KB_STORAGE_ROOT', 'kb')
|
||||
@@ -289,6 +291,10 @@ class Config:
|
||||
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS = int(
|
||||
os.getenv('IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS', '600') or '600'
|
||||
)
|
||||
# 行库存查得时刻(inventory_checked_at)的 stale 徽标判定窗口(纯展示阈值)。
|
||||
IN_TRANSIT_TRANSFER_INVENTORY_STALE_TTL_SECONDS = int(
|
||||
os.getenv('IN_TRANSIT_TRANSFER_INVENTORY_STALE_TTL_SECONDS', '86400') or '86400'
|
||||
)
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS', '3') or '3')
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS', '5') or '5')
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS', '7') or '7')
|
||||
@@ -364,14 +370,18 @@ class Config:
|
||||
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY = float(
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY') or '0.98'
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS = int(
|
||||
os.getenv('FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS') or '900'
|
||||
FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS = int(
|
||||
os.getenv('FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS') or '900'
|
||||
)
|
||||
FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS = int(
|
||||
os.getenv('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS') or '900'
|
||||
FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS = int(
|
||||
os.getenv('FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS') or '900'
|
||||
)
|
||||
# 出站抓取本期无 Worker;超时键与 inbound 同形预留,避免后续批次再改 env 骨架。
|
||||
FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS = int(
|
||||
os.getenv('FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS') or '900'
|
||||
)
|
||||
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int(
|
||||
os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90'
|
||||
@@ -433,35 +443,51 @@ class Config:
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS = int(
|
||||
os.getenv('SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS') or '24'
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
|
||||
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
|
||||
# RPA 运行期数据目录统一为 `freight_rpa/{inventory,receipt,common}` 三层布局(与 env/ps1 三侧一致)。
|
||||
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR', 'freight_rpa', 'inventory', 'drop'
|
||||
# RPA 运行期数据目录分域(2026-10-16 批次 R):
|
||||
# onhand/ inbound/ outbound/ — 抓取域,叶目录同构 triggers|drop|logs|archives
|
||||
# upload/ — 上传域,叶目录 triggers|queue(与抓取域并列,勿挂 outbound 下)
|
||||
# common/ — 跨 Worker 共享(browser_profile)
|
||||
# outbound 本期无 Worker,仍落盘同构目录 + env,避免切换日再改骨架。
|
||||
FREIGHT_RPA_SHARED_ONHAND_DROP_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_ONHAND_DROP_DIR', 'freight_rpa', 'onhand', 'drop'
|
||||
)
|
||||
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR', 'freight_rpa', 'inventory', 'triggers'
|
||||
FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR', 'freight_rpa', 'onhand', 'triggers'
|
||||
)
|
||||
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR', 'freight_rpa', 'receipt', 'drop'
|
||||
FREIGHT_RPA_SHARED_INBOUND_DROP_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_INBOUND_DROP_DIR', 'freight_rpa', 'inbound', 'drop'
|
||||
)
|
||||
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', 'freight_rpa', 'receipt', 'triggers'
|
||||
FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR', 'freight_rpa', 'inbound', 'triggers'
|
||||
)
|
||||
FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR', 'freight_rpa', 'outbound', 'drop'
|
||||
)
|
||||
FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR', 'freight_rpa', 'outbound', 'triggers'
|
||||
)
|
||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR', 'freight_rpa', 'inventory', 'upload_queue'
|
||||
'FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR', 'freight_rpa', 'upload', 'queue'
|
||||
)
|
||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR', 'freight_rpa', 'inventory', 'upload_triggers'
|
||||
'FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR', 'freight_rpa', 'upload', 'triggers'
|
||||
)
|
||||
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR', 'freight_rpa', 'common', 'browser_profile'
|
||||
)
|
||||
FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_INVENTORY_ARCHIVE_DIR', 'freight_rpa', 'inventory', 'archives'
|
||||
FREIGHT_RPA_ONHAND_ARCHIVE_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_ONHAND_ARCHIVE_DIR', 'freight_rpa', 'onhand', 'archives'
|
||||
)
|
||||
FREIGHT_RPA_INBOUND_ARCHIVE_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_INBOUND_ARCHIVE_DIR', 'freight_rpa', 'inbound', 'archives'
|
||||
)
|
||||
FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR', 'freight_rpa', 'outbound', 'archives'
|
||||
)
|
||||
FREIGHT_RPA_WORKER_MOCK = os.getenv('FREIGHT_RPA_WORKER_MOCK', 'false')
|
||||
|
||||
@@ -487,7 +513,7 @@ 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,training_lean_video_push,training_overseas_thailand_guidelines')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning,equipment_acceptance_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,order_delivery_reply_notify,training_lean_video_push,training_overseas_thailand_guidelines')
|
||||
# 精益培训企微提醒卡片跳转的员工培训聊天页 agent id(前端路由 /chat/<id>)。
|
||||
# 缺省 0 = 不显式指定,由后端按 handler_config.content_profile='training' 动态解析各环境的培训 Agent
|
||||
# (测试/正式环境 Agent ID 不同,动态解析保证卡片均可定位「员工培训-精益管理」);
|
||||
@@ -541,6 +567,13 @@ class Config:
|
||||
SCHEDULE_WORKER_ENABLED = os.getenv('SCHEDULE_WORKER_ENABLED', 'true').lower() == 'true'
|
||||
SCHEDULE_WORKER_POLL_SECONDS = float(os.getenv('SCHEDULE_WORKER_POLL_SECONDS', '30') or '30')
|
||||
SCHEDULE_JOB_RUNNING_TIMEOUT_SECONDS = float(os.getenv('SCHEDULE_JOB_RUNNING_TIMEOUT_SECONDS', '7200') or '7200')
|
||||
# Web 进程内排程兜底扫描:仅本地开发(ENV_NAME=dev,无 schedule-worker 容器)默认开启;
|
||||
# test/prod 由 hxops-schedule-worker 容器负责(run.py 固定走 DevelopmentConfig,不能按配置类判定)。
|
||||
_scanner_env_raw = str(os.getenv('SCHEDULE_WEB_SCANNER_ENABLED') or '').strip().lower()
|
||||
if _scanner_env_raw:
|
||||
SCHEDULE_WEB_SCANNER_ENABLED = _scanner_env_raw in ('1', 'true', 'yes', 'on')
|
||||
else:
|
||||
SCHEDULE_WEB_SCANNER_ENABLED = _normalize_env_name(os.getenv('ENV_NAME') or ACTIVE_ENV_NAME) == 'dev'
|
||||
# Cron 表达式按此时区解读(如 0 12 * * * 表示该时区 12:00);入库 next_run_at 仍为 UTC。
|
||||
SCHEDULE_TIMEZONE = (os.getenv('SCHEDULE_TIMEZONE') or 'Asia/Shanghai').strip()
|
||||
SRM_SQLSERVER_HOST = os.getenv('SRM_SQLSERVER_HOST', '')
|
||||
@@ -761,9 +794,12 @@ class TestingConfig(Config):
|
||||
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
|
||||
# 钉住测试 TTL 语义(陈旧行门禁用例按 600s 书写),不随开发者 .env.shared 漂移。
|
||||
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS = 600
|
||||
# 库存查得时刻 stale 阈值钉 24h(stale 用例按 86400s 书写)。
|
||||
IN_TRANSIT_TRANSFER_INVENTORY_STALE_TTL_SECONDS = 86400
|
||||
WTF_CSRF_ENABLED = False
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {}
|
||||
SCHEDULE_WORKER_ENABLED = False
|
||||
SCHEDULE_WEB_SCANNER_ENABLED = False
|
||||
FIXED_ASSETS_SYNC_ENABLED = False
|
||||
FIXED_ASSETS_EXPORT_TO_DOCS = False
|
||||
ENV_NAME = 'dev'
|
||||
|
||||
@@ -47,7 +47,7 @@ def _resolve_request_agent_id() -> str | None:
|
||||
def require_agent_permission(f):
|
||||
"""
|
||||
装饰器:校验当前用户是否拥有指定 Agent 访问权限。
|
||||
核心逻辑:从 body/query/form 读 agent_id → 获取用户 → admin 放行或检查 user.agents。
|
||||
核心逻辑:从 body/query/form 读 agent_id → 获取用户 → 平台管理员放行或检查 user.agents。
|
||||
Args:
|
||||
f: 被装饰的视图函数。
|
||||
Returns:
|
||||
@@ -66,7 +66,7 @@ def require_agent_permission(f):
|
||||
if not agent:
|
||||
raise NotFoundError('Agent not found')
|
||||
g.current_agent = agent
|
||||
if user.role == 'admin':
|
||||
if user.is_platform_admin():
|
||||
return f(*args, **kwargs)
|
||||
if agent not in user.agents:
|
||||
raise ForbiddenError('Permission denied for this agent')
|
||||
@@ -77,8 +77,8 @@ def require_agent_permission(f):
|
||||
|
||||
def require_admin(f):
|
||||
"""
|
||||
装饰器:限制仅 admin 角色可访问。
|
||||
核心逻辑:解析用户 → 校验 role == admin;JWT 必填时检查 Authorization 头。
|
||||
装饰器:限制仅平台管理员可访问。
|
||||
核心逻辑:解析用户 → 校验 is_platform_admin;JWT 必填时检查 Authorization 头。
|
||||
"""
|
||||
|
||||
@wraps(f)
|
||||
@@ -88,7 +88,7 @@ def require_admin(f):
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
if bool(current_app.config.get('AUTH_JWT_REQUIRED', False)) and (not request.headers.get('Authorization')):
|
||||
raise UnauthorizedError('JWT token is required')
|
||||
if user.role != 'admin':
|
||||
if not user.is_platform_admin():
|
||||
raise ForbiddenError('Admin privilege required')
|
||||
return f(*args, **kwargs)
|
||||
|
||||
|
||||
@@ -28,11 +28,14 @@ class ValidationError(AppError):
|
||||
*,
|
||||
code: str = "VALIDATION.INVALID_PARAM",
|
||||
details: dict[str, Any] | None = None,
|
||||
http_status: int = 400,
|
||||
):
|
||||
super().__init__(
|
||||
code=code,
|
||||
message=message,
|
||||
http_status=400,
|
||||
# 默认 400(参数形态类校验);业务契约指定状态码时显式传入
|
||||
# (如调拨类型门禁 REQUIRED/NOT_CONFIGURED/DISABLED = 422,规格 §11)。
|
||||
http_status=http_status,
|
||||
details=details or {},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
"""
|
||||
backend/app/core/tool_auth.py
|
||||
|
||||
用途:集成密钥鉴权的公共实现,供所有以 Bearer / X-Integration-Key 方式接入的
|
||||
Tool / 回调蓝图共用(当前:shipping_notice Tool 蓝图、freight-rpa 回调蓝图)。
|
||||
依赖:flask.current_app/request、app.core.errors(ServiceUnavailableError / UnauthorizedError)。
|
||||
逻辑:由各蓝图 before_request 调用 require_tool_auth();本模块只做 Header 校验,
|
||||
不感知任何具体蓝图的错误 envelope(由蓝图自身 errorhandler 决定响应格式)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import current_app, request
|
||||
|
||||
from app.core.errors import ServiceUnavailableError, UnauthorizedError
|
||||
|
||||
|
||||
def require_tool_auth() -> None:
|
||||
"""
|
||||
校验集成方 Tool / RPA 回调 API 鉴权 Header。
|
||||
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;当 Dify、RPA Worker 或
|
||||
外部系统请求挂接本鉴权的蓝图时,由该蓝图的 before_request 自动触发。
|
||||
|
||||
核心逻辑:只接受 `Authorization: Bearer <token>` 或 `X-Integration-Key`。
|
||||
货代专用 `SHIPPING_NOTICE_TOOL_API_KEY` 优先,未配置时回退 `INTEGRATION_API_KEY`;
|
||||
未配置任何可用 key 时报服务不可用,缺失或错误时报未授权。
|
||||
"""
|
||||
configured = str(
|
||||
current_app.config.get('SHIPPING_NOTICE_TOOL_API_KEY')
|
||||
or current_app.config.get('INTEGRATION_API_KEY')
|
||||
or ''
|
||||
).strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError(
|
||||
'SHIPPING_NOTICE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured',
|
||||
code='missing_auth',
|
||||
)
|
||||
bearer = str(request.headers.get('Authorization') or '').strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith('bearer ') else ''
|
||||
integration_key = str(request.headers.get('X-Integration-Key') or '').strip()
|
||||
if configured in {token, integration_key}:
|
||||
return
|
||||
if not token and (not integration_key):
|
||||
raise UnauthorizedError('missing_auth')
|
||||
raise UnauthorizedError('invalid_auth')
|
||||
@@ -16,7 +16,7 @@ from app.jobs.handlers import ( # noqa: F401
|
||||
procurement_contract_review,
|
||||
schedule_run,
|
||||
shipping_document_layout,
|
||||
shipping_inventory_callback_process,
|
||||
freight_rpa_onhand_callback_process,
|
||||
shipping_notice_parse,
|
||||
shipping_notice_run,
|
||||
shipping_order_extraction,
|
||||
|
||||
+31
-7
@@ -1,9 +1,13 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/shipping_inventory_callback_process.py
|
||||
backend/app/jobs/handlers/freight_rpa_onhand_callback_process.py
|
||||
|
||||
用途:异步处理已收件的库存 RPA batch 回调,避免 Worker HTTP 回调被 Excel 处理阻塞。
|
||||
依赖:Job 队列、inventory_rpa_workflow 的正式批量处理函数。
|
||||
依赖:Job 队列、onhand_rpa_workflow 的正式批量处理函数。
|
||||
逻辑:HTTP 回调只写本 Job;shipping worker 领取后执行结构校验、库存解析、任务关联与后续推进。
|
||||
业务失败(transport/result_status=failed)收口为不可重试;意外异常(含批量 commit 后
|
||||
onhand 事实处理函数失败的重抛)收口为可重试(Task 7 修复轮 2——文件行已提交不回滚,
|
||||
重放按幂等契约补齐候选/门禁收口);修复轮 3:投递失败重抛携带的未成功文件清单写回
|
||||
payload(retry_dispatch_files),重试经批量入口的「只重投失败文件」通道补齐。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,7 +20,7 @@ from app.jobs.types import JobType
|
||||
from app.models import Job
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS)
|
||||
@register_handler(JobType.FREIGHT_RPA_ONHAND_CALLBACK_PROCESS)
|
||||
def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> None:
|
||||
"""处理一个已收件的库存 RPA 回调。
|
||||
|
||||
@@ -31,7 +35,7 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N
|
||||
|
||||
owned_attempt = int(job.attempts or 0)
|
||||
try:
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import process_rpa_report_inventory_batch
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch
|
||||
|
||||
result = process_rpa_report_inventory_batch(dict(job.payload_json or {}))
|
||||
result_data = result.get('data') if isinstance(result, dict) else None
|
||||
@@ -44,7 +48,7 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N
|
||||
if transport_status == 'failed' or result_status in {'failed', 'partial_failed'}:
|
||||
failed_items = result_data.get('failed') if isinstance(result_data, dict) else []
|
||||
first_error = failed_items[0].get('error') if isinstance(failed_items, list) and failed_items and isinstance(failed_items[0], dict) else None
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import settle_failed_inventory_callback
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import settle_failed_inventory_callback
|
||||
|
||||
settle_failed_inventory_callback(
|
||||
dict(job.payload_json or {}),
|
||||
@@ -64,12 +68,32 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N
|
||||
message='库存 RPA 回调已异步处理',
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 - queue must retain retryable receipt evidence
|
||||
except Exception as exc: # noqa: BLE001 - 队列收口保留可重试证据
|
||||
db.session.rollback()
|
||||
# 【Task 7 修复轮 3】批量 commit 后投递失败的重抛携带「未成功文件清单」——
|
||||
# 写回 Job payload(retry_dispatch_files),重试经批量入口的「只重投失败
|
||||
# 文件」通道补齐(整批重放会被 callback_id 已消费的 replay 检查跳过、
|
||||
# 已收口的排程 run 校验拦下);清单随重试结果逐轮收敛,直至全部成功或
|
||||
# attempts 耗尽。普通意外异常(无清单)仍整批自然重放。
|
||||
from app.services.shipping_notice.onhand_rpa_workflow import (
|
||||
OnhandReportDispatchAfterCommitError,
|
||||
)
|
||||
|
||||
if isinstance(exc, OnhandReportDispatchAfterCommitError) and exc.failed_files:
|
||||
job.payload_json = {
|
||||
**(dict(job.payload_json or {})),
|
||||
'retry_dispatch_files': list(exc.failed_files),
|
||||
}
|
||||
db.session.commit()
|
||||
fail_job(
|
||||
job.id,
|
||||
error=str(exc),
|
||||
result={'status': 'processing_failed', 'error': str(exc)[:1000]},
|
||||
retryable=False,
|
||||
# 【Task 7 修复轮 2】意外异常(含批量 commit 后 onhand 事实处理函数失败
|
||||
# ——process_rpa_report_inventory_batch 已尽力完成其余投递、排程收口与
|
||||
# drop 文件清理入队后原样重抛)必须可重试:文件行已提交不回滚,重放按
|
||||
# 幂等契约补齐收口;业务失败(transport/result_status=failed)仍走上方
|
||||
# retryable=False 分支。
|
||||
retryable=True,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
@@ -5,6 +5,13 @@
|
||||
逻辑:领取后按 payload.matching_id 加载匹配,运行 run_matching 并回写
|
||||
状态/计数/Hash;匹配不存在时 fail-closed 抛 RuntimeError。业务收尾后
|
||||
handler 自行 finish_job(runner 仅兜底异常路径,正常完成不代收口)。
|
||||
【2026-10-14 出生翻转/快照自足确认】异步重跑的全部口径从 scope_json
|
||||
快照回读——transfer_type 编码 + scope_rules/transform_rules 覆盖传入
|
||||
(不读现行配置规则,在途匹配口径不被中途改配置扰动);类型门禁按
|
||||
require_enabled=False(「停用后存量不受影响」,规格 §4.1),仅要求配置
|
||||
仍存在(类型只有停用没有删除)。run_matching 传 matching_id:重跑圈档
|
||||
仅补建「未被有效 items 占用」的新档记录(D17:自有 items 不重复圈定/
|
||||
不重复评估他匹配行),并刷新本匹配自有 items。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -36,6 +43,8 @@ def run_in_transit_transfer_match(_ctx, payload: dict) -> None:
|
||||
owned_attempt = int(job_row.attempts) if job_row is not None else None
|
||||
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
# [快照自足] 类型/范围/转换规则全部回读 scope_json(无枚举依赖、不查现行
|
||||
# 配置规则);warehouse 路由的 fixed 定义随类型配置现行值(未入快照契约)。
|
||||
scope = matching.scope_json if isinstance(matching.scope_json, dict) else {}
|
||||
source_codes = list(scope.get("source_codes") or [])
|
||||
result = run_matching(
|
||||
@@ -43,14 +52,18 @@ def run_in_transit_transfer_match(_ctx, payload: dict) -> None:
|
||||
business_date=matching.business_date,
|
||||
deps=deps,
|
||||
run_no=matching.run.run_no if matching.run else "RUN-PENDING",
|
||||
# 类型范围随匹配落库回读:异步重跑与创建时口径一致(缺省回落类型1)。
|
||||
transfer_type=str(scope.get("transfer_type")) if scope.get("transfer_type") else None,
|
||||
matching_id=matching.id,
|
||||
scope_rules_override=scope.get("scope_rules") if isinstance(scope.get("scope_rules"), list) else None,
|
||||
transform_rules_override=(
|
||||
scope.get("transform_rules") if isinstance(scope.get("transform_rules"), list) else None
|
||||
),
|
||||
require_enabled=False, # 存量重跑:停用类型不受影响(仅要求配置仍存在)
|
||||
)
|
||||
summary = result.summary
|
||||
matching.status = summary.status
|
||||
matching.counts_json = {
|
||||
"file_invoice_count": summary.counts.file_invoice_count,
|
||||
"not_matured_count": summary.counts.not_matured_count,
|
||||
"matched_count": summary.counts.matched_count,
|
||||
"executable_count": summary.counts.executable_count,
|
||||
"blocked_count": summary.counts.blocked_count,
|
||||
|
||||
@@ -724,6 +724,58 @@ def _handoff_continue_order_extraction(
|
||||
return True
|
||||
|
||||
|
||||
def _emit_reservation_heuristic_audit(
|
||||
*,
|
||||
run: Any,
|
||||
merged_by_unit_id: dict[int, list[dict[str, Any]]],
|
||||
) -> None:
|
||||
"""
|
||||
合并末段「裸数字预约单号兜底」落地后补审计事件,供上线后观察误判率。
|
||||
|
||||
【AI 触发时机】:EML 补充合并(merge_email_supplements)完成后调用。
|
||||
只读订单上的 _hxops_reservation_heuristic 标记,不修改订单;命中与多候选
|
||||
各发一条事件,metadata 携带 unit/候选值/正文文档定位,便于按 Case 回溯证据。
|
||||
|
||||
Args:
|
||||
run: 当前订单抽取 Run(审计聚合根)。
|
||||
merged_by_unit_id: 本趟合并产物 {unit_id: [order]}。
|
||||
"""
|
||||
applied_entries: list[dict[str, Any]] = []
|
||||
ambiguous_entries: list[dict[str, Any]] = []
|
||||
for unit_id, orders in (merged_by_unit_id or {}).items():
|
||||
for order in orders or []:
|
||||
marker = order.get('_hxops_reservation_heuristic') if isinstance(order, dict) else None
|
||||
if not isinstance(marker, dict):
|
||||
continue
|
||||
entry = {
|
||||
'unit_id': int(unit_id),
|
||||
'values': marker.get('values') or [],
|
||||
'document_id': marker.get('document_id'),
|
||||
}
|
||||
if marker.get('status') == 'applied':
|
||||
applied_entries.append({**entry, 'value': marker.get('value')})
|
||||
else:
|
||||
ambiguous_entries.append(entry)
|
||||
for event_type, entries in (
|
||||
('reservation_heuristic_applied', applied_entries),
|
||||
('reservation_heuristic_ambiguous', ambiguous_entries),
|
||||
):
|
||||
if not entries:
|
||||
continue
|
||||
append_shipping_audit_event(
|
||||
event_type=event_type,
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id=str(run.id),
|
||||
run_no=run.run_no,
|
||||
actor_type='system',
|
||||
source='shipping_order_extraction',
|
||||
metadata={
|
||||
'entries': entries,
|
||||
'decision_rule_version': 'bare-numeric-reservation-v1',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _is_transient_lock_error(exc: BaseException) -> bool:
|
||||
"""
|
||||
判断异常是否为瞬时锁冲突(PostgreSQL 死锁 40P01 / 锁等待超时 55P03)。
|
||||
@@ -1139,6 +1191,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
},
|
||||
)
|
||||
_merge_group_orders(eml_units, apply_email_supplements=True)
|
||||
_emit_reservation_heuristic_audit(run=run, merged_by_unit_id=merged_by_unit_id)
|
||||
append_shipping_audit_event(
|
||||
event_type='ORDER_EMAIL_ADJUDICATION_COMPLETED',
|
||||
aggregate_type='order_extraction_run',
|
||||
|
||||
@@ -3,7 +3,9 @@ backend/app/jobs/types.py
|
||||
|
||||
用途:Job 类型与状态枚举;KbJob.job_type 与 handler JobType 的双向映射。
|
||||
逻辑:handlers 与 queue 通过 JobType 注册;store 持久化仍走 KbJob 表(Wave 2 双轨);
|
||||
shipping_process_gate 由 shipping worker 与发货通知任务同队列领取。
|
||||
shipping_process_gate 由 shipping worker 与发货通知任务同队列领取;
|
||||
在手回调成员 FREIGHT_RPA_ONHAND_CALLBACK_PROCESS 的持久化值为
|
||||
freight_rpa_onhand_callback_process。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -20,8 +22,9 @@ class JobType(StrEnum):
|
||||
SHIPPING_ORDER_EXTRACTION = 'shipping_order_extraction'
|
||||
SHIPPING_DOCUMENT_LAYOUT = 'shipping_document_layout'
|
||||
SHIPPING_PROCESS_GATE = 'shipping_process_gate'
|
||||
# RPA 回调 HTTP 只收件;Excel 校验、解析、任务关联由 shipping worker 异步完成。
|
||||
SHIPPING_INVENTORY_CALLBACK_PROCESS = 'shipping_inventory_callback_process'
|
||||
# 在手 RPA 回调 HTTP 只收件;Excel 校验、解析、任务关联由 shipping worker 异步完成。
|
||||
# 持久化 jobs.job_type 为 freight_rpa_onhand_callback_process。
|
||||
FREIGHT_RPA_ONHAND_CALLBACK_PROCESS = 'freight_rpa_onhand_callback_process'
|
||||
# 统一 PDF 自动标记:按实际证据能力执行坐标重建或 XFA 多源视觉融合。
|
||||
SHIPPING_PDF_AUTOMARK = 'shipping_pdf_automark'
|
||||
# 资格达标后的 STP 自动建单入队(先 queued,再由 worker 执行 confirm)
|
||||
@@ -76,7 +79,7 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
|
||||
'shipping': frozenset({
|
||||
'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction',
|
||||
'shipping_document_layout', 'shipping_process_gate', 'shipping_pdf_automark',
|
||||
'shipping_inventory_callback_process',
|
||||
'freight_rpa_onhand_callback_process',
|
||||
'shipping_stp_auto_create', 'shipping_line_auto_fulfill',
|
||||
'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress',
|
||||
}),
|
||||
|
||||
+102
-60
@@ -2,12 +2,14 @@
|
||||
backend/app/models/__init__.py
|
||||
|
||||
用途:按业务域拆分的 ORM 模型包入口;聚合导出以保持 `from app.models import User` 兼容。
|
||||
依赖:models/* 子模块(含 voucher_check)、app.extensions.db(经 base.Base)。
|
||||
依赖:models/* 子模块(含 voucher_check、equipment_acceptance、freight_rpa_*)、app.extensions.db(经 base.Base)。
|
||||
逻辑:Alembic / Flask-Migrate 通过本模块 import 注册全部表元数据;业务代码继续从此处导入模型类。
|
||||
在手/入站/出站模型导出 FreightRpa*。
|
||||
"""
|
||||
|
||||
from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest
|
||||
from app.models.base import Base, user_agent_permissions
|
||||
from app.models.permission_role import PermissionRole, permission_role_agents
|
||||
from app.models.chat import ChatLog, ChatSession, ChatToolRun, Feedback, GeneralFeedback
|
||||
from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlLanguage
|
||||
from app.models.department import Department
|
||||
@@ -30,15 +32,15 @@ from app.models.contract_payment import (
|
||||
ContractPaymentVendorRequest,
|
||||
)
|
||||
from app.models.shipping import (
|
||||
ShippingInventoryFile,
|
||||
ShippingNotice,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
ShippingTaskEvent,
|
||||
ShippingTaskPurgeAudit,
|
||||
ShippingTaskInventoryLink,
|
||||
ShippingTaskOnhandLink,
|
||||
)
|
||||
from app.models.freight_rpa_onhand_report_file import FreightRpaOnhandReportFile
|
||||
from app.models.shipping_order_submission import ShippingOrderSubmission
|
||||
from app.models.shipping_order_task import ShippingOrderTask
|
||||
from app.models.shipping_order_candidate_evidence import ShippingOrderCandidateEvidence
|
||||
@@ -51,8 +53,8 @@ from app.models.shipping_context_provider import ShippingContextProvider, Shippi
|
||||
from app.models.shipping_excel_template import ShippingExcelTemplate, ShippingExportArtifact
|
||||
from app.models.shipping_fulfillment import (
|
||||
ShippingExportArtifactLine,
|
||||
ShippingInventoryVerification,
|
||||
ShippingInventoryVerificationLine,
|
||||
ShippingOnhandVerification,
|
||||
ShippingOnhandVerificationLine,
|
||||
ShippingReservation,
|
||||
ShippingUploadAttempt,
|
||||
)
|
||||
@@ -94,7 +96,7 @@ from app.models.shipping_order_review import (
|
||||
from app.models.shipping_order_review_line_decision import ShippingOrderReviewLineDecision
|
||||
from app.models.shipping_order_review_wave_line import ShippingOrderReviewWaveLine
|
||||
from app.models.shipping_order_review_wave_idempotency import ShippingOrderReviewWaveIdempotency
|
||||
from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch
|
||||
from app.models.shipping_notice_line_onhand_match import ShippingNoticeLineOnhandMatch
|
||||
from app.models.shipping_order_review_suggestion import ShippingOrderReviewSuggestion
|
||||
from app.models.shipping_order_extraction_run import (
|
||||
ShippingOrderExtractionDiagnosticAudit,
|
||||
@@ -136,27 +138,32 @@ from app.models.shipping_document_layout import ShippingDocumentLayoutVersion
|
||||
from app.models.shipping_eml_preview_snapshot import ShippingEmlPreviewSnapshot
|
||||
from app.models.shipping_xfa_structure_analysis import ShippingXfaStructureAnalysis
|
||||
from app.models.shipping_xfa_audit_snapshot import ShippingXfaAuditSnapshot
|
||||
from app.models.shipping_inventory_config import (
|
||||
ShippingInventoryField,
|
||||
ShippingInventoryExternalMapping,
|
||||
ShippingInventoryConfigurationTestRun,
|
||||
ShippingInventoryValidationBatch,
|
||||
ShippingInventorySourceParsingBindingAudit,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventoryRoutingRule,
|
||||
ShippingInventoryRoutingRuleCondition,
|
||||
ShippingInventoryRoutingRuleVersion,
|
||||
ShippingInventorySource,
|
||||
ShippingInventoryStructureAnalysis,
|
||||
ShippingRpaProfile,
|
||||
from app.models.freight_rpa_config import (
|
||||
FreightRpaOnhandField,
|
||||
FreightRpaOnhandExternalMapping,
|
||||
FreightRpaOnhandConfigurationTestRun,
|
||||
FreightRpaOnhandValidationBatch,
|
||||
FreightRpaSourceParsingBindingAudit,
|
||||
FreightRpaParsingProfile,
|
||||
FreightRpaOnhandRoutingRule,
|
||||
FreightRpaOnhandRoutingRuleCondition,
|
||||
FreightRpaOnhandRoutingRuleVersion,
|
||||
FreightRpaSource,
|
||||
FreightRpaOnhandReportConfig,
|
||||
FreightRpaOnhandStructureAnalysis,
|
||||
FreightRpaProfile,
|
||||
)
|
||||
from app.models.shipping_receipt_report import (
|
||||
ShippingReceiptNotificationDelivery,
|
||||
ShippingReceiptReportConfig,
|
||||
ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun,
|
||||
from app.models.freight_rpa_inbound_report import (
|
||||
FreightRpaInboundReportConfig,
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
)
|
||||
from app.models.shipping_temporary_inventory import ShippingTemporaryInventorySession
|
||||
from app.models.freight_rpa_outbound_report import (
|
||||
FreightRpaOutboundReportConfig,
|
||||
FreightRpaOutboundReportFile,
|
||||
FreightRpaOutboundUnitRun,
|
||||
)
|
||||
from app.models.shipping_temporary_onhand import ShippingTemporaryOnhandSession
|
||||
from app.models.shipping_customer import (
|
||||
ShippingBusinessSequence,
|
||||
ShippingCustomer,
|
||||
@@ -179,18 +186,18 @@ from app.models.shipping_identity_rule import (
|
||||
ShippingIdentityRuleAuditEvent,
|
||||
ShippingIdentityRuleSet,
|
||||
)
|
||||
from app.models.shipping_inventory_candidates import (
|
||||
ShippingInventoryCandidateLine,
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingInventoryCandidateSource,
|
||||
from app.models.shipping_onhand_candidates import (
|
||||
ShippingOnhandCandidateLine,
|
||||
ShippingOnhandCandidateSet,
|
||||
ShippingOnhandCandidateSource,
|
||||
)
|
||||
from app.models.shipping_task_inventory_rpa_attempts import ShippingTaskInventoryRpaAttempt
|
||||
from app.models.freight_rpa_onhand_task_attempts import FreightRpaOnhandTaskAttempt
|
||||
from app.models.shipping_process_recovery_plan import ShippingProcessRecoveryPlan
|
||||
from app.models.shipping_inventory_preparation import (
|
||||
ShippingInventoryPreparationAttempt,
|
||||
ShippingInventoryPreparationSourceAttempt,
|
||||
from app.models.shipping_onhand_preparation import (
|
||||
ShippingOnhandPreparationAttempt,
|
||||
ShippingOnhandPreparationSourceAttempt,
|
||||
)
|
||||
from app.models.shipping_inventory_mapping import ShippingInventoryMapping
|
||||
from app.models.freight_rpa_onhand_mapping import FreightRpaOnhandMapping
|
||||
from app.models.training import (
|
||||
LeanTrainingCompletion,
|
||||
LeanTrainingReminder,
|
||||
@@ -207,8 +214,10 @@ from app.models.in_transit_transfer import (
|
||||
TransferDocument,
|
||||
TransferInvoiceItem,
|
||||
TransferMatching,
|
||||
TransferMovementLedger,
|
||||
TransferRun,
|
||||
TransferSourceJob,
|
||||
TransferTypeConfig,
|
||||
)
|
||||
from app.models.integration_connector import (
|
||||
IntegrationBinding,
|
||||
@@ -237,11 +246,28 @@ from app.models.contract_payment import (
|
||||
ContractPaymentSyncState,
|
||||
ContractPaymentVendorRequest,
|
||||
)
|
||||
from app.models.equipment_acceptance import (
|
||||
EquipmentAcceptanceNode,
|
||||
EquipmentAcceptanceOperator,
|
||||
EquipmentAcceptanceOrder,
|
||||
EquipmentAcceptanceSendFile,
|
||||
EquipmentAcceptanceSendRecord,
|
||||
EquipmentAcceptanceSetting,
|
||||
)
|
||||
from app.models.order_delivery_reply import (
|
||||
OrderDeliveryAuditEvent,
|
||||
OrderDeliveryBatch,
|
||||
OrderDeliveryErpLine,
|
||||
OrderDeliveryLineState,
|
||||
OrderDeliverySyncRun,
|
||||
)
|
||||
from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit
|
||||
|
||||
__all__ = [
|
||||
'Base',
|
||||
'user_agent_permissions',
|
||||
'permission_role_agents',
|
||||
'PermissionRole',
|
||||
'ZlLanguage',
|
||||
'Department',
|
||||
'UserHomepageConfig',
|
||||
@@ -299,7 +325,7 @@ __all__ = [
|
||||
'ShippingOrderReviewLineDecision',
|
||||
'ShippingOrderReviewWaveLine',
|
||||
'ShippingOrderReviewWaveIdempotency',
|
||||
'ShippingNoticeLineInventoryMatch',
|
||||
'ShippingNoticeLineOnhandMatch',
|
||||
'ShippingOrderReviewSuggestion',
|
||||
'ShippingOrderProcessingRun',
|
||||
'ShippingOrderProcessingRunIntake',
|
||||
@@ -348,30 +374,33 @@ __all__ = [
|
||||
'ShippingIdentityRuleAuditEvent',
|
||||
'ShippingTaskEvent',
|
||||
'ShippingTaskPurgeAudit',
|
||||
'ShippingInventoryFile',
|
||||
'ShippingTaskInventoryLink',
|
||||
'ShippingRpaProfile',
|
||||
'ShippingInventorySource',
|
||||
'ShippingReceiptReportConfig',
|
||||
'ShippingReceiptRpaUnitRun',
|
||||
'ShippingReceiptReportFile',
|
||||
'ShippingReceiptNotificationDelivery',
|
||||
'ShippingInventoryField',
|
||||
'ShippingInventoryStructureAnalysis',
|
||||
'ShippingInventoryRoutingRule',
|
||||
'ShippingInventoryRoutingRuleCondition',
|
||||
'ShippingInventoryRoutingRuleVersion',
|
||||
'ShippingInventoryExternalMapping',
|
||||
'ShippingInventoryConfigurationTestRun',
|
||||
'ShippingInventoryValidationBatch',
|
||||
'ShippingInventorySourceParsingBindingAudit',
|
||||
'ShippingInventoryParsingProfile',
|
||||
'ShippingTemporaryInventorySession',
|
||||
'FreightRpaOnhandReportFile',
|
||||
'ShippingTaskOnhandLink',
|
||||
'FreightRpaProfile',
|
||||
'FreightRpaSource',
|
||||
'FreightRpaOnhandReportConfig',
|
||||
'FreightRpaInboundReportConfig',
|
||||
'FreightRpaInboundUnitRun',
|
||||
'FreightRpaInboundReportFile',
|
||||
'FreightRpaOutboundReportConfig',
|
||||
'FreightRpaOutboundUnitRun',
|
||||
'FreightRpaOutboundReportFile',
|
||||
'FreightRpaOnhandField',
|
||||
'FreightRpaOnhandStructureAnalysis',
|
||||
'FreightRpaOnhandRoutingRule',
|
||||
'FreightRpaOnhandRoutingRuleCondition',
|
||||
'FreightRpaOnhandRoutingRuleVersion',
|
||||
'FreightRpaOnhandExternalMapping',
|
||||
'FreightRpaOnhandConfigurationTestRun',
|
||||
'FreightRpaOnhandValidationBatch',
|
||||
'FreightRpaSourceParsingBindingAudit',
|
||||
'FreightRpaParsingProfile',
|
||||
'ShippingTemporaryOnhandSession',
|
||||
'ShippingExcelTemplate',
|
||||
'ShippingExportArtifact',
|
||||
'ShippingReservation',
|
||||
'ShippingInventoryVerification',
|
||||
'ShippingInventoryVerificationLine',
|
||||
'ShippingOnhandVerification',
|
||||
'ShippingOnhandVerificationLine',
|
||||
'ShippingExportArtifactLine',
|
||||
'ShippingUploadAttempt',
|
||||
'ShippingProcessExecution',
|
||||
@@ -406,10 +435,10 @@ __all__ = [
|
||||
'MaintenanceDevice',
|
||||
'MaintenanceRecord',
|
||||
'MaintenanceAuditLog',
|
||||
'ShippingInventoryCandidateSet',
|
||||
'ShippingInventoryCandidateSource',
|
||||
'ShippingInventoryCandidateLine',
|
||||
'ShippingTaskInventoryRpaAttempt',
|
||||
'ShippingOnhandCandidateSet',
|
||||
'ShippingOnhandCandidateSource',
|
||||
'ShippingOnhandCandidateLine',
|
||||
'FreightRpaOnhandTaskAttempt',
|
||||
'VoucherCheckProfile',
|
||||
'VoucherCheckRun',
|
||||
'VoucherCheckSubject',
|
||||
@@ -424,6 +453,12 @@ __all__ = [
|
||||
'ContractPaymentAlert',
|
||||
'ContractPaymentAlertBatch',
|
||||
'ContractPaymentSyncState',
|
||||
'EquipmentAcceptanceOrder',
|
||||
'EquipmentAcceptanceNode',
|
||||
'EquipmentAcceptanceOperator',
|
||||
'EquipmentAcceptanceSetting',
|
||||
'EquipmentAcceptanceSendFile',
|
||||
'EquipmentAcceptanceSendRecord',
|
||||
'TransferRun',
|
||||
'TransferSourceJob',
|
||||
'TransferMatching',
|
||||
@@ -432,9 +467,16 @@ __all__ = [
|
||||
'TransferAttempt',
|
||||
'TransferAuditEvent',
|
||||
'TransferArchive',
|
||||
'TransferTypeConfig',
|
||||
'TransferMovementLedger',
|
||||
'IntegrationCredentialReference',
|
||||
'IntegrationClientInstance',
|
||||
'IntegrationInterfaceDefinition',
|
||||
'IntegrationBinding',
|
||||
'IntegrationCall',
|
||||
'OrderDeliveryErpLine',
|
||||
'OrderDeliveryBatch',
|
||||
'OrderDeliveryLineState',
|
||||
'OrderDeliveryAuditEvent',
|
||||
'OrderDeliverySyncRun',
|
||||
]
|
||||
@@ -130,4 +130,8 @@ class GeneralFeedback(Base):
|
||||
feedback_module: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
content: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
source_page: Mapped[Optional[str]] = mapped_column(String(32))
|
||||
# 处理状态:pending=待处理,closed=已关闭(数据分析卡片用;默认待处理)
|
||||
status: Mapped[str] = mapped_column(String(20), default='pending', nullable=False, index=True)
|
||||
# 关闭时间:记录何时被处理/关闭,用于「本月已关闭」统计
|
||||
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
@@ -35,6 +35,7 @@ class QuickQuestion(Base):
|
||||
常用问题表
|
||||
用途:存储全局/用户常用问题;全局条目(user_id 为空)可配置标准答案并启用 FAQ 缓存命中。
|
||||
is_enabled 控制工作台首页快捷入口;cache_enabled 控制聊天是否跳过 Dify 直答,二者独立。
|
||||
fuzzy_enabled / fuzzy_threshold 控制精确未命中后的模糊兜底直答(逐条目独立,阈值钳制在 0.5~1.0)。
|
||||
"""
|
||||
|
||||
__tablename__ = 'quick_questions'
|
||||
@@ -48,6 +49,8 @@ class QuickQuestion(Base):
|
||||
aliases: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
cache_enabled: Mapped[bool] = mapped_column(default=False)
|
||||
is_enabled: Mapped[bool] = mapped_column(default=True)
|
||||
fuzzy_enabled: Mapped[bool] = mapped_column(default=False)
|
||||
fuzzy_threshold: Mapped[float] = mapped_column(default=0.80)
|
||||
hit_count: Mapped[int] = mapped_column(default=0)
|
||||
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
source_kb_document_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
"""
|
||||
backend/app/models/equipment_acceptance.py
|
||||
|
||||
用途:设备验收预警的本地同步快照和可改配置。
|
||||
依赖:models.base.Base、users。
|
||||
逻辑:同步服务按流程实例 request_id upsert 主表,并整批替换当前节点和操作人子表。
|
||||
配置表存四档天数、第 4 轮是否启用,以及三个固定岗位的系统用户。发送时刻不在这张表。
|
||||
发送记录按验收单和档位留一行。已发送和已取消的姓名不回写;待发送每次扫描重算。
|
||||
发给每位收件人的 Excel 另存一行,并用 send_record_ids 挂回发送记录,供表格列下载。
|
||||
不保存流程编号、第二合同编号、验收日期和 isremark。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import JSON, BigInteger, Boolean, DateTime, ForeignKey, Index, LargeBinary, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class EquipmentAcceptanceOrder(Base):
|
||||
"""一张验收单的最近一次同步结果。流程实例 request_id 唯一。"""
|
||||
|
||||
__tablename__ = "equipment_acceptance_orders"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("request_id", name="uq_equipment_acceptance_orders_request_id"),
|
||||
Index("ix_equipment_acceptance_orders_status", "monitor_status"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
acceptance_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
purchase_order_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
contract_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
timer_started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
dwell_days: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
can_accept: Mapped[Optional[int]] = mapped_column(
|
||||
nullable=True,
|
||||
comment="是否可以正常验收。0 否,1 是。空表示未标明。由 OA sfkyzcys 翻转,OA 为 0 是、1 否。",
|
||||
)
|
||||
cannot_accept_note: Mapped[Optional[str]] = mapped_column(
|
||||
Text,
|
||||
nullable=True,
|
||||
comment="无法验收说明正文,来自 OA ft_gdzcysdv2.ycsm。只留痕,不单独触发停表。",
|
||||
)
|
||||
is_returned: Mapped[Optional[int]] = mapped_column(
|
||||
nullable=True,
|
||||
comment="是否退回。0 否,1 是。由 OA sfzfth 翻转,OA 为 0 是、1 否;OA 空值收成 0。",
|
||||
)
|
||||
flow_status_raw: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
request_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||
request_match_count: Mapped[int] = mapped_column(nullable=False, default=0)
|
||||
owner_oa_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
|
||||
owner_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
owner_job_num: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
equip_oa_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
|
||||
equip_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
equip_job_num: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
applicant_oa_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
|
||||
applicant_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
applicant_job_num: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
monitor_status: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||
present_in_source: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
|
||||
synced_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
|
||||
)
|
||||
|
||||
|
||||
class EquipmentAcceptanceNode(Base):
|
||||
"""同步时看到的当前节点。一条流程可以有多行。"""
|
||||
|
||||
__tablename__ = "equipment_acceptance_nodes"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("order_id", "node_id", name="uq_equipment_acceptance_nodes_order_node"),
|
||||
Index("ix_equipment_acceptance_nodes_order", "order_id"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
order_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("equipment_acceptance_orders.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
node_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||
node_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
node_type: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
|
||||
|
||||
class EquipmentAcceptanceOperator(Base):
|
||||
"""当前节点上的操作人。同一节点同一人只留一行。不保存 isremark。"""
|
||||
|
||||
__tablename__ = "equipment_acceptance_operators"
|
||||
__table_args__ = (
|
||||
Index("ix_equipment_acceptance_operators_order", "order_id"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
order_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("equipment_acceptance_orders.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
node_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||
user_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||
handler_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
handler_job_num: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
|
||||
|
||||
class EquipmentAcceptanceSetting(Base):
|
||||
"""预警配置。全表只使用 id=1 这一行。岗位存系统用户主键,姓名不入库。"""
|
||||
|
||||
__tablename__ = "equipment_acceptance_settings"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
day_1: Mapped[int] = mapped_column(nullable=False, default=30)
|
||||
day_2: Mapped[int] = mapped_column(nullable=False, default=37)
|
||||
day_3: Mapped[int] = mapped_column(nullable=False, default=44)
|
||||
day_4: Mapped[int] = mapped_column(nullable=False, default=51)
|
||||
round_4_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
buyer_manager_user_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
coo_user_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
executive_user_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
updated_by: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
|
||||
|
||||
class EquipmentAcceptanceSendRecord(Base):
|
||||
"""一张验收单某一档的发送记录。同一张单同一档只留一行。已发送后不改收件人。"""
|
||||
|
||||
__tablename__ = "equipment_acceptance_send_records"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("order_id", "tier", name="uq_equipment_acceptance_send_records_order_tier"),
|
||||
Index("ix_equipment_acceptance_send_records_created", "created_at"),
|
||||
Index("ix_equipment_acceptance_send_records_status", "status"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
order_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey("equipment_acceptance_orders.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
acceptance_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
purchase_order_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
tier: Mapped[int] = mapped_column(nullable=False)
|
||||
threshold_days: Mapped[int] = mapped_column(nullable=False)
|
||||
to_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
cc_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
recipients_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default="pending")
|
||||
sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
|
||||
|
||||
|
||||
class EquipmentAcceptanceSendFile(Base):
|
||||
"""一位收件人一次发送留下的 Excel。字节与当时发给企业微信的文件相同。"""
|
||||
|
||||
__tablename__ = "equipment_acceptance_send_files"
|
||||
__table_args__ = (
|
||||
Index("ix_equipment_acceptance_send_files_created", "created_at"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
recipient_user_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
recipient_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
excel_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
excel_file_data: Mapped[Optional[bytes]] = mapped_column(LargeBinary, nullable=True)
|
||||
excel_file_size: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
send_record_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default="sent")
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
|
||||
+145
-97
@@ -1,9 +1,11 @@
|
||||
"""
|
||||
models/shipping_inventory_config.py
|
||||
backend/app/models/freight_rpa_config.py
|
||||
|
||||
用途:定义货代库存源、RPA Profile、通用路由规则及外部系统仓库映射主数据。
|
||||
依赖:models.base.Base、SQLAlchemy ORM;凭据密文由 shipping_notice.credential_crypto 读写。
|
||||
逻辑:库存运行链路以 ShippingInventorySource.source_code 为业务主键;RPA Profile 仅提供登录连接配置,
|
||||
用途:定义货代库存源、RPA Profile、在手/入站/出站报表配置、通用路由规则及外部系统仓库映射主数据。
|
||||
依赖:models.base.Base、SQLAlchemy ORM;凭据密文由 freight_rpa.common.credential_crypto 读写。
|
||||
逻辑:库存运行链路以 FreightRpaSource.source_code 为业务主键;RPA Profile 仅提供登录连接配置;
|
||||
在手报表路径/查询条件/解析方案绑定自 s18 起归 FreightRpaOnhandReportConfig(站点行不再存这三列),
|
||||
入站/出站配置分别挂 inbound_report_config / outbound_report_config 一对一关系;
|
||||
外部系统映射仅供后端内部复用,不承载调拨决策。
|
||||
"""
|
||||
|
||||
@@ -18,18 +20,18 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingInventoryField(Base):
|
||||
class FreightRpaOnhandField(Base):
|
||||
"""用户维护的库存业务字段目录;程序仅依据字段 ID 和业务用途运行。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_fields'
|
||||
__tablename__ = 'freight_rpa_onhand_fields'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('field_code', name='uq_shipping_inventory_fields_code'),
|
||||
UniqueConstraint('display_name', name='uq_shipping_inventory_fields_display_name'),
|
||||
CheckConstraint("status IN ('active', 'retired')", name='ck_shipping_inventory_fields_status'),
|
||||
CheckConstraint("value_type IN ('text', 'integer', 'decimal', 'date')", name='ck_shipping_inventory_fields_value_type'),
|
||||
UniqueConstraint('field_code', name='uq_freight_rpa_onhand_fields_code'),
|
||||
UniqueConstraint('display_name', name='uq_freight_rpa_onhand_fields_display_name'),
|
||||
CheckConstraint("status IN ('active', 'retired')", name='ck_freight_rpa_onhand_fields_status'),
|
||||
CheckConstraint("value_type IN ('text', 'integer', 'decimal', 'date')", name='ck_freight_rpa_onhand_fields_value_type'),
|
||||
CheckConstraint(
|
||||
"usage_type IN ('match_identity', 'inventory_quantity', 'warehouse_identity', 'general')",
|
||||
name='ck_shipping_inventory_fields_usage_type',
|
||||
name='ck_freight_rpa_onhand_fields_usage_type',
|
||||
),
|
||||
)
|
||||
|
||||
@@ -48,13 +50,13 @@ class ShippingInventoryField(Base):
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ShippingRpaProfile(Base):
|
||||
class FreightRpaProfile(Base):
|
||||
"""货代库存登录连接配置;凭据字段始终保存密文。"""
|
||||
|
||||
__tablename__ = 'shipping_rpa_profiles'
|
||||
__tablename__ = 'freight_rpa_profiles'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('profile_code', name='uq_shipping_rpa_profiles_profile_code'),
|
||||
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_shipping_rpa_profiles_connector_type'),
|
||||
UniqueConstraint('profile_code', name='uq_freight_rpa_profiles_profile_code'),
|
||||
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_freight_rpa_profiles_connector_type'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -67,11 +69,9 @@ class ShippingRpaProfile(Base):
|
||||
login_config_json: Mapped[dict[str, Any]] = mapped_column(
|
||||
JSON, default=lambda: {'auth_mode': 'password'}, nullable=False,
|
||||
)
|
||||
# 连接级“发货 Excel 自动上传”配置。先使用 login_url 登录,再访问 upload_config_json.entry_url 进入上传页;
|
||||
# 上传配置由管理端表单编辑,后端白名单校验后保存为受限 JSON。白名单字段仅
|
||||
# enabled / entry_url / file_input_selector / submit_mode / submit_selector /
|
||||
# result_mode / result_selector / success_texts / timeout_seconds。
|
||||
# 一条连接只保存一份上传配置;该配置变更不递增 config_version(见 admin 服务)。
|
||||
# 连接级“发货 Excel 自动上传”开关。只保存 {enabled}。
|
||||
# 上传页、文件控件、提交和成功判断在连接器代码里,由 login_url 的主机拼出入口。
|
||||
# 该配置变更不递增 config_version(见 admin 服务)。
|
||||
upload_config_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
|
||||
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||
@@ -81,24 +81,24 @@ class ShippingRpaProfile(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='rpa_profile')
|
||||
sources: Mapped[list['FreightRpaSource']] = relationship(back_populates='rpa_profile')
|
||||
|
||||
|
||||
class ShippingInventorySource(Base):
|
||||
class FreightRpaSource(Base):
|
||||
"""库存业务来源;固定仓或库存行动态解析 Warehouse。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_sources'
|
||||
__tablename__ = 'freight_rpa_sources'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('source_code', name='uq_shipping_inventory_sources_source_code'),
|
||||
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_shipping_inventory_sources_connector_type'),
|
||||
UniqueConstraint('source_code', name='uq_freight_rpa_sources_source_code'),
|
||||
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_freight_rpa_sources_connector_type'),
|
||||
CheckConstraint(
|
||||
"(warehouse_resolution_mode = 'fixed' AND fixed_warehouse_id IS NOT NULL) "
|
||||
"OR (warehouse_resolution_mode = 'inventory_match' AND fixed_warehouse_id IS NULL)",
|
||||
name='ck_shipping_inventory_sources_warehouse_mode',
|
||||
name='ck_freight_rpa_sources_warehouse_mode',
|
||||
),
|
||||
CheckConstraint(
|
||||
"enabled = false OR (parsing_profile_id IS NOT NULL AND excel_template_id IS NOT NULL)",
|
||||
name='ck_shipping_inventory_sources_enabled_bindings',
|
||||
"enabled = false OR excel_template_id IS NOT NULL",
|
||||
name='ck_freight_rpa_sources_enabled_template',
|
||||
),
|
||||
)
|
||||
|
||||
@@ -106,14 +106,12 @@ class ShippingInventorySource(Base):
|
||||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
connector_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
rpa_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_rpa_profiles.id'), nullable=False, index=True)
|
||||
parsing_profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True)
|
||||
rpa_profile_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_profiles.id'), nullable=False, index=True)
|
||||
excel_template_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=True, index=True)
|
||||
warehouse_resolution_mode: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
fixed_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
# 业务报表定义属于 Source;Driver 的 selector、等待与下载实现不进入数据库配置。
|
||||
report_path_json: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict, server_default=text("'{}'"), nullable=False)
|
||||
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, default=list, server_default=text("'[]'"), nullable=False)
|
||||
# 业务报表定义自 s18 起搬到 FreightRpaOnhandReportConfig(路径、查询条件、解析方案绑定);
|
||||
# CHECK 不能跨表,模板绑定仍留在站点行的启用约束上,解析方案存在性由保存站点的服务校验。
|
||||
snapshot_ttl_seconds: Mapped[int] = mapped_column(Integer, default=86400, server_default=text('86400'), nullable=False)
|
||||
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
|
||||
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||
@@ -122,31 +120,75 @@ class ShippingInventorySource(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
rpa_profile: Mapped[ShippingRpaProfile] = relationship(back_populates='sources')
|
||||
parsing_profile: Mapped[Optional['ShippingInventoryParsingProfile']] = relationship(back_populates='sources')
|
||||
rpa_profile: Mapped[FreightRpaProfile] = relationship(back_populates='sources')
|
||||
excel_template: Mapped[Optional['ShippingExcelTemplate']] = relationship(back_populates='sources')
|
||||
external_mappings: Mapped[list['ShippingInventoryExternalMapping']] = relationship(
|
||||
back_populates='inventory_source', cascade='all, delete-orphan'
|
||||
onhand_report_config: Mapped[Optional['FreightRpaOnhandReportConfig']] = relationship(
|
||||
back_populates='source', uselist=False, cascade='all, delete-orphan',
|
||||
)
|
||||
receipt_report_config: Mapped[Optional['ShippingReceiptReportConfig']] = relationship(
|
||||
back_populates='inventory_source', uselist=False, cascade='all, delete-orphan',
|
||||
external_mappings: Mapped[list['FreightRpaOnhandExternalMapping']] = relationship(
|
||||
back_populates='source', cascade='all, delete-orphan'
|
||||
)
|
||||
inbound_report_config: Mapped[Optional['FreightRpaInboundReportConfig']] = relationship(
|
||||
back_populates='source', uselist=False, cascade='all, delete-orphan',
|
||||
)
|
||||
outbound_report_config: Mapped[Optional['FreightRpaOutboundReportConfig']] = relationship(
|
||||
back_populates='source', uselist=False, cascade='all, delete-orphan',
|
||||
)
|
||||
|
||||
|
||||
class ShippingInventorySourceParsingBindingAudit(Base):
|
||||
"""库存站点解析方案绑定的只追加审计;保存绑定前后快照以支持上线追溯。"""
|
||||
class FreightRpaOnhandReportConfig(Base):
|
||||
"""库存站点的一对一在手报表配置;报表路径与查询条件归 RPA 域。
|
||||
|
||||
__tablename__ = 'shipping_inventory_source_parsing_binding_audits'
|
||||
解析方案绑定随本表保存(purpose='onhand')。站点启用要求「本配置存在且
|
||||
parsing_profile_id 非空」,PostgreSQL CHECK 不能跨表,该校验由保存站点的服务执行。
|
||||
"""
|
||||
|
||||
__tablename__ = 'freight_rpa_onhand_report_configs'
|
||||
__table_args__ = (
|
||||
Index('ix_inventory_source_parsing_binding_audit_source_created', 'inventory_source_id', 'created_at'),
|
||||
UniqueConstraint('source_id', name='uq_freight_rpa_onhand_report_configs_source'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False)
|
||||
previous_parsing_profile_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True,
|
||||
# 站点删除时配置行级联删除(与迁移端 fk_freight_rpa_onhand_report_configs_source 的 ondelete 一致)。
|
||||
source_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('freight_rpa_sources.id', ondelete='CASCADE'), nullable=False, index=True,
|
||||
)
|
||||
parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=False)
|
||||
# 在手报表文件解析规则(purpose='onhand');空则站点不得启用(服务层校验)。
|
||||
parsing_profile_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('freight_rpa_parsing_profiles.id'), nullable=True, index=True,
|
||||
)
|
||||
# 业务报表定义属于配置行;Driver 的 selector、等待与下载实现不进入数据库配置。
|
||||
report_path_json: Mapped[dict[str, Any]] = mapped_column(
|
||||
JSON, default=dict, server_default=text("'{}'"), nullable=False,
|
||||
)
|
||||
# 与入站同构:查询条件原样下发 Worker;空条件表示页面默认。
|
||||
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(
|
||||
JSON, default=list, server_default=text("'[]'"), nullable=False,
|
||||
)
|
||||
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
source: Mapped['FreightRpaSource'] = relationship(back_populates='onhand_report_config')
|
||||
parsing_profile: Mapped[Optional['FreightRpaParsingProfile']] = relationship(back_populates='sources')
|
||||
|
||||
|
||||
class FreightRpaSourceParsingBindingAudit(Base):
|
||||
"""库存站点解析方案绑定的只追加审计;保存绑定前后快照以支持上线追溯。"""
|
||||
|
||||
__tablename__ = 'freight_rpa_onhand_source_parsing_binding_audits'
|
||||
__table_args__ = (
|
||||
Index('ix_inventory_source_parsing_binding_audit_source_created', 'source_id', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False)
|
||||
previous_parsing_profile_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('freight_rpa_parsing_profiles.id'), nullable=True,
|
||||
)
|
||||
parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_parsing_profiles.id'), nullable=False)
|
||||
operation: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
reason: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
@@ -157,31 +199,32 @@ class ShippingInventorySourceParsingBindingAudit(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ShippingInventoryParsingProfile(Base):
|
||||
"""可跨源复用的通用文件解析规则(库存/异动按 purpose 区分)。
|
||||
class FreightRpaParsingProfile(Base):
|
||||
"""可跨源复用的通用文件解析规则(在手/入站/出站按 purpose 区分)。
|
||||
|
||||
注意:表名中的 inventory 是历史命名——本表实为"通用文件解析规则表",
|
||||
用途以 purpose 字段为准,勿按表名推断只服务库存。
|
||||
purpose='inventory':端点用 ShippingInventoryField 库存字段目录(既有语义);
|
||||
purpose='movement':端点用定死领域字段(MOVEMENT_FIELDS,doc_no/line_no/.../movement_date),
|
||||
供收料/异动文件映射,不依赖库存字段目录。校验逻辑按 purpose 分支。
|
||||
绑定入口:库存站点 ShippingInventorySource.parsing_profile_id /
|
||||
收料配置 ShippingReceiptReportConfig.parsing_profile_id(后者必须 purpose='movement')。
|
||||
表 freight_rpa_parsing_profiles 按 purpose 服务在手/入站/出站。
|
||||
purpose='onhand':在手库存文件,端点用 FreightRpaOnhandField 库存字段目录;
|
||||
purpose='inbound':入站文件,端点用定死领域字段
|
||||
(MOVEMENT_FIELDS,doc_no/line_no/.../movement_date),
|
||||
不依赖库存字段目录。校验逻辑按 purpose 分支。
|
||||
绑定入口:在手配置 FreightRpaOnhandReportConfig.parsing_profile_id /
|
||||
入站配置 FreightRpaInboundReportConfig.parsing_profile_id(后者必须 purpose='inbound');
|
||||
purpose='outbound':出站文件,结构就位(白名单放行,暂无运行时消费方)。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_parsing_profiles'
|
||||
__tablename__ = 'freight_rpa_parsing_profiles'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('profile_code', 'version', name='uq_inventory_parsing_profiles_code_version'),
|
||||
Index('ix_inv_parse_profile_exact_fp', 'exact_structure_fingerprint'),
|
||||
Index('ix_inv_parse_profile_compat_fp', 'compatibility_fingerprint'),
|
||||
CheckConstraint(
|
||||
"purpose IN ('inventory', 'movement')",
|
||||
name='ck_shipping_inventory_parsing_profiles_purpose',
|
||||
"purpose IN ('onhand', 'inbound', 'outbound')",
|
||||
name='ck_freight_rpa_parsing_profiles_purpose',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
purpose: Mapped[str] = mapped_column(String(16), nullable=False, default='inventory', server_default='inventory')
|
||||
purpose: Mapped[str] = mapped_column(String(16), nullable=False, default='onhand', server_default='onhand')
|
||||
profile_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
|
||||
@@ -195,7 +238,7 @@ class ShippingInventoryParsingProfile(Base):
|
||||
fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
# Draft and published definitions keep their analysed sample evidence without retaining the full uploaded workbook.
|
||||
sample_analysis_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True, index=True,
|
||||
ForeignKey('freight_rpa_onhand_structure_analyses.id'), nullable=True, index=True,
|
||||
)
|
||||
# Preserve every confirmed evidence switch so a draft remains explainable after samples change.
|
||||
sample_evidence_history_json: Mapped[list[dict[str, Any]]] = mapped_column(
|
||||
@@ -206,16 +249,17 @@ class ShippingInventoryParsingProfile(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='parsing_profile')
|
||||
sample_analysis: Mapped[Optional['ShippingInventoryStructureAnalysis']] = relationship(
|
||||
# s18 起站点行不再绑定解析方案;在手配置行(FreightRpaOnhandReportConfig)是 onhand 侧的唯一挂点。
|
||||
sources: Mapped[list['FreightRpaOnhandReportConfig']] = relationship(back_populates='parsing_profile')
|
||||
sample_analysis: Mapped[Optional['FreightRpaOnhandStructureAnalysis']] = relationship(
|
||||
foreign_keys=[sample_analysis_id],
|
||||
)
|
||||
|
||||
|
||||
class ShippingInventoryStructureAnalysis(Base):
|
||||
class FreightRpaOnhandStructureAnalysis(Base):
|
||||
"""库存文件结构分析记录;保存脱敏结构证据,不承载正式库存快照。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_structure_analyses'
|
||||
__tablename__ = 'freight_rpa_onhand_structure_analyses'
|
||||
__table_args__ = (
|
||||
Index('ix_inv_structure_analysis_file_hash', 'file_checksum'),
|
||||
Index('ix_inv_structure_analysis_created', 'created_at'),
|
||||
@@ -243,24 +287,28 @@ class ShippingInventoryStructureAnalysis(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ShippingInventoryConfigurationTestRun(Base):
|
||||
class FreightRpaOnhandConfigurationTestRun(Base):
|
||||
"""库存站点配置测试的异步 RPA 运行;锁定站点和连接配置版本且不进入生产库存池。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_configuration_test_runs'
|
||||
__table_args__ = (UniqueConstraint('run_no', name='uq_inventory_configuration_test_runs_run_no'),)
|
||||
__tablename__ = 'freight_rpa_onhand_configuration_test_runs'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('run_no', name='uq_inventory_configuration_test_runs_run_no'),
|
||||
# PostgreSQL 标识符上限 63。index=True 会生成 65 字节的自动名,故用显式短名。
|
||||
Index('ix_fr_onhand_cfg_test_runs_validation_batch_id', 'validation_batch_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
validation_batch_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_inventory_validation_batches.id'), nullable=True, index=True,
|
||||
ForeignKey('freight_rpa_onhand_validation_batches.id'), nullable=True,
|
||||
)
|
||||
rpa_batch_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True)
|
||||
source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False, index=True)
|
||||
source_config_version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
rpa_profile_config_version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='awaiting_rpa', server_default='awaiting_rpa')
|
||||
stage: Mapped[str] = mapped_column(String(32), nullable=False, default='waiting_worker', server_default='waiting_worker')
|
||||
analysis_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True)
|
||||
analysis_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_structure_analyses.id'), nullable=True)
|
||||
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
@@ -268,10 +316,10 @@ class ShippingInventoryConfigurationTestRun(Base):
|
||||
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
|
||||
class ShippingInventoryValidationBatch(Base):
|
||||
class FreightRpaOnhandValidationBatch(Base):
|
||||
"""库存站点批量验证的聚合运行;逐站点结果仍由 ConfigurationTestRun 保存。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_validation_batches'
|
||||
__tablename__ = 'freight_rpa_onhand_validation_batches'
|
||||
__table_args__ = (UniqueConstraint('batch_no', name='uq_inventory_validation_batches_batch_no'),)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -284,21 +332,21 @@ class ShippingInventoryValidationBatch(Base):
|
||||
stale_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
retry_of_batch_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_inventory_validation_batches.id'), nullable=True,
|
||||
ForeignKey('freight_rpa_onhand_validation_batches.id'), nullable=True,
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
|
||||
class ShippingInventoryRoutingRule(Base):
|
||||
class FreightRpaOnhandRoutingRule(Base):
|
||||
"""可版本化的库存源路由决策表;仅产出受控 Source 候选。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_routing_rules'
|
||||
__tablename__ = 'freight_rpa_onhand_routing_rules'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('rule_code', 'version', name='uq_shipping_inventory_routing_rules_code_version'),
|
||||
CheckConstraint("scope IN ('task', 'line')", name='ck_shipping_inventory_routing_rules_scope'),
|
||||
CheckConstraint("match_mode IN ('all', 'any')", name='ck_shipping_inventory_routing_rules_match_mode'),
|
||||
CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_inventory_routing_rules_status'),
|
||||
UniqueConstraint('rule_code', 'version', name='uq_freight_rpa_onhand_routing_rules_code_version'),
|
||||
CheckConstraint("scope IN ('task', 'line')", name='ck_freight_rpa_onhand_routing_rules_scope'),
|
||||
CheckConstraint("match_mode IN ('all', 'any')", name='ck_freight_rpa_onhand_routing_rules_match_mode'),
|
||||
CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_freight_rpa_onhand_routing_rules_status'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -318,17 +366,17 @@ class ShippingInventoryRoutingRule(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
conditions: Mapped[list['ShippingInventoryRoutingRuleCondition']] = relationship(
|
||||
back_populates='rule', cascade='all, delete-orphan', order_by='ShippingInventoryRoutingRuleCondition.sequence'
|
||||
conditions: Mapped[list['FreightRpaOnhandRoutingRuleCondition']] = relationship(
|
||||
back_populates='rule', cascade='all, delete-orphan', order_by='FreightRpaOnhandRoutingRuleCondition.sequence'
|
||||
)
|
||||
|
||||
|
||||
class ShippingInventoryRoutingRuleCondition(Base):
|
||||
class FreightRpaOnhandRoutingRuleCondition(Base):
|
||||
"""库存源路由条件;仅引用已发布订单 Schema 的稳定 field_id。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_routing_rule_conditions'
|
||||
__tablename__ = 'freight_rpa_onhand_routing_rule_conditions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('rule_id', 'sequence', name='uq_shipping_inventory_routing_rule_conditions_sequence'),
|
||||
UniqueConstraint('rule_id', 'sequence', name='uq_freight_rpa_onhand_routing_rule_conditions_sequence'),
|
||||
CheckConstraint(
|
||||
"source_kind = 'order_field' AND order_field_id IS NOT NULL",
|
||||
name='ck_inventory_routing_condition_source',
|
||||
@@ -336,7 +384,7 @@ class ShippingInventoryRoutingRuleCondition(Base):
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
rule_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_routing_rules.id'), nullable=False, index=True)
|
||||
rule_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_routing_rules.id'), nullable=False, index=True)
|
||||
condition_group: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||
source_kind: Mapped[str] = mapped_column(String(16), nullable=False, default='order_field')
|
||||
order_field_id: Mapped[Optional[str]] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=True)
|
||||
@@ -344,24 +392,24 @@ class ShippingInventoryRoutingRuleCondition(Base):
|
||||
expected_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
|
||||
sequence: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
|
||||
rule: Mapped[ShippingInventoryRoutingRule] = relationship(back_populates='conditions')
|
||||
rule: Mapped[FreightRpaOnhandRoutingRule] = relationship(back_populates='conditions')
|
||||
|
||||
|
||||
class ShippingInventoryRoutingRuleVersion(Base):
|
||||
class FreightRpaOnhandRoutingRuleVersion(Base):
|
||||
"""已发布路由规则的不可变定义快照,供任务审计回放使用。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_routing_rule_versions'
|
||||
__table_args__ = (UniqueConstraint('rule_id', 'version', name='uq_shipping_inventory_routing_rule_versions_rule_version'),)
|
||||
__tablename__ = 'freight_rpa_onhand_routing_rule_versions'
|
||||
__table_args__ = (UniqueConstraint('rule_id', 'version', name='uq_freight_rpa_onhand_routing_rule_versions_rule_version'),)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
rule_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_routing_rules.id'), nullable=False, index=True)
|
||||
rule_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_routing_rules.id'), nullable=False, index=True)
|
||||
version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False)
|
||||
published_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
published_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ShippingInventoryExternalMapping(Base):
|
||||
class FreightRpaOnhandExternalMapping(Base):
|
||||
"""库存源到外部系统仓库的映射。
|
||||
|
||||
freight_warehouse_id(货代仓库)为可选维度:inventory_match 源用它匹配收料文件
|
||||
@@ -371,18 +419,18 @@ class ShippingInventoryExternalMapping(Base):
|
||||
(in_transit_transfer DefaultRouteResolver),保存端必填,库内空串仅为存量行兼容。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_external_mappings'
|
||||
__tablename__ = 'freight_rpa_onhand_external_mappings'
|
||||
__table_args__ = (
|
||||
Index(
|
||||
'uq_shipping_inv_ext_map_src_default_enabled',
|
||||
'inventory_source_id',
|
||||
'source_id',
|
||||
unique=True,
|
||||
postgresql_where=text('freight_warehouse_id IS NULL AND enabled = true'),
|
||||
sqlite_where=text('freight_warehouse_id IS NULL AND enabled = 1'),
|
||||
),
|
||||
Index(
|
||||
'uq_shipping_inv_ext_map_src_wh_enabled',
|
||||
'inventory_source_id',
|
||||
'source_id',
|
||||
'freight_warehouse_id',
|
||||
unique=True,
|
||||
postgresql_where=text('freight_warehouse_id IS NOT NULL AND enabled = true'),
|
||||
@@ -391,7 +439,7 @@ class ShippingInventoryExternalMapping(Base):
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True)
|
||||
source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False, index=True)
|
||||
freight_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
external_system_code: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
external_organization_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
@@ -407,4 +455,4 @@ class ShippingInventoryExternalMapping(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
inventory_source: Mapped[ShippingInventorySource] = relationship(back_populates='external_mappings')
|
||||
source: Mapped[FreightRpaSource] = relationship(back_populates='external_mappings')
|
||||
@@ -0,0 +1,128 @@
|
||||
"""
|
||||
backend/app/models/freight_rpa_inbound_report.py
|
||||
|
||||
用途:入站报表 RPA 的配置、运行与归档持久化模型(per-file 企微投递表已拆除,见 Task 4 迁移)。
|
||||
依赖:freight_rpa_sources、排程运行、freight_rpa_parsing_profiles、SQLAlchemy Base;完整操作追溯统一写入 ShippingAuditEvent。
|
||||
逻辑:模型只复用站点连接资料,通过独立外键与唯一约束隔离在手快照、匹配和旧 RPA Worker 链路。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class FreightRpaInboundReportConfig(Base):
|
||||
"""库存站点的一对一收料报表配置;路径和条件始终独立于库存配置。"""
|
||||
|
||||
__tablename__ = 'freight_rpa_inbound_report_configs'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('source_id', name='uq_freight_rpa_inbound_report_configs_source'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
source_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('freight_rpa_sources.id'), nullable=False, index=True,
|
||||
)
|
||||
# 收料不设独立启停:是否运行统一由库存站点 enabled 与本配置是否存在决定。
|
||||
# 收料文件解析规则(purpose='inbound');定死领域字段端点。空则无法解析收料文件。
|
||||
parsing_profile_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('freight_rpa_parsing_profiles.id'), nullable=True, index=True,
|
||||
)
|
||||
report_path_json: Mapped[dict[str, Any]] = mapped_column(
|
||||
JSON, default=dict, server_default=text("'{}'"), nullable=False,
|
||||
)
|
||||
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(
|
||||
JSON, default=list, server_default=text("'[]'"), nullable=False,
|
||||
)
|
||||
# 与库存同构:查询条件原样下发 Worker;空条件表示页面默认。排程一源一单元,不按仓拆分。
|
||||
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
source: Mapped['FreightRpaSource'] = relationship(back_populates='inbound_report_config')
|
||||
parsing_profile: Mapped[Optional['FreightRpaParsingProfile']] = relationship()
|
||||
|
||||
|
||||
class FreightRpaInboundUnitRun(Base):
|
||||
"""一次收料执行的站点或站点-Warehouse 不可重复执行单元。
|
||||
|
||||
schedule_run_id 指向排程 run;调拨按需触发(重试/预检补抓)无排程,保持 NULL。
|
||||
"""
|
||||
|
||||
__tablename__ = 'freight_rpa_inbound_rpa_unit_runs'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('callback_id', name='uq_freight_rpa_inbound_rpa_unit_runs_callback'),
|
||||
CheckConstraint(
|
||||
"status IN ('queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled')",
|
||||
name='ck_freight_rpa_inbound_rpa_unit_runs_status',
|
||||
),
|
||||
Index('ix_shipping_receipt_unit_run_schedule_status', 'schedule_run_id', 'status'),
|
||||
Index('ix_shipping_receipt_unit_run_source_created', 'source_id', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
schedule_run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_runs.id'), nullable=True, index=True)
|
||||
source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False, index=True)
|
||||
retry_of_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('freight_rpa_inbound_rpa_unit_runs.id'), nullable=True, index=True,
|
||||
)
|
||||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
connector_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
callback_id: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
||||
config_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
trigger_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
schedule_run: Mapped[Optional['ScheduleRun']] = relationship(foreign_keys=[schedule_run_id])
|
||||
source: Mapped['FreightRpaSource'] = relationship()
|
||||
retry_of: Mapped[Optional['FreightRpaInboundUnitRun']] = relationship(remote_side=[id])
|
||||
files: Mapped[list['FreightRpaInboundReportFile']] = relationship(
|
||||
back_populates='unit_run', cascade='all, delete-orphan',
|
||||
)
|
||||
|
||||
|
||||
class FreightRpaInboundReportFile(Base):
|
||||
"""收料原样归档文件;保留文件身份和对象清理事实,不关联库存快照。"""
|
||||
|
||||
__tablename__ = 'freight_rpa_inbound_report_files'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('unit_run_id', 'sha256', name='uq_freight_rpa_inbound_report_files_unit_sha256'),
|
||||
CheckConstraint("file_size >= 0", name='ck_freight_rpa_inbound_report_files_size'),
|
||||
Index('ix_freight_rpa_inbound_report_files_unit', 'unit_run_id'),
|
||||
Index('ix_freight_rpa_inbound_report_files_expires', 'archive_expires_at', 'archive_deleted_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
unit_run_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_inbound_rpa_unit_runs.id'), nullable=False, index=True)
|
||||
storage_provider: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
storage_key: Mapped[str] = mapped_column(String(1024), nullable=False)
|
||||
original_filename: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
content_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
file_size: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
sha256: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
# 解析失败分层标记:归档文件解析失败时写入;三者全空=未失败/已清除。
|
||||
parse_failed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
parse_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
parse_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
archive_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
archive_deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
archive_delete_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
unit_run: Mapped[FreightRpaInboundUnitRun] = relationship(back_populates='files')
|
||||
+9
-9
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
models/shipping_inventory_mapping.py
|
||||
backend/app/models/freight_rpa_onhand_mapping.py
|
||||
|
||||
用途:保存不可变库存字段映射版本。
|
||||
依赖:ShippingInventoryFile、ShippingInventoryParsingProfile、Base。
|
||||
依赖:FreightRpaOnhandReportFile、FreightRpaParsingProfile、Base。
|
||||
逻辑:每次确认/重跑创建新版本,匹配 Attempt 通过 mapping_id 精确引用。
|
||||
"""
|
||||
|
||||
@@ -17,24 +17,24 @@ from sqlalchemy.orm import Mapped, mapped_column
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingInventoryMapping(Base):
|
||||
class FreightRpaOnhandMapping(Base):
|
||||
"""库存文件的不可变字段映射版本。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_mappings'
|
||||
__tablename__ = 'freight_rpa_onhand_mappings'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('inventory_file_id', 'version', name='uq_shipping_inventory_mapping_file_version'),
|
||||
UniqueConstraint('onhand_file_id', 'version', name='uq_shipping_inventory_mapping_file_version'),
|
||||
CheckConstraint("status IN ('active','superseded','invalidated')", name='ck_shipping_inventory_mapping_status'),
|
||||
Index('ix_shipping_inventory_mapping_file_status', 'inventory_file_id', 'status'),
|
||||
Index('ix_shipping_inventory_mapping_file_status', 'onhand_file_id', 'status'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id', ondelete='CASCADE'), nullable=False)
|
||||
onhand_file_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id', ondelete='CASCADE'), nullable=False)
|
||||
version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active')
|
||||
profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id', ondelete='SET NULL'), nullable=True)
|
||||
profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_parsing_profiles.id', ondelete='SET NULL'), nullable=True)
|
||||
mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_mappings.id'), nullable=True)
|
||||
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_mappings.id'), nullable=True)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
@@ -0,0 +1,123 @@
|
||||
"""
|
||||
backend/app/models/freight_rpa_onhand_report_file.py
|
||||
|
||||
用途:货代 RPA 抓回的在手报表文件。
|
||||
依赖:models.base.Base、shipping.py 里的 ShippingTaskOnhandLink。
|
||||
逻辑:表名 freight_rpa_onhand_report_files 不变;发货任务通过 ShippingTaskOnhandLink 引用本行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
JSON,
|
||||
String,
|
||||
text,
|
||||
)
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class FreightRpaOnhandReportFile(Base):
|
||||
"""货代发货批次库存快照文件,承载一次上传后可被多票任务共用的库存数据。
|
||||
|
||||
在手文件表归货代 RPA(s18 由 shipping_onhand_files 改名而来);列不改,
|
||||
仍含解析行、字段映射与快照状态,本阶段只改表名与指向它的外键。
|
||||
"""
|
||||
|
||||
__tablename__ = 'freight_rpa_onhand_report_files'
|
||||
__table_args__ = (
|
||||
Index('ix_freight_rpa_onhand_report_files_user_created', 'user_id', 'created_at'),
|
||||
Index(
|
||||
'ix_freight_rpa_onhand_report_files_source_snapshot',
|
||||
'source_code',
|
||||
'warehouse_id',
|
||||
'snapshot_status',
|
||||
'exported_at',
|
||||
),
|
||||
Index(
|
||||
'ix_freight_rpa_onhand_report_files_source_warehouse',
|
||||
'source_code',
|
||||
'warehouse_id',
|
||||
),
|
||||
Index(
|
||||
'uq_freight_rpa_onhand_report_files_rpa_identity_ready',
|
||||
'rpa_run_no',
|
||||
'source_code',
|
||||
'warehouse_id',
|
||||
unique=True,
|
||||
postgresql_where=text(
|
||||
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
|
||||
"AND source_code IS NOT NULL AND warehouse_id IS NOT NULL"
|
||||
),
|
||||
sqlite_where=text(
|
||||
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
|
||||
"AND source_code IS NOT NULL AND warehouse_id IS NOT NULL"
|
||||
),
|
||||
),
|
||||
# 动态多仓文件没有单一 Warehouse;按 RPA run + Source 保证回调重放幂等。
|
||||
Index(
|
||||
'uq_freight_rpa_onhand_report_files_rpa_dynamic_source_ready',
|
||||
'rpa_run_no',
|
||||
'source_code',
|
||||
unique=True,
|
||||
postgresql_where=text(
|
||||
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
|
||||
"AND source_code IS NOT NULL AND warehouse_id IS NULL"
|
||||
),
|
||||
sqlite_where=text(
|
||||
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
|
||||
"AND source_code IS NOT NULL AND warehouse_id IS NULL"
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
onhand_file_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
|
||||
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
storage_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
schema_preview_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
field_mapping_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
mapping_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
mapping_confirmed: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
|
||||
onhand_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
line_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
share_mode: Mapped[str] = mapped_column(String(32), default='task_only')
|
||||
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
identity_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
|
||||
source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
snapshot_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
|
||||
exported_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
|
||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
|
||||
rpa_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
schedule_run_id: Mapped[Optional[int]] = mapped_column(nullable=True, index=True)
|
||||
source_query_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id'), nullable=True)
|
||||
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
|
||||
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
|
||||
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
links: Mapped[List['ShippingTaskOnhandLink']] = relationship(
|
||||
'ShippingTaskOnhandLink',
|
||||
back_populates='inventory_file',
|
||||
cascade='all, delete-orphan',
|
||||
)
|
||||
+4
-4
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
models/shipping_task_inventory_rpa_attempts.py
|
||||
backend/app/models/freight_rpa_onhand_task_attempts.py
|
||||
|
||||
用途:逐库存源的 RPA 导出 Attempt 结构化记录(决策 D1/D2 三元组幂等)。
|
||||
依赖:Base、ShippingNotice(task_no FK 可选直连 id 先保留 task_no 字符串关联)、users。
|
||||
@@ -47,10 +47,10 @@ PER_SOURCE_RPA_ATTEMPT_STATUSES = (
|
||||
)
|
||||
|
||||
|
||||
class ShippingTaskInventoryRpaAttempt(Base):
|
||||
class FreightRpaOnhandTaskAttempt(Base):
|
||||
"""逐 (task_no, source_code) 的库存 RPA 导出 Attempt 记录。"""
|
||||
|
||||
__tablename__ = 'shipping_task_inventory_rpa_attempts'
|
||||
__tablename__ = 'freight_rpa_onhand_task_rpa_attempts'
|
||||
__table_args__ = (
|
||||
# 三元组唯一:同一运行号同一源只允许一条记录
|
||||
UniqueConstraint('task_no', 'source_code', 'source_run_no', name='uq_shipping_task_inv_rpa_triplet'),
|
||||
@@ -87,7 +87,7 @@ class ShippingTaskInventoryRpaAttempt(Base):
|
||||
|
||||
trigger_file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
|
||||
callback_file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
|
||||
inventory_file_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
onhand_file_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
@@ -0,0 +1,129 @@
|
||||
"""
|
||||
backend/app/models/freight_rpa_outbound_report.py
|
||||
|
||||
用途:出站报表 RPA 的配置、运行与归档持久化模型(不建 per-file 企微投递表)。
|
||||
依赖:freight_rpa_sources、排程运行、freight_rpa_parsing_profiles、SQLAlchemy Base;完整操作追溯统一写入 ShippingAuditEvent。
|
||||
逻辑:模型只复用站点连接资料,通过独立外键与唯一约束隔离在手快照、匹配和旧 RPA Worker 链路。
|
||||
FreightRpaSource.outbound_report_config 一对一回指本配置行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class FreightRpaOutboundReportConfig(Base):
|
||||
"""库存站点的一对一出站报表配置;路径和条件始终独立于库存 / 入站配置。"""
|
||||
|
||||
__tablename__ = 'freight_rpa_outbound_report_configs'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('source_id', name='uq_freight_rpa_outbound_report_configs_source'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
source_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('freight_rpa_sources.id'), nullable=False, index=True,
|
||||
)
|
||||
# 出站不设独立启停:是否运行统一由库存站点 enabled 与本配置是否存在决定。
|
||||
# 出站文件解析规则(purpose='outbound');定死领域字段端点。空则无法解析出站文件。
|
||||
parsing_profile_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('freight_rpa_parsing_profiles.id'), nullable=True, index=True,
|
||||
)
|
||||
report_path_json: Mapped[dict[str, Any]] = mapped_column(
|
||||
JSON, default=dict, server_default=text("'{}'"), nullable=False,
|
||||
)
|
||||
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(
|
||||
JSON, default=list, server_default=text("'[]'"), nullable=False,
|
||||
)
|
||||
# 与库存同构:查询条件原样下发 Worker;空条件表示页面默认。排程一源一单元,不按仓拆分。
|
||||
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
source: Mapped['FreightRpaSource'] = relationship(back_populates='outbound_report_config')
|
||||
parsing_profile: Mapped[Optional['FreightRpaParsingProfile']] = relationship()
|
||||
|
||||
|
||||
class FreightRpaOutboundUnitRun(Base):
|
||||
"""一次出站执行的站点或站点-Warehouse 不可重复执行单元。
|
||||
|
||||
schedule_run_id 指向排程 run;调拨按需触发(重试/预检补抓)无排程,保持 NULL。
|
||||
"""
|
||||
|
||||
__tablename__ = 'freight_rpa_outbound_rpa_unit_runs'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('callback_id', name='uq_freight_rpa_outbound_rpa_unit_runs_callback'),
|
||||
CheckConstraint(
|
||||
"status IN ('queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled')",
|
||||
name='ck_freight_rpa_outbound_rpa_unit_runs_status',
|
||||
),
|
||||
Index('ix_freight_rpa_outbound_unit_run_schedule_status', 'schedule_run_id', 'status'),
|
||||
Index('ix_freight_rpa_outbound_unit_run_source_created', 'source_id', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
schedule_run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_runs.id'), nullable=True, index=True)
|
||||
source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False, index=True)
|
||||
retry_of_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('freight_rpa_outbound_rpa_unit_runs.id'), nullable=True, index=True,
|
||||
)
|
||||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
connector_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
callback_id: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
||||
config_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
trigger_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
schedule_run: Mapped[Optional['ScheduleRun']] = relationship(foreign_keys=[schedule_run_id])
|
||||
source: Mapped['FreightRpaSource'] = relationship()
|
||||
retry_of: Mapped[Optional['FreightRpaOutboundUnitRun']] = relationship(remote_side=[id])
|
||||
files: Mapped[list['FreightRpaOutboundReportFile']] = relationship(
|
||||
back_populates='unit_run', cascade='all, delete-orphan',
|
||||
)
|
||||
|
||||
|
||||
class FreightRpaOutboundReportFile(Base):
|
||||
"""出站原样归档文件;保留文件身份和对象清理事实,不关联库存快照。"""
|
||||
|
||||
__tablename__ = 'freight_rpa_outbound_report_files'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('unit_run_id', 'sha256', name='uq_freight_rpa_outbound_report_files_unit_sha256'),
|
||||
CheckConstraint("file_size >= 0", name='ck_freight_rpa_outbound_report_files_size'),
|
||||
Index('ix_freight_rpa_outbound_report_files_unit', 'unit_run_id'),
|
||||
Index('ix_freight_rpa_outbound_report_files_expires', 'archive_expires_at', 'archive_deleted_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
unit_run_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_outbound_rpa_unit_runs.id'), nullable=False, index=True)
|
||||
storage_provider: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
storage_key: Mapped[str] = mapped_column(String(1024), nullable=False)
|
||||
original_filename: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
content_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
file_size: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
sha256: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
# 解析失败分层标记:归档文件解析失败时写入;三者全空=未失败/已清除。
|
||||
parse_failed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
parse_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
parse_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
archive_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
archive_deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
archive_delete_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
unit_run: Mapped[FreightRpaOutboundUnitRun] = relationship(back_populates='files')
|
||||
@@ -1,13 +1,22 @@
|
||||
"""models/in_transit_transfer.py
|
||||
|
||||
用途:在途仓自动调拨一期核心领域模型:Run、SourceJob、Matching、InvoiceItem、
|
||||
Document(ERP 调拨单)、Attempt、AuditEvent 与 Archive。
|
||||
依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁)。
|
||||
Document(ERP 调拨单)、Attempt、AuditEvent 与 Archive;另含调拨类型
|
||||
配置表 TransferTypeConfig(类型配置化,ADR 0002)与库存异动档
|
||||
TransferMovementLedger(外部系统入站/出站记录镜像,ADR 0001)。
|
||||
依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁);
|
||||
source_file_id 外键指向 freight_rpa_inbound_report_files(FreightRpaInboundReportFile 原样归档,入站证据)。
|
||||
逻辑:Run 是异步真相源;InvoiceItem 按(matching_id, invoice_no)唯一防止重复建单;
|
||||
Document(单)实现「五元组一组一单」,同组未完结单唯一由部分唯一索引在
|
||||
DB 层强制(D15 防双单兜底);单:Attempt=1:N,外键在 Attempt 侧(D14);
|
||||
Attempt 保留每次恢复/重查/执行事实,旧 Attempt 永不覆盖;
|
||||
AuditEvent 保存脱敏快照与事件 Hash,禁止更新/删除。
|
||||
AuditEvent 保存脱敏快照与事件 Hash,禁止更新/删除;
|
||||
transfer_runs.transfer_type 合法值由 TransferTypeConfig 配置承接
|
||||
(原枚举 CHECK 约束已移除);
|
||||
TransferMovementLedger 以自然键 (source_code, record_kind, doc_no,
|
||||
line_no, line_seq, in_out_flag, carton_id, lot_no) 幂等增量落地外部记录,
|
||||
已执行记录经 transfer_executed 封存(防二次调拨),来源文件删除后档事实留存
|
||||
(ON DELETE SET NULL,链接仅溯源)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -34,20 +43,16 @@ from app.core.errors import ValidationError
|
||||
from app.models.base import Base
|
||||
|
||||
# 与 services/in_transit_transfer/status.py 保持一致的冻结枚举(数据库级兜底)。
|
||||
# 【not_matured 已退役 2026-10-16】成熟概念删除,存量行经 tt16 重映射 cancelled。
|
||||
TRANSFER_ITEM_STATUSES = (
|
||||
'file_pending', 'file_ready', 'matching', 'ready_to_execute', 'executing',
|
||||
'success', 'duplicate_success', 'blocked_recoverable', 'not_matured',
|
||||
'success', 'duplicate_success', 'blocked_recoverable',
|
||||
'result_unknown', 'manually_closed', 'cancelled', 'notification_failed',
|
||||
)
|
||||
TRANSFER_RUN_STATUSES = (
|
||||
'queued', 'preparing_files', 'matching', 'ready_to_execute', 'executing',
|
||||
'success', 'partial_failed', 'failed', 'cancelled',
|
||||
)
|
||||
# 与 services/in_transit_transfer/transfer_type.py TransferType 保持一致的冻结枚举
|
||||
# (数据库级兜底);一期仅 in_transit_to_hub 进入处理链路,其余为占位值。
|
||||
TRANSFER_RUN_TYPES = (
|
||||
'in_transit_to_hub', 'hub_repair_out', 'hub_to_hub',
|
||||
)
|
||||
TRANSFER_SOURCE_JOB_STATUSES = (
|
||||
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
|
||||
'matching', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
|
||||
@@ -69,7 +74,8 @@ TRANSFER_DOCUMENT_STATUSES = (
|
||||
)
|
||||
# 未完结单状态集合(组锁生效范围,D7①/D15):同五元组存在任一未完结单时
|
||||
# 复用其 doc_no+submit_timestamp,禁止新建;部分唯一索引的 WHERE 子句由该
|
||||
# 元组生成,保证「常量集 ↔ DB 约束」永远一致(test_document_model.py 锁定)。
|
||||
# 元组生成,保证「常量集 ↔ DB 约束」永远一致(原锁定测试 test_document_model.py
|
||||
# 已删除,改动本元组时须人工核对迁移内 CHECK/WHERE 字面量同口径)。
|
||||
UNRESOLVED_DOC_STATUSES = (
|
||||
'pending', 'executing', 'result_unknown', 'business_failed', 'technical_failed',
|
||||
)
|
||||
@@ -97,10 +103,6 @@ class TransferRun(Base):
|
||||
"trigger_type IN ('manual', 'schedule')",
|
||||
name='ck_transfer_runs_trigger_type',
|
||||
),
|
||||
CheckConstraint(
|
||||
f"transfer_type IN ({', '.join(repr(t) for t in TRANSFER_RUN_TYPES)})",
|
||||
name='ck_transfer_runs_transfer_type',
|
||||
),
|
||||
Index('ix_transfer_runs_status_created', 'status', 'created_at'),
|
||||
Index('ix_transfer_runs_business_date', 'business_date'),
|
||||
)
|
||||
@@ -108,9 +110,11 @@ class TransferRun(Base):
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
trigger_type: Mapped[str] = mapped_column(String(16), nullable=False, default='manual', server_default='manual')
|
||||
# 调拨业务类型(在途仓至HUB仓/HUB仓维修出/HUB仓间调拨);决定匹配收料数据范围。
|
||||
# 调拨业务类型(合法值由 TransferTypeConfig 配置承接,合法 code 正则
|
||||
# ^[a-z][a-z0-9_]{1,63}$ 上限 64);决定匹配入站数据范围。列宽 64 与配置表
|
||||
# code 上限对齐(终审 I2:33~64 字符 code 建匹配时写 32 宽列会 DB 500)。
|
||||
transfer_type: Mapped[str] = mapped_column(
|
||||
String(32), nullable=False, default='in_transit_to_hub', server_default='in_transit_to_hub',
|
||||
String(64), nullable=False, default='in_transit_to_hub', server_default='in_transit_to_hub',
|
||||
)
|
||||
business_date: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
||||
@@ -214,15 +218,18 @@ class TransferMatching(Base):
|
||||
|
||||
|
||||
class TransferInvoiceItem(Base):
|
||||
"""匹配明细项;同一匹配内 (来源,Invoice,料号,收料日期) 唯一,保留原始行追溯。
|
||||
"""匹配明细项;同一匹配内 (来源,Invoice,料号,异动日期) 唯一,保留原始行追溯。
|
||||
|
||||
Invoice 锚定批号(2026-09-21 业务口径):同一批号跨料号/跨日期拆分为多行。
|
||||
【2026-10-14 出生翻转(ADR 0001/D4)】行不再由文件落地写入,而是匹配创建时
|
||||
从库存异动档圈定生成:ledger_record_id 指向档记录(业务字段=档原值),
|
||||
matching_id 创建即绑定(D17:一条档记录一生只生成一次 items 绑定)。
|
||||
"""
|
||||
|
||||
__tablename__ = 'transfer_invoice_items'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'matching_id', 'source_code', 'invoice_no', 'material_no', 'receipt_date',
|
||||
'matching_id', 'source_code', 'invoice_no', 'material_no', 'movement_date',
|
||||
name='uq_transfer_invoice_items_matching_grain',
|
||||
),
|
||||
CheckConstraint(
|
||||
@@ -235,33 +242,45 @@ class TransferInvoiceItem(Base):
|
||||
# 单据级执行(T10)高频「按单查行」:document_id 单列索引(控制器裁决,
|
||||
# 并入 tt0d1e2f3a4b 避免额外迁移节点)。
|
||||
Index('ix_transfer_invoice_items_document_id', 'document_id'),
|
||||
# 匹配创建圈档的占用互斥检查(D17)高频「按档记录查行」:单列索引
|
||||
# (并入 tt12c3d4e5f6a7 避免额外迁移节点)。
|
||||
Index('ix_transfer_invoice_items_ledger_record_id', 'ledger_record_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
# 行归属解耦后 matching_id 仅留痕(首次创建值);落地证据同步行尚无匹配归属
|
||||
# (2026-09-25),放开非空。uq_transfer_invoice_items_matching_grain 含本列,
|
||||
# NULL 行不受该唯一约束保护——同步的幂等去重由 evidence_sync 应用层按
|
||||
# (source, invoice, material, receipt_date) 四元组负责(见 evidence_sync)。
|
||||
# 【2026-10-14 出生翻转】matching_id 回归「创建即绑定」:行由匹配创建时从档
|
||||
# 圈定生成(落地不再写 items,见 evidence_sync/ADR 0001),新行恒非空
|
||||
# (模型层不强制 NOT NULL,存量兼容,服务层保证);D17 圈档互斥的占用判定
|
||||
# 以本列 + 所属匹配状态为准(取消匹配即释放占用)。
|
||||
matching_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_matchings.id'), nullable=True, index=True)
|
||||
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True)
|
||||
# 【2026-10-14 出生翻转】行来源档记录外键(可空:隔离的历史行允许 NULL);
|
||||
# 行上业务字段=档原值,批号等转换只在系统边界按匹配快照规则派生(不落库)。
|
||||
ledger_record_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('transfer_movement_ledger.id'), nullable=True,
|
||||
)
|
||||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
invoice_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
# 批号(External ASN 等)原值;「拨入批号」展示由 WTP→HOW 转换派生,不落库。
|
||||
lot_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(拨出库位解析审计)。
|
||||
receipt_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
||||
# 入站文件「仓库」列原值:inventory_match 源映射行匹配键(拨出库位解析审计)。
|
||||
movement_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
||||
# 交易单位原值(movement 契约第 11 字段 unit,计划 D4):解析原样保留(仅 trim,
|
||||
# 不换算);空值行在匹配阶段落 blocked_missing_unit。unit 不参与匹配 Hash(口径冻结)。
|
||||
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, default='', server_default='')
|
||||
material_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
material_name: Mapped[str] = mapped_column(String(200), nullable=False, default='')
|
||||
specification: Mapped[str] = mapped_column(String(200), nullable=False, default='')
|
||||
receipt_date: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||||
movement_date: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||||
from_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
# 数量以 Decimal 文本保存,杜绝浮点误差;比较在服务层完成。
|
||||
receipt_quantity: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||
movement_quantity: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||
external_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
# [库存查得时刻] 当前 external_quantity 的 ERP 取数时间戳(stale 徽标判定时钟,
|
||||
# 2026-09-29 起与行新鲜度 updated_at 分离:证据同步换戳/存续不续期本字段,
|
||||
# 仅匹配评估/重查/写前复查在真实取数时写入;置空库存时同步置空)。NULL=无库存数据。
|
||||
inventory_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
result_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
result_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
@@ -284,6 +303,12 @@ class TransferInvoiceItem(Base):
|
||||
# (document_id 置 NULL)回到 ready_to_execute,可被重新勾选组建新单。
|
||||
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_documents.id'), nullable=True)
|
||||
document: Mapped[Optional['TransferDocument']] = relationship(back_populates='items')
|
||||
# 【2026-10-14 改锚(规格 §10)】行 → 档记录只读导航:file_current 门禁与行装饰
|
||||
# 的版本戳取档记录 file_sha256(档记录是证据权威)。纯 ORM relationship——
|
||||
# 不新增列/索引/约束(ledger_record_id 列与索引既有),无配套迁移。
|
||||
ledger_record: Mapped[Optional['TransferMovementLedger']] = relationship(
|
||||
foreign_keys=[ledger_record_id],
|
||||
)
|
||||
|
||||
|
||||
class TransferDocument(Base):
|
||||
@@ -315,7 +340,7 @@ class TransferDocument(Base):
|
||||
# 建表同语义(部分唯一,非全组唯一)。
|
||||
Index(
|
||||
'uq_transfer_documents_group_live',
|
||||
'source_code', 'external_org', 'receipt_date', 'from_warehouse', 'to_warehouse',
|
||||
'source_code', 'external_org', 'movement_date', 'from_warehouse', 'to_warehouse',
|
||||
unique=True,
|
||||
postgresql_where=text(UNRESOLVED_DOC_STATUS_WHERE),
|
||||
sqlite_where=text(UNRESOLVED_DOC_STATUS_WHERE),
|
||||
@@ -328,7 +353,7 @@ class TransferDocument(Base):
|
||||
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True)
|
||||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
external_org: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
receipt_date: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
movement_date: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
from_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
# 提交标识(D3 终身复用):同组复用单时保持首建值不变;唯一性由
|
||||
@@ -471,6 +496,146 @@ class TransferArchive(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class TransferTypeConfig(Base):
|
||||
"""调拨类型配置(ADR 0002):编码/四语言名称/启停/排序 + 范围规则/仓库定义/转换规则。
|
||||
|
||||
code 创建后不可变(transfer_runs.transfer_type 引用);只有停用没有删除;
|
||||
配置为空时匹配链路 fail-closed(TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED)。
|
||||
"""
|
||||
|
||||
__tablename__ = 'transfer_type_configs'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('code', name='uq_transfer_type_configs_code'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
names_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
|
||||
enabled: Mapped[bool] = mapped_column(default=False, server_default=text('false'), nullable=False)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0, server_default=text('0'), nullable=False)
|
||||
scope_rules_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
|
||||
warehouse_config_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
|
||||
transform_rules_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
|
||||
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class TransferMovementLedger(Base):
|
||||
"""库存异动档(ADR 0001):外部系统入站/出站记录的平台镜像(参照 ERP inaj_t 形态)。
|
||||
|
||||
用途:外部系统入站(一期)/出站(结构就位,record_kind='outbound')记录统一落档;
|
||||
匹配明细(items)由匹配创建时从档圈定生成(落地不再写 items,出生翻转)。
|
||||
幂等增量落地:自然键 (source_code, record_kind, doc_no, line_no, line_seq,
|
||||
in_out_flag, carton_id, lot_no, external_doc_no, external_line_no) 唯一约束
|
||||
去重——不存在则插入、证据变化则原行更新、文件缺席不删(tt14 扩维:真实 WMS
|
||||
行身份=单据+行+箱/批,carton_id/lot_no 加入键防同箱/批塌缩丢行;R7 终审:
|
||||
两列同步 NOT NULL + default '',nullable 成分的 NULL 不参与 PG/SQLite 唯一
|
||||
比对会逃逸约束,空值成分一律以空串入库保证唯一约束可比;2026-10-21 再扩维:
|
||||
外部单号/外部项次=WMS Order #/Line # 入键,外部单据身份作为档幂等主键管控);
|
||||
已执行记录 transfer_executed=true 封存(executed_doc_no 回写),永不更新、
|
||||
永不复活、永不再次被圈定(防二次调拨,档级封存兜底)。
|
||||
刻意双字段:record_kind(文件种类声明,权威)与 in_out_flag(数据列原值),
|
||||
两者矛盾即解析错位,由落档链路打审计事件,记录照常落档。
|
||||
可空语义:自然键 8 成分一律 NOT NULL(line_seq/in_out_flag/carton_id/lot_no
|
||||
default '' 保证唯一约束可比、防 PG NULL 逃逸唯一比对),业务/证据列一律
|
||||
nullable(外部列宽松落地);movement_date 可空——空值记录照常落档但不进
|
||||
异动日期圈定(日期条件恒排除 NULL)。
|
||||
source_file_id ON DELETE SET NULL:来源文件被清理(文件资产保留策略)后
|
||||
档记录必须留存(事实不随文件消失,链接仅溯源)。
|
||||
D 组 ⭐5 列(order_type/odm_id/odm_name/carton_id/pallet_id)为本期新增强
|
||||
业务字段(进解析 Profile 可映射);🔖预留列(doc_nature/movement_type/
|
||||
reason_code/source_ref_no/partner_code/remark)出货报告确认后直接映射,
|
||||
免后续迁移。
|
||||
"""
|
||||
|
||||
__tablename__ = 'transfer_movement_ledger'
|
||||
__table_args__ = (
|
||||
# 自然键唯一(幂等增量落地兜底;应用层按自然键查档先行)。tt14 扩维 8 成分:
|
||||
# carton_id/lot_no 进键(真实 WMS 行身份=单据+行+箱/批),R7 终审同步
|
||||
# NOT NULL + default ''(可空成分以空串入库,防 PG NULL 逃逸唯一比对)。
|
||||
# 2026-10-21 扩维 10 成分:external_doc_no/external_line_no(外部单号/
|
||||
# 外部项次,WMS Order #/Line #)进键——外部单据身份作为档幂等主键管控,
|
||||
# 同一外部单号+项次的重复落档/证据更新收敛到同一档行(存量行以空串参与
|
||||
# 键;配置外部映射后重放同文件即按新键收敛,必要时走清空并重解析重建)。
|
||||
UniqueConstraint(
|
||||
'source_code', 'record_kind', 'doc_no', 'line_no', 'line_seq', 'in_out_flag',
|
||||
'carton_id', 'lot_no', 'external_doc_no', 'external_line_no',
|
||||
name='uq_transfer_movement_ledger_natural_key',
|
||||
),
|
||||
# 匹配创建圈档主路径:来源 + 记录种类 + 异动日期范围扫描。
|
||||
Index('ix_transfer_movement_ledger_source_kind_date', 'source_code', 'record_kind', 'movement_date'),
|
||||
# 档级封存/待匹配桶扫描:按记录种类过滤已执行位。
|
||||
Index('ix_transfer_movement_ledger_kind_executed', 'record_kind', 'transfer_executed'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
# --- A 单据标识(自然键成分,NOT NULL;line_seq/in_out_flag 可空成分 default '')---
|
||||
doc_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
line_no: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
line_seq: Mapped[str] = mapped_column(String(32), nullable=False, default='', server_default='')
|
||||
# 数据列原值(入站=收发标记),与 record_kind 交叉校验用,不参与权威判定。
|
||||
in_out_flag: Mapped[str] = mapped_column(String(8), nullable=False, default='', server_default='')
|
||||
# --- A+ 外部单据身份(2026-10-21 起入自然键:外部单号/外部项次 = WMS Order #/
|
||||
# --- 行号;NOT NULL + default '' 与 line_seq 同口径,防 NULL 逃逸唯一比对)---
|
||||
external_doc_no: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
||||
external_line_no: Mapped[str] = mapped_column(String(32), nullable=False, default='', server_default='')
|
||||
# --- B 物料与数量(数量 Decimal 文本,与 items.movement_quantity 同约定)---
|
||||
material_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
material_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
specification: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
# 批号原值(tt14 起入自然键:NOT NULL + default '' 防 PG NULL 逃逸唯一比对;
|
||||
# 空值成分以空串入库保证唯一约束可比,与 line_seq/in_out_flag 同口径)。
|
||||
lot_no: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
||||
quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
# --- C 仓储与日期(movement_date 可空:空值不进异动日期圈定)---
|
||||
warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
storage_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
movement_date: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||||
# --- D 业务属性(⭐本期新增强业务字段;carton_id tt14 起入自然键 NOT NULL
|
||||
# --- default '';🔖预留列 nullable,出货侧直接映射)---
|
||||
order_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
odm_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
odm_name: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
# 箱号(tt14 起入自然键:NOT NULL + default '',与 lot_no 同口径,防 NULL 逃逸唯一比对)。
|
||||
carton_id: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
||||
pallet_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
doc_nature: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
movement_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
reason_code: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
source_ref_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
partner_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
# --- E 平台溯源(证据字段:evidence_sync 原行更新时整体换新)---
|
||||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
# 文件种类声明(tt14 值迁移后 'inbound'/'outbound',权威);与 in_out_flag 矛盾打审计事件。
|
||||
record_kind: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
# 来源文件溯源:ON DELETE SET NULL(文件清理后档事实留存)。
|
||||
source_file_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('freight_rpa_inbound_report_files.id', ondelete='SET NULL'), nullable=True,
|
||||
)
|
||||
file_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
sheet_name: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
row_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
# --- F 平台回写(档级封存:票据执行成功落单号时回写,永不解除)---
|
||||
transfer_executed: Mapped[bool] = mapped_column(
|
||||
default=False, server_default=text('false'), nullable=False,
|
||||
)
|
||||
executed_doc_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
|
||||
# 溯源关系:档案行 → FreightRpaInboundReportFile 原样归档文件(单向,不回挂;FreightRpaInboundReportFile
|
||||
# 不感知调拨域,避免跨域 back_populates 环)。
|
||||
source_file: Mapped[Optional['FreightRpaInboundReportFile']] = relationship()
|
||||
|
||||
|
||||
@event.listens_for(TransferAuditEvent, 'before_update')
|
||||
def _reject_transfer_audit_update(_mapper, _connection, _target) -> None:
|
||||
"""拒绝 ORM 更新,确保审计事件不可改写。"""
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/models/job.py
|
||||
|
||||
用途:通用后台任务模型,承载跨业务域的异步任务执行状态。
|
||||
依赖:models.base.Base。
|
||||
依赖:models.base.Base;候选集外键指向 shipping_onhand_candidate_sets。
|
||||
逻辑:由 app.jobs.queue 写入和领取,由 worker 分发到具体业务 handler;业务模型保存业务状态,本表保存执行状态、锁、重试与结果。
|
||||
"""
|
||||
|
||||
@@ -149,7 +149,7 @@ class Job(Base):
|
||||
ForeignKey('shipping_process_gates.id'), nullable=True, index=True,
|
||||
)
|
||||
candidate_set_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_inventory_candidate_sets.id'), nullable=True, index=True,
|
||||
ForeignKey('shipping_onhand_candidate_sets.id'), nullable=True, index=True,
|
||||
)
|
||||
fencing_token: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
"""
|
||||
backend/app/models/order_delivery_reply.py
|
||||
|
||||
用途:订单交期回复域模型,保存 ERP 订单行快照、交期批次、行级锁定状态、审计与同步运行记录。
|
||||
依赖:models.base.Base、users。
|
||||
逻辑:同步服务只写 erp_lines 的 ERP 快照列;保存回复只写 batches;通知成功路径才写
|
||||
line_states.locked;audit_events 记录保存/通知/锁定/同步;sync_runs 记录每次同步。
|
||||
工作台所有读取只打本地库,禁止回写 ERP。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Index, JSON, Numeric, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class OrderDeliveryErpLine(Base):
|
||||
"""ERP 销售订单行快照(订单单号+项次唯一);仅同步服务写入 ERP 列,不覆盖批次与锁定。"""
|
||||
|
||||
__tablename__ = "order_delivery_erp_lines"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("order_no", "line_no", name="uq_order_delivery_erp_lines_order_line"),
|
||||
Index("ix_order_delivery_erp_lines_order_date", "order_date"),
|
||||
Index("ix_order_delivery_erp_lines_customer_no", "customer_no"),
|
||||
Index("ix_order_delivery_erp_lines_salesperson", "salesperson_code"),
|
||||
Index("ix_order_delivery_erp_lines_slip_code", "slip_code"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
order_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
line_no: Mapped[int] = mapped_column(nullable=False)
|
||||
order_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
customer_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
customer_short_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
customer_full_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
# salesperson_code 对 HXOPS User.employee_id,供企微收件人映射;列表展示 salesperson_name。
|
||||
salesperson_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
salesperson_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
dept_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
dept_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
customer_po: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
part_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
part_name: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
|
||||
spec: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
|
||||
customer_part_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
agreed_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
qty: Mapped[Optional[Decimal]] = mapped_column(Numeric(18, 4), nullable=True)
|
||||
delivered_qty: Mapped[Optional[Decimal]] = mapped_column(Numeric(18, 4), nullable=True)
|
||||
# 单别取 oea01 连字符前段(8301-1605280014 → 8301);一期只落库预留,不展示不过滤。
|
||||
slip_code: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
# 本轮同步未命中但已有批次或锁定的行不删除,置 true 后默认列表不展示。
|
||||
erp_missing: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False, index=True)
|
||||
last_synced_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class OrderDeliveryBatch(Base):
|
||||
"""订单行的交期批次(计划交期+数量+备注);未锁定行保存时整表替换。仅保存回复路径写入。"""
|
||||
|
||||
__tablename__ = "order_delivery_batches"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("line_id", "seq", name="uq_order_delivery_batches_line_seq"),
|
||||
Index("ix_order_delivery_batches_line", "line_id"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
line_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("order_delivery_erp_lines.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
seq: Mapped[int] = mapped_column(nullable=False)
|
||||
planned_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||
qty: Mapped[Decimal] = mapped_column(Numeric(18, 4), nullable=False)
|
||||
# 备注 ≤ 200 字符,由 API 层校验。
|
||||
remark: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class OrderDeliveryLineState(Base):
|
||||
"""订单行锁定状态(一行一态);仅通知成功路径写入 locked=true,与通知同一事务。"""
|
||||
|
||||
__tablename__ = "order_delivery_line_states"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("line_id", name="uq_order_delivery_line_states_line"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
line_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("order_delivery_erp_lines.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
locked: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
# 交期回复人员 = 最近一次发送成功的生管;存快照工号+姓名便于审计回溯。
|
||||
notified_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
||||
notified_employee_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
notified_user_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
notified_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class OrderDeliveryAuditEvent(Base):
|
||||
"""订单交期回复审计:保存批次、发送通知、锁定、同步、出货提醒、未回复提醒六类动作。"""
|
||||
|
||||
__tablename__ = "order_delivery_audit_events"
|
||||
__table_args__ = (
|
||||
Index("ix_order_delivery_audit_events_line", "line_id"),
|
||||
Index("ix_order_delivery_audit_events_action", "action", "created_at"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
# sync 事件无具体行时 line_id 为空。
|
||||
line_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey("order_delivery_erp_lines.id", ondelete="CASCADE"), nullable=True
|
||||
)
|
||||
order_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
line_no: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
# save | notify | lock | sync | ship_remind(出货提醒,payload.ok=true 参与去重)| unreplied_remind(未回复再提醒)
|
||||
action: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
operator_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
||||
payload_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class OrderDeliverySyncRun(Base):
|
||||
"""订单交期同步运行记录;同步作业每次运行写一行,失败保留上次快照。"""
|
||||
|
||||
__tablename__ = "order_delivery_sync_runs"
|
||||
__table_args__ = (
|
||||
Index("ix_order_delivery_sync_runs_started", "started_at"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
trigger: Mapped[str] = mapped_column(String(16), nullable=False) # scheduled | manual
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False) # running | success | failed
|
||||
started_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
line_count: Mapped[int] = mapped_column(default=0, nullable=False)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
@@ -0,0 +1,53 @@
|
||||
"""
|
||||
models/permission_role.py
|
||||
|
||||
用途:可配置权限组(角色包)及角色与 Agent 的授权关系。
|
||||
依赖:models.base.Base、agents / 无直接 User FK(成员仍写在 users.role)。
|
||||
逻辑:Admin 角色配置读写本表;运行时按 users.role=code 取包,再同步到 user_agent_permissions。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, JSON, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.extensions import db
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
permission_role_agents = db.Table(
|
||||
'permission_role_agents',
|
||||
db.Column('role_id', ForeignKey('permission_roles.id', ondelete='CASCADE'), primary_key=True),
|
||||
db.Column('agent_id', ForeignKey('agents.id', ondelete='CASCADE'), primary_key=True),
|
||||
)
|
||||
|
||||
|
||||
class PermissionRole(Base):
|
||||
"""权限组:可用应用入口 + 应用内能力。"""
|
||||
|
||||
__tablename__ = 'permission_roles'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('code', name='uq_permission_roles_code'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
code: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
||||
name: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
is_default: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
is_system: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
is_platform_admin: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
feature_permissions: Mapped[dict] = mapped_column(JSON, default=dict, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
|
||||
agents: Mapped[List['Agent']] = relationship(
|
||||
'Agent',
|
||||
secondary=permission_role_agents,
|
||||
)
|
||||
+12
-105
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
backend/app/models/shipping.py
|
||||
|
||||
用途:货代发货通知正式 Notice(shipping_notices)、事件、库存文件、接入记录、文档/候选与库存映射模型。
|
||||
用途:货代发货通知正式 Notice(shipping_notices)、事件、在手报表文件(freight_rpa_onhand_report_files,s18 起归 RPA,列仍含解析行与快照状态)、任务关联(shipping_task_onhand_links)、接入记录与文档/候选模型。
|
||||
依赖:models.base.Base;规范订单行见 shipping_task_line;建单前 OT 见 shipping_order_task。
|
||||
逻辑:co8e9f0a1b2c 已物理 DROP shipping_batches 及全表 batch_id / consumed_batch_id 列;
|
||||
Intake 消费绑定仅保留 consumed_task_id / consumed_at;upload_batch_id 为上传边界批次(非 shipping_batches);
|
||||
@@ -164,108 +164,15 @@ class ShippingTaskPurgeAudit(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
|
||||
class ShippingInventoryFile(Base):
|
||||
"""货代发货批次库存快照文件,承载一次上传后可被多票任务共用的库存数据。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_files'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_inventory_files_user_created', 'user_id', 'created_at'),
|
||||
Index(
|
||||
'ix_shipping_inventory_files_source_snapshot',
|
||||
'source_code',
|
||||
'warehouse_id',
|
||||
'snapshot_status',
|
||||
'exported_at',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_inventory_files_source_warehouse',
|
||||
'source_code',
|
||||
'warehouse_id',
|
||||
),
|
||||
Index(
|
||||
'uq_shipping_inventory_files_rpa_identity_ready',
|
||||
'rpa_run_no',
|
||||
'source_code',
|
||||
'warehouse_id',
|
||||
unique=True,
|
||||
postgresql_where=text(
|
||||
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
|
||||
"AND source_code IS NOT NULL AND warehouse_id IS NOT NULL"
|
||||
),
|
||||
sqlite_where=text(
|
||||
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
|
||||
"AND source_code IS NOT NULL AND warehouse_id IS NOT NULL"
|
||||
),
|
||||
),
|
||||
# 动态多仓文件没有单一 Warehouse;按 RPA run + Source 保证回调重放幂等。
|
||||
Index(
|
||||
'uq_shipping_inventory_files_rpa_dynamic_source_ready',
|
||||
'rpa_run_no',
|
||||
'source_code',
|
||||
unique=True,
|
||||
postgresql_where=text(
|
||||
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
|
||||
"AND source_code IS NOT NULL AND warehouse_id IS NULL"
|
||||
),
|
||||
sqlite_where=text(
|
||||
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
|
||||
"AND source_code IS NOT NULL AND warehouse_id IS NULL"
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
inventory_file_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
|
||||
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
storage_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
schema_preview_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
field_mapping_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
mapping_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
mapping_confirmed: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
|
||||
inventory_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
line_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
share_mode: Mapped[str] = mapped_column(String(32), default='task_only')
|
||||
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
identity_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
|
||||
source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
snapshot_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
|
||||
exported_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
|
||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
|
||||
rpa_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
schedule_run_id: Mapped[Optional[int]] = mapped_column(nullable=True, index=True)
|
||||
source_query_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True)
|
||||
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
|
||||
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
|
||||
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
links: Mapped[List['ShippingTaskInventoryLink']] = relationship(
|
||||
'ShippingTaskInventoryLink',
|
||||
back_populates='inventory_file',
|
||||
cascade='all, delete-orphan',
|
||||
)
|
||||
|
||||
|
||||
class ShippingTaskInventoryLink(Base):
|
||||
class ShippingTaskOnhandLink(Base):
|
||||
"""发货任务与库存快照的关联记录,一期每个任务只保留一条 active link。"""
|
||||
|
||||
__tablename__ = 'shipping_task_inventory_links'
|
||||
__tablename__ = 'shipping_task_onhand_links'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_task_inventory_links_task_active', 'task_id', 'is_active'),
|
||||
Index('ix_shipping_task_inventory_links_file_active', 'inventory_file_id', 'is_active'),
|
||||
Index('ix_shipping_task_onhand_links_task_active', 'task_id', 'is_active'),
|
||||
Index('ix_shipping_task_onhand_links_file_active', 'onhand_file_id', 'is_active'),
|
||||
Index(
|
||||
'ix_shipping_task_inventory_links_task_source',
|
||||
'ix_shipping_task_onhand_links_task_source',
|
||||
'task_id',
|
||||
'matched_source_code',
|
||||
),
|
||||
@@ -273,7 +180,7 @@ class ShippingTaskInventoryLink(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), index=True)
|
||||
inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id'), index=True)
|
||||
onhand_file_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id'), index=True)
|
||||
link_role: Mapped[str] = mapped_column(String(32), default='member')
|
||||
access_mode: Mapped[str] = mapped_column(String(32), default='readonly')
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default=text('true'), index=True)
|
||||
@@ -283,8 +190,8 @@ class ShippingTaskInventoryLink(Base):
|
||||
identity_check_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
identity_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
snapshot_age_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', use_alter=True), nullable=True, index=True)
|
||||
source_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_source_attempts.id', use_alter=True), nullable=True, index=True)
|
||||
preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_onhand_preparation_attempts.id', use_alter=True), nullable=True, index=True)
|
||||
source_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_onhand_preparation_source_attempts.id', use_alter=True), nullable=True, index=True)
|
||||
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
|
||||
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
|
||||
@@ -294,10 +201,10 @@ class ShippingTaskInventoryLink(Base):
|
||||
linked_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
task: Mapped['ShippingOrderTask'] = relationship('ShippingOrderTask', foreign_keys=[task_id])
|
||||
inventory_file: Mapped['ShippingInventoryFile'] = relationship(
|
||||
'ShippingInventoryFile',
|
||||
inventory_file: Mapped['FreightRpaOnhandReportFile'] = relationship(
|
||||
'FreightRpaOnhandReportFile',
|
||||
back_populates='links',
|
||||
foreign_keys=[inventory_file_id],
|
||||
foreign_keys=[onhand_file_id],
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -30,8 +30,9 @@ class ShippingDocumentProfileAutoFreezeQualification(Base):
|
||||
"status IN ('manual_confirmation', 'auto_freeze_approved', 'auto_freeze_suspended')",
|
||||
name='ck_shipping_document_profile_auto_freeze_qualification_status',
|
||||
),
|
||||
# 索引名沿用迁移 0aa34b5c6d7e 的短名;PostgreSQL 标识符上限 63 字符,超长名会导致建库失败。
|
||||
Index(
|
||||
'ix_shipping_document_profile_auto_freeze_qualification_profile_status',
|
||||
'ix_ship_doc_prof_auto_freeze_profile_status',
|
||||
'profile_id', 'status',
|
||||
),
|
||||
)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
models/shipping_excel_template.py
|
||||
|
||||
用途:定义版本化发货 Excel 模板及不可变 Notice 导出产物。
|
||||
依赖:models.base.Base、库存源、订单 Schema、ShippingNotice 与库存快照模型。
|
||||
依赖:models.base.Base、FreightRpaSource、订单 Schema、ShippingNotice、freight_rpa_parsing_profiles 与 freight_rpa_onhand_report_files。
|
||||
逻辑:库存源只绑定已发布模板版本;每次生成均新增 Artifact 并锁定输入版本与校验和;
|
||||
co8e9f0a1b2c 已删除 export artifact 的 batch_id 列;Artifact 直接属于一张 Notice。
|
||||
"""
|
||||
@@ -44,7 +44,7 @@ class ShippingExcelTemplate(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='excel_template')
|
||||
sources: Mapped[list['FreightRpaSource']] = relationship(back_populates='excel_template')
|
||||
|
||||
|
||||
class ShippingExportArtifact(Base):
|
||||
@@ -62,8 +62,8 @@ class ShippingExportArtifact(Base):
|
||||
template_id: Mapped[int] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=False)
|
||||
order_schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
|
||||
order_extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False)
|
||||
inventory_parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=False)
|
||||
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True)
|
||||
inventory_parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_parsing_profiles.id'), nullable=False)
|
||||
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id'), nullable=True)
|
||||
input_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
file_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
file_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/models/shipping_fulfillment.py
|
||||
|
||||
用途:保存预约单全局注册、每轮库存核验和 Excel 对预约单的不可重叠归属。
|
||||
依赖:冻结订单 Snapshot、库存文件、导出 Artifact 与 SQLAlchemy Base;Notice 主表 shipping_notices。
|
||||
依赖:冻结订单 Snapshot、freight_rpa_onhand_report_files、导出 Artifact 与 SQLAlchemy Base;核验表 shipping_notice_onhand_verifications / shipping_notice_onhand_verification_lines;Notice 主表 shipping_notices。
|
||||
逻辑:Snapshot 行可保留历史预约号;全局 Reservation 决定当前有效行和履约状态,核验与 Artifact 行均追加保存。
|
||||
"""
|
||||
|
||||
@@ -46,53 +46,53 @@ class ShippingReservation(Base):
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ShippingInventoryVerification(Base):
|
||||
class ShippingOnhandVerification(Base):
|
||||
"""一次任务库存核验的不可变轮次,绑定当时有效库存快照。"""
|
||||
|
||||
__tablename__ = 'shipping_notice_inventory_verifications'
|
||||
__tablename__ = 'shipping_notice_onhand_verifications'
|
||||
__table_args__ = (
|
||||
CheckConstraint(
|
||||
"status IN ('completed', 'expired', 'superseded')",
|
||||
name='ck_shipping_notice_inventory_verifications_status',
|
||||
name='ck_shipping_notice_onhand_verifications_status',
|
||||
),
|
||||
Index('ix_shipping_notice_inventory_verifications_task_created', 'task_id', 'created_at'),
|
||||
Index('ix_shipping_notice_onhand_verifications_task_created', 'task_id', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False)
|
||||
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True)
|
||||
onhand_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id'), nullable=True)
|
||||
source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', ondelete='SET NULL'), nullable=True, index=True)
|
||||
preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_onhand_preparation_attempts.id', ondelete='SET NULL'), nullable=True, index=True)
|
||||
matching_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True, index=True)
|
||||
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_inventory_verifications.id'), nullable=True)
|
||||
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_onhand_verifications.id'), nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='completed', server_default='completed')
|
||||
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
lines: Mapped[list['ShippingInventoryVerificationLine']] = relationship(
|
||||
back_populates='verification', cascade='all, delete-orphan', order_by='ShippingInventoryVerificationLine.id',
|
||||
lines: Mapped[list['ShippingOnhandVerificationLine']] = relationship(
|
||||
back_populates='verification', cascade='all, delete-orphan', order_by='ShippingOnhandVerificationLine.id',
|
||||
)
|
||||
|
||||
|
||||
class ShippingInventoryVerificationLine(Base):
|
||||
class ShippingOnhandVerificationLine(Base):
|
||||
"""一个预约单在一轮库存中的需求、可用数量和确定性结果。"""
|
||||
|
||||
__tablename__ = 'shipping_notice_inventory_verification_lines'
|
||||
__tablename__ = 'shipping_notice_onhand_verification_lines'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'verification_id', 'reservation_id',
|
||||
name='uq_shipping_notice_inventory_verification_lines_reservation',
|
||||
name='uq_shipping_notice_onhand_verification_lines_reservation',
|
||||
),
|
||||
CheckConstraint(
|
||||
"status IN ('available', 'shortage', 'invalid')",
|
||||
name='ck_shipping_notice_inventory_verification_lines_status',
|
||||
name='ck_shipping_notice_onhand_verification_lines_status',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
verification_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_inventory_verifications.id', ondelete='CASCADE'), nullable=False,
|
||||
ForeignKey('shipping_notice_onhand_verifications.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False)
|
||||
required_qty: Mapped[Decimal] = mapped_column(Numeric(24, 8), nullable=False)
|
||||
@@ -100,7 +100,7 @@ class ShippingInventoryVerificationLine(Base):
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
|
||||
verification: Mapped['ShippingInventoryVerification'] = relationship(back_populates='lines')
|
||||
verification: Mapped['ShippingOnhandVerification'] = relationship(back_populates='lines')
|
||||
|
||||
|
||||
class ShippingExportArtifactLine(Base):
|
||||
@@ -120,7 +120,7 @@ class ShippingExportArtifactLine(Base):
|
||||
)
|
||||
reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False)
|
||||
verification_line_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_inventory_verification_lines.id'), nullable=False,
|
||||
ForeignKey('shipping_notice_onhand_verification_lines.id'), nullable=False,
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/models/shipping_notice_line.py
|
||||
|
||||
用途:正式发货通知行(shipping_notice_lines),对齐蓝图建单后命名空间。
|
||||
依赖:shipping_notices、shipping_order_snapshot_lines、SQLAlchemy Base。
|
||||
依赖:shipping_notices、shipping_order_snapshot_lines、freight_rpa_onhand_report_files、SQLAlchemy Base。
|
||||
逻辑:冻结 Snapshot 时双写;履约仍以 Snapshot 为权威,本表供 Notice 域查询与 1:N 扩展。
|
||||
"""
|
||||
|
||||
@@ -47,7 +47,7 @@ class ShippingNoticeLine(Base):
|
||||
# 正式履约事实按通知行固化;Notice 单头不得承载仓库或库存快照。
|
||||
inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
inventory_file_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'), nullable=True, index=True,
|
||||
ForeignKey('freight_rpa_onhand_report_files.id', ondelete='SET NULL'), nullable=True, index=True,
|
||||
)
|
||||
inventory_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
field_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
|
||||
+20
-17
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
models/shipping_notice_line_inventory_match.py
|
||||
models/shipping_notice_line_onhand_match.py
|
||||
|
||||
用途:正式 OT(ShippingNotice)行级库存匹配事实持久化——可用数量/短缺/match_result 的真相源。
|
||||
依赖:shipping_notices、shipping_inventory_files、shipping_order_review_cases(可选关联)。
|
||||
逻辑:由 inventory_matching 完成后写入;同一 OT+行+快照唯一;新快照新增行不覆盖历史;
|
||||
依赖:shipping_notices、freight_rpa_onhand_report_files、shipping_order_review_cases(可选关联)。
|
||||
逻辑:由 onhand_matching 完成后写入;同一 OT+行+快照唯一;新快照新增行不覆盖历史;
|
||||
is_current 标记投影用的当前事实;禁止用 Job payload / line_projections 充当正式真相。
|
||||
"""
|
||||
|
||||
@@ -30,15 +30,15 @@ from sqlalchemy.orm import Mapped, mapped_column
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingNoticeLineInventoryMatch(Base):
|
||||
class ShippingNoticeLineOnhandMatch(Base):
|
||||
"""一条 OT 明细在某库存快照下的匹配事实(不可原地覆盖历史快照结果)。"""
|
||||
|
||||
__tablename__ = 'shipping_notice_line_inventory_matches'
|
||||
__tablename__ = 'shipping_notice_line_onhand_matches'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'task_id',
|
||||
'snapshot_line_id',
|
||||
'inventory_snapshot_id',
|
||||
'onhand_snapshot_id',
|
||||
name='uq_shipping_notice_line_inv_match_task_line_snap',
|
||||
),
|
||||
# 同一 OT 行同一时刻仅一条当前事实(PostgreSQL partial unique)。
|
||||
@@ -51,7 +51,7 @@ class ShippingNoticeLineInventoryMatch(Base):
|
||||
),
|
||||
Index('ix_shipping_notice_line_inv_match_task', 'task_id'),
|
||||
Index('ix_shipping_notice_line_inv_match_case', 'review_case_id'),
|
||||
Index('ix_shipping_notice_line_inv_match_snapshot', 'inventory_snapshot_id'),
|
||||
Index('ix_shipping_notice_line_inv_match_snapshot', 'onhand_snapshot_id'),
|
||||
CheckConstraint(
|
||||
"match_result IN ("
|
||||
"'matched', 'not_found', 'result_missing', 'preparing', "
|
||||
@@ -60,7 +60,7 @@ class ShippingNoticeLineInventoryMatch(Base):
|
||||
name='ck_shipping_notice_line_inv_match_result',
|
||||
),
|
||||
CheckConstraint(
|
||||
"inventory_status IN ("
|
||||
"onhand_status IN ("
|
||||
"'ready', 'preparing', 'mapping_failed', 'source_conflict', "
|
||||
"'unavailable', 'invalid_key', 'invalid'"
|
||||
")",
|
||||
@@ -85,30 +85,33 @@ class ShippingNoticeLineInventoryMatch(Base):
|
||||
line_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
|
||||
line_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
candidate_set_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'),
|
||||
ForeignKey('shipping_onhand_candidate_sets.id', ondelete='SET NULL'),
|
||||
nullable=True,
|
||||
index=True,
|
||||
)
|
||||
candidate_set_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
candidate_line_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_inventory_candidate_lines.id', ondelete='SET NULL'),
|
||||
ForeignKey('shipping_onhand_candidate_lines.id', ondelete='SET NULL'),
|
||||
nullable=True,
|
||||
index=True,
|
||||
)
|
||||
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'),
|
||||
onhand_snapshot_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('freight_rpa_onhand_report_files.id', ondelete='SET NULL'),
|
||||
nullable=True,
|
||||
)
|
||||
match_result: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
inventory_status: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
onhand_status: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
required_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
shortage_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
# 料号维度总可用量(忽略预约号、行允许源内汇总);预约号不匹配行的放行兜底依据。
|
||||
# 历史行与无快照行为 NULL,前端显示占位符;重新匹配后回填。
|
||||
part_available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
matching_rule_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
is_current: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True, server_default='true')
|
||||
matched_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow)
|
||||
detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
@@ -143,7 +146,7 @@ class ShippingNoticeLineInventoryMatch(Base):
|
||||
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
|
||||
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
|
||||
superseded_by_match_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_line_inventory_matches.id'), nullable=True)
|
||||
superseded_by_match_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_line_onhand_matches.id'), nullable=True)
|
||||
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
mapping_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_mappings.id', ondelete='SET NULL'), nullable=True, index=True)
|
||||
verification_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_inventory_verifications.id', ondelete='SET NULL'), nullable=True, index=True)
|
||||
mapping_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_mappings.id', ondelete='SET NULL'), nullable=True, index=True)
|
||||
verification_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_onhand_verifications.id', ondelete='SET NULL'), nullable=True, index=True)
|
||||
+19
-19
@@ -1,12 +1,12 @@
|
||||
"""
|
||||
models/shipping_inventory_candidates.py
|
||||
models/shipping_onhand_candidates.py
|
||||
|
||||
用途:库存候选冻结的结构化持久化——决策 C1 的正式业务真相。
|
||||
InventoryCandidateSet(候选集合)→ Source(任务级候选源)→ Line(行级候选源),
|
||||
ShippingOnhandCandidateSet(候选集合)→ Source(任务级候选源)→ Line(行级候选源),
|
||||
同时 ShippingOrderSnapshot.source_manifest_json['inventory_candidate_freeze'] 保存
|
||||
同一时刻的完整不可变副本,用于审计与回滚。
|
||||
依赖:Base、ShippingOrderTask、ShippingProcessExecution、ShippingOrderReviewCase、users、
|
||||
ShippingInventoryRoutingRule(可选外键,路由规则版本)。
|
||||
FreightRpaOnhandRoutingRule(可选外键,路由规则版本)。
|
||||
逻辑:建单前复核阶段(review_case 绑定)或建单后正式推进阶段(task 绑定)都可冻结;
|
||||
input_fingerprint 相同的重复 freeze 直接返回旧 set_id(幂等);
|
||||
source_codes_json 为有序列表(路由优先级信息不能丢),禁止用 SET 类型。
|
||||
@@ -39,7 +39,7 @@ def _utc_now() -> datetime:
|
||||
return datetime.utcnow()
|
||||
|
||||
|
||||
class ShippingInventoryCandidateSet(Base):
|
||||
class ShippingOnhandCandidateSet(Base):
|
||||
"""
|
||||
库存候选集合(冻结真相根)。
|
||||
|
||||
@@ -48,7 +48,7 @@ class ShippingInventoryCandidateSet(Base):
|
||||
二者至少一个非空(CheckConstraint 强制)。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_candidate_sets'
|
||||
__tablename__ = 'shipping_onhand_candidate_sets'
|
||||
__table_args__ = (
|
||||
CheckConstraint(
|
||||
'task_id IS NOT NULL OR review_case_id IS NOT NULL',
|
||||
@@ -98,7 +98,7 @@ class ShippingInventoryCandidateSet(Base):
|
||||
)
|
||||
superseded_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
superseded_by_set_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'), nullable=True,
|
||||
ForeignKey('shipping_onhand_candidate_sets.id', ondelete='SET NULL'), nullable=True,
|
||||
)
|
||||
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
invalidated_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
@@ -111,19 +111,19 @@ class ShippingInventoryCandidateSet(Base):
|
||||
)
|
||||
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
|
||||
sources: Mapped[list['ShippingInventoryCandidateSource']] = relationship(
|
||||
sources: Mapped[list['ShippingOnhandCandidateSource']] = relationship(
|
||||
back_populates='candidate_set',
|
||||
cascade='all, delete-orphan',
|
||||
order_by='ShippingInventoryCandidateSource.candidate_order',
|
||||
order_by='ShippingOnhandCandidateSource.candidate_order',
|
||||
)
|
||||
lines: Mapped[list['ShippingInventoryCandidateLine']] = relationship(
|
||||
lines: Mapped[list['ShippingOnhandCandidateLine']] = relationship(
|
||||
back_populates='candidate_set',
|
||||
cascade='all, delete-orphan',
|
||||
order_by='ShippingInventoryCandidateLine.line_no',
|
||||
order_by='ShippingOnhandCandidateLine.line_no',
|
||||
)
|
||||
|
||||
|
||||
class ShippingInventoryCandidateSource(Base):
|
||||
class ShippingOnhandCandidateSource(Base):
|
||||
"""
|
||||
任务级候选库存源(Set 的子级)。
|
||||
|
||||
@@ -132,7 +132,7 @@ class ShippingInventoryCandidateSource(Base):
|
||||
candidate_origin ∈ {rule, manual_override},区分是规则算出来还是人工强制指定。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_candidate_sources'
|
||||
__tablename__ = 'shipping_onhand_candidate_sources'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'candidate_set_id', 'source_code',
|
||||
@@ -151,13 +151,13 @@ class ShippingInventoryCandidateSource(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
candidate_set_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_inventory_candidate_sets.id', ondelete='CASCADE'), nullable=False,
|
||||
ForeignKey('shipping_onhand_candidate_sets.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
candidate_order: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
candidate_origin: Mapped[str] = mapped_column(String(32), nullable=False, default='rule')
|
||||
routing_rule_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_inventory_routing_rules.id', ondelete='SET NULL'), nullable=True,
|
||||
ForeignKey('freight_rpa_onhand_routing_rules.id', ondelete='SET NULL'), nullable=True,
|
||||
)
|
||||
routing_rule_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
@@ -170,12 +170,12 @@ class ShippingInventoryCandidateSource(Base):
|
||||
DateTime, default=_utc_now, onupdate=_utc_now, nullable=False,
|
||||
)
|
||||
|
||||
candidate_set: Mapped['ShippingInventoryCandidateSet'] = relationship(
|
||||
candidate_set: Mapped['ShippingOnhandCandidateSet'] = relationship(
|
||||
back_populates='sources',
|
||||
)
|
||||
|
||||
|
||||
class ShippingInventoryCandidateLine(Base):
|
||||
class ShippingOnhandCandidateLine(Base):
|
||||
"""
|
||||
行级候选库存源(Set 的子级,按稳定 line_no 对齐订单行)。
|
||||
|
||||
@@ -185,7 +185,7 @@ class ShippingInventoryCandidateLine(Base):
|
||||
part_number + reservation_id,不能只依赖 Snapshot JSON 做高频查询。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_candidate_lines'
|
||||
__tablename__ = 'shipping_onhand_candidate_lines'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'candidate_set_id', 'line_no',
|
||||
@@ -199,7 +199,7 @@ class ShippingInventoryCandidateLine(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
candidate_set_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_inventory_candidate_sets.id', ondelete='CASCADE'), nullable=False,
|
||||
ForeignKey('shipping_onhand_candidate_sets.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
line_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
source_line_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
@@ -215,6 +215,6 @@ class ShippingInventoryCandidateLine(Base):
|
||||
DateTime, default=_utc_now, onupdate=_utc_now, nullable=False,
|
||||
)
|
||||
|
||||
candidate_set: Mapped['ShippingInventoryCandidateSet'] = relationship(
|
||||
candidate_set: Mapped['ShippingOnhandCandidateSet'] = relationship(
|
||||
back_populates='lines',
|
||||
)
|
||||
+13
-13
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
models/shipping_inventory_preparation.py
|
||||
models/shipping_onhand_preparation.py
|
||||
|
||||
用途:表达一次任务级库存准备轮次及逐库存源状态。
|
||||
依赖:ShippingOrderTask、RecoveryPlan、RPA Attempt、InventoryFile、TaskInventoryLink、Base。
|
||||
依赖:ShippingOrderTask、RecoveryPlan、FreightRpaOnhandTaskAttempt、FreightRpaOnhandReportFile、ShippingTaskOnhandLink、Base。
|
||||
逻辑:PreparationAttempt 聚合多个 SourceAttempt,支持有效源复用和问题源单独重拉。
|
||||
"""
|
||||
|
||||
@@ -17,10 +17,10 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingInventoryPreparationAttempt(Base):
|
||||
class ShippingOnhandPreparationAttempt(Base):
|
||||
"""一次任务级库存准备恢复轮次。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_preparation_attempts'
|
||||
__tablename__ = 'shipping_onhand_preparation_attempts'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('task_id', 'attempt_no', name='uq_shipping_inventory_preparation_task_attempt'),
|
||||
CheckConstraint(
|
||||
@@ -38,7 +38,7 @@ class ShippingInventoryPreparationAttempt(Base):
|
||||
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
||||
combination_input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
candidate_set_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'), nullable=True)
|
||||
candidate_set_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_onhand_candidate_sets.id', ondelete='SET NULL'), nullable=True)
|
||||
input_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
output_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
@@ -46,13 +46,13 @@ class ShippingInventoryPreparationAttempt(Base):
|
||||
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
source_attempts = relationship('ShippingInventoryPreparationSourceAttempt', back_populates='preparation_attempt', cascade='all, delete-orphan')
|
||||
source_attempts = relationship('ShippingOnhandPreparationSourceAttempt', back_populates='preparation_attempt', cascade='all, delete-orphan')
|
||||
|
||||
|
||||
class ShippingInventoryPreparationSourceAttempt(Base):
|
||||
class ShippingOnhandPreparationSourceAttempt(Base):
|
||||
"""准备轮次中某个库存源的业务状态。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_preparation_source_attempts'
|
||||
__tablename__ = 'shipping_onhand_preparation_source_attempts'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('preparation_attempt_id', 'source_code', name='uq_shipping_inventory_preparation_source_attempt'),
|
||||
CheckConstraint(
|
||||
@@ -63,17 +63,17 @@ class ShippingInventoryPreparationSourceAttempt(Base):
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
preparation_attempt_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', ondelete='CASCADE'), nullable=False)
|
||||
preparation_attempt_id: Mapped[int] = mapped_column(ForeignKey('shipping_onhand_preparation_attempts.id', ondelete='CASCADE'), nullable=False)
|
||||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
||||
skip_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
|
||||
rpa_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_task_inventory_rpa_attempts.id', ondelete='SET NULL'), nullable=True)
|
||||
inventory_file_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'), nullable=True)
|
||||
task_inventory_link_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_task_inventory_links.id', ondelete='SET NULL'), nullable=True)
|
||||
rpa_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_task_rpa_attempts.id', ondelete='SET NULL'), nullable=True)
|
||||
onhand_file_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id', ondelete='SET NULL'), nullable=True)
|
||||
task_onhand_link_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_task_onhand_links.id', ondelete='SET NULL'), nullable=True)
|
||||
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
preparation_attempt = relationship('ShippingInventoryPreparationAttempt', back_populates='source_attempts')
|
||||
preparation_attempt = relationship('ShippingOnhandPreparationAttempt', back_populates='source_attempts')
|
||||
Loaded 100 of 1212 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user