Compare commits
203
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c3df85b2e | ||
|
|
97c46625e4 | ||
|
|
c99513092a | ||
|
|
859f20eb00 | ||
|
|
d5f988a16c | ||
|
|
26d213c05b | ||
|
|
f269df7941 | ||
|
|
3710aa4d81 | ||
|
|
02aa00e913 | ||
|
|
f0334e5d22 | ||
|
|
b02b776a97 | ||
|
|
81d82a88d5 | ||
|
|
a10ecc8073 | ||
|
|
79050d02ba | ||
|
|
f5611d6783 | ||
|
|
70c7f03a5a | ||
|
|
440afe097f | ||
|
|
dfd48e08e7 | ||
|
|
00c52fdaae | ||
|
|
0331029ead | ||
|
|
5d0a79f5fb | ||
|
|
3bb9938c05 | ||
|
|
fa5d316b25 | ||
|
|
95e7db0831 | ||
|
|
724cd74043 | ||
|
|
d3204f1db8 | ||
|
|
bce589eb96 | ||
|
|
31434f8424 | ||
|
|
e15b7b1ac2 | ||
|
|
663f401873 | ||
|
|
627da80e65 | ||
|
|
5a269f940d | ||
|
|
b69c725992 | ||
|
|
331a983476 | ||
|
|
4c2a7e2a23 | ||
|
|
11cfedcc62 | ||
|
|
55e56e4dc9 | ||
|
|
e421d2607d | ||
|
|
a5d7085c08 | ||
|
|
cdc8610ec1 | ||
|
|
911afa0f73 | ||
|
|
39fe3c05f2 | ||
|
|
ffc0d4a430 | ||
|
|
bf3154033b | ||
|
|
8102a1fe44 | ||
|
|
9236f2949c | ||
|
|
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 | ||
|
|
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 | ||
|
|
ac3fc99883 | ||
|
|
5c6ccf9792 | ||
|
|
993e581135 | ||
|
|
b5fc2c6bb5 | ||
|
|
ec87c1fdaa | ||
|
|
9c7776b5cb | ||
|
|
393a8f6858 | ||
|
|
e35f01bbe9 | ||
|
|
0cc6506c0d | ||
|
|
5412ddc7a8 | ||
|
|
9f2b023a10 | ||
|
|
e750fa8602 | ||
|
|
8a814e7152 | ||
|
|
36f3cdb58c | ||
|
|
a0508de14f | ||
|
|
9376a7c348 | ||
|
|
2df9bdda0d | ||
|
|
387b3157fe | ||
|
|
54a4114daa | ||
|
|
59b37422ab | ||
|
|
89c8da2990 | ||
|
|
0cf3c24119 | ||
|
|
f9f5053f0b | ||
|
|
c4c3cf00ff | ||
|
|
6867aeb90c | ||
|
|
556d3fd3db | ||
|
|
d13c881efb | ||
|
|
161666c0e7 | ||
|
|
298fadf1c8 | ||
|
|
36868f875c | ||
|
|
bb7e0977b8 | ||
|
|
7fb36b301c | ||
|
|
d0e5c9c57e | ||
|
|
616034a4cd | ||
|
|
3de24fd373 | ||
|
|
49f6a0f222 | ||
|
|
f321e2ddd8 | ||
|
|
76583c4e5a | ||
|
|
5772ded347 | ||
|
|
6c9fb16496 | ||
|
|
fe8659c62e | ||
|
|
6655ce8309 | ||
|
|
a24bd94d43 | ||
|
|
27e3d73cb1 | ||
|
|
85384bc973 | ||
|
|
97cb27c632 | ||
|
|
933ac8ebcc | ||
|
|
697e2c55c0 | ||
|
|
6440889bf6 | ||
|
|
acedbbc3ab | ||
|
|
15c89d1426 | ||
|
|
7fb9022bb7 | ||
|
|
04153b401e | ||
|
|
8593e7970b | ||
|
|
94bddbc8e5 |
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`。
|
||||||
|
- 字号和颜色用 `shared/styles/element-theme.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
|
# Development — docker compose / deploy_compose.sh dev
|
||||||
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
||||||
# - .env.dev / .env.test / .env.prod for deployment environments
|
# - .env.dev / .env.test / .env.prod for deployment environments
|
||||||
@@ -102,15 +102,13 @@ SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
|||||||
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
|
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
|
||||||
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
||||||
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
|
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
|
||||||
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
|
|
||||||
# 复核工作台字段级 AI 建议;仅开发环境启用,建议仍须证据校验与人工裁决
|
# 复核工作台字段级 AI 建议;仅开发环境启用,建议仍须证据校验与人工裁决
|
||||||
SHIPPING_NOTICE_LLM_REVIEW_ENABLED=true
|
SHIPPING_NOTICE_LLM_REVIEW_ENABLED=true
|
||||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true
|
||||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED=true
|
||||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
||||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
|
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
|
||||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
|
|
||||||
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
||||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||||
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||||
@@ -135,31 +133,37 @@ SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
|
|||||||
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true
|
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true
|
||||||
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true
|
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true
|
||||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
|
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
|
||||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
|
|
||||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS=900
|
||||||
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
|
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||||
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||||
# RPA 目录(相对 backend/ 根目录,统一 freight_rpa/{inventory,receipt,common} 三层布局)
|
# RPA 目录(相对 backend/ 根;freight_rpa/{onhand,inbound,outbound,upload,common},2026-10-16 批次 R)
|
||||||
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=data/freight_rpa/inventory/drop
|
FREIGHT_RPA_SHARED_ONHAND_DROP_DIR=data/freight_rpa/onhand/drop
|
||||||
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory/triggers
|
FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR=data/freight_rpa/onhand/triggers
|
||||||
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=data/freight_rpa/receipt/drop
|
FREIGHT_RPA_SHARED_INBOUND_DROP_DIR=data/freight_rpa/inbound/drop
|
||||||
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=data/freight_rpa/receipt/triggers
|
FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR=data/freight_rpa/inbound/triggers
|
||||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=data/freight_rpa/inventory/upload_queue
|
FREIGHT_RPA_INBOUND_ARCHIVE_DIR=data/freight_rpa/inbound/archives
|
||||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/freight_rpa/inventory/upload_triggers
|
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
|
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR=data/freight_rpa/common/browser_profile
|
||||||
# AWS 库存列映射(可选 JSON 字符串)
|
# AWS 库存列映射(可选 JSON 字符串)
|
||||||
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
|
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
|
||||||
# 本地 RPA(scripts/freight_rpa/inventory/inventory_rpa_worker.py)
|
# 本地 RPA(scripts/freight_rpa/onhand/onhand_rpa_worker.py)
|
||||||
FREIGHT_RPA_WORKER_MOCK=false
|
FREIGHT_RPA_WORKER_MOCK=false
|
||||||
# 本机无 Redis 时允许进程内存记录心跳;有 Redis 时优先写 Redis
|
# 本机无 Redis 时允许进程内存记录心跳;有 Redis 时优先写 Redis
|
||||||
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false
|
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false
|
||||||
FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK=true
|
FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK=true
|
||||||
# 企微心跳告警总开关(默认关闭;需要时改为 true)
|
|
||||||
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
|
|
||||||
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
|
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
|
||||||
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
|
# FREIGHT_RPA_WORKER_SAMPLE_ONHAND=
|
||||||
# --- 10. 运维、告警与维护工具 ---
|
# --- 10. 运维、告警与维护工具 ---
|
||||||
# 设备维保助手后端工具调用密钥
|
# 设备维保助手后端工具调用密钥
|
||||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||||
|
|
||||||
|
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||||
|
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||||
|
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
|
||||||
|
WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
# =============================================================================
|
# =============================================================================
|
||||||
# Production — docker compose env_file + deploy_compose.sh prod
|
# Production — docker compose env_file + deploy_compose.sh prod
|
||||||
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
||||||
# - .env.dev / .env.test / .env.prod for deployment environments
|
# - .env.dev / .env.test / .env.prod for deployment environments
|
||||||
@@ -25,6 +25,7 @@ HXOPS_PUBLIC_BASE_URL=https://ai.well-trust.com
|
|||||||
AUTH_LOGIN_MODE=casdoor
|
AUTH_LOGIN_MODE=casdoor
|
||||||
# 如果需要用户密码登录,修改该值为password
|
# 如果需要用户密码登录,修改该值为password
|
||||||
# AUTH_LOGIN_MODE=password
|
# AUTH_LOGIN_MODE=password
|
||||||
|
|
||||||
# 是否启用 JWT 认证
|
# 是否启用 JWT 认证
|
||||||
AUTH_JWT_REQUIRED=true
|
AUTH_JWT_REQUIRED=true
|
||||||
AUTH_JWT_ISSUER=https://auth.well-trust.com
|
AUTH_JWT_ISSUER=https://auth.well-trust.com
|
||||||
@@ -72,7 +73,6 @@ GUNICORN_WORKERS=20
|
|||||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||||
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||||
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
|
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
|
||||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines
|
|
||||||
WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com
|
WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||||
|
|
||||||
# --- 5. 数据库与基础设施 ---
|
# --- 5. 数据库与基础设施 ---
|
||||||
@@ -116,11 +116,10 @@ SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
|||||||
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
|
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
|
||||||
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
||||||
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
|
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
|
||||||
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
|
|
||||||
|
|
||||||
# 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享)
|
# 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享)
|
||||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true
|
||||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED=true
|
||||||
# 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥)
|
# 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||||
SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh
|
SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh
|
||||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||||
@@ -138,33 +137,33 @@ SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
|
|||||||
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=false
|
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=false
|
||||||
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=false
|
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=false
|
||||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=false
|
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=false
|
||||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
|
|
||||||
# RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。
|
# RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。
|
||||||
# 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。
|
# 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。
|
||||||
FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
|
FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
|
||||||
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致)
|
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致)
|
||||||
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
|
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
|
||||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS=900
|
||||||
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
||||||
# 企微心跳告警总开关(默认关闭;需要时改为 true)
|
|
||||||
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
|
|
||||||
# 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微
|
# 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微
|
||||||
FREIGHT_RPA_WORKER_ALERT_USERNAMES=
|
FREIGHT_RPA_WORKER_ALERT_USERNAMES=
|
||||||
FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
|
FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
|
||||||
FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
|
FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
|
||||||
FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
|
FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
|
||||||
# RPA 目录(正式环境:Ubuntu 挂载 Windows RPA 正式共享,统一 freight_rpa/{inventory,receipt,common} 三层布局)
|
# RPA 目录(正式:Ubuntu 挂载 Windows 共享;freight_rpa/{onhand,inbound,outbound,upload,common})
|
||||||
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/drop
|
FREIGHT_RPA_SHARED_ONHAND_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/onhand/drop
|
||||||
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/triggers
|
FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/onhand/triggers
|
||||||
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/drop
|
FREIGHT_RPA_SHARED_INBOUND_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inbound/drop
|
||||||
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/triggers
|
FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inbound/triggers
|
||||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_queue
|
FREIGHT_RPA_INBOUND_ARCHIVE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inbound/archives
|
||||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_triggers
|
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 访问)
|
# 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
|
||||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod
|
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod
|
||||||
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
# 订单交期回复 Agent(2026-10-10 上线边界):只同步订单日期 ≥ 起始日的订单行,早于边界的历史行随 erp_missing 语义自动移出工作台;留空/删除 = 全量同步(dev/test 不配置)
|
||||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
ORDER_DELIVERY_SYNC_DATE_FROM=2026-10-10
|
||||||
# --- 10. 运维、告警与维护工具 ---
|
# --- 10. 运维、告警与维护工具 ---
|
||||||
# 设备维保助手后端工具调用密钥
|
# 设备维保助手后端工具调用密钥
|
||||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||||
+5
-3
@@ -150,7 +150,7 @@ WECOM_TRUSTED_DOMAIN=
|
|||||||
WECOM_PUBLIC_BASE_URL=
|
WECOM_PUBLIC_BASE_URL=
|
||||||
WECOM_NOTIFY_ENABLED=true
|
WECOM_NOTIFY_ENABLED=true
|
||||||
WECOM_NOTIFY_BASE_URL=
|
WECOM_NOTIFY_BASE_URL=
|
||||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines
|
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,equipment_acceptance_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,order_delivery_reply_notify,training_overseas_thailand_guidelines
|
||||||
WECOM_FEEDBACK_NOTIFY_ENABLED=true
|
WECOM_FEEDBACK_NOTIFY_ENABLED=true
|
||||||
WECOM_FEEDBACK_NOTIFY_BASE_URL=http://ai.well-trust.com:8881
|
WECOM_FEEDBACK_NOTIFY_BASE_URL=http://ai.well-trust.com:8881
|
||||||
# 企业微信群机器人 webhook,按环境写入 .env.<env> 或部署平台变量;不要提交真实 URL。
|
# 企业微信群机器人 webhook,按环境写入 .env.<env> 或部署平台变量;不要提交真实 URL。
|
||||||
@@ -229,10 +229,12 @@ EDKB_WORD_FILE_TIMEOUT_SEC=420
|
|||||||
|
|
||||||
# --- 9. 业务模块 ---
|
# --- 9. 业务模块 ---
|
||||||
|
|
||||||
# 在途仓自动调拨 Agent(来源并发 / 确认有效期 10 分钟 / 老化阈值);
|
# 在途仓自动调拨 Agent(来源并发 / 行评估当日有效 24h / 老化阈值);
|
||||||
# 外部系统端点与凭据由集成连接器客户端实例管理,不在环境变量中配置。
|
# 外部系统端点与凭据由集成连接器客户端实例管理,不在环境变量中配置。
|
||||||
IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY=3
|
IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY=3
|
||||||
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS=600
|
# 行级新鲜度 TTL:当天评估的行当天可执行;跨日由文件版本对账门禁兜底
|
||||||
|
# (防错看 file_sha256 是否最新,不看墙上时钟),故从确认窗 10 分钟放宽为 24h。
|
||||||
|
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS=86400
|
||||||
IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS=3
|
IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS=3
|
||||||
IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS=5
|
IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS=5
|
||||||
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS=7
|
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS=7
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# =============================================================================
|
# =============================================================================
|
||||||
# Test — docker compose / deploy_compose.sh test
|
# Test — docker compose / deploy_compose.sh test
|
||||||
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
||||||
# - .env.dev / .env.test / .env.prod for deployment environments
|
# - .env.dev / .env.test / .env.prod for deployment environments
|
||||||
@@ -24,8 +24,6 @@ HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
|
|||||||
# 如果需要用户密码登录,修改该值为password
|
# 如果需要用户密码登录,修改该值为password
|
||||||
#AUTH_LOGIN_MODE=casdoor
|
#AUTH_LOGIN_MODE=casdoor
|
||||||
AUTH_LOGIN_MODE=casdoor
|
AUTH_LOGIN_MODE=casdoor
|
||||||
# 是否启用 JWT 认证
|
|
||||||
AUTH_JWT_REQUIRED=true
|
|
||||||
|
|
||||||
# 必须与 CASDOOR_BASE_URL discovery 返回的 issuer 完全一致,不能填写 HXOPS 地址。
|
# 必须与 CASDOOR_BASE_URL discovery 返回的 issuer 完全一致,不能填写 HXOPS 地址。
|
||||||
AUTH_JWT_ISSUER=https://autht.well-trust.com
|
AUTH_JWT_ISSUER=https://autht.well-trust.com
|
||||||
@@ -72,7 +70,6 @@ GUNICORN_WORKERS=6
|
|||||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||||
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||||
WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
|
WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
|
||||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines
|
|
||||||
WECOM_PUBLIC_BASE_URL=https://ait.well-trust.com
|
WECOM_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||||
HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
|
HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||||
|
|
||||||
@@ -120,13 +117,11 @@ SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
|||||||
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
|
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
|
||||||
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
||||||
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
|
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
|
||||||
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
|
SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED=true
|
||||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED=true
|
||||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
|
||||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
||||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
|
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
|
||||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
|
|
||||||
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
||||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||||
# 货代专用 Tool API Key(RPA 回调优先读取;真实值请在服务器本地配置,禁止提交真实密钥)
|
# 货代专用 Tool API Key(RPA 回调优先读取;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||||
@@ -151,16 +146,16 @@ SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
|
|||||||
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true
|
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true
|
||||||
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true
|
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true
|
||||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
|
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
|
||||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
|
|
||||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||||
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐)
|
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐)
|
||||||
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
|
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
|
||||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
# 两域超时须覆盖最坏批次总时长(10 站串行 + 单站失败重试可达 30 分钟+),
|
||||||
|
# 否则每轮对账会把仍在飞的健康批次误回收(2026-10-08 RUN20261008003113B726 实测教训)
|
||||||
|
FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS=3600
|
||||||
|
FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS=3600
|
||||||
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
|
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||||
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||||
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
||||||
# 企微心跳告警总开关(默认关闭;需要时改为 true)
|
|
||||||
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
|
|
||||||
# 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微
|
# 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微
|
||||||
# 两者皆无则告警只写日志、不会发企微
|
# 两者皆无则告警只写日志、不会发企微
|
||||||
FREIGHT_RPA_WORKER_ALERT_USERNAMES=
|
FREIGHT_RPA_WORKER_ALERT_USERNAMES=
|
||||||
@@ -170,24 +165,25 @@ FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
|
|||||||
FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
|
FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
|
||||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||||
FREIGHT_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns=
|
FREIGHT_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns=
|
||||||
# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享,统一 freight_rpa/{inventory,receipt,common} 三层布局)
|
# RPA 目录(测试:Ubuntu 挂载 Windows 共享;freight_rpa/{onhand,inbound,outbound,upload,common})
|
||||||
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/drop
|
FREIGHT_RPA_SHARED_ONHAND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/onhand/drop
|
||||||
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers
|
FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/onhand/triggers
|
||||||
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/drop
|
FREIGHT_RPA_SHARED_INBOUND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/drop
|
||||||
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/triggers
|
FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/triggers
|
||||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_queue
|
FREIGHT_RPA_INBOUND_ARCHIVE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/archives
|
||||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_triggers
|
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 字符串)
|
# AWS 库存列映射(可选 JSON 字符串)
|
||||||
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
|
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
|
||||||
# 本地 Mock RPA(scripts/freight_rpa/inventory/inventory_rpa_worker.py,可选)
|
# 本地 Mock RPA(scripts/freight_rpa/onhand/onhand_rpa_worker.py,可选)
|
||||||
# FREIGHT_RPA_WORKER_MOCK=true
|
# FREIGHT_RPA_WORKER_MOCK=true
|
||||||
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
|
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
|
||||||
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
|
# FREIGHT_RPA_WORKER_SAMPLE_ONHAND=
|
||||||
# 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
# 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
|
||||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
|
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
|
||||||
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
|
||||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
|
||||||
# --- 10. 运维、告警与维护工具 ---
|
# --- 10. 运维、告警与维护工具 ---
|
||||||
# 设备维保助手后端工具调用密钥
|
# 设备维保助手后端工具调用密钥
|
||||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
## 改动说明
|
||||||
|
|
||||||
|
<!-- 这次改了什么、为什么改。 -->
|
||||||
|
|
||||||
|
## 管理端界面
|
||||||
|
|
||||||
|
这次改动如果碰到管理控制台、知识库配置,或已经换成 Element Plus 的页面,按 `docs/ui/ELEMENT_MIGRATION.md` §6 核对。没改界面就删掉下面的清单。
|
||||||
|
|
||||||
|
- [ ] 只在该页入口引入 Element 样式。全站皮肤用 `element-theme.css`;管理列表用 `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
|
!.vscode/extensions.json
|
||||||
.trae/*
|
.trae/*
|
||||||
.cursor/*
|
.cursor/*
|
||||||
|
!.cursor/rules/
|
||||||
|
!.cursor/rules/*.mdc
|
||||||
|
.cursor/rules/* copy.mdc
|
||||||
.idea/
|
.idea/
|
||||||
*.swp
|
*.swp
|
||||||
*.swo
|
*.swo
|
||||||
|
|||||||
@@ -150,6 +150,7 @@ docker compose logs -f hxops-backend
|
|||||||
- 🧬 **修改数据库表结构必须配套迁移**:任何对 `models.py` / 数据表结构的新增、删除、字段或约束变更,都必须生成并提交对应的 Alembic 迁移脚本(`flask db migrate -m "..."` → `flask db upgrade`),禁止只改模型不出迁移。
|
- 🧬 **修改数据库表结构必须配套迁移**:任何对 `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)**。
|
- 🌐 **环境变量分层**:`.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)。
|
- 🌍 **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,改动需保持流式不被破坏。
|
- 📡 **SSE 流式约束**:对话链路依赖 Gevent 异步 worker + Nginx `proxy_buffering off`;对话接口(`chat.py`)使用原生 Fetch/SSE 而非 Axios,改动需保持流式不被破坏。
|
||||||
- 🔌 **外部集成依赖**:Oracle Instant Client 19.30 / `pyodbc` / `zeep`(OA、PLM、HR)等本地未必可运行,涉及这些 service 时谨慎并说明。
|
- 🔌 **外部集成依赖**:Oracle Instant Client 19.30 / `pyodbc` / `zeep`(OA、PLM、HR)等本地未必可运行,涉及这些 service 时谨慎并说明。
|
||||||
- ➕ **新增依赖需克制**:不擅自引入未经评审的第三方依赖;如需新增,在提交说明中给出理由。
|
- ➕ **新增依赖需克制**:不擅自引入未经评审的第三方依赖;如需新增,在提交说明中给出理由。
|
||||||
@@ -163,7 +164,7 @@ docker compose logs -f hxops-backend
|
|||||||
- **文件内章节顺序**:① 环境与应用标识 → ② 应用运行与进程 → ③ 公共地址与网络入口 → ④ 安全、认证与身份源 → ⑤ 数据库与基础设施 → ⑥ AI 平台、模型与内部工具 → ⑦ 企业系统集成 → ⑧ 知识库与文件处理 → ⑨ 业务模块 → ⑩ 运维、告警与维护工具;文件没有某类变量时直接省略该章节。
|
- **文件内章节顺序**:① 环境与应用标识 → ② 应用运行与进程 → ③ 公共地址与网络入口 → ④ 安全、认证与身份源 → ⑤ 数据库与基础设施 → ⑥ AI 平台、模型与内部工具 → ⑦ 企业系统集成 → ⑧ 知识库与文件处理 → ⑨ 业务模块 → ⑩ 运维、告警与维护工具;文件没有某类变量时直接省略该章节。
|
||||||
- **章节内组织**:先按业务域及子域聚合(如 Casdoor、MinIO、WeCom、HR、PLM、SRM、FAQ、Shipping Notice、Fixed Asset),不得把同一域拆散后做全局字母排序;同一域内按“开关/模式 → 地址 → 标识 → 凭据 → 路径 → 业务参数 → 超时/重试/并发 → 兼容/Mock”排列,同级变量再按字母排序。
|
- **章节内组织**:先按业务域及子域聚合(如 Casdoor、MinIO、WeCom、HR、PLM、SRM、FAQ、Shipping Notice、Fixed Asset),不得把同一域拆散后做全局字母排序;同一域内按“开关/模式 → 地址 → 标识 → 凭据 → 路径 → 业务参数 → 超时/重试/并发 → 兼容/Mock”排列,同级变量再按字母排序。
|
||||||
- **数据库连接固定顺序**:`HOST → PORT → DATABASE/SID → USERNAME → PASSWORD → DRIVER → ENCRYPT/TRUST_CERT → TIMEOUT`;完整连接串(如 `DATABASE_URL`、`*_DSN`)置于该数据源首位。
|
- **数据库连接固定顺序**:`HOST → PORT → DATABASE/SID → USERNAME → PASSWORD → DRIVER → ENCRYPT/TRUST_CERT → TIMEOUT`;完整连接串(如 `DATABASE_URL`、`*_DSN`)置于该数据源首位。
|
||||||
- **RPA 命名空间(强制,2026-09-18 修订)**:货代 RPA(库存/收料/上传及后续新增 Worker)统一使用 `FREIGHT_RPA_*`。后端业务参数使用 `FREIGHT_RPA_<配置项>`,后端与 Windows Worker 的共享目录/标识使用 `FREIGHT_RPA_SHARED_*`,Windows Worker 自身运行参数使用 `FREIGHT_RPA_WORKER_*`,平台凭据主密钥使用 `FREIGHT_RPA_CREDENTIAL_KEY`。禁止新增 `SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`。历史名称 `SHIPPING_NOTICE_RPA_*` 于 2026-09-18 未上线期一刀切废弃,**不设兼容层**;RPA 运行期数据统一存放于独立 `freight_rpa/` 根下,按 `inventory/`、`receipt/`、`common/` 分域(common 仅放跨 Worker 共享物,如 browser_profile)。
|
- **RPA 命名空间(强制,2026-09-18 修订)**:货代 RPA(库存/收料/上传及后续新增 Worker)统一使用 `FREIGHT_RPA_*`。后端业务参数使用 `FREIGHT_RPA_<配置项>`,后端与 Windows Worker 的共享目录/标识使用 `FREIGHT_RPA_SHARED_*`,Windows Worker 自身运行参数使用 `FREIGHT_RPA_WORKER_*`,平台凭据主密钥使用 `FREIGHT_RPA_CREDENTIAL_KEY`。禁止新增 `SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`。历史名称 `SHIPPING_NOTICE_RPA_*` 于 2026-09-18 未上线期一刀切废弃,**不设兼容层**;RPA 运行期数据统一存放于独立 `freight_rpa/` 根下,按 `onhand/`、`inbound/`、`outbound/`(抓取域,叶目录同构 triggers/drop/logs/archives)、`upload/`(上传域,triggers/queue)、`common/`(跨 Worker 共享物,如 browser_profile)分域(2026-10-16 批次 R:原 inventory/receipt 已随迁)。
|
||||||
- **跨环境一致性**:`.env.dev`、`.env.test`、`.env.prod` 使用相同章节骨架;同名变量保持相同相对位置,便于审查差异;新增变量时同步检查所有适用环境文件和上述权威文档。
|
- **跨环境一致性**:`.env.dev`、`.env.test`、`.env.prod` 使用相同章节骨架;同名变量保持相同相对位置,便于审查差异;新增变量时同步检查所有适用环境文件和上述权威文档。
|
||||||
- **调整红线**:重排环境变量时只能移动“注释 + 完整赋值行”,禁止修改变量名或值,禁止删除变量、注释或示例;真实密码、密钥、Token、Webhook 与生产连接信息必须由系统环境变量、Jenkins/CI 或 Secret 管理机制注入。
|
- **调整红线**:重排环境变量时只能移动“注释 + 完整赋值行”,禁止修改变量名或值,禁止删除变量、注释或示例;真实密码、密钥、Token、Webhook 与生产连接信息必须由系统环境变量、Jenkins/CI 或 Secret 管理机制注入。
|
||||||
|
|
||||||
@@ -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/convention/env_loading_priority.md](docs/convention/env_loading_priority.md) · [docs/convention/环境变量规则.md](docs/convention/环境变量规则.md) |
|
||||||
| 知识库部署 | [docs/knowledge_base_runtime_deploy.md](docs/knowledge_base_runtime_deploy.md) |
|
| 知识库部署 | [docs/knowledge_base_runtime_deploy.md](docs/knowledge_base_runtime_deploy.md) |
|
||||||
| Excel/CSV 切块与 Dify 分段 | [docs/kb-excel-dify-chunking.md](docs/kb-excel-dify-chunking.md) |
|
| Excel/CSV 切块与 Dify 分段 | [docs/kb-excel-dify-chunking.md](docs/kb-excel-dify-chunking.md) |
|
||||||
| FAQ 缓存 / 热点发现运维 | [docs/faq_cache_ops_manual.md](docs/faq_cache_ops_manual.md) |
|
| FAQ 缓存 / 热点发现运维 | [docs/features/faq/faq_cache_ops_manual.md](docs/features/faq/faq_cache_ops_manual.md) |
|
||||||
| 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.md) |
|
| 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.md) |
|
||||||
| 前端架构规范 | [docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md) |
|
| 前端架构规范 | [docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md) |
|
||||||
|
| 前端 Element Plus | [docs/ui/ELEMENT_MIGRATION.md](docs/ui/ELEMENT_MIGRATION.md) |
|
||||||
| 错误处理规范 | [docs/convention/error_handling.md](docs/convention/error_handling.md) |
|
| 错误处理规范 | [docs/convention/error_handling.md](docs/convention/error_handling.md) |
|
||||||
| Cursor Skills 索引 | [docs/skills/README.md](docs/skills/README.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) |
|
| 前端四语言 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)') {
|
// stage('Frontend Build (CI)') {
|
||||||
// when {
|
// when {
|
||||||
// expression { env.FRONTEND_CHANGED == 'true' }
|
// expression { env.FRONTEND_CHANGED == 'true' }
|
||||||
|
|||||||
+3
-1
@@ -45,10 +45,12 @@ RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
|
|||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
# Install Python dependencies
|
# Install Python dependencies
|
||||||
|
# 注意:勿加 --no-cache-dir,否则 BuildKit 的 /root/.cache/pip 挂载无效,
|
||||||
|
# 每次重建都全量下载 onnxruntime 等大包,镜像源抖动时极易 Read timed out。
|
||||||
COPY backend/requirements.txt backend/requirements-ocr.txt ./
|
COPY backend/requirements.txt backend/requirements-ocr.txt ./
|
||||||
RUN --mount=type=cache,target=/root/.cache/pip \
|
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||||
set -eux; \
|
set -eux; \
|
||||||
PIP_ARGS="--no-cache-dir --retries 10 --timeout 60"; \
|
PIP_ARGS="--retries ${PIP_RETRIES} --timeout ${PIP_TIMEOUT}"; \
|
||||||
if [ -n "${PIP_INDEX_URL:-}" ]; then \
|
if [ -n "${PIP_INDEX_URL:-}" ]; then \
|
||||||
PIP_ARGS="$PIP_ARGS --index-url ${PIP_INDEX_URL}"; \
|
PIP_ARGS="$PIP_ARGS --index-url ${PIP_INDEX_URL}"; \
|
||||||
fi; \
|
fi; \
|
||||||
|
|||||||
+42
-14
@@ -42,17 +42,17 @@ def _is_database_table_ready(table_name: str) -> bool:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def _apply_persisted_settings(app: Flask) -> None:
|
def _apply_persisted_settings(app: Flask, *, force: bool = False) -> None:
|
||||||
"""Pull the latest runtime-editable settings into ``app.config``.
|
"""
|
||||||
|
将运行时可编辑配置同步进 ``app.config``。
|
||||||
|
|
||||||
Reads from the database first, then ``backend/.env``. Tolerates the
|
核心逻辑:委托 apply_env_settings(进程内 TTL,默认 30s);force 时强制读库。
|
||||||
common case where the table does not yet exist (fresh deploy before
|
表尚未创建(迁移前)时静默跳过。
|
||||||
``flask db upgrade`` runs).
|
|
||||||
"""
|
"""
|
||||||
from app.core.config.env_persistence import apply_env_settings
|
from app.core.config.env_persistence import apply_env_settings
|
||||||
|
|
||||||
try:
|
try:
|
||||||
applied = apply_env_settings()
|
applied = apply_env_settings(force=force)
|
||||||
except Exception as exc: # pragma: no cover - defensive
|
except Exception as exc: # pragma: no cover - defensive
|
||||||
logger.warning('Failed to refresh persisted settings: %s', exc)
|
logger.warning('Failed to refresh persisted settings: %s', exc)
|
||||||
return
|
return
|
||||||
@@ -79,12 +79,23 @@ def create_app(config_name='default'):
|
|||||||
|
|
||||||
_transfer_capabilities.register_transfer_capabilities()
|
_transfer_capabilities.register_transfer_capabilities()
|
||||||
|
|
||||||
# Eagerly load persisted runtime settings so the very first request after
|
# onhand/inbound/outbound RPA 回调 sink 注册(幂等):按消费域分组合根——
|
||||||
# a worker boot already sees the admin-saved configuration (otherwise the
|
# onhand → shipping_notice.rpa_sinks;inbound/outbound → in_transit_transfer.rpa_sinks。
|
||||||
# window between worker boot and the first ``before_request`` would still
|
# 进度类经 callback_sinks.dispatch_sink;文件事实经 reports.dispatch;
|
||||||
# serve the defaults baked into config.py / the image).
|
# 未注册 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():
|
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
|
from app.services.agent_runtime_context.bootstrap import load_context_adapters
|
||||||
load_context_adapters()
|
load_context_adapters()
|
||||||
from app.services.agent_registry.handlers.bootstrap import load_handlers
|
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()
|
ensure_default_contract_payment_schedules()
|
||||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||||
logger.warning('Failed to ensure contract-payment schedules: %s', exc)
|
logger.warning('Failed to ensure contract-payment schedules: %s', exc)
|
||||||
|
try:
|
||||||
|
from app.services.equipment_acceptance.schedule_seed import ensure_default_equipment_acceptance_schedules
|
||||||
|
ensure_default_equipment_acceptance_schedules()
|
||||||
|
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||||
|
logger.warning('Failed to ensure equipment-acceptance schedules: %s', exc)
|
||||||
|
try:
|
||||||
|
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:
|
try:
|
||||||
from app.services.lean_training_schedule_seed import ensure_default_lean_training_schedule
|
from app.services.lean_training_schedule_seed import ensure_default_lean_training_schedule
|
||||||
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)
|
logger.warning('Failed to ensure lean-training schedule: %s', exc)
|
||||||
else:
|
else:
|
||||||
logger.info('Skip startup schedule seeding: schedule_tasks table is not ready')
|
logger.info('Skip startup schedule seeding: schedule_tasks table is not ready')
|
||||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
# 固资快照同步已迁至独立进程 workers/worker_fixed_assets.py,Web 不再起线程;
|
||||||
FixedAssetsSnapshotService.start_worker(app)
|
# 排程执行同样由独立 worker 进程(workers/worker_scheduler.py,生产 hxops-schedule-worker 容器)
|
||||||
|
# 负责(dev Wave 4),Web 进程不再兜底扫描。
|
||||||
# AUTO_UPLOAD 显式开启时启动级校验货代上传 RPA(仅告警,不阻断启动)。
|
# AUTO_UPLOAD 显式开启时启动级校验货代上传 RPA(仅告警,不阻断启动)。
|
||||||
try:
|
try:
|
||||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||||
log_auto_upload_readiness_at_startup,
|
log_auto_upload_readiness_at_startup,
|
||||||
)
|
)
|
||||||
log_auto_upload_readiness_at_startup(app)
|
log_auto_upload_readiness_at_startup(app)
|
||||||
@@ -145,6 +172,7 @@ def create_app(config_name='default'):
|
|||||||
|
|
||||||
@app.before_request
|
@app.before_request
|
||||||
def _sync_persisted_settings():
|
def _sync_persisted_settings():
|
||||||
|
# TTL 内复用进程缓存,不每请求打 app_settings;跨 worker 最多延迟一个 TTL。
|
||||||
_apply_persisted_settings(app)
|
_apply_persisted_settings(app)
|
||||||
incoming_request_id = (request.headers.get('X-Request-Id') or '').strip()
|
incoming_request_id = (request.headers.get('X-Request-Id') or '').strip()
|
||||||
g.request_id = incoming_request_id or f"req_{uuid.uuid4().hex[:16]}"
|
g.request_id = incoming_request_id or f"req_{uuid.uuid4().hex[:16]}"
|
||||||
|
|||||||
@@ -17,21 +17,20 @@ def register_blueprints(app: Flask) -> None:
|
|||||||
Args:
|
Args:
|
||||||
app: Flask 应用实例。
|
app: Flask 应用实例。
|
||||||
"""
|
"""
|
||||||
# [STEP 1] 单体模块(Wave 3 前保持不变)
|
# [STEP 1] 域包入口(Blueprint 多在包 __init__ 或子模块)
|
||||||
from app.api.chat import chat_bp
|
from app.api.chat import chat_bp
|
||||||
from app.api.admin import admin_bp
|
from app.api.admin import admin_bp
|
||||||
from app.api.agents import agents_bp
|
from app.api.agents import agents_bp
|
||||||
from app.api.user import auth_bp, user_bp
|
from app.api.user import auth_bp, user_bp
|
||||||
from app.api.integration import integration_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.maintenance import maintenance_bp
|
||||||
from app.api.speech import speech_bp
|
from app.api.speech import speech_bp
|
||||||
from app.api.sso import sso_bp, sso_well_known_bp
|
from app.api.sso import sso_bp, sso_well_known_bp
|
||||||
from app.api.linked_services import linked_services_bp
|
from app.api.linked_services import linked_services_bp
|
||||||
from app.api.training import training_admin_bp, training_user_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.kb import knowledge_base_bp
|
||||||
from app.api.schedule import schedule_admin_bp
|
from app.api.schedule import schedule_admin_bp
|
||||||
from app.api.workspace import (
|
from app.api.workspace import (
|
||||||
@@ -41,10 +40,18 @@ def register_blueprints(app: Flask) -> None:
|
|||||||
workspace_shipping_notice_bp,
|
workspace_shipping_notice_bp,
|
||||||
workspace_voucher_check_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.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.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.in_transit_transfer import in_transit_transfer_bp
|
||||||
from app.api.integration_connector import integration_connector_bp
|
from app.api.integration_connector import integration_connector_bp
|
||||||
|
|
||||||
@@ -65,6 +72,7 @@ def register_blueprints(app: Flask) -> None:
|
|||||||
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
|
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
|
||||||
app.register_blueprint(maintenance_bp, url_prefix='/api/maintenance')
|
app.register_blueprint(maintenance_bp, url_prefix='/api/maintenance')
|
||||||
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
|
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
|
||||||
|
app.register_blueprint(freight_rpa_bp, url_prefix='/api/freight-rpa')
|
||||||
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
|
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
|
||||||
app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context')
|
app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context')
|
||||||
app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance')
|
app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance')
|
||||||
@@ -76,5 +84,7 @@ def register_blueprints(app: Flask) -> None:
|
|||||||
app.register_blueprint(files_bp, url_prefix='/api/files')
|
app.register_blueprint(files_bp, url_prefix='/api/files')
|
||||||
app.register_blueprint(procurement_contract_bp, url_prefix='/api/procurement-contract')
|
app.register_blueprint(procurement_contract_bp, url_prefix='/api/procurement-contract')
|
||||||
app.register_blueprint(contract_payment_bp, url_prefix='/api/contract-payment')
|
app.register_blueprint(contract_payment_bp, url_prefix='/api/contract-payment')
|
||||||
|
app.register_blueprint(equipment_acceptance_bp, url_prefix='/api/equipment-acceptance')
|
||||||
|
app.register_blueprint(order_delivery_reply_bp, url_prefix='/api/order-delivery-reply')
|
||||||
app.register_blueprint(in_transit_transfer_bp, url_prefix='/api/in-transit-transfer')
|
app.register_blueprint(in_transit_transfer_bp, url_prefix='/api/in-transit-transfer')
|
||||||
app.register_blueprint(integration_connector_bp, url_prefix='/api/integration-connector')
|
app.register_blueprint(integration_connector_bp, url_prefix='/api/integration-connector')
|
||||||
@@ -16,13 +16,15 @@ import app.api.admin.faq_candidates # noqa: F401
|
|||||||
import app.api.admin.reports # noqa: F401
|
import app.api.admin.reports # noqa: F401
|
||||||
import app.api.admin.database # noqa: F401
|
import app.api.admin.database # noqa: F401
|
||||||
import app.api.admin.permissions # 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.users # noqa: F401
|
||||||
import app.api.admin.wecom # noqa: F401
|
import app.api.admin.wecom # noqa: F401
|
||||||
import app.api.admin.shipping_order_extraction # noqa: F401
|
import app.api.admin.shipping_order_extraction # noqa: F401
|
||||||
import app.api.admin.announcements # noqa: F401
|
import app.api.admin.announcements # noqa: F401
|
||||||
import app.api.admin.shipping_customers # noqa: F401
|
import app.api.admin.shipping_customers # noqa: F401
|
||||||
import app.api.admin.shipping_identity_rules # noqa: F401
|
import app.api.admin.shipping_identity_rules # noqa: F401
|
||||||
import app.api.admin.shipping_inventory # noqa: F401
|
import app.api.admin.shipping_notice_admin # noqa: F401
|
||||||
|
import app.api.admin_freight_rpa # noqa: F401
|
||||||
import app.api.admin.shipping_order_schema # noqa: F401
|
import app.api.admin.shipping_order_schema # noqa: F401
|
||||||
import app.api.admin.shipping_field_assets # noqa: F401
|
import app.api.admin.shipping_field_assets # noqa: F401
|
||||||
import app.api.admin.shipping_order_document_profiles # noqa: F401
|
import app.api.admin.shipping_order_document_profiles # noqa: F401
|
||||||
@@ -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.linked_services # noqa: F401
|
||||||
import app.api.admin.procurement_contract # noqa: F401
|
import app.api.admin.procurement_contract # noqa: F401
|
||||||
import app.api.admin.training_configs # noqa: F401
|
import app.api.admin.training_configs # noqa: F401
|
||||||
|
import app.api.admin.transfer_type # noqa: F401
|
||||||
|
|
||||||
__all__ = ['admin_bp']
|
__all__ = ['admin_bp']
|
||||||
@@ -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,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))
|
||||||
@@ -42,6 +42,14 @@ def update_user(id: int):
|
|||||||
return jsonify(user_service.update_user(id, data))
|
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'])
|
@admin_bp.route('/users/cleanup-rejected', methods=['POST'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def cleanup_rejected_users():
|
def cleanup_rejected_users():
|
||||||
|
|||||||
@@ -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
|
backend/app/api/agent_runtime_context_tools.py
|
||||||
|
|
||||||
用途:暴露 agent_runtime_context 只读 Tool API,供 Dify Chatflow 解析 HXOPS 上下文。
|
用途:兼容旧 import 路径的薄 shim(真实现已迁至 api/tools/agent_runtime_context.py)。
|
||||||
依赖:app.core.errors、agent_runtime_context.parser/openapi_spec、shipping_notice.tool_api_url。
|
依赖:app.api.tools.agent_runtime_context。
|
||||||
逻辑:OpenAPI 文档接口放行;parse 工具复用 Authorization Bearer / X-Integration-Key 鉴权,不推进业务状态。
|
逻辑:保留 Blueprint;新代码请从 app.api.tools 导入。
|
||||||
"""
|
"""
|
||||||
|
from app.api.tools.agent_runtime_context import agent_runtime_context_bp # noqa: F401
|
||||||
|
|
||||||
from __future__ import annotations
|
__all__ = ['agent_runtime_context_bp']
|
||||||
|
|
||||||
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,5 +1,5 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/api/agents.py
|
backend/app/api/agents/__init__.py
|
||||||
|
|
||||||
用途:普通用户可见的 Agent 列表与 AgentGuide 静态资源。
|
用途:普通用户可见的 Agent 列表与 AgentGuide 静态资源。
|
||||||
依赖:app.core.auth.jwt、models、minio_service、agent_registry.serialization。
|
依赖: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]:
|
def _list_active_agents_for_user(user: User) -> list[Agent]:
|
||||||
"""返回用户可见的完整 Agent ORM 行(含 Registry 结构化列)。"""
|
"""返回用户可见的完整 Agent ORM 行(含 Registry 结构化列)。"""
|
||||||
if user.role == 'admin':
|
if user.is_platform_admin():
|
||||||
return (
|
return (
|
||||||
db.session.query(Agent)
|
db.session.query(Agent)
|
||||||
.filter(Agent.is_active.is_(True))
|
.filter(Agent.is_active.is_(True))
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
api/chat/__init__.py
|
api/chat/__init__.py
|
||||||
|
|
||||||
用途:聊天域 Blueprint 的统一入口。
|
用途:聊天域 Blueprint 的统一入口。
|
||||||
依赖:chat 各职责路由模块、app.api.chat_turns。
|
依赖:chat 各职责路由模块、chat.turns。
|
||||||
逻辑:创建唯一的 chat_bp,导入子模块完成路由注册,并挂载 Chat Turn 流式接口。
|
逻辑:创建唯一的 chat_bp,导入子模块完成路由注册,并挂载 Chat Turn 流式接口。
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -12,7 +12,7 @@ from flask import Blueprint
|
|||||||
chat_bp = Blueprint('chat', __name__)
|
chat_bp = Blueprint('chat', __name__)
|
||||||
|
|
||||||
# 子模块导入时在同一 Blueprint 上注册原有 URL。
|
# 子模块导入时在同一 Blueprint 上注册原有 URL。
|
||||||
from . import assets, completions, directory, feedback, previews, sessions, uploads # noqa: E402, F401
|
from . import assets, capability_list, completions, directory, feedback, previews, sessions, uploads # noqa: E402, F401
|
||||||
from .shared import ( # noqa: E402, F401
|
from .shared import ( # noqa: E402, F401
|
||||||
CHAT_USER_ATTACHMENT_LIMIT,
|
CHAT_USER_ATTACHMENT_LIMIT,
|
||||||
CHAT_USER_ATTACHMENT_MAX_SIZE,
|
CHAT_USER_ATTACHMENT_MAX_SIZE,
|
||||||
@@ -21,7 +21,7 @@ from .shared import ( # noqa: E402, F401
|
|||||||
_merge_user_attachments_from_terminal_event,
|
_merge_user_attachments_from_terminal_event,
|
||||||
_normalize_user_attachments,
|
_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)
|
register_chat_turn_routes(chat_bp)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
"""
|
||||||
|
api/chat/capability_list.py
|
||||||
|
|
||||||
|
用途:聊天端「知识库内容清单」查询接口,作为知识库未命中兜底回复按钮的数据源。
|
||||||
|
依赖:chat.shared(公共上下文与异常)、chat_bp、services.chat.capability_list。
|
||||||
|
逻辑:GET /api/chat/capability-list?agent_id=...,经 require_agent_permission 鉴权后
|
||||||
|
返回常用问题中该应用「能力清单条目」的标准答案;未配置时抛 404 业务错误。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from .shared import * # noqa: F403
|
||||||
|
from . import chat_bp
|
||||||
|
from app.services.chat.capability_list import get_agent_capability_list
|
||||||
|
|
||||||
|
|
||||||
|
@chat_bp.route('/capability-list', methods=['GET'])
|
||||||
|
@require_agent_permission
|
||||||
|
def get_capability_list():
|
||||||
|
"""
|
||||||
|
获取当前应用的知识库内容清单。
|
||||||
|
用途:AI 回复命中知识库未命中兜底语句时,前端【知识库内容清单】按钮点击后调用。
|
||||||
|
核心逻辑:
|
||||||
|
1. require_agent_permission 从 query 读取 agent_id 并校验用户对该应用的访问权限;
|
||||||
|
2. 委托 services.chat.capability_list 返回「能力清单条目」标准答案;
|
||||||
|
3. 未配置时抛 code=CHAT.CAPABILITY_LIST_NOT_FOUND(404),前端按错误码本地化提示。
|
||||||
|
参数约束:agent_id 必须来自当前会话路由(当前聊天应用),禁止跨应用探测他人条目。
|
||||||
|
"""
|
||||||
|
agent = getattr(g, 'current_agent', None)
|
||||||
|
if agent is None:
|
||||||
|
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing agent context', http_status=500)
|
||||||
|
return jsonify(get_agent_capability_list(agent))
|
||||||
@@ -39,6 +39,7 @@ def chat_completions():
|
|||||||
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
|
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
|
||||||
conversation_id = data.get('conversation_id')
|
conversation_id = data.get('conversation_id')
|
||||||
shipping_task_id = str(data.get('task_id') or '').strip()
|
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', '企业知识库')
|
kb_type = data.get('kb_type', '企业知识库')
|
||||||
files = data.get('files')
|
files = data.get('files')
|
||||||
request_id = uuid.uuid4().hex[:12]
|
request_id = uuid.uuid4().hex[:12]
|
||||||
@@ -174,6 +175,7 @@ def chat_completions():
|
|||||||
normalized_files=normalized_files,
|
normalized_files=normalized_files,
|
||||||
adapter_hints=_build_chat_adapter_hints(
|
adapter_hints=_build_chat_adapter_hints(
|
||||||
shipping_task_id=shipping_task_id,
|
shipping_task_id=shipping_task_id,
|
||||||
|
shipping_batch_no=shipping_batch_no,
|
||||||
),
|
),
|
||||||
shipping_task_id=shipping_task_id,
|
shipping_task_id=shipping_task_id,
|
||||||
kb_type=kb_type,
|
kb_type=kb_type,
|
||||||
@@ -214,6 +216,7 @@ def chat_completions():
|
|||||||
user_role=user_proxy.role,
|
user_role=user_proxy.role,
|
||||||
adapter_hints=_build_chat_adapter_hints(
|
adapter_hints=_build_chat_adapter_hints(
|
||||||
shipping_task_id=shipping_task_id,
|
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
|
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 的提示字典。
|
构建聊天入口分发给领域 adapter 的提示字典。
|
||||||
|
|
||||||
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task 提示,
|
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示,
|
||||||
统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。
|
统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。
|
||||||
"""
|
"""
|
||||||
task_id = str(shipping_task_id or '').strip()
|
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 None
|
||||||
return {
|
return {
|
||||||
'shipping_notice': {
|
'shipping_notice': {
|
||||||
'task_id': task_id or None,
|
'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)。
|
用途:Chat Turn 流式 API 路由(POST /api/chat/turns/stream)。
|
||||||
依赖:app.core.decorators、ChatTurnRuntime、chat_bp。
|
依赖:app.core.decorators、ChatTurnRuntime、chat_bp。
|
||||||
逻辑:支持 JSON 与 multipart(附件上传 + Turn);由 chat.py 注册到同一 Blueprint。
|
逻辑:支持 JSON 与 multipart(附件上传 + Turn);由 chat 包注册到同一 Blueprint。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
+137
-29
@@ -1,12 +1,14 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/api/contract_payment.py
|
backend/app/api/contract_payment/__init__.py
|
||||||
|
|
||||||
用途:采购合同付款预警 Agent 的合同台账、付款计划、待发送摘要、台账汇总卡和同步 API。
|
用途:采购合同付款预警 Agent 的合同台账、付款计划、待发送摘要、台账汇总卡和同步 API。
|
||||||
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、Agent 授权、contract_payment 服务和通用 Job 队列。
|
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、Agent 授权、contract_payment 服务和通用 Job 队列。
|
||||||
逻辑:页面查询合同、节点、本周待发送摘要与四张汇总卡;同步和预警操作入队,避免请求线程执行外部系统和企微调用。
|
逻辑:页面查询合同、节点、本周待发送摘要、四张汇总卡和周汇总批次;失败批次返回可展示原因。同步和预警操作入队,避免请求线程执行外部系统和企微调用;发送后可按 Job 查询是否真正完成。
|
||||||
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍。
|
下载和单合同重解析走 read_contract_attachment_bytes:原文还在则直接读,被临时清理删掉则按附件 ID 从 OA/DMS 重新下载。
|
||||||
鉴权:查询接口要求平台 admin 或持有 `agent_code=contract_payment` 的 Agent 授权;
|
待确认合同的人工复核走 apply_manual_review:比例合计 100% 后改为已解析并进入台账。四个付款阶段未付时都可手动标为已付。
|
||||||
同步/扫描/周汇总发送仅 `role=admin`。
|
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍;同时返回 OA 公司及对应 ERP 账套。
|
||||||
|
鉴权:查询接口要求平台管理员(is_platform_admin)或持有 `agent_code=contract_payment` 的 Agent 授权;
|
||||||
|
同步/扫描/周汇总发送仅平台管理员。权限组启用后,普通用户通过角色包获得该 Agent,不再按人授权。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -28,16 +30,22 @@ from app.models import (
|
|||||||
ContractPaymentContract,
|
ContractPaymentContract,
|
||||||
ContractPaymentNode,
|
ContractPaymentNode,
|
||||||
FileAsset,
|
FileAsset,
|
||||||
|
Job,
|
||||||
)
|
)
|
||||||
from app.services.contract_payment.alert_service import build_weekly_alert_summary
|
from app.services.contract_payment.alert_service import build_weekly_alert_summary, describe_batch_failure, mark_payment_node_paid
|
||||||
from app.services.contract_payment.ledger_focus import (
|
from app.services.contract_payment.ledger_focus import (
|
||||||
LEDGER_FOCUS_VALUES,
|
LEDGER_FOCUS_VALUES,
|
||||||
apply_ledger_focus,
|
apply_ledger_focus,
|
||||||
ledger_focus_counts,
|
ledger_focus_counts,
|
||||||
)
|
)
|
||||||
|
from app.services.contract_payment.erp_payment_service import erp_schema_for_company, normalize_purchase_order_no
|
||||||
from app.services.contract_payment.parse_service import unique_parse_issues
|
from app.services.contract_payment.parse_service import unique_parse_issues
|
||||||
from app.services.contract_payment.sync_service import build_payment_plan, build_payment_plan_from_bytes
|
from app.services.contract_payment.review_service import apply_manual_review
|
||||||
from app.services.file_assets.service import read_asset_bytes
|
from app.services.contract_payment.sync_service import (
|
||||||
|
build_payment_plan,
|
||||||
|
build_payment_plan_from_bytes,
|
||||||
|
read_contract_attachment_bytes,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
contract_payment_bp = Blueprint("contract_payment", __name__)
|
contract_payment_bp = Blueprint("contract_payment", __name__)
|
||||||
@@ -103,7 +111,7 @@ def _require_contract_payment_access():
|
|||||||
ForbiddenError: 已登录但没有合同付款预警 Agent 授权。
|
ForbiddenError: 已登录但没有合同付款预警 Agent 授权。
|
||||||
"""
|
"""
|
||||||
user = _require_user()
|
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
|
return user
|
||||||
raise ForbiddenError(
|
raise ForbiddenError(
|
||||||
'Contract payment agent permission required',
|
'Contract payment agent permission required',
|
||||||
@@ -116,7 +124,7 @@ def _require_contract_payment_admin():
|
|||||||
确保当前用户既有合同付款预警访问权,又是平台管理员。
|
确保当前用户既有合同付款预警访问权,又是平台管理员。
|
||||||
|
|
||||||
核心逻辑:持有 Agent 的普通用户可查台账;同步 OA、强制覆盖、批量重解析、扫描预警和发送周汇总
|
核心逻辑:持有 Agent 的普通用户可查台账;同步 OA、强制覆盖、批量重解析、扫描预警和发送周汇总
|
||||||
会改写外部系统或触发企微,因此仅 `role=admin` 可调用。
|
会改写外部系统或触发企微,因此仅平台管理员可调用。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
无。当前请求身份由 JWT 上下文提供。
|
无。当前请求身份由 JWT 上下文提供。
|
||||||
@@ -127,7 +135,7 @@ def _require_contract_payment_admin():
|
|||||||
ForbiddenError: 无合同付款访问权,或已授权但不是管理员。
|
ForbiddenError: 无合同付款访问权,或已授权但不是管理员。
|
||||||
"""
|
"""
|
||||||
user = _require_contract_payment_access()
|
user = _require_contract_payment_access()
|
||||||
if getattr(user, "role", None) != "admin":
|
if not user.is_platform_admin():
|
||||||
raise ForbiddenError(
|
raise ForbiddenError(
|
||||||
'Admin privilege required for contract payment jobs',
|
'Admin privilege required for contract payment jobs',
|
||||||
code='CONTRACT_PAYMENT.ADMIN_REQUIRED',
|
code='CONTRACT_PAYMENT.ADMIN_REQUIRED',
|
||||||
@@ -151,7 +159,9 @@ def _serialize_contract(row: ContractPaymentContract) -> dict:
|
|||||||
"id": row.id,
|
"id": row.id,
|
||||||
"contract_no": row.contract_no,
|
"contract_no": row.contract_no,
|
||||||
"workflow_no": row.workflow_no,
|
"workflow_no": row.workflow_no,
|
||||||
"purchase_order_no": row.purchase_order_no,
|
"purchase_order_no": normalize_purchase_order_no(row.purchase_order_no) or None,
|
||||||
|
"company_name": row.company_name,
|
||||||
|
"erp_schema": erp_schema_for_company(row.company_name),
|
||||||
"supplier_name": row.supplier_name,
|
"supplier_name": row.supplier_name,
|
||||||
"total_amount": str(row.total_amount) if row.total_amount is not None else None,
|
"total_amount": str(row.total_amount) if row.total_amount is not None else None,
|
||||||
"currency": row.currency,
|
"currency": row.currency,
|
||||||
@@ -192,8 +202,9 @@ def _serialize_contract(row: ContractPaymentContract) -> dict:
|
|||||||
"anchor_type": node.anchor_type,
|
"anchor_type": node.anchor_type,
|
||||||
"anchor_date": node.anchor_date.isoformat() if node.anchor_date else None,
|
"anchor_date": node.anchor_date.isoformat() if node.anchor_date else None,
|
||||||
"due_date": node.due_date.isoformat() if node.due_date else None,
|
"due_date": node.due_date.isoformat() if node.due_date else None,
|
||||||
# ERP apa_file 付款日期;已付款时展示,未付为空。
|
# 付款日期。paid_source=manual 表示人工标记,其余来自 ERP。
|
||||||
"paid_at": (node.evidence_json or {}).get("paid_at"),
|
"paid_at": (node.evidence_json or {}).get("paid_at"),
|
||||||
|
"paid_source": (node.evidence_json or {}).get("paid_source"),
|
||||||
"status": node.status,
|
"status": node.status,
|
||||||
} for node in nodes],
|
} for node in nodes],
|
||||||
"alerts": [{
|
"alerts": [{
|
||||||
@@ -354,7 +365,8 @@ def download_contract_attachment(contract_id: int, attachment_id: int):
|
|||||||
"""
|
"""
|
||||||
下载合同详情中已归档的原文附件。
|
下载合同详情中已归档的原文附件。
|
||||||
|
|
||||||
核心逻辑:附件必须同时属于请求中的合同和本地 FileAsset,避免通过附件 ID 越权读取其他合同原文。
|
核心逻辑:附件必须属于请求中的合同。本地 FileAsset 仍可读时直接返回;
|
||||||
|
若临时清理已删除对象,则按 OA/DMS 附件 ID 重新下载后再返回。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
contract_id: 合同台账主键。
|
contract_id: 合同台账主键。
|
||||||
@@ -364,20 +376,19 @@ def download_contract_attachment(contract_id: int, attachment_id: int):
|
|||||||
受控下载的附件二进制流。
|
受控下载的附件二进制流。
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
NotFoundError: 合同、附件或其保存的文件资产不存在。
|
NotFoundError: 合同或附件不存在,或原文已被清理且无法从原系统重新下载。
|
||||||
"""
|
"""
|
||||||
_require_contract_payment_access()
|
_require_contract_payment_access()
|
||||||
|
row = db.session.get(ContractPaymentContract, contract_id)
|
||||||
attachment = db.session.query(ContractPaymentAttachment).filter_by(id=attachment_id, contract_id=contract_id).first()
|
attachment = db.session.query(ContractPaymentAttachment).filter_by(id=attachment_id, contract_id=contract_id).first()
|
||||||
if not attachment or not attachment.file_asset_id:
|
if not row or not attachment or not attachment.file_asset_id:
|
||||||
raise NotFoundError("合同原文附件不存在")
|
|
||||||
asset = db.session.get(FileAsset, attachment.file_asset_id)
|
|
||||||
if not asset:
|
|
||||||
raise NotFoundError("合同原文附件不存在")
|
raise NotFoundError("合同原文附件不存在")
|
||||||
|
data = read_contract_attachment_bytes(row, attachment)
|
||||||
return send_file(
|
return send_file(
|
||||||
BytesIO(read_asset_bytes(asset)),
|
BytesIO(data),
|
||||||
mimetype=attachment.mime_type or asset.mime_type or "application/octet-stream",
|
mimetype=attachment.mime_type or "application/octet-stream",
|
||||||
as_attachment=True,
|
as_attachment=True,
|
||||||
download_name=attachment.file_name or asset.original_filename,
|
download_name=attachment.file_name or "contract",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -464,9 +475,55 @@ def enqueue_weekly_alert_send():
|
|||||||
return ok({"job_id": job_id}, request_id=getattr(g, "request_id", None), status=202)
|
return ok({"job_id": job_id}, request_id=getattr(g, "request_id", None), status=202)
|
||||||
|
|
||||||
|
|
||||||
|
_CONTRACT_PAYMENT_JOB_TYPES = {
|
||||||
|
JobType.CONTRACT_PAYMENT_SYNC.value,
|
||||||
|
JobType.CONTRACT_PAYMENT_ALERT.value,
|
||||||
|
JobType.CONTRACT_PAYMENT_ALERT_WEEKLY.value,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@contract_payment_bp.route("/jobs/<int:job_id>", methods=["GET"])
|
||||||
|
def get_contract_payment_job(job_id: int):
|
||||||
|
"""查询当前管理员提交的合同付款后台任务是否已经跑完。
|
||||||
|
|
||||||
|
核心逻辑:只返回本人创建的合同付款 Job,避免用任务号读到其它域的执行结果。
|
||||||
|
周汇总发送的 result 含 sent / failed,供页面在刷新批次列表前判断这次有没有真正发出。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
job_id: jobs 表主键。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
标准成功 envelope,含 status、message 与 result。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
NotFoundError: 任务不存在,或不属于当前管理员的合同付款任务。
|
||||||
|
"""
|
||||||
|
user = _require_contract_payment_admin()
|
||||||
|
row = db.session.get(Job, job_id)
|
||||||
|
if (
|
||||||
|
row is None
|
||||||
|
or row.domain != "procurement_contract"
|
||||||
|
or row.job_type not in _CONTRACT_PAYMENT_JOB_TYPES
|
||||||
|
or row.created_by_id != user.id
|
||||||
|
):
|
||||||
|
raise NotFoundError("任务不存在")
|
||||||
|
return ok({
|
||||||
|
"id": row.id,
|
||||||
|
"status": row.status,
|
||||||
|
"message": row.message,
|
||||||
|
"result": row.result_json or {},
|
||||||
|
}, request_id=getattr(g, "request_id", None))
|
||||||
|
|
||||||
|
|
||||||
@contract_payment_bp.route("/alert-batches", methods=["GET"])
|
@contract_payment_bp.route("/alert-batches", methods=["GET"])
|
||||||
def list_alert_batches():
|
def list_alert_batches():
|
||||||
"""查询近期合同付款预警周汇总批次。"""
|
"""查询近期合同付款预警周汇总批次。
|
||||||
|
|
||||||
|
核心逻辑:按创建时间倒序最多返回 100 条。失败批次附带 failure_reasons,
|
||||||
|
供周汇总页点击图标展示;成功批次不返回原因,也不下发企微原始轨迹。
|
||||||
|
Returns:
|
||||||
|
标准成功 envelope,items 含批次摘要;失败项另含 failure_reasons。
|
||||||
|
"""
|
||||||
_require_contract_payment_access()
|
_require_contract_payment_access()
|
||||||
rows = db.session.query(ContractPaymentAlertBatch).order_by(ContractPaymentAlertBatch.created_at.desc()).limit(100).all()
|
rows = db.session.query(ContractPaymentAlertBatch).order_by(ContractPaymentAlertBatch.created_at.desc()).limit(100).all()
|
||||||
return ok({"items": [{
|
return ok({"items": [{
|
||||||
@@ -475,6 +532,11 @@ def list_alert_batches():
|
|||||||
"summary": row.summary_json, "excel_file_name": row.excel_file_name,
|
"summary": row.summary_json, "excel_file_name": row.excel_file_name,
|
||||||
"excel_file_size": row.excel_file_size, "sent_at": row.sent_at.isoformat() if row.sent_at else None,
|
"excel_file_size": row.excel_file_size, "sent_at": row.sent_at.isoformat() if row.sent_at else None,
|
||||||
"created_at": row.created_at.isoformat(),
|
"created_at": row.created_at.isoformat(),
|
||||||
|
"failure_reasons": (
|
||||||
|
describe_batch_failure(row.wecom_trace_json, fallback=row.error_message)
|
||||||
|
if row.status == "failed"
|
||||||
|
else []
|
||||||
|
),
|
||||||
} for row in rows]}, request_id=getattr(g, "request_id", None))
|
} for row in rows]}, request_id=getattr(g, "request_id", None))
|
||||||
|
|
||||||
|
|
||||||
@@ -519,8 +581,8 @@ def reparse_contract_attachment(contract_id: int):
|
|||||||
"""
|
"""
|
||||||
使用已归档的合同原文附件重新生成付款解析结果。
|
使用已归档的合同原文附件重新生成付款解析结果。
|
||||||
|
|
||||||
核心逻辑:管理员在待确认合同中发现旧规则或附件抽取异常时触发;服务端只读取该合同
|
核心逻辑:管理员在待确认合同中发现旧规则或附件抽取异常时触发;优先读取该合同
|
||||||
已保存的附件,优先盖章完成合同上传,覆盖付款节点、解析状态和问题列表,不调用 OA。
|
已保存的附件(盖章完成合同上传优先)。原文若已被临时清理删除,则按附件 ID 重新下载后再解析。
|
||||||
Args:
|
Args:
|
||||||
contract_id: 合同付款台账主键。
|
contract_id: 合同付款台账主键。
|
||||||
Returns:
|
Returns:
|
||||||
@@ -543,12 +605,58 @@ def reparse_contract_attachment(contract_id: int):
|
|||||||
raise ValidationError("当前合同没有已归档的原文附件,无法重新解析", code="CONTRACT_PAYMENT.ATTACHMENT_REQUIRED")
|
raise ValidationError("当前合同没有已归档的原文附件,无法重新解析", code="CONTRACT_PAYMENT.ATTACHMENT_REQUIRED")
|
||||||
# [STEP 1] 使用同步链路同一附件优先级,保证人工重跑与首次解析的结果可复现。
|
# [STEP 1] 使用同步链路同一附件优先级,保证人工重跑与首次解析的结果可复现。
|
||||||
attachment = min(attachments, key=_attachment_parse_priority)
|
attachment = min(attachments, key=_attachment_parse_priority)
|
||||||
asset = db.session.get(FileAsset, attachment.file_asset_id)
|
data = read_contract_attachment_bytes(row, attachment)
|
||||||
if not asset:
|
result = build_payment_plan_from_bytes(row, filename=attachment.file_name, data=data)
|
||||||
raise ValidationError("当前合同原文附件不存在,无法重新解析", code="CONTRACT_PAYMENT.ATTACHMENT_REQUIRED")
|
|
||||||
result = build_payment_plan_from_bytes(row, filename=attachment.file_name, data=read_asset_bytes(asset))
|
|
||||||
return ok({
|
return ok({
|
||||||
"contract": _serialize_contract(row),
|
"contract": _serialize_contract(row),
|
||||||
"parse_result": result,
|
"parse_result": result,
|
||||||
"attachment_name": attachment.file_name,
|
"attachment_name": attachment.file_name,
|
||||||
}, request_id=getattr(g, "request_id", None))
|
}, request_id=getattr(g, "request_id", None))
|
||||||
|
|
||||||
|
|
||||||
|
@contract_payment_bp.route("/contracts/<int:contract_id>/manual-review", methods=["POST"])
|
||||||
|
def manual_review_contract(contract_id: int):
|
||||||
|
"""
|
||||||
|
保存待确认合同的人工复核,并在校验通过后放入合同台账。
|
||||||
|
|
||||||
|
核心逻辑:与单合同重解析一样,持有合同付款 Agent 的用户即可提交,不要求平台管理员。
|
||||||
|
服务层负责比例合计、金额核对和必填日期;本接口只转交请求体并返回更新后的合同。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
contract_id: 合同付款台账主键。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
标准成功 envelope,含复核后的合同详情。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
NotFoundError: 合同不存在。
|
||||||
|
ValidationError: 采购单号、金额、比例或日期不满足进入台账的条件。
|
||||||
|
"""
|
||||||
|
user = _require_contract_payment_access()
|
||||||
|
data = request.get_json() or {}
|
||||||
|
row = apply_manual_review(contract_id, data, operator_id=getattr(user, "id", None))
|
||||||
|
return ok({"contract": _serialize_contract(row)}, request_id=getattr(g, "request_id", None))
|
||||||
|
|
||||||
|
|
||||||
|
@contract_payment_bp.route("/contracts/<int:contract_id>/nodes/<int:node_id>/mark-paid", methods=["POST"])
|
||||||
|
def mark_contract_node_paid(contract_id: int, node_id: int):
|
||||||
|
"""
|
||||||
|
把未付的付款阶段手动标为已付。
|
||||||
|
|
||||||
|
核心逻辑:与人工复核一样,持有合同付款 Agent 的用户即可提交。四个阶段都可以标记,只改这一阶段,并关闭尚未发送的预警。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
contract_id: 合同台账主键。
|
||||||
|
node_id: 付款节点主键。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
标准成功 envelope,含更新后的合同详情。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
NotFoundError: 合同或节点不存在。
|
||||||
|
ValidationError: 阶段不能标记,或付款日期无效。
|
||||||
|
"""
|
||||||
|
user = _require_contract_payment_access()
|
||||||
|
data = request.get_json() or {}
|
||||||
|
row = mark_payment_node_paid(contract_id, node_id, data, operator_id=getattr(user, "id", None))
|
||||||
|
return ok({"contract": _serialize_contract(row)}, request_id=getattr(g, "request_id", None))
|
||||||
@@ -0,0 +1,207 @@
|
|||||||
|
"""
|
||||||
|
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 按状态分组,keyword 查三种单号,applicant 查申请人。"""
|
||||||
|
_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,
|
||||||
|
keyword=request.args.get("keyword"),
|
||||||
|
applicant=request.args.get("applicant"),
|
||||||
|
)
|
||||||
|
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
|
backend/app/api/file_check_tools.py
|
||||||
|
|
||||||
用途:文件检核 / 立账凭证检核 Chatflow 显式 HTTP Tool API(启动检核复用本蓝图)。
|
用途:兼容旧 import 路径的薄 shim(真实现已迁至 api/tools/file_check.py)。
|
||||||
依赖:workspace_file_check、file_check_tools、schedule.scheduler_service。
|
依赖:app.api.tools.file_check。
|
||||||
逻辑:发起检核时可透传顶层 mode/invoice_no(或嵌套 run_options)写入 ScheduleRun.api_request_json;实际执行入队 FILE_CHECK_RUN,由 schedule worker 执行。
|
逻辑:保留 Blueprint 与测试 monkeypatch 常用符号;新代码请从 app.api.tools 导入。
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from app.api.tools.file_check import ( # noqa: F401
|
||||||
|
_RUN_START_LOCK,
|
||||||
import threading
|
_build_excel_download_url,
|
||||||
import time
|
_precheck_no_data,
|
||||||
from io import BytesIO
|
enqueue,
|
||||||
from datetime import datetime
|
file_check_bp,
|
||||||
|
get_schedule_sql_config_by_task_id,
|
||||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
_build_srm_conn_str,
|
||||||
from sqlalchemy import text
|
_fetch_records,
|
||||||
|
|
||||||
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:
|
__all__ = [
|
||||||
import pyodbc # type: ignore
|
'file_check_bp',
|
||||||
except Exception: # pragma: no cover
|
'enqueue',
|
||||||
pyodbc = None
|
'_precheck_no_data',
|
||||||
|
'_build_excel_download_url',
|
||||||
|
'_RUN_START_LOCK',
|
||||||
file_check_bp = Blueprint("file_check_tools", __name__)
|
'get_schedule_sql_config_by_task_id',
|
||||||
|
'_build_srm_conn_str',
|
||||||
_EXCEL_TOKEN_SCOPES = {"file_check_excel", "file_schedule_excel"}
|
'_fetch_records',
|
||||||
_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()))
|
|
||||||
@@ -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,516 +0,0 @@
|
|||||||
"""backend/app/api/in_transit_transfer.py
|
|
||||||
|
|
||||||
用途:在途仓自动调拨用户态 API(仓库管理人员)。
|
|
||||||
依赖:app.core.auth.jwt、app.core.errors、app.core.response、precheck_service、deps。
|
|
||||||
逻辑:薄路由层鉴权与参数校验;成功响应统一 envelope(ok + request_id);
|
|
||||||
Phase 1 提供预检创建(POST /prechecks)与进度恢复(GET /prechecks/{id})。
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
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 (
|
|
||||||
execute_precheck,
|
|
||||||
get_run,
|
|
||||||
serialize_run_result,
|
|
||||||
)
|
|
||||||
from app.services.in_transit_transfer.manual_close_service import manual_close_item
|
|
||||||
from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck
|
|
||||||
from app.services.in_transit_transfer.retry_service import requery_items as retry_service_requery_items, retry_item
|
|
||||||
from app.services.in_transit_transfer.serializers import (
|
|
||||||
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("/prechecks", methods=["POST"])
|
|
||||||
@require_transfer_permission
|
|
||||||
def create_precheck_api():
|
|
||||||
"""创建或复用一次调拨预检(只读,不写 外部系统)。
|
|
||||||
|
|
||||||
请求体:{"source_codes": [...], "business_date": "YYYY-MM-DD"(可选),
|
|
||||||
"receipt_date_from"/"receipt_date_to"(可选),
|
|
||||||
"transfer_type": "in_transit_to_hub"(可选,缺省在途仓至HUB仓)}。
|
|
||||||
响应:201 envelope,data 为预检摘要(precheck_id/hash/计数/来源进度)。
|
|
||||||
"""
|
|
||||||
body = request.get_json(silent=True) or {}
|
|
||||||
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_precheck(
|
|
||||||
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("/prechecks/<precheck_id>", methods=["GET"])
|
|
||||||
@require_transfer_permission
|
|
||||||
def get_precheck_api(precheck_id: str):
|
|
||||||
"""恢复预检进度与明细(页面刷新/会话恢复)。"""
|
|
||||||
restored = restore_precheck(precheck_id)
|
|
||||||
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("/prechecks/<precheck_id>/execute", methods=["POST"])
|
|
||||||
@require_transfer_permission
|
|
||||||
def execute_precheck_api(precheck_id: str):
|
|
||||||
"""确认预检选择范围并直接生成执行 Run(决策 4/5:无独立确认页)。
|
|
||||||
|
|
||||||
请求体:{"invoice_nos": [...]}(可选;缺省执行全部可执行项)。
|
|
||||||
响应:201 envelope,data 为 run_no / run 状态 / 外部系统 单号聚合结果。
|
|
||||||
"""
|
|
||||||
body = request.get_json(silent=True) or {}
|
|
||||||
invoice_nos = body.get("invoice_nos") if isinstance(body, dict) else None
|
|
||||||
if invoice_nos is not None and not isinstance(invoice_nos, list):
|
|
||||||
raise ValidationError("invoice_nos must be a list")
|
|
||||||
deps = transfer_deps.get_transfer_dependencies()
|
|
||||||
outcome = execute_precheck(
|
|
||||||
precheck_id=precheck_id,
|
|
||||||
deps=deps,
|
|
||||||
selected_invoice_nos=invoice_nos,
|
|
||||||
)
|
|
||||||
return _ok({
|
|
||||||
"run_no": outcome.run_no,
|
|
||||||
"status": outcome.status,
|
|
||||||
"result": serialize_run_result(outcome.result),
|
|
||||||
}, status=201)
|
|
||||||
|
|
||||||
|
|
||||||
@in_transit_transfer_bp.route("/prechecks/<precheck_no>/items/requery", methods=["POST"])
|
|
||||||
@require_transfer_permission
|
|
||||||
def requery_items_api(precheck_no: str):
|
|
||||||
"""批量重查 外部系统 库存(可恢复阻断行);body 可选 invoice_nos 限定范围。"""
|
|
||||||
user = _require_user()
|
|
||||||
body = request.get_json(silent=True) or {}
|
|
||||||
invoice_nos = body.get("invoice_nos") if isinstance(body.get("invoice_nos"), list) else None
|
|
||||||
deps = transfer_deps.get_transfer_dependencies()
|
|
||||||
return _ok(retry_service_requery_items(
|
|
||||||
precheck_no=precheck_no, deps=deps, invoice_nos=invoice_nos,
|
|
||||||
actor_id=str(user.id) if user.id else None,
|
|
||||||
))
|
|
||||||
|
|
||||||
|
|
||||||
@in_transit_transfer_bp.route("/sources/receipt-files", methods=["POST"])
|
|
||||||
@require_transfer_permission
|
|
||||||
def download_source_receipt_files_api():
|
|
||||||
"""按选中来源打包下载各自最新归档收料文件(zip);记录访问审计。"""
|
|
||||||
import io
|
|
||||||
import zipfile
|
|
||||||
from pathlib import Path as _Path
|
|
||||||
|
|
||||||
from app import db
|
|
||||||
from app.models import ShippingReceiptReportFile
|
|
||||||
from app.services.file_assets.storage import file_asset_storage
|
|
||||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
|
||||||
from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition
|
|
||||||
|
|
||||||
body = request.get_json(silent=True) or {}
|
|
||||||
source_codes = body.get("source_codes")
|
|
||||||
if not isinstance(source_codes, list) or not [c for c in source_codes if str(c or "").strip()]:
|
|
||||||
raise ValidationError("source_codes is required")
|
|
||||||
|
|
||||||
buffer = io.BytesIO()
|
|
||||||
included: list[str] = []
|
|
||||||
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
|
|
||||||
for code in source_codes:
|
|
||||||
code = str(code or "").strip()
|
|
||||||
if not code:
|
|
||||||
continue
|
|
||||||
report = (
|
|
||||||
ShippingReceiptReportFile.query
|
|
||||||
.join(ShippingReceiptReportFile.unit_run)
|
|
||||||
.filter(
|
|
||||||
ShippingReceiptReportFile.unit_run.has(source_code=code),
|
|
||||||
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)与徽标/预检取文件同口径,
|
|
||||||
# 单一事实来源见 receipt_file_gate。
|
|
||||||
usable_receipt_file_condition(),
|
|
||||||
)
|
|
||||||
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
|
|
||||||
.first()
|
|
||||||
)
|
|
||||||
if report is None:
|
|
||||||
continue
|
|
||||||
data = file_asset_storage.get_bytes(report.storage_key)
|
|
||||||
safe_name = _Path(report.original_filename or f"{report.id}.xlsx").name
|
|
||||||
archive.writestr(f"{code}-{safe_name}", data)
|
|
||||||
included.append(code)
|
|
||||||
if not included:
|
|
||||||
raise NotFoundError("no archived receipt files", code="SHIPPING.RECEIPT_FILE_NOT_FOUND")
|
|
||||||
|
|
||||||
user = _require_user()
|
|
||||||
db.session.add(build_transfer_audit_event(
|
|
||||||
event_type="TRANSFER_RECEIPT_FILES_DOWNLOADED",
|
|
||||||
aggregate_type="in_transit_source",
|
|
||||||
aggregate_id=",".join(included),
|
|
||||||
actor_type="user",
|
|
||||||
actor_id=str(user.id) if user.id else None,
|
|
||||||
actor_display=str(getattr(user, "name", "") or ""),
|
|
||||||
request_id=getattr(g, "request_id", None),
|
|
||||||
result="success",
|
|
||||||
))
|
|
||||||
db.session.commit()
|
|
||||||
buffer.seek(0)
|
|
||||||
return send_file(
|
|
||||||
buffer,
|
|
||||||
mimetype="application/zip",
|
|
||||||
as_attachment=True,
|
|
||||||
download_name=f"receipt-files-{len(included)}-source{'s' if len(included) > 1 else ''}.zip",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@in_transit_transfer_bp.route("/runs/<run_no>", methods=["GET"])
|
|
||||||
@require_transfer_permission
|
|
||||||
def get_run_api(run_no: str):
|
|
||||||
"""恢复 Run 最终结果(页面刷新/会话恢复)。"""
|
|
||||||
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))
|
|
||||||
|
|
||||||
|
|
||||||
@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")
|
|
||||||
precheck = run.prechecks[0] if run.prechecks else None
|
|
||||||
file_snapshot = precheck.file_snapshot_json if precheck and isinstance(precheck.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,
|
|
||||||
}
|
|
||||||
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 与聊天源文件预览解析)。
|
用途:知识库外部集成查询/下载接口(供 Dify Tool 与聊天源文件预览解析)。
|
||||||
依赖:Flask Blueprint、SQLAlchemy、IntegrationApiService、Kb* 模型。
|
依赖:Flask Blueprint、SQLAlchemy、IntegrationApiService、Kb* 模型。
|
||||||
+363
-48
@@ -1,13 +1,20 @@
|
|||||||
"""api/integration_connector.py
|
"""
|
||||||
|
backend/app/api/integration_connector/__init__.py
|
||||||
|
|
||||||
用途:Integration Connector Admin API——配置实体 CRUD、能力清单、能力调用端点与连接测试。
|
|
||||||
依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway、credential_crypto。
|
用途:Integration Connector Admin API——配置实体 CRUD、能力清单、能力调用端点、
|
||||||
|
连接测试与集成调用日志查询(列表 + 详情 + 同 operation 步骤时间线)。
|
||||||
|
依赖:Flask Blueprint、app.core.response、app.core.decorators.require_admin、gateway、credential_crypto、
|
||||||
|
models.integration_connector.CONNECTOR_TYPES / DB_KINDS(白名单同源)。
|
||||||
逻辑:全部 require_admin;能力调用只接受 {params, context, operation_id, idempotency_key},
|
逻辑:全部 require_admin;能力调用只接受 {params, context, operation_id, idempotency_key},
|
||||||
拒绝 interface_id(禁止覆盖 Binding);配置写操作做字段白名单校验,非法即 400。
|
拒绝 interface_id(禁止覆盖 Binding);配置写操作做字段白名单校验,非法即 400。
|
||||||
|
客户端实例 connector_type ∈ rest/soap/database;database 时 db_kind 必填且 ∈
|
||||||
|
mysql/oracle/sqlserver/postgresql,非 database 强制置 NULL。
|
||||||
接口定义的连接器类型由所属客户端实例服务端推导(单一事实源);接口定义与绑定的
|
接口定义的连接器类型由所属客户端实例服务端推导(单一事实源);接口定义与绑定的
|
||||||
状态只经 /publish /unpublish /retire /reopen 动作端点按 CONFIG_STATUS_TRANSITIONS
|
状态只经 /publish /unpublish /retire /reopen 动作端点按 CONFIG_STATUS_TRANSITIONS
|
||||||
转移(绑定发布附加就绪门禁:接口须已发布且客户端启用);绑定创建/更新做客户端
|
转移(绑定发布附加就绪门禁:每步接口须已发布且每步客户端启用);绑定以
|
||||||
与接口成对校验(接口定义必须属于所选客户端实例,错配即 400)。
|
steps_json 有序数组表达一对多配方(每步 interface_code + param_mapping_json),
|
||||||
|
客户端由各步接口归属自带;旧单步字段可合成单元素 steps(兼容窗)。
|
||||||
凭据引用状态为两态开关:PUT 仅允许 active/retired(rotating 不可进入,存量可置回
|
凭据引用状态为两态开关:PUT 仅允许 active/retired(rotating 不可进入,存量可置回
|
||||||
active 恢复);接口定义 enabled 冻结忽略传值(可用性只由 status 表达)。
|
active 恢复);接口定义 enabled 冻结忽略传值(可用性只由 status 表达)。
|
||||||
凭据引用 db 模式在服务端加密用户名/密码落库,接口响应永不回显明文/密文。
|
凭据引用 db 模式在服务端加密用户名/密码落库,接口响应永不回显明文/密文。
|
||||||
@@ -28,10 +35,12 @@ from app.core.errors import AppError, NotFoundError, ValidationError
|
|||||||
from app.core.response import ok
|
from app.core.response import ok
|
||||||
from app.models import (
|
from app.models import (
|
||||||
IntegrationBinding,
|
IntegrationBinding,
|
||||||
|
IntegrationCall,
|
||||||
IntegrationClientInstance,
|
IntegrationClientInstance,
|
||||||
IntegrationCredentialReference,
|
IntegrationCredentialReference,
|
||||||
IntegrationInterfaceDefinition,
|
IntegrationInterfaceDefinition,
|
||||||
)
|
)
|
||||||
|
from app.models.integration_connector import CONNECTOR_TYPES, DB_KINDS
|
||||||
from app.services.integration_connector.capability import list_capabilities
|
from app.services.integration_connector.capability import list_capabilities
|
||||||
from app.services.integration_connector.credential_types import (
|
from app.services.integration_connector.credential_types import (
|
||||||
build_secret_dict,
|
build_secret_dict,
|
||||||
@@ -40,12 +49,18 @@ from app.services.integration_connector.credential_types import (
|
|||||||
visible_fields,
|
visible_fields,
|
||||||
)
|
)
|
||||||
from app.services.integration_connector.gateway import get_capability_gateway
|
from app.services.integration_connector.gateway import get_capability_gateway
|
||||||
from app.services.integration_connector.security import CREDENTIAL_KEY_CONFIG_NAME, _DB_SECRET_CODES
|
from app.services.integration_connector.security import (
|
||||||
|
CREDENTIAL_KEY_CONFIG_NAME,
|
||||||
|
_DB_SECRET_CODES,
|
||||||
|
resolve_credential,
|
||||||
|
)
|
||||||
from app.services.integration_connector.transports.base import IntegrationCallResult, merge_client_config
|
from app.services.integration_connector.transports.base import IntegrationCallResult, merge_client_config
|
||||||
|
|
||||||
integration_connector_bp = Blueprint('integration_connector', __name__)
|
integration_connector_bp = Blueprint('integration_connector', __name__)
|
||||||
|
|
||||||
VALID_CONNECTOR_TYPES = ('rest', 'soap')
|
# 与模型 CONNECTOR_TYPES / DB_KINDS 同源,禁止本地另维护一份白名单。
|
||||||
|
VALID_CONNECTOR_TYPES = CONNECTOR_TYPES
|
||||||
|
VALID_DB_KINDS = DB_KINDS
|
||||||
VALID_STATUSES = ('draft', 'published', 'retired')
|
VALID_STATUSES = ('draft', 'published', 'retired')
|
||||||
VALID_SECRET_PROVIDERS = ('db', 'env')
|
VALID_SECRET_PROVIDERS = ('db', 'env')
|
||||||
# 凭据两态化(UI 可达状态):resolve_credential 只解析 active(fail-closed),「轮换中」
|
# 凭据两态化(UI 可达状态):resolve_credential 只解析 active(fail-closed),「轮换中」
|
||||||
@@ -70,6 +85,32 @@ def _require(value, field: str) -> None:
|
|||||||
raise ValidationError(f'{field} is required', details={'field': field})
|
raise ValidationError(f'{field} is required', details={'field': field})
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_db_kind(connector_type: str, raw_db_kind) -> str | None:
|
||||||
|
"""按连接器类型解析 db_kind:database 必填且 ∈ VALID_DB_KINDS;其余强制 NULL。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
connector_type: 已校验的连接器类型。
|
||||||
|
raw_db_kind: 请求体中的 db_kind(可为 None/空串)。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
合法库种字符串,或非 database 时的 None。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValidationError: database 缺省或未知库种(fail-closed,含历史别名 mssql)。
|
||||||
|
"""
|
||||||
|
if connector_type != 'database':
|
||||||
|
return None
|
||||||
|
kind = str(raw_db_kind or '').strip()
|
||||||
|
if not kind:
|
||||||
|
raise ValidationError('db_kind is required for database connector', details={'field': 'db_kind'})
|
||||||
|
if kind not in VALID_DB_KINDS:
|
||||||
|
raise ValidationError(
|
||||||
|
'invalid db_kind',
|
||||||
|
details={'field': 'db_kind', 'allowed': list(VALID_DB_KINDS)},
|
||||||
|
)
|
||||||
|
return kind
|
||||||
|
|
||||||
|
|
||||||
def _require_client(code: str) -> IntegrationClientInstance:
|
def _require_client(code: str) -> IntegrationClientInstance:
|
||||||
"""按编码取客户端实例;不存在即 400(接口定义的连接器类型以其为单一事实源)。"""
|
"""按编码取客户端实例;不存在即 400(接口定义的连接器类型以其为单一事实源)。"""
|
||||||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||||||
@@ -112,7 +153,8 @@ def _validate_binding_pair(client_code, interface_code) -> tuple[IntegrationClie
|
|||||||
"""绑定成对校验:接口定义必须属于所选客户端实例(接口归属即客户端归属)。
|
"""绑定成对校验:接口定义必须属于所选客户端实例(接口归属即客户端归属)。
|
||||||
|
|
||||||
错配组合会产生「拿 A 客户端的地址/凭据发 B 接口报文」的调用,创建/更新时直接
|
错配组合会产生「拿 A 客户端的地址/凭据发 B 接口报文」的调用,创建/更新时直接
|
||||||
400(fail-fast),不留给调用期 fail-closed。
|
400(fail-fast),不留给调用期 fail-closed。多步绑定时仅用于可选的绑定级
|
||||||
|
client_instance_code 与首步接口的一致性检查。
|
||||||
"""
|
"""
|
||||||
client = _require_client(str(client_code).strip())
|
client = _require_client(str(client_code).strip())
|
||||||
iface = _require_interface(str(interface_code).strip())
|
iface = _require_interface(str(interface_code).strip())
|
||||||
@@ -129,16 +171,101 @@ def _validate_binding_pair(client_code, interface_code) -> tuple[IntegrationClie
|
|||||||
return client, iface
|
return client, iface
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_binding_steps(body: dict) -> list[dict]:
|
||||||
|
"""校验并归一化绑定 steps_json(非空数组;每步 interface 存在且客户端可用)。
|
||||||
|
|
||||||
|
核心逻辑:优先读 steps_json;缺省时用旧单步字段合成一元素数组(兼容窗)。
|
||||||
|
每步 interface_code 必须存在,其归属客户端必须存在(绑定的客户端实例族);
|
||||||
|
param_mapping_json 须为 dict。返回供落库的 [{interface_code, param_mapping_json}, ...]。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
body: 创建/更新请求体。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
归一化后的步骤列表(至少一元素)。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValidationError: 空数组、步形状非法、接口不存在、映射非 dict。
|
||||||
|
"""
|
||||||
|
raw = body.get('steps_json')
|
||||||
|
if raw is None:
|
||||||
|
# 兼容窗:旧单步 API 字段 → 单元素 steps
|
||||||
|
iface_code = body.get('interface_definition_code')
|
||||||
|
if not iface_code:
|
||||||
|
raise ValidationError(
|
||||||
|
'steps_json is required',
|
||||||
|
code='INTEGRATION.BINDING_STEPS_INVALID',
|
||||||
|
details={'field': 'steps_json'},
|
||||||
|
)
|
||||||
|
raw = [{
|
||||||
|
'interface_code': iface_code,
|
||||||
|
'param_mapping_json': body.get('param_mapping_json') or {},
|
||||||
|
}]
|
||||||
|
if not isinstance(raw, list) or len(raw) == 0:
|
||||||
|
raise ValidationError(
|
||||||
|
'steps_json must be a non-empty array',
|
||||||
|
code='INTEGRATION.BINDING_STEPS_INVALID',
|
||||||
|
details={'field': 'steps_json'},
|
||||||
|
)
|
||||||
|
|
||||||
|
normalized: list[dict] = []
|
||||||
|
for idx, step in enumerate(raw):
|
||||||
|
if not isinstance(step, dict):
|
||||||
|
raise ValidationError(
|
||||||
|
'each step must be an object',
|
||||||
|
code='INTEGRATION.BINDING_STEPS_INVALID',
|
||||||
|
details={'field': 'steps_json', 'index': idx},
|
||||||
|
)
|
||||||
|
iface_code = step.get('interface_code') or step.get('interface_definition_code')
|
||||||
|
_require(iface_code, f'steps_json[{idx}].interface_code')
|
||||||
|
mapping = step.get('param_mapping_json', step.get('param_mapping', {}))
|
||||||
|
if mapping is None:
|
||||||
|
mapping = {}
|
||||||
|
if not isinstance(mapping, dict):
|
||||||
|
raise ValidationError(
|
||||||
|
'step param_mapping_json must be an object',
|
||||||
|
code='INTEGRATION.BINDING_STEPS_INVALID',
|
||||||
|
details={'field': 'steps_json', 'index': idx, 'key': 'param_mapping_json'},
|
||||||
|
)
|
||||||
|
iface = _require_interface(str(iface_code).strip())
|
||||||
|
# 客户端实例族:接口归属客户端必须存在(跨步可不同客户端,如 database+soap)。
|
||||||
|
_require_client(iface.client_instance_code)
|
||||||
|
normalized.append({
|
||||||
|
'interface_code': iface.code,
|
||||||
|
'param_mapping_json': mapping,
|
||||||
|
})
|
||||||
|
|
||||||
|
# 若请求仍带绑定级 client_instance_code,与首步接口做成对校验(防错配镜像列)。
|
||||||
|
binding_client = body.get('client_instance_code')
|
||||||
|
if binding_client is not None and str(binding_client).strip():
|
||||||
|
_validate_binding_pair(binding_client, normalized[0]['interface_code'])
|
||||||
|
|
||||||
|
return normalized
|
||||||
|
|
||||||
|
|
||||||
|
def _mirror_legacy_binding_columns(steps: list[dict]) -> tuple[str, str, dict]:
|
||||||
|
"""由归一化 steps 镜像旧 NOT NULL 列(首步);P2 删列前保持可写。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(client_instance_code, interface_definition_code, param_mapping_json)
|
||||||
|
"""
|
||||||
|
first = steps[0]
|
||||||
|
iface = _require_interface(first['interface_code'])
|
||||||
|
return iface.client_instance_code, iface.code, dict(first.get('param_mapping_json') or {})
|
||||||
|
|
||||||
|
|
||||||
def _interface_transition(iface, action: str) -> None:
|
def _interface_transition(iface, action: str) -> None:
|
||||||
"""按转移表校验并落库接口定义状态;非法动作或源状态不符即 400。"""
|
"""按转移表校验并落库接口定义状态;非法动作或源状态不符即 400。"""
|
||||||
_apply_status_transition(iface, action, kind='interface')
|
_apply_status_transition(iface, action, kind='interface')
|
||||||
|
|
||||||
|
|
||||||
def _serialize_client(client) -> dict:
|
def _serialize_client(client) -> dict:
|
||||||
|
"""客户端实例序列化(含 database 专列 db_kind;非 database 为 null)。"""
|
||||||
return {
|
return {
|
||||||
'id': client.id, 'code': client.code, 'name': client.name,
|
'id': client.id, 'code': client.code, 'name': client.name,
|
||||||
'connector_type': client.connector_type, 'environment': client.environment,
|
'connector_type': client.connector_type, 'environment': client.environment,
|
||||||
'endpoint': client.endpoint, 'timeout_seconds': client.timeout_seconds,
|
'endpoint': client.endpoint, 'timeout_seconds': client.timeout_seconds,
|
||||||
|
'db_kind': client.db_kind,
|
||||||
'config_json': client.config_json or {}, 'credential_ref_code': client.credential_ref_code,
|
'config_json': client.config_json or {}, 'credential_ref_code': client.credential_ref_code,
|
||||||
'enabled': client.enabled,
|
'enabled': client.enabled,
|
||||||
}
|
}
|
||||||
@@ -156,9 +283,11 @@ def _serialize_interface(iface) -> dict:
|
|||||||
|
|
||||||
|
|
||||||
def _serialize_binding(binding) -> dict:
|
def _serialize_binding(binding) -> dict:
|
||||||
|
"""绑定序列化:含 steps_json;旧单步列仍回显(P2 删前列镜像)。"""
|
||||||
return {
|
return {
|
||||||
'id': binding.id, 'capability': binding.capability,
|
'id': binding.id, 'capability': binding.capability,
|
||||||
'context_selector_json': binding.context_selector_json or {},
|
'context_selector_json': binding.context_selector_json or {},
|
||||||
|
'steps_json': binding.steps_json or [],
|
||||||
'param_mapping_json': binding.param_mapping_json or {},
|
'param_mapping_json': binding.param_mapping_json or {},
|
||||||
'client_instance_code': binding.client_instance_code,
|
'client_instance_code': binding.client_instance_code,
|
||||||
'interface_definition_code': binding.interface_definition_code,
|
'interface_definition_code': binding.interface_definition_code,
|
||||||
@@ -276,6 +405,7 @@ def list_client_instances():
|
|||||||
@integration_connector_bp.route('/client-instances', methods=['POST'])
|
@integration_connector_bp.route('/client-instances', methods=['POST'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def create_client_instance():
|
def create_client_instance():
|
||||||
|
"""创建客户端实例;database 类型强制校验 db_kind 四库枚举,非 database 置 NULL。"""
|
||||||
body = request.get_json(silent=True) or {}
|
body = request.get_json(silent=True) or {}
|
||||||
connector_type = str(body.get('connector_type') or '').strip()
|
connector_type = str(body.get('connector_type') or '').strip()
|
||||||
_require(body.get('code'), 'code')
|
_require(body.get('code'), 'code')
|
||||||
@@ -284,11 +414,13 @@ def create_client_instance():
|
|||||||
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
|
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
|
||||||
if IntegrationClientInstance.query.filter_by(code=body['code']).first():
|
if IntegrationClientInstance.query.filter_by(code=body['code']).first():
|
||||||
raise ValidationError('client instance code already exists', code='RESOURCE.CONFLICT')
|
raise ValidationError('client instance code already exists', code='RESOURCE.CONFLICT')
|
||||||
|
db_kind = _resolve_db_kind(connector_type, body.get('db_kind'))
|
||||||
client = IntegrationClientInstance(
|
client = IntegrationClientInstance(
|
||||||
code=str(body['code']).strip(), name=str(body['name']).strip(),
|
code=str(body['code']).strip(), name=str(body['name']).strip(),
|
||||||
connector_type=connector_type, environment=str(body.get('environment') or 'prod').strip(),
|
connector_type=connector_type, environment=str(body.get('environment') or 'prod').strip(),
|
||||||
endpoint=(str(body.get('endpoint') or '').strip() or None),
|
endpoint=(str(body.get('endpoint') or '').strip() or None),
|
||||||
timeout_seconds=(int(body['timeout_seconds']) if body.get('timeout_seconds') is not None else None),
|
timeout_seconds=(int(body['timeout_seconds']) if body.get('timeout_seconds') is not None else None),
|
||||||
|
db_kind=db_kind,
|
||||||
config_json=body.get('config_json') or {},
|
config_json=body.get('config_json') or {},
|
||||||
credential_ref_code=body.get('credential_ref_code'),
|
credential_ref_code=body.get('credential_ref_code'),
|
||||||
enabled=bool(body.get('enabled', True)),
|
enabled=bool(body.get('enabled', True)),
|
||||||
@@ -323,7 +455,10 @@ def delete_client_instance(code):
|
|||||||
@integration_connector_bp.route('/client-instances/<code>', methods=['PUT'])
|
@integration_connector_bp.route('/client-instances/<code>', methods=['PUT'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def update_client_instance(code):
|
def update_client_instance(code):
|
||||||
"""更新客户端实例(code 不变;可改名称/连接配置/凭据引用/启停)。"""
|
"""更新客户端实例(code 不变;可改名称/连接配置/凭据引用/启停/db_kind)。
|
||||||
|
|
||||||
|
database 类型必填合法 db_kind;切离 database 时强制清空 db_kind。
|
||||||
|
"""
|
||||||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||||||
if client is None:
|
if client is None:
|
||||||
raise NotFoundError('client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND')
|
raise NotFoundError('client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND')
|
||||||
@@ -348,6 +483,9 @@ def update_client_instance(code):
|
|||||||
client.credential_ref_code = body.get('credential_ref_code')
|
client.credential_ref_code = body.get('credential_ref_code')
|
||||||
if 'enabled' in body:
|
if 'enabled' in body:
|
||||||
client.enabled = bool(body.get('enabled', True))
|
client.enabled = bool(body.get('enabled', True))
|
||||||
|
# 最终类型决定 db_kind:database 必填合法值;rest/soap 强制 NULL。
|
||||||
|
raw_kind = body['db_kind'] if 'db_kind' in body else client.db_kind
|
||||||
|
client.db_kind = _resolve_db_kind(connector_type, raw_kind)
|
||||||
from app import db
|
from app import db
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return ok(_serialize_client(client))
|
return ok(_serialize_client(client))
|
||||||
@@ -482,18 +620,22 @@ def list_bindings():
|
|||||||
@integration_connector_bp.route('/bindings', methods=['POST'])
|
@integration_connector_bp.route('/bindings', methods=['POST'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def create_binding():
|
def create_binding():
|
||||||
"""创建绑定:成对校验客户端与接口后落库;新建固定落 draft,发布走 /publish 动作端点。"""
|
"""创建绑定:校验 steps_json 后落库;新建固定落 draft,发布走 /publish 动作端点。
|
||||||
|
|
||||||
|
核心逻辑:归一化 steps → 镜像首步到旧列(NOT NULL)→ 落 draft。
|
||||||
|
仍接受旧单步字段(无 steps_json 时合成一元素数组)。
|
||||||
|
"""
|
||||||
body = request.get_json(silent=True) or {}
|
body = request.get_json(silent=True) or {}
|
||||||
_require(body.get('capability'), 'capability')
|
_require(body.get('capability'), 'capability')
|
||||||
_require(body.get('client_instance_code'), 'client_instance_code')
|
steps = _normalize_binding_steps(body)
|
||||||
_require(body.get('interface_definition_code'), 'interface_definition_code')
|
client_code, iface_code, param_mapping = _mirror_legacy_binding_columns(steps)
|
||||||
client, iface = _validate_binding_pair(body['client_instance_code'], body['interface_definition_code'])
|
|
||||||
binding = IntegrationBinding(
|
binding = IntegrationBinding(
|
||||||
capability=body['capability'],
|
capability=body['capability'],
|
||||||
context_selector_json=body.get('context_selector_json') or {},
|
context_selector_json=body.get('context_selector_json') or {},
|
||||||
param_mapping_json=body.get('param_mapping_json') or {},
|
steps_json=steps,
|
||||||
client_instance_code=client.code,
|
param_mapping_json=param_mapping,
|
||||||
interface_definition_code=iface.code,
|
client_instance_code=client_code,
|
||||||
|
interface_definition_code=iface_code,
|
||||||
mapping_version=int(body.get('mapping_version') or 1),
|
mapping_version=int(body.get('mapping_version') or 1),
|
||||||
priority=int(body.get('priority') or 0),
|
priority=int(body.get('priority') or 0),
|
||||||
environment=str(body.get('environment') or 'prod').strip(),
|
environment=str(body.get('environment') or 'prod').strip(),
|
||||||
@@ -508,10 +650,14 @@ def create_binding():
|
|||||||
@integration_connector_bp.route('/bindings/<int:binding_id>', methods=['PUT'])
|
@integration_connector_bp.route('/bindings/<int:binding_id>', methods=['PUT'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def update_binding(binding_id):
|
def update_binding(binding_id):
|
||||||
"""更新绑定(capability 不变;可改 context 选择器、客户端/接口、映射版本、优先级、环境、生效区间)。
|
"""更新绑定(可改 context / steps_json / 映射版本 / 优先级 / 环境 / 生效区间)。
|
||||||
|
|
||||||
状态不在此改写(须经 /publish /unpublish /retire /reopen 动作端点按转移表流转);
|
状态不在此改写(须经动作端点按转移表流转)。规则(评审修正轮收紧后):
|
||||||
客户端与接口成对校验:以变更后的最终组合为准,接口定义不属于该客户端即 400。
|
[1] steps_json 与旧单步字段(interface_definition_code/param_mapping_json)同 PUT
|
||||||
|
属矛盾载荷 → 400(旧键会被静默忽略、部分生效无提示);
|
||||||
|
[2] 三把旧钥匙(interface_definition_code/param_mapping_json/client_instance_code)
|
||||||
|
任一出现在多步绑定 PUT → 400(兼容窗会合成单元素 steps 回写、静默销毁第 2..n 步);
|
||||||
|
[3] 单步绑定的旧字段 PUT 走兼容窗(换绑接口 / 仅更新首步映射);纯 steps_json PUT 不受限。
|
||||||
"""
|
"""
|
||||||
from app import db
|
from app import db
|
||||||
binding = db.session.get(IntegrationBinding, binding_id)
|
binding = db.session.get(IntegrationBinding, binding_id)
|
||||||
@@ -523,23 +669,83 @@ def update_binding(binding_id):
|
|||||||
binding.capability = body['capability']
|
binding.capability = body['capability']
|
||||||
if 'context_selector_json' in body:
|
if 'context_selector_json' in body:
|
||||||
binding.context_selector_json = body.get('context_selector_json') or {}
|
binding.context_selector_json = body.get('context_selector_json') or {}
|
||||||
if 'param_mapping_json' in body:
|
|
||||||
binding.param_mapping_json = body.get('param_mapping_json') or {}
|
if 'steps_json' in body:
|
||||||
new_client_code = body.get('client_instance_code')
|
# 评审 P2-2:矛盾载荷 fail-fast——steps_json 分支本会静默忽略旧单步键(部分生效无提示)。
|
||||||
new_iface_code = body.get('interface_definition_code')
|
# client_instance_code 不在矛盾集:它在 steps_json 分支仍被消费(首步成对校验)。
|
||||||
if new_client_code is not None:
|
conflicts = sorted(
|
||||||
_require(new_client_code, 'client_instance_code')
|
key for key in ('interface_definition_code', 'param_mapping_json') if key in body
|
||||||
if new_iface_code is not None:
|
|
||||||
_require(new_iface_code, 'interface_definition_code')
|
|
||||||
if new_client_code is not None or new_iface_code is not None:
|
|
||||||
_validate_binding_pair(
|
|
||||||
new_client_code if new_client_code is not None else binding.client_instance_code,
|
|
||||||
new_iface_code if new_iface_code is not None else binding.interface_definition_code,
|
|
||||||
)
|
)
|
||||||
if new_client_code is not None:
|
if conflicts:
|
||||||
binding.client_instance_code = str(new_client_code).strip()
|
raise ValidationError(
|
||||||
if new_iface_code is not None:
|
'steps_json PUT cannot carry legacy single-step fields; they would be silently ignored',
|
||||||
binding.interface_definition_code = str(new_iface_code).strip()
|
code='INTEGRATION.BINDING_LEGACY_PUT_REJECTED',
|
||||||
|
details={
|
||||||
|
'fields': conflicts,
|
||||||
|
'conflicting_with': 'steps_json',
|
||||||
|
'hint': 'submit the full ordered recipe via steps_json only',
|
||||||
|
},
|
||||||
|
)
|
||||||
|
merge_body = {
|
||||||
|
'steps_json': body['steps_json'],
|
||||||
|
'client_instance_code': body.get('client_instance_code'),
|
||||||
|
}
|
||||||
|
steps = _normalize_binding_steps(merge_body)
|
||||||
|
client_code, iface_code, param_mapping = _mirror_legacy_binding_columns(steps)
|
||||||
|
binding.steps_json = steps
|
||||||
|
binding.client_instance_code = client_code
|
||||||
|
binding.interface_definition_code = iface_code
|
||||||
|
binding.param_mapping_json = param_mapping
|
||||||
|
elif 'interface_definition_code' in body or 'client_instance_code' in body or 'param_mapping_json' in body:
|
||||||
|
# 评审 P1 守卫:三把旧钥匙(含 client_instance_code)任一出现在多步绑定 PUT,
|
||||||
|
# 都会经兼容窗用旧单步列合成单元素 steps 回写、静默销毁第 2..n 步 → fail-fast 400。
|
||||||
|
legacy_keys = sorted(
|
||||||
|
key for key in ('interface_definition_code', 'param_mapping_json', 'client_instance_code')
|
||||||
|
if key in body
|
||||||
|
)
|
||||||
|
if binding.steps_json and len(binding.steps_json) > 1:
|
||||||
|
raise ValidationError(
|
||||||
|
'legacy single-step fields cannot update a multi-step binding; use steps_json',
|
||||||
|
code='INTEGRATION.BINDING_LEGACY_PUT_REJECTED',
|
||||||
|
details={
|
||||||
|
'fields': legacy_keys,
|
||||||
|
'steps_count': len(binding.steps_json),
|
||||||
|
'hint': 'submit the full ordered recipe via steps_json',
|
||||||
|
},
|
||||||
|
)
|
||||||
|
# 兼容窗:旧单步字段 → 重写/局部更新 steps
|
||||||
|
if (
|
||||||
|
'param_mapping_json' in body
|
||||||
|
and 'interface_definition_code' not in body
|
||||||
|
and 'client_instance_code' not in body
|
||||||
|
and binding.steps_json
|
||||||
|
):
|
||||||
|
steps = [dict(s) if isinstance(s, dict) else s for s in binding.steps_json]
|
||||||
|
first = dict(steps[0])
|
||||||
|
first['param_mapping_json'] = body.get('param_mapping_json') or {}
|
||||||
|
steps[0] = first
|
||||||
|
steps = _normalize_binding_steps({
|
||||||
|
'steps_json': steps,
|
||||||
|
'client_instance_code': binding.client_instance_code,
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
steps = _normalize_binding_steps({
|
||||||
|
'interface_definition_code': body.get(
|
||||||
|
'interface_definition_code', binding.interface_definition_code,
|
||||||
|
),
|
||||||
|
'client_instance_code': body.get(
|
||||||
|
'client_instance_code', binding.client_instance_code,
|
||||||
|
),
|
||||||
|
'param_mapping_json': body.get(
|
||||||
|
'param_mapping_json', binding.param_mapping_json or {},
|
||||||
|
),
|
||||||
|
})
|
||||||
|
client_code, iface_code, param_mapping = _mirror_legacy_binding_columns(steps)
|
||||||
|
binding.steps_json = steps
|
||||||
|
binding.client_instance_code = client_code
|
||||||
|
binding.interface_definition_code = iface_code
|
||||||
|
binding.param_mapping_json = param_mapping
|
||||||
|
|
||||||
if body.get('mapping_version') is not None:
|
if body.get('mapping_version') is not None:
|
||||||
binding.mapping_version = int(body.get('mapping_version') or 1)
|
binding.mapping_version = int(body.get('mapping_version') or 1)
|
||||||
if body.get('priority') is not None:
|
if body.get('priority') is not None:
|
||||||
@@ -550,7 +756,6 @@ def update_binding(binding_id):
|
|||||||
binding.effective_from = body['effective_from'] or None
|
binding.effective_from = body['effective_from'] or None
|
||||||
if body.get('effective_to') is not None:
|
if body.get('effective_to') is not None:
|
||||||
binding.effective_to = body['effective_to'] or None
|
binding.effective_to = body['effective_to'] or None
|
||||||
from app import db
|
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return ok(_serialize_binding(binding))
|
return ok(_serialize_binding(binding))
|
||||||
|
|
||||||
@@ -560,7 +765,7 @@ def update_binding(binding_id):
|
|||||||
def _do_binding_lifecycle(binding_id: int, action: str):
|
def _do_binding_lifecycle(binding_id: int, action: str):
|
||||||
"""动作端点共用体:取绑定 → 按转移表转移 → 落库并回显。
|
"""动作端点共用体:取绑定 → 按转移表转移 → 落库并回显。
|
||||||
|
|
||||||
发布(publish)附加就绪门禁:引用的接口定义须已发布、客户端实例须启用,
|
发布(publish)附加就绪门禁:steps_json 每步接口须已发布、每步客户端须启用,
|
||||||
否则 400——避免出现列表「已发布」但调用期永远 fail-closed 的死绑定
|
否则 400——避免出现列表「已发布」但调用期永远 fail-closed 的死绑定
|
||||||
(与 binding.resolve_binding 的调用期门禁同一语义)。
|
(与 binding.resolve_binding 的调用期门禁同一语义)。
|
||||||
"""
|
"""
|
||||||
@@ -569,17 +774,44 @@ def _do_binding_lifecycle(binding_id: int, action: str):
|
|||||||
if binding is None:
|
if binding is None:
|
||||||
raise NotFoundError('binding not found', code='INTEGRATION.BINDING_NOT_FOUND')
|
raise NotFoundError('binding not found', code='INTEGRATION.BINDING_NOT_FOUND')
|
||||||
if action == 'publish':
|
if action == 'publish':
|
||||||
client = IntegrationClientInstance.query.filter_by(code=binding.client_instance_code).first()
|
raw_steps = list(binding.steps_json or [])
|
||||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=binding.interface_definition_code).first()
|
if not raw_steps and binding.interface_definition_code:
|
||||||
if client is None or iface is None or iface.status != 'published' or not client.enabled:
|
raw_steps = [{
|
||||||
|
'interface_code': binding.interface_definition_code,
|
||||||
|
'param_mapping_json': binding.param_mapping_json or {},
|
||||||
|
}]
|
||||||
|
if not raw_steps:
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
'binding target not ready: interface must be published and client instance enabled',
|
'binding target not ready: steps_json is empty',
|
||||||
code='INTEGRATION.BINDING_TARGET_NOT_READY',
|
code='INTEGRATION.BINDING_TARGET_NOT_READY',
|
||||||
details={
|
details={'steps_json': []},
|
||||||
'client_instance_code': binding.client_instance_code,
|
|
||||||
'interface_definition_code': binding.interface_definition_code,
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
|
for idx, step in enumerate(raw_steps):
|
||||||
|
if not isinstance(step, dict):
|
||||||
|
raise ValidationError(
|
||||||
|
'binding target not ready: invalid step',
|
||||||
|
code='INTEGRATION.BINDING_TARGET_NOT_READY',
|
||||||
|
details={'index': idx},
|
||||||
|
)
|
||||||
|
iface_code = str(step.get('interface_code') or '').strip()
|
||||||
|
iface = IntegrationInterfaceDefinition.query.filter_by(code=iface_code).first()
|
||||||
|
client = (
|
||||||
|
IntegrationClientInstance.query.filter_by(code=iface.client_instance_code).first()
|
||||||
|
if iface is not None else None
|
||||||
|
)
|
||||||
|
if client is None or iface is None or iface.status != 'published' or not client.enabled:
|
||||||
|
raise ValidationError(
|
||||||
|
'binding target not ready: each step interface must be published '
|
||||||
|
'and client instance enabled',
|
||||||
|
code='INTEGRATION.BINDING_TARGET_NOT_READY',
|
||||||
|
details={
|
||||||
|
'index': idx,
|
||||||
|
'interface_code': iface_code,
|
||||||
|
'client_instance_code': getattr(iface, 'client_instance_code', None),
|
||||||
|
'iface_status': getattr(iface, 'status', None),
|
||||||
|
'client_enabled': getattr(client, 'enabled', None),
|
||||||
|
},
|
||||||
|
)
|
||||||
_apply_status_transition(binding, action, kind='binding')
|
_apply_status_transition(binding, action, kind='binding')
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return ok(_serialize_binding(binding))
|
return ok(_serialize_binding(binding))
|
||||||
@@ -718,8 +950,8 @@ def update_credential_reference(code):
|
|||||||
def test_connection(code):
|
def test_connection(code):
|
||||||
"""连接测试探针:只证明网络/服务可达(设计文档:连接测试不做业务调用)。
|
"""连接测试探针:只证明网络/服务可达(设计文档:连接测试不做业务调用)。
|
||||||
|
|
||||||
配置兼容层与 binding.resolve_binding 同源:endpoint/timeout_seconds 独立列
|
配置兼容层与 binding.resolve_binding 同源:endpoint/timeout_seconds/db_kind
|
||||||
拼回 config_json 后再交给 transport,否则存独立列的地址会被误判为未冻结。
|
独立列拼回 config_json 后再交给 transport,否则存独立列的地址/库种会被误判为未冻结。
|
||||||
"""
|
"""
|
||||||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||||||
if client is None:
|
if client is None:
|
||||||
@@ -735,8 +967,12 @@ def test_connection(code):
|
|||||||
'config_json': client.config_json or {},
|
'config_json': client.config_json or {},
|
||||||
'endpoint': client.endpoint,
|
'endpoint': client.endpoint,
|
||||||
'timeout_seconds': client.timeout_seconds,
|
'timeout_seconds': client.timeout_seconds,
|
||||||
|
'db_kind': client.db_kind,
|
||||||
}),
|
}),
|
||||||
'credential': {},
|
# 连接测试按设计须证明「网络与认证」可用(数据库直连无凭据无法建连):
|
||||||
|
# 有凭据引用时解析真实凭据(db 解密 / env 注入,与 engine 调用链同源),
|
||||||
|
# 无引用(匿名)为空 dict;解析失败 fail-closed 抛 CredentialUnresolvedError。
|
||||||
|
'credential': resolve_credential(client.credential_ref_code) if client.credential_ref_code else {},
|
||||||
}
|
}
|
||||||
probe = getattr(transport, 'probe', None)
|
probe = getattr(transport, 'probe', None)
|
||||||
if probe is not None:
|
if probe is not None:
|
||||||
@@ -747,3 +983,82 @@ def test_connection(code):
|
|||||||
raw = transport.call(client=client_payload, interface={'request_spec_json': {}}, request={})
|
raw = transport.call(client=client_payload, interface={'request_spec_json': {}}, request={})
|
||||||
ok_flag = raw.get('status') not in ('business_failed', 'technical_failed', 'timeout', 'result_unknown')
|
ok_flag = raw.get('status') not in ('business_failed', 'technical_failed', 'timeout', 'result_unknown')
|
||||||
return ok({'ok': ok_flag, 'status': 'success' if ok_flag else 'failed', 'result': raw})
|
return ok({'ok': ok_flag, 'status': 'success' if ok_flag else 'failed', 'result': raw})
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 集成调用日志查询 ----
|
||||||
|
|
||||||
|
@integration_connector_bp.route('/calls', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def list_integration_calls_api():
|
||||||
|
"""集成调用日志分页查询(能力无关通用口径)。
|
||||||
|
|
||||||
|
筛选:capability/interface_code/client_code/connector_type/status/
|
||||||
|
operation_id/trace_id/business_ref 精确;keyword 对请求摘要 JSON 文本模糊;
|
||||||
|
date_from/date_to=YYYY-MM-DD(按 created_at 闭区间,date_to 补全天)。
|
||||||
|
"""
|
||||||
|
from sqlalchemy import cast, String
|
||||||
|
|
||||||
|
args = request.args
|
||||||
|
query = IntegrationCall.query
|
||||||
|
for field in ('capability', 'status', 'operation_id', 'trace_id', 'business_ref'):
|
||||||
|
value = (args.get(field) or '').strip()
|
||||||
|
if value:
|
||||||
|
query = query.filter(getattr(IntegrationCall, field) == value)
|
||||||
|
for json_field in ('interface_code', 'client_code', 'connector_type'):
|
||||||
|
value = (args.get(json_field) or '').strip()
|
||||||
|
if value:
|
||||||
|
query = query.filter(
|
||||||
|
IntegrationCall.binding_snapshot_json[json_field].as_string() == value)
|
||||||
|
keyword = (args.get('keyword') or '').strip()
|
||||||
|
if keyword:
|
||||||
|
query = query.filter(
|
||||||
|
cast(IntegrationCall.request_summary_json, String).ilike(f'%{keyword}%'))
|
||||||
|
date_from = (args.get('date_from') or '').strip()
|
||||||
|
if date_from:
|
||||||
|
query = query.filter(IntegrationCall.created_at >= f'{date_from} 00:00:00')
|
||||||
|
date_to = (args.get('date_to') or '').strip()
|
||||||
|
if date_to:
|
||||||
|
query = query.filter(IntegrationCall.created_at <= f'{date_to} 23:59:59.999999')
|
||||||
|
|
||||||
|
page = max(int(args.get('page') or 1), 1)
|
||||||
|
page_size = min(max(int(args.get('page_size') or 20), 1), 100)
|
||||||
|
total = query.count()
|
||||||
|
rows = (query.order_by(IntegrationCall.id.desc())
|
||||||
|
.offset((page - 1) * page_size).limit(page_size).all())
|
||||||
|
|
||||||
|
def _row(c: IntegrationCall) -> dict:
|
||||||
|
snap = c.binding_snapshot_json or {}
|
||||||
|
return {'id': c.id, 'created_at': c.created_at.isoformat() if c.created_at else None,
|
||||||
|
'capability': c.capability, 'operation_id': c.operation_id,
|
||||||
|
'trace_id': c.trace_id, 'status': c.status, 'elapsed_ms': c.elapsed_ms,
|
||||||
|
'business_ref': c.business_ref,
|
||||||
|
'client_code': snap.get('client_code'), 'interface_code': snap.get('interface_code'),
|
||||||
|
'connector_type': snap.get('connector_type'),
|
||||||
|
'step_index': snap.get('step_index'), 'step_count': snap.get('step_count')}
|
||||||
|
|
||||||
|
return ok({'total': total, 'page': page, 'page_size': page_size,
|
||||||
|
'items': [_row(c) for c in rows]})
|
||||||
|
|
||||||
|
|
||||||
|
@integration_connector_bp.route('/calls/<int:call_id>', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def get_integration_call_api(call_id: int):
|
||||||
|
"""单条全量(含 wire_json/request/response/绑定快照)+ 同 operation_id 步骤时间线。"""
|
||||||
|
call = IntegrationCall.query.get(call_id)
|
||||||
|
if call is None:
|
||||||
|
raise NotFoundError('integration call not found', code='INTEGRATION.CALL_NOT_FOUND')
|
||||||
|
full = {'id': call.id, 'created_at': call.created_at.isoformat() if call.created_at else None,
|
||||||
|
'capability': call.capability, 'operation_id': call.operation_id,
|
||||||
|
'trace_id': call.trace_id, 'status': call.status, 'elapsed_ms': call.elapsed_ms,
|
||||||
|
'business_ref': call.business_ref,
|
||||||
|
'binding_snapshot_json': call.binding_snapshot_json or {},
|
||||||
|
'request_summary_json': call.request_summary_json or {},
|
||||||
|
'response_summary_json': call.response_summary_json or {},
|
||||||
|
'wire_json': call.wire_json}
|
||||||
|
siblings = (IntegrationCall.query.filter_by(operation_id=call.operation_id)
|
||||||
|
.order_by(IntegrationCall.id.asc()).all())
|
||||||
|
timeline = [{'id': c.id, 'step_index': (c.binding_snapshot_json or {}).get('step_index'),
|
||||||
|
'step_count': (c.binding_snapshot_json or {}).get('step_count'),
|
||||||
|
'interface_code': (c.binding_snapshot_json or {}).get('interface_code'),
|
||||||
|
'status': c.status, 'elapsed_ms': c.elapsed_ms} for c in siblings]
|
||||||
|
return ok({'call': full, 'timeline': timeline})
|
||||||
@@ -1,7 +1,9 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/api/internal/__init__.py
|
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
|
from app.api.internal.jobs import internal_jobs_bp # noqa: F401
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,243 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/api/internal/jobs.py
|
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/工作台侧栏入口展示。
|
用途:已登录用户读取启用中的关联服务,供 Chat/工作台侧栏入口展示。
|
||||||
依赖:JWT current-user、linked_service_service。
|
依赖:JWT current-user、linked_service_service。
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/api/maintenance.py
|
backend/app/api/maintenance/__init__.py
|
||||||
|
|
||||||
用途:设备维保助手 HTTP API,当前提供设备台账配置与 Excel 导入能力。
|
用途:设备维保助手 HTTP API,当前提供设备台账配置与 Excel 导入能力。
|
||||||
依赖:JWT 当前用户、maintenance_ledger_service、Flask Blueprint/send_file。
|
依赖:JWT 当前用户、maintenance_ledger_service、Flask Blueprint/send_file。
|
||||||
@@ -55,9 +55,9 @@ def _require_ledger_admin():
|
|||||||
ForbiddenError: 当前角色不允许写入台账或维修记录。
|
ForbiddenError: 当前角色不允许写入台账或维修记录。
|
||||||
"""
|
"""
|
||||||
user = _require_user()
|
user = _require_user()
|
||||||
if getattr(user, 'role', None) not in {'admin', 'maintenance_manager'}:
|
if user.has_feature_permission('maintenance.ledger_write'):
|
||||||
raise ForbiddenError('Maintenance manager privilege required')
|
return user
|
||||||
return user
|
raise ForbiddenError('Maintenance manager privilege required')
|
||||||
|
|
||||||
|
|
||||||
def _record_list_filters_from_request() -> dict[str, Any]:
|
def _record_list_filters_from_request() -> dict[str, Any]:
|
||||||
@@ -1,149 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/api/maintenance_tools.py
|
backend/app/api/maintenance_tools.py
|
||||||
|
|
||||||
用途:设备维保助手 Dify Tool API,只开放只读查询工具。
|
用途:兼容旧 import 路径的薄 shim(真实现已迁至 api/tools/maintenance.py)。
|
||||||
依赖:maintenance_chat_service、maintenance_record_service、OpenAPI 构建、Tool API 基地址解析。
|
依赖:app.api.tools.maintenance。
|
||||||
逻辑:Dify 复杂问法调用本蓝图查询设备台账/维修记录;明确查询仍由 chat.py 本地直答,写操作仍走 HXOPS 管理面板。
|
逻辑:保留 Blueprint;新代码请从 app.api.tools 导入。
|
||||||
"""
|
"""
|
||||||
|
from app.api.tools.maintenance import maintenance_tool_bp # noqa: F401
|
||||||
|
|
||||||
from __future__ import annotations
|
__all__ = ['maintenance_tool_bp']
|
||||||
|
|
||||||
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,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
|
backend/app/api/procurement_contract_tools.py
|
||||||
|
|
||||||
Purpose: Chat/tool-facing procurement contract review APIs.
|
用途:兼容旧 import 路径的薄 shim(真实现已迁至 api/tools/procurement_contract.py)。
|
||||||
Dependencies: procurement_contract services, JWT current user, unified response envelope.
|
依赖:app.api.tools.procurement_contract。
|
||||||
Flow: Authenticated users upload comparison files, start reviews, query own history, and download own reports.
|
逻辑:保留 Blueprint;新代码请从 app.api.tools 导入。
|
||||||
"""
|
"""
|
||||||
|
from app.api.tools.procurement_contract import procurement_contract_bp # noqa: F401
|
||||||
|
|
||||||
from __future__ import annotations
|
__all__ = ['procurement_contract_bp']
|
||||||
|
|
||||||
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))
|
|
||||||
@@ -67,7 +67,7 @@ def update_schedule_task_config(task_id: int):
|
|||||||
|
|
||||||
config_data = data.get('config', data)
|
config_data = data.get('config', data)
|
||||||
if isinstance(config_data, dict) and config_data:
|
if isinstance(config_data, dict) and config_data:
|
||||||
# platform_job 仅白名单且 enabled 的任务(如 shipping-inventory-rpa)允许写 ScheduleTaskConfig
|
# platform_job 仅白名单且 enabled 的任务(如 freight-rpa-onhand)允许写 ScheduleTaskConfig
|
||||||
if task.schedule_type != SCHEDULE_TYPE_DATA_PIPELINE and not platform_job_allows_config(task.platform_api_path):
|
if task.schedule_type != SCHEDULE_TYPE_DATA_PIPELINE and not platform_job_allows_config(task.platform_api_path):
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
f"platform_job '{task.platform_api_path}' does not accept ScheduleTaskConfig"
|
f"platform_job '{task.platform_api_path}' does not accept ScheduleTaskConfig"
|
||||||
|
|||||||
@@ -1,24 +1,29 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/api/schedule/rpa_workers.py
|
backend/app/api/schedule/rpa_workers.py
|
||||||
|
|
||||||
用途:管理端查询货代库存 RPA Worker 在线状态与就绪摘要。
|
用途:管理端查询货代库存/入站/出站 RPA Worker 在线状态与就绪摘要。
|
||||||
依赖:schedule.blueprint、rpa_worker_heartbeat.serialize_rpa_worker_status。
|
依赖:schedule.blueprint、freight_rpa.common.worker_heartbeat.serialize_rpa_worker_status。
|
||||||
逻辑:ScheduleWorkbenchPanel 在库存 RPA 排程工作台展示 worker 心跳状态。
|
逻辑:ScheduleWorkbenchPanel 在库存、入站或出站 RPA 排程工作台展示对应 worker 心跳状态。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from flask import request
|
||||||
|
|
||||||
from app.api.schedule.blueprint import schedule_admin_bp
|
from app.api.schedule.blueprint import schedule_admin_bp
|
||||||
from app.core.decorators import require_admin
|
from app.core.decorators import require_admin
|
||||||
from app.core.response import ok
|
from app.core.response import ok
|
||||||
from app.services.shipping_notice.rpa_worker_heartbeat import serialize_rpa_worker_status
|
from app.services.freight_rpa.common.worker_heartbeat import serialize_rpa_worker_status
|
||||||
|
|
||||||
|
|
||||||
@schedule_admin_bp.route('/rpa-workers/status', methods=['GET'])
|
@schedule_admin_bp.route('/rpa-workers/status', methods=['GET'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def get_rpa_workers_status():
|
def get_rpa_workers_status():
|
||||||
"""
|
"""
|
||||||
返回库存 RPA Worker 心跳摘要(在线/离线、最后心跳时间、就绪原因)。
|
返回 RPA Worker 心跳摘要(在线/离线、最后心跳时间、就绪原因)。
|
||||||
核心逻辑:读取 Redis/内存心跳并与当前环境、trigger 目录比对。
|
|
||||||
|
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
|
backend/app/api/schedule/runs.py
|
||||||
|
|
||||||
用途:排程运行触发与运行记录查询 API。
|
用途:排程运行触发与运行记录查询 API。
|
||||||
依赖:schedule.blueprint、services/schedule/query_service、queue_service。
|
依赖:schedule.blueprint、services/schedule/query_service、queue_service、
|
||||||
|
freight_rpa inbound/outbound archive 与 trigger_io。
|
||||||
逻辑:手动执行仅创建 queued run/job;独立 schedule worker 承担实际运行。
|
逻辑:手动执行仅创建 queued run/job;独立 schedule worker 承担实际运行。
|
||||||
|
入站/出站 raw-zip 下载与失败单元 list/retry 对照同构。
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -18,13 +20,15 @@ from app.api.schedule.blueprint import schedule_admin_bp
|
|||||||
from app.core.auth.jwt import get_current_user
|
from app.core.auth.jwt import get_current_user
|
||||||
from app.core.decorators import require_admin
|
from app.core.decorators import require_admin
|
||||||
from app.core.errors import ConflictError, NotFoundError
|
from app.core.errors import ConflictError, NotFoundError
|
||||||
from app.models import ScheduleRun, ScheduleTask, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
|
from app.models import ScheduleRun, ScheduleTask, FreightRpaInboundUnitRun, FreightRpaOutboundUnitRun
|
||||||
from app.services.schedule.query_service import get_run, list_runs, serialize_run
|
from app.services.schedule.query_service import get_run, list_runs, serialize_run
|
||||||
from app.services.schedule.queue_service import enqueue_manual_schedule_run
|
from app.services.schedule.queue_service import enqueue_manual_schedule_run
|
||||||
from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download
|
from app.services.schedule.freight_rpa_onhand_archive import resolve_inventory_raw_zip_download
|
||||||
from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file
|
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.audit_service import append_shipping_audit_event
|
||||||
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
|
from app.services.freight_rpa.inbound.trigger_io import SCHEMA, write_inbound_export_batch_trigger
|
||||||
|
from app.services.freight_rpa.outbound.trigger_io import SCHEMA as OUTBOUND_SCHEMA, write_outbound_export_batch_trigger
|
||||||
|
|
||||||
|
|
||||||
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
|
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
|
||||||
@@ -43,7 +47,11 @@ def run_schedule(task_id: int):
|
|||||||
triggered_by_user_id=getattr(user, 'id', None),
|
triggered_by_user_id=getattr(user, 'id', None),
|
||||||
)
|
)
|
||||||
if not created:
|
if not created:
|
||||||
raise ConflictError('该排程正在等待或执行中,请等待完成后再试', details={'run_id': run.id})
|
raise ConflictError(
|
||||||
|
'该排程正在等待或执行中,请等待完成后再试',
|
||||||
|
code='SCHEDULE.RUN_ALREADY_ACTIVE',
|
||||||
|
details={'run_id': run.id},
|
||||||
|
)
|
||||||
fresh = db.session.get(ScheduleRun, run.id)
|
fresh = db.session.get(ScheduleRun, run.id)
|
||||||
return jsonify(serialize_run(fresh))
|
return jsonify(serialize_run(fresh))
|
||||||
|
|
||||||
@@ -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
|
@require_admin
|
||||||
def resend_receipt_report_file(file_id: int):
|
def get_schedule_run_inbound_raw_zip(run_id: int):
|
||||||
"""管理员重发已归档的收料文件;禁止借重发重新触发 RPA 导出。"""
|
"""
|
||||||
report_file = db.session.get(ShippingReceiptReportFile, file_id)
|
下载入站 RPA 排程 run 的原始入站 Excel 打包(ZIP + manifest)。
|
||||||
if report_file is None or report_file.archive_deleted_at is not None:
|
|
||||||
raise NotFoundError('Receipt report file not found')
|
核心逻辑:对齐 inventory-raw-zip;展示名为 入站RPA-{日期}-{时刻}-入站.zip。
|
||||||
user = get_current_user()
|
"""
|
||||||
outcome = deliver_receipt_file(report_file.id, force=True)
|
run = get_run(run_id)
|
||||||
append_shipping_audit_event(
|
if not run:
|
||||||
event_type='shipping_receipt_report_notification_resent', aggregate_type='shipping_receipt_file',
|
raise NotFoundError('Not found')
|
||||||
aggregate_id=str(report_file.id), actor_type='admin', actor_id=getattr(user, 'id', None),
|
zip_path, file_name = resolve_inbound_raw_zip_download(run)
|
||||||
owner_user_id=getattr(user, 'id', None), unit_id=report_file.unit_run_id, result='success',
|
return send_file(
|
||||||
after={'status': 'resent', 'owner_user_id': getattr(user, 'id', None)},
|
zip_path,
|
||||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
as_attachment=True,
|
||||||
metadata={'success_count': int(outcome.get('success_count', 0)), 'failed_count': int(outcome.get('failed_count', 0))},
|
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
|
@require_admin
|
||||||
def list_receipt_rpa_units():
|
def list_inbound_rpa_units():
|
||||||
"""管理员查看收料单元运行事实,供失败单元填写原因后人工重试。"""
|
"""管理员查看入站单元运行事实,供失败单元填写原因后人工重试。"""
|
||||||
status = str(request.args.get('status') or '').strip().lower()
|
status = str(request.args.get('status') or '').strip().lower()
|
||||||
if status and status not in {'queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled'}:
|
if status and status not in {'queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled'}:
|
||||||
from app.core.errors import ValidationError
|
from app.core.errors import ValidationError
|
||||||
@@ -157,19 +164,19 @@ def list_receipt_rpa_units():
|
|||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
from app.core.errors import ValidationError
|
from app.core.errors import ValidationError
|
||||||
raise ValidationError('limit is invalid')
|
raise ValidationError('limit is invalid')
|
||||||
query = ShippingReceiptRpaUnitRun.query.order_by(
|
query = FreightRpaInboundUnitRun.query.order_by(
|
||||||
ShippingReceiptRpaUnitRun.created_at.desc(), ShippingReceiptRpaUnitRun.id.desc(),
|
FreightRpaInboundUnitRun.created_at.desc(), FreightRpaInboundUnitRun.id.desc(),
|
||||||
)
|
)
|
||||||
if status:
|
if status:
|
||||||
query = query.filter(ShippingReceiptRpaUnitRun.status == status)
|
query = query.filter(FreightRpaInboundUnitRun.status == status)
|
||||||
units = query.limit(limit).all()
|
units = query.limit(limit).all()
|
||||||
user = get_current_user()
|
user = get_current_user()
|
||||||
append_shipping_audit_event(
|
append_shipping_audit_event(
|
||||||
event_type='shipping_receipt_rpa_units_listed', aggregate_type='shipping_receipt_unit_collection',
|
event_type='shipping_inbound_rpa_units_listed', aggregate_type='shipping_inbound_unit_collection',
|
||||||
aggregate_id=str(getattr(user, 'id', 'admin')), actor_type='admin', actor_id=getattr(user, 'id', None),
|
aggregate_id=str(getattr(user, 'id', 'admin')), actor_type='admin', actor_id=getattr(user, 'id', None),
|
||||||
owner_user_id=getattr(user, 'id', None), result='success',
|
owner_user_id=getattr(user, 'id', None), result='success',
|
||||||
after={'visible_count': len(units), 'status': status or None, 'limit': limit},
|
after={'visible_count': len(units), 'status': status or None, 'limit': limit},
|
||||||
metadata={'surface': 'workspace_receipt_report_files'},
|
metadata={'surface': 'admin_inbound_rpa_units'},
|
||||||
)
|
)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return jsonify({'success': True, 'data': {'items': [{
|
return jsonify({'success': True, 'data': {'items': [{
|
||||||
@@ -186,34 +193,34 @@ def list_receipt_rpa_units():
|
|||||||
} for unit in units]}})
|
} for unit in units]}})
|
||||||
|
|
||||||
|
|
||||||
@schedule_admin_bp.route('/receipt-rpa-units/<int:unit_id>/retry', methods=['POST'])
|
@schedule_admin_bp.route('/inbound-rpa-units/<int:unit_id>/retry', methods=['POST'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def retry_receipt_rpa_unit(unit_id: int):
|
def retry_inbound_rpa_unit(unit_id: int):
|
||||||
"""管理员为失败收料单元创建独立重试事实;旧单元永不覆盖。"""
|
"""管理员为失败入站单元创建独立重试事实;旧单元永不覆盖。"""
|
||||||
failed = db.session.get(ShippingReceiptRpaUnitRun, unit_id)
|
failed = db.session.get(FreightRpaInboundUnitRun, unit_id)
|
||||||
if failed is None:
|
if failed is None:
|
||||||
raise NotFoundError('Receipt RPA unit not found')
|
raise NotFoundError('Inbound RPA unit not found')
|
||||||
if failed.status not in {'failed', 'cancelled'}:
|
if failed.status not in {'failed', 'cancelled'}:
|
||||||
raise ConflictError('Only failed receipt RPA units can be retried')
|
raise ConflictError('Only failed inbound RPA units can be retried')
|
||||||
data = request.get_json(silent=True) or {}
|
data = request.get_json(silent=True) or {}
|
||||||
reason = str(data.get('reason') or '').strip()
|
reason = str(data.get('reason') or '').strip()
|
||||||
if not reason:
|
if not reason:
|
||||||
from app.core.errors import ValidationError
|
from app.core.errors import ValidationError
|
||||||
raise ValidationError('reason is required', code='SHIPPING.RECEIPT_RETRY_REASON_REQUIRED')
|
raise ValidationError('reason is required', code='SHIPPING.INBOUND_RETRY_REASON_REQUIRED')
|
||||||
user = get_current_user()
|
user = get_current_user()
|
||||||
retry = ShippingReceiptRpaUnitRun(
|
retry = FreightRpaInboundUnitRun(
|
||||||
schedule_run_id=failed.schedule_run_id, inventory_source_id=failed.inventory_source_id,
|
schedule_run_id=failed.schedule_run_id, source_id=failed.source_id,
|
||||||
retry_of_id=failed.id, source_code=failed.source_code, connector_type=failed.connector_type,
|
retry_of_id=failed.id, source_code=failed.source_code, connector_type=failed.connector_type,
|
||||||
warehouse_id=failed.warehouse_id, callback_id=f'receipt:{uuid.uuid4().hex}', status='awaiting_rpa',
|
warehouse_id=failed.warehouse_id, callback_id=f'inbound:{uuid.uuid4().hex}', status='awaiting_rpa',
|
||||||
config_snapshot_json=dict(failed.config_snapshot_json or {}),
|
config_snapshot_json=dict(failed.config_snapshot_json or {}),
|
||||||
)
|
)
|
||||||
db.session.add(retry)
|
db.session.add(retry)
|
||||||
db.session.flush()
|
db.session.flush()
|
||||||
source = retry.inventory_source
|
source = retry.source
|
||||||
profile = source.rpa_profile if source is not None else None
|
profile = source.rpa_profile if source is not None else None
|
||||||
if source is None or profile is None or not profile.enabled:
|
if source is None or profile is None or not profile.enabled:
|
||||||
db.session.rollback()
|
db.session.rollback()
|
||||||
raise ConflictError('Receipt RPA profile is unavailable')
|
raise ConflictError('Inbound RPA profile is unavailable')
|
||||||
snapshot = dict(retry.config_snapshot_json or {})
|
snapshot = dict(retry.config_snapshot_json or {})
|
||||||
trigger_unit = {
|
trigger_unit = {
|
||||||
'unit_run_id': retry.id, 'callback_id': retry.callback_id, 'source_code': retry.source_code,
|
'unit_run_id': retry.id, 'callback_id': retry.callback_id, 'source_code': retry.source_code,
|
||||||
@@ -226,20 +233,153 @@ def retry_receipt_rpa_unit(unit_id: int):
|
|||||||
}
|
}
|
||||||
retry.trigger_snapshot_json = trigger_unit
|
retry.trigger_snapshot_json = trigger_unit
|
||||||
run = retry.schedule_run
|
run = retry.schedule_run
|
||||||
trigger_path = write_receipt_export_batch_trigger(
|
trigger_path = write_inbound_export_batch_trigger(
|
||||||
f'{run.run_no}-retry-{retry.id}', [trigger_unit],
|
f'{run.run_no}-retry-{retry.id}', [trigger_unit],
|
||||||
{'schedule_run_id': run.id, 'schedule_task_id': run.schedule_task_id, 'schema_version': 'shipping_receipt_rpa.v1', 'retry_of_unit_id': failed.id},
|
{'schedule_run_id': run.id, 'schedule_task_id': run.schedule_task_id, 'schema_version': SCHEMA, 'retry_of_unit_id': failed.id},
|
||||||
)
|
)
|
||||||
if not trigger_path:
|
if not trigger_path:
|
||||||
db.session.rollback()
|
db.session.rollback()
|
||||||
raise ConflictError('Receipt RPA trigger directory is unavailable')
|
raise ConflictError('Inbound RPA trigger directory is unavailable')
|
||||||
run.status = 'running'
|
run.status = 'running'
|
||||||
run.finished_at = None
|
run.finished_at = None
|
||||||
summary = dict(run.response_summary_json or {})
|
summary = dict(run.response_summary_json or {})
|
||||||
summary['awaiting_receipt_rpa'] = True
|
summary['awaiting_inbound_rpa'] = True
|
||||||
run.response_summary_json = summary
|
run.response_summary_json = summary
|
||||||
append_shipping_audit_event(
|
append_shipping_audit_event(
|
||||||
event_type='shipping_receipt_rpa_unit_retried', aggregate_type='shipping_receipt_unit',
|
event_type='shipping_inbound_rpa_unit_retried', aggregate_type='shipping_inbound_unit',
|
||||||
|
aggregate_id=str(retry.id), actor_type='admin', actor_id=getattr(user, 'id', None),
|
||||||
|
owner_user_id=getattr(user, 'id', None), unit_id=retry.id, result='success', reason=reason,
|
||||||
|
before={'status': failed.status, 'error_code': failed.error_code},
|
||||||
|
after={'status': retry.status, 'source_run_no': retry.callback_id, 'owner_user_id': getattr(user, 'id', None)},
|
||||||
|
metadata={'retry_of_id': failed.id},
|
||||||
|
)
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'success': True, 'data': {'unit_id': retry.id, 'retry_of_id': failed.id, 'callback_id': retry.callback_id, 'trigger_path': trigger_path}})
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/outbound-raw-zip', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def get_schedule_run_outbound_raw_zip(run_id: int):
|
||||||
|
"""
|
||||||
|
下载出站 RPA 排程 run 的原始出站 Excel 打包(ZIP + manifest)。
|
||||||
|
|
||||||
|
核心逻辑:对齐 inbound-raw-zip;展示名为 出站RPA-{日期}-{时刻}-出站.zip。
|
||||||
|
"""
|
||||||
|
run = get_run(run_id)
|
||||||
|
if not run:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
zip_path, file_name = resolve_outbound_raw_zip_download(run)
|
||||||
|
return send_file(
|
||||||
|
zip_path,
|
||||||
|
as_attachment=True,
|
||||||
|
download_name=file_name,
|
||||||
|
mimetype='application/zip',
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/outbound-rpa-units', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def list_outbound_rpa_units():
|
||||||
|
"""管理员查出站单元运行事实,供失败单元填写原因后人工重试。"""
|
||||||
|
status = str(request.args.get('status') or '').strip().lower()
|
||||||
|
if status and status not in {'queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled'}:
|
||||||
|
from app.core.errors import ValidationError
|
||||||
|
raise ValidationError('status is invalid')
|
||||||
|
try:
|
||||||
|
limit = max(1, min(int(request.args.get('limit') or 100), 200))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
from app.core.errors import ValidationError
|
||||||
|
raise ValidationError('limit is invalid')
|
||||||
|
query = FreightRpaOutboundUnitRun.query.order_by(
|
||||||
|
FreightRpaOutboundUnitRun.created_at.desc(), FreightRpaOutboundUnitRun.id.desc(),
|
||||||
|
)
|
||||||
|
if status:
|
||||||
|
query = query.filter(FreightRpaOutboundUnitRun.status == status)
|
||||||
|
units = query.limit(limit).all()
|
||||||
|
user = get_current_user()
|
||||||
|
append_shipping_audit_event(
|
||||||
|
event_type='shipping_outbound_rpa_units_listed', aggregate_type='shipping_outbound_unit_collection',
|
||||||
|
aggregate_id=str(getattr(user, 'id', 'admin')), actor_type='admin', actor_id=getattr(user, 'id', None),
|
||||||
|
owner_user_id=getattr(user, 'id', None), result='success',
|
||||||
|
after={'visible_count': len(units), 'status': status or None, 'limit': limit},
|
||||||
|
metadata={'surface': 'admin_outbound_rpa_units'},
|
||||||
|
)
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'success': True, 'data': {'items': [{
|
||||||
|
'id': unit.id,
|
||||||
|
'source_code': unit.source_code,
|
||||||
|
'warehouse_id': unit.warehouse_id,
|
||||||
|
'status': unit.status,
|
||||||
|
'error_code': unit.error_code,
|
||||||
|
'error_message': unit.error_message,
|
||||||
|
'retry_of_id': unit.retry_of_id,
|
||||||
|
'schedule_run_id': unit.schedule_run_id,
|
||||||
|
'created_at': unit.created_at.isoformat() if unit.created_at else None,
|
||||||
|
'finished_at': unit.finished_at.isoformat() if unit.finished_at else None,
|
||||||
|
} for unit in units]}})
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/outbound-rpa-units/<int:unit_id>/retry', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def retry_outbound_rpa_unit(unit_id: int):
|
||||||
|
"""管理员为失败出站单元创建独立重试事实;旧单元永不覆盖。调拨按需单元无排程 run 时仍可重试。"""
|
||||||
|
failed = db.session.get(FreightRpaOutboundUnitRun, unit_id)
|
||||||
|
if failed is None:
|
||||||
|
raise NotFoundError('Outbound RPA unit not found')
|
||||||
|
if failed.status not in {'failed', 'cancelled'}:
|
||||||
|
raise ConflictError('Only failed outbound RPA units can be retried')
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
reason = str(data.get('reason') or '').strip()
|
||||||
|
if not reason:
|
||||||
|
from app.core.errors import ValidationError
|
||||||
|
raise ValidationError('reason is required', code='SHIPPING.OUTBOUND_RETRY_REASON_REQUIRED')
|
||||||
|
user = get_current_user()
|
||||||
|
retry = FreightRpaOutboundUnitRun(
|
||||||
|
schedule_run_id=failed.schedule_run_id, source_id=failed.source_id,
|
||||||
|
retry_of_id=failed.id, source_code=failed.source_code, connector_type=failed.connector_type,
|
||||||
|
warehouse_id=failed.warehouse_id, callback_id=f'outbound:{uuid.uuid4().hex}', status='awaiting_rpa',
|
||||||
|
config_snapshot_json=dict(failed.config_snapshot_json or {}),
|
||||||
|
)
|
||||||
|
db.session.add(retry)
|
||||||
|
db.session.flush()
|
||||||
|
source = retry.source
|
||||||
|
profile = source.rpa_profile if source is not None else None
|
||||||
|
if source is None or profile is None or not profile.enabled:
|
||||||
|
db.session.rollback()
|
||||||
|
raise ConflictError('Outbound RPA profile is unavailable')
|
||||||
|
snapshot = dict(retry.config_snapshot_json or {})
|
||||||
|
trigger_unit = {
|
||||||
|
'unit_run_id': retry.id, 'callback_id': retry.callback_id, 'source_code': retry.source_code,
|
||||||
|
'connector_type': retry.connector_type, 'warehouse_id': retry.warehouse_id,
|
||||||
|
'rpa_profile_id': profile.id, 'rpa_profile_code': profile.profile_code, 'login_url': profile.login_url,
|
||||||
|
'login_config': dict(profile.login_config_json or {}),
|
||||||
|
'credential_envelope': {'username_ciphertext': profile.username_ciphertext, 'password_ciphertext': profile.password_ciphertext},
|
||||||
|
'report_path_json': dict(snapshot.get('report_path_json') or {}),
|
||||||
|
'query_parameters_json': list(snapshot.get('query_parameters_json') or []), 'config_snapshot': snapshot,
|
||||||
|
}
|
||||||
|
retry.trigger_snapshot_json = trigger_unit
|
||||||
|
run = retry.schedule_run
|
||||||
|
run_no = run.run_no if run is not None else f'outbound-retry-{retry.id}'
|
||||||
|
trigger_meta = {
|
||||||
|
'schema_version': OUTBOUND_SCHEMA, 'retry_of_unit_id': failed.id,
|
||||||
|
}
|
||||||
|
if run is not None:
|
||||||
|
trigger_meta['schedule_run_id'] = run.id
|
||||||
|
trigger_meta['schedule_task_id'] = run.schedule_task_id
|
||||||
|
trigger_path = write_outbound_export_batch_trigger(
|
||||||
|
f'{run_no}-retry-{retry.id}', [trigger_unit], trigger_meta,
|
||||||
|
)
|
||||||
|
if not trigger_path:
|
||||||
|
db.session.rollback()
|
||||||
|
raise ConflictError('Outbound RPA trigger directory is unavailable')
|
||||||
|
if run is not None:
|
||||||
|
run.status = 'running'
|
||||||
|
run.finished_at = None
|
||||||
|
summary = dict(run.response_summary_json or {})
|
||||||
|
summary['awaiting_outbound_rpa'] = True
|
||||||
|
run.response_summary_json = summary
|
||||||
|
append_shipping_audit_event(
|
||||||
|
event_type='shipping_outbound_rpa_unit_retried', aggregate_type='shipping_outbound_unit',
|
||||||
aggregate_id=str(retry.id), actor_type='admin', actor_id=getattr(user, 'id', None),
|
aggregate_id=str(retry.id), actor_type='admin', actor_id=getattr(user, 'id', None),
|
||||||
owner_user_id=getattr(user, 'id', None), unit_id=retry.id, result='success', reason=reason,
|
owner_user_id=getattr(user, 'id', None), unit_id=retry.id, result='success', reason=reason,
|
||||||
before={'status': failed.status, 'error_code': failed.error_code},
|
before={'status': failed.status, 'error_code': failed.error_code},
|
||||||
|
|||||||
@@ -1,409 +1,13 @@
|
|||||||
"""
|
"""
|
||||||
api/shipping_notice_tools.py
|
backend/app/api/shipping_notice_tools.py
|
||||||
|
|
||||||
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。
|
用途:兼容旧 import 路径的薄 shim(真实现已迁至 api/tools/shipping_notice.py)。
|
||||||
依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url、
|
依赖:app.api.tools.shipping_notice。
|
||||||
tool_api_url。
|
逻辑:保留 Blueprint 与 `_payload` 等测试符号;新代码请从 app.api.tools 导入。
|
||||||
逻辑:Tool 成功响应仍用 status: ok/failed 业务 envelope;HTTP 级参数/资源错误统一 raise AppError;
|
|
||||||
`_payload()` 剥离 body 中的操作人伪造字段,禁止集成密钥冒充用户写审计;
|
|
||||||
历史批次 Tool 已删除,订单抽取统一走 order-extraction-submissions。
|
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from app.api.tools.shipping_notice import ( # noqa: F401
|
||||||
|
_payload,
|
||||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
shipping_notice_bp,
|
||||||
|
|
||||||
from app import db
|
|
||||||
from app.core.errors import (
|
|
||||||
AppError,
|
|
||||||
NotFoundError,
|
|
||||||
ServiceUnavailableError,
|
|
||||||
UnauthorizedError,
|
|
||||||
ValidationError,
|
|
||||||
)
|
)
|
||||||
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__)
|
__all__ = ['shipping_notice_bp', '_payload']
|
||||||
|
|
||||||
|
|
||||||
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)
|
|
||||||
@@ -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 flask import Blueprint, jsonify, request
|
||||||
|
|
||||||
from app.core.auth.jwt import get_current_user
|
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.
|
Purpose: Expose peer-service discovery, short-lived assertion issuance, and public JWKS APIs.
|
||||||
Dependencies: JWT current-user resolver, SSO services, and Flask Blueprint.
|
Dependencies: JWT current-user resolver, SSO services, and Flask Blueprint.
|
||||||
@@ -1,11 +1,20 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/api/tools/__init__.py
|
backend/app/api/tools/__init__.py
|
||||||
|
|
||||||
用途:Dify HTTP Tool API Blueprint 聚合。
|
用途:Dify / Chatflow HTTP Tool API Blueprint 聚合。
|
||||||
逻辑:re-export shipping_notice、file_check、maintenance tools。
|
依赖: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.file_check import file_check_bp # noqa: F401
|
||||||
from app.api.tools.maintenance import maintenance_tool_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
|
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
|
backend/app/api/tools/maintenance.py
|
||||||
|
|
||||||
用途:设备维保 Tool API Blueprint re-export。
|
用途:设备维保助手 Dify Tool API,只开放只读查询工具。
|
||||||
依赖:app.api.maintenance_tools。
|
依赖:maintenance_chat_service、maintenance_record_service、OpenAPI 构建、Tool API 基地址解析。
|
||||||
逻辑:保持 api.tools 分包统一入口,register_blueprints 只从 app.api.tools 导入各 Tool Blueprint。
|
逻辑: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
|
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。
|
依赖: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,
|
'username': user.username,
|
||||||
'role': user.role,
|
'role': user.role,
|
||||||
'default_agent_id': user.default_agent_id,
|
'default_agent_id': user.default_agent_id,
|
||||||
'feature_permissions': user.get_feature_permissions(),
|
**user.client_auth_fields(),
|
||||||
'source': source,
|
'source': source,
|
||||||
'access_token': issue_local_access_token(user),
|
'access_token': issue_local_access_token(user),
|
||||||
'token_type': 'Bearer',
|
'token_type': 'Bearer',
|
||||||
|
|||||||
@@ -185,7 +185,7 @@ def home():
|
|||||||
raise UnauthorizedError('Unauthorized')
|
raise UnauthorizedError('Unauthorized')
|
||||||
|
|
||||||
def _load_home_payload():
|
def _load_home_payload():
|
||||||
if user.role == 'admin':
|
if user.is_platform_admin():
|
||||||
agent_rows = Agent.query.filter(Agent.is_active.is_(True)).all()
|
agent_rows = Agent.query.filter(Agent.is_active.is_(True)).all()
|
||||||
else:
|
else:
|
||||||
agent_rows = [agent for agent in user.agents if agent.is_active]
|
agent_rows = [agent for agent in user.agents if agent.is_active]
|
||||||
@@ -213,7 +213,7 @@ def home():
|
|||||||
'runtime_provider': registry.get('runtime_provider'),
|
'runtime_provider': registry.get('runtime_provider'),
|
||||||
'conversation_mode': registry.get('conversation_mode'),
|
'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:
|
try:
|
||||||
return _run_db_with_retry(_load_home_payload, label='user.home')
|
return _run_db_with_retry(_load_home_payload, label='user.home')
|
||||||
except (OperationalError, DatabaseError) as exc:
|
except (OperationalError, DatabaseError) as exc:
|
||||||
@@ -297,7 +297,7 @@ def user_profile():
|
|||||||
if not user:
|
if not user:
|
||||||
raise UnauthorizedError('Unauthorized')
|
raise UnauthorizedError('Unauthorized')
|
||||||
if request.method == 'GET':
|
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 {}
|
data = request.get_json() or {}
|
||||||
|
|
||||||
def _update_profile():
|
def _update_profile():
|
||||||
@@ -348,7 +348,7 @@ def get_agent_details(id):
|
|||||||
agent = db.session.get(Agent, id)
|
agent = db.session.get(Agent, id)
|
||||||
if not agent:
|
if not agent:
|
||||||
raise NotFoundError('Not found')
|
raise NotFoundError('Not found')
|
||||||
if user.role != 'admin':
|
if not user.is_platform_admin():
|
||||||
has_permission = agent in user.agents
|
has_permission = agent in user.agents
|
||||||
if not has_permission:
|
if not has_permission:
|
||||||
raise ForbiddenError('Access denied')
|
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
|
from app.api.workspace.voucher_check import workspace_voucher_check_bp
|
||||||
|
|
||||||
import app.api.workspace.shipping_process_gate # noqa: F401
|
import app.api.workspace.shipping_process_gate # noqa: F401
|
||||||
import app.api.workspace.shipping_inventory_candidates # noqa: F401
|
import app.api.workspace.shipping_onhand_candidates # noqa: F401
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
'workspace_announcements_bp',
|
'workspace_announcements_bp',
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ from flask import Blueprint, Response, current_app, g, request, send_file
|
|||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
from app.core.auth.jwt import get_current_user
|
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.core.response import ok
|
||||||
from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice, ShippingOrderTask
|
from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice, ShippingOrderTask
|
||||||
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
|
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)
|
return ok(payload, request_id=getattr(g, 'request_id', None), status=status)
|
||||||
|
|
||||||
|
|
||||||
@workspace_shipping_notice_bp.route('/receipt-report-files/<int:file_id>/download', methods=['GET'])
|
|
||||||
def workspace_download_receipt_report_file(file_id: int):
|
|
||||||
"""下载当前接收人或管理员有权读取的原样收料报表。"""
|
|
||||||
user = _require_user()
|
|
||||||
from app.services.shipping_notice.receipt_report_access import resolve_receipt_report_download
|
|
||||||
|
|
||||||
stream, filename, content_type = resolve_receipt_report_download(file_id, user)
|
|
||||||
response = send_file(
|
|
||||||
stream, as_attachment=True, download_name=filename,
|
|
||||||
mimetype=content_type or 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
||||||
)
|
|
||||||
response.call_on_close(stream.close)
|
|
||||||
return response
|
|
||||||
|
|
||||||
|
|
||||||
@workspace_shipping_notice_bp.route('/receipt-report-files', methods=['GET'])
|
|
||||||
def workspace_list_receipt_report_files():
|
|
||||||
"""列出当前接收人或管理员可下载的收料归档文件,不返回对象存储定位。"""
|
|
||||||
user = _require_user()
|
|
||||||
try:
|
|
||||||
limit = int(request.args.get('limit') or 100)
|
|
||||||
except (TypeError, ValueError) as exc:
|
|
||||||
raise ValidationError('limit must be an integer') from exc
|
|
||||||
from app.services.shipping_notice.receipt_report_access import list_receipt_report_files
|
|
||||||
|
|
||||||
return _ok({'items': list_receipt_report_files(user, limit=limit)})
|
|
||||||
|
|
||||||
|
|
||||||
def _assert_fulfillment_task_ownership(task: ShippingNotice, user_id: int) -> None:
|
def _assert_fulfillment_task_ownership(task: ShippingNotice, user_id: int) -> None:
|
||||||
"""
|
"""
|
||||||
履约写接口:若请求携带期望 OT/Case/Run,校验与正式 Notice 归属一致。
|
履约写接口:若请求携带期望 OT/Case/Run,校验与正式 Notice 归属一致。
|
||||||
@@ -186,6 +158,7 @@ def workspace_shipping_tasks():
|
|||||||
lifecycle_status=lifecycle_status,
|
lifecycle_status=lifecycle_status,
|
||||||
page=page,
|
page=page,
|
||||||
page_size=page_size,
|
page_size=page_size,
|
||||||
|
is_admin=bool(user.is_platform_admin()),
|
||||||
))
|
))
|
||||||
|
|
||||||
|
|
||||||
@@ -199,7 +172,7 @@ def workspace_shipping_my_todos():
|
|||||||
user = _require_user()
|
user = _require_user()
|
||||||
from app.services.shipping_notice.query_service import list_my_todos
|
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:
|
try:
|
||||||
page = int(request.args.get('page') or 1)
|
page = int(request.args.get('page') or 1)
|
||||||
page_size = int(request.args.get('page_size') or 20)
|
page_size = int(request.args.get('page_size') or 20)
|
||||||
@@ -224,7 +197,7 @@ def workspace_shipping_my_todos_count():
|
|||||||
user = _require_user()
|
user = _require_user()
|
||||||
from app.services.shipping_notice.query_service import count_my_todos
|
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))
|
return _ok(count_my_todos(user.id, is_admin=is_admin))
|
||||||
|
|
||||||
|
|
||||||
@@ -249,7 +222,7 @@ def workspace_shipping_done_lines():
|
|||||||
user = _require_user()
|
user = _require_user()
|
||||||
from app.services.shipping_notice.done_line_report import list_done_notice_lines
|
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:
|
try:
|
||||||
page = int(request.args.get('page') or 1)
|
page = int(request.args.get('page') or 1)
|
||||||
page_size = int(request.args.get('page_size') or 20)
|
page_size = int(request.args.get('page_size') or 20)
|
||||||
@@ -276,7 +249,7 @@ def workspace_shipping_done_lines_export():
|
|||||||
user = _require_user()
|
user = _require_user()
|
||||||
from app.services.shipping_notice.done_line_report import build_done_lines_xlsx
|
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(
|
stream, filename = build_done_lines_xlsx(
|
||||||
user.id,
|
user.id,
|
||||||
is_admin=is_admin,
|
is_admin=is_admin,
|
||||||
@@ -302,7 +275,7 @@ def _batch_task_nos(data: dict) -> list[str]:
|
|||||||
|
|
||||||
def _can_dispose_task(user, task) -> bool:
|
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):
|
def _batch_dispose(action: str):
|
||||||
@@ -345,7 +318,7 @@ def _batch_dispose(action: str):
|
|||||||
def workspace_batch_purge_shipping_tasks():
|
def workspace_batch_purge_shipping_tasks():
|
||||||
"""仅管理员可永久清除回收站中的纯误建任务;每条均在行锁下重查全部引用。"""
|
"""仅管理员可永久清除回收站中的纯误建任务;每条均在行锁下重查全部引用。"""
|
||||||
user = _require_user()
|
user = _require_user()
|
||||||
if str(getattr(user, 'role', '')).lower() != 'admin':
|
if not user.is_platform_admin():
|
||||||
from app.core.errors import ForbiddenError
|
from app.core.errors import ForbiddenError
|
||||||
|
|
||||||
raise ForbiddenError('Admin privilege required')
|
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'])
|
@workspace_shipping_notice_bp.route('/shipping-exports/archive', methods=['POST'])
|
||||||
def workspace_shipping_export_archive():
|
def workspace_shipping_export_archive():
|
||||||
"""按显式任务号下载当前用户可访问的 ready 发货 Excel ZIP。"""
|
"""按显式任务号下载当前用户可下载(创建者或管理员)的 ready 发货 Excel ZIP。"""
|
||||||
user = _require_user()
|
user = _require_user()
|
||||||
data = request.get_json(silent=True) or {}
|
data = request.get_json(silent=True) or {}
|
||||||
task_nos = data.get('task_nos')
|
task_nos = data.get('task_nos')
|
||||||
if task_nos is not None and not isinstance(task_nos, list):
|
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')
|
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
|
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 = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip')
|
||||||
response.call_on_close(stream.close)
|
response.call_on_close(stream.close)
|
||||||
return response
|
return response
|
||||||
@@ -455,7 +452,11 @@ def workspace_confirm_shipping_customer(task_no: str):
|
|||||||
details={'field': 'customer_id'},
|
details={'field': 'customer_id'},
|
||||||
) from exc
|
) from exc
|
||||||
updated = confirm_task_customer(task, customer_id=customer_id, actor_id=user.id)
|
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'])
|
@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()
|
db.session.commit()
|
||||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
|
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
|
||||||
orchestrator_started = start_task_orchestrator(task_id)
|
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'])
|
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/replace-notice', methods=['POST'])
|
||||||
def workspace_replace_shipping_task_notice(task_no: str):
|
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,减少前端二次推导与竞态刷新。
|
position / user_mode / actions / steps,减少前端二次推导与竞态刷新。
|
||||||
"""
|
"""
|
||||||
user = _require_user()
|
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
|
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)
|
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
|
||||||
if not task:
|
if not task:
|
||||||
@@ -562,7 +563,7 @@ def workspace_shipping_task_detail(task_no: str):
|
|||||||
def workspace_shipping_task_odm_options(task_no: str):
|
def workspace_shipping_task_odm_options(task_no: str):
|
||||||
"""返回整单 ODM ID 候选与当前选择(工作台整单裁决路径,只读)。"""
|
"""返回整单 ODM ID 候选与当前选择(工作台整单裁决路径,只读)。"""
|
||||||
user = _require_user()
|
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.notice_odm_choice_service import notice_odm_options
|
||||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
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):
|
def workspace_set_shipping_task_odm_choice(task_no: str):
|
||||||
"""保存整单 ODM ID 用户选择;重复提交覆盖旧选择,成功后前端可重试生成 Excel。"""
|
"""保存整单 ODM ID 用户选择;重复提交覆盖旧选择,成功后前端可重试生成 Excel。"""
|
||||||
user = _require_user()
|
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.notice_odm_choice_service import set_notice_odm_choice
|
||||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
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):
|
def workspace_list_shipping_task_audit_timeline(task_no: str):
|
||||||
"""业务用户 Task 审计时间线(统一 ShippingAuditEvent,无敏感快照)。"""
|
"""业务用户 Task 审计时间线(统一 ShippingAuditEvent,无敏感快照)。"""
|
||||||
user = _require_user()
|
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.audit_query_service import list_task_audit_timeline
|
||||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
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):
|
def workspace_shipping_task_freight_notice_groups(task_no: str):
|
||||||
"""读取当前 PO 下按 business_no 聚合的货代上传 Notice;仅供订单工作台展示。"""
|
"""读取当前 PO 下按 business_no 聚合的货代上传 Notice;仅供订单工作台展示。"""
|
||||||
user = _require_user()
|
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 (
|
from app.services.shipping_notice.query_service import (
|
||||||
get_task_visible_to_user,
|
get_task_visible_to_user,
|
||||||
list_freight_notice_groups_for_task,
|
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)
|
task = get_task_for_user(task_no, user.id)
|
||||||
if not task:
|
if not task:
|
||||||
raise NotFoundError('Not found')
|
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'])
|
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET'])
|
||||||
def workspace_shipping_task_chat_actions(task_no: str):
|
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
|
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]:
|
def _start_notice_rpa_upload(*, business_no: str, user_id: int, artifact_id: int | None = None) -> dict[str, Any]:
|
||||||
"""按 business_no 发起单张通知的货代 RPA 上传或重试。"""
|
"""按 business_no 发起单张通知的货代 RPA 上传或重试。"""
|
||||||
task = _load_business_notice_for_user(business_no=business_no, user_id=user_id)
|
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'])
|
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/rpa-upload', methods=['POST'])
|
||||||
def workspace_start_shipping_notice_rpa_upload(business_no: str):
|
def workspace_start_shipping_notice_rpa_upload(business_no: str):
|
||||||
"""按发货通知单号发起 RPA 上传;RPA 成功事实仍由受信回调裁决。"""
|
"""按发货通知单号发起 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'])
|
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/export', methods=['GET'])
|
||||||
def workspace_shipping_notice_export(business_no: str):
|
def workspace_shipping_notice_export(business_no: str):
|
||||||
"""按发货通知单号下载该通知唯一的正式 Excel,并保留下载审计。"""
|
"""按发货通知单号下载该通知唯一的正式 Excel(创建者或管理员),并保留下载审计。"""
|
||||||
user = _require_user()
|
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)
|
err_msg = task_export_error_message(task)
|
||||||
if err_msg:
|
if err_msg:
|
||||||
raise NotFoundError(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'])
|
@workspace_shipping_notice_bp.route('/shipping-notices/batch/export', methods=['POST'])
|
||||||
def workspace_shipping_notice_export_archive():
|
def workspace_shipping_notice_export_archive():
|
||||||
"""按多个 business_no 下载各自唯一 Excel 的 ZIP;任一越权或缺文件均整体拒绝。"""
|
"""按多个 business_no 下载各自唯一 Excel 的 ZIP(创建者或管理员);任一越权或缺文件均整体拒绝。"""
|
||||||
user = _require_user()
|
user = _require_user()
|
||||||
data = request.get_json(silent=True) or {}
|
data = request.get_json(silent=True) or {}
|
||||||
raw_values = data.get('business_nos')
|
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:
|
if not business_nos or len(business_nos) > 100:
|
||||||
raise ValidationError('business_nos must contain 1 to 100 business numbers')
|
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.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 = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip')
|
||||||
response.call_on_close(stream.close)
|
response.call_on_close(stream.close)
|
||||||
return response
|
return response
|
||||||
@@ -1183,9 +1290,10 @@ def workspace_shipping_notice_export_archive():
|
|||||||
|
|
||||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
|
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
|
||||||
def workspace_shipping_task_export(task_no: str):
|
def workspace_shipping_task_export(task_no: str):
|
||||||
"""下载当前用户可访问任务的出货 Excel;写入统一访问审计。"""
|
"""下载当前用户可下载任务的出货 Excel(创建者或管理员);写入统一访问审计。"""
|
||||||
user = _require_user()
|
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)
|
task = _require_formal_notice(task)
|
||||||
err_msg = task_export_error_message(task)
|
err_msg = task_export_error_message(task)
|
||||||
if err_msg:
|
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)
|
task = get_task_for_user(task_no, user.id)
|
||||||
if not task:
|
if not task:
|
||||||
raise NotFoundError('Not found')
|
raise NotFoundError('Not found')
|
||||||
from app.services.shipping_notice.inventory_file_store import resolve_task_inventory_download
|
from app.services.shipping_notice.onhand_file_store import resolve_task_inventory_download
|
||||||
|
|
||||||
resolved = resolve_task_inventory_download(task)
|
resolved = resolve_task_inventory_download(task)
|
||||||
if resolved is None:
|
if resolved is None:
|
||||||
raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND')
|
raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_ONHAND_FILE_NOT_FOUND')
|
||||||
path, download_name = resolved
|
path, download_name = resolved
|
||||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||||
record_access_audit(
|
record_access_audit(
|
||||||
@@ -1243,30 +1351,31 @@ def workspace_shipping_task_line_inventory_file(task_no: str, inventory_file_no:
|
|||||||
raise NotFoundError('Not found')
|
raise NotFoundError('Not found')
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch
|
from app.models import FreightRpaOnhandReportFile, ShippingNoticeLineOnhandMatch
|
||||||
|
|
||||||
requested_file_no = str(inventory_file_no or '').strip()
|
requested_file_no = str(inventory_file_no or '').strip()
|
||||||
inventory_file = (
|
inventory_file = (
|
||||||
ShippingInventoryFile.query
|
FreightRpaOnhandReportFile.query
|
||||||
.join(
|
.join(
|
||||||
ShippingNoticeLineInventoryMatch,
|
ShippingNoticeLineOnhandMatch,
|
||||||
ShippingNoticeLineInventoryMatch.inventory_snapshot_id == ShippingInventoryFile.id,
|
ShippingNoticeLineOnhandMatch.onhand_snapshot_id == FreightRpaOnhandReportFile.id,
|
||||||
)
|
)
|
||||||
.filter(
|
.filter(
|
||||||
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
|
ShippingNoticeLineOnhandMatch.task_id == int(task.id),
|
||||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
ShippingNoticeLineOnhandMatch.is_current.is_(True),
|
||||||
ShippingNoticeLineInventoryMatch.matched_file_no == requested_file_no,
|
ShippingNoticeLineOnhandMatch.matched_file_no == requested_file_no,
|
||||||
ShippingInventoryFile.inventory_file_no == requested_file_no,
|
FreightRpaOnhandReportFile.onhand_file_no == requested_file_no,
|
||||||
)
|
)
|
||||||
.first()
|
.first()
|
||||||
)
|
)
|
||||||
storage_path = str(getattr(inventory_file, 'storage_path', '') or '').strip()
|
storage_path = str(getattr(inventory_file, 'storage_path', '') or '').strip()
|
||||||
path = Path(storage_path).resolve() if storage_path else None
|
path = Path(storage_path).resolve() if storage_path else None
|
||||||
if inventory_file is None or not storage_path or storage_path.startswith('failed://') or not path.is_file():
|
if inventory_file is None or not storage_path or storage_path.startswith('failed://') or not path.is_file():
|
||||||
raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND')
|
raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_ONHAND_FILE_NOT_FOUND')
|
||||||
download_name = str(
|
from app.services.shipping_notice.onhand_file_store import build_inventory_download_name
|
||||||
inventory_file.source_file_name or f'{inventory_file.inventory_file_no}{path.suffix or ".xlsx"}',
|
download_name = build_inventory_download_name(
|
||||||
).strip()
|
inventory_file, source_file_name=inventory_file.source_file_name, path=path,
|
||||||
|
)
|
||||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||||
record_access_audit(
|
record_access_audit(
|
||||||
action='download_task_line_inventory_file',
|
action='download_task_line_inventory_file',
|
||||||
@@ -1604,7 +1713,7 @@ def workspace_get_shipping_order_review_run(run_no: str):
|
|||||||
JSON 响应契约或业务数据。
|
JSON 响应契约或业务数据。
|
||||||
"""
|
"""
|
||||||
user = _require_user()
|
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.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_projection import serialize_review_run
|
||||||
from app.services.shipping_notice.order_review_service import get_review_run_visible_to_user
|
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 响应契约或业务数据。
|
JSON 响应契约或业务数据。
|
||||||
"""
|
"""
|
||||||
user = _require_user()
|
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.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_projection import serialize_review_queue
|
||||||
from app.services.shipping_notice.order_review_service import get_review_queue_visible_to_user
|
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 响应契约或业务数据。
|
JSON 响应契约或业务数据。
|
||||||
"""
|
"""
|
||||||
user = _require_user()
|
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.fulfillment_audit import record_access_audit
|
||||||
from app.services.shipping_notice.order_review_case_snapshot import (
|
from app.services.shipping_notice.order_review_case_snapshot import (
|
||||||
build_order_review_case_snapshot,
|
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。
|
要求前端切换到 reconcile-and-progress;通过后再委托 retry_stp_auto_create_for_case。
|
||||||
"""
|
"""
|
||||||
user = _require_user()
|
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_review_service import get_review_case_visible_to_user
|
||||||
from app.services.shipping_notice.order_stp_auto_create_service import (
|
from app.services.shipping_notice.order_stp_auto_create_service import (
|
||||||
retry_stp_auto_create_for_case,
|
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(可选,请求快照用于参数一致性)
|
source_content_hash: string(可选,请求快照用于参数一致性)
|
||||||
"""
|
"""
|
||||||
user = _require_user()
|
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
|
payload = request.get_json(silent=True) if request.is_json else None
|
||||||
if not isinstance(payload, dict):
|
if not isinstance(payload, dict):
|
||||||
payload = {}
|
payload = {}
|
||||||
@@ -1821,7 +1930,7 @@ def workspace_audit_shipping_order_review_version_history(case_no: str):
|
|||||||
核心逻辑:先做 Case 可见性校验,再写入 access + 工作台语义事件,禁止仅改本地 UI 状态而不留痕。
|
核心逻辑:先做 Case 可见性校验,再写入 access + 工作台语义事件,禁止仅改本地 UI 状态而不留痕。
|
||||||
"""
|
"""
|
||||||
user = _require_user()
|
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.fulfillment_audit import record_access_audit, record_fulfillment_audit
|
||||||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
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 + 工作台语义事件。
|
核心逻辑:先做 Case 可见性校验,再写入 access + 工作台语义事件。
|
||||||
"""
|
"""
|
||||||
user = _require_user()
|
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.fulfillment_audit import record_access_audit, record_fulfillment_audit
|
||||||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
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(
|
@workspace_shipping_notice_bp.route(
|
||||||
'/shipping-notice/order-review-cases/<case_no>/reservation/revalidate',
|
'/shipping-notice/order-review-cases/<case_no>/reservation/revalidate',
|
||||||
methods=['POST'],
|
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):
|
def workspace_list_shipping_order_review_audit_timeline(case_no: str):
|
||||||
"""业务用户 Case 审计时间线(无敏感快照)。"""
|
"""业务用户 Case 审计时间线(无敏感快照)。"""
|
||||||
user = _require_user()
|
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.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.fulfillment_audit import record_access_audit
|
||||||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
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,
|
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(
|
result = decide_review_line_fulfillment(
|
||||||
user_id=user.id,
|
user_id=user.id,
|
||||||
case_no=case_no,
|
case_no=case_no,
|
||||||
@@ -2277,7 +2468,7 @@ def workspace_close_shipping_order_review_fulfillment(case_no: str):
|
|||||||
close_remaining_fulfillment,
|
close_remaining_fulfillment,
|
||||||
)
|
)
|
||||||
|
|
||||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
is_admin = bool(user.is_platform_admin())
|
||||||
result = close_remaining_fulfillment(
|
result = close_remaining_fulfillment(
|
||||||
user_id=user.id,
|
user_id=user.id,
|
||||||
case_no=case_no,
|
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):
|
def workspace_list_shipping_order_review_llm_suggestions(case_no: str):
|
||||||
"""列出 Case 下 Dify 最小证据建议记录。"""
|
"""列出 Case 下 Dify 最小证据建议记录。"""
|
||||||
user = _require_user()
|
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
|
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))
|
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):
|
def workspace_request_shipping_order_review_llm_suggestion(case_no: str):
|
||||||
"""为指定字段请求 Dify 最小证据建议;Provider 不可用时不阻断人工复核。"""
|
"""为指定字段请求 Dify 最小证据建议;Provider 不可用时不阻断人工复核。"""
|
||||||
user = _require_user()
|
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
|
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')
|
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):
|
def workspace_adjudicate_shipping_order_review_llm_suggestion(case_no: str, suggestion_no: str):
|
||||||
"""人工裁决 LLM 建议:accept / modify / reject。"""
|
"""人工裁决 LLM 建议:accept / modify / reject。"""
|
||||||
user = _require_user()
|
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
|
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')
|
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。
|
用途:正式 Task 库存候选只读详情 API。
|
||||||
依赖:workspace_shipping_notice_bp、query_service.get_task_for_user、inventory_candidate_projection。
|
依赖:workspace_shipping_notice_bp、query_service.get_task_for_user、onhand_candidate_projection。
|
||||||
逻辑:路由层仅做鉴权与查询参数校验;当前版本缺失返回 200 + current_set=null + blocking_reason,
|
逻辑:路由层仅做鉴权与查询参数校验;当前版本缺失返回 200 + current_set=null + blocking_reason,
|
||||||
不把可恢复业务阻断误报成 404。
|
不把可恢复业务阻断误报成 404。
|
||||||
"""
|
"""
|
||||||
@@ -13,7 +13,7 @@ from flask import request
|
|||||||
|
|
||||||
from app.api.workspace.shipping_notice import _ok, _require_user, workspace_shipping_notice_bp
|
from app.api.workspace.shipping_notice import _ok, _require_user, workspace_shipping_notice_bp
|
||||||
from app.core.errors import ValidationError
|
from app.core.errors import ValidationError
|
||||||
from app.services.shipping_notice.inventory_candidate_projection import (
|
from app.services.shipping_notice.onhand_candidate_projection import (
|
||||||
project_inventory_candidate_detail,
|
project_inventory_candidate_detail,
|
||||||
)
|
)
|
||||||
from app.services.shipping_notice.query_service import get_task_for_user
|
from app.services.shipping_notice.query_service import get_task_for_user
|
||||||
@@ -135,7 +135,7 @@ def workspace_post_process_gate_action(execution_no: str, gate_code: str):
|
|||||||
action_code=parsed['action_code'],
|
action_code=parsed['action_code'],
|
||||||
expected_gate_version=parsed['expected_gate_version'],
|
expected_gate_version=parsed['expected_gate_version'],
|
||||||
idempotency_key=parsed['idempotency_key'],
|
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),
|
actor_id=int(user.id),
|
||||||
payload=parsed['payload'],
|
payload=parsed['payload'],
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -4,17 +4,20 @@ backend/app/api/workspace/voucher_check.py
|
|||||||
用途:立账凭证检核查询、强制重检与通知配置 API(任务列表 / 最近一次检核 / 批次明细 / 企微发送记录 / 按类型接收人)。
|
用途:立账凭证检核查询、强制重检与通知配置 API(任务列表 / 最近一次检核 / 批次明细 / 企微发送记录 / 按类型接收人)。
|
||||||
依赖:auth.jwt、response_utils envelope、Agent 授权、voucher_check.query_service、notify_config_service。
|
依赖:auth.jwt、response_utils envelope、Agent 授权、voucher_check.query_service、notify_config_service。
|
||||||
逻辑:Chat Agent 与旧工作台查询共用;GET runs/latest 不跟筛选;GET notifications 为企微发送记录;
|
逻辑:Chat Agent 与旧工作台查询共用;GET runs/latest 不跟筛选;GET notifications 为企微发送记录;
|
||||||
查询要求平台 admin 或持有 `agent_code=voucher_check` 的 Agent 授权;POST runs 与通知配置仅 admin。
|
批次明细可按 result 与 invoice_no 筛选。企微记录里的 Excel 走本模块下载,不走排程通知人权限。
|
||||||
|
查询要求 is_platform_admin 或持有 `agent_code=voucher_check` 的 Agent 授权;POST runs 与通知配置仅平台管理员。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from flask import Blueprint, request
|
from io import BytesIO
|
||||||
|
|
||||||
|
from flask import Blueprint, request, send_file
|
||||||
|
|
||||||
from app.core.auth.jwt import get_current_user
|
from app.core.auth.jwt import get_current_user
|
||||||
from app.core.errors import ForbiddenError, UnauthorizedError, ValidationError
|
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError
|
||||||
from app.core.response import ok
|
from app.core.response import ok
|
||||||
from app.models import Agent
|
from app.models import Agent, ScheduleRun, VoucherCheckRun
|
||||||
from app.services.voucher_check import notify_config_service, query_service
|
from app.services.voucher_check import notify_config_service, query_service
|
||||||
|
|
||||||
workspace_voucher_check_bp = Blueprint("workspace_voucher_check", __name__)
|
workspace_voucher_check_bp = Blueprint("workspace_voucher_check", __name__)
|
||||||
@@ -42,7 +45,7 @@ def _user_has_voucher_check_agent(user) -> bool:
|
|||||||
"""
|
"""
|
||||||
判断用户是否持有启用中的立账凭证检核 Agent。
|
判断用户是否持有启用中的立账凭证检核 Agent。
|
||||||
|
|
||||||
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions;admin 不走此判断。
|
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions;平台管理员不走此判断。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
user: 已认证用户。
|
user: 已认证用户。
|
||||||
@@ -58,18 +61,18 @@ def _require_voucher_check_access():
|
|||||||
"""
|
"""
|
||||||
确保当前用户已登录且具备立账凭证检核访问权限。
|
确保当前用户已登录且具备立账凭证检核访问权限。
|
||||||
|
|
||||||
核心逻辑:平台 admin 放行;普通用户必须被授予启用中的 `agent_code=voucher_check` Agent。
|
核心逻辑:is_platform_admin 放行;普通用户必须被授予启用中的 `agent_code=voucher_check` Agent。
|
||||||
无权限时返回业务 403,而不是静默空数据。
|
无权限时返回业务 403,而不是静默空数据。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
已认证且具备立账凭证 Agent 授权(或 admin)的用户。
|
已认证且具备立账凭证 Agent 授权(或平台管理员)的用户。
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
UnauthorizedError: 请求没有有效登录身份。
|
UnauthorizedError: 请求没有有效登录身份。
|
||||||
ForbiddenError: 已登录但没有立账凭证 Agent 授权。
|
ForbiddenError: 已登录但没有立账凭证 Agent 授权。
|
||||||
"""
|
"""
|
||||||
user = _require_user()
|
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
|
return user
|
||||||
raise ForbiddenError(
|
raise ForbiddenError(
|
||||||
"Voucher check agent permission required",
|
"Voucher check agent permission required",
|
||||||
@@ -81,7 +84,7 @@ def _require_admin():
|
|||||||
"""
|
"""
|
||||||
确保当前用户既有立账凭证访问权,又是平台管理员。
|
确保当前用户既有立账凭证访问权,又是平台管理员。
|
||||||
|
|
||||||
核心逻辑:持有 Agent 的普通用户可查检核任务与发送记录;强制重检与通知配置仅 `role=admin`。
|
核心逻辑:持有 Agent 的普通用户可查检核任务与发送记录;强制重检与通知配置仅 is_platform_admin。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
已认证的管理员用户。
|
已认证的管理员用户。
|
||||||
@@ -91,7 +94,7 @@ def _require_admin():
|
|||||||
ForbiddenError: 无立账凭证访问权,或已授权但不是管理员。
|
ForbiddenError: 无立账凭证访问权,或已授权但不是管理员。
|
||||||
"""
|
"""
|
||||||
user = _require_voucher_check_access()
|
user = _require_voucher_check_access()
|
||||||
if getattr(user, "role", None) != "admin":
|
if not user.is_platform_admin():
|
||||||
raise ForbiddenError(
|
raise ForbiddenError(
|
||||||
"Admin privilege required for voucher check jobs",
|
"Admin privilege required for voucher check jobs",
|
||||||
code="VOUCHER_CHECK.ADMIN_REQUIRED",
|
code="VOUCHER_CHECK.ADMIN_REQUIRED",
|
||||||
@@ -149,12 +152,13 @@ def workspace_voucher_latest_run():
|
|||||||
def workspace_voucher_run_items(run_id: int):
|
def workspace_voucher_run_items(run_id: int):
|
||||||
"""
|
"""
|
||||||
分页查看批次明细。
|
分页查看批次明细。
|
||||||
核心逻辑:委托 query_service.list_run_items,可按 result 过滤,并返回 by_file_type。
|
核心逻辑:委托 query_service.list_run_items,可按 result 与 invoice_no 过滤,并返回 by_file_type。
|
||||||
"""
|
"""
|
||||||
_require_voucher_check_access()
|
_require_voucher_check_access()
|
||||||
data = query_service.list_run_items(
|
data = query_service.list_run_items(
|
||||||
run_id=run_id,
|
run_id=run_id,
|
||||||
result=request.args.get("result"),
|
result=request.args.get("result"),
|
||||||
|
invoice_no=request.args.get("invoice_no"),
|
||||||
page=request.args.get("page", default=1, type=int) or 1,
|
page=request.args.get("page", default=1, type=int) or 1,
|
||||||
page_size=request.args.get("page_size", default=50, type=int) or 50,
|
page_size=request.args.get("page_size", default=50, type=int) or 50,
|
||||||
)
|
)
|
||||||
@@ -177,11 +181,38 @@ def workspace_voucher_notifications():
|
|||||||
return ok(data)
|
return ok(data)
|
||||||
|
|
||||||
|
|
||||||
|
@workspace_voucher_check_bp.route(
|
||||||
|
"/accounting-voucher-check/schedule-runs/<int:schedule_run_id>/excel",
|
||||||
|
methods=["GET"],
|
||||||
|
)
|
||||||
|
def workspace_voucher_schedule_excel(schedule_run_id: int):
|
||||||
|
"""
|
||||||
|
下载企微发送记录对应的检核结果 Excel。
|
||||||
|
核心逻辑:能看发送记录的人即可下载。只放行已挂到立账凭证批次上的 ScheduleRun,不按排程负责人或通知人拦截。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
NotFoundError: 该排程记录不是立账凭证批次,或还没有生成 Excel。
|
||||||
|
"""
|
||||||
|
_require_voucher_check_access()
|
||||||
|
engine = VoucherCheckRun.query.filter_by(schedule_run_id=schedule_run_id).first()
|
||||||
|
if engine is None:
|
||||||
|
raise NotFoundError("立账凭证检核批次不存在", code="VOUCHER_CHECK.RUN_NOT_FOUND")
|
||||||
|
run = ScheduleRun.query.get(schedule_run_id)
|
||||||
|
if run is None or not run.excel_file_data:
|
||||||
|
raise NotFoundError("检核结果 Excel 不存在", code="VOUCHER_CHECK.EXCEL_NOT_FOUND")
|
||||||
|
return send_file(
|
||||||
|
BytesIO(run.excel_file_data),
|
||||||
|
as_attachment=True,
|
||||||
|
download_name=run.excel_file_name or "voucher_check.xlsx",
|
||||||
|
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@workspace_voucher_check_bp.route("/accounting-voucher-check/notify-config", methods=["GET"])
|
@workspace_voucher_check_bp.route("/accounting-voucher-check/notify-config", methods=["GET"])
|
||||||
def workspace_voucher_notify_config_get():
|
def workspace_voucher_notify_config_get():
|
||||||
"""
|
"""
|
||||||
读取按文件类型的企微接收人配置。
|
读取按文件类型的企微接收人配置。
|
||||||
核心逻辑:仅 admin;规则来自销售 Profile,接收人来自独立配置表。
|
核心逻辑:仅 is_platform_admin;规则来自销售 Profile,接收人来自独立配置表。
|
||||||
"""
|
"""
|
||||||
_require_admin()
|
_require_admin()
|
||||||
return ok(notify_config_service.get_notify_config(profile_code=request.args.get("profile_code")))
|
return ok(notify_config_service.get_notify_config(profile_code=request.args.get("profile_code")))
|
||||||
@@ -191,7 +222,7 @@ def workspace_voucher_notify_config_get():
|
|||||||
def workspace_voucher_notify_config_put():
|
def workspace_voucher_notify_config_put():
|
||||||
"""
|
"""
|
||||||
保存按文件类型的企微接收人。
|
保存按文件类型的企微接收人。
|
||||||
核心逻辑:仅 admin;未知规则码丢弃;未绑企微的人可保存但发送时跳过。
|
核心逻辑:仅 is_platform_admin;未知规则码丢弃;未绑企微的人可保存但发送时跳过。
|
||||||
"""
|
"""
|
||||||
user = _require_admin()
|
user = _require_admin()
|
||||||
payload = request.get_json(silent=True) or {}
|
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
|
backend/app/core/config/env_persistence.py
|
||||||
|
|
||||||
用途:运行时配置 DB 持久化与 env 镜像(WeCom 等 admin 设置)。
|
用途:运行时配置 DB 持久化与 env 镜像(WeCom 等 admin 设置)。
|
||||||
依赖:app.extensions.db、app.models.AppSetting。
|
依赖:app.extensions.db、app.models.AppSetting、threading/time(进程内 TTL 缓存)。
|
||||||
逻辑:before_request 调用 apply_env_settings;persist_env_settings 供 admin 写入。
|
逻辑:admin 经 persist_env_settings 写入;HTTP before_request 调用 apply_env_settings
|
||||||
|
按 APP_SETTINGS_REFRESH_SECONDS 做进程内 TTL,避免每个请求全表扫描;写入时刷新缓存。
|
||||||
|
|
||||||
Storage strategy:
|
Storage strategy:
|
||||||
1. Database (app_settings) - canonical
|
1. Database (app_settings) - canonical
|
||||||
@@ -15,6 +16,8 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Iterable
|
from typing import Iterable
|
||||||
|
|
||||||
@@ -39,6 +42,12 @@ WECOM_BOOL_KEYS = {
|
|||||||
'WECOM_FEEDBACK_NOTIFY_ENABLED',
|
'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
|
# Helpers
|
||||||
@@ -87,6 +96,27 @@ def _matches_prefixes(key: str, prefixes: Iterable[str]) -> bool:
|
|||||||
return any(key.startswith(prefix) for prefix in prefixes)
|
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)
|
# 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]:
|
def _load_from_db(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||||
|
"""
|
||||||
|
从 app_settings 读取匹配前缀的配置行。
|
||||||
|
|
||||||
|
核心逻辑:用 LIKE 前缀过滤,避免每次 before_request 拉全表后再 Python 过滤。
|
||||||
|
"""
|
||||||
try:
|
try:
|
||||||
|
from sqlalchemy import or_
|
||||||
|
|
||||||
from app.extensions import db
|
from app.extensions import db
|
||||||
from app.models import AppSetting
|
from app.models import AppSetting
|
||||||
except Exception as exc: # pragma: no cover
|
except Exception as exc: # pragma: no cover
|
||||||
@@ -135,7 +172,11 @@ def _load_from_db(prefixes: tuple[str, ...]) -> dict[str, str]:
|
|||||||
return {}
|
return {}
|
||||||
|
|
||||||
try:
|
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:
|
except Exception as exc:
|
||||||
# Most common case: the migration has not been applied yet on a
|
# Most common case: the migration has not been applied yet on a
|
||||||
# freshly-built container. Degrade gracefully to .env-only mode.
|
# 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]:
|
def invalidate_env_settings_cache() -> None:
|
||||||
"""Persist settings to the canonical store and mirror to ``os.environ``.
|
"""
|
||||||
|
清空进程内配置缓存,使下次 apply_env_settings 强制读库。
|
||||||
|
|
||||||
Order:
|
用途:测试或运维需要立刻看到外部写入的 app_settings 时调用。
|
||||||
1. Mirror to ``os.environ`` so the current process picks them up
|
"""
|
||||||
immediately.
|
global _cache_loaded_at, _cache_applied, _cache_prefixes
|
||||||
2. Persist to the database (canonical, survives container rebuilds).
|
with _cache_lock:
|
||||||
3. In dev only, best-effort write to ``.env.local`` so local restarts
|
_cache_loaded_at = 0.0
|
||||||
without DB access keep working.
|
_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:
|
if not values:
|
||||||
return {}
|
return {}
|
||||||
@@ -226,24 +288,61 @@ def persist_env_settings(values: dict[str, object]) -> dict[str, str]:
|
|||||||
list(persisted.keys()),
|
list(persisted.keys()),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# [STEP] 写入后失效缓存:下一请求全量重载,避免「只合并写入键」导致 TTL 内缺键。
|
||||||
|
# 当前进程通常已在 admin service 里同步写过 current_app.config。
|
||||||
|
invalidate_env_settings_cache()
|
||||||
|
|
||||||
return persisted
|
return persisted
|
||||||
|
|
||||||
|
|
||||||
def apply_env_settings(prefixes: tuple[str, ...] = ('WECOM_',)) -> dict[str, object]:
|
def apply_env_settings(
|
||||||
"""Load settings from the canonical store and apply to ``os.environ``.
|
prefixes: tuple[str, ...] = ('WECOM_',),
|
||||||
|
*,
|
||||||
DB values take priority over env-file values; both are merged so
|
force: bool = False,
|
||||||
keys that only live in env files (e.g. fresh deploy before any admin
|
) -> dict[str, object]:
|
||||||
edit) are still honored.
|
|
||||||
"""
|
"""
|
||||||
|
从权威存储加载设置并应用到 ``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)
|
file_values = _load_from_env_file(prefixes)
|
||||||
db_values = _load_from_db(prefixes)
|
db_values = _load_from_db(prefixes)
|
||||||
|
|
||||||
merged: dict[str, str] = {**file_values, **db_values}
|
merged: dict[str, str] = {**file_values, **db_values}
|
||||||
|
|
||||||
applied: dict[str, object] = {}
|
applied = {}
|
||||||
for key, raw_value in merged.items():
|
for key, raw_value in merged.items():
|
||||||
parsed = _parse_env_value(key, raw_value)
|
parsed = _parse_env_value(key, raw_value)
|
||||||
os.environ[key] = _to_env_string(parsed)
|
os.environ[key] = _to_env_string(parsed)
|
||||||
applied[key] = 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
|
ENV_NAME = ACTIVE_ENV_NAME
|
||||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||||
SECRET_KEY = os.getenv('SECRET_KEY')
|
SECRET_KEY = os.getenv('SECRET_KEY')
|
||||||
|
# 运行时可编辑配置(app_settings)进程内热更新间隔(秒);0=每请求强制读库
|
||||||
|
APP_SETTINGS_REFRESH_SECONDS = float(os.getenv('APP_SETTINGS_REFRESH_SECONDS', '30') or '30')
|
||||||
# 配置最大上传文件大小(200MB)
|
# 配置最大上传文件大小(200MB)
|
||||||
MAX_CONTENT_LENGTH = 200 * 1024 * 1024
|
MAX_CONTENT_LENGTH = 200 * 1024 * 1024
|
||||||
KB_STORAGE_ROOT = _data_path('KB_STORAGE_ROOT', 'kb')
|
KB_STORAGE_ROOT = _data_path('KB_STORAGE_ROOT', 'kb')
|
||||||
@@ -289,6 +291,10 @@ class Config:
|
|||||||
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS = int(
|
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS = int(
|
||||||
os.getenv('IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS', '600') or '600'
|
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_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_ESCALATE_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS', '5') or '5')
|
||||||
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS', '7') or '7')
|
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS', '7') or '7')
|
||||||
@@ -364,14 +370,18 @@ class Config:
|
|||||||
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY = float(
|
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY = float(
|
||||||
os.getenv('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY') or '0.98'
|
os.getenv('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY') or '0.98'
|
||||||
)
|
)
|
||||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
|
SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED = (
|
||||||
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
|
os.getenv('SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED', 'true').lower() == 'true'
|
||||||
)
|
)
|
||||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS = int(
|
FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS = int(
|
||||||
os.getenv('FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS') or '900'
|
os.getenv('FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS') or '900'
|
||||||
)
|
)
|
||||||
FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS = int(
|
FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS = int(
|
||||||
os.getenv('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS') or '900'
|
os.getenv('FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS') or '900'
|
||||||
|
)
|
||||||
|
# 出站抓取本期无 Worker;超时键与 inbound 同形预留,避免后续批次再改 env 骨架。
|
||||||
|
FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS = int(
|
||||||
|
os.getenv('FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS') or '900'
|
||||||
)
|
)
|
||||||
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int(
|
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int(
|
||||||
os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90'
|
os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90'
|
||||||
@@ -433,35 +443,51 @@ class Config:
|
|||||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS = int(
|
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS = int(
|
||||||
os.getenv('SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS') or '24'
|
os.getenv('SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS') or '24'
|
||||||
)
|
)
|
||||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED = (
|
SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED = (
|
||||||
os.getenv('SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED', 'true').lower() == 'true'
|
os.getenv('SHIPPING_NOTICE_ONHAND_RPA_BATCH_ENABLED', 'true').lower() == 'true'
|
||||||
)
|
)
|
||||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
|
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
|
||||||
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
|
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
|
||||||
# RPA 运行期数据目录统一为 `freight_rpa/{inventory,receipt,common}` 三层布局(与 env/ps1 三侧一致)。
|
# RPA 运行期数据目录分域(2026-10-16 批次 R):
|
||||||
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR = _rpa_data_path(
|
# onhand/ inbound/ outbound/ — 抓取域,叶目录同构 triggers|drop|logs|archives
|
||||||
'FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR', 'freight_rpa', 'inventory', 'drop'
|
# upload/ — 上传域,叶目录 triggers|queue(与抓取域并列,勿挂 outbound 下)
|
||||||
|
# common/ — 跨 Worker 共享(browser_profile)
|
||||||
|
# outbound 本期无 Worker,仍落盘同构目录 + env,避免切换日再改骨架。
|
||||||
|
FREIGHT_RPA_SHARED_ONHAND_DROP_DIR = _rpa_data_path(
|
||||||
|
'FREIGHT_RPA_SHARED_ONHAND_DROP_DIR', 'freight_rpa', 'onhand', 'drop'
|
||||||
)
|
)
|
||||||
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR = _rpa_data_path(
|
FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR = _rpa_data_path(
|
||||||
'FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR', 'freight_rpa', 'inventory', 'triggers'
|
'FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR', 'freight_rpa', 'onhand', 'triggers'
|
||||||
)
|
)
|
||||||
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR = _rpa_data_path(
|
FREIGHT_RPA_SHARED_INBOUND_DROP_DIR = _rpa_data_path(
|
||||||
'FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR', 'freight_rpa', 'receipt', 'drop'
|
'FREIGHT_RPA_SHARED_INBOUND_DROP_DIR', 'freight_rpa', 'inbound', 'drop'
|
||||||
)
|
)
|
||||||
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR = _rpa_data_path(
|
FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR = _rpa_data_path(
|
||||||
'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', 'freight_rpa', 'receipt', 'triggers'
|
'FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR', 'freight_rpa', 'inbound', 'triggers'
|
||||||
|
)
|
||||||
|
FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR = _rpa_data_path(
|
||||||
|
'FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR', 'freight_rpa', 'outbound', 'drop'
|
||||||
|
)
|
||||||
|
FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR = _rpa_data_path(
|
||||||
|
'FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR', 'freight_rpa', 'outbound', 'triggers'
|
||||||
)
|
)
|
||||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = _rpa_data_path(
|
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = _rpa_data_path(
|
||||||
'FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR', 'freight_rpa', 'inventory', 'upload_queue'
|
'FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR', 'freight_rpa', 'upload', 'queue'
|
||||||
)
|
)
|
||||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = _rpa_data_path(
|
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = _rpa_data_path(
|
||||||
'FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR', 'freight_rpa', 'inventory', 'upload_triggers'
|
'FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR', 'freight_rpa', 'upload', 'triggers'
|
||||||
)
|
)
|
||||||
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = _rpa_data_path(
|
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = _rpa_data_path(
|
||||||
'FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR', 'freight_rpa', 'common', 'browser_profile'
|
'FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR', 'freight_rpa', 'common', 'browser_profile'
|
||||||
)
|
)
|
||||||
FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = _rpa_data_path(
|
FREIGHT_RPA_ONHAND_ARCHIVE_DIR = _rpa_data_path(
|
||||||
'FREIGHT_RPA_INVENTORY_ARCHIVE_DIR', 'freight_rpa', 'inventory', 'archives'
|
'FREIGHT_RPA_ONHAND_ARCHIVE_DIR', 'freight_rpa', 'onhand', 'archives'
|
||||||
|
)
|
||||||
|
FREIGHT_RPA_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')
|
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_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
|
||||||
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
||||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines')
|
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning,equipment_acceptance_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,order_delivery_reply_notify,training_lean_video_push,training_overseas_thailand_guidelines')
|
||||||
# 精益培训企微提醒卡片跳转的员工培训聊天页 agent id(前端路由 /chat/<id>)。
|
# 精益培训企微提醒卡片跳转的员工培训聊天页 agent id(前端路由 /chat/<id>)。
|
||||||
# 缺省 0 = 不显式指定,由后端按 handler_config.content_profile='training' 动态解析各环境的培训 Agent
|
# 缺省 0 = 不显式指定,由后端按 handler_config.content_profile='training' 动态解析各环境的培训 Agent
|
||||||
# (测试/正式环境 Agent ID 不同,动态解析保证卡片均可定位「员工培训-精益管理」);
|
# (测试/正式环境 Agent ID 不同,动态解析保证卡片均可定位「员工培训-精益管理」);
|
||||||
@@ -541,6 +567,13 @@ class Config:
|
|||||||
SCHEDULE_WORKER_ENABLED = os.getenv('SCHEDULE_WORKER_ENABLED', 'true').lower() == 'true'
|
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_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')
|
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。
|
# Cron 表达式按此时区解读(如 0 12 * * * 表示该时区 12:00);入库 next_run_at 仍为 UTC。
|
||||||
SCHEDULE_TIMEZONE = (os.getenv('SCHEDULE_TIMEZONE') or 'Asia/Shanghai').strip()
|
SCHEDULE_TIMEZONE = (os.getenv('SCHEDULE_TIMEZONE') or 'Asia/Shanghai').strip()
|
||||||
SRM_SQLSERVER_HOST = os.getenv('SRM_SQLSERVER_HOST', '')
|
SRM_SQLSERVER_HOST = os.getenv('SRM_SQLSERVER_HOST', '')
|
||||||
@@ -759,9 +792,14 @@ class ProductionConfig(Config):
|
|||||||
class TestingConfig(Config):
|
class TestingConfig(Config):
|
||||||
TESTING = True
|
TESTING = True
|
||||||
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
|
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
|
WTF_CSRF_ENABLED = False
|
||||||
SQLALCHEMY_ENGINE_OPTIONS = {}
|
SQLALCHEMY_ENGINE_OPTIONS = {}
|
||||||
SCHEDULE_WORKER_ENABLED = False
|
SCHEDULE_WORKER_ENABLED = False
|
||||||
|
SCHEDULE_WEB_SCANNER_ENABLED = False
|
||||||
FIXED_ASSETS_SYNC_ENABLED = False
|
FIXED_ASSETS_SYNC_ENABLED = False
|
||||||
FIXED_ASSETS_EXPORT_TO_DOCS = False
|
FIXED_ASSETS_EXPORT_TO_DOCS = False
|
||||||
ENV_NAME = 'dev'
|
ENV_NAME = 'dev'
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ def _resolve_request_agent_id() -> str | None:
|
|||||||
def require_agent_permission(f):
|
def require_agent_permission(f):
|
||||||
"""
|
"""
|
||||||
装饰器:校验当前用户是否拥有指定 Agent 访问权限。
|
装饰器:校验当前用户是否拥有指定 Agent 访问权限。
|
||||||
核心逻辑:从 body/query/form 读 agent_id → 获取用户 → admin 放行或检查 user.agents。
|
核心逻辑:从 body/query/form 读 agent_id → 获取用户 → 平台管理员放行或检查 user.agents。
|
||||||
Args:
|
Args:
|
||||||
f: 被装饰的视图函数。
|
f: 被装饰的视图函数。
|
||||||
Returns:
|
Returns:
|
||||||
@@ -66,7 +66,7 @@ def require_agent_permission(f):
|
|||||||
if not agent:
|
if not agent:
|
||||||
raise NotFoundError('Agent not found')
|
raise NotFoundError('Agent not found')
|
||||||
g.current_agent = agent
|
g.current_agent = agent
|
||||||
if user.role == 'admin':
|
if user.is_platform_admin():
|
||||||
return f(*args, **kwargs)
|
return f(*args, **kwargs)
|
||||||
if agent not in user.agents:
|
if agent not in user.agents:
|
||||||
raise ForbiddenError('Permission denied for this agent')
|
raise ForbiddenError('Permission denied for this agent')
|
||||||
@@ -77,8 +77,8 @@ def require_agent_permission(f):
|
|||||||
|
|
||||||
def require_admin(f):
|
def require_admin(f):
|
||||||
"""
|
"""
|
||||||
装饰器:限制仅 admin 角色可访问。
|
装饰器:限制仅平台管理员可访问。
|
||||||
核心逻辑:解析用户 → 校验 role == admin;JWT 必填时检查 Authorization 头。
|
核心逻辑:解析用户 → 校验 is_platform_admin;JWT 必填时检查 Authorization 头。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@wraps(f)
|
@wraps(f)
|
||||||
@@ -88,7 +88,7 @@ def require_admin(f):
|
|||||||
raise UnauthorizedError('Unauthorized')
|
raise UnauthorizedError('Unauthorized')
|
||||||
if bool(current_app.config.get('AUTH_JWT_REQUIRED', False)) and (not request.headers.get('Authorization')):
|
if bool(current_app.config.get('AUTH_JWT_REQUIRED', False)) and (not request.headers.get('Authorization')):
|
||||||
raise UnauthorizedError('JWT token is required')
|
raise UnauthorizedError('JWT token is required')
|
||||||
if user.role != 'admin':
|
if not user.is_platform_admin():
|
||||||
raise ForbiddenError('Admin privilege required')
|
raise ForbiddenError('Admin privilege required')
|
||||||
return f(*args, **kwargs)
|
return f(*args, **kwargs)
|
||||||
|
|
||||||
|
|||||||
@@ -28,11 +28,14 @@ class ValidationError(AppError):
|
|||||||
*,
|
*,
|
||||||
code: str = "VALIDATION.INVALID_PARAM",
|
code: str = "VALIDATION.INVALID_PARAM",
|
||||||
details: dict[str, Any] | None = None,
|
details: dict[str, Any] | None = None,
|
||||||
|
http_status: int = 400,
|
||||||
):
|
):
|
||||||
super().__init__(
|
super().__init__(
|
||||||
code=code,
|
code=code,
|
||||||
message=message,
|
message=message,
|
||||||
http_status=400,
|
# 默认 400(参数形态类校验);业务契约指定状态码时显式传入
|
||||||
|
# (如调拨类型门禁 REQUIRED/NOT_CONFIGURED/DISABLED = 422,规格 §11)。
|
||||||
|
http_status=http_status,
|
||||||
details=details or {},
|
details=details or {},
|
||||||
retryable=False,
|
retryable=False,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
"""
|
||||||
|
backend/app/core/tool_auth.py
|
||||||
|
|
||||||
|
用途:集成密钥鉴权的公共实现,供所有以 Bearer / X-Integration-Key 方式接入的
|
||||||
|
Tool / 回调蓝图共用(当前:shipping_notice Tool 蓝图、freight-rpa 回调蓝图)。
|
||||||
|
依赖:flask.current_app/request、app.core.errors(ServiceUnavailableError / UnauthorizedError)。
|
||||||
|
逻辑:由各蓝图 before_request 调用 require_tool_auth();本模块只做 Header 校验,
|
||||||
|
不感知任何具体蓝图的错误 envelope(由蓝图自身 errorhandler 决定响应格式)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from flask import current_app, request
|
||||||
|
|
||||||
|
from app.core.errors import ServiceUnavailableError, UnauthorizedError
|
||||||
|
|
||||||
|
|
||||||
|
def require_tool_auth() -> None:
|
||||||
|
"""
|
||||||
|
校验集成方 Tool / RPA 回调 API 鉴权 Header。
|
||||||
|
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;当 Dify、RPA Worker 或
|
||||||
|
外部系统请求挂接本鉴权的蓝图时,由该蓝图的 before_request 自动触发。
|
||||||
|
|
||||||
|
核心逻辑:只接受 `Authorization: Bearer <token>` 或 `X-Integration-Key`。
|
||||||
|
货代专用 `SHIPPING_NOTICE_TOOL_API_KEY` 优先,未配置时回退 `INTEGRATION_API_KEY`;
|
||||||
|
未配置任何可用 key 时报服务不可用,缺失或错误时报未授权。
|
||||||
|
"""
|
||||||
|
configured = str(
|
||||||
|
current_app.config.get('SHIPPING_NOTICE_TOOL_API_KEY')
|
||||||
|
or current_app.config.get('INTEGRATION_API_KEY')
|
||||||
|
or ''
|
||||||
|
).strip()
|
||||||
|
if not configured:
|
||||||
|
raise ServiceUnavailableError(
|
||||||
|
'SHIPPING_NOTICE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured',
|
||||||
|
code='missing_auth',
|
||||||
|
)
|
||||||
|
bearer = str(request.headers.get('Authorization') or '').strip()
|
||||||
|
token = bearer[7:].strip() if bearer.lower().startswith('bearer ') else ''
|
||||||
|
integration_key = str(request.headers.get('X-Integration-Key') or '').strip()
|
||||||
|
if configured in {token, integration_key}:
|
||||||
|
return
|
||||||
|
if not token and (not integration_key):
|
||||||
|
raise UnauthorizedError('missing_auth')
|
||||||
|
raise UnauthorizedError('invalid_auth')
|
||||||
@@ -9,14 +9,14 @@ from app.jobs.handlers import ( # noqa: F401
|
|||||||
contract_payment,
|
contract_payment,
|
||||||
file_check_run,
|
file_check_run,
|
||||||
in_transit_transfer_item,
|
in_transit_transfer_item,
|
||||||
in_transit_transfer_precheck,
|
in_transit_transfer_match,
|
||||||
in_transit_transfer_run,
|
in_transit_transfer_run,
|
||||||
kb_clean,
|
kb_clean,
|
||||||
kb_dify_sync,
|
kb_dify_sync,
|
||||||
procurement_contract_review,
|
procurement_contract_review,
|
||||||
schedule_run,
|
schedule_run,
|
||||||
shipping_document_layout,
|
shipping_document_layout,
|
||||||
shipping_inventory_callback_process,
|
freight_rpa_onhand_callback_process,
|
||||||
shipping_notice_parse,
|
shipping_notice_parse,
|
||||||
shipping_notice_run,
|
shipping_notice_run,
|
||||||
shipping_order_extraction,
|
shipping_order_extraction,
|
||||||
|
|||||||
+31
-7
@@ -1,9 +1,13 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/jobs/handlers/shipping_inventory_callback_process.py
|
backend/app/jobs/handlers/freight_rpa_onhand_callback_process.py
|
||||||
|
|
||||||
用途:异步处理已收件的库存 RPA batch 回调,避免 Worker HTTP 回调被 Excel 处理阻塞。
|
用途:异步处理已收件的库存 RPA batch 回调,避免 Worker HTTP 回调被 Excel 处理阻塞。
|
||||||
依赖:Job 队列、inventory_rpa_workflow 的正式批量处理函数。
|
依赖:Job 队列、onhand_rpa_workflow 的正式批量处理函数。
|
||||||
逻辑:HTTP 回调只写本 Job;shipping worker 领取后执行结构校验、库存解析、任务关联与后续推进。
|
逻辑:HTTP 回调只写本 Job;shipping worker 领取后执行结构校验、库存解析、任务关联与后续推进。
|
||||||
|
业务失败(transport/result_status=failed)收口为不可重试;意外异常(含批量 commit 后
|
||||||
|
onhand 事实处理函数失败的重抛)收口为可重试(Task 7 修复轮 2——文件行已提交不回滚,
|
||||||
|
重放按幂等契约补齐候选/门禁收口);修复轮 3:投递失败重抛携带的未成功文件清单写回
|
||||||
|
payload(retry_dispatch_files),重试经批量入口的「只重投失败文件」通道补齐。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -16,7 +20,7 @@ from app.jobs.types import JobType
|
|||||||
from app.models import Job
|
from app.models import Job
|
||||||
|
|
||||||
|
|
||||||
@register_handler(JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS)
|
@register_handler(JobType.FREIGHT_RPA_ONHAND_CALLBACK_PROCESS)
|
||||||
def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> None:
|
def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> None:
|
||||||
"""处理一个已收件的库存 RPA 回调。
|
"""处理一个已收件的库存 RPA 回调。
|
||||||
|
|
||||||
@@ -31,7 +35,7 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N
|
|||||||
|
|
||||||
owned_attempt = int(job.attempts or 0)
|
owned_attempt = int(job.attempts or 0)
|
||||||
try:
|
try:
|
||||||
from app.services.shipping_notice.inventory_rpa_workflow import process_rpa_report_inventory_batch
|
from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch
|
||||||
|
|
||||||
result = process_rpa_report_inventory_batch(dict(job.payload_json or {}))
|
result = process_rpa_report_inventory_batch(dict(job.payload_json or {}))
|
||||||
result_data = result.get('data') if isinstance(result, dict) else None
|
result_data = result.get('data') if isinstance(result, dict) else None
|
||||||
@@ -44,7 +48,7 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N
|
|||||||
if transport_status == 'failed' or result_status in {'failed', 'partial_failed'}:
|
if transport_status == 'failed' or result_status in {'failed', 'partial_failed'}:
|
||||||
failed_items = result_data.get('failed') if isinstance(result_data, dict) else []
|
failed_items = result_data.get('failed') if isinstance(result_data, dict) else []
|
||||||
first_error = failed_items[0].get('error') if isinstance(failed_items, list) and failed_items and isinstance(failed_items[0], dict) else None
|
first_error = failed_items[0].get('error') if isinstance(failed_items, list) and failed_items and isinstance(failed_items[0], dict) else None
|
||||||
from app.services.shipping_notice.inventory_rpa_workflow import settle_failed_inventory_callback
|
from app.services.shipping_notice.onhand_rpa_workflow import settle_failed_inventory_callback
|
||||||
|
|
||||||
settle_failed_inventory_callback(
|
settle_failed_inventory_callback(
|
||||||
dict(job.payload_json or {}),
|
dict(job.payload_json or {}),
|
||||||
@@ -64,12 +68,32 @@ def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> N
|
|||||||
message='库存 RPA 回调已异步处理',
|
message='库存 RPA 回调已异步处理',
|
||||||
owned_attempt=owned_attempt,
|
owned_attempt=owned_attempt,
|
||||||
)
|
)
|
||||||
except Exception as exc: # noqa: BLE001 - queue must retain retryable receipt evidence
|
except Exception as exc: # noqa: BLE001 - 队列收口保留可重试证据
|
||||||
db.session.rollback()
|
db.session.rollback()
|
||||||
|
# 【Task 7 修复轮 3】批量 commit 后投递失败的重抛携带「未成功文件清单」——
|
||||||
|
# 写回 Job payload(retry_dispatch_files),重试经批量入口的「只重投失败
|
||||||
|
# 文件」通道补齐(整批重放会被 callback_id 已消费的 replay 检查跳过、
|
||||||
|
# 已收口的排程 run 校验拦下);清单随重试结果逐轮收敛,直至全部成功或
|
||||||
|
# attempts 耗尽。普通意外异常(无清单)仍整批自然重放。
|
||||||
|
from app.services.shipping_notice.onhand_rpa_workflow import (
|
||||||
|
OnhandReportDispatchAfterCommitError,
|
||||||
|
)
|
||||||
|
|
||||||
|
if isinstance(exc, OnhandReportDispatchAfterCommitError) and exc.failed_files:
|
||||||
|
job.payload_json = {
|
||||||
|
**(dict(job.payload_json or {})),
|
||||||
|
'retry_dispatch_files': list(exc.failed_files),
|
||||||
|
}
|
||||||
|
db.session.commit()
|
||||||
fail_job(
|
fail_job(
|
||||||
job.id,
|
job.id,
|
||||||
error=str(exc),
|
error=str(exc),
|
||||||
result={'status': 'processing_failed', 'error': str(exc)[:1000]},
|
result={'status': 'processing_failed', 'error': str(exc)[:1000]},
|
||||||
retryable=False,
|
# 【Task 7 修复轮 2】意外异常(含批量 commit 后 onhand 事实处理函数失败
|
||||||
|
# ——process_rpa_report_inventory_batch 已尽力完成其余投递、排程收口与
|
||||||
|
# drop 文件清理入队后原样重抛)必须可重试:文件行已提交不回滚,重放按
|
||||||
|
# 幂等契约补齐收口;业务失败(transport/result_status=failed)仍走上方
|
||||||
|
# retryable=False 分支。
|
||||||
|
retryable=True,
|
||||||
owned_attempt=owned_attempt,
|
owned_attempt=owned_attempt,
|
||||||
)
|
)
|
||||||
@@ -2,13 +2,17 @@
|
|||||||
|
|
||||||
用途:Invoice 级执行 Job:对单个明细执行写前复查 + ERP 原子写入。
|
用途:Invoice 级执行 Job:对单个明细执行写前复查 + ERP 原子写入。
|
||||||
依赖:execution_service.execute_item、transfer deps、Job 注册表。
|
依赖:execution_service.execute_item、transfer deps、Job 注册表。
|
||||||
逻辑:payload 携带 item_id;单项结果不影响其他项。
|
逻辑:payload 携带 item_id;单项结果不影响其他项。业务收尾后 handler 自行
|
||||||
|
finish_job(runner 仅兜底异常路径,正常完成不代收口)。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.jobs.queue import finish_job
|
||||||
from app.jobs.registry import register_handler
|
from app.jobs.registry import register_handler
|
||||||
from app.jobs.types import JobType
|
from app.jobs.types import JobType
|
||||||
|
from app.models import Job
|
||||||
from app.services.in_transit_transfer import deps as transfer_deps
|
from app.services.in_transit_transfer import deps as transfer_deps
|
||||||
from app.services.in_transit_transfer.execution_service import execute_item
|
from app.services.in_transit_transfer.execution_service import execute_item
|
||||||
|
|
||||||
@@ -23,7 +27,16 @@ def run_in_transit_transfer_item(_ctx, payload: dict) -> None:
|
|||||||
item_id = payload.get("item_id")
|
item_id = payload.get("item_id")
|
||||||
if item_id is None:
|
if item_id is None:
|
||||||
raise RuntimeError("missing_transfer_item_id")
|
raise RuntimeError("missing_transfer_item_id")
|
||||||
execute_item(
|
# 领取代次快照:finish_job 条件 UPDATE 需与领取时一致,防止超时重领后错收新代次。
|
||||||
|
job_row = db.session.get(Job, int(payload["job_id"])) if payload.get("job_id") else None
|
||||||
|
owned_attempt = int(job_row.attempts) if job_row is not None else None
|
||||||
|
status = execute_item(
|
||||||
item_id=int(item_id),
|
item_id=int(item_id),
|
||||||
deps=transfer_deps.get_transfer_dependencies(),
|
deps=transfer_deps.get_transfer_dependencies(),
|
||||||
)
|
)
|
||||||
|
if job_row is not None:
|
||||||
|
finish_job(
|
||||||
|
int(job_row.id),
|
||||||
|
message=f"调拨单行执行完成:item_id={item_id} status={status}",
|
||||||
|
owned_attempt=owned_attempt,
|
||||||
|
)
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
"""backend/app/jobs/handlers/in_transit_transfer_match.py
|
||||||
|
|
||||||
|
用途:异步执行在途调拨匹配(文件准备 + 只读匹配),并更新匹配状态。
|
||||||
|
依赖:Job 注册表、matching_service、transfer 模型、transfer deps。
|
||||||
|
逻辑:领取后按 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
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.jobs.queue import finish_job
|
||||||
|
from app.jobs.registry import register_handler
|
||||||
|
from app.jobs.types import JobType
|
||||||
|
from app.models import Job, TransferMatching
|
||||||
|
from app.services.in_transit_transfer import deps as transfer_deps
|
||||||
|
from app.services.in_transit_transfer.matching_service import run_matching
|
||||||
|
|
||||||
|
|
||||||
|
@register_handler(JobType.TRANSFER_MATCH)
|
||||||
|
def run_in_transit_transfer_match(_ctx, payload: dict) -> None:
|
||||||
|
"""执行一次匹配 Job 并更新匹配状态。
|
||||||
|
|
||||||
|
【AI 触发时机】:仅由匹配创建异步路径入队;页面直连走 API 同步路径。
|
||||||
|
"""
|
||||||
|
payload = payload if isinstance(payload, dict) else {}
|
||||||
|
matching_no = str(payload.get("matching_id") or "").strip()
|
||||||
|
if not matching_no:
|
||||||
|
raise RuntimeError("missing_transfer_matching_id")
|
||||||
|
matching = db.session.query(TransferMatching).filter_by(matching_no=matching_no).first()
|
||||||
|
if matching is None:
|
||||||
|
raise RuntimeError(f"missing_transfer_matching: {matching_no}")
|
||||||
|
# 领取代次快照:finish_job 条件 UPDATE 需与领取时一致,防止超时重领后错收新代次。
|
||||||
|
job_row = db.session.get(Job, int(payload["job_id"])) if payload.get("job_id") else 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(
|
||||||
|
source_codes=source_codes,
|
||||||
|
business_date=matching.business_date,
|
||||||
|
deps=deps,
|
||||||
|
run_no=matching.run.run_no if matching.run else "RUN-PENDING",
|
||||||
|
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,
|
||||||
|
"matched_count": summary.counts.matched_count,
|
||||||
|
"executable_count": summary.counts.executable_count,
|
||||||
|
"blocked_count": summary.counts.blocked_count,
|
||||||
|
}
|
||||||
|
matching.estimated_transfer_quantity = summary.estimated_transfer_quantity
|
||||||
|
matching.estimated_external_write_count = summary.estimated_external_write_count
|
||||||
|
matching.matching_hash = summary.matching_hash
|
||||||
|
db.session.commit()
|
||||||
|
if job_row is not None:
|
||||||
|
finish_job(
|
||||||
|
int(job_row.id),
|
||||||
|
message=f"调拨匹配完成:matching={matching_no} status={summary.status}",
|
||||||
|
owned_attempt=owned_attempt,
|
||||||
|
)
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
"""backend/app/jobs/handlers/in_transit_transfer_precheck.py
|
|
||||||
|
|
||||||
用途:异步执行在途调拨预检(文件准备 + 只读预检),并更新预检状态。
|
|
||||||
依赖:Job 注册表、precheck_service、transfer 模型、transfer deps。
|
|
||||||
逻辑:领取后按 payload.precheck_id 加载预检,运行 run_precheck 并回写
|
|
||||||
状态/计数/Hash;预检不存在时 fail-closed 抛 RuntimeError。
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from app import db
|
|
||||||
from app.jobs.registry import register_handler
|
|
||||||
from app.jobs.types import JobType
|
|
||||||
from app.models import TransferPrecheck
|
|
||||||
from app.services.in_transit_transfer import deps as transfer_deps
|
|
||||||
from app.services.in_transit_transfer.precheck_service import run_precheck
|
|
||||||
|
|
||||||
|
|
||||||
@register_handler(JobType.TRANSFER_PRECHECK)
|
|
||||||
def run_in_transit_transfer_precheck(_ctx, payload: dict) -> None:
|
|
||||||
"""执行一次预检 Job 并更新预检状态。
|
|
||||||
|
|
||||||
【AI 触发时机】:仅由预检创建异步路径入队;页面直连走 API 同步路径。
|
|
||||||
"""
|
|
||||||
payload = payload if isinstance(payload, dict) else {}
|
|
||||||
precheck_no = str(payload.get("precheck_id") or "").strip()
|
|
||||||
if not precheck_no:
|
|
||||||
raise RuntimeError("missing_transfer_precheck_id")
|
|
||||||
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=precheck_no).first()
|
|
||||||
if precheck is None:
|
|
||||||
raise RuntimeError(f"missing_transfer_precheck: {precheck_no}")
|
|
||||||
|
|
||||||
deps = transfer_deps.get_transfer_dependencies()
|
|
||||||
scope = precheck.scope_json if isinstance(precheck.scope_json, dict) else {}
|
|
||||||
source_codes = list(scope.get("source_codes") or [])
|
|
||||||
result = run_precheck(
|
|
||||||
source_codes=source_codes,
|
|
||||||
business_date=precheck.business_date,
|
|
||||||
deps=deps,
|
|
||||||
run_no=precheck.run.run_no if precheck.run else "RUN-PENDING",
|
|
||||||
# 类型范围随预检落库回读:异步重跑与创建时口径一致(缺省回落类型1)。
|
|
||||||
transfer_type=str(scope.get("transfer_type")) if scope.get("transfer_type") else None,
|
|
||||||
)
|
|
||||||
summary = result.summary
|
|
||||||
precheck.status = summary.status
|
|
||||||
precheck.counts_json = {
|
|
||||||
"file_invoice_count": summary.counts.file_invoice_count,
|
|
||||||
"not_matured_count": summary.counts.not_matured_count,
|
|
||||||
"prechecked_count": summary.counts.prechecked_count,
|
|
||||||
"executable_count": summary.counts.executable_count,
|
|
||||||
"blocked_count": summary.counts.blocked_count,
|
|
||||||
}
|
|
||||||
precheck.estimated_transfer_quantity = summary.estimated_transfer_quantity
|
|
||||||
precheck.estimated_external_write_count = summary.estimated_external_write_count
|
|
||||||
precheck.precheck_hash = summary.precheck_hash
|
|
||||||
db.session.commit()
|
|
||||||
@@ -1,29 +1,49 @@
|
|||||||
"""backend/app/jobs/handlers/in_transit_transfer_run.py
|
"""backend/app/jobs/handlers/in_transit_transfer_run.py
|
||||||
|
|
||||||
用途:Run 级执行 Job:加载预检并驱动执行服务完成全部可执行项写入。
|
用途:Run 级执行 Job:领取 TRANSFER_RUN 任务并驱动执行服务 worker 段完成单据级写入。
|
||||||
依赖:execution_service、transfer deps、Job 注册表。
|
依赖:execution_service.execute_run、transfer deps、Job 注册表。
|
||||||
逻辑:payload 携带 precheck_id;执行后预检与 Run 落库终态。
|
逻辑:payload {run_id, item_ids} 为常规路径(worker 执行 Run 名下全部单);
|
||||||
|
{run_id, doc_id} 为 retrigger 路径(D11:result_unknown 单唯一出口,仅执行
|
||||||
|
该单且只触发末步);门禁/组复用守卫由 prepare_execution 前置完成,二次门禁
|
||||||
|
由 execute_run 统一裁定(fail-closed)。业务收尾后 handler 须自行 finish_job
|
||||||
|
(runner 仅兜底异常路径,正常完成不代收口)。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.jobs.queue import finish_job
|
||||||
from app.jobs.registry import register_handler
|
from app.jobs.registry import register_handler
|
||||||
from app.jobs.types import JobType
|
from app.jobs.types import JobType
|
||||||
|
from app.models import Job
|
||||||
from app.services.in_transit_transfer import deps as transfer_deps
|
from app.services.in_transit_transfer import deps as transfer_deps
|
||||||
from app.services.in_transit_transfer.execution_service import execute_precheck
|
from app.services.in_transit_transfer.execution_service import execute_run
|
||||||
|
|
||||||
|
|
||||||
@register_handler(JobType.TRANSFER_RUN)
|
@register_handler(JobType.TRANSFER_RUN)
|
||||||
def run_in_transit_transfer_run(_ctx, payload: dict) -> None:
|
def run_in_transit_transfer_run(_ctx, payload: dict) -> None:
|
||||||
"""执行一个 Run(异步路径)。
|
"""执行 Run 名下全部单(或 retrigger 指定单)(异步路径)。
|
||||||
|
|
||||||
【AI 触发时机】:仅由执行 Run 入队路径调用;页面直连走 API 同步路径。
|
【AI 触发时机】:仅由 prepare_execution(提交建单后)与 retrigger_document
|
||||||
|
(人工重新触发)入队路径调用;页面直连走 API 同步段,不经过本 handler。
|
||||||
"""
|
"""
|
||||||
payload = payload if isinstance(payload, dict) else {}
|
payload = payload if isinstance(payload, dict) else {}
|
||||||
precheck_id = str(payload.get("precheck_id") or "").strip()
|
run_id = str(payload.get("run_id") or "").strip()
|
||||||
if not precheck_id:
|
if not run_id:
|
||||||
raise RuntimeError("missing_transfer_precheck_id")
|
raise RuntimeError("missing_transfer_run_id")
|
||||||
execute_precheck(
|
doc_id = str(payload.get("doc_id") or "").strip()
|
||||||
precheck_id=precheck_id,
|
# 领取代次快照:finish_job 条件 UPDATE 需与领取时一致,防止超时重领后错收新代次。
|
||||||
|
job_row = db.session.get(Job, int(payload["job_id"])) if payload.get("job_id") else None
|
||||||
|
owned_attempt = int(job_row.attempts) if job_row is not None else None
|
||||||
|
status = execute_run(
|
||||||
|
run_id=int(run_id),
|
||||||
deps=transfer_deps.get_transfer_dependencies(),
|
deps=transfer_deps.get_transfer_dependencies(),
|
||||||
|
doc_id=int(doc_id) if doc_id else None,
|
||||||
|
skip_write_recheck=bool(payload.get("skip_write_recheck")),
|
||||||
)
|
)
|
||||||
|
if job_row is not None:
|
||||||
|
finish_job(
|
||||||
|
int(job_row.id),
|
||||||
|
message=f"调拨单执行完成:run_id={run_id} status={status}",
|
||||||
|
owned_attempt=owned_attempt,
|
||||||
|
)
|
||||||
@@ -724,16 +724,83 @@ def _handoff_continue_order_extraction(
|
|||||||
return True
|
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:
|
def _is_transient_lock_error(exc: BaseException) -> bool:
|
||||||
"""
|
"""
|
||||||
判断异常是否为瞬时锁冲突(PostgreSQL 死锁 40P01 / 锁等待超时 55P03)。
|
判断异常是否为瞬时锁冲突(PostgreSQL 死锁 40P01 / 锁等待超时 55P03)。
|
||||||
|
|
||||||
【AI 触发时机】:订单抽取 Job 异常收口时决定是否标记可重试。此类错误重试即可恢复,
|
【AI 触发时机】:订单抽取 Job 异常收口时决定是否标记可重试。此类错误重试即可恢复,
|
||||||
按终态失败收口会触发 run failed 并要求人工重新识别(2026-09-22 生产事故两次)。
|
按终态失败收口会触发 run failed 并要求人工重新识别(2026-09-22 生产事故两次)。
|
||||||
SQLAlchemy 将 DBAPI 错误包装为 exc.orig;非 DBAPI 异常(无 pgcode)一律返回 False。
|
|
||||||
|
需要穿透两层包装:①SQLAlchemy 将 DBAPI 错误挂在 exc.orig;②若失败后同一事务里
|
||||||
|
还有后续语句,SQLAlchemy 会改抛 PendingRollbackError(无 .orig,原文内嵌在 message),
|
||||||
|
或经 __cause__ 链包装。沿 orig/__cause__ 链遍历并对消息做特征匹配,确保包装后的
|
||||||
|
死锁仍被判为瞬时(2026-09-24 test job 8840:同类死锁因分类漏判而一次判死)。
|
||||||
"""
|
"""
|
||||||
orig = getattr(exc, 'orig', None)
|
pgcode_set = {'40P01', '55P03'}
|
||||||
return getattr(orig, 'pgcode', None) in {'40P01', '55P03'}
|
seen: set[int] = set()
|
||||||
|
current: BaseException | None = exc
|
||||||
|
while current is not None and id(current) not in seen and len(seen) < 6:
|
||||||
|
seen.add(id(current))
|
||||||
|
orig = getattr(current, 'orig', None)
|
||||||
|
if getattr(orig, 'pgcode', None) in pgcode_set:
|
||||||
|
return True
|
||||||
|
text = str(current)
|
||||||
|
if 'DeadlockDetected' in text or 'deadlock detected' in text or '40P01' in text or '55P03' in text:
|
||||||
|
return True
|
||||||
|
current = getattr(current, 'orig', None) or getattr(current, '__cause__', None)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
@register_handler(JobType.SHIPPING_ORDER_EXTRACTION)
|
@register_handler(JobType.SHIPPING_ORDER_EXTRACTION)
|
||||||
@@ -929,15 +996,13 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
|||||||
persisted_orders.extend(unit_orders_by_id[int(unit.id)])
|
persisted_orders.extend(unit_orders_by_id[int(unit.id)])
|
||||||
wave_orders.extend(unit_orders_by_id[int(unit.id)])
|
wave_orders.extend(unit_orders_by_id[int(unit.id)])
|
||||||
# 重试路径:已 candidate_ready 的 Unit 仍须独立触发下游(幂等)。
|
# 重试路径:已 candidate_ready 的 Unit 仍须独立触发下游(幂等)。
|
||||||
# [交接不变量] defer_stp_enqueue:开工快照仍有待排版附件(本 Job 必交接)时
|
# [收口不变量] 推送只物化 Candidate/Review Case,STP 统一由 run 收口
|
||||||
# 推迟 STP 入队到 run 收口,确保 STP 只由最后一个抽取 Job 提交;否则本 Job
|
# (submit_order_extraction_run_result)入队——STP Job 可见时抽取 Job
|
||||||
# 提交的 STP Job 会与续抽 Job 并发执行,双方以相反顺序抢 run/intake 行锁
|
# 必已提交完毕,结构性消除抽取∥STP 并发死锁(2026-09-22/24 事故族)。
|
||||||
# 形成结构性死锁(2026-09-22 SNER-20260922-6466EB53 生产事故)。
|
# 推送失败必须冒泡:此处是这些 Unit 候选与复核 Case 的唯一物化触发点,
|
||||||
# 推送失败必须冒泡(与下方新单元推送同一规则):此处是这些 Unit 候选与
|
# 吞掉等于静默丢单。
|
||||||
# 复核 Case 的唯一物化触发点,吞掉等于静默丢单。
|
|
||||||
progress_ready_extraction_unit(
|
progress_ready_extraction_unit(
|
||||||
run=run, unit=unit, orders=unit_orders_by_id[int(unit.id)],
|
run=run, unit=unit, orders=unit_orders_by_id[int(unit.id)],
|
||||||
defer_stp_enqueue=bool(pending_layout_ids),
|
|
||||||
)
|
)
|
||||||
continue
|
continue
|
||||||
if unit.status == 'review_required':
|
if unit.status == 'review_required':
|
||||||
@@ -1126,6 +1191,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
_merge_group_orders(eml_units, apply_email_supplements=True)
|
_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(
|
append_shipping_audit_event(
|
||||||
event_type='ORDER_EMAIL_ADJUDICATION_COMPLETED',
|
event_type='ORDER_EMAIL_ADJUDICATION_COMPLETED',
|
||||||
aggregate_type='order_extraction_run',
|
aggregate_type='order_extraction_run',
|
||||||
@@ -1208,11 +1274,10 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
|||||||
apply_worker_cancellation_checkpoint(run=run)
|
apply_worker_cancellation_checkpoint(run=run)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
continue
|
continue
|
||||||
# [交接不变量] 同 replay 路径:本 Job 仍会交接时推迟 STP 入队到 run 收口。
|
# [收口不变量] 同 replay 路径:推送只物化候选与复核 Case,STP 由 run 收口入队。
|
||||||
try:
|
try:
|
||||||
unit_persist = progress_ready_extraction_unit(
|
unit_persist = progress_ready_extraction_unit(
|
||||||
run=run, unit=unit, orders=merged_unit_orders,
|
run=run, unit=unit, orders=merged_unit_orders,
|
||||||
defer_stp_enqueue=bool(pending_layout_ids),
|
|
||||||
)
|
)
|
||||||
record_unit_progress(
|
record_unit_progress(
|
||||||
run=run,
|
run=run,
|
||||||
@@ -1226,6 +1291,10 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
|||||||
job_id=job.id,
|
job_id=job.id,
|
||||||
)
|
)
|
||||||
except Exception as unit_exc:
|
except Exception as unit_exc:
|
||||||
|
# [STEP] 先回滚再记录:推送失败时事务可能已中止(如死锁),直接写进度会抛
|
||||||
|
# PendingRollbackError 顶掉原始异常(2026-09-24 test job 8840)。回滚后在新
|
||||||
|
# 事务记录单元技术失败,再抛出原始异常交外层收口(瞬时锁错由其自动重排)。
|
||||||
|
db.session.rollback()
|
||||||
record_unit_progress(
|
record_unit_progress(
|
||||||
run=run,
|
run=run,
|
||||||
unit=unit,
|
unit=unit,
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ backend/app/jobs/handlers/shipping_process_gate.py
|
|||||||
次数耗尽时 fail_job 并 complete_gate_attempt(blocked_retryable),保留人工恢复入口;
|
次数耗尽时 fail_job 并 complete_gate_attempt(blocked_retryable),保留人工恢复入口;
|
||||||
不修改 input_snapshot_json,以保持 input_snapshot_hash 与正文一致;
|
不修改 input_snapshot_json,以保持 input_snapshot_hash 与正文一致;
|
||||||
waiting_external 先结束当前 Job 再延迟入队新 Job;
|
waiting_external 先结束当前 Job 再延迟入队新 Job;
|
||||||
|
external-wait 轮询异常时回滚并按 Gate 现状重排/安静结束,保证轮询链不因瞬时冲突断裂;
|
||||||
healthcheck_probe 载荷用于部署探针,不依赖真实 Attempt。
|
healthcheck_probe 载荷用于部署探针,不依赖真实 Attempt。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -88,7 +89,37 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None:
|
|||||||
if external_wait_poll_gate_id and job is not None:
|
if external_wait_poll_gate_id and job is not None:
|
||||||
from app.services.shipping_notice.process_gate_job_service import run_inventory_external_wait_poll
|
from app.services.shipping_notice.process_gate_job_service import run_inventory_external_wait_poll
|
||||||
|
|
||||||
result = run_inventory_external_wait_poll(gate_id=external_wait_poll_gate_id)
|
try:
|
||||||
|
result = run_inventory_external_wait_poll(gate_id=external_wait_poll_gate_id)
|
||||||
|
except Exception as exc:
|
||||||
|
# [STEP] 轮询与库存回调可能以相反顺序争抢 Gate 行与候选行(2026-09-23 test job 8818,
|
||||||
|
# 事务被毒化后以 InFailedSqlTransaction 收口,轮询链断裂导致 Gate 永久等待)。
|
||||||
|
# 回滚后按 Gate 现状分流:仍在等待外部 → 结束本 Job 并延迟重排,保持轮询链不断;
|
||||||
|
# Gate 已被回调等其他路径收口 → 安静结束。错误文本留在 result_json 供排查。
|
||||||
|
db.session.rollback()
|
||||||
|
gate = db.session.get(ShippingProcessGate, external_wait_poll_gate_id)
|
||||||
|
gate_status = str(getattr(gate, 'status', '') or '') if gate is not None else None
|
||||||
|
if gate_status == 'waiting_external':
|
||||||
|
poll = max(int(current_app.config.get('SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS', 30) or 30), 5)
|
||||||
|
finish_job(
|
||||||
|
job.id,
|
||||||
|
result={
|
||||||
|
'status': 'waiting_external_requeued',
|
||||||
|
'poll_error': sanitize_gate_error_text(exc, max_len=300),
|
||||||
|
},
|
||||||
|
owned_attempt=int(job.attempts or 0),
|
||||||
|
)
|
||||||
|
if gate is not None and gate.latest_attempt_id:
|
||||||
|
schedule_waiting_external_poll(attempt_id=int(gate.latest_attempt_id))
|
||||||
|
db.session.commit()
|
||||||
|
return
|
||||||
|
finish_job(
|
||||||
|
job.id,
|
||||||
|
result={'status': 'poll_superseded', 'gate_status': gate_status},
|
||||||
|
owned_attempt=int(job.attempts or 0),
|
||||||
|
)
|
||||||
|
db.session.commit()
|
||||||
|
return
|
||||||
finish_job(job.id, result=result, owned_attempt=int(job.attempts or 0))
|
finish_job(job.id, result=result, owned_attempt=int(job.attempts or 0))
|
||||||
if str(result.get('gate_status') or '') == 'waiting_external':
|
if str(result.get('gate_status') or '') == 'waiting_external':
|
||||||
gate = db.session.get(ShippingProcessGate, external_wait_poll_gate_id)
|
gate = db.session.get(ShippingProcessGate, external_wait_poll_gate_id)
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ backend/app/jobs/store.py
|
|||||||
|
|
||||||
用途:Job 认领与状态读写(KbJob 双轨 adapter + 通用 Job)。
|
用途:Job 认领与状态读写(KbJob 双轨 adapter + 通用 Job)。
|
||||||
依赖:KbJob、各域 queue_service 的 claim/recover 逻辑。
|
依赖:KbJob、各域 queue_service 的 claim/recover 逻辑。
|
||||||
逻辑:runner 通过 claim_next 获取 kb / shipping / contract / schedule 任务;返回归一化 dict 供 handler 分发。
|
逻辑:runner 通过 claim_next 获取 kb / shipping / contract / schedule / transfer 任务;返回归一化 dict 供 handler 分发。
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -56,7 +56,7 @@ def _normalize_kb_job(job: KbJob) -> dict[str, Any]:
|
|||||||
def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
|
def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
|
||||||
"""
|
"""
|
||||||
认领下一条待执行 Job(SELECT FOR UPDATE SKIP LOCKED,委托各域 queue_service)。
|
认领下一条待执行 Job(SELECT FOR UPDATE SKIP LOCKED,委托各域 queue_service)。
|
||||||
核心逻辑:按 queues 顺序依次尝试 kb / shipping / contract 队列;先 recover 卡死 running 任务。
|
核心逻辑:按 queues 顺序依次尝试 kb / shipping / contract / schedule / transfer 队列;先 recover 卡死 running 任务。
|
||||||
Args:
|
Args:
|
||||||
queues: worker 消费的队列名,如 ['kb'] 或 ['kb', 'shipping']。
|
queues: worker 消费的队列名,如 ['kb'] 或 ['kb', 'shipping']。
|
||||||
Returns:
|
Returns:
|
||||||
@@ -156,6 +156,22 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
|
|||||||
)
|
)
|
||||||
if job:
|
if job:
|
||||||
return _normalize_generic_job(job)
|
return _normalize_generic_job(job)
|
||||||
|
elif name == 'transfer':
|
||||||
|
# 在途调拨域:预检/票级执行/行级任务共用 domain="in_transit_transfer"
|
||||||
|
# (与 execution_service 入队口径一致);缺此分支时 transfer worker
|
||||||
|
# 会空轮询永远领不到任务,Run 卡在 queued。
|
||||||
|
from app.jobs.queue import claim_next_job
|
||||||
|
|
||||||
|
job = claim_next_job(
|
||||||
|
domain="in_transit_transfer",
|
||||||
|
job_types=[
|
||||||
|
JobType.TRANSFER_MATCH,
|
||||||
|
JobType.TRANSFER_RUN,
|
||||||
|
JobType.TRANSFER_ITEM,
|
||||||
|
],
|
||||||
|
)
|
||||||
|
if job:
|
||||||
|
return _normalize_generic_job(job)
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,9 @@ backend/app/jobs/types.py
|
|||||||
|
|
||||||
用途:Job 类型与状态枚举;KbJob.job_type 与 handler JobType 的双向映射。
|
用途:Job 类型与状态枚举;KbJob.job_type 与 handler JobType 的双向映射。
|
||||||
逻辑:handlers 与 queue 通过 JobType 注册;store 持久化仍走 KbJob 表(Wave 2 双轨);
|
逻辑:handlers 与 queue 通过 JobType 注册;store 持久化仍走 KbJob 表(Wave 2 双轨);
|
||||||
shipping_process_gate 由 shipping worker 与发货通知任务同队列领取。
|
shipping_process_gate 由 shipping worker 与发货通知任务同队列领取;
|
||||||
|
在手回调成员 FREIGHT_RPA_ONHAND_CALLBACK_PROCESS 的持久化值为
|
||||||
|
freight_rpa_onhand_callback_process。
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -20,8 +22,9 @@ class JobType(StrEnum):
|
|||||||
SHIPPING_ORDER_EXTRACTION = 'shipping_order_extraction'
|
SHIPPING_ORDER_EXTRACTION = 'shipping_order_extraction'
|
||||||
SHIPPING_DOCUMENT_LAYOUT = 'shipping_document_layout'
|
SHIPPING_DOCUMENT_LAYOUT = 'shipping_document_layout'
|
||||||
SHIPPING_PROCESS_GATE = 'shipping_process_gate'
|
SHIPPING_PROCESS_GATE = 'shipping_process_gate'
|
||||||
# RPA 回调 HTTP 只收件;Excel 校验、解析、任务关联由 shipping worker 异步完成。
|
# 在手 RPA 回调 HTTP 只收件;Excel 校验、解析、任务关联由 shipping worker 异步完成。
|
||||||
SHIPPING_INVENTORY_CALLBACK_PROCESS = 'shipping_inventory_callback_process'
|
# 持久化 jobs.job_type 为 freight_rpa_onhand_callback_process。
|
||||||
|
FREIGHT_RPA_ONHAND_CALLBACK_PROCESS = 'freight_rpa_onhand_callback_process'
|
||||||
# 统一 PDF 自动标记:按实际证据能力执行坐标重建或 XFA 多源视觉融合。
|
# 统一 PDF 自动标记:按实际证据能力执行坐标重建或 XFA 多源视觉融合。
|
||||||
SHIPPING_PDF_AUTOMARK = 'shipping_pdf_automark'
|
SHIPPING_PDF_AUTOMARK = 'shipping_pdf_automark'
|
||||||
# 资格达标后的 STP 自动建单入队(先 queued,再由 worker 执行 confirm)
|
# 资格达标后的 STP 自动建单入队(先 queued,再由 worker 执行 confirm)
|
||||||
@@ -39,8 +42,8 @@ class JobType(StrEnum):
|
|||||||
CONTRACT_PAYMENT_SYNC = 'contract_payment_sync'
|
CONTRACT_PAYMENT_SYNC = 'contract_payment_sync'
|
||||||
CONTRACT_PAYMENT_ALERT = 'contract_payment_alert'
|
CONTRACT_PAYMENT_ALERT = 'contract_payment_alert'
|
||||||
CONTRACT_PAYMENT_ALERT_WEEKLY = 'contract_payment_alert_weekly'
|
CONTRACT_PAYMENT_ALERT_WEEKLY = 'contract_payment_alert_weekly'
|
||||||
# 在途仓自动调拨:文件准备 + 只读预检(Phase 1);执行 Run/Item 在 Phase 2 注册。
|
# 在途仓自动调拨:文件准备 + 只读匹配(Phase 1);执行 Run/Item 在 Phase 2 注册。
|
||||||
TRANSFER_PRECHECK = 'in_transit_transfer_precheck'
|
TRANSFER_MATCH = 'in_transit_transfer_match'
|
||||||
TRANSFER_RUN = 'in_transit_transfer_run'
|
TRANSFER_RUN = 'in_transit_transfer_run'
|
||||||
TRANSFER_ITEM = 'in_transit_transfer_item'
|
TRANSFER_ITEM = 'in_transit_transfer_item'
|
||||||
|
|
||||||
@@ -76,14 +79,14 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
|
|||||||
'shipping': frozenset({
|
'shipping': frozenset({
|
||||||
'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction',
|
'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction',
|
||||||
'shipping_document_layout', 'shipping_process_gate', 'shipping_pdf_automark',
|
'shipping_document_layout', 'shipping_process_gate', 'shipping_pdf_automark',
|
||||||
'shipping_inventory_callback_process',
|
'freight_rpa_onhand_callback_process',
|
||||||
'shipping_stp_auto_create', 'shipping_line_auto_fulfill',
|
'shipping_stp_auto_create', 'shipping_line_auto_fulfill',
|
||||||
'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress',
|
'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress',
|
||||||
}),
|
}),
|
||||||
'contract': frozenset({'procurement_contract_review', 'contract_payment_sync', 'contract_payment_alert', 'contract_payment_alert_weekly'}),
|
'contract': frozenset({'procurement_contract_review', 'contract_payment_sync', 'contract_payment_alert', 'contract_payment_alert_weekly'}),
|
||||||
'schedule': frozenset({'schedule_run', 'file_check_run', 'wecom_directory_sync'}),
|
'schedule': frozenset({'schedule_run', 'file_check_run', 'wecom_directory_sync'}),
|
||||||
'transfer': frozenset({
|
'transfer': frozenset({
|
||||||
'in_transit_transfer_precheck', 'in_transit_transfer_run', 'in_transit_transfer_item',
|
'in_transit_transfer_match', 'in_transit_transfer_run', 'in_transit_transfer_item',
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+107
-62
@@ -2,12 +2,14 @@
|
|||||||
backend/app/models/__init__.py
|
backend/app/models/__init__.py
|
||||||
|
|
||||||
用途:按业务域拆分的 ORM 模型包入口;聚合导出以保持 `from app.models import User` 兼容。
|
用途:按业务域拆分的 ORM 模型包入口;聚合导出以保持 `from app.models import User` 兼容。
|
||||||
依赖:models/* 子模块(含 voucher_check)、app.extensions.db(经 base.Base)。
|
依赖:models/* 子模块(含 voucher_check、equipment_acceptance、freight_rpa_*)、app.extensions.db(经 base.Base)。
|
||||||
逻辑:Alembic / Flask-Migrate 通过本模块 import 注册全部表元数据;业务代码继续从此处导入模型类。
|
逻辑:Alembic / Flask-Migrate 通过本模块 import 注册全部表元数据;业务代码继续从此处导入模型类。
|
||||||
|
在手/入站/出站模型导出 FreightRpa*。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest
|
from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest
|
||||||
from app.models.base import Base, user_agent_permissions
|
from app.models.base import Base, user_agent_permissions
|
||||||
|
from app.models.permission_role import PermissionRole, permission_role_agents, user_permission_roles
|
||||||
from app.models.chat import ChatLog, ChatSession, ChatToolRun, Feedback, GeneralFeedback
|
from app.models.chat import ChatLog, ChatSession, ChatToolRun, Feedback, GeneralFeedback
|
||||||
from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlLanguage
|
from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlLanguage
|
||||||
from app.models.department import Department
|
from app.models.department import Department
|
||||||
@@ -30,15 +32,15 @@ from app.models.contract_payment import (
|
|||||||
ContractPaymentVendorRequest,
|
ContractPaymentVendorRequest,
|
||||||
)
|
)
|
||||||
from app.models.shipping import (
|
from app.models.shipping import (
|
||||||
ShippingInventoryFile,
|
|
||||||
ShippingNotice,
|
ShippingNotice,
|
||||||
ShippingOrderCandidate,
|
ShippingOrderCandidate,
|
||||||
ShippingOrderDocument,
|
ShippingOrderDocument,
|
||||||
ShippingOrderIntake,
|
ShippingOrderIntake,
|
||||||
ShippingTaskEvent,
|
ShippingTaskEvent,
|
||||||
ShippingTaskPurgeAudit,
|
ShippingTaskPurgeAudit,
|
||||||
ShippingTaskInventoryLink,
|
ShippingTaskOnhandLink,
|
||||||
)
|
)
|
||||||
|
from app.models.freight_rpa_onhand_report_file import FreightRpaOnhandReportFile
|
||||||
from app.models.shipping_order_submission import ShippingOrderSubmission
|
from app.models.shipping_order_submission import ShippingOrderSubmission
|
||||||
from app.models.shipping_order_task import ShippingOrderTask
|
from app.models.shipping_order_task import ShippingOrderTask
|
||||||
from app.models.shipping_order_candidate_evidence import ShippingOrderCandidateEvidence
|
from app.models.shipping_order_candidate_evidence import ShippingOrderCandidateEvidence
|
||||||
@@ -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_excel_template import ShippingExcelTemplate, ShippingExportArtifact
|
||||||
from app.models.shipping_fulfillment import (
|
from app.models.shipping_fulfillment import (
|
||||||
ShippingExportArtifactLine,
|
ShippingExportArtifactLine,
|
||||||
ShippingInventoryVerification,
|
ShippingOnhandVerification,
|
||||||
ShippingInventoryVerificationLine,
|
ShippingOnhandVerificationLine,
|
||||||
ShippingReservation,
|
ShippingReservation,
|
||||||
ShippingUploadAttempt,
|
ShippingUploadAttempt,
|
||||||
)
|
)
|
||||||
@@ -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_line_decision import ShippingOrderReviewLineDecision
|
||||||
from app.models.shipping_order_review_wave_line import ShippingOrderReviewWaveLine
|
from app.models.shipping_order_review_wave_line import ShippingOrderReviewWaveLine
|
||||||
from app.models.shipping_order_review_wave_idempotency import ShippingOrderReviewWaveIdempotency
|
from app.models.shipping_order_review_wave_idempotency import ShippingOrderReviewWaveIdempotency
|
||||||
from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch
|
from app.models.shipping_notice_line_onhand_match import ShippingNoticeLineOnhandMatch
|
||||||
from app.models.shipping_order_review_suggestion import ShippingOrderReviewSuggestion
|
from app.models.shipping_order_review_suggestion import ShippingOrderReviewSuggestion
|
||||||
from app.models.shipping_order_extraction_run import (
|
from app.models.shipping_order_extraction_run import (
|
||||||
ShippingOrderExtractionDiagnosticAudit,
|
ShippingOrderExtractionDiagnosticAudit,
|
||||||
@@ -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_eml_preview_snapshot import ShippingEmlPreviewSnapshot
|
||||||
from app.models.shipping_xfa_structure_analysis import ShippingXfaStructureAnalysis
|
from app.models.shipping_xfa_structure_analysis import ShippingXfaStructureAnalysis
|
||||||
from app.models.shipping_xfa_audit_snapshot import ShippingXfaAuditSnapshot
|
from app.models.shipping_xfa_audit_snapshot import ShippingXfaAuditSnapshot
|
||||||
from app.models.shipping_inventory_config import (
|
from app.models.freight_rpa_config import (
|
||||||
ShippingInventoryField,
|
FreightRpaOnhandField,
|
||||||
ShippingInventoryExternalMapping,
|
FreightRpaOnhandExternalMapping,
|
||||||
ShippingInventoryConfigurationTestRun,
|
FreightRpaOnhandConfigurationTestRun,
|
||||||
ShippingInventoryValidationBatch,
|
FreightRpaOnhandValidationBatch,
|
||||||
ShippingInventorySourceParsingBindingAudit,
|
FreightRpaSourceParsingBindingAudit,
|
||||||
ShippingInventoryParsingProfile,
|
FreightRpaParsingProfile,
|
||||||
ShippingInventoryRoutingRule,
|
FreightRpaOnhandRoutingRule,
|
||||||
ShippingInventoryRoutingRuleCondition,
|
FreightRpaOnhandRoutingRuleCondition,
|
||||||
ShippingInventoryRoutingRuleVersion,
|
FreightRpaOnhandRoutingRuleVersion,
|
||||||
ShippingInventorySource,
|
FreightRpaSource,
|
||||||
ShippingInventoryStructureAnalysis,
|
FreightRpaOnhandReportConfig,
|
||||||
ShippingRpaProfile,
|
FreightRpaOnhandStructureAnalysis,
|
||||||
|
FreightRpaProfile,
|
||||||
)
|
)
|
||||||
from app.models.shipping_receipt_report import (
|
from app.models.freight_rpa_inbound_report import (
|
||||||
ShippingReceiptNotificationDelivery,
|
FreightRpaInboundReportConfig,
|
||||||
ShippingReceiptReportConfig,
|
FreightRpaInboundReportFile,
|
||||||
ShippingReceiptReportFile,
|
FreightRpaInboundUnitRun,
|
||||||
ShippingReceiptRpaUnitRun,
|
|
||||||
)
|
)
|
||||||
from app.models.shipping_temporary_inventory import ShippingTemporaryInventorySession
|
from app.models.freight_rpa_outbound_report import (
|
||||||
|
FreightRpaOutboundReportConfig,
|
||||||
|
FreightRpaOutboundReportFile,
|
||||||
|
FreightRpaOutboundUnitRun,
|
||||||
|
)
|
||||||
|
from app.models.shipping_temporary_onhand import ShippingTemporaryOnhandSession
|
||||||
from app.models.shipping_customer import (
|
from app.models.shipping_customer import (
|
||||||
ShippingBusinessSequence,
|
ShippingBusinessSequence,
|
||||||
ShippingCustomer,
|
ShippingCustomer,
|
||||||
@@ -179,18 +186,18 @@ from app.models.shipping_identity_rule import (
|
|||||||
ShippingIdentityRuleAuditEvent,
|
ShippingIdentityRuleAuditEvent,
|
||||||
ShippingIdentityRuleSet,
|
ShippingIdentityRuleSet,
|
||||||
)
|
)
|
||||||
from app.models.shipping_inventory_candidates import (
|
from app.models.shipping_onhand_candidates import (
|
||||||
ShippingInventoryCandidateLine,
|
ShippingOnhandCandidateLine,
|
||||||
ShippingInventoryCandidateSet,
|
ShippingOnhandCandidateSet,
|
||||||
ShippingInventoryCandidateSource,
|
ShippingOnhandCandidateSource,
|
||||||
)
|
)
|
||||||
from app.models.shipping_task_inventory_rpa_attempts import ShippingTaskInventoryRpaAttempt
|
from app.models.freight_rpa_onhand_task_attempts import FreightRpaOnhandTaskAttempt
|
||||||
from app.models.shipping_process_recovery_plan import ShippingProcessRecoveryPlan
|
from app.models.shipping_process_recovery_plan import ShippingProcessRecoveryPlan
|
||||||
from app.models.shipping_inventory_preparation import (
|
from app.models.shipping_onhand_preparation import (
|
||||||
ShippingInventoryPreparationAttempt,
|
ShippingOnhandPreparationAttempt,
|
||||||
ShippingInventoryPreparationSourceAttempt,
|
ShippingOnhandPreparationSourceAttempt,
|
||||||
)
|
)
|
||||||
from app.models.shipping_inventory_mapping import ShippingInventoryMapping
|
from app.models.freight_rpa_onhand_mapping import FreightRpaOnhandMapping
|
||||||
from app.models.training import (
|
from app.models.training import (
|
||||||
LeanTrainingCompletion,
|
LeanTrainingCompletion,
|
||||||
LeanTrainingReminder,
|
LeanTrainingReminder,
|
||||||
@@ -204,10 +211,13 @@ from app.models.in_transit_transfer import (
|
|||||||
TransferArchive,
|
TransferArchive,
|
||||||
TransferAttempt,
|
TransferAttempt,
|
||||||
TransferAuditEvent,
|
TransferAuditEvent,
|
||||||
|
TransferDocument,
|
||||||
TransferInvoiceItem,
|
TransferInvoiceItem,
|
||||||
TransferPrecheck,
|
TransferMatching,
|
||||||
|
TransferMovementLedger,
|
||||||
TransferRun,
|
TransferRun,
|
||||||
TransferSourceJob,
|
TransferSourceJob,
|
||||||
|
TransferTypeConfig,
|
||||||
)
|
)
|
||||||
from app.models.integration_connector import (
|
from app.models.integration_connector import (
|
||||||
IntegrationBinding,
|
IntegrationBinding,
|
||||||
@@ -236,11 +246,29 @@ from app.models.contract_payment import (
|
|||||||
ContractPaymentSyncState,
|
ContractPaymentSyncState,
|
||||||
ContractPaymentVendorRequest,
|
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
|
from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
'Base',
|
'Base',
|
||||||
'user_agent_permissions',
|
'user_agent_permissions',
|
||||||
|
'permission_role_agents',
|
||||||
|
'user_permission_roles',
|
||||||
|
'PermissionRole',
|
||||||
'ZlLanguage',
|
'ZlLanguage',
|
||||||
'Department',
|
'Department',
|
||||||
'UserHomepageConfig',
|
'UserHomepageConfig',
|
||||||
@@ -298,7 +326,7 @@ __all__ = [
|
|||||||
'ShippingOrderReviewLineDecision',
|
'ShippingOrderReviewLineDecision',
|
||||||
'ShippingOrderReviewWaveLine',
|
'ShippingOrderReviewWaveLine',
|
||||||
'ShippingOrderReviewWaveIdempotency',
|
'ShippingOrderReviewWaveIdempotency',
|
||||||
'ShippingNoticeLineInventoryMatch',
|
'ShippingNoticeLineOnhandMatch',
|
||||||
'ShippingOrderReviewSuggestion',
|
'ShippingOrderReviewSuggestion',
|
||||||
'ShippingOrderProcessingRun',
|
'ShippingOrderProcessingRun',
|
||||||
'ShippingOrderProcessingRunIntake',
|
'ShippingOrderProcessingRunIntake',
|
||||||
@@ -347,30 +375,33 @@ __all__ = [
|
|||||||
'ShippingIdentityRuleAuditEvent',
|
'ShippingIdentityRuleAuditEvent',
|
||||||
'ShippingTaskEvent',
|
'ShippingTaskEvent',
|
||||||
'ShippingTaskPurgeAudit',
|
'ShippingTaskPurgeAudit',
|
||||||
'ShippingInventoryFile',
|
'FreightRpaOnhandReportFile',
|
||||||
'ShippingTaskInventoryLink',
|
'ShippingTaskOnhandLink',
|
||||||
'ShippingRpaProfile',
|
'FreightRpaProfile',
|
||||||
'ShippingInventorySource',
|
'FreightRpaSource',
|
||||||
'ShippingReceiptReportConfig',
|
'FreightRpaOnhandReportConfig',
|
||||||
'ShippingReceiptRpaUnitRun',
|
'FreightRpaInboundReportConfig',
|
||||||
'ShippingReceiptReportFile',
|
'FreightRpaInboundUnitRun',
|
||||||
'ShippingReceiptNotificationDelivery',
|
'FreightRpaInboundReportFile',
|
||||||
'ShippingInventoryField',
|
'FreightRpaOutboundReportConfig',
|
||||||
'ShippingInventoryStructureAnalysis',
|
'FreightRpaOutboundUnitRun',
|
||||||
'ShippingInventoryRoutingRule',
|
'FreightRpaOutboundReportFile',
|
||||||
'ShippingInventoryRoutingRuleCondition',
|
'FreightRpaOnhandField',
|
||||||
'ShippingInventoryRoutingRuleVersion',
|
'FreightRpaOnhandStructureAnalysis',
|
||||||
'ShippingInventoryExternalMapping',
|
'FreightRpaOnhandRoutingRule',
|
||||||
'ShippingInventoryConfigurationTestRun',
|
'FreightRpaOnhandRoutingRuleCondition',
|
||||||
'ShippingInventoryValidationBatch',
|
'FreightRpaOnhandRoutingRuleVersion',
|
||||||
'ShippingInventorySourceParsingBindingAudit',
|
'FreightRpaOnhandExternalMapping',
|
||||||
'ShippingInventoryParsingProfile',
|
'FreightRpaOnhandConfigurationTestRun',
|
||||||
'ShippingTemporaryInventorySession',
|
'FreightRpaOnhandValidationBatch',
|
||||||
|
'FreightRpaSourceParsingBindingAudit',
|
||||||
|
'FreightRpaParsingProfile',
|
||||||
|
'ShippingTemporaryOnhandSession',
|
||||||
'ShippingExcelTemplate',
|
'ShippingExcelTemplate',
|
||||||
'ShippingExportArtifact',
|
'ShippingExportArtifact',
|
||||||
'ShippingReservation',
|
'ShippingReservation',
|
||||||
'ShippingInventoryVerification',
|
'ShippingOnhandVerification',
|
||||||
'ShippingInventoryVerificationLine',
|
'ShippingOnhandVerificationLine',
|
||||||
'ShippingExportArtifactLine',
|
'ShippingExportArtifactLine',
|
||||||
'ShippingUploadAttempt',
|
'ShippingUploadAttempt',
|
||||||
'ShippingProcessExecution',
|
'ShippingProcessExecution',
|
||||||
@@ -405,10 +436,10 @@ __all__ = [
|
|||||||
'MaintenanceDevice',
|
'MaintenanceDevice',
|
||||||
'MaintenanceRecord',
|
'MaintenanceRecord',
|
||||||
'MaintenanceAuditLog',
|
'MaintenanceAuditLog',
|
||||||
'ShippingInventoryCandidateSet',
|
'ShippingOnhandCandidateSet',
|
||||||
'ShippingInventoryCandidateSource',
|
'ShippingOnhandCandidateSource',
|
||||||
'ShippingInventoryCandidateLine',
|
'ShippingOnhandCandidateLine',
|
||||||
'ShippingTaskInventoryRpaAttempt',
|
'FreightRpaOnhandTaskAttempt',
|
||||||
'VoucherCheckProfile',
|
'VoucherCheckProfile',
|
||||||
'VoucherCheckRun',
|
'VoucherCheckRun',
|
||||||
'VoucherCheckSubject',
|
'VoucherCheckSubject',
|
||||||
@@ -423,16 +454,30 @@ __all__ = [
|
|||||||
'ContractPaymentAlert',
|
'ContractPaymentAlert',
|
||||||
'ContractPaymentAlertBatch',
|
'ContractPaymentAlertBatch',
|
||||||
'ContractPaymentSyncState',
|
'ContractPaymentSyncState',
|
||||||
|
'EquipmentAcceptanceOrder',
|
||||||
|
'EquipmentAcceptanceNode',
|
||||||
|
'EquipmentAcceptanceOperator',
|
||||||
|
'EquipmentAcceptanceSetting',
|
||||||
|
'EquipmentAcceptanceSendFile',
|
||||||
|
'EquipmentAcceptanceSendRecord',
|
||||||
'TransferRun',
|
'TransferRun',
|
||||||
'TransferSourceJob',
|
'TransferSourceJob',
|
||||||
'TransferPrecheck',
|
'TransferMatching',
|
||||||
|
'TransferDocument',
|
||||||
'TransferInvoiceItem',
|
'TransferInvoiceItem',
|
||||||
'TransferAttempt',
|
'TransferAttempt',
|
||||||
'TransferAuditEvent',
|
'TransferAuditEvent',
|
||||||
'TransferArchive',
|
'TransferArchive',
|
||||||
|
'TransferTypeConfig',
|
||||||
|
'TransferMovementLedger',
|
||||||
'IntegrationCredentialReference',
|
'IntegrationCredentialReference',
|
||||||
'IntegrationClientInstance',
|
'IntegrationClientInstance',
|
||||||
'IntegrationInterfaceDefinition',
|
'IntegrationInterfaceDefinition',
|
||||||
'IntegrationBinding',
|
'IntegrationBinding',
|
||||||
'IntegrationCall',
|
'IntegrationCall',
|
||||||
|
'OrderDeliveryErpLine',
|
||||||
|
'OrderDeliveryBatch',
|
||||||
|
'OrderDeliveryLineState',
|
||||||
|
'OrderDeliveryAuditEvent',
|
||||||
|
'OrderDeliverySyncRun',
|
||||||
]
|
]
|
||||||
@@ -35,6 +35,7 @@ class QuickQuestion(Base):
|
|||||||
常用问题表
|
常用问题表
|
||||||
用途:存储全局/用户常用问题;全局条目(user_id 为空)可配置标准答案并启用 FAQ 缓存命中。
|
用途:存储全局/用户常用问题;全局条目(user_id 为空)可配置标准答案并启用 FAQ 缓存命中。
|
||||||
is_enabled 控制工作台首页快捷入口;cache_enabled 控制聊天是否跳过 Dify 直答,二者独立。
|
is_enabled 控制工作台首页快捷入口;cache_enabled 控制聊天是否跳过 Dify 直答,二者独立。
|
||||||
|
fuzzy_enabled / fuzzy_threshold 控制精确未命中后的模糊兜底直答(逐条目独立,阈值钳制在 0.5~1.0)。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__tablename__ = 'quick_questions'
|
__tablename__ = 'quick_questions'
|
||||||
@@ -48,6 +49,8 @@ class QuickQuestion(Base):
|
|||||||
aliases: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
aliases: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||||
cache_enabled: Mapped[bool] = mapped_column(default=False)
|
cache_enabled: Mapped[bool] = mapped_column(default=False)
|
||||||
is_enabled: Mapped[bool] = mapped_column(default=True)
|
is_enabled: Mapped[bool] = mapped_column(default=True)
|
||||||
|
fuzzy_enabled: Mapped[bool] = mapped_column(default=False)
|
||||||
|
fuzzy_threshold: Mapped[float] = mapped_column(default=0.80)
|
||||||
hit_count: Mapped[int] = mapped_column(default=0)
|
hit_count: Mapped[int] = mapped_column(default=0)
|
||||||
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||||
source_kb_document_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
source_kb_document_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||||
|
|||||||
@@ -33,6 +33,8 @@ class ContractPaymentContract(Base):
|
|||||||
contract_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
contract_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||||
purchase_order_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
purchase_order_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||||
supplier_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
supplier_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||||
|
# OA 合同申请单「公司」。付款事实按该公司映射到 ERP 账套,空值按 HXJM 处理。
|
||||||
|
company_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||||
applicant_name: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
applicant_name: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||||
total_amount: Mapped[Optional[Decimal]] = mapped_column(Numeric(18, 2), nullable=True)
|
total_amount: Mapped[Optional[Decimal]] = mapped_column(Numeric(18, 2), nullable=True)
|
||||||
currency: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
currency: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||||||
|
|||||||
@@ -0,0 +1,197 @@
|
|||||||
|
"""
|
||||||
|
backend/app/models/equipment_acceptance.py
|
||||||
|
|
||||||
|
用途:设备验收预警的本地同步快照和可改配置。
|
||||||
|
依赖:models.base.Base、users。
|
||||||
|
逻辑:同步服务按来源 oa_system 加流程实例 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("oa_system", "request_id", name="uq_equipment_acceptance_orders_oa_request"),
|
||||||
|
Index("ix_equipment_acceptance_orders_status", "monitor_status"),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
oa_system: Mapped[str] = mapped_column(String(8), nullable=False, default="e10")
|
||||||
|
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)
|
||||||
|
flow_no: Mapped[Optional[str]] = mapped_column(
|
||||||
|
String(1000),
|
||||||
|
nullable=True,
|
||||||
|
comment="流程编号。E10 取 wfc_requestbase.requestmark,E8 取 formtable_main_324.lcbh。",
|
||||||
|
)
|
||||||
|
request_title: Mapped[Optional[str]] = mapped_column(
|
||||||
|
String(1000),
|
||||||
|
nullable=True,
|
||||||
|
comment="流程标题。两边都取流程表 requestname。E10 这一列是流程默认标题。",
|
||||||
|
)
|
||||||
|
request_created_at: Mapped[Optional[datetime]] = mapped_column(
|
||||||
|
DateTime,
|
||||||
|
nullable=True,
|
||||||
|
comment="流程创建时间。E10 取 wfc_requestbase.createdatetime。E8 取 createdate 加 createtime。不用 E10 的 create_time。",
|
||||||
|
)
|
||||||
|
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、通用路由规则及外部系统仓库映射主数据。
|
用途:定义货代库存源、RPA Profile、在手/入站/出站报表配置、通用路由规则及外部系统仓库映射主数据。
|
||||||
依赖:models.base.Base、SQLAlchemy ORM;凭据密文由 shipping_notice.credential_crypto 读写。
|
依赖:models.base.Base、SQLAlchemy ORM;凭据密文由 freight_rpa.common.credential_crypto 读写。
|
||||||
逻辑:库存运行链路以 ShippingInventorySource.source_code 为业务主键;RPA Profile 仅提供登录连接配置,
|
逻辑:库存运行链路以 FreightRpaSource.source_code 为业务主键;RPA Profile 仅提供登录连接配置;
|
||||||
|
在手报表路径/查询条件/解析方案绑定自 s18 起归 FreightRpaOnhandReportConfig(站点行不再存这三列),
|
||||||
|
入站/出站配置分别挂 inbound_report_config / outbound_report_config 一对一关系;
|
||||||
外部系统映射仅供后端内部复用,不承载调拨决策。
|
外部系统映射仅供后端内部复用,不承载调拨决策。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -18,18 +20,18 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship
|
|||||||
from app.models.base import Base
|
from app.models.base import Base
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryField(Base):
|
class FreightRpaOnhandField(Base):
|
||||||
"""用户维护的库存业务字段目录;程序仅依据字段 ID 和业务用途运行。"""
|
"""用户维护的库存业务字段目录;程序仅依据字段 ID 和业务用途运行。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_fields'
|
__tablename__ = 'freight_rpa_onhand_fields'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint('field_code', name='uq_shipping_inventory_fields_code'),
|
UniqueConstraint('field_code', name='uq_freight_rpa_onhand_fields_code'),
|
||||||
UniqueConstraint('display_name', name='uq_shipping_inventory_fields_display_name'),
|
UniqueConstraint('display_name', name='uq_freight_rpa_onhand_fields_display_name'),
|
||||||
CheckConstraint("status IN ('active', 'retired')", name='ck_shipping_inventory_fields_status'),
|
CheckConstraint("status IN ('active', 'retired')", name='ck_freight_rpa_onhand_fields_status'),
|
||||||
CheckConstraint("value_type IN ('text', 'integer', 'decimal', 'date')", name='ck_shipping_inventory_fields_value_type'),
|
CheckConstraint("value_type IN ('text', 'integer', 'decimal', 'date')", name='ck_freight_rpa_onhand_fields_value_type'),
|
||||||
CheckConstraint(
|
CheckConstraint(
|
||||||
"usage_type IN ('match_identity', 'inventory_quantity', 'warehouse_identity', 'general')",
|
"usage_type IN ('match_identity', 'inventory_quantity', 'warehouse_identity', 'general')",
|
||||||
name='ck_shipping_inventory_fields_usage_type',
|
name='ck_freight_rpa_onhand_fields_usage_type',
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -48,13 +50,13 @@ class ShippingInventoryField(Base):
|
|||||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
class ShippingRpaProfile(Base):
|
class FreightRpaProfile(Base):
|
||||||
"""货代库存登录连接配置;凭据字段始终保存密文。"""
|
"""货代库存登录连接配置;凭据字段始终保存密文。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_rpa_profiles'
|
__tablename__ = 'freight_rpa_profiles'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint('profile_code', name='uq_shipping_rpa_profiles_profile_code'),
|
UniqueConstraint('profile_code', name='uq_freight_rpa_profiles_profile_code'),
|
||||||
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_shipping_rpa_profiles_connector_type'),
|
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_freight_rpa_profiles_connector_type'),
|
||||||
)
|
)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
@@ -67,11 +69,9 @@ class ShippingRpaProfile(Base):
|
|||||||
login_config_json: Mapped[dict[str, Any]] = mapped_column(
|
login_config_json: Mapped[dict[str, Any]] = mapped_column(
|
||||||
JSON, default=lambda: {'auth_mode': 'password'}, nullable=False,
|
JSON, default=lambda: {'auth_mode': 'password'}, nullable=False,
|
||||||
)
|
)
|
||||||
# 连接级“发货 Excel 自动上传”配置。先使用 login_url 登录,再访问 upload_config_json.entry_url 进入上传页;
|
# 连接级“发货 Excel 自动上传”开关。只保存 {enabled}。
|
||||||
# 上传配置由管理端表单编辑,后端白名单校验后保存为受限 JSON。白名单字段仅
|
# 上传页、文件控件、提交和成功判断在连接器代码里,由 login_url 的主机拼出入口。
|
||||||
# enabled / entry_url / file_input_selector / submit_mode / submit_selector /
|
# 该配置变更不递增 config_version(见 admin 服务)。
|
||||||
# result_mode / result_selector / success_texts / timeout_seconds。
|
|
||||||
# 一条连接只保存一份上传配置;该配置变更不递增 config_version(见 admin 服务)。
|
|
||||||
upload_config_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
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)
|
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
|
||||||
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||||
@@ -81,24 +81,24 @@ class ShippingRpaProfile(Base):
|
|||||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='rpa_profile')
|
sources: Mapped[list['FreightRpaSource']] = relationship(back_populates='rpa_profile')
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventorySource(Base):
|
class FreightRpaSource(Base):
|
||||||
"""库存业务来源;固定仓或库存行动态解析 Warehouse。"""
|
"""库存业务来源;固定仓或库存行动态解析 Warehouse。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_sources'
|
__tablename__ = 'freight_rpa_sources'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint('source_code', name='uq_shipping_inventory_sources_source_code'),
|
UniqueConstraint('source_code', name='uq_freight_rpa_sources_source_code'),
|
||||||
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_shipping_inventory_sources_connector_type'),
|
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_freight_rpa_sources_connector_type'),
|
||||||
CheckConstraint(
|
CheckConstraint(
|
||||||
"(warehouse_resolution_mode = 'fixed' AND fixed_warehouse_id IS NOT NULL) "
|
"(warehouse_resolution_mode = 'fixed' AND fixed_warehouse_id IS NOT NULL) "
|
||||||
"OR (warehouse_resolution_mode = 'inventory_match' AND fixed_warehouse_id IS NULL)",
|
"OR (warehouse_resolution_mode = 'inventory_match' AND fixed_warehouse_id IS NULL)",
|
||||||
name='ck_shipping_inventory_sources_warehouse_mode',
|
name='ck_freight_rpa_sources_warehouse_mode',
|
||||||
),
|
),
|
||||||
CheckConstraint(
|
CheckConstraint(
|
||||||
"enabled = false OR (parsing_profile_id IS NOT NULL AND excel_template_id IS NOT NULL)",
|
"enabled = false OR excel_template_id IS NOT NULL",
|
||||||
name='ck_shipping_inventory_sources_enabled_bindings',
|
name='ck_freight_rpa_sources_enabled_template',
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -106,14 +106,12 @@ class ShippingInventorySource(Base):
|
|||||||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
connector_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
connector_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||||
rpa_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_rpa_profiles.id'), nullable=False, index=True)
|
rpa_profile_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_profiles.id'), nullable=False, index=True)
|
||||||
parsing_profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True)
|
|
||||||
excel_template_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=True, index=True)
|
excel_template_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=True, index=True)
|
||||||
warehouse_resolution_mode: Mapped[str] = mapped_column(String(32), nullable=False)
|
warehouse_resolution_mode: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||||
fixed_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
fixed_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
# 业务报表定义属于 Source;Driver 的 selector、等待与下载实现不进入数据库配置。
|
# 业务报表定义自 s18 起搬到 FreightRpaOnhandReportConfig(路径、查询条件、解析方案绑定);
|
||||||
report_path_json: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict, server_default=text("'{}'"), nullable=False)
|
# CHECK 不能跨表,模板绑定仍留在站点行的启用约束上,解析方案存在性由保存站点的服务校验。
|
||||||
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, default=list, server_default=text("'[]'"), nullable=False)
|
|
||||||
snapshot_ttl_seconds: Mapped[int] = mapped_column(Integer, default=86400, server_default=text('86400'), nullable=False)
|
snapshot_ttl_seconds: Mapped[int] = mapped_column(Integer, default=86400, server_default=text('86400'), nullable=False)
|
||||||
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
|
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
|
||||||
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||||
@@ -122,31 +120,75 @@ class ShippingInventorySource(Base):
|
|||||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
rpa_profile: Mapped[ShippingRpaProfile] = relationship(back_populates='sources')
|
rpa_profile: Mapped[FreightRpaProfile] = relationship(back_populates='sources')
|
||||||
parsing_profile: Mapped[Optional['ShippingInventoryParsingProfile']] = relationship(back_populates='sources')
|
|
||||||
excel_template: Mapped[Optional['ShippingExcelTemplate']] = relationship(back_populates='sources')
|
excel_template: Mapped[Optional['ShippingExcelTemplate']] = relationship(back_populates='sources')
|
||||||
external_mappings: Mapped[list['ShippingInventoryExternalMapping']] = relationship(
|
onhand_report_config: Mapped[Optional['FreightRpaOnhandReportConfig']] = relationship(
|
||||||
back_populates='inventory_source', cascade='all, delete-orphan'
|
back_populates='source', uselist=False, cascade='all, delete-orphan',
|
||||||
)
|
)
|
||||||
receipt_report_config: Mapped[Optional['ShippingReceiptReportConfig']] = relationship(
|
external_mappings: Mapped[list['FreightRpaOnhandExternalMapping']] = relationship(
|
||||||
back_populates='inventory_source', uselist=False, cascade='all, delete-orphan',
|
back_populates='source', cascade='all, delete-orphan'
|
||||||
|
)
|
||||||
|
inbound_report_config: Mapped[Optional['FreightRpaInboundReportConfig']] = relationship(
|
||||||
|
back_populates='source', uselist=False, cascade='all, delete-orphan',
|
||||||
|
)
|
||||||
|
outbound_report_config: Mapped[Optional['FreightRpaOutboundReportConfig']] = relationship(
|
||||||
|
back_populates='source', uselist=False, cascade='all, delete-orphan',
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventorySourceParsingBindingAudit(Base):
|
class FreightRpaOnhandReportConfig(Base):
|
||||||
"""库存站点解析方案绑定的只追加审计;保存绑定前后快照以支持上线追溯。"""
|
"""库存站点的一对一在手报表配置;报表路径与查询条件归 RPA 域。
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_source_parsing_binding_audits'
|
解析方案绑定随本表保存(purpose='onhand')。站点启用要求「本配置存在且
|
||||||
|
parsing_profile_id 非空」,PostgreSQL CHECK 不能跨表,该校验由保存站点的服务执行。
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = 'freight_rpa_onhand_report_configs'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
Index('ix_inventory_source_parsing_binding_audit_source_created', 'inventory_source_id', 'created_at'),
|
UniqueConstraint('source_id', name='uq_freight_rpa_onhand_report_configs_source'),
|
||||||
)
|
)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False)
|
# 站点删除时配置行级联删除(与迁移端 fk_freight_rpa_onhand_report_configs_source 的 ondelete 一致)。
|
||||||
previous_parsing_profile_id: Mapped[Optional[int]] = mapped_column(
|
source_id: Mapped[int] = mapped_column(
|
||||||
ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True,
|
ForeignKey('freight_rpa_sources.id', ondelete='CASCADE'), nullable=False, index=True,
|
||||||
)
|
)
|
||||||
parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=False)
|
# 在手报表文件解析规则(purpose='onhand');空则站点不得启用(服务层校验)。
|
||||||
|
parsing_profile_id: Mapped[Optional[int]] = mapped_column(
|
||||||
|
ForeignKey('freight_rpa_parsing_profiles.id'), nullable=True, index=True,
|
||||||
|
)
|
||||||
|
# 业务报表定义属于配置行;Driver 的 selector、等待与下载实现不进入数据库配置。
|
||||||
|
report_path_json: Mapped[dict[str, Any]] = mapped_column(
|
||||||
|
JSON, default=dict, server_default=text("'{}'"), nullable=False,
|
||||||
|
)
|
||||||
|
# 与入站同构:查询条件原样下发 Worker;空条件表示页面默认。
|
||||||
|
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(
|
||||||
|
JSON, default=list, server_default=text("'[]'"), nullable=False,
|
||||||
|
)
|
||||||
|
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||||
|
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||||
|
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
source: Mapped['FreightRpaSource'] = relationship(back_populates='onhand_report_config')
|
||||||
|
parsing_profile: Mapped[Optional['FreightRpaParsingProfile']] = relationship(back_populates='sources')
|
||||||
|
|
||||||
|
|
||||||
|
class FreightRpaSourceParsingBindingAudit(Base):
|
||||||
|
"""库存站点解析方案绑定的只追加审计;保存绑定前后快照以支持上线追溯。"""
|
||||||
|
|
||||||
|
__tablename__ = 'freight_rpa_onhand_source_parsing_binding_audits'
|
||||||
|
__table_args__ = (
|
||||||
|
Index('ix_inventory_source_parsing_binding_audit_source_created', 'source_id', 'created_at'),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False)
|
||||||
|
previous_parsing_profile_id: Mapped[Optional[int]] = mapped_column(
|
||||||
|
ForeignKey('freight_rpa_parsing_profiles.id'), nullable=True,
|
||||||
|
)
|
||||||
|
parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_parsing_profiles.id'), nullable=False)
|
||||||
operation: Mapped[str] = mapped_column(String(32), nullable=False)
|
operation: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||||
reason: Mapped[str] = mapped_column(String(500), nullable=False)
|
reason: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||||
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||||
@@ -157,31 +199,32 @@ class ShippingInventorySourceParsingBindingAudit(Base):
|
|||||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryParsingProfile(Base):
|
class FreightRpaParsingProfile(Base):
|
||||||
"""可跨源复用的通用文件解析规则(库存/异动按 purpose 区分)。
|
"""可跨源复用的通用文件解析规则(在手/入站/出站按 purpose 区分)。
|
||||||
|
|
||||||
注意:表名中的 inventory 是历史命名——本表实为"通用文件解析规则表",
|
表 freight_rpa_parsing_profiles 按 purpose 服务在手/入站/出站。
|
||||||
用途以 purpose 字段为准,勿按表名推断只服务库存。
|
purpose='onhand':在手库存文件,端点用 FreightRpaOnhandField 库存字段目录;
|
||||||
purpose='inventory':端点用 ShippingInventoryField 库存字段目录(既有语义);
|
purpose='inbound':入站文件,端点用定死领域字段
|
||||||
purpose='movement':端点用定死领域字段(MOVEMENT_FIELDS,doc_no/line_no/.../movement_date),
|
(MOVEMENT_FIELDS,doc_no/line_no/.../movement_date),
|
||||||
供收料/异动文件映射,不依赖库存字段目录。校验逻辑按 purpose 分支。
|
不依赖库存字段目录。校验逻辑按 purpose 分支。
|
||||||
绑定入口:库存站点 ShippingInventorySource.parsing_profile_id /
|
绑定入口:在手配置 FreightRpaOnhandReportConfig.parsing_profile_id /
|
||||||
收料配置 ShippingReceiptReportConfig.parsing_profile_id(后者必须 purpose='movement')。
|
入站配置 FreightRpaInboundReportConfig.parsing_profile_id(后者必须 purpose='inbound');
|
||||||
|
purpose='outbound':出站文件,结构就位(白名单放行,暂无运行时消费方)。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_parsing_profiles'
|
__tablename__ = 'freight_rpa_parsing_profiles'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint('profile_code', 'version', name='uq_inventory_parsing_profiles_code_version'),
|
UniqueConstraint('profile_code', 'version', name='uq_inventory_parsing_profiles_code_version'),
|
||||||
Index('ix_inv_parse_profile_exact_fp', 'exact_structure_fingerprint'),
|
Index('ix_inv_parse_profile_exact_fp', 'exact_structure_fingerprint'),
|
||||||
Index('ix_inv_parse_profile_compat_fp', 'compatibility_fingerprint'),
|
Index('ix_inv_parse_profile_compat_fp', 'compatibility_fingerprint'),
|
||||||
CheckConstraint(
|
CheckConstraint(
|
||||||
"purpose IN ('inventory', 'movement')",
|
"purpose IN ('onhand', 'inbound', 'outbound')",
|
||||||
name='ck_shipping_inventory_parsing_profiles_purpose',
|
name='ck_freight_rpa_parsing_profiles_purpose',
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
purpose: Mapped[str] = mapped_column(String(16), nullable=False, default='inventory', server_default='inventory')
|
purpose: Mapped[str] = mapped_column(String(16), nullable=False, default='onhand', server_default='onhand')
|
||||||
profile_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
profile_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
|
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
|
||||||
@@ -195,7 +238,7 @@ class ShippingInventoryParsingProfile(Base):
|
|||||||
fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||||
# Draft and published definitions keep their analysed sample evidence without retaining the full uploaded workbook.
|
# Draft and published definitions keep their analysed sample evidence without retaining the full uploaded workbook.
|
||||||
sample_analysis_id: Mapped[Optional[int]] = mapped_column(
|
sample_analysis_id: Mapped[Optional[int]] = mapped_column(
|
||||||
ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True, index=True,
|
ForeignKey('freight_rpa_onhand_structure_analyses.id'), nullable=True, index=True,
|
||||||
)
|
)
|
||||||
# Preserve every confirmed evidence switch so a draft remains explainable after samples change.
|
# Preserve every confirmed evidence switch so a draft remains explainable after samples change.
|
||||||
sample_evidence_history_json: Mapped[list[dict[str, Any]]] = mapped_column(
|
sample_evidence_history_json: Mapped[list[dict[str, Any]]] = mapped_column(
|
||||||
@@ -206,16 +249,17 @@ class ShippingInventoryParsingProfile(Base):
|
|||||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
|
||||||
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='parsing_profile')
|
# s18 起站点行不再绑定解析方案;在手配置行(FreightRpaOnhandReportConfig)是 onhand 侧的唯一挂点。
|
||||||
sample_analysis: Mapped[Optional['ShippingInventoryStructureAnalysis']] = relationship(
|
sources: Mapped[list['FreightRpaOnhandReportConfig']] = relationship(back_populates='parsing_profile')
|
||||||
|
sample_analysis: Mapped[Optional['FreightRpaOnhandStructureAnalysis']] = relationship(
|
||||||
foreign_keys=[sample_analysis_id],
|
foreign_keys=[sample_analysis_id],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryStructureAnalysis(Base):
|
class FreightRpaOnhandStructureAnalysis(Base):
|
||||||
"""库存文件结构分析记录;保存脱敏结构证据,不承载正式库存快照。"""
|
"""库存文件结构分析记录;保存脱敏结构证据,不承载正式库存快照。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_structure_analyses'
|
__tablename__ = 'freight_rpa_onhand_structure_analyses'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
Index('ix_inv_structure_analysis_file_hash', 'file_checksum'),
|
Index('ix_inv_structure_analysis_file_hash', 'file_checksum'),
|
||||||
Index('ix_inv_structure_analysis_created', 'created_at'),
|
Index('ix_inv_structure_analysis_created', 'created_at'),
|
||||||
@@ -243,24 +287,28 @@ class ShippingInventoryStructureAnalysis(Base):
|
|||||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryConfigurationTestRun(Base):
|
class FreightRpaOnhandConfigurationTestRun(Base):
|
||||||
"""库存站点配置测试的异步 RPA 运行;锁定站点和连接配置版本且不进入生产库存池。"""
|
"""库存站点配置测试的异步 RPA 运行;锁定站点和连接配置版本且不进入生产库存池。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_configuration_test_runs'
|
__tablename__ = 'freight_rpa_onhand_configuration_test_runs'
|
||||||
__table_args__ = (UniqueConstraint('run_no', name='uq_inventory_configuration_test_runs_run_no'),)
|
__table_args__ = (
|
||||||
|
UniqueConstraint('run_no', name='uq_inventory_configuration_test_runs_run_no'),
|
||||||
|
# PostgreSQL 标识符上限 63。index=True 会生成 65 字节的自动名,故用显式短名。
|
||||||
|
Index('ix_fr_onhand_cfg_test_runs_validation_batch_id', 'validation_batch_id'),
|
||||||
|
)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
validation_batch_id: Mapped[Optional[int]] = mapped_column(
|
validation_batch_id: Mapped[Optional[int]] = mapped_column(
|
||||||
ForeignKey('shipping_inventory_validation_batches.id'), nullable=True, index=True,
|
ForeignKey('freight_rpa_onhand_validation_batches.id'), nullable=True,
|
||||||
)
|
)
|
||||||
rpa_batch_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
rpa_batch_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||||
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True)
|
source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False, index=True)
|
||||||
source_config_version: Mapped[int] = mapped_column(Integer, nullable=False)
|
source_config_version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
rpa_profile_config_version: Mapped[int] = mapped_column(Integer, nullable=False)
|
rpa_profile_config_version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='awaiting_rpa', server_default='awaiting_rpa')
|
status: Mapped[str] = mapped_column(String(32), nullable=False, default='awaiting_rpa', server_default='awaiting_rpa')
|
||||||
stage: Mapped[str] = mapped_column(String(32), nullable=False, default='waiting_worker', server_default='waiting_worker')
|
stage: Mapped[str] = mapped_column(String(32), nullable=False, default='waiting_worker', server_default='waiting_worker')
|
||||||
analysis_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True)
|
analysis_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_structure_analyses.id'), nullable=True)
|
||||||
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||||
@@ -268,10 +316,10 @@ class ShippingInventoryConfigurationTestRun(Base):
|
|||||||
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryValidationBatch(Base):
|
class FreightRpaOnhandValidationBatch(Base):
|
||||||
"""库存站点批量验证的聚合运行;逐站点结果仍由 ConfigurationTestRun 保存。"""
|
"""库存站点批量验证的聚合运行;逐站点结果仍由 ConfigurationTestRun 保存。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_validation_batches'
|
__tablename__ = 'freight_rpa_onhand_validation_batches'
|
||||||
__table_args__ = (UniqueConstraint('batch_no', name='uq_inventory_validation_batches_batch_no'),)
|
__table_args__ = (UniqueConstraint('batch_no', name='uq_inventory_validation_batches_batch_no'),)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
@@ -284,21 +332,21 @@ class ShippingInventoryValidationBatch(Base):
|
|||||||
stale_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
|
stale_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
|
||||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||||
retry_of_batch_id: Mapped[Optional[int]] = mapped_column(
|
retry_of_batch_id: Mapped[Optional[int]] = mapped_column(
|
||||||
ForeignKey('shipping_inventory_validation_batches.id'), nullable=True,
|
ForeignKey('freight_rpa_onhand_validation_batches.id'), nullable=True,
|
||||||
)
|
)
|
||||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryRoutingRule(Base):
|
class FreightRpaOnhandRoutingRule(Base):
|
||||||
"""可版本化的库存源路由决策表;仅产出受控 Source 候选。"""
|
"""可版本化的库存源路由决策表;仅产出受控 Source 候选。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_routing_rules'
|
__tablename__ = 'freight_rpa_onhand_routing_rules'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint('rule_code', 'version', name='uq_shipping_inventory_routing_rules_code_version'),
|
UniqueConstraint('rule_code', 'version', name='uq_freight_rpa_onhand_routing_rules_code_version'),
|
||||||
CheckConstraint("scope IN ('task', 'line')", name='ck_shipping_inventory_routing_rules_scope'),
|
CheckConstraint("scope IN ('task', 'line')", name='ck_freight_rpa_onhand_routing_rules_scope'),
|
||||||
CheckConstraint("match_mode IN ('all', 'any')", name='ck_shipping_inventory_routing_rules_match_mode'),
|
CheckConstraint("match_mode IN ('all', 'any')", name='ck_freight_rpa_onhand_routing_rules_match_mode'),
|
||||||
CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_inventory_routing_rules_status'),
|
CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_freight_rpa_onhand_routing_rules_status'),
|
||||||
)
|
)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
@@ -318,17 +366,17 @@ class ShippingInventoryRoutingRule(Base):
|
|||||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
conditions: Mapped[list['ShippingInventoryRoutingRuleCondition']] = relationship(
|
conditions: Mapped[list['FreightRpaOnhandRoutingRuleCondition']] = relationship(
|
||||||
back_populates='rule', cascade='all, delete-orphan', order_by='ShippingInventoryRoutingRuleCondition.sequence'
|
back_populates='rule', cascade='all, delete-orphan', order_by='FreightRpaOnhandRoutingRuleCondition.sequence'
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryRoutingRuleCondition(Base):
|
class FreightRpaOnhandRoutingRuleCondition(Base):
|
||||||
"""库存源路由条件;仅引用已发布订单 Schema 的稳定 field_id。"""
|
"""库存源路由条件;仅引用已发布订单 Schema 的稳定 field_id。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_routing_rule_conditions'
|
__tablename__ = 'freight_rpa_onhand_routing_rule_conditions'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint('rule_id', 'sequence', name='uq_shipping_inventory_routing_rule_conditions_sequence'),
|
UniqueConstraint('rule_id', 'sequence', name='uq_freight_rpa_onhand_routing_rule_conditions_sequence'),
|
||||||
CheckConstraint(
|
CheckConstraint(
|
||||||
"source_kind = 'order_field' AND order_field_id IS NOT NULL",
|
"source_kind = 'order_field' AND order_field_id IS NOT NULL",
|
||||||
name='ck_inventory_routing_condition_source',
|
name='ck_inventory_routing_condition_source',
|
||||||
@@ -336,7 +384,7 @@ class ShippingInventoryRoutingRuleCondition(Base):
|
|||||||
)
|
)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
rule_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_routing_rules.id'), nullable=False, index=True)
|
rule_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_routing_rules.id'), nullable=False, index=True)
|
||||||
condition_group: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
condition_group: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||||
source_kind: Mapped[str] = mapped_column(String(16), nullable=False, default='order_field')
|
source_kind: Mapped[str] = mapped_column(String(16), nullable=False, default='order_field')
|
||||||
order_field_id: Mapped[Optional[str]] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=True)
|
order_field_id: Mapped[Optional[str]] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=True)
|
||||||
@@ -344,24 +392,24 @@ class ShippingInventoryRoutingRuleCondition(Base):
|
|||||||
expected_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
|
expected_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
|
||||||
sequence: Mapped[int] = mapped_column(Integer, nullable=False)
|
sequence: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
|
|
||||||
rule: Mapped[ShippingInventoryRoutingRule] = relationship(back_populates='conditions')
|
rule: Mapped[FreightRpaOnhandRoutingRule] = relationship(back_populates='conditions')
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryRoutingRuleVersion(Base):
|
class FreightRpaOnhandRoutingRuleVersion(Base):
|
||||||
"""已发布路由规则的不可变定义快照,供任务审计回放使用。"""
|
"""已发布路由规则的不可变定义快照,供任务审计回放使用。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_routing_rule_versions'
|
__tablename__ = 'freight_rpa_onhand_routing_rule_versions'
|
||||||
__table_args__ = (UniqueConstraint('rule_id', 'version', name='uq_shipping_inventory_routing_rule_versions_rule_version'),)
|
__table_args__ = (UniqueConstraint('rule_id', 'version', name='uq_freight_rpa_onhand_routing_rule_versions_rule_version'),)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
rule_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_routing_rules.id'), nullable=False, index=True)
|
rule_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_routing_rules.id'), nullable=False, index=True)
|
||||||
version: Mapped[int] = mapped_column(Integer, nullable=False)
|
version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False)
|
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False)
|
||||||
published_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
published_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||||
published_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
published_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryExternalMapping(Base):
|
class FreightRpaOnhandExternalMapping(Base):
|
||||||
"""库存源到外部系统仓库的映射。
|
"""库存源到外部系统仓库的映射。
|
||||||
|
|
||||||
freight_warehouse_id(货代仓库)为可选维度:inventory_match 源用它匹配收料文件
|
freight_warehouse_id(货代仓库)为可选维度:inventory_match 源用它匹配收料文件
|
||||||
@@ -371,18 +419,18 @@ class ShippingInventoryExternalMapping(Base):
|
|||||||
(in_transit_transfer DefaultRouteResolver),保存端必填,库内空串仅为存量行兼容。
|
(in_transit_transfer DefaultRouteResolver),保存端必填,库内空串仅为存量行兼容。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_external_mappings'
|
__tablename__ = 'freight_rpa_onhand_external_mappings'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
Index(
|
Index(
|
||||||
'uq_shipping_inv_ext_map_src_default_enabled',
|
'uq_shipping_inv_ext_map_src_default_enabled',
|
||||||
'inventory_source_id',
|
'source_id',
|
||||||
unique=True,
|
unique=True,
|
||||||
postgresql_where=text('freight_warehouse_id IS NULL AND enabled = true'),
|
postgresql_where=text('freight_warehouse_id IS NULL AND enabled = true'),
|
||||||
sqlite_where=text('freight_warehouse_id IS NULL AND enabled = 1'),
|
sqlite_where=text('freight_warehouse_id IS NULL AND enabled = 1'),
|
||||||
),
|
),
|
||||||
Index(
|
Index(
|
||||||
'uq_shipping_inv_ext_map_src_wh_enabled',
|
'uq_shipping_inv_ext_map_src_wh_enabled',
|
||||||
'inventory_source_id',
|
'source_id',
|
||||||
'freight_warehouse_id',
|
'freight_warehouse_id',
|
||||||
unique=True,
|
unique=True,
|
||||||
postgresql_where=text('freight_warehouse_id IS NOT NULL AND enabled = true'),
|
postgresql_where=text('freight_warehouse_id IS NOT NULL AND enabled = true'),
|
||||||
@@ -391,7 +439,7 @@ class ShippingInventoryExternalMapping(Base):
|
|||||||
)
|
)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True)
|
source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False, index=True)
|
||||||
freight_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
freight_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
external_system_code: Mapped[str] = mapped_column(String(32), nullable=False)
|
external_system_code: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||||
external_organization_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
external_organization_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
@@ -407,4 +455,4 @@ class ShippingInventoryExternalMapping(Base):
|
|||||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
inventory_source: Mapped[ShippingInventorySource] = relationship(back_populates='external_mappings')
|
source: Mapped[FreightRpaSource] = relationship(back_populates='external_mappings')
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
"""
|
||||||
|
backend/app/models/freight_rpa_inbound_report.py
|
||||||
|
|
||||||
|
用途:入站报表 RPA 的配置、运行与归档持久化模型(per-file 企微投递表已拆除,见 Task 4 迁移)。
|
||||||
|
依赖:freight_rpa_sources、排程运行、freight_rpa_parsing_profiles、SQLAlchemy Base;完整操作追溯统一写入 ShippingAuditEvent。
|
||||||
|
逻辑:模型只复用站点连接资料,通过独立外键与唯一约束隔离在手快照、匹配和旧 RPA Worker 链路。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
|
|
||||||
|
from app.models.base import Base
|
||||||
|
|
||||||
|
|
||||||
|
class FreightRpaInboundReportConfig(Base):
|
||||||
|
"""库存站点的一对一收料报表配置;路径和条件始终独立于库存配置。"""
|
||||||
|
|
||||||
|
__tablename__ = 'freight_rpa_inbound_report_configs'
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint('source_id', name='uq_freight_rpa_inbound_report_configs_source'),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
source_id: Mapped[int] = mapped_column(
|
||||||
|
ForeignKey('freight_rpa_sources.id'), nullable=False, index=True,
|
||||||
|
)
|
||||||
|
# 收料不设独立启停:是否运行统一由库存站点 enabled 与本配置是否存在决定。
|
||||||
|
# 收料文件解析规则(purpose='inbound');定死领域字段端点。空则无法解析收料文件。
|
||||||
|
parsing_profile_id: Mapped[Optional[int]] = mapped_column(
|
||||||
|
ForeignKey('freight_rpa_parsing_profiles.id'), nullable=True, index=True,
|
||||||
|
)
|
||||||
|
report_path_json: Mapped[dict[str, Any]] = mapped_column(
|
||||||
|
JSON, default=dict, server_default=text("'{}'"), nullable=False,
|
||||||
|
)
|
||||||
|
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(
|
||||||
|
JSON, default=list, server_default=text("'[]'"), nullable=False,
|
||||||
|
)
|
||||||
|
# 与库存同构:查询条件原样下发 Worker;空条件表示页面默认。排程一源一单元,不按仓拆分。
|
||||||
|
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||||
|
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||||
|
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
source: Mapped['FreightRpaSource'] = relationship(back_populates='inbound_report_config')
|
||||||
|
parsing_profile: Mapped[Optional['FreightRpaParsingProfile']] = relationship()
|
||||||
|
|
||||||
|
|
||||||
|
class FreightRpaInboundUnitRun(Base):
|
||||||
|
"""一次收料执行的站点或站点-Warehouse 不可重复执行单元。
|
||||||
|
|
||||||
|
schedule_run_id 指向排程 run;调拨按需触发(重试/预检补抓)无排程,保持 NULL。
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = 'freight_rpa_inbound_rpa_unit_runs'
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint('callback_id', name='uq_freight_rpa_inbound_rpa_unit_runs_callback'),
|
||||||
|
CheckConstraint(
|
||||||
|
"status IN ('queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled')",
|
||||||
|
name='ck_freight_rpa_inbound_rpa_unit_runs_status',
|
||||||
|
),
|
||||||
|
Index('ix_shipping_receipt_unit_run_schedule_status', 'schedule_run_id', 'status'),
|
||||||
|
Index('ix_shipping_receipt_unit_run_source_created', 'source_id', 'created_at'),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
schedule_run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_runs.id'), nullable=True, index=True)
|
||||||
|
source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False, index=True)
|
||||||
|
retry_of_id: Mapped[Optional[int]] = mapped_column(
|
||||||
|
ForeignKey('freight_rpa_inbound_rpa_unit_runs.id'), nullable=True, index=True,
|
||||||
|
)
|
||||||
|
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
connector_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||||
|
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
callback_id: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
|
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
||||||
|
config_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||||
|
trigger_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||||
|
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||||
|
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
|
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
schedule_run: Mapped[Optional['ScheduleRun']] = relationship(foreign_keys=[schedule_run_id])
|
||||||
|
source: Mapped['FreightRpaSource'] = relationship()
|
||||||
|
retry_of: Mapped[Optional['FreightRpaInboundUnitRun']] = relationship(remote_side=[id])
|
||||||
|
files: Mapped[list['FreightRpaInboundReportFile']] = relationship(
|
||||||
|
back_populates='unit_run', cascade='all, delete-orphan',
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class FreightRpaInboundReportFile(Base):
|
||||||
|
"""收料原样归档文件;保留文件身份和对象清理事实,不关联库存快照。"""
|
||||||
|
|
||||||
|
__tablename__ = 'freight_rpa_inbound_report_files'
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint('unit_run_id', 'sha256', name='uq_freight_rpa_inbound_report_files_unit_sha256'),
|
||||||
|
CheckConstraint("file_size >= 0", name='ck_freight_rpa_inbound_report_files_size'),
|
||||||
|
Index('ix_freight_rpa_inbound_report_files_unit', 'unit_run_id'),
|
||||||
|
Index('ix_freight_rpa_inbound_report_files_expires', 'archive_expires_at', 'archive_deleted_at'),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
unit_run_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_inbound_rpa_unit_runs.id'), nullable=False, index=True)
|
||||||
|
storage_provider: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||||
|
storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
|
storage_key: Mapped[str] = mapped_column(String(1024), nullable=False)
|
||||||
|
original_filename: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||||
|
content_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||||
|
file_size: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
|
sha256: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
# 解析失败分层标记:归档文件解析失败时写入;三者全空=未失败/已清除。
|
||||||
|
parse_failed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
parse_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
parse_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
|
archive_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
archive_deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
archive_delete_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
unit_run: Mapped[FreightRpaInboundUnitRun] = relationship(back_populates='files')
|
||||||
+9
-9
@@ -1,8 +1,8 @@
|
|||||||
"""
|
"""
|
||||||
models/shipping_inventory_mapping.py
|
backend/app/models/freight_rpa_onhand_mapping.py
|
||||||
|
|
||||||
用途:保存不可变库存字段映射版本。
|
用途:保存不可变库存字段映射版本。
|
||||||
依赖:ShippingInventoryFile、ShippingInventoryParsingProfile、Base。
|
依赖:FreightRpaOnhandReportFile、FreightRpaParsingProfile、Base。
|
||||||
逻辑:每次确认/重跑创建新版本,匹配 Attempt 通过 mapping_id 精确引用。
|
逻辑:每次确认/重跑创建新版本,匹配 Attempt 通过 mapping_id 精确引用。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -17,24 +17,24 @@ from sqlalchemy.orm import Mapped, mapped_column
|
|||||||
from app.models.base import Base
|
from app.models.base import Base
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryMapping(Base):
|
class FreightRpaOnhandMapping(Base):
|
||||||
"""库存文件的不可变字段映射版本。"""
|
"""库存文件的不可变字段映射版本。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_mappings'
|
__tablename__ = 'freight_rpa_onhand_mappings'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint('inventory_file_id', 'version', name='uq_shipping_inventory_mapping_file_version'),
|
UniqueConstraint('onhand_file_id', 'version', name='uq_shipping_inventory_mapping_file_version'),
|
||||||
CheckConstraint("status IN ('active','superseded','invalidated')", name='ck_shipping_inventory_mapping_status'),
|
CheckConstraint("status IN ('active','superseded','invalidated')", name='ck_shipping_inventory_mapping_status'),
|
||||||
Index('ix_shipping_inventory_mapping_file_status', 'inventory_file_id', 'status'),
|
Index('ix_shipping_inventory_mapping_file_status', 'onhand_file_id', 'status'),
|
||||||
)
|
)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||||
inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id', ondelete='CASCADE'), nullable=False)
|
onhand_file_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id', ondelete='CASCADE'), nullable=False)
|
||||||
version: Mapped[int] = mapped_column(Integer, nullable=False)
|
version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active')
|
status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active')
|
||||||
profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id', ondelete='SET NULL'), nullable=True)
|
profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_parsing_profiles.id', ondelete='SET NULL'), nullable=True)
|
||||||
mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||||
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_mappings.id'), nullable=True)
|
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_mappings.id'), nullable=True)
|
||||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||||
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
"""
|
||||||
|
backend/app/models/freight_rpa_onhand_report_file.py
|
||||||
|
|
||||||
|
用途:货代 RPA 抓回的在手报表文件。
|
||||||
|
依赖:models.base.Base、shipping.py 里的 ShippingTaskOnhandLink。
|
||||||
|
逻辑:表名 freight_rpa_onhand_report_files 不变;发货任务通过 ShippingTaskOnhandLink 引用本行。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
from sqlalchemy import (
|
||||||
|
Boolean,
|
||||||
|
DateTime,
|
||||||
|
ForeignKey,
|
||||||
|
Index,
|
||||||
|
Integer,
|
||||||
|
JSON,
|
||||||
|
String,
|
||||||
|
text,
|
||||||
|
)
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
|
|
||||||
|
from app.models.base import Base
|
||||||
|
|
||||||
|
|
||||||
|
class FreightRpaOnhandReportFile(Base):
|
||||||
|
"""货代发货批次库存快照文件,承载一次上传后可被多票任务共用的库存数据。
|
||||||
|
|
||||||
|
在手文件表归货代 RPA(s18 由 shipping_onhand_files 改名而来);列不改,
|
||||||
|
仍含解析行、字段映射与快照状态,本阶段只改表名与指向它的外键。
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = 'freight_rpa_onhand_report_files'
|
||||||
|
__table_args__ = (
|
||||||
|
Index('ix_freight_rpa_onhand_report_files_user_created', 'user_id', 'created_at'),
|
||||||
|
Index(
|
||||||
|
'ix_freight_rpa_onhand_report_files_source_snapshot',
|
||||||
|
'source_code',
|
||||||
|
'warehouse_id',
|
||||||
|
'snapshot_status',
|
||||||
|
'exported_at',
|
||||||
|
),
|
||||||
|
Index(
|
||||||
|
'ix_freight_rpa_onhand_report_files_source_warehouse',
|
||||||
|
'source_code',
|
||||||
|
'warehouse_id',
|
||||||
|
),
|
||||||
|
Index(
|
||||||
|
'uq_freight_rpa_onhand_report_files_rpa_identity_ready',
|
||||||
|
'rpa_run_no',
|
||||||
|
'source_code',
|
||||||
|
'warehouse_id',
|
||||||
|
unique=True,
|
||||||
|
postgresql_where=text(
|
||||||
|
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
|
||||||
|
"AND source_code IS NOT NULL AND warehouse_id IS NOT NULL"
|
||||||
|
),
|
||||||
|
sqlite_where=text(
|
||||||
|
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
|
||||||
|
"AND source_code IS NOT NULL AND warehouse_id IS NOT NULL"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
# 动态多仓文件没有单一 Warehouse;按 RPA run + Source 保证回调重放幂等。
|
||||||
|
Index(
|
||||||
|
'uq_freight_rpa_onhand_report_files_rpa_dynamic_source_ready',
|
||||||
|
'rpa_run_no',
|
||||||
|
'source_code',
|
||||||
|
unique=True,
|
||||||
|
postgresql_where=text(
|
||||||
|
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
|
||||||
|
"AND source_code IS NOT NULL AND warehouse_id IS NULL"
|
||||||
|
),
|
||||||
|
sqlite_where=text(
|
||||||
|
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
|
||||||
|
"AND source_code IS NOT NULL AND warehouse_id IS NULL"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
onhand_file_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||||
|
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
|
||||||
|
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||||
|
storage_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||||
|
schema_preview_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||||
|
field_mapping_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||||
|
mapping_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||||
|
mapping_confirmed: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
|
||||||
|
onhand_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||||
|
line_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||||
|
share_mode: Mapped[str] = mapped_column(String(32), default='task_only')
|
||||||
|
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||||
|
warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||||
|
identity_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
|
||||||
|
source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||||
|
source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||||
|
snapshot_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
|
||||||
|
exported_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
|
||||||
|
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
|
||||||
|
rpa_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
schedule_run_id: Mapped[Optional[int]] = mapped_column(nullable=True, index=True)
|
||||||
|
source_query_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||||
|
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id'), nullable=True)
|
||||||
|
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
|
||||||
|
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
|
||||||
|
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||||
|
|
||||||
|
links: Mapped[List['ShippingTaskOnhandLink']] = relationship(
|
||||||
|
'ShippingTaskOnhandLink',
|
||||||
|
back_populates='inventory_file',
|
||||||
|
cascade='all, delete-orphan',
|
||||||
|
)
|
||||||
+4
-4
@@ -1,5 +1,5 @@
|
|||||||
"""
|
"""
|
||||||
models/shipping_task_inventory_rpa_attempts.py
|
backend/app/models/freight_rpa_onhand_task_attempts.py
|
||||||
|
|
||||||
用途:逐库存源的 RPA 导出 Attempt 结构化记录(决策 D1/D2 三元组幂等)。
|
用途:逐库存源的 RPA 导出 Attempt 结构化记录(决策 D1/D2 三元组幂等)。
|
||||||
依赖:Base、ShippingNotice(task_no FK 可选直连 id 先保留 task_no 字符串关联)、users。
|
依赖:Base、ShippingNotice(task_no FK 可选直连 id 先保留 task_no 字符串关联)、users。
|
||||||
@@ -47,10 +47,10 @@ PER_SOURCE_RPA_ATTEMPT_STATUSES = (
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class ShippingTaskInventoryRpaAttempt(Base):
|
class FreightRpaOnhandTaskAttempt(Base):
|
||||||
"""逐 (task_no, source_code) 的库存 RPA 导出 Attempt 记录。"""
|
"""逐 (task_no, source_code) 的库存 RPA 导出 Attempt 记录。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_task_inventory_rpa_attempts'
|
__tablename__ = 'freight_rpa_onhand_task_rpa_attempts'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
# 三元组唯一:同一运行号同一源只允许一条记录
|
# 三元组唯一:同一运行号同一源只允许一条记录
|
||||||
UniqueConstraint('task_no', 'source_code', 'source_run_no', name='uq_shipping_task_inv_rpa_triplet'),
|
UniqueConstraint('task_no', 'source_code', 'source_run_no', name='uq_shipping_task_inv_rpa_triplet'),
|
||||||
@@ -87,7 +87,7 @@ class ShippingTaskInventoryRpaAttempt(Base):
|
|||||||
|
|
||||||
trigger_file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
|
trigger_file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
|
||||||
callback_file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
|
callback_file_path: Mapped[Optional[str]] = mapped_column(String(1024), nullable=True)
|
||||||
inventory_file_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
onhand_file_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||||
|
|
||||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
"""
|
||||||
|
backend/app/models/freight_rpa_outbound_report.py
|
||||||
|
|
||||||
|
用途:出站报表 RPA 的配置、运行与归档持久化模型(不建 per-file 企微投递表)。
|
||||||
|
依赖:freight_rpa_sources、排程运行、freight_rpa_parsing_profiles、SQLAlchemy Base;完整操作追溯统一写入 ShippingAuditEvent。
|
||||||
|
逻辑:模型只复用站点连接资料,通过独立外键与唯一约束隔离在手快照、匹配和旧 RPA Worker 链路。
|
||||||
|
FreightRpaSource.outbound_report_config 一对一回指本配置行。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
|
|
||||||
|
from app.models.base import Base
|
||||||
|
|
||||||
|
|
||||||
|
class FreightRpaOutboundReportConfig(Base):
|
||||||
|
"""库存站点的一对一出站报表配置;路径和条件始终独立于库存 / 入站配置。"""
|
||||||
|
|
||||||
|
__tablename__ = 'freight_rpa_outbound_report_configs'
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint('source_id', name='uq_freight_rpa_outbound_report_configs_source'),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
source_id: Mapped[int] = mapped_column(
|
||||||
|
ForeignKey('freight_rpa_sources.id'), nullable=False, index=True,
|
||||||
|
)
|
||||||
|
# 出站不设独立启停:是否运行统一由库存站点 enabled 与本配置是否存在决定。
|
||||||
|
# 出站文件解析规则(purpose='outbound');定死领域字段端点。空则无法解析出站文件。
|
||||||
|
parsing_profile_id: Mapped[Optional[int]] = mapped_column(
|
||||||
|
ForeignKey('freight_rpa_parsing_profiles.id'), nullable=True, index=True,
|
||||||
|
)
|
||||||
|
report_path_json: Mapped[dict[str, Any]] = mapped_column(
|
||||||
|
JSON, default=dict, server_default=text("'{}'"), nullable=False,
|
||||||
|
)
|
||||||
|
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(
|
||||||
|
JSON, default=list, server_default=text("'[]'"), nullable=False,
|
||||||
|
)
|
||||||
|
# 与库存同构:查询条件原样下发 Worker;空条件表示页面默认。排程一源一单元,不按仓拆分。
|
||||||
|
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||||
|
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||||
|
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
source: Mapped['FreightRpaSource'] = relationship(back_populates='outbound_report_config')
|
||||||
|
parsing_profile: Mapped[Optional['FreightRpaParsingProfile']] = relationship()
|
||||||
|
|
||||||
|
|
||||||
|
class FreightRpaOutboundUnitRun(Base):
|
||||||
|
"""一次出站执行的站点或站点-Warehouse 不可重复执行单元。
|
||||||
|
|
||||||
|
schedule_run_id 指向排程 run;调拨按需触发(重试/预检补抓)无排程,保持 NULL。
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = 'freight_rpa_outbound_rpa_unit_runs'
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint('callback_id', name='uq_freight_rpa_outbound_rpa_unit_runs_callback'),
|
||||||
|
CheckConstraint(
|
||||||
|
"status IN ('queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled')",
|
||||||
|
name='ck_freight_rpa_outbound_rpa_unit_runs_status',
|
||||||
|
),
|
||||||
|
Index('ix_freight_rpa_outbound_unit_run_schedule_status', 'schedule_run_id', 'status'),
|
||||||
|
Index('ix_freight_rpa_outbound_unit_run_source_created', 'source_id', 'created_at'),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
schedule_run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_runs.id'), nullable=True, index=True)
|
||||||
|
source_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_sources.id'), nullable=False, index=True)
|
||||||
|
retry_of_id: Mapped[Optional[int]] = mapped_column(
|
||||||
|
ForeignKey('freight_rpa_outbound_rpa_unit_runs.id'), nullable=True, index=True,
|
||||||
|
)
|
||||||
|
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
connector_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||||
|
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
callback_id: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
|
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
||||||
|
config_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||||
|
trigger_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||||
|
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||||
|
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
|
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
schedule_run: Mapped[Optional['ScheduleRun']] = relationship(foreign_keys=[schedule_run_id])
|
||||||
|
source: Mapped['FreightRpaSource'] = relationship()
|
||||||
|
retry_of: Mapped[Optional['FreightRpaOutboundUnitRun']] = relationship(remote_side=[id])
|
||||||
|
files: Mapped[list['FreightRpaOutboundReportFile']] = relationship(
|
||||||
|
back_populates='unit_run', cascade='all, delete-orphan',
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class FreightRpaOutboundReportFile(Base):
|
||||||
|
"""出站原样归档文件;保留文件身份和对象清理事实,不关联库存快照。"""
|
||||||
|
|
||||||
|
__tablename__ = 'freight_rpa_outbound_report_files'
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint('unit_run_id', 'sha256', name='uq_freight_rpa_outbound_report_files_unit_sha256'),
|
||||||
|
CheckConstraint("file_size >= 0", name='ck_freight_rpa_outbound_report_files_size'),
|
||||||
|
Index('ix_freight_rpa_outbound_report_files_unit', 'unit_run_id'),
|
||||||
|
Index('ix_freight_rpa_outbound_report_files_expires', 'archive_expires_at', 'archive_deleted_at'),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
unit_run_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_outbound_rpa_unit_runs.id'), nullable=False, index=True)
|
||||||
|
storage_provider: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||||
|
storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
|
storage_key: Mapped[str] = mapped_column(String(1024), nullable=False)
|
||||||
|
original_filename: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||||
|
content_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||||
|
file_size: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
|
sha256: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
# 解析失败分层标记:归档文件解析失败时写入;三者全空=未失败/已清除。
|
||||||
|
parse_failed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
parse_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
parse_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
|
archive_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
archive_deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
archive_delete_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
unit_run: Mapped[FreightRpaOutboundUnitRun] = relationship(back_populates='files')
|
||||||
@@ -1,11 +1,22 @@
|
|||||||
"""models/in_transit_transfer.py
|
"""models/in_transit_transfer.py
|
||||||
|
|
||||||
用途:在途仓自动调拨一期核心领域模型:Run、SourceJob、Precheck、InvoiceItem、
|
用途:在途仓自动调拨一期核心领域模型:Run、SourceJob、Matching、InvoiceItem、
|
||||||
Attempt、AuditEvent 与 Archive。
|
Document(ERP 调拨单)、Attempt、AuditEvent 与 Archive;另含调拨类型
|
||||||
依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁)。
|
配置表 TransferTypeConfig(类型配置化,ADR 0002)与库存异动档
|
||||||
逻辑:Run 是异步真相源;InvoiceItem 按(precheck_id, invoice_no)唯一防止重复建单;
|
TransferMovementLedger(外部系统入站/出站记录镜像,ADR 0001)。
|
||||||
Attempt 保留每次恢复/重查事实,旧 Attempt 永不覆盖;
|
依赖:models.base.Base、SQLAlchemy 2.0 ORM;审计事件为只追加(ORM 门禁);
|
||||||
AuditEvent 保存脱敏快照与事件 Hash,禁止更新/删除。
|
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,禁止更新/删除;
|
||||||
|
transfer_runs.transfer_type 合法值由 TransferTypeConfig 配置承接
|
||||||
|
(原枚举 CHECK 约束已移除);
|
||||||
|
TransferMovementLedger 以自然键 (source_code, record_kind, doc_no,
|
||||||
|
line_no, line_seq, in_out_flag, carton_id, lot_no) 幂等增量落地外部记录,
|
||||||
|
已执行记录经 transfer_executed 封存(防二次调拨),来源文件删除后档事实留存
|
||||||
|
(ON DELETE SET NULL,链接仅溯源)。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -32,38 +43,50 @@ from app.core.errors import ValidationError
|
|||||||
from app.models.base import Base
|
from app.models.base import Base
|
||||||
|
|
||||||
# 与 services/in_transit_transfer/status.py 保持一致的冻结枚举(数据库级兜底)。
|
# 与 services/in_transit_transfer/status.py 保持一致的冻结枚举(数据库级兜底)。
|
||||||
|
# 【not_matured 已退役 2026-10-16】成熟概念删除,存量行经 tt16 重映射 cancelled。
|
||||||
TRANSFER_ITEM_STATUSES = (
|
TRANSFER_ITEM_STATUSES = (
|
||||||
'file_pending', 'file_ready', 'prechecking', 'ready_to_execute', 'executing',
|
'file_pending', 'file_ready', 'matching', 'ready_to_execute', 'executing',
|
||||||
'success', 'duplicate_success', 'blocked_recoverable', 'not_matured',
|
'success', 'duplicate_success', 'blocked_recoverable',
|
||||||
'result_unknown', 'manually_closed', 'cancelled', 'notification_failed',
|
'result_unknown', 'manually_closed', 'cancelled', 'notification_failed',
|
||||||
)
|
)
|
||||||
TRANSFER_RUN_STATUSES = (
|
TRANSFER_RUN_STATUSES = (
|
||||||
'queued', 'preparing_files', 'prechecking', 'ready_to_execute', 'executing',
|
'queued', 'preparing_files', 'matching', 'ready_to_execute', 'executing',
|
||||||
'success', 'partial_failed', 'failed', 'cancelled',
|
'success', 'partial_failed', 'failed', 'cancelled',
|
||||||
)
|
)
|
||||||
# 与 services/in_transit_transfer/transfer_type.py TransferType 保持一致的冻结枚举
|
|
||||||
# (数据库级兜底);一期仅 in_transit_to_hub 进入处理链路,其余为占位值。
|
|
||||||
TRANSFER_RUN_TYPES = (
|
|
||||||
'in_transit_to_hub', 'hub_repair_out', 'hub_to_hub',
|
|
||||||
)
|
|
||||||
TRANSFER_SOURCE_JOB_STATUSES = (
|
TRANSFER_SOURCE_JOB_STATUSES = (
|
||||||
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
|
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
|
||||||
'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
|
'matching', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
|
||||||
)
|
)
|
||||||
TRANSFER_PRECHECK_STATUSES = (
|
TRANSFER_MATCH_STATUSES = (
|
||||||
'file_pending', 'file_ready', 'prechecking', 'ready_to_execute', 'executing',
|
'file_pending', 'file_ready', 'matching', 'ready_to_execute', 'executing',
|
||||||
'success', 'failed', 'cancelled', 'expired',
|
'success', 'failed', 'cancelled', 'expired',
|
||||||
)
|
)
|
||||||
TRANSFER_ATTEMPT_KINDS = ('precheck', 'rpa', 'external_query', 'external_write')
|
TRANSFER_ATTEMPT_KINDS = ('match', 'rpa', 'external_query', 'external_write')
|
||||||
TRANSFER_ATTEMPT_STATUSES = (
|
TRANSFER_ATTEMPT_STATUSES = (
|
||||||
'queued', 'running', 'waiting_external', 'success', 'failed',
|
'queued', 'running', 'waiting_external', 'success', 'failed',
|
||||||
'result_unknown', 'superseded',
|
'result_unknown', 'superseded',
|
||||||
)
|
)
|
||||||
|
# ERP 调拨单(TransferDocument)状态冻结枚举:服务层口径真相源;
|
||||||
|
# ck_transfer_documents_status CHECK 由该元组生成(DB 兜底,非法态 fail-closed)。
|
||||||
|
TRANSFER_DOCUMENT_STATUSES = (
|
||||||
|
'pending', 'executing', 'success', 'duplicate_success',
|
||||||
|
'business_failed', 'technical_failed', 'result_unknown', 'cancelled',
|
||||||
|
)
|
||||||
|
# 未完结单状态集合(组锁生效范围,D7①/D15):同五元组存在任一未完结单时
|
||||||
|
# 复用其 doc_no+submit_timestamp,禁止新建;部分唯一索引的 WHERE 子句由该
|
||||||
|
# 元组生成,保证「常量集 ↔ DB 约束」永远一致(原锁定测试 test_document_model.py
|
||||||
|
# 已删除,改动本元组时须人工核对迁移内 CHECK/WHERE 字面量同口径)。
|
||||||
|
UNRESOLVED_DOC_STATUSES = (
|
||||||
|
'pending', 'executing', 'result_unknown', 'business_failed', 'technical_failed',
|
||||||
|
)
|
||||||
|
UNRESOLVED_DOC_STATUS_WHERE = "status IN ({})".format(
|
||||||
|
', '.join(repr(s) for s in UNRESOLVED_DOC_STATUSES),
|
||||||
|
)
|
||||||
TRANSFER_AUDIT_ACTOR_TYPES = ('user', 'system', 'worker', 'admin', 'rpa', 'schedule')
|
TRANSFER_AUDIT_ACTOR_TYPES = ('user', 'system', 'worker', 'admin', 'rpa', 'schedule')
|
||||||
|
|
||||||
|
|
||||||
class TransferRun(Base):
|
class TransferRun(Base):
|
||||||
"""一次调拨执行(或只读预检)的业务真相源。"""
|
"""一次调拨执行(或只读匹配)的业务真相源。"""
|
||||||
|
|
||||||
__tablename__ = 'transfer_runs'
|
__tablename__ = 'transfer_runs'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
@@ -80,10 +103,6 @@ class TransferRun(Base):
|
|||||||
"trigger_type IN ('manual', 'schedule')",
|
"trigger_type IN ('manual', 'schedule')",
|
||||||
name='ck_transfer_runs_trigger_type',
|
name='ck_transfer_runs_trigger_type',
|
||||||
),
|
),
|
||||||
CheckConstraint(
|
|
||||||
f"transfer_type IN ({', '.join(repr(t) for t in TRANSFER_RUN_TYPES)})",
|
|
||||||
name='ck_transfer_runs_transfer_type',
|
|
||||||
),
|
|
||||||
Index('ix_transfer_runs_status_created', 'status', 'created_at'),
|
Index('ix_transfer_runs_status_created', 'status', 'created_at'),
|
||||||
Index('ix_transfer_runs_business_date', 'business_date'),
|
Index('ix_transfer_runs_business_date', 'business_date'),
|
||||||
)
|
)
|
||||||
@@ -91,9 +110,11 @@ class TransferRun(Base):
|
|||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
trigger_type: Mapped[str] = mapped_column(String(16), nullable=False, default='manual', server_default='manual')
|
trigger_type: Mapped[str] = mapped_column(String(16), nullable=False, default='manual', server_default='manual')
|
||||||
# 调拨业务类型(在途仓至HUB仓/HUB仓维修出/HUB仓间调拨);决定预检收料数据范围。
|
# 调拨业务类型(合法值由 TransferTypeConfig 配置承接,合法 code 正则
|
||||||
|
# ^[a-z][a-z0-9_]{1,63}$ 上限 64);决定匹配入站数据范围。列宽 64 与配置表
|
||||||
|
# code 上限对齐(终审 I2:33~64 字符 code 建匹配时写 32 宽列会 DB 500)。
|
||||||
transfer_type: Mapped[str] = mapped_column(
|
transfer_type: Mapped[str] = mapped_column(
|
||||||
String(32), nullable=False, default='in_transit_to_hub', server_default='in_transit_to_hub',
|
String(64), nullable=False, default='in_transit_to_hub', server_default='in_transit_to_hub',
|
||||||
)
|
)
|
||||||
business_date: Mapped[str] = mapped_column(String(16), nullable=False)
|
business_date: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
||||||
@@ -116,14 +137,14 @@ class TransferRun(Base):
|
|||||||
source_jobs: Mapped[list['TransferSourceJob']] = relationship(
|
source_jobs: Mapped[list['TransferSourceJob']] = relationship(
|
||||||
back_populates='run', cascade='all, delete-orphan',
|
back_populates='run', cascade='all, delete-orphan',
|
||||||
)
|
)
|
||||||
prechecks: Mapped[list['TransferPrecheck']] = relationship(
|
matchings: Mapped[list['TransferMatching']] = relationship(
|
||||||
back_populates='run', cascade='all, delete-orphan',
|
back_populates='run', cascade='all, delete-orphan',
|
||||||
)
|
)
|
||||||
items: Mapped[list['TransferInvoiceItem']] = relationship(back_populates='run')
|
items: Mapped[list['TransferInvoiceItem']] = relationship(back_populates='run')
|
||||||
|
|
||||||
|
|
||||||
class TransferSourceJob(Base):
|
class TransferSourceJob(Base):
|
||||||
"""来源实例级的文件准备/预检执行单元;来源间互不阻断。"""
|
"""来源实例级的文件准备/匹配执行单元;来源间互不阻断。"""
|
||||||
|
|
||||||
__tablename__ = 'transfer_source_jobs'
|
__tablename__ = 'transfer_source_jobs'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
@@ -155,25 +176,25 @@ class TransferSourceJob(Base):
|
|||||||
run: Mapped[TransferRun] = relationship(back_populates='source_jobs')
|
run: Mapped[TransferRun] = relationship(back_populates='source_jobs')
|
||||||
|
|
||||||
|
|
||||||
class TransferPrecheck(Base):
|
class TransferMatching(Base):
|
||||||
"""一次冻结快照的预检结果;确认/执行绑定其 Hash。"""
|
"""一次冻结快照的匹配结果;确认/执行绑定其 Hash。"""
|
||||||
|
|
||||||
__tablename__ = 'transfer_prechecks'
|
__tablename__ = 'transfer_matchings'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint('precheck_no', name='uq_transfer_prechecks_precheck_no'),
|
UniqueConstraint('matching_no', name='uq_transfer_matchings_matching_no'),
|
||||||
CheckConstraint(
|
CheckConstraint(
|
||||||
f"status IN ({', '.join(repr(s) for s in TRANSFER_PRECHECK_STATUSES)})",
|
f"status IN ({', '.join(repr(s) for s in TRANSFER_MATCH_STATUSES)})",
|
||||||
name='ck_transfer_prechecks_status',
|
name='ck_transfer_matchings_status',
|
||||||
),
|
),
|
||||||
Index('ix_transfer_prechecks_run_status', 'run_id', 'status'),
|
Index('ix_transfer_matchings_run_status', 'run_id', 'status'),
|
||||||
Index('ix_transfer_prechecks_business_date', 'business_date'),
|
Index('ix_transfer_matchings_business_date', 'business_date'),
|
||||||
)
|
)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
precheck_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
matching_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True, index=True)
|
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True, index=True)
|
||||||
business_date: Mapped[str] = mapped_column(String(16), nullable=False)
|
business_date: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='prechecking', server_default='prechecking')
|
status: Mapped[str] = mapped_column(String(32), nullable=False, default='matching', server_default='matching')
|
||||||
scope_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
scope_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||||
file_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
file_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||||
mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
@@ -181,7 +202,7 @@ class TransferPrecheck(Base):
|
|||||||
counts_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
counts_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||||
estimated_transfer_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
estimated_transfer_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||||
estimated_external_write_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
|
estimated_external_write_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
|
||||||
precheck_hash: Mapped[str] = mapped_column(String(128), nullable=False)
|
matching_hash: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
confirmed_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
confirmed_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||||
@@ -190,23 +211,26 @@ class TransferPrecheck(Base):
|
|||||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
run: Mapped[Optional[TransferRun]] = relationship(back_populates='prechecks')
|
run: Mapped[Optional[TransferRun]] = relationship(back_populates='matchings')
|
||||||
items: Mapped[list['TransferInvoiceItem']] = relationship(
|
items: Mapped[list['TransferInvoiceItem']] = relationship(
|
||||||
back_populates='precheck', cascade='all, delete-orphan',
|
back_populates='matching', cascade='all, delete-orphan',
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class TransferInvoiceItem(Base):
|
class TransferInvoiceItem(Base):
|
||||||
"""预检明细项;同一预检内 (来源,Invoice,料号,收料日期) 唯一,保留原始行追溯。
|
"""匹配明细项;同一匹配内 (来源,Invoice,料号,异动日期) 唯一,保留原始行追溯。
|
||||||
|
|
||||||
Invoice 锚定批号(2026-09-21 业务口径):同一批号跨料号/跨日期拆分为多行。
|
Invoice 锚定批号(2026-09-21 业务口径):同一批号跨料号/跨日期拆分为多行。
|
||||||
|
【2026-10-14 出生翻转(ADR 0001/D4)】行不再由文件落地写入,而是匹配创建时
|
||||||
|
从库存异动档圈定生成:ledger_record_id 指向档记录(业务字段=档原值),
|
||||||
|
matching_id 创建即绑定(D17:一条档记录一生只生成一次 items 绑定)。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__tablename__ = 'transfer_invoice_items'
|
__tablename__ = 'transfer_invoice_items'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint(
|
UniqueConstraint(
|
||||||
'precheck_id', 'source_code', 'invoice_no', 'material_no', 'receipt_date',
|
'matching_id', 'source_code', 'invoice_no', 'material_no', 'movement_date',
|
||||||
name='uq_transfer_invoice_items_precheck_grain',
|
name='uq_transfer_invoice_items_matching_grain',
|
||||||
),
|
),
|
||||||
CheckConstraint(
|
CheckConstraint(
|
||||||
f"status IN ({', '.join(repr(s) for s in TRANSFER_ITEM_STATUSES)})",
|
f"status IN ({', '.join(repr(s) for s in TRANSFER_ITEM_STATUSES)})",
|
||||||
@@ -215,26 +239,48 @@ class TransferInvoiceItem(Base):
|
|||||||
Index('ix_transfer_invoice_items_source_invoice_status', 'source_code', 'invoice_no', 'status'),
|
Index('ix_transfer_invoice_items_source_invoice_status', 'source_code', 'invoice_no', 'status'),
|
||||||
Index('ix_transfer_invoice_items_run_id', 'run_id'),
|
Index('ix_transfer_invoice_items_run_id', 'run_id'),
|
||||||
Index('ix_transfer_invoice_items_external_document_no', 'external_document_no'),
|
Index('ix_transfer_invoice_items_external_document_no', 'external_document_no'),
|
||||||
|
# 单据级执行(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)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
precheck_id: Mapped[int] = mapped_column(ForeignKey('transfer_prechecks.id'), nullable=False, index=True)
|
# 【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)
|
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_runs.id'), nullable=True)
|
||||||
|
# 【2026-10-14 出生翻转】行来源档记录外键(可空:隔离的历史行允许 NULL);
|
||||||
|
# 行上业务字段=档原值,批号等转换只在系统边界按匹配快照规则派生(不落库)。
|
||||||
|
ledger_record_id: Mapped[Optional[int]] = mapped_column(
|
||||||
|
ForeignKey('transfer_movement_ledger.id'), nullable=True,
|
||||||
|
)
|
||||||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
invoice_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
invoice_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
# 批号(External ASN 等)原值;「拨入批号」展示由 WTP→HOW 转换派生,不落库。
|
# 批号(External ASN 等)原值;「拨入批号」展示由 WTP→HOW 转换派生,不落库。
|
||||||
lot_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
lot_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(拨出库位解析审计)。
|
# 入站文件「仓库」列原值:inventory_match 源映射行匹配键(拨出库位解析审计)。
|
||||||
receipt_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
movement_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
||||||
|
# 交易单位原值(movement 契约第 11 字段 unit,计划 D4):解析原样保留(仅 trim,
|
||||||
|
# 不换算);空值行在匹配阶段落 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_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
material_name: Mapped[str] = mapped_column(String(200), nullable=False, default='')
|
material_name: Mapped[str] = mapped_column(String(200), nullable=False, default='')
|
||||||
specification: Mapped[str] = mapped_column(String(200), nullable=False, default='')
|
specification: Mapped[str] = mapped_column(String(200), nullable=False, default='')
|
||||||
receipt_date: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
movement_date: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||||||
from_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
|
from_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
|
to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
# 数量以 Decimal 文本保存,杜绝浮点误差;比较在服务层完成。
|
# 数量以 Decimal 文本保存,杜绝浮点误差;比较在服务层完成。
|
||||||
receipt_quantity: Mapped[str] = mapped_column(String(40), nullable=False)
|
movement_quantity: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||||
external_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
external_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||||
|
# [库存查得时刻] 当前 external_quantity 的 ERP 取数时间戳(stale 徽标判定时钟,
|
||||||
|
# 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)
|
status: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||||
result_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
result_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
result_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
result_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
@@ -248,11 +294,93 @@ class TransferInvoiceItem(Base):
|
|||||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
precheck: Mapped[TransferPrecheck] = relationship(back_populates='items')
|
matching: Mapped[TransferMatching] = relationship(back_populates='items')
|
||||||
run: Mapped[Optional[TransferRun]] = relationship(back_populates='items')
|
run: Mapped[Optional[TransferRun]] = relationship(back_populates='items')
|
||||||
attempts: Mapped[list['TransferAttempt']] = relationship(
|
attempts: Mapped[list['TransferAttempt']] = relationship(
|
||||||
back_populates='item', cascade='all, delete-orphan',
|
back_populates='item', cascade='all, delete-orphan',
|
||||||
)
|
)
|
||||||
|
# 所属单(D14/D18):行随单执行推进;人工关闭调拨单(cancelled)时行脱离
|
||||||
|
# (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):
|
||||||
|
"""一张 ERP 调拨单(单):五元组一组一单;doc_no/submit_timestamp 终身复用(D3)。
|
||||||
|
|
||||||
|
防双单(D7/D15):同五元组至多一张未完结单,由部分唯一索引
|
||||||
|
uq_transfer_documents_group_live 在 DB 层强制(并发提交竞态兜底;
|
||||||
|
竞态方捕获 IntegrityError 后按同组复用重试);终态单(success/
|
||||||
|
duplicate_success/cancelled)不占组锁。status 由
|
||||||
|
ck_transfer_documents_status CHECK 兜底(非法态 fail-closed)。
|
||||||
|
本表不存行集快照(D14:完整行集随写 Attempt 的 request_snapshot_json
|
||||||
|
留档);closed_reason 为人工关闭原因(D18,审计之外的可视留档,
|
||||||
|
仅失败单关闭时写入)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = 'transfer_documents'
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint('doc_no', name='uq_transfer_documents_doc_no'),
|
||||||
|
UniqueConstraint('submit_timestamp', name='uq_transfer_documents_submit_timestamp'),
|
||||||
|
# 状态冻结枚举 DB 兜底(D15 纵深):组锁 WHERE 依赖状态字面量逐字匹配,
|
||||||
|
# 非法态必须在 DB 层拒绝(fail-closed),生成口径同 TRANSFER_DOCUMENT_STATUSES。
|
||||||
|
CheckConstraint(
|
||||||
|
f"status IN ({', '.join(repr(s) for s in TRANSFER_DOCUMENT_STATUSES)})",
|
||||||
|
name='ck_transfer_documents_status',
|
||||||
|
),
|
||||||
|
# D15 防线:同组至多一张未完结单,由 DB 强制(并发提交竞态兜底;竞态方
|
||||||
|
# 捕获 IntegrityError 按复用重试)。WHERE 子句由 UNRESOLVED_DOC_STATUSES
|
||||||
|
# 生成;同时声明 postgresql_where/sqlite_where,保证 PG 与测试 SQLite
|
||||||
|
# 建表同语义(部分唯一,非全组唯一)。
|
||||||
|
Index(
|
||||||
|
'uq_transfer_documents_group_live',
|
||||||
|
'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),
|
||||||
|
),
|
||||||
|
Index('ix_transfer_documents_run_status', 'run_id', 'status'),
|
||||||
|
Index('ix_transfer_documents_erp_no', 'erp_document_no'),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
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)
|
||||||
|
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 终身复用):同组复用单时保持首建值不变;唯一性由
|
||||||
|
# uq_transfer_documents_doc_no / uq_transfer_documents_submit_timestamp 强制。
|
||||||
|
doc_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
submit_timestamp: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
status: Mapped[str] = mapped_column(
|
||||||
|
String(32), nullable=False, default='pending', server_default='pending',
|
||||||
|
)
|
||||||
|
# 写中间表成功时刻(D7② 末步跳过依据)。
|
||||||
|
stage_confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
erp_document_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
|
# D18 人工关闭原因(仅失败单可关闭,状态 → cancelled 以释放组锁)。
|
||||||
|
closed_reason: Mapped[Optional[str]] = mapped_column(Text, 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,
|
||||||
|
)
|
||||||
|
|
||||||
|
items: Mapped[list['TransferInvoiceItem']] = relationship(back_populates='document')
|
||||||
|
attempts: Mapped[list['TransferAttempt']] = relationship(back_populates='document')
|
||||||
|
# 只读投影关系(评审修正轮 ①):按 run_id 取现任 Run(Task 17 已执行单投影
|
||||||
|
# serialize_executed_order / 关闭调拨单审计需要 run_no)。单向 relationship 不带
|
||||||
|
# back_populates,避免与 TransferRun.items 环纠缠;纯 ORM 增量,无迁移。
|
||||||
|
run: Mapped[Optional['TransferRun']] = relationship(foreign_keys=[run_id])
|
||||||
|
|
||||||
|
|
||||||
class TransferAttempt(Base):
|
class TransferAttempt(Base):
|
||||||
@@ -274,6 +402,10 @@ class TransferAttempt(Base):
|
|||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
item_id: Mapped[int] = mapped_column(ForeignKey('transfer_invoice_items.id'), nullable=False)
|
item_id: Mapped[int] = mapped_column(ForeignKey('transfer_invoice_items.id'), nullable=False)
|
||||||
|
# 单据级外键(D14:单:Attempt=1:N,外键在 Attempt 侧)。语义与 item_id 并存:
|
||||||
|
# 写 Attempt(external_write)挂单(document_id=单 id),其 request_snapshot_json
|
||||||
|
# 必须含单字段+完整行集;重查 Attempt(external_query)仍只挂 item,不挂单。
|
||||||
|
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('transfer_documents.id'), nullable=True)
|
||||||
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||||
kind: Mapped[str] = mapped_column(String(16), nullable=False)
|
kind: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
||||||
@@ -287,6 +419,7 @@ class TransferAttempt(Base):
|
|||||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
item: Mapped[TransferInvoiceItem] = relationship(back_populates='attempts')
|
item: Mapped[TransferInvoiceItem] = relationship(back_populates='attempts')
|
||||||
|
document: Mapped[Optional['TransferDocument']] = relationship(back_populates='attempts')
|
||||||
|
|
||||||
|
|
||||||
class TransferAuditEvent(Base):
|
class TransferAuditEvent(Base):
|
||||||
@@ -314,7 +447,7 @@ class TransferAuditEvent(Base):
|
|||||||
aggregate_type: Mapped[str] = mapped_column(String(64), nullable=False)
|
aggregate_type: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
aggregate_id: Mapped[str] = mapped_column(String(128), nullable=False)
|
aggregate_id: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
precheck_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
matching_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
invoice_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
invoice_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
item_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
item_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
attempt_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
attempt_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||||
@@ -363,6 +496,146 @@ class TransferArchive(Base):
|
|||||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class TransferTypeConfig(Base):
|
||||||
|
"""调拨类型配置(ADR 0002):编码/四语言名称/启停/排序 + 范围规则/仓库定义/转换规则。
|
||||||
|
|
||||||
|
code 创建后不可变(transfer_runs.transfer_type 引用);只有停用没有删除;
|
||||||
|
配置为空时匹配链路 fail-closed(TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = 'transfer_type_configs'
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint('code', name='uq_transfer_type_configs_code'),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
names_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
|
||||||
|
enabled: Mapped[bool] = mapped_column(default=False, server_default=text('false'), nullable=False)
|
||||||
|
sort_order: Mapped[int] = mapped_column(Integer, default=0, server_default=text('0'), nullable=False)
|
||||||
|
scope_rules_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
|
||||||
|
warehouse_config_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
|
||||||
|
transform_rules_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
|
||||||
|
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
|
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||||
|
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class TransferMovementLedger(Base):
|
||||||
|
"""库存异动档(ADR 0001):外部系统入站/出站记录的平台镜像(参照 ERP inaj_t 形态)。
|
||||||
|
|
||||||
|
用途:外部系统入站(一期)/出站(结构就位,record_kind='outbound')记录统一落档;
|
||||||
|
匹配明细(items)由匹配创建时从档圈定生成(落地不再写 items,出生翻转)。
|
||||||
|
幂等增量落地:自然键 (source_code, record_kind, doc_no, line_no, line_seq,
|
||||||
|
in_out_flag, carton_id, lot_no, external_doc_no, external_line_no) 唯一约束
|
||||||
|
去重——不存在则插入、证据变化则原行更新、文件缺席不删(tt14 扩维:真实 WMS
|
||||||
|
行身份=单据+行+箱/批,carton_id/lot_no 加入键防同箱/批塌缩丢行;R7 终审:
|
||||||
|
两列同步 NOT NULL + default '',nullable 成分的 NULL 不参与 PG/SQLite 唯一
|
||||||
|
比对会逃逸约束,空值成分一律以空串入库保证唯一约束可比;2026-10-21 再扩维:
|
||||||
|
外部单号/外部项次=WMS Order #/Line # 入键,外部单据身份作为档幂等主键管控);
|
||||||
|
已执行记录 transfer_executed=true 封存(executed_doc_no 回写),永不更新、
|
||||||
|
永不复活、永不再次被圈定(防二次调拨,档级封存兜底)。
|
||||||
|
刻意双字段:record_kind(文件种类声明,权威)与 in_out_flag(数据列原值),
|
||||||
|
两者矛盾即解析错位,由落档链路打审计事件,记录照常落档。
|
||||||
|
可空语义:自然键 8 成分一律 NOT NULL(line_seq/in_out_flag/carton_id/lot_no
|
||||||
|
default '' 保证唯一约束可比、防 PG NULL 逃逸唯一比对),业务/证据列一律
|
||||||
|
nullable(外部列宽松落地);movement_date 可空——空值记录照常落档但不进
|
||||||
|
异动日期圈定(日期条件恒排除 NULL)。
|
||||||
|
source_file_id ON DELETE SET NULL:来源文件被清理(文件资产保留策略)后
|
||||||
|
档记录必须留存(事实不随文件消失,链接仅溯源)。
|
||||||
|
D 组 ⭐5 列(order_type/odm_id/odm_name/carton_id/pallet_id)为本期新增强
|
||||||
|
业务字段(进解析 Profile 可映射);🔖预留列(doc_nature/movement_type/
|
||||||
|
reason_code/source_ref_no/partner_code/remark)出货报告确认后直接映射,
|
||||||
|
免后续迁移。
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = 'transfer_movement_ledger'
|
||||||
|
__table_args__ = (
|
||||||
|
# 自然键唯一(幂等增量落地兜底;应用层按自然键查档先行)。tt14 扩维 8 成分:
|
||||||
|
# carton_id/lot_no 进键(真实 WMS 行身份=单据+行+箱/批),R7 终审同步
|
||||||
|
# NOT NULL + default ''(可空成分以空串入库,防 PG NULL 逃逸唯一比对)。
|
||||||
|
# 2026-10-21 扩维 10 成分:external_doc_no/external_line_no(外部单号/
|
||||||
|
# 外部项次,WMS Order #/Line #)进键——外部单据身份作为档幂等主键管控,
|
||||||
|
# 同一外部单号+项次的重复落档/证据更新收敛到同一档行(存量行以空串参与
|
||||||
|
# 键;配置外部映射后重放同文件即按新键收敛,必要时走清空并重解析重建)。
|
||||||
|
UniqueConstraint(
|
||||||
|
'source_code', 'record_kind', 'doc_no', 'line_no', 'line_seq', 'in_out_flag',
|
||||||
|
'carton_id', 'lot_no', 'external_doc_no', 'external_line_no',
|
||||||
|
name='uq_transfer_movement_ledger_natural_key',
|
||||||
|
),
|
||||||
|
# 匹配创建圈档主路径:来源 + 记录种类 + 异动日期范围扫描。
|
||||||
|
Index('ix_transfer_movement_ledger_source_kind_date', 'source_code', 'record_kind', 'movement_date'),
|
||||||
|
# 档级封存/待匹配桶扫描:按记录种类过滤已执行位。
|
||||||
|
Index('ix_transfer_movement_ledger_kind_executed', 'record_kind', 'transfer_executed'),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
# --- A 单据标识(自然键成分,NOT NULL;line_seq/in_out_flag 可空成分 default '')---
|
||||||
|
doc_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
line_no: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||||
|
line_seq: Mapped[str] = mapped_column(String(32), nullable=False, default='', server_default='')
|
||||||
|
# 数据列原值(入站=收发标记),与 record_kind 交叉校验用,不参与权威判定。
|
||||||
|
in_out_flag: Mapped[str] = mapped_column(String(8), nullable=False, default='', server_default='')
|
||||||
|
# --- A+ 外部单据身份(2026-10-21 起入自然键:外部单号/外部项次 = WMS Order #/
|
||||||
|
# --- 行号;NOT NULL + default '' 与 line_seq 同口径,防 NULL 逃逸唯一比对)---
|
||||||
|
external_doc_no: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
||||||
|
external_line_no: Mapped[str] = mapped_column(String(32), nullable=False, default='', server_default='')
|
||||||
|
# --- B 物料与数量(数量 Decimal 文本,与 items.movement_quantity 同约定)---
|
||||||
|
material_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
material_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||||
|
specification: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||||
|
# 批号原值(tt14 起入自然键:NOT NULL + default '' 防 PG NULL 逃逸唯一比对;
|
||||||
|
# 空值成分以空串入库保证唯一约束可比,与 line_seq/in_out_flag 同口径)。
|
||||||
|
lot_no: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
||||||
|
quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||||
|
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||||
|
# --- C 仓储与日期(movement_date 可空:空值不进异动日期圈定)---
|
||||||
|
warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
storage_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
movement_date: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||||||
|
# --- D 业务属性(⭐本期新增强业务字段;carton_id tt14 起入自然键 NOT NULL
|
||||||
|
# --- default '';🔖预留列 nullable,出货侧直接映射)---
|
||||||
|
order_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
odm_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
odm_name: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||||
|
# 箱号(tt14 起入自然键:NOT NULL + default '',与 lot_no 同口径,防 NULL 逃逸唯一比对)。
|
||||||
|
carton_id: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
||||||
|
pallet_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
doc_nature: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
movement_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
reason_code: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||||
|
source_ref_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
partner_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
|
# --- E 平台溯源(证据字段:evidence_sync 原行更新时整体换新)---
|
||||||
|
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
# 文件种类声明(tt14 值迁移后 'inbound'/'outbound',权威);与 in_out_flag 矛盾打审计事件。
|
||||||
|
record_kind: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||||
|
# 来源文件溯源:ON DELETE SET NULL(文件清理后档事实留存)。
|
||||||
|
source_file_id: Mapped[Optional[int]] = mapped_column(
|
||||||
|
ForeignKey('freight_rpa_inbound_report_files.id', ondelete='SET NULL'), nullable=True,
|
||||||
|
)
|
||||||
|
file_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
sheet_name: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||||
|
row_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||||
|
)
|
||||||
|
# --- F 平台回写(档级封存:票据执行成功落单号时回写,永不解除)---
|
||||||
|
transfer_executed: Mapped[bool] = mapped_column(
|
||||||
|
default=False, server_default=text('false'), nullable=False,
|
||||||
|
)
|
||||||
|
executed_doc_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
|
|
||||||
|
# 溯源关系:档案行 → FreightRpaInboundReportFile 原样归档文件(单向,不回挂;FreightRpaInboundReportFile
|
||||||
|
# 不感知调拨域,避免跨域 back_populates 环)。
|
||||||
|
source_file: Mapped[Optional['FreightRpaInboundReportFile']] = relationship()
|
||||||
|
|
||||||
|
|
||||||
@event.listens_for(TransferAuditEvent, 'before_update')
|
@event.listens_for(TransferAuditEvent, 'before_update')
|
||||||
def _reject_transfer_audit_update(_mapper, _connection, _target) -> None:
|
def _reject_transfer_audit_update(_mapper, _connection, _target) -> None:
|
||||||
"""拒绝 ORM 更新,确保审计事件不可改写。"""
|
"""拒绝 ORM 更新,确保审计事件不可改写。"""
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
"""models/integration_connector.py
|
"""models/integration_connector.py
|
||||||
|
|
||||||
用途:Integration Connector(外部系统连接器框架)P1 配置与运行时模型:
|
用途:Integration Connector(外部系统连接器框架)配置与运行时模型:
|
||||||
CredentialReference、ClientInstance、InterfaceDefinition、Binding、Call。
|
CredentialReference、ClientInstance、InterfaceDefinition、Binding、Call。
|
||||||
依赖:models.base.Base、SQLAlchemy 2.0 ORM。
|
依赖:models.base.Base、SQLAlchemy 2.0 ORM。
|
||||||
逻辑:配置层实体(CredentialReference/ClientInstance/InterfaceDefinition/Binding)
|
逻辑:配置层实体(CredentialReference/ClientInstance/InterfaceDefinition/Binding)
|
||||||
维护版本与状态;IntegrationCall 记录一次技术调用事实(冻结绑定版本 + 脱敏摘要)。
|
维护版本与状态;IntegrationCall 记录一次技术调用事实(冻结绑定版本 + 脱敏摘要)。
|
||||||
连接器类型(rest/soap)与状态均用 CheckConstraint 兜底,fail-closed 语义在服务层。
|
连接器类型(rest/soap/database)与状态均用 CheckConstraint 兜底;database 客户端
|
||||||
|
另有 db_kind 专列(mysql/oracle/sqlserver/postgresql),fail-closed 语义在服务层。
|
||||||
|
Binding.steps_json 表达一对多有序接口配方(D10);旧单步列保留至 P2。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -31,8 +33,10 @@ from sqlalchemy.dialects.postgresql import JSONB
|
|||||||
|
|
||||||
from app.models.base import Base
|
from app.models.base import Base
|
||||||
|
|
||||||
# P1 仅落地 REST/SOAP;后续扩 RPA/SQL/FILE 时放宽约束并新建迁移。
|
# 连接器类型白名单;模型 CHECK 由本常量动态生成,扩枚举须配套 Alembic 迁移重建 CHECK。
|
||||||
CONNECTOR_TYPES = ('rest', 'soap')
|
CONNECTOR_TYPES = ('rest', 'soap', 'database')
|
||||||
|
# database 专属库种(D16):专列 db_kind,非 config_json;API/transport 同源 fail-closed。
|
||||||
|
DB_KINDS = ('mysql', 'oracle', 'sqlserver', 'postgresql')
|
||||||
CONFIG_STATUSES = ('draft', 'published', 'retired')
|
CONFIG_STATUSES = ('draft', 'published', 'retired')
|
||||||
CREDENTIAL_STATUSES = ('active', 'rotating', 'retired')
|
CREDENTIAL_STATUSES = ('active', 'rotating', 'retired')
|
||||||
|
|
||||||
@@ -89,9 +93,12 @@ class IntegrationClientInstance(Base):
|
|||||||
connector_type: Mapped[str] = mapped_column(String(16), nullable=False)
|
connector_type: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||||
environment: Mapped[str] = mapped_column(String(16), nullable=False, default='prod', server_default='prod')
|
environment: Mapped[str] = mapped_column(String(16), nullable=False, default='prod', server_default='prod')
|
||||||
# 关键强类型字段独立列(JSON 保留作兜底;兼容层 binding.py 拼回 dict)。
|
# 关键强类型字段独立列(JSON 保留作兜底;兼容层 binding.py 拼回 dict)。
|
||||||
# endpoint = 连接地址:REST 为接口基地址,SOAP 为 WSDL 地址(WSDL 内含服务端点)。
|
# endpoint = 连接地址:REST 为接口基地址,SOAP 为 WSDL 地址(WSDL 内含服务端点);
|
||||||
|
# database 为 host:port[/database|service_name]。
|
||||||
endpoint: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
|
endpoint: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
|
||||||
timeout_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
timeout_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||||
|
# database 专属库种(仅 connector_type='database' 有值;rest/soap 为 NULL)。
|
||||||
|
db_kind: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||||
config_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
config_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||||
credential_ref_code: Mapped[Optional[str]] = mapped_column(
|
credential_ref_code: Mapped[Optional[str]] = mapped_column(
|
||||||
ForeignKey('integration_credential_references.code'), nullable=True,
|
ForeignKey('integration_credential_references.code'), nullable=True,
|
||||||
@@ -144,7 +151,12 @@ class IntegrationInterfaceDefinition(Base):
|
|||||||
|
|
||||||
|
|
||||||
class IntegrationBinding(Base):
|
class IntegrationBinding(Base):
|
||||||
"""绑定:(Capability, context_selector) → 客户端 + 接口 + 映射版本;版本化、可发布、可退役。"""
|
"""绑定:(Capability, context_selector) → 有序接口步骤配方;版本化、可发布、可退役。
|
||||||
|
|
||||||
|
一对多有序(D10/D13):steps_json = [{interface_code, param_mapping_json}, ...];
|
||||||
|
每步客户端由接口归属自带。旧列 interface_definition_code / param_mapping_json /
|
||||||
|
client_instance_code 迁移后保留镜像首步,解析不再读取,P2 删除。
|
||||||
|
"""
|
||||||
|
|
||||||
__tablename__ = 'integration_bindings'
|
__tablename__ = 'integration_bindings'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
@@ -165,8 +177,11 @@ class IntegrationBinding(Base):
|
|||||||
capability: Mapped[str] = mapped_column(String(128), nullable=False)
|
capability: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||||
# 路由条件(来源/组织/租户等键值对;空对象 = 默认绑定):须为调用 context 的子集才命中。
|
# 路由条件(来源/组织/租户等键值对;空对象 = 默认绑定):须为调用 context 的子集才命中。
|
||||||
context_selector_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict)
|
context_selector_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict)
|
||||||
# 域参数 → 接口参数的声明式映射(map_response 规范:{接口参数: {expr/template/transform/args}});
|
# 有序步骤配方:每步 {interface_code, param_mapping_json};客户端由接口归属推导。
|
||||||
# 空对象 = 域参数同名直通。结构属绑定(capability↔接口的翻译契约),不属接口定义。
|
steps_json: Mapped[list[dict[str, Any]]] = mapped_column(
|
||||||
|
CONTEXT_SELECTOR_JSON, nullable=False, default=list,
|
||||||
|
)
|
||||||
|
# 域参数 → 接口参数的声明式映射(旧单步列,P2 删;迁移后镜像 steps_json[0])。
|
||||||
# 与 context_selector_json 同用 JSONB variant(PostgreSQL)保持表内 JSON 列类型一致。
|
# 与 context_selector_json 同用 JSONB variant(PostgreSQL)保持表内 JSON 列类型一致。
|
||||||
param_mapping_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict)
|
param_mapping_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict)
|
||||||
client_instance_code: Mapped[str] = mapped_column(
|
client_instance_code: Mapped[str] = mapped_column(
|
||||||
@@ -188,13 +203,20 @@ class IntegrationBinding(Base):
|
|||||||
|
|
||||||
|
|
||||||
class IntegrationCall(Base):
|
class IntegrationCall(Base):
|
||||||
"""一次技术调用事实:冻结绑定版本 + 脱敏请求/响应摘要,供审计与追溯。"""
|
"""一次技术调用事实:冻结绑定版本 + 脱敏请求/响应摘要,供审计与追溯。
|
||||||
|
|
||||||
|
多步顺序引擎(Task 4)一次能力调用按步骤落 N 条审计、共享同一 operation_id
|
||||||
|
(一票一次执行 = N 条,按 operation_id 串联 + binding_snapshot_json.step_index
|
||||||
|
定位),故 operation_id 无唯一约束;原唯一约束兼作的索引由普通索引
|
||||||
|
ix_integration_calls_operation_id 补回(迁移 tt5b6c7d8e9f)。
|
||||||
|
"""
|
||||||
|
|
||||||
__tablename__ = 'integration_calls'
|
__tablename__ = 'integration_calls'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint('operation_id', name='uq_integration_calls_operation_id'),
|
Index('ix_integration_calls_operation_id', 'operation_id'),
|
||||||
Index('ix_integration_calls_capability_created', 'capability', 'created_at'),
|
Index('ix_integration_calls_capability_created', 'capability', 'created_at'),
|
||||||
Index('ix_integration_calls_trace_id', 'trace_id'),
|
Index('ix_integration_calls_trace_id', 'trace_id'),
|
||||||
|
Index('ix_integration_calls_business_ref', 'business_ref'),
|
||||||
)
|
)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
@@ -206,4 +228,9 @@ class IntegrationCall(Base):
|
|||||||
status: Mapped[str] = mapped_column(String(32), nullable=False)
|
status: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||||
elapsed_ms: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
|
elapsed_ms: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
|
||||||
trace_id: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
trace_id: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
||||||
|
# 线级事实(database 最终 SQL/绑定/行数;soap endpoint+XML;rest HTTP 往返)。
|
||||||
|
# 可空:历史行与未捕获场景为 NULL,前台如实展示。
|
||||||
|
wire_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||||
|
# 通用业务锚点:调用方透传的业务单号/任务号(能力无关;不传为 NULL)。
|
||||||
|
business_ref: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
backend/app/models/job.py
|
backend/app/models/job.py
|
||||||
|
|
||||||
用途:通用后台任务模型,承载跨业务域的异步任务执行状态。
|
用途:通用后台任务模型,承载跨业务域的异步任务执行状态。
|
||||||
依赖:models.base.Base。
|
依赖:models.base.Base;候选集外键指向 shipping_onhand_candidate_sets。
|
||||||
逻辑:由 app.jobs.queue 写入和领取,由 worker 分发到具体业务 handler;业务模型保存业务状态,本表保存执行状态、锁、重试与结果。
|
逻辑:由 app.jobs.queue 写入和领取,由 worker 分发到具体业务 handler;业务模型保存业务状态,本表保存执行状态、锁、重试与结果。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -149,7 +149,7 @@ class Job(Base):
|
|||||||
ForeignKey('shipping_process_gates.id'), nullable=True, index=True,
|
ForeignKey('shipping_process_gates.id'), nullable=True, index=True,
|
||||||
)
|
)
|
||||||
candidate_set_id: Mapped[Optional[int]] = mapped_column(
|
candidate_set_id: Mapped[Optional[int]] = mapped_column(
|
||||||
ForeignKey('shipping_inventory_candidate_sets.id'), nullable=True, index=True,
|
ForeignKey('shipping_onhand_candidate_sets.id'), nullable=True, index=True,
|
||||||
)
|
)
|
||||||
fencing_token: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
fencing_token: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||||
|
|||||||
@@ -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,60 @@
|
|||||||
|
"""
|
||||||
|
models/permission_role.py
|
||||||
|
|
||||||
|
用途:可配置权限组(角色包)、角色与 Agent、用户与角色的授权关系。
|
||||||
|
依赖:models.base.Base、agents、users。
|
||||||
|
逻辑:Admin 角色配置读写本表;一个用户可挂多个业务角色,经 user_permission_roles 关联。
|
||||||
|
users.role 只保留排序最前的主角色,供旧查询兼容;运行时按全部角色取并集后再同步到 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),
|
||||||
|
)
|
||||||
|
|
||||||
|
user_permission_roles = db.Table(
|
||||||
|
'user_permission_roles',
|
||||||
|
db.Column('user_id', ForeignKey('users.id', ondelete='CASCADE'), primary_key=True),
|
||||||
|
db.Column('role_id', ForeignKey('permission_roles.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
|
backend/app/models/shipping.py
|
||||||
|
|
||||||
用途:货代发货通知正式 Notice(shipping_notices)、事件、库存文件、接入记录、文档/候选与库存映射模型。
|
用途:货代发货通知正式 Notice(shipping_notices)、事件、在手报表文件(freight_rpa_onhand_report_files,s18 起归 RPA,列仍含解析行与快照状态)、任务关联(shipping_task_onhand_links)、接入记录与文档/候选模型。
|
||||||
依赖:models.base.Base;规范订单行见 shipping_task_line;建单前 OT 见 shipping_order_task。
|
依赖:models.base.Base;规范订单行见 shipping_task_line;建单前 OT 见 shipping_order_task。
|
||||||
逻辑:co8e9f0a1b2c 已物理 DROP shipping_batches 及全表 batch_id / consumed_batch_id 列;
|
逻辑:co8e9f0a1b2c 已物理 DROP shipping_batches 及全表 batch_id / consumed_batch_id 列;
|
||||||
Intake 消费绑定仅保留 consumed_task_id / consumed_at;upload_batch_id 为上传边界批次(非 shipping_batches);
|
Intake 消费绑定仅保留 consumed_task_id / consumed_at;upload_batch_id 为上传边界批次(非 shipping_batches);
|
||||||
@@ -164,108 +164,15 @@ class ShippingTaskPurgeAudit(Base):
|
|||||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryFile(Base):
|
class ShippingTaskOnhandLink(Base):
|
||||||
"""货代发货批次库存快照文件,承载一次上传后可被多票任务共用的库存数据。"""
|
|
||||||
|
|
||||||
__tablename__ = 'shipping_inventory_files'
|
|
||||||
__table_args__ = (
|
|
||||||
Index('ix_shipping_inventory_files_user_created', 'user_id', 'created_at'),
|
|
||||||
Index(
|
|
||||||
'ix_shipping_inventory_files_source_snapshot',
|
|
||||||
'source_code',
|
|
||||||
'warehouse_id',
|
|
||||||
'snapshot_status',
|
|
||||||
'exported_at',
|
|
||||||
),
|
|
||||||
Index(
|
|
||||||
'ix_shipping_inventory_files_source_warehouse',
|
|
||||||
'source_code',
|
|
||||||
'warehouse_id',
|
|
||||||
),
|
|
||||||
Index(
|
|
||||||
'uq_shipping_inventory_files_rpa_identity_ready',
|
|
||||||
'rpa_run_no',
|
|
||||||
'source_code',
|
|
||||||
'warehouse_id',
|
|
||||||
unique=True,
|
|
||||||
postgresql_where=text(
|
|
||||||
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
|
|
||||||
"AND source_code IS NOT NULL AND warehouse_id IS NOT NULL"
|
|
||||||
),
|
|
||||||
sqlite_where=text(
|
|
||||||
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
|
|
||||||
"AND source_code IS NOT NULL AND warehouse_id IS NOT NULL"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
# 动态多仓文件没有单一 Warehouse;按 RPA run + Source 保证回调重放幂等。
|
|
||||||
Index(
|
|
||||||
'uq_shipping_inventory_files_rpa_dynamic_source_ready',
|
|
||||||
'rpa_run_no',
|
|
||||||
'source_code',
|
|
||||||
unique=True,
|
|
||||||
postgresql_where=text(
|
|
||||||
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
|
|
||||||
"AND source_code IS NOT NULL AND warehouse_id IS NULL"
|
|
||||||
),
|
|
||||||
sqlite_where=text(
|
|
||||||
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
|
|
||||||
"AND source_code IS NOT NULL AND warehouse_id IS NULL"
|
|
||||||
),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
|
||||||
inventory_file_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
|
||||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
|
|
||||||
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
|
||||||
storage_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
|
||||||
schema_preview_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
|
||||||
field_mapping_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
|
||||||
mapping_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
|
||||||
mapping_confirmed: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
|
|
||||||
inventory_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
|
||||||
line_count: Mapped[int] = mapped_column(Integer, default=0)
|
|
||||||
share_mode: Mapped[str] = mapped_column(String(32), default='task_only')
|
|
||||||
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
|
||||||
warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
|
||||||
source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
|
||||||
identity_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
|
|
||||||
source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
|
||||||
source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
|
||||||
snapshot_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
|
|
||||||
exported_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
|
|
||||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
|
|
||||||
rpa_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
|
||||||
schedule_run_id: Mapped[Optional[int]] = mapped_column(nullable=True, index=True)
|
|
||||||
source_query_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
|
||||||
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True)
|
|
||||||
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
|
||||||
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
|
|
||||||
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
|
|
||||||
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
|
||||||
file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
|
||||||
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
|
||||||
mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
|
||||||
operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
|
||||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
|
||||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
|
||||||
|
|
||||||
links: Mapped[List['ShippingTaskInventoryLink']] = relationship(
|
|
||||||
'ShippingTaskInventoryLink',
|
|
||||||
back_populates='inventory_file',
|
|
||||||
cascade='all, delete-orphan',
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class ShippingTaskInventoryLink(Base):
|
|
||||||
"""发货任务与库存快照的关联记录,一期每个任务只保留一条 active link。"""
|
"""发货任务与库存快照的关联记录,一期每个任务只保留一条 active link。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_task_inventory_links'
|
__tablename__ = 'shipping_task_onhand_links'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
Index('ix_shipping_task_inventory_links_task_active', 'task_id', 'is_active'),
|
Index('ix_shipping_task_onhand_links_task_active', 'task_id', 'is_active'),
|
||||||
Index('ix_shipping_task_inventory_links_file_active', 'inventory_file_id', 'is_active'),
|
Index('ix_shipping_task_onhand_links_file_active', 'onhand_file_id', 'is_active'),
|
||||||
Index(
|
Index(
|
||||||
'ix_shipping_task_inventory_links_task_source',
|
'ix_shipping_task_onhand_links_task_source',
|
||||||
'task_id',
|
'task_id',
|
||||||
'matched_source_code',
|
'matched_source_code',
|
||||||
),
|
),
|
||||||
@@ -273,7 +180,7 @@ class ShippingTaskInventoryLink(Base):
|
|||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), index=True)
|
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'), index=True)
|
||||||
inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id'), index=True)
|
onhand_file_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id'), index=True)
|
||||||
link_role: Mapped[str] = mapped_column(String(32), default='member')
|
link_role: Mapped[str] = mapped_column(String(32), default='member')
|
||||||
access_mode: Mapped[str] = mapped_column(String(32), default='readonly')
|
access_mode: Mapped[str] = mapped_column(String(32), default='readonly')
|
||||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default=text('true'), index=True)
|
is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default=text('true'), index=True)
|
||||||
@@ -283,8 +190,8 @@ class ShippingTaskInventoryLink(Base):
|
|||||||
identity_check_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
identity_check_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||||
identity_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
identity_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
snapshot_age_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
snapshot_age_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||||
preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', use_alter=True), nullable=True, index=True)
|
preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_onhand_preparation_attempts.id', use_alter=True), nullable=True, index=True)
|
||||||
source_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_source_attempts.id', use_alter=True), nullable=True, index=True)
|
source_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_onhand_preparation_source_attempts.id', use_alter=True), nullable=True, index=True)
|
||||||
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
|
invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True)
|
||||||
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
|
invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True)
|
||||||
@@ -294,10 +201,10 @@ class ShippingTaskInventoryLink(Base):
|
|||||||
linked_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
linked_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||||
|
|
||||||
task: Mapped['ShippingOrderTask'] = relationship('ShippingOrderTask', foreign_keys=[task_id])
|
task: Mapped['ShippingOrderTask'] = relationship('ShippingOrderTask', foreign_keys=[task_id])
|
||||||
inventory_file: Mapped['ShippingInventoryFile'] = relationship(
|
inventory_file: Mapped['FreightRpaOnhandReportFile'] = relationship(
|
||||||
'ShippingInventoryFile',
|
'FreightRpaOnhandReportFile',
|
||||||
back_populates='links',
|
back_populates='links',
|
||||||
foreign_keys=[inventory_file_id],
|
foreign_keys=[onhand_file_id],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -30,8 +30,9 @@ class ShippingDocumentProfileAutoFreezeQualification(Base):
|
|||||||
"status IN ('manual_confirmation', 'auto_freeze_approved', 'auto_freeze_suspended')",
|
"status IN ('manual_confirmation', 'auto_freeze_approved', 'auto_freeze_suspended')",
|
||||||
name='ck_shipping_document_profile_auto_freeze_qualification_status',
|
name='ck_shipping_document_profile_auto_freeze_qualification_status',
|
||||||
),
|
),
|
||||||
|
# 索引名沿用迁移 0aa34b5c6d7e 的短名;PostgreSQL 标识符上限 63 字符,超长名会导致建库失败。
|
||||||
Index(
|
Index(
|
||||||
'ix_shipping_document_profile_auto_freeze_qualification_profile_status',
|
'ix_ship_doc_prof_auto_freeze_profile_status',
|
||||||
'profile_id', 'status',
|
'profile_id', 'status',
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
models/shipping_excel_template.py
|
models/shipping_excel_template.py
|
||||||
|
|
||||||
用途:定义版本化发货 Excel 模板及不可变 Notice 导出产物。
|
用途:定义版本化发货 Excel 模板及不可变 Notice 导出产物。
|
||||||
依赖:models.base.Base、库存源、订单 Schema、ShippingNotice 与库存快照模型。
|
依赖:models.base.Base、FreightRpaSource、订单 Schema、ShippingNotice、freight_rpa_parsing_profiles 与 freight_rpa_onhand_report_files。
|
||||||
逻辑:库存源只绑定已发布模板版本;每次生成均新增 Artifact 并锁定输入版本与校验和;
|
逻辑:库存源只绑定已发布模板版本;每次生成均新增 Artifact 并锁定输入版本与校验和;
|
||||||
co8e9f0a1b2c 已删除 export artifact 的 batch_id 列;Artifact 直接属于一张 Notice。
|
co8e9f0a1b2c 已删除 export artifact 的 batch_id 列;Artifact 直接属于一张 Notice。
|
||||||
"""
|
"""
|
||||||
@@ -44,7 +44,7 @@ class ShippingExcelTemplate(Base):
|
|||||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
|
|
||||||
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='excel_template')
|
sources: Mapped[list['FreightRpaSource']] = relationship(back_populates='excel_template')
|
||||||
|
|
||||||
|
|
||||||
class ShippingExportArtifact(Base):
|
class ShippingExportArtifact(Base):
|
||||||
@@ -62,8 +62,8 @@ class ShippingExportArtifact(Base):
|
|||||||
template_id: Mapped[int] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=False)
|
template_id: Mapped[int] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=False)
|
||||||
order_schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
|
order_schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
|
||||||
order_extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False)
|
order_extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False)
|
||||||
inventory_parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=False)
|
inventory_parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('freight_rpa_parsing_profiles.id'), nullable=False)
|
||||||
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True)
|
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id'), nullable=True)
|
||||||
input_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
|
input_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
file_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
file_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||||
file_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
file_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
backend/app/models/shipping_fulfillment.py
|
backend/app/models/shipping_fulfillment.py
|
||||||
|
|
||||||
用途:保存预约单全局注册、每轮库存核验和 Excel 对预约单的不可重叠归属。
|
用途:保存预约单全局注册、每轮库存核验和 Excel 对预约单的不可重叠归属。
|
||||||
依赖:冻结订单 Snapshot、库存文件、导出 Artifact 与 SQLAlchemy Base;Notice 主表 shipping_notices。
|
依赖:冻结订单 Snapshot、freight_rpa_onhand_report_files、导出 Artifact 与 SQLAlchemy Base;核验表 shipping_notice_onhand_verifications / shipping_notice_onhand_verification_lines;Notice 主表 shipping_notices。
|
||||||
逻辑:Snapshot 行可保留历史预约号;全局 Reservation 决定当前有效行和履约状态,核验与 Artifact 行均追加保存。
|
逻辑:Snapshot 行可保留历史预约号;全局 Reservation 决定当前有效行和履约状态,核验与 Artifact 行均追加保存。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -46,53 +46,53 @@ class ShippingReservation(Base):
|
|||||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryVerification(Base):
|
class ShippingOnhandVerification(Base):
|
||||||
"""一次任务库存核验的不可变轮次,绑定当时有效库存快照。"""
|
"""一次任务库存核验的不可变轮次,绑定当时有效库存快照。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_notice_inventory_verifications'
|
__tablename__ = 'shipping_notice_onhand_verifications'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
CheckConstraint(
|
CheckConstraint(
|
||||||
"status IN ('completed', 'expired', 'superseded')",
|
"status IN ('completed', 'expired', 'superseded')",
|
||||||
name='ck_shipping_notice_inventory_verifications_status',
|
name='ck_shipping_notice_onhand_verifications_status',
|
||||||
),
|
),
|
||||||
Index('ix_shipping_notice_inventory_verifications_task_created', 'task_id', 'created_at'),
|
Index('ix_shipping_notice_onhand_verifications_task_created', 'task_id', 'created_at'),
|
||||||
)
|
)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False)
|
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False)
|
||||||
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True)
|
onhand_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('freight_rpa_onhand_report_files.id'), nullable=True)
|
||||||
source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', ondelete='SET NULL'), nullable=True, index=True)
|
preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_onhand_preparation_attempts.id', ondelete='SET NULL'), nullable=True, index=True)
|
||||||
matching_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True, index=True)
|
matching_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True, index=True)
|
||||||
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||||
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_inventory_verifications.id'), nullable=True)
|
superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_onhand_verifications.id'), nullable=True)
|
||||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='completed', server_default='completed')
|
status: Mapped[str] = mapped_column(String(16), nullable=False, default='completed', server_default='completed')
|
||||||
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
lines: Mapped[list['ShippingInventoryVerificationLine']] = relationship(
|
lines: Mapped[list['ShippingOnhandVerificationLine']] = relationship(
|
||||||
back_populates='verification', cascade='all, delete-orphan', order_by='ShippingInventoryVerificationLine.id',
|
back_populates='verification', cascade='all, delete-orphan', order_by='ShippingOnhandVerificationLine.id',
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class ShippingInventoryVerificationLine(Base):
|
class ShippingOnhandVerificationLine(Base):
|
||||||
"""一个预约单在一轮库存中的需求、可用数量和确定性结果。"""
|
"""一个预约单在一轮库存中的需求、可用数量和确定性结果。"""
|
||||||
|
|
||||||
__tablename__ = 'shipping_notice_inventory_verification_lines'
|
__tablename__ = 'shipping_notice_onhand_verification_lines'
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
UniqueConstraint(
|
UniqueConstraint(
|
||||||
'verification_id', 'reservation_id',
|
'verification_id', 'reservation_id',
|
||||||
name='uq_shipping_notice_inventory_verification_lines_reservation',
|
name='uq_shipping_notice_onhand_verification_lines_reservation',
|
||||||
),
|
),
|
||||||
CheckConstraint(
|
CheckConstraint(
|
||||||
"status IN ('available', 'shortage', 'invalid')",
|
"status IN ('available', 'shortage', 'invalid')",
|
||||||
name='ck_shipping_notice_inventory_verification_lines_status',
|
name='ck_shipping_notice_onhand_verification_lines_status',
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
verification_id: Mapped[int] = mapped_column(
|
verification_id: Mapped[int] = mapped_column(
|
||||||
ForeignKey('shipping_notice_inventory_verifications.id', ondelete='CASCADE'), nullable=False,
|
ForeignKey('shipping_notice_onhand_verifications.id', ondelete='CASCADE'), nullable=False,
|
||||||
)
|
)
|
||||||
reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False)
|
reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False)
|
||||||
required_qty: Mapped[Decimal] = mapped_column(Numeric(24, 8), nullable=False)
|
required_qty: Mapped[Decimal] = mapped_column(Numeric(24, 8), nullable=False)
|
||||||
@@ -100,7 +100,7 @@ class ShippingInventoryVerificationLine(Base):
|
|||||||
status: Mapped[str] = mapped_column(String(16), nullable=False)
|
status: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||||
detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||||
|
|
||||||
verification: Mapped['ShippingInventoryVerification'] = relationship(back_populates='lines')
|
verification: Mapped['ShippingOnhandVerification'] = relationship(back_populates='lines')
|
||||||
|
|
||||||
|
|
||||||
class ShippingExportArtifactLine(Base):
|
class ShippingExportArtifactLine(Base):
|
||||||
@@ -120,7 +120,7 @@ class ShippingExportArtifactLine(Base):
|
|||||||
)
|
)
|
||||||
reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False)
|
reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_reservations.id'), nullable=False)
|
||||||
verification_line_id: Mapped[int] = mapped_column(
|
verification_line_id: Mapped[int] = mapped_column(
|
||||||
ForeignKey('shipping_notice_inventory_verification_lines.id'), nullable=False,
|
ForeignKey('shipping_notice_onhand_verification_lines.id'), nullable=False,
|
||||||
)
|
)
|
||||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||||
|
|
||||||
|
|||||||
Loaded 100 of 1339 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user