Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fe636432d0 |
No files matched your search
@@ -1,70 +0,0 @@
|
||||
---
|
||||
description: 文件层与函数层注释强制规范(撰写与调整代码时均适用)
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# 代码注释(强制)
|
||||
|
||||
撰写或**修改**代码时,必须补齐或更新两层注释。完整说明见 `AGENTS.md` §5。
|
||||
|
||||
## 文件层(文件顶部)
|
||||
|
||||
块注释须包含:**用途**、**主要 import/依赖**、**与上下游文件的逻辑关系**。
|
||||
|
||||
```typescript
|
||||
/**
|
||||
* features/kb/composables/useKbWorkspace.ts
|
||||
* 用途:知识库作业面编排入口,组合 state / computed / data 等子模块。
|
||||
* 依赖:kb-workspace/* composables、kb.api、kb-display.utils。
|
||||
* 逻辑:KbWorkspaceView 调用本 composable;本文件再分发至 useKbWorkspaceData 等子模块。
|
||||
*/
|
||||
```
|
||||
|
||||
```python
|
||||
"""
|
||||
services/kb_sync.py
|
||||
|
||||
用途:知识库文档与 Dify 之间的同步编排。
|
||||
依赖:dify_service、models.KbDocument、minio_service。
|
||||
逻辑:由 api/knowledge_base 路由调用;内部委托 chunking 与 job 状态机。
|
||||
"""
|
||||
```
|
||||
|
||||
## 函数层(每个函数定义上方)
|
||||
|
||||
须说明:**用途**、**核心逻辑与实现方式**、**参数**与**返回值**(及异常)。
|
||||
|
||||
```typescript
|
||||
/**
|
||||
* 加载当前分组下的文档列表,并在静默刷新时合并 stable 项避免闪烁。
|
||||
* 核心逻辑:调用 getKbGroupFilesSafe,按 mergeStableItems 策略合并新旧列表。
|
||||
* @param options.silent - 为 true 时不切换 loading,用于轮询刷新
|
||||
* @returns 是否成功拉取到数据
|
||||
*/
|
||||
async function loadDocuments(options?: LoadListOptions): Promise<boolean> { ... }
|
||||
```
|
||||
|
||||
```python
|
||||
def sync_document_to_dify(document_id: int, *, force: bool = False) -> SyncResult:
|
||||
"""
|
||||
将指定文档切片同步至 Dify 知识库。
|
||||
|
||||
核心逻辑:读 MinIO 原文 → 切块 → 调 Dify API upsert;失败写入 KbJob 供重试。
|
||||
|
||||
Args:
|
||||
document_id: 本地 KbDocument 主键。
|
||||
force: 为 True 时忽略已完成状态强制重同步。
|
||||
|
||||
Returns:
|
||||
SyncResult: 含 dify_document_id 与分段数。
|
||||
|
||||
Raises:
|
||||
KbNotFoundError: 文档不存在或无权限。
|
||||
"""
|
||||
```
|
||||
|
||||
## 修改既有文件时
|
||||
|
||||
- 改函数逻辑/签名 → 同步改该函数注释。
|
||||
- 改 import 或模块协作关系 → 同步改文件头注释。
|
||||
- Vue SFC:`<script setup>` 内每个函数同样要求函数层注释。
|
||||
@@ -1,112 +0,0 @@
|
||||
---
|
||||
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>` 内的每个核心函数同样要求遵循上述“函数层”注释规范。
|
||||
@@ -1,18 +0,0 @@
|
||||
.git
|
||||
.gitignore
|
||||
.venv
|
||||
venv
|
||||
**/__pycache__/
|
||||
**/*.pyc
|
||||
**/*.pyo
|
||||
**/*.log
|
||||
frontend/node_modules
|
||||
frontend/dist
|
||||
backend/venv
|
||||
backend/local_test.db
|
||||
deploy
|
||||
docs/*
|
||||
!docs/
|
||||
!docs/(表+字段).md
|
||||
tmp_restore
|
||||
tests
|
||||
@@ -1,119 +0,0 @@
|
||||
# =============================================================================
|
||||
# Development — docker compose / deploy_compose.sh dev
|
||||
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
||||
# - .env.dev / .env.test / .env.prod for deployment environments
|
||||
# =============================================================================
|
||||
ENV_NAME=dev
|
||||
FLASK_ENV=development
|
||||
DATABASE_URL=postgresql://hxops:1qaz%40WSX@127.0.0.1/hxops
|
||||
ORACLE_CLIENT_MOUNT_DIR=/home/lisq/ai/platform/hxops/oracle_client
|
||||
ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_19_31
|
||||
LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client
|
||||
|
||||
# 是否启用 JWT 认证
|
||||
AUTH_JWT_REQUIRED=true
|
||||
|
||||
AUTH_LOGIN_MODE=password
|
||||
# 如果需要用户密码登录,修改该值为password
|
||||
#AUTH_LOGIN_MODE=casdoor
|
||||
|
||||
AUTH_JWT_ISSUER=http://ait.well-trust.com:8872
|
||||
AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
|
||||
AUTH_JWT_JWKS_URL=http://192.168.100.192:8870/.well-known/jwks
|
||||
|
||||
# Casdoor
|
||||
CASDOOR_BASE_URL=http://192.168.100.192:8870
|
||||
# 以下为 hxops-dev 应用在 Casdoor 控制台里的 Client ID / Secret(勿与 prod 混用)
|
||||
CASDOOR_CLIENT_ID=758be5fcba2df784fdb4
|
||||
CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab
|
||||
# 本地开发常用;若用其它入口访问前端,请在 Casdoor 该应用的 Redirect URLs 中一并登记
|
||||
CASDOOR_REDIRECT_URI=http://localhost:8881/casdoor-callback
|
||||
CASDOOR_SCOPE=openid profile email
|
||||
CASDOOR_ORGANIZATION=organization_HX
|
||||
# Casdoor Providers → wecom(Name=wecom,与 prod 共用同一 Provider 即可)
|
||||
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
||||
|
||||
# 知识库 Dify 对接
|
||||
PUBLIC_BASE_URL=http://192.168.100.192:8890
|
||||
DIFY_API_BASE=http://192.168.100.192:8882/v1
|
||||
DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF
|
||||
DEFAULT_ADMIN_USERNAME=admin
|
||||
DEFAULT_ADMIN_PASSWORD=admin123456
|
||||
TASK_EXECUTION_MODE=sync
|
||||
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=10
|
||||
|
||||
# MinIO(知识库文档清洗图片托管;dev 与测试机同机时用测试 MinIO)
|
||||
# 本地非 Docker 跑 worker 时可改为 127.0.0.1:9000 或 192.168.100.192:9000
|
||||
# 账号与 minio-app 的 MINIO_ROOT_USER / MINIO_ROOT_PASSWORD 保持一致
|
||||
MINIO_ENDPOINT=192.168.100.192:9000
|
||||
MINIO_ACCESS_KEY=minio_testing_admin
|
||||
MINIO_SECRET_KEY=M3CLE928P8GavJBFZPhJO3RIHVZSRYlDouOMabasojfAGBlx
|
||||
MINIO_SECURE=false
|
||||
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
|
||||
|
||||
# 货代发货通知 Agent(见 docs/features/shipping-notice/technical.md §1.2;Tool 基地址见 HXOPS_TOOLS_API_BASE)
|
||||
# RoHS / 货代等 Dify Tool API 基地址(Dify 服务端内网调用,无尾斜杠)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
|
||||
# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠)
|
||||
HXOPS_PUBLIC_BASE_URL=http://192.168.100.192:8890
|
||||
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=MymLe1StfTCuMOl0IYTp-BRYKln_TnywEDxJ0X0mraYjhFtGeL8mRqoiVPlP9Er8
|
||||
|
||||
# 文件存储(相对 backend/ 根目录)
|
||||
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
||||
|
||||
# 解析与文本上限
|
||||
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
|
||||
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
|
||||
|
||||
# 字段对齐确认(生产建议 true;测试可设 false)
|
||||
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true
|
||||
|
||||
# 自动推进(auto_progress)
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=true
|
||||
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||
|
||||
# RPA 目录(相对 backend/ 根目录)
|
||||
FREIGHT_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers
|
||||
FREIGHT_RPA_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
|
||||
|
||||
# 发货 Excel 模板(可选)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
|
||||
|
||||
# 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
|
||||
|
||||
# 本地 RPA(scripts/rpa/freight_rpa_worker.py)
|
||||
FREIGHT_RPA_MOCK=false
|
||||
# FREIGHT_RPA_POLL_SECONDS=3
|
||||
# FREIGHT_RPA_SAMPLE_INVENTORY=
|
||||
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
@@ -0,0 +1,16 @@
|
||||
JWT_SECRET=change-me
|
||||
DATABASE_BACKEND=postgres
|
||||
DATABASE_URL=
|
||||
SQLITE_DATABASE_URL=sqlite:///./document_cleaning.db
|
||||
POSTGRES_DATABASE_URL=postgresql+psycopg://document_cleaning:document_cleaning@postgres:5432/document_cleaning
|
||||
PUBLIC_BASE_URL=http://127.0.0.1:8891
|
||||
DIFY_BASE_URL=https://api.dify.ai/v1
|
||||
DIFY_API_KEY=
|
||||
INTEGRATION_API_KEY=change-me-internal
|
||||
INTEGRATION_DOWNLOAD_SECRET=change-me-download-signing-secret
|
||||
DEFAULT_ADMIN_USERNAME=admin
|
||||
DEFAULT_ADMIN_PASSWORD=admin123456
|
||||
TASK_EXECUTION_MODE=rq
|
||||
DIFY_SYNC_MAX_RETRIES=4
|
||||
DIFY_SYNC_RETRY_SCHEDULE=30,60,120,300
|
||||
DIFY_SYNC_COOLDOWN_SECONDS=60
|
||||
@@ -1,96 +0,0 @@
|
||||
# =============================================================================
|
||||
# Production — docker compose env_file + deploy_compose.sh prod
|
||||
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
||||
# - .env.dev / .env.test / .env.prod for deployment environments
|
||||
# =============================================================================
|
||||
ENV_NAME=prod
|
||||
FLASK_ENV=production
|
||||
DATABASE_URL=postgresql://postgres:difyai123456@192.168.100.230:5432/hxops_db
|
||||
ORACLE_CLIENT_MOUNT_DIR=/data/ai-platform/hxops/oracle_client
|
||||
ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_19_31
|
||||
LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client
|
||||
|
||||
# 是否启用 JWT 认证
|
||||
AUTH_JWT_REQUIRED=true
|
||||
|
||||
# AUTH_LOGIN_MODE=casdoor
|
||||
# 如果需要用户密码登录,修改该值为password
|
||||
AUTH_LOGIN_MODE=password
|
||||
|
||||
AUTH_JWT_ISSUER=http://ai.well-trust.com:8870
|
||||
AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
|
||||
AUTH_JWT_JWKS_URL=http://192.168.100.230:8870/.well-known/jwks
|
||||
|
||||
# Casdoor
|
||||
CASDOOR_BASE_URL=https://auth.well-trust.com
|
||||
# 与 Casdoor 里 Application「hxops-prod」(或你当前生产应用)的 Client ID 一致
|
||||
CASDOOR_CLIENT_ID=758be5fcba2df784fdb4
|
||||
CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab
|
||||
# 兜底 redirect_uri;实际 OAuth 以浏览器地址为准,Casdoor「hxops-prod」应用须登记例如:
|
||||
# http://192.168.100.230:8881/casdoor-callback
|
||||
# http://ai.well-trust.com:8881/casdoor-callback
|
||||
CASDOOR_REDIRECT_URI=https://ai.well-trust.com/casdoor-callback
|
||||
CASDOOR_SCOPE=openid profile email
|
||||
CASDOOR_ORGANIZATION=organization_HX
|
||||
# Casdoor Providers → wecom:Name 字段(截图即为 wecom);Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo
|
||||
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
||||
|
||||
# 知识库 Dify 对接
|
||||
PUBLIC_BASE_URL=http://192.168.100.230:8891
|
||||
DIFY_API_BASE=http://192.168.100.230:8882/v1
|
||||
DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF
|
||||
DEFAULT_ADMIN_USERNAME=admin
|
||||
DEFAULT_ADMIN_PASSWORD=admin123456
|
||||
TASK_EXECUTION_MODE=rq
|
||||
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=20
|
||||
|
||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
|
||||
WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||
|
||||
# MinIO(知识库文档清洗图片托管,容器 minio-app)
|
||||
# MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1)
|
||||
MINIO_ENDPOINT=host.docker.internal:9000
|
||||
MINIO_ACCESS_KEY=admin
|
||||
MINIO_SECRET_KEY=difyai123456
|
||||
MINIO_SECURE=false
|
||||
# MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问
|
||||
MINIO_PUBLIC_BASE_URL=http://ai.well-trust.com:9000
|
||||
|
||||
# RoHS / 货代 / 设备维保等 Dify Tool API 基地址(Dify 服务端内网调用,无尾斜杠)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.230:8890
|
||||
# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠)
|
||||
HXOPS_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||
|
||||
# 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh
|
||||
|
||||
# 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享)
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
FREIGHT_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/inventory_drop
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/inventory_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/upload_queue
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/upload_triggers
|
||||
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致)
|
||||
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
||||
# 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
|
||||
|
||||
# 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
||||
|
||||
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
-162
@@ -1,162 +0,0 @@
|
||||
# Shared environment variables for all environments (dev/test/prod)
|
||||
# Keep only values that are truly identical across all environments.
|
||||
|
||||
# Runtime selector fallback (actual deployment still sets ENV_NAME explicitly)
|
||||
ENV_NAME=dev
|
||||
# Common runtime defaults
|
||||
FLASK_APP=run.py
|
||||
|
||||
# 知识库管理(后续需要修改此地址)
|
||||
# 查「Dify 文档对应原始源文件下载地址」时,要连的那台 Integration API 的根 URL
|
||||
INTEGRATION_API_BASE=http://192.168.100.230:8891
|
||||
# 连接文档清洗系统的API KEY
|
||||
INTEGRATION_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
# 文件检核 Tool API Key;未单独配置时建议与 INTEGRATION_API_KEY 保持一致
|
||||
FILE_CHECK_TOOL_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
|
||||
SECRET_KEY=hxops-dify
|
||||
|
||||
# Knowledge base runtime
|
||||
# KB_STORAGE_ROOT=backend/data/kb
|
||||
KB_TASK_EXECUTION_MODE=worker
|
||||
KB_WORKER_POLL_SECONDS=2
|
||||
KB_WORKER_CONCURRENCY=3
|
||||
# Linux 容器内 LibreOffice 路径(避免探测 Windows 安装路径)
|
||||
EDKB_SOFFICE=/usr/bin/soffice
|
||||
# LibreOffice 单次格式转换超时(秒);复杂 .doc 在容器内可能需 10 分钟左右
|
||||
EDKB_SOFFICE_TIMEOUT_SEC=600
|
||||
# Windows Word COM / word_bridge 单次转换超时(秒);复杂 .doc 可适当放宽
|
||||
EDKB_WORD_TIMEOUT_SEC=300
|
||||
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免单条任务长期卡住整个 worker
|
||||
EDKB_FILE_TIMEOUT_SEC=300
|
||||
# Word 文档(.doc/.docx)单文件清洗总超时(秒);优先于 EDKB_FILE_TIMEOUT_SEC
|
||||
EDKB_WORD_FILE_TIMEOUT_SEC=420
|
||||
# running 任务回收阈值,须大于 EDKB_SOFFICE_TIMEOUT_SEC 及整条清洗链路耗时
|
||||
KB_JOB_RUNNING_TIMEOUT_SECONDS=900
|
||||
|
||||
# chat回答的评分与评论
|
||||
FEEDBACK_ENABLED=true
|
||||
|
||||
# Common auth defaults
|
||||
AUTH_LEGACY_HEADER_ENABLED=true
|
||||
AUTH_JWT_REQUIRED=true
|
||||
|
||||
# 是否保留本地密码登录/本地TWT兼容
|
||||
AUTH_ALLOW_LOCAL_PASSWORD_LOGIN=true
|
||||
AUTH_ALLOW_LOCAL_JWT=true
|
||||
AUTH_LOCAL_JWT_ISSUER=hxops-backend
|
||||
AUTH_LOCAL_JWT_AUDIENCE=hxops-frontend
|
||||
AUTH_LOCAL_JWT_EXPIRES_HOURS=12
|
||||
|
||||
# WeCom
|
||||
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
|
||||
WECOM_MATCH_OPERATOR=AND
|
||||
WECOM_FIRST_LOGIN_BIND_MODE=match_rules
|
||||
WECOM_FIRST_LOGIN_INPUT_FIELDS=employee_id,mobile,email
|
||||
WECOM_EMPLOYEE_ID_SOURCE=userid
|
||||
WECOM_MOBILE_NORMALIZE=true
|
||||
WECOM_CALLBACK_TOKEN=
|
||||
WECOM_ENCODING_AES_KEY=
|
||||
WECOM_CALLBACK_URL=
|
||||
WECOM_HOMEPAGE_URL=
|
||||
WECOM_TRUSTED_DOMAIN=
|
||||
# Public HTTPS origin for WeCom console URLs (takes priority over notify base + request host)
|
||||
WECOM_PUBLIC_BASE_URL=
|
||||
WECOM_NOTIFY_ENABLED=true
|
||||
WECOM_NOTIFY_BASE_URL=
|
||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset
|
||||
WECOM_FEEDBACK_NOTIFY_ENABLED=true
|
||||
WECOM_FEEDBACK_NOTIFY_BASE_URL=http://ai.well-trust.com:8881
|
||||
# 企业微信群机器人 webhook,按环境写入 .env.<env> 或部署平台变量;不要提交真实 URL。
|
||||
WECOM_FEEDBACK_BOT_WEBHOOK=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=bdb65cf6-e537-44b2-a10b-d826b15f4498
|
||||
|
||||
|
||||
# Common integration defaults
|
||||
INTEGRATION_API_MODE=local
|
||||
DIFY_API_BASE=https://api.dify.ai/v1
|
||||
# HXOPS Tool API 对外基地址(RoHS / 货代等 Dify Chatflow 服务端调用;无尾斜杠;各环境 .env.* 覆盖)
|
||||
HXOPS_TOOLS_API_BASE=
|
||||
# HXOPS 浏览器可访问根地址(Excel 签名下载等用户可见链接;无尾斜杠;各环境 .env.* 覆盖)
|
||||
HXOPS_PUBLIC_BASE_URL=
|
||||
|
||||
# MinIO:按环境配置见 .env.dev / .env.test / .env.prod
|
||||
# MINIO_KB_IMAGE_BUCKET — 知识库文档清洗图片托管(kb-worker / export)
|
||||
# MINIO_AGENT_GUIDES_BUCKET — Agent 指南文件上传(Flask minio_service)
|
||||
MINIO_KB_IMAGE_BUCKET=image-hosting-service
|
||||
MINIO_AGENT_GUIDES_BUCKET=agent-guides
|
||||
|
||||
# 硅基流动相关
|
||||
GJL_API_KEY=sk-umfzicwjcvwampzblqczckkqojiscyybtaljzbsvpdwdvxlu
|
||||
GJL_API_BASE=https://api.siliconflow.cn/v1
|
||||
GJL_MODEL=deepseek-ai/DeepSeek-V3
|
||||
# 硅基流动 ASR:FunAudioLLM/SenseVoiceSmall 或 TeleAI/TeleSpeechASR
|
||||
ASR_MODEL=FunAudioLLM/SenseVoiceSmall
|
||||
|
||||
# HR SQL Server Configuration
|
||||
HR_SQLSERVER_HOST=192.168.100.191
|
||||
HR_SQLSERVER_PORT=1433
|
||||
HR_SQLSERVER_DATABASE=NH_N8_HEXIN
|
||||
HR_SQLSERVER_USERNAME=AI_Knowledge_Base_Hr
|
||||
HR_SQLSERVER_PASSWORD=hoo-thai@123_AI_HR
|
||||
HR_SQLSERVER_DRIVER=ODBC Driver 18 for SQL Server
|
||||
HR_SQLSERVER_ENCRYPT=no
|
||||
HR_SQLSERVER_TRUST_CERT=yes
|
||||
HR_SQLSERVER_TIMEOUT=10
|
||||
|
||||
# PLM Oracle
|
||||
PLM_ORACLE_HOST=192.168.0.11
|
||||
PLM_ORACLE_PORT=1521
|
||||
PLM_ORACLE_SID=orcl
|
||||
PLM_ORACLE_USERNAME=PLM
|
||||
PLM_ORACLE_PASSWORD=PLM
|
||||
|
||||
# SRM SQL Server Configuration
|
||||
SRM_SQLSERVER_HOST=192.168.55.106
|
||||
SRM_SQLSERVER_PORT=1433
|
||||
SRM_SQLSERVER_DATABASE=HX-SRM
|
||||
SRM_SQLSERVER_USERNAME=sa
|
||||
SRM_SQLSERVER_PASSWORD=sa@moreyou456
|
||||
SRM_SQLSERVER_DRIVER=ODBC Driver 18 for SQL Server
|
||||
SRM_SQLSERVER_ENCRYPT=no
|
||||
SRM_SQLSERVER_TRUST_CERT=yes
|
||||
SRM_SQLSERVER_TIMEOUT=10
|
||||
|
||||
# ERP
|
||||
ERP_DB_DSN=192.168.8.24:1521/topprod
|
||||
TEXT2SQL_SCHEMA_PATH=
|
||||
|
||||
# 固资履历共享盘
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
||||
|
||||
# 固资图片文档库
|
||||
FIXED_ASSET_IMAGE_BASE_URL=http://192.168.8.158:8071/Web/#/login
|
||||
FIXED_ASSET_IMAGE_USERNAME=26040006
|
||||
FIXED_ASSET_IMAGE_PASSWORD=26040006
|
||||
FIXED_ASSET_IMAGE_LIBRARY_ID=8d61bd96-ff2d-489b-86fc-ca0b8c6bbcf8
|
||||
FIXED_ASSET_IMAGE_FOLDER_ID=3aea6c19-d9ac-40fa-ab16-9cb06c0db3e3
|
||||
|
||||
# 热点 FAQ 离线聚合(ChatLog -> PostgreSQL faq_hot_candidates 表)
|
||||
# 管理端「常用问题 > 热点发现」刷新聚合时读取以下配置
|
||||
FAQ_HOT_ENABLED=true # 是否启用热点聚合(false 时刷新/CLI 直接跳过)
|
||||
FAQ_HOT_WINDOW_DAYS=7 # 统计时间窗口(天),仅扫描近 N 天 ChatLog
|
||||
FAQ_HOT_MIN_COUNT=5 # 同一应用+问句最少提问次数,低于此不进入候选
|
||||
FAQ_HOT_MIN_USERS=3 # 最少独立用户数,防止单人刷榜
|
||||
FAQ_HOT_MIN_AVG_TOKENS=0 # 组内平均 token 下限(0=不限制;须 tokens_used>0 才纳入)
|
||||
FAQ_HOT_MAX_QUERY_LEN=200 # 问句最大字符数,过长跳过
|
||||
FAQ_HOT_MIN_QUERY_LEN=4 # 问句最短字符数,过短跳过
|
||||
FAQ_HOT_MIN_ANSWER_LEN=8 # 答案最短字符数,过短跳过
|
||||
FAQ_HOT_TTL_SECONDS=604800 # 候选/忽略黑名单有效期(秒),默认 7 天
|
||||
FAQ_HOT_ANSWER_SIMILARITY=0.95 # (聚类已关闭)答案聚类相似度阈值,恢复聚类时生效
|
||||
FAQ_HOT_ANSWER_DOMINANCE=0.6 # (聚类已关闭)最大答案簇占比下限,恢复聚类时生效
|
||||
FAQ_HOT_GOOD_SCORE=4 # 选代表答案时「好评」反馈分阈值(≥此分优先)
|
||||
FAQ_HOT_BAD_SCORE=2 # 选代表答案时「差评」反馈分阈值(≤此分排除)
|
||||
# Freight RPA defaults to real browser automation. Set to true only for local mock/debug runs.
|
||||
FREIGHT_RPA_MOCK=false
|
||||
@@ -1,142 +0,0 @@
|
||||
# =============================================================================
|
||||
# Test — docker compose / deploy_compose.sh test
|
||||
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
||||
# - .env.dev / .env.test / .env.prod for deployment environments
|
||||
# =============================================================================
|
||||
ENV_NAME=test
|
||||
FLASK_ENV=test
|
||||
DATABASE_URL=postgresql://postgres:8je2olWwHj28fCfVTgRWmankoTQORjqyBn6iIK3dG2q10vAq@192.168.100.192:5432/hxops_testing
|
||||
ORACLE_CLIENT_MOUNT_DIR=/home/lisq/ai/platform/hxops/oracle_client
|
||||
ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_23_26
|
||||
LD_LIBRARY_PATH=/app/oracle_client/instantclient_23_26:/app/oracle_client
|
||||
|
||||
# 是否启用 JWT 认证
|
||||
AUTH_JWT_REQUIRED=true
|
||||
|
||||
AUTH_LOGIN_MODE=casdoor
|
||||
# 如果需要用户密码登录,修改该值为password
|
||||
#AUTH_LOGIN_MODE=casdoor
|
||||
|
||||
AUTH_JWT_ISSUER=http://ait.well-trust.com:8872
|
||||
AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
|
||||
AUTH_JWT_JWKS_URL=http://192.168.100.192:8870/.well-known/jwks
|
||||
|
||||
# Casdoor
|
||||
CASDOOR_BASE_URL=https://autht.well-trust.com
|
||||
# 与 Casdoor 里 Application「hxops-prod」(或你当前生产应用)的 Client ID 一致
|
||||
CASDOOR_CLIENT_ID=758be5fcba2df784fdb4
|
||||
CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab
|
||||
# 兜底 redirect_uri;实际 OAuth 以浏览器地址为准,Casdoor「hxops-prod」应用须登记例如:
|
||||
# http://192.168.100.192:8881/casdoor-callback
|
||||
# http://ai.well-trust.com:8881/casdoor-callback
|
||||
CASDOOR_REDIRECT_URI=https://ait.well-trust.com/casdoor-callback
|
||||
CASDOOR_SCOPE=openid profile email
|
||||
CASDOOR_ORGANIZATION=organization_HX
|
||||
# Casdoor Providers → wecom:Name 字段;Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo
|
||||
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
||||
|
||||
# 知识库 Dify 对接
|
||||
PUBLIC_BASE_URL=http://192.168.100.192:8891
|
||||
DIFY_API_BASE=http://192.168.100.192:8882/v1
|
||||
DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF
|
||||
DEFAULT_ADMIN_USERNAME=admin
|
||||
DEFAULT_ADMIN_PASSWORD=admin123456
|
||||
TASK_EXECUTION_MODE=rq
|
||||
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=6
|
||||
|
||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||
WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
|
||||
WECOM_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||
HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||
|
||||
# MinIO(知识库文档清洗图片托管,容器 minio-app)
|
||||
# MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1)
|
||||
# 账号与 minio-app 的 MINIO_ROOT_USER / MINIO_ROOT_PASSWORD(及 DIFY_S3_ACCESS_KEY)保持一致
|
||||
MINIO_ENDPOINT=host.docker.internal:9000
|
||||
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
|
||||
|
||||
# 货代发货通知 Agent(见 docs/features/shipping-notice/technical.md §1.2;Tool 基地址见 HXOPS_TOOLS_API_BASE)
|
||||
# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
|
||||
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||
HXOPS_TOOLS_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
# 货代专用 Tool API Key(RPA 回调优先读取;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=GOnGt04o0-Ev4wEw6a6C4NOmm4XF7dxsLPP6fPtTC2vV341l1QKVASV75ONj72er
|
||||
|
||||
# 文件存储(相对 backend/ 根目录)
|
||||
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
||||
|
||||
# 解析与文本上限
|
||||
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
|
||||
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
|
||||
|
||||
# 字段对齐确认(生产建议 true;测试可设 false)
|
||||
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true
|
||||
|
||||
# 自动推进(auto_progress)
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
|
||||
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||
|
||||
# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享)
|
||||
FREIGHT_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers
|
||||
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐)
|
||||
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
||||
# 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微
|
||||
# 两者皆无则告警只写日志、不会发企微
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
|
||||
# 企微发送中短锁秒数(发送失败过期后可重试,默认 120)
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
|
||||
|
||||
# 发货 Excel 模板(可选)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
|
||||
|
||||
# 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
||||
|
||||
# AWS 库存列映射(可选 JSON 字符串)
|
||||
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
|
||||
|
||||
# Dify Chatflow(seed_shipping_notice_agents.py)
|
||||
SHIPPING_NOTICE_CHAT_DIFY_APP_ID=
|
||||
SHIPPING_NOTICE_CHAT_DIFY_API_KEY=
|
||||
SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
|
||||
|
||||
# 本地 Mock RPA(scripts/rpa/freight_rpa_worker.py,可选)
|
||||
# FREIGHT_RPA_MOCK=true
|
||||
# FREIGHT_RPA_POLL_SECONDS=3
|
||||
# FREIGHT_RPA_SAMPLE_INVENTORY=
|
||||
|
||||
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
@@ -1,130 +0,0 @@
|
||||
# shellcheck shell=bash
|
||||
# 供 pre-commit / pre-push 引用;勿直接执行。
|
||||
|
||||
hook_should_skip() {
|
||||
[[ "${SKIP_GIT_HOOKS:-}" == "1" ]] || [[ "${SKIP_FRONTEND_HOOKS:-}" == "1" ]]
|
||||
}
|
||||
|
||||
frontend_paths_in() {
|
||||
local file_list="${1:-}"
|
||||
echo "${file_list}" | grep -qE '^frontend/'
|
||||
}
|
||||
|
||||
ensure_frontend_deps() {
|
||||
local frontend_dir="${1}/frontend"
|
||||
if [[ ! -d "${frontend_dir}/node_modules" ]]; then
|
||||
echo "[git-hook] frontend/node_modules 不存在,请先执行:"
|
||||
echo " cd frontend && npm install"
|
||||
return 1
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
run_frontend_typecheck() {
|
||||
local root_dir="${1}"
|
||||
echo "[pre-commit] 检测到 frontend/ 变更,运行 vue-tsc 类型检查..."
|
||||
if ! ensure_frontend_deps "${root_dir}"; then
|
||||
return 1
|
||||
fi
|
||||
(
|
||||
cd "${root_dir}/frontend"
|
||||
npx vue-tsc -b --pretty false
|
||||
)
|
||||
}
|
||||
|
||||
run_frontend_build() {
|
||||
local root_dir="${1}"
|
||||
echo "[pre-push] 检测到将要推送的提交包含 frontend/ 变更,运行 npm run build..."
|
||||
if ! ensure_frontend_deps "${root_dir}"; then
|
||||
return 1
|
||||
fi
|
||||
(
|
||||
cd "${root_dir}/frontend"
|
||||
npm run build
|
||||
)
|
||||
}
|
||||
|
||||
ensure_commitlint_deps() {
|
||||
local root_dir="${1}"
|
||||
if [[ ! -d "${root_dir}/node_modules/@commitlint/cli" ]]; then
|
||||
echo "[commit-msg] 根目录 node_modules 不存在,请先执行:"
|
||||
echo " cd ${root_dir}"
|
||||
echo " npm install"
|
||||
echo " 或重新运行: ./scripts/install_git_hooks.sh"
|
||||
return 1
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
run_commitlint() {
|
||||
local root_dir="${1}"
|
||||
local msg_file="${2}"
|
||||
if ! ensure_commitlint_deps "${root_dir}"; then
|
||||
return 1
|
||||
fi
|
||||
(
|
||||
cd "${root_dir}"
|
||||
npx --no-install commitlint --edit "${msg_file}"
|
||||
)
|
||||
}
|
||||
|
||||
resolve_python_cmd() {
|
||||
# 优先使用 backend 虚拟环境内的 Python,与日常 flask 开发环境一致
|
||||
local root_dir="${1}"
|
||||
local candidates=(
|
||||
"${root_dir}/backend/.venv/bin/python"
|
||||
"${root_dir}/backend/.venv/Scripts/python.exe"
|
||||
"${root_dir}/backend/venv/bin/python"
|
||||
"${root_dir}/backend/venv/Scripts/python.exe"
|
||||
)
|
||||
local candidate
|
||||
for candidate in "${candidates[@]}"; do
|
||||
if [[ -x "${candidate}" ]]; then
|
||||
echo "${candidate}"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
if command -v python3 >/dev/null 2>&1; then
|
||||
echo "python3"
|
||||
return 0
|
||||
fi
|
||||
if command -v python >/dev/null 2>&1; then
|
||||
echo "python"
|
||||
return 0
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
run_migration_heads_check() {
|
||||
# 调用 scripts/check_migration_heads.py:
|
||||
# - 校验 Alembic 仅 1 个 head
|
||||
# - 可选传入本次新增的 migration 路径,校验 down_revision
|
||||
# 注意:不可被 SKIP_FRONTEND_HOOKS 跳过(见 pre-commit 调用处)
|
||||
local root_dir="${1}"
|
||||
local staged_new_migrations="${2:-}"
|
||||
local python_cmd
|
||||
local -a check_args=()
|
||||
|
||||
if ! python_cmd="$(resolve_python_cmd "${root_dir}")"; then
|
||||
echo "[pre-commit] 未找到 Python,无法校验 migration heads。"
|
||||
echo "[pre-commit] 请先配置 backend 虚拟环境,或确保 python/python3 在 PATH 中。"
|
||||
return 1
|
||||
fi
|
||||
|
||||
echo "[pre-commit] 校验 Alembic migration 链(必须仅 1 个 head)..."
|
||||
if [[ -n "${staged_new_migrations}" ]]; then
|
||||
while IFS= read -r migration_file; do
|
||||
[[ -n "${migration_file}" ]] || continue
|
||||
check_args+=("${root_dir}/${migration_file}")
|
||||
done <<< "${staged_new_migrations}"
|
||||
fi
|
||||
|
||||
if ! "${python_cmd}" "${root_dir}/scripts/check_migration_heads.py" "${check_args[@]}"; then
|
||||
echo "[pre-commit] migration heads 校验失败,已阻止提交。"
|
||||
echo "[pre-commit] migration 检查不可通过 SKIP_FRONTEND_HOOKS 跳过;仅可使用 git commit --no-verify"
|
||||
return 1
|
||||
fi
|
||||
|
||||
echo "[pre-commit] migration heads 校验通过。"
|
||||
return 0
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(git rev-parse --show-toplevel)"
|
||||
cd "${ROOT_DIR}"
|
||||
# shellcheck source=_common.sh
|
||||
source "${ROOT_DIR}/.githooks/_common.sh"
|
||||
|
||||
COMMIT_MSG_FILE="${1:-}"
|
||||
|
||||
if [[ -z "${COMMIT_MSG_FILE}" ]]; then
|
||||
echo "[commit-msg] missing commit message file path."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ -f "${ROOT_DIR}/.git/MERGE_HEAD" ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if ! run_commitlint "${ROOT_DIR}" "${COMMIT_MSG_FILE}"; then
|
||||
echo "[commit-msg] 提交信息不符合规范,详见 docs/convention/COMMIT_CONVENTION.md"
|
||||
echo "[commit-msg] 示例: feat(auth): add SMS login support"
|
||||
echo "[commit-msg] 跳过校验: git commit --no-verify"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
exit 0
|
||||
@@ -1,58 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(git rev-parse --show-toplevel)"
|
||||
cd "${ROOT_DIR}"
|
||||
# shellcheck source=_common.sh
|
||||
source "${ROOT_DIR}/.githooks/_common.sh"
|
||||
|
||||
STAGED_FILES="$(git diff --cached --name-only --diff-filter=ACMR || true)"
|
||||
if [[ -z "${STAGED_FILES}" ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
MODELS_CHANGED=0
|
||||
MIGRATION_CHANGED=0
|
||||
|
||||
if echo "${STAGED_FILES}" | grep -Eq '^backend/app/models\.py$'; then
|
||||
MODELS_CHANGED=1
|
||||
fi
|
||||
|
||||
if echo "${STAGED_FILES}" | grep -Eq '^backend/migrations/versions/.*\.py$'; then
|
||||
MIGRATION_CHANGED=1
|
||||
fi
|
||||
|
||||
if [[ "${MODELS_CHANGED}" -eq 1 && "${MIGRATION_CHANGED}" -eq 0 ]]; then
|
||||
echo "[pre-commit] 检测到 backend/app/models.py 已暂存,但未检测到 migration 文件暂存。"
|
||||
echo "[pre-commit] 请先执行:"
|
||||
echo " cd backend"
|
||||
echo " venv/bin/flask --app manage.py db migrate -m \"your_change\""
|
||||
echo " venv/bin/flask --app manage.py db upgrade"
|
||||
echo " git add backend/migrations/versions/*.py"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# migration 链校验:防止多人并行 migration 合并后出现多 head,部署时 db upgrade 失败
|
||||
# 实现见 scripts/check_migration_heads.py(离线读文件,无需数据库)
|
||||
if [[ "${MIGRATION_CHANGED}" -eq 1 ]]; then
|
||||
STAGED_NEW_MIGRATIONS="$(git diff --cached --name-only --diff-filter=A -- 'backend/migrations/versions/*.py' || true)"
|
||||
if ! run_migration_heads_check "${ROOT_DIR}" "${STAGED_NEW_MIGRATIONS}"; then
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
if hook_should_skip; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if frontend_paths_in "${STAGED_FILES}"; then
|
||||
if ! run_frontend_typecheck "${ROOT_DIR}"; then
|
||||
echo "[pre-commit] vue-tsc 失败,已阻止提交。"
|
||||
echo "[pre-commit] 跳过前端检查: SKIP_FRONTEND_HOOKS=1 git commit"
|
||||
echo "[pre-commit] 或跳过全部 hook: git commit --no-verify"
|
||||
exit 1
|
||||
fi
|
||||
echo "[pre-commit] frontend 类型检查通过。"
|
||||
fi
|
||||
|
||||
exit 0
|
||||
@@ -1,68 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(git rev-parse --show-toplevel)"
|
||||
# shellcheck source=_common.sh
|
||||
source "${ROOT_DIR}/.githooks/_common.sh"
|
||||
|
||||
if [[ "${SKIP_GIT_HOOKS:-}" == "1" ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
zero="0000000000000000000000000000000000000000"
|
||||
need_migration_check=0
|
||||
need_frontend_build=0
|
||||
|
||||
while read -r local_ref local_sha remote_ref remote_sha; do
|
||||
[[ "${local_sha}" == "${zero}" ]] && continue
|
||||
|
||||
changed_files=""
|
||||
if [[ "${remote_sha}" == "${zero}" ]]; then
|
||||
upstream_ref="$(git rev-parse --abbrev-ref --symbolic-full-name '@{u}' 2>/dev/null || true)"
|
||||
if [[ -n "${upstream_ref}" ]]; then
|
||||
remote_branch="${upstream_ref#*/}"
|
||||
remote_name="${upstream_ref%%/*}"
|
||||
merge_base="$(git merge-base "${local_sha}" "${remote_name}/${remote_branch}" 2>/dev/null || true)"
|
||||
if [[ -n "${merge_base}" ]]; then
|
||||
changed_files="$(git diff --name-only --diff-filter=ACMR "${merge_base}" "${local_sha}" || true)"
|
||||
fi
|
||||
fi
|
||||
if [[ -z "${changed_files}" ]]; then
|
||||
changed_files="$(git diff-tree --no-commit-id --name-only --diff-filter=ACMR -r "${local_sha}" || true)"
|
||||
fi
|
||||
else
|
||||
changed_files="$(git diff --name-only --diff-filter=ACMR "${remote_sha}" "${local_sha}" || true)"
|
||||
fi
|
||||
|
||||
if echo "${changed_files}" | grep -qE '^backend/migrations/versions/.*\.py$'; then
|
||||
need_migration_check=1
|
||||
fi
|
||||
|
||||
if frontend_paths_in "${changed_files}"; then
|
||||
need_frontend_build=1
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ "${need_migration_check}" -eq 1 ]]; then
|
||||
if ! run_migration_heads_check "${ROOT_DIR}"; then
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ "${SKIP_FRONTEND_HOOKS:-}" == "1" ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [[ "${need_frontend_build}" -eq 0 ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if ! run_frontend_build "${ROOT_DIR}"; then
|
||||
echo "[pre-push] 前端 build 失败,已阻止 push。"
|
||||
echo "[pre-push] 跳过检查可设置: SKIP_FRONTEND_HOOKS=1 git push"
|
||||
echo "[pre-push] 或跳过全部 hook: git push --no-verify"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "[pre-push] 前端 build 通过。"
|
||||
exit 0
|
||||
+70
-83
@@ -1,88 +1,75 @@
|
||||
# Environments
|
||||
#docs/
|
||||
venv/
|
||||
backend/venv/
|
||||
backend/instance/
|
||||
tmpwork/
|
||||
env/
|
||||
# =========================
|
||||
# Secrets / env
|
||||
# =========================
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
backend.env
|
||||
backend.env.*
|
||||
!backend.env.example
|
||||
*.key
|
||||
*.pem
|
||||
*secret*
|
||||
*token*
|
||||
|
||||
# .env
|
||||
.venv
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# Pytest / local temp
|
||||
backend/.pytest_tmp/
|
||||
.pytest_tmp/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# Root tooling (commitlint)
|
||||
/node_modules/
|
||||
package-lock.json
|
||||
|
||||
# Frontend
|
||||
frontend/node_modules/
|
||||
frontend/dist/
|
||||
frontend/.DS_Store
|
||||
frontend/.env.local
|
||||
frontend/.env.*.local
|
||||
frontend/.npm-cache
|
||||
frontend/public/WW_verify_46MjWA55y3PBRLid.txt
|
||||
frontend/package-lock.json
|
||||
|
||||
# IDEs
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/extensions.json
|
||||
.trae/*
|
||||
.cursor/*
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
.cursorrules
|
||||
|
||||
# Runtime files
|
||||
.run/
|
||||
|
||||
# OS
|
||||
# =========================
|
||||
# OS / IDE
|
||||
# =========================
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
.idea/
|
||||
.vscode/
|
||||
|
||||
# Runtime files
|
||||
.run/
|
||||
# tmp
|
||||
.tmp/
|
||||
.tmp2/
|
||||
|
||||
.npm-cache
|
||||
.npm-cache2
|
||||
.pip-cache
|
||||
|
||||
|
||||
# 忽略Oracle Instant Client本地目录
|
||||
oracle_client/
|
||||
|
||||
# local env override
|
||||
.env.local
|
||||
backend/data/kb/
|
||||
# =========================
|
||||
# Python
|
||||
# =========================
|
||||
__pycache__/
|
||||
*.pyc
|
||||
*.pyo
|
||||
*.pyd
|
||||
.pytest_cache/
|
||||
backend/data/fixed_assets/manifest.json
|
||||
backend/data/shipping_notice/
|
||||
backend/data/logs/
|
||||
backend/data/logs/*.log
|
||||
.venv/
|
||||
venv/
|
||||
python/
|
||||
|
||||
# =========================
|
||||
# Node
|
||||
# =========================
|
||||
frontend/node_modules/
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# =========================
|
||||
# Build outputs
|
||||
# =========================
|
||||
frontend/dist/
|
||||
dist/
|
||||
build/
|
||||
out/
|
||||
target/
|
||||
|
||||
# =========================
|
||||
# Runtime temp/logs
|
||||
# =========================
|
||||
tmp_run/
|
||||
*.log
|
||||
|
||||
# =========================
|
||||
# Databases (不要提交测试数据/本地库)
|
||||
# =========================
|
||||
*.db
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
|
||||
# =========================
|
||||
# Archives / bundles (不要提交打包产物)
|
||||
# =========================
|
||||
*.zip
|
||||
*.tar.gz
|
||||
*.tgz
|
||||
|
||||
# =========================
|
||||
# Optional: staging deploy output (如果是生成物就忽略)
|
||||
# =========================
|
||||
.deploy-stage/
|
||||
Vendored
-3
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"recommendations": ["ms-python.python", "ms-python.vscode-pylance"]
|
||||
}
|
||||
Vendored
-59
@@ -1,59 +0,0 @@
|
||||
{
|
||||
// 后端 Python 虚拟环境(解释器路径供语言服务/调试使用)
|
||||
"python.defaultInterpreterPath": "${workspaceFolder}/backend/.venv/Scripts/python.exe",
|
||||
// 关闭 Python 扩展在新建终端时自动 activate,避免与下方 PowerShell (HXOPS) 的 cd 钩子重复激活
|
||||
"python.terminal.activateEnvironment": false,
|
||||
"python.venvPath": "${workspaceFolder}/backend",
|
||||
"python.venvFolders": [".venv"],
|
||||
"github.copilot.chat.commitMessageGeneration.instructions": [
|
||||
{
|
||||
"text": "Generate Git commit messages in Simplified Chinese by default."
|
||||
},
|
||||
{
|
||||
"text": "Follow Conventional Commits format: <type>(<scope>): <subject>."
|
||||
},
|
||||
{
|
||||
"text": "Use English for type and scope; use Simplified Chinese for subject and body."
|
||||
},
|
||||
{
|
||||
"text": "Allowed types are feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert."
|
||||
},
|
||||
{
|
||||
"text": "The subject must be imperative, no period at the end, and no longer than 100 Chinese characters."
|
||||
},
|
||||
{
|
||||
"text": "Avoid vague messages such as update, fix bug, or WIP."
|
||||
},
|
||||
{
|
||||
"text": "When a body is useful, write concise Chinese bullet points describing concrete changes."
|
||||
}
|
||||
],
|
||||
|
||||
// 默认终端:加载 cd 钩子,进入 backend 时自动激活 .venv
|
||||
"terminal.integrated.defaultProfile.windows": "PowerShell (HXOPS)",
|
||||
"terminal.integrated.profiles.windows": {
|
||||
"PowerShell (HXOPS)": {
|
||||
"source": "PowerShell",
|
||||
"icon": "terminal-powershell",
|
||||
"args": [
|
||||
"-NoExit",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-File",
|
||||
"${workspaceFolder}/scripts/powershell-backend-auto-venv.ps1"
|
||||
]
|
||||
},
|
||||
"HXOPS Backend": {
|
||||
"source": "PowerShell",
|
||||
"icon": "server-environment",
|
||||
"args": [
|
||||
"-NoExit",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-Command",
|
||||
"Set-Location '${workspaceFolder}/backend'; if (Test-Path '.venv/Scripts/Activate.ps1') { . '.venv/Scripts/Activate.ps1' }"
|
||||
]
|
||||
}
|
||||
},
|
||||
"js/ts.tsdk.path": "node_modules\\typescript\\lib"
|
||||
}
|
||||
-196
@@ -1,196 +0,0 @@
|
||||
# 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) |
|
||||
@@ -1,205 +0,0 @@
|
||||
# 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/
|
||||
main.ts · App.vue · i18n.ts · config.ts # Vite 入口(保留 src 根)
|
||||
app/ # 应用基础设施:router/(routes/* · guards)、plugins/pinia
|
||||
shared/ # 跨域共享(无业务语义)
|
||||
# api/client · composables · components · layouts · utils · styles
|
||||
features/ # 业务域垂直切分(新代码主要落在这里)
|
||||
# auth · workspace · chat · admin · kb
|
||||
# 域内:api/ · composables/ · views/ · stores/ · components/
|
||||
# admin 子模块:modules/<name>/*Page.vue + use*Admin.ts
|
||||
locales/ # i18n 四语言 JSON(zh-CN / zh-TW / en / th),按域拆分
|
||||
scripts/ # 部署与运维脚本(deploy_compose.sh、healthcheck.sh ...)
|
||||
docs/ # 权威文档(规范、上下文、流程、发布说明)
|
||||
# features/ 业务域手册 · platform/ 平台设计 · prototype/ 产品原型
|
||||
# convention/ · openapi/ · dify/ · refactor/
|
||||
```
|
||||
|
||||
**约定**:
|
||||
|
||||
- **后端**:新逻辑优先放入 `services/`,复用 `response_utils` / `errors` / `decorators` 模式,不要另造轮子。
|
||||
- **前端**:Feature-Module + Composables + Pinia;新功能放入 `features/<domain>/`(`api/` · `composables/` · `views/` 等),跨域通用代码放 `shared/`;HTTP 统一 `@/shared/api/client`。**禁止**在已废弃的 `src/api/`、`src/views/`、`src/composables/` 等路径新增代码。完整规范见 **[docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md)**。
|
||||
|
||||
---
|
||||
|
||||
## 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. 代码规范与注释 (Code & Comments)
|
||||
|
||||
> **适用范围**:**新建或调整**业务代码(人工与 AI Agent 均适用)。
|
||||
> **核心理念**:我们的注释采用“三层结构”,**既是写给人类团队看的,更是写给 AI(大模型/代码助手)看的**。
|
||||
> 🚨 **详细规范与标准范例,请严格遵循:[`.cursor/rules/code-comments.mdc`](.cursor/rules/code-comments.mdc)**。
|
||||
|
||||
### 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>`;`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 生成/重构代码同样适用,不得省略。
|
||||
- ⚠️ **错误处理统一契约**:JSON API 使用 `{ success, data | error, request_id }` envelope;后端业务失败 **`raise AppError` 子类**(`app/core/errors.py`),禁止新写 `jsonify({"error": ...})`;前端 HTTP 统一 **`requestJson`**(`@/shared/api/client`),失败为 **`BusinessError`**,在 composable/view 用 **`useMessage()`** 展示;新增 `error.code` 须同步四语言 **`locales/*/errors.json`**。详见 **[docs/convention/error_handling.md](docs/convention/error_handling.md)**。
|
||||
- ⚠️ 改动**数据库结构、部署脚本(`scripts/`、`Jenkinsfile`、`docker-compose.yml`)或敏感配置**前,先说明影响面再动手。
|
||||
|
||||
合并前最低自检(详见 [新人文档 §3.3](docs/新人环境搭建与配置文档.md)):前后端可启动、`frontend/` 改动后 `npm run build` 通过、关键页面与登录可用。
|
||||
|
||||
---
|
||||
|
||||
## 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/README.md](docs/README.md) |
|
||||
| 项目上下文 / 架构 / 数据模型 | [docs/project_context.md](docs/project_context.md) |
|
||||
| 需求文档 | [docs/demand.md](docs/demand.md) |
|
||||
| 技术架构文档 | [docs/tec.md](docs/tec.md) |
|
||||
| 功能清单 | [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) |
|
||||
| FAQ 缓存 / 热点发现运维 | [docs/faq_cache_ops_manual.md](docs/faq_cache_ops_manual.md) |
|
||||
| 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.md) |
|
||||
| 前端架构规范 | [docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md) |
|
||||
| 错误处理规范 | [docs/convention/error_handling.md](docs/convention/error_handling.md) |
|
||||
| **业务域文档索引** | [docs/features/README.md](docs/features/README.md) |
|
||||
| 货代发货通知 | [docs/features/shipping-notice/technical.md](docs/features/shipping-notice/technical.md) |
|
||||
| 文件检核 | [docs/features/file-check/technical.md](docs/features/file-check/technical.md) |
|
||||
| Agent 应用管理(设计) | [docs/platform/agent_application_management.md](platform/agent_application_management.md) |
|
||||
| Agent 应用管理(实现) | [docs/platform/agent_application_management_implementation.md](platform/agent_application_management_implementation.md) |
|
||||
@@ -0,0 +1,423 @@
|
||||
# 文档清洗系统对外接口文档
|
||||
|
||||
版本:`v1`
|
||||
|
||||
适用对象:需要根据 Dify 文档信息反查文档清洗系统中的本地原文件,并获取原文件下载地址的外部系统。
|
||||
|
||||
## 1. 接入目标
|
||||
|
||||
外部系统通常已经从 Dify 拿到了某条知识库文档的以下信息:
|
||||
|
||||
- `dataset_id`
|
||||
- `remote_document_id`
|
||||
|
||||
其中:
|
||||
|
||||
- `dataset_id` = Dify 知识库 id
|
||||
- `remote_document_id` = Dify 文档 id
|
||||
- `remote_document_id` 应从 Dify 文档接口返回的 `id` 获取,不是 batch id
|
||||
|
||||
外部系统可使用本文档提供的接口,反查这条 Dify 文档在文档清洗系统中的本地映射关系,并获取原文件下载地址。
|
||||
|
||||
## 2. 接入原则
|
||||
|
||||
- 外部系统应由服务端调用查询接口,不要在前端浏览器中保存 `INTEGRATION_API_KEY`。
|
||||
- 查询接口需要鉴权。
|
||||
- 文件下载地址为短期签名链接,前端可直接打开,不需要再附带鉴权 key。
|
||||
- 下载链接过期后,应重新调用查询接口获取新的下载链接。
|
||||
|
||||
## 3. 基础信息
|
||||
|
||||
- Base URL:`http://192.168.100.230:8891`
|
||||
- 鉴权方式:HTTP Header
|
||||
- Header 名称:`X-Integration-Key`
|
||||
|
||||
请求示例:
|
||||
|
||||
```http
|
||||
X-Integration-Key: <平台分配的对接密钥>
|
||||
```
|
||||
|
||||
说明:
|
||||
|
||||
- 该 key 由文档清洗系统平台方提供。
|
||||
- 外部系统请将该 key 保存在自身服务端配置中,不要下发到前端页面。
|
||||
|
||||
## 4. 推荐对接流程
|
||||
|
||||
### 4.1 外部系统后端流程
|
||||
|
||||
1. 从 Dify 获取目标文档的:
|
||||
- `dataset_id`
|
||||
- `remote_document_id`
|
||||
2. 调用文档清洗系统查询接口:
|
||||
- `GET /api/integration/dify-file`
|
||||
3. 解析返回结果,读取:
|
||||
- 文件名
|
||||
- 所属知识库
|
||||
- 所属部门
|
||||
- 原文件下载地址
|
||||
4. 将需要展示的字段返回给自身前端页面。
|
||||
5. 前端用户点击下载时,直接打开 `source_download_url`。
|
||||
|
||||
### 4.2 外部系统前端流程
|
||||
|
||||
1. 调用外部系统自己的后端接口。
|
||||
2. 展示外部系统后端返回的文件信息。
|
||||
3. 用户点击“下载原文件”时,直接访问 `source_download_url`。
|
||||
4. 如果下载失败且提示链接失效,由外部系统后端重新查询一次并返回新链接。
|
||||
|
||||
## 5. 核心接口:按 Dify 文档反查本地文件
|
||||
|
||||
- 方法:`GET`
|
||||
- 路径:`/api/integration/dify-file`
|
||||
|
||||
### 5.1 请求参数
|
||||
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `dataset_id` | `string` | 是 | Dify 知识库 id |
|
||||
| `remote_document_id` | `string` | 是 | Dify 文档 id,应取自 Dify 文档接口返回的 `id` |
|
||||
|
||||
### 5.2 请求头
|
||||
|
||||
```http
|
||||
X-Integration-Key: <平台分配的对接密钥>
|
||||
```
|
||||
|
||||
### 5.3 请求示例
|
||||
|
||||
```bash
|
||||
curl -H "X-Integration-Key: YOUR_KEY" \
|
||||
"http://192.168.100.230:8891/api/integration/dify-file?dataset_id=7a9f158c-90f5-478a-8956-2732c72a7546&remote_document_id=abcd1234"
|
||||
```
|
||||
|
||||
### 5.4 成功响应示例
|
||||
|
||||
```json
|
||||
{
|
||||
"queried_at": "2026-04-01T12:00:00+08:00",
|
||||
"document_id": 14,
|
||||
"knowledge_base": {
|
||||
"id": 3,
|
||||
"name": "03 质量",
|
||||
"department_id": 2,
|
||||
"department_name": "质量部",
|
||||
"dify_dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546"
|
||||
},
|
||||
"title": "假期控制程序1",
|
||||
"source_filename": "假期控制程序1.doc",
|
||||
"source_ext": ".doc",
|
||||
"file_name": "假期控制程序1.doc",
|
||||
"version_id": 22,
|
||||
"version_no": 1,
|
||||
"convert_status": "success",
|
||||
"sync_status": "synced",
|
||||
"uploaded_at": "2026-04-01T11:32:10+08:00",
|
||||
"converted_at": "2026-04-01T11:33:05+08:00",
|
||||
"download_url_expires_at": "2026-04-01T12:15:00+08:00",
|
||||
"source_download_url": "http://192.168.100.230:8891/api/integration/download?version_id=22&kind=source&token=xxxxx",
|
||||
"markdown_download_url": "http://192.168.100.230:8891/api/integration/download?version_id=22&kind=md&token=yyyyy",
|
||||
"markdown_download_url_expires_at": "2026-04-01T12:15:00+08:00",
|
||||
"markdown_public_url": "http://192.168.100.230:8891/storage/markdown/group_0003/document_000014/v001/document.md",
|
||||
"dify": {
|
||||
"dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546",
|
||||
"remote_document_id": "abcd1234",
|
||||
"status": "synced",
|
||||
"last_indexing_status": "completed",
|
||||
"last_synced_at": "2026-04-01T11:34:20+08:00"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 6. 核心接口:批量按 Dify 文档反查本地文件
|
||||
|
||||
- 方法:`POST`
|
||||
- 路径:`/api/integration/dify-files/resolve`
|
||||
|
||||
### 6.1 请求头
|
||||
|
||||
```http
|
||||
X-Integration-Key: <平台分配的对接密钥>
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
### 6.2 请求体
|
||||
|
||||
```json
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546",
|
||||
"remote_document_id": "abcd1234"
|
||||
},
|
||||
{
|
||||
"dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546",
|
||||
"remote_document_id": "efgh5678"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
说明:
|
||||
|
||||
- `items` 为待查询列表。
|
||||
- 建议每次批量查询控制在 `100` 条以内。
|
||||
- 返回结果会按请求里的输入顺序返回。
|
||||
- `remote_document_id` 应取自 Dify 文档接口返回的 `id`,不是 batch id。
|
||||
|
||||
### 6.3 请求示例
|
||||
|
||||
```bash
|
||||
curl -X POST \
|
||||
-H "X-Integration-Key: YOUR_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"items\":[{\"dataset_id\":\"7a9f158c-90f5-478a-8956-2732c72a7546\",\"remote_document_id\":\"abcd1234\"},{\"dataset_id\":\"7a9f158c-90f5-478a-8956-2732c72a7546\",\"remote_document_id\":\"efgh5678\"}]}" \
|
||||
"http://192.168.100.230:8891/api/integration/dify-files/resolve"
|
||||
```
|
||||
|
||||
### 6.4 成功响应示例
|
||||
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"request": {
|
||||
"dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546",
|
||||
"remote_document_id": "abcd1234"
|
||||
},
|
||||
"found": true,
|
||||
"document": {
|
||||
"document_id": 14,
|
||||
"source_filename": "假期控制程序1.doc",
|
||||
"source_download_url": "http://192.168.100.230:8891/api/integration/download?version_id=22&kind=source&token=xxxxx",
|
||||
"knowledge_base": {
|
||||
"id": 3,
|
||||
"name": "03 质量",
|
||||
"department_id": 2,
|
||||
"department_name": "质量部",
|
||||
"dify_dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546"
|
||||
},
|
||||
"dify": {
|
||||
"dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546",
|
||||
"remote_document_id": "abcd1234"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546",
|
||||
"remote_document_id": "efgh5678"
|
||||
},
|
||||
"found": false,
|
||||
"document": null
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 6.5 返回说明
|
||||
|
||||
- `request`
|
||||
- 原样回显本次输入的查询条件
|
||||
- `found`
|
||||
- 是否命中文档清洗系统中的本地映射
|
||||
- `document`
|
||||
- 命中时返回完整文档信息
|
||||
- 未命中时返回 `null`
|
||||
|
||||
## 6.6 版本映射说明
|
||||
|
||||
- 反查接口返回的是“命中的同步版本”,不是盲目返回当前最新版本。
|
||||
- 如果同一文档本地后来又上传了新版本,但新版本尚未同步到 Dify,接口仍会返回旧的已同步版本。
|
||||
- 如果某条文档从未同步到 Dify,则不会存在可用的 `remote_document_id` 映射。
|
||||
|
||||
## 7. 返回字段说明
|
||||
|
||||
### 7.1 顶层字段
|
||||
|
||||
| 字段名 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `queried_at` | `string` | 本次查询结果生成时间 |
|
||||
| `document_id` | `integer` | 文档清洗系统内部文档 id |
|
||||
| `title` | `string` | 文档清洗系统内部文档标题 |
|
||||
| `source_filename` | `string` | 原始上传文件名 |
|
||||
| `source_ext` | `string` | 原文件扩展名 |
|
||||
| `file_name` | `string` | 与 `source_filename` 相同,便于统一读取 |
|
||||
| `version_id` | `integer` | 当前版本 id |
|
||||
| `version_no` | `integer` | 当前版本号 |
|
||||
| `convert_status` | `string` | 转换状态,如 `queued` `running` `success` `failed` |
|
||||
| `sync_status` | `string` | 同步状态,如 `unsynced` `syncing` `synced` `sync_failed` |
|
||||
| `uploaded_at` | `string` | 原文件上传时间 |
|
||||
| `converted_at` | `string` | Markdown 转换完成时间 |
|
||||
| `download_url_expires_at` | `string` | 原文件下载链接过期时间 |
|
||||
| `source_download_url` | `string` | 原文件签名下载链接 |
|
||||
| `markdown_download_url` | `string` | Markdown 签名下载链接 |
|
||||
| `markdown_download_url_expires_at` | `string` | Markdown 下载链接过期时间 |
|
||||
| `markdown_public_url` | `string` | Markdown 在本系统内的访问地址 |
|
||||
| `knowledge_base` | `object` | 所属知识库信息 |
|
||||
| `dify` | `object` | Dify 映射信息 |
|
||||
|
||||
### 7.2 `knowledge_base` 字段说明
|
||||
|
||||
| 字段名 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `id` | `integer` | 文档清洗系统内部知识库 id |
|
||||
| `name` | `string` | 知识库名称 |
|
||||
| `department_id` | `integer` \| `null` | 所属部门 id |
|
||||
| `department_name` | `string` \| `null` | 所属部门名称 |
|
||||
| `dify_dataset_id` | `string` \| `null` | 该知识库在 Dify 对应的 dataset id |
|
||||
|
||||
### 7.3 `dify` 字段说明
|
||||
|
||||
| 字段名 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `dataset_id` | `string` | Dify 知识库 id |
|
||||
| `remote_document_id` | `string` | Dify 文档 id |
|
||||
| `status` | `string` | 本地记录的最近同步状态 |
|
||||
| `last_indexing_status` | `string` | Dify 最近索引状态 |
|
||||
| `last_synced_at` | `string` \| `null` | 最近同步完成时间 |
|
||||
|
||||
## 8. 下载说明
|
||||
|
||||
### 8.1 下载接口
|
||||
|
||||
外部系统通常不需要自己拼下载接口,直接使用查询结果中的:
|
||||
|
||||
- `source_download_url`
|
||||
- `markdown_download_url`
|
||||
|
||||
即可。
|
||||
|
||||
### 8.2 下载接口格式
|
||||
|
||||
- 方法:`GET`
|
||||
- 路径:`/api/integration/download`
|
||||
|
||||
请求参数:
|
||||
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `version_id` | `integer` | 是 | 文档清洗系统内部版本 id |
|
||||
| `kind` | `string` | 是 | `source` 或 `md` |
|
||||
| `token` | `string` | 是 | 签名令牌 |
|
||||
|
||||
示例:
|
||||
|
||||
```text
|
||||
http://192.168.100.230:8891/api/integration/download?version_id=22&kind=source&token=xxxxx
|
||||
```
|
||||
|
||||
### 8.3 下载接口说明
|
||||
|
||||
- 下载接口不需要再附带 `X-Integration-Key`。
|
||||
- 这是一个短期签名链接,可直接在浏览器打开。
|
||||
- 链接过期后,请重新调用查询接口获取新的下载链接。
|
||||
|
||||
## 9. 可选查询接口
|
||||
|
||||
如果外部系统不是从 Dify 文档开始反查,也可使用以下接口。
|
||||
|
||||
### 9.1 获取知识库列表
|
||||
|
||||
- 方法:`GET`
|
||||
- 路径:`/api/integration/knowledge-bases`
|
||||
|
||||
查询参数:
|
||||
|
||||
| 参数名 | 必填 | 说明 |
|
||||
|---|---|---|
|
||||
| `department_id` | 否 | 按部门筛选 |
|
||||
| `q` | 否 | 按知识库名称模糊搜索 |
|
||||
|
||||
请求示例:
|
||||
|
||||
```bash
|
||||
curl -H "X-Integration-Key: YOUR_KEY" \
|
||||
"http://192.168.100.230:8891/api/integration/knowledge-bases"
|
||||
```
|
||||
|
||||
### 9.2 获取文件列表
|
||||
|
||||
- 方法:`GET`
|
||||
- 路径:`/api/integration/files`
|
||||
|
||||
查询参数:
|
||||
|
||||
| 参数名 | 必填 | 说明 |
|
||||
|---|---|---|
|
||||
| `knowledge_base_id` | 否 | 按知识库筛选 |
|
||||
| `department_id` | 否 | 按部门筛选 |
|
||||
| `file_name` | 否 | 按文件名或标题模糊搜索 |
|
||||
|
||||
请求示例:
|
||||
|
||||
```bash
|
||||
curl -H "X-Integration-Key: YOUR_KEY" \
|
||||
"http://192.168.100.230:8891/api/integration/files?knowledge_base_id=3"
|
||||
```
|
||||
|
||||
### 9.3 获取单个文件详情
|
||||
|
||||
- 方法:`GET`
|
||||
- 路径:`/api/integration/files/{file_id}`
|
||||
|
||||
请求示例:
|
||||
|
||||
```bash
|
||||
curl -H "X-Integration-Key: YOUR_KEY" \
|
||||
"http://192.168.100.230:8891/api/integration/files/14"
|
||||
```
|
||||
|
||||
## 10. 状态码说明
|
||||
|
||||
### 10.1 查询接口
|
||||
|
||||
| 状态码 | 说明 |
|
||||
|---|---|
|
||||
| `200` | 查询成功 |
|
||||
| `401` | 鉴权失败,`X-Integration-Key` 无效 |
|
||||
| `404` | 未找到对应的本地文件映射 |
|
||||
| `503` | 接口未配置完成,通常为平台未配置 `INTEGRATION_API_KEY` |
|
||||
|
||||
### 10.2 下载接口
|
||||
|
||||
| 状态码 | 说明 |
|
||||
|---|---|
|
||||
| `200` | 下载成功 |
|
||||
| `401` | 签名无效或已过期 |
|
||||
| `404` | 文件不存在 |
|
||||
| `409` | 请求 `md`,但 Markdown 尚未生成 |
|
||||
|
||||
## 11. 对接建议
|
||||
|
||||
- 外部系统前端不要直接调用查询接口。
|
||||
- 外部系统后端负责:
|
||||
- 保存 integration key
|
||||
- 调用查询接口
|
||||
- 将结果整理后返回给自身前端
|
||||
- 外部系统前端负责:
|
||||
- 展示文件信息
|
||||
- 使用 `source_download_url` 直接下载原文件
|
||||
|
||||
## 12. 最小接入流程
|
||||
|
||||
1. 外部系统从 Dify 获取:
|
||||
- `dataset_id`
|
||||
- `remote_document_id`
|
||||
2. 外部系统后端调用:
|
||||
- `GET /api/integration/dify-file?dataset_id=...&remote_document_id=...`
|
||||
3. 从返回结果中读取:
|
||||
- `source_filename`
|
||||
- `source_download_url`
|
||||
- `knowledge_base.name`
|
||||
- `knowledge_base.department_name`
|
||||
4. 将上述字段展示给用户。
|
||||
5. 用户点击下载时,直接打开 `source_download_url`。
|
||||
|
||||
## 13. 对接注意事项
|
||||
|
||||
- `source_download_url` 为短期签名链接,不是永久地址。
|
||||
- `source_download_url` 可直接用于下载,无需再次附加鉴权 key。
|
||||
- 若链接过期,外部系统应重新调用查询接口获取新链接。
|
||||
- 若返回 `404`,表示该 Dify 文档在文档清洗系统中没有本地文件映射。
|
||||
Vendored
-583
@@ -1,583 +0,0 @@
|
||||
import groovy.json.JsonOutput
|
||||
|
||||
// 企业微信群机器人部署通知(成功/失败/中止)。Webhook 完整 URL 存 Jenkins 凭据 WECOM_WEBHOOK_DEPLOY,勿写入 Git。
|
||||
// WeCom group-bot deploy notifications. Store webhook URL in Jenkins Secret text credential only.
|
||||
def notifyWecomDeploy(Map opts) {
|
||||
if ((env.DISABLE_DEPLOY_WECOM_NOTIFY ?: '').equalsIgnoreCase('true')) {
|
||||
echo '[WeCom] DISABLE_DEPLOY_WECOM_NOTIFY=true,跳过通知'
|
||||
return
|
||||
}
|
||||
|
||||
def credId = (opts.webhookCredId ?: env.WECOM_WEBHOOK_CRED ?: 'WECOM_WEBHOOK_DEPLOY').trim()
|
||||
def content = buildDeployNotifyMarkdown(opts)
|
||||
|
||||
try {
|
||||
withCredentials([string(credentialsId: credId, variable: 'WECOM_WEBHOOK_URL')]) {
|
||||
def webhookUrl = WECOM_WEBHOOK_URL?.trim()
|
||||
if (!webhookUrl) {
|
||||
echo "[WeCom] 凭据 ${credId} 为空,跳过通知"
|
||||
return
|
||||
}
|
||||
|
||||
def payload = [
|
||||
msgtype: 'markdown',
|
||||
markdown: [content: content.markdown],
|
||||
]
|
||||
writeFile(file: 'wecom-notify-payload.json', encoding: 'UTF-8', text: JsonOutput.toJson(payload))
|
||||
|
||||
def httpCode = sh(
|
||||
returnStdout: true,
|
||||
script: '''
|
||||
set +e
|
||||
code=$(curl -sS -o wecom-notify-response.txt -w "%{http_code}" \
|
||||
-X POST "$WECOM_WEBHOOK_URL" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d @wecom-notify-payload.json)
|
||||
echo "[WeCom] HTTP ${code}" >&2
|
||||
cat wecom-notify-response.txt >&2 || true
|
||||
echo "${code}"
|
||||
'''
|
||||
).trim()
|
||||
|
||||
def resp = readFile('wecom-notify-response.txt').trim()
|
||||
if (httpCode == '200' && resp.contains('"errcode":0')) {
|
||||
echo '[WeCom] 通知已发送'
|
||||
} else {
|
||||
echo "[WeCom] 发送可能失败,HTTP=${httpCode},响应=${resp}"
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
echo "[WeCom] 通知发送异常(不影响构建结果): ${e.message}"
|
||||
}
|
||||
}
|
||||
|
||||
// PushPlus → 个人微信(方案3)。Token 存 Jenkins 凭据 PUSHPLUS_DEPLOY_TOKEN,见 https://www.pushplus.plus/
|
||||
def buildDeployNotifyMarkdown(Map opts) {
|
||||
def envLabel = opts.envLabel ?: '部署环境'
|
||||
def host = opts.host ?: '-'
|
||||
def status = (opts.status ?: 'success').toString().toLowerCase()
|
||||
def isSuccess = status == 'success'
|
||||
def extraNote = (opts.extraNote ?: '').trim()
|
||||
def shortCommit = env.GIT_COMMIT ? env.GIT_COMMIT.take(8) : '-'
|
||||
def buildLink = env.BUILD_URL ?: '-'
|
||||
def title = isSuccess ? "✅ ${envLabel} 部署成功" : "❌ ${envLabel} 部署失败"
|
||||
def lines = [
|
||||
"## ${title}",
|
||||
"> **分支**: ${env.BRANCH_NAME ?: '-'}",
|
||||
"> **提交**: `${shortCommit}`",
|
||||
"> **目标主机**: ${host}",
|
||||
"> **构建**: [#${env.BUILD_NUMBER}](${buildLink})",
|
||||
"> **变更**: 前端=${env.FRONTEND_CHANGED ?: '-'} 后端=${env.BACKEND_CHANGED ?: '-'} 配置=${env.DEPLOY_CONFIG_CHANGED ?: '-'}",
|
||||
]
|
||||
if (env.FORCE_FULL_DEPLOY_USED == 'true') {
|
||||
lines << '> **备注**: 强制全量部署'
|
||||
}
|
||||
if (env.REMOTE_DRIFT_DETECTED == 'true') {
|
||||
lines << '> **备注**: 远端版本漂移触发部署'
|
||||
}
|
||||
if (env.ROLLBACK_IMAGE_TAG?.trim()) {
|
||||
lines << "> **备注**: 镜像回滚 → `${env.ROLLBACK_IMAGE_TAG.trim()}`(预构建模式,跳过 db upgrade)"
|
||||
}
|
||||
if (extraNote) {
|
||||
lines << "> **说明**: ${extraNote}"
|
||||
}
|
||||
if (!isSuccess) {
|
||||
lines << '> **处理**: 请打开 Jenkins 构建日志排查失败步骤'
|
||||
}
|
||||
return [title: title, markdown: lines.join('\n')]
|
||||
}
|
||||
|
||||
def notifyPushPlusDeploy(Map opts) {
|
||||
if ((env.DISABLE_DEPLOY_PUSHPLUS_NOTIFY ?: '').equalsIgnoreCase('true')) {
|
||||
echo '[PushPlus] DISABLE_DEPLOY_PUSHPLUS_NOTIFY=true,跳过通知'
|
||||
return
|
||||
}
|
||||
|
||||
def credId = (opts.tokenCredId ?: env.PUSHPLUS_TOKEN_CRED ?: 'PUSHPLUS_DEPLOY_TOKEN').trim()
|
||||
def content = buildDeployNotifyMarkdown(opts)
|
||||
|
||||
try {
|
||||
withCredentials([string(credentialsId: credId, variable: 'PUSHPLUS_TOKEN')]) {
|
||||
def token = PUSHPLUS_TOKEN?.trim()
|
||||
if (!token) {
|
||||
echo "[PushPlus] 凭据 ${credId} 为空,跳过通知"
|
||||
return
|
||||
}
|
||||
|
||||
def payload = [
|
||||
token: token,
|
||||
title: "[HxOps] ${content.title}",
|
||||
content: content.markdown,
|
||||
template: 'markdown',
|
||||
channel: 'wechat',
|
||||
]
|
||||
def topic = (env.PUSHPLUS_TOPIC ?: '').trim()
|
||||
if (topic) {
|
||||
payload.topic = topic
|
||||
}
|
||||
|
||||
writeFile(file: 'pushplus-notify-payload.json', encoding: 'UTF-8', text: JsonOutput.toJson(payload))
|
||||
|
||||
def httpCode = sh(
|
||||
returnStdout: true,
|
||||
script: '''
|
||||
set +e
|
||||
code=$(curl -sS -o pushplus-notify-response.txt -w "%{http_code}" \
|
||||
-X POST "https://www.pushplus.plus/send" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d @pushplus-notify-payload.json)
|
||||
echo "[PushPlus] HTTP ${code}" >&2
|
||||
cat pushplus-notify-response.txt >&2 || true
|
||||
echo "${code}"
|
||||
'''
|
||||
).trim()
|
||||
|
||||
def resp = readFile('pushplus-notify-response.txt').trim()
|
||||
if (httpCode == '200' && (resp.contains('"code":200') || resp.contains('"code": 200'))) {
|
||||
echo '[PushPlus] 微信通知已发送'
|
||||
} else {
|
||||
echo "[PushPlus] 发送可能失败,HTTP=${httpCode},响应=${resp}"
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
echo "[PushPlus] 通知发送异常(不影响构建结果): ${e.message}"
|
||||
}
|
||||
}
|
||||
|
||||
// 企业微信 + PushPlus 微信双通道
|
||||
def notifyDeployAll(Map opts) {
|
||||
notifyWecomDeploy(opts)
|
||||
// 暂时只发企业微信通知
|
||||
// notifyPushPlusDeploy(opts)
|
||||
}
|
||||
|
||||
pipeline {
|
||||
agent any
|
||||
|
||||
// 构建参数:首次在 Jenkinsfile 中加入后需至少跑一次构建,后续才能在「Build with Parameters」中看到 / Build params appear after first run
|
||||
parameters {
|
||||
// 跳过变更检测,强制进入部署阶段(等同前后端与部署配置均有变更)
|
||||
booleanParam(
|
||||
name: 'FORCE_FULL_DEPLOY',
|
||||
defaultValue: false,
|
||||
description: '勾选则跳过 Git diff(以及下方的远端校验);仍会执行生产人工确认(除非 Job 环境变量 SKIP_PROD_DEPLOY_INPUT=true)。'
|
||||
)
|
||||
// 本地判定「无变更」时,SSH 读远端部署目录的提交与分支,不一致则触发部署
|
||||
booleanParam(
|
||||
name: 'VERIFY_REMOTE_WHEN_NO_DIFF',
|
||||
defaultValue: false,
|
||||
description: '仅当本地 diff 判定无前后端/部署配置变更时生效:额外 SSH 到本分支对应目标机执行 git rev-parse / branch --show-current,与本次 GIT_COMMIT、BRANCH_NAME 比对,不一致则视为需要部署。'
|
||||
)
|
||||
// 生产镜像回滚:填写 Git 7 位短 hash 后缀(如 prod-e5b65d9),走 deploy_compose.sh 预构建模式
|
||||
string(
|
||||
name: 'ROLLBACK_IMAGE_TAG',
|
||||
defaultValue: '',
|
||||
description: '【仅生产】非空时回滚到该镜像 tag(hxops-frontend:<tag> / hxops-backend:<tag>)。示例:prod-e5b65d9(Git 短 hash 7 位)。不拉最新代码、不执行 db upgrade。留空为正常部署。'
|
||||
)
|
||||
}
|
||||
|
||||
options {
|
||||
// 打印时间戳,便于在 Jenkins 日志里定位耗时步骤 / Add timestamps to locate slow steps in Jenkins logs
|
||||
timestamps()
|
||||
// 禁止同一任务并发执行,避免部署相互覆盖 / Prevent concurrent runs to avoid deployment conflicts
|
||||
disableConcurrentBuilds()
|
||||
}
|
||||
|
||||
environment {
|
||||
// 环境服务器地址 / Environment hosts
|
||||
DEV_DEPLOY_HOST = '8.152.207.171'
|
||||
TEST_DEPLOY_HOST = '192.168.100.192'
|
||||
PROD_DEPLOY_HOST = '192.168.100.230'
|
||||
|
||||
// SSH 连接参数 / SSH connection settings
|
||||
DEV_SSH_USER = 'root'
|
||||
TEST_SSH_USER = 'lisq'
|
||||
PROD_SSH_USER = 'inspur'
|
||||
SSH_PORT = '22'
|
||||
|
||||
// 各环境统一部署目录 / Unified deploy root
|
||||
DEV_DEPLOY_ROOT = '/opt/hxops'
|
||||
TEST_DEPLOY_ROOT = '/home/lisq/ai/platform/hxops'
|
||||
PROD_DEPLOY_ROOT = '/data/ai-platform/hxops/'
|
||||
|
||||
// PushPlus 群组编码(一对多推送到个人微信);Token 仍用 Jenkins 凭据 PUSHPLUS_DEPLOY_TOKEN
|
||||
PUSHPLUS_TOPIC = 'hxops666'
|
||||
|
||||
// 生产机保留的可回滚镜像 tag 数量(deploy_compose.sh 按 ${ENV_NAME}-<commit> 清理旧 tag)
|
||||
IMAGE_TAG_RETAIN_COUNT = '10'
|
||||
}
|
||||
|
||||
stages {
|
||||
stage('Checkout') {
|
||||
steps {
|
||||
// 多分支流水线检出当前分支代码 / Checkout source from current branch in Multibranch Pipeline
|
||||
checkout scm
|
||||
echo "[Checkout] BRANCH_NAME=${env.BRANCH_NAME}, GIT_BRANCH=${env.GIT_BRANCH}, COMMIT=${env.GIT_COMMIT}"
|
||||
}
|
||||
}
|
||||
|
||||
stage('Detect Changes') {
|
||||
steps {
|
||||
script {
|
||||
env.FORCE_FULL_DEPLOY_USED = 'false'
|
||||
env.REMOTE_DRIFT_DETECTED = 'false'
|
||||
env.REMOTE_VERIFY_SKIPPED = 'false'
|
||||
env.ROLLBACK_IMAGE_TAG = ''
|
||||
|
||||
def rollbackTag = params.ROLLBACK_IMAGE_TAG?.trim()
|
||||
if (rollbackTag) {
|
||||
env.ROLLBACK_IMAGE_TAG = rollbackTag
|
||||
env.FRONTEND_CHANGED = 'true'
|
||||
env.BACKEND_CHANGED = 'true'
|
||||
env.DEPLOY_CONFIG_CHANGED = 'false'
|
||||
echo "[Detect Changes] ROLLBACK_IMAGE_TAG=${rollbackTag},将使用预构建模式回滚(跳过 Git 更新与 db upgrade)"
|
||||
return
|
||||
}
|
||||
|
||||
// BRANCH_NAME 必须由 Multibranch Pipeline 提供 / BRANCH_NAME must be provided by Multibranch Pipeline
|
||||
def branchName = env.BRANCH_NAME?.trim()
|
||||
if (!branchName) {
|
||||
error('BRANCH_NAME is empty. Please run this as a Multibranch Pipeline job.')
|
||||
}
|
||||
|
||||
// 与 Deploy Prod 阶段一致:用于判断当前分支是否有对应部署目标(远端校验仅在这些分支上有意义)
|
||||
def extraBranches = (env.EXTRA_PROD_BRANCHES ?: '').split(',').collect { it.trim() }.findAll { it }
|
||||
def prodLikeBranches = (['prod', 'sophie', 'sophie-wecom'] + extraBranches).unique()
|
||||
|
||||
def getDeploySshTarget = { String b ->
|
||||
if (b == 'dev') {
|
||||
return [host: env.DEV_DEPLOY_HOST, user: env.DEV_SSH_USER, root: env.DEV_DEPLOY_ROOT, cred: 'SSH_DEV_DEPLOY']
|
||||
}
|
||||
if (b == 'test') {
|
||||
return [host: env.TEST_DEPLOY_HOST, user: env.TEST_SSH_USER, root: env.TEST_DEPLOY_ROOT, cred: 'SSH_TEST_DEPLOY']
|
||||
}
|
||||
if (prodLikeBranches.contains(b)) {
|
||||
return [host: env.PROD_DEPLOY_HOST, user: env.PROD_SSH_USER, root: env.PROD_DEPLOY_ROOT, cred: 'SSH_PROD_DEPLOY']
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// 强制全量:跳过 Git diff 与远端校验,避免「换分支同 SHA」或纯重发时被跳过
|
||||
if (params.FORCE_FULL_DEPLOY == true) {
|
||||
env.FRONTEND_CHANGED = 'true'
|
||||
env.BACKEND_CHANGED = 'true'
|
||||
env.DEPLOY_CONFIG_CHANGED = 'true'
|
||||
env.FORCE_FULL_DEPLOY_USED = 'true'
|
||||
echo "[Detect Changes] FORCE_FULL_DEPLOY=true,已跳过 Git diff 与远端校验"
|
||||
echo "[Detect Changes] FRONTEND_CHANGED=${env.FRONTEND_CHANGED}, BACKEND_CHANGED=${env.BACKEND_CHANGED}, DEPLOY_CONFIG_CHANGED=${env.DEPLOY_CONFIG_CHANGED}"
|
||||
return
|
||||
}
|
||||
|
||||
// 以上次成功构建为差异基线 / Use previous successful commit as diff base
|
||||
def baseCommit = env.GIT_PREVIOUS_SUCCESSFUL_COMMIT?.trim()
|
||||
if (!baseCommit) {
|
||||
baseCommit = sh(returnStdout: true, script: 'git rev-parse HEAD^ 2>/dev/null || true').trim()
|
||||
}
|
||||
|
||||
List<String> changedFiles = []
|
||||
if (baseCommit) {
|
||||
changedFiles = sh(
|
||||
returnStdout: true,
|
||||
script: "git diff --name-only ${baseCommit} ${env.GIT_COMMIT}"
|
||||
).trim().split('\\n').findAll { it?.trim() }
|
||||
} else {
|
||||
// 首次构建默认按前后端都变更处理 / First build defaults to full-scope deployment
|
||||
changedFiles = ['frontend/', 'backend/']
|
||||
}
|
||||
|
||||
// 目录级变更识别:用于前后端增量构建 / Directory-level change detection for incremental builds
|
||||
def frontendChanged = changedFiles.any { it.startsWith('frontend/') }
|
||||
def backendChanged = changedFiles.any {
|
||||
it.startsWith('backend/') || it == 'docs/(表+字段).md'
|
||||
}
|
||||
def deployConfigChanged = changedFiles.any {
|
||||
it == 'docker-compose.yml' ||
|
||||
it == 'Jenkinsfile' ||
|
||||
it == '.dockerignore' ||
|
||||
it == 'scripts/deploy_compose.sh' ||
|
||||
it == 'scripts/healthcheck.sh' ||
|
||||
it == '.env.dev' ||
|
||||
it == '.env.test' ||
|
||||
it == '.env.prod'
|
||||
}
|
||||
|
||||
// 本地判定无变更且开启远端校验:SSH 读部署目录提交与分支,与本次构建对齐(需目标机允许只读 git 命令)
|
||||
def noLocalDiff = !frontendChanged && !backendChanged && !deployConfigChanged
|
||||
if (noLocalDiff && params.VERIFY_REMOTE_WHEN_NO_DIFF == true) {
|
||||
def target = getDeploySshTarget(branchName)
|
||||
if (!target) {
|
||||
env.REMOTE_VERIFY_SKIPPED = 'true'
|
||||
echo "[Detect Changes] VERIFY_REMOTE_WHEN_NO_DIFF=true,但当前分支无对应部署目标,跳过远端校验"
|
||||
} else {
|
||||
def expectedCommit = env.GIT_COMMIT?.trim()
|
||||
def remoteOut = ''
|
||||
sshagent(credentials: [target.cred]) {
|
||||
// 仅查询:不 fetch,不改变远端工作区;cd 失败或仓库异常会导致 SSH 步骤失败
|
||||
remoteOut = sh(
|
||||
returnStdout: true,
|
||||
script: """ssh -p ${env.SSH_PORT} -o StrictHostKeyChecking=no ${target.user}@${target.host} 'set -e; cd "${target.root}"; git rev-parse HEAD; git branch --show-current 2>/dev/null || true'"""
|
||||
).trim()
|
||||
}
|
||||
def remoteLines = remoteOut.split('\n') as List
|
||||
def remoteCommit = remoteLines ? remoteLines[0].trim() : ''
|
||||
def remoteBranch = remoteLines.size() > 1 ? remoteLines[1..-1].join('\n').trim() : ''
|
||||
|
||||
def commitMismatch = remoteCommit && expectedCommit && remoteCommit != expectedCommit
|
||||
def branchMismatch = remoteBranch && remoteBranch != branchName
|
||||
|
||||
echo "[Detect Changes] 远端校验 host=${target.host} root=${target.root}"
|
||||
echo "[Detect Changes] 远端 HEAD=${remoteCommit}, 期望=${expectedCommit}"
|
||||
echo "[Detect Changes] 远端分支=${remoteBranch ?: '(空或 detached)'}, 期望=${branchName}"
|
||||
|
||||
if (commitMismatch || branchMismatch) {
|
||||
frontendChanged = true
|
||||
backendChanged = true
|
||||
deployConfigChanged = true
|
||||
env.REMOTE_DRIFT_DETECTED = 'true'
|
||||
echo '[Detect Changes] 远端与本次构建不一致,已强制视为需要部署(前后端+部署配置标志均为 true)'
|
||||
} else {
|
||||
echo '[Detect Changes] 远端与本次构建一致(或无法解析分支名),仍按本地无变更处理'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
env.FRONTEND_CHANGED = frontendChanged ? 'true' : 'false'
|
||||
env.BACKEND_CHANGED = backendChanged ? 'true' : 'false'
|
||||
env.DEPLOY_CONFIG_CHANGED = deployConfigChanged ? 'true' : 'false'
|
||||
|
||||
echo "[Detect Changes] branch=${branchName}"
|
||||
echo "[Detect Changes] baseCommit=${baseCommit ?: 'none'}"
|
||||
echo "[Detect Changes] files=${changedFiles.join(', ')}"
|
||||
echo "[Detect Changes] FRONTEND_CHANGED=${env.FRONTEND_CHANGED}, BACKEND_CHANGED=${env.BACKEND_CHANGED}, DEPLOY_CONFIG_CHANGED=${env.DEPLOY_CONFIG_CHANGED}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// stage('Frontend Build (CI)') {
|
||||
// when {
|
||||
// expression { env.FRONTEND_CHANGED == 'true' }
|
||||
// }
|
||||
// steps {
|
||||
// echo '[Frontend Build] FRONTEND_CHANGED=true,容器内执行 npm ci && npm run build(与部署构建一致)'
|
||||
// sh '''
|
||||
// set -e
|
||||
// docker run --rm \
|
||||
// -v "${WORKSPACE}:/repo" \
|
||||
// -w /repo \
|
||||
// node:22-alpine sh -c "chmod +x scripts/ci_frontend_build.sh && ./scripts/ci_frontend_build.sh"
|
||||
// '''
|
||||
// }
|
||||
// }
|
||||
|
||||
stage('Deploy Dev') {
|
||||
when {
|
||||
expression {
|
||||
// dev 分支都部署到 dev 环境 / dev branches deploy to dev environment
|
||||
(env.BRANCH_NAME == 'dev') &&
|
||||
// 无变更不部署 / Skip deploy when no effective changes
|
||||
(env.FRONTEND_CHANGED == 'true' || env.BACKEND_CHANGED == 'true' || env.DEPLOY_CONFIG_CHANGED == 'true')
|
||||
}
|
||||
}
|
||||
steps {
|
||||
echo "[Deploy Dev] start branch=${env.BRANCH_NAME} host=${env.DEV_DEPLOY_HOST}"
|
||||
|
||||
// 使用Jenkins中的SSH_DEV_DEPLOY私钥部署到开发服务器
|
||||
// Use SSH_DEV_DEPLOY credential to deploy to dev server
|
||||
sshagent(credentials: ['SSH_DEV_DEPLOY']) {
|
||||
sh """
|
||||
set -e
|
||||
# 远端更新代码并执行部署脚本 / Update repo on target host and run deploy script
|
||||
ssh -p ${SSH_PORT} -o StrictHostKeyChecking=no ${DEV_SSH_USER}@${DEV_DEPLOY_HOST} '
|
||||
set -e
|
||||
cd ${DEV_DEPLOY_ROOT}
|
||||
git fetch origin
|
||||
# 清掉工作区里对已跟踪文件的本地修改,否则改 deploy 脚本后 checkout 会报 “would be overwritten”
|
||||
git reset --hard HEAD
|
||||
git checkout -B ${BRANCH_NAME} origin/${BRANCH_NAME}
|
||||
git reset --hard "origin/${BRANCH_NAME}"
|
||||
chmod +x scripts/deploy_compose.sh scripts/healthcheck.sh
|
||||
./scripts/deploy_compose.sh dev "" "" ${FRONTEND_CHANGED} ${BACKEND_CHANGED} ${DEPLOY_CONFIG_CHANGED}
|
||||
'
|
||||
"""
|
||||
}
|
||||
echo "[Deploy Dev] done"
|
||||
}
|
||||
}
|
||||
|
||||
stage('Deploy Test') {
|
||||
when {
|
||||
expression {
|
||||
// test / env 分支均部署到 test 环境主机;代码与当前构建分支一致(不再强制 origin/test)
|
||||
(env.BRANCH_NAME == 'test' || env.BRANCH_NAME == 'env') &&
|
||||
(env.FRONTEND_CHANGED == 'true' || env.BACKEND_CHANGED == 'true' || env.DEPLOY_CONFIG_CHANGED == 'true')
|
||||
}
|
||||
}
|
||||
steps {
|
||||
echo "[Deploy Test] start branch=${env.BRANCH_NAME} host=${env.TEST_DEPLOY_HOST}"
|
||||
|
||||
// 使用Jenkins中的SSH_TEST_DEPLOY私钥部署到测试服务器
|
||||
// Use SSH_TEST_DEPLOY credential to deploy to test server
|
||||
sshagent(credentials: ['SSH_TEST_DEPLOY']) {
|
||||
sh """
|
||||
set -e
|
||||
ssh -p ${SSH_PORT} -o StrictHostKeyChecking=no ${TEST_SSH_USER}@${TEST_DEPLOY_HOST} '
|
||||
set -e
|
||||
cd ${TEST_DEPLOY_ROOT}
|
||||
git fetch origin
|
||||
git reset --hard HEAD
|
||||
git checkout -B ${BRANCH_NAME} origin/${BRANCH_NAME}
|
||||
git reset --hard "origin/${BRANCH_NAME}"
|
||||
chmod +x scripts/deploy_compose.sh scripts/healthcheck.sh
|
||||
./scripts/deploy_compose.sh test "" "" ${FRONTEND_CHANGED} ${BACKEND_CHANGED} ${DEPLOY_CONFIG_CHANGED}
|
||||
'
|
||||
"""
|
||||
}
|
||||
echo "[Deploy Test] done"
|
||||
}
|
||||
post {
|
||||
success {
|
||||
script {
|
||||
notifyDeployAll(
|
||||
envLabel: '测试环境',
|
||||
host: env.TEST_DEPLOY_HOST,
|
||||
status: 'success',
|
||||
)
|
||||
}
|
||||
}
|
||||
failure {
|
||||
script {
|
||||
notifyDeployAll(
|
||||
envLabel: '测试环境',
|
||||
host: env.TEST_DEPLOY_HOST,
|
||||
status: 'failure',
|
||||
)
|
||||
}
|
||||
}
|
||||
aborted {
|
||||
script {
|
||||
notifyDeployAll(
|
||||
envLabel: '测试环境',
|
||||
host: env.TEST_DEPLOY_HOST,
|
||||
status: 'failure',
|
||||
extraNote: '阶段已中止(可能为人工取消)',
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Deploy Prod') {
|
||||
// 默认允许分支:prod、sophie。其它分支在 Job 环境变量设 EXTRA_PROD_BRANCHES=分支a,分支b
|
||||
// 临时免确认试跑:SKIP_PROD_DEPLOY_INPUT=true
|
||||
when {
|
||||
expression {
|
||||
def extra = (env.EXTRA_PROD_BRANCHES ?: '').split(',').collect { it.trim() }.findAll { it }
|
||||
def allowed = (['prod', 'sophie', 'sophie-wecom'] + extra).unique()
|
||||
allowed.contains(env.BRANCH_NAME) &&
|
||||
(env.FRONTEND_CHANGED == 'true' || env.BACKEND_CHANGED == 'true' || env.DEPLOY_CONFIG_CHANGED == 'true')
|
||||
}
|
||||
}
|
||||
steps {
|
||||
script {
|
||||
def rollbackTag = env.ROLLBACK_IMAGE_TAG?.trim()
|
||||
// 临时免确认(仅无人使用的生产试跑):在 Job 环境变量设 SKIP_PROD_DEPLOY_INPUT=true;正式流程勿开启
|
||||
def skipInput = (env.SKIP_PROD_DEPLOY_INPUT ?: '').equalsIgnoreCase('true')
|
||||
if (!skipInput) {
|
||||
// 人工确认超时(分钟):超时未点「Proceed」构建将失败,避免任务永久挂在 input 上;可通过 Job 环境变量覆盖
|
||||
def inputTimeoutMin = 30
|
||||
try {
|
||||
def rawTm = (env.PROD_DEPLOY_INPUT_TIMEOUT_MINUTES ?: '30').trim()
|
||||
inputTimeoutMin = Integer.parseInt(rawTm)
|
||||
if (inputTimeoutMin <= 0) {
|
||||
inputTimeoutMin = 30
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
inputTimeoutMin = 30
|
||||
}
|
||||
echo "[Deploy Prod] 生产部署人工确认超时=${inputTimeoutMin} 分钟(环境变量 PROD_DEPLOY_INPUT_TIMEOUT_MINUTES 可覆盖)"
|
||||
def confirmMessage = rollbackTag ?
|
||||
"确认将生产回滚到镜像 tag ${rollbackTag} ?(预构建模式,不拉最新代码,不执行 db upgrade)" :
|
||||
"确认将分支 ${env.BRANCH_NAME} 部署到生产主机 ${env.PROD_DEPLOY_HOST} ?"
|
||||
timeout(time: inputTimeoutMin, unit: 'MINUTES') {
|
||||
input message: confirmMessage
|
||||
}
|
||||
} else {
|
||||
echo "[Deploy Prod] SKIP_PROD_DEPLOY_INPUT=true,已跳过人工确认"
|
||||
}
|
||||
|
||||
echo "[Deploy Prod] start branch=${env.BRANCH_NAME} host=${env.PROD_DEPLOY_HOST} rollbackTag=${rollbackTag ?: '(none)'}"
|
||||
|
||||
// 使用Jenkins中的SSH_PROD_DEPLOY私钥部署到生产服务器
|
||||
// Use SSH_PROD_DEPLOY credential to deploy to prod server
|
||||
sshagent(credentials: ['SSH_PROD_DEPLOY']) {
|
||||
if (rollbackTag) {
|
||||
sh """
|
||||
set -e
|
||||
ssh -p ${SSH_PORT} -o StrictHostKeyChecking=no ${PROD_SSH_USER}@${PROD_DEPLOY_HOST} '
|
||||
set -e
|
||||
cd ${PROD_DEPLOY_ROOT}
|
||||
chmod +x scripts/deploy_compose.sh scripts/healthcheck.sh
|
||||
./scripts/deploy_compose.sh prod "hxops-frontend:${rollbackTag}" "hxops-backend:${rollbackTag}" true true false true
|
||||
'
|
||||
"""
|
||||
} else {
|
||||
sh """
|
||||
set -e
|
||||
ssh -p ${SSH_PORT} -o StrictHostKeyChecking=no ${PROD_SSH_USER}@${PROD_DEPLOY_HOST} '
|
||||
set -e
|
||||
cd ${PROD_DEPLOY_ROOT}
|
||||
git fetch origin
|
||||
git reset --hard HEAD
|
||||
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} IMAGE_TAG_RETAIN_COUNT=${env.IMAGE_TAG_RETAIN_COUNT} ./scripts/deploy_compose.sh prod "" "" ${FRONTEND_CHANGED} ${BACKEND_CHANGED} ${DEPLOY_CONFIG_CHANGED}
|
||||
'
|
||||
"""
|
||||
}
|
||||
}
|
||||
echo "[Deploy Prod] done"
|
||||
}
|
||||
}
|
||||
post {
|
||||
success {
|
||||
script {
|
||||
notifyDeployAll(
|
||||
envLabel: '生产环境',
|
||||
host: env.PROD_DEPLOY_HOST,
|
||||
status: 'success',
|
||||
)
|
||||
}
|
||||
}
|
||||
failure {
|
||||
script {
|
||||
notifyDeployAll(
|
||||
envLabel: '生产环境',
|
||||
host: env.PROD_DEPLOY_HOST,
|
||||
status: 'failure',
|
||||
)
|
||||
}
|
||||
}
|
||||
aborted {
|
||||
script {
|
||||
notifyDeployAll(
|
||||
envLabel: '生产环境',
|
||||
host: env.PROD_DEPLOY_HOST,
|
||||
status: 'failure',
|
||||
extraNote: '阶段已中止(可能为未确认生产部署或人工取消)',
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
post {
|
||||
always {
|
||||
// 统一输出最终状态,便于回溯 / Print final flags for traceability
|
||||
echo "[Post] BRANCH_NAME=${env.BRANCH_NAME}, FRONTEND_CHANGED=${env.FRONTEND_CHANGED}, BACKEND_CHANGED=${env.BACKEND_CHANGED}, DEPLOY_CONFIG_CHANGED=${env.DEPLOY_CONFIG_CHANGED}"
|
||||
echo "[Post] FORCE_FULL_DEPLOY_USED=${env.FORCE_FULL_DEPLOY_USED ?: 'false'}, REMOTE_DRIFT_DETECTED=${env.REMOTE_DRIFT_DETECTED ?: 'false'}, REMOTE_VERIFY_SKIPPED=${env.REMOTE_VERIFY_SKIPPED ?: 'false'}, ROLLBACK_IMAGE_TAG=${env.ROLLBACK_IMAGE_TAG ?: ''}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,48 +1,210 @@
|
||||
# hxops
|
||||
|
||||
#### 介绍
|
||||
hxops
|
||||
|
||||
#### 软件架构
|
||||
软件架构说明
|
||||
|
||||
|
||||
#### 安装教程
|
||||
|
||||
1. xxxx
|
||||
2. xxxx
|
||||
3. xxxx
|
||||
|
||||
#### 使用说明
|
||||
|
||||
1. xxxx
|
||||
2. xxxx
|
||||
3. xxxx
|
||||
|
||||
#### 参与贡献
|
||||
|
||||
1. Fork 本仓库
|
||||
2. 新建 Feat_xxx 分支
|
||||
3. 提交代码
|
||||
4. 新建 Pull Request
|
||||
|
||||
|
||||
#### 特技
|
||||
|
||||
1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md
|
||||
2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com)
|
||||
3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目
|
||||
4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目
|
||||
5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help)
|
||||
6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
|
||||
## 环境配置
|
||||
|
||||
本项目依赖 Oracle Instant Client 19.30。
|
||||
|
||||
### 安装步骤:
|
||||
1. 访问 [Oracle Instant Client 下载页面](官方链接),并接受许可协议。
|
||||
2. 根据你的操作系统,下载对应的 **Basic Lite** 版本安装包。
|
||||
3. 将下载的压缩包解压到本地目录。
|
||||
4. 在项目根目录下创建名为 `oracle_client` 的文件夹,并将解压后的所有文件(`adrci.exe` 等)放入其中。
|
||||
|
||||
 *(可在此处放置一个目录结构截图,清晰地展示 `oracle_client` 文件夹的位置和内部文件)*
|
||||
# Document Cleaning
|
||||
|
||||
Independent internal web system for document cleaning, version tracking, batch download, and manual sync into Dify datasets.
|
||||
|
||||
## Stack
|
||||
|
||||
- Frontend: Vue 3, Vite, Tailwind, Uppy
|
||||
- Backend: FastAPI, SQLAlchemy, Alembic
|
||||
- Queue: RQ + Redis
|
||||
- Worker runtime: Python + LibreOffice
|
||||
- Database: SQLite or PostgreSQL (configurable)
|
||||
|
||||
## Project Layout
|
||||
|
||||
- `frontend/`: Vue workspace UI
|
||||
- `backend/`: FastAPI API, RQ worker tasks, vendored `edkb_system`
|
||||
- `project-governance/`: Codex skill governance, workflow docs, and audit snapshots
|
||||
- `docker-compose.yml`: full deployment stack for `192.168.100.230`
|
||||
|
||||
## Local Run
|
||||
|
||||
1. Copy `.env.example` to `.env` and fill in `DIFY_API_KEY`.
|
||||
2. Start services:
|
||||
|
||||
```bash
|
||||
docker compose up --build -d
|
||||
```
|
||||
|
||||
3. Open `http://localhost:8891`.
|
||||
|
||||
Default login comes from `.env`:
|
||||
|
||||
- username: `admin`
|
||||
- password: `admin123456`
|
||||
|
||||
## Local Direct Run Without Docker
|
||||
|
||||
Use this mode on a workstation that does not have Docker available.
|
||||
|
||||
1. Copy `backend/backend.env.example` to `backend/.env`.
|
||||
2. Choose a database mode in `backend/.env`:
|
||||
|
||||
```env
|
||||
# Option A: local SQLite
|
||||
DATABASE_BACKEND=sqlite
|
||||
DATABASE_URL=
|
||||
SQLITE_DATABASE_URL=sqlite:///./document_cleaning.db
|
||||
|
||||
# Option B: local/shared PostgreSQL
|
||||
DATABASE_BACKEND=postgres
|
||||
DATABASE_URL=
|
||||
POSTGRES_DATABASE_URL=postgresql+psycopg://postgres:difyai123456@localhost:5432/doccleaning_db
|
||||
```
|
||||
|
||||
`DATABASE_URL` remains supported as a direct override. If it is set, it takes priority over `DATABASE_BACKEND`.
|
||||
|
||||
3. Keep `TASK_EXECUTION_MODE=sync` for local smoke tests.
|
||||
4. You can now use the project-local Python runtime under `python/`.
|
||||
|
||||
5. Start the backend:
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
python -m alembic upgrade head
|
||||
python -m uvicorn app.main:app --host 127.0.0.1 --port 8000
|
||||
```
|
||||
|
||||
6. Start the frontend in another terminal:
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm run dev -- --host 127.0.0.1 --port 5174
|
||||
```
|
||||
|
||||
7. Open `http://127.0.0.1:5174`.
|
||||
|
||||
Convenience scripts in the project root:
|
||||
|
||||
```powershell
|
||||
.\start-local-backend.ps1
|
||||
.\start-local-frontend.ps1
|
||||
.\start-local-dev.ps1
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- `start-local-backend.ps1` runs Alembic first, then starts FastAPI.
|
||||
- `start-local-frontend.ps1` starts the Vite dev server.
|
||||
- `start-local-dev.ps1` starts both in background and writes logs to `tmp_run/`.
|
||||
|
||||
Notes:
|
||||
|
||||
- In local direct mode, queue tasks run inline through the API process.
|
||||
- Real Dify sync still requires a valid `DIFY_API_KEY`.
|
||||
- Server deployment should continue using `docker compose`.
|
||||
|
||||
## Production Deployment
|
||||
|
||||
The compose file is already configured for the planned entrypoint:
|
||||
|
||||
- `http://192.168.100.230:8891`
|
||||
|
||||
Deploy on the target server with:
|
||||
|
||||
```bash
|
||||
docker compose --env-file .env up --build -d
|
||||
```
|
||||
|
||||
Database selection is now configurable through `.env`:
|
||||
|
||||
```env
|
||||
# Option A: use the compose PostgreSQL service
|
||||
DATABASE_BACKEND=postgres
|
||||
DATABASE_URL=
|
||||
POSTGRES_DATABASE_URL=postgresql+psycopg://document_cleaning:document_cleaning@postgres:5432/document_cleaning
|
||||
|
||||
# Option B: use SQLite
|
||||
DATABASE_BACKEND=sqlite
|
||||
DATABASE_URL=
|
||||
SQLITE_DATABASE_URL=sqlite:///./document_cleaning.db
|
||||
|
||||
# Option C: explicit override
|
||||
DATABASE_URL=postgresql+psycopg://postgres:difyai123456@localhost:5432/doccleaning_db
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- `DATABASE_URL` has the highest priority.
|
||||
- When running inside Docker, `localhost` points to the container itself. A host-level PostgreSQL service must use a reachable host name or IP instead of `localhost`.
|
||||
|
||||
Current deployment path on the server:
|
||||
|
||||
- `/home/inspur/tools/document-cleaning`
|
||||
|
||||
## Core Flows
|
||||
|
||||
- Upload one or many files into a group.
|
||||
- Deduplicate by `SHA-256` within the same group.
|
||||
- Create a new version when title matches but content changed.
|
||||
- Convert in the background through RQ workers.
|
||||
- Download original files or generated markdown individually or in bulk.
|
||||
- Manually sync selected documents to Dify.
|
||||
- Auto-create a Dify dataset on first sync for each group.
|
||||
|
||||
## Dify Integration
|
||||
|
||||
- Group name maps to one Dify dataset.
|
||||
- Sync uses cleaned markdown text, not the raw original file.
|
||||
- Existing logical documents are updated in Dify instead of duplicated.
|
||||
- Dataset defaults are managed in the admin console.
|
||||
|
||||
## External Integration API
|
||||
|
||||
Use this when another internal site needs to query knowledge-base/file relationships without direct database access.
|
||||
|
||||
1. Set `INTEGRATION_API_KEY` in `.env`.
|
||||
2. Optionally set `INTEGRATION_DOWNLOAD_SECRET` to a dedicated signing secret. If omitted, the app falls back to `JWT_SECRET`.
|
||||
3. Call the query API with `X-Integration-Key: <your key>`.
|
||||
|
||||
Recommended pattern:
|
||||
|
||||
- External site backend stores `INTEGRATION_API_KEY`
|
||||
- Backend calls this system's query API
|
||||
- Query response returns short-lived signed download URLs
|
||||
- External site frontend opens those signed URLs directly without carrying the integration key
|
||||
|
||||
Example endpoints:
|
||||
|
||||
- `GET /api/integration/knowledge-bases`
|
||||
- `GET /api/integration/files?knowledge_base_id=123`
|
||||
- `GET /api/integration/files?file_name=report`
|
||||
- `GET /api/integration/files/456`
|
||||
- `GET /api/integration/dify-file?dataset_id=<dify_dataset_id>&remote_document_id=<dify_document_id>`
|
||||
- `GET /api/integration/download?version_id=<local_version_id>&kind=source&token=<signed token>`
|
||||
- `GET /api/integration/download?version_id=<local_version_id>&kind=md&token=<signed token>`
|
||||
|
||||
## Dify Sync Throttling
|
||||
|
||||
To avoid overloading Dify when many files are pushed at once, sync jobs now support retry backoff and a short global cooldown gate.
|
||||
|
||||
Relevant `.env` knobs:
|
||||
|
||||
```env
|
||||
DIFY_SYNC_MAX_RETRIES=4
|
||||
DIFY_SYNC_RETRY_SCHEDULE=30,60,120,300
|
||||
DIFY_SYNC_COOLDOWN_SECONDS=60
|
||||
```
|
||||
|
||||
Behavior:
|
||||
|
||||
- Retryable Dify congestion errors such as `too many clients already` are not marked failed immediately.
|
||||
- The sync job is re-queued with backoff.
|
||||
- A short global cooldown prevents the next sync jobs from hammering Dify during the same congestion window.
|
||||
|
||||
## Tests
|
||||
|
||||
Backend:
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
python -m pytest tests -q
|
||||
```
|
||||
|
||||
Frontend:
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm install
|
||||
npm run build
|
||||
```
|
||||
@@ -1,8 +0,0 @@
|
||||
venv
|
||||
__pycache__
|
||||
*.pyc
|
||||
*.pyo
|
||||
local_test.db
|
||||
.git
|
||||
.vscode
|
||||
tests
|
||||
+10
-68
@@ -1,78 +1,20 @@
|
||||
# syntax=docker/dockerfile:1.4
|
||||
ARG PYTHON_BASE_IMAGE=python:3.12-slim-bookworm
|
||||
FROM ${PYTHON_BASE_IMAGE}
|
||||
FROM python:3.12-slim
|
||||
|
||||
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
|
||||
ENV PYTHONDONTWRITEBYTECODE=1
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
|
||||
--mount=type=cache,target=/var/lib/apt,sharing=locked \
|
||||
set -eux; \
|
||||
if [ -f /etc/apt/sources.list.d/debian.sources ]; then \
|
||||
sed -i "s|http://deb.debian.org/debian|${APT_MIRROR}/debian|g" /etc/apt/sources.list.d/debian.sources; \
|
||||
sed -i "s|http://deb.debian.org/debian-security|${APT_MIRROR}/debian-security|g" /etc/apt/sources.list.d/debian.sources; \
|
||||
fi; \
|
||||
if [ -f /etc/apt/sources.list ]; then \
|
||||
sed -i "s|http://deb.debian.org/debian|${APT_MIRROR}/debian|g" /etc/apt/sources.list; \
|
||||
sed -i "s|http://deb.debian.org/debian-security|${APT_MIRROR}/debian-security|g" /etc/apt/sources.list; \
|
||||
fi; \
|
||||
apt-get update && apt-get install -y --no-install-recommends \
|
||||
libgl1 \
|
||||
libglib2.0-0 \
|
||||
libxcb1 \
|
||||
libx11-6 \
|
||||
libxext6 \
|
||||
libnsl2 \
|
||||
libreoffice-nogui \
|
||||
fonts-noto-cjk \
|
||||
curl \
|
||||
ca-certificates \
|
||||
gnupg \
|
||||
unixodbc-dev \
|
||||
&& (apt-get install -y --no-install-recommends libaio1 || apt-get install -y --no-install-recommends libaio1t64) \
|
||||
&& if [ ! -e /usr/lib/$(dpkg-architecture -qDEB_HOST_MULTIARCH)/libaio.so.1 ] && [ -e /usr/lib/$(dpkg-architecture -qDEB_HOST_MULTIARCH)/libaio.so.1t64 ]; then ln -s /usr/lib/$(dpkg-architecture -qDEB_HOST_MULTIARCH)/libaio.so.1t64 /usr/lib/$(dpkg-architecture -qDEB_HOST_MULTIARCH)/libaio.so.1; fi \
|
||||
&& install -d -m 0755 /etc/apt/keyrings \
|
||||
&& curl -fsSL https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor -o /etc/apt/keyrings/microsoft-prod.gpg \
|
||||
&& chmod a+r /etc/apt/keyrings/microsoft-prod.gpg \
|
||||
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/microsoft-prod.gpg] https://packages.microsoft.com/debian/12/prod bookworm main" > /etc/apt/sources.list.d/mssql-release.list \
|
||||
&& apt-get update \
|
||||
&& ACCEPT_EULA=Y apt-get install -y --no-install-recommends msodbcsql18 \
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends libreoffice fonts-noto-cjk curl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install Python dependencies
|
||||
COPY backend/requirements.txt backend/requirements-ocr.txt ./
|
||||
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||
set -eux; \
|
||||
PIP_ARGS="--no-cache-dir --retries 10 --timeout 60"; \
|
||||
if [ -n "${PIP_INDEX_URL:-}" ]; then \
|
||||
PIP_ARGS="$PIP_ARGS --index-url ${PIP_INDEX_URL}"; \
|
||||
fi; \
|
||||
if [ -n "${PIP_EXTRA_INDEX_URL:-}" ]; then \
|
||||
PIP_ARGS="$PIP_ARGS --extra-index-url ${PIP_EXTRA_INDEX_URL}"; \
|
||||
fi; \
|
||||
pip install $PIP_ARGS -r requirements.txt && \
|
||||
pip install $PIP_ARGS \
|
||||
"$(grep '^opencv-python-headless' requirements-ocr.txt)" && \
|
||||
pip install $PIP_ARGS --no-deps \
|
||||
"$(grep '^rapidocr-onnxruntime' requirements-ocr.txt)" && \
|
||||
pip install $PIP_ARGS \
|
||||
pyclipper Shapely six onnxruntime && \
|
||||
python -c "import cv2; from rapidocr_onnxruntime import RapidOCR; import networkx, openpyxl"
|
||||
COPY requirements.txt /app/requirements.txt
|
||||
RUN pip install --no-cache-dir -r /app/requirements.txt
|
||||
|
||||
# Copy backend code and the Text2SQL schema required at runtime
|
||||
COPY backend/ .
|
||||
RUN mkdir -p /app/docs
|
||||
COPY docs/(表+字段).md /app/docs/(表+字段).md
|
||||
COPY . /app
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
# Expose port 5000
|
||||
EXPOSE 5000
|
||||
CMD ["sh", "-c", "alembic upgrade head && uvicorn app.main:app --host 0.0.0.0 --port 8000"]
|
||||
|
||||
# Start Gunicorn
|
||||
# Using the config file we created earlier
|
||||
CMD ["gunicorn", "-c", "deploy/gunicorn_config.py", "run:app"]
|
||||
@@ -0,0 +1,36 @@
|
||||
[alembic]
|
||||
script_location = migrations
|
||||
sqlalchemy.url = sqlite:///./document_cleaning.db
|
||||
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers = console
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
|
||||
+1
-212
@@ -1,212 +1 @@
|
||||
"""
|
||||
backend/app/__init__.py
|
||||
|
||||
用途:应用工厂:创建 Flask 应用、挂载全局异常与响应处理。
|
||||
依赖:app.extensions(db、migrate)、app.api.register_blueprints、app.core.config。
|
||||
逻辑:create_app 初始化扩展后委托 api 层集中注册 Blueprint;启动时 load_context_adapters 注册 Dify 上下文 adapter;
|
||||
并幂等补建 file-asset-cleanup 默认排程(覆盖空库先迁移后建用户)。
|
||||
"""
|
||||
import logging
|
||||
import uuid
|
||||
|
||||
from flask import Flask, jsonify, request, g
|
||||
from flask_cors import CORS
|
||||
from werkzeug.exceptions import HTTPException
|
||||
|
||||
from app.core.config.settings import config
|
||||
from app.core.errors import AppError
|
||||
from app.extensions import db, migrate
|
||||
from app.core.response import error_payload, utc_iso_now
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _apply_persisted_settings(app: Flask) -> None:
|
||||
"""Pull the latest runtime-editable settings into ``app.config``.
|
||||
|
||||
Reads from the database first, then ``backend/.env``. Tolerates the
|
||||
common case where the table does not yet exist (fresh deploy before
|
||||
``flask db upgrade`` runs).
|
||||
"""
|
||||
from app.core.config.env_persistence import apply_env_settings
|
||||
|
||||
try:
|
||||
applied = apply_env_settings()
|
||||
except Exception as exc: # pragma: no cover - defensive
|
||||
logger.warning('Failed to refresh persisted settings: %s', exc)
|
||||
return
|
||||
for key, value in applied.items():
|
||||
app.config[key] = value
|
||||
|
||||
|
||||
def create_app(config_name='default'):
|
||||
app = Flask(__name__)
|
||||
app.config.from_object(config[config_name])
|
||||
|
||||
db.init_app(app)
|
||||
migrate.init_app(app, db)
|
||||
CORS(app) # 允许跨域
|
||||
|
||||
from app.api import register_blueprints
|
||||
|
||||
register_blueprints(app)
|
||||
|
||||
# Eagerly load persisted runtime settings so the very first request after
|
||||
# a worker boot already sees the admin-saved configuration (otherwise the
|
||||
# window between worker boot and the first ``before_request`` would still
|
||||
# serve the defaults baked into config.py / the image).
|
||||
with app.app_context():
|
||||
_apply_persisted_settings(app)
|
||||
from app.services.agent_runtime_context.bootstrap import load_context_adapters
|
||||
load_context_adapters()
|
||||
from app.services.agent_registry.handlers.bootstrap import load_handlers
|
||||
load_handlers()
|
||||
from app.services.chat.intent_route_registry import ensure_intent_routes_loaded
|
||||
ensure_intent_routes_loaded()
|
||||
from app.services.schedule.scheduler_service import start_scheduler
|
||||
start_scheduler(app)
|
||||
# 空库先迁移后建用户:启动补建 + User commit 钩子即时补建,消除无排程窗口
|
||||
try:
|
||||
from app.services.file_assets.cleanup_schedule import (
|
||||
ensure_default_file_asset_cleanup_schedule,
|
||||
register_file_asset_cleanup_schedule_hooks,
|
||||
)
|
||||
register_file_asset_cleanup_schedule_hooks()
|
||||
ensure_default_file_asset_cleanup_schedule()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure file-asset-cleanup schedule: %s', exc)
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
FixedAssetsSnapshotService.start_worker(app)
|
||||
|
||||
@app.before_request
|
||||
def _sync_persisted_settings():
|
||||
_apply_persisted_settings(app)
|
||||
incoming_request_id = (request.headers.get('X-Request-Id') or '').strip()
|
||||
g.request_id = incoming_request_id or f"req_{uuid.uuid4().hex[:16]}"
|
||||
|
||||
@app.after_request
|
||||
def _wrap_success_response(resp):
|
||||
if not bool(app.config.get('ENABLE_API_ENVELOPE', False)):
|
||||
return resp
|
||||
if not request.path.startswith('/api/'):
|
||||
return resp
|
||||
if resp.is_streamed:
|
||||
return resp
|
||||
if resp.status_code < 200 or resp.status_code >= 300:
|
||||
return resp
|
||||
if not (resp.mimetype or '').startswith('application/json'):
|
||||
return resp
|
||||
try:
|
||||
payload = resp.get_json(silent=True)
|
||||
except Exception:
|
||||
payload = None
|
||||
if isinstance(payload, dict) and 'success' in payload:
|
||||
return resp
|
||||
wrapped = {
|
||||
'success': True,
|
||||
'data': payload,
|
||||
'request_id': getattr(g, 'request_id', None),
|
||||
'timestamp': utc_iso_now(),
|
||||
}
|
||||
wrapped_resp = jsonify(wrapped)
|
||||
wrapped_resp.status_code = resp.status_code
|
||||
for key, value in resp.headers.items():
|
||||
lower = key.lower()
|
||||
if lower in ('content-length', 'content-type'):
|
||||
continue
|
||||
wrapped_resp.headers[key] = value
|
||||
return wrapped_resp
|
||||
|
||||
def _should_return_json_error() -> bool:
|
||||
if request.path.startswith('/api/'):
|
||||
return True
|
||||
accepted = request.headers.get('Accept', '')
|
||||
return 'application/json' in accepted.lower()
|
||||
|
||||
def _log_api_error(
|
||||
*,
|
||||
code: str,
|
||||
message: str,
|
||||
status: int,
|
||||
details: dict | None = None,
|
||||
exc: Exception | None = None,
|
||||
) -> None:
|
||||
request_id = getattr(g, 'request_id', None)
|
||||
log_kwargs = {
|
||||
'method': request.method,
|
||||
'path': request.path,
|
||||
'status': status,
|
||||
'code': code,
|
||||
'message': message,
|
||||
'request_id': request_id,
|
||||
'details': details or {},
|
||||
}
|
||||
log_text = (
|
||||
'API error %(method)s %(path)s status=%(status)s code=%(code)s '
|
||||
'message=%(message)s request_id=%(request_id)s details=%(details)s'
|
||||
)
|
||||
if status >= 500:
|
||||
app.logger.error(log_text, log_kwargs, exc_info=exc)
|
||||
else:
|
||||
app.logger.warning(log_text, log_kwargs)
|
||||
|
||||
@app.errorhandler(HTTPException)
|
||||
def _handle_http_exception(exc: HTTPException):
|
||||
if not _should_return_json_error():
|
||||
return exc
|
||||
message = exc.description or exc.name or 'HTTP error'
|
||||
code_num = int(exc.code or 500)
|
||||
code_map = {
|
||||
400: 'VALIDATION.INVALID_PARAM',
|
||||
401: 'AUTH.UNAUTHORIZED',
|
||||
403: 'AUTH.FORBIDDEN',
|
||||
404: 'RESOURCE.NOT_FOUND',
|
||||
409: 'RESOURCE.CONFLICT',
|
||||
429: 'SYSTEM.RATE_LIMITED',
|
||||
}
|
||||
code = code_map.get(code_num, 'SYSTEM.HTTP_ERROR')
|
||||
_log_api_error(code=code, message=str(message), status=code_num, exc=exc)
|
||||
payload = error_payload(
|
||||
code=code,
|
||||
message=str(message),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
)
|
||||
return jsonify(payload), code_num
|
||||
|
||||
@app.errorhandler(AppError)
|
||||
def _handle_app_error(exc: AppError):
|
||||
"""统一业务异常 → JSON error_payload(API 层应 raise AppError 而非 jsonify error)。"""
|
||||
_log_api_error(
|
||||
code=exc.code,
|
||||
message=exc.message,
|
||||
status=exc.http_status,
|
||||
details=exc.details,
|
||||
exc=exc,
|
||||
)
|
||||
payload = error_payload(
|
||||
code=exc.code,
|
||||
message=exc.message,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
details=exc.details,
|
||||
retryable=exc.retryable,
|
||||
)
|
||||
return jsonify(payload), exc.http_status
|
||||
|
||||
@app.errorhandler(Exception)
|
||||
def _handle_unexpected_exception(exc: Exception):
|
||||
_log_api_error(
|
||||
code='SYSTEM.INTERNAL_ERROR',
|
||||
message='Internal server error',
|
||||
status=500,
|
||||
exc=exc,
|
||||
)
|
||||
if not _should_return_json_error():
|
||||
return '<h1><p>Internal Server Error</p></h1>', 500
|
||||
payload = error_payload(
|
||||
code='SYSTEM.INTERNAL_ERROR',
|
||||
message='Internal server error',
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
)
|
||||
return jsonify(payload), 500
|
||||
|
||||
return app
|
||||
"""Document Cleaning backend package."""
|
||||
@@ -1,64 +1 @@
|
||||
"""
|
||||
backend/app/api/__init__.py
|
||||
|
||||
用途:集中注册所有 HTTP Blueprint。
|
||||
依赖:各 api 子模块 blueprint(单体或分包 re-export)。
|
||||
逻辑:create_app 唯一调用 register_blueprints(app);后续拆包只改本文件 import 来源。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Flask
|
||||
|
||||
|
||||
def register_blueprints(app: Flask) -> None:
|
||||
"""
|
||||
注册全部 HTTP Blueprint,保持对外 url_prefix 与 Wave 0 之前一致。
|
||||
核心逻辑:集中管理路由挂载点;后续 api/user、api/chat 等分包迁移时仅改本函数 import 来源。
|
||||
Args:
|
||||
app: Flask 应用实例。
|
||||
"""
|
||||
# [STEP 1] 单体模块(Wave 3 前保持不变)
|
||||
from app.api.chat import chat_bp
|
||||
from app.api.admin import admin_bp
|
||||
from app.api.agents import agents_bp
|
||||
from app.api.user import user_bp
|
||||
from app.api.integration import integration_bp
|
||||
from app.api.internal_jobs import internal_jobs_bp
|
||||
from app.api.maintenance import maintenance_bp
|
||||
from app.api.speech import speech_bp
|
||||
from app.api.training import training_admin_bp, training_user_bp
|
||||
from app.api.agent_runtime_context_tools import agent_runtime_context_bp
|
||||
|
||||
# [STEP 2] 已分包骨架(Wave 3:kb、schedule 等)
|
||||
from app.api.kb import knowledge_base_bp
|
||||
from app.api.schedule import schedule_admin_bp
|
||||
from app.api.workspace import (
|
||||
workspace_announcements_bp,
|
||||
workspace_file_check_bp,
|
||||
workspace_schedule_bp,
|
||||
workspace_shipping_notice_bp,
|
||||
)
|
||||
from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp
|
||||
from app.api.files import files_bp
|
||||
|
||||
app.register_blueprint(chat_bp, url_prefix='/api/chat')
|
||||
app.register_blueprint(admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(agents_bp, url_prefix='/api/agents')
|
||||
app.register_blueprint(user_bp, url_prefix='/api/user')
|
||||
app.register_blueprint(training_user_bp, url_prefix='/api/user')
|
||||
app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb')
|
||||
app.register_blueprint(integration_bp, url_prefix='/api/integration')
|
||||
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_announcements_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_file_check_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
|
||||
app.register_blueprint(maintenance_bp, url_prefix='/api/maintenance')
|
||||
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
|
||||
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
|
||||
app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context')
|
||||
app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance')
|
||||
app.register_blueprint(speech_bp, url_prefix='/api/speech')
|
||||
app.register_blueprint(training_admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(files_bp, url_prefix='/api/files')
|
||||
from app.api import admin, auth, files, groups, integration, jobs
|
||||
@@ -0,0 +1,454 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy import func, or_
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from app.config import get_settings
|
||||
from app.database import get_db
|
||||
from app.deps import require_admin
|
||||
from app.models import Department, Document, DocumentVersion, Group, Job, SystemSetting, User, UserDepartmentAccess, UserGroupAccess
|
||||
from app.schemas import (
|
||||
DepartmentCreateRequest,
|
||||
DepartmentDeleteRequest,
|
||||
DepartmentUpdateRequest,
|
||||
SettingsUpdateRequest,
|
||||
UserCreateRequest,
|
||||
UserUpdateRequest,
|
||||
)
|
||||
from app.security import hash_password
|
||||
from app.serializers import serialize_department, serialize_settings, serialize_user
|
||||
from app.services.dify_service import DifyError, DifyService
|
||||
from app.services.watchdog_service import (
|
||||
local_convert_health_summary,
|
||||
local_sync_health_summary,
|
||||
read_watchdog_snapshot,
|
||||
recover_stale_converts,
|
||||
recover_stale_syncs,
|
||||
)
|
||||
from app.user_policy import PRIMARY_SUPER_ADMIN_USERNAME, is_primary_super_admin_username
|
||||
|
||||
|
||||
router = APIRouter(prefix="/admin", tags=["admin"])
|
||||
|
||||
|
||||
def _replace_user_department_access(db: Session, *, user_id: int, primary_department_id: int | None, department_ids: list[int]) -> None:
|
||||
existing_accesses = db.query(UserDepartmentAccess).filter(UserDepartmentAccess.user_id == user_id).all()
|
||||
for access in existing_accesses:
|
||||
db.delete(access)
|
||||
db.flush()
|
||||
requested_ids = sorted({item for item in department_ids if item is not None} | ({primary_department_id} if primary_department_id is not None else set()))
|
||||
if not requested_ids:
|
||||
return
|
||||
existing_ids = {row[0] for row in db.query(Department.id).filter(Department.id.in_(requested_ids)).all()}
|
||||
missing_ids = sorted(set(requested_ids) - existing_ids)
|
||||
if missing_ids:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=f"Department(s) not found: {', '.join(map(str, missing_ids))}",
|
||||
)
|
||||
for department_id in requested_ids:
|
||||
if department_id == primary_department_id:
|
||||
continue
|
||||
db.add(UserDepartmentAccess(user_id=user_id, department_id=department_id))
|
||||
|
||||
|
||||
def _validate_super_admin_constraints(*, username: str, requested_role: str | None, requested_active: bool | None = None) -> None:
|
||||
if requested_role == "super_admin" and not is_primary_super_admin_username(username):
|
||||
raise HTTPException(status_code=400, detail=f"Only {PRIMARY_SUPER_ADMIN_USERNAME} can be a super admin.")
|
||||
if is_primary_super_admin_username(username):
|
||||
if requested_role is not None and requested_role != "super_admin":
|
||||
raise HTTPException(status_code=400, detail=f"{PRIMARY_SUPER_ADMIN_USERNAME} must remain a super admin.")
|
||||
if requested_active is False:
|
||||
raise HTTPException(status_code=400, detail=f"{PRIMARY_SUPER_ADMIN_USERNAME} cannot be deactivated.")
|
||||
|
||||
|
||||
def _department_metrics_query(db: Session):
|
||||
knowledge_base_counts = (
|
||||
db.query(Group.department_id.label("department_id"), func.count(Group.id).label("knowledge_base_count"))
|
||||
.group_by(Group.department_id)
|
||||
.subquery()
|
||||
)
|
||||
primary_user_counts = (
|
||||
db.query(
|
||||
User.primary_department_id.label("department_id"),
|
||||
func.count(User.id).label("primary_user_count"),
|
||||
)
|
||||
.group_by(User.primary_department_id)
|
||||
.subquery()
|
||||
)
|
||||
extra_user_counts = (
|
||||
db.query(
|
||||
UserDepartmentAccess.department_id.label("department_id"),
|
||||
func.count(UserDepartmentAccess.id).label("extra_user_count"),
|
||||
)
|
||||
.group_by(UserDepartmentAccess.department_id)
|
||||
.subquery()
|
||||
)
|
||||
return (
|
||||
db.query(
|
||||
Department,
|
||||
(func.coalesce(primary_user_counts.c.primary_user_count, 0) + func.coalesce(extra_user_counts.c.extra_user_count, 0)).label(
|
||||
"user_count"
|
||||
),
|
||||
func.coalesce(knowledge_base_counts.c.knowledge_base_count, 0).label("knowledge_base_count"),
|
||||
)
|
||||
.outerjoin(primary_user_counts, primary_user_counts.c.department_id == Department.id)
|
||||
.outerjoin(extra_user_counts, extra_user_counts.c.department_id == Department.id)
|
||||
.outerjoin(knowledge_base_counts, knowledge_base_counts.c.department_id == Department.id)
|
||||
.order_by(Department.name.asc())
|
||||
)
|
||||
|
||||
|
||||
def _department_reference_summary(db: Session, department_id: int) -> dict[str, int]:
|
||||
return {
|
||||
"knowledge_base_count": db.query(func.count(Group.id)).filter(Group.department_id == department_id).scalar() or 0,
|
||||
"primary_user_count": db.query(func.count(User.id)).filter(User.primary_department_id == department_id).scalar() or 0,
|
||||
"extra_user_count": db.query(func.count(UserDepartmentAccess.id)).filter(UserDepartmentAccess.department_id == department_id).scalar() or 0,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/departments")
|
||||
def list_all_departments(db: Session = Depends(get_db), admin: User = Depends(require_admin)):
|
||||
rows = _department_metrics_query(db).all()
|
||||
return {
|
||||
"data": [
|
||||
serialize_department(item, user_count=user_count, knowledge_base_count=knowledge_base_count)
|
||||
for item, user_count, knowledge_base_count in rows
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@router.post("/departments")
|
||||
def create_department(
|
||||
payload: DepartmentCreateRequest,
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_admin),
|
||||
):
|
||||
name = payload.name.strip()
|
||||
if not name:
|
||||
raise HTTPException(status_code=400, detail="Department name is required.")
|
||||
exists = db.query(Department).filter(func.lower(Department.name) == name.lower()).first()
|
||||
if exists:
|
||||
raise HTTPException(status_code=409, detail="Department already exists.")
|
||||
department = Department(name=name, description=payload.description)
|
||||
db.add(department)
|
||||
db.commit()
|
||||
db.refresh(department)
|
||||
return serialize_department(department)
|
||||
|
||||
|
||||
@router.patch("/departments/{department_id}")
|
||||
def update_department(
|
||||
department_id: int,
|
||||
payload: DepartmentUpdateRequest,
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_admin),
|
||||
):
|
||||
department = db.query(Department).filter(Department.id == department_id).first()
|
||||
if not department:
|
||||
raise HTTPException(status_code=404, detail="Department not found.")
|
||||
if payload.name is not None:
|
||||
name = payload.name.strip()
|
||||
if not name:
|
||||
raise HTTPException(status_code=400, detail="Department name is required.")
|
||||
conflict = (
|
||||
db.query(Department)
|
||||
.filter(func.lower(Department.name) == name.lower(), Department.id != department_id)
|
||||
.first()
|
||||
)
|
||||
if conflict:
|
||||
raise HTTPException(status_code=409, detail="Department already exists.")
|
||||
department.name = name
|
||||
if payload.description is not None:
|
||||
department.description = payload.description
|
||||
db.commit()
|
||||
db.refresh(department)
|
||||
return serialize_department(department)
|
||||
|
||||
|
||||
@router.delete("/departments/{department_id}")
|
||||
def delete_department(
|
||||
department_id: int,
|
||||
payload: DepartmentDeleteRequest,
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_admin),
|
||||
):
|
||||
department = db.query(Department).filter(Department.id == department_id).first()
|
||||
if not department:
|
||||
raise HTTPException(status_code=404, detail="Department not found.")
|
||||
|
||||
target_department = None
|
||||
if payload.target_department_id is not None:
|
||||
if payload.target_department_id == department_id:
|
||||
raise HTTPException(status_code=400, detail="Migration target must be a different department.")
|
||||
target_department = db.query(Department).filter(Department.id == payload.target_department_id).first()
|
||||
if not target_department:
|
||||
raise HTTPException(status_code=404, detail="Migration target department not found.")
|
||||
|
||||
reference_summary = _department_reference_summary(db, department_id)
|
||||
has_references = any(reference_summary.values())
|
||||
if has_references and target_department is None:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Department still has knowledge bases or users. Choose another department to migrate first.",
|
||||
)
|
||||
|
||||
if target_department is not None:
|
||||
db.query(Group).filter(Group.department_id == department_id).update(
|
||||
{Group.department_id: target_department.id},
|
||||
synchronize_session=False,
|
||||
)
|
||||
|
||||
affected_users = (
|
||||
db.query(User)
|
||||
.options(joinedload(User.department_accesses))
|
||||
.filter(
|
||||
or_(
|
||||
User.primary_department_id == department_id,
|
||||
User.department_accesses.any(UserDepartmentAccess.department_id == department_id),
|
||||
)
|
||||
)
|
||||
.all()
|
||||
)
|
||||
|
||||
for user in affected_users:
|
||||
if user.primary_department_id == department_id:
|
||||
user.primary_department_id = target_department.id
|
||||
migrated_access_ids = [access.department_id for access in user.department_accesses if access.department_id != department_id]
|
||||
if user.primary_department_id != target_department.id:
|
||||
migrated_access_ids.append(target_department.id)
|
||||
_replace_user_department_access(
|
||||
db,
|
||||
user_id=user.id,
|
||||
primary_department_id=user.primary_department_id,
|
||||
department_ids=migrated_access_ids,
|
||||
)
|
||||
|
||||
db.query(Department).filter(Department.id == department_id).delete(synchronize_session=False)
|
||||
db.commit()
|
||||
return {
|
||||
"deleted_department_id": department_id,
|
||||
"migrated_to_department_id": target_department.id if target_department else None,
|
||||
**reference_summary,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/users")
|
||||
def list_users(db: Session = Depends(get_db), admin: User = Depends(require_admin)):
|
||||
users = (
|
||||
db.query(User)
|
||||
.options(joinedload(User.primary_department), joinedload(User.department_accesses))
|
||||
.order_by(User.username.asc())
|
||||
.all()
|
||||
)
|
||||
return {"data": [serialize_user(item) for item in users]}
|
||||
|
||||
|
||||
@router.post("/users")
|
||||
def create_user(
|
||||
payload: UserCreateRequest,
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_admin),
|
||||
):
|
||||
if payload.primary_department_id is None:
|
||||
raise HTTPException(status_code=400, detail="Primary department is required.")
|
||||
exists = db.query(User).filter(User.username == payload.username).first()
|
||||
if exists:
|
||||
raise HTTPException(status_code=409, detail="Username already exists.")
|
||||
_validate_super_admin_constraints(username=payload.username, requested_role=payload.role, requested_active=True)
|
||||
user = User(
|
||||
username=payload.username,
|
||||
full_name=payload.full_name,
|
||||
password_hash=hash_password(payload.password),
|
||||
role=payload.role,
|
||||
is_active=True,
|
||||
primary_department_id=payload.primary_department_id,
|
||||
)
|
||||
db.add(user)
|
||||
db.flush()
|
||||
db.refresh(user)
|
||||
_replace_user_department_access(
|
||||
db,
|
||||
user_id=user.id,
|
||||
primary_department_id=payload.primary_department_id,
|
||||
department_ids=payload.accessible_department_ids,
|
||||
)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
return serialize_user(user)
|
||||
|
||||
|
||||
@router.patch("/users/{user_id}")
|
||||
def update_user(
|
||||
user_id: int,
|
||||
payload: UserUpdateRequest,
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_admin),
|
||||
):
|
||||
user = db.query(User).options(joinedload(User.department_accesses)).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found.")
|
||||
_validate_super_admin_constraints(
|
||||
username=user.username,
|
||||
requested_role=payload.role,
|
||||
requested_active=payload.is_active,
|
||||
)
|
||||
if payload.full_name is not None:
|
||||
user.full_name = payload.full_name
|
||||
if payload.role is not None:
|
||||
user.role = payload.role
|
||||
if payload.is_active is not None:
|
||||
user.is_active = payload.is_active
|
||||
if payload.password:
|
||||
user.password_hash = hash_password(payload.password)
|
||||
|
||||
target_primary_department_id = payload.primary_department_id if payload.primary_department_id is not None else user.primary_department_id
|
||||
if payload.primary_department_id is not None:
|
||||
user.primary_department_id = payload.primary_department_id
|
||||
if payload.accessible_department_ids is not None or payload.primary_department_id is not None:
|
||||
_replace_user_department_access(
|
||||
db,
|
||||
user_id=user.id,
|
||||
primary_department_id=target_primary_department_id,
|
||||
department_ids=payload.accessible_department_ids or [],
|
||||
)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
return serialize_user(user)
|
||||
|
||||
|
||||
@router.delete("/users/{user_id}")
|
||||
def delete_user(
|
||||
user_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_admin),
|
||||
):
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found.")
|
||||
if is_primary_super_admin_username(user.username):
|
||||
raise HTTPException(status_code=400, detail=f"{PRIMARY_SUPER_ADMIN_USERNAME} cannot be deleted.")
|
||||
if user.id == admin.id:
|
||||
raise HTTPException(status_code=400, detail="You cannot delete your own account.")
|
||||
|
||||
db.query(Group).filter(Group.created_by_id == user_id).update({Group.created_by_id: None}, synchronize_session=False)
|
||||
db.query(Document).filter(Document.created_by_id == user_id).update({Document.created_by_id: None}, synchronize_session=False)
|
||||
db.query(DocumentVersion).filter(DocumentVersion.uploader_id == user_id).update(
|
||||
{DocumentVersion.uploader_id: None},
|
||||
synchronize_session=False,
|
||||
)
|
||||
db.query(Job).filter(Job.created_by_id == user_id).update({Job.created_by_id: None}, synchronize_session=False)
|
||||
db.query(UserDepartmentAccess).filter(UserDepartmentAccess.user_id == user_id).delete(synchronize_session=False)
|
||||
db.query(UserGroupAccess).filter(UserGroupAccess.user_id == user_id).delete(synchronize_session=False)
|
||||
db.query(User).filter(User.id == user_id).delete(synchronize_session=False)
|
||||
db.commit()
|
||||
return {"deleted_user_id": user_id}
|
||||
|
||||
|
||||
@router.get("/settings")
|
||||
def get_settings_row(db: Session = Depends(get_db), admin: User = Depends(require_admin)):
|
||||
settings_row = db.query(SystemSetting).filter(SystemSetting.id == 1).first()
|
||||
if not settings_row:
|
||||
raise HTTPException(status_code=404, detail="Settings not found.")
|
||||
return serialize_settings(settings_row)
|
||||
|
||||
|
||||
@router.get("/dify-models")
|
||||
def list_dify_models(admin: User = Depends(require_admin)):
|
||||
try:
|
||||
dify = DifyService()
|
||||
embedding_models = dify.list_available_embedding_models()
|
||||
rerank_models = dify.list_available_rerank_models()
|
||||
default_embedding_provider, default_embedding_model = dify.resolve_embedding_model_choice()
|
||||
default_rerank_provider, default_rerank_model = dify.resolve_rerank_model_choice()
|
||||
except DifyError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
|
||||
return {
|
||||
"embedding_models": [
|
||||
{"provider": item.provider, "model": item.model, "label": item.label}
|
||||
for item in embedding_models
|
||||
],
|
||||
"rerank_models": [
|
||||
{"provider": item.provider, "model": item.model, "label": item.label}
|
||||
for item in rerank_models
|
||||
],
|
||||
"automatic_defaults": {
|
||||
"embedding_model_provider": default_embedding_provider,
|
||||
"embedding_model": default_embedding_model,
|
||||
"reranking_model_provider": default_rerank_provider,
|
||||
"reranking_model": default_rerank_model,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/dify-health")
|
||||
def get_dify_health(db: Session = Depends(get_db), admin: User = Depends(require_admin)):
|
||||
settings = get_settings()
|
||||
return {
|
||||
"dify_base_url": settings.dify_base_url,
|
||||
"dify_api_configured": bool(settings.dify_api_key),
|
||||
"watchdog_snapshot": read_watchdog_snapshot(settings),
|
||||
"local_convert_health": local_convert_health_summary(
|
||||
db,
|
||||
timeout_seconds=settings.watchdog_stale_convert_timeout_seconds,
|
||||
orphan_grace_seconds=settings.watchdog_convert_orphan_grace_seconds,
|
||||
settings=settings,
|
||||
),
|
||||
"local_sync_health": local_sync_health_summary(
|
||||
db,
|
||||
timeout_seconds=settings.watchdog_stale_sync_timeout_seconds,
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/recover-stale-syncs")
|
||||
def run_stale_sync_recovery(db: Session = Depends(get_db), admin: User = Depends(require_admin)):
|
||||
settings = get_settings()
|
||||
return recover_stale_syncs(
|
||||
db,
|
||||
timeout_seconds=settings.watchdog_stale_sync_timeout_seconds,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/recover-stale-converts")
|
||||
def run_stale_convert_recovery(db: Session = Depends(get_db), admin: User = Depends(require_admin)):
|
||||
settings = get_settings()
|
||||
return recover_stale_converts(
|
||||
db,
|
||||
timeout_seconds=settings.watchdog_stale_convert_timeout_seconds,
|
||||
orphan_grace_seconds=settings.watchdog_convert_orphan_grace_seconds,
|
||||
settings=settings,
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/settings")
|
||||
def update_settings_row(
|
||||
payload: SettingsUpdateRequest,
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_admin),
|
||||
):
|
||||
settings_row = db.query(SystemSetting).filter(SystemSetting.id == 1).first()
|
||||
if not settings_row:
|
||||
raise HTTPException(status_code=404, detail="Settings not found.")
|
||||
for field in [
|
||||
"dify_permission",
|
||||
"indexing_technique",
|
||||
"search_method",
|
||||
"doc_form",
|
||||
"embedding_model_provider",
|
||||
"embedding_model",
|
||||
"reranking_model_provider",
|
||||
"reranking_model",
|
||||
"top_k",
|
||||
"score_threshold_enabled",
|
||||
]:
|
||||
value = getattr(payload, field)
|
||||
if value is not None:
|
||||
setattr(settings_row, field, value)
|
||||
if payload.score_threshold is not None:
|
||||
settings_row.score_threshold = str(payload.score_threshold)
|
||||
db.commit()
|
||||
db.refresh(settings_row)
|
||||
return serialize_settings(settings_row)
|
||||
@@ -1,23 +0,0 @@
|
||||
"""
|
||||
backend/app/api/admin/__init__.py
|
||||
|
||||
用途:管理后台 Blueprint 入口(Wave 3 分包)。
|
||||
依赖:admin/blueprint.py 及各子模块路由。
|
||||
逻辑:import 子模块注册路由;register_blueprints 从本包 import admin_bp。
|
||||
"""
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
|
||||
import app.api.admin.dashboard # noqa: F401
|
||||
import app.api.admin.departments # noqa: F401
|
||||
import app.api.admin.agents # noqa: F401
|
||||
import app.api.admin.guides # noqa: F401
|
||||
import app.api.admin.quick_questions # noqa: F401
|
||||
import app.api.admin.faq_candidates # noqa: F401
|
||||
import app.api.admin.reports # noqa: F401
|
||||
import app.api.admin.database # noqa: F401
|
||||
import app.api.admin.permissions # noqa: F401
|
||||
import app.api.admin.users # noqa: F401
|
||||
import app.api.admin.wecom # noqa: F401
|
||||
import app.api.admin.announcements # noqa: F401
|
||||
|
||||
__all__ = ['admin_bp']
|
||||
@@ -1,132 +0,0 @@
|
||||
"""
|
||||
backend/app/api/admin/agents.py
|
||||
|
||||
用途:管理后台 Agent CRUD、连通性测试、权限绑定 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/agent_service、core.response.ok。
|
||||
逻辑:/agents* 路由;统一 success/data/request_id envelope。
|
||||
"""
|
||||
from flask import g, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.response import ok
|
||||
from app.services.admin import agent_service
|
||||
|
||||
|
||||
def _request_id() -> str | None:
|
||||
return getattr(g, 'request_id', None)
|
||||
|
||||
|
||||
@admin_bp.route('/agents/schema', methods=['GET'])
|
||||
@require_admin
|
||||
def get_agent_registry_schema():
|
||||
"""返回 Admin Agent Registry 权威 schema(平台枚举、Catalog、handler_config schema)。"""
|
||||
from app.services.agent_registry.admin_schema import build_agent_registry_schema
|
||||
|
||||
return ok(build_agent_registry_schema(), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/infer-content-profile', methods=['POST'])
|
||||
@require_admin
|
||||
def infer_agent_content_profile():
|
||||
"""根据 intent_routes 推断 content_profile(Admin 表单建议,不参与运行时)。"""
|
||||
from app.services.agent_registry.content_profiles import infer_content_profile_from_intent_routes
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
routes = data.get('intent_routes') if isinstance(data.get('intent_routes'), list) else []
|
||||
profile = infer_content_profile_from_intent_routes(routes)
|
||||
return ok({'content_profile': profile}, request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/type-catalog', methods=['GET'])
|
||||
@require_admin
|
||||
def list_agent_type_catalog():
|
||||
"""返回 Admin 应用类型 Catalog 下拉列表。"""
|
||||
from app.services.agent_registry.catalog import list_type_catalog
|
||||
|
||||
return ok(list_type_catalog(), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/content-profiles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_agent_content_profiles():
|
||||
"""返回 Admin 可选 content_profile 及默认文案模板。"""
|
||||
from app.services.agent_registry.content_profiles import list_content_profiles
|
||||
|
||||
return ok(list_content_profiles(), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/intent-routes', methods=['GET'])
|
||||
@require_admin
|
||||
def list_agent_intent_routes():
|
||||
"""返回 Admin 可选 Intent route 注册表(前端表单动态选项)。"""
|
||||
from app.services.chat.intent_route_registry import list_chat_intent_route_definitions
|
||||
|
||||
return ok(list_chat_intent_route_definitions(), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents', methods=['GET'])
|
||||
@require_admin
|
||||
def list_agents():
|
||||
"""返回全部 Agent 列表。"""
|
||||
return ok(agent_service.list_agents(), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents', methods=['POST'])
|
||||
@require_admin
|
||||
def create_agent():
|
||||
"""创建 Agent。"""
|
||||
data = request.get_json() or {}
|
||||
payload = agent_service.create_agent(data)
|
||||
return ok(payload, request_id=_request_id(), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_agent(id: int):
|
||||
"""更新 Agent。"""
|
||||
data = request.get_json() or {}
|
||||
agent_service.update_agent(id, data)
|
||||
return ok({'status': 'ok'}, request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_agent(id: int):
|
||||
"""删除 Agent。"""
|
||||
agent_service.delete_agent(id)
|
||||
return ok({'status': 'ok'}, request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/test', methods=['POST'])
|
||||
@require_admin
|
||||
def test_agent(id: int):
|
||||
"""测试 Agent 连通性。"""
|
||||
payload = agent_service.test_agent_connectivity(id)
|
||||
return ok(payload, request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/permissions', methods=['POST'])
|
||||
@require_admin
|
||||
def update_agent_permissions(id: int):
|
||||
"""设置 Agent 授权用户列表。"""
|
||||
data = request.get_json() or {}
|
||||
user_ids = data.get('user_ids', [])
|
||||
agent_service.update_agent_permissions(id, user_ids)
|
||||
return ok({'status': 'ok'}, request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/training-question-bank/import-pdf', methods=['POST'])
|
||||
@require_admin
|
||||
def import_training_question_bank_from_pdf(id: int):
|
||||
"""
|
||||
从已上传的培训试题 PDF 解析题库。
|
||||
|
||||
用途:给 Agent 管理表单提供“从试题 PDF 导入题库”入口,返回结构化题目供前端回填并继续人工微调。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = agent_service.import_training_question_bank_from_pdf(
|
||||
agent_id=id,
|
||||
guide_id=data.get('guide_id'),
|
||||
)
|
||||
return ok(payload, request_id=_request_id())
|
||||
@@ -1,43 +0,0 @@
|
||||
"""
|
||||
backend/app/api/admin/announcements.py
|
||||
|
||||
用途:管理后台公告 CRUD API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/announcement_service。
|
||||
逻辑:/announcements* 路由;工作台只读见 api/workspace/announcements.py。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import announcement_service
|
||||
|
||||
|
||||
@admin_bp.route('/announcements', methods=['GET'])
|
||||
@require_admin
|
||||
def list_announcements():
|
||||
"""列出全部公告(含 is_active)。"""
|
||||
return jsonify(announcement_service.list_announcements())
|
||||
|
||||
|
||||
@admin_bp.route('/announcements', methods=['POST'])
|
||||
@require_admin
|
||||
def create_announcement():
|
||||
"""创建公告。"""
|
||||
data = request.get_json() or {}
|
||||
payload = announcement_service.create_announcement(data)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@admin_bp.route('/announcements/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_announcement(id: int):
|
||||
"""更新公告。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(announcement_service.update_announcement(id, data))
|
||||
|
||||
|
||||
@admin_bp.route('/announcements/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_announcement(id: int):
|
||||
"""删除公告。"""
|
||||
return jsonify(announcement_service.delete_announcement(id))
|
||||
@@ -1,10 +0,0 @@
|
||||
"""
|
||||
backend/app/api/admin/blueprint.py
|
||||
|
||||
用途:管理后台 API 共享 Blueprint(Wave 3 分包后各子模块共用)。
|
||||
依赖:Flask Blueprint。
|
||||
逻辑:dashboard、departments、users、wecom 等子模块在此 bp 上注册路由;__init__ 导出 admin_bp。
|
||||
"""
|
||||
from flask import Blueprint
|
||||
|
||||
admin_bp = Blueprint('admin', __name__)
|
||||
@@ -1,42 +0,0 @@
|
||||
"""
|
||||
backend/app/api/admin/dashboard.py
|
||||
|
||||
用途:管理后台仪表盘 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/dashboard_service。
|
||||
逻辑:/dashboard* 路由。
|
||||
"""
|
||||
from flask import jsonify
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import dashboard_service
|
||||
|
||||
|
||||
@admin_bp.route('/dashboard/summary', methods=['GET'])
|
||||
@require_admin
|
||||
def dashboard_summary():
|
||||
"""
|
||||
管理后台仪表盘概览(供 Dashboard 页单次请求)。
|
||||
GET /api/admin/dashboard/summary
|
||||
"""
|
||||
return jsonify(dashboard_service.compute_dashboard_summary())
|
||||
|
||||
|
||||
@admin_bp.route('/dashboard/badges', methods=['GET'])
|
||||
@require_admin
|
||||
def dashboard_badges():
|
||||
"""
|
||||
管理后台侧栏待办角标(供 AdminLayout 轻量轮询/缓存刷新)。
|
||||
GET /api/admin/dashboard/badges
|
||||
"""
|
||||
return jsonify(dashboard_service.compute_dashboard_badges())
|
||||
|
||||
|
||||
@admin_bp.route('/dashboard', methods=['GET'])
|
||||
@require_admin
|
||||
def dashboard_stats():
|
||||
"""
|
||||
仪表盘统计(遗留接口;新代码请用 /dashboard/summary 与 /dashboard/badges)。
|
||||
GET /api/admin/dashboard
|
||||
"""
|
||||
return jsonify(dashboard_service.compute_legacy_dashboard_stats())
|
||||
@@ -1,38 +0,0 @@
|
||||
"""
|
||||
backend/app/api/admin/database.py
|
||||
|
||||
用途:管理后台数据表浏览 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/database_admin_service。
|
||||
逻辑:/database/* 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import database_admin_service
|
||||
|
||||
|
||||
def _query_params() -> dict[str, str]:
|
||||
return {k: str(v) for k, v in request.args.items()}
|
||||
|
||||
|
||||
@admin_bp.route('/database/<table>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_table_data(table: str):
|
||||
"""浏览指定表数据(最多 100 行)。"""
|
||||
return jsonify(database_admin_service.get_table_data(table, _query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/database/chat_logs/batch-delete', methods=['POST'])
|
||||
@require_admin
|
||||
def batch_delete_chat_logs():
|
||||
"""批量删除 chat_logs。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(database_admin_service.batch_delete_chat_logs(data.get('ids', [])))
|
||||
|
||||
|
||||
@admin_bp.route('/database/<table>/count', methods=['GET'])
|
||||
@require_admin
|
||||
def get_table_count(table: str):
|
||||
"""返回表行数。"""
|
||||
return jsonify(database_admin_service.get_table_count(table, _query_params()))
|
||||
@@ -1,45 +0,0 @@
|
||||
"""
|
||||
backend/app/api/admin/departments.py
|
||||
|
||||
用途:管理后台部门 CRUD API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/department_service。
|
||||
逻辑:/departments* 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import department_service
|
||||
|
||||
|
||||
@admin_bp.route('/departments', methods=['GET'])
|
||||
@require_admin
|
||||
def list_departments():
|
||||
"""返回全部部门列表。"""
|
||||
return jsonify(department_service.list_departments())
|
||||
|
||||
|
||||
@admin_bp.route('/departments', methods=['POST'])
|
||||
@require_admin
|
||||
def create_department():
|
||||
"""创建部门。"""
|
||||
data = request.get_json() or {}
|
||||
payload = department_service.create_department(data)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@admin_bp.route('/departments/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_department(id: int):
|
||||
"""更新部门。"""
|
||||
data = request.get_json() or {}
|
||||
department_service.update_department(id, data)
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
@admin_bp.route('/departments/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_department(id: int):
|
||||
"""删除部门。"""
|
||||
department_service.delete_department(id)
|
||||
return jsonify({'status': 'ok'})
|
||||
@@ -1,50 +0,0 @@
|
||||
"""
|
||||
backend/app/api/admin/faq_candidates.py
|
||||
|
||||
用途:热点 FAQ 候选管理 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/faq_service。
|
||||
逻辑:/faq-candidates* 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import faq_service
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates', methods=['GET'])
|
||||
@require_admin
|
||||
def list_faq_candidates():
|
||||
"""列出 PostgreSQL 热点 FAQ 候选。"""
|
||||
agent_id = request.args.get('agent_id', type=int)
|
||||
return jsonify(faq_service.list_faq_candidates(agent_id=agent_id))
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates/refresh', methods=['POST'])
|
||||
@require_admin
|
||||
def refresh_faq_candidates():
|
||||
"""手动触发离线热点聚合。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
agent_id = data.get('agent_id')
|
||||
dry_run = bool(data.get('dry_run'))
|
||||
if agent_id is not None:
|
||||
agent_id = int(agent_id)
|
||||
return jsonify(faq_service.refresh_faq_candidates(agent_id=agent_id, dry_run=dry_run))
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates/promote', methods=['POST'])
|
||||
@require_admin
|
||||
def promote_faq_candidate():
|
||||
"""将热点候选晋升为 QuickQuestion。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(faq_service.promote_faq_candidate(data))
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates/dismiss', methods=['POST'])
|
||||
@require_admin
|
||||
def dismiss_faq_candidate():
|
||||
"""忽略热点 FAQ 候选。"""
|
||||
data = request.get_json() or {}
|
||||
agent_id = data.get('agent_id')
|
||||
q_norm = str(data.get('q_norm') or '')
|
||||
return jsonify(faq_service.dismiss_faq_candidate(agent_id=int(agent_id), q_norm=q_norm))
|
||||
@@ -1,57 +0,0 @@
|
||||
"""
|
||||
backend/app/api/admin/guides.py
|
||||
|
||||
用途:Agent 引导资料 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/guide_service。
|
||||
逻辑:/guides* 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import guide_service
|
||||
|
||||
|
||||
@admin_bp.route('/guides/upload', methods=['POST'])
|
||||
@require_admin
|
||||
def upload_guide():
|
||||
"""上传引导文件至 MinIO。"""
|
||||
file = request.files.get('file')
|
||||
return jsonify(guide_service.upload_guide_file(file))
|
||||
|
||||
|
||||
@admin_bp.route('/guides', methods=['POST'])
|
||||
@require_admin
|
||||
def create_guide():
|
||||
"""创建引导记录。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
current_user = get_current_user()
|
||||
payload = guide_service.create_guide(data, created_by_id=getattr(current_user, 'id', None))
|
||||
return jsonify(payload)
|
||||
|
||||
|
||||
@admin_bp.route('/guides', methods=['GET'])
|
||||
@require_admin
|
||||
def list_guides():
|
||||
"""列出引导资料,可按 agent_id 过滤。"""
|
||||
agent_id_raw = request.args.get('agent_id')
|
||||
agent_id = int(agent_id_raw) if agent_id_raw else None
|
||||
return jsonify(guide_service.list_guides(agent_id=agent_id))
|
||||
|
||||
|
||||
@admin_bp.route('/guides/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_guide(id: int):
|
||||
"""更新引导元数据。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
guide_service.update_guide(id, data)
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@admin_bp.route('/guides/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_guide(id: int):
|
||||
"""删除引导及 MinIO 文件。"""
|
||||
guide_service.delete_guide(id)
|
||||
return jsonify({'success': True})
|
||||
@@ -1,49 +0,0 @@
|
||||
"""
|
||||
backend/app/api/admin/permissions.py
|
||||
|
||||
用途:管理后台权限批量更新与权限申请审批 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/permission_service。
|
||||
逻辑:/permissions/*、/permission-requests/*、/users/<id>/permissions 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import permission_service
|
||||
|
||||
|
||||
@admin_bp.route('/permissions/batch', methods=['POST'])
|
||||
@require_admin
|
||||
def batch_update_permissions():
|
||||
"""批量更新用户 Agent 权限(add / remove / set)。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(permission_service.batch_update_permissions(data))
|
||||
|
||||
|
||||
@admin_bp.route('/users/<int:id>/permissions', methods=['POST'])
|
||||
@require_admin
|
||||
def update_user_permissions(id: int):
|
||||
"""将指定用户的 Agent 权限重置为请求体 agent_ids。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(permission_service.update_user_permissions(id, data))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-requests', methods=['GET'])
|
||||
@require_admin
|
||||
def list_permission_requests():
|
||||
"""列出全部权限申请。"""
|
||||
return jsonify(permission_service.list_permission_requests())
|
||||
|
||||
|
||||
@admin_bp.route('/permission-requests/<int:id>/approve', methods=['POST'])
|
||||
@require_admin
|
||||
def approve_request(id: int):
|
||||
"""批准权限申请。"""
|
||||
return jsonify(permission_service.approve_permission_request(id))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-requests/<int:id>/reject', methods=['POST'])
|
||||
@require_admin
|
||||
def reject_request(id: int):
|
||||
"""拒绝权限申请。"""
|
||||
return jsonify(permission_service.reject_permission_request(id))
|
||||
@@ -1,46 +0,0 @@
|
||||
"""
|
||||
backend/app/api/admin/quick_questions.py
|
||||
|
||||
用途:全局常用问题 CRUD API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/faq_service。
|
||||
逻辑:/quick-questions* 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import faq_service
|
||||
|
||||
|
||||
@admin_bp.route('/quick-questions', methods=['GET'])
|
||||
@require_admin
|
||||
def list_quick_questions():
|
||||
"""列出全局常用问题,可选 stale_only 过滤。"""
|
||||
stale_only = str(request.args.get('stale_only', '')).lower() in {'1', 'true', 'yes'}
|
||||
return jsonify(faq_service.list_quick_questions(stale_only=stale_only))
|
||||
|
||||
|
||||
@admin_bp.route('/quick-questions', methods=['POST'])
|
||||
@require_admin
|
||||
def create_quick_question():
|
||||
"""创建全局常用问题。"""
|
||||
data = request.get_json() or {}
|
||||
payload = faq_service.create_quick_question(data)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@admin_bp.route('/quick-questions/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_quick_question(id: int):
|
||||
"""更新全局常用问题。"""
|
||||
data = request.get_json() or {}
|
||||
faq_service.update_quick_question(id, data)
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
@admin_bp.route('/quick-questions/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_quick_question(id: int):
|
||||
"""删除全局常用问题。"""
|
||||
faq_service.delete_quick_question(id)
|
||||
return jsonify({'status': 'ok'})
|
||||
@@ -1,88 +0,0 @@
|
||||
"""
|
||||
backend/app/api/admin/reports.py
|
||||
|
||||
用途:管理后台报表 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/report_service。
|
||||
逻辑:/reports/usage、/reports/applications、feedback 与 general-feedbacks 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import report_service
|
||||
|
||||
|
||||
def _query_params() -> dict[str, str]:
|
||||
return {k: str(v) for k, v in request.args.items()}
|
||||
|
||||
|
||||
@admin_bp.route('/reports/usage', methods=['GET'])
|
||||
@require_admin
|
||||
def usage_report():
|
||||
"""聊天使用分析报表(支持时间范围 range=7d|30d|90d|180d|365d)。"""
|
||||
try:
|
||||
user_page = int(request.args.get('user_page', 1))
|
||||
except (TypeError, ValueError):
|
||||
user_page = 1
|
||||
try:
|
||||
user_page_size = int(request.args.get('user_page_size', 10))
|
||||
except (TypeError, ValueError):
|
||||
user_page_size = 10
|
||||
range_key = request.args.get('range')
|
||||
return jsonify(
|
||||
report_service.build_usage_report(
|
||||
user_page=user_page,
|
||||
user_page_size=user_page_size,
|
||||
range_key=range_key,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/reports/applications', methods=['GET'])
|
||||
@require_admin
|
||||
def applications_report():
|
||||
"""
|
||||
应用运营报表:按应用聚合使用 / 权限 / 评分。
|
||||
Query: range, status, usage, q, sort, order, page, page_size。
|
||||
"""
|
||||
try:
|
||||
page = int(request.args.get('page', 1))
|
||||
except (TypeError, ValueError):
|
||||
page = 1
|
||||
try:
|
||||
page_size = int(request.args.get('page_size', 20))
|
||||
except (TypeError, ValueError):
|
||||
page_size = 20
|
||||
return jsonify(
|
||||
report_service.build_application_report(
|
||||
range_key=request.args.get('range'),
|
||||
status=request.args.get('status'),
|
||||
usage=request.args.get('usage'),
|
||||
q=request.args.get('q'),
|
||||
sort=request.args.get('sort'),
|
||||
order=request.args.get('order'),
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/reports/feedback', methods=['GET'])
|
||||
@require_admin
|
||||
def feedback_report():
|
||||
"""反馈评分分布报表。"""
|
||||
return jsonify(report_service.build_feedback_report())
|
||||
|
||||
|
||||
@admin_bp.route('/reports/general-feedbacks', methods=['GET'])
|
||||
@require_admin
|
||||
def list_general_feedbacks_report():
|
||||
"""通用反馈列表。"""
|
||||
return jsonify(report_service.list_general_feedbacks_report(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/reports/general-feedbacks/count', methods=['GET'])
|
||||
@require_admin
|
||||
def count_general_feedbacks_report():
|
||||
"""通用反馈计数。"""
|
||||
return jsonify(report_service.count_general_feedbacks_report(_query_params()))
|
||||
@@ -1,82 +0,0 @@
|
||||
"""
|
||||
backend/app/api/admin/users.py
|
||||
|
||||
用途:管理后台用户 CRUD API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/user_service、core.auth.jwt。
|
||||
逻辑:/users* 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.auth.jwt import get_current_user as _get_auth_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import user_service
|
||||
|
||||
|
||||
def _query_params() -> dict[str, str]:
|
||||
return {k: str(v) for k, v in request.args.items()}
|
||||
|
||||
|
||||
@admin_bp.route('/users', methods=['GET'])
|
||||
@require_admin
|
||||
def list_users():
|
||||
"""列出管理端用户(支持分页与筛选)。"""
|
||||
result = user_service.list_users(_query_params())
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@admin_bp.route('/users', methods=['POST'])
|
||||
@require_admin
|
||||
def create_user():
|
||||
"""创建用户并同步 Casdoor。"""
|
||||
data = request.get_json() or {}
|
||||
payload = user_service.create_user(data)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@admin_bp.route('/users/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_user(id: int):
|
||||
"""更新用户资料;有 password 时同步 Casdoor 改密。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(user_service.update_user(id, data))
|
||||
|
||||
|
||||
@admin_bp.route('/users/cleanup-rejected', methods=['POST'])
|
||||
@require_admin
|
||||
def cleanup_rejected_users():
|
||||
"""批量删除 status=rejected 的用户。"""
|
||||
return jsonify(user_service.cleanup_rejected_users())
|
||||
|
||||
|
||||
@admin_bp.route('/users/batch-delete', methods=['POST'])
|
||||
@require_admin
|
||||
def batch_delete_users():
|
||||
"""批量删除用户(排除当前登录管理员)。"""
|
||||
data = request.get_json() or {}
|
||||
current_user = _get_auth_user()
|
||||
current_user_id = current_user.id if current_user else None
|
||||
return jsonify(user_service.batch_delete_users(data.get('user_ids', []), current_user_id=current_user_id))
|
||||
|
||||
|
||||
@admin_bp.route('/users/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_user(id: int):
|
||||
"""删除单个用户。"""
|
||||
current_user = _get_auth_user()
|
||||
current_user_id = current_user.id if current_user else None
|
||||
return jsonify(user_service.delete_user(id, current_user_id=current_user_id))
|
||||
|
||||
|
||||
@admin_bp.route('/users/<int:id>/approve', methods=['POST'])
|
||||
@require_admin
|
||||
def approve_user(id: int):
|
||||
"""审批通过用户。"""
|
||||
return jsonify(user_service.approve_user(id))
|
||||
|
||||
|
||||
@admin_bp.route('/users/<int:id>/reject', methods=['POST'])
|
||||
@require_admin
|
||||
def reject_user(id: int):
|
||||
"""拒绝用户注册。"""
|
||||
return jsonify(user_service.reject_user(id))
|
||||
@@ -1,118 +0,0 @@
|
||||
"""
|
||||
backend/app/api/admin/wecom.py
|
||||
|
||||
用途:管理后台企微绑定、配置与诊断 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/wecom_admin_service。
|
||||
逻辑:/wecom/* 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import wecom_admin_service
|
||||
|
||||
|
||||
def _query_params() -> dict[str, str]:
|
||||
return {k: str(v) for k, v in request.args.items()}
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/debug-user-by-code', methods=['POST'])
|
||||
@require_admin
|
||||
def debug_wecom_user_by_code():
|
||||
"""通过 OAuth code 诊断企微用户匹配结果。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(wecom_admin_service.debug_user_by_code(data.get('code')))
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/bindings', methods=['GET'])
|
||||
@require_admin
|
||||
def list_wecom_bindings():
|
||||
"""分页列出企微绑定。"""
|
||||
return jsonify(wecom_admin_service.list_bindings(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/bind', methods=['POST'])
|
||||
@require_admin
|
||||
def bind_wecom_user():
|
||||
"""管理员手动绑定企微账号。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(wecom_admin_service.bind_user(data))
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/unbind', methods=['POST'])
|
||||
@require_admin
|
||||
def unbind_wecom_user():
|
||||
"""管理员解绑企微账号。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(wecom_admin_service.unbind_user(data))
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/provision', methods=['POST'])
|
||||
@require_admin
|
||||
def provision_wecom_user():
|
||||
"""创建/更新用户并绑定企微、分配权限。"""
|
||||
data = request.get_json() or {}
|
||||
payload, status_code = wecom_admin_service.provision_user(data)
|
||||
return jsonify(payload), status_code
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/login-audits', methods=['GET'])
|
||||
@require_admin
|
||||
def get_wecom_login_audits():
|
||||
"""查询登录审计(企微/密码等来源)。"""
|
||||
return jsonify(wecom_admin_service.list_login_audits(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/notify-settings', methods=['GET', 'PUT'])
|
||||
@require_admin
|
||||
def wecom_notify_settings():
|
||||
"""读取或更新企微通知配置。"""
|
||||
if request.method == 'GET':
|
||||
return jsonify(wecom_admin_service.serialize_notify_settings())
|
||||
data = request.get_json() or {}
|
||||
return jsonify(wecom_admin_service.update_notify_settings(data))
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/system-settings', methods=['GET', 'PUT'])
|
||||
@require_admin
|
||||
def wecom_system_settings():
|
||||
"""读取或更新企微 OAuth 系统配置。"""
|
||||
if request.method == 'GET':
|
||||
return jsonify(wecom_admin_service.serialize_system_settings())
|
||||
data = request.get_json() or {}
|
||||
return jsonify(wecom_admin_service.update_system_settings(data))
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/integration-manifest', methods=['GET'])
|
||||
@require_admin
|
||||
def wecom_integration_manifest():
|
||||
"""返回企微集成 manifest(回调 URL、OAuth 端点等)。"""
|
||||
return jsonify(
|
||||
wecom_admin_service.integration_manifest(
|
||||
host_url=request.host_url,
|
||||
host=request.host,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/notify-metrics', methods=['GET'])
|
||||
@require_admin
|
||||
def wecom_notify_metrics():
|
||||
"""企微通知发送/打开率指标(近 30 天)。"""
|
||||
return jsonify(wecom_admin_service.notify_metrics())
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/binding-stats', methods=['GET'])
|
||||
@require_admin
|
||||
def wecom_binding_stats():
|
||||
"""活跃用户企微绑定统计。"""
|
||||
return jsonify(wecom_admin_service.binding_stats())
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/sync-userids', methods=['POST'])
|
||||
@require_admin
|
||||
def sync_wecom_userids_admin():
|
||||
"""从 OA 按工号同步 users.wecom_userid。"""
|
||||
data = request.get_json() or {}
|
||||
apply = bool(data.get('apply'))
|
||||
return jsonify(wecom_admin_service.sync_userids(apply=apply))
|
||||
@@ -1,107 +0,0 @@
|
||||
"""
|
||||
backend/app/api/agent_runtime_context_tools.py
|
||||
|
||||
用途:暴露 agent_runtime_context 只读 Tool API,供 Dify Chatflow 解析 HXOPS 上下文。
|
||||
依赖:app.core.errors、agent_runtime_context.parser/openapi_spec、shipping_notice.tool_api_url。
|
||||
逻辑:OpenAPI 文档接口放行;parse 工具复用 Authorization Bearer / X-Integration-Key 鉴权,不推进业务状态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request
|
||||
|
||||
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError
|
||||
from app.services.agent_runtime_context.openapi_spec import build_agent_runtime_context_openapi_spec
|
||||
from app.services.agent_runtime_context.parser import parse_agent_runtime_context
|
||||
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||
|
||||
agent_runtime_context_bp = Blueprint("agent_runtime_context_tools", __name__)
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验 agent_runtime_context Tool API 鉴权 Header。
|
||||
|
||||
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;Dify 请求 parse 工具时由 before_request 自动触发。
|
||||
|
||||
核心逻辑:只接受 Authorization Bearer 或 X-Integration-Key,复用 INTEGRATION_API_KEY 作为平台工具密钥。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 未配置 INTEGRATION_API_KEY。
|
||||
UnauthorizedError: 缺少或传入错误鉴权。
|
||||
"""
|
||||
configured = str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError("INTEGRATION_API_KEY is not configured", code="missing_auth")
|
||||
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||
if configured in {token, integration_key}:
|
||||
return
|
||||
if not token and not integration_key:
|
||||
raise UnauthorizedError("missing_auth")
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
"""
|
||||
归一化 Tool API 错误码。
|
||||
|
||||
核心逻辑:保持与 shipping/file-check Tool API 的 ok:false 响应风格一致,便于 Dify 侧统一处理。
|
||||
|
||||
Args:
|
||||
exc: 业务异常。
|
||||
|
||||
Returns:
|
||||
Tool 侧错误码。
|
||||
"""
|
||||
message = str(exc.message or "").strip()
|
||||
if message in {"missing_auth", "invalid_auth"}:
|
||||
return message
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
return "missing_auth"
|
||||
return exc.code
|
||||
|
||||
|
||||
@agent_runtime_context_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
"""把业务异常统一转成 Tool 侧约定的 JSON 结构。"""
|
||||
return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status
|
||||
|
||||
|
||||
@agent_runtime_context_bp.before_request
|
||||
def _verify_tool_access():
|
||||
"""
|
||||
对上下文解析 Tool 做统一 Header 鉴权。
|
||||
|
||||
核心逻辑:OpenAPI 导入文档无需鉴权;parse 工具必须携带平台 Tool Key。
|
||||
"""
|
||||
if request.path.endswith("/openapi.json"):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
@agent_runtime_context_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def openapi_spec():
|
||||
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
|
||||
return jsonify(build_agent_runtime_context_openapi_spec(resolve_tool_api_base_url()))
|
||||
|
||||
|
||||
@agent_runtime_context_bp.route("/tools/parse", methods=["POST"])
|
||||
def parse_context_tool():
|
||||
"""
|
||||
解析 agent_runtime_context 的白名单字段。
|
||||
|
||||
【AI 触发时机】:Dify 需要读取 HXOPS session/task/batch/run_purpose/state_hint 等上下文字段时调用;
|
||||
不用于推进业务状态。
|
||||
"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
return jsonify(
|
||||
parse_agent_runtime_context(
|
||||
payload.get("agent_runtime_context"),
|
||||
payload.get("paths"),
|
||||
)
|
||||
)
|
||||
@@ -1,200 +0,0 @@
|
||||
"""
|
||||
backend/app/api/agents.py
|
||||
|
||||
用途:普通用户可见的 Agent 列表与 AgentGuide 静态资源。
|
||||
依赖:app.core.auth.jwt、models、minio_service、agent_registry.serialization。
|
||||
逻辑:按当前用户 RBAC 返回可访问 Agent;列表统一 serialize_agent_for_user_list(结构化列为准)。
|
||||
"""
|
||||
import os
|
||||
import mimetypes
|
||||
import re
|
||||
from flask import Blueprint, Response, jsonify, request, send_from_directory, stream_with_context
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError
|
||||
from app.models import Agent, User, AgentGuide
|
||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||
from app.services.minio_service import minio_service
|
||||
|
||||
# 定义 Blueprint,将在应用工厂中注册为 /api/agents
|
||||
agents_bp = Blueprint('agents', __name__)
|
||||
|
||||
|
||||
def _serialize_agent_row(agent: Agent, *, visible_agent_ids: set[int] | None = None) -> dict:
|
||||
payload = serialize_agent_list_item(agent)
|
||||
if not bool(getattr(agent, 'is_aggregate', False)):
|
||||
return payload
|
||||
from app.services.agent_directory import serialize_directory_members
|
||||
|
||||
members = serialize_directory_members(agent.id, active_only=True)
|
||||
if visible_agent_ids is not None:
|
||||
members = [member for member in members if int(member.get('id') or 0) in visible_agent_ids]
|
||||
if members:
|
||||
payload['directory_members'] = members
|
||||
return payload
|
||||
|
||||
|
||||
def _list_active_agents_for_user(user: User) -> list[Agent]:
|
||||
"""返回用户可见的完整 Agent ORM 行(含 Registry 结构化列)。"""
|
||||
if user.role == 'admin':
|
||||
return (
|
||||
db.session.query(Agent)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.order_by(Agent.id.asc())
|
||||
.all()
|
||||
)
|
||||
return [agent for agent in user.agents if agent.is_active]
|
||||
|
||||
|
||||
@agents_bp.route('', methods=['GET'])
|
||||
def list_user_agents():
|
||||
"""
|
||||
获取当前用户可见的 Agent 列表
|
||||
用途:Workspace 页面展示应用网格、聊天侧栏 Agent 切换
|
||||
"""
|
||||
user: User = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
|
||||
agents = _list_active_agents_for_user(user)
|
||||
visible_agent_ids = {agent.id for agent in agents}
|
||||
return jsonify([_serialize_agent_row(agent, visible_agent_ids=visible_agent_ids) for agent in sort_agent_rows(agents)])
|
||||
|
||||
@agents_bp.route('/<int:agent_id>/guides', methods=['GET'])
|
||||
def list_agent_guides(agent_id):
|
||||
"""
|
||||
获取指定应用的新手指南列表 (需登录)
|
||||
用途:客户端 Chat 界面点击新手指南
|
||||
"""
|
||||
get_current_user() # 确保已登录
|
||||
|
||||
if agent_id == 0:
|
||||
generic_agent = (
|
||||
db.session.query(Agent)
|
||||
.filter_by(agent_code='generic', is_active=True)
|
||||
.order_by(Agent.sort_order.asc(), Agent.id.asc())
|
||||
.first()
|
||||
)
|
||||
if generic_agent:
|
||||
agent_id = generic_agent.id
|
||||
else:
|
||||
return jsonify([])
|
||||
|
||||
guides = (
|
||||
db.session.query(AgentGuide)
|
||||
.filter_by(agent_id=agent_id, status=1)
|
||||
.order_by(AgentGuide.sort_order.asc(), AgentGuide.created_at.desc())
|
||||
.all()
|
||||
)
|
||||
|
||||
result = []
|
||||
for g in guides:
|
||||
result.append({
|
||||
'id': g.id,
|
||||
'file_name': g.file_name,
|
||||
'file_type': g.file_type,
|
||||
'guide_usage': g.guide_usage,
|
||||
'file_url': minio_service.get_public_url(g.file_path),
|
||||
'file_size': g.file_size,
|
||||
'remark': g.remark,
|
||||
'updated_at': g.updated_at.isoformat()
|
||||
})
|
||||
return jsonify(result)
|
||||
|
||||
@agents_bp.route('/public', methods=['GET'])
|
||||
def list_public_agents():
|
||||
"""
|
||||
获取公开的 Agent 列表 (无需登录)
|
||||
用途:登录页面展示
|
||||
"""
|
||||
agents = (
|
||||
db.session.query(Agent)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.order_by(Agent.id.asc())
|
||||
.all()
|
||||
)
|
||||
visible_agent_ids = {agent.id for agent in agents}
|
||||
return jsonify([_serialize_agent_row(agent, visible_agent_ids=visible_agent_ids) for agent in sort_agent_rows(agents)])
|
||||
|
||||
def _parse_byte_range(range_header: str, file_size: int) -> tuple[int, int] | None:
|
||||
"""
|
||||
解析浏览器单段字节范围请求。
|
||||
|
||||
用途:iOS Safari/企业微信播放 MP4 时依赖 Range 请求,本函数将请求转换为闭区间。
|
||||
参数约束:仅接受单个 bytes 范围;无效或越界范围返回 None。
|
||||
"""
|
||||
match = re.fullmatch(r'bytes=(\d*)-(\d*)', range_header.strip())
|
||||
if not match or file_size <= 0:
|
||||
return None
|
||||
start_text, end_text = match.groups()
|
||||
if not start_text and not end_text:
|
||||
return None
|
||||
if start_text:
|
||||
start = int(start_text)
|
||||
end = int(end_text) if end_text else file_size - 1
|
||||
else:
|
||||
suffix_length = int(end_text)
|
||||
if suffix_length <= 0:
|
||||
return None
|
||||
start = max(file_size - suffix_length, 0)
|
||||
end = file_size - 1
|
||||
if start >= file_size or end < start:
|
||||
return None
|
||||
return start, min(end, file_size - 1)
|
||||
|
||||
|
||||
def _stream_minio_guide_file(filename: str) -> Response:
|
||||
"""
|
||||
以同源流式响应返回 MinIO 指南文件。
|
||||
|
||||
用途:消除生产 HTTPS 页面加载 HTTP MinIO 地址的混合内容问题,并支持 iOS 所需的 206 响应。
|
||||
参数约束:filename 为系统生成的 MinIO 对象名;响应流结束后必须释放连接。
|
||||
"""
|
||||
stat = minio_service.stat_file(filename)
|
||||
file_size = int(stat.size)
|
||||
content_type = stat.content_type or mimetypes.guess_type(filename)[0] or 'application/octet-stream'
|
||||
requested_range = request.headers.get('Range', '').strip()
|
||||
byte_range = _parse_byte_range(requested_range, file_size) if requested_range else None
|
||||
if requested_range and byte_range is None:
|
||||
return Response(status=416, headers={'Content-Range': f'bytes */{file_size}'})
|
||||
|
||||
start, end = byte_range or (0, file_size - 1)
|
||||
content_length = end - start + 1
|
||||
source = minio_service.open_file_stream(filename, offset=start, length=content_length)
|
||||
|
||||
def generate():
|
||||
try:
|
||||
while True:
|
||||
chunk = source.read(64 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
yield chunk
|
||||
finally:
|
||||
source.close()
|
||||
source.release_conn()
|
||||
|
||||
headers = {
|
||||
'Accept-Ranges': 'bytes',
|
||||
'Content-Length': str(content_length),
|
||||
'Cache-Control': 'private, max-age=3600',
|
||||
}
|
||||
status = 206 if byte_range else 200
|
||||
if byte_range:
|
||||
headers['Content-Range'] = f'bytes {start}-{end}/{file_size}'
|
||||
return Response(stream_with_context(generate()), status=status, headers=headers, content_type=content_type)
|
||||
|
||||
|
||||
@agents_bp.route('/guides/files/<path:filename>', methods=['GET'])
|
||||
def serve_guide_file(filename):
|
||||
"""
|
||||
返回本地或 MinIO 中的指南文件。
|
||||
|
||||
用途:为 PDF、图片和培训视频提供统一同源地址;本地文件沿用 Flask 条件响应,MinIO 文件支持 Range。
|
||||
参数约束:filename 仅用于系统指南存储目录或 MinIO 指南桶,不接受任意外部路径。
|
||||
"""
|
||||
local_directory = os.path.join(os.getcwd(), 'data', 'agent-guides')
|
||||
if os.path.isfile(os.path.join(local_directory, filename)):
|
||||
return send_from_directory(local_directory, filename, conditional=True)
|
||||
return _stream_minio_guide_file(filename)
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.database import get_db
|
||||
from app.models import User
|
||||
from app.schemas import LoginRequest, TokenResponse
|
||||
from app.security import create_access_token, verify_password
|
||||
from app.serializers import serialize_user
|
||||
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
|
||||
@router.post("/login", response_model=TokenResponse)
|
||||
def login(payload: LoginRequest, db: Session = Depends(get_db)):
|
||||
user = db.query(User).filter(User.username == payload.username, User.is_active.is_(True)).first()
|
||||
if not user or not verify_password(payload.password, user.password_hash):
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
|
||||
token = create_access_token(user.username)
|
||||
return TokenResponse(access_token=token, user=serialize_user(user))
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,162 +0,0 @@
|
||||
"""
|
||||
backend/app/api/chat_turns.py
|
||||
|
||||
用途:Chat Turn 流式 API 路由(POST /api/chat/turns/stream)。
|
||||
依赖:app.core.decorators、ChatTurnRuntime、notice_upload、batch_from_notices、chat_bp。
|
||||
逻辑:支持 JSON 与 multipart(附件上传 + Turn);由 chat.py 注册到同一 Blueprint。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import uuid
|
||||
|
||||
from flask import Response, g, request, stream_with_context
|
||||
|
||||
from app.core.decorators import require_agent_permission
|
||||
from app.core.errors import AppError, ValidationError
|
||||
from app.services.chat.turn_runtime import ChatTurnRuntime
|
||||
|
||||
|
||||
def _parse_turn_body_and_files() -> tuple[dict, list]:
|
||||
"""
|
||||
解析 Chat Turn 请求体;multipart 时从 form 字段读取 JSON 与 files。
|
||||
|
||||
Returns:
|
||||
(body, uploads) — uploads 为 Werkzeug FileStorage 列表,JSON 请求时为空。
|
||||
"""
|
||||
content_type = str(request.content_type or "")
|
||||
if "multipart/form-data" in content_type:
|
||||
input_raw = request.form.get("input") or "{}"
|
||||
try:
|
||||
input_data = json.loads(input_raw)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValidationError("input must be valid JSON") from exc
|
||||
context_raw = request.form.get("context") or "{}"
|
||||
try:
|
||||
context_data = json.loads(context_raw) if context_raw else {}
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValidationError("context must be valid JSON") from exc
|
||||
agent_id = request.form.get("agent_id") or request.form.get("agentId")
|
||||
conversation_id = request.form.get("conversation_id") or request.form.get("conversationId")
|
||||
body: dict = {
|
||||
"agent_id": agent_id,
|
||||
"conversation_id": conversation_id,
|
||||
"input": input_data if isinstance(input_data, dict) else {},
|
||||
"context": context_data if isinstance(context_data, dict) else {},
|
||||
}
|
||||
uploads = request.files.getlist("files")
|
||||
if not uploads:
|
||||
single = request.files.get("file")
|
||||
if single:
|
||||
uploads = [single]
|
||||
return body, uploads
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
return body if isinstance(body, dict) else {}, []
|
||||
|
||||
|
||||
def _stage_upload_files(uploads: list) -> list[dict]:
|
||||
"""将 multipart 文件读入内存 staged 结构,供 handler 构造 FileStorage。"""
|
||||
staged: list[dict] = []
|
||||
for upload in uploads:
|
||||
if upload is None:
|
||||
continue
|
||||
data = upload.read() or b""
|
||||
if not data:
|
||||
continue
|
||||
staged.append({
|
||||
"filename": str(getattr(upload, "filename", None) or "upload"),
|
||||
"content_type": str(getattr(upload, "content_type", None) or ""),
|
||||
"data": data,
|
||||
})
|
||||
return staged
|
||||
|
||||
|
||||
def _inject_multipart_upload_payload(body: dict, uploads: list) -> None:
|
||||
"""
|
||||
将 multipart 附件写入 Turn input.payload。
|
||||
|
||||
- shipping.create_batch_from_notices:预检 notice_items
|
||||
- shipping.upload_inventory / shipping.replace_notice:staged 原始文件字节
|
||||
"""
|
||||
if not uploads:
|
||||
return
|
||||
input_block = body.get("input") if isinstance(body.get("input"), dict) else {}
|
||||
action_type = str(input_block.get("action_type") or input_block.get("actionType") or "").strip()
|
||||
payload = input_block.get("payload") if isinstance(input_block.get("payload"), dict) else {}
|
||||
payload = dict(payload)
|
||||
|
||||
if action_type == "shipping.create_batch_from_notices":
|
||||
from app.services.shipping_notice.batch_from_notices import intake_notice_uploads_for_batch
|
||||
from app.services.shipping_notice.notice_upload import cleanup_temp_notice_uploads
|
||||
|
||||
temp_request_id = uuid.uuid4().hex
|
||||
try:
|
||||
notice_items, file_summary = intake_notice_uploads_for_batch(temp_request_id, uploads)
|
||||
finally:
|
||||
cleanup_temp_notice_uploads(temp_request_id)
|
||||
if not notice_items:
|
||||
raise ValidationError(
|
||||
"未能从发货通知附件中抽取到可解析文本,请上传清晰版 PDF/文本后重试",
|
||||
details={"file_summary": file_summary},
|
||||
)
|
||||
payload["notice_items"] = notice_items
|
||||
payload["file_summary"] = file_summary
|
||||
conversation_id = str(body.get("conversation_id") or body.get("conversationId") or "").strip()
|
||||
if conversation_id:
|
||||
payload["conversation_id"] = conversation_id
|
||||
elif action_type in ("shipping.upload_inventory", "shipping.replace_notice"):
|
||||
staged = _stage_upload_files(uploads)
|
||||
if not staged:
|
||||
raise ValidationError("file is required")
|
||||
payload["_staged_files"] = staged
|
||||
else:
|
||||
return
|
||||
|
||||
input_block["payload"] = payload
|
||||
input_block["type"] = input_block.get("type") or "upload_followup"
|
||||
body["input"] = input_block
|
||||
|
||||
|
||||
def register_chat_turn_routes(chat_bp) -> None:
|
||||
"""将 Chat Turn 路由注册到 chat Blueprint。"""
|
||||
|
||||
@chat_bp.route('/turns/stream', methods=['POST'])
|
||||
@require_agent_permission
|
||||
def chat_turns_stream():
|
||||
"""
|
||||
统一 Chat Turn SSE 接口。
|
||||
|
||||
核心逻辑:解析 action/form_submit/upload_followup;multipart 时预检附件并注入 payload,
|
||||
经 ChatTurnRuntime 路由至 action handler,返回 run.started / step.* / message.* / run.completed。
|
||||
"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
if user is None or agent is None:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
|
||||
|
||||
body, uploads = _parse_turn_body_and_files()
|
||||
request_id = uuid.uuid4().hex[:12]
|
||||
# [STEP 1] multipart 附件必须在返回 SSE 前读完;生成器延迟执行时 request.files 可能已关闭。
|
||||
if uploads:
|
||||
_inject_multipart_upload_payload(body, uploads)
|
||||
|
||||
def relay_stream():
|
||||
yield from ChatTurnRuntime.stream(
|
||||
user=user,
|
||||
agent=agent,
|
||||
body=body,
|
||||
request_id=request_id,
|
||||
)
|
||||
|
||||
return Response(
|
||||
stream_with_context(relay_stream()),
|
||||
mimetype='text/event-stream',
|
||||
headers={
|
||||
'Cache-Control': 'no-cache',
|
||||
'Content-Type': 'text/event-stream; charset=utf-8',
|
||||
'Connection': 'keep-alive',
|
||||
'X-Accel-Buffering': 'no',
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,32 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.database import get_db
|
||||
from app.deps import accessible_department_ids, get_current_user
|
||||
from app.models import Department, Group, User
|
||||
from app.serializers import serialize_department
|
||||
|
||||
|
||||
router = APIRouter(prefix="/departments", tags=["departments"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_departments(db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
||||
department_ids = accessible_department_ids(db, user)
|
||||
group_counts = (
|
||||
db.query(Group.department_id.label("department_id"), func.count(Group.id).label("knowledge_base_count"))
|
||||
.group_by(Group.department_id)
|
||||
.subquery()
|
||||
)
|
||||
query = (
|
||||
db.query(Department, func.coalesce(group_counts.c.knowledge_base_count, 0).label("knowledge_base_count"))
|
||||
.outerjoin(group_counts, group_counts.c.department_id == Department.id)
|
||||
.order_by(Department.name.asc())
|
||||
)
|
||||
if department_ids is not None:
|
||||
query = query.filter(Department.id.in_(department_ids or [-1]))
|
||||
rows = query.all()
|
||||
return {"data": [serialize_department(item, knowledge_base_count=count) for item, count in rows]}
|
||||
@@ -1,562 +0,0 @@
|
||||
"""
|
||||
backend/app/api/file_check_tools.py
|
||||
|
||||
用途:文件检核 Chatflow 显式 HTTP Tool API。
|
||||
依赖:workspace_file_check、file_check_tools、schedule.scheduler_service。
|
||||
逻辑:Dify Chatflow 调用本蓝图发起检核、查询批次、下载 Excel。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from io import BytesIO
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
from sqlalchemy import text
|
||||
|
||||
from app import db
|
||||
from app.api.workspace_file_check import serialize_file_judgement
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
)
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.file_check_tools.openapi_spec import build_file_check_openapi_spec
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE, resolve_hxops_user_facing_base_url
|
||||
from app.services.schedule import _build_srm_conn_str
|
||||
from app.services.schedule.query_service import get_run, serialize_run
|
||||
from app.services.schedule.srm_service import _fetch_records
|
||||
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
|
||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
|
||||
|
||||
try:
|
||||
import pyodbc # type: ignore
|
||||
except Exception: # pragma: no cover
|
||||
pyodbc = None
|
||||
|
||||
|
||||
file_check_bp = Blueprint("file_check_tools", __name__)
|
||||
|
||||
_EXCEL_TOKEN_SCOPES = {"file_check_excel", "file_schedule_excel"}
|
||||
_RUN_START_LOCK = threading.Lock()
|
||||
_TASK_LOCK_KEY_BASE = 8700000000
|
||||
|
||||
|
||||
def _download_token_secret() -> str:
|
||||
"""
|
||||
Excel 下载 JWT 签名密钥。
|
||||
|
||||
核心逻辑:与 Dify Tool API Key 分离,仅用 SECRET_KEY,避免 API Key 未配置时浏览器下载失败。
|
||||
"""
|
||||
return str(current_app.config.get("SECRET_KEY") or "default-secret").strip()
|
||||
|
||||
|
||||
def _decode_download_token(token: str | None) -> dict | None:
|
||||
normalized = str(token or "").strip()
|
||||
if not normalized:
|
||||
return None
|
||||
try:
|
||||
import jwt
|
||||
|
||||
payload = jwt.decode(normalized, _download_token_secret(), algorithms=["HS256"])
|
||||
return payload if isinstance(payload, dict) else None
|
||||
except Exception as exc:
|
||||
current_app.logger.warning("[file-check-tool] download token validation failed: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验 Tool API 访问权限。
|
||||
|
||||
核心逻辑:Excel 下载仅校验 query token(浏览器场景);其余端点校验 Dify/RPA 的 Tool API Key。
|
||||
"""
|
||||
# [STEP 1] 浏览器 Excel 下载:JWT token 独立于 Tool API Key
|
||||
if request.path.endswith("/excel"):
|
||||
query_token = str(request.args.get("token") or "").strip()
|
||||
if query_token:
|
||||
if _decode_download_token(query_token):
|
||||
return
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
# [STEP 2] Dify / RPA 服务端调用
|
||||
configured = str(
|
||||
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
or ""
|
||||
).strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError(
|
||||
"FILE_CHECK_TOOL_API_KEY or INTEGRATION_API_KEY is not configured",
|
||||
code="missing_auth",
|
||||
)
|
||||
|
||||
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||
api_token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||
if configured in {api_token, integration_key}:
|
||||
return
|
||||
if not api_token and not integration_key:
|
||||
raise UnauthorizedError("missing_auth")
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
message = str(exc.message or "").strip()
|
||||
if message in {
|
||||
"missing_auth",
|
||||
"invalid_auth",
|
||||
"task_not_found",
|
||||
"run_not_found",
|
||||
"excel_not_ready",
|
||||
"kb_sync_failed",
|
||||
"query_required",
|
||||
"kb_not_configured",
|
||||
"kb_group_not_found",
|
||||
"kb_dataset_not_bound",
|
||||
"dify_retrieve_failed",
|
||||
}:
|
||||
return message
|
||||
if exc.code == "data_source_unavailable":
|
||||
return "data_source_unavailable"
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
return "missing_auth"
|
||||
if exc.code == "RESOURCE.NOT_FOUND":
|
||||
return message or "run_not_found"
|
||||
if exc.code == "VALIDATION.INVALID_PARAM":
|
||||
return message or "invalid_request"
|
||||
if exc.code == "RESOURCE.CONFLICT":
|
||||
return message or "conflict"
|
||||
return exc.code
|
||||
|
||||
|
||||
@file_check_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
status = exc.http_status
|
||||
return jsonify({
|
||||
"ok": False,
|
||||
"error_code": _tool_error_code(exc),
|
||||
"message": exc.message,
|
||||
}), status
|
||||
|
||||
|
||||
def _public_base_url() -> str:
|
||||
"""用户可见下载链基地址;与 Dify 调 Tool API 的内网基地址分离。"""
|
||||
return resolve_hxops_user_facing_base_url()
|
||||
|
||||
|
||||
def _acquire_task_start_lock(task_id: int) -> None:
|
||||
"""按 schedule_task_id 串行化同任务启动检核(PostgreSQL advisory lock)。"""
|
||||
bind = db.session.get_bind()
|
||||
if bind.dialect.name != "postgresql":
|
||||
return
|
||||
lock_key = _TASK_LOCK_KEY_BASE + int(task_id)
|
||||
db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": lock_key})
|
||||
|
||||
|
||||
def _build_excel_download_url(run: ScheduleRun) -> str:
|
||||
import jwt
|
||||
|
||||
payload = {
|
||||
"scope": "file_check_excel",
|
||||
"run_id": run.id,
|
||||
"exp": int(time.time()) + 600,
|
||||
}
|
||||
token = jwt.encode(payload, _download_token_secret(), algorithm="HS256")
|
||||
return f"{_public_base_url()}/api/file-check/tools/runs/{run.id}/excel?token={token}"
|
||||
|
||||
|
||||
@file_check_bp.before_request
|
||||
def _verify_tool_access():
|
||||
if request.path.endswith("/openapi.json"):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
def _serialize_tool_run(run: ScheduleRun) -> dict:
|
||||
payload = serialize_run(run)
|
||||
return {
|
||||
"run_id": payload["id"],
|
||||
"run_no": payload["run_no"],
|
||||
"task_id": payload["schedule_task_id"],
|
||||
"task_name": payload.get("schedule_name"),
|
||||
"status": payload["status"],
|
||||
"total_count": payload["total_count"],
|
||||
"success_count": payload["success_count"],
|
||||
"failed_count": payload["failed_count"],
|
||||
"skipped_count": payload["skipped_count"],
|
||||
"judgement": serialize_file_judgement(payload),
|
||||
"started_at": payload.get("started_at"),
|
||||
"finished_at": payload.get("finished_at"),
|
||||
"duration_ms": payload.get("duration_ms"),
|
||||
"error_message": payload.get("error_message"),
|
||||
"excel": {
|
||||
"file_name": payload.get("excel_file_name"),
|
||||
"file_size": payload.get("excel_file_size"),
|
||||
"download_url": _build_excel_download_url(run) if payload.get("excel_file_name") else None,
|
||||
},
|
||||
"knowledge_base": {
|
||||
"enabled": bool(getattr(run.task, "kb_sync_enabled", False)) if run.task else bool(payload.get("kb_group_id")),
|
||||
"sync_status": payload.get("kb_sync_status"),
|
||||
"group_id": payload.get("kb_group_id"),
|
||||
"document_id": payload.get("kb_document_id"),
|
||||
"document_version_id": payload.get("kb_document_version_id"),
|
||||
"sync_job_id": payload.get("kb_sync_job_id"),
|
||||
"error_message": payload.get("kb_sync_error"),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _resolve_check_task(data: dict | None = None, *, task_id: int | None = None) -> ScheduleTask:
|
||||
data = data or {}
|
||||
raw_task_id = task_id if task_id is not None else data.get("task_id")
|
||||
if raw_task_id in (None, "", 0, "0") and not str(data.get("task_no") or "").strip():
|
||||
raise ValidationError("task_id_required")
|
||||
try:
|
||||
normalized_task_id = int(raw_task_id) if raw_task_id not in (None, "", 0, "0") else None
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError("task_id_invalid")
|
||||
task = db.session.get(ScheduleTask, normalized_task_id) if normalized_task_id is not None else None
|
||||
if not task:
|
||||
task_no = str(data.get("task_no") or "").strip()
|
||||
if task_no:
|
||||
task = ScheduleTask.query.filter_by(schedule_no=task_no).first()
|
||||
if not task:
|
||||
raise NotFoundError("task_not_found")
|
||||
return task
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/tasks", methods=["GET"])
|
||||
def list_file_check_tasks():
|
||||
"""
|
||||
查询指定检核任务摘要;须传 task_id(Agent 绑定的 schedule_task_id),不再返回全量任务列表。
|
||||
"""
|
||||
raw_task_id = request.args.get("task_id", type=int)
|
||||
if raw_task_id is None:
|
||||
raise ValidationError("task_id_required")
|
||||
task = _resolve_check_task(task_id=raw_task_id)
|
||||
latest = (
|
||||
ScheduleRun.query.filter_by(schedule_task_id=task.id)
|
||||
.order_by(ScheduleRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
tasks = [{
|
||||
"task_id": task.id,
|
||||
"task_no": task.schedule_no,
|
||||
"name": task.name,
|
||||
"enabled": bool(task.enabled),
|
||||
"last_status": latest.status if latest else None,
|
||||
"last_run_at": task.last_run_at.isoformat() if task.last_run_at else None,
|
||||
"next_run_at": task.next_run_at.isoformat() if task.next_run_at else None,
|
||||
}]
|
||||
return jsonify({"ok": True, "tasks": tasks})
|
||||
|
||||
|
||||
def _normalize_bind_payload(data: dict | None) -> dict:
|
||||
"""规范化启动检核 Body;兼容 Chatflow 漏传 hxops_session_id。"""
|
||||
payload = dict(data or {})
|
||||
session_id = str(payload.get("hxops_session_id") or "").strip()
|
||||
if session_id:
|
||||
return payload
|
||||
conversation_id = str(payload.get("conversation_id") or "").strip()
|
||||
if not conversation_id:
|
||||
return payload
|
||||
from app.models import ChatSession
|
||||
|
||||
session = ChatSession.query.filter_by(session_id=conversation_id).first()
|
||||
if session:
|
||||
payload["hxops_session_id"] = conversation_id
|
||||
return payload
|
||||
|
||||
|
||||
def _prepare_bind_payload(data: dict | None) -> dict:
|
||||
from app.services.file_check_tools.chat_turn_registry import infer_bind_context_for_run_request
|
||||
|
||||
payload = _normalize_bind_payload(data)
|
||||
inferred = infer_bind_context_for_run_request(payload)
|
||||
if inferred:
|
||||
payload = {**payload, **inferred}
|
||||
return payload
|
||||
|
||||
|
||||
def _record_run_bind(run: ScheduleRun, data: dict) -> None:
|
||||
from app.services.file_check_tools.chat_log_run_binding import merge_chat_log_bind_context
|
||||
from app.services.file_check_tools.chat_tool_run_binding import (
|
||||
_has_ambiguous_pending_turns,
|
||||
bind_schedule_run,
|
||||
)
|
||||
from app.services.file_check_tools.chat_turn_registry import attach_run_to_turn
|
||||
|
||||
turn_id = str(data.get("hxops_turn_id") or "").strip()
|
||||
session_id = str(data.get("hxops_session_id") or "").strip() or None
|
||||
user_message = str(data.get("user_message") or "").strip() or None
|
||||
bound = bind_schedule_run(
|
||||
schedule_run_id=int(run.id),
|
||||
turn_id=turn_id or None,
|
||||
session_id=session_id,
|
||||
user_message=user_message,
|
||||
schedule_task_id=int(run.schedule_task_id) if run.schedule_task_id else None,
|
||||
bind_source='tool_start',
|
||||
)
|
||||
ambiguous = _has_ambiguous_pending_turns(
|
||||
session_id=session_id,
|
||||
user_message=user_message,
|
||||
schedule_task_id=int(run.schedule_task_id) if run.schedule_task_id else None,
|
||||
)
|
||||
if bound or (not ambiguous and (turn_id or session_id)):
|
||||
merge_chat_log_bind_context(run, data)
|
||||
if bound and turn_id:
|
||||
attach_run_to_turn(turn_id, int(run.id))
|
||||
|
||||
|
||||
def _build_no_data_response(task: ScheduleTask) -> dict:
|
||||
"""无待检资料时直接返回提示,不创建批次也不绑定 run_id。"""
|
||||
return {
|
||||
"ok": False,
|
||||
"error_code": "no_data_to_check",
|
||||
"message": "目前没有资料需要检核",
|
||||
"task": {
|
||||
"task_id": task.id,
|
||||
"task_name": task.name,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _raise_data_source_unavailable(task: ScheduleTask, exc: Exception) -> None:
|
||||
"""
|
||||
将检核预检阶段的数据源连接/配置错误转为 Tool API 503。
|
||||
|
||||
核心逻辑:ODBC/SQL Server 不可用时返回 data_source_unavailable,避免 Dify 收到 500 后显示 maximum retries。
|
||||
"""
|
||||
current_app.logger.warning(
|
||||
"[file-check-tool] precheck data source unavailable task_id=%s error=%s",
|
||||
task.id,
|
||||
exc,
|
||||
exc_info=True,
|
||||
)
|
||||
raise ServiceUnavailableError(
|
||||
"检核数据源不可用,请检查排程 SQL 配置、SRM_SQLSERVER_* 环境变量及本机 ODBC 驱动",
|
||||
code="data_source_unavailable",
|
||||
) from exc
|
||||
|
||||
|
||||
def _precheck_no_data(task: ScheduleTask) -> dict | None:
|
||||
"""
|
||||
启动前预检当前任务是否存在待检资料。
|
||||
|
||||
核心逻辑:仅在数据库型检核任务上做轻量预检;若结果为空,则直接返回 no_data_to_check,
|
||||
避免创建空批次并向 ChatLog 回写 run_id。数据源连接失败时抛 503 data_source_unavailable。
|
||||
"""
|
||||
if str(getattr(task, "data_source_type", "") or "database").lower() != "database":
|
||||
return None
|
||||
|
||||
cfg = get_schedule_sql_config_by_task_id(task.id)
|
||||
if not cfg or not str(cfg.fetch_sql or "").strip():
|
||||
return None
|
||||
|
||||
try:
|
||||
if cfg.data_source and not cfg.data_source.is_empty():
|
||||
conn_str = cfg.data_source.build_connection_string()
|
||||
else:
|
||||
conn_str = _build_srm_conn_str()
|
||||
rows = _fetch_records(conn_str, cfg.fetch_sql)
|
||||
except RuntimeError as exc:
|
||||
_raise_data_source_unavailable(task, exc)
|
||||
except Exception as exc:
|
||||
if pyodbc is not None and isinstance(exc, pyodbc.Error):
|
||||
_raise_data_source_unavailable(task, exc)
|
||||
raise
|
||||
|
||||
if rows:
|
||||
return None
|
||||
return _build_no_data_response(task)
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/tasks/run", methods=["POST"])
|
||||
def run_file_check():
|
||||
"""立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。"""
|
||||
perf_started = time.perf_counter()
|
||||
data = _prepare_bind_payload(request.get_json(silent=True) or {})
|
||||
task = _resolve_check_task(data)
|
||||
resolve_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
|
||||
lock_started = time.perf_counter()
|
||||
with _RUN_START_LOCK:
|
||||
_acquire_task_start_lock(task.id)
|
||||
existing = (
|
||||
ScheduleRun.query.filter_by(schedule_task_id=task.id, status="running")
|
||||
.order_by(ScheduleRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
if existing:
|
||||
_record_run_bind(existing, data)
|
||||
db.session.commit()
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
current_app.logger.info(
|
||||
"[file-check-tool-perf] run_file_check outcome=check_running resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
existing.id,
|
||||
)
|
||||
return jsonify({
|
||||
"ok": False,
|
||||
"error_code": "check_running",
|
||||
"message": "该检核任务正在执行中,请稍后查询结果",
|
||||
"run": _serialize_tool_run(existing),
|
||||
})
|
||||
|
||||
no_data_response = _precheck_no_data(task)
|
||||
if no_data_response:
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
current_app.logger.info(
|
||||
"[file-check-tool-perf] run_file_check outcome=no_data resolve_ms=%s lock_ms=%s total_ms=%s task_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
task.id,
|
||||
)
|
||||
return jsonify(no_data_response)
|
||||
|
||||
run = ScheduleRun(
|
||||
run_no=_generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
trigger_type="dify_chatflow",
|
||||
started_at=datetime.utcnow(),
|
||||
status="running",
|
||||
api_request_json={
|
||||
"trigger_source": data.get("trigger_source") or "dify_chatflow",
|
||||
"conversation_id": data.get("conversation_id"),
|
||||
},
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
_record_run_bind(run, data)
|
||||
db.session.commit()
|
||||
app = current_app._get_current_object()
|
||||
run_id = run.id
|
||||
task_id = task.id
|
||||
|
||||
def _background():
|
||||
with app.app_context():
|
||||
t = db.session.get(ScheduleTask, task_id)
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if not t or not r:
|
||||
return
|
||||
try:
|
||||
run_task_now(t, trigger_type="dify_chatflow", triggered_by_user_id=None, run=r)
|
||||
except Exception as exc:
|
||||
current_app.logger.error("[file-check-tool] run_id=%s failed: %s", run_id, exc, exc_info=True)
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if r and r.status == "running":
|
||||
r.status = "failed"
|
||||
r.error_message = str(exc)
|
||||
r.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
threading.Thread(target=_background, daemon=True, name=f"file-check-run-{run_id}").start()
|
||||
db.session.refresh(run)
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
current_app.logger.info(
|
||||
"[file-check-tool-perf] run_file_check outcome=started resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
run_id,
|
||||
)
|
||||
return jsonify({"ok": True, "message": "检核已启动", "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/runs/<int:run_id>", methods=["GET"])
|
||||
def get_file_check_run(run_id: int):
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/runs", methods=["GET"])
|
||||
def list_file_check_runs():
|
||||
raw_task_id = request.args.get("task_id", type=int)
|
||||
raw_limit = request.args.get("limit", default=20, type=int)
|
||||
limit = max(1, min(int(raw_limit or 20), 100))
|
||||
if raw_task_id is not None:
|
||||
task = _resolve_check_task(task_id=raw_task_id)
|
||||
query = ScheduleRun.query.filter_by(schedule_task_id=task.id)
|
||||
else:
|
||||
query = ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
|
||||
rows = query.order_by(ScheduleRun.created_at.desc()).limit(limit).all()
|
||||
runs = [_serialize_tool_run(row) for row in rows]
|
||||
return jsonify({"ok": True, "runs": runs, "count": len(runs)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/runs/<int:run_id>/excel", methods=["GET"])
|
||||
def download_file_check_run_excel(run_id: int):
|
||||
token_payload = _decode_download_token(request.args.get("token"))
|
||||
if token_payload:
|
||||
if token_payload.get("scope") not in _EXCEL_TOKEN_SCOPES or int(token_payload.get("run_id") or 0) != run_id:
|
||||
raise UnauthorizedError("Unauthorized")
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
if not run.excel_file_data:
|
||||
raise ConflictError("excel_not_ready")
|
||||
filename = run.excel_file_name or f"{run.run_no}.xlsx"
|
||||
return send_file(
|
||||
BytesIO(run.excel_file_data),
|
||||
as_attachment=True,
|
||||
download_name=filename,
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/tasks/<int:task_id>/latest-run", methods=["GET"])
|
||||
def get_latest_file_check_run(task_id: int):
|
||||
task = _resolve_check_task(task_id=task_id)
|
||||
run = ScheduleRun.query.filter_by(schedule_task_id=task.id).order_by(ScheduleRun.id.desc()).first()
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/history/search", methods=["POST"])
|
||||
def search_file_check_history():
|
||||
"""
|
||||
检索已入库的历史检核报告片段;按 task_id 解析 ScheduleTask → KbGroup → Dify Dataset。
|
||||
|
||||
核心逻辑:Chatflow history_report_query 分支调用;task_id 来自 HXOPS 注入的 Start 变量。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
raw_task_id = data.get("task_id")
|
||||
try:
|
||||
task_id = int(raw_task_id)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError("task_id_invalid")
|
||||
if task_id <= 0:
|
||||
raise ValidationError("task_id_invalid")
|
||||
|
||||
from app.services.file_check_tools.history_search_service import search_file_check_history as run_history_search
|
||||
|
||||
result = run_history_search(
|
||||
task_id=task_id,
|
||||
query=str(data.get("query") or ""),
|
||||
top_k=data.get("top_k"),
|
||||
score_threshold=data.get("score_threshold"),
|
||||
)
|
||||
return jsonify({"ok": True, **result})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def file_check_openapi_spec():
|
||||
return jsonify(build_file_check_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
|
||||
@@ -0,0 +1,490 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
import uuid
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, UploadFile
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from app.config import get_settings
|
||||
from app.database import get_db
|
||||
from app.deps import accessible_group_ids, ensure_group_access, get_current_user
|
||||
from app.models import Document, DocumentVersion, DifySyncRecord, Group, Job, User
|
||||
from app.schemas import BatchDownloadRequest, BatchSyncRequest
|
||||
from app.serializers import current_version, serialize_document, serialize_job, serialize_version
|
||||
from app.services.queue_service import get_queue
|
||||
from app.services.storage_service import build_zip, remove_path_if_exists, sha256_file, version_dir
|
||||
|
||||
|
||||
router = APIRouter(prefix="/files", tags=["files"])
|
||||
settings = get_settings()
|
||||
MAX_BATCH_UPLOAD_FILES = 500
|
||||
|
||||
|
||||
def _group_scope_filter(db: Session, user: User):
|
||||
group_ids = accessible_group_ids(db, user)
|
||||
return None if group_ids is None else (group_ids or [-1])
|
||||
|
||||
|
||||
def _get_document_for_user(db: Session, user: User, file_id: int) -> Document | None:
|
||||
query = (
|
||||
db.query(Document)
|
||||
.options(joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
|
||||
.filter(Document.id == file_id, Document.is_deleted.is_(False))
|
||||
)
|
||||
group_ids = _group_scope_filter(db, user)
|
||||
if group_ids is not None:
|
||||
query = query.filter(Document.group_id.in_(group_ids))
|
||||
return query.first()
|
||||
|
||||
|
||||
def _create_job(
|
||||
db: Session,
|
||||
*,
|
||||
job_type: str,
|
||||
created_by_id: int,
|
||||
group_id: int,
|
||||
document_id: int,
|
||||
version_id: int,
|
||||
payload: dict | None = None,
|
||||
) -> Job:
|
||||
job = Job(
|
||||
id=str(uuid.uuid4()),
|
||||
job_type=job_type,
|
||||
status="queued",
|
||||
group_id=group_id,
|
||||
document_id=document_id,
|
||||
version_id=version_id,
|
||||
created_by_id=created_by_id,
|
||||
payload=payload or {},
|
||||
)
|
||||
db.add(job)
|
||||
db.commit()
|
||||
db.refresh(job)
|
||||
return job
|
||||
|
||||
|
||||
def _enqueue(job: Job, task_name: str, version_id: int, db: Session) -> Job:
|
||||
return _enqueue_args(job, task_name, db, version_id)
|
||||
|
||||
|
||||
def _enqueue_args(job: Job, task_name: str, db: Session, *task_args) -> Job:
|
||||
queue = get_queue()
|
||||
rq_job = queue.enqueue(task_name, job.id, *task_args)
|
||||
job.queue_job_id = rq_job.id
|
||||
db.commit()
|
||||
db.refresh(job)
|
||||
return job
|
||||
|
||||
|
||||
def _resolve_storage_target(path_value: str | None, *, parent: bool = False) -> Path | None:
|
||||
if not path_value:
|
||||
return None
|
||||
raw_target = Path(path_value)
|
||||
data_root = settings.data_root.resolve(strict=False)
|
||||
if raw_target.is_absolute():
|
||||
target = raw_target
|
||||
else:
|
||||
resolved_raw = raw_target.resolve(strict=False)
|
||||
target = resolved_raw if resolved_raw.is_relative_to(data_root) else settings.data_root / raw_target
|
||||
if parent:
|
||||
target = target.parent
|
||||
resolved = target.resolve(strict=False)
|
||||
if not resolved.is_relative_to(data_root):
|
||||
return None
|
||||
return resolved
|
||||
|
||||
|
||||
def _cleanup_document_storage(document: Document) -> None:
|
||||
targets: set[Path] = set()
|
||||
for version in document.versions:
|
||||
for candidate in (
|
||||
_resolve_storage_target(version.source_path, parent=True),
|
||||
_resolve_storage_target(version.md_path, parent=True),
|
||||
_resolve_storage_target(version.asset_dir),
|
||||
):
|
||||
if candidate is not None:
|
||||
targets.add(candidate)
|
||||
|
||||
for target in sorted(targets, key=lambda item: len(item.parts), reverse=True):
|
||||
remove_path_if_exists(target)
|
||||
|
||||
|
||||
@router.post("/upload")
|
||||
async def upload_files(
|
||||
group_id: int = Form(...),
|
||||
files: list[UploadFile] = File(default_factory=list),
|
||||
file: UploadFile | None = File(None),
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
ensure_group_access(db, user, group_id)
|
||||
group = db.query(Group).filter(Group.id == group_id).first()
|
||||
if not group:
|
||||
raise HTTPException(status_code=404, detail="Group not found.")
|
||||
|
||||
incoming = list(files)
|
||||
if file is not None:
|
||||
incoming.append(file)
|
||||
if not incoming:
|
||||
raise HTTPException(status_code=400, detail="No files uploaded.")
|
||||
if len(incoming) > MAX_BATCH_UPLOAD_FILES:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Batch upload accepts at most {MAX_BATCH_UPLOAD_FILES} files at a time.",
|
||||
)
|
||||
|
||||
created: list[dict] = []
|
||||
duplicates: list[dict] = []
|
||||
|
||||
for upload in incoming:
|
||||
tmp_dir = settings.data_root / "tmp" / "uploads"
|
||||
tmp_dir.mkdir(parents=True, exist_ok=True)
|
||||
tmp_path = tmp_dir / f"{uuid.uuid4()}_{Path(upload.filename).name}"
|
||||
with tmp_path.open("wb") as handle:
|
||||
while True:
|
||||
chunk = await upload.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
handle.write(chunk)
|
||||
digest = sha256_file(tmp_path)
|
||||
ext = Path(upload.filename).suffix.lower()
|
||||
title = Path(upload.filename).stem
|
||||
|
||||
duplicate_version = (
|
||||
db.query(DocumentVersion)
|
||||
.join(Document, Document.id == DocumentVersion.document_id)
|
||||
.filter(
|
||||
Document.group_id == group.id,
|
||||
Document.is_deleted.is_(False),
|
||||
DocumentVersion.source_sha256 == digest,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if duplicate_version:
|
||||
duplicates.append(
|
||||
{
|
||||
"filename": upload.filename,
|
||||
"document_id": duplicate_version.document_id,
|
||||
"version_id": duplicate_version.id,
|
||||
"reason": "same_sha256_in_group",
|
||||
}
|
||||
)
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
continue
|
||||
|
||||
document = (
|
||||
db.query(Document)
|
||||
.options(joinedload(Document.versions))
|
||||
.filter(
|
||||
Document.group_id == group.id,
|
||||
func.lower(Document.title) == title.lower(),
|
||||
Document.is_deleted.is_(False),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if document is None:
|
||||
document = Document(group_id=group.id, title=title, created_by_id=user.id, is_deleted=False)
|
||||
db.add(document)
|
||||
db.commit()
|
||||
db.refresh(document)
|
||||
version_no = 1
|
||||
else:
|
||||
for item in document.versions:
|
||||
if item.is_current:
|
||||
item.is_current = False
|
||||
db.commit()
|
||||
version_no = (document.versions[0].version_no + 1) if document.versions else 1
|
||||
|
||||
sync_status = "unsynced"
|
||||
prior_sync = (
|
||||
db.query(DifySyncRecord)
|
||||
.join(DocumentVersion, DifySyncRecord.version_id == DocumentVersion.id)
|
||||
.filter(DocumentVersion.document_id == document.id, DifySyncRecord.status == "synced")
|
||||
.first()
|
||||
)
|
||||
if prior_sync:
|
||||
sync_status = "stale"
|
||||
|
||||
source_dir = version_dir("original", group.id, document.id, version_no)
|
||||
source_dir.mkdir(parents=True, exist_ok=True)
|
||||
final_source = source_dir / Path(upload.filename).name
|
||||
shutil.move(str(tmp_path), str(final_source))
|
||||
|
||||
version = DocumentVersion(
|
||||
document_id=document.id,
|
||||
version_no=version_no,
|
||||
is_current=True,
|
||||
source_filename=Path(upload.filename).name,
|
||||
source_ext=ext,
|
||||
source_path=str(final_source),
|
||||
source_sha256=digest,
|
||||
file_size=final_source.stat().st_size,
|
||||
uploader_id=user.id,
|
||||
convert_status="queued",
|
||||
sync_status=sync_status,
|
||||
)
|
||||
db.add(version)
|
||||
db.commit()
|
||||
db.refresh(version)
|
||||
|
||||
job = _create_job(
|
||||
db,
|
||||
job_type="convert",
|
||||
created_by_id=user.id,
|
||||
group_id=group.id,
|
||||
document_id=document.id,
|
||||
version_id=version.id,
|
||||
payload={"filename": upload.filename},
|
||||
)
|
||||
_enqueue(job, "app.tasks.run_convert_job", version.id, db)
|
||||
created.append(
|
||||
{
|
||||
"document_id": document.id,
|
||||
"version_id": version.id,
|
||||
"job": serialize_job(job),
|
||||
}
|
||||
)
|
||||
|
||||
return {"created": created, "duplicates": duplicates}
|
||||
|
||||
|
||||
@router.get("/group/{group_id}")
|
||||
def list_group_files(
|
||||
group_id: int,
|
||||
q: str | None = None,
|
||||
status: str | None = None,
|
||||
sync_status: str | None = None,
|
||||
file_type: str | None = None,
|
||||
uploaded_from: str | None = None,
|
||||
uploaded_to: str | None = None,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
ensure_group_access(db, user, group_id)
|
||||
query = (
|
||||
db.query(Document)
|
||||
.options(joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
|
||||
.filter(Document.group_id == group_id, Document.is_deleted.is_(False))
|
||||
.order_by(Document.updated_at.desc())
|
||||
)
|
||||
documents = query.all()
|
||||
filtered: list[Document] = []
|
||||
uploaded_from_date = date.fromisoformat(uploaded_from) if uploaded_from else None
|
||||
uploaded_to_date = date.fromisoformat(uploaded_to) if uploaded_to else None
|
||||
for document in documents:
|
||||
version = current_version(document)
|
||||
if version is None:
|
||||
continue
|
||||
version_uploaded_at = version.uploaded_at.date() if version.uploaded_at else None
|
||||
if q and q.lower() not in document.title.lower():
|
||||
continue
|
||||
if status and version.convert_status != status:
|
||||
continue
|
||||
if sync_status and version.sync_status != sync_status:
|
||||
continue
|
||||
if file_type and version.source_ext != file_type:
|
||||
continue
|
||||
if uploaded_from_date and (version_uploaded_at is None or version_uploaded_at < uploaded_from_date):
|
||||
continue
|
||||
if uploaded_to_date and (version_uploaded_at is None or version_uploaded_at > uploaded_to_date):
|
||||
continue
|
||||
filtered.append(document)
|
||||
return {"data": [serialize_document(document) for document in filtered]}
|
||||
|
||||
|
||||
@router.get("/{file_id}")
|
||||
def get_file(file_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
||||
document = _get_document_for_user(db, user, file_id)
|
||||
if not document:
|
||||
raise HTTPException(status_code=404, detail="Document not found.")
|
||||
payload = serialize_document(document)
|
||||
payload["versions"] = [serialize_version(item) for item in document.versions]
|
||||
return payload
|
||||
|
||||
|
||||
@router.get("/{file_id}/download")
|
||||
def download_file(
|
||||
file_id: int,
|
||||
kind: str = Query("md"),
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
document = _get_document_for_user(db, user, file_id)
|
||||
if not document:
|
||||
raise HTTPException(status_code=404, detail="Document not found.")
|
||||
version = current_version(document)
|
||||
if not version:
|
||||
raise HTTPException(status_code=404, detail="No version found.")
|
||||
|
||||
if kind == "source":
|
||||
path = Path(version.source_path)
|
||||
filename = version.source_filename
|
||||
else:
|
||||
if not version.md_path:
|
||||
raise HTTPException(status_code=409, detail="Markdown not ready.")
|
||||
path = Path(version.md_path)
|
||||
filename = f"{document.title}.md"
|
||||
if not path.exists():
|
||||
raise HTTPException(status_code=404, detail="File missing on disk.")
|
||||
return FileResponse(path, filename=filename)
|
||||
|
||||
|
||||
@router.post("/download-batch")
|
||||
def batch_download(
|
||||
payload: BatchDownloadRequest,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
query = (
|
||||
db.query(Document)
|
||||
.options(joinedload(Document.versions))
|
||||
.filter(Document.id.in_(payload.document_ids), Document.is_deleted.is_(False))
|
||||
)
|
||||
group_ids = _group_scope_filter(db, user)
|
||||
if group_ids is not None:
|
||||
query = query.filter(Document.group_id.in_(group_ids))
|
||||
documents = query.all()
|
||||
if not documents:
|
||||
raise HTTPException(status_code=404, detail="No documents found.")
|
||||
bundle_id = str(uuid.uuid4())
|
||||
bundle_dir = settings.data_root / "tmp" / "downloads"
|
||||
bundle_path = bundle_dir / f"download_{bundle_id}.zip"
|
||||
entries: list[tuple[Path, str]] = []
|
||||
for document in documents:
|
||||
version = current_version(document)
|
||||
if not version:
|
||||
continue
|
||||
if payload.kind == "source":
|
||||
entries.append((Path(version.source_path), version.source_filename))
|
||||
else:
|
||||
if version.md_path:
|
||||
entries.append((Path(version.md_path), f"{document.title}.md"))
|
||||
if not entries:
|
||||
raise HTTPException(status_code=409, detail="No downloadable files available.")
|
||||
build_zip(entries, bundle_path)
|
||||
download_date = date.today().strftime("%Y%m%d")
|
||||
return FileResponse(bundle_path, filename=f"文件下载_{download_date}.zip")
|
||||
|
||||
|
||||
@router.post("/{file_id}/retry-convert")
|
||||
def retry_convert(file_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
||||
document = _get_document_for_user(db, user, file_id)
|
||||
if not document:
|
||||
raise HTTPException(status_code=404, detail="Document not found.")
|
||||
version = current_version(document)
|
||||
if not version:
|
||||
raise HTTPException(status_code=404, detail="Version not found.")
|
||||
job = _create_job(
|
||||
db,
|
||||
job_type="convert",
|
||||
created_by_id=user.id,
|
||||
group_id=document.group_id,
|
||||
document_id=document.id,
|
||||
version_id=version.id,
|
||||
payload={"retry": True},
|
||||
)
|
||||
_enqueue(job, "app.tasks.run_convert_job", version.id, db)
|
||||
return serialize_job(job)
|
||||
|
||||
|
||||
@router.post("/{file_id}/sync-dify")
|
||||
def sync_dify(file_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
||||
document = _get_document_for_user(db, user, file_id)
|
||||
if not document:
|
||||
raise HTTPException(status_code=404, detail="Document not found.")
|
||||
version = current_version(document)
|
||||
if not version or version.convert_status != "success":
|
||||
raise HTTPException(status_code=409, detail="Document is not ready for sync.")
|
||||
if version.sync_status == "synced":
|
||||
raise HTTPException(status_code=409, detail="Current version is already synced to Dify.")
|
||||
if version.sync_status == "syncing":
|
||||
raise HTTPException(status_code=409, detail="Current version is already syncing to Dify.")
|
||||
version.sync_status = "syncing"
|
||||
db.commit()
|
||||
job = _create_job(
|
||||
db,
|
||||
job_type="sync",
|
||||
created_by_id=user.id,
|
||||
group_id=document.group_id,
|
||||
document_id=document.id,
|
||||
version_id=version.id,
|
||||
payload={"single": True},
|
||||
)
|
||||
_enqueue(job, "app.tasks.run_sync_job", version.id, db)
|
||||
return serialize_job(job)
|
||||
|
||||
|
||||
@router.post("/sync-dify-batch")
|
||||
def batch_sync(
|
||||
payload: BatchSyncRequest,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
query = db.query(Document).options(joinedload(Document.versions)).filter(Document.id.in_(payload.document_ids))
|
||||
group_ids = _group_scope_filter(db, user)
|
||||
if group_ids is not None:
|
||||
query = query.filter(Document.group_id.in_(group_ids))
|
||||
documents = query.all()
|
||||
jobs: list[dict] = []
|
||||
for document in documents:
|
||||
if document.is_deleted:
|
||||
continue
|
||||
version = current_version(document)
|
||||
if not version or version.convert_status != "success":
|
||||
continue
|
||||
if version.sync_status in {"synced", "syncing"}:
|
||||
continue
|
||||
version.sync_status = "syncing"
|
||||
db.commit()
|
||||
job = _create_job(
|
||||
db,
|
||||
job_type="sync",
|
||||
created_by_id=user.id,
|
||||
group_id=document.group_id,
|
||||
document_id=document.id,
|
||||
version_id=version.id,
|
||||
payload={"batch": True},
|
||||
)
|
||||
_enqueue(job, "app.tasks.run_sync_job", version.id, db)
|
||||
jobs.append(serialize_job(job))
|
||||
return {"data": jobs}
|
||||
|
||||
|
||||
@router.delete("/{file_id}")
|
||||
def delete_file(
|
||||
file_id: int,
|
||||
delete_dify: bool = Query(False),
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
document = _get_document_for_user(db, user, file_id)
|
||||
if not document:
|
||||
raise HTTPException(status_code=404, detail="Document not found.")
|
||||
|
||||
version = current_version(document)
|
||||
original_title = document.title
|
||||
document.is_deleted = True
|
||||
document.title = f"{document.title}__deleted__{document.id}"
|
||||
db.commit()
|
||||
try:
|
||||
job = _create_job(
|
||||
db,
|
||||
job_type="delete",
|
||||
created_by_id=user.id,
|
||||
group_id=document.group_id,
|
||||
document_id=document.id,
|
||||
version_id=version.id if version else None,
|
||||
payload={"delete_dify": delete_dify},
|
||||
)
|
||||
_enqueue_args(job, "app.tasks.run_delete_document_job", db, document.id)
|
||||
except Exception:
|
||||
document.is_deleted = False
|
||||
document.title = original_title
|
||||
db.commit()
|
||||
raise
|
||||
return {"deleted": True}
|
||||
@@ -1,11 +0,0 @@
|
||||
"""
|
||||
backend/app/api/files/__init__.py
|
||||
|
||||
用途:平台级文件资产 API 包入口。
|
||||
依赖:files.assets。
|
||||
逻辑:register_blueprints 挂载 /api/files。
|
||||
"""
|
||||
|
||||
from app.api.files.assets import files_bp
|
||||
|
||||
__all__ = ['files_bp']
|
||||
@@ -1,80 +0,0 @@
|
||||
"""
|
||||
backend/app/api/files/assets.py
|
||||
|
||||
用途:通用文件资产上传、查询、删除与受控下载 API。
|
||||
依赖:file_assets.service、app.core.auth.jwt、app.core.response。
|
||||
逻辑:薄路由鉴权与参数校验;storage_key 不向前端返回。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
|
||||
from flask import Blueprint, g, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError
|
||||
from app.core.response import ok
|
||||
from app.services.file_assets.service import (
|
||||
delete_temporary_asset,
|
||||
get_asset_for_user,
|
||||
read_asset_bytes,
|
||||
serialize_asset_public,
|
||||
upload_file_asset,
|
||||
)
|
||||
|
||||
files_bp = Blueprint('files', __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
@files_bp.route('/assets', methods=['POST'])
|
||||
def upload_asset():
|
||||
"""上传文件并创建 FileAsset。"""
|
||||
user = _require_user()
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
raise ValidationError('file is required')
|
||||
if not upload.filename:
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
raise ValidationError('file is required')
|
||||
data = upload_file_asset(user_id=user.id, upload=upload)
|
||||
return ok(data, request_id=getattr(g, 'request_id', None), status=201)
|
||||
|
||||
|
||||
@files_bp.route('/assets/<asset_no>', methods=['GET'])
|
||||
def get_asset(asset_no: str):
|
||||
"""查询当前用户的文件资产元数据。"""
|
||||
user = _require_user()
|
||||
asset = get_asset_for_user(asset_no, user.id)
|
||||
return ok(serialize_asset_public(asset), request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@files_bp.route('/assets/<asset_no>', methods=['DELETE'])
|
||||
def delete_asset(asset_no: str):
|
||||
"""逻辑删除未引用的临时资产。"""
|
||||
user = _require_user()
|
||||
delete_temporary_asset(asset_no=asset_no, user_id=user.id)
|
||||
return ok({'deleted': True}, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@files_bp.route('/assets/<asset_no>/download', methods=['GET'])
|
||||
def download_asset(asset_no: str):
|
||||
"""鉴权后流式下载文件内容。"""
|
||||
user = _require_user()
|
||||
asset = get_asset_for_user(asset_no, user.id)
|
||||
data = read_asset_bytes(asset)
|
||||
return send_file(
|
||||
io.BytesIO(data),
|
||||
mimetype=asset.mime_type or 'application/octet-stream',
|
||||
as_attachment=True,
|
||||
download_name=asset.original_filename,
|
||||
)
|
||||
@@ -0,0 +1,757 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy import func, or_
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from app.config import get_settings
|
||||
from app.database import get_db
|
||||
from app.deps import (
|
||||
accessible_department_ids,
|
||||
accessible_group_ids,
|
||||
ensure_department_access,
|
||||
ensure_group_access,
|
||||
get_current_user,
|
||||
require_admin,
|
||||
)
|
||||
from app.models import Department, DifySyncRecord, Document, DocumentVersion, Group, Job, SystemSetting, User
|
||||
from app.schemas import DifyImportRequest, GroupCreateRequest, GroupUpdateRequest
|
||||
from app.serializers import current_version, serialize_document, serialize_group
|
||||
from app.services.dify_service import DifyError, DifyService
|
||||
from app.services.storage_service import public_storage_url, remove_path_if_exists, sha256_file, version_dir
|
||||
from app.time_utils import utc_now
|
||||
import requests
|
||||
|
||||
|
||||
router = APIRouter(prefix="/groups", tags=["groups"])
|
||||
settings = get_settings()
|
||||
|
||||
|
||||
def _scoped_group_ids(db: Session, user: User) -> list[int] | None:
|
||||
return accessible_group_ids(db, user)
|
||||
|
||||
|
||||
def _scoped_department_ids(db: Session, user: User) -> list[int] | None:
|
||||
return accessible_department_ids(db, user)
|
||||
|
||||
|
||||
def _scoped_groups_query(db: Session, user: User, *, department_id: int | None = None):
|
||||
query = db.query(Group)
|
||||
group_ids = _scoped_group_ids(db, user)
|
||||
if group_ids is not None:
|
||||
query = query.filter(Group.id.in_(group_ids or [-1]))
|
||||
if department_id is not None:
|
||||
query = query.filter(Group.department_id == department_id)
|
||||
return query
|
||||
|
||||
|
||||
def _document_name_key(name: str) -> str:
|
||||
trimmed = (name or "").strip().lower()
|
||||
candidate = Path(trimmed)
|
||||
return candidate.stem if candidate.suffix else trimmed
|
||||
|
||||
|
||||
def _normalized_document_title(name: str) -> str:
|
||||
candidate = Path((name or "").strip())
|
||||
return candidate.stem if candidate.suffix else candidate.name
|
||||
|
||||
|
||||
def _resolve_storage_target(path_value: str | None, *, parent: bool = False) -> Path | None:
|
||||
if not path_value:
|
||||
return None
|
||||
raw_target = Path(path_value)
|
||||
data_root = settings.data_root.resolve(strict=False)
|
||||
if raw_target.is_absolute():
|
||||
target = raw_target
|
||||
else:
|
||||
resolved_raw = raw_target.resolve(strict=False)
|
||||
target = resolved_raw if resolved_raw.is_relative_to(data_root) else settings.data_root / raw_target
|
||||
if parent:
|
||||
target = target.parent
|
||||
resolved = target.resolve(strict=False)
|
||||
if not resolved.is_relative_to(data_root):
|
||||
return None
|
||||
return resolved
|
||||
|
||||
|
||||
def _cleanup_document_storage(document: Document) -> None:
|
||||
targets: set[Path] = set()
|
||||
for version in document.versions:
|
||||
for candidate in (
|
||||
_resolve_storage_target(version.source_path, parent=True),
|
||||
_resolve_storage_target(version.md_path, parent=True),
|
||||
_resolve_storage_target(version.asset_dir),
|
||||
):
|
||||
if candidate is not None:
|
||||
targets.add(candidate)
|
||||
|
||||
for target in sorted(targets, key=lambda item: len(item.parts), reverse=True):
|
||||
remove_path_if_exists(target)
|
||||
|
||||
|
||||
def _local_documents_for_group(group: Group) -> dict[str, list[dict]]:
|
||||
local_docs: dict[str, list[dict]] = {}
|
||||
for document in group.documents:
|
||||
if document.is_deleted:
|
||||
continue
|
||||
version = current_version(document)
|
||||
if version is None:
|
||||
continue
|
||||
local_docs.setdefault(_document_name_key(document.title), []).append(
|
||||
{
|
||||
"document_id": document.id,
|
||||
"title": document.title,
|
||||
"source_ext": version.source_ext,
|
||||
"convert_status": version.convert_status,
|
||||
"sync_status": version.sync_status,
|
||||
"remote_document_id": version.sync_records[0].remote_document_id if version.sync_records else None,
|
||||
}
|
||||
)
|
||||
return local_docs
|
||||
|
||||
|
||||
def _remote_documents_for_dataset(dify: DifyService, dataset_id: str | None) -> dict[str, list[dict]]:
|
||||
if not dataset_id:
|
||||
return {}
|
||||
remote_docs: dict[str, list[dict]] = {}
|
||||
for remote in dify.list_documents(dataset_id=dataset_id):
|
||||
remote_docs.setdefault(_document_name_key(remote.name), []).append(
|
||||
{
|
||||
"document_id": remote.id,
|
||||
"name": remote.name,
|
||||
"indexing_status": remote.indexing_status,
|
||||
"display_status": remote.display_status,
|
||||
"enabled": remote.enabled,
|
||||
}
|
||||
)
|
||||
return remote_docs
|
||||
|
||||
|
||||
def _diff_status(local_entry: dict | None, remote_entry: dict | None) -> str:
|
||||
if local_entry and not remote_entry:
|
||||
return "local_only"
|
||||
if remote_entry and not local_entry:
|
||||
return "dify_only"
|
||||
if (
|
||||
(local_entry or {}).get("sync_status") != "synced"
|
||||
or (remote_entry or {}).get("indexing_status") not in {"completed", "completed_with_warning"}
|
||||
):
|
||||
return "attention"
|
||||
return "matched"
|
||||
|
||||
|
||||
def _build_diff_rows(
|
||||
*,
|
||||
knowledge_base_name: str,
|
||||
dataset_id: str | None,
|
||||
local_docs: dict[str, list[dict]],
|
||||
remote_docs: dict[str, list[dict]],
|
||||
group: Group | None = None,
|
||||
term: str = "",
|
||||
include_knowledge_base: bool = False,
|
||||
) -> list[dict]:
|
||||
rows: list[dict] = []
|
||||
for key in sorted(set(local_docs) | set(remote_docs)):
|
||||
local_entries = list(local_docs.get(key, []))
|
||||
remote_entries = list(remote_docs.get(key, []))
|
||||
|
||||
local_entries.sort(
|
||||
key=lambda item: (
|
||||
f"{item.get('title') or ''}{item.get('source_ext') or ''}".lower(),
|
||||
int(item.get("document_id") or 0),
|
||||
)
|
||||
)
|
||||
remote_entries.sort(
|
||||
key=lambda item: (
|
||||
(item.get("name") or "").lower(),
|
||||
str(item.get("document_id") or ""),
|
||||
)
|
||||
)
|
||||
|
||||
paired_rows: list[tuple[dict | None, dict | None]] = []
|
||||
remaining_remote = remote_entries.copy()
|
||||
|
||||
for local_entry in local_entries:
|
||||
local_full_name = f"{local_entry.get('title') or ''}{local_entry.get('source_ext') or ''}".lower()
|
||||
match_index = next(
|
||||
(
|
||||
index
|
||||
for index, remote_entry in enumerate(remaining_remote)
|
||||
if (remote_entry.get("name") or "").strip().lower() == local_full_name
|
||||
),
|
||||
None,
|
||||
)
|
||||
if match_index is None and remaining_remote:
|
||||
match_index = 0
|
||||
|
||||
if match_index is None:
|
||||
paired_rows.append((local_entry, None))
|
||||
else:
|
||||
paired_rows.append((local_entry, remaining_remote.pop(match_index)))
|
||||
|
||||
paired_rows.extend((None, remote_entry) for remote_entry in remaining_remote)
|
||||
|
||||
for index, (local_entry, remote_entry) in enumerate(paired_rows, start=1):
|
||||
display_name = (local_entry or {}).get("title") or (remote_entry or {}).get("name") or key
|
||||
haystacks = [display_name.lower(), knowledge_base_name.lower()]
|
||||
if term and not any(term in item for item in haystacks):
|
||||
continue
|
||||
|
||||
row = {
|
||||
"key": f"{knowledge_base_name}:{key}:{index}" if include_knowledge_base else f"{key}:{index}",
|
||||
"status": _diff_status(local_entry, remote_entry),
|
||||
"local": local_entry,
|
||||
"remote": remote_entry,
|
||||
"display_name": display_name,
|
||||
}
|
||||
if include_knowledge_base:
|
||||
row["knowledge_base"] = {
|
||||
"group_id": group.id if group else None,
|
||||
"name": knowledge_base_name,
|
||||
"dataset_id": dataset_id,
|
||||
}
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
def _summarize_diff_rows(rows: list[dict]) -> dict[str, int]:
|
||||
return {
|
||||
"matched": sum(1 for row in rows if row["status"] == "matched"),
|
||||
"local_only": sum(1 for row in rows if row["status"] == "local_only"),
|
||||
"dify_only": sum(1 for row in rows if row["status"] == "dify_only"),
|
||||
"attention": sum(1 for row in rows if row["status"] == "attention"),
|
||||
}
|
||||
|
||||
|
||||
def _create_group_from_remote_name(*, db: Session, admin: User, group_name: str) -> Group:
|
||||
if admin.primary_department_id is None:
|
||||
raise HTTPException(status_code=400, detail="Admin must belong to a department before importing Dify documents.")
|
||||
return _create_group_from_remote_name_in_department(
|
||||
db=db,
|
||||
admin=admin,
|
||||
group_name=group_name,
|
||||
department_id=admin.primary_department_id,
|
||||
)
|
||||
|
||||
|
||||
def _create_group_from_remote_name_in_department(
|
||||
*,
|
||||
db: Session,
|
||||
admin: User,
|
||||
group_name: str,
|
||||
department_id: int,
|
||||
) -> Group:
|
||||
defaults = db.query(SystemSetting).filter(SystemSetting.id == 1).first()
|
||||
existing = (
|
||||
db.query(Group)
|
||||
.filter(Group.department_id == department_id, Group.name == group_name)
|
||||
.first()
|
||||
)
|
||||
if existing:
|
||||
return existing
|
||||
group = Group(
|
||||
name=group_name,
|
||||
description=None,
|
||||
department_id=department_id,
|
||||
created_by_id=admin.id,
|
||||
indexing_technique=defaults.indexing_technique if defaults else "high_quality",
|
||||
search_method=defaults.search_method if defaults else "hybrid_search",
|
||||
doc_form=defaults.doc_form if defaults else "text_model",
|
||||
top_k=defaults.top_k if defaults else 5,
|
||||
score_threshold_enabled=defaults.score_threshold_enabled if defaults else True,
|
||||
score_threshold=defaults.score_threshold if defaults else "0.35",
|
||||
)
|
||||
db.add(group)
|
||||
db.commit()
|
||||
db.refresh(group)
|
||||
return group
|
||||
|
||||
|
||||
def _download_remote_upload(upload_file: dict | None) -> tuple[str, bytes] | None:
|
||||
if not upload_file:
|
||||
return None
|
||||
download_url = upload_file.get("download_url") or upload_file.get("url")
|
||||
if not download_url:
|
||||
return None
|
||||
response = requests.get(download_url, timeout=60)
|
||||
response.raise_for_status()
|
||||
filename = upload_file.get("name") or "remote-file"
|
||||
return filename, response.content
|
||||
|
||||
|
||||
def _import_dify_document_to_local(
|
||||
*,
|
||||
db: Session,
|
||||
user: User,
|
||||
dataset_id: str,
|
||||
remote_document_id: str,
|
||||
group: Group,
|
||||
) -> Document:
|
||||
dify = DifyService()
|
||||
detail = dify.get_document_detail(dataset_id=dataset_id, document_id=remote_document_id)
|
||||
remote_name = (detail.get("name") or "").strip() or remote_document_id
|
||||
title = _normalized_document_title(remote_name)
|
||||
|
||||
existing = (
|
||||
db.query(Document)
|
||||
.options(joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
|
||||
.filter(
|
||||
Document.group_id == group.id,
|
||||
func.lower(Document.title) == title.lower(),
|
||||
Document.is_deleted.is_(False),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if existing:
|
||||
raise HTTPException(status_code=409, detail="Document already exists locally. Refresh diff and retry.")
|
||||
|
||||
segments = dify.list_document_segments(dataset_id=dataset_id, document_id=remote_document_id)
|
||||
markdown_text = "\n\n".join(item.content.strip() for item in segments if item.content and item.content.strip()).strip()
|
||||
if not markdown_text:
|
||||
raise HTTPException(status_code=409, detail="Remote Dify document has no importable content.")
|
||||
|
||||
document = Document(group_id=group.id, title=title, created_by_id=user.id, is_deleted=False)
|
||||
db.add(document)
|
||||
db.commit()
|
||||
db.refresh(document)
|
||||
|
||||
version_no = 1
|
||||
source_dir = version_dir("original", group.id, document.id, version_no)
|
||||
markdown_dir = version_dir("markdown", group.id, document.id, version_no)
|
||||
source_dir.mkdir(parents=True, exist_ok=True)
|
||||
markdown_dir.mkdir(parents=True, exist_ok=True)
|
||||
markdown_target = markdown_dir / "document.md"
|
||||
markdown_target.write_text(markdown_text, encoding="utf-8")
|
||||
|
||||
source_filename = remote_name if Path(remote_name).suffix else f"{remote_name}.md"
|
||||
source_ext = Path(source_filename).suffix.lower() or ".md"
|
||||
source_target = source_dir / source_filename
|
||||
|
||||
upload_file = None
|
||||
try:
|
||||
upload_file = dify.get_upload_file(dataset_id=dataset_id, document_id=remote_document_id)
|
||||
except DifyError:
|
||||
upload_file = None
|
||||
|
||||
downloaded = None
|
||||
if upload_file:
|
||||
try:
|
||||
downloaded = _download_remote_upload(upload_file)
|
||||
except Exception:
|
||||
downloaded = None
|
||||
|
||||
if downloaded:
|
||||
source_filename, source_bytes = downloaded
|
||||
source_ext = Path(source_filename).suffix.lower() or ".bin"
|
||||
source_target = source_dir / source_filename
|
||||
source_target.write_bytes(source_bytes)
|
||||
else:
|
||||
source_target.write_text(markdown_text, encoding="utf-8")
|
||||
source_filename = source_target.name
|
||||
source_ext = ".md"
|
||||
|
||||
version = DocumentVersion(
|
||||
document_id=document.id,
|
||||
version_no=version_no,
|
||||
is_current=True,
|
||||
source_filename=source_filename,
|
||||
source_ext=source_ext,
|
||||
source_path=str(source_target),
|
||||
source_sha256=sha256_file(source_target),
|
||||
md_path=str(markdown_target),
|
||||
md_public_url=public_storage_url(markdown_target),
|
||||
asset_dir=None,
|
||||
file_size=source_target.stat().st_size,
|
||||
word_count=len(markdown_text.split()),
|
||||
convert_status="success",
|
||||
sync_status="synced",
|
||||
uploader_id=user.id,
|
||||
uploaded_at=utc_now(),
|
||||
converted_at=utc_now(),
|
||||
warnings_json=[{"message": "imported_from_dify"}],
|
||||
)
|
||||
db.add(version)
|
||||
db.commit()
|
||||
db.refresh(version)
|
||||
|
||||
sync_record = DifySyncRecord(
|
||||
version_id=version.id,
|
||||
dataset_id=dataset_id,
|
||||
remote_document_id=remote_document_id,
|
||||
status="synced",
|
||||
last_indexing_status=detail.get("indexing_status"),
|
||||
last_synced_at=utc_now(),
|
||||
error=None,
|
||||
)
|
||||
db.add(sync_record)
|
||||
if group.dify_dataset_id != dataset_id:
|
||||
group.dify_dataset_id = dataset_id
|
||||
db.commit()
|
||||
db.refresh(document)
|
||||
return document
|
||||
|
||||
|
||||
def _group_name_conflict(
|
||||
db: Session,
|
||||
*,
|
||||
department_id: int | None,
|
||||
name: str,
|
||||
exclude_group_id: int | None = None,
|
||||
) -> bool:
|
||||
query = db.query(Group).filter(Group.department_id == department_id, Group.name == name)
|
||||
if exclude_group_id is not None:
|
||||
query = query.filter(Group.id != exclude_group_id)
|
||||
return db.query(query.exists()).scalar()
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_groups(
|
||||
department_id: int | None = Query(None),
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
if department_id is not None:
|
||||
ensure_department_access(db, user, department_id)
|
||||
group_ids = _scoped_group_ids(db, user)
|
||||
document_counts_query = (
|
||||
db.query(
|
||||
Document.group_id.label("group_id"),
|
||||
func.count(Document.id).label("document_count"),
|
||||
)
|
||||
.filter(Document.is_deleted.is_(False))
|
||||
.group_by(Document.group_id)
|
||||
)
|
||||
if group_ids is not None:
|
||||
document_counts_query = document_counts_query.filter(Document.group_id.in_(group_ids or [-1]))
|
||||
document_counts = document_counts_query.subquery()
|
||||
query = db.query(
|
||||
Group,
|
||||
func.coalesce(document_counts.c.document_count, 0).label("document_count"),
|
||||
).options(joinedload(Group.department)).outerjoin(document_counts, document_counts.c.group_id == Group.id)
|
||||
if group_ids is not None:
|
||||
query = query.filter(Group.id.in_(group_ids or [-1]))
|
||||
if department_id is not None:
|
||||
query = query.filter(Group.department_id == department_id)
|
||||
groups = query.order_by(Group.name.asc()).all()
|
||||
return {
|
||||
"data": [serialize_group(group, document_count=document_count) for group, document_count in groups]
|
||||
}
|
||||
|
||||
|
||||
@router.get("/summary")
|
||||
def get_dashboard_summary(
|
||||
department_id: int | None = Query(None),
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
if department_id is not None:
|
||||
ensure_department_access(db, user, department_id)
|
||||
group_ids = _scoped_group_ids(db, user)
|
||||
knowledge_base_query = db.query(Group)
|
||||
file_query = db.query(Document).filter(Document.is_deleted.is_(False))
|
||||
if group_ids is not None:
|
||||
scoped_filter = group_ids or [-1]
|
||||
knowledge_base_query = knowledge_base_query.filter(Group.id.in_(scoped_filter))
|
||||
file_query = file_query.filter(Document.group_id.in_(scoped_filter))
|
||||
if department_id is not None:
|
||||
knowledge_base_query = knowledge_base_query.filter(Group.department_id == department_id)
|
||||
file_query = file_query.join(Group, Group.id == Document.group_id).filter(Group.department_id == department_id)
|
||||
knowledge_base_count = knowledge_base_query.count()
|
||||
file_count = file_query.count()
|
||||
running_query = (
|
||||
db.query(DocumentVersion)
|
||||
.join(Document, Document.id == DocumentVersion.document_id)
|
||||
.filter(Document.is_deleted.is_(False), DocumentVersion.is_current.is_(True))
|
||||
.filter(
|
||||
or_(
|
||||
DocumentVersion.convert_status.in_(["queued", "running"]),
|
||||
DocumentVersion.sync_status == "syncing",
|
||||
)
|
||||
)
|
||||
)
|
||||
if group_ids is not None:
|
||||
running_query = running_query.filter(Document.group_id.in_(group_ids or [-1]))
|
||||
if department_id is not None:
|
||||
running_query = running_query.join(Group, Group.id == Document.group_id).filter(Group.department_id == department_id)
|
||||
running_count = running_query.count()
|
||||
return {
|
||||
"knowledge_base_count": knowledge_base_count,
|
||||
"file_count": file_count,
|
||||
"running_count": running_count,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/dify-diff-global")
|
||||
def get_global_dify_diff(
|
||||
q: str | None = Query(None),
|
||||
department_id: int | None = Query(None),
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
if department_id is not None:
|
||||
ensure_department_access(db, user, department_id)
|
||||
groups_query = (
|
||||
db.query(Group)
|
||||
.options(joinedload(Group.department))
|
||||
.options(joinedload(Group.documents).joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
|
||||
)
|
||||
group_ids = _scoped_group_ids(db, user)
|
||||
if group_ids is not None:
|
||||
groups_query = groups_query.filter(Group.id.in_(group_ids or [-1]))
|
||||
if department_id is not None:
|
||||
groups_query = groups_query.filter(Group.department_id == department_id)
|
||||
groups = groups_query.order_by(Group.name.asc()).all()
|
||||
dify = DifyService()
|
||||
datasets = dify.list_datasets()
|
||||
datasets_by_id = {item.id: item for item in datasets}
|
||||
datasets_by_name = {item.name: item for item in datasets}
|
||||
used_dataset_ids: set[str] = set()
|
||||
term = (q or "").strip().lower()
|
||||
rows: list[dict] = []
|
||||
|
||||
for group in groups:
|
||||
dataset = datasets_by_id.get(group.dify_dataset_id or "") or datasets_by_name.get(group.name)
|
||||
dataset_id = dataset.id if dataset else group.dify_dataset_id
|
||||
if dataset:
|
||||
used_dataset_ids.add(dataset.id)
|
||||
rows.extend(
|
||||
_build_diff_rows(
|
||||
knowledge_base_name=group.name,
|
||||
dataset_id=dataset_id,
|
||||
local_docs=_local_documents_for_group(group),
|
||||
remote_docs=_remote_documents_for_dataset(dify, dataset.id if dataset else group.dify_dataset_id),
|
||||
group=group,
|
||||
term=term,
|
||||
include_knowledge_base=True,
|
||||
)
|
||||
)
|
||||
|
||||
return {"summary": _summarize_diff_rows(rows), "rows": rows}
|
||||
|
||||
|
||||
@router.post("/import-dify-document")
|
||||
def import_dify_document(
|
||||
payload: DifyImportRequest,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
target_group: Group | None = None
|
||||
if payload.group_id is not None:
|
||||
ensure_group_access(db, user, payload.group_id)
|
||||
target_group = db.query(Group).filter(Group.id == payload.group_id).first()
|
||||
if not target_group:
|
||||
raise HTTPException(status_code=404, detail="Knowledge base not found.")
|
||||
else:
|
||||
if user.role not in {"admin", "super_admin"}:
|
||||
raise HTTPException(status_code=403, detail="Admin permission required.")
|
||||
knowledge_base_name = (payload.knowledge_base_name or "").strip()
|
||||
if not knowledge_base_name:
|
||||
raise HTTPException(status_code=400, detail="Knowledge base name is required for Dify import.")
|
||||
department_id = payload.department_id or user.primary_department_id
|
||||
if department_id is None:
|
||||
raise HTTPException(status_code=400, detail="Department is required for Dify import.")
|
||||
ensure_department_access(db, user, department_id)
|
||||
target_group = _create_group_from_remote_name_in_department(
|
||||
db=db,
|
||||
admin=user,
|
||||
group_name=knowledge_base_name,
|
||||
department_id=department_id,
|
||||
)
|
||||
|
||||
document = _import_dify_document_to_local(
|
||||
db=db,
|
||||
user=user,
|
||||
dataset_id=payload.dataset_id,
|
||||
remote_document_id=payload.remote_document_id,
|
||||
group=target_group,
|
||||
)
|
||||
return {
|
||||
"group_id": target_group.id,
|
||||
"group_name": target_group.name,
|
||||
"document": serialize_document(document),
|
||||
}
|
||||
|
||||
|
||||
@router.post("")
|
||||
def create_group(
|
||||
payload: GroupCreateRequest,
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_admin),
|
||||
):
|
||||
ensure_department_access(db, admin, payload.department_id)
|
||||
if _group_name_conflict(db, department_id=payload.department_id, name=payload.name):
|
||||
raise HTTPException(status_code=409, detail="Group already exists.")
|
||||
defaults = db.query(SystemSetting).filter(SystemSetting.id == 1).first()
|
||||
group = Group(
|
||||
name=payload.name,
|
||||
description=payload.description,
|
||||
department_id=payload.department_id,
|
||||
created_by_id=admin.id,
|
||||
indexing_technique=defaults.indexing_technique if defaults else "high_quality",
|
||||
search_method=defaults.search_method if defaults else "hybrid_search",
|
||||
doc_form=defaults.doc_form if defaults else "text_model",
|
||||
top_k=defaults.top_k if defaults else 5,
|
||||
score_threshold_enabled=defaults.score_threshold_enabled if defaults else True,
|
||||
score_threshold=defaults.score_threshold if defaults else "0.35",
|
||||
)
|
||||
db.add(group)
|
||||
db.commit()
|
||||
db.refresh(group)
|
||||
return serialize_group(group)
|
||||
|
||||
|
||||
@router.patch("/{group_id}")
|
||||
def update_group(
|
||||
group_id: int,
|
||||
payload: GroupUpdateRequest,
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_admin),
|
||||
):
|
||||
ensure_group_access(db, admin, group_id)
|
||||
group = db.query(Group).filter(Group.id == group_id).first()
|
||||
if not group:
|
||||
raise HTTPException(status_code=404, detail="Group not found.")
|
||||
old_name = group.name
|
||||
target_name = payload.name or group.name
|
||||
target_department_id = payload.department_id if payload.department_id is not None else group.department_id
|
||||
if payload.department_id is not None and payload.department_id != group.department_id:
|
||||
ensure_department_access(db, admin, payload.department_id)
|
||||
if payload.name or payload.department_id is not None:
|
||||
if _group_name_conflict(
|
||||
db,
|
||||
department_id=target_department_id,
|
||||
name=target_name,
|
||||
exclude_group_id=group.id,
|
||||
):
|
||||
raise HTTPException(status_code=409, detail="Group already exists.")
|
||||
if payload.name:
|
||||
group.name = payload.name
|
||||
if payload.description is not None:
|
||||
group.description = payload.description
|
||||
if payload.department_id is not None and payload.department_id != group.department_id:
|
||||
group.department_id = payload.department_id
|
||||
db.commit()
|
||||
if payload.rename_dify and group.dify_dataset_id and payload.name and payload.name != old_name:
|
||||
dify = DifyService()
|
||||
dify.update_dataset(dataset_id=group.dify_dataset_id, name=payload.name)
|
||||
db.refresh(group)
|
||||
return serialize_group(group)
|
||||
|
||||
|
||||
@router.delete("/{group_id}")
|
||||
def delete_group(
|
||||
group_id: int,
|
||||
delete_dify: bool = Query(False),
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_admin),
|
||||
):
|
||||
ensure_group_access(db, admin, group_id)
|
||||
group = (
|
||||
db.query(Group)
|
||||
.options(joinedload(Group.department))
|
||||
.options(joinedload(Group.documents).joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
|
||||
.filter(Group.id == group_id)
|
||||
.first()
|
||||
)
|
||||
if not group:
|
||||
raise HTTPException(status_code=404, detail="Group not found.")
|
||||
|
||||
running_job = (
|
||||
db.query(Job)
|
||||
.filter(Job.group_id == group.id, Job.status.in_(["queued", "running"]))
|
||||
.first()
|
||||
)
|
||||
if running_job:
|
||||
raise HTTPException(status_code=409, detail="Group has running jobs and cannot be deleted.")
|
||||
|
||||
if delete_dify and group.dify_dataset_id:
|
||||
dify = DifyService()
|
||||
dify.delete_dataset(dataset_id=group.dify_dataset_id)
|
||||
|
||||
for document in group.documents:
|
||||
_cleanup_document_storage(document)
|
||||
|
||||
db.query(Job).filter(Job.group_id == group.id).delete(synchronize_session=False)
|
||||
for document in list(group.documents):
|
||||
db.delete(document)
|
||||
db.delete(group)
|
||||
db.commit()
|
||||
return {"deleted": True}
|
||||
|
||||
|
||||
@router.get("/{group_id}/files")
|
||||
def list_group_files(
|
||||
group_id: int,
|
||||
q: str | None = Query(None),
|
||||
status: str | None = Query(None),
|
||||
sync_status: str | None = Query(None),
|
||||
file_type: str | None = Query(None),
|
||||
uploaded_from: str | None = Query(None),
|
||||
uploaded_to: str | None = Query(None),
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
ensure_group_access(db, user, group_id)
|
||||
query = (
|
||||
db.query(Document)
|
||||
.options(joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
|
||||
.filter(Document.group_id == group_id, Document.is_deleted.is_(False))
|
||||
.order_by(Document.updated_at.desc())
|
||||
)
|
||||
documents = query.all()
|
||||
filtered: list[Document] = []
|
||||
uploaded_from_date = date.fromisoformat(uploaded_from) if uploaded_from else None
|
||||
uploaded_to_date = date.fromisoformat(uploaded_to) if uploaded_to else None
|
||||
for document in documents:
|
||||
version = current_version(document)
|
||||
if version is None:
|
||||
continue
|
||||
version_uploaded_at = version.uploaded_at.date() if version.uploaded_at else None
|
||||
if q and q.lower() not in document.title.lower():
|
||||
continue
|
||||
if status and version.convert_status != status:
|
||||
continue
|
||||
if sync_status and version.sync_status != sync_status:
|
||||
continue
|
||||
if file_type and version.source_ext != file_type:
|
||||
continue
|
||||
if uploaded_from_date and (version_uploaded_at is None or version_uploaded_at < uploaded_from_date):
|
||||
continue
|
||||
if uploaded_to_date and (version_uploaded_at is None or version_uploaded_at > uploaded_to_date):
|
||||
continue
|
||||
filtered.append(document)
|
||||
return {"data": [serialize_document(document) for document in filtered]}
|
||||
|
||||
|
||||
@router.get("/{group_id}/dify-diff")
|
||||
def get_group_dify_diff(
|
||||
group_id: int,
|
||||
q: str | None = Query(None),
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
ensure_group_access(db, user, group_id)
|
||||
group = (
|
||||
db.query(Group)
|
||||
.options(joinedload(Group.department))
|
||||
.options(joinedload(Group.documents).joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
|
||||
.filter(Group.id == group_id)
|
||||
.first()
|
||||
)
|
||||
if not group:
|
||||
raise HTTPException(status_code=404, detail="Group not found.")
|
||||
|
||||
term = (q or "").strip().lower()
|
||||
dify = DifyService() if group.dify_dataset_id else None
|
||||
rows = _build_diff_rows(
|
||||
knowledge_base_name=group.name,
|
||||
dataset_id=group.dify_dataset_id,
|
||||
local_docs=_local_documents_for_group(group),
|
||||
remote_docs=_remote_documents_for_dataset(dify, group.dify_dataset_id) if dify else {},
|
||||
group=group,
|
||||
term=term,
|
||||
)
|
||||
return {"group": serialize_group(group), "summary": _summarize_diff_rows(rows), "rows": rows}
|
||||
+341
-275
@@ -1,312 +1,378 @@
|
||||
"""
|
||||
backend/app/api/integration.py
|
||||
文件用途:知识库外部集成查询接口
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from flask import Blueprint, abort, current_app, jsonify, request, send_file
|
||||
|
||||
from pydantic import BaseModel
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import joinedload
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
raise_for_status,
|
||||
)
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
integration_bp = Blueprint('integration', __name__)
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from app.config import get_settings
|
||||
from app.database import get_db
|
||||
from app.deps import require_integration_key
|
||||
from app.models import DifySyncRecord, Document, DocumentVersion, Group
|
||||
from app.security import create_integration_download_token, decode_integration_download_token
|
||||
from app.serializers import current_version, serialize_group
|
||||
from app.time_utils import utc_now
|
||||
|
||||
|
||||
def _integration_token_secret() -> str:
|
||||
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
|
||||
return configured or str(current_app.config.get('SECRET_KEY') or 'default-secret').strip()
|
||||
router = APIRouter(prefix="/integration", tags=["integration"])
|
||||
settings = get_settings()
|
||||
|
||||
|
||||
def _decode_integration_token(token: str | None) -> dict | None:
|
||||
normalized_token = str(token or '').strip()
|
||||
if not normalized_token:
|
||||
return None
|
||||
try:
|
||||
import jwt
|
||||
payload = jwt.decode(
|
||||
normalized_token,
|
||||
_integration_token_secret(),
|
||||
algorithms=['HS256'],
|
||||
)
|
||||
return payload if isinstance(payload, dict) else None
|
||||
except Exception as e:
|
||||
current_app.logger.warning(f"Integration API token validation failed: {e}")
|
||||
return None
|
||||
class DifyResolveItem(BaseModel):
|
||||
remote_document_id: str
|
||||
dataset_id: str | None = None
|
||||
|
||||
|
||||
def _build_download_url(document_id: int, *, kind: str, version_id: int | None = None) -> str:
|
||||
base_url = _integration_base_url()
|
||||
url = f'{base_url}/api/integration/files/{document_id}/download?kind={kind}'
|
||||
if version_id is not None:
|
||||
url += f'&version_id={version_id}'
|
||||
return url
|
||||
class DifyResolveRequest(BaseModel):
|
||||
items: list[DifyResolveItem]
|
||||
|
||||
|
||||
def _version_query():
|
||||
def _document_query(db: Session):
|
||||
return (
|
||||
db.session.query(KbDocumentVersion)
|
||||
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
|
||||
.filter(KbDocument.is_deleted.is_(False))
|
||||
db.query(Document)
|
||||
.options(
|
||||
joinedload(Document.group).joinedload(Group.department),
|
||||
joinedload(Document.versions).joinedload(DocumentVersion.sync_records),
|
||||
)
|
||||
.filter(Document.is_deleted.is_(False))
|
||||
)
|
||||
|
||||
|
||||
def _resolve_requested_version(file_id: int) -> tuple[KbDocumentVersion | None, KbDocument | None]:
|
||||
requested_version_id = request.args.get('version_id', type=int)
|
||||
token_payload = _decode_integration_token(request.args.get('token'))
|
||||
if isinstance(token_payload, dict):
|
||||
token_version_id = token_payload.get('version_id')
|
||||
if token_version_id is not None:
|
||||
try:
|
||||
requested_version_id = int(token_version_id)
|
||||
except (TypeError, ValueError):
|
||||
current_app.logger.warning(
|
||||
'Integration API token carried invalid version_id: %r',
|
||||
token_version_id,
|
||||
)
|
||||
dataset_id = str(token_payload.get('dataset_id') or '').strip()
|
||||
remote_document_id = str(token_payload.get('remote_document_id') or '').strip()
|
||||
if dataset_id and remote_document_id:
|
||||
record = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
|
||||
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
|
||||
.options(joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.document))
|
||||
.filter(
|
||||
KbDocument.is_deleted.is_(False),
|
||||
KbDocument.id == file_id,
|
||||
KbDifySyncRecord.dataset_id == dataset_id,
|
||||
KbDifySyncRecord.remote_document_id == remote_document_id,
|
||||
)
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
.first()
|
||||
)
|
||||
if record and record.document_version and record.document_version.document:
|
||||
return record.document_version, record.document_version.document
|
||||
|
||||
if requested_version_id is not None:
|
||||
version = (
|
||||
_version_query()
|
||||
.filter(
|
||||
KbDocumentVersion.id == requested_version_id,
|
||||
KbDocumentVersion.document_id == file_id,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if version:
|
||||
return version, version.document
|
||||
|
||||
document = _document_query().filter(KbDocument.id == file_id).first()
|
||||
if not document:
|
||||
return None, None
|
||||
return _current_version(document), document
|
||||
|
||||
def _require_integration_key():
|
||||
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
|
||||
incoming = str(request.headers.get('X-Integration-Key') or '').strip()
|
||||
|
||||
if not configured:
|
||||
|
||||
raise ServiceUnavailableError('INTEGRATION_API_KEY is not configured')
|
||||
|
||||
if configured == incoming:
|
||||
return None
|
||||
|
||||
token = request.args.get('token')
|
||||
if token and _decode_integration_token(token):
|
||||
return None
|
||||
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
|
||||
|
||||
def _integration_base_url() -> str:
|
||||
request_origin = IntegrationApiService._request_origin_url()
|
||||
if request_origin:
|
||||
return request_origin
|
||||
explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/')
|
||||
if explicit:
|
||||
return explicit
|
||||
return request.host_url.rstrip('/')
|
||||
|
||||
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 _resolve_storage_path(path_value: str | None) -> Path | None:
|
||||
if not path_value:
|
||||
return None
|
||||
raw_path = Path(str(path_value))
|
||||
candidate = (raw_path if raw_path.is_absolute() else (_kb_storage_root() / raw_path)).resolve()
|
||||
root = _kb_storage_root()
|
||||
try:
|
||||
candidate.relative_to(root)
|
||||
except ValueError:
|
||||
return None
|
||||
return candidate
|
||||
|
||||
def _current_version(document: KbDocument) -> KbDocumentVersion | None:
|
||||
versions = list(getattr(document, 'versions', []) or [])
|
||||
if not versions:
|
||||
return None
|
||||
return next((item for item in versions if item.is_current), versions[0])
|
||||
|
||||
def _document_query():
|
||||
return db.session.query(KbDocument).options(joinedload(KbDocument.group), joinedload(KbDocument.versions).joinedload(KbDocumentVersion.sync_records)).filter(KbDocument.is_deleted.is_(False))
|
||||
|
||||
def _serialize_integration_document(document: KbDocument, *, version: KbDocumentVersion | None=None, sync_record: KbDifySyncRecord | None=None):
|
||||
version = version or _current_version(document)
|
||||
if not version:
|
||||
abort(404, description='No current version found.')
|
||||
sync_record = sync_record or (next((item for item in getattr(version, 'sync_records', []) if item.status == 'synced'), None) or (version.sync_records[0] if getattr(version, 'sync_records', None) else None))
|
||||
source_download_url = _build_download_url(document.id, kind='source', version_id=version.id)
|
||||
markdown_download_url = _build_download_url(document.id, kind='md', version_id=version.id) if version.cleaned_file_path or version.cleaned_preview_path else None
|
||||
return {'document_id': document.id, 'knowledge_base': {'id': document.group.id if document.group else None, 'name': document.group.name if document.group else None, 'department_id': document.group.department_id if document.group else None, 'dify_dataset_id': document.group.dify_dataset_id if document.group else None}, 'title': document.title, 'source_filename': version.source_file_name, 'source_ext': version.source_file_ext, 'file_name': version.source_file_name, 'version_id': version.id, 'version_no': version.version_no, 'convert_status': version.status, 'sync_status': sync_record.status if sync_record else None, 'uploaded_at': version.created_at.isoformat() if version.created_at else None, 'converted_at': version.converted_at.isoformat() if version.converted_at else None, 'download_url_expires_at': None, 'source_download_url': source_download_url, 'markdown_download_url': markdown_download_url, 'markdown_download_url_expires_at': None, 'markdown_public_url': markdown_download_url, 'dify': {'dataset_id': sync_record.dataset_id if sync_record else document.group.dify_dataset_id if document.group else None, 'remote_document_id': sync_record.remote_document_id if sync_record else None, 'status': sync_record.status if sync_record else None, 'last_synced_at': sync_record.synced_at.isoformat() if sync_record and sync_record.synced_at else None}}
|
||||
|
||||
def _serialize_knowledge_base(group: KbGroup, *, document_count: int) -> dict:
|
||||
return {'id': group.id, 'knowledge_base_id': group.id, 'name': group.name, 'description': group.description, 'department_id': group.department_id, 'dify_dataset_id': group.dify_dataset_id, 'document_count': int(document_count or 0), 'created_at': group.created_at.isoformat() if group.created_at else None, 'updated_at': group.updated_at.isoformat() if group.updated_at else None}
|
||||
|
||||
def _list_files_payload(*, knowledge_base_id: int | None=None, department_id: int | None=None, file_name: str | None=None) -> list[dict]:
|
||||
normalized_file_name = str(file_name or '').strip().lower()
|
||||
query = _document_query().order_by(KbDocument.updated_at.desc(), KbDocument.id.desc())
|
||||
if knowledge_base_id is not None:
|
||||
query = query.filter(KbDocument.group_id == knowledge_base_id)
|
||||
if department_id is not None:
|
||||
query = query.join(KbGroup, KbGroup.id == KbDocument.group_id).filter(KbGroup.department_id == department_id)
|
||||
documents = query.all()
|
||||
payload = []
|
||||
for document in documents:
|
||||
version = _current_version(document)
|
||||
if not version:
|
||||
continue
|
||||
normalized_name = version.source_file_name.lower() if version.source_file_name else ''
|
||||
if normalized_file_name and normalized_file_name not in normalized_name and (normalized_file_name not in document.title.lower()):
|
||||
continue
|
||||
payload.append(_serialize_integration_document(document, version=version))
|
||||
def _knowledge_base_summary(group: Group, *, document_count: int) -> dict:
|
||||
payload = serialize_group(group, document_count=document_count)
|
||||
payload["knowledge_base_id"] = payload["id"]
|
||||
return payload
|
||||
|
||||
def _resolve_download_path(version: KbDocumentVersion, kind: str) -> tuple[Path, str]:
|
||||
if kind == 'source':
|
||||
path = _resolve_storage_path(version.source_file_path)
|
||||
if path is None:
|
||||
raise NotFoundError('File not found on disk.')
|
||||
filename = version.source_file_name or f'document-{version.document_id}'
|
||||
return (path, filename)
|
||||
preferred = _resolve_storage_path(version.cleaned_file_path) or _resolve_storage_path(version.cleaned_preview_path)
|
||||
if not preferred:
|
||||
abort(409, description='Markdown not ready.')
|
||||
filename = f'document-{version.document_id}-v{version.version_no}.md'
|
||||
return (preferred, filename)
|
||||
|
||||
@integration_bp.before_request
|
||||
def _verify_integration_access():
|
||||
result = _require_integration_key()
|
||||
if result is not None:
|
||||
return result
|
||||
return None
|
||||
def _integration_document_payload(
|
||||
document: Document,
|
||||
*,
|
||||
version: DocumentVersion | None = None,
|
||||
sync_record: DifySyncRecord | None = None,
|
||||
) -> dict:
|
||||
version = version or current_version(document)
|
||||
if version is None:
|
||||
raise HTTPException(status_code=404, detail="No current version found.")
|
||||
sync_record = sync_record or (version.sync_records[0] if version.sync_records else None)
|
||||
try:
|
||||
source_token, source_expires_at = create_integration_download_token(
|
||||
file_id=document.id,
|
||||
version_id=version.id,
|
||||
kind="source",
|
||||
)
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=503, detail=str(exc)) from exc
|
||||
md_token = None
|
||||
md_expires_at = None
|
||||
if version.md_path:
|
||||
try:
|
||||
md_token, md_expires_at = create_integration_download_token(
|
||||
file_id=document.id,
|
||||
version_id=version.id,
|
||||
kind="md",
|
||||
)
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=503, detail=str(exc)) from exc
|
||||
return {
|
||||
"queried_at": utc_now().isoformat(),
|
||||
"document_id": document.id,
|
||||
"knowledge_base": {
|
||||
"id": document.group.id,
|
||||
"name": document.group.name,
|
||||
"department_id": document.group.department_id,
|
||||
"department_name": document.group.department.name if document.group.department else None,
|
||||
"dify_dataset_id": document.group.dify_dataset_id,
|
||||
},
|
||||
"title": document.title,
|
||||
"source_filename": version.source_filename,
|
||||
"source_ext": version.source_ext,
|
||||
"file_name": version.source_filename,
|
||||
"version_id": version.id,
|
||||
"version_no": version.version_no,
|
||||
"convert_status": version.convert_status,
|
||||
"sync_status": version.sync_status,
|
||||
"uploaded_at": version.uploaded_at.isoformat() if version.uploaded_at else None,
|
||||
"converted_at": version.converted_at.isoformat() if version.converted_at else None,
|
||||
"download_url_expires_at": source_expires_at.isoformat(),
|
||||
"source_download_url": (
|
||||
f"{settings.public_base_url}{settings.api_prefix}/integration/download"
|
||||
f"?version_id={version.id}&kind=source&token={source_token}"
|
||||
),
|
||||
"markdown_download_url": (
|
||||
f"{settings.public_base_url}{settings.api_prefix}/integration/download"
|
||||
f"?version_id={version.id}&kind=md&token={md_token}"
|
||||
if version.md_path and md_token
|
||||
else None
|
||||
),
|
||||
"markdown_download_url_expires_at": md_expires_at.isoformat() if md_expires_at else None,
|
||||
"markdown_public_url": version.md_public_url,
|
||||
"dify": {
|
||||
"dataset_id": sync_record.dataset_id if sync_record else document.group.dify_dataset_id,
|
||||
"remote_document_id": sync_record.remote_document_id if sync_record else None,
|
||||
"status": sync_record.status if sync_record else None,
|
||||
"last_indexing_status": sync_record.last_indexing_status if sync_record else None,
|
||||
"last_synced_at": sync_record.last_synced_at.isoformat() if sync_record and sync_record.last_synced_at else None,
|
||||
},
|
||||
}
|
||||
|
||||
@integration_bp.route('/files/<int:file_id>', methods=['GET'])
|
||||
def get_file_detail(file_id: int):
|
||||
document = _document_query().filter(KbDocument.id == file_id).first()
|
||||
if not document:
|
||||
raise NotFoundError('Document not found.')
|
||||
return jsonify(_serialize_integration_document(document))
|
||||
|
||||
@integration_bp.route('/knowledge-bases', methods=['GET'])
|
||||
def list_knowledge_bases():
|
||||
department_id = request.args.get('department_id', type=int)
|
||||
q = str(request.args.get('q') or '').strip()
|
||||
document_counts = db.session.query(KbDocument.group_id.label('group_id'), func.count(KbDocument.id).label('document_count')).filter(KbDocument.is_deleted.is_(False)).group_by(KbDocument.group_id).subquery()
|
||||
query = db.session.query(KbGroup, func.coalesce(document_counts.c.document_count, 0).label('document_count')).outerjoin(document_counts, document_counts.c.group_id == KbGroup.id).filter(KbGroup.is_active.is_(True)).order_by(KbGroup.name.asc())
|
||||
@router.get("/knowledge-bases")
|
||||
def list_knowledge_bases(
|
||||
department_id: int | None = None,
|
||||
q: str | None = None,
|
||||
db: Session = Depends(get_db),
|
||||
_: str = Depends(require_integration_key),
|
||||
):
|
||||
document_counts = (
|
||||
db.query(Document.group_id.label("group_id"), func.count(Document.id).label("document_count"))
|
||||
.filter(Document.is_deleted.is_(False))
|
||||
.group_by(Document.group_id)
|
||||
.subquery()
|
||||
)
|
||||
query = (
|
||||
db.query(Group, func.coalesce(document_counts.c.document_count, 0).label("document_count"))
|
||||
.outerjoin(document_counts, document_counts.c.group_id == Group.id)
|
||||
.options(joinedload(Group.department))
|
||||
.order_by(Group.name.asc())
|
||||
)
|
||||
if department_id is not None:
|
||||
query = query.filter(KbGroup.department_id == department_id)
|
||||
query = query.filter(Group.department_id == department_id)
|
||||
if q:
|
||||
query = query.filter(KbGroup.name.ilike(f'%{q}%'))
|
||||
query = query.filter(Group.name.ilike(f"%{q.strip()}%"))
|
||||
rows = query.all()
|
||||
return jsonify({'data': [_serialize_knowledge_base(group, document_count=document_count) for group, document_count in rows]})
|
||||
return {"data": [_knowledge_base_summary(group, document_count=document_count) for group, document_count in rows]}
|
||||
|
||||
@integration_bp.route('/files', methods=['GET'])
|
||||
def list_files():
|
||||
knowledge_base_id = request.args.get('knowledge_base_id', type=int)
|
||||
department_id = request.args.get('department_id', type=int)
|
||||
file_name = request.args.get('file_name')
|
||||
return jsonify({'data': _list_files_payload(knowledge_base_id=knowledge_base_id, department_id=department_id, file_name=file_name)})
|
||||
|
||||
@integration_bp.route('/knowledge-bases/<int:knowledge_base_id>/files', methods=['GET'])
|
||||
def list_files_for_knowledge_base(knowledge_base_id: int):
|
||||
return jsonify({'data': _list_files_payload(knowledge_base_id=knowledge_base_id, file_name=request.args.get('file_name'))})
|
||||
@router.get("/files")
|
||||
def list_files(
|
||||
knowledge_base_id: int | None = None,
|
||||
department_id: int | None = None,
|
||||
file_name: str | None = Query(default=None, description="Filter by source filename or title."),
|
||||
db: Session = Depends(get_db),
|
||||
_: str = Depends(require_integration_key),
|
||||
):
|
||||
query = _document_query(db)
|
||||
if knowledge_base_id is not None:
|
||||
query = query.filter(Document.group_id == knowledge_base_id)
|
||||
if department_id is not None:
|
||||
query = query.join(Group, Group.id == Document.group_id).filter(Group.department_id == department_id)
|
||||
documents = query.order_by(Document.updated_at.desc()).all()
|
||||
normalized = file_name.strip().lower() if file_name else None
|
||||
|
||||
@integration_bp.route('/dify-file', methods=['GET'])
|
||||
def get_file_detail_by_dify():
|
||||
remote_document_id = str(request.args.get('remote_document_id') or '').strip()
|
||||
dataset_id = str(request.args.get('dataset_id') or '').strip() or None
|
||||
if not remote_document_id:
|
||||
raise ValidationError('remote_document_id is required')
|
||||
record_query = db.session.query(KbDifySyncRecord).join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id).join(KbDocument, KbDocument.id == KbDocumentVersion.document_id).options(joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.document).joinedload(KbDocument.group), joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records)).filter(KbDocument.is_deleted.is_(False), KbDifySyncRecord.remote_document_id == remote_document_id).order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
if dataset_id:
|
||||
record_query = record_query.filter(KbDifySyncRecord.dataset_id == dataset_id)
|
||||
record = record_query.first()
|
||||
version = record.document_version if record else None
|
||||
document = version.document if version else None
|
||||
payload: list[dict] = []
|
||||
for document in documents:
|
||||
version = current_version(document)
|
||||
if version is None:
|
||||
continue
|
||||
if normalized and normalized not in version.source_filename.lower() and normalized not in document.title.lower():
|
||||
continue
|
||||
payload.append(_integration_document_payload(document))
|
||||
return {"data": payload}
|
||||
|
||||
|
||||
@router.get("/knowledge-bases/{knowledge_base_id}/files")
|
||||
def list_files_for_knowledge_base(
|
||||
knowledge_base_id: int,
|
||||
file_name: str | None = Query(default=None, description="Filter by source filename or title."),
|
||||
db: Session = Depends(get_db),
|
||||
_: str = Depends(require_integration_key),
|
||||
):
|
||||
return list_files(
|
||||
knowledge_base_id=knowledge_base_id,
|
||||
file_name=file_name,
|
||||
db=db,
|
||||
_="integration",
|
||||
)
|
||||
|
||||
|
||||
@router.get("/files/{file_id}")
|
||||
def get_file_detail(
|
||||
file_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
_: str = Depends(require_integration_key),
|
||||
):
|
||||
document = _document_query(db).filter(Document.id == file_id).first()
|
||||
if not document:
|
||||
raise NotFoundError('No local file mapping found for the given Dify document.')
|
||||
return jsonify(_serialize_integration_document(document, version=version, sync_record=record))
|
||||
raise HTTPException(status_code=404, detail="Document not found.")
|
||||
return _integration_document_payload(document)
|
||||
|
||||
@integration_bp.route('/dify-files/resolve', methods=['POST'])
|
||||
def resolve_files_by_dify():
|
||||
data = request.get_json(silent=True) or {}
|
||||
items = data.get('items') if isinstance(data.get('items'), list) else []
|
||||
if not items:
|
||||
return jsonify({'data': []})
|
||||
remote_ids = sorted({str(item.get('remote_document_id') or '').strip() for item in items if isinstance(item, dict) and str(item.get('remote_document_id') or '').strip()})
|
||||
dataset_ids = sorted({str(item.get('dataset_id') or '').strip() for item in items if isinstance(item, dict) and str(item.get('dataset_id') or '').strip()})
|
||||
if not remote_ids:
|
||||
return jsonify({'data': []})
|
||||
query = db.session.query(KbDifySyncRecord).join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id).join(KbDocument, KbDocument.id == KbDocumentVersion.document_id).options(joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.document).joinedload(KbDocument.group), joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records)).filter(KbDocument.is_deleted.is_(False), KbDifySyncRecord.remote_document_id.in_(remote_ids)).order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
|
||||
@router.get("/dify-file")
|
||||
def get_file_detail_by_dify(
|
||||
remote_document_id: str = Query(..., description="Dify document id."),
|
||||
dataset_id: str | None = Query(default=None, description="Optional Dify dataset id."),
|
||||
db: Session = Depends(get_db),
|
||||
_: str = Depends(require_integration_key),
|
||||
):
|
||||
record_query = (
|
||||
db.query(DifySyncRecord)
|
||||
.join(DocumentVersion, DocumentVersion.id == DifySyncRecord.version_id)
|
||||
.join(Document, Document.id == DocumentVersion.document_id)
|
||||
.options(
|
||||
joinedload(DifySyncRecord.version)
|
||||
.joinedload(DocumentVersion.document)
|
||||
.joinedload(Document.group)
|
||||
.joinedload(Group.department),
|
||||
joinedload(DifySyncRecord.version).joinedload(DocumentVersion.sync_records),
|
||||
)
|
||||
.filter(
|
||||
Document.is_deleted.is_(False),
|
||||
DifySyncRecord.remote_document_id == remote_document_id,
|
||||
)
|
||||
.order_by(DifySyncRecord.updated_at.desc(), DifySyncRecord.created_at.desc())
|
||||
)
|
||||
if dataset_id:
|
||||
record_query = record_query.filter(DifySyncRecord.dataset_id == dataset_id)
|
||||
record = record_query.first()
|
||||
if not record or not record.version or not record.version.document:
|
||||
raise HTTPException(status_code=404, detail="No local file mapping found for the given Dify document.")
|
||||
return _integration_document_payload(record.version.document, version=record.version, sync_record=record)
|
||||
|
||||
|
||||
@router.post("/dify-files/resolve")
|
||||
def resolve_files_by_dify(
|
||||
payload: DifyResolveRequest,
|
||||
db: Session = Depends(get_db),
|
||||
_: str = Depends(require_integration_key),
|
||||
):
|
||||
if not payload.items:
|
||||
return {"data": []}
|
||||
|
||||
remote_ids = sorted({item.remote_document_id for item in payload.items if item.remote_document_id})
|
||||
dataset_ids = sorted({item.dataset_id for item in payload.items if item.dataset_id})
|
||||
|
||||
record_query = (
|
||||
db.query(DifySyncRecord)
|
||||
.join(DocumentVersion, DocumentVersion.id == DifySyncRecord.version_id)
|
||||
.join(Document, Document.id == DocumentVersion.document_id)
|
||||
.options(
|
||||
joinedload(DifySyncRecord.version)
|
||||
.joinedload(DocumentVersion.document)
|
||||
.joinedload(Document.group)
|
||||
.joinedload(Group.department),
|
||||
joinedload(DifySyncRecord.version).joinedload(DocumentVersion.sync_records),
|
||||
)
|
||||
.filter(
|
||||
Document.is_deleted.is_(False),
|
||||
DifySyncRecord.remote_document_id.in_(remote_ids),
|
||||
)
|
||||
.order_by(DifySyncRecord.updated_at.desc(), DifySyncRecord.created_at.desc())
|
||||
)
|
||||
if dataset_ids:
|
||||
query = query.filter(KbDifySyncRecord.dataset_id.in_(dataset_ids) | KbDifySyncRecord.dataset_id.is_(None))
|
||||
records = query.all()
|
||||
records_by_key: dict[tuple[str | None, str], KbDifySyncRecord] = {}
|
||||
records_by_remote: dict[str, KbDifySyncRecord] = {}
|
||||
record_query = record_query.filter(
|
||||
(DifySyncRecord.dataset_id.in_(dataset_ids)) | (DifySyncRecord.dataset_id.is_(None))
|
||||
)
|
||||
records = record_query.all()
|
||||
|
||||
records_by_key: dict[tuple[str | None, str], DifySyncRecord] = {}
|
||||
records_by_remote: dict[str, DifySyncRecord] = {}
|
||||
for record in records:
|
||||
key = (record.dataset_id, record.remote_document_id)
|
||||
records_by_key.setdefault(key, record)
|
||||
records_by_remote.setdefault(record.remote_document_id, record)
|
||||
payload = []
|
||||
for item in items:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
requested_dataset_id = str(item.get('dataset_id') or '').strip() or None
|
||||
requested_remote_document_id = str(item.get('remote_document_id') or '').strip()
|
||||
if not requested_remote_document_id:
|
||||
continue
|
||||
record = records_by_key.get((requested_dataset_id, requested_remote_document_id))
|
||||
if record is None and requested_dataset_id is None:
|
||||
record = records_by_remote.get(requested_remote_document_id)
|
||||
version = record.document_version if record else None
|
||||
document = version.document if version else None
|
||||
payload.append({'request': {'dataset_id': requested_dataset_id, 'remote_document_id': requested_remote_document_id}, 'found': bool(document), 'document': _serialize_integration_document(document, version=version, sync_record=record) if document else None})
|
||||
return jsonify({'data': payload})
|
||||
|
||||
@integration_bp.route('/files/<int:file_id>/download', methods=['GET'])
|
||||
def download_file(file_id: int):
|
||||
kind = str(request.args.get('kind') or 'md').strip().lower()
|
||||
version, document = _resolve_requested_version(file_id)
|
||||
data: list[dict] = []
|
||||
for item in payload.items:
|
||||
record = records_by_key.get((item.dataset_id, item.remote_document_id))
|
||||
if record is None and item.dataset_id is None:
|
||||
record = records_by_remote.get(item.remote_document_id)
|
||||
data.append(
|
||||
{
|
||||
"request": {
|
||||
"dataset_id": item.dataset_id,
|
||||
"remote_document_id": item.remote_document_id,
|
||||
},
|
||||
"found": bool(record and record.version and record.version.document),
|
||||
"document": (
|
||||
_integration_document_payload(record.version.document, version=record.version, sync_record=record)
|
||||
if record and record.version and record.version.document
|
||||
else None
|
||||
),
|
||||
}
|
||||
)
|
||||
return {"data": data}
|
||||
|
||||
|
||||
@router.get("/files/{file_id}/download")
|
||||
def download_file(
|
||||
file_id: int,
|
||||
kind: str = Query(default="md"),
|
||||
db: Session = Depends(get_db),
|
||||
_: str = Depends(require_integration_key),
|
||||
):
|
||||
document = _document_query(db).filter(Document.id == file_id).first()
|
||||
if not document:
|
||||
raise NotFoundError('Document not found.')
|
||||
raise HTTPException(status_code=404, detail="Document not found.")
|
||||
version = current_version(document)
|
||||
if not version:
|
||||
raise NotFoundError('No version found.')
|
||||
path, filename = _resolve_download_path(version, kind)
|
||||
raise HTTPException(status_code=404, detail="No version found.")
|
||||
|
||||
if kind == "source":
|
||||
path = Path(version.source_path)
|
||||
filename = version.source_filename
|
||||
else:
|
||||
if not version.md_path:
|
||||
raise HTTPException(status_code=409, detail="Markdown not ready.")
|
||||
path = Path(version.md_path)
|
||||
filename = f"{document.title}.md"
|
||||
|
||||
if not path.exists():
|
||||
raise NotFoundError('File not found on disk.')
|
||||
return send_file(path, as_attachment=True, download_name=filename)
|
||||
raise HTTPException(status_code=404, detail="File missing on disk.")
|
||||
|
||||
return FileResponse(path, filename=filename)
|
||||
|
||||
|
||||
@router.get("/download")
|
||||
def download_file_from_signed_url(
|
||||
file_id: int | None = Query(default=None),
|
||||
version_id: int | None = Query(default=None),
|
||||
kind: str = Query(default="source"),
|
||||
token: str = Query(...),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
payload = decode_integration_download_token(token)
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=503, detail=str(exc)) from exc
|
||||
if not payload:
|
||||
raise HTTPException(status_code=401, detail="Invalid or expired download token.")
|
||||
expected_kind = payload.get("kind")
|
||||
expected_version_id = payload.get("version_id")
|
||||
expected_file_id = payload.get("file_id")
|
||||
if expected_kind != kind:
|
||||
raise HTTPException(status_code=401, detail="Download token does not match the requested file.")
|
||||
if expected_version_id is not None:
|
||||
if version_id != int(expected_version_id):
|
||||
raise HTTPException(status_code=401, detail="Download token does not match the requested file.")
|
||||
version = db.query(DocumentVersion).join(Document).filter(
|
||||
DocumentVersion.id == version_id,
|
||||
Document.is_deleted.is_(False),
|
||||
).first()
|
||||
if not version or not version.document:
|
||||
raise HTTPException(status_code=404, detail="Version not found.")
|
||||
document = version.document
|
||||
else:
|
||||
if file_id is None or expected_file_id is None or int(expected_file_id) != file_id:
|
||||
raise HTTPException(status_code=401, detail="Download token does not match the requested file.")
|
||||
document = _document_query(db).filter(Document.id == file_id).first()
|
||||
if not document:
|
||||
raise HTTPException(status_code=404, detail="Document not found.")
|
||||
version = current_version(document)
|
||||
if not version:
|
||||
raise HTTPException(status_code=404, detail="No version found.")
|
||||
|
||||
if kind == "source":
|
||||
path = Path(version.source_path)
|
||||
filename = version.source_filename
|
||||
else:
|
||||
if not version.md_path:
|
||||
raise HTTPException(status_code=409, detail="Markdown not ready.")
|
||||
path = Path(version.md_path)
|
||||
filename = f"{document.title}.md"
|
||||
|
||||
if not path.exists():
|
||||
raise HTTPException(status_code=404, detail="File missing on disk.")
|
||||
return FileResponse(path, filename=filename)
|
||||
@@ -1,8 +0,0 @@
|
||||
"""
|
||||
backend/app/api/internal/__init__.py
|
||||
|
||||
用途:内部 job 回调/健康检查 Blueprint。
|
||||
"""
|
||||
from app.api.internal.jobs import internal_jobs_bp # noqa: F401
|
||||
|
||||
__all__ = ['internal_jobs_bp']
|
||||
@@ -1,8 +0,0 @@
|
||||
"""
|
||||
backend/app/api/internal/jobs.py
|
||||
|
||||
用途:内部 jobs API(Wave 1 自 internal_jobs.py 迁入)。
|
||||
"""
|
||||
from app.api.internal_jobs import internal_jobs_bp # noqa: F401
|
||||
|
||||
__all__ = ['internal_jobs_bp']
|
||||
@@ -1,204 +0,0 @@
|
||||
"""
|
||||
backend/app/api/internal_jobs.py
|
||||
|
||||
用途:平台内置 Job 内部 API(POST /api/internal/jobs/<job_key>)。
|
||||
依赖:job_registry、schedule_contract、scheduler_service。
|
||||
逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||
from app.services.schedule.job_registry import get_platform_job, run_platform_job
|
||||
from app.services.schedule.schedule_contract import normalize_job_key
|
||||
from app.services.schedule.scheduler_service import _generate_run_no
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import (
|
||||
apply_deferred_schedule_run_state,
|
||||
recover_stale_awaiting_rpa_schedule_runs,
|
||||
should_defer_schedule_run_finalization,
|
||||
)
|
||||
|
||||
internal_jobs_bp = Blueprint('internal_jobs', __name__)
|
||||
|
||||
|
||||
def _assert_task_matches_job_key(task: ScheduleTask, job_key: str) -> None:
|
||||
"""
|
||||
校验 task 与 URL job key 一致,防止 schedule_task_id 指向错误 handler。
|
||||
Raises:
|
||||
ValidationError: 非 platform_job 或 platform_api_path 不匹配
|
||||
"""
|
||||
if task.schedule_type != 'platform_job':
|
||||
raise ValidationError(f"schedule_task_id {task.id} is not a platform_job task")
|
||||
task_key = normalize_job_key(task.platform_api_path)
|
||||
if task_key != job_key:
|
||||
raise ValidationError(
|
||||
f"schedule_task_id {task.id} platform_api_path '{task.platform_api_path}' "
|
||||
f"does not match job key '{job_key}'"
|
||||
)
|
||||
|
||||
|
||||
def _resolve_schedule_task_and_run(job_key: str, data: dict) -> tuple[ScheduleTask, ScheduleRun]:
|
||||
"""
|
||||
解析或创建 ScheduleTask / ScheduleRun。
|
||||
核心逻辑:优先 schedule_task_id(须匹配 job key);否则按 platform_api_path 匹配 job key。
|
||||
run_no 查询限定 schedule_task_id,避免跨任务写入。
|
||||
"""
|
||||
schedule_task_id = data.get('schedule_task_id')
|
||||
task = db.session.get(ScheduleTask, int(schedule_task_id)) if schedule_task_id else None
|
||||
if task:
|
||||
_assert_task_matches_job_key(task, job_key)
|
||||
else:
|
||||
task = (
|
||||
ScheduleTask.query.filter(
|
||||
ScheduleTask.platform_api_path == job_key,
|
||||
ScheduleTask.schedule_type == 'platform_job',
|
||||
)
|
||||
.order_by(ScheduleTask.id.desc())
|
||||
.first()
|
||||
)
|
||||
if not task:
|
||||
raise NotFoundError(f"No schedule task found for platform job '{job_key}'")
|
||||
|
||||
run_no = str(data.get('run_no') or '').strip()
|
||||
run = None
|
||||
if run_no:
|
||||
run = ScheduleRun.query.filter_by(run_no=run_no, schedule_task_id=task.id).first()
|
||||
if not run:
|
||||
foreign = ScheduleRun.query.filter_by(run_no=run_no).first()
|
||||
if foreign and foreign.schedule_task_id != task.id:
|
||||
raise ValidationError(
|
||||
f"run_no '{run_no}' belongs to schedule_task_id {foreign.schedule_task_id}, "
|
||||
f"not {task.id}"
|
||||
)
|
||||
if not run:
|
||||
run = ScheduleRun(
|
||||
run_no=run_no or _generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
trigger_type='api',
|
||||
started_at=datetime.utcnow(),
|
||||
status='running',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
if not run.dify_execution_snapshot:
|
||||
capture_dify_execution_snapshot(run, task)
|
||||
db.session.commit()
|
||||
return task, run
|
||||
|
||||
|
||||
def _finalize_run(
|
||||
run: ScheduleRun,
|
||||
*,
|
||||
total_count: int,
|
||||
success_count: int,
|
||||
failed_count: int,
|
||||
skipped_count: int,
|
||||
step_logs: list | None,
|
||||
) -> None:
|
||||
"""写入 run 汇总字段并 commit。"""
|
||||
run.status = (
|
||||
'success' if failed_count == 0
|
||||
else 'failed' if success_count == 0
|
||||
else 'partial_failed'
|
||||
)
|
||||
run.total_count = total_count
|
||||
run.success_count = success_count
|
||||
run.failed_count = failed_count
|
||||
run.skipped_count = skipped_count
|
||||
run.finished_at = datetime.utcnow()
|
||||
if run.started_at and run.finished_at:
|
||||
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000)
|
||||
run.step_logs = step_logs if step_logs else None
|
||||
db.session.commit()
|
||||
|
||||
|
||||
@internal_jobs_bp.route('/<name>', methods=['POST'])
|
||||
def run_internal_job(name: str):
|
||||
"""
|
||||
执行已注册平台 Job。
|
||||
核心逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。
|
||||
"""
|
||||
key = normalize_job_key(name)
|
||||
data = request.get_json(silent=True) or {}
|
||||
|
||||
if not get_platform_job(key):
|
||||
raise NotFoundError(f"Unknown platform job: {name}")
|
||||
|
||||
task, run = _resolve_schedule_task_and_run(key, data)
|
||||
recover_stale_awaiting_rpa_schedule_runs(task)
|
||||
try:
|
||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = run_platform_job(
|
||||
key, task, run, data,
|
||||
)
|
||||
except Exception as exc:
|
||||
run.status = 'failed'
|
||||
run.error_message = str(exc)
|
||||
run.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
raise AppError(
|
||||
code='SYSTEM.HTTP_ERROR',
|
||||
message=str(exc),
|
||||
http_status=500,
|
||||
details={
|
||||
'traceback': traceback.format_exc(),
|
||||
'summary': {
|
||||
'total_count': 0,
|
||||
'success_count': 0,
|
||||
'failed_count': 0,
|
||||
'skipped_count': 0,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
if should_defer_schedule_run_finalization(task, step_logs):
|
||||
apply_deferred_schedule_run_state(
|
||||
run,
|
||||
task,
|
||||
total_count=total_count,
|
||||
success_count=success_count,
|
||||
failed_count=failed_count,
|
||||
skipped_count=skipped_count,
|
||||
details=details,
|
||||
errors=errors,
|
||||
step_logs=step_logs,
|
||||
)
|
||||
return jsonify({
|
||||
'summary': {
|
||||
'total_count': total_count,
|
||||
'success_count': success_count,
|
||||
'failed_count': failed_count,
|
||||
'skipped_count': skipped_count,
|
||||
},
|
||||
'details': details,
|
||||
'errors': errors,
|
||||
'step_logs': step_logs,
|
||||
'awaiting_rpa_callback': True,
|
||||
})
|
||||
|
||||
_finalize_run(
|
||||
run,
|
||||
total_count=total_count,
|
||||
success_count=success_count,
|
||||
failed_count=failed_count,
|
||||
skipped_count=skipped_count,
|
||||
step_logs=step_logs,
|
||||
)
|
||||
return jsonify({
|
||||
'summary': {
|
||||
'total_count': total_count,
|
||||
'success_count': success_count,
|
||||
'failed_count': failed_count,
|
||||
'skipped_count': skipped_count,
|
||||
},
|
||||
'details': details,
|
||||
'errors': errors,
|
||||
'step_logs': step_logs,
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.database import get_db
|
||||
from app.deps import accessible_group_ids, get_current_user, is_super_admin
|
||||
from app.models import Job, User
|
||||
from app.serializers import serialize_job
|
||||
|
||||
|
||||
router = APIRouter(prefix="/jobs", tags=["jobs"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_jobs(
|
||||
limit: int = 50,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
query = db.query(Job).order_by(Job.created_at.desc())
|
||||
if not is_super_admin(user):
|
||||
group_ids = accessible_group_ids(db, user)
|
||||
if user.role == "admin":
|
||||
query = query.filter(or_(Job.created_by_id == user.id, Job.group_id.in_(group_ids or [-1])))
|
||||
else:
|
||||
query = query.filter(Job.created_by_id == user.id)
|
||||
jobs = query.limit(min(limit, 200)).all()
|
||||
return {"data": [serialize_job(job) for job in jobs]}
|
||||
|
||||
|
||||
@router.get("/{job_id}")
|
||||
def get_job(job_id: str, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
||||
job = db.query(Job).filter(Job.id == job_id).first()
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found.")
|
||||
if is_super_admin(user):
|
||||
return serialize_job(job)
|
||||
if user.role == "admin":
|
||||
group_ids = accessible_group_ids(db, user)
|
||||
if job.created_by_id != user.id and job.group_id not in (group_ids or []):
|
||||
raise HTTPException(status_code=403, detail="Forbidden")
|
||||
return serialize_job(job)
|
||||
if job.created_by_id != user.id:
|
||||
raise HTTPException(status_code=403, detail="Forbidden")
|
||||
return serialize_job(job)
|
||||
@@ -1,16 +0,0 @@
|
||||
"""
|
||||
backend/app/api/kb/__init__.py
|
||||
|
||||
用途:知识库管理 Blueprint 入口(Wave 3 分包)。
|
||||
依赖:kb/blueprint.py、common、dify、groups、documents、jobs。
|
||||
逻辑:import 子模块注册路由;register_blueprints 从本包 import knowledge_base_bp。
|
||||
"""
|
||||
from app.api.kb.blueprint import knowledge_base_bp
|
||||
|
||||
import app.api.kb.common # noqa: F401
|
||||
import app.api.kb.dify # noqa: F401
|
||||
import app.api.kb.groups # noqa: F401
|
||||
import app.api.kb.documents # noqa: F401
|
||||
import app.api.kb.jobs # noqa: F401
|
||||
|
||||
__all__ = ['knowledge_base_bp']
|
||||
@@ -1,10 +0,0 @@
|
||||
"""
|
||||
backend/app/api/kb/blueprint.py
|
||||
|
||||
用途:知识库 API 共享 Blueprint(Wave 3 分包后各子模块共用)。
|
||||
依赖:Flask Blueprint。
|
||||
逻辑:kb/dify、groups、documents、jobs 等子模块在此 bp 上注册路由;__init__ 导出 knowledge_base_bp。
|
||||
"""
|
||||
from flask import Blueprint
|
||||
|
||||
knowledge_base_bp = Blueprint('knowledge_base', __name__)
|
||||
@@ -1,73 +0,0 @@
|
||||
"""
|
||||
backend/app/api/kb/common.py
|
||||
|
||||
用途:知识库 API 共享 helper(鉴权、序列化、Markdown 预览)。
|
||||
依赖:app.core.*、models、services/kb/storage、edkb_system。
|
||||
逻辑:dify/groups/documents/jobs 子模块共用;存储读写见 services/kb/storage。
|
||||
"""
|
||||
from flask import current_app
|
||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError
|
||||
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup
|
||||
from app.services.kb.markdown import (
|
||||
markdown_unavailable_message,
|
||||
resolve_markdown_read_path,
|
||||
resolve_markdown_write_path,
|
||||
serialize_markdown_payload,
|
||||
)
|
||||
from app.services.kb.storage import (
|
||||
kb_storage_root,
|
||||
resolve_storage_path,
|
||||
safe_upload_filename,
|
||||
save_upload,
|
||||
)
|
||||
|
||||
def require_user():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
def run_db_read(label: str, loader):
|
||||
try:
|
||||
return loader()
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('[kb] transient db error during %s, retry with reconnect: %s', label, exc)
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
db.engine.dispose()
|
||||
except Exception:
|
||||
current_app.logger.warning('[kb] failed to dispose engine during %s recovery', label, exc_info=True)
|
||||
return loader()
|
||||
|
||||
def serialize_group(group: KbGroup, document_count: int=0):
|
||||
return {'id': group.id, 'name': group.name, 'description': group.description, 'department_id': group.department_id, 'document_count': int(document_count or 0), 'created_at': group.created_at.isoformat() if group.created_at else None, 'updated_at': group.updated_at.isoformat() if group.updated_at else None}
|
||||
|
||||
def serialize_document(doc: KbDocument):
|
||||
latest_version = current_version(doc)
|
||||
return {'id': doc.id, 'group_id': doc.group_id, 'title': doc.title, 'description': doc.description, 'status': doc.status, 'source_type': doc.source_type, 'created_at': doc.created_at.isoformat() if doc.created_at else None, 'updated_at': doc.updated_at.isoformat() if doc.updated_at else None, 'version_count': len(doc.versions) if getattr(doc, 'versions', None) else 0, 'latest_version': serialize_version(latest_version) if latest_version else None}
|
||||
|
||||
def serialize_version(version: KbDocumentVersion | None):
|
||||
if version is None:
|
||||
return None
|
||||
return {'id': version.id, 'document_id': version.document_id, 'version_no': version.version_no, 'status': version.status, 'is_current': version.is_current, 'source_file_name': version.source_file_name, 'source_file_ext': version.source_file_ext, 'source_file_size': version.source_file_size, 'sha256': version.sha256, 'cleaned_file_path': version.cleaned_file_path, 'cleaned_preview_path': version.cleaned_preview_path, 'error_message': version.error_message, 'created_at': version.created_at.isoformat() if version.created_at else None}
|
||||
|
||||
def serialize_sync_record(record: KbDifySyncRecord):
|
||||
return {'id': record.id, 'group_id': record.group_id, 'document_id': record.document_id, 'document_version_id': record.document_version_id, 'dataset_id': record.dataset_id, 'dataset_name': record.dataset_name, 'remote_document_id': record.remote_document_id, 'remote_document_name': record.remote_document_name, 'status': record.status, 'sync_hash': record.sync_hash, 'error_message': record.error_message, 'synced_at': record.synced_at.isoformat() if record.synced_at else None, 'updated_at': record.updated_at.isoformat() if record.updated_at else None}
|
||||
|
||||
def current_version(document: KbDocument | None) -> KbDocumentVersion | None:
|
||||
versions = list(getattr(document, 'versions', []) or [])
|
||||
if not versions:
|
||||
return None
|
||||
return next((item for item in versions if item.is_current), versions[0])
|
||||
|
||||
|
||||
def next_version_no(document: KbDocument) -> int:
|
||||
versions = list(getattr(document, 'versions', []) or [])
|
||||
if not versions:
|
||||
return 1
|
||||
return max((item.version_no for item in versions)) + 1
|
||||
@@ -1,45 +0,0 @@
|
||||
"""
|
||||
backend/app/api/kb/dify.py
|
||||
|
||||
用途:知识库 Dify 连接配置与健康检查 API。
|
||||
依赖:kb.blueprint、knowledge_cleaning.settings_service。
|
||||
逻辑:管理员读写 Dify 设置;GET /dify/health 探测远端 dataset。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.kb.blueprint import knowledge_base_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.knowledge_cleaning.settings_service import (
|
||||
get_kb_dify_health_payload,
|
||||
get_kb_dify_settings,
|
||||
save_kb_dify_settings,
|
||||
)
|
||||
|
||||
@knowledge_base_bp.route('/dify/settings', methods=['GET'])
|
||||
@require_admin
|
||||
def get_dify_settings():
|
||||
payload = get_kb_dify_settings()
|
||||
return jsonify(payload)
|
||||
|
||||
@knowledge_base_bp.route('/dify/settings', methods=['PATCH'])
|
||||
@require_admin
|
||||
def update_dify_settings():
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = save_kb_dify_settings(data)
|
||||
return jsonify(payload)
|
||||
|
||||
@knowledge_base_bp.route('/dify/health', methods=['GET'])
|
||||
@require_admin
|
||||
def get_dify_health():
|
||||
payload = get_kb_dify_health_payload()
|
||||
if payload['dify_api_configured'] and payload['dify_base_url']:
|
||||
try:
|
||||
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
|
||||
datasets = KbDifySyncService().list_datasets()
|
||||
payload['api']['reachable'] = True
|
||||
payload['api']['dataset_count'] = len(datasets)
|
||||
except Exception as exc:
|
||||
payload['api']['error'] = str(exc)
|
||||
else:
|
||||
payload['api']['error'] = 'Dify 连接尚未配置'
|
||||
return jsonify(payload)
|
||||
@@ -1,113 +0,0 @@
|
||||
"""
|
||||
backend/app/api/kb/documents.py
|
||||
|
||||
用途:知识库文档版本、Markdown、上传/清洗/同步 API(薄路由层)。
|
||||
依赖:kb.blueprint、kb.common、services/kb/document_service。
|
||||
逻辑:/documents* 与 /document-versions* 路由;业务见 document_service。
|
||||
"""
|
||||
from flask import jsonify, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.api.kb.blueprint import knowledge_base_bp
|
||||
from app.api.kb.common import require_user, serialize_document, serialize_sync_record, serialize_version
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.kb import document_service
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/versions', methods=['GET'])
|
||||
def list_document_versions(document_id: int):
|
||||
require_user()
|
||||
versions = document_service.list_document_versions(document_id)
|
||||
return jsonify([serialize_version(item) for item in versions])
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/document-versions/<int:version_id>/source-file', methods=['GET'])
|
||||
def get_document_version_source_file(version_id: int):
|
||||
require_user()
|
||||
source_path, filename = document_service.resolve_source_file_path(version_id)
|
||||
as_attachment = str(request.args.get('download') or '').strip() == '1'
|
||||
return send_file(source_path, as_attachment=as_attachment, download_name=filename)
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/sync-records', methods=['GET'])
|
||||
def list_document_sync_records(document_id: int):
|
||||
require_user()
|
||||
records = document_service.list_sync_records(document_id)
|
||||
return jsonify([serialize_sync_record(item) for item in records])
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/markdown', methods=['GET'])
|
||||
def get_document_markdown(document_id: int):
|
||||
require_user()
|
||||
return jsonify(document_service.read_markdown(document_id))
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/markdown', methods=['PATCH'])
|
||||
def update_document_markdown(document_id: int):
|
||||
current_user = require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = document_service.update_markdown(
|
||||
document_id,
|
||||
data.get('content'),
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify(payload)
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/upload', methods=['POST'])
|
||||
def upload_document_version(document_id: int):
|
||||
current_user = require_user()
|
||||
uploaded = request.files.get('file')
|
||||
payload = document_service.upload_new_version(
|
||||
document_id,
|
||||
uploaded,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/clean', methods=['POST'])
|
||||
@require_admin
|
||||
def submit_document_clean(document_id: int):
|
||||
current_user = get_current_user()
|
||||
payload, status_code = document_service.submit_clean(
|
||||
document_id,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
return jsonify(payload), status_code
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/sync', methods=['POST'])
|
||||
@require_admin
|
||||
def sync_document(document_id: int):
|
||||
current_user = get_current_user()
|
||||
payload = document_service.submit_sync(
|
||||
document_id,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
return jsonify(payload), 202
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>', methods=['PATCH'])
|
||||
def update_document(document_id: int):
|
||||
current_user = require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
document = document_service.update_metadata(
|
||||
document_id,
|
||||
data,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify(serialize_document(document))
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>', methods=['DELETE'])
|
||||
def delete_document(document_id: int):
|
||||
current_user = require_user()
|
||||
result = document_service.delete_document(
|
||||
document_id,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
return jsonify(result)
|
||||
@@ -1,292 +0,0 @@
|
||||
"""
|
||||
backend/app/api/kb/groups.py
|
||||
|
||||
用途:知识库分组 CRUD、组内文档列表与路径批量上传 API(薄路由)。
|
||||
依赖:kb.blueprint、kb.common、services/kb/path_upload_service、services/kb/job_lifecycle。
|
||||
逻辑:/groups* 与 /path-upload-jobs*;业务编排委托 path_upload_service。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import jsonify, request
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
from app import db
|
||||
from app.api.kb.blueprint import knowledge_base_bp
|
||||
from app.api.kb.common import require_user, run_db_read, serialize_document, serialize_group
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import KbDocument, KbGroup, KbJob
|
||||
from app.services.kb import path_upload_service
|
||||
from app.services.kb.job_lifecycle import cancel_active_kb_jobs_for_group, serialize_job
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups', methods=['GET'])
|
||||
def list_groups():
|
||||
require_user()
|
||||
document_counts = (
|
||||
db.session.query(KbDocument.group_id.label('group_id'), func.count(KbDocument.id).label('document_count'))
|
||||
.filter(KbDocument.is_deleted.is_(False))
|
||||
.group_by(KbDocument.group_id)
|
||||
.subquery()
|
||||
)
|
||||
rows = run_db_read(
|
||||
'list_groups',
|
||||
lambda: db.session.query(KbGroup, func.coalesce(document_counts.c.document_count, 0).label('document_count'))
|
||||
.outerjoin(document_counts, document_counts.c.group_id == KbGroup.id)
|
||||
.filter(KbGroup.is_active.is_(True))
|
||||
.order_by(KbGroup.updated_at.desc(), KbGroup.id.desc())
|
||||
.all(),
|
||||
)
|
||||
return jsonify([serialize_group(group, document_count) for group, document_count in rows])
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups', methods=['POST'])
|
||||
@require_admin
|
||||
def create_group():
|
||||
data = request.get_json(silent=True) or {}
|
||||
name = str(data.get('name') or '').strip()
|
||||
description = str(data.get('description') or '').strip() or None
|
||||
department_id = data.get('department_id')
|
||||
if not name:
|
||||
raise ValidationError('name is required')
|
||||
existing_query = db.session.query(KbGroup).filter(KbGroup.name == name, KbGroup.is_active.is_(True))
|
||||
if department_id is None:
|
||||
existing_query = existing_query.filter(KbGroup.department_id.is_(None))
|
||||
else:
|
||||
existing_query = existing_query.filter(KbGroup.department_id == department_id)
|
||||
if existing_query.first():
|
||||
raise ValidationError('知识库分组已存在')
|
||||
current_user = get_current_user()
|
||||
group = KbGroup(
|
||||
name=name,
|
||||
description=description,
|
||||
department_id=department_id,
|
||||
created_by_id=getattr(current_user, 'id', None),
|
||||
updated_by_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.add(group)
|
||||
db.session.commit()
|
||||
return jsonify(serialize_group(group, 0)), 201
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups/<int:group_id>', methods=['PATCH'])
|
||||
@require_admin
|
||||
def update_group(group_id: int):
|
||||
group = db.session.get(KbGroup, group_id)
|
||||
if not group or not group.is_active:
|
||||
raise NotFoundError('知识库分组不存在')
|
||||
data = request.get_json(silent=True) or {}
|
||||
name = str(data.get('name') or group.name).strip()
|
||||
description = data.get('description')
|
||||
department_id = data.get('department_id', group.department_id)
|
||||
if not name:
|
||||
raise ValidationError('name is required')
|
||||
existing_query = db.session.query(KbGroup).filter(
|
||||
KbGroup.id != group.id,
|
||||
KbGroup.name == name,
|
||||
KbGroup.is_active.is_(True),
|
||||
)
|
||||
if department_id is None:
|
||||
existing_query = existing_query.filter(KbGroup.department_id.is_(None))
|
||||
else:
|
||||
existing_query = existing_query.filter(KbGroup.department_id == department_id)
|
||||
if existing_query.first():
|
||||
raise ValidationError('知识库分组已存在')
|
||||
current_user = get_current_user()
|
||||
group.name = name
|
||||
group.description = str(description).strip() or None if description is not None else None
|
||||
group.department_id = department_id
|
||||
group.updated_by_id = getattr(current_user, 'id', None)
|
||||
db.session.commit()
|
||||
document_count = db.session.query(func.count(KbDocument.id)).filter(
|
||||
KbDocument.group_id == group.id,
|
||||
KbDocument.is_deleted.is_(False),
|
||||
).scalar()
|
||||
return jsonify(serialize_group(group, document_count))
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups/<int:group_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_group(group_id: int):
|
||||
group = db.session.get(KbGroup, group_id)
|
||||
if not group or not group.is_active:
|
||||
raise NotFoundError('知识库分组不存在')
|
||||
current_user = get_current_user()
|
||||
group.is_active = False
|
||||
group.updated_by_id = getattr(current_user, 'id', None)
|
||||
cancel_active_kb_jobs_for_group(group.id, '知识库分组已删除,后台任务已取消')
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True, 'id': group_id})
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups/<int:group_id>/files', methods=['GET'])
|
||||
def list_group_files(group_id: int):
|
||||
require_user()
|
||||
group = run_db_read('get_group_for_files', lambda: db.session.get(KbGroup, group_id))
|
||||
if not group or not group.is_active:
|
||||
raise NotFoundError('Knowledge base group not found')
|
||||
documents = run_db_read(
|
||||
'list_group_files',
|
||||
lambda: db.session.query(KbDocument)
|
||||
.options(joinedload(KbDocument.versions))
|
||||
.filter(KbDocument.group_id == group_id, KbDocument.is_deleted.is_(False))
|
||||
.order_by(KbDocument.updated_at.desc(), KbDocument.id.desc())
|
||||
.all(),
|
||||
)
|
||||
return jsonify([serialize_document(doc) for doc in documents])
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups/<int:group_id>/files', methods=['POST'])
|
||||
def create_group_file(group_id: int):
|
||||
current_user = require_user()
|
||||
path_upload_service.require_active_group(group_id)
|
||||
data = request.get_json(silent=True) or {}
|
||||
title = str(data.get('title') or '').strip()
|
||||
description = str(data.get('description') or '').strip() or None
|
||||
status = str(data.get('status') or 'draft').strip() or 'draft'
|
||||
if not title:
|
||||
raise ValidationError('title is required')
|
||||
existing = (
|
||||
db.session.query(KbDocument)
|
||||
.options(joinedload(KbDocument.versions))
|
||||
.filter(KbDocument.group_id == group_id, KbDocument.title == title)
|
||||
.first()
|
||||
)
|
||||
if existing and not existing.is_deleted:
|
||||
raise ValidationError('当前分组下已存在同名文档')
|
||||
if existing and existing.is_deleted:
|
||||
existing.is_deleted = False
|
||||
existing.description = description
|
||||
existing.status = status
|
||||
existing.updated_by_id = getattr(current_user, 'id', None)
|
||||
db.session.commit()
|
||||
return jsonify(serialize_document(existing)), 201
|
||||
document = KbDocument(
|
||||
group_id=group_id,
|
||||
title=title,
|
||||
description=description,
|
||||
status=status,
|
||||
source_type='manual',
|
||||
created_by_id=getattr(current_user, 'id', None),
|
||||
updated_by_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.commit()
|
||||
return jsonify(serialize_document(document)), 201
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups/<int:group_id>/path-upload-jobs', methods=['POST'])
|
||||
def create_path_upload_job(group_id: int):
|
||||
current_user = require_user()
|
||||
path_upload_service.require_active_group(group_id)
|
||||
job, reused = path_upload_service.create_path_upload_job(
|
||||
group_id,
|
||||
request.get_json(silent=True) or {},
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
payload = serialize_job(job)
|
||||
if reused:
|
||||
payload['reused_existing'] = True
|
||||
payload['message'] = payload.get('message') or '检测到未完成的路径上传任务,已自动续传'
|
||||
return jsonify(payload)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/files', methods=['POST'])
|
||||
def upload_path_job_file(job_id: int):
|
||||
current_user = require_user()
|
||||
job = path_upload_service.require_path_upload_job(job_id)
|
||||
try:
|
||||
job = path_upload_service.upload_path_job_file(
|
||||
job,
|
||||
file_storage=request.files.get('file'),
|
||||
relative_path_raw=request.form.get('relative_path'),
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc)) from exc
|
||||
db.session.commit()
|
||||
return jsonify(serialize_job(job)), 201
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/files/fail', methods=['POST'])
|
||||
def mark_path_job_file_failed(job_id: int):
|
||||
require_user()
|
||||
job = path_upload_service.require_path_upload_job(job_id)
|
||||
data = request.get_json(silent=True) or {}
|
||||
original_name = str(data.get('original_name') or '').strip() or None
|
||||
relative_path_raw = str(data.get('relative_path') or '').strip()
|
||||
error_message = str(data.get('error') or '路径文件上传失败').strip() or '路径文件上传失败'
|
||||
try:
|
||||
job = path_upload_service.mark_path_job_file_failed(
|
||||
job,
|
||||
relative_path_raw=relative_path_raw,
|
||||
original_name=original_name,
|
||||
error_message=error_message,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc)) from exc
|
||||
db.session.commit()
|
||||
return jsonify(serialize_job(job))
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/finalize', methods=['POST'])
|
||||
def finalize_path_upload_job(job_id: int):
|
||||
current_user = require_user()
|
||||
job = path_upload_service.require_path_upload_job(job_id)
|
||||
job, status_code = path_upload_service.finalize_path_upload_job(
|
||||
job,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
refreshed = db.session.get(KbJob, job.id)
|
||||
response_payload = serialize_job(refreshed or job)
|
||||
if status_code == 202:
|
||||
response_payload['queue_result'] = 'inline_per_file'
|
||||
response_payload['accepted'] = True
|
||||
return jsonify(response_payload), status_code
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/files', methods=['DELETE'])
|
||||
def delete_path_job_file(job_id: int):
|
||||
current_user = require_user()
|
||||
job = path_upload_service.require_path_upload_job(job_id)
|
||||
relative_path_raw = str(request.args.get('relative_path') or '').strip()
|
||||
if not relative_path_raw:
|
||||
raise ValidationError('relative_path is required')
|
||||
try:
|
||||
job, document_deleted, relative_path = path_upload_service.delete_path_job_file(
|
||||
job,
|
||||
relative_path_raw=relative_path_raw,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc)) from exc
|
||||
db.session.commit()
|
||||
return jsonify({
|
||||
'ok': True,
|
||||
'job': serialize_job(job),
|
||||
'document_deleted': document_deleted,
|
||||
'relative_path': relative_path,
|
||||
})
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/retry-failed', methods=['POST'])
|
||||
def retry_failed_path_upload_job(job_id: int):
|
||||
current_user = require_user()
|
||||
source_job = path_upload_service.require_path_upload_job(job_id)
|
||||
data = request.get_json(silent=True) or {}
|
||||
requested_paths = data.get('relative_paths') or []
|
||||
if not isinstance(requested_paths, list):
|
||||
requested_paths = []
|
||||
retry_job = path_upload_service.retry_failed_path_upload_job(
|
||||
source_job,
|
||||
relative_paths=requested_paths,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
refreshed = db.session.get(KbJob, retry_job.id)
|
||||
return jsonify(serialize_job(refreshed or retry_job)), 201
|
||||
@@ -1,97 +0,0 @@
|
||||
"""
|
||||
backend/app/api/kb/jobs.py
|
||||
|
||||
用途:知识库后台任务 API(列表、手动触发);序列化/取消 helper 来自 services/kb/job_lifecycle。
|
||||
依赖:kb.blueprint、kb.common、app.jobs、services/kb/job_lifecycle。
|
||||
逻辑:注册 /jobs 路由。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import jsonify
|
||||
|
||||
from app import db
|
||||
from app.api.kb.blueprint import knowledge_base_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.jobs import enqueue_kb_job
|
||||
from app.models import KbDocumentVersion, KbJob
|
||||
from app.services.kb.job_lifecycle import serialize_job
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/jobs', methods=['GET'])
|
||||
def list_jobs():
|
||||
"""
|
||||
返回最近 50 条 KbJob(登录用户可见)。
|
||||
核心逻辑:只读查询,经 run_db_read 处理瞬态 DB 错误。
|
||||
"""
|
||||
from app.api.kb.common import require_user, run_db_read
|
||||
|
||||
require_user()
|
||||
jobs = run_db_read(
|
||||
'list_jobs',
|
||||
lambda: db.session.query(KbJob)
|
||||
.order_by(KbJob.created_at.desc(), KbJob.id.desc())
|
||||
.limit(50)
|
||||
.all(),
|
||||
)
|
||||
return jsonify([serialize_job(job) for job in jobs])
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/jobs/<int:job_id>/run', methods=['POST'])
|
||||
@require_admin
|
||||
def run_job(job_id: int):
|
||||
"""
|
||||
管理员手动将 clean/sync_dify 任务重新提交后台执行。
|
||||
核心逻辑:重置 queued 状态后 enqueue_kb_job;已在队列中则 202 返回 already_queued。
|
||||
"""
|
||||
job = db.session.get(KbJob, job_id)
|
||||
if not job:
|
||||
raise NotFoundError('任务不存在')
|
||||
|
||||
if job.job_type not in ('clean', 'sync_dify'):
|
||||
raise ValidationError('当前仅支持手动执行 clean 或 sync_dify 任务')
|
||||
|
||||
if job.status in ('queued', 'running'):
|
||||
refreshed = db.session.get(KbJob, job_id)
|
||||
payload = serialize_job(refreshed) if refreshed else {'id': job_id}
|
||||
payload['accepted'] = True
|
||||
payload['queue_result'] = 'already_queued'
|
||||
payload['run_result'] = '任务已在后台处理中'
|
||||
return jsonify(payload), 202
|
||||
|
||||
version = db.session.get(KbDocumentVersion, job.document_version_id) if job.document_version_id else None
|
||||
|
||||
if job.job_type == 'clean':
|
||||
if not version:
|
||||
raise NotFoundError('关联文档版本不存在')
|
||||
job.status = 'queued'
|
||||
job.progress = 0
|
||||
job.started_at = None
|
||||
job.finished_at = None
|
||||
job.error_message = None
|
||||
job.message = '等待清洗任务执行'
|
||||
version.status = 'uploaded'
|
||||
version.error_message = None
|
||||
if version.document:
|
||||
version.document.status = 'uploaded'
|
||||
else:
|
||||
if not version:
|
||||
raise NotFoundError('关联文档版本不存在')
|
||||
job.status = 'queued'
|
||||
job.progress = 0
|
||||
job.started_at = None
|
||||
job.finished_at = None
|
||||
job.error_message = None
|
||||
job.message = '等待同步到 Dify'
|
||||
if version.status in ('failed', 'ready', 'synced'):
|
||||
version.error_message = None
|
||||
|
||||
db.session.commit()
|
||||
|
||||
_enqueued, queue_result = enqueue_kb_job(job.id)
|
||||
refreshed = db.session.get(KbJob, job_id)
|
||||
payload = serialize_job(refreshed) if refreshed else {'id': job_id}
|
||||
payload['accepted'] = True
|
||||
payload['queue_result'] = queue_result
|
||||
payload['run_result'] = '任务已提交后台异步执行'
|
||||
return jsonify(payload), 202
|
||||
@@ -1,10 +0,0 @@
|
||||
"""
|
||||
backend/app/api/knowledge_base.py
|
||||
|
||||
用途:知识库 API 兼容 shim(Wave 3 迁包过渡期)。
|
||||
依赖:app.api.kb。
|
||||
逻辑:旧 import 路径仍可用;新代码请用 app.api.kb。
|
||||
"""
|
||||
from app.api.kb import knowledge_base_bp
|
||||
|
||||
__all__ = ['knowledge_base_bp']
|
||||
@@ -1,231 +0,0 @@
|
||||
"""
|
||||
backend/app/api/maintenance.py
|
||||
|
||||
用途:设备维保助手 HTTP API,当前提供设备台账配置与 Excel 导入能力。
|
||||
依赖:JWT 当前用户、maintenance_ledger_service、Flask Blueprint/send_file。
|
||||
逻辑:查询接口面向会话与面板复用;写入/导入接口先做角色校验,再委托 service。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
|
||||
from flask import Blueprint, g, jsonify, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, UnauthorizedError, ValidationError
|
||||
from app.services.maintenance_ledger_service import (
|
||||
build_import_template,
|
||||
create_device,
|
||||
get_device,
|
||||
import_devices_from_excel,
|
||||
list_devices,
|
||||
update_device,
|
||||
_parse_date,
|
||||
)
|
||||
from app.services.maintenance_record_service import (
|
||||
build_records_import_template,
|
||||
build_records_export,
|
||||
create_record,
|
||||
delete_record,
|
||||
get_record,
|
||||
import_records_from_excel,
|
||||
list_records,
|
||||
update_record,
|
||||
)
|
||||
|
||||
maintenance_bp = Blueprint('maintenance', __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""确保当前请求存在登录用户。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _require_ledger_admin():
|
||||
"""
|
||||
校验设备维保管理权限。
|
||||
Returns:
|
||||
当前用户对象。
|
||||
Raises:
|
||||
ForbiddenError: 当前角色不允许写入台账或维修记录。
|
||||
"""
|
||||
user = _require_user()
|
||||
if getattr(user, 'role', None) not in {'admin', 'maintenance_manager'}:
|
||||
raise ForbiddenError('Maintenance manager privilege required')
|
||||
return user
|
||||
|
||||
|
||||
def _record_list_filters_from_request() -> dict[str, Any]:
|
||||
"""
|
||||
从请求参数解析维修记录列表/导出共用的筛选条件。
|
||||
核心逻辑:兼容 snake_case 与 camelCase 报修日期参数;日期非法时抛出 ValidationError。
|
||||
"""
|
||||
report_date_from = _parse_date(
|
||||
request.args.get('report_date_from') or request.args.get('reportDateFrom'),
|
||||
'reportDateFrom',
|
||||
)
|
||||
report_date_to = _parse_date(
|
||||
request.args.get('report_date_to') or request.args.get('reportDateTo'),
|
||||
'reportDateTo',
|
||||
)
|
||||
return {
|
||||
'keyword': request.args.get('keyword'),
|
||||
'device_code': request.args.get('device_code') or request.args.get('deviceCode'),
|
||||
'status': request.args.get('status'),
|
||||
'report_date_from': report_date_from,
|
||||
'report_date_to': report_date_to,
|
||||
}
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/devices', methods=['GET'])
|
||||
def list_ledger_devices():
|
||||
"""查询设备台账列表,供 Agent 查询结果与右侧台账配置面板使用。"""
|
||||
_require_user()
|
||||
result = list_devices(
|
||||
keyword=request.args.get('keyword'),
|
||||
status=request.args.get('status'),
|
||||
page=request.args.get('page', type=int) or 1,
|
||||
page_size=request.args.get('page_size', type=int) or 20,
|
||||
)
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/devices/<int:device_id>', methods=['GET'])
|
||||
def get_ledger_device(device_id: int):
|
||||
"""读取设备台账详情。"""
|
||||
_require_user()
|
||||
return jsonify(get_device(device_id))
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/devices', methods=['POST'])
|
||||
def create_ledger_device():
|
||||
"""新增设备台账,仅固定管理角色可用。"""
|
||||
user = _require_ledger_admin()
|
||||
payload = request.get_json() or {}
|
||||
return jsonify(create_device(payload, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/devices/<int:device_id>', methods=['PUT'])
|
||||
def update_ledger_device(device_id: int):
|
||||
"""更新设备台账,仅固定管理角色可用。"""
|
||||
user = _require_ledger_admin()
|
||||
payload = request.get_json() or {}
|
||||
return jsonify(update_device(device_id, payload, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/import-template', methods=['GET'])
|
||||
def download_ledger_import_template():
|
||||
"""下载设备台账 Excel 导入模板。"""
|
||||
_require_ledger_admin()
|
||||
return send_file(
|
||||
BytesIO(build_import_template()),
|
||||
as_attachment=True,
|
||||
download_name='maintenance_devices_import_template.xlsx',
|
||||
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
)
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/import', methods=['POST'])
|
||||
def import_ledger_devices():
|
||||
"""上传 Excel 模板并批量新增/更新设备台账。"""
|
||||
user = _require_ledger_admin()
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
raise ValidationError('file is required')
|
||||
result = import_devices_from_excel(upload, operator=user, request_id=getattr(g, 'request_id', None))
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@maintenance_bp.route('/records', methods=['GET'])
|
||||
def list_maintenance_records():
|
||||
"""查询设备维修记录,供 Agent 会话查询和结果卡片使用。"""
|
||||
_require_user()
|
||||
filters = _record_list_filters_from_request()
|
||||
result = list_records(
|
||||
keyword=filters['keyword'],
|
||||
device_code=filters['device_code'],
|
||||
status=filters['status'],
|
||||
report_date_from=filters['report_date_from'],
|
||||
report_date_to=filters['report_date_to'],
|
||||
page=request.args.get('page', type=int) or 1,
|
||||
page_size=request.args.get('page_size', type=int) or 20,
|
||||
)
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/<int:record_id>', methods=['GET'])
|
||||
def get_maintenance_record(record_id: int):
|
||||
"""读取设备维修记录详情。"""
|
||||
_require_user()
|
||||
return jsonify(get_record(record_id))
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/export', methods=['GET'])
|
||||
def export_maintenance_records():
|
||||
"""按当前筛选条件导出设备维修记录 Excel。"""
|
||||
_require_ledger_admin()
|
||||
filters = _record_list_filters_from_request()
|
||||
data = build_records_export(
|
||||
keyword=filters['keyword'],
|
||||
device_code=filters['device_code'],
|
||||
status=filters['status'],
|
||||
report_date_from=filters['report_date_from'],
|
||||
report_date_to=filters['report_date_to'],
|
||||
)
|
||||
return send_file(
|
||||
BytesIO(data),
|
||||
as_attachment=True,
|
||||
download_name='maintenance_records.xlsx',
|
||||
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
)
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/import-template', methods=['GET'])
|
||||
def download_records_import_template():
|
||||
"""下载维修记录 Excel 导入模板。"""
|
||||
_require_ledger_admin()
|
||||
return send_file(
|
||||
BytesIO(build_records_import_template()),
|
||||
as_attachment=True,
|
||||
download_name='maintenance_record_history_template.xls',
|
||||
mimetype='application/vnd.ms-excel',
|
||||
)
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/import', methods=['POST'])
|
||||
def import_maintenance_records():
|
||||
"""上传 Excel 模板并批量新增维修记录。"""
|
||||
user = _require_ledger_admin()
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
raise ValidationError('file is required')
|
||||
result = import_records_from_excel(upload, operator=user, request_id=getattr(g, 'request_id', None))
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@maintenance_bp.route('/records', methods=['POST'])
|
||||
def create_maintenance_record():
|
||||
"""新增设备维修记录,仅固定管理角色可用。"""
|
||||
user = _require_ledger_admin()
|
||||
payload = request.get_json() or {}
|
||||
return jsonify(create_record(payload, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/<int:record_id>', methods=['PUT'])
|
||||
def update_maintenance_record(record_id: int):
|
||||
"""更新设备维修记录,仅固定管理角色可用。"""
|
||||
user = _require_ledger_admin()
|
||||
payload = request.get_json() or {}
|
||||
return jsonify(update_record(record_id, payload, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/<int:record_id>', methods=['DELETE'])
|
||||
def delete_maintenance_record(record_id: int):
|
||||
"""删除设备维修记录,仅固定管理角色可用。"""
|
||||
user = _require_ledger_admin()
|
||||
return jsonify(delete_record(record_id, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||
@@ -1,149 +0,0 @@
|
||||
"""
|
||||
backend/app/api/maintenance_tools.py
|
||||
|
||||
用途:设备维保助手 Dify Tool API,只开放只读查询工具。
|
||||
依赖:maintenance_chat_service、maintenance_record_service、OpenAPI 构建、Tool API 基地址解析。
|
||||
逻辑:Dify 复杂问法调用本蓝图查询设备台账/维修记录;明确查询仍由 chat.py 本地直答,写操作仍走 HXOPS 管理面板。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError, ValidationError
|
||||
from app.models import MaintenanceRecord
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
|
||||
from app.services.maintenance_chat_service import build_device_query_result
|
||||
from app.services.maintenance_record_service import serialize_record
|
||||
from app.services.maintenance_tools.openapi_spec import build_maintenance_openapi_spec
|
||||
|
||||
maintenance_tool_bp = Blueprint("maintenance_tools", __name__)
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验设备维保 Tool API 鉴权。
|
||||
AI 触发时机:Dify Tool 调用本蓝图时由 before_request 自动执行,不是给 LLM 直接调用的业务工具。
|
||||
"""
|
||||
configured = str(
|
||||
current_app.config.get("MAINTENANCE_TOOL_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
or ""
|
||||
).strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError(
|
||||
"MAINTENANCE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured",
|
||||
code="missing_auth",
|
||||
)
|
||||
|
||||
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||
if configured in {token, integration_key}:
|
||||
return
|
||||
if not token and not integration_key:
|
||||
raise UnauthorizedError("missing_auth")
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
"""把 AppError 归一成 Dify Tool 侧可读错误码。"""
|
||||
message = str(exc.message or "").strip()
|
||||
if message in {"missing_auth", "invalid_auth"}:
|
||||
return message
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
return "missing_auth"
|
||||
if exc.code == "VALIDATION.INVALID_PARAM":
|
||||
return message or "invalid_request"
|
||||
return exc.code
|
||||
|
||||
|
||||
@maintenance_tool_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
"""Tool API 统一错误响应。"""
|
||||
return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status
|
||||
|
||||
|
||||
@maintenance_tool_bp.before_request
|
||||
def _verify_tool_access():
|
||||
"""除 OpenAPI 文档外,所有 Tool 调用必须携带有效服务级 token。"""
|
||||
if request.path.endswith("/openapi.json") or request.path.endswith("/openapi.dify.yaml"):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
def _payload() -> dict:
|
||||
"""读取 JSON 请求体。"""
|
||||
return request.get_json(silent=True) or {}
|
||||
|
||||
|
||||
def _clean_text(value) -> str:
|
||||
return str(value or "").strip()
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def openapi_spec():
|
||||
"""返回 Dify 导入用的 OpenAPI JSON。"""
|
||||
return jsonify(build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/openapi.dify.yaml", methods=["GET"])
|
||||
def openapi_dify_yaml():
|
||||
"""返回 Dify 导入用的 OpenAPI YAML。"""
|
||||
import yaml
|
||||
|
||||
body = yaml.safe_dump(
|
||||
build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()),
|
||||
allow_unicode=True,
|
||||
sort_keys=False,
|
||||
)
|
||||
return current_app.response_class(body, mimetype="text/yaml; charset=utf-8")
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/query_device", methods=["POST"])
|
||||
def query_device():
|
||||
"""按设备编号或名称查询设备台账,并可带出最近维修记录。"""
|
||||
data = _payload()
|
||||
keyword = _clean_text(data.get("keyword"))
|
||||
if not keyword:
|
||||
raise ValidationError("keyword is required")
|
||||
include_records = bool(data.get("include_records", True))
|
||||
record_limit = max(0, min(20, int(data.get("record_limit") or 5)))
|
||||
result = build_device_query_result(keyword, include_records=include_records, record_limit=record_limit)
|
||||
return jsonify({"ok": True, **result})
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/query_records", methods=["POST"])
|
||||
def query_records():
|
||||
"""按设备编号/名称和状态查询维修记录。"""
|
||||
data = _payload()
|
||||
keyword = _clean_text(data.get("keyword"))
|
||||
if not keyword:
|
||||
raise ValidationError("keyword is required")
|
||||
status = _clean_text(data.get("status"))
|
||||
limit = max(1, min(50, int(data.get("limit") or 10)))
|
||||
|
||||
query = db.session.query(MaintenanceRecord)
|
||||
like = f"%{keyword}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
MaintenanceRecord.device_code.ilike(like),
|
||||
MaintenanceRecord.device_name.ilike(like),
|
||||
)
|
||||
)
|
||||
if status:
|
||||
query = query.filter(MaintenanceRecord.repair_status == status)
|
||||
rows = query.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc()).limit(limit).all()
|
||||
return jsonify({
|
||||
"ok": True,
|
||||
"matched": bool(rows),
|
||||
"keyword": keyword,
|
||||
"items": [serialize_record(item) for item in rows],
|
||||
"totalReturned": len(rows),
|
||||
})
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
"""
|
||||
backend/app/api/schedule/__init__.py
|
||||
|
||||
用途:排程管理 Blueprint 入口(Wave 3 分包)。
|
||||
依赖:schedule/blueprint.py、config、tasks、runs、platform_tasks。
|
||||
逻辑:import 子模块注册路由;register_blueprints 从本包 import schedule_admin_bp。
|
||||
"""
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
|
||||
import app.api.schedule.common # noqa: F401
|
||||
import app.api.schedule.config # noqa: F401
|
||||
import app.api.schedule.tasks # noqa: F401
|
||||
import app.api.schedule.runs # noqa: F401
|
||||
import app.api.schedule.platform_tasks # noqa: F401
|
||||
import app.api.schedule.rpa_workers # noqa: F401
|
||||
|
||||
__all__ = ['schedule_admin_bp']
|
||||
@@ -1,10 +0,0 @@
|
||||
"""
|
||||
backend/app/api/schedule/blueprint.py
|
||||
|
||||
用途:排程管理 API 共享 Blueprint(Wave 3 分包后各子模块共用)。
|
||||
依赖:Flask Blueprint。
|
||||
逻辑:config/tasks/runs 子模块在此 bp 上注册路由;__init__ 导出 schedule_admin_bp。
|
||||
"""
|
||||
from flask import Blueprint
|
||||
|
||||
schedule_admin_bp = Blueprint('schedule_admin', __name__)
|
||||
@@ -1,59 +0,0 @@
|
||||
"""
|
||||
backend/app/api/schedule/common.py
|
||||
|
||||
用途:排程 API 共享序列化 helper。
|
||||
依赖:models、services/schedule/query_service。
|
||||
逻辑:config/tasks 子模块导出任务配置 JSON 时共用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.models import ScheduleTask, ScheduleTaskConfig
|
||||
from app.services.schedule.query_service import serialize_task
|
||||
from app.services.schedule.serialization import safe_json_value
|
||||
|
||||
|
||||
def serialize_task_config(cfg_model: ScheduleTaskConfig) -> dict:
|
||||
"""
|
||||
将 ScheduleTaskConfig ORM 转为 API 响应 dict。
|
||||
核心逻辑:扁平化 data_source / external_api 嵌套结构。
|
||||
"""
|
||||
return {
|
||||
'row_id_key': cfg_model.row_id_key or 'id',
|
||||
'log_prefix': cfg_model.log_prefix or '',
|
||||
'base_fetch_sql': cfg_model.base_fetch_sql or '',
|
||||
'fetch_where_conditions': cfg_model.fetch_where_conditions or '',
|
||||
'fetch_order_by': cfg_model.fetch_order_by or '',
|
||||
'writeback_sql': cfg_model.writeback_sql or '',
|
||||
'detail_sql': cfg_model.detail_sql or '',
|
||||
'alias_order': cfg_model.alias_order or [],
|
||||
'detail_alias_order': cfg_model.detail_alias_order or [],
|
||||
'header_labels': cfg_model.header_labels or {},
|
||||
'data_source': {
|
||||
'db_type': cfg_model.ds_db_type or 'sqlserver',
|
||||
'host': cfg_model.ds_host or '',
|
||||
'port': cfg_model.ds_port or '',
|
||||
'database': cfg_model.ds_database or '',
|
||||
'username': cfg_model.ds_username or '',
|
||||
'password': cfg_model.ds_password or '',
|
||||
'driver': cfg_model.ds_driver or '',
|
||||
'encrypt': cfg_model.ds_encrypt or '',
|
||||
'trust_cert': cfg_model.ds_trust_cert or '',
|
||||
},
|
||||
'external_api': {
|
||||
'url': cfg_model.api_url or '',
|
||||
'method': cfg_model.api_method or 'POST',
|
||||
'headers': cfg_model.api_headers or {},
|
||||
'body_template': cfg_model.api_body_template or '',
|
||||
},
|
||||
'dify_system_prompt': cfg_model.dify_system_prompt or '',
|
||||
}
|
||||
|
||||
|
||||
def serialize_task_for_export(task: ScheduleTask, cfg_model: ScheduleTaskConfig | None) -> dict:
|
||||
"""组装单条排程导出 JSON(含 config 快照)。"""
|
||||
payload = serialize_task(task)
|
||||
payload['config'] = serialize_task_config(cfg_model) if cfg_model else None
|
||||
return payload
|
||||
|
||||
|
||||
__all__ = ['safe_json_value', 'serialize_task_config', 'serialize_task_for_export']
|
||||
@@ -1,111 +0,0 @@
|
||||
"""
|
||||
backend/app/api/schedule/config.py
|
||||
|
||||
用途:排程任务 SQL/数据源配置 API 与测试接口(薄路由层)。
|
||||
依赖:schedule.blueprint、schedule.common、schedule_contract、services/schedule/*。
|
||||
逻辑:/schedule-config/* 路由;配置更新仅允许 data_pipeline 任务修改 data_source_type。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
from app.api.schedule.common import serialize_task_config
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import ScheduleTask, ScheduleTaskConfig
|
||||
from app.services.schedule.schedule_contract import (
|
||||
SCHEDULE_TYPE_DATA_PIPELINE,
|
||||
apply_schedule_contract_to_payload,
|
||||
platform_job_allows_config,
|
||||
)
|
||||
from app.services.schedule.sql_config import upsert_schedule_task_config
|
||||
from app.services.schedule.sql_preview_service import preview_fetch_sql
|
||||
from app.services.schedule.test_run_service import execute_test_run
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_task_config(task_id: int):
|
||||
"""返回排程任务关联的 SQL/数据源配置。"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if not cfg_model:
|
||||
return jsonify({'data_source_type': task.data_source_type, 'config': None})
|
||||
return jsonify({'data_source_type': task.data_source_type, 'config': serialize_task_config(cfg_model)})
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_schedule_task_config(task_id: int):
|
||||
"""
|
||||
更新排程 data_source_type 与 ScheduleTaskConfig。
|
||||
核心逻辑:仅 data_pipeline 允许改 data_source_type;platform_job 禁止经此接口绕过契约。
|
||||
"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
if task.schedule_type != SCHEDULE_TYPE_DATA_PIPELINE:
|
||||
if 'data_source_type' in data:
|
||||
raise ValidationError(
|
||||
'data_source_type can only be updated for data_pipeline schedules; '
|
||||
'use schedule task PATCH for platform_job'
|
||||
)
|
||||
elif 'data_source_type' in data:
|
||||
contract = apply_schedule_contract_to_payload({
|
||||
'schedule_type': task.schedule_type,
|
||||
'data_source_type': data.get('data_source_type'),
|
||||
'platform_api_path': task.platform_api_path,
|
||||
})
|
||||
task.data_source_type = contract['data_source_type']
|
||||
|
||||
config_data = data.get('config', data)
|
||||
if isinstance(config_data, dict) and config_data:
|
||||
# platform_job 仅白名单且 enabled 的任务(如 shipping-inventory-rpa)允许写 ScheduleTaskConfig
|
||||
if task.schedule_type != SCHEDULE_TYPE_DATA_PIPELINE and not platform_job_allows_config(task.platform_api_path):
|
||||
raise ValidationError(
|
||||
f"platform_job '{task.platform_api_path}' does not accept ScheduleTaskConfig"
|
||||
)
|
||||
upsert_schedule_task_config(task_id, config_data, commit=False)
|
||||
db.session.commit()
|
||||
cfg_model = task.config
|
||||
if cfg_model is None:
|
||||
with db.session.no_autoflush:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
return jsonify({
|
||||
'data_source_type': task.data_source_type,
|
||||
'config': serialize_task_config(cfg_model) if cfg_model else None,
|
||||
})
|
||||
except ValidationError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ValidationError(str(exc))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-sql', methods=['POST'])
|
||||
@require_admin
|
||||
def test_schedule_sql(task_id: int):
|
||||
"""预览抓取 SQL 执行结果(最多 100 行)。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return jsonify(preview_fetch_sql(task_id, data))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-run', methods=['POST'])
|
||||
@require_admin
|
||||
def test_schedule_run(task_id: int):
|
||||
"""同步执行小规模排程测试跑(默认 3 条),可选 KB 同步。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = execute_test_run(
|
||||
task_id,
|
||||
data,
|
||||
triggered_by_user_id=getattr(get_current_user(), 'id', None),
|
||||
)
|
||||
return jsonify(payload)
|
||||
@@ -1,59 +0,0 @@
|
||||
"""
|
||||
backend/app/api/schedule/platform_tasks.py
|
||||
|
||||
用途:平台任务契约 API(任务定义 + 动态选项),供前端 DynamicTaskParamsForm 通用渲染。
|
||||
依赖:schedule.blueprint、job_registry(任务契约中心)、job_options(options_source 分发)。
|
||||
逻辑:/platform-tasks/definitions 下发 params_schema(仅 enabled);/platform-tasks/options 按 source 返回统一选项;
|
||||
前端不再按任务硬编码 UI,红框参数区完全由 schema 决定。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import request
|
||||
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.schedule.job_options import list_job_options
|
||||
from app.services.schedule.job_registry import list_platform_jobs
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/platform-tasks/definitions', methods=['GET'])
|
||||
@require_admin
|
||||
def get_platform_task_definitions():
|
||||
"""
|
||||
返回全部启用平台任务的完整契约(展示信息 + params_schema + defaults)。
|
||||
核心逻辑:直接序列化 job_registry 注册项;前端选择任务后按 params_schema 渲染参数表单。
|
||||
"""
|
||||
return ok([
|
||||
{
|
||||
'task_type': job.key,
|
||||
'label': job.label,
|
||||
'label_key': job.label_key or None,
|
||||
'description': job.description,
|
||||
'description_key': job.description_key or None,
|
||||
'category': job.category,
|
||||
'enabled': job.enabled,
|
||||
'params_schema': list(job.params_schema),
|
||||
'defaults': job.defaults,
|
||||
}
|
||||
for job in list_platform_jobs()
|
||||
if job.enabled
|
||||
])
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/platform-tasks/options', methods=['GET'])
|
||||
@require_admin
|
||||
def get_platform_task_options():
|
||||
"""
|
||||
按 options_source 返回动态选项(统一 {label, value, description?})。
|
||||
核心逻辑:source 参数分发到 job_options 登记的 provider;前端不感知数据来源。
|
||||
"""
|
||||
source = str(request.args.get('source') or '').strip()
|
||||
if not source:
|
||||
raise ValidationError('source is required')
|
||||
try:
|
||||
options = list_job_options(source)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc))
|
||||
return ok(options)
|
||||
@@ -1,24 +0,0 @@
|
||||
"""
|
||||
backend/app/api/schedule/rpa_workers.py
|
||||
|
||||
用途:管理端查询货代库存 RPA Worker 在线状态与就绪摘要。
|
||||
依赖:schedule.blueprint、rpa_worker_heartbeat.serialize_rpa_worker_status。
|
||||
逻辑:ScheduleWorkbenchPanel 在库存 RPA 排程工作台展示 worker 心跳状态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.response import ok
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import serialize_rpa_worker_status
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/rpa-workers/status', methods=['GET'])
|
||||
@require_admin
|
||||
def get_rpa_workers_status():
|
||||
"""
|
||||
返回库存 RPA Worker 心跳摘要(在线/离线、最后心跳时间、就绪原因)。
|
||||
核心逻辑:读取 Redis/内存心跳并与当前环境、trigger 目录比对。
|
||||
"""
|
||||
return ok(serialize_rpa_worker_status())
|
||||
@@ -1,158 +0,0 @@
|
||||
"""
|
||||
backend/app/api/schedule/runs.py
|
||||
|
||||
用途:排程运行触发与运行记录查询 API。
|
||||
依赖:schedule.blueprint、services/schedule/query_service、scheduler_service。
|
||||
逻辑:/schedules/<id>/run、/schedules/<id>/runs、/schedule-runs/* 路由。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from io import BytesIO
|
||||
|
||||
from flask import current_app, jsonify, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import ConflictError, NotFoundError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.schedule.query_service import get_run, list_runs, serialize_run
|
||||
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import recover_stale_awaiting_rpa_schedule_runs
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
|
||||
@require_admin
|
||||
def run_schedule(task_id: int):
|
||||
"""
|
||||
手动触发排程后台执行。
|
||||
核心逻辑:创建 running ScheduleRun → 守护线程内 run_task_now。
|
||||
"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
recover_stale_awaiting_rpa_schedule_runs(task)
|
||||
user = get_current_user()
|
||||
existing = (
|
||||
db.session.query(ScheduleRun)
|
||||
.filter(ScheduleRun.schedule_task_id == task.id, ScheduleRun.status == 'running')
|
||||
.first()
|
||||
)
|
||||
if existing:
|
||||
raise ConflictError('该排程正在执行中,请等待完成后再试', details={'run_id': existing.id})
|
||||
run = ScheduleRun(
|
||||
run_no=_generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
trigger_type='manual',
|
||||
triggered_by_user_id=getattr(user, 'id', None),
|
||||
started_at=datetime.utcnow(),
|
||||
status='running',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
app = current_app._get_current_object()
|
||||
run_id = run.id
|
||||
|
||||
def _background():
|
||||
with app.app_context():
|
||||
t = db.session.get(ScheduleTask, task_id)
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if not t or not r:
|
||||
return
|
||||
try:
|
||||
run_task_now(t, trigger_type='manual', triggered_by_user_id=r.triggered_by_user_id, run=r)
|
||||
except Exception as exc:
|
||||
try:
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if r and r.status == 'running':
|
||||
r.status = 'failed'
|
||||
r.error_message = str(exc)
|
||||
r.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
current_app.logger.error('[schedule-run] run_id=%s failed: %s', run_id, exc, exc_info=True)
|
||||
|
||||
t = threading.Thread(target=_background, daemon=True, name=f'schedule-run-{run_id}')
|
||||
t.start()
|
||||
fresh = db.session.get(ScheduleRun, run_id)
|
||||
return jsonify(serialize_run(fresh))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/runs', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_runs(task_id: int):
|
||||
"""按任务 ID 分页/过滤返回运行记录。"""
|
||||
status = str(request.args.get('status') or '').strip() or None
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
started_after = None
|
||||
started_before = None
|
||||
sa = request.args.get('started_after')
|
||||
sb = request.args.get('started_before')
|
||||
if sa:
|
||||
try:
|
||||
started_after = datetime.fromisoformat(sa.replace('Z', '+00:00'))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
if sb:
|
||||
try:
|
||||
started_before = datetime.fromisoformat(sb.replace('Z', '+00:00'))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
return jsonify(
|
||||
list_runs(
|
||||
task_id=task_id,
|
||||
status=status,
|
||||
started_after=started_after,
|
||||
started_before=started_before,
|
||||
limit=limit,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_run(run_id: int):
|
||||
"""返回单条运行记录详情。"""
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(serialize_run(run))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_run_excel(run_id: int):
|
||||
"""下载运行结果 Excel 附件。"""
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError('Excel not found')
|
||||
buf = BytesIO(run.excel_file_data)
|
||||
return send_file(
|
||||
buf,
|
||||
as_attachment=True,
|
||||
download_name=run.excel_file_name or 'result.xlsx',
|
||||
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
)
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/inventory-raw-zip', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_run_inventory_raw_zip(run_id: int):
|
||||
"""下载库存 RPA 排程 run 的原始库存 Excel 打包(ZIP + manifest)。"""
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
zip_path, file_name = resolve_inventory_raw_zip_download(run)
|
||||
return send_file(
|
||||
zip_path,
|
||||
as_attachment=True,
|
||||
download_name=file_name,
|
||||
mimetype='application/zip',
|
||||
)
|
||||
@@ -1,282 +0,0 @@
|
||||
"""
|
||||
backend/app/api/schedule/tasks.py
|
||||
|
||||
用途:排程任务 CRUD、导入导出、启用/禁用 API。
|
||||
依赖:schedule.blueprint、schedule.common、services/schedule/*。
|
||||
逻辑:/schedules* 路由(不含 run 触发与运行记录);job_params 归一化与切换重置
|
||||
由 scheduler_service.create_task/update_task 唯一兜底;本层只做请求校验与
|
||||
ValueError→ValidationError 映射。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Response, jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
from app.api.schedule.common import serialize_task_for_export
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig
|
||||
from app.services.schedule.query_service import list_tasks, serialize_task
|
||||
from app.services.schedule.import_service import import_schedules_from_payload
|
||||
from app.services.schedule.schedule_contract import (
|
||||
apply_schedule_contract_to_payload,
|
||||
assert_schedule_config_writable,
|
||||
)
|
||||
from app.services.schedule.scheduler_service import create_task, update_task
|
||||
from app.services.schedule.sql_config import upsert_schedule_task_config
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedules():
|
||||
"""返回全部排程任务列表。"""
|
||||
return jsonify(list_tasks())
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule/platform-jobs', methods=['GET'])
|
||||
@require_admin
|
||||
def get_platform_jobs():
|
||||
"""
|
||||
返回 Job Registry 已启用平台任务列表,供前端下拉动态加载。
|
||||
与 /platform-tasks/definitions 一致:只返回 enabled=True,避免下拉可选却无参数定义。
|
||||
"""
|
||||
from app.services.schedule.job_registry import list_platform_jobs
|
||||
|
||||
return jsonify([
|
||||
{
|
||||
'key': job.key,
|
||||
'label_key': job.label_key or None,
|
||||
'label': job.label,
|
||||
'description': job.description,
|
||||
'enabled': job.enabled,
|
||||
}
|
||||
for job in list_platform_jobs()
|
||||
if job.enabled
|
||||
])
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/export', methods=['GET'])
|
||||
@require_admin
|
||||
def export_schedule(task_id: int):
|
||||
"""导出单条排程任务及配置为 JSON 文件。"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
payload = {
|
||||
'schema_version': 1,
|
||||
'exported_at': datetime.utcnow().isoformat(),
|
||||
'schedules': [serialize_task_for_export(task, cfg_model)],
|
||||
}
|
||||
body = json.dumps(payload, ensure_ascii=False, indent=2)
|
||||
filename = f"{task.schedule_no or f'schedule_{task.id}'}_export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
|
||||
return Response(
|
||||
body,
|
||||
mimetype='application/json; charset=utf-8',
|
||||
headers={'Content-Disposition': f'attachment; filename="{filename}"'},
|
||||
)
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/import', methods=['POST'])
|
||||
@require_admin
|
||||
def import_schedules():
|
||||
"""批量导入排程 JSON(按 schedule_no upsert)。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
user = get_current_user()
|
||||
result = import_schedules_from_payload(
|
||||
data.get('schedules'),
|
||||
actor_id=getattr(user, 'id', None),
|
||||
)
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules', methods=['POST'])
|
||||
@require_admin
|
||||
def post_schedule():
|
||||
"""创建排程任务。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
user = get_current_user()
|
||||
schedule_type = str(data.get('schedule_type') or 'data_pipeline')
|
||||
data_source_type = data.get('data_source_type')
|
||||
platform_api_path = data.get('platform_api_path')
|
||||
config_data = data.get('config')
|
||||
if config_data is not None and not isinstance(config_data, dict):
|
||||
raise ValidationError('config must be a JSON object')
|
||||
if schedule_type.strip().lower() == 'data_pipeline' and data_source_type in (None, ''):
|
||||
data_source_type = 'database'
|
||||
try:
|
||||
# [STEP 1] 契约与 config 写入权限预校验(失败不落库);job_params 由 create_task 归一化
|
||||
contract = apply_schedule_contract_to_payload({
|
||||
'schedule_type': schedule_type,
|
||||
'data_source_type': data_source_type,
|
||||
'platform_api_path': platform_api_path,
|
||||
})
|
||||
assert_schedule_config_writable(
|
||||
schedule_type=contract['schedule_type'],
|
||||
platform_api_path=contract['platform_api_path'],
|
||||
config=config_data,
|
||||
)
|
||||
task = create_task(
|
||||
name=str(data.get('name') or '').strip(),
|
||||
schedule_type=schedule_type,
|
||||
owner_user_id=int(data.get('owner_user_id')),
|
||||
cron_expr=str(data.get('cron_expr') or '').strip(),
|
||||
schedule_timezone=data.get('schedule_timezone'),
|
||||
wait_seconds=int(data.get('wait_seconds') or 0),
|
||||
dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None,
|
||||
platform_api_path=str(platform_api_path).strip() if platform_api_path else None,
|
||||
data_source_type=str(data_source_type) if data_source_type is not None else None,
|
||||
job_params=data.get('job_params'),
|
||||
notify_user_ids_json=data.get('notify_user_ids_json')
|
||||
if isinstance(data.get('notify_user_ids_json'), list)
|
||||
else [],
|
||||
notify_enabled=bool(data.get('notify_enabled', True)),
|
||||
enabled=bool(data.get('enabled', True)),
|
||||
kb_sync_enabled=bool(data.get('kb_sync_enabled', False)),
|
||||
kb_group_id=int(data.get('kb_group_id')) if data.get('kb_group_id') not in (None, '', 0, '0') else None,
|
||||
actor_id=getattr(user, 'id', None),
|
||||
commit=not config_data,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc))
|
||||
if config_data:
|
||||
try:
|
||||
upsert_schedule_task_config(task.id, config_data, commit=False)
|
||||
if not task.dify_agent_id:
|
||||
cfg_model = task.config
|
||||
if cfg_model is None:
|
||||
with db.session.no_autoflush:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
|
||||
if cfg_model and cfg_model.dify_system_prompt:
|
||||
cfg_model.dify_system_prompt = None
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
raise
|
||||
db.session.refresh(task)
|
||||
return jsonify(serialize_task(task)), 201
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule(task_id: int):
|
||||
"""返回单条排程任务详情。"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['PATCH'])
|
||||
@require_admin
|
||||
def patch_schedule(task_id: int):
|
||||
"""更新排程任务字段与关联配置。"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
user = get_current_user()
|
||||
config_data = data.get('config')
|
||||
if config_data is not None and not isinstance(config_data, dict):
|
||||
raise ValidationError('config must be a JSON object')
|
||||
try:
|
||||
# [STEP 1] 契约与 config 预校验;job_params 重置/归一化由 update_task 唯一兜底
|
||||
contract = apply_schedule_contract_to_payload({
|
||||
'schedule_type': data.get('schedule_type', task.schedule_type),
|
||||
'data_source_type': data.get('data_source_type', task.data_source_type),
|
||||
'platform_api_path': data.get('platform_api_path', task.platform_api_path),
|
||||
})
|
||||
assert_schedule_config_writable(
|
||||
schedule_type=contract['schedule_type'],
|
||||
platform_api_path=contract['platform_api_path'],
|
||||
config=config_data,
|
||||
)
|
||||
task = update_task(
|
||||
task,
|
||||
payload=data,
|
||||
actor_id=getattr(user, 'id', None),
|
||||
commit=not config_data,
|
||||
)
|
||||
if config_data:
|
||||
upsert_schedule_task_config(task_id, config_data, commit=False)
|
||||
if not task.dify_agent_id:
|
||||
cfg_model = task.config
|
||||
if cfg_model is None:
|
||||
with db.session.no_autoflush:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if cfg_model and cfg_model.dify_system_prompt:
|
||||
cfg_model.dify_system_prompt = None
|
||||
if config_data:
|
||||
db.session.commit()
|
||||
except ValueError as exc:
|
||||
db.session.rollback()
|
||||
raise ValidationError(str(exc))
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
raise
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_schedule(task_id: int):
|
||||
"""删除排程任务及其运行记录;中断进行中的 run。"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.schedule.scheduler_service import request_cancel_run
|
||||
|
||||
running_runs = (
|
||||
db.session.query(ScheduleRun)
|
||||
.filter(ScheduleRun.schedule_task_id == task_id, ScheduleRun.status == 'running')
|
||||
.all()
|
||||
)
|
||||
for rr in running_runs:
|
||||
request_cancel_run(rr.id)
|
||||
rr.status = 'failed'
|
||||
rr.error_message = '排程已被删除,执行中断'
|
||||
rr.finished_at = datetime.utcnow()
|
||||
if running_runs:
|
||||
db.session.commit()
|
||||
db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False)
|
||||
db.session.delete(task)
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/enable', methods=['POST'])
|
||||
@require_admin
|
||||
def enable_schedule(task_id: int):
|
||||
"""
|
||||
启用排程并重新计算 next_run_at。
|
||||
核心逻辑:委托 enable_task 重新校验契约与 job_params,拒绝已停用 platform_job 重新入队。
|
||||
"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.schedule.scheduler_service import enable_task
|
||||
|
||||
try:
|
||||
task = enable_task(task)
|
||||
except ValueError as exc:
|
||||
db.session.rollback()
|
||||
raise ValidationError(str(exc)) from exc
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/disable', methods=['POST'])
|
||||
@require_admin
|
||||
def disable_schedule(task_id: int):
|
||||
"""禁用排程并清空 next_run_at。"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
task.enabled = False
|
||||
task.next_run_at = None
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
@@ -1,10 +0,0 @@
|
||||
"""
|
||||
backend/app/api/schedule_admin.py
|
||||
|
||||
用途:排程 API 兼容 shim(Wave 3 迁包过渡期)。
|
||||
依赖:app.api.schedule。
|
||||
逻辑:旧 import 路径仍可用;新代码请用 app.api.schedule。
|
||||
"""
|
||||
from app.api.schedule import schedule_admin_bp
|
||||
|
||||
__all__ = ['schedule_admin_bp']
|
||||
@@ -1,392 +0,0 @@
|
||||
"""
|
||||
api/shipping_notice_tools.py
|
||||
|
||||
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。
|
||||
依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url。
|
||||
逻辑:Tool 成功响应仍用 status: ok/failed 业务 envelope;HTTP 级参数/资源错误统一 raise AppError。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
)
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
|
||||
from app.services.shipping_notice.query_service import (
|
||||
EXPORT_MIME_TYPE,
|
||||
get_batch_by_no,
|
||||
get_focus_task_for_batch,
|
||||
get_task_by_ref,
|
||||
get_task_in_batch,
|
||||
list_batch_task_summaries,
|
||||
resolve_task_export_download,
|
||||
serialize_batch_summary,
|
||||
serialize_task_summary,
|
||||
task_export_error_message,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import switch_batch_focus
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import record_rpa_worker_heartbeat
|
||||
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||
|
||||
shipping_notice_bp = Blueprint("shipping_notice", __name__)
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验货代 Tool API 鉴权 Header。
|
||||
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;当 Dify、RPA 或外部系统请求本蓝图时由 before_request 自动触发。
|
||||
|
||||
核心逻辑:只接受 `Authorization: Bearer <token>` 或 `X-Integration-Key`。
|
||||
货代专用 `SHIPPING_NOTICE_TOOL_API_KEY` 优先,未配置时回退 `INTEGRATION_API_KEY`;
|
||||
未配置任何可用 key 时报服务不可用,缺失或错误时报未授权。
|
||||
"""
|
||||
configured = str(
|
||||
current_app.config.get('SHIPPING_NOTICE_TOOL_API_KEY')
|
||||
or current_app.config.get('INTEGRATION_API_KEY')
|
||||
or ''
|
||||
).strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError(
|
||||
'SHIPPING_NOTICE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured',
|
||||
code='missing_auth',
|
||||
)
|
||||
bearer = str(request.headers.get('Authorization') or '').strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith('bearer ') else ''
|
||||
integration_key = str(request.headers.get('X-Integration-Key') or '').strip()
|
||||
if configured in {token, integration_key}:
|
||||
return
|
||||
if not token and (not integration_key):
|
||||
raise UnauthorizedError('missing_auth')
|
||||
raise UnauthorizedError('invalid_auth')
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
"""统一归一化 Tool API 的错误码,保持与文件检核 Tool 返回风格一致。"""
|
||||
message = str(exc.message or '').strip()
|
||||
if message in {'missing_auth', 'invalid_auth'}:
|
||||
return message
|
||||
if exc.code == 'AUTH.UNAUTHORIZED':
|
||||
return 'invalid_auth'
|
||||
if exc.code == 'SYSTEM.SERVICE_UNAVAILABLE' and 'not configured' in message.lower():
|
||||
return 'missing_auth'
|
||||
return exc.code
|
||||
|
||||
@shipping_notice_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
"""把业务异常统一转成 Tool 侧约定的 JSON 结构。"""
|
||||
body: dict[str, object] = {'ok': False, 'error_code': _tool_error_code(exc), 'message': exc.message}
|
||||
if exc.details:
|
||||
body['details'] = exc.details
|
||||
return jsonify(body), exc.http_status
|
||||
|
||||
@shipping_notice_bp.before_request
|
||||
def _verify_tool_access():
|
||||
"""
|
||||
对货代 Tool / RPA / 导出接口做统一 Header 鉴权。
|
||||
核心逻辑:仅放行 OpenAPI 导入文档,其他请求都必须携带有效 Tool Key。
|
||||
"""
|
||||
if request.path.endswith('/openapi.json') or request.path.endswith('/openapi.dify.yaml'):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
def _tool_api_base_url() -> str:
|
||||
"""Base URL for OpenAPI servers — hxops backend, NOT Dify (8882)."""
|
||||
return resolve_tool_api_base_url()
|
||||
|
||||
def _dify_openapi_spec() -> dict:
|
||||
return build_dify_openapi_spec(_tool_api_base_url())
|
||||
|
||||
def _payload() -> dict:
|
||||
return request.get_json(silent=True) or {}
|
||||
|
||||
def _generate_batch_no() -> str:
|
||||
from datetime import datetime
|
||||
return f"SB-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
@shipping_notice_bp.route('/tools/openapi.json', methods=['GET'])
|
||||
def openapi_spec():
|
||||
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
|
||||
return jsonify(_dify_openapi_spec())
|
||||
|
||||
@shipping_notice_bp.route('/tools/checkpoint-catalog', methods=['GET'])
|
||||
def checkpoint_catalog():
|
||||
"""返回检查点目录,供开发联调和文档核对 human_options/action_buttons。"""
|
||||
from app.services.shipping_notice.state_machine import build_checkpoint_catalog
|
||||
return jsonify(build_checkpoint_catalog())
|
||||
|
||||
@shipping_notice_bp.route('/tools/openapi.dify.yaml', methods=['GET'])
|
||||
def openapi_dify_yaml():
|
||||
"""返回 Dify 导入用的 OpenAPI YAML 文档。"""
|
||||
import yaml
|
||||
body = yaml.safe_dump(_dify_openapi_spec(), allow_unicode=True, sort_keys=False)
|
||||
return current_app.response_class(body, mimetype='text/yaml; charset=utf-8')
|
||||
|
||||
@shipping_notice_bp.route('/tools/create_task', methods=['POST'])
|
||||
def tool_create_task():
|
||||
"""
|
||||
创建单个发货任务。
|
||||
【AI 触发时机】:仅供 Hxops 内部建单链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.create_task(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/create_batch', methods=['POST'])
|
||||
def tool_create_batch():
|
||||
"""
|
||||
创建或复用发货批次。
|
||||
【AI 触发时机】:仅供 Hxops 内部建批链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
payload = _payload()
|
||||
if isinstance(payload.get('notice_items'), list) and payload.get('notice_items'):
|
||||
return jsonify(shipping_tools.create_batch_tasks(payload))
|
||||
batch_no = str(payload.get('batch_no') or '').strip()
|
||||
if batch_no:
|
||||
batch = get_batch_by_no(batch_no)
|
||||
if batch:
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已复用批次 {batch.batch_no}', 'data': serialize_batch_summary(batch)})
|
||||
batch, _created = shipping_tools.create_batch(payload)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已创建批次 {batch.batch_no}', 'data': serialize_batch_summary(batch)})
|
||||
|
||||
@shipping_notice_bp.route('/tools/parse_notice', methods=['POST'])
|
||||
def tool_parse_notice():
|
||||
"""
|
||||
解析发货通知正文。
|
||||
【AI 触发时机】:当用户上传、粘贴或修正发货通知内容后,需要把文本转成任务单头和订单行时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.parse_notice(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/update_notice_fields', methods=['POST'])
|
||||
def tool_update_notice_fields():
|
||||
"""
|
||||
修改发货通知单头字段。
|
||||
【AI 触发时机】:当用户明确要求更正客户、PO、收货地或交期等单头信息时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.update_notice_fields(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/update_notice_line', methods=['POST'])
|
||||
def tool_update_notice_line():
|
||||
"""
|
||||
修改指定订单行。
|
||||
【AI 触发时机】:当用户指出某一行的 SKU、数量、Reservation ID 或交期有误时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.update_notice_line(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/add_notice_line', methods=['POST'])
|
||||
def tool_add_notice_line():
|
||||
"""
|
||||
新增订单行。
|
||||
【AI 触发时机】:当用户说明漏了一行订单、需要补录发货通知明细时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.add_notice_line(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/remove_notice_line', methods=['POST'])
|
||||
def tool_remove_notice_line():
|
||||
"""
|
||||
删除订单行。
|
||||
【AI 触发时机】:当用户确认某一行是误解析、重复行或不应出货的行时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.remove_notice_line(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/parse_inventory', methods=['POST'])
|
||||
def tool_parse_inventory():
|
||||
"""
|
||||
解析库存内容。
|
||||
【AI 触发时机】:当用户提供库存文本或表格内容,需要把库存转成系统可匹配格式时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.parse_inventory(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/upload_inventory_file', methods=['POST'])
|
||||
def tool_upload_inventory_file():
|
||||
"""
|
||||
服务器侧接收库存 Excel 并解析。
|
||||
【AI 触发时机】:当用户上传库存 Excel,且不希望把二进制文件内容经由 LLM 传输时调用。
|
||||
"""
|
||||
task_id = str(request.form.get('task_id') or request.args.get('task_id') or '').strip()
|
||||
upload = request.files.get('file')
|
||||
return jsonify(shipping_tools.upload_inventory_file(task_id, upload))
|
||||
|
||||
@shipping_notice_bp.route('/tools/get_inventory_schema_preview', methods=['POST'])
|
||||
def tool_get_inventory_schema_preview():
|
||||
"""
|
||||
获取库存表头预览。
|
||||
【AI 触发时机】:当 Agent 需要先看 Excel/表格列名,再决定 map_json 或提示用户确认映射时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.get_inventory_schema_preview(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/apply_inventory_mapping', methods=['POST'])
|
||||
def tool_apply_inventory_mapping():
|
||||
"""
|
||||
应用库存字段映射。
|
||||
【AI 触发时机】:当用户或 Agent 已确认列名与系统字段的对应关系,需要提交 map_json 时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.apply_inventory_mapping(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/ensure_inventory', methods=['POST'])
|
||||
def tool_ensure_inventory():
|
||||
"""
|
||||
保证任务已取得库存数据。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.ensure_inventory(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/auto_progress', methods=['POST'])
|
||||
def tool_auto_progress():
|
||||
"""
|
||||
自动推进任务。
|
||||
【AI 触发时机】:仅供后端 orchestrator / worker 调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.auto_progress(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/match_inventory', methods=['POST'])
|
||||
def tool_match_inventory():
|
||||
"""
|
||||
执行库存匹配。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.match_inventory(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/submit_decision', methods=['POST'])
|
||||
def tool_submit_decision():
|
||||
"""
|
||||
提交人工决策。
|
||||
【AI 触发时机】:当用户明确表达确认、驳回、重解析、重匹配、确认映射或关闭任务时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.submit_decision(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/confirm_inventory_source', methods=['POST'])
|
||||
def tool_confirm_inventory_source():
|
||||
"""
|
||||
确认库存查询来源(仅提交 source_code)。
|
||||
【AI 触发时机】:用户在库存源人工检查点选择正式库存源后调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.confirm_inventory_source(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/generate_shipment_excel', methods=['POST'])
|
||||
def tool_generate_shipment_excel():
|
||||
"""
|
||||
生成出货 Excel。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.generate_excel(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/upload_to_freight', methods=['POST'])
|
||||
def tool_upload_to_freight():
|
||||
"""
|
||||
上传到货代系统或确认人工上传完成。
|
||||
【AI 触发时机】:仅供后端主调度、内部恢复链路或人工上传收口调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.upload_to_freight(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/get_task_status', methods=['POST'])
|
||||
def tool_get_task_status():
|
||||
"""
|
||||
查询任务状态。
|
||||
【AI 触发时机】:当 Agent 只拿到任务号/会话号,需要先确认当前卡点后再决定下一步时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.get_task_status(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/get_batch_status', methods=['POST'])
|
||||
def tool_get_batch_status():
|
||||
"""
|
||||
查询批次状态。
|
||||
【AI 触发时机】:当用户关注整批任务处理进度,或 Agent 需要查看当前 focus task 与批次摘要时调用。
|
||||
"""
|
||||
payload = _payload()
|
||||
batch_no = str(payload.get('batch_no') or '').strip()
|
||||
if not batch_no:
|
||||
raise ValidationError("batch_no is required")
|
||||
batch = get_batch_by_no(batch_no)
|
||||
if not batch:
|
||||
raise NotFoundError("batch not found")
|
||||
focus_task = get_focus_task_for_batch(batch_no, batch.user_id or 0) if batch.user_id is not None else None
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已获取批次 {batch.batch_no} 状态', 'data': {**serialize_batch_summary(batch), 'focus_task': serialize_task_summary(focus_task) if focus_task else None, 'tasks': list_batch_task_summaries(batch)}})
|
||||
|
||||
@shipping_notice_bp.route('/tools/switch_focus_task', methods=['POST'])
|
||||
def tool_switch_focus_task():
|
||||
"""
|
||||
切换批次当前焦点任务。
|
||||
【AI 触发时机】:当前仅保留给 Hxops 内部切票能力;不属于 Dify 正式导出 Tool。
|
||||
"""
|
||||
payload = _payload()
|
||||
batch_no = str(payload.get('batch_no') or '').strip()
|
||||
task_no = str(payload.get('task_no') or payload.get('target_task_no') or '').strip()
|
||||
if not batch_no or not task_no:
|
||||
raise ValidationError("batch_no and task_no are required")
|
||||
batch = get_batch_by_no(batch_no)
|
||||
if not batch:
|
||||
raise NotFoundError("batch not found")
|
||||
task = get_task_in_batch(batch_no, task_no)
|
||||
if not task:
|
||||
raise NotFoundError("task not found in batch")
|
||||
switch_batch_focus(
|
||||
batch,
|
||||
task,
|
||||
source="tool_api",
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'task_no': task.task_no, 'message': f'已切换当前任务到 {task.task_no}', 'data': {'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)}})
|
||||
|
||||
@shipping_notice_bp.route('/rpa/heartbeat', methods=['POST'])
|
||||
def rpa_worker_heartbeat():
|
||||
"""
|
||||
RPA Worker 心跳上报。
|
||||
核心逻辑:校验 payload 后写入 Redis/内存;供触发库存 RPA 前就绪检查使用。
|
||||
"""
|
||||
payload = _payload()
|
||||
try:
|
||||
worker = record_rpa_worker_heartbeat(payload)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc))
|
||||
except ServiceUnavailableError:
|
||||
raise
|
||||
return jsonify({'status': 'ok', 'message': 'heartbeat recorded', 'data': worker})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-ready', methods=['POST'])
|
||||
def rpa_inventory_ready():
|
||||
"""RPA 回调入口:上报库存导出结果并回写任务状态。"""
|
||||
return jsonify(shipping_tools.rpa_report_inventory(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-batch-ready', methods=['POST'])
|
||||
def rpa_inventory_batch_ready():
|
||||
"""RPA 批量库存导出回调:按 Warehouse 写入库存快照。"""
|
||||
return jsonify(shipping_tools.rpa_report_inventory_batch(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tasks/<task_no>/repair-inventory-attachment', methods=['POST'])
|
||||
def repair_task_inventory_attachment(task_no: str):
|
||||
"""
|
||||
从任务库存快照幂等重建正式附件(不重新消费 RPA callback)。
|
||||
核心逻辑:供晋升失败或 marker 异常后的人工/后台补偿。
|
||||
"""
|
||||
payload = _payload()
|
||||
payload.setdefault("task_no", task_no)
|
||||
payload.setdefault("task_id", task_no)
|
||||
return jsonify(shipping_tools.repair_task_inventory_attachment(payload))
|
||||
|
||||
@shipping_notice_bp.route('/rpa/upload-complete', methods=['POST'])
|
||||
def rpa_upload_complete():
|
||||
"""RPA 回调入口:上报货代上传结果并回写任务状态。"""
|
||||
return jsonify(shipping_tools.rpa_report_upload(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tasks/<task_no>/export', methods=['GET'])
|
||||
def download_task_export(task_no: str):
|
||||
"""下载任务已生成的出货 Excel。"""
|
||||
task = get_task_by_ref(task_no)
|
||||
err_msg = task_export_error_message(task)
|
||||
if err_msg:
|
||||
raise NotFoundError(err_msg)
|
||||
resolved = resolve_task_export_download(task)
|
||||
assert resolved is not None
|
||||
path, download_name = resolved
|
||||
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
|
||||
@@ -1,40 +0,0 @@
|
||||
"""
|
||||
Speech transcription API — forwards audio to SiliconFlow ASR.
|
||||
"""
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError, ValidationError, ServiceUnavailableError
|
||||
from app.services.speech_asr import SpeechAsrService
|
||||
|
||||
speech_bp = Blueprint('speech', __name__)
|
||||
|
||||
|
||||
@speech_bp.route('/transcribe', methods=['POST'])
|
||||
def transcribe_audio():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
|
||||
uploaded = request.files.get('audio') or request.files.get('file')
|
||||
if not uploaded or not uploaded.filename:
|
||||
raise ValidationError('audio file is required')
|
||||
|
||||
audio_bytes = uploaded.read()
|
||||
filename = uploaded.filename or 'recording.webm'
|
||||
content_type = uploaded.content_type or ''
|
||||
|
||||
try:
|
||||
SpeechAsrService.validate_upload(filename, len(audio_bytes))
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc)) from exc
|
||||
|
||||
try:
|
||||
text, model = SpeechAsrService.transcribe(audio_bytes, filename, content_type)
|
||||
except RuntimeError as exc:
|
||||
raise ServiceUnavailableError(str(exc)) from exc
|
||||
|
||||
return jsonify({
|
||||
'text': text,
|
||||
'model': model,
|
||||
})
|
||||
@@ -1,11 +0,0 @@
|
||||
"""
|
||||
backend/app/api/tools/__init__.py
|
||||
|
||||
用途:Dify HTTP Tool API Blueprint 聚合。
|
||||
逻辑:Wave 1 前 re-export shipping_notice_tools、file_check_tools。
|
||||
"""
|
||||
from app.api.tools.shipping_notice import shipping_notice_bp # noqa: F401
|
||||
from app.api.tools.file_check import file_check_bp # noqa: F401
|
||||
from app.api.tools.maintenance import maintenance_tool_bp # noqa: F401
|
||||
|
||||
__all__ = ['shipping_notice_bp', 'file_check_bp']
|
||||
@@ -1,8 +0,0 @@
|
||||
"""
|
||||
backend/app/api/tools/file_check.py
|
||||
|
||||
用途:文件检核 Tool API Blueprint(Wave 1 自 file_check_tools.py 迁入)。
|
||||
"""
|
||||
from app.api.file_check_tools import file_check_bp # noqa: F401
|
||||
|
||||
__all__ = ['file_check_bp']
|
||||
@@ -1,9 +0,0 @@
|
||||
"""
|
||||
backend/app/api/tools/maintenance.py
|
||||
|
||||
用途:设备维保 Tool API Blueprint re-export。
|
||||
依赖:app.api.maintenance_tools。
|
||||
逻辑:保持 api.tools 分包统一入口,register_blueprints 只从 app.api.tools 导入各 Tool Blueprint。
|
||||
"""
|
||||
|
||||
from app.api.maintenance_tools import maintenance_tool_bp # noqa: F401
|
||||
@@ -1,8 +0,0 @@
|
||||
"""
|
||||
backend/app/api/tools/shipping_notice.py
|
||||
|
||||
用途:出货通知 Tool API Blueprint(Wave 1 自 shipping_notice_tools.py 迁入)。
|
||||
"""
|
||||
from app.api.shipping_notice_tools import shipping_notice_bp # noqa: F401
|
||||
|
||||
__all__ = ['shipping_notice_bp']
|
||||
@@ -1,126 +0,0 @@
|
||||
"""
|
||||
backend/app/api/training.py
|
||||
|
||||
用途:提供新人培训用户侧进度接口与管理端统计导出接口。
|
||||
依赖:JWT 当前用户解析、training_service、Flask Blueprint/send_file。
|
||||
逻辑:员工端负责读写个人培训进度;管理端负责真实记录查询、统计与 Excel 导出。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, UnauthorizedError
|
||||
from app.services.training_service import (
|
||||
export_training_records_excel,
|
||||
get_user_training_record,
|
||||
list_training_records,
|
||||
serialize_training_record,
|
||||
summarize_training_records,
|
||||
upsert_user_training_record,
|
||||
)
|
||||
|
||||
training_user_bp = Blueprint("training_user", __name__)
|
||||
training_admin_bp = Blueprint("training_admin", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""确保当前请求存在登录用户。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _require_training_admin():
|
||||
"""
|
||||
确保当前用户具备培训管理权限。
|
||||
|
||||
用途:统一拦截 HR 管理面板的数据查询、统计与导出接口。
|
||||
核心逻辑:优先复用 User.can_manage_training(),把“角色默认权限 + 前端可配置功能权限”收敛到同一个判断入口。
|
||||
"""
|
||||
user = _require_user()
|
||||
if not user.can_manage_training():
|
||||
raise ForbiddenError("Training admin privilege required")
|
||||
return user
|
||||
|
||||
|
||||
@training_user_bp.route("/training-record", methods=["GET"])
|
||||
def get_my_training_record():
|
||||
"""读取当前用户的培训进度;未创建时返回 null data。"""
|
||||
user = _require_user()
|
||||
record = get_user_training_record(user.id)
|
||||
return jsonify(serialize_training_record(record) if record else None)
|
||||
|
||||
|
||||
@training_user_bp.route("/training-record/progress", methods=["PUT"])
|
||||
def save_my_training_record():
|
||||
"""保存当前用户培训进度,用于视频完成、答题推进与结算归档。"""
|
||||
user = _require_user()
|
||||
payload = request.get_json() or {}
|
||||
record = upsert_user_training_record(user, payload)
|
||||
return jsonify(serialize_training_record(record))
|
||||
|
||||
|
||||
@training_admin_bp.route("/training-records", methods=["GET"])
|
||||
def list_admin_training_records():
|
||||
"""列出培训记录,支持关键字、部门、状态筛选。"""
|
||||
_require_training_admin()
|
||||
keyword = request.args.get("keyword")
|
||||
department = request.args.get("department")
|
||||
status = request.args.get("status")
|
||||
|
||||
result = list_training_records(keyword=keyword, department=department, status=status)
|
||||
all_records = list_training_records()
|
||||
department_options = sorted({str(item.department or "").strip() for item in all_records.records if str(item.department or "").strip()})
|
||||
|
||||
page = max(1, request.args.get("page", type=int) or 1)
|
||||
page_size = max(1, min(200, request.args.get("page_size", type=int) or max(result.total, 1)))
|
||||
start = (page - 1) * page_size
|
||||
end = start + page_size
|
||||
items = result.records[start:end]
|
||||
pages = max(1, (result.total + page_size - 1) // page_size) if result.total else 1
|
||||
|
||||
return jsonify(
|
||||
{
|
||||
"items": [serialize_training_record(item) for item in items],
|
||||
"total": result.total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"pages": pages,
|
||||
"department_options": department_options,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@training_admin_bp.route("/training-records/stats", methods=["GET"])
|
||||
def get_admin_training_stats():
|
||||
"""返回培训记录聚合统计,供 HR 面板展示。"""
|
||||
_require_training_admin()
|
||||
result = list_training_records(
|
||||
keyword=request.args.get("keyword"),
|
||||
department=request.args.get("department"),
|
||||
status=request.args.get("status"),
|
||||
)
|
||||
return jsonify(summarize_training_records(result.records))
|
||||
|
||||
|
||||
@training_admin_bp.route("/training-records/export", methods=["GET"])
|
||||
def export_admin_training_records():
|
||||
"""导出培训记录为 Excel。"""
|
||||
_require_training_admin()
|
||||
result = list_training_records(
|
||||
keyword=request.args.get("keyword"),
|
||||
department=request.args.get("department"),
|
||||
status=request.args.get("status"),
|
||||
)
|
||||
file_data, file_name = export_training_records_excel(result.records)
|
||||
return send_file(
|
||||
BytesIO(file_data),
|
||||
as_attachment=True,
|
||||
download_name=file_name,
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,18 +0,0 @@
|
||||
"""
|
||||
backend/app/api/workspace/__init__.py
|
||||
|
||||
用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check、announcements)。
|
||||
依赖:workspace 各子模块 blueprint。
|
||||
逻辑:import 子模块注册路由;register_blueprints 从本包导入各 bp。
|
||||
"""
|
||||
from app.api.workspace.announcements import workspace_announcements_bp
|
||||
from app.api.workspace.file_check import workspace_file_check_bp
|
||||
from app.api.workspace.schedule import workspace_schedule_bp
|
||||
from app.api.workspace.shipping_notice import workspace_shipping_notice_bp
|
||||
|
||||
__all__ = [
|
||||
'workspace_announcements_bp',
|
||||
'workspace_file_check_bp',
|
||||
'workspace_schedule_bp',
|
||||
'workspace_shipping_notice_bp',
|
||||
]
|
||||
@@ -1,27 +0,0 @@
|
||||
"""
|
||||
backend/app/api/workspace/announcements.py
|
||||
|
||||
用途:工作台/登录页只读公告列表 API。
|
||||
依赖:services/admin/announcement_service(读活跃公告)。
|
||||
逻辑:GET /announcements 无需登录;管理 CRUD 见 api/admin/announcements.py。
|
||||
"""
|
||||
from flask import Blueprint, jsonify
|
||||
|
||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.admin import announcement_service
|
||||
|
||||
workspace_announcements_bp = Blueprint('workspace_announcements', __name__)
|
||||
|
||||
|
||||
@workspace_announcements_bp.route('/announcements', methods=['GET'])
|
||||
def list_active_announcements():
|
||||
"""返回已发布的公司公告(公开,供登录页与工作台展示)。"""
|
||||
try:
|
||||
return jsonify(announcement_service.list_active_announcements())
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
from flask import current_app
|
||||
|
||||
current_app.logger.warning('workspace.announcements query failed: %s', exc)
|
||||
raise ServiceUnavailableError('Database connection failed')
|
||||
@@ -1,126 +0,0 @@
|
||||
"""
|
||||
backend/app/api/workspace/file_check.py
|
||||
|
||||
用途:工作台文件检核进度轮询 API(对话页 tool_run_progress)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、file_check_tools、schedule.query_service。
|
||||
逻辑:鉴权后查询 ScheduleRun 进度;register_blueprints 经 workspace 包注册。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.file_check_tools.chat_log_run_resolver import find_run_for_chat_log_with_source
|
||||
from app.services.schedule.query_service import get_run, serialize_run
|
||||
|
||||
workspace_file_check_bp = Blueprint("workspace_file_check", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""
|
||||
校验当前登录用户。
|
||||
Raises:
|
||||
UnauthorizedError: 未认证。
|
||||
"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
def serialize_file_judgement(payload: dict) -> dict:
|
||||
"""序列化检核判定统计(读取 response_summary_json.file_judgement)。"""
|
||||
response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {}
|
||||
judgement = response_summary.get('file_judgement')
|
||||
if not isinstance(judgement, dict):
|
||||
judgement = {}
|
||||
return {
|
||||
'qualified_count': int(judgement.get('qualified_count') or 0),
|
||||
'unqualified_count': int(judgement.get('unqualified_count') or 0),
|
||||
'manual_count': int(judgement.get('manual_count') or 0),
|
||||
'dify_error_count': int(judgement.get('dify_error_count') or 0),
|
||||
'invalid_result_count': int(judgement.get('invalid_result_count') or 0),
|
||||
'business_manual_count': int(judgement.get('business_manual_count') or 0),
|
||||
'system_error_count': int(judgement.get('system_error_count') or 0),
|
||||
'dify_timeout_count': int(judgement.get('dify_timeout_count') or 0),
|
||||
'invalid_output_count': int(judgement.get('invalid_output_count') or 0),
|
||||
'attachment_error_count': int(judgement.get('attachment_error_count') or 0),
|
||||
}
|
||||
|
||||
def serialize_current_step(payload: dict) -> dict | None:
|
||||
response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {}
|
||||
current_step = response_summary.get('current_step') if isinstance(response_summary.get('current_step'), dict) else None
|
||||
if not current_step:
|
||||
return None
|
||||
return {'step': str(current_step.get('step') or ''), 'label': str(current_step.get('label') or current_step.get('step') or ''), 'row_id': current_step.get('row_id'), 'started_at': current_step.get('started_at'), 'processed_count': int(current_step.get('processed_count') or 0), 'success_count': int(current_step.get('success_count') or 0), 'failed_count': int(current_step.get('failed_count') or 0), 'skipped_count': int(current_step.get('skipped_count') or 0)}
|
||||
|
||||
def _serialize_progress_run(run: ScheduleRun) -> dict:
|
||||
payload = serialize_run(run)
|
||||
total = int(payload.get('total_count') or 0)
|
||||
success = int(payload.get('success_count') or 0)
|
||||
failed = int(payload.get('failed_count') or 0)
|
||||
skipped = int(payload.get('skipped_count') or 0)
|
||||
processed = success + failed + skipped
|
||||
percent = int(round(processed / total * 100)) if total > 0 else 0
|
||||
percent = max(0, min(percent, 100))
|
||||
return {'run_id': payload['id'], 'run_no': payload['run_no'], 'task_id': payload['schedule_task_id'], 'title': payload.get('schedule_name') or '', 'status': payload['status'], 'total_count': total, 'processed_count': processed, 'success_count': success, 'failed_count': failed, 'skipped_count': skipped, 'judgement': serialize_file_judgement(payload), 'current_step': serialize_current_step(payload), 'progress_percent': percent, 'started_at': payload.get('started_at'), 'finished_at': payload.get('finished_at'), 'duration_ms': payload.get('duration_ms'), 'error_message': payload.get('error_message'), 'excel': {'file_name': payload.get('excel_file_name'), 'file_size': payload.get('excel_file_size'), 'download_url': f'/api/workspace/file-check/runs/{run.id}/excel' if payload.get('excel_file_name') else None}, 'knowledge_base': {'sync_status': payload.get('kb_sync_status'), 'group_id': payload.get('kb_group_id'), 'document_id': payload.get('kb_document_id'), 'document_version_id': payload.get('kb_document_version_id'), 'sync_job_id': payload.get('kb_sync_job_id'), 'error_message': payload.get('kb_sync_error')}}
|
||||
|
||||
@workspace_file_check_bp.route('/file-check/runs/for-log', methods=['GET'])
|
||||
def workspace_file_check_run_for_log():
|
||||
"""按 chat_log_id + schedule_task_id 返回该轮问答绑定的检核批次。"""
|
||||
_require_user()
|
||||
task_id = request.args.get('task_id', type=int)
|
||||
chat_log_id = request.args.get('chat_log_id', type=int)
|
||||
if not task_id or task_id <= 0:
|
||||
raise ValidationError("task_id_required")
|
||||
if not chat_log_id or chat_log_id <= 0:
|
||||
raise ValidationError("chat_log_id_required")
|
||||
match = find_run_for_chat_log_with_source(task_id=task_id, chat_log_id=chat_log_id)
|
||||
return jsonify({
|
||||
'ok': True,
|
||||
'run': _serialize_progress_run(match.run) if match.run else None,
|
||||
'match_source': match.match_source,
|
||||
})
|
||||
|
||||
@workspace_file_check_bp.route('/file-check/runs/for-session', methods=['GET'])
|
||||
def workspace_file_check_run_for_session():
|
||||
"""已废弃:请改用 for-log?chat_log_id=。保留接口避免旧客户端 404。"""
|
||||
_require_user()
|
||||
return jsonify({'ok': True, 'run': None, 'match_source': None, 'session_updated_at': None})
|
||||
|
||||
@workspace_file_check_bp.route('/file-check/runs/active', methods=['GET'])
|
||||
def workspace_file_check_active_run():
|
||||
"""查询当前进行中的检核批次;优先按 schedule_task_id(query: task_id)过滤。"""
|
||||
_require_user()
|
||||
task_id = request.args.get('task_id', type=int)
|
||||
conversation_id = str(request.args.get('conversation_id') or '').strip()
|
||||
query = ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id).filter(ScheduleRun.status == 'running')
|
||||
if task_id is not None:
|
||||
query = query.filter(ScheduleRun.schedule_task_id == task_id)
|
||||
rows = query.order_by(ScheduleRun.id.desc()).all()
|
||||
if task_id is not None:
|
||||
run = rows[0] if rows else None
|
||||
else:
|
||||
run = next((row for row in rows if not conversation_id or str((row.api_request_json or {}).get('conversation_id') or '').strip() == conversation_id), None)
|
||||
return jsonify({'ok': True, 'run': _serialize_progress_run(run) if run else None})
|
||||
|
||||
@workspace_file_check_bp.route('/file-check/runs/<int:run_id>', methods=['GET'])
|
||||
def workspace_file_check_run_detail(run_id: int):
|
||||
_require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('run_not_found')
|
||||
return jsonify({'ok': True, 'run': _serialize_progress_run(run)})
|
||||
|
||||
@workspace_file_check_bp.route('/file-check/runs/<int:run_id>/excel', methods=['GET'])
|
||||
def workspace_file_check_run_excel(run_id: int):
|
||||
_require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('run_not_found')
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError('excel_not_found')
|
||||
return send_file(BytesIO(run.excel_file_data), as_attachment=True, download_name=run.excel_file_name or f'{run.run_no}.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
@@ -1,80 +0,0 @@
|
||||
"""
|
||||
backend/app/api/workspace/schedule.py
|
||||
|
||||
用途:工作台排程运行记录查询 API。
|
||||
依赖:app.core.auth.jwt、app.core.errors、schedule.query_service。
|
||||
逻辑:鉴权后只读查询 ScheduleRun;register_blueprints 经 workspace 包注册。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError
|
||||
from app.services.schedule.query_service import can_view_run, get_run, list_runs, serialize_run
|
||||
|
||||
workspace_schedule_bp = Blueprint("workspace_schedule", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""校验当前用户;未登录时抛出 UnauthorizedError。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
@workspace_schedule_bp.route("/schedule-runs", methods=["GET"])
|
||||
def workspace_schedule_runs():
|
||||
user = _require_user()
|
||||
status = str(request.args.get("status") or "").strip() or None
|
||||
schedule_name = str(request.args.get("schedule_name") or "").strip() or None
|
||||
started_after_str = request.args.get("started_after")
|
||||
started_before_str = request.args.get("started_before")
|
||||
started_after = datetime.fromisoformat(started_after_str.replace("Z", "+00:00")) if started_after_str else None
|
||||
started_before = datetime.fromisoformat(started_before_str.replace("Z", "+00:00")) if started_before_str else None
|
||||
limit = int(request.args.get("limit") or 100)
|
||||
return jsonify(
|
||||
list_runs(
|
||||
notify_user_id=user.id,
|
||||
schedule_name=schedule_name,
|
||||
status=status,
|
||||
started_after=started_after,
|
||||
started_before=started_before,
|
||||
limit=limit,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@workspace_schedule_bp.route("/schedule-runs/<int:run_id>", methods=["GET"])
|
||||
def workspace_schedule_run_detail(run_id: int):
|
||||
user = _require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("Not found")
|
||||
if not can_view_run(run, user.id):
|
||||
raise ForbiddenError("Forbidden")
|
||||
return jsonify(serialize_run(run))
|
||||
|
||||
|
||||
@workspace_schedule_bp.route("/schedule-runs/<int:run_id>/excel", methods=["GET"])
|
||||
def workspace_schedule_run_excel(run_id: int):
|
||||
from io import BytesIO
|
||||
|
||||
user = _require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("Not found")
|
||||
if not can_view_run(run, user.id):
|
||||
raise ForbiddenError("Forbidden")
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError("Excel not found")
|
||||
buf = BytesIO(run.excel_file_data)
|
||||
return send_file(
|
||||
buf,
|
||||
as_attachment=True,
|
||||
download_name=run.excel_file_name or "result.xlsx",
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
@@ -1,741 +0,0 @@
|
||||
"""
|
||||
backend/app/api/workspace/shipping_notice.py
|
||||
|
||||
用途:HXOPS 工作台与聊天前端使用的发货通知用户态 API。
|
||||
依赖:app.core.auth.jwt、app.core.errors、shipping_notice.query_service / tools / notice_upload / ui_state。
|
||||
逻辑:薄路由层鉴权与参数校验;register_blueprints 经 workspace 包注册。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from flask import Blueprint, g, jsonify, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
|
||||
from app.services.shipping_notice.constants import (
|
||||
AUTO_CHAIN_FALLBACK,
|
||||
CP_EXPORT_GENERATED,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
MAP_JSON,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import switch_batch_focus
|
||||
from app.services.shipping_notice.query_service import (
|
||||
EXPORT_MIME_TYPE,
|
||||
get_batch_for_user,
|
||||
get_conversation_batch_workspace,
|
||||
get_focus_task_for_batch,
|
||||
get_task_for_user,
|
||||
list_batches_for_user,
|
||||
list_tasks_for_batch,
|
||||
list_tasks_for_user,
|
||||
resolve_task_export_download,
|
||||
serialize_batch_summary,
|
||||
serialize_task_detail,
|
||||
serialize_task_summary,
|
||||
task_export_error_message,
|
||||
)
|
||||
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
|
||||
|
||||
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""
|
||||
校验当前登录用户;未认证时抛出 UnauthorizedError,由全局 handler 输出标准错误 JSON。
|
||||
Returns:
|
||||
User 模型实例。
|
||||
Raises:
|
||||
UnauthorizedError: 无有效 JWT 或 legacy header。
|
||||
"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _ok(payload: dict):
|
||||
"""返回带 request_id 的成功 envelope,供工作台读接口复用。"""
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
|
||||
def workspace_shipping_tasks():
|
||||
"""列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
|
||||
user = _require_user()
|
||||
batch_no = str(request.args.get('batch_no') or '').strip() or None
|
||||
process_status = str(request.args.get('process_status') or '').strip() or None
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
return jsonify(list_tasks_for_user(user.id, batch_no=batch_no, process_status=process_status, limit=limit))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches', methods=['GET'])
|
||||
def workspace_shipping_batches():
|
||||
"""列出当前用户的发货批次摘要。"""
|
||||
user = _require_user()
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
return jsonify(list_batches_for_user(user.id, limit=limit))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-conversations/<conversation_id>/batch-workspace', methods=['GET'])
|
||||
def workspace_shipping_conversation_batch_workspace(conversation_id: str):
|
||||
"""返回一个 Agent 会话下的多批次执行工作台快照。"""
|
||||
user = _require_user()
|
||||
return _ok(get_conversation_batch_workspace(conversation_id, user.id))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-notices', methods=['POST'])
|
||||
def workspace_create_shipping_batch_from_notices():
|
||||
"""接收多份发货通知附件,创建批次并交给后台编排器逐票推进。"""
|
||||
user = _require_user()
|
||||
uploads = request.files.getlist('files')
|
||||
if not uploads:
|
||||
single = request.files.get('file')
|
||||
if single:
|
||||
uploads = [single]
|
||||
if not uploads:
|
||||
raise ValidationError('files is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.batch_from_notices import (
|
||||
create_shipping_batch_from_notice_items,
|
||||
intake_notice_uploads_for_batch,
|
||||
)
|
||||
from app.services.shipping_notice.batch_create_idempotency import (
|
||||
normalize_create_idempotency_key,
|
||||
warn_missing_create_idempotency_key,
|
||||
)
|
||||
from app.services.shipping_notice.notice_upload import cleanup_temp_notice_uploads
|
||||
conversation_id = str(request.form.get('conversation_id') or '').strip()
|
||||
idempotency_key = normalize_create_idempotency_key(
|
||||
request.headers.get('Idempotency-Key') or request.form.get('idempotency_key')
|
||||
)
|
||||
if not idempotency_key:
|
||||
warn_missing_create_idempotency_key(source='workspace_create_shipping_batch_from_notices')
|
||||
temp_request_id = str(getattr(g, 'request_id', None) or uuid.uuid4().hex)
|
||||
try:
|
||||
notice_items, file_summary = intake_notice_uploads_for_batch(temp_request_id, uploads)
|
||||
finally:
|
||||
cleanup_temp_notice_uploads(temp_request_id)
|
||||
|
||||
created = create_shipping_batch_from_notice_items(
|
||||
user_id=user.id,
|
||||
conversation_id=conversation_id or None,
|
||||
notice_items=notice_items,
|
||||
file_summary=file_summary,
|
||||
create_idempotency_key=idempotency_key,
|
||||
)
|
||||
return _ok(created)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>', methods=['GET'])
|
||||
def workspace_shipping_batch_detail(batch_no: str):
|
||||
"""
|
||||
返回批次详情与聚合 UI State。
|
||||
|
||||
核心逻辑:工作台详情页与独立 `/ui-state` 端点共享同一份批次状态构建结果,
|
||||
避免批次摘要、焦点任务和任务卡片在不同接口里各自推导造成漂移。
|
||||
"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok(build_batch_ui_state(batch))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/ui-state', methods=['GET'])
|
||||
def workspace_shipping_batch_ui_state(batch_no: str):
|
||||
"""
|
||||
返回批次级 UI State。
|
||||
|
||||
核心逻辑:供右侧工作台、步骤条与批次任务卡统一读取同源状态,
|
||||
保持与批次详情接口返回的 `focus_task_ui_state/tasks[].ui_state` 完全一致。
|
||||
"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok(build_batch_ui_state(batch))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/tasks', methods=['GET'])
|
||||
def workspace_shipping_batch_tasks(batch_no: str):
|
||||
"""返回指定批次下的任务列表。"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(list_tasks_for_batch(batch_no, user.id))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['GET'])
|
||||
def workspace_shipping_batch_focus_task(batch_no: str):
|
||||
"""返回指定批次当前焦点任务的摘要。"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
focus_task = get_focus_task_for_batch(batch_no, user.id)
|
||||
if not focus_task:
|
||||
raise NotFoundError('Focus task not found')
|
||||
return jsonify(serialize_task_summary(focus_task))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['POST'])
|
||||
def workspace_switch_shipping_batch_focus_task(batch_no: str):
|
||||
"""切换批次当前焦点任务,供工作台在同批次任务间跳转。"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
task_no = str(data.get('task_no') or data.get('target_task_no') or '').strip()
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if not task_no:
|
||||
raise ValidationError('task_no is required')
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task or task.batch_id != batch.id:
|
||||
raise NotFoundError('Task not found in batch')
|
||||
switch_batch_focus(
|
||||
batch,
|
||||
task,
|
||||
source='workspace_api',
|
||||
comment=comment or None,
|
||||
extra={'actor_user_id': user.id},
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify({'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)})
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['POST'])
|
||||
def workspace_create_shipping_task():
|
||||
"""创建单个发货任务,适用于手工录入或聊天入口先建单。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = {'user_id': user.id}
|
||||
source_type = str(data.get('source_type') or '').strip()
|
||||
if source_type:
|
||||
payload['source_type'] = source_type
|
||||
conversation_id = str(data.get('conversation_id') or '').strip()
|
||||
if conversation_id:
|
||||
payload['conversation_id'] = conversation_id
|
||||
raw_content = str(data.get('raw_content') or '').strip()
|
||||
if raw_content:
|
||||
payload['raw_content'] = raw_content
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.create_task(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
|
||||
def workspace_create_shipping_task_from_notice():
|
||||
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。"""
|
||||
user = _require_user()
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
raise ValidationError('file is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.notice_upload import guess_source_type, intake_notice_attachment, notice_source_file_type
|
||||
filename = upload.filename or 'notice'
|
||||
raw = upload.read() or b''
|
||||
source_file_type = notice_source_file_type(upload)
|
||||
source_type = guess_source_type(filename)
|
||||
conversation_id = str(request.form.get('conversation_id') or '').strip()
|
||||
payload = {'user_id': user.id, 'source_type': source_type}
|
||||
if conversation_id:
|
||||
payload['conversation_id'] = conversation_id
|
||||
created = shipping_tools.create_task(payload)
|
||||
task_id = str(created.get('task_id') or '').strip()
|
||||
if not task_id:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='failed to create task', http_status=500)
|
||||
intake = intake_notice_attachment(
|
||||
filename=filename,
|
||||
raw=raw,
|
||||
source_file_type=source_file_type,
|
||||
storage='task',
|
||||
task_no=task_id,
|
||||
)
|
||||
if not intake.accepted:
|
||||
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint
|
||||
return jsonify({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED)})
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
if task:
|
||||
task.raw_content = intake.text
|
||||
task.source_file_name = intake.filename or task.source_file_name
|
||||
task.source_file_type = intake.source_file_type or task.source_file_type
|
||||
db.session.commit()
|
||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
|
||||
orchestrator_started = start_task_orchestrator(task_id)
|
||||
return jsonify({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/replace-notice', methods=['POST'])
|
||||
def workspace_replace_shipping_task_notice(task_no: str):
|
||||
"""重新上传发货通知并覆盖当前任务,不新建批次/任务。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
raise ValidationError('file is required')
|
||||
from app.services.shipping_notice import task_workflow
|
||||
from app.services.shipping_notice.notice_upload import intake_notice_attachment, notice_source_file_type
|
||||
intake = intake_notice_attachment(
|
||||
filename=upload.filename or 'notice',
|
||||
raw=upload.read() or b'',
|
||||
source_file_type=notice_source_file_type(upload),
|
||||
storage='task',
|
||||
task_no=task.task_no,
|
||||
)
|
||||
task.source_type = intake.source_type or task.source_type
|
||||
result = task_workflow.replace_task_notice(
|
||||
task,
|
||||
raw_text=intake.text,
|
||||
source_file_name=intake.filename,
|
||||
source_file_type=intake.source_file_type,
|
||||
warnings=list(intake.warnings),
|
||||
)
|
||||
data = result.setdefault('data', {})
|
||||
if isinstance(data, dict):
|
||||
data['notice_upload'] = intake.to_notice_upload_meta()
|
||||
return _ok(result)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>', methods=['GET'])
|
||||
def workspace_shipping_task_detail(task_no: str):
|
||||
"""
|
||||
返回指定任务的详情快照与内嵌 UI State。
|
||||
|
||||
核心逻辑:详情接口直接内嵌 `ui_state`,让页面首屏读取任务详情时即可拿到
|
||||
checkpoint / action_buttons / steps,减少前端二次推导与竞态刷新。
|
||||
"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok({
|
||||
**serialize_task_detail(task),
|
||||
'ui_state': build_task_ui_state(task),
|
||||
})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/ui-state', methods=['GET'])
|
||||
def workspace_shipping_task_ui_state(task_no: str):
|
||||
"""
|
||||
返回单票任务 UI State。
|
||||
|
||||
核心逻辑:Chat 顶部步骤条、动作按钮和工作台详情统一复用这里的状态机投影,
|
||||
避免不同前端入口重复拼装按钮集合。
|
||||
"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok(build_task_ui_state(task))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET'])
|
||||
def workspace_shipping_task_chat_actions(task_no: str):
|
||||
"""返回聊天气泡侧所需的动作按钮与检查点信息。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(build_chat_actions_payload(task))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry', methods=['POST'])
|
||||
def workspace_retry_shipping_task(task_no: str):
|
||||
"""重试当前任务,适用于超时、解析失败或自动推进中断后的恢复。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = {'task_id': task.task_no}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.retry_task(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/upload-inventory', methods=['POST'])
|
||||
def workspace_upload_shipping_inventory(task_no: str):
|
||||
"""用户态上传库存 Excel,并在服务端完成解析。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
upload = request.files.get('file')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.upload_inventory_file(task.task_no, upload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/confirm-inventory-source', methods=['POST'])
|
||||
def workspace_confirm_shipping_inventory_source(task_no: str):
|
||||
"""确认当前任务的库存 RPA 来源,并继续触发库存导出。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
source_code = str(data.get('source_code') or '').strip()
|
||||
if not source_code:
|
||||
raise ValidationError('source_code is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.confirm_inventory_source({
|
||||
'task_id': task.task_no,
|
||||
'source_code': source_code,
|
||||
'_trusted_user_id': user.id,
|
||||
}))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/apply-inventory-mapping', methods=['POST'])
|
||||
def workspace_apply_inventory_mapping(task_no: str):
|
||||
"""提交库存字段映射,并允许在工作台侧自动回退到下一步。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
data = request.get_json(silent=True) or {}
|
||||
map_json = data.get(MAP_JSON)
|
||||
if not isinstance(map_json, dict) or not map_json:
|
||||
raise ValidationError(f'{MAP_JSON} is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {'task_id': task.task_no, MAP_JSON: map_json, AUTO_CHAIN_FALLBACK: True}
|
||||
return jsonify(shipping_tools.apply_inventory_mapping(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/submit-decision', methods=['POST'])
|
||||
def workspace_submit_shipping_decision(task_no: str):
|
||||
"""以用户态提交人工决策,绕过 Dify Tool 路由直接驱动状态机。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
decision = str(data.get('decision') or '').strip()
|
||||
if not decision:
|
||||
raise ValidationError('decision is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {'task_id': task.task_no, 'decision': decision, AUTO_CHAIN_FALLBACK: True, 'event_source': 'workspace_api'}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.submit_decision(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-fields', methods=['POST'])
|
||||
def workspace_update_shipping_notice_fields(task_no: str):
|
||||
"""更新发货通知单头字段。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
fields = data.get('fields')
|
||||
if not isinstance(fields, dict) or not fields:
|
||||
raise ValidationError('fields is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {'task_id': task.task_no, 'fields': fields}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.update_notice_fields(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-line', methods=['POST'])
|
||||
def workspace_update_shipping_notice_line(task_no: str):
|
||||
"""更新发货通知中的指定订单行。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
line_index = int(data.get('line_index'))
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('line_index is required')
|
||||
patch = data.get('patch')
|
||||
if not isinstance(patch, dict) or not patch:
|
||||
raise ValidationError('patch is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {'task_id': task.task_no, 'line_index': line_index, 'patch': patch}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.update_notice_line(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/add-notice-line', methods=['POST'])
|
||||
def workspace_add_shipping_notice_line(task_no: str):
|
||||
"""为发货通知新增订单行。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
line = data.get('line')
|
||||
if not isinstance(line, dict) or not line:
|
||||
raise ValidationError('line is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {'task_id': task.task_no, 'line': line}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.add_notice_line(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/remove-notice-line', methods=['POST'])
|
||||
def workspace_remove_shipping_notice_line(task_no: str):
|
||||
"""删除发货通知中的指定订单行。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
line_index = int(data.get('line_index'))
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('line_index is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {'task_id': task.task_no, 'line_index': line_index}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.remove_notice_line(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/auto-progress', methods=['POST'])
|
||||
def workspace_auto_progress_shipping_task(task_no: str):
|
||||
"""用户态触发 auto_progress,作为聊天前端的兜底自动推进入口。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload: dict = {'task_id': task.task_no}
|
||||
for key in ('lang', 'locale', 'language'):
|
||||
if data.get(key):
|
||||
payload[key] = data[key]
|
||||
break
|
||||
result = shipping_tools.auto_progress(payload)
|
||||
if isinstance(result, dict) and result.get('status') == 'ok':
|
||||
gen_data = result.get('data')
|
||||
if isinstance(gen_data, dict) and gen_data.get('export_file_path'):
|
||||
gen_data = {**gen_data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}
|
||||
result = {**result, 'data': gen_data}
|
||||
return jsonify(result)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/match-inventory', methods=['POST'])
|
||||
def workspace_match_shipping_inventory(task_no: str):
|
||||
"""执行库存匹配,并在生成 Excel 后补充前端可直接下载的链接。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint, human_options_for_checkpoint
|
||||
matched = shipping_tools.match_inventory({'task_id': task.task_no, AUTO_CHAIN_FALLBACK: True})
|
||||
if not isinstance(matched, dict):
|
||||
return jsonify(matched)
|
||||
data = matched.get('data')
|
||||
if isinstance(data, dict) and data.get('export_file_path'):
|
||||
matched = {**matched, 'data': {**data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}}
|
||||
checkpoint = matched.get('checkpoint') or CP_EXPORT_GENERATED
|
||||
if matched.get('status') == 'ok' and data and data.get('export_file_path'):
|
||||
matched['checkpoint'] = checkpoint
|
||||
if 'human_options' not in matched:
|
||||
options = human_options_for_checkpoint(checkpoint)
|
||||
if options is not None:
|
||||
matched['human_options'] = options
|
||||
if 'action_buttons' not in matched:
|
||||
buttons = action_buttons_for_checkpoint(checkpoint)
|
||||
if buttons:
|
||||
matched['action_buttons'] = buttons
|
||||
return jsonify(matched)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/mark-manual-uploaded', methods=['POST'])
|
||||
def workspace_mark_manual_uploaded(task_no: str):
|
||||
"""标记货代系统已人工上传完成,无需再等待 RPA 回执。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'}))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry-upload', methods=['POST'])
|
||||
def workspace_retry_shipping_upload(task_no: str):
|
||||
"""用户态重试上传货代系统,直接触发既有 RPA 上传链路。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'retry_upload'}))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/generate-excel', methods=['POST'])
|
||||
def workspace_generate_shipping_excel(task_no: str):
|
||||
"""为指定任务生成出货 Excel,并补充工作台下载链接。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
result = shipping_tools.generate_excel({'task_id': task.task_no})
|
||||
if isinstance(result, dict) and result.get('status') == 'ok':
|
||||
data = result.get('data')
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
result['data'] = data
|
||||
data['download_url'] = f'/api/workspace/shipping-tasks/{task.task_no}/export'
|
||||
return jsonify(result)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
|
||||
def workspace_shipping_task_export(task_no: str):
|
||||
"""下载当前用户可访问任务的出货 Excel。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
err_msg = task_export_error_message(task)
|
||||
if err_msg:
|
||||
raise NotFoundError(err_msg)
|
||||
resolved = resolve_task_export_download(task)
|
||||
assert resolved is not None
|
||||
path, download_name = resolved
|
||||
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['GET'])
|
||||
def workspace_list_shipping_notice_intakes():
|
||||
"""列出当前会话下未消费的活跃接入记录。"""
|
||||
user = _require_user()
|
||||
conversation_id = str(request.args.get('conversation_id') or '').strip() or None
|
||||
status = str(request.args.get('status') or '').strip().lower()
|
||||
from app.services.shipping_notice.intake_service import list_active_intakes_for_conversation
|
||||
|
||||
if status and status != 'active':
|
||||
return _ok({'items': []})
|
||||
items = list_active_intakes_for_conversation(user_id=user.id, conversation_id=conversation_id)
|
||||
return _ok({'items': items})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['POST'])
|
||||
def workspace_create_shipping_notice_intake():
|
||||
"""基于 FileAsset 创建发货通知接入记录并投递预解析任务。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
asset_no = str(body.get('asset_no') or '').strip()
|
||||
if not asset_no:
|
||||
raise ValidationError('asset_no is required')
|
||||
conversation_id = str(body.get('conversation_id') or '').strip() or None
|
||||
from app.services.shipping_notice.intake_service import create_shipping_notice_intake
|
||||
|
||||
data = create_shipping_notice_intake(
|
||||
user_id=user.id,
|
||||
asset_no=asset_no,
|
||||
conversation_id=conversation_id,
|
||||
)
|
||||
return ok(data, request_id=getattr(g, 'request_id', None), status=202)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/<intake_no>', methods=['GET'])
|
||||
def workspace_get_shipping_notice_intake(intake_no: str):
|
||||
"""查询单个接入记录。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.intake_service import get_intake_detail
|
||||
|
||||
return _ok(get_intake_detail(user_id=user.id, intake_no=intake_no))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/status', methods=['POST'])
|
||||
def workspace_shipping_notice_intake_statuses():
|
||||
"""批量查询接入状态。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
intake_nos = body.get('intake_nos')
|
||||
if not isinstance(intake_nos, list):
|
||||
raise ValidationError('intake_nos is required')
|
||||
from app.services.shipping_notice.intake_service import get_intake_statuses
|
||||
|
||||
return _ok({'items': get_intake_statuses(user_id=user.id, intake_nos=intake_nos)})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/<intake_no>/retry', methods=['POST'])
|
||||
def workspace_retry_shipping_notice_intake(intake_no: str):
|
||||
"""重试失败的预解析。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.intake_service import retry_intake_parse
|
||||
|
||||
return _ok(retry_intake_parse(user_id=user.id, intake_no=intake_no))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/<intake_no>', methods=['DELETE'])
|
||||
def workspace_cancel_shipping_notice_intake(intake_no: str):
|
||||
"""取消未消费接入记录。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.intake_service import cancel_intake
|
||||
|
||||
cancel_intake(user_id=user.id, intake_no=intake_no)
|
||||
return _ok({'cancelled': True})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/intakes/<intake_no>/duplicate-resolution',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_resolve_shipping_notice_duplicate(intake_no: str):
|
||||
"""保存发货通知重复检测决策。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
action = str(body.get('action') or '').strip()
|
||||
target_task_no = str(body.get('target_task_no') or '').strip() or None
|
||||
reason = str(body.get('reason') or '').strip() or None
|
||||
from app.services.shipping_notice.intake_service import resolve_intake_duplicate
|
||||
|
||||
return _ok(
|
||||
resolve_intake_duplicate(
|
||||
user_id=user.id,
|
||||
intake_no=intake_no,
|
||||
action=action,
|
||||
target_task_no=target_task_no,
|
||||
reason=reason,
|
||||
actor=user,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/intakes/<intake_no>/duplicate-refresh',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_refresh_shipping_notice_duplicate(intake_no: str):
|
||||
"""重新执行重复检测。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.intake_service import refresh_intake_duplicate_detection
|
||||
|
||||
return _ok(refresh_intake_duplicate_detection(user_id=user.id, intake_no=intake_no))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-intakes', methods=['POST'])
|
||||
def workspace_create_shipping_batch_from_intakes():
|
||||
"""从已解析接入记录确认建批。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
intake_nos = body.get('intake_nos')
|
||||
if not isinstance(intake_nos, list) or not intake_nos:
|
||||
raise ValidationError('intake_nos is required')
|
||||
conversation_id = str(body.get('conversation_id') or '').strip() or None
|
||||
from app.services.shipping_notice.batch_create_idempotency import (
|
||||
normalize_create_idempotency_key,
|
||||
warn_missing_create_idempotency_key,
|
||||
)
|
||||
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
|
||||
|
||||
idempotency_key = normalize_create_idempotency_key(
|
||||
request.headers.get('Idempotency-Key') or body.get('idempotency_key')
|
||||
)
|
||||
if not idempotency_key:
|
||||
warn_missing_create_idempotency_key(source='workspace_create_shipping_batch_from_intakes')
|
||||
result = create_shipping_batch_from_intakes(
|
||||
user_id=user.id,
|
||||
conversation_id=conversation_id,
|
||||
intake_nos=[str(item) for item in intake_nos],
|
||||
create_idempotency_key=idempotency_key,
|
||||
)
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/retry-pending', methods=['POST'])
|
||||
def workspace_retry_shipping_batch_pending(batch_no: str):
|
||||
"""重试批次中仍可自动推进的任务,跳过终态和人工阻断任务。"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks
|
||||
return jsonify(retry_batch_pending_tasks(batch.batch_no))
|
||||
@@ -1,18 +0,0 @@
|
||||
"""
|
||||
backend/app/api/workspace_file_check.py
|
||||
|
||||
用途:工作台文件检核 API 兼容 shim(Wave 1 迁包)。
|
||||
依赖:app.api.workspace.file_check。
|
||||
逻辑:旧 import 路径仍可用;新代码请用 app.api.workspace。
|
||||
"""
|
||||
from app.api.workspace.file_check import (
|
||||
serialize_current_step,
|
||||
serialize_file_judgement,
|
||||
workspace_file_check_bp,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'serialize_current_step',
|
||||
'serialize_file_judgement',
|
||||
'workspace_file_check_bp',
|
||||
]
|
||||
@@ -1,10 +0,0 @@
|
||||
"""
|
||||
backend/app/api/workspace_schedule.py
|
||||
|
||||
用途:工作台排程 API 兼容 shim(Wave 1 迁包)。
|
||||
依赖:app.api.workspace.schedule。
|
||||
逻辑:旧 import 路径仍可用;新代码请用 app.api.workspace。
|
||||
"""
|
||||
from app.api.workspace.schedule import workspace_schedule_bp
|
||||
|
||||
__all__ = ['workspace_schedule_bp']
|
||||
@@ -1,10 +0,0 @@
|
||||
"""
|
||||
backend/app/api/workspace_shipping_notice.py
|
||||
|
||||
用途:工作台发货通知 API 兼容 shim(Wave 1 迁包)。
|
||||
依赖:app.api.workspace.shipping_notice。
|
||||
逻辑:旧 import 路径继续 re-export `workspace_shipping_notice_bp`;真实实现统一维护在 workspace 子包中,避免双份路由漂移。
|
||||
"""
|
||||
from app.api.workspace.shipping_notice import workspace_shipping_notice_bp
|
||||
|
||||
__all__ = ['workspace_shipping_notice_bp']
|
||||
@@ -0,0 +1,112 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=".env",
|
||||
env_file_encoding="utf-8",
|
||||
extra="ignore",
|
||||
)
|
||||
|
||||
app_name: str = "Document Cleaning"
|
||||
api_prefix: str = "/api"
|
||||
jwt_secret: str = "change-me-in-production"
|
||||
jwt_algorithm: str = "HS256"
|
||||
access_token_expire_minutes: int = 720
|
||||
|
||||
database_backend: Literal["sqlite", "postgres"] = "sqlite"
|
||||
database_url: str = ""
|
||||
sqlite_database_url: str = "sqlite:///./document_cleaning.db"
|
||||
postgres_database_url: str = "postgresql+psycopg://postgres:postgres@localhost:5432/document_cleaning"
|
||||
redis_url: str = "redis://redis:6379/0"
|
||||
|
||||
data_root: Path = Field(default=Path("./data"))
|
||||
public_base_url: str = "http://192.168.100.230:8891"
|
||||
allowed_origins: str = "http://192.168.100.230:8891,http://localhost:5173"
|
||||
|
||||
dify_base_url: str = "https://api.dify.ai/v1"
|
||||
dify_api_key: str = ""
|
||||
dify_permission: str = "all_team_members"
|
||||
|
||||
default_indexing_technique: str = "high_quality"
|
||||
default_search_method: str = "hybrid_search"
|
||||
default_doc_form: str = "text_model"
|
||||
default_embedding_model_provider: str = ""
|
||||
default_embedding_model: str = ""
|
||||
default_reranking_model_provider: str = ""
|
||||
default_reranking_model: str = ""
|
||||
default_top_k: int = 5
|
||||
default_score_threshold_enabled: bool = True
|
||||
default_score_threshold: float = 0.35
|
||||
|
||||
default_admin_username: str = "admin"
|
||||
default_admin_password: str = "admin123456"
|
||||
default_admin_name: str = "System Admin"
|
||||
integration_api_key: str = ""
|
||||
integration_download_secret: str = ""
|
||||
integration_download_expire_minutes: int = 15
|
||||
|
||||
rq_queue_name: str = "document-cleaning"
|
||||
rq_default_timeout: int = 3600
|
||||
task_execution_mode: Literal["rq", "sync"] = "rq"
|
||||
dify_sync_max_retries: int = 4
|
||||
dify_sync_retry_schedule: str = "30,60,120,300"
|
||||
dify_sync_cooldown_seconds: int = 60
|
||||
watchdog_stale_sync_timeout_seconds: int = 900
|
||||
watchdog_stale_convert_timeout_seconds: int = 900
|
||||
watchdog_convert_orphan_grace_seconds: int = 120
|
||||
|
||||
edkb_word_timeout_sec: int = 120
|
||||
edkb_file_timeout_sec: int = 900
|
||||
|
||||
def origins_list(self) -> list[str]:
|
||||
return [item.strip() for item in self.allowed_origins.split(",") if item.strip()]
|
||||
|
||||
def dify_sync_retry_delays(self) -> list[int]:
|
||||
values: list[int] = []
|
||||
for raw in self.dify_sync_retry_schedule.split(","):
|
||||
token = raw.strip()
|
||||
if not token:
|
||||
continue
|
||||
try:
|
||||
parsed = int(token)
|
||||
except ValueError:
|
||||
continue
|
||||
if parsed > 0:
|
||||
values.append(parsed)
|
||||
return values or [30, 60, 120, 300]
|
||||
|
||||
@staticmethod
|
||||
def _normalize_database_url(url: str) -> str:
|
||||
normalized = url.strip()
|
||||
if normalized.startswith("postgresql://"):
|
||||
return normalized.replace("postgresql://", "postgresql+psycopg://", 1)
|
||||
return normalized
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_database_url(self) -> "Settings":
|
||||
if self.database_url:
|
||||
self.database_url = self._normalize_database_url(self.database_url)
|
||||
return self
|
||||
|
||||
selected = self.sqlite_database_url if self.database_backend == "sqlite" else self.postgres_database_url
|
||||
self.database_url = self._normalize_database_url(selected)
|
||||
return self
|
||||
|
||||
def ensure_data_dirs(self) -> None:
|
||||
for name in ["original", "markdown", "assets", "jobs", "tmp"]:
|
||||
(self.data_root / name).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
settings = Settings()
|
||||
settings.ensure_data_dirs()
|
||||
return settings
|
||||
@@ -1,10 +0,0 @@
|
||||
"""
|
||||
backend/app/core/__init__.py
|
||||
|
||||
用途:横切能力包入口(errors、response、auth、config、decorators)。
|
||||
逻辑:业务代码 from app.core.errors / app.core.auth.jwt 等子模块 import。
|
||||
"""
|
||||
|
||||
from app.core.errors import AppError # noqa: F401
|
||||
|
||||
__all__ = ['AppError']
|
||||
@@ -1,6 +0,0 @@
|
||||
"""
|
||||
backend/app/core/auth/__init__.py
|
||||
|
||||
用途:认证与当前用户解析包入口。
|
||||
逻辑:api 层通过 get_current_user 获取 User;Wave 1 自 auth_jwt.py 迁入 jwt.py。
|
||||
"""
|
||||
@@ -1,39 +0,0 @@
|
||||
"""
|
||||
backend/app/core/auth/context.py
|
||||
|
||||
用途:从 Flask g/request 解析请求上下文(request_id、user),供 api 层薄封装。
|
||||
逻辑:Wave 3 拆分 user/chat 路由时,将重复 auth 逻辑收敛到本模块。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def get_request_id() -> str | None:
|
||||
"""
|
||||
读取当前请求的 X-Request-Id 或 g.request_id。
|
||||
核心逻辑:延迟 import flask.g,避免 services 层依赖。
|
||||
Returns:
|
||||
request_id 字符串,无上下文时返回 None。
|
||||
"""
|
||||
try:
|
||||
from flask import g
|
||||
|
||||
return getattr(g, 'request_id', None)
|
||||
except RuntimeError:
|
||||
return None
|
||||
|
||||
|
||||
def get_optional_config(key: str, default: Any = None) -> Any:
|
||||
"""
|
||||
读取 Flask app.config 项(仅 api / jobs context 使用)。
|
||||
Args:
|
||||
key: config 键名。
|
||||
default: 无 app context 时的默认值。
|
||||
"""
|
||||
try:
|
||||
from flask import current_app
|
||||
|
||||
return current_app.config.get(key, default)
|
||||
except RuntimeError:
|
||||
return default
|
||||
@@ -1,314 +0,0 @@
|
||||
"""
|
||||
backend/app/core/auth/jwt.py
|
||||
|
||||
用途:Casdoor JWT 校验、legacy header 回退与当前用户解析。
|
||||
依赖:app.extensions.db、app.models.User、PyJWT、requests。
|
||||
逻辑:api 层与 decorators 调用 get_current_user()。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Optional
|
||||
|
||||
import jwt
|
||||
import requests
|
||||
from flask import current_app, g, request
|
||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import User
|
||||
|
||||
_JWKS_CACHE: dict[str, Any] = {
|
||||
'url': None,
|
||||
'keys': None,
|
||||
'expires_at': 0.0,
|
||||
}
|
||||
|
||||
|
||||
def _token_brief(token: Optional[str]) -> str:
|
||||
if not token:
|
||||
return 'empty'
|
||||
text = str(token)
|
||||
if len(text) <= 16:
|
||||
return f'len={len(text)}:{text}'
|
||||
return f'len={len(text)}:{text[:8]}...{text[-8:]}'
|
||||
|
||||
|
||||
def _extract_bearer_token() -> Optional[str]:
|
||||
auth = request.headers.get('Authorization', '')
|
||||
if not auth:
|
||||
return None
|
||||
parts = auth.split(' ', 1)
|
||||
if len(parts) != 2 or parts[0].lower() != 'bearer':
|
||||
return None
|
||||
token = parts[1].strip()
|
||||
return token or None
|
||||
|
||||
|
||||
def _get_jwks_keys(jwks_url: str) -> dict:
|
||||
now = time.time()
|
||||
if (
|
||||
_JWKS_CACHE.get('url') == jwks_url
|
||||
and isinstance(_JWKS_CACHE.get('keys'), dict)
|
||||
and now < float(_JWKS_CACHE.get('expires_at') or 0.0)
|
||||
):
|
||||
return _JWKS_CACHE['keys']
|
||||
|
||||
resp = requests.get(jwks_url, timeout=5)
|
||||
resp.raise_for_status()
|
||||
data = resp.json() or {}
|
||||
keys = {}
|
||||
for item in data.get('keys', []):
|
||||
kid = item.get('kid')
|
||||
if kid:
|
||||
keys[kid] = item
|
||||
if not keys:
|
||||
raise ValueError('No JWKS keys found')
|
||||
|
||||
_JWKS_CACHE['url'] = jwks_url
|
||||
_JWKS_CACHE['keys'] = keys
|
||||
_JWKS_CACHE['expires_at'] = now + 300
|
||||
return keys
|
||||
|
||||
|
||||
def _decode_jwt(token: str) -> dict:
|
||||
issuer = (current_app.config.get('AUTH_JWT_ISSUER') or '').strip()
|
||||
audience = (current_app.config.get('AUTH_JWT_AUDIENCE') or '').strip()
|
||||
jwks_url = (current_app.config.get('AUTH_JWT_JWKS_URL') or '').strip()
|
||||
if not issuer or not audience or not jwks_url:
|
||||
raise ValueError('JWT auth is not fully configured')
|
||||
|
||||
header = jwt.get_unverified_header(token)
|
||||
kid = header.get('kid')
|
||||
if not kid:
|
||||
if not bool(current_app.config.get('AUTH_ALLOW_LOCAL_JWT', True)):
|
||||
raise ValueError('JWT header missing kid')
|
||||
secret = current_app.config.get('SECRET_KEY')
|
||||
if not secret:
|
||||
raise ValueError('Local JWT secret is missing')
|
||||
local_issuer = (current_app.config.get('AUTH_LOCAL_JWT_ISSUER') or 'hxops-backend').strip()
|
||||
local_audience = (current_app.config.get('AUTH_LOCAL_JWT_AUDIENCE') or 'hxops-frontend').strip()
|
||||
return jwt.decode(
|
||||
token,
|
||||
key=secret,
|
||||
algorithms=['HS256'],
|
||||
audience=local_audience,
|
||||
issuer=local_issuer,
|
||||
options={'require': ['exp', 'iat']},
|
||||
)
|
||||
|
||||
keys = _get_jwks_keys(jwks_url)
|
||||
jwk = keys.get(kid)
|
||||
if not jwk:
|
||||
_JWKS_CACHE['expires_at'] = 0.0
|
||||
keys = _get_jwks_keys(jwks_url)
|
||||
jwk = keys.get(kid)
|
||||
if not jwk:
|
||||
raise ValueError('No matching JWKS key for token')
|
||||
|
||||
public_key = None
|
||||
pyjwk = getattr(jwt, 'PyJWK', None)
|
||||
if pyjwk and hasattr(pyjwk, 'from_dict'):
|
||||
public_key = pyjwk.from_dict(jwk).key
|
||||
if public_key is None:
|
||||
rsa_alg = getattr(getattr(jwt, 'algorithms', None), 'RSAAlgorithm', None)
|
||||
if rsa_alg and hasattr(rsa_alg, 'from_jwk'):
|
||||
public_key = rsa_alg.from_jwk(json.dumps(jwk))
|
||||
if public_key is None:
|
||||
get_algs = getattr(getattr(jwt, 'algorithms', None), 'get_default_algorithms', None)
|
||||
if callable(get_algs):
|
||||
rs256 = (get_algs() or {}).get('RS256')
|
||||
if rs256 and hasattr(rs256, 'from_jwk'):
|
||||
public_key = rs256.from_jwk(json.dumps(jwk))
|
||||
if public_key is None:
|
||||
raise ValueError('Cannot build RSA public key from JWK; check installed jwt package')
|
||||
|
||||
return jwt.decode(
|
||||
token,
|
||||
key=public_key,
|
||||
algorithms=['RS256', 'RS384', 'RS512'],
|
||||
audience=audience,
|
||||
issuer=issuer,
|
||||
options={'require': ['exp', 'iat']},
|
||||
)
|
||||
|
||||
|
||||
def _extract_unverified_claims(token: str) -> dict:
|
||||
try:
|
||||
return jwt.decode(
|
||||
token,
|
||||
options={
|
||||
'verify_signature': False,
|
||||
'verify_exp': False,
|
||||
'verify_iat': False,
|
||||
'verify_nbf': False,
|
||||
'verify_aud': False,
|
||||
'verify_iss': False,
|
||||
},
|
||||
) or {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _resolve_user_from_claims(claims: dict) -> Optional[User]:
|
||||
def _lookup() -> Optional[User]:
|
||||
user_id = claims.get('user_id') or claims.get('id')
|
||||
if user_id is not None:
|
||||
try:
|
||||
user = db.session.get(User, int(user_id))
|
||||
if user:
|
||||
return user
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
username = claims.get('preferred_username') or claims.get('username') or claims.get('name')
|
||||
if username:
|
||||
user = db.session.query(User).filter_by(username=str(username)).first()
|
||||
if user:
|
||||
return user
|
||||
|
||||
email = claims.get('email')
|
||||
if email:
|
||||
user = db.session.query(User).filter_by(email=str(email)).first()
|
||||
if user:
|
||||
return user
|
||||
return None
|
||||
|
||||
try:
|
||||
return _lookup()
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning(
|
||||
'[auth_jwt] transient db error when resolving user, retry with reconnect path=%s err=%s',
|
||||
request.path,
|
||||
exc,
|
||||
)
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
db.engine.dispose()
|
||||
except Exception:
|
||||
current_app.logger.warning('[auth_jwt] failed to dispose engine during user reconnect recovery', exc_info=True)
|
||||
return _lookup()
|
||||
|
||||
|
||||
def _legacy_header_user() -> Optional[User]:
|
||||
def _lookup() -> Optional[User]:
|
||||
user_id = request.headers.get('X-User-Id')
|
||||
if user_id:
|
||||
try:
|
||||
user = db.session.get(User, int(user_id))
|
||||
if user:
|
||||
return user
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
username = request.headers.get('X-Username')
|
||||
if username:
|
||||
return db.session.query(User).filter_by(username=username).first()
|
||||
return None
|
||||
|
||||
try:
|
||||
return _lookup()
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning(
|
||||
'[auth_jwt] transient db error when resolving legacy header user, retry with reconnect path=%s err=%s',
|
||||
request.path,
|
||||
exc,
|
||||
)
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
db.engine.dispose()
|
||||
except Exception:
|
||||
current_app.logger.warning('[auth_jwt] failed to dispose engine during legacy user reconnect recovery', exc_info=True)
|
||||
return _lookup()
|
||||
|
||||
|
||||
def _current_user_cache_key() -> tuple[str, str, str, str]:
|
||||
"""构造当前请求用户缓存键,避免测试或保留上下文场景串用上一条请求的用户缓存。"""
|
||||
return (
|
||||
str(request.headers.get('Authorization') or '').strip(),
|
||||
str(request.headers.get('X-User-Id') or '').strip(),
|
||||
str(request.headers.get('X-Username') or '').strip(),
|
||||
f'{request.method}:{request.path}',
|
||||
)
|
||||
|
||||
|
||||
def get_current_user() -> Optional[User]:
|
||||
"""
|
||||
解析当前请求用户:优先 JWT Bearer,其次 legacy header(若配置启用)。
|
||||
Returns:
|
||||
User 实例;未认证时返回 None。
|
||||
"""
|
||||
cache_key = _current_user_cache_key()
|
||||
cached = getattr(g, 'current_user', None)
|
||||
cached_key = getattr(g, 'current_user_cache_key', None)
|
||||
if cached is not None and cached_key == cache_key:
|
||||
return cached
|
||||
|
||||
token = _extract_bearer_token()
|
||||
if token:
|
||||
try:
|
||||
claims = _decode_jwt(token)
|
||||
user = _resolve_user_from_claims(claims)
|
||||
except Exception:
|
||||
# Decode metadata is diagnostic-only: do not emit it for successful requests.
|
||||
try:
|
||||
header = jwt.get_unverified_header(token)
|
||||
except Exception:
|
||||
header = {}
|
||||
unverified = _extract_unverified_claims(token)
|
||||
expected_issuer = (current_app.config.get('AUTH_JWT_ISSUER') or '').strip()
|
||||
expected_audience = (current_app.config.get('AUTH_JWT_AUDIENCE') or '').strip()
|
||||
current_app.logger.error(
|
||||
'[auth_jwt] decode context kid=%s alg=%s token=%s token_iss=%s token_aud=%s '
|
||||
'expected_iss=%s expected_aud=%s path=%s',
|
||||
header.get('kid'),
|
||||
header.get('alg'),
|
||||
_token_brief(token),
|
||||
unverified.get('iss'),
|
||||
unverified.get('aud'),
|
||||
expected_issuer,
|
||||
expected_audience,
|
||||
request.path,
|
||||
)
|
||||
current_app.logger.exception('[auth_jwt] decode failed')
|
||||
user = None
|
||||
claims = None
|
||||
if user:
|
||||
g.jwt_claims = claims
|
||||
g.current_user = user
|
||||
g.current_user_cache_key = cache_key
|
||||
return user
|
||||
|
||||
if bool(current_app.config.get('AUTH_LEGACY_HEADER_ENABLED', True)):
|
||||
user = _legacy_header_user()
|
||||
if user:
|
||||
g.current_user = user
|
||||
g.current_user_cache_key = cache_key
|
||||
return user
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def issue_local_access_token(user: User) -> str:
|
||||
"""签发本地 HS256 JWT(密码登录兼容)。"""
|
||||
now = datetime.now(timezone.utc)
|
||||
exp_hours = int(current_app.config.get('AUTH_LOCAL_JWT_EXPIRES_HOURS') or 12)
|
||||
payload = {
|
||||
'sub': str(user.id),
|
||||
'id': user.id,
|
||||
'user_id': user.id,
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'email': user.email,
|
||||
'iat': int(now.timestamp()),
|
||||
'exp': int((now + timedelta(hours=max(1, exp_hours))).timestamp()),
|
||||
'iss': (current_app.config.get('AUTH_LOCAL_JWT_ISSUER') or 'hxops-backend'),
|
||||
'aud': (current_app.config.get('AUTH_LOCAL_JWT_AUDIENCE') or 'hxops-frontend'),
|
||||
}
|
||||
secret = current_app.config.get('SECRET_KEY')
|
||||
return jwt.encode(payload, secret, algorithm='HS256')
|
||||
@@ -1,5 +0,0 @@
|
||||
"""
|
||||
backend/app/core/config/__init__.py
|
||||
|
||||
用途:配置包入口(settings、env_persistence)。
|
||||
"""
|
||||
@@ -1,249 +0,0 @@
|
||||
"""
|
||||
backend/app/core/config/env_persistence.py
|
||||
|
||||
用途:运行时配置 DB 持久化与 env 镜像(WeCom 等 admin 设置)。
|
||||
依赖:app.extensions.db、app.models.AppSetting。
|
||||
逻辑:before_request 调用 apply_env_settings;persist_env_settings 供 admin 写入。
|
||||
|
||||
Storage strategy:
|
||||
1. Database (app_settings) - canonical
|
||||
2. .env.local (dev only) - secondary mirror
|
||||
3. os.environ - in-process mirror on write
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
from dotenv import dotenv_values, set_key
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
_BACKEND_DIR = Path(__file__).resolve().parents[3]
|
||||
_ROOT_DIR = _BACKEND_DIR.parent
|
||||
ROOT_ENV_LOCAL_PATH = _ROOT_DIR / '.env.local'
|
||||
LEGACY_BACKEND_ENV_PATH = _BACKEND_DIR / '.env'
|
||||
# Backward-compatible alias for tests and older callers that still patch/read
|
||||
# the historical backend/.env location directly.
|
||||
BACKEND_ENV_PATH = LEGACY_BACKEND_ENV_PATH
|
||||
WECOM_BOOL_KEYS = {
|
||||
'WECOM_ENABLED',
|
||||
'WECOM_AUTO_CREATE_USER',
|
||||
'WECOM_MOBILE_NORMALIZE',
|
||||
'WECOM_NOTIFY_ENABLED',
|
||||
'WECOM_FEEDBACK_NOTIFY_ENABLED',
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _ensure_env_file_exists() -> bool:
|
||||
try:
|
||||
ROOT_ENV_LOCAL_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not ROOT_ENV_LOCAL_PATH.exists():
|
||||
ROOT_ENV_LOCAL_PATH.write_text('', encoding='utf-8')
|
||||
return True
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot create %s: %s', ROOT_ENV_LOCAL_PATH, exc)
|
||||
return False
|
||||
|
||||
|
||||
def _normalize_env_name(raw: str | None) -> str:
|
||||
value = (raw or '').strip().lower()
|
||||
if value in ('dev', 'development', ''):
|
||||
return 'dev'
|
||||
if value in ('test', 'testing'):
|
||||
return 'test'
|
||||
if value in ('prod', 'production'):
|
||||
return 'prod'
|
||||
return 'dev'
|
||||
|
||||
|
||||
def _to_env_string(value: object) -> str:
|
||||
if isinstance(value, bool):
|
||||
return 'true' if value else 'false'
|
||||
if value is None:
|
||||
return ''
|
||||
return str(value)
|
||||
|
||||
|
||||
def _parse_env_value(key: str, value: object) -> object:
|
||||
if value is None:
|
||||
return None
|
||||
if key in WECOM_BOOL_KEYS:
|
||||
return str(value).strip().lower() == 'true'
|
||||
return str(value)
|
||||
|
||||
|
||||
def _matches_prefixes(key: str, prefixes: Iterable[str]) -> bool:
|
||||
return any(key.startswith(prefix) for prefix in prefixes)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Database read/write (primary store)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _persist_to_db(values: dict[str, str]) -> bool:
|
||||
"""Write key/value pairs into the ``app_settings`` table.
|
||||
|
||||
Returns True if every value was committed, False otherwise. The function
|
||||
is defensive: it must not raise, because settings persistence is also
|
||||
written to ``.env`` and we don't want to fail the API request.
|
||||
"""
|
||||
if not values:
|
||||
return True
|
||||
try:
|
||||
from app.extensions import db
|
||||
from app.models import AppSetting
|
||||
except Exception as exc: # pragma: no cover - import safety net
|
||||
logger.warning('AppSetting model unavailable: %s', exc)
|
||||
return False
|
||||
|
||||
try:
|
||||
for key, value in values.items():
|
||||
existing = db.session.get(AppSetting, key)
|
||||
if existing is None:
|
||||
db.session.add(AppSetting(key=key, value=value))
|
||||
else:
|
||||
existing.value = value
|
||||
db.session.commit()
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.warning('Failed to persist settings to DB: %s', exc)
|
||||
try:
|
||||
db.session.rollback()
|
||||
except Exception: # pragma: no cover
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _load_from_db(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
try:
|
||||
from app.extensions import db
|
||||
from app.models import AppSetting
|
||||
except Exception as exc: # pragma: no cover
|
||||
logger.debug('AppSetting model unavailable for read: %s', exc)
|
||||
return {}
|
||||
|
||||
try:
|
||||
rows = db.session.query(AppSetting).all()
|
||||
except Exception as exc:
|
||||
# Most common case: the migration has not been applied yet on a
|
||||
# freshly-built container. Degrade gracefully to .env-only mode.
|
||||
logger.debug('app_settings table not readable yet: %s', exc)
|
||||
try:
|
||||
db.session.rollback()
|
||||
except Exception: # pragma: no cover
|
||||
pass
|
||||
return {}
|
||||
|
||||
result: dict[str, str] = {}
|
||||
for row in rows:
|
||||
if row.key and _matches_prefixes(row.key, prefixes):
|
||||
result[row.key] = row.value if row.value is not None else ''
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# .env read/write (secondary store, best-effort)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _persist_to_env_file(values: dict[str, str]) -> bool:
|
||||
env_name = _normalize_env_name(os.getenv('ENV_NAME') or os.getenv('FLASK_ENV'))
|
||||
if env_name != 'dev':
|
||||
return True
|
||||
if not values:
|
||||
return True
|
||||
if not _ensure_env_file_exists():
|
||||
return False
|
||||
ok = True
|
||||
for key, value in values.items():
|
||||
try:
|
||||
set_key(str(ROOT_ENV_LOCAL_PATH), key, value, quote_mode='auto')
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot write %s to %s: %s', key, ROOT_ENV_LOCAL_PATH, exc)
|
||||
ok = False
|
||||
return ok
|
||||
|
||||
|
||||
def _load_from_env_file(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
merged: dict[str, str] = {}
|
||||
for env_path in (BACKEND_ENV_PATH, ROOT_ENV_LOCAL_PATH):
|
||||
if not env_path.exists():
|
||||
continue
|
||||
try:
|
||||
loaded = dotenv_values(env_path)
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot read %s: %s', env_path, exc)
|
||||
continue
|
||||
for key, value in loaded.items():
|
||||
if key and _matches_prefixes(key, prefixes):
|
||||
merged[key] = value if value is not None else ''
|
||||
return merged
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public API
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def persist_env_settings(values: dict[str, object]) -> dict[str, str]:
|
||||
"""Persist settings to the canonical store and mirror to ``os.environ``.
|
||||
|
||||
Order:
|
||||
1. Mirror to ``os.environ`` so the current process picks them up
|
||||
immediately.
|
||||
2. Persist to the database (canonical, survives container rebuilds).
|
||||
3. In dev only, best-effort write to ``.env.local`` so local restarts
|
||||
without DB access keep working.
|
||||
"""
|
||||
if not values:
|
||||
return {}
|
||||
|
||||
persisted: dict[str, str] = {}
|
||||
for key, value in values.items():
|
||||
env_value = _to_env_string(value)
|
||||
os.environ[key] = env_value
|
||||
persisted[key] = env_value
|
||||
|
||||
db_ok = _persist_to_db(persisted)
|
||||
file_ok = _persist_to_env_file(persisted)
|
||||
|
||||
if not db_ok and not file_ok:
|
||||
logger.error(
|
||||
'Failed to persist settings %s to BOTH database and .env.local mirror. '
|
||||
'Settings will be lost when the process restarts.',
|
||||
list(persisted.keys()),
|
||||
)
|
||||
|
||||
return persisted
|
||||
|
||||
|
||||
def apply_env_settings(prefixes: tuple[str, ...] = ('WECOM_',)) -> dict[str, object]:
|
||||
"""Load settings from the canonical store and apply to ``os.environ``.
|
||||
|
||||
DB values take priority over env-file values; both are merged so
|
||||
keys that only live in env files (e.g. fresh deploy before any admin
|
||||
edit) are still honored.
|
||||
"""
|
||||
file_values = _load_from_env_file(prefixes)
|
||||
db_values = _load_from_db(prefixes)
|
||||
|
||||
merged: dict[str, str] = {**file_values, **db_values}
|
||||
|
||||
applied: dict[str, object] = {}
|
||||
for key, raw_value in merged.items():
|
||||
parsed = _parse_env_value(key, raw_value)
|
||||
os.environ[key] = _to_env_string(parsed)
|
||||
applied[key] = parsed
|
||||
return applied
|
||||
@@ -1,432 +0,0 @@
|
||||
"""
|
||||
backend/app/core/config/settings.py
|
||||
|
||||
用途:Flask Config 类与环境文件加载(dev/test/prod)。
|
||||
依赖:dotenv、app.path_utils。
|
||||
逻辑:create_app 通过 config[config_name] 加载;旧路径 app.config 为兼容 shim。
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import dotenv_values
|
||||
|
||||
|
||||
_BACKEND_DIR = Path(__file__).resolve().parents[3]
|
||||
_ROOT_DIR = _BACKEND_DIR.parent
|
||||
|
||||
|
||||
def _normalize_env_name(raw: str | None) -> str:
|
||||
value = (raw or '').strip().lower()
|
||||
if value in ('dev', 'development', ''):
|
||||
return 'dev'
|
||||
if value in ('test', 'testing'):
|
||||
return 'test'
|
||||
if value in ('prod', 'production'):
|
||||
return 'prod'
|
||||
return 'dev'
|
||||
|
||||
|
||||
def _load_environment_files() -> str:
|
||||
"""Load env files from project root with stable priority.
|
||||
|
||||
Priority (low -> high):
|
||||
1. .env.shared
|
||||
2. .env.<ENV_NAME>
|
||||
3. .env.local (only for dev)
|
||||
4. system environment variables (always highest, never overridden)
|
||||
"""
|
||||
env_name = _normalize_env_name(os.getenv('ENV_NAME') or os.getenv('FLASK_ENV'))
|
||||
preserved_env = dict(os.environ)
|
||||
merged_values: dict[str, str] = {}
|
||||
|
||||
shared_file = _ROOT_DIR / '.env.shared'
|
||||
if shared_file.exists():
|
||||
merged_values.update({k: v for k, v in dotenv_values(shared_file).items() if v is not None})
|
||||
|
||||
env_file = _ROOT_DIR / f'.env.{env_name}'
|
||||
if env_file.exists():
|
||||
merged_values.update({k: v for k, v in dotenv_values(env_file).items() if v is not None})
|
||||
|
||||
if env_name == 'dev':
|
||||
local_file = _ROOT_DIR / '.env.local'
|
||||
if local_file.exists():
|
||||
merged_values.update({k: v for k, v in dotenv_values(local_file).items() if v is not None})
|
||||
|
||||
for key, value in merged_values.items():
|
||||
if key not in preserved_env:
|
||||
os.environ[key] = value
|
||||
return env_name
|
||||
|
||||
|
||||
ACTIVE_ENV_NAME = _load_environment_files()
|
||||
|
||||
|
||||
def _data_path(env_key: str, *parts: str) -> str:
|
||||
from app.path_utils import resolve_backend_relative_path
|
||||
|
||||
default = _BACKEND_DIR.joinpath("data", *parts)
|
||||
return resolve_backend_relative_path(os.getenv(env_key), default)
|
||||
|
||||
|
||||
def _backend_path(env_key: str, *parts: str) -> str:
|
||||
from app.path_utils import resolve_backend_relative_path
|
||||
|
||||
default = _BACKEND_DIR.joinpath(*parts)
|
||||
return resolve_backend_relative_path(os.getenv(env_key), default)
|
||||
|
||||
|
||||
class Config:
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
SECRET_KEY = os.getenv('SECRET_KEY')
|
||||
# 配置最大上传文件大小(200MB)
|
||||
MAX_CONTENT_LENGTH = 200 * 1024 * 1024
|
||||
KB_STORAGE_ROOT = _data_path('KB_STORAGE_ROOT', 'kb')
|
||||
KB_TASK_EXECUTION_MODE = os.getenv('KB_TASK_EXECUTION_MODE', 'worker').strip().lower()
|
||||
KB_WORKER_POLL_SECONDS = float(os.getenv('KB_WORKER_POLL_SECONDS', '2'))
|
||||
KB_WORKER_CONCURRENCY = int(os.getenv('KB_WORKER_CONCURRENCY', '3') or '3')
|
||||
# kb-worker 自动回收长时间 running 的任务(秒),默认 300,应大于单次清洗预期耗时
|
||||
KB_JOB_RUNNING_TIMEOUT_SECONDS = float(os.getenv('KB_JOB_RUNNING_TIMEOUT_SECONDS', '300'))
|
||||
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免卡住整个 worker 队列
|
||||
EDKB_FILE_TIMEOUT_SEC = int(os.getenv('EDKB_FILE_TIMEOUT_SEC', '0') or '0')
|
||||
# 数据库连接池配置
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {
|
||||
'pool_size': 20,
|
||||
'max_overflow': 10,
|
||||
'pool_recycle': 3600,
|
||||
'pool_pre_ping': True,
|
||||
}
|
||||
PUBLIC_BASE_URL = os.getenv('PUBLIC_BASE_URL')
|
||||
DEFAULT_ADMIN_USERNAME = os.getenv('DEFAULT_ADMIN_USERNAME')
|
||||
DEFAULT_ADMIN_PASSWORD = os.getenv('DEFAULT_ADMIN_PASSWORD')
|
||||
TASK_EXECUTION_MODE = os.getenv('TASK_EXECUTION_MODE', '').strip().lower()
|
||||
# Dify 网关配置
|
||||
DIFY_API_BASE = os.getenv('DIFY_API_BASE')
|
||||
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
|
||||
DIFY_CHAT_CONNECT_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_CONNECT_TIMEOUT_SECONDS', '5'))
|
||||
DIFY_CHAT_READ_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_READ_TIMEOUT_SECONDS', '30'))
|
||||
# Redis 连接配置,默认使用本地 Redis + 密码
|
||||
REDIS_URL = os.getenv('REDIS_URL')
|
||||
FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true'
|
||||
HR_WORKFLOW_IFRAME_URL = os.getenv('HR_WORKFLOW_IFRAME_URL')
|
||||
HR_WORKFLOW_API_BASE = os.getenv('HR_WORKFLOW_API_BASE')
|
||||
HR_WORKFLOW_API_KEY = os.getenv('HR_WORKFLOW_API_KEY')
|
||||
OA_WORKFLOW_WSDL_URL = os.getenv(
|
||||
'OA_WORKFLOW_WSDL_URL',
|
||||
'http://oa.well-trust.com:8888/services/WorkflowService?wsdl',
|
||||
)
|
||||
OA_LEAVE_WORKFLOW_CODE = os.getenv('OA_LEAVE_WORKFLOW_CODE', '879')
|
||||
|
||||
# External integration API (resolve original source file links by Dify IDs)
|
||||
INTEGRATION_API_MODE = os.getenv('INTEGRATION_API_MODE', 'local').strip().lower()
|
||||
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
|
||||
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
|
||||
|
||||
# HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 服务端调用;无尾斜杠,常为内网 IP)
|
||||
HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOLS_API_BASE')
|
||||
|
||||
# HXOPS 浏览器可访问根地址(Excel 签名下载等用户可见链接;无尾斜杠,应为域名)
|
||||
HXOPS_PUBLIC_BASE_URL = os.getenv('HXOPS_PUBLIC_BASE_URL')
|
||||
|
||||
# 货代发货通知 Agent Tool API
|
||||
SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY')
|
||||
|
||||
# 文件检核 Chatflow Tool API
|
||||
FILE_CHECK_TOOL_API_KEY = os.getenv('FILE_CHECK_TOOL_API_KEY')
|
||||
|
||||
# 设备维保助手 Chatflow Tool API
|
||||
MAINTENANCE_TOOL_API_KEY = os.getenv('MAINTENANCE_TOOL_API_KEY')
|
||||
SHIPPING_NOTICE_STORAGE_ROOT = _data_path("SHIPPING_NOTICE_STORAGE_ROOT", "shipping_notice")
|
||||
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD = float(
|
||||
os.getenv('SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD') or '0.7'
|
||||
)
|
||||
# 建单后是否延后 parse_notice,交由 Dify 画布 LLM + Tool 解析(默认 true,符合 Dify 优先原则)
|
||||
SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY = os.getenv('SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY = int(
|
||||
os.getenv('SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY') or '3'
|
||||
)
|
||||
SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS') or '180'
|
||||
)
|
||||
SHIPPING_NOTICE_TASK_EXECUTION_MODE = os.getenv('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker').strip().lower()
|
||||
SHIPPING_NOTICE_WORKER_POLL_SECONDS = float(os.getenv('SHIPPING_NOTICE_WORKER_POLL_SECONDS', '2'))
|
||||
SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float(
|
||||
os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '300')
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW = os.getenv('SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW', 'true')
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED', 'false').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '900'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED = (
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = (
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS', '').strip().lower()
|
||||
in {'1', 'true', 'yes', 'on'}
|
||||
if os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS')
|
||||
else _normalize_env_name(os.getenv('ENV_NAME')) in {'test', 'prod'}
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = (
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK', 'false').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID = os.getenv('SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID', '').strip()
|
||||
SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME = (
|
||||
os.getenv('SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME', '.hxops_rpa_shared_mount').strip()
|
||||
or '.hxops_rpa_shared_mount'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS') or '1800'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES = os.getenv(
|
||||
'SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES', ''
|
||||
).strip()
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN = (
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS') or '120'
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM = os.getenv('SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM', 'false').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_MATCH_ENABLED', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN = os.getenv(
|
||||
'SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN',
|
||||
'shipment_{task_no}_{ts}.xlsx',
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED', 'false').lower() == 'true'
|
||||
# Hxops 工作台 / 聊天按钮兜底串联(Dify 主路径走 auto_progress;画布 HTTP 不传 auto_chain_fallback)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK = os.getenv('SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS') or '3')
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS') or '30'
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS = int(
|
||||
os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000'
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG = _backend_path(
|
||||
'SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG', 'config', 'shipping_inventory_sources.yaml'
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS = int(
|
||||
os.getenv('SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS') or '24'
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE = float(
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE') or '0.8'
|
||||
)
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
|
||||
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
|
||||
FREIGHT_INVENTORY_DROP_DIR = _data_path(
|
||||
"FREIGHT_INVENTORY_DROP_DIR", "shipping_notice", "freight_rpa", "inventory_drop"
|
||||
)
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR = _data_path(
|
||||
"FREIGHT_RPA_INVENTORY_TRIGGER_DIR", "shipping_notice", "freight_rpa", "inventory_triggers"
|
||||
)
|
||||
FREIGHT_UPLOAD_QUEUE_DIR = _data_path(
|
||||
"FREIGHT_UPLOAD_QUEUE_DIR", "shipping_notice", "freight_rpa", "upload_queue"
|
||||
)
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR = _data_path(
|
||||
"FREIGHT_RPA_UPLOAD_TRIGGER_DIR", "shipping_notice", "freight_rpa", "upload_triggers"
|
||||
)
|
||||
FREIGHT_RPA_BROWSER_PROFILE_DIR = _data_path(
|
||||
"FREIGHT_RPA_BROWSER_PROFILE_DIR", "shipping_notice", "freight_rpa", "browser_profile"
|
||||
)
|
||||
FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = _data_path(
|
||||
"FREIGHT_RPA_INVENTORY_ARCHIVE_DIR", "shipping_notice", "freight_rpa", "inventory_archives"
|
||||
)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH = _backend_path(
|
||||
"FREIGHT_SHIPMENT_TEMPLATE_PATH", "templates", "freight_shipment_upload.xlsx"
|
||||
)
|
||||
|
||||
# WeCom (企业微信) 登录配置
|
||||
WECOM_ENABLED = os.getenv('WECOM_ENABLED', 'false').lower() == 'true'
|
||||
WECOM_CORP_ID = os.getenv('WECOM_CORP_ID')
|
||||
WECOM_AGENT_ID = os.getenv('WECOM_AGENT_ID')
|
||||
WECOM_SECRET = os.getenv('WECOM_SECRET')
|
||||
WECOM_REDIRECT_URI = os.getenv('WECOM_REDIRECT_URI')
|
||||
WECOM_AUTO_CREATE_USER = os.getenv('WECOM_AUTO_CREATE_USER', 'true').lower() == 'true'
|
||||
WECOM_MATCH_RULES = os.getenv('WECOM_MATCH_RULES')
|
||||
WECOM_MATCH_OPERATOR = os.getenv('WECOM_MATCH_OPERATOR').upper()
|
||||
WECOM_FIRST_LOGIN_BIND_MODE = os.getenv('WECOM_FIRST_LOGIN_BIND_MODE')
|
||||
WECOM_FIRST_LOGIN_INPUT_FIELDS = os.getenv('WECOM_FIRST_LOGIN_INPUT_FIELDS')
|
||||
WECOM_EMPLOYEE_ID_SOURCE = os.getenv('WECOM_EMPLOYEE_ID_SOURCE')
|
||||
WECOM_MOBILE_NORMALIZE = os.getenv('WECOM_MOBILE_NORMALIZE', 'true').lower() == 'true'
|
||||
WECOM_CALLBACK_TOKEN = os.getenv('WECOM_CALLBACK_TOKEN')
|
||||
WECOM_ENCODING_AES_KEY = os.getenv('WECOM_ENCODING_AES_KEY')
|
||||
WECOM_CALLBACK_URL = os.getenv('WECOM_CALLBACK_URL')
|
||||
WECOM_HOMEPAGE_URL = os.getenv('WECOM_HOMEPAGE_URL')
|
||||
WECOM_TRUSTED_DOMAIN = os.getenv('WECOM_TRUSTED_DOMAIN')
|
||||
# Public HTTPS origin for WeCom console URLs (takes priority over notify base + request host).
|
||||
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
|
||||
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset')
|
||||
WECOM_FEEDBACK_NOTIFY_ENABLED = os.getenv('WECOM_FEEDBACK_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_FEEDBACK_NOTIFY_BASE_URL = os.getenv('WECOM_FEEDBACK_NOTIFY_BASE_URL')
|
||||
WECOM_FEEDBACK_BOT_WEBHOOK = os.getenv('WECOM_FEEDBACK_BOT_WEBHOOK')
|
||||
|
||||
# JWT/Casdoor auth configuration (phase-1 compatible rollout)
|
||||
AUTH_LEGACY_HEADER_ENABLED = os.getenv('AUTH_LEGACY_HEADER_ENABLED', 'true').lower() == 'true'
|
||||
AUTH_JWT_REQUIRED = os.getenv('AUTH_JWT_REQUIRED', 'true').lower() == 'true'
|
||||
AUTH_ALLOW_LOCAL_PASSWORD_LOGIN = os.getenv('AUTH_ALLOW_LOCAL_PASSWORD_LOGIN', 'true').lower() == 'true'
|
||||
# Login mode switch: "casdoor" (default) or "password".
|
||||
# casdoor: login form credentials are sent to Casdoor token endpoint (no redirect page for users).
|
||||
# password: keep legacy local username/password login.
|
||||
AUTH_LOGIN_MODE = os.getenv('AUTH_LOGIN_MODE').strip().lower()
|
||||
AUTH_ALLOW_LOCAL_JWT = os.getenv('AUTH_ALLOW_LOCAL_JWT', 'true').lower() == 'true'
|
||||
# JWT 的签发者(iss)校验值,后端用它确认“这个 token 是谁发的”
|
||||
AUTH_JWT_ISSUER = os.getenv('AUTH_JWT_ISSUER')
|
||||
# JWT 的受众(aud)校验值,后端用它确认“这个 token 是发给哪个应用的”
|
||||
AUTH_JWT_AUDIENCE = os.getenv('AUTH_JWT_AUDIENCE')
|
||||
# 公钥集合地址(JWKS),后端从这里拉公钥来验签 JWT
|
||||
AUTH_JWT_JWKS_URL = os.getenv('AUTH_JWT_JWKS_URL')
|
||||
CASDOOR_BASE_URL = os.getenv('CASDOOR_BASE_URL')
|
||||
CASDOOR_CLIENT_ID = os.getenv('CASDOOR_CLIENT_ID')
|
||||
CASDOOR_CLIENT_SECRET = os.getenv('CASDOOR_CLIENT_SECRET')
|
||||
# Fallback when authorize-url request omits redirect_uri; OAuth flow sends browser origin + /casdoor-callback.
|
||||
# Casdoor Application must whitelist every origin users hit, e.g. IP and domain on port 8881.
|
||||
CASDOOR_REDIRECT_URI = os.getenv('CASDOOR_REDIRECT_URI')
|
||||
CASDOOR_SCOPE = os.getenv('CASDOOR_SCOPE')
|
||||
# Casdoor organization (userOwner) for set-password and other management APIs.
|
||||
CASDOOR_ORGANIZATION = (os.getenv('CASDOOR_ORGANIZATION') or 'organization_HX').strip()
|
||||
# WeCom as Casdoor IdP: provider Name from Casdoor Providers page (used with default_provider=wecom on authorize-url).
|
||||
CASDOOR_WECOM_PROVIDER_HINT = os.getenv('CASDOOR_WECOM_PROVIDER_HINT').strip()
|
||||
CASDOOR_WECOM_SILENT_SIGNIN = os.getenv('CASDOOR_WECOM_SILENT_SIGNIN', 'false').lower() == 'true'
|
||||
AUTH_LOCAL_JWT_ISSUER = os.getenv('AUTH_LOCAL_JWT_ISSUER')
|
||||
AUTH_LOCAL_JWT_AUDIENCE = os.getenv('AUTH_LOCAL_JWT_AUDIENCE')
|
||||
AUTH_LOCAL_JWT_EXPIRES_HOURS = int(os.getenv('AUTH_LOCAL_JWT_EXPIRES_HOURS', '12'))
|
||||
SCHEDULE_WORKER_ENABLED = os.getenv('SCHEDULE_WORKER_ENABLED', 'true').lower() == 'true'
|
||||
# Cron 表达式按此时区解读(如 0 12 * * * 表示该时区 12:00);入库 next_run_at 仍为 UTC。
|
||||
SCHEDULE_TIMEZONE = (os.getenv('SCHEDULE_TIMEZONE') or 'Asia/Shanghai').strip()
|
||||
SRM_SQLSERVER_HOST = os.getenv('SRM_SQLSERVER_HOST', '')
|
||||
SRM_SQLSERVER_PORT = os.getenv('SRM_SQLSERVER_PORT', '1433')
|
||||
SRM_SQLSERVER_DATABASE = os.getenv('SRM_SQLSERVER_DATABASE', '')
|
||||
SRM_SQLSERVER_USERNAME = os.getenv('SRM_SQLSERVER_USERNAME', '')
|
||||
SRM_SQLSERVER_PASSWORD = os.getenv('SRM_SQLSERVER_PASSWORD', '')
|
||||
SRM_SQLSERVER_DRIVER = os.getenv('SRM_SQLSERVER_DRIVER', 'SQL Server')
|
||||
SRM_SQLSERVER_ENCRYPT = os.getenv('SRM_SQLSERVER_ENCRYPT', 'no')
|
||||
SRM_SQLSERVER_TRUST_CERT = os.getenv('SRM_SQLSERVER_TRUST_CERT', 'yes')
|
||||
SRM_SQLSERVER_TIMEOUT = int(os.getenv('SRM_SQLSERVER_TIMEOUT', '15'))
|
||||
SMTP_HOST = os.getenv('SMTP_HOST', '')
|
||||
SMTP_PORT = int(os.getenv('SMTP_PORT', '25'))
|
||||
SMTP_USER = os.getenv('SMTP_USER', '')
|
||||
SMTP_PASSWORD = os.getenv('SMTP_PASSWORD', '')
|
||||
SMTP_FROM = os.getenv('SMTP_FROM', '')
|
||||
SMTP_USE_TLS = os.getenv('SMTP_USE_TLS', 'true').lower() == 'true'
|
||||
INTERNAL_API_BASE_URL = os.getenv('INTERNAL_API_BASE_URL', 'http://127.0.0.1:5052')
|
||||
FIXED_ASSETS_SYNC_ENABLED = os.getenv('FIXED_ASSETS_SYNC_ENABLED', 'true').lower() == 'true'
|
||||
FIXED_ASSETS_SYNC_TIMEZONE = (os.getenv('FIXED_ASSETS_SYNC_TIMEZONE') or 'Asia/Shanghai').strip()
|
||||
FIXED_ASSETS_SYNC_HOUR = int(os.getenv('FIXED_ASSETS_SYNC_HOUR', '3') or '3')
|
||||
FIXED_ASSETS_SYNC_MINUTE = int(os.getenv('FIXED_ASSETS_SYNC_MINUTE', '0') or '0')
|
||||
FIXED_ASSETS_SYNC_TIMEOUT_SECONDS = int(os.getenv('FIXED_ASSETS_SYNC_TIMEOUT_SECONDS', '600') or '600')
|
||||
FIXED_ASSETS_SYNC_RETRY_INTERVAL_MINUTES = int(
|
||||
os.getenv('FIXED_ASSETS_SYNC_RETRY_INTERVAL_MINUTES', '30') or '30'
|
||||
)
|
||||
FIXED_ASSETS_SYNC_MAX_ATTEMPTS = int(os.getenv('FIXED_ASSETS_SYNC_MAX_ATTEMPTS', '4') or '4')
|
||||
FIXED_ASSETS_SYNC_POLL_SECONDS = int(os.getenv('FIXED_ASSETS_SYNC_POLL_SECONDS', '60') or '60')
|
||||
FIXED_ASSETS_SYNC_ON_BOOT_IF_MISSING = (
|
||||
os.getenv('FIXED_ASSETS_SYNC_ON_BOOT_IF_MISSING', 'true').lower() == 'true'
|
||||
)
|
||||
FIXED_ASSETS_HISTORY_KEEP_COUNT = int(os.getenv('FIXED_ASSETS_HISTORY_KEEP_COUNT', '3') or '3')
|
||||
FIXED_ASSETS_STORAGE_ROOT = _data_path('FIXED_ASSETS_STORAGE_ROOT', 'fixed_assets')
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT = os.getenv('FIXED_ASSET_HISTORY_SHARE_ROOT', '').strip()
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT = os.getenv('FIXED_ASSET_HISTORY_LOCAL_ROOT', '').strip()
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME = os.getenv('FIXED_ASSET_HISTORY_SHARE_USERNAME', '').strip()
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD = os.getenv('FIXED_ASSET_HISTORY_SHARE_PASSWORD', '')
|
||||
FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS = int(os.getenv('FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS', '20') or '20')
|
||||
FIXED_ASSET_IMAGE_BASE_URL = os.getenv('FIXED_ASSET_IMAGE_BASE_URL', '').strip()
|
||||
FIXED_ASSET_IMAGE_USERNAME = os.getenv('FIXED_ASSET_IMAGE_USERNAME', '').strip()
|
||||
FIXED_ASSET_IMAGE_PASSWORD = os.getenv('FIXED_ASSET_IMAGE_PASSWORD', '')
|
||||
FIXED_ASSET_IMAGE_LIBRARY_ID = os.getenv('FIXED_ASSET_IMAGE_LIBRARY_ID', '').strip()
|
||||
FIXED_ASSET_IMAGE_FOLDER_ID = os.getenv('FIXED_ASSET_IMAGE_FOLDER_ID', '').strip()
|
||||
FIXED_ASSETS_DOCS_EXPORT_ROOT = os.getenv(
|
||||
'FIXED_ASSETS_DOCS_EXPORT_ROOT',
|
||||
str(_ROOT_DIR / 'docs'),
|
||||
)
|
||||
FIXED_ASSETS_EXPORT_TO_DOCS = os.getenv('FIXED_ASSETS_EXPORT_TO_DOCS', 'true').lower() == 'true'
|
||||
FIXED_ASSETS_ERP_USERNAME = os.getenv('FIXED_ASSETS_ERP_USERNAME', 'EXT_VIEW_USER')
|
||||
FIXED_ASSETS_ERP_PASSWORD = os.getenv('FIXED_ASSETS_ERP_PASSWORD', 'extviewuser')
|
||||
FIXED_ASSETS_ERP_DSN = os.getenv('FIXED_ASSETS_ERP_DSN') or os.getenv('ERP_DB_DSN', '192.168.8.24:1521/topprod')
|
||||
|
||||
# MinIO 配置
|
||||
MINIO_ENDPOINT = os.getenv('MINIO_ENDPOINT', '127.0.0.1:9000')
|
||||
MINIO_ACCESS_KEY = os.getenv('MINIO_ACCESS_KEY', 'minioadmin')
|
||||
MINIO_SECRET_KEY = os.getenv('MINIO_SECRET_KEY', 'minioadmin')
|
||||
MINIO_SECURE = os.getenv('MINIO_SECURE', 'false').lower() == 'true'
|
||||
MINIO_AGENT_GUIDES_BUCKET = os.getenv('MINIO_AGENT_GUIDES_BUCKET', 'agent-guides')
|
||||
MINIO_PUBLIC_BASE_URL = os.getenv('MINIO_PUBLIC_BASE_URL', 'http://127.0.0.1:9000')
|
||||
MINIO_FILE_ASSETS_BUCKET = os.getenv('MINIO_FILE_ASSETS_BUCKET', 'hxops-file-assets')
|
||||
FILE_ASSET_MAX_SIZE_MB = int(os.getenv('FILE_ASSET_MAX_SIZE_MB', '30'))
|
||||
FILE_ASSET_TEMP_TTL_HOURS = int(os.getenv('FILE_ASSET_TEMP_TTL_HOURS', '72'))
|
||||
FILE_ASSET_DOWNLOAD_URL_TTL_SECONDS = int(os.getenv('FILE_ASSET_DOWNLOAD_URL_TTL_SECONDS', '300'))
|
||||
SHIPPING_NOTICE_INTAKE_TTL_HOURS = int(os.getenv('SHIPPING_NOTICE_INTAKE_TTL_HOURS', '72'))
|
||||
SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS', '3'))
|
||||
SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', '300')
|
||||
)
|
||||
SHIPPING_NOTICE_PARSER_VERSION = os.getenv('SHIPPING_NOTICE_PARSER_VERSION', 'v6')
|
||||
# EML 附件提取安全上限(阶段一对齐:只抽取文本,不执行宏/脚本)
|
||||
# parser v6:阶段二附件派生 FileAsset + Document/Candidate;相对 v5 须强制重解析
|
||||
# parser v5:mixed 保留独立 HTML 段 + 附件型 alternative 可提取正文
|
||||
SHIPPING_NOTICE_EML_MAX_ATTACHMENTS = int(os.getenv('SHIPPING_NOTICE_EML_MAX_ATTACHMENTS', '20'))
|
||||
SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES = int(
|
||||
os.getenv('SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES', str(20 * 1024 * 1024))
|
||||
)
|
||||
SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES = int(
|
||||
os.getenv('SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES', str(50 * 1024 * 1024))
|
||||
)
|
||||
SHIPPING_NOTICE_EML_MAX_NESTING_DEPTH = int(os.getenv('SHIPPING_NOTICE_EML_MAX_NESTING_DEPTH', '3'))
|
||||
# EML 全部附件 extracted_text 写入 structured_result_json 的合计字符上限
|
||||
SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS = int(
|
||||
os.getenv('SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS', str(500_000))
|
||||
)
|
||||
|
||||
|
||||
class DevelopmentConfig(Config):
|
||||
DEBUG = True
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
|
||||
|
||||
|
||||
class ProductionConfig(Config):
|
||||
DEBUG = False
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
|
||||
|
||||
|
||||
class TestingConfig(Config):
|
||||
TESTING = True
|
||||
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
|
||||
WTF_CSRF_ENABLED = False
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {}
|
||||
SCHEDULE_WORKER_ENABLED = False
|
||||
FIXED_ASSETS_SYNC_ENABLED = False
|
||||
FIXED_ASSETS_EXPORT_TO_DOCS = False
|
||||
ENV_NAME = 'dev'
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
|
||||
|
||||
|
||||
config = {
|
||||
'dev': DevelopmentConfig,
|
||||
'development': DevelopmentConfig,
|
||||
'test': TestingConfig,
|
||||
'testing': TestingConfig, # alias for create_app('testing') in pytest
|
||||
'prod': ProductionConfig,
|
||||
'production': ProductionConfig,
|
||||
'default': DevelopmentConfig,
|
||||
}
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
"""
|
||||
backend/app/core/db/__init__.py
|
||||
|
||||
用途:数据库会话工具包入口。
|
||||
逻辑:Wave 1 提供 run_with_retry;sequence 工具供迁移/运维脚本使用。
|
||||
"""
|
||||
Loaded 100 of 1403 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user