Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
88fcf3c70b | ||
|
|
9838b77441 | ||
|
|
e457a66465 | ||
|
|
ec2c9eca6f | ||
|
|
6a26a4dba8 | ||
|
|
fc4631218b | ||
|
|
0d735def90 | ||
|
|
9203a90637 | ||
|
|
8023acd212 | ||
|
|
d100a39cf8 | ||
|
|
ffccf19ba2 | ||
|
|
e8255f5943 | ||
|
|
70f684b94a | ||
|
|
bc86720744 | ||
|
|
ceb49461e8 | ||
|
|
ea9a96b2fb | ||
|
|
49629aeb0f | ||
|
|
cd81911514 | ||
|
|
49c149eb3e | ||
|
|
729546a7b7 | ||
|
|
202d626a7a | ||
|
|
143e054d86 | ||
|
|
0a9bd6415d | ||
|
|
42de6c02d3 | ||
|
|
b2fa2688a3 | ||
|
|
1ee4c69dee | ||
|
|
2ebac99d43 | ||
|
|
c621f7696c | ||
|
|
db067085e4 | ||
|
|
6d39e474f5 | ||
|
|
a31735b689 | ||
|
|
5a147c4d85 | ||
|
|
c3f05ba96b | ||
|
|
918d4f1835 | ||
|
|
fc843905d1 | ||
|
|
f21216f81e | ||
|
|
0939aeb0d8 | ||
|
|
64205b72bd | ||
|
|
854793f3fe | ||
|
|
ffd3634302 | ||
|
|
5e7e5a8717 | ||
|
|
8b1efbedb9 | ||
|
|
c81717df30 | ||
|
|
f4e74f7b07 | ||
|
|
39ef8a49c9 | ||
|
|
50ccd31b84 | ||
|
|
348f0fdcfd | ||
|
|
c778f40fbc | ||
|
|
b89f9bafb6 | ||
|
|
dab04d4c3e | ||
|
|
f1b9b7c3a9 | ||
|
|
0d68048b8e | ||
|
|
8b5b0b49bf | ||
|
|
61acbe50a7 | ||
|
|
8bd66baa21 | ||
|
|
5bef77f86c | ||
|
|
37e08c83d8 | ||
|
|
2ce1aca023 | ||
|
|
99453aa52a | ||
|
|
fa965dd45b | ||
|
|
d54f51ddc3 | ||
|
|
fc694a8f43 | ||
|
|
c8ce77199e | ||
|
|
9ea49d7060 | ||
|
|
fd024c1c32 | ||
|
|
dfaa55b365 | ||
|
|
bf18a7ef1d | ||
|
|
6ce0942fef | ||
|
|
fa8f6990a7 | ||
|
|
2566ce53e4 | ||
|
|
ac4262cd75 | ||
|
|
090281835a | ||
|
|
76d5778c3b | ||
|
|
f72c1c9f0e | ||
|
|
95f3906779 | ||
|
|
91758ef2b4 | ||
|
|
3a22df736e | ||
|
|
0f3f40e735 | ||
|
|
56b6ea06a8 | ||
|
|
7a9c36d16b | ||
|
|
8846ce159f | ||
|
|
1164ae2e3c | ||
|
|
599475d4e2 | ||
|
|
09cd6fc3c7 | ||
|
|
60dd0c0f58 | ||
|
|
6261d2e1f3 | ||
|
|
9c036c825b | ||
|
|
bba6e6f221 | ||
|
|
c8054476c1 | ||
|
|
4a14960e01 | ||
|
|
f96684a614 | ||
|
|
af999d8a11 | ||
|
|
6a0a51313f | ||
|
|
9f5493185d | ||
|
|
4cd987eef6 | ||
|
|
19f43e8018 | ||
|
|
3f13bb5b46 | ||
|
|
eb0466245b | ||
|
|
ce80867d09 | ||
|
|
1921959fc1 | ||
|
|
d5e76dee36 | ||
|
|
b476b58a91 | ||
|
|
ca32191c77 | ||
|
|
7f1d5dfbcd | ||
|
|
7e4a2037d8 | ||
|
|
f434402530 | ||
|
|
1fc9976ca3 | ||
|
|
cafce5cfa9 | ||
|
|
a3420c5266 | ||
|
|
3b771fc0b6 | ||
|
|
0b083cfdbd | ||
|
|
53efa7e14e | ||
|
|
d6af566601 | ||
|
|
25876f94bd | ||
|
|
1cf8ff40bd | ||
|
|
70d7435b5f | ||
|
|
a451951e7a | ||
|
|
053ea392f2 | ||
|
|
1dc5a459b3 | ||
|
|
6e78c10171 | ||
|
|
639df1b8c5 | ||
|
|
1bd9f278fe | ||
|
|
1cdc365955 | ||
|
|
b89d93d738 | ||
|
|
6adea87a5f | ||
|
|
4474ef7e3f | ||
|
|
0d3a812e16 | ||
|
|
acbf7d5921 | ||
|
|
a89491f4b1 | ||
|
|
8efc526ca8 | ||
|
|
f9b04eddc8 | ||
|
|
873331dd20 | ||
|
|
2aa8609c17 | ||
|
|
1bc938155a | ||
|
|
0c5ee4aec1 | ||
|
|
d5928b42f3 | ||
|
|
08360a4142 | ||
|
|
0a7e68a58a | ||
|
|
8246c09ab0 | ||
|
|
ddb704f574 | ||
|
|
7300098ff9 | ||
|
|
82ad4323f8 | ||
|
|
70e8f700ff | ||
|
|
cdd227d550 | ||
|
|
0f499b47f7 | ||
|
|
0d59b23e0c | ||
|
|
757231e3d5 | ||
|
|
c38a56536e | ||
|
|
10b6f9b692 | ||
|
|
6757ad869f | ||
|
|
d46d61bfa1 | ||
|
|
f224217fb0 | ||
|
|
97a5a1f106 | ||
|
|
55cf7ff734 | ||
|
|
634dee4b81 | ||
|
|
93f4ea5537 | ||
|
|
66410c9a27 | ||
|
|
cf7cc11ffc | ||
|
|
98481c7ea7 | ||
|
|
457f0f4e5e | ||
|
|
a523ec0454 | ||
|
|
21b8c24815 | ||
|
|
b69d549b2c | ||
|
|
6f9c25bb34 | ||
|
|
950d661b4f | ||
|
|
3264ed1e07 | ||
|
|
9b36ced288 | ||
|
|
b079524b4f | ||
|
|
d3cfd24d6f | ||
|
|
0ac165049d | ||
|
|
1eb6bf4aad | ||
|
|
7544361c05 | ||
|
|
f6fe56f205 | ||
|
|
638fdcb7fd | ||
|
|
29a7704d46 | ||
|
|
24310b63b3 | ||
|
|
6baeffba64 | ||
|
|
fa0cdee8df | ||
|
|
9cba517bff | ||
|
|
f5aac9c893 | ||
|
|
9bc4d1dd18 | ||
|
|
ec97ea8787 | ||
|
|
587a215d88 | ||
|
|
8d8b40812d | ||
|
|
3f61e92549 | ||
|
|
c1c4efe4f1 | ||
|
|
6d0e78be81 | ||
|
|
d4f629106f | ||
|
|
ced7fbe085 | ||
|
|
ae6a5e7c55 | ||
|
|
9d7dad6a4b | ||
|
|
dc141d19a2 | ||
|
|
e827c5dc38 | ||
|
|
599d492895 | ||
|
|
bf32f8b954 | ||
|
|
4b562cfa82 | ||
|
|
ee39270069 | ||
|
|
b82f31af8f | ||
|
|
67d08924a4 | ||
|
|
487b4e6090 | ||
|
|
a18a07ef1a | ||
|
|
fee33f69d9 | ||
|
|
3068e3abb4 | ||
|
|
25cc87fdb3 | ||
|
|
2631f78b00 | ||
|
|
1f1f7236b0 | ||
|
|
54edba8b39 | ||
|
|
24551e9a9a | ||
|
|
8a541211b7 | ||
|
|
33d505cd53 | ||
|
|
5d5127f5e8 | ||
|
|
89616179db | ||
|
|
c01ddb8b23 | ||
|
|
8a0a7fd6ed | ||
|
|
a88b60e505 | ||
|
|
6d40d504c5 | ||
|
|
d9b414b07b | ||
|
|
96cc3913fc | ||
|
|
a6df97f731 | ||
|
|
0a647a0b79 | ||
|
|
c98754e634 | ||
|
|
6b06e74946 | ||
|
|
d4db6876ad | ||
|
|
4fc85be607 | ||
|
|
ff7c227cc2 |
No files matched your search
@@ -0,0 +1,70 @@
|
||||
---
|
||||
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,112 @@
|
||||
---
|
||||
description: 文件层、函数层与代码逻辑层注释强制规范(撰写与调整代码时均适用)
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# 📝 代码与 Agent 注释规范(强制)
|
||||
|
||||
**【核心思想】**
|
||||
本规范适用于我们的敏捷开发团队。代码中的注释不仅是为了让人类团队成员(包括非科班背景的同事)看懂,**更是为了让 AI(如大模型调用、代码补全工具)准确理解上下文。**
|
||||
|
||||
撰写或**修改**代码时,必须补齐或更新以下**三层注释**。
|
||||
|
||||
---
|
||||
|
||||
## 1. 文件层(文件顶部)
|
||||
|
||||
块注释须包含:**文件路径/名称**、**用途**、**主要 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 状态机。
|
||||
"""
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 函数/工具层(每个函数定义上方)
|
||||
|
||||
须说明:**用途(如果是给大模型调用的Tool,必须写明触发时机)**、**核心逻辑与实现方式**、**参数**与**返回值**(及异常)。
|
||||
|
||||
**普通业务函数示例 (TypeScript):**
|
||||
```typescript
|
||||
/**
|
||||
* 加载当前分组下的文档列表,并在静默刷新时合并 stable 项避免闪烁。
|
||||
* 核心逻辑:调用 getKbGroupFilesSafe,按 mergeStableItems 策略合并新旧列表。
|
||||
* @param options.silent - 为 true 时不切换 loading,用于轮询刷新
|
||||
* @returns 是否成功拉取到数据
|
||||
*/
|
||||
async function loadDocuments(options?: LoadListOptions): Promise<boolean> { ... }
|
||||
```
|
||||
|
||||
**Agent 工具函数示例 (Python,给大模型看的):**
|
||||
```python
|
||||
def sync_document_to_dify(document_id: int, *, force: bool = False) -> SyncResult:
|
||||
"""
|
||||
将指定文档切片同步至 Dify 知识库。
|
||||
【AI 触发时机】:当用户要求“更新知识库”、“同步最新文档资料”时调用此工具。
|
||||
|
||||
核心逻辑:读 MinIO 原文 → 切块 → 调 Dify API upsert;失败写入 KbJob 供重试。
|
||||
|
||||
Args:
|
||||
document_id: 本地 KbDocument 主键。禁止传入非整数的 ID。
|
||||
force: 为 True 时忽略已完成状态强制重同步。默认为 False。
|
||||
|
||||
Returns:
|
||||
SyncResult: 包含 dify_document_id (str) 与分段数 (int) 的对象。
|
||||
|
||||
Raises:
|
||||
KbNotFoundError: 文档不存在或无权限。
|
||||
"""
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 代码逻辑层(函数内部)
|
||||
|
||||
**严禁逐行翻译代码**(如 `i = i + 1` 不用注释)。只针对**复杂业务逻辑块**和**AI特定组件**进行标准化标记。
|
||||
|
||||
* **逻辑分块**:使用 `[STEP 1]`, `[STEP 2]` 来拆解长函数的执行步骤。解释“为什么这么做”。
|
||||
* **Prompt 标记**:使用 `[PROMPT_UPDATE]` 记录提示词的修改时间和原因。
|
||||
* **参数标记**:使用 `[PARAM_TUNING]` 说明大模型参数(如 Temperature)为何这么设置。
|
||||
|
||||
```python
|
||||
def generate_article_summary(topic: str):
|
||||
# [STEP 1] 构建并校验基础参数
|
||||
if not topic:
|
||||
return {"error": "主题不能为空"}
|
||||
|
||||
# [STEP 2] 组装 LLM 提示词
|
||||
# [PROMPT_UPDATE] 2024-05-20: 增加"禁止道歉"指令,防止模型遇到敏感词时输出无用废话。
|
||||
system_prompt = f"You are an expert. Topic: {topic}. Rule: Do not apologize."
|
||||
|
||||
# [STEP 3] 调用模型
|
||||
response = llm_client.chat(
|
||||
prompt=system_prompt,
|
||||
# [PARAM_TUNING] Temperature 设为 0.2,因为此处需要严格提取摘要,不需要发散性创意。
|
||||
temperature=0.2
|
||||
)
|
||||
return response
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 修改既有文件时的纪律
|
||||
|
||||
- **改函数逻辑/签名** → 强制同步改该函数的上方注释。
|
||||
- **改 import 或模块协作关系** → 强制同步改文件头部的依赖与逻辑注释。
|
||||
- **改了 Prompt 或模型参数** → 强制追加 `[PROMPT_UPDATE]` 或 `[PARAM_TUNING]` 记录。
|
||||
- **Vue SFC**:`<script setup>` 内的每个核心函数同样要求遵循上述“函数层”注释规范。
|
||||
@@ -22,8 +22,6 @@ AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
|
||||
AUTH_JWT_JWKS_URL=http://192.168.100.192:8870/.well-known/jwks
|
||||
|
||||
# Casdoor
|
||||
|
||||
# 共用 IdP(可与生产 Casdoor 同机)
|
||||
CASDOOR_BASE_URL=http://192.168.100.192:8870
|
||||
# 以下为 hxops-dev 应用在 Casdoor 控制台里的 Client ID / Secret(勿与 prod 混用)
|
||||
CASDOOR_CLIENT_ID=758be5fcba2df784fdb4
|
||||
@@ -55,11 +53,14 @@ MINIO_SECRET_KEY=M3CLE928P8GavJBFZPhJO3RIHVZSRYlDouOMabasojfAGBlx
|
||||
MINIO_SECURE=false
|
||||
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
|
||||
|
||||
# 货代发货通知 Agent(见 docs/shipping_notice.md §1.2)
|
||||
# Tool API(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
# OpenAPI / Dify Tool 调用基地址(默认等于 PUBLIC_BASE_URL + /api/shipping-notice)
|
||||
SHIPPING_NOTICE_TOOL_API_BASE=http://192.168.36.108:5052/
|
||||
# 货代发货通知 Agent(见 docs/features/shipping-notice/technical.md §1.2;Tool 基地址见 HXOPS_TOOLS_API_BASE)
|
||||
# RoHS / 货代等 Dify Tool API 基地址(Dify 服务端内网调用,无尾斜杠)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
|
||||
# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠)
|
||||
HXOPS_PUBLIC_BASE_URL=http://192.168.100.192:8890
|
||||
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=MymLe1StfTCuMOl0IYTp-BRYKln_TnywEDxJ0X0mraYjhFtGeL8mRqoiVPlP9Er8
|
||||
|
||||
# 文件存储(相对 backend/ 根目录)
|
||||
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
||||
@@ -68,6 +69,9 @@ SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
||||
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
|
||||
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
|
||||
|
||||
# 字段对齐确认(生产建议 true;测试可设 false)
|
||||
@@ -77,22 +81,23 @@ SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=6
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
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=true
|
||||
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 shipping_notice.md §2.4)
|
||||
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||
|
||||
# RPA 目录(相对 backend/ 根目录)
|
||||
FREIGHT_INVENTORY_DROP_DIR=data/freight_rpa/inventory_drop
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=data/freight_rpa/upload_queue
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/freight_rpa/upload_triggers
|
||||
FREIGHT_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers
|
||||
FREIGHT_RPA_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
|
||||
|
||||
# 发货 Excel 模板(可选)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
|
||||
@@ -105,7 +110,10 @@ SHIPPING_NOTICE_CHAT_DIFY_APP_ID=
|
||||
SHIPPING_NOTICE_CHAT_DIFY_API_KEY=
|
||||
SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
|
||||
|
||||
# 本地 Mock RPA(scripts/rpa/freight_rpa_worker.py,可选)
|
||||
# FREIGHT_RPA_MOCK=true
|
||||
# 本地 RPA(scripts/rpa/freight_rpa_worker.py)
|
||||
FREIGHT_RPA_MOCK=false
|
||||
# FREIGHT_RPA_POLL_SECONDS=3
|
||||
# FREIGHT_RPA_SAMPLE_INVENTORY=
|
||||
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
@@ -22,14 +22,14 @@ AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
|
||||
AUTH_JWT_JWKS_URL=http://192.168.100.230:8870/.well-known/jwks
|
||||
|
||||
# Casdoor
|
||||
CASDOOR_BASE_URL=http://ai.well-trust.com:8870
|
||||
CASDOOR_BASE_URL=https://auth.well-trust.com
|
||||
# 与 Casdoor 里 Application「hxops-prod」(或你当前生产应用)的 Client ID 一致
|
||||
CASDOOR_CLIENT_ID=758be5fcba2df784fdb4
|
||||
CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab
|
||||
# 兜底 redirect_uri;实际 OAuth 以浏览器地址为准,Casdoor「hxops-prod」应用须登记例如:
|
||||
# http://192.168.100.230:8881/casdoor-callback
|
||||
# http://ai.well-trust.com:8881/casdoor-callback
|
||||
CASDOOR_REDIRECT_URI=http://192.168.100.230:8881/casdoor-callback
|
||||
CASDOOR_REDIRECT_URI=https://ai.well-trust.com/casdoor-callback
|
||||
CASDOOR_SCOPE=openid profile email
|
||||
CASDOOR_ORGANIZATION=organization_HX
|
||||
# Casdoor Providers → wecom:Name 字段(截图即为 wecom);Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo
|
||||
@@ -46,6 +46,11 @@ TASK_EXECUTION_MODE=rq
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=20
|
||||
|
||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||
# 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
|
||||
|
||||
# MinIO(知识库文档清洗图片托管,容器 minio-app)
|
||||
# MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1)
|
||||
MINIO_ENDPOINT=host.docker.internal:9000
|
||||
@@ -54,3 +59,38 @@ MINIO_SECRET_KEY=difyai123456
|
||||
MINIO_SECURE=false
|
||||
# MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问
|
||||
MINIO_PUBLIC_BASE_URL=http://ai.well-trust.com:9000
|
||||
|
||||
# RoHS / 货代 / 设备维保等 Dify Tool API 基地址(Dify 服务端内网调用,无尾斜杠)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.230:8890
|
||||
# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠)
|
||||
HXOPS_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||
|
||||
# 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh
|
||||
|
||||
# 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享)
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
FREIGHT_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/inventory_drop
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/inventory_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/upload_queue
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/upload_triggers
|
||||
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致)
|
||||
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
||||
# 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
|
||||
|
||||
# 固资履历共享盘(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
|
||||
|
||||
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
+45
-27
@@ -11,6 +11,8 @@ FLASK_APP=run.py
|
||||
INTEGRATION_API_BASE=http://192.168.100.230:8891
|
||||
# 连接文档清洗系统的API KEY
|
||||
INTEGRATION_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
# 文件检核 Tool API Key;未单独配置时建议与 INTEGRATION_API_KEY 保持一致
|
||||
FILE_CHECK_TOOL_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
|
||||
SECRET_KEY=hxops-dify
|
||||
|
||||
@@ -26,7 +28,7 @@ EDKB_SOFFICE_TIMEOUT_SEC=600
|
||||
# Windows Word COM / word_bridge 单次转换超时(秒);复杂 .doc 可适当放宽
|
||||
EDKB_WORD_TIMEOUT_SEC=300
|
||||
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免单条任务长期卡住整个 worker
|
||||
EDKB_FILE_TIMEOUT_SEC=180
|
||||
EDKB_FILE_TIMEOUT_SEC=300
|
||||
# Word 文档(.doc/.docx)单文件清洗总超时(秒);优先于 EDKB_FILE_TIMEOUT_SEC
|
||||
EDKB_WORD_FILE_TIMEOUT_SEC=420
|
||||
# running 任务回收阈值,须大于 EDKB_SOFFICE_TIMEOUT_SEC 及整条清洗链路耗时
|
||||
@@ -47,10 +49,10 @@ AUTH_LOCAL_JWT_AUDIENCE=hxops-frontend
|
||||
AUTH_LOCAL_JWT_EXPIRES_HOURS=12
|
||||
|
||||
# WeCom
|
||||
WECOM_ENABLED=false
|
||||
WECOM_CORP_ID=
|
||||
WECOM_AGENT_ID=
|
||||
WECOM_SECRET=
|
||||
WECOM_ENABLED=true
|
||||
WECOM_CORP_ID=ww1ada6c11b684783e
|
||||
WECOM_AGENT_ID=1000065
|
||||
WECOM_SECRET=N9a1EE6pDj_6wTpRrXmg9Vn4BdK54jb7yFmSQ0-FSwU
|
||||
WECOM_REDIRECT_URI=
|
||||
WECOM_AUTO_CREATE_USER=true
|
||||
WECOM_MATCH_RULES=employee_id,mobile
|
||||
@@ -68,12 +70,20 @@ 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
|
||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset
|
||||
WECOM_FEEDBACK_NOTIFY_ENABLED=true
|
||||
WECOM_FEEDBACK_NOTIFY_BASE_URL=http://ai.well-trust.com:8881
|
||||
# 企业微信群机器人 webhook,按环境写入 .env.<env> 或部署平台变量;不要提交真实 URL。
|
||||
WECOM_FEEDBACK_BOT_WEBHOOK=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=bdb65cf6-e537-44b2-a10b-d826b15f4498
|
||||
|
||||
|
||||
# Common integration defaults
|
||||
INTEGRATION_API_MODE=local
|
||||
DIFY_API_BASE=https://api.dify.ai/v1
|
||||
# HXOPS Tool API 对外基地址(RoHS / 货代等 Dify Chatflow 服务端调用;无尾斜杠;各环境 .env.* 覆盖)
|
||||
HXOPS_TOOLS_API_BASE=
|
||||
# HXOPS 浏览器可访问根地址(Excel 签名下载等用户可见链接;无尾斜杠;各环境 .env.* 覆盖)
|
||||
HXOPS_PUBLIC_BASE_URL=
|
||||
|
||||
# MinIO:按环境配置见 .env.dev / .env.test / .env.prod
|
||||
# MINIO_KB_IMAGE_BUCKET — 知识库文档清洗图片托管(kb-worker / export)
|
||||
@@ -121,24 +131,32 @@ SRM_SQLSERVER_TIMEOUT=10
|
||||
ERP_DB_DSN=192.168.8.24:1521/topprod
|
||||
TEXT2SQL_SCHEMA_PATH=
|
||||
|
||||
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
||||
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
|
||||
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=120
|
||||
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=true
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||
SHIPPING_NOTICE_CHAT_DIFY_APP_ID=
|
||||
SHIPPING_NOTICE_CHAT_DIFY_API_KEY=
|
||||
SHIPPING_NOTICE_CHAT_DIFY_BASE=
|
||||
# 固资履历共享盘
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
||||
|
||||
# 固资图片文档库
|
||||
FIXED_ASSET_IMAGE_BASE_URL=http://192.168.8.158:8071/Web/#/login
|
||||
FIXED_ASSET_IMAGE_USERNAME=26040006
|
||||
FIXED_ASSET_IMAGE_PASSWORD=26040006
|
||||
FIXED_ASSET_IMAGE_LIBRARY_ID=8d61bd96-ff2d-489b-86fc-ca0b8c6bbcf8
|
||||
FIXED_ASSET_IMAGE_FOLDER_ID=3aea6c19-d9ac-40fa-ab16-9cb06c0db3e3
|
||||
|
||||
# 热点 FAQ 离线聚合(ChatLog -> PostgreSQL faq_hot_candidates 表)
|
||||
# 管理端「常用问题 > 热点发现」刷新聚合时读取以下配置
|
||||
FAQ_HOT_ENABLED=true # 是否启用热点聚合(false 时刷新/CLI 直接跳过)
|
||||
FAQ_HOT_WINDOW_DAYS=7 # 统计时间窗口(天),仅扫描近 N 天 ChatLog
|
||||
FAQ_HOT_MIN_COUNT=5 # 同一应用+问句最少提问次数,低于此不进入候选
|
||||
FAQ_HOT_MIN_USERS=3 # 最少独立用户数,防止单人刷榜
|
||||
FAQ_HOT_MIN_AVG_TOKENS=0 # 组内平均 token 下限(0=不限制;须 tokens_used>0 才纳入)
|
||||
FAQ_HOT_MAX_QUERY_LEN=200 # 问句最大字符数,过长跳过
|
||||
FAQ_HOT_MIN_QUERY_LEN=4 # 问句最短字符数,过短跳过
|
||||
FAQ_HOT_MIN_ANSWER_LEN=8 # 答案最短字符数,过短跳过
|
||||
FAQ_HOT_TTL_SECONDS=604800 # 候选/忽略黑名单有效期(秒),默认 7 天
|
||||
FAQ_HOT_ANSWER_SIMILARITY=0.95 # (聚类已关闭)答案聚类相似度阈值,恢复聚类时生效
|
||||
FAQ_HOT_ANSWER_DOMINANCE=0.6 # (聚类已关闭)最大答案簇占比下限,恢复聚类时生效
|
||||
FAQ_HOT_GOOD_SCORE=4 # 选代表答案时「好评」反馈分阈值(≥此分优先)
|
||||
FAQ_HOT_BAD_SCORE=2 # 选代表答案时「差评」反馈分阈值(≤此分排除)
|
||||
# Freight RPA defaults to real browser automation. Set to true only for local mock/debug runs.
|
||||
FREIGHT_RPA_MOCK=false
|
||||
@@ -22,17 +22,17 @@ AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
|
||||
AUTH_JWT_JWKS_URL=http://192.168.100.192:8870/.well-known/jwks
|
||||
|
||||
# Casdoor
|
||||
CASDOOR_BASE_URL=http://192.168.100.192:8870
|
||||
CASDOOR_BASE_URL=https://autht.well-trust.com
|
||||
# 与 Casdoor 里 Application「hxops-prod」(或你当前生产应用)的 Client ID 一致
|
||||
CASDOOR_CLIENT_ID=758be5fcba2df784fdb4
|
||||
CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab
|
||||
# 兜底 redirect_uri;实际 OAuth 以浏览器地址为准,Casdoor「hxops-prod」应用须登记例如:
|
||||
# http://192.168.100.192:8881/casdoor-callback
|
||||
# http://ai.well-trust.com:8881/casdoor-callback
|
||||
CASDOOR_REDIRECT_URI=http://192.168.100.192:8881/casdoor-callback
|
||||
CASDOOR_REDIRECT_URI=https://ait.well-trust.com/casdoor-callback
|
||||
CASDOOR_SCOPE=openid profile email
|
||||
CASDOOR_ORGANIZATION=organization_HX
|
||||
# Casdoor Providers → wecom:Name 字段(截图即为 wecom);Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo
|
||||
# Casdoor Providers → wecom:Name 字段;Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo
|
||||
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
||||
|
||||
# 知识库 Dify 对接
|
||||
@@ -47,7 +47,10 @@ TASK_EXECUTION_MODE=rq
|
||||
GUNICORN_WORKERS=6
|
||||
|
||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||
WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
|
||||
WECOM_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||
HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||
|
||||
# MinIO(知识库文档清洗图片托管,容器 minio-app)
|
||||
# MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1)
|
||||
@@ -57,4 +60,83 @@ MINIO_ACCESS_KEY=minio_testing_admin
|
||||
MINIO_SECRET_KEY=M3CLE928P8GavJBFZPhJO3RIHVZSRYlDouOMabasojfAGBlx
|
||||
MINIO_SECURE=false
|
||||
# MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问
|
||||
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
|
||||
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
|
||||
|
||||
# 货代发货通知 Agent(见 docs/features/shipping-notice/technical.md §1.2;Tool 基地址见 HXOPS_TOOLS_API_BASE)
|
||||
# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
|
||||
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||
HXOPS_TOOLS_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
# 货代专用 Tool API Key(RPA 回调优先读取;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=GOnGt04o0-Ev4wEw6a6C4NOmm4XF7dxsLPP6fPtTC2vV341l1QKVASV75ONj72er
|
||||
|
||||
# 文件存储(相对 backend/ 根目录)
|
||||
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
||||
|
||||
# 解析与文本上限
|
||||
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
|
||||
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
|
||||
|
||||
# 字段对齐确认(生产建议 true;测试可设 false)
|
||||
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true
|
||||
|
||||
# 自动推进(auto_progress)
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
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
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||
|
||||
# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享)
|
||||
FREIGHT_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers
|
||||
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐)
|
||||
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
||||
# 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微
|
||||
# 两者皆无则告警只写日志、不会发企微
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
|
||||
# 企微发送中短锁秒数(发送失败过期后可重试,默认 120)
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
|
||||
|
||||
# 发货 Excel 模板(可选)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
|
||||
|
||||
# 固资履历共享盘(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
|
||||
|
||||
# AWS 库存列映射(可选 JSON 字符串)
|
||||
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
|
||||
|
||||
# Dify Chatflow(seed_shipping_notice_agents.py)
|
||||
SHIPPING_NOTICE_CHAT_DIFY_APP_ID=
|
||||
SHIPPING_NOTICE_CHAT_DIFY_API_KEY=
|
||||
SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
|
||||
|
||||
# 本地 Mock RPA(scripts/rpa/freight_rpa_worker.py,可选)
|
||||
# FREIGHT_RPA_MOCK=true
|
||||
# FREIGHT_RPA_POLL_SECONDS=3
|
||||
# FREIGHT_RPA_SAMPLE_INVENTORY=
|
||||
|
||||
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
+16
-2
@@ -5,11 +5,12 @@ ROOT_DIR="$(git rev-parse --show-toplevel)"
|
||||
# shellcheck source=_common.sh
|
||||
source "${ROOT_DIR}/.githooks/_common.sh"
|
||||
|
||||
if hook_should_skip; then
|
||||
if [[ "${SKIP_GIT_HOOKS:-}" == "1" ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
zero="0000000000000000000000000000000000000000"
|
||||
need_migration_check=0
|
||||
need_frontend_build=0
|
||||
|
||||
while read -r local_ref local_sha remote_ref remote_sha; do
|
||||
@@ -33,12 +34,25 @@ while read -r local_ref local_sha remote_ref remote_sha; do
|
||||
changed_files="$(git diff --name-only --diff-filter=ACMR "${remote_sha}" "${local_sha}" || true)"
|
||||
fi
|
||||
|
||||
if echo "${changed_files}" | grep -qE '^backend/migrations/versions/.*\.py$'; then
|
||||
need_migration_check=1
|
||||
fi
|
||||
|
||||
if frontend_paths_in "${changed_files}"; then
|
||||
need_frontend_build=1
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ "${need_migration_check}" -eq 1 ]]; then
|
||||
if ! run_migration_heads_check "${ROOT_DIR}"; then
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ "${SKIP_FRONTEND_HOOKS:-}" == "1" ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [[ "${need_frontend_build}" -eq 0 ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
+15
-3
@@ -26,8 +26,9 @@ share/python-wheels/
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
# Pytest / local temp
|
||||
backend/.pytest_tmp/
|
||||
.pytest_tmp/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
@@ -46,10 +47,15 @@ frontend/public/WW_verify_46MjWA55y3PBRLid.txt
|
||||
frontend/package-lock.json
|
||||
|
||||
# IDEs
|
||||
.vscode/
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/extensions.json
|
||||
.trae/*
|
||||
.cursor/*
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
.cursorrules
|
||||
|
||||
# Runtime files
|
||||
.run/
|
||||
@@ -74,3 +80,9 @@ oracle_client/
|
||||
|
||||
# local env override
|
||||
.env.local
|
||||
backend/data/kb/
|
||||
.pytest_cache/
|
||||
backend/data/fixed_assets/manifest.json
|
||||
backend/data/shipping_notice/
|
||||
backend/data/logs/
|
||||
backend/data/logs/*.log
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"recommendations": ["ms-python.python", "ms-python.vscode-pylance"]
|
||||
}
|
||||
Vendored
+59
@@ -0,0 +1,59 @@
|
||||
{
|
||||
// 后端 Python 虚拟环境(解释器路径供语言服务/调试使用)
|
||||
"python.defaultInterpreterPath": "${workspaceFolder}/backend/.venv/Scripts/python.exe",
|
||||
// 关闭 Python 扩展在新建终端时自动 activate,避免与下方 PowerShell (HXOPS) 的 cd 钩子重复激活
|
||||
"python.terminal.activateEnvironment": false,
|
||||
"python.venvPath": "${workspaceFolder}/backend",
|
||||
"python.venvFolders": [".venv"],
|
||||
"github.copilot.chat.commitMessageGeneration.instructions": [
|
||||
{
|
||||
"text": "Generate Git commit messages in Simplified Chinese by default."
|
||||
},
|
||||
{
|
||||
"text": "Follow Conventional Commits format: <type>(<scope>): <subject>."
|
||||
},
|
||||
{
|
||||
"text": "Use English for type and scope; use Simplified Chinese for subject and body."
|
||||
},
|
||||
{
|
||||
"text": "Allowed types are feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert."
|
||||
},
|
||||
{
|
||||
"text": "The subject must be imperative, no period at the end, and no longer than 100 Chinese characters."
|
||||
},
|
||||
{
|
||||
"text": "Avoid vague messages such as update, fix bug, or WIP."
|
||||
},
|
||||
{
|
||||
"text": "When a body is useful, write concise Chinese bullet points describing concrete changes."
|
||||
}
|
||||
],
|
||||
|
||||
// 默认终端:加载 cd 钩子,进入 backend 时自动激活 .venv
|
||||
"terminal.integrated.defaultProfile.windows": "PowerShell (HXOPS)",
|
||||
"terminal.integrated.profiles.windows": {
|
||||
"PowerShell (HXOPS)": {
|
||||
"source": "PowerShell",
|
||||
"icon": "terminal-powershell",
|
||||
"args": [
|
||||
"-NoExit",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-File",
|
||||
"${workspaceFolder}/scripts/powershell-backend-auto-venv.ps1"
|
||||
]
|
||||
},
|
||||
"HXOPS Backend": {
|
||||
"source": "PowerShell",
|
||||
"icon": "server-environment",
|
||||
"args": [
|
||||
"-NoExit",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-Command",
|
||||
"Set-Location '${workspaceFolder}/backend'; if (Test-Path '.venv/Scripts/Activate.ps1') { . '.venv/Scripts/Activate.ps1' }"
|
||||
]
|
||||
}
|
||||
},
|
||||
"js/ts.tsdk.path": "node_modules\\typescript\\lib"
|
||||
}
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
# AGENTS.md — HXOPS 协作与开发规范
|
||||
|
||||
> 本文件是 **AI 编程助手(Cursor / Codex 等)和团队成员的统一入口**。
|
||||
> 原则:**只写最关键的强约束、速览与索引,详细内容一律链接到 `docs/` 下的权威文档**,避免双份维护。
|
||||
> 修改本文件请走正常评审;规则若与 `docs/` 冲突,以 `docs/` 中的专项文档为准。
|
||||
|
||||
---
|
||||
|
||||
## 1. 项目速览
|
||||
|
||||
**Enterprise AI Gateway(HXOPS)**:企业级 AI 聚合网关,统一管理/分发 AI Agent(Dify 应用),提供统一对话入口、RBAC 权限、全链路审计与个性化工作台。
|
||||
|
||||
| 层 | 技术栈 |
|
||||
| --- | --- |
|
||||
| 前端 | Vue 3 (Composition API) + TypeScript + Vite + TailwindCSS + Pinia + Vue Router + Vue I18n |
|
||||
| 后端 | Flask (Python 3.12) + Gevent + SQLAlchemy 2.0 + Flask-Migrate(Alembic) + Gunicorn |
|
||||
| 数据/基建 | PostgreSQL + Redis + Nginx + Supervisor + Docker Compose |
|
||||
| 集成 | Dify、企业微信、OA/HR(SQLServer)、PLM(Oracle)、MinIO |
|
||||
| 研发协作 | Gitee 托管 + Jenkins CI/CD(dev/test/prod 多环境) |
|
||||
|
||||
完整背景见 **[docs/project_context.md](docs/project_context.md)**。
|
||||
|
||||
---
|
||||
|
||||
## 2. 技术架构统一(新功能选型)
|
||||
|
||||
> 仓库历史代码后端为 Flask,仍按原栈维护;**新功能/新模块**统一向以下技术栈收敛:
|
||||
|
||||
- **后端**:优先使用 **Python + FastAPI**(异步、Pydantic 校验、自动 OpenAPI 文档)。
|
||||
- **前端**:优先使用 **Vue 3 + TailwindCSS**(Composition API + TypeScript)。
|
||||
- 数据访问继续使用 **SQLAlchemy 2.0**;数据库迁移继续使用 **Alembic**(见 §8)。
|
||||
- 选型有特殊需要偏离上述约定时,须在评审/提交说明中给出理由。
|
||||
|
||||
---
|
||||
|
||||
## 3. 目录地图(改代码前先定位)
|
||||
|
||||
```text
|
||||
backend/app/
|
||||
api/ # Blueprint 路由(admin / chat / agents / knowledge_base / shipping_notice ...)
|
||||
services/ # 业务逻辑(dify、oa_*、plm_oracle、minio_service、wecom_* ...)
|
||||
models.py # SQLAlchemy 模型(改这里必须配套迁移,见 §8)
|
||||
response_utils.py / errors.py / decorators.py # 统一返回、异常、权限装饰器
|
||||
backend/migrations/ # Alembic 迁移文件
|
||||
frontend/src/
|
||||
features/ # 按业务域组织(admin / auth / chat)
|
||||
composables/# Hooks(如 useChat.ts)
|
||||
views/ components/ i18n.ts
|
||||
scripts/ # 部署与运维脚本(deploy_compose.sh、healthcheck.sh ...)
|
||||
docs/ # 权威文档(规范、上下文、流程、发布说明)
|
||||
```
|
||||
|
||||
**约定**:新逻辑优先放入对应 `services/`(后端)或 `features/composables/`(前端),复用既有 `response_utils` / `errors` / `decorators` 模式,不要另造轮子。
|
||||
|
||||
---
|
||||
|
||||
## 4. 常用命令
|
||||
|
||||
```bash
|
||||
# 后端
|
||||
cd backend && source venv/bin/activate
|
||||
python run.py # 启动开发服务器
|
||||
flask db migrate -m "msg" && flask db upgrade # 数据库迁移
|
||||
|
||||
# 前端
|
||||
cd frontend && npm run dev # 开发
|
||||
npm run build # 改动了 frontend/ 必须保证 build 通过
|
||||
|
||||
# 部署(与 Jenkins 一致,示例:prod)
|
||||
./scripts/deploy_compose.sh prod true true true
|
||||
docker compose logs -f hxops-backend
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 代码规范与注释
|
||||
|
||||
> **适用范围**:**新建或调整**业务代码(人工与 AI Agent 均适用)。Agent 持久规则见 **[`.cursor/rules/code-comments.mdc`](.cursor/rules/code-comments.mdc)**。
|
||||
|
||||
### 5.1 文件层注释(必须)
|
||||
|
||||
每个源文件顶部须有块注释,说明:
|
||||
|
||||
1. **用途**:本文件在模块/业务流程中的职责。
|
||||
2. **引用关系**:主要 `import` / 依赖的上游模块或文件(不必列全量 import,列关键依赖即可)。
|
||||
3. **逻辑关系**:与同级或上下游文件如何协作(谁调用谁、数据/状态如何流转)。
|
||||
|
||||
| 语言/形态 | 写法 |
|
||||
| --- | --- |
|
||||
| 前端 TS/JS | 文件首行 `/** ... */`(JSDoc 块注释) |
|
||||
| Vue SFC | 写在 `<script>` / `<script setup>` 块内首行 |
|
||||
| 后端 Python | 模块级 docstring(文件首行三引号字符串) |
|
||||
|
||||
### 5.2 函数层注释(必须)
|
||||
|
||||
**每个函数**(含方法、composable、路由 handler、类方法;导出的工具函数、组件内 `<script setup>` 函数均包含在内)在定义**上方**须有注释,说明:
|
||||
|
||||
1. **用途**:该函数解决什么问题、在调用链中的位置。
|
||||
2. **核心逻辑与实现方式**:关键步骤、算法/策略、外部服务或副作用。
|
||||
3. **参数与输出**:每个入参含义、返回值含义;可能抛出的异常或错误码(如有)。
|
||||
|
||||
| 语言 | 写法 |
|
||||
| --- | --- |
|
||||
| 前端 | JSDoc:`@param` / `@returns` / `@throws`(TypeScript 类型无法表达的业务约束写在描述里) |
|
||||
| 后端 | docstring(Google 或 NumPy 风格均可,须含 Args/Returns/Raises 或等价段落) |
|
||||
|
||||
**调整既有代码时**:修改函数签名、逻辑或副作用,必须**同步更新**对应函数注释;协作关系变化时同步更新文件层注释。
|
||||
|
||||
### 5.3 其它约定
|
||||
|
||||
- **函数内**:不必逐行复述「是什么」;对非显而易见的分支、业务规则、兼容处理、外部协议/边界条件可补 brief 行内注释。
|
||||
- **复杂或临时方案**:临时方案用 `TODO:` / `FIXME:` 标注并附原因或关联任务号。
|
||||
- **注释与代码同步**:禁止留下与实现不符的过期注释。
|
||||
- **统一语言**:注释可用中文,术语/标识符保持与代码一致。
|
||||
- **禁止**用注释提交被注释掉的废弃代码(交给 Git 历史管理)。
|
||||
|
||||
### 5.4 测试代码
|
||||
|
||||
测试代码在 §5.1–§5.2 基础上,另须 **代码层注释**(函数内关键断言与分支意图),见 **[docs/test_plan_matrix.md](docs/test_plan_matrix.md) §1**。
|
||||
|
||||
---
|
||||
|
||||
## 6. Git 提交规范(强制 / 已自动校验)
|
||||
|
||||
- 提交信息必须符合 **Conventional Commits**,由 `commitlint.config.cjs` + `.githooks/commit-msg` **自动拦截**。
|
||||
- 首次拉取后需安装 hooks:`./scripts/install_git_hooks.sh`。
|
||||
- 格式:`<type>(<scope>): <subject>`;`type`/`scope` 英文(scope 为 kebab-case 模块名),`subject` 中文,祈使语气、不以句号结尾、≤100 字符。
|
||||
- 允许的 `type`:`feat` `fix` `docs` `style` `refactor` `perf` `test` `build` `ci` `chore` `revert`。
|
||||
- 禁止无语义提交(`update`、`fix bug`、`111`);一个提交只做一件事。
|
||||
- **Cursor IDE**:源代码管理 ✨「Generate commit message」仅读取根目录 **`.cursorrules`**(不读 `.cursor/rules/`、`AGENTS.md`);**Agent 写/改代码**读 `AGENTS.md` §5 与 **`.cursor/rules/`**(如 `code-comments.mdc`);Agent 代提交读 `.cursor/rules/`。
|
||||
|
||||
详见 **[docs/convention/COMMIT_CONVENTION.md](docs/convention/COMMIT_CONVENTION.md)** 与 **[docs/GIT_HOOKS.md](docs/GIT_HOOKS.md)**。
|
||||
|
||||
---
|
||||
|
||||
## 7. 分支与发布流程
|
||||
|
||||
- 分支主线:`dev`(日常开发)→ `test`(自测/交叉/质检)→ `prod`(生产发布)。
|
||||
- 功能分支从 `dev` 切出(`feature/xxx`、`fix/xxx`),完成后合回 `dev`。
|
||||
- **禁止**直接在 `prod` / 公共分支上开发或直推;`prod` 必须经合并请求。
|
||||
- 生产 hotfix 合入 `prod` 后须**反向同步**回 `dev`(必要时 `test`),避免分支漂移。
|
||||
- 发布完成对版本打 tag,格式 `V26.6.1`(26 年 6 月第 1 次发布)。
|
||||
|
||||
完整流程(含自测/交叉测试/质检/Review 卡点)见 **[docs/release_workflow.md](docs/release_workflow.md)** 与 **[docs/convention/开发标准流程.md](docs/convention/开发标准流程.md)**。
|
||||
|
||||
---
|
||||
|
||||
## 8. 红线与高风险约束(agent 必须遵守)
|
||||
|
||||
- 🔒 **严禁提交任何密钥/密码/生产地址等敏感信息**。`.env.local` / `.env.*` 不进仓库的部分不得硬编码进代码或提交。
|
||||
- 🧬 **修改数据库表结构必须配套迁移**:任何对 `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-US / th-TH`,禁止硬编码中文。
|
||||
- 📡 **SSE 流式约束**:对话链路依赖 Gevent 异步 worker + Nginx `proxy_buffering off`;对话接口(`chat.py`)使用原生 Fetch/SSE 而非 Axios,改动需保持流式不被破坏。
|
||||
- 🔌 **外部集成依赖**:Oracle Instant Client 19.30 / `pyodbc` / `zeep`(OA、PLM、HR)等本地未必可运行,涉及这些 service 时谨慎并说明。
|
||||
- ➕ **新增依赖需克制**:不擅自引入未经评审的第三方依赖;如需新增,在提交说明中给出理由。
|
||||
- 📝 **注释两层标准(强制)**:新建或调整代码须满足 §5 文件层 + 函数层注释;AI 生成/重构代码同样适用,不得省略。
|
||||
- ⚠️ 改动**数据库结构、部署脚本(`scripts/`、`Jenkinsfile`、`docker-compose.yml`)或敏感配置**前,先说明影响面再动手。
|
||||
|
||||
合并前最低自检(详见 [新人文档 §3.3](docs/新人环境搭建与配置文档.md)):前后端可启动、`frontend/` 改动后 `npm run build` 通过、关键页面与登录可用。
|
||||
|
||||
---
|
||||
|
||||
## 9. 需求与文档维护(开发前先查,开发后必更)
|
||||
|
||||
开发任何功能前,**优先查阅以下文档**了解背景与现状:
|
||||
|
||||
- **[docs/demand.md](docs/demand.md)** — 需求文档(要做什么、业务目标与范围)。
|
||||
- **[docs/tec.md](docs/tec.md)** — 技术架构文档(架构设计、技术选型与约束)。
|
||||
- **[docs/funclist.md](docs/funclist.md)** — 功能清单(已有/在建功能总览)。
|
||||
|
||||
**撰写或变更功能时,必须同步更新相关文档**:
|
||||
|
||||
- 新增/调整功能 → 更新 `funclist.md`(功能清单)。
|
||||
- 涉及需求变化 → 更新 `demand.md`。
|
||||
- 涉及架构/技术选型变化 → 更新 `tec.md`。
|
||||
- 文档更新与代码改动放在同一提交或同一 PR 中,保证「代码与文档一致」。
|
||||
|
||||
---
|
||||
|
||||
## 10. 文档索引(权威来源)
|
||||
|
||||
| 主题 | 文档 |
|
||||
| --- | --- |
|
||||
| 项目上下文 / 架构 / 数据模型 | [docs/project_context.md](docs/project_context.md) |
|
||||
| 需求文档 | [docs/demand.md](docs/demand.md) |
|
||||
| 技术架构文档 | [docs/tec.md](docs/tec.md) |
|
||||
| 功能清单 | [docs/funclist.md](docs/funclist.md) |
|
||||
| 新人环境搭建 / 分支原则 | [docs/新人环境搭建与配置文档.md](docs/新人环境搭建与配置文档.md) |
|
||||
| 发布流程(dev→test→prod) | [docs/release_workflow.md](docs/release_workflow.md) · [docs/convention/开发标准流程.md](docs/convention/开发标准流程.md) |
|
||||
| 提交规范 | [docs/convention/COMMIT_CONVENTION.md](docs/convention/COMMIT_CONVENTION.md) |
|
||||
| Git Hooks | [docs/GIT_HOOKS.md](docs/GIT_HOOKS.md) |
|
||||
| 环境变量 | [docs/convention/env_loading_priority.md](docs/convention/env_loading_priority.md) · [docs/convention/环境变量规则.md](docs/convention/环境变量规则.md) |
|
||||
| 知识库部署 | [docs/knowledge_base_runtime_deploy.md](docs/knowledge_base_runtime_deploy.md) |
|
||||
| Excel/CSV 切块与 Dify 分段 | [docs/kb-excel-dify-chunking.md](docs/kb-excel-dify-chunking.md) |
|
||||
| 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.md) |
|
||||
@@ -43,14 +43,25 @@ backend/app/
|
||||
response_utils.py / errors.py / decorators.py # 统一返回、异常、权限装饰器
|
||||
backend/migrations/ # Alembic 迁移文件
|
||||
frontend/src/
|
||||
features/ # 按业务域组织(admin / auth / chat)
|
||||
composables/# Hooks(如 useChat.ts)
|
||||
views/ components/ i18n.ts
|
||||
main.ts · App.vue · i18n.ts · config.ts # Vite 入口(保留 src 根)
|
||||
app/ # 应用基础设施:router/(routes/* · guards)、plugins/pinia
|
||||
shared/ # 跨域共享(无业务语义)
|
||||
# api/client · composables · components · layouts · utils · styles
|
||||
features/ # 业务域垂直切分(新代码主要落在这里)
|
||||
# auth · workspace · chat · admin · kb
|
||||
# 域内:api/ · composables/ · views/ · stores/ · components/
|
||||
# admin 子模块:modules/<name>/*Page.vue + use*Admin.ts
|
||||
locales/ # i18n 四语言 JSON(zh-CN / zh-TW / en / th),按域拆分
|
||||
scripts/ # 部署与运维脚本(deploy_compose.sh、healthcheck.sh ...)
|
||||
docs/ # 权威文档(规范、上下文、流程、发布说明)
|
||||
# features/ 业务域手册 · platform/ 平台设计 · prototype/ 产品原型
|
||||
# convention/ · openapi/ · dify/ · refactor/
|
||||
```
|
||||
|
||||
**约定**:新逻辑优先放入对应 `services/`(后端)或 `features/composables/`(前端),复用既有 `response_utils` / `errors` / `decorators` 模式,不要另造轮子。
|
||||
**约定**:
|
||||
|
||||
- **后端**:新逻辑优先放入 `services/`,复用 `response_utils` / `errors` / `decorators` 模式,不要另造轮子。
|
||||
- **前端**:Feature-Module + Composables + Pinia;新功能放入 `features/<domain>/`(`api/` · `composables/` · `views/` 等),跨域通用代码放 `shared/`;HTTP 统一 `@/shared/api/client`。**禁止**在已废弃的 `src/api/`、`src/views/`、`src/composables/` 等路径新增代码。完整规范见 **[docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md)**。
|
||||
|
||||
---
|
||||
|
||||
@@ -72,27 +83,50 @@ docker compose logs -f hxops-backend
|
||||
```
|
||||
|
||||
---
|
||||
## 5. 代码规范与注释 (Code & Comments)
|
||||
|
||||
## 5. 代码规范与注释
|
||||
> **适用范围**:**新建或调整**业务代码(人工与 AI Agent 均适用)。
|
||||
> **核心理念**:我们的注释采用“三层结构”,**既是写给人类团队看的,更是写给 AI(大模型/代码助手)看的**。
|
||||
> 🚨 **详细规范与标准范例,请严格遵循:[`.cursor/rules/code-comments.mdc`](.cursor/rules/code-comments.mdc)**。
|
||||
|
||||
- **注释写「为什么」,不写「是什么」**:避免逐行复述代码(如 `// 自增 i`、`# 调用接口`);只对非显而易见的意图、权衡、约束、坑点、外部协议/边界条件加注释。
|
||||
- **公共接口必须有文档注释**:
|
||||
- 后端:对外的函数/类/接口使用 docstring,说明用途、参数、返回、可能抛出的异常;FastAPI 路由用类型注解 + Pydantic 模型,复杂逻辑补 docstring。
|
||||
- 前端:导出的 composable / 工具函数 / 复杂组件 props 用 JSDoc/TSDoc 说明。
|
||||
- **复杂或临时方案要留痕**:含业务规则、算法、兼容性处理的代码段加简要说明;临时方案用 `TODO:` / `FIXME:` 标注并附原因或关联任务号。
|
||||
- **注释与代码同步更新**:改逻辑必须同步改注释,禁止留下与实现不符的过期注释。
|
||||
- **统一语言**:注释可用中文,但术语/标识符保持与代码一致,避免中英混排导致歧义。
|
||||
- 不要用注释提交被注释掉的废弃代码(交给 Git 历史管理)。
|
||||
### 5.1 文件层注释(全局概览)
|
||||
|
||||
每个源文件顶部须有块注释,帮助新人与 AI 快速建立全局认知。核心包含三要素:
|
||||
1. **用途**:本文件在业务流程中的职责。
|
||||
2. **依赖关系**:主要引用的上游模块(列关键即可)。
|
||||
3. **逻辑关系**:与上下游文件如何协作(数据流转或调用关系)。
|
||||
*(前端写在文件/Script首行块注释,后端使用模块级 docstring)*
|
||||
|
||||
### 5.2 函数与工具层注释(面向 AI 调用)
|
||||
|
||||
**每个核心函数**定义上方必须有注释。**极其重要**:如果该函数是被大模型调用的 Agent Tool,其注释将直接影响 AI 的判断。
|
||||
1. **用途与触发时机**:解决什么问题。**作为 AI 工具时,必须用大白话写明【AI 触发时机】**。
|
||||
2. **核心逻辑**:关键步骤与外部通讯流。
|
||||
3. **参数与输出约束**:除常规类型外,必须说明业务约束(如“禁止传入省份”、“必须返回 JSON”),以防 AI 乱传参。
|
||||
*(前端使用 JSDoc,后端使用含 Args/Returns 的 docstring)*
|
||||
|
||||
### 5.3 代码逻辑与 AI 专项标记
|
||||
|
||||
函数内部**严禁逐行翻译代码**(如说明 `i=i+1`)。应聚焦于“为什么这么做”以及 AI 的调优溯源:
|
||||
- **逻辑分块**:对非显而易见的长流程,使用 `[STEP 1]`, `[STEP 2]` 标注业务步骤。
|
||||
- **AI 调优溯源**:修改 Prompt 或大模型参数(如 Temperature)时,**强制使用 `[PROMPT_UPDATE]` 或 `[PARAM_TUNING]` 标注原因**。
|
||||
- **临时方案**:用 `TODO:` / `FIXME:` 标注并附原因或任务号。
|
||||
- **一致性纪律**:修改代码逻辑、修改协作关系,必须**同步更新**对应注释!禁止留下过期注释误导 AI。
|
||||
- **整洁度**:禁止用注释提交废弃代码(请交给 Git 历史管理)。
|
||||
|
||||
### 5.4 测试代码注释
|
||||
|
||||
测试代码在遵循上述基础之上,另须具备**代码层面的断言注释**(说明关键断言与分支测试意图),详见 **[docs/test_plan_matrix.md](docs/test_plan_matrix.md) §1**。
|
||||
---
|
||||
|
||||
## 6. Git 提交规范(强制 / 已自动校验)
|
||||
|
||||
- 提交信息必须符合 **Conventional Commits**,由 `commitlint.config.cjs` + `.githooks/commit-msg` **自动拦截**。
|
||||
- 首次拉取后需安装 hooks:`./scripts/install_git_hooks.sh`。
|
||||
- 格式:`<type>(<scope>): <subject>`,`subject` 用祈使语气、不以句号结尾、≤100 字符。
|
||||
- 格式:`<type>(<scope>): <subject>`;`type`/`scope` 英文(scope 为 kebab-case 模块名),`subject` 中文,祈使语气、不以句号结尾、≤100 字符。
|
||||
- 允许的 `type`:`feat` `fix` `docs` `style` `refactor` `perf` `test` `build` `ci` `chore` `revert`。
|
||||
- 禁止无语义提交(`update`、`fix bug`、`111`);一个提交只做一件事。
|
||||
- **Cursor IDE**:源代码管理 ✨「Generate commit message」仅读取根目录 **`.cursorrules`**(不读 `.cursor/rules/`、`AGENTS.md`);**Agent 写/改代码**读 `AGENTS.md` §5 与 **`.cursor/rules/`**(如 `code-comments.mdc`);Agent 代提交读 `.cursor/rules/`。
|
||||
|
||||
详见 **[docs/convention/COMMIT_CONVENTION.md](docs/convention/COMMIT_CONVENTION.md)** 与 **[docs/GIT_HOOKS.md](docs/GIT_HOOKS.md)**。
|
||||
|
||||
@@ -119,6 +153,8 @@ docker compose logs -f hxops-backend
|
||||
- 📡 **SSE 流式约束**:对话链路依赖 Gevent 异步 worker + Nginx `proxy_buffering off`;对话接口(`chat.py`)使用原生 Fetch/SSE 而非 Axios,改动需保持流式不被破坏。
|
||||
- 🔌 **外部集成依赖**:Oracle Instant Client 19.30 / `pyodbc` / `zeep`(OA、PLM、HR)等本地未必可运行,涉及这些 service 时谨慎并说明。
|
||||
- ➕ **新增依赖需克制**:不擅自引入未经评审的第三方依赖;如需新增,在提交说明中给出理由。
|
||||
- 📝 **注释两层标准(强制)**:新建或调整代码须满足 §5 文件层 + 函数层注释;AI 生成/重构代码同样适用,不得省略。
|
||||
- ⚠️ **错误处理统一契约**:JSON API 使用 `{ success, data | error, request_id }` envelope;后端业务失败 **`raise AppError` 子类**(`app/core/errors.py`),禁止新写 `jsonify({"error": ...})`;前端 HTTP 统一 **`requestJson`**(`@/shared/api/client`),失败为 **`BusinessError`**,在 composable/view 用 **`useMessage()`** 展示;新增 `error.code` 须同步四语言 **`locales/*/errors.json`**。详见 **[docs/convention/error_handling.md](docs/convention/error_handling.md)**。
|
||||
- ⚠️ 改动**数据库结构、部署脚本(`scripts/`、`Jenkinsfile`、`docker-compose.yml`)或敏感配置**前,先说明影响面再动手。
|
||||
|
||||
合并前最低自检(详见 [新人文档 §3.3](docs/新人环境搭建与配置文档.md)):前后端可启动、`frontend/` 改动后 `npm run build` 通过、关键页面与登录可用。
|
||||
@@ -146,6 +182,7 @@ docker compose logs -f hxops-backend
|
||||
|
||||
| 主题 | 文档 |
|
||||
| --- | --- |
|
||||
| **文档总索引** | [docs/README.md](docs/README.md) |
|
||||
| 项目上下文 / 架构 / 数据模型 | [docs/project_context.md](docs/project_context.md) |
|
||||
| 需求文档 | [docs/demand.md](docs/demand.md) |
|
||||
| 技术架构文档 | [docs/tec.md](docs/tec.md) |
|
||||
@@ -156,4 +193,13 @@ docker compose logs -f hxops-backend
|
||||
| Git Hooks | [docs/GIT_HOOKS.md](docs/GIT_HOOKS.md) |
|
||||
| 环境变量 | [docs/convention/env_loading_priority.md](docs/convention/env_loading_priority.md) · [docs/convention/环境变量规则.md](docs/convention/环境变量规则.md) |
|
||||
| 知识库部署 | [docs/knowledge_base_runtime_deploy.md](docs/knowledge_base_runtime_deploy.md) |
|
||||
| Excel/CSV 切块与 Dify 分段 | [docs/kb-excel-dify-chunking.md](docs/kb-excel-dify-chunking.md) |
|
||||
| FAQ 缓存 / 热点发现运维 | [docs/faq_cache_ops_manual.md](docs/faq_cache_ops_manual.md) |
|
||||
| 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.md) |
|
||||
| 前端架构规范 | [docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md) |
|
||||
| 错误处理规范 | [docs/convention/error_handling.md](docs/convention/error_handling.md) |
|
||||
| **业务域文档索引** | [docs/features/README.md](docs/features/README.md) |
|
||||
| 货代发货通知 | [docs/features/shipping-notice/technical.md](docs/features/shipping-notice/technical.md) |
|
||||
| 文件检核 | [docs/features/file-check/technical.md](docs/features/file-check/technical.md) |
|
||||
| Agent 应用管理(设计) | [docs/platform/agent_application_management.md](platform/agent_application_management.md) |
|
||||
| Agent 应用管理(实现) | [docs/platform/agent_application_management_implementation.md](platform/agent_application_management_implementation.md) |
|
||||
Vendored
+8
-4
@@ -147,7 +147,8 @@ def notifyPushPlusDeploy(Map opts) {
|
||||
// 企业微信 + PushPlus 微信双通道
|
||||
def notifyDeployAll(Map opts) {
|
||||
notifyWecomDeploy(opts)
|
||||
notifyPushPlusDeploy(opts)
|
||||
// 暂时只发企业微信通知
|
||||
// notifyPushPlusDeploy(opts)
|
||||
}
|
||||
|
||||
pipeline {
|
||||
@@ -167,11 +168,11 @@ pipeline {
|
||||
defaultValue: false,
|
||||
description: '仅当本地 diff 判定无前后端/部署配置变更时生效:额外 SSH 到本分支对应目标机执行 git rev-parse / branch --show-current,与本次 GIT_COMMIT、BRANCH_NAME 比对,不一致则视为需要部署。'
|
||||
)
|
||||
// 生产镜像回滚:填写历史 tag 后缀(如 prod-a1b2c3d4),走 deploy_compose.sh 预构建模式
|
||||
// 生产镜像回滚:填写 Git 7 位短 hash 后缀(如 prod-e5b65d9),走 deploy_compose.sh 预构建模式
|
||||
string(
|
||||
name: 'ROLLBACK_IMAGE_TAG',
|
||||
defaultValue: '',
|
||||
description: '【仅生产】非空时回滚到该镜像 tag(hxops-frontend:<tag> / hxops-backend:<tag>)。示例:prod-a1b2c3d4。不拉最新代码、不执行 db upgrade。留空为正常部署。'
|
||||
description: '【仅生产】非空时回滚到该镜像 tag(hxops-frontend:<tag> / hxops-backend:<tag>)。示例:prod-e5b65d9(Git 短 hash 7 位)。不拉最新代码、不执行 db upgrade。留空为正常部署。'
|
||||
)
|
||||
}
|
||||
|
||||
@@ -201,6 +202,9 @@ pipeline {
|
||||
|
||||
// PushPlus 群组编码(一对多推送到个人微信);Token 仍用 Jenkins 凭据 PUSHPLUS_DEPLOY_TOKEN
|
||||
PUSHPLUS_TOPIC = 'hxops666'
|
||||
|
||||
// 生产机保留的可回滚镜像 tag 数量(deploy_compose.sh 按 ${ENV_NAME}-<commit> 清理旧 tag)
|
||||
IMAGE_TAG_RETAIN_COUNT = '10'
|
||||
}
|
||||
|
||||
stages {
|
||||
@@ -527,7 +531,7 @@ pipeline {
|
||||
git checkout -B ${BRANCH_NAME} origin/${BRANCH_NAME}
|
||||
git reset --hard "origin/${BRANCH_NAME}"
|
||||
chmod +x scripts/deploy_compose.sh scripts/healthcheck.sh
|
||||
GIT_COMMIT=${env.GIT_COMMIT} ./scripts/deploy_compose.sh prod "" "" ${FRONTEND_CHANGED} ${BACKEND_CHANGED} ${DEPLOY_CONFIG_CHANGED}
|
||||
GIT_COMMIT=${env.GIT_COMMIT} IMAGE_TAG_RETAIN_COUNT=${env.IMAGE_TAG_RETAIN_COUNT} ./scripts/deploy_compose.sh prod "" "" ${FRONTEND_CHANGED} ${BACKEND_CHANGED} ${DEPLOY_CONFIG_CHANGED}
|
||||
'
|
||||
"""
|
||||
}
|
||||
|
||||
+31
-40
@@ -1,21 +1,22 @@
|
||||
"""
|
||||
backend/app/__init__.py
|
||||
应用工厂:创建 Flask 应用、注册蓝图并挂载全局异常与响应处理。
|
||||
|
||||
用途:应用工厂:创建 Flask 应用、挂载全局异常与响应处理。
|
||||
依赖:app.extensions(db、migrate)、app.api.register_blueprints、app.core.config。
|
||||
逻辑:create_app 初始化扩展后委托 api 层集中注册 Blueprint;启动时 load_context_adapters 注册 Dify 上下文 adapter;
|
||||
并幂等补建 file-asset-cleanup 默认排程(覆盖空库先迁移后建用户)。
|
||||
"""
|
||||
import logging
|
||||
import uuid
|
||||
|
||||
from flask import Flask, jsonify, request, g
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
from flask_cors import CORS
|
||||
from werkzeug.exceptions import HTTPException
|
||||
from app.config import config
|
||||
from app.errors import AppError
|
||||
from app.response_utils import error_payload, utc_iso_now
|
||||
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
from app.core.config.settings import config
|
||||
from app.core.errors import AppError
|
||||
from app.extensions import db, migrate
|
||||
from app.core.response import error_payload, utc_iso_now
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -27,7 +28,7 @@ def _apply_persisted_settings(app: Flask) -> None:
|
||||
common case where the table does not yet exist (fresh deploy before
|
||||
``flask db upgrade`` runs).
|
||||
"""
|
||||
from app.env_persistence import apply_env_settings
|
||||
from app.core.config.env_persistence import apply_env_settings
|
||||
|
||||
try:
|
||||
applied = apply_env_settings()
|
||||
@@ -46,38 +47,9 @@ def create_app(config_name='default'):
|
||||
migrate.init_app(app, db)
|
||||
CORS(app) # 允许跨域
|
||||
|
||||
# 注册 Blueprints
|
||||
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 user_bp
|
||||
from app.api.knowledge_base import knowledge_base_bp
|
||||
from app.api.integration import integration_bp
|
||||
from app.api.schedule_admin import schedule_admin_bp
|
||||
from app.api.workspace_schedule import workspace_schedule_bp
|
||||
from app.api.workspace_shipping_notice import workspace_shipping_notice_bp
|
||||
from app.api.internal_jobs import internal_jobs_bp
|
||||
from app.api.shipping_notice_tools import shipping_notice_bp
|
||||
from app.api.speech import speech_bp
|
||||
from app.api import register_blueprints
|
||||
|
||||
# 聊天相关接口
|
||||
app.register_blueprint(chat_bp, url_prefix='/api/chat')
|
||||
# 管理员相关接口
|
||||
app.register_blueprint(admin_bp, url_prefix='/api/admin')
|
||||
# 普通用户可见的 Agent 列表接口
|
||||
app.register_blueprint(agents_bp, url_prefix='/api/agents')
|
||||
# 当前用户相关接口(首页、常见问题等)
|
||||
app.register_blueprint(user_bp, url_prefix='/api/user')
|
||||
# 知识库数据清洗模块接口
|
||||
app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb')
|
||||
# 知识库外部集成接口(供外部系统按 Dify 映射反查源文件)
|
||||
app.register_blueprint(integration_bp, url_prefix='/api/integration')
|
||||
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
|
||||
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
|
||||
app.register_blueprint(speech_bp, url_prefix='/api/speech')
|
||||
register_blueprints(app)
|
||||
|
||||
# Eagerly load persisted runtime settings so the very first request after
|
||||
# a worker boot already sees the admin-saved configuration (otherwise the
|
||||
@@ -85,8 +57,26 @@ def create_app(config_name='default'):
|
||||
# serve the defaults baked into config.py / the image).
|
||||
with app.app_context():
|
||||
_apply_persisted_settings(app)
|
||||
from app.services.agent_runtime_context.bootstrap import load_context_adapters
|
||||
load_context_adapters()
|
||||
from app.services.agent_registry.handlers.bootstrap import load_handlers
|
||||
load_handlers()
|
||||
from app.services.chat.intent_route_registry import ensure_intent_routes_loaded
|
||||
ensure_intent_routes_loaded()
|
||||
from app.services.schedule.scheduler_service import start_scheduler
|
||||
start_scheduler(app)
|
||||
# 空库先迁移后建用户:启动补建 + User commit 钩子即时补建,消除无排程窗口
|
||||
try:
|
||||
from app.services.file_assets.cleanup_schedule import (
|
||||
ensure_default_file_asset_cleanup_schedule,
|
||||
register_file_asset_cleanup_schedule_hooks,
|
||||
)
|
||||
register_file_asset_cleanup_schedule_hooks()
|
||||
ensure_default_file_asset_cleanup_schedule()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure file-asset-cleanup schedule: %s', exc)
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
FixedAssetsSnapshotService.start_worker(app)
|
||||
|
||||
@app.before_request
|
||||
def _sync_persisted_settings():
|
||||
@@ -185,6 +175,7 @@ def create_app(config_name='default'):
|
||||
|
||||
@app.errorhandler(AppError)
|
||||
def _handle_app_error(exc: AppError):
|
||||
"""统一业务异常 → JSON error_payload(API 层应 raise AppError 而非 jsonify error)。"""
|
||||
_log_api_error(
|
||||
code=exc.code,
|
||||
message=exc.message,
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"""
|
||||
backend/app/api/__init__.py
|
||||
|
||||
用途:集中注册所有 HTTP Blueprint。
|
||||
依赖:各 api 子模块 blueprint(单体或分包 re-export)。
|
||||
逻辑:create_app 唯一调用 register_blueprints(app);后续拆包只改本文件 import 来源。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Flask
|
||||
|
||||
|
||||
def register_blueprints(app: Flask) -> None:
|
||||
"""
|
||||
注册全部 HTTP Blueprint,保持对外 url_prefix 与 Wave 0 之前一致。
|
||||
核心逻辑:集中管理路由挂载点;后续 api/user、api/chat 等分包迁移时仅改本函数 import 来源。
|
||||
Args:
|
||||
app: Flask 应用实例。
|
||||
"""
|
||||
# [STEP 1] 单体模块(Wave 3 前保持不变)
|
||||
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 user_bp
|
||||
from app.api.integration import integration_bp
|
||||
from app.api.internal_jobs import internal_jobs_bp
|
||||
from app.api.maintenance import maintenance_bp
|
||||
from app.api.speech import speech_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 等)
|
||||
from app.api.kb import knowledge_base_bp
|
||||
from app.api.schedule import schedule_admin_bp
|
||||
from app.api.workspace import (
|
||||
workspace_announcements_bp,
|
||||
workspace_file_check_bp,
|
||||
workspace_schedule_bp,
|
||||
workspace_shipping_notice_bp,
|
||||
)
|
||||
from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp
|
||||
from app.api.files import files_bp
|
||||
|
||||
app.register_blueprint(chat_bp, url_prefix='/api/chat')
|
||||
app.register_blueprint(admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(agents_bp, url_prefix='/api/agents')
|
||||
app.register_blueprint(user_bp, url_prefix='/api/user')
|
||||
app.register_blueprint(training_user_bp, url_prefix='/api/user')
|
||||
app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb')
|
||||
app.register_blueprint(integration_bp, url_prefix='/api/integration')
|
||||
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_announcements_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_file_check_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
|
||||
app.register_blueprint(maintenance_bp, url_prefix='/api/maintenance')
|
||||
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
|
||||
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
|
||||
app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context')
|
||||
app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance')
|
||||
app.register_blueprint(speech_bp, url_prefix='/api/speech')
|
||||
app.register_blueprint(training_admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(files_bp, url_prefix='/api/files')
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,23 @@
|
||||
"""
|
||||
backend/app/api/admin/__init__.py
|
||||
|
||||
用途:管理后台 Blueprint 入口(Wave 3 分包)。
|
||||
依赖:admin/blueprint.py 及各子模块路由。
|
||||
逻辑:import 子模块注册路由;register_blueprints 从本包 import admin_bp。
|
||||
"""
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
|
||||
import app.api.admin.dashboard # noqa: F401
|
||||
import app.api.admin.departments # noqa: F401
|
||||
import app.api.admin.agents # noqa: F401
|
||||
import app.api.admin.guides # noqa: F401
|
||||
import app.api.admin.quick_questions # noqa: F401
|
||||
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.users # noqa: F401
|
||||
import app.api.admin.wecom # noqa: F401
|
||||
import app.api.admin.announcements # noqa: F401
|
||||
|
||||
__all__ = ['admin_bp']
|
||||
@@ -0,0 +1,132 @@
|
||||
"""
|
||||
backend/app/api/admin/agents.py
|
||||
|
||||
用途:管理后台 Agent CRUD、连通性测试、权限绑定 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/agent_service、core.response.ok。
|
||||
逻辑:/agents* 路由;统一 success/data/request_id envelope。
|
||||
"""
|
||||
from flask import g, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.response import ok
|
||||
from app.services.admin import agent_service
|
||||
|
||||
|
||||
def _request_id() -> str | None:
|
||||
return getattr(g, 'request_id', None)
|
||||
|
||||
|
||||
@admin_bp.route('/agents/schema', methods=['GET'])
|
||||
@require_admin
|
||||
def get_agent_registry_schema():
|
||||
"""返回 Admin Agent Registry 权威 schema(平台枚举、Catalog、handler_config schema)。"""
|
||||
from app.services.agent_registry.admin_schema import build_agent_registry_schema
|
||||
|
||||
return ok(build_agent_registry_schema(), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/infer-content-profile', methods=['POST'])
|
||||
@require_admin
|
||||
def infer_agent_content_profile():
|
||||
"""根据 intent_routes 推断 content_profile(Admin 表单建议,不参与运行时)。"""
|
||||
from app.services.agent_registry.content_profiles import infer_content_profile_from_intent_routes
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
routes = data.get('intent_routes') if isinstance(data.get('intent_routes'), list) else []
|
||||
profile = infer_content_profile_from_intent_routes(routes)
|
||||
return ok({'content_profile': profile}, request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/type-catalog', methods=['GET'])
|
||||
@require_admin
|
||||
def list_agent_type_catalog():
|
||||
"""返回 Admin 应用类型 Catalog 下拉列表。"""
|
||||
from app.services.agent_registry.catalog import list_type_catalog
|
||||
|
||||
return ok(list_type_catalog(), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/content-profiles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_agent_content_profiles():
|
||||
"""返回 Admin 可选 content_profile 及默认文案模板。"""
|
||||
from app.services.agent_registry.content_profiles import list_content_profiles
|
||||
|
||||
return ok(list_content_profiles(), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/intent-routes', methods=['GET'])
|
||||
@require_admin
|
||||
def list_agent_intent_routes():
|
||||
"""返回 Admin 可选 Intent route 注册表(前端表单动态选项)。"""
|
||||
from app.services.chat.intent_route_registry import list_chat_intent_route_definitions
|
||||
|
||||
return ok(list_chat_intent_route_definitions(), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents', methods=['GET'])
|
||||
@require_admin
|
||||
def list_agents():
|
||||
"""返回全部 Agent 列表。"""
|
||||
return ok(agent_service.list_agents(), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents', methods=['POST'])
|
||||
@require_admin
|
||||
def create_agent():
|
||||
"""创建 Agent。"""
|
||||
data = request.get_json() or {}
|
||||
payload = agent_service.create_agent(data)
|
||||
return ok(payload, request_id=_request_id(), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_agent(id: int):
|
||||
"""更新 Agent。"""
|
||||
data = request.get_json() or {}
|
||||
agent_service.update_agent(id, data)
|
||||
return ok({'status': 'ok'}, request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_agent(id: int):
|
||||
"""删除 Agent。"""
|
||||
agent_service.delete_agent(id)
|
||||
return ok({'status': 'ok'}, request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/test', methods=['POST'])
|
||||
@require_admin
|
||||
def test_agent(id: int):
|
||||
"""测试 Agent 连通性。"""
|
||||
payload = agent_service.test_agent_connectivity(id)
|
||||
return ok(payload, request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/permissions', methods=['POST'])
|
||||
@require_admin
|
||||
def update_agent_permissions(id: int):
|
||||
"""设置 Agent 授权用户列表。"""
|
||||
data = request.get_json() or {}
|
||||
user_ids = data.get('user_ids', [])
|
||||
agent_service.update_agent_permissions(id, user_ids)
|
||||
return ok({'status': 'ok'}, request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/training-question-bank/import-pdf', methods=['POST'])
|
||||
@require_admin
|
||||
def import_training_question_bank_from_pdf(id: int):
|
||||
"""
|
||||
从已上传的培训试题 PDF 解析题库。
|
||||
|
||||
用途:给 Agent 管理表单提供“从试题 PDF 导入题库”入口,返回结构化题目供前端回填并继续人工微调。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = agent_service.import_training_question_bank_from_pdf(
|
||||
agent_id=id,
|
||||
guide_id=data.get('guide_id'),
|
||||
)
|
||||
return ok(payload, request_id=_request_id())
|
||||
@@ -0,0 +1,43 @@
|
||||
"""
|
||||
backend/app/api/admin/announcements.py
|
||||
|
||||
用途:管理后台公告 CRUD API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/announcement_service。
|
||||
逻辑:/announcements* 路由;工作台只读见 api/workspace/announcements.py。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import announcement_service
|
||||
|
||||
|
||||
@admin_bp.route('/announcements', methods=['GET'])
|
||||
@require_admin
|
||||
def list_announcements():
|
||||
"""列出全部公告(含 is_active)。"""
|
||||
return jsonify(announcement_service.list_announcements())
|
||||
|
||||
|
||||
@admin_bp.route('/announcements', methods=['POST'])
|
||||
@require_admin
|
||||
def create_announcement():
|
||||
"""创建公告。"""
|
||||
data = request.get_json() or {}
|
||||
payload = announcement_service.create_announcement(data)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@admin_bp.route('/announcements/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_announcement(id: int):
|
||||
"""更新公告。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(announcement_service.update_announcement(id, data))
|
||||
|
||||
|
||||
@admin_bp.route('/announcements/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_announcement(id: int):
|
||||
"""删除公告。"""
|
||||
return jsonify(announcement_service.delete_announcement(id))
|
||||
@@ -0,0 +1,10 @@
|
||||
"""
|
||||
backend/app/api/admin/blueprint.py
|
||||
|
||||
用途:管理后台 API 共享 Blueprint(Wave 3 分包后各子模块共用)。
|
||||
依赖:Flask Blueprint。
|
||||
逻辑:dashboard、departments、users、wecom 等子模块在此 bp 上注册路由;__init__ 导出 admin_bp。
|
||||
"""
|
||||
from flask import Blueprint
|
||||
|
||||
admin_bp = Blueprint('admin', __name__)
|
||||
@@ -0,0 +1,42 @@
|
||||
"""
|
||||
backend/app/api/admin/dashboard.py
|
||||
|
||||
用途:管理后台仪表盘 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/dashboard_service。
|
||||
逻辑:/dashboard* 路由。
|
||||
"""
|
||||
from flask import jsonify
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import dashboard_service
|
||||
|
||||
|
||||
@admin_bp.route('/dashboard/summary', methods=['GET'])
|
||||
@require_admin
|
||||
def dashboard_summary():
|
||||
"""
|
||||
管理后台仪表盘概览(供 Dashboard 页单次请求)。
|
||||
GET /api/admin/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)。
|
||||
GET /api/admin/dashboard
|
||||
"""
|
||||
return jsonify(dashboard_service.compute_legacy_dashboard_stats())
|
||||
@@ -0,0 +1,38 @@
|
||||
"""
|
||||
backend/app/api/admin/database.py
|
||||
|
||||
用途:管理后台数据表浏览 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/database_admin_service。
|
||||
逻辑:/database/* 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import database_admin_service
|
||||
|
||||
|
||||
def _query_params() -> dict[str, str]:
|
||||
return {k: str(v) for k, v in request.args.items()}
|
||||
|
||||
|
||||
@admin_bp.route('/database/<table>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_table_data(table: str):
|
||||
"""浏览指定表数据(最多 100 行)。"""
|
||||
return jsonify(database_admin_service.get_table_data(table, _query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/database/chat_logs/batch-delete', methods=['POST'])
|
||||
@require_admin
|
||||
def batch_delete_chat_logs():
|
||||
"""批量删除 chat_logs。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(database_admin_service.batch_delete_chat_logs(data.get('ids', [])))
|
||||
|
||||
|
||||
@admin_bp.route('/database/<table>/count', methods=['GET'])
|
||||
@require_admin
|
||||
def get_table_count(table: str):
|
||||
"""返回表行数。"""
|
||||
return jsonify(database_admin_service.get_table_count(table, _query_params()))
|
||||
@@ -0,0 +1,45 @@
|
||||
"""
|
||||
backend/app/api/admin/departments.py
|
||||
|
||||
用途:管理后台部门 CRUD API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/department_service。
|
||||
逻辑:/departments* 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import department_service
|
||||
|
||||
|
||||
@admin_bp.route('/departments', methods=['GET'])
|
||||
@require_admin
|
||||
def list_departments():
|
||||
"""返回全部部门列表。"""
|
||||
return jsonify(department_service.list_departments())
|
||||
|
||||
|
||||
@admin_bp.route('/departments', methods=['POST'])
|
||||
@require_admin
|
||||
def create_department():
|
||||
"""创建部门。"""
|
||||
data = request.get_json() or {}
|
||||
payload = department_service.create_department(data)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@admin_bp.route('/departments/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_department(id: int):
|
||||
"""更新部门。"""
|
||||
data = request.get_json() or {}
|
||||
department_service.update_department(id, data)
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
@admin_bp.route('/departments/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_department(id: int):
|
||||
"""删除部门。"""
|
||||
department_service.delete_department(id)
|
||||
return jsonify({'status': 'ok'})
|
||||
@@ -0,0 +1,50 @@
|
||||
"""
|
||||
backend/app/api/admin/faq_candidates.py
|
||||
|
||||
用途:热点 FAQ 候选管理 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/faq_service。
|
||||
逻辑:/faq-candidates* 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import faq_service
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates', methods=['GET'])
|
||||
@require_admin
|
||||
def list_faq_candidates():
|
||||
"""列出 PostgreSQL 热点 FAQ 候选。"""
|
||||
agent_id = request.args.get('agent_id', type=int)
|
||||
return jsonify(faq_service.list_faq_candidates(agent_id=agent_id))
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates/refresh', methods=['POST'])
|
||||
@require_admin
|
||||
def refresh_faq_candidates():
|
||||
"""手动触发离线热点聚合。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
agent_id = data.get('agent_id')
|
||||
dry_run = bool(data.get('dry_run'))
|
||||
if agent_id is not None:
|
||||
agent_id = int(agent_id)
|
||||
return jsonify(faq_service.refresh_faq_candidates(agent_id=agent_id, dry_run=dry_run))
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates/promote', methods=['POST'])
|
||||
@require_admin
|
||||
def promote_faq_candidate():
|
||||
"""将热点候选晋升为 QuickQuestion。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(faq_service.promote_faq_candidate(data))
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates/dismiss', methods=['POST'])
|
||||
@require_admin
|
||||
def dismiss_faq_candidate():
|
||||
"""忽略热点 FAQ 候选。"""
|
||||
data = request.get_json() or {}
|
||||
agent_id = data.get('agent_id')
|
||||
q_norm = str(data.get('q_norm') or '')
|
||||
return jsonify(faq_service.dismiss_faq_candidate(agent_id=int(agent_id), q_norm=q_norm))
|
||||
@@ -0,0 +1,57 @@
|
||||
"""
|
||||
backend/app/api/admin/guides.py
|
||||
|
||||
用途:Agent 引导资料 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/guide_service。
|
||||
逻辑:/guides* 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import guide_service
|
||||
|
||||
|
||||
@admin_bp.route('/guides/upload', methods=['POST'])
|
||||
@require_admin
|
||||
def upload_guide():
|
||||
"""上传引导文件至 MinIO。"""
|
||||
file = request.files.get('file')
|
||||
return jsonify(guide_service.upload_guide_file(file))
|
||||
|
||||
|
||||
@admin_bp.route('/guides', methods=['POST'])
|
||||
@require_admin
|
||||
def create_guide():
|
||||
"""创建引导记录。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
current_user = get_current_user()
|
||||
payload = guide_service.create_guide(data, created_by_id=getattr(current_user, 'id', None))
|
||||
return jsonify(payload)
|
||||
|
||||
|
||||
@admin_bp.route('/guides', methods=['GET'])
|
||||
@require_admin
|
||||
def list_guides():
|
||||
"""列出引导资料,可按 agent_id 过滤。"""
|
||||
agent_id_raw = request.args.get('agent_id')
|
||||
agent_id = int(agent_id_raw) if agent_id_raw else None
|
||||
return jsonify(guide_service.list_guides(agent_id=agent_id))
|
||||
|
||||
|
||||
@admin_bp.route('/guides/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_guide(id: int):
|
||||
"""更新引导元数据。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
guide_service.update_guide(id, data)
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@admin_bp.route('/guides/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_guide(id: int):
|
||||
"""删除引导及 MinIO 文件。"""
|
||||
guide_service.delete_guide(id)
|
||||
return jsonify({'success': True})
|
||||
@@ -0,0 +1,49 @@
|
||||
"""
|
||||
backend/app/api/admin/permissions.py
|
||||
|
||||
用途:管理后台权限批量更新与权限申请审批 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/permission_service。
|
||||
逻辑:/permissions/*、/permission-requests/*、/users/<id>/permissions 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import permission_service
|
||||
|
||||
|
||||
@admin_bp.route('/permissions/batch', methods=['POST'])
|
||||
@require_admin
|
||||
def batch_update_permissions():
|
||||
"""批量更新用户 Agent 权限(add / remove / set)。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(permission_service.batch_update_permissions(data))
|
||||
|
||||
|
||||
@admin_bp.route('/users/<int:id>/permissions', methods=['POST'])
|
||||
@require_admin
|
||||
def update_user_permissions(id: int):
|
||||
"""将指定用户的 Agent 权限重置为请求体 agent_ids。"""
|
||||
data = request.get_json() or {}
|
||||
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))
|
||||
@@ -0,0 +1,46 @@
|
||||
"""
|
||||
backend/app/api/admin/quick_questions.py
|
||||
|
||||
用途:全局常用问题 CRUD API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/faq_service。
|
||||
逻辑:/quick-questions* 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import faq_service
|
||||
|
||||
|
||||
@admin_bp.route('/quick-questions', methods=['GET'])
|
||||
@require_admin
|
||||
def list_quick_questions():
|
||||
"""列出全局常用问题,可选 stale_only 过滤。"""
|
||||
stale_only = str(request.args.get('stale_only', '')).lower() in {'1', 'true', 'yes'}
|
||||
return jsonify(faq_service.list_quick_questions(stale_only=stale_only))
|
||||
|
||||
|
||||
@admin_bp.route('/quick-questions', methods=['POST'])
|
||||
@require_admin
|
||||
def create_quick_question():
|
||||
"""创建全局常用问题。"""
|
||||
data = request.get_json() or {}
|
||||
payload = faq_service.create_quick_question(data)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@admin_bp.route('/quick-questions/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_quick_question(id: int):
|
||||
"""更新全局常用问题。"""
|
||||
data = request.get_json() or {}
|
||||
faq_service.update_quick_question(id, data)
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
@admin_bp.route('/quick-questions/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_quick_question(id: int):
|
||||
"""删除全局常用问题。"""
|
||||
faq_service.delete_quick_question(id)
|
||||
return jsonify({'status': 'ok'})
|
||||
@@ -0,0 +1,88 @@
|
||||
"""
|
||||
backend/app/api/admin/reports.py
|
||||
|
||||
用途:管理后台报表 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/report_service。
|
||||
逻辑:/reports/usage、/reports/applications、feedback 与 general-feedbacks 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import report_service
|
||||
|
||||
|
||||
def _query_params() -> dict[str, str]:
|
||||
return {k: str(v) for k, v in request.args.items()}
|
||||
|
||||
|
||||
@admin_bp.route('/reports/usage', methods=['GET'])
|
||||
@require_admin
|
||||
def usage_report():
|
||||
"""聊天使用分析报表(支持时间范围 range=7d|30d|90d|180d|365d)。"""
|
||||
try:
|
||||
user_page = int(request.args.get('user_page', 1))
|
||||
except (TypeError, ValueError):
|
||||
user_page = 1
|
||||
try:
|
||||
user_page_size = int(request.args.get('user_page_size', 10))
|
||||
except (TypeError, ValueError):
|
||||
user_page_size = 10
|
||||
range_key = request.args.get('range')
|
||||
return jsonify(
|
||||
report_service.build_usage_report(
|
||||
user_page=user_page,
|
||||
user_page_size=user_page_size,
|
||||
range_key=range_key,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/reports/applications', methods=['GET'])
|
||||
@require_admin
|
||||
def applications_report():
|
||||
"""
|
||||
应用运营报表:按应用聚合使用 / 权限 / 评分。
|
||||
Query: range, status, usage, q, sort, order, page, page_size。
|
||||
"""
|
||||
try:
|
||||
page = int(request.args.get('page', 1))
|
||||
except (TypeError, ValueError):
|
||||
page = 1
|
||||
try:
|
||||
page_size = int(request.args.get('page_size', 20))
|
||||
except (TypeError, ValueError):
|
||||
page_size = 20
|
||||
return jsonify(
|
||||
report_service.build_application_report(
|
||||
range_key=request.args.get('range'),
|
||||
status=request.args.get('status'),
|
||||
usage=request.args.get('usage'),
|
||||
q=request.args.get('q'),
|
||||
sort=request.args.get('sort'),
|
||||
order=request.args.get('order'),
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/reports/feedback', methods=['GET'])
|
||||
@require_admin
|
||||
def feedback_report():
|
||||
"""反馈评分分布报表。"""
|
||||
return jsonify(report_service.build_feedback_report())
|
||||
|
||||
|
||||
@admin_bp.route('/reports/general-feedbacks', methods=['GET'])
|
||||
@require_admin
|
||||
def list_general_feedbacks_report():
|
||||
"""通用反馈列表。"""
|
||||
return jsonify(report_service.list_general_feedbacks_report(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/reports/general-feedbacks/count', methods=['GET'])
|
||||
@require_admin
|
||||
def count_general_feedbacks_report():
|
||||
"""通用反馈计数。"""
|
||||
return jsonify(report_service.count_general_feedbacks_report(_query_params()))
|
||||
@@ -0,0 +1,82 @@
|
||||
"""
|
||||
backend/app/api/admin/users.py
|
||||
|
||||
用途:管理后台用户 CRUD API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/user_service、core.auth.jwt。
|
||||
逻辑:/users* 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.auth.jwt import get_current_user as _get_auth_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import user_service
|
||||
|
||||
|
||||
def _query_params() -> dict[str, str]:
|
||||
return {k: str(v) for k, v in request.args.items()}
|
||||
|
||||
|
||||
@admin_bp.route('/users', methods=['GET'])
|
||||
@require_admin
|
||||
def list_users():
|
||||
"""列出管理端用户(支持分页与筛选)。"""
|
||||
result = user_service.list_users(_query_params())
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@admin_bp.route('/users', methods=['POST'])
|
||||
@require_admin
|
||||
def create_user():
|
||||
"""创建用户并同步 Casdoor。"""
|
||||
data = request.get_json() or {}
|
||||
payload = user_service.create_user(data)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@admin_bp.route('/users/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_user(id: int):
|
||||
"""更新用户资料;有 password 时同步 Casdoor 改密。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(user_service.update_user(id, data))
|
||||
|
||||
|
||||
@admin_bp.route('/users/cleanup-rejected', methods=['POST'])
|
||||
@require_admin
|
||||
def cleanup_rejected_users():
|
||||
"""批量删除 status=rejected 的用户。"""
|
||||
return jsonify(user_service.cleanup_rejected_users())
|
||||
|
||||
|
||||
@admin_bp.route('/users/batch-delete', methods=['POST'])
|
||||
@require_admin
|
||||
def batch_delete_users():
|
||||
"""批量删除用户(排除当前登录管理员)。"""
|
||||
data = request.get_json() or {}
|
||||
current_user = _get_auth_user()
|
||||
current_user_id = current_user.id if current_user else None
|
||||
return jsonify(user_service.batch_delete_users(data.get('user_ids', []), current_user_id=current_user_id))
|
||||
|
||||
|
||||
@admin_bp.route('/users/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_user(id: int):
|
||||
"""删除单个用户。"""
|
||||
current_user = _get_auth_user()
|
||||
current_user_id = current_user.id if current_user else None
|
||||
return jsonify(user_service.delete_user(id, current_user_id=current_user_id))
|
||||
|
||||
|
||||
@admin_bp.route('/users/<int:id>/approve', methods=['POST'])
|
||||
@require_admin
|
||||
def approve_user(id: int):
|
||||
"""审批通过用户。"""
|
||||
return jsonify(user_service.approve_user(id))
|
||||
|
||||
|
||||
@admin_bp.route('/users/<int:id>/reject', methods=['POST'])
|
||||
@require_admin
|
||||
def reject_user(id: int):
|
||||
"""拒绝用户注册。"""
|
||||
return jsonify(user_service.reject_user(id))
|
||||
@@ -0,0 +1,118 @@
|
||||
"""
|
||||
backend/app/api/admin/wecom.py
|
||||
|
||||
用途:管理后台企微绑定、配置与诊断 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/wecom_admin_service。
|
||||
逻辑:/wecom/* 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import wecom_admin_service
|
||||
|
||||
|
||||
def _query_params() -> dict[str, str]:
|
||||
return {k: str(v) for k, v in request.args.items()}
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/debug-user-by-code', methods=['POST'])
|
||||
@require_admin
|
||||
def debug_wecom_user_by_code():
|
||||
"""通过 OAuth code 诊断企微用户匹配结果。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(wecom_admin_service.debug_user_by_code(data.get('code')))
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/bindings', methods=['GET'])
|
||||
@require_admin
|
||||
def list_wecom_bindings():
|
||||
"""分页列出企微绑定。"""
|
||||
return jsonify(wecom_admin_service.list_bindings(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/bind', methods=['POST'])
|
||||
@require_admin
|
||||
def bind_wecom_user():
|
||||
"""管理员手动绑定企微账号。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(wecom_admin_service.bind_user(data))
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/unbind', methods=['POST'])
|
||||
@require_admin
|
||||
def unbind_wecom_user():
|
||||
"""管理员解绑企微账号。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(wecom_admin_service.unbind_user(data))
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/provision', methods=['POST'])
|
||||
@require_admin
|
||||
def provision_wecom_user():
|
||||
"""创建/更新用户并绑定企微、分配权限。"""
|
||||
data = request.get_json() or {}
|
||||
payload, status_code = wecom_admin_service.provision_user(data)
|
||||
return jsonify(payload), status_code
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/login-audits', methods=['GET'])
|
||||
@require_admin
|
||||
def get_wecom_login_audits():
|
||||
"""查询登录审计(企微/密码等来源)。"""
|
||||
return jsonify(wecom_admin_service.list_login_audits(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/notify-settings', methods=['GET', 'PUT'])
|
||||
@require_admin
|
||||
def wecom_notify_settings():
|
||||
"""读取或更新企微通知配置。"""
|
||||
if request.method == 'GET':
|
||||
return jsonify(wecom_admin_service.serialize_notify_settings())
|
||||
data = request.get_json() or {}
|
||||
return jsonify(wecom_admin_service.update_notify_settings(data))
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/system-settings', methods=['GET', 'PUT'])
|
||||
@require_admin
|
||||
def wecom_system_settings():
|
||||
"""读取或更新企微 OAuth 系统配置。"""
|
||||
if request.method == 'GET':
|
||||
return jsonify(wecom_admin_service.serialize_system_settings())
|
||||
data = request.get_json() or {}
|
||||
return jsonify(wecom_admin_service.update_system_settings(data))
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/integration-manifest', methods=['GET'])
|
||||
@require_admin
|
||||
def wecom_integration_manifest():
|
||||
"""返回企微集成 manifest(回调 URL、OAuth 端点等)。"""
|
||||
return jsonify(
|
||||
wecom_admin_service.integration_manifest(
|
||||
host_url=request.host_url,
|
||||
host=request.host,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/notify-metrics', methods=['GET'])
|
||||
@require_admin
|
||||
def wecom_notify_metrics():
|
||||
"""企微通知发送/打开率指标(近 30 天)。"""
|
||||
return jsonify(wecom_admin_service.notify_metrics())
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/binding-stats', methods=['GET'])
|
||||
@require_admin
|
||||
def wecom_binding_stats():
|
||||
"""活跃用户企微绑定统计。"""
|
||||
return jsonify(wecom_admin_service.binding_stats())
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/sync-userids', methods=['POST'])
|
||||
@require_admin
|
||||
def sync_wecom_userids_admin():
|
||||
"""从 OA 按工号同步 users.wecom_userid。"""
|
||||
data = request.get_json() or {}
|
||||
apply = bool(data.get('apply'))
|
||||
return jsonify(wecom_admin_service.sync_userids(apply=apply))
|
||||
@@ -0,0 +1,107 @@
|
||||
"""
|
||||
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 鉴权,不推进业务状态。
|
||||
"""
|
||||
|
||||
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"),
|
||||
)
|
||||
)
|
||||
+130
-48
@@ -1,64 +1,65 @@
|
||||
"""
|
||||
backend/app/api/agents.py
|
||||
文件用途:普通用户可见的 Agent 列表接口
|
||||
引用文件:flask, models, decorators
|
||||
逻辑关系:根据当前用户的权限返回其可访问的 Agent 集合
|
||||
|
||||
用途:普通用户可见的 Agent 列表与 AgentGuide 静态资源。
|
||||
依赖:app.core.auth.jwt、models、minio_service、agent_registry.serialization。
|
||||
逻辑:按当前用户 RBAC 返回可访问 Agent;列表统一 serialize_agent_for_user_list(结构化列为准)。
|
||||
"""
|
||||
import os
|
||||
from flask import Blueprint, jsonify, send_from_directory
|
||||
import mimetypes
|
||||
import re
|
||||
from flask import Blueprint, Response, jsonify, request, send_from_directory, stream_with_context
|
||||
|
||||
from app import db
|
||||
from app.decorators import _get_current_user # 内部工具函数
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError
|
||||
from app.models import Agent, User, AgentGuide
|
||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||
from app.services.minio_service import minio_service
|
||||
|
||||
# 定义 Blueprint,将在应用工厂中注册为 /api/agents
|
||||
agents_bp = Blueprint('agents', __name__)
|
||||
|
||||
|
||||
def _serialize_agent_row(row) -> dict:
|
||||
return {
|
||||
'id': row.id,
|
||||
'name': row.name,
|
||||
'description': row.description,
|
||||
'icon_url': row.icon_url,
|
||||
'dify_app_type': (row.extra_config or {}).get('dify_app_type') if hasattr(row, 'extra_config') else None,
|
||||
}
|
||||
def _serialize_agent_row(agent: Agent, *, visible_agent_ids: set[int] | None = None) -> dict:
|
||||
payload = serialize_agent_list_item(agent)
|
||||
if not bool(getattr(agent, 'is_aggregate', False)):
|
||||
return payload
|
||||
from app.services.agent_directory import serialize_directory_members
|
||||
|
||||
members = serialize_directory_members(agent.id, active_only=True)
|
||||
if visible_agent_ids is not None:
|
||||
members = [member for member in members if int(member.get('id') or 0) in visible_agent_ids]
|
||||
if members:
|
||||
payload['directory_members'] = members
|
||||
return payload
|
||||
|
||||
|
||||
def _list_active_agents_for_user(user: User) -> list[Agent]:
|
||||
"""返回用户可见的完整 Agent ORM 行(含 Registry 结构化列)。"""
|
||||
if user.role == 'admin':
|
||||
return (
|
||||
db.session.query(Agent)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.order_by(Agent.id.asc())
|
||||
.all()
|
||||
)
|
||||
return [agent for agent in user.agents if agent.is_active]
|
||||
|
||||
|
||||
@agents_bp.route('', methods=['GET'])
|
||||
def list_user_agents():
|
||||
"""
|
||||
获取当前用户可见的 Agent 列表
|
||||
用途:Workspace 页面展示应用网格
|
||||
用途:Workspace 页面展示应用网格、聊天侧栏 Agent 切换
|
||||
"""
|
||||
# 获取当前用户(目前固定为 admin 用户,用于演示)
|
||||
user: User = _get_current_user()
|
||||
user: User = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
|
||||
# 管理员:返回所有激活的 Agent
|
||||
if user.role == 'admin':
|
||||
agent_rows = (
|
||||
db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url, Agent.extra_config)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.order_by(Agent.id.asc())
|
||||
.all()
|
||||
)
|
||||
else:
|
||||
# 普通用户:仅返回多对多关系中已授权的 Agent
|
||||
agent_rows = [
|
||||
type('AgentRow', (), {
|
||||
'id': a.id,
|
||||
'name': a.name,
|
||||
'description': a.description,
|
||||
'icon_url': a.icon_url,
|
||||
'extra_config': a.extra_config,
|
||||
})()
|
||||
for a in user.agents
|
||||
if a.is_active
|
||||
]
|
||||
|
||||
# 序列化为前端所需字段
|
||||
return jsonify([_serialize_agent_row(row) for row in agent_rows])
|
||||
agents = _list_active_agents_for_user(user)
|
||||
visible_agent_ids = {agent.id for agent in agents}
|
||||
return jsonify([_serialize_agent_row(agent, visible_agent_ids=visible_agent_ids) for agent in sort_agent_rows(agents)])
|
||||
|
||||
@agents_bp.route('/<int:agent_id>/guides', methods=['GET'])
|
||||
def list_agent_guides(agent_id):
|
||||
@@ -66,10 +67,15 @@ def list_agent_guides(agent_id):
|
||||
获取指定应用的新手指南列表 (需登录)
|
||||
用途:客户端 Chat 界面点击新手指南
|
||||
"""
|
||||
_get_current_user() # 确保已登录
|
||||
get_current_user() # 确保已登录
|
||||
|
||||
if agent_id == 0:
|
||||
generic_agent = db.session.query(Agent).filter_by(name='通用入口').first()
|
||||
generic_agent = (
|
||||
db.session.query(Agent)
|
||||
.filter_by(agent_code='generic', is_active=True)
|
||||
.order_by(Agent.sort_order.asc(), Agent.id.asc())
|
||||
.first()
|
||||
)
|
||||
if generic_agent:
|
||||
agent_id = generic_agent.id
|
||||
else:
|
||||
@@ -88,6 +94,7 @@ def list_agent_guides(agent_id):
|
||||
'id': g.id,
|
||||
'file_name': g.file_name,
|
||||
'file_type': g.file_type,
|
||||
'guide_usage': g.guide_usage,
|
||||
'file_url': minio_service.get_public_url(g.file_path),
|
||||
'file_size': g.file_size,
|
||||
'remark': g.remark,
|
||||
@@ -101,18 +108,93 @@ def list_public_agents():
|
||||
获取公开的 Agent 列表 (无需登录)
|
||||
用途:登录页面展示
|
||||
"""
|
||||
# 返回所有激活的 Agent,包含基本信息
|
||||
agent_rows = (
|
||||
db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url, Agent.extra_config)
|
||||
agents = (
|
||||
db.session.query(Agent)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.order_by(Agent.id.asc())
|
||||
.all()
|
||||
)
|
||||
return jsonify([_serialize_agent_row(row) for row in agent_rows])
|
||||
visible_agent_ids = {agent.id for agent in agents}
|
||||
return jsonify([_serialize_agent_row(agent, visible_agent_ids=visible_agent_ids) for agent in sort_agent_rows(agents)])
|
||||
|
||||
def _parse_byte_range(range_header: str, file_size: int) -> tuple[int, int] | None:
|
||||
"""
|
||||
解析浏览器单段字节范围请求。
|
||||
|
||||
用途:iOS Safari/企业微信播放 MP4 时依赖 Range 请求,本函数将请求转换为闭区间。
|
||||
参数约束:仅接受单个 bytes 范围;无效或越界范围返回 None。
|
||||
"""
|
||||
match = re.fullmatch(r'bytes=(\d*)-(\d*)', range_header.strip())
|
||||
if not match or file_size <= 0:
|
||||
return None
|
||||
start_text, end_text = match.groups()
|
||||
if not start_text and not end_text:
|
||||
return None
|
||||
if start_text:
|
||||
start = int(start_text)
|
||||
end = int(end_text) if end_text else file_size - 1
|
||||
else:
|
||||
suffix_length = int(end_text)
|
||||
if suffix_length <= 0:
|
||||
return None
|
||||
start = max(file_size - suffix_length, 0)
|
||||
end = file_size - 1
|
||||
if start >= file_size or end < start:
|
||||
return None
|
||||
return start, min(end, file_size - 1)
|
||||
|
||||
|
||||
def _stream_minio_guide_file(filename: str) -> Response:
|
||||
"""
|
||||
以同源流式响应返回 MinIO 指南文件。
|
||||
|
||||
用途:消除生产 HTTPS 页面加载 HTTP MinIO 地址的混合内容问题,并支持 iOS 所需的 206 响应。
|
||||
参数约束:filename 为系统生成的 MinIO 对象名;响应流结束后必须释放连接。
|
||||
"""
|
||||
stat = minio_service.stat_file(filename)
|
||||
file_size = int(stat.size)
|
||||
content_type = stat.content_type or mimetypes.guess_type(filename)[0] or 'application/octet-stream'
|
||||
requested_range = request.headers.get('Range', '').strip()
|
||||
byte_range = _parse_byte_range(requested_range, file_size) if requested_range else None
|
||||
if requested_range and byte_range is None:
|
||||
return Response(status=416, headers={'Content-Range': f'bytes */{file_size}'})
|
||||
|
||||
start, end = byte_range or (0, file_size - 1)
|
||||
content_length = end - start + 1
|
||||
source = minio_service.open_file_stream(filename, offset=start, length=content_length)
|
||||
|
||||
def generate():
|
||||
try:
|
||||
while True:
|
||||
chunk = source.read(64 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
yield chunk
|
||||
finally:
|
||||
source.close()
|
||||
source.release_conn()
|
||||
|
||||
headers = {
|
||||
'Accept-Ranges': 'bytes',
|
||||
'Content-Length': str(content_length),
|
||||
'Cache-Control': 'private, max-age=3600',
|
||||
}
|
||||
status = 206 if byte_range else 200
|
||||
if byte_range:
|
||||
headers['Content-Range'] = f'bytes {start}-{end}/{file_size}'
|
||||
return Response(stream_with_context(generate()), status=status, headers=headers, content_type=content_type)
|
||||
|
||||
|
||||
# 为了兼容本地无MinIO的环境,暴露一个静态文件读取接口
|
||||
@agents_bp.route('/guides/files/<path:filename>', methods=['GET'])
|
||||
def serve_guide_file(filename):
|
||||
return send_from_directory(os.path.join(os.getcwd(), 'data', 'agent-guides'), filename)
|
||||
"""
|
||||
返回本地或 MinIO 中的指南文件。
|
||||
|
||||
用途:为 PDF、图片和培训视频提供统一同源地址;本地文件沿用 Flask 条件响应,MinIO 文件支持 Range。
|
||||
参数约束:filename 仅用于系统指南存储目录或 MinIO 指南桶,不接受任意外部路径。
|
||||
"""
|
||||
local_directory = os.path.join(os.getcwd(), 'data', 'agent-guides')
|
||||
if os.path.isfile(os.path.join(local_directory, filename)):
|
||||
return send_from_directory(local_directory, filename, conditional=True)
|
||||
return _stream_minio_guide_file(filename)
|
||||
|
||||
+432
-60
@@ -1,39 +1,84 @@
|
||||
"""
|
||||
backend/app/api/chat.py
|
||||
文件用途:定义聊天相关 API 路由
|
||||
引用文件:flask, services.dify, decorators, models
|
||||
逻辑关系:作为前端与 Dify 之间的 BFF 层,负责转发请求并流式返回结果
|
||||
|
||||
用途:聊天 BFF(SSE 流式、会话 CRUD、PLM/Excel 预览、反馈)。
|
||||
依赖:app.core.decorators、app.core.errors、services.dify、integrations。
|
||||
逻辑:/completions 按意图分流(Wave 3 抽至 services/chat/router.py);错误统一 raise AppError。
|
||||
"""
|
||||
import io
|
||||
import ipaddress
|
||||
import mimetypes
|
||||
import ntpath
|
||||
import posixpath
|
||||
import tempfile
|
||||
import os
|
||||
import subprocess
|
||||
import uuid
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime
|
||||
from urllib.parse import urlparse
|
||||
import requests
|
||||
from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app, has_request_context
|
||||
from sqlalchemy import func, desc, or_, exists, and_
|
||||
from openpyxl import load_workbook
|
||||
from app.services.agent_runtime_context.dify_inputs import build_chat_dify_inputs
|
||||
from app.services.dify import DifyService
|
||||
from app.core.config.settings import Config
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
from app.decorators import require_agent_permission
|
||||
from app.core.decorators import require_agent_permission
|
||||
from app.models import Agent, ChatLog, ChatSession, Feedback
|
||||
from app import db
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
raise_for_status,
|
||||
)
|
||||
chat_bp = Blueprint('chat', __name__)
|
||||
|
||||
LEAVE_FEATURE_AGENT_NAMES = {'通用入口', '人事规章'}
|
||||
SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice'
|
||||
|
||||
|
||||
def _can_use_leave_feature(agent_proxy) -> bool:
|
||||
agent_name = str(getattr(agent_proxy, 'name', None) or '').strip()
|
||||
return agent_name in LEAVE_FEATURE_AGENT_NAMES
|
||||
PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip()
|
||||
|
||||
|
||||
def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_batch_no: str | None = None) -> dict | None:
|
||||
"""
|
||||
构建聊天入口分发给领域 adapter 的提示字典。
|
||||
|
||||
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示,
|
||||
统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。
|
||||
"""
|
||||
task_id = str(shipping_task_id or '').strip()
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def _should_reset_provider_conversation_for_asset_query(query: str, agent_proxy) -> bool:
|
||||
"""
|
||||
判断固资管理里的当前问题是否应当切断上游 Dify 会话上下文。
|
||||
|
||||
核心逻辑:
|
||||
- 仅对“固资管理”Agent 生效;
|
||||
- 仅当用户本轮问题可脱离上一轮上下文独立完成时触发;
|
||||
- 这样可以保留本地同一历史会话,又避免把上一轮超大结果继续带给上游模型,导致 context length 爆掉。
|
||||
"""
|
||||
from app.services.text2sql import Text2SQLService
|
||||
|
||||
return Text2SQLService._should_reset_provider_conversation(query, agent_proxy)
|
||||
|
||||
def _session_title_from_text(text: str) -> str:
|
||||
value = str(text or '').strip()
|
||||
if not value:
|
||||
@@ -41,6 +86,28 @@ def _session_title_from_text(text: str) -> str:
|
||||
return value[:30] + ('...' if len(value) > 30 else '')
|
||||
|
||||
|
||||
def _user_facing_chat_query(text: str, *, agent_code: str | None = None) -> str:
|
||||
"""
|
||||
将内部 Agent 编排提示转换成业务用户可见话术。
|
||||
|
||||
Args:
|
||||
text: chat_logs.query 中保存的用户侧文本。
|
||||
agent_code: 当前 Agent 应用类型;仅 shipping_notice 做工具名净化。
|
||||
Returns:
|
||||
可直接展示在聊天历史里的用户问题。
|
||||
"""
|
||||
value = str(text or '').strip()
|
||||
if not value or str(agent_code or '').strip() != SHIPPING_NOTICE_AGENT_CODE:
|
||||
return value
|
||||
import re
|
||||
|
||||
task_match = re.search(r'(SN-\d{8}-[A-Z0-9]+)', value, re.I)
|
||||
task_no = task_match.group(1).upper() if task_match else ''
|
||||
if 'create_task' in value or 'get_task_status' in value or 'parse_notice' in value:
|
||||
return f'继续处理当前发货任务 {task_no}'.strip()
|
||||
return value
|
||||
|
||||
|
||||
def _serialize_session(session: ChatSession) -> dict:
|
||||
last_active = session.last_active_at or session.created_at
|
||||
return {
|
||||
@@ -161,16 +228,60 @@ def _update_chat_session(
|
||||
return session
|
||||
|
||||
|
||||
def _normalize_windows_share_path(path_value: str) -> str:
|
||||
normalized = str(path_value or '').strip().strip('"').replace('/', '\\')
|
||||
if normalized.startswith('\\\\'):
|
||||
return '\\\\' + normalized[2:].rstrip('\\')
|
||||
return normalized.rstrip('\\')
|
||||
def _normalize_allowed_share_path(path_value: str) -> tuple[str, str]:
|
||||
"""
|
||||
统一归一化 Windows UNC / Windows 本地盘符 / Linux 挂载目录路径。
|
||||
|
||||
Returns:
|
||||
(path_kind, normalized_path)
|
||||
- path_kind: 'windows' | 'posix' | ''
|
||||
- normalized_path: 归一化后的绝对路径文本
|
||||
"""
|
||||
raw_value = str(path_value or '').strip().strip('"')
|
||||
if not raw_value:
|
||||
return ('', '')
|
||||
if raw_value.startswith('\\\\'):
|
||||
normalized = raw_value.replace('/', '\\')
|
||||
normalized = '\\\\' + normalized[2:].rstrip('\\')
|
||||
return ('windows', normalized)
|
||||
if len(raw_value) >= 3 and raw_value[1] == ':' and raw_value[2] in ('\\', '/'):
|
||||
normalized = ntpath.normpath(raw_value.replace('/', '\\')).rstrip('\\')
|
||||
return ('windows', normalized)
|
||||
if raw_value.startswith('/'):
|
||||
normalized = posixpath.normpath(raw_value.replace('\\', '/'))
|
||||
return ('posix', normalized.rstrip('/'))
|
||||
return ('', '')
|
||||
|
||||
def _is_path_within_allowed_root(target_path: str, root_path: str) -> bool:
|
||||
target_kind, normalized_target = _normalize_allowed_share_path(target_path)
|
||||
root_kind, normalized_root = _normalize_allowed_share_path(root_path)
|
||||
if not normalized_target or not normalized_root or target_kind != root_kind:
|
||||
return False
|
||||
if target_kind == 'windows':
|
||||
target_lower = normalized_target.lower()
|
||||
root_lower = normalized_root.lower()
|
||||
return target_lower == root_lower or target_lower.startswith(root_lower.rstrip('\\') + '\\')
|
||||
return normalized_target == normalized_root or normalized_target.startswith(normalized_root.rstrip('/') + '/')
|
||||
|
||||
def _is_allowed_share_path(target_url: str) -> bool:
|
||||
normalized_target = _normalize_windows_share_path(target_url)
|
||||
normalized_root = _normalize_windows_share_path(PLM_PREVIEW_SHARE_ROOT)
|
||||
return bool(normalized_root and normalized_target.startswith('\\\\') and normalized_target.lower().startswith(normalized_root.lower()))
|
||||
target_kind, normalized_target = _normalize_allowed_share_path(target_url)
|
||||
if not normalized_target:
|
||||
return False
|
||||
history_share_root = ''
|
||||
history_local_root = ''
|
||||
if has_request_context():
|
||||
history_share_root = str(current_app.config.get('FIXED_ASSET_HISTORY_SHARE_ROOT') or '').strip()
|
||||
history_local_root = str(current_app.config.get('FIXED_ASSET_HISTORY_LOCAL_ROOT') or '').strip()
|
||||
if not history_share_root:
|
||||
history_share_root = str(Config.FIXED_ASSET_HISTORY_SHARE_ROOT or '').strip()
|
||||
if not history_local_root:
|
||||
history_local_root = str(Config.FIXED_ASSET_HISTORY_LOCAL_ROOT or '').strip()
|
||||
roots = [
|
||||
PLM_PREVIEW_SHARE_ROOT,
|
||||
history_share_root,
|
||||
history_local_root,
|
||||
]
|
||||
return any(root and _is_path_within_allowed_root(normalized_target, root) for root in roots)
|
||||
|
||||
def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
"""
|
||||
@@ -225,7 +336,7 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
|
||||
import sqlalchemy as sa
|
||||
from urllib.parse import parse_qs
|
||||
if _is_allowed_share_path(file_url):
|
||||
normalized_path = _normalize_windows_share_path(file_url)
|
||||
_path_kind, normalized_path = _normalize_allowed_share_path(file_url)
|
||||
try:
|
||||
if not os.path.isfile(normalized_path):
|
||||
return (None, None, ('source file not found', 404))
|
||||
@@ -241,6 +352,16 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
|
||||
if _extract_placeholder_text(content):
|
||||
guessed_type = 'text/plain; charset=utf-8'
|
||||
return (content, guessed_type, None)
|
||||
try:
|
||||
from app.services.fixed_asset_image import FixedAssetImageService
|
||||
content, content_type, asset_image_err = FixedAssetImageService.fetch_preview_bytes(
|
||||
file_url,
|
||||
max_size=max_size,
|
||||
)
|
||||
if content is not None or asset_image_err is not None:
|
||||
return (content, content_type, asset_image_err)
|
||||
except Exception as exc:
|
||||
current_app.logger.warning('[file-preview] fixed asset image fetch failed url=%s err=%s', file_url, exc)
|
||||
headers = {}
|
||||
base_url = IntegrationApiService.get_base_url()
|
||||
api_key = IntegrationApiService.get_api_key()
|
||||
@@ -898,10 +1019,32 @@ def get_chat_messages():
|
||||
).order_by(ChatLog.created_at.asc()).all()
|
||||
|
||||
messages = []
|
||||
agent_code = str(getattr(g.current_agent, 'agent_code', '') or '').strip() or 'generic'
|
||||
for log in logs:
|
||||
if log.query:
|
||||
messages.append({'role': 'user', 'content': log.query})
|
||||
assistant_msg = {'role': 'assistant', 'content': log.answer, 'chat_log_id': log.id, 'retriever_resources': log.retriever_resources or [], 'attribution_parts': log.attribution_parts or []}
|
||||
messages.append({'role': 'user', 'content': _user_facing_chat_query(log.query, agent_code=agent_code)})
|
||||
if (
|
||||
not log.answer
|
||||
and not log.message_type
|
||||
and not log.payload
|
||||
):
|
||||
continue
|
||||
if (
|
||||
log.query
|
||||
and log.answer == log.query
|
||||
and (not log.message_type or log.message_type == 'text')
|
||||
and not log.payload
|
||||
):
|
||||
continue
|
||||
assistant_msg = {
|
||||
'role': 'assistant',
|
||||
'content': DifyService._dedupe_exact_doubled_text(log.answer or ''),
|
||||
'chat_log_id': log.id,
|
||||
'retriever_resources': log.retriever_resources or [],
|
||||
'attribution_parts': log.attribution_parts or [],
|
||||
}
|
||||
if log.run_id:
|
||||
assistant_msg['run_id'] = log.run_id
|
||||
if log.message_type:
|
||||
assistant_msg['type'] = log.message_type
|
||||
if log.payload:
|
||||
@@ -921,10 +1064,17 @@ def save_local_message():
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
|
||||
data = request.get_json() or {}
|
||||
conversation_id = (data.get('conversation_id') or '').strip()
|
||||
role = (data.get('role') or 'assistant').strip()
|
||||
message_type = data.get('type')
|
||||
content = data.get('content', '')
|
||||
payload = data.get('payload')
|
||||
user_query = data.get('query', '')
|
||||
if role == 'user':
|
||||
user_query = user_query or content
|
||||
content = ''
|
||||
else:
|
||||
# 本地生成的助手/表单消息不能携带 query;历史回放会把 query 渲染成用户气泡。
|
||||
user_query = ''
|
||||
|
||||
if not message_type:
|
||||
raise ValidationError('type is required')
|
||||
@@ -983,6 +1133,126 @@ def save_local_message():
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'chat_log_id': chat_log.id, 'conversation_id': conversation_id})
|
||||
|
||||
@chat_bp.route('/query-preview/<int:chat_log_id>', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def get_chat_query_preview(chat_log_id: int):
|
||||
page = request.args.get('page', type=int) or 1
|
||||
page_size = request.args.get('page_size', type=int) or 100
|
||||
page = max(1, page)
|
||||
page_size = max(1, min(200, page_size))
|
||||
|
||||
log = db.session.query(ChatLog).filter(
|
||||
ChatLog.id == chat_log_id,
|
||||
ChatLog.user_id == getattr(g.current_user, 'id', 0),
|
||||
ChatLog.agent_id == getattr(g.current_agent, 'id', 0),
|
||||
).first()
|
||||
if not log:
|
||||
raise NotFoundError('query preview not found')
|
||||
|
||||
payload = log.payload if isinstance(log.payload, dict) else {}
|
||||
if payload.get('kind') != 'text2sql_result_preview':
|
||||
raise ValidationError('current message does not support query preview')
|
||||
|
||||
sql = str(payload.get('sql') or '').strip()
|
||||
query = str(payload.get('query') or log.query or '').strip()
|
||||
if not sql:
|
||||
raise ValidationError('query preview sql is missing')
|
||||
|
||||
from app.services.text2sql import Text2SQLService
|
||||
total_count = payload.get('total_count')
|
||||
try:
|
||||
total_count = int(total_count) if total_count is not None else None
|
||||
except (TypeError, ValueError):
|
||||
total_count = None
|
||||
|
||||
columns, rows, resolved_total = Text2SQLService.get_preview_page(
|
||||
sql=sql,
|
||||
query=query,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
agent=g.current_agent,
|
||||
total_count=total_count,
|
||||
user_context=Text2SQLService._normalize_user_context(g.current_user),
|
||||
)
|
||||
if columns == ["Error"]:
|
||||
raise AppError(code='CHAT.QUERY_PREVIEW_FAILED', message=str(rows[0][0] if rows and rows[0] else 'query preview failed'), http_status=500)
|
||||
|
||||
total = resolved_total if resolved_total is not None else len(rows)
|
||||
return jsonify({
|
||||
'columns': columns,
|
||||
'rows': [list(row) for row in rows],
|
||||
'page': page,
|
||||
'page_size': page_size,
|
||||
'total': total,
|
||||
'has_more': page * page_size < total,
|
||||
'query': query,
|
||||
})
|
||||
|
||||
|
||||
@chat_bp.route('/asset-history/search', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def search_asset_history_files():
|
||||
"""
|
||||
检索固定资产履历文件。
|
||||
|
||||
用途:聊天结果表格点击“资产编号”时,返回共享盘中的候选履历文件列表。
|
||||
约束:至少提供资产编号或资产名称之一;不直接返回文件内容,只返回预览所需路径元数据。
|
||||
"""
|
||||
asset_id = (request.args.get('asset_id') or '').strip()
|
||||
asset_name = (request.args.get('asset_name') or '').strip()
|
||||
limit = request.args.get('limit', type=int) or 20
|
||||
limit = max(1, min(limit, 50))
|
||||
|
||||
if not asset_id and not asset_name:
|
||||
raise ValidationError('asset_id or asset_name is required')
|
||||
|
||||
from app.services.fixed_asset_history import FixedAssetHistoryService
|
||||
|
||||
if not FixedAssetHistoryService.is_enabled():
|
||||
raise ServiceUnavailableError('asset history share is not configured')
|
||||
|
||||
items = FixedAssetHistoryService.search_history_files(
|
||||
asset_id=asset_id,
|
||||
asset_name=asset_name,
|
||||
limit=limit,
|
||||
)
|
||||
return jsonify({
|
||||
'asset_id': asset_id,
|
||||
'asset_name': asset_name,
|
||||
'total': len(items),
|
||||
'items': items,
|
||||
})
|
||||
|
||||
|
||||
@chat_bp.route('/asset-image/resolve', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def resolve_asset_image_preview():
|
||||
"""
|
||||
解析固定资产图片预览链接。
|
||||
|
||||
用途:聊天结果表格点击“图片 -> 查看”时,后端自动登录外部文档库并返回最佳图片的可预览元数据。
|
||||
约束:至少提供资产编号或资产名称之一;只返回当前最佳命中的单张图片,不向前端暴露文档库登录态。
|
||||
"""
|
||||
asset_id = (request.args.get('asset_id') or '').strip()
|
||||
asset_name = (request.args.get('asset_name') or '').strip()
|
||||
if not asset_id and not asset_name:
|
||||
raise ValidationError('asset_id or asset_name is required')
|
||||
|
||||
from app.services.fixed_asset_image import FixedAssetImageService
|
||||
|
||||
result = FixedAssetImageService.resolve_images(
|
||||
asset_id=asset_id,
|
||||
asset_name=asset_name,
|
||||
)
|
||||
return jsonify({
|
||||
'asset_id': asset_id,
|
||||
'asset_name': asset_name,
|
||||
'item': result.get('item'),
|
||||
'items': result.get('items', []),
|
||||
'total': result.get('total', 0),
|
||||
})
|
||||
|
||||
|
||||
@chat_bp.route('/completions', methods=['POST'])
|
||||
@require_agent_permission
|
||||
def chat_completions():
|
||||
@@ -1000,8 +1270,11 @@ def chat_completions():
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
query = data.get('query')
|
||||
display_query = str(data.get('display_query') or query or '').strip()
|
||||
# 前端传入的 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]
|
||||
@@ -1012,25 +1285,45 @@ def chat_completions():
|
||||
current_app.logger.error("[chat-api] missing user/agent context user=%s agent=%s", bool(user), bool(agent))
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
|
||||
|
||||
from app.services.agent_registry.resolver import resolve_runtime_provider
|
||||
|
||||
if resolve_runtime_provider(agent) == 'iframe':
|
||||
raise ValidationError('Embedded iframe agents do not support chat completions')
|
||||
|
||||
user_id = getattr(user, 'id', None)
|
||||
agent_id = getattr(agent, 'id', None)
|
||||
|
||||
from types import SimpleNamespace
|
||||
from app.services.agent_directory import serialize_directory_members
|
||||
|
||||
is_aggregate = bool(getattr(agent, 'is_aggregate', False))
|
||||
directory_members = serialize_directory_members(agent_id, active_only=True) if is_aggregate else []
|
||||
agent_proxy = SimpleNamespace(
|
||||
id=agent_id,
|
||||
name=getattr(agent, 'name', None),
|
||||
type=getattr(agent, 'type', None),
|
||||
dify_api_key=getattr(agent, 'dify_api_key', None),
|
||||
api_base_url=getattr(agent, 'api_base_url', None),
|
||||
extra_config=getattr(agent, 'extra_config', None) or {},
|
||||
agent_code=getattr(agent, 'agent_code', None),
|
||||
runtime_provider=getattr(agent, 'runtime_provider', None),
|
||||
conversation_mode=getattr(agent, 'conversation_mode', None),
|
||||
dify_app_type=getattr(agent, 'dify_app_type', None),
|
||||
capabilities=getattr(agent, 'capabilities', None),
|
||||
bound_schedule_task_id=getattr(agent, 'bound_schedule_task_id', None),
|
||||
handler_config=getattr(agent, 'handler_config', None),
|
||||
is_aggregate=is_aggregate,
|
||||
directory_members=directory_members,
|
||||
)
|
||||
user_proxy = SimpleNamespace(
|
||||
id=user_id,
|
||||
username=getattr(user, 'username', None),
|
||||
employee_id=getattr(user, 'employee_id', None),
|
||||
real_name=getattr(user, 'real_name', None),
|
||||
role=getattr(user, 'role', None),
|
||||
)
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.services.plm_oracle import PLMOracleService
|
||||
|
||||
external_conversation_id = None
|
||||
if conversation_id:
|
||||
@@ -1040,22 +1333,35 @@ def chat_completions():
|
||||
user_id,
|
||||
agent_id,
|
||||
existing_session.session_id,
|
||||
title=query,
|
||||
title=display_query,
|
||||
status='running',
|
||||
)
|
||||
external_conversation_id = session.external_conversation_id
|
||||
if external_conversation_id and _should_reset_provider_conversation_for_asset_query(query, agent_proxy):
|
||||
current_app.logger.info(
|
||||
'[chat-api] reset provider conversation for asset query request_id=%s session_id=%s old_provider_conversation_id=%s query=%s',
|
||||
request_id,
|
||||
session.session_id,
|
||||
external_conversation_id,
|
||||
query,
|
||||
)
|
||||
session.external_conversation_id = None
|
||||
session.updated_at = datetime.utcnow()
|
||||
session.last_active_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
external_conversation_id = None
|
||||
else:
|
||||
session = _ensure_chat_session(
|
||||
user_id,
|
||||
agent_id,
|
||||
conversation_id,
|
||||
title=query,
|
||||
title=display_query,
|
||||
status='running',
|
||||
external_conversation_id=conversation_id,
|
||||
)
|
||||
external_conversation_id = session.external_conversation_id
|
||||
else:
|
||||
session = _ensure_chat_session(user_id, agent_id, None, title=query, status='running')
|
||||
session = _ensure_chat_session(user_id, agent_id, None, title=display_query, status='running')
|
||||
|
||||
normalized_files: list[dict] | None = None
|
||||
if files is not None:
|
||||
@@ -1084,47 +1390,75 @@ def chat_completions():
|
||||
if not normalized_files:
|
||||
normalized_files = None
|
||||
|
||||
if normalized_files and PLMOracleService.supports(query, agent_proxy):
|
||||
raise ValidationError('This route does not support attachments')
|
||||
from app.services.agent_registry.handlers.base import ChatStreamContext
|
||||
|
||||
relay_stream_ctx = ChatStreamContext(
|
||||
query=query,
|
||||
display_query=display_query,
|
||||
user=user_proxy,
|
||||
agent=agent_proxy,
|
||||
session=session,
|
||||
external_conversation_id=external_conversation_id,
|
||||
request_id=request_id,
|
||||
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,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
kb_type=kb_type,
|
||||
)
|
||||
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
from app.services.chat.router import try_fast_route
|
||||
|
||||
leave_supported = HRLeaveSQLServerService.supports(query)
|
||||
leave_feature_enabled = _can_use_leave_feature(agent_proxy)
|
||||
if PLMOracleService.supports(query, agent_proxy):
|
||||
generator = PLMOracleService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
elif leave_supported and leave_feature_enabled:
|
||||
if normalized_files:
|
||||
raise ValidationError('This route does not support attachments')
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
|
||||
fast_route = try_fast_route(
|
||||
user=user_proxy,
|
||||
agent=agent_proxy,
|
||||
query=query,
|
||||
agent_id=agent_id,
|
||||
session_id=session.session_id,
|
||||
external_conversation_id=external_conversation_id,
|
||||
normalized_files=normalized_files,
|
||||
kb_type=kb_type,
|
||||
leave_supported=leave_supported,
|
||||
)
|
||||
if fast_route is not None:
|
||||
generator = fast_route.generator
|
||||
elif leave_supported:
|
||||
generator = DifyService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, request_id=request_id, session_id=session.session_id, files=normalized_files)
|
||||
elif kb_type == 'ERP知识库':
|
||||
from app.services.text2sql import Text2SQLService
|
||||
if normalized_files:
|
||||
raise ValidationError('This route does not support attachments')
|
||||
generator = Text2SQLService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
else:
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
if HRLeaveSQLServerService.supports(query):
|
||||
if normalized_files:
|
||||
raise ValidationError('This route does not support attachments')
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
else:
|
||||
dify_inputs = None
|
||||
from app.services.shipping_notice.dify_inputs import build_dify_chat_inputs, is_shipping_notice_chat_agent
|
||||
if is_shipping_notice_chat_agent(agent_proxy):
|
||||
dify_inputs = build_dify_chat_inputs()
|
||||
generator = DifyService.stream_chat(
|
||||
query,
|
||||
user_proxy.id,
|
||||
generator = DifyService.stream_chat(
|
||||
query,
|
||||
user_proxy.id,
|
||||
agent_proxy,
|
||||
external_conversation_id,
|
||||
request_id=request_id,
|
||||
session_id=session.session_id,
|
||||
files=normalized_files,
|
||||
inputs=build_chat_dify_inputs(
|
||||
agent_proxy,
|
||||
external_conversation_id,
|
||||
request_id=request_id,
|
||||
session_id=session.session_id,
|
||||
files=normalized_files,
|
||||
inputs=dify_inputs,
|
||||
)
|
||||
request_id=request_id,
|
||||
trigger_source="frontend_chat",
|
||||
user_role=user_proxy.role,
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
),
|
||||
),
|
||||
)
|
||||
else:
|
||||
from app.services.chat.executors import stream_chat_via_executor
|
||||
|
||||
generator = stream_chat_via_executor(relay_stream_ctx)
|
||||
|
||||
def relay_stream():
|
||||
from app.services.chat_perf import chat_perf_enabled
|
||||
|
||||
relay_started = time.perf_counter()
|
||||
relay_first_chunk_at: float | None = None
|
||||
created_event = {
|
||||
'event': 'session_created',
|
||||
'conversation_id': session.session_id,
|
||||
@@ -1135,9 +1469,20 @@ def chat_completions():
|
||||
|
||||
known_provider_conversation_id = session.external_conversation_id
|
||||
known_status = session.status
|
||||
emitted_handler_state_keys: set[str] = set()
|
||||
|
||||
from app.services.chat.stream_relay import (
|
||||
iter_handler_preface_sse,
|
||||
iter_handler_terminal_sse,
|
||||
)
|
||||
|
||||
for preface_line in iter_handler_preface_sse(relay_stream_ctx, emitted_keys=emitted_handler_state_keys):
|
||||
yield preface_line
|
||||
|
||||
try:
|
||||
for chunk in generator:
|
||||
if relay_first_chunk_at is None:
|
||||
relay_first_chunk_at = time.perf_counter()
|
||||
if not isinstance(chunk, str) or not chunk.startswith('data: '):
|
||||
yield chunk
|
||||
continue
|
||||
@@ -1155,7 +1500,7 @@ def chat_completions():
|
||||
if provider_conversation_id and provider_conversation_id != known_provider_conversation_id:
|
||||
known_provider_conversation_id = provider_conversation_id
|
||||
should_touch = True
|
||||
if event_name == 'message_end':
|
||||
if event_name in ('message_end', 'workflow_finished'):
|
||||
known_status = 'done'
|
||||
should_touch = True
|
||||
elif event_name == 'error':
|
||||
@@ -1177,7 +1522,29 @@ def chat_completions():
|
||||
event_data['provider_conversation_id'] = provider_conversation_id
|
||||
event_data['conversation_id'] = session.session_id
|
||||
event_data['session_status'] = known_status
|
||||
if chat_perf_enabled() and event_name in ('message_end', 'workflow_finished'):
|
||||
relay_first_ms = int((relay_first_chunk_at - relay_started) * 1000) if relay_first_chunk_at else None
|
||||
relay_total_ms = int((time.perf_counter() - relay_started) * 1000)
|
||||
current_app.logger.info(
|
||||
'[chat-perf] relay request_id=%s session_id=%s first_chunk_ms=%s total_relay_ms=%s event=%s',
|
||||
request_id,
|
||||
session.session_id,
|
||||
relay_first_ms,
|
||||
relay_total_ms,
|
||||
event_name,
|
||||
)
|
||||
event_data['hxops_relay'] = {
|
||||
'first_chunk_ms': relay_first_ms,
|
||||
'total_relay_ms': relay_total_ms,
|
||||
}
|
||||
yield f"data: {json.dumps(event_data, ensure_ascii=False)}\n\n"
|
||||
if event_name in ('message_end', 'workflow_finished'):
|
||||
for terminal_line in iter_handler_terminal_sse(
|
||||
relay_stream_ctx,
|
||||
event_data,
|
||||
emitted_keys=emitted_handler_state_keys,
|
||||
):
|
||||
yield terminal_line
|
||||
except Exception as exc:
|
||||
current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, session.session_id)
|
||||
payload = {'event': 'error', 'message': str(exc), 'conversation_id': session.session_id, 'session_status': 'error'}
|
||||
@@ -1216,7 +1583,7 @@ def upload_chat_file():
|
||||
raise ValidationError('file is required')
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.config import Config
|
||||
from app.core.config.settings import Config
|
||||
|
||||
params = DifyService.get_app_parameters(agent, force_refresh=True)
|
||||
file_upload_cfg = (params or {}).get('file_upload') if isinstance(params, dict) else {}
|
||||
@@ -1769,3 +2136,8 @@ def preview_file_raw():
|
||||
resp.headers['X-Preview-Actual-Ext'] = ext or ''
|
||||
resp.headers['X-Preview-Original-Ext'] = original_ext or ''
|
||||
return resp
|
||||
|
||||
|
||||
from app.api.chat_turns import register_chat_turn_routes
|
||||
|
||||
register_chat_turn_routes(chat_bp)
|
||||
@@ -0,0 +1,162 @@
|
||||
"""
|
||||
backend/app/api/chat_turns.py
|
||||
|
||||
用途:Chat Turn 流式 API 路由(POST /api/chat/turns/stream)。
|
||||
依赖:app.core.decorators、ChatTurnRuntime、notice_upload、batch_from_notices、chat_bp。
|
||||
逻辑:支持 JSON 与 multipart(附件上传 + Turn);由 chat.py 注册到同一 Blueprint。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import uuid
|
||||
|
||||
from flask import Response, g, request, stream_with_context
|
||||
|
||||
from app.core.decorators import require_agent_permission
|
||||
from app.core.errors import AppError, ValidationError
|
||||
from app.services.chat.turn_runtime import ChatTurnRuntime
|
||||
|
||||
|
||||
def _parse_turn_body_and_files() -> tuple[dict, list]:
|
||||
"""
|
||||
解析 Chat Turn 请求体;multipart 时从 form 字段读取 JSON 与 files。
|
||||
|
||||
Returns:
|
||||
(body, uploads) — uploads 为 Werkzeug FileStorage 列表,JSON 请求时为空。
|
||||
"""
|
||||
content_type = str(request.content_type or "")
|
||||
if "multipart/form-data" in content_type:
|
||||
input_raw = request.form.get("input") or "{}"
|
||||
try:
|
||||
input_data = json.loads(input_raw)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValidationError("input must be valid JSON") from exc
|
||||
context_raw = request.form.get("context") or "{}"
|
||||
try:
|
||||
context_data = json.loads(context_raw) if context_raw else {}
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValidationError("context must be valid JSON") from exc
|
||||
agent_id = request.form.get("agent_id") or request.form.get("agentId")
|
||||
conversation_id = request.form.get("conversation_id") or request.form.get("conversationId")
|
||||
body: dict = {
|
||||
"agent_id": agent_id,
|
||||
"conversation_id": conversation_id,
|
||||
"input": input_data if isinstance(input_data, dict) else {},
|
||||
"context": context_data if isinstance(context_data, dict) else {},
|
||||
}
|
||||
uploads = request.files.getlist("files")
|
||||
if not uploads:
|
||||
single = request.files.get("file")
|
||||
if single:
|
||||
uploads = [single]
|
||||
return body, uploads
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
return body if isinstance(body, dict) else {}, []
|
||||
|
||||
|
||||
def _stage_upload_files(uploads: list) -> list[dict]:
|
||||
"""将 multipart 文件读入内存 staged 结构,供 handler 构造 FileStorage。"""
|
||||
staged: list[dict] = []
|
||||
for upload in uploads:
|
||||
if upload is None:
|
||||
continue
|
||||
data = upload.read() or b""
|
||||
if not data:
|
||||
continue
|
||||
staged.append({
|
||||
"filename": str(getattr(upload, "filename", None) or "upload"),
|
||||
"content_type": str(getattr(upload, "content_type", None) or ""),
|
||||
"data": data,
|
||||
})
|
||||
return staged
|
||||
|
||||
|
||||
def _inject_multipart_upload_payload(body: dict, uploads: list) -> None:
|
||||
"""
|
||||
将 multipart 附件写入 Turn input.payload。
|
||||
|
||||
- shipping.create_batch_from_notices:预检 notice_items
|
||||
- shipping.upload_inventory / shipping.replace_notice:staged 原始文件字节
|
||||
"""
|
||||
if not uploads:
|
||||
return
|
||||
input_block = body.get("input") if isinstance(body.get("input"), dict) else {}
|
||||
action_type = str(input_block.get("action_type") or input_block.get("actionType") or "").strip()
|
||||
payload = input_block.get("payload") if isinstance(input_block.get("payload"), dict) else {}
|
||||
payload = dict(payload)
|
||||
|
||||
if action_type == "shipping.create_batch_from_notices":
|
||||
from app.services.shipping_notice.batch_from_notices import intake_notice_uploads_for_batch
|
||||
from app.services.shipping_notice.notice_upload import cleanup_temp_notice_uploads
|
||||
|
||||
temp_request_id = uuid.uuid4().hex
|
||||
try:
|
||||
notice_items, file_summary = intake_notice_uploads_for_batch(temp_request_id, uploads)
|
||||
finally:
|
||||
cleanup_temp_notice_uploads(temp_request_id)
|
||||
if not notice_items:
|
||||
raise ValidationError(
|
||||
"未能从发货通知附件中抽取到可解析文本,请上传清晰版 PDF/文本后重试",
|
||||
details={"file_summary": file_summary},
|
||||
)
|
||||
payload["notice_items"] = notice_items
|
||||
payload["file_summary"] = file_summary
|
||||
conversation_id = str(body.get("conversation_id") or body.get("conversationId") or "").strip()
|
||||
if conversation_id:
|
||||
payload["conversation_id"] = conversation_id
|
||||
elif action_type in ("shipping.upload_inventory", "shipping.replace_notice"):
|
||||
staged = _stage_upload_files(uploads)
|
||||
if not staged:
|
||||
raise ValidationError("file is required")
|
||||
payload["_staged_files"] = staged
|
||||
else:
|
||||
return
|
||||
|
||||
input_block["payload"] = payload
|
||||
input_block["type"] = input_block.get("type") or "upload_followup"
|
||||
body["input"] = input_block
|
||||
|
||||
|
||||
def register_chat_turn_routes(chat_bp) -> None:
|
||||
"""将 Chat Turn 路由注册到 chat Blueprint。"""
|
||||
|
||||
@chat_bp.route('/turns/stream', methods=['POST'])
|
||||
@require_agent_permission
|
||||
def chat_turns_stream():
|
||||
"""
|
||||
统一 Chat Turn SSE 接口。
|
||||
|
||||
核心逻辑:解析 action/form_submit/upload_followup;multipart 时预检附件并注入 payload,
|
||||
经 ChatTurnRuntime 路由至 action handler,返回 run.started / step.* / message.* / run.completed。
|
||||
"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
if user is None or agent is None:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
|
||||
|
||||
body, uploads = _parse_turn_body_and_files()
|
||||
request_id = uuid.uuid4().hex[:12]
|
||||
# [STEP 1] multipart 附件必须在返回 SSE 前读完;生成器延迟执行时 request.files 可能已关闭。
|
||||
if uploads:
|
||||
_inject_multipart_upload_payload(body, uploads)
|
||||
|
||||
def relay_stream():
|
||||
yield from ChatTurnRuntime.stream(
|
||||
user=user,
|
||||
agent=agent,
|
||||
body=body,
|
||||
request_id=request_id,
|
||||
)
|
||||
|
||||
return Response(
|
||||
stream_with_context(relay_stream()),
|
||||
mimetype='text/event-stream',
|
||||
headers={
|
||||
'Cache-Control': 'no-cache',
|
||||
'Content-Type': 'text/event-stream; charset=utf-8',
|
||||
'Connection': 'keep-alive',
|
||||
'X-Accel-Buffering': 'no',
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,562 @@
|
||||
"""
|
||||
backend/app/api/file_check_tools.py
|
||||
|
||||
用途:文件检核 Chatflow 显式 HTTP Tool API。
|
||||
依赖:workspace_file_check、file_check_tools、schedule.scheduler_service。
|
||||
逻辑:Dify Chatflow 调用本蓝图发起检核、查询批次、下载 Excel。
|
||||
"""
|
||||
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.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, run_task_now
|
||||
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(浏览器场景);其余端点校验 Dify/RPA 的 Tool API Key。
|
||||
"""
|
||||
# [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 服务端调用
|
||||
configured = str(
|
||||
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
or ""
|
||||
).strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError(
|
||||
"FILE_CHECK_TOOL_API_KEY or INTEGRATION_API_KEY is not configured",
|
||||
code="missing_auth",
|
||||
)
|
||||
|
||||
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||
api_token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||
if configured in {api_token, integration_key}:
|
||||
return
|
||||
if not api_token and not integration_key:
|
||||
raise UnauthorizedError("missing_auth")
|
||||
raise UnauthorizedError("invalid_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 _build_no_data_response(task: ScheduleTask) -> dict:
|
||||
"""无待检资料时直接返回提示,不创建批次也不绑定 run_id。"""
|
||||
return {
|
||||
"ok": False,
|
||||
"error_code": "no_data_to_check",
|
||||
"message": "目前没有资料需要检核",
|
||||
"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,
|
||||
避免创建空批次并向 ChatLog 回写 run_id。数据源连接失败时抛 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 _build_no_data_response(task)
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/tasks/run", methods=["POST"])
|
||||
def run_file_check():
|
||||
"""立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。"""
|
||||
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:
|
||||
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",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
task.id,
|
||||
)
|
||||
return jsonify(no_data_response)
|
||||
|
||||
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={
|
||||
"trigger_source": data.get("trigger_source") or "dify_chatflow",
|
||||
"conversation_id": data.get("conversation_id"),
|
||||
},
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
_record_run_bind(run, data)
|
||||
db.session.commit()
|
||||
app = current_app._get_current_object()
|
||||
run_id = run.id
|
||||
task_id = task.id
|
||||
|
||||
def _background():
|
||||
with app.app_context():
|
||||
t = db.session.get(ScheduleTask, task_id)
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if not t or not r:
|
||||
return
|
||||
try:
|
||||
run_task_now(t, trigger_type="dify_chatflow", triggered_by_user_id=None, run=r)
|
||||
except Exception as exc:
|
||||
current_app.logger.error("[file-check-tool] run_id=%s failed: %s", run_id, exc, exc_info=True)
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if r and r.status == "running":
|
||||
r.status = "failed"
|
||||
r.error_message = str(exc)
|
||||
r.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
threading.Thread(target=_background, daemon=True, name=f"file-check-run-{run_id}").start()
|
||||
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")
|
||||
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/history/search", methods=["POST"])
|
||||
def search_file_check_history():
|
||||
"""
|
||||
检索已入库的历史检核报告片段;按 task_id 解析 ScheduleTask → KbGroup → Dify Dataset。
|
||||
|
||||
核心逻辑:Chatflow history_report_query 分支调用;task_id 来自 HXOPS 注入的 Start 变量。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
raw_task_id = data.get("task_id")
|
||||
try:
|
||||
task_id = int(raw_task_id)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError("task_id_invalid")
|
||||
if task_id <= 0:
|
||||
raise ValidationError("task_id_invalid")
|
||||
|
||||
from app.services.file_check_tools.history_search_service import search_file_check_history as run_history_search
|
||||
|
||||
result = run_history_search(
|
||||
task_id=task_id,
|
||||
query=str(data.get("query") or ""),
|
||||
top_k=data.get("top_k"),
|
||||
score_threshold=data.get("score_threshold"),
|
||||
)
|
||||
return jsonify({"ok": True, **result})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def file_check_openapi_spec():
|
||||
return jsonify(build_file_check_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
|
||||
@@ -0,0 +1,11 @@
|
||||
"""
|
||||
backend/app/api/files/__init__.py
|
||||
|
||||
用途:平台级文件资产 API 包入口。
|
||||
依赖:files.assets。
|
||||
逻辑:register_blueprints 挂载 /api/files。
|
||||
"""
|
||||
|
||||
from app.api.files.assets import files_bp
|
||||
|
||||
__all__ = ['files_bp']
|
||||
@@ -0,0 +1,80 @@
|
||||
"""
|
||||
backend/app/api/files/assets.py
|
||||
|
||||
用途:通用文件资产上传、查询、删除与受控下载 API。
|
||||
依赖:file_assets.service、app.core.auth.jwt、app.core.response。
|
||||
逻辑:薄路由鉴权与参数校验;storage_key 不向前端返回。
|
||||
"""
|
||||
|
||||
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
|
||||
from app.core.response import ok
|
||||
from app.services.file_assets.service import (
|
||||
delete_temporary_asset,
|
||||
get_asset_for_user,
|
||||
read_asset_bytes,
|
||||
serialize_asset_public,
|
||||
upload_file_asset,
|
||||
)
|
||||
|
||||
files_bp = Blueprint('files', __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
@files_bp.route('/assets', methods=['POST'])
|
||||
def upload_asset():
|
||||
"""上传文件并创建 FileAsset。"""
|
||||
user = _require_user()
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
raise ValidationError('file is required')
|
||||
if not upload.filename:
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
raise ValidationError('file is required')
|
||||
data = upload_file_asset(user_id=user.id, upload=upload)
|
||||
return ok(data, request_id=getattr(g, 'request_id', None), status=201)
|
||||
|
||||
|
||||
@files_bp.route('/assets/<asset_no>', methods=['GET'])
|
||||
def get_asset(asset_no: str):
|
||||
"""查询当前用户的文件资产元数据。"""
|
||||
user = _require_user()
|
||||
asset = get_asset_for_user(asset_no, user.id)
|
||||
return ok(serialize_asset_public(asset), request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@files_bp.route('/assets/<asset_no>', methods=['DELETE'])
|
||||
def delete_asset(asset_no: str):
|
||||
"""逻辑删除未引用的临时资产。"""
|
||||
user = _require_user()
|
||||
delete_temporary_asset(asset_no=asset_no, user_id=user.id)
|
||||
return ok({'deleted': True}, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@files_bp.route('/assets/<asset_no>/download', methods=['GET'])
|
||||
def download_asset(asset_no: str):
|
||||
"""鉴权后流式下载文件内容。"""
|
||||
user = _require_user()
|
||||
asset = get_asset_for_user(asset_no, user.id)
|
||||
data = read_asset_bytes(asset)
|
||||
return send_file(
|
||||
io.BytesIO(data),
|
||||
mimetype=asset.mime_type or 'application/octet-stream',
|
||||
as_attachment=True,
|
||||
download_name=asset.original_filename,
|
||||
)
|
||||
@@ -9,7 +9,16 @@ from sqlalchemy import func
|
||||
from sqlalchemy.orm import joinedload
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
raise_for_status,
|
||||
)
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
integration_bp = Blueprint('integration', __name__)
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
"""
|
||||
backend/app/api/internal/__init__.py
|
||||
|
||||
用途:内部 job 回调/健康检查 Blueprint。
|
||||
"""
|
||||
from app.api.internal.jobs import internal_jobs_bp # noqa: F401
|
||||
|
||||
__all__ = ['internal_jobs_bp']
|
||||
@@ -0,0 +1,8 @@
|
||||
"""
|
||||
backend/app/api/internal/jobs.py
|
||||
|
||||
用途:内部 jobs API(Wave 1 自 internal_jobs.py 迁入)。
|
||||
"""
|
||||
from app.api.internal_jobs import internal_jobs_bp # noqa: F401
|
||||
|
||||
__all__ = ['internal_jobs_bp']
|
||||
@@ -1,49 +1,114 @@
|
||||
"""
|
||||
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 import _run_generic_check_job
|
||||
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
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,
|
||||
)
|
||||
|
||||
internal_jobs_bp = Blueprint('internal_jobs', __name__)
|
||||
|
||||
@internal_jobs_bp.route('/<name>', methods=['POST'])
|
||||
def run_internal_job(name: str):
|
||||
key = name.strip().lower()
|
||||
data = request.get_json(silent=True) or {}
|
||||
run_no = str(data.get('run_no') or '').strip()
|
||||
|
||||
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 = None
|
||||
if schedule_task_id:
|
||||
task = db.session.get(ScheduleTask, int(schedule_task_id))
|
||||
if not task and key.isdigit():
|
||||
task = db.session.get(ScheduleTask, int(key))
|
||||
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:
|
||||
task = ScheduleTask.query.filter(ScheduleTask.platform_api_path.ilike(f'%{key}%')).first()
|
||||
if not task:
|
||||
raise NotFoundError(f"No schedule task found for '{name}'")
|
||||
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).first()
|
||||
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:
|
||||
from app.services.schedule.scheduler_service import _generate_run_no
|
||||
run = ScheduleRun(run_no=run_no or _generate_run_no(), schedule_task_id=task.id, trigger_type='api', started_at=datetime.utcnow(), status='running')
|
||||
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()
|
||||
try:
|
||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_generic_check_job(task, run)
|
||||
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}})
|
||||
run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed'
|
||||
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
|
||||
@@ -53,4 +118,87 @@ def run_internal_job(name: str):
|
||||
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()
|
||||
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})
|
||||
|
||||
|
||||
@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)
|
||||
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,
|
||||
})
|
||||
|
||||
_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,
|
||||
})
|
||||
@@ -0,0 +1,16 @@
|
||||
"""
|
||||
backend/app/api/kb/__init__.py
|
||||
|
||||
用途:知识库管理 Blueprint 入口(Wave 3 分包)。
|
||||
依赖:kb/blueprint.py、common、dify、groups、documents、jobs。
|
||||
逻辑:import 子模块注册路由;register_blueprints 从本包 import knowledge_base_bp。
|
||||
"""
|
||||
from app.api.kb.blueprint import knowledge_base_bp
|
||||
|
||||
import app.api.kb.common # noqa: F401
|
||||
import app.api.kb.dify # noqa: F401
|
||||
import app.api.kb.groups # noqa: F401
|
||||
import app.api.kb.documents # noqa: F401
|
||||
import app.api.kb.jobs # noqa: F401
|
||||
|
||||
__all__ = ['knowledge_base_bp']
|
||||
@@ -0,0 +1,10 @@
|
||||
"""
|
||||
backend/app/api/kb/blueprint.py
|
||||
|
||||
用途:知识库 API 共享 Blueprint(Wave 3 分包后各子模块共用)。
|
||||
依赖:Flask Blueprint。
|
||||
逻辑:kb/dify、groups、documents、jobs 等子模块在此 bp 上注册路由;__init__ 导出 knowledge_base_bp。
|
||||
"""
|
||||
from flask import Blueprint
|
||||
|
||||
knowledge_base_bp = Blueprint('knowledge_base', __name__)
|
||||
@@ -0,0 +1,73 @@
|
||||
"""
|
||||
backend/app/api/kb/common.py
|
||||
|
||||
用途:知识库 API 共享 helper(鉴权、序列化、Markdown 预览)。
|
||||
依赖:app.core.*、models、services/kb/storage、edkb_system。
|
||||
逻辑:dify/groups/documents/jobs 子模块共用;存储读写见 services/kb/storage。
|
||||
"""
|
||||
from flask import current_app
|
||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError
|
||||
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup
|
||||
from app.services.kb.markdown import (
|
||||
markdown_unavailable_message,
|
||||
resolve_markdown_read_path,
|
||||
resolve_markdown_write_path,
|
||||
serialize_markdown_payload,
|
||||
)
|
||||
from app.services.kb.storage import (
|
||||
kb_storage_root,
|
||||
resolve_storage_path,
|
||||
safe_upload_filename,
|
||||
save_upload,
|
||||
)
|
||||
|
||||
def require_user():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
def run_db_read(label: str, loader):
|
||||
try:
|
||||
return loader()
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('[kb] transient db error during %s, retry with reconnect: %s', label, exc)
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
db.engine.dispose()
|
||||
except Exception:
|
||||
current_app.logger.warning('[kb] failed to dispose engine during %s recovery', label, exc_info=True)
|
||||
return loader()
|
||||
|
||||
def serialize_group(group: KbGroup, document_count: int=0):
|
||||
return {'id': group.id, 'name': group.name, 'description': group.description, 'department_id': group.department_id, 'document_count': int(document_count or 0), 'created_at': group.created_at.isoformat() if group.created_at else None, 'updated_at': group.updated_at.isoformat() if group.updated_at else None}
|
||||
|
||||
def serialize_document(doc: KbDocument):
|
||||
latest_version = current_version(doc)
|
||||
return {'id': doc.id, 'group_id': doc.group_id, 'title': doc.title, 'description': doc.description, 'status': doc.status, 'source_type': doc.source_type, 'created_at': doc.created_at.isoformat() if doc.created_at else None, 'updated_at': doc.updated_at.isoformat() if doc.updated_at else None, 'version_count': len(doc.versions) if getattr(doc, 'versions', None) else 0, 'latest_version': serialize_version(latest_version) if latest_version else None}
|
||||
|
||||
def serialize_version(version: KbDocumentVersion | None):
|
||||
if version is None:
|
||||
return None
|
||||
return {'id': version.id, 'document_id': version.document_id, 'version_no': version.version_no, 'status': version.status, 'is_current': version.is_current, 'source_file_name': version.source_file_name, 'source_file_ext': version.source_file_ext, 'source_file_size': version.source_file_size, 'sha256': version.sha256, 'cleaned_file_path': version.cleaned_file_path, 'cleaned_preview_path': version.cleaned_preview_path, 'error_message': version.error_message, 'created_at': version.created_at.isoformat() if version.created_at else None}
|
||||
|
||||
def serialize_sync_record(record: KbDifySyncRecord):
|
||||
return {'id': record.id, 'group_id': record.group_id, 'document_id': record.document_id, 'document_version_id': record.document_version_id, 'dataset_id': record.dataset_id, 'dataset_name': record.dataset_name, 'remote_document_id': record.remote_document_id, 'remote_document_name': record.remote_document_name, 'status': record.status, 'sync_hash': record.sync_hash, 'error_message': record.error_message, 'synced_at': record.synced_at.isoformat() if record.synced_at else None, 'updated_at': record.updated_at.isoformat() if record.updated_at else None}
|
||||
|
||||
def current_version(document: KbDocument | None) -> KbDocumentVersion | None:
|
||||
versions = list(getattr(document, 'versions', []) or [])
|
||||
if not versions:
|
||||
return None
|
||||
return next((item for item in versions if item.is_current), versions[0])
|
||||
|
||||
|
||||
def next_version_no(document: KbDocument) -> int:
|
||||
versions = list(getattr(document, 'versions', []) or [])
|
||||
if not versions:
|
||||
return 1
|
||||
return max((item.version_no for item in versions)) + 1
|
||||
@@ -0,0 +1,45 @@
|
||||
"""
|
||||
backend/app/api/kb/dify.py
|
||||
|
||||
用途:知识库 Dify 连接配置与健康检查 API。
|
||||
依赖:kb.blueprint、knowledge_cleaning.settings_service。
|
||||
逻辑:管理员读写 Dify 设置;GET /dify/health 探测远端 dataset。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.kb.blueprint import knowledge_base_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.knowledge_cleaning.settings_service import (
|
||||
get_kb_dify_health_payload,
|
||||
get_kb_dify_settings,
|
||||
save_kb_dify_settings,
|
||||
)
|
||||
|
||||
@knowledge_base_bp.route('/dify/settings', methods=['GET'])
|
||||
@require_admin
|
||||
def get_dify_settings():
|
||||
payload = get_kb_dify_settings()
|
||||
return jsonify(payload)
|
||||
|
||||
@knowledge_base_bp.route('/dify/settings', methods=['PATCH'])
|
||||
@require_admin
|
||||
def update_dify_settings():
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = save_kb_dify_settings(data)
|
||||
return jsonify(payload)
|
||||
|
||||
@knowledge_base_bp.route('/dify/health', methods=['GET'])
|
||||
@require_admin
|
||||
def get_dify_health():
|
||||
payload = get_kb_dify_health_payload()
|
||||
if payload['dify_api_configured'] and payload['dify_base_url']:
|
||||
try:
|
||||
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
|
||||
datasets = KbDifySyncService().list_datasets()
|
||||
payload['api']['reachable'] = True
|
||||
payload['api']['dataset_count'] = len(datasets)
|
||||
except Exception as exc:
|
||||
payload['api']['error'] = str(exc)
|
||||
else:
|
||||
payload['api']['error'] = 'Dify 连接尚未配置'
|
||||
return jsonify(payload)
|
||||
@@ -0,0 +1,113 @@
|
||||
"""
|
||||
backend/app/api/kb/documents.py
|
||||
|
||||
用途:知识库文档版本、Markdown、上传/清洗/同步 API(薄路由层)。
|
||||
依赖:kb.blueprint、kb.common、services/kb/document_service。
|
||||
逻辑:/documents* 与 /document-versions* 路由;业务见 document_service。
|
||||
"""
|
||||
from flask import jsonify, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.api.kb.blueprint import knowledge_base_bp
|
||||
from app.api.kb.common import require_user, serialize_document, serialize_sync_record, serialize_version
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.kb import document_service
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/versions', methods=['GET'])
|
||||
def list_document_versions(document_id: int):
|
||||
require_user()
|
||||
versions = document_service.list_document_versions(document_id)
|
||||
return jsonify([serialize_version(item) for item in versions])
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/document-versions/<int:version_id>/source-file', methods=['GET'])
|
||||
def get_document_version_source_file(version_id: int):
|
||||
require_user()
|
||||
source_path, filename = document_service.resolve_source_file_path(version_id)
|
||||
as_attachment = str(request.args.get('download') or '').strip() == '1'
|
||||
return send_file(source_path, as_attachment=as_attachment, download_name=filename)
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/sync-records', methods=['GET'])
|
||||
def list_document_sync_records(document_id: int):
|
||||
require_user()
|
||||
records = document_service.list_sync_records(document_id)
|
||||
return jsonify([serialize_sync_record(item) for item in records])
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/markdown', methods=['GET'])
|
||||
def get_document_markdown(document_id: int):
|
||||
require_user()
|
||||
return jsonify(document_service.read_markdown(document_id))
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/markdown', methods=['PATCH'])
|
||||
def update_document_markdown(document_id: int):
|
||||
current_user = require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = document_service.update_markdown(
|
||||
document_id,
|
||||
data.get('content'),
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify(payload)
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/upload', methods=['POST'])
|
||||
def upload_document_version(document_id: int):
|
||||
current_user = require_user()
|
||||
uploaded = request.files.get('file')
|
||||
payload = document_service.upload_new_version(
|
||||
document_id,
|
||||
uploaded,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/clean', methods=['POST'])
|
||||
@require_admin
|
||||
def submit_document_clean(document_id: int):
|
||||
current_user = get_current_user()
|
||||
payload, status_code = document_service.submit_clean(
|
||||
document_id,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
return jsonify(payload), status_code
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/sync', methods=['POST'])
|
||||
@require_admin
|
||||
def sync_document(document_id: int):
|
||||
current_user = get_current_user()
|
||||
payload = document_service.submit_sync(
|
||||
document_id,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
return jsonify(payload), 202
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>', methods=['PATCH'])
|
||||
def update_document(document_id: int):
|
||||
current_user = require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
document = document_service.update_metadata(
|
||||
document_id,
|
||||
data,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify(serialize_document(document))
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>', methods=['DELETE'])
|
||||
def delete_document(document_id: int):
|
||||
current_user = require_user()
|
||||
result = document_service.delete_document(
|
||||
document_id,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
return jsonify(result)
|
||||
@@ -0,0 +1,292 @@
|
||||
"""
|
||||
backend/app/api/kb/groups.py
|
||||
|
||||
用途:知识库分组 CRUD、组内文档列表与路径批量上传 API(薄路由)。
|
||||
依赖:kb.blueprint、kb.common、services/kb/path_upload_service、services/kb/job_lifecycle。
|
||||
逻辑:/groups* 与 /path-upload-jobs*;业务编排委托 path_upload_service。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import jsonify, request
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
from app import db
|
||||
from app.api.kb.blueprint import knowledge_base_bp
|
||||
from app.api.kb.common import require_user, run_db_read, serialize_document, serialize_group
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import KbDocument, KbGroup, KbJob
|
||||
from app.services.kb import path_upload_service
|
||||
from app.services.kb.job_lifecycle import cancel_active_kb_jobs_for_group, serialize_job
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups', methods=['GET'])
|
||||
def list_groups():
|
||||
require_user()
|
||||
document_counts = (
|
||||
db.session.query(KbDocument.group_id.label('group_id'), func.count(KbDocument.id).label('document_count'))
|
||||
.filter(KbDocument.is_deleted.is_(False))
|
||||
.group_by(KbDocument.group_id)
|
||||
.subquery()
|
||||
)
|
||||
rows = run_db_read(
|
||||
'list_groups',
|
||||
lambda: db.session.query(KbGroup, func.coalesce(document_counts.c.document_count, 0).label('document_count'))
|
||||
.outerjoin(document_counts, document_counts.c.group_id == KbGroup.id)
|
||||
.filter(KbGroup.is_active.is_(True))
|
||||
.order_by(KbGroup.updated_at.desc(), KbGroup.id.desc())
|
||||
.all(),
|
||||
)
|
||||
return jsonify([serialize_group(group, document_count) for group, document_count in rows])
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups', methods=['POST'])
|
||||
@require_admin
|
||||
def create_group():
|
||||
data = request.get_json(silent=True) or {}
|
||||
name = str(data.get('name') or '').strip()
|
||||
description = str(data.get('description') or '').strip() or None
|
||||
department_id = data.get('department_id')
|
||||
if not name:
|
||||
raise ValidationError('name is required')
|
||||
existing_query = db.session.query(KbGroup).filter(KbGroup.name == name, KbGroup.is_active.is_(True))
|
||||
if department_id is None:
|
||||
existing_query = existing_query.filter(KbGroup.department_id.is_(None))
|
||||
else:
|
||||
existing_query = existing_query.filter(KbGroup.department_id == department_id)
|
||||
if existing_query.first():
|
||||
raise ValidationError('知识库分组已存在')
|
||||
current_user = get_current_user()
|
||||
group = KbGroup(
|
||||
name=name,
|
||||
description=description,
|
||||
department_id=department_id,
|
||||
created_by_id=getattr(current_user, 'id', None),
|
||||
updated_by_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.add(group)
|
||||
db.session.commit()
|
||||
return jsonify(serialize_group(group, 0)), 201
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups/<int:group_id>', methods=['PATCH'])
|
||||
@require_admin
|
||||
def update_group(group_id: int):
|
||||
group = db.session.get(KbGroup, group_id)
|
||||
if not group or not group.is_active:
|
||||
raise NotFoundError('知识库分组不存在')
|
||||
data = request.get_json(silent=True) or {}
|
||||
name = str(data.get('name') or group.name).strip()
|
||||
description = data.get('description')
|
||||
department_id = data.get('department_id', group.department_id)
|
||||
if not name:
|
||||
raise ValidationError('name is required')
|
||||
existing_query = db.session.query(KbGroup).filter(
|
||||
KbGroup.id != group.id,
|
||||
KbGroup.name == name,
|
||||
KbGroup.is_active.is_(True),
|
||||
)
|
||||
if department_id is None:
|
||||
existing_query = existing_query.filter(KbGroup.department_id.is_(None))
|
||||
else:
|
||||
existing_query = existing_query.filter(KbGroup.department_id == department_id)
|
||||
if existing_query.first():
|
||||
raise ValidationError('知识库分组已存在')
|
||||
current_user = get_current_user()
|
||||
group.name = name
|
||||
group.description = str(description).strip() or None if description is not None else None
|
||||
group.department_id = department_id
|
||||
group.updated_by_id = getattr(current_user, 'id', None)
|
||||
db.session.commit()
|
||||
document_count = db.session.query(func.count(KbDocument.id)).filter(
|
||||
KbDocument.group_id == group.id,
|
||||
KbDocument.is_deleted.is_(False),
|
||||
).scalar()
|
||||
return jsonify(serialize_group(group, document_count))
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups/<int:group_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_group(group_id: int):
|
||||
group = db.session.get(KbGroup, group_id)
|
||||
if not group or not group.is_active:
|
||||
raise NotFoundError('知识库分组不存在')
|
||||
current_user = get_current_user()
|
||||
group.is_active = False
|
||||
group.updated_by_id = getattr(current_user, 'id', None)
|
||||
cancel_active_kb_jobs_for_group(group.id, '知识库分组已删除,后台任务已取消')
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True, 'id': group_id})
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups/<int:group_id>/files', methods=['GET'])
|
||||
def list_group_files(group_id: int):
|
||||
require_user()
|
||||
group = run_db_read('get_group_for_files', lambda: db.session.get(KbGroup, group_id))
|
||||
if not group or not group.is_active:
|
||||
raise NotFoundError('Knowledge base group not found')
|
||||
documents = run_db_read(
|
||||
'list_group_files',
|
||||
lambda: db.session.query(KbDocument)
|
||||
.options(joinedload(KbDocument.versions))
|
||||
.filter(KbDocument.group_id == group_id, KbDocument.is_deleted.is_(False))
|
||||
.order_by(KbDocument.updated_at.desc(), KbDocument.id.desc())
|
||||
.all(),
|
||||
)
|
||||
return jsonify([serialize_document(doc) for doc in documents])
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups/<int:group_id>/files', methods=['POST'])
|
||||
def create_group_file(group_id: int):
|
||||
current_user = require_user()
|
||||
path_upload_service.require_active_group(group_id)
|
||||
data = request.get_json(silent=True) or {}
|
||||
title = str(data.get('title') or '').strip()
|
||||
description = str(data.get('description') or '').strip() or None
|
||||
status = str(data.get('status') or 'draft').strip() or 'draft'
|
||||
if not title:
|
||||
raise ValidationError('title is required')
|
||||
existing = (
|
||||
db.session.query(KbDocument)
|
||||
.options(joinedload(KbDocument.versions))
|
||||
.filter(KbDocument.group_id == group_id, KbDocument.title == title)
|
||||
.first()
|
||||
)
|
||||
if existing and not existing.is_deleted:
|
||||
raise ValidationError('当前分组下已存在同名文档')
|
||||
if existing and existing.is_deleted:
|
||||
existing.is_deleted = False
|
||||
existing.description = description
|
||||
existing.status = status
|
||||
existing.updated_by_id = getattr(current_user, 'id', None)
|
||||
db.session.commit()
|
||||
return jsonify(serialize_document(existing)), 201
|
||||
document = KbDocument(
|
||||
group_id=group_id,
|
||||
title=title,
|
||||
description=description,
|
||||
status=status,
|
||||
source_type='manual',
|
||||
created_by_id=getattr(current_user, 'id', None),
|
||||
updated_by_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.commit()
|
||||
return jsonify(serialize_document(document)), 201
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups/<int:group_id>/path-upload-jobs', methods=['POST'])
|
||||
def create_path_upload_job(group_id: int):
|
||||
current_user = require_user()
|
||||
path_upload_service.require_active_group(group_id)
|
||||
job, reused = path_upload_service.create_path_upload_job(
|
||||
group_id,
|
||||
request.get_json(silent=True) or {},
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
payload = serialize_job(job)
|
||||
if reused:
|
||||
payload['reused_existing'] = True
|
||||
payload['message'] = payload.get('message') or '检测到未完成的路径上传任务,已自动续传'
|
||||
return jsonify(payload)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/files', methods=['POST'])
|
||||
def upload_path_job_file(job_id: int):
|
||||
current_user = require_user()
|
||||
job = path_upload_service.require_path_upload_job(job_id)
|
||||
try:
|
||||
job = path_upload_service.upload_path_job_file(
|
||||
job,
|
||||
file_storage=request.files.get('file'),
|
||||
relative_path_raw=request.form.get('relative_path'),
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc)) from exc
|
||||
db.session.commit()
|
||||
return jsonify(serialize_job(job)), 201
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/files/fail', methods=['POST'])
|
||||
def mark_path_job_file_failed(job_id: int):
|
||||
require_user()
|
||||
job = path_upload_service.require_path_upload_job(job_id)
|
||||
data = request.get_json(silent=True) or {}
|
||||
original_name = str(data.get('original_name') or '').strip() or None
|
||||
relative_path_raw = str(data.get('relative_path') or '').strip()
|
||||
error_message = str(data.get('error') or '路径文件上传失败').strip() or '路径文件上传失败'
|
||||
try:
|
||||
job = path_upload_service.mark_path_job_file_failed(
|
||||
job,
|
||||
relative_path_raw=relative_path_raw,
|
||||
original_name=original_name,
|
||||
error_message=error_message,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc)) from exc
|
||||
db.session.commit()
|
||||
return jsonify(serialize_job(job))
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/finalize', methods=['POST'])
|
||||
def finalize_path_upload_job(job_id: int):
|
||||
current_user = require_user()
|
||||
job = path_upload_service.require_path_upload_job(job_id)
|
||||
job, status_code = path_upload_service.finalize_path_upload_job(
|
||||
job,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
refreshed = db.session.get(KbJob, job.id)
|
||||
response_payload = serialize_job(refreshed or job)
|
||||
if status_code == 202:
|
||||
response_payload['queue_result'] = 'inline_per_file'
|
||||
response_payload['accepted'] = True
|
||||
return jsonify(response_payload), status_code
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/files', methods=['DELETE'])
|
||||
def delete_path_job_file(job_id: int):
|
||||
current_user = require_user()
|
||||
job = path_upload_service.require_path_upload_job(job_id)
|
||||
relative_path_raw = str(request.args.get('relative_path') or '').strip()
|
||||
if not relative_path_raw:
|
||||
raise ValidationError('relative_path is required')
|
||||
try:
|
||||
job, document_deleted, relative_path = path_upload_service.delete_path_job_file(
|
||||
job,
|
||||
relative_path_raw=relative_path_raw,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc)) from exc
|
||||
db.session.commit()
|
||||
return jsonify({
|
||||
'ok': True,
|
||||
'job': serialize_job(job),
|
||||
'document_deleted': document_deleted,
|
||||
'relative_path': relative_path,
|
||||
})
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/retry-failed', methods=['POST'])
|
||||
def retry_failed_path_upload_job(job_id: int):
|
||||
current_user = require_user()
|
||||
source_job = path_upload_service.require_path_upload_job(job_id)
|
||||
data = request.get_json(silent=True) or {}
|
||||
requested_paths = data.get('relative_paths') or []
|
||||
if not isinstance(requested_paths, list):
|
||||
requested_paths = []
|
||||
retry_job = path_upload_service.retry_failed_path_upload_job(
|
||||
source_job,
|
||||
relative_paths=requested_paths,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
refreshed = db.session.get(KbJob, retry_job.id)
|
||||
return jsonify(serialize_job(refreshed or retry_job)), 201
|
||||
@@ -0,0 +1,97 @@
|
||||
"""
|
||||
backend/app/api/kb/jobs.py
|
||||
|
||||
用途:知识库后台任务 API(列表、手动触发);序列化/取消 helper 来自 services/kb/job_lifecycle。
|
||||
依赖:kb.blueprint、kb.common、app.jobs、services/kb/job_lifecycle。
|
||||
逻辑:注册 /jobs 路由。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import jsonify
|
||||
|
||||
from app import db
|
||||
from app.api.kb.blueprint import knowledge_base_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.jobs import enqueue_kb_job
|
||||
from app.models import KbDocumentVersion, KbJob
|
||||
from app.services.kb.job_lifecycle import serialize_job
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/jobs', methods=['GET'])
|
||||
def list_jobs():
|
||||
"""
|
||||
返回最近 50 条 KbJob(登录用户可见)。
|
||||
核心逻辑:只读查询,经 run_db_read 处理瞬态 DB 错误。
|
||||
"""
|
||||
from app.api.kb.common import require_user, run_db_read
|
||||
|
||||
require_user()
|
||||
jobs = run_db_read(
|
||||
'list_jobs',
|
||||
lambda: db.session.query(KbJob)
|
||||
.order_by(KbJob.created_at.desc(), KbJob.id.desc())
|
||||
.limit(50)
|
||||
.all(),
|
||||
)
|
||||
return jsonify([serialize_job(job) for job in jobs])
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/jobs/<int:job_id>/run', methods=['POST'])
|
||||
@require_admin
|
||||
def run_job(job_id: int):
|
||||
"""
|
||||
管理员手动将 clean/sync_dify 任务重新提交后台执行。
|
||||
核心逻辑:重置 queued 状态后 enqueue_kb_job;已在队列中则 202 返回 already_queued。
|
||||
"""
|
||||
job = db.session.get(KbJob, job_id)
|
||||
if not job:
|
||||
raise NotFoundError('任务不存在')
|
||||
|
||||
if job.job_type not in ('clean', 'sync_dify'):
|
||||
raise ValidationError('当前仅支持手动执行 clean 或 sync_dify 任务')
|
||||
|
||||
if job.status in ('queued', 'running'):
|
||||
refreshed = db.session.get(KbJob, job_id)
|
||||
payload = serialize_job(refreshed) if refreshed else {'id': job_id}
|
||||
payload['accepted'] = True
|
||||
payload['queue_result'] = 'already_queued'
|
||||
payload['run_result'] = '任务已在后台处理中'
|
||||
return jsonify(payload), 202
|
||||
|
||||
version = db.session.get(KbDocumentVersion, job.document_version_id) if job.document_version_id else None
|
||||
|
||||
if job.job_type == 'clean':
|
||||
if not version:
|
||||
raise NotFoundError('关联文档版本不存在')
|
||||
job.status = 'queued'
|
||||
job.progress = 0
|
||||
job.started_at = None
|
||||
job.finished_at = None
|
||||
job.error_message = None
|
||||
job.message = '等待清洗任务执行'
|
||||
version.status = 'uploaded'
|
||||
version.error_message = None
|
||||
if version.document:
|
||||
version.document.status = 'uploaded'
|
||||
else:
|
||||
if not version:
|
||||
raise NotFoundError('关联文档版本不存在')
|
||||
job.status = 'queued'
|
||||
job.progress = 0
|
||||
job.started_at = None
|
||||
job.finished_at = None
|
||||
job.error_message = None
|
||||
job.message = '等待同步到 Dify'
|
||||
if version.status in ('failed', 'ready', 'synced'):
|
||||
version.error_message = None
|
||||
|
||||
db.session.commit()
|
||||
|
||||
_enqueued, queue_result = enqueue_kb_job(job.id)
|
||||
refreshed = db.session.get(KbJob, job_id)
|
||||
payload = serialize_job(refreshed) if refreshed else {'id': job_id}
|
||||
payload['accepted'] = True
|
||||
payload['queue_result'] = queue_result
|
||||
payload['run_result'] = '任务已提交后台异步执行'
|
||||
return jsonify(payload), 202
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,231 @@
|
||||
"""
|
||||
backend/app/api/maintenance.py
|
||||
|
||||
用途:设备维保助手 HTTP API,当前提供设备台账配置与 Excel 导入能力。
|
||||
依赖:JWT 当前用户、maintenance_ledger_service、Flask Blueprint/send_file。
|
||||
逻辑:查询接口面向会话与面板复用;写入/导入接口先做角色校验,再委托 service。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
|
||||
from flask import Blueprint, g, jsonify, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, UnauthorizedError, ValidationError
|
||||
from app.services.maintenance_ledger_service import (
|
||||
build_import_template,
|
||||
create_device,
|
||||
get_device,
|
||||
import_devices_from_excel,
|
||||
list_devices,
|
||||
update_device,
|
||||
_parse_date,
|
||||
)
|
||||
from app.services.maintenance_record_service import (
|
||||
build_records_import_template,
|
||||
build_records_export,
|
||||
create_record,
|
||||
delete_record,
|
||||
get_record,
|
||||
import_records_from_excel,
|
||||
list_records,
|
||||
update_record,
|
||||
)
|
||||
|
||||
maintenance_bp = Blueprint('maintenance', __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""确保当前请求存在登录用户。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _require_ledger_admin():
|
||||
"""
|
||||
校验设备维保管理权限。
|
||||
Returns:
|
||||
当前用户对象。
|
||||
Raises:
|
||||
ForbiddenError: 当前角色不允许写入台账或维修记录。
|
||||
"""
|
||||
user = _require_user()
|
||||
if getattr(user, 'role', None) not in {'admin', 'maintenance_manager'}:
|
||||
raise ForbiddenError('Maintenance manager privilege required')
|
||||
return user
|
||||
|
||||
|
||||
def _record_list_filters_from_request() -> dict[str, Any]:
|
||||
"""
|
||||
从请求参数解析维修记录列表/导出共用的筛选条件。
|
||||
核心逻辑:兼容 snake_case 与 camelCase 报修日期参数;日期非法时抛出 ValidationError。
|
||||
"""
|
||||
report_date_from = _parse_date(
|
||||
request.args.get('report_date_from') or request.args.get('reportDateFrom'),
|
||||
'reportDateFrom',
|
||||
)
|
||||
report_date_to = _parse_date(
|
||||
request.args.get('report_date_to') or request.args.get('reportDateTo'),
|
||||
'reportDateTo',
|
||||
)
|
||||
return {
|
||||
'keyword': request.args.get('keyword'),
|
||||
'device_code': request.args.get('device_code') or request.args.get('deviceCode'),
|
||||
'status': request.args.get('status'),
|
||||
'report_date_from': report_date_from,
|
||||
'report_date_to': report_date_to,
|
||||
}
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/devices', methods=['GET'])
|
||||
def list_ledger_devices():
|
||||
"""查询设备台账列表,供 Agent 查询结果与右侧台账配置面板使用。"""
|
||||
_require_user()
|
||||
result = list_devices(
|
||||
keyword=request.args.get('keyword'),
|
||||
status=request.args.get('status'),
|
||||
page=request.args.get('page', type=int) or 1,
|
||||
page_size=request.args.get('page_size', type=int) or 20,
|
||||
)
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/devices/<int:device_id>', methods=['GET'])
|
||||
def get_ledger_device(device_id: int):
|
||||
"""读取设备台账详情。"""
|
||||
_require_user()
|
||||
return jsonify(get_device(device_id))
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/devices', methods=['POST'])
|
||||
def create_ledger_device():
|
||||
"""新增设备台账,仅固定管理角色可用。"""
|
||||
user = _require_ledger_admin()
|
||||
payload = request.get_json() or {}
|
||||
return jsonify(create_device(payload, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/devices/<int:device_id>', methods=['PUT'])
|
||||
def update_ledger_device(device_id: int):
|
||||
"""更新设备台账,仅固定管理角色可用。"""
|
||||
user = _require_ledger_admin()
|
||||
payload = request.get_json() or {}
|
||||
return jsonify(update_device(device_id, payload, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/import-template', methods=['GET'])
|
||||
def download_ledger_import_template():
|
||||
"""下载设备台账 Excel 导入模板。"""
|
||||
_require_ledger_admin()
|
||||
return send_file(
|
||||
BytesIO(build_import_template()),
|
||||
as_attachment=True,
|
||||
download_name='maintenance_devices_import_template.xlsx',
|
||||
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
)
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/import', methods=['POST'])
|
||||
def import_ledger_devices():
|
||||
"""上传 Excel 模板并批量新增/更新设备台账。"""
|
||||
user = _require_ledger_admin()
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
raise ValidationError('file is required')
|
||||
result = import_devices_from_excel(upload, operator=user, request_id=getattr(g, 'request_id', None))
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@maintenance_bp.route('/records', methods=['GET'])
|
||||
def list_maintenance_records():
|
||||
"""查询设备维修记录,供 Agent 会话查询和结果卡片使用。"""
|
||||
_require_user()
|
||||
filters = _record_list_filters_from_request()
|
||||
result = list_records(
|
||||
keyword=filters['keyword'],
|
||||
device_code=filters['device_code'],
|
||||
status=filters['status'],
|
||||
report_date_from=filters['report_date_from'],
|
||||
report_date_to=filters['report_date_to'],
|
||||
page=request.args.get('page', type=int) or 1,
|
||||
page_size=request.args.get('page_size', type=int) or 20,
|
||||
)
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/<int:record_id>', methods=['GET'])
|
||||
def get_maintenance_record(record_id: int):
|
||||
"""读取设备维修记录详情。"""
|
||||
_require_user()
|
||||
return jsonify(get_record(record_id))
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/export', methods=['GET'])
|
||||
def export_maintenance_records():
|
||||
"""按当前筛选条件导出设备维修记录 Excel。"""
|
||||
_require_ledger_admin()
|
||||
filters = _record_list_filters_from_request()
|
||||
data = build_records_export(
|
||||
keyword=filters['keyword'],
|
||||
device_code=filters['device_code'],
|
||||
status=filters['status'],
|
||||
report_date_from=filters['report_date_from'],
|
||||
report_date_to=filters['report_date_to'],
|
||||
)
|
||||
return send_file(
|
||||
BytesIO(data),
|
||||
as_attachment=True,
|
||||
download_name='maintenance_records.xlsx',
|
||||
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
)
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/import-template', methods=['GET'])
|
||||
def download_records_import_template():
|
||||
"""下载维修记录 Excel 导入模板。"""
|
||||
_require_ledger_admin()
|
||||
return send_file(
|
||||
BytesIO(build_records_import_template()),
|
||||
as_attachment=True,
|
||||
download_name='maintenance_record_history_template.xls',
|
||||
mimetype='application/vnd.ms-excel',
|
||||
)
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/import', methods=['POST'])
|
||||
def import_maintenance_records():
|
||||
"""上传 Excel 模板并批量新增维修记录。"""
|
||||
user = _require_ledger_admin()
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
raise ValidationError('file is required')
|
||||
result = import_records_from_excel(upload, operator=user, request_id=getattr(g, 'request_id', None))
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@maintenance_bp.route('/records', methods=['POST'])
|
||||
def create_maintenance_record():
|
||||
"""新增设备维修记录,仅固定管理角色可用。"""
|
||||
user = _require_ledger_admin()
|
||||
payload = request.get_json() or {}
|
||||
return jsonify(create_record(payload, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/<int:record_id>', methods=['PUT'])
|
||||
def update_maintenance_record(record_id: int):
|
||||
"""更新设备维修记录,仅固定管理角色可用。"""
|
||||
user = _require_ledger_admin()
|
||||
payload = request.get_json() or {}
|
||||
return jsonify(update_record(record_id, payload, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/<int:record_id>', methods=['DELETE'])
|
||||
def delete_maintenance_record(record_id: int):
|
||||
"""删除设备维修记录,仅固定管理角色可用。"""
|
||||
user = _require_ledger_admin()
|
||||
return jsonify(delete_record(record_id, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||
@@ -0,0 +1,149 @@
|
||||
"""
|
||||
backend/app/api/maintenance_tools.py
|
||||
|
||||
用途:设备维保助手 Dify Tool API,只开放只读查询工具。
|
||||
依赖:maintenance_chat_service、maintenance_record_service、OpenAPI 构建、Tool API 基地址解析。
|
||||
逻辑:Dify 复杂问法调用本蓝图查询设备台账/维修记录;明确查询仍由 chat.py 本地直答,写操作仍走 HXOPS 管理面板。
|
||||
"""
|
||||
|
||||
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,17 @@
|
||||
"""
|
||||
backend/app/api/schedule/__init__.py
|
||||
|
||||
用途:排程管理 Blueprint 入口(Wave 3 分包)。
|
||||
依赖:schedule/blueprint.py、config、tasks、runs、platform_tasks。
|
||||
逻辑:import 子模块注册路由;register_blueprints 从本包 import schedule_admin_bp。
|
||||
"""
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
|
||||
import app.api.schedule.common # noqa: F401
|
||||
import app.api.schedule.config # noqa: F401
|
||||
import app.api.schedule.tasks # noqa: F401
|
||||
import app.api.schedule.runs # noqa: F401
|
||||
import app.api.schedule.platform_tasks # noqa: F401
|
||||
import app.api.schedule.rpa_workers # noqa: F401
|
||||
|
||||
__all__ = ['schedule_admin_bp']
|
||||
@@ -0,0 +1,10 @@
|
||||
"""
|
||||
backend/app/api/schedule/blueprint.py
|
||||
|
||||
用途:排程管理 API 共享 Blueprint(Wave 3 分包后各子模块共用)。
|
||||
依赖:Flask Blueprint。
|
||||
逻辑:config/tasks/runs 子模块在此 bp 上注册路由;__init__ 导出 schedule_admin_bp。
|
||||
"""
|
||||
from flask import Blueprint
|
||||
|
||||
schedule_admin_bp = Blueprint('schedule_admin', __name__)
|
||||
@@ -0,0 +1,59 @@
|
||||
"""
|
||||
backend/app/api/schedule/common.py
|
||||
|
||||
用途:排程 API 共享序列化 helper。
|
||||
依赖:models、services/schedule/query_service。
|
||||
逻辑:config/tasks 子模块导出任务配置 JSON 时共用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.models import ScheduleTask, ScheduleTaskConfig
|
||||
from app.services.schedule.query_service import serialize_task
|
||||
from app.services.schedule.serialization import safe_json_value
|
||||
|
||||
|
||||
def serialize_task_config(cfg_model: ScheduleTaskConfig) -> dict:
|
||||
"""
|
||||
将 ScheduleTaskConfig ORM 转为 API 响应 dict。
|
||||
核心逻辑:扁平化 data_source / external_api 嵌套结构。
|
||||
"""
|
||||
return {
|
||||
'row_id_key': cfg_model.row_id_key or 'id',
|
||||
'log_prefix': cfg_model.log_prefix or '',
|
||||
'base_fetch_sql': cfg_model.base_fetch_sql or '',
|
||||
'fetch_where_conditions': cfg_model.fetch_where_conditions or '',
|
||||
'fetch_order_by': cfg_model.fetch_order_by or '',
|
||||
'writeback_sql': cfg_model.writeback_sql or '',
|
||||
'detail_sql': cfg_model.detail_sql or '',
|
||||
'alias_order': cfg_model.alias_order or [],
|
||||
'detail_alias_order': cfg_model.detail_alias_order or [],
|
||||
'header_labels': cfg_model.header_labels or {},
|
||||
'data_source': {
|
||||
'db_type': cfg_model.ds_db_type or 'sqlserver',
|
||||
'host': cfg_model.ds_host or '',
|
||||
'port': cfg_model.ds_port or '',
|
||||
'database': cfg_model.ds_database or '',
|
||||
'username': cfg_model.ds_username or '',
|
||||
'password': cfg_model.ds_password or '',
|
||||
'driver': cfg_model.ds_driver or '',
|
||||
'encrypt': cfg_model.ds_encrypt or '',
|
||||
'trust_cert': cfg_model.ds_trust_cert or '',
|
||||
},
|
||||
'external_api': {
|
||||
'url': cfg_model.api_url or '',
|
||||
'method': cfg_model.api_method or 'POST',
|
||||
'headers': cfg_model.api_headers or {},
|
||||
'body_template': cfg_model.api_body_template or '',
|
||||
},
|
||||
'dify_system_prompt': cfg_model.dify_system_prompt or '',
|
||||
}
|
||||
|
||||
|
||||
def serialize_task_for_export(task: ScheduleTask, cfg_model: ScheduleTaskConfig | None) -> dict:
|
||||
"""组装单条排程导出 JSON(含 config 快照)。"""
|
||||
payload = serialize_task(task)
|
||||
payload['config'] = serialize_task_config(cfg_model) if cfg_model else None
|
||||
return payload
|
||||
|
||||
|
||||
__all__ = ['safe_json_value', 'serialize_task_config', 'serialize_task_for_export']
|
||||
@@ -0,0 +1,111 @@
|
||||
"""
|
||||
backend/app/api/schedule/config.py
|
||||
|
||||
用途:排程任务 SQL/数据源配置 API 与测试接口(薄路由层)。
|
||||
依赖:schedule.blueprint、schedule.common、schedule_contract、services/schedule/*。
|
||||
逻辑:/schedule-config/* 路由;配置更新仅允许 data_pipeline 任务修改 data_source_type。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
from app.api.schedule.common import serialize_task_config
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import ScheduleTask, ScheduleTaskConfig
|
||||
from app.services.schedule.schedule_contract import (
|
||||
SCHEDULE_TYPE_DATA_PIPELINE,
|
||||
apply_schedule_contract_to_payload,
|
||||
platform_job_allows_config,
|
||||
)
|
||||
from app.services.schedule.sql_config import upsert_schedule_task_config
|
||||
from app.services.schedule.sql_preview_service import preview_fetch_sql
|
||||
from app.services.schedule.test_run_service import execute_test_run
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_task_config(task_id: int):
|
||||
"""返回排程任务关联的 SQL/数据源配置。"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if not cfg_model:
|
||||
return jsonify({'data_source_type': task.data_source_type, 'config': None})
|
||||
return jsonify({'data_source_type': task.data_source_type, 'config': serialize_task_config(cfg_model)})
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_schedule_task_config(task_id: int):
|
||||
"""
|
||||
更新排程 data_source_type 与 ScheduleTaskConfig。
|
||||
核心逻辑:仅 data_pipeline 允许改 data_source_type;platform_job 禁止经此接口绕过契约。
|
||||
"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
if task.schedule_type != SCHEDULE_TYPE_DATA_PIPELINE:
|
||||
if 'data_source_type' in data:
|
||||
raise ValidationError(
|
||||
'data_source_type can only be updated for data_pipeline schedules; '
|
||||
'use schedule task PATCH for platform_job'
|
||||
)
|
||||
elif 'data_source_type' in data:
|
||||
contract = apply_schedule_contract_to_payload({
|
||||
'schedule_type': task.schedule_type,
|
||||
'data_source_type': data.get('data_source_type'),
|
||||
'platform_api_path': task.platform_api_path,
|
||||
})
|
||||
task.data_source_type = contract['data_source_type']
|
||||
|
||||
config_data = data.get('config', data)
|
||||
if isinstance(config_data, dict) and config_data:
|
||||
# platform_job 仅白名单且 enabled 的任务(如 shipping-inventory-rpa)允许写 ScheduleTaskConfig
|
||||
if task.schedule_type != SCHEDULE_TYPE_DATA_PIPELINE and not platform_job_allows_config(task.platform_api_path):
|
||||
raise ValidationError(
|
||||
f"platform_job '{task.platform_api_path}' does not accept ScheduleTaskConfig"
|
||||
)
|
||||
upsert_schedule_task_config(task_id, config_data, commit=False)
|
||||
db.session.commit()
|
||||
cfg_model = task.config
|
||||
if cfg_model is None:
|
||||
with db.session.no_autoflush:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
return jsonify({
|
||||
'data_source_type': task.data_source_type,
|
||||
'config': serialize_task_config(cfg_model) if cfg_model else None,
|
||||
})
|
||||
except ValidationError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ValidationError(str(exc))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-sql', methods=['POST'])
|
||||
@require_admin
|
||||
def test_schedule_sql(task_id: int):
|
||||
"""预览抓取 SQL 执行结果(最多 100 行)。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return jsonify(preview_fetch_sql(task_id, data))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-run', methods=['POST'])
|
||||
@require_admin
|
||||
def test_schedule_run(task_id: int):
|
||||
"""同步执行小规模排程测试跑(默认 3 条),可选 KB 同步。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = execute_test_run(
|
||||
task_id,
|
||||
data,
|
||||
triggered_by_user_id=getattr(get_current_user(), 'id', None),
|
||||
)
|
||||
return jsonify(payload)
|
||||
@@ -0,0 +1,59 @@
|
||||
"""
|
||||
backend/app/api/schedule/platform_tasks.py
|
||||
|
||||
用途:平台任务契约 API(任务定义 + 动态选项),供前端 DynamicTaskParamsForm 通用渲染。
|
||||
依赖:schedule.blueprint、job_registry(任务契约中心)、job_options(options_source 分发)。
|
||||
逻辑:/platform-tasks/definitions 下发 params_schema(仅 enabled);/platform-tasks/options 按 source 返回统一选项;
|
||||
前端不再按任务硬编码 UI,红框参数区完全由 schema 决定。
|
||||
"""
|
||||
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.errors import ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.schedule.job_options import list_job_options
|
||||
from app.services.schedule.job_registry import list_platform_jobs
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/platform-tasks/definitions', methods=['GET'])
|
||||
@require_admin
|
||||
def get_platform_task_definitions():
|
||||
"""
|
||||
返回全部启用平台任务的完整契约(展示信息 + params_schema + defaults)。
|
||||
核心逻辑:直接序列化 job_registry 注册项;前端选择任务后按 params_schema 渲染参数表单。
|
||||
"""
|
||||
return ok([
|
||||
{
|
||||
'task_type': job.key,
|
||||
'label': job.label,
|
||||
'label_key': job.label_key or None,
|
||||
'description': job.description,
|
||||
'description_key': job.description_key or None,
|
||||
'category': job.category,
|
||||
'enabled': job.enabled,
|
||||
'params_schema': list(job.params_schema),
|
||||
'defaults': job.defaults,
|
||||
}
|
||||
for job in list_platform_jobs()
|
||||
if job.enabled
|
||||
])
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/platform-tasks/options', methods=['GET'])
|
||||
@require_admin
|
||||
def get_platform_task_options():
|
||||
"""
|
||||
按 options_source 返回动态选项(统一 {label, value, description?})。
|
||||
核心逻辑:source 参数分发到 job_options 登记的 provider;前端不感知数据来源。
|
||||
"""
|
||||
source = str(request.args.get('source') or '').strip()
|
||||
if not source:
|
||||
raise ValidationError('source is required')
|
||||
try:
|
||||
options = list_job_options(source)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc))
|
||||
return ok(options)
|
||||
@@ -0,0 +1,24 @@
|
||||
"""
|
||||
backend/app/api/schedule/rpa_workers.py
|
||||
|
||||
用途:管理端查询货代库存 RPA Worker 在线状态与就绪摘要。
|
||||
依赖:schedule.blueprint、rpa_worker_heartbeat.serialize_rpa_worker_status。
|
||||
逻辑:ScheduleWorkbenchPanel 在库存 RPA 排程工作台展示 worker 心跳状态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.response import ok
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import serialize_rpa_worker_status
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/rpa-workers/status', methods=['GET'])
|
||||
@require_admin
|
||||
def get_rpa_workers_status():
|
||||
"""
|
||||
返回库存 RPA Worker 心跳摘要(在线/离线、最后心跳时间、就绪原因)。
|
||||
核心逻辑:读取 Redis/内存心跳并与当前环境、trigger 目录比对。
|
||||
"""
|
||||
return ok(serialize_rpa_worker_status())
|
||||
@@ -0,0 +1,158 @@
|
||||
"""
|
||||
backend/app/api/schedule/runs.py
|
||||
|
||||
用途:排程运行触发与运行记录查询 API。
|
||||
依赖:schedule.blueprint、services/schedule/query_service、scheduler_service。
|
||||
逻辑:/schedules/<id>/run、/schedules/<id>/runs、/schedule-runs/* 路由。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from io import BytesIO
|
||||
|
||||
from flask import current_app, jsonify, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import ConflictError, NotFoundError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.schedule.query_service import get_run, list_runs, serialize_run
|
||||
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import recover_stale_awaiting_rpa_schedule_runs
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
|
||||
@require_admin
|
||||
def run_schedule(task_id: int):
|
||||
"""
|
||||
手动触发排程后台执行。
|
||||
核心逻辑:创建 running ScheduleRun → 守护线程内 run_task_now。
|
||||
"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
recover_stale_awaiting_rpa_schedule_runs(task)
|
||||
user = get_current_user()
|
||||
existing = (
|
||||
db.session.query(ScheduleRun)
|
||||
.filter(ScheduleRun.schedule_task_id == task.id, ScheduleRun.status == 'running')
|
||||
.first()
|
||||
)
|
||||
if existing:
|
||||
raise ConflictError('该排程正在执行中,请等待完成后再试', details={'run_id': existing.id})
|
||||
run = ScheduleRun(
|
||||
run_no=_generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
trigger_type='manual',
|
||||
triggered_by_user_id=getattr(user, 'id', None),
|
||||
started_at=datetime.utcnow(),
|
||||
status='running',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
app = current_app._get_current_object()
|
||||
run_id = run.id
|
||||
|
||||
def _background():
|
||||
with app.app_context():
|
||||
t = db.session.get(ScheduleTask, task_id)
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if not t or not r:
|
||||
return
|
||||
try:
|
||||
run_task_now(t, trigger_type='manual', triggered_by_user_id=r.triggered_by_user_id, run=r)
|
||||
except Exception as exc:
|
||||
try:
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if r and r.status == 'running':
|
||||
r.status = 'failed'
|
||||
r.error_message = str(exc)
|
||||
r.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
current_app.logger.error('[schedule-run] run_id=%s failed: %s', run_id, exc, exc_info=True)
|
||||
|
||||
t = threading.Thread(target=_background, daemon=True, name=f'schedule-run-{run_id}')
|
||||
t.start()
|
||||
fresh = db.session.get(ScheduleRun, run_id)
|
||||
return jsonify(serialize_run(fresh))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/runs', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_runs(task_id: int):
|
||||
"""按任务 ID 分页/过滤返回运行记录。"""
|
||||
status = str(request.args.get('status') or '').strip() or None
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
started_after = None
|
||||
started_before = None
|
||||
sa = request.args.get('started_after')
|
||||
sb = request.args.get('started_before')
|
||||
if sa:
|
||||
try:
|
||||
started_after = datetime.fromisoformat(sa.replace('Z', '+00:00'))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
if sb:
|
||||
try:
|
||||
started_before = datetime.fromisoformat(sb.replace('Z', '+00:00'))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
return jsonify(
|
||||
list_runs(
|
||||
task_id=task_id,
|
||||
status=status,
|
||||
started_after=started_after,
|
||||
started_before=started_before,
|
||||
limit=limit,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_run(run_id: int):
|
||||
"""返回单条运行记录详情。"""
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(serialize_run(run))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_run_excel(run_id: int):
|
||||
"""下载运行结果 Excel 附件。"""
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError('Excel not found')
|
||||
buf = BytesIO(run.excel_file_data)
|
||||
return send_file(
|
||||
buf,
|
||||
as_attachment=True,
|
||||
download_name=run.excel_file_name or 'result.xlsx',
|
||||
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
)
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/inventory-raw-zip', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_run_inventory_raw_zip(run_id: int):
|
||||
"""下载库存 RPA 排程 run 的原始库存 Excel 打包(ZIP + manifest)。"""
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
zip_path, file_name = resolve_inventory_raw_zip_download(run)
|
||||
return send_file(
|
||||
zip_path,
|
||||
as_attachment=True,
|
||||
download_name=file_name,
|
||||
mimetype='application/zip',
|
||||
)
|
||||
@@ -0,0 +1,282 @@
|
||||
"""
|
||||
backend/app/api/schedule/tasks.py
|
||||
|
||||
用途:排程任务 CRUD、导入导出、启用/禁用 API。
|
||||
依赖:schedule.blueprint、schedule.common、services/schedule/*。
|
||||
逻辑:/schedules* 路由(不含 run 触发与运行记录);job_params 归一化与切换重置
|
||||
由 scheduler_service.create_task/update_task 唯一兜底;本层只做请求校验与
|
||||
ValueError→ValidationError 映射。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Response, jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
from app.api.schedule.common import serialize_task_for_export
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig
|
||||
from app.services.schedule.query_service import list_tasks, serialize_task
|
||||
from app.services.schedule.import_service import import_schedules_from_payload
|
||||
from app.services.schedule.schedule_contract import (
|
||||
apply_schedule_contract_to_payload,
|
||||
assert_schedule_config_writable,
|
||||
)
|
||||
from app.services.schedule.scheduler_service import create_task, update_task
|
||||
from app.services.schedule.sql_config import upsert_schedule_task_config
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedules():
|
||||
"""返回全部排程任务列表。"""
|
||||
return jsonify(list_tasks())
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule/platform-jobs', methods=['GET'])
|
||||
@require_admin
|
||||
def get_platform_jobs():
|
||||
"""
|
||||
返回 Job Registry 已启用平台任务列表,供前端下拉动态加载。
|
||||
与 /platform-tasks/definitions 一致:只返回 enabled=True,避免下拉可选却无参数定义。
|
||||
"""
|
||||
from app.services.schedule.job_registry import list_platform_jobs
|
||||
|
||||
return jsonify([
|
||||
{
|
||||
'key': job.key,
|
||||
'label_key': job.label_key or None,
|
||||
'label': job.label,
|
||||
'description': job.description,
|
||||
'enabled': job.enabled,
|
||||
}
|
||||
for job in list_platform_jobs()
|
||||
if job.enabled
|
||||
])
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/export', methods=['GET'])
|
||||
@require_admin
|
||||
def export_schedule(task_id: int):
|
||||
"""导出单条排程任务及配置为 JSON 文件。"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
payload = {
|
||||
'schema_version': 1,
|
||||
'exported_at': datetime.utcnow().isoformat(),
|
||||
'schedules': [serialize_task_for_export(task, cfg_model)],
|
||||
}
|
||||
body = json.dumps(payload, ensure_ascii=False, indent=2)
|
||||
filename = f"{task.schedule_no or f'schedule_{task.id}'}_export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
|
||||
return Response(
|
||||
body,
|
||||
mimetype='application/json; charset=utf-8',
|
||||
headers={'Content-Disposition': f'attachment; filename="{filename}"'},
|
||||
)
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/import', methods=['POST'])
|
||||
@require_admin
|
||||
def import_schedules():
|
||||
"""批量导入排程 JSON(按 schedule_no upsert)。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
user = get_current_user()
|
||||
result = import_schedules_from_payload(
|
||||
data.get('schedules'),
|
||||
actor_id=getattr(user, 'id', None),
|
||||
)
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules', methods=['POST'])
|
||||
@require_admin
|
||||
def post_schedule():
|
||||
"""创建排程任务。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
user = get_current_user()
|
||||
schedule_type = str(data.get('schedule_type') or 'data_pipeline')
|
||||
data_source_type = data.get('data_source_type')
|
||||
platform_api_path = data.get('platform_api_path')
|
||||
config_data = data.get('config')
|
||||
if config_data is not None and not isinstance(config_data, dict):
|
||||
raise ValidationError('config must be a JSON object')
|
||||
if schedule_type.strip().lower() == 'data_pipeline' and data_source_type in (None, ''):
|
||||
data_source_type = 'database'
|
||||
try:
|
||||
# [STEP 1] 契约与 config 写入权限预校验(失败不落库);job_params 由 create_task 归一化
|
||||
contract = apply_schedule_contract_to_payload({
|
||||
'schedule_type': schedule_type,
|
||||
'data_source_type': data_source_type,
|
||||
'platform_api_path': platform_api_path,
|
||||
})
|
||||
assert_schedule_config_writable(
|
||||
schedule_type=contract['schedule_type'],
|
||||
platform_api_path=contract['platform_api_path'],
|
||||
config=config_data,
|
||||
)
|
||||
task = create_task(
|
||||
name=str(data.get('name') or '').strip(),
|
||||
schedule_type=schedule_type,
|
||||
owner_user_id=int(data.get('owner_user_id')),
|
||||
cron_expr=str(data.get('cron_expr') or '').strip(),
|
||||
schedule_timezone=data.get('schedule_timezone'),
|
||||
wait_seconds=int(data.get('wait_seconds') or 0),
|
||||
dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None,
|
||||
platform_api_path=str(platform_api_path).strip() if platform_api_path else None,
|
||||
data_source_type=str(data_source_type) if data_source_type is not None else None,
|
||||
job_params=data.get('job_params'),
|
||||
notify_user_ids_json=data.get('notify_user_ids_json')
|
||||
if isinstance(data.get('notify_user_ids_json'), list)
|
||||
else [],
|
||||
notify_enabled=bool(data.get('notify_enabled', True)),
|
||||
enabled=bool(data.get('enabled', True)),
|
||||
kb_sync_enabled=bool(data.get('kb_sync_enabled', False)),
|
||||
kb_group_id=int(data.get('kb_group_id')) if data.get('kb_group_id') not in (None, '', 0, '0') else None,
|
||||
actor_id=getattr(user, 'id', None),
|
||||
commit=not config_data,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc))
|
||||
if config_data:
|
||||
try:
|
||||
upsert_schedule_task_config(task.id, config_data, commit=False)
|
||||
if not task.dify_agent_id:
|
||||
cfg_model = task.config
|
||||
if cfg_model is None:
|
||||
with db.session.no_autoflush:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
|
||||
if cfg_model and cfg_model.dify_system_prompt:
|
||||
cfg_model.dify_system_prompt = None
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
raise
|
||||
db.session.refresh(task)
|
||||
return jsonify(serialize_task(task)), 201
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule(task_id: int):
|
||||
"""返回单条排程任务详情。"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['PATCH'])
|
||||
@require_admin
|
||||
def patch_schedule(task_id: int):
|
||||
"""更新排程任务字段与关联配置。"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
user = get_current_user()
|
||||
config_data = data.get('config')
|
||||
if config_data is not None and not isinstance(config_data, dict):
|
||||
raise ValidationError('config must be a JSON object')
|
||||
try:
|
||||
# [STEP 1] 契约与 config 预校验;job_params 重置/归一化由 update_task 唯一兜底
|
||||
contract = apply_schedule_contract_to_payload({
|
||||
'schedule_type': data.get('schedule_type', task.schedule_type),
|
||||
'data_source_type': data.get('data_source_type', task.data_source_type),
|
||||
'platform_api_path': data.get('platform_api_path', task.platform_api_path),
|
||||
})
|
||||
assert_schedule_config_writable(
|
||||
schedule_type=contract['schedule_type'],
|
||||
platform_api_path=contract['platform_api_path'],
|
||||
config=config_data,
|
||||
)
|
||||
task = update_task(
|
||||
task,
|
||||
payload=data,
|
||||
actor_id=getattr(user, 'id', None),
|
||||
commit=not config_data,
|
||||
)
|
||||
if config_data:
|
||||
upsert_schedule_task_config(task_id, config_data, commit=False)
|
||||
if not task.dify_agent_id:
|
||||
cfg_model = task.config
|
||||
if cfg_model is None:
|
||||
with db.session.no_autoflush:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if cfg_model and cfg_model.dify_system_prompt:
|
||||
cfg_model.dify_system_prompt = None
|
||||
if config_data:
|
||||
db.session.commit()
|
||||
except ValueError as exc:
|
||||
db.session.rollback()
|
||||
raise ValidationError(str(exc))
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
raise
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_schedule(task_id: int):
|
||||
"""删除排程任务及其运行记录;中断进行中的 run。"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.schedule.scheduler_service import request_cancel_run
|
||||
|
||||
running_runs = (
|
||||
db.session.query(ScheduleRun)
|
||||
.filter(ScheduleRun.schedule_task_id == task_id, ScheduleRun.status == 'running')
|
||||
.all()
|
||||
)
|
||||
for rr in running_runs:
|
||||
request_cancel_run(rr.id)
|
||||
rr.status = 'failed'
|
||||
rr.error_message = '排程已被删除,执行中断'
|
||||
rr.finished_at = datetime.utcnow()
|
||||
if running_runs:
|
||||
db.session.commit()
|
||||
db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False)
|
||||
db.session.delete(task)
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/enable', methods=['POST'])
|
||||
@require_admin
|
||||
def enable_schedule(task_id: int):
|
||||
"""
|
||||
启用排程并重新计算 next_run_at。
|
||||
核心逻辑:委托 enable_task 重新校验契约与 job_params,拒绝已停用 platform_job 重新入队。
|
||||
"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.schedule.scheduler_service import enable_task
|
||||
|
||||
try:
|
||||
task = enable_task(task)
|
||||
except ValueError as exc:
|
||||
db.session.rollback()
|
||||
raise ValidationError(str(exc)) from exc
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/disable', methods=['POST'])
|
||||
@require_admin
|
||||
def disable_schedule(task_id: int):
|
||||
"""禁用排程并清空 next_run_at。"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
task.enabled = False
|
||||
task.next_run_at = None
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
@@ -1,477 +1,10 @@
|
||||
from __future__ import annotations
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
from flask import Response
|
||||
from io import BytesIO
|
||||
import json
|
||||
from app.decorators import require_admin
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.services.schedule.query_service import get_run, list_runs, list_tasks, serialize_run, serialize_task
|
||||
from app.services.schedule.scheduler_service import create_task, run_task_now, update_task, _generate_run_no, _generate_test_run_no, _notify_schedule_run_wecom
|
||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id, upsert_schedule_task_config, _build_fetch_sql
|
||||
from app.services.schedule.srm_service import _fetch_records
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
schedule_admin_bp = Blueprint('schedule_admin', __name__)
|
||||
"""
|
||||
backend/app/api/schedule_admin.py
|
||||
|
||||
def _serialize_task_for_export(task: ScheduleTask, cfg_model: ScheduleTaskConfig | None) -> dict:
|
||||
payload = serialize_task(task)
|
||||
payload['config'] = _serialize_task_config(cfg_model) if cfg_model else None
|
||||
return payload
|
||||
用途:排程 API 兼容 shim(Wave 3 迁包过渡期)。
|
||||
依赖:app.api.schedule。
|
||||
逻辑:旧 import 路径仍可用;新代码请用 app.api.schedule。
|
||||
"""
|
||||
from app.api.schedule import schedule_admin_bp
|
||||
|
||||
def _serialize_task_config(cfg_model: ScheduleTaskConfig) -> dict:
|
||||
return {'row_id_key': cfg_model.row_id_key or 'id', 'log_prefix': cfg_model.log_prefix or '', 'base_fetch_sql': cfg_model.base_fetch_sql or '', 'fetch_where_conditions': cfg_model.fetch_where_conditions or '', 'fetch_order_by': cfg_model.fetch_order_by or '', 'writeback_sql': cfg_model.writeback_sql or '', 'detail_sql': cfg_model.detail_sql or '', 'alias_order': cfg_model.alias_order or [], 'detail_alias_order': cfg_model.detail_alias_order or [], 'header_labels': cfg_model.header_labels or {}, 'data_source': {'db_type': cfg_model.ds_db_type or 'sqlserver', 'host': cfg_model.ds_host or '', 'port': cfg_model.ds_port or '', 'database': cfg_model.ds_database or '', 'username': cfg_model.ds_username or '', 'password': cfg_model.ds_password or '', 'driver': cfg_model.ds_driver or '', 'encrypt': cfg_model.ds_encrypt or '', 'trust_cert': cfg_model.ds_trust_cert or ''}, 'external_api': {'url': cfg_model.api_url or '', 'method': cfg_model.api_method or 'POST', 'headers': cfg_model.api_headers or {}, 'body_template': cfg_model.api_body_template or ''}, 'dify_system_prompt': cfg_model.dify_system_prompt or ''}
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_task_config(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if not cfg_model:
|
||||
return jsonify({'data_source_type': task.data_source_type, 'config': None})
|
||||
return jsonify({'data_source_type': task.data_source_type, 'config': _serialize_task_config(cfg_model)})
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_schedule_task_config(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
if 'data_source_type' in data:
|
||||
task.data_source_type = str(data['data_source_type'])
|
||||
db.session.commit()
|
||||
config_data = data.get('config', data)
|
||||
cfg = upsert_schedule_task_config(task_id, config_data)
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
return jsonify({'data_source_type': task.data_source_type, 'config': _serialize_task_config(cfg_model) if cfg_model else None})
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
raise ValidationError(str(e))
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-sql', methods=['POST'])
|
||||
@require_admin
|
||||
def test_schedule_sql(task_id: int):
|
||||
cfg = get_schedule_sql_config_by_task_id(task_id)
|
||||
if not cfg:
|
||||
raise NotFoundError(f'Config for task {task_id} not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
custom_where = str(data.get('fetch_where_conditions') or cfg.fetch_where_conditions).strip()
|
||||
custom_order_by = str(data.get('fetch_order_by') or cfg.fetch_order_by).strip()
|
||||
limit = min(int(data.get('limit') or 10), 100)
|
||||
base = cfg.base_fetch_sql or cfg.fetch_sql
|
||||
if cfg.base_fetch_sql:
|
||||
sql = _build_fetch_sql(base, custom_where, custom_order_by)
|
||||
else:
|
||||
sql = base
|
||||
try:
|
||||
from app.services.schedule import _build_srm_conn_str
|
||||
import decimal, datetime
|
||||
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, sql)
|
||||
|
||||
def _safe(v):
|
||||
if isinstance(v, decimal.Decimal):
|
||||
return float(v)
|
||||
if isinstance(v, (datetime.date, datetime.datetime)):
|
||||
return v.isoformat()
|
||||
if isinstance(v, datetime.timedelta):
|
||||
return str(v)
|
||||
return v
|
||||
result_rows = [{k: _safe(v) for k, v in r.items()} for r in rows[:limit]]
|
||||
return jsonify({'total': len(rows), 'showing': len(result_rows), 'limit': limit, 'sql': sql, 'columns': list(result_rows[0].keys()) if result_rows else [], 'rows': result_rows})
|
||||
except Exception as e:
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message=str(e), http_status=400, details={'sql': sql})
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-run', methods=['POST'])
|
||||
@require_admin
|
||||
def test_schedule_run(task_id: int):
|
||||
import time as _time
|
||||
from app.services.schedule.excel_service import export_schedule_result_excel
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
cfg = get_schedule_sql_config_by_task_id(task_id)
|
||||
if not cfg:
|
||||
raise NotFoundError(f'Config for task {task_id} not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
custom_where = str(data.get('fetch_where_conditions') or cfg.fetch_where_conditions).strip()
|
||||
custom_order_by = str(data.get('fetch_order_by') or cfg.fetch_order_by).strip()
|
||||
limit = min(int(data.get('limit') or 3), 10)
|
||||
base = cfg.base_fetch_sql or cfg.fetch_sql
|
||||
if cfg.base_fetch_sql:
|
||||
test_sql = _build_fetch_sql(base, custom_where, custom_order_by)
|
||||
else:
|
||||
test_sql = base
|
||||
from app.services.schedule import _build_srm_conn_str, _resolve_dify_agent, _resolve_schedule_user
|
||||
from app.services.schedule.srm_service import _fetch_records, _run_check_job_loop, _build_record_text, _execute_writeback
|
||||
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()
|
||||
agent = _resolve_dify_agent(task) if task else None
|
||||
user = _resolve_schedule_user(task) if task else 'test_user'
|
||||
wait_seconds = task.wait_seconds if task else 120
|
||||
dify_agent_id = task.dify_agent_id if task else None
|
||||
run = ScheduleRun(run_no=_generate_test_run_no(), schedule_task_id=task_id, trigger_type='test', triggered_by_user_id=getattr(get_current_user(), 'id', None), started_at=datetime.utcnow(), status='running')
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||
capture_dify_execution_snapshot(run, task)
|
||||
db.session.commit()
|
||||
if not cfg.fetch_sql:
|
||||
run.status = 'success'
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.error_message = '无抓取SQL,跳过外部系统数据抓取'
|
||||
try:
|
||||
if task.notify_enabled:
|
||||
_notify_schedule_run_wecom(task, run)
|
||||
except Exception as wecom_exc:
|
||||
current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc)
|
||||
db.session.commit()
|
||||
return jsonify({'run_no': run.run_no, 'run_id': run.id, 'sql': '', 'limit': 0, 'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 0, 'details': [], 'errors': [], 'step_logs': [{'step': 'no_fetch_sql', 'status': 'skipped', 'detail': '无抓取SQL,跳过外部系统数据抓取'}], 'dify_agent_id': dify_agent_id})
|
||||
|
||||
def _test_fetch_fn(conn_str_arg):
|
||||
return _fetch_records(conn_str_arg, test_sql)
|
||||
|
||||
def _test_writeback_fn(conn_str_arg, *, row_id, run_no, dify_result, dify_message):
|
||||
_execute_writeback(conn_str_arg, cfg.writeback_sql, (run_no, dify_result, dify_message, str(row_id)))
|
||||
test_pre_dify = None
|
||||
test_build_record = None
|
||||
if cfg.detail_sql:
|
||||
|
||||
def _test_pre_dify(conn_str_arg, item, row_id_value):
|
||||
try:
|
||||
detail_rows = _fetch_records(conn_str_arg, cfg.detail_sql, params=(str(row_id_value),))
|
||||
except Exception as detail_exc:
|
||||
return {'dify_result': '人工判定', 'dify_message': f'查询成分明细失败:{detail_exc}', 'writeback_srm': False, 'writeback_err': str(detail_exc)}
|
||||
detail_lines = []
|
||||
for dr in detail_rows:
|
||||
parts = [f"{cfg.header_labels.get(dk, dk)}: {dr.get(dk, '')}" for dk in cfg.detail_alias_order]
|
||||
detail_lines.append(', '.join(parts))
|
||||
item['detail_text'] = '; '.join(detail_lines) if detail_lines else ''
|
||||
item['_detail_rows'] = detail_rows
|
||||
return None
|
||||
test_pre_dify = _test_pre_dify
|
||||
|
||||
def _test_build_with_detail(conn_str_arg, item, row_id_value):
|
||||
detail_rows = item.get('_detail_rows', [])
|
||||
text = _build_record_text(item, cfg.alias_order, cfg.header_labels, detail_rows, cfg.detail_alias_order)
|
||||
return (text, item.get('attachment'))
|
||||
test_build_record = _test_build_with_detail
|
||||
else:
|
||||
|
||||
def _test_build_simple(conn_str_arg, item, row_id_value):
|
||||
text = _build_record_text(item, cfg.alias_order, cfg.header_labels)
|
||||
return (text, item.get('attachment'))
|
||||
test_build_record = _test_build_simple
|
||||
start_ts = _time.time()
|
||||
try:
|
||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_check_job_loop(conn_str=conn_str, run_no=run.run_no, agent=agent, user=user, wait_seconds=wait_seconds, run_id=run.id, fetch_fn=_test_fetch_fn, build_record_fn=test_build_record, writeback_fn=_test_writeback_fn, writeback_sql=cfg.writeback_sql, row_id_key=cfg.row_id_key, log_prefix=cfg.log_prefix, fetch_sql=test_sql, max_rows=limit, pre_dify_fn=test_pre_dify, dify_system_prompt=cfg.dify_system_prompt)
|
||||
duration_ms = int((_time.time() - start_ts) * 1000)
|
||||
if total_count == 0 and (not errors):
|
||||
status = 'success'
|
||||
elif failed_count == 0:
|
||||
status = 'success'
|
||||
elif success_count == 0:
|
||||
status = 'failed'
|
||||
else:
|
||||
status = 'partial_failed'
|
||||
header_order = cfg.alias_order if cfg.alias_order else None
|
||||
header_labels = cfg.header_labels if cfg.header_labels else None
|
||||
detail_alias_order = cfg.detail_alias_order or []
|
||||
try:
|
||||
file_data, file_name, file_size = export_schedule_result_excel(run_no=run.run_no, summary={'status': status, 'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'duration_ms': duration_ms}, details=details, header_order=header_order, header_labels=header_labels, detail_alias_order=detail_alias_order)
|
||||
except Exception:
|
||||
file_data, file_name, file_size = (None, None, 0)
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.duration_ms = duration_ms
|
||||
run.status = status
|
||||
run.total_count = total_count
|
||||
run.success_count = success_count
|
||||
run.failed_count = failed_count
|
||||
run.skipped_count = skipped_count
|
||||
run.step_logs = step_logs if step_logs else None
|
||||
run.error_message = '; '.join(errors[:3]) if errors else None
|
||||
run.excel_file_data = file_data
|
||||
run.excel_file_name = file_name
|
||||
run.excel_file_size = file_size or 0
|
||||
try:
|
||||
if task.notify_enabled:
|
||||
_notify_schedule_run_wecom(task, run)
|
||||
except Exception as wecom_exc:
|
||||
current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc)
|
||||
db.session.commit()
|
||||
import decimal, datetime as dt
|
||||
|
||||
def _safe(v):
|
||||
if isinstance(v, decimal.Decimal):
|
||||
return float(v)
|
||||
if isinstance(v, (dt.date, dt.datetime)):
|
||||
return v.isoformat()
|
||||
if isinstance(v, dt.timedelta):
|
||||
return str(v)
|
||||
return v
|
||||
safe_details = []
|
||||
for item in details:
|
||||
safe_item = {k: _safe(v) for k, v in item.items()}
|
||||
safe_details.append(safe_item)
|
||||
return jsonify({'run_no': run.run_no, 'run_id': run.id, 'sql': test_sql, 'limit': limit, 'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'skipped_count': skipped_count, 'details': safe_details, 'errors': errors, 'step_logs': step_logs, 'dify_agent_id': dify_agent_id, 'dify_execution_snapshot': run.dify_execution_snapshot})
|
||||
except Exception as e:
|
||||
duration_ms = int((_time.time() - start_ts) * 1000)
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.duration_ms = duration_ms
|
||||
run.status = 'failed'
|
||||
run.error_message = str(e)
|
||||
db.session.commit()
|
||||
import traceback
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message=str(e), http_status=400, details={'sql': test_sql, 'traceback': traceback.format_exc()})
|
||||
|
||||
@schedule_admin_bp.route('/schedules', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedules():
|
||||
return jsonify(list_tasks())
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/export', methods=['GET'])
|
||||
@require_admin
|
||||
def export_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
payload = {'schema_version': 1, 'exported_at': datetime.utcnow().isoformat(), 'schedules': [_serialize_task_for_export(task, cfg_model)]}
|
||||
body = json.dumps(payload, ensure_ascii=False, indent=2)
|
||||
filename = f"{task.schedule_no or f'schedule_{task.id}'}_export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
|
||||
return Response(body, mimetype='application/json; charset=utf-8', headers={'Content-Disposition': f'attachment; filename="{filename}"'})
|
||||
|
||||
@schedule_admin_bp.route('/schedules/import', methods=['POST'])
|
||||
@require_admin
|
||||
def import_schedules():
|
||||
data = request.get_json(silent=True) or {}
|
||||
schedules = data.get('schedules')
|
||||
if not isinstance(schedules, list):
|
||||
raise ValidationError('Invalid import file: schedules missing')
|
||||
user = get_current_user()
|
||||
imported = 0
|
||||
skipped = 0
|
||||
errors: list[str] = []
|
||||
for item in schedules:
|
||||
if not isinstance(item, dict):
|
||||
skipped += 1
|
||||
continue
|
||||
try:
|
||||
name = str(item.get('name') or '').strip()
|
||||
cron_expr = str(item.get('cron_expr') or '').strip()
|
||||
owner_user_id = int(item.get('owner_user_id'))
|
||||
if not name or not cron_expr:
|
||||
raise ValueError('name or cron_expr missing')
|
||||
existing = None
|
||||
schedule_no = str(item.get('schedule_no') or '').strip()
|
||||
if schedule_no:
|
||||
existing = db.session.query(ScheduleTask).filter_by(schedule_no=schedule_no).first()
|
||||
task_payload = {'name': name, 'schedule_type': str(item.get('schedule_type') or 'platform_app'), 'owner_user_id': owner_user_id, 'cron_expr': cron_expr, 'wait_seconds': int(item.get('wait_seconds') or 0), 'dify_agent_id': item.get('dify_agent_id'), 'platform_api_path': item.get('platform_api_path'), 'notify_user_ids_json': item.get('notify_user_ids_json') if isinstance(item.get('notify_user_ids_json'), list) else [], 'notify_enabled': bool(item.get('notify_enabled', True)), 'enabled': bool(item.get('enabled', True)), 'data_source_type': str(item.get('data_source_type') or 'database')}
|
||||
cfg = item.get('config') if isinstance(item.get('config'), dict) else None
|
||||
if existing:
|
||||
update_task(existing, payload=task_payload, actor_id=getattr(user, 'id', None))
|
||||
existing.data_source_type = task_payload['data_source_type']
|
||||
if cfg:
|
||||
upsert_schedule_task_config(existing.id, cfg)
|
||||
else:
|
||||
task = create_task(name=name, schedule_type=task_payload['schedule_type'], owner_user_id=owner_user_id, cron_expr=cron_expr, wait_seconds=task_payload['wait_seconds'], dify_agent_id=task_payload['dify_agent_id'], platform_api_path=task_payload['platform_api_path'], notify_user_ids_json=task_payload['notify_user_ids_json'], notify_enabled=task_payload['notify_enabled'], enabled=task_payload['enabled'], actor_id=getattr(user, 'id', None))
|
||||
task.data_source_type = task_payload['data_source_type']
|
||||
db.session.commit()
|
||||
if cfg:
|
||||
upsert_schedule_task_config(task.id, cfg)
|
||||
imported += 1
|
||||
except Exception as exc:
|
||||
errors.append(str(exc))
|
||||
skipped += 1
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True, 'imported': imported, 'skipped': skipped, 'errors': errors[:20]})
|
||||
|
||||
@schedule_admin_bp.route('/schedules', methods=['POST'])
|
||||
@require_admin
|
||||
def post_schedule():
|
||||
data = request.get_json(silent=True) or {}
|
||||
user = get_current_user()
|
||||
data_source_type = str(data.get('data_source_type') or 'database')
|
||||
task = create_task(name=str(data.get('name') or '').strip(), schedule_type='platform_app', owner_user_id=int(data.get('owner_user_id')), cron_expr=str(data.get('cron_expr') or '').strip(), wait_seconds=int(data.get('wait_seconds') or 0), dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None, platform_api_path=str(data.get('platform_api_path') or '').strip() or None, notify_user_ids_json=data.get('notify_user_ids_json') if isinstance(data.get('notify_user_ids_json'), list) else [], notify_enabled=bool(data.get('notify_enabled', True)), enabled=bool(data.get('enabled', True)), actor_id=getattr(user, 'id', None))
|
||||
task.data_source_type = data_source_type
|
||||
task.platform_api_path = f'/{task.id}'
|
||||
db.session.commit()
|
||||
db.session.refresh(task)
|
||||
config_data = data.get('config')
|
||||
if config_data:
|
||||
upsert_schedule_task_config(task.id, config_data)
|
||||
if not task.dify_agent_id:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
|
||||
if cfg_model and cfg_model.dify_system_prompt:
|
||||
cfg_model.dify_system_prompt = None
|
||||
db.session.commit()
|
||||
return (jsonify(serialize_task(task)), 201)
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['PATCH'])
|
||||
@require_admin
|
||||
def patch_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
user = get_current_user()
|
||||
if 'data_source_type' in data:
|
||||
task.data_source_type = str(data['data_source_type'])
|
||||
db.session.commit()
|
||||
config_data = data.get('config')
|
||||
if config_data:
|
||||
upsert_schedule_task_config(task_id, config_data)
|
||||
task = update_task(task, payload=data, actor_id=getattr(user, 'id', None))
|
||||
if not task.dify_agent_id:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if cfg_model and cfg_model.dify_system_prompt:
|
||||
cfg_model.dify_system_prompt = None
|
||||
db.session.commit()
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.schedule.scheduler_service import request_cancel_run
|
||||
running_runs = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id, ScheduleRun.status == 'running').all()
|
||||
for rr in running_runs:
|
||||
request_cancel_run(rr.id)
|
||||
rr.status = 'failed'
|
||||
rr.error_message = '排程已被删除,执行中断'
|
||||
rr.finished_at = datetime.utcnow()
|
||||
if running_runs:
|
||||
db.session.commit()
|
||||
db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False)
|
||||
db.session.delete(task)
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/enable', methods=['POST'])
|
||||
@require_admin
|
||||
def enable_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
task.enabled = True
|
||||
if task.cron_expr:
|
||||
try:
|
||||
from croniter import croniter
|
||||
iter = croniter(task.cron_expr, datetime.utcnow())
|
||||
task.next_run_at = iter.get_next(datetime)
|
||||
except Exception:
|
||||
task.next_run_at = None
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/disable', methods=['POST'])
|
||||
@require_admin
|
||||
def disable_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
task.enabled = False
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
|
||||
@require_admin
|
||||
def run_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
user = get_current_user()
|
||||
existing = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task.id, ScheduleRun.status == 'running').first()
|
||||
if existing:
|
||||
raise ConflictError('该排程正在执行中,请等待完成后再试', details={'run_id': existing.id})
|
||||
run = ScheduleRun(run_no=_generate_run_no(), schedule_task_id=task.id, trigger_type='manual', triggered_by_user_id=getattr(user, 'id', None), started_at=datetime.utcnow(), status='running')
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
app = current_app._get_current_object()
|
||||
run_id = run.id
|
||||
|
||||
def _background():
|
||||
with app.app_context():
|
||||
t = db.session.get(ScheduleTask, task_id)
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if not t or not r:
|
||||
return
|
||||
try:
|
||||
run_task_now(t, trigger_type='manual', triggered_by_user_id=r.triggered_by_user_id, run=r)
|
||||
except Exception as exc:
|
||||
try:
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if r and r.status == 'running':
|
||||
r.status = 'failed'
|
||||
r.error_message = str(exc)
|
||||
r.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
current_app.logger.error('[schedule-run] run_id=%s failed: %s', run_id, exc, exc_info=True)
|
||||
t = threading.Thread(target=_background, daemon=True, name=f'schedule-run-{run_id}')
|
||||
t.start()
|
||||
fresh = db.session.get(ScheduleRun, run_id)
|
||||
return jsonify(serialize_run(fresh))
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/runs', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_runs(task_id: int):
|
||||
status = str(request.args.get('status') or '').strip() or None
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
started_after = None
|
||||
started_before = None
|
||||
sa = request.args.get('started_after')
|
||||
sb = request.args.get('started_before')
|
||||
if sa:
|
||||
try:
|
||||
started_after = datetime.fromisoformat(sa)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
if sb:
|
||||
try:
|
||||
started_before = datetime.fromisoformat(sb)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
return jsonify(list_runs(task_id=task_id, status=status, started_after=started_after, started_before=started_before, limit=limit))
|
||||
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_run(run_id: int):
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(serialize_run(run))
|
||||
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_run_excel(run_id: int):
|
||||
from io import BytesIO
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError('Excel not found')
|
||||
buf = BytesIO(run.excel_file_data)
|
||||
return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
__all__ = ['schedule_admin_bp']
|
||||
@@ -1,143 +1,392 @@
|
||||
"""
|
||||
货代发货通知 Tool API — 供 Dify Chatflow Agent 调用
|
||||
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 成功响应仍用 status: ok/failed 业务 envelope;HTTP 级参数/资源错误统一 raise AppError。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
from pathlib import Path
|
||||
import uuid
|
||||
|
||||
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_batch_by_no,
|
||||
get_focus_task_for_batch,
|
||||
get_task_by_ref,
|
||||
get_task_in_batch,
|
||||
list_batch_task_summaries,
|
||||
resolve_task_export_download,
|
||||
serialize_batch_summary,
|
||||
serialize_task_summary,
|
||||
task_export_error_message,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import switch_batch_focus
|
||||
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:
|
||||
return request.get_json(silent=True) or {}
|
||||
|
||||
def _generate_batch_no() -> str:
|
||||
from datetime import datetime
|
||||
return f"SB-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
@shipping_notice_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
@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/checkpoint-catalog", methods=["GET"])
|
||||
@shipping_notice_bp.route('/tools/checkpoint-catalog', methods=['GET'])
|
||||
def checkpoint_catalog():
|
||||
"""Checkpoint ids, human_options, action_buttons — developer/docs reference (Dify approach B: do not embed)."""
|
||||
"""返回检查点目录,供开发联调和文档核对 human_options/action_buttons。"""
|
||||
from app.services.shipping_notice.state_machine import build_checkpoint_catalog
|
||||
|
||||
return jsonify(build_checkpoint_catalog())
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/openapi.dify.yaml", methods=["GET"])
|
||||
@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")
|
||||
return current_app.response_class(body, mimetype='text/yaml; charset=utf-8')
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/create_task", methods=["POST"])
|
||||
@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_batch', methods=['POST'])
|
||||
def tool_create_batch():
|
||||
"""
|
||||
创建或复用发货批次。
|
||||
【AI 触发时机】:仅供 Hxops 内部建批链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
payload = _payload()
|
||||
if isinstance(payload.get('notice_items'), list) and payload.get('notice_items'):
|
||||
return jsonify(shipping_tools.create_batch_tasks(payload))
|
||||
batch_no = str(payload.get('batch_no') or '').strip()
|
||||
if batch_no:
|
||||
batch = get_batch_by_no(batch_no)
|
||||
if batch:
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已复用批次 {batch.batch_no}', 'data': serialize_batch_summary(batch)})
|
||||
batch, _created = shipping_tools.create_batch(payload)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已创建批次 {batch.batch_no}', 'data': serialize_batch_summary(batch)})
|
||||
|
||||
@shipping_notice_bp.route("/tools/parse_notice", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/parse_notice', methods=['POST'])
|
||||
def tool_parse_notice():
|
||||
"""
|
||||
解析发货通知正文。
|
||||
【AI 触发时机】:当用户上传、粘贴或修正发货通知内容后,需要把文本转成任务单头和订单行时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.parse_notice(_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/parse_inventory", methods=["POST"])
|
||||
@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/parse_inventory', methods=['POST'])
|
||||
def tool_parse_inventory():
|
||||
"""
|
||||
解析库存内容。
|
||||
【AI 触发时机】:当用户提供库存文本或表格内容,需要把库存转成系统可匹配格式时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.parse_inventory(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/upload_inventory_file", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/upload_inventory_file', methods=['POST'])
|
||||
def tool_upload_inventory_file():
|
||||
"""Multipart upload — parse server-side without sending Excel through LLM."""
|
||||
task_id = str(request.form.get("task_id") or request.args.get("task_id") or "").strip()
|
||||
upload = request.files.get("file")
|
||||
"""
|
||||
服务器侧接收库存 Excel 并解析。
|
||||
【AI 触发时机】:当用户上传库存 Excel,且不希望把二进制文件内容经由 LLM 传输时调用。
|
||||
"""
|
||||
task_id = str(request.form.get('task_id') or request.args.get('task_id') or '').strip()
|
||||
upload = request.files.get('file')
|
||||
return jsonify(shipping_tools.upload_inventory_file(task_id, upload))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/get_inventory_schema_preview", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/get_inventory_schema_preview', methods=['POST'])
|
||||
def tool_get_inventory_schema_preview():
|
||||
"""
|
||||
获取库存表头预览。
|
||||
【AI 触发时机】:当 Agent 需要先看 Excel/表格列名,再决定 map_json 或提示用户确认映射时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.get_inventory_schema_preview(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/apply_inventory_mapping", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/apply_inventory_mapping', methods=['POST'])
|
||||
def tool_apply_inventory_mapping():
|
||||
"""
|
||||
应用库存字段映射。
|
||||
【AI 触发时机】:当用户或 Agent 已确认列名与系统字段的对应关系,需要提交 map_json 时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.apply_inventory_mapping(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/ensure_inventory", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/ensure_inventory', methods=['POST'])
|
||||
def tool_ensure_inventory():
|
||||
"""
|
||||
保证任务已取得库存数据。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.ensure_inventory(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/auto_progress", methods=["POST"])
|
||||
@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"])
|
||||
@shipping_notice_bp.route('/tools/match_inventory', methods=['POST'])
|
||||
def tool_match_inventory():
|
||||
"""
|
||||
执行库存匹配。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.match_inventory(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/submit_decision", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/submit_decision', methods=['POST'])
|
||||
def tool_submit_decision():
|
||||
"""
|
||||
提交人工决策。
|
||||
【AI 触发时机】:当用户明确表达确认、驳回、重解析、重匹配、确认映射或关闭任务时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.submit_decision(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/generate_shipment_excel", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/confirm_inventory_source', methods=['POST'])
|
||||
def tool_confirm_inventory_source():
|
||||
"""
|
||||
确认库存查询来源(仅提交 source_code)。
|
||||
【AI 触发时机】:用户在库存源人工检查点选择正式库存源后调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.confirm_inventory_source(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/generate_shipment_excel', methods=['POST'])
|
||||
def tool_generate_shipment_excel():
|
||||
"""
|
||||
生成出货 Excel。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.generate_excel(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/upload_to_freight", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/upload_to_freight', methods=['POST'])
|
||||
def tool_upload_to_freight():
|
||||
"""
|
||||
上传到货代系统或确认人工上传完成。
|
||||
【AI 触发时机】:仅供后端主调度、内部恢复链路或人工上传收口调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.upload_to_freight(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/get_task_status", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/get_task_status', methods=['POST'])
|
||||
def tool_get_task_status():
|
||||
"""
|
||||
查询任务状态。
|
||||
【AI 触发时机】:当 Agent 只拿到任务号/会话号,需要先确认当前卡点后再决定下一步时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.get_task_status(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/get_batch_status', methods=['POST'])
|
||||
def tool_get_batch_status():
|
||||
"""
|
||||
查询批次状态。
|
||||
【AI 触发时机】:当用户关注整批任务处理进度,或 Agent 需要查看当前 focus task 与批次摘要时调用。
|
||||
"""
|
||||
payload = _payload()
|
||||
batch_no = str(payload.get('batch_no') or '').strip()
|
||||
if not batch_no:
|
||||
raise ValidationError("batch_no is required")
|
||||
batch = get_batch_by_no(batch_no)
|
||||
if not batch:
|
||||
raise NotFoundError("batch not found")
|
||||
focus_task = get_focus_task_for_batch(batch_no, batch.user_id or 0) if batch.user_id is not None else None
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已获取批次 {batch.batch_no} 状态', 'data': {**serialize_batch_summary(batch), 'focus_task': serialize_task_summary(focus_task) if focus_task else None, 'tasks': list_batch_task_summaries(batch)}})
|
||||
|
||||
@shipping_notice_bp.route("/rpa/inventory-ready", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/switch_focus_task', methods=['POST'])
|
||||
def tool_switch_focus_task():
|
||||
"""
|
||||
切换批次当前焦点任务。
|
||||
【AI 触发时机】:当前仅保留给 Hxops 内部切票能力;不属于 Dify 正式导出 Tool。
|
||||
"""
|
||||
payload = _payload()
|
||||
batch_no = str(payload.get('batch_no') or '').strip()
|
||||
task_no = str(payload.get('task_no') or payload.get('target_task_no') or '').strip()
|
||||
if not batch_no or not task_no:
|
||||
raise ValidationError("batch_no and task_no are required")
|
||||
batch = get_batch_by_no(batch_no)
|
||||
if not batch:
|
||||
raise NotFoundError("batch not found")
|
||||
task = get_task_in_batch(batch_no, task_no)
|
||||
if not task:
|
||||
raise NotFoundError("task not found in batch")
|
||||
switch_batch_focus(
|
||||
batch,
|
||||
task,
|
||||
source="tool_api",
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'task_no': task.task_no, 'message': f'已切换当前任务到 {task.task_no}', 'data': {'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)}})
|
||||
|
||||
@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/upload-complete", methods=["POST"])
|
||||
@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/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"])
|
||||
@shipping_notice_bp.route('/tasks/<task_no>/export', methods=['GET'])
|
||||
def download_task_export(task_no: str):
|
||||
from app.services.shipping_notice.tools import _get_task
|
||||
|
||||
task = _get_task(task_no)
|
||||
if not task or not task.export_file_path:
|
||||
return jsonify({"error": "export file not found"}), 404
|
||||
path = Path(task.export_file_path)
|
||||
if not path.is_file():
|
||||
return jsonify({"error": "export file missing on disk"}), 404
|
||||
return send_file(
|
||||
path,
|
||||
as_attachment=True,
|
||||
download_name=task.export_file_name or path.name,
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
"""下载任务已生成的出货 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)
|
||||
@@ -3,8 +3,8 @@ Speech transcription API — forwards audio to SiliconFlow ASR.
|
||||
"""
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.errors import UnauthorizedError, ValidationError, ServiceUnavailableError
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError, ValidationError, ServiceUnavailableError
|
||||
from app.services.speech_asr import SpeechAsrService
|
||||
|
||||
speech_bp = Blueprint('speech', __name__)
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
"""
|
||||
backend/app/api/tools/__init__.py
|
||||
|
||||
用途:Dify HTTP Tool API Blueprint 聚合。
|
||||
逻辑:Wave 1 前 re-export shipping_notice_tools、file_check_tools。
|
||||
"""
|
||||
from app.api.tools.shipping_notice import shipping_notice_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
|
||||
|
||||
__all__ = ['shipping_notice_bp', 'file_check_bp']
|
||||
@@ -0,0 +1,8 @@
|
||||
"""
|
||||
backend/app/api/tools/file_check.py
|
||||
|
||||
用途:文件检核 Tool API Blueprint(Wave 1 自 file_check_tools.py 迁入)。
|
||||
"""
|
||||
from app.api.file_check_tools import file_check_bp # noqa: F401
|
||||
|
||||
__all__ = ['file_check_bp']
|
||||
@@ -0,0 +1,9 @@
|
||||
"""
|
||||
backend/app/api/tools/maintenance.py
|
||||
|
||||
用途:设备维保 Tool API Blueprint re-export。
|
||||
依赖:app.api.maintenance_tools。
|
||||
逻辑:保持 api.tools 分包统一入口,register_blueprints 只从 app.api.tools 导入各 Tool Blueprint。
|
||||
"""
|
||||
|
||||
from app.api.maintenance_tools import maintenance_tool_bp # noqa: F401
|
||||
@@ -0,0 +1,8 @@
|
||||
"""
|
||||
backend/app/api/tools/shipping_notice.py
|
||||
|
||||
用途:出货通知 Tool API Blueprint(Wave 1 自 shipping_notice_tools.py 迁入)。
|
||||
"""
|
||||
from app.api.shipping_notice_tools import shipping_notice_bp # noqa: F401
|
||||
|
||||
__all__ = ['shipping_notice_bp']
|
||||
@@ -0,0 +1,126 @@
|
||||
"""
|
||||
backend/app/api/training.py
|
||||
|
||||
用途:提供新人培训用户侧进度接口与管理端统计导出接口。
|
||||
依赖:JWT 当前用户解析、training_service、Flask Blueprint/send_file。
|
||||
逻辑:员工端负责读写个人培训进度;管理端负责真实记录查询、统计与 Excel 导出。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, UnauthorizedError
|
||||
from app.services.training_service import (
|
||||
export_training_records_excel,
|
||||
get_user_training_record,
|
||||
list_training_records,
|
||||
serialize_training_record,
|
||||
summarize_training_records,
|
||||
upsert_user_training_record,
|
||||
)
|
||||
|
||||
training_user_bp = Blueprint("training_user", __name__)
|
||||
training_admin_bp = Blueprint("training_admin", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""确保当前请求存在登录用户。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _require_training_admin():
|
||||
"""
|
||||
确保当前用户具备培训管理权限。
|
||||
|
||||
用途:统一拦截 HR 管理面板的数据查询、统计与导出接口。
|
||||
核心逻辑:优先复用 User.can_manage_training(),把“角色默认权限 + 前端可配置功能权限”收敛到同一个判断入口。
|
||||
"""
|
||||
user = _require_user()
|
||||
if not user.can_manage_training():
|
||||
raise ForbiddenError("Training admin privilege required")
|
||||
return user
|
||||
|
||||
|
||||
@training_user_bp.route("/training-record", methods=["GET"])
|
||||
def get_my_training_record():
|
||||
"""读取当前用户的培训进度;未创建时返回 null data。"""
|
||||
user = _require_user()
|
||||
record = get_user_training_record(user.id)
|
||||
return jsonify(serialize_training_record(record) if record else None)
|
||||
|
||||
|
||||
@training_user_bp.route("/training-record/progress", methods=["PUT"])
|
||||
def save_my_training_record():
|
||||
"""保存当前用户培训进度,用于视频完成、答题推进与结算归档。"""
|
||||
user = _require_user()
|
||||
payload = request.get_json() or {}
|
||||
record = upsert_user_training_record(user, payload)
|
||||
return jsonify(serialize_training_record(record))
|
||||
|
||||
|
||||
@training_admin_bp.route("/training-records", methods=["GET"])
|
||||
def list_admin_training_records():
|
||||
"""列出培训记录,支持关键字、部门、状态筛选。"""
|
||||
_require_training_admin()
|
||||
keyword = request.args.get("keyword")
|
||||
department = request.args.get("department")
|
||||
status = request.args.get("status")
|
||||
|
||||
result = list_training_records(keyword=keyword, department=department, status=status)
|
||||
all_records = list_training_records()
|
||||
department_options = sorted({str(item.department or "").strip() for item in all_records.records if str(item.department or "").strip()})
|
||||
|
||||
page = max(1, request.args.get("page", type=int) or 1)
|
||||
page_size = max(1, min(200, request.args.get("page_size", type=int) or max(result.total, 1)))
|
||||
start = (page - 1) * page_size
|
||||
end = start + page_size
|
||||
items = result.records[start:end]
|
||||
pages = max(1, (result.total + page_size - 1) // page_size) if result.total else 1
|
||||
|
||||
return jsonify(
|
||||
{
|
||||
"items": [serialize_training_record(item) for item in items],
|
||||
"total": result.total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"pages": pages,
|
||||
"department_options": department_options,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@training_admin_bp.route("/training-records/stats", methods=["GET"])
|
||||
def get_admin_training_stats():
|
||||
"""返回培训记录聚合统计,供 HR 面板展示。"""
|
||||
_require_training_admin()
|
||||
result = list_training_records(
|
||||
keyword=request.args.get("keyword"),
|
||||
department=request.args.get("department"),
|
||||
status=request.args.get("status"),
|
||||
)
|
||||
return jsonify(summarize_training_records(result.records))
|
||||
|
||||
|
||||
@training_admin_bp.route("/training-records/export", methods=["GET"])
|
||||
def export_admin_training_records():
|
||||
"""导出培训记录为 Excel。"""
|
||||
_require_training_admin()
|
||||
result = list_training_records(
|
||||
keyword=request.args.get("keyword"),
|
||||
department=request.args.get("department"),
|
||||
status=request.args.get("status"),
|
||||
)
|
||||
file_data, file_name = export_training_records_excel(result.records)
|
||||
return send_file(
|
||||
BytesIO(file_data),
|
||||
as_attachment=True,
|
||||
download_name=file_name,
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
+420
-268
@@ -1,10 +1,20 @@
|
||||
"""
|
||||
backend/app/api/user.py
|
||||
|
||||
用途:当前用户域 API(Casdoor 登录、企微 OAuth、首页、FAQ、反馈等)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、models、wecom/dify 相关 services。
|
||||
逻辑:薄路由层鉴权与参数校验;Casdoor/企微 OAuth 委托 services/auth/*。
|
||||
"""
|
||||
from flask import Blueprint, request, jsonify, current_app
|
||||
from app import db
|
||||
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, Announcement, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog
|
||||
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog
|
||||
from app.services.feedback_notify import send_feedback_group_notification
|
||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||
from app.services.agent_registry.serialization import serialize_registry_fields
|
||||
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
|
||||
from app.auth_jwt import get_current_user as _auth_current_user
|
||||
from app.auth_jwt import issue_local_access_token
|
||||
from app.core.auth.jwt import get_current_user as _auth_current_user
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
|
||||
from sqlalchemy import and_, or_, inspect, insert
|
||||
from datetime import datetime, timedelta
|
||||
@@ -17,11 +27,24 @@ import base64
|
||||
import json
|
||||
import re
|
||||
import ast
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
raise_for_status,
|
||||
)
|
||||
from app.services.auth import casdoor_service as _casdoor_svc
|
||||
from app.services.auth import wecom_auth_service as _wecom_svc
|
||||
user_bp = Blueprint('user', __name__)
|
||||
_WECOM_ACCESS_TOKEN_CACHE = {'token': None, 'expires_at': None}
|
||||
_WECOM_STATE_CACHE = {}
|
||||
_WECOM_BIND_SESSION_CACHE = {}
|
||||
_WECOM_ACCESS_TOKEN_CACHE = _wecom_svc.ACCESS_TOKEN_CACHE
|
||||
_WECOM_STATE_CACHE = _wecom_svc.STATE_CACHE
|
||||
_WECOM_BIND_SESSION_CACHE = _wecom_svc.BIND_SESSION_CACHE
|
||||
_PASSWORD_RESET_RATE_CACHE = {}
|
||||
_PASSWORD_RESET_GENERIC_MESSAGE = 'If the account exists and WeCom is bound, a reset link has been sent to your WeCom.'
|
||||
_ALLOWED_WECOM_MATCH_FIELDS = {'employee_id', 'mobile', 'email'}
|
||||
_LOGIN_AUDIT_COLUMNS_CACHE = None
|
||||
_CASDOOR_OIDC_CACHE = {'value': None, 'expires_at': None}
|
||||
@@ -108,8 +131,12 @@ def _run_db_with_retry(operation, *, label: str):
|
||||
current_app.logger.warning('%s dispose engine failed: %s', label, dispose_exc)
|
||||
return operation()
|
||||
|
||||
def _is_wecom_configured():
|
||||
return all([current_app.config.get('WECOM_ENABLED'), current_app.config.get('WECOM_CORP_ID'), current_app.config.get('WECOM_AGENT_ID'), current_app.config.get('WECOM_SECRET')])
|
||||
def _get_wecom_config_missing_fields() -> list[str]:
|
||||
return _wecom_svc.get_config_missing_fields()
|
||||
|
||||
|
||||
def _is_wecom_configured() -> bool:
|
||||
return _wecom_svc.is_configured()
|
||||
|
||||
def _issue_casdoor_state(redirect_uri: str):
|
||||
exp_ts = int((datetime.utcnow() + timedelta(minutes=10)).timestamp())
|
||||
@@ -230,118 +257,58 @@ def _is_casdoor_login_mode() -> bool:
|
||||
return (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() == 'casdoor'
|
||||
|
||||
def _is_casdoor_configured() -> bool:
|
||||
if not _clean_str(current_app.config.get('CASDOOR_ORGANIZATION')):
|
||||
return False
|
||||
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
|
||||
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
|
||||
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
|
||||
return bool(base and client_id and client_secret)
|
||||
return _casdoor_svc.is_casdoor_configured()
|
||||
|
||||
def _casdoor_user_owner() -> str:
|
||||
owner = _clean_str(current_app.config.get('CASDOOR_ORGANIZATION'))
|
||||
if not owner:
|
||||
raise RuntimeError('CASDOOR_ORGANIZATION is not configured')
|
||||
return owner
|
||||
return _casdoor_svc.casdoor_user_owner()
|
||||
|
||||
def _verify_casdoor_password(username: str, password: str):
|
||||
_casdoor_password_login(username, password)
|
||||
|
||||
def _casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str):
|
||||
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
|
||||
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
|
||||
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
|
||||
if not base or not client_id or not client_secret:
|
||||
raise RuntimeError('Casdoor is not configured')
|
||||
url = f'{base}/api/set-password'
|
||||
resp = requests.post(url, files={'userOwner': (None, user_owner), 'userName': (None, user_name), 'oldPassword': (None, old_password), 'newPassword': (None, new_password)}, auth=(client_id, client_secret), timeout=8)
|
||||
try:
|
||||
data = resp.json() or {}
|
||||
except ValueError:
|
||||
raise RuntimeError(f'Casdoor set-password failed: HTTP {resp.status_code} {resp.text[:200]}')
|
||||
if data.get('status') != 'ok':
|
||||
_raise_casdoor_set_password_error(data)
|
||||
return _casdoor_svc.casdoor_set_password(user_owner, user_name, old_password, new_password)
|
||||
|
||||
def _is_casdoor_user_exists_error(message: str) -> bool:
|
||||
return _casdoor_svc.is_user_exists_error(message)
|
||||
|
||||
def _raise_casdoor_add_user_error(source) -> None:
|
||||
_casdoor_svc.raise_add_user_error(source)
|
||||
|
||||
def _casdoor_add_user(user_payload: dict):
|
||||
return _casdoor_svc.casdoor_add_user(user_payload)
|
||||
|
||||
def _sync_casdoor_create_user(*, username: str, password: str, email: str, real_name=None, phone_number=None, status='active', department=None):
|
||||
return _casdoor_svc.sync_create_user(username=username, password=password, email=email, real_name=real_name, phone_number=phone_number, status=status, department=department)
|
||||
|
||||
def _raise_casdoor_update_user_error(source) -> None:
|
||||
_casdoor_svc.raise_update_user_error(source)
|
||||
|
||||
def _casdoor_update_user(user_payload: dict):
|
||||
return _casdoor_svc.casdoor_update_user(user_payload)
|
||||
|
||||
def _sync_casdoor_admin_set_password(user: User, new_password: str):
|
||||
return _casdoor_svc.sync_admin_set_password(user, new_password)
|
||||
|
||||
def _sync_casdoor_update_user(user: User, *, new_password: str | None = None):
|
||||
return _casdoor_svc.sync_update_user(user, new_password=new_password)
|
||||
|
||||
def _is_casdoor_password_error(message: str) -> bool:
|
||||
lowered = (message or '').lower()
|
||||
return 'invalid_grant' in lowered or 'password login failed' in lowered or 'incorrect password' in lowered
|
||||
return _casdoor_svc.is_password_error(message)
|
||||
|
||||
def _is_casdoor_user_missing_error(message: str) -> bool:
|
||||
lowered = (message or '').lower()
|
||||
return (
|
||||
"doesn't exist" in lowered
|
||||
or 'does not exist' in lowered
|
||||
or 'user not found' in lowered
|
||||
or 'no such user' in lowered
|
||||
)
|
||||
return _casdoor_svc.is_user_missing_error(message)
|
||||
|
||||
def _raise_casdoor_user_not_in_idp(source=None) -> None:
|
||||
data = _extract_casdoor_error_payload(source)
|
||||
msg_text = _clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
|
||||
raise AppError(
|
||||
code='CASDOOR_USER_NOT_IN_IDP',
|
||||
message='Your account has not been registered in the authentication system. Please contact the administrator.',
|
||||
http_status=409,
|
||||
details={'technical': msg_text or str(source or '')[:300]},
|
||||
)
|
||||
_casdoor_svc.raise_user_not_in_idp(source)
|
||||
|
||||
def _extract_casdoor_error_payload(source) -> dict:
|
||||
if isinstance(source, dict):
|
||||
return source
|
||||
text = str(source or '')
|
||||
match = re.search(r'\{.*\}', text, re.DOTALL)
|
||||
if match:
|
||||
try:
|
||||
parsed = ast.literal_eval(match.group(0))
|
||||
if isinstance(parsed, dict):
|
||||
return parsed
|
||||
except (SyntaxError, ValueError):
|
||||
pass
|
||||
try:
|
||||
parsed = json.loads(text)
|
||||
if isinstance(parsed, dict):
|
||||
return parsed
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
pass
|
||||
return {}
|
||||
return _casdoor_svc.extract_error_payload(source)
|
||||
|
||||
def _raise_casdoor_auth_error(source, *, context: str, status_code: int = 401) -> None:
|
||||
"""
|
||||
Map Casdoor OAuth/API failures to stable business error codes for frontend i18n.
|
||||
context: password | verify | code | refresh
|
||||
"""
|
||||
data = _extract_casdoor_error_payload(source)
|
||||
raw = str(source or '')
|
||||
oauth_error = _clean_str(data.get('error')).lower()
|
||||
if not oauth_error and 'invalid_grant' in raw.lower():
|
||||
oauth_error = 'invalid_grant'
|
||||
if not oauth_error and 'invalid_client' in raw.lower():
|
||||
oauth_error = 'invalid_client'
|
||||
if oauth_error == 'invalid_grant' or _is_casdoor_password_error(raw):
|
||||
if context in ('password', 'verify'):
|
||||
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect username or password', http_status=401)
|
||||
raise AppError(code='CASDOOR_CODE_EXPIRED', message='Login session expired, please sign in again', http_status=401)
|
||||
if oauth_error in ('invalid_client', 'unauthorized_client'):
|
||||
raise AppError(code='CASDOOR_CONFIG_ERROR', message='Authentication service is misconfigured. Please contact the administrator.', http_status=503, details={'casdoor_error': oauth_error})
|
||||
if oauth_error == 'access_denied':
|
||||
raise AppError(code='CASDOOR_ACCESS_DENIED', message='Login was cancelled or denied', http_status=403)
|
||||
if 'token endpoint missing' in raw.lower() or 'casdoor_base_url is not configured' in raw.lower() or 'casdoor is not configured' in raw.lower():
|
||||
raise AppError(code='CASDOOR_CONFIG_ERROR', message='Authentication service is not configured. Please contact the administrator.', http_status=503)
|
||||
if 'invalid or expired casdoor state' in raw.lower():
|
||||
raise ValidationError('Invalid or expired Casdoor state')
|
||||
current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s raw=%s', context, data, raw[:500])
|
||||
raise AppError(code='CASDOOR_AUTH_FAILED', message='Authentication failed, please try again', http_status=status_code, details={'casdoor_error': oauth_error or None, 'technical': raw[:300]})
|
||||
_casdoor_svc.raise_auth_error(source, context=context, status_code=status_code)
|
||||
|
||||
def _raise_casdoor_set_password_error(source) -> None:
|
||||
data = _extract_casdoor_error_payload(source)
|
||||
msg_text = _clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
|
||||
lowered = (msg_text or str(source or '')).lower()
|
||||
if _is_casdoor_password_error(lowered) or 'old password' in lowered or 'current password' in lowered:
|
||||
_raise_incorrect_current_password()
|
||||
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
|
||||
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='New password does not meet security requirements', http_status=400)
|
||||
if _is_casdoor_user_missing_error(lowered):
|
||||
_raise_casdoor_user_not_in_idp(source)
|
||||
raise AppError(code='CASDOOR_SET_PASSWORD_FAILED', message='Failed to change password. Please try again or contact the administrator.', http_status=502, details={'technical': msg_text or str(source)[:300]})
|
||||
_casdoor_svc.raise_set_password_error(source)
|
||||
|
||||
def _raise_incorrect_current_password():
|
||||
raise AppError(
|
||||
@@ -439,17 +406,7 @@ def _consume_wecom_bind_session(token: str):
|
||||
return identity
|
||||
|
||||
def _parse_wecom_field_list(raw_value, default_fields: list[str]):
|
||||
if isinstance(raw_value, str):
|
||||
pieces = [item.strip().lower() for item in raw_value.split(',')]
|
||||
elif isinstance(raw_value, (list, tuple)):
|
||||
pieces = [str(item).strip().lower() for item in raw_value]
|
||||
else:
|
||||
pieces = []
|
||||
result = []
|
||||
for piece in pieces:
|
||||
if piece in _ALLOWED_WECOM_MATCH_FIELDS and piece not in result:
|
||||
result.append(piece)
|
||||
return result or list(default_fields)
|
||||
return _wecom_svc.parse_field_list(raw_value, default_fields)
|
||||
|
||||
def _verify_wecom_msg_signature(msg_signature: str, token: str, timestamp: str, nonce: str, encrypt: str) -> bool:
|
||||
if not msg_signature or not token or (not encrypt):
|
||||
@@ -477,24 +434,19 @@ def _persist_wecom_callback_audit(*, msg_signature, timestamp, nonce, encrypt_ra
|
||||
db.session.rollback()
|
||||
|
||||
def _get_wecom_access_token():
|
||||
now = datetime.utcnow()
|
||||
token = _WECOM_ACCESS_TOKEN_CACHE.get('token')
|
||||
expires_at = _WECOM_ACCESS_TOKEN_CACHE.get('expires_at')
|
||||
if token and expires_at and (now < expires_at):
|
||||
return token
|
||||
corp_id = current_app.config.get('WECOM_CORP_ID')
|
||||
secret = current_app.config.get('WECOM_SECRET')
|
||||
token_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
|
||||
resp = requests.get(token_url, params={'corpid': corp_id, 'corpsecret': secret}, timeout=8)
|
||||
data = resp.json()
|
||||
if data.get('errcode') != 0 or not data.get('access_token'):
|
||||
raise RuntimeError(f'Failed to fetch WeCom token: {data}')
|
||||
_WECOM_ACCESS_TOKEN_CACHE['token'] = data['access_token']
|
||||
_WECOM_ACCESS_TOKEN_CACHE['expires_at'] = now + timedelta(seconds=max(int(data.get('expires_in', 7200)) - 120, 60))
|
||||
return data['access_token']
|
||||
return _wecom_svc.get_access_token()
|
||||
|
||||
def _build_login_payload(user: User, source: str='password', bind_status: str=None):
|
||||
payload = {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'source': source, 'access_token': issue_local_access_token(user), 'token_type': 'Bearer'}
|
||||
payload = {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'default_agent_id': user.default_agent_id,
|
||||
'feature_permissions': user.get_feature_permissions(),
|
||||
'source': source,
|
||||
'access_token': issue_local_access_token(user),
|
||||
'token_type': 'Bearer',
|
||||
}
|
||||
if bind_status:
|
||||
payload['bind_status'] = bind_status
|
||||
return payload
|
||||
@@ -545,39 +497,16 @@ def _extract_wecom_extattr_value(wecom_user: dict, key: str):
|
||||
return None
|
||||
|
||||
def _get_wecom_match_config():
|
||||
raw_rules = current_app.config.get('WECOM_MATCH_RULES', 'employee_id,mobile')
|
||||
rules = _parse_wecom_field_list(raw_rules, ['employee_id', 'mobile'])
|
||||
operator = str(current_app.config.get('WECOM_MATCH_OPERATOR', 'AND')).upper()
|
||||
if operator not in {'AND', 'OR'}:
|
||||
operator = 'AND'
|
||||
return (rules, operator)
|
||||
return _wecom_svc.get_match_config()
|
||||
|
||||
def _get_wecom_first_login_bind_mode():
|
||||
mode = _clean_str(current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE')) or 'match_rules'
|
||||
mode = mode.lower()
|
||||
if mode not in {'match_rules', 'input_verify'}:
|
||||
mode = 'match_rules'
|
||||
return mode
|
||||
return _wecom_svc.get_first_login_bind_mode()
|
||||
|
||||
def _get_wecom_first_login_input_fields():
|
||||
raw_fields = current_app.config.get('WECOM_FIRST_LOGIN_INPUT_FIELDS', 'employee_id,mobile,email')
|
||||
return _parse_wecom_field_list(raw_fields, ['employee_id', 'mobile', 'email'])
|
||||
return _wecom_svc.get_first_login_input_fields()
|
||||
|
||||
def _extract_wecom_identity(wecom_user: dict):
|
||||
userid = _clean_str(wecom_user.get('userid'))
|
||||
unionid = _clean_str(wecom_user.get('unionid'))
|
||||
email = _clean_str(wecom_user.get('email'))
|
||||
mobile_raw = _clean_str(wecom_user.get('mobile'))
|
||||
normalize_mobile = bool(current_app.config.get('WECOM_MOBILE_NORMALIZE', True))
|
||||
mobile = _normalize_mobile(mobile_raw) if normalize_mobile else mobile_raw
|
||||
employee_id_source = _clean_str(current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE')) or 'userid'
|
||||
if employee_id_source == 'userid':
|
||||
employee_id = userid
|
||||
elif employee_id_source.startswith('extattr:'):
|
||||
employee_id = _extract_wecom_extattr_value(wecom_user, employee_id_source.split(':', 1)[1])
|
||||
else:
|
||||
employee_id = _clean_str(wecom_user.get(employee_id_source))
|
||||
return {'wecom_userid': userid, 'wecom_unionid': unionid, 'name': _clean_str(wecom_user.get('name')) or userid or 'wecom_user', 'email': email, 'mobile': mobile, 'mobile_raw': mobile_raw, 'employee_id': employee_id}
|
||||
return _wecom_svc.extract_identity(wecom_user)
|
||||
|
||||
def _mobile_candidates(identity: dict):
|
||||
values = []
|
||||
@@ -615,34 +544,7 @@ def _find_users_by_input_field(field: str, value):
|
||||
return ([], 'invalid_field')
|
||||
|
||||
def _find_users_by_match_rules(identity: dict, rules: list, operator: str):
|
||||
filters = []
|
||||
missing = []
|
||||
for rule in rules:
|
||||
if rule == 'employee_id':
|
||||
employee_id = _clean_str(identity.get('employee_id'))
|
||||
if not employee_id:
|
||||
missing.append('employee_id')
|
||||
else:
|
||||
filters.append(User.employee_id == employee_id)
|
||||
elif rule == 'mobile':
|
||||
candidates = _mobile_candidates(identity)
|
||||
if not candidates:
|
||||
missing.append('mobile')
|
||||
else:
|
||||
filters.append(User.phone_number.in_(candidates))
|
||||
elif rule == 'email':
|
||||
email = _clean_str(identity.get('email'))
|
||||
if not email:
|
||||
missing.append('email')
|
||||
else:
|
||||
filters.append(User.email == email)
|
||||
if missing:
|
||||
return ([], missing)
|
||||
if not filters:
|
||||
return ([], ['match_rules'])
|
||||
clause = and_(*filters) if operator == 'AND' else or_(*filters)
|
||||
users = db.session.query(User).filter(clause).all()
|
||||
return (users, [])
|
||||
return _wecom_svc.find_users_by_match_rules(identity, rules, operator)
|
||||
|
||||
def _assert_wecom_binding_not_occupied(user: User, identity: dict):
|
||||
wecom_userid = identity.get('wecom_userid')
|
||||
@@ -780,7 +682,11 @@ def login():
|
||||
Can be disabled via AUTH_ALLOW_LOCAL_PASSWORD_LOGIN=false.
|
||||
"""
|
||||
if not bool(current_app.config.get('AUTH_ALLOW_LOCAL_PASSWORD_LOGIN', True)):
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='Password login is disabled. Please use Casdoor login.', http_status=403, details={'error_code': 'PASSWORD_LOGIN_DISABLED'})
|
||||
raise AppError(
|
||||
code='AUTH.PASSWORD_LOGIN_DISABLED',
|
||||
message='Password login is disabled. Please use Casdoor login.',
|
||||
http_status=403,
|
||||
)
|
||||
|
||||
def _attempt_login():
|
||||
data = request.get_json() or {}
|
||||
@@ -836,7 +742,11 @@ def casdoor_password_login():
|
||||
Direct login with username/password against Casdoor (no browser redirect).
|
||||
"""
|
||||
if (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() != 'casdoor':
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='Casdoor password login is disabled by AUTH_LOGIN_MODE', http_status=403, details={'error_code': 'CASDOOR_PASSWORD_LOGIN_DISABLED'})
|
||||
raise AppError(
|
||||
code='AUTH.CASDOOR_PASSWORD_LOGIN_DISABLED',
|
||||
message='Casdoor password login is disabled by AUTH_LOGIN_MODE',
|
||||
http_status=403,
|
||||
)
|
||||
data = request.get_json() or {}
|
||||
username = _clean_str(data.get('username'))
|
||||
password = data.get('password') or ''
|
||||
@@ -860,7 +770,7 @@ def casdoor_password_login():
|
||||
_write_login_audit('casdoor', 'success', user=user)
|
||||
db.session.commit()
|
||||
api_bearer_token = id_token or access_token
|
||||
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
|
||||
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
|
||||
except WeComLoginError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
@@ -990,7 +900,7 @@ def casdoor_login():
|
||||
_write_login_audit('casdoor', 'success', user=user)
|
||||
db.session.commit()
|
||||
api_bearer_token = id_token or access_token
|
||||
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
|
||||
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
|
||||
except WeComLoginError:
|
||||
db.session.rollback()
|
||||
current_app.logger.warning('[casdoor_login] business_reject')
|
||||
@@ -1047,7 +957,11 @@ def casdoor_refresh():
|
||||
except Exception as e:
|
||||
message = str(e)
|
||||
if 'unsupported_grant_type' in message or 'refresh_token is not supported' in message:
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='Casdoor refresh token is not supported by current application config', http_status=400, details={'error_code': 'CASDOOR_REFRESH_UNSUPPORTED'})
|
||||
raise AppError(
|
||||
code='AUTH.CASDOOR_REFRESH_UNSUPPORTED',
|
||||
message='Casdoor refresh token is not supported by current application config',
|
||||
http_status=400,
|
||||
)
|
||||
current_app.logger.exception('[casdoor_refresh] failed refresh=%s', _token_brief(refresh_token))
|
||||
raise UnauthorizedError(f'Casdoor refresh failed: {str(e)}')
|
||||
|
||||
@@ -1094,7 +1008,11 @@ def wecom_login():
|
||||
if not wecom_userid_value:
|
||||
_write_login_audit('wecom', 'failed', reason=f"not_in_agent_scope:openid={wecom_openid_value or ''}", error_code='WECOM_NOT_IN_AGENT_SCOPE')
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='当前企业微信账号未授权登录该应用:账号不在自建应用的可见范围内,或不是本企业成员。请管理员到「企业微信后台 → 应用管理 → 该应用 → 可见范围」中加入该成员所在的部门或个人。', http_status=401, details={'error_code': 'WECOM_NOT_IN_AGENT_SCOPE'})
|
||||
raise AppError(
|
||||
code='WECOM_NOT_IN_AGENT_SCOPE',
|
||||
message='当前企业微信账号未授权登录该应用:账号不在自建应用的可见范围内,或不是本企业成员。请管理员到「企业微信后台 → 应用管理 → 该应用 → 可见范围」中加入该成员所在的部门或个人。',
|
||||
http_status=401,
|
||||
)
|
||||
user_resp = requests.get('https://qyapi.weixin.qq.com/cgi-bin/user/get', params={'access_token': access_token, 'userid': wecom_userid_value}, timeout=8)
|
||||
wecom_user = user_resp.json()
|
||||
wecom_userid_for_audit = wecom_user.get('userid') or wecom_userid_for_audit
|
||||
@@ -1120,7 +1038,11 @@ def wecom_login():
|
||||
if _is_users_pk_sequence_error(e):
|
||||
_write_login_audit('wecom', 'failed', reason='db_sequence_misconfig', wecom_userid=wecom_userid_for_audit, error_code='DB_SEQUENCE_MISCONFIG')
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='数据库主键自增配置异常,当前环境缺少 users.id 的自动序列。请执行数据库迁移后重试。', http_status=500, details={'error_code': 'DB_SEQUENCE_MISCONFIG'})
|
||||
raise AppError(
|
||||
code='SYSTEM.DB_SEQUENCE_MISCONFIG',
|
||||
message='数据库主键自增配置异常,当前环境缺少 users.id 的自动序列。请执行数据库迁移后重试。',
|
||||
http_status=500,
|
||||
)
|
||||
_write_login_audit('wecom', 'failed', reason=f'exception:{str(e)[:160]}')
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'WeCom login failed: {str(e)}', http_status=500)
|
||||
@@ -1135,21 +1057,44 @@ def wecom_complete_bind():
|
||||
value = data.get('value')
|
||||
identity = _get_wecom_bind_session(binding_token)
|
||||
if not identity:
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='WeCom binding session expired. Please restart WeCom login.', http_status=400, details={'error_code': 'WECOM_BIND_SESSION_EXPIRED'})
|
||||
raise AppError(
|
||||
code='WECOM_BIND_SESSION_EXPIRED',
|
||||
message='WeCom binding session expired. Please restart WeCom login.',
|
||||
http_status=400,
|
||||
)
|
||||
allowed_fields = _get_wecom_first_login_input_fields()
|
||||
if field not in allowed_fields:
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='Selected bind field is not allowed', http_status=400, details={'error_code': 'WECOM_BIND_FIELD_NOT_ALLOWED', 'allowed_fields': allowed_fields})
|
||||
raise AppError(
|
||||
code='WECOM_BIND_FIELD_NOT_ALLOWED',
|
||||
message='Selected bind field is not allowed',
|
||||
http_status=400,
|
||||
details={'allowed_fields': allowed_fields},
|
||||
)
|
||||
matched_users, missing_field = _find_users_by_input_field(field, value)
|
||||
if missing_field:
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message=f'{field} is required', http_status=400, details={'error_code': 'WECOM_BIND_INPUT_VALUE_REQUIRED', 'field': field})
|
||||
raise AppError(
|
||||
code='WECOM_BIND_INPUT_VALUE_REQUIRED',
|
||||
message=f'{field} is required',
|
||||
http_status=400,
|
||||
details={'field': field},
|
||||
)
|
||||
if len(matched_users) == 0:
|
||||
_write_login_audit('wecom', 'failed', reason=f'input_bind_not_found:{field}', wecom_userid=identity.get('wecom_userid'), error_code='WECOM_BIND_INPUT_NOT_FOUND', match_rules=[field], match_operator='AND')
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='No local account matched the verification value.', http_status=404, details={'error_code': 'WECOM_BIND_INPUT_NOT_FOUND', 'field': field})
|
||||
raise AppError(
|
||||
code='WECOM_BIND_INPUT_NOT_FOUND',
|
||||
message='No local account matched the verification value.',
|
||||
http_status=404,
|
||||
details={'field': field},
|
||||
)
|
||||
if len(matched_users) > 1:
|
||||
_write_login_audit('wecom', 'failed', reason=f'input_bind_ambiguous:{field}', wecom_userid=identity.get('wecom_userid'), error_code='WECOM_BIND_INPUT_AMBIGUOUS', match_rules=[field], match_operator='AND')
|
||||
db.session.commit()
|
||||
raise ConflictError('Multiple local accounts matched the verification value.', details={'error_code': 'WECOM_BIND_INPUT_AMBIGUOUS', 'field': field, 'candidate_count': len(matched_users)})
|
||||
raise ConflictError(
|
||||
'Multiple local accounts matched the verification value.',
|
||||
code='WECOM_BIND_INPUT_AMBIGUOUS',
|
||||
details={'field': field, 'candidate_count': len(matched_users)},
|
||||
)
|
||||
user = matched_users[0]
|
||||
if user.status != 'active':
|
||||
_write_login_audit('wecom', 'failed', user=user, reason='account_disabled', wecom_userid=identity.get('wecom_userid'), error_code='WECOM_ACCOUNT_DISABLED', match_rules=[field], match_operator='AND')
|
||||
@@ -1375,6 +1320,15 @@ def submit_general_feedback():
|
||||
row = GeneralFeedback(user_id=user.id, username=user.username, feedback_type=feedback_type, feedback_module=feedback_module, content=content, source_page=source_page, chat_log_id=chat_log_id)
|
||||
db.session.add(row)
|
||||
db.session.commit()
|
||||
notify_result = send_feedback_group_notification(row, user)
|
||||
if notify_result.get('ok'):
|
||||
current_app.logger.info('[feedback] group notification sent feedback_id=%s', row.id)
|
||||
elif not notify_result.get('skipped'):
|
||||
current_app.logger.warning(
|
||||
'[feedback] group notification failed feedback_id=%s reason=%s',
|
||||
row.id,
|
||||
notify_result.get('reason'),
|
||||
)
|
||||
return jsonify({'status': 'ok', 'id': row.id})
|
||||
|
||||
@user_bp.route('/home', methods=['GET'])
|
||||
@@ -1388,12 +1342,18 @@ def home():
|
||||
|
||||
def _load_home_payload():
|
||||
if user.role == 'admin':
|
||||
agent_rows = db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url, Agent.extra_config).filter(Agent.is_active.is_(True)).all()
|
||||
agent_rows = Agent.query.filter(Agent.is_active.is_(True)).all()
|
||||
else:
|
||||
agent_rows = [{'id': agent.id, 'name': agent.name, 'description': agent.description, 'icon_url': agent.icon_url, 'extra_config': agent.extra_config} for agent in user.agents]
|
||||
agent_rows = [agent for agent in user.agents if agent.is_active]
|
||||
agent_rows = sort_agent_rows(agent_rows)
|
||||
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
|
||||
favorite_ids = [f.agent_id for f in favorites]
|
||||
qqs = db.session.query(QuickQuestion).filter((QuickQuestion.user_id == user.id) | (QuickQuestion.user_id == None)).all()
|
||||
qqs = db.session.query(QuickQuestion).filter(
|
||||
or_(
|
||||
QuickQuestion.user_id == user.id,
|
||||
and_(QuickQuestion.user_id.is_(None), QuickQuestion.is_enabled.is_(True)),
|
||||
)
|
||||
).all()
|
||||
layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
|
||||
layout = layout_config.layout if layout_config else {}
|
||||
embedded_rel = db.session.query(UserDefaultAgent).filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all()
|
||||
@@ -1401,8 +1361,15 @@ def home():
|
||||
for rel in embedded_rel:
|
||||
agent = db.session.get(Agent, rel.agent_id)
|
||||
if agent:
|
||||
embedded_agents.append({'id': agent.id, 'name': agent.name, 'iframe_url': agent.extra_config.get('iframe_url') if agent.extra_config else None})
|
||||
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'}, 'agents': [{'id': a.id if hasattr(a, 'id') else a['id'], 'name': a.name if hasattr(a, 'name') else a['name'], 'description': a.description if hasattr(a, 'description') else a['description'], 'icon_url': a.icon_url if hasattr(a, 'icon_url') else a['icon_url'], 'dify_app_type': ((a.extra_config or {}).get('dify_app_type') if hasattr(a, 'extra_config') else (a.get('extra_config') or {}).get('dify_app_type')) or 'chatflow'} 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})
|
||||
registry = serialize_registry_fields(agent)
|
||||
embedded_agents.append({
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'iframe_url': registry.get('iframe_url'),
|
||||
'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})
|
||||
try:
|
||||
return _run_db_with_retry(_load_home_payload, label='user.home')
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
@@ -1486,7 +1453,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, '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, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'})
|
||||
data = request.get_json() or {}
|
||||
|
||||
def _update_profile():
|
||||
@@ -1560,6 +1527,225 @@ def change_password():
|
||||
db.session.rollback()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
|
||||
|
||||
def _get_password_reset_public_base_url() -> str:
|
||||
"""
|
||||
解析密码重置外链基地址,优先公网入口配置。
|
||||
核心逻辑:依次读取 WECOM_PUBLIC_BASE_URL / PUBLIC_BASE_URL / WECOM_NOTIFY_BASE_URL。
|
||||
Returns:
|
||||
去掉尾斜杠的基地址;均未配置时返回空字符串。
|
||||
"""
|
||||
for key in ('WECOM_PUBLIC_BASE_URL', 'PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'):
|
||||
base = _clean_str(current_app.config.get(key))
|
||||
if base:
|
||||
return base.rstrip('/')
|
||||
return ''
|
||||
|
||||
|
||||
def _build_password_reset_url(token: str) -> str:
|
||||
"""
|
||||
构造带 token 的密码重置页 URL。
|
||||
@param token: reset_token 明文
|
||||
Returns:
|
||||
完整重置链接
|
||||
Raises:
|
||||
RuntimeError: 公网基地址未配置
|
||||
"""
|
||||
base = _get_password_reset_public_base_url()
|
||||
if not base:
|
||||
raise RuntimeError('Password reset public base URL is not configured')
|
||||
return f'{base}/reset-password?token={token}'
|
||||
|
||||
|
||||
def _password_reset_rate_limit_state(key: str, *, window_seconds: int = 300) -> tuple[bool, int]:
|
||||
"""
|
||||
判断找回密码是否触发限流,并在允许时记录本次请求时间。
|
||||
@param key: 限流键,通常为 employee_id + IP
|
||||
@param window_seconds: 窗口秒数,默认 5 分钟
|
||||
Returns:
|
||||
(allowed, retry_after_seconds):allowed 为 False 时 retry_after_seconds 为剩余等待秒数
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
last = _PASSWORD_RESET_RATE_CACHE.get(key)
|
||||
if last:
|
||||
elapsed = (now - last).total_seconds()
|
||||
if elapsed < window_seconds:
|
||||
return False, max(1, int(window_seconds - elapsed))
|
||||
_PASSWORD_RESET_RATE_CACHE[key] = now
|
||||
return True, 0
|
||||
|
||||
|
||||
def _check_password_reset_rate_limit(key: str, *, window_seconds: int = 300) -> bool:
|
||||
"""
|
||||
简易内存限流,防止同工号/IP 频繁触发找回密码。
|
||||
@param key: 限流键,通常为 employee_id + IP
|
||||
@param window_seconds: 窗口秒数,默认 5 分钟
|
||||
Returns:
|
||||
True 表示允许继续;False 表示应拒绝
|
||||
"""
|
||||
allowed, _ = _password_reset_rate_limit_state(key, window_seconds=window_seconds)
|
||||
return allowed
|
||||
|
||||
|
||||
def _sync_casdoor_password_for_reset(user: User, new_password: str):
|
||||
"""
|
||||
Token 重置场景下将新密码同步至 Casdoor(无旧密码校验)。
|
||||
核心逻辑:Casdoor 已配置时调用 set-password,oldPassword 传空串(与 change-password fallback 一致)。
|
||||
@param user: 本地用户
|
||||
@param new_password: 新密码明文
|
||||
Raises:
|
||||
AppError: Casdoor 策略或 IdP 同步失败
|
||||
"""
|
||||
if not _is_casdoor_configured():
|
||||
return
|
||||
user_owner = _casdoor_user_owner()
|
||||
try:
|
||||
_casdoor_set_password(user_owner, user.username, '', new_password)
|
||||
except RuntimeError as exc:
|
||||
if _is_casdoor_user_missing_error(str(exc)):
|
||||
_raise_casdoor_user_not_in_idp(exc)
|
||||
_raise_casdoor_set_password_error(exc)
|
||||
|
||||
|
||||
def _password_reset_rate_key(employee_id: str) -> str:
|
||||
"""
|
||||
生成找回密码限流键。
|
||||
@param employee_id: 工号
|
||||
Returns:
|
||||
employee_id 与客户端 IP 组合键
|
||||
"""
|
||||
client_ip = request.headers.get('X-Forwarded-For', request.remote_addr) or 'unknown'
|
||||
return f'{employee_id}:{client_ip}'
|
||||
|
||||
|
||||
@user_bp.route('/reset-password-by-wecom', methods=['POST'])
|
||||
def reset_password_by_wecom():
|
||||
"""
|
||||
通过工号 + 用户名发起找回密码,并向已绑定 wecom_userid 发送 textcard 重置链接。
|
||||
Request JSON: { "employee_id": "...", "username": "..." }
|
||||
"""
|
||||
if not _is_wecom_configured():
|
||||
raise AppError(
|
||||
code='WECOM.RESET_NOT_CONFIGURED',
|
||||
message='WeCom password reset is not configured',
|
||||
http_status=503,
|
||||
details={'missing': _get_wecom_config_missing_fields()},
|
||||
)
|
||||
if not bool(current_app.config.get('WECOM_NOTIFY_ENABLED', True)):
|
||||
raise AppError(
|
||||
code='WECOM.NOTIFY_DISABLED',
|
||||
message='WeCom notification is disabled',
|
||||
http_status=503,
|
||||
)
|
||||
if not _get_password_reset_public_base_url():
|
||||
raise AppError(
|
||||
code='WECOM.RESET_URL_NOT_CONFIGURED',
|
||||
message='Password reset public base URL is not configured',
|
||||
http_status=503,
|
||||
)
|
||||
|
||||
data = request.get_json() or {}
|
||||
employee_id = _clean_str(data.get('employee_id'))
|
||||
username = _clean_str(data.get('username'))
|
||||
if not employee_id:
|
||||
raise ValidationError('Employee ID is required')
|
||||
if not username:
|
||||
raise ValidationError('Username is required')
|
||||
|
||||
rate_key = _password_reset_rate_key(employee_id)
|
||||
allowed, retry_after_seconds = _password_reset_rate_limit_state(rate_key)
|
||||
if not allowed:
|
||||
retry_minutes = max(1, (retry_after_seconds + 59) // 60)
|
||||
current_app.logger.info(
|
||||
'[password_reset] rejected reason=rate_limited employee_id=%s retry_after_seconds=%s',
|
||||
employee_id,
|
||||
retry_after_seconds,
|
||||
)
|
||||
raise AppError(
|
||||
code='AUTH.PASSWORD_RESET_RATE_LIMITED',
|
||||
message='Password reset requests are too frequent',
|
||||
http_status=429,
|
||||
details={
|
||||
'retry_after_seconds': retry_after_seconds,
|
||||
'retry_after_minutes': retry_minutes,
|
||||
},
|
||||
retryable=True,
|
||||
)
|
||||
|
||||
user = db.session.query(User).filter(User.employee_id == employee_id).first()
|
||||
if not user:
|
||||
current_app.logger.info(
|
||||
'[password_reset] noop reason=user_not_found employee_id=%s',
|
||||
employee_id,
|
||||
)
|
||||
return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE})
|
||||
if user.username != username:
|
||||
current_app.logger.info(
|
||||
'[password_reset] noop reason=username_mismatch employee_id=%s user_id=%s',
|
||||
employee_id,
|
||||
user.id,
|
||||
)
|
||||
return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE})
|
||||
if user.status != 'active':
|
||||
current_app.logger.info(
|
||||
'[password_reset] noop reason=account_inactive employee_id=%s user_id=%s',
|
||||
employee_id,
|
||||
user.id,
|
||||
)
|
||||
return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE})
|
||||
if not user.wecom_userid:
|
||||
current_app.logger.info(
|
||||
'[password_reset] noop reason=wecom_unbound employee_id=%s user_id=%s',
|
||||
employee_id,
|
||||
user.id,
|
||||
)
|
||||
return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE})
|
||||
|
||||
token = str(uuid.uuid4())
|
||||
user.reset_token = token
|
||||
user.reset_token_expiry = datetime.utcnow() + timedelta(hours=1)
|
||||
db.session.flush()
|
||||
|
||||
title = '和信AI智能工作台 密码重置'
|
||||
content = (
|
||||
'您发起了和信AI智能工作台密码重置请求。\n'
|
||||
'请在 1 小时内点击下方按钮设置新密码。\n'
|
||||
'如非本人操作,请忽略本消息。'
|
||||
)
|
||||
try:
|
||||
reset_jump_url = _build_password_reset_url(token)
|
||||
result = send_wecom_event_message(
|
||||
event_type='password_reset',
|
||||
user=user,
|
||||
title=title,
|
||||
content=content,
|
||||
jump_url=reset_jump_url,
|
||||
)
|
||||
if not result.get('ok'):
|
||||
db.session.rollback()
|
||||
current_app.logger.warning(
|
||||
'[password_reset] wecom send failed user_id=%s employee_id=%s reason=%s trace_id=%s raw=%s',
|
||||
user.id,
|
||||
employee_id,
|
||||
result.get('reason'),
|
||||
result.get('trace_id'),
|
||||
result.get('raw'),
|
||||
)
|
||||
return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE})
|
||||
|
||||
db.session.commit()
|
||||
current_app.logger.info(
|
||||
'[password_reset] reset link sent user_id=%s employee_id=%s trace_id=%s',
|
||||
user.id,
|
||||
employee_id,
|
||||
result.get('trace_id'),
|
||||
)
|
||||
return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE})
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
current_app.logger.exception('[password_reset] unexpected failure user_id=%s: %s', user.id, exc)
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Failed to request password reset', http_status=500)
|
||||
|
||||
|
||||
@user_bp.route('/reset-password-by-email', methods=['POST'])
|
||||
def reset_password_request():
|
||||
"""
|
||||
@@ -1590,19 +1776,32 @@ def reset_password_confirm():
|
||||
Reset password with token
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
token = data.get('token')
|
||||
token = _clean_str(data.get('token'))
|
||||
new_password = data.get('new_password')
|
||||
if not token or not new_password:
|
||||
raise ValidationError('Token and new password are required')
|
||||
user = db.session.query(User).filter_by(reset_token=token).first()
|
||||
if not user or not user.reset_token_expiry or user.reset_token_expiry < datetime.utcnow():
|
||||
raise ValidationError('Invalid or expired token')
|
||||
current_app.logger.info(
|
||||
'[password_reset] confirm rejected reason=token_invalid token_prefix=%s found_user=%s',
|
||||
token[:8] if token else '',
|
||||
bool(user),
|
||||
)
|
||||
raise AppError(
|
||||
code='AUTH.RESET_TOKEN_INVALID',
|
||||
message='Invalid or expired token',
|
||||
http_status=400,
|
||||
)
|
||||
try:
|
||||
_sync_casdoor_password_for_reset(user, new_password)
|
||||
user.set_password(new_password)
|
||||
user.reset_token = None
|
||||
user.reset_token_expiry = None
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Password has been reset successfully'})
|
||||
except AppError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
|
||||
@@ -1622,33 +1821,28 @@ def get_agent_details(id):
|
||||
has_permission = agent in user.agents
|
||||
if not has_permission:
|
||||
raise ForbiddenError('Access denied')
|
||||
extra_config = agent.extra_config or {}
|
||||
dify_app_type = extra_config.get('dify_app_type') if isinstance(extra_config, dict) else None
|
||||
|
||||
from app.services.agent_registry.resolver import resolve_runtime_provider
|
||||
from app.services.agent_registry.serialization import serialize_agent_for_user_detail
|
||||
|
||||
dify_parameters = None
|
||||
agent_type = str(getattr(agent, 'type', '') or '').strip().lower()
|
||||
if agent_type == 'api' and getattr(agent, 'dify_api_key', None):
|
||||
if resolve_runtime_provider(agent) in {'dify', 'hybrid'} and getattr(agent, 'dify_api_key', None):
|
||||
from app.services.dify import DifyService
|
||||
|
||||
params = DifyService.get_app_parameters(agent)
|
||||
if isinstance(params, dict):
|
||||
dify_parameters = {
|
||||
'file_upload': params.get('file_upload') if isinstance(params.get('file_upload'), dict) else {},
|
||||
'system_parameters': params.get('system_parameters') if isinstance(params.get('system_parameters'), dict) else {},
|
||||
}
|
||||
try:
|
||||
params = DifyService.get_app_parameters(agent)
|
||||
if isinstance(params, dict):
|
||||
dify_parameters = {
|
||||
'file_upload': params.get('file_upload') if isinstance(params.get('file_upload'), dict) else {},
|
||||
'system_parameters': params.get('system_parameters') if isinstance(params.get('system_parameters'), dict) else {},
|
||||
}
|
||||
except Exception as exc:
|
||||
current_app.logger.warning('[user.agents] dify parameters fetch failed agent_id=%s err=%s', id, exc)
|
||||
|
||||
return jsonify({
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'description': agent.description,
|
||||
'type': agent.type,
|
||||
'icon_url': agent.icon_url,
|
||||
'extra_config': extra_config if isinstance(extra_config, dict) else {},
|
||||
'dify_app_type': dify_app_type,
|
||||
'welcome_message': extra_config.get('welcome_message') if isinstance(extra_config, dict) else None,
|
||||
'suggested_questions': extra_config.get('suggested_questions', []) if isinstance(extra_config, dict) else [],
|
||||
'dify_parameters': dify_parameters,
|
||||
})
|
||||
return jsonify(serialize_agent_for_user_detail(
|
||||
agent,
|
||||
dify_parameters=dify_parameters,
|
||||
))
|
||||
|
||||
@user_bp.route('/db', methods=['GET'])
|
||||
def get_db():
|
||||
@@ -1656,45 +1850,3 @@ def get_db():
|
||||
from app import db
|
||||
u = db.session.query(User).filter_by(username='26040006').first()
|
||||
return jsonify({'db': current_app.config.get('SQLALCHEMY_DATABASE_URI'), 'user': u.username if u else None})
|
||||
|
||||
@user_bp.route('/announcements', methods=['GET'])
|
||||
def get_announcements():
|
||||
"""
|
||||
Get active announcements (Public)
|
||||
"""
|
||||
|
||||
def _load_announcements():
|
||||
anns = db.session.query(Announcement.id, Announcement.title, Announcement.content, Announcement.created_at).filter(Announcement.is_active.is_(True)).order_by(Announcement.created_at.desc()).all()
|
||||
return jsonify([{'id': a.id, 'title': a.title, 'content': a.content, 'created_at': a.created_at.isoformat()} for a in anns])
|
||||
try:
|
||||
return _run_db_with_retry(_load_announcements, label='user.announcements')
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('user.announcements retry failed: %s', exc)
|
||||
raise ServiceUnavailableError('Database connection failed')
|
||||
|
||||
@user_bp.route('/announcements', methods=['POST'])
|
||||
def create_announcement():
|
||||
"""
|
||||
Create announcement (Admin only)
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user or user.role != 'admin':
|
||||
raise ForbiddenError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
if not data.get('title') or not data.get('content'):
|
||||
raise ValidationError('Missing fields')
|
||||
ann = Announcement(title=data['title'], content=data['content'], is_active=True)
|
||||
db.session.add(ann)
|
||||
db.session.commit()
|
||||
return (jsonify({'message': 'Created', 'id': ann.id}), 201)
|
||||
|
||||
@user_bp.route('/announcements/<int:id>', methods=['DELETE'])
|
||||
def delete_announcement(id):
|
||||
user = _get_current_user()
|
||||
if not user or user.role != 'admin':
|
||||
raise ForbiddenError('Unauthorized')
|
||||
ann = db.session.get(Announcement, id)
|
||||
if ann:
|
||||
db.session.delete(ann)
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Deleted'})
|
||||
@@ -0,0 +1,18 @@
|
||||
"""
|
||||
backend/app/api/workspace/__init__.py
|
||||
|
||||
用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check、announcements)。
|
||||
依赖:workspace 各子模块 blueprint。
|
||||
逻辑:import 子模块注册路由;register_blueprints 从本包导入各 bp。
|
||||
"""
|
||||
from app.api.workspace.announcements import workspace_announcements_bp
|
||||
from app.api.workspace.file_check import workspace_file_check_bp
|
||||
from app.api.workspace.schedule import workspace_schedule_bp
|
||||
from app.api.workspace.shipping_notice import workspace_shipping_notice_bp
|
||||
|
||||
__all__ = [
|
||||
'workspace_announcements_bp',
|
||||
'workspace_file_check_bp',
|
||||
'workspace_schedule_bp',
|
||||
'workspace_shipping_notice_bp',
|
||||
]
|
||||
@@ -0,0 +1,27 @@
|
||||
"""
|
||||
backend/app/api/workspace/announcements.py
|
||||
|
||||
用途:工作台/登录页只读公告列表 API。
|
||||
依赖:services/admin/announcement_service(读活跃公告)。
|
||||
逻辑:GET /announcements 无需登录;管理 CRUD 见 api/admin/announcements.py。
|
||||
"""
|
||||
from flask import Blueprint, jsonify
|
||||
|
||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.admin import announcement_service
|
||||
|
||||
workspace_announcements_bp = Blueprint('workspace_announcements', __name__)
|
||||
|
||||
|
||||
@workspace_announcements_bp.route('/announcements', methods=['GET'])
|
||||
def list_active_announcements():
|
||||
"""返回已发布的公司公告(公开,供登录页与工作台展示)。"""
|
||||
try:
|
||||
return jsonify(announcement_service.list_active_announcements())
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
from flask import current_app
|
||||
|
||||
current_app.logger.warning('workspace.announcements query failed: %s', exc)
|
||||
raise ServiceUnavailableError('Database connection failed')
|
||||
@@ -0,0 +1,126 @@
|
||||
"""
|
||||
backend/app/api/workspace/file_check.py
|
||||
|
||||
用途:工作台文件检核进度轮询 API(对话页 tool_run_progress)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、file_check_tools、schedule.query_service。
|
||||
逻辑:鉴权后查询 ScheduleRun 进度;register_blueprints 经 workspace 包注册。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.file_check_tools.chat_log_run_resolver import find_run_for_chat_log_with_source
|
||||
from app.services.schedule.query_service import get_run, serialize_run
|
||||
|
||||
workspace_file_check_bp = Blueprint("workspace_file_check", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""
|
||||
校验当前登录用户。
|
||||
Raises:
|
||||
UnauthorizedError: 未认证。
|
||||
"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
def serialize_file_judgement(payload: dict) -> dict:
|
||||
"""序列化检核判定统计(读取 response_summary_json.file_judgement)。"""
|
||||
response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {}
|
||||
judgement = response_summary.get('file_judgement')
|
||||
if not isinstance(judgement, dict):
|
||||
judgement = {}
|
||||
return {
|
||||
'qualified_count': int(judgement.get('qualified_count') or 0),
|
||||
'unqualified_count': int(judgement.get('unqualified_count') or 0),
|
||||
'manual_count': int(judgement.get('manual_count') or 0),
|
||||
'dify_error_count': int(judgement.get('dify_error_count') or 0),
|
||||
'invalid_result_count': int(judgement.get('invalid_result_count') or 0),
|
||||
'business_manual_count': int(judgement.get('business_manual_count') or 0),
|
||||
'system_error_count': int(judgement.get('system_error_count') or 0),
|
||||
'dify_timeout_count': int(judgement.get('dify_timeout_count') or 0),
|
||||
'invalid_output_count': int(judgement.get('invalid_output_count') or 0),
|
||||
'attachment_error_count': int(judgement.get('attachment_error_count') or 0),
|
||||
}
|
||||
|
||||
def serialize_current_step(payload: dict) -> dict | None:
|
||||
response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {}
|
||||
current_step = response_summary.get('current_step') if isinstance(response_summary.get('current_step'), dict) else None
|
||||
if not current_step:
|
||||
return None
|
||||
return {'step': str(current_step.get('step') or ''), 'label': str(current_step.get('label') or current_step.get('step') or ''), 'row_id': current_step.get('row_id'), 'started_at': current_step.get('started_at'), 'processed_count': int(current_step.get('processed_count') or 0), 'success_count': int(current_step.get('success_count') or 0), 'failed_count': int(current_step.get('failed_count') or 0), 'skipped_count': int(current_step.get('skipped_count') or 0)}
|
||||
|
||||
def _serialize_progress_run(run: ScheduleRun) -> dict:
|
||||
payload = serialize_run(run)
|
||||
total = int(payload.get('total_count') or 0)
|
||||
success = int(payload.get('success_count') or 0)
|
||||
failed = int(payload.get('failed_count') or 0)
|
||||
skipped = int(payload.get('skipped_count') or 0)
|
||||
processed = success + failed + skipped
|
||||
percent = int(round(processed / total * 100)) if total > 0 else 0
|
||||
percent = max(0, min(percent, 100))
|
||||
return {'run_id': payload['id'], 'run_no': payload['run_no'], 'task_id': payload['schedule_task_id'], 'title': payload.get('schedule_name') or '', 'status': payload['status'], 'total_count': total, 'processed_count': processed, 'success_count': success, 'failed_count': failed, 'skipped_count': skipped, 'judgement': serialize_file_judgement(payload), 'current_step': serialize_current_step(payload), 'progress_percent': percent, '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': f'/api/workspace/file-check/runs/{run.id}/excel' if payload.get('excel_file_name') else None}, 'knowledge_base': {'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')}}
|
||||
|
||||
@workspace_file_check_bp.route('/file-check/runs/for-log', methods=['GET'])
|
||||
def workspace_file_check_run_for_log():
|
||||
"""按 chat_log_id + schedule_task_id 返回该轮问答绑定的检核批次。"""
|
||||
_require_user()
|
||||
task_id = request.args.get('task_id', type=int)
|
||||
chat_log_id = request.args.get('chat_log_id', type=int)
|
||||
if not task_id or task_id <= 0:
|
||||
raise ValidationError("task_id_required")
|
||||
if not chat_log_id or chat_log_id <= 0:
|
||||
raise ValidationError("chat_log_id_required")
|
||||
match = find_run_for_chat_log_with_source(task_id=task_id, chat_log_id=chat_log_id)
|
||||
return jsonify({
|
||||
'ok': True,
|
||||
'run': _serialize_progress_run(match.run) if match.run else None,
|
||||
'match_source': match.match_source,
|
||||
})
|
||||
|
||||
@workspace_file_check_bp.route('/file-check/runs/for-session', methods=['GET'])
|
||||
def workspace_file_check_run_for_session():
|
||||
"""已废弃:请改用 for-log?chat_log_id=。保留接口避免旧客户端 404。"""
|
||||
_require_user()
|
||||
return jsonify({'ok': True, 'run': None, 'match_source': None, 'session_updated_at': None})
|
||||
|
||||
@workspace_file_check_bp.route('/file-check/runs/active', methods=['GET'])
|
||||
def workspace_file_check_active_run():
|
||||
"""查询当前进行中的检核批次;优先按 schedule_task_id(query: task_id)过滤。"""
|
||||
_require_user()
|
||||
task_id = request.args.get('task_id', type=int)
|
||||
conversation_id = str(request.args.get('conversation_id') or '').strip()
|
||||
query = ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id).filter(ScheduleRun.status == 'running')
|
||||
if task_id is not None:
|
||||
query = query.filter(ScheduleRun.schedule_task_id == task_id)
|
||||
rows = query.order_by(ScheduleRun.id.desc()).all()
|
||||
if task_id is not None:
|
||||
run = rows[0] if rows else None
|
||||
else:
|
||||
run = next((row for row in rows if not conversation_id or str((row.api_request_json or {}).get('conversation_id') or '').strip() == conversation_id), None)
|
||||
return jsonify({'ok': True, 'run': _serialize_progress_run(run) if run else None})
|
||||
|
||||
@workspace_file_check_bp.route('/file-check/runs/<int:run_id>', methods=['GET'])
|
||||
def workspace_file_check_run_detail(run_id: int):
|
||||
_require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('run_not_found')
|
||||
return jsonify({'ok': True, 'run': _serialize_progress_run(run)})
|
||||
|
||||
@workspace_file_check_bp.route('/file-check/runs/<int:run_id>/excel', methods=['GET'])
|
||||
def workspace_file_check_run_excel(run_id: int):
|
||||
_require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('run_not_found')
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError('excel_not_found')
|
||||
return send_file(BytesIO(run.excel_file_data), as_attachment=True, download_name=run.excel_file_name or f'{run.run_no}.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
@@ -0,0 +1,80 @@
|
||||
"""
|
||||
backend/app/api/workspace/schedule.py
|
||||
|
||||
用途:工作台排程运行记录查询 API。
|
||||
依赖:app.core.auth.jwt、app.core.errors、schedule.query_service。
|
||||
逻辑:鉴权后只读查询 ScheduleRun;register_blueprints 经 workspace 包注册。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError
|
||||
from app.services.schedule.query_service import can_view_run, get_run, list_runs, serialize_run
|
||||
|
||||
workspace_schedule_bp = Blueprint("workspace_schedule", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""校验当前用户;未登录时抛出 UnauthorizedError。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
@workspace_schedule_bp.route("/schedule-runs", methods=["GET"])
|
||||
def workspace_schedule_runs():
|
||||
user = _require_user()
|
||||
status = str(request.args.get("status") or "").strip() or None
|
||||
schedule_name = str(request.args.get("schedule_name") or "").strip() or None
|
||||
started_after_str = request.args.get("started_after")
|
||||
started_before_str = request.args.get("started_before")
|
||||
started_after = datetime.fromisoformat(started_after_str.replace("Z", "+00:00")) if started_after_str else None
|
||||
started_before = datetime.fromisoformat(started_before_str.replace("Z", "+00:00")) if started_before_str else None
|
||||
limit = int(request.args.get("limit") or 100)
|
||||
return jsonify(
|
||||
list_runs(
|
||||
notify_user_id=user.id,
|
||||
schedule_name=schedule_name,
|
||||
status=status,
|
||||
started_after=started_after,
|
||||
started_before=started_before,
|
||||
limit=limit,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@workspace_schedule_bp.route("/schedule-runs/<int:run_id>", methods=["GET"])
|
||||
def workspace_schedule_run_detail(run_id: int):
|
||||
user = _require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("Not found")
|
||||
if not can_view_run(run, user.id):
|
||||
raise ForbiddenError("Forbidden")
|
||||
return jsonify(serialize_run(run))
|
||||
|
||||
|
||||
@workspace_schedule_bp.route("/schedule-runs/<int:run_id>/excel", methods=["GET"])
|
||||
def workspace_schedule_run_excel(run_id: int):
|
||||
from io import BytesIO
|
||||
|
||||
user = _require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("Not found")
|
||||
if not can_view_run(run, user.id):
|
||||
raise ForbiddenError("Forbidden")
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError("Excel not found")
|
||||
buf = BytesIO(run.excel_file_data)
|
||||
return send_file(
|
||||
buf,
|
||||
as_attachment=True,
|
||||
download_name=run.excel_file_name or "result.xlsx",
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
@@ -0,0 +1,741 @@
|
||||
"""
|
||||
backend/app/api/workspace/shipping_notice.py
|
||||
|
||||
用途:HXOPS 工作台与聊天前端使用的发货通知用户态 API。
|
||||
依赖:app.core.auth.jwt、app.core.errors、shipping_notice.query_service / tools / notice_upload / ui_state。
|
||||
逻辑:薄路由层鉴权与参数校验;register_blueprints 经 workspace 包注册。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from flask import Blueprint, g, jsonify, 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.response import ok
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
|
||||
from app.services.shipping_notice.constants import (
|
||||
AUTO_CHAIN_FALLBACK,
|
||||
CP_EXPORT_GENERATED,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
MAP_JSON,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import switch_batch_focus
|
||||
from app.services.shipping_notice.query_service import (
|
||||
EXPORT_MIME_TYPE,
|
||||
get_batch_for_user,
|
||||
get_conversation_batch_workspace,
|
||||
get_focus_task_for_batch,
|
||||
get_task_for_user,
|
||||
list_batches_for_user,
|
||||
list_tasks_for_batch,
|
||||
list_tasks_for_user,
|
||||
resolve_task_export_download,
|
||||
serialize_batch_summary,
|
||||
serialize_task_detail,
|
||||
serialize_task_summary,
|
||||
task_export_error_message,
|
||||
)
|
||||
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
|
||||
|
||||
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""
|
||||
校验当前登录用户;未认证时抛出 UnauthorizedError,由全局 handler 输出标准错误 JSON。
|
||||
Returns:
|
||||
User 模型实例。
|
||||
Raises:
|
||||
UnauthorizedError: 无有效 JWT 或 legacy header。
|
||||
"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _ok(payload: dict):
|
||||
"""返回带 request_id 的成功 envelope,供工作台读接口复用。"""
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
|
||||
def workspace_shipping_tasks():
|
||||
"""列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
|
||||
user = _require_user()
|
||||
batch_no = str(request.args.get('batch_no') or '').strip() or None
|
||||
process_status = str(request.args.get('process_status') or '').strip() or None
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
return jsonify(list_tasks_for_user(user.id, batch_no=batch_no, process_status=process_status, limit=limit))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches', methods=['GET'])
|
||||
def workspace_shipping_batches():
|
||||
"""列出当前用户的发货批次摘要。"""
|
||||
user = _require_user()
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
return jsonify(list_batches_for_user(user.id, limit=limit))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-conversations/<conversation_id>/batch-workspace', methods=['GET'])
|
||||
def workspace_shipping_conversation_batch_workspace(conversation_id: str):
|
||||
"""返回一个 Agent 会话下的多批次执行工作台快照。"""
|
||||
user = _require_user()
|
||||
return _ok(get_conversation_batch_workspace(conversation_id, user.id))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-notices', methods=['POST'])
|
||||
def workspace_create_shipping_batch_from_notices():
|
||||
"""接收多份发货通知附件,创建批次并交给后台编排器逐票推进。"""
|
||||
user = _require_user()
|
||||
uploads = request.files.getlist('files')
|
||||
if not uploads:
|
||||
single = request.files.get('file')
|
||||
if single:
|
||||
uploads = [single]
|
||||
if not uploads:
|
||||
raise ValidationError('files is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.batch_from_notices import (
|
||||
create_shipping_batch_from_notice_items,
|
||||
intake_notice_uploads_for_batch,
|
||||
)
|
||||
from app.services.shipping_notice.batch_create_idempotency import (
|
||||
normalize_create_idempotency_key,
|
||||
warn_missing_create_idempotency_key,
|
||||
)
|
||||
from app.services.shipping_notice.notice_upload import cleanup_temp_notice_uploads
|
||||
conversation_id = str(request.form.get('conversation_id') or '').strip()
|
||||
idempotency_key = normalize_create_idempotency_key(
|
||||
request.headers.get('Idempotency-Key') or request.form.get('idempotency_key')
|
||||
)
|
||||
if not idempotency_key:
|
||||
warn_missing_create_idempotency_key(source='workspace_create_shipping_batch_from_notices')
|
||||
temp_request_id = str(getattr(g, 'request_id', None) or uuid.uuid4().hex)
|
||||
try:
|
||||
notice_items, file_summary = intake_notice_uploads_for_batch(temp_request_id, uploads)
|
||||
finally:
|
||||
cleanup_temp_notice_uploads(temp_request_id)
|
||||
|
||||
created = create_shipping_batch_from_notice_items(
|
||||
user_id=user.id,
|
||||
conversation_id=conversation_id or None,
|
||||
notice_items=notice_items,
|
||||
file_summary=file_summary,
|
||||
create_idempotency_key=idempotency_key,
|
||||
)
|
||||
return _ok(created)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>', methods=['GET'])
|
||||
def workspace_shipping_batch_detail(batch_no: str):
|
||||
"""
|
||||
返回批次详情与聚合 UI State。
|
||||
|
||||
核心逻辑:工作台详情页与独立 `/ui-state` 端点共享同一份批次状态构建结果,
|
||||
避免批次摘要、焦点任务和任务卡片在不同接口里各自推导造成漂移。
|
||||
"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok(build_batch_ui_state(batch))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/ui-state', methods=['GET'])
|
||||
def workspace_shipping_batch_ui_state(batch_no: str):
|
||||
"""
|
||||
返回批次级 UI State。
|
||||
|
||||
核心逻辑:供右侧工作台、步骤条与批次任务卡统一读取同源状态,
|
||||
保持与批次详情接口返回的 `focus_task_ui_state/tasks[].ui_state` 完全一致。
|
||||
"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok(build_batch_ui_state(batch))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/tasks', methods=['GET'])
|
||||
def workspace_shipping_batch_tasks(batch_no: str):
|
||||
"""返回指定批次下的任务列表。"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(list_tasks_for_batch(batch_no, user.id))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['GET'])
|
||||
def workspace_shipping_batch_focus_task(batch_no: str):
|
||||
"""返回指定批次当前焦点任务的摘要。"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
focus_task = get_focus_task_for_batch(batch_no, user.id)
|
||||
if not focus_task:
|
||||
raise NotFoundError('Focus task not found')
|
||||
return jsonify(serialize_task_summary(focus_task))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['POST'])
|
||||
def workspace_switch_shipping_batch_focus_task(batch_no: str):
|
||||
"""切换批次当前焦点任务,供工作台在同批次任务间跳转。"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
task_no = str(data.get('task_no') or data.get('target_task_no') or '').strip()
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if not task_no:
|
||||
raise ValidationError('task_no is required')
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task or task.batch_id != batch.id:
|
||||
raise NotFoundError('Task not found in batch')
|
||||
switch_batch_focus(
|
||||
batch,
|
||||
task,
|
||||
source='workspace_api',
|
||||
comment=comment or None,
|
||||
extra={'actor_user_id': user.id},
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify({'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)})
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['POST'])
|
||||
def workspace_create_shipping_task():
|
||||
"""创建单个发货任务,适用于手工录入或聊天入口先建单。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = {'user_id': user.id}
|
||||
source_type = str(data.get('source_type') or '').strip()
|
||||
if source_type:
|
||||
payload['source_type'] = source_type
|
||||
conversation_id = str(data.get('conversation_id') or '').strip()
|
||||
if conversation_id:
|
||||
payload['conversation_id'] = conversation_id
|
||||
raw_content = str(data.get('raw_content') or '').strip()
|
||||
if raw_content:
|
||||
payload['raw_content'] = raw_content
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.create_task(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
|
||||
def workspace_create_shipping_task_from_notice():
|
||||
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。"""
|
||||
user = _require_user()
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
raise ValidationError('file is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.notice_upload import guess_source_type, intake_notice_attachment, notice_source_file_type
|
||||
filename = upload.filename or 'notice'
|
||||
raw = upload.read() or b''
|
||||
source_file_type = notice_source_file_type(upload)
|
||||
source_type = guess_source_type(filename)
|
||||
conversation_id = str(request.form.get('conversation_id') or '').strip()
|
||||
payload = {'user_id': user.id, 'source_type': source_type}
|
||||
if conversation_id:
|
||||
payload['conversation_id'] = conversation_id
|
||||
created = shipping_tools.create_task(payload)
|
||||
task_id = str(created.get('task_id') or '').strip()
|
||||
if not task_id:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='failed to create task', http_status=500)
|
||||
intake = intake_notice_attachment(
|
||||
filename=filename,
|
||||
raw=raw,
|
||||
source_file_type=source_file_type,
|
||||
storage='task',
|
||||
task_no=task_id,
|
||||
)
|
||||
if not intake.accepted:
|
||||
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint
|
||||
return jsonify({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED)})
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
if task:
|
||||
task.raw_content = intake.text
|
||||
task.source_file_name = intake.filename or task.source_file_name
|
||||
task.source_file_type = intake.source_file_type or task.source_file_type
|
||||
db.session.commit()
|
||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
|
||||
orchestrator_started = start_task_orchestrator(task_id)
|
||||
return jsonify({'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}})
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/replace-notice', methods=['POST'])
|
||||
def workspace_replace_shipping_task_notice(task_no: str):
|
||||
"""重新上传发货通知并覆盖当前任务,不新建批次/任务。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
raise ValidationError('file is required')
|
||||
from app.services.shipping_notice import task_workflow
|
||||
from app.services.shipping_notice.notice_upload import intake_notice_attachment, notice_source_file_type
|
||||
intake = intake_notice_attachment(
|
||||
filename=upload.filename or 'notice',
|
||||
raw=upload.read() or b'',
|
||||
source_file_type=notice_source_file_type(upload),
|
||||
storage='task',
|
||||
task_no=task.task_no,
|
||||
)
|
||||
task.source_type = intake.source_type or task.source_type
|
||||
result = task_workflow.replace_task_notice(
|
||||
task,
|
||||
raw_text=intake.text,
|
||||
source_file_name=intake.filename,
|
||||
source_file_type=intake.source_file_type,
|
||||
warnings=list(intake.warnings),
|
||||
)
|
||||
data = result.setdefault('data', {})
|
||||
if isinstance(data, dict):
|
||||
data['notice_upload'] = intake.to_notice_upload_meta()
|
||||
return _ok(result)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>', methods=['GET'])
|
||||
def workspace_shipping_task_detail(task_no: str):
|
||||
"""
|
||||
返回指定任务的详情快照与内嵌 UI State。
|
||||
|
||||
核心逻辑:详情接口直接内嵌 `ui_state`,让页面首屏读取任务详情时即可拿到
|
||||
checkpoint / action_buttons / steps,减少前端二次推导与竞态刷新。
|
||||
"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok({
|
||||
**serialize_task_detail(task),
|
||||
'ui_state': build_task_ui_state(task),
|
||||
})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/ui-state', methods=['GET'])
|
||||
def workspace_shipping_task_ui_state(task_no: str):
|
||||
"""
|
||||
返回单票任务 UI State。
|
||||
|
||||
核心逻辑:Chat 顶部步骤条、动作按钮和工作台详情统一复用这里的状态机投影,
|
||||
避免不同前端入口重复拼装按钮集合。
|
||||
"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok(build_task_ui_state(task))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET'])
|
||||
def workspace_shipping_task_chat_actions(task_no: str):
|
||||
"""返回聊天气泡侧所需的动作按钮与检查点信息。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(build_chat_actions_payload(task))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry', methods=['POST'])
|
||||
def workspace_retry_shipping_task(task_no: str):
|
||||
"""重试当前任务,适用于超时、解析失败或自动推进中断后的恢复。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = {'task_id': task.task_no}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.retry_task(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/upload-inventory', methods=['POST'])
|
||||
def workspace_upload_shipping_inventory(task_no: str):
|
||||
"""用户态上传库存 Excel,并在服务端完成解析。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
upload = request.files.get('file')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.upload_inventory_file(task.task_no, upload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/confirm-inventory-source', methods=['POST'])
|
||||
def workspace_confirm_shipping_inventory_source(task_no: str):
|
||||
"""确认当前任务的库存 RPA 来源,并继续触发库存导出。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
source_code = str(data.get('source_code') or '').strip()
|
||||
if not source_code:
|
||||
raise ValidationError('source_code is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.confirm_inventory_source({
|
||||
'task_id': task.task_no,
|
||||
'source_code': source_code,
|
||||
'_trusted_user_id': user.id,
|
||||
}))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/apply-inventory-mapping', methods=['POST'])
|
||||
def workspace_apply_inventory_mapping(task_no: str):
|
||||
"""提交库存字段映射,并允许在工作台侧自动回退到下一步。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
data = request.get_json(silent=True) or {}
|
||||
map_json = data.get(MAP_JSON)
|
||||
if not isinstance(map_json, dict) or not map_json:
|
||||
raise ValidationError(f'{MAP_JSON} is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {'task_id': task.task_no, MAP_JSON: map_json, AUTO_CHAIN_FALLBACK: True}
|
||||
return jsonify(shipping_tools.apply_inventory_mapping(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/submit-decision', methods=['POST'])
|
||||
def workspace_submit_shipping_decision(task_no: str):
|
||||
"""以用户态提交人工决策,绕过 Dify Tool 路由直接驱动状态机。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
decision = str(data.get('decision') or '').strip()
|
||||
if not decision:
|
||||
raise ValidationError('decision is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {'task_id': task.task_no, 'decision': decision, AUTO_CHAIN_FALLBACK: True, 'event_source': 'workspace_api'}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.submit_decision(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-fields', methods=['POST'])
|
||||
def workspace_update_shipping_notice_fields(task_no: str):
|
||||
"""更新发货通知单头字段。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
fields = data.get('fields')
|
||||
if not isinstance(fields, dict) or not fields:
|
||||
raise ValidationError('fields is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {'task_id': task.task_no, 'fields': fields}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.update_notice_fields(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-line', methods=['POST'])
|
||||
def workspace_update_shipping_notice_line(task_no: str):
|
||||
"""更新发货通知中的指定订单行。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
line_index = int(data.get('line_index'))
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('line_index is required')
|
||||
patch = data.get('patch')
|
||||
if not isinstance(patch, dict) or not patch:
|
||||
raise ValidationError('patch is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {'task_id': task.task_no, 'line_index': line_index, 'patch': patch}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.update_notice_line(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/add-notice-line', methods=['POST'])
|
||||
def workspace_add_shipping_notice_line(task_no: str):
|
||||
"""为发货通知新增订单行。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
line = data.get('line')
|
||||
if not isinstance(line, dict) or not line:
|
||||
raise ValidationError('line is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {'task_id': task.task_no, 'line': line}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.add_notice_line(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/remove-notice-line', methods=['POST'])
|
||||
def workspace_remove_shipping_notice_line(task_no: str):
|
||||
"""删除发货通知中的指定订单行。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
line_index = int(data.get('line_index'))
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('line_index is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {'task_id': task.task_no, 'line_index': line_index}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.remove_notice_line(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/auto-progress', methods=['POST'])
|
||||
def workspace_auto_progress_shipping_task(task_no: str):
|
||||
"""用户态触发 auto_progress,作为聊天前端的兜底自动推进入口。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload: dict = {'task_id': task.task_no}
|
||||
for key in ('lang', 'locale', 'language'):
|
||||
if data.get(key):
|
||||
payload[key] = data[key]
|
||||
break
|
||||
result = shipping_tools.auto_progress(payload)
|
||||
if isinstance(result, dict) and result.get('status') == 'ok':
|
||||
gen_data = result.get('data')
|
||||
if isinstance(gen_data, dict) and gen_data.get('export_file_path'):
|
||||
gen_data = {**gen_data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}
|
||||
result = {**result, 'data': gen_data}
|
||||
return jsonify(result)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/match-inventory', methods=['POST'])
|
||||
def workspace_match_shipping_inventory(task_no: str):
|
||||
"""执行库存匹配,并在生成 Excel 后补充前端可直接下载的链接。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint, human_options_for_checkpoint
|
||||
matched = shipping_tools.match_inventory({'task_id': task.task_no, AUTO_CHAIN_FALLBACK: True})
|
||||
if not isinstance(matched, dict):
|
||||
return jsonify(matched)
|
||||
data = matched.get('data')
|
||||
if isinstance(data, dict) and data.get('export_file_path'):
|
||||
matched = {**matched, 'data': {**data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}}
|
||||
checkpoint = matched.get('checkpoint') or CP_EXPORT_GENERATED
|
||||
if matched.get('status') == 'ok' and data and data.get('export_file_path'):
|
||||
matched['checkpoint'] = checkpoint
|
||||
if 'human_options' not in matched:
|
||||
options = human_options_for_checkpoint(checkpoint)
|
||||
if options is not None:
|
||||
matched['human_options'] = options
|
||||
if 'action_buttons' not in matched:
|
||||
buttons = action_buttons_for_checkpoint(checkpoint)
|
||||
if buttons:
|
||||
matched['action_buttons'] = buttons
|
||||
return jsonify(matched)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/mark-manual-uploaded', methods=['POST'])
|
||||
def workspace_mark_manual_uploaded(task_no: str):
|
||||
"""标记货代系统已人工上传完成,无需再等待 RPA 回执。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'}))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry-upload', methods=['POST'])
|
||||
def workspace_retry_shipping_upload(task_no: str):
|
||||
"""用户态重试上传货代系统,直接触发既有 RPA 上传链路。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'retry_upload'}))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/generate-excel', methods=['POST'])
|
||||
def workspace_generate_shipping_excel(task_no: str):
|
||||
"""为指定任务生成出货 Excel,并补充工作台下载链接。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
result = shipping_tools.generate_excel({'task_id': task.task_no})
|
||||
if isinstance(result, dict) and result.get('status') == 'ok':
|
||||
data = result.get('data')
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
result['data'] = data
|
||||
data['download_url'] = f'/api/workspace/shipping-tasks/{task.task_no}/export'
|
||||
return jsonify(result)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
|
||||
def workspace_shipping_task_export(task_no: str):
|
||||
"""下载当前用户可访问任务的出货 Excel。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
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)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['GET'])
|
||||
def workspace_list_shipping_notice_intakes():
|
||||
"""列出当前会话下未消费的活跃接入记录。"""
|
||||
user = _require_user()
|
||||
conversation_id = str(request.args.get('conversation_id') or '').strip() or None
|
||||
status = str(request.args.get('status') or '').strip().lower()
|
||||
from app.services.shipping_notice.intake_service import list_active_intakes_for_conversation
|
||||
|
||||
if status and status != 'active':
|
||||
return _ok({'items': []})
|
||||
items = list_active_intakes_for_conversation(user_id=user.id, conversation_id=conversation_id)
|
||||
return _ok({'items': items})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['POST'])
|
||||
def workspace_create_shipping_notice_intake():
|
||||
"""基于 FileAsset 创建发货通知接入记录并投递预解析任务。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
asset_no = str(body.get('asset_no') or '').strip()
|
||||
if not asset_no:
|
||||
raise ValidationError('asset_no is required')
|
||||
conversation_id = str(body.get('conversation_id') or '').strip() or None
|
||||
from app.services.shipping_notice.intake_service import create_shipping_notice_intake
|
||||
|
||||
data = create_shipping_notice_intake(
|
||||
user_id=user.id,
|
||||
asset_no=asset_no,
|
||||
conversation_id=conversation_id,
|
||||
)
|
||||
return ok(data, request_id=getattr(g, 'request_id', None), status=202)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/<intake_no>', methods=['GET'])
|
||||
def workspace_get_shipping_notice_intake(intake_no: str):
|
||||
"""查询单个接入记录。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.intake_service import get_intake_detail
|
||||
|
||||
return _ok(get_intake_detail(user_id=user.id, intake_no=intake_no))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/status', methods=['POST'])
|
||||
def workspace_shipping_notice_intake_statuses():
|
||||
"""批量查询接入状态。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
intake_nos = body.get('intake_nos')
|
||||
if not isinstance(intake_nos, list):
|
||||
raise ValidationError('intake_nos is required')
|
||||
from app.services.shipping_notice.intake_service import get_intake_statuses
|
||||
|
||||
return _ok({'items': get_intake_statuses(user_id=user.id, intake_nos=intake_nos)})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/<intake_no>/retry', methods=['POST'])
|
||||
def workspace_retry_shipping_notice_intake(intake_no: str):
|
||||
"""重试失败的预解析。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.intake_service import retry_intake_parse
|
||||
|
||||
return _ok(retry_intake_parse(user_id=user.id, intake_no=intake_no))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/<intake_no>', methods=['DELETE'])
|
||||
def workspace_cancel_shipping_notice_intake(intake_no: str):
|
||||
"""取消未消费接入记录。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.intake_service import cancel_intake
|
||||
|
||||
cancel_intake(user_id=user.id, intake_no=intake_no)
|
||||
return _ok({'cancelled': True})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/intakes/<intake_no>/duplicate-resolution',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_resolve_shipping_notice_duplicate(intake_no: str):
|
||||
"""保存发货通知重复检测决策。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
action = str(body.get('action') or '').strip()
|
||||
target_task_no = str(body.get('target_task_no') or '').strip() or None
|
||||
reason = str(body.get('reason') or '').strip() or None
|
||||
from app.services.shipping_notice.intake_service import resolve_intake_duplicate
|
||||
|
||||
return _ok(
|
||||
resolve_intake_duplicate(
|
||||
user_id=user.id,
|
||||
intake_no=intake_no,
|
||||
action=action,
|
||||
target_task_no=target_task_no,
|
||||
reason=reason,
|
||||
actor=user,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/intakes/<intake_no>/duplicate-refresh',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_refresh_shipping_notice_duplicate(intake_no: str):
|
||||
"""重新执行重复检测。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.intake_service import refresh_intake_duplicate_detection
|
||||
|
||||
return _ok(refresh_intake_duplicate_detection(user_id=user.id, intake_no=intake_no))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-intakes', methods=['POST'])
|
||||
def workspace_create_shipping_batch_from_intakes():
|
||||
"""从已解析接入记录确认建批。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
intake_nos = body.get('intake_nos')
|
||||
if not isinstance(intake_nos, list) or not intake_nos:
|
||||
raise ValidationError('intake_nos is required')
|
||||
conversation_id = str(body.get('conversation_id') or '').strip() or None
|
||||
from app.services.shipping_notice.batch_create_idempotency import (
|
||||
normalize_create_idempotency_key,
|
||||
warn_missing_create_idempotency_key,
|
||||
)
|
||||
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
|
||||
|
||||
idempotency_key = normalize_create_idempotency_key(
|
||||
request.headers.get('Idempotency-Key') or body.get('idempotency_key')
|
||||
)
|
||||
if not idempotency_key:
|
||||
warn_missing_create_idempotency_key(source='workspace_create_shipping_batch_from_intakes')
|
||||
result = create_shipping_batch_from_intakes(
|
||||
user_id=user.id,
|
||||
conversation_id=conversation_id,
|
||||
intake_nos=[str(item) for item in intake_nos],
|
||||
create_idempotency_key=idempotency_key,
|
||||
)
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/retry-pending', methods=['POST'])
|
||||
def workspace_retry_shipping_batch_pending(batch_no: str):
|
||||
"""重试批次中仍可自动推进的任务,跳过终态和人工阻断任务。"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks
|
||||
return jsonify(retry_batch_pending_tasks(batch.batch_no))
|
||||
@@ -0,0 +1,18 @@
|
||||
"""
|
||||
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',
|
||||
]
|
||||
@@ -1,49 +1,10 @@
|
||||
from __future__ import annotations
|
||||
from datetime import datetime
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.services.schedule.query_service import can_view_run, get_run, list_runs, serialize_run
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
workspace_schedule_bp = Blueprint('workspace_schedule', __name__)
|
||||
"""
|
||||
backend/app/api/workspace_schedule.py
|
||||
|
||||
def _require_user():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
用途:工作台排程 API 兼容 shim(Wave 1 迁包)。
|
||||
依赖:app.api.workspace.schedule。
|
||||
逻辑:旧 import 路径仍可用;新代码请用 app.api.workspace。
|
||||
"""
|
||||
from app.api.workspace.schedule import workspace_schedule_bp
|
||||
|
||||
@workspace_schedule_bp.route('/schedule-runs', methods=['GET'])
|
||||
def workspace_schedule_runs():
|
||||
user = _require_user()
|
||||
status = str(request.args.get('status') or '').strip() or None
|
||||
schedule_name = str(request.args.get('schedule_name') or '').strip() or None
|
||||
started_after_str = request.args.get('started_after')
|
||||
started_before_str = request.args.get('started_before')
|
||||
started_after = datetime.fromisoformat(started_after_str) if started_after_str else None
|
||||
started_before = datetime.fromisoformat(started_before_str) if started_before_str else None
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
return jsonify(list_runs(notify_user_id=user.id, schedule_name=schedule_name, status=status, started_after=started_after, started_before=started_before, limit=limit))
|
||||
|
||||
@workspace_schedule_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
|
||||
def workspace_schedule_run_detail(run_id: int):
|
||||
user = _require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
if not can_view_run(run, user.id):
|
||||
raise ForbiddenError('Forbidden')
|
||||
return jsonify(serialize_run(run))
|
||||
|
||||
@workspace_schedule_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
||||
def workspace_schedule_run_excel(run_id: int):
|
||||
from io import BytesIO
|
||||
user = _require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
if not can_view_run(run, user.id):
|
||||
raise ForbiddenError('Forbidden')
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError('Excel not found')
|
||||
buf = BytesIO(run.excel_file_data)
|
||||
return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
__all__ = ['workspace_schedule_bp']
|
||||
@@ -1,323 +1,10 @@
|
||||
from __future__ import annotations
|
||||
"""
|
||||
backend/app/api/workspace_shipping_notice.py
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
from pathlib import Path
|
||||
用途:工作台发货通知 API 兼容 shim(Wave 1 迁包)。
|
||||
依赖:app.api.workspace.shipping_notice。
|
||||
逻辑:旧 import 路径继续 re-export `workspace_shipping_notice_bp`;真实实现统一维护在 workspace 子包中,避免双份路由漂移。
|
||||
"""
|
||||
from app.api.workspace.shipping_notice import workspace_shipping_notice_bp
|
||||
|
||||
from app import db
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.models import ShippingTask
|
||||
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
|
||||
from app.services.shipping_notice.constants import CP_EXPORT_GENERATED, CP_NOTICE_TEXT_EXTRACTION_FAILED, AUTO_CHAIN_FALLBACK, MAP_JSON
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_task_for_user,
|
||||
list_tasks_for_user,
|
||||
serialize_task_detail,
|
||||
)
|
||||
|
||||
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return None, (jsonify({"error": "Unauthorized"}), 401)
|
||||
return user, None
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks", methods=["GET"])
|
||||
def workspace_shipping_tasks():
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
process_status = str(request.args.get("process_status") or "").strip() or None
|
||||
limit = int(request.args.get("limit") or 100)
|
||||
return jsonify(list_tasks_for_user(user.id, process_status=process_status, limit=limit))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks", methods=["POST"])
|
||||
def workspace_create_shipping_task():
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = {"user_id": user.id}
|
||||
source_type = str(data.get("source_type") or "").strip()
|
||||
if source_type:
|
||||
payload["source_type"] = source_type
|
||||
conversation_id = str(data.get("conversation_id") or "").strip()
|
||||
if conversation_id:
|
||||
payload["conversation_id"] = conversation_id
|
||||
raw_content = str(data.get("raw_content") or "").strip()
|
||||
if raw_content:
|
||||
payload["raw_content"] = raw_content
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
return jsonify(shipping_tools.create_task(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/create-from-notice", methods=["POST"])
|
||||
def workspace_create_shipping_task_from_notice():
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
|
||||
upload = request.files.get("file")
|
||||
if not upload:
|
||||
return jsonify({"error": "file is required"}), 400
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.notice_upload import (
|
||||
extract_notice_text,
|
||||
guess_source_type,
|
||||
max_notice_chars,
|
||||
save_task_notice_upload,
|
||||
)
|
||||
|
||||
source_type = guess_source_type(upload.filename or "")
|
||||
created = shipping_tools.create_task({"user_id": user.id, "source_type": source_type})
|
||||
task_id = str(created.get("task_id") or "").strip()
|
||||
if not task_id:
|
||||
return jsonify({"error": "failed to create task"}), 500
|
||||
|
||||
raw = upload.read() or b""
|
||||
saved_path = save_task_notice_upload(task_id, upload.filename or "notice", raw)
|
||||
text, meta = extract_notice_text(saved_path)
|
||||
if not text:
|
||||
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint
|
||||
|
||||
return jsonify(
|
||||
{
|
||||
"status": "needs_human",
|
||||
"task_id": task_id,
|
||||
"message": "未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。",
|
||||
"data": {"notice_upload": {"filename": upload.filename or "", **meta}},
|
||||
"human_options": ["reparse", "reject"],
|
||||
"checkpoint": CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
"action_buttons": action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED),
|
||||
}
|
||||
)
|
||||
|
||||
if text:
|
||||
limit = max_notice_chars()
|
||||
if len(text) > limit:
|
||||
text = text[:limit]
|
||||
meta.setdefault("warnings", []).append(f"notice_text_truncated:{limit}")
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
if task:
|
||||
task.raw_content = text
|
||||
db.session.commit()
|
||||
|
||||
payload = {"task_id": task_id}
|
||||
parsed = shipping_tools.parse_notice(payload)
|
||||
data = parsed.get("data") if isinstance(parsed, dict) else None
|
||||
if isinstance(data, dict):
|
||||
data["notice_upload"] = {"filename": upload.filename or "", **meta}
|
||||
parsed["message"] = f"已上传发货通知文件并创建任务 {task_id}。{parsed.get('message') or ''}".strip()
|
||||
return jsonify(parsed)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>", methods=["GET"])
|
||||
def workspace_shipping_task_detail(task_no: str):
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
return jsonify(serialize_task_detail(task))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/chat-actions", methods=["GET"])
|
||||
def workspace_shipping_task_chat_actions(task_no: str):
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
return jsonify(build_chat_actions_payload(task))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/upload-inventory", methods=["POST"])
|
||||
def workspace_upload_shipping_inventory(task_no: str):
|
||||
"""Hxops chat UI: upload inventory Excel with user auth (not Tool Key)."""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
upload = request.files.get("file")
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
return jsonify(shipping_tools.upload_inventory_file(task.task_no, upload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/apply-inventory-mapping", methods=["POST"])
|
||||
def workspace_apply_inventory_mapping(task_no: str):
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
map_json = data.get(MAP_JSON)
|
||||
if not isinstance(map_json, dict) or not map_json:
|
||||
return jsonify({"error": f"{MAP_JSON} is required"}), 400
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
payload = {"task_id": task.task_no, MAP_JSON: map_json, AUTO_CHAIN_FALLBACK: True}
|
||||
return jsonify(shipping_tools.apply_inventory_mapping(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/submit-decision", methods=["POST"])
|
||||
def workspace_submit_shipping_decision(task_no: str):
|
||||
"""Hxops chat UI: submit shipping decision with user auth (bypass Dify tool routing)."""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
decision = str(data.get("decision") or "").strip()
|
||||
if not decision:
|
||||
return jsonify({"error": "decision is required"}), 400
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
payload = {"task_id": task.task_no, "decision": decision, AUTO_CHAIN_FALLBACK: True}
|
||||
comment = str(data.get("comment") or "").strip()
|
||||
if comment:
|
||||
payload["comment"] = comment
|
||||
return jsonify(shipping_tools.submit_decision(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/auto-progress", methods=["POST"])
|
||||
def workspace_auto_progress_shipping_task(task_no: str):
|
||||
"""Hxops chat fallback: same as Dify auto_progress tool."""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload: dict = {"task_id": task.task_no}
|
||||
for key in ("lang", "locale", "language"):
|
||||
if data.get(key):
|
||||
payload[key] = data[key]
|
||||
break
|
||||
result = shipping_tools.auto_progress(payload)
|
||||
if isinstance(result, dict) and result.get("status") == "ok":
|
||||
gen_data = result.get("data")
|
||||
if isinstance(gen_data, dict) and gen_data.get("export_file_path"):
|
||||
gen_data = {**gen_data, "download_url": f"/api/workspace/shipping-tasks/{task.task_no}/export"}
|
||||
result = {**result, "data": gen_data}
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/match-inventory", methods=["POST"])
|
||||
def workspace_match_shipping_inventory(task_no: str):
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
action_buttons_for_checkpoint,
|
||||
human_options_for_checkpoint,
|
||||
)
|
||||
|
||||
matched = shipping_tools.match_inventory({"task_id": task.task_no, AUTO_CHAIN_FALLBACK: True})
|
||||
if not isinstance(matched, dict):
|
||||
return jsonify(matched)
|
||||
data = matched.get("data")
|
||||
if isinstance(data, dict) and data.get("export_file_path"):
|
||||
matched = {
|
||||
**matched,
|
||||
"data": {**data, "download_url": f"/api/workspace/shipping-tasks/{task.task_no}/export"},
|
||||
}
|
||||
checkpoint = matched.get("checkpoint") or CP_EXPORT_GENERATED
|
||||
if matched.get("status") == "ok" and data and data.get("export_file_path"):
|
||||
matched["checkpoint"] = checkpoint
|
||||
if "human_options" not in matched:
|
||||
options = human_options_for_checkpoint(checkpoint)
|
||||
if options is not None:
|
||||
matched["human_options"] = options
|
||||
if "action_buttons" not in matched:
|
||||
buttons = action_buttons_for_checkpoint(checkpoint)
|
||||
if buttons:
|
||||
matched["action_buttons"] = buttons
|
||||
return jsonify(matched)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/mark-manual-uploaded", methods=["POST"])
|
||||
def workspace_mark_manual_uploaded(task_no: str):
|
||||
"""Hxops chat: mark freight manual upload complete (no ref no required)."""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
return jsonify(
|
||||
shipping_tools.upload_to_freight({"task_id": task.task_no, "mode": "manual_confirm"})
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/generate-excel", methods=["POST"])
|
||||
def workspace_generate_shipping_excel(task_no: str):
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
result = shipping_tools.generate_excel({"task_id": task.task_no})
|
||||
if isinstance(result, dict) and result.get("status") == "ok":
|
||||
data = result.get("data")
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
result["data"] = data
|
||||
data["download_url"] = f"/api/workspace/shipping-tasks/{task.task_no}/export"
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/export", methods=["GET"])
|
||||
def workspace_shipping_task_export(task_no: str):
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task or not task.export_file_path:
|
||||
return jsonify({"error": "export file not found"}), 404
|
||||
path = Path(task.export_file_path)
|
||||
if not path.is_file():
|
||||
return jsonify({"error": "export file missing on disk"}), 404
|
||||
return send_file(
|
||||
path,
|
||||
as_attachment=True,
|
||||
download_name=task.export_file_name or path.name,
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
__all__ = ['workspace_shipping_notice_bp']
|
||||
@@ -0,0 +1,10 @@
|
||||
"""
|
||||
backend/app/core/__init__.py
|
||||
|
||||
用途:横切能力包入口(errors、response、auth、config、decorators)。
|
||||
逻辑:业务代码 from app.core.errors / app.core.auth.jwt 等子模块 import。
|
||||
"""
|
||||
|
||||
from app.core.errors import AppError # noqa: F401
|
||||
|
||||
__all__ = ['AppError']
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
backend/app/core/auth/__init__.py
|
||||
|
||||
用途:认证与当前用户解析包入口。
|
||||
逻辑:api 层通过 get_current_user 获取 User;Wave 1 自 auth_jwt.py 迁入 jwt.py。
|
||||
"""
|
||||
@@ -0,0 +1,39 @@
|
||||
"""
|
||||
backend/app/core/auth/context.py
|
||||
|
||||
用途:从 Flask g/request 解析请求上下文(request_id、user),供 api 层薄封装。
|
||||
逻辑:Wave 3 拆分 user/chat 路由时,将重复 auth 逻辑收敛到本模块。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def get_request_id() -> str | None:
|
||||
"""
|
||||
读取当前请求的 X-Request-Id 或 g.request_id。
|
||||
核心逻辑:延迟 import flask.g,避免 services 层依赖。
|
||||
Returns:
|
||||
request_id 字符串,无上下文时返回 None。
|
||||
"""
|
||||
try:
|
||||
from flask import g
|
||||
|
||||
return getattr(g, 'request_id', None)
|
||||
except RuntimeError:
|
||||
return None
|
||||
|
||||
|
||||
def get_optional_config(key: str, default: Any = None) -> Any:
|
||||
"""
|
||||
读取 Flask app.config 项(仅 api / jobs context 使用)。
|
||||
Args:
|
||||
key: config 键名。
|
||||
default: 无 app context 时的默认值。
|
||||
"""
|
||||
try:
|
||||
from flask import current_app
|
||||
|
||||
return current_app.config.get(key, default)
|
||||
except RuntimeError:
|
||||
return default
|
||||
@@ -1,5 +1,15 @@
|
||||
import time
|
||||
"""
|
||||
backend/app/core/auth/jwt.py
|
||||
|
||||
用途:Casdoor JWT 校验、legacy header 回退与当前用户解析。
|
||||
依赖:app.extensions.db、app.models.User、PyJWT、requests。
|
||||
逻辑:api 层与 decorators 调用 get_current_user()。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Optional
|
||||
|
||||
@@ -8,7 +18,7 @@ import requests
|
||||
from flask import current_app, g, request
|
||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||
|
||||
from app import db
|
||||
from app.extensions import db
|
||||
from app.models import User
|
||||
|
||||
_JWKS_CACHE: dict[str, Any] = {
|
||||
@@ -17,6 +27,7 @@ _JWKS_CACHE: dict[str, Any] = {
|
||||
'expires_at': 0.0,
|
||||
}
|
||||
|
||||
|
||||
def _token_brief(token: Optional[str]) -> str:
|
||||
if not token:
|
||||
return 'empty'
|
||||
@@ -27,7 +38,6 @@ def _token_brief(token: Optional[str]) -> str:
|
||||
|
||||
|
||||
def _extract_bearer_token() -> Optional[str]:
|
||||
# Only trust standard Bearer token; reject all non-Bearer auth schemes.
|
||||
auth = request.headers.get('Authorization', '')
|
||||
if not auth:
|
||||
return None
|
||||
@@ -39,7 +49,6 @@ def _extract_bearer_token() -> Optional[str]:
|
||||
|
||||
|
||||
def _get_jwks_keys(jwks_url: str) -> dict:
|
||||
# Keep a short in-memory JWKS cache to avoid hitting Casdoor for every request.
|
||||
now = time.time()
|
||||
if (
|
||||
_JWKS_CACHE.get('url') == jwks_url
|
||||
@@ -66,7 +75,6 @@ def _get_jwks_keys(jwks_url: str) -> dict:
|
||||
|
||||
|
||||
def _decode_jwt(token: str) -> dict:
|
||||
# Strictly validate iss/aud/exp/iat against Casdoor metadata-derived settings.
|
||||
issuer = (current_app.config.get('AUTH_JWT_ISSUER') or '').strip()
|
||||
audience = (current_app.config.get('AUTH_JWT_AUDIENCE') or '').strip()
|
||||
jwks_url = (current_app.config.get('AUTH_JWT_JWKS_URL') or '').strip()
|
||||
@@ -75,12 +83,6 @@ def _decode_jwt(token: str) -> dict:
|
||||
|
||||
header = jwt.get_unverified_header(token)
|
||||
kid = header.get('kid')
|
||||
current_app.logger.info(
|
||||
'[auth_jwt] decode start kid=%s alg=%s token=%s',
|
||||
kid,
|
||||
header.get('alg'),
|
||||
_token_brief(token),
|
||||
)
|
||||
if not kid:
|
||||
if not bool(current_app.config.get('AUTH_ALLOW_LOCAL_JWT', True)):
|
||||
raise ValueError('JWT header missing kid')
|
||||
@@ -101,15 +103,12 @@ def _decode_jwt(token: str) -> dict:
|
||||
keys = _get_jwks_keys(jwks_url)
|
||||
jwk = keys.get(kid)
|
||||
if not jwk:
|
||||
# stale cache fallback
|
||||
_JWKS_CACHE['expires_at'] = 0.0
|
||||
keys = _get_jwks_keys(jwks_url)
|
||||
jwk = keys.get(kid)
|
||||
if not jwk:
|
||||
raise ValueError('No matching JWKS key for token')
|
||||
|
||||
# Different jwt packages/versions expose JWK->public-key helpers differently.
|
||||
# Try multiple compatible paths to avoid hard dependency on one symbol name.
|
||||
public_key = None
|
||||
pyjwk = getattr(jwt, 'PyJWK', None)
|
||||
if pyjwk and hasattr(pyjwk, 'from_dict'):
|
||||
@@ -138,7 +137,6 @@ def _decode_jwt(token: str) -> dict:
|
||||
|
||||
|
||||
def _extract_unverified_claims(token: str) -> dict:
|
||||
"""Best-effort decode without signature verification for troubleshooting logs."""
|
||||
try:
|
||||
return jwt.decode(
|
||||
token,
|
||||
@@ -156,7 +154,6 @@ def _extract_unverified_claims(token: str) -> dict:
|
||||
|
||||
|
||||
def _resolve_user_from_claims(claims: dict) -> Optional[User]:
|
||||
# Resolution order keeps compatibility with different token claim conventions.
|
||||
def _lookup() -> Optional[User]:
|
||||
user_id = claims.get('user_id') or claims.get('id')
|
||||
if user_id is not None:
|
||||
@@ -183,7 +180,11 @@ def _resolve_user_from_claims(claims: dict) -> Optional[User]:
|
||||
try:
|
||||
return _lookup()
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('[auth_jwt] transient db error when resolving user, retry with reconnect path=%s err=%s', request.path, exc)
|
||||
current_app.logger.warning(
|
||||
'[auth_jwt] transient db error when resolving user, retry with reconnect path=%s err=%s',
|
||||
request.path,
|
||||
exc,
|
||||
)
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
@@ -212,7 +213,11 @@ def _legacy_header_user() -> Optional[User]:
|
||||
try:
|
||||
return _lookup()
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('[auth_jwt] transient db error when resolving legacy header user, retry with reconnect path=%s err=%s', request.path, exc)
|
||||
current_app.logger.warning(
|
||||
'[auth_jwt] transient db error when resolving legacy header user, retry with reconnect path=%s err=%s',
|
||||
request.path,
|
||||
exc,
|
||||
)
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
@@ -222,9 +227,26 @@ def _legacy_header_user() -> Optional[User]:
|
||||
return _lookup()
|
||||
|
||||
|
||||
def _current_user_cache_key() -> tuple[str, str, str, str]:
|
||||
"""构造当前请求用户缓存键,避免测试或保留上下文场景串用上一条请求的用户缓存。"""
|
||||
return (
|
||||
str(request.headers.get('Authorization') or '').strip(),
|
||||
str(request.headers.get('X-User-Id') or '').strip(),
|
||||
str(request.headers.get('X-Username') or '').strip(),
|
||||
f'{request.method}:{request.path}',
|
||||
)
|
||||
|
||||
|
||||
def get_current_user() -> Optional[User]:
|
||||
"""
|
||||
解析当前请求用户:优先 JWT Bearer,其次 legacy header(若配置启用)。
|
||||
Returns:
|
||||
User 实例;未认证时返回 None。
|
||||
"""
|
||||
cache_key = _current_user_cache_key()
|
||||
cached = getattr(g, 'current_user', None)
|
||||
if cached is not None:
|
||||
cached_key = getattr(g, 'current_user_cache_key', None)
|
||||
if cached is not None and cached_key == cache_key:
|
||||
return cached
|
||||
|
||||
token = _extract_bearer_token()
|
||||
@@ -232,43 +254,48 @@ def get_current_user() -> Optional[User]:
|
||||
try:
|
||||
claims = _decode_jwt(token)
|
||||
user = _resolve_user_from_claims(claims)
|
||||
current_app.logger.info(
|
||||
'[auth_jwt] decode ok sub=%s username=%s resolved_user=%s',
|
||||
claims.get('sub'),
|
||||
claims.get('preferred_username') or claims.get('username') or claims.get('name'),
|
||||
getattr(user, 'username', None),
|
||||
)
|
||||
except Exception:
|
||||
# Any decode/lookup failure should behave as unauthenticated.
|
||||
# Decode metadata is diagnostic-only: do not emit it for successful requests.
|
||||
try:
|
||||
header = jwt.get_unverified_header(token)
|
||||
except Exception:
|
||||
header = {}
|
||||
unverified = _extract_unverified_claims(token)
|
||||
expected_issuer = (current_app.config.get('AUTH_JWT_ISSUER') or '').strip()
|
||||
expected_audience = (current_app.config.get('AUTH_JWT_AUDIENCE') or '').strip()
|
||||
current_app.logger.error(
|
||||
'[auth_jwt] decode context token_iss=%s token_aud=%s expected_iss=%s expected_aud=%s',
|
||||
'[auth_jwt] decode context kid=%s alg=%s token=%s token_iss=%s token_aud=%s '
|
||||
'expected_iss=%s expected_aud=%s path=%s',
|
||||
header.get('kid'),
|
||||
header.get('alg'),
|
||||
_token_brief(token),
|
||||
unverified.get('iss'),
|
||||
unverified.get('aud'),
|
||||
expected_issuer,
|
||||
expected_audience,
|
||||
request.path,
|
||||
)
|
||||
current_app.logger.exception('[auth_jwt] decode failed token=%s path=%s', _token_brief(token), request.path)
|
||||
current_app.logger.exception('[auth_jwt] decode failed')
|
||||
user = None
|
||||
claims = None
|
||||
if user:
|
||||
g.jwt_claims = claims
|
||||
g.current_user = user
|
||||
g.current_user_cache_key = cache_key
|
||||
return user
|
||||
|
||||
if bool(current_app.config.get('AUTH_LEGACY_HEADER_ENABLED', True)):
|
||||
user = _legacy_header_user()
|
||||
if user:
|
||||
g.current_user = user
|
||||
g.current_user_cache_key = cache_key
|
||||
return user
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def issue_local_access_token(user: User) -> str:
|
||||
"""Issue local HS256 JWT for password-login flow compatibility."""
|
||||
"""签发本地 HS256 JWT(密码登录兼容)。"""
|
||||
now = datetime.now(timezone.utc)
|
||||
exp_hours = int(current_app.config.get('AUTH_LOCAL_JWT_EXPIRES_HOURS') or 12)
|
||||
payload = {
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/app/core/config/__init__.py
|
||||
|
||||
用途:配置包入口(settings、env_persistence)。
|
||||
"""
|
||||
@@ -1,20 +1,14 @@
|
||||
"""Persistent storage for runtime-editable application settings.
|
||||
"""
|
||||
backend/app/core/config/env_persistence.py
|
||||
|
||||
Settings managed from the admin console (e.g. WeCom configuration) need to
|
||||
survive process restarts AND container/image rebuilds in production. Writing
|
||||
only to ``backend/.env`` is not enough on Docker deployments because the
|
||||
container's writable layer is discarded on every ``docker compose up --build``.
|
||||
用途:运行时配置 DB 持久化与 env 镜像(WeCom 等 admin 设置)。
|
||||
依赖:app.extensions.db、app.models.AppSetting。
|
||||
逻辑:before_request 调用 apply_env_settings;persist_env_settings 供 admin 写入。
|
||||
|
||||
Storage strategy:
|
||||
|
||||
1. Database (``app_settings`` table) - canonical, always authoritative.
|
||||
2. ``.env.local`` (dev only) - best-effort secondary write so local/dev
|
||||
workflows that restart without DB access still see updates.
|
||||
3. ``os.environ`` - mirrored on write so legacy ``os.getenv`` consumers stay
|
||||
in sync within the running process.
|
||||
|
||||
On read we merge env files (lowest priority) over DB (highest priority); the DB
|
||||
value wins whenever it exists.
|
||||
1. Database (app_settings) - canonical
|
||||
2. .env.local (dev only) - secondary mirror
|
||||
3. os.environ - in-process mirror on write
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -30,7 +24,7 @@ from dotenv import dotenv_values, set_key
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
_BACKEND_DIR = Path(__file__).resolve().parents[1]
|
||||
_BACKEND_DIR = Path(__file__).resolve().parents[3]
|
||||
_ROOT_DIR = _BACKEND_DIR.parent
|
||||
ROOT_ENV_LOCAL_PATH = _ROOT_DIR / '.env.local'
|
||||
LEGACY_BACKEND_ENV_PATH = _BACKEND_DIR / '.env'
|
||||
@@ -42,6 +36,7 @@ WECOM_BOOL_KEYS = {
|
||||
'WECOM_AUTO_CREATE_USER',
|
||||
'WECOM_MOBILE_NORMALIZE',
|
||||
'WECOM_NOTIFY_ENABLED',
|
||||
'WECOM_FEEDBACK_NOTIFY_ENABLED',
|
||||
}
|
||||
|
||||
|
||||
@@ -107,7 +102,7 @@ def _persist_to_db(values: dict[str, str]) -> bool:
|
||||
if not values:
|
||||
return True
|
||||
try:
|
||||
from app import db
|
||||
from app.extensions import db
|
||||
from app.models import AppSetting
|
||||
except Exception as exc: # pragma: no cover - import safety net
|
||||
logger.warning('AppSetting model unavailable: %s', exc)
|
||||
@@ -133,7 +128,7 @@ def _persist_to_db(values: dict[str, str]) -> bool:
|
||||
|
||||
def _load_from_db(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
try:
|
||||
from app import db
|
||||
from app.extensions import db
|
||||
from app.models import AppSetting
|
||||
except Exception as exc: # pragma: no cover
|
||||
logger.debug('AppSetting model unavailable for read: %s', exc)
|
||||
@@ -1,14 +1,17 @@
|
||||
"""
|
||||
backend/app/config.py
|
||||
配置类,区分开发/生产环境
|
||||
backend/app/core/config/settings.py
|
||||
|
||||
用途:Flask Config 类与环境文件加载(dev/test/prod)。
|
||||
依赖:dotenv、app.path_utils。
|
||||
逻辑:create_app 通过 config[config_name] 加载;旧路径 app.config 为兼容 shim。
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from dotenv import dotenv_values
|
||||
|
||||
|
||||
_BACKEND_DIR = Path(__file__).resolve().parents[1]
|
||||
_BACKEND_DIR = Path(__file__).resolve().parents[3]
|
||||
_ROOT_DIR = _BACKEND_DIR.parent
|
||||
|
||||
|
||||
@@ -33,18 +36,25 @@ def _load_environment_files() -> str:
|
||||
4. system environment variables (always highest, never overridden)
|
||||
"""
|
||||
env_name = _normalize_env_name(os.getenv('ENV_NAME') or os.getenv('FLASK_ENV'))
|
||||
preserved_env = dict(os.environ)
|
||||
merged_values: dict[str, str] = {}
|
||||
|
||||
shared_file = _ROOT_DIR / '.env.shared'
|
||||
if shared_file.exists():
|
||||
load_dotenv(shared_file, override=False)
|
||||
merged_values.update({k: v for k, v in dotenv_values(shared_file).items() if v is not None})
|
||||
|
||||
env_file = _ROOT_DIR / f'.env.{env_name}'
|
||||
if env_file.exists():
|
||||
load_dotenv(env_file, override=True)
|
||||
merged_values.update({k: v for k, v in dotenv_values(env_file).items() if v is not None})
|
||||
|
||||
if env_name == 'dev':
|
||||
local_file = _ROOT_DIR / '.env.local'
|
||||
if local_file.exists():
|
||||
load_dotenv(local_file, override=True)
|
||||
merged_values.update({k: v for k, v in dotenv_values(local_file).items() if v is not None})
|
||||
|
||||
for key, value in merged_values.items():
|
||||
if key not in preserved_env:
|
||||
os.environ[key] = value
|
||||
return env_name
|
||||
|
||||
|
||||
@@ -68,7 +78,9 @@ def _backend_path(env_key: str, *parts: str) -> str:
|
||||
class Config:
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
SECRET_KEY = os.getenv('SECRET_KEY')
|
||||
KB_STORAGE_ROOT = os.getenv('KB_STORAGE_ROOT', str(_BACKEND_DIR / 'data' / 'kb'))
|
||||
# 配置最大上传文件大小(200MB)
|
||||
MAX_CONTENT_LENGTH = 200 * 1024 * 1024
|
||||
KB_STORAGE_ROOT = _data_path('KB_STORAGE_ROOT', 'kb')
|
||||
KB_TASK_EXECUTION_MODE = os.getenv('KB_TASK_EXECUTION_MODE', 'worker').strip().lower()
|
||||
KB_WORKER_POLL_SECONDS = float(os.getenv('KB_WORKER_POLL_SECONDS', '2'))
|
||||
KB_WORKER_CONCURRENCY = int(os.getenv('KB_WORKER_CONCURRENCY', '3') or '3')
|
||||
@@ -90,6 +102,8 @@ class Config:
|
||||
# Dify 网关配置
|
||||
DIFY_API_BASE = os.getenv('DIFY_API_BASE')
|
||||
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
|
||||
DIFY_CHAT_CONNECT_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_CONNECT_TIMEOUT_SECONDS', '5'))
|
||||
DIFY_CHAT_READ_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_READ_TIMEOUT_SECONDS', '30'))
|
||||
# Redis 连接配置,默认使用本地 Redis + 密码
|
||||
REDIS_URL = os.getenv('REDIS_URL')
|
||||
FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true'
|
||||
@@ -107,24 +121,82 @@ class Config:
|
||||
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
|
||||
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
|
||||
|
||||
# HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 服务端调用;无尾斜杠,常为内网 IP)
|
||||
HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOLS_API_BASE')
|
||||
|
||||
# HXOPS 浏览器可访问根地址(Excel 签名下载等用户可见链接;无尾斜杠,应为域名)
|
||||
HXOPS_PUBLIC_BASE_URL = os.getenv('HXOPS_PUBLIC_BASE_URL')
|
||||
|
||||
# 货代发货通知 Agent Tool API
|
||||
SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY')
|
||||
# OpenAPI servers.url 基地址(Dify 调 Tool 时访问 hxops,不是 Dify 的 8882)
|
||||
SHIPPING_NOTICE_TOOL_API_BASE = os.getenv('SHIPPING_NOTICE_TOOL_API_BASE')
|
||||
|
||||
# 文件检核 Chatflow Tool API
|
||||
FILE_CHECK_TOOL_API_KEY = os.getenv('FILE_CHECK_TOOL_API_KEY')
|
||||
|
||||
# 设备维保助手 Chatflow Tool API
|
||||
MAINTENANCE_TOOL_API_KEY = os.getenv('MAINTENANCE_TOOL_API_KEY')
|
||||
SHIPPING_NOTICE_STORAGE_ROOT = _data_path("SHIPPING_NOTICE_STORAGE_ROOT", "shipping_notice")
|
||||
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD = float(
|
||||
os.getenv('SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD') or '0.7'
|
||||
)
|
||||
# 建单后是否延后 parse_notice,交由 Dify 画布 LLM + Tool 解析(默认 true,符合 Dify 优先原则)
|
||||
SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY = os.getenv('SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY = int(
|
||||
os.getenv('SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY') or '3'
|
||||
)
|
||||
SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS') or '180'
|
||||
)
|
||||
SHIPPING_NOTICE_TASK_EXECUTION_MODE = os.getenv('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker').strip().lower()
|
||||
SHIPPING_NOTICE_WORKER_POLL_SECONDS = float(os.getenv('SHIPPING_NOTICE_WORKER_POLL_SECONDS', '2'))
|
||||
SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float(
|
||||
os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '300')
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW = os.getenv('SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW', 'true')
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED', 'false').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS') or '3'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '120'
|
||||
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '900'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED = (
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = (
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS', '').strip().lower()
|
||||
in {'1', 'true', 'yes', 'on'}
|
||||
if os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS')
|
||||
else _normalize_env_name(os.getenv('ENV_NAME')) in {'test', 'prod'}
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = (
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK', 'false').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID = os.getenv('SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID', '').strip()
|
||||
SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME = (
|
||||
os.getenv('SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME', '.hxops_rpa_shared_mount').strip()
|
||||
or '.hxops_rpa_shared_mount'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS') or '1800'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES = os.getenv(
|
||||
'SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES', ''
|
||||
).strip()
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN = (
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS') or '120'
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM = os.getenv('SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM', 'false').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_MATCH_ENABLED', 'true').lower() == 'true'
|
||||
@@ -145,18 +217,37 @@ class Config:
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS = int(
|
||||
os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000'
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG = _backend_path(
|
||||
'SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG', 'config', 'shipping_inventory_sources.yaml'
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS = int(
|
||||
os.getenv('SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS') or '24'
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE = float(
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE') or '0.8'
|
||||
)
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
|
||||
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
|
||||
FREIGHT_INVENTORY_DROP_DIR = _data_path("FREIGHT_INVENTORY_DROP_DIR", "freight_rpa", "inventory_drop")
|
||||
FREIGHT_INVENTORY_DROP_DIR = _data_path(
|
||||
"FREIGHT_INVENTORY_DROP_DIR", "shipping_notice", "freight_rpa", "inventory_drop"
|
||||
)
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR = _data_path(
|
||||
"FREIGHT_RPA_INVENTORY_TRIGGER_DIR", "freight_rpa", "inventory_triggers"
|
||||
"FREIGHT_RPA_INVENTORY_TRIGGER_DIR", "shipping_notice", "freight_rpa", "inventory_triggers"
|
||||
)
|
||||
FREIGHT_UPLOAD_QUEUE_DIR = _data_path(
|
||||
"FREIGHT_UPLOAD_QUEUE_DIR", "shipping_notice", "freight_rpa", "upload_queue"
|
||||
)
|
||||
FREIGHT_UPLOAD_QUEUE_DIR = _data_path("FREIGHT_UPLOAD_QUEUE_DIR", "freight_rpa", "upload_queue")
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR = _data_path(
|
||||
"FREIGHT_RPA_UPLOAD_TRIGGER_DIR", "freight_rpa", "upload_triggers"
|
||||
"FREIGHT_RPA_UPLOAD_TRIGGER_DIR", "shipping_notice", "freight_rpa", "upload_triggers"
|
||||
)
|
||||
FREIGHT_RPA_BROWSER_PROFILE_DIR = _data_path(
|
||||
"FREIGHT_RPA_BROWSER_PROFILE_DIR", "shipping_notice", "freight_rpa", "browser_profile"
|
||||
)
|
||||
FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = _data_path(
|
||||
"FREIGHT_RPA_INVENTORY_ARCHIVE_DIR", "shipping_notice", "freight_rpa", "inventory_archives"
|
||||
)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH = _backend_path(
|
||||
"FREIGHT_SHIPMENT_TEMPLATE_PATH", "templates", "freight_shipment_upload.xlsx"
|
||||
@@ -184,7 +275,10 @@ 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')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset')
|
||||
WECOM_FEEDBACK_NOTIFY_ENABLED = os.getenv('WECOM_FEEDBACK_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_FEEDBACK_NOTIFY_BASE_URL = os.getenv('WECOM_FEEDBACK_NOTIFY_BASE_URL')
|
||||
WECOM_FEEDBACK_BOT_WEBHOOK = os.getenv('WECOM_FEEDBACK_BOT_WEBHOOK')
|
||||
|
||||
# JWT/Casdoor auth configuration (phase-1 compatible rollout)
|
||||
AUTH_LEGACY_HEADER_ENABLED = os.getenv('AUTH_LEGACY_HEADER_ENABLED', 'true').lower() == 'true'
|
||||
@@ -217,6 +311,8 @@ class Config:
|
||||
AUTH_LOCAL_JWT_AUDIENCE = os.getenv('AUTH_LOCAL_JWT_AUDIENCE')
|
||||
AUTH_LOCAL_JWT_EXPIRES_HOURS = int(os.getenv('AUTH_LOCAL_JWT_EXPIRES_HOURS', '12'))
|
||||
SCHEDULE_WORKER_ENABLED = os.getenv('SCHEDULE_WORKER_ENABLED', 'true').lower() == 'true'
|
||||
# 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', '')
|
||||
SRM_SQLSERVER_PORT = os.getenv('SRM_SQLSERVER_PORT', '1433')
|
||||
SRM_SQLSERVER_DATABASE = os.getenv('SRM_SQLSERVER_DATABASE', '')
|
||||
@@ -233,6 +329,39 @@ class Config:
|
||||
SMTP_FROM = os.getenv('SMTP_FROM', '')
|
||||
SMTP_USE_TLS = os.getenv('SMTP_USE_TLS', 'true').lower() == 'true'
|
||||
INTERNAL_API_BASE_URL = os.getenv('INTERNAL_API_BASE_URL', 'http://127.0.0.1:5052')
|
||||
FIXED_ASSETS_SYNC_ENABLED = os.getenv('FIXED_ASSETS_SYNC_ENABLED', 'true').lower() == 'true'
|
||||
FIXED_ASSETS_SYNC_TIMEZONE = (os.getenv('FIXED_ASSETS_SYNC_TIMEZONE') or 'Asia/Shanghai').strip()
|
||||
FIXED_ASSETS_SYNC_HOUR = int(os.getenv('FIXED_ASSETS_SYNC_HOUR', '3') or '3')
|
||||
FIXED_ASSETS_SYNC_MINUTE = int(os.getenv('FIXED_ASSETS_SYNC_MINUTE', '0') or '0')
|
||||
FIXED_ASSETS_SYNC_TIMEOUT_SECONDS = int(os.getenv('FIXED_ASSETS_SYNC_TIMEOUT_SECONDS', '600') or '600')
|
||||
FIXED_ASSETS_SYNC_RETRY_INTERVAL_MINUTES = int(
|
||||
os.getenv('FIXED_ASSETS_SYNC_RETRY_INTERVAL_MINUTES', '30') or '30'
|
||||
)
|
||||
FIXED_ASSETS_SYNC_MAX_ATTEMPTS = int(os.getenv('FIXED_ASSETS_SYNC_MAX_ATTEMPTS', '4') or '4')
|
||||
FIXED_ASSETS_SYNC_POLL_SECONDS = int(os.getenv('FIXED_ASSETS_SYNC_POLL_SECONDS', '60') or '60')
|
||||
FIXED_ASSETS_SYNC_ON_BOOT_IF_MISSING = (
|
||||
os.getenv('FIXED_ASSETS_SYNC_ON_BOOT_IF_MISSING', 'true').lower() == 'true'
|
||||
)
|
||||
FIXED_ASSETS_HISTORY_KEEP_COUNT = int(os.getenv('FIXED_ASSETS_HISTORY_KEEP_COUNT', '3') or '3')
|
||||
FIXED_ASSETS_STORAGE_ROOT = _data_path('FIXED_ASSETS_STORAGE_ROOT', 'fixed_assets')
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT = os.getenv('FIXED_ASSET_HISTORY_SHARE_ROOT', '').strip()
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT = os.getenv('FIXED_ASSET_HISTORY_LOCAL_ROOT', '').strip()
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME = os.getenv('FIXED_ASSET_HISTORY_SHARE_USERNAME', '').strip()
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD = os.getenv('FIXED_ASSET_HISTORY_SHARE_PASSWORD', '')
|
||||
FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS = int(os.getenv('FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS', '20') or '20')
|
||||
FIXED_ASSET_IMAGE_BASE_URL = os.getenv('FIXED_ASSET_IMAGE_BASE_URL', '').strip()
|
||||
FIXED_ASSET_IMAGE_USERNAME = os.getenv('FIXED_ASSET_IMAGE_USERNAME', '').strip()
|
||||
FIXED_ASSET_IMAGE_PASSWORD = os.getenv('FIXED_ASSET_IMAGE_PASSWORD', '')
|
||||
FIXED_ASSET_IMAGE_LIBRARY_ID = os.getenv('FIXED_ASSET_IMAGE_LIBRARY_ID', '').strip()
|
||||
FIXED_ASSET_IMAGE_FOLDER_ID = os.getenv('FIXED_ASSET_IMAGE_FOLDER_ID', '').strip()
|
||||
FIXED_ASSETS_DOCS_EXPORT_ROOT = os.getenv(
|
||||
'FIXED_ASSETS_DOCS_EXPORT_ROOT',
|
||||
str(_ROOT_DIR / 'docs'),
|
||||
)
|
||||
FIXED_ASSETS_EXPORT_TO_DOCS = os.getenv('FIXED_ASSETS_EXPORT_TO_DOCS', 'true').lower() == 'true'
|
||||
FIXED_ASSETS_ERP_USERNAME = os.getenv('FIXED_ASSETS_ERP_USERNAME', 'EXT_VIEW_USER')
|
||||
FIXED_ASSETS_ERP_PASSWORD = os.getenv('FIXED_ASSETS_ERP_PASSWORD', 'extviewuser')
|
||||
FIXED_ASSETS_ERP_DSN = os.getenv('FIXED_ASSETS_ERP_DSN') or os.getenv('ERP_DB_DSN', '192.168.8.24:1521/topprod')
|
||||
|
||||
# MinIO 配置
|
||||
MINIO_ENDPOINT = os.getenv('MINIO_ENDPOINT', '127.0.0.1:9000')
|
||||
@@ -241,6 +370,31 @@ class Config:
|
||||
MINIO_SECURE = os.getenv('MINIO_SECURE', 'false').lower() == 'true'
|
||||
MINIO_AGENT_GUIDES_BUCKET = os.getenv('MINIO_AGENT_GUIDES_BUCKET', 'agent-guides')
|
||||
MINIO_PUBLIC_BASE_URL = os.getenv('MINIO_PUBLIC_BASE_URL', 'http://127.0.0.1:9000')
|
||||
MINIO_FILE_ASSETS_BUCKET = os.getenv('MINIO_FILE_ASSETS_BUCKET', 'hxops-file-assets')
|
||||
FILE_ASSET_MAX_SIZE_MB = int(os.getenv('FILE_ASSET_MAX_SIZE_MB', '30'))
|
||||
FILE_ASSET_TEMP_TTL_HOURS = int(os.getenv('FILE_ASSET_TEMP_TTL_HOURS', '72'))
|
||||
FILE_ASSET_DOWNLOAD_URL_TTL_SECONDS = int(os.getenv('FILE_ASSET_DOWNLOAD_URL_TTL_SECONDS', '300'))
|
||||
SHIPPING_NOTICE_INTAKE_TTL_HOURS = int(os.getenv('SHIPPING_NOTICE_INTAKE_TTL_HOURS', '72'))
|
||||
SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS', '3'))
|
||||
SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', '300')
|
||||
)
|
||||
SHIPPING_NOTICE_PARSER_VERSION = os.getenv('SHIPPING_NOTICE_PARSER_VERSION', 'v6')
|
||||
# EML 附件提取安全上限(阶段一对齐:只抽取文本,不执行宏/脚本)
|
||||
# parser v6:阶段二附件派生 FileAsset + Document/Candidate;相对 v5 须强制重解析
|
||||
# parser v5:mixed 保留独立 HTML 段 + 附件型 alternative 可提取正文
|
||||
SHIPPING_NOTICE_EML_MAX_ATTACHMENTS = int(os.getenv('SHIPPING_NOTICE_EML_MAX_ATTACHMENTS', '20'))
|
||||
SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES = int(
|
||||
os.getenv('SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES', str(20 * 1024 * 1024))
|
||||
)
|
||||
SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES = int(
|
||||
os.getenv('SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES', str(50 * 1024 * 1024))
|
||||
)
|
||||
SHIPPING_NOTICE_EML_MAX_NESTING_DEPTH = int(os.getenv('SHIPPING_NOTICE_EML_MAX_NESTING_DEPTH', '3'))
|
||||
# EML 全部附件 extracted_text 写入 structured_result_json 的合计字符上限
|
||||
SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS = int(
|
||||
os.getenv('SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS', str(500_000))
|
||||
)
|
||||
|
||||
|
||||
class DevelopmentConfig(Config):
|
||||
@@ -259,6 +413,11 @@ class TestingConfig(Config):
|
||||
WTF_CSRF_ENABLED = False
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {}
|
||||
SCHEDULE_WORKER_ENABLED = False
|
||||
FIXED_ASSETS_SYNC_ENABLED = False
|
||||
FIXED_ASSETS_EXPORT_TO_DOCS = False
|
||||
ENV_NAME = 'dev'
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
|
||||
|
||||
|
||||
config = {
|
||||
@@ -270,3 +429,4 @@ config = {
|
||||
'production': ProductionConfig,
|
||||
'default': DevelopmentConfig,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
backend/app/core/db/__init__.py
|
||||
|
||||
用途:数据库会话工具包入口。
|
||||
逻辑:Wave 1 提供 run_with_retry;sequence 工具供迁移/运维脚本使用。
|
||||
"""
|
||||
@@ -0,0 +1,7 @@
|
||||
"""
|
||||
backend/app/core/db/sequence.py
|
||||
|
||||
用途:PostgreSQL 序列修复工具(Wave 1 自 services/db_sequence.py 迁入)。
|
||||
逻辑:迁移脚本与 check_schema_drift 调用。
|
||||
"""
|
||||
from app.services.db_sequence import * # noqa: F403
|
||||
@@ -0,0 +1,28 @@
|
||||
"""
|
||||
backend/app/core/db/session.py
|
||||
|
||||
用途:数据库会话辅助(重试、只读查询封装)。
|
||||
逻辑:Wave 1 从 api/user.py、knowledge_base.py 等抽取 _run_db_with_retry 模式。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from typing import TypeVar
|
||||
|
||||
T = TypeVar('T')
|
||||
|
||||
|
||||
def run_with_retry(fn: Callable[[], T], *, max_attempts: int = 3) -> T:
|
||||
"""
|
||||
在数据库短暂失败时重试可调用对象。
|
||||
核心逻辑:捕获 OperationalError/DisconnectionError 后 rollback 并重试。
|
||||
Args:
|
||||
fn: 无参 callable,内部使用 db.session。
|
||||
max_attempts: 最大尝试次数。
|
||||
Returns:
|
||||
fn 的返回值。
|
||||
Raises:
|
||||
最后一次失败的异常。
|
||||
"""
|
||||
# [STEP 1] Wave 0 占位:Wave 1 从 user.py / knowledge_base.py 抽取实现
|
||||
return fn()
|
||||
@@ -0,0 +1,95 @@
|
||||
"""
|
||||
backend/app/core/decorators.py
|
||||
|
||||
用途:API 路由权限装饰器(admin、agent 权限)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、app.models。
|
||||
逻辑:api 路由使用 @require_admin、@require_agent_permission。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import wraps
|
||||
|
||||
from flask import current_app, g, request
|
||||
|
||||
from app.core.auth.jwt import get_current_user as _auth_current_user
|
||||
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.models import Agent, User
|
||||
|
||||
|
||||
def _get_current_user() -> User:
|
||||
"""通过 JWT / legacy header 解析当前用户并写入 g.current_user。"""
|
||||
user = _auth_current_user()
|
||||
if user:
|
||||
g.current_user = user
|
||||
return user
|
||||
|
||||
|
||||
def _resolve_request_agent_id() -> str | None:
|
||||
"""
|
||||
从 JSON body、query 或 multipart form 解析 agent_id。
|
||||
|
||||
核心逻辑:Chat Turn 附件上传走 multipart/form-data,agent_id 在 form 字段而非 JSON body。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
return (
|
||||
data.get("agent_id")
|
||||
or data.get("agentId")
|
||||
or request.args.get("agent_id")
|
||||
or request.args.get("agentId")
|
||||
or request.form.get("agent_id")
|
||||
or request.form.get("agentId")
|
||||
)
|
||||
|
||||
|
||||
def require_agent_permission(f):
|
||||
"""
|
||||
装饰器:校验当前用户是否拥有指定 Agent 访问权限。
|
||||
核心逻辑:从 body/query/form 读 agent_id → 获取用户 → admin 放行或检查 user.agents。
|
||||
Args:
|
||||
f: 被装饰的视图函数。
|
||||
Returns:
|
||||
包装后的视图函数。
|
||||
"""
|
||||
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
agent_id = _resolve_request_agent_id()
|
||||
if not agent_id:
|
||||
raise ValidationError('agent_id is required')
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
agent = Agent.query.get(agent_id)
|
||||
if not agent:
|
||||
raise NotFoundError('Agent not found')
|
||||
g.current_agent = agent
|
||||
if user.role == 'admin':
|
||||
return f(*args, **kwargs)
|
||||
if agent not in user.agents:
|
||||
raise ForbiddenError('Permission denied for this agent')
|
||||
return f(*args, **kwargs)
|
||||
|
||||
return decorated_function
|
||||
|
||||
|
||||
def require_admin(f):
|
||||
"""
|
||||
装饰器:限制仅 admin 角色可访问。
|
||||
核心逻辑:解析用户 → 校验 role == admin;JWT 必填时检查 Authorization 头。
|
||||
"""
|
||||
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
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':
|
||||
raise ForbiddenError('Admin privilege required')
|
||||
return f(*args, **kwargs)
|
||||
|
||||
return decorated_function
|
||||
@@ -0,0 +1,155 @@
|
||||
"""
|
||||
backend/app/core/errors.py
|
||||
|
||||
用途:定义后端统一业务异常类型,供全局异常处理器识别并输出标准错误响应。
|
||||
依赖:无 Flask 依赖。
|
||||
逻辑:业务层 raise AppError 子类;create_app 注册全局 handler。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class AppError(Exception):
|
||||
code: str
|
||||
message: str
|
||||
http_status: int = 400
|
||||
details: dict[str, Any] = field(default_factory=dict)
|
||||
retryable: bool = False
|
||||
|
||||
|
||||
class ValidationError(AppError):
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Invalid request parameters",
|
||||
*,
|
||||
code: str = "VALIDATION.INVALID_PARAM",
|
||||
details: dict[str, Any] | None = None,
|
||||
):
|
||||
super().__init__(
|
||||
code=code,
|
||||
message=message,
|
||||
http_status=400,
|
||||
details=details or {},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
class UnauthorizedError(AppError):
|
||||
def __init__(self, message: str = "Unauthorized"):
|
||||
super().__init__(code="AUTH.UNAUTHORIZED", message=message, http_status=401, retryable=False)
|
||||
|
||||
|
||||
class ForbiddenError(AppError):
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Forbidden",
|
||||
*,
|
||||
code: str = "AUTH.FORBIDDEN",
|
||||
):
|
||||
super().__init__(code=code, message=message, http_status=403, retryable=False)
|
||||
|
||||
|
||||
class NotFoundError(AppError):
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Resource not found",
|
||||
*,
|
||||
code: str = "RESOURCE.NOT_FOUND",
|
||||
):
|
||||
super().__init__(code=code, message=message, http_status=404, retryable=False)
|
||||
|
||||
|
||||
class ConflictError(AppError):
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Resource conflict",
|
||||
*,
|
||||
code: str = "RESOURCE.CONFLICT",
|
||||
details: dict[str, Any] | None = None,
|
||||
):
|
||||
super().__init__(
|
||||
code=code,
|
||||
message=message,
|
||||
http_status=409,
|
||||
details=details or {},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
class ServiceUnavailableError(AppError):
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Service unavailable",
|
||||
*,
|
||||
code: str = "SYSTEM.SERVICE_UNAVAILABLE",
|
||||
details: dict[str, Any] | None = None,
|
||||
):
|
||||
super().__init__(code=code, message=message, http_status=503, details=details or {}, retryable=True)
|
||||
|
||||
|
||||
class AgentHandlerNotConfiguredError(AppError):
|
||||
"""Catalog 声明 runtime_handler 但 HANDLER_REGISTRY 未注册实现。"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Agent handler is not configured",
|
||||
*,
|
||||
agent_code: str | None = None,
|
||||
handler_key: str | None = None,
|
||||
runtime_provider: str | None = None,
|
||||
details: dict[str, Any] | None = None,
|
||||
):
|
||||
merged_details = dict(details or {})
|
||||
if agent_code:
|
||||
merged_details.setdefault('agent_code', agent_code)
|
||||
if handler_key:
|
||||
merged_details.setdefault('handler_key', handler_key)
|
||||
if runtime_provider:
|
||||
merged_details.setdefault('runtime_provider', runtime_provider)
|
||||
super().__init__(
|
||||
code='AGENT.HANDLER_NOT_CONFIGURED',
|
||||
message=message,
|
||||
http_status=501,
|
||||
details=merged_details,
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
def raise_for_status(message: str, status: int, *, code: str | None = None, details: dict[str, Any] | None = None) -> None:
|
||||
"""
|
||||
按 HTTP 状态码映射并抛出对应 AppError 子类。
|
||||
Args:
|
||||
message: 错误文案。
|
||||
status: HTTP 状态码。
|
||||
code: 可选业务错误码。
|
||||
details: 可选详情 dict。
|
||||
Raises:
|
||||
AppError 或其子类。
|
||||
"""
|
||||
if status == 401:
|
||||
raise UnauthorizedError(message)
|
||||
if status == 403:
|
||||
raise ForbiddenError(message)
|
||||
if status == 404:
|
||||
raise NotFoundError(message)
|
||||
if status == 409:
|
||||
raise ConflictError(message, code=code or "RESOURCE.CONFLICT", details=details)
|
||||
if status == 503:
|
||||
raise ServiceUnavailableError(message, code=code or "SYSTEM.SERVICE_UNAVAILABLE")
|
||||
if status >= 500:
|
||||
raise AppError(
|
||||
code=code or "SYSTEM.INTERNAL_ERROR",
|
||||
message=message,
|
||||
http_status=status,
|
||||
details=details or {},
|
||||
)
|
||||
raise AppError(
|
||||
code=code or "VALIDATION.INVALID_PARAM",
|
||||
message=message,
|
||||
http_status=status,
|
||||
details=details or {},
|
||||
)
|
||||
@@ -0,0 +1,88 @@
|
||||
"""
|
||||
backend/app/core/response.py
|
||||
|
||||
用途:统一 API 响应结构工具(成功 envelope 与错误 payload)。
|
||||
依赖:flask.jsonify(仅 ok() 使用)。
|
||||
逻辑:create_app 异常 handler 使用 error_payload;可选 ENABLE_API_ENVELOPE 包装成功响应。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from flask import jsonify
|
||||
|
||||
|
||||
def utc_iso_now() -> str:
|
||||
"""返回当前 UTC 时间的 ISO8601 字符串(Z 后缀)。"""
|
||||
return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
def utc_iso(dt: datetime | None) -> str | None:
|
||||
"""
|
||||
将 naive UTC datetime 序列化为带 Z 后缀的 ISO 字符串。
|
||||
Args:
|
||||
dt: datetime 或 None。
|
||||
Returns:
|
||||
ISO 字符串或 None。
|
||||
"""
|
||||
if dt is None:
|
||||
return None
|
||||
if dt.tzinfo is not None:
|
||||
return dt.astimezone(timezone.utc).replace(tzinfo=None).isoformat() + "Z"
|
||||
return dt.isoformat() + "Z"
|
||||
|
||||
|
||||
def ok(data: Any, *, request_id: str | None = None, status: int = 200):
|
||||
"""
|
||||
构造 success=true 的标准 JSON 响应。
|
||||
Args:
|
||||
data: 业务数据。
|
||||
request_id: 可选请求追踪 id。
|
||||
status: HTTP 状态码。
|
||||
Returns:
|
||||
(jsonify Response, status) 元组。
|
||||
"""
|
||||
payload: dict[str, Any] = {
|
||||
"success": True,
|
||||
"data": data,
|
||||
"timestamp": utc_iso_now(),
|
||||
}
|
||||
if request_id:
|
||||
payload["request_id"] = request_id
|
||||
return jsonify(payload), status
|
||||
|
||||
|
||||
def error_payload(
|
||||
*,
|
||||
code: str,
|
||||
message: str,
|
||||
request_id: str | None = None,
|
||||
details: dict[str, Any] | None = None,
|
||||
retryable: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构造 success=false 的错误响应体 dict(供 jsonify 使用)。
|
||||
Args:
|
||||
code: 业务错误码。
|
||||
message: 用户可见文案。
|
||||
request_id: 可选请求 id。
|
||||
details: 可选详情。
|
||||
retryable: 是否可重试。
|
||||
Returns:
|
||||
可 jsonify 的 dict。
|
||||
"""
|
||||
payload: dict[str, Any] = {
|
||||
"success": False,
|
||||
"error": {
|
||||
"code": code,
|
||||
"message": message,
|
||||
"details": details or {},
|
||||
"retryable": retryable,
|
||||
},
|
||||
"timestamp": utc_iso_now(),
|
||||
}
|
||||
if request_id:
|
||||
payload["request_id"] = request_id
|
||||
return payload
|
||||
@@ -1,72 +0,0 @@
|
||||
"""
|
||||
backend/app/decorators.py
|
||||
文件用途:权限控制装饰器集合
|
||||
引用文件:flask, functools, models, db
|
||||
逻辑关系:为需要鉴权的 API 提供统一的用户获取、权限校验入口
|
||||
"""
|
||||
from functools import wraps
|
||||
from flask import request, jsonify, g, current_app
|
||||
from app.models import Agent, User
|
||||
from app.auth_jwt import get_current_user as _auth_current_user
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
|
||||
def _get_current_user() -> User:
|
||||
"""Resolve current user via JWT auth flow (legacy headers optional via config)."""
|
||||
user = _auth_current_user()
|
||||
if user:
|
||||
g.current_user = user
|
||||
return user
|
||||
|
||||
def require_agent_permission(f):
|
||||
"""
|
||||
装饰器:检查当前用户是否有指定 Agent 的访问权限
|
||||
核心逻辑:
|
||||
1. 从请求体中读取 agent_id
|
||||
2. 获取当前用户 (临时固定为 ID=1)
|
||||
3. 如果用户是 admin,则放行
|
||||
4. 否则检查 user.agents 是否包含该 agent
|
||||
传入参数:
|
||||
f: 被装饰的视图函数
|
||||
返回值:
|
||||
包装后的视图函数
|
||||
"""
|
||||
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
data = request.get_json(silent=True) or {}
|
||||
agent_id = data.get('agent_id') or request.args.get('agent_id')
|
||||
if not agent_id:
|
||||
raise ValidationError('agent_id is required')
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
agent = Agent.query.get(agent_id)
|
||||
if not agent:
|
||||
raise NotFoundError('Agent not found')
|
||||
g.current_agent = agent
|
||||
if user.role == 'admin':
|
||||
return f(*args, **kwargs)
|
||||
if agent not in user.agents:
|
||||
raise ForbiddenError('Permission denied for this agent')
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
|
||||
def require_admin(f):
|
||||
"""
|
||||
装饰器:限制只有管理员角色才能访问的接口
|
||||
核心逻辑:
|
||||
1. 获取当前用户
|
||||
2. 判断 user.role 是否为 'admin'
|
||||
"""
|
||||
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
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':
|
||||
raise ForbiddenError('Admin privilege required')
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
@@ -1,96 +0,0 @@
|
||||
"""
|
||||
backend/app/errors.py
|
||||
用途:定义后端统一业务异常类型,供全局异常处理器识别并输出标准错误响应。
|
||||
说明:
|
||||
1. AppError 作为基础异常,包含 code/message/http_status/details/retryable。
|
||||
2. 各子类用于表达常见语义(参数错误、未授权、无权限、资源不存在)。
|
||||
3. 业务层可直接 raise 这些异常,避免到处手写 jsonify(error)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class AppError(Exception):
|
||||
code: str
|
||||
message: str
|
||||
http_status: int = 400
|
||||
details: dict[str, Any] = field(default_factory=dict)
|
||||
retryable: bool = False
|
||||
|
||||
|
||||
class ValidationError(AppError):
|
||||
def __init__(self, message: str = "Invalid request parameters", *, details: dict[str, Any] | None = None):
|
||||
super().__init__(
|
||||
code="VALIDATION.INVALID_PARAM",
|
||||
message=message,
|
||||
http_status=400,
|
||||
details=details or {},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
class UnauthorizedError(AppError):
|
||||
def __init__(self, message: str = "Unauthorized"):
|
||||
super().__init__(code="AUTH.UNAUTHORIZED", message=message, http_status=401, retryable=False)
|
||||
|
||||
|
||||
class ForbiddenError(AppError):
|
||||
def __init__(self, message: str = "Forbidden"):
|
||||
super().__init__(code="AUTH.FORBIDDEN", message=message, http_status=403, retryable=False)
|
||||
|
||||
|
||||
class NotFoundError(AppError):
|
||||
def __init__(self, message: str = "Resource not found"):
|
||||
super().__init__(code="RESOURCE.NOT_FOUND", message=message, http_status=404, retryable=False)
|
||||
|
||||
|
||||
class ConflictError(AppError):
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Resource conflict",
|
||||
*,
|
||||
code: str = "RESOURCE.CONFLICT",
|
||||
details: dict[str, Any] | None = None,
|
||||
):
|
||||
super().__init__(
|
||||
code=code,
|
||||
message=message,
|
||||
http_status=409,
|
||||
details=details or {},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
class ServiceUnavailableError(AppError):
|
||||
def __init__(self, message: str = "Service unavailable", *, code: str = "SYSTEM.SERVICE_UNAVAILABLE"):
|
||||
super().__init__(code=code, message=message, http_status=503, retryable=True)
|
||||
|
||||
|
||||
def raise_for_status(message: str, status: int, *, code: str | None = None, details: dict[str, Any] | None = None) -> None:
|
||||
if status == 401:
|
||||
raise UnauthorizedError(message)
|
||||
if status == 403:
|
||||
raise ForbiddenError(message)
|
||||
if status == 404:
|
||||
raise NotFoundError(message)
|
||||
if status == 409:
|
||||
raise ConflictError(message, code=code or "RESOURCE.CONFLICT", details=details)
|
||||
if status == 503:
|
||||
raise ServiceUnavailableError(message, code=code or "SYSTEM.SERVICE_UNAVAILABLE")
|
||||
if status >= 500:
|
||||
raise AppError(
|
||||
code=code or "SYSTEM.INTERNAL_ERROR",
|
||||
message=message,
|
||||
http_status=status,
|
||||
details=details or {},
|
||||
)
|
||||
raise AppError(
|
||||
code=code or "VALIDATION.INVALID_PARAM",
|
||||
message=message,
|
||||
http_status=status,
|
||||
details=details or {},
|
||||
)
|
||||
@@ -0,0 +1,14 @@
|
||||
"""
|
||||
backend/app/extensions.py
|
||||
|
||||
用途:Flask 扩展单例(SQLAlchemy db、Flask-Migrate migrate)的唯一定义处。
|
||||
依赖:flask_sqlalchemy、flask_migrate。
|
||||
逻辑:create_app 调用 db.init_app / migrate.init_app;models 与 services 通过 from app import db 或
|
||||
from app.extensions import db 引用同一实例,避免在 app/__init__.py 与应用工厂混杂定义。
|
||||
"""
|
||||
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
@@ -0,0 +1,17 @@
|
||||
"""
|
||||
backend/app/jobs/__init__.py
|
||||
|
||||
用途:统一后台任务层入口(方案 D)。
|
||||
依赖:types、registry、queue、runner。
|
||||
逻辑:Web API enqueue;worker.py 调用 runner.run_forever。
|
||||
"""
|
||||
from app.jobs.types import JobStatus, JobType
|
||||
from app.jobs.queue import enqueue, enqueue_clean_job, enqueue_kb_job
|
||||
|
||||
__all__ = [
|
||||
'JobType',
|
||||
'JobStatus',
|
||||
'enqueue',
|
||||
'enqueue_kb_job',
|
||||
'enqueue_clean_job',
|
||||
]
|
||||
@@ -0,0 +1,26 @@
|
||||
"""
|
||||
backend/app/jobs/context.py
|
||||
|
||||
用途:Worker 运行时上下文,注入 config / db / logger。
|
||||
逻辑:handler.run(ctx, payload) 通过 ctx 访问依赖,禁止 import flask.request。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class JobContext:
|
||||
"""
|
||||
Worker 执行上下文。
|
||||
Attributes:
|
||||
config: Flask app.config 快照或类 dict。
|
||||
logger: 模块 logger。
|
||||
extras: 扩展字段(如 worker_label)。
|
||||
"""
|
||||
|
||||
config: dict[str, Any]
|
||||
logger: logging.Logger
|
||||
extras: dict[str, Any] = field(default_factory=dict)
|
||||
@@ -0,0 +1,8 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/__init__.py
|
||||
|
||||
用途:导入各 handler 模块以触发 @register_handler 注册。
|
||||
逻辑:Wave 2 起在 worker 启动前 import 本包。
|
||||
"""
|
||||
|
||||
from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, schedule_run, shipping_notice_parse, shipping_notice_run, wecom_directory_sync # noqa: F401
|
||||
@@ -0,0 +1,18 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/file_check_run.py
|
||||
|
||||
用途:文件检核异步执行 handler。
|
||||
逻辑:Wave 4 替代 api/file_check_tools 内 threading.Thread。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
|
||||
|
||||
@register_handler(JobType.FILE_CHECK_RUN)
|
||||
def run_file_check(ctx: JobContext, payload: dict) -> None:
|
||||
"""执行异步文件检核。"""
|
||||
ctx.logger.info('file_check_run handler skeleton invoked payload=%s', payload)
|
||||
raise NotImplementedError('file_check_run handler pending Wave 4')
|
||||
@@ -0,0 +1,35 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/kb_clean.py
|
||||
|
||||
用途:KB 文档清洗 / 路径上传任务 handler。
|
||||
逻辑:包装 knowledge_cleaning.tasks.run_clean_job / run_path_upload_job。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
|
||||
|
||||
@register_handler(JobType.KB_CLEAN)
|
||||
def run_kb_clean(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行单条 KB 清洗或路径上传任务。
|
||||
Args:
|
||||
ctx: Worker 上下文。
|
||||
payload: 须含 job_id;raw_job_type 为 path_upload 时走路径上传分支。
|
||||
"""
|
||||
job_id = int(payload['job_id'])
|
||||
raw_type = str(payload.get('raw_job_type') or 'clean').strip()
|
||||
|
||||
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job
|
||||
|
||||
if raw_type == 'path_upload':
|
||||
ok, message = run_path_upload_job(job_id)
|
||||
else:
|
||||
ok, message = run_clean_job(job_id)
|
||||
|
||||
level = ctx.logger.info if ok else ctx.logger.warning
|
||||
level('kb_clean job_id=%s raw_type=%s ok=%s message=%s', job_id, raw_type, ok, message)
|
||||
if not ok:
|
||||
raise RuntimeError(message)
|
||||
@@ -0,0 +1,29 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/kb_dify_sync.py
|
||||
|
||||
用途:KB 文档同步至 Dify 任务 handler。
|
||||
逻辑:包装 knowledge_cleaning.tasks.run_sync_job。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
|
||||
|
||||
@register_handler(JobType.KB_DIFY_SYNC)
|
||||
def run_kb_dify_sync(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
同步已清洗文档到 Dify。
|
||||
Args:
|
||||
ctx: Worker 上下文。
|
||||
payload: 须含 job_id(KbJob 主键)。
|
||||
"""
|
||||
job_id = int(payload['job_id'])
|
||||
from app.services.knowledge_cleaning.tasks import run_sync_job
|
||||
|
||||
ok, message = run_sync_job(job_id)
|
||||
level = ctx.logger.info if ok else ctx.logger.warning
|
||||
level('kb_dify_sync job_id=%s ok=%s message=%s', job_id, ok, message)
|
||||
if not ok:
|
||||
raise RuntimeError(message)
|
||||
@@ -0,0 +1,18 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/schedule_run.py
|
||||
|
||||
用途:排程任务执行 handler。
|
||||
逻辑:Wave 4 从 scheduler_service in-process 执行体迁入。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
|
||||
|
||||
@register_handler(JobType.SCHEDULE_RUN)
|
||||
def run_schedule(ctx: JobContext, payload: dict) -> None:
|
||||
"""执行单条 ScheduleTask。"""
|
||||
ctx.logger.info('schedule_run handler skeleton invoked payload=%s', payload)
|
||||
raise NotImplementedError('schedule_run handler pending Wave 4')
|
||||
@@ -0,0 +1,276 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/shipping_notice_parse.py
|
||||
|
||||
用途:发货通知接入记录异步预解析 handler。
|
||||
依赖:jobs.context、jobs.registry、intake_parse_workflow、queue.fail/finish。
|
||||
逻辑:领取时写入 parse_lease="{job_id}:{attempts}";写回/失败清理均校验 lease;
|
||||
Job 收口一律 finish_job/fail_job(owned_attempt=...) 条件 UPDATE,
|
||||
禁止依赖 Session 身份映射判断执行权。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import and_, or_, update
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, NotFoundError
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.queue import fail_job, finish_job
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import FileAsset, Job, ShippingNoticeIntake
|
||||
from app.services.shipping_notice.intake_parse_workflow import (
|
||||
fail_intake_with_stage2_cleanup,
|
||||
run_intake_parse,
|
||||
)
|
||||
|
||||
# 真终态:无论 Job 身份都不再领取
|
||||
_TERMINAL_SKIP_STATUSES = frozenset({'parsed', 'consumed', 'cancelled', 'expired'})
|
||||
# 正常可领取进入 parsing
|
||||
_CLAIMABLE_STATUSES = frozenset({'created', 'queued', 'parse_failed'})
|
||||
|
||||
|
||||
def _load_asset(asset_id: int) -> FileAsset:
|
||||
"""
|
||||
加载父级 FileAsset;软删或不存在则抛 NotFoundError。
|
||||
|
||||
Args:
|
||||
asset_id: FileAsset 主键。
|
||||
|
||||
Returns:
|
||||
可用的 FileAsset。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 资产不存在或已软删。
|
||||
"""
|
||||
asset = db.session.get(FileAsset, asset_id)
|
||||
if not asset or asset.deleted_at is not None:
|
||||
raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='关联文件资产不存在')
|
||||
return asset
|
||||
|
||||
|
||||
def _build_parse_lease(*, job_id: int | None, owned_attempt: int | None) -> str:
|
||||
"""
|
||||
构造本轮解析执行代次 token。
|
||||
|
||||
核心逻辑:有 Job 时使用 "{job_id}:{attempts}",与 claim_next_job 递增的 attempts 对齐;
|
||||
无 Job(单测直调)时使用随机 UUID。
|
||||
"""
|
||||
if job_id is not None and owned_attempt is not None:
|
||||
return f'{int(job_id)}:{int(owned_attempt)}'
|
||||
return uuid.uuid4().hex
|
||||
|
||||
|
||||
def _claim_intake_for_parsing(
|
||||
intake_no: str,
|
||||
*,
|
||||
job_id: int | None,
|
||||
owned_attempt: int | None,
|
||||
) -> tuple[ShippingNoticeIntake, str] | None:
|
||||
"""
|
||||
原子领取 Intake 并轮转 parse_lease。
|
||||
|
||||
核心逻辑:仅 created/queued/parse_failed,或 parsing 且 parse_job_id 精确等于当前 Job
|
||||
(回收漏同步时由新 attempts 轮转 lease,旧 lease 立即失效)。
|
||||
|
||||
Returns:
|
||||
(Intake, lease) 或 None。
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
lease = _build_parse_lease(job_id=job_id, owned_attempt=owned_attempt)
|
||||
claim_predicate = ShippingNoticeIntake.parse_status.in_(tuple(_CLAIMABLE_STATUSES))
|
||||
if job_id is not None:
|
||||
claim_predicate = or_(
|
||||
claim_predicate,
|
||||
and_(
|
||||
ShippingNoticeIntake.parse_status == 'parsing',
|
||||
ShippingNoticeIntake.parse_job_id == int(job_id),
|
||||
),
|
||||
)
|
||||
values: dict = {
|
||||
'parse_status': 'parsing',
|
||||
'parse_lease': lease,
|
||||
'updated_at': now,
|
||||
}
|
||||
if job_id is not None:
|
||||
values['parse_job_id'] = int(job_id)
|
||||
stmt = (
|
||||
update(ShippingNoticeIntake)
|
||||
.where(
|
||||
ShippingNoticeIntake.intake_no == intake_no,
|
||||
claim_predicate,
|
||||
)
|
||||
.values(**values)
|
||||
)
|
||||
result = db.session.execute(stmt)
|
||||
if int(result.rowcount or 0) != 1:
|
||||
db.session.rollback()
|
||||
return None
|
||||
db.session.commit()
|
||||
intake = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter_by(intake_no=intake_no)
|
||||
.first()
|
||||
)
|
||||
if intake is None:
|
||||
return None
|
||||
return intake, lease
|
||||
|
||||
|
||||
def _is_retryable_exc(exc: BaseException) -> bool:
|
||||
"""业务 NotFound / AppError.retryable=False 视为不可再排队。"""
|
||||
if isinstance(exc, NotFoundError):
|
||||
return False
|
||||
if isinstance(exc, AppError):
|
||||
return bool(getattr(exc, 'retryable', False))
|
||||
return True
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_NOTICE_PARSE)
|
||||
def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
消费发货通知预解析任务。
|
||||
|
||||
Args:
|
||||
ctx: Worker 上下文。
|
||||
payload: 须含 job_id 或 intake_no。
|
||||
"""
|
||||
raw_job_id = payload.get('job_id')
|
||||
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
|
||||
job_id = int(job.id) if job is not None else None
|
||||
# claim_next_job 已递增 attempts;该值即本轮执行代次(收口必须带入条件 UPDATE)
|
||||
owned_attempt = int(job.attempts or 0) if job is not None else None
|
||||
intake_no = str(
|
||||
(job.payload_json or {}).get('intake_no') if job else payload.get('intake_no') or ''
|
||||
).strip().upper()
|
||||
if not intake_no:
|
||||
if job_id is not None:
|
||||
fail_job(
|
||||
job_id,
|
||||
error='missing intake_no',
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
intake = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_no).first()
|
||||
if not intake:
|
||||
if job_id is not None:
|
||||
fail_job(
|
||||
job_id,
|
||||
error=f'intake not found: {intake_no}',
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
# [STEP 1] 真终态跳过
|
||||
if intake.parse_status in _TERMINAL_SKIP_STATUSES:
|
||||
if job_id is not None:
|
||||
finish_job(
|
||||
job_id,
|
||||
result={'status': intake.parse_status, 'intake_no': intake_no, 'skipped': True},
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
# [STEP 1b] parsing 但非本 Job:另一 worker 持有 → 跳过
|
||||
if (
|
||||
intake.parse_status == 'parsing'
|
||||
and job_id is not None
|
||||
and (
|
||||
intake.parse_job_id is None
|
||||
or int(intake.parse_job_id) != int(job_id)
|
||||
)
|
||||
):
|
||||
finish_job(
|
||||
job_id,
|
||||
result={'status': 'parsing', 'intake_no': intake_no, 'skipped': True},
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
# [STEP 2] 原子领取并轮转 lease
|
||||
claimed = _claim_intake_for_parsing(
|
||||
intake_no, job_id=job_id, owned_attempt=owned_attempt
|
||||
)
|
||||
if claimed is None:
|
||||
current = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_no).first()
|
||||
if job_id is not None:
|
||||
finish_job(
|
||||
job_id,
|
||||
result={
|
||||
'status': str(getattr(current, 'parse_status', None) or 'unknown'),
|
||||
'intake_no': intake_no,
|
||||
'skipped': True,
|
||||
},
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
intake, parse_lease = claimed
|
||||
intake_id = int(intake.id)
|
||||
preserved_parser = str(intake.parser_version or 'v6')
|
||||
preserved_text = intake.extracted_text
|
||||
preserved_structured = (
|
||||
dict(intake.structured_result_json)
|
||||
if isinstance(intake.structured_result_json, dict)
|
||||
else {}
|
||||
)
|
||||
preserved_warnings = list(intake.parse_warnings_json or [])
|
||||
|
||||
try:
|
||||
asset = _load_asset(intake.asset_id)
|
||||
result = run_intake_parse(intake, asset, parse_lease=parse_lease)
|
||||
if job_id is None:
|
||||
return
|
||||
status = str(result.get('status') or '')
|
||||
if status in {'parsed', 'skipped'}:
|
||||
finish_job(
|
||||
job_id,
|
||||
result=result,
|
||||
message=(
|
||||
'发货通知预解析完成'
|
||||
if status == 'parsed'
|
||||
else '接入已取消、过期或执行代次失效,跳过'
|
||||
),
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
else:
|
||||
fail_job(
|
||||
job_id,
|
||||
error=str(result.get('error_message') or 'parse failed'),
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
error_code = getattr(exc, 'code', None) or 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED'
|
||||
fail_result = fail_intake_with_stage2_cleanup(
|
||||
intake_id=intake_id,
|
||||
intake_no=intake_no,
|
||||
parser_version=preserved_parser,
|
||||
error_code=str(error_code),
|
||||
error_message=str(exc)[:1000],
|
||||
extracted_text=preserved_text,
|
||||
structured_result_json=preserved_structured,
|
||||
parse_warnings_json=preserved_warnings,
|
||||
allowed_statuses=frozenset({'parsing', 'queued', 'created'}),
|
||||
required_lease=parse_lease,
|
||||
)
|
||||
# 租约已失效:旧 Worker 不得触碰 Job(条件 UPDATE 亦会 no-op,此处直接返回)
|
||||
if str(fail_result.get('reason') or '') == 'stale_parse_lease':
|
||||
return
|
||||
retryable = _is_retryable_exc(exc)
|
||||
if job_id is not None:
|
||||
fail_job(
|
||||
job_id,
|
||||
error=str(exc),
|
||||
retryable=retryable,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
if retryable:
|
||||
raise
|
||||
Loaded 100 of 1127 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user