Compare commits
96
Commits
V26.9.1
...
chat-format
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
331a983476 | ||
|
|
55e56e4dc9 | ||
|
|
cdc8610ec1 | ||
|
|
9236f2949c | ||
|
|
6c47d0639c | ||
|
|
22bee49346 | ||
|
|
c27379d933 | ||
|
|
f7734c8ccb | ||
|
|
dde2093e06 | ||
|
|
e78f750db0 | ||
|
|
1efb165fd5 | ||
|
|
47ee68ed25 | ||
|
|
97059b336b | ||
|
|
a92df4c38d | ||
|
|
5f6fbcd76f | ||
|
|
d7d4819a42 | ||
|
|
041bb73b9a | ||
|
|
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 | ||
|
|
5faf86b184 | ||
|
|
298fadf1c8 | ||
|
|
36868f875c | ||
|
|
bb7e0977b8 | ||
|
|
7fb36b301c | ||
|
|
616034a4cd | ||
|
|
3de24fd373 | ||
|
|
49f6a0f222 | ||
|
|
a24bd94d43 | ||
|
|
de9db2ea77 | ||
|
|
590a21515a | ||
|
|
ed4a47ffba | ||
|
|
09603b334b | ||
|
|
ca9c174f29 | ||
|
|
cc41f8fe25 | ||
|
|
4445ff68d4 | ||
|
|
07e83132c0 | ||
|
|
55c6467d83 |
No files matched your search
@@ -1,70 +0,0 @@
|
||||
---
|
||||
description: 文件层与函数层注释强制规范(撰写与调整代码时均适用)
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# 代码注释(强制)
|
||||
|
||||
撰写或**修改**代码时,必须补齐或更新两层注释。完整说明见 `AGENTS.md` §5。
|
||||
|
||||
## 文件层(文件顶部)
|
||||
|
||||
块注释须包含:**用途**、**主要 import/依赖**、**与上下游文件的逻辑关系**。
|
||||
|
||||
```typescript
|
||||
/**
|
||||
* features/kb/composables/useKbWorkspace.ts
|
||||
* 用途:知识库作业面编排入口,组合 state / computed / data 等子模块。
|
||||
* 依赖:kb-workspace/* composables、kb.api、kb-display.utils。
|
||||
* 逻辑:KbWorkspaceView 调用本 composable;本文件再分发至 useKbWorkspaceData 等子模块。
|
||||
*/
|
||||
```
|
||||
|
||||
```python
|
||||
"""
|
||||
services/kb_sync.py
|
||||
|
||||
用途:知识库文档与 Dify 之间的同步编排。
|
||||
依赖:dify_service、models.KbDocument、minio_service。
|
||||
逻辑:由 api/knowledge_base 路由调用;内部委托 chunking 与 job 状态机。
|
||||
"""
|
||||
```
|
||||
|
||||
## 函数层(每个函数定义上方)
|
||||
|
||||
须说明:**用途**、**核心逻辑与实现方式**、**参数**与**返回值**(及异常)。
|
||||
|
||||
```typescript
|
||||
/**
|
||||
* 加载当前分组下的文档列表,并在静默刷新时合并 stable 项避免闪烁。
|
||||
* 核心逻辑:调用 getKbGroupFilesSafe,按 mergeStableItems 策略合并新旧列表。
|
||||
* @param options.silent - 为 true 时不切换 loading,用于轮询刷新
|
||||
* @returns 是否成功拉取到数据
|
||||
*/
|
||||
async function loadDocuments(options?: LoadListOptions): Promise<boolean> { ... }
|
||||
```
|
||||
|
||||
```python
|
||||
def sync_document_to_dify(document_id: int, *, force: bool = False) -> SyncResult:
|
||||
"""
|
||||
将指定文档切片同步至 Dify 知识库。
|
||||
|
||||
核心逻辑:读 MinIO 原文 → 切块 → 调 Dify API upsert;失败写入 KbJob 供重试。
|
||||
|
||||
Args:
|
||||
document_id: 本地 KbDocument 主键。
|
||||
force: 为 True 时忽略已完成状态强制重同步。
|
||||
|
||||
Returns:
|
||||
SyncResult: 含 dify_document_id 与分段数。
|
||||
|
||||
Raises:
|
||||
KbNotFoundError: 文档不存在或无权限。
|
||||
"""
|
||||
```
|
||||
|
||||
## 修改既有文件时
|
||||
|
||||
- 改函数逻辑/签名 → 同步改该函数注释。
|
||||
- 改 import 或模块协作关系 → 同步改文件头注释。
|
||||
- Vue SFC:`<script setup>` 内每个函数同样要求函数层注释。
|
||||
@@ -0,0 +1,21 @@
|
||||
---
|
||||
description: 未启用。管理端改用 Element Plus 的写法。启用前不要自动套用。
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# 管理端 Element Plus(未启用)
|
||||
|
||||
本规则现在不自动生效:`alwaysApply` 为 false,且没有 `globs`。打开管理端文件时不会套用。
|
||||
|
||||
启用:在本文件顶部 frontmatter 加上下面的 `globs` 后保存。不要改 `alwaysApply`。
|
||||
|
||||
```yaml
|
||||
globs: frontend/src/features/admin/**/*.vue,frontend/src/features/kb/components/KbAdminPanel.vue,frontend/src/features/kb/components/KbGroupDrawer.vue
|
||||
```
|
||||
|
||||
启用之后,改这些 Vue 时遵守 `docs/ui/ELEMENT_MIGRATION.md` §4:
|
||||
|
||||
- 按钮、输入、下拉、表格、弹窗、分页用 Element Plus,不要新写 `<button>`、`<input>`、`<select>`、`<textarea>`。
|
||||
- 不要新写 `btn-primary`、`btn-secondary`、`btn-ghost`、`btn-danger`、`input-field`、`select-field`。
|
||||
- 图标用 `@element-plus/icons-vue`,不要新加 `lucide-vue-next`。
|
||||
- 字号和颜色用 `element-trial.css` 里的 Element 变量,不要在单元格上写 `text-sm`、`text-xs`、`text-muted`。
|
||||
@@ -102,7 +102,6 @@ SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
|
||||
# 复核工作台字段级 AI 建议;仅开发环境启用,建议仍须证据校验与人工裁决
|
||||
SHIPPING_NOTICE_LLM_REVIEW_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
@@ -110,7 +109,6 @@ SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
|
||||
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||
@@ -135,7 +133,6 @@ SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true
|
||||
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||
@@ -146,6 +143,7 @@ FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=data/freight_rpa/inventory/drop
|
||||
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory/triggers
|
||||
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=data/freight_rpa/receipt/drop
|
||||
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=data/freight_rpa/receipt/triggers
|
||||
FREIGHT_RPA_RECEIPT_ARCHIVE_DIR=data/freight_rpa/receipt/archives
|
||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=data/freight_rpa/inventory/upload_queue
|
||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/freight_rpa/inventory/upload_triggers
|
||||
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR=data/freight_rpa/common/browser_profile
|
||||
@@ -156,10 +154,13 @@ FREIGHT_RPA_WORKER_MOCK=false
|
||||
# 本机无 Redis 时允许进程内存记录心跳;有 Redis 时优先写 Redis
|
||||
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false
|
||||
FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK=true
|
||||
# 企微心跳告警总开关(默认关闭;需要时改为 true)
|
||||
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
|
||||
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
|
||||
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
|
||||
# --- 10. 运维、告警与维护工具 ---
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
|
||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
|
||||
WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||
@@ -25,6 +25,7 @@ HXOPS_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||
AUTH_LOGIN_MODE=casdoor
|
||||
# 如果需要用户密码登录,修改该值为password
|
||||
# AUTH_LOGIN_MODE=password
|
||||
|
||||
# 是否启用 JWT 认证
|
||||
AUTH_JWT_REQUIRED=true
|
||||
AUTH_JWT_ISSUER=https://auth.well-trust.com
|
||||
@@ -72,7 +73,6 @@ GUNICORN_WORKERS=20
|
||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
|
||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines
|
||||
WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||
|
||||
# --- 5. 数据库与基础设施 ---
|
||||
@@ -116,7 +116,6 @@ SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
|
||||
|
||||
# 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享)
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
@@ -138,7 +137,6 @@ SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=false
|
||||
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=false
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=false
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
|
||||
# RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。
|
||||
# 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。
|
||||
FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
|
||||
@@ -146,8 +144,6 @@ FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
|
||||
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
|
||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
||||
# 企微心跳告警总开关(默认关闭;需要时改为 true)
|
||||
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
|
||||
# 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微
|
||||
FREIGHT_RPA_WORKER_ALERT_USERNAMES=
|
||||
FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
|
||||
@@ -158,13 +154,13 @@ FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inven
|
||||
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/triggers
|
||||
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/drop
|
||||
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/triggers
|
||||
FREIGHT_RPA_RECEIPT_ARCHIVE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/archives
|
||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_queue
|
||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_triggers
|
||||
# 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
||||
# 订单交期回复 Agent(2026-10-10 上线边界):只同步订单日期 ≥ 起始日的订单行,早于边界的历史行随 erp_missing 语义自动移出工作台;留空/删除 = 全量同步(dev/test 不配置)
|
||||
ORDER_DELIVERY_SYNC_DATE_FROM=2026-10-10
|
||||
# --- 10. 运维、告警与维护工具 ---
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
+2
-1
@@ -150,7 +150,7 @@ WECOM_TRUSTED_DOMAIN=
|
||||
WECOM_PUBLIC_BASE_URL=
|
||||
WECOM_NOTIFY_ENABLED=true
|
||||
WECOM_NOTIFY_BASE_URL=
|
||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines
|
||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,equipment_acceptance_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,order_delivery_reply_notify,training_overseas_thailand_guidelines
|
||||
WECOM_FEEDBACK_NOTIFY_ENABLED=true
|
||||
WECOM_FEEDBACK_NOTIFY_BASE_URL=http://ai.well-trust.com:8881
|
||||
# 企业微信群机器人 webhook,按环境写入 .env.<env> 或部署平台变量;不要提交真实 URL。
|
||||
@@ -238,6 +238,7 @@ IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS=86400
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS=3
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS=5
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS=7
|
||||
IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS=2
|
||||
# 归档 bucket(MinIO;凭据复用 MINIO_*)
|
||||
IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET=hxops-transfer
|
||||
|
||||
|
||||
@@ -24,8 +24,6 @@ HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||
# 如果需要用户密码登录,修改该值为password
|
||||
#AUTH_LOGIN_MODE=casdoor
|
||||
AUTH_LOGIN_MODE=casdoor
|
||||
# 是否启用 JWT 认证
|
||||
AUTH_JWT_REQUIRED=true
|
||||
|
||||
# 必须与 CASDOOR_BASE_URL discovery 返回的 issuer 完全一致,不能填写 HXOPS 地址。
|
||||
AUTH_JWT_ISSUER=https://autht.well-trust.com
|
||||
@@ -72,7 +70,6 @@ GUNICORN_WORKERS=6
|
||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||
WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
|
||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines
|
||||
WECOM_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||
HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||
|
||||
@@ -120,13 +117,11 @@ SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
|
||||
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||
# 货代专用 Tool API Key(RPA 回调优先读取;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||
@@ -151,16 +146,16 @@ SHIPPING_NOTICE_LAYOUT_WORKER_TIMEOUT_SECONDS=360
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true
|
||||
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐)
|
||||
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
|
||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
# 两域超时须覆盖最坏批次总时长(10 站串行 + 单站失败重试可达 30 分钟+),
|
||||
# 否则每轮对账会把仍在飞的健康批次误回收(2026-10-08 RUN20261008003113B726 实测教训)
|
||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=3600
|
||||
FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS=3600
|
||||
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
||||
# 企微心跳告警总开关(默认关闭;需要时改为 true)
|
||||
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
|
||||
# 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微
|
||||
# 两者皆无则告警只写日志、不会发企微
|
||||
FREIGHT_RPA_WORKER_ALERT_USERNAMES=
|
||||
@@ -175,6 +170,7 @@ FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inven
|
||||
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers
|
||||
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/drop
|
||||
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/triggers
|
||||
FREIGHT_RPA_RECEIPT_ARCHIVE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/archives
|
||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_queue
|
||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_triggers
|
||||
# AWS 库存列映射(可选 JSON 字符串)
|
||||
@@ -184,10 +180,7 @@ FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inven
|
||||
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
|
||||
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
|
||||
# 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
||||
# --- 10. 运维、告警与维护工具 ---
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
@@ -0,0 +1,23 @@
|
||||
## 改动说明
|
||||
|
||||
<!-- 这次改了什么、为什么改。 -->
|
||||
|
||||
## 管理端界面
|
||||
|
||||
这次改动如果碰到管理控制台、知识库配置,或已经换成 Element Plus 的页面,按 `docs/ui/ELEMENT_MIGRATION.md` §6 核对。没改界面就删掉下面的清单。
|
||||
|
||||
- [ ] 只在该页入口引入 Element 样式和 `element-trial.css`,并用 `ElConfigProvider` 包住。
|
||||
- [ ] 列表骨架符合规范 §3,左右 32px 对齐,只有一层卡片。
|
||||
- [ ] 按钮符合规范 §4.1,没有 `size="small"` 和默认按钮混在一行。
|
||||
- [ ] 表格状态是 `ElTag`,单元格没有 `text-xs` / `text-sm` / `text-muted`。
|
||||
- [ ] 筛选框没有被拉成整行,空选项不是「请选择」。
|
||||
- [ ] 弹窗宽度只有 480px 或 680px,短表单不是整屏抽屉。
|
||||
- [ ] 加载遮罩只等列表请求,数据出来后遮罩消失。
|
||||
- [ ] 删除确认与本页其他确认框是同一种。
|
||||
- [ ] 四种语言下按钮、表头、空状态、分页都能读通。
|
||||
- [ ] `html.dark` 下边框、表头、弹窗底色跟着变量变。
|
||||
- [ ] `frontend` 下 `npx vue-tsc -b --pretty false` 通过。
|
||||
|
||||
## 测试
|
||||
|
||||
<!-- 怎么验证。 -->
|
||||
@@ -59,6 +59,9 @@ frontend/package-lock.json
|
||||
!.vscode/extensions.json
|
||||
.trae/*
|
||||
.cursor/*
|
||||
!.cursor/rules/
|
||||
!.cursor/rules/*.mdc
|
||||
.cursor/rules/* copy.mdc
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
@@ -150,6 +150,7 @@ docker compose logs -f hxops-backend
|
||||
- 🧬 **修改数据库表结构必须配套迁移**:任何对 `models.py` / 数据表结构的新增、删除、字段或约束变更,都必须生成并提交对应的 Alembic 迁移脚本(`flask db migrate -m "..."` → `flask db upgrade`),禁止只改模型不出迁移。
|
||||
- 🌐 **环境变量分层**:`.env.shared` + `.env.<env>`(dev/test/prod),不要在代码里写死环境值。规则见 **[docs/convention/env_loading_priority.md](docs/convention/env_loading_priority.md)** 与 **[docs/convention/环境变量规则.md](docs/convention/环境变量规则.md)**。
|
||||
- 🌍 **i18n 四语言**:前端新增文案必须同时补齐 `zh-CN / zh-TW / en / th`,禁止硬编码中文。Agent 流程见项目 Skill `add-i18n-keys` 与 [docs/skills/add-i18n-keys-skill.md](docs/skills/add-i18n-keys-skill.md)。
|
||||
- 🎨 **前端界面统一 Element Plus**:`frontend/src` 的页面、弹窗、筛选、表格、按钮和输入使用 Element Plus,写法以 [docs/ui/ELEMENT_MIGRATION.md](docs/ui/ELEMENT_MIGRATION.md) 为准。新改的界面禁止再加 `btn-*`、`input-field`、`select-field`,以及手写 `<button>` / `<input>` / `<select>` / `<textarea>`。尚未替换的旧页面保持原样,轮到该页再整页替换,同一页不要混用两套控件。管理端列表骨架用 `AdminListPage`,页签用 `AdminListTabs`。
|
||||
- 📡 **SSE 流式约束**:对话链路依赖 Gevent 异步 worker + Nginx `proxy_buffering off`;对话接口(`chat.py`)使用原生 Fetch/SSE 而非 Axios,改动需保持流式不被破坏。
|
||||
- 🔌 **外部集成依赖**:Oracle Instant Client 19.30 / `pyodbc` / `zeep`(OA、PLM、HR)等本地未必可运行,涉及这些 service 时谨慎并说明。
|
||||
- ➕ **新增依赖需克制**:不擅自引入未经评审的第三方依赖;如需新增,在提交说明中给出理由。
|
||||
@@ -207,6 +208,7 @@ docker compose logs -f hxops-backend
|
||||
| FAQ 缓存 / 热点发现运维 | [docs/faq_cache_ops_manual.md](docs/faq_cache_ops_manual.md) |
|
||||
| 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.md) |
|
||||
| 前端架构规范 | [docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md) |
|
||||
| 前端 Element Plus | [docs/ui/ELEMENT_MIGRATION.md](docs/ui/ELEMENT_MIGRATION.md) |
|
||||
| 错误处理规范 | [docs/convention/error_handling.md](docs/convention/error_handling.md) |
|
||||
| Cursor Skills 索引 | [docs/skills/README.md](docs/skills/README.md) |
|
||||
| 前端四语言 i18n Skill | [docs/skills/add-i18n-keys-skill.md](docs/skills/add-i18n-keys-skill.md) |
|
||||
|
||||
Vendored
+23
@@ -353,6 +353,29 @@ pipeline {
|
||||
}
|
||||
}
|
||||
|
||||
stage('Frontend Lint') {
|
||||
when {
|
||||
expression { env.FRONTEND_CHANGED == 'true' }
|
||||
}
|
||||
steps {
|
||||
echo '[Frontend Lint] FRONTEND_CHANGED=true,执行 npm run lint(Element 规则当前为 off)'
|
||||
sh '''
|
||||
set -eu
|
||||
test -f "${WORKSPACE}/scripts/ci_frontend_lint.sh"
|
||||
test -f "${WORKSPACE}/frontend/package.json"
|
||||
# 不用 -v 挂载工作区:Jenkins 在容器里时,宿主机 Docker 看不到 /var/jenkins_home。
|
||||
# 把前端源码和脚本打进容器再检查。node_modules 由容器内 npm ci 安装。
|
||||
tar -C "${WORKSPACE}" \
|
||||
--exclude=frontend/node_modules \
|
||||
--exclude=frontend/dist \
|
||||
-cf - \
|
||||
frontend scripts/ci_frontend_lint.sh \
|
||||
| docker run --rm -i node:22-alpine \
|
||||
sh -c 'mkdir -p /repo && tar -xf - -C /repo && sh /repo/scripts/ci_frontend_lint.sh'
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
// stage('Frontend Build (CI)') {
|
||||
// when {
|
||||
// expression { env.FRONTEND_CHANGED == 'true' }
|
||||
|
||||
+27
-13
@@ -42,17 +42,17 @@ def _is_database_table_ready(table_name: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _apply_persisted_settings(app: Flask) -> None:
|
||||
"""Pull the latest runtime-editable settings into ``app.config``.
|
||||
def _apply_persisted_settings(app: Flask, *, force: bool = False) -> None:
|
||||
"""
|
||||
将运行时可编辑配置同步进 ``app.config``。
|
||||
|
||||
Reads from the database first, then ``backend/.env``. Tolerates the
|
||||
common case where the table does not yet exist (fresh deploy before
|
||||
``flask db upgrade`` runs).
|
||||
核心逻辑:委托 apply_env_settings(进程内 TTL,默认 30s);force 时强制读库。
|
||||
表尚未创建(迁移前)时静默跳过。
|
||||
"""
|
||||
from app.core.config.env_persistence import apply_env_settings
|
||||
|
||||
try:
|
||||
applied = apply_env_settings()
|
||||
applied = apply_env_settings(force=force)
|
||||
except Exception as exc: # pragma: no cover - defensive
|
||||
logger.warning('Failed to refresh persisted settings: %s', exc)
|
||||
return
|
||||
@@ -79,12 +79,9 @@ def create_app(config_name='default'):
|
||||
|
||||
_transfer_capabilities.register_transfer_capabilities()
|
||||
|
||||
# Eagerly load persisted runtime settings so the very first request after
|
||||
# a worker boot already sees the admin-saved configuration (otherwise the
|
||||
# window between worker boot and the first ``before_request`` would still
|
||||
# serve the defaults baked into config.py / the image).
|
||||
# 启动时强制加载一次,避免 worker 冷启动到首个请求之间仍用镜像默认值。
|
||||
with app.app_context():
|
||||
_apply_persisted_settings(app)
|
||||
_apply_persisted_settings(app, force=True)
|
||||
from app.services.agent_runtime_context.bootstrap import load_context_adapters
|
||||
load_context_adapters()
|
||||
from app.services.agent_registry.handlers.bootstrap import load_handlers
|
||||
@@ -125,6 +122,21 @@ def create_app(config_name='default'):
|
||||
ensure_default_contract_payment_schedules()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure contract-payment schedules: %s', exc)
|
||||
try:
|
||||
from app.services.equipment_acceptance.schedule_seed import ensure_default_equipment_acceptance_schedules
|
||||
ensure_default_equipment_acceptance_schedules()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure equipment-acceptance schedules: %s', exc)
|
||||
try:
|
||||
from app.services.order_delivery_reply.schedule_seed import ensure_default_order_delivery_schedules
|
||||
ensure_default_order_delivery_schedules()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure order-delivery-reply schedule: %s', exc)
|
||||
try:
|
||||
from app.services.order_delivery_reply.app_seed import ensure_builtin_order_delivery_agent
|
||||
ensure_builtin_order_delivery_agent()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure order-delivery-reply agent: %s', exc)
|
||||
try:
|
||||
from app.services.lean_training_schedule_seed import ensure_default_lean_training_schedule
|
||||
ensure_default_lean_training_schedule()
|
||||
@@ -132,8 +144,9 @@ def create_app(config_name='default'):
|
||||
logger.warning('Failed to ensure lean-training schedule: %s', exc)
|
||||
else:
|
||||
logger.info('Skip startup schedule seeding: schedule_tasks table is not ready')
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
FixedAssetsSnapshotService.start_worker(app)
|
||||
# 固资快照同步已迁至独立进程 workers/worker_fixed_assets.py,Web 不再起线程;
|
||||
# 排程执行同样由独立 worker 进程(workers/worker_scheduler.py,生产 hxops-schedule-worker 容器)
|
||||
# 负责(dev Wave 4),Web 进程不再兜底扫描。
|
||||
# AUTO_UPLOAD 显式开启时启动级校验货代上传 RPA(仅告警,不阻断启动)。
|
||||
try:
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
@@ -145,6 +158,7 @@ def create_app(config_name='default'):
|
||||
|
||||
@app.before_request
|
||||
def _sync_persisted_settings():
|
||||
# TTL 内复用进程缓存,不每请求打 app_settings;跨 worker 最多延迟一个 TTL。
|
||||
_apply_persisted_settings(app)
|
||||
incoming_request_id = (request.headers.get('X-Request-Id') or '').strip()
|
||||
g.request_id = incoming_request_id or f"req_{uuid.uuid4().hex[:16]}"
|
||||
|
||||
@@ -17,21 +17,20 @@ def register_blueprints(app: Flask) -> None:
|
||||
Args:
|
||||
app: Flask 应用实例。
|
||||
"""
|
||||
# [STEP 1] 单体模块(Wave 3 前保持不变)
|
||||
# [STEP 1] 域包入口(Blueprint 多在包 __init__ 或子模块)
|
||||
from app.api.chat import chat_bp
|
||||
from app.api.admin import admin_bp
|
||||
from app.api.agents import agents_bp
|
||||
from app.api.user import auth_bp, user_bp
|
||||
from app.api.integration import integration_bp
|
||||
from app.api.internal_jobs import internal_jobs_bp
|
||||
from app.api.internal import internal_jobs_bp
|
||||
from app.api.maintenance import maintenance_bp
|
||||
from app.api.speech import speech_bp
|
||||
from app.api.sso import sso_bp, sso_well_known_bp
|
||||
from app.api.linked_services import linked_services_bp
|
||||
from app.api.training import training_admin_bp, training_user_bp
|
||||
from app.api.agent_runtime_context_tools import agent_runtime_context_bp
|
||||
|
||||
# [STEP 2] 已分包骨架(Wave 3:kb、schedule 等)
|
||||
# [STEP 2] 其余域包与 Tool API
|
||||
from app.api.kb import knowledge_base_bp
|
||||
from app.api.schedule import schedule_admin_bp
|
||||
from app.api.workspace import (
|
||||
@@ -41,10 +40,17 @@ def register_blueprints(app: Flask) -> None:
|
||||
workspace_shipping_notice_bp,
|
||||
workspace_voucher_check_bp,
|
||||
)
|
||||
from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp
|
||||
from app.api.tools import (
|
||||
agent_runtime_context_bp,
|
||||
file_check_bp,
|
||||
maintenance_tool_bp,
|
||||
procurement_contract_bp,
|
||||
shipping_notice_bp,
|
||||
)
|
||||
from app.api.files import files_bp
|
||||
from app.api.procurement_contract_tools import procurement_contract_bp
|
||||
from app.api.contract_payment import contract_payment_bp
|
||||
from app.api.equipment_acceptance import equipment_acceptance_bp
|
||||
from app.api.order_delivery_reply import order_delivery_reply_bp
|
||||
from app.api.in_transit_transfer import in_transit_transfer_bp
|
||||
from app.api.integration_connector import integration_connector_bp
|
||||
|
||||
@@ -76,5 +82,7 @@ def register_blueprints(app: Flask) -> None:
|
||||
app.register_blueprint(files_bp, url_prefix='/api/files')
|
||||
app.register_blueprint(procurement_contract_bp, url_prefix='/api/procurement-contract')
|
||||
app.register_blueprint(contract_payment_bp, url_prefix='/api/contract-payment')
|
||||
app.register_blueprint(equipment_acceptance_bp, url_prefix='/api/equipment-acceptance')
|
||||
app.register_blueprint(order_delivery_reply_bp, url_prefix='/api/order-delivery-reply')
|
||||
app.register_blueprint(in_transit_transfer_bp, url_prefix='/api/in-transit-transfer')
|
||||
app.register_blueprint(integration_connector_bp, url_prefix='/api/integration-connector')
|
||||
@@ -16,6 +16,7 @@ import app.api.admin.faq_candidates # noqa: F401
|
||||
import app.api.admin.reports # noqa: F401
|
||||
import app.api.admin.database # noqa: F401
|
||||
import app.api.admin.permissions # noqa: F401
|
||||
import app.api.admin.permission_roles # noqa: F401
|
||||
import app.api.admin.users # noqa: F401
|
||||
import app.api.admin.wecom # noqa: F401
|
||||
import app.api.admin.shipping_order_extraction # noqa: F401
|
||||
|
||||
@@ -22,21 +22,11 @@ def dashboard_summary():
|
||||
return jsonify(dashboard_service.compute_dashboard_summary())
|
||||
|
||||
|
||||
@admin_bp.route('/dashboard/badges', methods=['GET'])
|
||||
@require_admin
|
||||
def dashboard_badges():
|
||||
"""
|
||||
管理后台侧栏待办角标(供 AdminLayout 轻量轮询/缓存刷新)。
|
||||
GET /api/admin/dashboard/badges
|
||||
"""
|
||||
return jsonify(dashboard_service.compute_dashboard_badges())
|
||||
|
||||
|
||||
@admin_bp.route('/dashboard', methods=['GET'])
|
||||
@require_admin
|
||||
def dashboard_stats():
|
||||
"""
|
||||
仪表盘统计(遗留接口;新代码请用 /dashboard/summary 与 /dashboard/badges)。
|
||||
仪表盘统计(遗留接口;新代码请用 /dashboard/summary)。
|
||||
GET /api/admin/dashboard
|
||||
"""
|
||||
return jsonify(dashboard_service.compute_legacy_dashboard_stats())
|
||||
@@ -28,6 +28,13 @@ def create_department():
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@admin_bp.route('/departments/<int:id>/members', methods=['GET'])
|
||||
@require_admin
|
||||
def list_department_members(id: int):
|
||||
"""返回部门员工数量与名单。"""
|
||||
return jsonify(department_service.list_department_members(id))
|
||||
|
||||
|
||||
@admin_bp.route('/departments/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_department(id: int):
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"""
|
||||
api/admin/permission_roles.py
|
||||
|
||||
用途:管理端权限组列表、编辑、成员预览与确认调整。
|
||||
依赖:admin.blueprint、permission_roles.service。
|
||||
逻辑:/permission-roles* 路由;成员调整必须先 preview 再 apply。
|
||||
"""
|
||||
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.permission_roles import service as role_service
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_permission_roles():
|
||||
"""列出全部权限组。"""
|
||||
return jsonify(role_service.list_roles())
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/catalog', methods=['GET'])
|
||||
@require_admin
|
||||
def permission_role_catalog():
|
||||
"""角色编辑可选应用与应用内能力。"""
|
||||
return jsonify(role_service.grantable_catalog())
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/picker-users', methods=['GET'])
|
||||
@require_admin
|
||||
def permission_role_picker_users():
|
||||
"""选人弹窗候选人(排除管理员)。"""
|
||||
return jsonify(role_service.list_picker_people())
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles', methods=['POST'])
|
||||
@require_admin
|
||||
def create_permission_role():
|
||||
"""新建权限组。"""
|
||||
data = request.get_json() or {}
|
||||
payload = role_service.create_role(data)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/<code>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_permission_role(code: str):
|
||||
"""权限组详情。"""
|
||||
return jsonify(role_service.get_role_detail(code))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/<code>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_permission_role(code: str):
|
||||
"""保存权限包并同步该组用户授权。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(role_service.update_role(code, data))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/<code>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_permission_role(code: str):
|
||||
"""删除空的非内置权限组。"""
|
||||
return jsonify(role_service.delete_role(code))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/<code>/members/preview', methods=['POST'])
|
||||
@require_admin
|
||||
def preview_permission_role_members(code: str):
|
||||
"""确认前预览将改入/移出的人及来源角色。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(role_service.preview_role_members(code, data.get('selected_ids')))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-roles/<code>/members', methods=['POST'])
|
||||
@require_admin
|
||||
def apply_permission_role_members(code: str):
|
||||
"""确认后写回成员。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(role_service.apply_role_members(code, data.get('selected_ids')))
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/api/admin/permissions.py
|
||||
|
||||
用途:管理后台权限批量更新与权限申请审批 API(薄路由层)。
|
||||
用途:管理后台应用权限批量更新 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/permission_service。
|
||||
逻辑:/permissions/*、/permission-requests/*、/users/<id>/permissions 路由。
|
||||
逻辑:/permissions/*、/users/<id>/permissions 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
@@ -28,22 +28,3 @@ def update_user_permissions(id: int):
|
||||
return jsonify(permission_service.update_user_permissions(id, data))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-requests', methods=['GET'])
|
||||
@require_admin
|
||||
def list_permission_requests():
|
||||
"""列出全部权限申请。"""
|
||||
return jsonify(permission_service.list_permission_requests())
|
||||
|
||||
|
||||
@admin_bp.route('/permission-requests/<int:id>/approve', methods=['POST'])
|
||||
@require_admin
|
||||
def approve_request(id: int):
|
||||
"""批准权限申请。"""
|
||||
return jsonify(permission_service.approve_permission_request(id))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-requests/<int:id>/reject', methods=['POST'])
|
||||
@require_admin
|
||||
def reject_request(id: int):
|
||||
"""拒绝权限申请。"""
|
||||
return jsonify(permission_service.reject_permission_request(id))
|
||||
@@ -19,7 +19,7 @@ def _query_params() -> dict[str, str]:
|
||||
@admin_bp.route('/reports/usage', methods=['GET'])
|
||||
@require_admin
|
||||
def usage_report():
|
||||
"""聊天使用分析报表(支持时间范围 range=7d|30d|90d|180d|365d)。"""
|
||||
"""聊天使用分析报表(统计范围:start_date/end_date 自定义日期优先,否则 range=7d|30d|90d|180d|365d)。"""
|
||||
try:
|
||||
user_page = int(request.args.get('user_page', 1))
|
||||
except (TypeError, ValueError):
|
||||
@@ -34,6 +34,8 @@ def usage_report():
|
||||
user_page=user_page,
|
||||
user_page_size=user_page_size,
|
||||
range_key=range_key,
|
||||
start_date=request.args.get('start_date'),
|
||||
end_date=request.args.get('end_date'),
|
||||
)
|
||||
)
|
||||
|
||||
@@ -43,7 +45,7 @@ def usage_report():
|
||||
def applications_report():
|
||||
"""
|
||||
应用运营报表:按应用聚合使用 / 权限 / 评分。
|
||||
Query: range, status, usage, q, sort, order, page, page_size。
|
||||
Query: start_date, end_date(自定义日期优先), range, status, usage, q, sort, order, page, page_size。
|
||||
"""
|
||||
try:
|
||||
page = int(request.args.get('page', 1))
|
||||
@@ -56,6 +58,8 @@ def applications_report():
|
||||
return jsonify(
|
||||
report_service.build_application_report(
|
||||
range_key=request.args.get('range'),
|
||||
start_date=request.args.get('start_date'),
|
||||
end_date=request.args.get('end_date'),
|
||||
status=request.args.get('status'),
|
||||
usage=request.args.get('usage'),
|
||||
q=request.args.get('q'),
|
||||
@@ -67,6 +71,22 @@ def applications_report():
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/reports/overview', methods=['GET'])
|
||||
@require_admin
|
||||
def ops_overview_report():
|
||||
"""
|
||||
运营总览报表:对话量 / 活跃用户 / 活跃应用 / 趋势环比 / Top 与低使用应用 / 未处理反馈。
|
||||
Query: start_date, end_date(自定义日期优先),否则 range(7d/30d/90d/180d/365d)。
|
||||
"""
|
||||
return jsonify(
|
||||
report_service.build_ops_overview_report(
|
||||
range_key=request.args.get('range'),
|
||||
start_date=request.args.get('start_date'),
|
||||
end_date=request.args.get('end_date'),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/reports/feedback', methods=['GET'])
|
||||
@require_admin
|
||||
def feedback_report():
|
||||
@@ -86,3 +106,31 @@ def list_general_feedbacks_report():
|
||||
def count_general_feedbacks_report():
|
||||
"""通用反馈计数。"""
|
||||
return jsonify(report_service.count_general_feedbacks_report(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/reports/chat-log-tops', methods=['GET'])
|
||||
@require_admin
|
||||
def chat_log_tops():
|
||||
"""聊天日志 Top 提问/回答内容(直接按 ChatLog 明细统计,复用 FAQ 问句归一化)。"""
|
||||
return jsonify(report_service.build_chat_log_top_content(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/reports/feedback-summary', methods=['GET'])
|
||||
@require_admin
|
||||
def feedback_summary():
|
||||
"""用户反馈概览:待处理 / 本月已关闭 / 最多反馈应用(三张概览卡)。"""
|
||||
return jsonify(report_service.build_feedback_summary(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/reports/issue-analysis', methods=['GET'])
|
||||
@require_admin
|
||||
def issue_analysis():
|
||||
"""问题分析:高频问题簇 KPI + 优先处理问题(复用聊天日志风险规则)。"""
|
||||
return jsonify(report_service.build_issue_analysis_report(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/reports/general-feedbacks/<int:feedback_id>/close', methods=['POST'])
|
||||
@require_admin
|
||||
def close_general_feedback(feedback_id: int):
|
||||
"""将一条意见反馈标记为已关闭(status='closed')。"""
|
||||
return jsonify(report_service.mark_general_feedback_closed(feedback_id))
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
"""
|
||||
backend/app/api/admin/users.py
|
||||
|
||||
用途:管理后台用户 CRUD API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/user_service、core.auth.jwt。
|
||||
逻辑:/users* 路由。
|
||||
鐢ㄩ€旓細绠$悊鍚庡彴鐢ㄦ埛 CRUD API锛堣杽璺敱灞傦級銆?
|
||||
渚濊禆锛歛dmin.blueprint銆乻ervices/admin/user_service銆乧ore.auth.jwt銆?
|
||||
閫昏緫锛?users* 璺敱銆?
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
@@ -20,7 +20,7 @@ def _query_params() -> dict[str, str]:
|
||||
@admin_bp.route('/users', methods=['GET'])
|
||||
@require_admin
|
||||
def list_users():
|
||||
"""列出管理端用户(支持分页与筛选)。"""
|
||||
"""Admin user operation."""
|
||||
result = user_service.list_users(_query_params())
|
||||
return jsonify(result)
|
||||
|
||||
@@ -28,7 +28,7 @@ def list_users():
|
||||
@admin_bp.route('/users', methods=['POST'])
|
||||
@require_admin
|
||||
def create_user():
|
||||
"""创建用户并同步 Casdoor。"""
|
||||
"""Admin user operation."""
|
||||
data = request.get_json() or {}
|
||||
payload = user_service.create_user(data)
|
||||
return jsonify(payload), 201
|
||||
@@ -37,22 +37,30 @@ def create_user():
|
||||
@admin_bp.route('/users/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_user(id: int):
|
||||
"""更新用户资料;有 password 时同步 Casdoor 改密。"""
|
||||
"""Admin user operation."""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(user_service.update_user(id, data))
|
||||
|
||||
|
||||
@admin_bp.route('/users/batch', methods=['PUT'])
|
||||
@require_admin
|
||||
def batch_update_users():
|
||||
"""批量更新用户部门 / 角色 / 状态。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(user_service.batch_update_users(data.get('user_ids', []), data.get('data') or {}))
|
||||
|
||||
|
||||
@admin_bp.route('/users/cleanup-rejected', methods=['POST'])
|
||||
@require_admin
|
||||
def cleanup_rejected_users():
|
||||
"""批量删除 status=rejected 的用户。"""
|
||||
"""Admin user operation."""
|
||||
return jsonify(user_service.cleanup_rejected_users())
|
||||
|
||||
|
||||
@admin_bp.route('/users/batch-delete', methods=['POST'])
|
||||
@require_admin
|
||||
def batch_delete_users():
|
||||
"""批量删除用户(排除当前登录管理员)。"""
|
||||
"""Admin user operation."""
|
||||
data = request.get_json() or {}
|
||||
current_user = _get_auth_user()
|
||||
current_user_id = current_user.id if current_user else None
|
||||
@@ -62,21 +70,7 @@ def batch_delete_users():
|
||||
@admin_bp.route('/users/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_user(id: int):
|
||||
"""删除单个用户。"""
|
||||
"""Admin user operation."""
|
||||
current_user = _get_auth_user()
|
||||
current_user_id = current_user.id if current_user else None
|
||||
return jsonify(user_service.delete_user(id, current_user_id=current_user_id))
|
||||
|
||||
|
||||
@admin_bp.route('/users/<int:id>/approve', methods=['POST'])
|
||||
@require_admin
|
||||
def approve_user(id: int):
|
||||
"""审批通过用户。"""
|
||||
return jsonify(user_service.approve_user(id))
|
||||
|
||||
|
||||
@admin_bp.route('/users/<int:id>/reject', methods=['POST'])
|
||||
@require_admin
|
||||
def reject_user(id: int):
|
||||
"""拒绝用户注册。"""
|
||||
return jsonify(user_service.reject_user(id))
|
||||
@@ -1,107 +1,10 @@
|
||||
"""
|
||||
backend/app/api/agent_runtime_context_tools.py
|
||||
|
||||
用途:暴露 agent_runtime_context 只读 Tool API,供 Dify Chatflow 解析 HXOPS 上下文。
|
||||
依赖:app.core.errors、agent_runtime_context.parser/openapi_spec、shipping_notice.tool_api_url。
|
||||
逻辑:OpenAPI 文档接口放行;parse 工具复用 Authorization Bearer / X-Integration-Key 鉴权,不推进业务状态。
|
||||
用途:兼容旧 import 路径的薄 shim(真实现已迁至 api/tools/agent_runtime_context.py)。
|
||||
依赖:app.api.tools.agent_runtime_context。
|
||||
逻辑:保留 Blueprint;新代码请从 app.api.tools 导入。
|
||||
"""
|
||||
from app.api.tools.agent_runtime_context import agent_runtime_context_bp # noqa: F401
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request
|
||||
|
||||
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError
|
||||
from app.services.agent_runtime_context.openapi_spec import build_agent_runtime_context_openapi_spec
|
||||
from app.services.agent_runtime_context.parser import parse_agent_runtime_context
|
||||
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||
|
||||
agent_runtime_context_bp = Blueprint("agent_runtime_context_tools", __name__)
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验 agent_runtime_context Tool API 鉴权 Header。
|
||||
|
||||
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;Dify 请求 parse 工具时由 before_request 自动触发。
|
||||
|
||||
核心逻辑:只接受 Authorization Bearer 或 X-Integration-Key,复用 INTEGRATION_API_KEY 作为平台工具密钥。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 未配置 INTEGRATION_API_KEY。
|
||||
UnauthorizedError: 缺少或传入错误鉴权。
|
||||
"""
|
||||
configured = str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError("INTEGRATION_API_KEY is not configured", code="missing_auth")
|
||||
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||
if configured in {token, integration_key}:
|
||||
return
|
||||
if not token and not integration_key:
|
||||
raise UnauthorizedError("missing_auth")
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
"""
|
||||
归一化 Tool API 错误码。
|
||||
|
||||
核心逻辑:保持与 shipping/file-check Tool API 的 ok:false 响应风格一致,便于 Dify 侧统一处理。
|
||||
|
||||
Args:
|
||||
exc: 业务异常。
|
||||
|
||||
Returns:
|
||||
Tool 侧错误码。
|
||||
"""
|
||||
message = str(exc.message or "").strip()
|
||||
if message in {"missing_auth", "invalid_auth"}:
|
||||
return message
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
return "missing_auth"
|
||||
return exc.code
|
||||
|
||||
|
||||
@agent_runtime_context_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
"""把业务异常统一转成 Tool 侧约定的 JSON 结构。"""
|
||||
return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status
|
||||
|
||||
|
||||
@agent_runtime_context_bp.before_request
|
||||
def _verify_tool_access():
|
||||
"""
|
||||
对上下文解析 Tool 做统一 Header 鉴权。
|
||||
|
||||
核心逻辑:OpenAPI 导入文档无需鉴权;parse 工具必须携带平台 Tool Key。
|
||||
"""
|
||||
if request.path.endswith("/openapi.json"):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
@agent_runtime_context_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def openapi_spec():
|
||||
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
|
||||
return jsonify(build_agent_runtime_context_openapi_spec(resolve_tool_api_base_url()))
|
||||
|
||||
|
||||
@agent_runtime_context_bp.route("/tools/parse", methods=["POST"])
|
||||
def parse_context_tool():
|
||||
"""
|
||||
解析 agent_runtime_context 的白名单字段。
|
||||
|
||||
【AI 触发时机】:Dify 需要读取 HXOPS session/task/batch/run_purpose/state_hint 等上下文字段时调用;
|
||||
不用于推进业务状态。
|
||||
"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
return jsonify(
|
||||
parse_agent_runtime_context(
|
||||
payload.get("agent_runtime_context"),
|
||||
payload.get("paths"),
|
||||
)
|
||||
)
|
||||
__all__ = ['agent_runtime_context_bp']
|
||||
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
backend/app/api/agents.py
|
||||
backend/app/api/agents/__init__.py
|
||||
|
||||
用途:普通用户可见的 Agent 列表与 AgentGuide 静态资源。
|
||||
依赖:app.core.auth.jwt、models、minio_service、agent_registry.serialization。
|
||||
@@ -37,7 +37,7 @@ def _serialize_agent_row(agent: Agent, *, visible_agent_ids: set[int] | None = N
|
||||
|
||||
def _list_active_agents_for_user(user: User) -> list[Agent]:
|
||||
"""返回用户可见的完整 Agent ORM 行(含 Registry 结构化列)。"""
|
||||
if user.role == 'admin':
|
||||
if user.is_platform_admin():
|
||||
return (
|
||||
db.session.query(Agent)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
@@ -2,7 +2,7 @@
|
||||
api/chat/__init__.py
|
||||
|
||||
用途:聊天域 Blueprint 的统一入口。
|
||||
依赖:chat 各职责路由模块、app.api.chat_turns。
|
||||
依赖:chat 各职责路由模块、chat.turns。
|
||||
逻辑:创建唯一的 chat_bp,导入子模块完成路由注册,并挂载 Chat Turn 流式接口。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
@@ -21,7 +21,7 @@ from .shared import ( # noqa: E402, F401
|
||||
_merge_user_attachments_from_terminal_event,
|
||||
_normalize_user_attachments,
|
||||
)
|
||||
from app.api.chat_turns import register_chat_turn_routes # noqa: E402
|
||||
from .turns import register_chat_turn_routes # noqa: E402
|
||||
|
||||
register_chat_turn_routes(chat_bp)
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ def chat_completions():
|
||||
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
|
||||
conversation_id = data.get('conversation_id')
|
||||
shipping_task_id = str(data.get('task_id') or '').strip()
|
||||
shipping_batch_no = str(data.get('batch_no') or '').strip()
|
||||
kb_type = data.get('kb_type', '企业知识库')
|
||||
files = data.get('files')
|
||||
request_id = uuid.uuid4().hex[:12]
|
||||
@@ -174,6 +175,7 @@ def chat_completions():
|
||||
normalized_files=normalized_files,
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
),
|
||||
shipping_task_id=shipping_task_id,
|
||||
kb_type=kb_type,
|
||||
@@ -214,6 +216,7 @@ def chat_completions():
|
||||
user_role=user_proxy.role,
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -10,19 +10,21 @@ from __future__ import annotations
|
||||
from .shared import * # noqa: F403
|
||||
|
||||
|
||||
def _build_chat_adapter_hints(*, shipping_task_id: str | None = None) -> dict | None:
|
||||
def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_batch_no: str | None = None) -> dict | None:
|
||||
"""
|
||||
构建聊天入口分发给领域 adapter 的提示字典。
|
||||
|
||||
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task 提示,
|
||||
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示,
|
||||
统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。
|
||||
"""
|
||||
task_id = str(shipping_task_id or '').strip()
|
||||
if not task_id:
|
||||
batch_no = str(shipping_batch_no or '').strip()
|
||||
if not task_id and not batch_no:
|
||||
return None
|
||||
return {
|
||||
'shipping_notice': {
|
||||
'task_id': task_id or None,
|
||||
'batch_no': batch_no or None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/api/chat_turns.py
|
||||
backend/app/api/chat/turns.py
|
||||
|
||||
用途:Chat Turn 流式 API 路由(POST /api/chat/turns/stream)。
|
||||
依赖:app.core.decorators、ChatTurnRuntime、chat_bp。
|
||||
逻辑:支持 JSON 与 multipart(附件上传 + Turn);由 chat.py 注册到同一 Blueprint。
|
||||
逻辑:支持 JSON 与 multipart(附件上传 + Turn);由 chat 包注册到同一 Blueprint。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
backend/app/api/contract_payment.py
|
||||
backend/app/api/contract_payment/__init__.py
|
||||
|
||||
用途:采购合同付款预警 Agent 的合同台账、付款计划、待发送摘要、台账汇总卡和同步 API。
|
||||
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、Agent 授权、contract_payment 服务和通用 Job 队列。
|
||||
@@ -7,8 +7,8 @@ backend/app/api/contract_payment.py
|
||||
下载和单合同重解析走 read_contract_attachment_bytes:原文还在则直接读,被临时清理删掉则按附件 ID 从 OA/DMS 重新下载。
|
||||
待确认合同的人工复核走 apply_manual_review:比例合计 100% 后改为已解析并进入台账。未付的预付款、出货款可手动标为已付。
|
||||
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍;同时返回 OA 公司及对应 ERP 账套。
|
||||
鉴权:查询接口要求平台 admin 或持有 `agent_code=contract_payment` 的 Agent 授权;
|
||||
同步/扫描/周汇总发送仅 `role=admin`。
|
||||
鉴权:查询接口要求平台管理员(is_platform_admin)或持有 `agent_code=contract_payment` 的 Agent 授权;
|
||||
同步/扫描/周汇总发送仅平台管理员。权限组启用后,普通用户通过角色包获得该 Agent,不再按人授权。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -111,7 +111,7 @@ def _require_contract_payment_access():
|
||||
ForbiddenError: 已登录但没有合同付款预警 Agent 授权。
|
||||
"""
|
||||
user = _require_user()
|
||||
if getattr(user, "role", None) == "admin" or _user_has_contract_payment_agent(user):
|
||||
if user.is_platform_admin() or _user_has_contract_payment_agent(user):
|
||||
return user
|
||||
raise ForbiddenError(
|
||||
'Contract payment agent permission required',
|
||||
@@ -124,7 +124,7 @@ def _require_contract_payment_admin():
|
||||
确保当前用户既有合同付款预警访问权,又是平台管理员。
|
||||
|
||||
核心逻辑:持有 Agent 的普通用户可查台账;同步 OA、强制覆盖、批量重解析、扫描预警和发送周汇总
|
||||
会改写外部系统或触发企微,因此仅 `role=admin` 可调用。
|
||||
会改写外部系统或触发企微,因此仅平台管理员可调用。
|
||||
|
||||
Args:
|
||||
无。当前请求身份由 JWT 上下文提供。
|
||||
@@ -135,7 +135,7 @@ def _require_contract_payment_admin():
|
||||
ForbiddenError: 无合同付款访问权,或已授权但不是管理员。
|
||||
"""
|
||||
user = _require_contract_payment_access()
|
||||
if getattr(user, "role", None) != "admin":
|
||||
if not user.is_platform_admin():
|
||||
raise ForbiddenError(
|
||||
'Admin privilege required for contract payment jobs',
|
||||
code='CONTRACT_PAYMENT.ADMIN_REQUIRED',
|
||||
@@ -0,0 +1,205 @@
|
||||
"""
|
||||
backend/app/api/equipment_acceptance/__init__.py
|
||||
|
||||
用途:设备验收预警的 Chat 作业面接口。
|
||||
依赖:JWT 当前用户、Agent 授权、sync_service、统一成功响应。
|
||||
逻辑:持有 equipment_acceptance Agent 的用户可看停留列表、发送记录、已归档 Excel 和配置;同步、扫描、发送和保存配置仅平台管理员。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
from flask import Blueprint, g, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, UnauthorizedError
|
||||
from app.core.response import ok
|
||||
from app.models import Agent
|
||||
from app.services.equipment_acceptance.config_service import (
|
||||
get_acceptance_config,
|
||||
save_acceptance_config,
|
||||
)
|
||||
from app.services.equipment_acceptance.alert_service import generate_alerts, send_pending_alerts
|
||||
from app.services.equipment_acceptance.send_record_service import get_send_file, list_send_files, list_send_records
|
||||
from app.services.equipment_acceptance.sync_service import (
|
||||
get_acceptance_order,
|
||||
list_acceptance_orders,
|
||||
sync_acceptance_snapshots,
|
||||
)
|
||||
|
||||
equipment_acceptance_bp = Blueprint("equipment_acceptance", __name__)
|
||||
EQUIPMENT_ACCEPTANCE_AGENT_CODE = "equipment_acceptance"
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""
|
||||
读取当前登录用户。
|
||||
|
||||
Returns:
|
||||
已认证用户。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 没有有效登录身份。
|
||||
"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _user_has_equipment_acceptance_agent(user) -> bool:
|
||||
"""
|
||||
判断用户是否持有启用中的设备验收预警 Agent。
|
||||
|
||||
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions。
|
||||
"""
|
||||
agent = Agent.query.filter_by(agent_code=EQUIPMENT_ACCEPTANCE_AGENT_CODE, is_active=True).first()
|
||||
return bool(agent is not None and agent in user.agents)
|
||||
|
||||
|
||||
def _require_equipment_acceptance_access():
|
||||
"""
|
||||
确保当前用户可以打开设备验收预警作业面。
|
||||
|
||||
核心逻辑:平台管理员放行;普通用户必须被授予启用中的 equipment_acceptance Agent。
|
||||
|
||||
Returns:
|
||||
已认证且有权查看的用户。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 没有有效登录身份。
|
||||
ForbiddenError: 已登录但没有该 Agent。
|
||||
"""
|
||||
user = _require_user()
|
||||
if user.is_platform_admin() or _user_has_equipment_acceptance_agent(user):
|
||||
return user
|
||||
raise ForbiddenError(
|
||||
"Equipment acceptance agent permission required",
|
||||
code="EQUIPMENT_ACCEPTANCE.FORBIDDEN",
|
||||
)
|
||||
|
||||
|
||||
def _require_equipment_acceptance_admin():
|
||||
"""
|
||||
确保当前用户可以触发 E10 同步。
|
||||
|
||||
核心逻辑:先确认能看作业面,再要求平台管理员。同步会读取外部库并改写本地快照。
|
||||
|
||||
Returns:
|
||||
已认证的管理员。
|
||||
|
||||
Raises:
|
||||
ForbiddenError: 不是平台管理员。
|
||||
"""
|
||||
user = _require_equipment_acceptance_access()
|
||||
if not user.is_platform_admin():
|
||||
raise ForbiddenError(
|
||||
"Admin privilege required for equipment acceptance sync",
|
||||
code="EQUIPMENT_ACCEPTANCE.ADMIN_REQUIRED",
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/sync", methods=["POST"])
|
||||
def sync_equipment_acceptance():
|
||||
"""从 E10 拉取验收单并写入本地快照。仅平台管理员。"""
|
||||
_require_equipment_acceptance_admin()
|
||||
return ok(sync_acceptance_snapshots(), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/orders", methods=["GET"])
|
||||
def list_equipment_acceptance_orders():
|
||||
"""分页查看已同步的验收单。focus 按原型分组过滤,summary 始终统计全部单据。"""
|
||||
_require_equipment_acceptance_access()
|
||||
page = _int_arg("page", 1)
|
||||
page_size = _int_arg("page_size", 20)
|
||||
payload = list_acceptance_orders(
|
||||
monitor_status=request.args.get("monitor_status"),
|
||||
focus=request.args.get("focus"),
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/config", methods=["GET"])
|
||||
def get_equipment_acceptance_config():
|
||||
"""读取四档天数和三个固定岗位。候选人名单只给平台管理员。"""
|
||||
user = _require_equipment_acceptance_access()
|
||||
payload = get_acceptance_config(include_candidates=user.is_platform_admin())
|
||||
return ok(payload, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/config", methods=["PUT"])
|
||||
def save_equipment_acceptance_config():
|
||||
"""保存四档天数和三个固定岗位。仅平台管理员。发送时刻不在本接口。"""
|
||||
user = _require_equipment_acceptance_access()
|
||||
if not user.is_platform_admin():
|
||||
raise ForbiddenError(
|
||||
"Admin privilege required for equipment acceptance settings",
|
||||
code="EQUIPMENT_ACCEPTANCE.SETTINGS_ADMIN_REQUIRED",
|
||||
)
|
||||
payload = request.get_json(silent=True) or {}
|
||||
saved = save_acceptance_config(payload, updated_by=user.id)
|
||||
return ok(saved, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/alerts/scan", methods=["POST"])
|
||||
def scan_equipment_acceptance_alerts():
|
||||
"""管理员立即同步 E10 并生成待发送记录。不发企业微信。"""
|
||||
_require_equipment_acceptance_admin()
|
||||
return ok(generate_alerts(), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/alerts/send", methods=["POST"])
|
||||
def send_equipment_acceptance_alerts():
|
||||
"""管理员立即把待发送记录按收件人发到企业微信。"""
|
||||
_require_equipment_acceptance_admin()
|
||||
return ok(send_pending_alerts(), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/send-files", methods=["GET"])
|
||||
def list_equipment_acceptance_send_files():
|
||||
"""列出最近按收件人归档的 Excel。不含文件字节。"""
|
||||
_require_equipment_acceptance_access()
|
||||
return ok({"items": list_send_files()}, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/send-files/<int:file_id>/excel", methods=["GET"])
|
||||
def download_equipment_acceptance_send_file(file_id: int):
|
||||
"""下载一份当时发给收件人的设备验收预警 Excel。"""
|
||||
_require_equipment_acceptance_access()
|
||||
row = get_send_file(file_id)
|
||||
return send_file(
|
||||
BytesIO(row.excel_file_data),
|
||||
as_attachment=True,
|
||||
download_name=row.excel_file_name or f"equipment-acceptance-alert-{file_id}.xlsx",
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/sends", methods=["GET"])
|
||||
def list_equipment_acceptance_sends():
|
||||
"""分页查看发送记录。扫描写入后这里才有行。"""
|
||||
_require_equipment_acceptance_access()
|
||||
payload = list_send_records(page=_int_arg("page", 1), page_size=_int_arg("page_size", 20))
|
||||
return ok(payload, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@equipment_acceptance_bp.route("/orders/<int:order_id>", methods=["GET"])
|
||||
def get_equipment_acceptance_order(order_id: int):
|
||||
"""查看一张验收单的节点和操作人原值。"""
|
||||
_require_equipment_acceptance_access()
|
||||
return ok(get_acceptance_order(order_id), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
def _int_arg(name: str, default: int) -> int:
|
||||
"""读取正整数查询参数,非法时用默认值。"""
|
||||
raw = request.args.get(name)
|
||||
if raw is None or str(raw).strip() == "":
|
||||
return default
|
||||
try:
|
||||
return int(raw)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
@@ -1,657 +1,28 @@
|
||||
"""
|
||||
backend/app/api/file_check_tools.py
|
||||
|
||||
用途:文件检核 / 立账凭证检核 Chatflow 显式 HTTP Tool API(启动检核复用本蓝图)。
|
||||
依赖:workspace_file_check、file_check_tools、schedule.scheduler_service。
|
||||
逻辑:发起检核时可透传顶层 mode/invoice_no(或嵌套 run_options)写入 ScheduleRun.api_request_json;实际执行入队 FILE_CHECK_RUN,由 schedule worker 执行。
|
||||
用途:兼容旧 import 路径的薄 shim(真实现已迁至 api/tools/file_check.py)。
|
||||
依赖:app.api.tools.file_check。
|
||||
逻辑:保留 Blueprint 与测试 monkeypatch 常用符号;新代码请从 app.api.tools 导入。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from io import BytesIO
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
from sqlalchemy import text
|
||||
|
||||
from app import db
|
||||
from app.api.workspace_file_check import serialize_file_judgement
|
||||
from app.jobs import JobType, enqueue
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
from app.api.tools.file_check import ( # noqa: F401
|
||||
_RUN_START_LOCK,
|
||||
_build_excel_download_url,
|
||||
_precheck_no_data,
|
||||
enqueue,
|
||||
file_check_bp,
|
||||
get_schedule_sql_config_by_task_id,
|
||||
_build_srm_conn_str,
|
||||
_fetch_records,
|
||||
)
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.file_check_tools.openapi_spec import build_file_check_openapi_spec
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE, resolve_hxops_user_facing_base_url
|
||||
from app.services.schedule import _build_srm_conn_str
|
||||
from app.services.schedule.query_service import get_run, serialize_run
|
||||
from app.services.schedule.srm_service import _fetch_records
|
||||
from app.services.schedule.scheduler_service import _generate_run_no
|
||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
|
||||
|
||||
try:
|
||||
import pyodbc # type: ignore
|
||||
except Exception: # pragma: no cover
|
||||
pyodbc = None
|
||||
|
||||
|
||||
file_check_bp = Blueprint("file_check_tools", __name__)
|
||||
|
||||
_EXCEL_TOKEN_SCOPES = {"file_check_excel", "file_schedule_excel"}
|
||||
_RUN_START_LOCK = threading.Lock()
|
||||
_TASK_LOCK_KEY_BASE = 8700000000
|
||||
|
||||
|
||||
def _download_token_secret() -> str:
|
||||
"""
|
||||
Excel 下载 JWT 签名密钥。
|
||||
|
||||
核心逻辑:与 Dify Tool API Key 分离,仅用 SECRET_KEY,避免 API Key 未配置时浏览器下载失败。
|
||||
"""
|
||||
return str(current_app.config.get("SECRET_KEY") or "default-secret").strip()
|
||||
|
||||
|
||||
def _decode_download_token(token: str | None) -> dict | None:
|
||||
normalized = str(token or "").strip()
|
||||
if not normalized:
|
||||
return None
|
||||
try:
|
||||
import jwt
|
||||
|
||||
payload = jwt.decode(normalized, _download_token_secret(), algorithms=["HS256"])
|
||||
return payload if isinstance(payload, dict) else None
|
||||
except Exception as exc:
|
||||
current_app.logger.warning("[file-check-tool] download token validation failed: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验 Tool API 访问权限。
|
||||
|
||||
核心逻辑:Excel 下载仅校验 query token(浏览器场景);其余端点走共用 integration_tool_auth。
|
||||
"""
|
||||
# [STEP 1] 浏览器 Excel 下载:JWT token 独立于 Tool API Key
|
||||
if request.path.endswith("/excel"):
|
||||
query_token = str(request.args.get("token") or "").strip()
|
||||
if query_token:
|
||||
if _decode_download_token(query_token):
|
||||
return
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
# [STEP 2] Dify / RPA 服务端调用(与立账凭证检核等 Tool 共用密钥)
|
||||
from app.services.integration_tool_auth import require_integration_tool_auth
|
||||
|
||||
require_integration_tool_auth()
|
||||
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
message = str(exc.message or "").strip()
|
||||
if message in {
|
||||
"missing_auth",
|
||||
"invalid_auth",
|
||||
"task_not_found",
|
||||
"run_not_found",
|
||||
"excel_not_ready",
|
||||
"kb_sync_failed",
|
||||
"query_required",
|
||||
"kb_not_configured",
|
||||
"kb_group_not_found",
|
||||
"kb_dataset_not_bound",
|
||||
"dify_retrieve_failed",
|
||||
}:
|
||||
return message
|
||||
if exc.code == "data_source_unavailable":
|
||||
return "data_source_unavailable"
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
return "missing_auth"
|
||||
if exc.code == "RESOURCE.NOT_FOUND":
|
||||
return message or "run_not_found"
|
||||
if exc.code == "VALIDATION.INVALID_PARAM":
|
||||
return message or "invalid_request"
|
||||
if exc.code == "RESOURCE.CONFLICT":
|
||||
return message or "conflict"
|
||||
return exc.code
|
||||
|
||||
|
||||
@file_check_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
status = exc.http_status
|
||||
return jsonify({
|
||||
"ok": False,
|
||||
"error_code": _tool_error_code(exc),
|
||||
"message": exc.message,
|
||||
}), status
|
||||
|
||||
|
||||
def _public_base_url() -> str:
|
||||
"""用户可见下载链基地址;与 Dify 调 Tool API 的内网基地址分离。"""
|
||||
return resolve_hxops_user_facing_base_url()
|
||||
|
||||
|
||||
def _acquire_task_start_lock(task_id: int) -> None:
|
||||
"""按 schedule_task_id 串行化同任务启动检核(PostgreSQL advisory lock)。"""
|
||||
bind = db.session.get_bind()
|
||||
if bind.dialect.name != "postgresql":
|
||||
return
|
||||
lock_key = _TASK_LOCK_KEY_BASE + int(task_id)
|
||||
db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": lock_key})
|
||||
|
||||
|
||||
def _build_excel_download_url(run: ScheduleRun) -> str:
|
||||
import jwt
|
||||
|
||||
payload = {
|
||||
"scope": "file_check_excel",
|
||||
"run_id": run.id,
|
||||
"exp": int(time.time()) + 600,
|
||||
}
|
||||
token = jwt.encode(payload, _download_token_secret(), algorithm="HS256")
|
||||
return f"{_public_base_url()}/api/file-check/tools/runs/{run.id}/excel?token={token}"
|
||||
|
||||
|
||||
@file_check_bp.before_request
|
||||
def _verify_tool_access():
|
||||
if request.path.endswith("/openapi.json"):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
def _serialize_tool_run(run: ScheduleRun) -> dict:
|
||||
payload = serialize_run(run)
|
||||
return {
|
||||
"run_id": payload["id"],
|
||||
"run_no": payload["run_no"],
|
||||
"task_id": payload["schedule_task_id"],
|
||||
"task_name": payload.get("schedule_name"),
|
||||
"status": payload["status"],
|
||||
"total_count": payload["total_count"],
|
||||
"success_count": payload["success_count"],
|
||||
"failed_count": payload["failed_count"],
|
||||
"skipped_count": payload["skipped_count"],
|
||||
"judgement": serialize_file_judgement(payload),
|
||||
"started_at": payload.get("started_at"),
|
||||
"finished_at": payload.get("finished_at"),
|
||||
"duration_ms": payload.get("duration_ms"),
|
||||
"error_message": payload.get("error_message"),
|
||||
"excel": {
|
||||
"file_name": payload.get("excel_file_name"),
|
||||
"file_size": payload.get("excel_file_size"),
|
||||
"download_url": _build_excel_download_url(run) if payload.get("excel_file_name") else None,
|
||||
},
|
||||
"knowledge_base": {
|
||||
"enabled": bool(getattr(run.task, "kb_sync_enabled", False)) if run.task else bool(payload.get("kb_group_id")),
|
||||
"sync_status": payload.get("kb_sync_status"),
|
||||
"group_id": payload.get("kb_group_id"),
|
||||
"document_id": payload.get("kb_document_id"),
|
||||
"document_version_id": payload.get("kb_document_version_id"),
|
||||
"sync_job_id": payload.get("kb_sync_job_id"),
|
||||
"error_message": payload.get("kb_sync_error"),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _resolve_check_task(data: dict | None = None, *, task_id: int | None = None) -> ScheduleTask:
|
||||
data = data or {}
|
||||
raw_task_id = task_id if task_id is not None else data.get("task_id")
|
||||
if raw_task_id in (None, "", 0, "0") and not str(data.get("task_no") or "").strip():
|
||||
raise ValidationError("task_id_required")
|
||||
try:
|
||||
normalized_task_id = int(raw_task_id) if raw_task_id not in (None, "", 0, "0") else None
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError("task_id_invalid")
|
||||
task = db.session.get(ScheduleTask, normalized_task_id) if normalized_task_id is not None else None
|
||||
if not task:
|
||||
task_no = str(data.get("task_no") or "").strip()
|
||||
if task_no:
|
||||
task = ScheduleTask.query.filter_by(schedule_no=task_no).first()
|
||||
if not task:
|
||||
raise NotFoundError("task_not_found")
|
||||
return task
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/tasks", methods=["GET"])
|
||||
def list_file_check_tasks():
|
||||
"""
|
||||
查询指定检核任务摘要;须传 task_id(Agent 绑定的 schedule_task_id),不再返回全量任务列表。
|
||||
"""
|
||||
raw_task_id = request.args.get("task_id", type=int)
|
||||
if raw_task_id is None:
|
||||
raise ValidationError("task_id_required")
|
||||
task = _resolve_check_task(task_id=raw_task_id)
|
||||
latest = (
|
||||
ScheduleRun.query.filter_by(schedule_task_id=task.id)
|
||||
.order_by(ScheduleRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
tasks = [{
|
||||
"task_id": task.id,
|
||||
"task_no": task.schedule_no,
|
||||
"name": task.name,
|
||||
"enabled": bool(task.enabled),
|
||||
"last_status": latest.status if latest else None,
|
||||
"last_run_at": task.last_run_at.isoformat() if task.last_run_at else None,
|
||||
"next_run_at": task.next_run_at.isoformat() if task.next_run_at else None,
|
||||
}]
|
||||
return jsonify({"ok": True, "tasks": tasks})
|
||||
|
||||
|
||||
def _normalize_bind_payload(data: dict | None) -> dict:
|
||||
"""规范化启动检核 Body;兼容 Chatflow 漏传 hxops_session_id。"""
|
||||
payload = dict(data or {})
|
||||
session_id = str(payload.get("hxops_session_id") or "").strip()
|
||||
if session_id:
|
||||
return payload
|
||||
conversation_id = str(payload.get("conversation_id") or "").strip()
|
||||
if not conversation_id:
|
||||
return payload
|
||||
from app.models import ChatSession
|
||||
|
||||
session = ChatSession.query.filter_by(session_id=conversation_id).first()
|
||||
if session:
|
||||
payload["hxops_session_id"] = conversation_id
|
||||
return payload
|
||||
|
||||
|
||||
def _prepare_bind_payload(data: dict | None) -> dict:
|
||||
from app.services.file_check_tools.chat_turn_registry import infer_bind_context_for_run_request
|
||||
|
||||
payload = _normalize_bind_payload(data)
|
||||
inferred = infer_bind_context_for_run_request(payload)
|
||||
if inferred:
|
||||
payload = {**payload, **inferred}
|
||||
return payload
|
||||
|
||||
|
||||
def _record_run_bind(run: ScheduleRun, data: dict) -> None:
|
||||
from app.services.file_check_tools.chat_log_run_binding import merge_chat_log_bind_context
|
||||
from app.services.file_check_tools.chat_tool_run_binding import (
|
||||
_has_ambiguous_pending_turns,
|
||||
bind_schedule_run,
|
||||
)
|
||||
from app.services.file_check_tools.chat_turn_registry import attach_run_to_turn
|
||||
|
||||
turn_id = str(data.get("hxops_turn_id") or "").strip()
|
||||
session_id = str(data.get("hxops_session_id") or "").strip() or None
|
||||
user_message = str(data.get("user_message") or "").strip() or None
|
||||
bound = bind_schedule_run(
|
||||
schedule_run_id=int(run.id),
|
||||
turn_id=turn_id or None,
|
||||
session_id=session_id,
|
||||
user_message=user_message,
|
||||
schedule_task_id=int(run.schedule_task_id) if run.schedule_task_id else None,
|
||||
bind_source='tool_start',
|
||||
)
|
||||
ambiguous = _has_ambiguous_pending_turns(
|
||||
session_id=session_id,
|
||||
user_message=user_message,
|
||||
schedule_task_id=int(run.schedule_task_id) if run.schedule_task_id else None,
|
||||
)
|
||||
if bound or (not ambiguous and (turn_id or session_id)):
|
||||
merge_chat_log_bind_context(run, data)
|
||||
if bound and turn_id:
|
||||
attach_run_to_turn(turn_id, int(run.id))
|
||||
|
||||
|
||||
def _bind_queried_run_to_turn(run: ScheduleRun, data: dict) -> None:
|
||||
"""
|
||||
将已有检核批次关联到本轮查询对话,不改写批次原始执行上下文。
|
||||
|
||||
查询最近批次时触发;仅更新 chat_tool_runs 与内存 turn registry,
|
||||
使 message_end 可以把既有 ScheduleRun.id 写入当前 ChatLog.run_id。
|
||||
"""
|
||||
from app.services.file_check_tools.chat_tool_run_binding import bind_schedule_run
|
||||
from app.services.file_check_tools.chat_turn_registry import attach_run_to_turn
|
||||
|
||||
turn_id = str(data.get("hxops_turn_id") or "").strip()
|
||||
session_id = str(data.get("conversation_id") or "").strip() or None
|
||||
user_message = str(data.get("user_message") or "").strip() or None
|
||||
if not turn_id:
|
||||
return
|
||||
|
||||
bound = bind_schedule_run(
|
||||
schedule_run_id=int(run.id),
|
||||
turn_id=turn_id,
|
||||
session_id=session_id,
|
||||
user_message=user_message,
|
||||
schedule_task_id=int(run.schedule_task_id),
|
||||
bind_source="tool_query_latest",
|
||||
)
|
||||
if bound:
|
||||
attach_run_to_turn(turn_id, int(run.id))
|
||||
|
||||
|
||||
def _build_no_data_response(task: ScheduleTask, run: ScheduleRun) -> dict:
|
||||
"""
|
||||
组装无待检资料的 Tool 响应,并返回本轮已完成的空批次。
|
||||
|
||||
【AI 触发时机】:用户要求立即执行文件检核,但预检未发现待检资料时调用。
|
||||
核心逻辑:保留 no_data_to_check 供 Chatflow 回复无资料提示,同时携带已绑定的 Run,
|
||||
使前端能在该轮消息下展示总数 0、进度 100% 的完成进度卡。
|
||||
|
||||
Args:
|
||||
task: 当前检核任务。
|
||||
run: 已持久化并绑定当前对话的成功空批次。
|
||||
|
||||
Returns:
|
||||
dict: 包含 no_data_to_check、任务信息和 Run 摘要的 HTTP 200 响应体。
|
||||
"""
|
||||
return {
|
||||
"ok": False,
|
||||
"error_code": "no_data_to_check",
|
||||
"message": "目前没有资料需要检核",
|
||||
"run": _serialize_tool_run(run),
|
||||
"task": {
|
||||
"task_id": task.id,
|
||||
"task_name": task.name,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _raise_data_source_unavailable(task: ScheduleTask, exc: Exception) -> None:
|
||||
"""
|
||||
将检核预检阶段的数据源连接/配置错误转为 Tool API 503。
|
||||
|
||||
核心逻辑:ODBC/SQL Server 不可用时返回 data_source_unavailable,避免 Dify 收到 500 后显示 maximum retries。
|
||||
"""
|
||||
current_app.logger.warning(
|
||||
"[file-check-tool] precheck data source unavailable task_id=%s error=%s",
|
||||
task.id,
|
||||
exc,
|
||||
exc_info=True,
|
||||
)
|
||||
raise ServiceUnavailableError(
|
||||
"检核数据源不可用,请检查排程 SQL 配置、SRM_SQLSERVER_* 环境变量及本机 ODBC 驱动",
|
||||
code="data_source_unavailable",
|
||||
) from exc
|
||||
|
||||
|
||||
def _precheck_no_data(task: ScheduleTask) -> dict | None:
|
||||
"""
|
||||
启动前预检当前任务是否存在待检资料。
|
||||
|
||||
核心逻辑:仅在数据库型检核任务上做轻量预检;若结果为空,则返回 no_data_to_check 标识,
|
||||
由启动入口创建并绑定完成态的 0 笔 Run。数据源连接失败时抛 503 data_source_unavailable。
|
||||
"""
|
||||
if str(getattr(task, "data_source_type", "") or "database").lower() != "database":
|
||||
return None
|
||||
|
||||
cfg = get_schedule_sql_config_by_task_id(task.id)
|
||||
if not cfg or not str(cfg.fetch_sql or "").strip():
|
||||
return None
|
||||
|
||||
try:
|
||||
if cfg.data_source and not cfg.data_source.is_empty():
|
||||
conn_str = cfg.data_source.build_connection_string()
|
||||
else:
|
||||
conn_str = _build_srm_conn_str()
|
||||
rows = _fetch_records(conn_str, cfg.fetch_sql)
|
||||
except RuntimeError as exc:
|
||||
_raise_data_source_unavailable(task, exc)
|
||||
except Exception as exc:
|
||||
if pyodbc is not None and isinstance(exc, pyodbc.Error):
|
||||
_raise_data_source_unavailable(task, exc)
|
||||
raise
|
||||
|
||||
if rows:
|
||||
return None
|
||||
return {
|
||||
"ok": False,
|
||||
"error_code": "no_data_to_check",
|
||||
"message": "目前没有资料需要检核",
|
||||
}
|
||||
|
||||
|
||||
def _create_no_data_run(task: ScheduleTask, data: dict) -> ScheduleRun:
|
||||
"""
|
||||
为预检为空的立即执行请求创建并绑定已完成的 0 笔检核批次。
|
||||
|
||||
【AI 触发时机】:run_file_check 收到 no_data_to_check 预检结果时调用。
|
||||
核心逻辑:不启动后台 worker,仅写入 success Run 与对话绑定;完成态空批次由工作区进度接口
|
||||
序列化为 100%,让用户明确知道本次检核已经结束且没有待处理资料。
|
||||
|
||||
Args:
|
||||
task: 已解析的文件检核任务。
|
||||
data: Tool 请求及对话绑定上下文。
|
||||
|
||||
Returns:
|
||||
ScheduleRun: 已提交且已绑定当前对话的成功空批次。
|
||||
"""
|
||||
finished_at = datetime.utcnow()
|
||||
run = ScheduleRun(
|
||||
run_no=_generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
trigger_type="dify_chatflow",
|
||||
started_at=finished_at,
|
||||
finished_at=finished_at,
|
||||
duration_ms=0,
|
||||
status="success",
|
||||
total_count=0,
|
||||
success_count=0,
|
||||
failed_count=0,
|
||||
skipped_count=0,
|
||||
api_request_json={
|
||||
"trigger_source": data.get("trigger_source") or "dify_chatflow",
|
||||
"conversation_id": data.get("conversation_id"),
|
||||
},
|
||||
response_summary_json={"errors": [], "no_data": True},
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
_record_run_bind(run, data)
|
||||
db.session.commit()
|
||||
return run
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/tasks/run", methods=["POST"])
|
||||
def run_file_check():
|
||||
"""
|
||||
立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。
|
||||
|
||||
核心逻辑:解析 task → 防并发锁 → 可选透传 mode/invoice_no(或 run_options)到
|
||||
ScheduleRun.api_request_json → 异步启动平台 Job。Dify 推荐填顶层 mode/invoice_no。
|
||||
|
||||
Body 关键字段(立账凭证检核):
|
||||
mode: incremental | force_all | single
|
||||
invoice_no: mode=single 时发票号
|
||||
run_options: 可选嵌套对象,与顶层字段合并(顶层优先)
|
||||
"""
|
||||
perf_started = time.perf_counter()
|
||||
data = _prepare_bind_payload(request.get_json(silent=True) or {})
|
||||
task = _resolve_check_task(data)
|
||||
resolve_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
|
||||
lock_started = time.perf_counter()
|
||||
with _RUN_START_LOCK:
|
||||
_acquire_task_start_lock(task.id)
|
||||
existing = (
|
||||
ScheduleRun.query.filter_by(schedule_task_id=task.id, status="running")
|
||||
.order_by(ScheduleRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
if existing:
|
||||
_record_run_bind(existing, data)
|
||||
db.session.commit()
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
current_app.logger.info(
|
||||
"[file-check-tool-perf] run_file_check outcome=check_running resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
existing.id,
|
||||
)
|
||||
return jsonify({
|
||||
"ok": False,
|
||||
"error_code": "check_running",
|
||||
"message": "该检核任务正在执行中,请稍后查询结果",
|
||||
"run": _serialize_tool_run(existing),
|
||||
})
|
||||
|
||||
no_data_response = _precheck_no_data(task)
|
||||
if no_data_response:
|
||||
run = _create_no_data_run(task, data)
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
current_app.logger.info(
|
||||
"[file-check-tool-perf] run_file_check outcome=no_data resolve_ms=%s lock_ms=%s total_ms=%s task_id=%s run_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
task.id,
|
||||
run.id,
|
||||
)
|
||||
return jsonify(_build_no_data_response(task, run))
|
||||
|
||||
# [STEP] 解析运行选项:优先顶层 mode/invoice_no(Dify Tool 表单对嵌套 object 常不展示),
|
||||
# 再与 run_options 对象合并;立账凭证检核读取,普通文件检核忽略。
|
||||
raw_options = data.get("run_options") if isinstance(data.get("run_options"), dict) else {}
|
||||
run_options = {}
|
||||
mode = str(data.get("mode") or raw_options.get("mode") or "").strip().lower()
|
||||
if mode in {"incremental", "force_all", "single"}:
|
||||
run_options["mode"] = mode
|
||||
invoice_no = data.get("invoice_no")
|
||||
if invoice_no is None or not str(invoice_no).strip():
|
||||
invoice_no = raw_options.get("invoice_no")
|
||||
if invoice_no is not None and str(invoice_no).strip():
|
||||
run_options["invoice_no"] = str(invoice_no).strip()
|
||||
|
||||
api_request_json = {
|
||||
"trigger_source": data.get("trigger_source") or "dify_chatflow",
|
||||
"conversation_id": data.get("conversation_id"),
|
||||
}
|
||||
if run_options:
|
||||
api_request_json["run_options"] = run_options
|
||||
|
||||
run = ScheduleRun(
|
||||
run_no=_generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
trigger_type="dify_chatflow",
|
||||
started_at=datetime.utcnow(),
|
||||
status="running",
|
||||
api_request_json=api_request_json,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
_record_run_bind(run, data)
|
||||
db.session.commit()
|
||||
run_id = run.id
|
||||
task_id = task.id
|
||||
|
||||
enqueue(
|
||||
JobType.FILE_CHECK_RUN,
|
||||
{"task_id": task_id, "schedule_run_id": run_id},
|
||||
domain="file_check",
|
||||
business_ref=str(run_id),
|
||||
message="等待执行文件检核",
|
||||
)
|
||||
db.session.refresh(run)
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
current_app.logger.info(
|
||||
"[file-check-tool-perf] run_file_check outcome=started resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
run_id,
|
||||
)
|
||||
return jsonify({"ok": True, "message": "检核已启动", "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/runs/<int:run_id>", methods=["GET"])
|
||||
def get_file_check_run(run_id: int):
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/runs", methods=["GET"])
|
||||
def list_file_check_runs():
|
||||
raw_task_id = request.args.get("task_id", type=int)
|
||||
raw_limit = request.args.get("limit", default=20, type=int)
|
||||
limit = max(1, min(int(raw_limit or 20), 100))
|
||||
if raw_task_id is not None:
|
||||
task = _resolve_check_task(task_id=raw_task_id)
|
||||
query = ScheduleRun.query.filter_by(schedule_task_id=task.id)
|
||||
else:
|
||||
query = ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
|
||||
rows = query.order_by(ScheduleRun.created_at.desc()).limit(limit).all()
|
||||
runs = [_serialize_tool_run(row) for row in rows]
|
||||
return jsonify({"ok": True, "runs": runs, "count": len(runs)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/runs/<int:run_id>/excel", methods=["GET"])
|
||||
def download_file_check_run_excel(run_id: int):
|
||||
token_payload = _decode_download_token(request.args.get("token"))
|
||||
if token_payload:
|
||||
if token_payload.get("scope") not in _EXCEL_TOKEN_SCOPES or int(token_payload.get("run_id") or 0) != run_id:
|
||||
raise UnauthorizedError("Unauthorized")
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
if not run.excel_file_data:
|
||||
raise ConflictError("excel_not_ready")
|
||||
filename = run.excel_file_name or f"{run.run_no}.xlsx"
|
||||
return send_file(
|
||||
BytesIO(run.excel_file_data),
|
||||
as_attachment=True,
|
||||
download_name=filename,
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/tasks/<int:task_id>/latest-run", methods=["GET"])
|
||||
def get_latest_file_check_run(task_id: int):
|
||||
"""查询任务最近批次;可绑定本轮对话以展示该批次进度。"""
|
||||
task = _resolve_check_task(task_id=task_id)
|
||||
run = ScheduleRun.query.filter_by(schedule_task_id=task.id).order_by(ScheduleRun.id.desc()).first()
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
_bind_queried_run_to_turn(run, {
|
||||
"hxops_turn_id": request.args.get("hxops_turn_id"),
|
||||
"conversation_id": request.args.get("conversation_id"),
|
||||
"user_message": request.args.get("user_message"),
|
||||
})
|
||||
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/history/search", methods=["POST"])
|
||||
def search_file_check_history():
|
||||
"""
|
||||
检索已入库的历史检核报告片段;按 task_id 解析 ScheduleTask → KbGroup → Dify Dataset。
|
||||
|
||||
核心逻辑:Chatflow history_report_query 分支调用;task_id 来自 HXOPS 注入的 Start 变量。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
raw_task_id = data.get("task_id")
|
||||
try:
|
||||
task_id = int(raw_task_id)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError("task_id_invalid")
|
||||
if task_id <= 0:
|
||||
raise ValidationError("task_id_invalid")
|
||||
|
||||
from app.services.file_check_tools.history_search_service import search_file_check_history as run_history_search
|
||||
|
||||
result = run_history_search(
|
||||
task_id=task_id,
|
||||
query=str(data.get("query") or ""),
|
||||
top_k=data.get("top_k"),
|
||||
score_threshold=data.get("score_threshold"),
|
||||
)
|
||||
return jsonify({"ok": True, **result})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def file_check_openapi_spec():
|
||||
return jsonify(build_file_check_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
|
||||
__all__ = [
|
||||
'file_check_bp',
|
||||
'enqueue',
|
||||
'_precheck_no_data',
|
||||
'_build_excel_download_url',
|
||||
'_RUN_START_LOCK',
|
||||
'get_schedule_sql_config_by_task_id',
|
||||
'_build_srm_conn_str',
|
||||
'_fetch_records',
|
||||
]
|
||||
+85
-19
@@ -1,4 +1,4 @@
|
||||
"""backend/app/api/in_transit_transfer.py
|
||||
"""backend/app/api/in_transit_transfer/__init__.py
|
||||
|
||||
用途:在途仓自动调拨用户态 API(仓库管理人员)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、app.core.response、matching_service、deps。
|
||||
@@ -65,12 +65,12 @@ def _require_user():
|
||||
|
||||
|
||||
def require_transfer_permission(f):
|
||||
"""装饰器:admin 放行,或持有 in_transit_transfer Agent 权限的用户放行。"""
|
||||
"""装饰器:平台管理员放行,或持有 in_transit_transfer Agent 权限的用户放行。"""
|
||||
|
||||
@wraps(f)
|
||||
def decorated(*args, **kwargs):
|
||||
user = _require_user()
|
||||
if user.role == "admin":
|
||||
if user.is_platform_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:
|
||||
@@ -322,15 +322,18 @@ def retrigger_document_api(run_no: str, doc_no: str):
|
||||
@in_transit_transfer_bp.route("/documents", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def list_documents_api():
|
||||
"""已执行单分页查询(首页「已执行」区块数据源;只读,不写审计)。
|
||||
"""已执行单分页查询(首页「执行看板」区块数据源;只读,不写审计)。
|
||||
|
||||
Query:
|
||||
status_group ∈ {success, failed, executing, result_unknown}(可选,缺省全部;
|
||||
非法 400);date_from/date_to=YYYY-MM-DD(可选,仅作用 orders 列表);
|
||||
非法 400);date_from/date_to=YYYY-MM-DD(可选,仅作用 orders 列表,
|
||||
按收料日期过滤——列表展示的业务日期口径,2026-09-29 由 created_at 切换);
|
||||
page(默认 1);page_size(默认 20,上限 100)。
|
||||
口径:分组计数恒全量(GROUP BY status 对全部单统计,不受筛选影响——
|
||||
失败/结果未知/执行中=未完结即待办,全量才不漏;成功=累计产出);
|
||||
列表 created_at 倒序分页,cancelled 不展示(无产生路径)。
|
||||
列表按 收料日期→数据源→拨出/拨入库位 升序分页(2026-09-29 与可调拨
|
||||
明细/待处理池/结果卡统一口径,跨数据源不再乱序;执行落库时间仅作
|
||||
同序兜底),cancelled 不展示(无产生路径)。
|
||||
响应:{groups, total, page, page_size, orders:[serialize_executed_order 投影]}。
|
||||
"""
|
||||
from app import db
|
||||
@@ -383,19 +386,28 @@ def list_documents_api():
|
||||
for group, statuses in DOCUMENT_STATUS_GROUPS.items()
|
||||
}
|
||||
|
||||
# [STEP 3] 列表查询:status_group / created_at 时间窗仅作用列表;
|
||||
# cancelled 恒不展示;created_at 倒序稳定分页(id 兜底同刻排序)。
|
||||
# [STEP 3] 列表查询:status_group / 时间窗仅作用列表;cancelled 恒不展示。
|
||||
# [2026-09-29 口径] 时间窗按收料日期过滤(receipt_date 为 ISO 日期字符串,
|
||||
# 字典序即时间序);排序与可调拨明细/结果卡统一:收料日期→数据源→库位升序,
|
||||
# created_at/id 兜底稳定分页(跨数据源不再按落库序乱序)。
|
||||
query = TransferDocument.query.filter(TransferDocument.status != "cancelled")
|
||||
if status_group:
|
||||
query = query.filter(TransferDocument.status.in_(DOCUMENT_STATUS_GROUPS[status_group]))
|
||||
if date_from:
|
||||
query = query.filter(TransferDocument.created_at >= datetime(date_from.year, date_from.month, date_from.day))
|
||||
query = query.filter(TransferDocument.receipt_date >= date_from.isoformat())
|
||||
if date_to:
|
||||
window_end = datetime(date_to.year, date_to.month, date_to.day) + timedelta(days=1)
|
||||
query = query.filter(TransferDocument.created_at < window_end)
|
||||
window_end = (date_to + timedelta(days=1)).isoformat()
|
||||
query = query.filter(TransferDocument.receipt_date < window_end)
|
||||
total = query.count()
|
||||
docs = (
|
||||
query.order_by(TransferDocument.created_at.desc(), TransferDocument.id.desc())
|
||||
query.order_by(
|
||||
TransferDocument.receipt_date.asc(),
|
||||
TransferDocument.source_code.asc(),
|
||||
TransferDocument.from_warehouse.asc(),
|
||||
TransferDocument.to_warehouse.asc(),
|
||||
TransferDocument.created_at.asc(),
|
||||
TransferDocument.id.asc(),
|
||||
)
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
@@ -507,9 +519,9 @@ def retry_document_api(doc_no: str):
|
||||
|
||||
门禁:仅 business_failed/technical_failed 可重试;result_unknown → 400
|
||||
(D11 唯一出口=重新触发);pending/executing 在飞拒绝;单不存在 404。
|
||||
行为:单内 blocked 行逐行重查(复用 retry_item,单行隔离)→ 全部 ready 则
|
||||
自动建新 Run 重跑(prepare_execution,D7①分支②复用原单号);任一行仍
|
||||
阻断则不重跑(单是原子单位),阻断明细随响应返回由恢复池兜底。
|
||||
行为:单内 blocked 行按组织批量重查(一次外部查询,行级 Attempt/隔离不变)
|
||||
→ 全部 ready 则自动建新 Run 重跑(prepare_execution,D7①分支②复用原单号);
|
||||
任一行仍阻断则不重跑(单是原子单位),阻断明细随响应返回由恢复池兜底。
|
||||
"""
|
||||
from app.services.in_transit_transfer.retry_service import retry_document
|
||||
|
||||
@@ -525,7 +537,7 @@ def retry_document_api(doc_no: str):
|
||||
@in_transit_transfer_bp.route("/items/batch-requery", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def batch_requery_items_api():
|
||||
"""批量重查外部系统库存(待处理池多选「重查」;单行隔离)。"""
|
||||
"""批量重查外部系统库存(待处理池多选「重查」;单行隔离,按组织一次外部查询)。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
item_ids = _require_item_ids(body)
|
||||
@@ -698,7 +710,7 @@ def transfer_metrics_api():
|
||||
def transfer_sources_api():
|
||||
"""来源实例列表(决策 3:平台 DBS/Crane 仅分组,实例为执行边界)。
|
||||
|
||||
每来源附收料文件状态(ready/fetching/failed/expired/none + has_ready_file),
|
||||
每来源附收料文件状态(ready/parse_failed/fetching/failed/expired/none + has_ready_file),
|
||||
供前端门禁(无 ready 文件时禁止确认匹配)与状态标识;保留期已到或非当天
|
||||
(业务日)抓取且未清理均投影 expired。只读复用已启用库存来源。
|
||||
"""
|
||||
@@ -725,13 +737,41 @@ def transfer_sources_api():
|
||||
def retry_source_rpa_api(source_code: str):
|
||||
"""对指定来源重新触发一次收料 RPA 抓取(复用货代收料 trigger 链路)。
|
||||
|
||||
响应:{"source_code", "file_status", "ok"};配置缺失时 fail-closed(ok=False)。
|
||||
【AI 触发时机】来源收料文件不可用需要恢复时调用:解析失败(parse_failed)先
|
||||
本地重解析已归档文件;文件缺失/失效(none/expired/failed)才重新触发 RPA 抓取。
|
||||
|
||||
解析失败优先本地重解析(解析失败分层 2026-09-29):当日文件可用但解析失败时,
|
||||
先走 sync_and_commit_for_callback 重解析归档文件——成功且投影回 ready →
|
||||
200 {"source_code", "ok": true, "file_status": "ready", "reparsed": true}
|
||||
(不触发 RPA、不返回 202/fetching);仍失败 → 同结构 ok=false
|
||||
(file_status=parse_failed)。其余状态沿用原路径:重新触发一次收料 RPA,
|
||||
成功 202+fetching;配置缺失时 fail-closed(ok=False)。
|
||||
"""
|
||||
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
|
||||
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()
|
||||
|
||||
# [STEP 1] 解析失败分层:文件可用但解析失败 → 先本地重解析归档文件,不触发 RPA。
|
||||
status = resolve_source_file_status(source_code=source_code)
|
||||
if status.get("file_status") == "parse_failed" and status.get("file_sha256"):
|
||||
synced = sync_and_commit_for_callback(
|
||||
source_code=source_code,
|
||||
business_date=str(business_date_now()),
|
||||
now=datetime.utcnow(),
|
||||
)
|
||||
# 重解析后再取投影:以真实落库事实(而非 sync 返回值)决定 ok。
|
||||
status = resolve_source_file_status(source_code=source_code)
|
||||
ready = bool(synced) and status.get("file_status") == "ready"
|
||||
return _ok({
|
||||
"source_code": source_code,
|
||||
"ok": ready,
|
||||
"file_status": status["file_status"],
|
||||
"reparsed": True,
|
||||
})
|
||||
|
||||
# [STEP 2] 其余状态沿用原路径:重新触发一次收料 RPA 抓取(202 + fetching)。
|
||||
outcome = trigger_receipt_rpa(
|
||||
source_code=source_code,
|
||||
business_date=str(business_date_now()),
|
||||
@@ -753,6 +793,32 @@ def retry_source_rpa_api(source_code: str):
|
||||
}, status=202)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/sources/retry-rpa-batch", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def retry_sources_rpa_batch_api():
|
||||
"""批量重试多来源收料 RPA:全部有效来源合并写**一个** batch trigger(一文件 N units)。
|
||||
|
||||
【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个来源编码时调用;
|
||||
逐来源调用单来源端点会产生 N 个 trigger 文件,Worker 每文件开/关一次浏览器;
|
||||
合并单文件后 Worker 单次登录串行导出全部来源(与收料排程路径同效率)。
|
||||
|
||||
请求体:{"source_codes": ["DSV360_AWSBI", ...]}。逐来源解析失败分层与
|
||||
fail-closed 语义同单来源端点;单源配置缺失跳过并记录,不阻断其余来源。
|
||||
"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
source_codes = [str(code).strip() for code in (payload.get("source_codes") or []) if str(code).strip()]
|
||||
if not source_codes:
|
||||
raise ValidationError("source_codes is required")
|
||||
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa_batch
|
||||
|
||||
outcome = trigger_receipt_rpa_batch(
|
||||
source_codes=source_codes,
|
||||
business_date=str(business_date_now()),
|
||||
reason="transfer_retry_receipt",
|
||||
)
|
||||
return _ok(outcome)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/backlog", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def backlog_api():
|
||||
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
backend/app/api/integration.py
|
||||
backend/app/api/integration/__init__.py
|
||||
|
||||
用途:知识库外部集成查询/下载接口(供 Dify Tool 与聊天源文件预览解析)。
|
||||
依赖:Flask Blueprint、SQLAlchemy、IntegrationApiService、Kb* 模型。
|
||||
+3
-1
@@ -1,4 +1,6 @@
|
||||
"""api/integration_connector.py
|
||||
"""
|
||||
backend/app/api/integration_connector/__init__.py
|
||||
|
||||
|
||||
用途:Integration Connector Admin API——配置实体 CRUD、能力清单、能力调用端点、
|
||||
连接测试与集成调用日志查询(列表 + 详情 + 同 operation 步骤时间线)。
|
||||
@@ -1,7 +1,9 @@
|
||||
"""
|
||||
backend/app/api/internal/__init__.py
|
||||
|
||||
用途:内部 job 回调/健康检查 Blueprint。
|
||||
用途:内部 Job 回调 / 健康检查 Blueprint 包。
|
||||
依赖:internal.jobs。
|
||||
逻辑:register_blueprints 从本包导入 internal_jobs_bp,挂载 /api/internal/jobs。
|
||||
"""
|
||||
from app.api.internal.jobs import internal_jobs_bp # noqa: F401
|
||||
|
||||
|
||||
@@ -1,8 +1,223 @@
|
||||
"""
|
||||
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。
|
||||
逻辑:标准化 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.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,223 +0,0 @@
|
||||
"""
|
||||
backend/app/api/internal_jobs.py
|
||||
|
||||
用途:平台内置 Job 内部 API(POST /api/internal/jobs/<job_key>)。
|
||||
依赖:job_registry、schedule_contract、scheduler_service。
|
||||
逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||
from app.services.schedule.job_registry import get_platform_job, run_platform_job
|
||||
from app.services.schedule.schedule_contract import normalize_job_key
|
||||
from app.services.schedule.scheduler_service import _generate_run_no
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import (
|
||||
apply_deferred_schedule_run_state,
|
||||
recover_stale_awaiting_rpa_schedule_runs,
|
||||
should_defer_schedule_run_finalization,
|
||||
)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import (
|
||||
apply_deferred_receipt_schedule_run_state,
|
||||
recover_stale_receipt_rpa_schedule_runs,
|
||||
should_defer_receipt_schedule_run,
|
||||
)
|
||||
|
||||
internal_jobs_bp = Blueprint('internal_jobs', __name__)
|
||||
|
||||
|
||||
def _assert_task_matches_job_key(task: ScheduleTask, job_key: str) -> None:
|
||||
"""
|
||||
校验 task 与 URL job key 一致,防止 schedule_task_id 指向错误 handler。
|
||||
Raises:
|
||||
ValidationError: 非 platform_job 或 platform_api_path 不匹配
|
||||
"""
|
||||
if task.schedule_type != 'platform_job':
|
||||
raise ValidationError(f"schedule_task_id {task.id} is not a platform_job task")
|
||||
task_key = normalize_job_key(task.platform_api_path)
|
||||
if task_key != job_key:
|
||||
raise ValidationError(
|
||||
f"schedule_task_id {task.id} platform_api_path '{task.platform_api_path}' "
|
||||
f"does not match job key '{job_key}'"
|
||||
)
|
||||
|
||||
|
||||
def _resolve_schedule_task_and_run(job_key: str, data: dict) -> tuple[ScheduleTask, ScheduleRun]:
|
||||
"""
|
||||
解析或创建 ScheduleTask / ScheduleRun。
|
||||
核心逻辑:优先 schedule_task_id(须匹配 job key);否则按 platform_api_path 匹配 job key。
|
||||
run_no 查询限定 schedule_task_id,避免跨任务写入。
|
||||
"""
|
||||
schedule_task_id = data.get('schedule_task_id')
|
||||
task = db.session.get(ScheduleTask, int(schedule_task_id)) if schedule_task_id else None
|
||||
if task:
|
||||
_assert_task_matches_job_key(task, job_key)
|
||||
else:
|
||||
task = (
|
||||
ScheduleTask.query.filter(
|
||||
ScheduleTask.platform_api_path == job_key,
|
||||
ScheduleTask.schedule_type == 'platform_job',
|
||||
)
|
||||
.order_by(ScheduleTask.id.desc())
|
||||
.first()
|
||||
)
|
||||
if not task:
|
||||
raise NotFoundError(f"No schedule task found for platform job '{job_key}'")
|
||||
|
||||
run_no = str(data.get('run_no') or '').strip()
|
||||
run = None
|
||||
if run_no:
|
||||
run = ScheduleRun.query.filter_by(run_no=run_no, schedule_task_id=task.id).first()
|
||||
if not run:
|
||||
foreign = ScheduleRun.query.filter_by(run_no=run_no).first()
|
||||
if foreign and foreign.schedule_task_id != task.id:
|
||||
raise ValidationError(
|
||||
f"run_no '{run_no}' belongs to schedule_task_id {foreign.schedule_task_id}, "
|
||||
f"not {task.id}"
|
||||
)
|
||||
if not run:
|
||||
run = ScheduleRun(
|
||||
run_no=run_no or _generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
trigger_type='api',
|
||||
started_at=datetime.utcnow(),
|
||||
status='running',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
if not run.dify_execution_snapshot:
|
||||
capture_dify_execution_snapshot(run, task)
|
||||
db.session.commit()
|
||||
return task, run
|
||||
|
||||
|
||||
def _finalize_run(
|
||||
run: ScheduleRun,
|
||||
*,
|
||||
total_count: int,
|
||||
success_count: int,
|
||||
failed_count: int,
|
||||
skipped_count: int,
|
||||
step_logs: list | None,
|
||||
) -> None:
|
||||
"""写入 run 汇总字段并 commit。"""
|
||||
run.status = (
|
||||
'success' if failed_count == 0
|
||||
else 'failed' if success_count == 0
|
||||
else 'partial_failed'
|
||||
)
|
||||
run.total_count = total_count
|
||||
run.success_count = success_count
|
||||
run.failed_count = failed_count
|
||||
run.skipped_count = skipped_count
|
||||
run.finished_at = datetime.utcnow()
|
||||
if run.started_at and run.finished_at:
|
||||
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000)
|
||||
run.step_logs = step_logs if step_logs else None
|
||||
db.session.commit()
|
||||
|
||||
|
||||
@internal_jobs_bp.route('/<name>', methods=['POST'])
|
||||
def run_internal_job(name: str):
|
||||
"""
|
||||
执行已注册平台 Job。
|
||||
核心逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。
|
||||
"""
|
||||
key = normalize_job_key(name)
|
||||
data = request.get_json(silent=True) or {}
|
||||
|
||||
if not get_platform_job(key):
|
||||
raise NotFoundError(f"Unknown platform job: {name}")
|
||||
|
||||
task, run = _resolve_schedule_task_and_run(key, data)
|
||||
recover_stale_awaiting_rpa_schedule_runs(task)
|
||||
recover_stale_receipt_rpa_schedule_runs(task)
|
||||
try:
|
||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = run_platform_job(
|
||||
key, task, run, data,
|
||||
)
|
||||
except Exception as exc:
|
||||
run.status = 'failed'
|
||||
run.error_message = str(exc)
|
||||
run.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
raise AppError(
|
||||
code='SYSTEM.HTTP_ERROR',
|
||||
message=str(exc),
|
||||
http_status=500,
|
||||
details={
|
||||
'traceback': traceback.format_exc(),
|
||||
'summary': {
|
||||
'total_count': 0,
|
||||
'success_count': 0,
|
||||
'failed_count': 0,
|
||||
'skipped_count': 0,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
if should_defer_schedule_run_finalization(task, step_logs):
|
||||
apply_deferred_schedule_run_state(
|
||||
run,
|
||||
task,
|
||||
total_count=total_count,
|
||||
success_count=success_count,
|
||||
failed_count=failed_count,
|
||||
skipped_count=skipped_count,
|
||||
details=details,
|
||||
errors=errors,
|
||||
step_logs=step_logs,
|
||||
)
|
||||
return jsonify({
|
||||
'summary': {
|
||||
'total_count': total_count,
|
||||
'success_count': success_count,
|
||||
'failed_count': failed_count,
|
||||
'skipped_count': skipped_count,
|
||||
},
|
||||
'details': details,
|
||||
'errors': errors,
|
||||
'step_logs': step_logs,
|
||||
'awaiting_rpa_callback': True,
|
||||
})
|
||||
|
||||
if should_defer_receipt_schedule_run(task, step_logs):
|
||||
apply_deferred_receipt_schedule_run_state(
|
||||
run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs,
|
||||
)
|
||||
return jsonify({
|
||||
'summary': {
|
||||
'total_count': total_count, 'success_count': success_count,
|
||||
'failed_count': failed_count, 'skipped_count': skipped_count,
|
||||
},
|
||||
'details': details, 'errors': errors, 'step_logs': step_logs,
|
||||
'awaiting_receipt_rpa_callback': True,
|
||||
})
|
||||
|
||||
_finalize_run(
|
||||
run,
|
||||
total_count=total_count,
|
||||
success_count=success_count,
|
||||
failed_count=failed_count,
|
||||
skipped_count=skipped_count,
|
||||
step_logs=step_logs,
|
||||
)
|
||||
return jsonify({
|
||||
'summary': {
|
||||
'total_count': total_count,
|
||||
'success_count': success_count,
|
||||
'failed_count': failed_count,
|
||||
'skipped_count': skipped_count,
|
||||
},
|
||||
'details': details,
|
||||
'errors': errors,
|
||||
'step_logs': step_logs,
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
backend/app/api/linked_services.py
|
||||
backend/app/api/linked_services/__init__.py
|
||||
|
||||
用途:已登录用户读取启用中的关联服务,供 Chat/工作台侧栏入口展示。
|
||||
依赖:JWT current-user、linked_service_service。
|
||||
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
backend/app/api/maintenance.py
|
||||
backend/app/api/maintenance/__init__.py
|
||||
|
||||
用途:设备维保助手 HTTP API,当前提供设备台账配置与 Excel 导入能力。
|
||||
依赖:JWT 当前用户、maintenance_ledger_service、Flask Blueprint/send_file。
|
||||
@@ -55,9 +55,9 @@ def _require_ledger_admin():
|
||||
ForbiddenError: 当前角色不允许写入台账或维修记录。
|
||||
"""
|
||||
user = _require_user()
|
||||
if getattr(user, 'role', None) not in {'admin', 'maintenance_manager'}:
|
||||
raise ForbiddenError('Maintenance manager privilege required')
|
||||
return user
|
||||
if user.has_feature_permission('maintenance.ledger_write'):
|
||||
return user
|
||||
raise ForbiddenError('Maintenance manager privilege required')
|
||||
|
||||
|
||||
def _record_list_filters_from_request() -> dict[str, Any]:
|
||||
@@ -1,149 +1,10 @@
|
||||
"""
|
||||
backend/app/api/maintenance_tools.py
|
||||
|
||||
用途:设备维保助手 Dify Tool API,只开放只读查询工具。
|
||||
依赖:maintenance_chat_service、maintenance_record_service、OpenAPI 构建、Tool API 基地址解析。
|
||||
逻辑:Dify 复杂问法调用本蓝图查询设备台账/维修记录;明确查询仍由 chat.py 本地直答,写操作仍走 HXOPS 管理面板。
|
||||
用途:兼容旧 import 路径的薄 shim(真实现已迁至 api/tools/maintenance.py)。
|
||||
依赖:app.api.tools.maintenance。
|
||||
逻辑:保留 Blueprint;新代码请从 app.api.tools 导入。
|
||||
"""
|
||||
from app.api.tools.maintenance import maintenance_tool_bp # noqa: F401
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError, ValidationError
|
||||
from app.models import MaintenanceRecord
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
|
||||
from app.services.maintenance_chat_service import build_device_query_result
|
||||
from app.services.maintenance_record_service import serialize_record
|
||||
from app.services.maintenance_tools.openapi_spec import build_maintenance_openapi_spec
|
||||
|
||||
maintenance_tool_bp = Blueprint("maintenance_tools", __name__)
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验设备维保 Tool API 鉴权。
|
||||
AI 触发时机:Dify Tool 调用本蓝图时由 before_request 自动执行,不是给 LLM 直接调用的业务工具。
|
||||
"""
|
||||
configured = str(
|
||||
current_app.config.get("MAINTENANCE_TOOL_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
or ""
|
||||
).strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError(
|
||||
"MAINTENANCE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured",
|
||||
code="missing_auth",
|
||||
)
|
||||
|
||||
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||
if configured in {token, integration_key}:
|
||||
return
|
||||
if not token and not integration_key:
|
||||
raise UnauthorizedError("missing_auth")
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
"""把 AppError 归一成 Dify Tool 侧可读错误码。"""
|
||||
message = str(exc.message or "").strip()
|
||||
if message in {"missing_auth", "invalid_auth"}:
|
||||
return message
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
return "missing_auth"
|
||||
if exc.code == "VALIDATION.INVALID_PARAM":
|
||||
return message or "invalid_request"
|
||||
return exc.code
|
||||
|
||||
|
||||
@maintenance_tool_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
"""Tool API 统一错误响应。"""
|
||||
return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status
|
||||
|
||||
|
||||
@maintenance_tool_bp.before_request
|
||||
def _verify_tool_access():
|
||||
"""除 OpenAPI 文档外,所有 Tool 调用必须携带有效服务级 token。"""
|
||||
if request.path.endswith("/openapi.json") or request.path.endswith("/openapi.dify.yaml"):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
def _payload() -> dict:
|
||||
"""读取 JSON 请求体。"""
|
||||
return request.get_json(silent=True) or {}
|
||||
|
||||
|
||||
def _clean_text(value) -> str:
|
||||
return str(value or "").strip()
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def openapi_spec():
|
||||
"""返回 Dify 导入用的 OpenAPI JSON。"""
|
||||
return jsonify(build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/openapi.dify.yaml", methods=["GET"])
|
||||
def openapi_dify_yaml():
|
||||
"""返回 Dify 导入用的 OpenAPI YAML。"""
|
||||
import yaml
|
||||
|
||||
body = yaml.safe_dump(
|
||||
build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()),
|
||||
allow_unicode=True,
|
||||
sort_keys=False,
|
||||
)
|
||||
return current_app.response_class(body, mimetype="text/yaml; charset=utf-8")
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/query_device", methods=["POST"])
|
||||
def query_device():
|
||||
"""按设备编号或名称查询设备台账,并可带出最近维修记录。"""
|
||||
data = _payload()
|
||||
keyword = _clean_text(data.get("keyword"))
|
||||
if not keyword:
|
||||
raise ValidationError("keyword is required")
|
||||
include_records = bool(data.get("include_records", True))
|
||||
record_limit = max(0, min(20, int(data.get("record_limit") or 5)))
|
||||
result = build_device_query_result(keyword, include_records=include_records, record_limit=record_limit)
|
||||
return jsonify({"ok": True, **result})
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/query_records", methods=["POST"])
|
||||
def query_records():
|
||||
"""按设备编号/名称和状态查询维修记录。"""
|
||||
data = _payload()
|
||||
keyword = _clean_text(data.get("keyword"))
|
||||
if not keyword:
|
||||
raise ValidationError("keyword is required")
|
||||
status = _clean_text(data.get("status"))
|
||||
limit = max(1, min(50, int(data.get("limit") or 10)))
|
||||
|
||||
query = db.session.query(MaintenanceRecord)
|
||||
like = f"%{keyword}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
MaintenanceRecord.device_code.ilike(like),
|
||||
MaintenanceRecord.device_name.ilike(like),
|
||||
)
|
||||
)
|
||||
if status:
|
||||
query = query.filter(MaintenanceRecord.repair_status == status)
|
||||
rows = query.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc()).limit(limit).all()
|
||||
return jsonify({
|
||||
"ok": True,
|
||||
"matched": bool(rows),
|
||||
"keyword": keyword,
|
||||
"items": [serialize_record(item) for item in rows],
|
||||
"totalReturned": len(rows),
|
||||
})
|
||||
|
||||
__all__ = ['maintenance_tool_bp']
|
||||
@@ -0,0 +1,320 @@
|
||||
"""
|
||||
backend/app/api/order_delivery_reply.py
|
||||
|
||||
用途:订单交期回复工作台 API——列表筛选分页、单行详情、最近同步时间、保存交期批次、单行通知、
|
||||
联合回复保存与批量通知、手动全量同步。
|
||||
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError/NotFoundError/ValidationError、
|
||||
services/order_delivery_reply(query_service 查询、reply_service 保存批次、
|
||||
notify_service 通知锁定、sync_service 同步状态)。
|
||||
逻辑:读取只打本地快照,不触碰 ERP;保存批次只写批次与 save 审计,不通知不锁定;
|
||||
通知与锁定在 notify_service 中同事务完成(企微成功才锁定)。
|
||||
权限要求 access 或 manage(manage 隐含 access),键常量与技术文档 §7.2 一致;写接口要求 manage。
|
||||
鉴权:GET 系列要求 `order_delivery_reply.access` 或 `order_delivery_reply.manage`;
|
||||
保存批次 / 单行通知 / 联合回复 / 批量通知 / 手动同步要求 `order_delivery_reply.manage`;
|
||||
部门批量发放仅 admin 角色。两键 admin 默认开(User._role_default_feature_permissions)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from io import BytesIO
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from flask import Blueprint, g, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.extensions import db
|
||||
from app.models import User
|
||||
from app.services.order_delivery_reply import notify_service, query_service, reply_service
|
||||
from app.services.order_delivery_reply.sync_service import OrderDeliverySyncService
|
||||
|
||||
order_delivery_reply_bp = Blueprint("order_delivery_reply", __name__)
|
||||
|
||||
XLSX_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
|
||||
|
||||
def _utc_to_shanghai(value) -> str | None:
|
||||
"""
|
||||
把后端 naive-UTC 时间转为北京时间的展示字符串(YYYY-MM-DD HH:MM:SS)。
|
||||
|
||||
用途:sync_runs / notified_at 等以 utcnow 落库,直接 isoformat 会把 UTC 当本地时间误导用户。
|
||||
约束:仅用于展示序列化,不改变库内存储;无法解析时原样返回。
|
||||
"""
|
||||
from datetime import timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
local = value.replace(tzinfo=timezone.utc).astimezone(ZoneInfo("Asia/Shanghai"))
|
||||
return local.strftime("%Y-%m-%d %H:%M:%S")
|
||||
except (AttributeError, ValueError):
|
||||
return value.isoformat() if hasattr(value, "isoformat") else str(value)
|
||||
|
||||
# 功能权限键(与 docs/features/order-delivery-reply/technical-design.md §7.2 对齐)。
|
||||
PERMISSION_MANAGE = "order_delivery_reply.manage"
|
||||
PERMISSION_ACCESS = "order_delivery_reply.access"
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""返回当前登录用户;未认证抛 UnauthorizedError。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _has_order_delivery_permission(user, key: str) -> bool:
|
||||
"""
|
||||
判定功能权限:统一走 User.has_feature_permission(角色默认 + 显式勾选合并)。
|
||||
|
||||
核心逻辑:admin 角色两键默认开(User._role_default_feature_permissions);
|
||||
普通用户按用户管理表单勾选;每次请求只看勾选,不拿部门当门禁(技术文档 §7.2)。
|
||||
"""
|
||||
return user.has_feature_permission(key)
|
||||
|
||||
|
||||
def _require_access():
|
||||
"""
|
||||
确保当前用户可访问订单交期回复(查看)。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 未登录。
|
||||
ForbiddenError: 已登录但既无 manage 也无 access(manage 命中视为有 access)。
|
||||
"""
|
||||
user = _require_user()
|
||||
if not (_has_order_delivery_permission(user, PERMISSION_MANAGE) or _has_order_delivery_permission(user, PERMISSION_ACCESS)):
|
||||
raise ForbiddenError(
|
||||
"Order delivery reply access required",
|
||||
code="ORDER_DELIVERY_REPLY.FORBIDDEN",
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
def _require_manage():
|
||||
"""
|
||||
确保当前用户可写订单交期回复(保存批次 / 通知 / 手动同步)。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 未登录。
|
||||
ForbiddenError: 已登录但无 manage(仅有 access 的业务用户只读)。
|
||||
"""
|
||||
user = _require_user()
|
||||
if not _has_order_delivery_permission(user, PERMISSION_MANAGE):
|
||||
raise ForbiddenError(
|
||||
"Order delivery reply manage permission required",
|
||||
code="ORDER_DELIVERY_REPLY.MANAGE_FORBIDDEN",
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
@order_delivery_reply_bp.get("/lines")
|
||||
def list_lines():
|
||||
"""
|
||||
订单行列表(筛选 + 分页)。
|
||||
|
||||
用途与触发时机:工作台首屏与筛选刷新;全选仅作用于本页返回的 items。
|
||||
|
||||
参数与输出约束:查询参数 keyword/order_date/status/page/page_size——keyword 为合并搜索
|
||||
(订单单号/客户订单/客户编号/客户简称/公司全名/产品编号/品名/客户产品编号
|
||||
命中任一即返回);status ∈ 空(全部) | replied(已回复) | not_fully_replied(未完全回复);
|
||||
返回统一 envelope,data.items 为行序列化(含批次、状态、未交数量)。
|
||||
"""
|
||||
_require_access()
|
||||
data = query_service.list_lines(request.args.to_dict(flat=True))
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@order_delivery_reply_bp.get("/lines/export")
|
||||
def export_lines():
|
||||
"""
|
||||
导出当前筛选下的全部订单行 Excel(不分页)。
|
||||
|
||||
用途与触发时机:工作台工具栏「导出 Excel」按钮;查询参数与列表一致
|
||||
(keyword/order_date/status),导出全部命中行(服务层 EXPORT_MAX_ROWS 兜底)。
|
||||
|
||||
参数与输出约束:要求 order_delivery_reply.access 及以上;返回 xlsx 文件流(attachment,
|
||||
文件名带北京时间日期)。
|
||||
"""
|
||||
_require_access()
|
||||
content = query_service.export_lines(request.args.to_dict(flat=True))
|
||||
filename = f"订单交期回复_{datetime.now(ZoneInfo('Asia/Shanghai')):%Y%m%d}.xlsx"
|
||||
return send_file(
|
||||
BytesIO(content),
|
||||
as_attachment=True,
|
||||
download_name=filename,
|
||||
mimetype=XLSX_MIME_TYPE,
|
||||
)
|
||||
|
||||
|
||||
@order_delivery_reply_bp.get("/lines/<order_no>/<int:line_no>")
|
||||
def get_line(order_no: str, line_no: int):
|
||||
"""
|
||||
单行详情:快照 + 批次 + 状态 + 审计事件。
|
||||
|
||||
参数与输出约束:order_no/line_no 为行唯一键;不存在或已标 erp_missing(已不在同步范围)
|
||||
的行一律按不存在处理返回 404,不在工作台展示。
|
||||
"""
|
||||
_require_access()
|
||||
payload = query_service.get_line(order_no, line_no)
|
||||
if payload is None:
|
||||
raise NotFoundError(
|
||||
"Order delivery line not found",
|
||||
code="ORDER_DELIVERY_REPLY.LINE_NOT_FOUND",
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@order_delivery_reply_bp.put("/lines/<order_no>/<int:line_no>/batches")
|
||||
def save_line_batches(order_no: str, line_no: int):
|
||||
"""
|
||||
保存单行交期批次(未锁定行整表替换)。
|
||||
|
||||
用途与触发时机:单行弹窗「回复交期/修改回复」提交;联合回复保存逐行复用同一服务入口。
|
||||
|
||||
参数与输出约束:body {"batches": [{planned_date, qty, remark?}]};交期必填 YYYY-MM-DD、
|
||||
数量 > 0、备注 ≤ 200、批次 1..20 条且交期不重复;各批次合计必须等于订单数量,
|
||||
不等返回 422 BATCH_QTY_TOTAL_MISMATCH(2026-09-23 由「超额仅提醒」修订)。
|
||||
已锁定行返回 409 LINE_LOCKED;erp_missing 行按 404。
|
||||
"""
|
||||
user = _require_manage()
|
||||
payload = request.get_json(silent=True) or {}
|
||||
data = reply_service.save_batches(order_no, line_no, payload.get("batches"), user.id)
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@order_delivery_reply_bp.post("/lines/<order_no>/<int:line_no>/notify")
|
||||
def notify_line(order_no: str, line_no: int):
|
||||
"""
|
||||
单行发送通知业务部门(企微),成功后行级锁定。
|
||||
|
||||
用途与触发时机:生管在行内点「发送通知业务部门」(该行已有批次且未锁定时可用)。
|
||||
|
||||
参数与输出约束:无 body;无批次 422(请先回复交期)、已锁定 409、业务员对不上
|
||||
User.employee_id 或企微发送失败 503(该行不锁定);成功返回
|
||||
locked=true 与交期回复人员(生管工号+姓名)、通知时间、trace_id。
|
||||
"""
|
||||
user = _require_manage()
|
||||
data = notify_service.notify_line(order_no, line_no, user)
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@order_delivery_reply_bp.post("/batch-reply")
|
||||
def batch_reply():
|
||||
"""
|
||||
联合回复交期:对勾选多行逐行保存批次(只保存,不通知、不锁定)。
|
||||
|
||||
用途与触发时机:勾选多行 →「+ 联合回复交期」→ 按行填批次 → 保存回复(R-REPLY-02)。
|
||||
|
||||
参数与输出约束:body {"items": [{order_no, line_no, batches: [{planned_date, qty, remark?}]}]},
|
||||
单次 ≤ 200 行;每行各批次合计必须等于订单数量(不等该行失败,2026-09-23 修订);
|
||||
单行失败不回滚其它行,响应按行给 ok/error;
|
||||
全部行保存成功 success 才为 true 语义由 data.succeeded/failed 表达。
|
||||
"""
|
||||
user = _require_manage()
|
||||
payload = request.get_json(silent=True) or {}
|
||||
data = reply_service.batch_reply(payload.get("items"), user.id)
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@order_delivery_reply_bp.post("/notify-batch")
|
||||
def notify_batch():
|
||||
"""
|
||||
批量通知:对勾选中「已有批次且未锁定」的行逐行发送企微通知并锁定。
|
||||
|
||||
用途与触发时机:勾选多行 → 工具栏「批量通知」(R-NOTIFY-02);与联合回复是两个独立操作。
|
||||
|
||||
参数与输出约束:body {"lines": [{order_no, line_no}]},单次 ≤ 200 行;
|
||||
无批次或已锁定的勾选行 skipped(带 reason)不计成败;
|
||||
单行失败不回滚其它行;返回 succeeded/failed/skipped 与逐行结果。
|
||||
"""
|
||||
user = _require_manage()
|
||||
payload = request.get_json(silent=True) or {}
|
||||
data = notify_service.notify_batch(payload.get("lines"), user)
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@order_delivery_reply_bp.get("/sync/latest")
|
||||
def latest_sync():
|
||||
"""
|
||||
最近一次同步运行记录,供页面展示同步时间与结果。
|
||||
|
||||
参数与输出约束:无参数;从未同步过时 data 为 null(前端展示「尚未同步」),
|
||||
失败时返回 failed 状态与错误摘要,前端明示同步失败并保留上次快照口径。
|
||||
"""
|
||||
_require_access()
|
||||
run = OrderDeliverySyncService.latest_run()
|
||||
if run is None:
|
||||
return ok(None, request_id=getattr(g, "request_id", None))
|
||||
return ok(
|
||||
{
|
||||
"id": run.id,
|
||||
"trigger": run.trigger,
|
||||
"status": run.status,
|
||||
"started_at": _utc_to_shanghai(run.started_at),
|
||||
"finished_at": _utc_to_shanghai(run.finished_at),
|
||||
"line_count": run.line_count,
|
||||
"error_message": run.error_message,
|
||||
},
|
||||
request_id=getattr(g, "request_id", None),
|
||||
)
|
||||
|
||||
|
||||
@order_delivery_reply_bp.post("/sync")
|
||||
def run_sync():
|
||||
"""
|
||||
手动触发一次 ERP 全量同步(范围与 07:00 排程完全一致)。
|
||||
|
||||
用途与触发时机:生管在工作台点「手动刷新」(需求 §15);同步互斥——排程正在跑时
|
||||
返回 skipped,不并发执行。
|
||||
|
||||
参数与输出约束:无 body;同步在本请求内同步执行(一期口径,行量在万级内可控),
|
||||
返回 {run_id, status: success|skipped, line_count};失败原样抛 AppError
|
||||
(上次快照保留,页面明示失败原因)。
|
||||
"""
|
||||
_require_manage()
|
||||
data = OrderDeliverySyncService.run_sync(trigger="manual")
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@order_delivery_reply_bp.post("/admin/permissions/grant-by-department")
|
||||
def grant_permissions_by_department():
|
||||
"""
|
||||
按部门批量发放订单交期回复功能权限(可选能力,仅 admin)。
|
||||
|
||||
用途与触发时机:用户量大时管理员选部门一次性把勾选写到当时该部门成员账号上(需求 §3)。
|
||||
|
||||
参数与输出约束:body {"department": "<部门名>", "permission": "manage" | "access"};
|
||||
这是一次性发放——调岗后权限不随部门字段变化自动增减,需再勾或再跑一次;
|
||||
只做授予(置 true),不撤销;返回 {"department", "permission", "granted"}。
|
||||
部门无成员时 granted=0,不视为错误。
|
||||
"""
|
||||
user = _require_user()
|
||||
if getattr(user, "role", None) != "admin":
|
||||
raise ForbiddenError(
|
||||
"Admin privilege required for department permission grant",
|
||||
code="ORDER_DELIVERY_REPLY.ADMIN_REQUIRED",
|
||||
)
|
||||
payload = request.get_json(silent=True) or {}
|
||||
department = str(payload.get("department") or "").strip()
|
||||
permission = str(payload.get("permission") or "").strip()
|
||||
if not department:
|
||||
raise ValidationError("department 必填", code="ORDER_DELIVERY_REPLY.GRANT_DEPARTMENT_REQUIRED")
|
||||
if permission not in (PERMISSION_MANAGE, PERMISSION_ACCESS):
|
||||
raise ValidationError("permission 须为 manage 或 access", code="ORDER_DELIVERY_REPLY.GRANT_PERMISSION_INVALID")
|
||||
|
||||
members = User.query.filter(User.department == department).all()
|
||||
granted = 0
|
||||
for member in members:
|
||||
# [STEP] 经 set_feature_permissions 归一化:只持久化与角色默认不同的覆盖项。
|
||||
raw = dict(member.feature_permissions) if isinstance(member.feature_permissions, dict) else {}
|
||||
raw[permission] = True
|
||||
member.set_feature_permissions(raw)
|
||||
granted += 1
|
||||
db.session.commit()
|
||||
return ok(
|
||||
{"department": department, "permission": permission, "granted": granted},
|
||||
request_id=getattr(g, "request_id", None),
|
||||
)
|
||||
@@ -1,111 +1,10 @@
|
||||
"""
|
||||
backend/app/api/procurement_contract_tools.py
|
||||
|
||||
Purpose: Chat/tool-facing procurement contract review APIs.
|
||||
Dependencies: procurement_contract services, JWT current user, unified response envelope.
|
||||
Flow: Authenticated users upload comparison files, start reviews, query own history, and download own reports.
|
||||
用途:兼容旧 import 路径的薄 shim(真实现已迁至 api/tools/procurement_contract.py)。
|
||||
依赖:app.api.tools.procurement_contract。
|
||||
逻辑:保留 Blueprint;新代码请从 app.api.tools 导入。
|
||||
"""
|
||||
from app.api.tools.procurement_contract import procurement_contract_bp # noqa: F401
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
|
||||
from flask import Blueprint, g, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.procurement_contract import review_service, template_service
|
||||
|
||||
procurement_contract_bp = Blueprint("procurement_contract", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""Return current authenticated user."""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _optional_int(value, field: str) -> int | None:
|
||||
"""Parse optional int payload fields with a ValidationError on bad input."""
|
||||
if value in (None, ""):
|
||||
return None
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(f"{field} must be integer") from exc
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/templates", methods=["GET"])
|
||||
def list_enabled_templates():
|
||||
"""List enabled templates for chat dropdown."""
|
||||
_require_user()
|
||||
return ok(template_service.list_enabled_for_chat(), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews", methods=["POST"])
|
||||
def start_contract_review():
|
||||
"""Start a review; compare mode requires a user-uploaded original contract baseline."""
|
||||
user = _require_user()
|
||||
data = request.get_json() or {}
|
||||
contract_asset_no = (data.get("contract_asset_no") or "").strip()
|
||||
if not contract_asset_no:
|
||||
raise ValidationError("contract_asset_no is required")
|
||||
result = review_service.start_review(
|
||||
user_id=user.id,
|
||||
review_mode=str(data.get("review_mode") or "compare"),
|
||||
contract_asset_no=contract_asset_no,
|
||||
original_contract_asset_no=(data.get("original_contract_asset_no") or None),
|
||||
contract_type=(data.get("contract_type") or None),
|
||||
supplier_name=(data.get("supplier_name") or None),
|
||||
agent_id=_optional_int(data.get("agent_id"), "agent_id"),
|
||||
chat_log_id=_optional_int(data.get("chat_log_id"), "chat_log_id"),
|
||||
)
|
||||
return ok(result, request_id=getattr(g, "request_id", None), status=202)
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews/<review_no>", methods=["GET"])
|
||||
def get_contract_review(review_no: str):
|
||||
"""Get a current user's review by review number."""
|
||||
user = _require_user()
|
||||
return ok(review_service.get_review_for_owner(review_no=review_no, user_id=user.id), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews/<review_no>/report", methods=["GET"])
|
||||
def download_my_contract_review_report(review_no: str):
|
||||
"""Download current user's review report as txt or docx."""
|
||||
user = _require_user()
|
||||
review_service.get_review_for_owner(review_no=review_no, user_id=user.id)
|
||||
if (request.args.get("format") or "").lower() == "docx":
|
||||
name, data, mimetype = review_service.read_review_report_docx_bytes(review_no=review_no)
|
||||
else:
|
||||
name, data = review_service.read_review_report_bytes(review_no=review_no)
|
||||
mimetype = "text/plain; charset=utf-8"
|
||||
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=name)
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews/<review_no>/annotated-contract", methods=["GET"])
|
||||
def download_my_annotated_contract(review_no: str):
|
||||
"""Download current user's original PDF with anchored risk highlights."""
|
||||
user = _require_user()
|
||||
review_service.get_review_for_owner(review_no=review_no, user_id=user.id)
|
||||
name, data, mimetype = review_service.read_review_annotated_contract_bytes(review_no=review_no)
|
||||
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=name)
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews", methods=["GET"])
|
||||
def list_my_contract_reviews():
|
||||
"""List current user's recent procurement contract reviews."""
|
||||
user = _require_user()
|
||||
data = review_service.list_reviews(
|
||||
user_id=user.id,
|
||||
review_mode=request.args.get("review_mode") or None,
|
||||
status=request.args.get("status") or None,
|
||||
keyword=request.args.get("keyword") or None,
|
||||
risk_level=request.args.get("risk_level") or None,
|
||||
limit=_optional_int(request.args.get("limit"), "limit") or 20,
|
||||
offset=_optional_int(request.args.get("offset"), "offset") or 0,
|
||||
)
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
__all__ = ['procurement_contract_bp']
|
||||
@@ -1,13 +1,15 @@
|
||||
"""
|
||||
backend/app/api/schedule/rpa_workers.py
|
||||
|
||||
用途:管理端查询货代库存 RPA Worker 在线状态与就绪摘要。
|
||||
用途:管理端查询货代库存/收料 RPA Worker 在线状态与就绪摘要。
|
||||
依赖:schedule.blueprint、rpa_worker_heartbeat.serialize_rpa_worker_status。
|
||||
逻辑:ScheduleWorkbenchPanel 在库存 RPA 排程工作台展示 worker 心跳状态。
|
||||
逻辑:ScheduleWorkbenchPanel 在库存或收料 RPA 排程工作台展示对应 worker 心跳状态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import request
|
||||
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.response import ok
|
||||
@@ -18,7 +20,10 @@ from app.services.shipping_notice.rpa_worker_heartbeat import serialize_rpa_work
|
||||
@require_admin
|
||||
def get_rpa_workers_status():
|
||||
"""
|
||||
返回库存 RPA Worker 心跳摘要(在线/离线、最后心跳时间、就绪原因)。
|
||||
核心逻辑:读取 Redis/内存心跳并与当前环境、trigger 目录比对。
|
||||
返回 RPA Worker 心跳摘要(在线/离线、最后心跳时间、就绪原因)。
|
||||
|
||||
Query:
|
||||
scope: inventory(默认)或 receipt。
|
||||
"""
|
||||
return ok(serialize_rpa_worker_status())
|
||||
scope = str(request.args.get('scope') or 'inventory').strip().lower() or 'inventory'
|
||||
return ok(serialize_rpa_worker_status(scope=scope))
|
||||
@@ -22,6 +22,7 @@ from app.models import ScheduleRun, ScheduleTask, ShippingReceiptReportFile, Shi
|
||||
from app.services.schedule.query_service import get_run, list_runs, serialize_run
|
||||
from app.services.schedule.queue_service import enqueue_manual_schedule_run
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download
|
||||
from app.services.schedule.shipping_receipt_rpa_archive import resolve_receipt_raw_zip_download
|
||||
from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file
|
||||
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
|
||||
@@ -123,6 +124,26 @@ def get_schedule_run_inventory_raw_zip(run_id: int):
|
||||
)
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/receipt-raw-zip', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_run_receipt_raw_zip(run_id: int):
|
||||
"""
|
||||
下载收料 RPA 排程 run 的原始收料 Excel 打包(ZIP + manifest)。
|
||||
|
||||
核心逻辑:对齐 inventory-raw-zip;展示名为 收料RPA-{日期}-{时刻}-收料.zip。
|
||||
"""
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
zip_path, file_name = resolve_receipt_raw_zip_download(run)
|
||||
return send_file(
|
||||
zip_path,
|
||||
as_attachment=True,
|
||||
download_name=file_name,
|
||||
mimetype='application/zip',
|
||||
)
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/receipt-report-files/<int:file_id>/resend', methods=['POST'])
|
||||
@require_admin
|
||||
def resend_receipt_report_file(file_id: int):
|
||||
|
||||
@@ -1,409 +1,13 @@
|
||||
"""
|
||||
api/shipping_notice_tools.py
|
||||
backend/app/api/shipping_notice_tools.py
|
||||
|
||||
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。
|
||||
依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url、
|
||||
tool_api_url。
|
||||
逻辑:Tool 成功响应仍用 status: ok/failed 业务 envelope;HTTP 级参数/资源错误统一 raise AppError;
|
||||
`_payload()` 剥离 body 中的操作人伪造字段,禁止集成密钥冒充用户写审计;
|
||||
历史批次 Tool 已删除,订单抽取统一走 order-extraction-submissions。
|
||||
用途:兼容旧 import 路径的薄 shim(真实现已迁至 api/tools/shipping_notice.py)。
|
||||
依赖:app.api.tools.shipping_notice。
|
||||
逻辑:保留 Blueprint 与 `_payload` 等测试符号;新代码请从 app.api.tools 导入。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
from app.api.tools.shipping_notice import ( # noqa: F401
|
||||
_payload,
|
||||
shipping_notice_bp,
|
||||
)
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
|
||||
from app.services.shipping_notice.query_service import (
|
||||
EXPORT_MIME_TYPE,
|
||||
get_task_by_ref,
|
||||
resolve_task_export_download,
|
||||
serialize_task_summary,
|
||||
task_export_error_message,
|
||||
)
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import record_rpa_worker_heartbeat
|
||||
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||
|
||||
shipping_notice_bp = Blueprint("shipping_notice", __name__)
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验货代 Tool API 鉴权 Header。
|
||||
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;当 Dify、RPA 或外部系统请求本蓝图时由 before_request 自动触发。
|
||||
|
||||
核心逻辑:只接受 `Authorization: Bearer <token>` 或 `X-Integration-Key`。
|
||||
货代专用 `SHIPPING_NOTICE_TOOL_API_KEY` 优先,未配置时回退 `INTEGRATION_API_KEY`;
|
||||
未配置任何可用 key 时报服务不可用,缺失或错误时报未授权。
|
||||
"""
|
||||
configured = str(
|
||||
current_app.config.get('SHIPPING_NOTICE_TOOL_API_KEY')
|
||||
or current_app.config.get('INTEGRATION_API_KEY')
|
||||
or ''
|
||||
).strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError(
|
||||
'SHIPPING_NOTICE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured',
|
||||
code='missing_auth',
|
||||
)
|
||||
bearer = str(request.headers.get('Authorization') or '').strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith('bearer ') else ''
|
||||
integration_key = str(request.headers.get('X-Integration-Key') or '').strip()
|
||||
if configured in {token, integration_key}:
|
||||
return
|
||||
if not token and (not integration_key):
|
||||
raise UnauthorizedError('missing_auth')
|
||||
raise UnauthorizedError('invalid_auth')
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
"""统一归一化 Tool API 的错误码,保持与文件检核 Tool 返回风格一致。"""
|
||||
message = str(exc.message or '').strip()
|
||||
if message in {'missing_auth', 'invalid_auth'}:
|
||||
return message
|
||||
if exc.code == 'AUTH.UNAUTHORIZED':
|
||||
return 'invalid_auth'
|
||||
if exc.code == 'SYSTEM.SERVICE_UNAVAILABLE' and 'not configured' in message.lower():
|
||||
return 'missing_auth'
|
||||
return exc.code
|
||||
|
||||
@shipping_notice_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
"""把业务异常统一转成 Tool 侧约定的 JSON 结构。"""
|
||||
body: dict[str, object] = {'ok': False, 'error_code': _tool_error_code(exc), 'message': exc.message}
|
||||
if exc.details:
|
||||
body['details'] = exc.details
|
||||
return jsonify(body), exc.http_status
|
||||
|
||||
@shipping_notice_bp.before_request
|
||||
def _verify_tool_access():
|
||||
"""
|
||||
对货代 Tool / RPA / 导出接口做统一 Header 鉴权。
|
||||
核心逻辑:仅放行 OpenAPI 导入文档,其他请求都必须携带有效 Tool Key。
|
||||
"""
|
||||
if request.path.endswith('/openapi.json') or request.path.endswith('/openapi.dify.yaml'):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
def _tool_api_base_url() -> str:
|
||||
"""Base URL for OpenAPI servers — hxops backend, NOT Dify (8882)."""
|
||||
return resolve_tool_api_base_url()
|
||||
|
||||
def _dify_openapi_spec() -> dict:
|
||||
return build_dify_openapi_spec(_tool_api_base_url())
|
||||
|
||||
def _payload() -> dict:
|
||||
"""
|
||||
读取 Tool API JSON 请求体,并剥离不可信的操作人身份字段。
|
||||
|
||||
核心逻辑:集成密钥调用方不得通过 body 伪造 `_trusted_user_id` /
|
||||
`operator_id` / `actor_id`;真实用户身份仅允许工作台/会话层鉴权后注入。
|
||||
"""
|
||||
raw = request.get_json(silent=True) or {}
|
||||
if not isinstance(raw, dict):
|
||||
return {}
|
||||
payload = dict(raw)
|
||||
for key in ('_trusted_user_id', 'operator_id', 'actor_id'):
|
||||
payload.pop(key, None)
|
||||
return payload
|
||||
|
||||
|
||||
def _require_read_capability(payload: dict, *, scope: str, task_no: str | None = None) -> None:
|
||||
"""Chatflow 只读查询必须携带短效会话能力令牌,不能仅依赖全局集成密钥。"""
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.chat_tool_capability import require_chat_capability
|
||||
claims = require_chat_capability(token=payload.get('shipping_chat_capability_token'), scope=scope, task_no=task_no)
|
||||
db.session.add(ShippingAuditEvent(
|
||||
event_type='chatflow_tool_read', aggregate_type='chat_session', aggregate_id=str(claims['sid']),
|
||||
task_no=task_no, actor_type='chatflow', actor_id=str(claims['uid']),
|
||||
request_id=str(request.headers.get('X-Request-ID') or '')[:64] or None,
|
||||
metadata_json={'tool': scope, 'token_nonce': str(claims['nonce'])[:16], 'success': True},
|
||||
))
|
||||
|
||||
@shipping_notice_bp.route('/tools/openapi.json', methods=['GET'])
|
||||
def openapi_spec():
|
||||
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
|
||||
return jsonify(_dify_openapi_spec())
|
||||
|
||||
@shipping_notice_bp.route('/tools/openapi.dify.yaml', methods=['GET'])
|
||||
def openapi_dify_yaml():
|
||||
"""返回 Dify 导入用的 OpenAPI YAML 文档。"""
|
||||
import yaml
|
||||
body = yaml.safe_dump(_dify_openapi_spec(), allow_unicode=True, sort_keys=False)
|
||||
return current_app.response_class(body, mimetype='text/yaml; charset=utf-8')
|
||||
|
||||
@shipping_notice_bp.route('/tools/create_task', methods=['POST'])
|
||||
def tool_create_task():
|
||||
"""
|
||||
创建单个发货任务。
|
||||
【AI 触发时机】:仅供 Hxops 内部建单链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.create_task(_payload()))
|
||||
|
||||
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/create_temporary_inventory_session', methods=['POST'])
|
||||
def tool_create_temporary_inventory_session():
|
||||
"""
|
||||
创建对话上传库存候选会话。
|
||||
【AI 触发时机】:用户明确说明 .xls、.xlsx 或 .csv 附件是库存文件时,在临时库存固定分支调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.create_temporary_inventory_session(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/get_temporary_inventory_session', methods=['POST'])
|
||||
def tool_get_temporary_inventory_session():
|
||||
"""
|
||||
读取临时库存候选的脱敏分析结果。
|
||||
【AI 触发时机】:创建临时会话后,需要决定采用已有方案还是请求映射建议时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.get_temporary_inventory_session(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/submit_temporary_inventory_mapping_suggestion', methods=['POST'])
|
||||
def tool_submit_temporary_inventory_mapping_suggestion():
|
||||
"""
|
||||
保存临时库存字段映射建议。
|
||||
【AI 触发时机】:仅在临时库存 LLM 节点返回真实表头到库存字段目录的候选后调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.submit_temporary_inventory_mapping_suggestion(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/confirm_temporary_inventory_use', methods=['POST'])
|
||||
def tool_confirm_temporary_inventory_use():
|
||||
"""
|
||||
确认本次对话临时库存文件的使用。
|
||||
【AI 触发时机】:仅在用户明确确认当前文件和方案后调用,禁止模型自行确认。
|
||||
"""
|
||||
return jsonify(shipping_tools.confirm_temporary_inventory_use(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/update_notice_fields', methods=['POST'])
|
||||
def tool_update_notice_fields():
|
||||
"""
|
||||
修改发货通知单头字段。
|
||||
【AI 触发时机】:当用户明确要求更正客户、PO、收货地或交期等单头信息时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.update_notice_fields(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/update_notice_line', methods=['POST'])
|
||||
def tool_update_notice_line():
|
||||
"""
|
||||
修改指定订单行。
|
||||
【AI 触发时机】:当用户指出某一行的 SKU、数量、Reservation ID 或交期有误时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.update_notice_line(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/add_notice_line', methods=['POST'])
|
||||
def tool_add_notice_line():
|
||||
"""
|
||||
新增订单行。
|
||||
【AI 触发时机】:当用户说明漏了一行订单、需要补录发货通知明细时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.add_notice_line(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/remove_notice_line', methods=['POST'])
|
||||
def tool_remove_notice_line():
|
||||
"""
|
||||
删除订单行。
|
||||
【AI 触发时机】:当用户确认某一行是误解析、重复行或不应出货的行时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.remove_notice_line(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/ensure_inventory', methods=['POST'])
|
||||
def tool_ensure_inventory():
|
||||
"""
|
||||
保证任务已取得库存数据。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
payload = _payload()
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
return jsonify(run_task_auto_progress(
|
||||
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
|
||||
trigger='legacy_tool_ensure_inventory',
|
||||
operator_id=payload.get('operator_id'),
|
||||
resume_gate_code='inventory_preparation',
|
||||
))
|
||||
|
||||
@shipping_notice_bp.route('/tools/auto_progress', methods=['POST'])
|
||||
def tool_auto_progress():
|
||||
"""
|
||||
自动推进任务。
|
||||
【AI 触发时机】:仅供后端 orchestrator / worker 调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.auto_progress(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/match_inventory', methods=['POST'])
|
||||
def tool_match_inventory():
|
||||
"""
|
||||
执行库存匹配。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
payload = _payload()
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
return jsonify(run_task_auto_progress(
|
||||
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
|
||||
trigger='legacy_tool_match_inventory',
|
||||
operator_id=payload.get('operator_id'),
|
||||
resume_gate_code='inventory_matching',
|
||||
))
|
||||
|
||||
@shipping_notice_bp.route('/tools/confirm_customer', methods=['POST'])
|
||||
def tool_confirm_customer():
|
||||
"""
|
||||
确认任务所属标准客户(仅提交 customer_id)。
|
||||
【AI 触发时机】:用户在客户人工确认检查点选择正式客户后调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.confirm_customer(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/generate_shipment_excel', methods=['POST'])
|
||||
def tool_generate_shipment_excel():
|
||||
"""
|
||||
生成出货 Excel。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
payload = _payload()
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
return jsonify(run_task_auto_progress(
|
||||
task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(),
|
||||
trigger='legacy_tool_generate_excel',
|
||||
operator_id=payload.get('operator_id'),
|
||||
resume_gate_code='artifact_generation',
|
||||
))
|
||||
|
||||
@shipping_notice_bp.route('/tools/upload_to_freight', methods=['POST'])
|
||||
def tool_upload_to_freight():
|
||||
"""
|
||||
上传到货代系统或确认人工上传完成。
|
||||
【AI 触发时机】:仅供后端主调度、内部恢复链路或人工上传收口调用;不是 Dify 画布正式入口。
|
||||
Agent 应优先引导用户走工作台 mark-manual-uploaded,勿在自动链中调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.upload_to_freight(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/get_task_status', methods=['POST'])
|
||||
def tool_get_task_status():
|
||||
"""
|
||||
查询任务状态。
|
||||
【AI 触发时机】:当 Agent 只拿到任务号/会话号,需要先确认当前卡点后再决定下一步时调用。
|
||||
"""
|
||||
payload = _payload()
|
||||
task_no = str(payload.get('task_id') or payload.get('task_no') or '').strip().upper()
|
||||
_require_read_capability(payload, scope='get_shipping_status', task_no=task_no or None)
|
||||
return jsonify(shipping_tools.get_task_status(payload))
|
||||
|
||||
@shipping_notice_bp.route('/rpa/heartbeat', methods=['POST'])
|
||||
def rpa_worker_heartbeat():
|
||||
"""
|
||||
RPA Worker 心跳上报。
|
||||
核心逻辑:校验 payload 后写入 Redis/内存;供触发库存 RPA 前就绪检查使用。
|
||||
"""
|
||||
payload = _payload()
|
||||
try:
|
||||
worker = record_rpa_worker_heartbeat(payload)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc))
|
||||
except ServiceUnavailableError:
|
||||
raise
|
||||
return jsonify({'status': 'ok', 'message': 'heartbeat recorded', 'data': worker})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-ready', methods=['POST'])
|
||||
def rpa_inventory_ready():
|
||||
"""RPA 回调入口:上报库存导出结果并回写任务状态。"""
|
||||
return jsonify(shipping_tools.rpa_report_inventory(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-batch-ready', methods=['POST'])
|
||||
def rpa_inventory_batch_ready():
|
||||
"""RPA 批量库存导出回调:按 Warehouse 写入库存快照。"""
|
||||
return jsonify(shipping_tools.rpa_report_inventory_batch(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/receipt-batch-ready', methods=['POST'])
|
||||
def rpa_receipt_batch_ready():
|
||||
"""收料 RPA 回调:独立归档文件,绝不进入库存回调或库存匹配链路。"""
|
||||
from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback
|
||||
|
||||
return jsonify({'success': True, 'data': ingest_receipt_callback(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-batch-claimed', methods=['POST'])
|
||||
def rpa_inventory_batch_claimed():
|
||||
"""v2 Worker 领取回调:仅记录 Attempt 执行阶段。"""
|
||||
from app.services.shipping_notice.per_source_rpa_service import claim_inventory_batch
|
||||
return jsonify({'success': True, 'data': claim_inventory_batch(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-batch-progress', methods=['POST'])
|
||||
def rpa_inventory_batch_progress():
|
||||
"""RPA 批量库存导出进度回调:实时回写排程 run 计数(非终态,最终以 batch-ready 为准)。"""
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import report_inventory_batch_progress
|
||||
return jsonify(report_inventory_batch_progress(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-configuration-test-ready', methods=['POST'])
|
||||
def rpa_inventory_configuration_test_ready():
|
||||
"""RPA 配置测试回调:仅分析文件结构,不创建生产库存快照或任务关联。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_test_export(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-configuration-test-batch-ready', methods=['POST'])
|
||||
def rpa_inventory_configuration_test_batch_ready():
|
||||
"""RPA 批量配置测试回调:按 validation_run_no 独立回写每个库存站点。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_batch_test_exports(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-configuration-test-batch-progress', methods=['POST'])
|
||||
def rpa_inventory_configuration_test_batch_progress():
|
||||
"""RPA 批量配置测试进度:Worker 领取单个站点后立即回写执行阶段。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_batch_test_progress(_payload())})
|
||||
|
||||
@shipping_notice_bp.route('/tasks/<task_no>/repair-inventory-attachment', methods=['POST'])
|
||||
def repair_task_inventory_attachment(task_no: str):
|
||||
"""
|
||||
从任务库存快照幂等重建正式附件(不重新消费 RPA callback)。
|
||||
核心逻辑:供晋升失败或 marker 异常后的人工/后台补偿。
|
||||
"""
|
||||
payload = _payload()
|
||||
payload.setdefault("task_no", task_no)
|
||||
payload.setdefault("task_id", task_no)
|
||||
return jsonify(shipping_tools.repair_task_inventory_attachment(payload))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-repair', methods=['POST'])
|
||||
def rpa_inventory_repair():
|
||||
"""受控库存回调修复:复用正式 v2 ingest 链路。"""
|
||||
payload = _payload()
|
||||
payload['repair'] = True
|
||||
return jsonify(shipping_tools.rpa_report_inventory_batch(payload))
|
||||
|
||||
@shipping_notice_bp.route('/rpa/upload-complete', methods=['POST'])
|
||||
def rpa_upload_complete():
|
||||
"""RPA 回调入口:上报货代上传结果并回写任务状态。"""
|
||||
return jsonify(shipping_tools.rpa_report_upload(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tasks/<task_no>/export', methods=['GET'])
|
||||
def download_task_export(task_no: str):
|
||||
"""下载任务已生成的出货 Excel。"""
|
||||
task = get_task_by_ref(task_no)
|
||||
err_msg = task_export_error_message(task)
|
||||
if err_msg:
|
||||
raise NotFoundError(err_msg)
|
||||
resolved = resolve_task_export_download(task)
|
||||
assert resolved is not None
|
||||
path, download_name = resolved
|
||||
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
|
||||
__all__ = ['shipping_notice_bp', '_payload']
|
||||
@@ -1,6 +1,11 @@
|
||||
"""
|
||||
Speech transcription API — forwards audio to SiliconFlow ASR.
|
||||
backend/app/api/speech/__init__.py
|
||||
|
||||
用途:语音转写 API,将音频转发至 SiliconFlow ASR。
|
||||
依赖:app.core.auth.jwt、SpeechAsrService。
|
||||
逻辑:register_blueprints 挂载 /api/speech;需登录后上传 audio/file。
|
||||
"""
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
backend/app/api/sso.py
|
||||
backend/app/api/sso/__init__.py
|
||||
|
||||
Purpose: Expose peer-service discovery, short-lived assertion issuance, and public JWKS APIs.
|
||||
Dependencies: JWT current-user resolver, SSO services, and Flask Blueprint.
|
||||
@@ -1,11 +1,20 @@
|
||||
"""
|
||||
backend/app/api/tools/__init__.py
|
||||
|
||||
用途:Dify HTTP Tool API Blueprint 聚合。
|
||||
逻辑:re-export shipping_notice、file_check、maintenance tools。
|
||||
用途:Dify / Chatflow HTTP Tool API Blueprint 聚合。
|
||||
依赖:tools 子模块(file_check、shipping_notice、maintenance、agent_runtime_context、procurement_contract)。
|
||||
逻辑:register_blueprints 只从本包导入 Tool Blueprint;真实现已收口到本目录,根路径 *_tools.py 仅为兼容 shim。
|
||||
"""
|
||||
from app.api.tools.shipping_notice import shipping_notice_bp # noqa: F401
|
||||
from app.api.tools.agent_runtime_context import agent_runtime_context_bp # noqa: F401
|
||||
from app.api.tools.file_check import file_check_bp # noqa: F401
|
||||
from app.api.tools.maintenance import maintenance_tool_bp # noqa: F401
|
||||
from app.api.tools.procurement_contract import procurement_contract_bp # noqa: F401
|
||||
from app.api.tools.shipping_notice import shipping_notice_bp # noqa: F401
|
||||
|
||||
__all__ = ['shipping_notice_bp', 'file_check_bp', 'maintenance_tool_bp']
|
||||
__all__ = [
|
||||
'agent_runtime_context_bp',
|
||||
'file_check_bp',
|
||||
'maintenance_tool_bp',
|
||||
'procurement_contract_bp',
|
||||
'shipping_notice_bp',
|
||||
]
|
||||
@@ -0,0 +1,108 @@
|
||||
"""
|
||||
backend/app/api/tools/agent_runtime_context.py
|
||||
|
||||
用途:暴露 agent_runtime_context 只读 Tool API,供 Dify Chatflow 解析 HXOPS 上下文。
|
||||
依赖:app.core.errors、agent_runtime_context.parser/openapi_spec、shipping_notice.tool_api_url。
|
||||
逻辑:register_blueprints 从 api.tools 挂载;OpenAPI 文档接口放行;parse 工具复用
|
||||
Authorization Bearer / X-Integration-Key 鉴权,不推进业务状态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request
|
||||
|
||||
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError
|
||||
from app.services.agent_runtime_context.openapi_spec import build_agent_runtime_context_openapi_spec
|
||||
from app.services.agent_runtime_context.parser import parse_agent_runtime_context
|
||||
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||
|
||||
agent_runtime_context_bp = Blueprint("agent_runtime_context_tools", __name__)
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验 agent_runtime_context Tool API 鉴权 Header。
|
||||
|
||||
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;Dify 请求 parse 工具时由 before_request 自动触发。
|
||||
|
||||
核心逻辑:只接受 Authorization Bearer 或 X-Integration-Key,复用 INTEGRATION_API_KEY 作为平台工具密钥。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 未配置 INTEGRATION_API_KEY。
|
||||
UnauthorizedError: 缺少或传入错误鉴权。
|
||||
"""
|
||||
configured = str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError("INTEGRATION_API_KEY is not configured", code="missing_auth")
|
||||
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||
if configured in {token, integration_key}:
|
||||
return
|
||||
if not token and not integration_key:
|
||||
raise UnauthorizedError("missing_auth")
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
"""
|
||||
归一化 Tool API 错误码。
|
||||
|
||||
核心逻辑:保持与 shipping/file-check Tool API 的 ok:false 响应风格一致,便于 Dify 侧统一处理。
|
||||
|
||||
Args:
|
||||
exc: 业务异常。
|
||||
|
||||
Returns:
|
||||
Tool 侧错误码。
|
||||
"""
|
||||
message = str(exc.message or "").strip()
|
||||
if message in {"missing_auth", "invalid_auth"}:
|
||||
return message
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
return "missing_auth"
|
||||
return exc.code
|
||||
|
||||
|
||||
@agent_runtime_context_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
"""把业务异常统一转成 Tool 侧约定的 JSON 结构。"""
|
||||
return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status
|
||||
|
||||
|
||||
@agent_runtime_context_bp.before_request
|
||||
def _verify_tool_access():
|
||||
"""
|
||||
对上下文解析 Tool 做统一 Header 鉴权。
|
||||
|
||||
核心逻辑:OpenAPI 导入文档无需鉴权;parse 工具必须携带平台 Tool Key。
|
||||
"""
|
||||
if request.path.endswith("/openapi.json"):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
@agent_runtime_context_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def openapi_spec():
|
||||
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
|
||||
return jsonify(build_agent_runtime_context_openapi_spec(resolve_tool_api_base_url()))
|
||||
|
||||
|
||||
@agent_runtime_context_bp.route("/tools/parse", methods=["POST"])
|
||||
def parse_context_tool():
|
||||
"""
|
||||
解析 agent_runtime_context 的白名单字段。
|
||||
|
||||
【AI 触发时机】:Dify 需要读取 HXOPS session/task/batch/run_purpose/state_hint 等上下文字段时调用;
|
||||
不用于推进业务状态。
|
||||
"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
return jsonify(
|
||||
parse_agent_runtime_context(
|
||||
payload.get("agent_runtime_context"),
|
||||
payload.get("paths"),
|
||||
)
|
||||
)
|
||||
@@ -1,8 +1,657 @@
|
||||
"""
|
||||
backend/app/api/tools/file_check.py
|
||||
|
||||
用途:文件检核 Tool API Blueprint(Wave 1 自 file_check_tools.py 迁入)。
|
||||
用途:文件检核 / 立账凭证检核 Chatflow 显式 HTTP Tool API(启动检核复用本蓝图)。
|
||||
依赖:workspace.file_check、services.file_check_tools、schedule.scheduler_service、jobs.enqueue。
|
||||
逻辑:register_blueprints 从 api.tools 挂载;发起检核时可透传顶层 mode/invoice_no(或嵌套 run_options)写入 ScheduleRun.api_request_json;实际执行入队 FILE_CHECK_RUN,由 schedule worker 执行。
|
||||
"""
|
||||
from app.api.file_check_tools import file_check_bp # noqa: F401
|
||||
from __future__ import annotations
|
||||
|
||||
__all__ = ['file_check_bp']
|
||||
import threading
|
||||
import time
|
||||
from io import BytesIO
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
from sqlalchemy import text
|
||||
|
||||
from app import db
|
||||
from app.api.workspace.file_check import serialize_file_judgement
|
||||
from app.jobs import JobType, enqueue
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
)
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.file_check_tools.openapi_spec import build_file_check_openapi_spec
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE, resolve_hxops_user_facing_base_url
|
||||
from app.services.schedule import _build_srm_conn_str
|
||||
from app.services.schedule.query_service import get_run, serialize_run
|
||||
from app.services.schedule.srm_service import _fetch_records
|
||||
from app.services.schedule.scheduler_service import _generate_run_no
|
||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
|
||||
|
||||
try:
|
||||
import pyodbc # type: ignore
|
||||
except Exception: # pragma: no cover
|
||||
pyodbc = None
|
||||
|
||||
|
||||
file_check_bp = Blueprint("file_check_tools", __name__)
|
||||
|
||||
_EXCEL_TOKEN_SCOPES = {"file_check_excel", "file_schedule_excel"}
|
||||
_RUN_START_LOCK = threading.Lock()
|
||||
_TASK_LOCK_KEY_BASE = 8700000000
|
||||
|
||||
|
||||
def _download_token_secret() -> str:
|
||||
"""
|
||||
Excel 下载 JWT 签名密钥。
|
||||
|
||||
核心逻辑:与 Dify Tool API Key 分离,仅用 SECRET_KEY,避免 API Key 未配置时浏览器下载失败。
|
||||
"""
|
||||
return str(current_app.config.get("SECRET_KEY") or "default-secret").strip()
|
||||
|
||||
|
||||
def _decode_download_token(token: str | None) -> dict | None:
|
||||
normalized = str(token or "").strip()
|
||||
if not normalized:
|
||||
return None
|
||||
try:
|
||||
import jwt
|
||||
|
||||
payload = jwt.decode(normalized, _download_token_secret(), algorithms=["HS256"])
|
||||
return payload if isinstance(payload, dict) else None
|
||||
except Exception as exc:
|
||||
current_app.logger.warning("[file-check-tool] download token validation failed: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验 Tool API 访问权限。
|
||||
|
||||
核心逻辑:Excel 下载仅校验 query token(浏览器场景);其余端点走共用 integration_tool_auth。
|
||||
"""
|
||||
# [STEP 1] 浏览器 Excel 下载:JWT token 独立于 Tool API Key
|
||||
if request.path.endswith("/excel"):
|
||||
query_token = str(request.args.get("token") or "").strip()
|
||||
if query_token:
|
||||
if _decode_download_token(query_token):
|
||||
return
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
# [STEP 2] Dify / RPA 服务端调用(与立账凭证检核等 Tool 共用密钥)
|
||||
from app.services.integration_tool_auth import require_integration_tool_auth
|
||||
|
||||
require_integration_tool_auth()
|
||||
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
message = str(exc.message or "").strip()
|
||||
if message in {
|
||||
"missing_auth",
|
||||
"invalid_auth",
|
||||
"task_not_found",
|
||||
"run_not_found",
|
||||
"excel_not_ready",
|
||||
"kb_sync_failed",
|
||||
"query_required",
|
||||
"kb_not_configured",
|
||||
"kb_group_not_found",
|
||||
"kb_dataset_not_bound",
|
||||
"dify_retrieve_failed",
|
||||
}:
|
||||
return message
|
||||
if exc.code == "data_source_unavailable":
|
||||
return "data_source_unavailable"
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
return "missing_auth"
|
||||
if exc.code == "RESOURCE.NOT_FOUND":
|
||||
return message or "run_not_found"
|
||||
if exc.code == "VALIDATION.INVALID_PARAM":
|
||||
return message or "invalid_request"
|
||||
if exc.code == "RESOURCE.CONFLICT":
|
||||
return message or "conflict"
|
||||
return exc.code
|
||||
|
||||
|
||||
@file_check_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
status = exc.http_status
|
||||
return jsonify({
|
||||
"ok": False,
|
||||
"error_code": _tool_error_code(exc),
|
||||
"message": exc.message,
|
||||
}), status
|
||||
|
||||
|
||||
def _public_base_url() -> str:
|
||||
"""用户可见下载链基地址;与 Dify 调 Tool API 的内网基地址分离。"""
|
||||
return resolve_hxops_user_facing_base_url()
|
||||
|
||||
|
||||
def _acquire_task_start_lock(task_id: int) -> None:
|
||||
"""按 schedule_task_id 串行化同任务启动检核(PostgreSQL advisory lock)。"""
|
||||
bind = db.session.get_bind()
|
||||
if bind.dialect.name != "postgresql":
|
||||
return
|
||||
lock_key = _TASK_LOCK_KEY_BASE + int(task_id)
|
||||
db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": lock_key})
|
||||
|
||||
|
||||
def _build_excel_download_url(run: ScheduleRun) -> str:
|
||||
import jwt
|
||||
|
||||
payload = {
|
||||
"scope": "file_check_excel",
|
||||
"run_id": run.id,
|
||||
"exp": int(time.time()) + 600,
|
||||
}
|
||||
token = jwt.encode(payload, _download_token_secret(), algorithm="HS256")
|
||||
return f"{_public_base_url()}/api/file-check/tools/runs/{run.id}/excel?token={token}"
|
||||
|
||||
|
||||
@file_check_bp.before_request
|
||||
def _verify_tool_access():
|
||||
if request.path.endswith("/openapi.json"):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
def _serialize_tool_run(run: ScheduleRun) -> dict:
|
||||
payload = serialize_run(run)
|
||||
return {
|
||||
"run_id": payload["id"],
|
||||
"run_no": payload["run_no"],
|
||||
"task_id": payload["schedule_task_id"],
|
||||
"task_name": payload.get("schedule_name"),
|
||||
"status": payload["status"],
|
||||
"total_count": payload["total_count"],
|
||||
"success_count": payload["success_count"],
|
||||
"failed_count": payload["failed_count"],
|
||||
"skipped_count": payload["skipped_count"],
|
||||
"judgement": serialize_file_judgement(payload),
|
||||
"started_at": payload.get("started_at"),
|
||||
"finished_at": payload.get("finished_at"),
|
||||
"duration_ms": payload.get("duration_ms"),
|
||||
"error_message": payload.get("error_message"),
|
||||
"excel": {
|
||||
"file_name": payload.get("excel_file_name"),
|
||||
"file_size": payload.get("excel_file_size"),
|
||||
"download_url": _build_excel_download_url(run) if payload.get("excel_file_name") else None,
|
||||
},
|
||||
"knowledge_base": {
|
||||
"enabled": bool(getattr(run.task, "kb_sync_enabled", False)) if run.task else bool(payload.get("kb_group_id")),
|
||||
"sync_status": payload.get("kb_sync_status"),
|
||||
"group_id": payload.get("kb_group_id"),
|
||||
"document_id": payload.get("kb_document_id"),
|
||||
"document_version_id": payload.get("kb_document_version_id"),
|
||||
"sync_job_id": payload.get("kb_sync_job_id"),
|
||||
"error_message": payload.get("kb_sync_error"),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _resolve_check_task(data: dict | None = None, *, task_id: int | None = None) -> ScheduleTask:
|
||||
data = data or {}
|
||||
raw_task_id = task_id if task_id is not None else data.get("task_id")
|
||||
if raw_task_id in (None, "", 0, "0") and not str(data.get("task_no") or "").strip():
|
||||
raise ValidationError("task_id_required")
|
||||
try:
|
||||
normalized_task_id = int(raw_task_id) if raw_task_id not in (None, "", 0, "0") else None
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError("task_id_invalid")
|
||||
task = db.session.get(ScheduleTask, normalized_task_id) if normalized_task_id is not None else None
|
||||
if not task:
|
||||
task_no = str(data.get("task_no") or "").strip()
|
||||
if task_no:
|
||||
task = ScheduleTask.query.filter_by(schedule_no=task_no).first()
|
||||
if not task:
|
||||
raise NotFoundError("task_not_found")
|
||||
return task
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/tasks", methods=["GET"])
|
||||
def list_file_check_tasks():
|
||||
"""
|
||||
查询指定检核任务摘要;须传 task_id(Agent 绑定的 schedule_task_id),不再返回全量任务列表。
|
||||
"""
|
||||
raw_task_id = request.args.get("task_id", type=int)
|
||||
if raw_task_id is None:
|
||||
raise ValidationError("task_id_required")
|
||||
task = _resolve_check_task(task_id=raw_task_id)
|
||||
latest = (
|
||||
ScheduleRun.query.filter_by(schedule_task_id=task.id)
|
||||
.order_by(ScheduleRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
tasks = [{
|
||||
"task_id": task.id,
|
||||
"task_no": task.schedule_no,
|
||||
"name": task.name,
|
||||
"enabled": bool(task.enabled),
|
||||
"last_status": latest.status if latest else None,
|
||||
"last_run_at": task.last_run_at.isoformat() if task.last_run_at else None,
|
||||
"next_run_at": task.next_run_at.isoformat() if task.next_run_at else None,
|
||||
}]
|
||||
return jsonify({"ok": True, "tasks": tasks})
|
||||
|
||||
|
||||
def _normalize_bind_payload(data: dict | None) -> dict:
|
||||
"""规范化启动检核 Body;兼容 Chatflow 漏传 hxops_session_id。"""
|
||||
payload = dict(data or {})
|
||||
session_id = str(payload.get("hxops_session_id") or "").strip()
|
||||
if session_id:
|
||||
return payload
|
||||
conversation_id = str(payload.get("conversation_id") or "").strip()
|
||||
if not conversation_id:
|
||||
return payload
|
||||
from app.models import ChatSession
|
||||
|
||||
session = ChatSession.query.filter_by(session_id=conversation_id).first()
|
||||
if session:
|
||||
payload["hxops_session_id"] = conversation_id
|
||||
return payload
|
||||
|
||||
|
||||
def _prepare_bind_payload(data: dict | None) -> dict:
|
||||
from app.services.file_check_tools.chat_turn_registry import infer_bind_context_for_run_request
|
||||
|
||||
payload = _normalize_bind_payload(data)
|
||||
inferred = infer_bind_context_for_run_request(payload)
|
||||
if inferred:
|
||||
payload = {**payload, **inferred}
|
||||
return payload
|
||||
|
||||
|
||||
def _record_run_bind(run: ScheduleRun, data: dict) -> None:
|
||||
from app.services.file_check_tools.chat_log_run_binding import merge_chat_log_bind_context
|
||||
from app.services.file_check_tools.chat_tool_run_binding import (
|
||||
_has_ambiguous_pending_turns,
|
||||
bind_schedule_run,
|
||||
)
|
||||
from app.services.file_check_tools.chat_turn_registry import attach_run_to_turn
|
||||
|
||||
turn_id = str(data.get("hxops_turn_id") or "").strip()
|
||||
session_id = str(data.get("hxops_session_id") or "").strip() or None
|
||||
user_message = str(data.get("user_message") or "").strip() or None
|
||||
bound = bind_schedule_run(
|
||||
schedule_run_id=int(run.id),
|
||||
turn_id=turn_id or None,
|
||||
session_id=session_id,
|
||||
user_message=user_message,
|
||||
schedule_task_id=int(run.schedule_task_id) if run.schedule_task_id else None,
|
||||
bind_source='tool_start',
|
||||
)
|
||||
ambiguous = _has_ambiguous_pending_turns(
|
||||
session_id=session_id,
|
||||
user_message=user_message,
|
||||
schedule_task_id=int(run.schedule_task_id) if run.schedule_task_id else None,
|
||||
)
|
||||
if bound or (not ambiguous and (turn_id or session_id)):
|
||||
merge_chat_log_bind_context(run, data)
|
||||
if bound and turn_id:
|
||||
attach_run_to_turn(turn_id, int(run.id))
|
||||
|
||||
|
||||
def _bind_queried_run_to_turn(run: ScheduleRun, data: dict) -> None:
|
||||
"""
|
||||
将已有检核批次关联到本轮查询对话,不改写批次原始执行上下文。
|
||||
|
||||
查询最近批次时触发;仅更新 chat_tool_runs 与内存 turn registry,
|
||||
使 message_end 可以把既有 ScheduleRun.id 写入当前 ChatLog.run_id。
|
||||
"""
|
||||
from app.services.file_check_tools.chat_tool_run_binding import bind_schedule_run
|
||||
from app.services.file_check_tools.chat_turn_registry import attach_run_to_turn
|
||||
|
||||
turn_id = str(data.get("hxops_turn_id") or "").strip()
|
||||
session_id = str(data.get("conversation_id") or "").strip() or None
|
||||
user_message = str(data.get("user_message") or "").strip() or None
|
||||
if not turn_id:
|
||||
return
|
||||
|
||||
bound = bind_schedule_run(
|
||||
schedule_run_id=int(run.id),
|
||||
turn_id=turn_id,
|
||||
session_id=session_id,
|
||||
user_message=user_message,
|
||||
schedule_task_id=int(run.schedule_task_id),
|
||||
bind_source="tool_query_latest",
|
||||
)
|
||||
if bound:
|
||||
attach_run_to_turn(turn_id, int(run.id))
|
||||
|
||||
|
||||
def _build_no_data_response(task: ScheduleTask, run: ScheduleRun) -> dict:
|
||||
"""
|
||||
组装无待检资料的 Tool 响应,并返回本轮已完成的空批次。
|
||||
|
||||
【AI 触发时机】:用户要求立即执行文件检核,但预检未发现待检资料时调用。
|
||||
核心逻辑:保留 no_data_to_check 供 Chatflow 回复无资料提示,同时携带已绑定的 Run,
|
||||
使前端能在该轮消息下展示总数 0、进度 100% 的完成进度卡。
|
||||
|
||||
Args:
|
||||
task: 当前检核任务。
|
||||
run: 已持久化并绑定当前对话的成功空批次。
|
||||
|
||||
Returns:
|
||||
dict: 包含 no_data_to_check、任务信息和 Run 摘要的 HTTP 200 响应体。
|
||||
"""
|
||||
return {
|
||||
"ok": False,
|
||||
"error_code": "no_data_to_check",
|
||||
"message": "目前没有资料需要检核",
|
||||
"run": _serialize_tool_run(run),
|
||||
"task": {
|
||||
"task_id": task.id,
|
||||
"task_name": task.name,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _raise_data_source_unavailable(task: ScheduleTask, exc: Exception) -> None:
|
||||
"""
|
||||
将检核预检阶段的数据源连接/配置错误转为 Tool API 503。
|
||||
|
||||
核心逻辑:ODBC/SQL Server 不可用时返回 data_source_unavailable,避免 Dify 收到 500 后显示 maximum retries。
|
||||
"""
|
||||
current_app.logger.warning(
|
||||
"[file-check-tool] precheck data source unavailable task_id=%s error=%s",
|
||||
task.id,
|
||||
exc,
|
||||
exc_info=True,
|
||||
)
|
||||
raise ServiceUnavailableError(
|
||||
"检核数据源不可用,请检查排程 SQL 配置、SRM_SQLSERVER_* 环境变量及本机 ODBC 驱动",
|
||||
code="data_source_unavailable",
|
||||
) from exc
|
||||
|
||||
|
||||
def _precheck_no_data(task: ScheduleTask) -> dict | None:
|
||||
"""
|
||||
启动前预检当前任务是否存在待检资料。
|
||||
|
||||
核心逻辑:仅在数据库型检核任务上做轻量预检;若结果为空,则返回 no_data_to_check 标识,
|
||||
由启动入口创建并绑定完成态的 0 笔 Run。数据源连接失败时抛 503 data_source_unavailable。
|
||||
"""
|
||||
if str(getattr(task, "data_source_type", "") or "database").lower() != "database":
|
||||
return None
|
||||
|
||||
cfg = get_schedule_sql_config_by_task_id(task.id)
|
||||
if not cfg or not str(cfg.fetch_sql or "").strip():
|
||||
return None
|
||||
|
||||
try:
|
||||
if cfg.data_source and not cfg.data_source.is_empty():
|
||||
conn_str = cfg.data_source.build_connection_string()
|
||||
else:
|
||||
conn_str = _build_srm_conn_str()
|
||||
rows = _fetch_records(conn_str, cfg.fetch_sql)
|
||||
except RuntimeError as exc:
|
||||
_raise_data_source_unavailable(task, exc)
|
||||
except Exception as exc:
|
||||
if pyodbc is not None and isinstance(exc, pyodbc.Error):
|
||||
_raise_data_source_unavailable(task, exc)
|
||||
raise
|
||||
|
||||
if rows:
|
||||
return None
|
||||
return {
|
||||
"ok": False,
|
||||
"error_code": "no_data_to_check",
|
||||
"message": "目前没有资料需要检核",
|
||||
}
|
||||
|
||||
|
||||
def _create_no_data_run(task: ScheduleTask, data: dict) -> ScheduleRun:
|
||||
"""
|
||||
为预检为空的立即执行请求创建并绑定已完成的 0 笔检核批次。
|
||||
|
||||
【AI 触发时机】:run_file_check 收到 no_data_to_check 预检结果时调用。
|
||||
核心逻辑:不启动后台 worker,仅写入 success Run 与对话绑定;完成态空批次由工作区进度接口
|
||||
序列化为 100%,让用户明确知道本次检核已经结束且没有待处理资料。
|
||||
|
||||
Args:
|
||||
task: 已解析的文件检核任务。
|
||||
data: Tool 请求及对话绑定上下文。
|
||||
|
||||
Returns:
|
||||
ScheduleRun: 已提交且已绑定当前对话的成功空批次。
|
||||
"""
|
||||
finished_at = datetime.utcnow()
|
||||
run = ScheduleRun(
|
||||
run_no=_generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
trigger_type="dify_chatflow",
|
||||
started_at=finished_at,
|
||||
finished_at=finished_at,
|
||||
duration_ms=0,
|
||||
status="success",
|
||||
total_count=0,
|
||||
success_count=0,
|
||||
failed_count=0,
|
||||
skipped_count=0,
|
||||
api_request_json={
|
||||
"trigger_source": data.get("trigger_source") or "dify_chatflow",
|
||||
"conversation_id": data.get("conversation_id"),
|
||||
},
|
||||
response_summary_json={"errors": [], "no_data": True},
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
_record_run_bind(run, data)
|
||||
db.session.commit()
|
||||
return run
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/tasks/run", methods=["POST"])
|
||||
def run_file_check():
|
||||
"""
|
||||
立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。
|
||||
|
||||
核心逻辑:解析 task → 防并发锁 → 可选透传 mode/invoice_no(或 run_options)到
|
||||
ScheduleRun.api_request_json → 异步启动平台 Job。Dify 推荐填顶层 mode/invoice_no。
|
||||
|
||||
Body 关键字段(立账凭证检核):
|
||||
mode: incremental | force_all | single
|
||||
invoice_no: mode=single 时发票号
|
||||
run_options: 可选嵌套对象,与顶层字段合并(顶层优先)
|
||||
"""
|
||||
perf_started = time.perf_counter()
|
||||
data = _prepare_bind_payload(request.get_json(silent=True) or {})
|
||||
task = _resolve_check_task(data)
|
||||
resolve_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
|
||||
lock_started = time.perf_counter()
|
||||
with _RUN_START_LOCK:
|
||||
_acquire_task_start_lock(task.id)
|
||||
existing = (
|
||||
ScheduleRun.query.filter_by(schedule_task_id=task.id, status="running")
|
||||
.order_by(ScheduleRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
if existing:
|
||||
_record_run_bind(existing, data)
|
||||
db.session.commit()
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
current_app.logger.info(
|
||||
"[file-check-tool-perf] run_file_check outcome=check_running resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
existing.id,
|
||||
)
|
||||
return jsonify({
|
||||
"ok": False,
|
||||
"error_code": "check_running",
|
||||
"message": "该检核任务正在执行中,请稍后查询结果",
|
||||
"run": _serialize_tool_run(existing),
|
||||
})
|
||||
|
||||
no_data_response = _precheck_no_data(task)
|
||||
if no_data_response:
|
||||
run = _create_no_data_run(task, data)
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
current_app.logger.info(
|
||||
"[file-check-tool-perf] run_file_check outcome=no_data resolve_ms=%s lock_ms=%s total_ms=%s task_id=%s run_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
task.id,
|
||||
run.id,
|
||||
)
|
||||
return jsonify(_build_no_data_response(task, run))
|
||||
|
||||
# [STEP] 解析运行选项:优先顶层 mode/invoice_no(Dify Tool 表单对嵌套 object 常不展示),
|
||||
# 再与 run_options 对象合并;立账凭证检核读取,普通文件检核忽略。
|
||||
raw_options = data.get("run_options") if isinstance(data.get("run_options"), dict) else {}
|
||||
run_options = {}
|
||||
mode = str(data.get("mode") or raw_options.get("mode") or "").strip().lower()
|
||||
if mode in {"incremental", "force_all", "single"}:
|
||||
run_options["mode"] = mode
|
||||
invoice_no = data.get("invoice_no")
|
||||
if invoice_no is None or not str(invoice_no).strip():
|
||||
invoice_no = raw_options.get("invoice_no")
|
||||
if invoice_no is not None and str(invoice_no).strip():
|
||||
run_options["invoice_no"] = str(invoice_no).strip()
|
||||
|
||||
api_request_json = {
|
||||
"trigger_source": data.get("trigger_source") or "dify_chatflow",
|
||||
"conversation_id": data.get("conversation_id"),
|
||||
}
|
||||
if run_options:
|
||||
api_request_json["run_options"] = run_options
|
||||
|
||||
run = ScheduleRun(
|
||||
run_no=_generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
trigger_type="dify_chatflow",
|
||||
started_at=datetime.utcnow(),
|
||||
status="running",
|
||||
api_request_json=api_request_json,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
_record_run_bind(run, data)
|
||||
db.session.commit()
|
||||
run_id = run.id
|
||||
task_id = task.id
|
||||
|
||||
enqueue(
|
||||
JobType.FILE_CHECK_RUN,
|
||||
{"task_id": task_id, "schedule_run_id": run_id},
|
||||
domain="file_check",
|
||||
business_ref=str(run_id),
|
||||
message="等待执行文件检核",
|
||||
)
|
||||
db.session.refresh(run)
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
current_app.logger.info(
|
||||
"[file-check-tool-perf] run_file_check outcome=started resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
run_id,
|
||||
)
|
||||
return jsonify({"ok": True, "message": "检核已启动", "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/runs/<int:run_id>", methods=["GET"])
|
||||
def get_file_check_run(run_id: int):
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/runs", methods=["GET"])
|
||||
def list_file_check_runs():
|
||||
raw_task_id = request.args.get("task_id", type=int)
|
||||
raw_limit = request.args.get("limit", default=20, type=int)
|
||||
limit = max(1, min(int(raw_limit or 20), 100))
|
||||
if raw_task_id is not None:
|
||||
task = _resolve_check_task(task_id=raw_task_id)
|
||||
query = ScheduleRun.query.filter_by(schedule_task_id=task.id)
|
||||
else:
|
||||
query = ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
|
||||
rows = query.order_by(ScheduleRun.created_at.desc()).limit(limit).all()
|
||||
runs = [_serialize_tool_run(row) for row in rows]
|
||||
return jsonify({"ok": True, "runs": runs, "count": len(runs)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/runs/<int:run_id>/excel", methods=["GET"])
|
||||
def download_file_check_run_excel(run_id: int):
|
||||
token_payload = _decode_download_token(request.args.get("token"))
|
||||
if token_payload:
|
||||
if token_payload.get("scope") not in _EXCEL_TOKEN_SCOPES or int(token_payload.get("run_id") or 0) != run_id:
|
||||
raise UnauthorizedError("Unauthorized")
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
if not run.excel_file_data:
|
||||
raise ConflictError("excel_not_ready")
|
||||
filename = run.excel_file_name or f"{run.run_no}.xlsx"
|
||||
return send_file(
|
||||
BytesIO(run.excel_file_data),
|
||||
as_attachment=True,
|
||||
download_name=filename,
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/tasks/<int:task_id>/latest-run", methods=["GET"])
|
||||
def get_latest_file_check_run(task_id: int):
|
||||
"""查询任务最近批次;可绑定本轮对话以展示该批次进度。"""
|
||||
task = _resolve_check_task(task_id=task_id)
|
||||
run = ScheduleRun.query.filter_by(schedule_task_id=task.id).order_by(ScheduleRun.id.desc()).first()
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
_bind_queried_run_to_turn(run, {
|
||||
"hxops_turn_id": request.args.get("hxops_turn_id"),
|
||||
"conversation_id": request.args.get("conversation_id"),
|
||||
"user_message": request.args.get("user_message"),
|
||||
})
|
||||
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/history/search", methods=["POST"])
|
||||
def search_file_check_history():
|
||||
"""
|
||||
检索已入库的历史检核报告片段;按 task_id 解析 ScheduleTask → KbGroup → Dify Dataset。
|
||||
|
||||
核心逻辑:Chatflow history_report_query 分支调用;task_id 来自 HXOPS 注入的 Start 变量。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
raw_task_id = data.get("task_id")
|
||||
try:
|
||||
task_id = int(raw_task_id)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError("task_id_invalid")
|
||||
if task_id <= 0:
|
||||
raise ValidationError("task_id_invalid")
|
||||
|
||||
from app.services.file_check_tools.history_search_service import search_file_check_history as run_history_search
|
||||
|
||||
result = run_history_search(
|
||||
task_id=task_id,
|
||||
query=str(data.get("query") or ""),
|
||||
top_k=data.get("top_k"),
|
||||
score_threshold=data.get("score_threshold"),
|
||||
)
|
||||
return jsonify({"ok": True, **result})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def file_check_openapi_spec():
|
||||
return jsonify(build_file_check_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
|
||||
@@ -1,9 +1,150 @@
|
||||
"""
|
||||
backend/app/api/tools/maintenance.py
|
||||
|
||||
用途:设备维保 Tool API Blueprint re-export。
|
||||
依赖:app.api.maintenance_tools。
|
||||
逻辑:保持 api.tools 分包统一入口,register_blueprints 只从 app.api.tools 导入各 Tool Blueprint。
|
||||
用途:设备维保助手 Dify Tool API,只开放只读查询工具。
|
||||
依赖:maintenance_chat_service、maintenance_record_service、OpenAPI 构建、Tool API 基地址解析。
|
||||
逻辑:register_blueprints 从 api.tools 挂载;Dify 复杂问法调用本蓝图查询设备台账/维修记录;
|
||||
明确查询仍由 chat 本地直答,写操作仍走 HXOPS 管理面板。
|
||||
"""
|
||||
|
||||
from app.api.maintenance_tools import maintenance_tool_bp # noqa: F401
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError, ValidationError
|
||||
from app.models import MaintenanceRecord
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
|
||||
from app.services.maintenance_chat_service import build_device_query_result
|
||||
from app.services.maintenance_record_service import serialize_record
|
||||
from app.services.maintenance_tools.openapi_spec import build_maintenance_openapi_spec
|
||||
|
||||
maintenance_tool_bp = Blueprint("maintenance_tools", __name__)
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验设备维保 Tool API 鉴权。
|
||||
AI 触发时机:Dify Tool 调用本蓝图时由 before_request 自动执行,不是给 LLM 直接调用的业务工具。
|
||||
"""
|
||||
configured = str(
|
||||
current_app.config.get("MAINTENANCE_TOOL_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
or ""
|
||||
).strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError(
|
||||
"MAINTENANCE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured",
|
||||
code="missing_auth",
|
||||
)
|
||||
|
||||
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||
if configured in {token, integration_key}:
|
||||
return
|
||||
if not token and not integration_key:
|
||||
raise UnauthorizedError("missing_auth")
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
"""把 AppError 归一成 Dify Tool 侧可读错误码。"""
|
||||
message = str(exc.message or "").strip()
|
||||
if message in {"missing_auth", "invalid_auth"}:
|
||||
return message
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
return "missing_auth"
|
||||
if exc.code == "VALIDATION.INVALID_PARAM":
|
||||
return message or "invalid_request"
|
||||
return exc.code
|
||||
|
||||
|
||||
@maintenance_tool_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
"""Tool API 统一错误响应。"""
|
||||
return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status
|
||||
|
||||
|
||||
@maintenance_tool_bp.before_request
|
||||
def _verify_tool_access():
|
||||
"""除 OpenAPI 文档外,所有 Tool 调用必须携带有效服务级 token。"""
|
||||
if request.path.endswith("/openapi.json") or request.path.endswith("/openapi.dify.yaml"):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
def _payload() -> dict:
|
||||
"""读取 JSON 请求体。"""
|
||||
return request.get_json(silent=True) or {}
|
||||
|
||||
|
||||
def _clean_text(value) -> str:
|
||||
return str(value or "").strip()
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def openapi_spec():
|
||||
"""返回 Dify 导入用的 OpenAPI JSON。"""
|
||||
return jsonify(build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/openapi.dify.yaml", methods=["GET"])
|
||||
def openapi_dify_yaml():
|
||||
"""返回 Dify 导入用的 OpenAPI YAML。"""
|
||||
import yaml
|
||||
|
||||
body = yaml.safe_dump(
|
||||
build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()),
|
||||
allow_unicode=True,
|
||||
sort_keys=False,
|
||||
)
|
||||
return current_app.response_class(body, mimetype="text/yaml; charset=utf-8")
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/query_device", methods=["POST"])
|
||||
def query_device():
|
||||
"""按设备编号或名称查询设备台账,并可带出最近维修记录。"""
|
||||
data = _payload()
|
||||
keyword = _clean_text(data.get("keyword"))
|
||||
if not keyword:
|
||||
raise ValidationError("keyword is required")
|
||||
include_records = bool(data.get("include_records", True))
|
||||
record_limit = max(0, min(20, int(data.get("record_limit") or 5)))
|
||||
result = build_device_query_result(keyword, include_records=include_records, record_limit=record_limit)
|
||||
return jsonify({"ok": True, **result})
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/query_records", methods=["POST"])
|
||||
def query_records():
|
||||
"""按设备编号/名称和状态查询维修记录。"""
|
||||
data = _payload()
|
||||
keyword = _clean_text(data.get("keyword"))
|
||||
if not keyword:
|
||||
raise ValidationError("keyword is required")
|
||||
status = _clean_text(data.get("status"))
|
||||
limit = max(1, min(50, int(data.get("limit") or 10)))
|
||||
|
||||
query = db.session.query(MaintenanceRecord)
|
||||
like = f"%{keyword}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
MaintenanceRecord.device_code.ilike(like),
|
||||
MaintenanceRecord.device_name.ilike(like),
|
||||
)
|
||||
)
|
||||
if status:
|
||||
query = query.filter(MaintenanceRecord.repair_status == status)
|
||||
rows = query.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc()).limit(limit).all()
|
||||
return jsonify({
|
||||
"ok": True,
|
||||
"matched": bool(rows),
|
||||
"keyword": keyword,
|
||||
"items": [serialize_record(item) for item in rows],
|
||||
"totalReturned": len(rows),
|
||||
})
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
"""
|
||||
backend/app/api/tools/procurement_contract.py
|
||||
|
||||
用途:采购合同审核面向 Chat/Tool 的 HTTP API。
|
||||
依赖:procurement_contract services、JWT 当前用户、统一 response envelope。
|
||||
逻辑:register_blueprints 从 api.tools 挂载;已登录用户可上传对照文件、发起审核、查本人历史并下载本人报告。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
|
||||
from flask import Blueprint, g, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.procurement_contract import review_service, template_service
|
||||
|
||||
procurement_contract_bp = Blueprint("procurement_contract", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""Return current authenticated user."""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _optional_int(value, field: str) -> int | None:
|
||||
"""Parse optional int payload fields with a ValidationError on bad input."""
|
||||
if value in (None, ""):
|
||||
return None
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(f"{field} must be integer") from exc
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/templates", methods=["GET"])
|
||||
def list_enabled_templates():
|
||||
"""List enabled templates for chat dropdown."""
|
||||
_require_user()
|
||||
return ok(template_service.list_enabled_for_chat(), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews", methods=["POST"])
|
||||
def start_contract_review():
|
||||
"""Start a review; compare mode requires a user-uploaded original contract baseline."""
|
||||
user = _require_user()
|
||||
data = request.get_json() or {}
|
||||
contract_asset_no = (data.get("contract_asset_no") or "").strip()
|
||||
if not contract_asset_no:
|
||||
raise ValidationError("contract_asset_no is required")
|
||||
result = review_service.start_review(
|
||||
user_id=user.id,
|
||||
review_mode=str(data.get("review_mode") or "compare"),
|
||||
contract_asset_no=contract_asset_no,
|
||||
original_contract_asset_no=(data.get("original_contract_asset_no") or None),
|
||||
contract_type=(data.get("contract_type") or None),
|
||||
supplier_name=(data.get("supplier_name") or None),
|
||||
agent_id=_optional_int(data.get("agent_id"), "agent_id"),
|
||||
chat_log_id=_optional_int(data.get("chat_log_id"), "chat_log_id"),
|
||||
)
|
||||
return ok(result, request_id=getattr(g, "request_id", None), status=202)
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews/<review_no>", methods=["GET"])
|
||||
def get_contract_review(review_no: str):
|
||||
"""Get a current user's review by review number."""
|
||||
user = _require_user()
|
||||
return ok(review_service.get_review_for_owner(review_no=review_no, user_id=user.id), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews/<review_no>/report", methods=["GET"])
|
||||
def download_my_contract_review_report(review_no: str):
|
||||
"""Download current user's review report as txt or docx."""
|
||||
user = _require_user()
|
||||
review_service.get_review_for_owner(review_no=review_no, user_id=user.id)
|
||||
if (request.args.get("format") or "").lower() == "docx":
|
||||
name, data, mimetype = review_service.read_review_report_docx_bytes(review_no=review_no)
|
||||
else:
|
||||
name, data = review_service.read_review_report_bytes(review_no=review_no)
|
||||
mimetype = "text/plain; charset=utf-8"
|
||||
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=name)
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews/<review_no>/annotated-contract", methods=["GET"])
|
||||
def download_my_annotated_contract(review_no: str):
|
||||
"""Download current user's original PDF with anchored risk highlights."""
|
||||
user = _require_user()
|
||||
review_service.get_review_for_owner(review_no=review_no, user_id=user.id)
|
||||
name, data, mimetype = review_service.read_review_annotated_contract_bytes(review_no=review_no)
|
||||
return send_file(io.BytesIO(data), mimetype=mimetype, as_attachment=True, download_name=name)
|
||||
|
||||
|
||||
@procurement_contract_bp.route("/reviews", methods=["GET"])
|
||||
def list_my_contract_reviews():
|
||||
"""List current user's recent procurement contract reviews."""
|
||||
user = _require_user()
|
||||
data = review_service.list_reviews(
|
||||
user_id=user.id,
|
||||
review_mode=request.args.get("review_mode") or None,
|
||||
status=request.args.get("status") or None,
|
||||
keyword=request.args.get("keyword") or None,
|
||||
risk_level=request.args.get("risk_level") or None,
|
||||
limit=_optional_int(request.args.get("limit"), "limit") or 20,
|
||||
offset=_optional_int(request.args.get("offset"), "offset") or 0,
|
||||
)
|
||||
return ok(data, request_id=getattr(g, "request_id", None))
|
||||
@@ -1,8 +1,428 @@
|
||||
"""
|
||||
backend/app/api/tools/shipping_notice.py
|
||||
|
||||
用途:出货通知 Tool API Blueprint(Wave 1 自 shipping_notice_tools.py 迁入)。
|
||||
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。
|
||||
依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url。
|
||||
逻辑:register_blueprints 从 api.tools 挂载;Tool 成功响应仍用 status: ok/failed 业务 envelope;
|
||||
HTTP 级参数/资源错误统一 raise AppError;`_payload()` 剥离 body 中的操作人伪造字段;
|
||||
历史批次 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,
|
||||
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__)
|
||||
|
||||
|
||||
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/receipt-unit-progress', methods=['POST'])
|
||||
def rpa_receipt_unit_progress():
|
||||
"""收料单元领取/导出中:awaiting_rpa → processing,供管理端实时看到进行中。
|
||||
|
||||
本路由同时是收料超时对账的活动锚数据源(mark 落单元 started_at);
|
||||
曾因重构分叉合并丢失(2026-10-08),Worker 上报全程 404,勿再从旧路径文件删除。
|
||||
"""
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import mark_receipt_unit_processing
|
||||
|
||||
return jsonify({'success': True, 'data': mark_receipt_unit_processing(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/receipt-batch-progress', methods=['POST'])
|
||||
def rpa_receipt_batch_progress():
|
||||
"""收料 RPA 每完成一笔导出的累计进度回写(非终态,对齐库存 inventory-batch-progress)。"""
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import report_receipt_batch_progress
|
||||
|
||||
return jsonify({'success': True, 'data': report_receipt_batch_progress(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-batch-claimed', methods=['POST'])
|
||||
def rpa_inventory_batch_claimed():
|
||||
"""v2 Worker 领取回调:仅记录 Attempt 执行阶段。"""
|
||||
from app.services.shipping_notice.per_source_rpa_service import claim_inventory_batch
|
||||
return jsonify({'success': True, 'data': claim_inventory_batch(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-batch-progress', methods=['POST'])
|
||||
def rpa_inventory_batch_progress():
|
||||
"""RPA 批量库存导出进度回调:实时回写排程 run 计数(非终态,最终以 batch-ready 为准)。"""
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import report_inventory_batch_progress
|
||||
return jsonify(report_inventory_batch_progress(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-configuration-test-ready', methods=['POST'])
|
||||
def rpa_inventory_configuration_test_ready():
|
||||
"""RPA 配置测试回调:仅分析文件结构,不创建生产库存快照或任务关联。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_test_export(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-configuration-test-batch-ready', methods=['POST'])
|
||||
def rpa_inventory_configuration_test_batch_ready():
|
||||
"""RPA 批量配置测试回调:按 validation_run_no 独立回写每个库存站点。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_batch_test_exports(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-configuration-test-batch-progress', methods=['POST'])
|
||||
def rpa_inventory_configuration_test_batch_progress():
|
||||
"""RPA 批量配置测试进度:Worker 领取单个站点后立即回写执行阶段。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_batch_test_progress(_payload())})
|
||||
|
||||
@shipping_notice_bp.route('/tasks/<task_no>/repair-inventory-attachment', methods=['POST'])
|
||||
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,5 +1,5 @@
|
||||
"""
|
||||
backend/app/api/training.py
|
||||
backend/app/api/training/__init__.py
|
||||
|
||||
用途:提供新人培训用户侧进度接口与管理端统计导出接口。
|
||||
依赖:JWT 当前用户解析、training_service、Flask Blueprint/send_file。
|
||||
@@ -435,7 +435,7 @@ def _build_login_payload(user: User, source: str='password', bind_status: str=No
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'default_agent_id': user.default_agent_id,
|
||||
'feature_permissions': user.get_feature_permissions(),
|
||||
**user.client_auth_fields(),
|
||||
'source': source,
|
||||
'access_token': issue_local_access_token(user),
|
||||
'token_type': 'Bearer',
|
||||
|
||||
@@ -185,7 +185,7 @@ def home():
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
|
||||
def _load_home_payload():
|
||||
if user.role == 'admin':
|
||||
if user.is_platform_admin():
|
||||
agent_rows = Agent.query.filter(Agent.is_active.is_(True)).all()
|
||||
else:
|
||||
agent_rows = [agent for agent in user.agents if agent.is_active]
|
||||
@@ -213,7 +213,7 @@ def home():
|
||||
'runtime_provider': registry.get('runtime_provider'),
|
||||
'conversation_mode': registry.get('conversation_mode'),
|
||||
})
|
||||
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
|
||||
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'language': user.language, 'theme_preference': user.theme_preference or 'system', **user.client_auth_fields()}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
|
||||
try:
|
||||
return _run_db_with_retry(_load_home_payload, label='user.home')
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
@@ -297,7 +297,7 @@ def user_profile():
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
if request.method == 'GET':
|
||||
return jsonify({'id': user.id, 'username': user.username, 'real_name': user.real_name, 'email': user.email, 'phone_number': user.phone_number, 'employee_id': user.employee_id, 'department': user.department, 'role': user.role, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'})
|
||||
return jsonify({'id': user.id, 'username': user.username, 'real_name': user.real_name, 'email': user.email, 'phone_number': user.phone_number, 'employee_id': user.employee_id, 'department': user.department, 'role': user.role, 'language': user.language, 'theme_preference': user.theme_preference or 'system', **user.client_auth_fields()})
|
||||
data = request.get_json() or {}
|
||||
|
||||
def _update_profile():
|
||||
@@ -348,7 +348,7 @@ def get_agent_details(id):
|
||||
agent = db.session.get(Agent, id)
|
||||
if not agent:
|
||||
raise NotFoundError('Not found')
|
||||
if user.role != 'admin':
|
||||
if not user.is_platform_admin():
|
||||
has_permission = agent in user.agents
|
||||
if not has_permission:
|
||||
raise ForbiddenError('Access denied')
|
||||
|
||||
@@ -20,7 +20,7 @@ from flask import Blueprint, Response, current_app, g, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.core.errors import AppError, ConflictError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice, ShippingOrderTask
|
||||
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
|
||||
@@ -186,6 +186,7 @@ def workspace_shipping_tasks():
|
||||
lifecycle_status=lifecycle_status,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
is_admin=bool(user.is_platform_admin()),
|
||||
))
|
||||
|
||||
|
||||
@@ -199,7 +200,7 @@ def workspace_shipping_my_todos():
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.query_service import list_my_todos
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
try:
|
||||
page = int(request.args.get('page') or 1)
|
||||
page_size = int(request.args.get('page_size') or 20)
|
||||
@@ -224,7 +225,7 @@ def workspace_shipping_my_todos_count():
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.query_service import count_my_todos
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
return _ok(count_my_todos(user.id, is_admin=is_admin))
|
||||
|
||||
|
||||
@@ -249,7 +250,7 @@ def workspace_shipping_done_lines():
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.done_line_report import list_done_notice_lines
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
try:
|
||||
page = int(request.args.get('page') or 1)
|
||||
page_size = int(request.args.get('page_size') or 20)
|
||||
@@ -276,7 +277,7 @@ def workspace_shipping_done_lines_export():
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.done_line_report import build_done_lines_xlsx
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
stream, filename = build_done_lines_xlsx(
|
||||
user.id,
|
||||
is_admin=is_admin,
|
||||
@@ -302,7 +303,7 @@ def _batch_task_nos(data: dict) -> list[str]:
|
||||
|
||||
def _can_dispose_task(user, task) -> bool:
|
||||
"""管理员可跨用户处置;普通用户仅可处置自己名下或未归属任务。"""
|
||||
return str(getattr(user, 'role', '')).lower() == 'admin' or task.user_id in {None, user.id}
|
||||
return bool(user.is_platform_admin()) or task.user_id in {None, user.id}
|
||||
|
||||
|
||||
def _batch_dispose(action: str):
|
||||
@@ -345,7 +346,7 @@ def _batch_dispose(action: str):
|
||||
def workspace_batch_purge_shipping_tasks():
|
||||
"""仅管理员可永久清除回收站中的纯误建任务;每条均在行锁下重查全部引用。"""
|
||||
user = _require_user()
|
||||
if str(getattr(user, 'role', '')).lower() != 'admin':
|
||||
if not user.is_platform_admin():
|
||||
from app.core.errors import ForbiddenError
|
||||
|
||||
raise ForbiddenError('Admin privilege required')
|
||||
@@ -394,14 +395,38 @@ def workspace_batch_restore_shipping_tasks():
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-exports/archive', methods=['POST'])
|
||||
def workspace_shipping_export_archive():
|
||||
"""按显式任务号下载当前用户可访问的 ready 发货 Excel ZIP。"""
|
||||
"""按显式任务号下载当前用户可下载(创建者或管理员)的 ready 发货 Excel ZIP。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
task_nos = data.get('task_nos')
|
||||
if task_nos is not None and not isinstance(task_nos, list):
|
||||
raise ValidationError('task_nos must be a list', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
|
||||
from app.services.shipping_notice.export_archive import build_export_archive
|
||||
stream, filename, _manifest = build_export_archive(user_id=user.id, task_nos=task_nos or [])
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
|
||||
stream, filename, manifest = build_export_archive(
|
||||
user_id=user.id,
|
||||
task_nos=task_nos or [],
|
||||
is_admin=bool(user.is_platform_admin()),
|
||||
)
|
||||
# 与 business_no 批量导出同一审计口径:按票落 record_access_audit(自行提交)。
|
||||
for entry in manifest.get('entries') or []:
|
||||
aggregate_no = str(entry.get('business_no') or '').strip()
|
||||
task_no = str(entry.get('task_no') or '').strip()
|
||||
if not aggregate_no and not task_no:
|
||||
continue
|
||||
record_access_audit(
|
||||
action='download_task_excel',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=task_no or aggregate_no,
|
||||
actor_id=user.id,
|
||||
task_no=task_no or None,
|
||||
reason_code='excel_downloaded',
|
||||
metadata={
|
||||
'export': 'batch_zip',
|
||||
'batch_status': str(entry.get('status') or ''),
|
||||
},
|
||||
)
|
||||
response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip')
|
||||
response.call_on_close(stream.close)
|
||||
return response
|
||||
@@ -455,7 +480,11 @@ def workspace_confirm_shipping_customer(task_no: str):
|
||||
details={'field': 'customer_id'},
|
||||
) from exc
|
||||
updated = confirm_task_customer(task, customer_id=customer_id, actor_id=user.id)
|
||||
return _ok(serialize_task_detail(updated))
|
||||
return _ok(serialize_task_detail(
|
||||
updated,
|
||||
viewer_user_id=user.id,
|
||||
is_admin=bool(user.is_platform_admin()),
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
|
||||
@@ -499,7 +528,7 @@ def workspace_create_shipping_task_from_notice():
|
||||
db.session.commit()
|
||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
|
||||
orchestrator_started = start_task_orchestrator(task_id)
|
||||
return _ok({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
|
||||
return _ok({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task, viewer_user_id=user.id) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/replace-notice', methods=['POST'])
|
||||
def workspace_replace_shipping_task_notice(task_no: str):
|
||||
@@ -542,7 +571,7 @@ def workspace_shipping_task_detail(task_no: str):
|
||||
position / user_mode / actions / steps,减少前端二次推导与竞态刷新。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||||
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
|
||||
if not task:
|
||||
@@ -562,7 +591,7 @@ def workspace_shipping_task_detail(task_no: str):
|
||||
def workspace_shipping_task_odm_options(task_no: str):
|
||||
"""返回整单 ODM ID 候选与当前选择(工作台整单裁决路径,只读)。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.notice_odm_choice_service import notice_odm_options
|
||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||||
|
||||
@@ -576,7 +605,7 @@ def workspace_shipping_task_odm_options(task_no: str):
|
||||
def workspace_set_shipping_task_odm_choice(task_no: str):
|
||||
"""保存整单 ODM ID 用户选择;重复提交覆盖旧选择,成功后前端可重试生成 Excel。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.notice_odm_choice_service import set_notice_odm_choice
|
||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||||
|
||||
@@ -601,7 +630,7 @@ def workspace_set_shipping_task_odm_choice(task_no: str):
|
||||
def workspace_list_shipping_task_audit_timeline(task_no: str):
|
||||
"""业务用户 Task 审计时间线(统一 ShippingAuditEvent,无敏感快照)。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.audit_query_service import list_task_audit_timeline
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||||
@@ -633,7 +662,7 @@ def workspace_list_shipping_task_audit_timeline(task_no: str):
|
||||
def workspace_shipping_task_freight_notice_groups(task_no: str):
|
||||
"""读取当前 PO 下按 business_no 聚合的货代上传 Notice;仅供订单工作台展示。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_task_visible_to_user,
|
||||
list_freight_notice_groups_for_task,
|
||||
@@ -657,7 +686,12 @@ def workspace_shipping_task_ui_state(task_no: str):
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok(build_task_ui_state(task, include_stage_context=True))
|
||||
return _ok(build_task_ui_state(
|
||||
task,
|
||||
include_stage_context=True,
|
||||
viewer_user_id=user.id,
|
||||
viewer_is_admin=bool(user.is_platform_admin()),
|
||||
))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET'])
|
||||
def workspace_shipping_task_chat_actions(task_no: str):
|
||||
@@ -1032,6 +1066,38 @@ def _load_business_notice_for_user(*, business_no: str, user_id: int) -> Shippin
|
||||
return task
|
||||
|
||||
|
||||
def _load_business_notice_readable_for_user(
|
||||
*,
|
||||
business_no: str,
|
||||
user_id: int,
|
||||
is_admin: bool,
|
||||
) -> ShippingNotice:
|
||||
"""
|
||||
按精确发货通知单号加载当前用户可下载的 Notice(创建者或管理员)。
|
||||
|
||||
核心逻辑:下载是只读动作,授权走 can_download_task_export 统一谓词口径
|
||||
(可下载=可见),不经过写路径的履约归属断言;管理员可下载其可见的正式
|
||||
Notice,且每次下载均由端点写入 record_access_audit。
|
||||
|
||||
Args:
|
||||
business_no: 对外发货通知单号。
|
||||
user_id: 当前服务端会话用户主键。
|
||||
is_admin: 是否平台管理员。
|
||||
|
||||
Returns:
|
||||
可下载的 ShippingNotice。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 编号不存在、非正式 Notice 或用户不可见。
|
||||
"""
|
||||
normalized = str(business_no or '').strip().upper()
|
||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||||
task = get_task_visible_to_user(normalized, user_id, is_admin=is_admin)
|
||||
if not isinstance(task, ShippingNotice) or str(task.business_no or '').strip().upper() != normalized:
|
||||
raise NotFoundError('Shipping notice not found')
|
||||
return task
|
||||
|
||||
|
||||
def _start_notice_rpa_upload(*, business_no: str, user_id: int, artifact_id: int | None = None) -> dict[str, Any]:
|
||||
"""按 business_no 发起单张通知的货代 RPA 上传或重试。"""
|
||||
task = _load_business_notice_for_user(business_no=business_no, user_id=user_id)
|
||||
@@ -1138,9 +1204,13 @@ def workspace_batch_start_shipping_notice_rpa_upload():
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/export', methods=['GET'])
|
||||
def workspace_shipping_notice_export(business_no: str):
|
||||
"""按发货通知单号下载该通知唯一的正式 Excel,并保留下载审计。"""
|
||||
"""按发货通知单号下载该通知唯一的正式 Excel(创建者或管理员),并保留下载审计。"""
|
||||
user = _require_user()
|
||||
task = _load_business_notice_for_user(business_no=business_no, user_id=int(user.id))
|
||||
task = _load_business_notice_readable_for_user(
|
||||
business_no=business_no,
|
||||
user_id=int(user.id),
|
||||
is_admin=bool(user.is_platform_admin()),
|
||||
)
|
||||
err_msg = task_export_error_message(task)
|
||||
if err_msg:
|
||||
raise NotFoundError(err_msg)
|
||||
@@ -1162,7 +1232,7 @@ def workspace_shipping_notice_export(business_no: str):
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notices/batch/export', methods=['POST'])
|
||||
def workspace_shipping_notice_export_archive():
|
||||
"""按多个 business_no 下载各自唯一 Excel 的 ZIP;任一越权或缺文件均整体拒绝。"""
|
||||
"""按多个 business_no 下载各自唯一 Excel 的 ZIP(创建者或管理员);任一越权或缺文件均整体拒绝。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
raw_values = data.get('business_nos')
|
||||
@@ -1174,8 +1244,32 @@ def workspace_shipping_notice_export_archive():
|
||||
if not business_nos or len(business_nos) > 100:
|
||||
raise ValidationError('business_nos must contain 1 to 100 business numbers')
|
||||
from app.services.shipping_notice.export_archive import build_export_archive
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
|
||||
stream, filename, _manifest = build_export_archive(user_id=int(user.id), business_nos=business_nos)
|
||||
stream, filename, manifest = build_export_archive(
|
||||
user_id=int(user.id),
|
||||
business_nos=business_nos,
|
||||
is_admin=bool(user.is_platform_admin()),
|
||||
)
|
||||
# 批量导出与单票下载同一审计口径:按票落 record_access_audit(自行提交),
|
||||
# manifest.business_no 是 aggregate 事实源;missing/checksum 票据也留痕。
|
||||
for entry in manifest.get('entries') or []:
|
||||
aggregate_no = str(entry.get('business_no') or '').strip()
|
||||
task_no = str(entry.get('task_no') or '').strip()
|
||||
if not aggregate_no and not task_no:
|
||||
continue
|
||||
record_access_audit(
|
||||
action='download_notice_excel',
|
||||
aggregate_type='shipping_notice',
|
||||
aggregate_id=aggregate_no or task_no,
|
||||
actor_id=user.id,
|
||||
task_no=task_no or None,
|
||||
reason_code='excel_downloaded',
|
||||
metadata={
|
||||
'export': 'batch_zip',
|
||||
'batch_status': str(entry.get('status') or ''),
|
||||
},
|
||||
)
|
||||
response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip')
|
||||
response.call_on_close(stream.close)
|
||||
return response
|
||||
@@ -1183,9 +1277,10 @@ def workspace_shipping_notice_export_archive():
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
|
||||
def workspace_shipping_task_export(task_no: str):
|
||||
"""下载当前用户可访问任务的出货 Excel;写入统一访问审计。"""
|
||||
"""下载当前用户可下载任务的出货 Excel(创建者或管理员);写入统一访问审计。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
from app.services.shipping_notice.query_service import get_task_visible_to_user
|
||||
task = get_task_visible_to_user(task_no, user.id, is_admin=bool(user.is_platform_admin()))
|
||||
task = _require_formal_notice(task)
|
||||
err_msg = task_export_error_message(task)
|
||||
if err_msg:
|
||||
@@ -1604,7 +1699,7 @@ def workspace_get_shipping_order_review_run(run_no: str):
|
||||
JSON 响应契约或业务数据。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_run
|
||||
from app.services.shipping_notice.order_review_service import get_review_run_visible_to_user
|
||||
@@ -1639,7 +1734,7 @@ def workspace_get_shipping_order_review_queue(run_no: str):
|
||||
JSON 响应契约或业务数据。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_queue
|
||||
from app.services.shipping_notice.order_review_service import get_review_queue_visible_to_user
|
||||
@@ -1676,7 +1771,7 @@ def workspace_get_shipping_order_review_case(case_no: str):
|
||||
JSON 响应契约或业务数据。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_case_snapshot import (
|
||||
build_order_review_case_snapshot,
|
||||
@@ -1724,7 +1819,7 @@ def workspace_retry_shipping_order_stp_auto_create(case_no: str):
|
||||
要求前端切换到 reconcile-and-progress;通过后再委托 retry_stp_auto_create_for_case。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import (
|
||||
retry_stp_auto_create_for_case,
|
||||
@@ -1762,7 +1857,7 @@ def workspace_reconcile_shipping_order_case_and_progress(case_no: str):
|
||||
source_content_hash: string(可选,请求快照用于参数一致性)
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
payload = request.get_json(silent=True) if request.is_json else None
|
||||
if not isinstance(payload, dict):
|
||||
payload = {}
|
||||
@@ -1821,7 +1916,7 @@ def workspace_audit_shipping_order_review_version_history(case_no: str):
|
||||
核心逻辑:先做 Case 可见性校验,再写入 access + 工作台语义事件,禁止仅改本地 UI 状态而不留痕。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit, record_fulfillment_audit
|
||||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||||
|
||||
@@ -1867,7 +1962,7 @@ def workspace_audit_shipping_order_review_eligibility_details(case_no: str):
|
||||
核心逻辑:先做 Case 可见性校验,再写入 access + 工作台语义事件。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit, record_fulfillment_audit
|
||||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||||
|
||||
@@ -2103,6 +2198,88 @@ def workspace_confirm_shipping_order_review_customer(case_no: str):
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/customer/rebind',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_rebind_shipping_order_review_customer(case_no: str):
|
||||
"""
|
||||
确认客户改绑:直接修改已确认的客户识别结果并刷新订单快照客户。
|
||||
|
||||
Body: customer_id, expected_order_data_version, reason?
|
||||
仅当订单编辑窗 header 可编辑(任一通知无 Export Artifact 且无活动 Gate Attempt,
|
||||
即发货通知/Excel 未产生)时允许;版本乐观锁与状态守卫在服务层 fail-closed。
|
||||
"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
customer_id = int(data.get('customer_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'Customer id is required',
|
||||
code='SHIPPING.CUSTOMER_REBIND_CUSTOMER_REQUIRED',
|
||||
details={'field': 'customer_id'},
|
||||
) from exc
|
||||
try:
|
||||
expected_order_data_version = int(data.get('expected_order_data_version'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'Expected order data version is required',
|
||||
code='SHIPPING.CUSTOMER_REBIND_VERSION_REQUIRED',
|
||||
details={'field': 'expected_order_data_version'},
|
||||
) from exc
|
||||
|
||||
from app.services.shipping_notice.customer_resolution_service import rebind_confirmed_customer
|
||||
from app.services.shipping_notice.order_review_customer_service import (
|
||||
project_review_case_customer_resolution,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_draft_service import soft_load_review_case_for_audit
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_case
|
||||
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
|
||||
|
||||
case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or ''))
|
||||
if case is None:
|
||||
raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
|
||||
formal = resolve_formal_ot(case)
|
||||
if not formal.get('has_formal_ot') or formal.get('task') is None:
|
||||
raise ConflictError(
|
||||
'A formal order task is required before rebinding customer',
|
||||
code='SHIPPING.FORMAL_OT_REQUIRED',
|
||||
details={'task_missing': bool(formal.get('task_missing'))},
|
||||
)
|
||||
|
||||
result = rebind_confirmed_customer(
|
||||
task=formal['task'],
|
||||
new_customer_id=customer_id,
|
||||
actor_id=int(user.id),
|
||||
expected_order_data_version=expected_order_data_version,
|
||||
reason=str(data.get('reason') or '').strip() or None,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
resolution = result['resolution']
|
||||
rebind_record = next(
|
||||
(
|
||||
item.get('rebind') for item in (resolution.evidence_json or [])
|
||||
if isinstance(item, dict) and item.get('rebind')
|
||||
),
|
||||
None,
|
||||
) or {}
|
||||
refreshed_case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or ''))
|
||||
return _ok({
|
||||
'case': serialize_review_case(refreshed_case) if refreshed_case is not None else None,
|
||||
'customer_resolution': (
|
||||
project_review_case_customer_resolution(refreshed_case)
|
||||
if refreshed_case is not None else None
|
||||
),
|
||||
'rebind': {
|
||||
'previous_customer_id': rebind_record.get('previous_customer_id'),
|
||||
'customer_id': int(resolution.confirmed_customer_id),
|
||||
'snapshot_id': int(result['snapshot'].id),
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/reservation/revalidate',
|
||||
methods=['POST'],
|
||||
@@ -2135,7 +2312,7 @@ def workspace_revalidate_shipping_order_review_reservation(case_no: str):
|
||||
def workspace_list_shipping_order_review_audit_timeline(case_no: str):
|
||||
"""业务用户 Case 审计时间线(无敏感快照)。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.audit_query_service import list_review_case_audit_timeline
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||||
@@ -2176,7 +2353,7 @@ def workspace_decide_shipping_order_review_line_fulfillment(case_no: str):
|
||||
decide_review_line_fulfillment,
|
||||
)
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
result = decide_review_line_fulfillment(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
@@ -2277,7 +2454,7 @@ def workspace_close_shipping_order_review_fulfillment(case_no: str):
|
||||
close_remaining_fulfillment,
|
||||
)
|
||||
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
result = close_remaining_fulfillment(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
@@ -2690,7 +2867,7 @@ def workspace_attempt_shipping_order_review_field_locate(case_no: str):
|
||||
def workspace_list_shipping_order_review_llm_suggestions(case_no: str):
|
||||
"""列出 Case 下 Dify 最小证据建议记录。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.order_review_llm_service import list_case_suggestions
|
||||
|
||||
return _ok(list_case_suggestions(user_id=user.id, case_no=case_no, is_admin=is_admin))
|
||||
@@ -2700,7 +2877,7 @@ def workspace_list_shipping_order_review_llm_suggestions(case_no: str):
|
||||
def workspace_request_shipping_order_review_llm_suggestion(case_no: str):
|
||||
"""为指定字段请求 Dify 最小证据建议;Provider 不可用时不阻断人工复核。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.order_review_llm_service import request_field_suggestion
|
||||
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='request_llm_suggestion')
|
||||
@@ -2725,7 +2902,7 @@ def workspace_request_shipping_order_review_llm_suggestion(case_no: str):
|
||||
def workspace_adjudicate_shipping_order_review_llm_suggestion(case_no: str, suggestion_no: str):
|
||||
"""人工裁决 LLM 建议:accept / modify / reject。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
is_admin = bool(user.is_platform_admin())
|
||||
from app.services.shipping_notice.order_review_llm_service import decide_suggestion
|
||||
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='adjudicate_llm_suggestion')
|
||||
|
||||
@@ -135,7 +135,7 @@ def workspace_post_process_gate_action(execution_no: str, gate_code: str):
|
||||
action_code=parsed['action_code'],
|
||||
expected_gate_version=parsed['expected_gate_version'],
|
||||
idempotency_key=parsed['idempotency_key'],
|
||||
actor_type='admin' if str(user.role or '').lower() == 'admin' else 'user',
|
||||
actor_type='admin' if user.is_platform_admin() else 'user',
|
||||
actor_id=int(user.id),
|
||||
payload=parsed['payload'],
|
||||
)
|
||||
|
||||
@@ -4,7 +4,7 @@ backend/app/api/workspace/voucher_check.py
|
||||
用途:立账凭证检核查询、强制重检与通知配置 API(任务列表 / 最近一次检核 / 批次明细 / 企微发送记录 / 按类型接收人)。
|
||||
依赖:auth.jwt、response_utils envelope、Agent 授权、voucher_check.query_service、notify_config_service。
|
||||
逻辑:Chat Agent 与旧工作台查询共用;GET runs/latest 不跟筛选;GET notifications 为企微发送记录;
|
||||
查询要求平台 admin 或持有 `agent_code=voucher_check` 的 Agent 授权;POST runs 与通知配置仅 admin。
|
||||
查询要求 is_platform_admin 或持有 `agent_code=voucher_check` 的 Agent 授权;POST runs 与通知配置仅平台管理员。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -42,7 +42,7 @@ def _user_has_voucher_check_agent(user) -> bool:
|
||||
"""
|
||||
判断用户是否持有启用中的立账凭证检核 Agent。
|
||||
|
||||
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions;admin 不走此判断。
|
||||
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions;平台管理员不走此判断。
|
||||
|
||||
Args:
|
||||
user: 已认证用户。
|
||||
@@ -58,18 +58,18 @@ def _require_voucher_check_access():
|
||||
"""
|
||||
确保当前用户已登录且具备立账凭证检核访问权限。
|
||||
|
||||
核心逻辑:平台 admin 放行;普通用户必须被授予启用中的 `agent_code=voucher_check` Agent。
|
||||
核心逻辑:is_platform_admin 放行;普通用户必须被授予启用中的 `agent_code=voucher_check` Agent。
|
||||
无权限时返回业务 403,而不是静默空数据。
|
||||
|
||||
Returns:
|
||||
已认证且具备立账凭证 Agent 授权(或 admin)的用户。
|
||||
已认证且具备立账凭证 Agent 授权(或平台管理员)的用户。
|
||||
|
||||
Raises:
|
||||
UnauthorizedError: 请求没有有效登录身份。
|
||||
ForbiddenError: 已登录但没有立账凭证 Agent 授权。
|
||||
"""
|
||||
user = _require_user()
|
||||
if getattr(user, "role", None) == "admin" or _user_has_voucher_check_agent(user):
|
||||
if user.is_platform_admin() or _user_has_voucher_check_agent(user):
|
||||
return user
|
||||
raise ForbiddenError(
|
||||
"Voucher check agent permission required",
|
||||
@@ -81,7 +81,7 @@ def _require_admin():
|
||||
"""
|
||||
确保当前用户既有立账凭证访问权,又是平台管理员。
|
||||
|
||||
核心逻辑:持有 Agent 的普通用户可查检核任务与发送记录;强制重检与通知配置仅 `role=admin`。
|
||||
核心逻辑:持有 Agent 的普通用户可查检核任务与发送记录;强制重检与通知配置仅 is_platform_admin。
|
||||
|
||||
Returns:
|
||||
已认证的管理员用户。
|
||||
@@ -91,7 +91,7 @@ def _require_admin():
|
||||
ForbiddenError: 无立账凭证访问权,或已授权但不是管理员。
|
||||
"""
|
||||
user = _require_voucher_check_access()
|
||||
if getattr(user, "role", None) != "admin":
|
||||
if not user.is_platform_admin():
|
||||
raise ForbiddenError(
|
||||
"Admin privilege required for voucher check jobs",
|
||||
code="VOUCHER_CHECK.ADMIN_REQUIRED",
|
||||
@@ -181,7 +181,7 @@ def workspace_voucher_notifications():
|
||||
def workspace_voucher_notify_config_get():
|
||||
"""
|
||||
读取按文件类型的企微接收人配置。
|
||||
核心逻辑:仅 admin;规则来自销售 Profile,接收人来自独立配置表。
|
||||
核心逻辑:仅 is_platform_admin;规则来自销售 Profile,接收人来自独立配置表。
|
||||
"""
|
||||
_require_admin()
|
||||
return ok(notify_config_service.get_notify_config(profile_code=request.args.get("profile_code")))
|
||||
@@ -191,7 +191,7 @@ def workspace_voucher_notify_config_get():
|
||||
def workspace_voucher_notify_config_put():
|
||||
"""
|
||||
保存按文件类型的企微接收人。
|
||||
核心逻辑:仅 admin;未知规则码丢弃;未绑企微的人可保存但发送时跳过。
|
||||
核心逻辑:仅 is_platform_admin;未知规则码丢弃;未绑企微的人可保存但发送时跳过。
|
||||
"""
|
||||
user = _require_admin()
|
||||
payload = request.get_json(silent=True) or {}
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
"""
|
||||
backend/app/api/workspace_file_check.py
|
||||
|
||||
用途:工作台文件检核 API 兼容 shim(Wave 1 迁包)。
|
||||
依赖:app.api.workspace.file_check。
|
||||
逻辑:旧 import 路径仍可用;新代码请用 app.api.workspace。
|
||||
"""
|
||||
from app.api.workspace.file_check import (
|
||||
serialize_current_step,
|
||||
serialize_file_judgement,
|
||||
workspace_file_check_bp,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'serialize_current_step',
|
||||
'serialize_file_judgement',
|
||||
'workspace_file_check_bp',
|
||||
]
|
||||
@@ -2,8 +2,9 @@
|
||||
backend/app/core/config/env_persistence.py
|
||||
|
||||
用途:运行时配置 DB 持久化与 env 镜像(WeCom 等 admin 设置)。
|
||||
依赖:app.extensions.db、app.models.AppSetting。
|
||||
逻辑:before_request 调用 apply_env_settings;persist_env_settings 供 admin 写入。
|
||||
依赖:app.extensions.db、app.models.AppSetting、threading/time(进程内 TTL 缓存)。
|
||||
逻辑:admin 经 persist_env_settings 写入;HTTP before_request 调用 apply_env_settings
|
||||
按 APP_SETTINGS_REFRESH_SECONDS 做进程内 TTL,避免每个请求全表扫描;写入时刷新缓存。
|
||||
|
||||
Storage strategy:
|
||||
1. Database (app_settings) - canonical
|
||||
@@ -15,6 +16,8 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
@@ -39,6 +42,12 @@ WECOM_BOOL_KEYS = {
|
||||
'WECOM_FEEDBACK_NOTIFY_ENABLED',
|
||||
}
|
||||
|
||||
_DEFAULT_REFRESH_SECONDS = 30.0
|
||||
_cache_lock = threading.Lock()
|
||||
_cache_prefixes: tuple[str, ...] | None = None
|
||||
_cache_applied: dict[str, object] = {}
|
||||
_cache_loaded_at: float = 0.0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
@@ -87,6 +96,27 @@ def _matches_prefixes(key: str, prefixes: Iterable[str]) -> bool:
|
||||
return any(key.startswith(prefix) for prefix in prefixes)
|
||||
|
||||
|
||||
def _refresh_ttl_seconds() -> float:
|
||||
"""
|
||||
读取进程内配置热更新 TTL(秒)。
|
||||
|
||||
核心逻辑:优先 Flask app.config;否则环境变量;非法值回退默认 30。
|
||||
设为 0 表示每次强制重载(兼容旧行为,便于排障)。
|
||||
"""
|
||||
raw: object = os.getenv('APP_SETTINGS_REFRESH_SECONDS', str(_DEFAULT_REFRESH_SECONDS))
|
||||
try:
|
||||
from flask import current_app, has_app_context
|
||||
|
||||
if has_app_context():
|
||||
raw = current_app.config.get('APP_SETTINGS_REFRESH_SECONDS', raw)
|
||||
except Exception: # pragma: no cover - 无 Flask 上下文时忽略
|
||||
pass
|
||||
try:
|
||||
return max(0.0, float(raw if raw not in (None, '') else _DEFAULT_REFRESH_SECONDS))
|
||||
except (TypeError, ValueError):
|
||||
return _DEFAULT_REFRESH_SECONDS
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Database read/write (primary store)
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -127,7 +157,14 @@ def _persist_to_db(values: dict[str, str]) -> bool:
|
||||
|
||||
|
||||
def _load_from_db(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
"""
|
||||
从 app_settings 读取匹配前缀的配置行。
|
||||
|
||||
核心逻辑:用 LIKE 前缀过滤,避免每次 before_request 拉全表后再 Python 过滤。
|
||||
"""
|
||||
try:
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import AppSetting
|
||||
except Exception as exc: # pragma: no cover
|
||||
@@ -135,7 +172,11 @@ def _load_from_db(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
return {}
|
||||
|
||||
try:
|
||||
rows = db.session.query(AppSetting).all()
|
||||
if not prefixes:
|
||||
rows = db.session.query(AppSetting).all()
|
||||
else:
|
||||
clauses = [AppSetting.key.like(f'{prefix}%') for prefix in prefixes]
|
||||
rows = db.session.query(AppSetting).filter(or_(*clauses)).all()
|
||||
except Exception as exc:
|
||||
# Most common case: the migration has not been applied yet on a
|
||||
# freshly-built container. Degrade gracefully to .env-only mode.
|
||||
@@ -197,15 +238,36 @@ def _load_from_env_file(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def persist_env_settings(values: dict[str, object]) -> dict[str, str]:
|
||||
"""Persist settings to the canonical store and mirror to ``os.environ``.
|
||||
def invalidate_env_settings_cache() -> None:
|
||||
"""
|
||||
清空进程内配置缓存,使下次 apply_env_settings 强制读库。
|
||||
|
||||
Order:
|
||||
1. Mirror to ``os.environ`` so the current process picks them up
|
||||
immediately.
|
||||
2. Persist to the database (canonical, survives container rebuilds).
|
||||
3. In dev only, best-effort write to ``.env.local`` so local restarts
|
||||
without DB access keep working.
|
||||
用途:测试或运维需要立刻看到外部写入的 app_settings 时调用。
|
||||
"""
|
||||
global _cache_loaded_at, _cache_applied, _cache_prefixes
|
||||
with _cache_lock:
|
||||
_cache_loaded_at = 0.0
|
||||
_cache_applied = {}
|
||||
_cache_prefixes = None
|
||||
|
||||
|
||||
def _store_cache(prefixes: tuple[str, ...], applied: dict[str, object]) -> None:
|
||||
"""写入进程内 TTL 缓存(调用方须已持有 _cache_lock)。"""
|
||||
global _cache_loaded_at, _cache_applied, _cache_prefixes
|
||||
_cache_prefixes = prefixes
|
||||
_cache_applied = dict(applied)
|
||||
_cache_loaded_at = time.monotonic()
|
||||
|
||||
|
||||
def persist_env_settings(values: dict[str, object]) -> dict[str, str]:
|
||||
"""
|
||||
将设置写入权威存储,并镜像到 ``os.environ`` 与进程内缓存。
|
||||
|
||||
顺序:
|
||||
1. 镜像到 ``os.environ``,当前进程立即可见;
|
||||
2. 写入数据库(权威源,容器重建后仍在);
|
||||
3. 仅在 dev 尽力写 ``.env.local``;
|
||||
4. 合并进 TTL 缓存并刷新时间戳,避免本进程还要等 TTL 才看到新值。
|
||||
"""
|
||||
if not values:
|
||||
return {}
|
||||
@@ -226,24 +288,61 @@ def persist_env_settings(values: dict[str, object]) -> dict[str, str]:
|
||||
list(persisted.keys()),
|
||||
)
|
||||
|
||||
# [STEP] 写入后失效缓存:下一请求全量重载,避免「只合并写入键」导致 TTL 内缺键。
|
||||
# 当前进程通常已在 admin service 里同步写过 current_app.config。
|
||||
invalidate_env_settings_cache()
|
||||
|
||||
return persisted
|
||||
|
||||
|
||||
def apply_env_settings(prefixes: tuple[str, ...] = ('WECOM_',)) -> dict[str, object]:
|
||||
"""Load settings from the canonical store and apply to ``os.environ``.
|
||||
|
||||
DB values take priority over env-file values; both are merged so
|
||||
keys that only live in env files (e.g. fresh deploy before any admin
|
||||
edit) are still honored.
|
||||
def apply_env_settings(
|
||||
prefixes: tuple[str, ...] = ('WECOM_',),
|
||||
*,
|
||||
force: bool = False,
|
||||
) -> dict[str, object]:
|
||||
"""
|
||||
从权威存储加载设置并应用到 ``os.environ``。
|
||||
|
||||
核心逻辑:DB 优先于 env 文件;进程内按 TTL 复用上次完整加载结果,减轻 before_request 查库压力。
|
||||
force=True 或 TTL=0 时始终重载。
|
||||
|
||||
Args:
|
||||
prefixes: 仅加载匹配此前缀的配置键,默认 WECOM_。
|
||||
force: 为 True 时忽略 TTL 强制读库。
|
||||
|
||||
Returns:
|
||||
解析后的配置字典(bool 键已转为 bool)。
|
||||
"""
|
||||
ttl = _refresh_ttl_seconds()
|
||||
now = time.monotonic()
|
||||
with _cache_lock:
|
||||
if (
|
||||
not force
|
||||
and ttl > 0
|
||||
and _cache_prefixes == prefixes
|
||||
and _cache_applied
|
||||
and (now - _cache_loaded_at) < ttl
|
||||
):
|
||||
applied = dict(_cache_applied)
|
||||
else:
|
||||
applied = None
|
||||
|
||||
if applied is not None:
|
||||
for key, parsed in applied.items():
|
||||
os.environ[key] = _to_env_string(parsed)
|
||||
return applied
|
||||
|
||||
# [STEP] 锁外读库/读文件,缩短临界区
|
||||
file_values = _load_from_env_file(prefixes)
|
||||
db_values = _load_from_db(prefixes)
|
||||
|
||||
merged: dict[str, str] = {**file_values, **db_values}
|
||||
|
||||
applied: dict[str, object] = {}
|
||||
applied = {}
|
||||
for key, raw_value in merged.items():
|
||||
parsed = _parse_env_value(key, raw_value)
|
||||
os.environ[key] = _to_env_string(parsed)
|
||||
applied[key] = parsed
|
||||
return applied
|
||||
|
||||
with _cache_lock:
|
||||
_store_cache(prefixes, applied)
|
||||
return dict(applied)
|
||||
@@ -101,6 +101,8 @@ class Config:
|
||||
ENV_NAME = ACTIVE_ENV_NAME
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
SECRET_KEY = os.getenv('SECRET_KEY')
|
||||
# 运行时可编辑配置(app_settings)进程内热更新间隔(秒);0=每请求强制读库
|
||||
APP_SETTINGS_REFRESH_SECONDS = float(os.getenv('APP_SETTINGS_REFRESH_SECONDS', '30') or '30')
|
||||
# 配置最大上传文件大小(200MB)
|
||||
MAX_CONTENT_LENGTH = 200 * 1024 * 1024
|
||||
KB_STORAGE_ROOT = _data_path('KB_STORAGE_ROOT', 'kb')
|
||||
@@ -289,10 +291,17 @@ class Config:
|
||||
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS = int(
|
||||
os.getenv('IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS', '600') or '600'
|
||||
)
|
||||
# 行库存查得时刻(inventory_checked_at)的 stale 徽标判定窗口(纯展示阈值)。
|
||||
IN_TRANSIT_TRANSFER_INVENTORY_STALE_TTL_SECONDS = int(
|
||||
os.getenv('IN_TRANSIT_TRANSFER_INVENTORY_STALE_TTL_SECONDS', '86400') or '86400'
|
||||
)
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS', '3') or '3')
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS', '5') or '5')
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS = int(os.getenv('IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS', '7') or '7')
|
||||
IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET = os.getenv('IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET', 'hxops-transfer').strip()
|
||||
IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS = int(
|
||||
os.getenv('IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS', '2') or '2'
|
||||
)
|
||||
SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float(
|
||||
os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '420')
|
||||
)
|
||||
@@ -463,6 +472,9 @@ class Config:
|
||||
FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_INVENTORY_ARCHIVE_DIR', 'freight_rpa', 'inventory', 'archives'
|
||||
)
|
||||
FREIGHT_RPA_RECEIPT_ARCHIVE_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_RECEIPT_ARCHIVE_DIR', 'freight_rpa', 'receipt', 'archives'
|
||||
)
|
||||
FREIGHT_RPA_WORKER_MOCK = os.getenv('FREIGHT_RPA_WORKER_MOCK', 'false')
|
||||
|
||||
# WeCom (企业微信) 登录配置
|
||||
@@ -487,7 +499,7 @@ class Config:
|
||||
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
|
||||
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning,equipment_acceptance_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,order_delivery_reply_notify,training_lean_video_push,training_overseas_thailand_guidelines')
|
||||
# 精益培训企微提醒卡片跳转的员工培训聊天页 agent id(前端路由 /chat/<id>)。
|
||||
# 缺省 0 = 不显式指定,由后端按 handler_config.content_profile='training' 动态解析各环境的培训 Agent
|
||||
# (测试/正式环境 Agent ID 不同,动态解析保证卡片均可定位「员工培训-精益管理」);
|
||||
@@ -541,6 +553,13 @@ class Config:
|
||||
SCHEDULE_WORKER_ENABLED = os.getenv('SCHEDULE_WORKER_ENABLED', 'true').lower() == 'true'
|
||||
SCHEDULE_WORKER_POLL_SECONDS = float(os.getenv('SCHEDULE_WORKER_POLL_SECONDS', '30') or '30')
|
||||
SCHEDULE_JOB_RUNNING_TIMEOUT_SECONDS = float(os.getenv('SCHEDULE_JOB_RUNNING_TIMEOUT_SECONDS', '7200') or '7200')
|
||||
# Web 进程内排程兜底扫描:仅本地开发(ENV_NAME=dev,无 schedule-worker 容器)默认开启;
|
||||
# test/prod 由 hxops-schedule-worker 容器负责(run.py 固定走 DevelopmentConfig,不能按配置类判定)。
|
||||
_scanner_env_raw = str(os.getenv('SCHEDULE_WEB_SCANNER_ENABLED') or '').strip().lower()
|
||||
if _scanner_env_raw:
|
||||
SCHEDULE_WEB_SCANNER_ENABLED = _scanner_env_raw in ('1', 'true', 'yes', 'on')
|
||||
else:
|
||||
SCHEDULE_WEB_SCANNER_ENABLED = _normalize_env_name(os.getenv('ENV_NAME') or ACTIVE_ENV_NAME) == 'dev'
|
||||
# Cron 表达式按此时区解读(如 0 12 * * * 表示该时区 12:00);入库 next_run_at 仍为 UTC。
|
||||
SCHEDULE_TIMEZONE = (os.getenv('SCHEDULE_TIMEZONE') or 'Asia/Shanghai').strip()
|
||||
SRM_SQLSERVER_HOST = os.getenv('SRM_SQLSERVER_HOST', '')
|
||||
@@ -761,9 +780,12 @@ class TestingConfig(Config):
|
||||
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
|
||||
# 钉住测试 TTL 语义(陈旧行门禁用例按 600s 书写),不随开发者 .env.shared 漂移。
|
||||
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS = 600
|
||||
# 库存查得时刻 stale 阈值钉 24h(stale 用例按 86400s 书写)。
|
||||
IN_TRANSIT_TRANSFER_INVENTORY_STALE_TTL_SECONDS = 86400
|
||||
WTF_CSRF_ENABLED = False
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {}
|
||||
SCHEDULE_WORKER_ENABLED = False
|
||||
SCHEDULE_WEB_SCANNER_ENABLED = False
|
||||
FIXED_ASSETS_SYNC_ENABLED = False
|
||||
FIXED_ASSETS_EXPORT_TO_DOCS = False
|
||||
ENV_NAME = 'dev'
|
||||
|
||||
@@ -47,7 +47,7 @@ def _resolve_request_agent_id() -> str | None:
|
||||
def require_agent_permission(f):
|
||||
"""
|
||||
装饰器:校验当前用户是否拥有指定 Agent 访问权限。
|
||||
核心逻辑:从 body/query/form 读 agent_id → 获取用户 → admin 放行或检查 user.agents。
|
||||
核心逻辑:从 body/query/form 读 agent_id → 获取用户 → 平台管理员放行或检查 user.agents。
|
||||
Args:
|
||||
f: 被装饰的视图函数。
|
||||
Returns:
|
||||
@@ -66,7 +66,7 @@ def require_agent_permission(f):
|
||||
if not agent:
|
||||
raise NotFoundError('Agent not found')
|
||||
g.current_agent = agent
|
||||
if user.role == 'admin':
|
||||
if user.is_platform_admin():
|
||||
return f(*args, **kwargs)
|
||||
if agent not in user.agents:
|
||||
raise ForbiddenError('Permission denied for this agent')
|
||||
@@ -77,8 +77,8 @@ def require_agent_permission(f):
|
||||
|
||||
def require_admin(f):
|
||||
"""
|
||||
装饰器:限制仅 admin 角色可访问。
|
||||
核心逻辑:解析用户 → 校验 role == admin;JWT 必填时检查 Authorization 头。
|
||||
装饰器:限制仅平台管理员可访问。
|
||||
核心逻辑:解析用户 → 校验 is_platform_admin;JWT 必填时检查 Authorization 头。
|
||||
"""
|
||||
|
||||
@wraps(f)
|
||||
@@ -88,7 +88,7 @@ def require_admin(f):
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
if bool(current_app.config.get('AUTH_JWT_REQUIRED', False)) and (not request.headers.get('Authorization')):
|
||||
raise UnauthorizedError('JWT token is required')
|
||||
if user.role != 'admin':
|
||||
if not user.is_platform_admin():
|
||||
raise ForbiddenError('Admin privilege required')
|
||||
return f(*args, **kwargs)
|
||||
|
||||
|
||||
@@ -724,6 +724,58 @@ def _handoff_continue_order_extraction(
|
||||
return True
|
||||
|
||||
|
||||
def _emit_reservation_heuristic_audit(
|
||||
*,
|
||||
run: Any,
|
||||
merged_by_unit_id: dict[int, list[dict[str, Any]]],
|
||||
) -> None:
|
||||
"""
|
||||
合并末段「裸数字预约单号兜底」落地后补审计事件,供上线后观察误判率。
|
||||
|
||||
【AI 触发时机】:EML 补充合并(merge_email_supplements)完成后调用。
|
||||
只读订单上的 _hxops_reservation_heuristic 标记,不修改订单;命中与多候选
|
||||
各发一条事件,metadata 携带 unit/候选值/正文文档定位,便于按 Case 回溯证据。
|
||||
|
||||
Args:
|
||||
run: 当前订单抽取 Run(审计聚合根)。
|
||||
merged_by_unit_id: 本趟合并产物 {unit_id: [order]}。
|
||||
"""
|
||||
applied_entries: list[dict[str, Any]] = []
|
||||
ambiguous_entries: list[dict[str, Any]] = []
|
||||
for unit_id, orders in (merged_by_unit_id or {}).items():
|
||||
for order in orders or []:
|
||||
marker = order.get('_hxops_reservation_heuristic') if isinstance(order, dict) else None
|
||||
if not isinstance(marker, dict):
|
||||
continue
|
||||
entry = {
|
||||
'unit_id': int(unit_id),
|
||||
'values': marker.get('values') or [],
|
||||
'document_id': marker.get('document_id'),
|
||||
}
|
||||
if marker.get('status') == 'applied':
|
||||
applied_entries.append({**entry, 'value': marker.get('value')})
|
||||
else:
|
||||
ambiguous_entries.append(entry)
|
||||
for event_type, entries in (
|
||||
('reservation_heuristic_applied', applied_entries),
|
||||
('reservation_heuristic_ambiguous', ambiguous_entries),
|
||||
):
|
||||
if not entries:
|
||||
continue
|
||||
append_shipping_audit_event(
|
||||
event_type=event_type,
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id=str(run.id),
|
||||
run_no=run.run_no,
|
||||
actor_type='system',
|
||||
source='shipping_order_extraction',
|
||||
metadata={
|
||||
'entries': entries,
|
||||
'decision_rule_version': 'bare-numeric-reservation-v1',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _is_transient_lock_error(exc: BaseException) -> bool:
|
||||
"""
|
||||
判断异常是否为瞬时锁冲突(PostgreSQL 死锁 40P01 / 锁等待超时 55P03)。
|
||||
@@ -1139,6 +1191,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
},
|
||||
)
|
||||
_merge_group_orders(eml_units, apply_email_supplements=True)
|
||||
_emit_reservation_heuristic_audit(run=run, merged_by_unit_id=merged_by_unit_id)
|
||||
append_shipping_audit_event(
|
||||
event_type='ORDER_EMAIL_ADJUDICATION_COMPLETED',
|
||||
aggregate_type='order_extraction_run',
|
||||
|
||||
@@ -2,12 +2,13 @@
|
||||
backend/app/models/__init__.py
|
||||
|
||||
用途:按业务域拆分的 ORM 模型包入口;聚合导出以保持 `from app.models import User` 兼容。
|
||||
依赖:models/* 子模块(含 voucher_check)、app.extensions.db(经 base.Base)。
|
||||
依赖:models/* 子模块(含 voucher_check、equipment_acceptance)、app.extensions.db(经 base.Base)。
|
||||
逻辑:Alembic / Flask-Migrate 通过本模块 import 注册全部表元数据;业务代码继续从此处导入模型类。
|
||||
"""
|
||||
|
||||
from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest
|
||||
from app.models.base import Base, user_agent_permissions
|
||||
from app.models.permission_role import PermissionRole, permission_role_agents
|
||||
from app.models.chat import ChatLog, ChatSession, ChatToolRun, Feedback, GeneralFeedback
|
||||
from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlLanguage
|
||||
from app.models.department import Department
|
||||
@@ -237,11 +238,28 @@ from app.models.contract_payment import (
|
||||
ContractPaymentSyncState,
|
||||
ContractPaymentVendorRequest,
|
||||
)
|
||||
from app.models.equipment_acceptance import (
|
||||
EquipmentAcceptanceNode,
|
||||
EquipmentAcceptanceOperator,
|
||||
EquipmentAcceptanceOrder,
|
||||
EquipmentAcceptanceSendFile,
|
||||
EquipmentAcceptanceSendRecord,
|
||||
EquipmentAcceptanceSetting,
|
||||
)
|
||||
from app.models.order_delivery_reply import (
|
||||
OrderDeliveryAuditEvent,
|
||||
OrderDeliveryBatch,
|
||||
OrderDeliveryErpLine,
|
||||
OrderDeliveryLineState,
|
||||
OrderDeliverySyncRun,
|
||||
)
|
||||
from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit
|
||||
|
||||
__all__ = [
|
||||
'Base',
|
||||
'user_agent_permissions',
|
||||
'permission_role_agents',
|
||||
'PermissionRole',
|
||||
'ZlLanguage',
|
||||
'Department',
|
||||
'UserHomepageConfig',
|
||||
@@ -424,6 +442,12 @@ __all__ = [
|
||||
'ContractPaymentAlert',
|
||||
'ContractPaymentAlertBatch',
|
||||
'ContractPaymentSyncState',
|
||||
'EquipmentAcceptanceOrder',
|
||||
'EquipmentAcceptanceNode',
|
||||
'EquipmentAcceptanceOperator',
|
||||
'EquipmentAcceptanceSetting',
|
||||
'EquipmentAcceptanceSendFile',
|
||||
'EquipmentAcceptanceSendRecord',
|
||||
'TransferRun',
|
||||
'TransferSourceJob',
|
||||
'TransferMatching',
|
||||
@@ -437,4 +461,9 @@ __all__ = [
|
||||
'IntegrationInterfaceDefinition',
|
||||
'IntegrationBinding',
|
||||
'IntegrationCall',
|
||||
'OrderDeliveryErpLine',
|
||||
'OrderDeliveryBatch',
|
||||
'OrderDeliveryLineState',
|
||||
'OrderDeliveryAuditEvent',
|
||||
'OrderDeliverySyncRun',
|
||||
]
|
||||
@@ -130,4 +130,8 @@ class GeneralFeedback(Base):
|
||||
feedback_module: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
content: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
source_page: Mapped[Optional[str]] = mapped_column(String(32))
|
||||
# 处理状态:pending=待处理,closed=已关闭(数据分析卡片用;默认待处理)
|
||||
status: Mapped[str] = mapped_column(String(20), default='pending', nullable=False, index=True)
|
||||
# 关闭时间:记录何时被处理/关闭,用于「本月已关闭」统计
|
||||
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
@@ -0,0 +1,181 @@
|
||||
"""
|
||||
backend/app/models/equipment_acceptance.py
|
||||
|
||||
用途:设备验收预警的本地同步快照和可改配置。
|
||||
依赖:models.base.Base、users。
|
||||
逻辑:同步服务按流程实例 request_id upsert 主表,并整批替换当前节点和操作人子表。
|
||||
配置表存四档天数、第 4 轮是否启用,以及三个固定岗位的系统用户。发送时刻不在这张表。
|
||||
发送记录按验收单和档位留一行。已发送和已取消的姓名不回写;待发送每次扫描重算。
|
||||
发给每位收件人的 Excel 另存一行,并用 send_record_ids 挂回发送记录,供表格列下载。
|
||||
不保存流程编号、第二合同编号、验收日期和 isremark。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import JSON, BigInteger, Boolean, DateTime, ForeignKey, Index, LargeBinary, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class EquipmentAcceptanceOrder(Base):
|
||||
"""一张验收单的最近一次同步结果。流程实例 request_id 唯一。"""
|
||||
|
||||
__tablename__ = "equipment_acceptance_orders"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("request_id", name="uq_equipment_acceptance_orders_request_id"),
|
||||
Index("ix_equipment_acceptance_orders_status", "monitor_status"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
acceptance_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
purchase_order_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
contract_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
timer_started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
dwell_days: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
can_accept: Mapped[Optional[int]] = mapped_column(
|
||||
nullable=True,
|
||||
comment="是否可以正常验收。0 否,1 是。空表示未标明。由 OA sfkyzcys 翻转,OA 为 0 是、1 否。",
|
||||
)
|
||||
cannot_accept_note: Mapped[Optional[str]] = mapped_column(
|
||||
Text,
|
||||
nullable=True,
|
||||
comment="无法验收说明正文,来自 OA ft_gdzcysdv2.ycsm。只留痕,不单独触发停表。",
|
||||
)
|
||||
is_returned: Mapped[Optional[int]] = mapped_column(
|
||||
nullable=True,
|
||||
comment="是否退回。0 否,1 是。由 OA sfzfth 翻转,OA 为 0 是、1 否;OA 空值收成 0。",
|
||||
)
|
||||
flow_status_raw: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
request_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||
request_match_count: Mapped[int] = mapped_column(nullable=False, default=0)
|
||||
owner_oa_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
|
||||
owner_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
owner_job_num: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
equip_oa_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
|
||||
equip_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
equip_job_num: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
applicant_oa_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
|
||||
applicant_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
applicant_job_num: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
monitor_status: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||
present_in_source: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
|
||||
synced_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
|
||||
)
|
||||
|
||||
|
||||
class EquipmentAcceptanceNode(Base):
|
||||
"""同步时看到的当前节点。一条流程可以有多行。"""
|
||||
|
||||
__tablename__ = "equipment_acceptance_nodes"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("order_id", "node_id", name="uq_equipment_acceptance_nodes_order_node"),
|
||||
Index("ix_equipment_acceptance_nodes_order", "order_id"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
order_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("equipment_acceptance_orders.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
node_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||
node_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
node_type: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
|
||||
|
||||
class EquipmentAcceptanceOperator(Base):
|
||||
"""当前节点上的操作人。同一节点同一人只留一行。不保存 isremark。"""
|
||||
|
||||
__tablename__ = "equipment_acceptance_operators"
|
||||
__table_args__ = (
|
||||
Index("ix_equipment_acceptance_operators_order", "order_id"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
order_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("equipment_acceptance_orders.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
node_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||
user_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||
handler_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
handler_job_num: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
|
||||
|
||||
class EquipmentAcceptanceSetting(Base):
|
||||
"""预警配置。全表只使用 id=1 这一行。岗位存系统用户主键,姓名不入库。"""
|
||||
|
||||
__tablename__ = "equipment_acceptance_settings"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
day_1: Mapped[int] = mapped_column(nullable=False, default=30)
|
||||
day_2: Mapped[int] = mapped_column(nullable=False, default=37)
|
||||
day_3: Mapped[int] = mapped_column(nullable=False, default=44)
|
||||
day_4: Mapped[int] = mapped_column(nullable=False, default=51)
|
||||
round_4_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
buyer_manager_user_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
coo_user_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
executive_user_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
updated_by: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
|
||||
|
||||
class EquipmentAcceptanceSendRecord(Base):
|
||||
"""一张验收单某一档的发送记录。同一张单同一档只留一行。已发送后不改收件人。"""
|
||||
|
||||
__tablename__ = "equipment_acceptance_send_records"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("order_id", "tier", name="uq_equipment_acceptance_send_records_order_tier"),
|
||||
Index("ix_equipment_acceptance_send_records_created", "created_at"),
|
||||
Index("ix_equipment_acceptance_send_records_status", "status"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
order_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey("equipment_acceptance_orders.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
acceptance_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
purchase_order_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
tier: Mapped[int] = mapped_column(nullable=False)
|
||||
threshold_days: Mapped[int] = mapped_column(nullable=False)
|
||||
to_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
cc_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
recipients_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default="pending")
|
||||
sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
|
||||
|
||||
|
||||
class EquipmentAcceptanceSendFile(Base):
|
||||
"""一位收件人一次发送留下的 Excel。字节与当时发给企业微信的文件相同。"""
|
||||
|
||||
__tablename__ = "equipment_acceptance_send_files"
|
||||
__table_args__ = (
|
||||
Index("ix_equipment_acceptance_send_files_created", "created_at"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
recipient_user_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
recipient_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
excel_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
excel_file_data: Mapped[Optional[bytes]] = mapped_column(LargeBinary, nullable=True)
|
||||
excel_file_size: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
send_record_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default="sent")
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
|
||||
@@ -69,7 +69,8 @@ TRANSFER_DOCUMENT_STATUSES = (
|
||||
)
|
||||
# 未完结单状态集合(组锁生效范围,D7①/D15):同五元组存在任一未完结单时
|
||||
# 复用其 doc_no+submit_timestamp,禁止新建;部分唯一索引的 WHERE 子句由该
|
||||
# 元组生成,保证「常量集 ↔ DB 约束」永远一致(test_document_model.py 锁定)。
|
||||
# 元组生成,保证「常量集 ↔ DB 约束」永远一致(原锁定测试 test_document_model.py
|
||||
# 已删除,改动本元组时须人工核对迁移内 CHECK/WHERE 字面量同口径)。
|
||||
UNRESOLVED_DOC_STATUSES = (
|
||||
'pending', 'executing', 'result_unknown', 'business_failed', 'technical_failed',
|
||||
)
|
||||
@@ -262,6 +263,10 @@ class TransferInvoiceItem(Base):
|
||||
# 数量以 Decimal 文本保存,杜绝浮点误差;比较在服务层完成。
|
||||
receipt_quantity: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||
external_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
# [库存查得时刻] 当前 external_quantity 的 ERP 取数时间戳(stale 徽标判定时钟,
|
||||
# 2026-09-29 起与行新鲜度 updated_at 分离:证据同步换戳/存续不续期本字段,
|
||||
# 仅匹配评估/重查/写前复查在真实取数时写入;置空库存时同步置空)。NULL=无库存数据。
|
||||
inventory_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
result_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
result_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
"""
|
||||
backend/app/models/order_delivery_reply.py
|
||||
|
||||
用途:订单交期回复域模型,保存 ERP 订单行快照、交期批次、行级锁定状态、审计与同步运行记录。
|
||||
依赖:models.base.Base、users。
|
||||
逻辑:同步服务只写 erp_lines 的 ERP 快照列;保存回复只写 batches;通知成功路径才写
|
||||
line_states.locked;audit_events 记录保存/通知/锁定/同步;sync_runs 记录每次同步。
|
||||
工作台所有读取只打本地库,禁止回写 ERP。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Index, JSON, Numeric, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class OrderDeliveryErpLine(Base):
|
||||
"""ERP 销售订单行快照(订单单号+项次唯一);仅同步服务写入 ERP 列,不覆盖批次与锁定。"""
|
||||
|
||||
__tablename__ = "order_delivery_erp_lines"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("order_no", "line_no", name="uq_order_delivery_erp_lines_order_line"),
|
||||
Index("ix_order_delivery_erp_lines_order_date", "order_date"),
|
||||
Index("ix_order_delivery_erp_lines_customer_no", "customer_no"),
|
||||
Index("ix_order_delivery_erp_lines_salesperson", "salesperson_code"),
|
||||
Index("ix_order_delivery_erp_lines_slip_code", "slip_code"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
order_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
line_no: Mapped[int] = mapped_column(nullable=False)
|
||||
order_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
customer_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
customer_short_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
customer_full_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
# salesperson_code 对 HXOPS User.employee_id,供企微收件人映射;列表展示 salesperson_name。
|
||||
salesperson_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
salesperson_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
dept_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
dept_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
customer_po: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
part_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
part_name: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
|
||||
spec: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
|
||||
customer_part_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
agreed_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
qty: Mapped[Optional[Decimal]] = mapped_column(Numeric(18, 4), nullable=True)
|
||||
delivered_qty: Mapped[Optional[Decimal]] = mapped_column(Numeric(18, 4), nullable=True)
|
||||
# 单别取 oea01 连字符前段(8301-1605280014 → 8301);一期只落库预留,不展示不过滤。
|
||||
slip_code: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
# 本轮同步未命中但已有批次或锁定的行不删除,置 true 后默认列表不展示。
|
||||
erp_missing: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False, index=True)
|
||||
last_synced_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class OrderDeliveryBatch(Base):
|
||||
"""订单行的交期批次(计划交期+数量+备注);未锁定行保存时整表替换。仅保存回复路径写入。"""
|
||||
|
||||
__tablename__ = "order_delivery_batches"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("line_id", "seq", name="uq_order_delivery_batches_line_seq"),
|
||||
Index("ix_order_delivery_batches_line", "line_id"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
line_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("order_delivery_erp_lines.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
seq: Mapped[int] = mapped_column(nullable=False)
|
||||
planned_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||
qty: Mapped[Decimal] = mapped_column(Numeric(18, 4), nullable=False)
|
||||
# 备注 ≤ 200 字符,由 API 层校验。
|
||||
remark: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class OrderDeliveryLineState(Base):
|
||||
"""订单行锁定状态(一行一态);仅通知成功路径写入 locked=true,与通知同一事务。"""
|
||||
|
||||
__tablename__ = "order_delivery_line_states"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("line_id", name="uq_order_delivery_line_states_line"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
line_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("order_delivery_erp_lines.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
locked: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
# 交期回复人员 = 最近一次发送成功的生管;存快照工号+姓名便于审计回溯。
|
||||
notified_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
||||
notified_employee_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
notified_user_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
notified_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class OrderDeliveryAuditEvent(Base):
|
||||
"""订单交期回复审计:保存批次、发送通知、锁定、同步、出货提醒、未回复提醒六类动作。"""
|
||||
|
||||
__tablename__ = "order_delivery_audit_events"
|
||||
__table_args__ = (
|
||||
Index("ix_order_delivery_audit_events_line", "line_id"),
|
||||
Index("ix_order_delivery_audit_events_action", "action", "created_at"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
# sync 事件无具体行时 line_id 为空。
|
||||
line_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey("order_delivery_erp_lines.id", ondelete="CASCADE"), nullable=True
|
||||
)
|
||||
order_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
line_no: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
# save | notify | lock | sync | ship_remind(出货提醒,payload.ok=true 参与去重)| unreplied_remind(未回复再提醒)
|
||||
action: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
operator_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
||||
payload_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class OrderDeliverySyncRun(Base):
|
||||
"""订单交期同步运行记录;同步作业每次运行写一行,失败保留上次快照。"""
|
||||
|
||||
__tablename__ = "order_delivery_sync_runs"
|
||||
__table_args__ = (
|
||||
Index("ix_order_delivery_sync_runs_started", "started_at"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
trigger: Mapped[str] = mapped_column(String(16), nullable=False) # scheduled | manual
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False) # running | success | failed
|
||||
started_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
line_count: Mapped[int] = mapped_column(default=0, nullable=False)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
@@ -0,0 +1,53 @@
|
||||
"""
|
||||
models/permission_role.py
|
||||
|
||||
用途:可配置权限组(角色包)及角色与 Agent 的授权关系。
|
||||
依赖:models.base.Base、agents / 无直接 User FK(成员仍写在 users.role)。
|
||||
逻辑:Admin 角色配置读写本表;运行时按 users.role=code 取包,再同步到 user_agent_permissions。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, JSON, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.extensions import db
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
permission_role_agents = db.Table(
|
||||
'permission_role_agents',
|
||||
db.Column('role_id', ForeignKey('permission_roles.id', ondelete='CASCADE'), primary_key=True),
|
||||
db.Column('agent_id', ForeignKey('agents.id', ondelete='CASCADE'), primary_key=True),
|
||||
)
|
||||
|
||||
|
||||
class PermissionRole(Base):
|
||||
"""权限组:可用应用入口 + 应用内能力。"""
|
||||
|
||||
__tablename__ = 'permission_roles'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('code', name='uq_permission_roles_code'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
code: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
||||
name: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
is_default: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
is_system: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
is_platform_admin: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
feature_permissions: Mapped[dict] = mapped_column(JSON, default=dict, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
|
||||
agents: Mapped[List['Agent']] = relationship(
|
||||
'Agent',
|
||||
secondary=permission_role_agents,
|
||||
)
|
||||
@@ -30,8 +30,9 @@ class ShippingDocumentProfileAutoFreezeQualification(Base):
|
||||
"status IN ('manual_confirmation', 'auto_freeze_approved', 'auto_freeze_suspended')",
|
||||
name='ck_shipping_document_profile_auto_freeze_qualification_status',
|
||||
),
|
||||
# 索引名沿用迁移 0aa34b5c6d7e 的短名;PostgreSQL 标识符上限 63 字符,超长名会导致建库失败。
|
||||
Index(
|
||||
'ix_shipping_document_profile_auto_freeze_qualification_profile_status',
|
||||
'ix_ship_doc_prof_auto_freeze_profile_status',
|
||||
'profile_id', 'status',
|
||||
),
|
||||
)
|
||||
|
||||
@@ -104,6 +104,9 @@ class ShippingNoticeLineInventoryMatch(Base):
|
||||
required_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
shortage_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
# 料号维度总可用量(忽略预约号、行允许源内汇总);预约号不匹配行的放行兜底依据。
|
||||
# 历史行与无快照行为 NULL,前端显示占位符;重新匹配后回填。
|
||||
part_available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
|
||||
@@ -204,9 +204,10 @@ class ShippingOrderDocumentProfileSuggestionDecision(Base):
|
||||
|
||||
__tablename__ = 'shipping_order_document_profile_suggestion_decisions'
|
||||
__table_args__ = (
|
||||
CheckConstraint("decision IN ('accepted', 'accepted_adjusted', 'rejected')", name='ck_shipping_order_document_profile_suggestion_decisions_decision'),
|
||||
UniqueConstraint('profile_id', 'suggestion_id', name='uq_shipping_order_document_profile_suggestion_decisions_suggestion'),
|
||||
Index('ix_shipping_order_document_profile_suggestion_decisions_profile_revision', 'profile_id', 'revision_no'),
|
||||
# 约束/索引名沿用迁移的短名;PostgreSQL 标识符上限 63 字符,超长名会导致建库失败。
|
||||
CheckConstraint("decision IN ('accepted', 'accepted_adjusted', 'rejected')", name='ck_order_profile_suggestion_decision'),
|
||||
UniqueConstraint('profile_id', 'suggestion_id', name='uq_order_profile_suggestion'),
|
||||
Index('ix_order_profile_suggestion_revision', 'profile_id', 'revision_no'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -238,8 +239,8 @@ class ShippingOrderDocumentProfileValidationRun(Base):
|
||||
name='ck_shipping_order_document_profile_validation_runs_type',
|
||||
),
|
||||
CheckConstraint("status IN ('pending', 'running', 'passed', 'failed')", name='ck_shipping_order_document_profile_validation_runs_status'),
|
||||
Index('ix_shipping_order_document_profile_validation_runs_profile_created', 'profile_id', 'created_at'),
|
||||
Index('ix_shipping_order_document_profile_validation_runs_checksum', 'profile_id', 'definition_checksum'),
|
||||
Index('ix_order_profile_validation_created', 'profile_id', 'created_at'),
|
||||
Index('ix_order_profile_validation_checksum', 'profile_id', 'definition_checksum'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -268,10 +269,10 @@ class ShippingOrderDocumentProfilePublishCheckReport(Base):
|
||||
|
||||
__tablename__ = 'shipping_order_document_profile_publish_check_reports'
|
||||
__table_args__ = (
|
||||
CheckConstraint("status IN ('valid', 'invalidated', 'consumed')", name='ck_shipping_order_document_profile_publish_check_reports_status'),
|
||||
UniqueConstraint('profile_id', 'operation_id', name='uq_shipping_order_document_profile_publish_check_reports_operation'),
|
||||
Index('ix_shipping_order_document_profile_publish_check_reports_profile_created', 'profile_id', 'created_at'),
|
||||
Index('ix_shipping_order_document_profile_publish_check_reports_report_no', 'report_no', unique=True),
|
||||
CheckConstraint("status IN ('valid', 'invalidated', 'consumed')", name='ck_sodppcr_status'),
|
||||
UniqueConstraint('profile_id', 'operation_id', name='uq_sodppcr_profile_operation'),
|
||||
Index('ix_sodppcr_profile_created', 'profile_id', 'created_at'),
|
||||
Index('ix_sodppcr_report_no', 'report_no', unique=True),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
|
||||
@@ -40,7 +40,7 @@ class ShippingReceiptReportConfig(Base):
|
||||
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(
|
||||
JSON, default=list, server_default=text("'[]'"), nullable=False,
|
||||
)
|
||||
# 与库存同构:Warehouse 是查询条件之一(支持多值),逐仓拆分在排程/触发时由该条件运行时派生,不单独持久化仓库清单。
|
||||
# 与库存同构:查询条件原样下发 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)
|
||||
@@ -116,6 +116,10 @@ class ShippingReceiptReportFile(Base):
|
||||
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)
|
||||
|
||||
+47
-16
@@ -2,8 +2,9 @@
|
||||
backend/app/models/user.py
|
||||
|
||||
用途:用户账户、首页偏好、登录审计相关模型。
|
||||
依赖:models.base(Base、user_agent_permissions)。
|
||||
逻辑:User 与 Agent 多对多经 user_agent_permissions;admin/user API 主要读写本模块。
|
||||
依赖:models.base(Base、user_agent_permissions);功能权限优先读 permission_roles。
|
||||
逻辑:User 与 Agent 多对多经 user_agent_permissions;角色包启用后个人 feature_permissions 仅作兼容覆盖。
|
||||
is_platform_admin() 读权限组标记,未种子时回退 role=admin。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -59,7 +60,7 @@ class User(Base):
|
||||
username: Mapped[str] = mapped_column(String(50), unique=True, index=True)
|
||||
email: Mapped[str] = mapped_column(String(100), unique=True)
|
||||
department: Mapped[Optional[str]] = mapped_column(String(100))
|
||||
role: Mapped[str] = mapped_column(String(20), default='user')
|
||||
role: Mapped[str] = mapped_column(String(64), default='user')
|
||||
status: Mapped[str] = mapped_column(String(20), default='active')
|
||||
feature_permissions: Mapped[dict] = mapped_column(JSON, default=dict, nullable=False)
|
||||
password_hash: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
@@ -85,27 +86,46 @@ class User(Base):
|
||||
)
|
||||
|
||||
def _role_default_feature_permissions(self) -> dict[str, bool]:
|
||||
"""返回当前角色自带的功能权限默认值。"""
|
||||
"""
|
||||
返回未配置权限组时的功能权限默认值。
|
||||
|
||||
核心逻辑:只认 is_platform_admin;不再用 hr / maintenance_manager 角色名暗示能力。
|
||||
"""
|
||||
admin = self.is_platform_admin()
|
||||
return {
|
||||
'training_hr_manage': self.role in {'admin', 'hr'},
|
||||
# 发货通知强制新建重复单据:admin 默认开;其他角色默认关,可显式授予
|
||||
'shipping_notice_force_create': self.role == 'admin',
|
||||
# 货代审计敏感快照/前后 Diff 读取:admin 默认开;不新建角色,可显式关闭或授予
|
||||
'shipping_notice.audit_sensitive_read': self.role == 'admin',
|
||||
# XFA 字段拆分:编辑 / 预览 / 发布审核;admin 默认开,可显式收紧
|
||||
'shipping_notice.xfa_split_rule_edit': self.role == 'admin',
|
||||
'shipping_notice.xfa_split_rule_preview': self.role == 'admin',
|
||||
'shipping_notice.xfa_split_rule_publish': self.role == 'admin',
|
||||
'training_hr_manage': admin,
|
||||
'shipping_notice_force_create': admin,
|
||||
'shipping_notice.audit_sensitive_read': admin,
|
||||
'shipping_notice.xfa_split_rule_edit': admin,
|
||||
'shipping_notice.xfa_split_rule_preview': admin,
|
||||
'shipping_notice.xfa_split_rule_publish': admin,
|
||||
'maintenance.ledger_write': admin,
|
||||
# 合同付款预警已改走 Agent 授权(agent_code=contract_payment),不再占用功能权限键。
|
||||
# 订单交期回复:manage=生管可写(保存/通知/同步),access=业务只读;
|
||||
# manage 命中视为有 access(判定见 api/order_delivery_reply.py)。
|
||||
'order_delivery_reply.manage': admin,
|
||||
'order_delivery_reply.access': admin,
|
||||
}
|
||||
|
||||
def is_platform_admin(self) -> bool:
|
||||
"""当前用户是否属于平台管理权限组。"""
|
||||
from app.services.permission_roles.service import user_is_platform_admin
|
||||
|
||||
return user_is_platform_admin(self)
|
||||
|
||||
def get_feature_permissions(self) -> dict[str, bool]:
|
||||
"""
|
||||
返回当前用户的有效功能权限。
|
||||
|
||||
用途:统一为前端展示、登录态注入与后端业务校验提供同一份权限结果。
|
||||
核心逻辑:先按角色生成默认权限,再用用户显式配置覆盖,避免把培训等业务权限硬编码在多个模块。
|
||||
输出约束:仅返回布尔型权限键,缺失项自动回退到角色默认值。
|
||||
核心逻辑:已配置 permission_roles 时完全由权限组计算;否则先按写死角色生成默认值,再用用户 JSON 覆盖。
|
||||
输出约束:仅返回布尔型权限键。
|
||||
"""
|
||||
from app.services.permission_roles.service import effective_feature_permissions
|
||||
|
||||
packaged = effective_feature_permissions(self)
|
||||
if packaged is not None:
|
||||
return packaged
|
||||
defaults = self._role_default_feature_permissions()
|
||||
raw = self.feature_permissions if isinstance(self.feature_permissions, dict) else {}
|
||||
result: dict[str, bool] = {}
|
||||
@@ -121,7 +141,7 @@ class User(Base):
|
||||
保存用户显式配置的功能权限覆盖项。
|
||||
|
||||
用途:给管理后台用户编辑表单落库权限配置。
|
||||
核心逻辑:只持久化与角色默认值不同的权限,既保留“admin/hr 角色默认可见”的现有语义,也支持前端手动关闭或给普通用户单独授予。合同付款预警改走 Agent 授权,不再占用功能权限键。
|
||||
核心逻辑:只持久化与默认值不同的权限。未种子权限组时默认仅平台管理员全开;其余角色靠 JSON 覆盖或权限组能力键。合同付款预警改走 Agent 授权,不再占用功能权限键。
|
||||
参数约束:permissions 必须为 dict 或 None;未知键会被忽略。
|
||||
"""
|
||||
defaults = self._role_default_feature_permissions()
|
||||
@@ -143,6 +163,17 @@ class User(Base):
|
||||
"""判断当前用户是否可使用培训 HR 管理面板与接口。"""
|
||||
return self.has_feature_permission('training_hr_manage')
|
||||
|
||||
def client_auth_fields(self) -> dict:
|
||||
"""登录态/首页共用的角色与功能权限字段。"""
|
||||
from app.services.permission_roles.service import list_role_name_map
|
||||
|
||||
names = list_role_name_map()
|
||||
return {
|
||||
'is_platform_admin': self.is_platform_admin(),
|
||||
'role_name': names.get(self.role) or self.role,
|
||||
'feature_permissions': self.get_feature_permissions(),
|
||||
}
|
||||
|
||||
def set_password(self, password: str) -> None:
|
||||
"""设置密码哈希。"""
|
||||
self.password_hash = generate_password_hash(password)
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
backend/app/services/admin/agent_service.py
|
||||
|
||||
用途:管理端 Agent CRUD、连通性测试、用户权限绑定。
|
||||
依赖:models、DifyService、agent_registry.admin_payload、agent_registry.serialization。
|
||||
依赖:models、DifyService、agent_registry.admin_payload、agent_registry.serialization、permission_roles。
|
||||
逻辑:由 api/admin/agents.py 调用;创建/更新写入 Registry 结构化列并清理 extra 已迁移键。
|
||||
权限组启用后 update_agent_permissions 拒绝按人改授权。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -15,7 +16,13 @@ import requests
|
||||
from app import db
|
||||
from app.core.config.settings import Config
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import Agent, User
|
||||
from app.models import (
|
||||
Agent, AgentDirectoryMember, ChatLog, ChatSession, ChatToolRun,
|
||||
ContractReview, FaqHotCandidate, Feedback, GeneralFeedback,
|
||||
PermissionRequest, QuickQuestion, ScheduleTask, User,
|
||||
UserDefaultAgent, UserFavoriteAgent, user_agent_permissions,
|
||||
)
|
||||
from sqlalchemy import delete, select, update
|
||||
from app.services.agent_directory import normalize_directory_member_ids, replace_directory_members
|
||||
from app.services.admin.training_exam_pdf_service import parse_training_question_bank_from_guide
|
||||
from app.services.agent_registry.admin_payload import apply_agent_payload, validate_agent_payload
|
||||
@@ -112,11 +119,40 @@ def update_agent(agent_id: int, data: dict[str, Any]) -> None:
|
||||
|
||||
|
||||
def delete_agent(agent_id: int) -> None:
|
||||
"""删除 Agent(不存在时静默成功)。"""
|
||||
"""
|
||||
删除 Agent 及其数据库引用,避免 chat_logs 外键导致管理端删除失败。
|
||||
|
||||
[STEP 1] 清理权限、目录、收藏、默认入口及业务直接引用。
|
||||
[STEP 2] 先清理 chat_log 子表,再删除会话日志。
|
||||
[STEP 3] 最后删除 Agent,整段操作使用当前事务保证原子性。
|
||||
"""
|
||||
agent = db.session.get(Agent, agent_id)
|
||||
if agent:
|
||||
db.session.delete(agent)
|
||||
db.session.commit()
|
||||
if not agent:
|
||||
return
|
||||
chat_log_ids = select(ChatLog.id).where(ChatLog.agent_id == agent_id)
|
||||
db.session.execute(delete(user_agent_permissions).where(user_agent_permissions.c.agent_id == agent_id))
|
||||
db.session.execute(delete(AgentDirectoryMember).where(
|
||||
(AgentDirectoryMember.directory_agent_id == agent_id)
|
||||
| (AgentDirectoryMember.member_agent_id == agent_id)
|
||||
))
|
||||
db.session.execute(delete(UserFavoriteAgent).where(UserFavoriteAgent.agent_id == agent_id))
|
||||
db.session.execute(delete(UserDefaultAgent).where(UserDefaultAgent.agent_id == agent_id))
|
||||
db.session.execute(update(User).where(User.default_agent_id == agent_id).values(default_agent_id=None))
|
||||
db.session.execute(update(ScheduleTask).where(ScheduleTask.dify_agent_id == agent_id).values(dify_agent_id=None))
|
||||
db.session.execute(delete(PermissionRequest).where(PermissionRequest.agent_id == agent_id))
|
||||
db.session.execute(delete(ContractReview).where(ContractReview.agent_id == agent_id))
|
||||
db.session.execute(delete(QuickQuestion).where(QuickQuestion.agent_id == agent_id))
|
||||
db.session.execute(delete(FaqHotCandidate).where(FaqHotCandidate.agent_id == agent_id))
|
||||
db.session.execute(delete(ChatSession).where(ChatSession.agent_id == agent_id))
|
||||
db.session.execute(delete(ChatToolRun).where(
|
||||
(ChatToolRun.agent_id == agent_id) | ChatToolRun.chat_log_id.in_(chat_log_ids)
|
||||
))
|
||||
db.session.execute(delete(Feedback).where(Feedback.chat_log_id.in_(chat_log_ids)))
|
||||
db.session.execute(delete(GeneralFeedback).where(GeneralFeedback.chat_log_id.in_(chat_log_ids)))
|
||||
db.session.execute(delete(ContractReview).where(ContractReview.chat_log_id.in_(chat_log_ids)))
|
||||
db.session.execute(delete(ChatLog).where(ChatLog.agent_id == agent_id))
|
||||
db.session.delete(agent)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def test_agent_connectivity(agent_id: int) -> dict[str, Any]:
|
||||
@@ -170,68 +206,65 @@ def _test_iframe_agent(agent: Agent, tested_at: str) -> dict[str, Any]:
|
||||
|
||||
|
||||
def _test_dify_agent(agent: Agent, tested_at: str) -> dict[str, Any]:
|
||||
"""
|
||||
Test Dify endpoint reachability without executing the configured application flow.
|
||||
|
||||
The test calls Dify's read-only ``/v1/parameters`` endpoint so a business
|
||||
Chatflow/Workflow never receives synthetic text such as ``OK`` that could be
|
||||
passed into a database or other external tool.
|
||||
"""
|
||||
if not agent.dify_api_key:
|
||||
return {
|
||||
'passed': False,
|
||||
'request_url': '',
|
||||
'output_info': 'Missing dify_api_key.',
|
||||
'analysis': '测试失败:未配置 API Key。',
|
||||
'analysis': '\u6d4b\u8bd5\u5931\u8d25\uff1a\u672a\u914d\u7f6e API Key\u3002',
|
||||
'http_status': 0,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
|
||||
base_url = (agent.api_base_url or Config.DIFY_API_BASE or '').rstrip('/')
|
||||
if not base_url:
|
||||
return {
|
||||
'passed': False,
|
||||
'request_url': '',
|
||||
'output_info': 'Missing api_base_url.',
|
||||
'analysis': '测试失败:未配置 API Base URL。',
|
||||
'analysis': '\u6d4b\u8bd5\u5931\u8d25\uff1a\u672a\u914d\u7f6e API Base URL\u3002',
|
||||
'http_status': 0,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
|
||||
dify_app_type = str(agent.dify_app_type or 'chatflow').strip().lower()
|
||||
if dify_app_type not in ('chatflow', 'workflow'):
|
||||
dify_app_type = 'chatflow'
|
||||
if dify_app_type == 'workflow':
|
||||
request_url = DifyService._build_workflow_url(base_url)
|
||||
payload = {
|
||||
'inputs': {'query': '系统连通性测试,请简短回复OK。'},
|
||||
'response_mode': 'blocking',
|
||||
'user': 'admin_test',
|
||||
}
|
||||
else:
|
||||
request_url = DifyService._build_chat_messages_url(base_url)
|
||||
payload = {
|
||||
'inputs': {},
|
||||
'query': '系统连通性测试,请简短回复OK。',
|
||||
'response_mode': 'blocking',
|
||||
'user': 'admin_test',
|
||||
}
|
||||
headers = {'Authorization': f'Bearer {agent.dify_api_key}', 'Content-Type': 'application/json'}
|
||||
|
||||
# [STEP 1] Read-only endpoint: never run a business Chatflow/Workflow in an admin connectivity test.
|
||||
request_url = DifyService._build_parameters_url(base_url)
|
||||
headers = {'Authorization': f'Bearer {agent.dify_api_key}'}
|
||||
try:
|
||||
resp = requests.post(request_url, headers=headers, json=payload, timeout=(5, 25))
|
||||
raw_text = (resp.text or '')[:4000]
|
||||
response = requests.get(request_url, headers=headers, timeout=(5, 15))
|
||||
raw_text = (response.text or '')[:4000]
|
||||
output_info = raw_text
|
||||
passed = False
|
||||
analysis = f'测试失败:HTTP {resp.status_code}。'
|
||||
if dify_app_type == 'workflow' and 200 <= resp.status_code < 300:
|
||||
if response.ok:
|
||||
passed = True
|
||||
analysis = '测试通过:Workflow 接口可访问且认证通过。'
|
||||
try:
|
||||
data = resp.json()
|
||||
if dify_app_type == 'workflow':
|
||||
passed, output_info, analysis = _parse_workflow_test_response(resp, data, output_info, analysis)
|
||||
else:
|
||||
passed, output_info, analysis = _parse_chatflow_test_response(resp, data, output_info, analysis, passed)
|
||||
except ValueError:
|
||||
if resp.ok and raw_text.strip():
|
||||
passed = True
|
||||
analysis = (
|
||||
'测试通过:Workflow 接口可访问并返回了文本内容。'
|
||||
if dify_app_type == 'workflow'
|
||||
else '测试通过:Chatflow 接口可访问并返回了文本内容。'
|
||||
)
|
||||
if passed and (not agent.is_active):
|
||||
analysis = '\u6d4b\u8bd5\u901a\u8fc7\uff1aDify \u53c2\u6570\u63a5\u53e3\u53ef\u8bbf\u95ee\u4e14 API Key \u8ba4\u8bc1\u901a\u8fc7\u3002'
|
||||
try:
|
||||
body = response.json()
|
||||
if isinstance(body, dict):
|
||||
output_info = str(body)[:4000]
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
passed = False
|
||||
analysis = f'\u6d4b\u8bd5\u5931\u8d25\uff1aHTTP {response.status_code}\u3002'
|
||||
try:
|
||||
body = response.json()
|
||||
if isinstance(body, dict) and body.get('message'):
|
||||
output_info = str(body['message'])[:4000]
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
if passed and not agent.is_active:
|
||||
agent.is_active = True
|
||||
db.session.commit()
|
||||
return {
|
||||
@@ -240,7 +273,7 @@ def _test_dify_agent(agent: Agent, tested_at: str) -> dict[str, Any]:
|
||||
'request_url': request_url,
|
||||
'output_info': output_info,
|
||||
'analysis': analysis,
|
||||
'http_status': resp.status_code,
|
||||
'http_status': response.status_code,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
except requests.RequestException as exc:
|
||||
@@ -249,12 +282,11 @@ def _test_dify_agent(agent: Agent, tested_at: str) -> dict[str, Any]:
|
||||
'dify_app_type': dify_app_type,
|
||||
'request_url': request_url,
|
||||
'output_info': str(exc),
|
||||
'analysis': '测试失败:请求异常(网络、超时或认证问题)。',
|
||||
'analysis': '\u6d4b\u8bd5\u5931\u8d25\uff1a\u8bf7\u6c42\u5f02\u5e38\uff08\u7f51\u7edc\u3001\u8d85\u65f6\u6216\u8ba4\u8bc1\u95ee\u9898\uff09\u3002',
|
||||
'http_status': 0,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
|
||||
|
||||
def _parse_workflow_test_response(resp, data, output_info: str, analysis: str) -> tuple[bool, str, str]:
|
||||
passed = 200 <= resp.status_code < 300
|
||||
workflow_data = data.get('data') if isinstance(data, dict) else None
|
||||
@@ -291,7 +323,13 @@ def _parse_chatflow_test_response(resp, data, output_info: str, analysis: str, p
|
||||
|
||||
|
||||
def update_agent_permissions(agent_id: int, user_ids: list[int]) -> None:
|
||||
"""将 Agent 的授权用户集合设为 user_ids(增量 add/remove)。"""
|
||||
"""
|
||||
将 Agent 的授权用户集合设为 user_ids(增量 add/remove)。
|
||||
权限组启用后禁止按人改应用,须改角色包或调整角色成员。
|
||||
"""
|
||||
from app.services.permission_roles.service import assert_direct_grants_allowed
|
||||
|
||||
assert_direct_grants_allowed()
|
||||
agent = db.session.get(Agent, agent_id)
|
||||
if not agent:
|
||||
raise NotFoundError('Not found')
|
||||
|
||||
@@ -10,7 +10,7 @@ from __future__ import annotations
|
||||
from sqlalchemy import func
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, ChatLog, Feedback, PermissionRequest, User
|
||||
from app.models import Agent, ChatLog, Feedback, User
|
||||
|
||||
|
||||
def compute_dashboard_summary() -> dict:
|
||||
@@ -32,29 +32,12 @@ def compute_dashboard_summary() -> dict:
|
||||
}
|
||||
|
||||
|
||||
def compute_dashboard_badges() -> dict:
|
||||
"""
|
||||
聚合侧栏角标所需的待办数量。
|
||||
Returns:
|
||||
pending_approvals、pending_requests。
|
||||
"""
|
||||
pending_approvals = db.session.query(func.count(User.id)).filter_by(status='pending').scalar() or 0
|
||||
pending_requests = db.session.query(func.count(PermissionRequest.id)).filter_by(status='pending').scalar() or 0
|
||||
return {
|
||||
'pending_approvals': pending_approvals,
|
||||
'pending_requests': pending_requests,
|
||||
}
|
||||
|
||||
|
||||
def compute_legacy_dashboard_stats() -> dict:
|
||||
"""遗留 /dashboard 接口响应(summary + badges 字段名兼容早期前端)。"""
|
||||
summary = compute_dashboard_summary()
|
||||
badges = compute_dashboard_badges()
|
||||
return {
|
||||
'total_users': summary['user_count'],
|
||||
'active_agents': summary['agent_count'],
|
||||
'total_conversations': summary['total_conversations'],
|
||||
'avg_score': summary['avg_score'],
|
||||
'pending_approvals': badges['pending_approvals'],
|
||||
'pending_requests': badges['pending_requests'],
|
||||
}
|
||||
@@ -19,7 +19,6 @@ from app.models import (
|
||||
ChatLog,
|
||||
Department,
|
||||
Feedback,
|
||||
PermissionRequest,
|
||||
QuickQuestion,
|
||||
User,
|
||||
UserDefaultAgent,
|
||||
@@ -33,7 +32,6 @@ ADMIN_TABLE_MODEL_MAP = {
|
||||
'agents': Agent,
|
||||
'chat_logs': ChatLog,
|
||||
'feedbacks': Feedback,
|
||||
'permission_requests': PermissionRequest,
|
||||
'departments': Department,
|
||||
'quick_questions': QuickQuestion,
|
||||
'user_homepage_configs': UserHomepageConfig,
|
||||
@@ -52,6 +50,35 @@ def _serialize_model_row(item) -> dict:
|
||||
return row
|
||||
|
||||
|
||||
def _apply_generic_table_filters(query, model, query_params: dict[str, str]):
|
||||
"""通用表筛选:created_at 时间范围(created_from/created_to)+ 各列 ILIKE/等值过滤。"""
|
||||
reserved = {'created_from', 'created_to'}
|
||||
# 时间范围(支持有 created_at 列的通用表,如 feedbacks 回答评价)
|
||||
created_from = (query_params.get('created_from') or '').strip()
|
||||
created_to = (query_params.get('created_to') or '').strip()
|
||||
if created_from and hasattr(model, 'created_at'):
|
||||
dt = report_service._parse_datetime(created_from, end_of_day=False)
|
||||
if dt:
|
||||
query = query.filter(model.created_at >= dt)
|
||||
if created_to and hasattr(model, 'created_at'):
|
||||
dt = report_service._parse_datetime(created_to, end_of_day=True)
|
||||
if dt:
|
||||
query = query.filter(model.created_at <= dt)
|
||||
|
||||
for key, value in query_params.items():
|
||||
if key in reserved or not value:
|
||||
continue
|
||||
if hasattr(model, key):
|
||||
col = getattr(model, key)
|
||||
col_type = getattr(col, 'type', None)
|
||||
# 整型外键(如 agent_id)用等值过滤,避免 ILIKE '%16%' 误匹配 160
|
||||
if value.isdigit() and col_type is not None and getattr(col_type, 'python_type', None) is int:
|
||||
query = query.filter(col == int(value))
|
||||
else:
|
||||
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
|
||||
return query
|
||||
|
||||
|
||||
def get_table_data(table: str, query_params: dict[str, str]) -> list[dict]:
|
||||
"""
|
||||
返回管理报表表数据(最多 100 行)。
|
||||
@@ -62,28 +89,20 @@ def get_table_data(table: str, query_params: dict[str, str]) -> list[dict]:
|
||||
model = ADMIN_TABLE_MODEL_MAP.get(table)
|
||||
if not model:
|
||||
raise ValidationError('Invalid table')
|
||||
query = db.session.query(model)
|
||||
for key, value in query_params.items():
|
||||
if hasattr(model, key) and value:
|
||||
col = getattr(model, key)
|
||||
col_type = getattr(col, 'type', None)
|
||||
# 整型外键(如 agent_id)用等值过滤,避免 ILIKE '%16%' 误匹配 160
|
||||
if value.isdigit() and col_type is not None and getattr(col_type, 'python_type', None) is int:
|
||||
query = query.filter(col == int(value))
|
||||
else:
|
||||
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
|
||||
query = _apply_generic_table_filters(db.session.query(model), model, query_params)
|
||||
items = query.limit(100).all()
|
||||
return [_serialize_model_row(item) for item in items]
|
||||
|
||||
|
||||
def get_table_count(table: str, query_params: dict[str, str]) -> dict:
|
||||
"""返回表行数;chat_logs 使用报表筛选。"""
|
||||
"""返回表行数(应用当前筛选);chat_logs 使用报表筛选。"""
|
||||
if table == 'chat_logs':
|
||||
return report_service.count_chat_logs_report(query_params)
|
||||
model = ADMIN_TABLE_MODEL_MAP.get(table)
|
||||
if not model:
|
||||
raise ValidationError('Invalid table')
|
||||
total = db.session.query(func.count(model.id)).scalar()
|
||||
query = _apply_generic_table_filters(db.session.query(model), model, query_params)
|
||||
total = query.count()
|
||||
return {'table': table, 'total': int(total or 0)}
|
||||
|
||||
|
||||
|
||||
@@ -9,9 +9,11 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import Department
|
||||
from app.models import Department, User
|
||||
|
||||
|
||||
def serialize_department(dept: Department) -> dict:
|
||||
@@ -27,8 +29,43 @@ def serialize_department(dept: Department) -> dict:
|
||||
|
||||
def list_departments() -> list[dict]:
|
||||
"""返回全部部门(按 name 升序)。"""
|
||||
depts = db.session.query(Department).order_by(Department.name.asc()).all()
|
||||
return [serialize_department(d) for d in depts]
|
||||
rows = (
|
||||
db.session.query(Department, func.count(User.id).label('member_count'))
|
||||
.outerjoin(User, User.department == Department.name)
|
||||
.group_by(Department.id)
|
||||
.order_by(Department.name.asc())
|
||||
.all()
|
||||
)
|
||||
return [{**serialize_department(dept), 'member_count': int(member_count or 0)} for dept, member_count in rows]
|
||||
|
||||
|
||||
def list_department_members(dept_id: int) -> dict:
|
||||
"""
|
||||
查询指定部门的员工名单。
|
||||
|
||||
[STEP 1] 通过部门主键读取部门名称。
|
||||
[STEP 2] 复用现有 users.department 文本关联查询成员。
|
||||
[STEP 3] 返回人数与脱敏后的管理端成员资料。
|
||||
"""
|
||||
dept = db.session.get(Department, dept_id)
|
||||
if not dept:
|
||||
raise NotFoundError('Not found')
|
||||
users = db.session.query(User).filter(User.department == dept.name).order_by(User.real_name.asc(), User.username.asc()).all()
|
||||
return {
|
||||
'department': serialize_department(dept),
|
||||
'count': len(users),
|
||||
'members': [
|
||||
{
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'real_name': user.real_name,
|
||||
'employee_id': user.employee_id,
|
||||
'email': user.email,
|
||||
'status': user.status,
|
||||
}
|
||||
for user in users
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def create_department(data: dict[str, Any]) -> dict:
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
backend/app/services/admin/permission_service.py
|
||||
|
||||
用途:用户 Agent 权限批量/单用户更新,以及权限申请审批业务逻辑。
|
||||
依赖:models、wecom_notify.send_wecom_event_message。
|
||||
逻辑:由 api/admin/permissions.py 调用;users 路由 /users/<id>/permissions 亦委托本模块。
|
||||
依赖:models.PermissionRequest、integrations.wecom.notify.send_wecom_event_message、permission_roles.service。
|
||||
逻辑:由 api/admin/permissions.py 调用;users 路由 /users/<id>/permissions 亦委托本模块。权限组启用后直接改应用会被拒绝。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -19,7 +19,15 @@ _BATCH_ACTION_LABELS = {'add': '新增', 'remove': '移除', 'set': '重置为'}
|
||||
|
||||
|
||||
def serialize_permission_request(req: PermissionRequest) -> dict:
|
||||
"""PermissionRequest ORM → 管理端列表 JSON。"""
|
||||
"""
|
||||
把权限申请记录转成管理端列表 JSON。
|
||||
|
||||
核心逻辑:只输出申请主键、用户、应用、理由、状态和创建时间。
|
||||
Args:
|
||||
req: 已落库的 PermissionRequest。
|
||||
Returns:
|
||||
可供列表接口直接返回的字典。
|
||||
"""
|
||||
return {
|
||||
'id': req.id,
|
||||
'user_id': req.user_id,
|
||||
@@ -68,11 +76,11 @@ def _notify_batch_permission_update(user: User, agents: list[Agent], action: str
|
||||
def batch_update_permissions(data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
批量更新多用户的 Agent 权限(add / remove / set)。
|
||||
Returns:
|
||||
{ status, updated_count }。
|
||||
Raises:
|
||||
ValidationError: 未选择用户。
|
||||
权限组启用后禁止按人改应用,须改角色包或调整角色成员。
|
||||
"""
|
||||
from app.services.permission_roles.service import assert_direct_grants_allowed
|
||||
|
||||
assert_direct_grants_allowed()
|
||||
user_ids = data.get('user_ids', [])
|
||||
agent_ids = data.get('agent_ids', [])
|
||||
action = data.get('action', 'add')
|
||||
@@ -95,11 +103,11 @@ def batch_update_permissions(data: dict[str, Any]) -> dict:
|
||||
def update_user_permissions(user_id: int, data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
将指定用户的 Agent 权限重置为 agent_ids 列表(全量替换)。
|
||||
Returns:
|
||||
{ status }。
|
||||
Raises:
|
||||
NotFoundError: 用户不存在。
|
||||
权限组启用后禁止按人改应用。
|
||||
"""
|
||||
from app.services.permission_roles.service import assert_direct_grants_allowed
|
||||
|
||||
assert_direct_grants_allowed()
|
||||
user = db.session.get(User, user_id)
|
||||
if not user:
|
||||
raise NotFoundError('Not found')
|
||||
@@ -123,9 +131,14 @@ def list_permission_requests() -> list[dict]:
|
||||
def approve_permission_request(request_id: int) -> dict:
|
||||
"""
|
||||
批准权限申请:更新状态并将 Agent 加入用户权限。
|
||||
权限组启用后禁止按人加应用,须改角色包或调整角色成员。
|
||||
Raises:
|
||||
NotFoundError: 申请不存在。
|
||||
ValidationError: 已启用角色包时禁止直接授权。
|
||||
"""
|
||||
from app.services.permission_roles.service import assert_direct_grants_allowed
|
||||
|
||||
assert_direct_grants_allowed()
|
||||
req = db.session.get(PermissionRequest, request_id)
|
||||
if not req:
|
||||
raise NotFoundError('Not found')
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -18,7 +18,6 @@ from app.models import (
|
||||
ShippingInventoryRoutingRuleVersion, ShippingInventorySource, ShippingRpaProfile, ScheduleRun, ScheduleTask, ShippingNotice,
|
||||
ShippingOrderField,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventoryConfigurationTestRun, ShippingInventoryStructureAnalysis,
|
||||
ShippingNoticeLine, ShippingNoticeLineInventoryMatch,
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventorySourceParsingBindingAudit,
|
||||
@@ -295,7 +294,11 @@ def _validate_movement_profile_binding(profile_id: Any) -> int | None:
|
||||
def _validate_receipt_report_config(
|
||||
source: ShippingInventorySource, data: dict[str, Any],
|
||||
) -> tuple[dict[str, str], list[dict[str, Any]]]:
|
||||
"""规范收料配置,与库存同构:路径+查询条件;日期禁填,DBS 以 Warehouse 条件为逐仓拆分维度。"""
|
||||
"""规范收料配置,与库存同构:路径+查询条件;日期禁填。
|
||||
|
||||
DBS 的 Warehouse 等查询条件均为可选报表筛选:空条件表示 Worker 使用页面默认;
|
||||
不作为排程是否产出执行单元的门禁(一源一单元)。
|
||||
"""
|
||||
try:
|
||||
parameters = _validate_query_parameters(data)
|
||||
except ValidationError as exc:
|
||||
@@ -309,14 +312,7 @@ def _validate_receipt_report_config(
|
||||
path = _validate_report_path('dbs', raw_path)
|
||||
except ValidationError as exc:
|
||||
raise ValidationError(str(exc), code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') from exc
|
||||
# Warehouse 条件即逐仓拆分维度(不单独持久化仓库清单):必须恰一条且至少一个有效值。
|
||||
warehouse_conditions = [item for item in parameters if str(item.get('name') or '').strip().lower() == 'warehouse']
|
||||
warehouse_values = [str(value or '').strip() for value in (warehouse_conditions[0].get('values') or [])] if warehouse_conditions else []
|
||||
if len(warehouse_conditions) != 1 or not any(warehouse_values):
|
||||
raise ValidationError(
|
||||
'DBS receipt report requires exactly one Warehouse query condition with values',
|
||||
code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID',
|
||||
)
|
||||
# Warehouse 等条件可选;缺失/空值允许保存,运行期原样下发或走页面默认。
|
||||
return path, parameters
|
||||
if source.connector_type == 'crane':
|
||||
if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Inbound Details'):
|
||||
@@ -385,9 +381,7 @@ def _binding_snapshot(source: ShippingInventorySource) -> dict[str, Any]:
|
||||
|
||||
|
||||
def _validate_source_parsing_binding(source: ShippingInventorySource, profile: ShippingInventoryParsingProfile) -> None:
|
||||
"""校验停用站点可直接采用的已发布方案与当前发货模板字段契约。"""
|
||||
if source.enabled:
|
||||
raise ConflictError('Disable inventory source before changing parsing profile', code='SHIPPING.INVENTORY_SOURCE_BINDING_BLOCKED')
|
||||
"""校验站点可直接采用的已发布方案与当前发货模板字段契约;启用中的站点同样允许更换解析绑定。"""
|
||||
if profile.status != 'published':
|
||||
raise ValidationError('Published parsing profile is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
@@ -418,7 +412,7 @@ def _validate_source_parsing_binding(source: ShippingInventorySource, profile: S
|
||||
def bind_source_parsing_profile(
|
||||
source_ids: list[int], profile_id: int, *, actor_id: int | None, reason: str | None = None, operation: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""为一个或多个停用库存站点原子绑定已发布解析方案并写入追加式审计。
|
||||
"""为一个或多个库存站点原子绑定已发布解析方案并写入追加式审计(含已启用站点)。
|
||||
|
||||
Args:
|
||||
source_ids: 待绑定的库存站点主键,不能为空且不得重复。
|
||||
@@ -642,115 +636,6 @@ def list_export_records(*, limit: int = 100) -> list[dict[str, Any]]:
|
||||
return records[:max(1, min(limit, 200))]
|
||||
|
||||
|
||||
def _enabled_external_mapping_exists(source: ShippingInventorySource, warehouse_id: str | None) -> bool:
|
||||
"""判断已确认的货代仓库是否已有精确映射或库存源默认映射。"""
|
||||
query = ShippingInventoryExternalMapping.query.filter_by(inventory_source_id=source.id, enabled=True)
|
||||
warehouse = str(warehouse_id or '').strip().upper()
|
||||
if warehouse and query.filter_by(freight_warehouse_id=warehouse).first() is not None:
|
||||
return True
|
||||
return query.filter(ShippingInventoryExternalMapping.freight_warehouse_id.is_(None)).first() is not None
|
||||
|
||||
|
||||
def _test_analysis_validation(source: ShippingInventorySource) -> tuple[list[str], dict[str, Any]]:
|
||||
"""复核测试连接证据并生成行级解析/调拨映射准备状态,不将后两者作为启用条件。"""
|
||||
missing: list[str] = []
|
||||
details: dict[str, Any] = {'sample_warehouses': []}
|
||||
confirmed_test = ShippingInventoryConfigurationTestRun.query.filter(
|
||||
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
|
||||
ShippingInventoryConfigurationTestRun.status.in_(['completed', 'completed_empty']),
|
||||
ShippingInventoryConfigurationTestRun.source_config_version == source.config_version,
|
||||
).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
|
||||
result = confirmed_test.result_json if confirmed_test and isinstance(confirmed_test.result_json, dict) else {}
|
||||
if (
|
||||
not confirmed_test
|
||||
or source.rpa_profile is None
|
||||
or confirmed_test.rpa_profile_config_version != source.rpa_profile.config_version
|
||||
or int(result.get('confirmed_profile_id') or 0) != int(source.parsing_profile_id or 0)
|
||||
):
|
||||
return ['configuration_test'], details
|
||||
if confirmed_test.status == 'completed_empty':
|
||||
# 无库存时只能确认连接与查询成功;行级解析和调拨映射留待首个非空文件或实际调拨前验证。
|
||||
details['data_validation'] = 'pending_first_non_empty_export'
|
||||
details['parsing_validation'] = 'pending_first_non_empty_export'
|
||||
details['warehouse_mapping'] = 'deferred_until_transfer'
|
||||
return missing, details
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, confirmed_test.analysis_id)
|
||||
profile = source.parsing_profile
|
||||
if analysis is None or profile is None:
|
||||
return ['configuration_test'], details
|
||||
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
|
||||
candidates = structure.get('candidates') if isinstance(structure.get('candidates'), list) else []
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
selected = next((item for item in candidates if isinstance(item, dict)
|
||||
and item.get('sheet_name') == definition.get('sheet_name')
|
||||
and item.get('header_row_index') == definition.get('header_row_index')), None)
|
||||
headers = [str(item).strip() for item in (selected or {}).get('headers', []) if str(item).strip()]
|
||||
duplicate_headers = {
|
||||
str(item.get('header') or '').strip()
|
||||
for item in (selected or {}).get('columns', [])
|
||||
if isinstance(item, dict) and item.get('duplicate')
|
||||
}
|
||||
mapping = definition.get('field_mapping') if isinstance(definition.get('field_mapping'), dict) else {}
|
||||
from app.services.shipping_notice.inventory_mapping import runtime_field_mapping, usage_field_ids
|
||||
|
||||
runtime_mapping, catalog = runtime_field_mapping(mapping)
|
||||
usages = usage_field_ids()
|
||||
mapped_ids = set(runtime_mapping)
|
||||
match_fields = mapped_ids & usages.get('match_identity', set())
|
||||
quantity_fields = mapped_ids & usages.get('inventory_quantity', set())
|
||||
required_fields = match_fields | quantity_fields
|
||||
if (
|
||||
not selected
|
||||
or not match_fields
|
||||
or len(quantity_fields) != 1
|
||||
or not required_fields <= set(runtime_mapping)
|
||||
or any(str(runtime_mapping.get(field) or '').strip() not in headers for field in required_fields)
|
||||
or any(str(value or '').strip() in duplicate_headers for value in mapping.values())
|
||||
or not int((selected or {}).get('sample_row_count') or 0)
|
||||
):
|
||||
details['parsing_validation'] = 'pending_first_non_empty_export'
|
||||
return missing, details
|
||||
column_by_header = {
|
||||
str(item.get('header') or '').strip(): item
|
||||
for item in (selected or {}).get('columns', []) if isinstance(item, dict)
|
||||
}
|
||||
quantity_codes = quantity_fields
|
||||
quantity_column = next((
|
||||
column_by_header.get(str(runtime_mapping.get(field) or '').strip(), {})
|
||||
for field in quantity_codes
|
||||
), {})
|
||||
identifier_columns = [
|
||||
column_by_header.get(str(runtime_mapping.get(field) or '').strip(), {})
|
||||
for field in match_fields
|
||||
]
|
||||
if (
|
||||
quantity_column.get('inferred_type') != 'number'
|
||||
or any(not item.get('sample_values') for item in identifier_columns)
|
||||
):
|
||||
details['parsing_validation'] = 'pending_first_non_empty_export'
|
||||
return missing, details
|
||||
if source.warehouse_resolution_mode == 'fixed':
|
||||
details['warehouse_mapping'] = 'ready_for_transfer' if _enabled_external_mapping_exists(source, source.fixed_warehouse_id) else 'deferred_until_transfer'
|
||||
return missing, details
|
||||
warehouse_codes = mapped_ids & usages.get('warehouse_identity', set())
|
||||
if len(warehouse_codes) != 1:
|
||||
details['warehouse_identification'] = 'pending_first_non_empty_export'
|
||||
return missing, details
|
||||
warehouse_header = next((str(runtime_mapping.get(field) or '').strip() for field in warehouse_codes), '')
|
||||
if not warehouse_header or warehouse_header not in headers or warehouse_header in duplicate_headers:
|
||||
details['warehouse_identification'] = 'pending_first_non_empty_export'
|
||||
return missing, details
|
||||
column = next((item for item in (selected or {}).get('columns', [])
|
||||
if isinstance(item, dict) and str(item.get('header') or '').strip() == warehouse_header), {})
|
||||
sample_warehouses = sorted({str(value).strip().upper() for value in column.get('sample_values', []) if str(value).strip()})
|
||||
details['sample_warehouses'] = sample_warehouses
|
||||
details['warehouse_identification'] = 'ready_for_transfer' if sample_warehouses else 'pending_first_non_empty_export'
|
||||
details['warehouse_mapping'] = 'ready_for_transfer' if sample_warehouses and all(
|
||||
_enabled_external_mapping_exists(source, warehouse) for warehouse in sample_warehouses
|
||||
) else 'deferred_until_transfer'
|
||||
return missing, details
|
||||
|
||||
|
||||
def _template_validation_missing(source: ShippingInventorySource) -> list[str]:
|
||||
"""确认发货模板引用的库存字段均由当前解析方案提供,避免启用后才发现字段断链。"""
|
||||
template = source.excel_template
|
||||
@@ -770,35 +655,11 @@ def _template_validation_missing(source: ShippingInventorySource) -> list[str]:
|
||||
return ['template_validation'] if not mappings or invalid else []
|
||||
|
||||
|
||||
def _latest_test_run_evidence(source: ShippingInventorySource) -> dict[str, Any]:
|
||||
"""提取最近一次配置测试的非敏感证据,供上线检查说明测试是否过期或失败。"""
|
||||
run = ShippingInventoryConfigurationTestRun.query.filter_by(
|
||||
inventory_source_id=source.id,
|
||||
).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
|
||||
if run is None:
|
||||
return {'state': 'not_started'}
|
||||
profile_version = source.rpa_profile.config_version if source.rpa_profile is not None else None
|
||||
if (
|
||||
run.source_config_version != source.config_version
|
||||
or run.rpa_profile_config_version != profile_version
|
||||
):
|
||||
return {
|
||||
'state': 'stale', 'run_no': run.run_no, 'status': run.status,
|
||||
'source_config_version': run.source_config_version,
|
||||
'rpa_profile_config_version': run.rpa_profile_config_version,
|
||||
}
|
||||
if run.status == 'failed':
|
||||
return {'state': 'failed', 'run_no': run.run_no, 'status': run.status, 'stage': run.stage}
|
||||
if run.status == 'completed_empty':
|
||||
return {'state': 'empty', 'run_no': run.run_no, 'status': run.status, 'stage': run.stage}
|
||||
return {'state': 'current', 'run_no': run.run_no, 'status': run.status, 'stage': run.stage}
|
||||
|
||||
|
||||
def _activation_check(
|
||||
code: str, *, passed: bool, action: str, evidence: dict[str, Any], status: str | None = None,
|
||||
blocking: bool | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""构造单项上线门禁结果,确保管理端只展示服务端已判定的业务事实。"""
|
||||
"""构造单项启用门禁结果,确保管理端只展示服务端已判定的业务事实。"""
|
||||
return {
|
||||
'code': code,
|
||||
'status': status or ('passed' if passed else 'pending'),
|
||||
@@ -809,16 +670,15 @@ def _activation_check(
|
||||
|
||||
|
||||
def _source_activation_checks(source: ShippingInventorySource) -> list[dict[str, Any]]:
|
||||
"""构建库存站点启用条件与后续准备项;行级解析和调拨映射不阻断启用。"""
|
||||
validation_missing, validation_details = _test_analysis_validation(source)
|
||||
missing = set(validation_missing)
|
||||
test_evidence = _latest_test_run_evidence(source)
|
||||
test_complete = 'configuration_test' not in missing
|
||||
"""构建库存站点启用硬门槛:可用连接、已发布解析方案、已绑定已发布发货模板及字段契约。
|
||||
|
||||
测试导出不再参与启用门禁;启停由管理员显式开关完成。
|
||||
"""
|
||||
profile_ready = source.rpa_profile is not None and bool(source.rpa_profile.enabled)
|
||||
parsing_ready = source.parsing_profile is not None and source.parsing_profile.status == 'published'
|
||||
template_ready = source.excel_template is not None and source.excel_template.status == 'published'
|
||||
template_valid = template_ready and 'template_validation' not in missing
|
||||
checks = [
|
||||
template_invalid = bool(_template_validation_missing(source)) if template_ready and parsing_ready else False
|
||||
return [
|
||||
_activation_check(
|
||||
'rpa_profile', passed=profile_ready, action='configure_connection',
|
||||
evidence={'profile_id': source.rpa_profile_id, 'enabled': profile_ready},
|
||||
@@ -832,40 +692,14 @@ def _source_activation_checks(source: ShippingInventorySource) -> list[dict[str,
|
||||
evidence={'template_id': source.excel_template_id, 'published': template_ready},
|
||||
),
|
||||
_activation_check(
|
||||
'template_validation', passed=not template_ready or template_valid,
|
||||
action='configure_excel_template', evidence={}, blocking=template_ready and not template_valid,
|
||||
),
|
||||
_activation_check(
|
||||
'configuration_test', passed=test_complete,
|
||||
action='run_configuration_test', evidence=test_evidence,
|
||||
status=test_evidence['state'] if test_evidence['state'] in {'stale', 'failed', 'empty'} else None,
|
||||
),
|
||||
_activation_check(
|
||||
'parsing_validation', passed=test_complete and not validation_details.get('parsing_validation'),
|
||||
action='run_configuration_test', evidence={'sample_warehouses': validation_details['sample_warehouses']},
|
||||
status='pending' if validation_details.get('parsing_validation') else None, blocking=False,
|
||||
'template_validation', passed=not template_invalid,
|
||||
action='configure_excel_template', evidence={}, blocking=template_invalid,
|
||||
),
|
||||
]
|
||||
if source.warehouse_resolution_mode == 'inventory_match':
|
||||
checks.append(_activation_check(
|
||||
'warehouse_identification', passed=validation_details.get('warehouse_identification') == 'ready_for_transfer',
|
||||
action='configure_parsing_profile', evidence={'sample_warehouses': validation_details['sample_warehouses']},
|
||||
status='pending' if validation_details.get('warehouse_identification') else None, blocking=False,
|
||||
))
|
||||
checks.append(_activation_check(
|
||||
'warehouse_mapping', passed=validation_details.get('warehouse_mapping') == 'ready_for_transfer', action='configure_warehouse_mapping',
|
||||
evidence={
|
||||
'mode': source.warehouse_resolution_mode,
|
||||
'fixed_warehouse_id': source.fixed_warehouse_id,
|
||||
'sample_warehouses': validation_details['sample_warehouses'],
|
||||
},
|
||||
status='pending' if validation_details.get('warehouse_mapping') else None, blocking=False,
|
||||
))
|
||||
return checks
|
||||
|
||||
|
||||
def get_source_activation_status(source: ShippingInventorySource) -> dict[str, Any]:
|
||||
"""返回库存站点正式运行的结构化门禁结果。
|
||||
"""返回库存站点启用硬门槛的结构化结果。
|
||||
|
||||
Args:
|
||||
source: 已持久化的库存站点,关联配置由当前数据库事务提供。
|
||||
@@ -883,25 +717,8 @@ def get_source_activation_status(source: ShippingInventorySource) -> dict[str, A
|
||||
}
|
||||
|
||||
|
||||
def activate_source_if_ready(source: ShippingInventorySource, *, actor_id: int | None) -> bool:
|
||||
"""在测试回调后自动启用已满足全部正式运行条件的停用站点。
|
||||
|
||||
Args:
|
||||
source: 已完成当前版本测试的库存站点;调用方负责统一提交事务。
|
||||
actor_id: 发起测试的管理员标识,仅用于更新审计字段。
|
||||
|
||||
Returns:
|
||||
当本次将站点改为启用时返回 ``True``;条件未齐或已启用时返回 ``False``。
|
||||
"""
|
||||
if source.enabled or not get_source_activation_status(source)['ready']:
|
||||
return False
|
||||
source.enabled = True
|
||||
source.updated_by = actor_id
|
||||
return True
|
||||
|
||||
|
||||
def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""启用完成验证的库存站点;未通过任一前置条件时保持停用。"""
|
||||
"""启用已满足硬门槛的库存站点;未通过任一前置条件时保持停用。"""
|
||||
source = db.session.get(ShippingInventorySource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
@@ -919,7 +736,7 @@ def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
|
||||
|
||||
def deactivate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""停用库存站点,保留其解析方案和历史运行审计以便后续重新测试。"""
|
||||
"""停用库存站点,保留其解析方案和历史运行审计。"""
|
||||
source = db.session.get(ShippingInventorySource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
|
||||
@@ -228,10 +228,10 @@ def _section_type_for_line(line: str) -> str | None:
|
||||
|
||||
|
||||
def _extract_repeated_section_answers(lines: list[str]) -> dict[str, list[str]]:
|
||||
"""提取 PDF 后半段按小节重复出现的填空标准答案,避免把答案行当作新题目。"""
|
||||
"""提取 PDF 后半段按小节重复出现的填空/判断标准答案,避免把答案行当作新题目。"""
|
||||
occurrences: dict[str, int] = {}
|
||||
active_type: str | None = None
|
||||
answers: dict[str, list[str]] = {'fill': []}
|
||||
answers: dict[str, list[str]] = {'fill': [], 'boolean': []}
|
||||
in_answer_sheet = False
|
||||
for line in lines:
|
||||
if _is_answer_section_heading(line):
|
||||
@@ -241,17 +241,34 @@ def _extract_repeated_section_answers(lines: list[str]) -> dict[str, list[str]]:
|
||||
section_type = _section_type_for_line(line)
|
||||
if section_type:
|
||||
occurrences[section_type] = occurrences.get(section_type, 0) + 1
|
||||
if occurrences[section_type] > 1:
|
||||
in_answer_sheet = True
|
||||
active_type = section_type if occurrences[section_type] > 1 or in_answer_sheet else None
|
||||
repeated = occurrences[section_type] > 1
|
||||
in_answer_sheet = in_answer_sheet or repeated
|
||||
active_type = section_type if (repeated or in_answer_sheet) else None
|
||||
# 小节标题行自带答案内容(如「二、判断题:1-2、√ ×」):去掉标题前缀后按判断答案表解析
|
||||
if in_answer_sheet and section_type == 'boolean':
|
||||
remainder = _BOOLEAN_SECTION_PATTERN.sub('', _normalize_spaces(line), count=1)
|
||||
remainder = remainder.lstrip('一二三四五六七八九十、..::\t (()) ')
|
||||
if remainder and not _QUESTION_START_PATTERN.match(remainder):
|
||||
for raw_token in _BOOLEAN_TOKEN_PATTERN.findall(remainder):
|
||||
answer = _normalize_answer_token(raw_token)
|
||||
if answer:
|
||||
answers['boolean'].append(answer)
|
||||
continue
|
||||
if not in_answer_sheet or active_type != 'fill':
|
||||
if not in_answer_sheet or active_type not in {'fill', 'boolean'}:
|
||||
continue
|
||||
match = _QUESTION_START_PATTERN.match(line)
|
||||
if match:
|
||||
value = _normalize_spaces(match.group(2))
|
||||
if value:
|
||||
answers['fill'].append(value)
|
||||
if not match:
|
||||
continue
|
||||
value = _normalize_spaces(match.group(2))
|
||||
if not value:
|
||||
continue
|
||||
if active_type == 'fill':
|
||||
answers['fill'].append(value)
|
||||
elif ' ' not in value:
|
||||
# 判断答案行只接受整行单 token(如「1、√」);带空格的多题答案表交由题号映射解析
|
||||
answer = _normalize_answer_token(value)
|
||||
if answer:
|
||||
answers['boolean'].append(answer)
|
||||
return answers
|
||||
|
||||
|
||||
@@ -320,11 +337,12 @@ def _split_question_blocks(lines: list[str]) -> list[tuple[int, str, str | None]
|
||||
continue
|
||||
if current_section_type == 'answer_sheet' or (current_section_type and current_section_type.startswith('answer_')):
|
||||
continue
|
||||
if _is_answer_sheet_line(line):
|
||||
continue
|
||||
# 题干匹配必须先于答案表过滤:行内答案题干(如「1. 题干… 答案:C 解析:…」)整行含「答案」,
|
||||
# 若先走答案表过滤会被整体丢弃导致整卷解析为空(2026-09-29 修复,原顺序该分支为死代码)。
|
||||
question_match = _QUESTION_START_PATTERN.match(line)
|
||||
if question_match:
|
||||
if _is_answer_sheet_line(line) and '答案' not in line:
|
||||
# 疑似答案表行(如「1.B 2.A 3.正确」)即使形如题干也不生成题目
|
||||
continue
|
||||
if current_no is not None and current_lines:
|
||||
blocks.append((current_no, ' '.join(current_lines).strip(), current_section_type))
|
||||
@@ -480,6 +498,7 @@ def parse_training_question_bank_text(text: str) -> dict[str, Any]:
|
||||
question_bank: list[dict[str, Any]] = []
|
||||
skipped_questions: list[int] = []
|
||||
fill_answer_index = 0
|
||||
boolean_answer_index = 0
|
||||
|
||||
# [STEP 1] 先按题号切块,再对每一块做题型、答案和解析判定,避免跨题串行污染。
|
||||
answer_sequence_index = 0
|
||||
@@ -497,6 +516,17 @@ def parse_training_question_bank_text(text: str) -> dict[str, Any]:
|
||||
mapped_answer=answer_map.get(question_no, ''),
|
||||
ordered_answer=ordered_answer,
|
||||
)
|
||||
if section_type == 'boolean':
|
||||
# 分节重复答案区(如「二、判断题 1、√」「二、判断题:1-2、√ ×」)提取到的判断答案
|
||||
# 作为兜底候选补入;内联/题号映射/整卷顺序命中时仍优先。
|
||||
repeated_answer = (
|
||||
repeated_section_answers['boolean'][boolean_answer_index]
|
||||
if boolean_answer_index < len(repeated_section_answers['boolean'])
|
||||
else ''
|
||||
)
|
||||
boolean_answer_index += 1
|
||||
if repeated_answer and repeated_answer not in answer_candidates:
|
||||
answer_candidates.append(repeated_answer)
|
||||
if section_type == 'boolean':
|
||||
for answer in answer_candidates:
|
||||
question_payload = _build_boolean_question(
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
backend/app/services/admin/user_service.py
|
||||
|
||||
用途:管理端用户 CRUD、审批与批量删除;创建/改密时同步 Casdoor。
|
||||
依赖:models、user_admin.delete_admin_users、services/auth/casdoor_service。
|
||||
逻辑:由 api/admin/users.py 调用。
|
||||
依赖:models、user_admin.delete_admin_users、services/auth/casdoor_service、permission_roles。
|
||||
逻辑:由 api/admin/users.py 调用;权限组启用后创建/改角色只同步角色包,不再按人勾应用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -17,6 +17,7 @@ from app import db
|
||||
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
|
||||
from app.models import Agent, User
|
||||
from app.services.auth import casdoor_service
|
||||
from app.services.permission_roles import service as role_service
|
||||
from app.services.user_admin import delete_admin_users
|
||||
|
||||
|
||||
@@ -68,13 +69,16 @@ def assert_user_unique_fields(exclude_user_id: int | None, **fields: str | None)
|
||||
raise ConflictError(message, code=code, details={'field': field})
|
||||
|
||||
|
||||
def serialize_admin_user(user: User) -> dict:
|
||||
def serialize_admin_user(user: User, role_names: dict[str, str] | None = None) -> dict:
|
||||
names = role_names if role_names is not None else role_service.list_role_name_map()
|
||||
return {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'email': user.email,
|
||||
'department': user.department,
|
||||
'role': user.role,
|
||||
'role_name': names.get(user.role) or user.role,
|
||||
'is_platform_admin': user.is_platform_admin(),
|
||||
'status': user.status,
|
||||
'real_name': user.real_name,
|
||||
'employee_id': user.employee_id,
|
||||
@@ -137,7 +141,8 @@ def list_users(query_params: dict[str, str]) -> list[dict] | dict:
|
||||
order_by = resolve_users_order_by(query_params)
|
||||
if 'page' not in query_params:
|
||||
users = query.options(joinedload(User.agents)).order_by(*order_by).all()
|
||||
return [serialize_admin_user(u) for u in users]
|
||||
names = role_service.list_role_name_map()
|
||||
return [serialize_admin_user(u, names) for u in users]
|
||||
|
||||
try:
|
||||
page = int(query_params.get('page') or 1)
|
||||
@@ -162,8 +167,9 @@ def list_users(query_params: dict[str, str]) -> list[dict] | dict:
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
names = role_service.list_role_name_map()
|
||||
return {
|
||||
'items': [serialize_admin_user(u) for u in users],
|
||||
'items': [serialize_admin_user(u, names) for u in users],
|
||||
'total': int(total),
|
||||
'page': page,
|
||||
'page_size': page_size,
|
||||
@@ -194,21 +200,28 @@ def create_user(data: dict[str, Any]) -> dict:
|
||||
employee_id=empty_to_none(data.get('employee_id')),
|
||||
phone_number=empty_to_none(data.get('phone_number')),
|
||||
)
|
||||
role_code = role_service.assert_role_assignable(
|
||||
data.get('role') or role_service.default_role_code(),
|
||||
allow_admin=True,
|
||||
)
|
||||
user = User(
|
||||
username=data['username'],
|
||||
email=email,
|
||||
department=empty_to_none(data.get('department')),
|
||||
role=data.get('role', 'user'),
|
||||
role=role_code,
|
||||
status=data.get('status', 'active'),
|
||||
real_name=empty_to_none(data.get('real_name')),
|
||||
employee_id=empty_to_none(data.get('employee_id')),
|
||||
phone_number=empty_to_none(data.get('phone_number')),
|
||||
)
|
||||
user.set_feature_permissions(data.get('feature_permissions'))
|
||||
if not role_service.roles_configured():
|
||||
user.set_feature_permissions(data.get('feature_permissions'))
|
||||
user.set_password(data['password'])
|
||||
db.session.add(user)
|
||||
try:
|
||||
if data.get('agent_ids'):
|
||||
if role_service.roles_configured():
|
||||
role_service.sync_user_grants_from_role(user)
|
||||
elif data.get('agent_ids'):
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
user.agents = agents
|
||||
casdoor_service.sync_create_user(
|
||||
@@ -268,13 +281,21 @@ def update_user(user_id: int, data: dict[str, Any]) -> dict:
|
||||
try:
|
||||
for key in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
|
||||
if key in data:
|
||||
if key in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
|
||||
if key == 'role':
|
||||
next_role = role_service.assert_role_assignable(data.get('role'), allow_admin=True)
|
||||
role_service.ensure_not_last_admin(user, next_role)
|
||||
user.role = next_role
|
||||
elif key in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
|
||||
setattr(user, key, empty_to_none(data[key]))
|
||||
else:
|
||||
setattr(user, key, data[key])
|
||||
if 'feature_permissions' in data or 'role' in data:
|
||||
permissions_payload = data.get('feature_permissions', user.feature_permissions)
|
||||
user.set_feature_permissions(permissions_payload)
|
||||
if role_service.roles_configured():
|
||||
if 'role' in data:
|
||||
role_service.sync_user_grants_from_role(user)
|
||||
else:
|
||||
if 'feature_permissions' in data or 'role' in data:
|
||||
permissions_payload = data.get('feature_permissions', user.feature_permissions)
|
||||
user.set_feature_permissions(permissions_payload)
|
||||
if new_password and user.check_password(new_password):
|
||||
raise AppError(
|
||||
code='AUTH.PASSWORD_UNCHANGED',
|
||||
@@ -283,7 +304,7 @@ def update_user(user_id: int, data: dict[str, Any]) -> dict:
|
||||
)
|
||||
if new_password:
|
||||
user.set_password(new_password)
|
||||
if 'agent_ids' in data:
|
||||
if 'agent_ids' in data and not role_service.roles_configured():
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
user.agents = agents
|
||||
if new_password:
|
||||
@@ -301,6 +322,30 @@ def update_user(user_id: int, data: dict[str, Any]) -> dict:
|
||||
return {'status': 'ok'}
|
||||
|
||||
|
||||
def batch_update_users(user_ids: list[Any], data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
批量更新用户部门 / 角色 / 状态。改角色时同步权限包。
|
||||
"""
|
||||
if not user_ids:
|
||||
raise ValidationError('No users selected')
|
||||
payload = data if isinstance(data, dict) else {}
|
||||
next_role = None
|
||||
if payload.get('role'):
|
||||
next_role = role_service.assert_role_assignable(payload.get('role'), allow_admin=True)
|
||||
users = db.session.query(User).filter(User.id.in_(user_ids)).all()
|
||||
for user in users:
|
||||
if 'department' in payload and payload.get('department') != '':
|
||||
user.department = empty_to_none(payload.get('department'))
|
||||
if 'status' in payload and payload.get('status') != '':
|
||||
user.status = payload.get('status')
|
||||
if next_role:
|
||||
role_service.ensure_not_last_admin(user, next_role)
|
||||
user.role = next_role
|
||||
role_service.sync_user_grants_from_role(user)
|
||||
db.session.commit()
|
||||
return {'status': 'ok', 'updated_count': len(users)}
|
||||
|
||||
|
||||
def cleanup_rejected_users() -> dict:
|
||||
rejected_ids = [row[0] for row in db.session.query(User.id).filter_by(status='rejected').all()]
|
||||
cnt = delete_admin_users(rejected_ids)
|
||||
|
||||
@@ -97,7 +97,12 @@ def raise_auth_error(source, *, context: str, status_code: int = 401) -> None:
|
||||
)
|
||||
if 'invalid or expired casdoor state' in lowered_raw:
|
||||
raise ValidationError('Invalid or expired Casdoor state')
|
||||
current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s', context, data)
|
||||
# [STEP 2] 未识别错误必须保留原始异常堆栈,否则本地换票后的崩溃会被吞成一行 payload={}。
|
||||
current_app.logger.warning(
|
||||
'[casdoor] unmapped auth error context=%s payload=%s source=%r',
|
||||
context, data, source,
|
||||
exc_info=source if isinstance(source, BaseException) else None,
|
||||
)
|
||||
raise AppError(
|
||||
code='CASDOOR_AUTH_FAILED',
|
||||
message='Authentication failed, please try again',
|
||||
|
||||
@@ -48,7 +48,7 @@ class LoginResult:
|
||||
'username': self.user.username,
|
||||
'role': self.user.role,
|
||||
'default_agent_id': self.user.default_agent_id,
|
||||
'feature_permissions': self.user.get_feature_permissions(),
|
||||
**self.user.client_auth_fields(),
|
||||
'source': 'casdoor',
|
||||
'access_token': self.access_token,
|
||||
'refresh_token': self.refresh_token,
|
||||
|
||||
@@ -91,7 +91,7 @@ def supports(*, user, agent, query: str) -> bool:
|
||||
普通知识问答、普通员工提问或其他 Agent 一律不命中。
|
||||
|
||||
Args:
|
||||
user: 当前聊天用户代理对象;需至少包含 role。
|
||||
user: 当前聊天用户;须能 has_feature_permission('training_hr_manage')。
|
||||
agent: 当前 Agent 代理对象;需能识别是否为员工培训 Agent。
|
||||
query: 用户原始问题。
|
||||
|
||||
@@ -100,7 +100,7 @@ def supports(*, user, agent, query: str) -> bool:
|
||||
"""
|
||||
if not is_training_chat_agent(agent):
|
||||
return False
|
||||
if str(getattr(user, 'role', '') or '').strip() not in {'admin', 'hr'}:
|
||||
if not bool(getattr(user, 'has_feature_permission', None) and user.has_feature_permission('training_hr_manage')):
|
||||
return False
|
||||
return (
|
||||
_matches_any(query, _TRAINING_TOTAL_PATTERNS)
|
||||
|
||||
@@ -141,7 +141,21 @@ def emit_run_failed(
|
||||
conversation_id: str,
|
||||
message: str,
|
||||
code: str | None = None,
|
||||
user_facing: bool = False,
|
||||
) -> str:
|
||||
"""
|
||||
发出本轮失败事件,并附带兼容用的 error 帧。
|
||||
|
||||
核心逻辑:user_facing 为 True 时两帧都带标记,前端原样展示 message。
|
||||
|
||||
Args:
|
||||
message: 失败说明。user_facing 为 True 时必须已是给用户看的句子。
|
||||
code: 业务错误码,可选。
|
||||
user_facing: 为 True 时前端不再把 message 收成通用失败提示。
|
||||
|
||||
Returns:
|
||||
连续两段 SSE 帧:run.failed 与 error。
|
||||
"""
|
||||
error_payload: dict[str, Any] = {
|
||||
"event": "run.failed",
|
||||
"run_id": run_id,
|
||||
@@ -150,10 +164,18 @@ def emit_run_failed(
|
||||
"message": message,
|
||||
"session_status": "error",
|
||||
}
|
||||
legacy_payload: dict[str, Any] = {
|
||||
"event": "error",
|
||||
"message": message,
|
||||
"conversation_id": conversation_id,
|
||||
"session_status": "error",
|
||||
}
|
||||
if code:
|
||||
error_payload["code"] = code
|
||||
legacy = sse_frame({"event": "error", "message": message, "conversation_id": conversation_id, "session_status": "error"})
|
||||
return sse_frame(error_payload) + legacy
|
||||
if user_facing:
|
||||
error_payload["user_facing"] = True
|
||||
legacy_payload["user_facing"] = True
|
||||
return sse_frame(error_payload) + sse_frame(legacy_payload)
|
||||
|
||||
|
||||
def emit_turn_event(event: TurnEvent, *, conversation_id: str) -> str:
|
||||
|
||||
@@ -194,6 +194,7 @@ class ChatTurnRuntime:
|
||||
conversation_id=session.session_id,
|
||||
message=exc.message,
|
||||
code=str(getattr(exc, "code", "") or "") or None,
|
||||
user_facing=True,
|
||||
)
|
||||
except Exception as exc:
|
||||
current_app.logger.exception("[chat-turn] unexpected failure request_id=%s turn_id=%s", req_id, turn_id)
|
||||
|
||||
@@ -5,6 +5,7 @@ backend/app/services/contract_payment/parse_service.py
|
||||
依赖:标准库正则与日期处理;原文抽取由调用方传入,避免绑定某一种文件解析器。
|
||||
逻辑:先识别固定字段和付款比例,再校验金额/比例/日期;无法确定的事实进入 needs_review,不猜测。
|
||||
合同金额以正文抽出的正数为准;OA 的 0 与空值都不是有效总额。同一付款阶段的相同比例重复抽取不报重复。
|
||||
增值税税率和「收到定金后 N 天」不计入付款比例。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -24,7 +25,12 @@ from app.services.procurement_contract.analyze import extract_text_from_bytes
|
||||
|
||||
_DATE_RE = re.compile(r"(20\d{2})[\s_]*[年./-][\s_]*(\d{1,2})[\s_]*[月./-][\s_]*(\d{1,2})[\s_]*日?")
|
||||
_MONEY_RE = re.compile(r"(?:设备总价款\s*[((]?含税[))]?|人民币合同金额|合同金额|合同总价|含税总价)[::\s¥¥]*([\d,]+(?:\.\d+)?)", re.I)
|
||||
_PERCENT_RE = re.compile(r"(预付款|定金|出货款|货款|验收款|质保款|保款|尾款)[^。;;\n]{0,140}?(\d+(?:\.\d+)?)\s*%", re.S)
|
||||
_STAGE_LABEL_RE = re.compile(r"预付款|定金|出货款|货款|验收款|质保款|保款|尾款")
|
||||
_PERCENT_VALUE_RE = re.compile(r"(\d+(?:\.\d+)?)\s*%")
|
||||
_DEPOSIT_SCHEDULE_RE = re.compile(r"定金\s*后\s*\d+\s*(?:个)?(?:工作日|天|日)")
|
||||
_SENTENCE_BREAK_RE = re.compile(r"[。;;\n]")
|
||||
_TAX_PREFIX_RE = re.compile(r"(?:增值税|税率)\s*$")
|
||||
_TAX_SUFFIX_RE = re.compile(r"\s*(?:的\s*)?增值税")
|
||||
_DELIVERY_RE = re.compile(r"(?:交货期限|约定到货日期|交付期限|交货期)[::\s]*[^。;;\n]{0,60}?(20\d{2}[^\n。;;]*)")
|
||||
_WARRANTY_RE = re.compile(r"(?:质保期|保修期|保固期|质保款[^。;;\n]{0,100}?)(?:满后|为|:|:)?\s*(\d+)\s*(年|个月|月|天)")
|
||||
_WARRANTY_PAYMENT_RE = re.compile(
|
||||
@@ -146,12 +152,82 @@ def unique_parse_issues(issues: list[Any] | None) -> list[str]:
|
||||
return result
|
||||
|
||||
|
||||
def _is_tax_percentage(body: str, number_start: int, percent_end: int) -> bool:
|
||||
"""
|
||||
判断百分号是增值税或税率,而不是付款比例。
|
||||
|
||||
核心逻辑:数字前紧挨「增值税」或「税率」,或百分号后紧挨「增值税」,都视为税率。
|
||||
「含13%增值税」靠百分号后面的「增值税」识别;单独的「含30%」仍可当作付款比例。
|
||||
Args:
|
||||
body: 合同正文。
|
||||
number_start: 百分数数字在正文中的起始下标。
|
||||
percent_end: 百分号结束下标,不含其后的文字。
|
||||
Returns:
|
||||
该百分号是税率时返回 True。
|
||||
"""
|
||||
before = body[max(0, number_start - 16):number_start]
|
||||
after = body[percent_end:percent_end + 16]
|
||||
return _TAX_PREFIX_RE.search(before) is not None or _TAX_SUFFIX_RE.match(after) is not None
|
||||
|
||||
|
||||
def _first_payment_percentage(body: str, label_end: int) -> re.Match[str] | None:
|
||||
"""
|
||||
在阶段词后的同一句、140 字内取第一个非税率百分号。
|
||||
|
||||
核心逻辑:税率百分号跳过并继续看,避免「含13%增值税」挡住同一句里的「总价款的30%」。
|
||||
遇到句号、分号或换行即停止,窗口长度与原先一致。
|
||||
Args:
|
||||
body: 合同正文。
|
||||
label_end: 阶段词结束下标。
|
||||
Returns:
|
||||
付款比例的正则匹配;窗口内没有可用百分号时返回 None。
|
||||
"""
|
||||
window_end = label_end + 140
|
||||
sentence = _SENTENCE_BREAK_RE.search(body, label_end)
|
||||
if sentence and sentence.start() < window_end:
|
||||
window_end = sentence.start()
|
||||
cursor = label_end
|
||||
while cursor < window_end:
|
||||
value_match = _PERCENT_VALUE_RE.search(body, cursor, window_end)
|
||||
if value_match is None:
|
||||
return None
|
||||
if _is_tax_percentage(body, value_match.start(1), value_match.end()):
|
||||
cursor = value_match.end()
|
||||
continue
|
||||
return value_match
|
||||
return None
|
||||
|
||||
|
||||
def _matched_payment_percentages(body: str) -> list[tuple[str, str]]:
|
||||
"""
|
||||
抽出每个付款阶段词对应的第一个付款比例。
|
||||
|
||||
核心逻辑:「收到定金后 N 天」是完成日期,不作为预付款锚点。
|
||||
其余阶段词沿用原窗口,但丢掉增值税、税率百分号。
|
||||
Args:
|
||||
body: 已抽取的合同正文。
|
||||
Returns:
|
||||
(阶段词, 百分数字符串) 列表,按出现顺序。未命中付款比例的阶段词不出现。
|
||||
"""
|
||||
matched: list[tuple[str, str]] = []
|
||||
for label_match in _STAGE_LABEL_RE.finditer(body):
|
||||
label = label_match.group(0)
|
||||
if label == "定金" and _DEPOSIT_SCHEDULE_RE.match(body, label_match.start()):
|
||||
continue
|
||||
value_match = _first_payment_percentage(body, label_match.end())
|
||||
if value_match is None:
|
||||
continue
|
||||
matched.append((label, value_match.group(1)))
|
||||
return matched
|
||||
|
||||
|
||||
def _extract_payment_percentages(body: str) -> tuple[dict[str, Decimal], list[str]]:
|
||||
"""
|
||||
提取四阶段付款比例,并校验阶段完整性及比例合计。
|
||||
|
||||
核心逻辑:同一语义阶段只允许一个比例。正文里同一比例被抽到多次(表格/页眉重复)
|
||||
视为同一事实,不报重复;只有同一阶段出现不同比例才阻断。四阶段须完整且合计 100%。
|
||||
增值税税率和「收到定金后 N 天」不计入付款比例。
|
||||
Args:
|
||||
body: 已抽取的合同正文。
|
||||
Returns:
|
||||
@@ -159,8 +235,8 @@ def _extract_payment_percentages(body: str) -> tuple[dict[str, Decimal], list[st
|
||||
"""
|
||||
found: dict[str, list[Decimal]] = {node_type: [] for node_type in _PAYMENT_NODE_TYPES}
|
||||
issues: list[str] = []
|
||||
for match in _PERCENT_RE.finditer(body):
|
||||
label, raw = match.groups()
|
||||
matched = _matched_payment_percentages(body)
|
||||
for label, raw in matched:
|
||||
node_type = _PAYMENT_LABEL_TO_NODE_TYPE[label]
|
||||
percentage = _parse_decimal(raw)
|
||||
if percentage is None:
|
||||
@@ -181,7 +257,6 @@ def _extract_payment_percentages(body: str) -> tuple[dict[str, Decimal], list[st
|
||||
if missing:
|
||||
issues.append(f"付款阶段比例无法识别:{'、'.join(_PAYMENT_NODE_LABELS[item] for item in missing)}")
|
||||
try:
|
||||
matched = [(m.group(1), m.group(2)) for m in _PERCENT_RE.finditer(body)]
|
||||
snippet = ""
|
||||
for label in ("质保款", "验收款", "尾款"):
|
||||
idx = body.find(label)
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
"""合同付款预警默认排程种子:每日扫描与周五 18:00 汇总。"""
|
||||
"""
|
||||
services/contract_payment/schedule_seed.py
|
||||
|
||||
用途:合同付款预警默认排程种子:每日扫描与周五 18:00 汇总。
|
||||
依赖:ScheduleTask、permission_roles.service.first_schedule_owner_user、timezone_util。
|
||||
逻辑:幂等创建;owner 优先平台管理员,否则任意用户。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleTask, User
|
||||
from app.models import ScheduleTask
|
||||
from app.services.permission_roles.service import first_schedule_owner_user
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
|
||||
@@ -24,7 +31,7 @@ def ensure_default_contract_payment_schedules(*, commit: bool = True):
|
||||
Returns:
|
||||
新建的 ScheduleTask 列表;无用户时返回空列表。
|
||||
"""
|
||||
owner = db.session.query(User).filter(User.role == 'admin').order_by(User.id.asc()).first() or db.session.query(User).order_by(User.id.asc()).first()
|
||||
owner = first_schedule_owner_user()
|
||||
if owner is None:
|
||||
return []
|
||||
created = []
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/__init__.py
|
||||
|
||||
用途:设备验收预警同步包。
|
||||
依赖:snapshot_rules、source_group、query_sql、sync_service。
|
||||
逻辑:本包只做 OA 只读同步和本地快照,不发送企业微信。
|
||||
"""
|
||||
@@ -0,0 +1,90 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/alert_notice.py
|
||||
|
||||
用途:把一名收件人的待发送记录收成企微汇总文案和 Excel 明细。
|
||||
依赖:openpyxl。
|
||||
逻辑:发送服务按企业微信账号调用。卡片只写张数,逐张明细进工作簿。不写主送、抄送。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Font
|
||||
|
||||
NOTICE_HEADERS = (
|
||||
"验收单号",
|
||||
"采购单号",
|
||||
"申请人",
|
||||
"轮次",
|
||||
"停留天数",
|
||||
"当前节点",
|
||||
"当前处理人",
|
||||
"通知身份",
|
||||
)
|
||||
NOTICE_FILE_NAME = "设备验收停留提醒.xlsx"
|
||||
|
||||
|
||||
def summary_message(lines: list[dict[str, Any]]) -> str:
|
||||
"""
|
||||
拼一名收件人的文字卡片。第一行写已逾期的验收单张数,不列单号。
|
||||
|
||||
核心逻辑:一张发送记录算一张。同一轮次的张数写在一起,顺序跟传入的明细一致。
|
||||
Args:
|
||||
lines: 已按发送记录去重的明细。每项含 threshold_days。
|
||||
Returns:
|
||||
卡片正文。没有明细时仍返回可发送的空汇总。
|
||||
"""
|
||||
counts: dict[int, int] = {}
|
||||
order: list[int] = []
|
||||
for line in lines:
|
||||
day = int(line.get("threshold_days") or 0)
|
||||
if day not in counts:
|
||||
order.append(day)
|
||||
counts[day] = 0
|
||||
counts[day] += 1
|
||||
detail = ",".join(f"超过 {day} 天 {counts[day]} 张" for day in order) or "无"
|
||||
return f"共 {len(lines)} 张验收单已逾期。\n{detail}。\n明细见下一条文件。"
|
||||
|
||||
|
||||
def build_notice_workbook(lines: list[dict[str, Any]]) -> bytes:
|
||||
"""
|
||||
生成这名收件人的验收停留明细。
|
||||
|
||||
核心逻辑:一行对应一张发送记录。通知身份写他为什么收到,不写主送或抄送。
|
||||
Args:
|
||||
lines: 验收单号、采购单号、申请人、轮次天数、停留天数、当前节点、当前处理人和通知身份。
|
||||
Returns:
|
||||
xlsx 字节。
|
||||
"""
|
||||
workbook = Workbook()
|
||||
sheet = workbook.active
|
||||
sheet.title = "停留提醒"
|
||||
sheet.append(list(NOTICE_HEADERS))
|
||||
for cell in sheet[1]:
|
||||
cell.font = Font(bold=True)
|
||||
for line in lines:
|
||||
dwell = line.get("dwell_days")
|
||||
sheet.append([
|
||||
_cell(line.get("acceptance_no")),
|
||||
_cell(line.get("purchase_order_no")),
|
||||
_cell(line.get("applicant")),
|
||||
f"超过 {int(line.get('threshold_days') or 0)} 天",
|
||||
"—" if dwell is None or dwell == "" else dwell,
|
||||
_cell(line.get("node_name")),
|
||||
_cell(line.get("handlers")),
|
||||
_cell(line.get("identity")),
|
||||
])
|
||||
sheet.freeze_panes = "A2"
|
||||
sheet.auto_filter.ref = sheet.dimensions
|
||||
output = BytesIO()
|
||||
workbook.save(output)
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def _cell(value: Any) -> str:
|
||||
"""空值写成横线,避免 Excel 里出现空白列。"""
|
||||
text = str(value or "").strip()
|
||||
return text or "—"
|
||||
@@ -0,0 +1,244 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/alert_plan.py
|
||||
|
||||
用途:判断验收单跨了哪几档,并把主送、抄送收成一条待发送。
|
||||
依赖:无。不读数据库,不访问 OA,不发企业微信。
|
||||
逻辑:扫描服务先解析出人员,再调用本模块去重和定状态。超过天数才进档,等于阈值不算。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def due_tiers(
|
||||
dwell_days: int | None,
|
||||
thresholds: tuple[int, int, int, int],
|
||||
*,
|
||||
max_tier: int = 4,
|
||||
) -> list[int]:
|
||||
"""
|
||||
按累计天数给出已经跨过的档位。
|
||||
|
||||
核心逻辑:需求是「超过 N 天」。停留刚好等于阈值时还不发。四档各自独立,一次可以跨多档。
|
||||
第 4 轮关闭时最高只到第 3 档,超过第 4 档天数也不产生总经理那一轮。
|
||||
Args:
|
||||
dwell_days: 签核自然日。没有计时起点时为空。
|
||||
thresholds: 四个天数,对应第 1 到第 4 档。
|
||||
max_tier: 允许的最高档,1 到 4。第 4 轮未启用时传 3。
|
||||
Returns:
|
||||
档位号列表。没有跨档时为空。
|
||||
"""
|
||||
if dwell_days is None:
|
||||
return []
|
||||
return [
|
||||
index + 1
|
||||
for index, day in enumerate(thresholds)
|
||||
if dwell_days > day and index + 1 <= max_tier
|
||||
]
|
||||
|
||||
|
||||
def make_person(
|
||||
*,
|
||||
slot: str,
|
||||
label: str,
|
||||
name: str | None = None,
|
||||
user_id: int | None = None,
|
||||
wecom_userid: str | None = None,
|
||||
oa_employee_id: int | None = None,
|
||||
error: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
收成一名收件人。
|
||||
|
||||
核心逻辑:解析失败时留下 error,不改成别的人。
|
||||
Args:
|
||||
slot: to 主送,cc 抄送。
|
||||
label: 角色名称,例如当前处理人、直接主管。
|
||||
name: 展示姓名。
|
||||
user_id: 系统用户主键。对不上时为空。
|
||||
wecom_userid: 已绑定的企业微信 userid。
|
||||
oa_employee_id: E10 employee.ID。
|
||||
error: 解析失败原因。成功时为空。
|
||||
Returns:
|
||||
写入 recipients_json 的字典。
|
||||
"""
|
||||
return {
|
||||
"slot": slot,
|
||||
"label": label,
|
||||
"name": name,
|
||||
"user_id": user_id,
|
||||
"wecom_userid": wecom_userid or None,
|
||||
"oa_employee_id": oa_employee_id,
|
||||
"error": error,
|
||||
}
|
||||
|
||||
|
||||
def resolve_account(
|
||||
*,
|
||||
slot: str,
|
||||
label: str,
|
||||
name: str | None,
|
||||
job_num: str | None,
|
||||
user: Any,
|
||||
missing_job_error: str,
|
||||
oa_employee_id: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
用工号对上系统用户,并要求已绑定企业微信。
|
||||
|
||||
核心逻辑:没有工号、对不上用户、没绑企微都记失败,不换成别人。
|
||||
Args:
|
||||
slot: to 或 cc。
|
||||
label: 角色名称。
|
||||
name: OA 或快照上的姓名。
|
||||
job_num: employee.JOB_NUM,对应 users.employee_id。
|
||||
user: 已按工号找到的用户。需要 id、wecom_userid,姓名优先 real_name。
|
||||
missing_job_error: 没有工号时的失败原因。
|
||||
oa_employee_id: E10 人员 ID。
|
||||
Returns:
|
||||
一名收件人。
|
||||
"""
|
||||
if not str(job_num or "").strip():
|
||||
return make_person(
|
||||
slot=slot,
|
||||
label=label,
|
||||
name=name,
|
||||
oa_employee_id=oa_employee_id,
|
||||
error=missing_job_error,
|
||||
)
|
||||
if user is None:
|
||||
return make_person(
|
||||
slot=slot,
|
||||
label=label,
|
||||
name=name,
|
||||
oa_employee_id=oa_employee_id,
|
||||
error="未对上系统用户",
|
||||
)
|
||||
display = _user_name(user) or name
|
||||
wecom = str(getattr(user, "wecom_userid", None) or "").strip()
|
||||
if not wecom:
|
||||
return make_person(
|
||||
slot=slot,
|
||||
label=label,
|
||||
name=display,
|
||||
user_id=getattr(user, "id", None),
|
||||
oa_employee_id=oa_employee_id,
|
||||
error="未绑定企业微信",
|
||||
)
|
||||
return make_person(
|
||||
slot=slot,
|
||||
label=label,
|
||||
name=display,
|
||||
user_id=getattr(user, "id", None),
|
||||
wecom_userid=wecom,
|
||||
oa_employee_id=oa_employee_id,
|
||||
)
|
||||
|
||||
|
||||
def resolve_configured_user(*, slot: str, label: str, user: Any, missing_error: str) -> dict[str, Any]:
|
||||
"""
|
||||
把预警配置里的固定岗位收成收件人。
|
||||
|
||||
核心逻辑:没选人或没绑企微都记失败。不使用代码里的姓名兜底。
|
||||
Args:
|
||||
slot: to 或 cc。
|
||||
label: 采购经副理、COO 或总经理。
|
||||
user: 配置指向的系统用户。空表示未选。
|
||||
missing_error: 未选人时的失败原因。
|
||||
Returns:
|
||||
一名收件人。
|
||||
"""
|
||||
if user is None:
|
||||
return make_person(slot=slot, label=label, error=missing_error)
|
||||
return resolve_account(
|
||||
slot=slot,
|
||||
label=label,
|
||||
name=_user_name(user),
|
||||
job_num="configured",
|
||||
user=user,
|
||||
missing_job_error=missing_error,
|
||||
)
|
||||
|
||||
|
||||
def assemble_tier(
|
||||
*,
|
||||
tier: int,
|
||||
threshold_days: int,
|
||||
to_people: list[dict[str, Any]],
|
||||
cc_people: list[dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
把一档的主送和抄送收成一条发送记录草稿。
|
||||
|
||||
核心逻辑:同一人同时出现在主送和抄送时只留主送。至少有一名可发的人则为待发送,否则整档失败。
|
||||
失败原因留在记录上,不把名额转给别人。
|
||||
Args:
|
||||
tier: 1 到 4。
|
||||
threshold_days: 这一档的天数。
|
||||
to_people: 主送。
|
||||
cc_people: 抄送。
|
||||
Returns:
|
||||
tier、threshold_days、to_text、cc_text、recipients、status、error_message。
|
||||
"""
|
||||
primary = _dedupe(to_people)
|
||||
copied = _drop_already_primary(_dedupe(cc_people), primary)
|
||||
recipients = primary + copied
|
||||
errors = [item["error"] for item in recipients if item.get("error")]
|
||||
ready = any(item.get("wecom_userid") and not item.get("error") for item in recipients)
|
||||
return {
|
||||
"tier": tier,
|
||||
"threshold_days": threshold_days,
|
||||
"to_text": _names(primary) or None,
|
||||
"cc_text": _names(copied) or None,
|
||||
"recipients": recipients,
|
||||
"status": "pending" if ready else "failed",
|
||||
"error_message": ";".join(errors) or None,
|
||||
}
|
||||
|
||||
|
||||
def _dedupe(people: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""同一系统用户或同一 OA 人员只留第一次。解析失败的行各自保留。"""
|
||||
seen: set[tuple[Any, ...]] = set()
|
||||
kept: list[dict[str, Any]] = []
|
||||
for person in people:
|
||||
if person.get("user_id"):
|
||||
key: tuple[Any, ...] = ("user", person["user_id"])
|
||||
elif person.get("oa_employee_id") and not person.get("error"):
|
||||
key = ("oa", person["oa_employee_id"])
|
||||
else:
|
||||
key = ("error", person.get("label"), person.get("name"), person.get("error"))
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
kept.append(person)
|
||||
return kept
|
||||
|
||||
|
||||
def _drop_already_primary(copied: list[dict[str, Any]], primary: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""抄送里已经是主送的人不再重复。"""
|
||||
keys = {_identity(person) for person in primary}
|
||||
return [person for person in copied if _identity(person) not in keys]
|
||||
|
||||
|
||||
def _identity(person: dict[str, Any]) -> tuple[Any, ...]:
|
||||
"""用系统用户或 OA 人员识别同一个人。失败行用原因区分。"""
|
||||
if person.get("user_id"):
|
||||
return ("user", person["user_id"])
|
||||
if person.get("oa_employee_id") and not person.get("error"):
|
||||
return ("oa", person["oa_employee_id"])
|
||||
return ("error", person.get("label"), person.get("name"), person.get("error"))
|
||||
|
||||
|
||||
def _names(people: list[dict[str, Any]]) -> str:
|
||||
"""只拼接解析成功的姓名。"""
|
||||
return "、".join(str(person["name"]) for person in people if person.get("name") and not person.get("error"))
|
||||
|
||||
|
||||
def _user_name(user: Any) -> str | None:
|
||||
"""系统用户展示名:真实姓名优先,其次用户名。"""
|
||||
real_name = str(getattr(user, "real_name", None) or "").strip()
|
||||
if real_name:
|
||||
return real_name
|
||||
username = str(getattr(user, "username", None) or "").strip()
|
||||
return username or None
|
||||
@@ -0,0 +1,682 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/alert_service.py
|
||||
|
||||
用途:每日扫描生成设备验收待发送记录,并在周五按收件人发送企业微信。
|
||||
依赖:同步服务、OA 人员目录、alert_plan、alert_notice、发送记录模型、企微通知。
|
||||
逻辑:扫描先同步 E10,再按停留天数跨档。第 4 轮关闭时不生成、也不发送总经理那一轮。
|
||||
周五按收件人发一条汇总卡片,紧跟着一份 Excel。卡片和文件都成功才算已发送。停表取消未发送记录。已发送的不重发、不改收件人。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from app.extensions import db
|
||||
from app.models.equipment_acceptance import (
|
||||
EquipmentAcceptanceNode,
|
||||
EquipmentAcceptanceOperator,
|
||||
EquipmentAcceptanceOrder,
|
||||
EquipmentAcceptanceSendFile,
|
||||
EquipmentAcceptanceSendRecord,
|
||||
EquipmentAcceptanceSetting,
|
||||
)
|
||||
from app.models.user import User
|
||||
from app.services.equipment_acceptance.alert_notice import (
|
||||
NOTICE_FILE_NAME,
|
||||
build_notice_workbook,
|
||||
summary_message,
|
||||
)
|
||||
from app.services.equipment_acceptance.alert_plan import (
|
||||
assemble_tier,
|
||||
due_tiers,
|
||||
make_person,
|
||||
resolve_account,
|
||||
resolve_configured_user,
|
||||
)
|
||||
from app.services.equipment_acceptance.config_service import is_round_4_enabled, reminder_days
|
||||
from app.services.equipment_acceptance.snapshot_rules import WATCHING
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
_SETTING_ID = 1
|
||||
_EVENT = "equipment_acceptance_warning"
|
||||
_UNSENT = ("pending", "failed")
|
||||
|
||||
|
||||
def generate_alerts() -> dict[str, Any]:
|
||||
"""
|
||||
同步 E10 后生成或更新待发送记录。
|
||||
|
||||
核心逻辑:先拉最新节点和停表状态,再按当前处理人解析收件人。本函数不发企业微信。
|
||||
Returns:
|
||||
sync 摘要,以及 created、updated、cancelled 条数。
|
||||
"""
|
||||
from app.services.equipment_acceptance.sync_service import sync_acceptance_snapshots
|
||||
|
||||
sync_result = sync_acceptance_snapshots()
|
||||
summary = refresh_pending_alerts()
|
||||
# 同步提交时已经取消的未发送,刷新阶段不会再数到,这里加回去。
|
||||
summary["cancelled"] += int(sync_result.get("cancelled") or 0)
|
||||
summary["sync"] = sync_result
|
||||
return summary
|
||||
|
||||
|
||||
def refresh_pending_alerts(
|
||||
*,
|
||||
directory: tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
按本地快照刷新待发送记录。
|
||||
|
||||
核心逻辑:计时中的单据跨过哪一档就保留哪一档。第 4 轮关闭时最高只到第 3 档。已发送和已取消不改。
|
||||
未计时或已停表的单据,把还没发出的记录改成已取消。
|
||||
Args:
|
||||
directory: 测试注入的人员目录和经副理。空则查询 E10。
|
||||
Returns:
|
||||
created、updated、cancelled。
|
||||
"""
|
||||
orders = db.session.query(EquipmentAcceptanceOrder).all()
|
||||
operators = _operators_by_order([order.id for order in orders])
|
||||
people, deputies = directory if directory is not None else _load_directory(orders, operators)
|
||||
users_by_job = _users_by_job(_job_numbers(orders, operators, people, deputies))
|
||||
roles = _configured_users()
|
||||
thresholds = reminder_days()
|
||||
max_tier = 4 if is_round_4_enabled() else 3
|
||||
existing = {
|
||||
(row.order_id, row.tier): row
|
||||
for row in db.session.query(EquipmentAcceptanceSendRecord).all()
|
||||
if row.order_id is not None
|
||||
}
|
||||
created = 0
|
||||
updated = 0
|
||||
cancelled = 0
|
||||
for order in orders:
|
||||
if order.monitor_status != WATCHING:
|
||||
cancelled += cancel_unsent(order.id)
|
||||
continue
|
||||
for draft in _drafts(
|
||||
order,
|
||||
operators.get(order.id, []),
|
||||
people,
|
||||
deputies,
|
||||
users_by_job,
|
||||
roles,
|
||||
thresholds,
|
||||
max_tier=max_tier,
|
||||
):
|
||||
current = existing.get((order.id, draft["tier"]))
|
||||
if current is not None and current.status in ("sent", "cancelled"):
|
||||
continue
|
||||
if current is None:
|
||||
current = EquipmentAcceptanceSendRecord(
|
||||
order_id=order.id,
|
||||
tier=draft["tier"],
|
||||
threshold_days=draft["threshold_days"],
|
||||
status=draft["status"],
|
||||
created_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(current)
|
||||
existing[(order.id, draft["tier"])] = current
|
||||
created += 1
|
||||
else:
|
||||
updated += 1
|
||||
_apply_draft(current, order, draft)
|
||||
db.session.commit()
|
||||
return {"created": created, "updated": updated, "cancelled": cancelled}
|
||||
|
||||
|
||||
def cancel_unsent(order_id: int) -> int:
|
||||
"""
|
||||
取消一张验收单上还没发出的预警。
|
||||
|
||||
核心逻辑:待发送和解析失败都还没出企业微信,停表后改成已取消。已发送的保留。
|
||||
Args:
|
||||
order_id: 本地验收单主键。
|
||||
Returns:
|
||||
改成已取消的行数。
|
||||
"""
|
||||
rows = (
|
||||
db.session.query(EquipmentAcceptanceSendRecord)
|
||||
.filter(
|
||||
EquipmentAcceptanceSendRecord.order_id == order_id,
|
||||
EquipmentAcceptanceSendRecord.status.in_(_UNSENT),
|
||||
EquipmentAcceptanceSendRecord.sent_at.is_(None),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for row in rows:
|
||||
row.status = "cancelled"
|
||||
return len(rows)
|
||||
|
||||
|
||||
def send_pending_alerts() -> dict[str, Any]:
|
||||
"""
|
||||
把待发送记录按收件人合并成一条企业微信。
|
||||
|
||||
核心逻辑:同一个人本轮只收一条汇总卡片和一份 Excel。卡片只写张数,明细在文件里。
|
||||
解析失败的人不改发给别人。已取消和已发送不参与。
|
||||
第 4 轮关闭时,已生成的待发送第 4 轮也不发出,避免通知总经理。
|
||||
卡片或附件任一失败都记失败原因,并打一条 warning 日志。
|
||||
每位收件人的 Excel 都写入 equipment_acceptance_send_files,发送失败也保留。
|
||||
Returns:
|
||||
成功人数、失败人数,以及对应的记录条数。
|
||||
"""
|
||||
from app.models import Agent
|
||||
from app.services.integrations.wecom.notify import (
|
||||
send_wecom_event_message,
|
||||
send_wecom_file_message,
|
||||
upload_wecom_temp_media,
|
||||
)
|
||||
|
||||
rows = (
|
||||
db.session.query(EquipmentAcceptanceSendRecord)
|
||||
.filter(EquipmentAcceptanceSendRecord.status == "pending")
|
||||
.all()
|
||||
)
|
||||
if not is_round_4_enabled():
|
||||
rows = [row for row in rows if row.tier != 4]
|
||||
orders = {
|
||||
order.id: order
|
||||
for order in db.session.query(EquipmentAcceptanceOrder)
|
||||
.filter(EquipmentAcceptanceOrder.id.in_([row.order_id for row in rows if row.order_id]))
|
||||
.all()
|
||||
} if rows else {}
|
||||
order_ids = [row.order_id for row in rows if row.order_id]
|
||||
nodes = _nodes_by_order(order_ids)
|
||||
operators = _operators_by_order(order_ids)
|
||||
users = _users_by_id(_recipient_user_ids(rows))
|
||||
buckets: dict[str, list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]]] = {}
|
||||
for row in rows:
|
||||
for person in list(row.recipients_json or []):
|
||||
wecom_id = str(person.get("wecom_userid") or "").strip()
|
||||
if person.get("error") or not wecom_id:
|
||||
continue
|
||||
buckets.setdefault(wecom_id, []).append((row, person))
|
||||
agent = db.session.query(Agent).filter_by(agent_code="equipment_acceptance", is_active=True).first()
|
||||
jump_path = f"/chat/{agent.id}" if agent is not None else "/workspace"
|
||||
jump_params = {"view": "sends"} if agent is not None else None
|
||||
sent_ids: set[str] = set()
|
||||
failed_reasons: dict[str, str] = {}
|
||||
for wecom_id, entries in buckets.items():
|
||||
user = _audit_user(entries, users)
|
||||
lines = _notice_lines(entries, orders, nodes, operators)
|
||||
workbook = build_notice_workbook(lines)
|
||||
archived = _archive_send_file(user, entries, workbook)
|
||||
failure = ""
|
||||
try:
|
||||
result = send_wecom_event_message(
|
||||
event_type=_EVENT,
|
||||
user=user,
|
||||
title="设备验收停留提醒",
|
||||
content=summary_message(lines),
|
||||
jump_path=jump_path,
|
||||
jump_params=jump_params,
|
||||
wecom_userid=wecom_id,
|
||||
)
|
||||
except Exception:
|
||||
_LOGGER.exception("equipment acceptance wecom send failed")
|
||||
failure = "企业微信发送异常"
|
||||
result = {}
|
||||
if not failure and not result.get("ok"):
|
||||
failure = _wecom_failure_text(result)
|
||||
_LOGGER.warning(
|
||||
"equipment acceptance wecom send failed reason=%s trace_id=%s detail=%s",
|
||||
result.get("reason"),
|
||||
result.get("trace_id"),
|
||||
failure,
|
||||
)
|
||||
if not failure:
|
||||
try:
|
||||
media_id = upload_wecom_temp_media(workbook, archived.excel_file_name or NOTICE_FILE_NAME)
|
||||
file_result = send_wecom_file_message(wecom_id, media_id)
|
||||
except Exception:
|
||||
_LOGGER.exception("equipment acceptance wecom file upload failed")
|
||||
failure = "企业微信附件上传失败"
|
||||
file_result = {}
|
||||
if not failure and file_result.get("errcode") != 0:
|
||||
failure = _file_failure_text(file_result)
|
||||
_LOGGER.warning(
|
||||
"equipment acceptance wecom file failed errcode=%s errmsg=%s",
|
||||
file_result.get("errcode"),
|
||||
failure,
|
||||
)
|
||||
if failure:
|
||||
failed_reasons[wecom_id] = failure
|
||||
archived.status = "failed"
|
||||
archived.error_message = failure
|
||||
else:
|
||||
sent_ids.add(wecom_id)
|
||||
archived.status = "sent"
|
||||
archived.sent_at = datetime.utcnow()
|
||||
records_sent = 0
|
||||
records_failed = 0
|
||||
now = datetime.utcnow()
|
||||
for row in rows:
|
||||
ready = {
|
||||
str(person.get("wecom_userid") or "").strip()
|
||||
for person in list(row.recipients_json or [])
|
||||
if person.get("wecom_userid") and not person.get("error")
|
||||
}
|
||||
ready.discard("")
|
||||
if not ready:
|
||||
continue
|
||||
hit = [failed_reasons[item] for item in ready if item in failed_reasons]
|
||||
if hit:
|
||||
row.status = "failed"
|
||||
row.error_message = _join_error(row.error_message, ";".join(dict.fromkeys(hit)))
|
||||
records_failed += 1
|
||||
elif ready <= sent_ids:
|
||||
row.status = "sent"
|
||||
row.sent_at = now
|
||||
records_sent += 1
|
||||
db.session.commit()
|
||||
return {
|
||||
"sent": len(sent_ids),
|
||||
"failed": len(failed_reasons),
|
||||
"records_sent": records_sent,
|
||||
"records_failed": records_failed,
|
||||
}
|
||||
|
||||
|
||||
def _drafts(
|
||||
order: EquipmentAcceptanceOrder,
|
||||
operators: list[EquipmentAcceptanceOperator],
|
||||
people: dict[int, dict[str, Any]],
|
||||
deputies: dict[str, list[dict[str, Any]]],
|
||||
users_by_job: dict[str, User],
|
||||
roles: dict[str, User | None],
|
||||
thresholds: tuple[int, int, int, int],
|
||||
*,
|
||||
max_tier: int = 4,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""按当前处理人展开已经跨过、且配置允许的档。第 4 轮关闭时最高到第 3 档。"""
|
||||
due = due_tiers(order.dwell_days, thresholds, max_tier=max_tier)
|
||||
if not due:
|
||||
return []
|
||||
handlers: list[dict[str, Any]] = []
|
||||
supervisors: list[dict[str, Any]] = []
|
||||
deputy_people: list[dict[str, Any]] = []
|
||||
if not operators:
|
||||
handlers.append(make_person(slot="to", label="当前处理人", error="没有当前处理人"))
|
||||
deputy_people.append(make_person(slot="to", label="经副理", error="没有当前处理人,查不到经副理"))
|
||||
for operator in operators:
|
||||
fact = people.get(operator.user_id) or {}
|
||||
name = fact.get("name") or operator.handler_name
|
||||
job_num = fact.get("job_num") or operator.handler_job_num
|
||||
shown = name or "处理人"
|
||||
handlers.append(resolve_account(
|
||||
slot="to",
|
||||
label="当前处理人",
|
||||
name=name,
|
||||
job_num=job_num,
|
||||
user=users_by_job.get(str(job_num or "")),
|
||||
missing_job_error=f"{shown}没有工号",
|
||||
oa_employee_id=operator.user_id,
|
||||
))
|
||||
superior_id = fact.get("superior_id")
|
||||
if superior_id is None:
|
||||
supervisors.append(make_person(slot="cc", label="直接主管", name=name, error=f"{shown}没有直接主管"))
|
||||
else:
|
||||
supervisors.append(resolve_account(
|
||||
slot="cc",
|
||||
label="直接主管",
|
||||
name=fact.get("superior_name"),
|
||||
job_num=fact.get("superior_job_num"),
|
||||
user=users_by_job.get(str(fact.get("superior_job_num") or "")),
|
||||
missing_job_error=f"{shown}的直接主管没有工号",
|
||||
oa_employee_id=superior_id,
|
||||
))
|
||||
found = deputies.get(str(fact.get("department_id") or ""), [])
|
||||
if not found:
|
||||
deputy_people.append(make_person(slot="to", label="经副理", name=name, error=f"{shown}没有经副理"))
|
||||
else:
|
||||
for item in found:
|
||||
deputy_people.append(resolve_account(
|
||||
slot="to",
|
||||
label="经副理",
|
||||
name=item.get("name"),
|
||||
job_num=item.get("job_num"),
|
||||
user=users_by_job.get(str(item.get("job_num") or "")),
|
||||
missing_job_error=f"{shown}的经副理没有工号",
|
||||
oa_employee_id=item.get("oa_id"),
|
||||
))
|
||||
applicant_fact = people.get(order.applicant_oa_id) if order.applicant_oa_id else None
|
||||
applicant = resolve_account(
|
||||
slot="cc",
|
||||
label="采购担当",
|
||||
name=(applicant_fact or {}).get("name") or order.applicant_name,
|
||||
job_num=(applicant_fact or {}).get("job_num") or order.applicant_job_num,
|
||||
user=users_by_job.get(str(((applicant_fact or {}).get("job_num") or order.applicant_job_num) or "")),
|
||||
missing_job_error="没有申请人工号",
|
||||
oa_employee_id=order.applicant_oa_id,
|
||||
)
|
||||
drafts: list[dict[str, Any]] = []
|
||||
if 1 in due:
|
||||
drafts.append(assemble_tier(
|
||||
tier=1,
|
||||
threshold_days=thresholds[0],
|
||||
to_people=handlers,
|
||||
cc_people=[*supervisors, applicant],
|
||||
))
|
||||
if 2 in due:
|
||||
drafts.append(assemble_tier(
|
||||
tier=2,
|
||||
threshold_days=thresholds[1],
|
||||
to_people=deputy_people,
|
||||
cc_people=[
|
||||
resolve_configured_user(slot="cc", label="COO", user=roles.get("coo"), missing_error="未配置COO"),
|
||||
resolve_configured_user(slot="cc", label="采购经副理", user=roles.get("buyer"), missing_error="未配置采购经副理"),
|
||||
],
|
||||
))
|
||||
if 3 in due:
|
||||
drafts.append(assemble_tier(
|
||||
tier=3,
|
||||
threshold_days=thresholds[2],
|
||||
to_people=[resolve_configured_user(slot="to", label="COO", user=roles.get("coo"), missing_error="未配置COO")],
|
||||
cc_people=[resolve_configured_user(slot="cc", label="采购经副理", user=roles.get("buyer"), missing_error="未配置采购经副理")],
|
||||
))
|
||||
if 4 in due:
|
||||
drafts.append(assemble_tier(
|
||||
tier=4,
|
||||
threshold_days=thresholds[3],
|
||||
to_people=[resolve_configured_user(slot="to", label="总经理", user=roles.get("executive"), missing_error="未配置总经理")],
|
||||
cc_people=[
|
||||
resolve_configured_user(slot="cc", label="COO", user=roles.get("coo"), missing_error="未配置COO"),
|
||||
resolve_configured_user(slot="cc", label="采购经副理", user=roles.get("buyer"), missing_error="未配置采购经副理"),
|
||||
],
|
||||
))
|
||||
return drafts
|
||||
|
||||
|
||||
def _apply_draft(row: EquipmentAcceptanceSendRecord, order: EquipmentAcceptanceOrder, draft: dict[str, Any]) -> None:
|
||||
"""把草稿写进未发送的记录。不改创建时间,也不填发送时间。"""
|
||||
row.acceptance_no = order.acceptance_no
|
||||
row.purchase_order_no = order.purchase_order_no
|
||||
row.threshold_days = draft["threshold_days"]
|
||||
row.to_text = draft["to_text"]
|
||||
row.cc_text = draft["cc_text"]
|
||||
row.recipients_json = draft["recipients"]
|
||||
row.status = draft["status"]
|
||||
row.error_message = draft["error_message"]
|
||||
|
||||
|
||||
def _load_directory(
|
||||
orders: list[EquipmentAcceptanceOrder],
|
||||
operators: dict[int, list[EquipmentAcceptanceOperator]],
|
||||
) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]]:
|
||||
"""向 E10 要当前处理人和申请人的主管、部门、经副理。"""
|
||||
from app.services.equipment_acceptance.oa_repository import fetch_alert_directory
|
||||
|
||||
ids: set[int] = set()
|
||||
for group in operators.values():
|
||||
for operator in group:
|
||||
if operator.user_id:
|
||||
ids.add(operator.user_id)
|
||||
for order in orders:
|
||||
if order.monitor_status == WATCHING and order.applicant_oa_id:
|
||||
ids.add(order.applicant_oa_id)
|
||||
return fetch_alert_directory(sorted(ids))
|
||||
|
||||
|
||||
def _job_numbers(
|
||||
orders: list[EquipmentAcceptanceOrder],
|
||||
operators: dict[int, list[EquipmentAcceptanceOperator]],
|
||||
people: dict[int, dict[str, Any]],
|
||||
deputies: dict[str, list[dict[str, Any]]],
|
||||
) -> set[str]:
|
||||
"""收集要对系统用户的工号。"""
|
||||
found: set[str] = set()
|
||||
for order in orders:
|
||||
if order.applicant_job_num:
|
||||
found.add(order.applicant_job_num)
|
||||
for group in operators.values():
|
||||
for operator in group:
|
||||
if operator.handler_job_num:
|
||||
found.add(operator.handler_job_num)
|
||||
for fact in people.values():
|
||||
if fact.get("job_num"):
|
||||
found.add(str(fact["job_num"]))
|
||||
if fact.get("superior_job_num"):
|
||||
found.add(str(fact["superior_job_num"]))
|
||||
for group in deputies.values():
|
||||
for item in group:
|
||||
if item.get("job_num"):
|
||||
found.add(str(item["job_num"]))
|
||||
return found
|
||||
|
||||
|
||||
def _users_by_job(job_nums: set[str]) -> dict[str, User]:
|
||||
"""用工号索引系统用户。"""
|
||||
if not job_nums:
|
||||
return {}
|
||||
rows = db.session.query(User).filter(User.employee_id.in_(job_nums)).all()
|
||||
return {str(row.employee_id): row for row in rows if row.employee_id}
|
||||
|
||||
|
||||
def _configured_users() -> dict[str, User | None]:
|
||||
"""读取三个固定岗位。没选时对应值是空。"""
|
||||
setting = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
|
||||
ids = []
|
||||
if setting is not None:
|
||||
ids = [item for item in (setting.buyer_manager_user_id, setting.coo_user_id, setting.executive_user_id) if item]
|
||||
found = _users_by_id(ids)
|
||||
if setting is None:
|
||||
return {"buyer": None, "coo": None, "executive": None}
|
||||
return {
|
||||
"buyer": found.get(setting.buyer_manager_user_id or 0),
|
||||
"coo": found.get(setting.coo_user_id or 0),
|
||||
"executive": found.get(setting.executive_user_id or 0),
|
||||
}
|
||||
|
||||
|
||||
def _users_by_id(user_ids: list[int]) -> dict[int, User]:
|
||||
"""按主键取出系统用户。"""
|
||||
if not user_ids:
|
||||
return {}
|
||||
rows = db.session.query(User).filter(User.id.in_(user_ids)).all()
|
||||
return {row.id: row for row in rows}
|
||||
|
||||
|
||||
def _nodes_by_order(order_ids: list[int]) -> dict[int, list[EquipmentAcceptanceNode]]:
|
||||
"""取出这些验收单的当前节点名称。"""
|
||||
if not order_ids:
|
||||
return {}
|
||||
grouped: dict[int, list[EquipmentAcceptanceNode]] = {}
|
||||
rows = (
|
||||
db.session.query(EquipmentAcceptanceNode)
|
||||
.filter(EquipmentAcceptanceNode.order_id.in_(order_ids))
|
||||
.all()
|
||||
)
|
||||
for row in rows:
|
||||
grouped.setdefault(row.order_id, []).append(row)
|
||||
return grouped
|
||||
|
||||
|
||||
def _operators_by_order(order_ids: list[int]) -> dict[int, list[EquipmentAcceptanceOperator]]:
|
||||
"""取出这些验收单的当前处理人。"""
|
||||
if not order_ids:
|
||||
return {}
|
||||
grouped: dict[int, list[EquipmentAcceptanceOperator]] = {}
|
||||
rows = (
|
||||
db.session.query(EquipmentAcceptanceOperator)
|
||||
.filter(EquipmentAcceptanceOperator.order_id.in_(order_ids))
|
||||
.all()
|
||||
)
|
||||
for row in rows:
|
||||
grouped.setdefault(row.order_id, []).append(row)
|
||||
return grouped
|
||||
|
||||
|
||||
def _recipient_user_ids(rows: list[EquipmentAcceptanceSendRecord]) -> list[int]:
|
||||
"""从待发送收件人里取出系统用户主键。"""
|
||||
found: list[int] = []
|
||||
for row in rows:
|
||||
for person in list(row.recipients_json or []):
|
||||
if person.get("user_id"):
|
||||
found.append(int(person["user_id"]))
|
||||
return found
|
||||
|
||||
|
||||
def _audit_user(
|
||||
entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]],
|
||||
users: dict[int, User],
|
||||
) -> User | None:
|
||||
"""取这名收件人在系统里的账号,供企微审计。没有账号时仍按企微 userid 发送。"""
|
||||
for _row, person in entries:
|
||||
user_id = person.get("user_id")
|
||||
if user_id and int(user_id) in users:
|
||||
return users[int(user_id)]
|
||||
return None
|
||||
|
||||
|
||||
def _archive_send_file(
|
||||
user: User | None,
|
||||
entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]],
|
||||
workbook: bytes,
|
||||
) -> EquipmentAcceptanceSendFile:
|
||||
"""
|
||||
把这次准备发给一名收件人的 Excel 先落库。
|
||||
|
||||
核心逻辑:发送成功或失败都保留同一份字节,并记下里面的发送记录,供表格列下载。不保存企微 userid。
|
||||
Args:
|
||||
user: 系统用户。对不上账号时只留姓名。
|
||||
entries: 这名收件人的发送记录和席位,用来取展示名。
|
||||
workbook: xlsx 字节。
|
||||
Returns:
|
||||
已加入当前事务、尚未提交的文件行。
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
name = _recipient_display_name(user, entries)
|
||||
row = EquipmentAcceptanceSendFile(
|
||||
recipient_user_id=None if user is None else user.id,
|
||||
recipient_name=name or None,
|
||||
excel_file_name=_archive_file_name(name, now),
|
||||
excel_file_data=workbook,
|
||||
excel_file_size=len(workbook),
|
||||
send_record_ids=[row.id for row, _person in entries if row.id],
|
||||
status="pending",
|
||||
created_at=now,
|
||||
)
|
||||
db.session.add(row)
|
||||
return row
|
||||
|
||||
|
||||
def _recipient_display_name(
|
||||
user: User | None,
|
||||
entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]],
|
||||
) -> str:
|
||||
"""优先用系统姓名,没有账号时用收件人席位上的名字。"""
|
||||
if user is not None:
|
||||
named = str(user.real_name or user.username or "").strip()
|
||||
if named:
|
||||
return named
|
||||
for _row, person in entries:
|
||||
named = str(person.get("name") or "").strip()
|
||||
if named:
|
||||
return named
|
||||
return ""
|
||||
|
||||
|
||||
def _archive_file_name(recipient_name: str, moment: datetime) -> str:
|
||||
"""文件名带上海日期和收件人,避免多次发送都叫同一个名字。"""
|
||||
local = moment.replace(tzinfo=ZoneInfo("UTC")).astimezone(ZoneInfo("Asia/Shanghai"))
|
||||
safe = "".join(char for char in recipient_name if char not in '\\/:*?"<>|').strip() or "收件人"
|
||||
return f"设备验收停留提醒-{local:%Y%m%d}-{safe}.xlsx"[:255]
|
||||
|
||||
|
||||
def _notice_lines(
|
||||
entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]],
|
||||
orders: dict[int, EquipmentAcceptanceOrder],
|
||||
nodes: dict[int, list[EquipmentAcceptanceNode]],
|
||||
operators: dict[int, list[EquipmentAcceptanceOperator]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
把一名收件人的发送记录收成 Excel 行。
|
||||
|
||||
核心逻辑:同一条发送记录只占一行。通知身份用角色名,例如当前处理人、直接主管,不写主送或抄送。
|
||||
Args:
|
||||
entries: 这名收件人挂到的发送记录和对应席位。
|
||||
orders: 验收单主键到快照。
|
||||
nodes: 验收单主键到当前节点。
|
||||
operators: 验收单主键到当前处理人。
|
||||
Returns:
|
||||
传给汇总文案和 Excel 的明细行。
|
||||
"""
|
||||
grouped: dict[int, dict[str, Any]] = {}
|
||||
order_keys: list[int] = []
|
||||
for row, person in entries:
|
||||
label = str(person.get("label") or "").strip()
|
||||
bucket = grouped.get(row.id)
|
||||
if bucket is None:
|
||||
bucket = {"row": row, "labels": []}
|
||||
grouped[row.id] = bucket
|
||||
order_keys.append(row.id)
|
||||
if label and label not in bucket["labels"]:
|
||||
bucket["labels"].append(label)
|
||||
lines: list[dict[str, Any]] = []
|
||||
for key in order_keys:
|
||||
row = grouped[key]["row"]
|
||||
order = orders.get(row.order_id or 0)
|
||||
node_names = _unique_text(node.node_name for node in nodes.get(row.order_id or 0, []))
|
||||
handler_names = _unique_text(operator.handler_name for operator in operators.get(row.order_id or 0, []))
|
||||
lines.append({
|
||||
"acceptance_no": row.acceptance_no,
|
||||
"purchase_order_no": row.purchase_order_no,
|
||||
"applicant": None if order is None else order.applicant_name,
|
||||
"threshold_days": row.threshold_days,
|
||||
"dwell_days": None if order is None else order.dwell_days,
|
||||
"node_name": "、".join(node_names),
|
||||
"handlers": "、".join(handler_names),
|
||||
"identity": "、".join(grouped[key]["labels"]),
|
||||
})
|
||||
return lines
|
||||
|
||||
|
||||
def _unique_text(values) -> list[str]:
|
||||
"""按出现顺序去掉空白和重复名称。"""
|
||||
found: list[str] = []
|
||||
for value in values:
|
||||
text = str(value or "").strip()
|
||||
if text and text not in found:
|
||||
found.append(text)
|
||||
return found
|
||||
|
||||
|
||||
def _file_failure_text(result: dict[str, Any]) -> str:
|
||||
"""把企微文件消息的返回收成失败原因。不写入 userid。"""
|
||||
code = result.get("errcode")
|
||||
message = str(result.get("errmsg") or "").strip()
|
||||
text = f"企业微信附件发送失败 {code} {message}".strip()
|
||||
return text[:255]
|
||||
|
||||
|
||||
def _wecom_failure_text(result: dict[str, Any]) -> str:
|
||||
"""把企微发送结果收成页面和日志都能看的失败原因。不写入 userid。"""
|
||||
reason = str(result.get("reason") or "")
|
||||
if reason == "notify_disabled":
|
||||
return "企业微信通知总开关已关闭"
|
||||
if reason == "event_disabled":
|
||||
return "未开启设备验收预警的企业微信事件"
|
||||
if reason == "user_unbound":
|
||||
return "收件人未绑定企业微信"
|
||||
raw = result.get("raw") if isinstance(result.get("raw"), dict) else {}
|
||||
if reason == "send_failed":
|
||||
code = raw.get("errcode")
|
||||
message = str(raw.get("errmsg") or "").strip()
|
||||
text = f"企业微信返回 {code} {message}".strip()
|
||||
return text[:255]
|
||||
if reason == "exception":
|
||||
return "企业微信发送异常"
|
||||
return "企业微信发送失败"
|
||||
|
||||
|
||||
def _join_error(current: str | None, extra: str) -> str:
|
||||
"""把新的失败原因接在原有原因后面。相同句子不重复。"""
|
||||
parts = [part for part in (current, extra) if part]
|
||||
unique: list[str] = []
|
||||
for part in parts:
|
||||
if part not in unique:
|
||||
unique.append(part)
|
||||
return ";".join(unique)
|
||||
@@ -0,0 +1,245 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/config_service.py
|
||||
|
||||
用途:读写设备验收预警配置:四档天数、第 4 轮开关和三个固定岗位。
|
||||
依赖:extensions.db、EquipmentAcceptanceSetting、User、统一错误。
|
||||
逻辑:配置页和停留列表调用。岗位只存系统用户主键。发送时刻不在这里,由排程 Cron 决定。
|
||||
没有配置行时按冻结默认值 30/37/44/51 返回,第 4 轮默认关闭,不把姓名写进代码。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.core.response import utc_iso
|
||||
from app.extensions import db
|
||||
from app.models.equipment_acceptance import EquipmentAcceptanceSetting
|
||||
from app.models.user import User
|
||||
from app.services.equipment_acceptance.snapshot_rules import FIRST_REMINDER_DAY
|
||||
|
||||
DEFAULT_REMINDER_DAYS = (FIRST_REMINDER_DAY, 37, 44, 51)
|
||||
_SETTING_ID = 1
|
||||
_ROLE_FIELDS = (
|
||||
"buyer_manager_user_id",
|
||||
"coo_user_id",
|
||||
"executive_user_id",
|
||||
)
|
||||
_MAX_DAY = 3650
|
||||
|
||||
|
||||
def is_round_4_enabled() -> bool:
|
||||
"""
|
||||
读取第 4 轮是否启用。
|
||||
|
||||
核心逻辑:没有配置行或字段为假时关闭。关闭后扫描不生成、发送不推出总经理那一轮。
|
||||
Returns:
|
||||
启用为 True。
|
||||
"""
|
||||
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
|
||||
if row is None:
|
||||
return False
|
||||
return bool(row.round_4_enabled)
|
||||
|
||||
|
||||
def parse_round_4_enabled(raw: Any) -> bool:
|
||||
"""
|
||||
校验第 4 轮开关。
|
||||
|
||||
核心逻辑:缺省按关闭处理,避免旧请求误打开总经理提醒。传入值必须是布尔。
|
||||
Args:
|
||||
raw: 接口里的 round_4_enabled。缺省为 None。
|
||||
Returns:
|
||||
是否启用第 4 轮。
|
||||
|
||||
Raises:
|
||||
ValidationError: 传入了布尔以外的值。
|
||||
"""
|
||||
if raw is None:
|
||||
return False
|
||||
if not isinstance(raw, bool):
|
||||
raise ValidationError(
|
||||
"第 4 轮开关必须是是否启用",
|
||||
code="EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID",
|
||||
details={"field": "round_4_enabled"},
|
||||
)
|
||||
return raw
|
||||
|
||||
|
||||
def reminder_days() -> tuple[int, int, int, int]:
|
||||
"""
|
||||
读取四档天数。
|
||||
|
||||
核心逻辑:没有配置行时用冻结默认值。扫描用这四个数判断有没有跨档。
|
||||
Returns:
|
||||
四个逐档增大的正整数。
|
||||
"""
|
||||
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
|
||||
if row is None:
|
||||
return DEFAULT_REMINDER_DAYS
|
||||
return (int(row.day_1), int(row.day_2), int(row.day_3), int(row.day_4))
|
||||
|
||||
|
||||
def first_reminder_day() -> int:
|
||||
"""
|
||||
读取第 1 档天数,供停留列表判断已逾期。
|
||||
|
||||
核心逻辑:没有配置行时用冻结默认值,避免列表在未保存配置前失去阈值。
|
||||
Returns:
|
||||
正整数天数。
|
||||
"""
|
||||
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
|
||||
if row is None:
|
||||
return DEFAULT_REMINDER_DAYS[0]
|
||||
return int(row.day_1)
|
||||
|
||||
|
||||
def get_acceptance_config(*, include_candidates: bool) -> dict[str, Any]:
|
||||
"""
|
||||
组装配置页数据。
|
||||
|
||||
核心逻辑:天数和已选用户谁都能看。候选人名单只给平台管理员,避免把全员目录交给普通用户。
|
||||
Args:
|
||||
include_candidates: 为 True 时附带在职用户,供选人弹窗使用。
|
||||
Returns:
|
||||
days、第 4 轮开关、三个岗位用户主键、已选用户、候选人和更新时间。
|
||||
"""
|
||||
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
|
||||
selected_ids = _selected_ids(row)
|
||||
return {
|
||||
"days": list(_days_of(row)),
|
||||
"round_4_enabled": False if row is None else bool(row.round_4_enabled),
|
||||
"buyer_manager_user_id": None if row is None else row.buyer_manager_user_id,
|
||||
"coo_user_id": None if row is None else row.coo_user_id,
|
||||
"executive_user_id": None if row is None else row.executive_user_id,
|
||||
"selected_users": _briefs(selected_ids),
|
||||
"users": _candidate_users() if include_candidates else [],
|
||||
"updated_at": None if row is None else utc_iso(row.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def save_acceptance_config(payload: dict[str, Any], *, updated_by: int) -> dict[str, Any]:
|
||||
"""
|
||||
保存四档天数、第 4 轮开关和三个岗位用户。
|
||||
|
||||
核心逻辑:天数必须逐档增大。第 4 轮缺省为关闭。岗位为空表示未选;有值时必须是已存在的系统用户。
|
||||
保存后只影响以后的预警,这里不改历史发送记录。已有的待发送第 4 轮在发送时会被跳过。
|
||||
Args:
|
||||
payload: days 为四个整数;round_4_enabled 为布尔;三个岗位字段为用户主键或空。
|
||||
updated_by: 操作人的系统用户主键。
|
||||
Returns:
|
||||
与读取接口相同的配置,并带候选人。
|
||||
|
||||
Raises:
|
||||
ValidationError: 天数不合法,或岗位用户不存在。
|
||||
"""
|
||||
days = validate_reminder_days(payload.get("days"))
|
||||
round_4_enabled = parse_round_4_enabled(payload.get("round_4_enabled"))
|
||||
role_ids = {field: _require_user_id(payload.get(field), field) for field in _ROLE_FIELDS}
|
||||
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
|
||||
if row is None:
|
||||
row = EquipmentAcceptanceSetting(id=_SETTING_ID)
|
||||
db.session.add(row)
|
||||
row.day_1, row.day_2, row.day_3, row.day_4 = days
|
||||
row.round_4_enabled = round_4_enabled
|
||||
row.buyer_manager_user_id = role_ids["buyer_manager_user_id"]
|
||||
row.coo_user_id = role_ids["coo_user_id"]
|
||||
row.executive_user_id = role_ids["executive_user_id"]
|
||||
row.updated_at = datetime.utcnow()
|
||||
row.updated_by = updated_by
|
||||
db.session.commit()
|
||||
return get_acceptance_config(include_candidates=True)
|
||||
|
||||
|
||||
def validate_reminder_days(raw: Any) -> tuple[int, int, int, int]:
|
||||
"""
|
||||
校验四档天数。
|
||||
|
||||
核心逻辑:必须是四个逐档增大的正整数。布尔值在 Python 里也是 int,这里明确拒绝。
|
||||
Args:
|
||||
raw: 接口里的 days。
|
||||
Returns:
|
||||
四个天数。
|
||||
|
||||
Raises:
|
||||
ValidationError: 不是四个逐档增大的天数。
|
||||
"""
|
||||
if not isinstance(raw, list) or len(raw) != 4:
|
||||
_reject_days()
|
||||
parsed: list[int] = []
|
||||
for value in raw:
|
||||
if isinstance(value, bool) or not isinstance(value, int) or value < 1 or value > _MAX_DAY:
|
||||
_reject_days()
|
||||
parsed.append(value)
|
||||
if not (parsed[0] < parsed[1] < parsed[2] < parsed[3]):
|
||||
_reject_days()
|
||||
return parsed[0], parsed[1], parsed[2], parsed[3]
|
||||
|
||||
|
||||
def _reject_days() -> None:
|
||||
"""四档天数不合法时用同一错误码拒绝。"""
|
||||
raise ValidationError(
|
||||
"设备验收预警的四档天数须逐档增大",
|
||||
code="EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID",
|
||||
details={"field": "days"},
|
||||
)
|
||||
|
||||
|
||||
def _require_user_id(raw: Any, field: str) -> int | None:
|
||||
"""空岗位允许保存。有值时必须指向 users 表里的一行。"""
|
||||
if raw is None or raw == "":
|
||||
return None
|
||||
if isinstance(raw, bool) or not isinstance(raw, int) or raw <= 0:
|
||||
raise ValidationError(
|
||||
"设备验收预警岗位必须选择系统用户",
|
||||
code="EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID",
|
||||
details={"field": field},
|
||||
)
|
||||
if db.session.get(User, raw) is None:
|
||||
raise ValidationError(
|
||||
"设备验收预警岗位必须选择系统用户",
|
||||
code="EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID",
|
||||
details={"field": field},
|
||||
)
|
||||
return raw
|
||||
|
||||
|
||||
def _days_of(row: EquipmentAcceptanceSetting | None) -> tuple[int, int, int, int]:
|
||||
"""没有配置行时返回冻结默认值。"""
|
||||
if row is None:
|
||||
return DEFAULT_REMINDER_DAYS
|
||||
return (int(row.day_1), int(row.day_2), int(row.day_3), int(row.day_4))
|
||||
|
||||
|
||||
def _selected_ids(row: EquipmentAcceptanceSetting | None) -> list[int]:
|
||||
"""收集三个岗位里已经选中的用户主键,供姓名回显。"""
|
||||
if row is None:
|
||||
return []
|
||||
return [user_id for user_id in (row.buyer_manager_user_id, row.coo_user_id, row.executive_user_id) if user_id]
|
||||
|
||||
|
||||
def _candidate_users() -> list[dict[str, Any]]:
|
||||
"""在职用户,带部门和企微绑定标记,供选人弹窗分组。"""
|
||||
rows = db.session.query(User).filter(User.status == "active").order_by(User.username).all()
|
||||
return [_user_brief(user) for user in rows]
|
||||
|
||||
|
||||
def _briefs(user_ids: list[int]) -> list[dict[str, Any]]:
|
||||
"""按主键取出已选用户。停用用户也返回,避免页面上只剩一个数字。"""
|
||||
if not user_ids:
|
||||
return []
|
||||
rows = db.session.query(User).filter(User.id.in_(user_ids)).all()
|
||||
return [_user_brief(user) for user in rows]
|
||||
|
||||
|
||||
def _user_brief(user: User) -> dict[str, Any]:
|
||||
"""选人组件要的展示字段。姓名只从用户资料来,不另存一份。"""
|
||||
return {
|
||||
"id": user.id,
|
||||
"username": user.username,
|
||||
"real_name": user.real_name,
|
||||
"employee_id": user.employee_id,
|
||||
"department": user.department,
|
||||
"wecom_bound": bool(user.wecom_userid),
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/oa_repository.py
|
||||
|
||||
用途:只读拉取 E10 验收单、当前节点、操作人,以及直接主管和经副理。
|
||||
依赖:pyodbc、settings、query_sql。不调用 E8 的 OA_SQLSERVER_* 连接。
|
||||
逻辑:先探测实例上的库名,再执行联表查询。经副理矩阵固定在 eteams。查询失败不把连接串写入日志。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
from app.services.equipment_acceptance.query_sql import _qualified, build_acceptance_sql, resolve_catalogs
|
||||
from app.services.equipment_acceptance.snapshot_rules import as_int
|
||||
from app.services.equipment_acceptance.settings import (
|
||||
EquipmentAcceptanceSqlSettings,
|
||||
load_equipment_acceptance_sql_settings,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
# 苏州和信「HXJM-审批矩阵」。取值配置是该矩阵下 config_name 为「经副理」的 id。
|
||||
_MATRIX_TENANT = "temkc46eme"
|
||||
_MATRIX_ID = 1115770797884751874
|
||||
_DEPUTY_CONFIG_ID = 1115771897387991041
|
||||
_MATRIX_CATALOG = "eteams"
|
||||
_PREFERRED_DRIVERS = (
|
||||
"ODBC Driver 18 for SQL Server",
|
||||
"ODBC Driver 17 for SQL Server",
|
||||
"SQL Server",
|
||||
)
|
||||
|
||||
|
||||
def fetch_acceptance_rows() -> list[dict[str, Any]]:
|
||||
"""
|
||||
从 E10 拉验收单联表结果。
|
||||
|
||||
核心逻辑:连接 ecology10 所在实例,按实际库名组装 SQL。不查询 isremark。
|
||||
Returns:
|
||||
字段名为小写别名的字典行。
|
||||
|
||||
Raises:
|
||||
ValidationError: 连接配置不完整,或库名非法。
|
||||
ServiceUnavailableError: 驱动、连接或查询失败。
|
||||
"""
|
||||
settings = load_equipment_acceptance_sql_settings()
|
||||
connection = _open_connection(settings)
|
||||
try:
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SELECT name FROM sys.databases")
|
||||
names = {str(row[0]) for row in cursor.fetchall() if row and row[0]}
|
||||
try:
|
||||
catalogs = resolve_catalogs(
|
||||
names,
|
||||
form=settings.form_catalog or None,
|
||||
employee=settings.employee_catalog or None,
|
||||
request=settings.request_catalog or None,
|
||||
node=settings.node_catalog or None,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(
|
||||
"设备验收同步找不到要查询的数据库",
|
||||
code="EQUIPMENT_ACCEPTANCE.CONFIG_INVALID",
|
||||
details={"reason": str(exc)},
|
||||
) from exc
|
||||
_LOGGER.info(
|
||||
"equipment acceptance catalogs form=%s employee=%s request=%s node=%s",
|
||||
catalogs.form,
|
||||
catalogs.employee,
|
||||
catalogs.request,
|
||||
catalogs.node,
|
||||
)
|
||||
cursor.execute(build_acceptance_sql(catalogs))
|
||||
columns = [str(col[0]).lower() for col in cursor.description]
|
||||
return [
|
||||
{columns[index]: raw[index] for index in range(len(columns))}
|
||||
for raw in cursor.fetchall()
|
||||
]
|
||||
except (ValidationError, ServiceUnavailableError):
|
||||
raise
|
||||
except Exception as exc:
|
||||
_LOGGER.warning("equipment acceptance sql failed error=%s", type(exc).__name__)
|
||||
raise ServiceUnavailableError(
|
||||
"查询 E10 设备验收数据失败",
|
||||
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
|
||||
) from exc
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def _open_connection(settings: EquipmentAcceptanceSqlSettings):
|
||||
"""
|
||||
打开 E10 只读连接。初始库固定为 ecology10,跨库表名在 SQL 里写全。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 没有 pyodbc、没有 ODBC 驱动或连接失败。
|
||||
"""
|
||||
try:
|
||||
import pyodbc
|
||||
except ImportError as exc:
|
||||
raise ServiceUnavailableError(
|
||||
"未安装 pyodbc,无法连接 E10 SQL Server",
|
||||
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
|
||||
) from exc
|
||||
driver = _pick_driver(pyodbc, settings.driver)
|
||||
database = settings.form_catalog or "ecology10"
|
||||
conn_str = (
|
||||
f"DRIVER={{{driver}}};"
|
||||
f"SERVER={settings.host},{settings.port};"
|
||||
f"DATABASE={database};"
|
||||
f"UID={settings.username};"
|
||||
f"PWD={settings.password};"
|
||||
)
|
||||
if driver != "SQL Server":
|
||||
conn_str += f"Encrypt={settings.encrypt};TrustServerCertificate={settings.trust_cert};"
|
||||
try:
|
||||
return pyodbc.connect(conn_str, timeout=settings.timeout)
|
||||
except Exception as exc:
|
||||
_LOGGER.warning("equipment acceptance connect failed error=%s", type(exc).__name__)
|
||||
raise ServiceUnavailableError(
|
||||
"连接 E10 SQL Server 失败",
|
||||
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
|
||||
) from exc
|
||||
|
||||
|
||||
def fetch_alert_directory(employee_ids: list[int]) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]]:
|
||||
"""
|
||||
读取处理人的直接主管,并按部门查出经副理。
|
||||
|
||||
核心逻辑:主管在 employee.SUPERIOR。经副理不在这一列,按部门 ID 走 eteams 矩阵条件表。
|
||||
人员 ID 必须是整数。没有人员时不连库。
|
||||
Args:
|
||||
employee_ids: 当前处理人和申请人的 employee.ID。
|
||||
Returns:
|
||||
(人员字典, 部门 ID 到经副理列表)。人员字典的键是 employee.ID。
|
||||
|
||||
Raises:
|
||||
ValidationError: 库名不合法。
|
||||
ServiceUnavailableError: 连接或查询失败。
|
||||
"""
|
||||
ids = sorted({int(item) for item in employee_ids})
|
||||
if not ids:
|
||||
return {}, {}
|
||||
settings = load_equipment_acceptance_sql_settings()
|
||||
connection = _open_connection(settings)
|
||||
try:
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SELECT name FROM sys.databases")
|
||||
names = {str(row[0]) for row in cursor.fetchall() if row and row[0]}
|
||||
catalogs = resolve_catalogs(
|
||||
names,
|
||||
form=settings.form_catalog or None,
|
||||
employee=settings.employee_catalog or None,
|
||||
request=settings.request_catalog or None,
|
||||
node=settings.node_catalog or None,
|
||||
)
|
||||
employee = _qualified(catalogs.employee, "employee")
|
||||
people = _load_people(cursor, employee, ids)
|
||||
departments = sorted({item["department_id"] for item in people.values() if item.get("department_id")})
|
||||
deputies = _load_deputies(cursor, employee, departments)
|
||||
return people, deputies
|
||||
except (ValidationError, ServiceUnavailableError):
|
||||
raise
|
||||
except Exception as exc:
|
||||
_LOGGER.warning("equipment acceptance directory sql failed error=%s", type(exc).__name__)
|
||||
raise ServiceUnavailableError(
|
||||
"查询 E10 直接主管和经副理失败",
|
||||
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
|
||||
) from exc
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def _load_people(cursor: Any, employee: str, employee_ids: list[int]) -> dict[int, dict[str, Any]]:
|
||||
"""按人员 ID 取出姓名、工号、直接主管和部门。"""
|
||||
found: dict[int, dict[str, Any]] = {}
|
||||
for chunk in _chunks(employee_ids):
|
||||
marks = ",".join("?" for _ in chunk)
|
||||
cursor.execute(
|
||||
f"""
|
||||
SELECT e.ID, e.USERNAME, e.JOB_NUM, e.SUPERIOR, e.DEPARTMENT,
|
||||
sup.USERNAME, sup.JOB_NUM
|
||||
FROM {employee} AS e
|
||||
LEFT JOIN {employee} AS sup ON sup.ID = e.SUPERIOR
|
||||
WHERE e.ID IN ({marks})
|
||||
""",
|
||||
chunk,
|
||||
)
|
||||
for raw in cursor.fetchall():
|
||||
oa_id = as_int(raw[0])
|
||||
if oa_id is None:
|
||||
continue
|
||||
department = _clean(raw[4])
|
||||
found[oa_id] = {
|
||||
"oa_id": oa_id,
|
||||
"name": _clean(raw[1]),
|
||||
"job_num": _clean(raw[2]),
|
||||
"superior_id": as_int(raw[3]),
|
||||
"department_id": department,
|
||||
"superior_name": _clean(raw[5]),
|
||||
"superior_job_num": _clean(raw[6]),
|
||||
}
|
||||
return found
|
||||
|
||||
|
||||
def _load_deputies(cursor: Any, employee: str, department_ids: list[str]) -> dict[str, list[dict[str, Any]]]:
|
||||
"""按部门 ID 字符串查出经副理。部门不在矩阵里时不产生人员。"""
|
||||
found: dict[str, list[dict[str, Any]]] = {}
|
||||
if not department_ids:
|
||||
return found
|
||||
matrix_condition = _qualified(_MATRIX_CATALOG, "hrm_matrix_condition_data")
|
||||
matrix_value = _qualified(_MATRIX_CATALOG, "hrm_matrix_value_data")
|
||||
for chunk in _chunks(department_ids):
|
||||
marks = ",".join("?" for _ in chunk)
|
||||
params: list[Any] = [_DEPUTY_CONFIG_ID, _MATRIX_TENANT, _MATRIX_ID, *_chunk_params(chunk)]
|
||||
cursor.execute(
|
||||
f"""
|
||||
SELECT c.relate_id, v.relate_id, emp.USERNAME, emp.JOB_NUM
|
||||
FROM {matrix_condition} AS c
|
||||
INNER JOIN {matrix_value} AS v
|
||||
ON v.matrix_data_id = c.matrix_data_id
|
||||
AND v.tenant_key = c.tenant_key
|
||||
AND v.matrix_id = c.matrix_id
|
||||
AND v.delete_type = 0
|
||||
AND v.matrix_value_config_id = ?
|
||||
LEFT JOIN {employee} AS emp ON emp.ID = v.relate_id
|
||||
WHERE c.tenant_key = ?
|
||||
AND c.matrix_id = ?
|
||||
AND c.delete_type = 0
|
||||
AND c.relate_id IN ({marks})
|
||||
""",
|
||||
params,
|
||||
)
|
||||
for raw in cursor.fetchall():
|
||||
department_id = _clean(raw[0])
|
||||
person_id = as_int(raw[1])
|
||||
if not department_id or person_id is None:
|
||||
continue
|
||||
found.setdefault(department_id, []).append({
|
||||
"oa_id": person_id,
|
||||
"name": _clean(raw[2]),
|
||||
"job_num": _clean(raw[3]),
|
||||
})
|
||||
return found
|
||||
|
||||
|
||||
def _chunk_params(chunk: list[Any]) -> list[Any]:
|
||||
"""部门 ID 按原字符串传给条件表。"""
|
||||
return list(chunk)
|
||||
|
||||
|
||||
def _chunks(values: list[Any], size: int = 400) -> list[list[Any]]:
|
||||
"""把 IN 列表拆开,避免一条 SQL 的参数过多。"""
|
||||
return [values[index:index + size] for index in range(0, len(values), size)]
|
||||
|
||||
|
||||
def _clean(value: Any) -> str | None:
|
||||
"""去掉空白。数字部门 ID 也收成字符串,供矩阵条件表比较。"""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
|
||||
|
||||
def _pick_driver(pyodbc: Any, configured: str) -> str:
|
||||
"""选用已配置且本机存在的 ODBC 驱动,否则按 18、17、SQL Server 的顺序挑。"""
|
||||
available = list(pyodbc.drivers())
|
||||
if configured and configured in available:
|
||||
return configured
|
||||
for name in _PREFERRED_DRIVERS:
|
||||
if name in available:
|
||||
return name
|
||||
if not available:
|
||||
raise ServiceUnavailableError(
|
||||
"未找到 SQL Server ODBC 驱动",
|
||||
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
|
||||
)
|
||||
return available[-1]
|
||||
@@ -0,0 +1,167 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/query_sql.py
|
||||
|
||||
用途:决定 E10 各表所在库,并组装只读联表 SQL。
|
||||
依赖:无 Flask。库名只允许字母、数字和下划线。
|
||||
逻辑:同步仓库调用。验收单用 FORM_DATA_ID 经 wfc_form_data 挂到流程实例。
|
||||
不读流程编号、第二合同编号、验收日期、optgroupid、batch_number、operate_log_id、isremark。无法验收说明读取 ycsm。字典库看不到时,流程表回退到 ecology10。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
||||
_FORM_CATALOG = "ecology10"
|
||||
_EMPLOYEE_CATALOG = "eteams"
|
||||
_REQUEST_CATALOG = "weaver_wfc"
|
||||
_NODE_CATALOG = "weaver_wfp"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AcceptanceCatalogs:
|
||||
"""一次同步使用的四个库名。"""
|
||||
|
||||
form: str
|
||||
employee: str
|
||||
request: str
|
||||
node: str
|
||||
|
||||
|
||||
def resolve_catalogs(
|
||||
database_names: set[str],
|
||||
*,
|
||||
form: str | None = None,
|
||||
employee: str | None = None,
|
||||
request: str | None = None,
|
||||
node: str | None = None,
|
||||
) -> AcceptanceCatalogs:
|
||||
"""
|
||||
按数据字典和实例上实际存在的库选择库名。
|
||||
|
||||
核心逻辑:显式传入的库名优先。否则流程库优先 weaver_wfc、节点库优先 weaver_wfp,
|
||||
实例里没有这两个库时用 ecology10。人员库只认 eteams,不猜测到别的库。
|
||||
Args:
|
||||
database_names: sys.databases 里的库名。
|
||||
form: 验收单库覆盖值。
|
||||
employee: 人员库覆盖值。
|
||||
request: 流程库覆盖值。
|
||||
node: 节点定义库覆盖值。
|
||||
Returns:
|
||||
AcceptanceCatalogs。
|
||||
|
||||
Raises:
|
||||
ValueError: 库名非法,或人员库、回退后的流程库仍然不存在。
|
||||
"""
|
||||
present = {name.lower(): name for name in database_names if name}
|
||||
return AcceptanceCatalogs(
|
||||
form=_pick(form, _FORM_CATALOG, present, allow_fallback=_FORM_CATALOG),
|
||||
employee=_pick(employee, _EMPLOYEE_CATALOG, present, allow_fallback=None),
|
||||
request=_pick(request, _REQUEST_CATALOG, present, allow_fallback=_FORM_CATALOG),
|
||||
node=_pick(node, _NODE_CATALOG, present, allow_fallback=_FORM_CATALOG),
|
||||
)
|
||||
|
||||
|
||||
def build_acceptance_sql(catalogs: AcceptanceCatalogs) -> str:
|
||||
"""
|
||||
组装验收单、人员、流程实例、当前节点、节点定义、操作人的只读 SQL。
|
||||
|
||||
核心逻辑:用 FORM_DATA_ID 对齐 wfc_form_data.dataid,再按 requestid 挂到流程实例。
|
||||
不查询流程编号、第二合同编号、验收日期和 isremark。当前节点和操作人按 requestid + nodeid 对齐,
|
||||
delete_type 只取 0。当前处理人就是这些 userid。
|
||||
Args:
|
||||
catalogs: 已解析的库名。
|
||||
Returns:
|
||||
一条 SELECT。
|
||||
|
||||
Raises:
|
||||
ValueError: 库名不是合法标识符。
|
||||
"""
|
||||
form = _qualified(catalogs.form, "ft_gdzcysdv2")
|
||||
employee = _qualified(catalogs.employee, "employee")
|
||||
form_data = _qualified(catalogs.request, "wfc_form_data")
|
||||
request = _qualified(catalogs.request, "wfc_requestbase")
|
||||
current = _qualified(catalogs.request, "wfc_currentnode")
|
||||
node = _qualified(catalogs.node, "wfp_node")
|
||||
operate = _qualified(catalogs.request, "wfc_operate")
|
||||
return f"""
|
||||
SELECT
|
||||
f.ysddh,
|
||||
f.cgdh,
|
||||
f.htbh,
|
||||
f.sbsyrjssj,
|
||||
f.sfzfth,
|
||||
f.sfkyzcys,
|
||||
f.ycsm,
|
||||
f.sybmdd,
|
||||
owner.USERNAME AS owner_name,
|
||||
owner.JOB_NUM AS owner_job_num,
|
||||
f.sbglry,
|
||||
equip.USERNAME AS equip_name,
|
||||
equip.JOB_NUM AS equip_job_num,
|
||||
f.sqr,
|
||||
applicant.USERNAME AS applicant_name,
|
||||
applicant.JOB_NUM AS applicant_job_num,
|
||||
r.requestid,
|
||||
r.flowstatus,
|
||||
r.finishdatetime,
|
||||
c.nodeid,
|
||||
n.nodename,
|
||||
n.nodetype,
|
||||
op.userid,
|
||||
handler.USERNAME AS handler_name,
|
||||
handler.JOB_NUM AS handler_job_num
|
||||
FROM {form} AS f
|
||||
LEFT JOIN {employee} AS owner ON owner.ID = f.sybmdd
|
||||
LEFT JOIN {employee} AS equip ON equip.ID = f.sbglry
|
||||
LEFT JOIN {employee} AS applicant ON applicant.ID = f.sqr
|
||||
LEFT JOIN {form_data} AS d
|
||||
ON d.dataid = f.FORM_DATA_ID
|
||||
AND d.delete_type = 0
|
||||
LEFT JOIN {request} AS r
|
||||
ON r.requestid = d.requestid
|
||||
AND r.delete_type = 0
|
||||
LEFT JOIN {current} AS c
|
||||
ON c.requestid = r.requestid
|
||||
AND c.delete_type = 0
|
||||
LEFT JOIN {node} AS n
|
||||
ON n.id = c.nodeid
|
||||
AND n.delete_type = 0
|
||||
LEFT JOIN {operate} AS op
|
||||
ON op.requestid = c.requestid
|
||||
AND op.nodeid = c.nodeid
|
||||
AND op.delete_type = 0
|
||||
LEFT JOIN {employee} AS handler ON handler.ID = op.userid
|
||||
WHERE ISNULL(f.delete_type, 0) = 0
|
||||
AND r.requestid IS NOT NULL
|
||||
""".strip()
|
||||
|
||||
|
||||
def _pick(
|
||||
override: str | None,
|
||||
preferred: str,
|
||||
present: dict[str, str],
|
||||
*,
|
||||
allow_fallback: str | None,
|
||||
) -> str:
|
||||
"""选择一个实际可用的库名。覆盖值不要求已经出现在探测结果里。"""
|
||||
if override and override.strip():
|
||||
return _ident(override.strip())
|
||||
if preferred.lower() in present:
|
||||
return _ident(present[preferred.lower()])
|
||||
if allow_fallback and allow_fallback.lower() in present:
|
||||
return _ident(present[allow_fallback.lower()])
|
||||
raise ValueError(f"缺少数据库 {preferred}")
|
||||
|
||||
|
||||
def _qualified(catalog: str, table: str) -> str:
|
||||
"""返回 [库].[dbo].[表]。"""
|
||||
return f"[{_ident(catalog)}].[dbo].[{_ident(table)}]"
|
||||
|
||||
|
||||
def _ident(name: str) -> str:
|
||||
"""拒绝不是普通标识符的库名或表名。"""
|
||||
if not _IDENT.match(name):
|
||||
raise ValueError(f"非法 SQL 标识符: {name}")
|
||||
return name
|
||||
@@ -0,0 +1,74 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/schedule_seed.py
|
||||
|
||||
用途:设备验收预警的默认排程:每日扫描和周五 18:00 发送。
|
||||
依赖:ScheduleTask、permission_roles.service.first_schedule_owner_user、timezone_util。
|
||||
逻辑:应用启动时幂等创建。已有同编号或同任务键时不覆盖管理员改过的 Cron。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleTask
|
||||
from app.services.permission_roles.service import first_schedule_owner_user
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
|
||||
_DEFAULTS = (
|
||||
("SCH-EQUIPMENT-ACCEPTANCE-SCAN", "equipment-acceptance-alert-scan", "设备验收预警扫描(日批)", "0 6 * * *"),
|
||||
("SCH-EQUIPMENT-ACCEPTANCE-WEEKLY", "equipment-acceptance-alert-weekly", "设备验收预警发送(周五 18:00)", "0 18 * * 5"),
|
||||
)
|
||||
|
||||
|
||||
def ensure_default_equipment_acceptance_schedules(*, commit: bool = True):
|
||||
"""
|
||||
幂等创建设备验收每日扫描和周五发送两个排程。
|
||||
|
||||
核心逻辑:发送时刻不在预警配置表。默认与合同付款一样,周五 18:00,时区 Asia/Shanghai。
|
||||
Args:
|
||||
commit: 为 False 时只 flush,交给外层事务提交。
|
||||
Returns:
|
||||
新建的排程。没有可当负责人的用户时返回空列表。
|
||||
"""
|
||||
owner = first_schedule_owner_user()
|
||||
if owner is None:
|
||||
return []
|
||||
created = []
|
||||
for schedule_no, platform_path, name, cron in _DEFAULTS:
|
||||
existing = (
|
||||
db.session.query(ScheduleTask)
|
||||
.filter((ScheduleTask.schedule_no == schedule_no) | (ScheduleTask.platform_api_path == platform_path))
|
||||
.first()
|
||||
)
|
||||
if existing:
|
||||
continue
|
||||
now = datetime.utcnow()
|
||||
task = ScheduleTask(
|
||||
schedule_no=schedule_no,
|
||||
name=name,
|
||||
schedule_type="platform_job",
|
||||
owner_user_id=owner.id,
|
||||
cron_expr=cron,
|
||||
schedule_timezone="Asia/Shanghai",
|
||||
wait_seconds=0,
|
||||
platform_api_path=platform_path,
|
||||
job_params={},
|
||||
kb_sync_enabled=False,
|
||||
notify_user_ids_json=[],
|
||||
notify_enabled=False,
|
||||
enabled=True,
|
||||
next_run_at=compute_next_run_at(cron, timezone_name="Asia/Shanghai") or now,
|
||||
created_by=owner.id,
|
||||
updated_by=owner.id,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
db.session.add(task)
|
||||
created.append(task)
|
||||
if commit and created:
|
||||
db.session.commit()
|
||||
elif not commit:
|
||||
db.session.flush()
|
||||
return created
|
||||
@@ -0,0 +1,176 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/send_record_service.py
|
||||
|
||||
用途:分页读取设备验收预警的发送记录。
|
||||
依赖:extensions.db、EquipmentAcceptanceSendRecord、EquipmentAcceptanceSendFile、utc_iso。
|
||||
逻辑:由发送记录列表和 Excel 下载接口调用。列表按 send_record_ids 把 Excel 挂到对应行,不读文件字节。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm import defer
|
||||
|
||||
from app.core.errors import NotFoundError
|
||||
from app.core.response import utc_iso
|
||||
from app.extensions import db
|
||||
from app.models.equipment_acceptance import EquipmentAcceptanceSendFile, EquipmentAcceptanceSendRecord
|
||||
|
||||
|
||||
def list_send_records(*, page: int, page_size: int) -> dict[str, Any]:
|
||||
"""
|
||||
按创建时间倒序分页列出发送记录。
|
||||
|
||||
核心逻辑:只读已落库的记录。扫描还没跑过时列表为空。
|
||||
Args:
|
||||
page: 从 1 开始。
|
||||
page_size: 每页条数,上限 100。
|
||||
Returns:
|
||||
items、total、page、page_size。
|
||||
"""
|
||||
page = max(1, page)
|
||||
page_size = min(100, max(1, page_size))
|
||||
query = db.session.query(EquipmentAcceptanceSendRecord)
|
||||
total = query.count()
|
||||
rows = (
|
||||
query.order_by(EquipmentAcceptanceSendRecord.created_at.desc(), EquipmentAcceptanceSendRecord.id.desc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
file_rows = _file_rows_for([row.id for row in rows])
|
||||
return {
|
||||
"items": [
|
||||
send_record_payload(row, _files_for_record(row.id, file_rows))
|
||||
for row in rows
|
||||
],
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
}
|
||||
|
||||
|
||||
def list_send_files(*, limit: int = 20) -> list[dict[str, Any]]:
|
||||
"""
|
||||
列出最近留下的收件人 Excel,不含文件字节。
|
||||
|
||||
核心逻辑:按创建时间倒序。发送失败的文件也返回,方便对照当时准备发出的明细。
|
||||
Args:
|
||||
limit: 最多返回条数,上限 50。
|
||||
Returns:
|
||||
文件名、收件人、状态和发送时间。
|
||||
"""
|
||||
limit = min(50, max(1, limit))
|
||||
rows = (
|
||||
db.session.query(EquipmentAcceptanceSendFile)
|
||||
.order_by(EquipmentAcceptanceSendFile.created_at.desc(), EquipmentAcceptanceSendFile.id.desc())
|
||||
.limit(limit)
|
||||
.all()
|
||||
)
|
||||
return [send_file_payload(row) for row in rows]
|
||||
|
||||
|
||||
def get_send_file(file_id: int) -> EquipmentAcceptanceSendFile:
|
||||
"""
|
||||
取出一份已归档的 Excel。
|
||||
|
||||
Args:
|
||||
file_id: 文件行主键。
|
||||
Returns:
|
||||
含字节的文件行。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 记录不存在或没有文件内容。
|
||||
"""
|
||||
row = db.session.get(EquipmentAcceptanceSendFile, file_id)
|
||||
if row is None or not row.excel_file_data:
|
||||
raise NotFoundError("设备验收预警附件不存在")
|
||||
return row
|
||||
|
||||
|
||||
def send_file_payload(row: EquipmentAcceptanceSendFile) -> dict[str, Any]:
|
||||
"""列表用的文件摘要。不返回 Excel 字节。"""
|
||||
return {
|
||||
"id": row.id,
|
||||
"recipient_name": row.recipient_name,
|
||||
"excel_file_name": row.excel_file_name,
|
||||
"excel_file_size": row.excel_file_size,
|
||||
"status": row.status,
|
||||
"sent_at": utc_iso(row.sent_at),
|
||||
"created_at": utc_iso(row.created_at),
|
||||
}
|
||||
|
||||
|
||||
def _file_rows_for(record_ids: list[int]) -> list[EquipmentAcceptanceSendFile]:
|
||||
"""
|
||||
取出可能挂在这些发送记录上的 Excel 摘要。
|
||||
|
||||
核心逻辑:延迟加载文件字节,只留下文件名和记录编号,避免列表把整份 xlsx 读进内存。
|
||||
Args:
|
||||
record_ids: 当前页发送记录主键。为空时不查。
|
||||
Returns:
|
||||
归档文件行,不含 excel_file_data。
|
||||
"""
|
||||
if not record_ids:
|
||||
return []
|
||||
return (
|
||||
db.session.query(EquipmentAcceptanceSendFile)
|
||||
.options(defer(EquipmentAcceptanceSendFile.excel_file_data))
|
||||
.order_by(EquipmentAcceptanceSendFile.id.asc())
|
||||
.all()
|
||||
)
|
||||
|
||||
|
||||
def _files_for_record(record_id: int, file_rows: list[EquipmentAcceptanceSendFile]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
挑出包含这条发送记录的 Excel。
|
||||
|
||||
核心逻辑:send_record_ids 里有这条记录才挂上。没有文件名的不展示。
|
||||
Args:
|
||||
record_id: 发送记录主键。
|
||||
file_rows: 已去掉文件字节的归档行。
|
||||
Returns:
|
||||
下载按钮需要的 id 和文件名。
|
||||
"""
|
||||
found: list[dict[str, Any]] = []
|
||||
for row in file_rows:
|
||||
ids = {int(item) for item in list(row.send_record_ids or []) if item}
|
||||
if record_id in ids and row.excel_file_name:
|
||||
found.append({
|
||||
"id": row.id,
|
||||
"excel_file_name": row.excel_file_name,
|
||||
})
|
||||
return found
|
||||
|
||||
|
||||
def send_record_payload(
|
||||
row: EquipmentAcceptanceSendRecord,
|
||||
files: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
把一条发送记录收成接口数据。
|
||||
|
||||
核心逻辑:单号和主送、抄送用写入时的快照,不回读当前岗位。Excel 只带文件名和主键。
|
||||
Args:
|
||||
row: 本地发送记录。
|
||||
files: 这份记录出现过的归档 Excel。
|
||||
Returns:
|
||||
页签表格用的字段。
|
||||
"""
|
||||
return {
|
||||
"id": row.id,
|
||||
"order_id": row.order_id,
|
||||
"acceptance_no": row.acceptance_no,
|
||||
"purchase_order_no": row.purchase_order_no,
|
||||
"tier": row.tier,
|
||||
"threshold_days": row.threshold_days,
|
||||
"to_text": row.to_text,
|
||||
"cc_text": row.cc_text,
|
||||
"recipients": list(row.recipients_json or []),
|
||||
"status": row.status,
|
||||
"sent_at": utc_iso(row.sent_at),
|
||||
"error_message": row.error_message,
|
||||
"created_at": utc_iso(row.created_at),
|
||||
"files": files or [],
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/settings.py
|
||||
|
||||
用途:读取设备验收同步要用的 E10 SQL Server 连接。
|
||||
依赖:Flask current_app、环境变量 OA_E10_SQLSERVER_HOST / USERNAME / PASSWORD。
|
||||
逻辑:主机、账号、密码不回退到 E8 的 OA_SQLSERVER_*。库名由查询时再探测。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
|
||||
from flask import current_app, has_app_context
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EquipmentAcceptanceSqlSettings:
|
||||
"""E10 只读连接。repr 不包含密码。"""
|
||||
|
||||
host: str
|
||||
port: str
|
||||
username: str
|
||||
password: str
|
||||
driver: str
|
||||
encrypt: str
|
||||
trust_cert: str
|
||||
timeout: int
|
||||
form_catalog: str
|
||||
employee_catalog: str
|
||||
request_catalog: str
|
||||
node_catalog: str
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return (
|
||||
"EquipmentAcceptanceSqlSettings("
|
||||
f"host={self.host!r}, port={self.port!r}, username={self.username!r}, "
|
||||
f"form_catalog={self.form_catalog!r}, employee_catalog={self.employee_catalog!r}, "
|
||||
f"request_catalog={self.request_catalog!r}, node_catalog={self.node_catalog!r})"
|
||||
)
|
||||
|
||||
|
||||
def load_equipment_acceptance_sql_settings() -> EquipmentAcceptanceSqlSettings:
|
||||
"""
|
||||
读取同步连接配置。
|
||||
|
||||
核心逻辑:三个必填变量只认 OA_E10_SQLSERVER_*。库名覆盖可空,空则交给实例探测。
|
||||
Returns:
|
||||
EquipmentAcceptanceSqlSettings。
|
||||
|
||||
Raises:
|
||||
ValidationError: 主机、账号或密码缺失。
|
||||
"""
|
||||
host = _cfg("OA_E10_SQLSERVER_HOST")
|
||||
username = _cfg("OA_E10_SQLSERVER_USERNAME")
|
||||
password = _cfg_raw("OA_E10_SQLSERVER_PASSWORD")
|
||||
missing = [
|
||||
key
|
||||
for key, value in (
|
||||
("OA_E10_SQLSERVER_HOST", host),
|
||||
("OA_E10_SQLSERVER_USERNAME", username),
|
||||
("OA_E10_SQLSERVER_PASSWORD", password),
|
||||
)
|
||||
if not str(value or "").strip()
|
||||
]
|
||||
if missing:
|
||||
raise ValidationError(
|
||||
"设备验收同步的 E10 数据库配置不完整",
|
||||
code="EQUIPMENT_ACCEPTANCE.CONFIG_INVALID",
|
||||
details={"missing": missing},
|
||||
)
|
||||
return EquipmentAcceptanceSqlSettings(
|
||||
host=host,
|
||||
port=_cfg("OA_E10_SQLSERVER_PORT") or "1433",
|
||||
username=username,
|
||||
password=password,
|
||||
driver=_cfg("OA_E10_SQLSERVER_DRIVER"),
|
||||
encrypt=(_cfg("OA_E10_SQLSERVER_ENCRYPT") or "no").lower(),
|
||||
trust_cert=(_cfg("OA_E10_SQLSERVER_TRUST_CERT") or "yes").lower(),
|
||||
timeout=_as_int(_cfg("OA_E10_SQLSERVER_TIMEOUT") or "60", 60),
|
||||
form_catalog=_cfg("EQUIPMENT_ACCEPTANCE_FORM_CATALOG"),
|
||||
employee_catalog=_cfg("EQUIPMENT_ACCEPTANCE_EMPLOYEE_CATALOG"),
|
||||
request_catalog=_cfg("EQUIPMENT_ACCEPTANCE_REQUEST_CATALOG"),
|
||||
node_catalog=_cfg("EQUIPMENT_ACCEPTANCE_NODE_CATALOG"),
|
||||
)
|
||||
|
||||
|
||||
def _cfg(key: str) -> str:
|
||||
"""优先 Flask config,再读环境变量,并去掉首尾空白。"""
|
||||
if has_app_context():
|
||||
value = current_app.config.get(key)
|
||||
if value is not None and str(value).strip():
|
||||
return str(value).strip()
|
||||
return str(os.getenv(key) or "").strip()
|
||||
|
||||
|
||||
def _cfg_raw(key: str) -> str:
|
||||
"""读取密码,保留中间空格。"""
|
||||
if has_app_context():
|
||||
value = current_app.config.get(key)
|
||||
if value is not None and str(value) != "":
|
||||
return str(value)
|
||||
env = os.getenv(key)
|
||||
if env is not None and env != "":
|
||||
return env
|
||||
return ""
|
||||
|
||||
|
||||
def _as_int(raw: str, default: int) -> int:
|
||||
"""超时秒数,非法时用默认值。"""
|
||||
try:
|
||||
return max(1, int(str(raw).strip() or default))
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
@@ -0,0 +1,243 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/snapshot_rules.py
|
||||
|
||||
用途:把 OA 原值收成同步快照上的监控状态和签核天数。
|
||||
依赖:无。不读数据库,也不使用 isremark。
|
||||
逻辑:同步服务对每一张验收单调用本模块。OA 的 0=是、1=否先翻成标准 0=否、1=是。
|
||||
flowstatus 为 7、8、99、-99 时记为已撤销,不再提醒。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from typing import Any
|
||||
|
||||
NOT_STARTED = "not_started"
|
||||
WATCHING = "watching"
|
||||
STOPPED_CANNOT_ACCEPT = "stopped_cannot_accept"
|
||||
STOPPED_RETURNED = "stopped_returned"
|
||||
STOPPED_ARCHIVED = "stopped_archived"
|
||||
STOPPED_FORCE_FINISHED = "stopped_force_finished"
|
||||
STOPPED_VOIDED = "stopped_voided"
|
||||
STOPPED_REVOKED = "stopped_revoked"
|
||||
EXCLUDED = "excluded"
|
||||
|
||||
MONITOR_STATUSES = (
|
||||
NOT_STARTED,
|
||||
WATCHING,
|
||||
STOPPED_CANNOT_ACCEPT,
|
||||
STOPPED_RETURNED,
|
||||
STOPPED_ARCHIVED,
|
||||
STOPPED_FORCE_FINISHED,
|
||||
STOPPED_VOIDED,
|
||||
STOPPED_REVOKED,
|
||||
EXCLUDED,
|
||||
)
|
||||
|
||||
# 需求冻结的第 1 档是超过 30 天。列表上的「已逾期」按这一档判断,还没有发送记录。
|
||||
FIRST_REMINDER_DAY = 30
|
||||
_FLOW_APPROVING = 1
|
||||
_FLOW_ARCHIVED = 3
|
||||
_FLOW_FORCE_FINISHED = 4
|
||||
_FLOW_VOIDED = 5
|
||||
# 7、8、99 已确认按撤销停表。字典截断值是 -99,一并按撤销处理。
|
||||
_REVOKED_FLOW = {7, 8, 99, -99}
|
||||
_TERMINAL_FLOW = {_FLOW_ARCHIVED, _FLOW_FORCE_FINISHED, _FLOW_VOIDED, *_REVOKED_FLOW}
|
||||
|
||||
|
||||
def as_int(value: Any) -> int | None:
|
||||
"""
|
||||
把 OA 数字收成 int。空值保持空。
|
||||
|
||||
核心逻辑:布尔值不是业务枚举;0 是有效取值,不能当成空。
|
||||
Args:
|
||||
value: 查询结果里的数字、数字字符串或空。
|
||||
Returns:
|
||||
整数或 None。
|
||||
"""
|
||||
if value is None or isinstance(value, bool):
|
||||
return None
|
||||
if isinstance(value, int):
|
||||
return value
|
||||
if isinstance(value, float):
|
||||
if value != value:
|
||||
return None
|
||||
return int(value)
|
||||
text = str(value).strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
return int(text)
|
||||
except ValueError:
|
||||
try:
|
||||
number = float(text)
|
||||
except ValueError:
|
||||
return None
|
||||
return int(number)
|
||||
|
||||
|
||||
def as_date(value: Any) -> date | None:
|
||||
"""
|
||||
把 OA 日期收成 date。
|
||||
|
||||
核心逻辑:datetime 取日期部分;常见字符串只认日期前 10 位。
|
||||
Args:
|
||||
value: datetime、date 或字符串。
|
||||
Returns:
|
||||
date 或 None。
|
||||
"""
|
||||
if value is None or isinstance(value, bool):
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value.date()
|
||||
if isinstance(value, date):
|
||||
return value
|
||||
text = str(value).strip()
|
||||
if len(text) < 10:
|
||||
return None
|
||||
try:
|
||||
return date.fromisoformat(text[:10])
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def as_datetime(value: Any) -> datetime | None:
|
||||
"""
|
||||
把 OA 时间收成去掉时区的 datetime,供本地快照保存。
|
||||
|
||||
Args:
|
||||
value: datetime 或可解析字符串。
|
||||
Returns:
|
||||
naive datetime 或 None。
|
||||
"""
|
||||
if value is None or isinstance(value, bool):
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value.replace(tzinfo=None)
|
||||
if isinstance(value, date):
|
||||
return datetime(value.year, value.month, value.day)
|
||||
text = str(value).strip().replace("T", " ")
|
||||
if not text:
|
||||
return None
|
||||
for fmt in ("%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d"):
|
||||
try:
|
||||
return datetime.strptime(text[:26], fmt)
|
||||
except ValueError:
|
||||
continue
|
||||
parsed = as_date(text)
|
||||
if parsed is None:
|
||||
return None
|
||||
return datetime(parsed.year, parsed.month, parsed.day)
|
||||
|
||||
|
||||
def can_accept_from_oa(value: int | None) -> int | None:
|
||||
"""
|
||||
把 OA「是否可以正常验收」翻成标准布尔。
|
||||
|
||||
核心逻辑:OA sfkyzcys 是 0=是、1=否。本地 can_accept 用 0=否、1=是。
|
||||
空值表示未标明,保持空,不收成否。0、1 以外的值原样留下,交给状态判断排除。
|
||||
Args:
|
||||
value: sfkyzcys 的整数。0 可以,1 不可以。
|
||||
Returns:
|
||||
1 表示可以验收,0 表示不可以,空保持空。
|
||||
"""
|
||||
# [STEP] OA 0=是、1=否,与本地 0=否、1=是对调。空不是「否」。
|
||||
if value == 0:
|
||||
return 1
|
||||
if value == 1:
|
||||
return 0
|
||||
return value
|
||||
|
||||
|
||||
def is_returned_from_oa(value: int | None) -> int | None:
|
||||
"""
|
||||
把 OA「是否退回」翻成标准布尔。
|
||||
|
||||
核心逻辑:OA sfzfth 是 0=是(退回),1=否(正常)。本地 is_returned 用 0=否、1=是。
|
||||
空和 1 都已确认是未退回,所以空收成 0。0、1、空以外的值原样留下。
|
||||
Args:
|
||||
value: sfzfth 的整数。0 退回,1 和空为正常。
|
||||
Returns:
|
||||
1 表示已退回,0 表示未退回。
|
||||
"""
|
||||
# [STEP] OA 0=是、1=否,翻成 0=否、1=是。空按已确认口径当作未退回。
|
||||
if value == 0:
|
||||
return 1
|
||||
if value in (1, None):
|
||||
return 0
|
||||
return value
|
||||
|
||||
|
||||
def classify_monitor_status(
|
||||
*,
|
||||
can_accept: int | None,
|
||||
is_returned: int | None,
|
||||
flow_status: int | None,
|
||||
timer_started: bool,
|
||||
) -> str:
|
||||
"""
|
||||
按已确认规则给出监控状态。入参已是标准 0=否、1=是。
|
||||
|
||||
核心逻辑:退回、无法验收、作废、归档、强制结束、撤销优先于未开始。
|
||||
审批中、可以验收、未退回、已有计时起点才是计时中。
|
||||
flowstatus 为 7、8、99、-99 时记为已撤销,有没有计时起点都不再提醒。
|
||||
Args:
|
||||
can_accept: 本地是否可以正常验收。0 否,1 是,空为未标明。
|
||||
is_returned: 本地是否退回。0 否,1 是。
|
||||
flow_status: wfc_requestbase.flowstatus。
|
||||
timer_started: sbsyrjssj 是否有值。
|
||||
Returns:
|
||||
MONITOR_STATUSES 中的一个代码。
|
||||
"""
|
||||
# [STEP 1] 表单上的停表原因优先于流程是否已经结束
|
||||
if is_returned == 1:
|
||||
return STOPPED_RETURNED
|
||||
if can_accept == 0:
|
||||
return STOPPED_CANNOT_ACCEPT
|
||||
if flow_status == _FLOW_VOIDED:
|
||||
return STOPPED_VOIDED
|
||||
if flow_status == _FLOW_ARCHIVED:
|
||||
return STOPPED_ARCHIVED
|
||||
if flow_status == _FLOW_FORCE_FINISHED:
|
||||
return STOPPED_FORCE_FINISHED
|
||||
if flow_status in _REVOKED_FLOW:
|
||||
return STOPPED_REVOKED
|
||||
if not timer_started:
|
||||
return NOT_STARTED
|
||||
# [STEP 2] 只有审批中、可以验收、未退回时继续计时
|
||||
if can_accept == 1 and flow_status == _FLOW_APPROVING and is_returned == 0:
|
||||
return WATCHING
|
||||
return EXCLUDED
|
||||
|
||||
|
||||
def dwell_days(
|
||||
*,
|
||||
timer_started_at: datetime | date | None,
|
||||
flow_status: int | None,
|
||||
finished_at: datetime | date | None,
|
||||
as_of: date,
|
||||
) -> int | None:
|
||||
"""
|
||||
计算同步日看到的签核自然日。
|
||||
|
||||
核心逻辑:起点为空则没有天数。归档、强制结束、作废、撤销且有结束时间时,
|
||||
截止到结束日,避免停表后每次同步继续加天。退回和无法验收没有结束时间,截止到同步日。
|
||||
Args:
|
||||
timer_started_at: sbsyrjssj。
|
||||
flow_status: 流程状态原值。
|
||||
finished_at: finishdatetime。
|
||||
as_of: 同步当日,使用 Asia/Shanghai 的日期。
|
||||
Returns:
|
||||
非负天数;没有起点时为 None。
|
||||
"""
|
||||
start = as_date(timer_started_at)
|
||||
if start is None:
|
||||
return None
|
||||
end = as_of
|
||||
if flow_status in _TERMINAL_FLOW:
|
||||
finished = as_date(finished_at)
|
||||
if finished is not None:
|
||||
end = finished if finished < as_of else as_of
|
||||
if end < start:
|
||||
return 0
|
||||
return (end - start).days
|
||||
@@ -0,0 +1,162 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/source_group.py
|
||||
|
||||
用途:把验收单联表的扁平行收成一张单一条草稿。
|
||||
依赖:snapshot_rules。
|
||||
逻辑:同步服务先分组再落库。是否可以验收、是否退回在这里从 OA 的 0=是、1=否
|
||||
翻成标准 0=否、1=是。无法验收说明取 ycsm,不参与停表。操作人按节点和人员去重,不读 isremark。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.services.equipment_acceptance.snapshot_rules import (
|
||||
as_datetime,
|
||||
as_int,
|
||||
can_accept_from_oa,
|
||||
is_returned_from_oa,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class OperatorDraft:
|
||||
"""当前节点上的一名操作人。不带操作状态。"""
|
||||
|
||||
node_id: int
|
||||
user_id: int
|
||||
handler_name: str | None
|
||||
handler_job_num: str | None
|
||||
|
||||
|
||||
@dataclass
|
||||
class NodeDraft:
|
||||
"""一条当前节点。"""
|
||||
|
||||
node_id: int
|
||||
node_name: str | None
|
||||
node_type: int | None
|
||||
|
||||
|
||||
@dataclass
|
||||
class AcceptanceDraft:
|
||||
"""一张验收单在一次同步中的快照草稿。不包含流程编号、第二合同编号和验收日期。"""
|
||||
|
||||
request_id: int
|
||||
acceptance_no: str | None
|
||||
purchase_order_no: str | None
|
||||
contract_no: str | None
|
||||
timer_started_at: datetime | None
|
||||
can_accept: int | None
|
||||
cannot_accept_note: str | None
|
||||
is_returned: int | None
|
||||
flow_status_raw: int | None
|
||||
finished_at: datetime | None
|
||||
request_match_count: int
|
||||
owner_oa_id: int | None
|
||||
owner_name: str | None
|
||||
owner_job_num: str | None
|
||||
equip_oa_id: int | None
|
||||
equip_name: str | None
|
||||
equip_job_num: str | None
|
||||
applicant_oa_id: int | None
|
||||
applicant_name: str | None
|
||||
applicant_job_num: str | None
|
||||
nodes: list[NodeDraft] = field(default_factory=list)
|
||||
operators: list[OperatorDraft] = field(default_factory=list)
|
||||
|
||||
|
||||
def group_acceptance_rows(rows: list[dict[str, Any]]) -> tuple[list[AcceptanceDraft], int]:
|
||||
"""
|
||||
按流程实例 requestid 合并联表结果。
|
||||
|
||||
核心逻辑:没有 requestid 的行跳过。同一请求上的节点和操作人收成一张单。
|
||||
不读取流程编号、第二合同编号和验收日期。
|
||||
Args:
|
||||
rows: 查询别名组成的字典行。
|
||||
Returns:
|
||||
(草稿列表, 因缺少 requestid 而跳过的行数)。
|
||||
"""
|
||||
skipped = 0
|
||||
buckets: dict[int, list[dict[str, Any]]] = {}
|
||||
for row in rows:
|
||||
request_id = as_int(row.get("requestid"))
|
||||
if request_id is None:
|
||||
skipped += 1
|
||||
continue
|
||||
buckets.setdefault(request_id, []).append(row)
|
||||
return [_draft_from_rows(request_id, items) for request_id, items in buckets.items()], skipped
|
||||
|
||||
|
||||
def _draft_from_rows(request_id: int, items: list[dict[str, Any]]) -> AcceptanceDraft:
|
||||
"""同一流程实例的多行收成一条草稿。"""
|
||||
header = items[0]
|
||||
return AcceptanceDraft(
|
||||
request_id=request_id,
|
||||
acceptance_no=_text(header.get("ysddh")),
|
||||
purchase_order_no=_text(header.get("cgdh")),
|
||||
contract_no=_text(header.get("htbh")),
|
||||
timer_started_at=as_datetime(header.get("sbsyrjssj")),
|
||||
can_accept=can_accept_from_oa(as_int(header.get("sfkyzcys"))),
|
||||
cannot_accept_note=_text(header.get("ycsm")),
|
||||
is_returned=is_returned_from_oa(as_int(header.get("sfzfth"))),
|
||||
flow_status_raw=as_int(header.get("flowstatus")),
|
||||
finished_at=as_datetime(header.get("finishdatetime")),
|
||||
request_match_count=1,
|
||||
nodes=_nodes(items),
|
||||
operators=_operators(items),
|
||||
owner_oa_id=as_int(header.get("sybmdd")),
|
||||
owner_name=_text(header.get("owner_name")),
|
||||
owner_job_num=_text(header.get("owner_job_num")),
|
||||
equip_oa_id=as_int(header.get("sbglry")),
|
||||
equip_name=_text(header.get("equip_name")),
|
||||
equip_job_num=_text(header.get("equip_job_num")),
|
||||
applicant_oa_id=as_int(header.get("sqr")),
|
||||
applicant_name=_text(header.get("applicant_name")),
|
||||
applicant_job_num=_text(header.get("applicant_job_num")),
|
||||
)
|
||||
|
||||
|
||||
def _nodes(rows: list[dict[str, Any]]) -> list[NodeDraft]:
|
||||
"""按节点 ID 去重,保留节点名称。"""
|
||||
found: dict[int, NodeDraft] = {}
|
||||
for row in rows:
|
||||
node_id = as_int(row.get("nodeid"))
|
||||
if node_id is None or node_id in found:
|
||||
continue
|
||||
found[node_id] = NodeDraft(
|
||||
node_id=node_id,
|
||||
node_name=_text(row.get("nodename")),
|
||||
node_type=as_int(row.get("nodetype")),
|
||||
)
|
||||
return list(found.values())
|
||||
|
||||
|
||||
def _operators(rows: list[dict[str, Any]]) -> list[OperatorDraft]:
|
||||
"""按节点和人员去重。不读 isremark,同一人只留一行。"""
|
||||
found: dict[tuple[int, int], OperatorDraft] = {}
|
||||
for row in rows:
|
||||
node_id = as_int(row.get("nodeid"))
|
||||
user_id = as_int(row.get("userid"))
|
||||
if node_id is None or user_id is None:
|
||||
continue
|
||||
key = (node_id, user_id)
|
||||
if key in found:
|
||||
continue
|
||||
found[key] = OperatorDraft(
|
||||
node_id=node_id,
|
||||
user_id=user_id,
|
||||
handler_name=_text(row.get("handler_name")),
|
||||
handler_job_num=_text(row.get("handler_job_num")),
|
||||
)
|
||||
return list(found.values())
|
||||
|
||||
|
||||
def _text(value: Any) -> str | None:
|
||||
"""去空白;空串视为没有值。"""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
Loaded 100 of 601 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user