Compare commits
41
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f7890be317 | ||
|
|
9bc4d1dd18 | ||
|
|
ec97ea8787 | ||
|
|
587a215d88 | ||
|
|
8d8b40812d | ||
|
|
3f61e92549 | ||
|
|
c1c4efe4f1 | ||
|
|
d4f629106f | ||
|
|
ced7fbe085 | ||
|
|
dc141d19a2 | ||
|
|
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:8891
|
||||
+7
-27
@@ -47,10 +47,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 +68,14 @@ 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
|
||||
|
||||
|
||||
# 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)
|
||||
@@ -120,25 +122,3 @@ SRM_SQLSERVER_TIMEOUT=10
|
||||
# ERP
|
||||
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=
|
||||
@@ -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=
|
||||
+5
-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,5 @@ oracle_client/
|
||||
|
||||
# local env override
|
||||
.env.local
|
||||
backend/data/kb/
|
||||
.pytest_cache/
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"recommendations": ["ms-python.python", "ms-python.vscode-pylance"]
|
||||
}
|
||||
Vendored
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
// 后端 Python 虚拟环境:新终端自动激活,无需手动 .venv\Scripts\activate
|
||||
"python.defaultInterpreterPath": "${workspaceFolder}/backend/.venv/Scripts/python.exe",
|
||||
"python.terminal.activateEnvironment": true,
|
||||
"python.venvPath": "${workspaceFolder}/backend",
|
||||
"python.venvFolders": [".venv"],
|
||||
|
||||
// 可选:在终端下拉中选择「HXOPS Backend」时,直接进入 backend 并激活 venv
|
||||
"terminal.integrated.profiles.windows": {
|
||||
"HXOPS Backend": {
|
||||
"source": "PowerShell",
|
||||
"icon": "server-environment",
|
||||
"args": [
|
||||
"-NoExit",
|
||||
"-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) |
|
||||
@@ -72,27 +72,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 +142,7 @@ 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 生成/重构代码同样适用,不得省略。
|
||||
- ⚠️ 改动**数据库结构、部署脚本(`scripts/`、`Jenkinsfile`、`docker-compose.yml`)或敏感配置**前,先说明影响面再动手。
|
||||
|
||||
合并前最低自检(详见 [新人文档 §3.3](docs/新人环境搭建与配置文档.md)):前后端可启动、`frontend/` 改动后 `npm run build` 通过、关键页面与登录可用。
|
||||
@@ -156,4 +180,5 @@ 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) |
|
||||
| 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.md) |
|
||||
Vendored
+4
-1
@@ -201,6 +201,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 +530,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}
|
||||
'
|
||||
"""
|
||||
}
|
||||
|
||||
@@ -5,8 +5,6 @@ FROM ${PYTHON_BASE_IMAGE}
|
||||
ARG APT_MIRROR=https://mirrors.aliyun.com
|
||||
ARG PIP_INDEX_URL=https://mirrors.aliyun.com/pypi/simple
|
||||
ARG PIP_EXTRA_INDEX_URL
|
||||
ARG PIP_TIMEOUT=300
|
||||
ARG PIP_RETRIES=15
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
|
||||
@@ -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_rohs_check import workspace_rohs_check_bp
|
||||
from app.api.internal_jobs import internal_jobs_bp
|
||||
from app.api.shipping_notice_tools import shipping_notice_bp
|
||||
from app.api.rohs_check_tools import rohs_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_rohs_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(rohs_check_bp, url_prefix='/api/rohs-check')
|
||||
app.register_blueprint(speech_bp, url_prefix='/api/speech')
|
||||
|
||||
# Eagerly load persisted runtime settings so the very first request after
|
||||
|
||||
+128
-4
@@ -11,7 +11,7 @@ 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 datetime import datetime, timedelta
|
||||
import csv
|
||||
@@ -20,6 +20,7 @@ import re
|
||||
import requests
|
||||
import uuid
|
||||
from app.services.wecom_notify import send_wecom_event_message
|
||||
from app.services.wecom_directory_sync import sync_wecom_userids_from_directory
|
||||
from app.services.dify import DifyService
|
||||
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
|
||||
@@ -839,14 +840,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 +1227,77 @@ 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():
|
||||
"""
|
||||
从企微通讯录按工号同步 users.wecom_userid。
|
||||
Request JSON: { "apply": false, "department_id": 1 }
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
apply = bool(data.get('apply'))
|
||||
department_id = data.get('department_id')
|
||||
if department_id is not None and department_id != '':
|
||||
try:
|
||||
department_id = int(department_id)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('department_id must be an integer')
|
||||
else:
|
||||
department_id = None
|
||||
try:
|
||||
summary = sync_wecom_userids_from_directory(apply=apply, department_id=department_id)
|
||||
current_app.logger.info(
|
||||
'[wecom_sync] admin apply=%s updated=%s would_update=%s conflicts=%s',
|
||||
apply,
|
||||
summary.get('updated'),
|
||||
summary.get('would_update'),
|
||||
len(summary.get('conflicts') or []),
|
||||
)
|
||||
return jsonify(summary)
|
||||
except RuntimeError as exc:
|
||||
message = str(exc)
|
||||
if 'not configured' in message.lower():
|
||||
raise AppError(
|
||||
code='SYSTEM.HTTP_ERROR',
|
||||
message=message,
|
||||
http_status=503,
|
||||
details={'error_code': 'WECOM_NOT_CONFIGURED'},
|
||||
)
|
||||
if 'conflicts detected' in message.lower():
|
||||
raise ConflictError(message, details={'error_code': 'WECOM_SYNC_CONFLICTS'})
|
||||
if 'department/list failed' in message.lower() or 'user/list failed' in message.lower():
|
||||
raise AppError(
|
||||
code='SYSTEM.HTTP_ERROR',
|
||||
message='WeCom directory API failed. Check app contact read permissions.',
|
||||
http_status=502,
|
||||
details={'error_code': 'WECOM_DIRECTORY_API_FAILED', 'technical': message[:300]},
|
||||
)
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=message, http_status=500)
|
||||
|
||||
+67
-4
@@ -983,6 +983,60 @@ 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,
|
||||
)
|
||||
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():
|
||||
@@ -1101,7 +1155,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 +1163,19 @@ 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
|
||||
dify_inputs: dict[str, str] | None = None
|
||||
from app.services.rohs_check_tools.dify_inputs import (
|
||||
build_dify_chat_inputs as build_rohs_dify_chat_inputs,
|
||||
is_rohs_check_chat_agent,
|
||||
)
|
||||
from app.services.shipping_notice.dify_inputs import (
|
||||
build_dify_chat_inputs as build_shipping_dify_chat_inputs,
|
||||
is_shipping_notice_chat_agent,
|
||||
)
|
||||
if is_shipping_notice_chat_agent(agent_proxy):
|
||||
dify_inputs = build_dify_chat_inputs()
|
||||
dify_inputs = build_shipping_dify_chat_inputs()
|
||||
elif is_rohs_check_chat_agent(agent_proxy):
|
||||
dify_inputs = build_rohs_dify_chat_inputs()
|
||||
generator = DifyService.stream_chat(
|
||||
query,
|
||||
user_proxy.id,
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
"""
|
||||
backend/app/api/rohs_check_tools.py
|
||||
文件用途:RoHS Chatflow 显式 HTTP Tool API。
|
||||
"""
|
||||
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_rohs_check import serialize_rohs_judgement
|
||||
from app.errors import AppError, ConflictError, NotFoundError, ServiceUnavailableError, UnauthorizedError, ValidationError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
|
||||
from app.services.rohs_check_tools.openapi_spec import build_rohs_openapi_spec
|
||||
from app.services.schedule.query_service import get_run, serialize_run
|
||||
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
|
||||
|
||||
rohs_check_bp = Blueprint("rohs_check_tools", __name__)
|
||||
|
||||
_EXCEL_TOKEN_SCOPES = {"rohs_check_excel", "rohs_schedule_excel"}
|
||||
_RUN_START_LOCK = threading.Lock()
|
||||
_ROHS_GLOBAL_LOCK_KEY = 8700000000
|
||||
_ROHS_TASK_KEYWORDS = ("rohs", "rohs文件检核", "rohs 文件检核")
|
||||
|
||||
|
||||
def _tool_token_secret() -> str:
|
||||
return str(
|
||||
current_app.config.get("ROHS_TOOLS_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("[rohs-tool] download token validation failed: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
configured = str(
|
||||
current_app.config.get("ROHS_TOOLS_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
or ""
|
||||
).strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError(
|
||||
"ROHS_TOOLS_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",
|
||||
}:
|
||||
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
|
||||
|
||||
|
||||
@rohs_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 _is_rohs_check_task(task: ScheduleTask | None) -> bool:
|
||||
if not task:
|
||||
return False
|
||||
values = (
|
||||
getattr(task, "schedule_no", None),
|
||||
getattr(task, "name", None),
|
||||
getattr(task, "platform_api_path", None),
|
||||
)
|
||||
haystack = " ".join(str(item or "").lower() for item in values)
|
||||
return any(keyword in haystack for keyword in _ROHS_TASK_KEYWORDS)
|
||||
|
||||
|
||||
def _acquire_rohs_start_lock() -> None:
|
||||
"""Serialize RoHS start checks across processes when PostgreSQL is used."""
|
||||
bind = db.session.get_bind()
|
||||
if bind.dialect.name != "postgresql":
|
||||
return
|
||||
db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": _ROHS_GLOBAL_LOCK_KEY})
|
||||
|
||||
|
||||
def _build_excel_download_url(run: ScheduleRun) -> str:
|
||||
import jwt
|
||||
|
||||
payload = {
|
||||
"scope": "rohs_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/rohs-check/tools/runs/{run.id}/excel?token={token}"
|
||||
|
||||
|
||||
@rohs_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_rohs_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")
|
||||
if not _is_rohs_check_task(task):
|
||||
raise NotFoundError("task_not_found")
|
||||
return task
|
||||
|
||||
|
||||
@rohs_check_bp.route("/tools/tasks", methods=["GET"])
|
||||
def list_rohs_tasks():
|
||||
rows = ScheduleTask.query.order_by(ScheduleTask.created_at.desc()).all()
|
||||
tasks = []
|
||||
for task in rows:
|
||||
if not _is_rohs_check_task(task):
|
||||
continue
|
||||
latest = (
|
||||
ScheduleRun.query.filter_by(schedule_task_id=task.id)
|
||||
.order_by(ScheduleRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
tasks.append({
|
||||
"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})
|
||||
|
||||
|
||||
@rohs_check_bp.route("/tools/tasks/run", methods=["POST"])
|
||||
def run_rohs_check():
|
||||
"""立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
task = _resolve_check_task(data)
|
||||
|
||||
with _RUN_START_LOCK:
|
||||
_acquire_rohs_start_lock()
|
||||
existing = (
|
||||
ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
|
||||
.filter(ScheduleRun.status == "running")
|
||||
.order_by(ScheduleRun.id.desc())
|
||||
.all()
|
||||
)
|
||||
existing = next((row for row in existing if _is_rohs_check_task(row.task)), None)
|
||||
if existing:
|
||||
db.session.commit()
|
||||
return jsonify({
|
||||
"ok": False,
|
||||
"error_code": "check_running",
|
||||
"message": "该检核任务正在执行中,请稍后查询结果",
|
||||
"run": _serialize_tool_run(existing),
|
||||
}), 409
|
||||
|
||||
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"),
|
||||
"user_message": data.get("user_message"),
|
||||
},
|
||||
)
|
||||
db.session.add(run)
|
||||
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("[rohs-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"rohs-check-run-{run_id}").start()
|
||||
db.session.refresh(run)
|
||||
return jsonify({"ok": True, "message": "检核已启动", "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@rohs_check_bp.route("/tools/runs/<int:run_id>", methods=["GET"])
|
||||
def get_rohs_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)})
|
||||
|
||||
|
||||
@rohs_check_bp.route("/tools/runs", methods=["GET"])
|
||||
def list_rohs_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 if _is_rohs_check_task(row.task)]
|
||||
return jsonify({"ok": True, "runs": runs, "count": len(runs)})
|
||||
|
||||
|
||||
@rohs_check_bp.route("/tools/runs/<int:run_id>/excel", methods=["GET"])
|
||||
def download_rohs_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",
|
||||
)
|
||||
|
||||
|
||||
@rohs_check_bp.route("/tools/tasks/<int:task_id>/latest-run", methods=["GET"])
|
||||
def get_latest_rohs_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)})
|
||||
|
||||
|
||||
@rohs_check_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def rohs_openapi_spec():
|
||||
return jsonify(build_rohs_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
|
||||
@@ -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, '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))
|
||||
@@ -287,6 +311,8 @@ def import_schedules():
|
||||
else:
|
||||
task = create_task(name=name, schedule_type=task_payload['schedule_type'], owner_user_id=owner_user_id, cron_expr=cron_expr, wait_seconds=task_payload['wait_seconds'], dify_agent_id=task_payload['dify_agent_id'], platform_api_path=task_payload['platform_api_path'], notify_user_ids_json=task_payload['notify_user_ids_json'], notify_enabled=task_payload['notify_enabled'], enabled=task_payload['enabled'], actor_id=getattr(user, 'id', None))
|
||||
task.data_source_type = task_payload['data_source_type']
|
||||
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)
|
||||
@@ -305,6 +331,9 @@ def post_schedule():
|
||||
data_source_type = str(data.get('data_source_type') or 'database')
|
||||
task = create_task(name=str(data.get('name') or '').strip(), schedule_type='platform_app', owner_user_id=int(data.get('owner_user_id')), cron_expr=str(data.get('cron_expr') or '').strip(), wait_seconds=int(data.get('wait_seconds') or 0), dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None, platform_api_path=str(data.get('platform_api_path') or '').strip() or None, notify_user_ids_json=data.get('notify_user_ids_json') if isinstance(data.get('notify_user_ids_json'), list) else [], notify_enabled=bool(data.get('notify_enabled', True)), enabled=bool(data.get('enabled', True)), actor_id=getattr(user, 'id', None))
|
||||
task.data_source_type = data_source_type
|
||||
task.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
|
||||
task.platform_api_path = f'/{task.id}'
|
||||
db.session.commit()
|
||||
db.session.refresh(task)
|
||||
@@ -446,12 +475,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 +503,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')
|
||||
+246
-2
@@ -22,6 +22,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 +110,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())
|
||||
@@ -1560,6 +1581,204 @@ 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 _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 表示应静默拒绝
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
last = _PASSWORD_RESET_RATE_CACHE.get(key)
|
||||
if last and (now - last).total_seconds() < window_seconds:
|
||||
return False
|
||||
_PASSWORD_RESET_RATE_CACHE[key] = now
|
||||
return True
|
||||
|
||||
|
||||
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)
|
||||
if not _check_password_reset_rate_limit(rate_key):
|
||||
current_app.logger.info(
|
||||
'[password_reset] noop reason=rate_limited employee_id=%s',
|
||||
employee_id,
|
||||
)
|
||||
return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE})
|
||||
|
||||
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 = 'HXOPS 密码重置'
|
||||
content = (
|
||||
'您发起了 HXOPS 密码重置请求。\n'
|
||||
'请在 1 小时内点击下方按钮设置新密码。\n'
|
||||
'如非本人操作,请忽略本消息。'
|
||||
)
|
||||
try:
|
||||
result = send_wecom_event_message(
|
||||
event_type='password_reset',
|
||||
user=user,
|
||||
title=title,
|
||||
content=content,
|
||||
jump_path='/reset-password',
|
||||
jump_params={'token': token},
|
||||
)
|
||||
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():
|
||||
"""
|
||||
@@ -1598,11 +1817,15 @@ def reset_password_confirm():
|
||||
if not user or not user.reset_token_expiry or user.reset_token_expiry < datetime.utcnow():
|
||||
raise ValidationError('Invalid or expired token')
|
||||
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)
|
||||
@@ -1688,6 +1911,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,135 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.errors import ForbiddenError, NotFoundError, UnauthorizedError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.schedule.query_service import get_run, serialize_run
|
||||
|
||||
workspace_rohs_check_bp = Blueprint("workspace_rohs_check", __name__)
|
||||
|
||||
_ROHS_TASK_KEYWORDS = ("rohs", "rohs文件检核", "rohs 文件检核")
|
||||
|
||||
|
||||
def _require_user():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _is_rohs_check_task(task: ScheduleTask | None) -> bool:
|
||||
if not task:
|
||||
return False
|
||||
values = (
|
||||
getattr(task, "schedule_no", None),
|
||||
getattr(task, "name", None),
|
||||
getattr(task, "platform_api_path", None),
|
||||
)
|
||||
haystack = " ".join(str(item or "").lower() for item in values)
|
||||
return any(keyword in haystack for keyword in _ROHS_TASK_KEYWORDS)
|
||||
|
||||
|
||||
def serialize_rohs_judgement(payload: dict) -> dict:
|
||||
response_summary = payload.get("response_summary_json") if isinstance(payload.get("response_summary_json"), dict) else {}
|
||||
judgement = response_summary.get("rohs_judgement") if isinstance(response_summary.get("rohs_judgement"), dict) else {}
|
||||
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 "RoHS 文件检核",
|
||||
"status": payload["status"],
|
||||
"total_count": total,
|
||||
"processed_count": processed,
|
||||
"success_count": success,
|
||||
"failed_count": failed,
|
||||
"skipped_count": skipped,
|
||||
"judgement": serialize_rohs_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/schedule-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_rohs_check_bp.route("/rohs-check/runs/active", methods=["GET"])
|
||||
def workspace_rohs_active_run():
|
||||
_require_user()
|
||||
conversation_id = str(request.args.get("conversation_id") or "").strip()
|
||||
rows = (
|
||||
ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
|
||||
.filter(ScheduleRun.status == "running")
|
||||
.order_by(ScheduleRun.id.desc())
|
||||
.all()
|
||||
)
|
||||
run = next((
|
||||
row for row in rows
|
||||
if _is_rohs_check_task(row.task)
|
||||
and (
|
||||
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_rohs_check_bp.route("/rohs-check/runs/<int:run_id>", methods=["GET"])
|
||||
def workspace_rohs_run_detail(run_id: int):
|
||||
_require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
if not _is_rohs_check_task(run.task):
|
||||
raise ForbiddenError("Forbidden")
|
||||
return jsonify({"ok": True, "run": _serialize_progress_run(run)})
|
||||
@@ -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))
|
||||
|
||||
|
||||
@@ -75,7 +75,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
|
||||
|
||||
@@ -107,10 +107,14 @@ class Config:
|
||||
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
|
||||
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
|
||||
|
||||
# HXOPS Tool API 对外基地址(RoHS / 货代等 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')
|
||||
|
||||
# RoHS 检核 Chatflow Tool API
|
||||
ROHS_TOOLS_API_KEY = os.getenv('ROHS_TOOLS_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'
|
||||
@@ -184,7 +188,7 @@ class Config:
|
||||
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
|
||||
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset')
|
||||
|
||||
# JWT/Casdoor auth configuration (phase-1 compatible rollout)
|
||||
AUTH_LEGACY_HEADER_ENABLED = os.getenv('AUTH_LEGACY_HEADER_ENABLED', 'true').lower() == 'true'
|
||||
@@ -270,3 +274,4 @@ config = {
|
||||
'production': ProductionConfig,
|
||||
'default': DevelopmentConfig,
|
||||
}
|
||||
|
||||
@@ -585,6 +585,8 @@ class ScheduleTask(Base):
|
||||
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 +599,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 +675,22 @@ 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 ShippingTask(Base):
|
||||
|
||||
@@ -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,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
|
||||
@@ -0,0 +1,27 @@
|
||||
"""
|
||||
backend/app/services/hxops_tool_api.py
|
||||
文件用途:解析 HXOPS 对外 Tool API 基地址(Dify Chatflow / OpenAPI / 签名下载链接)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import current_app, has_request_context, request
|
||||
|
||||
|
||||
def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: str | None = None) -> str:
|
||||
"""返回无尾斜杠的 hxops 对外根地址,如 http://192.168.100.192:8891。"""
|
||||
cfg = config
|
||||
if cfg is None and current_app:
|
||||
cfg = current_app.config
|
||||
cfg = cfg or {}
|
||||
|
||||
for key in ("HXOPS_TOOLS_API_BASE", "HXOPS_TOOLS_API_BASE", "PUBLIC_BASE_URL"):
|
||||
configured = str(cfg.get(key) or "").strip().rstrip("/")
|
||||
if configured:
|
||||
return configured
|
||||
|
||||
host = request_host
|
||||
if host is None and has_request_context():
|
||||
host = request.host_url.rstrip("/")
|
||||
return host or ""
|
||||
|
||||
|
||||
@@ -6,15 +6,41 @@ from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocumentVersion, KbGroup
|
||||
from app.services.db_sequence import add_and_flush_with_sequence_retry
|
||||
from app.services.knowledge_cleaning.settings_service import get_kb_dify_settings
|
||||
|
||||
|
||||
_EXCEL_SOURCE_EXTENSIONS = frozenset({'xlsx', 'xls', 'csv'})
|
||||
|
||||
|
||||
def _decode_separator(value: str) -> str:
|
||||
"""Turn env/AppSetting escape sequences into real separator characters."""
|
||||
return str(value or '').replace('\\n', '\n').replace('\\t', '\t')
|
||||
|
||||
|
||||
def _as_bool_setting(value: str | None) -> bool:
|
||||
return str(value or '').strip().lower() in ('true', '1', 'yes', 'on')
|
||||
|
||||
|
||||
def resolve_source_file_ext(version: KbDocumentVersion) -> str | None:
|
||||
"""Lowercase extension without dot, e.g. xlsx."""
|
||||
ext = str(version.source_file_ext or '').strip().lower().lstrip('.')
|
||||
if ext:
|
||||
return ext
|
||||
name = str(version.source_file_name or '').strip()
|
||||
if not name:
|
||||
return None
|
||||
suffix = Path(name).suffix.lower().lstrip('.')
|
||||
return suffix or None
|
||||
|
||||
|
||||
class KbDifySyncError(RuntimeError):
|
||||
pass
|
||||
|
||||
@@ -28,8 +54,44 @@ class KbDifySyncService:
|
||||
self.indexing_technique = str(settings.get('KB_DIFY_INDEXING_TECHNIQUE') or 'high_quality')
|
||||
self.search_method = str(settings.get('KB_DIFY_SEARCH_METHOD') or 'semantic_search')
|
||||
self.doc_form = str(settings.get('KB_DIFY_DOC_FORM') or 'text_model')
|
||||
self.process_mode = str(settings.get('KB_DIFY_PROCESS_MODE') or 'automatic').strip().lower()
|
||||
self.process_mode_excel = str(settings.get('KB_DIFY_PROCESS_MODE_EXCEL') or 'custom').strip().lower()
|
||||
self.segment_separator = _decode_separator(str(settings.get('KB_DIFY_SEGMENT_SEPARATOR') or '\\n\\n'))
|
||||
self.segment_separator_excel = _decode_separator(
|
||||
str(settings.get('KB_DIFY_SEGMENT_SEPARATOR_EXCEL') or '\\n\\n')
|
||||
)
|
||||
self.segment_max_tokens = int(str(settings.get('KB_DIFY_SEGMENT_MAX_TOKENS') or '800'))
|
||||
self.segment_chunk_overlap = int(str(settings.get('KB_DIFY_SEGMENT_CHUNK_OVERLAP') or '50'))
|
||||
self.remove_urls_emails = _as_bool_setting(settings.get('KB_DIFY_REMOVE_URLS'))
|
||||
self.timeout = 60
|
||||
|
||||
def _build_process_rule(self, source_ext: str | None = None) -> dict:
|
||||
ext = str(source_ext or '').strip().lower().lstrip('.')
|
||||
if ext in _EXCEL_SOURCE_EXTENSIONS:
|
||||
mode = self.process_mode_excel
|
||||
separator = self.segment_separator_excel
|
||||
else:
|
||||
mode = self.process_mode
|
||||
separator = self.segment_separator
|
||||
|
||||
if mode != 'custom':
|
||||
return {'mode': 'automatic'}
|
||||
|
||||
return {
|
||||
'mode': 'custom',
|
||||
'rules': {
|
||||
'pre_processing_rules': [
|
||||
{'id': 'remove_extra_spaces', 'enabled': True},
|
||||
{'id': 'remove_urls_emails', 'enabled': self.remove_urls_emails},
|
||||
],
|
||||
'segmentation': {
|
||||
'separator': separator,
|
||||
'max_tokens': self.segment_max_tokens,
|
||||
'chunk_overlap': self.segment_chunk_overlap,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
if not self.base_url:
|
||||
raise KbDifySyncError('DIFY_API_BASE 未配置')
|
||||
@@ -99,21 +161,36 @@ class KbDifySyncService:
|
||||
db.session.commit()
|
||||
return group.dify_dataset_id, group.dify_dataset_name
|
||||
|
||||
def create_document_by_text(self, *, dataset_id: str, name: str, text: str) -> dict:
|
||||
def create_document_by_text(
|
||||
self,
|
||||
*,
|
||||
dataset_id: str,
|
||||
name: str,
|
||||
text: str,
|
||||
source_ext: str | None = None,
|
||||
) -> dict:
|
||||
payload = {
|
||||
'name': name,
|
||||
'text': text,
|
||||
'indexing_technique': self.indexing_technique,
|
||||
'doc_form': self.doc_form,
|
||||
'process_rule': {'mode': 'automatic'},
|
||||
'process_rule': self._build_process_rule(source_ext),
|
||||
}
|
||||
return self._request('POST', f'/datasets/{dataset_id}/document/create-by-text', json=payload)
|
||||
|
||||
def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict:
|
||||
def update_document_by_text(
|
||||
self,
|
||||
*,
|
||||
dataset_id: str,
|
||||
document_id: str,
|
||||
name: str,
|
||||
text: str,
|
||||
source_ext: str | None = None,
|
||||
) -> dict:
|
||||
payload = {
|
||||
'name': name,
|
||||
'text': text,
|
||||
'process_rule': {'mode': 'automatic'},
|
||||
'process_rule': self._build_process_rule(source_ext),
|
||||
}
|
||||
return self._request(
|
||||
'POST',
|
||||
@@ -131,6 +208,13 @@ class KbDifySyncService:
|
||||
)
|
||||
|
||||
|
||||
def _strip_base64_images(text: str) -> str:
|
||||
"""Remove markdown image syntax containing base64 data to avoid token bloat in Dify."""
|
||||
# Matches 
|
||||
pattern = r'!\[[^\]]*\]\(data:image\/[a-zA-Z]*;base64,[^)]*\)'
|
||||
return re.sub(pattern, '', text)
|
||||
|
||||
|
||||
def _load_sync_text(version: KbDocumentVersion) -> tuple[str, str]:
|
||||
candidate_paths = [version.cleaned_file_path, version.cleaned_preview_path, version.source_file_path]
|
||||
for value in candidate_paths:
|
||||
@@ -141,6 +225,8 @@ def _load_sync_text(version: KbDocumentVersion) -> tuple[str, str]:
|
||||
continue
|
||||
text = path.read_text(encoding='utf-8', errors='ignore').strip()
|
||||
if text:
|
||||
# Strip base64 images before syncing
|
||||
text = _strip_base64_images(text)
|
||||
return text, str(path)
|
||||
raise KbDifySyncError('没有可用于同步的文本结果')
|
||||
|
||||
@@ -174,6 +260,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
|
||||
|
||||
service = KbDifySyncService()
|
||||
dataset_id, dataset_name = service.ensure_dataset(group)
|
||||
source_ext = resolve_source_file_ext(version)
|
||||
|
||||
existing_record = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
@@ -203,6 +290,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
|
||||
dataset_id=dataset_id,
|
||||
name=upload_name,
|
||||
text=text,
|
||||
source_ext=source_ext,
|
||||
)
|
||||
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
|
||||
remote_document_name = payload.get('document', {}).get('name') or upload_name
|
||||
@@ -213,6 +301,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
|
||||
document_id=existing_record.remote_document_id,
|
||||
name=upload_name,
|
||||
text=text,
|
||||
source_ext=source_ext,
|
||||
)
|
||||
except KbDifySyncError as exc:
|
||||
if not _is_remote_document_missing(str(exc)):
|
||||
@@ -221,6 +310,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
|
||||
dataset_id=dataset_id,
|
||||
name=upload_name,
|
||||
text=text,
|
||||
source_ext=source_ext,
|
||||
)
|
||||
remote_document_id = payload.get('document', {}).get('id') or payload.get('id') or existing_record.remote_document_id
|
||||
remote_document_name = payload.get('document', {}).get('name') or upload_name
|
||||
@@ -229,6 +319,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
|
||||
dataset_id=dataset_id,
|
||||
name=upload_name,
|
||||
text=text,
|
||||
source_ext=source_ext,
|
||||
)
|
||||
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
|
||||
remote_document_name = payload.get('document', {}).get('name') or upload_name
|
||||
@@ -257,7 +348,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
|
||||
sync_hash=sync_hash,
|
||||
synced_by_id=synced_by_id,
|
||||
)
|
||||
db.session.add(record)
|
||||
add_and_flush_with_sequence_retry(record, "kb_dify_sync_records")
|
||||
else:
|
||||
record.dataset_id = dataset_id
|
||||
record.dataset_name = dataset_name
|
||||
|
||||
@@ -52,6 +52,42 @@ def _find_generated_preview_markdown(output_root: Path) -> Path | None:
|
||||
return candidates[0]
|
||||
|
||||
|
||||
def _find_generated_chunks_jsonl(output_root: Path) -> Path | None:
|
||||
candidates = [path for path in output_root.rglob('04_chunks.jsonl') if path.is_file()]
|
||||
if not candidates:
|
||||
return None
|
||||
candidates.sort(key=lambda item: len(item.parts))
|
||||
return candidates[0]
|
||||
|
||||
|
||||
def _count_jsonl_lines(path: Path) -> int:
|
||||
count = 0
|
||||
with path.open(encoding='utf-8', errors='ignore') as handle:
|
||||
for line in handle:
|
||||
if line.strip():
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def _persist_debug_chunks(output_root: Path, target_dir: Path) -> tuple[str | None, int | None]:
|
||||
"""Copy edkb chunk artifacts into the KB version directory for local debugging."""
|
||||
chunks_source = _find_generated_chunks_jsonl(output_root)
|
||||
if not chunks_source or not chunks_source.exists():
|
||||
return None, None
|
||||
|
||||
chunks_target = target_dir / '04_chunks.jsonl'
|
||||
shutil.copy2(chunks_source, chunks_target)
|
||||
|
||||
chunks_dir_source = chunks_source.parent / 'chunks'
|
||||
chunks_dir_target = target_dir / 'chunks'
|
||||
if chunks_dir_source.is_dir():
|
||||
if chunks_dir_target.exists():
|
||||
shutil.rmtree(chunks_dir_target)
|
||||
shutil.copytree(chunks_dir_source, chunks_dir_target)
|
||||
|
||||
return str(chunks_target), _count_jsonl_lines(chunks_target)
|
||||
|
||||
|
||||
def _rewrite_preview_markdown_if_needed(preview_path: Path, target_dir: Path) -> None:
|
||||
content = preview_path.read_text(encoding='utf-8', errors='ignore')
|
||||
if 'data:image/' not in content:
|
||||
@@ -141,10 +177,13 @@ def build_clean_result(source_path: Path, target_dir: Path) -> dict:
|
||||
shutil.copytree(preview_images_dir, target_preview_images_dir)
|
||||
_rewrite_preview_markdown_if_needed(preview_path, target_dir)
|
||||
content = cleaned_path.read_text(encoding='utf-8', errors='ignore')
|
||||
chunks_file_path, chunks_count = _persist_debug_chunks(output_dir, target_dir)
|
||||
|
||||
return {
|
||||
'mode': 'edkb_system',
|
||||
'cleaned_file_path': str(cleaned_path),
|
||||
'cleaned_preview_path': str(preview_path),
|
||||
'word_count': len(content.split()),
|
||||
'chunks_file_path': chunks_file_path,
|
||||
'chunks_count': chunks_count,
|
||||
}
|
||||
@@ -20,6 +20,13 @@ SETTING_DEFAULTS = {
|
||||
'KB_DIFY_INDEXING_TECHNIQUE': 'high_quality',
|
||||
'KB_DIFY_SEARCH_METHOD': 'semantic_search',
|
||||
'KB_DIFY_DOC_FORM': 'text_model',
|
||||
'KB_DIFY_PROCESS_MODE': 'automatic',
|
||||
'KB_DIFY_PROCESS_MODE_EXCEL': 'custom',
|
||||
'KB_DIFY_SEGMENT_SEPARATOR': '\\n\\n',
|
||||
'KB_DIFY_SEGMENT_SEPARATOR_EXCEL': '\\n\\n',
|
||||
'KB_DIFY_SEGMENT_MAX_TOKENS': '800',
|
||||
'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '50',
|
||||
'KB_DIFY_REMOVE_URLS': 'false',
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import zipfile
|
||||
|
||||
from flask import current_app
|
||||
from app import db
|
||||
from app.models import KbDocument, KbDocumentVersion, KbJob
|
||||
from app.models import KbDocument, KbDocumentVersion, KbJob, ScheduleRun
|
||||
from app.services.knowledge_cleaning.edkb_adapter import build_clean_result
|
||||
from app.services.knowledge_cleaning.dify_sync_service import (
|
||||
KbDifySyncError,
|
||||
@@ -25,6 +25,26 @@ def _utc_now() -> datetime:
|
||||
return datetime.utcnow()
|
||||
|
||||
|
||||
def _schedule_run_id_from_job(job: KbJob | None) -> int | None:
|
||||
payload = dict(getattr(job, "payload_json", None) or {})
|
||||
raw_run_id = payload.get("schedule_run_id")
|
||||
if raw_run_id in (None, "", 0, "0"):
|
||||
return None
|
||||
try:
|
||||
return int(raw_run_id)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _touch_schedule_run_kb_sync(job: KbJob | None, *, status: str, error: str | None = None) -> None:
|
||||
run_id = _schedule_run_id_from_job(job)
|
||||
if not run_id:
|
||||
return
|
||||
from app.services.schedule.kb_sync import update_schedule_run_kb_sync_status
|
||||
|
||||
update_schedule_run_kb_sync_status(run_id, status=status, error=error)
|
||||
|
||||
|
||||
def _infer_missing_extension(source_path: Path) -> str:
|
||||
if zipfile.is_zipfile(source_path):
|
||||
try:
|
||||
@@ -398,6 +418,24 @@ def run_path_upload_job(job_id: int) -> tuple[bool, str]:
|
||||
db.session.commit()
|
||||
return False, 'partial_failed'
|
||||
|
||||
sync_job_id = None
|
||||
payload = dict(job.payload_json or {})
|
||||
if payload.get('auto_sync_dify'):
|
||||
sync_job = KbJob(
|
||||
job_type='sync_dify',
|
||||
status='queued',
|
||||
group_id=job.group_id,
|
||||
document_id=job.document_id,
|
||||
document_version_id=job.document_version_id,
|
||||
progress=0,
|
||||
message='等待同步到 Dify',
|
||||
payload_json={'document_version_id': job.document_version_id, 'source_job_id': job.id},
|
||||
created_by_id=job.created_by_id,
|
||||
)
|
||||
db.session.add(sync_job)
|
||||
db.session.flush()
|
||||
sync_job_id = sync_job.id
|
||||
|
||||
job.status = 'success'
|
||||
job.message = f'路径上传完成,成功 {success_count} 条'
|
||||
job.error_message = None
|
||||
@@ -432,6 +470,7 @@ def run_clean_job(job_id: int) -> tuple[bool, str]:
|
||||
job.error_message = '关联文档版本不存在'
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
_touch_schedule_run_kb_sync(job, status='failed', error='关联文档版本不存在')
|
||||
return False, '关联文档版本不存在'
|
||||
|
||||
source_path = Path(version.source_file_path)
|
||||
@@ -442,6 +481,7 @@ def run_clean_job(job_id: int) -> tuple[bool, str]:
|
||||
version.error_message = '原始文件不存在,无法执行 clean'
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
_touch_schedule_run_kb_sync(job, status='failed', error='原始文件不存在,无法执行 clean')
|
||||
return False, '原始文件不存在'
|
||||
|
||||
job.status = 'running'
|
||||
@@ -450,6 +490,7 @@ def run_clean_job(job_id: int) -> tuple[bool, str]:
|
||||
job.started_at = _utc_now()
|
||||
version.status = 'processing'
|
||||
db.session.commit()
|
||||
_touch_schedule_run_kb_sync(job, status='cleaning')
|
||||
|
||||
target_dir = source_path.parent
|
||||
warnings = []
|
||||
@@ -479,6 +520,7 @@ def run_clean_job(job_id: int) -> tuple[bool, str]:
|
||||
version.status = 'failed'
|
||||
version.error_message = str(exc)
|
||||
db.session.commit()
|
||||
_touch_schedule_run_kb_sync(job, status='failed', error=str(exc))
|
||||
return False, 'timeout'
|
||||
|
||||
preview_path = target_dir / f'{_normalized_source_filename(version, source_path)}.preview.txt'
|
||||
@@ -516,8 +558,42 @@ def run_clean_job(job_id: int) -> tuple[bool, str]:
|
||||
job.error_message = None
|
||||
job.result_json = result
|
||||
job.finished_at = _utc_now()
|
||||
|
||||
sync_job_id = None
|
||||
payload = dict(job.payload_json or {})
|
||||
if payload.get('auto_sync_dify'):
|
||||
sync_job = KbJob(
|
||||
job_type='sync_dify',
|
||||
status='queued',
|
||||
group_id=job.group_id,
|
||||
document_id=job.document_id,
|
||||
document_version_id=job.document_version_id,
|
||||
progress=0,
|
||||
message='等待同步到 Dify',
|
||||
payload_json={
|
||||
'document_version_id': job.document_version_id,
|
||||
'source_job_id': job.id,
|
||||
'schedule_run_id': payload.get('schedule_run_id'),
|
||||
},
|
||||
created_by_id=job.created_by_id,
|
||||
)
|
||||
db.session.add(sync_job)
|
||||
db.session.flush()
|
||||
sync_job_id = sync_job.id
|
||||
run_id = _schedule_run_id_from_job(job)
|
||||
if run_id:
|
||||
run = db.session.get(ScheduleRun, run_id)
|
||||
if run:
|
||||
run.kb_sync_job_id = sync_job_id
|
||||
run.kb_sync_status = 'syncing'
|
||||
|
||||
db.session.commit()
|
||||
|
||||
if sync_job_id:
|
||||
from app.services.knowledge_cleaning.queue_service import enqueue_kb_job
|
||||
|
||||
enqueue_kb_job(sync_job_id)
|
||||
|
||||
return True, 'ok'
|
||||
|
||||
|
||||
@@ -552,6 +628,7 @@ def run_sync_job(job_id: int) -> tuple[bool, str]:
|
||||
job.message = '同步到 Dify 失败'
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
_touch_schedule_run_kb_sync(job, status='failed', error=str(exc))
|
||||
return False, str(exc)
|
||||
except Exception as exc:
|
||||
version.status = 'ready'
|
||||
@@ -561,6 +638,7 @@ def run_sync_job(job_id: int) -> tuple[bool, str]:
|
||||
job.message = '同步到 Dify 失败'
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
_touch_schedule_run_kb_sync(job, status='failed', error=str(exc))
|
||||
return False, str(exc)
|
||||
|
||||
version.status = 'synced'
|
||||
@@ -571,4 +649,5 @@ def run_sync_job(job_id: int) -> tuple[bool, str]:
|
||||
job.result_json = result
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
_touch_schedule_run_kb_sync(job, status='success')
|
||||
return True, 'ok'
|
||||
@@ -0,0 +1,98 @@
|
||||
"""
|
||||
backend/app/services/rohs_check.py
|
||||
文件用途:RoHS 文件检核统一判定入口,当前适配现有 Dify Workflow。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.dify import DifyService
|
||||
|
||||
|
||||
VALID_ROHS_RESULTS = {"合格", "不合格", "人工判定"}
|
||||
|
||||
|
||||
class RoHSCheckService:
|
||||
"""Wrap RoHS judgement behind a stable backend interface."""
|
||||
|
||||
PROVIDER = "dify_workflow"
|
||||
|
||||
@classmethod
|
||||
def evaluate(
|
||||
cls,
|
||||
*,
|
||||
agent,
|
||||
run_no: str,
|
||||
record: str,
|
||||
attachment_url: str | None = None,
|
||||
system_prompt: str | None = None,
|
||||
user: str = "schedule_system",
|
||||
timeout: tuple[int, int] = (5, 300),
|
||||
) -> dict[str, Any]:
|
||||
inputs: dict[str, Any] = {
|
||||
"run_no": run_no,
|
||||
"record": record,
|
||||
"attachment_url": attachment_url,
|
||||
}
|
||||
prompt = str(system_prompt or "").strip()
|
||||
if prompt:
|
||||
inputs["system_prompt"] = prompt
|
||||
|
||||
try:
|
||||
workflow_result = DifyService.run_workflow_streaming(
|
||||
agent=agent,
|
||||
inputs=inputs,
|
||||
user=user,
|
||||
timeout=timeout,
|
||||
)
|
||||
except Exception as exc:
|
||||
return {
|
||||
"dify_result": "人工判定",
|
||||
"dify_message": f"Dify执行失败:{exc}",
|
||||
"provider": cls.PROVIDER,
|
||||
"workflow_run_id": None,
|
||||
"error": str(exc),
|
||||
}
|
||||
|
||||
normalized = cls.normalize_workflow_result(workflow_result)
|
||||
normalized["provider"] = cls.PROVIDER
|
||||
return normalized
|
||||
|
||||
@staticmethod
|
||||
def normalize_workflow_result(workflow_result: dict[str, Any] | None) -> dict[str, Any]:
|
||||
data = workflow_result if isinstance(workflow_result, dict) else {}
|
||||
outputs = (data.get("outputs") or {}).get("output") or data.get("outputs") or data
|
||||
output_data = outputs if isinstance(outputs, dict) else {}
|
||||
dify_result = str(output_data.get("dify_result") or output_data.get("result") or "").strip()
|
||||
dify_message = str(output_data.get("dify_message") or output_data.get("message") or "").strip()
|
||||
workflow_run_id = data.get("workflow_run_id") if isinstance(data, dict) else None
|
||||
status = data.get("status") if isinstance(data, dict) else None
|
||||
error = data.get("error") if isinstance(data, dict) else None
|
||||
|
||||
if status == "failed" or (error and not output_data):
|
||||
return {
|
||||
"dify_result": "人工判定",
|
||||
"dify_message": f"Dify执行失败:{error or f'status={status}'}",
|
||||
"workflow_run_id": workflow_run_id,
|
||||
"error": str(error or ""),
|
||||
"raw_outputs": output_data,
|
||||
}
|
||||
|
||||
if dify_result not in VALID_ROHS_RESULTS:
|
||||
bad_value = dify_result or "空"
|
||||
extra = f" | {dify_message}" if dify_message else ""
|
||||
return {
|
||||
"dify_result": "人工判定",
|
||||
"dify_message": f"返回值异常:{bad_value}{extra}",
|
||||
"workflow_run_id": workflow_run_id,
|
||||
"error": None,
|
||||
"raw_outputs": output_data,
|
||||
}
|
||||
|
||||
return {
|
||||
"dify_result": dify_result,
|
||||
"dify_message": dify_message,
|
||||
"workflow_run_id": workflow_run_id,
|
||||
"error": None,
|
||||
"raw_outputs": output_data,
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,21 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from app.models import Agent
|
||||
|
||||
# Dify / HXOPS Agent.name 常见取值(含「助手」后缀)
|
||||
CHAT_AGENT_NAMES = frozenset(
|
||||
{
|
||||
"RoHS文件检核",
|
||||
"RoHS文件检核助手",
|
||||
"RoHS 文件检核助手",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def is_rohs_check_chat_agent(agent) -> bool:
|
||||
name = (getattr(agent, "name", None) or "").strip()
|
||||
return name in CHAT_AGENT_NAMES
|
||||
|
||||
|
||||
def resolve_chat_agent() -> Agent | None:
|
||||
return Agent.query.filter(Agent.name.in_(CHAT_AGENT_NAMES), Agent.is_active.is_(True)).first()
|
||||
@@ -0,0 +1,34 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
|
||||
from app.services.rohs_check_tools.agent_resolver import is_rohs_check_chat_agent
|
||||
|
||||
# Dify Chatflow「用户输入」变量名 — 须与画布 Start 节点配置一致(见 docs/rohs_chatflow_guide.md §3.1)
|
||||
HXOPS_TOOLS_API_BASE_INPUT = "HXOPS_TOOLS_API_BASE"
|
||||
HXOPS_TOOL_API_TOKEN_INPUT = "hxops_tool_api_token"
|
||||
|
||||
|
||||
def build_dify_chat_inputs() -> dict[str, str]:
|
||||
"""Build Dify chat API inputs for RoHS Chatflow HTTP nodes."""
|
||||
base = resolve_HXOPS_TOOLS_API_BASE()
|
||||
key = str(
|
||||
current_app.config.get("ROHS_TOOLS_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
or ""
|
||||
).strip()
|
||||
inputs: dict[str, str] = {}
|
||||
if base:
|
||||
inputs[HXOPS_TOOLS_API_BASE_INPUT] = base
|
||||
if key:
|
||||
inputs[HXOPS_TOOL_API_TOKEN_INPUT] = key
|
||||
return inputs
|
||||
|
||||
|
||||
__all__ = [
|
||||
"HXOPS_TOOLS_API_BASE_INPUT",
|
||||
"HXOPS_TOOL_API_TOKEN_INPUT",
|
||||
"build_dify_chat_inputs",
|
||||
"is_rohs_check_chat_agent",
|
||||
]
|
||||
@@ -0,0 +1,435 @@
|
||||
{
|
||||
"openapi": "3.0.3",
|
||||
"info": {
|
||||
"title": "HXOPS RoHS Check Tool API",
|
||||
"description": "RoHS 文件检核 Chatflow 显式 HTTP Tool API:检核任务列表、发起检核、查询检核批次、下载检核报告。鉴权:Authorization Bearer 或 X-Integration-Key。",
|
||||
"version": "1.0.0"
|
||||
},
|
||||
"servers": [
|
||||
{
|
||||
"url": "http://192.168.100.192:8890",
|
||||
"description": "部署时设为 HXOPS_TOOLS_API_BASE;GET /tools/openapi.json 会按服务端配置自动覆盖"
|
||||
}
|
||||
],
|
||||
"security": [
|
||||
{ "BearerAuth": [] },
|
||||
{ "IntegrationKey": [] }
|
||||
],
|
||||
"paths": {
|
||||
"/api/rohs-check/tools/tasks": {
|
||||
"get": {
|
||||
"operationId": "list_rohs_tasks",
|
||||
"summary": "查询 RoHS 检核任务列表",
|
||||
"tags": ["RoHS Check"],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "成功",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/ListTasksResponse" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": { "$ref": "#/components/responses/Unauthorized" },
|
||||
"503": { "$ref": "#/components/responses/MissingAuth" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/rohs-check/tools/tasks/run": {
|
||||
"post": {
|
||||
"operationId": "run_rohs_check",
|
||||
"summary": "异步启动 RoHS 检核",
|
||||
"tags": ["RoHS Check"],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/RunCheckRequest" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "启动成功",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/RunCheckSuccessResponse" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "RoHS 检核进行中,全局不可重复启动",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/CheckRunningResponse" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": { "$ref": "#/components/responses/BadRequest" },
|
||||
"401": { "$ref": "#/components/responses/Unauthorized" },
|
||||
"404": { "$ref": "#/components/responses/TaskNotFound" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/rohs-check/tools/runs": {
|
||||
"get": {
|
||||
"operationId": "list_rohs_runs",
|
||||
"summary": "查询 RoHS 检核批次列表",
|
||||
"tags": ["RoHS Check"],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "task_id",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": { "type": "integer", "example": 12 },
|
||||
"description": "可选;指定检核任务 ID 时只返回该任务批次"
|
||||
},
|
||||
{
|
||||
"name": "limit",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": { "type": "integer", "minimum": 1, "maximum": 100, "default": 20 },
|
||||
"description": "返回条数,最大 100"
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "成功",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/ListRunsResponse" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": { "$ref": "#/components/responses/Unauthorized" },
|
||||
"404": { "$ref": "#/components/responses/TaskNotFound" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/rohs-check/tools/runs/{run_id}": {
|
||||
"get": {
|
||||
"operationId": "get_rohs_run",
|
||||
"summary": "查询指定检核批次",
|
||||
"tags": ["RoHS Check"],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "run_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": { "type": "integer", "example": 88 }
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "成功",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/GetRunResponse" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": { "$ref": "#/components/responses/Unauthorized" },
|
||||
"404": { "$ref": "#/components/responses/RunNotFound" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/rohs-check/tools/tasks/{task_id}/latest-run": {
|
||||
"get": {
|
||||
"operationId": "get_latest_rohs_run",
|
||||
"summary": "查询检核任务最近一次检核",
|
||||
"tags": ["RoHS Check"],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "task_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": { "type": "integer", "example": 12 }
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "成功",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/GetRunResponse" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": { "$ref": "#/components/responses/Unauthorized" },
|
||||
"404": { "$ref": "#/components/responses/RunNotFound" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/rohs-check/tools/runs/{run_id}/excel": {
|
||||
"get": {
|
||||
"operationId": "download_rohs_run_excel",
|
||||
"summary": "下载检核报告 Excel(短期签名 token)",
|
||||
"tags": ["RoHS Check"],
|
||||
"security": [],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "run_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": { "type": "integer", "example": 88 }
|
||||
},
|
||||
{
|
||||
"name": "token",
|
||||
"in": "query",
|
||||
"required": true,
|
||||
"description": "由 get_rohs_run 返回的 excel.download_url 中的 JWT,有效期 600 秒",
|
||||
"schema": { "type": "string" }
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Excel 文件流",
|
||||
"content": {
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
|
||||
"schema": { "type": "string", "format": "binary" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"409": { "$ref": "#/components/responses/ExcelNotReady" }
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
"securitySchemes": {
|
||||
"BearerAuth": {
|
||||
"type": "http",
|
||||
"scheme": "bearer",
|
||||
"description": "ROHS_TOOLS_API_KEY 或 INTEGRATION_API_KEY"
|
||||
},
|
||||
"IntegrationKey": {
|
||||
"type": "apiKey",
|
||||
"in": "header",
|
||||
"name": "X-Integration-Key",
|
||||
"description": "与 Bearer 二选一"
|
||||
}
|
||||
},
|
||||
"schemas": {
|
||||
"TaskSummary": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"task_id": { "type": "integer", "example": 12 },
|
||||
"task_no": { "type": "string", "example": "CHK202606090001" },
|
||||
"name": { "type": "string", "example": "RoHS 自动检核" },
|
||||
"enabled": { "type": "boolean" },
|
||||
"last_status": { "type": "string", "nullable": true, "example": "success" },
|
||||
"last_run_at": { "type": "string", "format": "date-time", "nullable": true },
|
||||
"next_run_at": { "type": "string", "format": "date-time", "nullable": true }
|
||||
}
|
||||
},
|
||||
"RunExcel": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"file_name": { "type": "string", "nullable": true, "example": "RUN202606090001.xlsx" },
|
||||
"file_size": { "type": "integer", "nullable": true, "example": 45678 },
|
||||
"download_url": {
|
||||
"type": "string",
|
||||
"nullable": true,
|
||||
"example": "http://192.168.100.192:8891/api/rohs-check/tools/runs/88/excel?token=..."
|
||||
}
|
||||
}
|
||||
},
|
||||
"RunKnowledgeBase": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": { "type": "boolean" },
|
||||
"sync_status": {
|
||||
"type": "string",
|
||||
"nullable": true,
|
||||
"enum": ["skipped", "queued", "cleaning", "syncing", "ready", "success", "failed"]
|
||||
},
|
||||
"group_id": { "type": "integer", "nullable": true },
|
||||
"document_id": { "type": "integer", "nullable": true },
|
||||
"document_version_id": { "type": "integer", "nullable": true },
|
||||
"sync_job_id": { "type": "integer", "nullable": true },
|
||||
"error_message": { "type": "string", "nullable": true }
|
||||
}
|
||||
},
|
||||
"RunDetail": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"run_id": { "type": "integer", "example": 88 },
|
||||
"run_no": { "type": "string", "example": "RUN202606090001" },
|
||||
"task_id": { "type": "integer", "example": 12 },
|
||||
"task_name": { "type": "string", "example": "RoHS 自动检核" },
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": ["running", "success", "partial_failed", "failed", "queued", "cancelled"]
|
||||
},
|
||||
"total_count": { "type": "integer" },
|
||||
"success_count": { "type": "integer" },
|
||||
"failed_count": { "type": "integer" },
|
||||
"skipped_count": { "type": "integer" },
|
||||
"started_at": { "type": "string", "format": "date-time", "nullable": true },
|
||||
"finished_at": { "type": "string", "format": "date-time", "nullable": true },
|
||||
"duration_ms": { "type": "integer", "nullable": true },
|
||||
"error_message": { "type": "string", "nullable": true },
|
||||
"excel": { "$ref": "#/components/schemas/RunExcel" },
|
||||
"knowledge_base": { "$ref": "#/components/schemas/RunKnowledgeBase" }
|
||||
}
|
||||
},
|
||||
"ListTasksResponse": {
|
||||
"type": "object",
|
||||
"required": ["ok", "tasks"],
|
||||
"properties": {
|
||||
"ok": { "type": "boolean", "example": true },
|
||||
"tasks": {
|
||||
"type": "array",
|
||||
"items": { "$ref": "#/components/schemas/TaskSummary" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"RunCheckRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"task_id": { "type": "integer", "example": 12 },
|
||||
"task_no": { "type": "string", "example": "CHK202606090001" },
|
||||
"trigger_source": { "type": "string", "default": "dify_chatflow" },
|
||||
"conversation_id": { "type": "string", "nullable": true },
|
||||
"user_message": { "type": "string", "nullable": true }
|
||||
},
|
||||
"required": ["task_id"],
|
||||
"description": "Chatflow Start 节点固定配置 task_id;后端仍兼容 task_no,但 RoHS Chatflow 不使用任务选择流程"
|
||||
},
|
||||
"RunCheckSuccessResponse": {
|
||||
"type": "object",
|
||||
"required": ["ok", "message", "run"],
|
||||
"properties": {
|
||||
"ok": { "type": "boolean", "example": true },
|
||||
"message": { "type": "string", "example": "检核已启动" },
|
||||
"run": { "$ref": "#/components/schemas/RunDetail" }
|
||||
}
|
||||
},
|
||||
"CheckRunningResponse": {
|
||||
"type": "object",
|
||||
"required": ["ok", "error_code", "message", "run"],
|
||||
"properties": {
|
||||
"ok": { "type": "boolean", "example": false },
|
||||
"error_code": { "type": "string", "example": "check_running" },
|
||||
"message": { "type": "string", "example": "该检核任务正在执行中,请稍后查询结果" },
|
||||
"run": { "$ref": "#/components/schemas/RunDetail" }
|
||||
}
|
||||
},
|
||||
"GetRunResponse": {
|
||||
"type": "object",
|
||||
"required": ["ok", "run"],
|
||||
"properties": {
|
||||
"ok": { "type": "boolean", "example": true },
|
||||
"run": { "$ref": "#/components/schemas/RunDetail" }
|
||||
}
|
||||
},
|
||||
"ListRunsResponse": {
|
||||
"type": "object",
|
||||
"required": ["ok", "runs", "count"],
|
||||
"properties": {
|
||||
"ok": { "type": "boolean", "example": true },
|
||||
"count": { "type": "integer", "example": 2 },
|
||||
"runs": {
|
||||
"type": "array",
|
||||
"items": { "$ref": "#/components/schemas/RunDetail" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"ErrorResponse": {
|
||||
"type": "object",
|
||||
"required": ["ok", "error_code", "message"],
|
||||
"properties": {
|
||||
"ok": { "type": "boolean", "example": false },
|
||||
"error_code": { "type": "string" },
|
||||
"message": { "type": "string" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"Unauthorized": {
|
||||
"description": "鉴权失败",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/ErrorResponse" },
|
||||
"examples": {
|
||||
"missing_auth": {
|
||||
"value": { "ok": false, "error_code": "missing_auth", "message": "missing_auth" }
|
||||
},
|
||||
"invalid_auth": {
|
||||
"value": { "ok": false, "error_code": "invalid_auth", "message": "invalid_auth" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"MissingAuth": {
|
||||
"description": "服务端未配置 ROHS_TOOLS_API_KEY / INTEGRATION_API_KEY",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/ErrorResponse" },
|
||||
"example": {
|
||||
"ok": false,
|
||||
"error_code": "missing_auth",
|
||||
"message": "ROHS_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"BadRequest": {
|
||||
"description": "请求参数无效",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/ErrorResponse" },
|
||||
"example": {
|
||||
"ok": false,
|
||||
"error_code": "invalid_request",
|
||||
"message": "invalid_request"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"TaskNotFound": {
|
||||
"description": "检核任务不存在",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/ErrorResponse" },
|
||||
"example": {
|
||||
"ok": false,
|
||||
"error_code": "task_not_found",
|
||||
"message": "task_not_found"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"RunNotFound": {
|
||||
"description": "检核批次不存在",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/ErrorResponse" },
|
||||
"example": {
|
||||
"ok": false,
|
||||
"error_code": "run_not_found",
|
||||
"message": "run_not_found"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"ExcelNotReady": {
|
||||
"description": "Excel 尚未生成",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/ErrorResponse" },
|
||||
"example": {
|
||||
"ok": false,
|
||||
"error_code": "excel_not_ready",
|
||||
"message": "excel_not_ready"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
_BASE_SPEC_PATH = Path(__file__).with_name("openapi_base.json")
|
||||
|
||||
|
||||
def _load_base_spec() -> dict[str, Any]:
|
||||
with _BASE_SPEC_PATH.open("r", encoding="utf-8") as fp:
|
||||
return json.load(fp)
|
||||
|
||||
|
||||
def build_rohs_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
"""Build OpenAPI 3.0 spec for RoHS Chatflow HTTP tools."""
|
||||
spec = copy.deepcopy(_load_base_spec())
|
||||
base = str(base_url or "").strip().rstrip("/")
|
||||
servers = spec.get("servers")
|
||||
if base and isinstance(servers, list) and servers:
|
||||
servers[0]["url"] = base
|
||||
servers[0]["description"] = "HXOPS_TOOLS_API_BASE"
|
||||
return spec
|
||||
@@ -0,0 +1,252 @@
|
||||
"""
|
||||
backend/app/services/schedule/kb_sync.py
|
||||
文件用途:把排程运行生成的 Excel 结果注册为知识库文档并触发清洗/同步。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
from flask import current_app
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
from app import db
|
||||
from app.services.db_sequence import add_and_flush_with_sequence_retry
|
||||
from app.models import KbDocument, KbDocumentVersion, KbGroup, KbJob, ScheduleRun, ScheduleTask
|
||||
from app.services.knowledge_cleaning.queue_service import enqueue_clean_job
|
||||
|
||||
|
||||
def update_schedule_run_kb_sync_status(
|
||||
run_id: int | None,
|
||||
*,
|
||||
status: str,
|
||||
error: str | None = None,
|
||||
) -> None:
|
||||
"""回写排程运行的知识库同步状态,供 Chatflow 查询。"""
|
||||
if not run_id:
|
||||
return
|
||||
run = db.session.get(ScheduleRun, int(run_id))
|
||||
if not run:
|
||||
return
|
||||
run.kb_sync_status = status
|
||||
if error is not None:
|
||||
run.kb_sync_error = error
|
||||
elif status == "success":
|
||||
run.kb_sync_error = None
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _kb_storage_root() -> Path:
|
||||
root = Path(current_app.config.get("KB_STORAGE_ROOT")).resolve()
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
return root
|
||||
|
||||
|
||||
def _next_version_no(document: KbDocument) -> int:
|
||||
versions = list(getattr(document, "versions", []) or [])
|
||||
if not versions:
|
||||
return 1
|
||||
return max(item.version_no for item in versions) + 1
|
||||
|
||||
|
||||
def _safe_excel_name(raw_name: str) -> str:
|
||||
name = Path(str(raw_name or "")).name.strip() or "schedule_result.xlsx"
|
||||
safe_stem = secure_filename(Path(name).stem) or "schedule_result"
|
||||
suffix = Path(name).suffix or ".xlsx"
|
||||
return f"{safe_stem}{suffix}"
|
||||
|
||||
|
||||
def _create_kb_document_with_sequence_retry(**fields) -> KbDocument:
|
||||
document = KbDocument(**fields)
|
||||
add_and_flush_with_sequence_retry(document, "kb_documents")
|
||||
return document
|
||||
|
||||
|
||||
def sync_schedule_run_excel_to_kb(
|
||||
task: ScheduleTask,
|
||||
run: ScheduleRun,
|
||||
*,
|
||||
enabled: bool | None = None,
|
||||
process_inline: bool = True,
|
||||
) -> None:
|
||||
kb_enabled = bool(getattr(task, "kb_sync_enabled", False)) if enabled is None else bool(enabled)
|
||||
if not kb_enabled:
|
||||
run.kb_sync_status = "skipped"
|
||||
run.kb_sync_error = None
|
||||
if current_app:
|
||||
current_app.logger.info("[schedule-kb-sync] skipped run=%s: kb sync disabled", run.id)
|
||||
return
|
||||
if not task.kb_group_id:
|
||||
run.kb_sync_status = "failed"
|
||||
run.kb_sync_error = "未配置目标知识库分组"
|
||||
if current_app:
|
||||
current_app.logger.warning("[schedule-kb-sync] failed run=%s: kb_group_id missing", run.id)
|
||||
return
|
||||
if run.status not in ("success", "partial_failed"):
|
||||
run.kb_sync_status = "skipped"
|
||||
run.kb_sync_error = None
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[schedule-kb-sync] skipped run=%s: status=%s",
|
||||
run.id,
|
||||
run.status,
|
||||
)
|
||||
return
|
||||
if not run.excel_file_data:
|
||||
run.kb_sync_status = "skipped"
|
||||
run.kb_sync_error = "未生成 Excel 文件"
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[schedule-kb-sync] skipped run=%s: excel_file_data empty (size=%s)",
|
||||
run.id,
|
||||
run.excel_file_size,
|
||||
)
|
||||
return
|
||||
|
||||
group = db.session.get(KbGroup, task.kb_group_id)
|
||||
if not group or not group.is_active:
|
||||
run.kb_sync_status = "failed"
|
||||
run.kb_group_id = task.kb_group_id
|
||||
run.kb_sync_error = "目标知识库分组不存在或已停用"
|
||||
return
|
||||
|
||||
title = f"{task.name}_{run.run_no}"
|
||||
actor_id = run.triggered_by_user_id or task.owner_user_id
|
||||
document = _create_kb_document_with_sequence_retry(
|
||||
group_id=group.id,
|
||||
title=title,
|
||||
description=f"排程 {task.name} 运行结果 {run.run_no}",
|
||||
status="uploaded",
|
||||
source_type="schedule",
|
||||
created_by_id=actor_id,
|
||||
updated_by_id=actor_id,
|
||||
)
|
||||
|
||||
version_no = _next_version_no(document)
|
||||
source_file_name = _safe_excel_name(run.excel_file_name or f"{run.run_no}.xlsx")
|
||||
version_dir = _kb_storage_root() / f"group_{group.id:04d}" / f"document_{document.id:06d}" / f"v{version_no:03d}"
|
||||
version_dir.mkdir(parents=True, exist_ok=True)
|
||||
target_path = version_dir / source_file_name
|
||||
target_path.write_bytes(run.excel_file_data)
|
||||
sha256 = hashlib.sha256(run.excel_file_data).hexdigest()
|
||||
file_size = len(run.excel_file_data)
|
||||
|
||||
version = KbDocumentVersion(
|
||||
document_id=document.id,
|
||||
version_no=version_no,
|
||||
status="uploaded",
|
||||
is_current=True,
|
||||
source_file_name=source_file_name,
|
||||
source_file_path=str(target_path),
|
||||
source_file_ext=Path(source_file_name).suffix.lower().lstrip(".") or None,
|
||||
source_file_size=file_size,
|
||||
sha256=sha256,
|
||||
uploaded_by_id=run.triggered_by_user_id or task.owner_user_id,
|
||||
)
|
||||
add_and_flush_with_sequence_retry(version, "kb_document_versions")
|
||||
|
||||
clean_job = KbJob(
|
||||
job_type="clean",
|
||||
status="queued",
|
||||
group_id=group.id,
|
||||
document_id=document.id,
|
||||
document_version_id=version.id,
|
||||
progress=0,
|
||||
message="等待清洗排程结果 Excel",
|
||||
payload_json={
|
||||
"document_version_id": version.id,
|
||||
"source_file_name": source_file_name,
|
||||
"source_type": "schedule_run",
|
||||
"schedule_run_id": run.id,
|
||||
"run_no": run.run_no,
|
||||
"auto_sync_dify": True,
|
||||
},
|
||||
created_by_id=run.triggered_by_user_id or task.owner_user_id,
|
||||
)
|
||||
add_and_flush_with_sequence_retry(clean_job, "kb_jobs")
|
||||
|
||||
run.kb_sync_status = "queued"
|
||||
run.kb_group_id = group.id
|
||||
run.kb_document_id = document.id
|
||||
run.kb_document_version_id = version.id
|
||||
run.kb_sync_job_id = clean_job.id
|
||||
run.kb_sync_error = None
|
||||
db.session.commit()
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[schedule-kb-sync] registered run=%s document_id=%s clean_job_id=%s",
|
||||
run.id,
|
||||
run.kb_document_id,
|
||||
run.kb_sync_job_id,
|
||||
)
|
||||
if process_inline:
|
||||
db.session.refresh(run)
|
||||
process_schedule_kb_jobs_inline(run)
|
||||
else:
|
||||
enqueue_clean_job(clean_job.id)
|
||||
|
||||
|
||||
def _find_pending_sync_job(run: ScheduleRun) -> KbJob | None:
|
||||
from app.models import KbJob
|
||||
|
||||
if run.kb_sync_job_id:
|
||||
job = db.session.get(KbJob, int(run.kb_sync_job_id))
|
||||
if job and job.job_type == "sync_dify" and job.status == "queued":
|
||||
return job
|
||||
if not run.kb_document_id:
|
||||
return None
|
||||
return (
|
||||
db.session.query(KbJob)
|
||||
.filter(
|
||||
KbJob.job_type == "sync_dify",
|
||||
KbJob.document_id == run.kb_document_id,
|
||||
KbJob.status == "queued",
|
||||
)
|
||||
.order_by(KbJob.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def process_schedule_kb_jobs_inline(run: ScheduleRun) -> None:
|
||||
"""
|
||||
同步执行清洗与 Dify 同步。
|
||||
默认在注册 Excel 后立即执行,避免仅 queued 而 worker_kb 未运行导致知识库看不到文档。
|
||||
"""
|
||||
if not run.id:
|
||||
return
|
||||
|
||||
from app.models import KbJob
|
||||
from app.services.knowledge_cleaning.tasks import run_clean_job, run_sync_job
|
||||
|
||||
try:
|
||||
db.session.refresh(run)
|
||||
clean_job_id = run.kb_sync_job_id
|
||||
if not clean_job_id:
|
||||
return
|
||||
|
||||
clean_job = db.session.get(KbJob, int(clean_job_id))
|
||||
if clean_job and clean_job.job_type == "clean" and clean_job.status == "queued":
|
||||
run_clean_job(clean_job.id)
|
||||
db.session.refresh(run)
|
||||
|
||||
sync_job = _find_pending_sync_job(run)
|
||||
if sync_job:
|
||||
run_sync_job(sync_job.id)
|
||||
db.session.refresh(run)
|
||||
|
||||
if run.kb_sync_status in (None, "queued", "cleaning", "syncing"):
|
||||
if run.kb_document_id:
|
||||
run.kb_sync_status = "ready"
|
||||
run.kb_sync_error = None
|
||||
db.session.commit()
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.error(
|
||||
"[schedule-kb-sync] inline process failed for run %s: %s",
|
||||
run.id,
|
||||
exc,
|
||||
exc_info=True,
|
||||
)
|
||||
run.kb_sync_status = "failed"
|
||||
run.kb_sync_error = str(exc)
|
||||
db.session.commit()
|
||||
@@ -1,6 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import func
|
||||
@@ -8,6 +8,15 @@ from sqlalchemy.orm import joinedload
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.response_utils import utc_iso
|
||||
|
||||
|
||||
def _as_naive_utc(dt: datetime | None) -> datetime | None:
|
||||
if dt is None:
|
||||
return None
|
||||
if dt.tzinfo is not None:
|
||||
return dt.astimezone(timezone.utc).replace(tzinfo=None)
|
||||
return dt
|
||||
|
||||
|
||||
def serialize_task(task: ScheduleTask, *, last_status: str | None = None) -> dict:
|
||||
@@ -23,14 +32,16 @@ def serialize_task(task: ScheduleTask, *, last_status: str | None = None) -> dic
|
||||
'dify_agent_id': task.dify_agent_id,
|
||||
'platform_api_path': task.platform_api_path,
|
||||
'data_source_type': task.data_source_type,
|
||||
'kb_sync_enabled': bool(getattr(task, 'kb_sync_enabled', False)),
|
||||
'kb_group_id': getattr(task, 'kb_group_id', None),
|
||||
'notify_user_ids_json': task.notify_user_ids_json or [],
|
||||
'notify_enabled': bool(task.notify_enabled),
|
||||
'enabled': bool(task.enabled),
|
||||
'next_run_at': task.next_run_at.isoformat() if task.next_run_at else None,
|
||||
'last_run_at': task.last_run_at.isoformat() if task.last_run_at else None,
|
||||
'next_run_at': utc_iso(task.next_run_at),
|
||||
'last_run_at': utc_iso(task.last_run_at),
|
||||
'last_status': last_status,
|
||||
'created_at': task.created_at.isoformat() if task.created_at else None,
|
||||
'updated_at': task.updated_at.isoformat() if task.updated_at else None,
|
||||
'created_at': utc_iso(task.created_at),
|
||||
'updated_at': utc_iso(task.updated_at),
|
||||
}
|
||||
|
||||
|
||||
@@ -42,8 +53,8 @@ def serialize_run(run: ScheduleRun) -> dict:
|
||||
'schedule_name': run.task.name if run.task else None,
|
||||
'trigger_type': run.trigger_type,
|
||||
'triggered_by_user_id': run.triggered_by_user_id,
|
||||
'started_at': run.started_at.isoformat() if run.started_at else None,
|
||||
'finished_at': run.finished_at.isoformat() if run.finished_at else None,
|
||||
'started_at': utc_iso(run.started_at),
|
||||
'finished_at': utc_iso(run.finished_at),
|
||||
'duration_ms': run.duration_ms,
|
||||
'status': run.status,
|
||||
'total_count': run.total_count,
|
||||
@@ -58,10 +69,16 @@ def serialize_run(run: ScheduleRun) -> dict:
|
||||
'error_message': run.error_message,
|
||||
'excel_file_name': run.excel_file_name,
|
||||
'excel_file_size': run.excel_file_size,
|
||||
'kb_sync_status': run.kb_sync_status,
|
||||
'kb_group_id': run.kb_group_id,
|
||||
'kb_document_id': run.kb_document_id,
|
||||
'kb_document_version_id': run.kb_document_version_id,
|
||||
'kb_sync_job_id': run.kb_sync_job_id,
|
||||
'kb_sync_error': run.kb_sync_error,
|
||||
'wecom_notified': bool(run.wecom_notified),
|
||||
'wecom_notified_at': run.wecom_notified_at.isoformat() if run.wecom_notified_at else None,
|
||||
'wecom_notified_at': utc_iso(run.wecom_notified_at),
|
||||
'wecom_notify_error': run.wecom_notify_error,
|
||||
'created_at': run.created_at.isoformat() if run.created_at else None,
|
||||
'created_at': utc_iso(run.created_at),
|
||||
}
|
||||
|
||||
|
||||
@@ -104,9 +121,9 @@ def list_runs(
|
||||
if status:
|
||||
query = query.filter(ScheduleRun.status == status)
|
||||
if started_after is not None:
|
||||
query = query.filter(ScheduleRun.started_at >= started_after)
|
||||
query = query.filter(ScheduleRun.started_at >= _as_naive_utc(started_after))
|
||||
if started_before is not None:
|
||||
query = query.filter(ScheduleRun.started_at < started_before)
|
||||
query = query.filter(ScheduleRun.started_at < _as_naive_utc(started_before))
|
||||
if owner_user_id is not None:
|
||||
query = query.filter(ScheduleTask.owner_user_id == owner_user_id)
|
||||
if notify_user_id is not None:
|
||||
|
||||
@@ -211,6 +211,11 @@ def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int |
|
||||
task.platform_api_path = normalize_platform_api_path(payload.get("platform_api_path")) or None
|
||||
if "notify_user_ids_json" in payload and isinstance(payload.get("notify_user_ids_json"), list):
|
||||
task.notify_user_ids_json = payload.get("notify_user_ids_json")
|
||||
if "kb_sync_enabled" in payload:
|
||||
task.kb_sync_enabled = bool(payload.get("kb_sync_enabled"))
|
||||
if "kb_group_id" in payload:
|
||||
raw_group_id = payload.get("kb_group_id")
|
||||
task.kb_group_id = int(raw_group_id) if raw_group_id not in (None, "", 0, "0") else None
|
||||
|
||||
if not normalize_platform_api_path(task.platform_api_path):
|
||||
raise ValueError("platform_api_path is required for platform_app")
|
||||
@@ -334,15 +339,36 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
||||
run.failed_count = failed_count
|
||||
run.skipped_count = skipped_count
|
||||
run.step_logs = step_logs if step_logs else None
|
||||
run.response_summary_json = {
|
||||
response_summary = dict(run.response_summary_json or {})
|
||||
response_summary.update({
|
||||
"errors": errors[:20],
|
||||
"schedule_type": task.schedule_type,
|
||||
"platform_api_path": task.platform_api_path,
|
||||
}
|
||||
})
|
||||
run.response_summary_json = response_summary
|
||||
run.error_message = "; ".join(errors[:3]) if errors else None
|
||||
run.excel_file_data = file_data
|
||||
run.excel_file_name = file_name
|
||||
run.excel_file_size = file_size or 0
|
||||
task.last_run_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
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, process_inline=True)
|
||||
db.session.refresh(run)
|
||||
except Exception as kb_exc:
|
||||
db.session.rollback()
|
||||
db.session.refresh(run)
|
||||
if current_app:
|
||||
current_app.logger.error("[schedule-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:
|
||||
@@ -351,8 +377,6 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
||||
if current_app:
|
||||
current_app.logger.error("[schedule-run] wecom notify failed: %s", wecom_exc)
|
||||
|
||||
task.last_run_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return run
|
||||
|
||||
|
||||
|
||||
@@ -3,9 +3,9 @@ from __future__ import annotations
|
||||
from datetime import datetime
|
||||
from typing import Any, Callable
|
||||
|
||||
from flask import current_app
|
||||
from flask import current_app, has_app_context
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.services.rohs_check import RoHSCheckService
|
||||
|
||||
try:
|
||||
import pyodbc # type: ignore
|
||||
@@ -16,13 +16,31 @@ except Exception: # pragma: no cover
|
||||
def _connect(conn_str: str):
|
||||
if pyodbc is None:
|
||||
raise RuntimeError("pyodbc is not installed")
|
||||
return pyodbc.connect(conn_str, timeout=15)
|
||||
return pyodbc.connect(conn_str, timeout=_sql_timeout_seconds())
|
||||
|
||||
|
||||
def _sql_timeout_seconds() -> int:
|
||||
if not has_app_context():
|
||||
return 15
|
||||
try:
|
||||
value = int(current_app.config.get("SRM_SQLSERVER_TIMEOUT", 15) or 15)
|
||||
except Exception:
|
||||
value = 15
|
||||
return max(1, value)
|
||||
|
||||
|
||||
def _apply_cursor_timeout(cursor) -> None:
|
||||
try:
|
||||
cursor.timeout = _sql_timeout_seconds()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _fetch_records(conn_str: str, sql: str, params: tuple | None = None) -> list[dict[str, Any]]:
|
||||
conn = _connect(conn_str)
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
_apply_cursor_timeout(cur)
|
||||
if params:
|
||||
cur.execute(sql, params)
|
||||
else:
|
||||
@@ -38,6 +56,7 @@ def _execute_writeback(conn_str: str, sql: str, params: tuple) -> None:
|
||||
conn = _connect(conn_str)
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
_apply_cursor_timeout(cur)
|
||||
cur.execute(sql, params)
|
||||
conn.commit()
|
||||
finally:
|
||||
@@ -111,6 +130,16 @@ def _make_step(
|
||||
return entry
|
||||
|
||||
|
||||
def _step_label(step: str) -> str:
|
||||
return {
|
||||
"fetch_srm": "查询待检数据",
|
||||
"pre_dify": "查询成分明细",
|
||||
"call_dify": "调用 Dify 判定",
|
||||
"writeback_srm": "写回 SRM",
|
||||
"completed": "处理完成",
|
||||
}.get(step, step)
|
||||
|
||||
|
||||
def _truncate_str(s: str, max_len: int = _MAX_DIFY_RESPONSE_LEN) -> str:
|
||||
if len(s) <= max_len:
|
||||
return s
|
||||
@@ -154,12 +183,66 @@ def _run_check_job_loop(
|
||||
raise RuntimeError("dify_agent_id is set, but Dify api key is missing")
|
||||
|
||||
step_logs: list[dict[str, Any]] = []
|
||||
details: list[dict[str, Any]] = []
|
||||
success_count = 0
|
||||
failed_count = 0
|
||||
skipped_count = 0
|
||||
judgement_stats = {
|
||||
"qualified_count": 0,
|
||||
"unqualified_count": 0,
|
||||
"manual_count": 0,
|
||||
"dify_error_count": 0,
|
||||
"invalid_result_count": 0,
|
||||
}
|
||||
current_step: dict[str, Any] | None = None
|
||||
all_errors: list[str] = []
|
||||
|
||||
def _save_progress(total: int | None = None) -> None:
|
||||
if run_id is None:
|
||||
return
|
||||
try:
|
||||
from app import db
|
||||
from app.models import ScheduleRun
|
||||
|
||||
progress_run = db.session.get(ScheduleRun, run_id)
|
||||
if not progress_run or progress_run.status != "running":
|
||||
return
|
||||
if total is not None:
|
||||
progress_run.total_count = max(0, int(total))
|
||||
progress_run.success_count = success_count
|
||||
progress_run.failed_count = failed_count
|
||||
progress_run.skipped_count = skipped_count
|
||||
summary = dict(progress_run.response_summary_json or {})
|
||||
summary["rohs_judgement"] = dict(judgement_stats)
|
||||
if current_step:
|
||||
summary["current_step"] = dict(current_step)
|
||||
progress_run.response_summary_json = summary
|
||||
db.session.commit()
|
||||
except Exception as progress_exc:
|
||||
if current_app:
|
||||
current_app.logger.warning("[%s] save progress failed run_id=%s error=%s", log_prefix, run_id, progress_exc)
|
||||
|
||||
def _set_current_step(step: str, row_id: str | None = None, total: int | None = None) -> None:
|
||||
nonlocal current_step
|
||||
current_step = {
|
||||
"step": step,
|
||||
"label": _step_label(step),
|
||||
"row_id": row_id,
|
||||
"started_at": _ts(),
|
||||
"processed_count": success_count + failed_count + skipped_count,
|
||||
"success_count": success_count,
|
||||
"failed_count": failed_count,
|
||||
"skipped_count": skipped_count,
|
||||
}
|
||||
_save_progress(total=total)
|
||||
|
||||
t0 = _ts()
|
||||
try:
|
||||
_set_current_step("fetch_srm")
|
||||
rows = fetch_fn(conn_str)
|
||||
if max_rows > 0:
|
||||
rows = rows[:max_rows]
|
||||
_save_progress(total=len(rows))
|
||||
step_logs.append(_make_step(
|
||||
"fetch_srm",
|
||||
"success",
|
||||
@@ -175,12 +258,6 @@ def _run_check_job_loop(
|
||||
))
|
||||
raise
|
||||
|
||||
details: list[dict[str, Any]] = []
|
||||
success_count = 0
|
||||
failed_count = 0
|
||||
skipped_count = 0
|
||||
all_errors: list[str] = []
|
||||
|
||||
for row in rows:
|
||||
if run_id is not None and is_run_cancelled(run_id):
|
||||
item = dict(row)
|
||||
@@ -192,6 +269,7 @@ def _run_check_job_loop(
|
||||
})
|
||||
skipped_count += 1
|
||||
details.append(item)
|
||||
_save_progress()
|
||||
continue
|
||||
|
||||
item = dict(row)
|
||||
@@ -200,6 +278,7 @@ def _run_check_job_loop(
|
||||
if pre_dify_fn:
|
||||
t_pre = _ts()
|
||||
try:
|
||||
_set_current_step("pre_dify", row_id_value)
|
||||
pre_result = pre_dify_fn(conn_str, item, row_id_value)
|
||||
except Exception as pre_exc:
|
||||
pre_result = {
|
||||
@@ -215,6 +294,7 @@ def _run_check_job_loop(
|
||||
failed_count += 1
|
||||
all_errors.append(pre_result.get("writeback_err", ""))
|
||||
details.append(item)
|
||||
_save_progress()
|
||||
continue
|
||||
|
||||
record_text, attachment_url = build_record_fn(conn_str, item, row_id_value)
|
||||
@@ -235,9 +315,13 @@ def _run_check_job_loop(
|
||||
dify_inputs["system_prompt"] = prompt
|
||||
t_dify = _ts()
|
||||
try:
|
||||
dify_res = DifyService.run_workflow_streaming(
|
||||
_set_current_step("call_dify", row_id_value)
|
||||
dify_res = RoHSCheckService.evaluate(
|
||||
agent=agent,
|
||||
inputs=dify_inputs,
|
||||
run_no=run_no,
|
||||
record=record_text,
|
||||
attachment_url=attachment_url,
|
||||
system_prompt=prompt,
|
||||
user=user,
|
||||
timeout=(5, max(300, int(wait_seconds))),
|
||||
)
|
||||
@@ -251,67 +335,54 @@ def _run_check_job_loop(
|
||||
}))
|
||||
raise
|
||||
|
||||
dify_status = dify_res.get("status") if isinstance(dify_res, dict) else None
|
||||
dify_error = dify_res.get("error") if isinstance(dify_res, dict) else None
|
||||
workflow_run_id = dify_res.get("workflow_run_id") if isinstance(dify_res, dict) else None
|
||||
|
||||
if dify_status == "failed" or (dify_error and not dify_res.get("outputs")):
|
||||
err_detail = str(dify_error) if dify_error else f"Dify status={dify_status}"
|
||||
dify_result = "人工判定"
|
||||
dify_message = f"Dify执行失败:{err_detail}"
|
||||
|
||||
step_logs.append(_make_step("call_dify", "failed", t_dify, _ts(), row_id=row_id_value, detail={
|
||||
"request": {
|
||||
"inputs": _serialize_dify_inputs_for_log(dify_inputs),
|
||||
"agent_id": getattr(agent, "id", None),
|
||||
},
|
||||
"response": _truncate_str(str(dify_res)),
|
||||
"workflow_run_id": workflow_run_id,
|
||||
}))
|
||||
|
||||
item.update({
|
||||
"dify_result": dify_result,
|
||||
"dify_message": dify_message,
|
||||
"writeback_srm": False,
|
||||
"writeback_err": err_detail,
|
||||
})
|
||||
failed_count += 1
|
||||
all_errors.append(f"Dify {log_prefix}={row_id_value}: {err_detail}")
|
||||
details.append(item)
|
||||
continue
|
||||
dify_result, dify_message = _derive_dify_result_and_message(dify_res if isinstance(dify_res, dict) else {})
|
||||
dify_ok = True
|
||||
if dify_result == "合格":
|
||||
judgement_stats["qualified_count"] += 1
|
||||
elif dify_result == "不合格":
|
||||
judgement_stats["unqualified_count"] += 1
|
||||
else:
|
||||
outputs = (dify_res.get("outputs") or {}).get("output") or dify_res.get("outputs") or dify_res
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[%s] %s=%s dify_result=%s dify_message=%s",
|
||||
log_prefix, log_prefix, row_id_value,
|
||||
(outputs.get("dify_result") or outputs.get("result")) if isinstance(outputs, dict) else None,
|
||||
(outputs.get("dify_message") or outputs.get("message")) if isinstance(outputs, dict) else None,
|
||||
)
|
||||
dify_result, dify_message = _derive_dify_result_and_message(outputs if isinstance(outputs, dict) else {})
|
||||
dify_ok = True
|
||||
judgement_stats["manual_count"] += 1
|
||||
if dify_error:
|
||||
judgement_stats["dify_error_count"] += 1
|
||||
raw_outputs = dify_res.get("raw_outputs") if isinstance(dify_res, dict) else None
|
||||
if dify_result == "人工判定" and isinstance(raw_outputs, dict) and not dify_error:
|
||||
raw_result = str(raw_outputs.get("dify_result") or raw_outputs.get("result") or "").strip()
|
||||
if raw_result and raw_result not in {"合格", "不合格", "人工判定"}:
|
||||
judgement_stats["invalid_result_count"] += 1
|
||||
|
||||
step_logs.append(_make_step("call_dify", "success", t_dify, _ts(), row_id=row_id_value, detail={
|
||||
"request": {
|
||||
"inputs": _serialize_dify_inputs_for_log(dify_inputs),
|
||||
"agent_id": getattr(agent, "id", None),
|
||||
},
|
||||
"response": {
|
||||
"status": dify_status,
|
||||
"dify_result": dify_result,
|
||||
"dify_message": _truncate_str(dify_message),
|
||||
"workflow_run_id": workflow_run_id,
|
||||
},
|
||||
}))
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[%s] %s=%s dify_result=%s dify_message=%s",
|
||||
log_prefix, log_prefix, row_id_value, dify_result, dify_message,
|
||||
)
|
||||
|
||||
step_logs.append(_make_step("call_dify", "success", t_dify, _ts(), row_id=row_id_value, detail={
|
||||
"request": {
|
||||
"inputs": _serialize_dify_inputs_for_log(dify_inputs),
|
||||
"agent_id": getattr(agent, "id", None),
|
||||
},
|
||||
"response": {
|
||||
"provider": dify_res.get("provider") if isinstance(dify_res, dict) else None,
|
||||
"dify_result": dify_result,
|
||||
"dify_message": _truncate_str(dify_message),
|
||||
"workflow_run_id": workflow_run_id,
|
||||
"error": dify_error,
|
||||
},
|
||||
}))
|
||||
else:
|
||||
dify_result = "人工判定"
|
||||
dify_message = "未配置 Agent ID,跳过 Dify"
|
||||
dify_ok = True
|
||||
judgement_stats["manual_count"] += 1
|
||||
|
||||
wb_sql = writeback_sql
|
||||
wb_params = (run_no, dify_result, dify_message, str(row_id_value))
|
||||
t_wb = _ts()
|
||||
try:
|
||||
_set_current_step("writeback_srm", row_id_value)
|
||||
writeback_fn(conn_str, row_id=row_id_value, run_no=run_no, dify_result=dify_result, dify_message=dify_message)
|
||||
step_logs.append(_make_step("writeback_srm", "success", t_wb, _ts(), row_id=row_id_value, detail={
|
||||
"sql": _truncate_str(wb_sql, 500),
|
||||
@@ -355,6 +426,7 @@ def _run_check_job_loop(
|
||||
all_errors.append(str(exc))
|
||||
t_wb2 = _ts()
|
||||
try:
|
||||
_set_current_step("writeback_srm", row_id_value)
|
||||
writeback_fn(conn_str, row_id=row_id_value, run_no=run_no, dify_result=dify_result, dify_message=dify_message)
|
||||
step_logs.append(_make_step("writeback_srm", "success", t_wb2, _ts(), row_id=row_id_value, detail={"note": "fallback writeback after dify error"}))
|
||||
item["writeback_srm"] = True
|
||||
@@ -364,9 +436,11 @@ def _run_check_job_loop(
|
||||
item["writeback_err"] = f"{item.get('writeback_err', '')}; writeback failed: {wb_exc}"
|
||||
|
||||
details.append(item)
|
||||
_save_progress()
|
||||
|
||||
if len(step_logs) > _MAX_STEP_LOGS_PER_ROW:
|
||||
step_logs = step_logs[:_MAX_STEP_LOGS_PER_ROW]
|
||||
|
||||
_set_current_step("completed")
|
||||
total_count = success_count + failed_count + skipped_count
|
||||
return total_count, success_count, failed_count, skipped_count, details, all_errors, step_logs
|
||||
@@ -6,7 +6,7 @@ from app.services.shipping_notice.agent_resolver import CHAT_AGENT_NAME
|
||||
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||
|
||||
# Dify Chatflow input variable names — must match canvas Start / 输入变量配置.
|
||||
HXOPS_TOOL_API_BASE_INPUT = "hxops_tool_api_base"
|
||||
HXOPS_TOOLS_API_BASE_INPUT = "HXOPS_TOOLS_API_BASE"
|
||||
HXOPS_TOOL_API_KEY_INPUT = "hxops_tool_api_key"
|
||||
|
||||
|
||||
@@ -20,7 +20,8 @@ def build_dify_chat_inputs() -> dict[str, str]:
|
||||
key = str(current_app.config.get("SHIPPING_NOTICE_TOOL_API_KEY") or "").strip()
|
||||
inputs: dict[str, str] = {}
|
||||
if base:
|
||||
inputs[HXOPS_TOOL_API_BASE_INPUT] = base
|
||||
inputs[HXOPS_TOOLS_API_BASE_INPUT] = base
|
||||
if key:
|
||||
inputs[HXOPS_TOOL_API_KEY_INPUT] = key
|
||||
return inputs
|
||||
|
||||
@@ -81,6 +81,7 @@ def format_parse_summary(
|
||||
lines: list[dict[str, Any]] | None = None,
|
||||
warnings: list[Any] | None = None,
|
||||
low_confidence: bool = False,
|
||||
include_confirmation_hint: bool = True,
|
||||
lang: str | None = None,
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> str:
|
||||
@@ -141,10 +142,11 @@ def format_parse_summary(
|
||||
parts.append("")
|
||||
if low_confidence:
|
||||
parts.append(t("parse.low_conf", lang=resolved))
|
||||
parts.append(t("parse.confirm", lang=resolved))
|
||||
parts.append(t("parse.hint", lang=resolved))
|
||||
hint_btn = t("parse.hint_btn", lang=resolved).strip()
|
||||
if hint_btn:
|
||||
parts.append(hint_btn)
|
||||
if include_confirmation_hint:
|
||||
parts.append(t("parse.confirm", lang=resolved))
|
||||
parts.append(t("parse.hint", lang=resolved))
|
||||
hint_btn = t("parse.hint_btn", lang=resolved).strip()
|
||||
if hint_btn:
|
||||
parts.append(hint_btn)
|
||||
|
||||
return "\n".join(parts).strip()
|
||||
@@ -1,24 +1,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import current_app, has_request_context, request
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
|
||||
|
||||
|
||||
def resolve_tool_api_base_url(*, config: dict | None = None, request_host: str | None = None) -> str:
|
||||
"""Resolve hxops Tool API base URL (…/api/shipping-notice, no trailing slash)."""
|
||||
cfg = config
|
||||
if cfg is None and current_app:
|
||||
cfg = current_app.config
|
||||
cfg = cfg or {}
|
||||
|
||||
configured = str(cfg.get("SHIPPING_NOTICE_TOOL_API_BASE") or "").strip().rstrip("/")
|
||||
if configured:
|
||||
return configured
|
||||
|
||||
configured = str(cfg.get("PUBLIC_BASE_URL") or "").strip().rstrip("/")
|
||||
if configured:
|
||||
return configured
|
||||
|
||||
host = request_host
|
||||
if host is None and has_request_context():
|
||||
host = request.host_url.rstrip("/")
|
||||
return host or ""
|
||||
"""Resolve hxops Tool API root URL (no trailing slash)."""
|
||||
return resolve_HXOPS_TOOLS_API_BASE(config=config, request_host=request_host)
|
||||
@@ -760,15 +760,20 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
apply_task_transition(task, TaskTransition.PARSED)
|
||||
_log_event(task, "parsed", {"confidence": confidence, "warnings": warnings})
|
||||
db.session.commit()
|
||||
summary_text = format_parse_summary(**summary_kwargs, payload=payload)
|
||||
|
||||
auto_threshold = float(current_app.config.get("SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE") or 0.8)
|
||||
if confidence >= auto_threshold and not task.inventory_lines_json:
|
||||
should_auto_continue = confidence >= auto_threshold and not task.inventory_lines_json
|
||||
summary_text = format_parse_summary(
|
||||
**summary_kwargs,
|
||||
payload=payload,
|
||||
include_confirmation_hint=not should_auto_continue,
|
||||
)
|
||||
|
||||
if should_auto_continue:
|
||||
lang = payload.get("lang") if isinstance(payload, dict) else None
|
||||
auto_payload: dict[str, Any] = {"task_id": task.task_no, "mode": "auto"}
|
||||
if lang:
|
||||
auto_payload["lang"] = lang
|
||||
auto_result = ensure_inventory(auto_payload)
|
||||
auto_result = auto_progress(auto_payload) if _auto_progress_enabled() else ensure_inventory(auto_payload)
|
||||
msg = str(auto_result.get("message") or "").strip()
|
||||
merged_message = summary_text if not msg else f"{summary_text}\n\n{msg}"
|
||||
merged_data = {}
|
||||
@@ -1583,7 +1588,10 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
_log_event(task, "parse_confirmed", {"comment": comment})
|
||||
db.session.commit()
|
||||
if (not task.inventory_lines_json) and (not has_uploaded_task_inventory(task.task_no)):
|
||||
return ensure_inventory({"task_id": task.task_no, "mode": "auto"})
|
||||
next_payload = _merge_tool_payload(task, payload, extra={"mode": "auto"})
|
||||
if _payload_wants_auto_chain_fallback(payload):
|
||||
return auto_progress(next_payload)
|
||||
return ensure_inventory(next_payload)
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
@@ -1609,6 +1617,29 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
data=_serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
if task.process_status == "waiting_inventory" or (
|
||||
task.pending_human_reason == PH_RPA_PENDING and not task.inventory_lines_json
|
||||
):
|
||||
follow_payload = _merge_tool_payload(task, payload, extra={"mode": "auto"})
|
||||
if _payload_wants_auto_chain_fallback(payload):
|
||||
return auto_progress(follow_payload)
|
||||
return ensure_inventory(follow_payload)
|
||||
|
||||
if _awaiting_inventory_mapping_confirm(task):
|
||||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
|
||||
return _inventory_mapping_checkpoint_response(task, lang=lang or None)
|
||||
|
||||
if task.inventory_lines_json or task.process_status == "inventory_ready":
|
||||
follow_payload = _merge_tool_payload(task, payload)
|
||||
if _payload_wants_auto_chain_fallback(payload):
|
||||
return auto_progress(follow_payload)
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message="发货通知已确认,当前任务已进入库存处理阶段,请按当前按钮继续。",
|
||||
data=_serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
|
||||
+1031
-51
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,244 @@
|
||||
"""
|
||||
backend/app/services/wecom_directory_sync.py
|
||||
|
||||
用途:从企业微信通讯录拉取成员,按工号回填本地 users.wecom_userid。
|
||||
依赖:Flask current_app、SQLAlchemy db、wecom_notify._get_access_token、User 模型。
|
||||
逻辑:供 admin API 与 scripts/sync_wecom_userid_by_employee_id.py 共用;支持 dry-run 与 apply。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.services.wecom_notify import _get_access_token
|
||||
|
||||
_PREVIEW_LIMIT = 20
|
||||
|
||||
|
||||
def _clean_str(value) -> str | None:
|
||||
"""Trim string-like values; empty strings become None."""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
|
||||
|
||||
def _extract_wecom_extattr_value(wecom_user: dict, key: str) -> str | None:
|
||||
"""
|
||||
从企微成员 extattr.attrs 中读取指定扩展字段。
|
||||
@param wecom_user: user/list 返回的成员 dict
|
||||
@param key: 扩展属性名
|
||||
Returns:
|
||||
字段文本或 None
|
||||
"""
|
||||
extattr = wecom_user.get('extattr') or {}
|
||||
attrs = extattr.get('attrs') if isinstance(extattr, dict) else None
|
||||
if not isinstance(attrs, list):
|
||||
return None
|
||||
for attr in attrs:
|
||||
if not isinstance(attr, dict):
|
||||
continue
|
||||
if _clean_str(attr.get('name')) != key:
|
||||
continue
|
||||
raw = attr.get('value')
|
||||
if isinstance(raw, dict):
|
||||
raw = raw.get('text') or raw.get('web') or raw.get('value')
|
||||
return _clean_str(raw)
|
||||
return None
|
||||
|
||||
|
||||
def extract_employee_id_from_wecom_user(wecom_user: dict, employee_id_source: str) -> str | None:
|
||||
"""
|
||||
按 WECOM_EMPLOYEE_ID_SOURCE 从企微成员解析工号。
|
||||
核心逻辑:userid / extattr:xxx / 其它字段名,与 user.py _extract_wecom_identity 对齐。
|
||||
"""
|
||||
userid = _clean_str(wecom_user.get('userid'))
|
||||
source = _clean_str(employee_id_source) or 'userid'
|
||||
if source == 'userid':
|
||||
return userid
|
||||
if source.startswith('extattr:'):
|
||||
return _extract_wecom_extattr_value(wecom_user, source.split(':', 1)[1])
|
||||
return _clean_str(wecom_user.get(source))
|
||||
|
||||
|
||||
def fetch_wecom_departments(access_token: str) -> list[dict[str, Any]]:
|
||||
"""
|
||||
拉取企业微信部门列表。
|
||||
Raises:
|
||||
RuntimeError: API 失败
|
||||
"""
|
||||
resp = requests.get(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/department/list',
|
||||
params={'access_token': access_token},
|
||||
timeout=15,
|
||||
)
|
||||
data = resp.json() or {}
|
||||
if data.get('errcode') != 0:
|
||||
raise RuntimeError(f'department/list failed: {data}')
|
||||
departments = data.get('department') or []
|
||||
if not isinstance(departments, list):
|
||||
return []
|
||||
return [item for item in departments if isinstance(item, dict)]
|
||||
|
||||
|
||||
def fetch_wecom_users_in_department(access_token: str, department_id: int) -> list[dict[str, Any]]:
|
||||
"""
|
||||
拉取指定部门(含子部门)成员简要列表。
|
||||
@param department_id: 企微部门 ID
|
||||
Returns:
|
||||
user/list 返回的 userlist
|
||||
"""
|
||||
resp = requests.get(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/user/list',
|
||||
params={
|
||||
'access_token': access_token,
|
||||
'department_id': department_id,
|
||||
'fetch_child': 1,
|
||||
},
|
||||
timeout=30,
|
||||
)
|
||||
data = resp.json() or {}
|
||||
if data.get('errcode') != 0:
|
||||
raise RuntimeError(f'user/list failed department_id={department_id}: {data}')
|
||||
userlist = data.get('userlist') or []
|
||||
if not isinstance(userlist, list):
|
||||
return []
|
||||
return [item for item in userlist if isinstance(item, dict)]
|
||||
|
||||
|
||||
def collect_wecom_users(access_token: str, department_ids: list[int]) -> dict[str, dict[str, Any]]:
|
||||
"""
|
||||
汇总多个部门成员,按 wecom_userid 去重。
|
||||
Returns:
|
||||
key=userid, value=成员 dict
|
||||
"""
|
||||
merged: dict[str, dict[str, Any]] = {}
|
||||
for dept_id in department_ids:
|
||||
for user in fetch_wecom_users_in_department(access_token, dept_id):
|
||||
userid = _clean_str(user.get('userid'))
|
||||
if userid:
|
||||
merged[userid] = user
|
||||
return merged
|
||||
|
||||
|
||||
def sync_wecom_userids_from_directory(*, apply: bool, department_id: int | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
执行工号 → wecom_userid 同步。
|
||||
核心逻辑:拉企微成员 → 解析 employee_id → 匹配本地 User → dry-run 或写 wecom_userid/wecom_unionid。
|
||||
@param apply: True 时提交数据库;存在 conflicts 时不写入
|
||||
@param department_id: 指定根部门 ID;None 时使用全部部门
|
||||
Returns:
|
||||
统计摘要 dict(含 conflicts、pending_updates 预览)
|
||||
"""
|
||||
if not current_app.config.get('WECOM_CORP_ID') or not current_app.config.get('WECOM_SECRET'):
|
||||
raise RuntimeError('WECOM_CORP_ID / WECOM_SECRET is not configured')
|
||||
|
||||
employee_id_source = _clean_str(current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE')) or 'userid'
|
||||
token = _get_access_token()
|
||||
|
||||
if department_id is not None:
|
||||
department_ids = [department_id]
|
||||
else:
|
||||
departments = fetch_wecom_departments(token)
|
||||
department_ids = [int(item.get('id')) for item in departments if item.get('id') is not None]
|
||||
if not department_ids:
|
||||
department_ids = [1]
|
||||
|
||||
wecom_users = collect_wecom_users(token, department_ids)
|
||||
summary: dict[str, Any] = {
|
||||
'apply': apply,
|
||||
'employee_id_source': employee_id_source,
|
||||
'department_ids': department_ids,
|
||||
'wecom_users': len(wecom_users),
|
||||
'wecom_without_employee_id': 0,
|
||||
'local_matched': 0,
|
||||
'would_update': 0,
|
||||
'updated': 0,
|
||||
'already_bound': 0,
|
||||
'local_missing': 0,
|
||||
'conflicts': [],
|
||||
'missing_samples': [],
|
||||
'pending_updates': [],
|
||||
}
|
||||
|
||||
for wecom_user in wecom_users.values():
|
||||
wecom_userid = _clean_str(wecom_user.get('userid'))
|
||||
wecom_unionid = _clean_str(wecom_user.get('unionid'))
|
||||
employee_id = extract_employee_id_from_wecom_user(wecom_user, employee_id_source)
|
||||
if not employee_id:
|
||||
summary['wecom_without_employee_id'] += 1
|
||||
if len(summary['missing_samples']) < _PREVIEW_LIMIT:
|
||||
summary['missing_samples'].append(
|
||||
{'wecom_userid': wecom_userid, 'name': _clean_str(wecom_user.get('name'))}
|
||||
)
|
||||
continue
|
||||
|
||||
local_user = db.session.query(User).filter(User.employee_id == employee_id).first()
|
||||
if not local_user:
|
||||
summary['local_missing'] += 1
|
||||
continue
|
||||
|
||||
summary['local_matched'] += 1
|
||||
|
||||
if local_user.wecom_userid == wecom_userid:
|
||||
summary['already_bound'] += 1
|
||||
continue
|
||||
|
||||
conflict = None
|
||||
if local_user.wecom_userid and local_user.wecom_userid != wecom_userid:
|
||||
conflict = {
|
||||
'employee_id': employee_id,
|
||||
'username': local_user.username,
|
||||
'old_wecom_userid': local_user.wecom_userid,
|
||||
'new_wecom_userid': wecom_userid,
|
||||
}
|
||||
else:
|
||||
occupied = (
|
||||
db.session.query(User)
|
||||
.filter(User.wecom_userid == wecom_userid, User.id != local_user.id)
|
||||
.first()
|
||||
)
|
||||
if occupied:
|
||||
conflict = {
|
||||
'employee_id': employee_id,
|
||||
'username': local_user.username,
|
||||
'new_wecom_userid': wecom_userid,
|
||||
'occupied_by_user_id': occupied.id,
|
||||
'occupied_by_username': occupied.username,
|
||||
}
|
||||
|
||||
if conflict:
|
||||
summary['conflicts'].append(conflict)
|
||||
continue
|
||||
|
||||
summary['would_update'] += 1
|
||||
if len(summary['pending_updates']) < _PREVIEW_LIMIT:
|
||||
summary['pending_updates'].append(
|
||||
{
|
||||
'employee_id': employee_id,
|
||||
'username': local_user.username,
|
||||
'wecom_userid': wecom_userid,
|
||||
'name': _clean_str(wecom_user.get('name')),
|
||||
}
|
||||
)
|
||||
if apply:
|
||||
local_user.wecom_userid = wecom_userid
|
||||
if wecom_unionid:
|
||||
local_user.wecom_unionid = wecom_unionid
|
||||
summary['updated'] += 1
|
||||
|
||||
if summary['conflicts'] and apply:
|
||||
db.session.rollback()
|
||||
raise RuntimeError('Conflicts detected; resolve manually before apply')
|
||||
|
||||
if apply and summary['updated'] > 0:
|
||||
db.session.commit()
|
||||
elif apply:
|
||||
db.session.rollback()
|
||||
|
||||
return summary
|
||||
@@ -27,8 +27,22 @@ def _get_enabled_events() -> set[str]:
|
||||
return set()
|
||||
|
||||
|
||||
def _get_notify_base_url() -> str:
|
||||
"""
|
||||
解析企微 textcard 跳转基地址。
|
||||
核心逻辑:优先 WECOM_NOTIFY_BASE_URL,其次 WECOM_PUBLIC_BASE_URL。
|
||||
Returns:
|
||||
去掉尾斜杠的基地址;均未配置时返回空字符串。
|
||||
"""
|
||||
for key in ('WECOM_NOTIFY_BASE_URL', 'WECOM_PUBLIC_BASE_URL'):
|
||||
raw = current_app.config.get(key)
|
||||
if isinstance(raw, str) and raw.strip():
|
||||
return raw.strip().rstrip('/')
|
||||
return ''
|
||||
|
||||
|
||||
def _build_jump_url(path: str, trace_id: str, params: dict | None = None) -> str:
|
||||
base = current_app.config.get('WECOM_NOTIFY_BASE_URL') or ''
|
||||
base = _get_notify_base_url()
|
||||
if not base:
|
||||
return ''
|
||||
base = base.rstrip('/')
|
||||
@@ -133,7 +147,7 @@ def send_wecom_textcard_message(
|
||||
'textcard': {
|
||||
'title': title[:120],
|
||||
'description': (description or '')[:1024],
|
||||
'url': jump_url or (current_app.config.get('WECOM_NOTIFY_BASE_URL') or 'https://work.weixin.qq.com'),
|
||||
'url': jump_url or _get_notify_base_url() or 'https://work.weixin.qq.com',
|
||||
'btntxt': '查看详情',
|
||||
},
|
||||
'safe': 0,
|
||||
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,4 @@
|
||||
source_file=su_schedule_4.xlsx
|
||||
source_size=5980
|
||||
clean_status=placeholder_success
|
||||
fallback_reason=No module named 'pydantic'
|
||||
@@ -0,0 +1,5 @@
|
||||
su_schedule_5
|
||||
## Sheet: result
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=PC6842;材质名称=标签;第三方编码=SHAEC25020186401;检测项目=RoHS十项+卤素;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2025-08-14 00:00:00;报告有效截止日期=2026-08-14 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/本色磨砂PC-有害物质报告-20250814-英文_1779086818095.pdf;chm_id=17790867106401639770;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101008E;检测项目=卤素;铅(Pb)=NA;镉(Cd)=NA;汞(Hg)=NA;六价铬(Cr6+)=NA;多溴联苯(PBBs)=NA;多溴二苯醚(PBDEs)=NA;邻苯二甲酸二丁酯(DBP)=NA;邻苯二甲酸丁苄酯(BBP)=NA;邻苯二甲酸二(2-乙基己)酯(DEHP)=NA;邻苯二甲酸二异丁酯(DIBP)=NA;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色HF_1774832573760.pdf;chm_id=17790869056412507491;检核结果=合格;检核说明=;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101001E;检测项目=RoHS十项;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=NA;溴(Br)=NA;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色ROHS_1774832608199.pdf;chm_id=17790870063173449273;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
@@ -0,0 +1,5 @@
|
||||
su_schedule_5
|
||||
## Sheet: result
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=PC6842;材质名称=标签;第三方编码=SHAEC25020186401;检测项目=RoHS十项+卤素;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2025-08-14 00:00:00;报告有效截止日期=2026-08-14 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/本色磨砂PC-有害物质报告-20250814-英文_1779086818095.pdf;chm_id=17790867106401639770;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101008E;检测项目=卤素;铅(Pb)=NA;镉(Cd)=NA;汞(Hg)=NA;六价铬(Cr6+)=NA;多溴联苯(PBBs)=NA;多溴二苯醚(PBDEs)=NA;邻苯二甲酸二丁酯(DBP)=NA;邻苯二甲酸丁苄酯(BBP)=NA;邻苯二甲酸二(2-乙基己)酯(DEHP)=NA;邻苯二甲酸二异丁酯(DIBP)=NA;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色HF_1774832573760.pdf;chm_id=17790869056412507491;检核结果=合格;检核说明=;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101001E;检测项目=RoHS十项;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=NA;溴(Br)=NA;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色ROHS_1774832608199.pdf;chm_id=17790870063173449273;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
Binary file not shown.
@@ -0,0 +1,4 @@
|
||||
source_file=su_schedule_5.xlsx
|
||||
source_size=5980
|
||||
clean_status=placeholder_success
|
||||
fallback_reason=[Errno 1] Operation not permitted
|
||||
@@ -0,0 +1,5 @@
|
||||
su_schedule_5
|
||||
## Sheet: result
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=PC6842;材质名称=标签;第三方编码=SHAEC25020186401;检测项目=RoHS十项+卤素;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2025-08-14 00:00:00;报告有效截止日期=2026-08-14 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/本色磨砂PC-有害物质报告-20250814-英文_1779086818095.pdf;chm_id=17790867106401639770;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101008E;检测项目=卤素;铅(Pb)=NA;镉(Cd)=NA;汞(Hg)=NA;六价铬(Cr6+)=NA;多溴联苯(PBBs)=NA;多溴二苯醚(PBDEs)=NA;邻苯二甲酸二丁酯(DBP)=NA;邻苯二甲酸丁苄酯(BBP)=NA;邻苯二甲酸二(2-乙基己)酯(DEHP)=NA;邻苯二甲酸二异丁酯(DIBP)=NA;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色HF_1774832573760.pdf;chm_id=17790869056412507491;检核结果=合格;检核说明=;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101001E;检测项目=RoHS十项;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=NA;溴(Br)=NA;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色ROHS_1774832608199.pdf;chm_id=17790870063173449273;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
@@ -0,0 +1,5 @@
|
||||
su_schedule_5
|
||||
## Sheet: result
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=PC6842;材质名称=标签;第三方编码=SHAEC25020186401;检测项目=RoHS十项+卤素;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2025-08-14 00:00:00;报告有效截止日期=2026-08-14 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/本色磨砂PC-有害物质报告-20250814-英文_1779086818095.pdf;chm_id=17790867106401639770;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101008E;检测项目=卤素;铅(Pb)=NA;镉(Cd)=NA;汞(Hg)=NA;六价铬(Cr6+)=NA;多溴联苯(PBBs)=NA;多溴二苯醚(PBDEs)=NA;邻苯二甲酸二丁酯(DBP)=NA;邻苯二甲酸丁苄酯(BBP)=NA;邻苯二甲酸二(2-乙基己)酯(DEHP)=NA;邻苯二甲酸二异丁酯(DIBP)=NA;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色HF_1774832573760.pdf;chm_id=17790869056412507491;检核结果=合格;检核说明=;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101001E;检测项目=RoHS十项;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=NA;溴(Br)=NA;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色ROHS_1774832608199.pdf;chm_id=17790870063173449273;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
@@ -0,0 +1,5 @@
|
||||
su_schedule_5
|
||||
## Sheet: result
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=PC6842;材质名称=标签;第三方编码=SHAEC25020186401;检测项目=RoHS十项+卤素;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2025-08-14 00:00:00;报告有效截止日期=2026-08-14 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/本色磨砂PC-有害物质报告-20250814-英文_1779086818095.pdf;chm_id=17790867106401639770;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101008E;检测项目=卤素;铅(Pb)=NA;镉(Cd)=NA;汞(Hg)=NA;六价铬(Cr6+)=NA;多溴联苯(PBBs)=NA;多溴二苯醚(PBDEs)=NA;邻苯二甲酸二丁酯(DBP)=NA;邻苯二甲酸丁苄酯(BBP)=NA;邻苯二甲酸二(2-乙基己)酯(DEHP)=NA;邻苯二甲酸二异丁酯(DIBP)=NA;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色HF_1774832573760.pdf;chm_id=17790869056412507491;检核结果=合格;检核说明=;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101001E;检测项目=RoHS十项;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=NA;溴(Br)=NA;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色ROHS_1774832608199.pdf;chm_id=17790870063173449273;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
@@ -0,0 +1,5 @@
|
||||
su_schedule_6
|
||||
## Sheet: result
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=PC6842;材质名称=标签;第三方编码=SHAEC25020186401;检测项目=RoHS十项+卤素;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2025-08-14 00:00:00;报告有效截止日期=2026-08-14 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/本色磨砂PC-有害物质报告-20250814-英文_1779086818095.pdf;chm_id=17790867106401639770;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101008E;检测项目=卤素;铅(Pb)=NA;镉(Cd)=NA;汞(Hg)=NA;六价铬(Cr6+)=NA;多溴联苯(PBBs)=NA;多溴二苯醚(PBDEs)=NA;邻苯二甲酸二丁酯(DBP)=NA;邻苯二甲酸丁苄酯(BBP)=NA;邻苯二甲酸二(2-乙基己)酯(DEHP)=NA;邻苯二甲酸二异丁酯(DIBP)=NA;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色HF_1774832573760.pdf;chm_id=17790869056412507491;检核结果=合格;检核说明=;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101001E;检测项目=RoHS十项;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=NA;溴(Br)=NA;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色ROHS_1774832608199.pdf;chm_id=17790870063173449273;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
Binary file not shown.
@@ -0,0 +1,5 @@
|
||||
su_schedule_7
|
||||
## Sheet: result
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=PC6842;材质名称=标签;第三方编码=SHAEC25020186401;检测项目=RoHS十项+卤素;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2025-08-14 00:00:00;报告有效截止日期=2026-08-14 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/本色磨砂PC-有害物质报告-20250814-英文_1779086818095.pdf;chm_id=17790867106401639770;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101008E;检测项目=卤素;铅(Pb)=NA;镉(Cd)=NA;汞(Hg)=NA;六价铬(Cr6+)=NA;多溴联苯(PBBs)=NA;多溴二苯醚(PBDEs)=NA;邻苯二甲酸二丁酯(DBP)=NA;邻苯二甲酸丁苄酯(BBP)=NA;邻苯二甲酸二(2-乙基己)酯(DEHP)=NA;邻苯二甲酸二异丁酯(DIBP)=NA;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色HF_1774832573760.pdf;chm_id=17790869056412507491;检核结果=合格;检核说明=;回写SRM=True;回写错误=。
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101001E;检测项目=RoHS十项;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=NA;溴(Br)=NA;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色ROHS_1774832608199.pdf;chm_id=17790870063173449273;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
|
||||
Binary file not shown.
@@ -235,6 +235,8 @@ def _normalize_path_for_match(p: Path | str) -> str:
|
||||
|
||||
|
||||
_WORD_TIMEOUT_EXTS = {".doc", ".docx"}
|
||||
# Excel/CSV are fast and in-process; skip spawn timeout wrapper (macOS/gevent safe).
|
||||
_FAST_PATH_EXTS = {".xlsx", ".xls", ".csv", ".txt", ".md"}
|
||||
|
||||
|
||||
def _parse_timeout_env(name: str, default: str = "0") -> int | None:
|
||||
@@ -248,6 +250,8 @@ def _parse_timeout_env(name: str, default: str = "0") -> int | None:
|
||||
|
||||
def _file_timeout_sec(file_path: Path | None = None) -> int | None:
|
||||
suffix = str(getattr(file_path, "suffix", "") or "").lower()
|
||||
if suffix in _FAST_PATH_EXTS:
|
||||
return None
|
||||
if suffix in _WORD_TIMEOUT_EXTS:
|
||||
specific = _parse_timeout_env("EDKB_WORD_FILE_TIMEOUT_SEC")
|
||||
if specific:
|
||||
|
||||
@@ -9,17 +9,39 @@ from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from openpyxl import load_workbook
|
||||
from openpyxl import load_workbook, Workbook
|
||||
|
||||
from edkb_system.contracts import Context
|
||||
from edkb_system.skills.soffice_util import convert_with_soffice, soffice_candidates
|
||||
from edkb_system.skills.excel_bridge import convert_with_excel
|
||||
|
||||
|
||||
def _convert_xls_to_xlsx_python(path: Path, output: Path) -> Path:
|
||||
"""使用 xlrd 和 openpyxl 进行纯 Python 转换。"""
|
||||
import xlrd
|
||||
|
||||
book = xlrd.open_workbook(str(path))
|
||||
wb = Workbook()
|
||||
wb.remove(wb.active) # 移除默认的 Sheet
|
||||
|
||||
for i in range(book.nsheets):
|
||||
sheet = book.sheet_by_index(i)
|
||||
new_ws = wb.create_sheet(title=sheet.name)
|
||||
for row in range(sheet.nrows):
|
||||
# 将 xlrd 的行值(list)追加到 openpyxl 的 sheet 中
|
||||
new_ws.append(sheet.row_values(row))
|
||||
|
||||
wb.save(str(output))
|
||||
return output
|
||||
|
||||
|
||||
def _convert_xls_to_xlsx(path: Path, out_dir: Path) -> Path:
|
||||
"""将 .xls 转为 .xlsx;soffice 调用带超时,见 EDKB_SOFFICE_TIMEOUT_SEC。"""
|
||||
"""将 .xls 转为 .xlsx。依次尝试 soffice、Excel COM 和 xlrd。"""
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
output = out_dir / f"{path.stem}.xlsx"
|
||||
errors: list[str] = []
|
||||
|
||||
# 1. 尝试 LibreOffice (soffice)
|
||||
for soffice in soffice_candidates():
|
||||
if not soffice:
|
||||
continue
|
||||
@@ -30,22 +52,31 @@ def _convert_xls_to_xlsx(path: Path, out_dir: Path) -> Path:
|
||||
source_path=path,
|
||||
out_dir=out_dir,
|
||||
)
|
||||
except FileNotFoundError:
|
||||
errors.append(f"soffice not found: {soffice}")
|
||||
continue
|
||||
except RuntimeError as exc:
|
||||
errors.append(str(exc))
|
||||
continue
|
||||
if proc.returncode == 0 and output.exists():
|
||||
return output
|
||||
stderr = (proc.stderr or "").strip()
|
||||
errors.append(
|
||||
f"soffice failed ({soffice}, code={proc.returncode}): {stderr or 'no stderr'}"
|
||||
)
|
||||
if proc.returncode == 0 and output.exists():
|
||||
return output
|
||||
stderr = (proc.stderr or "").strip()
|
||||
errors.append(
|
||||
f"soffice failed ({soffice}, code={proc.returncode}): {stderr or 'no stderr'}"
|
||||
)
|
||||
except Exception as exc:
|
||||
errors.append(f"soffice attempt failed ({soffice}): {exc}")
|
||||
|
||||
# 2. Windows 环境下尝试 Excel COM
|
||||
if os.name == "nt":
|
||||
try:
|
||||
return convert_with_excel(path, output)
|
||||
except Exception as exc:
|
||||
errors.append(f"Excel COM conversion failed: {exc}")
|
||||
|
||||
# 3. 最后尝试纯 Python (xlrd)
|
||||
try:
|
||||
return _convert_xls_to_xlsx_python(path, output)
|
||||
except Exception as exc:
|
||||
errors.append(f"Python xlrd conversion failed: {exc}")
|
||||
|
||||
joined = "; ".join(errors) if errors else "no converter attempted"
|
||||
raise RuntimeError(
|
||||
".xls 转 .xlsx 失败。请安装 LibreOffice(soffice)或设置 EDKB_SOFFICE。"
|
||||
".xls 转 .xlsx 失败。请安装 LibreOffice(soffice)、Microsoft Excel 或检查文件。"
|
||||
f" details: {joined}"
|
||||
)
|
||||
|
||||
@@ -62,6 +93,7 @@ def _trim_trailing_empty(vals: list[str]) -> list[str]:
|
||||
|
||||
|
||||
def run(input_data: dict, context: Context) -> list[dict]:
|
||||
import os
|
||||
file_path = Path(input_data["file_path"])
|
||||
work_dir = Path(input_data["work_dir"])
|
||||
if file_path.suffix.lower() == ".xls":
|
||||
|
||||
@@ -16,7 +16,7 @@ _MIN_TEXT_HEAVY_IMAGE_BYTES = 24 * 1024
|
||||
|
||||
|
||||
def _is_scanned(text_chars: int, pages: int) -> bool:
|
||||
return text_chars < int(300 * max(pages, 1) / 10)
|
||||
return text_chars < int(150 * max(pages, 1))
|
||||
|
||||
|
||||
def _is_text_heavy_pdf(text_chars: int, pages: int) -> bool:
|
||||
|
||||
@@ -7,6 +7,9 @@ COND_KWS = ["条件", "判定", "if", "IF"]
|
||||
ACT_KWS = ["处理", "动作", "措施", "结果", "输出"]
|
||||
OWN_KWS = ["责任", "负责人", "部门", "岗位"]
|
||||
|
||||
# Wide tables use row text blocks so Dify custom segmentation stays row-aligned.
|
||||
WIDE_TABLE_COLS = 8
|
||||
|
||||
|
||||
def _find_col(headers: list[str], kws: list[str]) -> int | None:
|
||||
for i, h in enumerate(headers):
|
||||
@@ -16,40 +19,73 @@ def _find_col(headers: list[str], kws: list[str]) -> int | None:
|
||||
return None
|
||||
|
||||
|
||||
def _to_table_md(headers: list[str], rows: list[list[str]]) -> str:
|
||||
def _to_table_md_loose(headers: list[str], rows: list[list[str]]) -> str:
|
||||
"""Markdown header block plus one pipe row per chunk, separated by blank lines."""
|
||||
hs = [h or "-" for h in headers]
|
||||
out = ["| " + " | ".join(hs) + " |", "| " + " | ".join(["---"] * len(hs)) + " |"]
|
||||
for r in rows:
|
||||
vals = [r[i] if i < len(r) else "" for i in range(len(hs))]
|
||||
out.append("| " + " | ".join(vals) + " |")
|
||||
return "\n".join(out)
|
||||
header_block = "\n".join(
|
||||
[
|
||||
"| " + " | ".join(hs) + " |",
|
||||
"| " + " | ".join(["---"] * len(hs)) + " |",
|
||||
]
|
||||
)
|
||||
data_blocks: list[str] = []
|
||||
for row in rows:
|
||||
vals = [row[i] if i < len(row) else "" for i in range(len(hs))]
|
||||
data_blocks.append("| " + " | ".join(vals) + " |")
|
||||
if not data_blocks:
|
||||
return header_block
|
||||
return header_block + "\n\n" + "\n\n".join(data_blocks)
|
||||
|
||||
|
||||
def _to_row_text_md(headers: list[str], rows: list[list[str]]) -> str:
|
||||
"""Wide-table fallback: one bullet per row for stable chunk boundaries."""
|
||||
hs = [h or "-" for h in headers]
|
||||
blocks: list[str] = []
|
||||
for row in rows:
|
||||
pairs = []
|
||||
for i, header in enumerate(hs):
|
||||
val = row[i] if i < len(row) else ""
|
||||
pairs.append(f"{header}={val}")
|
||||
blocks.append("- 【行】" + ";".join(pairs) + "。")
|
||||
return "\n\n".join(blocks)
|
||||
|
||||
|
||||
def run(input_data: list[dict] | dict, context: Context) -> str:
|
||||
tables = input_data if isinstance(input_data, list) else [input_data]
|
||||
parts: list[str] = []
|
||||
|
||||
for t in tables:
|
||||
headers = [str(x).strip() for x in t.get("headers", [])]
|
||||
rows = [[str(c).strip() for c in row] for row in t.get("rows", [])]
|
||||
parts.append(f"## Sheet: {t.get('sheet', 'Sheet1')}")
|
||||
for table in tables:
|
||||
headers = [str(x).strip() for x in table.get("headers", [])]
|
||||
rows = [[str(c).strip() for c in row] for row in table.get("rows", [])]
|
||||
sheet_blocks: list[str] = [f"## Sheet: {table.get('sheet', 'Sheet1')}"]
|
||||
|
||||
cidx = _find_col(headers, COND_KWS)
|
||||
aidx = _find_col(headers, ACT_KWS)
|
||||
oidx = _find_col(headers, OWN_KWS)
|
||||
if cidx is not None and aidx is not None:
|
||||
cond_idx = _find_col(headers, COND_KWS)
|
||||
act_idx = _find_col(headers, ACT_KWS)
|
||||
owner_idx = _find_col(headers, OWN_KWS)
|
||||
if cond_idx is not None and act_idx is not None:
|
||||
bullets: list[str] = []
|
||||
for row in rows:
|
||||
cond = row[cidx] if cidx < len(row) else "满足条件"
|
||||
act = row[aidx] if aidx < len(row) else "执行处理"
|
||||
cond = row[cond_idx] if cond_idx < len(row) else "满足条件"
|
||||
act = row[act_idx] if act_idx < len(row) else "执行处理"
|
||||
owner = (
|
||||
row[oidx] if oidx is not None and oidx < len(row) else "相关责任方"
|
||||
row[owner_idx]
|
||||
if owner_idx is not None and owner_idx < len(row)
|
||||
else "相关责任方"
|
||||
)
|
||||
parts.append(
|
||||
bullets.append(
|
||||
f"- 当 {cond or '满足条件'} 时,{owner or '相关责任方'} 执行 {act or '执行处理'}。"
|
||||
)
|
||||
if bullets:
|
||||
sheet_blocks.append("\n\n".join(bullets))
|
||||
elif len(headers) > WIDE_TABLE_COLS:
|
||||
content = _to_row_text_md(headers, rows)
|
||||
if content:
|
||||
sheet_blocks.append(content)
|
||||
else:
|
||||
parts.append(_to_table_md(headers, rows))
|
||||
content = _to_table_md_loose(headers, rows)
|
||||
if content:
|
||||
sheet_blocks.append(content)
|
||||
|
||||
parts.append("")
|
||||
parts.append("\n\n".join(sheet_blocks))
|
||||
|
||||
return "\n".join(parts).strip() + "\n"
|
||||
return "\n\n".join(parts).strip() + "\n"
|
||||
@@ -0,0 +1,50 @@
|
||||
"""add rohs schedule kb sync fields
|
||||
|
||||
Revision ID: b8c9d0e1f2a3
|
||||
Revises: 5569936e6e0b
|
||||
Create Date: 2026-06-09 00:00:00.000000
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = 'b8c9d0e1f2a3'
|
||||
down_revision = '5569936e6e0b'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column('schedule_tasks', sa.Column('kb_sync_enabled', sa.Boolean(), server_default=sa.text('false'), nullable=False))
|
||||
op.add_column('schedule_tasks', sa.Column('kb_group_id', sa.Integer(), nullable=True))
|
||||
op.create_index('ix_schedule_tasks_kb_group_id', 'schedule_tasks', ['kb_group_id'])
|
||||
op.create_foreign_key('fk_schedule_tasks_kb_group_id_kb_groups', 'schedule_tasks', 'kb_groups', ['kb_group_id'], ['id'])
|
||||
|
||||
op.add_column('schedule_runs', sa.Column('kb_sync_status', sa.String(length=32), nullable=True))
|
||||
op.add_column('schedule_runs', sa.Column('kb_group_id', sa.Integer(), nullable=True))
|
||||
op.add_column('schedule_runs', sa.Column('kb_document_id', sa.Integer(), nullable=True))
|
||||
op.add_column('schedule_runs', sa.Column('kb_document_version_id', sa.Integer(), nullable=True))
|
||||
op.add_column('schedule_runs', sa.Column('kb_sync_job_id', sa.Integer(), nullable=True))
|
||||
op.add_column('schedule_runs', sa.Column('kb_sync_error', sa.Text(), nullable=True))
|
||||
op.create_foreign_key('fk_schedule_runs_kb_group_id_kb_groups', 'schedule_runs', 'kb_groups', ['kb_group_id'], ['id'])
|
||||
op.create_foreign_key('fk_schedule_runs_kb_document_id_kb_documents', 'schedule_runs', 'kb_documents', ['kb_document_id'], ['id'])
|
||||
op.create_foreign_key('fk_schedule_runs_kb_document_version_id_kb_document_versions', 'schedule_runs', 'kb_document_versions', ['kb_document_version_id'], ['id'])
|
||||
op.create_foreign_key('fk_schedule_runs_kb_sync_job_id_kb_jobs', 'schedule_runs', 'kb_jobs', ['kb_sync_job_id'], ['id'])
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_constraint('fk_schedule_runs_kb_sync_job_id_kb_jobs', 'schedule_runs', type_='foreignkey')
|
||||
op.drop_constraint('fk_schedule_runs_kb_document_version_id_kb_document_versions', 'schedule_runs', type_='foreignkey')
|
||||
op.drop_constraint('fk_schedule_runs_kb_document_id_kb_documents', 'schedule_runs', type_='foreignkey')
|
||||
op.drop_constraint('fk_schedule_runs_kb_group_id_kb_groups', 'schedule_runs', type_='foreignkey')
|
||||
op.drop_column('schedule_runs', 'kb_sync_error')
|
||||
op.drop_column('schedule_runs', 'kb_sync_job_id')
|
||||
op.drop_column('schedule_runs', 'kb_document_version_id')
|
||||
op.drop_column('schedule_runs', 'kb_document_id')
|
||||
op.drop_column('schedule_runs', 'kb_group_id')
|
||||
op.drop_column('schedule_runs', 'kb_sync_status')
|
||||
|
||||
op.drop_constraint('fk_schedule_tasks_kb_group_id_kb_groups', 'schedule_tasks', type_='foreignkey')
|
||||
op.drop_index('ix_schedule_tasks_kb_group_id', table_name='schedule_tasks')
|
||||
op.drop_column('schedule_tasks', 'kb_group_id')
|
||||
op.drop_column('schedule_tasks', 'kb_sync_enabled')
|
||||
@@ -32,6 +32,7 @@ pypdfium2==5.0.0
|
||||
python-pptx==1.0.2
|
||||
beautifulsoup4==4.14.2
|
||||
lxml==6.0.2
|
||||
xlrd==2.0.1
|
||||
typer==0.17.4
|
||||
croniter
|
||||
pyyaml
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Export Dify-compatible OpenAPI for RoHS Check tools paste/import."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / "backend"))
|
||||
|
||||
from app.services.rohs_check_tools.openapi_spec import build_rohs_openapi_spec
|
||||
|
||||
|
||||
def main() -> None:
|
||||
base = (
|
||||
os.getenv("HXOPS_TOOLS_API_BASE")
|
||||
or os.getenv("PUBLIC_BASE_URL")
|
||||
or "http://127.0.0.1:5052"
|
||||
).rstrip("/")
|
||||
spec = build_rohs_openapi_spec(base)
|
||||
out_dir = ROOT / "docs" / "openapi"
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
json_path = out_dir / "rohs_check_tools_openapi.json"
|
||||
json_path.write_text(json.dumps(spec, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print(f"Wrote {json_path}")
|
||||
print(f"Import URL: {base}/api/rohs-check/tools/openapi.json")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -14,9 +14,8 @@ from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
|
||||
|
||||
def main() -> None:
|
||||
base = (
|
||||
os.getenv("SHIPPING_NOTICE_TOOL_API_BASE")
|
||||
os.getenv("HXOPS_TOOLS_API_BASE")
|
||||
or os.getenv("PUBLIC_BASE_URL")
|
||||
or os.getenv("HXOPS_PUBLIC_BASE_URL")
|
||||
or "http://127.0.0.1:5052"
|
||||
).rstrip("/")
|
||||
spec = build_dify_openapi_spec(base)
|
||||
@@ -30,3 +29,4 @@ def main() -> None:
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
backend/scripts/sync_wecom_userid_by_employee_id.py
|
||||
|
||||
用途:从企业微信通讯录拉取成员,按工号(employee_id)回填本地 users.wecom_userid。
|
||||
依赖:app.create_app、wecom_directory_sync.sync_wecom_userids_from_directory。
|
||||
逻辑:运维 CLI;默认 dry-run,--apply 才写库。
|
||||
|
||||
Usage:
|
||||
cd backend
|
||||
python scripts/sync_wecom_userid_by_employee_id.py
|
||||
python scripts/sync_wecom_userid_by_employee_id.py --apply
|
||||
python scripts/sync_wecom_userid_by_employee_id.py --apply --department-id 1
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
BACKEND_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(BACKEND_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(BACKEND_ROOT))
|
||||
|
||||
from app import create_app # noqa: E402
|
||||
from app.services.wecom_directory_sync import sync_wecom_userids_from_directory # noqa: E402
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""CLI 入口:解析参数并打印同步摘要 JSON。"""
|
||||
parser = argparse.ArgumentParser(description='Sync User.wecom_userid from WeCom directory by employee_id.')
|
||||
parser.add_argument('--apply', action='store_true', help='Persist changes (default: dry-run).')
|
||||
parser.add_argument('--department-id', type=int, default=None, help='Root department id (default: all departments).')
|
||||
args = parser.parse_args()
|
||||
|
||||
env = os.getenv('FLASK_ENV', 'production')
|
||||
app = create_app(env)
|
||||
with app.app_context():
|
||||
summary = sync_wecom_userids_from_directory(apply=args.apply, department_id=args.department_id)
|
||||
|
||||
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
if summary.get('conflicts'):
|
||||
print('\nConflicts detected; resolve manually before --apply.', file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Tests for Dify sync process_rule selection (Excel custom vs default automatic)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.knowledge_cleaning import dify_sync_service as dify_sync_module
|
||||
|
||||
|
||||
def _make_service(monkeypatch, **overrides):
|
||||
settings = {
|
||||
'DIFY_API_BASE': 'http://dify.example/v1',
|
||||
'DIFY_API_KEY': 'dataset-test-key',
|
||||
'KB_DIFY_PERMISSION': 'only_me',
|
||||
'KB_DIFY_INDEXING_TECHNIQUE': 'high_quality',
|
||||
'KB_DIFY_SEARCH_METHOD': 'semantic_search',
|
||||
'KB_DIFY_DOC_FORM': 'text_model',
|
||||
'KB_DIFY_PROCESS_MODE': 'automatic',
|
||||
'KB_DIFY_PROCESS_MODE_EXCEL': 'custom',
|
||||
'KB_DIFY_SEGMENT_SEPARATOR': '\\n\\n',
|
||||
'KB_DIFY_SEGMENT_SEPARATOR_EXCEL': '\\n\\n',
|
||||
'KB_DIFY_SEGMENT_MAX_TOKENS': '800',
|
||||
'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '50',
|
||||
'KB_DIFY_REMOVE_URLS': 'false',
|
||||
}
|
||||
settings.update(overrides)
|
||||
monkeypatch.setattr(dify_sync_module, 'get_kb_dify_settings', lambda: settings)
|
||||
return dify_sync_module.KbDifySyncService()
|
||||
|
||||
|
||||
def test_build_process_rule_xlsx_uses_custom_segmentation(monkeypatch):
|
||||
service = _make_service(monkeypatch)
|
||||
rule = service._build_process_rule('xlsx')
|
||||
|
||||
assert rule['mode'] == 'custom'
|
||||
assert rule['rules']['segmentation']['separator'] == '\n\n'
|
||||
assert rule['rules']['segmentation']['max_tokens'] == 800
|
||||
assert rule['rules']['segmentation']['chunk_overlap'] == 50
|
||||
assert rule['rules']['pre_processing_rules'][1]['enabled'] is False
|
||||
|
||||
|
||||
def test_build_process_rule_docx_defaults_to_automatic(monkeypatch):
|
||||
service = _make_service(monkeypatch)
|
||||
rule = service._build_process_rule('docx')
|
||||
assert rule == {'mode': 'automatic'}
|
||||
|
||||
|
||||
def test_create_document_by_text_xlsx_posts_custom_process_rule(monkeypatch):
|
||||
service = _make_service(monkeypatch)
|
||||
captured: dict = {}
|
||||
|
||||
def fake_request(method, path, **kwargs):
|
||||
captured['method'] = method
|
||||
captured['path'] = path
|
||||
captured['json'] = kwargs.get('json')
|
||||
return {'document': {'id': 'doc-1', 'name': 'demo.xlsx'}}
|
||||
|
||||
monkeypatch.setattr(service, '_request', fake_request)
|
||||
service.create_document_by_text(
|
||||
dataset_id='ds-1',
|
||||
name='demo.xlsx',
|
||||
text='row one\n\nrow two',
|
||||
source_ext='xlsx',
|
||||
)
|
||||
|
||||
assert captured['method'] == 'POST'
|
||||
assert captured['path'] == '/datasets/ds-1/document/create-by-text'
|
||||
process_rule = captured['json']['process_rule']
|
||||
assert process_rule['mode'] == 'custom'
|
||||
assert process_rule['rules']['segmentation']['separator'] == '\n\n'
|
||||
assert process_rule['rules']['segmentation']['max_tokens'] == 800
|
||||
|
||||
|
||||
def test_remove_urls_emails_respects_kb_dify_remove_urls_true(monkeypatch):
|
||||
service = _make_service(monkeypatch, KB_DIFY_REMOVE_URLS='true')
|
||||
rule = service._build_process_rule('csv')
|
||||
remove_urls = next(
|
||||
item for item in rule['rules']['pre_processing_rules']
|
||||
if item['id'] == 'remove_urls_emails'
|
||||
)
|
||||
assert remove_urls['enabled'] is True
|
||||
|
||||
|
||||
def test_resolve_source_file_ext_from_filename():
|
||||
class _Version:
|
||||
source_file_ext = None
|
||||
source_file_name = 'report.XLSX'
|
||||
|
||||
assert dify_sync_module.resolve_source_file_ext(_Version()) == 'xlsx'
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Tests for persisting edkb 04_chunks.jsonl into KB version directories."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from app.services.knowledge_cleaning import edkb_adapter
|
||||
|
||||
|
||||
def _fake_build_knowledge(file_path: Path, output_dir: Path, config, cache_dir):
|
||||
out_sub = output_dir / 'sample'
|
||||
out_sub.mkdir(parents=True, exist_ok=True)
|
||||
(out_sub / '03_clean.md').write_text(
|
||||
'## Sheet: Data\n\n| A | B |\n| --- | --- |\n\n| 1 | 2 |\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
(out_sub / '04_chunks.jsonl').write_text(
|
||||
'{"id":"chunk-0","text":"row one"}\n{"id":"chunk-1","text":"row two"}\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
chunks_dir = out_sub / 'chunks'
|
||||
chunks_dir.mkdir()
|
||||
(chunks_dir / 'chunk_0000.md').write_text('row one\n', encoding='utf-8')
|
||||
(chunks_dir / 'chunk_0001.md').write_text('row two\n', encoding='utf-8')
|
||||
return [{'status': 'success', 'file': str(file_path)}]
|
||||
|
||||
|
||||
def test_build_clean_result_persists_chunks_jsonl(monkeypatch, tmp_path):
|
||||
source_path = tmp_path / 'sample.xlsx'
|
||||
source_path.write_bytes(b'fake-xlsx-content')
|
||||
target_dir = tmp_path / 'output'
|
||||
|
||||
monkeypatch.setattr('edkb_system.controller.build_knowledge', _fake_build_knowledge)
|
||||
|
||||
class _FakeConfig:
|
||||
@staticmethod
|
||||
def load(_path):
|
||||
return _FakeConfig()
|
||||
|
||||
monkeypatch.setattr('edkb_system.config.SystemConfig', _FakeConfig)
|
||||
|
||||
result = edkb_adapter.build_clean_result(source_path, target_dir)
|
||||
|
||||
chunks_path = target_dir / '04_chunks.jsonl'
|
||||
assert chunks_path.exists()
|
||||
assert (target_dir / 'document.md').exists()
|
||||
assert (target_dir / 'chunks' / 'chunk_0000.md').exists()
|
||||
assert (target_dir / 'chunks' / 'chunk_0001.md').exists()
|
||||
assert result['chunks_file_path'] == str(chunks_path)
|
||||
assert result['chunks_count'] == 2
|
||||
|
||||
|
||||
def test_persist_debug_chunks_skips_missing_jsonl(tmp_path):
|
||||
output_root = tmp_path / 'output'
|
||||
output_root.mkdir()
|
||||
target_dir = tmp_path / 'target'
|
||||
target_dir.mkdir()
|
||||
|
||||
chunks_file_path, chunks_count = edkb_adapter._persist_debug_chunks(output_root, target_dir)
|
||||
|
||||
assert chunks_file_path is None
|
||||
assert chunks_count is None
|
||||
assert not (target_dir / '04_chunks.jsonl').exists()
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Tests for edkb per-file timeout selection."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from edkb_system.controller import _file_timeout_sec
|
||||
|
||||
|
||||
def test_excel_skips_spawn_timeout_wrapper(monkeypatch):
|
||||
monkeypatch.setenv('EDKB_FILE_TIMEOUT_SEC', '180')
|
||||
assert _file_timeout_sec(Path('report.xlsx')) is None
|
||||
assert _file_timeout_sec(Path('data.csv')) is None
|
||||
|
||||
|
||||
def test_word_still_uses_word_timeout(monkeypatch):
|
||||
monkeypatch.setenv('EDKB_FILE_TIMEOUT_SEC', '180')
|
||||
monkeypatch.setenv('EDKB_WORD_FILE_TIMEOUT_SEC', '420')
|
||||
assert _file_timeout_sec(Path('manual.docx')) == 420
|
||||
|
||||
|
||||
def test_other_formats_use_global_timeout(monkeypatch):
|
||||
monkeypatch.setenv('EDKB_FILE_TIMEOUT_SEC', '180')
|
||||
assert _file_timeout_sec(Path('slides.pptx')) == 180
|
||||
@@ -27,8 +27,11 @@ def test_build_clean_result_generates_markdown_for_xlsx(tmp_path):
|
||||
assert result['cleaned_preview_path'] == str(cleaned_path)
|
||||
|
||||
content = cleaned_path.read_text(encoding='utf-8')
|
||||
assert content.strip()
|
||||
assert '供应链' in content
|
||||
assert '能耗' in content
|
||||
# Narrow Excel tables should expose Dify-friendly row boundaries.
|
||||
assert '\n\n|' in content or '| 供应链 | 能耗 |' in content
|
||||
|
||||
|
||||
def test_normalized_source_filename_infers_xlsx_extension(tmp_path):
|
||||
|
||||
@@ -0,0 +1,859 @@
|
||||
import sys
|
||||
import types
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, User
|
||||
from app.services.rohs_check import RoHSCheckService
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _stub_minio(monkeypatch):
|
||||
minio_module = types.ModuleType('minio')
|
||||
minio_error_module = types.ModuleType('minio.error')
|
||||
|
||||
class DummyMinio:
|
||||
def __init__(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def bucket_exists(self, *args, **kwargs):
|
||||
return True
|
||||
|
||||
class DummyS3Error(Exception):
|
||||
pass
|
||||
|
||||
minio_module.Minio = DummyMinio
|
||||
minio_error_module.S3Error = DummyS3Error
|
||||
monkeypatch.setitem(sys.modules, 'minio', minio_module)
|
||||
monkeypatch.setitem(sys.modules, 'minio.error', minio_error_module)
|
||||
|
||||
|
||||
def _mk_admin():
|
||||
admin = User(username='admin', email='admin-rohs@example.com', role='admin', status='active')
|
||||
admin.set_password('x')
|
||||
db.session.add(admin)
|
||||
return admin
|
||||
|
||||
|
||||
def _mk_check_task(owner_id: int, *, enabled=True):
|
||||
task = ScheduleTask(
|
||||
schedule_no='CHK-ROHS-001',
|
||||
name='RoHS 自动检核',
|
||||
schedule_type='platform_app',
|
||||
owner_user_id=owner_id,
|
||||
cron_expr='0 * * * *',
|
||||
wait_seconds=5,
|
||||
platform_api_path='/1',
|
||||
enabled=enabled,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
return task
|
||||
|
||||
|
||||
def _mk_non_rohs_task(owner_id: int):
|
||||
task = ScheduleTask(
|
||||
schedule_no='CHK-GENERAL-001',
|
||||
name='通用检核',
|
||||
schedule_type='platform_app',
|
||||
owner_user_id=owner_id,
|
||||
cron_expr='0 * * * *',
|
||||
wait_seconds=5,
|
||||
platform_api_path='/general-check',
|
||||
enabled=True,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
return task
|
||||
|
||||
|
||||
def test_rohs_service_normalizes_failed_workflow():
|
||||
payload = RoHSCheckService.normalize_workflow_result({
|
||||
'status': 'failed',
|
||||
'error': 'workflow timeout',
|
||||
'workflow_run_id': 'wf-2',
|
||||
})
|
||||
assert payload['dify_result'] == '人工判定'
|
||||
assert 'Dify执行失败' in payload['dify_message']
|
||||
assert payload['workflow_run_id'] == 'wf-2'
|
||||
|
||||
|
||||
def test_rohs_service_evaluate_degrades_on_dify_error(monkeypatch):
|
||||
class _Agent:
|
||||
id = 1
|
||||
|
||||
def _boom(**kwargs):
|
||||
raise RuntimeError('dify down')
|
||||
|
||||
monkeypatch.setattr('app.services.rohs_check.DifyService.run_workflow_streaming', _boom)
|
||||
payload = RoHSCheckService.evaluate(
|
||||
agent=_Agent(),
|
||||
run_no='RUN-1',
|
||||
record='Pb: 100ppm',
|
||||
)
|
||||
assert payload['dify_result'] == '人工判定'
|
||||
assert 'Dify执行失败' in payload['dify_message']
|
||||
assert payload['error'] == 'dify down'
|
||||
|
||||
|
||||
def test_rohs_service_normalizes_invalid_result():
|
||||
payload = RoHSCheckService.normalize_workflow_result({
|
||||
'status': 'succeeded',
|
||||
'outputs': {'dify_result': 'OK', 'dify_message': 'bad enum'},
|
||||
'workflow_run_id': 'wf-1',
|
||||
})
|
||||
assert payload['dify_result'] == '人工判定'
|
||||
assert '返回值异常' in payload['dify_message']
|
||||
assert payload['workflow_run_id'] == 'wf-1'
|
||||
|
||||
|
||||
def test_rohs_loop_splits_processing_and_judgement_counts(app, monkeypatch):
|
||||
from app.services.schedule.srm_service import _run_check_job_loop
|
||||
|
||||
class _Agent:
|
||||
id = 1
|
||||
dify_api_key = 'secret'
|
||||
|
||||
def _evaluate(**kwargs):
|
||||
return {
|
||||
'dify_result': '人工判定',
|
||||
'dify_message': 'Dify执行失败:workflow timeout',
|
||||
'workflow_run_id': 'wf-failed',
|
||||
'error': 'workflow timeout',
|
||||
}
|
||||
|
||||
writebacks = []
|
||||
|
||||
monkeypatch.setattr('app.services.schedule.srm_service.RoHSCheckService.evaluate', _evaluate)
|
||||
with app.app_context():
|
||||
admin = _mk_admin()
|
||||
db.session.flush()
|
||||
task = _mk_check_task(admin.id)
|
||||
run = ScheduleRun(run_no='RUN-JUDGEMENT-SPLIT', schedule_task_id=task.id, status='running', trigger_type='manual')
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
run_id = run.id
|
||||
|
||||
total, success, failed, skipped, details, errors, step_logs = _run_check_job_loop(
|
||||
conn_str='',
|
||||
run_no='RUN-1',
|
||||
agent=_Agent(),
|
||||
user='tester',
|
||||
wait_seconds=5,
|
||||
run_id=run_id,
|
||||
fetch_fn=lambda _conn: [{'id': 'R1'}],
|
||||
build_record_fn=lambda _conn, item, row_id: ('record text', None),
|
||||
writeback_fn=lambda _conn, **kwargs: writebacks.append(kwargs),
|
||||
row_id_key='id',
|
||||
log_prefix='row',
|
||||
)
|
||||
db.session.refresh(run)
|
||||
judgement = (run.response_summary_json or {}).get('rohs_judgement') or {}
|
||||
|
||||
assert total == 1
|
||||
assert success == 1
|
||||
assert failed == 0
|
||||
assert skipped == 0
|
||||
assert writebacks
|
||||
assert details[0]['writeback_srm'] is True
|
||||
assert errors == []
|
||||
assert judgement['manual_count'] == 1
|
||||
assert judgement['dify_error_count'] == 1
|
||||
assert (run.response_summary_json or {}).get('current_step', {}).get('step') == 'completed'
|
||||
assert any(log['step'] == 'call_dify' and log['status'] == 'success' for log in step_logs)
|
||||
|
||||
|
||||
def test_srm_sql_operations_apply_configured_timeout(app, monkeypatch):
|
||||
from app.services.schedule import srm_service
|
||||
|
||||
observed = {'connect_timeout': None, 'cursor_timeout': None}
|
||||
|
||||
class _Cursor:
|
||||
description = [('id',)]
|
||||
|
||||
def __setattr__(self, name, value):
|
||||
if name == 'timeout':
|
||||
observed['cursor_timeout'] = value
|
||||
object.__setattr__(self, name, value)
|
||||
|
||||
def execute(self, *_args):
|
||||
return None
|
||||
|
||||
def fetchall(self):
|
||||
return [(1,)]
|
||||
|
||||
class _Conn:
|
||||
def cursor(self):
|
||||
return _Cursor()
|
||||
|
||||
def commit(self):
|
||||
return None
|
||||
|
||||
def close(self):
|
||||
return None
|
||||
|
||||
class _Pyodbc:
|
||||
@staticmethod
|
||||
def connect(_conn_str, timeout):
|
||||
observed['connect_timeout'] = timeout
|
||||
return _Conn()
|
||||
|
||||
monkeypatch.setattr(srm_service, 'pyodbc', _Pyodbc)
|
||||
with app.app_context():
|
||||
app.config['SRM_SQLSERVER_TIMEOUT'] = 7
|
||||
srm_service._execute_writeback('conn', 'update table set col=?', ('x',))
|
||||
|
||||
assert observed == {'connect_timeout': 7, 'cursor_timeout': 7}
|
||||
|
||||
|
||||
def test_rohs_tool_requires_auth(app, client):
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
res = client.get('/api/rohs-check/tools/tasks')
|
||||
assert res.status_code == 401
|
||||
assert res.get_json()['error_code'] == 'missing_auth'
|
||||
|
||||
|
||||
def test_rohs_tool_rejects_invalid_auth(app, client):
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
res = client.get('/api/rohs-check/tools/tasks', headers={'X-Integration-Key': 'wrong'})
|
||||
assert res.status_code == 401
|
||||
assert res.get_json()['error_code'] == 'invalid_auth'
|
||||
|
||||
|
||||
def test_rohs_tool_lists_tasks(app, client):
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
_mk_check_task(admin.id)
|
||||
_mk_non_rohs_task(admin.id)
|
||||
|
||||
res = client.get('/api/rohs-check/tools/tasks', headers={'X-Integration-Key': 'secret'})
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
assert data['ok'] is True
|
||||
assert [item['task_no'] for item in data['tasks']] == ['CHK-ROHS-001']
|
||||
|
||||
|
||||
def test_rohs_tool_rejects_non_rohs_task(app, client):
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_non_rohs_task(admin.id)
|
||||
task_id = task.id
|
||||
|
||||
res = client.post(
|
||||
'/api/rohs-check/tools/tasks/run',
|
||||
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
|
||||
json={'task_id': task_id},
|
||||
)
|
||||
assert res.status_code == 404
|
||||
assert res.get_json()['error_code'] == 'task_not_found'
|
||||
|
||||
|
||||
def test_rohs_tool_running_conflict(app, client):
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
task_id = task.id
|
||||
run = ScheduleRun(run_no='RUN-ROHS-001', schedule_task_id=task.id, status='running', trigger_type='manual')
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
res = client.post(
|
||||
'/api/rohs-check/tools/tasks/run',
|
||||
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
|
||||
json={'task_id': task_id},
|
||||
)
|
||||
assert res.status_code == 409
|
||||
data = res.get_json()
|
||||
assert data['error_code'] == 'check_running'
|
||||
|
||||
|
||||
def test_rohs_tool_requires_task_id(app, client):
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
|
||||
res = client.post(
|
||||
'/api/rohs-check/tools/tasks/run',
|
||||
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
|
||||
json={},
|
||||
)
|
||||
assert res.status_code == 400
|
||||
assert res.get_json()['error_code'] == 'task_id_required'
|
||||
|
||||
|
||||
def test_rohs_tool_rejects_invalid_task_id(app, client):
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
|
||||
res = client.post(
|
||||
'/api/rohs-check/tools/tasks/run',
|
||||
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
|
||||
json={'task_id': 'abc'},
|
||||
)
|
||||
assert res.status_code == 400
|
||||
assert res.get_json()['error_code'] == 'task_id_invalid'
|
||||
|
||||
|
||||
def test_rohs_tool_running_conflict_is_global(app, client):
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
running_task = _mk_check_task(admin.id)
|
||||
second_task = ScheduleTask(
|
||||
schedule_no='CHK-ROHS-002',
|
||||
name='RoHS 文件检核备用',
|
||||
schedule_type='platform_app',
|
||||
owner_user_id=admin.id,
|
||||
cron_expr='0 * * * *',
|
||||
wait_seconds=5,
|
||||
platform_api_path='/2',
|
||||
enabled=True,
|
||||
)
|
||||
db.session.add(second_task)
|
||||
db.session.flush()
|
||||
running = ScheduleRun(run_no='RUN-ROHS-RUNNING', schedule_task_id=running_task.id, status='running', trigger_type='manual')
|
||||
db.session.add(running)
|
||||
db.session.commit()
|
||||
second_task_id = second_task.id
|
||||
running_id = running.id
|
||||
|
||||
res = client.post(
|
||||
'/api/rohs-check/tools/tasks/run',
|
||||
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
|
||||
json={'task_id': second_task_id},
|
||||
)
|
||||
assert res.status_code == 409
|
||||
data = res.get_json()
|
||||
assert data['error_code'] == 'check_running'
|
||||
assert data['run']['run_id'] == running_id
|
||||
|
||||
|
||||
def test_rohs_tool_lists_all_rohs_runs(app, client):
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
rohs_task = _mk_check_task(admin.id)
|
||||
other_task = _mk_non_rohs_task(admin.id)
|
||||
db.session.add_all([
|
||||
ScheduleRun(run_no='RUN-ROHS-001', schedule_task_id=rohs_task.id, status='success', trigger_type='manual', total_count=3, success_count=3),
|
||||
ScheduleRun(run_no='RUN-ROHS-002', schedule_task_id=rohs_task.id, status='partial_failed', trigger_type='manual', total_count=4, success_count=3, failed_count=1),
|
||||
ScheduleRun(run_no='RUN-OTHER-001', schedule_task_id=other_task.id, status='success', trigger_type='manual', total_count=9, success_count=9),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
res = client.get('/api/rohs-check/tools/runs?limit=10', headers={'X-Integration-Key': 'secret'})
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
assert data['ok'] is True
|
||||
assert data['count'] == 2
|
||||
assert {item['run_no'] for item in data['runs']} == {'RUN-ROHS-001', 'RUN-ROHS-002'}
|
||||
|
||||
|
||||
def test_workspace_rohs_active_run_returns_progress(app, client):
|
||||
with app.app_context():
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
run = ScheduleRun(
|
||||
run_no='RUN-ROHS-ACTIVE',
|
||||
schedule_task_id=task.id,
|
||||
status='running',
|
||||
trigger_type='dify_chatflow',
|
||||
total_count=10,
|
||||
success_count=3,
|
||||
failed_count=1,
|
||||
skipped_count=1,
|
||||
response_summary_json={
|
||||
'current_step': {
|
||||
'step': 'writeback_srm',
|
||||
'label': '写回 SRM',
|
||||
'row_id': 'ROW-16',
|
||||
'started_at': '2026-06-11T10:00:00',
|
||||
'processed_count': 4,
|
||||
'success_count': 3,
|
||||
'failed_count': 1,
|
||||
'skipped_count': 0,
|
||||
},
|
||||
},
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
res = client.get('/api/workspace/rohs-check/runs/active', headers={'X-Username': 'admin'})
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
assert data['ok'] is True
|
||||
assert data['run']['run_no'] == 'RUN-ROHS-ACTIVE'
|
||||
assert data['run']['processed_count'] == 5
|
||||
assert data['run']['progress_percent'] == 50
|
||||
assert data['run']['current_step']['step'] == 'writeback_srm'
|
||||
assert data['run']['current_step']['row_id'] == 'ROW-16'
|
||||
|
||||
|
||||
def test_workspace_rohs_active_run_filters_by_conversation_id(app, client):
|
||||
with app.app_context():
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
run = ScheduleRun(
|
||||
run_no='RUN-ROHS-ACTIVE-CONV',
|
||||
schedule_task_id=task.id,
|
||||
status='running',
|
||||
trigger_type='dify_chatflow',
|
||||
total_count=10,
|
||||
success_count=2,
|
||||
api_request_json={'conversation_id': 'conv-a'},
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
miss = client.get('/api/workspace/rohs-check/runs/active?conversation_id=conv-b', headers={'X-Username': 'admin'})
|
||||
assert miss.status_code == 200
|
||||
assert miss.get_json()['run'] is None
|
||||
|
||||
hit = client.get('/api/workspace/rohs-check/runs/active?conversation_id=conv-a', headers={'X-Username': 'admin'})
|
||||
assert hit.status_code == 200
|
||||
assert hit.get_json()['run']['run_no'] == 'RUN-ROHS-ACTIVE-CONV'
|
||||
|
||||
|
||||
def test_workspace_rohs_active_run_returns_null_when_idle(app, client):
|
||||
with app.app_context():
|
||||
_mk_admin()
|
||||
db.session.commit()
|
||||
|
||||
res = client.get('/api/workspace/rohs-check/runs/active', headers={'X-Username': 'admin'})
|
||||
assert res.status_code == 200
|
||||
assert res.get_json()['run'] is None
|
||||
|
||||
|
||||
def test_rohs_tool_excel_download_uses_signed_token(app, client):
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
run = ScheduleRun(
|
||||
run_no='RUN-ROHS-EXCEL',
|
||||
schedule_task_id=task.id,
|
||||
status='success',
|
||||
trigger_type='manual',
|
||||
excel_file_name='result.xlsx',
|
||||
excel_file_data=b'xlsx-bytes',
|
||||
excel_file_size=10,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
run_id = run.id
|
||||
|
||||
query_res = client.get(f'/api/rohs-check/tools/runs/{run_id}', headers={'X-Integration-Key': 'secret'})
|
||||
token_url = query_res.get_json()['run']['excel']['download_url']
|
||||
download_path = token_url[token_url.index('/api/rohs-check'):]
|
||||
|
||||
res = client.get(download_path)
|
||||
assert res.status_code == 200
|
||||
assert res.data == b'xlsx-bytes'
|
||||
|
||||
res = client.get('/api/rohs-check/tools/tasks?token=' + download_path.split('token=', 1)[1])
|
||||
assert res.status_code == 401
|
||||
|
||||
|
||||
def test_rohs_tool_runs_disabled_schedule_immediately(app, client, monkeypatch):
|
||||
started_threads = []
|
||||
|
||||
class _Thread:
|
||||
def __init__(self, *, target, daemon, name):
|
||||
self.target = target
|
||||
self.daemon = daemon
|
||||
self.name = name
|
||||
|
||||
def start(self):
|
||||
started_threads.append(self.name)
|
||||
|
||||
monkeypatch.setattr('app.api.rohs_check_tools.threading.Thread', _Thread)
|
||||
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id, enabled=False)
|
||||
task_id = task.id
|
||||
|
||||
res = client.post(
|
||||
'/api/rohs-check/tools/tasks/run',
|
||||
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
|
||||
json={'task_id': task_id},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
assert data['ok'] is True
|
||||
assert data['run']['task_id'] == task_id
|
||||
assert data['run']['status'] == 'running'
|
||||
assert started_threads == [f"rohs-check-run-{data['run']['run_id']}"]
|
||||
|
||||
|
||||
def test_rohs_openapi_injects_tool_api_base(app, client):
|
||||
with app.app_context():
|
||||
app.config['HXOPS_TOOLS_API_BASE'] = 'https://rohs-tool.example.com'
|
||||
res = client.get('/api/rohs-check/tools/openapi.json')
|
||||
assert res.status_code == 200
|
||||
assert res.get_json()['servers'][0]['url'] == 'https://rohs-tool.example.com'
|
||||
|
||||
|
||||
def test_rohs_dify_chat_inputs(app):
|
||||
from app.services.rohs_check_tools.dify_inputs import (
|
||||
HXOPS_TOOL_API_TOKEN_INPUT,
|
||||
HXOPS_TOOLS_API_BASE_INPUT,
|
||||
build_dify_chat_inputs,
|
||||
)
|
||||
from app.services.rohs_check_tools.agent_resolver import is_rohs_check_chat_agent
|
||||
|
||||
class _Agent:
|
||||
def __init__(self, name: str):
|
||||
self.name = name
|
||||
|
||||
assert is_rohs_check_chat_agent(_Agent('RoHS文件检核助手'))
|
||||
assert not is_rohs_check_chat_agent(_Agent('货代发货通知 Agent'))
|
||||
|
||||
with app.app_context():
|
||||
app.config['HXOPS_TOOLS_API_BASE'] = 'https://rohs-tool.example.com'
|
||||
app.config['ROHS_TOOLS_API_KEY'] = 'rohs-secret'
|
||||
inputs = build_dify_chat_inputs()
|
||||
assert inputs[HXOPS_TOOLS_API_BASE_INPUT] == 'https://rohs-tool.example.com'
|
||||
assert inputs[HXOPS_TOOL_API_TOKEN_INPUT] == 'rohs-secret'
|
||||
|
||||
|
||||
def test_rohs_dify_chat_inputs_falls_back_to_legacy_env_key(app):
|
||||
from app.services.rohs_check_tools.dify_inputs import build_dify_chat_inputs
|
||||
|
||||
with app.app_context():
|
||||
app.config.pop('HXOPS_TOOLS_API_BASE', None)
|
||||
app.config['HXOPS_TOOLS_API_BASE'] = 'https://legacy-tool.example.com'
|
||||
app.config.pop('ROHS_TOOLS_API_KEY', None)
|
||||
app.config['INTEGRATION_API_KEY'] = 'integration-secret'
|
||||
inputs = build_dify_chat_inputs()
|
||||
assert inputs['HXOPS_TOOLS_API_BASE'] == 'https://legacy-tool.example.com'
|
||||
assert inputs['hxops_tool_api_token'] == 'integration-secret'
|
||||
|
||||
|
||||
def test_kb_sync_skips_failed_run(app):
|
||||
from app.models import KbGroup
|
||||
from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb
|
||||
|
||||
with app.app_context():
|
||||
admin = _mk_admin()
|
||||
group = KbGroup(name='RoHS KB', is_active=True)
|
||||
db.session.add(group)
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
task.kb_sync_enabled = True
|
||||
task.kb_group_id = group.id
|
||||
run = ScheduleRun(
|
||||
run_no='RUN-KB-SKIP',
|
||||
schedule_task_id=task.id,
|
||||
status='failed',
|
||||
trigger_type='manual',
|
||||
excel_file_data=b'xlsx',
|
||||
excel_file_name='result.xlsx',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
sync_schedule_run_excel_to_kb(task, run)
|
||||
assert run.kb_sync_status == 'skipped'
|
||||
|
||||
|
||||
def test_kb_sync_repairs_document_id_sequence_on_pkey_conflict(app, monkeypatch, tmp_path):
|
||||
from app.models import KbDocument, KbGroup
|
||||
from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
monkeypatch.setitem(app.config, 'KB_STORAGE_ROOT', str(tmp_path))
|
||||
original_flush = db.session.flush
|
||||
failed = {'value': False}
|
||||
|
||||
def _flush_with_one_pkey_failure(*args, **kwargs):
|
||||
if not failed['value'] and any(isinstance(item, KbDocument) for item in db.session.new):
|
||||
failed['value'] = True
|
||||
raise IntegrityError('insert', {}, Exception('duplicate key value violates unique constraint "kb_documents_pkey"'))
|
||||
return original_flush(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(db.session, 'flush', _flush_with_one_pkey_failure)
|
||||
repaired: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.db_sequence.repair_pg_id_sequence',
|
||||
lambda table_name: repaired.append(table_name),
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
admin = _mk_admin()
|
||||
group = KbGroup(name='RoHS KB Seq', is_active=True)
|
||||
db.session.add(group)
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
task.kb_sync_enabled = True
|
||||
task.kb_group_id = group.id
|
||||
run = ScheduleRun(
|
||||
run_no='TEST-RUN-KB-SEQ',
|
||||
schedule_task_id=task.id,
|
||||
status='success',
|
||||
trigger_type='test',
|
||||
triggered_by_user_id=admin.id,
|
||||
excel_file_data=b'fake-xlsx',
|
||||
excel_file_name='result.xlsx',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
sync_schedule_run_excel_to_kb(task, run, process_inline=False)
|
||||
|
||||
assert repaired == ['kb_documents']
|
||||
assert run.kb_document_id is not None
|
||||
assert run.kb_sync_status == 'queued'
|
||||
|
||||
|
||||
def test_kb_sync_repairs_version_id_sequence_without_losing_document(app, monkeypatch, tmp_path):
|
||||
from app.models import KbDocumentVersion, KbGroup
|
||||
from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
monkeypatch.setitem(app.config, 'KB_STORAGE_ROOT', str(tmp_path))
|
||||
original_flush = db.session.flush
|
||||
failed = {'value': False}
|
||||
|
||||
def _flush_with_version_pkey_failure(*args, **kwargs):
|
||||
if not failed['value'] and any(isinstance(item, KbDocumentVersion) for item in db.session.new):
|
||||
failed['value'] = True
|
||||
raise IntegrityError('insert', {}, Exception('duplicate key value violates unique constraint "kb_document_versions_pkey"'))
|
||||
return original_flush(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(db.session, 'flush', _flush_with_version_pkey_failure)
|
||||
repaired: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.db_sequence.repair_pg_id_sequence',
|
||||
lambda table_name: repaired.append(table_name),
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
admin = _mk_admin()
|
||||
group = KbGroup(name='RoHS KB Version Seq', is_active=True)
|
||||
db.session.add(group)
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
task.kb_sync_enabled = True
|
||||
task.kb_group_id = group.id
|
||||
run = ScheduleRun(
|
||||
run_no='TEST-RUN-KB-VERSION-SEQ',
|
||||
schedule_task_id=task.id,
|
||||
status='success',
|
||||
trigger_type='test',
|
||||
triggered_by_user_id=admin.id,
|
||||
excel_file_data=b'fake-xlsx',
|
||||
excel_file_name='result.xlsx',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
sync_schedule_run_excel_to_kb(task, run, process_inline=False)
|
||||
|
||||
assert repaired == ['kb_document_versions']
|
||||
assert run.kb_document_id is not None
|
||||
assert run.kb_document_version_id is not None
|
||||
assert run.kb_sync_status == 'queued'
|
||||
|
||||
|
||||
def test_dify_sync_repairs_sync_record_id_sequence_on_pkey_conflict(app, monkeypatch, tmp_path):
|
||||
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup
|
||||
from app.services.knowledge_cleaning import dify_sync_service as dify_sync_module
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
monkeypatch.setitem(app.config, 'KB_STORAGE_ROOT', str(tmp_path))
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'ensure_dataset',
|
||||
lambda self, group: ('ds-001', group.name),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'create_document_by_text',
|
||||
lambda self, dataset_id, name, text: {'document': {'id': 'remote-doc-001', 'name': name}},
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
admin = _mk_admin()
|
||||
group = KbGroup(name='RoHS KB Dify', is_active=True, dify_dataset_id='ds-001')
|
||||
document = KbDocument(
|
||||
group_id=None,
|
||||
title='RoHS sync seq',
|
||||
status='ready',
|
||||
source_type='schedule',
|
||||
created_by_id=admin.id,
|
||||
updated_by_id=admin.id,
|
||||
)
|
||||
db.session.add(group)
|
||||
db.session.flush()
|
||||
document.group_id = group.id
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
cleaned = tmp_path / 'cleaned.md'
|
||||
cleaned.write_text('# RoHS report', encoding='utf-8')
|
||||
version = KbDocumentVersion(
|
||||
document_id=document.id,
|
||||
version_no=1,
|
||||
status='ready',
|
||||
is_current=True,
|
||||
source_file_name='report.xlsx',
|
||||
source_file_path=str(cleaned),
|
||||
cleaned_file_path=str(cleaned),
|
||||
uploaded_by_id=admin.id,
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.commit()
|
||||
|
||||
original_flush = db.session.flush
|
||||
repaired: list[str] = []
|
||||
failed = {'value': False}
|
||||
|
||||
def _flush_with_one_pkey_failure(*args, **kwargs):
|
||||
if not failed['value'] and any(isinstance(item, KbDifySyncRecord) for item in db.session.new):
|
||||
failed['value'] = True
|
||||
raise IntegrityError(
|
||||
'insert',
|
||||
{},
|
||||
Exception(
|
||||
'duplicate key value violates unique constraint "kb_dify_sync_records_pkey"'
|
||||
),
|
||||
)
|
||||
return original_flush(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(db.session, 'flush', _flush_with_one_pkey_failure)
|
||||
monkeypatch.setattr(
|
||||
'app.services.db_sequence.repair_pg_id_sequence',
|
||||
lambda table_name: repaired.append(table_name),
|
||||
)
|
||||
|
||||
result = dify_sync_module.sync_document_version_to_dify(version.id, synced_by_id=admin.id)
|
||||
|
||||
assert repaired == ['kb_dify_sync_records']
|
||||
assert result['remote_document_id'] == 'remote-doc-001'
|
||||
|
||||
|
||||
def test_kb_sync_queues_test_run_excel(app, monkeypatch, tmp_path):
|
||||
from app.models import KbGroup
|
||||
from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb
|
||||
|
||||
monkeypatch.setitem(app.config, 'KB_STORAGE_ROOT', str(tmp_path))
|
||||
enqueued: list[int] = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.schedule.kb_sync.enqueue_clean_job',
|
||||
lambda job_id: enqueued.append(job_id),
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
admin = _mk_admin()
|
||||
group = KbGroup(name='RoHS KB Test', is_active=True)
|
||||
db.session.add(group)
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
task.kb_sync_enabled = True
|
||||
task.kb_group_id = group.id
|
||||
run = ScheduleRun(
|
||||
run_no='TEST-RUN-KB-001',
|
||||
schedule_task_id=task.id,
|
||||
status='success',
|
||||
trigger_type='test',
|
||||
triggered_by_user_id=admin.id,
|
||||
excel_file_data=b'fake-xlsx',
|
||||
excel_file_name='result.xlsx',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
sync_schedule_run_excel_to_kb(task, run, process_inline=False)
|
||||
|
||||
assert run.kb_sync_status == 'queued'
|
||||
assert run.kb_document_id is not None
|
||||
assert run.kb_sync_job_id is not None
|
||||
assert enqueued == [run.kb_sync_job_id]
|
||||
|
||||
|
||||
def test_kb_sync_inline_processes_clean_and_sync_jobs(app, monkeypatch, tmp_path):
|
||||
from app.models import KbGroup, KbJob
|
||||
from app.services.schedule.kb_sync import process_schedule_kb_jobs_inline, sync_schedule_run_excel_to_kb
|
||||
|
||||
monkeypatch.setitem(app.config, 'KB_STORAGE_ROOT', str(tmp_path))
|
||||
clean_calls: list[int] = []
|
||||
sync_calls: list[int] = []
|
||||
|
||||
def _fake_clean(job_id: int):
|
||||
clean_calls.append(job_id)
|
||||
job = db.session.get(KbJob, job_id)
|
||||
sync_job = KbJob(
|
||||
job_type='sync_dify',
|
||||
status='queued',
|
||||
group_id=job.group_id,
|
||||
document_id=job.document_id,
|
||||
document_version_id=job.document_version_id,
|
||||
progress=0,
|
||||
message='pending',
|
||||
payload_json={'document_version_id': job.document_version_id},
|
||||
created_by_id=job.created_by_id,
|
||||
)
|
||||
db.session.add(sync_job)
|
||||
db.session.flush()
|
||||
run = db.session.get(ScheduleRun, (job.payload_json or {}).get('schedule_run_id'))
|
||||
if run:
|
||||
run.kb_sync_job_id = sync_job.id
|
||||
run.kb_sync_status = 'syncing'
|
||||
job.status = 'success'
|
||||
db.session.commit()
|
||||
return True, 'ok'
|
||||
|
||||
def _fake_sync(job_id: int):
|
||||
sync_calls.append(job_id)
|
||||
job = db.session.get(KbJob, job_id)
|
||||
job.status = 'success'
|
||||
db.session.commit()
|
||||
return True, 'ok'
|
||||
|
||||
monkeypatch.setattr('app.services.knowledge_cleaning.tasks.run_clean_job', _fake_clean)
|
||||
monkeypatch.setattr('app.services.knowledge_cleaning.tasks.run_sync_job', _fake_sync)
|
||||
|
||||
with app.app_context():
|
||||
admin = _mk_admin()
|
||||
group = KbGroup(name='RoHS KB Inline', is_active=True)
|
||||
db.session.add(group)
|
||||
db.session.commit()
|
||||
task = _mk_check_task(admin.id)
|
||||
task.kb_sync_enabled = True
|
||||
task.kb_group_id = group.id
|
||||
run = ScheduleRun(
|
||||
run_no='TEST-RUN-KB-INLINE',
|
||||
schedule_task_id=task.id,
|
||||
status='success',
|
||||
trigger_type='test',
|
||||
triggered_by_user_id=admin.id,
|
||||
excel_file_data=b'fake-xlsx',
|
||||
excel_file_name='result.xlsx',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
sync_schedule_run_excel_to_kb(task, run, enabled=True, process_inline=False)
|
||||
clean_job_id = run.kb_sync_job_id
|
||||
process_schedule_kb_jobs_inline(run)
|
||||
db.session.refresh(run)
|
||||
|
||||
assert run.kb_document_id is not None
|
||||
assert clean_calls == [clean_job_id]
|
||||
assert sync_calls
|
||||
assert run.kb_sync_status in ('success', 'ready', 'syncing')
|
||||
@@ -132,7 +132,7 @@ def test_shipping_notice_match_shortage_needs_human(app, client):
|
||||
|
||||
|
||||
def test_openapi_spec_public(app, client):
|
||||
app.config["SHIPPING_NOTICE_TOOL_API_BASE"] = "http://tool-api.example.com"
|
||||
app.config["HXOPS_TOOLS_API_BASE"] = "http://tool-api.example.com"
|
||||
res = client.get("/api/shipping-notice/tools/openapi.json")
|
||||
assert res.status_code == 200
|
||||
spec = res.get_json()
|
||||
@@ -804,6 +804,71 @@ def test_confirm_parse_does_not_skip_inventory_match(app, client):
|
||||
assert task.match_status is None
|
||||
|
||||
|
||||
def test_parse_notice_auto_continue_hides_parse_confirmation_hint(app, client):
|
||||
headers = _tool_headers(app)
|
||||
|
||||
create_res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers=headers,
|
||||
json={"source_type": "manual"},
|
||||
)
|
||||
task_id = create_res.get_json()["task_id"]
|
||||
|
||||
parse_res = client.post(
|
||||
"/api/shipping-notice/tools/parse_notice",
|
||||
headers=headers,
|
||||
json={
|
||||
"task_id": task_id,
|
||||
"structured": {
|
||||
"customer_name": "ACME",
|
||||
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
|
||||
"confidence": 0.95,
|
||||
},
|
||||
},
|
||||
)
|
||||
parse_data = parse_res.get_json()
|
||||
assert "【发货通知解析确认】" in parse_data["message"]
|
||||
assert "回复「确认」进入库存检查" not in parse_data["message"]
|
||||
assert parse_data.get("checkpoint") != "parse_review"
|
||||
|
||||
|
||||
def test_submit_decision_confirm_during_waiting_inventory_is_not_failed(app, client, tmp_path):
|
||||
headers = _tool_headers(app)
|
||||
trigger = tmp_path / "inventory_triggers"
|
||||
trigger.mkdir()
|
||||
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
|
||||
|
||||
create_res = client.post(
|
||||
"/api/shipping-notice/tools/create_task",
|
||||
headers=headers,
|
||||
json={"source_type": "manual"},
|
||||
)
|
||||
task_id = create_res.get_json()["task_id"]
|
||||
|
||||
parse_res = client.post(
|
||||
"/api/shipping-notice/tools/parse_notice",
|
||||
headers=headers,
|
||||
json={
|
||||
"task_id": task_id,
|
||||
"structured": {
|
||||
"customer_name": "ACME",
|
||||
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
|
||||
"confidence": 0.95,
|
||||
},
|
||||
},
|
||||
)
|
||||
assert parse_res.get_json()["status"] == "running"
|
||||
|
||||
confirm_res = client.post(
|
||||
"/api/shipping-notice/tools/submit_decision",
|
||||
headers=headers,
|
||||
json={"task_id": task_id, "decision": "confirm"},
|
||||
)
|
||||
confirm_data = confirm_res.get_json()
|
||||
assert confirm_data["status"] == "running"
|
||||
assert "RPA 库存导出" in confirm_data["message"]
|
||||
|
||||
|
||||
def test_submit_decision_by_conversation_id(app, client):
|
||||
headers = _tool_headers(app)
|
||||
|
||||
@@ -883,3 +948,4 @@ def test_chat_actions_empty_when_task_rejected(app):
|
||||
payload = build_chat_actions_payload(task)
|
||||
assert payload["checkpoint"] == "rejected"
|
||||
assert payload["action_buttons"] == []
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Tests for Excel table linearization chunk boundaries."""
|
||||
from __future__ import annotations
|
||||
|
||||
from edkb_system.contracts import Context
|
||||
from edkb_system.skills import table_linearize
|
||||
|
||||
|
||||
def test_condition_action_table_uses_double_newline_between_bullets():
|
||||
tables = [
|
||||
{
|
||||
'sheet': 'Rules',
|
||||
'headers': ['条件', '处理', '责任'],
|
||||
'rows': [
|
||||
['库存不足', '补货', '采购部'],
|
||||
['价格变动', '更新报价', '销售部'],
|
||||
],
|
||||
}
|
||||
]
|
||||
output = table_linearize.run(tables, Context())
|
||||
|
||||
assert '\n\n- 当' in output
|
||||
assert output.count('- 当') == 2
|
||||
assert output.startswith('## Sheet: Rules')
|
||||
|
||||
|
||||
def test_narrow_table_separates_data_rows_with_double_newline():
|
||||
tables = [
|
||||
{
|
||||
'sheet': 'Data',
|
||||
'headers': ['A', 'B', 'C'],
|
||||
'rows': [
|
||||
['1', '2', '3'],
|
||||
['4', '5', '6'],
|
||||
],
|
||||
}
|
||||
]
|
||||
output = table_linearize.run(tables, Context())
|
||||
|
||||
assert '| --- | --- | --- |' in output
|
||||
assert '\n\n|' in output
|
||||
assert '| 1 | 2 | 3 |' in output
|
||||
assert '| 4 | 5 | 6 |' in output
|
||||
assert '【行】' not in output
|
||||
|
||||
|
||||
def test_wide_table_uses_row_text_blocks():
|
||||
headers = [f'列{i}' for i in range(1, 11)]
|
||||
rows = [[str(i * 10 + j) for j in range(10)] for i in range(1, 4)]
|
||||
tables = [{'sheet': 'Wide', 'headers': headers, 'rows': rows}]
|
||||
|
||||
output = table_linearize.run(tables, Context())
|
||||
|
||||
assert '【行】' in output
|
||||
assert '\n\n' in output
|
||||
assert output.count('【行】') == 3
|
||||
assert '列1=10' in output
|
||||
assert '|' not in output.split('## Sheet: Wide')[-1]
|
||||
|
||||
|
||||
def test_multiple_sheets_separated_by_double_newline():
|
||||
tables = [
|
||||
{'sheet': 'S1', 'headers': ['X'], 'rows': [['a']]},
|
||||
{'sheet': 'S2', 'headers': ['Y'], 'rows': [['b']]},
|
||||
]
|
||||
output = table_linearize.run(tables, Context())
|
||||
|
||||
assert '## Sheet: S1' in output
|
||||
assert '## Sheet: S2' in output
|
||||
assert output.index('## Sheet: S2') > output.index('## Sheet: S1')
|
||||
assert '\n\n## Sheet: S2' in output
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
- 一个提交只做一件事(或同一类紧密相关的事)。
|
||||
- 提交信息要让不了解上下文的人也能快速理解“改了什么、为什么改”。
|
||||
- 优先使用英文提交信息,避免中英文混用造成解析不一致。
|
||||
- **`type` 与 `scope` 使用英文**;**`subject` 与 `body` 使用中文**,便于团队阅读且 scope 与代码模块一一对应。
|
||||
- 所有人遵循同一格式,减少代码评审和回溯成本。
|
||||
|
||||
## 2. 标准格式(必须)
|
||||
@@ -21,10 +21,10 @@
|
||||
|
||||
说明:
|
||||
|
||||
- `type`:变更类型(必填)。
|
||||
- `scope`:影响范围(选填,但推荐填写)。
|
||||
- `subject`:一句话概述(必填)。
|
||||
- `body`:详细说明(选填,建议在复杂改动时填写)。
|
||||
- `type`:变更类型(必填,**英文枚举**)。
|
||||
- `scope`:影响模块(选填但推荐,**英文 kebab-case**,与代码目录/包名一致)。
|
||||
- `subject`:一句话概述(必填,**中文**)。
|
||||
- `body`:详细说明(选填,建议在复杂改动时填写,**中文**)。
|
||||
- `footer`:关联任务、破坏性变更等(选填)。
|
||||
|
||||
## 3. Header 书写规则(必须)
|
||||
@@ -32,16 +32,18 @@
|
||||
Header 即第一行:`<type>(<scope>): <subject>`
|
||||
|
||||
- 必须小写 `type`,后接英文冒号和空格。
|
||||
- `subject` 使用祈使语气,简明描述动作,如 `add` `fix` `remove` `refactor`。
|
||||
- `scope` 小写英文,多词用 kebab-case(如 `shipping-notice`),**禁止中文**。
|
||||
- `subject` 使用祈使语气,简明描述动作,如「新增」「修复」「移除」「重构」。
|
||||
- 不以句号结尾。
|
||||
- Header 最大长度建议不超过 100 个字符。
|
||||
|
||||
正确示例:
|
||||
|
||||
```text
|
||||
feat(auth): add SMS login support
|
||||
fix(order): handle null coupon in checkout
|
||||
refactor(api): split user service and repository
|
||||
feat(schedule): 新增 RoHS 知识库同步字段
|
||||
fix(shipping-notice): 修复 Dify 入参解析空值问题
|
||||
refactor(rohs-check): 拆分 Agent 解析与工具 API
|
||||
build(jenkins): 保留最近 10 组镜像并自动清理旧镜像
|
||||
```
|
||||
|
||||
错误示例:
|
||||
@@ -50,6 +52,9 @@ refactor(api): split user service and repository
|
||||
Feat: Added login feature.
|
||||
fix: bug
|
||||
update code
|
||||
feat(排程): 新增 RoHS 知识库同步字段
|
||||
feat(schedule): add kb sync fields
|
||||
fix(shipping-notice): handle null coupon
|
||||
```
|
||||
|
||||
## 4. Type 定义(必须使用以下枚举)
|
||||
@@ -68,18 +73,33 @@ update code
|
||||
|
||||
## 5. Scope 约定(推荐)
|
||||
|
||||
Scope 用于快速识别改动模块,建议使用以下命名:
|
||||
Scope 应对齐代码模块,便于从提交信息定位到目录。选取规则:
|
||||
|
||||
- 按业务域:`auth` `order` `payment` `user`
|
||||
- 按技术层:`api` `db` `ui` `deps` `config`
|
||||
- 按工程对象:`docker` `github-actions` `eslint`
|
||||
1. 看主要改动文件所在目录(`backend/app/services/<module>/`、`backend/app/api/`、`frontend/src/features/`)。
|
||||
2. 目录名转 kebab-case:`shipping_notice` → `shipping-notice`,`rohs_check` → `rohs-check`。
|
||||
3. 跨模块改动选影响最大的模块;纯基建用 `jenkins`、`migration`、`deps`、`ci` 等。
|
||||
|
||||
| scope | 典型目录/模块 |
|
||||
| --- | --- |
|
||||
| `schedule` | `services/schedule/`、`api/schedule_admin`、前端 `features/admin/modules/schedules/` |
|
||||
| `shipping-notice` | `services/shipping_notice/`、`api/workspace_shipping_notice` |
|
||||
| `rohs-check` | `services/rohs_check*`、`api/rohs_check_tools` |
|
||||
| `knowledge-base` | `api/knowledge_base`、`services/knowledge_cleaning/` |
|
||||
| `chat` | `api/chat`、前端 chat 相关 |
|
||||
| `auth` | 登录认证 |
|
||||
| `admin` | 管理后台通用 |
|
||||
| `agents` | Agent 管理 |
|
||||
| `api` | 跨模块 API 层重构 |
|
||||
| `migration` | Alembic 迁移 |
|
||||
| `jenkins` / `ci` / `deps` | 工程与依赖 |
|
||||
|
||||
示例:
|
||||
|
||||
```text
|
||||
fix(payment): prevent duplicate callback handling
|
||||
ci(github-actions): cache pnpm store
|
||||
build(deps): upgrade axios to v1.9.0
|
||||
fix(shipping-notice): 防止回调重复处理
|
||||
ci(github-actions): 缓存 pnpm store
|
||||
build(deps): 升级 axios 至 v1.9.0
|
||||
perf(schedule): 优化排程查询分页加载
|
||||
```
|
||||
|
||||
## 6. Body 编写建议(复杂改动强烈建议)
|
||||
@@ -93,11 +113,10 @@ Body 与 Header 空一行,重点写“为什么”和“影响面”:
|
||||
示例:
|
||||
|
||||
```text
|
||||
feat(order): support partial shipment
|
||||
feat(shipping-notice): 支持部分发货
|
||||
|
||||
Allow splitting one order into multiple shipment packages to support
|
||||
warehouse stock differences. This change updates shipment status flow
|
||||
and adds validation for package-level tracking numbers.
|
||||
允许将同一订单拆分为多个发货包裹,以应对仓库库存差异。
|
||||
本次变更更新发货状态流转,并增加包裹级运单号校验。
|
||||
```
|
||||
|
||||
## 7. Footer 约定(推荐)
|
||||
@@ -112,7 +131,7 @@ and adds validation for package-level tracking numbers.
|
||||
若存在不兼容修改,必须明确标注:
|
||||
|
||||
```text
|
||||
BREAKING CHANGE: remove legacy /v1/login endpoint, use /v2/login instead.
|
||||
BREAKING CHANGE: 移除旧版 /v1/login 接口,请改用 /v2/login。
|
||||
```
|
||||
|
||||
## 8. 常见场景示例
|
||||
@@ -120,36 +139,36 @@ BREAKING CHANGE: remove legacy /v1/login endpoint, use /v2/login instead.
|
||||
新增功能:
|
||||
|
||||
```text
|
||||
feat(profile): add avatar upload API
|
||||
feat(auth): 新增头像上传接口
|
||||
```
|
||||
|
||||
修复问题:
|
||||
|
||||
```text
|
||||
fix(cart): recalculate total when item quantity is zero
|
||||
fix(shipping-notice): 商品数量为 0 时重新计算总价
|
||||
```
|
||||
|
||||
依赖升级:
|
||||
|
||||
```text
|
||||
build(deps): bump spring-boot to 3.3.2
|
||||
build(deps): 升级 spring-boot 至 3.3.2
|
||||
```
|
||||
|
||||
仅文档:
|
||||
|
||||
```text
|
||||
docs(readme): add local development instructions
|
||||
docs(readme): 补充本地开发说明
|
||||
```
|
||||
|
||||
回滚提交:
|
||||
|
||||
```text
|
||||
revert: feat(payment): support WeChat QR checkout
|
||||
revert: feat(shipping-notice): 支持微信扫码结账
|
||||
```
|
||||
|
||||
## 9. Pull Request 要求(建议)
|
||||
|
||||
- PR 标题建议复用同样格式:`type(scope): subject`
|
||||
- PR 标题建议复用同样格式:`type(scope): subject`(scope 英文模块名,subject 中文)
|
||||
- 一个 PR 尽量聚焦一个主题。
|
||||
- 合并前整理提交历史,避免大量无意义提交(如 `update` `fix` `test`)。
|
||||
|
||||
@@ -158,12 +177,14 @@ revert: feat(payment): support WeChat QR checkout
|
||||
- 禁止无语义提交信息:`update` `fix bug` `modify` `111`
|
||||
- 禁止把多个无关改动放在同一提交中。
|
||||
- 禁止漏写破坏性变更说明。
|
||||
- 禁止 `scope` 使用中文(如 `排程`、`发货通知`)。
|
||||
- 禁止 `subject` 使用英文(历史英文提交可保留,新提交统一中文)。
|
||||
|
||||
## 11. 自检清单(提交前)
|
||||
|
||||
- 提交类型是否正确(`feat/fix/...`)?
|
||||
- `subject` 是否清晰说明“做了什么”?
|
||||
- 是否需要 `scope` 来提升可读性?
|
||||
- `scope` 是否为英文模块名且与改动目录一致?
|
||||
- `subject` 是否为中文且清晰说明“做了什么”?
|
||||
- 是否存在破坏性变更,若有是否标注 `BREAKING CHANGE`?
|
||||
- 是否关联了任务编号(`Refs/Closes #id`)?
|
||||
|
||||
@@ -171,9 +192,10 @@ revert: feat(payment): support WeChat QR checkout
|
||||
|
||||
仓库已通过 Git Hook 自动校验提交信息,配置如下:
|
||||
|
||||
- **commitlint**:根目录 `commitlint.config.cjs`,规则与本文档对齐。
|
||||
- **commitlint**:根目录 `commitlint.config.cjs`,规则与本文档对齐(校验 type 格式与 Header 长度,不限制 subject 语言)。
|
||||
- **commit-msg Hook**:`.githooks/commit-msg`,在 `git commit` 时自动运行。
|
||||
- **安装**:`./scripts/install_git_hooks.sh`(会设置 `core.hooksPath` 并执行根目录 `npm install`)。
|
||||
- **Cursor IDE**:源代码管理 ✨「Generate commit message」仅读取根目录 **`.cursorrules`**;Agent 对话代提交读取 **`.cursor/rules/git-commit-zh.mdc`**。两者内容需保持一致。
|
||||
|
||||
详见 [Git Hooks 团队启用指南](../GIT_HOOKS.md)。
|
||||
|
||||
|
||||
@@ -22,6 +22,15 @@
|
||||
|
||||
## 3. 范围说明
|
||||
|
||||
### 3.x RoHS 文件检核补充需求
|
||||
|
||||
- **核心目标**:提供 RoHS 文件检核能力(发起检核、查询实时结果、获取报告、可选同步知识库、基于知识库查询历史报告)。对用户统一称为「检核」,不区分排程触发与对话触发等实现方式。
|
||||
- 新增 `RoHSCheckService` 作为统一判定入口,内部复用现有 Dify RoHS Workflow 中的 Prompt 与模型配置。
|
||||
- 新增 Dify Chatflow 显式 HTTP Tool,用于对话中发起检核、查询检核状态与展示结果;不使用 Agent 节点做逐条判定。
|
||||
- 检核成功或部分成功并生成 Excel 报告后,可按配置自动同步到指定知识库分组;Chatflow 通过 Knowledge Retrieval 检索已入库历史报告(与 Tool API 实时查询并存)。
|
||||
- 后台执行、定时触发、数据抓取与写回沿用现有任务引擎(实现细节对用户透明)。
|
||||
- Dify Chatflow 编排与 OpenAPI 导入见 [docs/rohs_chatflow_guide.md](rohs_chatflow_guide.md)。
|
||||
|
||||
### 3.1 本期范围
|
||||
|
||||
- 查询员工本人假期余额
|
||||
|
||||
@@ -16,6 +16,15 @@
|
||||
|
||||
## 2. 详细功能拆分
|
||||
|
||||
### RoHS 文件检核
|
||||
|
||||
| 功能项 | 状态 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| RoHSCheckService 判定入口 | 已实现 | 检核执行链路统一调用,内部复用现有 Dify Workflow |
|
||||
| Chatflow 发起与查询检核 | 已实现 | Tool API:查检核任务、启动检核、查检核批次、查最近检核、Excel 报告链接 |
|
||||
| RoHS Chatflow 编排手册 | 已文档化 | 见 [docs/rohs_chatflow_guide.md](rohs_chatflow_guide.md) |
|
||||
| 检核报告同步知识库 | 已实现 | 检核 success / partial_failed 且生成 Excel 后同步到所选知识库分组 |
|
||||
|
||||
### F-01 本人假期查询
|
||||
|
||||
#### 目标
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
# 知识库 Excel/CSV 切块与 Dify 同步
|
||||
|
||||
> 说明 Excel/CSV 清洗成 Markdown 后如何与 Dify custom 分段配合,以及版本目录下调试产物路径。
|
||||
|
||||
---
|
||||
|
||||
## 1. 问题背景
|
||||
|
||||
知识库 Excel(如 RoHS/供应商排程宽表)经 edkb 清洗成 Markdown 后,同步 Dify 时若使用默认 `process_rule.mode=automatic`,宽表 pipe 行或长段落会被 Dify 按 token/标点切散,导致**同一数据行字段落入不同 segment**,Hit testing 检索时上下文不完整。
|
||||
|
||||
典型症状:
|
||||
|
||||
- 问「某供应商编码 + 物料」命中片段只有半行字段;
|
||||
- Dify 文档分段数远大于 Excel 数据行数,或一行被拆成多段。
|
||||
|
||||
---
|
||||
|
||||
## 2. 改造后数据流
|
||||
|
||||
```text
|
||||
上传 xlsx/csv
|
||||
→ edkb loader_excel / loader_csv
|
||||
→ table_linearize(宽表行文本化 / 窄表 pipe 行 \n\n 分隔)
|
||||
→ document.md(写入 KB 版本目录)
|
||||
→ [可选] 04_chunks.jsonl / chunks/(调试,不传 Dify)
|
||||
→ sync_dify:create-by-text / update-by-text
|
||||
→ Dify process_rule.mode=custom(Excel/CSV 专用,separator=\n\n)
|
||||
```
|
||||
|
||||
### table_linearize 输出规则(摘要)
|
||||
|
||||
| 表类型 | 条件 | 输出格式 |
|
||||
| --- | --- | --- |
|
||||
| 条件/处理/责任表 | 表头含「条件」「处理」等关键词 | 每条 bullet 之间 `\n\n` |
|
||||
| 窄表 | 列数 ≤ 8 | 表头块 + 每个数据行单独 `\| ... \|` 块,行间 `\n\n` |
|
||||
| 宽表 | 列数 > 8 | `- 【行】列1=值1;列2=值2;...`,行间 `\n\n` |
|
||||
|
||||
示例(宽表,与 RoHS 排程类文件一致):
|
||||
|
||||
```markdown
|
||||
## Sheet: result
|
||||
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;...
|
||||
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 配置项(KB_DIFY_*)
|
||||
|
||||
可通过 **环境变量** 或管理台 **AppSetting** 覆盖;读取入口:`get_kb_dify_settings()`。
|
||||
|
||||
| 键 | 默认值 | 含义 |
|
||||
| --- | --- | --- |
|
||||
| `KB_DIFY_PROCESS_MODE` | `automatic` | 非 Excel/CSV 文档的 Dify 分段模式 |
|
||||
| `KB_DIFY_PROCESS_MODE_EXCEL` | `custom` | xlsx / xls / csv 专用分段模式 |
|
||||
| `KB_DIFY_SEGMENT_SEPARATOR` | `\n\n`(env 写 `\\n\\n`) | custom 模式通用分隔符 |
|
||||
| `KB_DIFY_SEGMENT_SEPARATOR_EXCEL` | `\n\n` | Excel/CSV custom 分隔符,与 table_linearize 对齐 |
|
||||
| `KB_DIFY_SEGMENT_MAX_TOKENS` | `800` | custom 模式 max_tokens |
|
||||
| `KB_DIFY_SEGMENT_CHUNK_OVERLAP` | `50` | custom 模式 chunk_overlap |
|
||||
| `KB_DIFY_REMOVE_URLS` | `false` | 映射 Dify `remove_urls_emails`;RoHS 等表含 PDF 链接,默认关闭 |
|
||||
|
||||
`.env` 示例:
|
||||
|
||||
```bash
|
||||
KB_DIFY_PROCESS_MODE=automatic
|
||||
KB_DIFY_PROCESS_MODE_EXCEL=custom
|
||||
KB_DIFY_SEGMENT_SEPARATOR_EXCEL=\n\n
|
||||
KB_DIFY_SEGMENT_MAX_TOKENS=800
|
||||
KB_DIFY_SEGMENT_CHUNK_OVERLAP=50
|
||||
KB_DIFY_REMOVE_URLS=false
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 版本目录与调试文件
|
||||
|
||||
清洗完成后,单版本目录结构(相对 `backend/data/kb/` 或部署挂载路径):
|
||||
|
||||
```text
|
||||
group_XXXX/document_XXXXXX/vXXX/
|
||||
su_schedule_5.xlsx # 原始上传
|
||||
document.md # 清洗结果(sync_dify 读取此文件)
|
||||
document_preview.md # 可选,含图片预览时
|
||||
04_chunks.jsonl # 可选,edkb 切块调试(不传 Dify)
|
||||
chunks/
|
||||
chunk_0000.md
|
||||
chunk_0001.md
|
||||
...
|
||||
```
|
||||
|
||||
- `document.md`:权威同步文本;
|
||||
- `04_chunks.jsonl`:edkb export 阶段产物,一行一个 chunk JSON,便于与 Dify segment 列表对照;
|
||||
- 若清洗失败回退占位,会出现 `*.preview.txt`(含 `clean_status=placeholder_success`),**不应**作为 Dify 同步源。
|
||||
|
||||
---
|
||||
|
||||
## 5. 手动验收(curl)
|
||||
|
||||
对已有 dataset 创建文本文档,模拟 Excel custom 分段(需替换 `DATASET_ID`、`API_KEY`):
|
||||
|
||||
```bash
|
||||
curl -X POST "http://<DIFY_HOST>/v1/datasets/<DATASET_ID>/document/create-by-text" \
|
||||
-H "Authorization: Bearer <API_KEY>" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"name": "excel-chunk-test.md",
|
||||
"text": "## Sheet: result\n\n- 【行】列1=a;列2=b。\n\n- 【行】列1=c;列2=d。",
|
||||
"indexing_technique": "high_quality",
|
||||
"doc_form": "text_model",
|
||||
"process_rule": {
|
||||
"mode": "custom",
|
||||
"rules": {
|
||||
"pre_processing_rules": [
|
||||
{"id": "remove_extra_spaces", "enabled": true},
|
||||
{"id": "remove_urls_emails", "enabled": false}
|
||||
],
|
||||
"segmentation": {
|
||||
"separator": "\n\n",
|
||||
"max_tokens": 800,
|
||||
"chunk_overlap": 50
|
||||
}
|
||||
}
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. 对比 Dify 分段与本地 jsonl
|
||||
|
||||
1. 打开 Dify 知识库 → 该文档 → **分段列表**,记录 segment 数量与首段内容;
|
||||
2. 打开版本目录 `04_chunks.jsonl`,统计非空行数:`wc -l 04_chunks.jsonl`;
|
||||
3. 宽表场景:segment 数应接近 **数据行数**(每行一条 `【行】` bullet,经 `\n\n` 切开);
|
||||
4. 在 Dify **Hit testing** 用表中存在的「供应商编码 + 物料名称」提问,应命中包含完整行字段的片段。
|
||||
|
||||
---
|
||||
|
||||
## 7. 回滚
|
||||
|
||||
| 层级 | 做法 |
|
||||
| --- | --- |
|
||||
| Dify 分段 | 设 `KB_DIFY_PROCESS_MODE_EXCEL=automatic`,并对已有 Excel 文档 **重新 sync_dify** |
|
||||
| 清洗格式 | git revert `table_linearize` 相关提交(document.md 格式恢复旧行为) |
|
||||
| 调试文件 | 忽略 `04_chunks.jsonl`,不影响线上同步 |
|
||||
|
||||
> **发版说明**:环境变量变更后,**已有 Excel 文档需触发重新 sync_dify** 才会应用新的 `process_rule`;仅重新清洗不会更新 Dify 远端分段规则。
|
||||
|
||||
---
|
||||
|
||||
## 8. 本地开发注意
|
||||
|
||||
- API 与 KB worker 须使用同一虚拟环境:
|
||||
|
||||
```bash
|
||||
cd backend && source .venv/bin/activate
|
||||
python run.py # 终端 1
|
||||
python worker_kb.py # 终端 2
|
||||
```
|
||||
|
||||
- `.env.shared` 中 `EDKB_FILE_TIMEOUT_SEC` 对 Word 等慢格式启用 spawn 超时;**Excel/CSV 已在代码中豁免**,避免 macOS 本地 `Operation not permitted`。
|
||||
- 相关代码:`edkb_system/skills/table_linearize.py`、`app/services/knowledge_cleaning/dify_sync_service.py`、`edkb_adapter.py`。
|
||||
|
||||
---
|
||||
|
||||
## 9. 相关测试
|
||||
|
||||
```bash
|
||||
cd backend && source .venv/bin/activate
|
||||
python -m pytest tests/test_dify_sync_process_rule.py \
|
||||
tests/test_table_linearize.py \
|
||||
tests/test_kb_excel_cleaning.py \
|
||||
tests/test_edkb_adapter_chunks.py \
|
||||
tests/test_edkb_file_timeout.py -q
|
||||
```
|
||||
@@ -0,0 +1,713 @@
|
||||
{
|
||||
"openapi": "3.0.3",
|
||||
"info": {
|
||||
"title": "HXOPS RoHS Check Tool API",
|
||||
"description": "RoHS 文件检核 Chatflow 显式 HTTP Tool API:检核任务列表、发起检核、查询检核批次、下载检核报告。鉴权:Authorization Bearer 或 X-Integration-Key。",
|
||||
"version": "1.0.0"
|
||||
},
|
||||
"servers": [
|
||||
{
|
||||
"url": "http://localhost:8890",
|
||||
"description": "HXOPS_TOOLS_API_BASE"
|
||||
}
|
||||
],
|
||||
"security": [
|
||||
{
|
||||
"BearerAuth": []
|
||||
},
|
||||
{
|
||||
"IntegrationKey": []
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"/api/rohs-check/tools/tasks": {
|
||||
"get": {
|
||||
"operationId": "list_rohs_tasks",
|
||||
"summary": "查询 RoHS 检核任务列表",
|
||||
"tags": [
|
||||
"RoHS Check"
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "成功",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ListTasksResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"$ref": "#/components/responses/Unauthorized"
|
||||
},
|
||||
"503": {
|
||||
"$ref": "#/components/responses/MissingAuth"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/rohs-check/tools/tasks/run": {
|
||||
"post": {
|
||||
"operationId": "run_rohs_check",
|
||||
"summary": "异步启动 RoHS 检核",
|
||||
"tags": [
|
||||
"RoHS Check"
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/RunCheckRequest"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "启动成功",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/RunCheckSuccessResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "RoHS 检核进行中,全局不可重复启动",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/CheckRunningResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"401": {
|
||||
"$ref": "#/components/responses/Unauthorized"
|
||||
},
|
||||
"404": {
|
||||
"$ref": "#/components/responses/TaskNotFound"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/rohs-check/tools/runs": {
|
||||
"get": {
|
||||
"operationId": "list_rohs_runs",
|
||||
"summary": "查询 RoHS 检核批次列表",
|
||||
"tags": [
|
||||
"RoHS Check"
|
||||
],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "task_id",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"example": 12
|
||||
},
|
||||
"description": "可选;指定检核任务 ID 时只返回该任务批次"
|
||||
},
|
||||
{
|
||||
"name": "limit",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 100,
|
||||
"default": 20
|
||||
},
|
||||
"description": "返回条数,最大 100"
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "成功",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ListRunsResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"$ref": "#/components/responses/Unauthorized"
|
||||
},
|
||||
"404": {
|
||||
"$ref": "#/components/responses/TaskNotFound"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/rohs-check/tools/runs/{run_id}": {
|
||||
"get": {
|
||||
"operationId": "get_rohs_run",
|
||||
"summary": "查询指定检核批次",
|
||||
"tags": [
|
||||
"RoHS Check"
|
||||
],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "run_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"example": 88
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "成功",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/GetRunResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"$ref": "#/components/responses/Unauthorized"
|
||||
},
|
||||
"404": {
|
||||
"$ref": "#/components/responses/RunNotFound"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/rohs-check/tools/tasks/{task_id}/latest-run": {
|
||||
"get": {
|
||||
"operationId": "get_latest_rohs_run",
|
||||
"summary": "查询检核任务最近一次检核",
|
||||
"tags": [
|
||||
"RoHS Check"
|
||||
],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "task_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"example": 12
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "成功",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/GetRunResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"$ref": "#/components/responses/Unauthorized"
|
||||
},
|
||||
"404": {
|
||||
"$ref": "#/components/responses/RunNotFound"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/rohs-check/tools/runs/{run_id}/excel": {
|
||||
"get": {
|
||||
"operationId": "download_rohs_run_excel",
|
||||
"summary": "下载检核报告 Excel(短期签名 token)",
|
||||
"tags": [
|
||||
"RoHS Check"
|
||||
],
|
||||
"security": [],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "run_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"example": 88
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "token",
|
||||
"in": "query",
|
||||
"required": true,
|
||||
"description": "由 get_rohs_run 返回的 excel.download_url 中的 JWT,有效期 600 秒",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Excel 文件流",
|
||||
"content": {
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"format": "binary"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"$ref": "#/components/responses/ExcelNotReady"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
"securitySchemes": {
|
||||
"BearerAuth": {
|
||||
"type": "http",
|
||||
"scheme": "bearer",
|
||||
"description": "ROHS_TOOLS_API_KEY 或 INTEGRATION_API_KEY"
|
||||
},
|
||||
"IntegrationKey": {
|
||||
"type": "apiKey",
|
||||
"in": "header",
|
||||
"name": "X-Integration-Key",
|
||||
"description": "与 Bearer 二选一"
|
||||
}
|
||||
},
|
||||
"schemas": {
|
||||
"TaskSummary": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"task_id": {
|
||||
"type": "integer",
|
||||
"example": 12
|
||||
},
|
||||
"task_no": {
|
||||
"type": "string",
|
||||
"example": "CHK202606090001"
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"example": "RoHS 自动检核"
|
||||
},
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"last_status": {
|
||||
"type": "string",
|
||||
"nullable": true,
|
||||
"example": "success"
|
||||
},
|
||||
"last_run_at": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"nullable": true
|
||||
},
|
||||
"next_run_at": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"nullable": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"RunExcel": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"file_name": {
|
||||
"type": "string",
|
||||
"nullable": true,
|
||||
"example": "RUN202606090001.xlsx"
|
||||
},
|
||||
"file_size": {
|
||||
"type": "integer",
|
||||
"nullable": true,
|
||||
"example": 45678
|
||||
},
|
||||
"download_url": {
|
||||
"type": "string",
|
||||
"nullable": true,
|
||||
"example": "http://192.168.100.192:8891/api/rohs-check/tools/runs/88/excel?token=..."
|
||||
}
|
||||
}
|
||||
},
|
||||
"RunKnowledgeBase": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"sync_status": {
|
||||
"type": "string",
|
||||
"nullable": true,
|
||||
"enum": [
|
||||
"skipped",
|
||||
"queued",
|
||||
"cleaning",
|
||||
"syncing",
|
||||
"ready",
|
||||
"success",
|
||||
"failed"
|
||||
]
|
||||
},
|
||||
"group_id": {
|
||||
"type": "integer",
|
||||
"nullable": true
|
||||
},
|
||||
"document_id": {
|
||||
"type": "integer",
|
||||
"nullable": true
|
||||
},
|
||||
"document_version_id": {
|
||||
"type": "integer",
|
||||
"nullable": true
|
||||
},
|
||||
"sync_job_id": {
|
||||
"type": "integer",
|
||||
"nullable": true
|
||||
},
|
||||
"error_message": {
|
||||
"type": "string",
|
||||
"nullable": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"RunDetail": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"run_id": {
|
||||
"type": "integer",
|
||||
"example": 88
|
||||
},
|
||||
"run_no": {
|
||||
"type": "string",
|
||||
"example": "RUN202606090001"
|
||||
},
|
||||
"task_id": {
|
||||
"type": "integer",
|
||||
"example": 12
|
||||
},
|
||||
"task_name": {
|
||||
"type": "string",
|
||||
"example": "RoHS 自动检核"
|
||||
},
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"running",
|
||||
"success",
|
||||
"partial_failed",
|
||||
"failed",
|
||||
"queued",
|
||||
"cancelled"
|
||||
]
|
||||
},
|
||||
"total_count": {
|
||||
"type": "integer"
|
||||
},
|
||||
"success_count": {
|
||||
"type": "integer"
|
||||
},
|
||||
"failed_count": {
|
||||
"type": "integer"
|
||||
},
|
||||
"skipped_count": {
|
||||
"type": "integer"
|
||||
},
|
||||
"started_at": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"nullable": true
|
||||
},
|
||||
"finished_at": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"nullable": true
|
||||
},
|
||||
"duration_ms": {
|
||||
"type": "integer",
|
||||
"nullable": true
|
||||
},
|
||||
"error_message": {
|
||||
"type": "string",
|
||||
"nullable": true
|
||||
},
|
||||
"excel": {
|
||||
"$ref": "#/components/schemas/RunExcel"
|
||||
},
|
||||
"knowledge_base": {
|
||||
"$ref": "#/components/schemas/RunKnowledgeBase"
|
||||
}
|
||||
}
|
||||
},
|
||||
"ListTasksResponse": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"ok",
|
||||
"tasks"
|
||||
],
|
||||
"properties": {
|
||||
"ok": {
|
||||
"type": "boolean",
|
||||
"example": true
|
||||
},
|
||||
"tasks": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/TaskSummary"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"RunCheckRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"task_id": {
|
||||
"type": "integer",
|
||||
"example": 12
|
||||
},
|
||||
"task_no": {
|
||||
"type": "string",
|
||||
"example": "CHK202606090001"
|
||||
},
|
||||
"trigger_source": {
|
||||
"type": "string",
|
||||
"default": "dify_chatflow"
|
||||
},
|
||||
"conversation_id": {
|
||||
"type": "string",
|
||||
"nullable": true
|
||||
},
|
||||
"user_message": {
|
||||
"type": "string",
|
||||
"nullable": true
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"task_id"
|
||||
],
|
||||
"description": "Chatflow Start 节点固定配置 task_id;后端仍兼容 task_no,但 RoHS Chatflow 不使用任务选择流程"
|
||||
},
|
||||
"RunCheckSuccessResponse": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"ok",
|
||||
"message",
|
||||
"run"
|
||||
],
|
||||
"properties": {
|
||||
"ok": {
|
||||
"type": "boolean",
|
||||
"example": true
|
||||
},
|
||||
"message": {
|
||||
"type": "string",
|
||||
"example": "检核已启动"
|
||||
},
|
||||
"run": {
|
||||
"$ref": "#/components/schemas/RunDetail"
|
||||
}
|
||||
}
|
||||
},
|
||||
"CheckRunningResponse": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"ok",
|
||||
"error_code",
|
||||
"message",
|
||||
"run"
|
||||
],
|
||||
"properties": {
|
||||
"ok": {
|
||||
"type": "boolean",
|
||||
"example": false
|
||||
},
|
||||
"error_code": {
|
||||
"type": "string",
|
||||
"example": "check_running"
|
||||
},
|
||||
"message": {
|
||||
"type": "string",
|
||||
"example": "该检核任务正在执行中,请稍后查询结果"
|
||||
},
|
||||
"run": {
|
||||
"$ref": "#/components/schemas/RunDetail"
|
||||
}
|
||||
}
|
||||
},
|
||||
"GetRunResponse": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"ok",
|
||||
"run"
|
||||
],
|
||||
"properties": {
|
||||
"ok": {
|
||||
"type": "boolean",
|
||||
"example": true
|
||||
},
|
||||
"run": {
|
||||
"$ref": "#/components/schemas/RunDetail"
|
||||
}
|
||||
}
|
||||
},
|
||||
"ListRunsResponse": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"ok",
|
||||
"runs",
|
||||
"count"
|
||||
],
|
||||
"properties": {
|
||||
"ok": {
|
||||
"type": "boolean",
|
||||
"example": true
|
||||
},
|
||||
"count": {
|
||||
"type": "integer",
|
||||
"example": 2
|
||||
},
|
||||
"runs": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/RunDetail"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"ErrorResponse": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"ok",
|
||||
"error_code",
|
||||
"message"
|
||||
],
|
||||
"properties": {
|
||||
"ok": {
|
||||
"type": "boolean",
|
||||
"example": false
|
||||
},
|
||||
"error_code": {
|
||||
"type": "string"
|
||||
},
|
||||
"message": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"Unauthorized": {
|
||||
"description": "鉴权失败",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ErrorResponse"
|
||||
},
|
||||
"examples": {
|
||||
"missing_auth": {
|
||||
"value": {
|
||||
"ok": false,
|
||||
"error_code": "missing_auth",
|
||||
"message": "missing_auth"
|
||||
}
|
||||
},
|
||||
"invalid_auth": {
|
||||
"value": {
|
||||
"ok": false,
|
||||
"error_code": "invalid_auth",
|
||||
"message": "invalid_auth"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"MissingAuth": {
|
||||
"description": "服务端未配置 ROHS_TOOLS_API_KEY / INTEGRATION_API_KEY",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ErrorResponse"
|
||||
},
|
||||
"example": {
|
||||
"ok": false,
|
||||
"error_code": "missing_auth",
|
||||
"message": "ROHS_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"BadRequest": {
|
||||
"description": "请求参数无效",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ErrorResponse"
|
||||
},
|
||||
"example": {
|
||||
"ok": false,
|
||||
"error_code": "invalid_request",
|
||||
"message": "invalid_request"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"TaskNotFound": {
|
||||
"description": "检核任务不存在",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ErrorResponse"
|
||||
},
|
||||
"example": {
|
||||
"ok": false,
|
||||
"error_code": "task_not_found",
|
||||
"message": "task_not_found"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"RunNotFound": {
|
||||
"description": "检核批次不存在",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ErrorResponse"
|
||||
},
|
||||
"example": {
|
||||
"ok": false,
|
||||
"error_code": "run_not_found",
|
||||
"message": "run_not_found"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"ExcelNotReady": {
|
||||
"description": "Excel 尚未生成",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ErrorResponse"
|
||||
},
|
||||
"example": {
|
||||
"ok": false,
|
||||
"error_code": "excel_not_ready",
|
||||
"message": "excel_not_ready"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
# HXOPS 前端重构架构方案
|
||||
|
||||
> 更新时间:2026-06-02
|
||||
> 更新时间:2026-06-11
|
||||
> 适用范围:`frontend/` 目录
|
||||
> 文档定位:定义推荐的目标架构(Feature-Module + Composables + Pinia),作为后续分阶段重构的基准。
|
||||
|
||||
@@ -35,25 +35,27 @@
|
||||
|
||||
```text
|
||||
frontend/src/
|
||||
├── app/ # 应用启动层
|
||||
│ ├── main.ts
|
||||
│ ├── App.vue
|
||||
├── main.ts # Vite 入口(保留在 src 根,不迁入 app/)
|
||||
├── App.vue # 根组件(保留在 src 根)
|
||||
├── app/ # 应用基础设施(路由 / 插件)
|
||||
│ ├── router/
|
||||
│ │ ├── index.ts # 汇总各域路由
|
||||
│ │ ├── guards.ts # 认证 / 权限守卫(从 router/index.ts 抽出)
|
||||
│ │ ├── guards.ts # 认证 / 权限守卫
|
||||
│ │ └── routes/ # 按业务域拆分路由表
|
||||
│ │ ├── auth.routes.ts
|
||||
│ │ ├── chat.routes.ts
|
||||
│ │ ├── admin.routes.ts
|
||||
│ │ ├── workspace.routes.ts
|
||||
│ │ └── kb.routes.ts
|
||||
│ └── plugins/
|
||||
│ ├── i18n.ts # 仅注册 i18n 实例,messages 外置
|
||||
│ └── pinia.ts
|
||||
│
|
||||
├── shared/ # 跨域共享(无业务语义)
|
||||
│ ├── api/
|
||||
│ │ ├── client.ts # requestJson、BusinessError、响应 envelope 解析
|
||||
│ │ └── types.ts # 通用 API 类型
|
||||
│ │ ├── client.ts # requestJson、BusinessError(权威实现)
|
||||
│ │ └── types.ts # 通用 API 类型(待补充)
|
||||
│ ├── types/
|
||||
│ │ └── schedule.types.ts # admin / workspace 共用排程类型
|
||||
│ ├── composables/ # useTheme、useIsMobile、useMessage 等
|
||||
│ ├── components/ # 通用 UI:Dialog、DataTable、EmptyState、Pagination
|
||||
│ ├── layouts/ # AppShell、ChatShell、MinimalShell、MarketingShell
|
||||
@@ -70,13 +72,23 @@ frontend/src/
|
||||
│ │ ├── composables/
|
||||
│ │ │ └── useAuth.ts
|
||||
│ │ ├── views/
|
||||
│ │ │ ├── WorkspaceView.vue
|
||||
│ │ │ ├── LoginView.vue
|
||||
│ │ │ └── ResetPasswordView.vue
|
||||
│ │ └── components/
|
||||
│ │
|
||||
│ ├── workspace/ # AI 工作台(自 auth 拆出,2026-06)
|
||||
│ │ ├── api/
|
||||
│ │ │ └── schedule.api.ts # 工作台排程记录
|
||||
│ │ ├── views/
|
||||
│ │ │ └── WorkspaceLayout.vue
|
||||
│ │ ├── pages/ # HomePage、ProfilePage、ScheduleRunsPage 等
|
||||
│ │ ├── composables/
|
||||
│ │ └── components/
|
||||
│ │
|
||||
│ ├── chat/
|
||||
│ │ ├── api/
|
||||
│ │ │ └── chat.api.ts
|
||||
│ │ │ ├── chat.api.ts
|
||||
│ │ │ └── shipping.api.ts # 货代发货(/api/workspace/shipping-tasks)
|
||||
│ │ ├── types/
|
||||
│ │ │ └── chat.types.ts
|
||||
│ │ ├── stores/
|
||||
@@ -85,6 +97,8 @@ frontend/src/
|
||||
│ │ │ ├── useChat.ts # SSE 流式对话(保留并增强)
|
||||
│ │ │ ├── useChatSessions.ts
|
||||
│ │ │ └── useSourceFiles.ts # 源文件 / 检索来源逻辑
|
||||
│ │ ├── page/ # useChatPage 编排子模块(composable,非路由页)
|
||||
│ │ ├── history/ # 跨 Agent 历史(HistoryPage.vue)
|
||||
│ │ ├── views/
|
||||
│ │ │ └── ChatView.vue # 页面编排,目标 < 300 行
|
||||
│ │ └── components/
|
||||
@@ -98,7 +112,7 @@ frontend/src/
|
||||
│ ├── admin/
|
||||
│ │ ├── api/
|
||||
│ │ │ ├── admin.api.ts
|
||||
│ │ │ └── schedule.api.ts
|
||||
│ │ │ └── schedule.api.ts # 管理后台定时任务
|
||||
│ │ ├── stores/
|
||||
│ │ │ └── admin-nav.store.ts
|
||||
│ │ ├── views/
|
||||
@@ -115,7 +129,7 @@ frontend/src/
|
||||
│ │ │ ├── announcements/
|
||||
│ │ │ ├── questions/
|
||||
│ │ │ ├── wecom/
|
||||
│ │ │ ├── schedules/
|
||||
│ │ │ ├── schedules/ # types/utils + context + panel/overlays(见 §10.5)
|
||||
│ │ │ └── knowledge-base/
|
||||
│ │ └── components/
|
||||
│ │ └── AdminNav.vue
|
||||
@@ -123,9 +137,16 @@ frontend/src/
|
||||
│ └── kb/
|
||||
│ ├── api/
|
||||
│ │ └── kb.api.ts
|
||||
│ ├── types/
|
||||
│ │ └── kb-workspace.types.ts
|
||||
│ ├── utils/ # 列表/展示/工作流/路径上传纯函数
|
||||
│ ├── composables/
|
||||
│ │ ├── useKbWorkspace.ts # 编排入口
|
||||
│ │ └── kb-workspace/ # state / computed / data / pathUpload / documents / modals
|
||||
│ ├── views/
|
||||
│ │ └── KbWorkspaceView.vue
|
||||
│ └── components/ # 迁移现有 components/kb/*
|
||||
│ │ ├── KbWorkspaceView.vue # 作业面主内容壳
|
||||
│ │ └── components/KbWorkspaceOverlays.vue # 弹窗层
|
||||
│ └── components/ # 治理面:KbAdminPanel、Dify*Dialog
|
||||
│
|
||||
├── locales/ # i18n 按语言 + 业务域拆分
|
||||
│ ├── zh-CN/
|
||||
@@ -147,20 +168,20 @@ frontend/src/
|
||||
|
||||
| 现有路径 | 目标路径 | 说明 |
|
||||
|----------|----------|------|
|
||||
| `src/main.ts`、`src/App.vue` | `app/` | 启动与全局插件注册 |
|
||||
| `src/main.ts`、`src/App.vue` | **保留 `src/` 根目录** | Vite 入口约定;不迁入 `app/` |
|
||||
| `src/router/index.ts` | `app/router/` | 路由表与守卫拆分 |
|
||||
| `src/api/client.ts` | `shared/api/client.ts` | 保持不变,作为统一 HTTP 层 |
|
||||
| `src/api/*.ts` | `features/*/api/` | 按业务域归属 |
|
||||
| `src/api/client.ts` | `shared/api/client.ts` | 权威实现;`src/api/client.ts` deprecated 转发 |
|
||||
| `src/api/*.ts` | `features/*/api/` | 按业务域归属(KB 已迁入,见 §16) |
|
||||
| `src/composables/`(通用) | `shared/composables/` | useTheme、useMessage 等 |
|
||||
| `src/composables/useChat.ts` | `features/chat/composables/` | 聊天域专属 |
|
||||
| `src/components/`(通用 Dialog 等) | `shared/components/` | 跨域复用 UI |
|
||||
| `src/components/kb/` | `features/kb/components/` | 知识库域 |
|
||||
| `src/components/kb/` | `features/kb/components/` | ✅ 已迁入(2026-06-11) |
|
||||
| `src/layouts/` | `shared/layouts/` | 页面壳层 |
|
||||
| `src/utils/` | `shared/utils/` | 纯工具函数 |
|
||||
| `src/styles/` | `shared/styles/` | 设计 token 与全局样式 |
|
||||
| `src/views/AdminView.vue` | `features/admin/modules/*/` | 拆为 12+ 子模块页面 |
|
||||
| `src/views/ChatView.vue` | `features/chat/` | View + 多个子组件 |
|
||||
| `src/views/WorkspaceView.vue` | `features/auth/views/` | 登录 / 工作台 |
|
||||
| `src/views/WorkspaceView.vue` | `features/workspace/` + `features/auth/views/LoginView.vue` | 登录与工作台分离 |
|
||||
| `src/i18n.ts` | `locales/` | 按语言、域拆分 JSON |
|
||||
|
||||
---
|
||||
@@ -299,11 +320,24 @@ flowchart TB
|
||||
|
||||
### 4.4 kb(知识库)
|
||||
|
||||
**职责拆分(治理面 vs 作业面):**
|
||||
|
||||
| 入口 | 路由 | 组件 | 职责 |
|
||||
|------|------|------|------|
|
||||
| 管理控制台 | `/admin/knowledge-base` | `KbAdminPanel` | 分组 CRUD、Dify 配置、健康检查、任务队列 |
|
||||
| 工作台 | `/workspace/knowledge-base` | `KbWorkspaceView`(`embedded`) | 只读选分组 → 文档上传/清洗/同步 |
|
||||
| 兼容 | `/kb/workspace` → `/workspace/knowledge-base` | redirect | 旧书签 |
|
||||
| 兼容 | `/kb/admin` → `/admin/knowledge-base` | redirect | 旧书签 |
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| 路由 | `/kb/workspace`;`/kb/admin` redirect 至 `/admin/knowledge-base` |
|
||||
| 组件 | 迁移 `components/kb/KbAdminPanel.vue`、`DifyHealthDialog.vue` 等 |
|
||||
| 迁移来源 | `views/KbWorkspaceView.vue`(~2400 行)、`api/kb.ts` |
|
||||
| API | `features/kb/api/kb.api.ts`(`src/api/kb.ts` 已删除) |
|
||||
| 作业面编排 | `useKbWorkspace` + `kb-workspace/*` 子 composable |
|
||||
| 权限 | `hasKnowledgeBaseAccess` / 作业面批量操作:`role === 'admin'` |
|
||||
| i18n | `locales/{en,zh-CN,zh-TW,th}/kb.json` |
|
||||
| 迁移来源 | 原 `views/KbWorkspaceView.vue`(~3000 行 monolith) |
|
||||
|
||||
详见 §16。
|
||||
|
||||
---
|
||||
|
||||
@@ -343,7 +377,7 @@ resolve: {
|
||||
```text
|
||||
features/chat/views/ChatView.vue
|
||||
✅ import { useChat } from '../composables/useChat'
|
||||
✅ import { BaseDialog } from '@/shared/components/BaseDialog.vue'
|
||||
✅ import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue'
|
||||
✅ import { listChatSessions } from '../api/chat.api'
|
||||
❌ import { listAdminUsers } from '@/features/admin/api/admin.api' // 跨 feature 禁止
|
||||
```
|
||||
@@ -367,11 +401,13 @@ Phase 0 目标:搭好基础设施,**不迁移现有 views**,旧代码可
|
||||
| Auth Store | `features/auth/stores/auth.store.ts` |
|
||||
| Auth Composable | `features/auth/composables/useAuth.ts` |
|
||||
| Chat Store 骨架 | `features/chat/stores/chat.store.ts` |
|
||||
| API 转发层 | `shared/api/client.ts` → 现有 `api/client.ts` |
|
||||
| API 转发层 | `shared/api/client.ts` 为权威实现;`src/api/client.ts` deprecated 转发 |
|
||||
| 路由常量 | `shared/constants/routes.ts` |
|
||||
| 兼容入口 | `router/index.ts` re-export `app/router` |
|
||||
|
||||
### 7.2 启动顺序(main.ts)
|
||||
### 7.2 启动顺序(`src/main.ts`)
|
||||
|
||||
> **约定**:`main.ts` / `App.vue` 留在 `src/` 根目录,与 Vite `index.html` 入口一致;`app/` 仅放 router、plugins 等可拆分的基础设施。
|
||||
|
||||
```typescript
|
||||
app.use(pinia);
|
||||
@@ -404,49 +440,502 @@ Phase 1 已完成,见 §8。
|
||||
|
||||
---
|
||||
|
||||
## 8. Phase 1 落地说明(已实现)
|
||||
## 8. Phase 1 落地说明(已实现,后续全量拆分见 §9)
|
||||
|
||||
Phase 1 目标:管理后台嵌套子路由 + 首个独立模块 `agents`。
|
||||
|
||||
### 8.1 路由结构
|
||||
### 8.1 路由结构(初版)
|
||||
|
||||
| URL | 组件 | 说明 |
|
||||
|-----|------|------|
|
||||
| `/admin` | redirect → `/admin/dashboard` | |
|
||||
| `/admin/agents` | `AgentsPage.vue` | **已独立拆分** |
|
||||
| `/admin/dashboard` 等 | `AdminLegacyPage.vue` | 内嵌 `AdminView`(content-only) |
|
||||
| `/admin/reports/:table?` | `AdminLegacyPage.vue` | 报表模块 |
|
||||
| `/admin/agents` | `AgentsPage.vue` | **首个独立拆分** |
|
||||
| `/admin/dashboard` 等 | `AdminLegacyPage.vue` | 内嵌 `AdminView`(content-only,已移除) |
|
||||
| `/admin?module=xxx` | redirect | 兼容旧链接,跳转至 `/admin/xxx` |
|
||||
|
||||
### 8.2 新增文件(均含文件头注释)
|
||||
> **2026-06 更新**:全部 admin 子模块已独立,见 §9。
|
||||
|
||||
### 8.2 初版新增文件
|
||||
|
||||
```text
|
||||
features/admin/
|
||||
├── views/AdminLayout.vue # 壳层:顶栏 + AdminNav + router-view
|
||||
├── views/AdminLegacyPage.vue # 未拆分模块的过渡容器
|
||||
├── components/AdminNav.vue # 子路由导航
|
||||
├── modules/agents/
|
||||
│ ├── AgentsPage.vue
|
||||
│ ├── composables/useAgentsAdmin.ts
|
||||
│ └── components/{AgentTestModal,AgentPermissionModal}.vue
|
||||
├── views/AdminLayout.vue
|
||||
├── modules/agents/ ...
|
||||
├── stores/admin-nav.store.ts
|
||||
├── composables/useAdminNavBadges.ts
|
||||
├── constants/modules.ts
|
||||
└── types/{admin,agent}.types.ts
|
||||
└── ...
|
||||
```
|
||||
|
||||
### 8.3 构建验证
|
||||
|
||||
`npm run build` 通过;`AgentsPage`、`AdminLayout`、`AdminLegacyPage` 已代码分割为独立 chunk。
|
||||
`npm run build` 通过。
|
||||
|
||||
### 8.4 下一步(Phase 2)
|
||||
### 8.4 下一步
|
||||
|
||||
- 继续拆分 `users`、`permissions` 等 admin 模块
|
||||
- 拆分 `ChatView.vue` 为 `features/chat/components/*`
|
||||
Admin 全量拆分 → §9;Chat 拆分 → §10。
|
||||
|
||||
---
|
||||
|
||||
## 9. 相关文档
|
||||
## 9. Phase 1.5 Admin 全量拆分(已实现)
|
||||
|
||||
Phase 1.5 目标:移除 `AdminView.vue` / `AdminLegacyPage.vue`,全部 `config.admin.modules` 对应独立页面。
|
||||
|
||||
### 9.1 路由结构
|
||||
|
||||
| URL | 组件 |
|
||||
|-----|------|
|
||||
| `/admin/dashboard` | `DashboardPage.vue` |
|
||||
| `/admin/agents` | `AgentsPage.vue` |
|
||||
| `/admin/users` | `UsersPage.vue` |
|
||||
| `/admin/departments` | `DepartmentsPage.vue` |
|
||||
| `/admin/permissions` | `PermissionsPage.vue` |
|
||||
| `/admin/requests` | `RequestsPage.vue` |
|
||||
| `/admin/approvals` | `ApprovalsPage.vue` |
|
||||
| `/admin/announcements` | `AnnouncementsPage.vue` |
|
||||
| `/admin/questions` | `QuestionsPage.vue` |
|
||||
| `/admin/wecom` | `WecomPage.vue` |
|
||||
| `/admin/schedules` | `SchedulesPage.vue` |
|
||||
| `/admin/knowledge-base` | `KnowledgeBasePage.vue` |
|
||||
| `/admin/platform-apps` | `PlatformAppsPage.vue` |
|
||||
| `/admin/reports/:table?` | `ReportsPage.vue` |
|
||||
|
||||
### 9.2 模块目录
|
||||
|
||||
```text
|
||||
features/admin/modules/
|
||||
├── dashboard/ ├── agents/ ├── users/
|
||||
├── departments/ ├── permissions/ ├── requests/
|
||||
├── approvals/ ├── announcements/├── questions/
|
||||
├── wecom/ ├── schedules/ ├── knowledge-base/
|
||||
├── platform-apps/ └── reports/
|
||||
└── composables/use*Admin.ts + components/
|
||||
```
|
||||
|
||||
**schedules/**(2026-06 瘦身,详见 §10.5):`SchedulesPage.vue` 薄壳 + `useSchedulesAdmin` + `schedule-admin/*` + `schedules.context` + 6 个子组件(Header / Overview / Workbench / Overlays / TestRun / CreateEdit)。
|
||||
|
||||
### 9.3 构建验证
|
||||
|
||||
`npm run build` 通过;`AdminView.vue` 已删除。
|
||||
|
||||
---
|
||||
|
||||
## 10. Phase 2 Chat 域落地说明(已实现)
|
||||
|
||||
Phase 2 Chat 目标:将原 `views/ChatView.vue`(~5500 行)拆为 feature 模块,页面壳层 < 50 行。
|
||||
|
||||
### 10.1 已完成项
|
||||
|
||||
| 项 | 路径 / 说明 |
|
||||
|----|-------------|
|
||||
| 页面壳层 | `features/chat/views/ChatView.vue`(~19 行:`useChatPage()` + `provide` + `ChatViewContent` / `ChatViewOverlays`) |
|
||||
| 主编排 | `composables/useChatPage.ts`(~400 行,组合 `page/*` 子模块与各域 composable) |
|
||||
| 页面子模块 | `features/chat/page/*`:用户、本地消息、弹窗、语音、Markdown、会话、发送、handlers 打包 |
|
||||
| 出货子模块 | `features/chat/shipping/*`:纯函数 + `useChatShippingRefresh` / Menu / Upload / Send handler 工厂;`useChatShipping.ts` ~360 行 |
|
||||
| 请假子模块 | `features/chat/leave/*`:意图解析、OA 登录、代理人选择、表单提交、流程拦截;`useChatLeave.ts` ~130 行 |
|
||||
| 子 composable | `useChatAgent`、`useChatAttachments`、`useChatRouteSync`、`useChatBrowserPanel`、`useChatQueryPreview`、`useChatGuides`、`useChatScroll` 等 |
|
||||
| 子组件 | `ChatSidebar`、`ChatMessageList`、`ChatInputBar`、`ChatMessageBubble`、`ChatViewContent`、`ChatViewOverlays`、弹窗等 |
|
||||
| 路由 lazy | `app/router/routes/chat.routes.ts` → `features/chat/views/ChatView.vue` |
|
||||
| API | `features/chat/api/chat.api.ts`(`src/api/chat.ts` deprecated 转发) |
|
||||
| 货代 API | `features/chat/api/shipping.api.ts`(`src/api/shippingNotice.ts` deprecated 转发) |
|
||||
| 跨 Agent 历史 | `features/chat/history/HistoryPage.vue` + `useChatHistory` |
|
||||
| Pinia 接入 | `chat.store`:`currentAgentId`(路由同步)、`sidebarCollapsed`、`sessionHistoryByAgent` 缓存 |
|
||||
| 内置浏览器 | 输入栏「打开/收起浏览器」按钮已恢复,逻辑在 `useChatBrowserPanel` |
|
||||
| provide/inject | `chat.context.ts`:`CHAT_PAGE_KEY` + `useChatPageContext()`;`reactive(useChatPage())` 解包嵌套 Ref;`markRaw` 保留 template ref holder |
|
||||
|
||||
### 10.2 构建验证
|
||||
|
||||
历次拆分后 `npm run build` 通过。
|
||||
|
||||
### 10.3 待办(Chat 域内)
|
||||
|
||||
| 优先级 | 项 | 状态 |
|
||||
|--------|-----|------|
|
||||
| 中 | `chat.context` + provide/inject(`ChatViewContent` / `ChatViewOverlays` inject) | ✅ |
|
||||
| 中 | `ChatViewOverlays.vue` 抽出全部弹窗 | ✅ |
|
||||
| 中 | `chat.store` 按 Agent 缓存侧栏会话列表 | ✅ |
|
||||
| 中 | 瘦身 `useChatPage` → `page/*` 子模块 | ✅ |
|
||||
| 中 | 瘦身 `useChatShipping` → `shipping/*` 子模块 | ✅ |
|
||||
| 中 | 瘦身 `useChatLeave` → `leave/*` 子模块 | ✅ |
|
||||
| 低 | `LeaveAgentOption` 等类型已统一至 `leave.types.ts` 并 re-export | ✅ |
|
||||
| 低 | `chat.context` 完善类型(`ChatPageContextProvided` + `useChatPageContext()`) | ✅ |
|
||||
| 低 | `shipping/*`、`leave/*` 纯函数单元测试 | 待做 |
|
||||
|
||||
### 10.4 下一步
|
||||
|
||||
- ~~Admin 模块独立~~ → 见 §9
|
||||
- Workspace 壳层 → 见 §11
|
||||
- ~~API 按 feature 归属~~ → 见 §12
|
||||
- ~~`shared/` composables/components/layouts/utils/styles 迁移~~ → 见 §14
|
||||
- ~~KB 域收口~~ → 见 §16
|
||||
- ~~`locales/` 按域拆分~~ → 见 §15.2
|
||||
|
||||
### 10.5 Admin Schedules 模块瘦身(2026-06,已实现)
|
||||
|
||||
参照 KB 作业面模式,将原 `SchedulesPage.vue`(~1200 行)与 `useSchedulesAdmin.ts`(~1100 行)拆为薄壳 + provide/inject 子组件。
|
||||
|
||||
| 项 | 路径 / 约行数 |
|
||||
|----|---------------|
|
||||
| 页面壳层 | `SchedulesPage.vue`(~26 行:`reactive(useSchedulesAdmin())` + `provide` + 4 子组件) |
|
||||
| 编排入口 | `composables/useSchedulesAdmin.ts`(~28 行,组合子模块) |
|
||||
| 子 composable | `composables/schedule-admin/`:`state`(~145)、`useScheduleAdminLookups`(~40)、`useScheduleAdminList`(~124)、`useScheduleAdminRuns`(~196)、`useScheduleAdminForm`(~329)、`useScheduleAdminTestRun`(~95) |
|
||||
| provide/inject | `composables/schedules.context.ts`(~26 行) |
|
||||
| 类型与默认工厂 | `types/schedule-admin.types.ts`(~127 行) |
|
||||
| 纯函数 | `utils/schedule-cron.utils.ts`、`utils/schedule-format.utils.ts`、`utils/schedule-form-payload.utils.ts` |
|
||||
| 子组件 | `SchedulePageHeader`(~44)、`ScheduleOverviewPanel`(~146)、`ScheduleWorkbenchPanel`(~329)、`SchedulesPageOverlays`(~24)、`ScheduleTestRunDialog`(~175)、`ScheduleCreateEditModal`(~525) |
|
||||
|
||||
子 panel / overlays 通过 `useSchedulesAdminContext()` inject,无 props 透传。`npm run build` 通过。
|
||||
|
||||
**i18n(2026-06)**:`ScheduleCreateEditModal`、`ScheduleTestRunDialog`、`ScheduleWorkbenchPanel`(Dify 快照区)硬编码中文已外置至 `locales/*/admin.json`(`schedule.form.*`、`schedule.difySnapshot.*`、`schedule.testRun.*`);合并脚本 `frontend/scripts/merge-schedule-form-i18n.mjs`。顺带修复创建按钮误用 `admin.schedule.form.admin.createSchedule` 键。
|
||||
|
||||
---
|
||||
|
||||
## 11. Phase 3 Workspace 模块(已实现)
|
||||
|
||||
Phase 3 目标:将原 `WorkspaceView.vue` 拆为独立 feature,路由 `/workspace/*`。
|
||||
|
||||
### 11.1 已完成项
|
||||
|
||||
| 项 | 路径 / 说明 |
|
||||
|----|-------------|
|
||||
| 布局壳 | `features/workspace/views/WorkspaceLayout.vue` + `provide/inject` |
|
||||
| 子页面 | `HomePage`(应用管理)、`ProfilePage`、`ScheduleRunsPage`、`FeedbackPage` |
|
||||
| 路由 | `app/router/routes/workspace.routes.ts` |
|
||||
| Composable | `useWorkspace`、`useWorkspaceHome`、`useWorkspaceNavigation` 等 |
|
||||
| 排程 API | `features/workspace/api/schedule.api.ts` |
|
||||
| 历史页 | 复用 `features/chat/history/HistoryPage.vue` |
|
||||
|
||||
### 11.2 薄包装页
|
||||
|
||||
| 页面 | 现状 |
|
||||
|------|------|
|
||||
| `KnowledgeBasePage.vue` | ✅ 嵌入 `features/kb/views/KbWorkspaceView.vue`(`embedded`) |
|
||||
| `ShippingNoticePage.vue` | ✅ 嵌入 `features/workspace/views/ShippingNoticeView.vue`(`embedded`) |
|
||||
|
||||
### 11.3 路由
|
||||
|
||||
```text
|
||||
/workspace/applications → HomePage
|
||||
/workspace/profile → ProfilePage
|
||||
/workspace/schedule-runs → ScheduleRunsPage
|
||||
/workspace/shipping-notice → ShippingNoticePage(嵌入 ShippingNoticeView)
|
||||
/workspace/knowledge-base → KnowledgeBasePage(legacy 嵌入)
|
||||
/workspace/history → chat/history/HistoryPage
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 12. Phase 4 API 按 Feature 归属(已实现)
|
||||
|
||||
Phase 4 目标:领域 HTTP 请求迁入对应 `features/*/api/`,`shared/api/client.ts` 作为唯一 JSON 客户端。
|
||||
|
||||
### 12.1 迁移对照
|
||||
|
||||
| 原路径 | 新路径 | 状态 |
|
||||
|--------|--------|------|
|
||||
| `src/api/client.ts` | `shared/api/client.ts` | ✅ 权威实现;旧路径 deprecated 转发 |
|
||||
| `src/api/user.ts` | `features/auth/api/user.api.ts` | ✅(Phase 0 已完成) |
|
||||
| `src/api/chat.ts` | `features/chat/api/chat.api.ts` | ✅(Phase 2 已完成) |
|
||||
| `src/api/admin.ts` | `features/admin/api/admin.api.ts` | ✅ |
|
||||
| `src/api/schedule.ts`(admin 部分) | `features/admin/api/schedule.api.ts` | ✅ |
|
||||
| `src/api/schedule.ts`(workspace 部分) | `features/workspace/api/schedule.api.ts` | ✅ |
|
||||
| 排程共用类型 | `shared/types/schedule.types.ts` | ✅ |
|
||||
| `src/api/shippingNotice.ts` | `features/chat/api/shipping.api.ts` | ✅ |
|
||||
| 货代类型 | `features/chat/types/shipping.api.types.ts` | ✅ |
|
||||
| `src/api/toolRunProgress.ts` | `features/chat/api/toolRunProgress.api.ts` | ✅ |
|
||||
| 工具进度类型 | `features/chat/types/tool-run-progress.types.ts` | ✅ |
|
||||
| `src/api/kb.ts` | `features/kb/api/kb.api.ts` | ✅(deprecated 转发已删除) |
|
||||
|
||||
### 12.2 新代码 import 规范
|
||||
|
||||
```typescript
|
||||
// 共享 HTTP 客户端
|
||||
import { requestJson, BusinessError } from '@/shared/api/client';
|
||||
|
||||
// 各域 API
|
||||
import { listAdminUsers } from '@/features/admin/api/admin.api';
|
||||
import { listAdminSchedules } from '@/features/admin/api/schedule.api';
|
||||
import { listWorkspaceScheduleRuns } from '@/features/workspace/api/schedule.api';
|
||||
import { listChatSessions } from '@/features/chat/api/chat.api';
|
||||
import { getWorkspaceShippingTask } from '@/features/chat/api/shipping.api';
|
||||
import { getUserProfile } from '@/features/auth/api/user.api';
|
||||
import { getKbGroupsSafe } from '@/features/kb/api/kb.api';
|
||||
```
|
||||
|
||||
或通过 feature 入口 re-export:
|
||||
|
||||
```typescript
|
||||
import { listAdminUsers } from '@/features/admin';
|
||||
import { listWorkspaceScheduleRuns } from '@/features/workspace';
|
||||
import { getWorkspaceShippingTask } from '@/features/chat';
|
||||
```
|
||||
|
||||
### 12.3 兼容策略
|
||||
|
||||
- ~~`src/api/{client,admin,schedule,shippingNotice,chat,user,toolRunProgress,kb}.ts` deprecated 转发~~ → **已全部删除**(2026-06-11)
|
||||
- **`src/api/` 目录已清空**;新代码必须使用 `@/features/*/api/*` 或 `@/shared/api/client`
|
||||
|
||||
### 12.4 构建验证
|
||||
|
||||
迁移后 `npm run build` 须通过。
|
||||
|
||||
### 12.5 下一步
|
||||
|
||||
- ~~KB API 迁入 `features/kb/api/kb.api.ts`~~ → 已完成(见 §16)
|
||||
- ~~清理 deprecated `src/api/*` 转发~~ → 已完成(`src/api/` 已清空)
|
||||
- `locales/` 按域拆分 → 见 §15
|
||||
|
||||
---
|
||||
|
||||
## 14. Phase 5 Shared 共享层迁移(已实现)
|
||||
|
||||
Phase 5 目标:将原 `src/` 根目录下的跨域代码迁入 `src/shared/`,与 `features/` 划清边界。
|
||||
|
||||
### 14.1 迁移对照
|
||||
|
||||
| 原路径 | 新路径 | 状态 |
|
||||
|--------|--------|------|
|
||||
| `src/composables/*` | `shared/composables/*` | ✅ |
|
||||
| `src/components/*` | `shared/components/*` | ✅(`kb/` 已迁 `features/kb/components/`) |
|
||||
| `src/layouts/*` | `shared/layouts/*` | ✅ |
|
||||
| `src/utils/*` | `shared/utils/*` | ✅ |
|
||||
| `src/styles/*` | `shared/styles/*` | ✅ |
|
||||
| `style.css` 引用 | `@import './shared/styles/...'` | ✅ |
|
||||
|
||||
### 14.2 目录结构
|
||||
|
||||
```text
|
||||
shared/
|
||||
├── index.ts # 统一导出入口
|
||||
├── api/client.ts
|
||||
├── composables/ # useTheme、useMessage、useIsMobile 等
|
||||
├── components/ # Dialog、LocaleToggle 等(无 kb 子目录)
|
||||
├── layouts/ # AppShell、ChatShell、MarketingShell 等
|
||||
├── utils/ # auth、clipboard、wecom 等
|
||||
├── styles/ # tokens.css、components-ds.css、utilities.css
|
||||
├── constants/routes.ts
|
||||
└── types/ # auth.types、schedule.types
|
||||
```
|
||||
|
||||
### 14.3 新代码 import 规范
|
||||
|
||||
```typescript
|
||||
import { useTheme, useMessage } from '@/shared/composables/useTheme';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import ChatShell from '@/shared/layouts/ChatShell.vue';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
|
||||
// 或按需从入口导入
|
||||
import { useTheme, requestJson } from '@/shared';
|
||||
```
|
||||
|
||||
### 14.4 兼容策略
|
||||
|
||||
- ~~`src/composables/`、`src/utils/`、`src/styles/` deprecated 转发~~ → **已删除**(2026-06-11)
|
||||
- `src/components/`、`src/layouts/` **已删除**(全仓 import 已切换)
|
||||
- **新代码必须使用 `@/shared/*` 路径**
|
||||
- ~~`shared/components/kb/*`~~ → 已迁入 `features/kb/components/`
|
||||
|
||||
### 14.5 构建验证
|
||||
|
||||
迁移后 `npm run build` 须通过。
|
||||
|
||||
### 14.6 下一步
|
||||
|
||||
- ~~KB 组件/API 迁入 `features/kb/`~~ → 已完成(见 §16)
|
||||
- ~~清理 deprecated 转发~~ → 已完成
|
||||
- `locales/` 按域拆分 → 见 §15
|
||||
|
||||
---
|
||||
|
||||
## 15. 架构对齐清理清单
|
||||
|
||||
> 目标:与 Vite/Vue 默认约定及本文档目标结构对齐。
|
||||
> 状态更新时间:2026-06-11
|
||||
|
||||
### 15.1 已完成 ✅
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| 删除 `src/composables/` | 7 个 deprecated 转发已移除 |
|
||||
| 删除 `src/utils/` | 6 个 deprecated 转发已移除 |
|
||||
| 删除 `src/styles/` | 3 个 CSS 转发已移除 |
|
||||
| 删除 `src/api/*` | 全部转发已移除,`src/api/` 目录已清空 |
|
||||
| 移除 `axios` 依赖 | 代码未使用,已从 `package.json` 删除 |
|
||||
| `main.ts` / `App.vue` | 保留在 `src/` 根(见 §7.2 约定) |
|
||||
|
||||
### 15.2 i18n 按域拆分(已完成)
|
||||
|
||||
**现状**:`src/i18n.ts` 仅保留 `createI18n` 注册与空 locale 骨架;**全部** messages 均已外置 JSON。
|
||||
|
||||
**已完成 ✅**
|
||||
|
||||
| 域 | 路径 |
|
||||
|----|------|
|
||||
| `errors` | `locales/{en,zh-CN,zh-TW,th}/errors.json` |
|
||||
| `auth` | `locales/{en,zh-CN,zh-TW,th}/auth.json`(展平合并:`login.*` 等) |
|
||||
| `workspace` | `locales/{en,zh-CN,zh-TW,th}/workspace.json` |
|
||||
| `chat` | `locales/{en,zh-CN,zh-TW,th}/chat.json` |
|
||||
| `admin` | `locales/{en,zh-CN,zh-TW,th}/admin.json` |
|
||||
| `kb` | `locales/{en,zh-CN,zh-TW,th}/kb.json`(展平合并:`kbDifySettings.*` 等) |
|
||||
| `common` / `scheduleRuns` / `filePreview` / `profile` / `feedback` / `theme` | 同上四语言 JSON |
|
||||
| 合并入口 | `locales/index.ts` → `mergeExternalLocales()` |
|
||||
|
||||
`i18n.ts` 在 `createI18n` 前调用 `mergeExternalLocales(messages)`,四语言外置域与拆分前行为一致。
|
||||
|
||||
**目标结构**(已达成):
|
||||
|
||||
```text
|
||||
src/locales/
|
||||
├── index.ts # mergeExternalLocales + 导出
|
||||
├── zh-CN/ zh-TW/ en/ th/
|
||||
│ ├── errors.json
|
||||
│ ├── auth.json
|
||||
│ ├── workspace.json
|
||||
│ ├── chat.json
|
||||
│ ├── admin.json
|
||||
│ ├── kb.json
|
||||
│ ├── common.json
|
||||
│ ├── scheduleRuns.json
|
||||
│ ├── filePreview.json
|
||||
│ ├── profile.json
|
||||
│ ├── feedback.json
|
||||
│ └── theme.json
|
||||
```
|
||||
|
||||
**迁移步骤**(均已完成):
|
||||
|
||||
1. ~~拆 `errors.*` → `errors.json`~~ ✅
|
||||
2. ~~拆 `auth.*` → `auth.json`~~ ✅
|
||||
3. ~~拆 `workspace.*` → `workspace.json`~~ ✅
|
||||
4. ~~拆 `chat.*` → `chat.json`~~ ✅
|
||||
5. ~~拆 `admin.*` → `admin.json`~~ ✅
|
||||
6. ~~拆 `kb.*` → `kb.json`(四语言)~~ ✅
|
||||
7. ~~拆共享域 `common` / `scheduleRuns` / `filePreview` / `profile` / `feedback` / `theme`~~ ✅
|
||||
8. 每步 `npm run build` + 四语言 spot check
|
||||
9. `i18n.ts` 仅保留 `createI18n` 注册与 locale 骨架
|
||||
|
||||
**注意**:AGENTS.md 要求四语言同步;拆分时用脚本或 CI 校验 key 对齐。
|
||||
|
||||
### 15.3 清理 `src/views/`(已完成 ✅)
|
||||
|
||||
| 文件 | 状态 |
|
||||
|------|------|
|
||||
| ~~`KbWorkspaceView.vue`~~ | ✅ 已迁入 `features/kb/views/`(见 §16) |
|
||||
| ~~`ShippingNoticeView.vue`~~ | ✅ 已迁入 `features/workspace/views/` |
|
||||
|
||||
`src/views/`、`src/api/` 空目录已删除。
|
||||
|
||||
### 15.4 deprecated 遗留清理(已完成 ✅)
|
||||
|
||||
| 项 | 状态 |
|
||||
|----|------|
|
||||
| `shared/components/kb/*` | 已删除(canonical:`features/kb/components/*`) |
|
||||
| `shared/composables/useChat.ts` | 已删除(canonical:`features/chat/composables/useChat`) |
|
||||
| `features/workspace/pages/HistoryPage.vue` | 已删除(canonical:`chat/history/HistoryPage`) |
|
||||
| `features/workspace/composables/useWorkspaceHistory.ts` | 已删除 |
|
||||
| `src/api/toolRunProgress.ts` | 已迁入 `features/chat/api/toolRunProgress.api.ts` |
|
||||
| `src/api/kb.ts` | 已删除 |
|
||||
|
||||
### 15.5 KB 域收口(已实现,见 §16)
|
||||
|
||||
- ~~`src/api/kb.ts` → `features/kb/api/kb.api.ts`~~ ✅
|
||||
- ~~`shared/components/kb/*` → `features/kb/components/*`~~ ✅
|
||||
- ~~路由收敛:`/kb/workspace` redirect → `/workspace/knowledge-base`~~ ✅
|
||||
- ~~作业面 monolith 拆分:`useKbWorkspace` + `kb-workspace/*`~~ ✅
|
||||
|
||||
### 15.6 可选优化(非必须)
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| ~~`index.html` `lang="zh-CN"`~~ | ✅ |
|
||||
| ~~`App.vue` 文件头注释~~ | ✅ |
|
||||
| `frontend/.env.development` | 若需纯前端多环境 API 地址,再用 `VITE_*` |
|
||||
| Vite 8 beta → stable | 关注正式版发布后升级 |
|
||||
|
||||
### 15.7 推荐执行顺序
|
||||
|
||||
```text
|
||||
✅ Phase A:删 deprecated 转发 + 去 axios
|
||||
✅ Phase B:i18n 拆 locales/(errors → auth → workspace → chat → admin → kb)
|
||||
✅ Phase C:ShippingNoticeView 迁入 workspace
|
||||
✅ Phase E:API 遗留清理 + deprecated 文件删除 + i18n 共享域外置
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 16. Phase 6 KB 域落地说明(已实现)
|
||||
|
||||
Phase 6 目标:知识库从 monolith 迁入 `features/kb/`,治理面与作业面职责分离,作业面逻辑 composable 化。
|
||||
|
||||
### 16.1 职责与路由
|
||||
|
||||
| 面 | Canonical 路由 | 组件 | 说明 |
|
||||
|----|----------------|------|------|
|
||||
| 治理面 | `/admin/knowledge-base` | `KbAdminPanel` | 分组 CRUD、Dify 设置、健康检查、任务队列 |
|
||||
| 作业面 | `/workspace/knowledge-base` | `KbWorkspaceView`(`embedded`) | 选分组 → 文档上传/清洗/同步(无分组 CRUD) |
|
||||
| 兼容 | `/kb/workspace` | redirect | → `/workspace/knowledge-base` |
|
||||
| 兼容 | `/kb/admin` | redirect | → `/admin/knowledge-base` |
|
||||
|
||||
权限:`hasKnowledgeBaseAccess`(工作台入口)与作业面批量操作均收敛为 `role === 'admin'`。
|
||||
|
||||
### 16.2 目录结构
|
||||
|
||||
```text
|
||||
features/kb/
|
||||
├── api/kb.api.ts
|
||||
├── types/kb-workspace.types.ts
|
||||
├── utils/
|
||||
│ ├── kb-list.utils.ts
|
||||
│ ├── kb-display.utils.ts
|
||||
│ ├── kb-workflow.utils.ts
|
||||
│ └── kb-path-upload.utils.ts
|
||||
├── composables/
|
||||
│ ├── useKbWorkspace.ts # 编排入口(~160 行)
|
||||
│ └── kb-workspace/
|
||||
│ ├── kb-workspace.state.ts # 共享 ref + 删除确认
|
||||
│ ├── kb-workspace.bridge.ts # pathUpload ↔ data 延迟绑定
|
||||
│ ├── useKbWorkspaceComputed.ts
|
||||
│ ├── useKbWorkspaceData.ts
|
||||
│ ├── useKbWorkspacePathUpload.ts
|
||||
│ ├── useKbWorkspaceDocuments.ts
|
||||
│ └── useKbWorkspaceModals.ts
|
||||
├── views/KbWorkspaceView.vue # 主内容壳(~550 行)
|
||||
├── components/KbWorkspaceOverlays.vue # 弹窗层(~635 行)
|
||||
└── components/
|
||||
├── KbAdminPanel.vue
|
||||
├── DifySettingsDialog.vue
|
||||
└── DifyHealthDialog.vue
|
||||
```
|
||||
|
||||
### 16.3 已完成项
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| API 迁入 | `features/kb/api/kb.api.ts`(`src/api/kb.ts` 已删除) |
|
||||
| 组件迁入 | `KbAdminPanel`、`DifySettingsDialog`、`DifyHealthDialog` |
|
||||
| 作业面拆分 | 类型/纯函数 utils + `useKbWorkspace` 子 composable |
|
||||
| 视图薄壳 | `KbWorkspaceView.vue` script 仅 `useKbWorkspace({ embedded })` |
|
||||
| 工作台嵌入 | `workspace/pages/KnowledgeBasePage.vue` → `KbWorkspaceView` |
|
||||
| i18n | `locales/*/kb.json` 四语言外置 |
|
||||
| 路由收敛 | `app/router/routes/kb.routes.ts` 仅保留 redirect |
|
||||
|
||||
### 16.4 构建验证
|
||||
|
||||
拆分后 `npm run build` 通过。
|
||||
|
||||
### 16.5 待办(KB 域内,优先级低)
|
||||
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| 作业面 View 继续瘦身 | ✅ 弹窗已抽至 `KbWorkspaceOverlays.vue`(View ~550 行 → 主内容壳;Overlays ~620 行);文档列表区可继续拆 panel |
|
||||
| 作业面 i18n 全覆盖 | ✅ 模板 + utils/composable 运行时文案已迁入 `kb.json`(`kbWorkspace.*` 四语言);`kb.api.ts` 错误 fallback 仍为中文(低优先级) |
|
||||
| 删除 `src/api/kb.ts` | ✅ 全仓已无 `@/api/kb` import,deprecated 转发已移除 |
|
||||
|
||||
### 16.6 下一步(全项目)
|
||||
|
||||
- ~~`ShippingNoticeView` 迁入 workspace~~ → §15.3 ✅
|
||||
- Chat / admin 域内低优先级待办 → §10.3
|
||||
|
||||
---
|
||||
|
||||
- [项目上下文与技术栈](./project_context.md)
|
||||
- [UI 设计系统](./ui/DESIGN_SYSTEM.md)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+14
-12
@@ -65,9 +65,10 @@ flask db upgrade
|
||||
### 1.2 环境变量(`.env.dev` 示例)
|
||||
|
||||
```env
|
||||
# Tool API(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||
# Tool API 基地址(RoHS / 货代共用,无尾斜杠)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
|
||||
# 货代 Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=your-tool-key
|
||||
SHIPPING_NOTICE_TOOL_API_BASE=http://192.168.36.114:5052
|
||||
|
||||
# 文件存储(相对 backend/ 根目录;勿写 backend/data/… 以免 cwd 在 backend/ 时变成 backend/backend/…)
|
||||
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
||||
@@ -194,7 +195,7 @@ curl -s http://192.168.100.192:8890/api/shipping-notice/tools/openapi.json | hea
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
set SHIPPING_NOTICE_TOOL_API_BASE=http://192.168.100.192:8890
|
||||
set HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
|
||||
python scripts/export_shipping_notice_openapi.py
|
||||
# → docs/openapi/shipping_notice_tools.dify.json
|
||||
```
|
||||
@@ -409,21 +410,21 @@ flowchart TD
|
||||
|
||||
| 输入变量名 | 类型 | 必填 | 说明 |
|
||||
|------------|------|------|------|
|
||||
| `hxops_tool_api_base` | string | 否 | hxops 后端根地址,**无**尾斜杠,例 `http://host:8890` |
|
||||
| `HXOPS_TOOLS_API_BASE` | string | 否 | hxops 后端根地址,**无**尾斜杠,例 `http://host:8890` |
|
||||
| `hxops_tool_api_key` | string | 否 | 与 hxops `SHIPPING_NOTICE_TOOL_API_KEY` 一致 |
|
||||
|
||||
2. **hxops 自动注入**:用户经前端聊天调用 `货代发货通知 Agent` 时,`/api/chat/completions` 会把上述两项写入 Dify `inputs`(读 `SHIPPING_NOTICE_TOOL_API_BASE` / `SHIPPING_NOTICE_TOOL_API_KEY`)。**切换 dev / test / prod 只改 hxops 环境变量,Dify 画布 YAML 可原样导入**。
|
||||
2. **hxops 自动注入**:用户经前端聊天调用 `货代发货通知 Agent` 时,`/api/chat/completions` 会把上述两项写入 Dify `inputs`(读 `HXOPS_TOOLS_API_BASE` / `SHIPPING_NOTICE_TOOL_API_KEY`)。**切换 dev / test / prod 只改 hxops 环境变量,Dify 画布 YAML 可原样导入**。
|
||||
|
||||
3. **HTTP 节点统一模板**(所有 `HTTP_*` 节点 URL / Header 均按此填写,勿再写死 IP):
|
||||
|
||||
| 项 | 模板 |
|
||||
|----|------|
|
||||
| URL | `{{#hxops_tool_api_base#}}/api/shipping-notice/tools/<endpoint>`,例 `…/api/shipping-notice/tools/create_task` |
|
||||
| URL | `{{#HXOPS_TOOLS_API_BASE#}}/api/shipping-notice/tools/<endpoint>`,例 `…/api/shipping-notice/tools/create_task` |
|
||||
| Header `X-Shipping-Tool-Key` | `{{#hxops_tool_api_key#}}` |
|
||||
|
||||
> Dify 版本差异:若 UI 无法直接填 `{{#变量名#}}`,用变量选择器绑定 **输入变量** `hxops_tool_api_base` / `hxops_tool_api_key` 即可,语义相同。
|
||||
> Dify 版本差异:若 UI 无法直接填 `{{#变量名#}}`,用变量选择器绑定 **输入变量** `HXOPS_TOOLS_API_BASE` / `hxops_tool_api_key` 即可,语义相同。
|
||||
|
||||
**Agent 自定义工具(OpenAPI)**:导入地址 `{hxops_tool_api_base}/api/shipping-notice/tools/openapi.json`(或 Dify 环境变量拼 URL);换环境时重新「从 URL 导入」或改工具 Server URL 一次,**不必改 Chatflow 连线**。
|
||||
**Agent 自定义工具(OpenAPI)**:导入地址 `{HXOPS_TOOLS_API_BASE}/api/shipping-notice/tools/openapi.json`(或 Dify 环境变量拼 URL);换环境时重新「从 URL 导入」或改工具 Server URL 一次,**不必改 Chatflow 连线**。
|
||||
|
||||
**HTTP 公共配置**
|
||||
|
||||
@@ -432,7 +433,7 @@ flowchart TD
|
||||
| Method | POST |
|
||||
| Header | `X-Shipping-Tool-Key: {{#hxops_tool_api_key#}}` |
|
||||
| Header | `Content-Type: application/json`(JSON Body 节点) |
|
||||
| 基 URL | `{{#hxops_tool_api_base#}}/api/shipping-notice/tools/`(**禁止**写死 IP;旧示例 IP 仅作联调参考) |
|
||||
| 基 URL | `{{#HXOPS_TOOLS_API_BASE#}}/api/shipping-notice/tools/`(**禁止**写死 IP;旧示例 IP 仅作联调参考) |
|
||||
|
||||
**Dify Code 节点配置说明**
|
||||
|
||||
@@ -715,7 +716,7 @@ def main(
|
||||
| 项 | 值 |
|
||||
|----|-----|
|
||||
| Method | POST |
|
||||
| URL | `{{#hxops_tool_api_base#}}/api/shipping-notice/tools/create_task` |
|
||||
| URL | `{{#HXOPS_TOOLS_API_BASE#}}/api/shipping-notice/tools/create_task` |
|
||||
| Header | `X-Shipping-Tool-Key: {{#hxops_tool_api_key#}}`;`Content-Type: application/json` |
|
||||
| Body | `{{#拼装 create_task Body.create_body_json#}}`(JSON 对象,勿再加引号) |
|
||||
| 出参 | `body` · **String** |
|
||||
@@ -839,7 +840,7 @@ def main(text: str) -> dict:
|
||||
|
||||
| 项 | 值 |
|
||||
|----|-----|
|
||||
| URL | `{{#hxops_tool_api_base#}}/api/shipping-notice/tools/parse_notice` |
|
||||
| URL | `{{#HXOPS_TOOLS_API_BASE#}}/api/shipping-notice/tools/parse_notice` |
|
||||
| Header | `X-Shipping-Tool-Key`;`Content-Type: application/json` |
|
||||
| Body | 见下 |
|
||||
| 出参 | `body` · **String** |
|
||||
@@ -927,7 +928,7 @@ def main(body: str) -> dict:
|
||||
| 项 | 值 |
|
||||
|----|-----|
|
||||
| Method | POST |
|
||||
| URL | `{{#hxops_tool_api_base#}}/api/shipping-notice/tools/upload_inventory_file` |
|
||||
| URL | `{{#HXOPS_TOOLS_API_BASE#}}/api/shipping-notice/tools/upload_inventory_file` |
|
||||
| Header | `X-Shipping-Tool-Key: {{#hxops_tool_api_key#}}` |
|
||||
| Body 类型 | **form-data** |
|
||||
| form `task_id` | `{{#conversation.task_id#}}` · String |
|
||||
@@ -3024,3 +3025,4 @@ GET /api/shipping-notice/tools/checkpoint-catalog
|
||||
| `backend/tests/test_shipping_notice_tools.py` | Tool 集成测试 |
|
||||
| `backend/tests/test_shipping_notice_state_machine.py` | registry / task UI 快照 |
|
||||
| `scripts/rpa/freight_rpa_worker.py` | RPA Worker |
|
||||
|
||||
@@ -10,6 +10,14 @@
|
||||
|
||||
## 2. 现有可复用能力
|
||||
|
||||
### 2.x RoHS 文件检核可复用能力
|
||||
|
||||
- **产品语义**:对外统一为 RoHS 文件检核(发起、实时查询、报告、知识库同步、历史报告检索);Tool API 使用 `/api/rohs-check/tools/tasks` 与 `task_id` / `task_no` 字段;历史查询走 Dify Knowledge Retrieval(绑定检核报告同步的 Dataset);对外基地址由环境变量 `HXOPS_TOOLS_API_BASE` 配置。
|
||||
- 通过 `RoHSCheckService.evaluate()` 包装现有 Dify Workflow 调用,保持 `dify_result / dify_message` 输出兼容。
|
||||
- 新增 `/api/rohs-check/tools/*` 显式 HTTP Tool API,供 Dify Chatflow 发起检核、查询检核结果并返回 Excel 报告短期签名链接。
|
||||
- Chatflow 完整编排、Dify 逐步配置与 OpenAPI 导入见 **[docs/rohs_chatflow_guide.md](rohs_chatflow_guide.md)**;OpenAPI 规范见 **[docs/openapi/rohs_check_tools_openapi.json](openapi/rohs_check_tools_openapi.json)**(`python backend/scripts/export_rohs_check_openapi.py` 重新生成)。
|
||||
- 复用知识库 `KbDocument / KbDocumentVersion / KbJob` 清洗与 Dify 同步链路,将检核报告 Excel 作为独立文档入库。
|
||||
|
||||
### 2.1 已有聊天路由能力
|
||||
|
||||
- 后端 `chat` 接口已支持按意图分流
|
||||
@@ -878,3 +886,4 @@ const update = () => { isMobile.value = window.innerHeight > window.innerWidth;
|
||||
- Web 进程压力下降,系统稳定性提升
|
||||
- 失败任务可重试,进度展示更清晰
|
||||
- 整体知识库链路更适合后续扩展为高并发、多批次处理模式
|
||||
|
||||
@@ -3,10 +3,12 @@
|
||||
本文档旨在对系统的所有功能进行提炼,并规范化测试代码的撰写要求。
|
||||
|
||||
## 1. 测试代码撰写通用要求
|
||||
所有测试代码必须遵循以下三层注释标准:
|
||||
1. **文件层注释**:注明文件用途、引用的模块、逻辑关系。
|
||||
2. **函数层注释**:在函数名上方说明其用途、核心逻辑与实现方式,对传参与输出进行说明。
|
||||
3. **代码层注释**:在函数内部,对关键代码行进行注释,解释逻辑意图。
|
||||
|
||||
业务代码的文件层 + 函数层标准见 **[AGENTS.md §5](../AGENTS.md)**。测试代码在此基础上增加第三层:
|
||||
|
||||
1. **文件层注释**:注明文件用途、引用的模块、逻辑关系(同 AGENTS.md §5.1)。
|
||||
2. **函数层注释**:在函数名上方说明其用途、核心逻辑与实现方式,对传参与输出进行说明(同 AGENTS.md §5.2)。
|
||||
3. **代码层注释**(测试专有):在函数内部,对关键代码行进行注释,解释逻辑意图。
|
||||
|
||||
---
|
||||
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
|
||||
Generated
-259
@@ -13,7 +13,6 @@
|
||||
"@vue-office/docx": "^1.6.3",
|
||||
"@vue-office/excel": "^1.7.14",
|
||||
"@vue-office/pdf": "^1.6.5",
|
||||
"axios": "^1.13.5",
|
||||
"highlight.js": "^11.11.1",
|
||||
"lucide-vue-next": "^0.575.0",
|
||||
"marked": "^17.0.3",
|
||||
@@ -862,12 +861,6 @@
|
||||
"integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/asynckit": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://mirrors.tencent.com/npm/asynckit/-/asynckit-0.4.0.tgz",
|
||||
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/autoprefixer": {
|
||||
"version": "10.4.24",
|
||||
"resolved": "https://mirrors.tencent.com/npm/autoprefixer/-/autoprefixer-10.4.24.tgz",
|
||||
@@ -905,17 +898,6 @@
|
||||
"postcss": "^8.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/axios": {
|
||||
"version": "1.13.5",
|
||||
"resolved": "https://mirrors.tencent.com/npm/axios/-/axios-1.13.5.tgz",
|
||||
"integrity": "sha512-cz4ur7Vb0xS4/KUN0tPWe44eqxrIu31me+fbang3ijiNscE129POzipJJA6zniq2C/Z6sJCjMimjS8Lc/GAs8Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"follow-redirects": "^1.15.11",
|
||||
"form-data": "^4.0.5",
|
||||
"proxy-from-env": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/baseline-browser-mapping": {
|
||||
"version": "2.10.0",
|
||||
"resolved": "https://mirrors.tencent.com/npm/baseline-browser-mapping/-/baseline-browser-mapping-2.10.0.tgz",
|
||||
@@ -996,19 +978,6 @@
|
||||
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
|
||||
}
|
||||
},
|
||||
"node_modules/call-bind-apply-helpers": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://mirrors.tencent.com/npm/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
|
||||
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0",
|
||||
"function-bind": "^1.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/camelcase-css": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://mirrors.tencent.com/npm/camelcase-css/-/camelcase-css-2.0.1.tgz",
|
||||
@@ -1097,18 +1066,6 @@
|
||||
"node": ">=0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/combined-stream": {
|
||||
"version": "1.0.8",
|
||||
"resolved": "https://mirrors.tencent.com/npm/combined-stream/-/combined-stream-1.0.8.tgz",
|
||||
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"delayed-stream": "~1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/commander": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://mirrors.tencent.com/npm/commander/-/commander-4.1.1.tgz",
|
||||
@@ -1163,15 +1120,6 @@
|
||||
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/delayed-stream": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://mirrors.tencent.com/npm/delayed-stream/-/delayed-stream-1.0.0.tgz",
|
||||
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/detect-libc": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://mirrors.tencent.com/npm/detect-libc/-/detect-libc-2.1.2.tgz",
|
||||
@@ -1194,20 +1142,6 @@
|
||||
"integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/dunder-proto": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://mirrors.tencent.com/npm/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
||||
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"call-bind-apply-helpers": "^1.0.1",
|
||||
"es-errors": "^1.3.0",
|
||||
"gopd": "^1.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/electron-to-chromium": {
|
||||
"version": "1.5.302",
|
||||
"resolved": "https://mirrors.tencent.com/npm/electron-to-chromium/-/electron-to-chromium-1.5.302.tgz",
|
||||
@@ -1227,51 +1161,6 @@
|
||||
"url": "https://github.com/fb55/entities?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/es-define-property": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://mirrors.tencent.com/npm/es-define-property/-/es-define-property-1.0.1.tgz",
|
||||
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/es-errors": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://mirrors.tencent.com/npm/es-errors/-/es-errors-1.3.0.tgz",
|
||||
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/es-object-atoms": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://mirrors.tencent.com/npm/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
|
||||
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/es-set-tostringtag": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://mirrors.tencent.com/npm/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
|
||||
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"es-errors": "^1.3.0",
|
||||
"get-intrinsic": "^1.2.6",
|
||||
"has-tostringtag": "^1.0.2",
|
||||
"hasown": "^2.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/escalade": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://mirrors.tencent.com/npm/escalade/-/escalade-3.2.0.tgz",
|
||||
@@ -1354,42 +1243,6 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/follow-redirects": {
|
||||
"version": "1.15.11",
|
||||
"resolved": "https://mirrors.tencent.com/npm/follow-redirects/-/follow-redirects-1.15.11.tgz",
|
||||
"integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/RubenVerborgh"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=4.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"debug": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/form-data": {
|
||||
"version": "4.0.5",
|
||||
"resolved": "https://mirrors.tencent.com/npm/form-data/-/form-data-4.0.5.tgz",
|
||||
"integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"asynckit": "^0.4.0",
|
||||
"combined-stream": "^1.0.8",
|
||||
"es-set-tostringtag": "^2.1.0",
|
||||
"hasown": "^2.0.2",
|
||||
"mime-types": "^2.1.12"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/frac": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://mirrors.tencent.com/npm/frac/-/frac-1.1.2.tgz",
|
||||
@@ -1436,43 +1289,6 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/get-intrinsic": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://mirrors.tencent.com/npm/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
|
||||
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"call-bind-apply-helpers": "^1.0.2",
|
||||
"es-define-property": "^1.0.1",
|
||||
"es-errors": "^1.3.0",
|
||||
"es-object-atoms": "^1.1.1",
|
||||
"function-bind": "^1.1.2",
|
||||
"get-proto": "^1.0.1",
|
||||
"gopd": "^1.2.0",
|
||||
"has-symbols": "^1.1.0",
|
||||
"hasown": "^2.0.2",
|
||||
"math-intrinsics": "^1.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/get-proto": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://mirrors.tencent.com/npm/get-proto/-/get-proto-1.0.1.tgz",
|
||||
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"dunder-proto": "^1.0.1",
|
||||
"es-object-atoms": "^1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/glob-parent": {
|
||||
"version": "6.0.2",
|
||||
"resolved": "https://mirrors.tencent.com/npm/glob-parent/-/glob-parent-6.0.2.tgz",
|
||||
@@ -1485,45 +1301,6 @@
|
||||
"node": ">=10.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/gopd": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://mirrors.tencent.com/npm/gopd/-/gopd-1.2.0.tgz",
|
||||
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/has-symbols": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://mirrors.tencent.com/npm/has-symbols/-/has-symbols-1.1.0.tgz",
|
||||
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/has-tostringtag": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://mirrors.tencent.com/npm/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
|
||||
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"has-symbols": "^1.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/hasown": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://mirrors.tencent.com/npm/hasown/-/hasown-2.0.2.tgz",
|
||||
@@ -1938,15 +1715,6 @@
|
||||
"node": ">= 20"
|
||||
}
|
||||
},
|
||||
"node_modules/math-intrinsics": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://mirrors.tencent.com/npm/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
|
||||
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/merge2": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://mirrors.tencent.com/npm/merge2/-/merge2-1.4.1.tgz",
|
||||
@@ -1981,27 +1749,6 @@
|
||||
"url": "https://github.com/sponsors/jonschlinkert"
|
||||
}
|
||||
},
|
||||
"node_modules/mime-db": {
|
||||
"version": "1.52.0",
|
||||
"resolved": "https://mirrors.tencent.com/npm/mime-db/-/mime-db-1.52.0.tgz",
|
||||
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/mime-types": {
|
||||
"version": "2.1.35",
|
||||
"resolved": "https://mirrors.tencent.com/npm/mime-types/-/mime-types-2.1.35.tgz",
|
||||
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"mime-db": "1.52.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/mini-svg-data-uri": {
|
||||
"version": "1.4.4",
|
||||
"resolved": "https://mirrors.tencent.com/npm/mini-svg-data-uri/-/mini-svg-data-uri-1.4.4.tgz",
|
||||
@@ -2321,12 +2068,6 @@
|
||||
"integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/proxy-from-env": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://mirrors.tencent.com/npm/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
|
||||
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/queue-microtask": {
|
||||
"version": "1.2.3",
|
||||
"resolved": "https://mirrors.tencent.com/npm/queue-microtask/-/queue-microtask-1.2.3.tgz",
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
"@vue-office/docx": "^1.6.3",
|
||||
"@vue-office/excel": "^1.7.14",
|
||||
"@vue-office/pdf": "^1.6.5",
|
||||
"axios": "^1.13.5",
|
||||
"highlight.js": "^11.11.1",
|
||||
"lucide-vue-next": "^0.575.0",
|
||||
"marked": "^17.0.3",
|
||||
|
||||
Loaded 100 of 418 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user