Compare commits

..
107 Commits
Author SHA1 Message Date
sophie 639df1b8c5 Merge branch 'test' into prod 2026-06-24 17:37:23 +08:00
sophie 1bd9f278fe fix(chat): 修改回复不流式输出,回退useChat.ts 2026-06-24 17:24:24 +08:00
sophie 1cdc365955 Merge branch 'test' into prod 2026-06-24 16:27:07 +08:00
sophie b89d93d738 Merge branch 'feedback-nofity' into dev 2026-06-24 14:33:54 +08:00
sophie 6adea87a5f feat(feedback-notify): 用户提交意见反馈,发送通知到企业微信群 2026-06-24 14:22:27 +08:00
sophie 4474ef7e3f fix(chat): 优化chat页面项部样式 2026-06-24 11:23:04 +08:00
sophie 0d3a812e16 fix(admin): 优化admin管理台细节问题 2026-06-23 19:17:34 +08:00
sophie acbf7d5921 Merge branch 'test' into prod 2026-06-23 15:21:34 +08:00
sophie a89491f4b1 fix(chat): 源文件解析不再阻塞SSE流式结束事件 2026-06-23 15:08:48 +08:00
sophie 8efc526ca8 Merge branch 'test' into prod 2026-06-23 14:20:42 +08:00
runny f9b04eddc8 feat(asset-query): 优化固资快照与请假分流能力 2026-06-23 13:47:40 +08:00
runny 873331dd20 perf(人事规章): 优化查询他人假期提示 2026-06-23 13:47:40 +08:00
sophie 2aa8609c17 build(migration): push之前校验migration multiple head 2026-06-23 13:37:30 +08:00
sophie 1bc938155a fix(chat): 修复源文件显示了兜底文件名uploaded_file 2026-06-23 11:58:57 +08:00
hugo 0c5ee4aec1 feat(shipping): 货代发货说明文件调整 2026-06-23 11:24:53 +08:00
hugo d5928b42f3 Merge branch 'dev' into hugo 2026-06-23 11:22:39 +08:00
hugo 08360a4142 feat(shipping): 新增货代发货批量自动处理与任务重试功能
本次提交完整实现货代发货通知的自动化批量处理能力:
1.  新增发货单票后台任务类型与专用worker队列,实现任务持久化调度
2.  实现发货批次后台编排器,支持上传后自动逐票推进解析、匹配、导出全流程
3.  新增单票重试、批次待处理重试的API与前端操作界面
4.  补充全量多语言翻译,新增重试、任务列表、状态展示相关文案
5.  优化上传交互逻辑,改为后台自动处理任务,无需手动触发解析指令
6.  修复文件检核工具无数据预检逻辑,避免创建空检核批次
7.  调整发货工作流细节,优化Excel生成幂等性与任务状态同步
8.  更新环境配置与API文档,修正货代工具接口地址端口
2026-06-23 11:22:09 +08:00
sophie 0a7e68a58a fix(chat): 修复生产环境不带源文件 2026-06-23 11:04:33 +08:00
sophie 8246c09ab0 Merge branch 'test' into prod 2026-06-23 08:54:21 +08:00
runny ddb704f574 perf(固资管理): 对接dify平台进行查询固资 2026-06-23 00:34:54 +08:00
sophie 7300098ff9 fix(admin): 修改一些样式和布局 2026-06-22 19:31:14 +08:00
sophie 82ad4323f8 feat(admin): 排程管理触发热点问题离线聚合 2026-06-22 18:53:53 +08:00
hugo 70e8f700ff feat(shipping-notice): 支持发货通知解析延后至 Dify 画布,优化任务创建流程 2026-06-22 16:59:38 +08:00
sophie cdd227d550 fix(admin): 更新管理控制台应用管理布局,抽离出新建编辑弹框子组件 2026-06-22 16:24:52 +08:00
runny 0f499b47f7 perf(固资管理): 1.获取erp全量资产信息;2.本地化固资进行快照;3.优先查询本地固资信息可降级走erp直查 2026-06-22 15:38:19 +08:00
sophie 0d59b23e0c feat(faq): 知识库相对应文档更新,标记关联的问题为待复审状态并暂停缓存命中 2026-06-22 14:50:46 +08:00
sophie 757231e3d5 fix(admin): 优化聊天日志报表 2026-06-22 12:05:42 +08:00
sophie c38a56536e docs(agents.md): 补充前端架构约束与错误处理规范 2026-06-22 10:30:18 +08:00
sophie 10b6f9b692 fix(chat): 将流式错误信息映射为面向用户的提示方案 2026-06-19 21:25:14 +08:00
sophie 6757ad869f fix(admin): 用户字段唯一性校验 2026-06-18 10:18:18 +08:00
sophie d46d61bfa1 fix(migration): 解决migration多head问题 2026-06-18 08:49:45 +08:00
hugo f224217fb0 fix(file-check): 修正文件检核工具 API Key 名称及相关文档说明 2026-06-17 22:30:42 +08:00
hugo 97a5a1f106 Merge branch 'dev' into hugo 2026-06-17 22:29:48 +08:00
hugo 55cf7ff734 feat(file-check): 更新文件检核工具 API Key 配置及相关文档 2026-06-17 22:29:15 +08:00
hugo 634dee4b81 feat(shipping-notice): 新增发货批次和任务管理功能,支持批次创建与任务处理 2026-06-17 20:45:19 +08:00
sophie 93f4ea5537 fix(chat): 修复dify有token,chat_logs表却记录tokens_used为0 2026-06-17 18:02:13 +08:00
sophie 66410c9a27 Merge branch 'faq-cache' into dev 2026-06-17 16:54:26 +08:00
sophie cf7cc11ffc feat(faq): 缓存高频问题及答案,命中直接返回预置答案,不走dify 2026-06-17 16:46:17 +08:00
sophie 98481c7ea7 fix(admin): 修改用户时,只有修改了密码才同步给casdoor 2026-06-17 16:07:12 +08:00
hugo 457f0f4e5e Merge branch 'dev' into hugo 2026-06-17 11:28:09 +08:00
hugo a523ec0454 feat(file-check): 更新文件检核文档,整合 Chatflow 编排与 API 说明 2026-06-17 11:27:43 +08:00
sophie 21b8c24815 refactor(backend): 后端重构初步设想 2026-06-17 11:24:54 +08:00
sophie b69d549b2c fix(admin): 修复删除用户时没有级联删除 2026-06-17 10:29:10 +08:00
sophie 6f9c25bb34 fix(admin): 用户管理页面优化,增加服务器端分页,避免拉全量用户数据,同时修复一些bug 2026-06-17 09:47:14 +08:00
runny 950d661b4f perf(固资管理): 增加供应商模糊查询 2026-06-16 19:05:54 +08:00
hugo 3264ed1e07 Merge branch 'dev' into hugo 2026-06-16 17:34:45 +08:00
hugo 9b36ced288 feat(file-check): 增加文件检核进度展示功能及相关配置 2026-06-16 17:34:25 +08:00
runny b079524b4f perf(固资管理): 优化固资管理模糊查询提升用户体验 2026-06-16 15:58:21 +08:00
hugo d3cfd24d6f Merge branch 'dev' into hugo 2026-06-16 14:57:59 +08:00
hugo 0ac165049d feat(schedule): 优化排程管理界面,新增弹窗控制与交互逻辑 2026-06-16 14:57:13 +08:00
sophie 1eb6bf4aad fix(addmin): 添加修改用户时同步到casdoor 2026-06-16 14:01:01 +08:00
hugo 7544361c05 Merge branch 'dev' into hugo 2026-06-16 13:32:30 +08:00
hugo f6fe56f205 feat(file-check): 新增历史检核报告检索功能及相关 API 2026-06-16 13:32:00 +08:00
sophie 638fdcb7fd fix(admin): 企业微信管理界面增加从OA一键同步企业微信ID功能 2026-06-16 12:00:31 +08:00
hugo 29a7704d46 Merge branch 'dev' into hugo 2026-06-16 09:45:31 +08:00
hugo 24310b63b3 feat(file-check): 新增文件检核相关 API 和工具,替换 RoHS 检核功能 2026-06-16 09:28:37 +08:00
sophie 6baeffba64 feat(auth): 支持企业微信重置密码 2026-06-15 17:13:48 +08:00
hugo fa0cdee8df feat(rohs-check): 新增 RoHS 对话轮次注册与检核批次绑定功能 2026-06-15 16:30:17 +08:00
hugo 9cba517bff Merge branch 'dev' into hugo 2026-06-15 13:48:00 +08:00
hugo f5aac9c893 feat(schedule):cron支持图形,RoHS检核增加进度显示 2026-06-15 13:42:15 +08:00
hugo 6d0e78be81 Merge branch 'dev' into hugo 2026-06-12 15:13:11 +08:00
hugo ae6a5e7c55 Merge branch 'dev' into hugo 2026-06-12 11:50:43 +08:00
hugo 9d7dad6a4b feat(chat): 新增对话流性能监控功能及相关日志输出 2026-06-12 11:43:19 +08:00
hugo e827c5dc38 fix(conflicts): 解决冲突及功能迁移 2026-06-11 18:33:16 +08:00
hugo 599d492895 feat(rohs-check): 新增 RoHS 检核执行进度中增加 Excel 下载功能及相关配置 2026-06-11 17:35:16 +08:00
sophie e5b65d9ed4 Merge branch 'test' into prod 2026-06-09 11:33:13 +08:00
sophie 90700f1d59 Merge branch 'test' into prod 2026-06-08 16:04:33 +08:00
sophie dd6e7b8cb0 Merge branch 'test' into prod 2026-06-08 09:11:02 +08:00
sophie 7eaff3c8bf Merge branch 'test' into prod 2026-06-06 19:41:12 +08:00
sophie faedb625c7 Merge branch 'test' into prod 2026-06-05 15:14:06 +08:00
sophie b0ff3efba9 Merge branch 'test' into prod 2026-06-04 19:04:15 +08:00
sophie b3c6ebad2e Merge branch 'test' into prod 2026-06-02 18:07:50 +08:00
sophie c61f74866c Merge branch 'test' into prod 2026-06-02 13:21:12 +08:00
sophie e559473fff Merge branch 'test' into prod 2026-05-30 10:13:28 +08:00
super 2b40d7f507 MINIO_ENDPOINT 为100.230 by super 2026-05-29 23:50:13 +08:00
super fbf5537dcd Merge branch 'dev' into prod by super 2026-05-29 14:50:43 +08:00
sophie def791ff59 Merge branch 'test' into prod 2026-05-28 11:22:40 +08:00
sophie d3fa1cc243 Merge branch 'test' into prod 2026-05-27 16:46:36 +08:00
sophie 2b773eaac6 Merge branch 'test' into prod 2026-05-21 20:31:50 +08:00
sophie 23e058e662 Merge branch 'test' into prod 2026-05-21 19:17:21 +08:00
sophie 718c5a18d2 Merge branch 'test' into prod 2026-05-21 10:24:20 +08:00
sophie 092192b824 Merge branch 'test' into prod 2026-05-19 19:29:39 +08:00
sophie ea56e8bf65 Merge branch 'test' into prod 2026-05-19 17:41:55 +08:00
sophie fd049f98db Merge branch 'test' into prod
# Conflicts:
#	backend/Dockerfile
2026-05-18 14:20:23 +08:00
sophie cbc9f070ec 修改超时时间 2026-05-16 15:39:38 +08:00
sophie 729ec2908d Merge branch 'test' into prod
# Conflicts:
#	backend/.env
2026-05-16 14:56:51 +08:00
sophie 4e56387f31 临时改为密码登录 2026-05-14 15:32:21 +08:00
sophie 037fb499e5 Merge branch 'test' into prod 2026-05-14 12:02:24 +08:00
sophie ebf115e1c3 Merge branch 'test' into prod 2026-05-13 18:28:41 +08:00
sophie 3144489f34 Merge branch 'test' into prod 2026-05-13 08:49:48 +08:00
sophie 6003a98754 Merge branch 'test' into prod 2026-05-13 08:11:49 +08:00
sophie 47c926bd4a 修改注释乱码问题 2026-05-12 18:52:20 +08:00
sophie 8a4f6990e7 Merge branch 'test' into prod
# Conflicts:
#	docker-compose.yml
2026-05-12 18:49:27 +08:00
sophie c32d5e1c2f 部署层保证Oracle路径 2026-05-12 18:36:12 +08:00
sophie d00d549bd9 Merge branch 'test' into prod 2026-05-12 18:32:47 +08:00
sophie 7ecc88e234 Merge branch 'test' into prod 2026-05-12 15:53:39 +08:00
sophie f6cda775be Merge branch 'test' into prod 2026-05-12 15:32:08 +08:00
hugo a9276cc89c Merge branch 'test' into prod 2026-05-11 19:57:56 +08:00
sophie e76cb197d0 Merge branch 'test' into prod 2026-05-09 17:30:04 +08:00
sophie b30c867087 Merge branch 'test' into prod 2026-05-09 08:34:19 +08:00
sophie c91d4ff3c7 Merge branch 'test' into prod 2026-05-08 19:12:56 +08:00
sophie eaf518a01d Merge branch 'test' into prod 2026-05-08 14:42:55 +08:00
sophie b5c8a72728 Merge branch 'test' into prod 2026-05-08 13:18:34 +08:00
sophie 6543d3ad7d Merge branch 'test' into prod 2026-05-06 10:44:02 +08:00
sophie 6e5ef8f6c0 Merge branch 'test' into prod 2026-05-05 16:40:40 +08:00
sophie 23f9533124 !6 !5 修改build报错
Merge pull request !6 from sophie/test
2026-04-28 10:54:58 +00:00
sophie a4a083658e !4 !3 Merge branch 'sophie' into dev
Merge pull request !4 from sophie/test
2026-04-28 10:31:13 +00:00
399 changed files with 43048 additions and 10721 deletions

No files matched your search

+1 -1
View File
@@ -59,4 +59,4 @@ MINIO_SECURE=false
MINIO_PUBLIC_BASE_URL=http://ai.well-trust.com:9000
# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
HXOPS_TOOLS_API_BASE=http://192.168.100.230:8891
HXOPS_TOOLS_API_BASE=http://192.168.100.230:8890
+22
View File
@@ -11,6 +11,8 @@ FLASK_APP=run.py
INTEGRATION_API_BASE=http://192.168.100.230:8891
# 连接文档清洗系统的API KEY
INTEGRATION_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
# 文件检核 Tool API Key;未单独配置时建议与 INTEGRATION_API_KEY 保持一致
FILE_CHECK_TOOL_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
SECRET_KEY=hxops-dify
@@ -69,6 +71,10 @@ 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
@@ -122,3 +128,19 @@ SRM_SQLSERVER_TIMEOUT=10
# ERP
ERP_DB_DSN=192.168.8.24:1521/topprod
TEXT2SQL_SCHEMA_PATH=
# 热点 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 # 选代表答案时「差评」反馈分阈值(≤此分排除)
+16 -2
View File
@@ -5,11 +5,12 @@ ROOT_DIR="$(git rev-parse --show-toplevel)"
# shellcheck source=_common.sh
source "${ROOT_DIR}/.githooks/_common.sh"
if hook_should_skip; then
if [[ "${SKIP_GIT_HOOKS:-}" == "1" ]]; then
exit 0
fi
zero="0000000000000000000000000000000000000000"
need_migration_check=0
need_frontend_build=0
while read -r local_ref local_sha remote_ref remote_sha; do
@@ -33,12 +34,25 @@ while read -r local_ref local_sha remote_ref remote_sha; do
changed_files="$(git diff --name-only --diff-filter=ACMR "${remote_sha}" "${local_sha}" || true)"
fi
if echo "${changed_files}" | grep -qE '^backend/migrations/versions/.*\.py$'; then
need_migration_check=1
fi
if frontend_paths_in "${changed_files}"; then
need_frontend_build=1
break
fi
done
if [[ "${need_migration_check}" -eq 1 ]]; then
if ! run_migration_heads_check "${ROOT_DIR}"; then
exit 1
fi
fi
if [[ "${SKIP_FRONTEND_HOOKS:-}" == "1" ]]; then
exit 0
fi
if [[ "${need_frontend_build}" -eq 0 ]]; then
exit 0
fi
+2 -1
View File
@@ -77,4 +77,5 @@ oracle_client/
# local env override
.env.local
backend/data/kb/
.pytest_cache/
.pytest_cache/
backend/data/fixed_assets/manifest.json
+16 -2
View File
@@ -1,17 +1,31 @@
{
// 后端 Python 虚拟环境:新终端自动激活,无需手动 .venv\Scripts\activate
// 后端 Python 虚拟环境
"python.defaultInterpreterPath": "${workspaceFolder}/backend/.venv/Scripts/python.exe",
"python.terminal.activateEnvironment": true,
"python.venvPath": "${workspaceFolder}/backend",
"python.venvFolders": [".venv"],
// 可选:在终端下拉中选择「HXOPS Backend」时,直接进入 backend 并激活 venv
// 默认终端:加载 cd 钩子,进入 backend 时自动激活 .venv
"terminal.integrated.defaultProfile.windows": "PowerShell (HXOPS)",
"terminal.integrated.profiles.windows": {
"PowerShell (HXOPS)": {
"source": "PowerShell",
"icon": "terminal-powershell",
"args": [
"-NoExit",
"-ExecutionPolicy",
"Bypass",
"-File",
"${workspaceFolder}/scripts/powershell-backend-auto-venv.ps1"
]
},
"HXOPS Backend": {
"source": "PowerShell",
"icon": "server-environment",
"args": [
"-NoExit",
"-ExecutionPolicy",
"Bypass",
"-Command",
"Set-Location '${workspaceFolder}/backend'; if (Test-Path '.venv/Scripts/Activate.ps1') { . '.venv/Scripts/Activate.ps1' }"
]
+17 -4
View File
@@ -43,14 +43,23 @@ backend/app/
response_utils.py / errors.py / decorators.py # 统一返回、异常、权限装饰器
backend/migrations/ # Alembic 迁移文件
frontend/src/
features/ # 按业务域组织(admin / auth / chat)
composables/# Hooks(如 useChat.ts)
views/ components/ i18n.ts
main.ts · App.vue · i18n.ts · config.ts # Vite 入口(保留 src 根)
app/ # 应用基础设施:router/(routes/* · guards)、plugins/pinia
shared/ # 跨域共享(无业务语义)
# api/client · composables · components · layouts · utils · styles
features/ # 业务域垂直切分(新代码主要落在这里)
# auth · workspace · chat · admin · kb
# 域内:api/ · composables/ · views/ · stores/ · components/
# admin 子模块:modules/<name>/*Page.vue + use*Admin.ts
locales/ # i18n 四语言 JSON(zh-CN / zh-TW / en / th),按域拆分
scripts/ # 部署与运维脚本(deploy_compose.sh、healthcheck.sh ...)
docs/ # 权威文档(规范、上下文、流程、发布说明)
```
**约定**:新逻辑优先放入对应 `services/`(后端)或 `features/composables/`(前端),复用既有 `response_utils` / `errors` / `decorators` 模式,不要另造轮子。
**约定**:
- **后端**:新逻辑优先放入 `services/`,复用 `response_utils` / `errors` / `decorators` 模式,不要另造轮子。
- **前端**:Feature-Module + Composables + Pinia;新功能放入 `features/<domain>/`(`api/` · `composables/` · `views/` 等),跨域通用代码放 `shared/`;HTTP 统一 `@/shared/api/client`。**禁止**在已废弃的 `src/api/`、`src/views/`、`src/composables/` 等路径新增代码。完整规范见 **[docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md)**。
---
@@ -143,6 +152,7 @@ docker compose logs -f hxops-backend
- 🔌 **外部集成依赖**:Oracle Instant Client 19.30 / `pyodbc` / `zeep`(OA、PLM、HR)等本地未必可运行,涉及这些 service 时谨慎并说明。
- ➕ **新增依赖需克制**:不擅自引入未经评审的第三方依赖;如需新增,在提交说明中给出理由。
- 📝 **注释两层标准(强制)**:新建或调整代码须满足 §5 文件层 + 函数层注释;AI 生成/重构代码同样适用,不得省略。
- ⚠️ **错误处理统一契约**:JSON API 使用 `{ success, data | error, request_id }` envelope;后端业务失败 **`raise AppError` 子类**(`app/errors.py`),禁止新写 `jsonify({"error": ...})`;前端 HTTP 统一 **`requestJson`**(`@/shared/api/client`),失败为 **`BusinessError`**,在 composable/view 用 **`useMessage()`** 展示;新增 `error.code` 须同步四语言 **`locales/*/errors.json`**。详见 **[docs/convention/error_handling.md](docs/convention/error_handling.md)**。
- ⚠️ 改动**数据库结构、部署脚本(`scripts/`、`Jenkinsfile`、`docker-compose.yml`)或敏感配置**前,先说明影响面再动手。
合并前最低自检(详见 [新人文档 §3.3](docs/新人环境搭建与配置文档.md)):前后端可启动、`frontend/` 改动后 `npm run build` 通过、关键页面与登录可用。
@@ -181,4 +191,7 @@ docker compose logs -f hxops-backend
| 环境变量 | [docs/convention/env_loading_priority.md](docs/convention/env_loading_priority.md) · [docs/convention/环境变量规则.md](docs/convention/环境变量规则.md) |
| 知识库部署 | [docs/knowledge_base_runtime_deploy.md](docs/knowledge_base_runtime_deploy.md) |
| Excel/CSV 切块与 Dify 分段 | [docs/kb-excel-dify-chunking.md](docs/kb-excel-dify-chunking.md) |
| FAQ 缓存 / 热点发现运维 | [docs/faq_cache_ops_manual.md](docs/faq_cache_ops_manual.md) |
| 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.md) |
| 前端架构规范 | [docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md) |
| 错误处理规范 | [docs/convention/error_handling.md](docs/convention/error_handling.md) |
Vendored
+4 -3
View File
@@ -147,7 +147,8 @@ def notifyPushPlusDeploy(Map opts) {
// 企业微信 + PushPlus 微信双通道
def notifyDeployAll(Map opts) {
notifyWecomDeploy(opts)
notifyPushPlusDeploy(opts)
// 暂时只发企业微信通知
// notifyPushPlusDeploy(opts)
}
pipeline {
@@ -167,11 +168,11 @@ pipeline {
defaultValue: false,
description: '仅当本地 diff 判定无前后端/部署配置变更时生效:额外 SSH 到本分支对应目标机执行 git rev-parse / branch --show-current,与本次 GIT_COMMIT、BRANCH_NAME 比对,不一致则视为需要部署。'
)
// 生产镜像回滚:填写历史 tag 后缀(如 prod-a1b2c3d4),走 deploy_compose.sh 预构建模式
// 生产镜像回滚:填写 Git 7 位短 hash 后缀(如 prod-e5b65d9),走 deploy_compose.sh 预构建模式
string(
name: 'ROLLBACK_IMAGE_TAG',
defaultValue: '',
description: '【仅生产】非空时回滚到该镜像 tag(hxops-frontend:<tag> / hxops-backend:<tag>)。示例:prod-a1b2c3d4。不拉最新代码、不执行 db upgrade。留空为正常部署。'
description: '【仅生产】非空时回滚到该镜像 tag(hxops-frontend:<tag> / hxops-backend:<tag>)。示例:prod-e5b65d9(Git 短 hash 7 位)。不拉最新代码、不执行 db upgrade。留空为正常部署。'
)
}
+2
View File
@@ -5,6 +5,8 @@ FROM ${PYTHON_BASE_IMAGE}
ARG APT_MIRROR=https://mirrors.aliyun.com
ARG PIP_INDEX_URL=https://mirrors.aliyun.com/pypi/simple
ARG PIP_EXTRA_INDEX_URL
ARG PIP_TIMEOUT=300
ARG PIP_RETRIES=15
WORKDIR /app
+8 -4
View File
@@ -56,10 +56,10 @@ def create_app(config_name='default'):
from app.api.schedule_admin import schedule_admin_bp
from app.api.workspace_schedule import workspace_schedule_bp
from app.api.workspace_shipping_notice import workspace_shipping_notice_bp
from app.api.workspace_rohs_check import workspace_rohs_check_bp
from app.api.workspace_file_check import workspace_file_check_bp
from app.api.internal_jobs import internal_jobs_bp
from app.api.shipping_notice_tools import shipping_notice_bp
from app.api.rohs_check_tools import rohs_check_bp
from app.api.file_check_tools import file_check_bp
from app.api.speech import speech_bp
# 聊天相关接口
@@ -77,10 +77,10 @@ def create_app(config_name='default'):
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace')
app.register_blueprint(workspace_rohs_check_bp, url_prefix='/api/workspace')
app.register_blueprint(workspace_file_check_bp, url_prefix='/api/workspace')
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
app.register_blueprint(rohs_check_bp, url_prefix='/api/rohs-check')
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
app.register_blueprint(speech_bp, url_prefix='/api/speech')
# Eagerly load persisted runtime settings so the very first request after
@@ -91,6 +91,10 @@ def create_app(config_name='default'):
_apply_persisted_settings(app)
from app.services.schedule.scheduler_service import start_scheduler
start_scheduler(app)
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
FixedAssetsSnapshotService.start_worker(app)
from app.cli.faq_commands import init_app as init_faq_cli
init_faq_cli(app)
@app.before_request
def _sync_persisted_settings():
+52
View File
@@ -0,0 +1,52 @@
"""
backend/app/api/__init__.py
用途:集中注册所有 Blueprint(Wave 1 接入 create_app)。
依赖:各 api 子包 blueprint。
逻辑:替代 app/__init__.py 内 15 行散乱 register_blueprint。
"""
from __future__ import annotations
from flask import Flask
def register_blueprints(app: Flask) -> None:
"""
注册全部 HTTP Blueprint,保持对外 url_prefix 不变。
核心逻辑:Wave 0 仍从既有单体模块 import;Wave 1+ 逐步切换至分包。
Args:
app: Flask 应用实例。
"""
# [STEP 1] 单体模块(Wave 3 前保持不变)
from app.api.chat import chat_bp
from app.api.admin import admin_bp
from app.api.agents import agents_bp
from app.api.user import user_bp
from app.api.knowledge_base import knowledge_base_bp
from app.api.integration import integration_bp
from app.api.internal_jobs import internal_jobs_bp
from app.api.speech import speech_bp
# [STEP 2] 已分包骨架(re-export 旧模块,Wave 1 可切换 import 来源)
from app.api.schedule import schedule_admin_bp
from app.api.workspace import (
workspace_file_check_bp,
workspace_schedule_bp,
workspace_shipping_notice_bp,
)
from app.api.tools import file_check_bp, shipping_notice_bp
app.register_blueprint(chat_bp, url_prefix='/api/chat')
app.register_blueprint(admin_bp, url_prefix='/api/admin')
app.register_blueprint(agents_bp, url_prefix='/api/agents')
app.register_blueprint(user_bp, url_prefix='/api/user')
app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb')
app.register_blueprint(integration_bp, url_prefix='/api/integration')
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace')
app.register_blueprint(workspace_file_check_bp, url_prefix='/api/workspace')
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
app.register_blueprint(speech_bp, url_prefix='/api/speech')
+616 -69
View File
@@ -1,11 +1,12 @@
"""
backend/app/api/admin.py
文件用途:管理员相关 API 路由
引用文件:flask, models, decorators
逻辑关系:提供 Agent 配置管理、用户与权限管理接口,供前端 Admin 控制台使用
用途:管理员相关 API 路由(Agent、用户、权限、企业微信等)。
依赖:flask、models、decorators、app.api.user(Casdoor 用户同步)。
逻辑:供前端 Admin 控制台调用;创建/编辑用户时委托 user._sync_casdoor_* 与 IdP 保持同步。
"""
from flask import Blueprint, request, jsonify, current_app
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, GeneralFeedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit, WecomNotifyAudit, AgentGuide
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, GeneralFeedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit, WecomNotifyAudit, AgentGuide, KbDocument
from app.services.minio_service import minio_service
from app.decorators import require_admin
from app.config import Config
@@ -13,15 +14,18 @@ from app import db
from app.env_persistence import persist_env_settings
from sqlalchemy import func, desc, inspect, or_
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import joinedload
from datetime import datetime, timedelta
import csv
import io
import math
import re
import requests
import uuid
from app.services.wecom_notify import send_wecom_event_message
from app.services.wecom_directory_sync import sync_wecom_userids_from_directory
from app.services.oa_wecom_sync import sync_wecom_userids_from_oa
from app.services.dify import DifyService
from app.services.user_admin import delete_admin_users
from app.auth_jwt import get_current_user as _get_auth_user
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
admin_bp = Blueprint('admin', __name__)
@@ -38,6 +42,29 @@ def _raise_user_integrity_conflict(exc: IntegrityError) -> None:
raise ConflictError('Username already exists', code='USER.USERNAME_EXISTS')
raise ConflictError('Data uniqueness conflict', code='USER.UNIQUENESS_CONFLICT')
def _assert_user_unique_fields(exclude_user_id: int | None, **fields: str | None) -> None:
"""
校验用户唯一字段(邮箱、工号、手机号)不与其它账号冲突。
核心逻辑:对传入的非 None 字段查询 User 表;编辑时 exclude_user_id 排除当前用户。
@param exclude_user_id: 编辑场景传当前用户 id;创建场景传 None
@param fields: email / employee_id / phone_number 等待校验值
@raises ConflictError: 唯一字段已被占用
"""
checks = (
('email', 'USER.EMAIL_EXISTS', 'Email already exists'),
('employee_id', 'USER.EMPLOYEE_ID_EXISTS', 'Employee ID already exists'),
('phone_number', 'USER.PHONE_EXISTS', 'Phone number already exists'),
)
for field, code, message in checks:
value = fields.get(field)
if value is None:
continue
query = db.session.query(User.id).filter(getattr(User, field) == value)
if exclude_user_id is not None:
query = query.filter(User.id != exclude_user_id)
if query.first():
raise ConflictError(message, code=code, details={'field': field})
def _empty_to_none(value):
if value is None:
return None
@@ -451,18 +478,99 @@ def update_agent_permissions(id):
db.session.commit()
return jsonify({'status': 'ok'})
def _serialize_admin_user(user: User) -> dict:
"""将 User ORM 转为管理端列表/详情 JSON 结构。"""
return {
'id': user.id,
'username': user.username,
'email': user.email,
'department': user.department,
'role': user.role,
'status': user.status,
'real_name': user.real_name,
'employee_id': user.employee_id,
'phone_number': user.phone_number,
'agent_ids': [agent.id for agent in user.agents],
}
def _apply_admin_users_filters(query):
"""
按 Query 参数过滤用户列表(模糊匹配文本字段)。
支持:username, email, department, role, status, real_name, employee_id, phone_number, hide_rejected。
"""
if request.args.get('hide_rejected', 'false').lower() == 'true':
query = query.filter(User.status != 'rejected')
filter_columns = {
'username': User.username,
'email': User.email,
'department': User.department,
'role': User.role,
'status': User.status,
'real_name': User.real_name,
'employee_id': User.employee_id,
'phone_number': User.phone_number,
}
for key, column in filter_columns.items():
value = (request.args.get(key) or '').strip()
if value:
query = query.filter(column.cast(db.String).ilike(f'%{value}%'))
return query
@admin_bp.route('/users', methods=['GET'])
@require_admin
def list_users():
users = db.session.query(User).order_by(User.id.asc()).all()
res = []
for u in users:
res.append({'id': u.id, 'username': u.username, 'email': u.email, 'department': u.department, 'role': u.role, 'status': u.status, 'real_name': u.real_name, 'employee_id': u.employee_id, 'phone_number': u.phone_number, 'agent_ids': [a.id for a in u.agents]})
return jsonify(res)
"""
列出管理端用户。无 page 参数时返回全量数组(兼容旧调用);带 page 时分页并支持筛选。
Query: page, page_size, username, email, department, role, status, real_name,
employee_id, phone_number, hide_rejected
Returns (paginated): { items, total, page, page_size, pages }
Returns (legacy): User[]
"""
query = _apply_admin_users_filters(db.session.query(User))
if 'page' not in request.args:
users = query.options(joinedload(User.agents)).order_by(User.id.asc()).all()
return jsonify([_serialize_admin_user(u) for u in users])
page = request.args.get('page', type=int) or 1
page_size = request.args.get('page_size', type=int) or 20
page = max(1, page)
page_size = max(1, min(100, page_size))
total = query.count()
pages = max(1, (total + page_size - 1) // page_size) if total else 1
if page > pages:
page = pages
users = (
query.options(joinedload(User.agents))
.order_by(User.id.asc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return jsonify({
'items': [_serialize_admin_user(u) for u in users],
'total': int(total),
'page': page,
'page_size': page_size,
'pages': pages,
})
@admin_bp.route('/users', methods=['POST'])
@require_admin
def create_user():
"""
管理端创建用户:本地入库前先同步 Casdoor add-user,与改密一样保持 IdP 一致。
核心逻辑:校验 → 构建 User → _sync_casdoor_create_user → commit;Casdoor 失败则 rollback。
Request JSON: username, password, email, real_name, employee_id, phone_number 等
Returns:
201 + { id };Casdoor/唯一约束失败时抛出 AppError/ConflictError
"""
from app.api import user as user_api
data = request.get_json() or {}
required_field_errors = (
('username', 'USER.USERNAME_REQUIRED', 'Username is required'),
@@ -480,22 +588,51 @@ def create_user():
email = _empty_to_none(data.get('email'))
if not _is_valid_email(email):
raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'})
_assert_user_unique_fields(
None,
email=email,
employee_id=_empty_to_none(data.get('employee_id')),
phone_number=_empty_to_none(data.get('phone_number')),
)
user = User(username=data['username'], email=email, department=_empty_to_none(data.get('department')), role=data.get('role', 'user'), status=data.get('status', 'active'), real_name=_empty_to_none(data.get('real_name')), employee_id=_empty_to_none(data.get('employee_id')), phone_number=_empty_to_none(data.get('phone_number')))
user.set_password(data['password'])
if data.get('agent_ids'):
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
user.agents = agents
db.session.add(user)
try:
if data.get('agent_ids'):
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
user.agents = agents
user_api._sync_casdoor_create_user(
username=user.username,
password=data['password'],
email=email,
real_name=user.real_name,
phone_number=user.phone_number,
status=user.status,
department=user.department,
)
db.session.commit()
except IntegrityError as e:
db.session.rollback()
_raise_user_integrity_conflict(e)
except AppError:
db.session.rollback()
raise
except RuntimeError as e:
db.session.rollback()
user_api._raise_casdoor_add_user_error(e)
return (jsonify({'id': user.id}), 201)
@admin_bp.route('/users/<int:id>', methods=['PUT'])
@require_admin
def update_user(id):
"""
管理端编辑用户:资料仅写本地库;仅改密时同步 Casdoor set-password。
核心逻辑:唯一字段预校验 → 应用本地字段与 agent_ids →(有 new_password 时)_sync_casdoor_update_user → commit。
Request JSON: email, department, role, status, password 等;password 为空表示不改密
Returns:
{ status: ok };Casdoor 改密/唯一约束失败时抛出 AppError/ConflictError
"""
from app.api import user as user_api
user = db.session.get(User, id)
if not user:
raise NotFoundError('User not found')
@@ -504,28 +641,47 @@ def update_user(id):
email = _empty_to_none(data.get('email'))
if email is not None and (not _is_valid_email(email)):
raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'})
for k in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
if k in data:
if k in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
setattr(user, k, _empty_to_none(data[k]))
else:
setattr(user, k, data[k])
if data.get('password'):
user.set_password(data['password'])
if 'agent_ids' in data:
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
user.agents = agents
unique_updates = {
field: _empty_to_none(data[field])
for field in ('email', 'employee_id', 'phone_number')
if field in data
}
_assert_user_unique_fields(id, **unique_updates)
new_password = _empty_to_none(data.get('password'))
try:
for k in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
if k in data:
if k in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
setattr(user, k, _empty_to_none(data[k]))
else:
setattr(user, k, data[k])
if new_password:
user.set_password(new_password)
if 'agent_ids' in data:
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
user.agents = agents
if new_password:
user_api._sync_casdoor_update_user(user, new_password=new_password)
db.session.commit()
except IntegrityError as e:
db.session.rollback()
_raise_user_integrity_conflict(e)
except AppError:
db.session.rollback()
raise
except RuntimeError as e:
db.session.rollback()
user_api._raise_casdoor_set_password_error(e)
return jsonify({'status': 'ok'})
@admin_bp.route('/users/cleanup-rejected', methods=['POST'])
@require_admin
def cleanup_rejected_users():
cnt = db.session.query(User).filter_by(status='rejected').delete()
rejected_ids = [
row[0]
for row in db.session.query(User.id).filter_by(status='rejected').all()
]
cnt = delete_admin_users(rejected_ids)
db.session.commit()
return jsonify({'deleted_count': cnt})
@@ -539,10 +695,42 @@ def batch_delete_users():
target_ids = [uid for uid in ids if str(uid) != str(current_user_id)]
if not target_ids:
raise ValidationError('No valid users')
cnt = db.session.query(User).filter(User.id.in_(target_ids)).delete(synchronize_session=False)
db.session.commit()
try:
cnt = delete_admin_users(target_ids)
db.session.commit()
except IntegrityError as exc:
db.session.rollback()
raise AppError(
code='USER.DELETE_BLOCKED',
message='Unable to delete user because related records still exist',
http_status=409,
details={'reason': str(getattr(exc, 'orig', exc))},
) from exc
return jsonify({'deleted_count': cnt})
@admin_bp.route('/users/<int:id>', methods=['DELETE'])
@require_admin
def delete_user(id: int):
"""删除单个用户,复用 delete_admin_users 的关联清理逻辑。"""
current_user = _get_auth_user()
if current_user and str(current_user.id) == str(id):
raise ValidationError('Cannot delete current user')
user = db.session.get(User, id)
if not user:
raise NotFoundError('User not found')
try:
delete_admin_users([id])
db.session.commit()
except IntegrityError as exc:
db.session.rollback()
raise AppError(
code='USER.DELETE_BLOCKED',
message='Unable to delete user because related records still exist',
http_status=409,
details={'reason': str(getattr(exc, 'orig', exc))},
) from exc
return jsonify({'status': 'ok'})
@admin_bp.route('/permissions/batch', methods=['POST'])
@require_admin
def batch_update_permissions():
@@ -650,39 +838,175 @@ def reject_request(id):
@admin_bp.route('/quick-questions', methods=['GET'])
@require_admin
def list_quick_questions():
qqs = db.session.query(QuickQuestion).filter(QuickQuestion.user_id == None).order_by(QuickQuestion.sort_order.asc()).all()
"""
列出全局常用问题(含 FAQ 缓存字段)。
@query stale_only - 可选,true 时仅返回待复审(stale_at 非空)条目
@returns JSON 数组,每项含 answer/cache_enabled/hit_count/stale_* 等扩展字段
"""
stale_only = str(request.args.get('stale_only', '')).lower() in {'1', 'true', 'yes'}
query = (
db.session.query(QuickQuestion)
.filter(QuickQuestion.user_id.is_(None))
.order_by(QuickQuestion.sort_order.asc(), QuickQuestion.id.asc())
)
if stale_only:
query = query.filter(QuickQuestion.stale_at.isnot(None))
qqs = query.all()
res = []
for q in qqs:
agent = db.session.get(Agent, q.agent_id)
res.append({'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id, 'agent_name': agent.name if agent else 'Unknown', 'sort_order': q.sort_order})
stale_doc = db.session.get(KbDocument, q.stale_kb_document_id) if q.stale_kb_document_id else None
res.append(_serialize_admin_quick_question(q, agent.name if agent else 'Unknown', stale_doc))
return jsonify(res)
def _parse_aliases(raw_aliases) -> list[str]:
"""
解析别名列表,支持 JSON 数组或换行分隔字符串。
@param raw_aliases - 请求体 aliases 字段
@returns 去重后的别名字符串列表
"""
if raw_aliases is None:
return []
if isinstance(raw_aliases, list):
items = [str(item).strip() for item in raw_aliases if str(item).strip()]
elif isinstance(raw_aliases, str):
items = [line.strip() for line in raw_aliases.splitlines() if line.strip()]
else:
return []
seen: set[str] = set()
result: list[str] = []
for item in items:
if item not in seen:
seen.add(item)
result.append(item)
return result
def _parse_expires_at(raw_value) -> datetime | None:
"""
解析 FAQ 过期时间。
@param raw_value - ISO 字符串或 None
@returns datetime 或 None
"""
if not raw_value:
return None
text = str(raw_value).strip()
if not text:
return None
try:
return datetime.fromisoformat(text.replace('Z', '+00:00')).replace(tzinfo=None)
except ValueError:
raise ValidationError('Invalid expires_at format')
def _serialize_admin_quick_question(
q: QuickQuestion,
agent_name: str,
stale_kb_document: KbDocument | None = None,
) -> dict:
"""
序列化全局常用问题供管理端展示。
@param q - QuickQuestion 实例
@param agent_name - 所属应用名称
@param stale_kb_document - 触发待复审的 KB 文档(可选)
@returns 可 JSON 化的字典
"""
return {
'id': q.id,
'title': q.title,
'question': q.question,
'answer': q.answer,
'aliases': q.aliases if isinstance(q.aliases, list) else [],
'cache_enabled': bool(q.cache_enabled),
'is_enabled': bool(q.is_enabled),
'hit_count': q.hit_count or 0,
'agent_id': q.agent_id,
'agent_name': agent_name,
'sort_order': q.sort_order,
'expires_at': q.expires_at.isoformat() if q.expires_at else None,
'updated_at': q.updated_at.isoformat() if getattr(q, 'updated_at', None) else None,
'source_kb_document_ids': q.source_kb_document_ids if isinstance(q.source_kb_document_ids, list) else [],
'stale_at': q.stale_at.isoformat() if getattr(q, 'stale_at', None) else None,
'stale_reason': q.stale_reason,
'stale_kb_document_id': q.stale_kb_document_id,
'stale_kb_document_title': stale_kb_document.title if stale_kb_document else None,
}
def _apply_quick_question_payload(qq: QuickQuestion, data: dict, *, require_answer: bool = False) -> None:
"""
将请求体字段写入 QuickQuestion 实例。
@param qq - 待更新的 QuickQuestion
@param data - 请求 JSON
@param require_answer - 创建时为 True,cache_enabled 时强制校验 answer
"""
if 'title' in data:
qq.title = str(data['title']).strip()
if 'question' in data:
qq.question = str(data['question']).strip()
if 'agent_id' in data:
qq.agent_id = data['agent_id']
if 'sort_order' in data:
qq.sort_order = data.get('sort_order', 0)
if 'answer' in data:
qq.answer = str(data['answer']).strip() or None
if 'aliases' in data:
qq.aliases = _parse_aliases(data['aliases'])
if 'cache_enabled' in data:
qq.cache_enabled = bool(data['cache_enabled'])
if 'is_enabled' in data:
qq.is_enabled = bool(data['is_enabled'])
if 'expires_at' in data:
qq.expires_at = _parse_expires_at(data['expires_at'])
if 'retriever_resources' in data and isinstance(data.get('retriever_resources'), list):
from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq
apply_retriever_resources_to_faq(qq, data['retriever_resources'])
if data.get('clear_stale'):
from app.services.faq_kb_invalidation import clear_faq_stale
clear_faq_stale(qq)
if qq.cache_enabled and not str(qq.answer or '').strip():
raise ValidationError('启用 FAQ 缓存时必须填写标准答案')
if require_answer and (not qq.title or not qq.question or not qq.agent_id):
raise ValidationError('Missing required fields')
@admin_bp.route('/quick-questions', methods=['POST'])
@require_admin
def create_quick_question():
"""
创建全局常用问题,可选启用 FAQ 缓存。
@returns 201 + {id}
"""
data = request.get_json() or {}
if not data.get('title') or not data.get('question') or (not data.get('agent_id')):
raise ValidationError('Missing required fields')
qq = QuickQuestion(user_id=None, agent_id=data['agent_id'], title=data['title'], question=data['question'], sort_order=data.get('sort_order', 0))
qq = QuickQuestion(user_id=None)
_apply_quick_question_payload(qq, data, require_answer=True)
if isinstance(data.get('retriever_resources'), list):
from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq
apply_retriever_resources_to_faq(qq, data['retriever_resources'])
qq.updated_at = datetime.utcnow()
db.session.add(qq)
db.session.commit()
return (jsonify({'id': qq.id}), 201)
@admin_bp.route('/quick-questions/<int:id>', methods=['PUT'])
@require_admin
def update_quick_question(id):
"""
更新全局常用问题及 FAQ 缓存配置。
@returns {status: ok}
"""
qq = db.session.get(QuickQuestion, id)
if not qq:
if not qq or qq.user_id is not None:
raise NotFoundError('Not found')
data = request.get_json() or {}
if 'title' in data:
qq.title = data['title']
if 'question' in data:
qq.question = data['question']
if 'agent_id' in data:
qq.agent_id = data['agent_id']
if 'sort_order' in data:
qq.sort_order = data['sort_order']
_apply_quick_question_payload(qq, data)
qq.updated_at = datetime.utcnow()
db.session.commit()
return jsonify({'status': 'ok'})
@@ -695,13 +1019,177 @@ def delete_quick_question(id):
db.session.commit()
return jsonify({'status': 'ok'})
@admin_bp.route('/faq-candidates', methods=['GET'])
@require_admin
def list_faq_candidates():
"""
列出 PostgreSQL 中的热点 FAQ 候选(离线聚合结果)。
@query agent_id - 可选,按应用筛选
@returns { items, stats, rules }
"""
from app.services.hot_faq_aggregator import HotFaqAggregator
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
agent_id = request.args.get('agent_id', type=int)
items = HotFaqCandidateStore.list_candidates(agent_id)
stats = HotFaqCandidateStore.summarize(items)
return jsonify({
'items': items,
'stats': stats,
'rules': HotFaqAggregator.get_rules_document(),
})
@admin_bp.route('/faq-candidates/refresh', methods=['POST'])
@require_admin
def refresh_faq_candidates():
"""
手动触发离线热点聚合。
@body agent_id - 可选;dry_run - 可选,仅预览
@returns 聚合结果摘要
"""
from app.services.hot_faq_aggregator import HotFaqAggregator
data = request.get_json(silent=True) or {}
agent_id = data.get('agent_id')
dry_run = bool(data.get('dry_run'))
if agent_id is not None:
agent_id = int(agent_id)
result = HotFaqAggregator.aggregate_hot_faq_candidates(agent_id=agent_id, dry_run=dry_run)
return jsonify(result)
@admin_bp.route('/faq-candidates/promote', methods=['POST'])
@require_admin
def promote_faq_candidate():
"""
将热点候选晋升为全局 QuickQuestion(启用 FAQ 缓存),同事务更新候选状态。
@body agent_id, q_norm - 必填;title - 可选
@returns { id } 新建 QuickQuestion 主键
"""
from app.services.faq_text_utils import normalize_faq_query
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
data = request.get_json() or {}
agent_id = data.get('agent_id')
q_norm = normalize_faq_query(str(data.get('q_norm') or ''))
if not agent_id or not q_norm:
raise ValidationError('agent_id and q_norm are required')
candidate = HotFaqCandidateStore.get_candidate(int(agent_id), q_norm)
if not candidate:
raise NotFoundError('FAQ candidate not found')
title = str(data.get('title') or candidate.get('canonical_query') or q_norm).strip()[:100]
question = str(candidate.get('canonical_query') or q_norm).strip()
answer = str(candidate.get('answer') or '').strip()
if not answer:
raise ValidationError('Candidate has no answer')
aliases = [q for q in (candidate.get('sample_queries') or []) if normalize_faq_query(q) != q_norm]
retriever_resources = candidate.get('retriever_resources') if isinstance(candidate.get('retriever_resources'), list) else None
qq = QuickQuestion(
user_id=None,
agent_id=int(agent_id),
title=title,
question=question,
answer=answer,
aliases=aliases or None,
cache_enabled=True,
is_enabled=True,
retriever_resources=retriever_resources,
sort_order=int(data.get('sort_order') or 0),
updated_at=datetime.utcnow(),
)
from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq
apply_retriever_resources_to_faq(qq, retriever_resources)
db.session.add(qq)
db.session.flush()
if not HotFaqCandidateStore.mark_promoted(int(agent_id), q_norm, qq.id):
db.session.rollback()
raise NotFoundError('FAQ candidate not found')
db.session.commit()
return jsonify({'id': qq.id, 'status': 'ok'})
@admin_bp.route('/faq-candidates/dismiss', methods=['POST'])
@require_admin
def dismiss_faq_candidate():
"""
忽略热点候选:标记 dismissed 并设置 deny_until。
@body agent_id, q_norm - 必填
@returns { status: ok }
"""
from app.services.faq_text_utils import normalize_faq_query
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
data = request.get_json() or {}
agent_id = data.get('agent_id')
q_norm = normalize_faq_query(str(data.get('q_norm') or ''))
if not agent_id or not q_norm:
raise ValidationError('agent_id and q_norm are required')
HotFaqCandidateStore.dismiss(int(agent_id), q_norm)
return jsonify({'status': 'ok'})
USAGE_BY_USER_TOP_LIMIT = 50
@admin_bp.route('/reports/usage', methods=['GET'])
@require_admin
def usage_report():
"""
聊天使用分析:按应用汇总全部;按用户仅 TOP N(默认 50)并支持分页。
Query: user_page(默认 1)、user_page_size(默认 10,最大 50)
"""
total = db.session.query(ChatLog).count()
by_user = db.session.query(User.username, func.count(ChatLog.id)).join(ChatLog).group_by(User.username).all()
by_agent = db.session.query(Agent.name, func.count(ChatLog.id)).join(ChatLog).group_by(Agent.name).all()
return jsonify({'total': total, 'by_user': [{'username': u, 'count': c} for u, c in by_user], 'by_agent': [{'agent': a, 'count': c} for a, c in by_agent]})
by_agent = (
db.session.query(Agent.name, func.count(ChatLog.id))
.join(ChatLog)
.group_by(Agent.name)
.order_by(desc(func.count(ChatLog.id)), Agent.name)
.all()
)
try:
user_page = int(request.args.get('user_page', 1))
except (TypeError, ValueError):
user_page = 1
try:
user_page_size = int(request.args.get('user_page_size', 10))
except (TypeError, ValueError):
user_page_size = 10
user_page = max(1, user_page)
user_page_size = max(1, min(user_page_size, USAGE_BY_USER_TOP_LIMIT))
by_user_top = (
db.session.query(User.username, func.count(ChatLog.id))
.join(ChatLog)
.group_by(User.username)
.order_by(desc(func.count(ChatLog.id)), User.username)
.limit(USAGE_BY_USER_TOP_LIMIT)
.all()
)
user_total = len(by_user_top)
user_pages = max(1, math.ceil(user_total / user_page_size)) if user_total else 1
user_page = min(user_page, user_pages)
offset = (user_page - 1) * user_page_size
by_user_page = by_user_top[offset:offset + user_page_size]
return jsonify({
'total': total,
'by_user': [{'username': u, 'count': c} for u, c in by_user_page],
'by_agent': [{'agent': a, 'count': c} for a, c in by_agent],
'user_total': user_total,
'user_page': user_page,
'user_page_size': user_page_size,
'user_pages': user_pages,
'user_top_limit': USAGE_BY_USER_TOP_LIMIT,
})
@admin_bp.route('/reports/feedback', methods=['GET'])
@require_admin
@@ -776,9 +1264,74 @@ def count_general_feedbacks_report():
total = query.count()
return jsonify({'table': 'general_feedbacks', 'total': int(total)})
def _chat_logs_report_query():
"""
聊天日志报表查询:关联用户与应用,供管理后台数据报表展示。
核心逻辑:ChatLog JOIN User、Agent,按创建时间倒序。
"""
return (
db.session.query(
ChatLog,
User.username.label('username'),
Agent.name.label('agent_name'),
)
.join(User, User.id == ChatLog.user_id)
.join(Agent, Agent.id == ChatLog.agent_id)
)
def _serialize_chat_log_report_row(log: ChatLog, username: str | None, agent_name: str | None) -> dict:
"""
将 ChatLog 及关联字段序列化为报表行(隐藏 run_id / 原始 ID 类外键列)。
保留 id 供前端批量删除使用,默认不在表格列中展示。
"""
created_at = log.created_at.isoformat() if log.created_at else None
return {
'id': log.id,
'agent_name': agent_name or '',
'username': username or '',
'created_at': created_at,
'query': log.query,
'answer': log.answer,
'session_id': log.session_id,
'tokens_used': log.tokens_used,
'message_type': log.message_type,
}
def _apply_chat_logs_report_filters(query):
"""
对聊天日志报表查询应用列筛选(支持展示列名与 ChatLog 字段名)。
"""
reserved = {'limit', 'offset', 'page', 'page_size'}
for key, value in request.args.items():
if key in reserved or not value:
continue
if key == 'agent_name':
query = query.filter(Agent.name.cast(db.String).ilike(f'%{value}%'))
elif key == 'username':
query = query.filter(User.username.cast(db.String).ilike(f'%{value}%'))
elif hasattr(ChatLog, key):
col = getattr(ChatLog, key)
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
return query
def _list_chat_logs_report():
"""管理后台聊天日志报表数据列表(最多 100 条,支持列筛选)。"""
query = _apply_chat_logs_report_filters(_chat_logs_report_query())
query = query.order_by(desc(ChatLog.created_at), desc(ChatLog.id))
items = query.limit(100).all()
rows = [_serialize_chat_log_report_row(log, username, agent_name) for log, username, agent_name in items]
return jsonify(rows)
@admin_bp.route('/database/<table>', methods=['GET'])
@require_admin
def get_table_data(table):
if table == 'chat_logs':
return _list_chat_logs_report()
model_map = {'users': User, 'agents': Agent, 'chat_logs': ChatLog, 'feedbacks': Feedback, 'permission_requests': PermissionRequest, 'departments': Department, 'quick_questions': QuickQuestion, 'user_homepage_configs': UserHomepageConfig, 'user_favorite_agents': UserFavoriteAgent, 'user_default_agents': UserDefaultAgent}
model = model_map.get(table)
if not model:
@@ -1258,46 +1811,40 @@ def wecom_binding_stats():
@require_admin
def sync_wecom_userids_admin():
"""
从企微通讯录按工号同步 users.wecom_userid。
Request JSON: { "apply": false, "department_id": 1 }
从 OA userInfo_view 按工号同步 users.wecom_userid(workcode→employee_id,id→wecom_userid)。
Request JSON: { "apply": false }
"""
data = request.get_json() or {}
apply = bool(data.get('apply'))
department_id = data.get('department_id')
if department_id is not None and department_id != '':
try:
department_id = int(department_id)
except (TypeError, ValueError):
raise ValidationError('department_id must be an integer')
else:
department_id = None
try:
summary = sync_wecom_userids_from_directory(apply=apply, department_id=department_id)
summary = sync_wecom_userids_from_oa(apply=apply)
current_app.logger.info(
'[wecom_sync] admin apply=%s updated=%s would_update=%s conflicts=%s',
'[wecom_sync] oa apply=%s updated=%s would_update=%s conflicts=%s local_matched=%s',
apply,
summary.get('updated'),
summary.get('would_update'),
len(summary.get('conflicts') or []),
summary.get('local_matched'),
)
return jsonify(summary)
except RuntimeError as exc:
message = str(exc)
if 'not configured' in message.lower():
raise AppError(
code='SYSTEM.HTTP_ERROR',
message=message,
http_status=503,
details={'error_code': 'WECOM_NOT_CONFIGURED'},
)
if 'conflicts detected' in message.lower():
raise ConflictError(message, details={'error_code': 'WECOM_SYNC_CONFLICTS'})
if 'department/list failed' in message.lower() or 'user/list failed' in message.lower():
if '未找到可用的 SQL Server ODBC 驱动' in message or 'pyodbc' in message.lower():
raise AppError(
code='SYSTEM.HTTP_ERROR',
message='WeCom directory API failed. Check app contact read permissions.',
http_status=502,
details={'error_code': 'WECOM_DIRECTORY_API_FAILED', 'technical': message[:300]},
code='SYSTEM.SERVICE_UNAVAILABLE',
message='OA SQL Server driver is not available on this server',
http_status=503,
details={'error_code': 'OA_SQLSERVER_DRIVER_MISSING', 'technical': message[:300]},
)
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=message, http_status=500)
raise AppError(
code='SYSTEM.HTTP_ERROR',
message='OA SQL Server sync failed. Check OA_SQLSERVER_* env and network access.',
http_status=502,
details={'error_code': 'OA_SQLSERVER_SYNC_FAILED', 'technical': message[:300]},
)
except Exception as exc:
current_app.logger.exception('[wecom_sync] oa unexpected failure: %s', exc)
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(exc), http_status=500)
+84 -11
View File
@@ -12,6 +12,7 @@ import os
import subprocess
import uuid
import json
import time
from datetime import datetime
from urllib.parse import urlparse
import requests
@@ -901,7 +902,15 @@ def get_chat_messages():
for log in logs:
if log.query:
messages.append({'role': 'user', 'content': log.query})
assistant_msg = {'role': 'assistant', 'content': log.answer, 'chat_log_id': log.id, 'retriever_resources': log.retriever_resources or [], 'attribution_parts': log.attribution_parts or []}
assistant_msg = {
'role': 'assistant',
'content': log.answer,
'chat_log_id': log.id,
'retriever_resources': log.retriever_resources or [],
'attribution_parts': log.attribution_parts or [],
}
if log.run_id:
assistant_msg['run_id'] = log.run_id
if log.message_type:
assistant_msg['type'] = log.message_type
if log.payload:
@@ -1022,6 +1031,7 @@ def get_chat_query_preview(chat_log_id: int):
page_size=page_size,
agent=g.current_agent,
total_count=total_count,
user_context=Text2SQLService._normalize_user_context(g.current_user),
)
if columns == ["Error"]:
raise AppError(code='CHAT.QUERY_PREVIEW_FAILED', message=str(rows[0][0] if rows and rows[0] else 'query preview failed'), http_status=500)
@@ -1056,6 +1066,8 @@ def chat_completions():
query = data.get('query')
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
conversation_id = data.get('conversation_id')
shipping_task_id = str(data.get('task_id') or '').strip()
shipping_batch_no = str(data.get('batch_no') or '').strip()
kb_type = data.get('kb_type', '企业知识库')
files = data.get('files')
request_id = uuid.uuid4().hex[:12]
@@ -1075,6 +1087,7 @@ def chat_completions():
name=getattr(agent, 'name', None),
dify_api_key=getattr(agent, 'dify_api_key', None),
api_base_url=getattr(agent, 'api_base_url', None),
extra_config=getattr(agent, 'extra_config', None) or {},
)
user_proxy = SimpleNamespace(
id=user_id,
@@ -1143,7 +1156,20 @@ def chat_completions():
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
leave_supported = HRLeaveSQLServerService.supports(query)
leave_feature_enabled = _can_use_leave_feature(agent_proxy)
if PLMOracleService.supports(query, agent_proxy):
from app.services.faq_cache import FaqCacheService
faq_hit = FaqCacheService.try_match(query, agent_id) if not normalized_files else None
if faq_hit:
generator = FaqCacheService.stream_chat(
faq_hit,
query,
user_proxy,
agent_proxy,
external_conversation_id,
session_id=session.session_id,
)
elif PLMOracleService.supports(query, agent_proxy):
generator = PLMOracleService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
elif leave_supported and leave_feature_enabled:
if normalized_files:
@@ -1164,18 +1190,43 @@ def chat_completions():
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
else:
dify_inputs: dict[str, str] | None = None
from app.services.rohs_check_tools.dify_inputs import (
build_dify_chat_inputs as build_rohs_dify_chat_inputs,
is_rohs_check_chat_agent,
hxops_turn_id: str | None = None
from app.services.file_check_tools.agent_resolver import (
agent_declares_file_check_progress,
is_file_check_chat_agent,
)
from app.services.file_check_tools.dify_inputs import build_file_check_dify_inputs
from app.services.shipping_notice.dify_inputs import (
build_dify_chat_inputs as build_shipping_dify_chat_inputs,
build_dify_chat_inputs as build_shipping_notice_dify_inputs,
is_shipping_notice_chat_agent,
)
if is_shipping_notice_chat_agent(agent_proxy):
dify_inputs = build_shipping_dify_chat_inputs()
elif is_rohs_check_chat_agent(agent_proxy):
dify_inputs = build_rohs_dify_chat_inputs()
declares_file_check = agent_declares_file_check_progress(agent_proxy)
is_file_check_agent = is_file_check_chat_agent(agent_proxy)
is_shipping_agent = is_shipping_notice_chat_agent(agent_proxy)
if declares_file_check or is_file_check_agent:
# [STEP 1] 先校验 task_id,避免 Dify Chatflow 缺参时长连接挂死
dify_inputs = build_file_check_dify_inputs(agent_proxy, required=True)
if is_file_check_agent:
hxops_turn_id = uuid.uuid4().hex
from app.services.file_check_tools.chat_turn_registry import register_file_check_chat_turn
register_file_check_chat_turn(
turn_id=hxops_turn_id,
session_id=session.session_id,
user_id=user_proxy.id,
agent_id=agent_proxy.id,
query=query,
)
elif is_shipping_agent:
# [STEP 2] 发货通知 Chatflow 依赖会话级 task/batch 上下文稳定定位当前任务
dify_inputs = build_shipping_notice_dify_inputs(
external_conversation_id or session.session_id,
task_id=shipping_task_id,
batch_no=shipping_batch_no,
entry_mode="user_chat",
user_message=query,
trigger_source="frontend_chat",
)
generator = DifyService.stream_chat(
query,
user_proxy.id,
@@ -1183,11 +1234,16 @@ def chat_completions():
external_conversation_id,
request_id=request_id,
session_id=session.session_id,
hxops_turn_id=hxops_turn_id if is_file_check_agent else None,
files=normalized_files,
inputs=dify_inputs,
)
def relay_stream():
from app.services.chat_perf import chat_perf_enabled
relay_started = time.perf_counter()
relay_first_chunk_at: float | None = None
created_event = {
'event': 'session_created',
'conversation_id': session.session_id,
@@ -1201,6 +1257,8 @@ def chat_completions():
try:
for chunk in generator:
if relay_first_chunk_at is None:
relay_first_chunk_at = time.perf_counter()
if not isinstance(chunk, str) or not chunk.startswith('data: '):
yield chunk
continue
@@ -1218,7 +1276,7 @@ def chat_completions():
if provider_conversation_id and provider_conversation_id != known_provider_conversation_id:
known_provider_conversation_id = provider_conversation_id
should_touch = True
if event_name == 'message_end':
if event_name in ('message_end', 'workflow_finished'):
known_status = 'done'
should_touch = True
elif event_name == 'error':
@@ -1240,6 +1298,21 @@ def chat_completions():
event_data['provider_conversation_id'] = provider_conversation_id
event_data['conversation_id'] = session.session_id
event_data['session_status'] = known_status
if chat_perf_enabled() and event_name in ('message_end', 'workflow_finished'):
relay_first_ms = int((relay_first_chunk_at - relay_started) * 1000) if relay_first_chunk_at else None
relay_total_ms = int((time.perf_counter() - relay_started) * 1000)
current_app.logger.info(
'[chat-perf] relay request_id=%s session_id=%s first_chunk_ms=%s total_relay_ms=%s event=%s',
request_id,
session.session_id,
relay_first_ms,
relay_total_ms,
event_name,
)
event_data['hxops_relay'] = {
'first_chunk_ms': relay_first_ms,
'total_relay_ms': relay_total_ms,
}
yield f"data: {json.dumps(event_data, ensure_ascii=False)}\n\n"
except Exception as exc:
current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, session.session_id)
@@ -1,6 +1,9 @@
"""
backend/app/api/rohs_check_tools.py
文件用途:RoHS Chatflow 显式 HTTP Tool API。
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
@@ -13,25 +16,27 @@ from flask import Blueprint, current_app, jsonify, request, send_file
from sqlalchemy import text
from app import db
from app.api.workspace_rohs_check import serialize_rohs_judgement
from app.api.workspace_file_check import serialize_file_judgement
from app.errors import AppError, ConflictError, NotFoundError, ServiceUnavailableError, UnauthorizedError, ValidationError
from app.models import ScheduleRun, ScheduleTask
from app.services.file_check_tools.openapi_spec import build_file_check_openapi_spec
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
from app.services.rohs_check_tools.openapi_spec import build_rohs_openapi_spec
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
rohs_check_bp = Blueprint("rohs_check_tools", __name__)
file_check_bp = Blueprint("file_check_tools", __name__)
_EXCEL_TOKEN_SCOPES = {"rohs_check_excel", "rohs_schedule_excel"}
_EXCEL_TOKEN_SCOPES = {"file_check_excel", "file_schedule_excel"}
_RUN_START_LOCK = threading.Lock()
_ROHS_GLOBAL_LOCK_KEY = 8700000000
_ROHS_TASK_KEYWORDS = ("rohs", "rohs文件检核", "rohs 文件检核")
_TASK_LOCK_KEY_BASE = 8700000000
def _tool_token_secret() -> str:
return str(
current_app.config.get("ROHS_TOOLS_API_KEY")
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
or current_app.config.get("INTEGRATION_API_KEY")
or current_app.config.get("SECRET_KEY")
or "default-secret"
@@ -48,19 +53,19 @@ def _decode_download_token(token: str | None) -> dict | None:
payload = jwt.decode(normalized, _tool_token_secret(), algorithms=["HS256"])
return payload if isinstance(payload, dict) else None
except Exception as exc:
current_app.logger.warning("[rohs-tool] download token validation failed: %s", exc)
current_app.logger.warning("[file-check-tool] download token validation failed: %s", exc)
return None
def _require_tool_auth() -> None:
configured = str(
current_app.config.get("ROHS_TOOLS_API_KEY")
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
or current_app.config.get("INTEGRATION_API_KEY")
or ""
).strip()
if not configured:
raise ServiceUnavailableError(
"ROHS_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured",
"FILE_CHECK_TOOL_API_KEY or INTEGRATION_API_KEY is not configured",
code="missing_auth",
)
@@ -85,6 +90,11 @@ def _tool_error_code(exc: AppError) -> str:
"run_not_found",
"excel_not_ready",
"kb_sync_failed",
"query_required",
"kb_not_configured",
"kb_group_not_found",
"kb_dataset_not_bound",
"dify_retrieve_failed",
}:
return message
if exc.code == "AUTH.UNAUTHORIZED":
@@ -100,7 +110,7 @@ def _tool_error_code(exc: AppError) -> str:
return exc.code
@rohs_check_bp.errorhandler(AppError)
@file_check_bp.errorhandler(AppError)
def _handle_tool_app_error(exc: AppError):
status = exc.http_status
return jsonify({
@@ -114,39 +124,28 @@ def _public_base_url() -> str:
return resolve_HXOPS_TOOLS_API_BASE()
def _is_rohs_check_task(task: ScheduleTask | None) -> bool:
if not task:
return False
values = (
getattr(task, "schedule_no", None),
getattr(task, "name", None),
getattr(task, "platform_api_path", None),
)
haystack = " ".join(str(item or "").lower() for item in values)
return any(keyword in haystack for keyword in _ROHS_TASK_KEYWORDS)
def _acquire_rohs_start_lock() -> None:
"""Serialize RoHS start checks across processes when PostgreSQL is used."""
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
db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": _ROHS_GLOBAL_LOCK_KEY})
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": "rohs_check_excel",
"scope": "file_check_excel",
"run_id": run.id,
"exp": int(time.time()) + 600,
}
token = jwt.encode(payload, _tool_token_secret(), algorithm="HS256")
return f"{_public_base_url()}/api/rohs-check/tools/runs/{run.id}/excel?token={token}"
return f"{_public_base_url()}/api/file-check/tools/runs/{run.id}/excel?token={token}"
@rohs_check_bp.before_request
@file_check_bp.before_request
def _verify_tool_access():
if request.path.endswith("/openapi.json"):
return None
@@ -166,7 +165,7 @@ def _serialize_tool_run(run: ScheduleRun) -> dict:
"success_count": payload["success_count"],
"failed_count": payload["failed_count"],
"skipped_count": payload["skipped_count"],
"judgement": serialize_rohs_judgement(payload),
"judgement": serialize_file_judgement(payload),
"started_at": payload.get("started_at"),
"finished_at": payload.get("finished_at"),
"duration_ms": payload.get("duration_ms"),
@@ -204,58 +203,157 @@ def _resolve_check_task(data: dict | None = None, *, task_id: int | None = None)
task = ScheduleTask.query.filter_by(schedule_no=task_no).first()
if not task:
raise NotFoundError("task_not_found")
if not _is_rohs_check_task(task):
raise NotFoundError("task_not_found")
return task
@rohs_check_bp.route("/tools/tasks", methods=["GET"])
def list_rohs_tasks():
rows = ScheduleTask.query.order_by(ScheduleTask.created_at.desc()).all()
tasks = []
for task in rows:
if not _is_rohs_check_task(task):
continue
latest = (
ScheduleRun.query.filter_by(schedule_task_id=task.id)
.order_by(ScheduleRun.id.desc())
.first()
)
tasks.append({
"task_id": task.id,
"task_no": task.schedule_no,
"name": task.name,
"enabled": bool(task.enabled),
"last_status": latest.status if latest else None,
"last_run_at": task.last_run_at.isoformat() if task.last_run_at else None,
"next_run_at": task.next_run_at.isoformat() if task.next_run_at else None,
})
@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})
@rohs_check_bp.route("/tools/tasks/run", methods=["POST"])
def run_rohs_check():
"""立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。"""
data = request.get_json(silent=True) or {}
task = _resolve_check_task(data)
def _normalize_bind_payload(data: dict | None) -> dict:
"""规范化启动检核 Body;兼容 Chatflow 漏传 hxops_session_id。"""
payload = dict(data or {})
session_id = str(payload.get("hxops_session_id") or "").strip()
if session_id:
return payload
conversation_id = str(payload.get("conversation_id") or "").strip()
if not conversation_id:
return payload
from app.models import ChatSession
session = ChatSession.query.filter_by(session_id=conversation_id).first()
if session:
payload["hxops_session_id"] = conversation_id
return payload
def _prepare_bind_payload(data: dict | None) -> dict:
from app.services.file_check_tools.chat_turn_registry import infer_bind_context_for_run_request
payload = _normalize_bind_payload(data)
inferred = infer_bind_context_for_run_request(payload)
if inferred:
payload = {**payload, **inferred}
return payload
def _record_run_bind(run: ScheduleRun, data: dict) -> None:
from app.services.file_check_tools.chat_log_run_binding import merge_chat_log_bind_context
from app.services.file_check_tools.chat_turn_registry import attach_run_to_turn
merge_chat_log_bind_context(run, data)
turn_id = str(data.get("hxops_turn_id") or "").strip()
if turn_id:
attach_run_to_turn(turn_id, int(run.id))
def _build_no_data_response(task: ScheduleTask) -> dict:
"""无待检资料时直接返回提示,不创建批次也不绑定 run_id。"""
return {
"ok": False,
"error_code": "no_data_to_check",
"message": "目前没有资料需要检核",
"task": {
"task_id": task.id,
"task_name": task.name,
},
}
def _precheck_no_data(task: ScheduleTask) -> dict | None:
"""
启动前预检当前任务是否存在待检资料。
核心逻辑:仅在数据库型检核任务上做轻量预检;若结果为空,则直接返回 no_data_to_check,
避免创建空批次并向 ChatLog 回写 run_id。
"""
if str(getattr(task, "data_source_type", "") or "database").lower() != "database":
return None
cfg = get_schedule_sql_config_by_task_id(task.id)
if not cfg or not str(cfg.fetch_sql or "").strip():
return None
if cfg.data_source and not cfg.data_source.is_empty():
conn_str = cfg.data_source.build_connection_string()
else:
conn_str = _build_srm_conn_str()
rows = _fetch_records(conn_str, cfg.fetch_sql)
if rows:
return None
return _build_no_data_response(task)
@file_check_bp.route("/tools/tasks/run", methods=["POST"])
def run_file_check():
"""立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。"""
perf_started = time.perf_counter()
data = _prepare_bind_payload(request.get_json(silent=True) or {})
task = _resolve_check_task(data)
resolve_ms = int((time.perf_counter() - perf_started) * 1000)
lock_started = time.perf_counter()
with _RUN_START_LOCK:
_acquire_rohs_start_lock()
_acquire_task_start_lock(task.id)
existing = (
ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
.filter(ScheduleRun.status == "running")
ScheduleRun.query.filter_by(schedule_task_id=task.id, status="running")
.order_by(ScheduleRun.id.desc())
.all()
.first()
)
existing = next((row for row in existing if _is_rohs_check_task(row.task)), None)
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),
}), 409
})
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(),
@@ -266,11 +364,15 @@ def run_rohs_check():
api_request_json={
"trigger_source": data.get("trigger_source") or "dify_chatflow",
"conversation_id": data.get("conversation_id"),
"hxops_session_id": data.get("hxops_session_id"),
"hxops_turn_id": data.get("hxops_turn_id"),
"user_message": data.get("user_message"),
},
)
db.session.add(run)
db.session.commit()
_record_run_bind(run, data)
db.session.commit()
app = current_app._get_current_object()
run_id = run.id
task_id = task.id
@@ -284,7 +386,7 @@ def run_rohs_check():
try:
run_task_now(t, trigger_type="dify_chatflow", triggered_by_user_id=None, run=r)
except Exception as exc:
current_app.logger.error("[rohs-tool] run_id=%s failed: %s", run_id, exc, exc_info=True)
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"
@@ -292,21 +394,30 @@ def run_rohs_check():
r.finished_at = datetime.utcnow()
db.session.commit()
threading.Thread(target=_background, daemon=True, name=f"rohs-check-run-{run_id}").start()
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)})
@rohs_check_bp.route("/tools/runs/<int:run_id>", methods=["GET"])
def get_rohs_run(run_id: int):
@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)})
@rohs_check_bp.route("/tools/runs", methods=["GET"])
def list_rohs_runs():
@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))
@@ -316,12 +427,12 @@ def list_rohs_runs():
else:
query = ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
rows = query.order_by(ScheduleRun.created_at.desc()).limit(limit).all()
runs = [_serialize_tool_run(row) for row in rows if _is_rohs_check_task(row.task)]
runs = [_serialize_tool_run(row) for row in rows]
return jsonify({"ok": True, "runs": runs, "count": len(runs)})
@rohs_check_bp.route("/tools/runs/<int:run_id>/excel", methods=["GET"])
def download_rohs_run_excel(run_id: int):
@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:
@@ -340,8 +451,8 @@ def download_rohs_run_excel(run_id: int):
)
@rohs_check_bp.route("/tools/tasks/<int:task_id>/latest-run", methods=["GET"])
def get_latest_rohs_run(task_id: int):
@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:
@@ -349,6 +460,33 @@ def get_latest_rohs_run(task_id: int):
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
@rohs_check_bp.route("/tools/openapi.json", methods=["GET"])
def rohs_openapi_spec():
return jsonify(build_rohs_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
@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()))
+8
View File
@@ -0,0 +1,8 @@
"""
backend/app/api/internal/__init__.py
用途:内部 job 回调/健康检查 Blueprint。
"""
from app.api.internal.jobs import internal_jobs_bp # noqa: F401
__all__ = ['internal_jobs_bp']
+8
View File
@@ -0,0 +1,8 @@
"""
backend/app/api/internal/jobs.py
用途:内部 jobs API(Wave 1 自 internal_jobs.py 迁入)。
"""
from app.api.internal_jobs import internal_jobs_bp # noqa: F401
__all__ = ['internal_jobs_bp']
+69 -1
View File
@@ -13,6 +13,74 @@ internal_jobs_bp = Blueprint('internal_jobs', __name__)
def run_internal_job(name: str):
key = name.strip().lower()
data = request.get_json(silent=True) or {}
if key in {'fixed-assets-snapshot', 'fixed_assets_snapshot', 'fixedassets'}:
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
summary = FixedAssetsSnapshotService.sync_once(reason='internal_api', attempt=1)
row_count = int(summary.get('row_count') or 0)
return jsonify({
'summary': {
'total_count': row_count,
'success_count': row_count,
'failed_count': 0,
'skipped_count': 0,
},
'details': [summary],
'errors': [],
'step_logs': [
{
'step': 'fixed_assets_snapshot_sync',
'status': 'success',
'detail': {
'version': summary.get('current_version'),
'row_count': row_count,
},
}
],
})
if key in {'faq-aggregate-hot', 'faq_hot_aggregate', 'faq-hot-aggregate'}:
from app.services.hot_faq_aggregator import HotFaqAggregator
schedule_task_id = data.get('schedule_task_id')
agent_id = data.get('agent_id')
if schedule_task_id:
task = db.session.get(ScheduleTask, int(schedule_task_id))
if task and task.dify_agent_id:
agent_id = task.dify_agent_id
result = HotFaqAggregator.aggregate_hot_faq_candidates(
agent_id=int(agent_id) if agent_id else None,
dry_run=False,
)
if not result.get('enabled'):
message = str(result.get('message') or 'FAQ_HOT_ENABLED is false')
return jsonify({
'summary': {'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 1},
'details': [],
'errors': [message],
'step_logs': [{'step': 'faq_hot_aggregate', 'status': 'skipped', 'detail': {'message': message}}],
})
promoted = int(result.get('promoted_count') or 0)
skipped = int(result.get('skipped_count') or 0)
total = max(promoted + skipped, 1)
return jsonify({
'summary': {
'total_count': total,
'success_count': promoted,
'failed_count': 0,
'skipped_count': skipped,
},
'details': (result.get('candidates') or [])[:20],
'errors': [],
'step_logs': [{
'step': 'faq_hot_aggregate',
'status': 'success',
'detail': {
'scanned_logs': result.get('scanned_logs'),
'promoted_count': promoted,
'skipped_count': skipped,
},
}],
})
run_no = str(data.get('run_no') or '').strip()
schedule_task_id = data.get('schedule_task_id')
task = None
@@ -53,4 +121,4 @@ def run_internal_job(name: str):
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000)
run.step_logs = step_logs if step_logs else None
db.session.commit()
return jsonify({'summary': {'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'skipped_count': skipped_count}, 'details': details, 'errors': errors, 'step_logs': step_logs})
return jsonify({'summary': {'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'skipped_count': skipped_count}, 'details': details, 'errors': errors, 'step_logs': step_logs})
+15 -3
View File
@@ -889,12 +889,24 @@ def submit_document_clean(document_id: int):
raise ValidationError('当前文档暂无可清洗版本')
latest_clean_job = _latest_job_for_version(version.id, 'clean')
if latest_clean_job and latest_clean_job.status in ('queued', 'running'):
if latest_clean_job and latest_clean_job.status == 'running':
payload = _serialize_job(latest_clean_job)
payload['accepted'] = True
payload['queue_result'] = 'already_queued'
payload['message'] = latest_clean_job.message or '清洗任务已在处理中'
payload['queue_result'] = 'already_running'
payload['message'] = latest_clean_job.message or '清洗任务正在执行中'
return jsonify(payload), 202
if latest_clean_job and latest_clean_job.status == 'queued':
from app.services.knowledge_cleaning.tasks import run_clean_job
_ok, _message = run_clean_job(latest_clean_job.id)
db.session.expire_all()
refreshed = db.session.get(KbJob, latest_clean_job.id)
payload = _serialize_job(refreshed) if refreshed else {'id': latest_clean_job.id}
payload['accepted'] = True
payload['queue_result'] = 'inline_on_manual'
payload['message'] = (refreshed.message if refreshed else None) or _message or '清洗任务已执行'
status_code = 200 if refreshed and refreshed.status == 'success' else 202
return jsonify(payload), status_code
version.status = 'uploaded'
version.error_message = None
+9
View File
@@ -0,0 +1,9 @@
"""
backend/app/api/schedule/__init__.py
用途:排程管理 Blueprint 入口(自 schedule_admin.py 收敛)。
逻辑:Wave 1 前 re-export 旧模块 blueprint。
"""
from app.api.schedule_admin import schedule_admin_bp # noqa: F401
__all__ = ['schedule_admin_bp']
+19 -12
View File
@@ -301,7 +301,7 @@ def import_schedules():
schedule_no = str(item.get('schedule_no') or '').strip()
if schedule_no:
existing = db.session.query(ScheduleTask).filter_by(schedule_no=schedule_no).first()
task_payload = {'name': name, 'schedule_type': str(item.get('schedule_type') or 'platform_app'), 'owner_user_id': owner_user_id, 'cron_expr': cron_expr, 'wait_seconds': int(item.get('wait_seconds') or 0), 'dify_agent_id': item.get('dify_agent_id'), 'platform_api_path': item.get('platform_api_path'), 'notify_user_ids_json': item.get('notify_user_ids_json') if isinstance(item.get('notify_user_ids_json'), list) else [], 'notify_enabled': bool(item.get('notify_enabled', True)), 'enabled': bool(item.get('enabled', True)), 'data_source_type': str(item.get('data_source_type') or 'database'), 'kb_sync_enabled': bool(item.get('kb_sync_enabled', False)), 'kb_group_id': item.get('kb_group_id')}
task_payload = {'name': name, 'schedule_type': str(item.get('schedule_type') or 'platform_app'), 'owner_user_id': owner_user_id, 'cron_expr': cron_expr, 'schedule_timezone': item.get('schedule_timezone'), 'wait_seconds': int(item.get('wait_seconds') or 0), 'dify_agent_id': item.get('dify_agent_id'), 'platform_api_path': item.get('platform_api_path'), 'notify_user_ids_json': item.get('notify_user_ids_json') if isinstance(item.get('notify_user_ids_json'), list) else [], 'notify_enabled': bool(item.get('notify_enabled', True)), 'enabled': bool(item.get('enabled', True)), 'data_source_type': str(item.get('data_source_type') or 'database'), 'kb_sync_enabled': bool(item.get('kb_sync_enabled', False)), 'kb_group_id': item.get('kb_group_id')}
cfg = item.get('config') if isinstance(item.get('config'), dict) else None
if existing:
update_task(existing, payload=task_payload, actor_id=getattr(user, 'id', None))
@@ -309,7 +309,7 @@ def import_schedules():
if cfg:
upsert_schedule_task_config(existing.id, cfg)
else:
task = create_task(name=name, schedule_type=task_payload['schedule_type'], owner_user_id=owner_user_id, cron_expr=cron_expr, wait_seconds=task_payload['wait_seconds'], dify_agent_id=task_payload['dify_agent_id'], platform_api_path=task_payload['platform_api_path'], notify_user_ids_json=task_payload['notify_user_ids_json'], notify_enabled=task_payload['notify_enabled'], enabled=task_payload['enabled'], actor_id=getattr(user, 'id', None))
task = create_task(name=name, schedule_type=task_payload['schedule_type'], owner_user_id=owner_user_id, cron_expr=cron_expr, schedule_timezone=task_payload['schedule_timezone'], wait_seconds=task_payload['wait_seconds'], dify_agent_id=task_payload['dify_agent_id'], platform_api_path=task_payload['platform_api_path'], notify_user_ids_json=task_payload['notify_user_ids_json'], notify_enabled=task_payload['notify_enabled'], enabled=task_payload['enabled'], actor_id=getattr(user, 'id', None))
task.data_source_type = task_payload['data_source_type']
task.kb_sync_enabled = task_payload['kb_sync_enabled']
task.kb_group_id = int(task_payload['kb_group_id']) if task_payload.get('kb_group_id') not in (None, '', 0, '0') else None
@@ -329,16 +329,19 @@ def post_schedule():
data = request.get_json(silent=True) or {}
user = get_current_user()
data_source_type = str(data.get('data_source_type') or 'database')
task = create_task(name=str(data.get('name') or '').strip(), schedule_type='platform_app', owner_user_id=int(data.get('owner_user_id')), cron_expr=str(data.get('cron_expr') or '').strip(), wait_seconds=int(data.get('wait_seconds') or 0), dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None, platform_api_path=str(data.get('platform_api_path') or '').strip() or None, notify_user_ids_json=data.get('notify_user_ids_json') if isinstance(data.get('notify_user_ids_json'), list) else [], notify_enabled=bool(data.get('notify_enabled', True)), enabled=bool(data.get('enabled', True)), actor_id=getattr(user, 'id', None))
task = create_task(name=str(data.get('name') or '').strip(), schedule_type='platform_app', owner_user_id=int(data.get('owner_user_id')), cron_expr=str(data.get('cron_expr') or '').strip(), schedule_timezone=data.get('schedule_timezone'), wait_seconds=int(data.get('wait_seconds') or 0), dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None, platform_api_path=str(data.get('platform_api_path') or '').strip() or None, notify_user_ids_json=data.get('notify_user_ids_json') if isinstance(data.get('notify_user_ids_json'), list) else [], notify_enabled=bool(data.get('notify_enabled', True)), enabled=bool(data.get('enabled', True)), actor_id=getattr(user, 'id', None))
task.data_source_type = data_source_type
task.kb_sync_enabled = bool(data.get('kb_sync_enabled', False))
raw_kb_group_id = data.get('kb_group_id')
task.kb_group_id = int(raw_kb_group_id) if raw_kb_group_id not in (None, '', 0, '0') else None
task.platform_api_path = f'/{task.id}'
if data_source_type == 'faq_hot_aggregate':
task.platform_api_path = 'faq-aggregate-hot'
else:
task.platform_api_path = f'/{task.id}'
db.session.commit()
db.session.refresh(task)
config_data = data.get('config')
if config_data:
if config_data and data_source_type != 'faq_hot_aggregate':
upsert_schedule_task_config(task.id, config_data)
if not task.dify_agent_id:
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
@@ -403,16 +406,19 @@ def enable_schedule(task_id: int):
task = db.session.get(ScheduleTask, task_id)
if not task:
raise NotFoundError('Not found')
from app.services.schedule.cron_util import normalize_cron_expr
from app.services.schedule.query_service import serialize_task
from app.services.schedule.timezone_util import compute_next_run_at
from app.services.schedule.timezone_util import normalize_schedule_timezone
task.enabled = True
if task.cron_expr:
try:
from croniter import croniter
iter = croniter(task.cron_expr, datetime.utcnow())
task.next_run_at = iter.get_next(datetime)
except Exception:
task.next_run_at = None
task.cron_expr = normalize_cron_expr(task.cron_expr)
task.schedule_timezone = normalize_schedule_timezone(getattr(task, 'schedule_timezone', None))
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone)
db.session.commit()
return jsonify({'ok': True})
return jsonify(serialize_task(task))
@schedule_admin_bp.route('/schedules/<int:task_id>/disable', methods=['POST'])
@require_admin
@@ -421,6 +427,7 @@ def disable_schedule(task_id: int):
if not task:
raise NotFoundError('Not found')
task.enabled = False
task.next_run_at = None
db.session.commit()
return jsonify({'ok': True})
+283 -14
View File
@@ -1,11 +1,29 @@
"""
货代发货通知 Tool API — 供 Dify Chatflow Agent 调用
api/shipping_notice_tools.py
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。
依赖:shipping_notice.tools、query_service、openapi_spec、tool_api_url、Flask Blueprint。
逻辑:上游由 Dify/OpenAPI 或 RPA 请求进入本文件;本文件做轻量参数编排,再下沉到 services/shipping_notice/* workflow。
"""
from __future__ import annotations
import uuid
from flask import Blueprint, current_app, jsonify, request, send_file
from pathlib import Path
from app import db
from app.errors import AppError, ServiceUnavailableError, UnauthorizedError
from app.services.shipping_notice.query_service import (
EXPORT_MIME_TYPE,
get_batch_by_no,
get_focus_task_for_batch,
get_task_by_ref,
get_task_in_batch,
list_batch_task_summaries,
resolve_task_export_download,
serialize_batch_summary,
serialize_task_summary,
task_export_error_message,
)
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
@@ -13,6 +31,66 @@ from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
shipping_notice_bp = Blueprint("shipping_notice", __name__)
def _require_tool_auth() -> None:
"""
校验货代 Tool API 鉴权 Header。
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;当 Dify、RPA 或外部系统请求本蓝图时由 before_request 自动触发。
核心逻辑:对齐文件检核 Tool,只接受 `Authorization: Bearer <token>` 或
`X-Integration-Key`,并统一使用 `INTEGRATION_API_KEY` 作为服务端校验值;
未配置时报服务不可用,缺失或错误时报未授权。
"""
configured = str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
if not configured:
raise ServiceUnavailableError(
"INTEGRATION_API_KEY is not configured",
code="missing_auth",
)
bearer = str(request.headers.get("Authorization") or "").strip()
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
if configured in {token, integration_key}:
return
if not token and not integration_key:
raise UnauthorizedError("missing_auth")
raise UnauthorizedError("invalid_auth")
def _tool_error_code(exc: AppError) -> str:
"""统一归一化 Tool API 的错误码,保持与文件检核 Tool 返回风格一致。"""
message = str(exc.message or "").strip()
if message in {"missing_auth", "invalid_auth"}:
return message
if exc.code == "AUTH.UNAUTHORIZED":
return "invalid_auth"
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
return "missing_auth"
return exc.code
@shipping_notice_bp.errorhandler(AppError)
def _handle_tool_app_error(exc: AppError):
"""把业务异常统一转成 Tool 侧约定的 JSON 结构。"""
return jsonify({
"ok": False,
"error_code": _tool_error_code(exc),
"message": exc.message,
}), exc.http_status
@shipping_notice_bp.before_request
def _verify_tool_access():
"""
对货代 Tool / RPA / 导出接口做统一 Header 鉴权。
核心逻辑:仅放行 OpenAPI 导入文档,其他请求都必须携带有效 Tool Key。
"""
if request.path.endswith("/openapi.json") or request.path.endswith("/openapi.dify.yaml"):
return None
_require_tool_auth()
return None
def _tool_api_base_url() -> str:
"""Base URL for OpenAPI servers — hxops backend, NOT Dify (8882)."""
return resolve_tool_api_base_url()
@@ -26,14 +104,21 @@ def _payload() -> dict:
return request.get_json(silent=True) or {}
def _generate_batch_no() -> str:
from datetime import datetime
return f"SB-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
@shipping_notice_bp.route("/tools/openapi.json", methods=["GET"])
def openapi_spec():
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
return jsonify(_dify_openapi_spec())
@shipping_notice_bp.route("/tools/checkpoint-catalog", methods=["GET"])
def checkpoint_catalog():
"""Checkpoint ids, human_options, action_buttons — developer/docs reference (Dify approach B: do not embed)."""
"""返回检查点目录,供开发联调和文档核对 human_options/action_buttons。"""
from app.services.shipping_notice.state_machine import build_checkpoint_catalog
return jsonify(build_checkpoint_catalog())
@@ -41,6 +126,7 @@ def checkpoint_catalog():
@shipping_notice_bp.route("/tools/openapi.dify.yaml", methods=["GET"])
def openapi_dify_yaml():
"""返回 Dify 导入用的 OpenAPI YAML 文档。"""
import yaml
body = yaml.safe_dump(_dify_openapi_spec(), allow_unicode=True, sort_keys=False)
@@ -49,22 +135,106 @@ def openapi_dify_yaml():
@shipping_notice_bp.route("/tools/create_task", methods=["POST"])
def tool_create_task():
"""
创建单个发货任务。
【AI 触发时机】:当用户首次提交一张新的发货通知、当前会话里还没有对应任务时调用。
"""
return jsonify(shipping_tools.create_task(_payload()))
@shipping_notice_bp.route("/tools/create_batch", methods=["POST"])
def tool_create_batch():
"""
创建或复用发货批次。
【AI 触发时机】:当用户一次处理多份发货通知,需要把多任务挂到同一批次时调用。
"""
payload = _payload()
if isinstance(payload.get("notice_items"), list) and payload.get("notice_items"):
return jsonify(shipping_tools.create_batch_tasks(payload))
batch_no = str(payload.get("batch_no") or "").strip()
if batch_no:
batch = get_batch_by_no(batch_no)
if batch:
return jsonify(
{
"status": "ok",
"batch_no": batch.batch_no,
"message": f"已复用批次 {batch.batch_no}",
"data": serialize_batch_summary(batch),
}
)
batch = shipping_tools.create_batch(payload)
db.session.commit()
return jsonify(
{
"status": "ok",
"batch_no": batch.batch_no,
"message": f"已创建批次 {batch.batch_no}",
"data": serialize_batch_summary(batch),
}
)
@shipping_notice_bp.route("/tools/parse_notice", methods=["POST"])
def tool_parse_notice():
"""
解析发货通知正文。
【AI 触发时机】:当用户上传、粘贴或修正发货通知内容后,需要把文本转成任务单头和订单行时调用。
"""
return jsonify(shipping_tools.parse_notice(_payload()))
@shipping_notice_bp.route("/tools/update_notice_fields", methods=["POST"])
def tool_update_notice_fields():
"""
修改发货通知单头字段。
【AI 触发时机】:当用户明确要求更正客户、PO、收货地或交期等单头信息时调用。
"""
return jsonify(shipping_tools.update_notice_fields(_payload()))
@shipping_notice_bp.route("/tools/update_notice_line", methods=["POST"])
def tool_update_notice_line():
"""
修改指定订单行。
【AI 触发时机】:当用户指出某一行的 SKU、数量、Reservation ID 或交期有误时调用。
"""
return jsonify(shipping_tools.update_notice_line(_payload()))
@shipping_notice_bp.route("/tools/add_notice_line", methods=["POST"])
def tool_add_notice_line():
"""
新增订单行。
【AI 触发时机】:当用户说明漏了一行订单、需要补录发货通知明细时调用。
"""
return jsonify(shipping_tools.add_notice_line(_payload()))
@shipping_notice_bp.route("/tools/remove_notice_line", methods=["POST"])
def tool_remove_notice_line():
"""
删除订单行。
【AI 触发时机】:当用户确认某一行是误解析、重复行或不应出货的行时调用。
"""
return jsonify(shipping_tools.remove_notice_line(_payload()))
@shipping_notice_bp.route("/tools/parse_inventory", methods=["POST"])
def tool_parse_inventory():
"""
解析库存内容。
【AI 触发时机】:当用户提供库存文本或表格内容,需要把库存转成系统可匹配格式时调用。
"""
return jsonify(shipping_tools.parse_inventory(_payload()))
@shipping_notice_bp.route("/tools/upload_inventory_file", methods=["POST"])
def tool_upload_inventory_file():
"""Multipart upload — parse server-side without sending Excel through LLM."""
"""
服务器侧接收库存 Excel 并解析。
【AI 触发时机】:当用户上传库存 Excel,且不希望把二进制文件内容经由 LLM 传输时调用。
"""
task_id = str(request.form.get("task_id") or request.args.get("task_id") or "").strip()
upload = request.files.get("file")
return jsonify(shipping_tools.upload_inventory_file(task_id, upload))
@@ -72,72 +242,171 @@ def tool_upload_inventory_file():
@shipping_notice_bp.route("/tools/get_inventory_schema_preview", methods=["POST"])
def tool_get_inventory_schema_preview():
"""
获取库存表头预览。
【AI 触发时机】:当 Agent 需要先看 Excel/表格列名,再决定 map_json 或提示用户确认映射时调用。
"""
return jsonify(shipping_tools.get_inventory_schema_preview(_payload()))
@shipping_notice_bp.route("/tools/apply_inventory_mapping", methods=["POST"])
def tool_apply_inventory_mapping():
"""
应用库存字段映射。
【AI 触发时机】:当用户或 Agent 已确认列名与系统字段的对应关系,需要提交 map_json 时调用。
"""
return jsonify(shipping_tools.apply_inventory_mapping(_payload()))
@shipping_notice_bp.route("/tools/ensure_inventory", methods=["POST"])
def tool_ensure_inventory():
"""
保证任务已取得库存数据。
【AI 触发时机】:当发货通知已确认,下一步需要让系统拿到库存快照时调用。
"""
return jsonify(shipping_tools.ensure_inventory(_payload()))
@shipping_notice_bp.route("/tools/auto_progress", methods=["POST"])
def tool_auto_progress():
"""
自动推进任务。
【AI 触发时机】:当用户说“继续处理”“自动推进”“跑到下一步”时调用。
"""
return jsonify(shipping_tools.auto_progress(_payload()))
@shipping_notice_bp.route("/tools/match_inventory", methods=["POST"])
def tool_match_inventory():
"""
执行库存匹配。
【AI 触发时机】:当发货通知与库存都已准备好,需要判断是否缺货并生成匹配结果时调用。
"""
return jsonify(shipping_tools.match_inventory(_payload()))
@shipping_notice_bp.route("/tools/submit_decision", methods=["POST"])
def tool_submit_decision():
"""
提交人工决策。
【AI 触发时机】:当用户明确表达确认、驳回、重解析、重匹配、确认映射或关闭任务时调用。
"""
return jsonify(shipping_tools.submit_decision(_payload()))
@shipping_notice_bp.route("/tools/generate_shipment_excel", methods=["POST"])
def tool_generate_shipment_excel():
"""
生成出货 Excel。
【AI 触发时机】:当库存匹配已通过,用户要求导出货代上传模板时调用。
"""
return jsonify(shipping_tools.generate_excel(_payload()))
@shipping_notice_bp.route("/tools/upload_to_freight", methods=["POST"])
def tool_upload_to_freight():
"""
上传到货代系统或确认人工上传完成。
【AI 触发时机】:当用户要求推送到货代系统,或确认已手工完成上传时调用。
"""
return jsonify(shipping_tools.upload_to_freight(_payload()))
@shipping_notice_bp.route("/tools/get_task_status", methods=["POST"])
def tool_get_task_status():
"""
查询任务状态。
【AI 触发时机】:当 Agent 只拿到任务号/会话号,需要先确认当前卡点后再决定下一步时调用。
"""
return jsonify(shipping_tools.get_task_status(_payload()))
@shipping_notice_bp.route("/tools/get_batch_status", methods=["POST"])
def tool_get_batch_status():
"""
查询批次状态。
【AI 触发时机】:当用户关注整批任务处理进度,或 Agent 需要查看当前 focus task 与批次摘要时调用。
"""
payload = _payload()
batch_no = str(payload.get("batch_no") or "").strip()
if not batch_no:
return jsonify({"status": "failed", "message": "batch_no is required"}), 400
batch = get_batch_by_no(batch_no)
if not batch:
return jsonify({"status": "failed", "message": "batch not found"}), 404
focus_task = get_focus_task_for_batch(batch_no, batch.user_id or 0) if batch.user_id is not None else None
return jsonify(
{
"status": "ok",
"batch_no": batch.batch_no,
"message": f"已获取批次 {batch.batch_no} 状态",
"data": {
**serialize_batch_summary(batch),
"focus_task": serialize_task_summary(focus_task) if focus_task else None,
"tasks": list_batch_task_summaries(batch),
},
}
)
@shipping_notice_bp.route("/tools/switch_focus_task", methods=["POST"])
def tool_switch_focus_task():
"""
切换批次当前焦点任务。
【AI 触发时机】:当用户在同一批次里要求“看第 N 个任务”或切换当前处理对象时调用。
"""
payload = _payload()
batch_no = str(payload.get("batch_no") or "").strip()
task_no = str(payload.get("task_no") or payload.get("target_task_no") or "").strip()
if not batch_no or not task_no:
return jsonify({"status": "failed", "message": "batch_no and task_no are required"}), 400
batch = get_batch_by_no(batch_no)
if not batch:
return jsonify({"status": "failed", "message": "batch not found"}), 404
task = get_task_in_batch(batch_no, task_no)
if not task:
return jsonify({"status": "failed", "message": "task not found in batch"}), 404
batch.current_focus_task_no = task.task_no
db.session.commit()
return jsonify(
{
"status": "ok",
"batch_no": batch.batch_no,
"task_no": task.task_no,
"message": f"已切换当前任务到 {task.task_no}",
"data": {
"batch": serialize_batch_summary(batch),
"focus_task": serialize_task_summary(task),
},
}
)
@shipping_notice_bp.route("/rpa/inventory-ready", methods=["POST"])
def rpa_inventory_ready():
"""RPA 回调入口:上报库存导出结果并回写任务状态。"""
return jsonify(shipping_tools.rpa_report_inventory(_payload()))
@shipping_notice_bp.route("/rpa/upload-complete", methods=["POST"])
def rpa_upload_complete():
"""RPA 回调入口:上报货代上传结果并回写任务状态。"""
return jsonify(shipping_tools.rpa_report_upload(_payload()))
@shipping_notice_bp.route("/tasks/<task_no>/export", methods=["GET"])
def download_task_export(task_no: str):
from app.services.shipping_notice.tools import _get_task
task = _get_task(task_no)
if not task or not task.export_file_path:
return jsonify({"error": "export file not found"}), 404
path = Path(task.export_file_path)
if not path.is_file():
return jsonify({"error": "export file missing on disk"}), 404
"""下载任务已生成的出货 Excel。"""
task = get_task_by_ref(task_no)
err_msg = task_export_error_message(task)
if err_msg:
return jsonify({"error": err_msg}), 404
resolved = resolve_task_export_download(task)
assert resolved is not None
path, download_name = resolved
return send_file(
path,
as_attachment=True,
download_name=task.export_file_name or path.name,
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
download_name=download_name,
mimetype=EXPORT_MIME_TYPE,
)
+10
View File
@@ -0,0 +1,10 @@
"""
backend/app/api/tools/__init__.py
用途:Dify HTTP Tool API Blueprint 聚合。
逻辑:Wave 1 前 re-export shipping_notice_tools、file_check_tools。
"""
from app.api.tools.shipping_notice import shipping_notice_bp # noqa: F401
from app.api.tools.file_check import file_check_bp # noqa: F401
__all__ = ['shipping_notice_bp', 'file_check_bp']
+8
View File
@@ -0,0 +1,8 @@
"""
backend/app/api/tools/file_check.py
用途:文件检核 Tool API Blueprint(Wave 1 自 file_check_tools.py 迁入)。
"""
from app.api.file_check_tools import file_check_bp # noqa: F401
__all__ = ['file_check_bp']
+8
View File
@@ -0,0 +1,8 @@
"""
backend/app/api/tools/shipping_notice.py
用途:出货通知 Tool API Blueprint(Wave 1 自 shipping_notice_tools.py 迁入)。
"""
from app.api.shipping_notice_tools import shipping_notice_bp # noqa: F401
__all__ = ['shipping_notice_bp']
+285 -17
View File
@@ -1,6 +1,7 @@
from flask import Blueprint, request, jsonify, current_app
from app import db
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, Announcement, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog
from app.services.feedback_notify import send_feedback_group_notification
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
from app.auth_jwt import get_current_user as _auth_current_user
@@ -282,6 +283,218 @@ def _casdoor_set_password(user_owner: str, user_name: str, old_password: str, ne
if data.get('status') != 'ok':
_raise_casdoor_set_password_error(data)
def _is_casdoor_user_exists_error(message: str) -> bool:
lowered = (message or '').lower()
return 'already exist' in lowered or 'duplicate' in lowered or 'has existed' in lowered
def _raise_casdoor_add_user_error(source) -> None:
"""
将 Casdoor add-user 失败映射为稳定业务错误码,供管理端创建用户时展示。
@param source: Casdoor JSON 响应、RuntimeError 文本或其它异常来源
Raises:
ConflictError: Casdoor 侧用户名/邮箱已存在
AppError: 密码策略或 IdP 同步失败
"""
data = _extract_casdoor_error_payload(source)
msg_text = _clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if _is_casdoor_user_exists_error(lowered):
raise ConflictError('Username already exists in Casdoor', code='USER.USERNAME_EXISTS', details={'field': 'username', 'technical': msg_text})
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='Password does not meet security requirements', http_status=400)
raise AppError(code='CASDOOR_ADD_USER_FAILED', message='Failed to create user in authentication system. Please try again or contact the administrator.', http_status=502, details={'technical': msg_text or str(source or '')[:300]})
def _build_casdoor_user_profile_payload(*, username: str, email: str, real_name=None, phone_number=None, status='active', department=None) -> dict:
"""
组装 Casdoor 用户资料字段(create/update 共用),不含 password。
@param username: Casdoor name(与本地 username 一致)
@param email: 邮箱
@param real_name: 显示名/真实姓名
@param phone_number: 手机号
@param status: 本地账号状态;非 active 时 Casdoor 设为禁用
@param department: 部门,映射至 affiliation
Returns:
Casdoor User JSON 对象(资料部分)
"""
display_name = _clean_str(real_name) or username
payload = {
'owner': _casdoor_user_owner(),
'name': username,
'email': email or '',
'displayName': display_name,
'realName': _clean_str(real_name) or '',
'phone': _clean_str(phone_number) or '',
'isForbidden': _clean_str(status) not in (None, 'active'),
}
department_value = _clean_str(department)
if department_value:
payload['affiliation'] = department_value
return payload
def _build_casdoor_user_payload(*, username: str, password: str, email: str, real_name=None, phone_number=None, status='active', department=None) -> dict:
"""
组装 Casdoor add-user 请求体,字段与本地 User 模型对齐。
@param username: Casdoor name(与本地 username 一致)
@param password: 初始明文密码
@param email: 邮箱
@param real_name: 显示名/真实姓名
@param phone_number: 手机号
@param status: 本地账号状态;非 active 时 Casdoor 设为禁用
@param department: 部门,映射至 affiliation
Returns:
Casdoor User JSON 对象
"""
payload = _build_casdoor_user_profile_payload(
username=username,
email=email,
real_name=real_name,
phone_number=phone_number,
status=status,
department=department,
)
payload['password'] = password
return payload
def _casdoor_add_user(user_payload: dict):
"""
调用 Casdoor /api/add-user 创建 IdP 用户。
核心逻辑:使用 Client ID/Secret Basic Auth,与 set-password 管理 API 一致。
@param user_payload: Casdoor User 对象(owner/name/password 等)
Raises:
RuntimeError: HTTP 或配置异常
AppError: Casdoor 返回业务错误(经 _raise_casdoor_add_user_error 映射)
"""
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
if not base or not client_id or not client_secret:
raise RuntimeError('Casdoor is not configured')
url = f'{base}/api/add-user'
resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8)
try:
data = resp.json() or {}
except ValueError:
raise RuntimeError(f'Casdoor add-user failed: HTTP {resp.status_code} {resp.text[:200]}')
if data.get('status') != 'ok':
_raise_casdoor_add_user_error(data)
def _sync_casdoor_create_user(*, username: str, password: str, email: str, real_name=None, phone_number=None, status='active', department=None):
"""
管理端创建用户时同步至 Casdoor,与改密逻辑一致:Casdoor 已配置则必须成功,否则跳过。
核心逻辑:构建 add-user payload → 调 _casdoor_add_user;本地库 commit 由调用方负责。
@param username: 本地 username,同步为 Casdoor name
@param password: 初始明文密码
@param email: 邮箱
@param real_name: 真实姓名
@param phone_number: 手机号
@param status: 本地账号状态
@param department: 部门
Raises:
AppError / ConflictError: Casdoor 创建失败
"""
if not _is_casdoor_configured():
return
payload = _build_casdoor_user_payload(
username=username,
password=password,
email=email,
real_name=real_name,
phone_number=phone_number,
status=status,
department=department,
)
_casdoor_add_user(payload)
def _raise_casdoor_update_user_error(source) -> None:
"""
将 Casdoor update-user 失败映射为稳定业务错误码,供管理端编辑用户时展示。
@param source: Casdoor JSON 响应、RuntimeError 文本或其它异常来源
Raises:
ConflictError: Casdoor 侧邮箱等唯一字段冲突
AppError: IdP 同步失败
"""
data = _extract_casdoor_error_payload(source)
msg_text = _clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if _is_casdoor_user_missing_error(lowered):
_raise_casdoor_user_not_in_idp(source)
if _is_casdoor_user_exists_error(lowered) or ('email' in lowered and 'already' in lowered):
raise ConflictError('Email already exists in Casdoor', code='USER.EMAIL_EXISTS', details={'field': 'email', 'technical': msg_text})
raise AppError(code='CASDOOR_UPDATE_USER_FAILED', message='Failed to update user in authentication system. Please try again or contact the administrator.', http_status=502, details={'technical': msg_text or str(source or '')[:300]})
def _casdoor_update_user(user_payload: dict):
"""
调用 Casdoor /api/update-user 更新 IdP 用户资料。
核心逻辑:使用 Client ID/Secret Basic Auth,与 add-user/set-password 管理 API 一致。
@param user_payload: Casdoor User 对象(owner/name 及待更新字段)
Raises:
RuntimeError: HTTP 或配置异常
AppError: Casdoor 返回业务错误(经 _raise_casdoor_update_user_error 映射)
"""
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
if not base or not client_id or not client_secret:
raise RuntimeError('Casdoor is not configured')
url = f'{base}/api/update-user'
resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8)
try:
data = resp.json() or {}
except ValueError:
raise RuntimeError(f'Casdoor update-user failed: HTTP {resp.status_code} {resp.text[:200]}')
if data.get('status') != 'ok':
_raise_casdoor_update_user_error(data)
def _sync_casdoor_admin_set_password(user: User, new_password: str):
"""
管理端重设密码时同步 Casdoor(无旧密码,与 token 重置一致)。
IdP 用户不存在时抛出 CASDOOR_USER_NOT_IN_IDP,由上层决定是否 fallback add-user。
@param user: 本地用户
@param new_password: 新密码明文
Raises:
AppError: Casdoor 策略或 IdP 同步失败
"""
if not _is_casdoor_configured():
return
user_owner = _casdoor_user_owner()
try:
_casdoor_set_password(user_owner, user.username, '', new_password)
except RuntimeError as exc:
if _is_casdoor_user_missing_error(str(exc)):
_raise_casdoor_user_not_in_idp(exc)
_raise_casdoor_set_password_error(exc)
def _sync_casdoor_update_user(user: User, *, new_password: str | None = None):
"""
管理端编辑用户时同步 Casdoor:仅改密时 set-password;IdP 无账号则 add-user 补建。
核心逻辑:资料字段只写本地库,不调用 update-user;无新密码则跳过 Casdoor。
@param user: 已应用本地变更但未 commit 的 User 实例
@param new_password: 管理员设置的新密码;None 表示不改密
Raises:
AppError / ConflictError: Casdoor 改密或补建失败
"""
if not _is_casdoor_configured() or not new_password:
return
def _provision_missing_user_in_casdoor():
_sync_casdoor_create_user(
username=user.username,
password=new_password,
email=user.email,
real_name=user.real_name,
phone_number=user.phone_number,
status=user.status,
department=user.department,
)
try:
_sync_casdoor_admin_set_password(user, new_password)
except AppError as exc:
if exc.code == 'CASDOOR_USER_NOT_IN_IDP':
_provision_missing_user_in_casdoor()
return
raise
def _is_casdoor_password_error(message: str) -> bool:
lowered = (message or '').lower()
return 'invalid_grant' in lowered or 'password login failed' in lowered or 'incorrect password' in lowered
@@ -1396,6 +1609,15 @@ def submit_general_feedback():
row = GeneralFeedback(user_id=user.id, username=user.username, feedback_type=feedback_type, feedback_module=feedback_module, content=content, source_page=source_page, chat_log_id=chat_log_id)
db.session.add(row)
db.session.commit()
notify_result = send_feedback_group_notification(row, user)
if notify_result.get('ok'):
current_app.logger.info('[feedback] group notification sent feedback_id=%s', row.id)
elif not notify_result.get('skipped'):
current_app.logger.warning(
'[feedback] group notification failed feedback_id=%s reason=%s',
row.id,
notify_result.get('reason'),
)
return jsonify({'status': 'ok', 'id': row.id})
@user_bp.route('/home', methods=['GET'])
@@ -1414,7 +1636,12 @@ def home():
agent_rows = [{'id': agent.id, 'name': agent.name, 'description': agent.description, 'icon_url': agent.icon_url, 'extra_config': agent.extra_config} for agent in user.agents]
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
favorite_ids = [f.agent_id for f in favorites]
qqs = db.session.query(QuickQuestion).filter((QuickQuestion.user_id == user.id) | (QuickQuestion.user_id == None)).all()
qqs = db.session.query(QuickQuestion).filter(
or_(
QuickQuestion.user_id == user.id,
and_(QuickQuestion.user_id.is_(None), QuickQuestion.is_enabled.is_(True)),
)
).all()
layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
layout = layout_config.layout if layout_config else {}
embedded_rel = db.session.query(UserDefaultAgent).filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all()
@@ -1610,20 +1837,34 @@ def _build_password_reset_url(token: str) -> str:
return f'{base}/reset-password?token={token}'
def _password_reset_rate_limit_state(key: str, *, window_seconds: int = 300) -> tuple[bool, int]:
"""
判断找回密码是否触发限流,并在允许时记录本次请求时间。
@param key: 限流键,通常为 employee_id + IP
@param window_seconds: 窗口秒数,默认 5 分钟
Returns:
(allowed, retry_after_seconds):allowed 为 False 时 retry_after_seconds 为剩余等待秒数
"""
now = datetime.utcnow()
last = _PASSWORD_RESET_RATE_CACHE.get(key)
if last:
elapsed = (now - last).total_seconds()
if elapsed < window_seconds:
return False, max(1, int(window_seconds - elapsed))
_PASSWORD_RESET_RATE_CACHE[key] = now
return True, 0
def _check_password_reset_rate_limit(key: str, *, window_seconds: int = 300) -> bool:
"""
简易内存限流,防止同工号/IP 频繁触发找回密码。
@param key: 限流键,通常为 employee_id + IP
@param window_seconds: 窗口秒数,默认 5 分钟
Returns:
True 表示允许继续;False 表示应静默拒绝
True 表示允许继续;False 表示应拒绝
"""
now = datetime.utcnow()
last = _PASSWORD_RESET_RATE_CACHE.get(key)
if last and (now - last).total_seconds() < window_seconds:
return False
_PASSWORD_RESET_RATE_CACHE[key] = now
return True
allowed, _ = _password_reset_rate_limit_state(key, window_seconds=window_seconds)
return allowed
def _sync_casdoor_password_for_reset(user: User, new_password: str):
@@ -1697,12 +1938,25 @@ def reset_password_by_wecom():
raise ValidationError('Username is required')
rate_key = _password_reset_rate_key(employee_id)
if not _check_password_reset_rate_limit(rate_key):
allowed, retry_after_seconds = _password_reset_rate_limit_state(rate_key)
if not allowed:
retry_minutes = max(1, (retry_after_seconds + 59) // 60)
current_app.logger.info(
'[password_reset] noop reason=rate_limited employee_id=%s',
'[password_reset] rejected reason=rate_limited employee_id=%s retry_after_seconds=%s',
employee_id,
retry_after_seconds,
)
raise AppError(
code='AUTH.PASSWORD_RESET_RATE_LIMITED',
message='Password reset requests are too frequent',
http_status=429,
details={
'error_code': 'PASSWORD_RESET_RATE_LIMITED',
'retry_after_seconds': retry_after_seconds,
'retry_after_minutes': retry_minutes,
},
retryable=True,
)
return jsonify({'message': _PASSWORD_RESET_GENERIC_MESSAGE})
user = db.session.query(User).filter(User.employee_id == employee_id).first()
if not user:
@@ -1738,20 +1992,20 @@ def reset_password_by_wecom():
user.reset_token_expiry = datetime.utcnow() + timedelta(hours=1)
db.session.flush()
title = 'HXOPS 密码重置'
title = '和信AI智能工作台 密码重置'
content = (
'您发起了 HXOPS 密码重置请求。\n'
'您发起了和信AI智能工作台密码重置请求。\n'
'请在 1 小时内点击下方按钮设置新密码。\n'
'如非本人操作,请忽略本消息。'
)
try:
reset_jump_url = _build_password_reset_url(token)
result = send_wecom_event_message(
event_type='password_reset',
user=user,
title=title,
content=content,
jump_path='/reset-password',
jump_params={'token': token},
jump_url=reset_jump_url,
)
if not result.get('ok'):
db.session.rollback()
@@ -1809,13 +2063,23 @@ def reset_password_confirm():
Reset password with token
"""
data = request.get_json() or {}
token = data.get('token')
token = _clean_str(data.get('token'))
new_password = data.get('new_password')
if not token or not new_password:
raise ValidationError('Token and new password are required')
user = db.session.query(User).filter_by(reset_token=token).first()
if not user or not user.reset_token_expiry or user.reset_token_expiry < datetime.utcnow():
raise ValidationError('Invalid or expired token')
current_app.logger.info(
'[password_reset] confirm rejected reason=token_invalid token_prefix=%s found_user=%s',
token[:8] if token else '',
bool(user),
)
raise AppError(
code='AUTH.RESET_TOKEN_INVALID',
message='Invalid or expired token',
http_status=400,
details={'error_code': 'RESET_TOKEN_INVALID'},
)
try:
_sync_casdoor_password_for_reset(user, new_password)
user.set_password(new_password)
@@ -1846,6 +2110,10 @@ def get_agent_details(id):
if not has_permission:
raise ForbiddenError('Access denied')
extra_config = agent.extra_config or {}
if isinstance(extra_config, dict):
from app.services.file_check_tools.task_resolver import enrich_agent_extra_if_file_check
extra_config = enrich_agent_extra_if_file_check(agent)
dify_app_type = extra_config.get('dify_app_type') if isinstance(extra_config, dict) else None
dify_parameters = None
+15
View File
@@ -0,0 +1,15 @@
"""
backend/app/api/workspace/__init__.py
用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check)。
逻辑:Wave 1 前 re-export 旧 workspace_* 模块。
"""
from app.api.workspace_schedule import workspace_schedule_bp # noqa: F401
from app.api.workspace_shipping_notice import workspace_shipping_notice_bp # noqa: F401
from app.api.workspace_file_check import workspace_file_check_bp # noqa: F401
__all__ = [
'workspace_schedule_bp',
'workspace_shipping_notice_bp',
'workspace_file_check_bp',
]
+5
View File
@@ -0,0 +1,5 @@
"""
backend/app/api/workspace/file_check.py
用途:工作台文件检核路由(Wave 1 自 workspace_file_check.py 迁入)。
"""
+5
View File
@@ -0,0 +1,5 @@
"""
backend/app/api/workspace/schedule.py
用途:工作台排程路由(Wave 1 自 workspace_schedule.py 迁入)。
"""
@@ -0,0 +1,5 @@
"""
backend/app/api/workspace/shipping_notice.py
用途:工作台出货通知路由(Wave 1 自 workspace_shipping_notice.py 迁入)。
"""
@@ -1,15 +1,23 @@
"""
backend/app/api/workspace_file_check.py
用途:工作台文件检核进度轮询 API(对话页 tool_run_progress)。
依赖:file_check_tools.chat_log_run_resolver、schedule.query_service。
逻辑:前端按 chat_log_id / run_id 轮询检核批次状态与 Excel 链接。
"""
from __future__ import annotations
from flask import Blueprint, jsonify, request
from io import BytesIO
from flask import Blueprint, jsonify, request, send_file
from app.auth_jwt import get_current_user
from app.errors import ForbiddenError, NotFoundError, UnauthorizedError
from app.errors import NotFoundError, UnauthorizedError
from app.models import ScheduleRun, ScheduleTask
from app.services.file_check_tools.chat_log_run_resolver import find_run_for_chat_log
from app.services.schedule.query_service import get_run, serialize_run
workspace_rohs_check_bp = Blueprint("workspace_rohs_check", __name__)
_ROHS_TASK_KEYWORDS = ("rohs", "rohs文件检核", "rohs 文件检核")
workspace_file_check_bp = Blueprint("workspace_file_check", __name__)
def _require_user():
@@ -19,21 +27,12 @@ def _require_user():
return user
def _is_rohs_check_task(task: ScheduleTask | None) -> bool:
if not task:
return False
values = (
getattr(task, "schedule_no", None),
getattr(task, "name", None),
getattr(task, "platform_api_path", None),
)
haystack = " ".join(str(item or "").lower() for item in values)
return any(keyword in haystack for keyword in _ROHS_TASK_KEYWORDS)
def serialize_rohs_judgement(payload: dict) -> dict:
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("rohs_judgement") if isinstance(response_summary.get("rohs_judgement"), 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),
@@ -73,14 +72,14 @@ def _serialize_progress_run(run: ScheduleRun) -> dict:
"run_id": payload["id"],
"run_no": payload["run_no"],
"task_id": payload["schedule_task_id"],
"title": payload.get("schedule_name") or "RoHS 文件检核",
"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_rohs_judgement(payload),
"judgement": serialize_file_judgement(payload),
"current_step": serialize_current_step(payload),
"progress_percent": percent,
"started_at": payload.get("started_at"),
@@ -90,7 +89,7 @@ def _serialize_progress_run(run: ScheduleRun) -> dict:
"excel": {
"file_name": payload.get("excel_file_name"),
"file_size": payload.get("excel_file_size"),
"download_url": f"/api/workspace/schedule-runs/{run.id}/excel" if payload.get("excel_file_name") else None,
"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"),
@@ -103,33 +102,78 @@ def _serialize_progress_run(run: ScheduleRun) -> dict:
}
@workspace_rohs_check_bp.route("/rohs-check/runs/active", methods=["GET"])
def workspace_rohs_active_run():
@workspace_file_check_bp.route("/file-check/runs/for-log", methods=["GET"])
def workspace_file_check_run_for_log():
"""按 chat_log_id + schedule_task_id 返回该轮问答绑定的检核批次。"""
_require_user()
task_id = request.args.get("task_id", type=int)
chat_log_id = request.args.get("chat_log_id", type=int)
if not task_id or task_id <= 0:
return jsonify({"ok": False, "error": "task_id_required"}), 400
if not chat_log_id or chat_log_id <= 0:
return jsonify({"ok": False, "error": "chat_log_id_required"}), 400
run = find_run_for_chat_log(task_id=task_id, chat_log_id=chat_log_id)
return jsonify({
"ok": True,
"run": _serialize_progress_run(run) if run else None,
"match_source": "chat_log" if run else None,
})
@workspace_file_check_bp.route("/file-check/runs/for-session", methods=["GET"])
def workspace_file_check_run_for_session():
"""已废弃:请改用 for-log?chat_log_id=。保留接口避免旧客户端 404。"""
_require_user()
return jsonify({"ok": True, "run": None, "match_source": None, "session_updated_at": None})
@workspace_file_check_bp.route("/file-check/runs/active", methods=["GET"])
def workspace_file_check_active_run():
"""查询当前进行中的检核批次;优先按 schedule_task_id(query: task_id)过滤。"""
_require_user()
task_id = request.args.get("task_id", type=int)
conversation_id = str(request.args.get("conversation_id") or "").strip()
rows = (
query = (
ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
.filter(ScheduleRun.status == "running")
.order_by(ScheduleRun.id.desc())
.all()
)
run = next((
row for row in rows
if _is_rohs_check_task(row.task)
and (
not conversation_id
or str((row.api_request_json or {}).get("conversation_id") or "").strip() == conversation_id
)
), None)
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_rohs_check_bp.route("/rohs-check/runs/<int:run_id>", methods=["GET"])
def workspace_rohs_run_detail(run_id: int):
@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")
if not _is_rohs_check_task(run.task):
raise ForbiddenError("Forbidden")
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",
)
+376 -21
View File
@@ -1,23 +1,40 @@
"""
api/workspace_shipping_notice.py
用途:提供 HXOPS 工作台与聊天前端使用的发货通知用户态 API。
依赖:auth_jwt、query_service、shipping_notice.tools、notice_upload、chat_actions。
逻辑:前端通过本 Blueprint 访问用户鉴权路由;本文件做权限校验与参数编排,再调用 shipping_notice service/workflow 返回页面所需数据。
"""
from __future__ import annotations
from flask import Blueprint, jsonify, request, send_file
from pathlib import Path
from app import db
from app.auth_jwt import get_current_user
from app.models import ShippingTask
from app.models import ShippingBatch, ShippingTask
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
from app.services.shipping_notice.constants import CP_EXPORT_GENERATED, CP_NOTICE_TEXT_EXTRACTION_FAILED, AUTO_CHAIN_FALLBACK, MAP_JSON
from app.services.shipping_notice.query_service import (
EXPORT_MIME_TYPE,
get_batch_for_user,
get_focus_task_for_batch,
get_task_for_user,
list_batches_for_user,
list_tasks_for_batch,
list_tasks_for_user,
resolve_task_export_download,
serialize_batch_summary,
serialize_task_detail,
serialize_task_summary,
task_export_error_message,
)
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
def _require_user():
"""校验当前请求用户,统一返回 `(user, error_response)` 结构。"""
user = get_current_user()
if not user:
return None, (jsonify({"error": "Unauthorized"}), 401)
@@ -26,16 +43,191 @@ def _require_user():
@workspace_shipping_notice_bp.route("/shipping-tasks", methods=["GET"])
def workspace_shipping_tasks():
"""列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
user, err = _require_user()
if err:
return err
batch_no = str(request.args.get("batch_no") or "").strip() or None
process_status = str(request.args.get("process_status") or "").strip() or None
limit = int(request.args.get("limit") or 100)
return jsonify(list_tasks_for_user(user.id, process_status=process_status, limit=limit))
return jsonify(list_tasks_for_user(user.id, batch_no=batch_no, process_status=process_status, limit=limit))
@workspace_shipping_notice_bp.route("/shipping-batches", methods=["GET"])
def workspace_shipping_batches():
"""列出当前用户的发货批次摘要。"""
user, err = _require_user()
if err:
return err
limit = int(request.args.get("limit") or 100)
return jsonify(list_batches_for_user(user.id, limit=limit))
@workspace_shipping_notice_bp.route("/shipping-batches/create-from-notices", methods=["POST"])
def workspace_create_shipping_batch_from_notices():
"""接收多份发货通知附件,创建批次并交给后台编排器逐票推进。"""
user, err = _require_user()
if err:
return err
uploads = request.files.getlist("files")
if not uploads:
single = request.files.get("file")
if single:
uploads = [single]
if not uploads:
return jsonify({"error": "files is required"}), 400
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.notice_upload import (
extract_notice_text,
guess_source_type,
max_notice_chars,
save_task_notice_upload,
)
conversation_id = str(request.form.get("conversation_id") or "").strip()
notice_items: list[dict] = []
for upload in uploads:
raw = upload.read() or b""
filename = upload.filename or "notice"
source_type = guess_source_type(filename)
text = ""
warnings: list[str] = []
try:
temp_task_no = f"TMP-{len(notice_items) + 1}"
saved_path = save_task_notice_upload(temp_task_no, filename, raw)
text, meta = extract_notice_text(saved_path)
warnings = list(meta.get("warnings") or []) if isinstance(meta, dict) else []
except Exception as exc:
warnings = [f"notice_extract_failed:{exc}"]
if text:
limit = max_notice_chars()
if len(text) > limit:
text = text[:limit]
warnings.append(f"notice_text_truncated:{limit}")
notice_items.append(
{
"source_type": source_type,
"source_file_name": filename,
"source_file_type": str(getattr(upload, "mimetype", "") or "").strip() or None,
"raw_text": text,
"warnings": warnings,
}
)
payload = {
"user_id": user.id,
"conversation_id": conversation_id or None,
"file_count": len(notice_items),
"notice_items": notice_items,
# 上传接口先快速完成建批/建任务与 raw_text 落库,避免请求阻塞;
# 后续首轮解析与可自动推进步骤交给后台编排线程逐票执行。
"defer_parse": True,
}
created = shipping_tools.create_batch_tasks(payload)
data = created.get("data") if isinstance(created, dict) else None
batch_data = data.get("batch") if isinstance(data, dict) else None
tasks_data = data.get("tasks") if isinstance(data, dict) else None
batch_no = str(created.get("batch_no") or (batch_data or {}).get("batch_no") or "").strip()
orchestrator_started = False
if batch_no:
from app.services.shipping_notice.batch_orchestrator import start_batch_orchestrator
orchestrator_started = start_batch_orchestrator(batch_no)
if isinstance(data, dict) and batch_no:
focus_task = get_focus_task_for_batch(batch_no, user.id)
if focus_task:
data["focus_task"] = serialize_task_summary(focus_task)
if isinstance(tasks_data, list):
data["tasks"] = tasks_data
data["orchestrator_started"] = orchestrator_started
if isinstance(created, dict):
base_message = str(created.get("message") or "").strip()
if orchestrator_started:
created["message"] = (
f"{base_message},后台已开始逐票处理。"
if base_message
else "后台已开始逐票处理。"
)
return jsonify(created)
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>", methods=["GET"])
def workspace_shipping_batch_detail(batch_no: str):
"""返回批次详情、批次内任务列表和当前焦点任务。"""
user, err = _require_user()
if err:
return err
batch = get_batch_for_user(batch_no, user.id)
if not batch:
return jsonify({"error": "Not found"}), 404
focus_task = get_focus_task_for_batch(batch_no, user.id)
return jsonify(
{
**serialize_batch_summary(batch),
"tasks": list_tasks_for_batch(batch_no, user.id),
"focus_task": serialize_task_summary(focus_task) if focus_task else None,
}
)
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>/tasks", methods=["GET"])
def workspace_shipping_batch_tasks(batch_no: str):
"""返回指定批次下的任务列表。"""
user, err = _require_user()
if err:
return err
batch = get_batch_for_user(batch_no, user.id)
if not batch:
return jsonify({"error": "Not found"}), 404
return jsonify(list_tasks_for_batch(batch_no, user.id))
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>/focus-task", methods=["GET"])
def workspace_shipping_batch_focus_task(batch_no: str):
"""返回指定批次当前焦点任务的摘要。"""
user, err = _require_user()
if err:
return err
batch = get_batch_for_user(batch_no, user.id)
if not batch:
return jsonify({"error": "Not found"}), 404
focus_task = get_focus_task_for_batch(batch_no, user.id)
if not focus_task:
return jsonify({"error": "Focus task not found"}), 404
return jsonify(serialize_task_summary(focus_task))
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>/focus-task", methods=["POST"])
def workspace_switch_shipping_batch_focus_task(batch_no: str):
"""切换批次当前焦点任务,供工作台在同批次任务间跳转。"""
user, err = _require_user()
if err:
return err
batch = get_batch_for_user(batch_no, user.id)
if not batch:
return jsonify({"error": "Not found"}), 404
data = request.get_json(silent=True) or {}
task_no = str(data.get("task_no") or data.get("target_task_no") or "").strip()
if not task_no:
return jsonify({"error": "task_no is required"}), 400
task = get_task_for_user(task_no, user.id)
if not task or task.batch_id != batch.id:
return jsonify({"error": "Task not found in batch"}), 404
batch.current_focus_task_no = task.task_no
db.session.commit()
return jsonify(
{
"batch": serialize_batch_summary(batch),
"focus_task": serialize_task_summary(task),
}
)
@workspace_shipping_notice_bp.route("/shipping-tasks", methods=["POST"])
def workspace_create_shipping_task():
"""创建单个发货任务,适用于手工录入或聊天入口先建单。"""
user, err = _require_user()
if err:
return err
@@ -58,6 +250,7 @@ def workspace_create_shipping_task():
@workspace_shipping_notice_bp.route("/shipping-tasks/create-from-notice", methods=["POST"])
def workspace_create_shipping_task_from_notice():
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。"""
user, err = _require_user()
if err:
return err
@@ -112,17 +305,37 @@ def workspace_create_shipping_task_from_notice():
task.raw_content = text
db.session.commit()
payload = {"task_id": task_id}
parsed = shipping_tools.parse_notice(payload)
data = parsed.get("data") if isinstance(parsed, dict) else None
if isinstance(data, dict):
data["notice_upload"] = {"filename": upload.filename or "", **meta}
parsed["message"] = f"已上传发货通知文件并创建任务 {task_id}。{parsed.get('message') or ''}".strip()
return jsonify(parsed)
task = ShippingTask.query.filter_by(task_no=task_id).first()
if task:
task.source_file_name = str(upload.filename or "").strip() or task.source_file_name
task.source_file_type = str(getattr(upload, "mimetype", "") or "").strip() or task.source_file_type
db.session.commit()
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
orchestrator_started = start_task_orchestrator(task_id)
return jsonify(
{
"status": "ok",
"task_id": task_id,
"message": (
f"已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。"
if orchestrator_started
else f"已上传发货通知文件并创建任务 {task_id}。通知原文已保存。"
),
"data": {
"task": serialize_task_summary(task) if task else {"task_no": task_id},
"notice_upload": {"filename": upload.filename or "", **meta},
"parse_status": "deferred",
"orchestrator_started": orchestrator_started,
},
}
)
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>", methods=["GET"])
def workspace_shipping_task_detail(task_no: str):
"""返回指定任务的详情快照。"""
user, err = _require_user()
if err:
return err
@@ -134,6 +347,7 @@ def workspace_shipping_task_detail(task_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/chat-actions", methods=["GET"])
def workspace_shipping_task_chat_actions(task_no: str):
"""返回聊天气泡侧所需的动作按钮与检查点信息。"""
user, err = _require_user()
if err:
return err
@@ -143,9 +357,29 @@ def workspace_shipping_task_chat_actions(task_no: str):
return jsonify(build_chat_actions_payload(task))
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/retry", methods=["POST"])
def workspace_retry_shipping_task(task_no: str):
"""重试当前任务,适用于超时、解析失败或自动推进中断后的恢复。"""
user, err = _require_user()
if err:
return err
task = get_task_for_user(task_no, user.id)
if not task:
return jsonify({"error": "Not found"}), 404
from app.services.shipping_notice import tools as shipping_tools
data = request.get_json(silent=True) or {}
payload = {"task_id": task.task_no}
comment = str(data.get("comment") or "").strip()
if comment:
payload["comment"] = comment
return jsonify(shipping_tools.retry_task(payload))
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/upload-inventory", methods=["POST"])
def workspace_upload_shipping_inventory(task_no: str):
"""Hxops chat UI: upload inventory Excel with user auth (not Tool Key)."""
"""用户态上传库存 Excel,并在服务端完成解析。"""
user, err = _require_user()
if err:
return err
@@ -161,6 +395,7 @@ def workspace_upload_shipping_inventory(task_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/apply-inventory-mapping", methods=["POST"])
def workspace_apply_inventory_mapping(task_no: str):
"""提交库存字段映射,并允许在工作台侧自动回退到下一步。"""
user, err = _require_user()
if err:
return err
@@ -183,7 +418,7 @@ def workspace_apply_inventory_mapping(task_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/submit-decision", methods=["POST"])
def workspace_submit_shipping_decision(task_no: str):
"""Hxops chat UI: submit shipping decision with user auth (bypass Dify tool routing)."""
"""以用户态提交人工决策,绕过 Dify Tool 路由直接驱动状态机。"""
user, err = _require_user()
if err:
return err
@@ -205,9 +440,110 @@ def workspace_submit_shipping_decision(task_no: str):
return jsonify(shipping_tools.submit_decision(payload))
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/update-notice-fields", methods=["POST"])
def workspace_update_shipping_notice_fields(task_no: str):
"""更新发货通知单头字段。"""
user, err = _require_user()
if err:
return err
task = get_task_for_user(task_no, user.id)
if not task:
return jsonify({"error": "Not found"}), 404
data = request.get_json(silent=True) or {}
fields = data.get("fields")
if not isinstance(fields, dict) or not fields:
return jsonify({"error": "fields is required"}), 400
from app.services.shipping_notice import tools as shipping_tools
payload = {"task_id": task.task_no, "fields": fields}
comment = str(data.get("comment") or "").strip()
if comment:
payload["comment"] = comment
return jsonify(shipping_tools.update_notice_fields(payload))
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/update-notice-line", methods=["POST"])
def workspace_update_shipping_notice_line(task_no: str):
"""更新发货通知中的指定订单行。"""
user, err = _require_user()
if err:
return err
task = get_task_for_user(task_no, user.id)
if not task:
return jsonify({"error": "Not found"}), 404
data = request.get_json(silent=True) or {}
try:
line_index = int(data.get("line_index"))
except (TypeError, ValueError):
return jsonify({"error": "line_index is required"}), 400
patch = data.get("patch")
if not isinstance(patch, dict) or not patch:
return jsonify({"error": "patch is required"}), 400
from app.services.shipping_notice import tools as shipping_tools
payload = {"task_id": task.task_no, "line_index": line_index, "patch": patch}
comment = str(data.get("comment") or "").strip()
if comment:
payload["comment"] = comment
return jsonify(shipping_tools.update_notice_line(payload))
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/add-notice-line", methods=["POST"])
def workspace_add_shipping_notice_line(task_no: str):
"""为发货通知新增订单行。"""
user, err = _require_user()
if err:
return err
task = get_task_for_user(task_no, user.id)
if not task:
return jsonify({"error": "Not found"}), 404
data = request.get_json(silent=True) or {}
line = data.get("line")
if not isinstance(line, dict) or not line:
return jsonify({"error": "line is required"}), 400
from app.services.shipping_notice import tools as shipping_tools
payload = {"task_id": task.task_no, "line": line}
comment = str(data.get("comment") or "").strip()
if comment:
payload["comment"] = comment
return jsonify(shipping_tools.add_notice_line(payload))
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/remove-notice-line", methods=["POST"])
def workspace_remove_shipping_notice_line(task_no: str):
"""删除发货通知中的指定订单行。"""
user, err = _require_user()
if err:
return err
task = get_task_for_user(task_no, user.id)
if not task:
return jsonify({"error": "Not found"}), 404
data = request.get_json(silent=True) or {}
try:
line_index = int(data.get("line_index"))
except (TypeError, ValueError):
return jsonify({"error": "line_index is required"}), 400
from app.services.shipping_notice import tools as shipping_tools
payload = {"task_id": task.task_no, "line_index": line_index}
comment = str(data.get("comment") or "").strip()
if comment:
payload["comment"] = comment
return jsonify(shipping_tools.remove_notice_line(payload))
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/auto-progress", methods=["POST"])
def workspace_auto_progress_shipping_task(task_no: str):
"""Hxops chat fallback: same as Dify auto_progress tool."""
"""用户态触发 auto_progress,作为聊天前端的兜底自动推进入口。"""
user, err = _require_user()
if err:
return err
@@ -234,6 +570,7 @@ def workspace_auto_progress_shipping_task(task_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/match-inventory", methods=["POST"])
def workspace_match_shipping_inventory(task_no: str):
"""执行库存匹配,并在生成 Excel 后补充前端可直接下载的链接。"""
user, err = _require_user()
if err:
return err
@@ -272,7 +609,7 @@ def workspace_match_shipping_inventory(task_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/mark-manual-uploaded", methods=["POST"])
def workspace_mark_manual_uploaded(task_no: str):
"""Hxops chat: mark freight manual upload complete (no ref no required)."""
"""标记货代系统已人工上传完成,无需再等待 RPA 回执。"""
user, err = _require_user()
if err:
return err
@@ -289,6 +626,7 @@ def workspace_mark_manual_uploaded(task_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/generate-excel", methods=["POST"])
def workspace_generate_shipping_excel(task_no: str):
"""为指定任务生成出货 Excel,并补充工作台下载链接。"""
user, err = _require_user()
if err:
return err
@@ -310,18 +648,35 @@ def workspace_generate_shipping_excel(task_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/export", methods=["GET"])
def workspace_shipping_task_export(task_no: str):
"""下载当前用户可访问任务的出货 Excel。"""
user, err = _require_user()
if err:
return err
task = get_task_for_user(task_no, user.id)
if not task or not task.export_file_path:
return jsonify({"error": "export file not found"}), 404
path = Path(task.export_file_path)
if not path.is_file():
return jsonify({"error": "export file missing on disk"}), 404
err_msg = task_export_error_message(task)
if err_msg:
return jsonify({"error": err_msg}), 404
resolved = resolve_task_export_download(task)
assert resolved is not None
path, download_name = resolved
return send_file(
path,
as_attachment=True,
download_name=task.export_file_name or path.name,
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
download_name=download_name,
mimetype=EXPORT_MIME_TYPE,
)
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>/retry-pending", methods=["POST"])
def workspace_retry_shipping_batch_pending(batch_no: str):
"""重试批次中仍可自动推进的任务,跳过终态和人工阻断任务。"""
user, err = _require_user()
if err:
return err
batch = get_batch_for_user(batch_no, user.id)
if not batch:
return jsonify({"error": "Not found"}), 404
from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks
return jsonify(retry_batch_pending_tasks(batch.batch_no))
+1
View File
@@ -0,0 +1 @@
"""FAQ CLI 包。"""
+44
View File
@@ -0,0 +1,44 @@
"""
backend/app/cli/faq_commands.py
用途:FAQ 相关 Flask CLI 命令注册。
依赖:HotFaqAggregator、Flask click。
逻辑:create_app 时 init_app 注册 faq-aggregate-hot 命令。
"""
import click
from flask.cli import with_appcontext
from app.services.hot_faq_aggregator import HotFaqAggregator
@click.command('faq-aggregate-hot')
@click.option('--agent-id', type=int, default=None, help='仅聚合指定 Agent')
@click.option('--dry-run', is_flag=True, help='只统计不写 PostgreSQL')
@with_appcontext
def faq_aggregate_hot(agent_id: int | None, dry_run: bool):
"""
离线聚合 ChatLog 热点 FAQ 候选并写入 faq_hot_candidates 表。
核心逻辑:委托 HotFaqAggregator.aggregate_hot_faq_candidates。
"""
result = HotFaqAggregator.aggregate_hot_faq_candidates(agent_id=agent_id, dry_run=dry_run)
if not result.get('enabled'):
click.echo(result.get('message', 'FAQ hot aggregation disabled'))
return
click.echo(
f"scanned={result['scanned_logs']} groups={result['group_count']} "
f"promoted={result['promoted_count']} skipped={result['skipped_count']} dry_run={dry_run}"
)
for item in result.get('candidates', [])[:20]:
click.echo(
f" [{item.get('agent_name')}] {item.get('canonical_query')} "
f"asks={item.get('ask_count_7d')} users={item.get('user_count_7d')} "
f"dominance={item.get('answer_dominance')}"
)
if len(result.get('candidates', [])) > 20:
click.echo(f" ... and {len(result['candidates']) - 20} more")
def init_app(app):
"""向 Flask app 注册 FAQ CLI 命令。"""
app.cli.add_command(faq_aggregate_hot)
+51 -3
View File
@@ -90,6 +90,8 @@ class Config:
# Dify 网关配置
DIFY_API_BASE = os.getenv('DIFY_API_BASE')
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
DIFY_CHAT_CONNECT_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_CONNECT_TIMEOUT_SECONDS', '5'))
DIFY_CHAT_READ_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_READ_TIMEOUT_SECONDS', '30'))
# Redis 连接配置,默认使用本地 Redis + 密码
REDIS_URL = os.getenv('REDIS_URL')
FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true'
@@ -107,18 +109,34 @@ class Config:
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
# HXOPS Tool API 对外基地址(RoHS / 货代等 Dify Chatflow 共用;无尾斜杠)
# HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 共用;无尾斜杠)
HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOLS_API_BASE')
# 货代发货通知 Agent Tool API
SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY')
# RoHS 检核 Chatflow Tool API
ROHS_TOOLS_API_KEY = os.getenv('ROHS_TOOLS_API_KEY')
# 文件检核 Chatflow Tool API
FILE_CHECK_TOOL_API_KEY = os.getenv('FILE_CHECK_TOOL_API_KEY')
SHIPPING_NOTICE_STORAGE_ROOT = _data_path("SHIPPING_NOTICE_STORAGE_ROOT", "shipping_notice")
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD = float(
os.getenv('SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD') or '0.7'
)
# 建单后是否延后 parse_notice,交由 Dify 画布 LLM + Tool 解析(默认 true,符合 Dify 优先原则)
SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY = os.getenv('SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY', 'true').lower() == 'true'
SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED = (
os.getenv('SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY = int(
os.getenv('SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY') or '3'
)
SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS') or '180'
)
SHIPPING_NOTICE_TASK_EXECUTION_MODE = os.getenv('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker').strip().lower()
SHIPPING_NOTICE_WORKER_POLL_SECONDS = float(os.getenv('SHIPPING_NOTICE_WORKER_POLL_SECONDS', '2'))
SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float(
os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '300')
)
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW = os.getenv('SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW', 'true')
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED', 'false').lower() == 'true'
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
@@ -189,6 +207,9 @@ class Config:
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'
@@ -221,6 +242,8 @@ class Config:
AUTH_LOCAL_JWT_AUDIENCE = os.getenv('AUTH_LOCAL_JWT_AUDIENCE')
AUTH_LOCAL_JWT_EXPIRES_HOURS = int(os.getenv('AUTH_LOCAL_JWT_EXPIRES_HOURS', '12'))
SCHEDULE_WORKER_ENABLED = os.getenv('SCHEDULE_WORKER_ENABLED', 'true').lower() == 'true'
# Cron 表达式按此时区解读(如 0 12 * * * 表示该时区 12:00);入库 next_run_at 仍为 UTC。
SCHEDULE_TIMEZONE = (os.getenv('SCHEDULE_TIMEZONE') or 'Asia/Shanghai').strip()
SRM_SQLSERVER_HOST = os.getenv('SRM_SQLSERVER_HOST', '')
SRM_SQLSERVER_PORT = os.getenv('SRM_SQLSERVER_PORT', '1433')
SRM_SQLSERVER_DATABASE = os.getenv('SRM_SQLSERVER_DATABASE', '')
@@ -237,6 +260,29 @@ class Config:
SMTP_FROM = os.getenv('SMTP_FROM', '')
SMTP_USE_TLS = os.getenv('SMTP_USE_TLS', 'true').lower() == 'true'
INTERNAL_API_BASE_URL = os.getenv('INTERNAL_API_BASE_URL', 'http://127.0.0.1:5052')
FIXED_ASSETS_SYNC_ENABLED = os.getenv('FIXED_ASSETS_SYNC_ENABLED', 'true').lower() == 'true'
FIXED_ASSETS_SYNC_TIMEZONE = (os.getenv('FIXED_ASSETS_SYNC_TIMEZONE') or 'Asia/Shanghai').strip()
FIXED_ASSETS_SYNC_HOUR = int(os.getenv('FIXED_ASSETS_SYNC_HOUR', '3') or '3')
FIXED_ASSETS_SYNC_MINUTE = int(os.getenv('FIXED_ASSETS_SYNC_MINUTE', '0') or '0')
FIXED_ASSETS_SYNC_TIMEOUT_SECONDS = int(os.getenv('FIXED_ASSETS_SYNC_TIMEOUT_SECONDS', '600') or '600')
FIXED_ASSETS_SYNC_RETRY_INTERVAL_MINUTES = int(
os.getenv('FIXED_ASSETS_SYNC_RETRY_INTERVAL_MINUTES', '30') or '30'
)
FIXED_ASSETS_SYNC_MAX_ATTEMPTS = int(os.getenv('FIXED_ASSETS_SYNC_MAX_ATTEMPTS', '4') or '4')
FIXED_ASSETS_SYNC_POLL_SECONDS = int(os.getenv('FIXED_ASSETS_SYNC_POLL_SECONDS', '60') or '60')
FIXED_ASSETS_SYNC_ON_BOOT_IF_MISSING = (
os.getenv('FIXED_ASSETS_SYNC_ON_BOOT_IF_MISSING', 'true').lower() == 'true'
)
FIXED_ASSETS_HISTORY_KEEP_COUNT = int(os.getenv('FIXED_ASSETS_HISTORY_KEEP_COUNT', '3') or '3')
FIXED_ASSETS_STORAGE_ROOT = _data_path('FIXED_ASSETS_STORAGE_ROOT', 'fixed_assets')
FIXED_ASSETS_DOCS_EXPORT_ROOT = os.getenv(
'FIXED_ASSETS_DOCS_EXPORT_ROOT',
str(_ROOT_DIR / 'docs'),
)
FIXED_ASSETS_EXPORT_TO_DOCS = os.getenv('FIXED_ASSETS_EXPORT_TO_DOCS', 'true').lower() == 'true'
FIXED_ASSETS_ERP_USERNAME = os.getenv('FIXED_ASSETS_ERP_USERNAME', 'EXT_VIEW_USER')
FIXED_ASSETS_ERP_PASSWORD = os.getenv('FIXED_ASSETS_ERP_PASSWORD', 'extviewuser')
FIXED_ASSETS_ERP_DSN = os.getenv('FIXED_ASSETS_ERP_DSN') or os.getenv('ERP_DB_DSN', '192.168.8.24:1521/topprod')
# MinIO 配置
MINIO_ENDPOINT = os.getenv('MINIO_ENDPOINT', '127.0.0.1:9000')
@@ -263,6 +309,8 @@ class TestingConfig(Config):
WTF_CSRF_ENABLED = False
SQLALCHEMY_ENGINE_OPTIONS = {}
SCHEDULE_WORKER_ENABLED = False
FIXED_ASSETS_SYNC_ENABLED = False
FIXED_ASSETS_EXPORT_TO_DOCS = False
config = {
+6
View File
@@ -0,0 +1,6 @@
"""
backend/app/core/__init__.py
用途:横切能力包入口(errors、response、auth、config、db)。
逻辑:Wave 1 逐步将 app 根目录模块迁入 core/ 子包;过渡期旧路径 re-export。
"""
+6
View File
@@ -0,0 +1,6 @@
"""
backend/app/core/auth/__init__.py
用途:认证与当前用户解析包入口。
逻辑:api 层通过 get_current_user 获取 User;Wave 1 自 auth_jwt.py 迁入 jwt.py。
"""
+39
View File
@@ -0,0 +1,39 @@
"""
backend/app/core/auth/context.py
用途:从 Flask g/request 解析请求上下文(request_id、user),供 api 层薄封装。
逻辑:Wave 3 拆分 user/chat 路由时,将重复 auth 逻辑收敛到本模块。
"""
from __future__ import annotations
from typing import Any
def get_request_id() -> str | None:
"""
读取当前请求的 X-Request-Id 或 g.request_id。
核心逻辑:延迟 import flask.g,避免 services 层依赖。
Returns:
request_id 字符串,无上下文时返回 None。
"""
try:
from flask import g
return getattr(g, 'request_id', None)
except RuntimeError:
return None
def get_optional_config(key: str, default: Any = None) -> Any:
"""
读取 Flask app.config 项(仅 api / jobs context 使用)。
Args:
key: config 键名。
default: 无 app context 时的默认值。
"""
try:
from flask import current_app
return current_app.config.get(key, default)
except RuntimeError:
return default
+9
View File
@@ -0,0 +1,9 @@
"""
backend/app/core/auth/jwt.py
用途:Casdoor JWT 校验与当前用户解析(Wave 1 自 app/auth_jwt.py 迁入)。
逻辑:api 路由与 decorators 调用 get_current_user()。
"""
from app.auth_jwt import get_current_user # noqa: F401
__all__ = ['get_current_user']
+6
View File
@@ -0,0 +1,6 @@
"""
backend/app/core/config/__init__.py
用途:应用配置包入口(settings、env_persistence)。
逻辑:create_app 加载 Config;before_request 刷新 DB 持久化配置。
"""
@@ -0,0 +1,9 @@
"""
backend/app/core/config/env_persistence.py
用途:DB 持久化运行时配置(Wave 1 自 app/env_persistence.py 迁入)。
逻辑:before_request 调用 apply_env_settings 刷新 app.config。
"""
from app.env_persistence import apply_env_settings # noqa: F401
__all__ = ['apply_env_settings']
+9
View File
@@ -0,0 +1,9 @@
"""
backend/app/core/config/settings.py
用途:Config 类与环境映射(Wave 1 自 app/config.py 迁入)。
逻辑:create_app(config_name) 通过 config[config_name] 加载。
"""
from app.config import ACTIVE_ENV_NAME, config # noqa: F401
__all__ = ['config', 'ACTIVE_ENV_NAME']
+6
View File
@@ -0,0 +1,6 @@
"""
backend/app/core/db/__init__.py
用途:数据库会话工具包入口。
逻辑:Wave 1 提供 run_with_retry;sequence 工具供迁移/运维脚本使用。
"""
+7
View File
@@ -0,0 +1,7 @@
"""
backend/app/core/db/sequence.py
用途:PostgreSQL 序列修复工具(Wave 1 自 services/db_sequence.py 迁入)。
逻辑:迁移脚本与 check_schema_drift 调用。
"""
from app.services.db_sequence import * # noqa: F403
+28
View File
@@ -0,0 +1,28 @@
"""
backend/app/core/db/session.py
用途:数据库会话辅助(重试、只读查询封装)。
逻辑:Wave 1 从 api/user.py、knowledge_base.py 等抽取 _run_db_with_retry 模式。
"""
from __future__ import annotations
from collections.abc import Callable
from typing import TypeVar
T = TypeVar('T')
def run_with_retry(fn: Callable[[], T], *, max_attempts: int = 3) -> T:
"""
在数据库短暂失败时重试可调用对象。
核心逻辑:捕获 OperationalError/DisconnectionError 后 rollback 并重试。
Args:
fn: 无参 callable,内部使用 db.session。
max_attempts: 最大尝试次数。
Returns:
fn 的返回值。
Raises:
最后一次失败的异常。
"""
# [STEP 1] Wave 0 占位:Wave 1 从 user.py / knowledge_base.py 抽取实现
return fn()
+9
View File
@@ -0,0 +1,9 @@
"""
backend/app/core/decorators.py
用途:路由权限装饰器(Wave 1 自 app/decorators.py 迁入)。
逻辑:api 层路由使用 @require_admin、@require_agent_permission。
"""
from app.decorators import require_admin, require_agent_permission # noqa: F401
__all__ = ['require_admin', 'require_agent_permission']
+26
View File
@@ -0,0 +1,26 @@
"""
backend/app/core/errors.py
用途:统一业务异常类型(Wave 1 自 app/errors.py 迁入)。
依赖:无 Flask 依赖。
逻辑:API 全局 handler 识别 AppError;业务层 raise 子类替代 jsonify(error)。
"""
from app.errors import ( # noqa: F401 — Wave 1: 实现迁入本文件后删除 app/errors.py shim
AppError,
ConflictError,
ForbiddenError,
NotFoundError,
ServiceUnavailableError,
UnauthorizedError,
ValidationError,
)
__all__ = [
'AppError',
'ValidationError',
'UnauthorizedError',
'ForbiddenError',
'NotFoundError',
'ConflictError',
'ServiceUnavailableError',
]
+9
View File
@@ -0,0 +1,9 @@
"""
backend/app/core/response.py
用途:统一 API 响应工具(Wave 1 自 app/response_utils.py 迁入)。
逻辑:error_payload 供全局异常 handler 使用;ok() 供成功 envelope(可选)。
"""
from app.response_utils import error_payload, ok, utc_iso_now # noqa: F401
__all__ = ['error_payload', 'ok', 'utc_iso_now']
+1
View File
@@ -42,6 +42,7 @@ WECOM_BOOL_KEYS = {
'WECOM_AUTO_CREATE_USER',
'WECOM_MOBILE_NORMALIZE',
'WECOM_NOTIFY_ENABLED',
'WECOM_FEEDBACK_NOTIFY_ENABLED',
}
+12
View File
@@ -0,0 +1,12 @@
"""
backend/app/extensions.py
用途:Flask 扩展实例(db、migrate)集中定义;Wave 1 从 __init__.py 迁入并接线。
依赖:flask_sqlalchemy、flask_migrate。
逻辑:create_app 调用 db.init_app(app);models 与各 service 从本模块 import db。
"""
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
db = SQLAlchemy()
migrate = Migrate()
+11
View File
@@ -0,0 +1,11 @@
"""
backend/app/jobs/__init__.py
用途:统一后台任务层入口(方案 D)。
依赖:types、registry、queue、runner。
逻辑:Web API enqueue;worker.py 调用 runner.run_forever。
"""
from app.jobs.types import JobStatus, JobType
from app.jobs.queue import enqueue
__all__ = ['JobType', 'JobStatus', 'enqueue']
+26
View File
@@ -0,0 +1,26 @@
"""
backend/app/jobs/context.py
用途:Worker 运行时上下文,注入 config / db / logger。
逻辑:handler.run(ctx, payload) 通过 ctx 访问依赖,禁止 import flask.request。
"""
from __future__ import annotations
import logging
from dataclasses import dataclass, field
from typing import Any
@dataclass
class JobContext:
"""
Worker 执行上下文。
Attributes:
config: Flask app.config 快照或类 dict。
logger: 模块 logger。
extras: 扩展字段(如 worker_label)。
"""
config: dict[str, Any]
logger: logging.Logger
extras: dict[str, Any] = field(default_factory=dict)
+8
View File
@@ -0,0 +1,8 @@
"""
backend/app/jobs/handlers/__init__.py
用途:导入各 handler 模块以触发 @register_handler 注册。
逻辑:Wave 2 起在 worker 启动前 import 本包。
"""
from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, schedule_run, shipping_notice_run, wecom_directory_sync # noqa: F401
@@ -0,0 +1,18 @@
"""
backend/app/jobs/handlers/file_check_run.py
用途:文件检核异步执行 handler。
逻辑:Wave 4 替代 api/file_check_tools 内 threading.Thread。
"""
from __future__ import annotations
from app.jobs.context import JobContext
from app.jobs.registry import register_handler
from app.jobs.types import JobType
@register_handler(JobType.FILE_CHECK_RUN)
def run_file_check(ctx: JobContext, payload: dict) -> None:
"""执行异步文件检核。"""
ctx.logger.info('file_check_run handler skeleton invoked payload=%s', payload)
raise NotImplementedError('file_check_run handler pending Wave 4')
+24
View File
@@ -0,0 +1,24 @@
"""
backend/app/jobs/handlers/kb_clean.py
用途:KB 文档清洗任务 handler。
逻辑:Wave 2 包装 knowledge_cleaning.queue_service.process_next_clean_job。
"""
from __future__ import annotations
from app.jobs.context import JobContext
from app.jobs.registry import register_handler
from app.jobs.types import JobType
@register_handler(JobType.KB_CLEAN)
def run_kb_clean(ctx: JobContext, payload: dict) -> None:
"""
执行单条 KB 清洗任务。
Args:
ctx: Worker 上下文。
payload: 含 document_id 等字段。
"""
ctx.logger.info('kb_clean handler skeleton invoked payload=%s', payload)
# Wave 2: from app.services.knowledge_cleaning.queue_service import process_job
raise NotImplementedError('kb_clean handler pending Wave 2')
+18
View File
@@ -0,0 +1,18 @@
"""
backend/app/jobs/handlers/kb_dify_sync.py
用途:KB 文档同步至 Dify 任务 handler。
逻辑:Wave 2 包装 knowledge_cleaning.dify_sync_service。
"""
from __future__ import annotations
from app.jobs.context import JobContext
from app.jobs.registry import register_handler
from app.jobs.types import JobType
@register_handler(JobType.KB_DIFY_SYNC)
def run_kb_dify_sync(ctx: JobContext, payload: dict) -> None:
"""同步已清洗文档到 Dify。"""
ctx.logger.info('kb_dify_sync handler skeleton invoked payload=%s', payload)
raise NotImplementedError('kb_dify_sync handler pending Wave 2')
+18
View File
@@ -0,0 +1,18 @@
"""
backend/app/jobs/handlers/schedule_run.py
用途:排程任务执行 handler。
逻辑:Wave 4 从 scheduler_service in-process 执行体迁入。
"""
from __future__ import annotations
from app.jobs.context import JobContext
from app.jobs.registry import register_handler
from app.jobs.types import JobType
@register_handler(JobType.SCHEDULE_RUN)
def run_schedule(ctx: JobContext, payload: dict) -> None:
"""执行单条 ScheduleTask。"""
ctx.logger.info('schedule_run handler skeleton invoked payload=%s', payload)
raise NotImplementedError('schedule_run handler pending Wave 4')
@@ -0,0 +1,19 @@
"""
backend/app/jobs/handlers/shipping_notice_run.py
用途:货代发货单票后台任务 handler。
依赖:jobs.context、jobs.registry、shipping_notice.queue_service。
逻辑:统一由 worker 消费 `shipping_notice_run` 队列任务,再委托 shipping_notice.queue_service 执行单票。
"""
from __future__ import annotations
from app.jobs.context import JobContext
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.services.shipping_notice.queue_service import run_shipping_notice_job
@register_handler(JobType.SHIPPING_NOTICE_RUN)
def run_shipping_notice(ctx: JobContext, payload: dict) -> None:
"""消费单票发货后台任务。"""
run_shipping_notice_job(payload, logger=ctx.logger)
@@ -0,0 +1,18 @@
"""
backend/app/jobs/handlers/wecom_directory_sync.py
用途:企微通讯录同步 handler。
逻辑:Wave 4 包装 wecom_directory_sync 服务。
"""
from __future__ import annotations
from app.jobs.context import JobContext
from app.jobs.registry import register_handler
from app.jobs.types import JobType
@register_handler(JobType.WECOM_DIRECTORY_SYNC)
def run_wecom_directory_sync(ctx: JobContext, payload: dict) -> None:
"""同步企微通讯录到本地用户/部门。"""
ctx.logger.info('wecom_directory_sync handler skeleton invoked payload=%s', payload)
raise NotImplementedError('wecom_directory_sync handler pending Wave 4')
+34
View File
@@ -0,0 +1,34 @@
"""
backend/app/jobs/queue.py
用途:任务入队 API。
逻辑:API / services 调用 enqueue;Wave 2 写入 Job 表并 adapter KbJob。
"""
from __future__ import annotations
from typing import Any
from app.jobs.types import JobType
def enqueue(
job_type: JobType,
payload: dict[str, Any],
*,
correlation_id: str | None = None,
scheduled_at: Any = None,
) -> int:
"""
将任务写入队列并返回 job id。
核心逻辑:Wave 2 实现 store.create + KbJob adapter。
Args:
job_type: 任务类型。
payload: 任务参数 JSON。
correlation_id: 关联业务 id(如 kb_document_id)。
scheduled_at: 延迟执行时间(可选)。
Returns:
Job 主键。
Raises:
NotImplementedError: Wave 0 占位。
"""
raise NotImplementedError('jobs.enqueue is not wired until Wave 2')
+37
View File
@@ -0,0 +1,37 @@
"""
backend/app/jobs/registry.py
用途:JobType → Handler 注册表。
逻辑:handlers 模块 import 时 @register_handler 装饰;runner 按 type 分发。
"""
from __future__ import annotations
from collections.abc import Callable
from typing import Any
from app.jobs.types import JobType
HandlerFn = Callable[[Any, dict], None]
_REGISTRY: dict[JobType, HandlerFn] = {}
def register_handler(job_type: JobType) -> Callable[[HandlerFn], HandlerFn]:
"""
注册某 JobType 的处理函数。
Args:
job_type: 任务类型枚举。
Returns:
装饰器。
"""
def decorator(fn: HandlerFn) -> HandlerFn:
_REGISTRY[job_type] = fn
return fn
return decorator
def get_handler(job_type: JobType) -> HandlerFn | None:
"""按类型获取 handler;未注册返回 None。"""
return _REGISTRY.get(job_type)
+38
View File
@@ -0,0 +1,38 @@
"""
backend/app/jobs/runner.py
用途:Worker 主循环 poll → dispatch → ack/fail。
逻辑:worker.py 调用 run_forever(ctx);Wave 2 接入 store 与 registry。
"""
from __future__ import annotations
import time
from app.jobs.context import JobContext
from app.jobs.registry import get_handler
from app.jobs import store
def run_forever(ctx: JobContext, *, poll_interval_seconds: float = 2.0) -> None:
"""
持续轮询并执行任务。
核心逻辑:claim_next → get_handler → handler(ctx, payload) → 更新状态。
Args:
ctx: Worker 上下文。
poll_interval_seconds: 无任务时的休眠秒数。
"""
ctx.logger.info('Job runner started (skeleton mode — Wave 2 will enable claim loop)')
while True:
try:
job = store.claim_next()
except NotImplementedError:
time.sleep(poll_interval_seconds)
continue
if not job:
time.sleep(poll_interval_seconds)
continue
handler = get_handler(job['job_type'])
if not handler:
ctx.logger.error('No handler for job_type=%s', job.get('job_type'))
continue
handler(ctx, job.get('payload') or {})
+20
View File
@@ -0,0 +1,20 @@
"""
backend/app/jobs/store.py
用途:Job 表 CRUD(claim、update status)。
逻辑:runner 通过 claim_next 获取待执行任务;Wave 2 落地 SQLAlchemy 模型。
"""
from __future__ import annotations
from typing import Any
def claim_next() -> dict[str, Any] | None:
"""
认领下一条待执行 Job(SELECT FOR UPDATE SKIP LOCKED)。
Returns:
job 字典或 None。
Raises:
NotImplementedError: Wave 0 占位。
"""
raise NotImplementedError('jobs.store.claim_next is not wired until Wave 2')
+30
View File
@@ -0,0 +1,30 @@
"""
backend/app/jobs/types.py
用途:Job 类型与状态枚举。
逻辑:handlers 与 queue 通过 JobType 注册;store 持久化 status 字符串。
"""
from __future__ import annotations
from enum import StrEnum
class JobType(StrEnum):
"""后台任务类型。"""
KB_CLEAN = 'kb_clean'
KB_DIFY_SYNC = 'kb_dify_sync'
SHIPPING_NOTICE_RUN = 'shipping_notice_run'
SCHEDULE_RUN = 'schedule_run'
FILE_CHECK_RUN = 'file_check_run'
WECOM_DIRECTORY_SYNC = 'wecom_directory_sync'
class JobStatus(StrEnum):
"""Job 生命周期状态。"""
PENDING = 'pending'
RUNNING = 'running'
SUCCEEDED = 'succeeded'
FAILED = 'failed'
DEAD = 'dead'
+107 -1
View File
@@ -214,6 +214,7 @@ class ChatLog(Base):
latency: Mapped[int] = mapped_column(default=0)
conversation_id: Mapped[Optional[str]] = mapped_column(String(100))
session_id: Mapped[Optional[str]] = mapped_column(String(100), index=True, nullable=True)
run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_runs.id'), index=True, nullable=True)
message_type: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
payload: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
tokens_used: Mapped[int] = mapped_column(default=0)
@@ -275,7 +276,7 @@ class PermissionRequest(Base):
class QuickQuestion(Base):
"""
常用问题表
用途:存储用户自定义的常用问题
用途:存储全局/用户常用问题;全局条目(user_id 为空)可配置标准答案并启用 FAQ 缓存命中。
"""
__tablename__ = 'quick_questions'
@@ -284,8 +285,54 @@ class QuickQuestion(Base):
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
title: Mapped[str] = mapped_column(String(100))
question: Mapped[str] = mapped_column(Text)
answer: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
aliases: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
cache_enabled: Mapped[bool] = mapped_column(default=False)
is_enabled: Mapped[bool] = mapped_column(default=True)
hit_count: Mapped[int] = mapped_column(default=0)
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
source_kb_document_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
stale_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
stale_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
stale_kb_document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id'), nullable=True)
sort_order: Mapped[int] = mapped_column(default=0)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
class FaqHotCandidate(Base):
"""
热点 FAQ 候选表
用途:离线聚合 ChatLog 后的待审核热点问句与推荐答案(PostgreSQL 存储,不含在线命中)。
"""
__tablename__ = 'faq_hot_candidates'
__table_args__ = (
UniqueConstraint('agent_id', 'q_norm', name='uq_faq_hot_candidates_agent_qnorm'),
Index('ix_faq_hot_candidates_status_expires', 'status', 'expires_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), index=True)
q_norm: Mapped[str] = mapped_column(String(255))
canonical_query: Mapped[str] = mapped_column(Text)
answer: Mapped[str] = mapped_column(Text)
source_chat_log_id: Mapped[Optional[int]] = mapped_column(ForeignKey('chat_logs.id'), nullable=True)
ask_count_7d: Mapped[int] = mapped_column(default=0)
user_count_7d: Mapped[int] = mapped_column(default=0)
avg_tokens: Mapped[int] = mapped_column(default=0)
avg_latency_ms: Mapped[int] = mapped_column(default=0)
answer_dominance: Mapped[float] = mapped_column(default=0.0)
sample_queries: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
last_asked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
status: Mapped[str] = mapped_column(String(20), default='candidate') # candidate | promoted | dismissed
promoted_quick_question_id: Mapped[Optional[int]] = mapped_column(ForeignKey('quick_questions.id'), nullable=True)
deny_until: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
class Announcement(Base):
"""
@@ -581,6 +628,7 @@ class ScheduleTask(Base):
schedule_type: Mapped[str] = mapped_column(String(32), default='platform_app')
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True)
cron_expr: Mapped[str] = mapped_column(String(64))
schedule_timezone: Mapped[str] = mapped_column(String(64), default='Asia/Shanghai', server_default=text("'Asia/Shanghai'"))
wait_seconds: Mapped[int] = mapped_column(Integer, default=0)
dify_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True, index=True)
platform_api_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
@@ -693,19 +741,59 @@ class ScheduleRun(Base):
kb_sync_job: Mapped[Optional["KbJob"]] = relationship("KbJob", foreign_keys=[kb_sync_job_id])
class ShippingBatch(Base):
"""货代发货通知批次(一次多文件上传的聚合容器)"""
__tablename__ = 'shipping_batches'
__table_args__ = (
Index('ix_shipping_batches_user_created', 'user_id', 'created_at'),
Index('ix_shipping_batches_conversation', 'conversation_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
batch_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
current_focus_task_no: Mapped[Optional[str]] = mapped_column(
String(64),
ForeignKey(
'shipping_tasks.task_no',
name='fk_shipping_batches_current_focus_task_no_shipping_tasks',
use_alter=True,
),
nullable=True,
)
file_count: Mapped[int] = mapped_column(Integer, default=1)
process_summary_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
tasks: Mapped[List["ShippingTask"]] = relationship(
"ShippingTask",
back_populates="batch",
foreign_keys="ShippingTask.batch_id",
)
class ShippingTask(Base):
"""货代发货通知 task(Chatflow Tool 编排状态机)"""
__tablename__ = 'shipping_tasks'
__table_args__ = (
Index('ix_shipping_tasks_user_status', 'user_id', 'process_status'),
Index('ix_shipping_tasks_conversation', 'conversation_id'),
Index('ix_shipping_tasks_batch_step', 'batch_id', 'current_step'),
Index('ix_shipping_tasks_upload_status', 'upload_status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), index=True, nullable=True)
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
source_type: Mapped[str] = mapped_column(String(32), default='manual')
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
source_file_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
batch_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
batch_total: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
raw_content: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
customer_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
@@ -717,6 +805,7 @@ class ShippingTask(Base):
parse_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
process_status: Mapped[str] = mapped_column(String(32), default='created', index=True)
current_step: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
review_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
match_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
shortage_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
@@ -726,13 +815,29 @@ class ShippingTask(Base):
export_file_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
export_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
export_version: Mapped[int] = mapped_column(Integer, default=1)
freight_ref_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
upload_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
upload_mode: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
upload_attempt: Mapped[int] = mapped_column(Integer, default=0)
idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
upload_started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
upload_finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
upload_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
upload_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
upload_receipt_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
step_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
pending_human_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
batch: Mapped[Optional["ShippingBatch"]] = relationship(
"ShippingBatch",
back_populates="tasks",
foreign_keys=[batch_id],
)
events: Mapped[List["ShippingTaskEvent"]] = relationship(
"ShippingTaskEvent",
back_populates="task",
@@ -754,6 +859,7 @@ class ShippingTaskEvent(Base):
class ShippingInventoryMapping(Base):
"""客户库存 Excel 表头 → 标准字段的列映射缓存(按 customer_code + header_hash 去重)。"""
__tablename__ = 'shipping_inventory_mappings'
__table_args__ = (
UniqueConstraint('customer_code', 'header_hash', name='uq_shipping_inventory_mappings_customer_header'),
+6
View File
@@ -0,0 +1,6 @@
"""
backend/app/schemas/__init__.py
用途:请求/响应 DTO 包(dataclass 或 Pydantic,非 FastAPI 专用)。
逻辑:api 层解析入参、校验后传入 services;Wave 3 随 admin/user/kb 拆分落地。
"""
+5
View File
@@ -0,0 +1,5 @@
"""
backend/app/schemas/admin/__init__.py
用途:管理后台 DTO 包入口。
"""
+5
View File
@@ -0,0 +1,5 @@
"""
backend/app/schemas/admin/agents.py
用途:Agent 管理 API DTO。
"""
+5
View File
@@ -0,0 +1,5 @@
"""
backend/app/schemas/admin/settings.py
用途:系统设置 API DTO。
"""
+6
View File
@@ -0,0 +1,6 @@
"""
backend/app/schemas/admin/users.py
用途:用户管理 API DTO。
逻辑:Wave 3 admin/users 路由使用。
"""
+6
View File
@@ -0,0 +1,6 @@
"""
backend/app/schemas/chat.py
用途:聊天域 API 请求/响应 DTO。
逻辑:Wave 3 从 api/chat/_legacy 抽取 completions、sessions 参数模型。
"""
+6
View File
@@ -0,0 +1,6 @@
"""
backend/app/schemas/kb.py
用途:知识库域 API 请求/响应 DTO。
逻辑:Wave 3 从 api/kb 拆分 upload、sync 参数模型。
"""
+5
View File
@@ -0,0 +1,5 @@
"""
backend/app/schemas/user/__init__.py
用途:当前用户域 API DTO(profile、homepage、faq)。
"""
+6
View File
@@ -0,0 +1,6 @@
"""
backend/app/services/admin/__init__.py
用途:管理后台业务服务包。
逻辑:Wave 3 从 api/admin/_legacy 抽取 users/agents/departments/settings 等。
"""
@@ -0,0 +1,5 @@
"""
backend/app/services/admin/agent_service.py
用途:Agent CRUD、权限、guide 配置。
"""
@@ -0,0 +1,5 @@
"""
backend/app/services/admin/dashboard_service.py
用途:管理后台仪表盘统计聚合。
"""
@@ -0,0 +1,5 @@
"""
backend/app/services/admin/department_service.py
用途:部门 CRUD。
"""
@@ -0,0 +1,5 @@
"""
backend/app/services/admin/permission_service.py
用途:权限申请、批量授权业务逻辑。
"""
@@ -0,0 +1,5 @@
"""
backend/app/services/admin/settings_service.py
用途:AppSetting、运行时配置管理业务逻辑。
"""
@@ -0,0 +1,5 @@
"""
backend/app/services/admin/user_service.py
用途:管理端用户 CRUD、权限分配。
"""
+6
View File
@@ -0,0 +1,6 @@
"""
backend/app/services/auth/__init__.py
用途:认证域业务(Casdoor OIDC、企微 OAuth)。
逻辑:Wave 3 从 api/user/_legacy auth 相关路由抽取。
"""
@@ -0,0 +1,5 @@
"""
backend/app/services/auth/casdoor_service.py
用途:Casdoor OIDC 登录、token 交换、用户同步业务逻辑。
"""
@@ -0,0 +1,5 @@
"""
backend/app/services/auth/wecom_auth_service.py
用途:企业微信 OAuth、绑定、解绑业务逻辑。
"""
+6
View File
@@ -0,0 +1,6 @@
"""
backend/app/services/chat/__init__.py
用途:聊天域业务服务包。
逻辑:Wave 3 从 api/chat/_legacy 与 chat.py 意图路由抽取。
"""
+5
View File
@@ -0,0 +1,5 @@
"""
backend/app/services/chat/log_service.py
用途:聊天历史、反馈业务逻辑。
"""
+6
View File
@@ -0,0 +1,6 @@
"""
backend/app/services/chat/perf.py
用途:聊天性能埋点(Wave 3 自 services/chat_perf.py 迁入)。
"""
from app.services.chat_perf import * # noqa: F403
@@ -0,0 +1,6 @@
"""
backend/app/services/chat/preview_service.py
用途:PLM/Excel 预览与文件转换(从 api/chat 抽出)。
逻辑:Wave 3 将 subprocess/openpyxl 逻辑迁入本模块。
"""
+27
View File
@@ -0,0 +1,27 @@
"""
backend/app/services/chat/router.py
用途:Chat Intent Router,按意图分流至 PLM/HR/Text2SQL/Dify。
依赖:integrations/* stream_chat 实现。
逻辑:api/chat/completions 调用本模块 select_stream_generator。
设计参考:docs/tec.md §4.1 Chat Intent Router。
"""
from __future__ import annotations
from typing import Any, Iterator
def select_stream_generator(*, user: Any, agent: Any, query: str, **kwargs: Any) -> Iterator[str]:
"""
根据 agent 配置与用户问题选择流式 generator。
核心逻辑:Wave 3 从 api/chat.py /completions 分支迁入。
Args:
user: 当前 User 模型实例。
agent: 当前 Agent 模型实例。
query: 用户问题文本。
Returns:
SSE 事件字符串迭代器。
Raises:
NotImplementedError: Wave 0 占位。
"""
raise NotImplementedError('ChatIntentRouter pending Wave 3 migration from api/chat.py')
@@ -0,0 +1,6 @@
"""
backend/app/services/chat/session_service.py
用途:聊天会话 CRUD 业务逻辑。
逻辑:Wave 3 从 api/chat/_legacy 抽取 sessions 相关路由逻辑。
"""
+128
View File
@@ -0,0 +1,128 @@
"""
backend/app/services/chat_perf.py
文件用途:对话流式链路各节点耗时采集与结构化日志输出。
"""
from __future__ import annotations
import os
import time
from typing import Any
def chat_perf_enabled() -> bool:
return str(os.getenv("CHAT_PERF_LOG", "0")).strip().lower() in ("1", "true", "yes", "on")
class ChatPerfTracker:
"""Collect Dify Chatflow / Chat SSE node timings for one request."""
def __init__(self, *, request_id: str | None, agent_id: int | None = None) -> None:
self.request_id = str(request_id or "").strip() or None
self.agent_id = agent_id
self.started_at = time.perf_counter()
self.workflow_run_id: str | None = None
self.first_event_at: float | None = None
self.first_token_at: float | None = None
self.nodes: list[dict[str, Any]] = []
self.workflow_elapsed_ms: int | None = None
self.workflow_status: str | None = None
self.total_tokens: int | None = None
def _since_start_ms(self, at: float | None = None) -> int:
return int(((at or time.perf_counter()) - self.started_at) * 1000)
def on_event(self, event: str | None, data: dict[str, Any]) -> None:
if not chat_perf_enabled():
return
now = time.perf_counter()
if self.first_event_at is None:
self.first_event_at = now
event_name = str(event or "").strip()
if event_name == "workflow_started":
payload = data.get("data") if isinstance(data.get("data"), dict) else {}
self.workflow_run_id = str(payload.get("workflow_run_id") or data.get("workflow_run_id") or "").strip() or None
return
if event_name == "node_finished":
payload = data.get("data") if isinstance(data.get("data"), dict) else {}
elapsed_raw = payload.get("elapsed_time")
try:
elapsed_ms = int(float(elapsed_raw or 0) * 1000)
except (TypeError, ValueError):
elapsed_ms = 0
self.nodes.append({
"index": payload.get("index"),
"title": str(payload.get("title") or payload.get("node_id") or "").strip() or "unknown",
"node_type": str(payload.get("node_type") or "").strip() or None,
"node_id": str(payload.get("node_id") or "").strip() or None,
"status": str(payload.get("status") or "").strip() or None,
"elapsed_ms": elapsed_ms,
"at_ms": self._since_start_ms(now),
})
return
if event_name == "message" and data.get("answer"):
if self.first_token_at is None:
self.first_token_at = now
return
if event_name in ("message_end", "workflow_finished"):
payload = data.get("data") if isinstance(data.get("data"), dict) else {}
metadata = data.get("metadata") if isinstance(data.get("metadata"), dict) else {}
usage = metadata.get("usage") if isinstance(metadata.get("usage"), dict) else {}
elapsed_raw = payload.get("elapsed_time")
if elapsed_raw is None:
elapsed_raw = usage.get("latency")
try:
self.workflow_elapsed_ms = int(float(elapsed_raw or 0) * 1000)
except (TypeError, ValueError):
self.workflow_elapsed_ms = None
self.workflow_status = str(payload.get("status") or "").strip() or None
try:
self.total_tokens = int(payload.get("total_tokens") or usage.get("total_tokens") or 0) or None
except (TypeError, ValueError):
self.total_tokens = None
def build_summary(self) -> dict[str, Any]:
total_ms = self._since_start_ms()
return {
"request_id": self.request_id,
"agent_id": self.agent_id,
"workflow_run_id": self.workflow_run_id,
"total_ms": total_ms,
"ttft_ms": self._since_start_ms(self.first_token_at) if self.first_token_at else None,
"first_event_ms": self._since_start_ms(self.first_event_at) if self.first_event_at else None,
"workflow_elapsed_ms": self.workflow_elapsed_ms,
"workflow_status": self.workflow_status,
"total_tokens": self.total_tokens,
"nodes": self.nodes,
"node_total_ms": sum(int(n.get("elapsed_ms") or 0) for n in self.nodes),
}
def log_summary(self, logger: Any, *, phase: str = "stream_end") -> dict[str, Any]:
summary = self.build_summary()
if not chat_perf_enabled():
return summary
lines = [
f"[chat-perf] {phase} request_id={summary['request_id']} agent_id={summary['agent_id']} "
f"total_ms={summary['total_ms']} ttft_ms={summary['ttft_ms']} "
f"workflow_elapsed_ms={summary['workflow_elapsed_ms']} nodes={len(summary['nodes'])}"
]
for node in summary["nodes"]:
lines.append(
"[chat-perf] node "
f"request_id={summary['request_id']} "
f"index={node.get('index')} "
f"title={node.get('title')} "
f"type={node.get('node_type')} "
f"elapsed_ms={node.get('elapsed_ms')} "
f"at_ms={node.get('at_ms')} "
f"status={node.get('status')}"
)
if logger:
for line in lines:
logger.info(line)
return summary
+381 -58
View File
@@ -8,6 +8,7 @@ It is responsible for:
1) Forwarding chat requests from this system to Dify in streaming mode.
2) Relaying Dify SSE events to the frontend.
3) Aggregating answer text and metadata (retriever resources / attribution).
Chatflow 模式下来源在 knowledge-retrieval 的 node_finished.outputs.result。
4) Enriching retriever resources with original source-file download URLs via
the integration API mapping (dataset_id + remote_document_id).
5) Persisting chat logs to the local database.
@@ -27,7 +28,7 @@ import os
import time
import uuid
from datetime import datetime, timedelta
from threading import Lock
from threading import Lock, Thread
from typing import Any, List, Optional
import requests
@@ -35,6 +36,7 @@ from flask import current_app
from app.config import Config
from app.models import ChatLog, db
from app.services.chat_perf import ChatPerfTracker, chat_perf_enabled
from app.services.integration_api import IntegrationApiService
@@ -507,6 +509,7 @@ class DifyService:
conversation_id: str = None,
request_id: str | None = None,
session_id: str | None = None,
hxops_turn_id: str | None = None,
files: list[dict[str, Any]] | None = None,
inputs: dict[str, Any] | None = None,
):
@@ -561,84 +564,130 @@ class DifyService:
)
start_time = time.time()
perf = ChatPerfTracker(request_id=request_id, agent_id=getattr(agent, "id", None))
first_token_at: float | None = None
message_count = 0
event_count = 0
full_answer: List[str] = []
retriever_resources: List[Any] = []
attribution_parts: List[str] = []
chat_logged = False
chat_persist_started = False
has_sent_answer = False
chat_log_id_persisted: int | None = None
run_id_persisted: int | None = None
def _resolve_persist_run_id() -> int | None:
try:
from app.services.file_check_tools.agent_resolver import is_file_check_chat_agent
from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
if not is_file_check_chat_agent(agent):
return None
return resolve_run_id_for_chat_log(
session_id=session_id,
query=query,
turn_id=hxops_turn_id,
)
except Exception:
return None
def persist_stream_chat(data: dict, event_name: str) -> None:
nonlocal chat_logged
if chat_logged:
return
result = persist_stream_chat_async(data, event_name)
if isinstance(result, dict):
if result.get("chat_log_id") is not None:
data["chat_log_id"] = result["chat_log_id"]
if result.get("run_id") is not None:
data["run_id"] = result["run_id"]
if data.get('answer'):
full_answer.append(data.get('answer', ''))
def persist_stream_chat_async(data: dict, event_name: str) -> dict | None:
nonlocal chat_persist_started, chat_log_id_persisted, run_id_persisted
if chat_persist_started and event_name == "workflow_finished" and chat_log_id_persisted:
# [STEP 1] message_end 可能已落库但 tokens=0;workflow_finished 携带 data.total_tokens 时回写
wf_tokens = DifyService._extract_token_usage(data)
app_obj = current_app._get_current_object() if current_app else None
if app_obj and wf_tokens > 0:
with app_obj.app_context():
DifyService._update_chat_log_tokens(chat_log_id_persisted, wf_tokens)
run_id = _resolve_persist_run_id()
if run_id and run_id != run_id_persisted:
from app.services.file_check_tools.chat_log_run_binding import update_chat_log_run_id
if update_chat_log_run_id(chat_log_id_persisted, run_id):
run_id_persisted = run_id
return {"chat_log_id": chat_log_id_persisted, "run_id": run_id_persisted}
if chat_persist_started:
return {"chat_log_id": chat_log_id_persisted, "run_id": run_id_persisted} if chat_log_id_persisted else None
chat_persist_started = True
app_obj = current_app._get_current_object() if current_app else None
persist_data = json.loads(json.dumps(data, ensure_ascii=False, default=str))
# 优先使用已 enrich 并挂到 event 上的 retriever_resources(与 SSE 下发一致)
resources_for_persist = data.get('retriever_resources') or retriever_resources
resources_snapshot = json.loads(json.dumps(resources_for_persist, ensure_ascii=False, default=str))
attribution_snapshot = list(attribution_parts)
answer_snapshot = build_final_answer_text(persist_data, event_name)
latency_snapshot = int((time.time() - start_time) * 1000)
message_payload = persist_data.get('message_payload')
if not app_obj:
return None
with app_obj.app_context():
result = DifyService._persist_stream_chat_record(
data=persist_data,
event_name=event_name,
request_id=request_id,
user_id=user_id,
agent=agent,
session_id=session_id,
hxops_turn_id=hxops_turn_id,
normalized_conversation_id=normalized_conversation_id,
query=query,
answer_text=answer_snapshot,
latency=latency_snapshot,
retriever_resources=resources_snapshot,
attribution_parts=attribution_snapshot,
message_payload=message_payload if isinstance(message_payload, dict) else None,
)
if isinstance(result, dict):
if result.get("chat_log_id"):
chat_log_id_persisted = int(result["chat_log_id"])
if result.get("run_id"):
run_id_persisted = int(result["run_id"])
return result
def build_final_answer_text(data: dict, event_name: str) -> str:
answer_text = ''.join(full_answer).strip()
if data.get('answer'):
answer_text = (answer_text + str(data.get('answer') or '')).strip()
if not answer_text and event_name == 'workflow_finished':
wf_data = data.get('data') or {}
outputs = wf_data.get('outputs') if isinstance(wf_data, dict) else None
if isinstance(outputs, dict):
for key in ('answer', 'text', 'result'):
for key in ('answer', 'final_answer', 'output', 'text', 'result', 'message'):
value = outputs.get(key)
if isinstance(value, str) and value.strip():
answer_text = value.strip()
break
if not answer_text:
for value in outputs.values():
if isinstance(value, str) and value.strip():
answer_text = value.strip()
break
return answer_text
if not answer_text and not str(query or '').strip():
return
if current_app:
current_app.logger.info(
"[source-link] persist chat request_id=%s event=%s collected retriever_resources=%s",
request_id,
event_name,
len(retriever_resources),
)
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
metadata = data.get('metadata') or {}
metadata['retriever_resources'] = retriever_resources
data['metadata'] = metadata
data['retriever_resources'] = retriever_resources
latency = int((time.time() - start_time) * 1000)
usage = metadata.get('usage', {}) or {}
db_write_started = time.time()
with current_app.app_context():
chat_log_id = DifyService._log_chat(
user_id=user_id,
agent_id=agent.id,
session_id=session_id,
conversation_id=data.get('conversation_id') or normalized_conversation_id,
query=query,
answer=answer_text,
tokens=usage.get('total_tokens', 0),
latency=latency,
retriever_resources=retriever_resources,
attribution_parts=attribution_parts,
)
if chat_log_id:
data['chat_log_id'] = chat_log_id
chat_logged = True
if current_app:
current_app.logger.info(
"[chat-perf] persisted request_id=%s event=%s total_ms=%s db_write_ms=%s answer_len=%s conversation_id=%s",
request_id,
event_name,
latency,
int((time.time() - db_write_started) * 1000),
len(answer_text),
data.get('conversation_id') or normalized_conversation_id,
)
max_retries = 3
for attempt in range(1, max_retries + 1):
try:
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 300)) as response:
connect_timeout = max(1, int(getattr(Config, "DIFY_CHAT_CONNECT_TIMEOUT_SECONDS", 5) or 5))
read_timeout = max(5, int(getattr(Config, "DIFY_CHAT_READ_TIMEOUT_SECONDS", 30) or 30))
if attempt == 1:
yield f"data: {json.dumps({'event': 'upstream_start', 'message': '正在连接 Dify'}, ensure_ascii=False)}\n\n"
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(connect_timeout, read_timeout)) as response:
if current_app:
current_app.logger.info(
"[chat-stream] dify response request_id=%s status=%s reason=%s attempt=%s",
@@ -665,6 +714,7 @@ class DifyService:
time.sleep(attempt * 2)
continue
response.raise_for_status()
yield f"data: {json.dumps({'event': 'upstream_connected', 'message': 'Dify 已连接'}, ensure_ascii=False)}\n\n"
for line in response.iter_lines():
if not line:
@@ -682,6 +732,7 @@ class DifyService:
event = data.get('event')
event_count += 1
perf.on_event(event, data)
# Keep stream event logs behind an explicit switch to prevent
# flooding when global logger level is DEBUG.
if DifyService.VERBOSE_STREAM_LOG and current_app:
@@ -694,8 +745,14 @@ class DifyService:
data.get('conversation_id') or normalized_conversation_id,
)
if event == 'message':
if event == 'node_finished':
# [STEP] Chatflow 知识检索结果在 node_finished.outputs.result,不在 message_end
DifyService._collect_knowledge_retrieval_from_node(retriever_resources, data)
elif event == 'message':
message_count += 1
if data.get('answer'):
has_sent_answer = True
if first_token_at is None:
first_token_at = time.time()
if current_app:
@@ -709,20 +766,70 @@ class DifyService:
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
elif event in ('message_end', 'agent_message', 'workflow_finished'):
if event in ('message_end', 'workflow_finished') or data.get('answer'):
has_sent_answer = True
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
if event == 'workflow_finished' and not data.get('answer'):
final_answer = build_final_answer_text(data, event)
if final_answer:
data['answer'] = final_answer
data['replace_answer'] = True
if event in ('message_end', 'workflow_finished'):
DifyService._attach_retriever_resources_to_event(data, retriever_resources)
persist_stream_chat(data, event)
if chat_perf_enabled():
perf_summary = perf.log_summary(current_app.logger if current_app else None)
yield f"data: {json.dumps({'event': 'chat_perf', 'perf': perf_summary}, ensure_ascii=False)}\n\n"
yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
if event in ('message_end', 'workflow_finished'):
break
break
except requests.exceptions.RequestException as e:
if current_app:
current_app.logger.exception("[chat-stream] request exception request_id=%s attempt=%s: %s", request_id, attempt, e)
if attempt < max_retries:
is_timeout = isinstance(e, (requests.exceptions.ReadTimeout, requests.exceptions.ConnectTimeout))
if isinstance(e, requests.exceptions.ReadTimeout) and has_sent_answer:
if current_app:
current_app.logger.warning(
"[chat-stream] read timeout after answer request_id=%s attempt=%s; finish stream silently",
request_id,
attempt,
)
persist_stream_chat(
{
'event': 'message_end',
'conversation_id': normalized_conversation_id,
'answer': ''.join(full_answer).strip(),
'metadata': {},
},
'message_end',
)
break
if not is_timeout and attempt < max_retries:
time.sleep(attempt * 2)
continue
error_msg = json.dumps({'event': 'error', 'message': str(e)})
if isinstance(e, requests.exceptions.ReadTimeout):
message = (
f"Dify 在 {int(getattr(Config, 'DIFY_CHAT_READ_TIMEOUT_SECONDS', 30) or 30)} 秒内没有返回响应。"
"请检查 Dify 应用地址/API Key、Chatflow 是否发布,以及 Dify 服务是否能正常执行。"
)
elif isinstance(e, requests.exceptions.ConnectTimeout):
message = "连接 Dify 超时,请检查 Dify API Base URL 和网络连通性。"
else:
message = str(e)
persist_stream_chat(
{
'event': 'error',
'conversation_id': normalized_conversation_id,
'answer': f"[Error: {message}]",
'metadata': {},
},
'error',
)
error_msg = json.dumps({'event': 'error', 'message': message})
yield f"data: {error_msg}\n\n"
@staticmethod
@@ -737,6 +844,8 @@ class DifyService:
latency,
retriever_resources=None,
attribution_parts=None,
payload=None,
run_id: int | None = None,
) -> Optional[int]:
"""
把最终问答和元数据写入 ChatLog
@@ -750,6 +859,7 @@ class DifyService:
latency: End-to-end latency in milliseconds.
retriever_resources: Source retrieval metadata list.
attribution_parts: Attribution/annotation list.
run_id: 文件检核批次 ID(按轮问答绑定,可选)。
"""
try:
chat_log = ChatLog(
@@ -763,6 +873,8 @@ class DifyService:
latency=latency or 0,
retriever_resources=retriever_resources or [],
attribution_parts=attribution_parts or [],
payload=payload if isinstance(payload, dict) else None,
run_id=run_id if run_id and run_id > 0 else None,
)
db.session.add(chat_log)
db.session.commit()
@@ -775,6 +887,146 @@ class DifyService:
return None
@staticmethod
def _extract_token_usage(data: dict) -> int:
"""
从 Dify SSE 事件 payload 提取 token 用量(best effort)。
核心逻辑:Chatbot 在 metadata.usage.total_tokens;Chatflow/Workflow 在 data.total_tokens
或 data.execution_metadata.total_tokens(与 chat_perf.ChatPerfTracker 对齐)。
@param data - 单条 SSE 解析后的 dict
@returns 非负整数 token 数;无法解析时返回 0
"""
metadata = data.get('metadata') if isinstance(data.get('metadata'), dict) else {}
usage = metadata.get('usage') if isinstance(metadata.get('usage'), dict) else {}
payload = data.get('data') if isinstance(data.get('data'), dict) else {}
candidates = [
usage.get('total_tokens'),
payload.get('total_tokens'),
]
exec_meta = payload.get('execution_metadata')
if isinstance(exec_meta, dict):
candidates.append(exec_meta.get('total_tokens'))
for raw in candidates:
try:
value = int(raw or 0)
if value > 0:
return value
except (TypeError, ValueError):
continue
return 0
@staticmethod
def _update_chat_log_tokens(chat_log_id: int, tokens: int) -> bool:
"""
回写已有 ChatLog 的 tokens_used。
核心逻辑:message_end 先落库时可能尚无 token;workflow_finished 到达后补写更大值。
@param chat_log_id - ChatLog 主键
@param tokens - 从 Dify 事件解析出的 token 数
@returns 是否成功更新
"""
if not chat_log_id or tokens <= 0:
return False
try:
log = db.session.get(ChatLog, chat_log_id)
if not log:
return False
if int(log.tokens_used or 0) >= tokens:
return False
log.tokens_used = tokens
db.session.commit()
return True
except Exception as e:
if current_app:
current_app.logger.error(
'Failed to update chat log tokens chat_log_id=%s: %s',
chat_log_id,
e,
)
db.session.rollback()
return False
@staticmethod
def _persist_stream_chat_record(
*,
data: dict,
event_name: str,
request_id: str | None,
user_id: int,
agent,
session_id: str | None,
hxops_turn_id: str | None,
normalized_conversation_id: str | None,
query: str,
answer_text: str,
latency: int,
retriever_resources: List[Any],
attribution_parts: List[str],
message_payload: dict | None = None,
) -> dict | None:
if not answer_text and not str(query or '').strip():
return None
if current_app:
current_app.logger.info(
"[source-link] persist chat request_id=%s event=%s collected retriever_resources=%s",
request_id,
event_name,
len(retriever_resources),
)
metadata = data.get('metadata') if isinstance(data.get('metadata'), dict) else {}
metadata['retriever_resources'] = retriever_resources
data['metadata'] = metadata
data['retriever_resources'] = retriever_resources
tokens_used = DifyService._extract_token_usage(data)
db_write_started = time.time()
run_id = None
try:
from app.services.file_check_tools.agent_resolver import is_file_check_chat_agent
from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
if is_file_check_chat_agent(agent):
run_id = resolve_run_id_for_chat_log(
session_id=session_id,
query=query,
turn_id=hxops_turn_id,
)
except Exception:
run_id = None
chat_log_id = DifyService._log_chat(
user_id=user_id,
agent_id=agent.id,
session_id=session_id,
conversation_id=data.get('conversation_id') or normalized_conversation_id,
query=query,
answer=answer_text,
tokens=tokens_used,
latency=latency,
retriever_resources=retriever_resources,
attribution_parts=attribution_parts,
payload=message_payload,
run_id=run_id,
)
if chat_log_id and current_app:
current_app.logger.info(
"[chat-perf] persisted async request_id=%s event=%s total_ms=%s db_write_ms=%s answer_len=%s tokens=%s conversation_id=%s chat_log_id=%s run_id=%s",
request_id,
event_name,
latency,
int((time.time() - db_write_started) * 1000),
len(answer_text),
tokens_used,
data.get('conversation_id') or normalized_conversation_id,
chat_log_id,
run_id,
)
if not chat_log_id:
return None
return {"chat_log_id": chat_log_id, "run_id": run_id}
@staticmethod
def _normalize_resources(resources):
"""
@@ -870,6 +1122,77 @@ class DifyService:
DifyService._merge_attribution_parts(attribution_parts, event_data.get('citation'))
DifyService._merge_attribution_parts(attribution_parts, metadata.get('citation'))
@staticmethod
def _normalize_knowledge_retrieval_result(item: Any) -> dict | None:
"""
将 Chatflow 知识检索节点的单条 result 规范化为 retriever_resource 结构。
核心逻辑:合并 metadata 中的 dataset/document/segment 字段到顶层,供前后端统一解析。
"""
if not isinstance(item, dict):
return None
metadata = item.get('metadata') if isinstance(item.get('metadata'), dict) else {}
document_name = (
item.get('document_name')
or metadata.get('document_name')
or item.get('title')
or metadata.get('title')
)
resource = {
**item,
'document_name': document_name,
'content': item.get('content') or metadata.get('content') or '',
'metadata': dict(metadata),
}
for key in ('dataset_id', 'dataset_name', 'document_id', 'segment_id', 'score'):
value = metadata.get(key) if metadata.get(key) not in (None, '') else item.get(key)
if value not in (None, '') and resource.get(key) in (None, ''):
resource[key] = value
return resource
@staticmethod
def _collect_knowledge_retrieval_from_node(retriever_resources: List[Any], event_data: dict):
"""
从 knowledge-retrieval 节点的 node_finished 事件提取检索来源。
核心逻辑:读取 data.outputs.result 列表,规范化后合并进 retriever_resources accumulator。
"""
if event_data.get('event') != 'node_finished':
return
node = event_data.get('data') if isinstance(event_data.get('data'), dict) else {}
if node.get('node_type') != 'knowledge-retrieval':
return
if node.get('status') not in (None, 'succeeded'):
return
outputs = node.get('outputs') if isinstance(node.get('outputs'), dict) else {}
results = outputs.get('result')
if not isinstance(results, list):
return
normalized: List[Any] = []
for item in results:
resource = DifyService._normalize_knowledge_retrieval_result(item)
if resource:
normalized.append(resource)
DifyService._merge_retriever_resources(retriever_resources, normalized)
@staticmethod
def _attach_retriever_resources_to_event(event_data: dict, retriever_resources: List[Any]):
"""
在 message_end / workflow_finished 下发前,把检索来源挂到 SSE 事件体。
核心逻辑:只复制基础 retriever_resources;源文件下载链接由前端按需调用
/api/chat/source-file 解析,避免阻塞最终答案的流式结束事件。
"""
if not retriever_resources:
return
snapshot = json.loads(json.dumps(retriever_resources, ensure_ascii=False, default=str))
event_data['retriever_resources'] = snapshot
metadata = event_data.get('metadata') if isinstance(event_data.get('metadata'), dict) else {}
metadata['retriever_resources'] = snapshot
event_data['metadata'] = metadata
@staticmethod
def _extract_dify_ids(resource: dict):
"""
+6
View File
@@ -0,0 +1,6 @@
"""
backend/app/services/faq/__init__.py
用途:FAQ 缓存与热榜聚合(收敛 faq_*、hot_faq_* 模块)。
逻辑:Wave 4 自 services 根目录迁入。
"""
+2
View File
@@ -0,0 +1,2 @@
"""FAQ 热榜聚合(Wave 4 自 hot_faq_aggregator.py 迁入)。"""
from app.services import hot_faq_aggregator # noqa: F401
+2
View File
@@ -0,0 +1,2 @@
"""FAQ Redis 缓存(Wave 4 自 faq_cache.py 迁入)。"""
from app.services import faq_cache # noqa: F401
+2
View File
@@ -0,0 +1,2 @@
"""FAQ 热榜设置(Wave 4 自 faq_hot_settings.py 迁入)。"""
from app.services import faq_hot_settings # noqa: F401
+188
View File
@@ -0,0 +1,188 @@
"""
backend/app/services/faq_cache.py
用途:全局常用问题 FAQ 缓存匹配与 SSE 直答,避免重复调用 Dify。
依赖:models.QuickQuestion、ChatLog、SQLAlchemy db。
逻辑:chat.py 在调用 DifyService 前委托本模块 try_match;命中则 stream_chat 返回预置答案。
"""
import json
import time
from datetime import datetime
from typing import Any, Optional
from flask import current_app
from app.models import ChatLog, QuickQuestion, db
from app.services.faq_text_utils import normalize_faq_query
class FaqCacheService:
"""全局常用问题 FAQ 缓存服务。"""
@staticmethod
def _normalize_text(text: str) -> str:
"""
归一化问句文本,便于精确/别名匹配。
核心逻辑:委托 faq_text_utils.normalize_faq_query,与热点聚合共用规则。
@param text - 原始问句
@returns 归一化后的字符串
"""
return normalize_faq_query(text)
@staticmethod
def _is_expired(entry: QuickQuestion) -> bool:
"""
判断 FAQ 条目是否已过期。
@param entry - QuickQuestion 实例
@returns 过期返回 True
"""
expires_at = getattr(entry, "expires_at", None)
if not expires_at:
return False
return expires_at <= datetime.utcnow()
@staticmethod
def _candidate_texts(entry: QuickQuestion) -> list[str]:
"""
收集条目可用于匹配的标准化文本集合。
@param entry - QuickQuestion 实例
@returns 归一化后的候选文本列表
"""
texts: list[str] = []
for raw in (entry.question, entry.title):
normalized = FaqCacheService._normalize_text(raw)
if normalized:
texts.append(normalized)
aliases = entry.aliases if isinstance(entry.aliases, list) else []
for alias in aliases:
normalized = FaqCacheService._normalize_text(str(alias))
if normalized:
texts.append(normalized)
return texts
@staticmethod
def try_match(query: str, agent_id: int) -> Optional[QuickQuestion]:
"""
尝试为指定 Agent 命中全局 FAQ 缓存条目。
核心逻辑:加载 cache_enabled 的全局条目,对 question/title/aliases 做归一化精确匹配。
@param query - 用户提问
@param agent_id - 当前 Agent 主键
@returns 命中的 QuickQuestion;未命中返回 None
"""
normalized_query = FaqCacheService._normalize_text(query)
if not normalized_query or not agent_id:
return None
entries = (
db.session.query(QuickQuestion)
.filter(
QuickQuestion.user_id.is_(None),
QuickQuestion.agent_id == agent_id,
QuickQuestion.cache_enabled.is_(True),
QuickQuestion.is_enabled.is_(True),
QuickQuestion.answer.isnot(None),
QuickQuestion.answer != "",
QuickQuestion.stale_at.is_(None),
)
.order_by(QuickQuestion.sort_order.asc(), QuickQuestion.id.asc())
.all()
)
for entry in entries:
if FaqCacheService._is_expired(entry):
continue
if normalized_query in FaqCacheService._candidate_texts(entry):
return entry
return None
@staticmethod
def _increment_hit_count(entry_id: int) -> None:
"""
异步安全地增加 FAQ 命中计数。
@param entry_id - QuickQuestion 主键
"""
try:
db.session.query(QuickQuestion).filter_by(id=entry_id).update(
{
QuickQuestion.hit_count: QuickQuestion.hit_count + 1,
QuickQuestion.updated_at: datetime.utcnow(),
},
synchronize_session=False,
)
db.session.commit()
except Exception as exc:
if current_app:
current_app.logger.warning("[faq-cache] failed to increment hit_count id=%s: %s", entry_id, exc)
db.session.rollback()
@staticmethod
def stream_chat(
entry: QuickQuestion,
query: str,
user,
agent,
conversation_id: str | None = None,
session_id: str | None = None,
):
"""
以 SSE 形式返回 FAQ 预置答案,并写入 ChatLog。
核心逻辑:产出 message + message_end 事件,标记 payload.source=faq_cache。
@param entry - 命中的 QuickQuestion
@param query - 用户原始提问
@param user - 当前用户代理对象(需含 id)
@param agent - 当前 Agent 代理对象(需含 id)
@param conversation_id - Dify/外部会话 ID
@param session_id - 本地会话 ID
@yields SSE 格式字符串
"""
start_time = time.time()
final_conversation_id = conversation_id or f"faq_{int(time.time())}"
answer = str(entry.answer or "").strip()
retriever_resources = entry.retriever_resources if isinstance(entry.retriever_resources, list) else []
yield f"data: {json.dumps({'event': 'message', 'answer': answer}, ensure_ascii=False)}\n\n"
latency = int((time.time() - start_time) * 1000)
chat_log_id = None
try:
chat_log = ChatLog(
user_id=user.id,
agent_id=agent.id,
conversation_id=final_conversation_id,
session_id=session_id,
query=query,
answer=answer,
tokens_used=0,
latency=latency,
retriever_resources=retriever_resources,
payload={
"source": "faq_cache",
"faq_id": entry.id,
"faq_title": entry.title,
},
)
db.session.add(chat_log)
db.session.commit()
chat_log_id = chat_log.id
except Exception as exc:
if current_app:
current_app.logger.error("[faq-cache] failed to log chat: %s", exc)
db.session.rollback()
FaqCacheService._increment_hit_count(entry.id)
end_data: dict[str, Any] = {
"event": "message_end",
"answer": answer,
"replace_answer": True,
"chat_log_id": chat_log_id,
"conversation_id": final_conversation_id,
"metadata": {
"retriever_resources": retriever_resources,
"source": "faq_cache",
"faq_id": entry.id,
},
}
if retriever_resources:
end_data["retriever_resources"] = retriever_resources
yield f"data: {json.dumps(end_data, ensure_ascii=False)}\n\n"
+29
View File
@@ -0,0 +1,29 @@
"""
backend/app/services/faq_hot_settings.py
用途:读取热点 FAQ 离线聚合环境变量(权威默认值在仓库根 `.env.shared`)。
依赖:os.environ(由 config._load_environment_files 在启动时加载)。
逻辑:hot_faq_aggregator、hot_faq_candidate_store 通过本模块读配置,不经过 config.py。
"""
import os
from typing import Any
def read_faq_hot_env(key: str, default: Any) -> Any:
"""
读取单个 FAQ_HOT_* 环境变量并按 default 类型转换。
@param key - 环境变量名,如 FAQ_HOT_WINDOW_DAYS
@param default - 未配置时的兜底值,同时决定返回类型
@returns 转换后的配置值
"""
raw = os.getenv(key)
if raw is None or str(raw).strip() == '':
return default
text = str(raw).strip()
if isinstance(default, bool):
return text.lower() == 'true'
if isinstance(default, float):
return float(text)
if isinstance(default, int):
return int(text)
return text
+224
View File
@@ -0,0 +1,224 @@
"""
backend/app/services/faq_kb_invalidation.py
用途:知识库文档更新/删除时,标记关联 FAQ 为待复审并暂停 L1 缓存命中。
依赖:models.QuickQuestion、KbDifySyncRecord、DifyService._extract_dify_ids、IntegrationApiService。
逻辑:dify_sync_service 同步成功后调用 invalidate_faqs_for_kb_document;晋升 FAQ 时写入 source_kb_document_ids。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from flask import current_app
from app.models import KbDifySyncRecord, QuickQuestion, db
from app.services.dify import DifyService
from app.services.integration_api import IntegrationApiService
STALE_REASON_KB_UPDATED = 'kb_document_updated'
STALE_REASON_KB_DELETED = 'kb_document_deleted'
def extract_dify_id_pairs(retriever_resources: list | None) -> list[tuple[str, str]]:
"""
从 retriever_resources 提取 (dataset_id, remote_document_id) 对。
@param retriever_resources - ChatLog / FAQ 上的引用元数据
@returns 去重后的 Dify ID 对列表
"""
if not isinstance(retriever_resources, list):
return []
pairs: list[tuple[str, str]] = []
seen: set[tuple[str, str]] = set()
for item in retriever_resources:
if not isinstance(item, dict):
continue
dataset_id, remote_document_id = DifyService._extract_dify_ids(item)
if not dataset_id or not remote_document_id:
continue
key = (str(dataset_id), str(remote_document_id))
if key in seen:
continue
seen.add(key)
pairs.append(key)
return pairs
def resolve_kb_document_ids_from_resources(retriever_resources: list | None) -> list[int]:
"""
将 retriever_resources 解析为本地 kb_documents.id 列表。
核心逻辑:优先 IntegrationApiService 本地映射,失败则查 KbDifySyncRecord。
@param retriever_resources - Dify 检索引用列表
@returns 去重后的文档主键列表
"""
doc_ids: list[int] = []
seen: set[int] = set()
for dataset_id, remote_document_id in extract_dify_id_pairs(retriever_resources):
local_doc_id: Optional[int] = None
try:
payload = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
if payload and payload.get('document_id') is not None:
local_doc_id = int(payload['document_id'])
except Exception:
local_doc_id = None
if local_doc_id is None:
record = (
db.session.query(KbDifySyncRecord.document_id)
.filter(
KbDifySyncRecord.dataset_id == str(dataset_id),
KbDifySyncRecord.remote_document_id == str(remote_document_id),
)
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
.first()
)
if record and record[0] is not None:
local_doc_id = int(record[0])
if local_doc_id is not None and local_doc_id not in seen:
seen.add(local_doc_id)
doc_ids.append(local_doc_id)
return doc_ids
def merge_source_kb_document_ids(
existing: list | None,
retriever_resources: list | None,
) -> list[int] | None:
"""
合并已有 source_kb_document_ids 与 retriever_resources 解析结果。
@returns 合并去重后的 ID 列表;无有效 ID 时返回 None
"""
merged: list[int] = []
seen: set[int] = set()
for raw in (existing if isinstance(existing, list) else []):
try:
doc_id = int(raw)
except (TypeError, ValueError):
continue
if doc_id not in seen:
seen.add(doc_id)
merged.append(doc_id)
for doc_id in resolve_kb_document_ids_from_resources(retriever_resources):
if doc_id not in seen:
seen.add(doc_id)
merged.append(doc_id)
return merged or None
def _faq_links_kb_document(
qq: QuickQuestion,
document_id: int,
dataset_id: str | None,
remote_document_id: str | None,
) -> bool:
"""判断 FAQ 是否关联指定 KB 文档(本地 ID 或 Dify ID 对)。"""
source_ids = qq.source_kb_document_ids if isinstance(qq.source_kb_document_ids, list) else []
for raw in source_ids:
try:
if int(raw) == int(document_id):
return True
except (TypeError, ValueError):
continue
if not dataset_id or not remote_document_id:
return False
target = (str(dataset_id), str(remote_document_id))
return target in extract_dify_id_pairs(
qq.retriever_resources if isinstance(qq.retriever_resources, list) else None
)
def find_linked_faqs(
document_id: int,
*,
dataset_id: str | None = None,
remote_document_id: str | None = None,
cache_enabled_only: bool = True,
) -> list[QuickQuestion]:
"""
查找与 KB 文档关联的全局 FAQ。
@param cache_enabled_only - True 时仅扫描 cache_enabled 条目
@returns 匹配的 QuickQuestion 列表
"""
query = db.session.query(QuickQuestion).filter(QuickQuestion.user_id.is_(None))
if cache_enabled_only:
query = query.filter(QuickQuestion.cache_enabled.is_(True))
rows = query.all()
return [
row
for row in rows
if _faq_links_kb_document(row, document_id, dataset_id, remote_document_id)
]
def mark_faq_stale(qq: QuickQuestion, *, document_id: int, reason: str) -> None:
"""
将 FAQ 标记为待复审并暂停缓存。
核心逻辑:写 stale_* 字段,cache_enabled=false,用户提问将回退 Dify。
"""
now = datetime.utcnow()
qq.stale_at = now
qq.stale_reason = reason
qq.stale_kb_document_id = document_id
qq.cache_enabled = False
qq.updated_at = now
def clear_faq_stale(qq: QuickQuestion) -> None:
"""清除 FAQ 待复审标记。"""
qq.stale_at = None
qq.stale_reason = None
qq.stale_kb_document_id = None
def invalidate_faqs_for_kb_document(
document_id: int,
*,
reason: str,
dataset_id: str | None = None,
remote_document_id: str | None = None,
) -> int:
"""
KB 文档变更后,标记所有关联 FAQ 为待复审。
@param document_id - kb_documents.id
@param reason - stale_reason 枚举值
@param dataset_id - 可选,Dify dataset_id
@param remote_document_id - 可选,Dify remote document id
@returns 标记条数
"""
if not document_id:
return 0
try:
linked = find_linked_faqs(
int(document_id),
dataset_id=dataset_id,
remote_document_id=remote_document_id,
cache_enabled_only=True,
)
if not linked:
return 0
for qq in linked:
mark_faq_stale(qq, document_id=int(document_id), reason=reason)
db.session.commit()
return len(linked)
except Exception as exc:
db.session.rollback()
if current_app:
current_app.logger.warning(
'[faq-kb-invalidation] invalidate failed document_id=%s: %s',
document_id,
exc,
)
return 0
def apply_retriever_resources_to_faq(qq: QuickQuestion, retriever_resources: Any) -> None:
"""
将 retriever_resources 写入 FAQ,并解析 source_kb_document_ids。
@param qq - QuickQuestion 实例
@param retriever_resources - 引用列表或 None
"""
if isinstance(retriever_resources, list) and retriever_resources:
qq.retriever_resources = retriever_resources
qq.source_kb_document_ids = merge_source_kb_document_ids(
qq.source_kb_document_ids if isinstance(qq.source_kb_document_ids, list) else None,
qq.retriever_resources if isinstance(qq.retriever_resources, list) else None,
)
+20
View File
@@ -0,0 +1,20 @@
"""
backend/app/services/faq_text_utils.py
用途:FAQ / 热点问句归一化等纯文本工具,供 faq_cache 与 hot_faq_aggregator 共用。
依赖:无外部业务模块。
逻辑:保证离线聚合与在线命中使用同一 normalize 规则。
"""
import re
def normalize_faq_query(text: str) -> str:
"""
归一化问句文本,便于精确匹配与 ChatLog 分组。
核心逻辑:trim → 小写 → 去除空白与常见中英文标点。
@param text - 原始问句
@returns 归一化后的字符串;空输入返回空串
"""
value = str(text or "").strip().lower()
value = re.sub(r"[\s\u3000,。!?、;:""''()()\[\]【】\-—·,.!?;:'\"]+", "", value)
return value
+186
View File
@@ -0,0 +1,186 @@
"""
backend/app/services/feedback_notify.py
用途:将用户新提交的通用意见反馈即时推送到企业微信群,方便处理人第一时间跟进。
依赖:Flask current_app、requests、GeneralFeedback/User 模型。
逻辑:api/user.py 先保存 GeneralFeedback,再以 best-effort 方式调用本服务;
通知失败只写日志,不回滚反馈提交,也不影响用户侧响应。
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from urllib.parse import urlencode
import requests
from flask import current_app
from app.models import GeneralFeedback, User
def _get_feedback_notify_base_url() -> str:
"""
解析反馈通知中“打开后台报表”链接使用的公网基地址。
核心逻辑:优先读取反馈通知专用配置;未配置时复用已有企微通知或平台公网地址,
避免不同环境重复维护同一类外部访问域名。
Returns:
str: 去掉末尾斜杠的公网基地址;所有配置都缺失时返回空字符串。
"""
for key in (
'WECOM_FEEDBACK_NOTIFY_BASE_URL',
'WECOM_NOTIFY_BASE_URL',
'WECOM_PUBLIC_BASE_URL',
'PUBLIC_BASE_URL',
):
raw = current_app.config.get(key)
if isinstance(raw, str) and raw.strip():
return raw.strip().rstrip('/')
return ''
def _truncate_text(value: str | None, limit: int) -> str:
"""
截断过长的反馈内容,避免企业微信 markdown 消息超长或刷屏。
Args:
value: 用户提交的原始反馈文本或模型字段文本。
limit: 最多保留的字符数,必须为正整数。
Returns:
str: 截断后的文本;超过限制时追加省略号。
"""
text = (value or '').strip()
if len(text) <= limit:
return text
return f'{text[: max(limit - 3, 0)]}...'
def _format_created_at(value: datetime | None) -> str:
"""
将反馈创建时间格式化为企业微信群里可读的北京时间文本。
Args:
value: 当前 SQLAlchemy 模型保存的 UTC datetime;允许为空。
Returns:
str: 形如 YYYY-MM-DD HH:MM:SS 的 Asia/Shanghai 时间;缺失时返回空字符串。
"""
if not value:
return ''
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone(timedelta(hours=8))).strftime('%Y-%m-%d %H:%M:%S')
def build_feedback_report_url(feedback_id: int) -> str:
"""
构造后台报表链接,帮助处理人从群消息直接定位到对应反馈。
Args:
feedback_id: general_feedbacks 主键,必须是正整数。
Returns:
str: 配置公网基地址时返回完整后台报表 URL;未配置时返回空字符串,
让通知消息仍可发送,只是不带跳转链接。
"""
base_url = _get_feedback_notify_base_url()
if not base_url or not feedback_id:
return ''
return f'{base_url}/admin/reports/general_feedbacks?{urlencode({"id": feedback_id})}'
def build_feedback_markdown(feedback: GeneralFeedback, user: User | None) -> str:
"""
组装企业微信群机器人 markdown 消息正文。
Args:
feedback: 已入库的 GeneralFeedback 记录,调用前应已有 id。
user: 提交反馈的当前用户;测试或异常兜底场景允许为空。
Returns:
str: 企业微信群机器人 webhook 可接受的 markdown 文本。
"""
display_name = (
(getattr(user, 'real_name', None) or '').strip()
or (getattr(user, 'username', None) or '').strip()
or feedback.username
)
username = (getattr(user, 'username', None) or feedback.username or '').strip()
employee_id = (getattr(user, 'employee_id', None) or '').strip()
reporter_parts = [display_name]
if username and username != display_name:
reporter_parts.append(username)
if employee_id:
reporter_parts.append(f'工号 {employee_id}')
reporter = ' / '.join([part for part in reporter_parts if part])
content = _truncate_text(feedback.content, 900)
report_url = build_feedback_report_url(feedback.id)
lines = [
'### HXOPS 新意见反馈',
f'>反馈编号:{feedback.id}',
f'>反馈类型:{feedback.feedback_type}',
f'>反馈模块:{feedback.feedback_module}',
f'>提交人:{reporter or "-"}',
f'>提交时间:{_format_created_at(feedback.created_at) or "-"}',
]
if feedback.source_page:
lines.append(f'>来源页面:{feedback.source_page}')
if feedback.chat_log_id:
lines.append(f'>关联对话:{feedback.chat_log_id}')
lines.extend(['', '**反馈内容:**', content or '-'])
if report_url:
lines.extend(['', f'[打开后台报表]({report_url})'])
return '\n'.join(lines)
def send_feedback_group_notification(feedback: GeneralFeedback, user: User | None) -> dict:
"""
发送通用意见反馈的企业微信群机器人通知。
触发时机:/api/user/feedback 成功提交 GeneralFeedback 后立即调用,
让处理人尽量实时看到用户反馈。
Args:
feedback: 需要推送的已入库反馈记录。
user: 提交人信息,用于在消息中展示姓名、账号和工号。
Returns:
dict: 包含 ok/skipped/reason 等字段,供路由记录日志。函数内部吞掉发送异常,
因为通知失败不能影响反馈入库和用户侧提交结果。
"""
if not current_app.config.get('WECOM_FEEDBACK_NOTIFY_ENABLED', True):
return {'ok': False, 'skipped': True, 'reason': 'notify_disabled'}
webhook = (current_app.config.get('WECOM_FEEDBACK_BOT_WEBHOOK') or '').strip()
if not webhook:
return {'ok': False, 'skipped': True, 'reason': 'webhook_unconfigured'}
payload = {
'msgtype': 'markdown',
'markdown': {
'content': build_feedback_markdown(feedback, user),
},
}
try:
response = requests.post(webhook, json=payload, timeout=3)
data = response.json()
except Exception as exc:
current_app.logger.warning(
'[feedback-notify] send exception feedback_id=%s err=%s',
getattr(feedback, 'id', None),
exc,
)
return {'ok': False, 'reason': 'exception'}
if data.get('errcode') == 0:
return {'ok': True}
current_app.logger.warning(
'[feedback-notify] send failed feedback_id=%s errcode=%s errmsg=%s',
getattr(feedback, 'id', None),
data.get('errcode'),
str(data.get('errmsg', ''))[:255],
)
return {'ok': False, 'reason': 'send_failed', 'raw': data}
@@ -1,6 +1,9 @@
"""
backend/app/services/rohs_check.py
文件用途:RoHS 文件检核统一判定入口,当前适配现有 Dify Workflow。
backend/app/services/file_check.py
用途:文件检核统一判定入口,调用 ScheduleTask 绑定的 Dify Workflow。
依赖:DifyService.run_workflow_streaming。
逻辑:由 schedule/srm_service 检核循环逐条调用;RoHS/MSDS 等差异在 Workflow 与排程 SQL 配置。
"""
from __future__ import annotations
@@ -8,12 +11,11 @@ from typing import Any
from app.services.dify import DifyService
VALID_ROHS_RESULTS = {"合格", "不合格", "人工判定"}
VALID_FILE_CHECK_RESULTS = {"合格", "不合格", "人工判定"}
class RoHSCheckService:
"""Wrap RoHS judgement behind a stable backend interface."""
class FileCheckService:
"""文件检核 Dify Workflow 调用与结果规范化。"""
PROVIDER = "dify_workflow"
@@ -29,6 +31,21 @@ class RoHSCheckService:
user: str = "schedule_system",
timeout: tuple[int, int] = (5, 300),
) -> dict[str, Any]:
"""
对单条待检记录调用 Dify Workflow 并返回规范化判定。
Args:
agent: ScheduleTask.dify_agent 对应的 Agent 记录。
run_no: 当前检核批次号。
record: 待检记录文本(由排程 SQL 组装)。
attachment_url: 附件 URL,可选。
system_prompt: 排程配置的补充系统提示,可选。
user: Dify 用户标识。
timeout: HTTP 超时 (connect, read) 秒。
Returns:
含 dify_result、dify_message、workflow_run_id 等字段的 dict。
"""
inputs: dict[str, Any] = {
"run_no": run_no,
"record": record,
@@ -60,6 +77,7 @@ class RoHSCheckService:
@staticmethod
def normalize_workflow_result(workflow_result: dict[str, Any] | None) -> dict[str, Any]:
"""将 Dify Workflow 输出规范为合格/不合格/人工判定。"""
data = workflow_result if isinstance(workflow_result, dict) else {}
outputs = (data.get("outputs") or {}).get("output") or data.get("outputs") or data
output_data = outputs if isinstance(outputs, dict) else {}
@@ -78,7 +96,7 @@ class RoHSCheckService:
"raw_outputs": output_data,
}
if dify_result not in VALID_ROHS_RESULTS:
if dify_result not in VALID_FILE_CHECK_RESULTS:
bad_value = dify_result or "空"
extra = f" | {dify_message}" if dify_message else ""
return {
@@ -0,0 +1 @@
"""文件检核 Chatflow 工具包。"""
Loaded 100 of 399 files, more files were not shown because too many files have changed in this diff. Show more