Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
88fcf3c70b | ||
|
|
9838b77441 | ||
|
|
e457a66465 | ||
|
|
ec2c9eca6f | ||
|
|
6a26a4dba8 | ||
|
|
fc4631218b | ||
|
|
0d735def90 | ||
|
|
9203a90637 | ||
|
|
8023acd212 | ||
|
|
d100a39cf8 | ||
|
|
ffccf19ba2 | ||
|
|
e8255f5943 | ||
|
|
70f684b94a | ||
|
|
bc86720744 | ||
|
|
ceb49461e8 | ||
|
|
ea9a96b2fb | ||
|
|
49629aeb0f | ||
|
|
cd81911514 | ||
|
|
49c149eb3e | ||
|
|
729546a7b7 | ||
|
|
202d626a7a | ||
|
|
143e054d86 | ||
|
|
0a9bd6415d | ||
|
|
42de6c02d3 | ||
|
|
b2fa2688a3 | ||
|
|
1ee4c69dee | ||
|
|
2ebac99d43 | ||
|
|
c621f7696c | ||
|
|
db067085e4 | ||
|
|
6d39e474f5 | ||
|
|
a31735b689 | ||
|
|
5a147c4d85 | ||
|
|
c3f05ba96b | ||
|
|
918d4f1835 | ||
|
|
fc843905d1 | ||
|
|
f21216f81e | ||
|
|
0939aeb0d8 | ||
|
|
64205b72bd | ||
|
|
854793f3fe | ||
|
|
ffd3634302 | ||
|
|
5e7e5a8717 | ||
|
|
8b1efbedb9 | ||
|
|
c81717df30 | ||
|
|
f4e74f7b07 | ||
|
|
39ef8a49c9 | ||
|
|
50ccd31b84 | ||
|
|
348f0fdcfd | ||
|
|
c778f40fbc | ||
|
|
b89f9bafb6 | ||
|
|
dab04d4c3e | ||
|
|
f1b9b7c3a9 | ||
|
|
0d68048b8e | ||
|
|
8b5b0b49bf | ||
|
|
61acbe50a7 | ||
|
|
8bd66baa21 | ||
|
|
5bef77f86c | ||
|
|
37e08c83d8 | ||
|
|
2ce1aca023 | ||
|
|
99453aa52a | ||
|
|
fa965dd45b | ||
|
|
d54f51ddc3 | ||
|
|
fc694a8f43 | ||
|
|
c8ce77199e | ||
|
|
9ea49d7060 | ||
|
|
fd024c1c32 | ||
|
|
dfaa55b365 | ||
|
|
bf18a7ef1d | ||
|
|
6ce0942fef | ||
|
|
fa8f6990a7 | ||
|
|
2566ce53e4 | ||
|
|
ac4262cd75 | ||
|
|
090281835a | ||
|
|
76d5778c3b | ||
|
|
f72c1c9f0e | ||
|
|
95f3906779 | ||
|
|
91758ef2b4 | ||
|
|
3a22df736e | ||
|
|
0f3f40e735 | ||
|
|
56b6ea06a8 | ||
|
|
7a9c36d16b | ||
|
|
8846ce159f | ||
|
|
1164ae2e3c | ||
|
|
599475d4e2 | ||
|
|
09cd6fc3c7 | ||
|
|
60dd0c0f58 | ||
|
|
6261d2e1f3 | ||
|
|
9c036c825b | ||
|
|
bba6e6f221 | ||
|
|
c8054476c1 | ||
|
|
4a14960e01 | ||
|
|
f96684a614 | ||
|
|
af999d8a11 | ||
|
|
6a0a51313f | ||
|
|
9f5493185d | ||
|
|
4cd987eef6 | ||
|
|
19f43e8018 | ||
|
|
3f13bb5b46 | ||
|
|
eb0466245b | ||
|
|
ce80867d09 | ||
|
|
1921959fc1 | ||
|
|
d5e76dee36 | ||
|
|
b476b58a91 | ||
|
|
ca32191c77 | ||
|
|
7f1d5dfbcd | ||
|
|
7e4a2037d8 | ||
|
|
f434402530 | ||
|
|
1fc9976ca3 | ||
|
|
cafce5cfa9 | ||
|
|
a3420c5266 | ||
|
|
3b771fc0b6 | ||
|
|
0b083cfdbd | ||
|
|
53efa7e14e | ||
|
|
d6af566601 | ||
|
|
25876f94bd | ||
|
|
1cf8ff40bd | ||
|
|
70d7435b5f | ||
|
|
a451951e7a | ||
|
|
053ea392f2 | ||
|
|
1dc5a459b3 | ||
|
|
6e78c10171 |
No files matched your search
@@ -22,8 +22,6 @@ AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
|
||||
AUTH_JWT_JWKS_URL=http://192.168.100.192:8870/.well-known/jwks
|
||||
|
||||
# Casdoor
|
||||
|
||||
# 共用 IdP(可与生产 Casdoor 同机)
|
||||
CASDOOR_BASE_URL=http://192.168.100.192:8870
|
||||
# 以下为 hxops-dev 应用在 Casdoor 控制台里的 Client ID / Secret(勿与 prod 混用)
|
||||
CASDOOR_CLIENT_ID=758be5fcba2df784fdb4
|
||||
@@ -55,11 +53,14 @@ MINIO_SECRET_KEY=M3CLE928P8GavJBFZPhJO3RIHVZSRYlDouOMabasojfAGBlx
|
||||
MINIO_SECURE=false
|
||||
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
|
||||
|
||||
# 货代发货通知 Agent(见 docs/shipping_notice.md §1.2;Tool 基地址见 HXOPS_TOOLS_API_BASE)
|
||||
# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
|
||||
# 货代发货通知 Agent(见 docs/features/shipping-notice/technical.md §1.2;Tool 基地址见 HXOPS_TOOLS_API_BASE)
|
||||
# RoHS / 货代等 Dify Tool API 基地址(Dify 服务端内网调用,无尾斜杠)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
|
||||
# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠)
|
||||
HXOPS_PUBLIC_BASE_URL=http://192.168.100.192:8890
|
||||
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=MymLe1StfTCuMOl0IYTp-BRYKln_TnywEDxJ0X0mraYjhFtGeL8mRqoiVPlP9Er8
|
||||
|
||||
# 文件存储(相对 backend/ 根目录)
|
||||
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
||||
@@ -68,6 +69,9 @@ SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
||||
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
|
||||
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
|
||||
|
||||
# 字段对齐确认(生产建议 true;测试可设 false)
|
||||
@@ -77,22 +81,23 @@ SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=6
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=true
|
||||
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 shipping_notice.md §2.4)
|
||||
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||
|
||||
# RPA 目录(相对 backend/ 根目录)
|
||||
FREIGHT_INVENTORY_DROP_DIR=data/freight_rpa/inventory_drop
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=data/freight_rpa/upload_queue
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/freight_rpa/upload_triggers
|
||||
FREIGHT_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers
|
||||
FREIGHT_RPA_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
|
||||
|
||||
# 发货 Excel 模板(可选)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
|
||||
@@ -105,7 +110,10 @@ SHIPPING_NOTICE_CHAT_DIFY_APP_ID=
|
||||
SHIPPING_NOTICE_CHAT_DIFY_API_KEY=
|
||||
SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
|
||||
|
||||
# 本地 Mock RPA(scripts/rpa/freight_rpa_worker.py,可选)
|
||||
# FREIGHT_RPA_MOCK=true
|
||||
# 本地 RPA(scripts/rpa/freight_rpa_worker.py)
|
||||
FREIGHT_RPA_MOCK=false
|
||||
# FREIGHT_RPA_POLL_SECONDS=3
|
||||
# FREIGHT_RPA_SAMPLE_INVENTORY=
|
||||
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
@@ -22,14 +22,14 @@ AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
|
||||
AUTH_JWT_JWKS_URL=http://192.168.100.230:8870/.well-known/jwks
|
||||
|
||||
# Casdoor
|
||||
CASDOOR_BASE_URL=http://ai.well-trust.com:8870
|
||||
CASDOOR_BASE_URL=https://auth.well-trust.com
|
||||
# 与 Casdoor 里 Application「hxops-prod」(或你当前生产应用)的 Client ID 一致
|
||||
CASDOOR_CLIENT_ID=758be5fcba2df784fdb4
|
||||
CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab
|
||||
# 兜底 redirect_uri;实际 OAuth 以浏览器地址为准,Casdoor「hxops-prod」应用须登记例如:
|
||||
# http://192.168.100.230:8881/casdoor-callback
|
||||
# http://ai.well-trust.com:8881/casdoor-callback
|
||||
CASDOOR_REDIRECT_URI=http://192.168.100.230:8881/casdoor-callback
|
||||
CASDOOR_REDIRECT_URI=https://ai.well-trust.com/casdoor-callback
|
||||
CASDOOR_SCOPE=openid profile email
|
||||
CASDOOR_ORGANIZATION=organization_HX
|
||||
# Casdoor Providers → wecom:Name 字段(截图即为 wecom);Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo
|
||||
@@ -47,7 +47,9 @@ TASK_EXECUTION_MODE=rq
|
||||
GUNICORN_WORKERS=20
|
||||
|
||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
|
||||
WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||
|
||||
# MinIO(知识库文档清洗图片托管,容器 minio-app)
|
||||
# MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1)
|
||||
@@ -58,5 +60,37 @@ MINIO_SECURE=false
|
||||
# MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问
|
||||
MINIO_PUBLIC_BASE_URL=http://ai.well-trust.com:9000
|
||||
|
||||
# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.230:8890
|
||||
# RoHS / 货代 / 设备维保等 Dify Tool API 基地址(Dify 服务端内网调用,无尾斜杠)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.230:8890
|
||||
# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠)
|
||||
HXOPS_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||
|
||||
# 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh
|
||||
|
||||
# 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享)
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
FREIGHT_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/inventory_drop
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/inventory_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/upload_queue
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/upload_triggers
|
||||
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致)
|
||||
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
||||
# 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
|
||||
|
||||
# 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
||||
|
||||
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
+18
-2
@@ -28,7 +28,7 @@ EDKB_SOFFICE_TIMEOUT_SEC=600
|
||||
# Windows Word COM / word_bridge 单次转换超时(秒);复杂 .doc 可适当放宽
|
||||
EDKB_WORD_TIMEOUT_SEC=300
|
||||
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免单条任务长期卡住整个 worker
|
||||
EDKB_FILE_TIMEOUT_SEC=180
|
||||
EDKB_FILE_TIMEOUT_SEC=300
|
||||
# Word 文档(.doc/.docx)单文件清洗总超时(秒);优先于 EDKB_FILE_TIMEOUT_SEC
|
||||
EDKB_WORD_FILE_TIMEOUT_SEC=420
|
||||
# running 任务回收阈值,须大于 EDKB_SOFFICE_TIMEOUT_SEC 及整条清洗链路耗时
|
||||
@@ -80,8 +80,10 @@ WECOM_FEEDBACK_BOT_WEBHOOK=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=
|
||||
# Common integration defaults
|
||||
INTEGRATION_API_MODE=local
|
||||
DIFY_API_BASE=https://api.dify.ai/v1
|
||||
# HXOPS Tool API 对外基地址(RoHS / 货代等 Dify Chatflow、OpenAPI、签名下载链接;无尾斜杠;各环境 .env.* 覆盖)
|
||||
# HXOPS Tool API 对外基地址(RoHS / 货代等 Dify Chatflow 服务端调用;无尾斜杠;各环境 .env.* 覆盖)
|
||||
HXOPS_TOOLS_API_BASE=
|
||||
# HXOPS 浏览器可访问根地址(Excel 签名下载等用户可见链接;无尾斜杠;各环境 .env.* 覆盖)
|
||||
HXOPS_PUBLIC_BASE_URL=
|
||||
|
||||
# MinIO:按环境配置见 .env.dev / .env.test / .env.prod
|
||||
# MINIO_KB_IMAGE_BUCKET — 知识库文档清洗图片托管(kb-worker / export)
|
||||
@@ -129,6 +131,18 @@ SRM_SQLSERVER_TIMEOUT=10
|
||||
ERP_DB_DSN=192.168.8.24:1521/topprod
|
||||
TEXT2SQL_SCHEMA_PATH=
|
||||
|
||||
# 固资履历共享盘
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
||||
|
||||
# 固资图片文档库
|
||||
FIXED_ASSET_IMAGE_BASE_URL=http://192.168.8.158:8071/Web/#/login
|
||||
FIXED_ASSET_IMAGE_USERNAME=26040006
|
||||
FIXED_ASSET_IMAGE_PASSWORD=26040006
|
||||
FIXED_ASSET_IMAGE_LIBRARY_ID=8d61bd96-ff2d-489b-86fc-ca0b8c6bbcf8
|
||||
FIXED_ASSET_IMAGE_FOLDER_ID=3aea6c19-d9ac-40fa-ab16-9cb06c0db3e3
|
||||
|
||||
# 热点 FAQ 离线聚合(ChatLog -> PostgreSQL faq_hot_candidates 表)
|
||||
# 管理端「常用问题 > 热点发现」刷新聚合时读取以下配置
|
||||
FAQ_HOT_ENABLED=true # 是否启用热点聚合(false 时刷新/CLI 直接跳过)
|
||||
@@ -144,3 +158,5 @@ FAQ_HOT_ANSWER_SIMILARITY=0.95 # (聚类已关闭)答案聚类相
|
||||
FAQ_HOT_ANSWER_DOMINANCE=0.6 # (聚类已关闭)最大答案簇占比下限,恢复聚类时生效
|
||||
FAQ_HOT_GOOD_SCORE=4 # 选代表答案时「好评」反馈分阈值(≥此分优先)
|
||||
FAQ_HOT_BAD_SCORE=2 # 选代表答案时「差评」反馈分阈值(≤此分排除)
|
||||
# Freight RPA defaults to real browser automation. Set to true only for local mock/debug runs.
|
||||
FREIGHT_RPA_MOCK=false
|
||||
@@ -22,17 +22,17 @@ AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
|
||||
AUTH_JWT_JWKS_URL=http://192.168.100.192:8870/.well-known/jwks
|
||||
|
||||
# Casdoor
|
||||
CASDOOR_BASE_URL=http://192.168.100.192:8870
|
||||
CASDOOR_BASE_URL=https://autht.well-trust.com
|
||||
# 与 Casdoor 里 Application「hxops-prod」(或你当前生产应用)的 Client ID 一致
|
||||
CASDOOR_CLIENT_ID=758be5fcba2df784fdb4
|
||||
CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab
|
||||
# 兜底 redirect_uri;实际 OAuth 以浏览器地址为准,Casdoor「hxops-prod」应用须登记例如:
|
||||
# http://192.168.100.192:8881/casdoor-callback
|
||||
# http://ai.well-trust.com:8881/casdoor-callback
|
||||
CASDOOR_REDIRECT_URI=http://192.168.100.192:8881/casdoor-callback
|
||||
CASDOOR_REDIRECT_URI=https://ait.well-trust.com/casdoor-callback
|
||||
CASDOOR_SCOPE=openid profile email
|
||||
CASDOOR_ORGANIZATION=organization_HX
|
||||
# Casdoor Providers → wecom:Name 字段(截图即为 wecom);Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo
|
||||
# Casdoor Providers → wecom:Name 字段;Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo
|
||||
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
||||
|
||||
# 知识库 Dify 对接
|
||||
@@ -47,7 +47,10 @@ TASK_EXECUTION_MODE=rq
|
||||
GUNICORN_WORKERS=6
|
||||
|
||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||
WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
|
||||
WECOM_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||
HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||
|
||||
# MinIO(知识库文档清洗图片托管,容器 minio-app)
|
||||
# MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1)
|
||||
@@ -59,11 +62,13 @@ MINIO_SECURE=false
|
||||
# MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问
|
||||
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
|
||||
|
||||
# 货代发货通知 Agent(见 docs/shipping_notice.md §1.2;Tool 基地址见 HXOPS_TOOLS_API_BASE)
|
||||
# 货代发货通知 Agent(见 docs/features/shipping-notice/technical.md §1.2;Tool 基地址见 HXOPS_TOOLS_API_BASE)
|
||||
# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
|
||||
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||
HXOPS_TOOLS_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
# 货代专用 Tool API Key(RPA 回调优先读取;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=GOnGt04o0-Ev4wEw6a6C4NOmm4XF7dxsLPP6fPtTC2vV341l1QKVASV75ONj72er
|
||||
|
||||
# 文件存储(相对 backend/ 根目录)
|
||||
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
||||
@@ -72,6 +77,9 @@ SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
||||
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
|
||||
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
|
||||
|
||||
# 字段对齐确认(生产建议 true;测试可设 false)
|
||||
@@ -81,26 +89,41 @@ SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=6
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=true
|
||||
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 shipping_notice.md §2.4)
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
|
||||
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||
|
||||
# RPA 目录(相对 backend/ 根目录)
|
||||
FREIGHT_INVENTORY_DROP_DIR=data/freight_rpa/inventory_drop
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=data/freight_rpa/upload_queue
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/freight_rpa/upload_triggers
|
||||
# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享)
|
||||
FREIGHT_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers
|
||||
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐)
|
||||
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
||||
# 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微
|
||||
# 两者皆无则告警只写日志、不会发企微
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
|
||||
# 企微发送中短锁秒数(发送失败过期后可重试,默认 120)
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
|
||||
|
||||
# 发货 Excel 模板(可选)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
|
||||
|
||||
# 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
||||
|
||||
# AWS 库存列映射(可选 JSON 字符串)
|
||||
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
|
||||
|
||||
@@ -112,4 +135,8 @@ SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
|
||||
# 本地 Mock RPA(scripts/rpa/freight_rpa_worker.py,可选)
|
||||
# FREIGHT_RPA_MOCK=true
|
||||
# FREIGHT_RPA_POLL_SECONDS=3
|
||||
# FREIGHT_RPA_SAMPLE_INVENTORY=
|
||||
# FREIGHT_RPA_SAMPLE_INVENTORY=
|
||||
|
||||
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
+9
-2
@@ -26,8 +26,9 @@ share/python-wheels/
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
# Pytest / local temp
|
||||
backend/.pytest_tmp/
|
||||
.pytest_tmp/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
@@ -49,9 +50,12 @@ frontend/package-lock.json
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/extensions.json
|
||||
.trae/*
|
||||
.cursor/*
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
.cursorrules
|
||||
|
||||
# Runtime files
|
||||
.run/
|
||||
@@ -79,3 +83,6 @@ oracle_client/
|
||||
backend/data/kb/
|
||||
.pytest_cache/
|
||||
backend/data/fixed_assets/manifest.json
|
||||
backend/data/shipping_notice/
|
||||
backend/data/logs/
|
||||
backend/data/logs/*.log
|
||||
Vendored
+28
-3
@@ -1,9 +1,33 @@
|
||||
{
|
||||
// 后端 Python 虚拟环境
|
||||
// 后端 Python 虚拟环境(解释器路径供语言服务/调试使用)
|
||||
"python.defaultInterpreterPath": "${workspaceFolder}/backend/.venv/Scripts/python.exe",
|
||||
"python.terminal.activateEnvironment": true,
|
||||
// 关闭 Python 扩展在新建终端时自动 activate,避免与下方 PowerShell (HXOPS) 的 cd 钩子重复激活
|
||||
"python.terminal.activateEnvironment": false,
|
||||
"python.venvPath": "${workspaceFolder}/backend",
|
||||
"python.venvFolders": [".venv"],
|
||||
"github.copilot.chat.commitMessageGeneration.instructions": [
|
||||
{
|
||||
"text": "Generate Git commit messages in Simplified Chinese by default."
|
||||
},
|
||||
{
|
||||
"text": "Follow Conventional Commits format: <type>(<scope>): <subject>."
|
||||
},
|
||||
{
|
||||
"text": "Use English for type and scope; use Simplified Chinese for subject and body."
|
||||
},
|
||||
{
|
||||
"text": "Allowed types are feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert."
|
||||
},
|
||||
{
|
||||
"text": "The subject must be imperative, no period at the end, and no longer than 100 Chinese characters."
|
||||
},
|
||||
{
|
||||
"text": "Avoid vague messages such as update, fix bug, or WIP."
|
||||
},
|
||||
{
|
||||
"text": "When a body is useful, write concise Chinese bullet points describing concrete changes."
|
||||
}
|
||||
],
|
||||
|
||||
// 默认终端:加载 cd 钩子,进入 backend 时自动激活 .venv
|
||||
"terminal.integrated.defaultProfile.windows": "PowerShell (HXOPS)",
|
||||
@@ -30,5 +54,6 @@
|
||||
"Set-Location '${workspaceFolder}/backend'; if (Test-Path '.venv/Scripts/Activate.ps1') { . '.venv/Scripts/Activate.ps1' }"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"js/ts.tsdk.path": "node_modules\\typescript\\lib"
|
||||
}
|
||||
@@ -54,6 +54,8 @@ frontend/src/
|
||||
locales/ # i18n 四语言 JSON(zh-CN / zh-TW / en / th),按域拆分
|
||||
scripts/ # 部署与运维脚本(deploy_compose.sh、healthcheck.sh ...)
|
||||
docs/ # 权威文档(规范、上下文、流程、发布说明)
|
||||
# features/ 业务域手册 · platform/ 平台设计 · prototype/ 产品原型
|
||||
# convention/ · openapi/ · dify/ · refactor/
|
||||
```
|
||||
|
||||
**约定**:
|
||||
@@ -152,7 +154,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)**。
|
||||
- ⚠️ **错误处理统一契约**:JSON API 使用 `{ success, data | error, request_id }` envelope;后端业务失败 **`raise AppError` 子类**(`app/core/errors.py`),禁止新写 `jsonify({"error": ...})`;前端 HTTP 统一 **`requestJson`**(`@/shared/api/client`),失败为 **`BusinessError`**,在 composable/view 用 **`useMessage()`** 展示;新增 `error.code` 须同步四语言 **`locales/*/errors.json`**。详见 **[docs/convention/error_handling.md](docs/convention/error_handling.md)**。
|
||||
- ⚠️ 改动**数据库结构、部署脚本(`scripts/`、`Jenkinsfile`、`docker-compose.yml`)或敏感配置**前,先说明影响面再动手。
|
||||
|
||||
合并前最低自检(详见 [新人文档 §3.3](docs/新人环境搭建与配置文档.md)):前后端可启动、`frontend/` 改动后 `npm run build` 通过、关键页面与登录可用。
|
||||
@@ -180,6 +182,7 @@ docker compose logs -f hxops-backend
|
||||
|
||||
| 主题 | 文档 |
|
||||
| --- | --- |
|
||||
| **文档总索引** | [docs/README.md](docs/README.md) |
|
||||
| 项目上下文 / 架构 / 数据模型 | [docs/project_context.md](docs/project_context.md) |
|
||||
| 需求文档 | [docs/demand.md](docs/demand.md) |
|
||||
| 技术架构文档 | [docs/tec.md](docs/tec.md) |
|
||||
@@ -195,3 +198,8 @@ docker compose logs -f hxops-backend
|
||||
| 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.md) |
|
||||
| 前端架构规范 | [docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md) |
|
||||
| 错误处理规范 | [docs/convention/error_handling.md](docs/convention/error_handling.md) |
|
||||
| **业务域文档索引** | [docs/features/README.md](docs/features/README.md) |
|
||||
| 货代发货通知 | [docs/features/shipping-notice/technical.md](docs/features/shipping-notice/technical.md) |
|
||||
| 文件检核 | [docs/features/file-check/technical.md](docs/features/file-check/technical.md) |
|
||||
| Agent 应用管理(设计) | [docs/platform/agent_application_management.md](platform/agent_application_management.md) |
|
||||
| Agent 应用管理(实现) | [docs/platform/agent_application_management_implementation.md](platform/agent_application_management_implementation.md) |
|
||||
+29
-46
@@ -1,21 +1,22 @@
|
||||
"""
|
||||
backend/app/__init__.py
|
||||
应用工厂:创建 Flask 应用、注册蓝图并挂载全局异常与响应处理。
|
||||
|
||||
用途:应用工厂:创建 Flask 应用、挂载全局异常与响应处理。
|
||||
依赖:app.extensions(db、migrate)、app.api.register_blueprints、app.core.config。
|
||||
逻辑:create_app 初始化扩展后委托 api 层集中注册 Blueprint;启动时 load_context_adapters 注册 Dify 上下文 adapter;
|
||||
并幂等补建 file-asset-cleanup 默认排程(覆盖空库先迁移后建用户)。
|
||||
"""
|
||||
import logging
|
||||
import uuid
|
||||
|
||||
from flask import Flask, jsonify, request, g
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
from flask_cors import CORS
|
||||
from werkzeug.exceptions import HTTPException
|
||||
from app.config import config
|
||||
from app.errors import AppError
|
||||
from app.response_utils import error_payload, utc_iso_now
|
||||
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
from app.core.config.settings import config
|
||||
from app.core.errors import AppError
|
||||
from app.extensions import db, migrate
|
||||
from app.core.response import error_payload, utc_iso_now
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -27,7 +28,7 @@ def _apply_persisted_settings(app: Flask) -> None:
|
||||
common case where the table does not yet exist (fresh deploy before
|
||||
``flask db upgrade`` runs).
|
||||
"""
|
||||
from app.env_persistence import apply_env_settings
|
||||
from app.core.config.env_persistence import apply_env_settings
|
||||
|
||||
try:
|
||||
applied = apply_env_settings()
|
||||
@@ -46,42 +47,9 @@ def create_app(config_name='default'):
|
||||
migrate.init_app(app, db)
|
||||
CORS(app) # 允许跨域
|
||||
|
||||
# 注册 Blueprints
|
||||
from app.api.chat import chat_bp
|
||||
from app.api.admin import admin_bp
|
||||
from app.api.agents import agents_bp
|
||||
from app.api.user import user_bp
|
||||
from app.api.knowledge_base import knowledge_base_bp
|
||||
from app.api.integration import integration_bp
|
||||
from app.api.schedule_admin import schedule_admin_bp
|
||||
from app.api.workspace_schedule import workspace_schedule_bp
|
||||
from app.api.workspace_shipping_notice import workspace_shipping_notice_bp
|
||||
from app.api.workspace_file_check import workspace_file_check_bp
|
||||
from app.api.internal_jobs import internal_jobs_bp
|
||||
from app.api.shipping_notice_tools import shipping_notice_bp
|
||||
from app.api.file_check_tools import file_check_bp
|
||||
from app.api.speech import speech_bp
|
||||
from app.api import register_blueprints
|
||||
|
||||
# 聊天相关接口
|
||||
app.register_blueprint(chat_bp, url_prefix='/api/chat')
|
||||
# 管理员相关接口
|
||||
app.register_blueprint(admin_bp, url_prefix='/api/admin')
|
||||
# 普通用户可见的 Agent 列表接口
|
||||
app.register_blueprint(agents_bp, url_prefix='/api/agents')
|
||||
# 当前用户相关接口(首页、常见问题等)
|
||||
app.register_blueprint(user_bp, url_prefix='/api/user')
|
||||
# 知识库数据清洗模块接口
|
||||
app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb')
|
||||
# 知识库外部集成接口(供外部系统按 Dify 映射反查源文件)
|
||||
app.register_blueprint(integration_bp, url_prefix='/api/integration')
|
||||
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(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')
|
||||
register_blueprints(app)
|
||||
|
||||
# Eagerly load persisted runtime settings so the very first request after
|
||||
# a worker boot already sees the admin-saved configuration (otherwise the
|
||||
@@ -89,12 +57,26 @@ def create_app(config_name='default'):
|
||||
# serve the defaults baked into config.py / the image).
|
||||
with app.app_context():
|
||||
_apply_persisted_settings(app)
|
||||
from app.services.agent_runtime_context.bootstrap import load_context_adapters
|
||||
load_context_adapters()
|
||||
from app.services.agent_registry.handlers.bootstrap import load_handlers
|
||||
load_handlers()
|
||||
from app.services.chat.intent_route_registry import ensure_intent_routes_loaded
|
||||
ensure_intent_routes_loaded()
|
||||
from app.services.schedule.scheduler_service import start_scheduler
|
||||
start_scheduler(app)
|
||||
# 空库先迁移后建用户:启动补建 + User commit 钩子即时补建,消除无排程窗口
|
||||
try:
|
||||
from app.services.file_assets.cleanup_schedule import (
|
||||
ensure_default_file_asset_cleanup_schedule,
|
||||
register_file_asset_cleanup_schedule_hooks,
|
||||
)
|
||||
register_file_asset_cleanup_schedule_hooks()
|
||||
ensure_default_file_asset_cleanup_schedule()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure file-asset-cleanup schedule: %s', exc)
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
FixedAssetsSnapshotService.start_worker(app)
|
||||
from app.cli.faq_commands import init_app as init_faq_cli
|
||||
init_faq_cli(app)
|
||||
|
||||
@app.before_request
|
||||
def _sync_persisted_settings():
|
||||
@@ -193,6 +175,7 @@ def create_app(config_name='default'):
|
||||
|
||||
@app.errorhandler(AppError)
|
||||
def _handle_app_error(exc: AppError):
|
||||
"""统一业务异常 → JSON error_payload(API 层应 raise AppError 而非 jsonify error)。"""
|
||||
_log_api_error(
|
||||
code=exc.code,
|
||||
message=exc.message,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/api/__init__.py
|
||||
|
||||
用途:集中注册所有 Blueprint(Wave 1 接入 create_app)。
|
||||
依赖:各 api 子包 blueprint。
|
||||
逻辑:替代 app/__init__.py 内 15 行散乱 register_blueprint。
|
||||
用途:集中注册所有 HTTP Blueprint。
|
||||
依赖:各 api 子模块 blueprint(单体或分包 re-export)。
|
||||
逻辑:create_app 唯一调用 register_blueprints(app);后续拆包只改本文件 import 来源。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -12,8 +12,8 @@ from flask import Flask
|
||||
|
||||
def register_blueprints(app: Flask) -> None:
|
||||
"""
|
||||
注册全部 HTTP Blueprint,保持对外 url_prefix 不变。
|
||||
核心逻辑:Wave 0 仍从既有单体模块 import;Wave 1+ 逐步切换至分包。
|
||||
注册全部 HTTP Blueprint,保持对外 url_prefix 与 Wave 0 之前一致。
|
||||
核心逻辑:集中管理路由挂载点;后续 api/user、api/chat 等分包迁移时仅改本函数 import 来源。
|
||||
Args:
|
||||
app: Flask 应用实例。
|
||||
"""
|
||||
@@ -22,31 +22,43 @@ def register_blueprints(app: Flask) -> None:
|
||||
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.maintenance import maintenance_bp
|
||||
from app.api.speech import speech_bp
|
||||
from app.api.training import training_admin_bp, training_user_bp
|
||||
from app.api.agent_runtime_context_tools import agent_runtime_context_bp
|
||||
|
||||
# [STEP 2] 已分包骨架(re-export 旧模块,Wave 1 可切换 import 来源)
|
||||
# [STEP 2] 已分包骨架(Wave 3:kb、schedule 等)
|
||||
from app.api.kb import knowledge_base_bp
|
||||
from app.api.schedule import schedule_admin_bp
|
||||
from app.api.workspace import (
|
||||
workspace_announcements_bp,
|
||||
workspace_file_check_bp,
|
||||
workspace_schedule_bp,
|
||||
workspace_shipping_notice_bp,
|
||||
)
|
||||
from app.api.tools import file_check_bp, shipping_notice_bp
|
||||
from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp
|
||||
from app.api.files import files_bp
|
||||
|
||||
app.register_blueprint(chat_bp, url_prefix='/api/chat')
|
||||
app.register_blueprint(admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(agents_bp, url_prefix='/api/agents')
|
||||
app.register_blueprint(user_bp, url_prefix='/api/user')
|
||||
app.register_blueprint(training_user_bp, url_prefix='/api/user')
|
||||
app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb')
|
||||
app.register_blueprint(integration_bp, url_prefix='/api/integration')
|
||||
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_announcements_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_file_check_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
|
||||
app.register_blueprint(maintenance_bp, url_prefix='/api/maintenance')
|
||||
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
|
||||
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
|
||||
app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context')
|
||||
app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance')
|
||||
app.register_blueprint(speech_bp, url_prefix='/api/speech')
|
||||
app.register_blueprint(training_admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(files_bp, url_prefix='/api/files')
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,23 @@
|
||||
"""
|
||||
backend/app/api/admin/__init__.py
|
||||
|
||||
用途:管理后台 Blueprint 入口(Wave 3 分包)。
|
||||
依赖:admin/blueprint.py 及各子模块路由。
|
||||
逻辑:import 子模块注册路由;register_blueprints 从本包 import admin_bp。
|
||||
"""
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
|
||||
import app.api.admin.dashboard # noqa: F401
|
||||
import app.api.admin.departments # noqa: F401
|
||||
import app.api.admin.agents # noqa: F401
|
||||
import app.api.admin.guides # noqa: F401
|
||||
import app.api.admin.quick_questions # noqa: F401
|
||||
import app.api.admin.faq_candidates # noqa: F401
|
||||
import app.api.admin.reports # noqa: F401
|
||||
import app.api.admin.database # noqa: F401
|
||||
import app.api.admin.permissions # noqa: F401
|
||||
import app.api.admin.users # noqa: F401
|
||||
import app.api.admin.wecom # noqa: F401
|
||||
import app.api.admin.announcements # noqa: F401
|
||||
|
||||
__all__ = ['admin_bp']
|
||||
@@ -0,0 +1,132 @@
|
||||
"""
|
||||
backend/app/api/admin/agents.py
|
||||
|
||||
用途:管理后台 Agent CRUD、连通性测试、权限绑定 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/agent_service、core.response.ok。
|
||||
逻辑:/agents* 路由;统一 success/data/request_id envelope。
|
||||
"""
|
||||
from flask import g, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.response import ok
|
||||
from app.services.admin import agent_service
|
||||
|
||||
|
||||
def _request_id() -> str | None:
|
||||
return getattr(g, 'request_id', None)
|
||||
|
||||
|
||||
@admin_bp.route('/agents/schema', methods=['GET'])
|
||||
@require_admin
|
||||
def get_agent_registry_schema():
|
||||
"""返回 Admin Agent Registry 权威 schema(平台枚举、Catalog、handler_config schema)。"""
|
||||
from app.services.agent_registry.admin_schema import build_agent_registry_schema
|
||||
|
||||
return ok(build_agent_registry_schema(), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/infer-content-profile', methods=['POST'])
|
||||
@require_admin
|
||||
def infer_agent_content_profile():
|
||||
"""根据 intent_routes 推断 content_profile(Admin 表单建议,不参与运行时)。"""
|
||||
from app.services.agent_registry.content_profiles import infer_content_profile_from_intent_routes
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
routes = data.get('intent_routes') if isinstance(data.get('intent_routes'), list) else []
|
||||
profile = infer_content_profile_from_intent_routes(routes)
|
||||
return ok({'content_profile': profile}, request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/type-catalog', methods=['GET'])
|
||||
@require_admin
|
||||
def list_agent_type_catalog():
|
||||
"""返回 Admin 应用类型 Catalog 下拉列表。"""
|
||||
from app.services.agent_registry.catalog import list_type_catalog
|
||||
|
||||
return ok(list_type_catalog(), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/content-profiles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_agent_content_profiles():
|
||||
"""返回 Admin 可选 content_profile 及默认文案模板。"""
|
||||
from app.services.agent_registry.content_profiles import list_content_profiles
|
||||
|
||||
return ok(list_content_profiles(), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/intent-routes', methods=['GET'])
|
||||
@require_admin
|
||||
def list_agent_intent_routes():
|
||||
"""返回 Admin 可选 Intent route 注册表(前端表单动态选项)。"""
|
||||
from app.services.chat.intent_route_registry import list_chat_intent_route_definitions
|
||||
|
||||
return ok(list_chat_intent_route_definitions(), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents', methods=['GET'])
|
||||
@require_admin
|
||||
def list_agents():
|
||||
"""返回全部 Agent 列表。"""
|
||||
return ok(agent_service.list_agents(), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents', methods=['POST'])
|
||||
@require_admin
|
||||
def create_agent():
|
||||
"""创建 Agent。"""
|
||||
data = request.get_json() or {}
|
||||
payload = agent_service.create_agent(data)
|
||||
return ok(payload, request_id=_request_id(), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_agent(id: int):
|
||||
"""更新 Agent。"""
|
||||
data = request.get_json() or {}
|
||||
agent_service.update_agent(id, data)
|
||||
return ok({'status': 'ok'}, request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_agent(id: int):
|
||||
"""删除 Agent。"""
|
||||
agent_service.delete_agent(id)
|
||||
return ok({'status': 'ok'}, request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/test', methods=['POST'])
|
||||
@require_admin
|
||||
def test_agent(id: int):
|
||||
"""测试 Agent 连通性。"""
|
||||
payload = agent_service.test_agent_connectivity(id)
|
||||
return ok(payload, request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/permissions', methods=['POST'])
|
||||
@require_admin
|
||||
def update_agent_permissions(id: int):
|
||||
"""设置 Agent 授权用户列表。"""
|
||||
data = request.get_json() or {}
|
||||
user_ids = data.get('user_ids', [])
|
||||
agent_service.update_agent_permissions(id, user_ids)
|
||||
return ok({'status': 'ok'}, request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/training-question-bank/import-pdf', methods=['POST'])
|
||||
@require_admin
|
||||
def import_training_question_bank_from_pdf(id: int):
|
||||
"""
|
||||
从已上传的培训试题 PDF 解析题库。
|
||||
|
||||
用途:给 Agent 管理表单提供“从试题 PDF 导入题库”入口,返回结构化题目供前端回填并继续人工微调。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = agent_service.import_training_question_bank_from_pdf(
|
||||
agent_id=id,
|
||||
guide_id=data.get('guide_id'),
|
||||
)
|
||||
return ok(payload, request_id=_request_id())
|
||||
@@ -0,0 +1,43 @@
|
||||
"""
|
||||
backend/app/api/admin/announcements.py
|
||||
|
||||
用途:管理后台公告 CRUD API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/announcement_service。
|
||||
逻辑:/announcements* 路由;工作台只读见 api/workspace/announcements.py。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import announcement_service
|
||||
|
||||
|
||||
@admin_bp.route('/announcements', methods=['GET'])
|
||||
@require_admin
|
||||
def list_announcements():
|
||||
"""列出全部公告(含 is_active)。"""
|
||||
return jsonify(announcement_service.list_announcements())
|
||||
|
||||
|
||||
@admin_bp.route('/announcements', methods=['POST'])
|
||||
@require_admin
|
||||
def create_announcement():
|
||||
"""创建公告。"""
|
||||
data = request.get_json() or {}
|
||||
payload = announcement_service.create_announcement(data)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@admin_bp.route('/announcements/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_announcement(id: int):
|
||||
"""更新公告。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(announcement_service.update_announcement(id, data))
|
||||
|
||||
|
||||
@admin_bp.route('/announcements/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_announcement(id: int):
|
||||
"""删除公告。"""
|
||||
return jsonify(announcement_service.delete_announcement(id))
|
||||
@@ -0,0 +1,10 @@
|
||||
"""
|
||||
backend/app/api/admin/blueprint.py
|
||||
|
||||
用途:管理后台 API 共享 Blueprint(Wave 3 分包后各子模块共用)。
|
||||
依赖:Flask Blueprint。
|
||||
逻辑:dashboard、departments、users、wecom 等子模块在此 bp 上注册路由;__init__ 导出 admin_bp。
|
||||
"""
|
||||
from flask import Blueprint
|
||||
|
||||
admin_bp = Blueprint('admin', __name__)
|
||||
@@ -0,0 +1,42 @@
|
||||
"""
|
||||
backend/app/api/admin/dashboard.py
|
||||
|
||||
用途:管理后台仪表盘 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/dashboard_service。
|
||||
逻辑:/dashboard* 路由。
|
||||
"""
|
||||
from flask import jsonify
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import dashboard_service
|
||||
|
||||
|
||||
@admin_bp.route('/dashboard/summary', methods=['GET'])
|
||||
@require_admin
|
||||
def dashboard_summary():
|
||||
"""
|
||||
管理后台仪表盘概览(供 Dashboard 页单次请求)。
|
||||
GET /api/admin/dashboard/summary
|
||||
"""
|
||||
return jsonify(dashboard_service.compute_dashboard_summary())
|
||||
|
||||
|
||||
@admin_bp.route('/dashboard/badges', methods=['GET'])
|
||||
@require_admin
|
||||
def dashboard_badges():
|
||||
"""
|
||||
管理后台侧栏待办角标(供 AdminLayout 轻量轮询/缓存刷新)。
|
||||
GET /api/admin/dashboard/badges
|
||||
"""
|
||||
return jsonify(dashboard_service.compute_dashboard_badges())
|
||||
|
||||
|
||||
@admin_bp.route('/dashboard', methods=['GET'])
|
||||
@require_admin
|
||||
def dashboard_stats():
|
||||
"""
|
||||
仪表盘统计(遗留接口;新代码请用 /dashboard/summary 与 /dashboard/badges)。
|
||||
GET /api/admin/dashboard
|
||||
"""
|
||||
return jsonify(dashboard_service.compute_legacy_dashboard_stats())
|
||||
@@ -0,0 +1,38 @@
|
||||
"""
|
||||
backend/app/api/admin/database.py
|
||||
|
||||
用途:管理后台数据表浏览 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/database_admin_service。
|
||||
逻辑:/database/* 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import database_admin_service
|
||||
|
||||
|
||||
def _query_params() -> dict[str, str]:
|
||||
return {k: str(v) for k, v in request.args.items()}
|
||||
|
||||
|
||||
@admin_bp.route('/database/<table>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_table_data(table: str):
|
||||
"""浏览指定表数据(最多 100 行)。"""
|
||||
return jsonify(database_admin_service.get_table_data(table, _query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/database/chat_logs/batch-delete', methods=['POST'])
|
||||
@require_admin
|
||||
def batch_delete_chat_logs():
|
||||
"""批量删除 chat_logs。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(database_admin_service.batch_delete_chat_logs(data.get('ids', [])))
|
||||
|
||||
|
||||
@admin_bp.route('/database/<table>/count', methods=['GET'])
|
||||
@require_admin
|
||||
def get_table_count(table: str):
|
||||
"""返回表行数。"""
|
||||
return jsonify(database_admin_service.get_table_count(table, _query_params()))
|
||||
@@ -0,0 +1,45 @@
|
||||
"""
|
||||
backend/app/api/admin/departments.py
|
||||
|
||||
用途:管理后台部门 CRUD API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/department_service。
|
||||
逻辑:/departments* 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import department_service
|
||||
|
||||
|
||||
@admin_bp.route('/departments', methods=['GET'])
|
||||
@require_admin
|
||||
def list_departments():
|
||||
"""返回全部部门列表。"""
|
||||
return jsonify(department_service.list_departments())
|
||||
|
||||
|
||||
@admin_bp.route('/departments', methods=['POST'])
|
||||
@require_admin
|
||||
def create_department():
|
||||
"""创建部门。"""
|
||||
data = request.get_json() or {}
|
||||
payload = department_service.create_department(data)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@admin_bp.route('/departments/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_department(id: int):
|
||||
"""更新部门。"""
|
||||
data = request.get_json() or {}
|
||||
department_service.update_department(id, data)
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
@admin_bp.route('/departments/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_department(id: int):
|
||||
"""删除部门。"""
|
||||
department_service.delete_department(id)
|
||||
return jsonify({'status': 'ok'})
|
||||
@@ -0,0 +1,50 @@
|
||||
"""
|
||||
backend/app/api/admin/faq_candidates.py
|
||||
|
||||
用途:热点 FAQ 候选管理 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/faq_service。
|
||||
逻辑:/faq-candidates* 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import faq_service
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates', methods=['GET'])
|
||||
@require_admin
|
||||
def list_faq_candidates():
|
||||
"""列出 PostgreSQL 热点 FAQ 候选。"""
|
||||
agent_id = request.args.get('agent_id', type=int)
|
||||
return jsonify(faq_service.list_faq_candidates(agent_id=agent_id))
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates/refresh', methods=['POST'])
|
||||
@require_admin
|
||||
def refresh_faq_candidates():
|
||||
"""手动触发离线热点聚合。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
agent_id = data.get('agent_id')
|
||||
dry_run = bool(data.get('dry_run'))
|
||||
if agent_id is not None:
|
||||
agent_id = int(agent_id)
|
||||
return jsonify(faq_service.refresh_faq_candidates(agent_id=agent_id, dry_run=dry_run))
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates/promote', methods=['POST'])
|
||||
@require_admin
|
||||
def promote_faq_candidate():
|
||||
"""将热点候选晋升为 QuickQuestion。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(faq_service.promote_faq_candidate(data))
|
||||
|
||||
|
||||
@admin_bp.route('/faq-candidates/dismiss', methods=['POST'])
|
||||
@require_admin
|
||||
def dismiss_faq_candidate():
|
||||
"""忽略热点 FAQ 候选。"""
|
||||
data = request.get_json() or {}
|
||||
agent_id = data.get('agent_id')
|
||||
q_norm = str(data.get('q_norm') or '')
|
||||
return jsonify(faq_service.dismiss_faq_candidate(agent_id=int(agent_id), q_norm=q_norm))
|
||||
@@ -0,0 +1,57 @@
|
||||
"""
|
||||
backend/app/api/admin/guides.py
|
||||
|
||||
用途:Agent 引导资料 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/guide_service。
|
||||
逻辑:/guides* 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import guide_service
|
||||
|
||||
|
||||
@admin_bp.route('/guides/upload', methods=['POST'])
|
||||
@require_admin
|
||||
def upload_guide():
|
||||
"""上传引导文件至 MinIO。"""
|
||||
file = request.files.get('file')
|
||||
return jsonify(guide_service.upload_guide_file(file))
|
||||
|
||||
|
||||
@admin_bp.route('/guides', methods=['POST'])
|
||||
@require_admin
|
||||
def create_guide():
|
||||
"""创建引导记录。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
current_user = get_current_user()
|
||||
payload = guide_service.create_guide(data, created_by_id=getattr(current_user, 'id', None))
|
||||
return jsonify(payload)
|
||||
|
||||
|
||||
@admin_bp.route('/guides', methods=['GET'])
|
||||
@require_admin
|
||||
def list_guides():
|
||||
"""列出引导资料,可按 agent_id 过滤。"""
|
||||
agent_id_raw = request.args.get('agent_id')
|
||||
agent_id = int(agent_id_raw) if agent_id_raw else None
|
||||
return jsonify(guide_service.list_guides(agent_id=agent_id))
|
||||
|
||||
|
||||
@admin_bp.route('/guides/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_guide(id: int):
|
||||
"""更新引导元数据。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
guide_service.update_guide(id, data)
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@admin_bp.route('/guides/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_guide(id: int):
|
||||
"""删除引导及 MinIO 文件。"""
|
||||
guide_service.delete_guide(id)
|
||||
return jsonify({'success': True})
|
||||
@@ -0,0 +1,49 @@
|
||||
"""
|
||||
backend/app/api/admin/permissions.py
|
||||
|
||||
用途:管理后台权限批量更新与权限申请审批 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/permission_service。
|
||||
逻辑:/permissions/*、/permission-requests/*、/users/<id>/permissions 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import permission_service
|
||||
|
||||
|
||||
@admin_bp.route('/permissions/batch', methods=['POST'])
|
||||
@require_admin
|
||||
def batch_update_permissions():
|
||||
"""批量更新用户 Agent 权限(add / remove / set)。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(permission_service.batch_update_permissions(data))
|
||||
|
||||
|
||||
@admin_bp.route('/users/<int:id>/permissions', methods=['POST'])
|
||||
@require_admin
|
||||
def update_user_permissions(id: int):
|
||||
"""将指定用户的 Agent 权限重置为请求体 agent_ids。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(permission_service.update_user_permissions(id, data))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-requests', methods=['GET'])
|
||||
@require_admin
|
||||
def list_permission_requests():
|
||||
"""列出全部权限申请。"""
|
||||
return jsonify(permission_service.list_permission_requests())
|
||||
|
||||
|
||||
@admin_bp.route('/permission-requests/<int:id>/approve', methods=['POST'])
|
||||
@require_admin
|
||||
def approve_request(id: int):
|
||||
"""批准权限申请。"""
|
||||
return jsonify(permission_service.approve_permission_request(id))
|
||||
|
||||
|
||||
@admin_bp.route('/permission-requests/<int:id>/reject', methods=['POST'])
|
||||
@require_admin
|
||||
def reject_request(id: int):
|
||||
"""拒绝权限申请。"""
|
||||
return jsonify(permission_service.reject_permission_request(id))
|
||||
@@ -0,0 +1,46 @@
|
||||
"""
|
||||
backend/app/api/admin/quick_questions.py
|
||||
|
||||
用途:全局常用问题 CRUD API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/faq_service。
|
||||
逻辑:/quick-questions* 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import faq_service
|
||||
|
||||
|
||||
@admin_bp.route('/quick-questions', methods=['GET'])
|
||||
@require_admin
|
||||
def list_quick_questions():
|
||||
"""列出全局常用问题,可选 stale_only 过滤。"""
|
||||
stale_only = str(request.args.get('stale_only', '')).lower() in {'1', 'true', 'yes'}
|
||||
return jsonify(faq_service.list_quick_questions(stale_only=stale_only))
|
||||
|
||||
|
||||
@admin_bp.route('/quick-questions', methods=['POST'])
|
||||
@require_admin
|
||||
def create_quick_question():
|
||||
"""创建全局常用问题。"""
|
||||
data = request.get_json() or {}
|
||||
payload = faq_service.create_quick_question(data)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@admin_bp.route('/quick-questions/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_quick_question(id: int):
|
||||
"""更新全局常用问题。"""
|
||||
data = request.get_json() or {}
|
||||
faq_service.update_quick_question(id, data)
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
@admin_bp.route('/quick-questions/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_quick_question(id: int):
|
||||
"""删除全局常用问题。"""
|
||||
faq_service.delete_quick_question(id)
|
||||
return jsonify({'status': 'ok'})
|
||||
@@ -0,0 +1,88 @@
|
||||
"""
|
||||
backend/app/api/admin/reports.py
|
||||
|
||||
用途:管理后台报表 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/report_service。
|
||||
逻辑:/reports/usage、/reports/applications、feedback 与 general-feedbacks 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import report_service
|
||||
|
||||
|
||||
def _query_params() -> dict[str, str]:
|
||||
return {k: str(v) for k, v in request.args.items()}
|
||||
|
||||
|
||||
@admin_bp.route('/reports/usage', methods=['GET'])
|
||||
@require_admin
|
||||
def usage_report():
|
||||
"""聊天使用分析报表(支持时间范围 range=7d|30d|90d|180d|365d)。"""
|
||||
try:
|
||||
user_page = int(request.args.get('user_page', 1))
|
||||
except (TypeError, ValueError):
|
||||
user_page = 1
|
||||
try:
|
||||
user_page_size = int(request.args.get('user_page_size', 10))
|
||||
except (TypeError, ValueError):
|
||||
user_page_size = 10
|
||||
range_key = request.args.get('range')
|
||||
return jsonify(
|
||||
report_service.build_usage_report(
|
||||
user_page=user_page,
|
||||
user_page_size=user_page_size,
|
||||
range_key=range_key,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/reports/applications', methods=['GET'])
|
||||
@require_admin
|
||||
def applications_report():
|
||||
"""
|
||||
应用运营报表:按应用聚合使用 / 权限 / 评分。
|
||||
Query: range, status, usage, q, sort, order, page, page_size。
|
||||
"""
|
||||
try:
|
||||
page = int(request.args.get('page', 1))
|
||||
except (TypeError, ValueError):
|
||||
page = 1
|
||||
try:
|
||||
page_size = int(request.args.get('page_size', 20))
|
||||
except (TypeError, ValueError):
|
||||
page_size = 20
|
||||
return jsonify(
|
||||
report_service.build_application_report(
|
||||
range_key=request.args.get('range'),
|
||||
status=request.args.get('status'),
|
||||
usage=request.args.get('usage'),
|
||||
q=request.args.get('q'),
|
||||
sort=request.args.get('sort'),
|
||||
order=request.args.get('order'),
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/reports/feedback', methods=['GET'])
|
||||
@require_admin
|
||||
def feedback_report():
|
||||
"""反馈评分分布报表。"""
|
||||
return jsonify(report_service.build_feedback_report())
|
||||
|
||||
|
||||
@admin_bp.route('/reports/general-feedbacks', methods=['GET'])
|
||||
@require_admin
|
||||
def list_general_feedbacks_report():
|
||||
"""通用反馈列表。"""
|
||||
return jsonify(report_service.list_general_feedbacks_report(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/reports/general-feedbacks/count', methods=['GET'])
|
||||
@require_admin
|
||||
def count_general_feedbacks_report():
|
||||
"""通用反馈计数。"""
|
||||
return jsonify(report_service.count_general_feedbacks_report(_query_params()))
|
||||
@@ -0,0 +1,82 @@
|
||||
"""
|
||||
backend/app/api/admin/users.py
|
||||
|
||||
用途:管理后台用户 CRUD API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/user_service、core.auth.jwt。
|
||||
逻辑:/users* 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.auth.jwt import get_current_user as _get_auth_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import user_service
|
||||
|
||||
|
||||
def _query_params() -> dict[str, str]:
|
||||
return {k: str(v) for k, v in request.args.items()}
|
||||
|
||||
|
||||
@admin_bp.route('/users', methods=['GET'])
|
||||
@require_admin
|
||||
def list_users():
|
||||
"""列出管理端用户(支持分页与筛选)。"""
|
||||
result = user_service.list_users(_query_params())
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@admin_bp.route('/users', methods=['POST'])
|
||||
@require_admin
|
||||
def create_user():
|
||||
"""创建用户并同步 Casdoor。"""
|
||||
data = request.get_json() or {}
|
||||
payload = user_service.create_user(data)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@admin_bp.route('/users/<int:id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_user(id: int):
|
||||
"""更新用户资料;有 password 时同步 Casdoor 改密。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(user_service.update_user(id, data))
|
||||
|
||||
|
||||
@admin_bp.route('/users/cleanup-rejected', methods=['POST'])
|
||||
@require_admin
|
||||
def cleanup_rejected_users():
|
||||
"""批量删除 status=rejected 的用户。"""
|
||||
return jsonify(user_service.cleanup_rejected_users())
|
||||
|
||||
|
||||
@admin_bp.route('/users/batch-delete', methods=['POST'])
|
||||
@require_admin
|
||||
def batch_delete_users():
|
||||
"""批量删除用户(排除当前登录管理员)。"""
|
||||
data = request.get_json() or {}
|
||||
current_user = _get_auth_user()
|
||||
current_user_id = current_user.id if current_user else None
|
||||
return jsonify(user_service.batch_delete_users(data.get('user_ids', []), current_user_id=current_user_id))
|
||||
|
||||
|
||||
@admin_bp.route('/users/<int:id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_user(id: int):
|
||||
"""删除单个用户。"""
|
||||
current_user = _get_auth_user()
|
||||
current_user_id = current_user.id if current_user else None
|
||||
return jsonify(user_service.delete_user(id, current_user_id=current_user_id))
|
||||
|
||||
|
||||
@admin_bp.route('/users/<int:id>/approve', methods=['POST'])
|
||||
@require_admin
|
||||
def approve_user(id: int):
|
||||
"""审批通过用户。"""
|
||||
return jsonify(user_service.approve_user(id))
|
||||
|
||||
|
||||
@admin_bp.route('/users/<int:id>/reject', methods=['POST'])
|
||||
@require_admin
|
||||
def reject_user(id: int):
|
||||
"""拒绝用户注册。"""
|
||||
return jsonify(user_service.reject_user(id))
|
||||
@@ -0,0 +1,118 @@
|
||||
"""
|
||||
backend/app/api/admin/wecom.py
|
||||
|
||||
用途:管理后台企微绑定、配置与诊断 API(薄路由层)。
|
||||
依赖:admin.blueprint、services/admin/wecom_admin_service。
|
||||
逻辑:/wecom/* 路由。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.admin import wecom_admin_service
|
||||
|
||||
|
||||
def _query_params() -> dict[str, str]:
|
||||
return {k: str(v) for k, v in request.args.items()}
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/debug-user-by-code', methods=['POST'])
|
||||
@require_admin
|
||||
def debug_wecom_user_by_code():
|
||||
"""通过 OAuth code 诊断企微用户匹配结果。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(wecom_admin_service.debug_user_by_code(data.get('code')))
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/bindings', methods=['GET'])
|
||||
@require_admin
|
||||
def list_wecom_bindings():
|
||||
"""分页列出企微绑定。"""
|
||||
return jsonify(wecom_admin_service.list_bindings(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/bind', methods=['POST'])
|
||||
@require_admin
|
||||
def bind_wecom_user():
|
||||
"""管理员手动绑定企微账号。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(wecom_admin_service.bind_user(data))
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/unbind', methods=['POST'])
|
||||
@require_admin
|
||||
def unbind_wecom_user():
|
||||
"""管理员解绑企微账号。"""
|
||||
data = request.get_json() or {}
|
||||
return jsonify(wecom_admin_service.unbind_user(data))
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/provision', methods=['POST'])
|
||||
@require_admin
|
||||
def provision_wecom_user():
|
||||
"""创建/更新用户并绑定企微、分配权限。"""
|
||||
data = request.get_json() or {}
|
||||
payload, status_code = wecom_admin_service.provision_user(data)
|
||||
return jsonify(payload), status_code
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/login-audits', methods=['GET'])
|
||||
@require_admin
|
||||
def get_wecom_login_audits():
|
||||
"""查询登录审计(企微/密码等来源)。"""
|
||||
return jsonify(wecom_admin_service.list_login_audits(_query_params()))
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/notify-settings', methods=['GET', 'PUT'])
|
||||
@require_admin
|
||||
def wecom_notify_settings():
|
||||
"""读取或更新企微通知配置。"""
|
||||
if request.method == 'GET':
|
||||
return jsonify(wecom_admin_service.serialize_notify_settings())
|
||||
data = request.get_json() or {}
|
||||
return jsonify(wecom_admin_service.update_notify_settings(data))
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/system-settings', methods=['GET', 'PUT'])
|
||||
@require_admin
|
||||
def wecom_system_settings():
|
||||
"""读取或更新企微 OAuth 系统配置。"""
|
||||
if request.method == 'GET':
|
||||
return jsonify(wecom_admin_service.serialize_system_settings())
|
||||
data = request.get_json() or {}
|
||||
return jsonify(wecom_admin_service.update_system_settings(data))
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/integration-manifest', methods=['GET'])
|
||||
@require_admin
|
||||
def wecom_integration_manifest():
|
||||
"""返回企微集成 manifest(回调 URL、OAuth 端点等)。"""
|
||||
return jsonify(
|
||||
wecom_admin_service.integration_manifest(
|
||||
host_url=request.host_url,
|
||||
host=request.host,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/notify-metrics', methods=['GET'])
|
||||
@require_admin
|
||||
def wecom_notify_metrics():
|
||||
"""企微通知发送/打开率指标(近 30 天)。"""
|
||||
return jsonify(wecom_admin_service.notify_metrics())
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/binding-stats', methods=['GET'])
|
||||
@require_admin
|
||||
def wecom_binding_stats():
|
||||
"""活跃用户企微绑定统计。"""
|
||||
return jsonify(wecom_admin_service.binding_stats())
|
||||
|
||||
|
||||
@admin_bp.route('/wecom/sync-userids', methods=['POST'])
|
||||
@require_admin
|
||||
def sync_wecom_userids_admin():
|
||||
"""从 OA 按工号同步 users.wecom_userid。"""
|
||||
data = request.get_json() or {}
|
||||
apply = bool(data.get('apply'))
|
||||
return jsonify(wecom_admin_service.sync_userids(apply=apply))
|
||||
@@ -0,0 +1,107 @@
|
||||
"""
|
||||
backend/app/api/agent_runtime_context_tools.py
|
||||
|
||||
用途:暴露 agent_runtime_context 只读 Tool API,供 Dify Chatflow 解析 HXOPS 上下文。
|
||||
依赖:app.core.errors、agent_runtime_context.parser/openapi_spec、shipping_notice.tool_api_url。
|
||||
逻辑:OpenAPI 文档接口放行;parse 工具复用 Authorization Bearer / X-Integration-Key 鉴权,不推进业务状态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request
|
||||
|
||||
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError
|
||||
from app.services.agent_runtime_context.openapi_spec import build_agent_runtime_context_openapi_spec
|
||||
from app.services.agent_runtime_context.parser import parse_agent_runtime_context
|
||||
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||
|
||||
agent_runtime_context_bp = Blueprint("agent_runtime_context_tools", __name__)
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验 agent_runtime_context Tool API 鉴权 Header。
|
||||
|
||||
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;Dify 请求 parse 工具时由 before_request 自动触发。
|
||||
|
||||
核心逻辑:只接受 Authorization Bearer 或 X-Integration-Key,复用 INTEGRATION_API_KEY 作为平台工具密钥。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 未配置 INTEGRATION_API_KEY。
|
||||
UnauthorizedError: 缺少或传入错误鉴权。
|
||||
"""
|
||||
configured = str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError("INTEGRATION_API_KEY is not configured", code="missing_auth")
|
||||
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||
if configured in {token, integration_key}:
|
||||
return
|
||||
if not token and not integration_key:
|
||||
raise UnauthorizedError("missing_auth")
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
"""
|
||||
归一化 Tool API 错误码。
|
||||
|
||||
核心逻辑:保持与 shipping/file-check Tool API 的 ok:false 响应风格一致,便于 Dify 侧统一处理。
|
||||
|
||||
Args:
|
||||
exc: 业务异常。
|
||||
|
||||
Returns:
|
||||
Tool 侧错误码。
|
||||
"""
|
||||
message = str(exc.message or "").strip()
|
||||
if message in {"missing_auth", "invalid_auth"}:
|
||||
return message
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
return "missing_auth"
|
||||
return exc.code
|
||||
|
||||
|
||||
@agent_runtime_context_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
"""把业务异常统一转成 Tool 侧约定的 JSON 结构。"""
|
||||
return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status
|
||||
|
||||
|
||||
@agent_runtime_context_bp.before_request
|
||||
def _verify_tool_access():
|
||||
"""
|
||||
对上下文解析 Tool 做统一 Header 鉴权。
|
||||
|
||||
核心逻辑:OpenAPI 导入文档无需鉴权;parse 工具必须携带平台 Tool Key。
|
||||
"""
|
||||
if request.path.endswith("/openapi.json"):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
@agent_runtime_context_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def openapi_spec():
|
||||
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
|
||||
return jsonify(build_agent_runtime_context_openapi_spec(resolve_tool_api_base_url()))
|
||||
|
||||
|
||||
@agent_runtime_context_bp.route("/tools/parse", methods=["POST"])
|
||||
def parse_context_tool():
|
||||
"""
|
||||
解析 agent_runtime_context 的白名单字段。
|
||||
|
||||
【AI 触发时机】:Dify 需要读取 HXOPS session/task/batch/run_purpose/state_hint 等上下文字段时调用;
|
||||
不用于推进业务状态。
|
||||
"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
return jsonify(
|
||||
parse_agent_runtime_context(
|
||||
payload.get("agent_runtime_context"),
|
||||
payload.get("paths"),
|
||||
)
|
||||
)
|
||||
+130
-48
@@ -1,64 +1,65 @@
|
||||
"""
|
||||
backend/app/api/agents.py
|
||||
文件用途:普通用户可见的 Agent 列表接口
|
||||
引用文件:flask, models, decorators
|
||||
逻辑关系:根据当前用户的权限返回其可访问的 Agent 集合
|
||||
|
||||
用途:普通用户可见的 Agent 列表与 AgentGuide 静态资源。
|
||||
依赖:app.core.auth.jwt、models、minio_service、agent_registry.serialization。
|
||||
逻辑:按当前用户 RBAC 返回可访问 Agent;列表统一 serialize_agent_for_user_list(结构化列为准)。
|
||||
"""
|
||||
import os
|
||||
from flask import Blueprint, jsonify, send_from_directory
|
||||
import mimetypes
|
||||
import re
|
||||
from flask import Blueprint, Response, jsonify, request, send_from_directory, stream_with_context
|
||||
|
||||
from app import db
|
||||
from app.decorators import _get_current_user # 内部工具函数
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError
|
||||
from app.models import Agent, User, AgentGuide
|
||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||
from app.services.minio_service import minio_service
|
||||
|
||||
# 定义 Blueprint,将在应用工厂中注册为 /api/agents
|
||||
agents_bp = Blueprint('agents', __name__)
|
||||
|
||||
|
||||
def _serialize_agent_row(row) -> dict:
|
||||
return {
|
||||
'id': row.id,
|
||||
'name': row.name,
|
||||
'description': row.description,
|
||||
'icon_url': row.icon_url,
|
||||
'dify_app_type': (row.extra_config or {}).get('dify_app_type') if hasattr(row, 'extra_config') else None,
|
||||
}
|
||||
def _serialize_agent_row(agent: Agent, *, visible_agent_ids: set[int] | None = None) -> dict:
|
||||
payload = serialize_agent_list_item(agent)
|
||||
if not bool(getattr(agent, 'is_aggregate', False)):
|
||||
return payload
|
||||
from app.services.agent_directory import serialize_directory_members
|
||||
|
||||
members = serialize_directory_members(agent.id, active_only=True)
|
||||
if visible_agent_ids is not None:
|
||||
members = [member for member in members if int(member.get('id') or 0) in visible_agent_ids]
|
||||
if members:
|
||||
payload['directory_members'] = members
|
||||
return payload
|
||||
|
||||
|
||||
def _list_active_agents_for_user(user: User) -> list[Agent]:
|
||||
"""返回用户可见的完整 Agent ORM 行(含 Registry 结构化列)。"""
|
||||
if user.role == 'admin':
|
||||
return (
|
||||
db.session.query(Agent)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.order_by(Agent.id.asc())
|
||||
.all()
|
||||
)
|
||||
return [agent for agent in user.agents if agent.is_active]
|
||||
|
||||
|
||||
@agents_bp.route('', methods=['GET'])
|
||||
def list_user_agents():
|
||||
"""
|
||||
获取当前用户可见的 Agent 列表
|
||||
用途:Workspace 页面展示应用网格
|
||||
用途:Workspace 页面展示应用网格、聊天侧栏 Agent 切换
|
||||
"""
|
||||
# 获取当前用户(目前固定为 admin 用户,用于演示)
|
||||
user: User = _get_current_user()
|
||||
user: User = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
|
||||
# 管理员:返回所有激活的 Agent
|
||||
if user.role == 'admin':
|
||||
agent_rows = (
|
||||
db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url, Agent.extra_config)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.order_by(Agent.id.asc())
|
||||
.all()
|
||||
)
|
||||
else:
|
||||
# 普通用户:仅返回多对多关系中已授权的 Agent
|
||||
agent_rows = [
|
||||
type('AgentRow', (), {
|
||||
'id': a.id,
|
||||
'name': a.name,
|
||||
'description': a.description,
|
||||
'icon_url': a.icon_url,
|
||||
'extra_config': a.extra_config,
|
||||
})()
|
||||
for a in user.agents
|
||||
if a.is_active
|
||||
]
|
||||
|
||||
# 序列化为前端所需字段
|
||||
return jsonify([_serialize_agent_row(row) for row in agent_rows])
|
||||
agents = _list_active_agents_for_user(user)
|
||||
visible_agent_ids = {agent.id for agent in agents}
|
||||
return jsonify([_serialize_agent_row(agent, visible_agent_ids=visible_agent_ids) for agent in sort_agent_rows(agents)])
|
||||
|
||||
@agents_bp.route('/<int:agent_id>/guides', methods=['GET'])
|
||||
def list_agent_guides(agent_id):
|
||||
@@ -66,10 +67,15 @@ def list_agent_guides(agent_id):
|
||||
获取指定应用的新手指南列表 (需登录)
|
||||
用途:客户端 Chat 界面点击新手指南
|
||||
"""
|
||||
_get_current_user() # 确保已登录
|
||||
get_current_user() # 确保已登录
|
||||
|
||||
if agent_id == 0:
|
||||
generic_agent = db.session.query(Agent).filter_by(name='通用入口').first()
|
||||
generic_agent = (
|
||||
db.session.query(Agent)
|
||||
.filter_by(agent_code='generic', is_active=True)
|
||||
.order_by(Agent.sort_order.asc(), Agent.id.asc())
|
||||
.first()
|
||||
)
|
||||
if generic_agent:
|
||||
agent_id = generic_agent.id
|
||||
else:
|
||||
@@ -88,6 +94,7 @@ def list_agent_guides(agent_id):
|
||||
'id': g.id,
|
||||
'file_name': g.file_name,
|
||||
'file_type': g.file_type,
|
||||
'guide_usage': g.guide_usage,
|
||||
'file_url': minio_service.get_public_url(g.file_path),
|
||||
'file_size': g.file_size,
|
||||
'remark': g.remark,
|
||||
@@ -101,18 +108,93 @@ def list_public_agents():
|
||||
获取公开的 Agent 列表 (无需登录)
|
||||
用途:登录页面展示
|
||||
"""
|
||||
# 返回所有激活的 Agent,包含基本信息
|
||||
agent_rows = (
|
||||
db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url, Agent.extra_config)
|
||||
agents = (
|
||||
db.session.query(Agent)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.order_by(Agent.id.asc())
|
||||
.all()
|
||||
)
|
||||
return jsonify([_serialize_agent_row(row) for row in agent_rows])
|
||||
visible_agent_ids = {agent.id for agent in agents}
|
||||
return jsonify([_serialize_agent_row(agent, visible_agent_ids=visible_agent_ids) for agent in sort_agent_rows(agents)])
|
||||
|
||||
def _parse_byte_range(range_header: str, file_size: int) -> tuple[int, int] | None:
|
||||
"""
|
||||
解析浏览器单段字节范围请求。
|
||||
|
||||
用途:iOS Safari/企业微信播放 MP4 时依赖 Range 请求,本函数将请求转换为闭区间。
|
||||
参数约束:仅接受单个 bytes 范围;无效或越界范围返回 None。
|
||||
"""
|
||||
match = re.fullmatch(r'bytes=(\d*)-(\d*)', range_header.strip())
|
||||
if not match or file_size <= 0:
|
||||
return None
|
||||
start_text, end_text = match.groups()
|
||||
if not start_text and not end_text:
|
||||
return None
|
||||
if start_text:
|
||||
start = int(start_text)
|
||||
end = int(end_text) if end_text else file_size - 1
|
||||
else:
|
||||
suffix_length = int(end_text)
|
||||
if suffix_length <= 0:
|
||||
return None
|
||||
start = max(file_size - suffix_length, 0)
|
||||
end = file_size - 1
|
||||
if start >= file_size or end < start:
|
||||
return None
|
||||
return start, min(end, file_size - 1)
|
||||
|
||||
|
||||
def _stream_minio_guide_file(filename: str) -> Response:
|
||||
"""
|
||||
以同源流式响应返回 MinIO 指南文件。
|
||||
|
||||
用途:消除生产 HTTPS 页面加载 HTTP MinIO 地址的混合内容问题,并支持 iOS 所需的 206 响应。
|
||||
参数约束:filename 为系统生成的 MinIO 对象名;响应流结束后必须释放连接。
|
||||
"""
|
||||
stat = minio_service.stat_file(filename)
|
||||
file_size = int(stat.size)
|
||||
content_type = stat.content_type or mimetypes.guess_type(filename)[0] or 'application/octet-stream'
|
||||
requested_range = request.headers.get('Range', '').strip()
|
||||
byte_range = _parse_byte_range(requested_range, file_size) if requested_range else None
|
||||
if requested_range and byte_range is None:
|
||||
return Response(status=416, headers={'Content-Range': f'bytes */{file_size}'})
|
||||
|
||||
start, end = byte_range or (0, file_size - 1)
|
||||
content_length = end - start + 1
|
||||
source = minio_service.open_file_stream(filename, offset=start, length=content_length)
|
||||
|
||||
def generate():
|
||||
try:
|
||||
while True:
|
||||
chunk = source.read(64 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
yield chunk
|
||||
finally:
|
||||
source.close()
|
||||
source.release_conn()
|
||||
|
||||
headers = {
|
||||
'Accept-Ranges': 'bytes',
|
||||
'Content-Length': str(content_length),
|
||||
'Cache-Control': 'private, max-age=3600',
|
||||
}
|
||||
status = 206 if byte_range else 200
|
||||
if byte_range:
|
||||
headers['Content-Range'] = f'bytes {start}-{end}/{file_size}'
|
||||
return Response(stream_with_context(generate()), status=status, headers=headers, content_type=content_type)
|
||||
|
||||
|
||||
# 为了兼容本地无MinIO的环境,暴露一个静态文件读取接口
|
||||
@agents_bp.route('/guides/files/<path:filename>', methods=['GET'])
|
||||
def serve_guide_file(filename):
|
||||
return send_from_directory(os.path.join(os.getcwd(), 'data', 'agent-guides'), filename)
|
||||
"""
|
||||
返回本地或 MinIO 中的指南文件。
|
||||
|
||||
用途:为 PDF、图片和培训视频提供统一同源地址;本地文件沿用 Flask 条件响应,MinIO 文件支持 Range。
|
||||
参数约束:filename 仅用于系统指南存储目录或 MinIO 指南桶,不接受任意外部路径。
|
||||
"""
|
||||
local_directory = os.path.join(os.getcwd(), 'data', 'agent-guides')
|
||||
if os.path.isfile(os.path.join(local_directory, filename)):
|
||||
return send_from_directory(local_directory, filename, conditional=True)
|
||||
return _stream_minio_guide_file(filename)
|
||||
|
||||
+339
-103
@@ -1,12 +1,15 @@
|
||||
"""
|
||||
backend/app/api/chat.py
|
||||
文件用途:定义聊天相关 API 路由
|
||||
引用文件:flask, services.dify, decorators, models
|
||||
逻辑关系:作为前端与 Dify 之间的 BFF 层,负责转发请求并流式返回结果
|
||||
|
||||
用途:聊天 BFF(SSE 流式、会话 CRUD、PLM/Excel 预览、反馈)。
|
||||
依赖:app.core.decorators、app.core.errors、services.dify、integrations。
|
||||
逻辑:/completions 按意图分流(Wave 3 抽至 services/chat/router.py);错误统一 raise AppError。
|
||||
"""
|
||||
import io
|
||||
import ipaddress
|
||||
import mimetypes
|
||||
import ntpath
|
||||
import posixpath
|
||||
import tempfile
|
||||
import os
|
||||
import subprocess
|
||||
@@ -19,22 +22,63 @@ import requests
|
||||
from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app, has_request_context
|
||||
from sqlalchemy import func, desc, or_, exists, and_
|
||||
from openpyxl import load_workbook
|
||||
from app.services.agent_runtime_context.dify_inputs import build_chat_dify_inputs
|
||||
from app.services.dify import DifyService
|
||||
from app.core.config.settings import Config
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
from app.decorators import require_agent_permission
|
||||
from app.core.decorators import require_agent_permission
|
||||
from app.models import Agent, ChatLog, ChatSession, Feedback
|
||||
from app import db
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
raise_for_status,
|
||||
)
|
||||
chat_bp = Blueprint('chat', __name__)
|
||||
|
||||
LEAVE_FEATURE_AGENT_NAMES = {'通用入口', '人事规章'}
|
||||
SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice'
|
||||
|
||||
|
||||
def _can_use_leave_feature(agent_proxy) -> bool:
|
||||
agent_name = str(getattr(agent_proxy, 'name', None) or '').strip()
|
||||
return agent_name in LEAVE_FEATURE_AGENT_NAMES
|
||||
PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip()
|
||||
|
||||
|
||||
def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_batch_no: str | None = None) -> dict | None:
|
||||
"""
|
||||
构建聊天入口分发给领域 adapter 的提示字典。
|
||||
|
||||
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示,
|
||||
统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。
|
||||
"""
|
||||
task_id = str(shipping_task_id or '').strip()
|
||||
batch_no = str(shipping_batch_no or '').strip()
|
||||
if not task_id and not batch_no:
|
||||
return None
|
||||
return {
|
||||
'shipping_notice': {
|
||||
'task_id': task_id or None,
|
||||
'batch_no': batch_no or None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def _should_reset_provider_conversation_for_asset_query(query: str, agent_proxy) -> bool:
|
||||
"""
|
||||
判断固资管理里的当前问题是否应当切断上游 Dify 会话上下文。
|
||||
|
||||
核心逻辑:
|
||||
- 仅对“固资管理”Agent 生效;
|
||||
- 仅当用户本轮问题可脱离上一轮上下文独立完成时触发;
|
||||
- 这样可以保留本地同一历史会话,又避免把上一轮超大结果继续带给上游模型,导致 context length 爆掉。
|
||||
"""
|
||||
from app.services.text2sql import Text2SQLService
|
||||
|
||||
return Text2SQLService._should_reset_provider_conversation(query, agent_proxy)
|
||||
|
||||
def _session_title_from_text(text: str) -> str:
|
||||
value = str(text or '').strip()
|
||||
if not value:
|
||||
@@ -42,6 +86,28 @@ def _session_title_from_text(text: str) -> str:
|
||||
return value[:30] + ('...' if len(value) > 30 else '')
|
||||
|
||||
|
||||
def _user_facing_chat_query(text: str, *, agent_code: str | None = None) -> str:
|
||||
"""
|
||||
将内部 Agent 编排提示转换成业务用户可见话术。
|
||||
|
||||
Args:
|
||||
text: chat_logs.query 中保存的用户侧文本。
|
||||
agent_code: 当前 Agent 应用类型;仅 shipping_notice 做工具名净化。
|
||||
Returns:
|
||||
可直接展示在聊天历史里的用户问题。
|
||||
"""
|
||||
value = str(text or '').strip()
|
||||
if not value or str(agent_code or '').strip() != SHIPPING_NOTICE_AGENT_CODE:
|
||||
return value
|
||||
import re
|
||||
|
||||
task_match = re.search(r'(SN-\d{8}-[A-Z0-9]+)', value, re.I)
|
||||
task_no = task_match.group(1).upper() if task_match else ''
|
||||
if 'create_task' in value or 'get_task_status' in value or 'parse_notice' in value:
|
||||
return f'继续处理当前发货任务 {task_no}'.strip()
|
||||
return value
|
||||
|
||||
|
||||
def _serialize_session(session: ChatSession) -> dict:
|
||||
last_active = session.last_active_at or session.created_at
|
||||
return {
|
||||
@@ -162,16 +228,60 @@ def _update_chat_session(
|
||||
return session
|
||||
|
||||
|
||||
def _normalize_windows_share_path(path_value: str) -> str:
|
||||
normalized = str(path_value or '').strip().strip('"').replace('/', '\\')
|
||||
if normalized.startswith('\\\\'):
|
||||
return '\\\\' + normalized[2:].rstrip('\\')
|
||||
return normalized.rstrip('\\')
|
||||
def _normalize_allowed_share_path(path_value: str) -> tuple[str, str]:
|
||||
"""
|
||||
统一归一化 Windows UNC / Windows 本地盘符 / Linux 挂载目录路径。
|
||||
|
||||
Returns:
|
||||
(path_kind, normalized_path)
|
||||
- path_kind: 'windows' | 'posix' | ''
|
||||
- normalized_path: 归一化后的绝对路径文本
|
||||
"""
|
||||
raw_value = str(path_value or '').strip().strip('"')
|
||||
if not raw_value:
|
||||
return ('', '')
|
||||
if raw_value.startswith('\\\\'):
|
||||
normalized = raw_value.replace('/', '\\')
|
||||
normalized = '\\\\' + normalized[2:].rstrip('\\')
|
||||
return ('windows', normalized)
|
||||
if len(raw_value) >= 3 and raw_value[1] == ':' and raw_value[2] in ('\\', '/'):
|
||||
normalized = ntpath.normpath(raw_value.replace('/', '\\')).rstrip('\\')
|
||||
return ('windows', normalized)
|
||||
if raw_value.startswith('/'):
|
||||
normalized = posixpath.normpath(raw_value.replace('\\', '/'))
|
||||
return ('posix', normalized.rstrip('/'))
|
||||
return ('', '')
|
||||
|
||||
def _is_path_within_allowed_root(target_path: str, root_path: str) -> bool:
|
||||
target_kind, normalized_target = _normalize_allowed_share_path(target_path)
|
||||
root_kind, normalized_root = _normalize_allowed_share_path(root_path)
|
||||
if not normalized_target or not normalized_root or target_kind != root_kind:
|
||||
return False
|
||||
if target_kind == 'windows':
|
||||
target_lower = normalized_target.lower()
|
||||
root_lower = normalized_root.lower()
|
||||
return target_lower == root_lower or target_lower.startswith(root_lower.rstrip('\\') + '\\')
|
||||
return normalized_target == normalized_root or normalized_target.startswith(normalized_root.rstrip('/') + '/')
|
||||
|
||||
def _is_allowed_share_path(target_url: str) -> bool:
|
||||
normalized_target = _normalize_windows_share_path(target_url)
|
||||
normalized_root = _normalize_windows_share_path(PLM_PREVIEW_SHARE_ROOT)
|
||||
return bool(normalized_root and normalized_target.startswith('\\\\') and normalized_target.lower().startswith(normalized_root.lower()))
|
||||
target_kind, normalized_target = _normalize_allowed_share_path(target_url)
|
||||
if not normalized_target:
|
||||
return False
|
||||
history_share_root = ''
|
||||
history_local_root = ''
|
||||
if has_request_context():
|
||||
history_share_root = str(current_app.config.get('FIXED_ASSET_HISTORY_SHARE_ROOT') or '').strip()
|
||||
history_local_root = str(current_app.config.get('FIXED_ASSET_HISTORY_LOCAL_ROOT') or '').strip()
|
||||
if not history_share_root:
|
||||
history_share_root = str(Config.FIXED_ASSET_HISTORY_SHARE_ROOT or '').strip()
|
||||
if not history_local_root:
|
||||
history_local_root = str(Config.FIXED_ASSET_HISTORY_LOCAL_ROOT or '').strip()
|
||||
roots = [
|
||||
PLM_PREVIEW_SHARE_ROOT,
|
||||
history_share_root,
|
||||
history_local_root,
|
||||
]
|
||||
return any(root and _is_path_within_allowed_root(normalized_target, root) for root in roots)
|
||||
|
||||
def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
"""
|
||||
@@ -226,7 +336,7 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
|
||||
import sqlalchemy as sa
|
||||
from urllib.parse import parse_qs
|
||||
if _is_allowed_share_path(file_url):
|
||||
normalized_path = _normalize_windows_share_path(file_url)
|
||||
_path_kind, normalized_path = _normalize_allowed_share_path(file_url)
|
||||
try:
|
||||
if not os.path.isfile(normalized_path):
|
||||
return (None, None, ('source file not found', 404))
|
||||
@@ -242,6 +352,16 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
|
||||
if _extract_placeholder_text(content):
|
||||
guessed_type = 'text/plain; charset=utf-8'
|
||||
return (content, guessed_type, None)
|
||||
try:
|
||||
from app.services.fixed_asset_image import FixedAssetImageService
|
||||
content, content_type, asset_image_err = FixedAssetImageService.fetch_preview_bytes(
|
||||
file_url,
|
||||
max_size=max_size,
|
||||
)
|
||||
if content is not None or asset_image_err is not None:
|
||||
return (content, content_type, asset_image_err)
|
||||
except Exception as exc:
|
||||
current_app.logger.warning('[file-preview] fixed asset image fetch failed url=%s err=%s', file_url, exc)
|
||||
headers = {}
|
||||
base_url = IntegrationApiService.get_base_url()
|
||||
api_key = IntegrationApiService.get_api_key()
|
||||
@@ -899,12 +1019,26 @@ def get_chat_messages():
|
||||
).order_by(ChatLog.created_at.asc()).all()
|
||||
|
||||
messages = []
|
||||
agent_code = str(getattr(g.current_agent, 'agent_code', '') or '').strip() or 'generic'
|
||||
for log in logs:
|
||||
if log.query:
|
||||
messages.append({'role': 'user', 'content': log.query})
|
||||
messages.append({'role': 'user', 'content': _user_facing_chat_query(log.query, agent_code=agent_code)})
|
||||
if (
|
||||
not log.answer
|
||||
and not log.message_type
|
||||
and not log.payload
|
||||
):
|
||||
continue
|
||||
if (
|
||||
log.query
|
||||
and log.answer == log.query
|
||||
and (not log.message_type or log.message_type == 'text')
|
||||
and not log.payload
|
||||
):
|
||||
continue
|
||||
assistant_msg = {
|
||||
'role': 'assistant',
|
||||
'content': log.answer,
|
||||
'content': DifyService._dedupe_exact_doubled_text(log.answer or ''),
|
||||
'chat_log_id': log.id,
|
||||
'retriever_resources': log.retriever_resources or [],
|
||||
'attribution_parts': log.attribution_parts or [],
|
||||
@@ -930,10 +1064,17 @@ def save_local_message():
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
|
||||
data = request.get_json() or {}
|
||||
conversation_id = (data.get('conversation_id') or '').strip()
|
||||
role = (data.get('role') or 'assistant').strip()
|
||||
message_type = data.get('type')
|
||||
content = data.get('content', '')
|
||||
payload = data.get('payload')
|
||||
user_query = data.get('query', '')
|
||||
if role == 'user':
|
||||
user_query = user_query or content
|
||||
content = ''
|
||||
else:
|
||||
# 本地生成的助手/表单消息不能携带 query;历史回放会把 query 渲染成用户气泡。
|
||||
user_query = ''
|
||||
|
||||
if not message_type:
|
||||
raise ValidationError('type is required')
|
||||
@@ -1047,6 +1188,71 @@ def get_chat_query_preview(chat_log_id: int):
|
||||
'query': query,
|
||||
})
|
||||
|
||||
|
||||
@chat_bp.route('/asset-history/search', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def search_asset_history_files():
|
||||
"""
|
||||
检索固定资产履历文件。
|
||||
|
||||
用途:聊天结果表格点击“资产编号”时,返回共享盘中的候选履历文件列表。
|
||||
约束:至少提供资产编号或资产名称之一;不直接返回文件内容,只返回预览所需路径元数据。
|
||||
"""
|
||||
asset_id = (request.args.get('asset_id') or '').strip()
|
||||
asset_name = (request.args.get('asset_name') or '').strip()
|
||||
limit = request.args.get('limit', type=int) or 20
|
||||
limit = max(1, min(limit, 50))
|
||||
|
||||
if not asset_id and not asset_name:
|
||||
raise ValidationError('asset_id or asset_name is required')
|
||||
|
||||
from app.services.fixed_asset_history import FixedAssetHistoryService
|
||||
|
||||
if not FixedAssetHistoryService.is_enabled():
|
||||
raise ServiceUnavailableError('asset history share is not configured')
|
||||
|
||||
items = FixedAssetHistoryService.search_history_files(
|
||||
asset_id=asset_id,
|
||||
asset_name=asset_name,
|
||||
limit=limit,
|
||||
)
|
||||
return jsonify({
|
||||
'asset_id': asset_id,
|
||||
'asset_name': asset_name,
|
||||
'total': len(items),
|
||||
'items': items,
|
||||
})
|
||||
|
||||
|
||||
@chat_bp.route('/asset-image/resolve', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def resolve_asset_image_preview():
|
||||
"""
|
||||
解析固定资产图片预览链接。
|
||||
|
||||
用途:聊天结果表格点击“图片 -> 查看”时,后端自动登录外部文档库并返回最佳图片的可预览元数据。
|
||||
约束:至少提供资产编号或资产名称之一;只返回当前最佳命中的单张图片,不向前端暴露文档库登录态。
|
||||
"""
|
||||
asset_id = (request.args.get('asset_id') or '').strip()
|
||||
asset_name = (request.args.get('asset_name') or '').strip()
|
||||
if not asset_id and not asset_name:
|
||||
raise ValidationError('asset_id or asset_name is required')
|
||||
|
||||
from app.services.fixed_asset_image import FixedAssetImageService
|
||||
|
||||
result = FixedAssetImageService.resolve_images(
|
||||
asset_id=asset_id,
|
||||
asset_name=asset_name,
|
||||
)
|
||||
return jsonify({
|
||||
'asset_id': asset_id,
|
||||
'asset_name': asset_name,
|
||||
'item': result.get('item'),
|
||||
'items': result.get('items', []),
|
||||
'total': result.get('total', 0),
|
||||
})
|
||||
|
||||
|
||||
@chat_bp.route('/completions', methods=['POST'])
|
||||
@require_agent_permission
|
||||
def chat_completions():
|
||||
@@ -1064,6 +1270,7 @@ def chat_completions():
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
query = data.get('query')
|
||||
display_query = str(data.get('display_query') or query or '').strip()
|
||||
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
|
||||
conversation_id = data.get('conversation_id')
|
||||
shipping_task_id = str(data.get('task_id') or '').strip()
|
||||
@@ -1078,26 +1285,45 @@ def chat_completions():
|
||||
current_app.logger.error("[chat-api] missing user/agent context user=%s agent=%s", bool(user), bool(agent))
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
|
||||
|
||||
from app.services.agent_registry.resolver import resolve_runtime_provider
|
||||
|
||||
if resolve_runtime_provider(agent) == 'iframe':
|
||||
raise ValidationError('Embedded iframe agents do not support chat completions')
|
||||
|
||||
user_id = getattr(user, 'id', None)
|
||||
agent_id = getattr(agent, 'id', None)
|
||||
|
||||
from types import SimpleNamespace
|
||||
from app.services.agent_directory import serialize_directory_members
|
||||
|
||||
is_aggregate = bool(getattr(agent, 'is_aggregate', False))
|
||||
directory_members = serialize_directory_members(agent_id, active_only=True) if is_aggregate else []
|
||||
agent_proxy = SimpleNamespace(
|
||||
id=agent_id,
|
||||
name=getattr(agent, 'name', None),
|
||||
type=getattr(agent, 'type', None),
|
||||
dify_api_key=getattr(agent, 'dify_api_key', None),
|
||||
api_base_url=getattr(agent, 'api_base_url', None),
|
||||
extra_config=getattr(agent, 'extra_config', None) or {},
|
||||
agent_code=getattr(agent, 'agent_code', None),
|
||||
runtime_provider=getattr(agent, 'runtime_provider', None),
|
||||
conversation_mode=getattr(agent, 'conversation_mode', None),
|
||||
dify_app_type=getattr(agent, 'dify_app_type', None),
|
||||
capabilities=getattr(agent, 'capabilities', None),
|
||||
bound_schedule_task_id=getattr(agent, 'bound_schedule_task_id', None),
|
||||
handler_config=getattr(agent, 'handler_config', None),
|
||||
is_aggregate=is_aggregate,
|
||||
directory_members=directory_members,
|
||||
)
|
||||
user_proxy = SimpleNamespace(
|
||||
id=user_id,
|
||||
username=getattr(user, 'username', None),
|
||||
employee_id=getattr(user, 'employee_id', None),
|
||||
real_name=getattr(user, 'real_name', None),
|
||||
role=getattr(user, 'role', None),
|
||||
)
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.services.plm_oracle import PLMOracleService
|
||||
|
||||
external_conversation_id = None
|
||||
if conversation_id:
|
||||
@@ -1107,22 +1333,35 @@ def chat_completions():
|
||||
user_id,
|
||||
agent_id,
|
||||
existing_session.session_id,
|
||||
title=query,
|
||||
title=display_query,
|
||||
status='running',
|
||||
)
|
||||
external_conversation_id = session.external_conversation_id
|
||||
if external_conversation_id and _should_reset_provider_conversation_for_asset_query(query, agent_proxy):
|
||||
current_app.logger.info(
|
||||
'[chat-api] reset provider conversation for asset query request_id=%s session_id=%s old_provider_conversation_id=%s query=%s',
|
||||
request_id,
|
||||
session.session_id,
|
||||
external_conversation_id,
|
||||
query,
|
||||
)
|
||||
session.external_conversation_id = None
|
||||
session.updated_at = datetime.utcnow()
|
||||
session.last_active_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
external_conversation_id = None
|
||||
else:
|
||||
session = _ensure_chat_session(
|
||||
user_id,
|
||||
agent_id,
|
||||
conversation_id,
|
||||
title=query,
|
||||
title=display_query,
|
||||
status='running',
|
||||
external_conversation_id=conversation_id,
|
||||
)
|
||||
external_conversation_id = session.external_conversation_id
|
||||
else:
|
||||
session = _ensure_chat_session(user_id, agent_id, None, title=query, status='running')
|
||||
session = _ensure_chat_session(user_id, agent_id, None, title=display_query, status='running')
|
||||
|
||||
normalized_files: list[dict] | None = None
|
||||
if files is not None:
|
||||
@@ -1151,93 +1390,69 @@ def chat_completions():
|
||||
if not normalized_files:
|
||||
normalized_files = None
|
||||
|
||||
if normalized_files and PLMOracleService.supports(query, agent_proxy):
|
||||
raise ValidationError('This route does not support attachments')
|
||||
from app.services.agent_registry.handlers.base import ChatStreamContext
|
||||
|
||||
relay_stream_ctx = ChatStreamContext(
|
||||
query=query,
|
||||
display_query=display_query,
|
||||
user=user_proxy,
|
||||
agent=agent_proxy,
|
||||
session=session,
|
||||
external_conversation_id=external_conversation_id,
|
||||
request_id=request_id,
|
||||
normalized_files=normalized_files,
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
),
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
kb_type=kb_type,
|
||||
)
|
||||
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
from app.services.chat.router import try_fast_route
|
||||
|
||||
leave_supported = HRLeaveSQLServerService.supports(query)
|
||||
leave_feature_enabled = _can_use_leave_feature(agent_proxy)
|
||||
|
||||
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,
|
||||
fast_route = try_fast_route(
|
||||
user=user_proxy,
|
||||
agent=agent_proxy,
|
||||
query=query,
|
||||
agent_id=agent_id,
|
||||
session_id=session.session_id,
|
||||
external_conversation_id=external_conversation_id,
|
||||
normalized_files=normalized_files,
|
||||
kb_type=kb_type,
|
||||
leave_supported=leave_supported,
|
||||
)
|
||||
if fast_route is not None:
|
||||
generator = fast_route.generator
|
||||
elif leave_supported:
|
||||
generator = DifyService.stream_chat(
|
||||
query,
|
||||
user_proxy,
|
||||
user_proxy.id,
|
||||
agent_proxy,
|
||||
external_conversation_id,
|
||||
request_id=request_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:
|
||||
raise ValidationError('This route does not support attachments')
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
elif leave_supported:
|
||||
generator = DifyService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, request_id=request_id, session_id=session.session_id, files=normalized_files)
|
||||
elif kb_type == 'ERP知识库':
|
||||
from app.services.text2sql import Text2SQLService
|
||||
if normalized_files:
|
||||
raise ValidationError('This route does not support attachments')
|
||||
generator = Text2SQLService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
else:
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
if HRLeaveSQLServerService.supports(query):
|
||||
if normalized_files:
|
||||
raise ValidationError('This route does not support attachments')
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
else:
|
||||
dify_inputs: dict[str, str] | None = None
|
||||
hxops_turn_id: str | None = None
|
||||
from app.services.file_check_tools.agent_resolver import (
|
||||
agent_declares_file_check_progress,
|
||||
is_file_check_chat_agent,
|
||||
)
|
||||
from app.services.file_check_tools.dify_inputs import build_file_check_dify_inputs
|
||||
from app.services.shipping_notice.dify_inputs import (
|
||||
build_dify_chat_inputs as build_shipping_notice_dify_inputs,
|
||||
is_shipping_notice_chat_agent,
|
||||
)
|
||||
declares_file_check = agent_declares_file_check_progress(agent_proxy)
|
||||
is_file_check_agent = is_file_check_chat_agent(agent_proxy)
|
||||
is_shipping_agent = is_shipping_notice_chat_agent(agent_proxy)
|
||||
if declares_file_check or is_file_check_agent:
|
||||
# [STEP 1] 先校验 task_id,避免 Dify Chatflow 缺参时长连接挂死
|
||||
dify_inputs = build_file_check_dify_inputs(agent_proxy, required=True)
|
||||
if is_file_check_agent:
|
||||
hxops_turn_id = uuid.uuid4().hex
|
||||
from app.services.file_check_tools.chat_turn_registry import register_file_check_chat_turn
|
||||
|
||||
register_file_check_chat_turn(
|
||||
turn_id=hxops_turn_id,
|
||||
session_id=session.session_id,
|
||||
user_id=user_proxy.id,
|
||||
agent_id=agent_proxy.id,
|
||||
query=query,
|
||||
)
|
||||
elif is_shipping_agent:
|
||||
# [STEP 2] 发货通知 Chatflow 依赖会话级 task/batch 上下文稳定定位当前任务
|
||||
dify_inputs = build_shipping_notice_dify_inputs(
|
||||
external_conversation_id or session.session_id,
|
||||
task_id=shipping_task_id,
|
||||
batch_no=shipping_batch_no,
|
||||
entry_mode="user_chat",
|
||||
user_message=query,
|
||||
trigger_source="frontend_chat",
|
||||
)
|
||||
generator = DifyService.stream_chat(
|
||||
query,
|
||||
user_proxy.id,
|
||||
files=normalized_files,
|
||||
inputs=build_chat_dify_inputs(
|
||||
agent_proxy,
|
||||
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,
|
||||
)
|
||||
request_id=request_id,
|
||||
trigger_source="frontend_chat",
|
||||
user_role=user_proxy.role,
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
),
|
||||
),
|
||||
)
|
||||
else:
|
||||
from app.services.chat.executors import stream_chat_via_executor
|
||||
|
||||
generator = stream_chat_via_executor(relay_stream_ctx)
|
||||
|
||||
def relay_stream():
|
||||
from app.services.chat_perf import chat_perf_enabled
|
||||
@@ -1254,6 +1469,15 @@ def chat_completions():
|
||||
|
||||
known_provider_conversation_id = session.external_conversation_id
|
||||
known_status = session.status
|
||||
emitted_handler_state_keys: set[str] = set()
|
||||
|
||||
from app.services.chat.stream_relay import (
|
||||
iter_handler_preface_sse,
|
||||
iter_handler_terminal_sse,
|
||||
)
|
||||
|
||||
for preface_line in iter_handler_preface_sse(relay_stream_ctx, emitted_keys=emitted_handler_state_keys):
|
||||
yield preface_line
|
||||
|
||||
try:
|
||||
for chunk in generator:
|
||||
@@ -1314,6 +1538,13 @@ def chat_completions():
|
||||
'total_relay_ms': relay_total_ms,
|
||||
}
|
||||
yield f"data: {json.dumps(event_data, ensure_ascii=False)}\n\n"
|
||||
if event_name in ('message_end', 'workflow_finished'):
|
||||
for terminal_line in iter_handler_terminal_sse(
|
||||
relay_stream_ctx,
|
||||
event_data,
|
||||
emitted_keys=emitted_handler_state_keys,
|
||||
):
|
||||
yield terminal_line
|
||||
except Exception as exc:
|
||||
current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, session.session_id)
|
||||
payload = {'event': 'error', 'message': str(exc), 'conversation_id': session.session_id, 'session_status': 'error'}
|
||||
@@ -1352,7 +1583,7 @@ def upload_chat_file():
|
||||
raise ValidationError('file is required')
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.config import Config
|
||||
from app.core.config.settings import Config
|
||||
|
||||
params = DifyService.get_app_parameters(agent, force_refresh=True)
|
||||
file_upload_cfg = (params or {}).get('file_upload') if isinstance(params, dict) else {}
|
||||
@@ -1905,3 +2136,8 @@ def preview_file_raw():
|
||||
resp.headers['X-Preview-Actual-Ext'] = ext or ''
|
||||
resp.headers['X-Preview-Original-Ext'] = original_ext or ''
|
||||
return resp
|
||||
|
||||
|
||||
from app.api.chat_turns import register_chat_turn_routes
|
||||
|
||||
register_chat_turn_routes(chat_bp)
|
||||
@@ -0,0 +1,162 @@
|
||||
"""
|
||||
backend/app/api/chat_turns.py
|
||||
|
||||
用途:Chat Turn 流式 API 路由(POST /api/chat/turns/stream)。
|
||||
依赖:app.core.decorators、ChatTurnRuntime、notice_upload、batch_from_notices、chat_bp。
|
||||
逻辑:支持 JSON 与 multipart(附件上传 + Turn);由 chat.py 注册到同一 Blueprint。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import uuid
|
||||
|
||||
from flask import Response, g, request, stream_with_context
|
||||
|
||||
from app.core.decorators import require_agent_permission
|
||||
from app.core.errors import AppError, ValidationError
|
||||
from app.services.chat.turn_runtime import ChatTurnRuntime
|
||||
|
||||
|
||||
def _parse_turn_body_and_files() -> tuple[dict, list]:
|
||||
"""
|
||||
解析 Chat Turn 请求体;multipart 时从 form 字段读取 JSON 与 files。
|
||||
|
||||
Returns:
|
||||
(body, uploads) — uploads 为 Werkzeug FileStorage 列表,JSON 请求时为空。
|
||||
"""
|
||||
content_type = str(request.content_type or "")
|
||||
if "multipart/form-data" in content_type:
|
||||
input_raw = request.form.get("input") or "{}"
|
||||
try:
|
||||
input_data = json.loads(input_raw)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValidationError("input must be valid JSON") from exc
|
||||
context_raw = request.form.get("context") or "{}"
|
||||
try:
|
||||
context_data = json.loads(context_raw) if context_raw else {}
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValidationError("context must be valid JSON") from exc
|
||||
agent_id = request.form.get("agent_id") or request.form.get("agentId")
|
||||
conversation_id = request.form.get("conversation_id") or request.form.get("conversationId")
|
||||
body: dict = {
|
||||
"agent_id": agent_id,
|
||||
"conversation_id": conversation_id,
|
||||
"input": input_data if isinstance(input_data, dict) else {},
|
||||
"context": context_data if isinstance(context_data, dict) else {},
|
||||
}
|
||||
uploads = request.files.getlist("files")
|
||||
if not uploads:
|
||||
single = request.files.get("file")
|
||||
if single:
|
||||
uploads = [single]
|
||||
return body, uploads
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
return body if isinstance(body, dict) else {}, []
|
||||
|
||||
|
||||
def _stage_upload_files(uploads: list) -> list[dict]:
|
||||
"""将 multipart 文件读入内存 staged 结构,供 handler 构造 FileStorage。"""
|
||||
staged: list[dict] = []
|
||||
for upload in uploads:
|
||||
if upload is None:
|
||||
continue
|
||||
data = upload.read() or b""
|
||||
if not data:
|
||||
continue
|
||||
staged.append({
|
||||
"filename": str(getattr(upload, "filename", None) or "upload"),
|
||||
"content_type": str(getattr(upload, "content_type", None) or ""),
|
||||
"data": data,
|
||||
})
|
||||
return staged
|
||||
|
||||
|
||||
def _inject_multipart_upload_payload(body: dict, uploads: list) -> None:
|
||||
"""
|
||||
将 multipart 附件写入 Turn input.payload。
|
||||
|
||||
- shipping.create_batch_from_notices:预检 notice_items
|
||||
- shipping.upload_inventory / shipping.replace_notice:staged 原始文件字节
|
||||
"""
|
||||
if not uploads:
|
||||
return
|
||||
input_block = body.get("input") if isinstance(body.get("input"), dict) else {}
|
||||
action_type = str(input_block.get("action_type") or input_block.get("actionType") or "").strip()
|
||||
payload = input_block.get("payload") if isinstance(input_block.get("payload"), dict) else {}
|
||||
payload = dict(payload)
|
||||
|
||||
if action_type == "shipping.create_batch_from_notices":
|
||||
from app.services.shipping_notice.batch_from_notices import intake_notice_uploads_for_batch
|
||||
from app.services.shipping_notice.notice_upload import cleanup_temp_notice_uploads
|
||||
|
||||
temp_request_id = uuid.uuid4().hex
|
||||
try:
|
||||
notice_items, file_summary = intake_notice_uploads_for_batch(temp_request_id, uploads)
|
||||
finally:
|
||||
cleanup_temp_notice_uploads(temp_request_id)
|
||||
if not notice_items:
|
||||
raise ValidationError(
|
||||
"未能从发货通知附件中抽取到可解析文本,请上传清晰版 PDF/文本后重试",
|
||||
details={"file_summary": file_summary},
|
||||
)
|
||||
payload["notice_items"] = notice_items
|
||||
payload["file_summary"] = file_summary
|
||||
conversation_id = str(body.get("conversation_id") or body.get("conversationId") or "").strip()
|
||||
if conversation_id:
|
||||
payload["conversation_id"] = conversation_id
|
||||
elif action_type in ("shipping.upload_inventory", "shipping.replace_notice"):
|
||||
staged = _stage_upload_files(uploads)
|
||||
if not staged:
|
||||
raise ValidationError("file is required")
|
||||
payload["_staged_files"] = staged
|
||||
else:
|
||||
return
|
||||
|
||||
input_block["payload"] = payload
|
||||
input_block["type"] = input_block.get("type") or "upload_followup"
|
||||
body["input"] = input_block
|
||||
|
||||
|
||||
def register_chat_turn_routes(chat_bp) -> None:
|
||||
"""将 Chat Turn 路由注册到 chat Blueprint。"""
|
||||
|
||||
@chat_bp.route('/turns/stream', methods=['POST'])
|
||||
@require_agent_permission
|
||||
def chat_turns_stream():
|
||||
"""
|
||||
统一 Chat Turn SSE 接口。
|
||||
|
||||
核心逻辑:解析 action/form_submit/upload_followup;multipart 时预检附件并注入 payload,
|
||||
经 ChatTurnRuntime 路由至 action handler,返回 run.started / step.* / message.* / run.completed。
|
||||
"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
if user is None or agent is None:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
|
||||
|
||||
body, uploads = _parse_turn_body_and_files()
|
||||
request_id = uuid.uuid4().hex[:12]
|
||||
# [STEP 1] multipart 附件必须在返回 SSE 前读完;生成器延迟执行时 request.files 可能已关闭。
|
||||
if uploads:
|
||||
_inject_multipart_upload_payload(body, uploads)
|
||||
|
||||
def relay_stream():
|
||||
yield from ChatTurnRuntime.stream(
|
||||
user=user,
|
||||
agent=agent,
|
||||
body=body,
|
||||
request_id=request_id,
|
||||
)
|
||||
|
||||
return Response(
|
||||
stream_with_context(relay_stream()),
|
||||
mimetype='text/event-stream',
|
||||
headers={
|
||||
'Cache-Control': 'no-cache',
|
||||
'Content-Type': 'text/event-stream; charset=utf-8',
|
||||
'Connection': 'keep-alive',
|
||||
'X-Accel-Buffering': 'no',
|
||||
},
|
||||
)
|
||||
@@ -17,16 +17,29 @@ from sqlalchemy import text
|
||||
|
||||
from app import db
|
||||
from app.api.workspace_file_check import serialize_file_judgement
|
||||
from app.errors import AppError, ConflictError, NotFoundError, ServiceUnavailableError, UnauthorizedError, ValidationError
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
)
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.file_check_tools.openapi_spec import build_file_check_openapi_spec
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE, resolve_hxops_user_facing_base_url
|
||||
from app.services.schedule import _build_srm_conn_str
|
||||
from app.services.schedule.query_service import get_run, serialize_run
|
||||
from app.services.schedule.srm_service import _fetch_records
|
||||
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
|
||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
|
||||
|
||||
try:
|
||||
import pyodbc # type: ignore
|
||||
except Exception: # pragma: no cover
|
||||
pyodbc = None
|
||||
|
||||
|
||||
file_check_bp = Blueprint("file_check_tools", __name__)
|
||||
|
||||
_EXCEL_TOKEN_SCOPES = {"file_check_excel", "file_schedule_excel"}
|
||||
@@ -34,13 +47,13 @@ _RUN_START_LOCK = threading.Lock()
|
||||
_TASK_LOCK_KEY_BASE = 8700000000
|
||||
|
||||
|
||||
def _tool_token_secret() -> str:
|
||||
return str(
|
||||
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
or current_app.config.get("SECRET_KEY")
|
||||
or "default-secret"
|
||||
).strip()
|
||||
def _download_token_secret() -> str:
|
||||
"""
|
||||
Excel 下载 JWT 签名密钥。
|
||||
|
||||
核心逻辑:与 Dify Tool API Key 分离,仅用 SECRET_KEY,避免 API Key 未配置时浏览器下载失败。
|
||||
"""
|
||||
return str(current_app.config.get("SECRET_KEY") or "default-secret").strip()
|
||||
|
||||
|
||||
def _decode_download_token(token: str | None) -> dict | None:
|
||||
@@ -50,7 +63,7 @@ def _decode_download_token(token: str | None) -> dict | None:
|
||||
try:
|
||||
import jwt
|
||||
|
||||
payload = jwt.decode(normalized, _tool_token_secret(), algorithms=["HS256"])
|
||||
payload = jwt.decode(normalized, _download_token_secret(), algorithms=["HS256"])
|
||||
return payload if isinstance(payload, dict) else None
|
||||
except Exception as exc:
|
||||
current_app.logger.warning("[file-check-tool] download token validation failed: %s", exc)
|
||||
@@ -58,6 +71,20 @@ def _decode_download_token(token: str | None) -> dict | None:
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验 Tool API 访问权限。
|
||||
|
||||
核心逻辑:Excel 下载仅校验 query token(浏览器场景);其余端点校验 Dify/RPA 的 Tool API Key。
|
||||
"""
|
||||
# [STEP 1] 浏览器 Excel 下载:JWT token 独立于 Tool API Key
|
||||
if request.path.endswith("/excel"):
|
||||
query_token = str(request.args.get("token") or "").strip()
|
||||
if query_token:
|
||||
if _decode_download_token(query_token):
|
||||
return
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
# [STEP 2] Dify / RPA 服务端调用
|
||||
configured = str(
|
||||
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
@@ -70,13 +97,11 @@ def _require_tool_auth() -> None:
|
||||
)
|
||||
|
||||
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
api_token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||
if configured in {token, integration_key}:
|
||||
if configured in {api_token, integration_key}:
|
||||
return
|
||||
if request.path.endswith("/excel") and _decode_download_token(request.args.get("token")):
|
||||
return
|
||||
if not token and not integration_key:
|
||||
if not api_token and not integration_key:
|
||||
raise UnauthorizedError("missing_auth")
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
@@ -97,6 +122,8 @@ def _tool_error_code(exc: AppError) -> str:
|
||||
"dify_retrieve_failed",
|
||||
}:
|
||||
return message
|
||||
if exc.code == "data_source_unavailable":
|
||||
return "data_source_unavailable"
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
@@ -121,7 +148,8 @@ def _handle_tool_app_error(exc: AppError):
|
||||
|
||||
|
||||
def _public_base_url() -> str:
|
||||
return resolve_HXOPS_TOOLS_API_BASE()
|
||||
"""用户可见下载链基地址;与 Dify 调 Tool API 的内网基地址分离。"""
|
||||
return resolve_hxops_user_facing_base_url()
|
||||
|
||||
|
||||
def _acquire_task_start_lock(task_id: int) -> None:
|
||||
@@ -141,7 +169,7 @@ def _build_excel_download_url(run: ScheduleRun) -> str:
|
||||
"run_id": run.id,
|
||||
"exp": int(time.time()) + 600,
|
||||
}
|
||||
token = jwt.encode(payload, _tool_token_secret(), algorithm="HS256")
|
||||
token = jwt.encode(payload, _download_token_secret(), algorithm="HS256")
|
||||
return f"{_public_base_url()}/api/file-check/tools/runs/{run.id}/excel?token={token}"
|
||||
|
||||
|
||||
@@ -261,11 +289,31 @@ def _prepare_bind_payload(data: dict | None) -> dict:
|
||||
|
||||
def _record_run_bind(run: ScheduleRun, data: dict) -> None:
|
||||
from app.services.file_check_tools.chat_log_run_binding import merge_chat_log_bind_context
|
||||
from app.services.file_check_tools.chat_tool_run_binding import (
|
||||
_has_ambiguous_pending_turns,
|
||||
bind_schedule_run,
|
||||
)
|
||||
from app.services.file_check_tools.chat_turn_registry import attach_run_to_turn
|
||||
|
||||
merge_chat_log_bind_context(run, data)
|
||||
turn_id = str(data.get("hxops_turn_id") or "").strip()
|
||||
if turn_id:
|
||||
session_id = str(data.get("hxops_session_id") or "").strip() or None
|
||||
user_message = str(data.get("user_message") or "").strip() or None
|
||||
bound = bind_schedule_run(
|
||||
schedule_run_id=int(run.id),
|
||||
turn_id=turn_id or None,
|
||||
session_id=session_id,
|
||||
user_message=user_message,
|
||||
schedule_task_id=int(run.schedule_task_id) if run.schedule_task_id else None,
|
||||
bind_source='tool_start',
|
||||
)
|
||||
ambiguous = _has_ambiguous_pending_turns(
|
||||
session_id=session_id,
|
||||
user_message=user_message,
|
||||
schedule_task_id=int(run.schedule_task_id) if run.schedule_task_id else None,
|
||||
)
|
||||
if bound or (not ambiguous and (turn_id or session_id)):
|
||||
merge_chat_log_bind_context(run, data)
|
||||
if bound and turn_id:
|
||||
attach_run_to_turn(turn_id, int(run.id))
|
||||
|
||||
|
||||
@@ -282,12 +330,30 @@ def _build_no_data_response(task: ScheduleTask) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _raise_data_source_unavailable(task: ScheduleTask, exc: Exception) -> None:
|
||||
"""
|
||||
将检核预检阶段的数据源连接/配置错误转为 Tool API 503。
|
||||
|
||||
核心逻辑:ODBC/SQL Server 不可用时返回 data_source_unavailable,避免 Dify 收到 500 后显示 maximum retries。
|
||||
"""
|
||||
current_app.logger.warning(
|
||||
"[file-check-tool] precheck data source unavailable task_id=%s error=%s",
|
||||
task.id,
|
||||
exc,
|
||||
exc_info=True,
|
||||
)
|
||||
raise ServiceUnavailableError(
|
||||
"检核数据源不可用,请检查排程 SQL 配置、SRM_SQLSERVER_* 环境变量及本机 ODBC 驱动",
|
||||
code="data_source_unavailable",
|
||||
) from exc
|
||||
|
||||
|
||||
def _precheck_no_data(task: ScheduleTask) -> dict | None:
|
||||
"""
|
||||
启动前预检当前任务是否存在待检资料。
|
||||
|
||||
核心逻辑:仅在数据库型检核任务上做轻量预检;若结果为空,则直接返回 no_data_to_check,
|
||||
避免创建空批次并向 ChatLog 回写 run_id。
|
||||
避免创建空批次并向 ChatLog 回写 run_id。数据源连接失败时抛 503 data_source_unavailable。
|
||||
"""
|
||||
if str(getattr(task, "data_source_type", "") or "database").lower() != "database":
|
||||
return None
|
||||
@@ -296,12 +362,19 @@ def _precheck_no_data(task: ScheduleTask) -> dict | None:
|
||||
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()
|
||||
try:
|
||||
if cfg.data_source and not cfg.data_source.is_empty():
|
||||
conn_str = cfg.data_source.build_connection_string()
|
||||
else:
|
||||
conn_str = _build_srm_conn_str()
|
||||
rows = _fetch_records(conn_str, cfg.fetch_sql)
|
||||
except RuntimeError as exc:
|
||||
_raise_data_source_unavailable(task, exc)
|
||||
except Exception as exc:
|
||||
if pyodbc is not None and isinstance(exc, pyodbc.Error):
|
||||
_raise_data_source_unavailable(task, exc)
|
||||
raise
|
||||
|
||||
rows = _fetch_records(conn_str, cfg.fetch_sql)
|
||||
if rows:
|
||||
return None
|
||||
return _build_no_data_response(task)
|
||||
@@ -364,9 +437,6 @@ def run_file_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)
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
"""
|
||||
backend/app/api/files/__init__.py
|
||||
|
||||
用途:平台级文件资产 API 包入口。
|
||||
依赖:files.assets。
|
||||
逻辑:register_blueprints 挂载 /api/files。
|
||||
"""
|
||||
|
||||
from app.api.files.assets import files_bp
|
||||
|
||||
__all__ = ['files_bp']
|
||||
@@ -0,0 +1,80 @@
|
||||
"""
|
||||
backend/app/api/files/assets.py
|
||||
|
||||
用途:通用文件资产上传、查询、删除与受控下载 API。
|
||||
依赖:file_assets.service、app.core.auth.jwt、app.core.response。
|
||||
逻辑:薄路由鉴权与参数校验;storage_key 不向前端返回。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
|
||||
from flask import Blueprint, g, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError
|
||||
from app.core.response import ok
|
||||
from app.services.file_assets.service import (
|
||||
delete_temporary_asset,
|
||||
get_asset_for_user,
|
||||
read_asset_bytes,
|
||||
serialize_asset_public,
|
||||
upload_file_asset,
|
||||
)
|
||||
|
||||
files_bp = Blueprint('files', __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
@files_bp.route('/assets', methods=['POST'])
|
||||
def upload_asset():
|
||||
"""上传文件并创建 FileAsset。"""
|
||||
user = _require_user()
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
raise ValidationError('file is required')
|
||||
if not upload.filename:
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
raise ValidationError('file is required')
|
||||
data = upload_file_asset(user_id=user.id, upload=upload)
|
||||
return ok(data, request_id=getattr(g, 'request_id', None), status=201)
|
||||
|
||||
|
||||
@files_bp.route('/assets/<asset_no>', methods=['GET'])
|
||||
def get_asset(asset_no: str):
|
||||
"""查询当前用户的文件资产元数据。"""
|
||||
user = _require_user()
|
||||
asset = get_asset_for_user(asset_no, user.id)
|
||||
return ok(serialize_asset_public(asset), request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@files_bp.route('/assets/<asset_no>', methods=['DELETE'])
|
||||
def delete_asset(asset_no: str):
|
||||
"""逻辑删除未引用的临时资产。"""
|
||||
user = _require_user()
|
||||
delete_temporary_asset(asset_no=asset_no, user_id=user.id)
|
||||
return ok({'deleted': True}, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@files_bp.route('/assets/<asset_no>/download', methods=['GET'])
|
||||
def download_asset(asset_no: str):
|
||||
"""鉴权后流式下载文件内容。"""
|
||||
user = _require_user()
|
||||
asset = get_asset_for_user(asset_no, user.id)
|
||||
data = read_asset_bytes(asset)
|
||||
return send_file(
|
||||
io.BytesIO(data),
|
||||
mimetype=asset.mime_type or 'application/octet-stream',
|
||||
as_attachment=True,
|
||||
download_name=asset.original_filename,
|
||||
)
|
||||
@@ -9,7 +9,16 @@ from sqlalchemy import func
|
||||
from sqlalchemy.orm import joinedload
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
raise_for_status,
|
||||
)
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
integration_bp = Blueprint('integration', __name__)
|
||||
|
||||
|
||||
@@ -1,117 +1,114 @@
|
||||
"""
|
||||
backend/app/api/internal_jobs.py
|
||||
|
||||
用途:平台内置 Job 内部 API(POST /api/internal/jobs/<job_key>)。
|
||||
依赖:job_registry、schedule_contract、scheduler_service。
|
||||
逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.schedule import _run_generic_check_job
|
||||
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
from app.services.schedule.job_registry import get_platform_job, run_platform_job
|
||||
from app.services.schedule.schedule_contract import normalize_job_key
|
||||
from app.services.schedule.scheduler_service import _generate_run_no
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import (
|
||||
apply_deferred_schedule_run_state,
|
||||
recover_stale_awaiting_rpa_schedule_runs,
|
||||
should_defer_schedule_run_finalization,
|
||||
)
|
||||
|
||||
internal_jobs_bp = Blueprint('internal_jobs', __name__)
|
||||
|
||||
@internal_jobs_bp.route('/<name>', methods=['POST'])
|
||||
def run_internal_job(name: str):
|
||||
key = name.strip().lower()
|
||||
data = request.get_json(silent=True) or {}
|
||||
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,
|
||||
def _assert_task_matches_job_key(task: ScheduleTask, job_key: str) -> None:
|
||||
"""
|
||||
校验 task 与 URL job key 一致,防止 schedule_task_id 指向错误 handler。
|
||||
Raises:
|
||||
ValidationError: 非 platform_job 或 platform_api_path 不匹配
|
||||
"""
|
||||
if task.schedule_type != 'platform_job':
|
||||
raise ValidationError(f"schedule_task_id {task.id} is not a platform_job task")
|
||||
task_key = normalize_job_key(task.platform_api_path)
|
||||
if task_key != job_key:
|
||||
raise ValidationError(
|
||||
f"schedule_task_id {task.id} platform_api_path '{task.platform_api_path}' "
|
||||
f"does not match job key '{job_key}'"
|
||||
)
|
||||
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()
|
||||
|
||||
|
||||
def _resolve_schedule_task_and_run(job_key: str, data: dict) -> tuple[ScheduleTask, ScheduleRun]:
|
||||
"""
|
||||
解析或创建 ScheduleTask / ScheduleRun。
|
||||
核心逻辑:优先 schedule_task_id(须匹配 job key);否则按 platform_api_path 匹配 job key。
|
||||
run_no 查询限定 schedule_task_id,避免跨任务写入。
|
||||
"""
|
||||
schedule_task_id = data.get('schedule_task_id')
|
||||
task = None
|
||||
if schedule_task_id:
|
||||
task = db.session.get(ScheduleTask, int(schedule_task_id))
|
||||
if not task and key.isdigit():
|
||||
task = db.session.get(ScheduleTask, int(key))
|
||||
task = db.session.get(ScheduleTask, int(schedule_task_id)) if schedule_task_id else None
|
||||
if task:
|
||||
_assert_task_matches_job_key(task, job_key)
|
||||
else:
|
||||
task = (
|
||||
ScheduleTask.query.filter(
|
||||
ScheduleTask.platform_api_path == job_key,
|
||||
ScheduleTask.schedule_type == 'platform_job',
|
||||
)
|
||||
.order_by(ScheduleTask.id.desc())
|
||||
.first()
|
||||
)
|
||||
if not task:
|
||||
task = ScheduleTask.query.filter(ScheduleTask.platform_api_path.ilike(f'%{key}%')).first()
|
||||
if not task:
|
||||
raise NotFoundError(f"No schedule task found for '{name}'")
|
||||
raise NotFoundError(f"No schedule task found for platform job '{job_key}'")
|
||||
|
||||
run_no = str(data.get('run_no') or '').strip()
|
||||
run = None
|
||||
if run_no:
|
||||
run = ScheduleRun.query.filter_by(run_no=run_no).first()
|
||||
run = ScheduleRun.query.filter_by(run_no=run_no, schedule_task_id=task.id).first()
|
||||
if not run:
|
||||
foreign = ScheduleRun.query.filter_by(run_no=run_no).first()
|
||||
if foreign and foreign.schedule_task_id != task.id:
|
||||
raise ValidationError(
|
||||
f"run_no '{run_no}' belongs to schedule_task_id {foreign.schedule_task_id}, "
|
||||
f"not {task.id}"
|
||||
)
|
||||
if not run:
|
||||
from app.services.schedule.scheduler_service import _generate_run_no
|
||||
run = ScheduleRun(run_no=run_no or _generate_run_no(), schedule_task_id=task.id, trigger_type='api', started_at=datetime.utcnow(), status='running')
|
||||
run = ScheduleRun(
|
||||
run_no=run_no or _generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
trigger_type='api',
|
||||
started_at=datetime.utcnow(),
|
||||
status='running',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
if not run.dify_execution_snapshot:
|
||||
capture_dify_execution_snapshot(run, task)
|
||||
db.session.commit()
|
||||
try:
|
||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_generic_check_job(task, run)
|
||||
except Exception as exc:
|
||||
run.status = 'failed'
|
||||
run.error_message = str(exc)
|
||||
run.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message=str(exc), http_status=500, details={'traceback': traceback.format_exc(), 'summary': {'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 0}})
|
||||
run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed'
|
||||
return task, run
|
||||
|
||||
|
||||
def _finalize_run(
|
||||
run: ScheduleRun,
|
||||
*,
|
||||
total_count: int,
|
||||
success_count: int,
|
||||
failed_count: int,
|
||||
skipped_count: int,
|
||||
step_logs: list | None,
|
||||
) -> None:
|
||||
"""写入 run 汇总字段并 commit。"""
|
||||
run.status = (
|
||||
'success' if failed_count == 0
|
||||
else 'failed' if success_count == 0
|
||||
else 'partial_failed'
|
||||
)
|
||||
run.total_count = total_count
|
||||
run.success_count = success_count
|
||||
run.failed_count = failed_count
|
||||
@@ -121,4 +118,87 @@ def run_internal_job(name: str):
|
||||
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000)
|
||||
run.step_logs = step_logs if step_logs else None
|
||||
db.session.commit()
|
||||
return jsonify({'summary': {'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'skipped_count': skipped_count}, 'details': details, 'errors': errors, 'step_logs': step_logs})
|
||||
|
||||
|
||||
@internal_jobs_bp.route('/<name>', methods=['POST'])
|
||||
def run_internal_job(name: str):
|
||||
"""
|
||||
执行已注册平台 Job。
|
||||
核心逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。
|
||||
"""
|
||||
key = normalize_job_key(name)
|
||||
data = request.get_json(silent=True) or {}
|
||||
|
||||
if not get_platform_job(key):
|
||||
raise NotFoundError(f"Unknown platform job: {name}")
|
||||
|
||||
task, run = _resolve_schedule_task_and_run(key, data)
|
||||
recover_stale_awaiting_rpa_schedule_runs(task)
|
||||
try:
|
||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = run_platform_job(
|
||||
key, task, run, data,
|
||||
)
|
||||
except Exception as exc:
|
||||
run.status = 'failed'
|
||||
run.error_message = str(exc)
|
||||
run.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
raise AppError(
|
||||
code='SYSTEM.HTTP_ERROR',
|
||||
message=str(exc),
|
||||
http_status=500,
|
||||
details={
|
||||
'traceback': traceback.format_exc(),
|
||||
'summary': {
|
||||
'total_count': 0,
|
||||
'success_count': 0,
|
||||
'failed_count': 0,
|
||||
'skipped_count': 0,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
if should_defer_schedule_run_finalization(task, step_logs):
|
||||
apply_deferred_schedule_run_state(
|
||||
run,
|
||||
task,
|
||||
total_count=total_count,
|
||||
success_count=success_count,
|
||||
failed_count=failed_count,
|
||||
skipped_count=skipped_count,
|
||||
details=details,
|
||||
errors=errors,
|
||||
step_logs=step_logs,
|
||||
)
|
||||
return jsonify({
|
||||
'summary': {
|
||||
'total_count': total_count,
|
||||
'success_count': success_count,
|
||||
'failed_count': failed_count,
|
||||
'skipped_count': skipped_count,
|
||||
},
|
||||
'details': details,
|
||||
'errors': errors,
|
||||
'step_logs': step_logs,
|
||||
'awaiting_rpa_callback': True,
|
||||
})
|
||||
|
||||
_finalize_run(
|
||||
run,
|
||||
total_count=total_count,
|
||||
success_count=success_count,
|
||||
failed_count=failed_count,
|
||||
skipped_count=skipped_count,
|
||||
step_logs=step_logs,
|
||||
)
|
||||
return jsonify({
|
||||
'summary': {
|
||||
'total_count': total_count,
|
||||
'success_count': success_count,
|
||||
'failed_count': failed_count,
|
||||
'skipped_count': skipped_count,
|
||||
},
|
||||
'details': details,
|
||||
'errors': errors,
|
||||
'step_logs': step_logs,
|
||||
})
|
||||
@@ -0,0 +1,16 @@
|
||||
"""
|
||||
backend/app/api/kb/__init__.py
|
||||
|
||||
用途:知识库管理 Blueprint 入口(Wave 3 分包)。
|
||||
依赖:kb/blueprint.py、common、dify、groups、documents、jobs。
|
||||
逻辑:import 子模块注册路由;register_blueprints 从本包 import knowledge_base_bp。
|
||||
"""
|
||||
from app.api.kb.blueprint import knowledge_base_bp
|
||||
|
||||
import app.api.kb.common # noqa: F401
|
||||
import app.api.kb.dify # noqa: F401
|
||||
import app.api.kb.groups # noqa: F401
|
||||
import app.api.kb.documents # noqa: F401
|
||||
import app.api.kb.jobs # noqa: F401
|
||||
|
||||
__all__ = ['knowledge_base_bp']
|
||||
@@ -0,0 +1,10 @@
|
||||
"""
|
||||
backend/app/api/kb/blueprint.py
|
||||
|
||||
用途:知识库 API 共享 Blueprint(Wave 3 分包后各子模块共用)。
|
||||
依赖:Flask Blueprint。
|
||||
逻辑:kb/dify、groups、documents、jobs 等子模块在此 bp 上注册路由;__init__ 导出 knowledge_base_bp。
|
||||
"""
|
||||
from flask import Blueprint
|
||||
|
||||
knowledge_base_bp = Blueprint('knowledge_base', __name__)
|
||||
@@ -0,0 +1,73 @@
|
||||
"""
|
||||
backend/app/api/kb/common.py
|
||||
|
||||
用途:知识库 API 共享 helper(鉴权、序列化、Markdown 预览)。
|
||||
依赖:app.core.*、models、services/kb/storage、edkb_system。
|
||||
逻辑:dify/groups/documents/jobs 子模块共用;存储读写见 services/kb/storage。
|
||||
"""
|
||||
from flask import current_app
|
||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError
|
||||
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup
|
||||
from app.services.kb.markdown import (
|
||||
markdown_unavailable_message,
|
||||
resolve_markdown_read_path,
|
||||
resolve_markdown_write_path,
|
||||
serialize_markdown_payload,
|
||||
)
|
||||
from app.services.kb.storage import (
|
||||
kb_storage_root,
|
||||
resolve_storage_path,
|
||||
safe_upload_filename,
|
||||
save_upload,
|
||||
)
|
||||
|
||||
def require_user():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
def run_db_read(label: str, loader):
|
||||
try:
|
||||
return loader()
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('[kb] transient db error during %s, retry with reconnect: %s', label, exc)
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
db.engine.dispose()
|
||||
except Exception:
|
||||
current_app.logger.warning('[kb] failed to dispose engine during %s recovery', label, exc_info=True)
|
||||
return loader()
|
||||
|
||||
def serialize_group(group: KbGroup, document_count: int=0):
|
||||
return {'id': group.id, 'name': group.name, 'description': group.description, 'department_id': group.department_id, 'document_count': int(document_count or 0), 'created_at': group.created_at.isoformat() if group.created_at else None, 'updated_at': group.updated_at.isoformat() if group.updated_at else None}
|
||||
|
||||
def serialize_document(doc: KbDocument):
|
||||
latest_version = current_version(doc)
|
||||
return {'id': doc.id, 'group_id': doc.group_id, 'title': doc.title, 'description': doc.description, 'status': doc.status, 'source_type': doc.source_type, 'created_at': doc.created_at.isoformat() if doc.created_at else None, 'updated_at': doc.updated_at.isoformat() if doc.updated_at else None, 'version_count': len(doc.versions) if getattr(doc, 'versions', None) else 0, 'latest_version': serialize_version(latest_version) if latest_version else None}
|
||||
|
||||
def serialize_version(version: KbDocumentVersion | None):
|
||||
if version is None:
|
||||
return None
|
||||
return {'id': version.id, 'document_id': version.document_id, 'version_no': version.version_no, 'status': version.status, 'is_current': version.is_current, 'source_file_name': version.source_file_name, 'source_file_ext': version.source_file_ext, 'source_file_size': version.source_file_size, 'sha256': version.sha256, 'cleaned_file_path': version.cleaned_file_path, 'cleaned_preview_path': version.cleaned_preview_path, 'error_message': version.error_message, 'created_at': version.created_at.isoformat() if version.created_at else None}
|
||||
|
||||
def serialize_sync_record(record: KbDifySyncRecord):
|
||||
return {'id': record.id, 'group_id': record.group_id, 'document_id': record.document_id, 'document_version_id': record.document_version_id, 'dataset_id': record.dataset_id, 'dataset_name': record.dataset_name, 'remote_document_id': record.remote_document_id, 'remote_document_name': record.remote_document_name, 'status': record.status, 'sync_hash': record.sync_hash, 'error_message': record.error_message, 'synced_at': record.synced_at.isoformat() if record.synced_at else None, 'updated_at': record.updated_at.isoformat() if record.updated_at else None}
|
||||
|
||||
def current_version(document: KbDocument | None) -> KbDocumentVersion | None:
|
||||
versions = list(getattr(document, 'versions', []) or [])
|
||||
if not versions:
|
||||
return None
|
||||
return next((item for item in versions if item.is_current), versions[0])
|
||||
|
||||
|
||||
def next_version_no(document: KbDocument) -> int:
|
||||
versions = list(getattr(document, 'versions', []) or [])
|
||||
if not versions:
|
||||
return 1
|
||||
return max((item.version_no for item in versions)) + 1
|
||||
@@ -0,0 +1,45 @@
|
||||
"""
|
||||
backend/app/api/kb/dify.py
|
||||
|
||||
用途:知识库 Dify 连接配置与健康检查 API。
|
||||
依赖:kb.blueprint、knowledge_cleaning.settings_service。
|
||||
逻辑:管理员读写 Dify 设置;GET /dify/health 探测远端 dataset。
|
||||
"""
|
||||
from flask import jsonify, request
|
||||
|
||||
from app.api.kb.blueprint import knowledge_base_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.knowledge_cleaning.settings_service import (
|
||||
get_kb_dify_health_payload,
|
||||
get_kb_dify_settings,
|
||||
save_kb_dify_settings,
|
||||
)
|
||||
|
||||
@knowledge_base_bp.route('/dify/settings', methods=['GET'])
|
||||
@require_admin
|
||||
def get_dify_settings():
|
||||
payload = get_kb_dify_settings()
|
||||
return jsonify(payload)
|
||||
|
||||
@knowledge_base_bp.route('/dify/settings', methods=['PATCH'])
|
||||
@require_admin
|
||||
def update_dify_settings():
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = save_kb_dify_settings(data)
|
||||
return jsonify(payload)
|
||||
|
||||
@knowledge_base_bp.route('/dify/health', methods=['GET'])
|
||||
@require_admin
|
||||
def get_dify_health():
|
||||
payload = get_kb_dify_health_payload()
|
||||
if payload['dify_api_configured'] and payload['dify_base_url']:
|
||||
try:
|
||||
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
|
||||
datasets = KbDifySyncService().list_datasets()
|
||||
payload['api']['reachable'] = True
|
||||
payload['api']['dataset_count'] = len(datasets)
|
||||
except Exception as exc:
|
||||
payload['api']['error'] = str(exc)
|
||||
else:
|
||||
payload['api']['error'] = 'Dify 连接尚未配置'
|
||||
return jsonify(payload)
|
||||
@@ -0,0 +1,113 @@
|
||||
"""
|
||||
backend/app/api/kb/documents.py
|
||||
|
||||
用途:知识库文档版本、Markdown、上传/清洗/同步 API(薄路由层)。
|
||||
依赖:kb.blueprint、kb.common、services/kb/document_service。
|
||||
逻辑:/documents* 与 /document-versions* 路由;业务见 document_service。
|
||||
"""
|
||||
from flask import jsonify, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.api.kb.blueprint import knowledge_base_bp
|
||||
from app.api.kb.common import require_user, serialize_document, serialize_sync_record, serialize_version
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.kb import document_service
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/versions', methods=['GET'])
|
||||
def list_document_versions(document_id: int):
|
||||
require_user()
|
||||
versions = document_service.list_document_versions(document_id)
|
||||
return jsonify([serialize_version(item) for item in versions])
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/document-versions/<int:version_id>/source-file', methods=['GET'])
|
||||
def get_document_version_source_file(version_id: int):
|
||||
require_user()
|
||||
source_path, filename = document_service.resolve_source_file_path(version_id)
|
||||
as_attachment = str(request.args.get('download') or '').strip() == '1'
|
||||
return send_file(source_path, as_attachment=as_attachment, download_name=filename)
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/sync-records', methods=['GET'])
|
||||
def list_document_sync_records(document_id: int):
|
||||
require_user()
|
||||
records = document_service.list_sync_records(document_id)
|
||||
return jsonify([serialize_sync_record(item) for item in records])
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/markdown', methods=['GET'])
|
||||
def get_document_markdown(document_id: int):
|
||||
require_user()
|
||||
return jsonify(document_service.read_markdown(document_id))
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/markdown', methods=['PATCH'])
|
||||
def update_document_markdown(document_id: int):
|
||||
current_user = require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = document_service.update_markdown(
|
||||
document_id,
|
||||
data.get('content'),
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify(payload)
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/upload', methods=['POST'])
|
||||
def upload_document_version(document_id: int):
|
||||
current_user = require_user()
|
||||
uploaded = request.files.get('file')
|
||||
payload = document_service.upload_new_version(
|
||||
document_id,
|
||||
uploaded,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/clean', methods=['POST'])
|
||||
@require_admin
|
||||
def submit_document_clean(document_id: int):
|
||||
current_user = get_current_user()
|
||||
payload, status_code = document_service.submit_clean(
|
||||
document_id,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
return jsonify(payload), status_code
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/sync', methods=['POST'])
|
||||
@require_admin
|
||||
def sync_document(document_id: int):
|
||||
current_user = get_current_user()
|
||||
payload = document_service.submit_sync(
|
||||
document_id,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
return jsonify(payload), 202
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>', methods=['PATCH'])
|
||||
def update_document(document_id: int):
|
||||
current_user = require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
document = document_service.update_metadata(
|
||||
document_id,
|
||||
data,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify(serialize_document(document))
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>', methods=['DELETE'])
|
||||
def delete_document(document_id: int):
|
||||
current_user = require_user()
|
||||
result = document_service.delete_document(
|
||||
document_id,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
return jsonify(result)
|
||||
@@ -0,0 +1,292 @@
|
||||
"""
|
||||
backend/app/api/kb/groups.py
|
||||
|
||||
用途:知识库分组 CRUD、组内文档列表与路径批量上传 API(薄路由)。
|
||||
依赖:kb.blueprint、kb.common、services/kb/path_upload_service、services/kb/job_lifecycle。
|
||||
逻辑:/groups* 与 /path-upload-jobs*;业务编排委托 path_upload_service。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import jsonify, request
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
from app import db
|
||||
from app.api.kb.blueprint import knowledge_base_bp
|
||||
from app.api.kb.common import require_user, run_db_read, serialize_document, serialize_group
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import KbDocument, KbGroup, KbJob
|
||||
from app.services.kb import path_upload_service
|
||||
from app.services.kb.job_lifecycle import cancel_active_kb_jobs_for_group, serialize_job
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups', methods=['GET'])
|
||||
def list_groups():
|
||||
require_user()
|
||||
document_counts = (
|
||||
db.session.query(KbDocument.group_id.label('group_id'), func.count(KbDocument.id).label('document_count'))
|
||||
.filter(KbDocument.is_deleted.is_(False))
|
||||
.group_by(KbDocument.group_id)
|
||||
.subquery()
|
||||
)
|
||||
rows = run_db_read(
|
||||
'list_groups',
|
||||
lambda: db.session.query(KbGroup, func.coalesce(document_counts.c.document_count, 0).label('document_count'))
|
||||
.outerjoin(document_counts, document_counts.c.group_id == KbGroup.id)
|
||||
.filter(KbGroup.is_active.is_(True))
|
||||
.order_by(KbGroup.updated_at.desc(), KbGroup.id.desc())
|
||||
.all(),
|
||||
)
|
||||
return jsonify([serialize_group(group, document_count) for group, document_count in rows])
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups', methods=['POST'])
|
||||
@require_admin
|
||||
def create_group():
|
||||
data = request.get_json(silent=True) or {}
|
||||
name = str(data.get('name') or '').strip()
|
||||
description = str(data.get('description') or '').strip() or None
|
||||
department_id = data.get('department_id')
|
||||
if not name:
|
||||
raise ValidationError('name is required')
|
||||
existing_query = db.session.query(KbGroup).filter(KbGroup.name == name, KbGroup.is_active.is_(True))
|
||||
if department_id is None:
|
||||
existing_query = existing_query.filter(KbGroup.department_id.is_(None))
|
||||
else:
|
||||
existing_query = existing_query.filter(KbGroup.department_id == department_id)
|
||||
if existing_query.first():
|
||||
raise ValidationError('知识库分组已存在')
|
||||
current_user = get_current_user()
|
||||
group = KbGroup(
|
||||
name=name,
|
||||
description=description,
|
||||
department_id=department_id,
|
||||
created_by_id=getattr(current_user, 'id', None),
|
||||
updated_by_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.add(group)
|
||||
db.session.commit()
|
||||
return jsonify(serialize_group(group, 0)), 201
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups/<int:group_id>', methods=['PATCH'])
|
||||
@require_admin
|
||||
def update_group(group_id: int):
|
||||
group = db.session.get(KbGroup, group_id)
|
||||
if not group or not group.is_active:
|
||||
raise NotFoundError('知识库分组不存在')
|
||||
data = request.get_json(silent=True) or {}
|
||||
name = str(data.get('name') or group.name).strip()
|
||||
description = data.get('description')
|
||||
department_id = data.get('department_id', group.department_id)
|
||||
if not name:
|
||||
raise ValidationError('name is required')
|
||||
existing_query = db.session.query(KbGroup).filter(
|
||||
KbGroup.id != group.id,
|
||||
KbGroup.name == name,
|
||||
KbGroup.is_active.is_(True),
|
||||
)
|
||||
if department_id is None:
|
||||
existing_query = existing_query.filter(KbGroup.department_id.is_(None))
|
||||
else:
|
||||
existing_query = existing_query.filter(KbGroup.department_id == department_id)
|
||||
if existing_query.first():
|
||||
raise ValidationError('知识库分组已存在')
|
||||
current_user = get_current_user()
|
||||
group.name = name
|
||||
group.description = str(description).strip() or None if description is not None else None
|
||||
group.department_id = department_id
|
||||
group.updated_by_id = getattr(current_user, 'id', None)
|
||||
db.session.commit()
|
||||
document_count = db.session.query(func.count(KbDocument.id)).filter(
|
||||
KbDocument.group_id == group.id,
|
||||
KbDocument.is_deleted.is_(False),
|
||||
).scalar()
|
||||
return jsonify(serialize_group(group, document_count))
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups/<int:group_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_group(group_id: int):
|
||||
group = db.session.get(KbGroup, group_id)
|
||||
if not group or not group.is_active:
|
||||
raise NotFoundError('知识库分组不存在')
|
||||
current_user = get_current_user()
|
||||
group.is_active = False
|
||||
group.updated_by_id = getattr(current_user, 'id', None)
|
||||
cancel_active_kb_jobs_for_group(group.id, '知识库分组已删除,后台任务已取消')
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True, 'id': group_id})
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups/<int:group_id>/files', methods=['GET'])
|
||||
def list_group_files(group_id: int):
|
||||
require_user()
|
||||
group = run_db_read('get_group_for_files', lambda: db.session.get(KbGroup, group_id))
|
||||
if not group or not group.is_active:
|
||||
raise NotFoundError('Knowledge base group not found')
|
||||
documents = run_db_read(
|
||||
'list_group_files',
|
||||
lambda: db.session.query(KbDocument)
|
||||
.options(joinedload(KbDocument.versions))
|
||||
.filter(KbDocument.group_id == group_id, KbDocument.is_deleted.is_(False))
|
||||
.order_by(KbDocument.updated_at.desc(), KbDocument.id.desc())
|
||||
.all(),
|
||||
)
|
||||
return jsonify([serialize_document(doc) for doc in documents])
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups/<int:group_id>/files', methods=['POST'])
|
||||
def create_group_file(group_id: int):
|
||||
current_user = require_user()
|
||||
path_upload_service.require_active_group(group_id)
|
||||
data = request.get_json(silent=True) or {}
|
||||
title = str(data.get('title') or '').strip()
|
||||
description = str(data.get('description') or '').strip() or None
|
||||
status = str(data.get('status') or 'draft').strip() or 'draft'
|
||||
if not title:
|
||||
raise ValidationError('title is required')
|
||||
existing = (
|
||||
db.session.query(KbDocument)
|
||||
.options(joinedload(KbDocument.versions))
|
||||
.filter(KbDocument.group_id == group_id, KbDocument.title == title)
|
||||
.first()
|
||||
)
|
||||
if existing and not existing.is_deleted:
|
||||
raise ValidationError('当前分组下已存在同名文档')
|
||||
if existing and existing.is_deleted:
|
||||
existing.is_deleted = False
|
||||
existing.description = description
|
||||
existing.status = status
|
||||
existing.updated_by_id = getattr(current_user, 'id', None)
|
||||
db.session.commit()
|
||||
return jsonify(serialize_document(existing)), 201
|
||||
document = KbDocument(
|
||||
group_id=group_id,
|
||||
title=title,
|
||||
description=description,
|
||||
status=status,
|
||||
source_type='manual',
|
||||
created_by_id=getattr(current_user, 'id', None),
|
||||
updated_by_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.commit()
|
||||
return jsonify(serialize_document(document)), 201
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/groups/<int:group_id>/path-upload-jobs', methods=['POST'])
|
||||
def create_path_upload_job(group_id: int):
|
||||
current_user = require_user()
|
||||
path_upload_service.require_active_group(group_id)
|
||||
job, reused = path_upload_service.create_path_upload_job(
|
||||
group_id,
|
||||
request.get_json(silent=True) or {},
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
payload = serialize_job(job)
|
||||
if reused:
|
||||
payload['reused_existing'] = True
|
||||
payload['message'] = payload.get('message') or '检测到未完成的路径上传任务,已自动续传'
|
||||
return jsonify(payload)
|
||||
return jsonify(payload), 201
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/files', methods=['POST'])
|
||||
def upload_path_job_file(job_id: int):
|
||||
current_user = require_user()
|
||||
job = path_upload_service.require_path_upload_job(job_id)
|
||||
try:
|
||||
job = path_upload_service.upload_path_job_file(
|
||||
job,
|
||||
file_storage=request.files.get('file'),
|
||||
relative_path_raw=request.form.get('relative_path'),
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc)) from exc
|
||||
db.session.commit()
|
||||
return jsonify(serialize_job(job)), 201
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/files/fail', methods=['POST'])
|
||||
def mark_path_job_file_failed(job_id: int):
|
||||
require_user()
|
||||
job = path_upload_service.require_path_upload_job(job_id)
|
||||
data = request.get_json(silent=True) or {}
|
||||
original_name = str(data.get('original_name') or '').strip() or None
|
||||
relative_path_raw = str(data.get('relative_path') or '').strip()
|
||||
error_message = str(data.get('error') or '路径文件上传失败').strip() or '路径文件上传失败'
|
||||
try:
|
||||
job = path_upload_service.mark_path_job_file_failed(
|
||||
job,
|
||||
relative_path_raw=relative_path_raw,
|
||||
original_name=original_name,
|
||||
error_message=error_message,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc)) from exc
|
||||
db.session.commit()
|
||||
return jsonify(serialize_job(job))
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/finalize', methods=['POST'])
|
||||
def finalize_path_upload_job(job_id: int):
|
||||
current_user = require_user()
|
||||
job = path_upload_service.require_path_upload_job(job_id)
|
||||
job, status_code = path_upload_service.finalize_path_upload_job(
|
||||
job,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
refreshed = db.session.get(KbJob, job.id)
|
||||
response_payload = serialize_job(refreshed or job)
|
||||
if status_code == 202:
|
||||
response_payload['queue_result'] = 'inline_per_file'
|
||||
response_payload['accepted'] = True
|
||||
return jsonify(response_payload), status_code
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/files', methods=['DELETE'])
|
||||
def delete_path_job_file(job_id: int):
|
||||
current_user = require_user()
|
||||
job = path_upload_service.require_path_upload_job(job_id)
|
||||
relative_path_raw = str(request.args.get('relative_path') or '').strip()
|
||||
if not relative_path_raw:
|
||||
raise ValidationError('relative_path is required')
|
||||
try:
|
||||
job, document_deleted, relative_path = path_upload_service.delete_path_job_file(
|
||||
job,
|
||||
relative_path_raw=relative_path_raw,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc)) from exc
|
||||
db.session.commit()
|
||||
return jsonify({
|
||||
'ok': True,
|
||||
'job': serialize_job(job),
|
||||
'document_deleted': document_deleted,
|
||||
'relative_path': relative_path,
|
||||
})
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/retry-failed', methods=['POST'])
|
||||
def retry_failed_path_upload_job(job_id: int):
|
||||
current_user = require_user()
|
||||
source_job = path_upload_service.require_path_upload_job(job_id)
|
||||
data = request.get_json(silent=True) or {}
|
||||
requested_paths = data.get('relative_paths') or []
|
||||
if not isinstance(requested_paths, list):
|
||||
requested_paths = []
|
||||
retry_job = path_upload_service.retry_failed_path_upload_job(
|
||||
source_job,
|
||||
relative_paths=requested_paths,
|
||||
user_id=getattr(current_user, 'id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
refreshed = db.session.get(KbJob, retry_job.id)
|
||||
return jsonify(serialize_job(refreshed or retry_job)), 201
|
||||
@@ -0,0 +1,97 @@
|
||||
"""
|
||||
backend/app/api/kb/jobs.py
|
||||
|
||||
用途:知识库后台任务 API(列表、手动触发);序列化/取消 helper 来自 services/kb/job_lifecycle。
|
||||
依赖:kb.blueprint、kb.common、app.jobs、services/kb/job_lifecycle。
|
||||
逻辑:注册 /jobs 路由。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import jsonify
|
||||
|
||||
from app import db
|
||||
from app.api.kb.blueprint import knowledge_base_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.jobs import enqueue_kb_job
|
||||
from app.models import KbDocumentVersion, KbJob
|
||||
from app.services.kb.job_lifecycle import serialize_job
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/jobs', methods=['GET'])
|
||||
def list_jobs():
|
||||
"""
|
||||
返回最近 50 条 KbJob(登录用户可见)。
|
||||
核心逻辑:只读查询,经 run_db_read 处理瞬态 DB 错误。
|
||||
"""
|
||||
from app.api.kb.common import require_user, run_db_read
|
||||
|
||||
require_user()
|
||||
jobs = run_db_read(
|
||||
'list_jobs',
|
||||
lambda: db.session.query(KbJob)
|
||||
.order_by(KbJob.created_at.desc(), KbJob.id.desc())
|
||||
.limit(50)
|
||||
.all(),
|
||||
)
|
||||
return jsonify([serialize_job(job) for job in jobs])
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/jobs/<int:job_id>/run', methods=['POST'])
|
||||
@require_admin
|
||||
def run_job(job_id: int):
|
||||
"""
|
||||
管理员手动将 clean/sync_dify 任务重新提交后台执行。
|
||||
核心逻辑:重置 queued 状态后 enqueue_kb_job;已在队列中则 202 返回 already_queued。
|
||||
"""
|
||||
job = db.session.get(KbJob, job_id)
|
||||
if not job:
|
||||
raise NotFoundError('任务不存在')
|
||||
|
||||
if job.job_type not in ('clean', 'sync_dify'):
|
||||
raise ValidationError('当前仅支持手动执行 clean 或 sync_dify 任务')
|
||||
|
||||
if job.status in ('queued', 'running'):
|
||||
refreshed = db.session.get(KbJob, job_id)
|
||||
payload = serialize_job(refreshed) if refreshed else {'id': job_id}
|
||||
payload['accepted'] = True
|
||||
payload['queue_result'] = 'already_queued'
|
||||
payload['run_result'] = '任务已在后台处理中'
|
||||
return jsonify(payload), 202
|
||||
|
||||
version = db.session.get(KbDocumentVersion, job.document_version_id) if job.document_version_id else None
|
||||
|
||||
if job.job_type == 'clean':
|
||||
if not version:
|
||||
raise NotFoundError('关联文档版本不存在')
|
||||
job.status = 'queued'
|
||||
job.progress = 0
|
||||
job.started_at = None
|
||||
job.finished_at = None
|
||||
job.error_message = None
|
||||
job.message = '等待清洗任务执行'
|
||||
version.status = 'uploaded'
|
||||
version.error_message = None
|
||||
if version.document:
|
||||
version.document.status = 'uploaded'
|
||||
else:
|
||||
if not version:
|
||||
raise NotFoundError('关联文档版本不存在')
|
||||
job.status = 'queued'
|
||||
job.progress = 0
|
||||
job.started_at = None
|
||||
job.finished_at = None
|
||||
job.error_message = None
|
||||
job.message = '等待同步到 Dify'
|
||||
if version.status in ('failed', 'ready', 'synced'):
|
||||
version.error_message = None
|
||||
|
||||
db.session.commit()
|
||||
|
||||
_enqueued, queue_result = enqueue_kb_job(job.id)
|
||||
refreshed = db.session.get(KbJob, job_id)
|
||||
payload = serialize_job(refreshed) if refreshed else {'id': job_id}
|
||||
payload['accepted'] = True
|
||||
payload['queue_result'] = queue_result
|
||||
payload['run_result'] = '任务已提交后台异步执行'
|
||||
return jsonify(payload), 202
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,231 @@
|
||||
"""
|
||||
backend/app/api/maintenance.py
|
||||
|
||||
用途:设备维保助手 HTTP API,当前提供设备台账配置与 Excel 导入能力。
|
||||
依赖:JWT 当前用户、maintenance_ledger_service、Flask Blueprint/send_file。
|
||||
逻辑:查询接口面向会话与面板复用;写入/导入接口先做角色校验,再委托 service。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
|
||||
from flask import Blueprint, g, jsonify, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, UnauthorizedError, ValidationError
|
||||
from app.services.maintenance_ledger_service import (
|
||||
build_import_template,
|
||||
create_device,
|
||||
get_device,
|
||||
import_devices_from_excel,
|
||||
list_devices,
|
||||
update_device,
|
||||
_parse_date,
|
||||
)
|
||||
from app.services.maintenance_record_service import (
|
||||
build_records_import_template,
|
||||
build_records_export,
|
||||
create_record,
|
||||
delete_record,
|
||||
get_record,
|
||||
import_records_from_excel,
|
||||
list_records,
|
||||
update_record,
|
||||
)
|
||||
|
||||
maintenance_bp = Blueprint('maintenance', __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""确保当前请求存在登录用户。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _require_ledger_admin():
|
||||
"""
|
||||
校验设备维保管理权限。
|
||||
Returns:
|
||||
当前用户对象。
|
||||
Raises:
|
||||
ForbiddenError: 当前角色不允许写入台账或维修记录。
|
||||
"""
|
||||
user = _require_user()
|
||||
if getattr(user, 'role', None) not in {'admin', 'maintenance_manager'}:
|
||||
raise ForbiddenError('Maintenance manager privilege required')
|
||||
return user
|
||||
|
||||
|
||||
def _record_list_filters_from_request() -> dict[str, Any]:
|
||||
"""
|
||||
从请求参数解析维修记录列表/导出共用的筛选条件。
|
||||
核心逻辑:兼容 snake_case 与 camelCase 报修日期参数;日期非法时抛出 ValidationError。
|
||||
"""
|
||||
report_date_from = _parse_date(
|
||||
request.args.get('report_date_from') or request.args.get('reportDateFrom'),
|
||||
'reportDateFrom',
|
||||
)
|
||||
report_date_to = _parse_date(
|
||||
request.args.get('report_date_to') or request.args.get('reportDateTo'),
|
||||
'reportDateTo',
|
||||
)
|
||||
return {
|
||||
'keyword': request.args.get('keyword'),
|
||||
'device_code': request.args.get('device_code') or request.args.get('deviceCode'),
|
||||
'status': request.args.get('status'),
|
||||
'report_date_from': report_date_from,
|
||||
'report_date_to': report_date_to,
|
||||
}
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/devices', methods=['GET'])
|
||||
def list_ledger_devices():
|
||||
"""查询设备台账列表,供 Agent 查询结果与右侧台账配置面板使用。"""
|
||||
_require_user()
|
||||
result = list_devices(
|
||||
keyword=request.args.get('keyword'),
|
||||
status=request.args.get('status'),
|
||||
page=request.args.get('page', type=int) or 1,
|
||||
page_size=request.args.get('page_size', type=int) or 20,
|
||||
)
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/devices/<int:device_id>', methods=['GET'])
|
||||
def get_ledger_device(device_id: int):
|
||||
"""读取设备台账详情。"""
|
||||
_require_user()
|
||||
return jsonify(get_device(device_id))
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/devices', methods=['POST'])
|
||||
def create_ledger_device():
|
||||
"""新增设备台账,仅固定管理角色可用。"""
|
||||
user = _require_ledger_admin()
|
||||
payload = request.get_json() or {}
|
||||
return jsonify(create_device(payload, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/devices/<int:device_id>', methods=['PUT'])
|
||||
def update_ledger_device(device_id: int):
|
||||
"""更新设备台账,仅固定管理角色可用。"""
|
||||
user = _require_ledger_admin()
|
||||
payload = request.get_json() or {}
|
||||
return jsonify(update_device(device_id, payload, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/import-template', methods=['GET'])
|
||||
def download_ledger_import_template():
|
||||
"""下载设备台账 Excel 导入模板。"""
|
||||
_require_ledger_admin()
|
||||
return send_file(
|
||||
BytesIO(build_import_template()),
|
||||
as_attachment=True,
|
||||
download_name='maintenance_devices_import_template.xlsx',
|
||||
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
)
|
||||
|
||||
|
||||
@maintenance_bp.route('/ledger/import', methods=['POST'])
|
||||
def import_ledger_devices():
|
||||
"""上传 Excel 模板并批量新增/更新设备台账。"""
|
||||
user = _require_ledger_admin()
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
raise ValidationError('file is required')
|
||||
result = import_devices_from_excel(upload, operator=user, request_id=getattr(g, 'request_id', None))
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@maintenance_bp.route('/records', methods=['GET'])
|
||||
def list_maintenance_records():
|
||||
"""查询设备维修记录,供 Agent 会话查询和结果卡片使用。"""
|
||||
_require_user()
|
||||
filters = _record_list_filters_from_request()
|
||||
result = list_records(
|
||||
keyword=filters['keyword'],
|
||||
device_code=filters['device_code'],
|
||||
status=filters['status'],
|
||||
report_date_from=filters['report_date_from'],
|
||||
report_date_to=filters['report_date_to'],
|
||||
page=request.args.get('page', type=int) or 1,
|
||||
page_size=request.args.get('page_size', type=int) or 20,
|
||||
)
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/<int:record_id>', methods=['GET'])
|
||||
def get_maintenance_record(record_id: int):
|
||||
"""读取设备维修记录详情。"""
|
||||
_require_user()
|
||||
return jsonify(get_record(record_id))
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/export', methods=['GET'])
|
||||
def export_maintenance_records():
|
||||
"""按当前筛选条件导出设备维修记录 Excel。"""
|
||||
_require_ledger_admin()
|
||||
filters = _record_list_filters_from_request()
|
||||
data = build_records_export(
|
||||
keyword=filters['keyword'],
|
||||
device_code=filters['device_code'],
|
||||
status=filters['status'],
|
||||
report_date_from=filters['report_date_from'],
|
||||
report_date_to=filters['report_date_to'],
|
||||
)
|
||||
return send_file(
|
||||
BytesIO(data),
|
||||
as_attachment=True,
|
||||
download_name='maintenance_records.xlsx',
|
||||
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
)
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/import-template', methods=['GET'])
|
||||
def download_records_import_template():
|
||||
"""下载维修记录 Excel 导入模板。"""
|
||||
_require_ledger_admin()
|
||||
return send_file(
|
||||
BytesIO(build_records_import_template()),
|
||||
as_attachment=True,
|
||||
download_name='maintenance_record_history_template.xls',
|
||||
mimetype='application/vnd.ms-excel',
|
||||
)
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/import', methods=['POST'])
|
||||
def import_maintenance_records():
|
||||
"""上传 Excel 模板并批量新增维修记录。"""
|
||||
user = _require_ledger_admin()
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
raise ValidationError('file is required')
|
||||
result = import_records_from_excel(upload, operator=user, request_id=getattr(g, 'request_id', None))
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@maintenance_bp.route('/records', methods=['POST'])
|
||||
def create_maintenance_record():
|
||||
"""新增设备维修记录,仅固定管理角色可用。"""
|
||||
user = _require_ledger_admin()
|
||||
payload = request.get_json() or {}
|
||||
return jsonify(create_record(payload, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/<int:record_id>', methods=['PUT'])
|
||||
def update_maintenance_record(record_id: int):
|
||||
"""更新设备维修记录,仅固定管理角色可用。"""
|
||||
user = _require_ledger_admin()
|
||||
payload = request.get_json() or {}
|
||||
return jsonify(update_record(record_id, payload, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||
|
||||
|
||||
@maintenance_bp.route('/records/<int:record_id>', methods=['DELETE'])
|
||||
def delete_maintenance_record(record_id: int):
|
||||
"""删除设备维修记录,仅固定管理角色可用。"""
|
||||
user = _require_ledger_admin()
|
||||
return jsonify(delete_record(record_id, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||
@@ -0,0 +1,149 @@
|
||||
"""
|
||||
backend/app/api/maintenance_tools.py
|
||||
|
||||
用途:设备维保助手 Dify Tool API,只开放只读查询工具。
|
||||
依赖:maintenance_chat_service、maintenance_record_service、OpenAPI 构建、Tool API 基地址解析。
|
||||
逻辑:Dify 复杂问法调用本蓝图查询设备台账/维修记录;明确查询仍由 chat.py 本地直答,写操作仍走 HXOPS 管理面板。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError, ValidationError
|
||||
from app.models import MaintenanceRecord
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
|
||||
from app.services.maintenance_chat_service import build_device_query_result
|
||||
from app.services.maintenance_record_service import serialize_record
|
||||
from app.services.maintenance_tools.openapi_spec import build_maintenance_openapi_spec
|
||||
|
||||
maintenance_tool_bp = Blueprint("maintenance_tools", __name__)
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验设备维保 Tool API 鉴权。
|
||||
AI 触发时机:Dify Tool 调用本蓝图时由 before_request 自动执行,不是给 LLM 直接调用的业务工具。
|
||||
"""
|
||||
configured = str(
|
||||
current_app.config.get("MAINTENANCE_TOOL_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
or ""
|
||||
).strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError(
|
||||
"MAINTENANCE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured",
|
||||
code="missing_auth",
|
||||
)
|
||||
|
||||
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||
if configured in {token, integration_key}:
|
||||
return
|
||||
if not token and not integration_key:
|
||||
raise UnauthorizedError("missing_auth")
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
"""把 AppError 归一成 Dify Tool 侧可读错误码。"""
|
||||
message = str(exc.message or "").strip()
|
||||
if message in {"missing_auth", "invalid_auth"}:
|
||||
return message
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
return "missing_auth"
|
||||
if exc.code == "VALIDATION.INVALID_PARAM":
|
||||
return message or "invalid_request"
|
||||
return exc.code
|
||||
|
||||
|
||||
@maintenance_tool_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
"""Tool API 统一错误响应。"""
|
||||
return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status
|
||||
|
||||
|
||||
@maintenance_tool_bp.before_request
|
||||
def _verify_tool_access():
|
||||
"""除 OpenAPI 文档外,所有 Tool 调用必须携带有效服务级 token。"""
|
||||
if request.path.endswith("/openapi.json") or request.path.endswith("/openapi.dify.yaml"):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
def _payload() -> dict:
|
||||
"""读取 JSON 请求体。"""
|
||||
return request.get_json(silent=True) or {}
|
||||
|
||||
|
||||
def _clean_text(value) -> str:
|
||||
return str(value or "").strip()
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def openapi_spec():
|
||||
"""返回 Dify 导入用的 OpenAPI JSON。"""
|
||||
return jsonify(build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/openapi.dify.yaml", methods=["GET"])
|
||||
def openapi_dify_yaml():
|
||||
"""返回 Dify 导入用的 OpenAPI YAML。"""
|
||||
import yaml
|
||||
|
||||
body = yaml.safe_dump(
|
||||
build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()),
|
||||
allow_unicode=True,
|
||||
sort_keys=False,
|
||||
)
|
||||
return current_app.response_class(body, mimetype="text/yaml; charset=utf-8")
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/query_device", methods=["POST"])
|
||||
def query_device():
|
||||
"""按设备编号或名称查询设备台账,并可带出最近维修记录。"""
|
||||
data = _payload()
|
||||
keyword = _clean_text(data.get("keyword"))
|
||||
if not keyword:
|
||||
raise ValidationError("keyword is required")
|
||||
include_records = bool(data.get("include_records", True))
|
||||
record_limit = max(0, min(20, int(data.get("record_limit") or 5)))
|
||||
result = build_device_query_result(keyword, include_records=include_records, record_limit=record_limit)
|
||||
return jsonify({"ok": True, **result})
|
||||
|
||||
|
||||
@maintenance_tool_bp.route("/tools/query_records", methods=["POST"])
|
||||
def query_records():
|
||||
"""按设备编号/名称和状态查询维修记录。"""
|
||||
data = _payload()
|
||||
keyword = _clean_text(data.get("keyword"))
|
||||
if not keyword:
|
||||
raise ValidationError("keyword is required")
|
||||
status = _clean_text(data.get("status"))
|
||||
limit = max(1, min(50, int(data.get("limit") or 10)))
|
||||
|
||||
query = db.session.query(MaintenanceRecord)
|
||||
like = f"%{keyword}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
MaintenanceRecord.device_code.ilike(like),
|
||||
MaintenanceRecord.device_name.ilike(like),
|
||||
)
|
||||
)
|
||||
if status:
|
||||
query = query.filter(MaintenanceRecord.repair_status == status)
|
||||
rows = query.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc()).limit(limit).all()
|
||||
return jsonify({
|
||||
"ok": True,
|
||||
"matched": bool(rows),
|
||||
"keyword": keyword,
|
||||
"items": [serialize_record(item) for item in rows],
|
||||
"totalReturned": len(rows),
|
||||
})
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
"""
|
||||
backend/app/api/schedule/__init__.py
|
||||
|
||||
用途:排程管理 Blueprint 入口(自 schedule_admin.py 收敛)。
|
||||
逻辑:Wave 1 前 re-export 旧模块 blueprint。
|
||||
用途:排程管理 Blueprint 入口(Wave 3 分包)。
|
||||
依赖:schedule/blueprint.py、config、tasks、runs、platform_tasks。
|
||||
逻辑:import 子模块注册路由;register_blueprints 从本包 import schedule_admin_bp。
|
||||
"""
|
||||
from app.api.schedule_admin import schedule_admin_bp # noqa: F401
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
|
||||
import app.api.schedule.common # noqa: F401
|
||||
import app.api.schedule.config # noqa: F401
|
||||
import app.api.schedule.tasks # noqa: F401
|
||||
import app.api.schedule.runs # noqa: F401
|
||||
import app.api.schedule.platform_tasks # noqa: F401
|
||||
import app.api.schedule.rpa_workers # noqa: F401
|
||||
|
||||
__all__ = ['schedule_admin_bp']
|
||||
@@ -0,0 +1,10 @@
|
||||
"""
|
||||
backend/app/api/schedule/blueprint.py
|
||||
|
||||
用途:排程管理 API 共享 Blueprint(Wave 3 分包后各子模块共用)。
|
||||
依赖:Flask Blueprint。
|
||||
逻辑:config/tasks/runs 子模块在此 bp 上注册路由;__init__ 导出 schedule_admin_bp。
|
||||
"""
|
||||
from flask import Blueprint
|
||||
|
||||
schedule_admin_bp = Blueprint('schedule_admin', __name__)
|
||||
@@ -0,0 +1,59 @@
|
||||
"""
|
||||
backend/app/api/schedule/common.py
|
||||
|
||||
用途:排程 API 共享序列化 helper。
|
||||
依赖:models、services/schedule/query_service。
|
||||
逻辑:config/tasks 子模块导出任务配置 JSON 时共用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.models import ScheduleTask, ScheduleTaskConfig
|
||||
from app.services.schedule.query_service import serialize_task
|
||||
from app.services.schedule.serialization import safe_json_value
|
||||
|
||||
|
||||
def serialize_task_config(cfg_model: ScheduleTaskConfig) -> dict:
|
||||
"""
|
||||
将 ScheduleTaskConfig ORM 转为 API 响应 dict。
|
||||
核心逻辑:扁平化 data_source / external_api 嵌套结构。
|
||||
"""
|
||||
return {
|
||||
'row_id_key': cfg_model.row_id_key or 'id',
|
||||
'log_prefix': cfg_model.log_prefix or '',
|
||||
'base_fetch_sql': cfg_model.base_fetch_sql or '',
|
||||
'fetch_where_conditions': cfg_model.fetch_where_conditions or '',
|
||||
'fetch_order_by': cfg_model.fetch_order_by or '',
|
||||
'writeback_sql': cfg_model.writeback_sql or '',
|
||||
'detail_sql': cfg_model.detail_sql or '',
|
||||
'alias_order': cfg_model.alias_order or [],
|
||||
'detail_alias_order': cfg_model.detail_alias_order or [],
|
||||
'header_labels': cfg_model.header_labels or {},
|
||||
'data_source': {
|
||||
'db_type': cfg_model.ds_db_type or 'sqlserver',
|
||||
'host': cfg_model.ds_host or '',
|
||||
'port': cfg_model.ds_port or '',
|
||||
'database': cfg_model.ds_database or '',
|
||||
'username': cfg_model.ds_username or '',
|
||||
'password': cfg_model.ds_password or '',
|
||||
'driver': cfg_model.ds_driver or '',
|
||||
'encrypt': cfg_model.ds_encrypt or '',
|
||||
'trust_cert': cfg_model.ds_trust_cert or '',
|
||||
},
|
||||
'external_api': {
|
||||
'url': cfg_model.api_url or '',
|
||||
'method': cfg_model.api_method or 'POST',
|
||||
'headers': cfg_model.api_headers or {},
|
||||
'body_template': cfg_model.api_body_template or '',
|
||||
},
|
||||
'dify_system_prompt': cfg_model.dify_system_prompt or '',
|
||||
}
|
||||
|
||||
|
||||
def serialize_task_for_export(task: ScheduleTask, cfg_model: ScheduleTaskConfig | None) -> dict:
|
||||
"""组装单条排程导出 JSON(含 config 快照)。"""
|
||||
payload = serialize_task(task)
|
||||
payload['config'] = serialize_task_config(cfg_model) if cfg_model else None
|
||||
return payload
|
||||
|
||||
|
||||
__all__ = ['safe_json_value', 'serialize_task_config', 'serialize_task_for_export']
|
||||
@@ -0,0 +1,111 @@
|
||||
"""
|
||||
backend/app/api/schedule/config.py
|
||||
|
||||
用途:排程任务 SQL/数据源配置 API 与测试接口(薄路由层)。
|
||||
依赖:schedule.blueprint、schedule.common、schedule_contract、services/schedule/*。
|
||||
逻辑:/schedule-config/* 路由;配置更新仅允许 data_pipeline 任务修改 data_source_type。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
from app.api.schedule.common import serialize_task_config
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import ScheduleTask, ScheduleTaskConfig
|
||||
from app.services.schedule.schedule_contract import (
|
||||
SCHEDULE_TYPE_DATA_PIPELINE,
|
||||
apply_schedule_contract_to_payload,
|
||||
platform_job_allows_config,
|
||||
)
|
||||
from app.services.schedule.sql_config import upsert_schedule_task_config
|
||||
from app.services.schedule.sql_preview_service import preview_fetch_sql
|
||||
from app.services.schedule.test_run_service import execute_test_run
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_task_config(task_id: int):
|
||||
"""返回排程任务关联的 SQL/数据源配置。"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if not cfg_model:
|
||||
return jsonify({'data_source_type': task.data_source_type, 'config': None})
|
||||
return jsonify({'data_source_type': task.data_source_type, 'config': serialize_task_config(cfg_model)})
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_schedule_task_config(task_id: int):
|
||||
"""
|
||||
更新排程 data_source_type 与 ScheduleTaskConfig。
|
||||
核心逻辑:仅 data_pipeline 允许改 data_source_type;platform_job 禁止经此接口绕过契约。
|
||||
"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
if task.schedule_type != SCHEDULE_TYPE_DATA_PIPELINE:
|
||||
if 'data_source_type' in data:
|
||||
raise ValidationError(
|
||||
'data_source_type can only be updated for data_pipeline schedules; '
|
||||
'use schedule task PATCH for platform_job'
|
||||
)
|
||||
elif 'data_source_type' in data:
|
||||
contract = apply_schedule_contract_to_payload({
|
||||
'schedule_type': task.schedule_type,
|
||||
'data_source_type': data.get('data_source_type'),
|
||||
'platform_api_path': task.platform_api_path,
|
||||
})
|
||||
task.data_source_type = contract['data_source_type']
|
||||
|
||||
config_data = data.get('config', data)
|
||||
if isinstance(config_data, dict) and config_data:
|
||||
# platform_job 仅白名单且 enabled 的任务(如 shipping-inventory-rpa)允许写 ScheduleTaskConfig
|
||||
if task.schedule_type != SCHEDULE_TYPE_DATA_PIPELINE and not platform_job_allows_config(task.platform_api_path):
|
||||
raise ValidationError(
|
||||
f"platform_job '{task.platform_api_path}' does not accept ScheduleTaskConfig"
|
||||
)
|
||||
upsert_schedule_task_config(task_id, config_data, commit=False)
|
||||
db.session.commit()
|
||||
cfg_model = task.config
|
||||
if cfg_model is None:
|
||||
with db.session.no_autoflush:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
return jsonify({
|
||||
'data_source_type': task.data_source_type,
|
||||
'config': serialize_task_config(cfg_model) if cfg_model else None,
|
||||
})
|
||||
except ValidationError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ValidationError(str(exc))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-sql', methods=['POST'])
|
||||
@require_admin
|
||||
def test_schedule_sql(task_id: int):
|
||||
"""预览抓取 SQL 执行结果(最多 100 行)。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return jsonify(preview_fetch_sql(task_id, data))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-run', methods=['POST'])
|
||||
@require_admin
|
||||
def test_schedule_run(task_id: int):
|
||||
"""同步执行小规模排程测试跑(默认 3 条),可选 KB 同步。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = execute_test_run(
|
||||
task_id,
|
||||
data,
|
||||
triggered_by_user_id=getattr(get_current_user(), 'id', None),
|
||||
)
|
||||
return jsonify(payload)
|
||||
@@ -0,0 +1,59 @@
|
||||
"""
|
||||
backend/app/api/schedule/platform_tasks.py
|
||||
|
||||
用途:平台任务契约 API(任务定义 + 动态选项),供前端 DynamicTaskParamsForm 通用渲染。
|
||||
依赖:schedule.blueprint、job_registry(任务契约中心)、job_options(options_source 分发)。
|
||||
逻辑:/platform-tasks/definitions 下发 params_schema(仅 enabled);/platform-tasks/options 按 source 返回统一选项;
|
||||
前端不再按任务硬编码 UI,红框参数区完全由 schema 决定。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import request
|
||||
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.schedule.job_options import list_job_options
|
||||
from app.services.schedule.job_registry import list_platform_jobs
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/platform-tasks/definitions', methods=['GET'])
|
||||
@require_admin
|
||||
def get_platform_task_definitions():
|
||||
"""
|
||||
返回全部启用平台任务的完整契约(展示信息 + params_schema + defaults)。
|
||||
核心逻辑:直接序列化 job_registry 注册项;前端选择任务后按 params_schema 渲染参数表单。
|
||||
"""
|
||||
return ok([
|
||||
{
|
||||
'task_type': job.key,
|
||||
'label': job.label,
|
||||
'label_key': job.label_key or None,
|
||||
'description': job.description,
|
||||
'description_key': job.description_key or None,
|
||||
'category': job.category,
|
||||
'enabled': job.enabled,
|
||||
'params_schema': list(job.params_schema),
|
||||
'defaults': job.defaults,
|
||||
}
|
||||
for job in list_platform_jobs()
|
||||
if job.enabled
|
||||
])
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/platform-tasks/options', methods=['GET'])
|
||||
@require_admin
|
||||
def get_platform_task_options():
|
||||
"""
|
||||
按 options_source 返回动态选项(统一 {label, value, description?})。
|
||||
核心逻辑:source 参数分发到 job_options 登记的 provider;前端不感知数据来源。
|
||||
"""
|
||||
source = str(request.args.get('source') or '').strip()
|
||||
if not source:
|
||||
raise ValidationError('source is required')
|
||||
try:
|
||||
options = list_job_options(source)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc))
|
||||
return ok(options)
|
||||
@@ -0,0 +1,24 @@
|
||||
"""
|
||||
backend/app/api/schedule/rpa_workers.py
|
||||
|
||||
用途:管理端查询货代库存 RPA Worker 在线状态与就绪摘要。
|
||||
依赖:schedule.blueprint、rpa_worker_heartbeat.serialize_rpa_worker_status。
|
||||
逻辑:ScheduleWorkbenchPanel 在库存 RPA 排程工作台展示 worker 心跳状态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.response import ok
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import serialize_rpa_worker_status
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/rpa-workers/status', methods=['GET'])
|
||||
@require_admin
|
||||
def get_rpa_workers_status():
|
||||
"""
|
||||
返回库存 RPA Worker 心跳摘要(在线/离线、最后心跳时间、就绪原因)。
|
||||
核心逻辑:读取 Redis/内存心跳并与当前环境、trigger 目录比对。
|
||||
"""
|
||||
return ok(serialize_rpa_worker_status())
|
||||
@@ -0,0 +1,158 @@
|
||||
"""
|
||||
backend/app/api/schedule/runs.py
|
||||
|
||||
用途:排程运行触发与运行记录查询 API。
|
||||
依赖:schedule.blueprint、services/schedule/query_service、scheduler_service。
|
||||
逻辑:/schedules/<id>/run、/schedules/<id>/runs、/schedule-runs/* 路由。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from io import BytesIO
|
||||
|
||||
from flask import current_app, jsonify, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import ConflictError, NotFoundError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.schedule.query_service import get_run, list_runs, serialize_run
|
||||
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import recover_stale_awaiting_rpa_schedule_runs
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
|
||||
@require_admin
|
||||
def run_schedule(task_id: int):
|
||||
"""
|
||||
手动触发排程后台执行。
|
||||
核心逻辑:创建 running ScheduleRun → 守护线程内 run_task_now。
|
||||
"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
recover_stale_awaiting_rpa_schedule_runs(task)
|
||||
user = get_current_user()
|
||||
existing = (
|
||||
db.session.query(ScheduleRun)
|
||||
.filter(ScheduleRun.schedule_task_id == task.id, ScheduleRun.status == 'running')
|
||||
.first()
|
||||
)
|
||||
if existing:
|
||||
raise ConflictError('该排程正在执行中,请等待完成后再试', details={'run_id': existing.id})
|
||||
run = ScheduleRun(
|
||||
run_no=_generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
trigger_type='manual',
|
||||
triggered_by_user_id=getattr(user, 'id', None),
|
||||
started_at=datetime.utcnow(),
|
||||
status='running',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
app = current_app._get_current_object()
|
||||
run_id = run.id
|
||||
|
||||
def _background():
|
||||
with app.app_context():
|
||||
t = db.session.get(ScheduleTask, task_id)
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if not t or not r:
|
||||
return
|
||||
try:
|
||||
run_task_now(t, trigger_type='manual', triggered_by_user_id=r.triggered_by_user_id, run=r)
|
||||
except Exception as exc:
|
||||
try:
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if r and r.status == 'running':
|
||||
r.status = 'failed'
|
||||
r.error_message = str(exc)
|
||||
r.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
current_app.logger.error('[schedule-run] run_id=%s failed: %s', run_id, exc, exc_info=True)
|
||||
|
||||
t = threading.Thread(target=_background, daemon=True, name=f'schedule-run-{run_id}')
|
||||
t.start()
|
||||
fresh = db.session.get(ScheduleRun, run_id)
|
||||
return jsonify(serialize_run(fresh))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/runs', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_runs(task_id: int):
|
||||
"""按任务 ID 分页/过滤返回运行记录。"""
|
||||
status = str(request.args.get('status') or '').strip() or None
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
started_after = None
|
||||
started_before = None
|
||||
sa = request.args.get('started_after')
|
||||
sb = request.args.get('started_before')
|
||||
if sa:
|
||||
try:
|
||||
started_after = datetime.fromisoformat(sa.replace('Z', '+00:00'))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
if sb:
|
||||
try:
|
||||
started_before = datetime.fromisoformat(sb.replace('Z', '+00:00'))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
return jsonify(
|
||||
list_runs(
|
||||
task_id=task_id,
|
||||
status=status,
|
||||
started_after=started_after,
|
||||
started_before=started_before,
|
||||
limit=limit,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_run(run_id: int):
|
||||
"""返回单条运行记录详情。"""
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(serialize_run(run))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_run_excel(run_id: int):
|
||||
"""下载运行结果 Excel 附件。"""
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError('Excel not found')
|
||||
buf = BytesIO(run.excel_file_data)
|
||||
return send_file(
|
||||
buf,
|
||||
as_attachment=True,
|
||||
download_name=run.excel_file_name or 'result.xlsx',
|
||||
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
)
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/inventory-raw-zip', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_run_inventory_raw_zip(run_id: int):
|
||||
"""下载库存 RPA 排程 run 的原始库存 Excel 打包(ZIP + manifest)。"""
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
zip_path, file_name = resolve_inventory_raw_zip_download(run)
|
||||
return send_file(
|
||||
zip_path,
|
||||
as_attachment=True,
|
||||
download_name=file_name,
|
||||
mimetype='application/zip',
|
||||
)
|
||||
@@ -0,0 +1,282 @@
|
||||
"""
|
||||
backend/app/api/schedule/tasks.py
|
||||
|
||||
用途:排程任务 CRUD、导入导出、启用/禁用 API。
|
||||
依赖:schedule.blueprint、schedule.common、services/schedule/*。
|
||||
逻辑:/schedules* 路由(不含 run 触发与运行记录);job_params 归一化与切换重置
|
||||
由 scheduler_service.create_task/update_task 唯一兜底;本层只做请求校验与
|
||||
ValueError→ValidationError 映射。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Response, jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
from app.api.schedule.common import serialize_task_for_export
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig
|
||||
from app.services.schedule.query_service import list_tasks, serialize_task
|
||||
from app.services.schedule.import_service import import_schedules_from_payload
|
||||
from app.services.schedule.schedule_contract import (
|
||||
apply_schedule_contract_to_payload,
|
||||
assert_schedule_config_writable,
|
||||
)
|
||||
from app.services.schedule.scheduler_service import create_task, update_task
|
||||
from app.services.schedule.sql_config import upsert_schedule_task_config
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedules():
|
||||
"""返回全部排程任务列表。"""
|
||||
return jsonify(list_tasks())
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule/platform-jobs', methods=['GET'])
|
||||
@require_admin
|
||||
def get_platform_jobs():
|
||||
"""
|
||||
返回 Job Registry 已启用平台任务列表,供前端下拉动态加载。
|
||||
与 /platform-tasks/definitions 一致:只返回 enabled=True,避免下拉可选却无参数定义。
|
||||
"""
|
||||
from app.services.schedule.job_registry import list_platform_jobs
|
||||
|
||||
return jsonify([
|
||||
{
|
||||
'key': job.key,
|
||||
'label_key': job.label_key or None,
|
||||
'label': job.label,
|
||||
'description': job.description,
|
||||
'enabled': job.enabled,
|
||||
}
|
||||
for job in list_platform_jobs()
|
||||
if job.enabled
|
||||
])
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/export', methods=['GET'])
|
||||
@require_admin
|
||||
def export_schedule(task_id: int):
|
||||
"""导出单条排程任务及配置为 JSON 文件。"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
payload = {
|
||||
'schema_version': 1,
|
||||
'exported_at': datetime.utcnow().isoformat(),
|
||||
'schedules': [serialize_task_for_export(task, cfg_model)],
|
||||
}
|
||||
body = json.dumps(payload, ensure_ascii=False, indent=2)
|
||||
filename = f"{task.schedule_no or f'schedule_{task.id}'}_export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
|
||||
return Response(
|
||||
body,
|
||||
mimetype='application/json; charset=utf-8',
|
||||
headers={'Content-Disposition': f'attachment; filename="{filename}"'},
|
||||
)
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/import', methods=['POST'])
|
||||
@require_admin
|
||||
def import_schedules():
|
||||
"""批量导入排程 JSON(按 schedule_no upsert)。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
user = get_current_user()
|
||||
result = import_schedules_from_payload(
|
||||
data.get('schedules'),
|
||||
actor_id=getattr(user, 'id', None),
|
||||
)
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules', methods=['POST'])
|
||||
@require_admin
|
||||
def post_schedule():
|
||||
"""创建排程任务。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
user = get_current_user()
|
||||
schedule_type = str(data.get('schedule_type') or 'data_pipeline')
|
||||
data_source_type = data.get('data_source_type')
|
||||
platform_api_path = data.get('platform_api_path')
|
||||
config_data = data.get('config')
|
||||
if config_data is not None and not isinstance(config_data, dict):
|
||||
raise ValidationError('config must be a JSON object')
|
||||
if schedule_type.strip().lower() == 'data_pipeline' and data_source_type in (None, ''):
|
||||
data_source_type = 'database'
|
||||
try:
|
||||
# [STEP 1] 契约与 config 写入权限预校验(失败不落库);job_params 由 create_task 归一化
|
||||
contract = apply_schedule_contract_to_payload({
|
||||
'schedule_type': schedule_type,
|
||||
'data_source_type': data_source_type,
|
||||
'platform_api_path': platform_api_path,
|
||||
})
|
||||
assert_schedule_config_writable(
|
||||
schedule_type=contract['schedule_type'],
|
||||
platform_api_path=contract['platform_api_path'],
|
||||
config=config_data,
|
||||
)
|
||||
task = create_task(
|
||||
name=str(data.get('name') or '').strip(),
|
||||
schedule_type=schedule_type,
|
||||
owner_user_id=int(data.get('owner_user_id')),
|
||||
cron_expr=str(data.get('cron_expr') or '').strip(),
|
||||
schedule_timezone=data.get('schedule_timezone'),
|
||||
wait_seconds=int(data.get('wait_seconds') or 0),
|
||||
dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None,
|
||||
platform_api_path=str(platform_api_path).strip() if platform_api_path else None,
|
||||
data_source_type=str(data_source_type) if data_source_type is not None else None,
|
||||
job_params=data.get('job_params'),
|
||||
notify_user_ids_json=data.get('notify_user_ids_json')
|
||||
if isinstance(data.get('notify_user_ids_json'), list)
|
||||
else [],
|
||||
notify_enabled=bool(data.get('notify_enabled', True)),
|
||||
enabled=bool(data.get('enabled', True)),
|
||||
kb_sync_enabled=bool(data.get('kb_sync_enabled', False)),
|
||||
kb_group_id=int(data.get('kb_group_id')) if data.get('kb_group_id') not in (None, '', 0, '0') else None,
|
||||
actor_id=getattr(user, 'id', None),
|
||||
commit=not config_data,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc))
|
||||
if config_data:
|
||||
try:
|
||||
upsert_schedule_task_config(task.id, config_data, commit=False)
|
||||
if not task.dify_agent_id:
|
||||
cfg_model = task.config
|
||||
if cfg_model is None:
|
||||
with db.session.no_autoflush:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
|
||||
if cfg_model and cfg_model.dify_system_prompt:
|
||||
cfg_model.dify_system_prompt = None
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
raise
|
||||
db.session.refresh(task)
|
||||
return jsonify(serialize_task(task)), 201
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule(task_id: int):
|
||||
"""返回单条排程任务详情。"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['PATCH'])
|
||||
@require_admin
|
||||
def patch_schedule(task_id: int):
|
||||
"""更新排程任务字段与关联配置。"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
user = get_current_user()
|
||||
config_data = data.get('config')
|
||||
if config_data is not None and not isinstance(config_data, dict):
|
||||
raise ValidationError('config must be a JSON object')
|
||||
try:
|
||||
# [STEP 1] 契约与 config 预校验;job_params 重置/归一化由 update_task 唯一兜底
|
||||
contract = apply_schedule_contract_to_payload({
|
||||
'schedule_type': data.get('schedule_type', task.schedule_type),
|
||||
'data_source_type': data.get('data_source_type', task.data_source_type),
|
||||
'platform_api_path': data.get('platform_api_path', task.platform_api_path),
|
||||
})
|
||||
assert_schedule_config_writable(
|
||||
schedule_type=contract['schedule_type'],
|
||||
platform_api_path=contract['platform_api_path'],
|
||||
config=config_data,
|
||||
)
|
||||
task = update_task(
|
||||
task,
|
||||
payload=data,
|
||||
actor_id=getattr(user, 'id', None),
|
||||
commit=not config_data,
|
||||
)
|
||||
if config_data:
|
||||
upsert_schedule_task_config(task_id, config_data, commit=False)
|
||||
if not task.dify_agent_id:
|
||||
cfg_model = task.config
|
||||
if cfg_model is None:
|
||||
with db.session.no_autoflush:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if cfg_model and cfg_model.dify_system_prompt:
|
||||
cfg_model.dify_system_prompt = None
|
||||
if config_data:
|
||||
db.session.commit()
|
||||
except ValueError as exc:
|
||||
db.session.rollback()
|
||||
raise ValidationError(str(exc))
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
raise
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_schedule(task_id: int):
|
||||
"""删除排程任务及其运行记录;中断进行中的 run。"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.schedule.scheduler_service import request_cancel_run
|
||||
|
||||
running_runs = (
|
||||
db.session.query(ScheduleRun)
|
||||
.filter(ScheduleRun.schedule_task_id == task_id, ScheduleRun.status == 'running')
|
||||
.all()
|
||||
)
|
||||
for rr in running_runs:
|
||||
request_cancel_run(rr.id)
|
||||
rr.status = 'failed'
|
||||
rr.error_message = '排程已被删除,执行中断'
|
||||
rr.finished_at = datetime.utcnow()
|
||||
if running_runs:
|
||||
db.session.commit()
|
||||
db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False)
|
||||
db.session.delete(task)
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/enable', methods=['POST'])
|
||||
@require_admin
|
||||
def enable_schedule(task_id: int):
|
||||
"""
|
||||
启用排程并重新计算 next_run_at。
|
||||
核心逻辑:委托 enable_task 重新校验契约与 job_params,拒绝已停用 platform_job 重新入队。
|
||||
"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.schedule.scheduler_service import enable_task
|
||||
|
||||
try:
|
||||
task = enable_task(task)
|
||||
except ValueError as exc:
|
||||
db.session.rollback()
|
||||
raise ValidationError(str(exc)) from exc
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/disable', methods=['POST'])
|
||||
@require_admin
|
||||
def disable_schedule(task_id: int):
|
||||
"""禁用排程并清空 next_run_at。"""
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
task.enabled = False
|
||||
task.next_run_at = None
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
@@ -1,513 +1,10 @@
|
||||
from __future__ import annotations
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
from flask import Response
|
||||
from io import BytesIO
|
||||
import json
|
||||
from app.decorators import require_admin
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.services.schedule.query_service import get_run, list_runs, list_tasks, serialize_run, serialize_task
|
||||
from app.services.schedule.scheduler_service import create_task, run_task_now, update_task, _generate_run_no, _generate_test_run_no, _notify_schedule_run_wecom
|
||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id, upsert_schedule_task_config, _build_fetch_sql
|
||||
from app.services.schedule.srm_service import _fetch_records
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
schedule_admin_bp = Blueprint('schedule_admin', __name__)
|
||||
"""
|
||||
backend/app/api/schedule_admin.py
|
||||
|
||||
def _serialize_task_for_export(task: ScheduleTask, cfg_model: ScheduleTaskConfig | None) -> dict:
|
||||
payload = serialize_task(task)
|
||||
payload['config'] = _serialize_task_config(cfg_model) if cfg_model else None
|
||||
return payload
|
||||
用途:排程 API 兼容 shim(Wave 3 迁包过渡期)。
|
||||
依赖:app.api.schedule。
|
||||
逻辑:旧 import 路径仍可用;新代码请用 app.api.schedule。
|
||||
"""
|
||||
from app.api.schedule import schedule_admin_bp
|
||||
|
||||
def _serialize_task_config(cfg_model: ScheduleTaskConfig) -> dict:
|
||||
return {'row_id_key': cfg_model.row_id_key or 'id', 'log_prefix': cfg_model.log_prefix or '', 'base_fetch_sql': cfg_model.base_fetch_sql or '', 'fetch_where_conditions': cfg_model.fetch_where_conditions or '', 'fetch_order_by': cfg_model.fetch_order_by or '', 'writeback_sql': cfg_model.writeback_sql or '', 'detail_sql': cfg_model.detail_sql or '', 'alias_order': cfg_model.alias_order or [], 'detail_alias_order': cfg_model.detail_alias_order or [], 'header_labels': cfg_model.header_labels or {}, 'data_source': {'db_type': cfg_model.ds_db_type or 'sqlserver', 'host': cfg_model.ds_host or '', 'port': cfg_model.ds_port or '', 'database': cfg_model.ds_database or '', 'username': cfg_model.ds_username or '', 'password': cfg_model.ds_password or '', 'driver': cfg_model.ds_driver or '', 'encrypt': cfg_model.ds_encrypt or '', 'trust_cert': cfg_model.ds_trust_cert or ''}, 'external_api': {'url': cfg_model.api_url or '', 'method': cfg_model.api_method or 'POST', 'headers': cfg_model.api_headers or {}, 'body_template': cfg_model.api_body_template or ''}, 'dify_system_prompt': cfg_model.dify_system_prompt or ''}
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_task_config(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if not cfg_model:
|
||||
return jsonify({'data_source_type': task.data_source_type, 'config': None})
|
||||
return jsonify({'data_source_type': task.data_source_type, 'config': _serialize_task_config(cfg_model)})
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_schedule_task_config(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
if 'data_source_type' in data:
|
||||
task.data_source_type = str(data['data_source_type'])
|
||||
db.session.commit()
|
||||
config_data = data.get('config', data)
|
||||
cfg = upsert_schedule_task_config(task_id, config_data)
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
return jsonify({'data_source_type': task.data_source_type, 'config': _serialize_task_config(cfg_model) if cfg_model else None})
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
raise ValidationError(str(e))
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-sql', methods=['POST'])
|
||||
@require_admin
|
||||
def test_schedule_sql(task_id: int):
|
||||
cfg = get_schedule_sql_config_by_task_id(task_id)
|
||||
if not cfg:
|
||||
raise NotFoundError(f'Config for task {task_id} not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
custom_where = str(data.get('fetch_where_conditions') or cfg.fetch_where_conditions).strip()
|
||||
custom_order_by = str(data.get('fetch_order_by') or cfg.fetch_order_by).strip()
|
||||
limit = min(int(data.get('limit') or 10), 100)
|
||||
base = cfg.base_fetch_sql or cfg.fetch_sql
|
||||
if cfg.base_fetch_sql:
|
||||
sql = _build_fetch_sql(base, custom_where, custom_order_by)
|
||||
else:
|
||||
sql = base
|
||||
try:
|
||||
from app.services.schedule import _build_srm_conn_str
|
||||
import decimal, datetime
|
||||
if cfg.data_source and (not cfg.data_source.is_empty()):
|
||||
conn_str = cfg.data_source.build_connection_string()
|
||||
else:
|
||||
conn_str = _build_srm_conn_str()
|
||||
rows = _fetch_records(conn_str, sql)
|
||||
|
||||
def _safe(v):
|
||||
if isinstance(v, decimal.Decimal):
|
||||
return float(v)
|
||||
if isinstance(v, (datetime.date, datetime.datetime)):
|
||||
return v.isoformat()
|
||||
if isinstance(v, datetime.timedelta):
|
||||
return str(v)
|
||||
return v
|
||||
result_rows = [{k: _safe(v) for k, v in r.items()} for r in rows[:limit]]
|
||||
return jsonify({'total': len(rows), 'showing': len(result_rows), 'limit': limit, 'sql': sql, 'columns': list(result_rows[0].keys()) if result_rows else [], 'rows': result_rows})
|
||||
except Exception as e:
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message=str(e), http_status=400, details={'sql': sql})
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-run', methods=['POST'])
|
||||
@require_admin
|
||||
def test_schedule_run(task_id: int):
|
||||
import time as _time
|
||||
from app.services.schedule.excel_service import export_schedule_result_excel
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
cfg = get_schedule_sql_config_by_task_id(task_id)
|
||||
if not cfg:
|
||||
raise NotFoundError(f'Config for task {task_id} not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
custom_where = str(data.get('fetch_where_conditions') or cfg.fetch_where_conditions).strip()
|
||||
custom_order_by = str(data.get('fetch_order_by') or cfg.fetch_order_by).strip()
|
||||
limit = min(int(data.get('limit') or 3), 10)
|
||||
raw_kb_sync = data.get('kb_sync_enabled', False)
|
||||
if isinstance(raw_kb_sync, str):
|
||||
test_kb_sync_enabled = raw_kb_sync.strip().lower() in ('1', 'true', 'yes', 'on')
|
||||
else:
|
||||
test_kb_sync_enabled = bool(raw_kb_sync)
|
||||
base = cfg.base_fetch_sql or cfg.fetch_sql
|
||||
if cfg.base_fetch_sql:
|
||||
test_sql = _build_fetch_sql(base, custom_where, custom_order_by)
|
||||
else:
|
||||
test_sql = base
|
||||
from app.services.schedule import _build_srm_conn_str, _resolve_dify_agent, _resolve_schedule_user
|
||||
from app.services.schedule.srm_service import _fetch_records, _run_check_job_loop, _build_record_text, _execute_writeback
|
||||
if cfg.data_source and (not cfg.data_source.is_empty()):
|
||||
conn_str = cfg.data_source.build_connection_string()
|
||||
else:
|
||||
conn_str = _build_srm_conn_str()
|
||||
agent = _resolve_dify_agent(task) if task else None
|
||||
user = _resolve_schedule_user(task) if task else 'test_user'
|
||||
wait_seconds = task.wait_seconds if task else 120
|
||||
dify_agent_id = task.dify_agent_id if task else None
|
||||
run = ScheduleRun(run_no=_generate_test_run_no(), schedule_task_id=task_id, trigger_type='test', triggered_by_user_id=getattr(get_current_user(), 'id', None), started_at=datetime.utcnow(), status='running')
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||
capture_dify_execution_snapshot(run, task)
|
||||
db.session.commit()
|
||||
if not cfg.fetch_sql:
|
||||
run.status = 'success'
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.error_message = '无抓取SQL,跳过外部系统数据抓取'
|
||||
try:
|
||||
if task.notify_enabled:
|
||||
_notify_schedule_run_wecom(task, run)
|
||||
except Exception as wecom_exc:
|
||||
current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc)
|
||||
db.session.commit()
|
||||
return jsonify({'run_no': run.run_no, 'run_id': run.id, 'sql': '', 'limit': 0, 'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 0, 'details': [], 'errors': [], 'step_logs': [{'step': 'no_fetch_sql', 'status': 'skipped', 'detail': '无抓取SQL,跳过外部系统数据抓取'}], 'dify_agent_id': dify_agent_id})
|
||||
|
||||
def _test_fetch_fn(conn_str_arg):
|
||||
return _fetch_records(conn_str_arg, test_sql)
|
||||
|
||||
def _test_writeback_fn(conn_str_arg, *, row_id, run_no, dify_result, dify_message):
|
||||
_execute_writeback(conn_str_arg, cfg.writeback_sql, (run_no, dify_result, dify_message, str(row_id)))
|
||||
test_pre_dify = None
|
||||
test_build_record = None
|
||||
if cfg.detail_sql:
|
||||
|
||||
def _test_pre_dify(conn_str_arg, item, row_id_value):
|
||||
try:
|
||||
detail_rows = _fetch_records(conn_str_arg, cfg.detail_sql, params=(str(row_id_value),))
|
||||
except Exception as detail_exc:
|
||||
return {'dify_result': '人工判定', 'dify_message': f'查询成分明细失败:{detail_exc}', 'writeback_srm': False, 'writeback_err': str(detail_exc)}
|
||||
detail_lines = []
|
||||
for dr in detail_rows:
|
||||
parts = [f"{cfg.header_labels.get(dk, dk)}: {dr.get(dk, '')}" for dk in cfg.detail_alias_order]
|
||||
detail_lines.append(', '.join(parts))
|
||||
item['detail_text'] = '; '.join(detail_lines) if detail_lines else ''
|
||||
item['_detail_rows'] = detail_rows
|
||||
return None
|
||||
test_pre_dify = _test_pre_dify
|
||||
|
||||
def _test_build_with_detail(conn_str_arg, item, row_id_value):
|
||||
detail_rows = item.get('_detail_rows', [])
|
||||
text = _build_record_text(item, cfg.alias_order, cfg.header_labels, detail_rows, cfg.detail_alias_order)
|
||||
return (text, item.get('attachment'))
|
||||
test_build_record = _test_build_with_detail
|
||||
else:
|
||||
|
||||
def _test_build_simple(conn_str_arg, item, row_id_value):
|
||||
text = _build_record_text(item, cfg.alias_order, cfg.header_labels)
|
||||
return (text, item.get('attachment'))
|
||||
test_build_record = _test_build_simple
|
||||
start_ts = _time.time()
|
||||
try:
|
||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_check_job_loop(conn_str=conn_str, run_no=run.run_no, agent=agent, user=user, wait_seconds=wait_seconds, run_id=run.id, fetch_fn=_test_fetch_fn, build_record_fn=test_build_record, writeback_fn=_test_writeback_fn, writeback_sql=cfg.writeback_sql, row_id_key=cfg.row_id_key, log_prefix=cfg.log_prefix, fetch_sql=test_sql, max_rows=limit, pre_dify_fn=test_pre_dify, dify_system_prompt=cfg.dify_system_prompt)
|
||||
duration_ms = int((_time.time() - start_ts) * 1000)
|
||||
if total_count == 0 and (not errors):
|
||||
status = 'success'
|
||||
elif failed_count == 0:
|
||||
status = 'success'
|
||||
elif success_count == 0:
|
||||
status = 'failed'
|
||||
else:
|
||||
status = 'partial_failed'
|
||||
header_order = cfg.alias_order if cfg.alias_order else None
|
||||
header_labels = cfg.header_labels if cfg.header_labels else None
|
||||
detail_alias_order = cfg.detail_alias_order or []
|
||||
try:
|
||||
file_data, file_name, file_size = export_schedule_result_excel(run_no=run.run_no, summary={'status': status, 'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'duration_ms': duration_ms}, details=details, header_order=header_order, header_labels=header_labels, detail_alias_order=detail_alias_order)
|
||||
except Exception as excel_exc:
|
||||
current_app.logger.error('[schedule-test-run] excel export failed: %s', excel_exc, exc_info=True)
|
||||
file_data, file_name, file_size = (None, None, 0)
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.duration_ms = duration_ms
|
||||
run.status = status
|
||||
run.total_count = total_count
|
||||
run.success_count = success_count
|
||||
run.failed_count = failed_count
|
||||
run.skipped_count = skipped_count
|
||||
run.step_logs = step_logs if step_logs else None
|
||||
run.error_message = '; '.join(errors[:3]) if errors else None
|
||||
run.excel_file_data = file_data
|
||||
run.excel_file_name = file_name
|
||||
run.excel_file_size = file_size or 0
|
||||
db.session.commit()
|
||||
if test_kb_sync_enabled:
|
||||
try:
|
||||
from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb
|
||||
|
||||
db.session.refresh(task)
|
||||
db.session.refresh(run)
|
||||
sync_schedule_run_excel_to_kb(task, run, enabled=True, process_inline=True)
|
||||
db.session.refresh(run)
|
||||
except Exception as kb_exc:
|
||||
db.session.rollback()
|
||||
db.session.refresh(run)
|
||||
current_app.logger.error('[schedule-test-run] kb sync failed: %s', kb_exc, exc_info=True)
|
||||
run.kb_sync_status = 'failed'
|
||||
run.kb_group_id = getattr(task, 'kb_group_id', None)
|
||||
run.kb_sync_error = str(kb_exc)
|
||||
db.session.commit()
|
||||
try:
|
||||
if task.notify_enabled:
|
||||
_notify_schedule_run_wecom(task, run)
|
||||
except Exception as wecom_exc:
|
||||
current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc)
|
||||
import decimal, datetime as dt
|
||||
|
||||
def _safe(v):
|
||||
if isinstance(v, decimal.Decimal):
|
||||
return float(v)
|
||||
if isinstance(v, (dt.date, dt.datetime)):
|
||||
return v.isoformat()
|
||||
if isinstance(v, dt.timedelta):
|
||||
return str(v)
|
||||
return v
|
||||
safe_details = []
|
||||
for item in details:
|
||||
safe_item = {k: _safe(v) for k, v in item.items()}
|
||||
safe_details.append(safe_item)
|
||||
return jsonify({'run_no': run.run_no, 'run_id': run.id, 'sql': test_sql, 'limit': limit, 'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'skipped_count': skipped_count, 'details': safe_details, 'errors': errors, 'step_logs': step_logs, 'dify_agent_id': dify_agent_id, 'dify_execution_snapshot': run.dify_execution_snapshot, 'kb_sync_status': run.kb_sync_status, 'kb_sync_error': run.kb_sync_error, 'kb_document_id': run.kb_document_id})
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
run = db.session.get(ScheduleRun, run.id)
|
||||
duration_ms = int((_time.time() - start_ts) * 1000)
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.duration_ms = duration_ms
|
||||
run.status = 'failed'
|
||||
run.error_message = str(e)
|
||||
db.session.commit()
|
||||
import traceback
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message=str(e), http_status=400, details={'sql': test_sql, 'traceback': traceback.format_exc()})
|
||||
|
||||
@schedule_admin_bp.route('/schedules', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedules():
|
||||
return jsonify(list_tasks())
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/export', methods=['GET'])
|
||||
@require_admin
|
||||
def export_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
payload = {'schema_version': 1, 'exported_at': datetime.utcnow().isoformat(), 'schedules': [_serialize_task_for_export(task, cfg_model)]}
|
||||
body = json.dumps(payload, ensure_ascii=False, indent=2)
|
||||
filename = f"{task.schedule_no or f'schedule_{task.id}'}_export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
|
||||
return Response(body, mimetype='application/json; charset=utf-8', headers={'Content-Disposition': f'attachment; filename="{filename}"'})
|
||||
|
||||
@schedule_admin_bp.route('/schedules/import', methods=['POST'])
|
||||
@require_admin
|
||||
def import_schedules():
|
||||
data = request.get_json(silent=True) or {}
|
||||
schedules = data.get('schedules')
|
||||
if not isinstance(schedules, list):
|
||||
raise ValidationError('Invalid import file: schedules missing')
|
||||
user = get_current_user()
|
||||
imported = 0
|
||||
skipped = 0
|
||||
errors: list[str] = []
|
||||
for item in schedules:
|
||||
if not isinstance(item, dict):
|
||||
skipped += 1
|
||||
continue
|
||||
try:
|
||||
name = str(item.get('name') or '').strip()
|
||||
cron_expr = str(item.get('cron_expr') or '').strip()
|
||||
owner_user_id = int(item.get('owner_user_id'))
|
||||
if not name or not cron_expr:
|
||||
raise ValueError('name or cron_expr missing')
|
||||
existing = None
|
||||
schedule_no = str(item.get('schedule_no') or '').strip()
|
||||
if schedule_no:
|
||||
existing = db.session.query(ScheduleTask).filter_by(schedule_no=schedule_no).first()
|
||||
task_payload = {'name': name, 'schedule_type': str(item.get('schedule_type') or 'platform_app'), 'owner_user_id': owner_user_id, 'cron_expr': cron_expr, '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))
|
||||
existing.data_source_type = task_payload['data_source_type']
|
||||
if cfg:
|
||||
upsert_schedule_task_config(existing.id, cfg)
|
||||
else:
|
||||
task = create_task(name=name, schedule_type=task_payload['schedule_type'], owner_user_id=owner_user_id, cron_expr=cron_expr, schedule_timezone=task_payload['schedule_timezone'], wait_seconds=task_payload['wait_seconds'], dify_agent_id=task_payload['dify_agent_id'], platform_api_path=task_payload['platform_api_path'], notify_user_ids_json=task_payload['notify_user_ids_json'], notify_enabled=task_payload['notify_enabled'], enabled=task_payload['enabled'], actor_id=getattr(user, 'id', None))
|
||||
task.data_source_type = task_payload['data_source_type']
|
||||
task.kb_sync_enabled = task_payload['kb_sync_enabled']
|
||||
task.kb_group_id = int(task_payload['kb_group_id']) if task_payload.get('kb_group_id') not in (None, '', 0, '0') else None
|
||||
db.session.commit()
|
||||
if cfg:
|
||||
upsert_schedule_task_config(task.id, cfg)
|
||||
imported += 1
|
||||
except Exception as exc:
|
||||
errors.append(str(exc))
|
||||
skipped += 1
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True, 'imported': imported, 'skipped': skipped, 'errors': errors[:20]})
|
||||
|
||||
@schedule_admin_bp.route('/schedules', methods=['POST'])
|
||||
@require_admin
|
||||
def post_schedule():
|
||||
data = request.get_json(silent=True) or {}
|
||||
user = get_current_user()
|
||||
data_source_type = str(data.get('data_source_type') or 'database')
|
||||
task = create_task(name=str(data.get('name') or '').strip(), schedule_type='platform_app', owner_user_id=int(data.get('owner_user_id')), cron_expr=str(data.get('cron_expr') or '').strip(), 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
|
||||
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 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()
|
||||
if cfg_model and cfg_model.dify_system_prompt:
|
||||
cfg_model.dify_system_prompt = None
|
||||
db.session.commit()
|
||||
return (jsonify(serialize_task(task)), 201)
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['PATCH'])
|
||||
@require_admin
|
||||
def patch_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
user = get_current_user()
|
||||
if 'data_source_type' in data:
|
||||
task.data_source_type = str(data['data_source_type'])
|
||||
db.session.commit()
|
||||
config_data = data.get('config')
|
||||
if config_data:
|
||||
upsert_schedule_task_config(task_id, config_data)
|
||||
task = update_task(task, payload=data, actor_id=getattr(user, 'id', None))
|
||||
if not task.dify_agent_id:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if cfg_model and cfg_model.dify_system_prompt:
|
||||
cfg_model.dify_system_prompt = None
|
||||
db.session.commit()
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.schedule.scheduler_service import request_cancel_run
|
||||
running_runs = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id, ScheduleRun.status == 'running').all()
|
||||
for rr in running_runs:
|
||||
request_cancel_run(rr.id)
|
||||
rr.status = 'failed'
|
||||
rr.error_message = '排程已被删除,执行中断'
|
||||
rr.finished_at = datetime.utcnow()
|
||||
if running_runs:
|
||||
db.session.commit()
|
||||
db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False)
|
||||
db.session.delete(task)
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/enable', methods=['POST'])
|
||||
@require_admin
|
||||
def enable_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
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:
|
||||
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(serialize_task(task))
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/disable', methods=['POST'])
|
||||
@require_admin
|
||||
def disable_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
task.enabled = False
|
||||
task.next_run_at = None
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
|
||||
@require_admin
|
||||
def run_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
user = get_current_user()
|
||||
existing = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task.id, ScheduleRun.status == 'running').first()
|
||||
if existing:
|
||||
raise ConflictError('该排程正在执行中,请等待完成后再试', details={'run_id': existing.id})
|
||||
run = ScheduleRun(run_no=_generate_run_no(), schedule_task_id=task.id, trigger_type='manual', triggered_by_user_id=getattr(user, 'id', None), started_at=datetime.utcnow(), status='running')
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
app = current_app._get_current_object()
|
||||
run_id = run.id
|
||||
|
||||
def _background():
|
||||
with app.app_context():
|
||||
t = db.session.get(ScheduleTask, task_id)
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if not t or not r:
|
||||
return
|
||||
try:
|
||||
run_task_now(t, trigger_type='manual', triggered_by_user_id=r.triggered_by_user_id, run=r)
|
||||
except Exception as exc:
|
||||
try:
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if r and r.status == 'running':
|
||||
r.status = 'failed'
|
||||
r.error_message = str(exc)
|
||||
r.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
current_app.logger.error('[schedule-run] run_id=%s failed: %s', run_id, exc, exc_info=True)
|
||||
t = threading.Thread(target=_background, daemon=True, name=f'schedule-run-{run_id}')
|
||||
t.start()
|
||||
fresh = db.session.get(ScheduleRun, run_id)
|
||||
return jsonify(serialize_run(fresh))
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/runs', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_runs(task_id: int):
|
||||
status = str(request.args.get('status') or '').strip() or None
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
started_after = None
|
||||
started_before = None
|
||||
sa = request.args.get('started_after')
|
||||
sb = request.args.get('started_before')
|
||||
if sa:
|
||||
try:
|
||||
started_after = datetime.fromisoformat(sa.replace('Z', '+00:00'))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
if sb:
|
||||
try:
|
||||
started_before = datetime.fromisoformat(sb.replace('Z', '+00:00'))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
return jsonify(list_runs(task_id=task_id, status=status, started_after=started_after, started_before=started_before, limit=limit))
|
||||
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_run(run_id: int):
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(serialize_run(run))
|
||||
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_run_excel(run_id: int):
|
||||
from io import BytesIO
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError('Excel not found')
|
||||
buf = BytesIO(run.excel_file_data)
|
||||
return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
__all__ = ['schedule_admin_bp']
|
||||
@@ -2,16 +2,25 @@
|
||||
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。
|
||||
依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url。
|
||||
逻辑:Tool 成功响应仍用 status: ok/failed 业务 envelope;HTTP 级参数/资源错误统一 raise AppError。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.errors import AppError, ServiceUnavailableError, UnauthorizedError
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
)
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
|
||||
from app.services.shipping_notice.query_service import (
|
||||
EXPORT_MIME_TYPE,
|
||||
get_batch_by_no,
|
||||
@@ -24,8 +33,8 @@ from app.services.shipping_notice.query_service import (
|
||||
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_common import switch_batch_focus
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import record_rpa_worker_heartbeat
|
||||
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||
|
||||
shipping_notice_bp = Blueprint("shipping_notice", __name__)
|
||||
@@ -36,48 +45,47 @@ 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` 作为服务端校验值;
|
||||
未配置时报服务不可用,缺失或错误时报未授权。
|
||||
核心逻辑:只接受 `Authorization: Bearer <token>` 或 `X-Integration-Key`。
|
||||
货代专用 `SHIPPING_NOTICE_TOOL_API_KEY` 优先,未配置时回退 `INTEGRATION_API_KEY`;
|
||||
未配置任何可用 key 时报服务不可用,缺失或错误时报未授权。
|
||||
"""
|
||||
configured = str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
|
||||
configured = str(
|
||||
current_app.config.get('SHIPPING_NOTICE_TOOL_API_KEY')
|
||||
or current_app.config.get('INTEGRATION_API_KEY')
|
||||
or ''
|
||||
).strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError(
|
||||
"INTEGRATION_API_KEY is not configured",
|
||||
code="missing_auth",
|
||||
'SHIPPING_NOTICE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured',
|
||||
code='missing_auth',
|
||||
)
|
||||
|
||||
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||
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")
|
||||
|
||||
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"}:
|
||||
message = str(exc.message or '').strip()
|
||||
if message in {'missing_auth', 'invalid_auth'}:
|
||||
return message
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
return "missing_auth"
|
||||
if exc.code == '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
|
||||
|
||||
body: dict[str, object] = {'ok': False, 'error_code': _tool_error_code(exc), 'message': exc.message}
|
||||
if exc.details:
|
||||
body['details'] = exc.details
|
||||
return jsonify(body), exc.http_status
|
||||
|
||||
@shipping_notice_bp.before_request
|
||||
def _verify_tool_access():
|
||||
@@ -85,97 +93,70 @@ def _verify_tool_access():
|
||||
对货代 Tool / RPA / 导出接口做统一 Header 鉴权。
|
||||
核心逻辑:仅放行 OpenAPI 导入文档,其他请求都必须携带有效 Tool Key。
|
||||
"""
|
||||
if request.path.endswith("/openapi.json") or request.path.endswith("/openapi.dify.yaml"):
|
||||
if request.path.endswith('/openapi.json') or request.path.endswith('/openapi.dify.yaml'):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
def _tool_api_base_url() -> str:
|
||||
"""Base URL for OpenAPI servers — hxops backend, NOT Dify (8882)."""
|
||||
return resolve_tool_api_base_url()
|
||||
|
||||
|
||||
def _dify_openapi_spec() -> dict:
|
||||
return build_dify_openapi_spec(_tool_api_base_url())
|
||||
|
||||
|
||||
def _payload() -> dict:
|
||||
return request.get_json(silent=True) or {}
|
||||
|
||||
|
||||
def _generate_batch_no() -> str:
|
||||
from datetime import datetime
|
||||
|
||||
return f"SB-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
@shipping_notice_bp.route('/tools/openapi.json', methods=['GET'])
|
||||
def openapi_spec():
|
||||
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
|
||||
return jsonify(_dify_openapi_spec())
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/checkpoint-catalog", methods=["GET"])
|
||||
@shipping_notice_bp.route('/tools/checkpoint-catalog', methods=['GET'])
|
||||
def checkpoint_catalog():
|
||||
"""返回检查点目录,供开发联调和文档核对 human_options/action_buttons。"""
|
||||
from app.services.shipping_notice.state_machine import build_checkpoint_catalog
|
||||
|
||||
return jsonify(build_checkpoint_catalog())
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/openapi.dify.yaml", methods=["GET"])
|
||||
@shipping_notice_bp.route('/tools/openapi.dify.yaml', methods=['GET'])
|
||||
def openapi_dify_yaml():
|
||||
"""返回 Dify 导入用的 OpenAPI YAML 文档。"""
|
||||
import yaml
|
||||
|
||||
body = yaml.safe_dump(_dify_openapi_spec(), allow_unicode=True, sort_keys=False)
|
||||
return current_app.response_class(body, mimetype="text/yaml; charset=utf-8")
|
||||
return current_app.response_class(body, mimetype='text/yaml; charset=utf-8')
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/create_task", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/create_task', methods=['POST'])
|
||||
def tool_create_task():
|
||||
"""
|
||||
创建单个发货任务。
|
||||
【AI 触发时机】:当用户首次提交一张新的发货通知、当前会话里还没有对应任务时调用。
|
||||
【AI 触发时机】:仅供 Hxops 内部建单链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.create_task(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/create_batch", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/create_batch', methods=['POST'])
|
||||
def tool_create_batch():
|
||||
"""
|
||||
创建或复用发货批次。
|
||||
【AI 触发时机】:当用户一次处理多份发货通知,需要把多任务挂到同一批次时调用。
|
||||
【AI 触发时机】:仅供 Hxops 内部建批链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
payload = _payload()
|
||||
if isinstance(payload.get("notice_items"), list) and payload.get("notice_items"):
|
||||
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()
|
||||
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)
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已复用批次 {batch.batch_no}', 'data': serialize_batch_summary(batch)})
|
||||
batch, _created = shipping_tools.create_batch(payload)
|
||||
db.session.commit()
|
||||
return jsonify(
|
||||
{
|
||||
"status": "ok",
|
||||
"batch_no": batch.batch_no,
|
||||
"message": f"已创建批次 {batch.batch_no}",
|
||||
"data": serialize_batch_summary(batch),
|
||||
}
|
||||
)
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已创建批次 {batch.batch_no}', 'data': serialize_batch_summary(batch)})
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/parse_notice", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/parse_notice', methods=['POST'])
|
||||
def tool_parse_notice():
|
||||
"""
|
||||
解析发货通知正文。
|
||||
@@ -183,8 +164,7 @@ def tool_parse_notice():
|
||||
"""
|
||||
return jsonify(shipping_tools.parse_notice(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/update_notice_fields", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/update_notice_fields', methods=['POST'])
|
||||
def tool_update_notice_fields():
|
||||
"""
|
||||
修改发货通知单头字段。
|
||||
@@ -192,8 +172,7 @@ def tool_update_notice_fields():
|
||||
"""
|
||||
return jsonify(shipping_tools.update_notice_fields(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/update_notice_line", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/update_notice_line', methods=['POST'])
|
||||
def tool_update_notice_line():
|
||||
"""
|
||||
修改指定订单行。
|
||||
@@ -201,8 +180,7 @@ def tool_update_notice_line():
|
||||
"""
|
||||
return jsonify(shipping_tools.update_notice_line(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/add_notice_line", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/add_notice_line', methods=['POST'])
|
||||
def tool_add_notice_line():
|
||||
"""
|
||||
新增订单行。
|
||||
@@ -210,8 +188,7 @@ def tool_add_notice_line():
|
||||
"""
|
||||
return jsonify(shipping_tools.add_notice_line(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/remove_notice_line", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/remove_notice_line', methods=['POST'])
|
||||
def tool_remove_notice_line():
|
||||
"""
|
||||
删除订单行。
|
||||
@@ -219,8 +196,7 @@ def tool_remove_notice_line():
|
||||
"""
|
||||
return jsonify(shipping_tools.remove_notice_line(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/parse_inventory", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/parse_inventory', methods=['POST'])
|
||||
def tool_parse_inventory():
|
||||
"""
|
||||
解析库存内容。
|
||||
@@ -228,19 +204,17 @@ def tool_parse_inventory():
|
||||
"""
|
||||
return jsonify(shipping_tools.parse_inventory(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/upload_inventory_file", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/upload_inventory_file', methods=['POST'])
|
||||
def tool_upload_inventory_file():
|
||||
"""
|
||||
服务器侧接收库存 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")
|
||||
task_id = str(request.form.get('task_id') or request.args.get('task_id') or '').strip()
|
||||
upload = request.files.get('file')
|
||||
return jsonify(shipping_tools.upload_inventory_file(task_id, upload))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/get_inventory_schema_preview", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/get_inventory_schema_preview', methods=['POST'])
|
||||
def tool_get_inventory_schema_preview():
|
||||
"""
|
||||
获取库存表头预览。
|
||||
@@ -248,8 +222,7 @@ def tool_get_inventory_schema_preview():
|
||||
"""
|
||||
return jsonify(shipping_tools.get_inventory_schema_preview(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/apply_inventory_mapping", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/apply_inventory_mapping', methods=['POST'])
|
||||
def tool_apply_inventory_mapping():
|
||||
"""
|
||||
应用库存字段映射。
|
||||
@@ -257,35 +230,31 @@ def tool_apply_inventory_mapping():
|
||||
"""
|
||||
return jsonify(shipping_tools.apply_inventory_mapping(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/ensure_inventory", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/ensure_inventory', methods=['POST'])
|
||||
def tool_ensure_inventory():
|
||||
"""
|
||||
保证任务已取得库存数据。
|
||||
【AI 触发时机】:当发货通知已确认,下一步需要让系统拿到库存快照时调用。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.ensure_inventory(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/auto_progress", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/auto_progress', methods=['POST'])
|
||||
def tool_auto_progress():
|
||||
"""
|
||||
自动推进任务。
|
||||
【AI 触发时机】:当用户说“继续处理”“自动推进”“跑到下一步”时调用。
|
||||
【AI 触发时机】:仅供后端 orchestrator / worker 调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.auto_progress(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/match_inventory", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/match_inventory', methods=['POST'])
|
||||
def tool_match_inventory():
|
||||
"""
|
||||
执行库存匹配。
|
||||
【AI 触发时机】:当发货通知与库存都已准备好,需要判断是否缺货并生成匹配结果时调用。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.match_inventory(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/submit_decision", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/submit_decision', methods=['POST'])
|
||||
def tool_submit_decision():
|
||||
"""
|
||||
提交人工决策。
|
||||
@@ -294,25 +263,32 @@ def tool_submit_decision():
|
||||
return jsonify(shipping_tools.submit_decision(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/generate_shipment_excel", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/confirm_inventory_source', methods=['POST'])
|
||||
def tool_confirm_inventory_source():
|
||||
"""
|
||||
确认库存查询来源(仅提交 source_code)。
|
||||
【AI 触发时机】:用户在库存源人工检查点选择正式库存源后调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.confirm_inventory_source(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/generate_shipment_excel', methods=['POST'])
|
||||
def tool_generate_shipment_excel():
|
||||
"""
|
||||
生成出货 Excel。
|
||||
【AI 触发时机】:当库存匹配已通过,用户要求导出货代上传模板时调用。
|
||||
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.generate_excel(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/upload_to_freight", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/upload_to_freight', methods=['POST'])
|
||||
def tool_upload_to_freight():
|
||||
"""
|
||||
上传到货代系统或确认人工上传完成。
|
||||
【AI 触发时机】:当用户要求推送到货代系统,或确认已手工完成上传时调用。
|
||||
【AI 触发时机】:仅供后端主调度、内部恢复链路或人工上传收口调用;不是 Dify 画布正式入口。
|
||||
"""
|
||||
return jsonify(shipping_tools.upload_to_freight(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/get_task_status", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tools/get_task_status', methods=['POST'])
|
||||
def tool_get_task_status():
|
||||
"""
|
||||
查询任务状态。
|
||||
@@ -320,93 +296,97 @@ def tool_get_task_status():
|
||||
"""
|
||||
return jsonify(shipping_tools.get_task_status(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/get_batch_status", methods=["POST"])
|
||||
@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()
|
||||
batch_no = str(payload.get('batch_no') or '').strip()
|
||||
if not batch_no:
|
||||
return jsonify({"status": "failed", "message": "batch_no is required"}), 400
|
||||
raise ValidationError("batch_no is required")
|
||||
batch = get_batch_by_no(batch_no)
|
||||
if not batch:
|
||||
return jsonify({"status": "failed", "message": "batch not found"}), 404
|
||||
raise NotFoundError("batch not found")
|
||||
focus_task = get_focus_task_for_batch(batch_no, batch.user_id or 0) if batch.user_id is not None else None
|
||||
return jsonify(
|
||||
{
|
||||
"status": "ok",
|
||||
"batch_no": batch.batch_no,
|
||||
"message": f"已获取批次 {batch.batch_no} 状态",
|
||||
"data": {
|
||||
**serialize_batch_summary(batch),
|
||||
"focus_task": serialize_task_summary(focus_task) if focus_task else None,
|
||||
"tasks": list_batch_task_summaries(batch),
|
||||
},
|
||||
}
|
||||
)
|
||||
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"])
|
||||
@shipping_notice_bp.route('/tools/switch_focus_task', methods=['POST'])
|
||||
def tool_switch_focus_task():
|
||||
"""
|
||||
切换批次当前焦点任务。
|
||||
【AI 触发时机】:当用户在同一批次里要求“看第 N 个任务”或切换当前处理对象时调用。
|
||||
【AI 触发时机】:当前仅保留给 Hxops 内部切票能力;不属于 Dify 正式导出 Tool。
|
||||
"""
|
||||
payload = _payload()
|
||||
batch_no = str(payload.get("batch_no") or "").strip()
|
||||
task_no = str(payload.get("task_no") or payload.get("target_task_no") or "").strip()
|
||||
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
|
||||
raise ValidationError("batch_no and task_no are required")
|
||||
batch = get_batch_by_no(batch_no)
|
||||
if not batch:
|
||||
return jsonify({"status": "failed", "message": "batch not found"}), 404
|
||||
raise NotFoundError("batch not found")
|
||||
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),
|
||||
},
|
||||
}
|
||||
raise NotFoundError("task not found in batch")
|
||||
switch_batch_focus(
|
||||
batch,
|
||||
task,
|
||||
source="tool_api",
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'task_no': task.task_no, 'message': f'已切换当前任务到 {task.task_no}', 'data': {'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)}})
|
||||
|
||||
@shipping_notice_bp.route('/rpa/heartbeat', methods=['POST'])
|
||||
def rpa_worker_heartbeat():
|
||||
"""
|
||||
RPA Worker 心跳上报。
|
||||
核心逻辑:校验 payload 后写入 Redis/内存;供触发库存 RPA 前就绪检查使用。
|
||||
"""
|
||||
payload = _payload()
|
||||
try:
|
||||
worker = record_rpa_worker_heartbeat(payload)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc))
|
||||
except ServiceUnavailableError:
|
||||
raise
|
||||
return jsonify({'status': 'ok', 'message': 'heartbeat recorded', 'data': worker})
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/rpa/inventory-ready", methods=["POST"])
|
||||
@shipping_notice_bp.route('/rpa/inventory-ready', methods=['POST'])
|
||||
def rpa_inventory_ready():
|
||||
"""RPA 回调入口:上报库存导出结果并回写任务状态。"""
|
||||
return jsonify(shipping_tools.rpa_report_inventory(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-batch-ready', methods=['POST'])
|
||||
def rpa_inventory_batch_ready():
|
||||
"""RPA 批量库存导出回调:按 Warehouse 写入库存快照。"""
|
||||
return jsonify(shipping_tools.rpa_report_inventory_batch(_payload()))
|
||||
|
||||
@shipping_notice_bp.route("/rpa/upload-complete", methods=["POST"])
|
||||
@shipping_notice_bp.route('/tasks/<task_no>/repair-inventory-attachment', methods=['POST'])
|
||||
def repair_task_inventory_attachment(task_no: str):
|
||||
"""
|
||||
从任务库存快照幂等重建正式附件(不重新消费 RPA callback)。
|
||||
核心逻辑:供晋升失败或 marker 异常后的人工/后台补偿。
|
||||
"""
|
||||
payload = _payload()
|
||||
payload.setdefault("task_no", task_no)
|
||||
payload.setdefault("task_id", task_no)
|
||||
return jsonify(shipping_tools.repair_task_inventory_attachment(payload))
|
||||
|
||||
@shipping_notice_bp.route('/rpa/upload-complete', methods=['POST'])
|
||||
def rpa_upload_complete():
|
||||
"""RPA 回调入口:上报货代上传结果并回写任务状态。"""
|
||||
return jsonify(shipping_tools.rpa_report_upload(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tasks/<task_no>/export", methods=["GET"])
|
||||
@shipping_notice_bp.route('/tasks/<task_no>/export', methods=['GET'])
|
||||
def download_task_export(task_no: str):
|
||||
"""下载任务已生成的出货 Excel。"""
|
||||
task = get_task_by_ref(task_no)
|
||||
err_msg = task_export_error_message(task)
|
||||
if err_msg:
|
||||
return jsonify({"error": err_msg}), 404
|
||||
raise NotFoundError(err_msg)
|
||||
resolved = resolve_task_export_download(task)
|
||||
assert resolved is not None
|
||||
path, download_name = resolved
|
||||
return send_file(
|
||||
path,
|
||||
as_attachment=True,
|
||||
download_name=download_name,
|
||||
mimetype=EXPORT_MIME_TYPE,
|
||||
)
|
||||
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
|
||||
@@ -3,8 +3,8 @@ Speech transcription API — forwards audio to SiliconFlow ASR.
|
||||
"""
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.errors import UnauthorizedError, ValidationError, ServiceUnavailableError
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import UnauthorizedError, ValidationError, ServiceUnavailableError
|
||||
from app.services.speech_asr import SpeechAsrService
|
||||
|
||||
speech_bp = Blueprint('speech', __name__)
|
||||
|
||||
@@ -6,5 +6,6 @@ backend/app/api/tools/__init__.py
|
||||
"""
|
||||
from app.api.tools.shipping_notice import shipping_notice_bp # noqa: F401
|
||||
from app.api.tools.file_check import file_check_bp # noqa: F401
|
||||
from app.api.tools.maintenance import maintenance_tool_bp # noqa: F401
|
||||
|
||||
__all__ = ['shipping_notice_bp', 'file_check_bp']
|
||||
@@ -0,0 +1,9 @@
|
||||
"""
|
||||
backend/app/api/tools/maintenance.py
|
||||
|
||||
用途:设备维保 Tool API Blueprint re-export。
|
||||
依赖:app.api.maintenance_tools。
|
||||
逻辑:保持 api.tools 分包统一入口,register_blueprints 只从 app.api.tools 导入各 Tool Blueprint。
|
||||
"""
|
||||
|
||||
from app.api.maintenance_tools import maintenance_tool_bp # noqa: F401
|
||||
@@ -0,0 +1,126 @@
|
||||
"""
|
||||
backend/app/api/training.py
|
||||
|
||||
用途:提供新人培训用户侧进度接口与管理端统计导出接口。
|
||||
依赖:JWT 当前用户解析、training_service、Flask Blueprint/send_file。
|
||||
逻辑:员工端负责读写个人培训进度;管理端负责真实记录查询、统计与 Excel 导出。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, UnauthorizedError
|
||||
from app.services.training_service import (
|
||||
export_training_records_excel,
|
||||
get_user_training_record,
|
||||
list_training_records,
|
||||
serialize_training_record,
|
||||
summarize_training_records,
|
||||
upsert_user_training_record,
|
||||
)
|
||||
|
||||
training_user_bp = Blueprint("training_user", __name__)
|
||||
training_admin_bp = Blueprint("training_admin", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""确保当前请求存在登录用户。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _require_training_admin():
|
||||
"""
|
||||
确保当前用户具备培训管理权限。
|
||||
|
||||
用途:统一拦截 HR 管理面板的数据查询、统计与导出接口。
|
||||
核心逻辑:优先复用 User.can_manage_training(),把“角色默认权限 + 前端可配置功能权限”收敛到同一个判断入口。
|
||||
"""
|
||||
user = _require_user()
|
||||
if not user.can_manage_training():
|
||||
raise ForbiddenError("Training admin privilege required")
|
||||
return user
|
||||
|
||||
|
||||
@training_user_bp.route("/training-record", methods=["GET"])
|
||||
def get_my_training_record():
|
||||
"""读取当前用户的培训进度;未创建时返回 null data。"""
|
||||
user = _require_user()
|
||||
record = get_user_training_record(user.id)
|
||||
return jsonify(serialize_training_record(record) if record else None)
|
||||
|
||||
|
||||
@training_user_bp.route("/training-record/progress", methods=["PUT"])
|
||||
def save_my_training_record():
|
||||
"""保存当前用户培训进度,用于视频完成、答题推进与结算归档。"""
|
||||
user = _require_user()
|
||||
payload = request.get_json() or {}
|
||||
record = upsert_user_training_record(user, payload)
|
||||
return jsonify(serialize_training_record(record))
|
||||
|
||||
|
||||
@training_admin_bp.route("/training-records", methods=["GET"])
|
||||
def list_admin_training_records():
|
||||
"""列出培训记录,支持关键字、部门、状态筛选。"""
|
||||
_require_training_admin()
|
||||
keyword = request.args.get("keyword")
|
||||
department = request.args.get("department")
|
||||
status = request.args.get("status")
|
||||
|
||||
result = list_training_records(keyword=keyword, department=department, status=status)
|
||||
all_records = list_training_records()
|
||||
department_options = sorted({str(item.department or "").strip() for item in all_records.records if str(item.department or "").strip()})
|
||||
|
||||
page = max(1, request.args.get("page", type=int) or 1)
|
||||
page_size = max(1, min(200, request.args.get("page_size", type=int) or max(result.total, 1)))
|
||||
start = (page - 1) * page_size
|
||||
end = start + page_size
|
||||
items = result.records[start:end]
|
||||
pages = max(1, (result.total + page_size - 1) // page_size) if result.total else 1
|
||||
|
||||
return jsonify(
|
||||
{
|
||||
"items": [serialize_training_record(item) for item in items],
|
||||
"total": result.total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"pages": pages,
|
||||
"department_options": department_options,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@training_admin_bp.route("/training-records/stats", methods=["GET"])
|
||||
def get_admin_training_stats():
|
||||
"""返回培训记录聚合统计,供 HR 面板展示。"""
|
||||
_require_training_admin()
|
||||
result = list_training_records(
|
||||
keyword=request.args.get("keyword"),
|
||||
department=request.args.get("department"),
|
||||
status=request.args.get("status"),
|
||||
)
|
||||
return jsonify(summarize_training_records(result.records))
|
||||
|
||||
|
||||
@training_admin_bp.route("/training-records/export", methods=["GET"])
|
||||
def export_admin_training_records():
|
||||
"""导出培训记录为 Excel。"""
|
||||
_require_training_admin()
|
||||
result = list_training_records(
|
||||
keyword=request.args.get("keyword"),
|
||||
department=request.args.get("department"),
|
||||
status=request.args.get("status"),
|
||||
)
|
||||
file_data, file_name = export_training_records_excel(result.records)
|
||||
return send_file(
|
||||
BytesIO(file_data),
|
||||
as_attachment=True,
|
||||
download_name=file_name,
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
+148
-508
@@ -1,11 +1,20 @@
|
||||
"""
|
||||
backend/app/api/user.py
|
||||
|
||||
用途:当前用户域 API(Casdoor 登录、企微 OAuth、首页、FAQ、反馈等)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、models、wecom/dify 相关 services。
|
||||
逻辑:薄路由层鉴权与参数校验;Casdoor/企微 OAuth 委托 services/auth/*。
|
||||
"""
|
||||
from flask import Blueprint, request, jsonify, current_app
|
||||
from app import db
|
||||
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, Announcement, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog
|
||||
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog
|
||||
from app.services.feedback_notify import send_feedback_group_notification
|
||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||
from app.services.agent_registry.serialization import serialize_registry_fields
|
||||
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
|
||||
from app.auth_jwt import get_current_user as _auth_current_user
|
||||
from app.auth_jwt import issue_local_access_token
|
||||
from app.core.auth.jwt import get_current_user as _auth_current_user
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
|
||||
from sqlalchemy import and_, or_, inspect, insert
|
||||
from datetime import datetime, timedelta
|
||||
@@ -18,11 +27,22 @@ import base64
|
||||
import json
|
||||
import re
|
||||
import ast
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
raise_for_status,
|
||||
)
|
||||
from app.services.auth import casdoor_service as _casdoor_svc
|
||||
from app.services.auth import wecom_auth_service as _wecom_svc
|
||||
user_bp = Blueprint('user', __name__)
|
||||
_WECOM_ACCESS_TOKEN_CACHE = {'token': None, 'expires_at': None}
|
||||
_WECOM_STATE_CACHE = {}
|
||||
_WECOM_BIND_SESSION_CACHE = {}
|
||||
_WECOM_ACCESS_TOKEN_CACHE = _wecom_svc.ACCESS_TOKEN_CACHE
|
||||
_WECOM_STATE_CACHE = _wecom_svc.STATE_CACHE
|
||||
_WECOM_BIND_SESSION_CACHE = _wecom_svc.BIND_SESSION_CACHE
|
||||
_PASSWORD_RESET_RATE_CACHE = {}
|
||||
_PASSWORD_RESET_GENERIC_MESSAGE = 'If the account exists and WeCom is bound, a reset link has been sent to your WeCom.'
|
||||
_ALLOWED_WECOM_MATCH_FIELDS = {'employee_id', 'mobile', 'email'}
|
||||
@@ -112,26 +132,11 @@ def _run_db_with_retry(operation, *, label: str):
|
||||
return operation()
|
||||
|
||||
def _get_wecom_config_missing_fields() -> list[str]:
|
||||
"""
|
||||
列出企微集成尚未配置的环境项。
|
||||
Returns:
|
||||
缺失的配置键名列表,如 WECOM_ENABLED、WECOM_CORP_ID 等。
|
||||
"""
|
||||
missing: list[str] = []
|
||||
if not current_app.config.get('WECOM_ENABLED'):
|
||||
missing.append('WECOM_ENABLED')
|
||||
if not _clean_str(current_app.config.get('WECOM_CORP_ID')):
|
||||
missing.append('WECOM_CORP_ID')
|
||||
if not _clean_str(current_app.config.get('WECOM_AGENT_ID')):
|
||||
missing.append('WECOM_AGENT_ID')
|
||||
if not _clean_str(current_app.config.get('WECOM_SECRET')):
|
||||
missing.append('WECOM_SECRET')
|
||||
return missing
|
||||
return _wecom_svc.get_config_missing_fields()
|
||||
|
||||
|
||||
def _is_wecom_configured() -> bool:
|
||||
"""企微 Corp/Agent/Secret 与总开关均已配置时返回 True。"""
|
||||
return len(_get_wecom_config_missing_fields()) == 0
|
||||
return _wecom_svc.is_configured()
|
||||
|
||||
def _issue_casdoor_state(redirect_uri: str):
|
||||
exp_ts = int((datetime.utcnow() + timedelta(minutes=10)).timestamp())
|
||||
@@ -252,330 +257,58 @@ def _is_casdoor_login_mode() -> bool:
|
||||
return (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() == 'casdoor'
|
||||
|
||||
def _is_casdoor_configured() -> bool:
|
||||
if not _clean_str(current_app.config.get('CASDOOR_ORGANIZATION')):
|
||||
return False
|
||||
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
|
||||
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
|
||||
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
|
||||
return bool(base and client_id and client_secret)
|
||||
return _casdoor_svc.is_casdoor_configured()
|
||||
|
||||
def _casdoor_user_owner() -> str:
|
||||
owner = _clean_str(current_app.config.get('CASDOOR_ORGANIZATION'))
|
||||
if not owner:
|
||||
raise RuntimeError('CASDOOR_ORGANIZATION is not configured')
|
||||
return owner
|
||||
return _casdoor_svc.casdoor_user_owner()
|
||||
|
||||
def _verify_casdoor_password(username: str, password: str):
|
||||
_casdoor_password_login(username, password)
|
||||
|
||||
def _casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str):
|
||||
base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/')
|
||||
client_id = current_app.config.get('CASDOOR_CLIENT_ID') or ''
|
||||
client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or ''
|
||||
if not base or not client_id or not client_secret:
|
||||
raise RuntimeError('Casdoor is not configured')
|
||||
url = f'{base}/api/set-password'
|
||||
resp = requests.post(url, files={'userOwner': (None, user_owner), 'userName': (None, user_name), 'oldPassword': (None, old_password), 'newPassword': (None, new_password)}, auth=(client_id, client_secret), timeout=8)
|
||||
try:
|
||||
data = resp.json() or {}
|
||||
except ValueError:
|
||||
raise RuntimeError(f'Casdoor set-password failed: HTTP {resp.status_code} {resp.text[:200]}')
|
||||
if data.get('status') != 'ok':
|
||||
_raise_casdoor_set_password_error(data)
|
||||
return _casdoor_svc.casdoor_set_password(user_owner, user_name, old_password, new_password)
|
||||
|
||||
def _is_casdoor_user_exists_error(message: str) -> bool:
|
||||
lowered = (message or '').lower()
|
||||
return 'already exist' in lowered or 'duplicate' in lowered or 'has existed' in lowered
|
||||
return _casdoor_svc.is_user_exists_error(message)
|
||||
|
||||
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
|
||||
_casdoor_svc.raise_add_user_error(source)
|
||||
|
||||
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)
|
||||
return _casdoor_svc.casdoor_add_user(user_payload)
|
||||
|
||||
def _sync_casdoor_create_user(*, username: str, password: str, email: str, real_name=None, phone_number=None, status='active', department=None):
|
||||
"""
|
||||
管理端创建用户时同步至 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)
|
||||
return _casdoor_svc.sync_create_user(username=username, password=password, email=email, real_name=real_name, phone_number=phone_number, status=status, department=department)
|
||||
|
||||
def _raise_casdoor_update_user_error(source) -> None:
|
||||
"""
|
||||
将 Casdoor 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]})
|
||||
_casdoor_svc.raise_update_user_error(source)
|
||||
|
||||
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)
|
||||
return _casdoor_svc.casdoor_update_user(user_payload)
|
||||
|
||||
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)
|
||||
return _casdoor_svc.sync_admin_set_password(user, new_password)
|
||||
|
||||
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
|
||||
return _casdoor_svc.sync_update_user(user, new_password=new_password)
|
||||
|
||||
def _is_casdoor_password_error(message: str) -> bool:
|
||||
lowered = (message or '').lower()
|
||||
return 'invalid_grant' in lowered or 'password login failed' in lowered or 'incorrect password' in lowered
|
||||
return _casdoor_svc.is_password_error(message)
|
||||
|
||||
def _is_casdoor_user_missing_error(message: str) -> bool:
|
||||
lowered = (message or '').lower()
|
||||
return (
|
||||
"doesn't exist" in lowered
|
||||
or 'does not exist' in lowered
|
||||
or 'user not found' in lowered
|
||||
or 'no such user' in lowered
|
||||
)
|
||||
return _casdoor_svc.is_user_missing_error(message)
|
||||
|
||||
def _raise_casdoor_user_not_in_idp(source=None) -> None:
|
||||
data = _extract_casdoor_error_payload(source)
|
||||
msg_text = _clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
|
||||
raise AppError(
|
||||
code='CASDOOR_USER_NOT_IN_IDP',
|
||||
message='Your account has not been registered in the authentication system. Please contact the administrator.',
|
||||
http_status=409,
|
||||
details={'technical': msg_text or str(source or '')[:300]},
|
||||
)
|
||||
_casdoor_svc.raise_user_not_in_idp(source)
|
||||
|
||||
def _extract_casdoor_error_payload(source) -> dict:
|
||||
if isinstance(source, dict):
|
||||
return source
|
||||
text = str(source or '')
|
||||
match = re.search(r'\{.*\}', text, re.DOTALL)
|
||||
if match:
|
||||
try:
|
||||
parsed = ast.literal_eval(match.group(0))
|
||||
if isinstance(parsed, dict):
|
||||
return parsed
|
||||
except (SyntaxError, ValueError):
|
||||
pass
|
||||
try:
|
||||
parsed = json.loads(text)
|
||||
if isinstance(parsed, dict):
|
||||
return parsed
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
pass
|
||||
return {}
|
||||
return _casdoor_svc.extract_error_payload(source)
|
||||
|
||||
def _raise_casdoor_auth_error(source, *, context: str, status_code: int = 401) -> None:
|
||||
"""
|
||||
Map Casdoor OAuth/API failures to stable business error codes for frontend i18n.
|
||||
context: password | verify | code | refresh
|
||||
"""
|
||||
data = _extract_casdoor_error_payload(source)
|
||||
raw = str(source or '')
|
||||
oauth_error = _clean_str(data.get('error')).lower()
|
||||
if not oauth_error and 'invalid_grant' in raw.lower():
|
||||
oauth_error = 'invalid_grant'
|
||||
if not oauth_error and 'invalid_client' in raw.lower():
|
||||
oauth_error = 'invalid_client'
|
||||
if oauth_error == 'invalid_grant' or _is_casdoor_password_error(raw):
|
||||
if context in ('password', 'verify'):
|
||||
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect username or password', http_status=401)
|
||||
raise AppError(code='CASDOOR_CODE_EXPIRED', message='Login session expired, please sign in again', http_status=401)
|
||||
if oauth_error in ('invalid_client', 'unauthorized_client'):
|
||||
raise AppError(code='CASDOOR_CONFIG_ERROR', message='Authentication service is misconfigured. Please contact the administrator.', http_status=503, details={'casdoor_error': oauth_error})
|
||||
if oauth_error == 'access_denied':
|
||||
raise AppError(code='CASDOOR_ACCESS_DENIED', message='Login was cancelled or denied', http_status=403)
|
||||
if 'token endpoint missing' in raw.lower() or 'casdoor_base_url is not configured' in raw.lower() or 'casdoor is not configured' in raw.lower():
|
||||
raise AppError(code='CASDOOR_CONFIG_ERROR', message='Authentication service is not configured. Please contact the administrator.', http_status=503)
|
||||
if 'invalid or expired casdoor state' in raw.lower():
|
||||
raise ValidationError('Invalid or expired Casdoor state')
|
||||
current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s raw=%s', context, data, raw[:500])
|
||||
raise AppError(code='CASDOOR_AUTH_FAILED', message='Authentication failed, please try again', http_status=status_code, details={'casdoor_error': oauth_error or None, 'technical': raw[:300]})
|
||||
_casdoor_svc.raise_auth_error(source, context=context, status_code=status_code)
|
||||
|
||||
def _raise_casdoor_set_password_error(source) -> None:
|
||||
data = _extract_casdoor_error_payload(source)
|
||||
msg_text = _clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
|
||||
lowered = (msg_text or str(source or '')).lower()
|
||||
if _is_casdoor_password_error(lowered) or 'old password' in lowered or 'current password' in lowered:
|
||||
_raise_incorrect_current_password()
|
||||
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
|
||||
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='New password does not meet security requirements', http_status=400)
|
||||
if _is_casdoor_user_missing_error(lowered):
|
||||
_raise_casdoor_user_not_in_idp(source)
|
||||
raise AppError(code='CASDOOR_SET_PASSWORD_FAILED', message='Failed to change password. Please try again or contact the administrator.', http_status=502, details={'technical': msg_text or str(source)[:300]})
|
||||
_casdoor_svc.raise_set_password_error(source)
|
||||
|
||||
def _raise_incorrect_current_password():
|
||||
raise AppError(
|
||||
@@ -673,17 +406,7 @@ def _consume_wecom_bind_session(token: str):
|
||||
return identity
|
||||
|
||||
def _parse_wecom_field_list(raw_value, default_fields: list[str]):
|
||||
if isinstance(raw_value, str):
|
||||
pieces = [item.strip().lower() for item in raw_value.split(',')]
|
||||
elif isinstance(raw_value, (list, tuple)):
|
||||
pieces = [str(item).strip().lower() for item in raw_value]
|
||||
else:
|
||||
pieces = []
|
||||
result = []
|
||||
for piece in pieces:
|
||||
if piece in _ALLOWED_WECOM_MATCH_FIELDS and piece not in result:
|
||||
result.append(piece)
|
||||
return result or list(default_fields)
|
||||
return _wecom_svc.parse_field_list(raw_value, default_fields)
|
||||
|
||||
def _verify_wecom_msg_signature(msg_signature: str, token: str, timestamp: str, nonce: str, encrypt: str) -> bool:
|
||||
if not msg_signature or not token or (not encrypt):
|
||||
@@ -711,24 +434,19 @@ def _persist_wecom_callback_audit(*, msg_signature, timestamp, nonce, encrypt_ra
|
||||
db.session.rollback()
|
||||
|
||||
def _get_wecom_access_token():
|
||||
now = datetime.utcnow()
|
||||
token = _WECOM_ACCESS_TOKEN_CACHE.get('token')
|
||||
expires_at = _WECOM_ACCESS_TOKEN_CACHE.get('expires_at')
|
||||
if token and expires_at and (now < expires_at):
|
||||
return token
|
||||
corp_id = current_app.config.get('WECOM_CORP_ID')
|
||||
secret = current_app.config.get('WECOM_SECRET')
|
||||
token_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
|
||||
resp = requests.get(token_url, params={'corpid': corp_id, 'corpsecret': secret}, timeout=8)
|
||||
data = resp.json()
|
||||
if data.get('errcode') != 0 or not data.get('access_token'):
|
||||
raise RuntimeError(f'Failed to fetch WeCom token: {data}')
|
||||
_WECOM_ACCESS_TOKEN_CACHE['token'] = data['access_token']
|
||||
_WECOM_ACCESS_TOKEN_CACHE['expires_at'] = now + timedelta(seconds=max(int(data.get('expires_in', 7200)) - 120, 60))
|
||||
return data['access_token']
|
||||
return _wecom_svc.get_access_token()
|
||||
|
||||
def _build_login_payload(user: User, source: str='password', bind_status: str=None):
|
||||
payload = {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'source': source, 'access_token': issue_local_access_token(user), 'token_type': 'Bearer'}
|
||||
payload = {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'default_agent_id': user.default_agent_id,
|
||||
'feature_permissions': user.get_feature_permissions(),
|
||||
'source': source,
|
||||
'access_token': issue_local_access_token(user),
|
||||
'token_type': 'Bearer',
|
||||
}
|
||||
if bind_status:
|
||||
payload['bind_status'] = bind_status
|
||||
return payload
|
||||
@@ -779,39 +497,16 @@ def _extract_wecom_extattr_value(wecom_user: dict, key: str):
|
||||
return None
|
||||
|
||||
def _get_wecom_match_config():
|
||||
raw_rules = current_app.config.get('WECOM_MATCH_RULES', 'employee_id,mobile')
|
||||
rules = _parse_wecom_field_list(raw_rules, ['employee_id', 'mobile'])
|
||||
operator = str(current_app.config.get('WECOM_MATCH_OPERATOR', 'AND')).upper()
|
||||
if operator not in {'AND', 'OR'}:
|
||||
operator = 'AND'
|
||||
return (rules, operator)
|
||||
return _wecom_svc.get_match_config()
|
||||
|
||||
def _get_wecom_first_login_bind_mode():
|
||||
mode = _clean_str(current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE')) or 'match_rules'
|
||||
mode = mode.lower()
|
||||
if mode not in {'match_rules', 'input_verify'}:
|
||||
mode = 'match_rules'
|
||||
return mode
|
||||
return _wecom_svc.get_first_login_bind_mode()
|
||||
|
||||
def _get_wecom_first_login_input_fields():
|
||||
raw_fields = current_app.config.get('WECOM_FIRST_LOGIN_INPUT_FIELDS', 'employee_id,mobile,email')
|
||||
return _parse_wecom_field_list(raw_fields, ['employee_id', 'mobile', 'email'])
|
||||
return _wecom_svc.get_first_login_input_fields()
|
||||
|
||||
def _extract_wecom_identity(wecom_user: dict):
|
||||
userid = _clean_str(wecom_user.get('userid'))
|
||||
unionid = _clean_str(wecom_user.get('unionid'))
|
||||
email = _clean_str(wecom_user.get('email'))
|
||||
mobile_raw = _clean_str(wecom_user.get('mobile'))
|
||||
normalize_mobile = bool(current_app.config.get('WECOM_MOBILE_NORMALIZE', True))
|
||||
mobile = _normalize_mobile(mobile_raw) if normalize_mobile else mobile_raw
|
||||
employee_id_source = _clean_str(current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE')) or 'userid'
|
||||
if employee_id_source == 'userid':
|
||||
employee_id = userid
|
||||
elif employee_id_source.startswith('extattr:'):
|
||||
employee_id = _extract_wecom_extattr_value(wecom_user, employee_id_source.split(':', 1)[1])
|
||||
else:
|
||||
employee_id = _clean_str(wecom_user.get(employee_id_source))
|
||||
return {'wecom_userid': userid, 'wecom_unionid': unionid, 'name': _clean_str(wecom_user.get('name')) or userid or 'wecom_user', 'email': email, 'mobile': mobile, 'mobile_raw': mobile_raw, 'employee_id': employee_id}
|
||||
return _wecom_svc.extract_identity(wecom_user)
|
||||
|
||||
def _mobile_candidates(identity: dict):
|
||||
values = []
|
||||
@@ -849,34 +544,7 @@ def _find_users_by_input_field(field: str, value):
|
||||
return ([], 'invalid_field')
|
||||
|
||||
def _find_users_by_match_rules(identity: dict, rules: list, operator: str):
|
||||
filters = []
|
||||
missing = []
|
||||
for rule in rules:
|
||||
if rule == 'employee_id':
|
||||
employee_id = _clean_str(identity.get('employee_id'))
|
||||
if not employee_id:
|
||||
missing.append('employee_id')
|
||||
else:
|
||||
filters.append(User.employee_id == employee_id)
|
||||
elif rule == 'mobile':
|
||||
candidates = _mobile_candidates(identity)
|
||||
if not candidates:
|
||||
missing.append('mobile')
|
||||
else:
|
||||
filters.append(User.phone_number.in_(candidates))
|
||||
elif rule == 'email':
|
||||
email = _clean_str(identity.get('email'))
|
||||
if not email:
|
||||
missing.append('email')
|
||||
else:
|
||||
filters.append(User.email == email)
|
||||
if missing:
|
||||
return ([], missing)
|
||||
if not filters:
|
||||
return ([], ['match_rules'])
|
||||
clause = and_(*filters) if operator == 'AND' else or_(*filters)
|
||||
users = db.session.query(User).filter(clause).all()
|
||||
return (users, [])
|
||||
return _wecom_svc.find_users_by_match_rules(identity, rules, operator)
|
||||
|
||||
def _assert_wecom_binding_not_occupied(user: User, identity: dict):
|
||||
wecom_userid = identity.get('wecom_userid')
|
||||
@@ -1014,7 +682,11 @@ def login():
|
||||
Can be disabled via AUTH_ALLOW_LOCAL_PASSWORD_LOGIN=false.
|
||||
"""
|
||||
if not bool(current_app.config.get('AUTH_ALLOW_LOCAL_PASSWORD_LOGIN', True)):
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='Password login is disabled. Please use Casdoor login.', http_status=403, details={'error_code': 'PASSWORD_LOGIN_DISABLED'})
|
||||
raise AppError(
|
||||
code='AUTH.PASSWORD_LOGIN_DISABLED',
|
||||
message='Password login is disabled. Please use Casdoor login.',
|
||||
http_status=403,
|
||||
)
|
||||
|
||||
def _attempt_login():
|
||||
data = request.get_json() or {}
|
||||
@@ -1070,7 +742,11 @@ def casdoor_password_login():
|
||||
Direct login with username/password against Casdoor (no browser redirect).
|
||||
"""
|
||||
if (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() != 'casdoor':
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='Casdoor password login is disabled by AUTH_LOGIN_MODE', http_status=403, details={'error_code': 'CASDOOR_PASSWORD_LOGIN_DISABLED'})
|
||||
raise AppError(
|
||||
code='AUTH.CASDOOR_PASSWORD_LOGIN_DISABLED',
|
||||
message='Casdoor password login is disabled by AUTH_LOGIN_MODE',
|
||||
http_status=403,
|
||||
)
|
||||
data = request.get_json() or {}
|
||||
username = _clean_str(data.get('username'))
|
||||
password = data.get('password') or ''
|
||||
@@ -1094,7 +770,7 @@ def casdoor_password_login():
|
||||
_write_login_audit('casdoor', 'success', user=user)
|
||||
db.session.commit()
|
||||
api_bearer_token = id_token or access_token
|
||||
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
|
||||
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
|
||||
except WeComLoginError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
@@ -1224,7 +900,7 @@ def casdoor_login():
|
||||
_write_login_audit('casdoor', 'success', user=user)
|
||||
db.session.commit()
|
||||
api_bearer_token = id_token or access_token
|
||||
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
|
||||
return jsonify({'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'source': 'casdoor', 'access_token': api_bearer_token, 'refresh_token': refresh_token, 'id_token': id_token, 'token_type': token_data.get('token_type') or 'Bearer', 'expires_in': expires_in})
|
||||
except WeComLoginError:
|
||||
db.session.rollback()
|
||||
current_app.logger.warning('[casdoor_login] business_reject')
|
||||
@@ -1281,7 +957,11 @@ def casdoor_refresh():
|
||||
except Exception as e:
|
||||
message = str(e)
|
||||
if 'unsupported_grant_type' in message or 'refresh_token is not supported' in message:
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='Casdoor refresh token is not supported by current application config', http_status=400, details={'error_code': 'CASDOOR_REFRESH_UNSUPPORTED'})
|
||||
raise AppError(
|
||||
code='AUTH.CASDOOR_REFRESH_UNSUPPORTED',
|
||||
message='Casdoor refresh token is not supported by current application config',
|
||||
http_status=400,
|
||||
)
|
||||
current_app.logger.exception('[casdoor_refresh] failed refresh=%s', _token_brief(refresh_token))
|
||||
raise UnauthorizedError(f'Casdoor refresh failed: {str(e)}')
|
||||
|
||||
@@ -1328,7 +1008,11 @@ def wecom_login():
|
||||
if not wecom_userid_value:
|
||||
_write_login_audit('wecom', 'failed', reason=f"not_in_agent_scope:openid={wecom_openid_value or ''}", error_code='WECOM_NOT_IN_AGENT_SCOPE')
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='当前企业微信账号未授权登录该应用:账号不在自建应用的可见范围内,或不是本企业成员。请管理员到「企业微信后台 → 应用管理 → 该应用 → 可见范围」中加入该成员所在的部门或个人。', http_status=401, details={'error_code': 'WECOM_NOT_IN_AGENT_SCOPE'})
|
||||
raise AppError(
|
||||
code='WECOM_NOT_IN_AGENT_SCOPE',
|
||||
message='当前企业微信账号未授权登录该应用:账号不在自建应用的可见范围内,或不是本企业成员。请管理员到「企业微信后台 → 应用管理 → 该应用 → 可见范围」中加入该成员所在的部门或个人。',
|
||||
http_status=401,
|
||||
)
|
||||
user_resp = requests.get('https://qyapi.weixin.qq.com/cgi-bin/user/get', params={'access_token': access_token, 'userid': wecom_userid_value}, timeout=8)
|
||||
wecom_user = user_resp.json()
|
||||
wecom_userid_for_audit = wecom_user.get('userid') or wecom_userid_for_audit
|
||||
@@ -1354,7 +1038,11 @@ def wecom_login():
|
||||
if _is_users_pk_sequence_error(e):
|
||||
_write_login_audit('wecom', 'failed', reason='db_sequence_misconfig', wecom_userid=wecom_userid_for_audit, error_code='DB_SEQUENCE_MISCONFIG')
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='数据库主键自增配置异常,当前环境缺少 users.id 的自动序列。请执行数据库迁移后重试。', http_status=500, details={'error_code': 'DB_SEQUENCE_MISCONFIG'})
|
||||
raise AppError(
|
||||
code='SYSTEM.DB_SEQUENCE_MISCONFIG',
|
||||
message='数据库主键自增配置异常,当前环境缺少 users.id 的自动序列。请执行数据库迁移后重试。',
|
||||
http_status=500,
|
||||
)
|
||||
_write_login_audit('wecom', 'failed', reason=f'exception:{str(e)[:160]}')
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'WeCom login failed: {str(e)}', http_status=500)
|
||||
@@ -1369,21 +1057,44 @@ def wecom_complete_bind():
|
||||
value = data.get('value')
|
||||
identity = _get_wecom_bind_session(binding_token)
|
||||
if not identity:
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='WeCom binding session expired. Please restart WeCom login.', http_status=400, details={'error_code': 'WECOM_BIND_SESSION_EXPIRED'})
|
||||
raise AppError(
|
||||
code='WECOM_BIND_SESSION_EXPIRED',
|
||||
message='WeCom binding session expired. Please restart WeCom login.',
|
||||
http_status=400,
|
||||
)
|
||||
allowed_fields = _get_wecom_first_login_input_fields()
|
||||
if field not in allowed_fields:
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='Selected bind field is not allowed', http_status=400, details={'error_code': 'WECOM_BIND_FIELD_NOT_ALLOWED', 'allowed_fields': allowed_fields})
|
||||
raise AppError(
|
||||
code='WECOM_BIND_FIELD_NOT_ALLOWED',
|
||||
message='Selected bind field is not allowed',
|
||||
http_status=400,
|
||||
details={'allowed_fields': allowed_fields},
|
||||
)
|
||||
matched_users, missing_field = _find_users_by_input_field(field, value)
|
||||
if missing_field:
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message=f'{field} is required', http_status=400, details={'error_code': 'WECOM_BIND_INPUT_VALUE_REQUIRED', 'field': field})
|
||||
raise AppError(
|
||||
code='WECOM_BIND_INPUT_VALUE_REQUIRED',
|
||||
message=f'{field} is required',
|
||||
http_status=400,
|
||||
details={'field': field},
|
||||
)
|
||||
if len(matched_users) == 0:
|
||||
_write_login_audit('wecom', 'failed', reason=f'input_bind_not_found:{field}', wecom_userid=identity.get('wecom_userid'), error_code='WECOM_BIND_INPUT_NOT_FOUND', match_rules=[field], match_operator='AND')
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='No local account matched the verification value.', http_status=404, details={'error_code': 'WECOM_BIND_INPUT_NOT_FOUND', 'field': field})
|
||||
raise AppError(
|
||||
code='WECOM_BIND_INPUT_NOT_FOUND',
|
||||
message='No local account matched the verification value.',
|
||||
http_status=404,
|
||||
details={'field': field},
|
||||
)
|
||||
if len(matched_users) > 1:
|
||||
_write_login_audit('wecom', 'failed', reason=f'input_bind_ambiguous:{field}', wecom_userid=identity.get('wecom_userid'), error_code='WECOM_BIND_INPUT_AMBIGUOUS', match_rules=[field], match_operator='AND')
|
||||
db.session.commit()
|
||||
raise ConflictError('Multiple local accounts matched the verification value.', details={'error_code': 'WECOM_BIND_INPUT_AMBIGUOUS', 'field': field, 'candidate_count': len(matched_users)})
|
||||
raise ConflictError(
|
||||
'Multiple local accounts matched the verification value.',
|
||||
code='WECOM_BIND_INPUT_AMBIGUOUS',
|
||||
details={'field': field, 'candidate_count': len(matched_users)},
|
||||
)
|
||||
user = matched_users[0]
|
||||
if user.status != 'active':
|
||||
_write_login_audit('wecom', 'failed', user=user, reason='account_disabled', wecom_userid=identity.get('wecom_userid'), error_code='WECOM_ACCOUNT_DISABLED', match_rules=[field], match_operator='AND')
|
||||
@@ -1631,9 +1342,10 @@ def home():
|
||||
|
||||
def _load_home_payload():
|
||||
if user.role == 'admin':
|
||||
agent_rows = db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url, Agent.extra_config).filter(Agent.is_active.is_(True)).all()
|
||||
agent_rows = Agent.query.filter(Agent.is_active.is_(True)).all()
|
||||
else:
|
||||
agent_rows = [{'id': agent.id, 'name': agent.name, 'description': agent.description, 'icon_url': agent.icon_url, 'extra_config': agent.extra_config} for agent in user.agents]
|
||||
agent_rows = [agent for agent in user.agents if agent.is_active]
|
||||
agent_rows = sort_agent_rows(agent_rows)
|
||||
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
|
||||
favorite_ids = [f.agent_id for f in favorites]
|
||||
qqs = db.session.query(QuickQuestion).filter(
|
||||
@@ -1649,8 +1361,15 @@ def home():
|
||||
for rel in embedded_rel:
|
||||
agent = db.session.get(Agent, rel.agent_id)
|
||||
if agent:
|
||||
embedded_agents.append({'id': agent.id, 'name': agent.name, 'iframe_url': agent.extra_config.get('iframe_url') if agent.extra_config else None})
|
||||
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [{'id': a.id if hasattr(a, 'id') else a['id'], 'name': a.name if hasattr(a, 'name') else a['name'], 'description': a.description if hasattr(a, 'description') else a['description'], 'icon_url': a.icon_url if hasattr(a, 'icon_url') else a['icon_url'], 'dify_app_type': ((a.extra_config or {}).get('dify_app_type') if hasattr(a, 'extra_config') else (a.get('extra_config') or {}).get('dify_app_type')) or 'chatflow'} for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
|
||||
registry = serialize_registry_fields(agent)
|
||||
embedded_agents.append({
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'iframe_url': registry.get('iframe_url'),
|
||||
'runtime_provider': registry.get('runtime_provider'),
|
||||
'conversation_mode': registry.get('conversation_mode'),
|
||||
})
|
||||
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
|
||||
try:
|
||||
return _run_db_with_retry(_load_home_payload, label='user.home')
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
@@ -1734,7 +1453,7 @@ def user_profile():
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
if request.method == 'GET':
|
||||
return jsonify({'id': user.id, 'username': user.username, 'real_name': user.real_name, 'email': user.email, 'phone_number': user.phone_number, 'employee_id': user.employee_id, 'department': user.department, 'role': user.role, 'language': user.language, 'theme_preference': user.theme_preference or 'system'})
|
||||
return jsonify({'id': user.id, 'username': user.username, 'real_name': user.real_name, 'email': user.email, 'phone_number': user.phone_number, 'employee_id': user.employee_id, 'department': user.department, 'role': user.role, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'})
|
||||
data = request.get_json() or {}
|
||||
|
||||
def _update_profile():
|
||||
@@ -1909,24 +1628,19 @@ def reset_password_by_wecom():
|
||||
code='WECOM.RESET_NOT_CONFIGURED',
|
||||
message='WeCom password reset is not configured',
|
||||
http_status=503,
|
||||
details={
|
||||
'error_code': 'WECOM_RESET_NOT_CONFIGURED',
|
||||
'missing': _get_wecom_config_missing_fields(),
|
||||
},
|
||||
details={'missing': _get_wecom_config_missing_fields()},
|
||||
)
|
||||
if not bool(current_app.config.get('WECOM_NOTIFY_ENABLED', True)):
|
||||
raise AppError(
|
||||
code='WECOM.NOTIFY_DISABLED',
|
||||
message='WeCom notification is disabled',
|
||||
http_status=503,
|
||||
details={'error_code': 'WECOM_NOTIFY_DISABLED'},
|
||||
)
|
||||
if not _get_password_reset_public_base_url():
|
||||
raise AppError(
|
||||
code='WECOM.RESET_URL_NOT_CONFIGURED',
|
||||
message='Password reset public base URL is not configured',
|
||||
http_status=503,
|
||||
details={'error_code': 'PASSWORD_RESET_URL_NOT_CONFIGURED'},
|
||||
)
|
||||
|
||||
data = request.get_json() or {}
|
||||
@@ -1951,7 +1665,6 @@ def reset_password_by_wecom():
|
||||
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,
|
||||
},
|
||||
@@ -2078,7 +1791,6 @@ def reset_password_confirm():
|
||||
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)
|
||||
@@ -2109,37 +1821,28 @@ def get_agent_details(id):
|
||||
has_permission = agent in user.agents
|
||||
if not has_permission:
|
||||
raise ForbiddenError('Access denied')
|
||||
extra_config = agent.extra_config or {}
|
||||
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
|
||||
from app.services.agent_registry.resolver import resolve_runtime_provider
|
||||
from app.services.agent_registry.serialization import serialize_agent_for_user_detail
|
||||
|
||||
dify_parameters = None
|
||||
agent_type = str(getattr(agent, 'type', '') or '').strip().lower()
|
||||
if agent_type == 'api' and getattr(agent, 'dify_api_key', None):
|
||||
if resolve_runtime_provider(agent) in {'dify', 'hybrid'} and getattr(agent, 'dify_api_key', None):
|
||||
from app.services.dify import DifyService
|
||||
|
||||
params = DifyService.get_app_parameters(agent)
|
||||
if isinstance(params, dict):
|
||||
dify_parameters = {
|
||||
'file_upload': params.get('file_upload') if isinstance(params.get('file_upload'), dict) else {},
|
||||
'system_parameters': params.get('system_parameters') if isinstance(params.get('system_parameters'), dict) else {},
|
||||
}
|
||||
try:
|
||||
params = DifyService.get_app_parameters(agent)
|
||||
if isinstance(params, dict):
|
||||
dify_parameters = {
|
||||
'file_upload': params.get('file_upload') if isinstance(params.get('file_upload'), dict) else {},
|
||||
'system_parameters': params.get('system_parameters') if isinstance(params.get('system_parameters'), dict) else {},
|
||||
}
|
||||
except Exception as exc:
|
||||
current_app.logger.warning('[user.agents] dify parameters fetch failed agent_id=%s err=%s', id, exc)
|
||||
|
||||
return jsonify({
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'description': agent.description,
|
||||
'type': agent.type,
|
||||
'icon_url': agent.icon_url,
|
||||
'extra_config': extra_config if isinstance(extra_config, dict) else {},
|
||||
'dify_app_type': dify_app_type,
|
||||
'welcome_message': extra_config.get('welcome_message') if isinstance(extra_config, dict) else None,
|
||||
'suggested_questions': extra_config.get('suggested_questions', []) if isinstance(extra_config, dict) else [],
|
||||
'dify_parameters': dify_parameters,
|
||||
})
|
||||
return jsonify(serialize_agent_for_user_detail(
|
||||
agent,
|
||||
dify_parameters=dify_parameters,
|
||||
))
|
||||
|
||||
@user_bp.route('/db', methods=['GET'])
|
||||
def get_db():
|
||||
@@ -2147,66 +1850,3 @@ def get_db():
|
||||
from app import db
|
||||
u = db.session.query(User).filter_by(username='26040006').first()
|
||||
return jsonify({'db': current_app.config.get('SQLALCHEMY_DATABASE_URI'), 'user': u.username if u else None})
|
||||
|
||||
@user_bp.route('/announcements', methods=['GET'])
|
||||
def get_announcements():
|
||||
"""
|
||||
Get active announcements (Public)
|
||||
"""
|
||||
|
||||
def _load_announcements():
|
||||
anns = db.session.query(Announcement.id, Announcement.title, Announcement.content, Announcement.created_at).filter(Announcement.is_active.is_(True)).order_by(Announcement.created_at.desc()).all()
|
||||
return jsonify([{'id': a.id, 'title': a.title, 'content': a.content, 'created_at': a.created_at.isoformat()} for a in anns])
|
||||
try:
|
||||
return _run_db_with_retry(_load_announcements, label='user.announcements')
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('user.announcements retry failed: %s', exc)
|
||||
raise ServiceUnavailableError('Database connection failed')
|
||||
|
||||
@user_bp.route('/announcements', methods=['POST'])
|
||||
def create_announcement():
|
||||
"""
|
||||
Create announcement (Admin only)
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user or user.role != 'admin':
|
||||
raise ForbiddenError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
if not data.get('title') or not data.get('content'):
|
||||
raise ValidationError('Missing fields')
|
||||
ann = Announcement(title=data['title'], content=data['content'], is_active=True)
|
||||
db.session.add(ann)
|
||||
db.session.commit()
|
||||
return (jsonify({'message': 'Created', 'id': ann.id}), 201)
|
||||
|
||||
@user_bp.route('/announcements/<int:id>', methods=['PUT'])
|
||||
def update_announcement(id):
|
||||
"""
|
||||
更新公告(仅管理员)。
|
||||
|
||||
核心逻辑:校验 title/content 非空后更新 Announcement 记录。
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user or user.role != 'admin':
|
||||
raise ForbiddenError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
if not data.get('title') or not data.get('content'):
|
||||
raise ValidationError('Missing fields')
|
||||
ann = db.session.get(Announcement, id)
|
||||
if not ann:
|
||||
raise NotFoundError('Not found')
|
||||
ann.title = data['title']
|
||||
ann.content = data['content']
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Updated'})
|
||||
|
||||
@user_bp.route('/announcements/<int:id>', methods=['DELETE'])
|
||||
def delete_announcement(id):
|
||||
user = _get_current_user()
|
||||
if not user or user.role != 'admin':
|
||||
raise ForbiddenError('Unauthorized')
|
||||
ann = db.session.get(Announcement, id)
|
||||
if ann:
|
||||
db.session.delete(ann)
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Deleted'})
|
||||
@@ -1,15 +1,18 @@
|
||||
"""
|
||||
backend/app/api/workspace/__init__.py
|
||||
|
||||
用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check)。
|
||||
逻辑:Wave 1 前 re-export 旧 workspace_* 模块。
|
||||
用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check、announcements)。
|
||||
依赖:workspace 各子模块 blueprint。
|
||||
逻辑:import 子模块注册路由;register_blueprints 从本包导入各 bp。
|
||||
"""
|
||||
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
|
||||
from app.api.workspace.announcements import workspace_announcements_bp
|
||||
from app.api.workspace.file_check import workspace_file_check_bp
|
||||
from app.api.workspace.schedule import workspace_schedule_bp
|
||||
from app.api.workspace.shipping_notice import workspace_shipping_notice_bp
|
||||
|
||||
__all__ = [
|
||||
'workspace_announcements_bp',
|
||||
'workspace_file_check_bp',
|
||||
'workspace_schedule_bp',
|
||||
'workspace_shipping_notice_bp',
|
||||
'workspace_file_check_bp',
|
||||
]
|
||||
@@ -0,0 +1,27 @@
|
||||
"""
|
||||
backend/app/api/workspace/announcements.py
|
||||
|
||||
用途:工作台/登录页只读公告列表 API。
|
||||
依赖:services/admin/announcement_service(读活跃公告)。
|
||||
逻辑:GET /announcements 无需登录;管理 CRUD 见 api/admin/announcements.py。
|
||||
"""
|
||||
from flask import Blueprint, jsonify
|
||||
|
||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.admin import announcement_service
|
||||
|
||||
workspace_announcements_bp = Blueprint('workspace_announcements', __name__)
|
||||
|
||||
|
||||
@workspace_announcements_bp.route('/announcements', methods=['GET'])
|
||||
def list_active_announcements():
|
||||
"""返回已发布的公司公告(公开,供登录页与工作台展示)。"""
|
||||
try:
|
||||
return jsonify(announcement_service.list_active_announcements())
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
from flask import current_app
|
||||
|
||||
current_app.logger.warning('workspace.announcements query failed: %s', exc)
|
||||
raise ServiceUnavailableError('Database connection failed')
|
||||
@@ -1,5 +1,126 @@
|
||||
"""
|
||||
backend/app/api/workspace/file_check.py
|
||||
|
||||
用途:工作台文件检核路由(Wave 1 自 workspace_file_check.py 迁入)。
|
||||
用途:工作台文件检核进度轮询 API(对话页 tool_run_progress)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、file_check_tools、schedule.query_service。
|
||||
逻辑:鉴权后查询 ScheduleRun 进度;register_blueprints 经 workspace 包注册。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.file_check_tools.chat_log_run_resolver import find_run_for_chat_log_with_source
|
||||
from app.services.schedule.query_service import get_run, serialize_run
|
||||
|
||||
workspace_file_check_bp = Blueprint("workspace_file_check", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""
|
||||
校验当前登录用户。
|
||||
Raises:
|
||||
UnauthorizedError: 未认证。
|
||||
"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
def serialize_file_judgement(payload: dict) -> dict:
|
||||
"""序列化检核判定统计(读取 response_summary_json.file_judgement)。"""
|
||||
response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {}
|
||||
judgement = response_summary.get('file_judgement')
|
||||
if not isinstance(judgement, dict):
|
||||
judgement = {}
|
||||
return {
|
||||
'qualified_count': int(judgement.get('qualified_count') or 0),
|
||||
'unqualified_count': int(judgement.get('unqualified_count') or 0),
|
||||
'manual_count': int(judgement.get('manual_count') or 0),
|
||||
'dify_error_count': int(judgement.get('dify_error_count') or 0),
|
||||
'invalid_result_count': int(judgement.get('invalid_result_count') or 0),
|
||||
'business_manual_count': int(judgement.get('business_manual_count') or 0),
|
||||
'system_error_count': int(judgement.get('system_error_count') or 0),
|
||||
'dify_timeout_count': int(judgement.get('dify_timeout_count') or 0),
|
||||
'invalid_output_count': int(judgement.get('invalid_output_count') or 0),
|
||||
'attachment_error_count': int(judgement.get('attachment_error_count') or 0),
|
||||
}
|
||||
|
||||
def serialize_current_step(payload: dict) -> dict | None:
|
||||
response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {}
|
||||
current_step = response_summary.get('current_step') if isinstance(response_summary.get('current_step'), dict) else None
|
||||
if not current_step:
|
||||
return None
|
||||
return {'step': str(current_step.get('step') or ''), 'label': str(current_step.get('label') or current_step.get('step') or ''), 'row_id': current_step.get('row_id'), 'started_at': current_step.get('started_at'), 'processed_count': int(current_step.get('processed_count') or 0), 'success_count': int(current_step.get('success_count') or 0), 'failed_count': int(current_step.get('failed_count') or 0), 'skipped_count': int(current_step.get('skipped_count') or 0)}
|
||||
|
||||
def _serialize_progress_run(run: ScheduleRun) -> dict:
|
||||
payload = serialize_run(run)
|
||||
total = int(payload.get('total_count') or 0)
|
||||
success = int(payload.get('success_count') or 0)
|
||||
failed = int(payload.get('failed_count') or 0)
|
||||
skipped = int(payload.get('skipped_count') or 0)
|
||||
processed = success + failed + skipped
|
||||
percent = int(round(processed / total * 100)) if total > 0 else 0
|
||||
percent = max(0, min(percent, 100))
|
||||
return {'run_id': payload['id'], 'run_no': payload['run_no'], 'task_id': payload['schedule_task_id'], 'title': payload.get('schedule_name') or '', 'status': payload['status'], 'total_count': total, 'processed_count': processed, 'success_count': success, 'failed_count': failed, 'skipped_count': skipped, 'judgement': serialize_file_judgement(payload), 'current_step': serialize_current_step(payload), 'progress_percent': percent, 'started_at': payload.get('started_at'), 'finished_at': payload.get('finished_at'), 'duration_ms': payload.get('duration_ms'), 'error_message': payload.get('error_message'), 'excel': {'file_name': payload.get('excel_file_name'), 'file_size': payload.get('excel_file_size'), 'download_url': f'/api/workspace/file-check/runs/{run.id}/excel' if payload.get('excel_file_name') else None}, 'knowledge_base': {'sync_status': payload.get('kb_sync_status'), 'group_id': payload.get('kb_group_id'), 'document_id': payload.get('kb_document_id'), 'document_version_id': payload.get('kb_document_version_id'), 'sync_job_id': payload.get('kb_sync_job_id'), 'error_message': payload.get('kb_sync_error')}}
|
||||
|
||||
@workspace_file_check_bp.route('/file-check/runs/for-log', methods=['GET'])
|
||||
def workspace_file_check_run_for_log():
|
||||
"""按 chat_log_id + schedule_task_id 返回该轮问答绑定的检核批次。"""
|
||||
_require_user()
|
||||
task_id = request.args.get('task_id', type=int)
|
||||
chat_log_id = request.args.get('chat_log_id', type=int)
|
||||
if not task_id or task_id <= 0:
|
||||
raise ValidationError("task_id_required")
|
||||
if not chat_log_id or chat_log_id <= 0:
|
||||
raise ValidationError("chat_log_id_required")
|
||||
match = find_run_for_chat_log_with_source(task_id=task_id, chat_log_id=chat_log_id)
|
||||
return jsonify({
|
||||
'ok': True,
|
||||
'run': _serialize_progress_run(match.run) if match.run else None,
|
||||
'match_source': match.match_source,
|
||||
})
|
||||
|
||||
@workspace_file_check_bp.route('/file-check/runs/for-session', methods=['GET'])
|
||||
def workspace_file_check_run_for_session():
|
||||
"""已废弃:请改用 for-log?chat_log_id=。保留接口避免旧客户端 404。"""
|
||||
_require_user()
|
||||
return jsonify({'ok': True, 'run': None, 'match_source': None, 'session_updated_at': None})
|
||||
|
||||
@workspace_file_check_bp.route('/file-check/runs/active', methods=['GET'])
|
||||
def workspace_file_check_active_run():
|
||||
"""查询当前进行中的检核批次;优先按 schedule_task_id(query: task_id)过滤。"""
|
||||
_require_user()
|
||||
task_id = request.args.get('task_id', type=int)
|
||||
conversation_id = str(request.args.get('conversation_id') or '').strip()
|
||||
query = ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id).filter(ScheduleRun.status == 'running')
|
||||
if task_id is not None:
|
||||
query = query.filter(ScheduleRun.schedule_task_id == task_id)
|
||||
rows = query.order_by(ScheduleRun.id.desc()).all()
|
||||
if task_id is not None:
|
||||
run = rows[0] if rows else None
|
||||
else:
|
||||
run = next((row for row in rows if not conversation_id or str((row.api_request_json or {}).get('conversation_id') or '').strip() == conversation_id), None)
|
||||
return jsonify({'ok': True, 'run': _serialize_progress_run(run) if run else None})
|
||||
|
||||
@workspace_file_check_bp.route('/file-check/runs/<int:run_id>', methods=['GET'])
|
||||
def workspace_file_check_run_detail(run_id: int):
|
||||
_require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('run_not_found')
|
||||
return jsonify({'ok': True, 'run': _serialize_progress_run(run)})
|
||||
|
||||
@workspace_file_check_bp.route('/file-check/runs/<int:run_id>/excel', methods=['GET'])
|
||||
def workspace_file_check_run_excel(run_id: int):
|
||||
_require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('run_not_found')
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError('excel_not_found')
|
||||
return send_file(BytesIO(run.excel_file_data), as_attachment=True, download_name=run.excel_file_name or f'{run.run_no}.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
@@ -1,5 +1,80 @@
|
||||
"""
|
||||
backend/app/api/workspace/schedule.py
|
||||
|
||||
用途:工作台排程路由(Wave 1 自 workspace_schedule.py 迁入)。
|
||||
用途:工作台排程运行记录查询 API。
|
||||
依赖:app.core.auth.jwt、app.core.errors、schedule.query_service。
|
||||
逻辑:鉴权后只读查询 ScheduleRun;register_blueprints 经 workspace 包注册。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError
|
||||
from app.services.schedule.query_service import can_view_run, get_run, list_runs, serialize_run
|
||||
|
||||
workspace_schedule_bp = Blueprint("workspace_schedule", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""校验当前用户;未登录时抛出 UnauthorizedError。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
@workspace_schedule_bp.route("/schedule-runs", methods=["GET"])
|
||||
def workspace_schedule_runs():
|
||||
user = _require_user()
|
||||
status = str(request.args.get("status") or "").strip() or None
|
||||
schedule_name = str(request.args.get("schedule_name") or "").strip() or None
|
||||
started_after_str = request.args.get("started_after")
|
||||
started_before_str = request.args.get("started_before")
|
||||
started_after = datetime.fromisoformat(started_after_str.replace("Z", "+00:00")) if started_after_str else None
|
||||
started_before = datetime.fromisoformat(started_before_str.replace("Z", "+00:00")) if started_before_str else None
|
||||
limit = int(request.args.get("limit") or 100)
|
||||
return jsonify(
|
||||
list_runs(
|
||||
notify_user_id=user.id,
|
||||
schedule_name=schedule_name,
|
||||
status=status,
|
||||
started_after=started_after,
|
||||
started_before=started_before,
|
||||
limit=limit,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@workspace_schedule_bp.route("/schedule-runs/<int:run_id>", methods=["GET"])
|
||||
def workspace_schedule_run_detail(run_id: int):
|
||||
user = _require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("Not found")
|
||||
if not can_view_run(run, user.id):
|
||||
raise ForbiddenError("Forbidden")
|
||||
return jsonify(serialize_run(run))
|
||||
|
||||
|
||||
@workspace_schedule_bp.route("/schedule-runs/<int:run_id>/excel", methods=["GET"])
|
||||
def workspace_schedule_run_excel(run_id: int):
|
||||
from io import BytesIO
|
||||
|
||||
user = _require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("Not found")
|
||||
if not can_view_run(run, user.id):
|
||||
raise ForbiddenError("Forbidden")
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError("Excel not found")
|
||||
buf = BytesIO(run.excel_file_data)
|
||||
return send_file(
|
||||
buf,
|
||||
as_attachment=True,
|
||||
download_name=run.excel_file_name or "result.xlsx",
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
@@ -1,5 +1,741 @@
|
||||
"""
|
||||
backend/app/api/workspace/shipping_notice.py
|
||||
|
||||
用途:工作台出货通知路由(Wave 1 自 workspace_shipping_notice.py 迁入)。
|
||||
用途:HXOPS 工作台与聊天前端使用的发货通知用户态 API。
|
||||
依赖:app.core.auth.jwt、app.core.errors、shipping_notice.query_service / tools / notice_upload / ui_state。
|
||||
逻辑:薄路由层鉴权与参数校验;register_blueprints 经 workspace 包注册。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from flask import Blueprint, g, jsonify, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
|
||||
from app.services.shipping_notice.constants import (
|
||||
AUTO_CHAIN_FALLBACK,
|
||||
CP_EXPORT_GENERATED,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
MAP_JSON,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import switch_batch_focus
|
||||
from app.services.shipping_notice.query_service import (
|
||||
EXPORT_MIME_TYPE,
|
||||
get_batch_for_user,
|
||||
get_conversation_batch_workspace,
|
||||
get_focus_task_for_batch,
|
||||
get_task_for_user,
|
||||
list_batches_for_user,
|
||||
list_tasks_for_batch,
|
||||
list_tasks_for_user,
|
||||
resolve_task_export_download,
|
||||
serialize_batch_summary,
|
||||
serialize_task_detail,
|
||||
serialize_task_summary,
|
||||
task_export_error_message,
|
||||
)
|
||||
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
|
||||
|
||||
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""
|
||||
校验当前登录用户;未认证时抛出 UnauthorizedError,由全局 handler 输出标准错误 JSON。
|
||||
Returns:
|
||||
User 模型实例。
|
||||
Raises:
|
||||
UnauthorizedError: 无有效 JWT 或 legacy header。
|
||||
"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def _ok(payload: dict):
|
||||
"""返回带 request_id 的成功 envelope,供工作台读接口复用。"""
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
|
||||
def workspace_shipping_tasks():
|
||||
"""列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
|
||||
user = _require_user()
|
||||
batch_no = str(request.args.get('batch_no') or '').strip() or None
|
||||
process_status = str(request.args.get('process_status') or '').strip() or None
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
return jsonify(list_tasks_for_user(user.id, batch_no=batch_no, process_status=process_status, limit=limit))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches', methods=['GET'])
|
||||
def workspace_shipping_batches():
|
||||
"""列出当前用户的发货批次摘要。"""
|
||||
user = _require_user()
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
return jsonify(list_batches_for_user(user.id, limit=limit))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-conversations/<conversation_id>/batch-workspace', methods=['GET'])
|
||||
def workspace_shipping_conversation_batch_workspace(conversation_id: str):
|
||||
"""返回一个 Agent 会话下的多批次执行工作台快照。"""
|
||||
user = _require_user()
|
||||
return _ok(get_conversation_batch_workspace(conversation_id, user.id))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-notices', methods=['POST'])
|
||||
def workspace_create_shipping_batch_from_notices():
|
||||
"""接收多份发货通知附件,创建批次并交给后台编排器逐票推进。"""
|
||||
user = _require_user()
|
||||
uploads = request.files.getlist('files')
|
||||
if not uploads:
|
||||
single = request.files.get('file')
|
||||
if single:
|
||||
uploads = [single]
|
||||
if not uploads:
|
||||
raise ValidationError('files is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.batch_from_notices import (
|
||||
create_shipping_batch_from_notice_items,
|
||||
intake_notice_uploads_for_batch,
|
||||
)
|
||||
from app.services.shipping_notice.batch_create_idempotency import (
|
||||
normalize_create_idempotency_key,
|
||||
warn_missing_create_idempotency_key,
|
||||
)
|
||||
from app.services.shipping_notice.notice_upload import cleanup_temp_notice_uploads
|
||||
conversation_id = str(request.form.get('conversation_id') or '').strip()
|
||||
idempotency_key = normalize_create_idempotency_key(
|
||||
request.headers.get('Idempotency-Key') or request.form.get('idempotency_key')
|
||||
)
|
||||
if not idempotency_key:
|
||||
warn_missing_create_idempotency_key(source='workspace_create_shipping_batch_from_notices')
|
||||
temp_request_id = str(getattr(g, 'request_id', None) or uuid.uuid4().hex)
|
||||
try:
|
||||
notice_items, file_summary = intake_notice_uploads_for_batch(temp_request_id, uploads)
|
||||
finally:
|
||||
cleanup_temp_notice_uploads(temp_request_id)
|
||||
|
||||
created = create_shipping_batch_from_notice_items(
|
||||
user_id=user.id,
|
||||
conversation_id=conversation_id or None,
|
||||
notice_items=notice_items,
|
||||
file_summary=file_summary,
|
||||
create_idempotency_key=idempotency_key,
|
||||
)
|
||||
return _ok(created)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>', methods=['GET'])
|
||||
def workspace_shipping_batch_detail(batch_no: str):
|
||||
"""
|
||||
返回批次详情与聚合 UI State。
|
||||
|
||||
核心逻辑:工作台详情页与独立 `/ui-state` 端点共享同一份批次状态构建结果,
|
||||
避免批次摘要、焦点任务和任务卡片在不同接口里各自推导造成漂移。
|
||||
"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok(build_batch_ui_state(batch))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/ui-state', methods=['GET'])
|
||||
def workspace_shipping_batch_ui_state(batch_no: str):
|
||||
"""
|
||||
返回批次级 UI State。
|
||||
|
||||
核心逻辑:供右侧工作台、步骤条与批次任务卡统一读取同源状态,
|
||||
保持与批次详情接口返回的 `focus_task_ui_state/tasks[].ui_state` 完全一致。
|
||||
"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok(build_batch_ui_state(batch))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/tasks', methods=['GET'])
|
||||
def workspace_shipping_batch_tasks(batch_no: str):
|
||||
"""返回指定批次下的任务列表。"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(list_tasks_for_batch(batch_no, user.id))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['GET'])
|
||||
def workspace_shipping_batch_focus_task(batch_no: str):
|
||||
"""返回指定批次当前焦点任务的摘要。"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
focus_task = get_focus_task_for_batch(batch_no, user.id)
|
||||
if not focus_task:
|
||||
raise NotFoundError('Focus task not found')
|
||||
return jsonify(serialize_task_summary(focus_task))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['POST'])
|
||||
def workspace_switch_shipping_batch_focus_task(batch_no: str):
|
||||
"""切换批次当前焦点任务,供工作台在同批次任务间跳转。"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
task_no = str(data.get('task_no') or data.get('target_task_no') or '').strip()
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if not task_no:
|
||||
raise ValidationError('task_no is required')
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task or task.batch_id != batch.id:
|
||||
raise NotFoundError('Task not found in batch')
|
||||
switch_batch_focus(
|
||||
batch,
|
||||
task,
|
||||
source='workspace_api',
|
||||
comment=comment or None,
|
||||
extra={'actor_user_id': user.id},
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify({'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)})
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['POST'])
|
||||
def workspace_create_shipping_task():
|
||||
"""创建单个发货任务,适用于手工录入或聊天入口先建单。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = {'user_id': user.id}
|
||||
source_type = str(data.get('source_type') or '').strip()
|
||||
if source_type:
|
||||
payload['source_type'] = source_type
|
||||
conversation_id = str(data.get('conversation_id') or '').strip()
|
||||
if conversation_id:
|
||||
payload['conversation_id'] = conversation_id
|
||||
raw_content = str(data.get('raw_content') or '').strip()
|
||||
if raw_content:
|
||||
payload['raw_content'] = raw_content
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.create_task(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
|
||||
def workspace_create_shipping_task_from_notice():
|
||||
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。"""
|
||||
user = _require_user()
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
raise ValidationError('file is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.notice_upload import guess_source_type, intake_notice_attachment, notice_source_file_type
|
||||
filename = upload.filename or 'notice'
|
||||
raw = upload.read() or b''
|
||||
source_file_type = notice_source_file_type(upload)
|
||||
source_type = guess_source_type(filename)
|
||||
conversation_id = str(request.form.get('conversation_id') or '').strip()
|
||||
payload = {'user_id': user.id, 'source_type': source_type}
|
||||
if conversation_id:
|
||||
payload['conversation_id'] = conversation_id
|
||||
created = shipping_tools.create_task(payload)
|
||||
task_id = str(created.get('task_id') or '').strip()
|
||||
if not task_id:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='failed to create task', http_status=500)
|
||||
intake = intake_notice_attachment(
|
||||
filename=filename,
|
||||
raw=raw,
|
||||
source_file_type=source_file_type,
|
||||
storage='task',
|
||||
task_no=task_id,
|
||||
)
|
||||
if not intake.accepted:
|
||||
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint
|
||||
return jsonify({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED)})
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
if task:
|
||||
task.raw_content = intake.text
|
||||
task.source_file_name = intake.filename or task.source_file_name
|
||||
task.source_file_type = intake.source_file_type or task.source_file_type
|
||||
db.session.commit()
|
||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
|
||||
orchestrator_started = start_task_orchestrator(task_id)
|
||||
return jsonify({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/replace-notice', methods=['POST'])
|
||||
def workspace_replace_shipping_task_notice(task_no: str):
|
||||
"""重新上传发货通知并覆盖当前任务,不新建批次/任务。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
raise ValidationError('file is required')
|
||||
from app.services.shipping_notice import task_workflow
|
||||
from app.services.shipping_notice.notice_upload import intake_notice_attachment, notice_source_file_type
|
||||
intake = intake_notice_attachment(
|
||||
filename=upload.filename or 'notice',
|
||||
raw=upload.read() or b'',
|
||||
source_file_type=notice_source_file_type(upload),
|
||||
storage='task',
|
||||
task_no=task.task_no,
|
||||
)
|
||||
task.source_type = intake.source_type or task.source_type
|
||||
result = task_workflow.replace_task_notice(
|
||||
task,
|
||||
raw_text=intake.text,
|
||||
source_file_name=intake.filename,
|
||||
source_file_type=intake.source_file_type,
|
||||
warnings=list(intake.warnings),
|
||||
)
|
||||
data = result.setdefault('data', {})
|
||||
if isinstance(data, dict):
|
||||
data['notice_upload'] = intake.to_notice_upload_meta()
|
||||
return _ok(result)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>', methods=['GET'])
|
||||
def workspace_shipping_task_detail(task_no: str):
|
||||
"""
|
||||
返回指定任务的详情快照与内嵌 UI State。
|
||||
|
||||
核心逻辑:详情接口直接内嵌 `ui_state`,让页面首屏读取任务详情时即可拿到
|
||||
checkpoint / action_buttons / steps,减少前端二次推导与竞态刷新。
|
||||
"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok({
|
||||
**serialize_task_detail(task),
|
||||
'ui_state': build_task_ui_state(task),
|
||||
})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/ui-state', methods=['GET'])
|
||||
def workspace_shipping_task_ui_state(task_no: str):
|
||||
"""
|
||||
返回单票任务 UI State。
|
||||
|
||||
核心逻辑:Chat 顶部步骤条、动作按钮和工作台详情统一复用这里的状态机投影,
|
||||
避免不同前端入口重复拼装按钮集合。
|
||||
"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok(build_task_ui_state(task))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET'])
|
||||
def workspace_shipping_task_chat_actions(task_no: str):
|
||||
"""返回聊天气泡侧所需的动作按钮与检查点信息。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(build_chat_actions_payload(task))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry', methods=['POST'])
|
||||
def workspace_retry_shipping_task(task_no: str):
|
||||
"""重试当前任务,适用于超时、解析失败或自动推进中断后的恢复。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = {'task_id': task.task_no}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.retry_task(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/upload-inventory', methods=['POST'])
|
||||
def workspace_upload_shipping_inventory(task_no: str):
|
||||
"""用户态上传库存 Excel,并在服务端完成解析。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
upload = request.files.get('file')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.upload_inventory_file(task.task_no, upload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/confirm-inventory-source', methods=['POST'])
|
||||
def workspace_confirm_shipping_inventory_source(task_no: str):
|
||||
"""确认当前任务的库存 RPA 来源,并继续触发库存导出。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
source_code = str(data.get('source_code') or '').strip()
|
||||
if not source_code:
|
||||
raise ValidationError('source_code is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.confirm_inventory_source({
|
||||
'task_id': task.task_no,
|
||||
'source_code': source_code,
|
||||
'_trusted_user_id': user.id,
|
||||
}))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/apply-inventory-mapping', methods=['POST'])
|
||||
def workspace_apply_inventory_mapping(task_no: str):
|
||||
"""提交库存字段映射,并允许在工作台侧自动回退到下一步。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
data = request.get_json(silent=True) or {}
|
||||
map_json = data.get(MAP_JSON)
|
||||
if not isinstance(map_json, dict) or not map_json:
|
||||
raise ValidationError(f'{MAP_JSON} is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {'task_id': task.task_no, MAP_JSON: map_json, AUTO_CHAIN_FALLBACK: True}
|
||||
return jsonify(shipping_tools.apply_inventory_mapping(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/submit-decision', methods=['POST'])
|
||||
def workspace_submit_shipping_decision(task_no: str):
|
||||
"""以用户态提交人工决策,绕过 Dify Tool 路由直接驱动状态机。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
decision = str(data.get('decision') or '').strip()
|
||||
if not decision:
|
||||
raise ValidationError('decision is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {'task_id': task.task_no, 'decision': decision, AUTO_CHAIN_FALLBACK: True, 'event_source': 'workspace_api'}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.submit_decision(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-fields', methods=['POST'])
|
||||
def workspace_update_shipping_notice_fields(task_no: str):
|
||||
"""更新发货通知单头字段。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
fields = data.get('fields')
|
||||
if not isinstance(fields, dict) or not fields:
|
||||
raise ValidationError('fields is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {'task_id': task.task_no, 'fields': fields}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.update_notice_fields(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-line', methods=['POST'])
|
||||
def workspace_update_shipping_notice_line(task_no: str):
|
||||
"""更新发货通知中的指定订单行。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
line_index = int(data.get('line_index'))
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('line_index is required')
|
||||
patch = data.get('patch')
|
||||
if not isinstance(patch, dict) or not patch:
|
||||
raise ValidationError('patch is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {'task_id': task.task_no, 'line_index': line_index, 'patch': patch}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.update_notice_line(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/add-notice-line', methods=['POST'])
|
||||
def workspace_add_shipping_notice_line(task_no: str):
|
||||
"""为发货通知新增订单行。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
line = data.get('line')
|
||||
if not isinstance(line, dict) or not line:
|
||||
raise ValidationError('line is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {'task_id': task.task_no, 'line': line}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.add_notice_line(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/remove-notice-line', methods=['POST'])
|
||||
def workspace_remove_shipping_notice_line(task_no: str):
|
||||
"""删除发货通知中的指定订单行。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
line_index = int(data.get('line_index'))
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('line_index is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {'task_id': task.task_no, 'line_index': line_index}
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.remove_notice_line(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/auto-progress', methods=['POST'])
|
||||
def workspace_auto_progress_shipping_task(task_no: str):
|
||||
"""用户态触发 auto_progress,作为聊天前端的兜底自动推进入口。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload: dict = {'task_id': task.task_no}
|
||||
for key in ('lang', 'locale', 'language'):
|
||||
if data.get(key):
|
||||
payload[key] = data[key]
|
||||
break
|
||||
result = shipping_tools.auto_progress(payload)
|
||||
if isinstance(result, dict) and result.get('status') == 'ok':
|
||||
gen_data = result.get('data')
|
||||
if isinstance(gen_data, dict) and gen_data.get('export_file_path'):
|
||||
gen_data = {**gen_data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}
|
||||
result = {**result, 'data': gen_data}
|
||||
return jsonify(result)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/match-inventory', methods=['POST'])
|
||||
def workspace_match_shipping_inventory(task_no: str):
|
||||
"""执行库存匹配,并在生成 Excel 后补充前端可直接下载的链接。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint, human_options_for_checkpoint
|
||||
matched = shipping_tools.match_inventory({'task_id': task.task_no, AUTO_CHAIN_FALLBACK: True})
|
||||
if not isinstance(matched, dict):
|
||||
return jsonify(matched)
|
||||
data = matched.get('data')
|
||||
if isinstance(data, dict) and data.get('export_file_path'):
|
||||
matched = {**matched, 'data': {**data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}}
|
||||
checkpoint = matched.get('checkpoint') or CP_EXPORT_GENERATED
|
||||
if matched.get('status') == 'ok' and data and data.get('export_file_path'):
|
||||
matched['checkpoint'] = checkpoint
|
||||
if 'human_options' not in matched:
|
||||
options = human_options_for_checkpoint(checkpoint)
|
||||
if options is not None:
|
||||
matched['human_options'] = options
|
||||
if 'action_buttons' not in matched:
|
||||
buttons = action_buttons_for_checkpoint(checkpoint)
|
||||
if buttons:
|
||||
matched['action_buttons'] = buttons
|
||||
return jsonify(matched)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/mark-manual-uploaded', methods=['POST'])
|
||||
def workspace_mark_manual_uploaded(task_no: str):
|
||||
"""标记货代系统已人工上传完成,无需再等待 RPA 回执。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'}))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry-upload', methods=['POST'])
|
||||
def workspace_retry_shipping_upload(task_no: str):
|
||||
"""用户态重试上传货代系统,直接触发既有 RPA 上传链路。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'retry_upload'}))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/generate-excel', methods=['POST'])
|
||||
def workspace_generate_shipping_excel(task_no: str):
|
||||
"""为指定任务生成出货 Excel,并补充工作台下载链接。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
result = shipping_tools.generate_excel({'task_id': task.task_no})
|
||||
if isinstance(result, dict) and result.get('status') == 'ok':
|
||||
data = result.get('data')
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
result['data'] = data
|
||||
data['download_url'] = f'/api/workspace/shipping-tasks/{task.task_no}/export'
|
||||
return jsonify(result)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
|
||||
def workspace_shipping_task_export(task_no: str):
|
||||
"""下载当前用户可访问任务的出货 Excel。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
err_msg = task_export_error_message(task)
|
||||
if err_msg:
|
||||
raise NotFoundError(err_msg)
|
||||
resolved = resolve_task_export_download(task)
|
||||
assert resolved is not None
|
||||
path, download_name = resolved
|
||||
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['GET'])
|
||||
def workspace_list_shipping_notice_intakes():
|
||||
"""列出当前会话下未消费的活跃接入记录。"""
|
||||
user = _require_user()
|
||||
conversation_id = str(request.args.get('conversation_id') or '').strip() or None
|
||||
status = str(request.args.get('status') or '').strip().lower()
|
||||
from app.services.shipping_notice.intake_service import list_active_intakes_for_conversation
|
||||
|
||||
if status and status != 'active':
|
||||
return _ok({'items': []})
|
||||
items = list_active_intakes_for_conversation(user_id=user.id, conversation_id=conversation_id)
|
||||
return _ok({'items': items})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['POST'])
|
||||
def workspace_create_shipping_notice_intake():
|
||||
"""基于 FileAsset 创建发货通知接入记录并投递预解析任务。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
asset_no = str(body.get('asset_no') or '').strip()
|
||||
if not asset_no:
|
||||
raise ValidationError('asset_no is required')
|
||||
conversation_id = str(body.get('conversation_id') or '').strip() or None
|
||||
from app.services.shipping_notice.intake_service import create_shipping_notice_intake
|
||||
|
||||
data = create_shipping_notice_intake(
|
||||
user_id=user.id,
|
||||
asset_no=asset_no,
|
||||
conversation_id=conversation_id,
|
||||
)
|
||||
return ok(data, request_id=getattr(g, 'request_id', None), status=202)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/<intake_no>', methods=['GET'])
|
||||
def workspace_get_shipping_notice_intake(intake_no: str):
|
||||
"""查询单个接入记录。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.intake_service import get_intake_detail
|
||||
|
||||
return _ok(get_intake_detail(user_id=user.id, intake_no=intake_no))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/status', methods=['POST'])
|
||||
def workspace_shipping_notice_intake_statuses():
|
||||
"""批量查询接入状态。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
intake_nos = body.get('intake_nos')
|
||||
if not isinstance(intake_nos, list):
|
||||
raise ValidationError('intake_nos is required')
|
||||
from app.services.shipping_notice.intake_service import get_intake_statuses
|
||||
|
||||
return _ok({'items': get_intake_statuses(user_id=user.id, intake_nos=intake_nos)})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/<intake_no>/retry', methods=['POST'])
|
||||
def workspace_retry_shipping_notice_intake(intake_no: str):
|
||||
"""重试失败的预解析。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.intake_service import retry_intake_parse
|
||||
|
||||
return _ok(retry_intake_parse(user_id=user.id, intake_no=intake_no))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/<intake_no>', methods=['DELETE'])
|
||||
def workspace_cancel_shipping_notice_intake(intake_no: str):
|
||||
"""取消未消费接入记录。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.intake_service import cancel_intake
|
||||
|
||||
cancel_intake(user_id=user.id, intake_no=intake_no)
|
||||
return _ok({'cancelled': True})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/intakes/<intake_no>/duplicate-resolution',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_resolve_shipping_notice_duplicate(intake_no: str):
|
||||
"""保存发货通知重复检测决策。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
action = str(body.get('action') or '').strip()
|
||||
target_task_no = str(body.get('target_task_no') or '').strip() or None
|
||||
reason = str(body.get('reason') or '').strip() or None
|
||||
from app.services.shipping_notice.intake_service import resolve_intake_duplicate
|
||||
|
||||
return _ok(
|
||||
resolve_intake_duplicate(
|
||||
user_id=user.id,
|
||||
intake_no=intake_no,
|
||||
action=action,
|
||||
target_task_no=target_task_no,
|
||||
reason=reason,
|
||||
actor=user,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/intakes/<intake_no>/duplicate-refresh',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_refresh_shipping_notice_duplicate(intake_no: str):
|
||||
"""重新执行重复检测。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.intake_service import refresh_intake_duplicate_detection
|
||||
|
||||
return _ok(refresh_intake_duplicate_detection(user_id=user.id, intake_no=intake_no))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-intakes', methods=['POST'])
|
||||
def workspace_create_shipping_batch_from_intakes():
|
||||
"""从已解析接入记录确认建批。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
intake_nos = body.get('intake_nos')
|
||||
if not isinstance(intake_nos, list) or not intake_nos:
|
||||
raise ValidationError('intake_nos is required')
|
||||
conversation_id = str(body.get('conversation_id') or '').strip() or None
|
||||
from app.services.shipping_notice.batch_create_idempotency import (
|
||||
normalize_create_idempotency_key,
|
||||
warn_missing_create_idempotency_key,
|
||||
)
|
||||
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
|
||||
|
||||
idempotency_key = normalize_create_idempotency_key(
|
||||
request.headers.get('Idempotency-Key') or body.get('idempotency_key')
|
||||
)
|
||||
if not idempotency_key:
|
||||
warn_missing_create_idempotency_key(source='workspace_create_shipping_batch_from_intakes')
|
||||
result = create_shipping_batch_from_intakes(
|
||||
user_id=user.id,
|
||||
conversation_id=conversation_id,
|
||||
intake_nos=[str(item) for item in intake_nos],
|
||||
create_idempotency_key=idempotency_key,
|
||||
)
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/retry-pending', methods=['POST'])
|
||||
def workspace_retry_shipping_batch_pending(batch_no: str):
|
||||
"""重试批次中仍可自动推进的任务,跳过终态和人工阻断任务。"""
|
||||
user = _require_user()
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks
|
||||
return jsonify(retry_batch_pending_tasks(batch.batch_no))
|
||||
@@ -1,179 +1,18 @@
|
||||
"""
|
||||
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 链接。
|
||||
用途:工作台文件检核 API 兼容 shim(Wave 1 迁包)。
|
||||
依赖:app.api.workspace.file_check。
|
||||
逻辑:旧 import 路径仍可用;新代码请用 app.api.workspace。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
from app.api.workspace.file_check import (
|
||||
serialize_current_step,
|
||||
serialize_file_judgement,
|
||||
workspace_file_check_bp,
|
||||
)
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.errors import NotFoundError, UnauthorizedError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.file_check_tools.chat_log_run_resolver import find_run_for_chat_log
|
||||
from app.services.schedule.query_service import get_run, serialize_run
|
||||
|
||||
workspace_file_check_bp = Blueprint("workspace_file_check", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def serialize_file_judgement(payload: dict) -> dict:
|
||||
"""序列化检核判定统计(读取 response_summary_json.file_judgement)。"""
|
||||
response_summary = payload.get("response_summary_json") if isinstance(payload.get("response_summary_json"), dict) else {}
|
||||
judgement = response_summary.get("file_judgement")
|
||||
if not isinstance(judgement, dict):
|
||||
judgement = {}
|
||||
return {
|
||||
"qualified_count": int(judgement.get("qualified_count") or 0),
|
||||
"unqualified_count": int(judgement.get("unqualified_count") or 0),
|
||||
"manual_count": int(judgement.get("manual_count") or 0),
|
||||
"dify_error_count": int(judgement.get("dify_error_count") or 0),
|
||||
"invalid_result_count": int(judgement.get("invalid_result_count") or 0),
|
||||
}
|
||||
|
||||
|
||||
def serialize_current_step(payload: dict) -> dict | None:
|
||||
response_summary = payload.get("response_summary_json") if isinstance(payload.get("response_summary_json"), dict) else {}
|
||||
current_step = response_summary.get("current_step") if isinstance(response_summary.get("current_step"), dict) else None
|
||||
if not current_step:
|
||||
return None
|
||||
return {
|
||||
"step": str(current_step.get("step") or ""),
|
||||
"label": str(current_step.get("label") or current_step.get("step") or ""),
|
||||
"row_id": current_step.get("row_id"),
|
||||
"started_at": current_step.get("started_at"),
|
||||
"processed_count": int(current_step.get("processed_count") or 0),
|
||||
"success_count": int(current_step.get("success_count") or 0),
|
||||
"failed_count": int(current_step.get("failed_count") or 0),
|
||||
"skipped_count": int(current_step.get("skipped_count") or 0),
|
||||
}
|
||||
|
||||
|
||||
def _serialize_progress_run(run: ScheduleRun) -> dict:
|
||||
payload = serialize_run(run)
|
||||
total = int(payload.get("total_count") or 0)
|
||||
success = int(payload.get("success_count") or 0)
|
||||
failed = int(payload.get("failed_count") or 0)
|
||||
skipped = int(payload.get("skipped_count") or 0)
|
||||
processed = success + failed + skipped
|
||||
percent = int(round((processed / total) * 100)) if total > 0 else 0
|
||||
percent = max(0, min(percent, 100))
|
||||
return {
|
||||
"run_id": payload["id"],
|
||||
"run_no": payload["run_no"],
|
||||
"task_id": payload["schedule_task_id"],
|
||||
"title": payload.get("schedule_name") or "",
|
||||
"status": payload["status"],
|
||||
"total_count": total,
|
||||
"processed_count": processed,
|
||||
"success_count": success,
|
||||
"failed_count": failed,
|
||||
"skipped_count": skipped,
|
||||
"judgement": serialize_file_judgement(payload),
|
||||
"current_step": serialize_current_step(payload),
|
||||
"progress_percent": percent,
|
||||
"started_at": payload.get("started_at"),
|
||||
"finished_at": payload.get("finished_at"),
|
||||
"duration_ms": payload.get("duration_ms"),
|
||||
"error_message": payload.get("error_message"),
|
||||
"excel": {
|
||||
"file_name": payload.get("excel_file_name"),
|
||||
"file_size": payload.get("excel_file_size"),
|
||||
"download_url": f"/api/workspace/file-check/runs/{run.id}/excel" if payload.get("excel_file_name") else None,
|
||||
},
|
||||
"knowledge_base": {
|
||||
"sync_status": payload.get("kb_sync_status"),
|
||||
"group_id": payload.get("kb_group_id"),
|
||||
"document_id": payload.get("kb_document_id"),
|
||||
"document_version_id": payload.get("kb_document_version_id"),
|
||||
"sync_job_id": payload.get("kb_sync_job_id"),
|
||||
"error_message": payload.get("kb_sync_error"),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@workspace_file_check_bp.route("/file-check/runs/for-log", methods=["GET"])
|
||||
def workspace_file_check_run_for_log():
|
||||
"""按 chat_log_id + schedule_task_id 返回该轮问答绑定的检核批次。"""
|
||||
_require_user()
|
||||
task_id = request.args.get("task_id", type=int)
|
||||
chat_log_id = request.args.get("chat_log_id", type=int)
|
||||
if not task_id or task_id <= 0:
|
||||
return jsonify({"ok": False, "error": "task_id_required"}), 400
|
||||
if not chat_log_id or chat_log_id <= 0:
|
||||
return jsonify({"ok": False, "error": "chat_log_id_required"}), 400
|
||||
|
||||
run = find_run_for_chat_log(task_id=task_id, chat_log_id=chat_log_id)
|
||||
return jsonify({
|
||||
"ok": True,
|
||||
"run": _serialize_progress_run(run) if run else None,
|
||||
"match_source": "chat_log" if run else None,
|
||||
})
|
||||
|
||||
|
||||
@workspace_file_check_bp.route("/file-check/runs/for-session", methods=["GET"])
|
||||
def workspace_file_check_run_for_session():
|
||||
"""已废弃:请改用 for-log?chat_log_id=。保留接口避免旧客户端 404。"""
|
||||
_require_user()
|
||||
return jsonify({"ok": True, "run": None, "match_source": None, "session_updated_at": None})
|
||||
|
||||
|
||||
@workspace_file_check_bp.route("/file-check/runs/active", methods=["GET"])
|
||||
def workspace_file_check_active_run():
|
||||
"""查询当前进行中的检核批次;优先按 schedule_task_id(query: task_id)过滤。"""
|
||||
_require_user()
|
||||
task_id = request.args.get("task_id", type=int)
|
||||
conversation_id = str(request.args.get("conversation_id") or "").strip()
|
||||
query = (
|
||||
ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
|
||||
.filter(ScheduleRun.status == "running")
|
||||
)
|
||||
if task_id is not None:
|
||||
query = query.filter(ScheduleRun.schedule_task_id == task_id)
|
||||
rows = query.order_by(ScheduleRun.id.desc()).all()
|
||||
if task_id is not None:
|
||||
run = rows[0] if rows else None
|
||||
else:
|
||||
run = next((
|
||||
row for row in rows
|
||||
if (
|
||||
not conversation_id
|
||||
or str((row.api_request_json or {}).get("conversation_id") or "").strip() == conversation_id
|
||||
)
|
||||
), None)
|
||||
return jsonify({"ok": True, "run": _serialize_progress_run(run) if run else None})
|
||||
|
||||
|
||||
@workspace_file_check_bp.route("/file-check/runs/<int:run_id>", methods=["GET"])
|
||||
def workspace_file_check_run_detail(run_id: int):
|
||||
_require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
return jsonify({"ok": True, "run": _serialize_progress_run(run)})
|
||||
|
||||
|
||||
@workspace_file_check_bp.route("/file-check/runs/<int:run_id>/excel", methods=["GET"])
|
||||
def workspace_file_check_run_excel(run_id: int):
|
||||
_require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError("excel_not_found")
|
||||
return send_file(
|
||||
BytesIO(run.excel_file_data),
|
||||
as_attachment=True,
|
||||
download_name=run.excel_file_name or f"{run.run_no}.xlsx",
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
__all__ = [
|
||||
'serialize_current_step',
|
||||
'serialize_file_judgement',
|
||||
'workspace_file_check_bp',
|
||||
]
|
||||
@@ -1,49 +1,10 @@
|
||||
from __future__ import annotations
|
||||
from datetime import datetime
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.services.schedule.query_service import can_view_run, get_run, list_runs, serialize_run
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
workspace_schedule_bp = Blueprint('workspace_schedule', __name__)
|
||||
"""
|
||||
backend/app/api/workspace_schedule.py
|
||||
|
||||
def _require_user():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
用途:工作台排程 API 兼容 shim(Wave 1 迁包)。
|
||||
依赖:app.api.workspace.schedule。
|
||||
逻辑:旧 import 路径仍可用;新代码请用 app.api.workspace。
|
||||
"""
|
||||
from app.api.workspace.schedule import workspace_schedule_bp
|
||||
|
||||
@workspace_schedule_bp.route('/schedule-runs', methods=['GET'])
|
||||
def workspace_schedule_runs():
|
||||
user = _require_user()
|
||||
status = str(request.args.get('status') or '').strip() or None
|
||||
schedule_name = str(request.args.get('schedule_name') or '').strip() or None
|
||||
started_after_str = request.args.get('started_after')
|
||||
started_before_str = request.args.get('started_before')
|
||||
started_after = datetime.fromisoformat(started_after_str.replace('Z', '+00:00')) if started_after_str else None
|
||||
started_before = datetime.fromisoformat(started_before_str.replace('Z', '+00:00')) if started_before_str else None
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
return jsonify(list_runs(notify_user_id=user.id, schedule_name=schedule_name, status=status, started_after=started_after, started_before=started_before, limit=limit))
|
||||
|
||||
@workspace_schedule_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
|
||||
def workspace_schedule_run_detail(run_id: int):
|
||||
user = _require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
if not can_view_run(run, user.id):
|
||||
raise ForbiddenError('Forbidden')
|
||||
return jsonify(serialize_run(run))
|
||||
|
||||
@workspace_schedule_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
||||
def workspace_schedule_run_excel(run_id: int):
|
||||
from io import BytesIO
|
||||
user = _require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
if not can_view_run(run, user.id):
|
||||
raise ForbiddenError('Forbidden')
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError('Excel not found')
|
||||
buf = BytesIO(run.excel_file_data)
|
||||
return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
__all__ = ['workspace_schedule_bp']
|
||||
@@ -1,682 +1,10 @@
|
||||
"""
|
||||
api/workspace_shipping_notice.py
|
||||
backend/app/api/workspace_shipping_notice.py
|
||||
|
||||
用途:提供 HXOPS 工作台与聊天前端使用的发货通知用户态 API。
|
||||
依赖:auth_jwt、query_service、shipping_notice.tools、notice_upload、chat_actions。
|
||||
逻辑:前端通过本 Blueprint 访问用户鉴权路由;本文件做权限校验与参数编排,再调用 shipping_notice service/workflow 返回页面所需数据。
|
||||
用途:工作台发货通知 API 兼容 shim(Wave 1 迁包)。
|
||||
依赖:app.api.workspace.shipping_notice。
|
||||
逻辑:旧 import 路径继续 re-export `workspace_shipping_notice_bp`;真实实现统一维护在 workspace 子包中,避免双份路由漂移。
|
||||
"""
|
||||
from app.api.workspace.shipping_notice import workspace_shipping_notice_bp
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.auth_jwt import get_current_user
|
||||
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)
|
||||
return user, None
|
||||
|
||||
|
||||
@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, 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
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = {"user_id": user.id}
|
||||
source_type = str(data.get("source_type") or "").strip()
|
||||
if source_type:
|
||||
payload["source_type"] = source_type
|
||||
conversation_id = str(data.get("conversation_id") or "").strip()
|
||||
if conversation_id:
|
||||
payload["conversation_id"] = conversation_id
|
||||
raw_content = str(data.get("raw_content") or "").strip()
|
||||
if raw_content:
|
||||
payload["raw_content"] = raw_content
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
return jsonify(shipping_tools.create_task(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/create-from-notice", methods=["POST"])
|
||||
def workspace_create_shipping_task_from_notice():
|
||||
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
|
||||
upload = request.files.get("file")
|
||||
if not upload:
|
||||
return jsonify({"error": "file is required"}), 400
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.notice_upload import (
|
||||
extract_notice_text,
|
||||
guess_source_type,
|
||||
max_notice_chars,
|
||||
save_task_notice_upload,
|
||||
)
|
||||
|
||||
source_type = guess_source_type(upload.filename or "")
|
||||
conversation_id = str(request.form.get("conversation_id") or "").strip()
|
||||
payload = {"user_id": user.id, "source_type": source_type}
|
||||
if conversation_id:
|
||||
payload["conversation_id"] = conversation_id
|
||||
created = shipping_tools.create_task(payload)
|
||||
task_id = str(created.get("task_id") or "").strip()
|
||||
if not task_id:
|
||||
return jsonify({"error": "failed to create task"}), 500
|
||||
|
||||
raw = upload.read() or b""
|
||||
saved_path = save_task_notice_upload(task_id, upload.filename or "notice", raw)
|
||||
text, meta = extract_notice_text(saved_path)
|
||||
if not text:
|
||||
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint
|
||||
|
||||
return jsonify(
|
||||
{
|
||||
"status": "needs_human",
|
||||
"task_id": task_id,
|
||||
"message": "未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。",
|
||||
"data": {"notice_upload": {"filename": upload.filename or "", **meta}},
|
||||
"human_options": ["reparse", "reject"],
|
||||
"checkpoint": CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
"action_buttons": action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED),
|
||||
}
|
||||
)
|
||||
|
||||
if text:
|
||||
limit = max_notice_chars()
|
||||
if len(text) > limit:
|
||||
text = text[:limit]
|
||||
meta.setdefault("warnings", []).append(f"notice_text_truncated:{limit}")
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
if task:
|
||||
task.raw_content = text
|
||||
db.session.commit()
|
||||
|
||||
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
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
return jsonify(serialize_task_detail(task))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/chat-actions", methods=["GET"])
|
||||
def workspace_shipping_task_chat_actions(task_no: str):
|
||||
"""返回聊天气泡侧所需的动作按钮与检查点信息。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
return jsonify(build_chat_actions_payload(task))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/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):
|
||||
"""用户态上传库存 Excel,并在服务端完成解析。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
upload = request.files.get("file")
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
return jsonify(shipping_tools.upload_inventory_file(task.task_no, upload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/apply-inventory-mapping", methods=["POST"])
|
||||
def workspace_apply_inventory_mapping(task_no: str):
|
||||
"""提交库存字段映射,并允许在工作台侧自动回退到下一步。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
map_json = data.get(MAP_JSON)
|
||||
if not isinstance(map_json, dict) or not map_json:
|
||||
return jsonify({"error": f"{MAP_JSON} is required"}), 400
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
payload = {"task_id": task.task_no, MAP_JSON: map_json, AUTO_CHAIN_FALLBACK: True}
|
||||
return jsonify(shipping_tools.apply_inventory_mapping(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/submit-decision", methods=["POST"])
|
||||
def workspace_submit_shipping_decision(task_no: str):
|
||||
"""以用户态提交人工决策,绕过 Dify Tool 路由直接驱动状态机。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
decision = str(data.get("decision") or "").strip()
|
||||
if not decision:
|
||||
return jsonify({"error": "decision is required"}), 400
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
payload = {"task_id": task.task_no, "decision": decision, AUTO_CHAIN_FALLBACK: True}
|
||||
comment = str(data.get("comment") or "").strip()
|
||||
if comment:
|
||||
payload["comment"] = comment
|
||||
return jsonify(shipping_tools.submit_decision(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/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):
|
||||
"""用户态触发 auto_progress,作为聊天前端的兜底自动推进入口。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload: dict = {"task_id": task.task_no}
|
||||
for key in ("lang", "locale", "language"):
|
||||
if data.get(key):
|
||||
payload[key] = data[key]
|
||||
break
|
||||
result = shipping_tools.auto_progress(payload)
|
||||
if isinstance(result, dict) and result.get("status") == "ok":
|
||||
gen_data = result.get("data")
|
||||
if isinstance(gen_data, dict) and gen_data.get("export_file_path"):
|
||||
gen_data = {**gen_data, "download_url": f"/api/workspace/shipping-tasks/{task.task_no}/export"}
|
||||
result = {**result, "data": gen_data}
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/match-inventory", methods=["POST"])
|
||||
def workspace_match_shipping_inventory(task_no: str):
|
||||
"""执行库存匹配,并在生成 Excel 后补充前端可直接下载的链接。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
action_buttons_for_checkpoint,
|
||||
human_options_for_checkpoint,
|
||||
)
|
||||
|
||||
matched = shipping_tools.match_inventory({"task_id": task.task_no, AUTO_CHAIN_FALLBACK: True})
|
||||
if not isinstance(matched, dict):
|
||||
return jsonify(matched)
|
||||
data = matched.get("data")
|
||||
if isinstance(data, dict) and data.get("export_file_path"):
|
||||
matched = {
|
||||
**matched,
|
||||
"data": {**data, "download_url": f"/api/workspace/shipping-tasks/{task.task_no}/export"},
|
||||
}
|
||||
checkpoint = matched.get("checkpoint") or CP_EXPORT_GENERATED
|
||||
if matched.get("status") == "ok" and data and data.get("export_file_path"):
|
||||
matched["checkpoint"] = checkpoint
|
||||
if "human_options" not in matched:
|
||||
options = human_options_for_checkpoint(checkpoint)
|
||||
if options is not None:
|
||||
matched["human_options"] = options
|
||||
if "action_buttons" not in matched:
|
||||
buttons = action_buttons_for_checkpoint(checkpoint)
|
||||
if buttons:
|
||||
matched["action_buttons"] = buttons
|
||||
return jsonify(matched)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/mark-manual-uploaded", methods=["POST"])
|
||||
def workspace_mark_manual_uploaded(task_no: str):
|
||||
"""标记货代系统已人工上传完成,无需再等待 RPA 回执。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
return jsonify(
|
||||
shipping_tools.upload_to_freight({"task_id": task.task_no, "mode": "manual_confirm"})
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/generate-excel", methods=["POST"])
|
||||
def workspace_generate_shipping_excel(task_no: str):
|
||||
"""为指定任务生成出货 Excel,并补充工作台下载链接。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
result = shipping_tools.generate_excel({"task_id": task.task_no})
|
||||
if isinstance(result, dict) and result.get("status") == "ok":
|
||||
data = result.get("data")
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
result["data"] = data
|
||||
data["download_url"] = f"/api/workspace/shipping-tasks/{task.task_no}/export"
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/export", methods=["GET"])
|
||||
def workspace_shipping_task_export(task_no: str):
|
||||
"""下载当前用户可访问任务的出货 Excel。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
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=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))
|
||||
__all__ = ['workspace_shipping_notice_bp']
|
||||
@@ -1,287 +0,0 @@
|
||||
import time
|
||||
import json
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Optional
|
||||
|
||||
import jwt
|
||||
import requests
|
||||
from flask import current_app, g, request
|
||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
|
||||
_JWKS_CACHE: dict[str, Any] = {
|
||||
'url': None,
|
||||
'keys': None,
|
||||
'expires_at': 0.0,
|
||||
}
|
||||
|
||||
def _token_brief(token: Optional[str]) -> str:
|
||||
if not token:
|
||||
return 'empty'
|
||||
text = str(token)
|
||||
if len(text) <= 16:
|
||||
return f'len={len(text)}:{text}'
|
||||
return f'len={len(text)}:{text[:8]}...{text[-8:]}'
|
||||
|
||||
|
||||
def _extract_bearer_token() -> Optional[str]:
|
||||
# Only trust standard Bearer token; reject all non-Bearer auth schemes.
|
||||
auth = request.headers.get('Authorization', '')
|
||||
if not auth:
|
||||
return None
|
||||
parts = auth.split(' ', 1)
|
||||
if len(parts) != 2 or parts[0].lower() != 'bearer':
|
||||
return None
|
||||
token = parts[1].strip()
|
||||
return token or None
|
||||
|
||||
|
||||
def _get_jwks_keys(jwks_url: str) -> dict:
|
||||
# Keep a short in-memory JWKS cache to avoid hitting Casdoor for every request.
|
||||
now = time.time()
|
||||
if (
|
||||
_JWKS_CACHE.get('url') == jwks_url
|
||||
and isinstance(_JWKS_CACHE.get('keys'), dict)
|
||||
and now < float(_JWKS_CACHE.get('expires_at') or 0.0)
|
||||
):
|
||||
return _JWKS_CACHE['keys']
|
||||
|
||||
resp = requests.get(jwks_url, timeout=5)
|
||||
resp.raise_for_status()
|
||||
data = resp.json() or {}
|
||||
keys = {}
|
||||
for item in data.get('keys', []):
|
||||
kid = item.get('kid')
|
||||
if kid:
|
||||
keys[kid] = item
|
||||
if not keys:
|
||||
raise ValueError('No JWKS keys found')
|
||||
|
||||
_JWKS_CACHE['url'] = jwks_url
|
||||
_JWKS_CACHE['keys'] = keys
|
||||
_JWKS_CACHE['expires_at'] = now + 300
|
||||
return keys
|
||||
|
||||
|
||||
def _decode_jwt(token: str) -> dict:
|
||||
# Strictly validate iss/aud/exp/iat against Casdoor metadata-derived settings.
|
||||
issuer = (current_app.config.get('AUTH_JWT_ISSUER') or '').strip()
|
||||
audience = (current_app.config.get('AUTH_JWT_AUDIENCE') or '').strip()
|
||||
jwks_url = (current_app.config.get('AUTH_JWT_JWKS_URL') or '').strip()
|
||||
if not issuer or not audience or not jwks_url:
|
||||
raise ValueError('JWT auth is not fully configured')
|
||||
|
||||
header = jwt.get_unverified_header(token)
|
||||
kid = header.get('kid')
|
||||
current_app.logger.info(
|
||||
'[auth_jwt] decode start kid=%s alg=%s token=%s',
|
||||
kid,
|
||||
header.get('alg'),
|
||||
_token_brief(token),
|
||||
)
|
||||
if not kid:
|
||||
if not bool(current_app.config.get('AUTH_ALLOW_LOCAL_JWT', True)):
|
||||
raise ValueError('JWT header missing kid')
|
||||
secret = current_app.config.get('SECRET_KEY')
|
||||
if not secret:
|
||||
raise ValueError('Local JWT secret is missing')
|
||||
local_issuer = (current_app.config.get('AUTH_LOCAL_JWT_ISSUER') or 'hxops-backend').strip()
|
||||
local_audience = (current_app.config.get('AUTH_LOCAL_JWT_AUDIENCE') or 'hxops-frontend').strip()
|
||||
return jwt.decode(
|
||||
token,
|
||||
key=secret,
|
||||
algorithms=['HS256'],
|
||||
audience=local_audience,
|
||||
issuer=local_issuer,
|
||||
options={'require': ['exp', 'iat']},
|
||||
)
|
||||
|
||||
keys = _get_jwks_keys(jwks_url)
|
||||
jwk = keys.get(kid)
|
||||
if not jwk:
|
||||
# stale cache fallback
|
||||
_JWKS_CACHE['expires_at'] = 0.0
|
||||
keys = _get_jwks_keys(jwks_url)
|
||||
jwk = keys.get(kid)
|
||||
if not jwk:
|
||||
raise ValueError('No matching JWKS key for token')
|
||||
|
||||
# Different jwt packages/versions expose JWK->public-key helpers differently.
|
||||
# Try multiple compatible paths to avoid hard dependency on one symbol name.
|
||||
public_key = None
|
||||
pyjwk = getattr(jwt, 'PyJWK', None)
|
||||
if pyjwk and hasattr(pyjwk, 'from_dict'):
|
||||
public_key = pyjwk.from_dict(jwk).key
|
||||
if public_key is None:
|
||||
rsa_alg = getattr(getattr(jwt, 'algorithms', None), 'RSAAlgorithm', None)
|
||||
if rsa_alg and hasattr(rsa_alg, 'from_jwk'):
|
||||
public_key = rsa_alg.from_jwk(json.dumps(jwk))
|
||||
if public_key is None:
|
||||
get_algs = getattr(getattr(jwt, 'algorithms', None), 'get_default_algorithms', None)
|
||||
if callable(get_algs):
|
||||
rs256 = (get_algs() or {}).get('RS256')
|
||||
if rs256 and hasattr(rs256, 'from_jwk'):
|
||||
public_key = rs256.from_jwk(json.dumps(jwk))
|
||||
if public_key is None:
|
||||
raise ValueError('Cannot build RSA public key from JWK; check installed jwt package')
|
||||
|
||||
return jwt.decode(
|
||||
token,
|
||||
key=public_key,
|
||||
algorithms=['RS256', 'RS384', 'RS512'],
|
||||
audience=audience,
|
||||
issuer=issuer,
|
||||
options={'require': ['exp', 'iat']},
|
||||
)
|
||||
|
||||
|
||||
def _extract_unverified_claims(token: str) -> dict:
|
||||
"""Best-effort decode without signature verification for troubleshooting logs."""
|
||||
try:
|
||||
return jwt.decode(
|
||||
token,
|
||||
options={
|
||||
'verify_signature': False,
|
||||
'verify_exp': False,
|
||||
'verify_iat': False,
|
||||
'verify_nbf': False,
|
||||
'verify_aud': False,
|
||||
'verify_iss': False,
|
||||
},
|
||||
) or {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _resolve_user_from_claims(claims: dict) -> Optional[User]:
|
||||
# Resolution order keeps compatibility with different token claim conventions.
|
||||
def _lookup() -> Optional[User]:
|
||||
user_id = claims.get('user_id') or claims.get('id')
|
||||
if user_id is not None:
|
||||
try:
|
||||
user = db.session.get(User, int(user_id))
|
||||
if user:
|
||||
return user
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
username = claims.get('preferred_username') or claims.get('username') or claims.get('name')
|
||||
if username:
|
||||
user = db.session.query(User).filter_by(username=str(username)).first()
|
||||
if user:
|
||||
return user
|
||||
|
||||
email = claims.get('email')
|
||||
if email:
|
||||
user = db.session.query(User).filter_by(email=str(email)).first()
|
||||
if user:
|
||||
return user
|
||||
return None
|
||||
|
||||
try:
|
||||
return _lookup()
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('[auth_jwt] transient db error when resolving user, retry with reconnect path=%s err=%s', request.path, exc)
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
db.engine.dispose()
|
||||
except Exception:
|
||||
current_app.logger.warning('[auth_jwt] failed to dispose engine during user reconnect recovery', exc_info=True)
|
||||
return _lookup()
|
||||
|
||||
|
||||
def _legacy_header_user() -> Optional[User]:
|
||||
def _lookup() -> Optional[User]:
|
||||
user_id = request.headers.get('X-User-Id')
|
||||
if user_id:
|
||||
try:
|
||||
user = db.session.get(User, int(user_id))
|
||||
if user:
|
||||
return user
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
username = request.headers.get('X-Username')
|
||||
if username:
|
||||
return db.session.query(User).filter_by(username=username).first()
|
||||
return None
|
||||
|
||||
try:
|
||||
return _lookup()
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('[auth_jwt] transient db error when resolving legacy header user, retry with reconnect path=%s err=%s', request.path, exc)
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
db.engine.dispose()
|
||||
except Exception:
|
||||
current_app.logger.warning('[auth_jwt] failed to dispose engine during legacy user reconnect recovery', exc_info=True)
|
||||
return _lookup()
|
||||
|
||||
|
||||
def get_current_user() -> Optional[User]:
|
||||
cached = getattr(g, 'current_user', None)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
token = _extract_bearer_token()
|
||||
if token:
|
||||
try:
|
||||
claims = _decode_jwt(token)
|
||||
user = _resolve_user_from_claims(claims)
|
||||
current_app.logger.info(
|
||||
'[auth_jwt] decode ok sub=%s username=%s resolved_user=%s',
|
||||
claims.get('sub'),
|
||||
claims.get('preferred_username') or claims.get('username') or claims.get('name'),
|
||||
getattr(user, 'username', None),
|
||||
)
|
||||
except Exception:
|
||||
# Any decode/lookup failure should behave as unauthenticated.
|
||||
unverified = _extract_unverified_claims(token)
|
||||
expected_issuer = (current_app.config.get('AUTH_JWT_ISSUER') or '').strip()
|
||||
expected_audience = (current_app.config.get('AUTH_JWT_AUDIENCE') or '').strip()
|
||||
current_app.logger.error(
|
||||
'[auth_jwt] decode context token_iss=%s token_aud=%s expected_iss=%s expected_aud=%s',
|
||||
unverified.get('iss'),
|
||||
unverified.get('aud'),
|
||||
expected_issuer,
|
||||
expected_audience,
|
||||
)
|
||||
current_app.logger.exception('[auth_jwt] decode failed token=%s path=%s', _token_brief(token), request.path)
|
||||
user = None
|
||||
claims = None
|
||||
if user:
|
||||
g.jwt_claims = claims
|
||||
g.current_user = user
|
||||
return user
|
||||
|
||||
if bool(current_app.config.get('AUTH_LEGACY_HEADER_ENABLED', True)):
|
||||
user = _legacy_header_user()
|
||||
if user:
|
||||
g.current_user = user
|
||||
return user
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def issue_local_access_token(user: User) -> str:
|
||||
"""Issue local HS256 JWT for password-login flow compatibility."""
|
||||
now = datetime.now(timezone.utc)
|
||||
exp_hours = int(current_app.config.get('AUTH_LOCAL_JWT_EXPIRES_HOURS') or 12)
|
||||
payload = {
|
||||
'sub': str(user.id),
|
||||
'id': user.id,
|
||||
'user_id': user.id,
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'email': user.email,
|
||||
'iat': int(now.timestamp()),
|
||||
'exp': int((now + timedelta(hours=max(1, exp_hours))).timestamp()),
|
||||
'iss': (current_app.config.get('AUTH_LOCAL_JWT_ISSUER') or 'hxops-backend'),
|
||||
'aud': (current_app.config.get('AUTH_LOCAL_JWT_AUDIENCE') or 'hxops-frontend'),
|
||||
}
|
||||
secret = current_app.config.get('SECRET_KEY')
|
||||
return jwt.encode(payload, secret, algorithm='HS256')
|
||||
@@ -1 +0,0 @@
|
||||
"""FAQ CLI 包。"""
|
||||
@@ -1,44 +0,0 @@
|
||||
"""
|
||||
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)
|
||||
@@ -1,325 +0,0 @@
|
||||
"""
|
||||
backend/app/config.py
|
||||
配置类,区分开发/生产环境
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
|
||||
_BACKEND_DIR = Path(__file__).resolve().parents[1]
|
||||
_ROOT_DIR = _BACKEND_DIR.parent
|
||||
|
||||
|
||||
def _normalize_env_name(raw: str | None) -> str:
|
||||
value = (raw or '').strip().lower()
|
||||
if value in ('dev', 'development', ''):
|
||||
return 'dev'
|
||||
if value in ('test', 'testing'):
|
||||
return 'test'
|
||||
if value in ('prod', 'production'):
|
||||
return 'prod'
|
||||
return 'dev'
|
||||
|
||||
|
||||
def _load_environment_files() -> str:
|
||||
"""Load env files from project root with stable priority.
|
||||
|
||||
Priority (low -> high):
|
||||
1. .env.shared
|
||||
2. .env.<ENV_NAME>
|
||||
3. .env.local (only for dev)
|
||||
4. system environment variables (always highest, never overridden)
|
||||
"""
|
||||
env_name = _normalize_env_name(os.getenv('ENV_NAME') or os.getenv('FLASK_ENV'))
|
||||
shared_file = _ROOT_DIR / '.env.shared'
|
||||
if shared_file.exists():
|
||||
load_dotenv(shared_file, override=False)
|
||||
|
||||
env_file = _ROOT_DIR / f'.env.{env_name}'
|
||||
if env_file.exists():
|
||||
load_dotenv(env_file, override=True)
|
||||
|
||||
if env_name == 'dev':
|
||||
local_file = _ROOT_DIR / '.env.local'
|
||||
if local_file.exists():
|
||||
load_dotenv(local_file, override=True)
|
||||
return env_name
|
||||
|
||||
|
||||
ACTIVE_ENV_NAME = _load_environment_files()
|
||||
|
||||
|
||||
def _data_path(env_key: str, *parts: str) -> str:
|
||||
from app.path_utils import resolve_backend_relative_path
|
||||
|
||||
default = _BACKEND_DIR.joinpath("data", *parts)
|
||||
return resolve_backend_relative_path(os.getenv(env_key), default)
|
||||
|
||||
|
||||
def _backend_path(env_key: str, *parts: str) -> str:
|
||||
from app.path_utils import resolve_backend_relative_path
|
||||
|
||||
default = _BACKEND_DIR.joinpath(*parts)
|
||||
return resolve_backend_relative_path(os.getenv(env_key), default)
|
||||
|
||||
|
||||
class Config:
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
SECRET_KEY = os.getenv('SECRET_KEY')
|
||||
KB_STORAGE_ROOT = os.getenv('KB_STORAGE_ROOT', str(_BACKEND_DIR / 'data' / 'kb'))
|
||||
KB_TASK_EXECUTION_MODE = os.getenv('KB_TASK_EXECUTION_MODE', 'worker').strip().lower()
|
||||
KB_WORKER_POLL_SECONDS = float(os.getenv('KB_WORKER_POLL_SECONDS', '2'))
|
||||
KB_WORKER_CONCURRENCY = int(os.getenv('KB_WORKER_CONCURRENCY', '3') or '3')
|
||||
# kb-worker 自动回收长时间 running 的任务(秒),默认 300,应大于单次清洗预期耗时
|
||||
KB_JOB_RUNNING_TIMEOUT_SECONDS = float(os.getenv('KB_JOB_RUNNING_TIMEOUT_SECONDS', '300'))
|
||||
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免卡住整个 worker 队列
|
||||
EDKB_FILE_TIMEOUT_SEC = int(os.getenv('EDKB_FILE_TIMEOUT_SEC', '0') or '0')
|
||||
# 数据库连接池配置
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {
|
||||
'pool_size': 20,
|
||||
'max_overflow': 10,
|
||||
'pool_recycle': 3600,
|
||||
'pool_pre_ping': True,
|
||||
}
|
||||
PUBLIC_BASE_URL = os.getenv('PUBLIC_BASE_URL')
|
||||
DEFAULT_ADMIN_USERNAME = os.getenv('DEFAULT_ADMIN_USERNAME')
|
||||
DEFAULT_ADMIN_PASSWORD = os.getenv('DEFAULT_ADMIN_PASSWORD')
|
||||
TASK_EXECUTION_MODE = os.getenv('TASK_EXECUTION_MODE', '').strip().lower()
|
||||
# Dify 网关配置
|
||||
DIFY_API_BASE = os.getenv('DIFY_API_BASE')
|
||||
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
|
||||
DIFY_CHAT_CONNECT_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_CONNECT_TIMEOUT_SECONDS', '5'))
|
||||
DIFY_CHAT_READ_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_READ_TIMEOUT_SECONDS', '30'))
|
||||
# Redis 连接配置,默认使用本地 Redis + 密码
|
||||
REDIS_URL = os.getenv('REDIS_URL')
|
||||
FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true'
|
||||
HR_WORKFLOW_IFRAME_URL = os.getenv('HR_WORKFLOW_IFRAME_URL')
|
||||
HR_WORKFLOW_API_BASE = os.getenv('HR_WORKFLOW_API_BASE')
|
||||
HR_WORKFLOW_API_KEY = os.getenv('HR_WORKFLOW_API_KEY')
|
||||
OA_WORKFLOW_WSDL_URL = os.getenv(
|
||||
'OA_WORKFLOW_WSDL_URL',
|
||||
'http://oa.well-trust.com:8888/services/WorkflowService?wsdl',
|
||||
)
|
||||
OA_LEAVE_WORKFLOW_CODE = os.getenv('OA_LEAVE_WORKFLOW_CODE', '879')
|
||||
|
||||
# External integration API (resolve original source file links by Dify IDs)
|
||||
INTEGRATION_API_MODE = os.getenv('INTEGRATION_API_MODE', 'local').strip().lower()
|
||||
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
|
||||
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
|
||||
|
||||
# HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 共用;无尾斜杠)
|
||||
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')
|
||||
|
||||
# 文件检核 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 = (
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS') or '3'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '120'
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM = os.getenv('SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM', 'false').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_MATCH_ENABLED', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN = os.getenv(
|
||||
'SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN',
|
||||
'shipment_{task_no}_{ts}.xlsx',
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED', 'false').lower() == 'true'
|
||||
# Hxops 工作台 / 聊天按钮兜底串联(Dify 主路径走 auto_progress;画布 HTTP 不传 auto_chain_fallback)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK = os.getenv('SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS') or '3')
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS') or '30'
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS = int(
|
||||
os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000'
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE = float(
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE') or '0.8'
|
||||
)
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
|
||||
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
|
||||
FREIGHT_INVENTORY_DROP_DIR = _data_path("FREIGHT_INVENTORY_DROP_DIR", "freight_rpa", "inventory_drop")
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR = _data_path(
|
||||
"FREIGHT_RPA_INVENTORY_TRIGGER_DIR", "freight_rpa", "inventory_triggers"
|
||||
)
|
||||
FREIGHT_UPLOAD_QUEUE_DIR = _data_path("FREIGHT_UPLOAD_QUEUE_DIR", "freight_rpa", "upload_queue")
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR = _data_path(
|
||||
"FREIGHT_RPA_UPLOAD_TRIGGER_DIR", "freight_rpa", "upload_triggers"
|
||||
)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH = _backend_path(
|
||||
"FREIGHT_SHIPMENT_TEMPLATE_PATH", "templates", "freight_shipment_upload.xlsx"
|
||||
)
|
||||
|
||||
# WeCom (企业微信) 登录配置
|
||||
WECOM_ENABLED = os.getenv('WECOM_ENABLED', 'false').lower() == 'true'
|
||||
WECOM_CORP_ID = os.getenv('WECOM_CORP_ID')
|
||||
WECOM_AGENT_ID = os.getenv('WECOM_AGENT_ID')
|
||||
WECOM_SECRET = os.getenv('WECOM_SECRET')
|
||||
WECOM_REDIRECT_URI = os.getenv('WECOM_REDIRECT_URI')
|
||||
WECOM_AUTO_CREATE_USER = os.getenv('WECOM_AUTO_CREATE_USER', 'true').lower() == 'true'
|
||||
WECOM_MATCH_RULES = os.getenv('WECOM_MATCH_RULES')
|
||||
WECOM_MATCH_OPERATOR = os.getenv('WECOM_MATCH_OPERATOR').upper()
|
||||
WECOM_FIRST_LOGIN_BIND_MODE = os.getenv('WECOM_FIRST_LOGIN_BIND_MODE')
|
||||
WECOM_FIRST_LOGIN_INPUT_FIELDS = os.getenv('WECOM_FIRST_LOGIN_INPUT_FIELDS')
|
||||
WECOM_EMPLOYEE_ID_SOURCE = os.getenv('WECOM_EMPLOYEE_ID_SOURCE')
|
||||
WECOM_MOBILE_NORMALIZE = os.getenv('WECOM_MOBILE_NORMALIZE', 'true').lower() == 'true'
|
||||
WECOM_CALLBACK_TOKEN = os.getenv('WECOM_CALLBACK_TOKEN')
|
||||
WECOM_ENCODING_AES_KEY = os.getenv('WECOM_ENCODING_AES_KEY')
|
||||
WECOM_CALLBACK_URL = os.getenv('WECOM_CALLBACK_URL')
|
||||
WECOM_HOMEPAGE_URL = os.getenv('WECOM_HOMEPAGE_URL')
|
||||
WECOM_TRUSTED_DOMAIN = os.getenv('WECOM_TRUSTED_DOMAIN')
|
||||
# Public HTTPS origin for WeCom console URLs (takes priority over notify base + request host).
|
||||
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
|
||||
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset')
|
||||
WECOM_FEEDBACK_NOTIFY_ENABLED = os.getenv('WECOM_FEEDBACK_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_FEEDBACK_NOTIFY_BASE_URL = os.getenv('WECOM_FEEDBACK_NOTIFY_BASE_URL')
|
||||
WECOM_FEEDBACK_BOT_WEBHOOK = os.getenv('WECOM_FEEDBACK_BOT_WEBHOOK')
|
||||
|
||||
# JWT/Casdoor auth configuration (phase-1 compatible rollout)
|
||||
AUTH_LEGACY_HEADER_ENABLED = os.getenv('AUTH_LEGACY_HEADER_ENABLED', 'true').lower() == 'true'
|
||||
AUTH_JWT_REQUIRED = os.getenv('AUTH_JWT_REQUIRED', 'true').lower() == 'true'
|
||||
AUTH_ALLOW_LOCAL_PASSWORD_LOGIN = os.getenv('AUTH_ALLOW_LOCAL_PASSWORD_LOGIN', 'true').lower() == 'true'
|
||||
# Login mode switch: "casdoor" (default) or "password".
|
||||
# casdoor: login form credentials are sent to Casdoor token endpoint (no redirect page for users).
|
||||
# password: keep legacy local username/password login.
|
||||
AUTH_LOGIN_MODE = os.getenv('AUTH_LOGIN_MODE').strip().lower()
|
||||
AUTH_ALLOW_LOCAL_JWT = os.getenv('AUTH_ALLOW_LOCAL_JWT', 'true').lower() == 'true'
|
||||
# JWT 的签发者(iss)校验值,后端用它确认“这个 token 是谁发的”
|
||||
AUTH_JWT_ISSUER = os.getenv('AUTH_JWT_ISSUER')
|
||||
# JWT 的受众(aud)校验值,后端用它确认“这个 token 是发给哪个应用的”
|
||||
AUTH_JWT_AUDIENCE = os.getenv('AUTH_JWT_AUDIENCE')
|
||||
# 公钥集合地址(JWKS),后端从这里拉公钥来验签 JWT
|
||||
AUTH_JWT_JWKS_URL = os.getenv('AUTH_JWT_JWKS_URL')
|
||||
CASDOOR_BASE_URL = os.getenv('CASDOOR_BASE_URL')
|
||||
CASDOOR_CLIENT_ID = os.getenv('CASDOOR_CLIENT_ID')
|
||||
CASDOOR_CLIENT_SECRET = os.getenv('CASDOOR_CLIENT_SECRET')
|
||||
# Fallback when authorize-url request omits redirect_uri; OAuth flow sends browser origin + /casdoor-callback.
|
||||
# Casdoor Application must whitelist every origin users hit, e.g. IP and domain on port 8881.
|
||||
CASDOOR_REDIRECT_URI = os.getenv('CASDOOR_REDIRECT_URI')
|
||||
CASDOOR_SCOPE = os.getenv('CASDOOR_SCOPE')
|
||||
# Casdoor organization (userOwner) for set-password and other management APIs.
|
||||
CASDOOR_ORGANIZATION = (os.getenv('CASDOOR_ORGANIZATION') or 'organization_HX').strip()
|
||||
# WeCom as Casdoor IdP: provider Name from Casdoor Providers page (used with default_provider=wecom on authorize-url).
|
||||
CASDOOR_WECOM_PROVIDER_HINT = os.getenv('CASDOOR_WECOM_PROVIDER_HINT').strip()
|
||||
CASDOOR_WECOM_SILENT_SIGNIN = os.getenv('CASDOOR_WECOM_SILENT_SIGNIN', 'false').lower() == 'true'
|
||||
AUTH_LOCAL_JWT_ISSUER = os.getenv('AUTH_LOCAL_JWT_ISSUER')
|
||||
AUTH_LOCAL_JWT_AUDIENCE = os.getenv('AUTH_LOCAL_JWT_AUDIENCE')
|
||||
AUTH_LOCAL_JWT_EXPIRES_HOURS = int(os.getenv('AUTH_LOCAL_JWT_EXPIRES_HOURS', '12'))
|
||||
SCHEDULE_WORKER_ENABLED = os.getenv('SCHEDULE_WORKER_ENABLED', 'true').lower() == 'true'
|
||||
# Cron 表达式按此时区解读(如 0 12 * * * 表示该时区 12:00);入库 next_run_at 仍为 UTC。
|
||||
SCHEDULE_TIMEZONE = (os.getenv('SCHEDULE_TIMEZONE') or 'Asia/Shanghai').strip()
|
||||
SRM_SQLSERVER_HOST = os.getenv('SRM_SQLSERVER_HOST', '')
|
||||
SRM_SQLSERVER_PORT = os.getenv('SRM_SQLSERVER_PORT', '1433')
|
||||
SRM_SQLSERVER_DATABASE = os.getenv('SRM_SQLSERVER_DATABASE', '')
|
||||
SRM_SQLSERVER_USERNAME = os.getenv('SRM_SQLSERVER_USERNAME', '')
|
||||
SRM_SQLSERVER_PASSWORD = os.getenv('SRM_SQLSERVER_PASSWORD', '')
|
||||
SRM_SQLSERVER_DRIVER = os.getenv('SRM_SQLSERVER_DRIVER', 'SQL Server')
|
||||
SRM_SQLSERVER_ENCRYPT = os.getenv('SRM_SQLSERVER_ENCRYPT', 'no')
|
||||
SRM_SQLSERVER_TRUST_CERT = os.getenv('SRM_SQLSERVER_TRUST_CERT', 'yes')
|
||||
SRM_SQLSERVER_TIMEOUT = int(os.getenv('SRM_SQLSERVER_TIMEOUT', '15'))
|
||||
SMTP_HOST = os.getenv('SMTP_HOST', '')
|
||||
SMTP_PORT = int(os.getenv('SMTP_PORT', '25'))
|
||||
SMTP_USER = os.getenv('SMTP_USER', '')
|
||||
SMTP_PASSWORD = os.getenv('SMTP_PASSWORD', '')
|
||||
SMTP_FROM = os.getenv('SMTP_FROM', '')
|
||||
SMTP_USE_TLS = os.getenv('SMTP_USE_TLS', 'true').lower() == 'true'
|
||||
INTERNAL_API_BASE_URL = os.getenv('INTERNAL_API_BASE_URL', 'http://127.0.0.1:5052')
|
||||
FIXED_ASSETS_SYNC_ENABLED = os.getenv('FIXED_ASSETS_SYNC_ENABLED', 'true').lower() == 'true'
|
||||
FIXED_ASSETS_SYNC_TIMEZONE = (os.getenv('FIXED_ASSETS_SYNC_TIMEZONE') or 'Asia/Shanghai').strip()
|
||||
FIXED_ASSETS_SYNC_HOUR = int(os.getenv('FIXED_ASSETS_SYNC_HOUR', '3') or '3')
|
||||
FIXED_ASSETS_SYNC_MINUTE = int(os.getenv('FIXED_ASSETS_SYNC_MINUTE', '0') or '0')
|
||||
FIXED_ASSETS_SYNC_TIMEOUT_SECONDS = int(os.getenv('FIXED_ASSETS_SYNC_TIMEOUT_SECONDS', '600') or '600')
|
||||
FIXED_ASSETS_SYNC_RETRY_INTERVAL_MINUTES = int(
|
||||
os.getenv('FIXED_ASSETS_SYNC_RETRY_INTERVAL_MINUTES', '30') or '30'
|
||||
)
|
||||
FIXED_ASSETS_SYNC_MAX_ATTEMPTS = int(os.getenv('FIXED_ASSETS_SYNC_MAX_ATTEMPTS', '4') or '4')
|
||||
FIXED_ASSETS_SYNC_POLL_SECONDS = int(os.getenv('FIXED_ASSETS_SYNC_POLL_SECONDS', '60') or '60')
|
||||
FIXED_ASSETS_SYNC_ON_BOOT_IF_MISSING = (
|
||||
os.getenv('FIXED_ASSETS_SYNC_ON_BOOT_IF_MISSING', 'true').lower() == 'true'
|
||||
)
|
||||
FIXED_ASSETS_HISTORY_KEEP_COUNT = int(os.getenv('FIXED_ASSETS_HISTORY_KEEP_COUNT', '3') or '3')
|
||||
FIXED_ASSETS_STORAGE_ROOT = _data_path('FIXED_ASSETS_STORAGE_ROOT', 'fixed_assets')
|
||||
FIXED_ASSETS_DOCS_EXPORT_ROOT = os.getenv(
|
||||
'FIXED_ASSETS_DOCS_EXPORT_ROOT',
|
||||
str(_ROOT_DIR / 'docs'),
|
||||
)
|
||||
FIXED_ASSETS_EXPORT_TO_DOCS = os.getenv('FIXED_ASSETS_EXPORT_TO_DOCS', 'true').lower() == 'true'
|
||||
FIXED_ASSETS_ERP_USERNAME = os.getenv('FIXED_ASSETS_ERP_USERNAME', 'EXT_VIEW_USER')
|
||||
FIXED_ASSETS_ERP_PASSWORD = os.getenv('FIXED_ASSETS_ERP_PASSWORD', 'extviewuser')
|
||||
FIXED_ASSETS_ERP_DSN = os.getenv('FIXED_ASSETS_ERP_DSN') or os.getenv('ERP_DB_DSN', '192.168.8.24:1521/topprod')
|
||||
|
||||
# MinIO 配置
|
||||
MINIO_ENDPOINT = os.getenv('MINIO_ENDPOINT', '127.0.0.1:9000')
|
||||
MINIO_ACCESS_KEY = os.getenv('MINIO_ACCESS_KEY', 'minioadmin')
|
||||
MINIO_SECRET_KEY = os.getenv('MINIO_SECRET_KEY', 'minioadmin')
|
||||
MINIO_SECURE = os.getenv('MINIO_SECURE', 'false').lower() == 'true'
|
||||
MINIO_AGENT_GUIDES_BUCKET = os.getenv('MINIO_AGENT_GUIDES_BUCKET', 'agent-guides')
|
||||
MINIO_PUBLIC_BASE_URL = os.getenv('MINIO_PUBLIC_BASE_URL', 'http://127.0.0.1:9000')
|
||||
|
||||
|
||||
class DevelopmentConfig(Config):
|
||||
DEBUG = True
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
|
||||
|
||||
|
||||
class ProductionConfig(Config):
|
||||
DEBUG = False
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
|
||||
|
||||
|
||||
class TestingConfig(Config):
|
||||
TESTING = True
|
||||
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
|
||||
WTF_CSRF_ENABLED = False
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {}
|
||||
SCHEDULE_WORKER_ENABLED = False
|
||||
FIXED_ASSETS_SYNC_ENABLED = False
|
||||
FIXED_ASSETS_EXPORT_TO_DOCS = False
|
||||
|
||||
|
||||
config = {
|
||||
'dev': DevelopmentConfig,
|
||||
'development': DevelopmentConfig,
|
||||
'test': TestingConfig,
|
||||
'testing': TestingConfig, # alias for create_app('testing') in pytest
|
||||
'prod': ProductionConfig,
|
||||
'production': ProductionConfig,
|
||||
'default': DevelopmentConfig,
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
"""
|
||||
backend/app/core/__init__.py
|
||||
|
||||
用途:横切能力包入口(errors、response、auth、config、db)。
|
||||
逻辑:Wave 1 逐步将 app 根目录模块迁入 core/ 子包;过渡期旧路径 re-export。
|
||||
用途:横切能力包入口(errors、response、auth、config、decorators)。
|
||||
逻辑:业务代码 from app.core.errors / app.core.auth.jwt 等子模块 import。
|
||||
"""
|
||||
|
||||
from app.core.errors import AppError # noqa: F401
|
||||
|
||||
__all__ = ['AppError']
|
||||
@@ -1,9 +1,314 @@
|
||||
"""
|
||||
backend/app/core/auth/jwt.py
|
||||
|
||||
用途:Casdoor JWT 校验与当前用户解析(Wave 1 自 app/auth_jwt.py 迁入)。
|
||||
逻辑:api 路由与 decorators 调用 get_current_user()。
|
||||
用途:Casdoor JWT 校验、legacy header 回退与当前用户解析。
|
||||
依赖:app.extensions.db、app.models.User、PyJWT、requests。
|
||||
逻辑:api 层与 decorators 调用 get_current_user()。
|
||||
"""
|
||||
from app.auth_jwt import get_current_user # noqa: F401
|
||||
|
||||
__all__ = ['get_current_user']
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Optional
|
||||
|
||||
import jwt
|
||||
import requests
|
||||
from flask import current_app, g, request
|
||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import User
|
||||
|
||||
_JWKS_CACHE: dict[str, Any] = {
|
||||
'url': None,
|
||||
'keys': None,
|
||||
'expires_at': 0.0,
|
||||
}
|
||||
|
||||
|
||||
def _token_brief(token: Optional[str]) -> str:
|
||||
if not token:
|
||||
return 'empty'
|
||||
text = str(token)
|
||||
if len(text) <= 16:
|
||||
return f'len={len(text)}:{text}'
|
||||
return f'len={len(text)}:{text[:8]}...{text[-8:]}'
|
||||
|
||||
|
||||
def _extract_bearer_token() -> Optional[str]:
|
||||
auth = request.headers.get('Authorization', '')
|
||||
if not auth:
|
||||
return None
|
||||
parts = auth.split(' ', 1)
|
||||
if len(parts) != 2 or parts[0].lower() != 'bearer':
|
||||
return None
|
||||
token = parts[1].strip()
|
||||
return token or None
|
||||
|
||||
|
||||
def _get_jwks_keys(jwks_url: str) -> dict:
|
||||
now = time.time()
|
||||
if (
|
||||
_JWKS_CACHE.get('url') == jwks_url
|
||||
and isinstance(_JWKS_CACHE.get('keys'), dict)
|
||||
and now < float(_JWKS_CACHE.get('expires_at') or 0.0)
|
||||
):
|
||||
return _JWKS_CACHE['keys']
|
||||
|
||||
resp = requests.get(jwks_url, timeout=5)
|
||||
resp.raise_for_status()
|
||||
data = resp.json() or {}
|
||||
keys = {}
|
||||
for item in data.get('keys', []):
|
||||
kid = item.get('kid')
|
||||
if kid:
|
||||
keys[kid] = item
|
||||
if not keys:
|
||||
raise ValueError('No JWKS keys found')
|
||||
|
||||
_JWKS_CACHE['url'] = jwks_url
|
||||
_JWKS_CACHE['keys'] = keys
|
||||
_JWKS_CACHE['expires_at'] = now + 300
|
||||
return keys
|
||||
|
||||
|
||||
def _decode_jwt(token: str) -> dict:
|
||||
issuer = (current_app.config.get('AUTH_JWT_ISSUER') or '').strip()
|
||||
audience = (current_app.config.get('AUTH_JWT_AUDIENCE') or '').strip()
|
||||
jwks_url = (current_app.config.get('AUTH_JWT_JWKS_URL') or '').strip()
|
||||
if not issuer or not audience or not jwks_url:
|
||||
raise ValueError('JWT auth is not fully configured')
|
||||
|
||||
header = jwt.get_unverified_header(token)
|
||||
kid = header.get('kid')
|
||||
if not kid:
|
||||
if not bool(current_app.config.get('AUTH_ALLOW_LOCAL_JWT', True)):
|
||||
raise ValueError('JWT header missing kid')
|
||||
secret = current_app.config.get('SECRET_KEY')
|
||||
if not secret:
|
||||
raise ValueError('Local JWT secret is missing')
|
||||
local_issuer = (current_app.config.get('AUTH_LOCAL_JWT_ISSUER') or 'hxops-backend').strip()
|
||||
local_audience = (current_app.config.get('AUTH_LOCAL_JWT_AUDIENCE') or 'hxops-frontend').strip()
|
||||
return jwt.decode(
|
||||
token,
|
||||
key=secret,
|
||||
algorithms=['HS256'],
|
||||
audience=local_audience,
|
||||
issuer=local_issuer,
|
||||
options={'require': ['exp', 'iat']},
|
||||
)
|
||||
|
||||
keys = _get_jwks_keys(jwks_url)
|
||||
jwk = keys.get(kid)
|
||||
if not jwk:
|
||||
_JWKS_CACHE['expires_at'] = 0.0
|
||||
keys = _get_jwks_keys(jwks_url)
|
||||
jwk = keys.get(kid)
|
||||
if not jwk:
|
||||
raise ValueError('No matching JWKS key for token')
|
||||
|
||||
public_key = None
|
||||
pyjwk = getattr(jwt, 'PyJWK', None)
|
||||
if pyjwk and hasattr(pyjwk, 'from_dict'):
|
||||
public_key = pyjwk.from_dict(jwk).key
|
||||
if public_key is None:
|
||||
rsa_alg = getattr(getattr(jwt, 'algorithms', None), 'RSAAlgorithm', None)
|
||||
if rsa_alg and hasattr(rsa_alg, 'from_jwk'):
|
||||
public_key = rsa_alg.from_jwk(json.dumps(jwk))
|
||||
if public_key is None:
|
||||
get_algs = getattr(getattr(jwt, 'algorithms', None), 'get_default_algorithms', None)
|
||||
if callable(get_algs):
|
||||
rs256 = (get_algs() or {}).get('RS256')
|
||||
if rs256 and hasattr(rs256, 'from_jwk'):
|
||||
public_key = rs256.from_jwk(json.dumps(jwk))
|
||||
if public_key is None:
|
||||
raise ValueError('Cannot build RSA public key from JWK; check installed jwt package')
|
||||
|
||||
return jwt.decode(
|
||||
token,
|
||||
key=public_key,
|
||||
algorithms=['RS256', 'RS384', 'RS512'],
|
||||
audience=audience,
|
||||
issuer=issuer,
|
||||
options={'require': ['exp', 'iat']},
|
||||
)
|
||||
|
||||
|
||||
def _extract_unverified_claims(token: str) -> dict:
|
||||
try:
|
||||
return jwt.decode(
|
||||
token,
|
||||
options={
|
||||
'verify_signature': False,
|
||||
'verify_exp': False,
|
||||
'verify_iat': False,
|
||||
'verify_nbf': False,
|
||||
'verify_aud': False,
|
||||
'verify_iss': False,
|
||||
},
|
||||
) or {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _resolve_user_from_claims(claims: dict) -> Optional[User]:
|
||||
def _lookup() -> Optional[User]:
|
||||
user_id = claims.get('user_id') or claims.get('id')
|
||||
if user_id is not None:
|
||||
try:
|
||||
user = db.session.get(User, int(user_id))
|
||||
if user:
|
||||
return user
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
username = claims.get('preferred_username') or claims.get('username') or claims.get('name')
|
||||
if username:
|
||||
user = db.session.query(User).filter_by(username=str(username)).first()
|
||||
if user:
|
||||
return user
|
||||
|
||||
email = claims.get('email')
|
||||
if email:
|
||||
user = db.session.query(User).filter_by(email=str(email)).first()
|
||||
if user:
|
||||
return user
|
||||
return None
|
||||
|
||||
try:
|
||||
return _lookup()
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning(
|
||||
'[auth_jwt] transient db error when resolving user, retry with reconnect path=%s err=%s',
|
||||
request.path,
|
||||
exc,
|
||||
)
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
db.engine.dispose()
|
||||
except Exception:
|
||||
current_app.logger.warning('[auth_jwt] failed to dispose engine during user reconnect recovery', exc_info=True)
|
||||
return _lookup()
|
||||
|
||||
|
||||
def _legacy_header_user() -> Optional[User]:
|
||||
def _lookup() -> Optional[User]:
|
||||
user_id = request.headers.get('X-User-Id')
|
||||
if user_id:
|
||||
try:
|
||||
user = db.session.get(User, int(user_id))
|
||||
if user:
|
||||
return user
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
username = request.headers.get('X-Username')
|
||||
if username:
|
||||
return db.session.query(User).filter_by(username=username).first()
|
||||
return None
|
||||
|
||||
try:
|
||||
return _lookup()
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning(
|
||||
'[auth_jwt] transient db error when resolving legacy header user, retry with reconnect path=%s err=%s',
|
||||
request.path,
|
||||
exc,
|
||||
)
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
db.engine.dispose()
|
||||
except Exception:
|
||||
current_app.logger.warning('[auth_jwt] failed to dispose engine during legacy user reconnect recovery', exc_info=True)
|
||||
return _lookup()
|
||||
|
||||
|
||||
def _current_user_cache_key() -> tuple[str, str, str, str]:
|
||||
"""构造当前请求用户缓存键,避免测试或保留上下文场景串用上一条请求的用户缓存。"""
|
||||
return (
|
||||
str(request.headers.get('Authorization') or '').strip(),
|
||||
str(request.headers.get('X-User-Id') or '').strip(),
|
||||
str(request.headers.get('X-Username') or '').strip(),
|
||||
f'{request.method}:{request.path}',
|
||||
)
|
||||
|
||||
|
||||
def get_current_user() -> Optional[User]:
|
||||
"""
|
||||
解析当前请求用户:优先 JWT Bearer,其次 legacy header(若配置启用)。
|
||||
Returns:
|
||||
User 实例;未认证时返回 None。
|
||||
"""
|
||||
cache_key = _current_user_cache_key()
|
||||
cached = getattr(g, 'current_user', None)
|
||||
cached_key = getattr(g, 'current_user_cache_key', None)
|
||||
if cached is not None and cached_key == cache_key:
|
||||
return cached
|
||||
|
||||
token = _extract_bearer_token()
|
||||
if token:
|
||||
try:
|
||||
claims = _decode_jwt(token)
|
||||
user = _resolve_user_from_claims(claims)
|
||||
except Exception:
|
||||
# Decode metadata is diagnostic-only: do not emit it for successful requests.
|
||||
try:
|
||||
header = jwt.get_unverified_header(token)
|
||||
except Exception:
|
||||
header = {}
|
||||
unverified = _extract_unverified_claims(token)
|
||||
expected_issuer = (current_app.config.get('AUTH_JWT_ISSUER') or '').strip()
|
||||
expected_audience = (current_app.config.get('AUTH_JWT_AUDIENCE') or '').strip()
|
||||
current_app.logger.error(
|
||||
'[auth_jwt] decode context kid=%s alg=%s token=%s token_iss=%s token_aud=%s '
|
||||
'expected_iss=%s expected_aud=%s path=%s',
|
||||
header.get('kid'),
|
||||
header.get('alg'),
|
||||
_token_brief(token),
|
||||
unverified.get('iss'),
|
||||
unverified.get('aud'),
|
||||
expected_issuer,
|
||||
expected_audience,
|
||||
request.path,
|
||||
)
|
||||
current_app.logger.exception('[auth_jwt] decode failed')
|
||||
user = None
|
||||
claims = None
|
||||
if user:
|
||||
g.jwt_claims = claims
|
||||
g.current_user = user
|
||||
g.current_user_cache_key = cache_key
|
||||
return user
|
||||
|
||||
if bool(current_app.config.get('AUTH_LEGACY_HEADER_ENABLED', True)):
|
||||
user = _legacy_header_user()
|
||||
if user:
|
||||
g.current_user = user
|
||||
g.current_user_cache_key = cache_key
|
||||
return user
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def issue_local_access_token(user: User) -> str:
|
||||
"""签发本地 HS256 JWT(密码登录兼容)。"""
|
||||
now = datetime.now(timezone.utc)
|
||||
exp_hours = int(current_app.config.get('AUTH_LOCAL_JWT_EXPIRES_HOURS') or 12)
|
||||
payload = {
|
||||
'sub': str(user.id),
|
||||
'id': user.id,
|
||||
'user_id': user.id,
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'email': user.email,
|
||||
'iat': int(now.timestamp()),
|
||||
'exp': int((now + timedelta(hours=max(1, exp_hours))).timestamp()),
|
||||
'iss': (current_app.config.get('AUTH_LOCAL_JWT_ISSUER') or 'hxops-backend'),
|
||||
'aud': (current_app.config.get('AUTH_LOCAL_JWT_AUDIENCE') or 'hxops-frontend'),
|
||||
}
|
||||
secret = current_app.config.get('SECRET_KEY')
|
||||
return jwt.encode(payload, secret, algorithm='HS256')
|
||||
@@ -1,6 +1,5 @@
|
||||
"""
|
||||
backend/app/core/config/__init__.py
|
||||
|
||||
用途:应用配置包入口(settings、env_persistence)。
|
||||
逻辑:create_app 加载 Config;before_request 刷新 DB 持久化配置。
|
||||
用途:配置包入口(settings、env_persistence)。
|
||||
"""
|
||||
@@ -1,9 +1,249 @@
|
||||
"""
|
||||
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
|
||||
用途:运行时配置 DB 持久化与 env 镜像(WeCom 等 admin 设置)。
|
||||
依赖:app.extensions.db、app.models.AppSetting。
|
||||
逻辑:before_request 调用 apply_env_settings;persist_env_settings 供 admin 写入。
|
||||
|
||||
__all__ = ['apply_env_settings']
|
||||
Storage strategy:
|
||||
1. Database (app_settings) - canonical
|
||||
2. .env.local (dev only) - secondary mirror
|
||||
3. os.environ - in-process mirror on write
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
from dotenv import dotenv_values, set_key
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
_BACKEND_DIR = Path(__file__).resolve().parents[3]
|
||||
_ROOT_DIR = _BACKEND_DIR.parent
|
||||
ROOT_ENV_LOCAL_PATH = _ROOT_DIR / '.env.local'
|
||||
LEGACY_BACKEND_ENV_PATH = _BACKEND_DIR / '.env'
|
||||
# Backward-compatible alias for tests and older callers that still patch/read
|
||||
# the historical backend/.env location directly.
|
||||
BACKEND_ENV_PATH = LEGACY_BACKEND_ENV_PATH
|
||||
WECOM_BOOL_KEYS = {
|
||||
'WECOM_ENABLED',
|
||||
'WECOM_AUTO_CREATE_USER',
|
||||
'WECOM_MOBILE_NORMALIZE',
|
||||
'WECOM_NOTIFY_ENABLED',
|
||||
'WECOM_FEEDBACK_NOTIFY_ENABLED',
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _ensure_env_file_exists() -> bool:
|
||||
try:
|
||||
ROOT_ENV_LOCAL_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not ROOT_ENV_LOCAL_PATH.exists():
|
||||
ROOT_ENV_LOCAL_PATH.write_text('', encoding='utf-8')
|
||||
return True
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot create %s: %s', ROOT_ENV_LOCAL_PATH, exc)
|
||||
return False
|
||||
|
||||
|
||||
def _normalize_env_name(raw: str | None) -> str:
|
||||
value = (raw or '').strip().lower()
|
||||
if value in ('dev', 'development', ''):
|
||||
return 'dev'
|
||||
if value in ('test', 'testing'):
|
||||
return 'test'
|
||||
if value in ('prod', 'production'):
|
||||
return 'prod'
|
||||
return 'dev'
|
||||
|
||||
|
||||
def _to_env_string(value: object) -> str:
|
||||
if isinstance(value, bool):
|
||||
return 'true' if value else 'false'
|
||||
if value is None:
|
||||
return ''
|
||||
return str(value)
|
||||
|
||||
|
||||
def _parse_env_value(key: str, value: object) -> object:
|
||||
if value is None:
|
||||
return None
|
||||
if key in WECOM_BOOL_KEYS:
|
||||
return str(value).strip().lower() == 'true'
|
||||
return str(value)
|
||||
|
||||
|
||||
def _matches_prefixes(key: str, prefixes: Iterable[str]) -> bool:
|
||||
return any(key.startswith(prefix) for prefix in prefixes)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Database read/write (primary store)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _persist_to_db(values: dict[str, str]) -> bool:
|
||||
"""Write key/value pairs into the ``app_settings`` table.
|
||||
|
||||
Returns True if every value was committed, False otherwise. The function
|
||||
is defensive: it must not raise, because settings persistence is also
|
||||
written to ``.env`` and we don't want to fail the API request.
|
||||
"""
|
||||
if not values:
|
||||
return True
|
||||
try:
|
||||
from app.extensions import db
|
||||
from app.models import AppSetting
|
||||
except Exception as exc: # pragma: no cover - import safety net
|
||||
logger.warning('AppSetting model unavailable: %s', exc)
|
||||
return False
|
||||
|
||||
try:
|
||||
for key, value in values.items():
|
||||
existing = db.session.get(AppSetting, key)
|
||||
if existing is None:
|
||||
db.session.add(AppSetting(key=key, value=value))
|
||||
else:
|
||||
existing.value = value
|
||||
db.session.commit()
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.warning('Failed to persist settings to DB: %s', exc)
|
||||
try:
|
||||
db.session.rollback()
|
||||
except Exception: # pragma: no cover
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _load_from_db(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
try:
|
||||
from app.extensions import db
|
||||
from app.models import AppSetting
|
||||
except Exception as exc: # pragma: no cover
|
||||
logger.debug('AppSetting model unavailable for read: %s', exc)
|
||||
return {}
|
||||
|
||||
try:
|
||||
rows = db.session.query(AppSetting).all()
|
||||
except Exception as exc:
|
||||
# Most common case: the migration has not been applied yet on a
|
||||
# freshly-built container. Degrade gracefully to .env-only mode.
|
||||
logger.debug('app_settings table not readable yet: %s', exc)
|
||||
try:
|
||||
db.session.rollback()
|
||||
except Exception: # pragma: no cover
|
||||
pass
|
||||
return {}
|
||||
|
||||
result: dict[str, str] = {}
|
||||
for row in rows:
|
||||
if row.key and _matches_prefixes(row.key, prefixes):
|
||||
result[row.key] = row.value if row.value is not None else ''
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# .env read/write (secondary store, best-effort)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _persist_to_env_file(values: dict[str, str]) -> bool:
|
||||
env_name = _normalize_env_name(os.getenv('ENV_NAME') or os.getenv('FLASK_ENV'))
|
||||
if env_name != 'dev':
|
||||
return True
|
||||
if not values:
|
||||
return True
|
||||
if not _ensure_env_file_exists():
|
||||
return False
|
||||
ok = True
|
||||
for key, value in values.items():
|
||||
try:
|
||||
set_key(str(ROOT_ENV_LOCAL_PATH), key, value, quote_mode='auto')
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot write %s to %s: %s', key, ROOT_ENV_LOCAL_PATH, exc)
|
||||
ok = False
|
||||
return ok
|
||||
|
||||
|
||||
def _load_from_env_file(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
merged: dict[str, str] = {}
|
||||
for env_path in (BACKEND_ENV_PATH, ROOT_ENV_LOCAL_PATH):
|
||||
if not env_path.exists():
|
||||
continue
|
||||
try:
|
||||
loaded = dotenv_values(env_path)
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot read %s: %s', env_path, exc)
|
||||
continue
|
||||
for key, value in loaded.items():
|
||||
if key and _matches_prefixes(key, prefixes):
|
||||
merged[key] = value if value is not None else ''
|
||||
return merged
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public API
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def persist_env_settings(values: dict[str, object]) -> dict[str, str]:
|
||||
"""Persist settings to the canonical store and mirror to ``os.environ``.
|
||||
|
||||
Order:
|
||||
1. Mirror to ``os.environ`` so the current process picks them up
|
||||
immediately.
|
||||
2. Persist to the database (canonical, survives container rebuilds).
|
||||
3. In dev only, best-effort write to ``.env.local`` so local restarts
|
||||
without DB access keep working.
|
||||
"""
|
||||
if not values:
|
||||
return {}
|
||||
|
||||
persisted: dict[str, str] = {}
|
||||
for key, value in values.items():
|
||||
env_value = _to_env_string(value)
|
||||
os.environ[key] = env_value
|
||||
persisted[key] = env_value
|
||||
|
||||
db_ok = _persist_to_db(persisted)
|
||||
file_ok = _persist_to_env_file(persisted)
|
||||
|
||||
if not db_ok and not file_ok:
|
||||
logger.error(
|
||||
'Failed to persist settings %s to BOTH database and .env.local mirror. '
|
||||
'Settings will be lost when the process restarts.',
|
||||
list(persisted.keys()),
|
||||
)
|
||||
|
||||
return persisted
|
||||
|
||||
|
||||
def apply_env_settings(prefixes: tuple[str, ...] = ('WECOM_',)) -> dict[str, object]:
|
||||
"""Load settings from the canonical store and apply to ``os.environ``.
|
||||
|
||||
DB values take priority over env-file values; both are merged so
|
||||
keys that only live in env files (e.g. fresh deploy before any admin
|
||||
edit) are still honored.
|
||||
"""
|
||||
file_values = _load_from_env_file(prefixes)
|
||||
db_values = _load_from_db(prefixes)
|
||||
|
||||
merged: dict[str, str] = {**file_values, **db_values}
|
||||
|
||||
applied: dict[str, object] = {}
|
||||
for key, raw_value in merged.items():
|
||||
parsed = _parse_env_value(key, raw_value)
|
||||
os.environ[key] = _to_env_string(parsed)
|
||||
applied[key] = parsed
|
||||
return applied
|
||||
@@ -1,9 +1,432 @@
|
||||
"""
|
||||
backend/app/core/config/settings.py
|
||||
|
||||
用途:Config 类与环境映射(Wave 1 自 app/config.py 迁入)。
|
||||
逻辑:create_app(config_name) 通过 config[config_name] 加载。
|
||||
用途:Flask Config 类与环境文件加载(dev/test/prod)。
|
||||
依赖:dotenv、app.path_utils。
|
||||
逻辑:create_app 通过 config[config_name] 加载;旧路径 app.config 为兼容 shim。
|
||||
"""
|
||||
from app.config import ACTIVE_ENV_NAME, config # noqa: F401
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import dotenv_values
|
||||
|
||||
|
||||
_BACKEND_DIR = Path(__file__).resolve().parents[3]
|
||||
_ROOT_DIR = _BACKEND_DIR.parent
|
||||
|
||||
|
||||
def _normalize_env_name(raw: str | None) -> str:
|
||||
value = (raw or '').strip().lower()
|
||||
if value in ('dev', 'development', ''):
|
||||
return 'dev'
|
||||
if value in ('test', 'testing'):
|
||||
return 'test'
|
||||
if value in ('prod', 'production'):
|
||||
return 'prod'
|
||||
return 'dev'
|
||||
|
||||
|
||||
def _load_environment_files() -> str:
|
||||
"""Load env files from project root with stable priority.
|
||||
|
||||
Priority (low -> high):
|
||||
1. .env.shared
|
||||
2. .env.<ENV_NAME>
|
||||
3. .env.local (only for dev)
|
||||
4. system environment variables (always highest, never overridden)
|
||||
"""
|
||||
env_name = _normalize_env_name(os.getenv('ENV_NAME') or os.getenv('FLASK_ENV'))
|
||||
preserved_env = dict(os.environ)
|
||||
merged_values: dict[str, str] = {}
|
||||
|
||||
shared_file = _ROOT_DIR / '.env.shared'
|
||||
if shared_file.exists():
|
||||
merged_values.update({k: v for k, v in dotenv_values(shared_file).items() if v is not None})
|
||||
|
||||
env_file = _ROOT_DIR / f'.env.{env_name}'
|
||||
if env_file.exists():
|
||||
merged_values.update({k: v for k, v in dotenv_values(env_file).items() if v is not None})
|
||||
|
||||
if env_name == 'dev':
|
||||
local_file = _ROOT_DIR / '.env.local'
|
||||
if local_file.exists():
|
||||
merged_values.update({k: v for k, v in dotenv_values(local_file).items() if v is not None})
|
||||
|
||||
for key, value in merged_values.items():
|
||||
if key not in preserved_env:
|
||||
os.environ[key] = value
|
||||
return env_name
|
||||
|
||||
|
||||
ACTIVE_ENV_NAME = _load_environment_files()
|
||||
|
||||
|
||||
def _data_path(env_key: str, *parts: str) -> str:
|
||||
from app.path_utils import resolve_backend_relative_path
|
||||
|
||||
default = _BACKEND_DIR.joinpath("data", *parts)
|
||||
return resolve_backend_relative_path(os.getenv(env_key), default)
|
||||
|
||||
|
||||
def _backend_path(env_key: str, *parts: str) -> str:
|
||||
from app.path_utils import resolve_backend_relative_path
|
||||
|
||||
default = _BACKEND_DIR.joinpath(*parts)
|
||||
return resolve_backend_relative_path(os.getenv(env_key), default)
|
||||
|
||||
|
||||
class Config:
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
SECRET_KEY = os.getenv('SECRET_KEY')
|
||||
# 配置最大上传文件大小(200MB)
|
||||
MAX_CONTENT_LENGTH = 200 * 1024 * 1024
|
||||
KB_STORAGE_ROOT = _data_path('KB_STORAGE_ROOT', 'kb')
|
||||
KB_TASK_EXECUTION_MODE = os.getenv('KB_TASK_EXECUTION_MODE', 'worker').strip().lower()
|
||||
KB_WORKER_POLL_SECONDS = float(os.getenv('KB_WORKER_POLL_SECONDS', '2'))
|
||||
KB_WORKER_CONCURRENCY = int(os.getenv('KB_WORKER_CONCURRENCY', '3') or '3')
|
||||
# kb-worker 自动回收长时间 running 的任务(秒),默认 300,应大于单次清洗预期耗时
|
||||
KB_JOB_RUNNING_TIMEOUT_SECONDS = float(os.getenv('KB_JOB_RUNNING_TIMEOUT_SECONDS', '300'))
|
||||
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免卡住整个 worker 队列
|
||||
EDKB_FILE_TIMEOUT_SEC = int(os.getenv('EDKB_FILE_TIMEOUT_SEC', '0') or '0')
|
||||
# 数据库连接池配置
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {
|
||||
'pool_size': 20,
|
||||
'max_overflow': 10,
|
||||
'pool_recycle': 3600,
|
||||
'pool_pre_ping': True,
|
||||
}
|
||||
PUBLIC_BASE_URL = os.getenv('PUBLIC_BASE_URL')
|
||||
DEFAULT_ADMIN_USERNAME = os.getenv('DEFAULT_ADMIN_USERNAME')
|
||||
DEFAULT_ADMIN_PASSWORD = os.getenv('DEFAULT_ADMIN_PASSWORD')
|
||||
TASK_EXECUTION_MODE = os.getenv('TASK_EXECUTION_MODE', '').strip().lower()
|
||||
# Dify 网关配置
|
||||
DIFY_API_BASE = os.getenv('DIFY_API_BASE')
|
||||
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
|
||||
DIFY_CHAT_CONNECT_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_CONNECT_TIMEOUT_SECONDS', '5'))
|
||||
DIFY_CHAT_READ_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_READ_TIMEOUT_SECONDS', '30'))
|
||||
# Redis 连接配置,默认使用本地 Redis + 密码
|
||||
REDIS_URL = os.getenv('REDIS_URL')
|
||||
FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true'
|
||||
HR_WORKFLOW_IFRAME_URL = os.getenv('HR_WORKFLOW_IFRAME_URL')
|
||||
HR_WORKFLOW_API_BASE = os.getenv('HR_WORKFLOW_API_BASE')
|
||||
HR_WORKFLOW_API_KEY = os.getenv('HR_WORKFLOW_API_KEY')
|
||||
OA_WORKFLOW_WSDL_URL = os.getenv(
|
||||
'OA_WORKFLOW_WSDL_URL',
|
||||
'http://oa.well-trust.com:8888/services/WorkflowService?wsdl',
|
||||
)
|
||||
OA_LEAVE_WORKFLOW_CODE = os.getenv('OA_LEAVE_WORKFLOW_CODE', '879')
|
||||
|
||||
# External integration API (resolve original source file links by Dify IDs)
|
||||
INTEGRATION_API_MODE = os.getenv('INTEGRATION_API_MODE', 'local').strip().lower()
|
||||
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
|
||||
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
|
||||
|
||||
# HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 服务端调用;无尾斜杠,常为内网 IP)
|
||||
HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOLS_API_BASE')
|
||||
|
||||
# HXOPS 浏览器可访问根地址(Excel 签名下载等用户可见链接;无尾斜杠,应为域名)
|
||||
HXOPS_PUBLIC_BASE_URL = os.getenv('HXOPS_PUBLIC_BASE_URL')
|
||||
|
||||
# 货代发货通知 Agent Tool API
|
||||
SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY')
|
||||
|
||||
# 文件检核 Chatflow Tool API
|
||||
FILE_CHECK_TOOL_API_KEY = os.getenv('FILE_CHECK_TOOL_API_KEY')
|
||||
|
||||
# 设备维保助手 Chatflow Tool API
|
||||
MAINTENANCE_TOOL_API_KEY = os.getenv('MAINTENANCE_TOOL_API_KEY')
|
||||
SHIPPING_NOTICE_STORAGE_ROOT = _data_path("SHIPPING_NOTICE_STORAGE_ROOT", "shipping_notice")
|
||||
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD = float(
|
||||
os.getenv('SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD') or '0.7'
|
||||
)
|
||||
# 建单后是否延后 parse_notice,交由 Dify 画布 LLM + Tool 解析(默认 true,符合 Dify 优先原则)
|
||||
SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY = os.getenv('SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY = int(
|
||||
os.getenv('SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY') or '3'
|
||||
)
|
||||
SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS') or '180'
|
||||
)
|
||||
SHIPPING_NOTICE_TASK_EXECUTION_MODE = os.getenv('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker').strip().lower()
|
||||
SHIPPING_NOTICE_WORKER_POLL_SECONDS = float(os.getenv('SHIPPING_NOTICE_WORKER_POLL_SECONDS', '2'))
|
||||
SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float(
|
||||
os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '300')
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW = os.getenv('SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW', 'true')
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED', 'false').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '900'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED = (
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = (
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS', '').strip().lower()
|
||||
in {'1', 'true', 'yes', 'on'}
|
||||
if os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS')
|
||||
else _normalize_env_name(os.getenv('ENV_NAME')) in {'test', 'prod'}
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = (
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK', 'false').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID = os.getenv('SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID', '').strip()
|
||||
SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME = (
|
||||
os.getenv('SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME', '.hxops_rpa_shared_mount').strip()
|
||||
or '.hxops_rpa_shared_mount'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS') or '1800'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES = os.getenv(
|
||||
'SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES', ''
|
||||
).strip()
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN = (
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS') or '120'
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM = os.getenv('SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM', 'false').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_MATCH_ENABLED', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN = os.getenv(
|
||||
'SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN',
|
||||
'shipment_{task_no}_{ts}.xlsx',
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED', 'false').lower() == 'true'
|
||||
# Hxops 工作台 / 聊天按钮兜底串联(Dify 主路径走 auto_progress;画布 HTTP 不传 auto_chain_fallback)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK = os.getenv('SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS') or '3')
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS') or '30'
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS = int(
|
||||
os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000'
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG = _backend_path(
|
||||
'SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG', 'config', 'shipping_inventory_sources.yaml'
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS = int(
|
||||
os.getenv('SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS') or '24'
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE = float(
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE') or '0.8'
|
||||
)
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
|
||||
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
|
||||
FREIGHT_INVENTORY_DROP_DIR = _data_path(
|
||||
"FREIGHT_INVENTORY_DROP_DIR", "shipping_notice", "freight_rpa", "inventory_drop"
|
||||
)
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR = _data_path(
|
||||
"FREIGHT_RPA_INVENTORY_TRIGGER_DIR", "shipping_notice", "freight_rpa", "inventory_triggers"
|
||||
)
|
||||
FREIGHT_UPLOAD_QUEUE_DIR = _data_path(
|
||||
"FREIGHT_UPLOAD_QUEUE_DIR", "shipping_notice", "freight_rpa", "upload_queue"
|
||||
)
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR = _data_path(
|
||||
"FREIGHT_RPA_UPLOAD_TRIGGER_DIR", "shipping_notice", "freight_rpa", "upload_triggers"
|
||||
)
|
||||
FREIGHT_RPA_BROWSER_PROFILE_DIR = _data_path(
|
||||
"FREIGHT_RPA_BROWSER_PROFILE_DIR", "shipping_notice", "freight_rpa", "browser_profile"
|
||||
)
|
||||
FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = _data_path(
|
||||
"FREIGHT_RPA_INVENTORY_ARCHIVE_DIR", "shipping_notice", "freight_rpa", "inventory_archives"
|
||||
)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH = _backend_path(
|
||||
"FREIGHT_SHIPMENT_TEMPLATE_PATH", "templates", "freight_shipment_upload.xlsx"
|
||||
)
|
||||
|
||||
# WeCom (企业微信) 登录配置
|
||||
WECOM_ENABLED = os.getenv('WECOM_ENABLED', 'false').lower() == 'true'
|
||||
WECOM_CORP_ID = os.getenv('WECOM_CORP_ID')
|
||||
WECOM_AGENT_ID = os.getenv('WECOM_AGENT_ID')
|
||||
WECOM_SECRET = os.getenv('WECOM_SECRET')
|
||||
WECOM_REDIRECT_URI = os.getenv('WECOM_REDIRECT_URI')
|
||||
WECOM_AUTO_CREATE_USER = os.getenv('WECOM_AUTO_CREATE_USER', 'true').lower() == 'true'
|
||||
WECOM_MATCH_RULES = os.getenv('WECOM_MATCH_RULES')
|
||||
WECOM_MATCH_OPERATOR = os.getenv('WECOM_MATCH_OPERATOR').upper()
|
||||
WECOM_FIRST_LOGIN_BIND_MODE = os.getenv('WECOM_FIRST_LOGIN_BIND_MODE')
|
||||
WECOM_FIRST_LOGIN_INPUT_FIELDS = os.getenv('WECOM_FIRST_LOGIN_INPUT_FIELDS')
|
||||
WECOM_EMPLOYEE_ID_SOURCE = os.getenv('WECOM_EMPLOYEE_ID_SOURCE')
|
||||
WECOM_MOBILE_NORMALIZE = os.getenv('WECOM_MOBILE_NORMALIZE', 'true').lower() == 'true'
|
||||
WECOM_CALLBACK_TOKEN = os.getenv('WECOM_CALLBACK_TOKEN')
|
||||
WECOM_ENCODING_AES_KEY = os.getenv('WECOM_ENCODING_AES_KEY')
|
||||
WECOM_CALLBACK_URL = os.getenv('WECOM_CALLBACK_URL')
|
||||
WECOM_HOMEPAGE_URL = os.getenv('WECOM_HOMEPAGE_URL')
|
||||
WECOM_TRUSTED_DOMAIN = os.getenv('WECOM_TRUSTED_DOMAIN')
|
||||
# Public HTTPS origin for WeCom console URLs (takes priority over notify base + request host).
|
||||
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
|
||||
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset')
|
||||
WECOM_FEEDBACK_NOTIFY_ENABLED = os.getenv('WECOM_FEEDBACK_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_FEEDBACK_NOTIFY_BASE_URL = os.getenv('WECOM_FEEDBACK_NOTIFY_BASE_URL')
|
||||
WECOM_FEEDBACK_BOT_WEBHOOK = os.getenv('WECOM_FEEDBACK_BOT_WEBHOOK')
|
||||
|
||||
# JWT/Casdoor auth configuration (phase-1 compatible rollout)
|
||||
AUTH_LEGACY_HEADER_ENABLED = os.getenv('AUTH_LEGACY_HEADER_ENABLED', 'true').lower() == 'true'
|
||||
AUTH_JWT_REQUIRED = os.getenv('AUTH_JWT_REQUIRED', 'true').lower() == 'true'
|
||||
AUTH_ALLOW_LOCAL_PASSWORD_LOGIN = os.getenv('AUTH_ALLOW_LOCAL_PASSWORD_LOGIN', 'true').lower() == 'true'
|
||||
# Login mode switch: "casdoor" (default) or "password".
|
||||
# casdoor: login form credentials are sent to Casdoor token endpoint (no redirect page for users).
|
||||
# password: keep legacy local username/password login.
|
||||
AUTH_LOGIN_MODE = os.getenv('AUTH_LOGIN_MODE').strip().lower()
|
||||
AUTH_ALLOW_LOCAL_JWT = os.getenv('AUTH_ALLOW_LOCAL_JWT', 'true').lower() == 'true'
|
||||
# JWT 的签发者(iss)校验值,后端用它确认“这个 token 是谁发的”
|
||||
AUTH_JWT_ISSUER = os.getenv('AUTH_JWT_ISSUER')
|
||||
# JWT 的受众(aud)校验值,后端用它确认“这个 token 是发给哪个应用的”
|
||||
AUTH_JWT_AUDIENCE = os.getenv('AUTH_JWT_AUDIENCE')
|
||||
# 公钥集合地址(JWKS),后端从这里拉公钥来验签 JWT
|
||||
AUTH_JWT_JWKS_URL = os.getenv('AUTH_JWT_JWKS_URL')
|
||||
CASDOOR_BASE_URL = os.getenv('CASDOOR_BASE_URL')
|
||||
CASDOOR_CLIENT_ID = os.getenv('CASDOOR_CLIENT_ID')
|
||||
CASDOOR_CLIENT_SECRET = os.getenv('CASDOOR_CLIENT_SECRET')
|
||||
# Fallback when authorize-url request omits redirect_uri; OAuth flow sends browser origin + /casdoor-callback.
|
||||
# Casdoor Application must whitelist every origin users hit, e.g. IP and domain on port 8881.
|
||||
CASDOOR_REDIRECT_URI = os.getenv('CASDOOR_REDIRECT_URI')
|
||||
CASDOOR_SCOPE = os.getenv('CASDOOR_SCOPE')
|
||||
# Casdoor organization (userOwner) for set-password and other management APIs.
|
||||
CASDOOR_ORGANIZATION = (os.getenv('CASDOOR_ORGANIZATION') or 'organization_HX').strip()
|
||||
# WeCom as Casdoor IdP: provider Name from Casdoor Providers page (used with default_provider=wecom on authorize-url).
|
||||
CASDOOR_WECOM_PROVIDER_HINT = os.getenv('CASDOOR_WECOM_PROVIDER_HINT').strip()
|
||||
CASDOOR_WECOM_SILENT_SIGNIN = os.getenv('CASDOOR_WECOM_SILENT_SIGNIN', 'false').lower() == 'true'
|
||||
AUTH_LOCAL_JWT_ISSUER = os.getenv('AUTH_LOCAL_JWT_ISSUER')
|
||||
AUTH_LOCAL_JWT_AUDIENCE = os.getenv('AUTH_LOCAL_JWT_AUDIENCE')
|
||||
AUTH_LOCAL_JWT_EXPIRES_HOURS = int(os.getenv('AUTH_LOCAL_JWT_EXPIRES_HOURS', '12'))
|
||||
SCHEDULE_WORKER_ENABLED = os.getenv('SCHEDULE_WORKER_ENABLED', 'true').lower() == 'true'
|
||||
# Cron 表达式按此时区解读(如 0 12 * * * 表示该时区 12:00);入库 next_run_at 仍为 UTC。
|
||||
SCHEDULE_TIMEZONE = (os.getenv('SCHEDULE_TIMEZONE') or 'Asia/Shanghai').strip()
|
||||
SRM_SQLSERVER_HOST = os.getenv('SRM_SQLSERVER_HOST', '')
|
||||
SRM_SQLSERVER_PORT = os.getenv('SRM_SQLSERVER_PORT', '1433')
|
||||
SRM_SQLSERVER_DATABASE = os.getenv('SRM_SQLSERVER_DATABASE', '')
|
||||
SRM_SQLSERVER_USERNAME = os.getenv('SRM_SQLSERVER_USERNAME', '')
|
||||
SRM_SQLSERVER_PASSWORD = os.getenv('SRM_SQLSERVER_PASSWORD', '')
|
||||
SRM_SQLSERVER_DRIVER = os.getenv('SRM_SQLSERVER_DRIVER', 'SQL Server')
|
||||
SRM_SQLSERVER_ENCRYPT = os.getenv('SRM_SQLSERVER_ENCRYPT', 'no')
|
||||
SRM_SQLSERVER_TRUST_CERT = os.getenv('SRM_SQLSERVER_TRUST_CERT', 'yes')
|
||||
SRM_SQLSERVER_TIMEOUT = int(os.getenv('SRM_SQLSERVER_TIMEOUT', '15'))
|
||||
SMTP_HOST = os.getenv('SMTP_HOST', '')
|
||||
SMTP_PORT = int(os.getenv('SMTP_PORT', '25'))
|
||||
SMTP_USER = os.getenv('SMTP_USER', '')
|
||||
SMTP_PASSWORD = os.getenv('SMTP_PASSWORD', '')
|
||||
SMTP_FROM = os.getenv('SMTP_FROM', '')
|
||||
SMTP_USE_TLS = os.getenv('SMTP_USE_TLS', 'true').lower() == 'true'
|
||||
INTERNAL_API_BASE_URL = os.getenv('INTERNAL_API_BASE_URL', 'http://127.0.0.1:5052')
|
||||
FIXED_ASSETS_SYNC_ENABLED = os.getenv('FIXED_ASSETS_SYNC_ENABLED', 'true').lower() == 'true'
|
||||
FIXED_ASSETS_SYNC_TIMEZONE = (os.getenv('FIXED_ASSETS_SYNC_TIMEZONE') or 'Asia/Shanghai').strip()
|
||||
FIXED_ASSETS_SYNC_HOUR = int(os.getenv('FIXED_ASSETS_SYNC_HOUR', '3') or '3')
|
||||
FIXED_ASSETS_SYNC_MINUTE = int(os.getenv('FIXED_ASSETS_SYNC_MINUTE', '0') or '0')
|
||||
FIXED_ASSETS_SYNC_TIMEOUT_SECONDS = int(os.getenv('FIXED_ASSETS_SYNC_TIMEOUT_SECONDS', '600') or '600')
|
||||
FIXED_ASSETS_SYNC_RETRY_INTERVAL_MINUTES = int(
|
||||
os.getenv('FIXED_ASSETS_SYNC_RETRY_INTERVAL_MINUTES', '30') or '30'
|
||||
)
|
||||
FIXED_ASSETS_SYNC_MAX_ATTEMPTS = int(os.getenv('FIXED_ASSETS_SYNC_MAX_ATTEMPTS', '4') or '4')
|
||||
FIXED_ASSETS_SYNC_POLL_SECONDS = int(os.getenv('FIXED_ASSETS_SYNC_POLL_SECONDS', '60') or '60')
|
||||
FIXED_ASSETS_SYNC_ON_BOOT_IF_MISSING = (
|
||||
os.getenv('FIXED_ASSETS_SYNC_ON_BOOT_IF_MISSING', 'true').lower() == 'true'
|
||||
)
|
||||
FIXED_ASSETS_HISTORY_KEEP_COUNT = int(os.getenv('FIXED_ASSETS_HISTORY_KEEP_COUNT', '3') or '3')
|
||||
FIXED_ASSETS_STORAGE_ROOT = _data_path('FIXED_ASSETS_STORAGE_ROOT', 'fixed_assets')
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT = os.getenv('FIXED_ASSET_HISTORY_SHARE_ROOT', '').strip()
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT = os.getenv('FIXED_ASSET_HISTORY_LOCAL_ROOT', '').strip()
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME = os.getenv('FIXED_ASSET_HISTORY_SHARE_USERNAME', '').strip()
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD = os.getenv('FIXED_ASSET_HISTORY_SHARE_PASSWORD', '')
|
||||
FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS = int(os.getenv('FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS', '20') or '20')
|
||||
FIXED_ASSET_IMAGE_BASE_URL = os.getenv('FIXED_ASSET_IMAGE_BASE_URL', '').strip()
|
||||
FIXED_ASSET_IMAGE_USERNAME = os.getenv('FIXED_ASSET_IMAGE_USERNAME', '').strip()
|
||||
FIXED_ASSET_IMAGE_PASSWORD = os.getenv('FIXED_ASSET_IMAGE_PASSWORD', '')
|
||||
FIXED_ASSET_IMAGE_LIBRARY_ID = os.getenv('FIXED_ASSET_IMAGE_LIBRARY_ID', '').strip()
|
||||
FIXED_ASSET_IMAGE_FOLDER_ID = os.getenv('FIXED_ASSET_IMAGE_FOLDER_ID', '').strip()
|
||||
FIXED_ASSETS_DOCS_EXPORT_ROOT = os.getenv(
|
||||
'FIXED_ASSETS_DOCS_EXPORT_ROOT',
|
||||
str(_ROOT_DIR / 'docs'),
|
||||
)
|
||||
FIXED_ASSETS_EXPORT_TO_DOCS = os.getenv('FIXED_ASSETS_EXPORT_TO_DOCS', 'true').lower() == 'true'
|
||||
FIXED_ASSETS_ERP_USERNAME = os.getenv('FIXED_ASSETS_ERP_USERNAME', 'EXT_VIEW_USER')
|
||||
FIXED_ASSETS_ERP_PASSWORD = os.getenv('FIXED_ASSETS_ERP_PASSWORD', 'extviewuser')
|
||||
FIXED_ASSETS_ERP_DSN = os.getenv('FIXED_ASSETS_ERP_DSN') or os.getenv('ERP_DB_DSN', '192.168.8.24:1521/topprod')
|
||||
|
||||
# MinIO 配置
|
||||
MINIO_ENDPOINT = os.getenv('MINIO_ENDPOINT', '127.0.0.1:9000')
|
||||
MINIO_ACCESS_KEY = os.getenv('MINIO_ACCESS_KEY', 'minioadmin')
|
||||
MINIO_SECRET_KEY = os.getenv('MINIO_SECRET_KEY', 'minioadmin')
|
||||
MINIO_SECURE = os.getenv('MINIO_SECURE', 'false').lower() == 'true'
|
||||
MINIO_AGENT_GUIDES_BUCKET = os.getenv('MINIO_AGENT_GUIDES_BUCKET', 'agent-guides')
|
||||
MINIO_PUBLIC_BASE_URL = os.getenv('MINIO_PUBLIC_BASE_URL', 'http://127.0.0.1:9000')
|
||||
MINIO_FILE_ASSETS_BUCKET = os.getenv('MINIO_FILE_ASSETS_BUCKET', 'hxops-file-assets')
|
||||
FILE_ASSET_MAX_SIZE_MB = int(os.getenv('FILE_ASSET_MAX_SIZE_MB', '30'))
|
||||
FILE_ASSET_TEMP_TTL_HOURS = int(os.getenv('FILE_ASSET_TEMP_TTL_HOURS', '72'))
|
||||
FILE_ASSET_DOWNLOAD_URL_TTL_SECONDS = int(os.getenv('FILE_ASSET_DOWNLOAD_URL_TTL_SECONDS', '300'))
|
||||
SHIPPING_NOTICE_INTAKE_TTL_HOURS = int(os.getenv('SHIPPING_NOTICE_INTAKE_TTL_HOURS', '72'))
|
||||
SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS', '3'))
|
||||
SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', '300')
|
||||
)
|
||||
SHIPPING_NOTICE_PARSER_VERSION = os.getenv('SHIPPING_NOTICE_PARSER_VERSION', 'v6')
|
||||
# EML 附件提取安全上限(阶段一对齐:只抽取文本,不执行宏/脚本)
|
||||
# parser v6:阶段二附件派生 FileAsset + Document/Candidate;相对 v5 须强制重解析
|
||||
# parser v5:mixed 保留独立 HTML 段 + 附件型 alternative 可提取正文
|
||||
SHIPPING_NOTICE_EML_MAX_ATTACHMENTS = int(os.getenv('SHIPPING_NOTICE_EML_MAX_ATTACHMENTS', '20'))
|
||||
SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES = int(
|
||||
os.getenv('SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES', str(20 * 1024 * 1024))
|
||||
)
|
||||
SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES = int(
|
||||
os.getenv('SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES', str(50 * 1024 * 1024))
|
||||
)
|
||||
SHIPPING_NOTICE_EML_MAX_NESTING_DEPTH = int(os.getenv('SHIPPING_NOTICE_EML_MAX_NESTING_DEPTH', '3'))
|
||||
# EML 全部附件 extracted_text 写入 structured_result_json 的合计字符上限
|
||||
SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS = int(
|
||||
os.getenv('SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS', str(500_000))
|
||||
)
|
||||
|
||||
|
||||
class DevelopmentConfig(Config):
|
||||
DEBUG = True
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
|
||||
|
||||
|
||||
class ProductionConfig(Config):
|
||||
DEBUG = False
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
|
||||
|
||||
|
||||
class TestingConfig(Config):
|
||||
TESTING = True
|
||||
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
|
||||
WTF_CSRF_ENABLED = False
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {}
|
||||
SCHEDULE_WORKER_ENABLED = False
|
||||
FIXED_ASSETS_SYNC_ENABLED = False
|
||||
FIXED_ASSETS_EXPORT_TO_DOCS = False
|
||||
ENV_NAME = 'dev'
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
|
||||
|
||||
|
||||
config = {
|
||||
'dev': DevelopmentConfig,
|
||||
'development': DevelopmentConfig,
|
||||
'test': TestingConfig,
|
||||
'testing': TestingConfig, # alias for create_app('testing') in pytest
|
||||
'prod': ProductionConfig,
|
||||
'production': ProductionConfig,
|
||||
'default': DevelopmentConfig,
|
||||
}
|
||||
|
||||
__all__ = ['config', 'ACTIVE_ENV_NAME']
|
||||
@@ -1,9 +1,95 @@
|
||||
"""
|
||||
backend/app/core/decorators.py
|
||||
|
||||
用途:路由权限装饰器(Wave 1 自 app/decorators.py 迁入)。
|
||||
逻辑:api 层路由使用 @require_admin、@require_agent_permission。
|
||||
用途:API 路由权限装饰器(admin、agent 权限)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、app.models。
|
||||
逻辑:api 路由使用 @require_admin、@require_agent_permission。
|
||||
"""
|
||||
from app.decorators import require_admin, require_agent_permission # noqa: F401
|
||||
|
||||
__all__ = ['require_admin', 'require_agent_permission']
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import wraps
|
||||
|
||||
from flask import current_app, g, request
|
||||
|
||||
from app.core.auth.jwt import get_current_user as _auth_current_user
|
||||
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.models import Agent, User
|
||||
|
||||
|
||||
def _get_current_user() -> User:
|
||||
"""通过 JWT / legacy header 解析当前用户并写入 g.current_user。"""
|
||||
user = _auth_current_user()
|
||||
if user:
|
||||
g.current_user = user
|
||||
return user
|
||||
|
||||
|
||||
def _resolve_request_agent_id() -> str | None:
|
||||
"""
|
||||
从 JSON body、query 或 multipart form 解析 agent_id。
|
||||
|
||||
核心逻辑:Chat Turn 附件上传走 multipart/form-data,agent_id 在 form 字段而非 JSON body。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
return (
|
||||
data.get("agent_id")
|
||||
or data.get("agentId")
|
||||
or request.args.get("agent_id")
|
||||
or request.args.get("agentId")
|
||||
or request.form.get("agent_id")
|
||||
or request.form.get("agentId")
|
||||
)
|
||||
|
||||
|
||||
def require_agent_permission(f):
|
||||
"""
|
||||
装饰器:校验当前用户是否拥有指定 Agent 访问权限。
|
||||
核心逻辑:从 body/query/form 读 agent_id → 获取用户 → admin 放行或检查 user.agents。
|
||||
Args:
|
||||
f: 被装饰的视图函数。
|
||||
Returns:
|
||||
包装后的视图函数。
|
||||
"""
|
||||
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
agent_id = _resolve_request_agent_id()
|
||||
if not agent_id:
|
||||
raise ValidationError('agent_id is required')
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
agent = Agent.query.get(agent_id)
|
||||
if not agent:
|
||||
raise NotFoundError('Agent not found')
|
||||
g.current_agent = agent
|
||||
if user.role == 'admin':
|
||||
return f(*args, **kwargs)
|
||||
if agent not in user.agents:
|
||||
raise ForbiddenError('Permission denied for this agent')
|
||||
return f(*args, **kwargs)
|
||||
|
||||
return decorated_function
|
||||
|
||||
|
||||
def require_admin(f):
|
||||
"""
|
||||
装饰器:限制仅 admin 角色可访问。
|
||||
核心逻辑:解析用户 → 校验 role == admin;JWT 必填时检查 Authorization 头。
|
||||
"""
|
||||
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
if bool(current_app.config.get('AUTH_JWT_REQUIRED', False)) and (not request.headers.get('Authorization')):
|
||||
raise UnauthorizedError('JWT token is required')
|
||||
if user.role != 'admin':
|
||||
raise ForbiddenError('Admin privilege required')
|
||||
return f(*args, **kwargs)
|
||||
|
||||
return decorated_function
|
||||
+149
-20
@@ -1,26 +1,155 @@
|
||||
"""
|
||||
backend/app/core/errors.py
|
||||
|
||||
用途:统一业务异常类型(Wave 1 自 app/errors.py 迁入)。
|
||||
用途:定义后端统一业务异常类型,供全局异常处理器识别并输出标准错误响应。
|
||||
依赖:无 Flask 依赖。
|
||||
逻辑:API 全局 handler 识别 AppError;业务层 raise 子类替代 jsonify(error)。
|
||||
逻辑:业务层 raise AppError 子类;create_app 注册全局 handler。
|
||||
"""
|
||||
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',
|
||||
]
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class AppError(Exception):
|
||||
code: str
|
||||
message: str
|
||||
http_status: int = 400
|
||||
details: dict[str, Any] = field(default_factory=dict)
|
||||
retryable: bool = False
|
||||
|
||||
|
||||
class ValidationError(AppError):
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Invalid request parameters",
|
||||
*,
|
||||
code: str = "VALIDATION.INVALID_PARAM",
|
||||
details: dict[str, Any] | None = None,
|
||||
):
|
||||
super().__init__(
|
||||
code=code,
|
||||
message=message,
|
||||
http_status=400,
|
||||
details=details or {},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
class UnauthorizedError(AppError):
|
||||
def __init__(self, message: str = "Unauthorized"):
|
||||
super().__init__(code="AUTH.UNAUTHORIZED", message=message, http_status=401, retryable=False)
|
||||
|
||||
|
||||
class ForbiddenError(AppError):
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Forbidden",
|
||||
*,
|
||||
code: str = "AUTH.FORBIDDEN",
|
||||
):
|
||||
super().__init__(code=code, message=message, http_status=403, retryable=False)
|
||||
|
||||
|
||||
class NotFoundError(AppError):
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Resource not found",
|
||||
*,
|
||||
code: str = "RESOURCE.NOT_FOUND",
|
||||
):
|
||||
super().__init__(code=code, message=message, http_status=404, retryable=False)
|
||||
|
||||
|
||||
class ConflictError(AppError):
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Resource conflict",
|
||||
*,
|
||||
code: str = "RESOURCE.CONFLICT",
|
||||
details: dict[str, Any] | None = None,
|
||||
):
|
||||
super().__init__(
|
||||
code=code,
|
||||
message=message,
|
||||
http_status=409,
|
||||
details=details or {},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
class ServiceUnavailableError(AppError):
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Service unavailable",
|
||||
*,
|
||||
code: str = "SYSTEM.SERVICE_UNAVAILABLE",
|
||||
details: dict[str, Any] | None = None,
|
||||
):
|
||||
super().__init__(code=code, message=message, http_status=503, details=details or {}, retryable=True)
|
||||
|
||||
|
||||
class AgentHandlerNotConfiguredError(AppError):
|
||||
"""Catalog 声明 runtime_handler 但 HANDLER_REGISTRY 未注册实现。"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Agent handler is not configured",
|
||||
*,
|
||||
agent_code: str | None = None,
|
||||
handler_key: str | None = None,
|
||||
runtime_provider: str | None = None,
|
||||
details: dict[str, Any] | None = None,
|
||||
):
|
||||
merged_details = dict(details or {})
|
||||
if agent_code:
|
||||
merged_details.setdefault('agent_code', agent_code)
|
||||
if handler_key:
|
||||
merged_details.setdefault('handler_key', handler_key)
|
||||
if runtime_provider:
|
||||
merged_details.setdefault('runtime_provider', runtime_provider)
|
||||
super().__init__(
|
||||
code='AGENT.HANDLER_NOT_CONFIGURED',
|
||||
message=message,
|
||||
http_status=501,
|
||||
details=merged_details,
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
def raise_for_status(message: str, status: int, *, code: str | None = None, details: dict[str, Any] | None = None) -> None:
|
||||
"""
|
||||
按 HTTP 状态码映射并抛出对应 AppError 子类。
|
||||
Args:
|
||||
message: 错误文案。
|
||||
status: HTTP 状态码。
|
||||
code: 可选业务错误码。
|
||||
details: 可选详情 dict。
|
||||
Raises:
|
||||
AppError 或其子类。
|
||||
"""
|
||||
if status == 401:
|
||||
raise UnauthorizedError(message)
|
||||
if status == 403:
|
||||
raise ForbiddenError(message)
|
||||
if status == 404:
|
||||
raise NotFoundError(message)
|
||||
if status == 409:
|
||||
raise ConflictError(message, code=code or "RESOURCE.CONFLICT", details=details)
|
||||
if status == 503:
|
||||
raise ServiceUnavailableError(message, code=code or "SYSTEM.SERVICE_UNAVAILABLE")
|
||||
if status >= 500:
|
||||
raise AppError(
|
||||
code=code or "SYSTEM.INTERNAL_ERROR",
|
||||
message=message,
|
||||
http_status=status,
|
||||
details=details or {},
|
||||
)
|
||||
raise AppError(
|
||||
code=code or "VALIDATION.INVALID_PARAM",
|
||||
message=message,
|
||||
http_status=status,
|
||||
details=details or {},
|
||||
)
|
||||
@@ -1,9 +1,88 @@
|
||||
"""
|
||||
backend/app/core/response.py
|
||||
|
||||
用途:统一 API 响应工具(Wave 1 自 app/response_utils.py 迁入)。
|
||||
逻辑:error_payload 供全局异常 handler 使用;ok() 供成功 envelope(可选)。
|
||||
用途:统一 API 响应结构工具(成功 envelope 与错误 payload)。
|
||||
依赖:flask.jsonify(仅 ok() 使用)。
|
||||
逻辑:create_app 异常 handler 使用 error_payload;可选 ENABLE_API_ENVELOPE 包装成功响应。
|
||||
"""
|
||||
from app.response_utils import error_payload, ok, utc_iso_now # noqa: F401
|
||||
|
||||
__all__ = ['error_payload', 'ok', 'utc_iso_now']
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from flask import jsonify
|
||||
|
||||
|
||||
def utc_iso_now() -> str:
|
||||
"""返回当前 UTC 时间的 ISO8601 字符串(Z 后缀)。"""
|
||||
return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
def utc_iso(dt: datetime | None) -> str | None:
|
||||
"""
|
||||
将 naive UTC datetime 序列化为带 Z 后缀的 ISO 字符串。
|
||||
Args:
|
||||
dt: datetime 或 None。
|
||||
Returns:
|
||||
ISO 字符串或 None。
|
||||
"""
|
||||
if dt is None:
|
||||
return None
|
||||
if dt.tzinfo is not None:
|
||||
return dt.astimezone(timezone.utc).replace(tzinfo=None).isoformat() + "Z"
|
||||
return dt.isoformat() + "Z"
|
||||
|
||||
|
||||
def ok(data: Any, *, request_id: str | None = None, status: int = 200):
|
||||
"""
|
||||
构造 success=true 的标准 JSON 响应。
|
||||
Args:
|
||||
data: 业务数据。
|
||||
request_id: 可选请求追踪 id。
|
||||
status: HTTP 状态码。
|
||||
Returns:
|
||||
(jsonify Response, status) 元组。
|
||||
"""
|
||||
payload: dict[str, Any] = {
|
||||
"success": True,
|
||||
"data": data,
|
||||
"timestamp": utc_iso_now(),
|
||||
}
|
||||
if request_id:
|
||||
payload["request_id"] = request_id
|
||||
return jsonify(payload), status
|
||||
|
||||
|
||||
def error_payload(
|
||||
*,
|
||||
code: str,
|
||||
message: str,
|
||||
request_id: str | None = None,
|
||||
details: dict[str, Any] | None = None,
|
||||
retryable: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构造 success=false 的错误响应体 dict(供 jsonify 使用)。
|
||||
Args:
|
||||
code: 业务错误码。
|
||||
message: 用户可见文案。
|
||||
request_id: 可选请求 id。
|
||||
details: 可选详情。
|
||||
retryable: 是否可重试。
|
||||
Returns:
|
||||
可 jsonify 的 dict。
|
||||
"""
|
||||
payload: dict[str, Any] = {
|
||||
"success": False,
|
||||
"error": {
|
||||
"code": code,
|
||||
"message": message,
|
||||
"details": details or {},
|
||||
"retryable": retryable,
|
||||
},
|
||||
"timestamp": utc_iso_now(),
|
||||
}
|
||||
if request_id:
|
||||
payload["request_id"] = request_id
|
||||
return payload
|
||||
@@ -1,72 +0,0 @@
|
||||
"""
|
||||
backend/app/decorators.py
|
||||
文件用途:权限控制装饰器集合
|
||||
引用文件:flask, functools, models, db
|
||||
逻辑关系:为需要鉴权的 API 提供统一的用户获取、权限校验入口
|
||||
"""
|
||||
from functools import wraps
|
||||
from flask import request, jsonify, g, current_app
|
||||
from app.models import Agent, User
|
||||
from app.auth_jwt import get_current_user as _auth_current_user
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
|
||||
def _get_current_user() -> User:
|
||||
"""Resolve current user via JWT auth flow (legacy headers optional via config)."""
|
||||
user = _auth_current_user()
|
||||
if user:
|
||||
g.current_user = user
|
||||
return user
|
||||
|
||||
def require_agent_permission(f):
|
||||
"""
|
||||
装饰器:检查当前用户是否有指定 Agent 的访问权限
|
||||
核心逻辑:
|
||||
1. 从请求体中读取 agent_id
|
||||
2. 获取当前用户 (临时固定为 ID=1)
|
||||
3. 如果用户是 admin,则放行
|
||||
4. 否则检查 user.agents 是否包含该 agent
|
||||
传入参数:
|
||||
f: 被装饰的视图函数
|
||||
返回值:
|
||||
包装后的视图函数
|
||||
"""
|
||||
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
data = request.get_json(silent=True) or {}
|
||||
agent_id = data.get('agent_id') or request.args.get('agent_id')
|
||||
if not agent_id:
|
||||
raise ValidationError('agent_id is required')
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
agent = Agent.query.get(agent_id)
|
||||
if not agent:
|
||||
raise NotFoundError('Agent not found')
|
||||
g.current_agent = agent
|
||||
if user.role == 'admin':
|
||||
return f(*args, **kwargs)
|
||||
if agent not in user.agents:
|
||||
raise ForbiddenError('Permission denied for this agent')
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
|
||||
def require_admin(f):
|
||||
"""
|
||||
装饰器:限制只有管理员角色才能访问的接口
|
||||
核心逻辑:
|
||||
1. 获取当前用户
|
||||
2. 判断 user.role 是否为 'admin'
|
||||
"""
|
||||
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
if bool(current_app.config.get('AUTH_JWT_REQUIRED', False)) and (not request.headers.get('Authorization')):
|
||||
raise UnauthorizedError('JWT token is required')
|
||||
if user.role != 'admin':
|
||||
raise ForbiddenError('Admin privilege required')
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
@@ -1,255 +0,0 @@
|
||||
"""Persistent storage for runtime-editable application settings.
|
||||
|
||||
Settings managed from the admin console (e.g. WeCom configuration) need to
|
||||
survive process restarts AND container/image rebuilds in production. Writing
|
||||
only to ``backend/.env`` is not enough on Docker deployments because the
|
||||
container's writable layer is discarded on every ``docker compose up --build``.
|
||||
|
||||
Storage strategy:
|
||||
|
||||
1. Database (``app_settings`` table) - canonical, always authoritative.
|
||||
2. ``.env.local`` (dev only) - best-effort secondary write so local/dev
|
||||
workflows that restart without DB access still see updates.
|
||||
3. ``os.environ`` - mirrored on write so legacy ``os.getenv`` consumers stay
|
||||
in sync within the running process.
|
||||
|
||||
On read we merge env files (lowest priority) over DB (highest priority); the DB
|
||||
value wins whenever it exists.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
from dotenv import dotenv_values, set_key
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
_BACKEND_DIR = Path(__file__).resolve().parents[1]
|
||||
_ROOT_DIR = _BACKEND_DIR.parent
|
||||
ROOT_ENV_LOCAL_PATH = _ROOT_DIR / '.env.local'
|
||||
LEGACY_BACKEND_ENV_PATH = _BACKEND_DIR / '.env'
|
||||
# Backward-compatible alias for tests and older callers that still patch/read
|
||||
# the historical backend/.env location directly.
|
||||
BACKEND_ENV_PATH = LEGACY_BACKEND_ENV_PATH
|
||||
WECOM_BOOL_KEYS = {
|
||||
'WECOM_ENABLED',
|
||||
'WECOM_AUTO_CREATE_USER',
|
||||
'WECOM_MOBILE_NORMALIZE',
|
||||
'WECOM_NOTIFY_ENABLED',
|
||||
'WECOM_FEEDBACK_NOTIFY_ENABLED',
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _ensure_env_file_exists() -> bool:
|
||||
try:
|
||||
ROOT_ENV_LOCAL_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not ROOT_ENV_LOCAL_PATH.exists():
|
||||
ROOT_ENV_LOCAL_PATH.write_text('', encoding='utf-8')
|
||||
return True
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot create %s: %s', ROOT_ENV_LOCAL_PATH, exc)
|
||||
return False
|
||||
|
||||
|
||||
def _normalize_env_name(raw: str | None) -> str:
|
||||
value = (raw or '').strip().lower()
|
||||
if value in ('dev', 'development', ''):
|
||||
return 'dev'
|
||||
if value in ('test', 'testing'):
|
||||
return 'test'
|
||||
if value in ('prod', 'production'):
|
||||
return 'prod'
|
||||
return 'dev'
|
||||
|
||||
|
||||
def _to_env_string(value: object) -> str:
|
||||
if isinstance(value, bool):
|
||||
return 'true' if value else 'false'
|
||||
if value is None:
|
||||
return ''
|
||||
return str(value)
|
||||
|
||||
|
||||
def _parse_env_value(key: str, value: object) -> object:
|
||||
if value is None:
|
||||
return None
|
||||
if key in WECOM_BOOL_KEYS:
|
||||
return str(value).strip().lower() == 'true'
|
||||
return str(value)
|
||||
|
||||
|
||||
def _matches_prefixes(key: str, prefixes: Iterable[str]) -> bool:
|
||||
return any(key.startswith(prefix) for prefix in prefixes)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Database read/write (primary store)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _persist_to_db(values: dict[str, str]) -> bool:
|
||||
"""Write key/value pairs into the ``app_settings`` table.
|
||||
|
||||
Returns True if every value was committed, False otherwise. The function
|
||||
is defensive: it must not raise, because settings persistence is also
|
||||
written to ``.env`` and we don't want to fail the API request.
|
||||
"""
|
||||
if not values:
|
||||
return True
|
||||
try:
|
||||
from app import db
|
||||
from app.models import AppSetting
|
||||
except Exception as exc: # pragma: no cover - import safety net
|
||||
logger.warning('AppSetting model unavailable: %s', exc)
|
||||
return False
|
||||
|
||||
try:
|
||||
for key, value in values.items():
|
||||
existing = db.session.get(AppSetting, key)
|
||||
if existing is None:
|
||||
db.session.add(AppSetting(key=key, value=value))
|
||||
else:
|
||||
existing.value = value
|
||||
db.session.commit()
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.warning('Failed to persist settings to DB: %s', exc)
|
||||
try:
|
||||
db.session.rollback()
|
||||
except Exception: # pragma: no cover
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _load_from_db(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
try:
|
||||
from app import db
|
||||
from app.models import AppSetting
|
||||
except Exception as exc: # pragma: no cover
|
||||
logger.debug('AppSetting model unavailable for read: %s', exc)
|
||||
return {}
|
||||
|
||||
try:
|
||||
rows = db.session.query(AppSetting).all()
|
||||
except Exception as exc:
|
||||
# Most common case: the migration has not been applied yet on a
|
||||
# freshly-built container. Degrade gracefully to .env-only mode.
|
||||
logger.debug('app_settings table not readable yet: %s', exc)
|
||||
try:
|
||||
db.session.rollback()
|
||||
except Exception: # pragma: no cover
|
||||
pass
|
||||
return {}
|
||||
|
||||
result: dict[str, str] = {}
|
||||
for row in rows:
|
||||
if row.key and _matches_prefixes(row.key, prefixes):
|
||||
result[row.key] = row.value if row.value is not None else ''
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# .env read/write (secondary store, best-effort)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _persist_to_env_file(values: dict[str, str]) -> bool:
|
||||
env_name = _normalize_env_name(os.getenv('ENV_NAME') or os.getenv('FLASK_ENV'))
|
||||
if env_name != 'dev':
|
||||
return True
|
||||
if not values:
|
||||
return True
|
||||
if not _ensure_env_file_exists():
|
||||
return False
|
||||
ok = True
|
||||
for key, value in values.items():
|
||||
try:
|
||||
set_key(str(ROOT_ENV_LOCAL_PATH), key, value, quote_mode='auto')
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot write %s to %s: %s', key, ROOT_ENV_LOCAL_PATH, exc)
|
||||
ok = False
|
||||
return ok
|
||||
|
||||
|
||||
def _load_from_env_file(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
merged: dict[str, str] = {}
|
||||
for env_path in (BACKEND_ENV_PATH, ROOT_ENV_LOCAL_PATH):
|
||||
if not env_path.exists():
|
||||
continue
|
||||
try:
|
||||
loaded = dotenv_values(env_path)
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot read %s: %s', env_path, exc)
|
||||
continue
|
||||
for key, value in loaded.items():
|
||||
if key and _matches_prefixes(key, prefixes):
|
||||
merged[key] = value if value is not None else ''
|
||||
return merged
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public API
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def persist_env_settings(values: dict[str, object]) -> dict[str, str]:
|
||||
"""Persist settings to the canonical store and mirror to ``os.environ``.
|
||||
|
||||
Order:
|
||||
1. Mirror to ``os.environ`` so the current process picks them up
|
||||
immediately.
|
||||
2. Persist to the database (canonical, survives container rebuilds).
|
||||
3. In dev only, best-effort write to ``.env.local`` so local restarts
|
||||
without DB access keep working.
|
||||
"""
|
||||
if not values:
|
||||
return {}
|
||||
|
||||
persisted: dict[str, str] = {}
|
||||
for key, value in values.items():
|
||||
env_value = _to_env_string(value)
|
||||
os.environ[key] = env_value
|
||||
persisted[key] = env_value
|
||||
|
||||
db_ok = _persist_to_db(persisted)
|
||||
file_ok = _persist_to_env_file(persisted)
|
||||
|
||||
if not db_ok and not file_ok:
|
||||
logger.error(
|
||||
'Failed to persist settings %s to BOTH database and .env.local mirror. '
|
||||
'Settings will be lost when the process restarts.',
|
||||
list(persisted.keys()),
|
||||
)
|
||||
|
||||
return persisted
|
||||
|
||||
|
||||
def apply_env_settings(prefixes: tuple[str, ...] = ('WECOM_',)) -> dict[str, object]:
|
||||
"""Load settings from the canonical store and apply to ``os.environ``.
|
||||
|
||||
DB values take priority over env-file values; both are merged so
|
||||
keys that only live in env files (e.g. fresh deploy before any admin
|
||||
edit) are still honored.
|
||||
"""
|
||||
file_values = _load_from_env_file(prefixes)
|
||||
db_values = _load_from_db(prefixes)
|
||||
|
||||
merged: dict[str, str] = {**file_values, **db_values}
|
||||
|
||||
applied: dict[str, object] = {}
|
||||
for key, raw_value in merged.items():
|
||||
parsed = _parse_env_value(key, raw_value)
|
||||
os.environ[key] = _to_env_string(parsed)
|
||||
applied[key] = parsed
|
||||
return applied
|
||||
@@ -1,96 +0,0 @@
|
||||
"""
|
||||
backend/app/errors.py
|
||||
用途:定义后端统一业务异常类型,供全局异常处理器识别并输出标准错误响应。
|
||||
说明:
|
||||
1. AppError 作为基础异常,包含 code/message/http_status/details/retryable。
|
||||
2. 各子类用于表达常见语义(参数错误、未授权、无权限、资源不存在)。
|
||||
3. 业务层可直接 raise 这些异常,避免到处手写 jsonify(error)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class AppError(Exception):
|
||||
code: str
|
||||
message: str
|
||||
http_status: int = 400
|
||||
details: dict[str, Any] = field(default_factory=dict)
|
||||
retryable: bool = False
|
||||
|
||||
|
||||
class ValidationError(AppError):
|
||||
def __init__(self, message: str = "Invalid request parameters", *, details: dict[str, Any] | None = None):
|
||||
super().__init__(
|
||||
code="VALIDATION.INVALID_PARAM",
|
||||
message=message,
|
||||
http_status=400,
|
||||
details=details or {},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
class UnauthorizedError(AppError):
|
||||
def __init__(self, message: str = "Unauthorized"):
|
||||
super().__init__(code="AUTH.UNAUTHORIZED", message=message, http_status=401, retryable=False)
|
||||
|
||||
|
||||
class ForbiddenError(AppError):
|
||||
def __init__(self, message: str = "Forbidden"):
|
||||
super().__init__(code="AUTH.FORBIDDEN", message=message, http_status=403, retryable=False)
|
||||
|
||||
|
||||
class NotFoundError(AppError):
|
||||
def __init__(self, message: str = "Resource not found"):
|
||||
super().__init__(code="RESOURCE.NOT_FOUND", message=message, http_status=404, retryable=False)
|
||||
|
||||
|
||||
class ConflictError(AppError):
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Resource conflict",
|
||||
*,
|
||||
code: str = "RESOURCE.CONFLICT",
|
||||
details: dict[str, Any] | None = None,
|
||||
):
|
||||
super().__init__(
|
||||
code=code,
|
||||
message=message,
|
||||
http_status=409,
|
||||
details=details or {},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
class ServiceUnavailableError(AppError):
|
||||
def __init__(self, message: str = "Service unavailable", *, code: str = "SYSTEM.SERVICE_UNAVAILABLE"):
|
||||
super().__init__(code=code, message=message, http_status=503, retryable=True)
|
||||
|
||||
|
||||
def raise_for_status(message: str, status: int, *, code: str | None = None, details: dict[str, Any] | None = None) -> None:
|
||||
if status == 401:
|
||||
raise UnauthorizedError(message)
|
||||
if status == 403:
|
||||
raise ForbiddenError(message)
|
||||
if status == 404:
|
||||
raise NotFoundError(message)
|
||||
if status == 409:
|
||||
raise ConflictError(message, code=code or "RESOURCE.CONFLICT", details=details)
|
||||
if status == 503:
|
||||
raise ServiceUnavailableError(message, code=code or "SYSTEM.SERVICE_UNAVAILABLE")
|
||||
if status >= 500:
|
||||
raise AppError(
|
||||
code=code or "SYSTEM.INTERNAL_ERROR",
|
||||
message=message,
|
||||
http_status=status,
|
||||
details=details or {},
|
||||
)
|
||||
raise AppError(
|
||||
code=code or "VALIDATION.INVALID_PARAM",
|
||||
message=message,
|
||||
http_status=status,
|
||||
details=details or {},
|
||||
)
|
||||
@@ -1,10 +1,12 @@
|
||||
"""
|
||||
backend/app/extensions.py
|
||||
|
||||
用途:Flask 扩展实例(db、migrate)集中定义;Wave 1 从 __init__.py 迁入并接线。
|
||||
用途:Flask 扩展单例(SQLAlchemy db、Flask-Migrate migrate)的唯一定义处。
|
||||
依赖:flask_sqlalchemy、flask_migrate。
|
||||
逻辑:create_app 调用 db.init_app(app);models 与各 service 从本模块 import db。
|
||||
逻辑:create_app 调用 db.init_app / migrate.init_app;models 与 services 通过 from app import db 或
|
||||
from app.extensions import db 引用同一实例,避免在 app/__init__.py 与应用工厂混杂定义。
|
||||
"""
|
||||
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
|
||||
|
||||
@@ -6,6 +6,12 @@ backend/app/jobs/__init__.py
|
||||
逻辑:Web API enqueue;worker.py 调用 runner.run_forever。
|
||||
"""
|
||||
from app.jobs.types import JobStatus, JobType
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.queue import enqueue, enqueue_clean_job, enqueue_kb_job
|
||||
|
||||
__all__ = ['JobType', 'JobStatus', 'enqueue']
|
||||
__all__ = [
|
||||
'JobType',
|
||||
'JobStatus',
|
||||
'enqueue',
|
||||
'enqueue_kb_job',
|
||||
'enqueue_clean_job',
|
||||
]
|
||||
@@ -5,4 +5,4 @@ backend/app/jobs/handlers/__init__.py
|
||||
逻辑: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
|
||||
from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, schedule_run, shipping_notice_parse, shipping_notice_run, wecom_directory_sync # noqa: F401
|
||||
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/kb_clean.py
|
||||
|
||||
用途:KB 文档清洗任务 handler。
|
||||
逻辑:Wave 2 包装 knowledge_cleaning.queue_service.process_next_clean_job。
|
||||
用途:KB 文档清洗 / 路径上传任务 handler。
|
||||
逻辑:包装 knowledge_cleaning.tasks.run_clean_job / run_path_upload_job。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -14,11 +14,22 @@ from app.jobs.types import JobType
|
||||
@register_handler(JobType.KB_CLEAN)
|
||||
def run_kb_clean(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行单条 KB 清洗任务。
|
||||
执行单条 KB 清洗或路径上传任务。
|
||||
Args:
|
||||
ctx: Worker 上下文。
|
||||
payload: 含 document_id 等字段。
|
||||
payload: 须含 job_id;raw_job_type 为 path_upload 时走路径上传分支。
|
||||
"""
|
||||
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')
|
||||
job_id = int(payload['job_id'])
|
||||
raw_type = str(payload.get('raw_job_type') or 'clean').strip()
|
||||
|
||||
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job
|
||||
|
||||
if raw_type == 'path_upload':
|
||||
ok, message = run_path_upload_job(job_id)
|
||||
else:
|
||||
ok, message = run_clean_job(job_id)
|
||||
|
||||
level = ctx.logger.info if ok else ctx.logger.warning
|
||||
level('kb_clean job_id=%s raw_type=%s ok=%s message=%s', job_id, raw_type, ok, message)
|
||||
if not ok:
|
||||
raise RuntimeError(message)
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/jobs/handlers/kb_dify_sync.py
|
||||
|
||||
用途:KB 文档同步至 Dify 任务 handler。
|
||||
逻辑:Wave 2 包装 knowledge_cleaning.dify_sync_service。
|
||||
逻辑:包装 knowledge_cleaning.tasks.run_sync_job。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -13,6 +13,17 @@ 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')
|
||||
"""
|
||||
同步已清洗文档到 Dify。
|
||||
Args:
|
||||
ctx: Worker 上下文。
|
||||
payload: 须含 job_id(KbJob 主键)。
|
||||
"""
|
||||
job_id = int(payload['job_id'])
|
||||
from app.services.knowledge_cleaning.tasks import run_sync_job
|
||||
|
||||
ok, message = run_sync_job(job_id)
|
||||
level = ctx.logger.info if ok else ctx.logger.warning
|
||||
level('kb_dify_sync job_id=%s ok=%s message=%s', job_id, ok, message)
|
||||
if not ok:
|
||||
raise RuntimeError(message)
|
||||
@@ -0,0 +1,276 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/shipping_notice_parse.py
|
||||
|
||||
用途:发货通知接入记录异步预解析 handler。
|
||||
依赖:jobs.context、jobs.registry、intake_parse_workflow、queue.fail/finish。
|
||||
逻辑:领取时写入 parse_lease="{job_id}:{attempts}";写回/失败清理均校验 lease;
|
||||
Job 收口一律 finish_job/fail_job(owned_attempt=...) 条件 UPDATE,
|
||||
禁止依赖 Session 身份映射判断执行权。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import and_, or_, update
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, NotFoundError
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.queue import fail_job, finish_job
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import FileAsset, Job, ShippingNoticeIntake
|
||||
from app.services.shipping_notice.intake_parse_workflow import (
|
||||
fail_intake_with_stage2_cleanup,
|
||||
run_intake_parse,
|
||||
)
|
||||
|
||||
# 真终态:无论 Job 身份都不再领取
|
||||
_TERMINAL_SKIP_STATUSES = frozenset({'parsed', 'consumed', 'cancelled', 'expired'})
|
||||
# 正常可领取进入 parsing
|
||||
_CLAIMABLE_STATUSES = frozenset({'created', 'queued', 'parse_failed'})
|
||||
|
||||
|
||||
def _load_asset(asset_id: int) -> FileAsset:
|
||||
"""
|
||||
加载父级 FileAsset;软删或不存在则抛 NotFoundError。
|
||||
|
||||
Args:
|
||||
asset_id: FileAsset 主键。
|
||||
|
||||
Returns:
|
||||
可用的 FileAsset。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 资产不存在或已软删。
|
||||
"""
|
||||
asset = db.session.get(FileAsset, asset_id)
|
||||
if not asset or asset.deleted_at is not None:
|
||||
raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='关联文件资产不存在')
|
||||
return asset
|
||||
|
||||
|
||||
def _build_parse_lease(*, job_id: int | None, owned_attempt: int | None) -> str:
|
||||
"""
|
||||
构造本轮解析执行代次 token。
|
||||
|
||||
核心逻辑:有 Job 时使用 "{job_id}:{attempts}",与 claim_next_job 递增的 attempts 对齐;
|
||||
无 Job(单测直调)时使用随机 UUID。
|
||||
"""
|
||||
if job_id is not None and owned_attempt is not None:
|
||||
return f'{int(job_id)}:{int(owned_attempt)}'
|
||||
return uuid.uuid4().hex
|
||||
|
||||
|
||||
def _claim_intake_for_parsing(
|
||||
intake_no: str,
|
||||
*,
|
||||
job_id: int | None,
|
||||
owned_attempt: int | None,
|
||||
) -> tuple[ShippingNoticeIntake, str] | None:
|
||||
"""
|
||||
原子领取 Intake 并轮转 parse_lease。
|
||||
|
||||
核心逻辑:仅 created/queued/parse_failed,或 parsing 且 parse_job_id 精确等于当前 Job
|
||||
(回收漏同步时由新 attempts 轮转 lease,旧 lease 立即失效)。
|
||||
|
||||
Returns:
|
||||
(Intake, lease) 或 None。
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
lease = _build_parse_lease(job_id=job_id, owned_attempt=owned_attempt)
|
||||
claim_predicate = ShippingNoticeIntake.parse_status.in_(tuple(_CLAIMABLE_STATUSES))
|
||||
if job_id is not None:
|
||||
claim_predicate = or_(
|
||||
claim_predicate,
|
||||
and_(
|
||||
ShippingNoticeIntake.parse_status == 'parsing',
|
||||
ShippingNoticeIntake.parse_job_id == int(job_id),
|
||||
),
|
||||
)
|
||||
values: dict = {
|
||||
'parse_status': 'parsing',
|
||||
'parse_lease': lease,
|
||||
'updated_at': now,
|
||||
}
|
||||
if job_id is not None:
|
||||
values['parse_job_id'] = int(job_id)
|
||||
stmt = (
|
||||
update(ShippingNoticeIntake)
|
||||
.where(
|
||||
ShippingNoticeIntake.intake_no == intake_no,
|
||||
claim_predicate,
|
||||
)
|
||||
.values(**values)
|
||||
)
|
||||
result = db.session.execute(stmt)
|
||||
if int(result.rowcount or 0) != 1:
|
||||
db.session.rollback()
|
||||
return None
|
||||
db.session.commit()
|
||||
intake = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter_by(intake_no=intake_no)
|
||||
.first()
|
||||
)
|
||||
if intake is None:
|
||||
return None
|
||||
return intake, lease
|
||||
|
||||
|
||||
def _is_retryable_exc(exc: BaseException) -> bool:
|
||||
"""业务 NotFound / AppError.retryable=False 视为不可再排队。"""
|
||||
if isinstance(exc, NotFoundError):
|
||||
return False
|
||||
if isinstance(exc, AppError):
|
||||
return bool(getattr(exc, 'retryable', False))
|
||||
return True
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_NOTICE_PARSE)
|
||||
def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
消费发货通知预解析任务。
|
||||
|
||||
Args:
|
||||
ctx: Worker 上下文。
|
||||
payload: 须含 job_id 或 intake_no。
|
||||
"""
|
||||
raw_job_id = payload.get('job_id')
|
||||
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
|
||||
job_id = int(job.id) if job is not None else None
|
||||
# claim_next_job 已递增 attempts;该值即本轮执行代次(收口必须带入条件 UPDATE)
|
||||
owned_attempt = int(job.attempts or 0) if job is not None else None
|
||||
intake_no = str(
|
||||
(job.payload_json or {}).get('intake_no') if job else payload.get('intake_no') or ''
|
||||
).strip().upper()
|
||||
if not intake_no:
|
||||
if job_id is not None:
|
||||
fail_job(
|
||||
job_id,
|
||||
error='missing intake_no',
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
intake = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_no).first()
|
||||
if not intake:
|
||||
if job_id is not None:
|
||||
fail_job(
|
||||
job_id,
|
||||
error=f'intake not found: {intake_no}',
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
# [STEP 1] 真终态跳过
|
||||
if intake.parse_status in _TERMINAL_SKIP_STATUSES:
|
||||
if job_id is not None:
|
||||
finish_job(
|
||||
job_id,
|
||||
result={'status': intake.parse_status, 'intake_no': intake_no, 'skipped': True},
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
# [STEP 1b] parsing 但非本 Job:另一 worker 持有 → 跳过
|
||||
if (
|
||||
intake.parse_status == 'parsing'
|
||||
and job_id is not None
|
||||
and (
|
||||
intake.parse_job_id is None
|
||||
or int(intake.parse_job_id) != int(job_id)
|
||||
)
|
||||
):
|
||||
finish_job(
|
||||
job_id,
|
||||
result={'status': 'parsing', 'intake_no': intake_no, 'skipped': True},
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
# [STEP 2] 原子领取并轮转 lease
|
||||
claimed = _claim_intake_for_parsing(
|
||||
intake_no, job_id=job_id, owned_attempt=owned_attempt
|
||||
)
|
||||
if claimed is None:
|
||||
current = db.session.query(ShippingNoticeIntake).filter_by(intake_no=intake_no).first()
|
||||
if job_id is not None:
|
||||
finish_job(
|
||||
job_id,
|
||||
result={
|
||||
'status': str(getattr(current, 'parse_status', None) or 'unknown'),
|
||||
'intake_no': intake_no,
|
||||
'skipped': True,
|
||||
},
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
intake, parse_lease = claimed
|
||||
intake_id = int(intake.id)
|
||||
preserved_parser = str(intake.parser_version or 'v6')
|
||||
preserved_text = intake.extracted_text
|
||||
preserved_structured = (
|
||||
dict(intake.structured_result_json)
|
||||
if isinstance(intake.structured_result_json, dict)
|
||||
else {}
|
||||
)
|
||||
preserved_warnings = list(intake.parse_warnings_json or [])
|
||||
|
||||
try:
|
||||
asset = _load_asset(intake.asset_id)
|
||||
result = run_intake_parse(intake, asset, parse_lease=parse_lease)
|
||||
if job_id is None:
|
||||
return
|
||||
status = str(result.get('status') or '')
|
||||
if status in {'parsed', 'skipped'}:
|
||||
finish_job(
|
||||
job_id,
|
||||
result=result,
|
||||
message=(
|
||||
'发货通知预解析完成'
|
||||
if status == 'parsed'
|
||||
else '接入已取消、过期或执行代次失效,跳过'
|
||||
),
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
else:
|
||||
fail_job(
|
||||
job_id,
|
||||
error=str(result.get('error_message') or 'parse failed'),
|
||||
retryable=False,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
error_code = getattr(exc, 'code', None) or 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED'
|
||||
fail_result = fail_intake_with_stage2_cleanup(
|
||||
intake_id=intake_id,
|
||||
intake_no=intake_no,
|
||||
parser_version=preserved_parser,
|
||||
error_code=str(error_code),
|
||||
error_message=str(exc)[:1000],
|
||||
extracted_text=preserved_text,
|
||||
structured_result_json=preserved_structured,
|
||||
parse_warnings_json=preserved_warnings,
|
||||
allowed_statuses=frozenset({'parsing', 'queued', 'created'}),
|
||||
required_lease=parse_lease,
|
||||
)
|
||||
# 租约已失效:旧 Worker 不得触碰 Job(条件 UPDATE 亦会 no-op,此处直接返回)
|
||||
if str(fail_result.get('reason') or '') == 'stale_parse_lease':
|
||||
return
|
||||
retryable = _is_retryable_exc(exc)
|
||||
if job_id is not None:
|
||||
fail_job(
|
||||
job_id,
|
||||
error=str(exc),
|
||||
retryable=retryable,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
if retryable:
|
||||
raise
|
||||
@@ -15,5 +15,12 @@ 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)
|
||||
"""
|
||||
消费单票发货后台任务。
|
||||
Args:
|
||||
ctx: Worker 上下文。
|
||||
payload: 须含 job_id 或 task_no。
|
||||
"""
|
||||
ok, message = run_shipping_notice_job(payload, logger=ctx.logger)
|
||||
if not ok:
|
||||
raise RuntimeError(message)
|
||||
+993
-13
File diff suppressed because it is too large.
Load diff
+43
-16
@@ -2,37 +2,64 @@
|
||||
backend/app/jobs/runner.py
|
||||
|
||||
用途:Worker 主循环 poll → dispatch → ack/fail。
|
||||
逻辑:worker.py 调用 run_forever(ctx);Wave 2 接入 store 与 registry。
|
||||
逻辑:worker.py 调用 run_forever(ctx);claim 走 store,执行走 registry handler。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.registry import get_handler
|
||||
from app.jobs import store
|
||||
from app.jobs.registry import get_handler
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.jobs.context import JobContext
|
||||
|
||||
|
||||
def run_forever(ctx: JobContext, *, poll_interval_seconds: float = 2.0) -> None:
|
||||
def _resolve_poll_seconds(ctx: JobContext) -> float:
|
||||
"""按队列配置读取轮询间隔。"""
|
||||
queues = ctx.extras.get('queues') or ['kb']
|
||||
if 'shipping' in queues and 'kb' not in queues:
|
||||
return float(ctx.config.get('SHIPPING_NOTICE_WORKER_POLL_SECONDS', 2))
|
||||
return float(ctx.config.get('KB_WORKER_POLL_SECONDS', 2))
|
||||
|
||||
|
||||
def run_forever(ctx: JobContext, *, poll_interval_seconds: float | None = None) -> None:
|
||||
"""
|
||||
持续轮询并执行任务。
|
||||
核心逻辑:claim_next → get_handler → handler(ctx, payload) → 更新状态。
|
||||
核心逻辑:claim_next → get_handler → handler(ctx, payload);异常时 mark_failed。
|
||||
Args:
|
||||
ctx: Worker 上下文。
|
||||
poll_interval_seconds: 无任务时的休眠秒数。
|
||||
ctx: Worker 上下文(extras.queues 指定消费队列)。
|
||||
poll_interval_seconds: 无任务时的休眠秒数;默认按队列读 config。
|
||||
"""
|
||||
ctx.logger.info('Job runner started (skeleton mode — Wave 2 will enable claim loop)')
|
||||
queues = ctx.extras.get('queues') or ['kb']
|
||||
poll = poll_interval_seconds if poll_interval_seconds is not None else _resolve_poll_seconds(ctx)
|
||||
ctx.logger.info('Job runner started queues=%s poll_seconds=%s', queues, poll)
|
||||
|
||||
while True:
|
||||
try:
|
||||
job = store.claim_next()
|
||||
except NotImplementedError:
|
||||
time.sleep(poll_interval_seconds)
|
||||
continue
|
||||
job = store.claim_next(queues=queues)
|
||||
if not job:
|
||||
time.sleep(poll_interval_seconds)
|
||||
time.sleep(poll)
|
||||
continue
|
||||
|
||||
handler = get_handler(job['job_type'])
|
||||
owned_attempt = job.get('attempts')
|
||||
owned_attempt_int = int(owned_attempt) if owned_attempt is not None else None
|
||||
if not handler:
|
||||
ctx.logger.error('No handler for job_type=%s', job.get('job_type'))
|
||||
ctx.logger.error('No handler for job_type=%s job_id=%s', job.get('job_type'), job.get('id'))
|
||||
store.mark_failed(
|
||||
job['id'],
|
||||
message=f'no handler for {job.get("job_type")}',
|
||||
owned_attempt=owned_attempt_int,
|
||||
)
|
||||
continue
|
||||
handler(ctx, job.get('payload') or {})
|
||||
|
||||
try:
|
||||
handler(ctx, job.get('payload') or {})
|
||||
except Exception as exc:
|
||||
ctx.logger.exception('Handler failed job_id=%s', job.get('id'))
|
||||
store.mark_failed(
|
||||
job['id'],
|
||||
message=str(exc),
|
||||
owned_attempt=owned_attempt_int,
|
||||
)
|
||||
+124
-8
@@ -1,20 +1,136 @@
|
||||
"""
|
||||
backend/app/jobs/store.py
|
||||
|
||||
用途:Job 表 CRUD(claim、update status)。
|
||||
逻辑:runner 通过 claim_next 获取待执行任务;Wave 2 落地 SQLAlchemy 模型。
|
||||
用途:Job 认领与状态读写(Wave 2:KbJob 双轨 adapter,无新表)。
|
||||
依赖:KbJob、各域 queue_service 的 claim/recover 逻辑。
|
||||
逻辑:runner 通过 claim_next 获取待执行任务;返回归一化 dict 供 handler 分发。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.jobs.types import QUEUE_KB_JOB_TYPES, JobType, handler_type_for_kb_job
|
||||
from app.models import Job, KbJob
|
||||
|
||||
def claim_next() -> dict[str, Any] | None:
|
||||
|
||||
def _normalize_generic_job(job: Job) -> dict[str, Any]:
|
||||
"""将通用 Job ORM 实例转为 runner/handler 使用的归一化任务 dict。"""
|
||||
job_type_value = str(job.job_type or '').strip()
|
||||
return {
|
||||
'id': job.id,
|
||||
'job_type': JobType(job_type_value),
|
||||
'raw_job_type': job_type_value,
|
||||
# 领取时代次,供异常收口条件 UPDATE(勿信 Session 缓存)
|
||||
'attempts': int(job.attempts or 0),
|
||||
'payload': {
|
||||
'job_id': job.id,
|
||||
**(job.payload_json or {}),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _normalize_kb_job(job: KbJob) -> dict[str, Any]:
|
||||
"""
|
||||
认领下一条待执行 Job(SELECT FOR UPDATE SKIP LOCKED)。
|
||||
将 KbJob ORM 实例转为 runner/handler 使用的归一化任务 dict。
|
||||
Args:
|
||||
job: 已 claim 的 KbJob。
|
||||
Returns:
|
||||
job 字典或 None。
|
||||
Raises:
|
||||
NotImplementedError: Wave 0 占位。
|
||||
含 id、job_type(handler 键)、payload、raw_job_type 的字典。
|
||||
"""
|
||||
raise NotImplementedError('jobs.store.claim_next is not wired until Wave 2')
|
||||
handler_type = handler_type_for_kb_job(job.job_type)
|
||||
if handler_type is None:
|
||||
raise ValueError(f'unsupported kb job_type={job.job_type!r}')
|
||||
|
||||
return {
|
||||
'id': job.id,
|
||||
'job_type': handler_type,
|
||||
'raw_job_type': job.job_type,
|
||||
'payload': {
|
||||
'job_id': job.id,
|
||||
'raw_job_type': job.job_type,
|
||||
**(job.payload_json or {}),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
|
||||
"""
|
||||
认领下一条待执行 Job(SELECT FOR UPDATE SKIP LOCKED,委托各域 queue_service)。
|
||||
核心逻辑:按 queues 顺序依次尝试 kb / shipping 队列;先 recover 卡死 running 任务。
|
||||
Args:
|
||||
queues: worker 消费的队列名,如 ['kb'] 或 ['kb', 'shipping']。
|
||||
Returns:
|
||||
归一化 job dict 或 None(无任务)。
|
||||
"""
|
||||
queue_names = [q.strip() for q in (queues or ['kb']) if q and q.strip()]
|
||||
if not queue_names:
|
||||
queue_names = ['kb']
|
||||
|
||||
# [STEP 1] 超时回收(按队列涉及的类型)
|
||||
allowed_types: set[str] = set()
|
||||
for name in queue_names:
|
||||
allowed_types.update(QUEUE_KB_JOB_TYPES.get(name, frozenset()))
|
||||
|
||||
if allowed_types & QUEUE_KB_JOB_TYPES['kb']:
|
||||
from app.services.knowledge_cleaning.queue_service import recover_stale_running_jobs
|
||||
|
||||
recover_stale_running_jobs()
|
||||
if 'shipping_notice_run' in allowed_types or 'shipping_notice_parse' in allowed_types:
|
||||
from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs
|
||||
|
||||
recover_stale_shipping_notice_jobs()
|
||||
|
||||
# [STEP 2] 按队列优先级 claim
|
||||
for name in queue_names:
|
||||
if name == 'kb':
|
||||
from app.services.knowledge_cleaning.queue_service import claim_next_kb_job
|
||||
|
||||
job = claim_next_kb_job()
|
||||
if job:
|
||||
return _normalize_kb_job(job)
|
||||
elif name == 'shipping':
|
||||
from app.services.shipping_notice.queue_service import claim_next_shipping_notice_job
|
||||
|
||||
job = claim_next_shipping_notice_job()
|
||||
if job:
|
||||
return _normalize_generic_job(job)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def mark_failed(job_id: int, *, message: str, owned_attempt: int | None = None) -> None:
|
||||
"""
|
||||
handler 未捕获异常时,将任务标记为 failed(KbJob 或通用 Job)。
|
||||
|
||||
Args:
|
||||
job_id: 任务主键。
|
||||
message: 失败原因(截断至 1000 字符)。
|
||||
owned_attempt: 领取时的 Job.attempts;通用 Job 用条件 UPDATE,避免覆盖新代次。
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.jobs.queue import fail_job
|
||||
|
||||
# 通用 Job 表命中则条件收口(rowcount=0 即代次/状态已变,安全 no-op)
|
||||
generic = db.session.query(Job.id).filter(Job.id == int(job_id)).first()
|
||||
if generic is not None:
|
||||
fail_job(
|
||||
int(job_id),
|
||||
error=message[:1000],
|
||||
retryable=True,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
kb_job = db.session.get(KbJob, job_id)
|
||||
if not kb_job or kb_job.status != 'running':
|
||||
return
|
||||
|
||||
now = datetime.utcnow()
|
||||
kb_job.status = 'failed'
|
||||
kb_job.error_message = message[:1000]
|
||||
kb_job.message = message[:500]
|
||||
kb_job.finished_at = now
|
||||
kb_job.progress = 100
|
||||
db.session.commit()
|
||||
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
backend/app/jobs/types.py
|
||||
|
||||
用途:Job 类型与状态枚举。
|
||||
逻辑:handlers 与 queue 通过 JobType 注册;store 持久化 status 字符串。
|
||||
用途:Job 类型与状态枚举;KbJob.job_type 与 handler JobType 的双向映射。
|
||||
逻辑:handlers 与 queue 通过 JobType 注册;store 持久化仍走 KbJob 表(Wave 2 双轨)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -10,21 +10,66 @@ from enum import StrEnum
|
||||
|
||||
|
||||
class JobType(StrEnum):
|
||||
"""后台任务类型。"""
|
||||
"""后台任务类型(handler 注册键)。"""
|
||||
|
||||
KB_CLEAN = 'kb_clean'
|
||||
KB_DIFY_SYNC = 'kb_dify_sync'
|
||||
SHIPPING_NOTICE_RUN = 'shipping_notice_run'
|
||||
SHIPPING_NOTICE_PARSE = 'shipping_notice_parse'
|
||||
SCHEDULE_RUN = 'schedule_run'
|
||||
FILE_CHECK_RUN = 'file_check_run'
|
||||
WECOM_DIRECTORY_SYNC = 'wecom_directory_sync'
|
||||
|
||||
|
||||
class JobStatus(StrEnum):
|
||||
"""Job 生命周期状态。"""
|
||||
"""通用 Job 生命周期状态(Wave 4 通用 Job 表预留;当前 KbJob 仍用 queued/running/success/failed)。"""
|
||||
|
||||
PENDING = 'pending'
|
||||
RUNNING = 'running'
|
||||
SUCCEEDED = 'succeeded'
|
||||
FAILED = 'failed'
|
||||
DEAD = 'dead'
|
||||
|
||||
|
||||
# KbJob.job_type 字符串 → handler JobType
|
||||
_KB_JOB_TYPE_TO_HANDLER: dict[str, JobType] = {
|
||||
'clean': JobType.KB_CLEAN,
|
||||
'path_upload': JobType.KB_CLEAN,
|
||||
'sync_dify': JobType.KB_DIFY_SYNC,
|
||||
'shipping_notice_run': JobType.SHIPPING_NOTICE_RUN,
|
||||
}
|
||||
|
||||
# handler JobType → 写入 KbJob 时使用的 job_type
|
||||
_HANDLER_TO_KB_JOB_TYPE: dict[JobType, str] = {
|
||||
JobType.KB_CLEAN: 'clean',
|
||||
JobType.KB_DIFY_SYNC: 'sync_dify',
|
||||
JobType.SHIPPING_NOTICE_RUN: 'shipping_notice_run',
|
||||
}
|
||||
|
||||
# worker --queues 参数 → 可消费的 KbJob.job_type 集合
|
||||
QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
|
||||
'kb': frozenset({'clean', 'path_upload', 'sync_dify'}),
|
||||
'shipping': frozenset({'shipping_notice_run', 'shipping_notice_parse'}),
|
||||
}
|
||||
|
||||
|
||||
def handler_type_for_kb_job(kb_job_type: str) -> JobType | None:
|
||||
"""
|
||||
将 KbJob.job_type 映射为 handler 注册用的 JobType。
|
||||
Args:
|
||||
kb_job_type: KbJob 表 job_type 列值。
|
||||
Returns:
|
||||
对应 JobType;未知类型返回 None。
|
||||
"""
|
||||
return _KB_JOB_TYPE_TO_HANDLER.get(str(kb_job_type or '').strip())
|
||||
|
||||
|
||||
def kb_job_type_for_handler(job_type: JobType) -> str | None:
|
||||
"""
|
||||
将 handler JobType 映射为写入 KbJob 的 job_type 字符串。
|
||||
Args:
|
||||
job_type: handler 注册键。
|
||||
Returns:
|
||||
KbJob.job_type 值;path_upload 等需调用方显式指定时不经此函数。
|
||||
"""
|
||||
return _HANDLER_TO_KB_JOB_TYPE.get(job_type)
|
||||
@@ -1,900 +0,0 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional, List
|
||||
from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index, Boolean, UniqueConstraint, LargeBinary, Float, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from app import db
|
||||
from werkzeug.security import generate_password_hash, check_password_hash
|
||||
|
||||
class Base(db.Model):
|
||||
"""
|
||||
基础模型类,设置为抽象基类
|
||||
"""
|
||||
__abstract__ = True
|
||||
|
||||
# RBAC 关联表:用户与 Agent 的多对多关系
|
||||
# 用于存储用户拥有哪些 Agent 的访问权限
|
||||
user_agent_permissions = db.Table(
|
||||
'user_agent_permissions',
|
||||
db.Column('user_id', ForeignKey('users.id'), primary_key=True),
|
||||
db.Column('agent_id', ForeignKey('agents.id'), primary_key=True)
|
||||
)
|
||||
|
||||
class ZlLanguage(Base):
|
||||
"""
|
||||
多语言配置表
|
||||
用途:存储系统支持的语言列表
|
||||
"""
|
||||
__tablename__ = 'zl_languages'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
code: Mapped[str] = mapped_column(String(10), unique=True) # en, zh-CN, zh-TW, th
|
||||
name: Mapped[str] = mapped_column(String(50)) # English, 简体中文, ...
|
||||
is_active: Mapped[bool] = mapped_column(default=True)
|
||||
|
||||
class Department(Base):
|
||||
"""
|
||||
部门表
|
||||
用途:存储公司部门列表
|
||||
"""
|
||||
__tablename__ = 'departments'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(100), unique=True)
|
||||
code: Mapped[Optional[str]] = mapped_column(String(50), unique=True) # 部门编号
|
||||
company: Mapped[Optional[str]] = mapped_column(String(100)) # 所属公司
|
||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||
|
||||
class UserHomepageConfig(Base):
|
||||
"""
|
||||
用户首页配置表
|
||||
用途:存储用户自定义的首页布局与配置
|
||||
"""
|
||||
__tablename__ = 'user_homepage_configs'
|
||||
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), primary_key=True)
|
||||
layout: Mapped[dict] = mapped_column(JSON, default={}) # 存储模块布局配置
|
||||
# 示例: { "modules": [{"id": "favorites", "x": 0, "y": 0}, {"id": "agents", "x": 0, "y": 1}] }
|
||||
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
class UserFavoriteAgent(Base):
|
||||
"""
|
||||
用户收藏 Agent 表
|
||||
用途:存储用户收藏的 Agent
|
||||
"""
|
||||
__tablename__ = 'user_favorite_agents'
|
||||
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), primary_key=True)
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), primary_key=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
class UserDefaultAgent(Base):
|
||||
"""
|
||||
用户默认 Agent 表 (嵌入首页)
|
||||
用途:存储用户设置的默认嵌入 Agent (最多2个)
|
||||
"""
|
||||
__tablename__ = 'user_default_agents'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
|
||||
sort_order: Mapped[int] = mapped_column(default=0) # 排序,0为第一个,1为第二个
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
class User(Base):
|
||||
"""
|
||||
用户表
|
||||
用途:存储系统用户信息
|
||||
核心逻辑:包含部门、角色等字段,关联 Agent 权限
|
||||
"""
|
||||
__tablename__ = 'users'
|
||||
|
||||
# 主键 ID
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
# 用户名,唯一且带索引
|
||||
username: Mapped[str] = mapped_column(String(50), unique=True, index=True)
|
||||
# 邮箱,唯一
|
||||
email: Mapped[str] = mapped_column(String(100), unique=True)
|
||||
# 部门信息
|
||||
department: Mapped[Optional[str]] = mapped_column(String(100))
|
||||
# 角色:admin 或 user
|
||||
role: Mapped[str] = mapped_column(String(20), default='user')
|
||||
# 账号状态:active (正常), pending (待审批), disabled (禁用)
|
||||
status: Mapped[str] = mapped_column(String(20), default='active')
|
||||
# 密码哈希
|
||||
password_hash: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
# 首选语言
|
||||
language: Mapped[str] = mapped_column(String(10), default='zh-CN')
|
||||
# 主题偏好: light / dark / system
|
||||
theme_preference: Mapped[str] = mapped_column(String(10), default='system')
|
||||
# 企业微信关联字段
|
||||
wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), unique=True, nullable=True)
|
||||
wecom_unionid: Mapped[Optional[str]] = mapped_column(String(128), unique=True, nullable=True)
|
||||
|
||||
# 真实姓名
|
||||
real_name: Mapped[Optional[str]] = mapped_column(String(50))
|
||||
# 公司工号,唯一
|
||||
employee_id: Mapped[Optional[str]] = mapped_column(String(50), unique=True)
|
||||
# 手机号,唯一
|
||||
phone_number: Mapped[Optional[str]] = mapped_column(String(20), unique=True)
|
||||
|
||||
# 默认嵌入的 Agent ID (忽略权限检查)
|
||||
default_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'))
|
||||
|
||||
# 关系:用户拥有的 Agent 权限 (多对多)
|
||||
agents: Mapped[List["Agent"]] = relationship(
|
||||
secondary=user_agent_permissions,
|
||||
back_populates="users"
|
||||
)
|
||||
|
||||
# 密码重置 Token
|
||||
reset_token: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
reset_token_expiry: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
def set_password(self, password):
|
||||
self.password_hash = generate_password_hash(password)
|
||||
|
||||
def check_password(self, password):
|
||||
if not self.password_hash:
|
||||
return False
|
||||
return check_password_hash(self.password_hash, password)
|
||||
|
||||
class Agent(Base):
|
||||
"""
|
||||
AI 应用配置表
|
||||
用途:存储接入的 Dify Agent 配置信息
|
||||
核心逻辑:存储 Dify App ID 和 API Key,控制应用开关
|
||||
"""
|
||||
__tablename__ = 'agents'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
# 应用名称
|
||||
name: Mapped[str] = mapped_column(String(100))
|
||||
# 应用描述
|
||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||
# 图标 URL
|
||||
icon_url: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
|
||||
# Dify 配置:App ID (唯一,对于 iframe 模式可选)
|
||||
dify_app_id: Mapped[Optional[str]] = mapped_column(String(100), unique=True, nullable=True)
|
||||
# Dify 配置:API Key (实际生产应加密存储,对于 iframe 模式可选)
|
||||
dify_api_key: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
|
||||
# 类型:api (默认) 或 iframe
|
||||
type: Mapped[str] = mapped_column(String(20), default='api')
|
||||
# 自定义 API Base URL (覆盖全局配置)
|
||||
api_base_url: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
# 额外配置 (JSON),用于存储 iframe_url 等
|
||||
extra_config: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
|
||||
# 是否激活
|
||||
is_active: Mapped[bool] = mapped_column(default=True)
|
||||
# 创建时间
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
# 关系:拥有该应用权限的用户 (多对多)
|
||||
users: Mapped[List["User"]] = relationship(
|
||||
secondary=user_agent_permissions,
|
||||
back_populates="agents"
|
||||
)
|
||||
|
||||
class ChatSession(Base):
|
||||
"""
|
||||
聊天会话表
|
||||
用途:独立持久化会话元数据,使生成中会话也能立即出现在历史记录中
|
||||
"""
|
||||
__tablename__ = 'chat_sessions'
|
||||
__table_args__ = (
|
||||
Index('ix_chat_sessions_user_agent_last_active', 'user_id', 'agent_id', 'last_active_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
session_id: Mapped[str] = mapped_column(String(100), unique=True, index=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True)
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), index=True)
|
||||
title: Mapped[str] = mapped_column(String(255), default='')
|
||||
status: Mapped[str] = mapped_column(String(20), default='running')
|
||||
external_conversation_id: Mapped[Optional[str]] = mapped_column(String(100), index=True, 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)
|
||||
last_active_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
class ChatLog(Base):
|
||||
"""
|
||||
对话日志表
|
||||
用途:存储用户与 Agent 的对话记录
|
||||
"""
|
||||
__tablename__ = 'chat_logs'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
|
||||
query: Mapped[str] = mapped_column(Text)
|
||||
answer: Mapped[str] = mapped_column(Text)
|
||||
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)
|
||||
# Persist citation/source metadata so history messages can still show sources.
|
||||
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON)
|
||||
attribution_parts: Mapped[Optional[list]] = mapped_column(JSON)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
# 关联 Feedback
|
||||
feedback: Mapped[Optional["Feedback"]] = relationship(back_populates="chat_log", uselist=False)
|
||||
|
||||
class Feedback(Base):
|
||||
"""
|
||||
反馈表
|
||||
用途:存储用户对回答的评分与评价
|
||||
"""
|
||||
__tablename__ = 'feedbacks'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
chat_log_id: Mapped[int] = mapped_column(ForeignKey('chat_logs.id'), unique=True)
|
||||
score: Mapped[int] = mapped_column(Integer) # 1-5
|
||||
comment: Mapped[Optional[str]] = mapped_column(Text)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
chat_log: Mapped["ChatLog"] = relationship(back_populates="feedback")
|
||||
|
||||
class GeneralFeedback(Base):
|
||||
"""
|
||||
通用意见反馈表
|
||||
用于存储 Workspace/Chat 页面提交的通用意见反馈
|
||||
"""
|
||||
__tablename__ = 'general_feedbacks'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True)
|
||||
chat_log_id: Mapped[Optional[int]] = mapped_column(ForeignKey('chat_logs.id'), nullable=True, index=True)
|
||||
username: Mapped[str] = mapped_column(String(50), nullable=False)
|
||||
feedback_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
feedback_module: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
content: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
source_page: Mapped[Optional[str]] = mapped_column(String(32))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
class PermissionRequest(Base):
|
||||
"""
|
||||
权限申请表
|
||||
用途:存储用户的权限申请记录
|
||||
"""
|
||||
__tablename__ = 'permission_requests'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
|
||||
reason: Mapped[str] = mapped_column(Text)
|
||||
status: Mapped[str] = mapped_column(String(20), default='pending') # pending, approved, rejected
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
reviewed_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
|
||||
class QuickQuestion(Base):
|
||||
"""
|
||||
常用问题表
|
||||
用途:存储全局/用户常用问题;全局条目(user_id 为空)可配置标准答案并启用 FAQ 缓存命中。
|
||||
"""
|
||||
__tablename__ = 'quick_questions'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
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):
|
||||
"""
|
||||
公告表
|
||||
用途:存储系统公告
|
||||
"""
|
||||
__tablename__ = 'announcements'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
title: Mapped[str] = mapped_column(String(200))
|
||||
content: Mapped[str] = mapped_column(Text)
|
||||
is_active: Mapped[bool] = mapped_column(default=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
class LoginAudit(Base):
|
||||
"""
|
||||
登录审计表
|
||||
用途:记录密码登录与企业微信登录结果,便于排障与审计
|
||||
"""
|
||||
__tablename__ = 'login_audits'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
username: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
|
||||
source: Mapped[str] = mapped_column(String(20), default='password') # password / wecom
|
||||
status: Mapped[str] = mapped_column(String(20), default='success') # success / failed
|
||||
reason: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
match_rules: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
match_operator: Mapped[Optional[str]] = mapped_column(String(8), nullable=True)
|
||||
match_result: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
ip: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
user_agent: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
|
||||
class WecomNotifyAudit(Base):
|
||||
"""
|
||||
企业微信触达审计表
|
||||
用途:记录企微消息发送结果与回流点击数据
|
||||
"""
|
||||
__tablename__ = 'wecom_notify_audits'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
event_type: Mapped[str] = mapped_column(String(64), index=True)
|
||||
status: Mapped[str] = mapped_column(String(20), default='sent', index=True) # sent / failed
|
||||
trace_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True, index=True)
|
||||
username: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
|
||||
wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
title: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
content: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
jump_url: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
opened_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
|
||||
|
||||
|
||||
class AppSetting(Base):
|
||||
"""
|
||||
应用运行时配置表(Key/Value)
|
||||
用途:将企业微信等管理员可编辑的配置长效保存到数据库,
|
||||
避免容器/部署重建后写入 backend/.env 的修改丢失。
|
||||
"""
|
||||
__tablename__ = 'app_settings'
|
||||
|
||||
key: Mapped[str] = mapped_column(String(128), primary_key=True)
|
||||
value: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow
|
||||
)
|
||||
|
||||
|
||||
class KbGroup(Base):
|
||||
"""
|
||||
知识库分组
|
||||
用途:承载数据清洗/知识库管理模块中的分组/知识库
|
||||
"""
|
||||
__tablename__ = 'kb_groups'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('department_id', 'name', name='uq_kb_groups_department_name'),
|
||||
Index('ix_kb_groups_department_active', 'department_id', 'is_active'),
|
||||
Index('ix_kb_groups_dify_dataset_id', 'dify_dataset_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(128), index=True)
|
||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||
department_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True, index=True)
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
dify_dataset_id: Mapped[Optional[str]] = mapped_column(String(128))
|
||||
dify_dataset_name: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
created_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[created_by_id])
|
||||
updated_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[updated_by_id])
|
||||
documents: Mapped[List["KbDocument"]] = relationship(
|
||||
"KbDocument",
|
||||
back_populates="group",
|
||||
cascade="all, delete-orphan",
|
||||
)
|
||||
|
||||
|
||||
class KbDocument(Base):
|
||||
"""
|
||||
知识库逻辑文档
|
||||
用途:表示一个文档条目,不直接等同于某一次上传文件
|
||||
"""
|
||||
__tablename__ = 'kb_documents'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('group_id', 'title', name='uq_kb_documents_group_title'),
|
||||
Index('ix_kb_documents_group_status', 'group_id', 'status'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
group_id: Mapped[int] = mapped_column(ForeignKey('kb_groups.id'), index=True)
|
||||
title: Mapped[str] = mapped_column(String(255))
|
||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||
status: Mapped[str] = mapped_column(String(32), default='draft', index=True)
|
||||
source_type: Mapped[Optional[str]] = mapped_column(String(32))
|
||||
is_deleted: Mapped[bool] = mapped_column(Boolean, default=False, index=True)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
group: Mapped["KbGroup"] = relationship("KbGroup", back_populates="documents")
|
||||
created_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[created_by_id])
|
||||
updated_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[updated_by_id])
|
||||
versions: Mapped[List["KbDocumentVersion"]] = relationship(
|
||||
"KbDocumentVersion",
|
||||
back_populates="document",
|
||||
cascade="all, delete-orphan",
|
||||
order_by="desc(KbDocumentVersion.version_no)",
|
||||
)
|
||||
|
||||
|
||||
class KbDocumentVersion(Base):
|
||||
"""
|
||||
知识库文档版本
|
||||
用途:记录每次上传、清洗、同步产生的版本信息
|
||||
"""
|
||||
__tablename__ = 'kb_document_versions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('document_id', 'version_no', name='uq_kb_document_versions_doc_version'),
|
||||
Index('ix_kb_document_versions_doc_status', 'document_id', 'status'),
|
||||
Index('ix_kb_document_versions_sha256', 'sha256'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
document_id: Mapped[int] = mapped_column(ForeignKey('kb_documents.id'), index=True)
|
||||
version_no: Mapped[int] = mapped_column(Integer)
|
||||
status: Mapped[str] = mapped_column(String(32), default='uploaded', index=True)
|
||||
is_current: Mapped[bool] = mapped_column(Boolean, default=True, index=True)
|
||||
source_file_name: Mapped[str] = mapped_column(String(255))
|
||||
source_file_path: Mapped[str] = mapped_column(Text)
|
||||
source_file_ext: Mapped[Optional[str]] = mapped_column(String(32))
|
||||
source_file_size: Mapped[Optional[int]] = mapped_column(Integer)
|
||||
cleaned_file_path: Mapped[Optional[str]] = mapped_column(Text)
|
||||
cleaned_preview_path: Mapped[Optional[str]] = mapped_column(Text)
|
||||
sha256: Mapped[Optional[str]] = mapped_column(String(64))
|
||||
word_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
warnings_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
uploaded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
converted_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
|
||||
document: Mapped["KbDocument"] = relationship("KbDocument", back_populates="versions")
|
||||
uploaded_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[uploaded_by_id])
|
||||
jobs: Mapped[List["KbJob"]] = relationship(
|
||||
"KbJob",
|
||||
back_populates="document_version",
|
||||
cascade="all, delete-orphan",
|
||||
)
|
||||
sync_records: Mapped[List["KbDifySyncRecord"]] = relationship(
|
||||
"KbDifySyncRecord",
|
||||
back_populates="document_version",
|
||||
cascade="all, delete-orphan",
|
||||
order_by="desc(KbDifySyncRecord.updated_at)",
|
||||
)
|
||||
|
||||
|
||||
class KbJob(Base):
|
||||
"""
|
||||
知识库后台任务
|
||||
用途:记录上传、清洗、同步等后台任务执行情况
|
||||
"""
|
||||
__tablename__ = 'kb_jobs'
|
||||
__table_args__ = (
|
||||
Index('ix_kb_jobs_status_created', 'status', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
job_type: Mapped[str] = mapped_column(String(32), index=True)
|
||||
status: Mapped[str] = mapped_column(String(32), default='queued', index=True)
|
||||
queue_job_id: Mapped[Optional[str]] = mapped_column(String(64))
|
||||
group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'))
|
||||
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id'))
|
||||
document_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_document_versions.id'), index=True)
|
||||
progress: Mapped[int] = mapped_column(Integer, default=0)
|
||||
message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
payload_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
result_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
|
||||
created_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[created_by_id])
|
||||
document_version: Mapped[Optional["KbDocumentVersion"]] = relationship(
|
||||
"KbDocumentVersion",
|
||||
back_populates="jobs",
|
||||
)
|
||||
|
||||
|
||||
class KbDifySyncRecord(Base):
|
||||
"""
|
||||
知识库 Dify 同步记录
|
||||
用途:记录本地文档版本与 Dify 远端文档之间的同步映射
|
||||
"""
|
||||
__tablename__ = 'kb_dify_sync_records'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'document_version_id',
|
||||
'remote_document_id',
|
||||
name='uq_kb_dify_sync_records_version_remote'
|
||||
),
|
||||
Index('ix_kb_dify_sync_records_dataset_id', 'dataset_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'))
|
||||
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id'))
|
||||
document_version_id: Mapped[int] = mapped_column(ForeignKey('kb_document_versions.id'), index=True)
|
||||
dataset_id: Mapped[str] = mapped_column(String(128))
|
||||
dataset_name: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
remote_document_id: Mapped[str] = mapped_column(String(128))
|
||||
remote_document_name: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
status: Mapped[str] = mapped_column(String(32), default='pending', index=True)
|
||||
sync_hash: Mapped[Optional[str]] = mapped_column(String(64))
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
synced_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
synced_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
document_version: Mapped["KbDocumentVersion"] = relationship(
|
||||
"KbDocumentVersion",
|
||||
back_populates="sync_records",
|
||||
)
|
||||
synced_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[synced_by_id])
|
||||
|
||||
|
||||
class WecomCallbackAudit(Base):
|
||||
"""
|
||||
企业微信回调审计表
|
||||
用途:记录消息与事件回调(安全模式解密后的内容摘要)
|
||||
"""
|
||||
__tablename__ = 'wecom_callback_audits'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
msg_signature: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
timestamp: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
nonce: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
encrypt_raw: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
decrypted_xml: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
msg_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
|
||||
event: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
from_user: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
|
||||
agent_id: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
msg_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
|
||||
class ScheduleTask(Base):
|
||||
__tablename__ = 'schedule_tasks'
|
||||
__table_args__ = (
|
||||
Index('ix_schedule_tasks_enabled_next_run', 'enabled', 'next_run_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
schedule_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
name: Mapped[str] = mapped_column(String(128), index=True)
|
||||
schedule_type: Mapped[str] = mapped_column(String(32), default='platform_app')
|
||||
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True)
|
||||
cron_expr: Mapped[str] = mapped_column(String(64))
|
||||
schedule_timezone: Mapped[str] = mapped_column(String(64), default='Asia/Shanghai', server_default=text("'Asia/Shanghai'"))
|
||||
wait_seconds: Mapped[int] = mapped_column(Integer, default=0)
|
||||
dify_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True, index=True)
|
||||
platform_api_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
data_source_type: Mapped[str] = mapped_column(String(32), default='database')
|
||||
kb_sync_enabled: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
|
||||
kb_group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'), nullable=True, index=True)
|
||||
notify_user_ids_json: Mapped[Optional[list]] = mapped_column(JSON, default=[])
|
||||
notify_enabled: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, default=True, index=True)
|
||||
next_run_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True)
|
||||
last_run_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
owner: Mapped[Optional["User"]] = relationship("User", foreign_keys=[owner_user_id])
|
||||
dify_agent: Mapped[Optional["Agent"]] = relationship("Agent", foreign_keys=[dify_agent_id])
|
||||
kb_group: Mapped[Optional["KbGroup"]] = relationship("KbGroup", foreign_keys=[kb_group_id])
|
||||
config: Mapped[Optional["ScheduleTaskConfig"]] = relationship("ScheduleTaskConfig", back_populates="task", uselist=False, cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class ScheduleTaskConfig(Base):
|
||||
__tablename__ = 'schedule_task_configs'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('schedule_task_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
schedule_task_id: Mapped[int] = mapped_column(ForeignKey('schedule_tasks.id'), index=True)
|
||||
|
||||
row_id_key: Mapped[str] = mapped_column(String(64), default='id')
|
||||
log_prefix: Mapped[str] = mapped_column(String(128), default='')
|
||||
|
||||
base_fetch_sql: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
fetch_where_conditions: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
fetch_order_by: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
writeback_sql: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
detail_sql: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
alias_order: Mapped[Optional[list]] = mapped_column(JSON, default=[])
|
||||
detail_alias_order: Mapped[Optional[list]] = mapped_column(JSON, default=[])
|
||||
header_labels: Mapped[Optional[dict]] = mapped_column(JSON, default={})
|
||||
|
||||
ds_db_type: Mapped[str] = mapped_column(String(32), default='sqlserver')
|
||||
ds_host: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
ds_port: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
ds_database: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
ds_username: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
ds_password: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
ds_driver: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
ds_encrypt: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||||
ds_trust_cert: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||||
|
||||
api_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
api_method: Mapped[str] = mapped_column(String(16), default='POST')
|
||||
api_headers: Mapped[Optional[dict]] = mapped_column(JSON, default={})
|
||||
api_body_template: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
dify_system_prompt: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", back_populates="config")
|
||||
|
||||
|
||||
class ScheduleRun(Base):
|
||||
__tablename__ = 'schedule_runs'
|
||||
__table_args__ = (
|
||||
Index('ix_schedule_runs_task_created', 'schedule_task_id', 'created_at'),
|
||||
Index('ix_schedule_runs_status_created', 'status', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
run_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
schedule_task_id: Mapped[int] = mapped_column(ForeignKey('schedule_tasks.id'), index=True)
|
||||
trigger_type: Mapped[str] = mapped_column(String(16), default='cron')
|
||||
triggered_by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True)
|
||||
duration_ms: Mapped[int] = mapped_column(Integer, default=0)
|
||||
status: Mapped[str] = mapped_column(String(32), default='queued', index=True)
|
||||
total_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
success_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
failed_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
skipped_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
api_request_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
api_response_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
response_summary_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
step_logs: Mapped[Optional[list]] = mapped_column(JSON)
|
||||
dify_execution_snapshot: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
excel_file_data: Mapped[Optional[bytes]] = mapped_column(LargeBinary)
|
||||
excel_file_name: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
excel_file_size: Mapped[Optional[int]] = mapped_column(Integer)
|
||||
kb_sync_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
kb_group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'), nullable=True)
|
||||
kb_document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id'), nullable=True)
|
||||
kb_document_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_document_versions.id'), nullable=True)
|
||||
kb_sync_job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_jobs.id'), nullable=True)
|
||||
kb_sync_error: Mapped[Optional[str]] = mapped_column(Text)
|
||||
wecom_notified: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
|
||||
wecom_notified_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
wecom_notify_error: Mapped[Optional[str]] = mapped_column(Text)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", foreign_keys=[schedule_task_id])
|
||||
kb_group: Mapped[Optional["KbGroup"]] = relationship("KbGroup", foreign_keys=[kb_group_id])
|
||||
kb_document: Mapped[Optional["KbDocument"]] = relationship("KbDocument", foreign_keys=[kb_document_id])
|
||||
kb_document_version: Mapped[Optional["KbDocumentVersion"]] = relationship("KbDocumentVersion", foreign_keys=[kb_document_version_id])
|
||||
kb_sync_job: Mapped[Optional["KbJob"]] = relationship("KbJob", foreign_keys=[kb_sync_job_id])
|
||||
|
||||
|
||||
class ShippingBatch(Base):
|
||||
"""货代发货通知批次(一次多文件上传的聚合容器)"""
|
||||
__tablename__ = 'shipping_batches'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_batches_user_created', 'user_id', 'created_at'),
|
||||
Index('ix_shipping_batches_conversation', 'conversation_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
batch_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
current_focus_task_no: Mapped[Optional[str]] = mapped_column(
|
||||
String(64),
|
||||
ForeignKey(
|
||||
'shipping_tasks.task_no',
|
||||
name='fk_shipping_batches_current_focus_task_no_shipping_tasks',
|
||||
use_alter=True,
|
||||
),
|
||||
nullable=True,
|
||||
)
|
||||
file_count: Mapped[int] = mapped_column(Integer, default=1)
|
||||
process_summary_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
tasks: Mapped[List["ShippingTask"]] = relationship(
|
||||
"ShippingTask",
|
||||
back_populates="batch",
|
||||
foreign_keys="ShippingTask.batch_id",
|
||||
)
|
||||
|
||||
|
||||
class ShippingTask(Base):
|
||||
"""货代发货通知 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)
|
||||
customer_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
ship_to: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
po_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
required_date: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
lines_json: Mapped[Optional[list]] = mapped_column(JSON, default=list)
|
||||
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)
|
||||
line_results_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
inventory_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
|
||||
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",
|
||||
cascade="all, delete-orphan",
|
||||
)
|
||||
|
||||
|
||||
class ShippingTaskEvent(Base):
|
||||
"""发货 task 审计事件"""
|
||||
__tablename__ = 'shipping_task_events'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), index=True)
|
||||
event_type: Mapped[str] = mapped_column(String(64), index=True)
|
||||
detail_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
task: Mapped["ShippingTask"] = relationship("ShippingTask", back_populates="events")
|
||||
|
||||
|
||||
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'),
|
||||
Index('ix_shipping_inventory_mappings_customer_code', 'customer_code'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
customer_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
header_hash: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
headers_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
field_mapping_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
|
||||
last_used_at: Mapped[Optional[datetime]] = mapped_column(DateTime, 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, index=True)
|
||||
|
||||
class AgentGuide(Base):
|
||||
"""
|
||||
平台应用新手指南表
|
||||
用途:存储 Agent 的新手指南文件信息 (如视频、PDF)
|
||||
"""
|
||||
__tablename__ = 'agent_guides'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), index=True)
|
||||
file_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
file_type: Mapped[str] = mapped_column(String(50), nullable=False) # video, pdf, image
|
||||
file_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
file_size: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0)
|
||||
status: Mapped[int] = mapped_column(Integer, default=1) # 1: 启用, 0: 禁用
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
agent: Mapped[Optional["Agent"]] = relationship("Agent", foreign_keys=[agent_id])
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
"""
|
||||
backend/app/models/__init__.py
|
||||
|
||||
用途:按业务域拆分的 ORM 模型包入口;聚合导出以保持 `from app.models import User` 兼容。
|
||||
依赖:models/* 子模块、app.extensions.db(经 base.Base)。
|
||||
逻辑:Alembic / Flask-Migrate 通过本模块 import 注册全部表元数据;业务代码继续从此处导入模型类。
|
||||
"""
|
||||
|
||||
from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest
|
||||
from app.models.base import Base, user_agent_permissions
|
||||
from app.models.chat import ChatLog, ChatSession, ChatToolRun, Feedback, GeneralFeedback
|
||||
from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlLanguage
|
||||
from app.models.department import Department
|
||||
from app.models.job import Job
|
||||
from app.models.kb import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup, KbJob
|
||||
from app.models.maintenance import MaintenanceAuditLog, MaintenanceDevice, MaintenanceRecord
|
||||
from app.models.schedule import ScheduleRun, ScheduleTask, ScheduleTaskConfig
|
||||
from app.models.settings import AppSetting
|
||||
from app.models.file_asset import FileAsset
|
||||
from app.models.shipping import (
|
||||
ShippingBatch,
|
||||
ShippingInventoryFile,
|
||||
ShippingInventoryMapping,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingTask,
|
||||
ShippingTaskEvent,
|
||||
ShippingTaskInventoryLink,
|
||||
)
|
||||
from app.models.training import TrainingRecord
|
||||
from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig
|
||||
from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit
|
||||
|
||||
__all__ = [
|
||||
'Base',
|
||||
'user_agent_permissions',
|
||||
'ZlLanguage',
|
||||
'Department',
|
||||
'UserHomepageConfig',
|
||||
'UserFavoriteAgent',
|
||||
'UserDefaultAgent',
|
||||
'User',
|
||||
'Agent',
|
||||
'ChatSession',
|
||||
'ChatLog',
|
||||
'ChatToolRun',
|
||||
'Feedback',
|
||||
'GeneralFeedback',
|
||||
'PermissionRequest',
|
||||
'QuickQuestion',
|
||||
'FaqHotCandidate',
|
||||
'Announcement',
|
||||
'LoginAudit',
|
||||
'WecomNotifyAudit',
|
||||
'AppSetting',
|
||||
'KbGroup',
|
||||
'KbDocument',
|
||||
'KbDocumentVersion',
|
||||
'KbJob',
|
||||
'Job',
|
||||
'KbDifySyncRecord',
|
||||
'WecomCallbackAudit',
|
||||
'ScheduleTask',
|
||||
'ScheduleTaskConfig',
|
||||
'ScheduleRun',
|
||||
'ShippingBatch',
|
||||
'ShippingTask',
|
||||
'ShippingTaskEvent',
|
||||
'ShippingInventoryFile',
|
||||
'ShippingTaskInventoryLink',
|
||||
'ShippingInventoryMapping',
|
||||
'ShippingNoticeIntake',
|
||||
'ShippingNoticeDocument',
|
||||
'ShippingNoticeCandidate',
|
||||
'FileAsset',
|
||||
'AgentGuide',
|
||||
'AgentDirectoryMember',
|
||||
'TrainingRecord',
|
||||
'MaintenanceDevice',
|
||||
'MaintenanceRecord',
|
||||
'MaintenanceAuditLog',
|
||||
]
|
||||
@@ -0,0 +1,132 @@
|
||||
"""
|
||||
backend/app/models/agent.py
|
||||
|
||||
用途:Dify Agent 配置、新手指南、权限申请模型;含 Agent 注册表结构化列(agent_code、runtime_provider 等)。
|
||||
依赖:models.base(Base、user_agent_permissions)、schedule_tasks(bound_schedule_task_id FK)。
|
||||
逻辑:Admin/聊天/Resolver 读写本表;运行时只读结构化列;extra_config 仅保留未迁移实验字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, JSON, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base, user_agent_permissions
|
||||
|
||||
|
||||
class Agent(Base):
|
||||
"""
|
||||
AI 应用配置表
|
||||
用途:存储接入的 Dify Agent 配置信息
|
||||
核心逻辑:存储 Dify App ID 和 API Key,控制应用开关;运行时只读结构化列,extra_config 仅实验字段。
|
||||
"""
|
||||
|
||||
__tablename__ = 'agents'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(100))
|
||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||
icon_url: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
dify_app_id: Mapped[Optional[str]] = mapped_column(String(100), unique=True, nullable=True)
|
||||
dify_api_key: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
type: Mapped[str] = mapped_column(String(20), default='api')
|
||||
api_base_url: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
extra_config: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
is_active: Mapped[bool] = mapped_column(default=True)
|
||||
is_aggregate: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
# Agent Registry 结构化列(迭代 1;详见 docs/platform/agent_application_management.md §3.1)
|
||||
agent_code: Mapped[str] = mapped_column(String(64), default='generic', nullable=False)
|
||||
runtime_provider: Mapped[str] = mapped_column(String(32), default='dify', nullable=False)
|
||||
conversation_mode: Mapped[str] = mapped_column(String(32), default='chat', nullable=False)
|
||||
dify_app_type: Mapped[str] = mapped_column(String(20), default='chatflow', nullable=False)
|
||||
iframe_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
category: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
sub_category: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
welcome_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
suggested_questions_style: Mapped[str] = mapped_column(String(20), default='plain', nullable=False)
|
||||
suggested_questions: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
capabilities: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
file_upload_policy: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
bound_schedule_task_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('schedule_tasks.id'),
|
||||
nullable=True,
|
||||
)
|
||||
handler_config: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
users: Mapped[List['User']] = relationship(
|
||||
secondary=user_agent_permissions,
|
||||
back_populates='agents',
|
||||
)
|
||||
|
||||
|
||||
class AgentGuide(Base):
|
||||
"""
|
||||
平台应用新手指南表
|
||||
用途:存储 Agent 的新手指南文件信息 (如视频、PDF)
|
||||
"""
|
||||
|
||||
__tablename__ = 'agent_guides'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), index=True)
|
||||
file_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
file_type: Mapped[str] = mapped_column(String(50), nullable=False)
|
||||
file_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
file_size: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
guide_usage: Mapped[str] = mapped_column(String(50), nullable=False, default='general')
|
||||
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0)
|
||||
status: Mapped[int] = mapped_column(Integer, default=1)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
agent: Mapped[Optional['Agent']] = relationship('Agent', foreign_keys=[agent_id])
|
||||
|
||||
|
||||
class AgentDirectoryMember(Base):
|
||||
"""
|
||||
Directory-agent membership.
|
||||
|
||||
Purpose: lets an Agent act as a clickable directory entry while explicitly
|
||||
listing the child Agents whose knowledge should be included by the upstream
|
||||
aggregate Chatflow.
|
||||
"""
|
||||
|
||||
__tablename__ = 'agent_directory_members'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('directory_agent_id', 'member_agent_id', name='uq_agent_directory_member_pair'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
directory_agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id', ondelete='CASCADE'), index=True)
|
||||
member_agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id', ondelete='CASCADE'), index=True)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
directory_agent: Mapped[Optional['Agent']] = relationship('Agent', foreign_keys=[directory_agent_id])
|
||||
member_agent: Mapped[Optional['Agent']] = relationship('Agent', foreign_keys=[member_agent_id])
|
||||
|
||||
|
||||
class PermissionRequest(Base):
|
||||
"""
|
||||
权限申请表
|
||||
用途:存储用户的权限申请记录
|
||||
"""
|
||||
|
||||
__tablename__ = 'permission_requests'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
|
||||
reason: Mapped[str] = mapped_column(Text)
|
||||
status: Mapped[str] = mapped_column(String(20), default='pending')
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
reviewed_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
@@ -0,0 +1,27 @@
|
||||
"""
|
||||
backend/app/models/base.py
|
||||
|
||||
用途:SQLAlchemy 抽象基类与用户-Agent RBAC 关联表。
|
||||
依赖:app.extensions.db。
|
||||
逻辑:各域 model 模块继承 Base;User.agents / Agent.users 共用 user_agent_permissions。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import ForeignKey
|
||||
|
||||
from app.extensions import db
|
||||
|
||||
|
||||
class Base(db.Model):
|
||||
"""抽象基类,所有业务模型继承此类。"""
|
||||
|
||||
__abstract__ = True
|
||||
|
||||
|
||||
# RBAC 关联表:用户与 Agent 的多对多关系
|
||||
user_agent_permissions = db.Table(
|
||||
'user_agent_permissions',
|
||||
db.Column('user_id', ForeignKey('users.id'), primary_key=True),
|
||||
db.Column('agent_id', ForeignKey('agents.id'), primary_key=True),
|
||||
)
|
||||
@@ -0,0 +1,133 @@
|
||||
"""
|
||||
backend/app/models/chat.py
|
||||
|
||||
用途:对话会话、消息日志与反馈模型。
|
||||
依赖:models.base.Base。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ChatSession(Base):
|
||||
"""
|
||||
聊天会话表
|
||||
用途:独立持久化会话元数据,使生成中会话也能立即出现在历史记录中
|
||||
"""
|
||||
|
||||
__tablename__ = 'chat_sessions'
|
||||
__table_args__ = (
|
||||
Index('ix_chat_sessions_user_agent_last_active', 'user_id', 'agent_id', 'last_active_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
session_id: Mapped[str] = mapped_column(String(100), unique=True, index=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True)
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), index=True)
|
||||
title: Mapped[str] = mapped_column(String(255), default='')
|
||||
status: Mapped[str] = mapped_column(String(20), default='running')
|
||||
external_conversation_id: Mapped[Optional[str]] = mapped_column(String(100), index=True, 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)
|
||||
last_active_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
|
||||
class ChatLog(Base):
|
||||
"""
|
||||
对话日志表
|
||||
用途:存储用户与 Agent 的对话记录
|
||||
"""
|
||||
|
||||
__tablename__ = 'chat_logs'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'))
|
||||
query: Mapped[str] = mapped_column(Text)
|
||||
answer: Mapped[str] = mapped_column(Text)
|
||||
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)
|
||||
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON)
|
||||
attribution_parts: Mapped[Optional[list]] = mapped_column(JSON)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
feedback: Mapped[Optional['Feedback']] = relationship(back_populates='chat_log', uselist=False)
|
||||
|
||||
|
||||
class Feedback(Base):
|
||||
"""
|
||||
反馈表
|
||||
用途:存储用户对回答的评分与评价
|
||||
"""
|
||||
|
||||
__tablename__ = 'feedbacks'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
chat_log_id: Mapped[int] = mapped_column(ForeignKey('chat_logs.id'), unique=True)
|
||||
score: Mapped[int] = mapped_column(Integer)
|
||||
comment: Mapped[Optional[str]] = mapped_column(Text)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
chat_log: Mapped['ChatLog'] = relationship(back_populates='feedback')
|
||||
|
||||
|
||||
class ChatToolRun(Base):
|
||||
"""
|
||||
对话轮次 Tool 运行绑定表(chat-turn binding)。
|
||||
|
||||
用途:持久化 hxops_turn_id / chat_log_id / schedule_run_id 绑定,支撑跨 worker 与异步时序的稳定进度显示。
|
||||
约束:turn_id 非空且唯一,仅适用于经 chat API 触发的检核轮次;非聊天入口勿复用本表。
|
||||
"""
|
||||
|
||||
__tablename__ = 'chat_tool_runs'
|
||||
__table_args__ = (
|
||||
Index('ix_chat_tool_runs_chat_log_id', 'chat_log_id'),
|
||||
Index('ix_chat_tool_runs_schedule_run_id', 'schedule_run_id'),
|
||||
Index('ix_chat_tool_runs_session_task_created', 'session_id', 'schedule_task_id', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
tool_name: Mapped[str] = mapped_column(String(64), default='run_file_check')
|
||||
agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), index=True, nullable=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
|
||||
session_id: Mapped[str] = mapped_column(String(100), index=True)
|
||||
turn_id: Mapped[str] = mapped_column(String(64), unique=True)
|
||||
chat_log_id: Mapped[Optional[int]] = mapped_column(ForeignKey('chat_logs.id'), nullable=True)
|
||||
schedule_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_tasks.id'), nullable=True)
|
||||
schedule_run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('schedule_runs.id'), nullable=True)
|
||||
user_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(20), default='pending')
|
||||
bind_source: Mapped[Optional[str]] = mapped_column(String(32), 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)
|
||||
|
||||
|
||||
class GeneralFeedback(Base):
|
||||
"""
|
||||
通用意见反馈表
|
||||
用于存储 Workspace/Chat 页面提交的通用意见反馈
|
||||
"""
|
||||
|
||||
__tablename__ = 'general_feedbacks'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True)
|
||||
chat_log_id: Mapped[Optional[int]] = mapped_column(ForeignKey('chat_logs.id'), nullable=True, index=True)
|
||||
username: Mapped[str] = mapped_column(String(50), nullable=False)
|
||||
feedback_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
feedback_module: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
content: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
source_page: Mapped[Optional[str]] = mapped_column(String(32))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
@@ -0,0 +1,109 @@
|
||||
"""
|
||||
backend/app/models/content.py
|
||||
|
||||
用途:多语言、常用问题、热点 FAQ 候选、公告等内容模型。
|
||||
依赖:models.base.Base。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, Float, ForeignKey, Index, JSON, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ZlLanguage(Base):
|
||||
"""
|
||||
多语言配置表
|
||||
用途:存储系统支持的语言列表
|
||||
"""
|
||||
|
||||
__tablename__ = 'zl_languages'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
code: Mapped[str] = mapped_column(String(10), unique=True)
|
||||
name: Mapped[str] = mapped_column(String(50))
|
||||
is_active: Mapped[bool] = mapped_column(default=True)
|
||||
|
||||
|
||||
class QuickQuestion(Base):
|
||||
"""
|
||||
常用问题表
|
||||
用途:存储全局/用户常用问题;全局条目(user_id 为空)可配置标准答案并启用 FAQ 缓存命中。
|
||||
"""
|
||||
|
||||
__tablename__ = 'quick_questions'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
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')
|
||||
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):
|
||||
"""
|
||||
公告表
|
||||
用途:存储系统公告
|
||||
"""
|
||||
|
||||
__tablename__ = 'announcements'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
title: Mapped[str] = mapped_column(String(200))
|
||||
content: Mapped[str] = mapped_column(Text)
|
||||
is_active: Mapped[bool] = mapped_column(default=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
@@ -0,0 +1,27 @@
|
||||
"""
|
||||
backend/app/models/department.py
|
||||
|
||||
用途:部门组织模型。
|
||||
依赖:models.base.Base。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class Department(Base):
|
||||
"""部门表:存储公司部门列表。"""
|
||||
|
||||
__tablename__ = 'departments'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(100), unique=True)
|
||||
code: Mapped[Optional[str]] = mapped_column(String(50), unique=True)
|
||||
company: Mapped[Optional[str]] = mapped_column(String(100))
|
||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||
@@ -0,0 +1,70 @@
|
||||
"""
|
||||
backend/app/models/file_asset.py
|
||||
|
||||
用途:平台级通用文件资产模型,承载私有 MinIO 存储元数据与生命周期。
|
||||
依赖:models.base.Base。
|
||||
逻辑:由 file_assets.service 创建与更新;ShippingNoticeIntake 经 asset_id 引用上传根资产;
|
||||
EML 解析后的订单附件以 parent_asset_id 挂为 derived 子资产(阶段二);
|
||||
派生资产对 (parent_asset_id, content_hash) 使用未删除行的部分唯一索引。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, UniqueConstraint, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class FileAsset(Base):
|
||||
"""通用文件资产(私有对象存储 + 审计元数据)。"""
|
||||
|
||||
__tablename__ = 'file_assets'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('asset_no', name='uq_file_assets_asset_no'),
|
||||
Index('ix_file_assets_owner_content_hash', 'owner_user_id', 'content_hash'),
|
||||
Index('ix_file_assets_lifecycle_expires', 'lifecycle_status', 'expires_at'),
|
||||
Index('ix_file_assets_owner_created', 'owner_user_id', 'created_at'),
|
||||
# 仅约束未删除派生资产,避免 soft-delete 永久阻塞同哈希重资产化
|
||||
Index(
|
||||
'uq_file_assets_parent_content_hash_alive',
|
||||
'parent_asset_id',
|
||||
'content_hash',
|
||||
unique=True,
|
||||
postgresql_where=text('deleted_at IS NULL AND parent_asset_id IS NOT NULL'),
|
||||
sqlite_where=text('deleted_at IS NULL AND parent_asset_id IS NOT NULL'),
|
||||
),
|
||||
Index('ix_file_assets_parent_attachment_key', 'parent_asset_id', 'source_attachment_key'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
asset_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True, nullable=False)
|
||||
tenant_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
# 派生资产:EML 根资产 → 附件 PDF 等子资产
|
||||
parent_asset_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('file_assets.id'),
|
||||
index=True,
|
||||
nullable=True,
|
||||
)
|
||||
asset_role: Mapped[str] = mapped_column(String(32), default='upload', nullable=False)
|
||||
# 派生资产首次落库时的 attachment_key;后续复用同哈希时不覆盖(当前来源见 Document.attachment_key)
|
||||
source_attachment_key: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
original_filename: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
storage_provider: Mapped[str] = mapped_column(String(32), default='minio', nullable=False)
|
||||
storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
storage_key: Mapped[str] = mapped_column(String(512), nullable=False)
|
||||
content_hash: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
file_size: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
mime_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
extension: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
upload_status: Mapped[str] = mapped_column(String(32), default='uploading', nullable=False)
|
||||
lifecycle_status: Mapped[str] = mapped_column(String(32), default='temporary', nullable=False)
|
||||
reference_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, 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)
|
||||
Loaded 100 of 759 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user