Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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>` 内的每个核心函数同样要求遵循上述“函数层”注释规范。
|
||||
@@ -55,11 +55,11 @@ 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 相同)
|
||||
# 货代发货通知 Agent(见 docs/shipping_notice.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 相同)
|
||||
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/
|
||||
|
||||
# 文件存储(相对 backend/ 根目录)
|
||||
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
||||
|
||||
@@ -46,6 +46,9 @@ TASK_EXECUTION_MODE=rq
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=20
|
||||
|
||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
|
||||
|
||||
# MinIO(知识库文档清洗图片托管,容器 minio-app)
|
||||
# MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1)
|
||||
MINIO_ENDPOINT=host.docker.internal:9000
|
||||
@@ -54,3 +57,6 @@ 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 基地址(默认与 PUBLIC_BASE_URL 一致)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.230:8890
|
||||
+28
-26
@@ -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
|
||||
|
||||
@@ -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,18 @@ 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、OpenAPI、签名下载链接;无尾斜杠;各环境 .env.* 覆盖)
|
||||
HXOPS_TOOLS_API_BASE=
|
||||
|
||||
# MinIO:按环境配置见 .env.dev / .env.test / .env.prod
|
||||
# MINIO_KB_IMAGE_BUCKET — 知识库文档清洗图片托管(kb-worker / export)
|
||||
@@ -121,24 +129,18 @@ 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=
|
||||
# 热点 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 # 选代表答案时「差评」反馈分阈值(≤此分排除)
|
||||
@@ -57,4 +57,59 @@ 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/shipping_notice.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
|
||||
|
||||
# 文件存储(相对 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_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=6
|
||||
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)
|
||||
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
|
||||
|
||||
# 发货 Excel 模板(可选)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
|
||||
|
||||
# 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=
|
||||
+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
|
||||
|
||||
+6
-1
@@ -46,7 +46,9 @@ frontend/public/WW_verify_46MjWA55y3PBRLid.txt
|
||||
frontend/package-lock.json
|
||||
|
||||
# IDEs
|
||||
.vscode/
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/extensions.json
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
@@ -74,3 +76,6 @@ oracle_client/
|
||||
|
||||
# local env override
|
||||
.env.local
|
||||
backend/data/kb/
|
||||
.pytest_cache/
|
||||
backend/data/fixed_assets/manifest.json
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"recommendations": ["ms-python.python", "ms-python.vscode-pylance"]
|
||||
}
|
||||
Vendored
+34
@@ -0,0 +1,34 @@
|
||||
{
|
||||
// 后端 Python 虚拟环境
|
||||
"python.defaultInterpreterPath": "${workspaceFolder}/backend/.venv/Scripts/python.exe",
|
||||
"python.terminal.activateEnvironment": true,
|
||||
"python.venvPath": "${workspaceFolder}/backend",
|
||||
"python.venvFolders": [".venv"],
|
||||
|
||||
// 默认终端:加载 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' }"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
+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,23 @@ 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/ # 权威文档(规范、上下文、流程、发布说明)
|
||||
```
|
||||
|
||||
**约定**:新逻辑优先放入对应 `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 +81,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 +151,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/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` 通过、关键页面与登录可用。
|
||||
@@ -156,4 +190,8 @@ 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) |
|
||||
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}
|
||||
'
|
||||
"""
|
||||
}
|
||||
|
||||
@@ -56,8 +56,10 @@ def create_app(config_name='default'):
|
||||
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.workspace_file_check import workspace_file_check_bp
|
||||
from app.api.internal_jobs import internal_jobs_bp
|
||||
from app.api.shipping_notice_tools import shipping_notice_bp
|
||||
from app.api.file_check_tools import file_check_bp
|
||||
from app.api.speech import speech_bp
|
||||
|
||||
# 聊天相关接口
|
||||
@@ -75,8 +77,10 @@ def create_app(config_name='default'):
|
||||
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(workspace_file_check_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(file_check_bp, url_prefix='/api/file-check')
|
||||
app.register_blueprint(speech_bp, url_prefix='/api/speech')
|
||||
|
||||
# Eagerly load persisted runtime settings so the very first request after
|
||||
@@ -87,6 +91,10 @@ def create_app(config_name='default'):
|
||||
_apply_persisted_settings(app)
|
||||
from app.services.schedule.scheduler_service import start_scheduler
|
||||
start_scheduler(app)
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
FixedAssetsSnapshotService.start_worker(app)
|
||||
from app.cli.faq_commands import init_app as init_faq_cli
|
||||
init_faq_cli(app)
|
||||
|
||||
@app.before_request
|
||||
def _sync_persisted_settings():
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
"""
|
||||
backend/app/api/__init__.py
|
||||
|
||||
用途:集中注册所有 Blueprint(Wave 1 接入 create_app)。
|
||||
依赖:各 api 子包 blueprint。
|
||||
逻辑:替代 app/__init__.py 内 15 行散乱 register_blueprint。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Flask
|
||||
|
||||
|
||||
def register_blueprints(app: Flask) -> None:
|
||||
"""
|
||||
注册全部 HTTP Blueprint,保持对外 url_prefix 不变。
|
||||
核心逻辑:Wave 0 仍从既有单体模块 import;Wave 1+ 逐步切换至分包。
|
||||
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.knowledge_base import knowledge_base_bp
|
||||
from app.api.integration import integration_bp
|
||||
from app.api.internal_jobs import internal_jobs_bp
|
||||
from app.api.speech import speech_bp
|
||||
|
||||
# [STEP 2] 已分包骨架(re-export 旧模块,Wave 1 可切换 import 来源)
|
||||
from app.api.schedule import schedule_admin_bp
|
||||
from app.api.workspace import (
|
||||
workspace_file_check_bp,
|
||||
workspace_schedule_bp,
|
||||
workspace_shipping_notice_bp,
|
||||
)
|
||||
from app.api.tools import file_check_bp, shipping_notice_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(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_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(shipping_notice_bp, url_prefix='/api/shipping-notice')
|
||||
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
|
||||
app.register_blueprint(speech_bp, url_prefix='/api/speech')
|
||||
+718
-47
@@ -1,26 +1,31 @@
|
||||
"""
|
||||
backend/app/api/admin.py
|
||||
文件用途:管理员相关 API 路由
|
||||
引用文件:flask, models, decorators
|
||||
逻辑关系:提供 Agent 配置管理、用户与权限管理接口,供前端 Admin 控制台使用
|
||||
|
||||
用途:管理员相关 API 路由(Agent、用户、权限、企业微信等)。
|
||||
依赖:flask、models、decorators、app.api.user(Casdoor 用户同步)。
|
||||
逻辑:供前端 Admin 控制台调用;创建/编辑用户时委托 user._sync_casdoor_* 与 IdP 保持同步。
|
||||
"""
|
||||
from flask import Blueprint, request, jsonify, current_app
|
||||
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, GeneralFeedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit, WecomNotifyAudit, AgentGuide
|
||||
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, GeneralFeedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit, WecomNotifyAudit, AgentGuide, KbDocument
|
||||
from app.services.minio_service import minio_service
|
||||
from app.decorators import require_admin
|
||||
from app.config import Config
|
||||
from app import db
|
||||
from app.env_persistence import persist_env_settings
|
||||
from sqlalchemy import func, desc, inspect
|
||||
from sqlalchemy import func, desc, inspect, or_
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import joinedload
|
||||
from datetime import datetime, timedelta
|
||||
import csv
|
||||
import io
|
||||
import math
|
||||
import re
|
||||
import requests
|
||||
import uuid
|
||||
from app.services.wecom_notify import send_wecom_event_message
|
||||
from app.services.oa_wecom_sync import sync_wecom_userids_from_oa
|
||||
from app.services.dify import DifyService
|
||||
from app.services.user_admin import delete_admin_users
|
||||
from app.auth_jwt import get_current_user as _get_auth_user
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
admin_bp = Blueprint('admin', __name__)
|
||||
@@ -37,6 +42,29 @@ def _raise_user_integrity_conflict(exc: IntegrityError) -> None:
|
||||
raise ConflictError('Username already exists', code='USER.USERNAME_EXISTS')
|
||||
raise ConflictError('Data uniqueness conflict', code='USER.UNIQUENESS_CONFLICT')
|
||||
|
||||
def _assert_user_unique_fields(exclude_user_id: int | None, **fields: str | None) -> None:
|
||||
"""
|
||||
校验用户唯一字段(邮箱、工号、手机号)不与其它账号冲突。
|
||||
核心逻辑:对传入的非 None 字段查询 User 表;编辑时 exclude_user_id 排除当前用户。
|
||||
@param exclude_user_id: 编辑场景传当前用户 id;创建场景传 None
|
||||
@param fields: email / employee_id / phone_number 等待校验值
|
||||
@raises ConflictError: 唯一字段已被占用
|
||||
"""
|
||||
checks = (
|
||||
('email', 'USER.EMAIL_EXISTS', 'Email already exists'),
|
||||
('employee_id', 'USER.EMPLOYEE_ID_EXISTS', 'Employee ID already exists'),
|
||||
('phone_number', 'USER.PHONE_EXISTS', 'Phone number already exists'),
|
||||
)
|
||||
for field, code, message in checks:
|
||||
value = fields.get(field)
|
||||
if value is None:
|
||||
continue
|
||||
query = db.session.query(User.id).filter(getattr(User, field) == value)
|
||||
if exclude_user_id is not None:
|
||||
query = query.filter(User.id != exclude_user_id)
|
||||
if query.first():
|
||||
raise ConflictError(message, code=code, details={'field': field})
|
||||
|
||||
def _empty_to_none(value):
|
||||
if value is None:
|
||||
return None
|
||||
@@ -450,18 +478,99 @@ def update_agent_permissions(id):
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
def _serialize_admin_user(user: User) -> dict:
|
||||
"""将 User ORM 转为管理端列表/详情 JSON 结构。"""
|
||||
return {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'email': user.email,
|
||||
'department': user.department,
|
||||
'role': user.role,
|
||||
'status': user.status,
|
||||
'real_name': user.real_name,
|
||||
'employee_id': user.employee_id,
|
||||
'phone_number': user.phone_number,
|
||||
'agent_ids': [agent.id for agent in user.agents],
|
||||
}
|
||||
|
||||
|
||||
def _apply_admin_users_filters(query):
|
||||
"""
|
||||
按 Query 参数过滤用户列表(模糊匹配文本字段)。
|
||||
支持:username, email, department, role, status, real_name, employee_id, phone_number, hide_rejected。
|
||||
"""
|
||||
if request.args.get('hide_rejected', 'false').lower() == 'true':
|
||||
query = query.filter(User.status != 'rejected')
|
||||
filter_columns = {
|
||||
'username': User.username,
|
||||
'email': User.email,
|
||||
'department': User.department,
|
||||
'role': User.role,
|
||||
'status': User.status,
|
||||
'real_name': User.real_name,
|
||||
'employee_id': User.employee_id,
|
||||
'phone_number': User.phone_number,
|
||||
}
|
||||
for key, column in filter_columns.items():
|
||||
value = (request.args.get(key) or '').strip()
|
||||
if value:
|
||||
query = query.filter(column.cast(db.String).ilike(f'%{value}%'))
|
||||
return query
|
||||
|
||||
|
||||
@admin_bp.route('/users', methods=['GET'])
|
||||
@require_admin
|
||||
def list_users():
|
||||
users = db.session.query(User).order_by(User.id.asc()).all()
|
||||
res = []
|
||||
for u in users:
|
||||
res.append({'id': u.id, 'username': u.username, 'email': u.email, 'department': u.department, 'role': u.role, 'status': u.status, 'real_name': u.real_name, 'employee_id': u.employee_id, 'phone_number': u.phone_number, 'agent_ids': [a.id for a in u.agents]})
|
||||
return jsonify(res)
|
||||
"""
|
||||
列出管理端用户。无 page 参数时返回全量数组(兼容旧调用);带 page 时分页并支持筛选。
|
||||
|
||||
Query: page, page_size, username, email, department, role, status, real_name,
|
||||
employee_id, phone_number, hide_rejected
|
||||
Returns (paginated): { items, total, page, page_size, pages }
|
||||
Returns (legacy): User[]
|
||||
"""
|
||||
query = _apply_admin_users_filters(db.session.query(User))
|
||||
|
||||
if 'page' not in request.args:
|
||||
users = query.options(joinedload(User.agents)).order_by(User.id.asc()).all()
|
||||
return jsonify([_serialize_admin_user(u) for u in users])
|
||||
|
||||
page = request.args.get('page', type=int) or 1
|
||||
page_size = request.args.get('page_size', type=int) or 20
|
||||
page = max(1, page)
|
||||
page_size = max(1, min(100, page_size))
|
||||
|
||||
total = query.count()
|
||||
pages = max(1, (total + page_size - 1) // page_size) if total else 1
|
||||
if page > pages:
|
||||
page = pages
|
||||
|
||||
users = (
|
||||
query.options(joinedload(User.agents))
|
||||
.order_by(User.id.asc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
return jsonify({
|
||||
'items': [_serialize_admin_user(u) for u in users],
|
||||
'total': int(total),
|
||||
'page': page,
|
||||
'page_size': page_size,
|
||||
'pages': pages,
|
||||
})
|
||||
|
||||
@admin_bp.route('/users', methods=['POST'])
|
||||
@require_admin
|
||||
def create_user():
|
||||
"""
|
||||
管理端创建用户:本地入库前先同步 Casdoor add-user,与改密一样保持 IdP 一致。
|
||||
核心逻辑:校验 → 构建 User → _sync_casdoor_create_user → commit;Casdoor 失败则 rollback。
|
||||
Request JSON: username, password, email, real_name, employee_id, phone_number 等
|
||||
Returns:
|
||||
201 + { id };Casdoor/唯一约束失败时抛出 AppError/ConflictError
|
||||
"""
|
||||
from app.api import user as user_api
|
||||
data = request.get_json() or {}
|
||||
required_field_errors = (
|
||||
('username', 'USER.USERNAME_REQUIRED', 'Username is required'),
|
||||
@@ -479,22 +588,51 @@ def create_user():
|
||||
email = _empty_to_none(data.get('email'))
|
||||
if not _is_valid_email(email):
|
||||
raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'})
|
||||
_assert_user_unique_fields(
|
||||
None,
|
||||
email=email,
|
||||
employee_id=_empty_to_none(data.get('employee_id')),
|
||||
phone_number=_empty_to_none(data.get('phone_number')),
|
||||
)
|
||||
user = User(username=data['username'], email=email, department=_empty_to_none(data.get('department')), role=data.get('role', 'user'), status=data.get('status', 'active'), real_name=_empty_to_none(data.get('real_name')), employee_id=_empty_to_none(data.get('employee_id')), phone_number=_empty_to_none(data.get('phone_number')))
|
||||
user.set_password(data['password'])
|
||||
if data.get('agent_ids'):
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
user.agents = agents
|
||||
db.session.add(user)
|
||||
try:
|
||||
if data.get('agent_ids'):
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
user.agents = agents
|
||||
user_api._sync_casdoor_create_user(
|
||||
username=user.username,
|
||||
password=data['password'],
|
||||
email=email,
|
||||
real_name=user.real_name,
|
||||
phone_number=user.phone_number,
|
||||
status=user.status,
|
||||
department=user.department,
|
||||
)
|
||||
db.session.commit()
|
||||
except IntegrityError as e:
|
||||
db.session.rollback()
|
||||
_raise_user_integrity_conflict(e)
|
||||
except AppError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except RuntimeError as e:
|
||||
db.session.rollback()
|
||||
user_api._raise_casdoor_add_user_error(e)
|
||||
return (jsonify({'id': user.id}), 201)
|
||||
|
||||
@admin_bp.route('/users/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_user(id):
|
||||
"""
|
||||
管理端编辑用户:资料仅写本地库;仅改密时同步 Casdoor set-password。
|
||||
核心逻辑:唯一字段预校验 → 应用本地字段与 agent_ids →(有 new_password 时)_sync_casdoor_update_user → commit。
|
||||
Request JSON: email, department, role, status, password 等;password 为空表示不改密
|
||||
Returns:
|
||||
{ status: ok };Casdoor 改密/唯一约束失败时抛出 AppError/ConflictError
|
||||
"""
|
||||
from app.api import user as user_api
|
||||
user = db.session.get(User, id)
|
||||
if not user:
|
||||
raise NotFoundError('User not found')
|
||||
@@ -503,28 +641,47 @@ def update_user(id):
|
||||
email = _empty_to_none(data.get('email'))
|
||||
if email is not None and (not _is_valid_email(email)):
|
||||
raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'})
|
||||
for k in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
|
||||
if k in data:
|
||||
if k in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
|
||||
setattr(user, k, _empty_to_none(data[k]))
|
||||
else:
|
||||
setattr(user, k, data[k])
|
||||
if data.get('password'):
|
||||
user.set_password(data['password'])
|
||||
if 'agent_ids' in data:
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
user.agents = agents
|
||||
unique_updates = {
|
||||
field: _empty_to_none(data[field])
|
||||
for field in ('email', 'employee_id', 'phone_number')
|
||||
if field in data
|
||||
}
|
||||
_assert_user_unique_fields(id, **unique_updates)
|
||||
new_password = _empty_to_none(data.get('password'))
|
||||
try:
|
||||
for k in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
|
||||
if k in data:
|
||||
if k in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
|
||||
setattr(user, k, _empty_to_none(data[k]))
|
||||
else:
|
||||
setattr(user, k, data[k])
|
||||
if new_password:
|
||||
user.set_password(new_password)
|
||||
if 'agent_ids' in data:
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
user.agents = agents
|
||||
if new_password:
|
||||
user_api._sync_casdoor_update_user(user, new_password=new_password)
|
||||
db.session.commit()
|
||||
except IntegrityError as e:
|
||||
db.session.rollback()
|
||||
_raise_user_integrity_conflict(e)
|
||||
except AppError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except RuntimeError as e:
|
||||
db.session.rollback()
|
||||
user_api._raise_casdoor_set_password_error(e)
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@admin_bp.route('/users/cleanup-rejected', methods=['POST'])
|
||||
@require_admin
|
||||
def cleanup_rejected_users():
|
||||
cnt = db.session.query(User).filter_by(status='rejected').delete()
|
||||
rejected_ids = [
|
||||
row[0]
|
||||
for row in db.session.query(User.id).filter_by(status='rejected').all()
|
||||
]
|
||||
cnt = delete_admin_users(rejected_ids)
|
||||
db.session.commit()
|
||||
return jsonify({'deleted_count': cnt})
|
||||
|
||||
@@ -538,10 +695,42 @@ def batch_delete_users():
|
||||
target_ids = [uid for uid in ids if str(uid) != str(current_user_id)]
|
||||
if not target_ids:
|
||||
raise ValidationError('No valid users')
|
||||
cnt = db.session.query(User).filter(User.id.in_(target_ids)).delete(synchronize_session=False)
|
||||
db.session.commit()
|
||||
try:
|
||||
cnt = delete_admin_users(target_ids)
|
||||
db.session.commit()
|
||||
except IntegrityError as exc:
|
||||
db.session.rollback()
|
||||
raise AppError(
|
||||
code='USER.DELETE_BLOCKED',
|
||||
message='Unable to delete user because related records still exist',
|
||||
http_status=409,
|
||||
details={'reason': str(getattr(exc, 'orig', exc))},
|
||||
) from exc
|
||||
return jsonify({'deleted_count': cnt})
|
||||
|
||||
@admin_bp.route('/users/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_user(id: int):
|
||||
"""删除单个用户,复用 delete_admin_users 的关联清理逻辑。"""
|
||||
current_user = _get_auth_user()
|
||||
if current_user and str(current_user.id) == str(id):
|
||||
raise ValidationError('Cannot delete current user')
|
||||
user = db.session.get(User, id)
|
||||
if not user:
|
||||
raise NotFoundError('User not found')
|
||||
try:
|
||||
delete_admin_users([id])
|
||||
db.session.commit()
|
||||
except IntegrityError as exc:
|
||||
db.session.rollback()
|
||||
raise AppError(
|
||||
code='USER.DELETE_BLOCKED',
|
||||
message='Unable to delete user because related records still exist',
|
||||
http_status=409,
|
||||
details={'reason': str(getattr(exc, 'orig', exc))},
|
||||
) from exc
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@admin_bp.route('/permissions/batch', methods=['POST'])
|
||||
@require_admin
|
||||
def batch_update_permissions():
|
||||
@@ -649,39 +838,175 @@ def reject_request(id):
|
||||
@admin_bp.route('/quick-questions', methods=['GET'])
|
||||
@require_admin
|
||||
def list_quick_questions():
|
||||
qqs = db.session.query(QuickQuestion).filter(QuickQuestion.user_id == None).order_by(QuickQuestion.sort_order.asc()).all()
|
||||
"""
|
||||
列出全局常用问题(含 FAQ 缓存字段)。
|
||||
@query stale_only - 可选,true 时仅返回待复审(stale_at 非空)条目
|
||||
@returns JSON 数组,每项含 answer/cache_enabled/hit_count/stale_* 等扩展字段
|
||||
"""
|
||||
stale_only = str(request.args.get('stale_only', '')).lower() in {'1', 'true', 'yes'}
|
||||
query = (
|
||||
db.session.query(QuickQuestion)
|
||||
.filter(QuickQuestion.user_id.is_(None))
|
||||
.order_by(QuickQuestion.sort_order.asc(), QuickQuestion.id.asc())
|
||||
)
|
||||
if stale_only:
|
||||
query = query.filter(QuickQuestion.stale_at.isnot(None))
|
||||
qqs = query.all()
|
||||
res = []
|
||||
for q in qqs:
|
||||
agent = db.session.get(Agent, q.agent_id)
|
||||
res.append({'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id, 'agent_name': agent.name if agent else 'Unknown', 'sort_order': q.sort_order})
|
||||
stale_doc = db.session.get(KbDocument, q.stale_kb_document_id) if q.stale_kb_document_id else None
|
||||
res.append(_serialize_admin_quick_question(q, agent.name if agent else 'Unknown', stale_doc))
|
||||
return jsonify(res)
|
||||
|
||||
|
||||
def _parse_aliases(raw_aliases) -> list[str]:
|
||||
"""
|
||||
解析别名列表,支持 JSON 数组或换行分隔字符串。
|
||||
@param raw_aliases - 请求体 aliases 字段
|
||||
@returns 去重后的别名字符串列表
|
||||
"""
|
||||
if raw_aliases is None:
|
||||
return []
|
||||
if isinstance(raw_aliases, list):
|
||||
items = [str(item).strip() for item in raw_aliases if str(item).strip()]
|
||||
elif isinstance(raw_aliases, str):
|
||||
items = [line.strip() for line in raw_aliases.splitlines() if line.strip()]
|
||||
else:
|
||||
return []
|
||||
seen: set[str] = set()
|
||||
result: list[str] = []
|
||||
for item in items:
|
||||
if item not in seen:
|
||||
seen.add(item)
|
||||
result.append(item)
|
||||
return result
|
||||
|
||||
|
||||
def _parse_expires_at(raw_value) -> datetime | None:
|
||||
"""
|
||||
解析 FAQ 过期时间。
|
||||
@param raw_value - ISO 字符串或 None
|
||||
@returns datetime 或 None
|
||||
"""
|
||||
if not raw_value:
|
||||
return None
|
||||
text = str(raw_value).strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
return datetime.fromisoformat(text.replace('Z', '+00:00')).replace(tzinfo=None)
|
||||
except ValueError:
|
||||
raise ValidationError('Invalid expires_at format')
|
||||
|
||||
|
||||
def _serialize_admin_quick_question(
|
||||
q: QuickQuestion,
|
||||
agent_name: str,
|
||||
stale_kb_document: KbDocument | None = None,
|
||||
) -> dict:
|
||||
"""
|
||||
序列化全局常用问题供管理端展示。
|
||||
@param q - QuickQuestion 实例
|
||||
@param agent_name - 所属应用名称
|
||||
@param stale_kb_document - 触发待复审的 KB 文档(可选)
|
||||
@returns 可 JSON 化的字典
|
||||
"""
|
||||
return {
|
||||
'id': q.id,
|
||||
'title': q.title,
|
||||
'question': q.question,
|
||||
'answer': q.answer,
|
||||
'aliases': q.aliases if isinstance(q.aliases, list) else [],
|
||||
'cache_enabled': bool(q.cache_enabled),
|
||||
'is_enabled': bool(q.is_enabled),
|
||||
'hit_count': q.hit_count or 0,
|
||||
'agent_id': q.agent_id,
|
||||
'agent_name': agent_name,
|
||||
'sort_order': q.sort_order,
|
||||
'expires_at': q.expires_at.isoformat() if q.expires_at else None,
|
||||
'updated_at': q.updated_at.isoformat() if getattr(q, 'updated_at', None) else None,
|
||||
'source_kb_document_ids': q.source_kb_document_ids if isinstance(q.source_kb_document_ids, list) else [],
|
||||
'stale_at': q.stale_at.isoformat() if getattr(q, 'stale_at', None) else None,
|
||||
'stale_reason': q.stale_reason,
|
||||
'stale_kb_document_id': q.stale_kb_document_id,
|
||||
'stale_kb_document_title': stale_kb_document.title if stale_kb_document else None,
|
||||
}
|
||||
|
||||
|
||||
def _apply_quick_question_payload(qq: QuickQuestion, data: dict, *, require_answer: bool = False) -> None:
|
||||
"""
|
||||
将请求体字段写入 QuickQuestion 实例。
|
||||
@param qq - 待更新的 QuickQuestion
|
||||
@param data - 请求 JSON
|
||||
@param require_answer - 创建时为 True,cache_enabled 时强制校验 answer
|
||||
"""
|
||||
if 'title' in data:
|
||||
qq.title = str(data['title']).strip()
|
||||
if 'question' in data:
|
||||
qq.question = str(data['question']).strip()
|
||||
if 'agent_id' in data:
|
||||
qq.agent_id = data['agent_id']
|
||||
if 'sort_order' in data:
|
||||
qq.sort_order = data.get('sort_order', 0)
|
||||
if 'answer' in data:
|
||||
qq.answer = str(data['answer']).strip() or None
|
||||
if 'aliases' in data:
|
||||
qq.aliases = _parse_aliases(data['aliases'])
|
||||
if 'cache_enabled' in data:
|
||||
qq.cache_enabled = bool(data['cache_enabled'])
|
||||
if 'is_enabled' in data:
|
||||
qq.is_enabled = bool(data['is_enabled'])
|
||||
if 'expires_at' in data:
|
||||
qq.expires_at = _parse_expires_at(data['expires_at'])
|
||||
if 'retriever_resources' in data and isinstance(data.get('retriever_resources'), list):
|
||||
from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq
|
||||
|
||||
apply_retriever_resources_to_faq(qq, data['retriever_resources'])
|
||||
if data.get('clear_stale'):
|
||||
from app.services.faq_kb_invalidation import clear_faq_stale
|
||||
|
||||
clear_faq_stale(qq)
|
||||
|
||||
if qq.cache_enabled and not str(qq.answer or '').strip():
|
||||
raise ValidationError('启用 FAQ 缓存时必须填写标准答案')
|
||||
if require_answer and (not qq.title or not qq.question or not qq.agent_id):
|
||||
raise ValidationError('Missing required fields')
|
||||
|
||||
|
||||
@admin_bp.route('/quick-questions', methods=['POST'])
|
||||
@require_admin
|
||||
def create_quick_question():
|
||||
"""
|
||||
创建全局常用问题,可选启用 FAQ 缓存。
|
||||
@returns 201 + {id}
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
if not data.get('title') or not data.get('question') or (not data.get('agent_id')):
|
||||
raise ValidationError('Missing required fields')
|
||||
qq = QuickQuestion(user_id=None, agent_id=data['agent_id'], title=data['title'], question=data['question'], sort_order=data.get('sort_order', 0))
|
||||
qq = QuickQuestion(user_id=None)
|
||||
_apply_quick_question_payload(qq, data, require_answer=True)
|
||||
if isinstance(data.get('retriever_resources'), list):
|
||||
from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq
|
||||
|
||||
apply_retriever_resources_to_faq(qq, data['retriever_resources'])
|
||||
qq.updated_at = datetime.utcnow()
|
||||
db.session.add(qq)
|
||||
db.session.commit()
|
||||
return (jsonify({'id': qq.id}), 201)
|
||||
|
||||
|
||||
@admin_bp.route('/quick-questions/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_quick_question(id):
|
||||
"""
|
||||
更新全局常用问题及 FAQ 缓存配置。
|
||||
@returns {status: ok}
|
||||
"""
|
||||
qq = db.session.get(QuickQuestion, id)
|
||||
if not qq:
|
||||
if not qq or qq.user_id is not None:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json() or {}
|
||||
if 'title' in data:
|
||||
qq.title = data['title']
|
||||
if 'question' in data:
|
||||
qq.question = data['question']
|
||||
if 'agent_id' in data:
|
||||
qq.agent_id = data['agent_id']
|
||||
if 'sort_order' in data:
|
||||
qq.sort_order = data['sort_order']
|
||||
_apply_quick_question_payload(qq, data)
|
||||
qq.updated_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@@ -694,13 +1019,177 @@ def delete_quick_question(id):
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates', methods=['GET'])
|
||||
@require_admin
|
||||
def list_faq_candidates():
|
||||
"""
|
||||
列出 PostgreSQL 中的热点 FAQ 候选(离线聚合结果)。
|
||||
@query agent_id - 可选,按应用筛选
|
||||
@returns { items, stats, rules }
|
||||
"""
|
||||
from app.services.hot_faq_aggregator import HotFaqAggregator
|
||||
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
|
||||
|
||||
agent_id = request.args.get('agent_id', type=int)
|
||||
items = HotFaqCandidateStore.list_candidates(agent_id)
|
||||
stats = HotFaqCandidateStore.summarize(items)
|
||||
return jsonify({
|
||||
'items': items,
|
||||
'stats': stats,
|
||||
'rules': HotFaqAggregator.get_rules_document(),
|
||||
})
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates/refresh', methods=['POST'])
|
||||
@require_admin
|
||||
def refresh_faq_candidates():
|
||||
"""
|
||||
手动触发离线热点聚合。
|
||||
@body agent_id - 可选;dry_run - 可选,仅预览
|
||||
@returns 聚合结果摘要
|
||||
"""
|
||||
from app.services.hot_faq_aggregator import HotFaqAggregator
|
||||
|
||||
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)
|
||||
|
||||
result = HotFaqAggregator.aggregate_hot_faq_candidates(agent_id=agent_id, dry_run=dry_run)
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates/promote', methods=['POST'])
|
||||
@require_admin
|
||||
def promote_faq_candidate():
|
||||
"""
|
||||
将热点候选晋升为全局 QuickQuestion(启用 FAQ 缓存),同事务更新候选状态。
|
||||
@body agent_id, q_norm - 必填;title - 可选
|
||||
@returns { id } 新建 QuickQuestion 主键
|
||||
"""
|
||||
from app.services.faq_text_utils import normalize_faq_query
|
||||
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
|
||||
|
||||
data = request.get_json() or {}
|
||||
agent_id = data.get('agent_id')
|
||||
q_norm = normalize_faq_query(str(data.get('q_norm') or ''))
|
||||
if not agent_id or not q_norm:
|
||||
raise ValidationError('agent_id and q_norm are required')
|
||||
|
||||
candidate = HotFaqCandidateStore.get_candidate(int(agent_id), q_norm)
|
||||
if not candidate:
|
||||
raise NotFoundError('FAQ candidate not found')
|
||||
|
||||
title = str(data.get('title') or candidate.get('canonical_query') or q_norm).strip()[:100]
|
||||
question = str(candidate.get('canonical_query') or q_norm).strip()
|
||||
answer = str(candidate.get('answer') or '').strip()
|
||||
if not answer:
|
||||
raise ValidationError('Candidate has no answer')
|
||||
|
||||
aliases = [q for q in (candidate.get('sample_queries') or []) if normalize_faq_query(q) != q_norm]
|
||||
|
||||
retriever_resources = candidate.get('retriever_resources') if isinstance(candidate.get('retriever_resources'), list) else None
|
||||
qq = QuickQuestion(
|
||||
user_id=None,
|
||||
agent_id=int(agent_id),
|
||||
title=title,
|
||||
question=question,
|
||||
answer=answer,
|
||||
aliases=aliases or None,
|
||||
cache_enabled=True,
|
||||
is_enabled=True,
|
||||
retriever_resources=retriever_resources,
|
||||
sort_order=int(data.get('sort_order') or 0),
|
||||
updated_at=datetime.utcnow(),
|
||||
)
|
||||
from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq
|
||||
|
||||
apply_retriever_resources_to_faq(qq, retriever_resources)
|
||||
db.session.add(qq)
|
||||
db.session.flush()
|
||||
if not HotFaqCandidateStore.mark_promoted(int(agent_id), q_norm, qq.id):
|
||||
db.session.rollback()
|
||||
raise NotFoundError('FAQ candidate not found')
|
||||
db.session.commit()
|
||||
return jsonify({'id': qq.id, 'status': 'ok'})
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates/dismiss', methods=['POST'])
|
||||
@require_admin
|
||||
def dismiss_faq_candidate():
|
||||
"""
|
||||
忽略热点候选:标记 dismissed 并设置 deny_until。
|
||||
@body agent_id, q_norm - 必填
|
||||
@returns { status: ok }
|
||||
"""
|
||||
from app.services.faq_text_utils import normalize_faq_query
|
||||
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
|
||||
|
||||
data = request.get_json() or {}
|
||||
agent_id = data.get('agent_id')
|
||||
q_norm = normalize_faq_query(str(data.get('q_norm') or ''))
|
||||
if not agent_id or not q_norm:
|
||||
raise ValidationError('agent_id and q_norm are required')
|
||||
|
||||
HotFaqCandidateStore.dismiss(int(agent_id), q_norm)
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
USAGE_BY_USER_TOP_LIMIT = 50
|
||||
|
||||
|
||||
@admin_bp.route('/reports/usage', methods=['GET'])
|
||||
@require_admin
|
||||
def usage_report():
|
||||
"""
|
||||
聊天使用分析:按应用汇总全部;按用户仅 TOP N(默认 50)并支持分页。
|
||||
Query: user_page(默认 1)、user_page_size(默认 10,最大 50)
|
||||
"""
|
||||
total = db.session.query(ChatLog).count()
|
||||
by_user = db.session.query(User.username, func.count(ChatLog.id)).join(ChatLog).group_by(User.username).all()
|
||||
by_agent = db.session.query(Agent.name, func.count(ChatLog.id)).join(ChatLog).group_by(Agent.name).all()
|
||||
return jsonify({'total': total, 'by_user': [{'username': u, 'count': c} for u, c in by_user], 'by_agent': [{'agent': a, 'count': c} for a, c in by_agent]})
|
||||
by_agent = (
|
||||
db.session.query(Agent.name, func.count(ChatLog.id))
|
||||
.join(ChatLog)
|
||||
.group_by(Agent.name)
|
||||
.order_by(desc(func.count(ChatLog.id)), Agent.name)
|
||||
.all()
|
||||
)
|
||||
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
|
||||
user_page = max(1, user_page)
|
||||
user_page_size = max(1, min(user_page_size, USAGE_BY_USER_TOP_LIMIT))
|
||||
|
||||
by_user_top = (
|
||||
db.session.query(User.username, func.count(ChatLog.id))
|
||||
.join(ChatLog)
|
||||
.group_by(User.username)
|
||||
.order_by(desc(func.count(ChatLog.id)), User.username)
|
||||
.limit(USAGE_BY_USER_TOP_LIMIT)
|
||||
.all()
|
||||
)
|
||||
user_total = len(by_user_top)
|
||||
user_pages = max(1, math.ceil(user_total / user_page_size)) if user_total else 1
|
||||
user_page = min(user_page, user_pages)
|
||||
offset = (user_page - 1) * user_page_size
|
||||
by_user_page = by_user_top[offset:offset + user_page_size]
|
||||
|
||||
return jsonify({
|
||||
'total': total,
|
||||
'by_user': [{'username': u, 'count': c} for u, c in by_user_page],
|
||||
'by_agent': [{'agent': a, 'count': c} for a, c in by_agent],
|
||||
'user_total': user_total,
|
||||
'user_page': user_page,
|
||||
'user_page_size': user_page_size,
|
||||
'user_pages': user_pages,
|
||||
'user_top_limit': USAGE_BY_USER_TOP_LIMIT,
|
||||
})
|
||||
|
||||
@admin_bp.route('/reports/feedback', methods=['GET'])
|
||||
@require_admin
|
||||
@@ -775,9 +1264,74 @@ def count_general_feedbacks_report():
|
||||
total = query.count()
|
||||
return jsonify({'table': 'general_feedbacks', 'total': int(total)})
|
||||
|
||||
def _chat_logs_report_query():
|
||||
"""
|
||||
聊天日志报表查询:关联用户与应用,供管理后台数据报表展示。
|
||||
核心逻辑:ChatLog JOIN User、Agent,按创建时间倒序。
|
||||
"""
|
||||
return (
|
||||
db.session.query(
|
||||
ChatLog,
|
||||
User.username.label('username'),
|
||||
Agent.name.label('agent_name'),
|
||||
)
|
||||
.join(User, User.id == ChatLog.user_id)
|
||||
.join(Agent, Agent.id == ChatLog.agent_id)
|
||||
)
|
||||
|
||||
|
||||
def _serialize_chat_log_report_row(log: ChatLog, username: str | None, agent_name: str | None) -> dict:
|
||||
"""
|
||||
将 ChatLog 及关联字段序列化为报表行(隐藏 run_id / 原始 ID 类外键列)。
|
||||
保留 id 供前端批量删除使用,默认不在表格列中展示。
|
||||
"""
|
||||
created_at = log.created_at.isoformat() if log.created_at else None
|
||||
return {
|
||||
'id': log.id,
|
||||
'agent_name': agent_name or '',
|
||||
'username': username or '',
|
||||
'created_at': created_at,
|
||||
'query': log.query,
|
||||
'answer': log.answer,
|
||||
'session_id': log.session_id,
|
||||
'tokens_used': log.tokens_used,
|
||||
'message_type': log.message_type,
|
||||
}
|
||||
|
||||
|
||||
def _apply_chat_logs_report_filters(query):
|
||||
"""
|
||||
对聊天日志报表查询应用列筛选(支持展示列名与 ChatLog 字段名)。
|
||||
"""
|
||||
reserved = {'limit', 'offset', 'page', 'page_size'}
|
||||
for key, value in request.args.items():
|
||||
if key in reserved or not value:
|
||||
continue
|
||||
if key == 'agent_name':
|
||||
query = query.filter(Agent.name.cast(db.String).ilike(f'%{value}%'))
|
||||
elif key == 'username':
|
||||
query = query.filter(User.username.cast(db.String).ilike(f'%{value}%'))
|
||||
elif hasattr(ChatLog, key):
|
||||
col = getattr(ChatLog, key)
|
||||
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
|
||||
return query
|
||||
|
||||
|
||||
def _list_chat_logs_report():
|
||||
"""管理后台聊天日志报表数据列表(最多 100 条,支持列筛选)。"""
|
||||
query = _apply_chat_logs_report_filters(_chat_logs_report_query())
|
||||
query = query.order_by(desc(ChatLog.created_at), desc(ChatLog.id))
|
||||
items = query.limit(100).all()
|
||||
rows = [_serialize_chat_log_report_row(log, username, agent_name) for log, username, agent_name in items]
|
||||
return jsonify(rows)
|
||||
|
||||
|
||||
@admin_bp.route('/database/<table>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_table_data(table):
|
||||
if table == 'chat_logs':
|
||||
return _list_chat_logs_report()
|
||||
|
||||
model_map = {'users': User, 'agents': Agent, 'chat_logs': ChatLog, 'feedbacks': Feedback, 'permission_requests': PermissionRequest, 'departments': Department, 'quick_questions': QuickQuestion, 'user_homepage_configs': UserHomepageConfig, 'user_favorite_agents': UserFavoriteAgent, 'user_default_agents': UserDefaultAgent}
|
||||
model = model_map.get(table)
|
||||
if not model:
|
||||
@@ -839,14 +1393,63 @@ def get_table_count(table):
|
||||
@require_admin
|
||||
def list_wecom_bindings():
|
||||
"""
|
||||
List users with optional filter for WeCom bindings.
|
||||
分页列出用户企微绑定,支持 keyword 模糊搜索与 bound_only 筛选。
|
||||
|
||||
Query: bound_only, keyword, page, page_size
|
||||
Returns: { items, total, page, page_size, pages }
|
||||
"""
|
||||
bound_only = request.args.get('bound_only', 'false').lower() == 'true'
|
||||
keyword = (request.args.get('keyword') or '').strip()
|
||||
page = request.args.get('page', type=int) or 1
|
||||
page_size = request.args.get('page_size', type=int) or 20
|
||||
page = max(1, page)
|
||||
page_size = max(1, min(100, page_size))
|
||||
|
||||
query = db.session.query(User)
|
||||
if bound_only:
|
||||
query = query.filter(User.wecom_userid.isnot(None))
|
||||
users = query.order_by(User.id.asc()).all()
|
||||
return jsonify([{'id': u.id, 'username': u.username, 'real_name': u.real_name, 'email': u.email, 'role': u.role, 'status': u.status, 'wecom_userid': u.wecom_userid, 'wecom_unionid': u.wecom_unionid, 'bound': bool(u.wecom_userid)} for u in users])
|
||||
if keyword:
|
||||
pattern = f'%{keyword}%'
|
||||
query = query.filter(or_(
|
||||
User.username.ilike(pattern),
|
||||
User.real_name.ilike(pattern),
|
||||
User.employee_id.ilike(pattern),
|
||||
User.wecom_userid.ilike(pattern),
|
||||
))
|
||||
|
||||
total = query.count()
|
||||
pages = max(1, (total + page_size - 1) // page_size) if total else 1
|
||||
if page > pages:
|
||||
page = pages
|
||||
|
||||
users = (
|
||||
query.order_by(User.id.asc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
items = [
|
||||
{
|
||||
'id': u.id,
|
||||
'username': u.username,
|
||||
'real_name': u.real_name,
|
||||
'employee_id': u.employee_id,
|
||||
'email': u.email,
|
||||
'role': u.role,
|
||||
'status': u.status,
|
||||
'wecom_userid': u.wecom_userid,
|
||||
'wecom_unionid': u.wecom_unionid,
|
||||
'bound': bool(u.wecom_userid),
|
||||
}
|
||||
for u in users
|
||||
]
|
||||
return jsonify({
|
||||
'items': items,
|
||||
'total': int(total),
|
||||
'page': page,
|
||||
'page_size': page_size,
|
||||
'pages': pages,
|
||||
})
|
||||
|
||||
@admin_bp.route('/guides/upload', methods=['POST'])
|
||||
@require_admin
|
||||
@@ -1177,3 +1780,71 @@ def wecom_notify_metrics():
|
||||
by_event[event_type] = {'sent': 0, 'failed': 0}
|
||||
by_event[event_type][status] = int(cnt)
|
||||
return jsonify({'window_days': 30, 'total': int(total), 'sent': int(sent), 'failed': int(total - sent), 'send_success_rate': round(sent / total * 100, 2) if total else 0, 'opened_24h': int(opened_24h), 'opened_24h_rate': round(opened_24h / sent * 100, 2) if sent else 0, 'by_event': by_event})
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/binding-stats', methods=['GET'])
|
||||
@require_admin
|
||||
def wecom_binding_stats():
|
||||
"""
|
||||
返回活跃用户的企微 userid 绑定统计,供管理端概览卡片使用。
|
||||
"""
|
||||
total_active = db.session.query(func.count(User.id)).filter(User.status == 'active').scalar() or 0
|
||||
bound = (
|
||||
db.session.query(func.count(User.id))
|
||||
.filter(User.status == 'active', User.wecom_userid.isnot(None), User.wecom_userid != '')
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
total_active = int(total_active)
|
||||
bound = int(bound)
|
||||
return jsonify(
|
||||
{
|
||||
'total_active': total_active,
|
||||
'bound': bound,
|
||||
'unbound': max(total_active - bound, 0),
|
||||
'bound_rate': round(bound / total_active * 100, 2) if total_active else 0,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/sync-userids', methods=['POST'])
|
||||
@require_admin
|
||||
def sync_wecom_userids_admin():
|
||||
"""
|
||||
从 OA userInfo_view 按工号同步 users.wecom_userid(workcode→employee_id,id→wecom_userid)。
|
||||
Request JSON: { "apply": false }
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
apply = bool(data.get('apply'))
|
||||
try:
|
||||
summary = sync_wecom_userids_from_oa(apply=apply)
|
||||
current_app.logger.info(
|
||||
'[wecom_sync] oa apply=%s updated=%s would_update=%s conflicts=%s local_matched=%s',
|
||||
apply,
|
||||
summary.get('updated'),
|
||||
summary.get('would_update'),
|
||||
len(summary.get('conflicts') or []),
|
||||
summary.get('local_matched'),
|
||||
)
|
||||
return jsonify(summary)
|
||||
except RuntimeError as exc:
|
||||
message = str(exc)
|
||||
if 'conflicts detected' in message.lower():
|
||||
raise ConflictError(message, details={'error_code': 'WECOM_SYNC_CONFLICTS'})
|
||||
if '未找到可用的 SQL Server ODBC 驱动' in message or 'pyodbc' in message.lower():
|
||||
raise AppError(
|
||||
code='SYSTEM.SERVICE_UNAVAILABLE',
|
||||
message='OA SQL Server driver is not available on this server',
|
||||
http_status=503,
|
||||
details={'error_code': 'OA_SQLSERVER_DRIVER_MISSING', 'technical': message[:300]},
|
||||
)
|
||||
raise AppError(
|
||||
code='SYSTEM.HTTP_ERROR',
|
||||
message='OA SQL Server sync failed. Check OA_SQLSERVER_* env and network access.',
|
||||
http_status=502,
|
||||
details={'error_code': 'OA_SQLSERVER_SYNC_FAILED', 'technical': message[:300]},
|
||||
)
|
||||
except Exception as exc:
|
||||
current_app.logger.exception('[wecom_sync] oa unexpected failure: %s', exc)
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(exc), http_status=500)
|
||||
|
||||
+144
-8
@@ -12,6 +12,7 @@ import os
|
||||
import subprocess
|
||||
import uuid
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime
|
||||
from urllib.parse import urlparse
|
||||
import requests
|
||||
@@ -901,7 +902,15 @@ def get_chat_messages():
|
||||
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 []}
|
||||
assistant_msg = {
|
||||
'role': 'assistant',
|
||||
'content': log.answer,
|
||||
'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:
|
||||
@@ -983,6 +992,61 @@ 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('/completions', methods=['POST'])
|
||||
@require_agent_permission
|
||||
def chat_completions():
|
||||
@@ -1002,6 +1066,8 @@ def chat_completions():
|
||||
query = data.get('query')
|
||||
# 前端传入的 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]
|
||||
@@ -1021,6 +1087,7 @@ def chat_completions():
|
||||
name=getattr(agent, 'name', 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 {},
|
||||
)
|
||||
user_proxy = SimpleNamespace(
|
||||
id=user_id,
|
||||
@@ -1089,7 +1156,20 @@ def chat_completions():
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
leave_supported = HRLeaveSQLServerService.supports(query)
|
||||
leave_feature_enabled = _can_use_leave_feature(agent_proxy)
|
||||
if PLMOracleService.supports(query, agent_proxy):
|
||||
|
||||
from app.services.faq_cache import FaqCacheService
|
||||
faq_hit = FaqCacheService.try_match(query, agent_id) if not normalized_files else None
|
||||
|
||||
if faq_hit:
|
||||
generator = FaqCacheService.stream_chat(
|
||||
faq_hit,
|
||||
query,
|
||||
user_proxy,
|
||||
agent_proxy,
|
||||
external_conversation_id,
|
||||
session_id=session.session_id,
|
||||
)
|
||||
elif 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:
|
||||
@@ -1101,7 +1181,7 @@ def chat_completions():
|
||||
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)
|
||||
generator = Text2SQLService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
else:
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
if HRLeaveSQLServerService.supports(query):
|
||||
@@ -1109,10 +1189,44 @@ def chat_completions():
|
||||
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()
|
||||
dify_inputs: dict[str, str] | None = None
|
||||
hxops_turn_id: str | None = None
|
||||
from app.services.file_check_tools.agent_resolver import (
|
||||
agent_declares_file_check_progress,
|
||||
is_file_check_chat_agent,
|
||||
)
|
||||
from app.services.file_check_tools.dify_inputs import build_file_check_dify_inputs
|
||||
from app.services.shipping_notice.dify_inputs import (
|
||||
build_dify_chat_inputs as build_shipping_notice_dify_inputs,
|
||||
is_shipping_notice_chat_agent,
|
||||
)
|
||||
declares_file_check = agent_declares_file_check_progress(agent_proxy)
|
||||
is_file_check_agent = is_file_check_chat_agent(agent_proxy)
|
||||
is_shipping_agent = is_shipping_notice_chat_agent(agent_proxy)
|
||||
if declares_file_check or is_file_check_agent:
|
||||
# [STEP 1] 先校验 task_id,避免 Dify Chatflow 缺参时长连接挂死
|
||||
dify_inputs = build_file_check_dify_inputs(agent_proxy, required=True)
|
||||
if is_file_check_agent:
|
||||
hxops_turn_id = uuid.uuid4().hex
|
||||
from app.services.file_check_tools.chat_turn_registry import register_file_check_chat_turn
|
||||
|
||||
register_file_check_chat_turn(
|
||||
turn_id=hxops_turn_id,
|
||||
session_id=session.session_id,
|
||||
user_id=user_proxy.id,
|
||||
agent_id=agent_proxy.id,
|
||||
query=query,
|
||||
)
|
||||
elif is_shipping_agent:
|
||||
# [STEP 2] 发货通知 Chatflow 依赖会话级 task/batch 上下文稳定定位当前任务
|
||||
dify_inputs = build_shipping_notice_dify_inputs(
|
||||
external_conversation_id or session.session_id,
|
||||
task_id=shipping_task_id,
|
||||
batch_no=shipping_batch_no,
|
||||
entry_mode="user_chat",
|
||||
user_message=query,
|
||||
trigger_source="frontend_chat",
|
||||
)
|
||||
generator = DifyService.stream_chat(
|
||||
query,
|
||||
user_proxy.id,
|
||||
@@ -1120,11 +1234,16 @@ def chat_completions():
|
||||
external_conversation_id,
|
||||
request_id=request_id,
|
||||
session_id=session.session_id,
|
||||
hxops_turn_id=hxops_turn_id if is_file_check_agent else None,
|
||||
files=normalized_files,
|
||||
inputs=dify_inputs,
|
||||
)
|
||||
|
||||
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,
|
||||
@@ -1138,6 +1257,8 @@ def chat_completions():
|
||||
|
||||
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 +1276,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,6 +1298,21 @@ 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"
|
||||
except Exception as exc:
|
||||
current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, session.session_id)
|
||||
|
||||
@@ -0,0 +1,492 @@
|
||||
"""
|
||||
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.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
|
||||
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
|
||||
|
||||
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 _tool_token_secret() -> str:
|
||||
return str(
|
||||
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
or 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, _tool_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:
|
||||
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()
|
||||
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 request.path.endswith("/excel") and _decode_download_token(request.args.get("token")):
|
||||
return
|
||||
if not 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 == "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:
|
||||
return resolve_HXOPS_TOOLS_API_BASE()
|
||||
|
||||
|
||||
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, _tool_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_turn_registry import attach_run_to_turn
|
||||
|
||||
merge_chat_log_bind_context(run, data)
|
||||
turn_id = str(data.get("hxops_turn_id") or "").strip()
|
||||
if 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 _precheck_no_data(task: ScheduleTask) -> dict | None:
|
||||
"""
|
||||
启动前预检当前任务是否存在待检资料。
|
||||
|
||||
核心逻辑:仅在数据库型检核任务上做轻量预检;若结果为空,则直接返回 no_data_to_check,
|
||||
避免创建空批次并向 ChatLog 回写 run_id。
|
||||
"""
|
||||
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
|
||||
|
||||
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)
|
||||
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"),
|
||||
"hxops_session_id": data.get("hxops_session_id"),
|
||||
"hxops_turn_id": data.get("hxops_turn_id"),
|
||||
"user_message": data.get("user_message"),
|
||||
},
|
||||
)
|
||||
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,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']
|
||||
@@ -13,6 +13,74 @@ internal_jobs_bp = Blueprint('internal_jobs', __name__)
|
||||
def run_internal_job(name: str):
|
||||
key = name.strip().lower()
|
||||
data = request.get_json(silent=True) or {}
|
||||
if key in {'fixed-assets-snapshot', 'fixed_assets_snapshot', 'fixedassets'}:
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
|
||||
summary = FixedAssetsSnapshotService.sync_once(reason='internal_api', attempt=1)
|
||||
row_count = int(summary.get('row_count') or 0)
|
||||
return jsonify({
|
||||
'summary': {
|
||||
'total_count': row_count,
|
||||
'success_count': row_count,
|
||||
'failed_count': 0,
|
||||
'skipped_count': 0,
|
||||
},
|
||||
'details': [summary],
|
||||
'errors': [],
|
||||
'step_logs': [
|
||||
{
|
||||
'step': 'fixed_assets_snapshot_sync',
|
||||
'status': 'success',
|
||||
'detail': {
|
||||
'version': summary.get('current_version'),
|
||||
'row_count': row_count,
|
||||
},
|
||||
}
|
||||
],
|
||||
})
|
||||
if key in {'faq-aggregate-hot', 'faq_hot_aggregate', 'faq-hot-aggregate'}:
|
||||
from app.services.hot_faq_aggregator import HotFaqAggregator
|
||||
|
||||
schedule_task_id = data.get('schedule_task_id')
|
||||
agent_id = data.get('agent_id')
|
||||
if schedule_task_id:
|
||||
task = db.session.get(ScheduleTask, int(schedule_task_id))
|
||||
if task and task.dify_agent_id:
|
||||
agent_id = task.dify_agent_id
|
||||
result = HotFaqAggregator.aggregate_hot_faq_candidates(
|
||||
agent_id=int(agent_id) if agent_id else None,
|
||||
dry_run=False,
|
||||
)
|
||||
if not result.get('enabled'):
|
||||
message = str(result.get('message') or 'FAQ_HOT_ENABLED is false')
|
||||
return jsonify({
|
||||
'summary': {'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 1},
|
||||
'details': [],
|
||||
'errors': [message],
|
||||
'step_logs': [{'step': 'faq_hot_aggregate', 'status': 'skipped', 'detail': {'message': message}}],
|
||||
})
|
||||
promoted = int(result.get('promoted_count') or 0)
|
||||
skipped = int(result.get('skipped_count') or 0)
|
||||
total = max(promoted + skipped, 1)
|
||||
return jsonify({
|
||||
'summary': {
|
||||
'total_count': total,
|
||||
'success_count': promoted,
|
||||
'failed_count': 0,
|
||||
'skipped_count': skipped,
|
||||
},
|
||||
'details': (result.get('candidates') or [])[:20],
|
||||
'errors': [],
|
||||
'step_logs': [{
|
||||
'step': 'faq_hot_aggregate',
|
||||
'status': 'success',
|
||||
'detail': {
|
||||
'scanned_logs': result.get('scanned_logs'),
|
||||
'promoted_count': promoted,
|
||||
'skipped_count': skipped,
|
||||
},
|
||||
}],
|
||||
})
|
||||
run_no = str(data.get('run_no') or '').strip()
|
||||
schedule_task_id = data.get('schedule_task_id')
|
||||
task = None
|
||||
@@ -53,4 +121,4 @@ 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})
|
||||
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})
|
||||
@@ -889,12 +889,24 @@ def submit_document_clean(document_id: int):
|
||||
raise ValidationError('当前文档暂无可清洗版本')
|
||||
|
||||
latest_clean_job = _latest_job_for_version(version.id, 'clean')
|
||||
if latest_clean_job and latest_clean_job.status in ('queued', 'running'):
|
||||
if latest_clean_job and latest_clean_job.status == 'running':
|
||||
payload = _serialize_job(latest_clean_job)
|
||||
payload['accepted'] = True
|
||||
payload['queue_result'] = 'already_queued'
|
||||
payload['message'] = latest_clean_job.message or '清洗任务已在处理中'
|
||||
payload['queue_result'] = 'already_running'
|
||||
payload['message'] = latest_clean_job.message or '清洗任务正在执行中'
|
||||
return jsonify(payload), 202
|
||||
if latest_clean_job and latest_clean_job.status == 'queued':
|
||||
from app.services.knowledge_cleaning.tasks import run_clean_job
|
||||
|
||||
_ok, _message = run_clean_job(latest_clean_job.id)
|
||||
db.session.expire_all()
|
||||
refreshed = db.session.get(KbJob, latest_clean_job.id)
|
||||
payload = _serialize_job(refreshed) if refreshed else {'id': latest_clean_job.id}
|
||||
payload['accepted'] = True
|
||||
payload['queue_result'] = 'inline_on_manual'
|
||||
payload['message'] = (refreshed.message if refreshed else None) or _message or '清洗任务已执行'
|
||||
status_code = 200 if refreshed and refreshed.status == 'success' else 202
|
||||
return jsonify(payload), status_code
|
||||
|
||||
version.status = 'uploaded'
|
||||
version.error_message = None
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
"""
|
||||
backend/app/api/schedule/__init__.py
|
||||
|
||||
用途:排程管理 Blueprint 入口(自 schedule_admin.py 收敛)。
|
||||
逻辑:Wave 1 前 re-export 旧模块 blueprint。
|
||||
"""
|
||||
from app.api.schedule_admin import schedule_admin_bp # noqa: F401
|
||||
|
||||
__all__ = ['schedule_admin_bp']
|
||||
@@ -106,6 +106,11 @@ def test_schedule_run(task_id: int):
|
||||
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)
|
||||
raw_kb_sync = data.get('kb_sync_enabled', False)
|
||||
if isinstance(raw_kb_sync, str):
|
||||
test_kb_sync_enabled = raw_kb_sync.strip().lower() in ('1', 'true', 'yes', 'on')
|
||||
else:
|
||||
test_kb_sync_enabled = bool(raw_kb_sync)
|
||||
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)
|
||||
@@ -190,7 +195,8 @@ def test_schedule_run(task_id: int):
|
||||
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:
|
||||
except Exception as excel_exc:
|
||||
current_app.logger.error('[schedule-test-run] excel export failed: %s', excel_exc, exc_info=True)
|
||||
file_data, file_name, file_size = (None, None, 0)
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.duration_ms = duration_ms
|
||||
@@ -204,12 +210,28 @@ def test_schedule_run(task_id: int):
|
||||
run.excel_file_data = file_data
|
||||
run.excel_file_name = file_name
|
||||
run.excel_file_size = file_size or 0
|
||||
db.session.commit()
|
||||
if test_kb_sync_enabled:
|
||||
try:
|
||||
from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb
|
||||
|
||||
db.session.refresh(task)
|
||||
db.session.refresh(run)
|
||||
sync_schedule_run_excel_to_kb(task, run, enabled=True, process_inline=True)
|
||||
db.session.refresh(run)
|
||||
except Exception as kb_exc:
|
||||
db.session.rollback()
|
||||
db.session.refresh(run)
|
||||
current_app.logger.error('[schedule-test-run] kb sync failed: %s', kb_exc, exc_info=True)
|
||||
run.kb_sync_status = 'failed'
|
||||
run.kb_group_id = getattr(task, 'kb_group_id', None)
|
||||
run.kb_sync_error = str(kb_exc)
|
||||
db.session.commit()
|
||||
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):
|
||||
@@ -224,8 +246,10 @@ def test_schedule_run(task_id: int):
|
||||
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})
|
||||
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, 'kb_sync_status': run.kb_sync_status, 'kb_sync_error': run.kb_sync_error, 'kb_document_id': run.kb_document_id})
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
run = db.session.get(ScheduleRun, run.id)
|
||||
duration_ms = int((_time.time() - start_ts) * 1000)
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.duration_ms = duration_ms
|
||||
@@ -277,7 +301,7 @@ def import_schedules():
|
||||
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')}
|
||||
task_payload = {'name': name, 'schedule_type': str(item.get('schedule_type') or 'platform_app'), 'owner_user_id': owner_user_id, 'cron_expr': cron_expr, 'schedule_timezone': item.get('schedule_timezone'), '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'), 'kb_sync_enabled': bool(item.get('kb_sync_enabled', False)), 'kb_group_id': item.get('kb_group_id')}
|
||||
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))
|
||||
@@ -285,8 +309,10 @@ def import_schedules():
|
||||
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 = create_task(name=name, schedule_type=task_payload['schedule_type'], owner_user_id=owner_user_id, cron_expr=cron_expr, schedule_timezone=task_payload['schedule_timezone'], 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']
|
||||
task.kb_sync_enabled = task_payload['kb_sync_enabled']
|
||||
task.kb_group_id = int(task_payload['kb_group_id']) if task_payload.get('kb_group_id') not in (None, '', 0, '0') else None
|
||||
db.session.commit()
|
||||
if cfg:
|
||||
upsert_schedule_task_config(task.id, cfg)
|
||||
@@ -303,13 +329,19 @@ 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 = 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(), 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(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}'
|
||||
task.kb_sync_enabled = bool(data.get('kb_sync_enabled', False))
|
||||
raw_kb_group_id = data.get('kb_group_id')
|
||||
task.kb_group_id = int(raw_kb_group_id) if raw_kb_group_id not in (None, '', 0, '0') else None
|
||||
if data_source_type == 'faq_hot_aggregate':
|
||||
task.platform_api_path = 'faq-aggregate-hot'
|
||||
else:
|
||||
task.platform_api_path = f'/{task.id}'
|
||||
db.session.commit()
|
||||
db.session.refresh(task)
|
||||
config_data = data.get('config')
|
||||
if config_data:
|
||||
if config_data and data_source_type != 'faq_hot_aggregate':
|
||||
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()
|
||||
@@ -374,16 +406,19 @@ def enable_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.schedule.cron_util import normalize_cron_expr
|
||||
from app.services.schedule.query_service import serialize_task
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
from app.services.schedule.timezone_util import normalize_schedule_timezone
|
||||
|
||||
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
|
||||
task.cron_expr = normalize_cron_expr(task.cron_expr)
|
||||
task.schedule_timezone = normalize_schedule_timezone(getattr(task, 'schedule_timezone', None))
|
||||
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone)
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/disable', methods=['POST'])
|
||||
@require_admin
|
||||
@@ -392,6 +427,7 @@ def disable_schedule(task_id: int):
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
task.enabled = False
|
||||
task.next_run_at = None
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
|
||||
@@ -446,12 +482,12 @@ def get_schedule_runs(task_id: int):
|
||||
sb = request.args.get('started_before')
|
||||
if sa:
|
||||
try:
|
||||
started_after = datetime.fromisoformat(sa)
|
||||
started_after = datetime.fromisoformat(sa.replace('Z', '+00:00'))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
if sb:
|
||||
try:
|
||||
started_before = datetime.fromisoformat(sb)
|
||||
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))
|
||||
@@ -474,4 +510,4 @@ def get_schedule_run_excel(run_id: int):
|
||||
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')
|
||||
return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
@@ -1,11 +1,29 @@
|
||||
"""
|
||||
货代发货通知 Tool API — 供 Dify Chatflow Agent 调用
|
||||
api/shipping_notice_tools.py
|
||||
|
||||
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。
|
||||
依赖:shipping_notice.tools、query_service、openapi_spec、tool_api_url、Flask Blueprint。
|
||||
逻辑:上游由 Dify/OpenAPI 或 RPA 请求进入本文件;本文件做轻量参数编排,再下沉到 services/shipping_notice/* workflow。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
from pathlib import Path
|
||||
|
||||
from app import db
|
||||
from app.errors import AppError, ServiceUnavailableError, UnauthorizedError
|
||||
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 import tools as shipping_tools
|
||||
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
|
||||
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||
@@ -13,6 +31,66 @@ 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 自动触发。
|
||||
|
||||
核心逻辑:对齐文件检核 Tool,只接受 `Authorization: Bearer <token>` 或
|
||||
`X-Integration-Key`,并统一使用 `INTEGRATION_API_KEY` 作为服务端校验值;
|
||||
未配置时报服务不可用,缺失或错误时报未授权。
|
||||
"""
|
||||
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 的错误码,保持与文件检核 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 结构。"""
|
||||
return jsonify({
|
||||
"ok": False,
|
||||
"error_code": _tool_error_code(exc),
|
||||
"message": exc.message,
|
||||
}), 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()
|
||||
@@ -26,14 +104,21 @@ 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"])
|
||||
def openapi_spec():
|
||||
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
|
||||
return jsonify(_dify_openapi_spec())
|
||||
|
||||
|
||||
@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())
|
||||
@@ -41,6 +126,7 @@ def checkpoint_catalog():
|
||||
|
||||
@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)
|
||||
@@ -49,22 +135,106 @@ def openapi_dify_yaml():
|
||||
|
||||
@shipping_notice_bp.route("/tools/create_task", methods=["POST"])
|
||||
def tool_create_task():
|
||||
"""
|
||||
创建单个发货任务。
|
||||
【AI 触发时机】:当用户首次提交一张新的发货通知、当前会话里还没有对应任务时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.create_task(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/create_batch", methods=["POST"])
|
||||
def tool_create_batch():
|
||||
"""
|
||||
创建或复用发货批次。
|
||||
【AI 触发时机】:当用户一次处理多份发货通知,需要把多任务挂到同一批次时调用。
|
||||
"""
|
||||
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 = 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"])
|
||||
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/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"])
|
||||
def tool_upload_inventory_file():
|
||||
"""Multipart upload — parse server-side without sending Excel through LLM."""
|
||||
"""
|
||||
服务器侧接收库存 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))
|
||||
@@ -72,72 +242,171 @@ def tool_upload_inventory_file():
|
||||
|
||||
@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"])
|
||||
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"])
|
||||
def tool_ensure_inventory():
|
||||
"""
|
||||
保证任务已取得库存数据。
|
||||
【AI 触发时机】:当发货通知已确认,下一步需要让系统拿到库存快照时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.ensure_inventory(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/auto_progress", methods=["POST"])
|
||||
def tool_auto_progress():
|
||||
"""
|
||||
自动推进任务。
|
||||
【AI 触发时机】:当用户说“继续处理”“自动推进”“跑到下一步”时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.auto_progress(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/match_inventory", methods=["POST"])
|
||||
def tool_match_inventory():
|
||||
"""
|
||||
执行库存匹配。
|
||||
【AI 触发时机】:当发货通知与库存都已准备好,需要判断是否缺货并生成匹配结果时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.match_inventory(_payload()))
|
||||
|
||||
|
||||
@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"])
|
||||
def tool_generate_shipment_excel():
|
||||
"""
|
||||
生成出货 Excel。
|
||||
【AI 触发时机】:当库存匹配已通过,用户要求导出货代上传模板时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.generate_excel(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/upload_to_freight", methods=["POST"])
|
||||
def tool_upload_to_freight():
|
||||
"""
|
||||
上传到货代系统或确认人工上传完成。
|
||||
【AI 触发时机】:当用户要求推送到货代系统,或确认已手工完成上传时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.upload_to_freight(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/get_task_status", methods=["POST"])
|
||||
def tool_get_task_status():
|
||||
"""
|
||||
查询任务状态。
|
||||
【AI 触发时机】:当 Agent 只拿到任务号/会话号,需要先确认当前卡点后再决定下一步时调用。
|
||||
"""
|
||||
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:
|
||||
return jsonify({"status": "failed", "message": "batch_no is required"}), 400
|
||||
batch = get_batch_by_no(batch_no)
|
||||
if not batch:
|
||||
return jsonify({"status": "failed", "message": "batch not found"}), 404
|
||||
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("/tools/switch_focus_task", methods=["POST"])
|
||||
def tool_switch_focus_task():
|
||||
"""
|
||||
切换批次当前焦点任务。
|
||||
【AI 触发时机】:当用户在同一批次里要求“看第 N 个任务”或切换当前处理对象时调用。
|
||||
"""
|
||||
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:
|
||||
return jsonify({"status": "failed", "message": "batch_no and task_no are required"}), 400
|
||||
batch = get_batch_by_no(batch_no)
|
||||
if not batch:
|
||||
return jsonify({"status": "failed", "message": "batch not found"}), 404
|
||||
task = get_task_in_batch(batch_no, task_no)
|
||||
if not task:
|
||||
return jsonify({"status": "failed", "message": "task not found in batch"}), 404
|
||||
batch.current_focus_task_no = task.task_no
|
||||
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/inventory-ready", methods=["POST"])
|
||||
def rpa_inventory_ready():
|
||||
"""RPA 回调入口:上报库存导出结果并回写任务状态。"""
|
||||
return jsonify(shipping_tools.rpa_report_inventory(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/rpa/upload-complete", methods=["POST"])
|
||||
def rpa_upload_complete():
|
||||
"""RPA 回调入口:上报货代上传结果并回写任务状态。"""
|
||||
return jsonify(shipping_tools.rpa_report_upload(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tasks/<task_no>/export", methods=["GET"])
|
||||
def download_task_export(task_no: str):
|
||||
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
|
||||
"""下载任务已生成的出货 Excel。"""
|
||||
task = get_task_by_ref(task_no)
|
||||
err_msg = task_export_error_message(task)
|
||||
if err_msg:
|
||||
return jsonify({"error": err_msg}), 404
|
||||
resolved = resolve_task_export_download(task)
|
||||
assert resolved is not None
|
||||
path, download_name = resolved
|
||||
return send_file(
|
||||
path,
|
||||
as_attachment=True,
|
||||
download_name=task.export_file_name or path.name,
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
download_name=download_name,
|
||||
mimetype=EXPORT_MIME_TYPE,
|
||||
)
|
||||
@@ -0,0 +1,10 @@
|
||||
"""
|
||||
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
|
||||
|
||||
__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,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']
|
||||
+517
-5
@@ -1,6 +1,7 @@
|
||||
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.services.feedback_notify import send_feedback_group_notification
|
||||
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
|
||||
@@ -22,6 +23,8 @@ user_bp = Blueprint('user', __name__)
|
||||
_WECOM_ACCESS_TOKEN_CACHE = {'token': None, 'expires_at': None}
|
||||
_WECOM_STATE_CACHE = {}
|
||||
_WECOM_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 +111,27 @@ 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]:
|
||||
"""
|
||||
列出企微集成尚未配置的环境项。
|
||||
Returns:
|
||||
缺失的配置键名列表,如 WECOM_ENABLED、WECOM_CORP_ID 等。
|
||||
"""
|
||||
missing: list[str] = []
|
||||
if not current_app.config.get('WECOM_ENABLED'):
|
||||
missing.append('WECOM_ENABLED')
|
||||
if not _clean_str(current_app.config.get('WECOM_CORP_ID')):
|
||||
missing.append('WECOM_CORP_ID')
|
||||
if not _clean_str(current_app.config.get('WECOM_AGENT_ID')):
|
||||
missing.append('WECOM_AGENT_ID')
|
||||
if not _clean_str(current_app.config.get('WECOM_SECRET')):
|
||||
missing.append('WECOM_SECRET')
|
||||
return missing
|
||||
|
||||
|
||||
def _is_wecom_configured() -> bool:
|
||||
"""企微 Corp/Agent/Secret 与总开关均已配置时返回 True。"""
|
||||
return len(_get_wecom_config_missing_fields()) == 0
|
||||
|
||||
def _issue_casdoor_state(redirect_uri: str):
|
||||
exp_ts = int((datetime.utcnow() + timedelta(minutes=10)).timestamp())
|
||||
@@ -261,6 +283,218 @@ def _casdoor_set_password(user_owner: str, user_name: str, old_password: str, ne
|
||||
if data.get('status') != 'ok':
|
||||
_raise_casdoor_set_password_error(data)
|
||||
|
||||
def _is_casdoor_user_exists_error(message: str) -> bool:
|
||||
lowered = (message or '').lower()
|
||||
return 'already exist' in lowered or 'duplicate' in lowered or 'has existed' in lowered
|
||||
|
||||
def _raise_casdoor_add_user_error(source) -> None:
|
||||
"""
|
||||
将 Casdoor add-user 失败映射为稳定业务错误码,供管理端创建用户时展示。
|
||||
@param source: Casdoor JSON 响应、RuntimeError 文本或其它异常来源
|
||||
Raises:
|
||||
ConflictError: Casdoor 侧用户名/邮箱已存在
|
||||
AppError: 密码策略或 IdP 同步失败
|
||||
"""
|
||||
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_user_exists_error(lowered):
|
||||
raise ConflictError('Username already exists in Casdoor', code='USER.USERNAME_EXISTS', details={'field': 'username', 'technical': msg_text})
|
||||
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
|
||||
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='Password does not meet security requirements', http_status=400)
|
||||
raise AppError(code='CASDOOR_ADD_USER_FAILED', message='Failed to create user in authentication system. Please try again or contact the administrator.', http_status=502, details={'technical': msg_text or str(source or '')[:300]})
|
||||
|
||||
def _build_casdoor_user_profile_payload(*, username: str, email: str, real_name=None, phone_number=None, status='active', department=None) -> dict:
|
||||
"""
|
||||
组装 Casdoor 用户资料字段(create/update 共用),不含 password。
|
||||
@param username: Casdoor name(与本地 username 一致)
|
||||
@param email: 邮箱
|
||||
@param real_name: 显示名/真实姓名
|
||||
@param phone_number: 手机号
|
||||
@param status: 本地账号状态;非 active 时 Casdoor 设为禁用
|
||||
@param department: 部门,映射至 affiliation
|
||||
Returns:
|
||||
Casdoor User JSON 对象(资料部分)
|
||||
"""
|
||||
display_name = _clean_str(real_name) or username
|
||||
payload = {
|
||||
'owner': _casdoor_user_owner(),
|
||||
'name': username,
|
||||
'email': email or '',
|
||||
'displayName': display_name,
|
||||
'realName': _clean_str(real_name) or '',
|
||||
'phone': _clean_str(phone_number) or '',
|
||||
'isForbidden': _clean_str(status) not in (None, 'active'),
|
||||
}
|
||||
department_value = _clean_str(department)
|
||||
if department_value:
|
||||
payload['affiliation'] = department_value
|
||||
return payload
|
||||
|
||||
def _build_casdoor_user_payload(*, username: str, password: str, email: str, real_name=None, phone_number=None, status='active', department=None) -> dict:
|
||||
"""
|
||||
组装 Casdoor add-user 请求体,字段与本地 User 模型对齐。
|
||||
@param username: Casdoor name(与本地 username 一致)
|
||||
@param password: 初始明文密码
|
||||
@param email: 邮箱
|
||||
@param real_name: 显示名/真实姓名
|
||||
@param phone_number: 手机号
|
||||
@param status: 本地账号状态;非 active 时 Casdoor 设为禁用
|
||||
@param department: 部门,映射至 affiliation
|
||||
Returns:
|
||||
Casdoor User JSON 对象
|
||||
"""
|
||||
payload = _build_casdoor_user_profile_payload(
|
||||
username=username,
|
||||
email=email,
|
||||
real_name=real_name,
|
||||
phone_number=phone_number,
|
||||
status=status,
|
||||
department=department,
|
||||
)
|
||||
payload['password'] = password
|
||||
return payload
|
||||
|
||||
def _casdoor_add_user(user_payload: dict):
|
||||
"""
|
||||
调用 Casdoor /api/add-user 创建 IdP 用户。
|
||||
核心逻辑:使用 Client ID/Secret Basic Auth,与 set-password 管理 API 一致。
|
||||
@param user_payload: Casdoor User 对象(owner/name/password 等)
|
||||
Raises:
|
||||
RuntimeError: HTTP 或配置异常
|
||||
AppError: Casdoor 返回业务错误(经 _raise_casdoor_add_user_error 映射)
|
||||
"""
|
||||
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/add-user'
|
||||
resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8)
|
||||
try:
|
||||
data = resp.json() or {}
|
||||
except ValueError:
|
||||
raise RuntimeError(f'Casdoor add-user failed: HTTP {resp.status_code} {resp.text[:200]}')
|
||||
if data.get('status') != 'ok':
|
||||
_raise_casdoor_add_user_error(data)
|
||||
|
||||
def _sync_casdoor_create_user(*, username: str, password: str, email: str, real_name=None, phone_number=None, status='active', department=None):
|
||||
"""
|
||||
管理端创建用户时同步至 Casdoor,与改密逻辑一致:Casdoor 已配置则必须成功,否则跳过。
|
||||
核心逻辑:构建 add-user payload → 调 _casdoor_add_user;本地库 commit 由调用方负责。
|
||||
@param username: 本地 username,同步为 Casdoor name
|
||||
@param password: 初始明文密码
|
||||
@param email: 邮箱
|
||||
@param real_name: 真实姓名
|
||||
@param phone_number: 手机号
|
||||
@param status: 本地账号状态
|
||||
@param department: 部门
|
||||
Raises:
|
||||
AppError / ConflictError: Casdoor 创建失败
|
||||
"""
|
||||
if not _is_casdoor_configured():
|
||||
return
|
||||
payload = _build_casdoor_user_payload(
|
||||
username=username,
|
||||
password=password,
|
||||
email=email,
|
||||
real_name=real_name,
|
||||
phone_number=phone_number,
|
||||
status=status,
|
||||
department=department,
|
||||
)
|
||||
_casdoor_add_user(payload)
|
||||
|
||||
def _raise_casdoor_update_user_error(source) -> None:
|
||||
"""
|
||||
将 Casdoor update-user 失败映射为稳定业务错误码,供管理端编辑用户时展示。
|
||||
@param source: Casdoor JSON 响应、RuntimeError 文本或其它异常来源
|
||||
Raises:
|
||||
ConflictError: Casdoor 侧邮箱等唯一字段冲突
|
||||
AppError: IdP 同步失败
|
||||
"""
|
||||
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_user_missing_error(lowered):
|
||||
_raise_casdoor_user_not_in_idp(source)
|
||||
if _is_casdoor_user_exists_error(lowered) or ('email' in lowered and 'already' in lowered):
|
||||
raise ConflictError('Email already exists in Casdoor', code='USER.EMAIL_EXISTS', details={'field': 'email', 'technical': msg_text})
|
||||
raise AppError(code='CASDOOR_UPDATE_USER_FAILED', message='Failed to update user in authentication system. Please try again or contact the administrator.', http_status=502, details={'technical': msg_text or str(source or '')[:300]})
|
||||
|
||||
def _casdoor_update_user(user_payload: dict):
|
||||
"""
|
||||
调用 Casdoor /api/update-user 更新 IdP 用户资料。
|
||||
核心逻辑:使用 Client ID/Secret Basic Auth,与 add-user/set-password 管理 API 一致。
|
||||
@param user_payload: Casdoor User 对象(owner/name 及待更新字段)
|
||||
Raises:
|
||||
RuntimeError: HTTP 或配置异常
|
||||
AppError: Casdoor 返回业务错误(经 _raise_casdoor_update_user_error 映射)
|
||||
"""
|
||||
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/update-user'
|
||||
resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8)
|
||||
try:
|
||||
data = resp.json() or {}
|
||||
except ValueError:
|
||||
raise RuntimeError(f'Casdoor update-user failed: HTTP {resp.status_code} {resp.text[:200]}')
|
||||
if data.get('status') != 'ok':
|
||||
_raise_casdoor_update_user_error(data)
|
||||
|
||||
def _sync_casdoor_admin_set_password(user: User, new_password: str):
|
||||
"""
|
||||
管理端重设密码时同步 Casdoor(无旧密码,与 token 重置一致)。
|
||||
IdP 用户不存在时抛出 CASDOOR_USER_NOT_IN_IDP,由上层决定是否 fallback add-user。
|
||||
@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 _sync_casdoor_update_user(user: User, *, new_password: str | None = None):
|
||||
"""
|
||||
管理端编辑用户时同步 Casdoor:仅改密时 set-password;IdP 无账号则 add-user 补建。
|
||||
核心逻辑:资料字段只写本地库,不调用 update-user;无新密码则跳过 Casdoor。
|
||||
@param user: 已应用本地变更但未 commit 的 User 实例
|
||||
@param new_password: 管理员设置的新密码;None 表示不改密
|
||||
Raises:
|
||||
AppError / ConflictError: Casdoor 改密或补建失败
|
||||
"""
|
||||
if not _is_casdoor_configured() or not new_password:
|
||||
return
|
||||
|
||||
def _provision_missing_user_in_casdoor():
|
||||
_sync_casdoor_create_user(
|
||||
username=user.username,
|
||||
password=new_password,
|
||||
email=user.email,
|
||||
real_name=user.real_name,
|
||||
phone_number=user.phone_number,
|
||||
status=user.status,
|
||||
department=user.department,
|
||||
)
|
||||
|
||||
try:
|
||||
_sync_casdoor_admin_set_password(user, new_password)
|
||||
except AppError as exc:
|
||||
if exc.code == 'CASDOOR_USER_NOT_IN_IDP':
|
||||
_provision_missing_user_in_casdoor()
|
||||
return
|
||||
raise
|
||||
|
||||
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
|
||||
@@ -1375,6 +1609,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'])
|
||||
@@ -1393,7 +1636,12 @@ def home():
|
||||
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]
|
||||
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()
|
||||
@@ -1560,6 +1808,231 @@ 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={
|
||||
'error_code': 'WECOM_RESET_NOT_CONFIGURED',
|
||||
'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,
|
||||
details={'error_code': 'WECOM_NOTIFY_DISABLED'},
|
||||
)
|
||||
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,
|
||||
details={'error_code': 'PASSWORD_RESET_URL_NOT_CONFIGURED'},
|
||||
)
|
||||
|
||||
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={
|
||||
'error_code': 'PASSWORD_RESET_RATE_LIMITED',
|
||||
'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 +2063,33 @@ 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,
|
||||
details={'error_code': 'RESET_TOKEN_INVALID'},
|
||||
)
|
||||
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)
|
||||
@@ -1623,6 +2110,10 @@ def get_agent_details(id):
|
||||
if not has_permission:
|
||||
raise ForbiddenError('Access denied')
|
||||
extra_config = agent.extra_config or {}
|
||||
if isinstance(extra_config, dict):
|
||||
from app.services.file_check_tools.task_resolver import enrich_agent_extra_if_file_check
|
||||
|
||||
extra_config = enrich_agent_extra_if_file_check(agent)
|
||||
dify_app_type = extra_config.get('dify_app_type') if isinstance(extra_config, dict) else None
|
||||
|
||||
dify_parameters = None
|
||||
@@ -1688,6 +2179,27 @@ def create_announcement():
|
||||
db.session.commit()
|
||||
return (jsonify({'message': 'Created', 'id': ann.id}), 201)
|
||||
|
||||
@user_bp.route('/announcements/<int:id>', methods=['PUT'])
|
||||
def update_announcement(id):
|
||||
"""
|
||||
更新公告(仅管理员)。
|
||||
|
||||
核心逻辑:校验 title/content 非空后更新 Announcement 记录。
|
||||
"""
|
||||
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 = db.session.get(Announcement, id)
|
||||
if not ann:
|
||||
raise NotFoundError('Not found')
|
||||
ann.title = data['title']
|
||||
ann.content = data['content']
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Updated'})
|
||||
|
||||
@user_bp.route('/announcements/<int:id>', methods=['DELETE'])
|
||||
def delete_announcement(id):
|
||||
user = _get_current_user()
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
"""
|
||||
backend/app/api/workspace/__init__.py
|
||||
|
||||
用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check)。
|
||||
逻辑:Wave 1 前 re-export 旧 workspace_* 模块。
|
||||
"""
|
||||
from app.api.workspace_schedule import workspace_schedule_bp # noqa: F401
|
||||
from app.api.workspace_shipping_notice import workspace_shipping_notice_bp # noqa: F401
|
||||
from app.api.workspace_file_check import workspace_file_check_bp # noqa: F401
|
||||
|
||||
__all__ = [
|
||||
'workspace_schedule_bp',
|
||||
'workspace_shipping_notice_bp',
|
||||
'workspace_file_check_bp',
|
||||
]
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/app/api/workspace/file_check.py
|
||||
|
||||
用途:工作台文件检核路由(Wave 1 自 workspace_file_check.py 迁入)。
|
||||
"""
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/app/api/workspace/schedule.py
|
||||
|
||||
用途:工作台排程路由(Wave 1 自 workspace_schedule.py 迁入)。
|
||||
"""
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/app/api/workspace/shipping_notice.py
|
||||
|
||||
用途:工作台出货通知路由(Wave 1 自 workspace_shipping_notice.py 迁入)。
|
||||
"""
|
||||
@@ -0,0 +1,179 @@
|
||||
"""
|
||||
backend/app/api/workspace_file_check.py
|
||||
|
||||
用途:工作台文件检核进度轮询 API(对话页 tool_run_progress)。
|
||||
依赖:file_check_tools.chat_log_run_resolver、schedule.query_service。
|
||||
逻辑:前端按 chat_log_id / run_id 轮询检核批次状态与 Excel 链接。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.errors import NotFoundError, UnauthorizedError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.file_check_tools.chat_log_run_resolver import find_run_for_chat_log
|
||||
from app.services.schedule.query_service import get_run, serialize_run
|
||||
|
||||
workspace_file_check_bp = Blueprint("workspace_file_check", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
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),
|
||||
}
|
||||
|
||||
|
||||
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:
|
||||
return jsonify({"ok": False, "error": "task_id_required"}), 400
|
||||
if not chat_log_id or chat_log_id <= 0:
|
||||
return jsonify({"ok": False, "error": "chat_log_id_required"}), 400
|
||||
|
||||
run = find_run_for_chat_log(task_id=task_id, chat_log_id=chat_log_id)
|
||||
return jsonify({
|
||||
"ok": True,
|
||||
"run": _serialize_progress_run(run) if run else None,
|
||||
"match_source": "chat_log" if run else None,
|
||||
})
|
||||
|
||||
|
||||
@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",
|
||||
)
|
||||
@@ -19,8 +19,8 @@ def workspace_schedule_runs():
|
||||
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
|
||||
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))
|
||||
|
||||
|
||||
@@ -1,23 +1,40 @@
|
||||
"""
|
||||
api/workspace_shipping_notice.py
|
||||
|
||||
用途:提供 HXOPS 工作台与聊天前端使用的发货通知用户态 API。
|
||||
依赖:auth_jwt、query_service、shipping_notice.tools、notice_upload、chat_actions。
|
||||
逻辑:前端通过本 Blueprint 访问用户鉴权路由;本文件做权限校验与参数编排,再调用 shipping_notice service/workflow 返回页面所需数据。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
from pathlib import Path
|
||||
|
||||
from app import db
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.models import ShippingTask
|
||||
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 CP_EXPORT_GENERATED, CP_NOTICE_TEXT_EXTRACTION_FAILED, AUTO_CHAIN_FALLBACK, MAP_JSON
|
||||
from app.services.shipping_notice.query_service import (
|
||||
EXPORT_MIME_TYPE,
|
||||
get_batch_for_user,
|
||||
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,
|
||||
)
|
||||
|
||||
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""校验当前请求用户,统一返回 `(user, error_response)` 结构。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return None, (jsonify({"error": "Unauthorized"}), 401)
|
||||
@@ -26,16 +43,191 @@ def _require_user():
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks", methods=["GET"])
|
||||
def workspace_shipping_tasks():
|
||||
"""列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
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, process_status=process_status, limit=limit))
|
||||
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, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
limit = int(request.args.get("limit") or 100)
|
||||
return jsonify(list_batches_for_user(user.id, limit=limit))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-batches/create-from-notices", methods=["POST"])
|
||||
def workspace_create_shipping_batch_from_notices():
|
||||
"""接收多份发货通知附件,创建批次并交给后台编排器逐票推进。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
|
||||
uploads = request.files.getlist("files")
|
||||
if not uploads:
|
||||
single = request.files.get("file")
|
||||
if single:
|
||||
uploads = [single]
|
||||
if not uploads:
|
||||
return jsonify({"error": "files 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,
|
||||
)
|
||||
|
||||
conversation_id = str(request.form.get("conversation_id") or "").strip()
|
||||
notice_items: list[dict] = []
|
||||
for upload in uploads:
|
||||
raw = upload.read() or b""
|
||||
filename = upload.filename or "notice"
|
||||
source_type = guess_source_type(filename)
|
||||
text = ""
|
||||
warnings: list[str] = []
|
||||
try:
|
||||
temp_task_no = f"TMP-{len(notice_items) + 1}"
|
||||
saved_path = save_task_notice_upload(temp_task_no, filename, raw)
|
||||
text, meta = extract_notice_text(saved_path)
|
||||
warnings = list(meta.get("warnings") or []) if isinstance(meta, dict) else []
|
||||
except Exception as exc:
|
||||
warnings = [f"notice_extract_failed:{exc}"]
|
||||
if text:
|
||||
limit = max_notice_chars()
|
||||
if len(text) > limit:
|
||||
text = text[:limit]
|
||||
warnings.append(f"notice_text_truncated:{limit}")
|
||||
notice_items.append(
|
||||
{
|
||||
"source_type": source_type,
|
||||
"source_file_name": filename,
|
||||
"source_file_type": str(getattr(upload, "mimetype", "") or "").strip() or None,
|
||||
"raw_text": text,
|
||||
"warnings": warnings,
|
||||
}
|
||||
)
|
||||
|
||||
payload = {
|
||||
"user_id": user.id,
|
||||
"conversation_id": conversation_id or None,
|
||||
"file_count": len(notice_items),
|
||||
"notice_items": notice_items,
|
||||
# 上传接口先快速完成建批/建任务与 raw_text 落库,避免请求阻塞;
|
||||
# 后续首轮解析与可自动推进步骤交给后台编排线程逐票执行。
|
||||
"defer_parse": True,
|
||||
}
|
||||
created = shipping_tools.create_batch_tasks(payload)
|
||||
data = created.get("data") if isinstance(created, dict) else None
|
||||
batch_data = data.get("batch") if isinstance(data, dict) else None
|
||||
tasks_data = data.get("tasks") if isinstance(data, dict) else None
|
||||
batch_no = str(created.get("batch_no") or (batch_data or {}).get("batch_no") or "").strip()
|
||||
orchestrator_started = False
|
||||
if batch_no:
|
||||
from app.services.shipping_notice.batch_orchestrator import start_batch_orchestrator
|
||||
|
||||
orchestrator_started = start_batch_orchestrator(batch_no)
|
||||
if isinstance(data, dict) and batch_no:
|
||||
focus_task = get_focus_task_for_batch(batch_no, user.id)
|
||||
if focus_task:
|
||||
data["focus_task"] = serialize_task_summary(focus_task)
|
||||
if isinstance(tasks_data, list):
|
||||
data["tasks"] = tasks_data
|
||||
data["orchestrator_started"] = orchestrator_started
|
||||
if isinstance(created, dict):
|
||||
base_message = str(created.get("message") or "").strip()
|
||||
if orchestrator_started:
|
||||
created["message"] = (
|
||||
f"{base_message},后台已开始逐票处理。"
|
||||
if base_message
|
||||
else "后台已开始逐票处理。"
|
||||
)
|
||||
return jsonify(created)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>", methods=["GET"])
|
||||
def workspace_shipping_batch_detail(batch_no: str):
|
||||
"""返回批次详情、批次内任务列表和当前焦点任务。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
focus_task = get_focus_task_for_batch(batch_no, user.id)
|
||||
return jsonify(
|
||||
{
|
||||
**serialize_batch_summary(batch),
|
||||
"tasks": list_tasks_for_batch(batch_no, user.id),
|
||||
"focus_task": serialize_task_summary(focus_task) if focus_task else None,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>/tasks", methods=["GET"])
|
||||
def workspace_shipping_batch_tasks(batch_no: str):
|
||||
"""返回指定批次下的任务列表。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
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, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
focus_task = get_focus_task_for_batch(batch_no, user.id)
|
||||
if not focus_task:
|
||||
return jsonify({"error": "Focus task not found"}), 404
|
||||
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, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
data = request.get_json(silent=True) or {}
|
||||
task_no = str(data.get("task_no") or data.get("target_task_no") or "").strip()
|
||||
if not task_no:
|
||||
return jsonify({"error": "task_no is required"}), 400
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task or task.batch_id != batch.id:
|
||||
return jsonify({"error": "Task not found in batch"}), 404
|
||||
batch.current_focus_task_no = task.task_no
|
||||
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, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
@@ -58,6 +250,7 @@ def workspace_create_shipping_task():
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/create-from-notice", methods=["POST"])
|
||||
def workspace_create_shipping_task_from_notice():
|
||||
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
@@ -75,7 +268,11 @@ def workspace_create_shipping_task_from_notice():
|
||||
)
|
||||
|
||||
source_type = guess_source_type(upload.filename or "")
|
||||
created = shipping_tools.create_task({"user_id": user.id, "source_type": source_type})
|
||||
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:
|
||||
return jsonify({"error": "failed to create task"}), 500
|
||||
@@ -108,17 +305,37 @@ def workspace_create_shipping_task_from_notice():
|
||||
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)
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
if task:
|
||||
task.source_file_name = str(upload.filename or "").strip() or task.source_file_name
|
||||
task.source_file_type = str(getattr(upload, "mimetype", "") or "").strip() 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": {"filename": upload.filename or "", **meta},
|
||||
"parse_status": "deferred",
|
||||
"orchestrator_started": orchestrator_started,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@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
|
||||
@@ -130,6 +347,7 @@ def workspace_shipping_task_detail(task_no: str):
|
||||
|
||||
@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
|
||||
@@ -139,9 +357,29 @@ def workspace_shipping_task_chat_actions(task_no: str):
|
||||
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, 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 = {"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):
|
||||
"""Hxops chat UI: upload inventory Excel with user auth (not Tool Key)."""
|
||||
"""用户态上传库存 Excel,并在服务端完成解析。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
@@ -157,6 +395,7 @@ def workspace_upload_shipping_inventory(task_no: str):
|
||||
|
||||
@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
|
||||
@@ -179,7 +418,7 @@ def workspace_apply_inventory_mapping(task_no: str):
|
||||
|
||||
@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)."""
|
||||
"""以用户态提交人工决策,绕过 Dify Tool 路由直接驱动状态机。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
@@ -201,9 +440,110 @@ def workspace_submit_shipping_decision(task_no: str):
|
||||
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, 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 {}
|
||||
fields = data.get("fields")
|
||||
if not isinstance(fields, dict) or not fields:
|
||||
return jsonify({"error": "fields is required"}), 400
|
||||
|
||||
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, 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 {}
|
||||
try:
|
||||
line_index = int(data.get("line_index"))
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({"error": "line_index is required"}), 400
|
||||
patch = data.get("patch")
|
||||
if not isinstance(patch, dict) or not patch:
|
||||
return jsonify({"error": "patch is required"}), 400
|
||||
|
||||
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, 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 {}
|
||||
line = data.get("line")
|
||||
if not isinstance(line, dict) or not line:
|
||||
return jsonify({"error": "line is required"}), 400
|
||||
|
||||
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, 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 {}
|
||||
try:
|
||||
line_index = int(data.get("line_index"))
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({"error": "line_index is required"}), 400
|
||||
|
||||
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):
|
||||
"""Hxops chat fallback: same as Dify auto_progress tool."""
|
||||
"""用户态触发 auto_progress,作为聊天前端的兜底自动推进入口。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
@@ -230,6 +570,7 @@ def workspace_auto_progress_shipping_task(task_no: str):
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/match-inventory", methods=["POST"])
|
||||
def workspace_match_shipping_inventory(task_no: str):
|
||||
"""执行库存匹配,并在生成 Excel 后补充前端可直接下载的链接。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
@@ -268,7 +609,7 @@ def workspace_match_shipping_inventory(task_no: str):
|
||||
|
||||
@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)."""
|
||||
"""标记货代系统已人工上传完成,无需再等待 RPA 回执。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
@@ -285,6 +626,7 @@ def workspace_mark_manual_uploaded(task_no: str):
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/generate-excel", methods=["POST"])
|
||||
def workspace_generate_shipping_excel(task_no: str):
|
||||
"""为指定任务生成出货 Excel,并补充工作台下载链接。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
@@ -306,18 +648,35 @@ def workspace_generate_shipping_excel(task_no: str):
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/export", methods=["GET"])
|
||||
def workspace_shipping_task_export(task_no: str):
|
||||
"""下载当前用户可访问任务的出货 Excel。"""
|
||||
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
|
||||
err_msg = task_export_error_message(task)
|
||||
if err_msg:
|
||||
return jsonify({"error": err_msg}), 404
|
||||
resolved = resolve_task_export_download(task)
|
||||
assert resolved is not None
|
||||
path, download_name = resolved
|
||||
return send_file(
|
||||
path,
|
||||
as_attachment=True,
|
||||
download_name=task.export_file_name or path.name,
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
download_name=download_name,
|
||||
mimetype=EXPORT_MIME_TYPE,
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>/retry-pending", methods=["POST"])
|
||||
def workspace_retry_shipping_batch_pending(batch_no: str):
|
||||
"""重试批次中仍可自动推进的任务,跳过终态和人工阻断任务。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks
|
||||
|
||||
return jsonify(retry_batch_pending_tasks(batch.batch_no))
|
||||
@@ -0,0 +1 @@
|
||||
"""FAQ CLI 包。"""
|
||||
@@ -0,0 +1,44 @@
|
||||
"""
|
||||
backend/app/cli/faq_commands.py
|
||||
|
||||
用途:FAQ 相关 Flask CLI 命令注册。
|
||||
依赖:HotFaqAggregator、Flask click。
|
||||
逻辑:create_app 时 init_app 注册 faq-aggregate-hot 命令。
|
||||
"""
|
||||
import click
|
||||
from flask.cli import with_appcontext
|
||||
|
||||
from app.services.hot_faq_aggregator import HotFaqAggregator
|
||||
|
||||
|
||||
@click.command('faq-aggregate-hot')
|
||||
@click.option('--agent-id', type=int, default=None, help='仅聚合指定 Agent')
|
||||
@click.option('--dry-run', is_flag=True, help='只统计不写 PostgreSQL')
|
||||
@with_appcontext
|
||||
def faq_aggregate_hot(agent_id: int | None, dry_run: bool):
|
||||
"""
|
||||
离线聚合 ChatLog 热点 FAQ 候选并写入 faq_hot_candidates 表。
|
||||
核心逻辑:委托 HotFaqAggregator.aggregate_hot_faq_candidates。
|
||||
"""
|
||||
result = HotFaqAggregator.aggregate_hot_faq_candidates(agent_id=agent_id, dry_run=dry_run)
|
||||
if not result.get('enabled'):
|
||||
click.echo(result.get('message', 'FAQ hot aggregation disabled'))
|
||||
return
|
||||
|
||||
click.echo(
|
||||
f"scanned={result['scanned_logs']} groups={result['group_count']} "
|
||||
f"promoted={result['promoted_count']} skipped={result['skipped_count']} dry_run={dry_run}"
|
||||
)
|
||||
for item in result.get('candidates', [])[:20]:
|
||||
click.echo(
|
||||
f" [{item.get('agent_name')}] {item.get('canonical_query')} "
|
||||
f"asks={item.get('ask_count_7d')} users={item.get('user_count_7d')} "
|
||||
f"dominance={item.get('answer_dominance')}"
|
||||
)
|
||||
if len(result.get('candidates', [])) > 20:
|
||||
click.echo(f" ... and {len(result['candidates']) - 20} more")
|
||||
|
||||
|
||||
def init_app(app):
|
||||
"""向 Flask app 注册 FAQ CLI 命令。"""
|
||||
app.cli.add_command(faq_aggregate_hot)
|
||||
+56
-3
@@ -90,6 +90,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,14 +109,34 @@ class Config:
|
||||
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
|
||||
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
|
||||
|
||||
# HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 共用;无尾斜杠)
|
||||
HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOLS_API_BASE')
|
||||
|
||||
# 货代发货通知 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')
|
||||
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 = (
|
||||
@@ -184,7 +206,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 +242,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 +260,29 @@ 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_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')
|
||||
@@ -259,6 +309,8 @@ 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
|
||||
|
||||
|
||||
config = {
|
||||
@@ -270,3 +322,4 @@ config = {
|
||||
'production': ProductionConfig,
|
||||
'default': DevelopmentConfig,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
backend/app/core/__init__.py
|
||||
|
||||
用途:横切能力包入口(errors、response、auth、config、db)。
|
||||
逻辑:Wave 1 逐步将 app 根目录模块迁入 core/ 子包;过渡期旧路径 re-export。
|
||||
"""
|
||||
@@ -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
|
||||
@@ -0,0 +1,9 @@
|
||||
"""
|
||||
backend/app/core/auth/jwt.py
|
||||
|
||||
用途:Casdoor JWT 校验与当前用户解析(Wave 1 自 app/auth_jwt.py 迁入)。
|
||||
逻辑:api 路由与 decorators 调用 get_current_user()。
|
||||
"""
|
||||
from app.auth_jwt import get_current_user # noqa: F401
|
||||
|
||||
__all__ = ['get_current_user']
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
backend/app/core/config/__init__.py
|
||||
|
||||
用途:应用配置包入口(settings、env_persistence)。
|
||||
逻辑:create_app 加载 Config;before_request 刷新 DB 持久化配置。
|
||||
"""
|
||||
@@ -0,0 +1,9 @@
|
||||
"""
|
||||
backend/app/core/config/env_persistence.py
|
||||
|
||||
用途:DB 持久化运行时配置(Wave 1 自 app/env_persistence.py 迁入)。
|
||||
逻辑:before_request 调用 apply_env_settings 刷新 app.config。
|
||||
"""
|
||||
from app.env_persistence import apply_env_settings # noqa: F401
|
||||
|
||||
__all__ = ['apply_env_settings']
|
||||
@@ -0,0 +1,9 @@
|
||||
"""
|
||||
backend/app/core/config/settings.py
|
||||
|
||||
用途:Config 类与环境映射(Wave 1 自 app/config.py 迁入)。
|
||||
逻辑:create_app(config_name) 通过 config[config_name] 加载。
|
||||
"""
|
||||
from app.config import ACTIVE_ENV_NAME, config # noqa: F401
|
||||
|
||||
__all__ = ['config', 'ACTIVE_ENV_NAME']
|
||||
@@ -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,9 @@
|
||||
"""
|
||||
backend/app/core/decorators.py
|
||||
|
||||
用途:路由权限装饰器(Wave 1 自 app/decorators.py 迁入)。
|
||||
逻辑:api 层路由使用 @require_admin、@require_agent_permission。
|
||||
"""
|
||||
from app.decorators import require_admin, require_agent_permission # noqa: F401
|
||||
|
||||
__all__ = ['require_admin', 'require_agent_permission']
|
||||
@@ -0,0 +1,26 @@
|
||||
"""
|
||||
backend/app/core/errors.py
|
||||
|
||||
用途:统一业务异常类型(Wave 1 自 app/errors.py 迁入)。
|
||||
依赖:无 Flask 依赖。
|
||||
逻辑:API 全局 handler 识别 AppError;业务层 raise 子类替代 jsonify(error)。
|
||||
"""
|
||||
from app.errors import ( # noqa: F401 — Wave 1: 实现迁入本文件后删除 app/errors.py shim
|
||||
AppError,
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'AppError',
|
||||
'ValidationError',
|
||||
'UnauthorizedError',
|
||||
'ForbiddenError',
|
||||
'NotFoundError',
|
||||
'ConflictError',
|
||||
'ServiceUnavailableError',
|
||||
]
|
||||
@@ -0,0 +1,9 @@
|
||||
"""
|
||||
backend/app/core/response.py
|
||||
|
||||
用途:统一 API 响应工具(Wave 1 自 app/response_utils.py 迁入)。
|
||||
逻辑:error_payload 供全局异常 handler 使用;ok() 供成功 envelope(可选)。
|
||||
"""
|
||||
from app.response_utils import error_payload, ok, utc_iso_now # noqa: F401
|
||||
|
||||
__all__ = ['error_payload', 'ok', 'utc_iso_now']
|
||||
@@ -42,6 +42,7 @@ WECOM_BOOL_KEYS = {
|
||||
'WECOM_AUTO_CREATE_USER',
|
||||
'WECOM_MOBILE_NORMALIZE',
|
||||
'WECOM_NOTIFY_ENABLED',
|
||||
'WECOM_FEEDBACK_NOTIFY_ENABLED',
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
"""
|
||||
backend/app/extensions.py
|
||||
|
||||
用途:Flask 扩展实例(db、migrate)集中定义;Wave 1 从 __init__.py 迁入并接线。
|
||||
依赖:flask_sqlalchemy、flask_migrate。
|
||||
逻辑:create_app 调用 db.init_app(app);models 与各 service 从本模块 import db。
|
||||
"""
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
@@ -0,0 +1,11 @@
|
||||
"""
|
||||
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
|
||||
|
||||
__all__ = ['JobType', 'JobStatus', 'enqueue']
|
||||
@@ -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_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,24 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/kb_clean.py
|
||||
|
||||
用途:KB 文档清洗任务 handler。
|
||||
逻辑:Wave 2 包装 knowledge_cleaning.queue_service.process_next_clean_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: 含 document_id 等字段。
|
||||
"""
|
||||
ctx.logger.info('kb_clean handler skeleton invoked payload=%s', payload)
|
||||
# Wave 2: from app.services.knowledge_cleaning.queue_service import process_job
|
||||
raise NotImplementedError('kb_clean handler pending Wave 2')
|
||||
@@ -0,0 +1,18 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/kb_dify_sync.py
|
||||
|
||||
用途:KB 文档同步至 Dify 任务 handler。
|
||||
逻辑:Wave 2 包装 knowledge_cleaning.dify_sync_service。
|
||||
"""
|
||||
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。"""
|
||||
ctx.logger.info('kb_dify_sync handler skeleton invoked payload=%s', payload)
|
||||
raise NotImplementedError('kb_dify_sync handler pending Wave 2')
|
||||
@@ -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,19 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/shipping_notice_run.py
|
||||
|
||||
用途:货代发货单票后台任务 handler。
|
||||
依赖:jobs.context、jobs.registry、shipping_notice.queue_service。
|
||||
逻辑:统一由 worker 消费 `shipping_notice_run` 队列任务,再委托 shipping_notice.queue_service 执行单票。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.services.shipping_notice.queue_service import run_shipping_notice_job
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_NOTICE_RUN)
|
||||
def run_shipping_notice(ctx: JobContext, payload: dict) -> None:
|
||||
"""消费单票发货后台任务。"""
|
||||
run_shipping_notice_job(payload, logger=ctx.logger)
|
||||
@@ -0,0 +1,18 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/wecom_directory_sync.py
|
||||
|
||||
用途:企微通讯录同步 handler。
|
||||
逻辑:Wave 4 包装 wecom_directory_sync 服务。
|
||||
"""
|
||||
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.WECOM_DIRECTORY_SYNC)
|
||||
def run_wecom_directory_sync(ctx: JobContext, payload: dict) -> None:
|
||||
"""同步企微通讯录到本地用户/部门。"""
|
||||
ctx.logger.info('wecom_directory_sync handler skeleton invoked payload=%s', payload)
|
||||
raise NotImplementedError('wecom_directory_sync handler pending Wave 4')
|
||||
@@ -0,0 +1,34 @@
|
||||
"""
|
||||
backend/app/jobs/queue.py
|
||||
|
||||
用途:任务入队 API。
|
||||
逻辑:API / services 调用 enqueue;Wave 2 写入 Job 表并 adapter KbJob。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.jobs.types import JobType
|
||||
|
||||
|
||||
def enqueue(
|
||||
job_type: JobType,
|
||||
payload: dict[str, Any],
|
||||
*,
|
||||
correlation_id: str | None = None,
|
||||
scheduled_at: Any = None,
|
||||
) -> int:
|
||||
"""
|
||||
将任务写入队列并返回 job id。
|
||||
核心逻辑:Wave 2 实现 store.create + KbJob adapter。
|
||||
Args:
|
||||
job_type: 任务类型。
|
||||
payload: 任务参数 JSON。
|
||||
correlation_id: 关联业务 id(如 kb_document_id)。
|
||||
scheduled_at: 延迟执行时间(可选)。
|
||||
Returns:
|
||||
Job 主键。
|
||||
Raises:
|
||||
NotImplementedError: Wave 0 占位。
|
||||
"""
|
||||
raise NotImplementedError('jobs.enqueue is not wired until Wave 2')
|
||||
@@ -0,0 +1,37 @@
|
||||
"""
|
||||
backend/app/jobs/registry.py
|
||||
|
||||
用途:JobType → Handler 注册表。
|
||||
逻辑:handlers 模块 import 时 @register_handler 装饰;runner 按 type 分发。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
from app.jobs.types import JobType
|
||||
|
||||
HandlerFn = Callable[[Any, dict], None]
|
||||
|
||||
_REGISTRY: dict[JobType, HandlerFn] = {}
|
||||
|
||||
|
||||
def register_handler(job_type: JobType) -> Callable[[HandlerFn], HandlerFn]:
|
||||
"""
|
||||
注册某 JobType 的处理函数。
|
||||
Args:
|
||||
job_type: 任务类型枚举。
|
||||
Returns:
|
||||
装饰器。
|
||||
"""
|
||||
|
||||
def decorator(fn: HandlerFn) -> HandlerFn:
|
||||
_REGISTRY[job_type] = fn
|
||||
return fn
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
def get_handler(job_type: JobType) -> HandlerFn | None:
|
||||
"""按类型获取 handler;未注册返回 None。"""
|
||||
return _REGISTRY.get(job_type)
|
||||
@@ -0,0 +1,38 @@
|
||||
"""
|
||||
backend/app/jobs/runner.py
|
||||
|
||||
用途:Worker 主循环 poll → dispatch → ack/fail。
|
||||
逻辑:worker.py 调用 run_forever(ctx);Wave 2 接入 store 与 registry。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.registry import get_handler
|
||||
from app.jobs import store
|
||||
|
||||
|
||||
def run_forever(ctx: JobContext, *, poll_interval_seconds: float = 2.0) -> None:
|
||||
"""
|
||||
持续轮询并执行任务。
|
||||
核心逻辑:claim_next → get_handler → handler(ctx, payload) → 更新状态。
|
||||
Args:
|
||||
ctx: Worker 上下文。
|
||||
poll_interval_seconds: 无任务时的休眠秒数。
|
||||
"""
|
||||
ctx.logger.info('Job runner started (skeleton mode — Wave 2 will enable claim loop)')
|
||||
while True:
|
||||
try:
|
||||
job = store.claim_next()
|
||||
except NotImplementedError:
|
||||
time.sleep(poll_interval_seconds)
|
||||
continue
|
||||
if not job:
|
||||
time.sleep(poll_interval_seconds)
|
||||
continue
|
||||
handler = get_handler(job['job_type'])
|
||||
if not handler:
|
||||
ctx.logger.error('No handler for job_type=%s', job.get('job_type'))
|
||||
continue
|
||||
handler(ctx, job.get('payload') or {})
|
||||
@@ -0,0 +1,20 @@
|
||||
"""
|
||||
backend/app/jobs/store.py
|
||||
|
||||
用途:Job 表 CRUD(claim、update status)。
|
||||
逻辑:runner 通过 claim_next 获取待执行任务;Wave 2 落地 SQLAlchemy 模型。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def claim_next() -> dict[str, Any] | None:
|
||||
"""
|
||||
认领下一条待执行 Job(SELECT FOR UPDATE SKIP LOCKED)。
|
||||
Returns:
|
||||
job 字典或 None。
|
||||
Raises:
|
||||
NotImplementedError: Wave 0 占位。
|
||||
"""
|
||||
raise NotImplementedError('jobs.store.claim_next is not wired until Wave 2')
|
||||
@@ -0,0 +1,30 @@
|
||||
"""
|
||||
backend/app/jobs/types.py
|
||||
|
||||
用途:Job 类型与状态枚举。
|
||||
逻辑:handlers 与 queue 通过 JobType 注册;store 持久化 status 字符串。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import StrEnum
|
||||
|
||||
|
||||
class JobType(StrEnum):
|
||||
"""后台任务类型。"""
|
||||
|
||||
KB_CLEAN = 'kb_clean'
|
||||
KB_DIFY_SYNC = 'kb_dify_sync'
|
||||
SHIPPING_NOTICE_RUN = 'shipping_notice_run'
|
||||
SCHEDULE_RUN = 'schedule_run'
|
||||
FILE_CHECK_RUN = 'file_check_run'
|
||||
WECOM_DIRECTORY_SYNC = 'wecom_directory_sync'
|
||||
|
||||
|
||||
class JobStatus(StrEnum):
|
||||
"""Job 生命周期状态。"""
|
||||
|
||||
PENDING = 'pending'
|
||||
RUNNING = 'running'
|
||||
SUCCEEDED = 'succeeded'
|
||||
FAILED = 'failed'
|
||||
DEAD = 'dead'
|
||||
+120
-1
@@ -214,6 +214,7 @@ class ChatLog(Base):
|
||||
latency: Mapped[int] = mapped_column(default=0)
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100))
|
||||
session_id: Mapped[Optional[str]] = mapped_column(String(100), index=True, nullable=True)
|
||||
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_runs.id'), index=True, nullable=True)
|
||||
message_type: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
|
||||
payload: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
tokens_used: Mapped[int] = mapped_column(default=0)
|
||||
@@ -275,7 +276,7 @@ class PermissionRequest(Base):
|
||||
class QuickQuestion(Base):
|
||||
"""
|
||||
常用问题表
|
||||
用途:存储用户自定义的常用问题
|
||||
用途:存储全局/用户常用问题;全局条目(user_id 为空)可配置标准答案并启用 FAQ 缓存命中。
|
||||
"""
|
||||
__tablename__ = 'quick_questions'
|
||||
|
||||
@@ -284,8 +285,54 @@ class QuickQuestion(Base):
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
|
||||
title: Mapped[str] = mapped_column(String(100))
|
||||
question: Mapped[str] = mapped_column(Text)
|
||||
answer: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
aliases: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
cache_enabled: Mapped[bool] = mapped_column(default=False)
|
||||
is_enabled: Mapped[bool] = mapped_column(default=True)
|
||||
hit_count: Mapped[int] = mapped_column(default=0)
|
||||
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
source_kb_document_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
stale_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
stale_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
stale_kb_document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id'), nullable=True)
|
||||
sort_order: Mapped[int] = mapped_column(default=0)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
|
||||
class FaqHotCandidate(Base):
|
||||
"""
|
||||
热点 FAQ 候选表
|
||||
用途:离线聚合 ChatLog 后的待审核热点问句与推荐答案(PostgreSQL 存储,不含在线命中)。
|
||||
"""
|
||||
__tablename__ = 'faq_hot_candidates'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('agent_id', 'q_norm', name='uq_faq_hot_candidates_agent_qnorm'),
|
||||
Index('ix_faq_hot_candidates_status_expires', 'status', 'expires_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), index=True)
|
||||
q_norm: Mapped[str] = mapped_column(String(255))
|
||||
canonical_query: Mapped[str] = mapped_column(Text)
|
||||
answer: Mapped[str] = mapped_column(Text)
|
||||
source_chat_log_id: Mapped[Optional[int]] = mapped_column(ForeignKey('chat_logs.id'), nullable=True)
|
||||
ask_count_7d: Mapped[int] = mapped_column(default=0)
|
||||
user_count_7d: Mapped[int] = mapped_column(default=0)
|
||||
avg_tokens: Mapped[int] = mapped_column(default=0)
|
||||
avg_latency_ms: Mapped[int] = mapped_column(default=0)
|
||||
answer_dominance: Mapped[float] = mapped_column(default=0.0)
|
||||
sample_queries: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
last_asked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(20), default='candidate') # candidate | promoted | dismissed
|
||||
promoted_quick_question_id: Mapped[Optional[int]] = mapped_column(ForeignKey('quick_questions.id'), nullable=True)
|
||||
deny_until: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
|
||||
class Announcement(Base):
|
||||
"""
|
||||
@@ -581,10 +628,13 @@ class ScheduleTask(Base):
|
||||
schedule_type: Mapped[str] = mapped_column(String(32), default='platform_app')
|
||||
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True)
|
||||
cron_expr: Mapped[str] = mapped_column(String(64))
|
||||
schedule_timezone: Mapped[str] = mapped_column(String(64), default='Asia/Shanghai', server_default=text("'Asia/Shanghai'"))
|
||||
wait_seconds: Mapped[int] = mapped_column(Integer, default=0)
|
||||
dify_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True, index=True)
|
||||
platform_api_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
data_source_type: Mapped[str] = mapped_column(String(32), default='database')
|
||||
kb_sync_enabled: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
|
||||
kb_group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'), nullable=True, index=True)
|
||||
notify_user_ids_json: Mapped[Optional[list]] = mapped_column(JSON, default=[])
|
||||
notify_enabled: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, default=True, index=True)
|
||||
@@ -597,6 +647,7 @@ class ScheduleTask(Base):
|
||||
|
||||
owner: Mapped[Optional["User"]] = relationship("User", foreign_keys=[owner_user_id])
|
||||
dify_agent: Mapped[Optional["Agent"]] = relationship("Agent", foreign_keys=[dify_agent_id])
|
||||
kb_group: Mapped[Optional["KbGroup"]] = relationship("KbGroup", foreign_keys=[kb_group_id])
|
||||
config: Mapped[Optional["ScheduleTaskConfig"]] = relationship("ScheduleTaskConfig", back_populates="task", uselist=False, cascade="all, delete-orphan")
|
||||
|
||||
|
||||
@@ -672,12 +723,55 @@ class ScheduleRun(Base):
|
||||
excel_file_data: Mapped[Optional[bytes]] = mapped_column(LargeBinary)
|
||||
excel_file_name: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
excel_file_size: Mapped[Optional[int]] = mapped_column(Integer)
|
||||
kb_sync_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
kb_group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'), nullable=True)
|
||||
kb_document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id'), nullable=True)
|
||||
kb_document_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_document_versions.id'), nullable=True)
|
||||
kb_sync_job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_jobs.id'), nullable=True)
|
||||
kb_sync_error: Mapped[Optional[str]] = mapped_column(Text)
|
||||
wecom_notified: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
|
||||
wecom_notified_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
wecom_notify_error: Mapped[Optional[str]] = mapped_column(Text)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", foreign_keys=[schedule_task_id])
|
||||
kb_group: Mapped[Optional["KbGroup"]] = relationship("KbGroup", foreign_keys=[kb_group_id])
|
||||
kb_document: Mapped[Optional["KbDocument"]] = relationship("KbDocument", foreign_keys=[kb_document_id])
|
||||
kb_document_version: Mapped[Optional["KbDocumentVersion"]] = relationship("KbDocumentVersion", foreign_keys=[kb_document_version_id])
|
||||
kb_sync_job: Mapped[Optional["KbJob"]] = relationship("KbJob", foreign_keys=[kb_sync_job_id])
|
||||
|
||||
|
||||
class ShippingBatch(Base):
|
||||
"""货代发货通知批次(一次多文件上传的聚合容器)"""
|
||||
__tablename__ = 'shipping_batches'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_batches_user_created', 'user_id', 'created_at'),
|
||||
Index('ix_shipping_batches_conversation', 'conversation_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
batch_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
current_focus_task_no: Mapped[Optional[str]] = mapped_column(
|
||||
String(64),
|
||||
ForeignKey(
|
||||
'shipping_tasks.task_no',
|
||||
name='fk_shipping_batches_current_focus_task_no_shipping_tasks',
|
||||
use_alter=True,
|
||||
),
|
||||
nullable=True,
|
||||
)
|
||||
file_count: Mapped[int] = mapped_column(Integer, default=1)
|
||||
process_summary_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
tasks: Mapped[List["ShippingTask"]] = relationship(
|
||||
"ShippingTask",
|
||||
back_populates="batch",
|
||||
foreign_keys="ShippingTask.batch_id",
|
||||
)
|
||||
|
||||
|
||||
class ShippingTask(Base):
|
||||
@@ -686,13 +780,20 @@ class ShippingTask(Base):
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_tasks_user_status', 'user_id', 'process_status'),
|
||||
Index('ix_shipping_tasks_conversation', 'conversation_id'),
|
||||
Index('ix_shipping_tasks_batch_step', 'batch_id', 'current_step'),
|
||||
Index('ix_shipping_tasks_upload_status', 'upload_status'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), index=True, nullable=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
source_type: Mapped[str] = mapped_column(String(32), default='manual')
|
||||
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
source_file_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
batch_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
batch_total: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
|
||||
raw_content: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
customer_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
@@ -704,6 +805,7 @@ class ShippingTask(Base):
|
||||
parse_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
||||
|
||||
process_status: Mapped[str] = mapped_column(String(32), default='created', index=True)
|
||||
current_step: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
review_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
match_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
shortage_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
@@ -713,13 +815,29 @@ class ShippingTask(Base):
|
||||
|
||||
export_file_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
export_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
export_version: Mapped[int] = mapped_column(Integer, default=1)
|
||||
freight_ref_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
upload_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
upload_mode: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
upload_attempt: Mapped[int] = mapped_column(Integer, default=0)
|
||||
idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
upload_started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
upload_finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
upload_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
upload_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
upload_receipt_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
step_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
pending_human_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
batch: Mapped[Optional["ShippingBatch"]] = relationship(
|
||||
"ShippingBatch",
|
||||
back_populates="tasks",
|
||||
foreign_keys=[batch_id],
|
||||
)
|
||||
events: Mapped[List["ShippingTaskEvent"]] = relationship(
|
||||
"ShippingTaskEvent",
|
||||
back_populates="task",
|
||||
@@ -741,6 +859,7 @@ class ShippingTaskEvent(Base):
|
||||
|
||||
|
||||
class ShippingInventoryMapping(Base):
|
||||
"""客户库存 Excel 表头 → 标准字段的列映射缓存(按 customer_code + header_hash 去重)。"""
|
||||
__tablename__ = 'shipping_inventory_mappings'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('customer_code', 'header_hash', name='uq_shipping_inventory_mappings_customer_header'),
|
||||
|
||||
@@ -19,6 +19,15 @@ def utc_iso_now() -> str:
|
||||
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 字符串,便于前端正确转本地时区。"""
|
||||
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):
|
||||
payload: dict[str, Any] = {
|
||||
"success": True,
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
backend/app/schemas/__init__.py
|
||||
|
||||
用途:请求/响应 DTO 包(dataclass 或 Pydantic,非 FastAPI 专用)。
|
||||
逻辑:api 层解析入参、校验后传入 services;Wave 3 随 admin/user/kb 拆分落地。
|
||||
"""
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/app/schemas/admin/__init__.py
|
||||
|
||||
用途:管理后台 DTO 包入口。
|
||||
"""
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/app/schemas/admin/agents.py
|
||||
|
||||
用途:Agent 管理 API DTO。
|
||||
"""
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/app/schemas/admin/settings.py
|
||||
|
||||
用途:系统设置 API DTO。
|
||||
"""
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
backend/app/schemas/admin/users.py
|
||||
|
||||
用途:用户管理 API DTO。
|
||||
逻辑:Wave 3 admin/users 路由使用。
|
||||
"""
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
backend/app/schemas/chat.py
|
||||
|
||||
用途:聊天域 API 请求/响应 DTO。
|
||||
逻辑:Wave 3 从 api/chat/_legacy 抽取 completions、sessions 参数模型。
|
||||
"""
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
backend/app/schemas/kb.py
|
||||
|
||||
用途:知识库域 API 请求/响应 DTO。
|
||||
逻辑:Wave 3 从 api/kb 拆分 upload、sync 参数模型。
|
||||
"""
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/app/schemas/user/__init__.py
|
||||
|
||||
用途:当前用户域 API DTO(profile、homepage、faq)。
|
||||
"""
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
backend/app/services/admin/__init__.py
|
||||
|
||||
用途:管理后台业务服务包。
|
||||
逻辑:Wave 3 从 api/admin/_legacy 抽取 users/agents/departments/settings 等。
|
||||
"""
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/app/services/admin/agent_service.py
|
||||
|
||||
用途:Agent CRUD、权限、guide 配置。
|
||||
"""
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/app/services/admin/dashboard_service.py
|
||||
|
||||
用途:管理后台仪表盘统计聚合。
|
||||
"""
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/app/services/admin/department_service.py
|
||||
|
||||
用途:部门 CRUD。
|
||||
"""
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/app/services/admin/permission_service.py
|
||||
|
||||
用途:权限申请、批量授权业务逻辑。
|
||||
"""
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/app/services/admin/settings_service.py
|
||||
|
||||
用途:AppSetting、运行时配置管理业务逻辑。
|
||||
"""
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/app/services/admin/user_service.py
|
||||
|
||||
用途:管理端用户 CRUD、权限分配。
|
||||
"""
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
backend/app/services/auth/__init__.py
|
||||
|
||||
用途:认证域业务(Casdoor OIDC、企微 OAuth)。
|
||||
逻辑:Wave 3 从 api/user/_legacy auth 相关路由抽取。
|
||||
"""
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/app/services/auth/casdoor_service.py
|
||||
|
||||
用途:Casdoor OIDC 登录、token 交换、用户同步业务逻辑。
|
||||
"""
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/app/services/auth/wecom_auth_service.py
|
||||
|
||||
用途:企业微信 OAuth、绑定、解绑业务逻辑。
|
||||
"""
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
backend/app/services/chat/__init__.py
|
||||
|
||||
用途:聊天域业务服务包。
|
||||
逻辑:Wave 3 从 api/chat/_legacy 与 chat.py 意图路由抽取。
|
||||
"""
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/app/services/chat/log_service.py
|
||||
|
||||
用途:聊天历史、反馈业务逻辑。
|
||||
"""
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
backend/app/services/chat/perf.py
|
||||
|
||||
用途:聊天性能埋点(Wave 3 自 services/chat_perf.py 迁入)。
|
||||
"""
|
||||
from app.services.chat_perf import * # noqa: F403
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
backend/app/services/chat/preview_service.py
|
||||
|
||||
用途:PLM/Excel 预览与文件转换(从 api/chat 抽出)。
|
||||
逻辑:Wave 3 将 subprocess/openpyxl 逻辑迁入本模块。
|
||||
"""
|
||||
@@ -0,0 +1,27 @@
|
||||
"""
|
||||
backend/app/services/chat/router.py
|
||||
|
||||
用途:Chat Intent Router,按意图分流至 PLM/HR/Text2SQL/Dify。
|
||||
依赖:integrations/* stream_chat 实现。
|
||||
逻辑:api/chat/completions 调用本模块 select_stream_generator。
|
||||
设计参考:docs/tec.md §4.1 Chat Intent Router。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Iterator
|
||||
|
||||
|
||||
def select_stream_generator(*, user: Any, agent: Any, query: str, **kwargs: Any) -> Iterator[str]:
|
||||
"""
|
||||
根据 agent 配置与用户问题选择流式 generator。
|
||||
核心逻辑:Wave 3 从 api/chat.py /completions 分支迁入。
|
||||
Args:
|
||||
user: 当前 User 模型实例。
|
||||
agent: 当前 Agent 模型实例。
|
||||
query: 用户问题文本。
|
||||
Returns:
|
||||
SSE 事件字符串迭代器。
|
||||
Raises:
|
||||
NotImplementedError: Wave 0 占位。
|
||||
"""
|
||||
raise NotImplementedError('ChatIntentRouter pending Wave 3 migration from api/chat.py')
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
backend/app/services/chat/session_service.py
|
||||
|
||||
用途:聊天会话 CRUD 业务逻辑。
|
||||
逻辑:Wave 3 从 api/chat/_legacy 抽取 sessions 相关路由逻辑。
|
||||
"""
|
||||
@@ -0,0 +1,128 @@
|
||||
"""
|
||||
backend/app/services/chat_perf.py
|
||||
文件用途:对话流式链路各节点耗时采集与结构化日志输出。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
|
||||
def chat_perf_enabled() -> bool:
|
||||
return str(os.getenv("CHAT_PERF_LOG", "0")).strip().lower() in ("1", "true", "yes", "on")
|
||||
|
||||
|
||||
class ChatPerfTracker:
|
||||
"""Collect Dify Chatflow / Chat SSE node timings for one request."""
|
||||
|
||||
def __init__(self, *, request_id: str | None, agent_id: int | None = None) -> None:
|
||||
self.request_id = str(request_id or "").strip() or None
|
||||
self.agent_id = agent_id
|
||||
self.started_at = time.perf_counter()
|
||||
self.workflow_run_id: str | None = None
|
||||
self.first_event_at: float | None = None
|
||||
self.first_token_at: float | None = None
|
||||
self.nodes: list[dict[str, Any]] = []
|
||||
self.workflow_elapsed_ms: int | None = None
|
||||
self.workflow_status: str | None = None
|
||||
self.total_tokens: int | None = None
|
||||
|
||||
def _since_start_ms(self, at: float | None = None) -> int:
|
||||
return int(((at or time.perf_counter()) - self.started_at) * 1000)
|
||||
|
||||
def on_event(self, event: str | None, data: dict[str, Any]) -> None:
|
||||
if not chat_perf_enabled():
|
||||
return
|
||||
now = time.perf_counter()
|
||||
if self.first_event_at is None:
|
||||
self.first_event_at = now
|
||||
|
||||
event_name = str(event or "").strip()
|
||||
if event_name == "workflow_started":
|
||||
payload = data.get("data") if isinstance(data.get("data"), dict) else {}
|
||||
self.workflow_run_id = str(payload.get("workflow_run_id") or data.get("workflow_run_id") or "").strip() or None
|
||||
return
|
||||
|
||||
if event_name == "node_finished":
|
||||
payload = data.get("data") if isinstance(data.get("data"), dict) else {}
|
||||
elapsed_raw = payload.get("elapsed_time")
|
||||
try:
|
||||
elapsed_ms = int(float(elapsed_raw or 0) * 1000)
|
||||
except (TypeError, ValueError):
|
||||
elapsed_ms = 0
|
||||
self.nodes.append({
|
||||
"index": payload.get("index"),
|
||||
"title": str(payload.get("title") or payload.get("node_id") or "").strip() or "unknown",
|
||||
"node_type": str(payload.get("node_type") or "").strip() or None,
|
||||
"node_id": str(payload.get("node_id") or "").strip() or None,
|
||||
"status": str(payload.get("status") or "").strip() or None,
|
||||
"elapsed_ms": elapsed_ms,
|
||||
"at_ms": self._since_start_ms(now),
|
||||
})
|
||||
return
|
||||
|
||||
if event_name == "message" and data.get("answer"):
|
||||
if self.first_token_at is None:
|
||||
self.first_token_at = now
|
||||
return
|
||||
|
||||
if event_name in ("message_end", "workflow_finished"):
|
||||
payload = data.get("data") if isinstance(data.get("data"), dict) else {}
|
||||
metadata = data.get("metadata") if isinstance(data.get("metadata"), dict) else {}
|
||||
usage = metadata.get("usage") if isinstance(metadata.get("usage"), dict) else {}
|
||||
|
||||
elapsed_raw = payload.get("elapsed_time")
|
||||
if elapsed_raw is None:
|
||||
elapsed_raw = usage.get("latency")
|
||||
try:
|
||||
self.workflow_elapsed_ms = int(float(elapsed_raw or 0) * 1000)
|
||||
except (TypeError, ValueError):
|
||||
self.workflow_elapsed_ms = None
|
||||
|
||||
self.workflow_status = str(payload.get("status") or "").strip() or None
|
||||
try:
|
||||
self.total_tokens = int(payload.get("total_tokens") or usage.get("total_tokens") or 0) or None
|
||||
except (TypeError, ValueError):
|
||||
self.total_tokens = None
|
||||
|
||||
def build_summary(self) -> dict[str, Any]:
|
||||
total_ms = self._since_start_ms()
|
||||
return {
|
||||
"request_id": self.request_id,
|
||||
"agent_id": self.agent_id,
|
||||
"workflow_run_id": self.workflow_run_id,
|
||||
"total_ms": total_ms,
|
||||
"ttft_ms": self._since_start_ms(self.first_token_at) if self.first_token_at else None,
|
||||
"first_event_ms": self._since_start_ms(self.first_event_at) if self.first_event_at else None,
|
||||
"workflow_elapsed_ms": self.workflow_elapsed_ms,
|
||||
"workflow_status": self.workflow_status,
|
||||
"total_tokens": self.total_tokens,
|
||||
"nodes": self.nodes,
|
||||
"node_total_ms": sum(int(n.get("elapsed_ms") or 0) for n in self.nodes),
|
||||
}
|
||||
|
||||
def log_summary(self, logger: Any, *, phase: str = "stream_end") -> dict[str, Any]:
|
||||
summary = self.build_summary()
|
||||
if not chat_perf_enabled():
|
||||
return summary
|
||||
lines = [
|
||||
f"[chat-perf] {phase} request_id={summary['request_id']} agent_id={summary['agent_id']} "
|
||||
f"total_ms={summary['total_ms']} ttft_ms={summary['ttft_ms']} "
|
||||
f"workflow_elapsed_ms={summary['workflow_elapsed_ms']} nodes={len(summary['nodes'])}"
|
||||
]
|
||||
for node in summary["nodes"]:
|
||||
lines.append(
|
||||
"[chat-perf] node "
|
||||
f"request_id={summary['request_id']} "
|
||||
f"index={node.get('index')} "
|
||||
f"title={node.get('title')} "
|
||||
f"type={node.get('node_type')} "
|
||||
f"elapsed_ms={node.get('elapsed_ms')} "
|
||||
f"at_ms={node.get('at_ms')} "
|
||||
f"status={node.get('status')}"
|
||||
)
|
||||
if logger:
|
||||
for line in lines:
|
||||
logger.info(line)
|
||||
return summary
|
||||
@@ -0,0 +1,60 @@
|
||||
"""
|
||||
backend/app/services/db_sequence.py
|
||||
文件用途:修复 PostgreSQL 主键序列与 MAX(id) 不同步导致的 UniqueViolation。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
|
||||
|
||||
def repair_pg_id_sequence(table_name: str) -> None:
|
||||
"""将 PostgreSQL 自增序列对齐到 MAX(id),修复手工导入或迁移后的主键冲突。"""
|
||||
bind = db.session.get_bind()
|
||||
if bind.dialect.name != "postgresql":
|
||||
return
|
||||
qualified = f"public.{table_name}"
|
||||
db.session.execute(
|
||||
text(
|
||||
"SELECT setval("
|
||||
"pg_get_serial_sequence(:qualified, 'id'), "
|
||||
f"COALESCE((SELECT MAX(id) FROM {table_name}), 0), true)"
|
||||
),
|
||||
{"qualified": qualified},
|
||||
)
|
||||
|
||||
|
||||
def is_pk_sequence_conflict(exc: IntegrityError, table_name: str) -> bool:
|
||||
orig = getattr(exc, "orig", exc)
|
||||
return f"{table_name}_pkey" in str(orig)
|
||||
|
||||
|
||||
def add_and_flush_with_sequence_retry(instance, table_name: str) -> None:
|
||||
"""插入并 flush;若主键序列落后则修复后重试一次。
|
||||
|
||||
使用 SAVEPOINT 隔离单次插入失败,避免全局 rollback 把同事务中已创建的
|
||||
前置对象一并回滚。
|
||||
"""
|
||||
try:
|
||||
nested = db.session.begin_nested()
|
||||
try:
|
||||
db.session.add(instance)
|
||||
db.session.flush()
|
||||
nested.commit()
|
||||
except Exception:
|
||||
nested.rollback()
|
||||
raise
|
||||
except IntegrityError as exc:
|
||||
if not is_pk_sequence_conflict(exc, table_name):
|
||||
raise
|
||||
repair_pg_id_sequence(table_name)
|
||||
nested = db.session.begin_nested()
|
||||
try:
|
||||
db.session.add(instance)
|
||||
db.session.flush()
|
||||
nested.commit()
|
||||
except Exception:
|
||||
nested.rollback()
|
||||
raise
|
||||
+381
-58
@@ -8,6 +8,7 @@ It is responsible for:
|
||||
1) Forwarding chat requests from this system to Dify in streaming mode.
|
||||
2) Relaying Dify SSE events to the frontend.
|
||||
3) Aggregating answer text and metadata (retriever resources / attribution).
|
||||
Chatflow 模式下来源在 knowledge-retrieval 的 node_finished.outputs.result。
|
||||
4) Enriching retriever resources with original source-file download URLs via
|
||||
the integration API mapping (dataset_id + remote_document_id).
|
||||
5) Persisting chat logs to the local database.
|
||||
@@ -27,7 +28,7 @@ import os
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from threading import Lock
|
||||
from threading import Lock, Thread
|
||||
from typing import Any, List, Optional
|
||||
|
||||
import requests
|
||||
@@ -35,6 +36,7 @@ from flask import current_app
|
||||
|
||||
from app.config import Config
|
||||
from app.models import ChatLog, db
|
||||
from app.services.chat_perf import ChatPerfTracker, chat_perf_enabled
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
|
||||
|
||||
@@ -507,6 +509,7 @@ class DifyService:
|
||||
conversation_id: str = None,
|
||||
request_id: str | None = None,
|
||||
session_id: str | None = None,
|
||||
hxops_turn_id: str | None = None,
|
||||
files: list[dict[str, Any]] | None = None,
|
||||
inputs: dict[str, Any] | None = None,
|
||||
):
|
||||
@@ -561,84 +564,130 @@ class DifyService:
|
||||
)
|
||||
|
||||
start_time = time.time()
|
||||
perf = ChatPerfTracker(request_id=request_id, agent_id=getattr(agent, "id", None))
|
||||
first_token_at: float | None = None
|
||||
message_count = 0
|
||||
event_count = 0
|
||||
full_answer: List[str] = []
|
||||
retriever_resources: List[Any] = []
|
||||
attribution_parts: List[str] = []
|
||||
chat_logged = False
|
||||
chat_persist_started = False
|
||||
has_sent_answer = False
|
||||
chat_log_id_persisted: int | None = None
|
||||
run_id_persisted: int | None = None
|
||||
|
||||
def _resolve_persist_run_id() -> int | None:
|
||||
try:
|
||||
from app.services.file_check_tools.agent_resolver import is_file_check_chat_agent
|
||||
from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
|
||||
|
||||
if not is_file_check_chat_agent(agent):
|
||||
return None
|
||||
return resolve_run_id_for_chat_log(
|
||||
session_id=session_id,
|
||||
query=query,
|
||||
turn_id=hxops_turn_id,
|
||||
)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def persist_stream_chat(data: dict, event_name: str) -> None:
|
||||
nonlocal chat_logged
|
||||
if chat_logged:
|
||||
return
|
||||
result = persist_stream_chat_async(data, event_name)
|
||||
if isinstance(result, dict):
|
||||
if result.get("chat_log_id") is not None:
|
||||
data["chat_log_id"] = result["chat_log_id"]
|
||||
if result.get("run_id") is not None:
|
||||
data["run_id"] = result["run_id"]
|
||||
|
||||
if data.get('answer'):
|
||||
full_answer.append(data.get('answer', ''))
|
||||
def persist_stream_chat_async(data: dict, event_name: str) -> dict | None:
|
||||
nonlocal chat_persist_started, chat_log_id_persisted, run_id_persisted
|
||||
|
||||
if chat_persist_started and event_name == "workflow_finished" and chat_log_id_persisted:
|
||||
# [STEP 1] message_end 可能已落库但 tokens=0;workflow_finished 携带 data.total_tokens 时回写
|
||||
wf_tokens = DifyService._extract_token_usage(data)
|
||||
app_obj = current_app._get_current_object() if current_app else None
|
||||
if app_obj and wf_tokens > 0:
|
||||
with app_obj.app_context():
|
||||
DifyService._update_chat_log_tokens(chat_log_id_persisted, wf_tokens)
|
||||
run_id = _resolve_persist_run_id()
|
||||
if run_id and run_id != run_id_persisted:
|
||||
from app.services.file_check_tools.chat_log_run_binding import update_chat_log_run_id
|
||||
|
||||
if update_chat_log_run_id(chat_log_id_persisted, run_id):
|
||||
run_id_persisted = run_id
|
||||
return {"chat_log_id": chat_log_id_persisted, "run_id": run_id_persisted}
|
||||
|
||||
if chat_persist_started:
|
||||
return {"chat_log_id": chat_log_id_persisted, "run_id": run_id_persisted} if chat_log_id_persisted else None
|
||||
|
||||
chat_persist_started = True
|
||||
|
||||
app_obj = current_app._get_current_object() if current_app else None
|
||||
persist_data = json.loads(json.dumps(data, ensure_ascii=False, default=str))
|
||||
# 优先使用已 enrich 并挂到 event 上的 retriever_resources(与 SSE 下发一致)
|
||||
resources_for_persist = data.get('retriever_resources') or retriever_resources
|
||||
resources_snapshot = json.loads(json.dumps(resources_for_persist, ensure_ascii=False, default=str))
|
||||
attribution_snapshot = list(attribution_parts)
|
||||
answer_snapshot = build_final_answer_text(persist_data, event_name)
|
||||
latency_snapshot = int((time.time() - start_time) * 1000)
|
||||
message_payload = persist_data.get('message_payload')
|
||||
|
||||
if not app_obj:
|
||||
return None
|
||||
with app_obj.app_context():
|
||||
result = DifyService._persist_stream_chat_record(
|
||||
data=persist_data,
|
||||
event_name=event_name,
|
||||
request_id=request_id,
|
||||
user_id=user_id,
|
||||
agent=agent,
|
||||
session_id=session_id,
|
||||
hxops_turn_id=hxops_turn_id,
|
||||
normalized_conversation_id=normalized_conversation_id,
|
||||
query=query,
|
||||
answer_text=answer_snapshot,
|
||||
latency=latency_snapshot,
|
||||
retriever_resources=resources_snapshot,
|
||||
attribution_parts=attribution_snapshot,
|
||||
message_payload=message_payload if isinstance(message_payload, dict) else None,
|
||||
)
|
||||
if isinstance(result, dict):
|
||||
if result.get("chat_log_id"):
|
||||
chat_log_id_persisted = int(result["chat_log_id"])
|
||||
if result.get("run_id"):
|
||||
run_id_persisted = int(result["run_id"])
|
||||
return result
|
||||
|
||||
def build_final_answer_text(data: dict, event_name: str) -> str:
|
||||
answer_text = ''.join(full_answer).strip()
|
||||
if data.get('answer'):
|
||||
answer_text = (answer_text + str(data.get('answer') or '')).strip()
|
||||
|
||||
if not answer_text and event_name == 'workflow_finished':
|
||||
wf_data = data.get('data') or {}
|
||||
outputs = wf_data.get('outputs') if isinstance(wf_data, dict) else None
|
||||
if isinstance(outputs, dict):
|
||||
for key in ('answer', 'text', 'result'):
|
||||
for key in ('answer', 'final_answer', 'output', 'text', 'result', 'message'):
|
||||
value = outputs.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
answer_text = value.strip()
|
||||
break
|
||||
if not answer_text:
|
||||
for value in outputs.values():
|
||||
if isinstance(value, str) and value.strip():
|
||||
answer_text = value.strip()
|
||||
break
|
||||
return answer_text
|
||||
|
||||
if not answer_text and not str(query or '').strip():
|
||||
return
|
||||
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[source-link] persist chat request_id=%s event=%s collected retriever_resources=%s",
|
||||
request_id,
|
||||
event_name,
|
||||
len(retriever_resources),
|
||||
)
|
||||
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
|
||||
|
||||
metadata = data.get('metadata') or {}
|
||||
metadata['retriever_resources'] = retriever_resources
|
||||
data['metadata'] = metadata
|
||||
data['retriever_resources'] = retriever_resources
|
||||
|
||||
latency = int((time.time() - start_time) * 1000)
|
||||
usage = metadata.get('usage', {}) or {}
|
||||
db_write_started = time.time()
|
||||
with current_app.app_context():
|
||||
chat_log_id = DifyService._log_chat(
|
||||
user_id=user_id,
|
||||
agent_id=agent.id,
|
||||
session_id=session_id,
|
||||
conversation_id=data.get('conversation_id') or normalized_conversation_id,
|
||||
query=query,
|
||||
answer=answer_text,
|
||||
tokens=usage.get('total_tokens', 0),
|
||||
latency=latency,
|
||||
retriever_resources=retriever_resources,
|
||||
attribution_parts=attribution_parts,
|
||||
)
|
||||
if chat_log_id:
|
||||
data['chat_log_id'] = chat_log_id
|
||||
chat_logged = True
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[chat-perf] persisted request_id=%s event=%s total_ms=%s db_write_ms=%s answer_len=%s conversation_id=%s",
|
||||
request_id,
|
||||
event_name,
|
||||
latency,
|
||||
int((time.time() - db_write_started) * 1000),
|
||||
len(answer_text),
|
||||
data.get('conversation_id') or normalized_conversation_id,
|
||||
)
|
||||
|
||||
max_retries = 3
|
||||
for attempt in range(1, max_retries + 1):
|
||||
try:
|
||||
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 300)) as response:
|
||||
connect_timeout = max(1, int(getattr(Config, "DIFY_CHAT_CONNECT_TIMEOUT_SECONDS", 5) or 5))
|
||||
read_timeout = max(5, int(getattr(Config, "DIFY_CHAT_READ_TIMEOUT_SECONDS", 30) or 30))
|
||||
if attempt == 1:
|
||||
yield f"data: {json.dumps({'event': 'upstream_start', 'message': '正在连接 Dify'}, ensure_ascii=False)}\n\n"
|
||||
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(connect_timeout, read_timeout)) as response:
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[chat-stream] dify response request_id=%s status=%s reason=%s attempt=%s",
|
||||
@@ -665,6 +714,7 @@ class DifyService:
|
||||
time.sleep(attempt * 2)
|
||||
continue
|
||||
response.raise_for_status()
|
||||
yield f"data: {json.dumps({'event': 'upstream_connected', 'message': 'Dify 已连接'}, ensure_ascii=False)}\n\n"
|
||||
|
||||
for line in response.iter_lines():
|
||||
if not line:
|
||||
@@ -682,6 +732,7 @@ class DifyService:
|
||||
|
||||
event = data.get('event')
|
||||
event_count += 1
|
||||
perf.on_event(event, data)
|
||||
# Keep stream event logs behind an explicit switch to prevent
|
||||
# flooding when global logger level is DEBUG.
|
||||
if DifyService.VERBOSE_STREAM_LOG and current_app:
|
||||
@@ -694,8 +745,14 @@ class DifyService:
|
||||
data.get('conversation_id') or normalized_conversation_id,
|
||||
)
|
||||
|
||||
if event == 'message':
|
||||
if event == 'node_finished':
|
||||
# [STEP] Chatflow 知识检索结果在 node_finished.outputs.result,不在 message_end
|
||||
DifyService._collect_knowledge_retrieval_from_node(retriever_resources, data)
|
||||
|
||||
elif event == 'message':
|
||||
message_count += 1
|
||||
if data.get('answer'):
|
||||
has_sent_answer = True
|
||||
if first_token_at is None:
|
||||
first_token_at = time.time()
|
||||
if current_app:
|
||||
@@ -709,20 +766,70 @@ class DifyService:
|
||||
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
|
||||
|
||||
elif event in ('message_end', 'agent_message', 'workflow_finished'):
|
||||
if event in ('message_end', 'workflow_finished') or data.get('answer'):
|
||||
has_sent_answer = True
|
||||
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
|
||||
|
||||
if event == 'workflow_finished' and not data.get('answer'):
|
||||
final_answer = build_final_answer_text(data, event)
|
||||
if final_answer:
|
||||
data['answer'] = final_answer
|
||||
data['replace_answer'] = True
|
||||
|
||||
if event in ('message_end', 'workflow_finished'):
|
||||
DifyService._attach_retriever_resources_to_event(data, retriever_resources)
|
||||
persist_stream_chat(data, event)
|
||||
if chat_perf_enabled():
|
||||
perf_summary = perf.log_summary(current_app.logger if current_app else None)
|
||||
yield f"data: {json.dumps({'event': 'chat_perf', 'perf': perf_summary}, ensure_ascii=False)}\n\n"
|
||||
|
||||
yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
|
||||
if event in ('message_end', 'workflow_finished'):
|
||||
break
|
||||
break
|
||||
except requests.exceptions.RequestException as e:
|
||||
if current_app:
|
||||
current_app.logger.exception("[chat-stream] request exception request_id=%s attempt=%s: %s", request_id, attempt, e)
|
||||
if attempt < max_retries:
|
||||
is_timeout = isinstance(e, (requests.exceptions.ReadTimeout, requests.exceptions.ConnectTimeout))
|
||||
if isinstance(e, requests.exceptions.ReadTimeout) and has_sent_answer:
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[chat-stream] read timeout after answer request_id=%s attempt=%s; finish stream silently",
|
||||
request_id,
|
||||
attempt,
|
||||
)
|
||||
persist_stream_chat(
|
||||
{
|
||||
'event': 'message_end',
|
||||
'conversation_id': normalized_conversation_id,
|
||||
'answer': ''.join(full_answer).strip(),
|
||||
'metadata': {},
|
||||
},
|
||||
'message_end',
|
||||
)
|
||||
break
|
||||
if not is_timeout and attempt < max_retries:
|
||||
time.sleep(attempt * 2)
|
||||
continue
|
||||
error_msg = json.dumps({'event': 'error', 'message': str(e)})
|
||||
if isinstance(e, requests.exceptions.ReadTimeout):
|
||||
message = (
|
||||
f"Dify 在 {int(getattr(Config, 'DIFY_CHAT_READ_TIMEOUT_SECONDS', 30) or 30)} 秒内没有返回响应。"
|
||||
"请检查 Dify 应用地址/API Key、Chatflow 是否发布,以及 Dify 服务是否能正常执行。"
|
||||
)
|
||||
elif isinstance(e, requests.exceptions.ConnectTimeout):
|
||||
message = "连接 Dify 超时,请检查 Dify API Base URL 和网络连通性。"
|
||||
else:
|
||||
message = str(e)
|
||||
persist_stream_chat(
|
||||
{
|
||||
'event': 'error',
|
||||
'conversation_id': normalized_conversation_id,
|
||||
'answer': f"[Error: {message}]",
|
||||
'metadata': {},
|
||||
},
|
||||
'error',
|
||||
)
|
||||
error_msg = json.dumps({'event': 'error', 'message': message})
|
||||
yield f"data: {error_msg}\n\n"
|
||||
|
||||
@staticmethod
|
||||
@@ -737,6 +844,8 @@ class DifyService:
|
||||
latency,
|
||||
retriever_resources=None,
|
||||
attribution_parts=None,
|
||||
payload=None,
|
||||
run_id: int | None = None,
|
||||
) -> Optional[int]:
|
||||
"""
|
||||
把最终问答和元数据写入 ChatLog
|
||||
@@ -750,6 +859,7 @@ class DifyService:
|
||||
latency: End-to-end latency in milliseconds.
|
||||
retriever_resources: Source retrieval metadata list.
|
||||
attribution_parts: Attribution/annotation list.
|
||||
run_id: 文件检核批次 ID(按轮问答绑定,可选)。
|
||||
"""
|
||||
try:
|
||||
chat_log = ChatLog(
|
||||
@@ -763,6 +873,8 @@ class DifyService:
|
||||
latency=latency or 0,
|
||||
retriever_resources=retriever_resources or [],
|
||||
attribution_parts=attribution_parts or [],
|
||||
payload=payload if isinstance(payload, dict) else None,
|
||||
run_id=run_id if run_id and run_id > 0 else None,
|
||||
)
|
||||
db.session.add(chat_log)
|
||||
db.session.commit()
|
||||
@@ -775,6 +887,146 @@ class DifyService:
|
||||
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _extract_token_usage(data: dict) -> int:
|
||||
"""
|
||||
从 Dify SSE 事件 payload 提取 token 用量(best effort)。
|
||||
核心逻辑:Chatbot 在 metadata.usage.total_tokens;Chatflow/Workflow 在 data.total_tokens
|
||||
或 data.execution_metadata.total_tokens(与 chat_perf.ChatPerfTracker 对齐)。
|
||||
@param data - 单条 SSE 解析后的 dict
|
||||
@returns 非负整数 token 数;无法解析时返回 0
|
||||
"""
|
||||
metadata = data.get('metadata') if isinstance(data.get('metadata'), dict) else {}
|
||||
usage = metadata.get('usage') if isinstance(metadata.get('usage'), dict) else {}
|
||||
payload = data.get('data') if isinstance(data.get('data'), dict) else {}
|
||||
|
||||
candidates = [
|
||||
usage.get('total_tokens'),
|
||||
payload.get('total_tokens'),
|
||||
]
|
||||
exec_meta = payload.get('execution_metadata')
|
||||
if isinstance(exec_meta, dict):
|
||||
candidates.append(exec_meta.get('total_tokens'))
|
||||
|
||||
for raw in candidates:
|
||||
try:
|
||||
value = int(raw or 0)
|
||||
if value > 0:
|
||||
return value
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
return 0
|
||||
|
||||
@staticmethod
|
||||
def _update_chat_log_tokens(chat_log_id: int, tokens: int) -> bool:
|
||||
"""
|
||||
回写已有 ChatLog 的 tokens_used。
|
||||
核心逻辑:message_end 先落库时可能尚无 token;workflow_finished 到达后补写更大值。
|
||||
@param chat_log_id - ChatLog 主键
|
||||
@param tokens - 从 Dify 事件解析出的 token 数
|
||||
@returns 是否成功更新
|
||||
"""
|
||||
if not chat_log_id or tokens <= 0:
|
||||
return False
|
||||
try:
|
||||
log = db.session.get(ChatLog, chat_log_id)
|
||||
if not log:
|
||||
return False
|
||||
if int(log.tokens_used or 0) >= tokens:
|
||||
return False
|
||||
log.tokens_used = tokens
|
||||
db.session.commit()
|
||||
return True
|
||||
except Exception as e:
|
||||
if current_app:
|
||||
current_app.logger.error(
|
||||
'Failed to update chat log tokens chat_log_id=%s: %s',
|
||||
chat_log_id,
|
||||
e,
|
||||
)
|
||||
db.session.rollback()
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _persist_stream_chat_record(
|
||||
*,
|
||||
data: dict,
|
||||
event_name: str,
|
||||
request_id: str | None,
|
||||
user_id: int,
|
||||
agent,
|
||||
session_id: str | None,
|
||||
hxops_turn_id: str | None,
|
||||
normalized_conversation_id: str | None,
|
||||
query: str,
|
||||
answer_text: str,
|
||||
latency: int,
|
||||
retriever_resources: List[Any],
|
||||
attribution_parts: List[str],
|
||||
message_payload: dict | None = None,
|
||||
) -> dict | None:
|
||||
if not answer_text and not str(query or '').strip():
|
||||
return None
|
||||
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[source-link] persist chat request_id=%s event=%s collected retriever_resources=%s",
|
||||
request_id,
|
||||
event_name,
|
||||
len(retriever_resources),
|
||||
)
|
||||
metadata = data.get('metadata') if isinstance(data.get('metadata'), dict) else {}
|
||||
metadata['retriever_resources'] = retriever_resources
|
||||
data['metadata'] = metadata
|
||||
data['retriever_resources'] = retriever_resources
|
||||
|
||||
tokens_used = DifyService._extract_token_usage(data)
|
||||
db_write_started = time.time()
|
||||
run_id = None
|
||||
try:
|
||||
from app.services.file_check_tools.agent_resolver import is_file_check_chat_agent
|
||||
from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
|
||||
|
||||
if is_file_check_chat_agent(agent):
|
||||
run_id = resolve_run_id_for_chat_log(
|
||||
session_id=session_id,
|
||||
query=query,
|
||||
turn_id=hxops_turn_id,
|
||||
)
|
||||
except Exception:
|
||||
run_id = None
|
||||
|
||||
chat_log_id = DifyService._log_chat(
|
||||
user_id=user_id,
|
||||
agent_id=agent.id,
|
||||
session_id=session_id,
|
||||
conversation_id=data.get('conversation_id') or normalized_conversation_id,
|
||||
query=query,
|
||||
answer=answer_text,
|
||||
tokens=tokens_used,
|
||||
latency=latency,
|
||||
retriever_resources=retriever_resources,
|
||||
attribution_parts=attribution_parts,
|
||||
payload=message_payload,
|
||||
run_id=run_id,
|
||||
)
|
||||
if chat_log_id and current_app:
|
||||
current_app.logger.info(
|
||||
"[chat-perf] persisted async request_id=%s event=%s total_ms=%s db_write_ms=%s answer_len=%s tokens=%s conversation_id=%s chat_log_id=%s run_id=%s",
|
||||
request_id,
|
||||
event_name,
|
||||
latency,
|
||||
int((time.time() - db_write_started) * 1000),
|
||||
len(answer_text),
|
||||
tokens_used,
|
||||
data.get('conversation_id') or normalized_conversation_id,
|
||||
chat_log_id,
|
||||
run_id,
|
||||
)
|
||||
if not chat_log_id:
|
||||
return None
|
||||
return {"chat_log_id": chat_log_id, "run_id": run_id}
|
||||
|
||||
@staticmethod
|
||||
def _normalize_resources(resources):
|
||||
"""
|
||||
@@ -870,6 +1122,77 @@ class DifyService:
|
||||
DifyService._merge_attribution_parts(attribution_parts, event_data.get('citation'))
|
||||
DifyService._merge_attribution_parts(attribution_parts, metadata.get('citation'))
|
||||
|
||||
@staticmethod
|
||||
def _normalize_knowledge_retrieval_result(item: Any) -> dict | None:
|
||||
"""
|
||||
将 Chatflow 知识检索节点的单条 result 规范化为 retriever_resource 结构。
|
||||
核心逻辑:合并 metadata 中的 dataset/document/segment 字段到顶层,供前后端统一解析。
|
||||
"""
|
||||
if not isinstance(item, dict):
|
||||
return None
|
||||
|
||||
metadata = item.get('metadata') if isinstance(item.get('metadata'), dict) else {}
|
||||
document_name = (
|
||||
item.get('document_name')
|
||||
or metadata.get('document_name')
|
||||
or item.get('title')
|
||||
or metadata.get('title')
|
||||
)
|
||||
resource = {
|
||||
**item,
|
||||
'document_name': document_name,
|
||||
'content': item.get('content') or metadata.get('content') or '',
|
||||
'metadata': dict(metadata),
|
||||
}
|
||||
for key in ('dataset_id', 'dataset_name', 'document_id', 'segment_id', 'score'):
|
||||
value = metadata.get(key) if metadata.get(key) not in (None, '') else item.get(key)
|
||||
if value not in (None, '') and resource.get(key) in (None, ''):
|
||||
resource[key] = value
|
||||
return resource
|
||||
|
||||
@staticmethod
|
||||
def _collect_knowledge_retrieval_from_node(retriever_resources: List[Any], event_data: dict):
|
||||
"""
|
||||
从 knowledge-retrieval 节点的 node_finished 事件提取检索来源。
|
||||
核心逻辑:读取 data.outputs.result 列表,规范化后合并进 retriever_resources accumulator。
|
||||
"""
|
||||
if event_data.get('event') != 'node_finished':
|
||||
return
|
||||
|
||||
node = event_data.get('data') if isinstance(event_data.get('data'), dict) else {}
|
||||
if node.get('node_type') != 'knowledge-retrieval':
|
||||
return
|
||||
if node.get('status') not in (None, 'succeeded'):
|
||||
return
|
||||
|
||||
outputs = node.get('outputs') if isinstance(node.get('outputs'), dict) else {}
|
||||
results = outputs.get('result')
|
||||
if not isinstance(results, list):
|
||||
return
|
||||
|
||||
normalized: List[Any] = []
|
||||
for item in results:
|
||||
resource = DifyService._normalize_knowledge_retrieval_result(item)
|
||||
if resource:
|
||||
normalized.append(resource)
|
||||
DifyService._merge_retriever_resources(retriever_resources, normalized)
|
||||
|
||||
@staticmethod
|
||||
def _attach_retriever_resources_to_event(event_data: dict, retriever_resources: List[Any]):
|
||||
"""
|
||||
在 message_end / workflow_finished 下发前,把检索来源挂到 SSE 事件体。
|
||||
核心逻辑:只复制基础 retriever_resources;源文件下载链接由前端按需调用
|
||||
/api/chat/source-file 解析,避免阻塞最终答案的流式结束事件。
|
||||
"""
|
||||
if not retriever_resources:
|
||||
return
|
||||
|
||||
snapshot = json.loads(json.dumps(retriever_resources, ensure_ascii=False, default=str))
|
||||
event_data['retriever_resources'] = snapshot
|
||||
metadata = event_data.get('metadata') if isinstance(event_data.get('metadata'), dict) else {}
|
||||
metadata['retriever_resources'] = snapshot
|
||||
event_data['metadata'] = metadata
|
||||
|
||||
@staticmethod
|
||||
def _extract_dify_ids(resource: dict):
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
backend/app/services/faq/__init__.py
|
||||
|
||||
用途:FAQ 缓存与热榜聚合(收敛 faq_*、hot_faq_* 模块)。
|
||||
逻辑:Wave 4 自 services 根目录迁入。
|
||||
"""
|
||||
@@ -0,0 +1,2 @@
|
||||
"""FAQ 热榜聚合(Wave 4 自 hot_faq_aggregator.py 迁入)。"""
|
||||
from app.services import hot_faq_aggregator # noqa: F401
|
||||
@@ -0,0 +1,2 @@
|
||||
"""FAQ Redis 缓存(Wave 4 自 faq_cache.py 迁入)。"""
|
||||
from app.services import faq_cache # noqa: F401
|
||||
Loaded 100 of 666 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user